Skip to content

feat: enhance WebSocket connection handling with token validation and update response caching#1820

Merged
Artuomka merged 2 commits into
mainfrom
backend_fixes
Jun 2, 2026
Merged

feat: enhance WebSocket connection handling with token validation and update response caching#1820
Artuomka merged 2 commits into
mainfrom
backend_fixes

Conversation

@Artuomka

@Artuomka Artuomka commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Security
    • Improved WebSocket connection authentication by validating and storing connection tokens for each session
    • Added token routing verification to ensure cached command responses are securely delivered only to their authorized connections
    • Strengthened authentication security through updated token expiration handling

Copilot AI review requested due to automatic review settings June 2, 2026 13:03
@coderabbitai

coderabbitai Bot commented Jun 2, 2026

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

WebSocket responses are cached with authentication tokens for routing validation. Commands now pass connectionToken.token to cacheResponse, which stores it as routedToken. On retrieval, the socket's agentToken must match the cached token. JWT expiration is reduced from 60 days to 120 seconds.

Changes

Token-based response routing

Layer / File(s) Summary
Response cache contract and token storage
autoadmin-ws-server/src/services/response-cache.ts
CachedResponse interface adds routedToken: string field. cacheResponse function now accepts and stores routedToken alongside existing resolve, reject, sendError, and createdAt fields.
Command-to-cache token propagation
autoadmin-ws-server/src/handlers/command.ts
executeCommand passes connectionToken.token as an argument to cacheResponse when setting up response caching handlers.
Socket authentication binding and verification
autoadmin-ws-server/src/handlers/websocket.ts
New AuthenticatedSocket type extends WebSocket with optional agentToken field. During initialConnection, the hashed connectionToken is stored as ws.agentToken. During dataFromAgent handling with a cached response, the socket's agentToken is verified against cachedResponse.routedToken; mismatched or missing tokens trigger a warning and discard the message.

JWT expiration update

Layer / File(s) Summary
JWT expiration logic update
shared-code/src/data-access-layer/data-access-objects/data-access-object-agent.ts
generateJWT now computes exp as a Unix timestamp (Math.floor(Date.now() / 1000) + 120) instead of a Date object offset, reducing JWT lifetime from 60 days to 120 seconds.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A token hops along the wire,
Matching claims to roots entire,
Socket guards the cached reply,
JWT's swift expiration flies—
Two minutes' grace, then tokens die! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Security Check ⚠️ Warning websocket.ts caches connections by hashed token; command.ts routes responses using raw JWT token. This token canonicalization mismatch breaks request-response routing and security validations. Hash JWT token in command.ts before cacheResponse/sendCommandToClient calls, or remove hashing from websocket.ts and use raw tokens consistently.
✅ 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 accurately describes the main changes across the pull request: token validation mechanisms added to WebSocket handling and response caching infrastructure updated to support token-based routing.
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.

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

✨ 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 backend_fixes

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.

@Artuomka Artuomka enabled auto-merge June 2, 2026 13:04

Copilot AI 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.

Pull request overview

This PR strengthens the autoadmin WebSocket request/response flow by binding cached HTTP responses to an authenticated agent connection token, preventing cross-connection response mix-ups, and it also adjusts the JWT expiration used for WS-server authorization.

Changes:

  • Bind dataFromAgent responses to the specific routed (hashed) connection token via responseCache metadata.
  • Track an authenticated token on each WebSocket and validate it before resolving cached responses.
  • Shorten the JWT exp calculation used by DataAccessObjectAgent when calling the WS server.

Reviewed changes

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

File Description
shared-code/src/data-access-layer/data-access-objects/data-access-object-agent.ts Updates JWT expiration logic used for WS-server authorization.
autoadmin-ws-server/src/services/response-cache.ts Extends cached response entries with the routed connection token.
autoadmin-ws-server/src/handlers/websocket.ts Binds sockets to an authenticated token and validates dataFromAgent against the routed token.
autoadmin-ws-server/src/handlers/command.ts Passes the routed token into the response cache when issuing a command.

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

Comment on lines 51 to 54
connectionToken = hashedToken;
data.connectionToken = connectionToken;
(ws as AuthenticatedSocket).agentToken = hashedToken;
}
Comment on lines 823 to 827
private generateJWT(connectionToken: string): string {
const exp = new Date();
exp.setDate(exp.getDate() + 60);
const exp = Math.floor(Date.now() / 1000) + 120;
const secret = process.env.JWT_SECRET;
return jwt.sign(
{
@Artuomka Artuomka merged commit f92662f into main Jun 2, 2026
16 of 17 checks passed
@Artuomka Artuomka deleted the backend_fixes branch June 2, 2026 13:12
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