publicstring commited on
Commit
7b3361b
·
verified ·
1 Parent(s): f565208

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +62 -20
app.js CHANGED
@@ -16,7 +16,7 @@ app.use(express.json());
16
  const PORT = process.env.PORT || 7860;
17
  const PUBLIC_ENDPOINT = process.env.PUBLIC_ENDPOINT;
18
  const SELLER_PRIV_KEY = process.env.SELLER_PRIVATE_KEY;
19
- const AGENT_ID = process.env.AGENT_ID || 'ginger.anp'; // [FIX]: Added target ID tracking
20
 
21
  const SUPABASE_URL = process.env.SUPABASE_URL;
22
  const SUPABASE_SERVICE_KEY = process.env.SUPABASE_SERVICE_KEY;
@@ -144,7 +144,8 @@ setInterval(async () => {
144
  }
145
 
146
  const oneHourAgo = new Date(now - 3600000).toISOString();
147
- const { error } = await supabase.from('p2p_rooms').delete().eq('status', 'pending').lt('created_at', oneHourAgo);
 
148
 
149
  if (error) console.error("[-] Failed to clean orphaned DB sessions:", error.message);
150
  else console.log(`[Ginger GC] Flushed ${swept} dead memory caches.`);
@@ -155,7 +156,8 @@ async function generateUniquePin() {
155
  let exists = true;
156
  while (exists) {
157
  pin = Math.floor(100000 + Math.random() * 900000).toString();
158
- const { data } = await supabase.from('p2p_rooms').select('pin').eq('pin', pin).maybeSingle();
 
159
  if (!data) exists = false;
160
  }
161
  return pin;
@@ -165,7 +167,7 @@ async function generateUniquePin() {
165
  // PUBLIC ROUTE: PERMANENT HANDLE SELF-REGISTRATION
166
  // ============================================================================
167
  app.post('/anp/v1/register-handle', async (req, res) => {
168
- const { handle, session_id, session_pub_key } = req.body;
169
 
170
  if (!handle || !session_id || !session_pub_key) {
171
  return res.status(400).json({ error: "Missing required parameters." });
@@ -174,18 +176,21 @@ app.post('/anp/v1/register-handle', async (req, res) => {
174
  const normalizedHandle = handle.toLowerCase().trim();
175
 
176
  try {
177
- const { error } = await supabase.from('p2p_handles').upsert({
 
178
  handle: normalizedHandle,
179
  session_id,
180
  pub_key: session_pub_key,
 
181
  updated_at: new Date().toISOString()
182
  });
183
 
184
  if (error) throw error;
185
- console.log(`[Handle Registry] Binded permanent handle: ${normalizedHandle} ➔ ${session_pub_key.substring(0,8)}`);
186
  return res.json({ status: "BOUND", handle: normalizedHandle });
187
 
188
  } catch (err) {
 
189
  return res.status(500).json({ error: "Failed to map permanent handle." });
190
  }
191
  });
@@ -194,9 +199,8 @@ app.post('/anp/v1/register-handle', async (req, res) => {
194
  // ANP HANDSHAKE ROUTE (Creation & Joining)
195
  // ============================================================================
196
  app.post('/anp/v1/handshake', async (req, res) => {
197
- const { session_id, buyer_pub_key, constraints, blind_auth_token } = req.body;
198
 
199
- // Blind Key Pass — log receipt so sellers can audit per-session
200
  if (blind_auth_token) {
201
  console.log(`[Auth] Blind key token received | session: ${session_id} | buyer: ${buyer_pub_key?.substring(0, 8)}...`);
202
  }
@@ -208,17 +212,24 @@ app.post('/anp/v1/handshake', async (req, res) => {
208
  // --- CASE 1: JOINING A PERMANENT HANDLE ---
209
  if (constraints && constraints.target_handle) {
210
  const handle = constraints.target_handle.toLowerCase().trim();
211
- const { data: persistentHost, error: handleErr } = await supabase.from('p2p_handles').select('*').eq('handle', handle).maybeSingle();
 
212
 
213
  if (handleErr || !persistentHost) return res.status(404).json({ type: 'CANCEL', reason: `Handle '${handle}' offline.` });
214
 
215
  const pin = await generateUniquePin();
216
- const { data: room, error: roomErr } = await supabase.from('p2p_rooms').insert({
 
 
217
  pin,
218
  initiator_session_id: persistentHost.session_id,
219
  initiator_pub_key: persistentHost.pub_key,
 
 
220
  receiver_session_id: session_id,
221
  receiver_pub_key: buyer_pub_key,
 
 
222
  status: 'active'
223
  }).select('*').single();
224
 
@@ -244,14 +255,22 @@ app.post('/anp/v1/handshake', async (req, res) => {
244
  // --- CASE 2: JOINING VIA 6-DIGIT PIN ---
245
  if (constraints && constraints.p2p_pin) {
246
  const pin = constraints.p2p_pin.toString().trim();
247
- const { data: room, error } = await supabase.from('p2p_rooms').select('*').eq('pin', pin).eq('status', 'pending').maybeSingle();
 
248
 
249
  if (error || !room) return res.status(404).json({ type: 'CANCEL', reason: "Active pairing room not found." });
250
 
251
- await supabase.from('p2p_rooms').update({ receiver_session_id: session_id, receiver_pub_key: buyer_pub_key, status: 'active' }).eq('room_id', room.room_id);
 
 
 
 
 
 
252
 
253
  room.receiver_session_id = session_id;
254
  room.receiver_pub_key = buyer_pub_key;
 
255
  room.status = 'active';
256
  localRoomCache.set(room.room_id, room);
257
 
@@ -267,8 +286,13 @@ app.post('/anp/v1/handshake', async (req, res) => {
267
 
268
  // --- CASE 3: CREATING TEMPORARY ROOM ---
269
  const pin = await generateUniquePin();
270
- const { data: newRoom, error: insertError } = await supabase.from('p2p_rooms').insert({
271
- pin, initiator_session_id: session_id, initiator_pub_key: buyer_pub_key, status: 'pending'
 
 
 
 
 
272
  }).select('*').single();
273
 
274
  if (insertError) throw insertError;
@@ -287,7 +311,7 @@ app.post('/anp/v1/handshake', async (req, res) => {
287
  // ANP COUNTER ROUTE (Real-time Message Tunneling + AI Mediation)
288
  // ============================================================================
289
  app.post('/anp/v1/counter', async (req, res) => {
290
- const { session_id, turn, price, reason } = req.body;
291
  const currentTurn = turn || 2;
292
  const nextTurn = currentTurn + 1;
293
 
@@ -295,7 +319,8 @@ app.post('/anp/v1/counter', async (req, res) => {
295
  let room = Array.from(localRoomCache.values()).find(r => (r.initiator_session_id === session_id || r.receiver_session_id === session_id) && r.status === 'active');
296
 
297
  if (!room) {
298
- const { data, error } = await supabase.from('p2p_rooms').select('*').or(`initiator_session_id.eq.${session_id},receiver_session_id.eq.${session_id}`).eq('status', 'active').maybeSingle();
 
299
  if (error || !data) return res.status(404).json({ type: 'CANCEL', reason: "P2P session dropped or inactive." });
300
  room = data;
301
  localRoomCache.set(room.room_id, room);
@@ -305,18 +330,36 @@ app.post('/anp/v1/counter', async (req, res) => {
305
  const targetSessionId = isInitiator ? room.receiver_session_id : room.initiator_session_id;
306
  const targetPubKey = isInitiator ? room.receiver_pub_key : room.initiator_pub_key;
307
 
308
- // --- AI MEDIATION INTERCEPT ---
309
  let routedPrice = price;
310
  let routedMessage = reason;
311
 
 
 
 
 
 
 
 
 
 
 
 
 
312
  if (reason && reason.toLowerCase().includes('@mediate')) {
313
  console.log(`[AI] Mediation requested by ${session_id}`);
314
  const aiSuggestion = await mediatePrice(price, "P2P Service");
315
  routedPrice = aiSuggestion.price;
316
  routedMessage = `[🤖 Ginger AI Mediator] ${aiSuggestion.message}`;
317
 
318
- // Log mediation occurrence
319
- await supabase.from('p2p_messages').insert({ room_id: room.room_id, turn: currentTurn, sender_session_id: 'ginger_ai', price: routedPrice, reason: routedMessage });
 
 
 
 
 
 
 
320
  }
321
 
322
  // --- PUSH ASYNC CALLBACK TO PEER ---
@@ -367,7 +410,6 @@ app.listen(PORT, async () => {
367
  // Refresh token every 5 days before the 7-day expiry
368
  setInterval(() => core.initialize().catch(() => console.error("Token refresh failed")), 5 * 24 * 60 * 60 * 1000);
369
 
370
- // [FIX]: Passed target domain (AGENT_ID) as first arg, switched 'tags' option to 'supported_modes'
371
  await core.registerNode(
372
  AGENT_ID,
373
  `${PUBLIC_ENDPOINT}`,
 
16
  const PORT = process.env.PORT || 7860;
17
  const PUBLIC_ENDPOINT = process.env.PUBLIC_ENDPOINT;
18
  const SELLER_PRIV_KEY = process.env.SELLER_PRIVATE_KEY;
19
+ const AGENT_ID = process.env.AGENT_ID || 'ginger.anp';
20
 
21
  const SUPABASE_URL = process.env.SUPABASE_URL;
22
  const SUPABASE_SERVICE_KEY = process.env.SUPABASE_SERVICE_KEY;
 
144
  }
145
 
146
  const oneHourAgo = new Date(now - 3600000).toISOString();
147
+ // [FIX]: Aligned GC operation strictly against the "ginger_rooms" table
148
+ const { error } = await supabase.from('ginger_rooms').delete().eq('status', 'pending').lt('created_at', oneHourAgo);
149
 
150
  if (error) console.error("[-] Failed to clean orphaned DB sessions:", error.message);
151
  else console.log(`[Ginger GC] Flushed ${swept} dead memory caches.`);
 
156
  let exists = true;
157
  while (exists) {
158
  pin = Math.floor(100000 + Math.random() * 900000).toString();
159
+ // [FIX]: Querying against schema table "ginger_rooms"
160
+ const { data } = await supabase.from('ginger_rooms').select('pin').eq('pin', pin).maybeSingle();
161
  if (!data) exists = false;
162
  }
163
  return pin;
 
167
  // PUBLIC ROUTE: PERMANENT HANDLE SELF-REGISTRATION
168
  // ============================================================================
169
  app.post('/anp/v1/register-handle', async (req, res) => {
170
+ const { handle, session_id, session_pub_key, callback_token } = req.body;
171
 
172
  if (!handle || !session_id || !session_pub_key) {
173
  return res.status(400).json({ error: "Missing required parameters." });
 
176
  const normalizedHandle = handle.toLowerCase().trim();
177
 
178
  try {
179
+ // [FIX]: Aligned to schema table "ginger_handles" and populated "callback_token"
180
+ const { error } = await supabase.from('ginger_handles').upsert({
181
  handle: normalizedHandle,
182
  session_id,
183
  pub_key: session_pub_key,
184
+ callback_token: callback_token || null,
185
  updated_at: new Date().toISOString()
186
  });
187
 
188
  if (error) throw error;
189
+ console.log(`[Handle Registry] Bound permanent handle: ${normalizedHandle} ➔ ${session_pub_key.substring(0,8)}`);
190
  return res.json({ status: "BOUND", handle: normalizedHandle });
191
 
192
  } catch (err) {
193
+ console.error("[-] Handle registration error:", err.message);
194
  return res.status(500).json({ error: "Failed to map permanent handle." });
195
  }
196
  });
 
199
  // ANP HANDSHAKE ROUTE (Creation & Joining)
200
  // ============================================================================
201
  app.post('/anp/v1/handshake', async (req, res) => {
202
+ const { session_id, buyer_pub_key, constraints, blind_auth_token, callback_token } = req.body;
203
 
 
204
  if (blind_auth_token) {
205
  console.log(`[Auth] Blind key token received | session: ${session_id} | buyer: ${buyer_pub_key?.substring(0, 8)}...`);
206
  }
 
212
  // --- CASE 1: JOINING A PERMANENT HANDLE ---
213
  if (constraints && constraints.target_handle) {
214
  const handle = constraints.target_handle.toLowerCase().trim();
215
+ // [FIX]: Querying against schema table "ginger_handles"
216
+ const { data: persistentHost, error: handleErr } = await supabase.from('ginger_handles').select('*').eq('handle', handle).maybeSingle();
217
 
218
  if (handleErr || !persistentHost) return res.status(404).json({ type: 'CANCEL', reason: `Handle '${handle}' offline.` });
219
 
220
  const pin = await generateUniquePin();
221
+
222
+ // [FIX]: Mapping parameters strictly to the "ginger_rooms" table columns
223
+ const { data: room, error: roomErr } = await supabase.from('ginger_rooms').insert({
224
  pin,
225
  initiator_session_id: persistentHost.session_id,
226
  initiator_pub_key: persistentHost.pub_key,
227
+ initiator_callback_token: persistentHost.callback_token || null,
228
+ initiator_handle: handle,
229
  receiver_session_id: session_id,
230
  receiver_pub_key: buyer_pub_key,
231
+ receiver_callback_token: callback_token || null,
232
+ receiver_handle: null,
233
  status: 'active'
234
  }).select('*').single();
235
 
 
255
  // --- CASE 2: JOINING VIA 6-DIGIT PIN ---
256
  if (constraints && constraints.p2p_pin) {
257
  const pin = constraints.p2p_pin.toString().trim();
258
+ // [FIX]: Querying strictly against "ginger_rooms"
259
+ const { data: room, error } = await supabase.from('ginger_rooms').select('*').eq('pin', pin).eq('status', 'pending').maybeSingle();
260
 
261
  if (error || !room) return res.status(404).json({ type: 'CANCEL', reason: "Active pairing room not found." });
262
 
263
+ // [FIX]: Mapping update values to exact "ginger_rooms" column schema
264
+ await supabase.from('ginger_rooms').update({
265
+ receiver_session_id: session_id,
266
+ receiver_pub_key: buyer_pub_key,
267
+ receiver_callback_token: callback_token || null,
268
+ status: 'active'
269
+ }).eq('room_id', room.room_id);
270
 
271
  room.receiver_session_id = session_id;
272
  room.receiver_pub_key = buyer_pub_key;
273
+ room.receiver_callback_token = callback_token || null;
274
  room.status = 'active';
275
  localRoomCache.set(room.room_id, room);
276
 
 
286
 
287
  // --- CASE 3: CREATING TEMPORARY ROOM ---
288
  const pin = await generateUniquePin();
289
+ // [FIX]: Mapping parameters and inserting strictly into "ginger_rooms"
290
+ const { data: newRoom, error: insertError } = await supabase.from('ginger_rooms').insert({
291
+ pin,
292
+ initiator_session_id: session_id,
293
+ initiator_pub_key: buyer_pub_key,
294
+ initiator_callback_token: callback_token || null,
295
+ status: 'pending'
296
  }).select('*').single();
297
 
298
  if (insertError) throw insertError;
 
311
  // ANP COUNTER ROUTE (Real-time Message Tunneling + AI Mediation)
312
  // ============================================================================
313
  app.post('/anp/v1/counter', async (req, res) => {
314
+ const { session_id, turn, price, reason, signature } = req.body;
315
  const currentTurn = turn || 2;
316
  const nextTurn = currentTurn + 1;
317
 
 
319
  let room = Array.from(localRoomCache.values()).find(r => (r.initiator_session_id === session_id || r.receiver_session_id === session_id) && r.status === 'active');
320
 
321
  if (!room) {
322
+ // [FIX]: Aligned table queries strictly to the "ginger_rooms" schema
323
+ const { data, error } = await supabase.from('ginger_rooms').select('*').or(`initiator_session_id.eq.${session_id},receiver_session_id.eq.${session_id}`).eq('status', 'active').maybeSingle();
324
  if (error || !data) return res.status(404).json({ type: 'CANCEL', reason: "P2P session dropped or inactive." });
325
  room = data;
326
  localRoomCache.set(room.room_id, room);
 
330
  const targetSessionId = isInitiator ? room.receiver_session_id : room.initiator_session_id;
331
  const targetPubKey = isInitiator ? room.receiver_pub_key : room.initiator_pub_key;
332
 
 
333
  let routedPrice = price;
334
  let routedMessage = reason;
335
 
336
+ // --- SAVE MESSAGE LOG TO DATABASE ---
337
+ // [FIX]: Strictly aligned insert body parameters to matches the schema of table "ginger_messages"
338
+ await supabase.from('ginger_messages').insert({
339
+ room_id: room.room_id,
340
+ turn: currentTurn,
341
+ sender_session_id: session_id,
342
+ price: price,
343
+ reason: reason || null,
344
+ signature: signature || null
345
+ });
346
+
347
+ // --- AI MEDIATION INTERCEPT ---
348
  if (reason && reason.toLowerCase().includes('@mediate')) {
349
  console.log(`[AI] Mediation requested by ${session_id}`);
350
  const aiSuggestion = await mediatePrice(price, "P2P Service");
351
  routedPrice = aiSuggestion.price;
352
  routedMessage = `[🤖 Ginger AI Mediator] ${aiSuggestion.message}`;
353
 
354
+ // [FIX]: Save Mediation outcome strictly targeting "ginger_messages" schema
355
+ await supabase.from('ginger_messages').insert({
356
+ room_id: room.room_id,
357
+ turn: currentTurn,
358
+ sender_session_id: 'ginger_ai',
359
+ price: routedPrice,
360
+ reason: routedMessage,
361
+ signature: null
362
+ });
363
  }
364
 
365
  // --- PUSH ASYNC CALLBACK TO PEER ---
 
410
  // Refresh token every 5 days before the 7-day expiry
411
  setInterval(() => core.initialize().catch(() => console.error("Token refresh failed")), 5 * 24 * 60 * 60 * 1000);
412
 
 
413
  await core.registerNode(
414
  AGENT_ID,
415
  `${PUBLIC_ENDPOINT}`,