Skip to content

Conversation

@Oksamies
Copy link
Contributor

@Oksamies Oksamies commented Dec 9, 2025

  • expose a clearInvalidSession helper from ts-api-react that handles storage, cookies, and stale flags with proper error reporting
  • update Dapper instantiations (root app, singleton, client loaders) to rely on the shared cleanup hook instead of duplicating logic

- expose a clearInvalidSession helper from ts-api-react that handles storage, cookies, and stale flags with proper error reporting
- update Dapper instantiations (root app, singleton, client loaders) to rely on the shared cleanup hook instead of duplicating logic
@coderabbitai
Copy link

coderabbitai bot commented Dec 9, 2025

Walkthrough

This PR adds a new clearInvalidSession public API method to the session context and updates DapperTs instantiation across the codebase to accept a second parameter: a cleanup callback. The callback invokes clearInvalidSession when session invalidation is needed. Additionally, currentUser error handling now branches on 401 errors to only clear sessions when an invalid token is specifically detected, using new helper functions to analyze error details. The session invalidation wiring is integrated into DapperTs initialization in root.tsx, client loaders, and the singleton.

Possibly related PRs

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: introducing a centralized invalid session cleanup mechanism and integrating it with Dapper instances.
Description check ✅ Passed The description directly addresses the changeset, explaining both the new helper and its integration points across multiple Dapper instantiations.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 12-09-add_centralized_invalid_session_cleanup_and_wire_dapper_to_it

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 41c60ce and 010dc62.

📒 Files selected for processing (6)
  • apps/cyberstorm-remix/app/root.tsx (2 hunks)
  • apps/cyberstorm-remix/cyberstorm/utils/dapperClientLoaders.ts (1 hunks)
  • apps/cyberstorm-remix/cyberstorm/utils/dapperSingleton.ts (1 hunks)
  • packages/dapper-ts/src/methods/currentUser.ts (2 hunks)
  • packages/ts-api-react/src/SessionContext.tsx (5 hunks)
  • packages/ts-api-react/src/index.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
packages/ts-api-react/src/SessionContext.tsx (1)
packages/ts-api-react/src/storage.ts (2)
  • _storage (37-43)
  • StorageManager (1-69)
apps/cyberstorm-remix/cyberstorm/utils/dapperSingleton.ts (2)
apps/cyberstorm-remix/cyberstorm/security/publicEnvVariables.ts (1)
  • getSessionTools (50-67)
packages/dapper-ts/src/index.ts (1)
  • DapperTs (41-102)
apps/cyberstorm-remix/cyberstorm/utils/dapperClientLoaders.ts (1)
packages/dapper-ts/src/index.ts (1)
  • DapperTs (41-102)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Build
  • GitHub Check: Agent
  • GitHub Check: Generate visual diffs
🔇 Additional comments (13)
packages/ts-api-react/src/index.ts (1)

6-6: LGTM!

The export is correctly placed and makes clearInvalidSession available as part of the public API.

packages/ts-api-react/src/SessionContext.tsx (5)

20-21: LGTM!

The interface addition is clear and the JSDoc comment accurately describes the function's purpose.


104-124: LGTM!

The implementation correctly handles:

  • Browser-only execution with early return
  • Complete session cleanup (storage + cookies + stale flag)
  • Cookie domain resolution with override support
  • Error handling that prevents failures from breaking the app

193-216: LGTM!

The integration correctly uses the new clearInvalidSession helper as the default cleanup behavior while maintaining the customClearSession override for testing flexibility.


271-276: LGTM!

The wrapper correctly forwards to the implementation with proper domain resolution, falling back to the context's cookie domain when no override is provided.


320-320: LGTM!

The function is correctly exposed in the returned context interface.

packages/dapper-ts/src/methods/currentUser.ts (2)

44-52: LGTM!

The updated logic correctly distinguishes between invalid-token 401s (which should clear session) and other 401s like permission denied (which should not). This prevents unnecessary session clearing on authorization failures.


9-32: Add test case for invalid token error scenario and document the expected error format.

The error detection logic is sound and properly integrated. The extractErrorDetail function correctly handles the documented error format (GenericApiError with optional detail field), and isInvalidTokenError safely checks for the "invalid token" string. However, there is no test case demonstrating the actual "invalid token" error response from the API. Add a test case to verify this scenario works as expected, and consider adding a brief comment to extractErrorDetail documenting the expected error response structure.

apps/cyberstorm-remix/cyberstorm/utils/dapperClientLoaders.ts (2)

48-48: LGTM!

Removing optional chaining is correct since getConfig is always present on the ContextInterface returned by getSessionTools().


49-55: LGTM!

The DapperTs instantiation correctly wires the cleanup callback to invoke clearInvalidSession(), aligning with the PR's objective to centralize invalid session cleanup.

apps/cyberstorm-remix/cyberstorm/utils/dapperSingleton.ts (1)

39-42: LGTM!

The singleton initialization correctly wires the cleanup callback, ensuring the global window.Dapper instance uses the centralized session cleanup mechanism.

apps/cyberstorm-remix/app/root.tsx (2)

49-49: LGTM!

The import correctly brings in getSessionTools for session management.


584-596: LGTM!

The DapperTs instantiation correctly wires the cleanup callback with the cookie domain from environment variables. The optional chaining on data handles cases where loader data might be unavailable.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor Author

Oksamies commented Dec 9, 2025

This stack of pull requests is managed by Graphite. Learn more about stacking.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This pull request centralizes invalid session cleanup logic by introducing a clearInvalidSession helper in the ts-api-react package and wiring it to all Dapper instantiations throughout the application. The centralization improves consistency and maintainability by eliminating duplicated cleanup logic.

Key Changes

  • Introduced clearInvalidSession helper that handles storage cleanup, cookie deletion, and stale flag setting with proper error reporting
  • Updated Dapper's getCurrentUser to conditionally clear sessions only for 401 errors with "invalid token" messages
  • Wired all Dapper instantiations (root app, singleton, client loaders) to use the centralized cleanup hook

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
packages/ts-api-react/src/index.ts Exports the new clearInvalidSession helper
packages/ts-api-react/src/SessionContext.tsx Implements clearInvalidSession and integrates it into the session context and updateCurrentUser
packages/dapper-ts/src/methods/currentUser.ts Adds conditional session cleanup for 401 errors with "invalid token" messages using string matching
apps/cyberstorm-remix/cyberstorm/utils/dapperSingleton.ts Wires singleton Dapper to use clearInvalidSession
apps/cyberstorm-remix/cyberstorm/utils/dapperClientLoaders.ts Wires client loader Dapper instances to use clearInvalidSession
apps/cyberstorm-remix/app/root.tsx Wires root app Dapper to use clearInvalidSession with cookie domain override

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +45 to +48
if (isInvalidTokenError(error)) {
// If the token is invalid, clear any persisted session data
this.removeSessionHook?.();
}
Copy link

Copilot AI Dec 9, 2025

Choose a reason for hiding this comment

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

The conditional session cleanup logic creates an inconsistency where only 401 errors with the exact text "invalid token" trigger session cleanup, while other 401 responses (e.g., expired tokens, revoked tokens, or authentication failures with different error messages) return null without clearing the session. This could leave stale session data in storage.

Consider either:

  1. Clearing the session for all 401 errors (restoring the previous behavior), or
  2. If the distinction is intentional, add a comment explaining why some 401s should preserve session data while others should clear it.
Suggested change
if (isInvalidTokenError(error)) {
// If the token is invalid, clear any persisted session data
this.removeSessionHook?.();
}
// Clear any persisted session data for all 401 errors
this.removeSessionHook?.();

Copilot uses AI. Check for mistakes.
function isInvalidTokenError(error: ApiError): boolean {
const detail = extractErrorDetail(error.responseJson);
return (
typeof detail === "string" && detail.toLowerCase().includes("invalid token")
Copy link

Copilot AI Dec 9, 2025

Choose a reason for hiding this comment

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

The string matching logic using .includes("invalid token") is fragile and could fail to match:

  1. Variations in casing (though .toLowerCase() helps)
  2. Variations in wording (e.g., "token is invalid", "invalid session token", "bad token")
  3. Localized error messages in different languages
  4. Changes to the API error message format

Consider using a more robust approach, such as:

  • Checking for specific error codes if the API provides them
  • Using a regex pattern to match variations
  • Documenting the expected API error message format and adding a test to ensure it matches
Suggested change
typeof detail === "string" && detail.toLowerCase().includes("invalid token")
typeof detail === "string" &&
/invalid\s+token|token\s+is\s+invalid|invalid\s+session\s+token|bad\s+token/i.test(detail)

Copilot uses AI. Check for mistakes.
return;
}
try {
clearSession(_storage, true);
Copy link

Copilot AI Dec 9, 2025

Choose a reason for hiding this comment

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

The new clearInvalidSession function calls clearSession(_storage, true), which clears the API host, while the previous implementation at line 205 called clearSession(_storage, false), which preserved the API host. This is a subtle behavior change that could affect session recovery flows.

Verify this is intentional. If the API host should be preserved during invalid session cleanup (to allow the user to re-authenticate with the same API), consider passing false instead.

Suggested change
clearSession(_storage, true);
clearSession(_storage, false);

Copilot uses AI. Check for mistakes.
clearSession: (clearApiHost?: boolean) => void;
/** Remove session cookies. */
clearCookies: (domain: string) => void;
/** Clear all persisted session data and flag as stale. */
Copy link

Copilot AI Dec 9, 2025

Choose a reason for hiding this comment

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

[nitpick] The JSDoc comment should be more descriptive about what "clear all persisted session data" means. Consider specifying:

  • Clears current user data
  • Clears API host
  • Clears session cookies
  • Sets session as stale

Example: /** Clear all persisted session data (current user, API host, cookies) and mark session as stale. */

Suggested change
/** Clear all persisted session data and flag as stale. */
/**
* Clear all persisted session data (current user, API host, cookies) and mark session as stale.
*/

Copilot uses AI. Check for mistakes.
}
if (
typeof payload === "object" &&
payload !== null &&
Copy link

Copilot AI Dec 9, 2025

Choose a reason for hiding this comment

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

Variable 'payload' is of type date, object or regular expression, but it is compared to an expression of type null.

Copilot uses AI. Check for mistakes.
@codecov
Copy link

codecov bot commented Dec 9, 2025

Codecov Report

❌ Patch coverage is 7.50000% with 74 lines in your changes missing coverage. Please review.
✅ Project coverage is 11.58%. Comparing base (41c60ce) to head (010dc62).

Files with missing lines Patch % Lines
packages/dapper-ts/src/methods/currentUser.ts 0.00% 26 Missing ⚠️
packages/ts-api-react/src/SessionContext.tsx 10.34% 26 Missing ⚠️
apps/cyberstorm-remix/app/root.tsx 0.00% 13 Missing ⚠️
...torm-remix/cyberstorm/utils/dapperClientLoaders.ts 0.00% 8 Missing ⚠️
...berstorm-remix/cyberstorm/utils/dapperSingleton.ts 75.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1660      +/-   ##
==========================================
+ Coverage   11.57%   11.58%   +0.01%     
==========================================
  Files         317      317              
  Lines       22867    22930      +63     
  Branches      505      508       +3     
==========================================
+ Hits         2647     2657      +10     
- Misses      20220    20273      +53     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Contributor

@Roffenlund Roffenlund left a comment

Choose a reason for hiding this comment

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

Looks good overall. I would suggest looking over the AI generated comments as some of them seem relevant to the implementation.

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.

3 participants