Skip to content

feat: add connected-accounts disconnect and listing with orphan cook… - #2784

Open
Piyush-85 wants to merge 5 commits into
mainfrom
fix/connected-accounts-disconnect
Open

feat: add connected-accounts disconnect and listing with orphan cook…#2784
Piyush-85 wants to merge 5 commits into
mainfrom
fix/connected-accounts-disconnect

Conversation

@Piyush-85

@Piyush-85 Piyush-85 commented Jul 29, 2026

Copy link
Copy Markdown
Contributor
  • All new/changed/fixed functionality is covered by tests (or N/A)
  • I have added documentation for all new/changed functionality (or N/A)

📋 Changes

Adds disconnect connected accounts and list connected accounts capability, and fixes a connection-token cookie leak that could grow the request header size until it hit an HTTP 431.

New public methods on Auth0Client:

  • disconnectAccount({ connection }) — unlinks all connected accounts for a connection via the My Account API, then prunes the matching cached connection tokens from the session. It is connection-scoped, not per-account.

    await auth0.disconnectAccount({ connection: "google-oauth2" });
  • getConnectedAccounts() — returns ConnectedAccount[]

    const accounts = await auth0.getConnectedAccounts();

Login-hint support for multiple accounts on one connection:

  • ConnectionTokenSet gains an optional login hint. When getAccessTokenForConnection({ connection, login_hint }) is called, the login hint is forwarded to the federated-connection token exchange and stamped onto the resulting cached token. Subsequent calls match cached tokens on both connection and login hint, falling back to connection-only when no hint is supplied (preserving existing single-account behavior).

  • This lets an app hold and refresh access tokens for several accounts on the same connection without one account's refresh overwriting a sibling's cached token. The hint is a token-fetch-time discriminator supplied on getAccessTokenForConnection; connectAccount itself does not take or persist a login hint, so the app is responsible for passing the same login_hint it uses to obtain each account's token.

    const { token } = await auth0.getAccessTokenForConnection({
        connection: "google-oauth2",
        login_hint: "alice@example.com"
     });

The 431 fix (stateless session store):

  • Connection tokens are stored one per account in positionally indexed cookies. When the account list shrank (e.g. after a disconnect), the trailing higher-index cookies were left behind, re-read into the session, and piled up over time until the request headers exceeded the 431 limit.
  • The store now deletes any indexed connection-token cookie past the current array length. It only touches cookies matching the exact indexed shape and leaves any other similarly prefixed cookie alone. The fix lives in the session store, so App Router, Pages Router, and middleware all benefit.
  • Failed connection-token exchange now clears the stale __FC cookie: when the refresh-token→connection-token exchange fails (FAILED_TO_EXCHANGE), the dead cached token for that account is pruned from the session (account-scoped by connection + login_hint) and the orphaned __FC cookie is deleted, instead of being left behind to bloat request headers

📎 References

Addresses GH-2450 (HTTP 431 caused by connection-token cookie accumulation).

🎯 Testing

Run the unit suite. Added coverage includes:

  • Orphan cookie cleanup in the session store: shrink, grow, empty, and non-indexed-cookie-preserved cases.
  • disconnectAccount and getConnectedAccounts facades across App Router and Pages Router paths, plus the connectAccount overloads.
  • Login-hint multi-account matching.
  • listConnectedAccounts pagination, field mapping (including orgId), and error paths.
  • End-to-end regression against the real stateless session store, asserting Set-Cookie deletions are emitted for orphaned indexed cookies.

Summary by CodeRabbit

  • New Features
    • Added connected-account listing and disconnection APIs with pagination support.
    • Added login_hint support for selecting and caching account tokens.
    • Introduced typed disconnect errors and public connected-account types.
  • Bug Fixes
    • Improved session and cookie reconciliation, including orphaned token-cookie cleanup.
    • Preserved rotated refresh tokens and removed stale cached entries.
  • Documentation
    • Expanded Connected Accounts examples and persistence guidance.
  • Tests
    • Added coverage for account management, token handling, and cookie cleanup.

@Piyush-85
Piyush-85 requested a review from a team as a code owner July 29, 2026 14:12
@codecov-commenter

codecov-commenter commented Jul 29, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.83691% with 66 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.58%. Comparing base (6eb5e2d) to head (e290461).

Files with missing lines Patch % Lines
src/server/client.ts 75.00% 56 Missing ⚠️
src/server/auth-client.ts 95.38% 9 Missing ⚠️
src/server/session/stateless-session-store.ts 96.55% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2784      +/-   ##
==========================================
+ Coverage   87.98%   88.58%   +0.59%     
==========================================
  Files          80       80              
  Lines       11514    11962     +448     
  Branches     2386     2486     +100     
==========================================
+ Hits        10131    10596     +465     
+ Misses       1338     1321      -17     
  Partials       45       45              

☔ View full report in Codecov by Harness.
📢 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.

@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Connected-account types and errors were added. AuthClient now lists and disconnects accounts through the My Account API. Auth0Client reconciles cached connection tokens, preserves login hints, and removes orphaned connection-token cookies.

Changes

Connected Accounts

Layer / File(s) Summary
Connected-account contracts
src/types/connected-accounts.ts, src/types/token-vault.ts, src/types/index.ts, src/errors/*
Adds connected-account and disconnect option types, login-hint token metadata, and typed disconnect errors with public re-exports.
My Account connected-account API
src/server/auth-client.ts, src/server/auth-client.test.ts
Adds paginated listing, matching-account deletion, typed API errors, DPoP detection, and API tests.
Client connected-account orchestration
src/server/client.ts, src/server/client.test.ts
Adds request-aware connect, disconnect, and list flows; My Account token minting; login-hint matching; cached-token reconciliation; and session persistence.
Connection-token cookie cleanup
src/server/session/stateless-session-store.ts, src/server/session/stateless-session-store.test.ts, src/server/client.test.ts
Deletes indexed orphan cookies after token-set shrinkage and verifies deletion and preservation cases.
Connected-account documentation
EXAMPLES.md
Documents connected-account methods, login-hint behavior, request context, reconciliation, and cookie persistence.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Request
  participant Auth0Client
  participant AuthClient
  participant MyAccountAPI
  participant SessionStore
  Request->>Auth0Client: Request connected-account operation
  Auth0Client->>AuthClient: Mint My Account token
  AuthClient->>MyAccountAPI: List or delete connected accounts
  MyAccountAPI-->>AuthClient: Return account data or status
  AuthClient-->>Auth0Client: Return result or typed error
  Auth0Client->>SessionStore: Reconcile cached token sets
  SessionStore-->>Request: Persist session and cookie changes
Loading

Possibly related PRs

Suggested reviewers: tusharpandey13

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 53.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main changes: connected-account listing, disconnection, and orphan cookie cleanup.
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.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/connected-accounts-disconnect

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
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (2)
src/server/client.ts (1)

1827-1827: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

connectAccount doesn't use the new getMyAccountAccessToken path.

Unlike disconnectAccount/getConnectedAccounts, this still calls getAccessToken(options) even when a request was supplied, so a refreshed token set isn't persisted in middleware/Pages Router usage. Since this overload takes no res, either document the limitation or thread a response through.

🤖 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/server/client.ts` at line 1827, Update connectAccount to use the
getMyAccountAccessToken path when a request is supplied, ensuring refreshed
tokens are persisted for middleware/Pages Router usage. Because connectAccount
has no response parameter, either thread the response through its API and call
path or explicitly document the persistence limitation; do not leave the request
path using getAccessToken alone.
src/server/auth-client.ts (1)

4495-4507: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low value

Partial-failure information is discarded.

If the second of three deletes fails, the accounts already removed server-side are dropped along with the returned tuple, so Auth0Client.disconnectAccount throws and skips pruning the now-invalid cached connection tokens. Consider surfacing the removed subset (e.g. on the error) so callers can reconcile.

🤖 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/server/auth-client.ts` around lines 4495 - 4507, Update the
matching-account deletion flow in Auth0Client.disconnectAccount so a later
delete failure preserves and surfaces the already removed accounts instead of
returning only the error. Attach or otherwise propagate the removed subset
alongside the delete error, and ensure the caller can use it to prune invalid
cached connection tokens while retaining the existing all-success result.
🤖 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/server/auth-client.ts`:
- Around line 4364-4397: Bound the pagination loop around the connected-accounts
fetch by enforcing a finite maximum page count and tracking previously seen next
tokens. Before each request, stop or return the existing failed-to-list error
when the limit is reached or the token repeats, while preserving normal account
accumulation and pagination for valid changing tokens.

In `@src/server/client.ts`:
- Around line 1185-1191: Update the token-set replacement logic in the
existingTokenSet branch to replace only the specific entry matched by the
retrieval lookup, rather than every entry sharing options.connection when
login_hint is absent. Reuse the matched token set’s identity or index from the
preceding find operation while preserving all other connectionTokenSets entries.

In `@src/server/session/stateless-session-store.ts`:
- Around line 149-162: Update the orphan-cookie cleanup loop in the session
store method containing getConnectionTokenSetsCookies so that each deleted
cookie is removed from both resCookies and reqCookies. Preserve the existing
index filtering and cookie deletion options, ensuring subsequent get/set
operations in the same request cannot reassemble deleted __FC_i cookies.

---

Nitpick comments:
In `@src/server/auth-client.ts`:
- Around line 4495-4507: Update the matching-account deletion flow in
Auth0Client.disconnectAccount so a later delete failure preserves and surfaces
the already removed accounts instead of returning only the error. Attach or
otherwise propagate the removed subset alongside the delete error, and ensure
the caller can use it to prune invalid cached connection tokens while retaining
the existing all-success result.

In `@src/server/client.ts`:
- Line 1827: Update connectAccount to use the getMyAccountAccessToken path when
a request is supplied, ensuring refreshed tokens are persisted for
middleware/Pages Router usage. Because connectAccount has no response parameter,
either thread the response through its API and call path or explicitly document
the persistence limitation; do not leave the request path using getAccessToken
alone.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: e7d17720-5819-4f3c-a35b-a786084fdb55

📥 Commits

Reviewing files that changed from the base of the PR and between ae12f99 and 3548ca9.

📒 Files selected for processing (11)
  • src/errors/index.ts
  • src/errors/my-account-errors.ts
  • src/server/auth-client.test.ts
  • src/server/auth-client.ts
  • src/server/client.test.ts
  • src/server/client.ts
  • src/server/session/stateless-session-store.test.ts
  • src/server/session/stateless-session-store.ts
  • src/types/connected-accounts.ts
  • src/types/index.ts
  • src/types/token-vault.ts

Comment thread src/server/auth-client.ts
Comment thread src/server/client.ts
Comment thread src/server/session/stateless-session-store.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

⚠️ Outside diff range comments (2)
src/server/client.ts (2)

1959-1982: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Post-mint session re-read reads request cookies, which saveToSession never updates. Both reconciliation paths re-read via getSessionFromAuthClient to avoid clobbering a rotated refresh token, but for middleware and Pages Router the rotated session was only written to res.cookies / response headers, so the re-read returns the pre-mint snapshot and the clobbering can still occur.

  • src/server/client.ts#L1959-L1982: in disconnectAccount, obtain the post-mint session from the mint path (e.g. have getMyAccountAccessToken return the persisted session) rather than re-reading request cookies.
  • src/server/client.ts#L2067-L2093: apply the same change in getConnectedAccounts so reconciliation prunes from the actually-persisted session.
🤖 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/server/client.ts` around lines 1959 - 1982, Update disconnectAccount at
src/server/client.ts lines 1959-1982 to use the session persisted by the
getMyAccountAccessToken mint path instead of re-reading request cookies, then
prune and save that session. Apply the same persisted-session flow in
getConnectedAccounts at src/server/client.ts lines 2067-2093; both sites must
reconcile against the post-mint session so rotated tokens are preserved.

1845-1863: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Route the My Account token mint through the request-aware getAccessToken overload.

connectAccount(options, req) resolves normalizedReq before minting, but then calls this.getAccessToken(getMyAccountTokenOpts), which uses the App Router signature without a response object. In middleware/Path Router contexts, refresh: true token updates are not persisted because saveToSession() takes the App Router cookies path. Use a helper that calls getAccessToken(req, res, options) when a response is available, and getAccessToken(req, options) when only middleware/request context is available, with no-op cookie persistence for App Router calls as needed.

🤖 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/server/client.ts` around lines 1845 - 1863, The My Account token mint in
connectAccount must use the request-aware getAccessToken overload so refreshed
tokens persist correctly. After resolving normalizedReq and the available
response, call getAccessToken(req, res, getMyAccountTokenOpts) when a response
exists, otherwise call getAccessToken(req, getMyAccountTokenOpts); preserve the
App Router path with no-op cookie persistence where required.
🧹 Nitpick comments (3)
src/server/auth-client.ts (2)

4363-4409: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Cycle guard looks correct; consider de-duplicating accumulated accounts.

The guard bounds pages and stops on a repeated token, but a misbehaving server that echoes next once still yields the same account twice in accounts. disconnectAccount would then issue a duplicate DELETE for that id, likely turning a success into failed_to_delete. Deduping by account.id while accumulating removes that edge case.

🤖 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/server/auth-client.ts` around lines 4363 - 4409, Deduplicate accounts in
the pagination loop before appending them to accounts, using account.id as the
uniqueness key. Update the accumulation logic around the body.accounts iteration
so repeated IDs are retained only once, while preserving the existing field
mapping and pagination behavior.

6891-6925: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Near-duplicate of buildConnectAccountErrorResponse.

Both helpers differ only in the error class and message text. A single generic builder (taking a factory + message) would keep the MyAccountApiError cause-parsing logic in one place.

🤖 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/server/auth-client.ts` around lines 6891 - 6925, The error-response
helpers duplicate the response parsing and MyAccountApiError cause construction.
Refactor buildConnectAccountErrorResponse and
buildDisconnectAccountErrorResponse into one generic builder that accepts the
appropriate error factory and action message, preserving each helper’s public
return type and error-specific behavior while centralizing JSON parsing and
fallback handling.
src/server/client.test.ts (1)

1197-1232: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Test mocks the very read it is validating.

Stubbing getSessionFromAuthClient with two queued values asserts the code calls it twice, not that a real re-read observes the rotated session. A variant driving the store through actual request/response cookies (as the gh-2450 test does) would cover the Pages Router / middleware path where request cookies are not updated by saveToSession.

🤖 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/server/client.test.ts` around lines 1197 - 1232, Replace the queued
getSessionFromAuthClient mocks in the disconnectAccount test with a realistic
session-store flow that drives rotation through actual request/response cookies,
following the gh-2450 test pattern. Ensure the test verifies the re-read
observes the rotated refresh token while disconnectAccount still prunes the
requested connection, without mocking the getSessionFromAuthClient read being
validated.
🤖 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.

Outside diff comments:
In `@src/server/client.ts`:
- Around line 1959-1982: Update disconnectAccount at src/server/client.ts lines
1959-1982 to use the session persisted by the getMyAccountAccessToken mint path
instead of re-reading request cookies, then prune and save that session. Apply
the same persisted-session flow in getConnectedAccounts at src/server/client.ts
lines 2067-2093; both sites must reconcile against the post-mint session so
rotated tokens are preserved.
- Around line 1845-1863: The My Account token mint in connectAccount must use
the request-aware getAccessToken overload so refreshed tokens persist correctly.
After resolving normalizedReq and the available response, call
getAccessToken(req, res, getMyAccountTokenOpts) when a response exists,
otherwise call getAccessToken(req, getMyAccountTokenOpts); preserve the App
Router path with no-op cookie persistence where required.

---

Nitpick comments:
In `@src/server/auth-client.ts`:
- Around line 4363-4409: Deduplicate accounts in the pagination loop before
appending them to accounts, using account.id as the uniqueness key. Update the
accumulation logic around the body.accounts iteration so repeated IDs are
retained only once, while preserving the existing field mapping and pagination
behavior.
- Around line 6891-6925: The error-response helpers duplicate the response
parsing and MyAccountApiError cause construction. Refactor
buildConnectAccountErrorResponse and buildDisconnectAccountErrorResponse into
one generic builder that accepts the appropriate error factory and action
message, preserving each helper’s public return type and error-specific behavior
while centralizing JSON parsing and fallback handling.

In `@src/server/client.test.ts`:
- Around line 1197-1232: Replace the queued getSessionFromAuthClient mocks in
the disconnectAccount test with a realistic session-store flow that drives
rotation through actual request/response cookies, following the gh-2450 test
pattern. Ensure the test verifies the re-read observes the rotated refresh token
while disconnectAccount still prunes the requested connection, without mocking
the getSessionFromAuthClient read being validated.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 864094a6-6a2e-423e-bfed-b9f661a152bb

📥 Commits

Reviewing files that changed from the base of the PR and between 8757983 and e7dcff4.

📒 Files selected for processing (5)
  • src/server/auth-client.test.ts
  • src/server/auth-client.ts
  • src/server/client.test.ts
  • src/server/client.ts
  • src/server/session/stateless-session-store.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/server/session/stateless-session-store.ts

// disconnected), the trailing higher-index cookies would otherwise linger as
// orphans and be re-assembled into the session on the next read. Delete any
// `__FC_i` present in the request whose index is beyond the current length.
for (const cookie of this.getConnectionTokenSetsCookies(reqCookies)) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

this loop is the __FC side of the 431 fix. the connection token cookies are positional (__FC_0..n-1), so when the array shrinks (someone disconnects an account) the higher-index cookies don't get overwritten by the write above. leave them and the browser keeps sending them, they get re-assembled into the session on the next read, and the request header grows until you hit 431. so here i just delete any __FC_i in the request whose index is past the current count.

the reqCookies.delete() is the easy-to-miss part: storeInCookie writes reqCookies too for read-after-write in the same middleware request, so a res-only deletion would still be re-read and re-assembled within that same request. deleting from both keeps it gone.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 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/server/auth-client.ts`:
- Around line 4370-4372: Update the pagination loop in the account-fetching
method containing the pages, next, and seenNext checks so exceeding MAX_PAGES or
detecting a repeated next cursor returns or propagates an error instead of
breaking with partial account data. Preserve normal pagination results while
ensuring downstream reconciliation cannot treat truncated results as successful.
- Around line 4412-4417: Replace the DPoPError instanceof checks in both catch
blocks with a shared predicate that identifies DPoP failures by the caught
error’s error.code value. Reuse that predicate when selecting the error message,
preserving the existing fallback message and DPoP-specific message behavior.

In `@src/server/client.ts`:
- Around line 1828-1833: Update the Connect Account token-minting flow around
resolveRequestContext, getSessionFromAuthClient, and connectAccountResponse to
pass normalizedReq instead of re-resolving ambient request context. Propagate
any refreshed session cookies produced during minting onto
connectAccountResponse, preserving the resolved auth client and normalized
request throughout middleware/MCD flows.
- Around line 1960-1967: The session pruning flow around
getSessionFromAuthClient must not re-read the session from request cookies after
token minting. Make the token-mint path return or expose its updated session
snapshot, then use that value for pruning and saving, preserving the existing
fallback only when no updated session is available; apply the same change to the
corresponding flow near the second occurrence.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 88e1f336-5491-4da5-92e6-add285d9fac9

📥 Commits

Reviewing files that changed from the base of the PR and between e7dcff4 and 6f1b073.

📒 Files selected for processing (4)
  • src/server/auth-client.ts
  • src/server/client.ts
  • src/types/index.ts
  • src/types/token-vault.ts

Comment thread src/server/auth-client.ts Outdated
Comment thread src/server/auth-client.ts
Comment thread src/server/client.ts
Comment thread src/server/client.ts Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
src/server/auth-client.ts (1)

6945-6954: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert message in the type guard.

The guard narrows to { code: DPoPErrorCode; message: string } but only checks code. All three call sites then assign e.message to the returned error message. If the thrown value has a matching code and no string message, the SDK surfaces undefined as the error message. Add a message check so the narrowed type matches what is verified.

♻️ Proposed refactor
 function isDPoPError(
   e: unknown
 ): e is { code: DPoPErrorCode; message: string } {
   return (
     typeof e === "object" &&
     e !== null &&
     "code" in e &&
+    typeof (e as { message?: unknown }).message === "string" &&
     Object.values(DPoPErrorCode).includes((e as { code: DPoPErrorCode }).code)
   );
 }
🤖 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/server/auth-client.ts` around lines 6945 - 6954, Update the isDPoPError
type guard to also verify that e has a message property whose value is a string,
alongside the existing DPoPErrorCode check, so its narrowed type is fully
validated before callers use e.message.
src/server/client.test.ts (1)

900-906: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add direct coverage for mintMyAccountToken.

These suites mock the private mintMyAccountToken, so the callers are verified against a stubbed contract only. The method's own logic stays untested: persist: true versus persist: false, the sessionChanged computation from getSessionChangesAfterGetAccessToken, the finalizeSession call, and the MISSING_SESSION throw. A regression inside mintMyAccountToken would keep all of these tests green.

Add one focused suite that calls mintMyAccountToken with a real session and a stubbed authClient.getTokenSet, and assert the returned session, sessionChanged, and whether saveToSession ran.

Also applies to: 1108-1115

🤖 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/server/client.test.ts` around lines 900 - 906, Add focused direct tests
for the private mintMyAccountToken method, using a real session and a stubbed
authClient.getTokenSet; cover both persist: true and persist: false, assert the
returned session and sessionChanged from getSessionChangesAfterGetAccessToken,
verify finalizeSession/saveToSession behavior, and assert MISSING_SESSION is
thrown when no session exists. Keep existing caller tests unchanged.
🤖 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.

Nitpick comments:
In `@src/server/auth-client.ts`:
- Around line 6945-6954: Update the isDPoPError type guard to also verify that e
has a message property whose value is a string, alongside the existing
DPoPErrorCode check, so its narrowed type is fully validated before callers use
e.message.

In `@src/server/client.test.ts`:
- Around line 900-906: Add focused direct tests for the private
mintMyAccountToken method, using a real session and a stubbed
authClient.getTokenSet; cover both persist: true and persist: false, assert the
returned session and sessionChanged from getSessionChangesAfterGetAccessToken,
verify finalizeSession/saveToSession behavior, and assert MISSING_SESSION is
thrown when no session exists. Keep existing caller tests unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 0abadc16-575e-40af-b5ab-0972b6ee1497

📥 Commits

Reviewing files that changed from the base of the PR and between 6f1b073 and e290461.

📒 Files selected for processing (4)
  • src/server/auth-client.test.ts
  • src/server/auth-client.ts
  • src/server/client.test.ts
  • src/server/client.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/server/auth-client.test.ts

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