Spaces:
Sleeping
Sleeping
Update app.js
Browse files
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 |
-
//
|
| 18 |
// ============================================================================
|
| 19 |
const PORT = process.env.PORT || 7860;
|
| 20 |
-
const
|
| 21 |
-
const
|
|
|
|
|
|
|
| 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 || !
|
| 26 |
-
console.error("FATAL: Missing required
|
| 27 |
process.exit(1);
|
| 28 |
}
|
| 29 |
|
| 30 |
const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_KEY);
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
// ============================================================================
|
| 33 |
-
//
|
| 34 |
// ============================================================================
|
| 35 |
-
|
| 36 |
-
return Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
|
| 37 |
-
}
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 63 |
-
const
|
| 64 |
-
const
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
}
|
| 74 |
|
| 75 |
// ============================================================================
|
| 76 |
-
//
|
| 77 |
// ============================================================================
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 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 |
-
|
| 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
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 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 |
-
//
|
| 128 |
// ============================================================================
|
| 129 |
-
|
| 130 |
-
const
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 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 |
-
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
}
|
| 158 |
-
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
}
|
| 161 |
-
});
|
| 162 |
-
ws.on('close', () => { if (authenticatedPubKey) activeClients.delete(authenticatedPubKey); });
|
| 163 |
-
});
|
| 164 |
|
| 165 |
-
//
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 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 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
|
|
|
|
|
|
| 182 |
|
| 183 |
-
|
| 184 |
-
|
|
|
|
| 185 |
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
|
| 201 |
-
|
| 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 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 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 |
-
|
|
|
|
| 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 |
-
//
|
| 316 |
// ============================================================================
|
| 317 |
-
app.post('/
|
| 318 |
-
const { session_id } = req.
|
| 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 |
-
|
| 335 |
-
|
| 336 |
-
}
|
| 337 |
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
|
|
|
|
|
|
|
|
|
| 342 |
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 349 |
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 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 |
-
|
| 363 |
-
|
| 364 |
-
|
|
|
|
|
|
|
|
|
|
| 365 |
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
.maybeSingle();
|
| 370 |
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 374 |
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
}, { onConflict: 'agent_id' });
|
| 382 |
|
| 383 |
-
|
| 384 |
-
|
|
|
|
|
|
|
| 385 |
});
|
| 386 |
|
| 387 |
// ============================================================================
|
| 388 |
-
//
|
| 389 |
// ============================================================================
|
| 390 |
-
app.post('/
|
| 391 |
-
const {
|
| 392 |
|
| 393 |
try {
|
| 394 |
-
const
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
|
|
|
|
|
|
| 400 |
}
|
| 401 |
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
}
|
| 405 |
-
|
| 406 |
-
const normalizedId = payload.agent_id.trim().toLowerCase();
|
| 407 |
|
| 408 |
-
const {
|
| 409 |
-
.from('
|
| 410 |
-
.
|
| 411 |
-
.eq('
|
| 412 |
-
.single();
|
| 413 |
|
| 414 |
-
if (
|
| 415 |
-
return res.status(404).json({ error: `Domain '${normalizedId}' not claimed. Please register it on your dashboard first.` });
|
| 416 |
-
}
|
| 417 |
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
|
|
|
|
|
|
| 421 |
}
|
| 422 |
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
.
|
| 426 |
-
|
| 427 |
-
|
| 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 |
-
|
|
|
|
| 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("[
|
| 442 |
-
res.status(500).json({ error: "
|
| 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 |
-
//
|
| 470 |
// ============================================================================
|
| 471 |
-
async
|
|
|
|
|
|
|
|
|
|
|
|
|
| 472 |
try {
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 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 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 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 |
+
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|