Skip to content

🎨 Fixed infinite wait when auth code email fails to send in Direct mode #23610

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

PaulBernhardt
Copy link

fixes #23050

When email is configured to use Direct mode, it can take over 15 minutes for the email to actually fail to send. When a user attempts to sign in on a new device in this situation, the login screen will appear to be stuck with no feedback.

This is especially problematic because the Docker installation sets up Direct mode for you automatically, and most hosts / ISPs block outbound port 25. This likely means almost any self hoster that has not taken the step of explicitly setting up email will unknowingly be unable to log in to from a new device, and will have difficulty even discovering why.

This change adds a timeout in Direct mode to the sendAuthCodeToUser function. If the email has not been sent after 15 seconds, an error is thrown, which will then surface the 'Failed to send email. Please check your site configuration and try again.', which will will then lead them to either setting up email correctly or disabling the email 2FA.

Please check your PR against these items:

  • I've read and followed the Contributor Guide
  • I've explained my change
  • I've written an automated test to prove my change works

We appreciate your contribution! 🙏

fixes TryGhost#23050

When email is configured to use Direct mode, it can take over 15 minutes
for the email to actually fail to send. When a user attempts to sign in
on a new device in this situation, the login screen will appear to be
stuck with no feedback.

This change adds a timeout in Direct mode to the sendAuthCodeToUser
function. If the email has not been sent after 15 seconds, an error is
thrown, which will then surface the 'Failed to send email. Please check
your site configuration and try again.', which will will then lead them
to either setting up email correctly or disabling the email 2FA.
Copy link
Contributor

coderabbitai bot commented Jun 1, 2025

Walkthrough

The changes update the sendAuthCodeToUser function in the session service to introduce a 15-second timeout when sending emails in "Direct" mailer mode. If the mailer's send promise does not resolve within 15 seconds in this mode, the function rejects with a timeout error. The error handling logic is otherwise unchanged. Additionally, two new unit tests are added to verify the timeout behavior: one ensures a timeout error is thrown in direct mode if sending takes too long, and another confirms no timeout occurs in non-direct mode. An afterEach hook is also added to restore Sinon stubs and mocks after each test.

Assessment against linked issues

Objective Addressed Explanation
Provide helpful errors or improved handling when login fails due to email setup issues (#23050)
Ensure session authentication and login flows handle mailer timeouts or failures gracefully (#23050)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes were found.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
ghost/core/test/unit/server/services/auth/session/session-service.test.js (1)

484-489: Fix code formatting in promise callbacks.

The promise callbacks have formatting issues that violate ESLint rules.

Apply this diff to fix the formatting:

-        const mailer = {
-            send: sinon.stub().returns(new Promise((resolve) => { setTimeout(() => resolve(), 20000) })),
-            state: {
-                usingDirect: true
-            }
-        };
+        const mailer = {
+            send: sinon.stub().returns(new Promise((resolve) => {
+                setTimeout(() => resolve(), 20000);
+            })),
+            state: {
+                usingDirect: true
+            }
+        };

And similarly for line 552:

-        const mailer = {
-            send: sinon.stub().returns(new Promise((resolve) => { setTimeout(() => resolve(), 20000) })),
-            state: {
-                usingDirect: false
-            }
-        };
+        const mailer = {
+            send: sinon.stub().returns(new Promise((resolve) => {
+                setTimeout(() => resolve(), 20000);
+            })),
+            state: {
+                usingDirect: false
+            }
+        };

Also applies to: 551-556

🧰 Tools
🪛 ESLint

[error] 485-485: Statement inside of curly braces should be on next line.

(brace-style)


[error] 485-485: Missing semicolon.

(semi)


[error] 485-485: Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.

(brace-style)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4ebc884 and 58e61ae.

📒 Files selected for processing (2)
  • ghost/core/core/server/services/auth/session/session-service.js (1 hunks)
  • ghost/core/test/unit/server/services/auth/session/session-service.test.js (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
ghost/core/core/server/services/auth/session/session-service.js (3)
ghost/core/test/unit/server/services/auth/session/session-service.test.js (5)
  • mailer (381-383)
  • mailer (431-433)
  • mailer (484-489)
  • mailer (551-556)
  • mailer (653-655)
ghost/core/core/server/services/auth/session/index.js (1)
  • mailer (39-39)
ghost/core/test/e2e-api/admin/session.test.js (2)
  • token (155-155)
  • email (151-153)
ghost/core/test/unit/server/services/auth/session/session-service.test.js (2)
ghost/core/test/e2e-api/admin/sso.test.js (1)
  • sinon (4-4)
ghost/core/core/server/services/auth/session/index.js (3)
  • mailer (39-39)
  • urlUtils (12-12)
  • sessionService (41-61)
🪛 ESLint
ghost/core/core/server/services/auth/session/session-service.js

[error] 282-283: Missing semicolon.

(semi)


[error] 286-286: Return values from promise executor functions cannot be read.

(no-promise-executor-return)

ghost/core/test/unit/server/services/auth/session/session-service.test.js

[error] 485-485: Statement inside of curly braces should be on next line.

(brace-style)


[error] 485-485: Missing semicolon.

(semi)


[error] 485-485: Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.

(brace-style)


[error] 552-552: Statement inside of curly braces should be on next line.

(brace-style)


[error] 552-552: Missing semicolon.

(semi)


[error] 552-552: Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.

(brace-style)

🔇 Additional comments (3)
ghost/core/test/unit/server/services/auth/session/session-service.test.js (3)

16-18: Good addition for test isolation!

Adding sinon.restore() in the afterEach hook ensures proper cleanup between tests.


461-527: Well-implemented test for Direct mode timeout!

The test correctly verifies that the 15-second timeout is enforced when using Direct mode. Good use of fake timers and proper promise handling with setImmediate.

🧰 Tools
🪛 ESLint

[error] 485-485: Statement inside of curly braces should be on next line.

(brace-style)


[error] 485-485: Missing semicolon.

(semi)


[error] 485-485: Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.

(brace-style)


529-592: Good test coverage for non-Direct mode!

The test correctly verifies that the timeout is not applied when not using Direct mode, ensuring the email can take longer than 15 seconds to send.

🧰 Tools
🪛 ESLint

[error] 552-552: Statement inside of curly braces should be on next line.

(brace-style)


[error] 552-552: Missing semicolon.

(semi)


[error] 552-552: Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.

(brace-style)

Comment on lines +278 to +288
let sendPromise = mailer.send({
to: recipient,
subject: `${token} is your Ghost sign in verification code`,
html: email
});
})
// In Direct mode, it can take 15+ minutes for the mailer to actually fail to send.
// Compromise by giving up after 15 seconds.
if (mailer.state?.usingDirect) {
sendPromise = Promise.race([sendPromise, new Promise((_resolve, reject) => setTimeout(reject, 15000))]);
}
await sendPromise;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the promise executor return value issue.

The implementation correctly adds a 15-second timeout for Direct mode. However, the promise executor should not return the setTimeout value.

Apply this diff to fix the ESLint warning:

-            if (mailer.state?.usingDirect) {
-                sendPromise = Promise.race([sendPromise, new Promise((_resolve, reject) => setTimeout(reject, 15000))]);
-            }
+            if (mailer.state?.usingDirect) {
+                sendPromise = Promise.race([sendPromise, new Promise((_resolve, reject) => {
+                    setTimeout(reject, 15000);
+                })]);
+            }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let sendPromise = mailer.send({
to: recipient,
subject: `${token} is your Ghost sign in verification code`,
html: email
});
})
// In Direct mode, it can take 15+ minutes for the mailer to actually fail to send.
// Compromise by giving up after 15 seconds.
if (mailer.state?.usingDirect) {
sendPromise = Promise.race([sendPromise, new Promise((_resolve, reject) => setTimeout(reject, 15000))]);
}
await sendPromise;
let sendPromise = mailer.send({
to: recipient,
subject: `${token} is your Ghost sign in verification code`,
html: email
})
// In Direct mode, it can take 15+ minutes for the mailer to actually fail to send.
// Compromise by giving up after 15 seconds.
if (mailer.state?.usingDirect) {
sendPromise = Promise.race([sendPromise, new Promise((_resolve, reject) => {
setTimeout(reject, 15000);
})]);
}
await sendPromise;
🧰 Tools
🪛 ESLint

[error] 282-283: Missing semicolon.

(semi)


[error] 286-286: Return values from promise executor functions cannot be read.

(no-promise-executor-return)

🤖 Prompt for AI Agents
In ghost/core/core/server/services/auth/session/session-service.js around lines
278 to 288, the promise executor function passed to the new Promise incorrectly
returns the setTimeout ID, causing an ESLint warning. To fix this, modify the
executor function so it does not return the setTimeout call; instead, just call
setTimeout inside the executor without returning its value.

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.

No helpful errors when attempting to login without email setup
2 participants