-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
474 lines (418 loc) · 15.4 KB
/
server.js
File metadata and controls
474 lines (418 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
/**
* server.js
*
* PhantomOperator HTTP server with x402 + (future) Monero payment middleware.
*
* x402 is a payment protocol built on HTTP 402 Payment Required.
* When a caller hits a paid endpoint without a valid payment proof the server
* returns 402 with a JSON body describing how to pay (token, amount, address).
* The caller attaches a signed payment proof in the X-PAYMENT header and
* retries. The server validates the proof and serves the response.
*
* Endpoints:
* GET /manifest — public: returns agent-manifest.json
* GET /health — public: liveness check
* POST /skills/threat-scan — PAID: PII threat scan
* POST /skills/data-removal — PAID: data broker opt-out
* POST /skills/full-privacy-sweep — PAID: full sweep (+ orchestration)
* POST /skills/opsec-score — PAID: multi-vector OPSEC exposure score
* POST /skills/breach-check — PAID: HIBP k-anonymity breach lookup
* POST /skills/metadata-audit — PAID: HTTP/HTML metadata privacy audit
*
* Run: node server.js
*/
require('dotenv').config();
const http = require('http');
const { ethers } = require('ethers');
const SearchAgent = require('./agents/SearchAgent');
const BrokerAgent = require('./agents/BrokerAgent');
const OpsecAgent = require('./agents/OpsecAgent');
const BreachAgent = require('./agents/BreachAgent');
const MetadataAgent = require('./agents/MetadataAgent');
const OrchestratorOperator = require('./operators/OrchestratorOperator');
const manifest = require('./agent-manifest.json');
const {
checkRateLimit,
setSecurityHeaders,
sanitizeString,
isValidEmail,
isValidHttpUrl,
RATE_LIMIT_PUBLIC,
RATE_LIMIT_PAID,
MAX_BODY_BYTES,
} = require('./middleware/security');
const PORT = process.env.PORT || 3000;
const IS_PRODUCTION = process.env.NODE_ENV === 'production';
// ── x402 configuration ───────────────────────────────────────────────────────
const PAYMENT_TOKEN_ADDRESS =
process.env.PAYMENT_TOKEN_ADDRESS ||
'0xD04383398dD2426297da660F9CCA3d439AF9ce1b';
const PAYMENT_RECEIVER =
process.env.PAYMENT_RECEIVER_ADDRESS ||
process.env.SOVEREIGN_AGENT_ADDRESS ||
process.env.PHANTOM_OPERATOR_ADDRESS;
const CHAIN_ID = process.env.CHAIN_ID ? Number(process.env.CHAIN_ID) : 8453;
const MAX_TIMEOUT_SECONDS = 300;
// ── Skill pricing (USDCx, 6 decimal places) ──────────────────────────────────
const SKILL_PRICES = {
'threat-scan': '1000000', // 1.00 USDCx
'data-removal': '5000000', // 5.00 USDCx
'full-privacy-sweep': '10000000', // 10.00 USDCx
'opsec-score': '5000000', // 5.00 USDCx
'breach-check': '2000000', // 2.00 USDCx
'metadata-audit': '1000000', // 1.00 USDCx
};
const VALID_SKILL_IDS = new Set(Object.keys(SKILL_PRICES));
// ── x402 helpers ─────────────────────────────────────────────────────────────
function buildPaymentRequired(skillId, resourcePath) {
if (!PAYMENT_RECEIVER) {
throw new Error(
'PAYMENT_RECEIVER_ADDRESS (or SOVEREIGN_AGENT_ADDRESS/PHANTOM_OPERATOR_ADDRESS) must be set in .env'
);
}
return {
x402Version: 1,
accepts: [{
scheme: 'exact',
network: 'base-mainnet',
maxAmountRequired: SKILL_PRICES[skillId] || '1000000',
resource: resourcePath,
description:
manifest.skills.find(s => s.id === skillId)?.description || skillId,
mimeType: 'application/json',
payTo: PAYMENT_RECEIVER,
maxTimeoutSeconds: MAX_TIMEOUT_SECONDS,
asset: PAYMENT_TOKEN_ADDRESS,
extra: { name: 'USD Coin', version: '2' },
}],
error: 'Payment required to access this skill.',
};
}
/**
* Legacy x402/EVM payment validation.
* This is your existing logic extracted under a more explicit name.
*/
async function validatePaymentX402(xPaymentHeader, skillId, resourcePath) {
if (!xPaymentHeader) {
return { valid: false, error: 'Missing X-PAYMENT header' };
}
let proof;
try {
proof = JSON.parse(Buffer.from(xPaymentHeader, 'base64').toString('utf8'));
} catch {
return {
valid: false,
error: 'X-PAYMENT header is not valid base64-encoded JSON',
};
}
const { payload, signature } = proof;
if (!payload || !signature) {
return { valid: false, error: 'X-PAYMENT proof missing payload or signature' };
}
const inner = payload.payload || {};
if (inner.resource && inner.resource !== resourcePath) {
return {
valid: false,
error: `Resource mismatch: expected ${resourcePath}`,
};
}
if (inner.expiresAt && Date.now() / 1000 > inner.expiresAt) {
return { valid: false, error: 'Payment proof has expired' };
}
const required = BigInt(SKILL_PRICES[skillId] || '1000000');
const provided = BigInt(inner.amount || '0');
if (provided < required) {
return {
valid: false,
error: `Insufficient payment: required ${required}, provided ${provided}`,
};
}
if (inner.asset && inner.asset.toLowerCase() !== PAYMENT_TOKEN_ADDRESS.toLowerCase()) {
return {
valid: false,
error: `Wrong payment token: expected ${PAYMENT_TOKEN_ADDRESS}`,
};
}
try {
const payerAddress = ethers.utils.verifyMessage(
JSON.stringify(payload),
signature
);
return { valid: true, payerAddress };
} catch (err) {
return { valid: false, error: 'Signature verification failed' };
}
}
/**
* Monero payment validation stub.
*
* This is where you will later integrate with a separate Monero bridge service
* that talks to monerod/monero-wallet-rpc and returns signed payment proofs.
*
* Expected header usage:
* X-PAYMENT-METHOD: monero
* X-PAYMENT: base64-encoded JSON like:
* { invoiceId, proof, signature }
*/
async function validatePaymentMonero(xPaymentHeader, skillId, resourcePath) {
if (!xPaymentHeader) {
return { valid: false, error: 'Missing X-PAYMENT header for Monero' };
}
// TODO: Implement actual integration with your Monero bridge service.
// For now we always fail with a clear message so callers know this path
// is not production-ready yet.
return {
valid: false,
error: 'Monero payment method not yet implemented on this deployment',
};
}
/**
* Unified payment validator.
*
* Chooses between x402 (Base / EVM) and Monero based on the X-PAYMENT-METHOD
* header. Defaults to x402 for backward compatibility.
*
* X-PAYMENT-METHOD: x402 → validatePaymentX402
* X-PAYMENT-METHOD: monero → validatePaymentMonero
*/
async function validateAnyPayment(req, skillId, resourcePath) {
const methodHeader = req.headers['x-payment-method'];
const method = (methodHeader || 'x402').toLowerCase();
const xPaymentHeader = req.headers['x-payment'];
if (method === 'x402') {
return validatePaymentX402(xPaymentHeader, skillId, resourcePath);
}
if (method === 'monero') {
return validatePaymentMonero(xPaymentHeader, skillId, resourcePath);
}
return {
valid: false,
error: `Unsupported payment method: ${method}`,
};
}
// ── Middleware helpers ────────────────────────────────────────────────────────
function sendJson(res, status, body) {
const json = JSON.stringify(body, null, 2);
res.writeHead(status, {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(json),
});
res.end(json);
}
async function readBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
let totalBytes = 0;
req.on('data', chunk => {
totalBytes += chunk.length;
if (totalBytes > MAX_BODY_BYTES) {
req.destroy();
return reject(
new Error(`Request body exceeds ${MAX_BODY_BYTES} bytes`)
);
}
chunks.push(chunk);
});
req.on('end', () => {
try {
resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'));
} catch {
reject(new Error('Invalid JSON body'));
}
});
req.on('error', reject);
});
}
function getClientIp(req) {
return (req.headers['x-forwarded-for'] || '').split(',')[0].trim() ||
req.socket.remoteAddress ||
'unknown';
}
// ── Route handlers ───────────────────────────────────────────────────────────
async function handleManifest(req, res) {
sendJson(res, 200, manifest);
}
async function handleHealth(req, res) {
sendJson(res, 200, {
status: 'ok',
agent: manifest.name || 'PhantomOperator',
version: manifest.version,
});
}
/**
* Main handler for all paid skills.
* Uses validateAnyPayment to support x402 and (future) Monero.
*/
async function handlePaidSkill(req, res, skillId) {
const resourcePath = `/skills/${skillId}`;
// x402 / Monero gate
const { valid, error: paymentError } = await validateAnyPayment(
req,
skillId,
resourcePath
);
if (!valid) {
res.setHeader(
'X-PAYMENT-RESPONSE',
JSON.stringify({ status: 'payment-required', error: paymentError })
);
return sendJson(res, 402, buildPaymentRequired(skillId, resourcePath));
}
let body;
try {
body = await readBody(req);
} catch (err) {
return sendJson(res, 400, { error: err.message });
}
try {
let result;
if (skillId === 'threat-scan') {
const fullName = sanitizeString(body.fullName);
if (!fullName) {
return sendJson(res, 400, { error: 'fullName is required' });
}
result = await SearchAgent.run({ fullName });
} else if (skillId === 'data-removal') {
const threatUrl = sanitizeString(body.threatUrl);
if (!threatUrl) {
return sendJson(res, 400, { error: 'threatUrl is required' });
}
result = await BrokerAgent.removeThreat({ link: threatUrl, ...body });
} else if (skillId === 'full-privacy-sweep') {
const fullName = sanitizeString(body.fullName);
if (!fullName) {
return sendJson(res, 400, { error: 'fullName is required' });
}
// Use OrchestratorOperator as the core coordinator for sweeps.
const operator = new OrchestratorOperator();
await operator.startDataRemovalTask({
fullName,
walletAddress: sanitizeString(body.walletAddress) || PAYMENT_RECEIVER,
flowRate: sanitizeString(body.flowRate) ||
process.env.FLOW_RATE ||
'385802469135802',
});
result = {
status: 'sweep-complete',
message: 'Full privacy sweep finished.',
};
} else if (skillId === 'opsec-score') {
const target = {};
if (body.fullName) target.fullName = sanitizeString(body.fullName);
if (body.handle) target.handle = sanitizeString(body.handle);
if (body.email) target.email = sanitizeString(body.email);
if (!target.fullName && !target.handle && !target.email) {
return sendJson(res, 400, {
error: 'At least one of fullName, handle, or email is required',
});
}
result = await OpsecAgent.assess(target);
} else if (skillId === 'breach-check') {
const email = sanitizeString(body.email);
const password = typeof body.password === 'string'
? body.password
: null;
if (!email && !password) {
return sendJson(res, 400, {
error: 'email or password is required',
});
}
result = {};
if (email) {
if (!isValidEmail(email)) {
return sendJson(res, 400, { error: 'Invalid email address' });
}
result.emailReport = await BreachAgent.getBreachReport(email);
}
if (password) {
result.passwordCheck = await BreachAgent.checkPassword(password);
}
} else if (skillId === 'metadata-audit') {
const url = sanitizeString(body.url, 2048);
if (!url) {
return sendJson(res, 400, { error: 'url is required' });
}
if (!isValidHttpUrl(url)) {
return sendJson(res, 400, {
error: 'url must be an absolute HTTP/HTTPS URL',
});
}
result = await MetadataAgent.audit(url);
} else {
return sendJson(res, 404, { error: 'Unknown skill' });
}
res.setHeader(
'X-PAYMENT-RESPONSE',
JSON.stringify({ status: 'settled' })
);
sendJson(res, 200, { skill: skillId, result });
} catch (err) {
console.error(`Skill error [${skillId}]:`, err.message);
const message = IS_PRODUCTION ? 'An internal error occurred' : err.message;
sendJson(res, 500, { error: message });
}
}
// ── HTTP server ──────────────────────────────────────────────────────────────
const server = http.createServer(async (req, res) => {
// Security headers on every response
setSecurityHeaders(res);
const url = req.url.split('?')[0];
const clientIp = getClientIp(req);
try {
// Public endpoints — higher rate limit
if (req.method === 'GET' && (url === '/manifest' || url === '/health')) {
const rl = checkRateLimit(clientIp, RATE_LIMIT_PUBLIC);
if (!rl.allowed) {
res.setHeader('Retry-After', String(rl.retryAfter));
return sendJson(res, 429, {
error: 'Too many requests',
retryAfter: rl.retryAfter,
});
}
if (url === '/manifest') return await handleManifest(req, res);
return await handleHealth(req, res);
}
// Paid skill endpoints — stricter rate limit
if (req.method === 'POST' && url.startsWith('/skills/')) {
const skillId = url.slice('/skills/'.length);
if (!VALID_SKILL_IDS.has(skillId)) {
return sendJson(res, 404, { error: 'Unknown skill' });
}
const rl = checkRateLimit(clientIp, RATE_LIMIT_PAID);
if (!rl.allowed) {
res.setHeader('Retry-After', String(rl.retryAfter));
return sendJson(res, 429, {
error: 'Too many requests',
retryAfter: rl.retryAfter,
});
}
return await handlePaidSkill(req, res, skillId);
}
sendJson(res, 404, {
error: 'Not found',
hint: 'Available: GET /manifest, GET /health, POST /skills/{skill-id}',
});
} catch (err) {
console.error('Unhandled error:', err.message);
sendJson(res, 500, { error: 'Internal server error' });
}
});
server.listen(PORT, () => {
console.log(`PhantomOperator server running on port ${PORT}`);
console.log(` GET http://localhost:${PORT}/health`);
console.log(` GET http://localhost:${PORT}/manifest`);
for (const [skillId, price] of Object.entries(SKILL_PRICES)) {
console.log(
` POST http://localhost:${PORT}/skills/${skillId} (${price} USDCx)`
);
}
console.log('');
console.log('x402 payment token:', PAYMENT_TOKEN_ADDRESS);
console.log(
'Payment receiver: ',
PAYMENT_RECEIVER ||
'(NOT SET — set PAYMENT_RECEIVER_ADDRESS or PHANTOM_OPERATOR_ADDRESS in .env)'
);
console.log('Chain ID: ', CHAIN_ID);
});
module.exports = server;