@saulwade/swl-ses 2.6.1 → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +14 -2
- package/README.md +65 -18
- package/agentes/_intent-spec.md +73 -73
- package/agentes/_propose-step.md +90 -90
- package/bin/swl-ses.js +10 -0
- package/comandos/swl/brainstorm.md +1 -0
- package/comandos/swl/briefing.md +119 -119
- package/comandos/swl/contribuir.md +233 -233
- package/comandos/swl/deuda-codigo.md +97 -97
- package/comandos/swl/mcp-status.md +1 -0
- package/gateway/lib/event-channel.js +191 -191
- package/habilidades/agent-deep-links/SKILL.md +148 -148
- package/habilidades/backend-async-postgres-testing/SKILL.md +216 -216
- package/habilidades/backend-error-design/SKILL.md +221 -221
- package/habilidades/backend-production-resilience/SKILL.md +288 -288
- package/habilidades/calidad-anti-patrones-universales/SKILL.md +105 -1
- package/habilidades/calidad-contract-testing/SKILL.md +165 -165
- package/habilidades/calidad-mutation-testing/SKILL.md +25 -1
- package/habilidades/checklist-seguridad/recursos/stride-cobertura.md +60 -60
- package/habilidades/ci-cd-pipelines/SKILL.md +5 -1
- package/habilidades/css-moderno/SKILL.md +7 -1
- package/habilidades/diagrama-arquitectura/assets/template.html +276 -276
- package/habilidades/doubt-driven-review/recursos/EXAMPLES.md +130 -130
- package/habilidades/estructura-proyecto-claude/recursos/mcp-json-template.json +57 -57
- package/habilidades/extractor-de-aprendizajes/SKILL.md +5 -1
- package/habilidades/feynman-auditor-swl/recursos/preguntas-language-agnostic.md +108 -108
- package/habilidades/harness-claude-code/SKILL.md +3 -2
- package/habilidades/meta-skills-estandar/recursos/convencion-examples.md +93 -93
- package/habilidades/patrones-python/recursos/patrones-avanzados.md +469 -469
- package/habilidades/perfil-usuario/SKILL.md +200 -200
- package/habilidades/prevencion-sobreingenieria/recursos/EXAMPLES.md +580 -580
- package/habilidades/prevencion-sobreingenieria/recursos/soluciones-nativas.md +166 -166
- package/habilidades/prevencion-sobreingenieria/recursos/variables-residuales-post-refactor.md +85 -85
- package/habilidades/proceso-ddia-streaming/SKILL.md +231 -231
- package/habilidades/proceso-discovery-machote/SKILL.md +157 -157
- package/habilidades/proceso-dynamic-workflows/SKILL.md +60 -0
- package/habilidades/proceso-dynamic-workflows/recursos/template-adversarial-verify.js +65 -65
- package/habilidades/proceso-dynamic-workflows/recursos/template-triage.js +65 -65
- package/habilidades/proceso-intent-engineering/SKILL.md +269 -269
- package/habilidades/proceso-modular-split/SKILL.md +256 -256
- package/habilidades/state-inconsistency-auditor-swl/recursos/coupled-state-patterns.md +147 -147
- package/habilidades/swl-claudemd/recursos/contrato-aprender.md +83 -83
- package/habilidades/swl-claudemd/recursos/duplicacion-reglas-globales.md +85 -85
- package/habilidades/swl-claudemd/recursos/plantillas-init.md +94 -94
- package/habilidades/tdd-workflow/recursos/gherkin-bdd.md +111 -111
- package/hooks/calidad-pre-commit.js +159 -10
- package/hooks/ciclo-evolucion-subagente.js +26 -26
- package/hooks/ciclo-evolucion.js +26 -26
- package/hooks/contexto-subagente.js +68 -68
- package/hooks/lib/auto-consolidator.js +335 -335
- package/hooks/lib/ciclo-evolucion.js +47 -47
- package/hooks/lib/deep-links.js +185 -185
- package/hooks/lib/error-classifier.js +308 -308
- package/hooks/lib/notificacion-formato.js +45 -11
- package/hooks/lib/provenance-tracker.js +191 -191
- package/hooks/lib/raiz-proyecto.js +35 -4
- package/hooks/lib/resource-quota.js +122 -122
- package/hooks/lib/retry-jitter.js +165 -165
- package/hooks/lib/security-net.js +201 -201
- package/hooks/lib/skill-auditor.js +588 -588
- package/hooks/lib/sync-status.js +228 -228
- package/hooks/lib/taint-tracker.js +107 -107
- package/hooks/lib/text-similarity.js +241 -241
- package/hooks/lib/toon-compressor.js +245 -245
- package/hooks/notificacion-telegram.js +5 -11
- package/hooks/session-briefing.js +12 -4
- package/instintos/autonomia.yaml +27 -27
- package/instintos/prompt-appendices.yaml +57 -57
- package/llms.txt +1 -1
- package/manifiestos/agent-output-schemas.json +57 -57
- package/manifiestos/canonical-hashes.json +662 -0
- package/manifiestos/harness-ir.json +47536 -0
- package/manifiestos/hooks-config.json +469 -469
- package/manifiestos/invariantes-criticos.json +30 -30
- package/manifiestos/policy-bundle.json +2065 -0
- package/manifiestos/policy-corpus-w2.json +3926 -0
- package/manifiestos/runtime-adapters-core3.json +208 -0
- package/manifiestos/runtime-conformance.json +139 -0
- package/manifiestos/skills-lock.json +43 -43
- package/package.json +2 -2
- package/plantillas/auditor-veto-template.md +105 -105
- package/plantillas/github-workflows/release-please.yml +44 -44
- package/plantillas/github-workflows/swl-ci.yml +107 -107
- package/plantillas/github-workflows/swl-security.yml +51 -51
- package/plugin.json +2 -2
- package/reglas/accesibilidad.md +10 -10
- package/reglas/auditorias-documentales-estructurales.md +7 -7
- package/reglas/cloud-infra.md +8 -8
- package/reglas/consultar-vault-primero.md +195 -195
- package/reglas/git-workflow.md +1 -0
- package/reglas/hooks.md +6 -6
- package/reglas/intent-engineering.md +218 -218
- package/reglas/markitdown.md +8 -8
- package/reglas/monitor-ci.md +12 -0
- package/reglas/patrones.md +6 -6
- package/reglas/testing.md +7 -7
- package/reglas/tests-cleanup.md +224 -224
- package/schemas/agent-message.schema.json +73 -73
- package/schemas/agent-output-implementacion.schema.json +114 -114
- package/schemas/agent-output-planificacion.schema.json +150 -150
- package/schemas/agent-output-review.schema.json +98 -98
- package/schemas/diary-entry.schema.json +112 -112
- package/schemas/gate-state.schema.json +76 -0
- package/schemas/harness-ir.schema.json +369 -0
- package/schemas/hook-profiles.schema.json +54 -54
- package/schemas/hooks-config.schema.json +89 -89
- package/schemas/legacy-gates.schema.json +45 -0
- package/schemas/modulos.schema.json +38 -38
- package/schemas/perfiles.schema.json +36 -36
- package/schemas/plugin.schema.json +77 -77
- package/schemas/policy-bundle.schema.json +140 -0
- package/schemas/policy-enforcement.schema.json +117 -0
- package/schemas/policy-operation.schema.json +261 -0
- package/schemas/runtime-adapter.schema.json +176 -0
- package/schemas/runtime-build-attestation.schema.json +100 -0
- package/schemas/runtime-conformance.schema.json +239 -0
- package/schemas/runtime-diagnostic.schema.json +395 -0
- package/schemas/skill-evals.schema.json +119 -119
- package/schemas/skill-frontmatter.schema.json +245 -245
- package/schemas/w4-certification-request.schema.json +72 -0
- package/schemas/w4-certification-verdict.schema.json +224 -0
- package/schemas/w4-corpus.schema.json +172 -0
- package/schemas/w4-mutation-report.schema.json +116 -0
- package/schemas/w4-replay-result.schema.json +164 -0
- package/schemas/w4-scoring-report.schema.json +89 -0
- package/scripts/audit-tools/audit-history.js +330 -330
- package/scripts/audit-tools/bundle-tracker.js +290 -290
- package/scripts/audit-tools/canary-monitor.js +352 -352
- package/scripts/audit-tools/code-profiler.js +605 -605
- package/scripts/audit-tools/dep-doctor.js +320 -320
- package/scripts/audit-tools/env-validator.js +206 -206
- package/scripts/audit-tools/lib/fs-walk.js +48 -48
- package/scripts/audit-tools/lib/output.js +23 -23
- package/scripts/audit-tools/migration-checker.js +392 -392
- package/scripts/audit-tools/pentest-scanner.js +1436 -1436
- package/scripts/bootstrap-instintos.js +3 -0
- package/scripts/cli/aprobar-plan.js +73 -73
- package/scripts/cli/briefing.js +23 -23
- package/scripts/cli/ciclo-evolucion.js +26 -26
- package/scripts/cli/derivar-feature-list.js +25 -25
- package/scripts/cli/detectar-host.js +27 -27
- package/scripts/cli/diary-entry.js +69 -69
- package/scripts/cli/execution-state.js +18 -18
- package/scripts/cli/gateway-notify.js +41 -41
- package/scripts/cli/liberar-fase.js +42 -42
- package/scripts/cli/mark-evolved.js +56 -56
- package/scripts/cli/metricas-dora.js +26 -26
- package/scripts/cli/near-duplicate.js +55 -55
- package/scripts/cli/notificaciones.js +123 -123
- package/scripts/cli/propose-step.js +29 -29
- package/scripts/cli/schedule-parse.js +19 -19
- package/scripts/cli/sugerir-modelo.js +20 -20
- package/scripts/cli/verificar-plan.js +36 -36
- package/scripts/cli/verificar-trazabilidad.js +35 -35
- package/scripts/comandos/install-asistido.js +8 -7
- package/scripts/configurar-branch-protection.js +418 -418
- package/scripts/detectar-aprendizajes-duplicados.js +151 -151
- package/scripts/doctor.js +61 -36
- package/scripts/generar-checklists-consolidados.js +273 -273
- package/scripts/generar-claims-runtime.js +1342 -0
- package/scripts/generar-harness-ir.js +257 -0
- package/scripts/generar-inventario.js +52 -54
- package/scripts/generar-policy-bundle.js +202 -0
- package/scripts/instalador.js +26 -7
- package/scripts/lib/approval-receipts.js +190 -0
- package/scripts/lib/artefactos-python.js +43 -43
- package/scripts/lib/benchmark-metrics.js +160 -160
- package/scripts/lib/budget-enforcer.js +252 -252
- package/scripts/lib/certificacion-loop-state.js +421 -0
- package/scripts/lib/ci-reader.js +193 -193
- package/scripts/lib/ciclo-autonomo/yaml-instintos.js +56 -0
- package/scripts/lib/clasificar-directorio.js +92 -0
- package/scripts/lib/contadores-inventario.js +217 -217
- package/scripts/lib/detectar-host-swl.js +175 -175
- package/scripts/lib/detectar-runtime.js +29 -20
- package/scripts/lib/detectar-stack-detallado.js +307 -307
- package/scripts/lib/detector-autoduplicacion-intra-archivo.js +234 -234
- package/scripts/lib/detector-reglas-duplicadas.js +220 -220
- package/scripts/lib/eval-metrics-store.js +218 -218
- package/scripts/lib/eval-quality.js +171 -171
- package/scripts/lib/eval-schemas.js +144 -144
- package/scripts/lib/eval-self-correct.js +106 -106
- package/scripts/lib/eval-validator.js +185 -185
- package/scripts/lib/evidence-verifier.js +192 -0
- package/scripts/lib/evidencia-release.js +322 -322
- package/scripts/lib/frontmatter-canonico.js +509 -0
- package/scripts/lib/gate-engine.js +871 -0
- package/scripts/lib/gate-hooks-requires.js +249 -249
- package/scripts/lib/gate-licencias.js +212 -212
- package/scripts/lib/git-config-preflight.js +48 -0
- package/scripts/lib/git-metricas.js +257 -257
- package/scripts/lib/harness-ir.js +778 -0
- package/scripts/lib/harness-source-snapshot.js +309 -0
- package/scripts/lib/integrity-ledger.js +1147 -0
- package/scripts/lib/jaccard-similarity.js +98 -98
- package/scripts/lib/legacy-gate-migration.js +324 -0
- package/scripts/lib/limpiar-basura-global.js +45 -2
- package/scripts/lib/longmemeval-runner.js +125 -125
- package/scripts/lib/metricas-dora.js +204 -204
- package/scripts/lib/notificaciones-telegram.js +1 -0
- package/scripts/lib/npm-version.js +1 -0
- package/scripts/lib/paquetes-conocidos.js +50 -50
- package/scripts/lib/plan-lock.js +61 -13
- package/scripts/lib/policy-broker.js +338 -0
- package/scripts/lib/policy-bundle.js +342 -0
- package/scripts/lib/policy-context-provider.js +310 -0
- package/scripts/lib/policy-contract.js +479 -0
- package/scripts/lib/policy-verifier-utils.js +65 -0
- package/scripts/lib/pr-analyzer.js +399 -399
- package/scripts/lib/principal-verifier.js +178 -0
- package/scripts/lib/prompt-builder.js +264 -264
- package/scripts/lib/resolver-plan-fase.js +37 -37
- package/scripts/lib/rrf-fusion.js +175 -175
- package/scripts/lib/runtime-adapter-contract.js +267 -0
- package/scripts/lib/runtime-artifact-verifier.js +426 -0
- package/scripts/lib/runtime-build-attestation.js +127 -0
- package/scripts/lib/runtime-bundle-installer.js +586 -0
- package/scripts/lib/runtime-compiler.js +327 -0
- package/scripts/lib/runtime-conformance.js +202 -0
- package/scripts/lib/runtime-doctor-core3.js +567 -0
- package/scripts/lib/runtime-doctor-input.js +59 -0
- package/scripts/lib/runtime-operation-adapter.js +267 -0
- package/scripts/lib/schema-version.js +164 -164
- package/scripts/lib/semantic-search.js +252 -252
- package/scripts/lib/signed-envelope.js +545 -0
- package/scripts/lib/single-use-store.js +359 -0
- package/scripts/lib/skills-externas.js +31 -0
- package/scripts/lib/transformadores/codex.js +15 -8
- package/scripts/lib/transformadores/gemini.js +79 -5
- package/scripts/lib/w4-attestation-adapter.js +158 -0
- package/scripts/lib/w4-canario.js +337 -0
- package/scripts/lib/w4-claims.js +182 -0
- package/scripts/lib/w4-corpus-generador.js +542 -0
- package/scripts/lib/w4-gate-c5.js +115 -0
- package/scripts/lib/w4-harness-bajo-prueba.js +155 -0
- package/scripts/lib/w4-matriz-combos.js +55 -0
- package/scripts/lib/w4-motor-mutacion.js +1348 -0
- package/scripts/lib/w4-motor-replay.js +735 -0
- package/scripts/lib/w4-pin-origen.js +54 -0
- package/scripts/lib/w4-publicar-request.js +132 -0
- package/scripts/lib/w4-revocacion.js +62 -0
- package/scripts/lib/w4-runtimes-core3.js +38 -0
- package/scripts/lib/w4-scorer-certificacion.js +692 -0
- package/scripts/lib/w4-superficie-candidato.js +49 -0
- package/scripts/lib/w4-veredicto.js +452 -0
- package/scripts/lib/w4-verificar-veredicto.js +302 -0
- package/scripts/limpiar-artefactos-python.js +131 -131
- package/scripts/migrar-csv-a-array.js +168 -168
- package/scripts/migrar-fase-dominio.js +200 -200
- package/scripts/migrar-gates-legacy.js +108 -0
- package/scripts/publicar-certification-request.js +115 -0
- package/scripts/runtime-doctor.js +107 -0
- package/scripts/tui/componentes/selector-multi.js +189 -189
- package/scripts/tui/componentes/selector-unico.js +158 -158
- package/scripts/tui/ejecutores.js +375 -375
- package/scripts/tui/lib/colores.js +129 -129
- package/scripts/tui/lib/render.js +264 -264
- package/scripts/tui/lib/teclas.js +113 -113
- package/scripts/tui/pantallas/install-wizard.js +12 -7
- package/scripts/tui/pantallas/menu-principal.js +52 -52
- package/scripts/tui/pantallas/progreso.js +274 -274
- package/scripts/tui/pantallas/resumen.js +132 -132
- package/scripts/validar-userland-vacio.js +110 -110
- package/scripts/verificar-aislamiento-swl-eval.js +87 -0
- package/scripts/verificar-empaquetado-downstream.js +375 -0
- package/scripts/verificar-loop-constructor.js +215 -0
- package/scripts/verificar-trazabilidad.js +13 -6
- package/scripts/verificar-veredicto-real.js +84 -0
|
@@ -0,0 +1,1147 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/** Ledger firmado y anclado fuera del workspace para el kernel W2. */
|
|
4
|
+
|
|
5
|
+
const crypto = require('node:crypto');
|
|
6
|
+
const fs = require('node:fs');
|
|
7
|
+
const path = require('node:path');
|
|
8
|
+
const util = require('node:util');
|
|
9
|
+
|
|
10
|
+
const {
|
|
11
|
+
canonicalizarIJson,
|
|
12
|
+
parsearIJson,
|
|
13
|
+
validarTimestampIso,
|
|
14
|
+
} = require('./signed-envelope');
|
|
15
|
+
|
|
16
|
+
const policyContextModule = require('./policy-context-provider');
|
|
17
|
+
const createPolicyContextProvider = policyContextModule.createPolicyContextProvider;
|
|
18
|
+
delete policyContextModule.createPolicyContextProvider;
|
|
19
|
+
Object.freeze(policyContextModule);
|
|
20
|
+
const singleUseModule = require('./single-use-store');
|
|
21
|
+
const createSingleUseStore = singleUseModule.createSingleUseStore;
|
|
22
|
+
delete singleUseModule.createSingleUseStore;
|
|
23
|
+
Object.freeze(singleUseModule);
|
|
24
|
+
const gateEngineModule = require('./gate-engine');
|
|
25
|
+
const createGateEngine = gateEngineModule.createGateEngine;
|
|
26
|
+
delete gateEngineModule.createGateEngine;
|
|
27
|
+
Object.freeze(gateEngineModule);
|
|
28
|
+
const policyBrokerPath = require.resolve('./policy-broker');
|
|
29
|
+
let policyBrokerModule = require(policyBrokerPath);
|
|
30
|
+
if (typeof policyBrokerModule.createPolicyBroker !== 'function') {
|
|
31
|
+
delete require.cache[policyBrokerPath];
|
|
32
|
+
policyBrokerModule = require(policyBrokerPath);
|
|
33
|
+
}
|
|
34
|
+
const createPolicyBroker = policyBrokerModule.createPolicyBroker;
|
|
35
|
+
delete policyBrokerModule.createPolicyBroker;
|
|
36
|
+
Object.freeze(policyBrokerModule);
|
|
37
|
+
const { compilarPolicyBundle } = require('./policy-bundle');
|
|
38
|
+
const { getContractValidators } = require('./policy-verifier-utils');
|
|
39
|
+
|
|
40
|
+
const ZERO = '0'.repeat(64);
|
|
41
|
+
const SHA256 = /^[a-f0-9]{64}$/u;
|
|
42
|
+
const IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
|
|
43
|
+
const EVENT_KEYS = [
|
|
44
|
+
'schemaVersion', 'streamId', 'sequence', 'previousHash', 'eventType', 'payload',
|
|
45
|
+
'payloadDigest', 'timestamp', 'trustEpoch', 'trustDigest', 'signerKeyId',
|
|
46
|
+
'eventHash', 'signature',
|
|
47
|
+
];
|
|
48
|
+
const ANCHOR_KEYS = [
|
|
49
|
+
'schemaVersion', 'streamId', 'sequence', 'headHash', 'trustEpoch', 'trustDigest',
|
|
50
|
+
'lastTrustedTime', 'generation',
|
|
51
|
+
];
|
|
52
|
+
const TRUST_KEYS = [
|
|
53
|
+
'schemaVersion', 'rootKeyDigest', 'trustEpoch', 'trustDigest', 'providers',
|
|
54
|
+
'signerPath', 'anchorPath', 'integrityKeyId', 'integrityPublicKey',
|
|
55
|
+
];
|
|
56
|
+
const APPEND_KEYS = ['expectedSequence', 'expectedHeadHash', 'eventType', 'payload'];
|
|
57
|
+
const PIN_KEYS = [
|
|
58
|
+
'schemaVersion', 'rootKeyDigest', 'trustPath', 'signerPath', 'anchorPath', 'streamId',
|
|
59
|
+
];
|
|
60
|
+
const PROCESS_FINGERPRINT = obtenerFingerprintProceso(process.pid);
|
|
61
|
+
const MAX_BYTES = Object.freeze({
|
|
62
|
+
anchor: 16 * 1024,
|
|
63
|
+
ledger: 64 * 1024 * 1024,
|
|
64
|
+
lock: 4 * 1024,
|
|
65
|
+
payload: 1024 * 1024,
|
|
66
|
+
provisioning: 16 * 1024,
|
|
67
|
+
signer: 16 * 1024,
|
|
68
|
+
trust: 256 * 1024,
|
|
69
|
+
});
|
|
70
|
+
const MAX_EVENTOS = 10000;
|
|
71
|
+
const LOCK_LECTURAS_MAX = 8;
|
|
72
|
+
const LOCK_ESPERA_BASE_MS = 1;
|
|
73
|
+
const LOCK_ESPERA_MAX_MS = 32;
|
|
74
|
+
const LOCK_ESPERA_BUFFER = new Int32Array(new SharedArrayBuffer(4));
|
|
75
|
+
const APPEND_RECEIPTS = new WeakSet();
|
|
76
|
+
const AUTHORITY_RECEIPTS = new WeakSet();
|
|
77
|
+
const RESERVED_EVENT_PREFIXES = Object.freeze([
|
|
78
|
+
'approval.', 'authorization.', 'gate.', 'grant.', 'legacy.', 'policy.',
|
|
79
|
+
]);
|
|
80
|
+
|
|
81
|
+
function crearError(codigo, mensaje) {
|
|
82
|
+
const error = new Error(mensaje);
|
|
83
|
+
error.codigo = codigo;
|
|
84
|
+
return error;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function fallar(codigo, mensaje) {
|
|
88
|
+
throw crearError(codigo, mensaje);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function validarObjeto(valor, codigo, etiqueta) {
|
|
92
|
+
if (!valor || typeof valor !== 'object' || Array.isArray(valor) || util.types.isProxy(valor)) {
|
|
93
|
+
fallar(codigo, `${etiqueta} inválido`);
|
|
94
|
+
}
|
|
95
|
+
const proto = Object.getPrototypeOf(valor);
|
|
96
|
+
if (proto !== Object.prototype && proto !== null) fallar(codigo, `${etiqueta} inválido`);
|
|
97
|
+
if (Object.getOwnPropertySymbols(valor).length > 0) fallar(codigo, `${etiqueta} inválido`);
|
|
98
|
+
const descriptores = Object.values(Object.getOwnPropertyDescriptors(valor));
|
|
99
|
+
if (descriptores.some((item) => !item.enumerable || !('value' in item))) {
|
|
100
|
+
fallar(codigo, `${etiqueta} inválido`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function validarClaves(valor, claves, codigo, etiqueta) {
|
|
105
|
+
if (JSON.stringify(Object.keys(valor).sort()) !== JSON.stringify([...claves].sort())) {
|
|
106
|
+
fallar(codigo, `${etiqueta} inválido`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function congelarProfundo(valor) {
|
|
111
|
+
if (!valor || typeof valor !== 'object' || Object.isFrozen(valor)) return valor;
|
|
112
|
+
Object.values(valor).forEach(congelarProfundo);
|
|
113
|
+
return Object.freeze(valor);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function hashBytes(bytes) {
|
|
117
|
+
return crypto.createHash('sha256').update(bytes).digest('hex');
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function hitFault(punto) {
|
|
121
|
+
if (process.env.SWL_INTEGRITY_FAULT === punto) {
|
|
122
|
+
if (!esModoPruebas()) fallar('FAULT_CONFIG_INVALID', 'fault injection fuera de pruebas');
|
|
123
|
+
fallar('FAULT_INJECTED', `falla inyectada: ${punto}`);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function esModoPruebas() {
|
|
128
|
+
return process.env.NODE_ENV === 'test' && process.env.SWL_INTEGRITY_TEST_MODE === '1';
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function obtenerFingerprintLinux(pid) {
|
|
132
|
+
try {
|
|
133
|
+
const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
|
|
134
|
+
const cierre = stat.lastIndexOf(')');
|
|
135
|
+
const campos = stat.slice(cierre + 2).trim().split(/\s+/u);
|
|
136
|
+
const bootId = fs.readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
|
|
137
|
+
return cierre > 0 && campos[19] && bootId ? `${bootId}:${campos[19]}` : null;
|
|
138
|
+
} catch {
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function obtenerFingerprintProceso(pid) {
|
|
144
|
+
const nativo = process.platform === 'linux' ? obtenerFingerprintLinux(pid) : null;
|
|
145
|
+
if (nativo) return nativo;
|
|
146
|
+
if (pid === process.pid) {
|
|
147
|
+
return `${process.pid}:${Math.round(Date.now() - process.uptime() * 1000)}`;
|
|
148
|
+
}
|
|
149
|
+
return null;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function validarBackendArchivos() {
|
|
153
|
+
if (process.env.SWL_INTEGRITY_FAULT && !esModoPruebas()) {
|
|
154
|
+
fallar('FAULT_CONFIG_INVALID', 'fault injection fuera de pruebas');
|
|
155
|
+
}
|
|
156
|
+
if (process.platform !== 'linux' && !esModoPruebas()) {
|
|
157
|
+
fallar('FILE_BACKEND_UNAVAILABLE', 'backend de archivos sin inspector nativo');
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function mismaRuta(a, b) {
|
|
162
|
+
return path.relative(path.resolve(a), path.resolve(b)) === '';
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function validarPermisos(stat, codigo, esDirectorio = false, privado = true) {
|
|
166
|
+
if (process.platform === 'win32') return;
|
|
167
|
+
if (typeof process.geteuid === 'function' && stat.uid !== process.geteuid()) {
|
|
168
|
+
fallar(codigo, 'propietario inseguro');
|
|
169
|
+
}
|
|
170
|
+
const permisos = stat.mode & 0o777;
|
|
171
|
+
const inseguros = esDirectorio && !privado ? (permisos & 0o022) !== 0 : permisos !== (
|
|
172
|
+
esDirectorio ? 0o700 : 0o600
|
|
173
|
+
);
|
|
174
|
+
if (inseguros) fallar(codigo, 'permisos inseguros');
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function validarDirectorioSeguro(directorio, privado = false) {
|
|
178
|
+
const stat = fs.lstatSync(directorio);
|
|
179
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) fallar('PATH_INVALID', 'directorio inseguro');
|
|
180
|
+
if (!mismaRuta(fs.realpathSync(directorio), directorio)) {
|
|
181
|
+
fallar('PATH_INVALID', 'directorio redirigido');
|
|
182
|
+
}
|
|
183
|
+
validarPermisos(stat, 'PATH_INVALID', true, privado);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function esRutaInterna(ruta, workspaceRoot) {
|
|
187
|
+
const relativa = path.relative(path.resolve(workspaceRoot), path.resolve(ruta));
|
|
188
|
+
return relativa === '' || (!relativa.startsWith('..') && !path.isAbsolute(relativa));
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function validarRutaExternaSegura(ruta, workspaceRoot) {
|
|
192
|
+
const root = path.parse(ruta).root;
|
|
193
|
+
const resto = ruta.slice(root.length);
|
|
194
|
+
const prohibida = typeof ruta !== 'string' || !path.isAbsolute(ruta) || ruta.includes('\0')
|
|
195
|
+
|| /^[\\/]{2}/u.test(ruta) || ruta.normalize('NFKC') !== ruta
|
|
196
|
+
|| /[\u200B-\u200F\u202A-\u202E\u2060-\u206F]/u.test(ruta)
|
|
197
|
+
|| resto.includes(':') || esRutaInterna(ruta, workspaceRoot);
|
|
198
|
+
if (prohibida) fallar('PATH_INVALID', 'locator externo inseguro');
|
|
199
|
+
validarDirectorioSeguro(path.dirname(ruta), true);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function asegurarDirectorio(directorio, privado = true) {
|
|
203
|
+
if (!fs.existsSync(directorio)) fs.mkdirSync(directorio, { mode: 0o700 });
|
|
204
|
+
validarDirectorioSeguro(directorio, privado);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function validarArchivoRegular(ruta, codigo, maxBytes, privado = true) {
|
|
208
|
+
validarDirectorioSeguro(path.dirname(ruta), privado);
|
|
209
|
+
let stat;
|
|
210
|
+
try {
|
|
211
|
+
stat = fs.lstatSync(ruta);
|
|
212
|
+
} catch (error) {
|
|
213
|
+
if (error.code === 'ENOENT') fallar(codigo, 'archivo no disponible');
|
|
214
|
+
throw error;
|
|
215
|
+
}
|
|
216
|
+
if (stat.isSymbolicLink() || !stat.isFile() || stat.nlink !== 1) {
|
|
217
|
+
fallar(codigo, 'archivo inseguro');
|
|
218
|
+
}
|
|
219
|
+
if (privado) validarPermisos(stat, codigo);
|
|
220
|
+
if (Number.isInteger(maxBytes) && stat.size > maxBytes) fallar(codigo, 'archivo excede límite');
|
|
221
|
+
return stat;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function leerBytesEstables(ruta, codigo, maxBytes, privado = true) {
|
|
225
|
+
const inicial = validarArchivoRegular(ruta, codigo, maxBytes, privado);
|
|
226
|
+
const descriptor = fs.openSync(ruta, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
|
|
227
|
+
try {
|
|
228
|
+
const bytes = fs.readFileSync(descriptor);
|
|
229
|
+
const final = fs.fstatSync(descriptor);
|
|
230
|
+
if (inicial.dev !== final.dev || inicial.ino !== final.ino || inicial.size !== final.size) {
|
|
231
|
+
fallar(codigo, 'archivo cambió durante lectura');
|
|
232
|
+
}
|
|
233
|
+
if (Number.isInteger(maxBytes) && bytes.length > maxBytes) {
|
|
234
|
+
fallar(codigo, 'archivo excede límite');
|
|
235
|
+
}
|
|
236
|
+
return bytes;
|
|
237
|
+
} finally {
|
|
238
|
+
fs.closeSync(descriptor);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function leerJson(ruta, codigo, maxBytes) {
|
|
243
|
+
try {
|
|
244
|
+
return parsearIJson(leerBytesEstables(ruta, codigo, maxBytes));
|
|
245
|
+
} catch (error) {
|
|
246
|
+
if (error.codigo === codigo) throw error;
|
|
247
|
+
fallar(codigo, 'JSON externo inválido');
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function sincronizarDirectorio(directorio) {
|
|
252
|
+
const descriptor = fs.openSync(directorio, 'r');
|
|
253
|
+
try {
|
|
254
|
+
fs.fsyncSync(descriptor);
|
|
255
|
+
} catch (error) {
|
|
256
|
+
const tolerable = process.platform === 'win32'
|
|
257
|
+
&& (error.code === 'EPERM' || error.code === 'EINVAL');
|
|
258
|
+
if (!tolerable) throw error;
|
|
259
|
+
} finally {
|
|
260
|
+
fs.closeSync(descriptor);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function escribirTemporal(ruta, bytes, punto) {
|
|
265
|
+
fs.writeFileSync(ruta, bytes, { flag: 'wx', mode: 0o600 });
|
|
266
|
+
hitFault(`after-${punto}-temp-write`);
|
|
267
|
+
const descriptor = fs.openSync(ruta, 'r+');
|
|
268
|
+
try {
|
|
269
|
+
fs.fsyncSync(descriptor);
|
|
270
|
+
} finally {
|
|
271
|
+
fs.closeSync(descriptor);
|
|
272
|
+
}
|
|
273
|
+
hitFault(`after-${punto}-temp-fsync`);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function sincronizarArchivo(ruta) {
|
|
277
|
+
const descriptor = fs.openSync(ruta, 'r+');
|
|
278
|
+
try {
|
|
279
|
+
fs.fsyncSync(descriptor);
|
|
280
|
+
} finally {
|
|
281
|
+
fs.closeSync(descriptor);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function eliminarSiExiste(ruta) {
|
|
286
|
+
try {
|
|
287
|
+
fs.unlinkSync(ruta);
|
|
288
|
+
} catch (error) {
|
|
289
|
+
if (error.code !== 'ENOENT') throw error;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function escrituraAtomica(ruta, bytes, puntoRename) {
|
|
294
|
+
const directorio = path.dirname(ruta);
|
|
295
|
+
const temporal = `${ruta}.tmp-${process.pid}-${crypto.randomBytes(8).toString('hex')}`;
|
|
296
|
+
validarDirectorioSeguro(directorio, true);
|
|
297
|
+
try {
|
|
298
|
+
escribirTemporal(temporal, bytes, puntoRename);
|
|
299
|
+
hitFault(`before-${puntoRename}-rename`);
|
|
300
|
+
validarDirectorioSeguro(directorio, true);
|
|
301
|
+
fs.renameSync(temporal, ruta);
|
|
302
|
+
hitFault(`after-${puntoRename}-rename`);
|
|
303
|
+
validarArchivoRegular(ruta, 'DURABILITY_INVALID', bytes.length);
|
|
304
|
+
sincronizarArchivo(ruta);
|
|
305
|
+
sincronizarDirectorio(directorio);
|
|
306
|
+
hitFault(`after-${puntoRename}-directory-fsync`);
|
|
307
|
+
} finally {
|
|
308
|
+
eliminarSiExiste(temporal);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function esperarLockBreve(intento) {
|
|
313
|
+
const espera = Math.min(LOCK_ESPERA_BASE_MS << intento, LOCK_ESPERA_MAX_MS);
|
|
314
|
+
Atomics.wait(LOCK_ESPERA_BUFFER, 0, 0, espera);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// Defensa en profundidad de la publicación atómica del escritor. persistirLockNuevo
|
|
318
|
+
// enlaza el lock con contenido completo, pero deja una ventana residual mínima donde
|
|
319
|
+
// el path final tiene nlink=2 (entre el link y el unlink del temporal): un lector
|
|
320
|
+
// concurrente que cae ahí ve validarArchivoRegular rechazarlo como transitorio. Es
|
|
321
|
+
// contención de creación en curso, no corrupción; se reintenta la lectura hasta que
|
|
322
|
+
// el escritor completa el unlink. Un fallo de VALIDACIÓN (campos malos sobre un lock
|
|
323
|
+
// ya completo) ocurre después, en parsearLock, y nunca se reintenta. Residuales
|
|
324
|
+
// benignos que también se reintentan sin daño (latencia acotada, nunca resultado
|
|
325
|
+
// incorrecto): ENOENT de un lock liberado durante la carrera y PATH_INVALID que
|
|
326
|
+
// leerJson normaliza a LOCK_INVALID.
|
|
327
|
+
function leerLockCrudo(ruta) {
|
|
328
|
+
let ultimoError;
|
|
329
|
+
for (let intento = 0; intento < LOCK_LECTURAS_MAX; intento += 1) {
|
|
330
|
+
try {
|
|
331
|
+
return leerJson(ruta, 'LOCK_INVALID', MAX_BYTES.lock);
|
|
332
|
+
} catch (error) {
|
|
333
|
+
// leerJson normaliza toda falla de lectura/parseo a LOCK_INVALID (ver su
|
|
334
|
+
// catch): un lock imparseable es contención de creación en curso, se reintenta.
|
|
335
|
+
ultimoError = error;
|
|
336
|
+
if (intento + 1 < LOCK_LECTURAS_MAX) esperarLockBreve(intento);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
throw ultimoError;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function parsearLock(ruta) {
|
|
343
|
+
const lock = leerLockCrudo(ruta);
|
|
344
|
+
validarObjeto(lock, 'LOCK_INVALID', 'lock');
|
|
345
|
+
validarClaves(lock, ['ownerToken', 'pid', 'processFingerprint'], 'LOCK_INVALID', 'lock');
|
|
346
|
+
if (!SHA256.test(lock.ownerToken) || !Number.isInteger(lock.pid) || lock.pid <= 0) {
|
|
347
|
+
fallar('LOCK_INVALID', 'lock inválido');
|
|
348
|
+
}
|
|
349
|
+
if (typeof lock.processFingerprint !== 'string' || lock.processFingerprint.length > 256) {
|
|
350
|
+
fallar('LOCK_INVALID', 'lock inválido');
|
|
351
|
+
}
|
|
352
|
+
return lock;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function inspeccionarProceso(lock) {
|
|
356
|
+
if (lock.pid === process.pid) {
|
|
357
|
+
return { alive: true, fingerprint: PROCESS_FINGERPRINT };
|
|
358
|
+
}
|
|
359
|
+
try {
|
|
360
|
+
process.kill(lock.pid, 0);
|
|
361
|
+
} catch (error) {
|
|
362
|
+
if (error.code === 'ESRCH') return { alive: false, fingerprint: null };
|
|
363
|
+
}
|
|
364
|
+
return { alive: true, fingerprint: obtenerFingerprintProceso(lock.pid) };
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function puedeReclamar(lock) {
|
|
368
|
+
const proceso = inspeccionarProceso(lock);
|
|
369
|
+
if (!proceso.alive) return true;
|
|
370
|
+
return proceso.fingerprint !== null && proceso.fingerprint !== lock.processFingerprint;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function locksIguales(a, b) {
|
|
374
|
+
return a.ownerToken === b.ownerToken
|
|
375
|
+
&& a.pid === b.pid
|
|
376
|
+
&& a.processFingerprint === b.processFingerprint;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function crearLockPropio() {
|
|
380
|
+
return {
|
|
381
|
+
ownerToken: crypto.randomBytes(32).toString('hex'),
|
|
382
|
+
pid: process.pid,
|
|
383
|
+
processFingerprint: PROCESS_FINGERPRINT,
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function persistirLockNuevo(ruta, valor) {
|
|
388
|
+
// Publicación atómica-exclusiva: el contenido completo se escribe primero en un
|
|
389
|
+
// temporal por-proceso y luego se enlaza al path final con linkSync. link() falla
|
|
390
|
+
// con EEXIST si el lock ya existe —preserva la exclusión mutua que adquirirLock
|
|
391
|
+
// necesita— y el path final, una vez visible, SIEMPRE trae contenido: nunca la
|
|
392
|
+
// ventana vacía de un create-then-write. Un crash antes del link deja sólo el
|
|
393
|
+
// temporal (huérfano limpiable), nunca un lock de 0 bytes irreclamable. La ventana
|
|
394
|
+
// residual nlink=2 entre link y unlink la absorbe leerLockCrudo (reintento).
|
|
395
|
+
const temporal = `${ruta}.${crypto.randomBytes(12).toString('hex')}.tmp`;
|
|
396
|
+
fs.writeFileSync(temporal, `${canonicalizarIJson(valor)}\n`, { flag: 'wx', mode: 0o600 });
|
|
397
|
+
sincronizarArchivo(temporal);
|
|
398
|
+
try {
|
|
399
|
+
fs.linkSync(temporal, ruta);
|
|
400
|
+
} catch (error) {
|
|
401
|
+
eliminarSiExiste(temporal);
|
|
402
|
+
throw error;
|
|
403
|
+
}
|
|
404
|
+
eliminarSiExiste(temporal);
|
|
405
|
+
sincronizarDirectorio(path.dirname(ruta));
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function eliminarLockVerificado(ruta, ownerToken) {
|
|
409
|
+
const actual = parsearLock(ruta);
|
|
410
|
+
if (actual.ownerToken !== ownerToken) fallar('LOCK_OWNER_MISMATCH', 'owner cambió');
|
|
411
|
+
fs.unlinkSync(ruta);
|
|
412
|
+
sincronizarDirectorio(path.dirname(ruta));
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
function cuarentenarLock(ruta, lock) {
|
|
416
|
+
const cuarentena = `${ruta}.orphan-${crypto.randomBytes(12).toString('hex')}`;
|
|
417
|
+
try {
|
|
418
|
+
fs.renameSync(ruta, cuarentena);
|
|
419
|
+
} catch (error) {
|
|
420
|
+
if (error.code === 'ENOENT') fallar('LOCK_CONFLICT', 'otro reclaimer ganó');
|
|
421
|
+
throw error;
|
|
422
|
+
}
|
|
423
|
+
const movido = parsearLock(cuarentena);
|
|
424
|
+
if (!locksIguales(lock, movido)) fallar('LOCK_CONFLICT', 'lock cambió durante reclaim');
|
|
425
|
+
fs.unlinkSync(cuarentena);
|
|
426
|
+
sincronizarDirectorio(path.dirname(ruta));
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function recuperarGuardiaReclaim(guardia) {
|
|
430
|
+
const lock = parsearLock(guardia);
|
|
431
|
+
if (!puedeReclamar(lock)) fallar('LOCK_CONFLICT', 'reclaim ya está en curso');
|
|
432
|
+
cuarentenarLock(guardia, lock);
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
function adquirirGuardiaReclaim(ruta) {
|
|
436
|
+
const guardia = `${ruta}.reclaim`;
|
|
437
|
+
const owner = crearLockPropio();
|
|
438
|
+
try {
|
|
439
|
+
persistirLockNuevo(guardia, owner);
|
|
440
|
+
return { guardia, owner };
|
|
441
|
+
} catch (error) {
|
|
442
|
+
if (error.code !== 'EEXIST') throw error;
|
|
443
|
+
recuperarGuardiaReclaim(guardia);
|
|
444
|
+
return adquirirGuardiaReclaim(ruta);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function reclamarLock(ruta) {
|
|
449
|
+
const observado = parsearLock(ruta);
|
|
450
|
+
if (!puedeReclamar(observado)) fallar('LOCK_HELD', 'lock pertenece a proceso vivo');
|
|
451
|
+
const { guardia, owner } = adquirirGuardiaReclaim(ruta);
|
|
452
|
+
try {
|
|
453
|
+
const actual = parsearLock(ruta);
|
|
454
|
+
if (!locksIguales(observado, actual)) fallar('LOCK_CONFLICT', 'lock cambió antes de reclaim');
|
|
455
|
+
if (!puedeReclamar(actual)) fallar('LOCK_HELD', 'lock pertenece a proceso vivo');
|
|
456
|
+
cuarentenarLock(ruta, actual);
|
|
457
|
+
} finally {
|
|
458
|
+
eliminarLockVerificado(guardia, owner.ownerToken);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function bloquearSiReclaimEnCurso(ruta, ownerToken = null) {
|
|
463
|
+
const guardia = `${ruta}.reclaim`;
|
|
464
|
+
if (!fs.existsSync(guardia)) return;
|
|
465
|
+
try {
|
|
466
|
+
recuperarGuardiaReclaim(guardia);
|
|
467
|
+
} catch (error) {
|
|
468
|
+
if (ownerToken) liberarLock(ruta, ownerToken);
|
|
469
|
+
throw error;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function adquirirLock(ruta) {
|
|
474
|
+
hitFault('before-lock');
|
|
475
|
+
const valor = crearLockPropio();
|
|
476
|
+
validarDirectorioSeguro(path.dirname(ruta), true);
|
|
477
|
+
bloquearSiReclaimEnCurso(ruta);
|
|
478
|
+
try {
|
|
479
|
+
persistirLockNuevo(ruta, valor);
|
|
480
|
+
} catch (error) {
|
|
481
|
+
if (error.code !== 'EEXIST') throw error;
|
|
482
|
+
reclamarLock(ruta);
|
|
483
|
+
return adquirirLock(ruta);
|
|
484
|
+
}
|
|
485
|
+
bloquearSiReclaimEnCurso(ruta, valor.ownerToken);
|
|
486
|
+
hitFault('after-lock');
|
|
487
|
+
return valor;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function liberarLock(ruta, ownerToken) {
|
|
491
|
+
eliminarLockVerificado(ruta, ownerToken);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function liberarLockConCodigo(ruta, ownerToken) {
|
|
495
|
+
try {
|
|
496
|
+
liberarLock(ruta, ownerToken);
|
|
497
|
+
} catch (error) {
|
|
498
|
+
if (error.codigo !== 'LOCK_OWNER_MISMATCH') error.codigo = 'LOCK_RELEASE_FAILED';
|
|
499
|
+
throw error;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
function conLock(ruta, accion) {
|
|
504
|
+
const owner = adquirirLock(ruta);
|
|
505
|
+
let resultado;
|
|
506
|
+
let falla;
|
|
507
|
+
try {
|
|
508
|
+
resultado = accion();
|
|
509
|
+
} catch (error) {
|
|
510
|
+
falla = error;
|
|
511
|
+
}
|
|
512
|
+
liberarLockConCodigo(ruta, owner.ownerToken);
|
|
513
|
+
if (falla) throw falla;
|
|
514
|
+
return resultado;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function validarProviders(actuales, esperados) {
|
|
518
|
+
validarObjeto(actuales, 'TRUST_INVALID', 'providers');
|
|
519
|
+
validarObjeto(esperados, 'TRUST_INVALID', 'providers');
|
|
520
|
+
const a = canonicalizarIJson(actuales);
|
|
521
|
+
const b = canonicalizarIJson(esperados);
|
|
522
|
+
if (a !== b) fallar('PROVIDER_BINDING_INVALID', 'providers no coinciden');
|
|
523
|
+
for (const provider of Object.values(actuales)) {
|
|
524
|
+
const esperado = hashBytes(Buffer.from(provider.implementation));
|
|
525
|
+
if (provider.fingerprint !== esperado) {
|
|
526
|
+
fallar('PROVIDER_BINDING_INVALID', 'fingerprint built-in inválido');
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
function validarPin(pin, config) {
|
|
532
|
+
validarObjeto(pin, 'PROVISIONING_INVALID', 'pin de provisioning');
|
|
533
|
+
validarClaves(pin, PIN_KEYS, 'PROVISIONING_INVALID', 'pin de provisioning');
|
|
534
|
+
if (pin.schemaVersion !== '1.0.0' || !SHA256.test(pin.rootKeyDigest)) {
|
|
535
|
+
fallar('PROVISIONING_INVALID', 'pin de provisioning inválido');
|
|
536
|
+
}
|
|
537
|
+
if (!IDENTIFIER.test(pin.streamId)) fallar('PROVISIONING_INVALID', 'streamId inválido');
|
|
538
|
+
const receipt = config.receipt;
|
|
539
|
+
if (pin.rootKeyDigest !== receipt.rootKeyDigest
|
|
540
|
+
|| pin.trustPath !== receipt.trustPath
|
|
541
|
+
|| pin.signerPath !== receipt.signerPath
|
|
542
|
+
|| pin.anchorPath !== receipt.anchorPath) {
|
|
543
|
+
fallar('ROOT_BINDING_INVALID', 'receipt no coincide con provisioning externo');
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
function validarTrust(trust, config) {
|
|
548
|
+
const receipt = config.receipt;
|
|
549
|
+
validarObjeto(trust, 'TRUST_INVALID', 'trust externo');
|
|
550
|
+
validarClaves(trust, TRUST_KEYS, 'TRUST_INVALID', 'trust externo');
|
|
551
|
+
if (trust.schemaVersion !== '1.0.0' || trust.rootKeyDigest !== receipt.rootKeyDigest) {
|
|
552
|
+
fallar('ROOT_BINDING_INVALID', 'root externo no coincide');
|
|
553
|
+
}
|
|
554
|
+
if (trust.trustEpoch !== receipt.trustEpoch || trust.trustDigest !== receipt.trustDigest) {
|
|
555
|
+
fallar('TRUST_BINDING_INVALID', 'trust externo no coincide');
|
|
556
|
+
}
|
|
557
|
+
validarProviders(trust.providers, receipt.providers);
|
|
558
|
+
if (trust.signerPath !== receipt.signerPath || trust.anchorPath !== receipt.anchorPath) {
|
|
559
|
+
fallar('TRUST_BINDING_INVALID', 'locators externos no coinciden');
|
|
560
|
+
}
|
|
561
|
+
if (!IDENTIFIER.test(trust.integrityKeyId) || typeof trust.integrityPublicKey !== 'string') {
|
|
562
|
+
fallar('TRUST_INVALID', 'signer externo inválido');
|
|
563
|
+
}
|
|
564
|
+
if (trust.integrityKeyId !== config.signerKeyId) {
|
|
565
|
+
fallar('TRUST_BINDING_INVALID', 'keyId externo no coincide con receipt');
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function validarAnchor(anchor, config) {
|
|
570
|
+
validarObjeto(anchor, 'ANCHOR_INVALID', 'anchor');
|
|
571
|
+
validarClaves(anchor, ANCHOR_KEYS, 'ANCHOR_INVALID', 'anchor');
|
|
572
|
+
if (anchor.schemaVersion !== '1.0.0' || anchor.streamId !== config.streamId) {
|
|
573
|
+
fallar('ANCHOR_INVALID', 'anchor de otro stream');
|
|
574
|
+
}
|
|
575
|
+
if (!Number.isInteger(anchor.sequence) || anchor.sequence < 0 || !SHA256.test(anchor.headHash)) {
|
|
576
|
+
fallar('ANCHOR_INVALID', 'head externo inválido');
|
|
577
|
+
}
|
|
578
|
+
if (!Number.isInteger(anchor.generation) || anchor.generation !== anchor.sequence) {
|
|
579
|
+
fallar('ANCHOR_INVALID', 'generación externa inválida');
|
|
580
|
+
}
|
|
581
|
+
if (anchor.trustEpoch !== config.receipt.trustEpoch
|
|
582
|
+
|| anchor.trustDigest !== config.receipt.trustDigest) {
|
|
583
|
+
fallar('ANCHOR_TRUST_INVALID', 'anchor trust inválido');
|
|
584
|
+
}
|
|
585
|
+
try {
|
|
586
|
+
validarTimestampIso(anchor.lastTrustedTime, 'anchor lastTrustedTime');
|
|
587
|
+
} catch {
|
|
588
|
+
fallar('ANCHOR_INVALID', 'tiempo externo inválido');
|
|
589
|
+
}
|
|
590
|
+
return anchor;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
function leerAnchor(config) {
|
|
594
|
+
return validarAnchor(leerJson(config.anchorPath, 'ANCHOR_UNAVAILABLE', MAX_BYTES.anchor), config);
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
function eventoSinPruebas(evento) {
|
|
598
|
+
const unsigned = { ...evento };
|
|
599
|
+
delete unsigned.eventHash;
|
|
600
|
+
delete unsigned.signature;
|
|
601
|
+
return unsigned;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
function bytesFirmaEvento(unsigned) {
|
|
605
|
+
return Buffer.concat([
|
|
606
|
+
Buffer.from('swl-ses/integrity-ledger/v1\0', 'utf8'),
|
|
607
|
+
Buffer.from(canonicalizarIJson(unsigned), 'utf8'),
|
|
608
|
+
]);
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
function validarCabeceraEvento(evento, config) {
|
|
612
|
+
if (evento.schemaVersion !== '1.0.0' || evento.streamId !== config.streamId) {
|
|
613
|
+
fallar('LEDGER_INVALID', 'evento de otro stream');
|
|
614
|
+
}
|
|
615
|
+
if (!Number.isInteger(evento.sequence) || evento.sequence < 1) {
|
|
616
|
+
fallar('LEDGER_INVALID', 'secuencia inválida');
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
function validarDigestsEvento(evento) {
|
|
621
|
+
const digests = [evento.previousHash, evento.payloadDigest, evento.trustDigest, evento.eventHash];
|
|
622
|
+
if (digests.some((digest) => !SHA256.test(digest))) {
|
|
623
|
+
fallar('LEDGER_INVALID', 'digest inválido');
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
function validarIdentidadEvento(evento, config) {
|
|
628
|
+
if (!IDENTIFIER.test(evento.eventType) || !IDENTIFIER.test(evento.signerKeyId)) {
|
|
629
|
+
fallar('LEDGER_INVALID', 'identificador inválido');
|
|
630
|
+
}
|
|
631
|
+
if (evento.signerKeyId !== config.trust.integrityKeyId) {
|
|
632
|
+
fallar('LEDGER_INVALID', 'signer keyId no coincide');
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
function validarTrustEvento(evento, config) {
|
|
637
|
+
if (evento.trustEpoch !== config.receipt.trustEpoch
|
|
638
|
+
|| evento.trustDigest !== config.receipt.trustDigest) {
|
|
639
|
+
fallar('LEDGER_INVALID', 'trust de evento inválido');
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
function validarPayloadEvento(payload, codigo) {
|
|
644
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
|
|
645
|
+
fallar(codigo, 'payload inválido');
|
|
646
|
+
}
|
|
647
|
+
validarValorIJson(payload, 0);
|
|
648
|
+
const bytes = Buffer.byteLength(canonicalizarIJson(payload), 'utf8');
|
|
649
|
+
if (bytes > MAX_BYTES.payload) fallar(codigo, 'payload excede límite');
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
function validarEventoShape(evento, config) {
|
|
653
|
+
validarObjeto(evento, 'LEDGER_INVALID', 'evento');
|
|
654
|
+
validarClaves(evento, EVENT_KEYS, 'LEDGER_INVALID', 'evento');
|
|
655
|
+
validarCabeceraEvento(evento, config);
|
|
656
|
+
validarDigestsEvento(evento);
|
|
657
|
+
validarIdentidadEvento(evento, config);
|
|
658
|
+
validarPayloadEvento(evento.payload, 'LEDGER_INVALID');
|
|
659
|
+
validarTimestampIso(evento.timestamp, 'evento timestamp');
|
|
660
|
+
validarTrustEvento(evento, config);
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
function verificarEvento(evento, anterior, config) {
|
|
664
|
+
validarEventoShape(evento, config);
|
|
665
|
+
if (evento.sequence !== anterior.sequence + 1 || evento.previousHash !== anterior.headHash) {
|
|
666
|
+
fallar('LEDGER_INVALID', 'cadena no contigua');
|
|
667
|
+
}
|
|
668
|
+
if (anterior.lastTrustedTime && evento.timestamp < anterior.lastTrustedTime) {
|
|
669
|
+
fallar('CLOCK_ROLLBACK', 'tiempo del ledger retrocedió');
|
|
670
|
+
}
|
|
671
|
+
const unsigned = eventoSinPruebas(evento);
|
|
672
|
+
if (hashBytes(Buffer.from(canonicalizarIJson(evento.payload))) !== evento.payloadDigest) {
|
|
673
|
+
fallar('LEDGER_INVALID', 'payload alterado');
|
|
674
|
+
}
|
|
675
|
+
if (hashBytes(Buffer.from(canonicalizarIJson(unsigned))) !== evento.eventHash) {
|
|
676
|
+
fallar('LEDGER_INVALID', 'evento rehasheado');
|
|
677
|
+
}
|
|
678
|
+
let firmaValida = false;
|
|
679
|
+
try {
|
|
680
|
+
firmaValida = crypto.verify(
|
|
681
|
+
null, bytesFirmaEvento(unsigned), config.publicKey, Buffer.from(evento.signature, 'base64url')
|
|
682
|
+
);
|
|
683
|
+
} catch { /* firma inválida */ }
|
|
684
|
+
if (!firmaValida) fallar('SIGNATURE_INVALID', 'firma de evento inválida');
|
|
685
|
+
return {
|
|
686
|
+
sequence: evento.sequence,
|
|
687
|
+
headHash: evento.eventHash,
|
|
688
|
+
lastTrustedTime: evento.timestamp,
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
function parsearLedger(config) {
|
|
693
|
+
if (!fs.existsSync(config.ledgerPath)) return [];
|
|
694
|
+
const bytes = leerBytesEstables(config.ledgerPath, 'LEDGER_INVALID', MAX_BYTES.ledger);
|
|
695
|
+
if (bytes.length === 0) return [];
|
|
696
|
+
if (bytes[bytes.length - 1] !== 0x0A) fallar('LEDGER_INVALID', 'línea parcial');
|
|
697
|
+
try {
|
|
698
|
+
const lineas = dividirJsonl(bytes);
|
|
699
|
+
if (lineas.length > MAX_EVENTOS) fallar('LEDGER_INVALID', 'ledger excede eventos');
|
|
700
|
+
return lineas.map((linea) => parsearIJson(linea));
|
|
701
|
+
} catch {
|
|
702
|
+
fallar('LEDGER_INVALID', 'ledger JSONL inválido');
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
function dividirJsonl(bytes) {
|
|
707
|
+
const lineas = [];
|
|
708
|
+
let inicio = 0;
|
|
709
|
+
for (let indice = 0; indice < bytes.length; indice += 1) {
|
|
710
|
+
if (bytes[indice] !== 0x0A) continue;
|
|
711
|
+
if (indice === inicio) fallar('LEDGER_INVALID', 'línea vacía');
|
|
712
|
+
lineas.push(bytes.subarray(inicio, indice));
|
|
713
|
+
inicio = indice + 1;
|
|
714
|
+
}
|
|
715
|
+
return lineas;
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
function verificarLedger(config) {
|
|
719
|
+
const eventos = parsearLedger(config);
|
|
720
|
+
let tip = { sequence: 0, headHash: ZERO, lastTrustedTime: config.receipt.issuedAt };
|
|
721
|
+
for (const evento of eventos) tip = verificarEvento(evento, tip, config);
|
|
722
|
+
return { ...tip, events: eventos };
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
function anchorsIguales(anchor, tip) {
|
|
726
|
+
return anchor.sequence === tip.sequence
|
|
727
|
+
&& anchor.headHash === tip.headHash
|
|
728
|
+
&& anchor.lastTrustedTime >= tip.lastTrustedTime
|
|
729
|
+
&& anchor.generation === tip.sequence;
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
function expectedAnchor(anchor) {
|
|
733
|
+
return {
|
|
734
|
+
streamId: anchor.streamId, sequence: anchor.sequence, headHash: anchor.headHash,
|
|
735
|
+
trustEpoch: anchor.trustEpoch, trustDigest: anchor.trustDigest,
|
|
736
|
+
lastTrustedTime: anchor.lastTrustedTime, generation: anchor.generation,
|
|
737
|
+
};
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
function anchorCoincide(anchor, expected) {
|
|
741
|
+
return Object.entries(expected).every(([clave, valor]) => anchor[clave] === valor);
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
function publicarAnchor(config, expected, siguiente) {
|
|
745
|
+
return conLock(`${config.anchorPath}.lock`, () => {
|
|
746
|
+
const actual = leerAnchor(config);
|
|
747
|
+
if (!anchorCoincide(actual, expected)) fallar('ANCHOR_CAS_CONFLICT', 'CAS externo rechazado');
|
|
748
|
+
escrituraAtomica(
|
|
749
|
+
config.anchorPath,
|
|
750
|
+
Buffer.from(`${canonicalizarIJson(siguiente)}\n`),
|
|
751
|
+
'anchor'
|
|
752
|
+
);
|
|
753
|
+
hitFault('anchor-updated-before-response');
|
|
754
|
+
return siguiente;
|
|
755
|
+
});
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
function confirmarAnchor(config, expected, siguiente) {
|
|
759
|
+
try {
|
|
760
|
+
return publicarAnchor(config, expected, siguiente);
|
|
761
|
+
} catch (error) {
|
|
762
|
+
const noAmbiguo = ['ANCHOR_CAS_CONFLICT', 'LOCK_OWNER_MISMATCH', 'LOCK_RELEASE_FAILED'];
|
|
763
|
+
if (noAmbiguo.includes(error.codigo)) throw error;
|
|
764
|
+
try {
|
|
765
|
+
const observado = leerAnchor(config);
|
|
766
|
+
if (anchorCoincide(observado, expectedAnchor(siguiente))) return observado;
|
|
767
|
+
} catch { /* conservar la falla original si el resultado es ambiguo */ }
|
|
768
|
+
throw error;
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
function avanzarTiempoAutoridad(config, anchor, observedAt) {
|
|
773
|
+
validarVigencia(config.receipt, anchor, observedAt);
|
|
774
|
+
if (observedAt === anchor.lastTrustedTime) return anchor;
|
|
775
|
+
return confirmarAnchor(config, expectedAnchor(anchor), {
|
|
776
|
+
...anchor, lastTrustedTime: observedAt,
|
|
777
|
+
});
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
function avanzarAnchor(config, anchor, state, observedAt) {
|
|
781
|
+
const primerPendiente = state.events[anchor.sequence];
|
|
782
|
+
if (!primerPendiente || primerPendiente.previousHash !== anchor.headHash) {
|
|
783
|
+
fallar('ANCHOR_DIVERGED', 'anchor no es prefijo del ledger');
|
|
784
|
+
}
|
|
785
|
+
const ultimo = state.events[state.events.length - 1];
|
|
786
|
+
if (primerPendiente.timestamp < anchor.lastTrustedTime) {
|
|
787
|
+
fallar('CLOCK_ROLLBACK', 'sufijo local reduce el tiempo confiable');
|
|
788
|
+
}
|
|
789
|
+
if (ultimo.timestamp > observedAt) fallar('CLOCK_FUTURE', 'sufijo local está en el futuro');
|
|
790
|
+
const siguiente = {
|
|
791
|
+
schemaVersion: '1.0.0', streamId: config.streamId,
|
|
792
|
+
sequence: state.sequence, headHash: state.headHash,
|
|
793
|
+
trustEpoch: config.receipt.trustEpoch, trustDigest: config.receipt.trustDigest,
|
|
794
|
+
lastTrustedTime: [anchor.lastTrustedTime, ultimo.timestamp].sort().at(-1),
|
|
795
|
+
generation: anchor.generation + (state.sequence - anchor.sequence),
|
|
796
|
+
};
|
|
797
|
+
return confirmarAnchor(config, expectedAnchor(anchor), siguiente);
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
function reconciliar(config, state, observedAt) {
|
|
801
|
+
const anchor = leerAnchor(config);
|
|
802
|
+
validarVigencia(config.receipt, anchor, observedAt);
|
|
803
|
+
if (anchorsIguales(anchor, state)) return anchor;
|
|
804
|
+
if (anchor.sequence > state.sequence) fallar('ANCHOR_AHEAD', 'workspace restaurado o stale');
|
|
805
|
+
if (anchor.sequence === state.sequence) fallar('ANCHOR_DIVERGED', 'anchor divergente');
|
|
806
|
+
return avanzarAnchor(config, anchor, state, observedAt);
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
function serializarSnapshot(config, state, anchor) {
|
|
810
|
+
return `${canonicalizarIJson({
|
|
811
|
+
schemaVersion: '1.0.0', streamId: config.streamId,
|
|
812
|
+
sequence: state.sequence, headHash: state.headHash,
|
|
813
|
+
anchorGeneration: anchor.generation, eventCount: state.events.length,
|
|
814
|
+
})}\n`;
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
function publicarSnapshot(config, state, anchor) {
|
|
818
|
+
escrituraAtomica(
|
|
819
|
+
config.snapshotPath,
|
|
820
|
+
Buffer.from(serializarSnapshot(config, state, anchor)),
|
|
821
|
+
'snapshot'
|
|
822
|
+
);
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
function estadoPublico(config, state) {
|
|
826
|
+
const valor = {
|
|
827
|
+
streamId: config.streamId, sequence: state.sequence,
|
|
828
|
+
headHash: state.headHash, events: state.events.map((evento) => structuredClone(evento)),
|
|
829
|
+
};
|
|
830
|
+
return congelarProfundo(valor);
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
function leerVerificado(config) {
|
|
834
|
+
const observedAt = new Date().toISOString();
|
|
835
|
+
const state = verificarLedger(config);
|
|
836
|
+
hitFault('after-reread');
|
|
837
|
+
const anchor = reconciliar(config, state, observedAt);
|
|
838
|
+
validarVigencia(config.receipt, anchor, observedAt);
|
|
839
|
+
publicarSnapshot(config, state, anchor);
|
|
840
|
+
return estadoPublico(config, state);
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
function validarEntradaAppend(entrada, esAutoridad = false) {
|
|
844
|
+
validarObjeto(entrada, 'EVENT_INVALID', 'append');
|
|
845
|
+
validarClaves(entrada, APPEND_KEYS, 'EVENT_INVALID', 'append');
|
|
846
|
+
if (!Number.isInteger(entrada.expectedSequence) || entrada.expectedSequence < 0
|
|
847
|
+
|| !SHA256.test(entrada.expectedHeadHash)) {
|
|
848
|
+
fallar('EVENT_INVALID', 'precondición CAS inválida');
|
|
849
|
+
}
|
|
850
|
+
if (!IDENTIFIER.test(entrada.eventType)) fallar('EVENT_INVALID', 'eventType inválido');
|
|
851
|
+
if (!esAutoridad && RESERVED_EVENT_PREFIXES.some(
|
|
852
|
+
(prefijo) => entrada.eventType.startsWith(prefijo)
|
|
853
|
+
)) {
|
|
854
|
+
fallar('EVENT_TYPE_RESERVED', 'eventType reservado para el kernel');
|
|
855
|
+
}
|
|
856
|
+
validarPayloadEvento(entrada.payload, 'EVENT_INVALID');
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
function crearEvento(config, previo, entrada, timestamp) {
|
|
860
|
+
const unsigned = {
|
|
861
|
+
schemaVersion: '1.0.0', streamId: config.streamId, sequence: previo.sequence + 1,
|
|
862
|
+
previousHash: previo.headHash, eventType: entrada.eventType,
|
|
863
|
+
payload: structuredClone(entrada.payload),
|
|
864
|
+
payloadDigest: hashBytes(Buffer.from(canonicalizarIJson(entrada.payload))),
|
|
865
|
+
timestamp, trustEpoch: config.receipt.trustEpoch, trustDigest: config.receipt.trustDigest,
|
|
866
|
+
signerKeyId: config.trust.integrityKeyId,
|
|
867
|
+
};
|
|
868
|
+
const eventHash = hashBytes(Buffer.from(canonicalizarIJson(unsigned)));
|
|
869
|
+
const signature = crypto.sign(
|
|
870
|
+
null, bytesFirmaEvento(unsigned), config.privateKey
|
|
871
|
+
).toString('base64url');
|
|
872
|
+
return { ...unsigned, eventHash, signature };
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
function persistirLedger(config, events) {
|
|
876
|
+
const bytes = Buffer.from(events.map((evento) => canonicalizarIJson(evento)).join('\n') + '\n');
|
|
877
|
+
if (events.length > MAX_EVENTOS || bytes.length > MAX_BYTES.ledger) {
|
|
878
|
+
fallar('LEDGER_LIMIT_EXCEEDED', 'ledger excede límite');
|
|
879
|
+
}
|
|
880
|
+
escrituraAtomica(config.ledgerPath, bytes, 'ledger');
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
function crearReceiptAppend(config, expected, state, anchor) {
|
|
884
|
+
const receipt = congelarProfundo({
|
|
885
|
+
kind: 'integrity-ledger-append-receipt', streamId: config.streamId,
|
|
886
|
+
expectedSequence: expected.sequence, expectedHeadHash: expected.headHash,
|
|
887
|
+
expectedAnchorGeneration: expected.generation,
|
|
888
|
+
sequence: state.sequence, headHash: state.headHash,
|
|
889
|
+
anchorGeneration: anchor.generation,
|
|
890
|
+
trustEpoch: anchor.trustEpoch, trustDigest: anchor.trustDigest,
|
|
891
|
+
});
|
|
892
|
+
APPEND_RECEIPTS.add(receipt);
|
|
893
|
+
return receipt;
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
function append(config, entrada, esAutoridad = false) {
|
|
897
|
+
validarEntradaAppend(entrada, esAutoridad);
|
|
898
|
+
return conLock(config.lockPath, () => {
|
|
899
|
+
const observedAt = new Date().toISOString();
|
|
900
|
+
const previo = verificarLedger(config);
|
|
901
|
+
hitFault('after-reread');
|
|
902
|
+
const anchorPrevio = reconciliar(config, previo, observedAt);
|
|
903
|
+
if (entrada.expectedSequence !== previo.sequence
|
|
904
|
+
|| entrada.expectedHeadHash !== previo.headHash) {
|
|
905
|
+
fallar('LEDGER_CAS_CONFLICT', 'precondición local cambió');
|
|
906
|
+
}
|
|
907
|
+
const evento = crearEvento(config, previo, entrada, observedAt);
|
|
908
|
+
const events = [...previo.events, evento];
|
|
909
|
+
persistirLedger(config, events);
|
|
910
|
+
hitFault('local-durable-before-anchor-cas');
|
|
911
|
+
const state = verificarLedger(config);
|
|
912
|
+
const anchor = avanzarAnchor(config, anchorPrevio, state, observedAt);
|
|
913
|
+
publicarSnapshot(config, state, anchor);
|
|
914
|
+
return crearReceiptAppend(config, anchorPrevio, state, anchor);
|
|
915
|
+
});
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
function mutarCasEnPruebas(entrada) {
|
|
919
|
+
if (process.env.SWL_INTEGRITY_FAULT !== 'before-transact-cas-check') return entrada;
|
|
920
|
+
return { ...entrada, expectedSequence: entrada.expectedSequence + 1 };
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
function transact(config, action) {
|
|
924
|
+
return conLock(config.lockPath, () => {
|
|
925
|
+
const observedAt = new Date().toISOString();
|
|
926
|
+
const previo = verificarLedger(config);
|
|
927
|
+
hitFault('after-reread');
|
|
928
|
+
const reconciliado = reconciliar(config, previo, observedAt);
|
|
929
|
+
const anchorPrevio = avanzarTiempoAutoridad(config, reconciliado, observedAt);
|
|
930
|
+
const authority = crearAuthorityReceipt(config, previo, anchorPrevio);
|
|
931
|
+
const entrada = mutarCasEnPruebas(action(estadoPublico(config, previo), authority));
|
|
932
|
+
validarEntradaAppend(entrada, true);
|
|
933
|
+
if (entrada.expectedSequence !== previo.sequence
|
|
934
|
+
|| entrada.expectedHeadHash !== previo.headHash) {
|
|
935
|
+
fallar('LEDGER_CAS_CONFLICT', 'precondición semántica cambió');
|
|
936
|
+
}
|
|
937
|
+
const evento = crearEvento(config, previo, entrada, observedAt);
|
|
938
|
+
const events = [...previo.events, evento];
|
|
939
|
+
persistirLedger(config, events);
|
|
940
|
+
hitFault('local-durable-before-anchor-cas');
|
|
941
|
+
const state = verificarLedger(config);
|
|
942
|
+
const anchor = avanzarAnchor(config, anchorPrevio, state, observedAt);
|
|
943
|
+
publicarSnapshot(config, state, anchor);
|
|
944
|
+
return crearReceiptAppend(config, anchorPrevio, state, anchor);
|
|
945
|
+
});
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
function inspect(config, action) {
|
|
949
|
+
return conLock(config.lockPath, () => {
|
|
950
|
+
const observedAt = new Date().toISOString();
|
|
951
|
+
const state = verificarLedger(config);
|
|
952
|
+
hitFault('after-reread');
|
|
953
|
+
const reconciliado = reconciliar(config, state, observedAt);
|
|
954
|
+
const anchor = avanzarTiempoAutoridad(config, reconciliado, observedAt);
|
|
955
|
+
const authority = crearAuthorityReceipt(config, state, anchor);
|
|
956
|
+
const result = action(estadoPublico(config, state), authority);
|
|
957
|
+
publicarSnapshot(config, state, anchor);
|
|
958
|
+
return result;
|
|
959
|
+
});
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
function crearAuthorityReceipt(config, state, anchor) {
|
|
963
|
+
const receipt = congelarProfundo({
|
|
964
|
+
kind: 'kernel-authority-receipt', streamId: config.streamId,
|
|
965
|
+
rootKeyDigest: config.receipt.rootKeyDigest,
|
|
966
|
+
sequence: state.sequence, headHash: state.headHash,
|
|
967
|
+
trustEpoch: anchor.trustEpoch, trustDigest: anchor.trustDigest,
|
|
968
|
+
lastTrustedTime: anchor.lastTrustedTime, observedAt: anchor.lastTrustedTime,
|
|
969
|
+
});
|
|
970
|
+
AUTHORITY_RECEIPTS.add(receipt);
|
|
971
|
+
return receipt;
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
function leerAutoridad(config) {
|
|
975
|
+
const observedAt = new Date().toISOString();
|
|
976
|
+
const state = verificarLedger(config);
|
|
977
|
+
hitFault('after-reread');
|
|
978
|
+
const reconciliado = reconciliar(config, state, observedAt);
|
|
979
|
+
const anchor = avanzarTiempoAutoridad(config, reconciliado, observedAt);
|
|
980
|
+
validarVigencia(config.receipt, anchor, observedAt);
|
|
981
|
+
publicarSnapshot(config, state, anchor);
|
|
982
|
+
return crearAuthorityReceipt(config, state, anchor);
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
function validarVigencia(receipt, anchor, now) {
|
|
986
|
+
if (now < receipt.issuedAt || now > receipt.expiresAt) {
|
|
987
|
+
fallar('BOOTSTRAP_EXPIRED', 'bootstrap fuera de vigencia');
|
|
988
|
+
}
|
|
989
|
+
if (now < anchor.lastTrustedTime) fallar('CLOCK_ROLLBACK', 'reloj detrás del anchor');
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
function validarValorIJson(valor, profundidad) {
|
|
993
|
+
if (profundidad > 64) fallar('EVENT_INVALID', 'payload demasiado profundo');
|
|
994
|
+
if (valor === null || typeof valor === 'string' || typeof valor === 'boolean') return;
|
|
995
|
+
if (typeof valor === 'number' && Number.isFinite(valor)) return;
|
|
996
|
+
if (!valor || typeof valor !== 'object' || util.types.isProxy(valor)) {
|
|
997
|
+
fallar('EVENT_INVALID', 'payload inválido');
|
|
998
|
+
}
|
|
999
|
+
const proto = Object.getPrototypeOf(valor);
|
|
1000
|
+
const permitido = Array.isArray(valor)
|
|
1001
|
+
? proto === Array.prototype
|
|
1002
|
+
: proto === Object.prototype || proto === null;
|
|
1003
|
+
if (!permitido || Object.getOwnPropertySymbols(valor).length > 0) {
|
|
1004
|
+
fallar('EVENT_INVALID', 'payload inválido');
|
|
1005
|
+
}
|
|
1006
|
+
for (const [clave, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(valor))) {
|
|
1007
|
+
if (Array.isArray(valor) && clave === 'length') continue;
|
|
1008
|
+
if (!descriptor.enumerable || !('value' in descriptor)) {
|
|
1009
|
+
fallar('EVENT_INVALID', 'payload inválido');
|
|
1010
|
+
}
|
|
1011
|
+
validarValorIJson(descriptor.value, profundidad + 1);
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
function cargarPrivateKey(config) {
|
|
1016
|
+
const privateBytes = leerBytesEstables(
|
|
1017
|
+
config.receipt.signerPath, 'SIGNER_UNAVAILABLE', MAX_BYTES.signer
|
|
1018
|
+
);
|
|
1019
|
+
try {
|
|
1020
|
+
const privateKey = crypto.createPrivateKey(privateBytes);
|
|
1021
|
+
if (privateKey.asymmetricKeyType !== 'ed25519') {
|
|
1022
|
+
fallar('SIGNER_INVALID', 'signer no es Ed25519');
|
|
1023
|
+
}
|
|
1024
|
+
return privateKey;
|
|
1025
|
+
} catch {
|
|
1026
|
+
fallar('SIGNER_INVALID', 'signer no es una llave privada');
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
function cargarPublicKey(trust) {
|
|
1031
|
+
try {
|
|
1032
|
+
const publicKey = crypto.createPublicKey(trust.integrityPublicKey);
|
|
1033
|
+
if (publicKey.asymmetricKeyType !== 'ed25519') {
|
|
1034
|
+
fallar('TRUST_INVALID', 'llave externa no Ed25519');
|
|
1035
|
+
}
|
|
1036
|
+
return publicKey;
|
|
1037
|
+
} catch {
|
|
1038
|
+
fallar('TRUST_INVALID', 'llave pública externa inválida');
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
function validarParFirmante(config, privateKey, publicKey) {
|
|
1043
|
+
const derivada = crypto.createPublicKey(privateKey).export({ format: 'der', type: 'spki' });
|
|
1044
|
+
const esperada = publicKey.export({ format: 'der', type: 'spki' });
|
|
1045
|
+
if (!Buffer.from(derivada).equals(Buffer.from(esperada))) {
|
|
1046
|
+
fallar('SIGNER_INVALID', 'signer no coincide con trust externo');
|
|
1047
|
+
}
|
|
1048
|
+
if (hashBytes(esperada) !== config.signerPublicKeyDigest) {
|
|
1049
|
+
fallar('TRUST_BINDING_INVALID', 'llave externa no coincide con receipt');
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
function cargarMaterial(config) {
|
|
1054
|
+
const provisioningPath = process.env.SWL_KERNEL_PROVISIONING_PATH;
|
|
1055
|
+
if (!provisioningPath || !path.isAbsolute(provisioningPath)) {
|
|
1056
|
+
fallar('PROVISIONING_UNAVAILABLE', 'provisioning externo no configurado');
|
|
1057
|
+
}
|
|
1058
|
+
validarRutaExternaSegura(provisioningPath, config.workspaceRoot);
|
|
1059
|
+
for (const ruta of [config.receipt.trustPath, config.receipt.signerPath, config.anchorPath]) {
|
|
1060
|
+
validarRutaExternaSegura(ruta, config.workspaceRoot);
|
|
1061
|
+
}
|
|
1062
|
+
const pin = leerJson(provisioningPath, 'PROVISIONING_UNAVAILABLE', MAX_BYTES.provisioning);
|
|
1063
|
+
validarPin(pin, config);
|
|
1064
|
+
const trust = leerJson(config.receipt.trustPath, 'TRUST_UNAVAILABLE', MAX_BYTES.trust);
|
|
1065
|
+
validarTrust(trust, config);
|
|
1066
|
+
const privateKey = cargarPrivateKey(config);
|
|
1067
|
+
const publicKey = cargarPublicKey(trust);
|
|
1068
|
+
validarParFirmante(config, privateKey, publicKey);
|
|
1069
|
+
return { pin, privateKey, publicKey, trust };
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
function crearPaths(workspaceRoot, streamId) {
|
|
1073
|
+
const nombre = hashBytes(Buffer.from(streamId)).slice(0, 24);
|
|
1074
|
+
validarDirectorioSeguro(workspaceRoot);
|
|
1075
|
+
const planning = path.join(workspaceRoot, '.planning');
|
|
1076
|
+
asegurarDirectorio(planning, false);
|
|
1077
|
+
const directorio = path.join(planning, 'integrity');
|
|
1078
|
+
asegurarDirectorio(directorio);
|
|
1079
|
+
return {
|
|
1080
|
+
ledgerPath: path.join(directorio, `${nombre}.jsonl`),
|
|
1081
|
+
lockPath: path.join(directorio, `${nombre}.lock`),
|
|
1082
|
+
snapshotPath: path.join(directorio, `${nombre}.snapshot.json`),
|
|
1083
|
+
};
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
function crearLedger(config) {
|
|
1087
|
+
const paths = congelarProfundo({
|
|
1088
|
+
ledger: config.ledgerPath, lock: config.lockPath, snapshot: config.snapshotPath,
|
|
1089
|
+
});
|
|
1090
|
+
return Object.freeze({
|
|
1091
|
+
append: (entrada) => append(config, entrada),
|
|
1092
|
+
isAppendReceipt: (receipt) => APPEND_RECEIPTS.has(receipt),
|
|
1093
|
+
isAuthorityReceipt: (receipt) => AUTHORITY_RECEIPTS.has(receipt),
|
|
1094
|
+
paths,
|
|
1095
|
+
read: () => conLock(config.lockPath, () => leerVerificado(config)),
|
|
1096
|
+
readAuthority: () => conLock(config.lockPath, () => leerAutoridad(config)),
|
|
1097
|
+
recover: () => conLock(config.lockPath, () => leerVerificado(config)),
|
|
1098
|
+
});
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
function crearAuthorityWriter(config) {
|
|
1102
|
+
return Object.freeze({
|
|
1103
|
+
inspect: (action) => inspect(config, action),
|
|
1104
|
+
transact: (action) => transact(config, action),
|
|
1105
|
+
});
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
function createBuiltInKernelRuntime({
|
|
1109
|
+
receipt, workspaceRoot, signerKeyId, signerPublicKeyDigest,
|
|
1110
|
+
}) {
|
|
1111
|
+
const validators = getContractValidators();
|
|
1112
|
+
validarBackendArchivos();
|
|
1113
|
+
const config = {
|
|
1114
|
+
receipt, workspaceRoot, signerKeyId, signerPublicKeyDigest,
|
|
1115
|
+
anchorPath: receipt.anchorPath,
|
|
1116
|
+
};
|
|
1117
|
+
Object.assign(config, cargarMaterial(config));
|
|
1118
|
+
config.streamId = config.pin.streamId;
|
|
1119
|
+
Object.assign(config, crearPaths(workspaceRoot, config.streamId));
|
|
1120
|
+
const anchor = leerAnchor(config);
|
|
1121
|
+
validarVigencia(receipt, anchor, new Date().toISOString());
|
|
1122
|
+
const integrityLedger = crearLedger(config);
|
|
1123
|
+
integrityLedger.read();
|
|
1124
|
+
const authorityWriter = crearAuthorityWriter(config);
|
|
1125
|
+
const contexts = createPolicyContextProvider(authorityWriter);
|
|
1126
|
+
const stores = createSingleUseStore(authorityWriter);
|
|
1127
|
+
const singleUseStore = stores.publicStore;
|
|
1128
|
+
const gates = createGateEngine(authorityWriter, singleUseStore, workspaceRoot);
|
|
1129
|
+
const policyBroker = createPolicyBroker({
|
|
1130
|
+
compileBundle: compilarPolicyBundle,
|
|
1131
|
+
contextReader: contexts.authorizationContextReader,
|
|
1132
|
+
gateReader: gates.authorizationGateReader,
|
|
1133
|
+
grantIssuer: stores.authorizationGrantIssuer,
|
|
1134
|
+
isVerifiedOperation: validators.isVerifiedOperation,
|
|
1135
|
+
workspaceRoot,
|
|
1136
|
+
writer: authorityWriter,
|
|
1137
|
+
});
|
|
1138
|
+
return congelarProfundo({
|
|
1139
|
+
gateEngine: gates.publicGateEngine, integrityLedger,
|
|
1140
|
+
policyContextProvider: contexts.publicProvider,
|
|
1141
|
+
policyBroker,
|
|
1142
|
+
providers: structuredClone(receipt.providers),
|
|
1143
|
+
singleUseStore,
|
|
1144
|
+
});
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
module.exports = { createBuiltInKernelRuntime };
|