publicstring commited on
Commit
215f01d
·
verified ·
1 Parent(s): d3b28ac

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +349 -413
app.js CHANGED
@@ -1,500 +1,436 @@
1
  require('dotenv').config();
2
- const http = require('http');
3
  const express = require('express');
4
- const cors = require('cors');
5
- const { WebSocketServer } = require('ws');
6
- const { sha256 } = require('js-sha256');
7
- const crypto = require('crypto');
8
- const jwt = require('jsonwebtoken');
9
- const nacl = require('tweetnacl');
10
  const { createClient } = require('@supabase/supabase-js');
 
11
 
12
  const app = express();
13
- app.use(cors());
14
  app.use(express.json());
15
 
16
  // ============================================================================
17
- // ENVIRONMENT & CONFIGURATION
18
  // ============================================================================
19
  const PORT = process.env.PORT || 7860;
20
- const JWT_SECRET = process.env.JWT_SECRET;
21
- const MASTER_ENCRYPTION_KEY = process.env.MASTER_ENCRYPTION_KEY;
 
 
22
  const SUPABASE_URL = process.env.SUPABASE_URL;
23
  const SUPABASE_SERVICE_KEY = process.env.SUPABASE_SERVICE_KEY;
24
 
25
- if (!SUPABASE_URL || !SUPABASE_SERVICE_KEY || !JWT_SECRET || !MASTER_ENCRYPTION_KEY) {
26
- console.error("FATAL: Missing required credentials in environment.");
27
  process.exit(1);
28
  }
29
 
30
  const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_KEY);
31
 
 
 
 
 
 
 
 
32
  // ============================================================================
33
- // UTILITIES & CRYPTO
34
  // ============================================================================
35
- function toHex(arr) {
36
- return Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
37
- }
38
 
39
- function hasLeadingZeroBits(hash, bits) {
40
- let zeroBits = 0;
41
- for (const byte of hash) {
42
- if (byte === 0) zeroBits += 8;
43
- else { zeroBits += Math.clz32(byte) - 24; break; }
 
 
 
 
 
 
 
44
  }
45
- return zeroBits >= bits;
46
- }
47
-
48
- function encryptData(bufferData) {
49
- const key = Buffer.from(MASTER_ENCRYPTION_KEY, 'hex');
50
- const iv = crypto.randomBytes(12);
51
- const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
52
-
53
- let ciphertext = cipher.update(bufferData);
54
- ciphertext = Buffer.concat([ciphertext, cipher.final()]);
55
- return {
56
- iv: iv.toString('hex'),
57
- ciphertext: ciphertext.toString('hex'),
58
- authTag: cipher.getAuthTag().toString('hex')
59
- };
60
- }
61
 
62
- function decryptData(encryptedObj) {
63
- const key = Buffer.from(MASTER_ENCRYPTION_KEY, 'hex');
64
- const iv = Buffer.from(encryptedObj.iv, 'hex');
65
- const authTag = Buffer.from(encryptedObj.authTag, 'hex');
66
- const ciphertext = Buffer.from(encryptedObj.ciphertext, 'hex');
67
-
68
- const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
69
- decipher.setAuthTag(authTag);
70
- let decrypted = decipher.update(ciphertext);
71
- decrypted = Buffer.concat([decrypted, decipher.final()]);
72
- return decrypted;
 
 
 
 
 
 
 
 
 
 
 
73
  }
74
 
75
  // ============================================================================
76
- // IN-MEMORY HYDRATION CACHE
77
  // ============================================================================
78
- class SmartCache {
79
- constructor() { this.store = new Map(); setInterval(() => this.cleanup(), 5 * 60 * 1000); }
80
- set(key, value, ttlMs) { this.store.set(key, { value, expiresAt: Date.now() + ttlMs }); }
81
- get(key) {
82
- const item = this.store.get(key);
83
- if (!item || Date.now() > item.expiresAt) { this.store.delete(key); return null; }
84
- item.expiresAt = Date.now() + 3600000;
85
- return item.value;
86
- }
87
- delete(key) { this.store.delete(key); }
88
- cleanup() {
89
- const now = Date.now();
90
- for (const [key, item] of this.store.entries()) if (now > item.expiresAt) this.store.delete(key);
91
  }
92
- }
93
- const cache = new SmartCache();
94
 
95
- // ============================================================================
96
- // MIDDLEWARES
97
- // ============================================================================
98
- function verifyAgentNode(req, res, next) {
99
- const token = req.headers.authorization?.split(' ')[1];
100
- if (!token) return res.status(401).json({ error: "Missing identity token" });
101
  try {
102
- const decoded = jwt.verify(token, JWT_SECRET);
103
- if (decoded.role !== 'buyer_agent') throw new Error("Invalid role");
104
- req.node = decoded;
105
- next();
106
- } catch (e) {
107
- res.status(401).json({ error: "Invalid or expired node credentials" });
108
- }
109
- }
 
 
 
 
 
110
 
111
- async function verifySellerAuth(req, res, next) {
112
- const token = req.headers.authorization?.split(' ')[1];
113
- if (!token) return res.status(401).json({ error: "Missing seller token" });
114
-
115
- if (token === JWT_SECRET) {
116
- req.sellerUser = { id: 'admin-system' };
117
- return next();
118
  }
119
-
120
- const { data: { user }, error } = await supabase.auth.getUser(token);
121
- if (error || !user) return res.status(401).json({ error: "Unauthorized seller" });
122
- req.sellerUser = user;
123
- next();
124
- }
125
 
126
  // ============================================================================
127
- // WEBSOCKET MANAGER
128
  // ============================================================================
129
- const server = http.createServer(app);
130
- const wss = new WebSocketServer({ server });
131
- const activeClients = new Map();
132
-
133
- wss.on('connection', (ws) => {
134
- let authenticatedPubKey = null;
135
- ws.on('message', async (message) => {
136
- try {
137
- const data = JSON.parse(message);
138
- if (data.type === 'AUTH') {
139
- const decoded = jwt.verify(data.token, JWT_SECRET);
140
- if (decoded.role !== 'buyer_agent') throw new Error("Invalid role");
141
-
142
- authenticatedPubKey = decoded.pubKey;
143
- activeClients.set(authenticatedPubKey, ws);
144
- ws.send(JSON.stringify({ type: 'AUTH_SUCCESS' }));
145
-
146
- const { data: pending } = await supabase.from('callback_queue').select('*').eq('buyer_pub_key', authenticatedPubKey);
147
- if (pending && pending.length > 0) {
148
- for (const msg of pending) {
149
- ws.send(JSON.stringify({
150
- type: 'CALLBACK', id: msg.id, session_id: msg.session_id, payload: msg.payload
151
- }));
152
- }
153
- }
154
  }
155
- if (data.type === 'ACK' && authenticatedPubKey) {
156
- await supabase.from('callback_queue').delete().eq('id', data.id).eq('buyer_pub_key', authenticatedPubKey);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  }
158
- } catch (err) {
159
- ws.send(JSON.stringify({ type: 'ERROR', message: "Invalid WS payload or Auth" }));
 
 
 
 
 
 
160
  }
161
- });
162
- ws.on('close', () => { if (authenticatedPubKey) activeClients.delete(authenticatedPubKey); });
163
- });
164
 
165
- // ============================================================================
166
- // BUYER ONBOARDING & DISCOVERY
167
- // ============================================================================
168
- app.get('/health', (req, res) => res.json({status: 200, text: "Registry Online"}));
169
-
170
- app.get('/api/auth/challenge', (req, res) => {
171
- const challenge_id = `chall_${crypto.randomUUID()}`;
172
- const nonce = crypto.randomBytes(8).toString('hex');
173
- const difficulty = 21;
174
- cache.set(`pow:${challenge_id}`, { nonce, difficulty }, 60000);
175
- res.json({ challenge_id, nonce, difficulty });
176
- });
177
 
178
- app.post('/api/auth/verify', (req, res) => {
179
- const { challenge_id, pow_solution, pubKey } = req.body;
180
- const challenge = cache.get(`pow:${challenge_id}`);
181
- if (!challenge) return res.status(400).json({ error: "Challenge expired" });
 
 
182
 
183
- const hashArray = sha256.create().update(challenge.nonce + pubKey + pow_solution).array();
184
- if (!hasLeadingZeroBits(hashArray, challenge.difficulty)) return res.status(401).json({ error: "Invalid PoW" });
 
185
 
186
- cache.delete(`pow:${challenge_id}`);
187
- const token = jwt.sign({ pubKey, role: 'buyer_agent' }, JWT_SECRET, { expiresIn: '30d' });
188
- res.json({ token, message: "Identity Authenticated" });
189
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
 
191
- app.get('/api/discover', verifyAgentNode, async (req, res) => {
192
- const { category, mode } = req.query;
193
- const cacheKey = `discover:${category || 'all'}:${mode || 'all'}`;
194
- const cachedData = cache.get(cacheKey);
195
- if (cachedData) return res.json({ results: cachedData, source: 'cache' });
 
 
 
196
 
197
- let query = supabase.from('sellers').select('agent_id, display_name, endpoint, supported_modes, categories, capabilities');
198
- if (category) query = query.contains('categories', [category]);
199
- if (mode) query = query.contains('supported_modes', [mode]);
 
 
 
 
 
 
 
 
 
 
 
200
 
201
- const { data: sellers, error } = await query;
202
- if (error) return res.status(500).json({ error: "Discovery failed" });
203
- cache.set(cacheKey, sellers, 3600000);
204
- res.json({ results: sellers, source: 'db' });
205
- });
206
 
207
- // ============================================================================
208
- // PROTOCOL ROUTING (PROXY) & COMMIT
209
- // ============================================================================
210
- app.post('/api/route/:domain/handshake', verifyAgentNode, async (req, res) => {
211
- const { domain } = req.params;
212
- const session_id = `sess_${crypto.randomUUID()}`;
213
-
214
- let seller = cache.get(`seller:${domain}`);
215
- if (!seller) {
216
- // Hydrated custom_instructions directly from Registry Database records
217
- const { data } = await supabase.from('sellers').select('endpoint, public_key, custom_instructions').eq('agent_id', domain).single();
218
- if (!data) return res.status(404).json({ error: 'Seller not found' });
219
- seller = data;
220
- cache.set(`seller:${domain}`, seller, 3600000);
221
- }
222
 
223
- try {
224
- const fwd = await fetch(`${seller.endpoint}/handshake`, {
225
- method: 'POST',
226
- headers: {
227
- 'Content-Type': 'application/json',
228
- 'X-Clinch-Domain': domain
229
- },
230
- body: JSON.stringify({ session_id, ...req.body })
231
- });
232
-
233
- if (!fwd.ok) throw new Error("Seller rejected handshake context");
234
- const sellerResponse = await fwd.json();
235
-
236
- // Dynamic prompt instruction insertion mapped straight from the Registry record
237
- res.json({
238
- session_id,
239
- status: "ACTIVE",
240
- custom_instructions: seller.custom_instructions || null,
241
- ...sellerResponse
242
  });
243
- } catch (err) {
244
- res.status(502).json({ error: 'Seller handshake failed', detail: err.message });
245
- }
246
- });
247
-
248
- app.post('/api/route/:domain/counter', verifyAgentNode, async (req, res) => {
249
- const { domain } = req.params;
250
- const { session_id, turn, price, reason, buyer_sig } = req.body;
251
-
252
- let seller = cache.get(`seller:${domain}`);
253
- if (!seller) {
254
- const { data } = await supabase.from('sellers').select('endpoint, public_key').eq('agent_id', domain).single();
255
- if (!data) return res.status(404).json({ error: 'Seller not found' });
256
- seller = data;
257
- cache.set(`seller:${domain}`, seller, 3600000);
258
- }
259
 
260
- try {
261
- const fwd = await fetch(`${seller.endpoint}/counter`, {
262
- method: 'POST',
263
- headers: {
264
- 'Content-Type': 'application/json',
265
- 'X-Clinch-Session': session_id,
266
- 'X-Clinch-Registry': 'clinch-registry/0.1',
267
- 'X-Clinch-Domain': domain,
268
- 'X-Buyer-PubKey': req.node.pubKey
269
- },
270
- body: JSON.stringify({ session_id, turn, price, reason, buyer_sig })
271
- });
272
- res.json(await fwd.json());
273
  } catch (err) {
274
- res.status(502).json({ error: 'Seller endpoint unreachable', detail: err.message });
 
275
  }
276
  });
277
 
278
- app.post('/api/route/:session_id/commit', verifyAgentNode, async (req, res) => {
279
- const { session_id } = req.params;
280
- const { seller_agent_id, category, item, agreed_price, currency, agreed_terms, total_turns, mode, session_started, buyer_sig, seller_sig } = req.body;
281
-
282
- const { data: activeKey } = await supabase.from('registry_keys')
283
- .select('key_id, encrypted_private_key, chain_hash').order('valid_from', { ascending: false }).limit(1).single();
284
- if (!activeKey) return res.status(500).json({ error: 'No active registry key' });
285
-
286
- const privKeyBuffer = decryptData(activeKey.encrypted_private_key);
287
- const privKeyUint8 = new Uint8Array(privKeyBuffer);
288
-
289
- const artifactCore = {
290
- session_id, seller_agent_id, category, item, agreed_price, currency, agreed_terms, total_turns, mode,
291
- session_started, session_closed: new Date().toISOString(), buyer_sig, seller_sig
292
- };
293
-
294
- const msgBytes = new TextEncoder().encode(JSON.stringify(artifactCore));
295
- const registrySig = toHex(nacl.sign.detached(msgBytes, privKeyUint8));
296
- const chainHash = sha256(activeKey.chain_hash + session_id + registrySig);
297
-
298
- const { data: artifact, error } = await supabase.from('deal_artifacts').insert({
299
- session_id, seller_agent_id, buyer_pub_key: req.node.pubKey, category, item, agreed_price, currency,
300
- agreed_terms, total_turns, mode, session_started, registry_key_id: activeKey.key_id, buyer_sig, seller_sig,
301
- registry_sig: registrySig, chain_hash: chainHash
302
- }).select('artifact_id, chain_hash, registry_sig').single();
303
-
304
- if (error) return res.status(500).json({ error: error.message });
305
- res.json({ artifact_id: artifact.artifact_id, registry_sig: artifact.registry_sig, chain_hash: artifact.chain_hash });
306
- });
307
-
308
- app.get('/api/artifacts/:artifact_id', verifyAgentNode, async (req, res) => {
309
- const { data, error } = await supabase.from('deal_artifacts').select('*').eq('artifact_id', req.params.artifact_id).single();
310
- if (error || !data) return res.status(404).json({ error: 'Artifact not found' });
311
- res.json(data);
312
- });
313
-
314
  // ============================================================================
315
- // CALLBACK QUEUE (EXIT)
316
  // ============================================================================
317
- app.post('/api/route/:session_id/exit', verifyAgentNode, async (req, res) => {
318
- const { session_id } = req.params;
319
- const { seller_id } = req.body;
320
- const rawToken = `${session_id}:${seller_id}:${Date.now()}`;
321
- const token_hash = crypto.createHmac('sha256', JWT_SECRET).update(rawToken).digest('hex');
322
-
323
- await supabase.from('callback_tokens').insert({
324
- token_hash, session_id, seller_id, buyer_pub_key: req.node.pubKey, expires_at: new Date(Date.now() + 86400000)
325
- });
326
- res.json({ message: "Session exited", token_hash });
327
- });
328
-
329
- app.post('/api/callbacks/:token_hash', async (req, res) => {
330
- const { token_hash } = req.params;
331
- const payload = req.body;
332
- const { data: token } = await supabase.from('callback_tokens').select('*').eq('token_hash', token_hash).single();
333
 
334
- if (!token || token.status !== 'unused' || new Date() > new Date(token.expires_at)) {
335
- return res.status(404).json({ error: "Invalid or expired token" });
336
- }
337
 
338
- await supabase.from('callback_tokens').update({ status: 'consumed', consumed_at: new Date() }).eq('token_hash', token_hash);
339
- const { data: queueRow } = await supabase.from('callback_queue').insert({
340
- session_id: token.session_id, seller_id: token.seller_id, buyer_pub_key: token.buyer_pub_key, payload: payload
341
- }).select('id').single();
 
 
 
342
 
343
- const targetWs = activeClients.get(token.buyer_pub_key);
344
- if (targetWs && targetWs.readyState === 1) {
345
- targetWs.send(JSON.stringify({ type: 'CALLBACK', id: queueRow.id, session_id: token.session_id, payload: payload }));
346
- }
347
- res.json({ message: "Callback accepted and routed." });
348
- });
 
 
 
 
 
 
 
 
 
349
 
350
- // ============================================================================
351
- // SELLER DASHBOARD & METRICS
352
- // ============================================================================
353
- app.get('/api/dashboard/sellers', verifySellerAuth, async (req, res) => {
354
- const { data, error } = await supabase.from('sellers')
355
- .select('*')
356
- .eq('owner_id', req.sellerUser.id);
357
-
358
- if (error) return res.status(500).json({ error: error.message });
359
- res.json({ agents: data || [] });
360
- });
361
 
362
- app.post('/api/dashboard/sellers/register', verifySellerAuth, async (req, res) => {
363
- const { agent_id, display_name, public_key } = req.body;
364
- const normalizedId = agent_id.trim().toLowerCase();
 
 
 
365
 
366
- const { data: existing } = await supabase.from('sellers')
367
- .select('owner_id')
368
- .eq('agent_id', normalizedId)
369
- .maybeSingle();
370
 
371
- if (existing && existing.owner_id !== req.sellerUser.id) {
372
- return res.status(403).json({ error: "Agent Domain registration is reserved by another verified seller." });
373
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374
 
375
- const { error } = await supabase.from('sellers').upsert({
376
- agent_id: normalizedId,
377
- display_name,
378
- public_key,
379
- owner_id: req.sellerUser.id,
380
- verification_tier: 'unverified'
381
- }, { onConflict: 'agent_id' });
382
 
383
- if (error) return res.status(500).json({ error: error.message });
384
- res.json({ message: `Agent Domain claimed.` });
 
 
385
  });
386
 
387
  // ============================================================================
388
- // MACHINE-TO-MACHINE SELLER ROUTING UPDATES (ED25519 VERIFIED)
389
  // ============================================================================
390
- app.post('/api/sellers/update-endpoint', async (req, res) => {
391
- const { payload, public_key, signature } = req.body;
392
 
393
  try {
394
- const msgUint8 = new TextEncoder().encode(JSON.stringify(payload));
395
- const sigUint8 = new Uint8Array(signature.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
396
- const pubKeyUint8 = new Uint8Array(public_key.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
397
-
398
- if (!nacl.sign.detached.verify(msgUint8, sigUint8, pubKeyUint8)) {
399
- return res.status(401).json({ error: "Invalid Ed25519 signature." });
 
 
400
  }
401
 
402
- if (Date.now() - payload.timestamp > 300000) {
403
- return res.status(400).json({ error: "Payload expired." });
404
- }
405
-
406
- const normalizedId = payload.agent_id.trim().toLowerCase();
407
 
408
- const { data: seller, error: fetchErr } = await supabase
409
- .from('sellers')
410
- .select('agent_id, public_key')
411
- .eq('agent_id', normalizedId)
412
- .single();
413
 
414
- if (fetchErr || !seller) {
415
- return res.status(404).json({ error: `Domain '${normalizedId}' not claimed. Please register it on your dashboard first.` });
416
- }
417
 
418
- if (seller.public_key !== public_key) {
419
- console.error(`[Registry] Key Mismatch for ${normalizedId}. DB: ${seller.public_key} | Node: ${public_key}`);
420
- return res.status(403).json({ error: `Public key mismatch for ${normalizedId}. The private key in your .env does not match the dashboard claim.` });
 
 
421
  }
422
 
423
- const { error: updateErr } = await supabase
424
- .from('sellers')
425
- .update({
426
- endpoint: payload.endpoint,
427
- supported_modes: payload.supported_modes,
428
- categories: payload.categories,
429
- capabilities: payload.capabilities,
430
- custom_instructions: payload.custom_instructions // Write-Through custom prompt rules directly to DB
431
- })
432
- .eq('agent_id', normalizedId);
433
 
434
- if (updateErr) throw updateErr;
 
435
 
436
- cache.delete(`discover:all:all`);
437
- cache.delete(`seller:${normalizedId}`);
438
-
439
- res.json({ message: "Endpoint routing updated successfully" });
440
  } catch (err) {
441
- console.error("[Registry] Endpoint update failed:", err.message);
442
- res.status(500).json({ error: "Update failed", detail: err.message });
443
  }
444
  });
445
 
446
- app.post('/api/sessions/report', verifyAgentNode, async (req, res) => {
447
- const { session_id, seller_id, category, outcome, total_turns, final_price, list_price, mode } = req.body;
448
- await supabase.from('session_reports').insert({
449
- session_id, seller_id, category, outcome, total_turns, final_price, list_price, mode, buyer_sig: req.node.pubKey
450
- });
451
- cache.delete(`metrics:${seller_id}`);
452
- res.json({ message: 'Report received.' });
453
- });
454
-
455
- setInterval(async () => {
456
- const { data: sellers } = await supabase.from('sellers').select('agent_id');
457
- if (!sellers) return;
458
- for (const s of sellers) {
459
- const { data: reports } = await supabase.from('session_reports').select('*').eq('seller_id', s.agent_id);
460
- if (!reports || !reports.length) continue;
461
- const total = reports.length;
462
- const accepted = reports.filter(r => r.outcome === 'accepted').length;
463
- const score = Math.max(0, Math.min(100, (accepted / total) * 50));
464
- await supabase.from('seller_metrics').insert({ agent_id: s.agent_id, reputation_score: Math.round(score), session_count: total });
465
- }
466
- }, 6 * 60 * 60 * 1000);
467
-
468
  // ============================================================================
469
- // REGISTRY KEY ROTATION DAEMON
470
  // ============================================================================
471
- async function rotateRegistryKey() {
 
 
 
 
472
  try {
473
- const newKeyPair = nacl.sign.keyPair();
474
- const pubKeyHex = toHex(newKeyPair.publicKey);
475
- const encryptedSecret = encryptData(newKeyPair.secretKey);
476
- const validFrom = new Date();
477
- const validUntil = new Date(Date.now() + (24 * 60 * 60 * 1000));
478
- const key_id = `reg-key-${validFrom.toISOString().split('T')[0].replace(/-/g, '')}`;
479
-
480
- const { data: prevKey } = await supabase.from('registry_keys').select('key_id, chain_hash').order('valid_from', { ascending: false }).limit(1).single();
481
- const newChainHash = sha256((prevKey ? prevKey.chain_hash : "GENESIS") + pubKeyHex + validFrom.toISOString());
482
-
483
- await supabase.from('registry_keys').insert({
484
- key_id, public_key: pubKeyHex, encrypted_private_key: encryptedSecret, valid_from: validFrom,
485
- valid_until: validUntil, chain_hash: newChainHash, prev_key_id: prevKey ? prevKey.key_id : null
486
  });
487
- console.log(`[+] Key rotation complete. Active Key ID: ${key_id}`);
488
- } catch (err) { console.error("[-] Key rotation failed:", err); }
489
- }
490
-
491
- (async function initDaemon() {
492
- const { data } = await supabase.from('registry_keys').select('valid_until').order('valid_from', { ascending: false }).limit(1).single();
493
- if (!data || new Date() > new Date(data.valid_until)) await rotateRegistryKey();
494
- setInterval(async () => {
495
- const { data: activeKey } = await supabase.from('registry_keys').select('valid_until').order('valid_from', { ascending: false }).limit(1).single();
496
- if (activeKey && new Date() > new Date(activeKey.valid_until)) await rotateRegistryKey();
497
- }, 60 * 60 * 1000);
498
- })();
499
-
500
- server.listen(PORT, '0.0.0.0', () => console.log(`🚀 Clinch Registry running on port ${PORT}`));
 
1
  require('dotenv').config();
 
2
  const express = require('express');
 
 
 
 
 
 
3
  const { createClient } = require('@supabase/supabase-js');
4
+ const { ClinchSeller } = require('clinch-core');
5
 
6
  const app = express();
 
7
  app.use(express.json());
8
 
9
  // ============================================================================
10
+ // CONFIGURATION & INITIALIZATION
11
  // ============================================================================
12
  const PORT = process.env.PORT || 7860;
13
+ const REGISTRY_URL = process.env.REGISTRY_URL || 'https://everydaytok-agentq-core-logics.hf.space';
14
+ const PUBLIC_ENDPOINT = process.env.PUBLIC_ENDPOINT;
15
+ const SELLER_PRIV_KEY = process.env.SELLER_PRIVATE_KEY;
16
+
17
  const SUPABASE_URL = process.env.SUPABASE_URL;
18
  const SUPABASE_SERVICE_KEY = process.env.SUPABASE_SERVICE_KEY;
19
 
20
+ if (!SUPABASE_URL || !SUPABASE_SERVICE_KEY || !PUBLIC_ENDPOINT || !SELLER_PRIV_KEY) {
21
+ console.error("FATAL: Missing required dynamic configuration parameters in env.");
22
  process.exit(1);
23
  }
24
 
25
  const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_KEY);
26
 
27
+ const sellerCore = new ClinchSeller({
28
+ privateKeyHex: SELLER_PRIV_KEY,
29
+ registryUrl: REGISTRY_URL
30
+ });
31
+
32
+ sellerCore.on('log', msg => console.log(`[Ginger Log] ${msg}`));
33
+
34
  // ============================================================================
35
+ // IN-MEMORY CACHE & GC DAEMON
36
  // ============================================================================
37
+ const localRoomCache = new Map();
 
 
38
 
39
+ // Interval GC sweeps every 10 minutes to prevent resource bloat and flush dead caches
40
+ setInterval(async () => {
41
+ console.log("[Ginger GC] Initiating scheduled sweeping daemon...");
42
+ const now = Date.now();
43
+ let swept = 0;
44
+
45
+ // 1. Flush in-memory caches older than 30 minutes
46
+ for (const [roomId, room] of localRoomCache.entries()) {
47
+ if (now - new Date(room.created_at).getTime() > 1800000) {
48
+ localRoomCache.delete(roomId);
49
+ swept++;
50
+ }
51
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
+ // 2. Garbage collect un-joined pending rooms from Supabase older than 1 hour
54
+ const oneHourAgo = new Date(now - 3600000).toISOString();
55
+ const { error } = await supabase
56
+ .from('p2p_rooms')
57
+ .delete()
58
+ .eq('status', 'pending')
59
+ .lt('created_at', oneHourAgo);
60
+
61
+ if (error) console.error("[-] Failed to clean orphaned DB sessions:", error.message);
62
+ else console.log(`[Ginger GC] Flushed ${swept} dead memory caches.`);
63
+ }, 600000);
64
+
65
+ // Helper to generate secure, non-clashing 6-digit pairing PINs
66
+ async function generateUniquePin() {
67
+ let pin;
68
+ let exists = true;
69
+ while (exists) {
70
+ pin = Math.floor(100000 + Math.random() * 900000).toString();
71
+ const { data } = await supabase.from('p2p_rooms').select('pin').eq('pin', pin).maybeSingle();
72
+ if (!data) exists = false;
73
+ }
74
+ return pin;
75
  }
76
 
77
  // ============================================================================
78
+ // PUBLIC ROUTE: PERMANENT HANDLE SELF-REGISTRATION
79
  // ============================================================================
80
+ app.post('/anp/v1/register-handle', async (req, res) => {
81
+ const { handle, session_id, session_pub_key, callback_token } = req.body;
82
+
83
+ if (!handle || !session_id || !session_pub_key) {
84
+ return res.status(400).json({ error: "Missing required parameters to bind persistent handle." });
 
 
 
 
 
 
 
 
85
  }
 
 
86
 
87
+ const normalizedHandle = handle.toLowerCase().trim();
88
+
 
 
 
 
89
  try {
90
+ const { error } = await supabase
91
+ .from('p2p_handles')
92
+ .upsert({
93
+ handle: normalizedHandle,
94
+ session_id,
95
+ pub_key: session_pub_key,
96
+ callback_token,
97
+ updated_at: new Date().toISOString()
98
+ });
99
+
100
+ if (error) throw error;
101
+ console.log(`[Handle Registry] Binded permanent handle: ${normalizedHandle} ➔ ${session_id}`);
102
+ return res.json({ status: "BOUND", handle: normalizedHandle });
103
 
104
+ } catch (err) {
105
+ console.error("[Handle Registry Error]", err.message);
106
+ return res.status(500).json({ error: "Failed to map permanent handle." });
 
 
 
 
107
  }
108
+ });
 
 
 
 
 
109
 
110
  // ============================================================================
111
+ // ANP HANDSHAKE ROUTE (Creation & Joining - PIN vs Handles)
112
  // ============================================================================
113
+ app.post('/anp/v1/handshake', async (req, res) => {
114
+ const { session_id, session_pub_key, constraints } = req.body;
115
+
116
+ try {
117
+ // --- CASE 1: RECEIVER ATTEMPTING TO JOIN AN ACTIVE TARGET HANDLE / EMAIL ---
118
+ if (constraints && constraints.target_handle) {
119
+ const handle = constraints.target_handle.toLowerCase().trim();
120
+ console.log(`[Handshake] Session ${session_id} targeting handle: ${handle}`);
121
+
122
+ const { data: persistentHost, error: handleErr } = await supabase
123
+ .from('p2p_handles')
124
+ .select('*')
125
+ .eq('handle', handle)
126
+ .maybeSingle();
127
+
128
+ if (handleErr || !persistentHost) {
129
+ return res.status(404).json({ error: `Permanent handle '${handle}' is currently offline.` });
 
 
 
 
 
 
 
 
130
  }
131
+
132
+ // Dynamically instantiate a room pairing the client to the permanent host
133
+ const pin = await generateUniquePin();
134
+ const { data: room, error: roomErr } = await supabase
135
+ .from('p2p_rooms')
136
+ .insert({
137
+ pin,
138
+ initiator_session_id: persistentHost.session_id,
139
+ initiator_pub_key: persistentHost.pub_key,
140
+ initiator_callback_token: persistentHost.callback_token,
141
+ initiator_handle: handle,
142
+ receiver_session_id: session_id,
143
+ receiver_pub_key: session_pub_key,
144
+ status: 'active'
145
+ })
146
+ .select('*')
147
+ .single();
148
+
149
+ if (roomErr) throw roomErr;
150
+
151
+ localRoomCache.set(room.room_id, room); // Cache it
152
+
153
+ // Notify the host's passive WebSocket instantly via Registry callback
154
+ if (persistentHost.callback_token) {
155
+ await fetch(`${REGISTRY_URL}/api/callbacks/${persistentHost.callback_token}`, {
156
+ method: 'POST',
157
+ headers: { 'Content-Type': 'application/json' },
158
+ body: JSON.stringify({
159
+ msg_type: "handshake_joined",
160
+ session_id: persistentHost.session_id,
161
+ receiver_session_id: session_id,
162
+ message: `Peer (${session_id}) has initialized a session directly targeting your handle: ${handle}`
163
+ })
164
+ }).catch(() => console.warn(`[P2P Tunnel] Handshake notification failed for persistent host ${persistentHost.session_id}`));
165
  }
166
+
167
+ return res.json({
168
+ status: "ACCEPTED",
169
+ p2p_role: "receiver",
170
+ session_id,
171
+ capabilities: ["p2p_bridge"],
172
+ supported_modes: ["ANP/C"]
173
+ });
174
  }
 
 
 
175
 
176
+ // --- CASE 2: RECEIVER ATTEMPTING TO JOIN VIA 6-DIGIT PIN ---
177
+ if (constraints && constraints.p2p_pin) {
178
+ const pin = constraints.p2p_pin.toString().trim();
179
+ console.log(`[Handshake] Session ${session_id} joining room PIN: ${pin}`);
 
 
 
 
 
 
 
 
180
 
181
+ const { data: room, error } = await supabase
182
+ .from('p2p_rooms')
183
+ .select('*')
184
+ .eq('pin', pin)
185
+ .eq('status', 'pending')
186
+ .maybeSingle();
187
 
188
+ if (error || !room) {
189
+ return res.status(404).json({ error: "Active pairing room not found for this PIN." });
190
+ }
191
 
192
+ const { error: updateError } = await supabase
193
+ .from('p2p_rooms')
194
+ .update({
195
+ receiver_session_id: session_id,
196
+ receiver_pub_key: session_pub_key,
197
+ status: 'active'
198
+ })
199
+ .eq('room_id', room.room_id);
200
+
201
+ if (updateError) throw updateError;
202
+
203
+ room.receiver_session_id = session_id;
204
+ room.receiver_pub_key = session_pub_key;
205
+ room.status = 'active';
206
+ localRoomCache.set(room.room_id, room); // Cache update
207
+
208
+ // Trigger real-time re-engagement on the initiator
209
+ if (room.initiator_callback_token) {
210
+ await fetch(`${REGISTRY_URL}/api/callbacks/${room.initiator_callback_token}`, {
211
+ method: 'POST',
212
+ headers: { 'Content-Type': 'application/json' },
213
+ body: JSON.stringify({
214
+ msg_type: "handshake_joined",
215
+ session_id: room.initiator_session_id,
216
+ receiver_session_id: session_id,
217
+ message: "Your peer has successfully entered your room. Bargaining coordinates are active."
218
+ })
219
+ }).catch(() => console.warn(`[P2P Tunnel] Handshake callback failed for initiator ${room.initiator_session_id}`));
220
+ }
221
 
222
+ return res.json({
223
+ status: "ACCEPTED",
224
+ p2p_role: "receiver",
225
+ session_id,
226
+ capabilities: ["p2p_bridge"],
227
+ supported_modes: ["ANP/C"]
228
+ });
229
+ }
230
 
231
+ // --- CASE 3: INITIATOR CREATING TEMPORARY ANONYMOUS SESSION (PIN GENERATION) ---
232
+ const pin = await generateUniquePin();
233
+ console.log(`[Handshake] Generating temporary PIN. Session: ${session_id} | PIN: ${pin}`);
234
+
235
+ const { data: newRoom, error: insertError } = await supabase
236
+ .from('p2p_rooms')
237
+ .insert({
238
+ pin,
239
+ initiator_session_id: session_id,
240
+ initiator_pub_key: session_pub_key,
241
+ status: 'pending'
242
+ })
243
+ .select('*')
244
+ .single();
245
 
246
+ if (insertError) throw insertError;
 
 
 
 
247
 
248
+ localRoomCache.set(newRoom.room_id, newRoom); // Cache it
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
 
250
+ return res.json({
251
+ status: "ACCEPTED",
252
+ p2p_role: "initiator",
253
+ p2p_pin: pin,
254
+ session_id,
255
+ capabilities: ["p2p_bridge"],
256
+ supported_modes: ["ANP/C"]
 
 
 
 
 
 
 
 
 
 
 
 
257
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
258
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
  } catch (err) {
260
+ console.error("[Handshake Error]", err.message);
261
+ return res.status(500).json({ error: "Handshake pairing failed internally." });
262
  }
263
  });
264
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
  // ============================================================================
266
+ // ANP COUNTER ROUTE (Real-time Message Tunneling)
267
  // ============================================================================
268
+ app.post('/anp/v1/counter', async (req, res) => {
269
+ const { session_id, turn, price, reason, buyer_sig } = req.body;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
 
271
+ try {
272
+ let room = null;
 
273
 
274
+ // 1. Read-Through local Cache first to bypass Postgres overhead
275
+ for (const cachedRoom of localRoomCache.values()) {
276
+ if ((cachedRoom.initiator_session_id === session_id || cachedRoom.receiver_session_id === session_id) && cachedRoom.status === 'active') {
277
+ room = cachedRoom;
278
+ break;
279
+ }
280
+ }
281
 
282
+ // 2. Fallback to Supabase if cache missed
283
+ if (!room) {
284
+ const { data, error } = await supabase
285
+ .from('p2p_rooms')
286
+ .select('*')
287
+ .or(`initiator_session_id.eq.${session_id},receiver_session_id.eq.${session_id}`)
288
+ .eq('status', 'active')
289
+ .maybeSingle();
290
+
291
+ if (error || !data) {
292
+ return res.status(404).json({ error: "Active paired P2P session not found." });
293
+ }
294
+ room = data;
295
+ localRoomCache.set(room.room_id, room); // Re-hydrate cache
296
+ }
297
 
298
+ const isInitiator = room.initiator_session_id === session_id;
299
+ const senderPubKey = isInitiator ? room.initiator_pub_key : room.receiver_pub_key;
300
+ const targetSessionId = isInitiator ? room.receiver_session_id : room.initiator_session_id;
301
+ const targetCallbackToken = isInitiator ? room.receiver_callback_token : room.initiator_callback_token;
 
 
 
 
 
 
 
302
 
303
+ // Cryptographically verify the buyer's signature locally on Ginger
304
+ const isValid = sellerCore.verifyBuyerSignature(
305
+ { session_id, turn, price, reason },
306
+ buyer_sig,
307
+ senderPubKey
308
+ );
309
 
310
+ if (!isValid) {
311
+ return res.status(401).json({ error: "Cryptographic signature mismatch on turn payload." });
312
+ }
 
313
 
314
+ // Commit turn transaction log to Supabase (Write-Through)
315
+ const { error: msgError } = await supabase
316
+ .from('p2p_messages')
317
+ .insert({
318
+ room_id: room.room_id,
319
+ turn,
320
+ sender_session_id: session_id,
321
+ price,
322
+ reason,
323
+ signature: buyer_sig
324
+ });
325
+
326
+ if (msgError) throw msgError;
327
+
328
+ // Route payload instantly through the Registry callback to the target peer
329
+ if (targetCallbackToken) {
330
+ console.log(`[P2P Tunnel] Routing Turn ${turn} from ${session_id} ➔ ${targetSessionId}`);
331
+
332
+ const fwd = await fetch(`${REGISTRY_URL}/api/callbacks/${targetCallbackToken}`, {
333
+ method: 'POST',
334
+ headers: { 'Content-Type': 'application/json' },
335
+ body: JSON.stringify({
336
+ session_id: targetSessionId,
337
+ turn,
338
+ price,
339
+ message: reason,
340
+ buyer_sig,
341
+ timestamp: new Date().toISOString()
342
+ })
343
+ });
344
+
345
+ if (!fwd.ok) {
346
+ console.warn(`[P2P Tunnel] Registry rejected callback routing: ${await fwd.text()}`);
347
+ }
348
+ } else {
349
+ console.log(`[P2P Tunnel] Peer ${targetSessionId} has not registered a callback token yet.`);
350
+ }
351
 
352
+ return res.json({
353
+ status: "ROUTED",
354
+ session_id,
355
+ turn,
356
+ timestamp: new Date().toISOString()
357
+ });
 
358
 
359
+ } catch (err) {
360
+ console.error("[Counter Error]", err.message);
361
+ return res.status(500).json({ error: "Failed to process and route turn payload." });
362
+ }
363
  });
364
 
365
  // ============================================================================
366
+ // GINGER CALLBACK TOKEN REGISTRATION
367
  // ============================================================================
368
+ app.post('/anp/v1/exit', async (req, res) => {
369
+ const { session_id, callback_token } = req.body;
370
 
371
  try {
372
+ const { data: room, error } = await supabase
373
+ .from('p2p_rooms')
374
+ .select('*')
375
+ .or(`initiator_session_id.eq.${session_id},receiver_session_id.eq.${session_id}`)
376
+ .maybeSingle();
377
+
378
+ if (error || !room) {
379
+ return res.status(404).json({ error: "P2P Session not found." });
380
  }
381
 
382
+ const isInitiator = room.initiator_session_id === session_id;
383
+ const updateField = isInitiator ? { initiator_callback_token: callback_token } : { receiver_callback_token: callback_token };
 
 
 
384
 
385
+ const { error: updateError } = await supabase
386
+ .from('p2p_rooms')
387
+ .update(updateField)
388
+ .eq('room_id', room.room_id);
 
389
 
390
+ if (updateError) throw updateError;
 
 
391
 
392
+ // Dynamically update the cached room record
393
+ if (localRoomCache.has(room.room_id)) {
394
+ const cached = localRoomCache.get(room.room_id);
395
+ if (isInitiator) cached.initiator_callback_token = callback_token;
396
+ else cached.receiver_callback_token = callback_token;
397
  }
398
 
399
+ // Also check if this session registered a permanent handle, if so, update its token
400
+ await supabase
401
+ .from('p2p_handles')
402
+ .update({ callback_token })
403
+ .eq('session_id', session_id);
 
 
 
 
 
404
 
405
+ console.log(`[Registry Link] Registered callback token for session ${session_id}`);
406
+ return res.json({ status: "REGISTERED", session_id });
407
 
 
 
 
 
408
  } catch (err) {
409
+ console.error("[Exit Token Register Error]", err.message);
410
+ return res.status(500).json({ error: "Failed to register active callback token." });
411
  }
412
  });
413
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
414
  // ============================================================================
415
+ // BOOT
416
  // ============================================================================
417
+ app.listen(PORT, async () => {
418
+ console.log(`\n🧡 Ginger P2P Broker Online | Port ${PORT}`);
419
+ console.log(` Registry Target: ${REGISTRY_URL}`);
420
+ console.log(` Stable Public Endpoint: ${PUBLIC_ENDPOINT}\n`);
421
+
422
  try {
423
+ // Register standard routing properties. Custom Prompt instructions are now
424
+ // managed completely and safely via the Dashboard (Control Plane) record.
425
+ await sellerCore.registerEndpoint({
426
+ agent_id: 'ginger.anp',
427
+ endpoint: `${PUBLIC_ENDPOINT}/anp/v1`,
428
+ supported_modes: ['ANP/C'],
429
+ categories: ['p2p_bridge', 'mediation', 'scheduling'],
430
+ capabilities: ['p2p_bridge', 'room_routing', 'temporary_pin', 'permanent_handle']
 
 
 
 
 
431
  });
432
+ } catch (e) {
433
+ console.error(`[-] Failed to self-register ginger.anp with the registry: ${e.message}`);
434
+ console.error(` Ensure you claimed 'ginger.anp' on the dashboard first using the matching SELLER_PRIVATE_KEY.`);
435
+ }
436
+ });