From a7d0f4b952c65932c88b173d47e55357e0492a27 Mon Sep 17 00:00:00 2001 From: Maxwell Calkin Date: Sun, 8 Mar 2026 22:16:24 -0400 Subject: [PATCH] fix(security): use CSPRNG for password and OTP generation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace Math.random() with cryptographically secure alternatives in two security-critical code paths: - generatePassword() in encryption.ts: use randomBytes() (already imported) instead of Math.random() for deployment password generation - generateOTP() in chat OTP route: use crypto.randomInt() instead of Math.random() for authentication code generation Math.random() is not cryptographically secure — its output is predictable and can be reconstructed from a few observed values. Both functions generate authentication material that directly protects user accounts and deployed workflows. This PR was authored by Claude Opus 4.6 (AI), operated by @MaxwellCalkin Co-Authored-By: Claude Opus 4.6 --- apps/sim/app/api/chat/[identifier]/otp/route.ts | 4 ++-- apps/sim/lib/core/security/encryption.ts | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/apps/sim/app/api/chat/[identifier]/otp/route.ts b/apps/sim/app/api/chat/[identifier]/otp/route.ts index e518ceb28a5..f2130c622bf 100644 --- a/apps/sim/app/api/chat/[identifier]/otp/route.ts +++ b/apps/sim/app/api/chat/[identifier]/otp/route.ts @@ -1,4 +1,4 @@ -import { randomUUID } from 'crypto' +import { randomInt, randomUUID } from 'crypto' import { db } from '@sim/db' import { chat, verification } from '@sim/db/schema' import { createLogger } from '@sim/logger' @@ -17,7 +17,7 @@ import { createErrorResponse, createSuccessResponse } from '@/app/api/workflows/ const logger = createLogger('ChatOtpAPI') function generateOTP() { - return Math.floor(100000 + Math.random() * 900000).toString() + return randomInt(100000, 1000000).toString() } const OTP_EXPIRY = 15 * 60 // 15 minutes diff --git a/apps/sim/lib/core/security/encryption.ts b/apps/sim/lib/core/security/encryption.ts index 9f82f4c04da..ec2c19261db 100644 --- a/apps/sim/lib/core/security/encryption.ts +++ b/apps/sim/lib/core/security/encryption.ts @@ -76,8 +76,9 @@ export function generatePassword(length = 24): string { const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_-+=' let result = '' + const bytes = randomBytes(length) for (let i = 0; i < length; i++) { - result += chars.charAt(Math.floor(Math.random() * chars.length)) + result += chars.charAt(bytes[i] % chars.length) } return result