moltspay 0.9.1 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -30943,6 +30943,7 @@ var MoltsPayServer = class {
30943
30943
  console.log(`[MoltsPay] Endpoints:`);
30944
30944
  console.log(` GET /services - List available services`);
30945
30945
  console.log(` POST /execute - Execute service (x402 payment)`);
30946
+ console.log(` POST /proxy - Proxy payment for external services`);
30946
30947
  console.log(` GET /health - Health check (incl. facilitators)`);
30947
30948
  });
30948
30949
  }
@@ -30972,6 +30973,15 @@ var MoltsPayServer = class {
30972
30973
  const paymentHeader = req.headers[PAYMENT_HEADER];
30973
30974
  return await this.handleExecute(body, paymentHeader, res);
30974
30975
  }
30976
+ if (url.pathname === "/proxy" && req.method === "POST") {
30977
+ const clientIP = req.headers["x-real-ip"] || req.headers["x-forwarded-for"]?.split(",")[0]?.trim() || req.socket.remoteAddress || "";
30978
+ if (!this.isProxyAllowed(clientIP)) {
30979
+ return this.sendJson(res, 403, { error: "Forbidden: IP not allowed" });
30980
+ }
30981
+ const body = await this.readBody(req);
30982
+ const paymentHeader = req.headers[PAYMENT_HEADER];
30983
+ return await this.handleProxy(body, paymentHeader, res);
30984
+ }
30975
30985
  this.sendJson(res, 404, { error: "Not found" });
30976
30986
  } catch (err) {
30977
30987
  console.error("[MoltsPay] Error:", err);
@@ -31181,6 +31191,217 @@ var MoltsPayServer = class {
31181
31191
  res.writeHead(status, headers);
31182
31192
  res.end(JSON.stringify(data, null, 2));
31183
31193
  }
31194
+ /**
31195
+ * Check if IP is allowed for /proxy endpoint
31196
+ */
31197
+ isProxyAllowed(clientIP) {
31198
+ const allowedIPs = process.env.PROXY_ALLOWED_IPS?.split(",").map((ip) => ip.trim()) || [];
31199
+ if (allowedIPs.length === 0) {
31200
+ console.log(`[MoltsPay] /proxy denied: no PROXY_ALLOWED_IPS configured`);
31201
+ return false;
31202
+ }
31203
+ const normalizedIP = clientIP === "::1" ? "127.0.0.1" : clientIP.replace("::ffff:", "");
31204
+ const allowed = allowedIPs.includes(normalizedIP) || allowedIPs.includes(clientIP);
31205
+ if (!allowed) {
31206
+ console.log(`[MoltsPay] /proxy denied for IP: ${clientIP} (normalized: ${normalizedIP})`);
31207
+ }
31208
+ return allowed;
31209
+ }
31210
+ /**
31211
+ * POST /proxy - Handle payment for external services (moltspay-creators)
31212
+ *
31213
+ * This endpoint allows other services to delegate x402 payment handling.
31214
+ * It does NOT execute any skill - just handles payment verification/settlement.
31215
+ *
31216
+ * Request body:
31217
+ * { wallet, amount, currency, chain, memo, serviceId, description }
31218
+ *
31219
+ * Without X-Payment header: returns 402 with payment requirements
31220
+ * With X-Payment header: verifies payment and returns result
31221
+ */
31222
+ async handleProxy(body, paymentHeader, res) {
31223
+ const { wallet, amount, currency, chain: chain2, memo, serviceId, description } = body;
31224
+ if (!wallet || !amount) {
31225
+ return this.sendJson(res, 400, { error: "Missing required fields: wallet, amount" });
31226
+ }
31227
+ if (!/^0x[a-fA-F0-9]{40}$/.test(wallet)) {
31228
+ return this.sendJson(res, 400, { error: "Invalid wallet address format" });
31229
+ }
31230
+ const amountNum = parseFloat(amount);
31231
+ if (isNaN(amountNum) || amountNum <= 0) {
31232
+ return this.sendJson(res, 400, { error: "Invalid amount" });
31233
+ }
31234
+ const proxyConfig = {
31235
+ id: serviceId || "proxy",
31236
+ name: description || "Proxy Payment",
31237
+ description: description || "",
31238
+ price: amountNum,
31239
+ currency: currency || "USDC",
31240
+ function: "",
31241
+ // Not used
31242
+ input: {},
31243
+ output: {}
31244
+ };
31245
+ const requirements = this.buildProxyPaymentRequirements(proxyConfig, wallet);
31246
+ if (!paymentHeader) {
31247
+ return this.sendProxyPaymentRequired(proxyConfig, wallet, memo, res);
31248
+ }
31249
+ let payment;
31250
+ try {
31251
+ const decoded = Buffer.from(paymentHeader, "base64").toString("utf-8");
31252
+ payment = JSON.parse(decoded);
31253
+ } catch {
31254
+ return this.sendJson(res, 400, { error: "Invalid X-Payment header" });
31255
+ }
31256
+ if (payment.x402Version !== X402_VERSION2) {
31257
+ return this.sendJson(res, 402, { error: `Unsupported x402 version: ${payment.x402Version}` });
31258
+ }
31259
+ const scheme = payment.accepted?.scheme || payment.scheme;
31260
+ const network = payment.accepted?.network || payment.network;
31261
+ if (scheme !== "exact") {
31262
+ return this.sendJson(res, 402, { error: `Unsupported scheme: ${scheme}` });
31263
+ }
31264
+ if (network !== this.networkId) {
31265
+ return this.sendJson(res, 402, { error: `Network mismatch: expected ${this.networkId}, got ${network}` });
31266
+ }
31267
+ console.log(`[MoltsPay] /proxy: Verifying payment for ${wallet}...`);
31268
+ const verifyResult = await this.registry.verify(payment, requirements);
31269
+ if (!verifyResult.valid) {
31270
+ return this.sendJson(res, 402, {
31271
+ success: false,
31272
+ error: `Payment verification failed: ${verifyResult.error}`,
31273
+ facilitator: verifyResult.facilitator
31274
+ });
31275
+ }
31276
+ console.log(`[MoltsPay] /proxy: Verified by ${verifyResult.facilitator}`);
31277
+ const { execute, service, params } = body;
31278
+ if (execute && service) {
31279
+ console.log(`[MoltsPay] /proxy: Executing skill first (pay on success): ${service}`);
31280
+ const skill = this.skills.get(service);
31281
+ if (!skill) {
31282
+ console.log(`[MoltsPay] /proxy: Service not found: ${service} - NOT settling`);
31283
+ return this.sendJson(res, 404, {
31284
+ success: false,
31285
+ paymentSettled: false,
31286
+ error: `Service not found: ${service}`
31287
+ });
31288
+ }
31289
+ let result;
31290
+ try {
31291
+ result = await skill.handler(params || {});
31292
+ console.log(`[MoltsPay] /proxy: Skill succeeded, now settling payment...`);
31293
+ } catch (err) {
31294
+ console.error(`[MoltsPay] /proxy: Skill failed: ${err.message} - NOT settling`);
31295
+ return this.sendJson(res, 500, {
31296
+ success: false,
31297
+ paymentSettled: false,
31298
+ error: `Service execution failed: ${err.message}`
31299
+ });
31300
+ }
31301
+ let settlement2 = null;
31302
+ try {
31303
+ settlement2 = await this.registry.settle(payment, requirements);
31304
+ console.log(`[MoltsPay] /proxy: Payment settled by ${settlement2.facilitator}: ${settlement2.transaction || "pending"}`);
31305
+ } catch (err) {
31306
+ console.error("[MoltsPay] /proxy: Settlement failed:", err.message);
31307
+ return this.sendJson(res, 200, {
31308
+ success: true,
31309
+ verified: true,
31310
+ settled: false,
31311
+ settlementError: err.message,
31312
+ from: payment.payload?.authorization?.from,
31313
+ // Buyer's wallet address
31314
+ paidTo: wallet,
31315
+ amount: amountNum,
31316
+ currency: currency || "USDC",
31317
+ memo,
31318
+ result
31319
+ });
31320
+ }
31321
+ return this.sendJson(res, 200, {
31322
+ success: true,
31323
+ verified: true,
31324
+ settled: settlement2?.success || false,
31325
+ txHash: settlement2?.transaction,
31326
+ from: payment.payload?.authorization?.from,
31327
+ // Buyer's wallet address
31328
+ paidTo: wallet,
31329
+ amount: amountNum,
31330
+ currency: currency || "USDC",
31331
+ facilitator: settlement2?.facilitator,
31332
+ memo,
31333
+ result
31334
+ });
31335
+ }
31336
+ console.log(`[MoltsPay] /proxy: Settling payment (no execution)...`);
31337
+ let settlement = null;
31338
+ try {
31339
+ settlement = await this.registry.settle(payment, requirements);
31340
+ console.log(`[MoltsPay] /proxy: Payment settled by ${settlement.facilitator}: ${settlement.transaction || "pending"}`);
31341
+ } catch (err) {
31342
+ console.error("[MoltsPay] /proxy: Settlement failed:", err.message);
31343
+ return this.sendJson(res, 500, {
31344
+ success: false,
31345
+ error: `Settlement failed: ${err.message}`
31346
+ });
31347
+ }
31348
+ this.sendJson(res, 200, {
31349
+ success: true,
31350
+ verified: true,
31351
+ settled: settlement?.success || false,
31352
+ txHash: settlement?.transaction,
31353
+ from: payment.payload?.authorization?.from,
31354
+ // Buyer's wallet address
31355
+ paidTo: wallet,
31356
+ amount: amountNum,
31357
+ currency: currency || "USDC",
31358
+ facilitator: settlement?.facilitator,
31359
+ memo
31360
+ });
31361
+ }
31362
+ /**
31363
+ * Build payment requirements for proxy endpoint (uses provided wallet)
31364
+ */
31365
+ buildProxyPaymentRequirements(config, wallet) {
31366
+ const amountInUnits = Math.floor(config.price * 1e6).toString();
31367
+ const usdcAddress = USDC_ADDRESSES[this.networkId];
31368
+ return {
31369
+ scheme: "exact",
31370
+ network: this.networkId,
31371
+ asset: usdcAddress,
31372
+ amount: amountInUnits,
31373
+ payTo: wallet,
31374
+ // Use provided wallet, not manifest
31375
+ maxTimeoutSeconds: 300,
31376
+ extra: USDC_DOMAIN
31377
+ };
31378
+ }
31379
+ /**
31380
+ * Return 402 with x402 payment requirements for proxy endpoint
31381
+ */
31382
+ sendProxyPaymentRequired(config, wallet, memo, res) {
31383
+ const requirements = this.buildProxyPaymentRequirements(config, wallet);
31384
+ const paymentRequired = {
31385
+ x402Version: X402_VERSION2,
31386
+ accepts: [requirements],
31387
+ resource: {
31388
+ url: `/proxy`,
31389
+ description: `${config.name} - $${config.price} ${config.currency}`,
31390
+ mimeType: "application/json",
31391
+ memo
31392
+ }
31393
+ };
31394
+ const encoded = Buffer.from(JSON.stringify(paymentRequired)).toString("base64");
31395
+ res.writeHead(402, {
31396
+ "Content-Type": "application/json",
31397
+ [PAYMENT_REQUIRED_HEADER]: encoded
31398
+ });
31399
+ res.end(JSON.stringify({
31400
+ error: "Payment required",
31401
+ message: `Payment requires $${config.price} ${config.currency}`,
31402
+ x402: paymentRequired
31403
+ }, null, 2));
31404
+ }
31184
31405
  };
31185
31406
 
31186
31407
  // src/client/index.ts