Repository navigation
fix(auth): keep a failing auth hook from failing login, signup and email verification - #436
Conversation
…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
left a comment
There was a problem hiding this comment.
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
handleVerifyEmailMutationtoo. They are still called directly onmain, so it's the same bug in a newer path. - The new verification test mocks
createSession, whichhandleVerifyEmailno 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):authenticateUserhas already started the session and redirected when the hook runs. If the hook throws,onLoginErrorandlogin.onErrorfire for a login that succeeded. Then the provider'scatchingoogle.ts/github.tscallssendOAuthError(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 meansreportSignupErrorfires and the user sees an error. reportSignupError(~L474): callsonSignupErrorandsignup.onErrordirectly, 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
(...) => voidtovoid | Promise<void>would document that. - The
| undefinedonfireAuthHook'sinvokeparameter is no longer needed, because every caller passes a closure. - The signup test only covers a synchronous throw. A rejecting
signup.onSuccesscase, like the one in the login test, would cover the async branch.
|
Two more things after checking this against 1. Please correct the crash claim in the description. 2. The new tests leak throwing mocks into later tests. |
…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.
|
@omegascorp thanks for the thorough review. All addressed in 5d07b3e:
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 The 9 new tests fail against main's source. lint, prettier, |
omegascorp
left a comment
There was a problem hiding this comment.
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 throughfireAuthHook. That's 39 call sites inlogin,loginWithOAuth,signup,verification(both handlers),magicLinkandoauthCommon(both login paths, new-user signup,reportSignupErrorand all six link-hook calls). None are left that call a hook directly, andsafelyCallHookis 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.
onBeforeSignupis still awaited and not wrapped. - Merge: The merge from
mainkept main'sverification.ts, including thealreadyVerifiedshort-circuit. The branch merges cleanly into the currentmain. - Tests: I swapped in
main's versions of the changed source files, with a pass-throughfireAuthHook. 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/authpasses (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', () => |
There was a problem hiding this comment.
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>; |
There was a problem hiding this comment.
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.
|
@omegascorp thanks, both nits done in b25c128:
The 12 hook tests fail against main's source. lint, prettier, |
omegascorp
left a comment
There was a problem hiding this comment.
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
fireAuthHookinauth/utils.ts, as onmain: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@/telemetryimport, becausesendOAuthErroruses it, and still removesafelyCallHook. - In
verification.ts, keep thefireAuthHookwrap and drop theconsole.error('Error verifying email:')line, becausemainnow logs after theif. - Update the new tests to match.
verification.test.tsandoauthCommon.test.tsalready mock@/telemetryonmain, so assert onmockLogErrorwith{ error: expect.any(Error) }, and ideally checkmockCaptureErrortoo. Forlogin.test.tsandsignup.test.ts, mock@/telemetrythe 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.
|
@omegascorp thanks for working out the resolution. Merged
The full suite passes (1650 tests), along with |
omegascorp
left a comment
There was a problem hiding this comment.
Thank you @Mohil-Ahuja looks good
Problem
magicLink.tsruns its auth hooks throughfireAuthHook, so a hook that throws or rejects is logged and never changes the auth result. The other paths call the hooks directly inside theirtryblocks:login.tsandloginWithOAuth.ts:onAfterLogin,onLoginError,login.onSuccess,login.onErrorsignup.ts:onAfterSignup,onSignupError,signup.onSuccess,signup.onErrorverification.ts(handleVerifyEmailandhandleVerifyEmailMutation):onAfterEmailVerification,onEmailVerificationErrorproviders/oauthCommon.ts(the Google and GitHub callbacks):onAfterLoginandlogin.onSuccessfor existing-user and auto-link logins,onAfterSignupandsignup.onSuccessfor new users,onLoginError/login.onError, andonSignupError/signup.onErrorinreportSignupErrorA hook that throws turns a completed operation into an error:
handleLoginWithPasswordthe new session is already started and its cookie set whenonAfterLoginruns, yet the client gets a 500 with the hook's message andonLoginErrorfires. The browser is signed in while the client sees a failed login.handleSignupWithPasswordthe account is already inserted and the verification email sent, so the client is told signup failed and a retry hits "already exists".handleVerifyEmailthe address is verified but the user is redirected withstatus=error.catchthen callssendOAuthErrorafter the response was already sent.onSignupError,onEmailVerificationError, ...) replaces the real error.An async hook that rejects is not awaited or caught.
startServer'sunhandledRejectionhandler keeps the process running, but the log is a genericUnhandled Promise Rejectionthat doesn't name the hook.safelyCallHookinoauthCommon.tsonly caught synchronous throws, so the asynconAfterOAuthLinkandonOAuthLinkErrorhad the same gap.Change
fireAuthHookmoves frommagicLink.tstoauth/utils.ts, and every hook call above goes through it, including the deprecatedlogin/signupcallbacks.safelyCallHookis removed and its call sites usefireAuthHooktoo. Hook failures, sync or async, are logged asError in <hook> hook:. The hooks still run at the same points with the same arguments.onBeforeSignupis still awaited and not wrapped, since it's a veto.The notify-only hook types are widened from
(...) => voidto(...) => void | Promise<void>, which documents that async hooks are supported.fireAuthHook'sinvokeparameter is no longer optional. TheAuthConfigJSDoc states the contract: notify-only hooks aren't awaited, their failures are logged without changing the response, andonBeforeSignupis the exception.In
loginWithOAuth.ts, the error path copiesproviderto a const so its narrowing holds inside the callback.Tests
login.test.ts: a throwingonAfterLoginand a rejectinglogin.onSuccessleave the login successful, without firing the error hookssignup.test.ts: a throwingonAfterSignupand a rejectingsignup.onSuccessstill return the new user id, without firing the error hooksverification.test.ts: a rejectingonAfterEmailVerificationstill redirects withstatus=verified; inhandleVerifyEmailMutation, a rejectingonAfterEmailVerificationstill resolves, and a throwingonEmailVerificationErrordoesn't replace the real erroroauthCommon.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 rejectingonAfterOAuthLinkis logged and the link still completesThe throwing and rejecting mocks use
mockImplementationOnce/mockRejectedValueOnce, so they don't leak into later tests. All 12 new tests fail againstmain's source. The test files that mock./utilsor../utilsnow pass the realfireAuthHookthrough.tsc --noEmit, eslint, prettier,npm run buildandnpm 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
fireAuthHookhelper is centralized inauth/utils.ts(replacing the magic-link–local copy and OAuth’ssafelyCallHook) 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.onBeforeSignupstays 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.