-
Notifications
You must be signed in to change notification settings - Fork 7
Implement session management with express-session and MemoryStorage #136
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
base: main
Are you sure you want to change the base?
Implement session management with express-session and MemoryStorage #136
Conversation
""" WalkthroughA new Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant ExpressApp
participant ExpressStore
Client->>ExpressApp: Sends HTTP request
ExpressApp->>ExpressStore: Instantiates with req
ExpressStore->>ExpressApp: Accesses req.session
Client->>ExpressApp: Get/set/remove session item
ExpressApp->>ExpressStore: Calls getSessionItem/setSessionItem/removeSessionItem
ExpressStore->>ExpressApp: Reads/writes/deletes from req.session
Client->>ExpressApp: Destroy session
ExpressApp->>ExpressStore: Calls destroySession
ExpressStore->>ExpressApp: Calls req.session.destroy()
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~15 minutes Suggested reviewers
Note ⚡️ Unit Test Generation - BetaCodeRabbit's unit test generation is now available in Beta! Automatically generate comprehensive unit tests for your code changes, ensuring better test coverage and catching edge cases you might miss. Our AI analyzes your code structure and creates tests that follow best practices and your project's testing patterns. Learn more here, or just try it under ✨ Finishing Touches. 📜 Recent review detailsConfiguration used: CodeRabbit UI ⛔ Files ignored due to path filters (2)
📒 Files selected for processing (5)
🚧 Files skipped from review as they are similar to previous changes (4)
🧰 Additional context used🧠 Learnings (2)📓 Common learnings
lib/sessionManager/stores/expressStore.test.ts (11)Learnt from: DanielRivers Learnt from: DanielRivers Learnt from: DanielRivers Learnt from: DanielRivers Learnt from: DanielRivers Learnt from: DanielRivers Learnt from: DanielRivers Learnt from: DanielRivers Learnt from: DanielRivers Learnt from: DanielRivers Learnt from: DanielRivers 🔇 Additional comments (5)
✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🔭 Outside diff range comments (1)
lib/sessionManager/stores/expressSessionManager.test.ts (1)
1-126
: Critical mismatch: Test file tests wrong class.The filename
expressSessionManager.test.ts
suggests this file should test theExpressSessionManager
class, but the actual code imports and testsMemoryStorage
instead. This is a significant inconsistency that needs to be resolved.The test file should either:
- Be renamed to
memory.test.ts
if it's intended to test MemoryStorage- Be rewritten to test ExpressSessionManager functionality
#!/bin/bash # Check if there's already a test file for MemoryStorage fd -e test.ts -e spec.ts | xargs grep -l "MemoryStorage" # Check if ExpressSessionManager has any other test files fd -e test.ts -e spec.ts | xargs grep -l "ExpressSessionManager"Based on the PR objectives to implement session management with express-session, this file should test the ExpressSessionManager class with Express request mocks, not MemoryStorage.
🧹 Nitpick comments (4)
lib/sessionManager/stores/expressSessionManager.ts (4)
1-2
: Consider removing the @ts-expect-error suppression.The
@ts-expect-error
directive suppresses TypeScript errors, but this might mask legitimate type issues. Since express is listed as a peer dependency, consider using proper TypeScript configuration orimport type
syntax instead of suppressing the error.-// @ts-expect-error express is not in dev deps but in peer deps -import type { Request } from "express"; +import type { Request } from "express";
47-51
: Consistent null handling for missing keys.The use of
?? null
ensures consistent return values for missing keys, which aligns with the interface contract. However, wrapping a synchronous operation inPromise.resolve()
is unnecessary overhead.- async getSessionItem(itemKey: V | StorageKeys): Promise<unknown | null> { - // ?? null ensures we consistently return null for missing keys - const itemValue = this.req.session![itemKey as string] ?? null; - return Promise.resolve(itemValue); - } + async getSessionItem(itemKey: V | StorageKeys): Promise<unknown | null> { + // ?? null ensures we consistently return null for missing keys + return this.req.session![itemKey as string] ?? null; + }
59-65
: Unnecessary Promise wrapping in setSessionItem.Similar to getSessionItem, wrapping a synchronous operation in
Promise.resolve()
adds unnecessary overhead.- async setSessionItem( - itemKey: V | StorageKeys, - itemValue: unknown - ): Promise<void> { - this.req.session![itemKey as string] = itemValue; - return Promise.resolve(); - } + async setSessionItem( + itemKey: V | StorageKeys, + itemValue: unknown + ): Promise<void> { + this.req.session![itemKey as string] = itemValue; + }
72-75
: Unnecessary Promise wrapping in removeSessionItem.The same optimization applies here - no need to wrap synchronous operations.
- async removeSessionItem(itemKey: V | StorageKeys): Promise<void> { - delete this.req.session![itemKey as string]; - return Promise.resolve(); - } + async removeSessionItem(itemKey: V | StorageKeys): Promise<void> { + delete this.req.session![itemKey as string]; + }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
package.json
is excluded by!**/*.json
📒 Files selected for processing (3)
lib/main.ts
(1 hunks)lib/sessionManager/stores/expressSessionManager.test.ts
(1 hunks)lib/sessionManager/stores/expressSessionManager.ts
(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: GitGuardian Security Checks
🔇 Additional comments (2)
lib/sessionManager/stores/expressSessionManager.ts (2)
5-15
: Global namespace extension is implemented correctly.The global declaration properly extends the Express Request interface to include typed session properties. This follows TypeScript best practices for module augmentation.
32-40
: Constructor validation provides clear error messaging.The constructor correctly validates that the session middleware is configured before usage. The error message is descriptive and guides developers on proper setup.
Codecov ReportAttention: Patch coverage is
📢 Thoughts on this report? Let us know! |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (1)
lib/sessionManager/stores/expressStore.ts (1)
77-78
: Consider adding a comment explaining the removal logicThe removal of existing items before setting is important to prevent orphaned split keys. Consider adding a comment to clarify this design decision.
- // Remove any existing split items first + // Remove any existing split items first to prevent orphaned keys + // when the new value has fewer chunks than the previous value await this.removeSessionItem(itemKey);
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
lib/main.test.ts
(1 hunks)lib/main.ts
(1 hunks)lib/sessionManager/index.ts
(1 hunks)lib/sessionManager/stores/expressStore.test.ts
(1 hunks)lib/sessionManager/stores/expressStore.ts
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- lib/main.test.ts
- lib/sessionManager/index.ts
- lib/main.ts
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: DanielRivers
PR: kinde-oss/js-utils#61
File: lib/sessionManager/types.ts:20-20
Timestamp: 2025-01-16T21:47:40.307Z
Learning: Security documentation for configuration options in this codebase should be placed in the implementation file (e.g., index.ts) rather than the types file, as demonstrated with `useInsecureForRefreshToken` in `lib/sessionManager/index.ts`.
Learnt from: DanielRivers
PR: kinde-oss/js-utils#130
File: lib/types.ts:62-66
Timestamp: 2025-06-02T08:18:51.057Z
Learning: In the kinde-oss/js-utils project, DanielRivers is comfortable with breaking changes to manual typing systems during refactoring, preferring clean migration to new naming conventions over backward compatibility aliases for types.
Learnt from: DanielRivers
PR: kinde-oss/js-utils#69
File: lib/utils/token/refreshToken.ts:54-57
Timestamp: 2025-01-20T20:01:21.460Z
Learning: In the Kinde JS utils library, when not using a custom domain, local storage is used by default for storing refresh tokens. This is an intentional design decision that will be documented. Users can explicitly opt out of this behavior if needed.
Learnt from: DanielRivers
PR: kinde-oss/js-utils#16
File: lib/sessionManager/types.ts:75-80
Timestamp: 2024-10-25T14:24:05.260Z
Learning: All storage classes (`MemoryStorage`, `LocalStorage`, `ChromeStore`, `ExpoSecureStore`) extend `SessionBase`, inheriting the `setItems` method, so they do not need to implement `setItems` explicitly.
Learnt from: DanielRivers
PR: kinde-oss/js-utils#12
File: lib/main.ts:0-0
Timestamp: 2024-09-23T22:08:18.788Z
Learning: When exporting modules in `lib/main.ts`, ensure that paths to modules like `./utils/token` are explicitly set to include `index.ts` (e.g., `./utils/token/index.ts`) to prevent missing export issues.
Learnt from: DanielRivers
PR: kinde-oss/js-utils#12
File: lib/main.ts:0-0
Timestamp: 2024-10-08T23:57:58.113Z
Learning: When exporting modules in `lib/main.ts`, ensure that paths to modules like `./utils/token` are explicitly set to include `index.ts` (e.g., `./utils/token/index.ts`) to prevent missing export issues.
lib/sessionManager/stores/expressStore.test.ts (9)
Learnt from: DanielRivers
PR: kinde-oss/js-utils#11
File: lib/utils/token/index.test.ts:59-62
Timestamp: 2024-11-19T20:31:59.197Z
Learning: In `lib/utils/token/index.test.ts`, the test "getInsecureStorage returns active storage when no insecure storage is set" is intentional. It verifies that when insecure storage is not set, `getInsecureStorage()` returns the active storage as a fallback, preferring secure storage but allowing for insecure storage when needed by consumers of the library.
Learnt from: DanielRivers
PR: kinde-oss/js-utils#8
File: lib/utils/token/testUtils/index.ts:3-39
Timestamp: 2024-09-19T22:17:02.939Z
Learning: The file `lib/utils/token/testUtils/index.ts` is a test utility, not production code.
Learnt from: DanielRivers
PR: kinde-oss/js-utils#8
File: lib/utils/token/testUtils/index.ts:3-39
Timestamp: 2024-10-08T23:57:58.113Z
Learning: The file `lib/utils/token/testUtils/index.ts` is a test utility, not production code.
Learnt from: DanielRivers
PR: kinde-oss/js-utils#61
File: lib/sessionManager/types.ts:20-20
Timestamp: 2025-01-16T21:47:40.307Z
Learning: Security documentation for configuration options in this codebase should be placed in the implementation file (e.g., index.ts) rather than the types file, as demonstrated with `useInsecureForRefreshToken` in `lib/sessionManager/index.ts`.
Learnt from: DanielRivers
PR: kinde-oss/js-utils#12
File: lib/main.ts:0-0
Timestamp: 2024-09-23T22:08:18.788Z
Learning: When exporting modules in `lib/main.ts`, ensure that paths to modules like `./utils/token` are explicitly set to include `index.ts` (e.g., `./utils/token/index.ts`) to prevent missing export issues.
Learnt from: DanielRivers
PR: kinde-oss/js-utils#12
File: lib/main.ts:0-0
Timestamp: 2024-10-08T23:57:58.113Z
Learning: When exporting modules in `lib/main.ts`, ensure that paths to modules like `./utils/token` are explicitly set to include `index.ts` (e.g., `./utils/token/index.ts`) to prevent missing export issues.
Learnt from: DanielRivers
PR: kinde-oss/js-utils#15
File: lib/utils/generateAuthUrl.test.ts:104-104
Timestamp: 2024-10-25T23:53:26.124Z
Learning: In `lib/utils/generateAuthUrl.test.ts`, the code is test code and may not require strict adherence to PKCE specifications.
Learnt from: DanielRivers
PR: kinde-oss/js-utils#16
File: lib/sessionManager/types.ts:34-42
Timestamp: 2024-10-25T15:15:13.928Z
Learning: In `lib/sessionManager/types.ts`, the `setItems` method is unlikely to be used with large batches of items, so chunking is not necessary.
Learnt from: DanielRivers
PR: kinde-oss/js-utils#15
File: lib/utils/generateAuthUrl.ts:27-30
Timestamp: 2024-10-25T23:50:56.599Z
Learning: In `lib/utils/generateAuthUrl.ts`, `StorageKeys` is imported from `../main` and includes the `state` key.
lib/sessionManager/stores/expressStore.ts (5)
Learnt from: DanielRivers
PR: kinde-oss/js-utils#16
File: lib/sessionManager/types.ts:75-80
Timestamp: 2024-10-25T14:24:05.260Z
Learning: All storage classes (`MemoryStorage`, `LocalStorage`, `ChromeStore`, `ExpoSecureStore`) extend `SessionBase`, inheriting the `setItems` method, so they do not need to implement `setItems` explicitly.
Learnt from: DanielRivers
PR: kinde-oss/js-utils#16
File: lib/sessionManager/types.ts:34-42
Timestamp: 2024-10-25T15:15:13.928Z
Learning: In `lib/sessionManager/types.ts`, the `setItems` method is unlikely to be used with large batches of items, so chunking is not necessary.
Learnt from: DanielRivers
PR: kinde-oss/js-utils#61
File: lib/sessionManager/types.ts:20-20
Timestamp: 2025-01-16T21:47:40.307Z
Learning: Security documentation for configuration options in this codebase should be placed in the implementation file (e.g., index.ts) rather than the types file, as demonstrated with `useInsecureForRefreshToken` in `lib/sessionManager/index.ts`.
Learnt from: DanielRivers
PR: kinde-oss/js-utils#11
File: lib/utils/exchangeAuthCode.ts:51-51
Timestamp: 2024-11-10T23:29:36.293Z
Learning: In `lib/utils/exchangeAuthCode.ts`, the `exchangeAuthCode` function intentionally uses `getInsecureStorage()` to store temporary authentication flow values locally between sessions. This is necessary for storing data needed for the return trip. The `getInsecureStorage()` function returns the secure storage if no active insecure storage is defined.
Learnt from: DanielRivers
PR: kinde-oss/js-utils#15
File: lib/utils/generateAuthUrl.ts:27-30
Timestamp: 2024-10-25T23:50:56.599Z
Learning: In `lib/utils/generateAuthUrl.ts`, `StorageKeys` is imported from `../main` and includes the `state` key.
🧬 Code Graph Analysis (2)
lib/sessionManager/stores/expressStore.test.ts (2)
lib/sessionManager/index.ts (3)
ExpressStore
(28-28)storageSettings
(3-21)StorageKeys
(31-31)lib/sessionManager/stores/expressStore.ts (1)
ExpressStore
(26-120)
lib/sessionManager/stores/expressStore.ts (2)
lib/main.ts (5)
ExpressStore
(77-77)StorageKeys
(59-59)SessionManager
(76-76)storageSettings
(55-55)splitString
(18-18)lib/sessionManager/index.ts (4)
ExpressStore
(28-28)StorageKeys
(31-31)SessionManager
(32-32)storageSettings
(3-21)
🔇 Additional comments (1)
lib/sessionManager/stores/expressStore.ts (1)
8-18
: No express-session type conflicts detectedSearched your
package.json
and codebase—there’s no@types/express-session
dependency and no othernamespace Express
augmentations. The global declaration inlib/sessionManager/stores/expressStore.ts
is safe as is. If you add express-session types in the future, consider moving this into a module augmentation (e.g. in a.d.ts
file withdeclare module 'express-session'
or extendingExpress.Session
) to avoid merging conflicts.
ca96815
to
9158ab7
Compare
- Implemented ExpressStore for session management in Express environments. - Added logic to split large session values to avoid cookie size limits, and reassemble them on retrieval. - Included comprehensive unit tests for the new store, including tests for the splitting logic. - Moved @types/express to devDependencies and created a separate 'express' entry point to prevent type conflicts in non-Express projects.
9050e70
to
e93980f
Compare
Introduce session management capabilities using the
express-session
package and a customMemoryStorage
implementation. Enhance TypeScript support and refactor session handling to improve type definitions and interface management.