-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
6699 lines (6254 loc) · 294 KB
/
Copy pathserver.js
File metadata and controls
6699 lines (6254 loc) · 294 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================================================
// UMBRAXON KYA-Hub — Phase 1 Server
// ============================================================================
// Beží pod PM2 (ecosystem.config.js). Konfigurácia v .env.
// Endpointy:
// GET /api/health — server/DB/BTCPay/Alby health
// GET / — unified www portal (live + whitelist + pay + CLI + docs)
// GET /bots/* — legacy path → 301 redirect to /
// GET /api/tiers — zoznam tierov
// POST /api/v1/register — M2M registrácia (canonical)
// POST /api/register/initiate — legacy alias (same handler)
// POST /api/pay — deprecated (410 → use /api/v1/register)
// GET /api/check-status/:invoiceId — polling stavu faktúry
// POST /api/webhook/btcpay — BTCPay webhook (HMAC validovaný)
// POST /api/webhook/alby — Alby Hub webhook (sig validovaný)
// GET /api/dashboard — admin-only zoznam agentov
// GET /api/admin/ops-summary — admin-only JSON (ops agregáty + posledné rejections)
//
// Bezpečnosť:
// - helmet.js security headers
// - CORS whitelist (z CORS_ALLOWED_ORIGINS env)
// - express-rate-limit
// - HMAC timing-safe verify
// - Admin auth cez X-Admin-Key header
// - Idempotency cez webhook_deliveries tabuľku
// - pino structured logging
// - DB user `kyahub_app` s least-privilege
// ============================================================================
require('dotenv').config({ override: true });
const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const rateLimit = require('express-rate-limit');
const { Pool } = require('pg');
const axios = require('axios');
const crypto = require('crypto');
const path = require('path');
const HUB_PACKAGE_JSON = require('./package.json');
/** Semver for ops + `/api/health`; override with `HUB_VERSION` in `.env` if needed. */
const HUB_RELEASE_VERSION = (process.env.HUB_VERSION || HUB_PACKAGE_JSON.version || 'unknown').trim();
/** Human-readable release track (not manifest `protocol_version`). */
const HUB_RELEASE_PHASE = (process.env.HUB_RELEASE_PHASE || 'Integrations v1').trim();
const logger = require('./lib/logger');
const security = require('./lib/security');
const alby = require('./lib/alby');
const hubkeys = require('./lib/hubkeys');
const manifestSchema = require('./lib/manifest-schema');
const integrationsManifest = require('./lib/integrations-manifest');
const apiV1Register = require('./lib/api-v1-register');
const registerStatus = require('./lib/register-status');
const delegationPass = require('./lib/delegation-pass');
const developerWebhooks = require('./lib/developer-webhooks');
const certs = require('./lib/certs');
const reputation = require('./lib/reputation');
const repEngine = require('./lib/reputation-engine');
const zoneRateLimiter = require('./lib/zone-rate-limiter');
const abuseTracker = require('./lib/abuse-tracker');
const pow = require('./lib/pow');
const http403Tracker = require('./lib/http-403-tracker');
const { allocateSequentialKyaId } = require('./lib/allocate-kya-id');
const decayWorker = require('./lib/decay-worker');
const eliteListing = require('./lib/elite-listing');
const appealService = require('./lib/appeal-service');
const retireService = require('./lib/retire-service');
const dataExportService = require('./lib/data-export-service');
const metrics = require('./lib/metrics');
const { fetchOpsSummaryFull } = require('./lib/ops-summary-data');
const filePermWatcher = require('./lib/file-perm-watcher');
const sybilResistance = require('./lib/sybil-resistance');
const pricing = require('./lib/pricing');
const retentionWorker = require('./lib/retention-worker');
const notifications = require('./lib/notifications');
const sentry = require('./lib/sentry');
const breaker = require('./lib/circuit-breaker');
const certIssuanceBreaker = require('./lib/cert-issuance-breaker');
const volumetricLimits = require('./lib/volumetric-limits');
const forkDetector = require('./lib/fork-detector');
const anchorLib = require('./lib/anchor');
const bitcoindRpc = require('./lib/bitcoind-rpc');
const crlLib = require('./lib/crl');
const manufacturer = require('./lib/manufacturer');
// Strategic Sprint §31 D — A+B+D no-custody penalty system (registration quote
// with re-registration multiplier + pubkey deny-list cooldown).
const regQuote = require('./lib/registration-quote');
const sponsorInvite = require('./lib/sponsor-invite');
const platformIntegrator = require('./lib/platform-integrator');
const developerApiAuth = require('./lib/developer-api-auth');
const developerApiKeys = require('./lib/developer-api-keys');
const developerWebhookQueue = require('./lib/developer-webhook-queue');
const integratorLsat = require('./lib/integrator-lsat');
const integratorKeyRequests = require('./lib/integrator-key-requests');
const integratorSandbox = require('./lib/platform-integrator-sandbox');
const platformIntegratorRoutes = require('./lib/routes/platform-integrator-routes');
const registrationIpCap = require('./lib/registration-ip-cap');
const protocolEconomics = require('./lib/protocol-economics');
const protocolPublicMetrics = require('./lib/protocol-public-metrics');
const httpPublicError = require('./lib/http-public-error');
// Strategic Sprint §31 C — PDF invoice generator.
const invoicePdf = require('./lib/invoice-pdf');
// Konfigurovateľný timestamp skew tolerance (default 5 min). Phase 2.4.
const TIMESTAMP_SKEW_MS = parseInt(process.env.TIMESTAMP_SKEW_MS || String(5 * 60 * 1000), 10);
// ----------------------------------------------------------------------------
// Konfigurácia + validácia env
// ----------------------------------------------------------------------------
const cfg = {
PORT: parseInt(process.env.PORT || '3000', 10),
NODE_ENV: process.env.NODE_ENV || 'development',
HUB_SECRET: process.env.HUB_SECRET,
ADMIN_API_KEY: process.env.ADMIN_API_KEY,
BTCPAY_URL: process.env.BTCPAY_URL,
BTCPAY_API_KEY: process.env.BTCPAY_API_KEY,
BTCPAY_STORE_ID: process.env.BTCPAY_STORE_ID,
BTCPAY_WEBHOOK_SECRET: process.env.BTCPAY_WEBHOOK_SECRET,
ALBY_NWC_URI: process.env.ALBY_NWC_URI || '',
ALBY_WEBHOOK_SECRET: process.env.ALBY_WEBHOOK_SECRET || '',
REDIRECT_URL: process.env.REDIRECT_URL || 'https://umbraxon.xyz/dashboard',
DB: {
// Preferuj least-privilege app usera ak heslo k nemu existuje
user: process.env.KYAHUB_APP_PASSWORD ? 'kyahub_app' : (process.env.DB_USER || 'postgres'),
host: process.env.DB_HOST || '127.0.0.1',
database: process.env.DB_NAME || 'kyahub',
password: process.env.KYAHUB_APP_PASSWORD || process.env.DB_PASSWORD || '',
port: parseInt(process.env.DB_PORT || '5432', 10),
// Pool tuning (Phase 2.4 follow-up):
// max=20 stačí pre 1k+ botov s krátkymi queries; pri >5k botov nasadíme PgBouncer.
max: parseInt(process.env.DB_POOL_MAX || '20', 10),
min: parseInt(process.env.DB_POOL_MIN || '2', 10),
idleTimeoutMillis: parseInt(process.env.DB_POOL_IDLE_MS || '30000', 10),
connectionTimeoutMillis: parseInt(process.env.DB_POOL_CONN_TIMEOUT_MS || '5000', 10),
// Server-side query timeout (statement_timeout) — chráni pred runaway SELECTmi
statement_timeout: parseInt(process.env.DB_STATEMENT_TIMEOUT_MS || '10000', 10),
query_timeout: parseInt(process.env.DB_QUERY_TIMEOUT_MS || '15000', 10),
}
};
const required = ['HUB_SECRET', 'BTCPAY_URL', 'BTCPAY_API_KEY', 'BTCPAY_STORE_ID', 'BTCPAY_WEBHOOK_SECRET'];
const missing = required.filter(k => !cfg[k]);
if (missing.length) {
logger.fatal({ missing }, 'Chýbajú povinné env premenné, exit.');
process.exit(1);
}
if (!cfg.ADMIN_API_KEY) {
logger.warn('ADMIN_API_KEY nie je nastavené — /api/dashboard bude odmietať všetko (503)');
}
if (!alby.isConfigured()) {
logger.warn('ALBY_NWC_URI / secrets file nie je nastavené — Lightning platby cez Alby Hub vypnuté (fallback iba BTCPay LNURL)');
} else if (!cfg.ALBY_NWC_URI) {
logger.info('ALBY_NWC_URI env prázdne — používa sa ALBY_NWC_URI_FILE / .secrets/alby-nwc.txt');
}
// ----------------------------------------------------------------------------
// Tiery (Phase 2.4: hot-reloadable cez lib/pricing.js + tier_pricing DB tabuľka)
//
// TIERS proxy expose-uje aktuálne hodnoty cache-nuté z pricing modulu.
// Pri update cez /api/admin/pricing sa snapshot reloaduje automaticky.
// ----------------------------------------------------------------------------
const TIERS = new Proxy({}, {
get(_target, prop) {
if (prop !== 'BASIC' && prop !== 'ELITE') return undefined;
const p = pricing.getTier(prop);
if (!p) return undefined;
return {
total: p.amount_sats,
grade: p.grade,
durationMonths: p.duration_months,
requiresAnchor: !!p.requires_anchor,
baseReputation: reputation.STARTING_SCORE[prop],
};
},
});
function getTierByAmount(amount) {
const val = parseInt(amount, 10);
if (TIERS.ELITE && val === TIERS.ELITE.total) return { ...TIERS.ELITE, name: 'ELITE' };
if (TIERS.BASIC && val === TIERS.BASIC.total) return { ...TIERS.BASIC, name: 'BASIC' };
return null;
}
// ----------------------------------------------------------------------------
// DB pool
// ----------------------------------------------------------------------------
const pool = new Pool(cfg.DB);
pool.on('error', (err) => logger.error({ err: err.message }, 'pg pool error'));
// ----------------------------------------------------------------------------
// Idempotency helper
// ----------------------------------------------------------------------------
async function recordWebhookDelivery({ source, deliveryId, invoiceId, eventType, payloadHash, agentTier, priority }) {
// Vráti true ak je to nový webhook, false ak duplikát.
// Phase 4: agentTier ('BASIC'/'ELITE') + priority (1..10) ukladáme pre operator
// dashboard a budúce out-of-band processing. ELITE → priority 9, BASIC → 5.
const resolvedPriority = priority != null ? priority
: (agentTier === 'ELITE' ? 9 : (agentTier === 'BASIC' ? 5 : 5));
try {
const r = await pool.query(
`INSERT INTO webhook_deliveries (source, delivery_id, invoice_id, event_type, payload_hash, agent_tier, priority)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (source, delivery_id) DO NOTHING
RETURNING id`,
[source, deliveryId, invoiceId || null, eventType, payloadHash, agentTier || null, resolvedPriority]
);
return r.rowCount > 0;
} catch (e) {
logger.error({ err: e.message, deliveryId, source }, 'recordWebhookDelivery FAIL');
return false;
}
}
// Phase 4 (P4-5): doplnenie tier-u na webhook delivery po tom, ako vieme, ktorý
// agent prislúcha invoice/payment_hash. Volá sa z webhook handlerov po registrácii.
async function backfillWebhookTier({ source, deliveryId, agentTier }) {
if (!agentTier) return;
const priority = agentTier === 'ELITE' ? 9 : 5;
try {
await pool.query(
`UPDATE webhook_deliveries SET agent_tier = $3, priority = $4
WHERE source = $1 AND delivery_id = $2`,
[source, deliveryId, agentTier, priority]
);
} catch (e) {
logger.warn({ err: e.message, deliveryId, source }, 'backfillWebhookTier FAIL');
}
}
async function markWebhookProcessed({ source, deliveryId, success, message }) {
try {
await pool.query(
`UPDATE webhook_deliveries SET processed = $3, processing_result = $4, processed_at = CURRENT_TIMESTAMP
WHERE source = $1 AND delivery_id = $2`,
[source, deliveryId, success, (message || '').slice(0, 500)]
);
} catch (e) {
logger.error({ err: e.message }, 'markWebhookProcessed FAIL');
}
}
// ----------------------------------------------------------------------------
// Trusted manufacturers (Phase 1.5 — hardcoded zoznam v .env)
// Formát: "MFR_ID:ed25519_pubkey_hex:reputation_bonus,MFR2:pub2:bonus2,..."
// ----------------------------------------------------------------------------
function parseTrustedManufacturers() {
const raw = process.env.TRUSTED_MANUFACTURERS || '';
const map = new Map();
raw.split(',').map(s => s.trim()).filter(Boolean).forEach(entry => {
const parts = entry.split(':');
if (parts.length < 3) return;
const [id, pub, bonus] = parts;
if (!/^[A-Z0-9_]+$/.test(id) || !/^[0-9a-fA-F]{64}$/.test(pub)) return;
map.set(id, { id, pubkey: pub.toLowerCase(), bonus: parseInt(bonus, 10) || 0 });
});
return map;
}
const TRUSTED_MFRS = parseTrustedManufacturers();
logger.info({ count: TRUSTED_MFRS.size, ids: [...TRUSTED_MFRS.keys()] }, 'Trusted manufacturers loaded');
/**
* Verifikuje manufacturer atestáciu manifestu.
* Pri spárovaní s trusted zoznamom vráti reputation bonus.
*/
function verifyManufacturerAttestation(manifest) {
const mfr = manifest.manufacturer;
if (!mfr) return { present: false, verified: false, bonus: 0 };
const trusted = TRUSTED_MFRS.get(mfr.id);
if (!trusted) {
return { present: true, verified: false, bonus: 0, reason: 'UNKNOWN_MANUFACTURER' };
}
if (trusted.pubkey !== mfr.pubkey.toLowerCase()) {
return { present: true, verified: false, bonus: 0, reason: 'MFR_PUBKEY_MISMATCH' };
}
// Manufacturer mal podpísať sha256(manifest bez manufacturer.attestation)
const { manufacturer, ...rest } = manifest;
const { attestation, ...mfrNoSig } = manufacturer;
const toVerify = { ...rest, manufacturer: mfrNoSig };
const digest = crypto.createHash('sha256').update(manifestSchema.canonicalize(toVerify)).digest();
const ok = hubkeys.verify(digest, attestation, mfr.pubkey);
if (!ok) {
return { present: true, verified: false, bonus: 0, reason: 'BAD_MFR_SIGNATURE' };
}
return { present: true, verified: true, bonus: trusted.bonus, manufacturerId: mfr.id };
}
// ----------------------------------------------------------------------------
// Challenge management (Phase 1.5)
// ----------------------------------------------------------------------------
const CHALLENGE_TTL_SEC = parseInt(process.env.AUTH_CHALLENGE_TTL_SEC || '300', 10);
// Tracks last seen spike state so we only run the optional "extend open
// challenges" UPDATE on the rising edge, not on every challenge request.
let _lastChallengeSpike = false;
async function createChallenge({ pubkey, purpose, clientIp }) {
const challengeId = 'CH-' + crypto.randomBytes(12).toString('hex');
const nonce = crypto.randomBytes(32).toString('hex');
const ttl = http403Tracker.computeChallengeTtl(CHALLENGE_TTL_SEC);
const expiresAt = new Date(Date.now() + ttl.ttl_sec * 1000);
await pool.query(
`INSERT INTO auth_challenges (challenge_id, nonce, pubkey, purpose, expires_at, used_by_ip)
VALUES ($1, $2, $3, $4, $5, $6)`,
[challengeId, nonce, pubkey || null, purpose || 'register', expiresAt, clientIp || null]
);
// Rising-edge: when we just transitioned into a spike, optionally extend
// already-issued but unused challenges so honest clients mid-flow do not
// get caught by the shorter base TTL. Opt-in via env (see lib/http-403-tracker.js).
if (ttl.mode === 'spike' && !_lastChallengeSpike) {
if (http403Tracker.CFG.EXTEND_OPEN_ON_SPIKE) {
const extraSec = Math.max(0, ttl.ttl_sec - CHALLENGE_TTL_SEC);
if (extraSec > 0) {
try {
await pool.query(
`UPDATE auth_challenges
SET expires_at = expires_at + make_interval(secs => $1)
WHERE used_at IS NULL
AND expires_at > NOW()
AND expires_at < NOW() + make_interval(secs => $2)`,
[extraSec, CHALLENGE_TTL_SEC]
);
} catch (e) {
logger.warn({ err: e.message }, 'extend open auth_challenges on spike FAIL');
}
}
}
logger.warn({
count_403_in_window: ttl.count_in_window,
window_min: http403Tracker.CFG.WINDOW_MIN,
new_ttl_sec: ttl.ttl_sec,
base_ttl_sec: CHALLENGE_TTL_SEC,
}, 'auth_challenge entering 403-spike mode (longer TTL)');
}
_lastChallengeSpike = (ttl.mode === 'spike');
return {
challenge_id: challengeId,
nonce,
expires_at: expiresAt.toISOString(),
ttl_sec: ttl.ttl_sec,
ttl_mode: ttl.mode,
};
}
async function consumeChallenge({ challengeId, nonce, expectedPubkey }) {
// Atomické: vybrať a označiť ako used; zlyhá ak je expired, used alebo neexistuje
const r = await pool.query(
`UPDATE auth_challenges
SET used_at = CURRENT_TIMESTAMP
WHERE challenge_id = $1
AND used_at IS NULL
AND expires_at > CURRENT_TIMESTAMP
AND ($2::text IS NULL OR pubkey IS NULL OR pubkey = $2)
AND nonce = $3
RETURNING id, pubkey, purpose, nonce`,
[challengeId, expectedPubkey || null, nonce]
);
return r.rowCount > 0 ? r.rows[0] : null;
}
// Pravidelne čistíme expired challenges (aby tabuľka nerástla donekonečna)
setInterval(async () => {
try {
const r = await pool.query("DELETE FROM auth_challenges WHERE expires_at < NOW() - INTERVAL '1 hour'");
if (r.rowCount > 0) logger.debug({ deleted: r.rowCount }, 'cleaned expired challenges');
} catch (_) { /* ignore */ }
}, 60 * 60 * 1000); // hodinu
// ----------------------------------------------------------------------------
// Cert issuance helper — uloží do DB tabuľky certificates a vráti signed cert
// ----------------------------------------------------------------------------
async function issueCertificate(client, { agent, tier, paymentMethod, paymentHash, amountSats, manifest }) {
const mf = manifest && typeof manifest === 'object' ? manifest : {};
// Strategic Sprint §30 Item 3 — cert-issuance circuit breaker.
// If the breaker is HARD HALTED, refuse to even build the body so we don't
// burn DB writes / signing CPU. The outer caller will surface the error.
if (!certIssuanceBreaker.canIssue()) {
const e = new Error('CERT_ISSUANCE_HALTED');
e.code = 'CERT_ISSUANCE_HALTED';
e.retryAfterSec = 300;
e.breakerState = certIssuanceBreaker.state();
throw e;
}
const serial = certs.makeSerial(agent.kya_id, 1);
let body, signed;
try {
body = certs.buildCertBody({
kya_id: agent.kya_id,
agentName: agent.agent_name,
pubkey: agent.agent_pubkey,
tier: tier.name,
grade: tier.grade,
validUntil: agent.valid_until,
manifestHash: agent.manifest_hash,
manufacturerId: agent.manufacturer_id,
reputationScore: agent.reputation_score,
paymentMethod,
paymentHash,
amountSats,
serial,
paymentHints: integrationsManifest.paymentHintsForCert(mf),
integrationsPublic: integrationsManifest.integrationsPublicForCert(mf),
});
signed = certs.signCert(body, {
purpose: 'cert_issue', serial, kya_id: agent.kya_id,
});
} catch (signErr) {
certIssuanceBreaker.recordFailure(signErr);
throw signErr;
}
const meta = _extractProofMeta(signed);
// Resolve signing_key_id z hub-key-store podľa primárnej pubkey (single-sig:
// jediná použitá; multi-sig: prvá v poradí — typicky BASIC).
let signingKeyId = null;
try {
const k = await hubkeys.store.lookupKeyByPubkey(client, meta.issuerPubkey);
signingKeyId = k ? k.key_id : null;
} catch (_) { /* best effort */ }
try {
await client.query(
`INSERT INTO certificates (
serial, agent_id, kya_id, cert_body, hub_signature, issuer_pubkey,
valid_until, signing_key_id,
proof_type, proof_threshold, proof_signing_roles
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,
[
serial, agent.id, agent.kya_id, JSON.stringify(signed),
meta.signatureForLegacyColumn, meta.issuerPubkey,
agent.valid_until, signingKeyId,
meta.proofType, meta.threshold, meta.signingRoles,
]
);
await client.query(
`UPDATE agents SET cert_issued_at = CURRENT_TIMESTAMP, cert_serial = $1 WHERE id = $2`,
[serial, agent.id]
);
} catch (dbErr) {
certIssuanceBreaker.recordFailure(dbErr);
throw dbErr;
}
certIssuanceBreaker.recordSuccess();
return signed;
}
// ----------------------------------------------------------------------------
// Helper: extract DB-friendly metadata from a signed cert (single OR multi).
// ----------------------------------------------------------------------------
function _extractProofMeta(signed) {
const proof = (signed && signed.proof) || {};
if (proof.type === 'Ed25519MultiSignature2020') {
const sigs = Array.isArray(proof.signatures) ? proof.signatures : [];
const firstPub = (() => {
for (const s of sigs) {
const m = (s.verificationMethod || '').match(/ed25519:([0-9a-fA-F]{64})/);
if (m) return m[1].toLowerCase();
}
return null;
})();
return {
proofType: 'Ed25519MultiSignature2020',
threshold: Number.isFinite(proof.threshold) ? proof.threshold : sigs.length,
signingRoles: sigs.map(s => s.role || null).filter(Boolean),
issuerPubkey: firstPub || (hubkeys.getPublicInfo().pubkey_hex),
// For backward compat the legacy hub_signature column expects ONE
// signature value. Use the first one as a representative; the
// canonical truth is `cert_body.proof.signatures[*]`.
signatureForLegacyColumn: (sigs[0] && (sigs[0].signatureValue || sigs[0].signature)) || '',
};
}
// Single-sig
const vm = proof.verificationMethod || '';
const m = vm.match(/ed25519:([0-9a-fA-F]{64})/);
return {
proofType: proof.type || 'Ed25519Signature2020',
threshold: 1,
signingRoles: proof.signingRole ? [proof.signingRole] : null,
issuerPubkey: (m && m[1].toLowerCase()) || hubkeys.getPublicInfo().pubkey_hex,
signatureForLegacyColumn: proof.signatureValue || '',
};
}
// ----------------------------------------------------------------------------
// Agent registration core — volaný z webhook handlerov po overení platby
// ----------------------------------------------------------------------------
async function registerAgent({ tier, agentName, pubkey, manifest, paymentMethod, invoiceId, amountSats, registrationIntent }) {
if (!tier || !agentName) throw new Error('tier + agentName povinné');
// Strategic Sprint §31 D — defense in depth: even if /api/pay was bypassed
// (e.g. cron-driven backfill or admin route), refuse to register an agent
// whose pubkey is on the active deny-list.
const effPubkey = registrationIntent ? registrationIntent.agent_pubkey : pubkey;
if (effPubkey) {
try {
const dl = await regQuote.isOnDenyList(pool, effPubkey);
if (dl.active) {
logger.warn({
agentName, pubkey_prefix: dl.pubkey ? dl.pubkey.slice(0, 16) : null,
expires_at: dl.expires_at, ban_count: dl.ban_count,
}, 'registerAgent BLOCKED — pubkey on deny-list');
const err = new Error(`PUBKEY_DENY_LISTED until ${dl.expires_at} (ban_count=${dl.ban_count})`);
err.code = 'PUBKEY_DENY_LISTED';
err.deny_listed_until = dl.expires_at;
err.ban_count = dl.ban_count;
throw err;
}
} catch (e) {
if (e && e.code === 'PUBKEY_DENY_LISTED') throw e;
// best-effort otherwise
}
}
const validUntil = tier.durationMonths
? new Date(new Date().setMonth(new Date().getMonth() + tier.durationMonths))
: null;
// Phase 1.5: Ak máme intent (validated manifest+signature), použijeme ho
let manifestHash = null;
let manifestSignature = null;
let manufacturerId = null;
let manufacturerVerified = false;
let manufacturerBonus = 0;
let protocolVersion = '1.0';
let mfrAttestationId = null;
let mfrTier = null;
if (registrationIntent) {
manifestHash = registrationIntent.manifest_hash;
manifestSignature = registrationIntent.manifest_signature;
manufacturerId = registrationIntent.manufacturer_id;
manufacturerVerified = !!registrationIntent.manufacturer_verified;
manufacturerBonus = registrationIntent.manufacturer_bonus || 0;
mfrAttestationId = registrationIntent.mfr_attestation_id
? Number(registrationIntent.mfr_attestation_id) : null;
mfrTier = registrationIntent.mfr_tier || null;
} else if (manifest && typeof manifest === 'object' && manifest.protocol_version) {
// Legacy direct manifest cez /api/pay — best-effort hash bez signature
manifestHash = manifestSchema.manifestHash(manifest);
protocolVersion = manifest.protocol_version;
}
// Vypočítaj starting reputation podľa tier + manufacturer bonus
const startingScore = reputation.computeStartingScore({
tierName: tier.name,
manufacturerBonus,
});
// ELITE → PENDING_ANCHOR, BASIC → VERIFIED hneď
const status = tier.requiresAnchor ? 'PENDING_ANCHOR' : 'VERIFIED';
const anchorStatus = tier.requiresAnchor ? 'PENDING' : null;
const client = await pool.connect();
try {
await client.query('BEGIN');
// Serialize registration for the same agent_name (parallel webhooks / BTCPay+LN).
// Transaction-scoped: released on COMMIT/ROLLBACK.
await client.query(
`SELECT pg_advisory_xact_lock(CAST(hashtext($1::text) AS bigint))`,
[`kya:agent_reg:${agentName}`]
);
// Phase 1.5: row lock on intent so only one txn can finalize PENDING_PAYMENT → COMPLETED.
if (registrationIntent && registrationIntent.id) {
const intentRow = await client.query(
`SELECT id, status, agent_name FROM registration_intents WHERE id = $1 FOR UPDATE`,
[registrationIntent.id]
);
if (intentRow.rowCount === 0) {
await client.query('COMMIT');
logger.warn({ intentId: registrationIntent.id, agentName }, 'registration intent row missing');
return { duplicate: true, agentName };
}
const ir = intentRow.rows[0];
if (ir.status !== 'PENDING_PAYMENT') {
await client.query('COMMIT');
logger.warn({
intentId: registrationIntent.id, agentName, status: ir.status,
}, 'registration intent already finalized');
return { duplicate: true, agentName };
}
if (ir.agent_name !== agentName) {
await client.query('ROLLBACK');
throw new Error('REGISTRATION_INTENT_AGENT_MISMATCH');
}
}
const existingAgent = await client.query(
`SELECT id, kya_id FROM agents WHERE agent_name = $1 FOR UPDATE`,
[agentName]
);
if (existingAgent.rowCount > 0) {
const row = existingAgent.rows[0];
if (registrationIntent && registrationIntent.id) {
await client.query(
`UPDATE registration_intents
SET status = 'COMPLETED', completed_at = CURRENT_TIMESTAMP
WHERE id = $1 AND status = 'PENDING_PAYMENT'`,
[registrationIntent.id]
);
}
await client.query('COMMIT');
logger.warn({ agentName, kya_id: row.kya_id }, 'Agent už existuje — preskakujem registráciu');
return { duplicate: true, agentName, axisId: row.kya_id };
}
// Chronological public id: UMBRA-000042 (hub_kya_seq, see migrations/018_hub_kya_seq.sql)
const axisId = await allocateSequentialKyaId(client);
const seal = crypto.createHmac('sha256', cfg.HUB_SECRET)
.update(`${agentName}:${axisId}:${tier.total}`)
.digest('hex');
const discoveryOptIn = integrationsManifest.discoveryOptInFromManifest(manifest || {});
const lightningNodeId = apiV1Register.lightningNodeIdFromManifest(manifest || {});
const insertRes = await client.query(
`INSERT INTO agents (
kya_id, agent_name, status, reputation_score, agent_pubkey,
data_hash, origin_node, conduct_grade, tier,
initial_deposit, current_deposit, agent_manifest,
valid_until, is_active, last_seen,
payment_invoice_id, payment_method, payment_amount_sats, payment_settled_at,
anchor_status,
protocol_version, manifest_hash, manifest_signature,
manufacturer_id, manufacturer_verified,
mfr_attestation_id, mfr_tier, discovery_opt_in,
lightning_node_id
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, CURRENT_TIMESTAMP, $15, $16, $17, CURRENT_TIMESTAMP, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27)
ON CONFLICT (agent_name) DO NOTHING
RETURNING id, kya_id, agent_name, agent_pubkey, valid_until, reputation_score, manifest_hash, manufacturer_id`,
[
axisId, agentName, status, startingScore, pubkey || '',
seal, 'UMBRA-NODE-01', tier.grade, tier.name,
tier.total, tier.total, JSON.stringify(manifest || {}),
validUntil, true,
invoiceId, paymentMethod, amountSats,
anchorStatus,
protocolVersion, manifestHash, manifestSignature,
manufacturerId, manufacturerVerified,
mfrAttestationId, mfrTier,
discoveryOptIn,
lightningNodeId,
]
);
if (insertRes.rowCount === 0) {
logger.warn({ agentName }, 'INSERT agents ON CONFLICT — duplikát agent_name');
const ag = await client.query(
`SELECT id, kya_id FROM agents WHERE agent_name = $1`,
[agentName]
);
if (ag.rowCount === 0) {
await client.query('ROLLBACK');
logger.error({ agentName }, 'INSERT ON CONFLICT but agent row missing');
throw new Error('AGENT_INSERT_CONFLICT_UNKNOWN');
}
if (registrationIntent && registrationIntent.id) {
await client.query(
`UPDATE registration_intents
SET status = 'COMPLETED', completed_at = CURRENT_TIMESTAMP
WHERE id = $1 AND status = 'PENDING_PAYMENT'`,
[registrationIntent.id]
);
}
await client.query('COMMIT');
return { duplicate: true, agentName, axisId: ag.rows[0].kya_id };
}
const newAgent = insertRes.rows[0];
// ELITE → naqueue anchor request
if (tier.requiresAnchor) {
await client.query(
`INSERT INTO pending_anchors (agent_id, hmac_hash, tier, status)
VALUES ($1, $2, $3, 'PENDING')`,
[newAgent.id, seal, tier.name]
);
}
// Phase 1.5: Vystav signed certifikát
let certificate = null;
try {
certificate = await issueCertificate(client, {
agent: newAgent,
tier,
paymentMethod,
paymentHash: invoiceId,
amountSats,
manifest: manifest || {},
});
} catch (certErr) {
logger.error({ err: certErr.message, agentName }, 'cert issuance failed (agent zostáva registrovaný)');
// Nepadáme — agent je registrovaný, cert si môže vyžiadať neskôr
}
// Update intent ako COMPLETED ak existoval
if (registrationIntent && registrationIntent.id) {
await client.query(
`UPDATE registration_intents
SET status = 'COMPLETED', completed_at = CURRENT_TIMESTAMP
WHERE id = $1`,
[registrationIntent.id]
);
}
if (registrationIntent?.sponsor_invite_id) {
try {
await sponsorInvite.linkAgentAfterRegistration(client, {
inviteId: registrationIntent.sponsor_invite_id,
agentKyaId: newAgent.kya_id,
});
} catch (e) {
logger.warn({ err: e.message, inviteId: registrationIntent.sponsor_invite_id },
'sponsor invite link FAIL (non-fatal)');
}
}
// Phase 4B: link the mfr attestation to this agent (one-shot consume).
// Idempotent: if already consumed by a different agent (race), this no-ops.
if (mfrAttestationId) {
try {
const consumed = await manufacturer.markAttestationConsumed(client, {
attestation_id: mfrAttestationId, agent_id: newAgent.id,
});
if (!consumed.ok) {
logger.warn({
agentName, mfrAttestationId, reason: consumed.reason,
}, 'mfr attestation already consumed (race?)');
}
} catch (e) {
logger.error({ err: e.message, mfrAttestationId },
'mfr attestation consume FAIL (non-fatal)');
}
}
await client.query('COMMIT');
const repInfo = reputation.describe(startingScore);
logger.info({
event: 'agent_registered',
agentName,
axisId: newAgent.kya_id,
tier: tier.name,
status,
cert: !!certificate,
mfr: manufacturerId,
reputation: startingScore,
zone: repInfo.zone,
registration_id: registrationIntent ? registrationIntent.registration_id : null,
invoice_id: invoiceId || null,
}, 'Agent zaregistrovaný');
developerWebhooks.emit(pool, {
event: 'agent.registered',
kya_id: newAgent.kya_id,
payload: {
tier: tier.name,
manifest_hash: manifestHash,
discovery_opt_in: discoveryOptIn,
},
}).catch(() => {});
// Fire-and-forget Telegram/Discord PING po každej zaplatenej registrácii (BASIC + ELITE).
notifications.notifyRegistrationPaid({
tier: tier.name,
agentName,
axisId: newAgent.kya_id,
paymentMethod: paymentMethod || 'unknown',
amountSats: amountSats || tier.total,
}).catch(() => { /* notifikácia nikdy nezhorí registráciu */ });
return {
duplicate: false,
axisId: newAgent.kya_id,
agentId: newAgent.id,
seal,
status,
certificate, // signed cert object (alebo null ak issuance zlyhal)
};
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
client.release();
}
}
// ----------------------------------------------------------------------------
// Express app
// ----------------------------------------------------------------------------
const app = express();
// P2: Error tracking (opt-in via SENTRY_DSN).
// Must be mounted before routes so request context is available.
try {
sentry.init(logger);
const rh = sentry.requestHandler();
const th = sentry.tracingHandler();
if (rh) app.use(rh);
if (th) app.use(th);
} catch (e) {
logger.warn({ err: e?.message }, 'Sentry init failed (continuing without it)');
}
// Expose pool cez app.locals pre middleware ktoré k nemu nemajú priamy prístup (napr. security.adminAuth)
app.locals.pool = pool;
app.set('trust proxy', 1); // ak je za nginx/cloudflare
// Globálne security headers
app.use(helmet({
contentSecurityPolicy: false, // frontend HTML používa inline scripty, dorobíme neskôr
crossOriginEmbedderPolicy: false,
}));
// HTTP 403 sliding-window counter (Phase 2.5) — must attach BEFORE any
// route/middleware that may emit 403, so `res.on('finish')` fires for every
// 403 response (zone limiter, ip ban, suspended agents, rejectAndLog …).
app.use(http403Tracker.buildExpressMiddleware());
// IP ban check (Phase 2.2) — beží PRED akýmkoľvek iným spracovaním
// Health a webhook majú výnimku (nech monitoring funguje aj keď je IP banned)
app.use(abuseTracker.buildIpBanMiddleware({
poolGetter: () => pool,
exemptPaths: ['/api/health', '/api/webhook/btcpay', '/api/webhook/alby'],
}));
// CORS s whitelist
app.use(cors(security.buildCorsOptions()));
// Admin bypass helper (definícia ďalej v súbore — function declaration je hoisted)
// Použité v rate-limiteroch nech testy a admin tooling s X-Admin-Key môžu preskočiť limity.
// Rate limiting — globálny
const globalLimiter = rateLimit({
windowMs: 60 * 1000,
max: 120,
standardHeaders: true,
legacyHeaders: false,
message: { error: 'RATE_LIMITED', message: 'Príliš veľa requestov' },
skip: (req) => _adminBypass(req),
});
app.use(globalLimiter);
// Špeciálny limiter pre /api/pay (drahšia operácia — BTCPay/Alby API call)
const payLimiter = rateLimit({
windowMs: 60 * 1000,
max: parseInt(process.env.RATE_PAY_PER_MIN || '5', 10),
standardHeaders: true,
legacyHeaders: false,
message: { error: 'RATE_LIMITED', message: 'Max 5 faktúr/min/IP. Skús neskôr.' },
skip: (req) => _adminBypass(req),
});
// M2M canonical register — stricter than legacy pay/initiate
const v1RegisterLimiter = rateLimit({
windowMs: 60 * 1000,
max: parseInt(process.env.RATE_V1_REGISTER_PER_MIN || '3', 10),
standardHeaders: true,
legacyHeaders: false,
message: {
error: 'RATE_LIMITED',
message: 'Max 3 registrácií/min/IP na /api/v1/register. Rešpektuj Retry-After.',
},
skip: (req) => _adminBypass(req),
});
// Phase 4B: manufacturer attestation submission throttle.
const mfrAttestLimiter = rateLimit({
windowMs: 60 * 1000,
max: parseInt(process.env.RATE_MFR_ATTEST_PER_MIN || '20', 10),
standardHeaders: true,
legacyHeaders: false,
message: { error: 'RATE_LIMITED', message: 'Too many attestation submissions; slow down.' },
skip: (req) => _adminBypass(req),
});
// Platform / plug-in read API (GET /api/v1/agents/*) — per-IP or per API key bucket
const integratorReadLimiter = rateLimit({
windowMs: 60 * 1000,
max: (req) => {
if (req.integrator && req.integrator.rate_limit_per_min) {
return req.integrator.rate_limit_per_min;
}
return parseInt(process.env.RATE_INTEGRATOR_READ_PER_MIN || '120', 10);
},
keyGenerator: (req) => {
if (req.integrator && req.integrator.id) return `devkey:${req.integrator.id}`;
return req.ip || 'unknown';
},
standardHeaders: true,
legacyHeaders: false,
message: {
error: 'RATE_LIMITED',
message: 'Integrator read rate limit exceeded. Honor Retry-After or use a developer API key.',
},
skip: (req) => _adminBypass(req),
});
// Registrácia rate-limit referencií pre admin reset (Phase 2.2 testovacie pomôcky)
const _rateLimiters = {
global: globalLimiter,
pay: payLimiter,
v1_register: v1RegisterLimiter,
mfr_attest: mfrAttestLimiter,
integrator_read: integratorReadLimiter,
};
// ----------------------------------------------------------------------------
// 1) Webhook BTCPay — raw body kvôli HMAC overeniu (PRED app.use(json()))
// ----------------------------------------------------------------------------
app.post('/api/webhook/btcpay', express.raw({ type: 'application/json', limit: '256kb' }), async (req, res) => {
const log = logger.child({ route: 'webhook/btcpay' });
const sig = req.headers['btcpay-sig'];
const deliveryId = req.headers['btcpay-delivery-id'] || crypto.randomBytes(8).toString('hex');
if (!sig || !req.body || req.body.length === 0) {
log.warn('prázdny alebo nepodpísaný webhook');
return res.status(400).send('Missing data');
}
if (!security.verifyHmacSignature(req.body, cfg.BTCPAY_WEBHOOK_SECRET, sig)) {
log.error({ deliveryId }, 'INVALID HMAC signature');
abuseTracker.recordRejection(pool, {
path: req.path, method: req.method, reason: 'BAD_HMAC_SIGNATURE',
http_status: 401, client_ip: req.ip, user_agent: req.headers['user-agent'],
error_detail: `deliveryId=${deliveryId}`,
}).catch(() => {});
return res.status(401).send('Invalid signature');
}
let payload;
try {
payload = JSON.parse(req.body.toString());
} catch {
return res.status(400).send('Bad JSON');
}
const payloadHash = crypto.createHash('sha256').update(req.body).digest('hex');
// Idempotency
const isNew = await recordWebhookDelivery({
source: 'btcpay',
deliveryId,
invoiceId: payload.invoiceId,
eventType: payload.type,
payloadHash,
});
if (!isNew) {
log.info({ deliveryId, eventType: payload.type }, 'duplicate webhook, skipping');
return res.status(200).send('Duplicate (idempotent)');
}
log.info({ deliveryId, eventType: payload.type, invoiceId: payload.invoiceId }, 'webhook received');
try {
if (payload.type === 'InvoiceSettled') {
const metadata = payload.metadata || {};
// ELITE public listing — heartbeat / reactivation (not registration)
if (metadata.integratorLsatAccessId) {
try {
const settled = await integratorLsat.markPaid(
pool,
metadata.integratorLsatAccessId,
payload.invoiceId
);
await markWebhookProcessed({
source: 'btcpay',
deliveryId,
success: !!settled.ok,
message: settled.already ? 'lsat_dup' : `lsat:${settled.access_id || 'fail'}`,
});
} catch (e) {
log.error({ err: e.message }, 'integrator LSAT BTCPay webhook FAIL');
await markWebhookProcessed({ source: 'btcpay', deliveryId, success: false, message: e.message });
}
return res.status(200).send('OK');
}
if (metadata.eliteListingPayment === 'heartbeat' || metadata.eliteListingPayment === 'reactivation') {
try {
const amt = parseInt(metadata.eliteListingExpectedSats || metadata.amount || 0, 10)
|| (payload.amount ? parseInt(String(payload.amount), 10) : 0);
const settled = await eliteListing.handlePaymentSettled(pool, {
invoiceId: payload.invoiceId,
paymentHash: payload.invoiceId,
amountSats: amt,
metadata,
source: 'btcpay',