v1.34.0: leer QR con la cámara
Botón ⌗ QR junto a cada campo (direcciones, URI de pago, txid, xpub, PSBT, tx en crudo). Enseña lo leído y pide confirmar. Rechaza semillas y claves privadas sin mostrarlas. Foto de respaldo sin cámara en directo. Librería qr 0.7.2 (Paul Miller) en vendor/qr/, con su huella en SETUP. Pruebas en tests/test22.js. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L5npnUYgSPkAaHkdaeUqBr
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
// ── QR: lógica pura (probada en tests/test22.js) ───────────────────────
|
||||
// Qué es lo que se ha leído en un QR y si encaja en el campo donde se
|
||||
// quiere usar. Nada de esto toca la red ni guarda nada: solo mira texto.
|
||||
//
|
||||
// Lo primero es SIEMPRE descartar secretos. Es fácil escanear sin querer
|
||||
// la tarjeta SeedQR del SeedSigner o una clave privada: Txoko no los
|
||||
// necesita nunca, así que ni se muestran ni se guardan.
|
||||
const QR_SEMILLA_PALABRAS = new Set([12, 15, 18, 21, 24]);
|
||||
function pareceSecretoQR(texto) {
|
||||
const s = String(texto ?? "");
|
||||
const t = s.trim();
|
||||
// SeedQR (estándar): 4 dígitos por palabra → 48 (12 palabras) a 96 (24).
|
||||
if (/^\d+$/.test(t) && t.length >= 48 && t.length <= 96 && t.length % 4 === 0) return true;
|
||||
// Semilla en palabras (BIP-39 completa o con las 4 primeras letras).
|
||||
const palabras = t.toLowerCase().split(/\s+/);
|
||||
if (QR_SEMILLA_PALABRAS.has(palabras.length) && palabras.every(p => /^[a-z]{3,8}$/.test(p))) return true;
|
||||
// CompactSeedQR: 16 o 32 bytes en binario (llegan como caracteres de control).
|
||||
if ((s.length === 16 || s.length === 32) && /[\u0000-\u0008\u000e-\u001f\u007f-ÿ]/.test(s)) return true;
|
||||
// Clave privada extendida (xprv, yprv, zprv, tprv…) o clave privada WIF.
|
||||
if (/[xyztuvXYZUV]prv[1-9A-HJ-NP-Za-km-z]{100,}/.test(t)) return true;
|
||||
if (/^[5KLc9][1-9A-HJ-NP-Za-km-z]{50,51}$/.test(t)) return true;
|
||||
return false;
|
||||
}
|
||||
// Las direcciones bech32 suelen ir en mayúsculas dentro del QR (ocupan
|
||||
// menos); en minúsculas son la misma dirección.
|
||||
const normalizarDireccionQR = d => /^(bc1|tb1|bcrt1)/i.test(d) ? d.toLowerCase() : d;
|
||||
const esDireccionQR = d => /^(bc1|tb1|bcrt1)[02-9ac-hj-np-z]{8,87}$/.test(d) || /^[13mn2][1-9A-HJ-NP-Za-km-z]{25,34}$/.test(d);
|
||||
const QR_XPUB = "[xyzXYZtuvUV]pub[1-9A-HJ-NP-Za-km-z]{100,112}";
|
||||
function clasificarQR(texto) {
|
||||
const crudo = String(texto ?? "");
|
||||
if (pareceSecretoQR(crudo)) return { tipo: "secreto" };
|
||||
const t = crudo.trim();
|
||||
if (!t) return { tipo: "vacio" };
|
||||
// URI de pago (BIP-21): bitcoin:<dirección>?amount=…&label=…
|
||||
const uri = t.match(/^bitcoin:([^?]+)(?:\?(.*))?$/i);
|
||||
if (uri) {
|
||||
const dir = normalizarDireccionQR(uri[1]);
|
||||
if (!esDireccionQR(dir)) return { tipo: "desconocido" };
|
||||
let importe = null, etiqueta = null;
|
||||
try { const p = new URLSearchParams(uri[2] || ""); importe = p.get("amount"); etiqueta = p.get("label"); } catch {}
|
||||
return { tipo: "direccion", valor: dir, importe, etiqueta };
|
||||
}
|
||||
if (/^lightning:|^ln(bc|tb|bcrt)\d*[a-z]?1/i.test(t)) return { tipo: "lightning" };
|
||||
// QR animados (varias partes): UR (Sparrow, SeedSigner), BBQr (Coldcard,
|
||||
// Sparrow…) y el antiguo de Specter. Se reconocen; leerlos es la fase 2.
|
||||
if (/^ur:/i.test(t)) { const m = t.match(/^ur:([a-z0-9-]+)\//i); return { tipo: "ur", urTipo: m ? m[1].toLowerCase() : null }; }
|
||||
if (/^B\$[2HZ][A-Z][0-9A-Z]{4}/.test(t)) return { tipo: "bbqr", archivo: t[3] };
|
||||
if (/^p\d+of\d+\s/i.test(t)) return { tipo: "specter" };
|
||||
if (/^cHNidP8/.test(t) || /^70736274ff/i.test(t)) return { tipo: "psbt", valor: t };
|
||||
// xpub suelta o como la muestra SeedSigner: [huella/ruta]zpub…
|
||||
const xp = t.match(new RegExp(`^(?:\\[([0-9a-fA-F]{8})((?:/\\d+[h']?)*)\\])?(${QR_XPUB})$`));
|
||||
if (xp) return { tipo: "xpub", valor: xp[3], huella: xp[1] ? xp[1].toLowerCase() : null, ruta: xp[2] ? "m" + xp[2] : null };
|
||||
// Descriptor con una xpub dentro: wpkh([…]xpub…/0/*)
|
||||
const desc = t.match(new RegExp(`^(?:wpkh|sh|pkh|tr|wsh)\\(.*?(${QR_XPUB})`));
|
||||
if (desc) return { tipo: "xpub", valor: desc[1], huella: null, ruta: null, descriptor: true };
|
||||
if (/^[0-9a-fA-F]{64}$/.test(t)) return { tipo: "txid", valor: t.toLowerCase() };
|
||||
if (/^0[1-3]000000[0-9a-fA-F]{100,}$/.test(t) && t.length % 2 === 0) return { tipo: "tx", valor: t.toLowerCase() };
|
||||
const dir = normalizarDireccionQR(t);
|
||||
if (esDireccionQR(dir)) return { tipo: "direccion", valor: dir };
|
||||
return { tipo: "desconocido" };
|
||||
}
|
||||
// Qué acepta cada campo de la app.
|
||||
const QR_CAMPOS = {
|
||||
txid: ["txid"],
|
||||
direccion: ["direccion"],
|
||||
busqueda: ["txid", "direccion"],
|
||||
xpub: ["xpub"],
|
||||
psbt: ["psbt"],
|
||||
tx: ["tx"],
|
||||
};
|
||||
const QR_NOMBRE = {
|
||||
direccion: "una dirección", txid: "un identificador de transacción (txid)", xpub: "una clave pública extendida (xpub)",
|
||||
psbt: "una PSBT", tx: "una transacción en crudo", lightning: "una factura de Lightning",
|
||||
ur: "un QR animado (UR)", bbqr: "un QR animado (BBQr)", specter: "un QR animado (Specter)",
|
||||
vacio: "un QR vacío", desconocido: "algo que Txoko no reconoce",
|
||||
};
|
||||
function encajaQR(r, campo) {
|
||||
const acepta = QR_CAMPOS[campo] || [];
|
||||
if (!r || r.tipo === "secreto") return { ok: false, mensaje: "" };
|
||||
if (acepta.includes(r.tipo)) return { ok: true, mensaje: "" };
|
||||
const espera = acepta.map(a => QR_NOMBRE[a]).join(" o ");
|
||||
if (["ur", "bbqr", "specter"].includes(r.tipo))
|
||||
return { ok: false, mensaje: `Es ${QR_NOMBRE[r.tipo]}, de los que pasan varias imágenes seguidas. Txoko todavía no lee QR animados. Mientras tanto, guarda la PSBT como archivo y ábrela con «…o abrir archivo .psbt».` };
|
||||
return { ok: false, mensaje: `Has leído ${QR_NOMBRE[r.tipo] || QR_NOMBRE.desconocido}, pero aquí va ${espera}.` };
|
||||
}
|
||||
// Bytes del QR → texto. Si son 16 o 32 bytes que no son texto, es una
|
||||
// CompactSeedQR: se devuelve algo que pareceSecretoQR reconoce, sin
|
||||
// convertir la semilla en texto legible.
|
||||
function textoDeBytesQR(bytes) {
|
||||
const imprimible = Array.from(bytes).every(b => b >= 0x20 && b <= 0x7e || b === 0x0a || b === 0x0d || b === 0x09);
|
||||
if ((bytes.length === 16 || bytes.length === 32) && !imprimible) return "\u0001".repeat(bytes.length);
|
||||
try { return new TextDecoder("utf-8", { fatal: true }).decode(bytes); }
|
||||
catch { return Array.from(bytes, b => String.fromCharCode(b)).join(""); }
|
||||
}
|
||||
// ── fin QR ──────────────────────────────────────────────────────────────
|
||||
Reference in New Issue
Block a user