-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
7345 lines (6723 loc) · 353 KB
/
Copy pathserver.js
File metadata and controls
7345 lines (6723 loc) · 353 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
// ─────────────────────────────────────────────────────────────────────────────
// v4call — server.js
// Decentralised paid communications via Hive blockchain + WebRTC
//
// FORKING: Only change the constants at the top of each section marked
// ── FORK CONFIG ── to rebrand for your own node.
// Everything else is logic — leave it alone unless you know why.
//
// Rate format: supports both [V4CALL-RATES-V1] and [V4CALL-RATES-V2]
// V2 adds: [BLOCKED], [TOKEN:SYMBOL], TEXT-SESSION, ALLOW-BLOCKED, CHAIN, SERVER, NOSTR
// ─────────────────────────────────────────────────────────────────────────────
// Load .env file if present (local dev and Docker).
// In production via systemd, env vars are set directly in the service file.
try { require('dotenv').config(); } catch(e) { /* dotenv is optional */ }
// ─────────────────────────────────────────────────────────────────────────────
// .env duplicate-key safety net (v0.16.19+)
//
// dotenv is "last-wins": writing `FEDERATION_PEERS=A` on one line and
// `FEDERATION_PEERS=B` on the next silently drops A — process.env.FEDERATION_PEERS
// only sees B. Caught in production 2026-05-28 in a three-server mesh; one peer
// of every pair was missing from the runtime config and nobody noticed because
// Nostr presence kept federated users visible in the lobby anyway. See
// FED-RECOVERY-NOTES.md Lesson 11.
//
// This scan re-reads the raw .env file at boot, looks for any key declared
// more than once, and prints a loud warning per duplicate. Behavioural impact:
// zero — dotenv has already loaded by this point. It just makes the silent
// dedup loud so the next operator catches it in seconds rather than weeks.
//
// Skips silently if there's no .env file (production via systemd, the example
// .env.example file in CI, etc.).
//
// path/fs are require()'d inline here because the main require block below
// hasn't run yet — keeping the scan at the very top of boot means the warning
// fires before any other [config] line, so an operator running
// `docker compose logs app | head -20` sees it immediately.
try {
const _fs = require('fs');
const _path = require('path');
const envPath = _path.resolve(process.cwd(), '.env');
if (_fs.existsSync(envPath)) {
const raw = _fs.readFileSync(envPath, 'utf8');
const counts = Object.create(null);
for (const line of raw.split('\n')) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const m = trimmed.match(/^([A-Z_][A-Z0-9_]*)\s*=/);
if (!m) continue;
const key = m[1];
counts[key] = (counts[key] || 0) + 1;
}
for (const [key, n] of Object.entries(counts)) {
if (n > 1) {
const hint = (key === 'FEDERATION_PEERS' || key === 'NOSTR_RELAYS')
? ' Use comma-separated form: ' + key + '=value1,value2'
: ' dotenv keeps only the LAST occurrence.';
console.log('[config] ⚠ multiple ' + key + ' lines in .env (' + n + ').' + hint);
}
}
}
} catch (e) {
// Don't crash the server over a diagnostic. Just log and move on.
console.log('[config] (env duplicate-key scan skipped: ' + e.message + ')');
}
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const path = require('path');
const crypto = require('crypto');
const fs = require('fs');
const Database = require('better-sqlite3');
const dhive = require('@hiveio/dhive');
const WebSocket = require('ws');
const app = express();
const server = http.createServer(app);
// CORS is permissive on the Socket.io server — browsers from federated peers
// connect here to join call rooms hosted on this server (see federation
// cross-server call flow below).
const io = new Server(server, { cors: { origin: true, credentials: true } });
app.use(express.static(path.join(__dirname, 'public')));
// ─────────────────────────────────────────────────────────────────────────────
// ── FORK CONFIG — Edit .env to set these. Do NOT hardcode values here. ───────
// ─────────────────────────────────────────────────────────────────────────────
const SERVER_NAME = process.env.SERVER_NAME || 'v4call';
const SERVER_DOMAIN = process.env.SERVER_DOMAIN || 'v4call.com';
const SERVER_HIVE_ACCOUNT = process.env.SERVER_HIVE_ACCOUNT || 'v4call';
const ESCROW_ACCOUNT = process.env.ESCROW_ACCOUNT || 'v4call-escrow';
const PLATFORM_FEE = parseFloat(process.env.DEFAULT_PLATFORM_FEE || '10') / 100;
// v0.16.8 — Precision floor for paid rates. Default for HBD/HIVE (3 decimals).
// Path B (per-currency precision) is now IMPLEMENTED: getCurrencyFloor(currency)
// returns 10^-precision for the actual currency (0.001 for HBD/HIVE, 1e-8 for an
// 8-decimal token like SWAP.BTC). RATE_FLOOR remains the HBD/HIVE default and the
// safe fallback when a token's precision can't be fetched. Rates below the
// currency's floor are treated as free (picker filters them, resolver ignores
// them, disbursement skips them). All `.toFixed(3)` in the disbursement pipeline
// was replaced with `.toFixed(getCurrencyPrecision(currency))`.
const RATE_FLOOR = 0.001;
const PORT = parseInt(process.env.PORT || '3000');
const BIND_HOST = process.env.BIND_HOST || '127.0.0.1';
// Hive API nodes — can override the primary node via HIVE_API env var.
// Server tries each in order and falls back automatically on failure.
// Refreshed 2026-04: dropped anyx.io and hived.emre.sh (intermittent/dead),
// added arcange / openhive / techcoderx as known-reliable fallbacks.
const HIVE_API = process.env.HIVE_API || 'https://api.hive.blog';
const HIVE_API_NODES = [
HIVE_API,
'https://api.deathwing.me',
'https://hive-api.arcange.eu',
'https://api.openhive.network',
'https://techcoderx.com'
].filter((v, i, a) => a.indexOf(v) === i); // deduplicate if HIVE_API matches a fallback
// Call behaviour — tunable via .env
const CALL_COOLDOWN_MS = parseInt(process.env.CALL_COOLDOWN_MS || '30000');
const MAX_CALL_DURATION_MIN = parseInt(process.env.MAX_CALL_DURATION_MIN || '120');
const PAYMENT_VERIFY_RETRIES = parseInt(process.env.PAYMENT_VERIFY_RETRIES || '3');
const PAYMENT_VERIFY_DELAY_MS = parseInt(process.env.PAYMENT_VERIFY_DELAY_MS || '5000');
// Chat storage — tunable via .env
const DM_RETENTION_DAYS = parseInt(process.env.DM_RETENTION_DAYS || '33');
const ROOM_RETENTION_DAYS = parseInt(process.env.ROOM_RETENTION_DAYS || '33');
const DM_PREVIEW_COUNT = parseInt(process.env.DM_PREVIEW_COUNT || '1'); // 0 = off
// Federation — comma-separated list of peer WebSocket URLs (e.g. wss://peer.com/federation)
const FEDERATION_PEERS = (process.env.FEDERATION_PEERS || '')
.split(',').map(s => s.trim()).filter(Boolean);
const FEDERATION_ENABLED = FEDERATION_PEERS.length > 0;
const FEDERATION_VERSION = '0.4';
// ── Nostr federation discovery (Phase B: publish own announce only) ─────────
// FED_DISCOVERY_MODE controls how servers find each other:
// hive = today's behaviour only (2h Hive scan), no Nostr
// nostr = Nostr relays only
// both = Nostr (fast) + Hive scan (fallback) ← default, belt-and-braces
// This knob does NOT touch the WS federation transport (DMs/calls/payments
// always ride that). It only affects discovery/presence. Phases C/D inherit it.
const FED_DISCOVERY_MODE = (process.env.FED_DISCOVERY_MODE || 'both').toLowerCase();
const NOSTR_RELAYS = (process.env.NOSTR_RELAYS || '')
.split(',').map(s => s.trim()).filter(Boolean);
const NOSTR_REPUBLISH_HOURS = parseInt(process.env.NOSTR_REPUBLISH_HOURS || '6');
const NOSTR_NSEC = process.env.NOSTR_NSEC || ''; // one-time seed only
const NOSTR_KEY_PATH = process.env.NOSTR_KEY_PATH || '/app/nostr/nostr-key.json';
// When FED_DISCOVERY_MODE=nostr, should the 2h Hive scan still run as a
// silent safety net? Default true. Set false ONLY for deliberate Nostr-only
// testing — losing the Hive net means a total relay outage = no discovery.
const NOSTR_HIVE_FALLBACK = (process.env.NOSTR_HIVE_FALLBACK || 'true').toLowerCase() !== 'false';
// Hive discovery scan runs UNLESS we're in pure-Nostr-no-fallback test mode.
const HIVE_SCAN_ENABLED = !(FED_DISCOVERY_MODE === 'nostr' && !NOSTR_HIVE_FALLBACK);
// Nostr subscribe runs when discovery mode includes Nostr.
const NOSTR_SUBSCRIBE_ENABLED = (FED_DISCOVERY_MODE === 'nostr' || FED_DISCOVERY_MODE === 'both');
// ── Phase D — cross-server presence via Nostr (WS-wins-Nostr-additive) ─────
// Master gate. Default off until proven; flip to true to opt in per server.
const FED_PRESENCE_VIA_NOSTR = (process.env.FED_PRESENCE_VIA_NOSTR || 'false').toLowerCase() === 'true';
// At most one publish per N seconds (joins/leaves coalesce inside the window).
const NOSTR_PRESENCE_THROTTLE_SECONDS = parseInt(process.env.NOSTR_PRESENCE_THROTTLE_SECONDS || '30');
// Republish every N seconds even if nothing changed (covers relay drops).
const NOSTR_PRESENCE_HEARTBEAT_SECONDS = parseInt(process.env.NOSTR_PRESENCE_HEARTBEAT_SECONDS || '60');
// Drop a peer's Nostr presence if we haven't heard from it for N seconds.
const NOSTR_PRESENCE_TTL_SECONDS = parseInt(process.env.NOSTR_PRESENCE_TTL_SECONDS || '300');
// ── Nostr payload transport — carry dm + dm-attachment over Nostr relays ────
// Lets cross-server DMs + media attachments deliver when the WS /federation
// transport is down/disabled. Default OFF until proven; enable on ALL peers
// together (a peer without it just won't subscribe = graceful degradation).
// Requires FED_DISCOVERY_MODE=nostr|both (to subscribe) AND FED_PRESENCE_VIA_NOSTR
// (to know which peer hosts a username) AND the peer's NOSTR_PUBKEY in their
// signed v4call-server.json (Hive-anchored binding). WS stays the PREFERRED
// route — Nostr is best-effort store-and-forward (see fedRouteSend: WS-first).
const NOSTR_FED_TRANSPORT = (process.env.NOSTR_FED_TRANSPORT || 'false').toLowerCase() === 'true';
// NIP-40 expiration on fedmsg events so relays GC delivered messages.
const NOSTR_FEDMSG_TTL_SECONDS = parseInt(process.env.NOSTR_FEDMSG_TTL_SECONDS || '86400');
console.log(`[config] Server: ${SERVER_NAME} (${SERVER_DOMAIN})`);
console.log(`[config] Escrow: @${ESCROW_ACCOUNT}`);
console.log(`[config] Platform fee: ${PLATFORM_FEE * 100}%`);
console.log(`[config] Max duration: ${MAX_CALL_DURATION_MIN} min`);
console.log(`[config] DM retention: ${DM_RETENTION_DAYS} days | Room retention: ${ROOM_RETENTION_DAYS} days | DM preview: ${DM_PREVIEW_COUNT}`);
if (FEDERATION_ENABLED) {
console.log(`[config] Federation: ENABLED — peers: ${FEDERATION_PEERS.join(', ')}`);
} else {
console.log(`[config] Federation: disabled (no FEDERATION_PEERS set)`);
}
if (NOSTR_FED_TRANSPORT) {
if (NOSTR_SUBSCRIBE_ENABLED && FED_PRESENCE_VIA_NOSTR) {
console.log(`[config] Nostr payload transport: ENABLED (dm + dm-attachment over relays, ttl ${NOSTR_FEDMSG_TTL_SECONDS}s)`);
} else {
console.warn(`[config] ⚠ NOSTR_FED_TRANSPORT=true but needs FED_DISCOVERY_MODE=nostr|both (subscribe=${NOSTR_SUBSCRIBE_ENABLED}) AND FED_PRESENCE_VIA_NOSTR=true (presence=${FED_PRESENCE_VIA_NOSTR}) — transport will NOT route until both are on.`);
}
}
// ── v0.13 Lobby Notice + Anti-Spam Gate (env only; no federation bump) ──────
const LOBBY_NOTICE_RAW = process.env.LOBBY_NOTICE || '';
const LOBBY_REQUIREMENTS_RAW = process.env.LOBBY_REQUIREMENTS_TEXT || '';
const LOBBY_POST_MIN_HP = parseFloat(process.env.LOBBY_POST_MIN_HP || '0') || 0;
const LOBBY_POST_MIN_HIVE = parseFloat(process.env.LOBBY_POST_MIN_HIVE || '0') || 0;
const LOBBY_POST_MIN_TOKEN_RAW = (process.env.LOBBY_POST_MIN_TOKEN || '').trim();
const LOBBY_POST_GATE_MODE = (process.env.LOBBY_POST_GATE_MODE || 'or').toLowerCase() === 'and' ? 'and' : 'or';
let LOBBY_POST_MIN_TOKEN_SYMBOL = null;
let LOBBY_POST_MIN_TOKEN_AMOUNT = 0;
if (LOBBY_POST_MIN_TOKEN_RAW.includes(':')) {
const [sym, amt] = LOBBY_POST_MIN_TOKEN_RAW.split(':');
LOBBY_POST_MIN_TOKEN_SYMBOL = sym.trim().toUpperCase();
LOBBY_POST_MIN_TOKEN_AMOUNT = parseFloat(amt) || 0;
}
const LOBBY_NOTICE_RESOLVED = LOBBY_NOTICE_RAW ||
`${SERVER_DOMAIN} — local lobby. For federated contacts use rooms / DMs / calls.`;
const LOBBY_REQUIREMENTS_RESOLVED = LOBBY_REQUIREMENTS_RAW || (() => {
const parts = [];
if (LOBBY_POST_MIN_HP > 0) parts.push(`${LOBBY_POST_MIN_HP} HP`);
if (LOBBY_POST_MIN_HIVE > 0) parts.push(`${LOBBY_POST_MIN_HIVE} HIVE`);
if (LOBBY_POST_MIN_TOKEN_SYMBOL) parts.push(`${LOBBY_POST_MIN_TOKEN_AMOUNT} ${LOBBY_POST_MIN_TOKEN_SYMBOL}`);
if (parts.length === 0) return '';
if (parts.length === 1) return `Posting requires ${parts[0]}.`;
return `Posting requires ${parts.join(LOBBY_POST_GATE_MODE === 'and' ? ' AND ' : ' OR ')}.`;
})();
// ─────────────────────────────────────────────────────────────────────────────
// ── SQLite Ledger ─────────────────────────────────────────────────────────────
// ─────────────────────────────────────────────────────────────────────────────
const LOG_DIR = path.join(__dirname, 'logs');
if (!fs.existsSync(LOG_DIR)) fs.mkdirSync(LOG_DIR, { recursive: true });
const db = new Database(path.join(LOG_DIR, 'v4call-ledger.db'));
db.exec(`
CREATE TABLE IF NOT EXISTS payments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts TEXT NOT NULL DEFAULT (datetime('now')),
call_id TEXT NOT NULL,
type TEXT NOT NULL, -- 'ring' | 'connect' | 'payout' | 'refund' | 'platform_fee'
from_user TEXT NOT NULL,
to_user TEXT NOT NULL,
amount REAL NOT NULL,
currency TEXT NOT NULL DEFAULT 'HBD',
memo TEXT,
tx_id TEXT, -- Hive transaction ID if available
status TEXT NOT NULL DEFAULT 'pending', -- 'pending' | 'verified' | 'sent' | 'failed'
note TEXT
);
CREATE TABLE IF NOT EXISTS calls (
id INTEGER PRIMARY KEY AUTOINCREMENT,
call_id TEXT UNIQUE NOT NULL,
caller TEXT NOT NULL,
callee TEXT NOT NULL,
call_type TEXT NOT NULL DEFAULT 'voice',
chain TEXT NOT NULL DEFAULT 'hive',
started_at TEXT,
connected_at TEXT,
ended_at TEXT,
duration_min REAL DEFAULT 0,
ring_paid REAL DEFAULT 0,
connect_paid REAL DEFAULT 0,
duration_cost REAL DEFAULT 0,
callee_net REAL DEFAULT 0,
platform_cut REAL DEFAULT 0,
status TEXT NOT NULL DEFAULT 'initiated',
end_reason TEXT
);
CREATE INDEX IF NOT EXISTS idx_calls_caller ON calls(caller);
CREATE INDEX IF NOT EXISTS idx_calls_callee ON calls(callee);
CREATE INDEX IF NOT EXISTS idx_calls_call_id ON calls(call_id);
CREATE INDEX IF NOT EXISTS idx_payments_call_id ON payments(call_id);
`);
console.log('[ledger] SQLite ready:', path.join(LOG_DIR, 'v4call-ledger.db'));
// ─────────────────────────────────────────────────────────────────────────────
// ── SQLite Chat Store (separate DB for security) ─────────────────────────────
// ─────────────────────────────────────────────────────────────────────────────
const chatDb = new Database(path.join(LOG_DIR, 'v4call-chat.db'));
chatDb.exec(`
CREATE TABLE IF NOT EXISTS dm_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts TEXT NOT NULL DEFAULT (datetime('now')),
from_user TEXT NOT NULL,
to_user TEXT NOT NULL,
owner TEXT NOT NULL,
ciphertext TEXT NOT NULL,
signature TEXT,
timestamp TEXT,
text_paid REAL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS room_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts TEXT NOT NULL DEFAULT (datetime('now')),
room_name TEXT NOT NULL,
from_user TEXT NOT NULL,
to_user TEXT NOT NULL,
ciphertext TEXT NOT NULL,
signature TEXT,
timestamp TEXT,
is_broadcast INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS user_seen (
username TEXT PRIMARY KEY,
last_seen TEXT NOT NULL DEFAULT (datetime('now'))
);
-- ipfs-gate v0.1 attachment envelopes. One row per emit. File bytes live on
-- ipfs-gate (not here); we store only the envelope so room-history can replay
-- attachment bubbles on rejoin. per_recipient is a JSON map { username: encKey }.
-- Kept even past expires_at so users see "someone sent X (now gone)" with a
-- ⚠ 404 chip when the client tries to fetch the expired pin.
CREATE TABLE IF NOT EXISTS room_attachments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
room_name TEXT NOT NULL,
sender TEXT NOT NULL,
sender_pubkey TEXT NOT NULL,
cid TEXT NOT NULL,
size_bytes INTEGER NOT NULL,
envelope_sig TEXT NOT NULL,
env_created_at TEXT NOT NULL,
expires_at TEXT,
gateway_hint TEXT,
kind_hint TEXT,
per_recipient TEXT NOT NULL,
original_filename TEXT,
original_mime TEXT,
original_size INTEGER,
stored_at TEXT NOT NULL DEFAULT (datetime('now'))
);
-- DM attachments (v0.16.17). Same envelope shape as room_attachments but
-- the context is a 1:1 conversation (sender ↔ to_user) rather than a room.
-- per_recipient is always exactly { sender: encKey, to_user: encKey }.
-- text_paid + currency mirror dm_messages so the paid-DM trail is
-- auditable per-attachment. Local-server only in v0.1 (no federation).
CREATE TABLE IF NOT EXISTS dm_attachments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sender TEXT NOT NULL,
to_user TEXT NOT NULL,
sender_pubkey TEXT NOT NULL,
cid TEXT NOT NULL,
size_bytes INTEGER NOT NULL,
envelope_sig TEXT NOT NULL,
env_created_at TEXT NOT NULL,
expires_at TEXT,
gateway_hint TEXT,
kind_hint TEXT,
per_recipient TEXT NOT NULL,
original_filename TEXT,
original_mime TEXT,
original_size INTEGER,
text_paid REAL NOT NULL DEFAULT 0,
currency TEXT NOT NULL DEFAULT 'HBD',
stored_at TEXT NOT NULL DEFAULT (datetime('now'))
);
-- Durable per-sender upload metadata index (v0.16.25 — uploads-management tab).
-- room_attachments is cascade-deleted when an ephemeral room is torn down, so
-- it can't supply filename/room context for the Uploads tab after you leave a
-- room. This table is written at send time and NEVER cascade-deleted, so the
-- gate's long-lived pin can still be shown with its real name + where it was
-- sent. Pure metadata (no ciphertext, no keys); pruned by retention cleanup.
-- The gate stays authoritative for what's actually pinned + quota.
CREATE TABLE IF NOT EXISTS upload_index (
cid TEXT PRIMARY KEY,
uploader TEXT NOT NULL,
filename TEXT,
mime TEXT,
kind TEXT,
context TEXT,
sent_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_dm_owner ON dm_messages(owner);
CREATE INDEX IF NOT EXISTS idx_dm_from ON dm_messages(from_user);
CREATE INDEX IF NOT EXISTS idx_dm_to ON dm_messages(to_user);
CREATE INDEX IF NOT EXISTS idx_dm_created ON dm_messages(created_at);
CREATE INDEX IF NOT EXISTS idx_room_name ON room_messages(room_name);
CREATE INDEX IF NOT EXISTS idx_room_created ON room_messages(created_at);
CREATE INDEX IF NOT EXISTS idx_room_att_room ON room_attachments(room_name);
CREATE INDEX IF NOT EXISTS idx_room_att_stored ON room_attachments(stored_at);
CREATE INDEX IF NOT EXISTS idx_dm_att_sender ON dm_attachments(sender);
CREATE INDEX IF NOT EXISTS idx_dm_att_to ON dm_attachments(to_user);
CREATE INDEX IF NOT EXISTS idx_dm_att_stored ON dm_attachments(stored_at);
CREATE INDEX IF NOT EXISTS idx_upload_index_up ON upload_index(uploader);
`);
// Migration: paid-DM badge needs the actual currency. Older rows back-default
// to 'HBD' which is wrong for token DMs but unfixable without payment metadata.
try { chatDb.exec(`ALTER TABLE dm_messages ADD COLUMN currency TEXT DEFAULT 'HBD'`); }
catch(e) { /* duplicate column = already migrated */ }
console.log('[chat] SQLite ready:', path.join(LOG_DIR, 'v4call-chat.db'));
// ── Chat DB helpers ──────────────────────────────────────────────────────────
function chatStoreDm(fromUser, toUser, ciphertextForRecipient, ciphertextForSender, signature, timestamp, textPaid, currency) {
try {
const cur = currency || 'HBD';
const stmt = chatDb.prepare(`
INSERT INTO dm_messages (from_user, to_user, owner, ciphertext, signature, timestamp, text_paid, currency)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`);
// Store recipient's copy (encrypted to recipient's key)
stmt.run(fromUser, toUser, toUser, ciphertextForRecipient, signature, timestamp, textPaid || 0, cur);
// Store sender's copy (encrypted to sender's key)
if (ciphertextForSender) {
stmt.run(fromUser, toUser, fromUser, ciphertextForSender, signature, timestamp, textPaid || 0, cur);
}
} catch(e) {
console.error('[chat] DM store failed:', e.message);
}
}
function chatStoreRoomMsg(roomName, fromUser, toUser, ciphertext, signature, timestamp, isBroadcast) {
try {
chatDb.prepare(`
INSERT INTO room_messages (room_name, from_user, to_user, ciphertext, signature, timestamp, is_broadcast)
VALUES (?, ?, ?, ?, ?, ?, ?)
`).run(roomName, fromUser, toUser, ciphertext, signature, timestamp, isBroadcast ? 1 : 0);
} catch(e) {
console.error('[chat] Room message store failed:', e.message);
}
}
function chatGetDmUnread(username) {
try {
const seen = chatDb.prepare(`SELECT last_seen FROM user_seen WHERE username = ?`).get(username);
const since = seen ? seen.last_seen : '1970-01-01 00:00:00';
const rows = chatDb.prepare(`
SELECT from_user, COUNT(*) as cnt
FROM dm_messages
WHERE owner = ? AND to_user = ? AND created_at > ?
GROUP BY from_user
`).all(username, username, since);
return rows; // [{ from_user, cnt }, ...]
} catch(e) {
console.error('[chat] Unread count failed:', e.message);
return [];
}
}
function chatGetDmPreviews(username, countPerUser) {
if (countPerUser <= 0) return [];
try {
// Get the N most recent messages per conversation partner
const partners = chatDb.prepare(`
SELECT DISTINCT CASE WHEN from_user = ? THEN to_user ELSE from_user END as partner
FROM dm_messages WHERE owner = ?
`).all(username, username);
const previews = [];
const stmt = chatDb.prepare(`
SELECT from_user, to_user, ciphertext, signature, timestamp, text_paid, currency, created_at
FROM dm_messages
WHERE owner = ? AND (
(from_user = ? AND to_user = ?) OR (from_user = ? AND to_user = ?)
)
ORDER BY created_at DESC LIMIT ?
`);
for (const { partner } of partners) {
const rows = stmt.all(username, username, partner, partner, username, countPerUser);
previews.push(...rows.reverse()); // chronological order
}
return previews;
} catch(e) {
console.error('[chat] DM preview failed:', e.message);
return [];
}
}
function chatGetDmHistory(username, withUser) {
try {
return chatDb.prepare(`
SELECT from_user, to_user, ciphertext, signature, timestamp, text_paid, currency, created_at
FROM dm_messages
WHERE owner = ? AND (
(from_user = ? AND to_user = ?) OR (from_user = ? AND to_user = ?)
)
ORDER BY created_at ASC
`).all(username, username, withUser, withUser, username);
} catch(e) {
console.error('[chat] DM history failed:', e.message);
return [];
}
}
function chatGetRoomHistory(roomName, username) {
try {
return chatDb.prepare(`
SELECT from_user, to_user, ciphertext, signature, timestamp, is_broadcast, created_at
FROM room_messages
WHERE room_name = ? AND (is_broadcast = 1 OR to_user = ? OR from_user = ?)
ORDER BY created_at ASC
`).all(roomName, username, username);
} catch(e) {
console.error('[chat] Room history failed:', e.message);
return [];
}
}
function chatDeleteRoom(roomName) {
try {
const info = chatDb.prepare(`DELETE FROM room_messages WHERE room_name = ?`).run(roomName);
if (info.changes > 0) console.log(`[chat] Deleted ${info.changes} messages for room #${roomName}`);
const aInfo = chatDb.prepare(`DELETE FROM room_attachments WHERE room_name = ?`).run(roomName);
if (aInfo.changes > 0) console.log(`[chat] Deleted ${aInfo.changes} attachment envelopes for room #${roomName}`);
} catch(e) {
console.error('[chat] Room delete failed:', e.message);
}
}
function chatStoreRoomAttachment(env) {
try {
chatDb.prepare(`
INSERT INTO room_attachments (
room_name, sender, sender_pubkey, cid, size_bytes, envelope_sig,
env_created_at, expires_at, gateway_hint, kind_hint, per_recipient,
original_filename, original_mime, original_size
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
env.room, env.sender, env.sender_pubkey || '', env.cid,
env.size_bytes | 0, env.envelope_sig, env.created_at || new Date().toISOString(),
env.expires_at || null, env.gateway_hint || null, env.kind_hint || null,
JSON.stringify(env.per_recipient || {}),
env.original_filename || null, env.original_mime || null,
env.original_size != null ? (env.original_size | 0) : null
);
} catch (e) {
console.error('[chat] Room attachment store failed:', e.message);
}
}
// History query: returns full envelopes for the room where the requesting user
// is either the sender OR present in per_recipient. Bystander-by-default for
// late joiners (they don't see attachments addressed to others sent before they
// joined — same privacy posture as chatGetRoomHistory for encrypted DMs).
function chatGetRoomAttachments(roomName, username) {
try {
const rows = chatDb.prepare(`
SELECT * FROM room_attachments
WHERE room_name = ? ORDER BY stored_at ASC
`).all(roomName);
const out = [];
for (const r of rows) {
let per_recipient = {};
try { per_recipient = JSON.parse(r.per_recipient || '{}'); } catch (_) {}
if (r.sender !== username && !(username in per_recipient)) continue;
out.push({
v: 1, type: 'room-attachment',
room: r.room_name, sender: r.sender, sender_pubkey: r.sender_pubkey,
cid: r.cid, size_bytes: r.size_bytes, envelope_sig: r.envelope_sig,
created_at: r.env_created_at, expires_at: r.expires_at,
gateway_hint: r.gateway_hint, kind_hint: r.kind_hint,
per_recipient,
original_filename: r.original_filename,
original_mime: r.original_mime,
original_size: r.original_size
});
}
return out;
} catch (e) {
console.error('[chat] Room attachment history failed:', e.message);
return [];
}
}
// v0.16.17 — DM attachment persistence + history. Mirrors the room helpers
// but keyed on the (sender, to_user) conversation pair. text_paid + currency
// captured so the paid-DM trail per attachment is auditable.
function chatStoreDmAttachment(env, textPaid, currency) {
try {
chatDb.prepare(`
INSERT INTO dm_attachments (
sender, to_user, sender_pubkey, cid, size_bytes, envelope_sig,
env_created_at, expires_at, gateway_hint, kind_hint, per_recipient,
original_filename, original_mime, original_size, text_paid, currency
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
env.sender, env.to_user, env.sender_pubkey || '', env.cid,
env.size_bytes | 0, env.envelope_sig, env.created_at || new Date().toISOString(),
env.expires_at || null, env.gateway_hint || null, env.kind_hint || null,
JSON.stringify(env.per_recipient || {}),
env.original_filename || null, env.original_mime || null,
env.original_size != null ? (env.original_size | 0) : null,
textPaid || 0, currency || 'HBD'
);
} catch (e) {
console.error('[chat] DM attachment store failed:', e.message);
}
}
// History query for the (username, withUser) conversation. Returns envelopes
// for either direction (sender = username AND to_user = withUser, OR sender =
// withUser AND to_user = username) where the requesting user is in
// per_recipient. Envelopes kept past expires_at — client renders ⚠ 404.
function chatGetDmAttachments(username, withUser) {
try {
const rows = chatDb.prepare(`
SELECT * FROM dm_attachments
WHERE (sender = ? AND to_user = ?) OR (sender = ? AND to_user = ?)
ORDER BY stored_at ASC
`).all(username, withUser, withUser, username);
const out = [];
for (const r of rows) {
let per_recipient = {};
try { per_recipient = JSON.parse(r.per_recipient || '{}'); } catch (_) {}
// Defensive — for DMs the audience is always {sender, to_user} so this
// should always pass; included for symmetry with the room query.
if (r.sender !== username && !(username in per_recipient)) continue;
out.push({
v: 1, type: 'dm-attachment',
to_user: r.to_user, sender: r.sender, sender_pubkey: r.sender_pubkey,
cid: r.cid, size_bytes: r.size_bytes, envelope_sig: r.envelope_sig,
created_at: r.env_created_at, expires_at: r.expires_at,
gateway_hint: r.gateway_hint, kind_hint: r.kind_hint,
per_recipient,
original_filename: r.original_filename,
original_mime: r.original_mime,
original_size: r.original_size,
text_paid: r.text_paid, currency: r.currency
});
}
return out;
} catch (e) {
console.error('[chat] DM attachment history failed:', e.message);
return [];
}
}
// v0.14.5 — every row for a room, regardless of recipient. Used by the
// .v4room export endpoint; per-recipient filtering happens client-side at
// decryption time (since the ciphertext is what's stored).
function chatGetRoomMessagesAll(roomName) {
try {
return chatDb.prepare(`
SELECT from_user, to_user, ciphertext, signature, timestamp, is_broadcast, created_at
FROM room_messages WHERE room_name = ? ORDER BY created_at ASC
`).all(roomName);
} catch(e) {
console.error('[chat] Room export query failed:', e.message);
return [];
}
}
// v0.16.25 — durable record of an upload's metadata for the sender, keyed by CID.
// Written at send time from both the room + DM attachment handlers. Survives
// ephemeral-room teardown (unlike room_attachments). INSERT OR REPLACE: CIDs are
// content-unique, and a re-send just refreshes the same metadata.
function chatRecordUploadIndex({ cid, uploader, filename, mime, kind, context }) {
if (!cid || !uploader) return;
try {
chatDb.prepare(`
INSERT OR REPLACE INTO upload_index (cid, uploader, filename, mime, kind, context, sent_at)
VALUES (?, ?, ?, ?, ?, ?, datetime('now'))
`).run(cid, uploader, filename || null, mime || null, kind || null, context || null);
} catch (e) {
console.error('[chat] upload-index write failed:', e.message);
}
}
// v0.16.25 — uploads-management tab enrichment. The ipfs-gate is authoritative for
// what's pinned, but it only ever saw ciphertext for encrypted uploads, so it
// has no filename / kind / "which room or DM" context. That context lives here,
// keyed by CID. Returns a map cid -> { filename, mime, kind, context } for every
// attachment this user sent. The durable `upload_index` is primary; we also
// merge any still-present room_attachments / dm_attachments rows (covers live
// rooms + pre-index legacy sends) WITHOUT clobbering the index. The client
// merges the result onto the gate's authoritative list by CID.
function chatGetUploadContextForUser(username) {
const map = {};
try {
const idxRows = chatDb.prepare(`
SELECT cid, filename, mime, kind, context FROM upload_index WHERE uploader = ?
`).all(username);
for (const r of idxRows) {
map[r.cid] = { filename: r.filename || null, mime: r.mime || null, kind: r.kind || null, context: r.context || null };
}
const roomRows = chatDb.prepare(`
SELECT cid, room_name, kind_hint, original_filename, original_mime
FROM room_attachments WHERE sender = ?
`).all(username);
for (const r of roomRows) {
if (map[r.cid]) continue;
map[r.cid] = { filename: r.original_filename || null, mime: r.original_mime || null, kind: r.kind_hint || null, context: `in #${r.room_name}` };
}
const dmRows = chatDb.prepare(`
SELECT cid, to_user, kind_hint, original_filename, original_mime
FROM dm_attachments WHERE sender = ?
`).all(username);
for (const r of dmRows) {
if (map[r.cid]) continue;
map[r.cid] = { filename: r.original_filename || null, mime: r.original_mime || null, kind: r.kind_hint || null, context: `→ @${r.to_user} (DM)` };
}
} catch (e) {
console.error('[chat] upload-context query failed:', e.message);
}
return map;
}
function chatUpdateSeen(username) {
try {
chatDb.prepare(`
INSERT INTO user_seen (username, last_seen) VALUES (?, datetime('now'))
ON CONFLICT(username) DO UPDATE SET last_seen = datetime('now')
`).run(username);
} catch(e) {
console.error('[chat] Seen update failed:', e.message);
}
}
function chatCleanup() {
try {
const dmCutoff = chatDb.prepare(`SELECT datetime('now', ?) as cutoff`).get(`-${DM_RETENTION_DAYS} days`).cutoff;
const roomCutoff = chatDb.prepare(`SELECT datetime('now', ?) as cutoff`).get(`-${ROOM_RETENTION_DAYS} days`).cutoff;
const dmDel = chatDb.prepare(`DELETE FROM dm_messages WHERE created_at < ?`).run(dmCutoff);
const roomDel = chatDb.prepare(`DELETE FROM room_messages WHERE created_at < ?`).run(roomCutoff);
const dmAttDel = chatDb.prepare(`DELETE FROM dm_attachments WHERE stored_at < ?`).run(dmCutoff);
// Prune the durable upload index on the longer of the two retentions so a
// row outlives the underlying gate pin but can't accumulate forever.
const idxCutoff = DM_RETENTION_DAYS >= ROOM_RETENTION_DAYS ? dmCutoff : roomCutoff;
const idxDel = chatDb.prepare(`DELETE FROM upload_index WHERE sent_at < ?`).run(idxCutoff);
if (dmDel.changes || roomDel.changes || dmAttDel.changes || idxDel.changes) {
console.log(`[chat] Cleanup: removed ${dmDel.changes} DMs, ${roomDel.changes} room messages, ${dmAttDel.changes} DM attachments, ${idxDel.changes} upload-index rows`);
}
} catch(e) {
console.error('[chat] Cleanup failed:', e.message);
}
}
// Run cleanup on startup and then every hour
chatCleanup();
setInterval(chatCleanup, 60 * 60 * 1000);
// ── Ledger helpers ────────────────────────────────────────────────────────────
function ledgerPayment(callId, type, fromUser, toUser, amount, memo = '', status = 'pending', txId = null, currency = 'HBD') {
try {
db.prepare(`
INSERT INTO payments (call_id, type, from_user, to_user, amount, currency, memo, status, tx_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(callId, type, fromUser, toUser, amount, currency, memo, status, txId);
} catch(e) {
console.error('[ledger] Payment insert failed:', e.message);
}
}
// v0.16.9 — Refundable missed/declined/cancelled calls for the callee.
// Returns rows where the caller paid a ring fee that's still in our escrow
// (no refund payment row exists yet). Used by the missed-call popup on login.
function getRefundableMissedCalls(callee, limit = 20) {
try {
return db.prepare(`
SELECT
c.call_id,
c.caller,
c.callee,
c.call_type,
c.started_at,
c.status,
c.end_reason,
p.amount AS ring_paid,
p.currency AS ring_currency,
p.memo AS ring_memo
FROM calls c
JOIN payments p
ON p.call_id = c.call_id
AND p.type = 'ring'
AND p.status IN ('verified', 'sent')
WHERE c.callee = ?
AND c.status IN ('missed', 'declined', 'cancelled')
AND p.amount > 0
AND NOT EXISTS (
SELECT 1 FROM payments r
WHERE r.call_id = c.call_id
AND r.type IN ('refund', 'ring_refund')
AND r.status IN ('pending', 'sent')
)
ORDER BY c.started_at DESC
LIMIT ?
`).all(callee, limit);
} catch(e) {
console.error('[ledger] getRefundableMissedCalls failed:', e.message);
return [];
}
}
function ledgerCallCreate(callId, caller, callee, callType = 'voice') {
try {
db.prepare(`
INSERT OR IGNORE INTO calls (call_id, caller, callee, call_type, started_at, status)
VALUES (?, ?, ?, ?, datetime('now'), 'initiated')
`).run(callId, caller, callee, callType);
} catch(e) {
console.error('[ledger] Call create failed:', e.message);
}
}
function ledgerCallUpdate(callId, fields) {
const keys = Object.keys(fields);
if (!keys.length) return;
const set = keys.map(k => k + ' = ?').join(', ');
const vals = [...keys.map(k => fields[k]), callId];
try {
db.prepare(`UPDATE calls SET ${set} WHERE call_id = ?`).run(...vals);
} catch(e) {
console.error('[ledger] Call update failed:', e.message);
}
}
function ledgerPaymentUpdate(callId, type, status, txId = null) {
try {
db.prepare(`
UPDATE payments SET status = ?, tx_id = COALESCE(?, tx_id)
WHERE call_id = ? AND type = ?
`).run(status, txId, callId, type);
} catch(e) {
console.error('[ledger] Payment update failed:', e.message);
}
}
// ─────────────────────────────────────────────────────────────────────────────
// ── Lobby & Rooms ─────────────────────────────────────────────────────────────
// ─────────────────────────────────────────────────────────────────────────────
const lobbyUsers = {}; // username → { socketId, pubKey, invisible, inCall? }
// v0.16.17 — debounce offline broadcasts for ≤5s to soak transient socket
// drops (laptop sleep wake, wifi blip). Keyed by username; cleared on
// lobby-join. See the disconnect handler for the firing semantics.
const pendingOfflineTimers = {};
const rooms = {}; // roomName → { creator, allowlist(Set), banlist(Set), tokenGate:{symbol,amount}|null, banlistVisibility:'admin'|'all', paidInvitees:Map, members[], createdAt, isCall?, callId?, ... }
// Federation state — populated by federation message handlers (see below).
// domain → { ws, connected, name, users: Map(username → { pubKey }), protocolVersion }
const federationPeers = {};
// In-flight federated room invites (v0.16, fed v0.4). One map serves both
// directions; `dir` distinguishes:
// outgoing — admin on this server invited a user on another server
// incoming — peer server invited a local user to a room on the peer
// Pruned by ttl-sweep (see start of fedHandleMessage section).
const pendingFederatedInvites = {};
const FED_INVITE_TTL_MS = 15 * 60 * 1000;
// v0.16.10 — paid LOCAL room invites awaiting recipient accept/decline. When
// an admin pays an invitee's room-invite fee, the funds sit in escrow under
// this key; on decline / 15-min timeout / explicit cancel the inviter is
// refunded the gross-paid amount. On accept, the recipient is paid net of
// platform fee. Keyed by inviteId (random hex).
// { room, inviter, invitee, currency, paid, memo, msgId, status,
// created_at, type: 'create' | 'allowlist' }
// status: 'pending' (sent, awaiting response) | 'accepted' | 'declined' |
// 'timed_out' | 'cancelled'
const pendingPaidInvites = {};
const PAID_INVITE_TTL_MS = 15 * 60 * 1000;
// ── Discovery state (populated by scanV4CallDirectory) ──────────────────────
// domain → { post_author, post_permlink, post_created, parsed, verified,
// verify_reason, last_seen }
const discoveredPeers = {};
// Domains the operator has explicitly approved to federate. Approval is
// required for both inbound acceptance and outbound initiation. Seeded from
// FEDERATION_PEERS env (auto-approved, backwards compat) + loaded from
// /app/logs/approved-peers.json on startup. Persisted on mutation.
const approvedPeers = new Set();
function _approvedPeersFile() { return path.join(LOG_DIR, 'approved-peers.json'); }
function loadApprovedPeers() {
// 1. Seed from FEDERATION_PEERS env — operator-declared trust is implicit.
for (const url of FEDERATION_PEERS) {
try { approvedPeers.add(new URL(url).host.toLowerCase()); }
catch(e) { /* bad URL, ignore */ }
}
// 2. Load persisted approvals from previous runs.
try {
const raw = fs.readFileSync(_approvedPeersFile(), 'utf8');
const list = JSON.parse(raw);
if (Array.isArray(list)) for (const d of list) if (typeof d === 'string') approvedPeers.add(d.toLowerCase());
} catch(e) { /* file doesn't exist yet — first run, fine */ }
}
function persistApprovedPeers() {
try {
fs.writeFileSync(_approvedPeersFile(), JSON.stringify([...approvedPeers].sort(), null, 2));
} catch(e) { console.error('[peers] Failed to persist approval list:', e.message); }
}
function federatedUserSnapshot() {
const out = [];
for (const [domain, peer] of Object.entries(federationPeers)) {
if (!peer.connected) continue;
for (const [username, u] of peer.users) {
// Skip collisions with local users — local identity wins to avoid spoofing.
if (lobbyUsers[username]) continue;
out.push({ username, pubKey: u.pubKey, server: domain });
}
}
return out;
}
function lobbySnapshot() {
const local = Object.entries(lobbyUsers)
.filter(([, u]) => !u.invisible)
.map(([username, u]) => ({ username, socketId: u.socketId, pubKey: u.pubKey, server: SERVER_DOMAIN }));
return [...local, ...federatedUserSnapshot(), ...nostrAdditivePresenceSnapshot()];
}
function broadcastLobby() {
io.emit('lobby-users', lobbySnapshot());
// Phase D: local presence may have changed → tell nostr-fed to publish
// (throttled + heartbeat-protected inside the module). No-op if Phase D
// is gated off or the module hasn't loaded yet.
try { nostrFedController?.notePresenceChange(); } catch { /* never crash on a Nostr hiccup */ }
}
// ── Phase D — cross-server presence via Nostr (WS-wins-Nostr-additive) ─────
// Map of domain → { users:Set<string>, lastTs:number(unix s), lastEventId,
// pubkey, updatedAt:ms }. Only domains we've Phase-C-discovered + verified
// land here, and only events from the expected (Hive-anchored when possible)
// pubkey are accepted. Stale entries time out via the TTL sweep.
const nostrCrossFedPresence = {};
let nostrFedController = null; // populated after dynamic import; see startup block
// Trust gate — what pubkey is THIS domain allowed to sign presence events with?
// Prefer the Hive-signature-anchored binding from verifyPeer's Option B
// canonical (`verified_nostr_hex`). Fall back to the Phase C "poke" binding
// (`nostr_pubkey` recorded when a Nostr discovery event arrived). If neither
// exists, we have no acceptable binding → reject.
function expectedNostrHexForDomain(domain) {
const p = discoveredPeers[domain];
if (!p || !p.verified) return null;
return (p.verified_nostr_hex || p.nostr_pubkey || null);
}
// Called when a verified-shape v4call-presence event arrives. Trust gate is
// already strict in the module (own-pubkey skip, content/d-tag domain match);
// here we make the FINAL trust decision against the Hive-anchored binding.
function recordNostrPresence({ domain, users, pubkey, eventId, ts }) {
try {
if (!FED_PRESENCE_VIA_NOSTR) return; // master gate
if (!domain || !pubkey) return;
domain = String(domain).toLowerCase();
if (domain === SERVER_DOMAIN.toLowerCase()) return; // can't be us
const expected = expectedNostrHexForDomain(domain);
if (!expected) {
// Peer not Phase-C-verified yet (or no Nostr binding for it). Drop.
// We do NOT silently buffer — they'll publish again at heartbeat.
return;
}
if (expected !== pubkey) {
console.warn(`[presence] ✗ pubkey mismatch from relay for @${domain}: expected ${expected.slice(0,12)}…, got ${pubkey.slice(0,12)}… — dropped`);
return;
}
// Newer-wins per domain (relays can echo older events).
const cur = nostrCrossFedPresence[domain];
if (cur && ts <= cur.lastTs) return;
const userSet = new Set(
(Array.isArray(users) ? users : [])
.map(u => String(u || '').trim().toLowerCase())
.filter(Boolean)
);
nostrCrossFedPresence[domain] = {
users: userSet,
lastTs: ts,
lastEventId: eventId,
pubkey,
updatedAt: Date.now(),
};
// Tell every connected client right away — the user list now has more
// people in it. broadcastLobby will call back into nostr-fed to publish
// our local change too; that's fine and throttle-protected.
io.emit('lobby-users', lobbySnapshot());
} catch (e) {
console.error('[presence] recordNostrPresence error (non-fatal):', e.message);
}
}
// Reconciliation — WS wins, Nostr is purely additive (never marks offline).
// For each domain we have Nostr presence for, return ONLY the users that the
// WS federation hasn't already reported for that same domain. Result: if WS
// is healthy, this is empty. If WS is lagging or down, Nostr fills the gap.
//
// v0.16.15 — visibility tracks approval. ONLY surface presence from domains