Conversation
| * Create a new session | ||
| */ | ||
| async createSession(userId?: string): Promise<string> { | ||
| const sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; |
Check failure
Code scanning / CodeQL
Insecure randomness High
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 6 days ago
In general, to fix insecure randomness you should replace Math.random() (or similarly weak PRNGs) wherever they are used to generate security-sensitive values (session IDs, tokens, passwords, etc.) with a cryptographically secure random number generator. In Node.js, the standard solution is crypto.randomBytes() from the built-in crypto module, which uses a CSPRNG. Convert those bytes to a URL-safe or hex string of sufficient length and use that as the random component of your identifier.
For this specific case, we should change createSession so that it no longer uses Math.random() and instead uses crypto.randomBytes to generate the random segment. We will keep the overall behavior and string format (a session_ prefix and timestamp) but change only the random suffix generation. That means:
- Add an import of Node’s
cryptomodule at the top ofserver/api/services/agent.ts. - In
createSession, replaceMath.random().toString(36).substr(2, 9)with something likecrypto.randomBytes(16).toString('hex'), which yields 32 hex characters (128 bits of randomness). - Keep the rest of the method intact so that how
sessionIdis stored and used remains unchanged.
Concretely:
- Modify
server/api/services/agent.ts:- Add
import crypto from 'crypto';(orimport * as crypto from 'crypto';) alongside existing imports. - Update line 51 to build
sessionIdusingcrypto.randomBytes(...)instead ofMath.random().
- Add
| @@ -14,6 +14,7 @@ | ||
| buildSystemPrompt, | ||
| } from './prompts.js'; | ||
| import axios from 'axios'; | ||
| import crypto from 'crypto'; | ||
|
|
||
| export interface AgentSource { | ||
| number: number; | ||
| @@ -48,7 +49,8 @@ | ||
| * Create a new session | ||
| */ | ||
| async createSession(userId?: string): Promise<string> { | ||
| const sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; | ||
| const randomSuffix = crypto.randomBytes(16).toString('hex'); | ||
| const sessionId = `session_${Date.now()}_${randomSuffix}`; | ||
|
|
||
| await AgentHistory.create({ | ||
| sessionId, |
Co-authored-by: Jake Turner <52841588+jakeaturner@users.noreply.github.com>
This reverts commit e9b148d.
|
🎉 This PR is included in version 2.116.0 🎉 The release is available on GitHub release Your semantic-release bot 📦🚀 |
No description provided.