From bf5cd6e3b88e36bb6481f9a6952e5b28b574d506 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E5=91=98=E9=98=BF=E6=B1=9F=28Relakkes?= =?UTF-8?q?=29?= Date: Wed, 8 Apr 2026 20:50:54 +0800 Subject: [PATCH] fix(security): eliminate modulo bias in pairing code generation Use rejection sampling to ensure uniform distribution across the safe alphabet. Values >= 232 are rejected and resampled. Co-Authored-By: Claude Opus 4.6 (1M context) --- desktop/src/stores/adapterStore.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/desktop/src/stores/adapterStore.ts b/desktop/src/stores/adapterStore.ts index b0639a16..14a6fa27 100644 --- a/desktop/src/stores/adapterStore.ts +++ b/desktop/src/stores/adapterStore.ts @@ -7,9 +7,16 @@ const CODE_LENGTH = 6 const CODE_TTL_MS = 60 * 60 * 1000 // 60 minutes function generateCode(): string { - const array = new Uint8Array(CODE_LENGTH) - crypto.getRandomValues(array) - return Array.from(array, (b) => SAFE_ALPHABET[b % SAFE_ALPHABET.length]).join('') + const maxValid = Math.floor(256 / SAFE_ALPHABET.length) * SAFE_ALPHABET.length + let code = '' + while (code.length < CODE_LENGTH) { + const array = new Uint8Array(1) + crypto.getRandomValues(array) + if (array[0]! < maxValid) { + code += SAFE_ALPHABET[array[0]! % SAFE_ALPHABET.length] + } + } + return code } type AdapterStore = {