v1.48.0: auditoría en frío, parche 1 — guarda de red única, secretos en todos los campos, garantías sin comprobar
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L5npnUYgSPkAaHkdaeUqBr
This commit is contained in:
@@ -23,5 +23,9 @@ if (s === -1 || e === -1) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
module.exports = new Function(lines.slice(s, e).join("\n") +
|
||||
"\nreturn { B32, SECP, deriveChildPubkey, ripemd160, hash160, toBech32, deriveAddresses, XPUB_VERSIONS, TIPO_SCRIPT, descriptorChecksum, contieneClavePrivada, analizarLineaDescriptor, analizarEntradaWallet };")();
|
||||
// La lista BIP-39 (07-palabras-bip39.js) va delante: la usa esSecretoTexto.
|
||||
const s39 = lines.findIndex(l => l.includes("// ── Lista oficial de palabras BIP-39"));
|
||||
const e39 = lines.findIndex((l, i) => i > s39 && l.includes("// ── fin BIP-39"));
|
||||
if (s39 === -1 || e39 === -1) { console.error("No se localiza la lista BIP-39"); process.exit(1); }
|
||||
module.exports = new Function(lines.slice(s39, e39).join("\n") + "\n" + lines.slice(s, e).join("\n") +
|
||||
"\nreturn { B32, SECP, deriveChildPubkey, ripemd160, hash160, toBech32, deriveAddresses, XPUB_VERSIONS, TIPO_SCRIPT, descriptorChecksum, contieneClavePrivada, esSecretoTexto, contieneSemilla, BIP39_PALABRAS, analizarLineaDescriptor, analizarEntradaWallet };")();
|
||||
|
||||
@@ -173,6 +173,19 @@ console.log("\n=== 9. Informe pericial desde el peritaje a demanda ===\n");
|
||||
ok("el contexto no da órdenes (genera, revisa, traslada, ten claro, no lo subas…)", !/\b(genera|revisa|traslada|ten claro|no lo subas|no compartas|no reutilices)\b/i.test(textos), textos.match(/\b(genera|revisa|traslada|ten claro|no lo subas|no compartas|no reutilices)\b/i)?.[0]);
|
||||
ok("sigue avisando de las falsas «recuperaciones» si hay declaración", rep.recommendations.some(r => r.fixed && /segunda estafa/.test(r.text)));
|
||||
}
|
||||
{
|
||||
// v1.48.0 (auditoría A6-03): si la vigilancia vuelve a comprobar una salida
|
||||
// «sin gastar» y la consulta falla, el informe nuevo ya no la da como HECHO.
|
||||
const sinGastar = [...per.gastos].filter(([, g]) => g.estado === "sin_gastar");
|
||||
const [clave, g] = sinGastar[0];
|
||||
const copia = { ...per, gastos: new Map(per.gastos) };
|
||||
copia.gastos.set(clave, { ...g, comprobado: 1700000000, ultimoFallo: { fecha: 1700090000, err: "el nodo respondió HTTP 503" } });
|
||||
const rep = P.buildForensicReport(P.grafoDesdePeritaje(copia), null);
|
||||
ok("[A6-03] vigilancia fallida después: esa salida sale de «fondos sin gastar» (HECHO)…", rep.unspentFunds.length === sinGastar.length - 1, rep.unspentFunds.length);
|
||||
ok("[A6-03] …y pasa a «sin comprobar», diciendo cuándo se vio y que después falló", rep.failedBranches.some(b => `${b.txid}:${b.vout}` === clave && /falló \(el nodo respondió HTTP 503\)/.test(b.note)), rep.failedBranches.map(b => b.note));
|
||||
copia.gastos.set(clave, { ...g, comprobado: 1700100000, ultimoFallo: { fecha: 1700090000, err: "timeout" } });
|
||||
ok("[A6-03] si después hay una comprobación buena, vuelve a ser HECHO", P.buildForensicReport(P.grafoDesdePeritaje(copia), null).unspentFunds.length === sinGastar.length);
|
||||
}
|
||||
|
||||
console.log("\n=== 10. El ejemplo ===\n");
|
||||
{
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@ const P = new Function(`const C = {}; const ENTITY_INDEX = new Map();
|
||||
ok: true, status: 200,
|
||||
json: () => new Promise((_, rej) => signal.addEventListener("abort", () => { const e = new Error("aborted"); e.name = "AbortError"; rej(e); })),
|
||||
});
|
||||
const fwt = new Function("fetch", `const FETCH_TIMEOUT_MS = 8000; ${cut("async function fetchWithTimeout", "// ── Caché de respuestas del nodo")} return fetchWithTimeout;`)(fetchFalso);
|
||||
const fwt = new Function("fetch", `const RED = { signet: false }; ${cut("// ── fetch con timeout", "// ── Caché de respuestas del nodo")} return fetchWithTimeout;`)(fetchFalso);
|
||||
const t0 = Date.now();
|
||||
let msg = null;
|
||||
try { const r = await fwt("http://nodo/x", 150); await r.json(); } catch (e) { msg = e.message; }
|
||||
|
||||
+4
-2
@@ -14,7 +14,8 @@ const cut = (desde, hasta) => {
|
||||
if (s === -1 || e === -1) { console.error(`No se localiza ${desde}`); process.exit(1); }
|
||||
return lines.slice(s, e).join("\n");
|
||||
};
|
||||
const Q = new Function(`${cut("// ── QR: lógica pura", "// ── fin QR")}
|
||||
const Q = new Function(`${cut("// ── Lista oficial de palabras BIP-39", "// ── fin BIP-39")}
|
||||
${cut("// ── QR: lógica pura", "// ── fin QR")}
|
||||
return { clasificarQR, encajaQR, pareceSecretoQR, textoDeBytesQR };`)();
|
||||
|
||||
let pass = 0, fail = 0;
|
||||
@@ -52,7 +53,8 @@ ok("xpub suelta", tipo(ZPUB) === "xpub");
|
||||
const r = Q.clasificarQR(`[73c5da0a/84h/0h/0h]${ZPUB}`);
|
||||
ok("xpub estática de SeedSigner: [huella/ruta]zpub", r.tipo === "xpub" && r.valor === ZPUB && r.huella === "73c5da0a" && r.ruta === "m/84h/0h/0h", JSON.stringify(r));
|
||||
}
|
||||
ok("xpub dentro de un descriptor", Q.clasificarQR(`wpkh([73c5da0a/84h/0h/0h]${ZPUB}/0/*)`).valor === ZPUB);
|
||||
ok("descriptor por QR: se entrega ENTERO (A2-02), con la xpub aparte", Q.clasificarQR(`wpkh([73c5da0a/84h/0h/0h]${ZPUB}/0/*)#abcdefgh`).valor === `wpkh([73c5da0a/84h/0h/0h]${ZPUB}/0/*)#abcdefgh` && Q.clasificarQR(`wpkh([73c5da0a/84h/0h/0h]${ZPUB}/0/*)`).xpub === ZPUB);
|
||||
ok("descriptor por QR con el comentario de Sparrow: se quita la línea #", Q.clasificarQR(`# Receive and change descriptor:\nwpkh([73c5da0a/84h/0h/0h]${ZPUB}/<0;1>/*)`).valor === `wpkh([73c5da0a/84h/0h/0h]${ZPUB}/<0;1>/*)`);
|
||||
ok("PSBT en base64", tipo(PSBT) === "psbt");
|
||||
ok("transacción en crudo", tipo("0200000001" + "ab".repeat(80)) === "tx");
|
||||
ok("QR animado UR (crypto-psbt)", Q.clasificarQR("UR:CRYPTO-PSBT/1-3/LPADAXCSOEDTHY").urTipo === "crypto-psbt");
|
||||
|
||||
@@ -29,6 +29,7 @@ const fn = (cabecera) => {
|
||||
const Q = new Function(`
|
||||
const fmtBtc = s => (s / 1e8).toFixed(8) + " BTC";
|
||||
${fn(" function sha256Bytes(")}
|
||||
${cut("// ── Lista oficial de palabras BIP-39", "// ── fin BIP-39")}
|
||||
${cut("// ── QR: lógica pura", "// ── fin QR ──")}
|
||||
${cut("// ── QR animado: lógica pura", "// ── fin QR animado")}
|
||||
${cut("// ── Parser PSBT (BIP174)", "const PSBT_TIPOS")}
|
||||
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
// v1.48.0 — primer parche de la auditoría en frío (25-oct): redes, secretos
|
||||
// y datos de ejemplo.
|
||||
//
|
||||
// · A5-01 / A1-01: la guarda de red vive en fetchWithTimeout, el único
|
||||
// fetch de la app. En signet no sale ninguna dirección de mainnet, y un
|
||||
// txid solo sale si tu nodo de mainnet dice que no lo conoce.
|
||||
// · A2-01: una sola puerta para reconocer secretos (semillas BIP-39 enteras,
|
||||
// numeradas o abreviadas, xprv, WIF, SeedQR), con la lista OFICIAL.
|
||||
// · A1-03: un 4xx que se cambia por datos de ejemplo queda marcado.
|
||||
// · A3-05: las direcciones tb1q/tb1p se reconocen como SegWit/Taproot.
|
||||
//
|
||||
// Uso: node tests/test36.js
|
||||
|
||||
const crypto = require("crypto");
|
||||
const lines = require("./fuente.js")().split("\n");
|
||||
const cut = (desde, hasta) => {
|
||||
const s = lines.findIndex(l => l.includes(desde));
|
||||
const e = lines.findIndex((l, i) => i > s && l.includes(hasta));
|
||||
if (s === -1 || e === -1) { console.error(`No se localiza «${desde}» en el código de la app`); process.exit(1); }
|
||||
return lines.slice(s, e).join("\n");
|
||||
};
|
||||
let pass = 0, fail = 0;
|
||||
const ok = (n, c, x) => { console.log(` ${c ? "✓" : "✗"} ${n}`); if (!c && x !== undefined) console.log(" " + x); c ? pass++ : fail++; };
|
||||
|
||||
// ── La capa de red, con un fetch falso que apunta cada petición ─────────
|
||||
function capaDeRed(respuestas) {
|
||||
const pedidas = [];
|
||||
const fetchFalso = async (url) => {
|
||||
pedidas.push(url);
|
||||
const r = respuestas(url);
|
||||
if (r instanceof Error) throw r;
|
||||
return { ok: r >= 200 && r < 300, status: r, json: async () => ({}), text: async () => "" };
|
||||
};
|
||||
const hooks = "const useState = v => [v, () => {}]; const useEffect = () => {}; const useCallback = f => f;";
|
||||
const R = new Function("fetch", `${hooks} const RED = { signet: false, urlMain: "" };
|
||||
${cut("// ── fetch con timeout", " const fmt = {")}
|
||||
return { RED, fetchWithTimeout, apiGetJson, useApi, useNodeHealth, NODE_HEALTH };`)(fetchFalso);
|
||||
return { R, pedidas };
|
||||
}
|
||||
const rechaza = async (p) => { try { await p; return null; } catch (e) { return e; } };
|
||||
|
||||
const BC1 = "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu"; // BIP84, vector público
|
||||
const TB1 = "tb1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq0l98cr";
|
||||
const TXM = "a".repeat(64), TXS = "b".repeat(64);
|
||||
const MAIN = "https://nodo:4083", SIG = "https://nodo:4083/signet-tor";
|
||||
|
||||
(async () => {
|
||||
console.log("=== Guarda de red en fetchWithTimeout (A5-01, A1-01) ===\n");
|
||||
{
|
||||
const { R, pedidas } = capaDeRed(url => url.startsWith(MAIN + "/api/tx/" + TXM) ? 200 : url.startsWith(MAIN + "/api/tx/") ? 404 : 200);
|
||||
R.RED.signet = true; R.RED.urlMain = MAIN;
|
||||
// El mapa de UTXOs llamaba a fetchWithTimeout directamente con estas dos rutas.
|
||||
let e = await rechaza(R.fetchWithTimeout(`${SIG}/api/address/${BC1}/utxo`));
|
||||
ok("signet: /api/address/bc1…/utxo (mapa de UTXOs) → bloqueado sin enviar nada", e && e.bloqueado && pedidas.length === 0, e && e.message);
|
||||
e = await rechaza(R.fetchWithTimeout(`${SIG}/api/v1/address/${BC1}/txs`));
|
||||
ok("signet: /api/v1/address/bc1…/txs → bloqueado", e && e.bloqueado && pedidas.length === 0);
|
||||
e = await rechaza(R.fetchWithTimeout(`${SIG}/api/address/${TB1}`));
|
||||
ok("signet: una dirección tb1… sí sale", !e && pedidas.at(-1) === `${SIG}/api/address/${TB1}`);
|
||||
pedidas.length = 0;
|
||||
e = await rechaza(R.fetchWithTimeout(`${SIG}/api/tx/${TXM}`));
|
||||
ok("signet: un txid que tu nodo de mainnet conoce → se pregunta SOLO a tu nodo y no se envía", e && e.bloqueado && /es de mainnet/.test(e.message) && pedidas.length === 1 && pedidas[0] === `${MAIN}/api/tx/${TXM}/status`, JSON.stringify(pedidas));
|
||||
pedidas.length = 0;
|
||||
e = await rechaza(R.fetchWithTimeout(`${SIG}/api/tx/${TXS}/outspends`));
|
||||
ok("signet: un txid que tu nodo no conoce (404) → sale hacia la signet", !e && pedidas.length === 2 && pedidas[1] === `${SIG}/api/tx/${TXS}/outspends`, JSON.stringify(pedidas));
|
||||
pedidas.length = 0;
|
||||
e = await rechaza(R.fetchWithTimeout(`${SIG}/api/tx/${TXS}`));
|
||||
ok("…y la respuesta se recuerda: no se vuelve a preguntar a tu nodo", !e && pedidas.length === 1);
|
||||
R.RED.signet = false; pedidas.length = 0;
|
||||
e = await rechaza(R.fetchWithTimeout(`${MAIN}/api/address/${BC1}`));
|
||||
ok("mainnet: nada de esto se aplica (una sola petición, a tu nodo)", !e && pedidas.length === 1);
|
||||
}
|
||||
{
|
||||
const { R, pedidas } = capaDeRed(url => url.startsWith(MAIN + "/api/tx/") ? new Error("el nodo tardó demasiado en responder (timeout)") : 200);
|
||||
R.RED.signet = true; R.RED.urlMain = MAIN;
|
||||
const e = await rechaza(R.fetchWithTimeout(`${SIG}/api/tx/${TXS}`));
|
||||
ok("signet: si tu nodo de mainnet no contesta, el txid NO sale (no se sabe de qué red es)", e && e.bloqueado && /no se ha podido comprobar/.test(e.message) && !pedidas.some(u => u.startsWith(SIG)), e && e.message);
|
||||
}
|
||||
{
|
||||
const { R, pedidas } = capaDeRed(() => 200);
|
||||
R.RED.signet = true; R.RED.urlMain = "";
|
||||
const e = await rechaza(R.fetchWithTimeout(`https://mempool.space/signet/api/tx/${TXS}`));
|
||||
ok("signet sin nodo de mainnet configurado: no hay a quién preguntar, el txid sale", !e && pedidas.length === 1);
|
||||
}
|
||||
{
|
||||
const { R, pedidas } = capaDeRed(() => 200);
|
||||
R.RED.signet = true; R.RED.urlMain = MAIN;
|
||||
const e = await rechaza(R.apiGetJson(SIG, `/api/address/${BC1}`));
|
||||
ok("apiGetJson conserva su guarda (no llega ni al fetch)", e && e.bloqueado && pedidas.length === 0);
|
||||
}
|
||||
|
||||
console.log("\n=== Datos de ejemplo marcados aunque el nodo conteste 4xx (A1-03) ===\n");
|
||||
{
|
||||
const { R } = capaDeRed(url => /fee-rates|address\/x/.test(url) ? 404 : /mempool$/.test(url) ? 403 : 200);
|
||||
const { get } = R.useApi(MAIN);
|
||||
const MOCK = { ejemplo: true };
|
||||
const d1 = await get("/api/v1/mining/blocks/fee-rates/1w", MOCK);
|
||||
const d2 = await get("/api/mempool", MOCK);
|
||||
const d3 = await get("/api/v1/fees/recommended", MOCK);
|
||||
const vacio = await get("/api/address/x/txs", []);
|
||||
const salud = R.useNodeHealth(MAIN);
|
||||
ok("un 404 que devuelve datos de ejemplo → esEjemplo() lo dice", d1 === MOCK && salud.esEjemplo("/api/v1/mining/blocks/fee-rates/1w"));
|
||||
ok("un 403 igual", d2 === MOCK && salud.esEjemplo("/api/mempool"));
|
||||
ok("…y una respuesta buena de la misma familia /api/v1 no queda marcada", d3 !== MOCK && !salud.esEjemplo("/api/v1/fees/recommended"));
|
||||
ok("un 4xx no cuenta como «nodo caído» (el aviso global no salta)", salud.fallos.size === 0);
|
||||
ok("una lista vacía no es «dato de ejemplo»: no se marca", Array.isArray(vacio) && !salud.sustituidos.has("/api/address/x/txs"));
|
||||
}
|
||||
|
||||
console.log("\n=== Secretos en cualquier campo (A2-01) ===\n");
|
||||
const K = require("./extraer-cripto.js");
|
||||
const lista = K.BIP39_PALABRAS.join("\n") + "\n";
|
||||
ok("lista BIP-39: 2048 palabras y la huella del archivo oficial", K.BIP39_PALABRAS.length === 2048 && crypto.createHash("sha256").update(lista).digest("hex") === "2f5eed53a4727b4bf8880d8f3f199efc90e58503646d9ff8eff3a2ed3b24dbda");
|
||||
const SEMILLA = "abandon ".repeat(11) + "about"; // vector público de BIP-39
|
||||
ok("semilla de 12 palabras → secreto", K.esSecretoTexto(SEMILLA));
|
||||
ok("semilla numerada «1. abandon 2. abandon…» → secreto", K.esSecretoTexto(SEMILLA.split(" ").map((p, i) => `${i + 1}. ${p}`).join("\n")));
|
||||
ok("semilla en mayúsculas y con comas → secreto", K.esSecretoTexto(SEMILLA.toUpperCase().replace(/ /g, ", ")));
|
||||
ok("semilla a 4 letras (como la escribe SeedSigner) → secreto", K.esSecretoTexto("aban ".repeat(11) + "abou"));
|
||||
ok("semilla dentro de una nota más larga → secreto", K.esSecretoTexto(`Mi nota: ${SEMILLA}. No la pierdas.`));
|
||||
ok("SeedQR en dígitos (12 palabras = 48 dígitos) → secreto", K.esSecretoTexto("0000".repeat(11) + "0003"));
|
||||
ok("xprv → secreto", K.esSecretoTexto("xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi"));
|
||||
ok("clave privada WIF → secreto", K.esSecretoTexto("KwdMAjGmerYanjeui5SHS7JkmpZvVipYvB2LJGU1ZxJwYvP98617"));
|
||||
const frase = "el dinero salió de mi wallet el lunes por la tarde y no sé a dónde fue, nadie me avisó de nada";
|
||||
ok("una nota normal en castellano → no es secreto", !K.esSecretoTexto(frase));
|
||||
ok("once palabras de la lista seguidas → todavía no es secreto", !K.esSecretoTexto("abandon ".repeat(11)));
|
||||
ok("una xpub, una dirección, un txid o un descriptor → no son secretos",
|
||||
!K.esSecretoTexto("xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8") &&
|
||||
!K.esSecretoTexto(BC1) && !K.esSecretoTexto(TXM) && !K.esSecretoTexto(`wpkh([73c5da0a/84h/0h/0h]xpub6CatWdiZiodmUeTDp8LT5or8nmbKNcuyvz7WyksVFkKB4RHwCD3XyuvPEbvqAQY3rAPshWcMLoP2fMFMKHPJ4ZeZXYVUhLv1VMrjPC7PW6V/<0;1>/*)`));
|
||||
ok("analizarEntradaWallet rechaza una semilla como secreto", await (async () => { try { await K.analizarEntradaWallet(SEMILLA, "bc"); return false; } catch (e) { return !!e.secreto; } })());
|
||||
|
||||
console.log("\n=== Formato de las direcciones de signet (A3-05) ===\n");
|
||||
const A = new Function(`const C = {}; const ENTITY_INDEX = new Map(); const OFAC_SET = new Set();
|
||||
${cut("// ── FORMATO: lógica pura", "// ── fin formato")}
|
||||
${cut("function detectWallets", "function analyzeAddress")}
|
||||
${cut("function analyzeAddress", "// ── SIMULADOR DE GASTO")}
|
||||
return { analyzeAddress };`)();
|
||||
const fmt = a => A.analyzeAddress({ address: a, chain_stats: { tx_count: 1, funded_txo_count: 1, spent_txo_count: 0 }, mempool_stats: { tx_count: 0 } }).checks.find(c => c.id === "script_type");
|
||||
const t1 = fmt(TB1), b1 = fmt(BC1);
|
||||
ok("tb1q… → SegWit con la misma penalización que bc1q… (antes «De script (3…)», 15)", t1.pass && t1.penalty === b1.penalty && /SegWit \(tb1q…\)/.test(t1.detail), t1.detail);
|
||||
ok("bc1q… sigue igual", b1.pass && /SegWit \(bc1q…\)/.test(b1.detail));
|
||||
|
||||
console.log(`\n${pass} correctas, ${fail} fallidas`);
|
||||
process.exit(fail ? 1 : 0);
|
||||
})();
|
||||
Reference in New Issue
Block a user