publicstring commited on
Commit
d3b28ac
·
verified ·
1 Parent(s): 0c9bf0c

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +466 -167
app.js CHANGED
@@ -1,201 +1,500 @@
1
  require('dotenv').config();
2
- const express = require('express');
3
- const fs = require('fs');
4
- const path = require('path');
5
- const { ClinchSeller } = require('clinch-core');
6
- const { GoogleGenAI } = require('@google/genai');
 
 
 
 
7
 
8
  const app = express();
 
9
  app.use(express.json());
10
 
11
- // ============================================================
12
- // CONFIG
13
- // ============================================================
14
- const PORT = process.env.PORT || 7860;
15
- const REGISTRY_URL = process.env.REGISTRY_URL;
16
- const SELLER_PRIV_KEY = process.env.SELLER_PRIVATE_KEY;
17
- const PUBLIC_ENDPOINT = process.env.PUBLIC_ENDPOINT;
18
- const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
19
-
20
- const sellerCore = new ClinchSeller({
21
- privateKeyHex: SELLER_PRIV_KEY,
22
- registryUrl: REGISTRY_URL
23
- });
24
- sellerCore.on('log', msg => console.log(msg));
 
 
 
 
 
 
 
 
25
 
26
- if (!PUBLIC_ENDPOINT) {
27
- console.error('FATAL: PUBLIC_ENDPOINT not set.');
28
- console.error('Set it to your stable public URL — domain, load balancer, reverse proxy.');
29
- console.error('Example: https://mystore.com/anp/v1');
30
- process.exit(1);
 
 
31
  }
32
 
33
- const ai = GEMINI_API_KEY ? new GoogleGenAI({ apiKey: GEMINI_API_KEY }) : null;
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
- // ============================================================
36
- // PLUGIN LOADER
37
- // ============================================================
38
- const vendors = {};
 
39
 
40
- function loadModules() {
41
- const dir = path.join(__dirname, 'modules');
42
- if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); return; }
 
 
 
43
 
44
- for (const file of fs.readdirSync(dir).filter(f => f.endsWith('.js'))) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  try {
46
- const mod = require(path.join(dir, file));
47
- if (!mod.agent_id || !mod.getItemConstraints) {
48
- console.warn(`[Modules] Skipped ${file} — missing agent_id or getItemConstraints`);
49
- continue;
50
- }
51
- vendors[mod.agent_id] = mod;
52
- console.log(`[Modules] Loaded: ${mod.agent_id}`);
53
  } catch (e) {
54
- console.error(`[Modules] Failed to load ${file}:`, e.message);
55
  }
56
- }
57
  }
58
 
59
- loadModules();
60
-
61
- // ============================================================
62
- // AI ENGINE
63
- // ============================================================
64
- async function evaluateOffer(buyerOffer, itemData, turn) {
65
- if (!ai) {
66
- const range = itemData.list_price - itemData.floor_price;
67
- const step = range * 0.07;
68
- const counter = Math.max(itemData.floor_price, itemData.list_price - step * turn);
69
- return { price: Math.round(counter * 100) / 100, reason: 'Meeting you partway.' };
70
- }
71
-
72
- const prompt = `You are a professional seller agent.
73
-
74
- Item: ${itemData.id}
75
- List price: $${itemData.list_price}
76
- Floor price (never go below this): $${itemData.floor_price}
77
- Buyer offered: $${buyerOffer}
78
- Turn: ${turn}
79
-
80
- Rules:
81
- - If buyer is within 5% of floor: accept at floor price
82
- - Otherwise: counter, moving 5-8% toward buyer per turn
83
- - One sentence, professional, brief
84
-
85
- Respond ONLY with JSON (no markdown):
86
- {"price": <number>, "reason": "<one sentence>"}`;
87
-
88
- try {
89
- const res = await ai.models.generateContent({
90
- model: 'gemini-2.5-flash',
91
- contents: prompt,
92
- config: { responseMimeType: 'application/json', temperature: 0.15 }
93
- });
94
- const result = JSON.parse(res.text());
95
- return {
96
- price: Math.max(result.price, itemData.floor_price),
97
- reason: result.reason
98
- };
99
- } catch (e) {
100
- console.error('[AI Engine]', e.message);
101
- return { price: itemData.list_price, reason: 'Unable to adjust price at this time.' };
102
- }
103
  }
104
 
105
- // ============================================================
106
- // ANP ROUTES
107
- // ============================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
- app.post('/anp/v1/handshake', (req, res) => {
110
- const { session_id, constraints, mode } = req.body;
111
- const domain = req.headers['x-clinch-domain'];
112
 
113
- console.log(`[Handshake] ${session_id} | Mode: ${mode} | Domain: ${domain}`);
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
- const vendor = vendors[domain];
116
- if (!vendor) {
117
- return res.status(404).json({ error: `Domain ${domain} not hosted here` });
118
- }
119
 
120
- res.json({
121
- status: 'ACCEPTED',
122
- session_id,
123
- capabilities: vendor.capabilities || [],
124
- supported_modes: vendor.supported_modes || ['ANP/C']
125
- });
126
  });
127
 
128
- app.post('/anp/v1/counter', async (req, res) => {
129
- const { session_id, price, turn, reason, buyer_sig, constraints } = req.body;
130
- const domain = req.headers['x-clinch-domain'];
131
- const buyerPub = req.headers['x-buyer-pubkey'];
132
- const itemIntent = constraints?.item || req.body.item_intent;
133
-
134
- console.log(`[Counter] ${session_id} | Turn ${turn} | $${price} | Item: ${itemIntent}`);
135
-
136
- const vendor = vendors[domain];
137
- if (!vendor) return res.status(404).json({ error: `Domain ${domain} not hosted here` });
138
-
139
- if (buyer_sig && buyerPub) {
140
- const valid = sellerCore.verifyBuyerSignature(
141
- { session_id, turn, price, reason },
142
- buyer_sig,
143
- buyerPub
144
- );
145
- if (!valid) console.warn(`[Security] Bad buyer sig on ${session_id} — logging, not rejecting`);
146
- }
147
-
148
- const itemData = vendor.getItemConstraints(itemIntent);
149
- if (!itemData) return res.status(400).json({ error: `Item not found: ${itemIntent}` });
150
-
151
- if (price >= itemData.floor_price * 0.95) {
152
- return res.json({
153
- session_id,
154
- msg_type: 'accept',
155
- price: Math.max(price, itemData.floor_price),
156
- reason: "We have a deal.",
157
- timestamp: new Date().toISOString()
158
  });
159
- }
 
160
 
161
- const { price: counter, reason: counterReason } = await evaluateOffer(price, itemData, turn || 1);
 
 
 
162
 
163
- res.json({
164
- session_id,
165
- msg_type: 'counter',
166
- price: counter,
167
- reason: counterReason,
168
- timestamp: new Date().toISOString()
169
- });
 
 
 
 
 
 
 
170
  });
171
 
172
- app.post('/anp/v1/accept', (req, res) => {
173
- const { session_id, price } = req.body;
174
- console.log(`[Deal] Session ${session_id} closed at $${price}`);
175
- res.json({ status: 'COMMITTED', session_id, price });
 
 
 
 
 
 
176
  });
177
 
178
- // ============================================================
179
- // BOOT
180
- // ============================================================
181
- app.listen(PORT, async () => {
182
- console.log(`\n💼 Seller Hub | Port ${PORT} | Endpoint: ${PUBLIC_ENDPOINT}`);
183
- console.log(` Vendors: ${Object.keys(vendors).join(', ') || 'none loaded'}\n`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
 
185
- for (const [domain, mod] of Object.entries(vendors)) {
186
  try {
187
- await sellerCore.registerEndpoint({
188
- agent_id: mod.agent_id,
189
- endpoint: PUBLIC_ENDPOINT,
190
- supported_modes: mod.supported_modes || ['ANP/C'],
191
- categories: mod.categories || [],
192
- capabilities: mod.capabilities || []
193
- });
194
- } catch (e) {
195
- console.error(`[Boot] Failed to register ${domain}:`);
196
- console.error(` -> ${e.message}`);
197
- console.error(` -> Did you claim '${domain}' on the dashboard and bind it to this .env private key?`);
198
- console.error(` -> If you don't own '${domain}', delete its file from your 'modules' folder!`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  }
200
- }
201
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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}`));