Skip to content

fix: Wave 3 auth session lifecycle and timezone reset safety - #11

Merged
TechHypeXP merged 1 commit into
mainfrom
fix/wave3-auth-resets-db
Jul 15, 2026
Merged

fix: Wave 3 auth session lifecycle and timezone reset safety#11
TechHypeXP merged 1 commit into
mainfrom
fix/wave3-auth-resets-db

Conversation

@TechHypeXP

@TechHypeXP TechHypeXP commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

Addressing Wave 3 auth lifecycle, cookie path scopes, and scheduler bugs:

  • Initialize user session context from request cookies inside logout/route.ts before calling signOut({ scope: 'global' }) to guarantee actual server-side refresh token invalidation in Supabase
  • Read refresh tokens directly from httpOnly cookies in refresh/route.ts, falling back to JSON body
  • Return new refresh_token in response JSON payload on refresh to prevent refresh chaining breaks
  • Explicitly add path: '/' to all session cookie set configurations
  • Align shouldResetMonthlyVolume timezone logic to UTC (Date.UTC) matching getStartOfCurrentMonth

Summary by cubic

Fixes auth session lifecycle and UTC-based monthly reset timing. Ensures global logout, cookie-based token refresh, consistent cookie paths, and cleanup on errors.

  • Bug Fixes
    • Logout: load session from cookies, then signOut({ scope: 'global' }); clear cookies with path: '/' on success/error; standardized error.
    • Refresh: read refresh token from httpOnly cookie (fallback to body); return refresh_token; set cookies with path: '/'; clear on error.
    • Login: set path: '/' on access/refresh cookies.
    • Scheduler: use UTC month start for resets; tests updated to UTC.

Written for commit 8cbc1f0. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

  • Bug Fixes
    • Improved login and session cookie handling across the site.
    • Logout now reliably ends sessions and clears authentication data.
    • Session refresh is more resilient and keeps authentication details up to date.
    • Standardized logout error messaging for a clearer experience.
    • Monthly commission volume resets now follow consistent UTC timing.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@netlify

netlify Bot commented Jul 15, 2026

Copy link
Copy Markdown

Deploy Preview for hex-diva ready!

Name Link
🔨 Latest commit 8cbc1f0
🔍 Latest deploy log https://app.netlify.com/projects/hex-diva/deploys/6a573cc55a879e000880ef24
😎 Deploy Preview https://deploy-preview-11--hex-diva.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Sorry @TechHypeXP, you have reached your weekly rate limit of 500000 diff characters.

Please try again later or upgrade to continue using Sourcery

@vercel

vercel Bot commented Jul 15, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
hex-diva Ready Ready Preview, Comment Jul 15, 2026 7:55am

@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown

Review Change Stack

Walkthrough

Authentication routes now scope session cookies to /, support cookie-based refresh and logout, and clear cookies explicitly. Monthly volume reset checks now calculate the current month boundary in UTC.

Changes

Authentication session cookie flow

Layer / File(s) Summary
Login cookie scope
src/app/api/auth/login/route.ts
Access and refresh cookies now specify the root path.
Refresh token fallback and response
src/app/api/auth/refresh/route.ts
Refresh prefers the cookie token, falls back to the request body, returns expanded session metadata, and updates session cookies.
Logout session cleanup
src/app/api/auth/logout/route.ts
Logout restores the Supabase session, performs global sign-out, returns a fixed failure message, and expires both session cookies.

UTC monthly reset calculation

Layer / File(s) Summary
UTC month boundary
src/lib/commissions/monthlyResetScheduler.ts
Monthly reset eligibility now uses the UTC start of the current month.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant RefreshRoute
  participant Cookies
  participant SupabaseAuth
  Client->>RefreshRoute: POST refresh request
  RefreshRoute->>Cookies: read sb-refresh-token
  RefreshRoute->>SupabaseAuth: refresh session
  SupabaseAuth-->>RefreshRoute: session and token metadata
  RefreshRoute->>Cookies: set access and refresh cookies
  RefreshRoute-->>Client: return refreshed session
Loading

Possibly related PRs

  • Hex-Tech-Lab/hex-diva#2: Adds related backend authentication routes and overlaps with the login, logout, and refresh cookie handling.
  • Hex-Tech-Lab/hex-diva#7: Introduces the same monthly reset scheduler and function affected by the UTC calculation change.

Suggested reviewers: claude

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main auth session and UTC reset changes in the pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/wave3-auth-resets-db
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch fix/wave3-auth-resets-db

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/app/api/auth/refresh/route.ts (1)

32-40: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Clear local session cookies when token refresh fails.

If the token refresh fails (e.g., because the refresh token is expired or revoked), the server currently returns a 401 error but leaves the invalid cookies intact. Proactively clearing the cookies here ensures the client state is sanitized, preventing subsequent requests from repeatedly attempting to authenticate with an invalid token.

♻️ Proposed refactor to clear cookies
     if (error || !data.session) {
       if (!error && !data.session) {
         Sentry.captureException(new Error('Token refresh: no error but no session'));
       }
-      return NextResponse.json(
+      const errorResponse = NextResponse.json(
         { error: 'Token refresh failed' },
         { status: 401 }
       );
+      errorResponse.cookies.set('sb-access-token', '', { path: '/', maxAge: 0 });
+      errorResponse.cookies.set('sb-refresh-token', '', { path: '/', maxAge: 0 });
+      return errorResponse;
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/app/api/auth/refresh/route.ts` around lines 32 - 40, Update the
token-refresh failure branch in the auth route to clear the local session
cookies before returning the 401 response. Preserve the existing Sentry capture
for the no-error/no-session case and the current error response, using the
route’s established cookie names and response mechanism.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/app/api/auth/logout/route.ts`:
- Around line 23-29: Update the logout route’s supabase.auth.signOut error path
so it clears the local session cookies before returning the existing 400
response. Reuse the same cookie-clearing logic as the successful logout path,
ensuring cookies are cleared regardless of whether signOut succeeds or fails.

In `@src/lib/commissions/monthlyResetScheduler.ts`:
- Around line 35-36: Update the monthly-reset logic in the webhook route and its
commission monthly-reset tests to use UTC consistently, matching
monthlyResetScheduler’s Date.UTC and getUTC* behavior. Replace local month/year
comparisons and date construction with UTC equivalents, preserving the existing
reset conditions and expected outcomes.

---

Outside diff comments:
In `@src/app/api/auth/refresh/route.ts`:
- Around line 32-40: Update the token-refresh failure branch in the auth route
to clear the local session cookies before returning the 401 response. Preserve
the existing Sentry capture for the no-error/no-session case and the current
error response, using the route’s established cookie names and response
mechanism.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 7fb325f1-1b17-4773-992e-df3fd48589ba

📥 Commits

Reviewing files that changed from the base of the PR and between 578f7ef and ef55ec6.

📒 Files selected for processing (5)
  • src/app/api/auth/login/route.ts
  • src/app/api/auth/logout/route.ts
  • src/app/api/auth/refresh/route.ts
  • src/lib/commissions/monthlyResetScheduler.ts
  • tsconfig.tsbuildinfo

Comment thread src/app/api/auth/logout/route.ts
Comment thread src/lib/commissions/monthlyResetScheduler.ts
@TechHypeXP
TechHypeXP force-pushed the fix/wave3-auth-resets-db branch from ef55ec6 to 14af44b Compare July 15, 2026 07:53
…ken refresh lifecycle, explicit cookie path configuration, and UTC monthly reset timezone alignment
@TechHypeXP
TechHypeXP force-pushed the fix/wave3-auth-resets-db branch from 14af44b to 8cbc1f0 Compare July 15, 2026 07:54
@TechHypeXP
TechHypeXP merged commit 90b4118 into main Jul 15, 2026
10 checks passed
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.

2 participants