feat: fix CompactSeedQR binary QR code scanning with jsQR library

- Replace BarcodeDetector with jsQR for raw binary byte access
- BarcodeDetector forced UTF-8 decoding which corrupted binary data
- jsQR's binaryData property preserves raw bytes without text conversion
- Fix regex bug: use single backslash \x00 instead of \x00 for binary detection
- Add debug logging for scan data inspection
- QR generation already worked (Krux-compatible), only scanning was broken

Resolves binary QR code scanning for 12/24-word CompactSeedQR format.
Tested with Krux device - full bidirectional compatibility confirmed.
This commit is contained in:
LC mac
2026-02-07 04:22:56 +08:00
parent 49d73a7ae4
commit aa06c9ae27
39 changed files with 4664 additions and 777 deletions

View File

@@ -4,11 +4,12 @@
* @description This component provides a full UI for the multi-step seed blending process,
* handling various input formats, per-row decryption, and final output actions.
*/
import { useState, useEffect } from 'react';
import { useState, useEffect, useCallback } from 'react';
import { QrCode, X, Plus, CheckCircle2, AlertTriangle, RefreshCw, Sparkles, EyeOff, Lock, Key, ArrowRight } from 'lucide-react';
import QRScanner from './QRScanner';
import { decryptFromSeed, detectEncryptionMode } from '../lib/seedpgp';
import { decryptFromKrux } from '../lib/krux';
import { decodeSeedQR } from '../lib/seedqr'; // New import
import { QrDisplay } from './QrDisplay';
import {
blendMnemonicsAsync,
@@ -36,7 +37,7 @@ interface MnemonicEntry {
rawInput: string;
decryptedMnemonic: string | null;
isEncrypted: boolean;
inputType: 'text' | 'seedpgp' | 'krux';
inputType: 'text' | 'seedpgp' | 'krux' | 'seedqr';
passwordRequired: boolean;
passwordInput: string;
error: string | null;
@@ -157,17 +158,68 @@ export function SeedBlender({ onDirtyStateChange, setMnemonicForBackup, requestT
setShowQRScanner(true);
};
const handleScanSuccess = (scannedText: string) => {
const handleScanSuccess = useCallback(async (scannedData: string | Uint8Array) => {
if (scanTargetIndex === null) return;
// Convert binary data to hex string if necessary
const scannedText = typeof scannedData === 'string'
? scannedData
: Array.from(scannedData).map(b => b.toString(16).padStart(2, '0')).join('');
const mode = detectEncryptionMode(scannedText);
const isEncrypted = mode === 'pgp' || mode === 'krux';
updateEntry(scanTargetIndex, {
rawInput: scannedText, isEncrypted, inputType: isEncrypted ? mode : 'text',
passwordRequired: isEncrypted, decryptedMnemonic: isEncrypted ? null : scannedText, error: null,
});
let mnemonic = scannedText;
let error: string | null = null;
let inputType: 'text' | 'seedpgp' | 'krux' | 'seedqr' = 'text';
try {
if (mode === 'seedqr') {
mnemonic = await decodeSeedQR(scannedText);
inputType = 'seedqr';
updateEntry(scanTargetIndex, {
rawInput: mnemonic,
decryptedMnemonic: mnemonic,
isEncrypted: false,
passwordRequired: false,
inputType,
error: null,
});
} else if (mode === 'pgp' || mode === 'krux') {
inputType = (mode === 'pgp' ? 'seedpgp' : mode);
updateEntry(scanTargetIndex, {
rawInput: scannedText,
decryptedMnemonic: null,
isEncrypted: true,
passwordRequired: true,
inputType,
error: null,
});
} else { // text or un-recognized
updateEntry(scanTargetIndex, {
rawInput: scannedText,
decryptedMnemonic: scannedText,
isEncrypted: false,
passwordRequired: false,
inputType: 'text',
error: null,
});
}
} catch (e: any) {
error = e.message || "Failed to process QR code";
updateEntry(scanTargetIndex, { rawInput: scannedText, error });
}
setShowQRScanner(false);
};
}, [scanTargetIndex]);
const handleScanClose = useCallback(() => {
setShowQRScanner(false);
}, []);
const handleScanError = useCallback((errMsg: string) => {
if (scanTargetIndex !== null) {
updateEntry(scanTargetIndex, { error: errMsg });
}
}, [scanTargetIndex]);
const handleDecrypt = async (index: number) => {
const entry = entries[index];
if (!entry.isEncrypted || !entry.passwordInput) return;
@@ -178,7 +230,7 @@ export function SeedBlender({ onDirtyStateChange, setMnemonicForBackup, requestT
} else { // seedpgp
mnemonic = (await decryptFromSeed({ frameText: entry.rawInput, messagePassword: entry.passwordInput, mode: 'pgp' })).w;
}
updateEntry(index, { decryptedMnemonic: mnemonic, isEncrypted: false, passwordRequired: false, error: null });
updateEntry(index, { rawInput: mnemonic, decryptedMnemonic: mnemonic, isEncrypted: false, passwordRequired: false, error: null });
} catch(e: any) {
updateEntry(index, { error: e.message || "Decryption failed" });
}
@@ -251,7 +303,7 @@ export function SeedBlender({ onDirtyStateChange, setMnemonicForBackup, requestT
<div className="p-6 bg-slate-700/50 rounded-xl border border-slate-600 min-h-[10rem]">
<h3 className="font-semibold text-lg mb-4 text-slate-200">Step 2: Blended Preview</h3>
{blending ? <p className="text-sm text-slate-400">Blending...</p> : !blendError && blendedResult ? (<div className="space-y-4 animate-in fade-in">{xorStrength?.isWeak && (<div className="p-3 bg-amber-500/10 border border-amber-500/30 text-amber-300 rounded-lg text-sm flex gap-3"><AlertTriangle /><div><span className="font-bold">Weak XOR Result:</span> Detected only {xorStrength.uniqueBytes} unique bytes. This can happen if seeds are identical or too similar.</div></div>)}<div className="space-y-1"><label className="text-xs font-semibold text-slate-400">Blended Mnemonic (12-word)</label><p className="p-3 bg-slate-800 rounded-md font-mono text-sm text-slate-100 break-words">{blendedResult.blendedMnemonic12}</p></div>{blendedResult.blendedMnemonic24 && (<div className="space-y-1"><label className="text-xs font-semibold text-slate-400">Blended Mnemonic (24-word)</label><p className="p-3 bg-slate-800 rounded-md font-mono text-sm text-slate-100 break-words">{blendedResult.blendedMnemonic24}</p></div>)}</div>) : (<p className="text-sm text-slate-400">{blendError || 'Previews will appear here once you enter one or more valid mnemonics.'}</p>)}
{blending ? <p className="text-sm text-slate-400">Blending...</p> : !blendError && blendedResult ? (<div className="space-y-4 animate-in fade-in">{xorStrength?.isWeak && (<div className="p-3 bg-amber-500/10 border border-amber-500/30 text-amber-300 rounded-lg text-sm flex gap-3"><AlertTriangle /><div><span className="font-bold">Weak XOR Result:</span> Detected only {xorStrength.uniqueBytes} unique bytes. This can happen if seeds are identical or too similar.</div></div>)}<div className="space-y-1"><label className="text-xs font-semibold text-slate-400">Blended Mnemonic (12-word)</label><p data-sensitive="Blended Mnemonic (12-word)" className="p-3 bg-slate-800 rounded-md font-mono text-sm text-slate-100 break-words">{blendedResult.blendedMnemonic12}</p></div>{blendedResult.blendedMnemonic24 && (<div className="space-y-1"><label className="text-xs font-semibold text-slate-400">Blended Mnemonic (24-word)</label><p data-sensitive="Blended Mnemonic (24-word)" className="p-3 bg-slate-800 rounded-md font-mono text-sm text-slate-100 break-words">{blendedResult.blendedMnemonic24}</p></div>)}</div>) : (<p className="text-sm text-slate-400">{blendError || 'Previews will appear here once you enter one or more valid mnemonics.'}</p>)}
</div>
<div className="p-6 bg-slate-700/50 rounded-xl border border-slate-600">
@@ -260,7 +312,7 @@ export function SeedBlender({ onDirtyStateChange, setMnemonicForBackup, requestT
<textarea value={diceRolls} onChange={(e) => setDiceRolls(e.target.value.replace(/[^1-6]/g, ''))} placeholder="Enter 99+ dice rolls (e.g., 16345...)" className="w-full h-32 p-3 bg-slate-50 border-2 border-slate-200 rounded-lg text-lg font-mono text-slate-900 placeholder:text-slate-400" />
{dicePatternWarning && (<div className="p-3 bg-amber-500/10 border border-amber-500/30 text-amber-300 rounded-lg text-sm flex gap-3"><AlertTriangle /><p><span className="font-bold">Warning:</span> {dicePatternWarning}</p></div>)}
{diceStats && diceStats.length > 0 && (<div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-center"><div className="p-3 bg-slate-800 rounded-lg"><p className="text-xs text-slate-400">Rolls</p><p className="text-lg font-bold">{diceStats.length}</p></div><div className="p-3 bg-slate-800 rounded-lg"><p className="text-xs text-slate-400">Entropy (bits)</p><p className="text-lg font-bold">{diceStats.estimatedEntropyBits.toFixed(1)}</p></div><div className="p-3 bg-slate-800 rounded-lg"><p className="text-xs text-slate-400">Mean</p><p className="text-lg font-bold">{diceStats.mean.toFixed(2)}</p></div><div className="p-3 bg-slate-800 rounded-lg"><p className="text-xs text-slate-400">Chi-Square</p><p className={`text-lg font-bold ${diceStats.chiSquare > 11.07 ? 'text-amber-400' : ''}`}>{diceStats.chiSquare.toFixed(2)}</p></div></div>)}
{diceOnlyMnemonic && (<div className="space-y-1 pt-2"><label className="text-xs font-semibold text-slate-400">Dice-Only Preview Mnemonic</label><p className="p-3 bg-slate-800 rounded-md font-mono text-sm text-slate-100 break-words">{diceOnlyMnemonic}</p></div>)}
{diceOnlyMnemonic && (<div className="space-y-1 pt-2"><label className="text-xs font-semibold text-slate-400">Dice-Only Preview Mnemonic</label><p data-sensitive="Dice-Only Preview Mnemonic" className="p-3 bg-slate-800 rounded-md font-mono text-sm text-slate-100 break-words">{diceOnlyMnemonic}</p></div>)}
</div>
</div>
@@ -269,7 +321,7 @@ export function SeedBlender({ onDirtyStateChange, setMnemonicForBackup, requestT
{finalMnemonic ? (
<div className="p-4 bg-gradient-to-br from-green-50 to-emerald-50 border-2 border-green-300 rounded-2xl shadow-lg">
<div className="flex items-center justify-between mb-4"><span className="font-bold text-green-700 flex items-center gap-2 text-lg"><CheckCircle2 size={22} /> Final Mnemonic Generated</span><button onClick={() => setFinalMnemonic(null)} className="p-2.5 hover:bg-green-100 rounded-xl"><EyeOff size={22} /></button></div>
<div className="p-6 bg-white rounded-xl border-2 border-green-200 shadow-sm"><p className="font-mono text-center text-lg text-slate-800 break-words">{finalMnemonic}</p></div>
<div className="p-6 bg-white rounded-xl border-2 border-green-200 shadow-sm"><p data-sensitive="Final Blended Mnemonic" className="font-mono text-center text-lg text-slate-800 break-words">{finalMnemonic}</p></div>
<div className="mt-4 p-3 bg-red-500/10 text-red-300 rounded-lg text-xs flex gap-2"><AlertTriangle size={16} className="shrink-0 mt-0.5" /><span><strong>Security Warning:</strong> Write this down immediately. Do not save it digitally.</span></div>
<div className="grid grid-cols-2 gap-3 mt-4">
<button onClick={() => setShowFinalQR(true)} className="w-full py-2.5 bg-slate-700 text-white rounded-lg font-semibold flex items-center justify-center gap-2"><QrCode size={16}/> Export as QR</button>
@@ -282,7 +334,11 @@ export function SeedBlender({ onDirtyStateChange, setMnemonicForBackup, requestT
</div>
</div>
{showQRScanner && <QRScanner onScanSuccess={handleScanSuccess} onClose={() => setShowQRScanner(false)} />}
{showQRScanner && <QRScanner
onScanSuccess={handleScanSuccess}
onClose={handleScanClose}
onError={handleScanError}
/>}
{showFinalQR && finalMnemonic && (
<div className="fixed inset-0 bg-black/60 z-50 flex items-center justify-center" onClick={() => setShowFinalQR(false)}>
<div className="bg-white rounded-2xl p-4" onClick={e => e.stopPropagation()}>