mirror of
https://github.com/kccleoc/seedpgp-web.git
synced 2026-03-07 09:57:50 +08:00
feat: seedpgp v1.1.0 - BIP39 mnemonic PGP encryption tool
- Implement cv25519 PGP encryption/decryption - Add Base45 encoding with CRC16 integrity checks - Create SEEDPGP1 frame format for QR codes - Support BIP39 passphrase flag indicator - Add comprehensive test suite with Trezor BIP39 vectors - 15 passing tests covering all core functionality
This commit is contained in:
42
src/App.css
Normal file
42
src/App.css
Normal file
@@ -0,0 +1,42 @@
|
||||
#root {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 6em;
|
||||
padding: 1.5em;
|
||||
will-change: filter;
|
||||
transition: filter 300ms;
|
||||
}
|
||||
.logo:hover {
|
||||
filter: drop-shadow(0 0 2em #646cffaa);
|
||||
}
|
||||
.logo.react:hover {
|
||||
filter: drop-shadow(0 0 2em #61dafbaa);
|
||||
}
|
||||
|
||||
@keyframes logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
a:nth-of-type(2) .logo {
|
||||
animation: logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 2em;
|
||||
}
|
||||
|
||||
.read-the-docs {
|
||||
color: #888;
|
||||
}
|
||||
405
src/App.tsx
Normal file
405
src/App.tsx
Normal file
@@ -0,0 +1,405 @@
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
Shield,
|
||||
QrCode,
|
||||
RefreshCw,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
Lock,
|
||||
Unlock,
|
||||
Eye,
|
||||
EyeOff,
|
||||
FileKey,
|
||||
Info
|
||||
} from 'lucide-react';
|
||||
import { PgpKeyInput } from './components/PgpKeyInput';
|
||||
import { QrDisplay } from './components/QrDisplay';
|
||||
import { validateBip39Mnemonic } from './lib/bip39';
|
||||
import { buildPlaintext, encryptToSeedPgp, decryptSeedPgp } from './lib/seedpgp';
|
||||
import type { SeedPgpPlaintext } from './lib/types';
|
||||
import * as openpgp from 'openpgp';
|
||||
console.log("OpenPGP.js version:", openpgp.config.versionString);
|
||||
|
||||
function App() {
|
||||
const [activeTab, setActiveTab] = useState<'backup' | 'restore'>('backup');
|
||||
const [mnemonic, setMnemonic] = useState('');
|
||||
const [messagePassword, setMessagePassword] = useState('');
|
||||
const [pgpKeyInput, setPgpKeyInput] = useState('');
|
||||
const [privateKeyPassphrase, setPrivateKeyPassphrase] = useState('');
|
||||
const [hasBip39Passphrase, setHasBip39Passphrase] = useState(false);
|
||||
const [qrPayload, setQrPayload] = useState('');
|
||||
const [recipientFpr, setRecipientFpr] = useState('');
|
||||
const [restoreInput, setRestoreInput] = useState('');
|
||||
const [restoredData, setRestoredData] = useState<SeedPgpPlaintext | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [showMnemonic, setShowMnemonic] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const copyToClipboard = async (text: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
setCopied(true);
|
||||
window.setTimeout(() => setCopied(false), 1500);
|
||||
} catch {
|
||||
// Fallback for environments where Clipboard API is blocked
|
||||
const ta = document.createElement("textarea");
|
||||
ta.value = text;
|
||||
ta.style.position = "fixed";
|
||||
ta.style.left = "-9999px";
|
||||
document.body.appendChild(ta);
|
||||
ta.focus();
|
||||
ta.select();
|
||||
document.execCommand("copy");
|
||||
document.body.removeChild(ta);
|
||||
setCopied(true);
|
||||
window.setTimeout(() => setCopied(false), 1500);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const handleBackup = async () => {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
setQrPayload('');
|
||||
setRecipientFpr('');
|
||||
|
||||
try {
|
||||
const validation = validateBip39Mnemonic(mnemonic);
|
||||
if (!validation.valid) {
|
||||
throw new Error(validation.error);
|
||||
}
|
||||
|
||||
const plaintext = buildPlaintext(mnemonic, hasBip39Passphrase);
|
||||
|
||||
const result = await encryptToSeedPgp({
|
||||
plaintext,
|
||||
publicKeyArmored: pgpKeyInput || undefined,
|
||||
messagePassword: messagePassword || undefined,
|
||||
});
|
||||
|
||||
setQrPayload(result.framed);
|
||||
if (result.recipientFingerprint) {
|
||||
setRecipientFpr(result.recipientFingerprint);
|
||||
}
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Encryption failed');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRestore = async () => {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
setRestoredData(null);
|
||||
|
||||
try {
|
||||
const result = await decryptSeedPgp({
|
||||
frameText: restoreInput,
|
||||
privateKeyArmored: pgpKeyInput || undefined,
|
||||
privateKeyPassphrase: privateKeyPassphrase || undefined,
|
||||
messagePassword: messagePassword || undefined,
|
||||
});
|
||||
|
||||
setRestoredData(result);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Decryption failed');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 text-slate-900 p-4 md:p-8">
|
||||
<div className="max-w-5xl mx-auto bg-white rounded-2xl shadow-2xl overflow-hidden border border-slate-200">
|
||||
|
||||
{/* Header */}
|
||||
<div className="bg-gradient-to-r from-slate-900 to-slate-800 p-6 text-white flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 bg-blue-600 rounded-lg shadow-lg">
|
||||
<Shield size={28} />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">
|
||||
SeedPGP <span className="text-blue-400 font-mono text-base ml-2">v1.1</span>
|
||||
</h1>
|
||||
<p className="text-xs text-slate-400 mt-0.5">OpenPGP-secured BIP39 backup</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex bg-slate-800/50 rounded-lg p-1 backdrop-blur">
|
||||
<button
|
||||
onClick={() => {
|
||||
setActiveTab('backup');
|
||||
setError('');
|
||||
setQrPayload('');
|
||||
setRestoredData(null);
|
||||
}}
|
||||
className={`px-5 py-2 rounded-md text-sm font-semibold transition-all ${activeTab === 'backup'
|
||||
? 'bg-white text-slate-900 shadow-lg'
|
||||
: 'text-slate-300 hover:text-white hover:bg-slate-700/50'
|
||||
}`}
|
||||
>
|
||||
Backup
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
setActiveTab('restore');
|
||||
setError('');
|
||||
setQrPayload('');
|
||||
setRestoredData(null);
|
||||
}}
|
||||
className={`px-5 py-2 rounded-md text-sm font-semibold transition-all ${activeTab === 'restore'
|
||||
? 'bg-white text-slate-900 shadow-lg'
|
||||
: 'text-slate-300 hover:text-white hover:bg-slate-700/50'
|
||||
}`}
|
||||
>
|
||||
Restore
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-6 md:p-8 space-y-6">
|
||||
{/* Error Display */}
|
||||
{error && (
|
||||
<div className="p-4 bg-red-50 border-l-4 border-red-500 rounded-r-xl flex gap-3 text-red-800 text-sm items-start animate-in slide-in-from-top-2">
|
||||
<AlertCircle className="shrink-0 mt-0.5" size={20} />
|
||||
<div>
|
||||
<p className="font-bold mb-1">Error</p>
|
||||
<p className="whitespace-pre-wrap">{error}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Info Banner */}
|
||||
{recipientFpr && activeTab === 'backup' && (
|
||||
<div className="p-3 bg-blue-50 border border-blue-200 rounded-lg flex items-start gap-3 text-blue-800 text-xs animate-in fade-in">
|
||||
<Info size={16} className="shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<strong>Recipient Key:</strong> <code className="bg-blue-100 px-1.5 py-0.5 rounded font-mono">{recipientFpr}</code>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Main Content Grid */}
|
||||
<div className="grid gap-6 md:grid-cols-3">
|
||||
<div className="md:col-span-2 space-y-6">
|
||||
{activeTab === 'backup' ? (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-semibold text-slate-700">BIP39 Mnemonic</label>
|
||||
<textarea
|
||||
className="w-full h-32 p-4 bg-slate-50 border border-slate-200 rounded-xl text-sm font-mono focus:outline-none focus:ring-2 focus:ring-blue-500 transition-all resize-none"
|
||||
placeholder="Enter your 12 or 24 word seed phrase..."
|
||||
value={mnemonic}
|
||||
onChange={(e) => setMnemonic(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<PgpKeyInput
|
||||
label="PGP Public Key (Optional)"
|
||||
icon={FileKey}
|
||||
placeholder="-----BEGIN PGP PUBLIC KEY BLOCK----- Paste or drag & drop your public key..."
|
||||
value={pgpKeyInput}
|
||||
onChange={setPgpKeyInput}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-semibold text-slate-700">SEEDPGP1 Payload</label>
|
||||
<textarea
|
||||
className="w-full h-32 p-4 bg-slate-50 border border-slate-200 rounded-xl text-xs font-mono focus:outline-none focus:ring-2 focus:ring-blue-500 transition-all resize-none"
|
||||
placeholder="SEEDPGP1:0:ABCD:..."
|
||||
value={restoreInput}
|
||||
onChange={(e) => setRestoreInput(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<PgpKeyInput
|
||||
label="PGP Private Key (Optional)"
|
||||
icon={FileKey}
|
||||
placeholder="-----BEGIN PGP PRIVATE KEY BLOCK----- Paste or drag & drop your private key..."
|
||||
value={pgpKeyInput}
|
||||
onChange={setPgpKeyInput}
|
||||
/>
|
||||
|
||||
{pgpKeyInput && (
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-bold text-slate-500 uppercase tracking-wider">Private Key Passphrase</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-3 text-slate-400" size={16} />
|
||||
<input
|
||||
type="password"
|
||||
className="w-full pl-10 pr-4 py-2.5 bg-white border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 transition-all"
|
||||
placeholder="Unlock private key..."
|
||||
value={privateKeyPassphrase}
|
||||
onChange={(e) => setPrivateKeyPassphrase(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Security Panel */}
|
||||
<div className="space-y-6">
|
||||
<div className="p-5 bg-gradient-to-br from-slate-50 to-slate-100 rounded-2xl border-2 border-slate-200 shadow-inner space-y-4">
|
||||
<h3 className="text-sm font-bold text-slate-800 uppercase tracking-wider flex items-center gap-2">
|
||||
<Lock size={14} /> Security Options
|
||||
</h3>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-bold text-slate-500 uppercase tracking-wider">Message Password</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-3 text-slate-400" size={16} />
|
||||
<input
|
||||
type="password"
|
||||
className="w-full pl-10 pr-4 py-2.5 bg-white border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 transition-all"
|
||||
placeholder="Optional password..."
|
||||
value={messagePassword}
|
||||
onChange={(e) => setMessagePassword(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-[10px] text-slate-500 mt-1">Symmetric encryption password (SKESK)</p>
|
||||
</div>
|
||||
|
||||
{activeTab === 'backup' && (
|
||||
<div className="pt-3 border-t border-slate-300">
|
||||
<label className="flex items-center gap-2 cursor-pointer group">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={hasBip39Passphrase}
|
||||
onChange={(e) => setHasBip39Passphrase(e.target.checked)}
|
||||
className="rounded text-blue-600 focus:ring-2 focus:ring-blue-500 transition-all"
|
||||
/>
|
||||
<span className="text-xs font-medium text-slate-700 group-hover:text-slate-900 transition-colors">
|
||||
BIP39 25th word active
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Action Button */}
|
||||
{activeTab === 'backup' ? (
|
||||
<button
|
||||
onClick={handleBackup}
|
||||
disabled={!mnemonic || loading}
|
||||
className="w-full py-4 bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-xl font-bold flex items-center justify-center gap-2 hover:from-blue-700 hover:to-blue-800 transition-all shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:from-blue-600 disabled:hover:to-blue-700"
|
||||
>
|
||||
{loading ? (
|
||||
<RefreshCw className="animate-spin" size={20} />
|
||||
) : (
|
||||
<QrCode size={20} />
|
||||
)}
|
||||
{loading ? 'Generating...' : 'Generate QR Backup'}
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={handleRestore}
|
||||
disabled={!restoreInput || loading}
|
||||
className="w-full py-4 bg-gradient-to-r from-slate-800 to-slate-900 text-white rounded-xl font-bold flex items-center justify-center gap-2 hover:from-slate-900 hover:to-black transition-all shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{loading ? (
|
||||
<RefreshCw className="animate-spin" size={20} />
|
||||
) : (
|
||||
<Unlock size={20} />
|
||||
)}
|
||||
{loading ? 'Decrypting...' : 'Decrypt & Restore'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* QR Output */}
|
||||
{qrPayload && activeTab === 'backup' && (
|
||||
<div className="pt-6 border-t border-slate-200 space-y-6 animate-in fade-in slide-in-from-bottom-4">
|
||||
<div className="flex justify-center">
|
||||
<QrDisplay value={qrPayload} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<label className="text-xs font-bold text-slate-500 uppercase tracking-wider">
|
||||
Raw payload (copy for backup)
|
||||
</label>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => copyToClipboard(qrPayload)}
|
||||
className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-slate-900 text-white text-xs font-semibold hover:bg-black transition-colors"
|
||||
>
|
||||
{copied ? <CheckCircle2 size={14} /> : <QrCode size={14} />}
|
||||
{copied ? "Copied" : "Copy"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<textarea
|
||||
readOnly
|
||||
value={qrPayload}
|
||||
onFocus={(e) => e.currentTarget.select()}
|
||||
className="w-full h-28 p-3 bg-slate-900 rounded-xl font-mono text-[10px] text-green-400 border border-slate-700 shadow-inner leading-relaxed resize-none focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
<p className="text-[11px] text-slate-500">
|
||||
Tip: click the box to select all, or use Copy.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Restored Mnemonic */}
|
||||
{restoredData && activeTab === 'restore' && (
|
||||
<div className="pt-6 border-t border-slate-200 animate-in zoom-in-95">
|
||||
<div className="p-6 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} /> Mnemonic Recovered
|
||||
</span>
|
||||
<button
|
||||
onClick={() => setShowMnemonic(!showMnemonic)}
|
||||
className="p-2.5 hover:bg-green-100 rounded-xl transition-all text-green-700 hover:shadow"
|
||||
>
|
||||
{showMnemonic ? <EyeOff size={22} /> : <Eye size={22} />}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className={`p-6 bg-white rounded-xl border-2 border-green-200 shadow-sm transition-all duration-300 ${showMnemonic ? 'blur-0' : 'blur-lg select-none'
|
||||
}`}>
|
||||
<p className="font-mono text-center text-lg text-slate-800 tracking-wide leading-relaxed break-words">
|
||||
{restoredData.w}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{restoredData.pp === 1 && (
|
||||
<div className="mt-4 p-3 bg-orange-100 border border-orange-300 rounded-lg">
|
||||
<p className="text-xs text-center text-orange-800 font-bold uppercase tracking-widest flex items-center justify-center gap-2">
|
||||
<AlertCircle size={14} /> BIP39 Passphrase Required (25th Word)
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{restoredData.fpr && restoredData.fpr.length > 0 && (
|
||||
<div className="mt-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
|
||||
<p className="text-xs text-blue-800">
|
||||
<strong>Encrypted for keys:</strong> {restoredData.fpr.join(', ')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="mt-8 text-center text-xs text-slate-500">
|
||||
<p>SeedPGP v1.1 • OpenPGP (RFC 4880) + Base45 (RFC 9285) + CRC16/CCITT-FALSE</p>
|
||||
<p className="mt-1">Never share your private keys or seed phrases. Always verify on an airgapped device.</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
1
src/assets/react.svg
Normal file
1
src/assets/react.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
84
src/components/PgpKeyInput.tsx
Normal file
84
src/components/PgpKeyInput.tsx
Normal file
@@ -0,0 +1,84 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Upload } from 'lucide-react';
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
interface PgpKeyInputProps {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
placeholder: string;
|
||||
label: string;
|
||||
icon?: LucideIcon;
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
export const PgpKeyInput: React.FC<PgpKeyInputProps> = ({
|
||||
value,
|
||||
onChange,
|
||||
placeholder,
|
||||
label,
|
||||
icon: Icon
|
||||
}) => {
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
|
||||
const handleDragOver = (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(true);
|
||||
};
|
||||
|
||||
const handleDragLeave = (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(false);
|
||||
};
|
||||
|
||||
const handleDrop = (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(false);
|
||||
|
||||
const file = e.dataTransfer.files[0];
|
||||
if (file) {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
if (event.target?.result) {
|
||||
onChange(event.target.result as string);
|
||||
}
|
||||
};
|
||||
reader.readAsText(file);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-semibold text-slate-700 flex items-center justify-between">
|
||||
<span className="flex items-center gap-2">
|
||||
{Icon && <Icon size={14} />} {label}
|
||||
</span>
|
||||
<span className="text-[10px] text-slate-400 font-normal bg-slate-100 px-2 py-0.5 rounded-full border border-slate-200">
|
||||
Drag & Drop .asc file
|
||||
</span>
|
||||
</label>
|
||||
<div
|
||||
className={`relative transition-all duration-200 ${isDragging ? 'scale-[1.01]' : ''}`}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
>
|
||||
<textarea
|
||||
className={`w-full h-40 p-3 bg-slate-50 border rounded-xl text-xs font-mono transition-colors resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 ${isDragging ? 'border-blue-500 bg-blue-50' : 'border-slate-200'
|
||||
}`}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
{isDragging && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-blue-50/90 rounded-xl border-2 border-dashed border-blue-500 pointer-events-none z-10">
|
||||
<div className="text-blue-600 font-bold flex flex-col items-center animate-bounce">
|
||||
<Upload size={24} />
|
||||
<span className="text-sm mt-2">Drop Key File Here</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
31
src/components/QrDisplay.tsx
Normal file
31
src/components/QrDisplay.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import QRCode from 'qrcode';
|
||||
|
||||
interface QrDisplayProps {
|
||||
value: string;
|
||||
}
|
||||
|
||||
export const QrDisplay: React.FC<QrDisplayProps> = ({ value }) => {
|
||||
const [dataUrl, setDataUrl] = useState<string>('');
|
||||
|
||||
useEffect(() => {
|
||||
if (value) {
|
||||
QRCode.toDataURL(value, {
|
||||
errorCorrectionLevel: 'Q',
|
||||
type: 'image/png',
|
||||
width: 512,
|
||||
margin: 2,
|
||||
})
|
||||
.then(setDataUrl)
|
||||
.catch(console.error);
|
||||
}
|
||||
}, [value]);
|
||||
|
||||
if (!dataUrl) return null;
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-center p-4 bg-white rounded-xl border-2 border-slate-200">
|
||||
<img src={dataUrl} alt="SeedPGP QR Code" className="w-64 h-64" />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
17
src/index.css
Normal file
17
src/index.css
Normal file
@@ -0,0 +1,17 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
|
||||
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
|
||||
sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
|
||||
monospace;
|
||||
}
|
||||
62
src/lib/base45.ts
Normal file
62
src/lib/base45.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
// RFC 9285 Base45 encoding (strict)
|
||||
const ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
|
||||
|
||||
const idx = (() => {
|
||||
const m = new Map<string, number>();
|
||||
for (let i = 0; i < ALPHABET.length; i++) m.set(ALPHABET[i], i);
|
||||
return m;
|
||||
})();
|
||||
|
||||
export function base45Encode(bytes: Uint8Array): string {
|
||||
let out = "";
|
||||
for (let i = 0; i < bytes.length; i += 2) {
|
||||
if (i + 1 < bytes.length) {
|
||||
const x = bytes[i] * 256 + bytes[i + 1];
|
||||
const c = x % 45;
|
||||
const d = Math.floor(x / 45) % 45;
|
||||
const e = Math.floor(x / (45 * 45));
|
||||
out += ALPHABET[c] + ALPHABET[d] + ALPHABET[e];
|
||||
} else {
|
||||
const x = bytes[i];
|
||||
const c = x % 45;
|
||||
const d = Math.floor(x / 45);
|
||||
out += ALPHABET[c] + ALPHABET[d];
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function base45Decode(text: string): Uint8Array {
|
||||
if (!text.length) return new Uint8Array();
|
||||
|
||||
for (const ch of text) {
|
||||
if (!idx.has(ch)) {
|
||||
throw new Error(`Base45 decode: invalid character '${ch}' (position ${text.indexOf(ch)})`);
|
||||
}
|
||||
}
|
||||
|
||||
if (text.length % 3 === 1) {
|
||||
throw new Error("Base45 decode: invalid length (length mod 3 == 1)");
|
||||
}
|
||||
|
||||
const out: number[] = [];
|
||||
for (let i = 0; i < text.length;) {
|
||||
const remaining = text.length - i;
|
||||
if (remaining >= 3) {
|
||||
const c = idx.get(text[i++])!;
|
||||
const d = idx.get(text[i++])!;
|
||||
const e = idx.get(text[i++])!;
|
||||
const x = c + d * 45 + e * 45 * 45;
|
||||
if (x > 0xffff) throw new Error("Base45 decode: value overflow in 3-tuple");
|
||||
out.push((x >> 8) & 0xff, x & 0xff);
|
||||
} else {
|
||||
const c = idx.get(text[i++])!;
|
||||
const d = idx.get(text[i++])!;
|
||||
const x = c + d * 45;
|
||||
if (x > 0xff) throw new Error("Base45 decode: value overflow in 2-tuple");
|
||||
out.push(x);
|
||||
}
|
||||
}
|
||||
|
||||
return new Uint8Array(out);
|
||||
}
|
||||
24
src/lib/bip39.ts
Normal file
24
src/lib/bip39.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
// Prototype-level BIP39 validation:
|
||||
// - enforces allowed word counts
|
||||
// - normalizes whitespace/case
|
||||
// NOTE: checksum + wordlist membership verification is intentionally omitted here.
|
||||
|
||||
export function normalizeBip39Mnemonic(words: string): string {
|
||||
return words.trim().toLowerCase().replace(/\s+/g, " ");
|
||||
}
|
||||
|
||||
export function validateBip39Mnemonic(words: string): { valid: boolean; error?: string } {
|
||||
const normalized = normalizeBip39Mnemonic(words);
|
||||
const arr = normalized.length ? normalized.split(" ") : [];
|
||||
|
||||
const validCounts = new Set([12, 15, 18, 21, 24]);
|
||||
if (!validCounts.has(arr.length)) {
|
||||
return {
|
||||
valid: false,
|
||||
error: `Invalid word count: ${arr.length}. Must be 12, 15, 18, 21, or 24.`,
|
||||
};
|
||||
}
|
||||
|
||||
// In production: verify each word is in the selected wordlist + verify checksum.
|
||||
return { valid: true };
|
||||
}
|
||||
12
src/lib/crc16.ts
Normal file
12
src/lib/crc16.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
// CRC-16/CCITT-FALSE: poly 0x1021, init 0xFFFF, xorout 0x0000, refin/refout false
|
||||
export function crc16CcittFalse(data: Uint8Array): string {
|
||||
let crc = 0xffff;
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
crc ^= data[i] << 8;
|
||||
for (let j = 0; j < 8; j++) {
|
||||
crc = (crc & 0x8000) ? ((crc << 1) ^ 0x1021) : (crc << 1);
|
||||
crc &= 0xffff;
|
||||
}
|
||||
}
|
||||
return crc.toString(16).toUpperCase().padStart(4, "0");
|
||||
}
|
||||
249
src/lib/seedpgp.test.ts
Normal file
249
src/lib/seedpgp.test.ts
Normal file
@@ -0,0 +1,249 @@
|
||||
import { describe, test, expect, beforeAll } from "bun:test";
|
||||
import { encryptToSeedPgp, decryptSeedPgp, buildPlaintext } from "./seedpgp";
|
||||
import * as openpgp from "openpgp";
|
||||
|
||||
// Official BIP39 test vectors from Trezor
|
||||
const TREZOR_VECTORS = [
|
||||
{
|
||||
name: "12-word all zeros",
|
||||
mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
|
||||
},
|
||||
{
|
||||
name: "12-word all 0x7f",
|
||||
mnemonic: "legal winner thank year wave sausage worth useful legal winner thank yellow",
|
||||
},
|
||||
{
|
||||
name: "12-word all 0x80",
|
||||
mnemonic: "letter advice cage absurd amount doctor acoustic avoid letter advice cage above",
|
||||
},
|
||||
{
|
||||
name: "12-word all 0xff",
|
||||
mnemonic: "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong",
|
||||
},
|
||||
{
|
||||
name: "18-word all zeros",
|
||||
mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon agent",
|
||||
},
|
||||
{
|
||||
name: "24-word all zeros",
|
||||
mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",
|
||||
},
|
||||
{
|
||||
name: "24-word random entropy",
|
||||
mnemonic: "hamster diagram private dutch cause delay private meat slide toddler razor book happy fancy gospel tennis maple dilemma loan word shrug inflict delay length",
|
||||
},
|
||||
{
|
||||
name: "12-word random entropy",
|
||||
mnemonic: "scheme spot photo card baby mountain device kick cradle pact join borrow",
|
||||
},
|
||||
];
|
||||
|
||||
// Your existing tests
|
||||
describe("seedpgp test vectors", () => {
|
||||
let testPublicKey: string;
|
||||
let testPrivateKey: string;
|
||||
const testPassphrase = "test-passphrase-123";
|
||||
|
||||
beforeAll(async () => {
|
||||
const { privateKey, publicKey } = await openpgp.generateKey({
|
||||
type: "ecc",
|
||||
curve: "curve25519Legacy",
|
||||
userIDs: [{ name: "Test User", email: "test@example.com" }],
|
||||
passphrase: testPassphrase,
|
||||
format: "armored",
|
||||
});
|
||||
|
||||
testPublicKey = publicKey;
|
||||
testPrivateKey = privateKey;
|
||||
});
|
||||
|
||||
test("vector 1: standard 24-word mnemonic", async () => {
|
||||
const mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art";
|
||||
|
||||
const plaintext = buildPlaintext(mnemonic, false);
|
||||
|
||||
const encrypted = await encryptToSeedPgp({
|
||||
plaintext,
|
||||
publicKeyArmored: testPublicKey,
|
||||
});
|
||||
|
||||
const decrypted = await decryptSeedPgp({
|
||||
frameText: encrypted.framed,
|
||||
privateKeyArmored: testPrivateKey,
|
||||
privateKeyPassphrase: testPassphrase,
|
||||
});
|
||||
|
||||
expect(decrypted.v).toBe(1);
|
||||
expect(decrypted.t).toBe("bip39");
|
||||
expect(decrypted.l).toBe("en");
|
||||
expect(decrypted.w).toBe(mnemonic);
|
||||
expect(decrypted.pp).toBe(0);
|
||||
});
|
||||
|
||||
test("vector 2: 12-word mnemonic", async () => {
|
||||
const mnemonic = "legal winner thank year wave sausage worth useful legal winner thank yellow";
|
||||
|
||||
const plaintext = buildPlaintext(mnemonic, false);
|
||||
|
||||
const encrypted = await encryptToSeedPgp({
|
||||
plaintext,
|
||||
publicKeyArmored: testPublicKey,
|
||||
});
|
||||
|
||||
const decrypted = await decryptSeedPgp({
|
||||
frameText: encrypted.framed,
|
||||
privateKeyArmored: testPrivateKey,
|
||||
privateKeyPassphrase: testPassphrase,
|
||||
});
|
||||
|
||||
expect(decrypted.w).toBe(mnemonic);
|
||||
});
|
||||
|
||||
test("vector 3: mnemonic with BIP39 passphrase flag", async () => {
|
||||
const mnemonic = "test wallet seed phrase example only do not use real funds";
|
||||
|
||||
const plaintext = buildPlaintext(mnemonic, true);
|
||||
|
||||
const encrypted = await encryptToSeedPgp({
|
||||
plaintext,
|
||||
publicKeyArmored: testPublicKey,
|
||||
});
|
||||
|
||||
expect(encrypted.framed).toContain("SEEDPGP1:");
|
||||
expect(encrypted.recipientFingerprint).toBeDefined();
|
||||
|
||||
const decrypted = await decryptSeedPgp({
|
||||
frameText: encrypted.framed,
|
||||
privateKeyArmored: testPrivateKey,
|
||||
privateKeyPassphrase: testPassphrase,
|
||||
});
|
||||
|
||||
expect(decrypted.w).toBe(mnemonic);
|
||||
expect(decrypted.pp).toBe(1);
|
||||
});
|
||||
|
||||
test("vector 4: reject wrong private key", async () => {
|
||||
const mnemonic = "test seed phrase";
|
||||
const plaintext = buildPlaintext(mnemonic, false);
|
||||
|
||||
const { privateKey: wrongKey } = await openpgp.generateKey({
|
||||
type: "ecc",
|
||||
curve: "curve25519Legacy",
|
||||
userIDs: [{ name: "Wrong User", email: "wrong@example.com" }],
|
||||
passphrase: "wrong-pw",
|
||||
format: "armored",
|
||||
});
|
||||
|
||||
const encrypted = await encryptToSeedPgp({
|
||||
plaintext,
|
||||
publicKeyArmored: testPublicKey,
|
||||
});
|
||||
|
||||
await expect(
|
||||
decryptSeedPgp({
|
||||
frameText: encrypted.framed,
|
||||
privateKeyArmored: wrongKey,
|
||||
privateKeyPassphrase: "wrong-pw",
|
||||
})
|
||||
).rejects.toThrow(/not encrypted to the provided private key/);
|
||||
});
|
||||
|
||||
test("vector 5: reject invalid passphrase", async () => {
|
||||
const mnemonic = "test seed phrase";
|
||||
const plaintext = buildPlaintext(mnemonic, false);
|
||||
|
||||
const encrypted = await encryptToSeedPgp({
|
||||
plaintext,
|
||||
publicKeyArmored: testPublicKey,
|
||||
});
|
||||
|
||||
await expect(
|
||||
decryptSeedPgp({
|
||||
frameText: encrypted.framed,
|
||||
privateKeyArmored: testPrivateKey,
|
||||
privateKeyPassphrase: "wrong-passphrase",
|
||||
})
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
test("vector 6: frame format validation", async () => {
|
||||
const mnemonic = "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong";
|
||||
const plaintext = buildPlaintext(mnemonic, false);
|
||||
|
||||
const encrypted = await encryptToSeedPgp({
|
||||
plaintext,
|
||||
publicKeyArmored: testPublicKey,
|
||||
});
|
||||
|
||||
const parts = encrypted.framed.split(":");
|
||||
expect(parts[0]).toBe("SEEDPGP1");
|
||||
expect(parts[1]).toBe("0");
|
||||
expect(parts[2]).toMatch(/^[0-9A-F]{4}$/);
|
||||
expect(parts.length).toBeGreaterThanOrEqual(4);
|
||||
});
|
||||
});
|
||||
|
||||
// NEW: Add the Trezor vectors as a second describe block
|
||||
describe("BIP39 Trezor test vectors", () => {
|
||||
let testPublicKey: string;
|
||||
let testPrivateKey: string;
|
||||
const testPassphrase = "test-passphrase-123";
|
||||
|
||||
beforeAll(async () => {
|
||||
const { privateKey, publicKey } = await openpgp.generateKey({
|
||||
type: "ecc",
|
||||
curve: "curve25519Legacy",
|
||||
userIDs: [{ name: "Test User", email: "test@example.com" }],
|
||||
passphrase: testPassphrase,
|
||||
format: "armored",
|
||||
});
|
||||
|
||||
testPublicKey = publicKey;
|
||||
testPrivateKey = privateKey;
|
||||
});
|
||||
|
||||
TREZOR_VECTORS.forEach(({ name, mnemonic }) => {
|
||||
test(`${name}`, async () => {
|
||||
const plaintext = buildPlaintext(mnemonic, false);
|
||||
|
||||
const encrypted = await encryptToSeedPgp({
|
||||
plaintext,
|
||||
publicKeyArmored: testPublicKey,
|
||||
});
|
||||
|
||||
expect(encrypted.framed).toMatch(/^SEEDPGP1:0:[0-9A-F]{4}:.+$/);
|
||||
expect(encrypted.recipientFingerprint).toBeDefined();
|
||||
|
||||
const decrypted = await decryptSeedPgp({
|
||||
frameText: encrypted.framed,
|
||||
privateKeyArmored: testPrivateKey,
|
||||
privateKeyPassphrase: testPassphrase,
|
||||
});
|
||||
|
||||
expect(decrypted.v).toBe(1);
|
||||
expect(decrypted.t).toBe("bip39");
|
||||
expect(decrypted.l).toBe("en");
|
||||
expect(decrypted.pp).toBe(0);
|
||||
expect(decrypted.w).toBe(mnemonic);
|
||||
});
|
||||
});
|
||||
|
||||
test("with BIP39 passphrase flag", async () => {
|
||||
const mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
|
||||
const plaintext = buildPlaintext(mnemonic, true);
|
||||
|
||||
const encrypted = await encryptToSeedPgp({
|
||||
plaintext,
|
||||
publicKeyArmored: testPublicKey,
|
||||
});
|
||||
|
||||
const decrypted = await decryptSeedPgp({
|
||||
frameText: encrypted.framed,
|
||||
privateKeyArmored: testPrivateKey,
|
||||
privateKeyPassphrase: testPassphrase,
|
||||
});
|
||||
|
||||
expect(decrypted.w).toBe(mnemonic);
|
||||
expect(decrypted.pp).toBe(1);
|
||||
});
|
||||
});
|
||||
190
src/lib/seedpgp.ts
Normal file
190
src/lib/seedpgp.ts
Normal file
@@ -0,0 +1,190 @@
|
||||
import * as openpgp from "openpgp";
|
||||
import { base45Encode, base45Decode } from "./base45";
|
||||
import { crc16CcittFalse } from "./crc16";
|
||||
import type { SeedPgpPlaintext, ParsedSeedPgpFrame } from "./types";
|
||||
|
||||
function nonEmptyTrimmed(s?: string): string | undefined {
|
||||
if (!s) return undefined;
|
||||
const t = s.trim();
|
||||
return t.length ? t : undefined;
|
||||
}
|
||||
|
||||
export function normalizeMnemonic(words: string): string {
|
||||
return words.trim().toLowerCase().replace(/\s+/g, " ");
|
||||
}
|
||||
|
||||
export function buildPlaintext(
|
||||
mnemonic: string,
|
||||
bip39PassphraseUsed: boolean,
|
||||
recipientFingerprints?: string[]
|
||||
): SeedPgpPlaintext {
|
||||
const plain: SeedPgpPlaintext = {
|
||||
v: 1,
|
||||
t: "bip39",
|
||||
w: normalizeMnemonic(mnemonic),
|
||||
l: "en",
|
||||
pp: bip39PassphraseUsed ? 1 : 0,
|
||||
};
|
||||
if (recipientFingerprints && recipientFingerprints.length > 0) {
|
||||
plain.fpr = recipientFingerprints;
|
||||
}
|
||||
return plain;
|
||||
}
|
||||
|
||||
export function frameEncode(pgpBinary: Uint8Array): string {
|
||||
const crc = crc16CcittFalse(pgpBinary);
|
||||
const b45 = base45Encode(pgpBinary);
|
||||
return `SEEDPGP1:0:${crc}:${b45}`;
|
||||
}
|
||||
|
||||
export function frameParse(text: string): ParsedSeedPgpFrame {
|
||||
const s = text.trim().replace(/^["']|["']$/g, "").replace(/[\n\r\t]/g, "");
|
||||
if (!s.startsWith("SEEDPGP1:")) throw new Error("Missing SEEDPGP1: prefix");
|
||||
|
||||
const parts = s.split(":");
|
||||
if (parts.length < 4) {
|
||||
throw new Error("Invalid frame format (need at least 4 colon-separated parts)");
|
||||
}
|
||||
|
||||
const prefix = parts[0];
|
||||
const frame = parts[1];
|
||||
const crc16 = parts[2].toUpperCase();
|
||||
const b45 = parts.slice(3).join(":");
|
||||
|
||||
if (prefix !== "SEEDPGP1") throw new Error("Invalid prefix");
|
||||
if (frame !== "0") throw new Error("Multipart frames not supported in this prototype");
|
||||
if (!/^[0-9A-F]{4}$/.test(crc16)) throw new Error("Invalid CRC16 format (must be 4 hex chars)");
|
||||
|
||||
return { kind: "single", crc16, b45 };
|
||||
}
|
||||
|
||||
export function frameDecodeToPgpBytes(frameText: string): Uint8Array {
|
||||
const f = frameParse(frameText);
|
||||
const pgp = base45Decode(f.b45);
|
||||
const crc = crc16CcittFalse(pgp);
|
||||
if (crc !== f.crc16) {
|
||||
throw new Error(`CRC16 mismatch! Expected: ${f.crc16}, Got: ${crc}. QR scan may be corrupted.`);
|
||||
}
|
||||
return pgp;
|
||||
}
|
||||
|
||||
export async function encryptToSeedPgp(params: {
|
||||
plaintext: SeedPgpPlaintext;
|
||||
publicKeyArmored?: string;
|
||||
messagePassword?: string;
|
||||
}): Promise<{ framed: string; pgpBytes: Uint8Array; recipientFingerprint?: string }> {
|
||||
const pub = nonEmptyTrimmed(params.publicKeyArmored);
|
||||
const pw = nonEmptyTrimmed(params.messagePassword);
|
||||
|
||||
if (!pub && !pw) {
|
||||
throw new Error("Provide either a PGP public key or a message password (or both).");
|
||||
}
|
||||
|
||||
let encryptionKeys: openpgp.PublicKey[] = [];
|
||||
let recipientFingerprint: string | undefined;
|
||||
|
||||
if (pub) {
|
||||
const pubKey = await openpgp.readKey({ armoredKey: pub });
|
||||
try {
|
||||
await pubKey.getEncryptionKey();
|
||||
} catch {
|
||||
throw new Error("This public key has no usable encryption subkey (E).");
|
||||
}
|
||||
|
||||
recipientFingerprint = pubKey.getFingerprint().toUpperCase();
|
||||
encryptionKeys = [pubKey];
|
||||
}
|
||||
|
||||
const message = await openpgp.createMessage({ text: JSON.stringify(params.plaintext) });
|
||||
|
||||
const encrypted = await openpgp.encrypt({
|
||||
message,
|
||||
encryptionKeys,
|
||||
passwords: pw ? [pw] : [],
|
||||
format: "binary",
|
||||
config: {
|
||||
preferredSymmetricAlgorithm: openpgp.enums.symmetric.aes256,
|
||||
},
|
||||
});
|
||||
|
||||
const pgpBytes = new Uint8Array(encrypted as Uint8Array);
|
||||
return { framed: frameEncode(pgpBytes), pgpBytes, recipientFingerprint };
|
||||
}
|
||||
|
||||
export async function decryptSeedPgp(params: {
|
||||
frameText: string;
|
||||
privateKeyArmored?: string;
|
||||
privateKeyPassphrase?: string;
|
||||
messagePassword?: string;
|
||||
}): Promise<SeedPgpPlaintext> {
|
||||
const pgpBytes = frameDecodeToPgpBytes(params.frameText);
|
||||
const message = await openpgp.readMessage({ binaryMessage: pgpBytes });
|
||||
const encKeyIds: openpgp.KeyID[] = message.getEncryptionKeyIDs?.() ?? [];
|
||||
|
||||
const privArmored = nonEmptyTrimmed(params.privateKeyArmored);
|
||||
const privPw = nonEmptyTrimmed(params.privateKeyPassphrase);
|
||||
const msgPw = nonEmptyTrimmed(params.messagePassword);
|
||||
|
||||
let decryptionKeys: openpgp.PrivateKey[] = [];
|
||||
|
||||
if (privArmored) {
|
||||
let privKey = await openpgp.readPrivateKey({ armoredKey: privArmored });
|
||||
|
||||
if (!privKey.isDecrypted()) {
|
||||
if (!privPw) {
|
||||
throw new Error("Private key is still locked. Enter the private key passphrase.");
|
||||
}
|
||||
privKey = await openpgp.decryptKey({ privateKey: privKey, passphrase: privPw });
|
||||
if (!privKey.isDecrypted()) {
|
||||
throw new Error("Private key passphrase incorrect (key still locked).");
|
||||
}
|
||||
}
|
||||
|
||||
// Preflight: validate the private key matches a recipient
|
||||
if (encKeyIds.length) {
|
||||
const dec = await privKey.getDecryptionKeys();
|
||||
const decArr = Array.isArray(dec) ? dec : [dec];
|
||||
const decKeyIds = decArr.map((k: any) => k.getKeyID().toHex().toUpperCase());
|
||||
const want = new Set(encKeyIds.map((kid: openpgp.KeyID) => kid.toHex().toUpperCase()));
|
||||
const matched = decKeyIds.some((id: string) => want.has(id));
|
||||
|
||||
if (!matched) {
|
||||
throw new Error(
|
||||
"This payload is not encrypted to the provided private key (no matching recipient KeyID)."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
decryptionKeys = [privKey];
|
||||
}
|
||||
|
||||
let decryptResult;
|
||||
try {
|
||||
const decryptOptions: any = {
|
||||
message,
|
||||
format: "utf8",
|
||||
};
|
||||
|
||||
if (decryptionKeys.length > 0) {
|
||||
decryptOptions.decryptionKeys = decryptionKeys;
|
||||
}
|
||||
|
||||
if (msgPw) {
|
||||
decryptOptions.passwords = [msgPw];
|
||||
}
|
||||
|
||||
decryptResult = await openpgp.decrypt(decryptOptions);
|
||||
} catch (err: any) {
|
||||
console.error("SeedPGP: decrypt failed:", err.message);
|
||||
throw err;
|
||||
}
|
||||
|
||||
const { data } = decryptResult;
|
||||
const obj = JSON.parse(data as string) as SeedPgpPlaintext;
|
||||
|
||||
if (obj.v !== 1) throw new Error(`Unsupported version: ${obj.v}`);
|
||||
if (obj.t !== "bip39") throw new Error(`Unsupported type: ${obj.t}`);
|
||||
if (obj.l !== "en") throw new Error(`Unsupported language: ${obj.l}`);
|
||||
|
||||
return obj;
|
||||
}
|
||||
14
src/lib/types.ts
Normal file
14
src/lib/types.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
export type SeedPgpPlaintext = {
|
||||
v: 1;
|
||||
t: "bip39";
|
||||
w: string;
|
||||
l: "en";
|
||||
pp: 0 | 1;
|
||||
fpr?: string[];
|
||||
};
|
||||
|
||||
export type ParsedSeedPgpFrame = {
|
||||
kind: "single";
|
||||
crc16: string;
|
||||
b45: string;
|
||||
};
|
||||
10
src/main.tsx
Normal file
10
src/main.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
Reference in New Issue
Block a user