Skip to content

feat: ts compatible session store #584

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

Merged
merged 8 commits into from
May 7, 2025
Merged

feat: ts compatible session store #584

merged 8 commits into from
May 7, 2025

Conversation

amhsirak
Copy link
Member

@amhsirak amhsirak commented May 6, 2025

Summary by CodeRabbit

  • Refactor
    • Improved session store configuration for better maintainability and efficiency.
    • Session cleanup now occurs every 15 minutes instead of every hour.
    • Enhanced error logging for clearer error messages.
    • Session cookies are now set to secure automatically in production environments.
    • Sessions are no longer saved unless they are modified.
  • Chores
    • Added a new environment variable for session secret management with recommended usage.
  • Documentation
    • Updated README to include guidance on setting a custom session secret for improved security.

Copy link

coderabbitai bot commented May 6, 2025

Walkthrough

The session store setup in the server code was refactored by introducing a typed options interface and creating a reusable session store instance. Configuration changes include a shorter session pruning interval, dynamic cookie security based on environment, updated session middleware options, and sourcing the session secret from an environment variable with a fallback.

Changes

File(s) Change Summary
server/src/server.ts Refactored session store initialization: added PgStoreOptions interface, created reusable store, updated options, changed prune interval, improved error logging, sourced session secret from env, and made cookie security dynamic.
ENVEXAMPLE Added new environment variable SESSION_SECRET for session cookie signing with guidance to define a strong secret.
README.md Updated documentation to include SESSION_SECRET environment variable, describing its purpose and recommended usage.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Server
    participant PgSession (Session Store)
    Note over Server: On incoming request
    Server->>PgSession (Session Store): Access session using reusable store instance
    PgSession (Session Store)-->>Server: Retrieve/store session data
    Server-->>User: Respond with session-enabled result
Loading

Possibly related PRs

Suggested labels

Scope: Documentation, Type: ❗❗ .env Changes❗❗

Poem

🐇 A secret in the env, so neat,
Sessions now are safe and sweet.
Prune runs faster, errors clear,
Cookies secure when prod is near.
A hop for code, a leap for trust,
In every session, hop we must! 🥕✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

@amhsirak amhsirak added the Type: Infra All issues/PRs related to infrastructure label May 6, 2025
Copy link

@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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a1986a9 and 9433860.

📒 Files selected for processing (1)
  • server/src/server.ts (1 hunks)
🧰 Additional context used
🪛 ast-grep (0.31.1)
server/src/server.ts

[warning] 62-62: A hard-coded credential was detected. It is not recommended to store credentials in source-code, as this risks secrets being leaked and used by either an internal or external malicious adversary. It is recommended to use environment variables to securely provide credentials or retrieve credentials from a secure vault or HSM (Hardware Security Module).
Context: secret: 'mx-session'
Note: [CWE-798] Use of Hard-coded Credentials. [REFERENCES]
- https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html

(express-session-hardcoded-secret-typescript)

🔇 Additional comments (3)
server/src/server.ts (3)

42-48: Excellent type safety improvement with PgStoreOptions interface

The introduction of a properly typed interface for session store options improves type safety and provides better IDE support. This is a good practice for TypeScript projects.


50-58: Good session store extraction and configuration improvements

Creating a reusable session store instance improves code organization. The reduced pruneSessionInterval (from 1 hour to 15 minutes) will clean up inactive sessions more frequently, which is good for database hygiene. The properly typed error logging that only logs the error message (instead of the entire object) is also an improvement.


62-70: Security improvements in session configuration

The session configuration has been improved in several ways:

  1. Using the reusable sessionStore instance
  2. Setting saveUninitialized to false (prevents storing empty sessions)
  3. Making cookie secure flag dynamic based on environment

These changes enhance security, but be aware they might change behavior:

  • With saveUninitialized: false, uninitialized sessions won't be saved anymore
  • With dynamic secure flag, cookies will only be sent over HTTPS in production

Verify that your application doesn't rely on uninitialized sessions being saved, and that you're serving over HTTPS in production.

🧰 Tools
🪛 ast-grep (0.31.1)

[warning] 62-62: A hard-coded credential was detected. It is not recommended to store credentials in source-code, as this risks secrets being leaked and used by either an internal or external malicious adversary. It is recommended to use environment variables to securely provide credentials or retrieve credentials from a secure vault or HSM (Hardware Security Module).
Context: secret: 'mx-session'
Note: [CWE-798] Use of Hard-coded Credentials. [REFERENCES]
- https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html

(express-session-hardcoded-secret-typescript)

},
} as any),
}),
store: sessionStore,
secret: 'mx-session',
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security risk: Hardcoded session secret

Using a hardcoded session secret is a security vulnerability. If compromised, this could lead to session hijacking.

Replace the hardcoded secret with an environment variable:

- secret: 'mx-session',
+ secret: process.env.SESSION_SECRET || 'mx-session-dev',

And add SESSION_SECRET to your environment variables in production. Consider adding this to your README or documentation:

# Required environment variables:
SESSION_SECRET - A strong, random string used to sign session cookies
📝 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
secret: 'mx-session',
secret: process.env.SESSION_SECRET || 'mx-session-dev',

@amhsirak amhsirak added the Type: ❗❗ .env Changes❗❗ Changes in environment variables label May 6, 2025
Copy link

@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: 0

🧹 Nitpick comments (1)
README.md (1)

101-101: Clarify default secret value and improve phrasing

The "If Not Set" column could specify the actual fallback secret ('mx-session') and refine the wording. For example:

-| `SESSION_SECRET`      | No       | A strong, random string used to sign session cookies                                          | Uses default secret. Recommended to define your own session secret to avoid session hijacking.  |
+| `SESSION_SECRET`      | No       | A strong, random string used to sign session cookies                                          | Uses default secret ('mx-session'). It is recommended to define your own session secret to avoid session hijacking.  |

This makes the fallback explicit and smooths the phrasing.

🧰 Tools
🪛 LanguageTool

[grammar] ~101-~101: The verb ‘Recommended’ is used with the gerund form.
Context: ... | Uses default secret. Recommended to define your own session secret to avoid sessio...

(ADMIT_ENJOY_VB)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9433860 and fcbc067.

📒 Files selected for processing (3)
  • ENVEXAMPLE (1 hunks)
  • README.md (1 hunks)
  • server/src/server.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • ENVEXAMPLE
🚧 Files skipped from review as they are similar to previous changes (1)
  • server/src/server.ts
🧰 Additional context used
🪛 LanguageTool
README.md

[grammar] ~101-~101: The verb ‘Recommended’ is used with the gerund form.
Context: ... | Uses default secret. Recommended to define your own session secret to avoid sessio...

(ADMIT_ENJOY_VB)

@amhsirak amhsirak merged commit 8287da5 into develop May 7, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Type: ❗❗ .env Changes❗❗ Changes in environment variables Type: Infra All issues/PRs related to infrastructure
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant