Skip to content

fix(socket): use core auth user id for socket state scoping#1984

Merged
senamakel merged 2 commits into
tinyhumansai:mainfrom
Yong-yuan-X:fix/1942-socket-user-id-from-core-state
May 17, 2026
Merged

fix(socket): use core auth user id for socket state scoping#1984
senamakel merged 2 commits into
tinyhumansai:mainfrom
Yong-yuan-X:fix/1942-socket-user-id-from-core-state

Conversation

@Yong-yuan-X
Copy link
Copy Markdown
Contributor

@Yong-yuan-X Yong-yuan-X commented May 17, 2026

Summary

  • Removed client-side JWT payload decoding from socketService.
  • Scoped socket Redux state from the authenticated core state snapshot.
  • Added regression coverage to ensure JWT payload user IDs are ignored.

Problem

  • socketService decoded sessionToken with atob() to derive a socket user ID.
  • That duplicated auth interpretation in the frontend and could drift from the core-authenticated user snapshot.
  • Socket state should trust core auth state, not token internals.

Solution

  • Updated getSocketUserId() to use getCoreStateSnapshot().snapshot.auth.userId ?? '__pending__'.
  • Removed the JWT payload parsing type and decode path.
  • Updated socket service mocks to include auth.userId.
  • Added a focused test where the JWT payload contains a different user ID and the core snapshot still wins.

Submission Checklist

  • Tests added or updated (happy path + at least one failure / edge case) per Testing Strategy
  • Diff coverage ≥ 80% - focused tests added for changed socket-service behavior; CI will enforce final changed-line coverage.
  • Coverage matrix updated - N/A: no feature added/removed/renamed.
  • All affected feature IDs from the matrix are listed in the PR description under ## Related - N/A: no coverage-matrix feature row affected.
  • No new external network dependencies introduced (mock backend used per Testing Strategy)
  • Manual smoke checklist updated if this touches release-cut surfaces - N/A: frontend socket state source change only.
  • Linked issue closed via Closes #NNN in the ## Related section

Impact

  • Frontend socket state now follows the core-authenticated user ID.
  • Reduces auth drift risk by removing frontend JWT interpretation.
  • No new runtime dependencies, migrations, backend changes, or user-visible UI changes.

Related


AI Authored PR Metadata (required for Codex/Linear PRs)

Linear Issue

  • Key: N/A
  • URL: N/A

Commit & Branch

  • Branch: fix/1942-socket-user-id-from-core-state
  • Commit SHA: 1801d215

Validation Run

  • pnpm --filter openhuman-app format:check
  • pnpm typecheck
  • Focused tests:
    • pnpm.cmd --dir app exec vitest run --config test/vitest.config.ts src/services/__tests__/socketService.test.ts src/services/__tests__/socketService.events.test.ts
  • Rust fmt/check (if changed):
    • cargo fmt --manifest-path ../Cargo.toml --all --check
    • cargo fmt --manifest-path src-tauri/Cargo.toml --all --check
    • cargo check --manifest-path src-tauri/Cargo.toml
  • Tauri fmt/check (if changed):
    • cargo fmt --manifest-path src-tauri/Cargo.toml --all --check
    • cargo check --manifest-path src-tauri/Cargo.toml

Validation Blocked

  • command: N/A
  • error: N/A
  • impact: N/A

Behavior Changes

  • Intended behavior change: socket user state is keyed from core auth snapshot user ID instead of decoded JWT payload fields.
  • User-visible effect: none expected.

Parity Contract

  • Legacy behavior preserved: socket connect/disconnect/backend status dispatch flow remains unchanged.
  • Guard/fallback/dispatch parity checks: fallback remains __pending__ when no core auth user ID is available; focused tests cover socket connection and event dispatch behavior.

Duplicate / Superseded PR Handling

  • Duplicate PR(s): N/A
  • Canonical PR: This PR
  • Resolution (closed/superseded/updated): N/A

Summary by CodeRabbit

  • Bug Fixes
    • User identity for socket connections is now resolved from the core auth state (reducing incorrect JWT-derived identities) and falls back to a pending placeholder when missing.
  • Tests
    • Added and updated unit tests to verify socket user resolution behavior and the pending-user fallback.

Review Change Stack

@Yong-yuan-X Yong-yuan-X requested a review from a team May 17, 2026 04:51
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 17, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: bddf024d-c1d9-4205-98e9-b3912722558d

📥 Commits

Reviewing files that changed from the base of the PR and between 1801d21 and c7b6b99.

📒 Files selected for processing (2)
  • app/src/services/__tests__/socketService.test.ts
  • app/src/services/socketService.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/src/services/tests/socketService.test.ts

📝 Walkthrough

Walkthrough

Socket service now derives the current user ID from CoreStateProvider snapshot auth state instead of unverified client-side JWT decoding. getSocketUserId() reads snapshot.auth.userId and falls back to 'pending'. Tests updated to mock snapshot.auth.userId and verify socket operations use the core auth userId.

Changes

Socket Service Auth State Migration

Layer / File(s) Summary
Socket user ID derivation from core auth state
app/src/services/socketService.ts
Removed JwtPayload type and JWT parsing/decoding from getSocketUserId(); it now returns getCoreStateSnapshot().snapshot?.auth?.userId ?? '__pending__'.
Test coverage for core auth state usage
app/src/services/__tests__/socketService.events.test.ts, app/src/services/__tests__/socketService.test.ts
Updated mocks of getCoreStateSnapshot() to include snapshot.auth.userId. Added tests asserting socketService calls setStatusForUser with the core auth.userId, and that it falls back to userId: '__pending__' when snapshot.auth.userId is absent.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 In memory a token hopped around,
I sniffed the core where truth is found,
No more raw decodes, no loose string,
From core auth now the user springs,
The rabbit nods — secure and sound.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.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 change: replacing JWT-based socket user ID derivation with the core auth user ID.
Linked Issues check ✅ Passed The changes fully address issue #1942 by removing client-side JWT decoding and sourcing userId from the core auth snapshot instead.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the linked issue: socketService tests updated, JWT decode removed, core auth userId used instead.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


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
Copy Markdown
Contributor

@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

🤖 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 `@app/src/services/socketService.ts`:
- Line 96: The current return expression directly dereferences
getCoreStateSnapshot().snapshot.auth.userId so if snapshot or auth is undefined
the access will throw and the '__pending__' fallback won't run; update the
access in socketService.ts to guard the nested path with optional chaining
(e.g., use snapshot?.auth?.userId) when retrieving the userId from
getCoreStateSnapshot() so the nullish fallback is honored.
🪄 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: CHILL

Plan: Pro

Run ID: d3876ff6-5f74-48fe-8f3f-17cb69231ce0

📥 Commits

Reviewing files that changed from the base of the PR and between a6e311e and 1801d21.

📒 Files selected for processing (3)
  • app/src/services/__tests__/socketService.events.test.ts
  • app/src/services/__tests__/socketService.test.ts
  • app/src/services/socketService.ts

Comment thread app/src/services/socketService.ts Outdated
@senamakel senamakel merged commit 3aa8477 into tinyhumansai:main May 17, 2026
24 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.

Security: Client-side JWT decode without verification in socketService.ts

2 participants