moltspay 1.6.0 → 2.0.0

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.
Files changed (55) hide show
  1. package/README.md +1 -0
  2. package/dist/cdp/index.js.map +1 -1
  3. package/dist/cdp/index.mjs.map +1 -1
  4. package/dist/{cdp-DeohBe1o.d.ts → cdp-B5PhDUTC.d.ts} +1 -1
  5. package/dist/{cdp-p_eHuQpb.d.mts → cdp-D-5Hg3y_.d.mts} +1 -1
  6. package/dist/chains/index.d.mts +37 -1
  7. package/dist/chains/index.d.ts +37 -1
  8. package/dist/chains/index.js +22 -0
  9. package/dist/chains/index.js.map +1 -1
  10. package/dist/chains/index.mjs +19 -0
  11. package/dist/chains/index.mjs.map +1 -1
  12. package/dist/cli/index.js +1466 -61
  13. package/dist/cli/index.js.map +1 -1
  14. package/dist/cli/index.mjs +1466 -61
  15. package/dist/cli/index.mjs.map +1 -1
  16. package/dist/client/index.d.mts +41 -0
  17. package/dist/client/index.d.ts +41 -0
  18. package/dist/client/index.js +824 -10
  19. package/dist/client/index.js.map +1 -1
  20. package/dist/client/index.mjs +824 -10
  21. package/dist/client/index.mjs.map +1 -1
  22. package/dist/client/web/index.d.mts +17 -1
  23. package/dist/client/web/index.mjs +11 -0
  24. package/dist/client/web/index.mjs.map +1 -1
  25. package/dist/facilitators/index.d.mts +161 -4
  26. package/dist/facilitators/index.d.ts +161 -4
  27. package/dist/facilitators/index.js +370 -0
  28. package/dist/facilitators/index.js.map +1 -1
  29. package/dist/facilitators/index.mjs +365 -0
  30. package/dist/facilitators/index.mjs.map +1 -1
  31. package/dist/index.d.mts +77 -2
  32. package/dist/index.d.ts +77 -2
  33. package/dist/index.js +1412 -31
  34. package/dist/index.js.map +1 -1
  35. package/dist/index.mjs +1406 -31
  36. package/dist/index.mjs.map +1 -1
  37. package/dist/mcp/index.js +828 -14
  38. package/dist/mcp/index.js.map +1 -1
  39. package/dist/mcp/index.mjs +828 -14
  40. package/dist/mcp/index.mjs.map +1 -1
  41. package/dist/{registry-OsEO2dOu.d.mts → registry-DIo0WNoO.d.mts} +8 -1
  42. package/dist/{registry-OsEO2dOu.d.ts → registry-DIo0WNoO.d.ts} +8 -1
  43. package/dist/server/index.d.mts +95 -2
  44. package/dist/server/index.d.ts +95 -2
  45. package/dist/server/index.js +554 -14
  46. package/dist/server/index.js.map +1 -1
  47. package/dist/server/index.mjs +554 -14
  48. package/dist/server/index.mjs.map +1 -1
  49. package/dist/verify/index.js.map +1 -1
  50. package/dist/verify/index.mjs.map +1 -1
  51. package/dist/wallet/index.js.map +1 -1
  52. package/dist/wallet/index.mjs.map +1 -1
  53. package/package.json +7 -1
  54. package/schemas/moltspay.services.schema.json +100 -6
  55. package/scripts/postinstall.js +91 -0
@@ -1218,6 +1218,365 @@ async function createSolanaPaymentTransaction(senderPubkey, recipientPubkey, amo
1218
1218
  return transaction;
1219
1219
  }
1220
1220
 
1221
+ // src/facilitators/alipay.ts
1222
+ import crypto2 from "crypto";
1223
+
1224
+ // src/facilitators/alipay/rsa2.ts
1225
+ import crypto from "crypto";
1226
+ function rsa2Sign(data, privateKeyPem) {
1227
+ const signer = crypto.createSign("RSA-SHA256");
1228
+ signer.update(data, "utf-8");
1229
+ signer.end();
1230
+ return signer.sign(privateKeyPem, "base64");
1231
+ }
1232
+
1233
+ // src/facilitators/alipay/encoding.ts
1234
+ function base64url(input) {
1235
+ return Buffer.from(input, "utf-8").toString("base64url");
1236
+ }
1237
+ function decodeBase64UrlWithPadFix(input) {
1238
+ const normalized = input.replace(/-/g, "+").replace(/_/g, "/");
1239
+ const padded = normalized + "=".repeat((4 - normalized.length % 4) % 4);
1240
+ return Buffer.from(padded, "base64").toString("utf-8");
1241
+ }
1242
+
1243
+ // src/facilitators/alipay/openapi.ts
1244
+ function formatAlipayTimestamp(d = /* @__PURE__ */ new Date()) {
1245
+ const pad = (n) => String(n).padStart(2, "0");
1246
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
1247
+ }
1248
+ function buildSigningString(params) {
1249
+ return Object.keys(params).sort().map((k) => `${k}=${params[k]}`).join("&");
1250
+ }
1251
+ function responseWrapperKey(method) {
1252
+ return `${method.replace(/\./g, "_")}_response`;
1253
+ }
1254
+ async function alipayOpenApiCall(method, bizContent, config) {
1255
+ const publicParams = {
1256
+ app_id: config.app_id,
1257
+ method,
1258
+ format: "JSON",
1259
+ charset: "utf-8",
1260
+ sign_type: config.sign_type ?? "RSA2",
1261
+ timestamp: formatAlipayTimestamp(),
1262
+ version: "1.0",
1263
+ biz_content: JSON.stringify(bizContent)
1264
+ };
1265
+ const signingString = buildSigningString(publicParams);
1266
+ const sign = rsa2Sign(signingString, config.private_key_pem);
1267
+ const body = new URLSearchParams({ ...publicParams, sign }).toString();
1268
+ const response = await fetch(config.gateway_url, {
1269
+ method: "POST",
1270
+ headers: {
1271
+ "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
1272
+ },
1273
+ body
1274
+ });
1275
+ if (!response.ok) {
1276
+ const text = await response.text().catch(() => "<unreadable>");
1277
+ throw new Error(
1278
+ `Alipay Open API HTTP ${response.status} for ${method}: ${text.slice(0, 500)}`
1279
+ );
1280
+ }
1281
+ const json = await response.json();
1282
+ const wrapperKey = responseWrapperKey(method);
1283
+ const business = json[wrapperKey];
1284
+ if (business === void 0 || business === null || typeof business !== "object") {
1285
+ throw new Error(
1286
+ `Alipay Open API response missing "${wrapperKey}" wrapper for ${method}: ${JSON.stringify(json).slice(0, 500)}`
1287
+ );
1288
+ }
1289
+ return business;
1290
+ }
1291
+
1292
+ // src/facilitators/alipay.ts
1293
+ var ALIPAY_NETWORK = "alipay";
1294
+ var ALIPAY_SCHEME = "alipay-aipay";
1295
+ var ALIPAY_GATEWAY_PROD = "https://openapi.alipay.com/gateway.do";
1296
+ var ALIPAY_GATEWAY_SANDBOX = "https://openapi.alipaydev.com/gateway.do";
1297
+ var ALIPAY_AMOUNT_REGEX = /^\d+(\.\d{1,2})?$/;
1298
+ var ALIPAY_PAY_BEFORE_MS = 30 * 60 * 1e3;
1299
+ var ALIPAY_SIGNING_FIELDS = [
1300
+ "amount",
1301
+ "currency",
1302
+ "goods_name",
1303
+ "out_trade_no",
1304
+ "pay_before",
1305
+ "resource_id",
1306
+ "seller_id",
1307
+ "service_id"
1308
+ ];
1309
+ var AlipayFacilitator = class extends BaseFacilitator {
1310
+ name = "alipay";
1311
+ displayName = "Alipay AI \u6536";
1312
+ supportedNetworks = [ALIPAY_NETWORK];
1313
+ config;
1314
+ constructor(config) {
1315
+ super();
1316
+ this.config = {
1317
+ gateway_url: ALIPAY_GATEWAY_PROD,
1318
+ sign_type: "RSA2",
1319
+ ...config
1320
+ };
1321
+ }
1322
+ /**
1323
+ * Build the 402 challenge for a service: signs the 8-field payload with
1324
+ * RSA2, packages the nested `{protocol, method}` JSON as Base64URL for
1325
+ * `Payment-Needed`, and emits the parallel x402 `accepts[]` entry.
1326
+ */
1327
+ async createPaymentRequirements(opts) {
1328
+ if (!ALIPAY_AMOUNT_REGEX.test(opts.priceCny)) {
1329
+ throw new Error(
1330
+ `AlipayFacilitator.createPaymentRequirements: priceCny "${opts.priceCny}" does not match /^\\d+(\\.\\d{1,2})?$/ (unit is \u5143, not \u5206; e.g. "1.00" not "100")`
1331
+ );
1332
+ }
1333
+ const now = /* @__PURE__ */ new Date();
1334
+ const outTradeNo = opts.outTradeNo ?? generateOutTradeNo();
1335
+ const payBefore = formatPayBefore(now);
1336
+ const signedFields = {
1337
+ amount: opts.priceCny,
1338
+ currency: "CNY",
1339
+ goods_name: opts.goodsName,
1340
+ out_trade_no: outTradeNo,
1341
+ pay_before: payBefore,
1342
+ resource_id: opts.resourceId,
1343
+ seller_id: this.config.seller_id,
1344
+ service_id: opts.serviceId
1345
+ };
1346
+ const signingString = ALIPAY_SIGNING_FIELDS.map((k) => `${k}=${signedFields[k]}`).join("&");
1347
+ const seller_signature = rsa2Sign(signingString, this.config.private_key_pem);
1348
+ const challenge = {
1349
+ protocol: {
1350
+ out_trade_no: outTradeNo,
1351
+ amount: signedFields.amount,
1352
+ currency: signedFields.currency,
1353
+ resource_id: signedFields.resource_id,
1354
+ pay_before: payBefore,
1355
+ seller_signature,
1356
+ seller_sign_type: this.config.sign_type ?? "RSA2",
1357
+ seller_unique_id: this.config.seller_id
1358
+ },
1359
+ method: {
1360
+ seller_name: this.config.seller_name,
1361
+ seller_id: this.config.seller_id,
1362
+ seller_app_id: this.config.app_id,
1363
+ goods_name: signedFields.goods_name,
1364
+ seller_unique_id_key: "seller_id",
1365
+ service_id: signedFields.service_id
1366
+ }
1367
+ };
1368
+ const paymentNeededHeader = base64url(JSON.stringify(challenge));
1369
+ const x402Accepts = {
1370
+ scheme: ALIPAY_SCHEME,
1371
+ network: ALIPAY_NETWORK,
1372
+ asset: "CNY",
1373
+ amount: opts.priceCny,
1374
+ payTo: this.config.seller_id,
1375
+ maxTimeoutSeconds: ALIPAY_PAY_BEFORE_MS / 1e3,
1376
+ extra: {
1377
+ payment_needed_header: paymentNeededHeader,
1378
+ out_trade_no: outTradeNo,
1379
+ pay_before: payBefore,
1380
+ service_id: signedFields.service_id
1381
+ }
1382
+ };
1383
+ return { x402Accepts, paymentNeededHeader };
1384
+ }
1385
+ /**
1386
+ * Verify a `Payment-Proof` by calling
1387
+ * `alipay.aipay.agent.payment.verify` against the Alipay Open API.
1388
+ *
1389
+ * The proof is conveyed via `paymentPayload.payload`, which may be:
1390
+ * - a raw Base64URL string (the `Payment-Proof` header value), or
1391
+ * - an object `{ paymentProof: string }` / `{ proofHeader: string }`.
1392
+ *
1393
+ * All failure modes (malformed payload, network errors, Alipay
1394
+ * `code != 10000`) return `{ valid: false, error }`. No exception
1395
+ * escapes, regardless of client-supplied input.
1396
+ */
1397
+ async verify(paymentPayload, _requirements) {
1398
+ try {
1399
+ const proofHeader = extractProofHeader(paymentPayload.payload);
1400
+ const decoded = decodeProof(proofHeader);
1401
+ const response = await alipayOpenApiCall(
1402
+ "alipay.aipay.agent.payment.verify",
1403
+ {
1404
+ payment_proof: decoded.protocol.payment_proof,
1405
+ trade_no: decoded.protocol.trade_no,
1406
+ client_session: decoded.method.client_session
1407
+ },
1408
+ this.getOpenApiConfig()
1409
+ );
1410
+ if (response.code !== "10000") {
1411
+ return {
1412
+ valid: false,
1413
+ error: `alipay verify ${response.code}: ${response.sub_msg ?? response.msg ?? "unknown"}`,
1414
+ details: {
1415
+ code: response.code,
1416
+ sub_code: response.sub_code,
1417
+ sub_msg: response.sub_msg
1418
+ }
1419
+ };
1420
+ }
1421
+ return {
1422
+ valid: true,
1423
+ details: {
1424
+ trade_no: response.trade_no ?? decoded.protocol.trade_no,
1425
+ amount: response.amount,
1426
+ out_trade_no: response.out_trade_no,
1427
+ resource_id: response.resource_id,
1428
+ active: response.active
1429
+ }
1430
+ };
1431
+ } catch (e) {
1432
+ return {
1433
+ valid: false,
1434
+ error: e instanceof Error ? e.message : String(e)
1435
+ };
1436
+ }
1437
+ }
1438
+ /**
1439
+ * Settle by calling `alipay.aipay.agent.fulfillment.confirm` after the
1440
+ * service resource has been returned to the buyer.
1441
+ *
1442
+ * Per the design (see ALIPAY-INTEGRATION-DESIGN.md §5.1, risk row
1443
+ * "履约确认失败"), this is **fire-and-forget**: the caller (registry /
1444
+ * server) is expected to log fulfillment failures but NOT roll back
1445
+ * the already-delivered resource.
1446
+ *
1447
+ * Re-decodes `paymentPayload.payload` to extract `trade_no` (verify
1448
+ * does the same; the redundant Base64URL decode is negligible).
1449
+ */
1450
+ async settle(paymentPayload, _requirements) {
1451
+ try {
1452
+ const proofHeader = extractProofHeader(paymentPayload.payload);
1453
+ const decoded = decodeProof(proofHeader);
1454
+ const tradeNo = decoded.protocol.trade_no;
1455
+ const response = await alipayOpenApiCall(
1456
+ "alipay.aipay.agent.fulfillment.confirm",
1457
+ { trade_no: tradeNo },
1458
+ this.getOpenApiConfig()
1459
+ );
1460
+ if (response.code !== "10000") {
1461
+ return {
1462
+ success: false,
1463
+ transaction: tradeNo,
1464
+ error: `alipay fulfillment ${response.code}: ${response.sub_msg ?? response.msg ?? "unknown"}`,
1465
+ status: "fulfillment_failed"
1466
+ };
1467
+ }
1468
+ return {
1469
+ success: true,
1470
+ transaction: tradeNo,
1471
+ status: "fulfilled"
1472
+ };
1473
+ } catch (e) {
1474
+ return {
1475
+ success: false,
1476
+ error: e instanceof Error ? e.message : String(e)
1477
+ };
1478
+ }
1479
+ }
1480
+ /**
1481
+ * Validate that the configured RSA keys parse and that the Open API
1482
+ * gateway is reachable. Does NOT make a real business API call (would
1483
+ * burn quota and could appear as a legitimate verify attempt in logs).
1484
+ */
1485
+ async healthCheck() {
1486
+ const start = Date.now();
1487
+ try {
1488
+ crypto2.createPrivateKey(this.config.private_key_pem);
1489
+ } catch (e) {
1490
+ return {
1491
+ healthy: false,
1492
+ error: `merchant private_key_pem parse failed: ${e instanceof Error ? e.message : String(e)}`
1493
+ };
1494
+ }
1495
+ try {
1496
+ crypto2.createPublicKey(this.config.alipay_public_key_pem);
1497
+ } catch (e) {
1498
+ return {
1499
+ healthy: false,
1500
+ error: `alipay_public_key_pem parse failed: ${e instanceof Error ? e.message : String(e)}`
1501
+ };
1502
+ }
1503
+ const gatewayUrl = this.config.gateway_url ?? ALIPAY_GATEWAY_PROD;
1504
+ const controller = new AbortController();
1505
+ const timeout = setTimeout(() => controller.abort(), 5e3);
1506
+ const response = await fetch(gatewayUrl, {
1507
+ method: "HEAD",
1508
+ signal: controller.signal
1509
+ }).catch(() => null);
1510
+ clearTimeout(timeout);
1511
+ const latencyMs = Date.now() - start;
1512
+ if (!response) {
1513
+ return { healthy: false, error: `gateway unreachable: ${gatewayUrl}`, latencyMs };
1514
+ }
1515
+ return { healthy: true, latencyMs };
1516
+ }
1517
+ /** Bundle the facilitator config into the shape openapi.ts wants. */
1518
+ getOpenApiConfig() {
1519
+ return {
1520
+ gateway_url: this.config.gateway_url ?? ALIPAY_GATEWAY_PROD,
1521
+ app_id: this.config.app_id,
1522
+ private_key_pem: this.config.private_key_pem,
1523
+ alipay_public_key_pem: this.config.alipay_public_key_pem,
1524
+ sign_type: this.config.sign_type
1525
+ };
1526
+ }
1527
+ };
1528
+ function generateOutTradeNo() {
1529
+ return "VID" + crypto2.randomBytes(22).toString("base64url").slice(0, 29);
1530
+ }
1531
+ function formatPayBefore(now) {
1532
+ const expiry = new Date(now.getTime() + ALIPAY_PAY_BEFORE_MS);
1533
+ return expiry.toISOString().replace(/\.\d{3}Z$/, "Z");
1534
+ }
1535
+ function extractProofHeader(payload) {
1536
+ if (typeof payload === "string") {
1537
+ if (payload.length === 0) {
1538
+ throw new Error("alipay Payment-Proof is empty");
1539
+ }
1540
+ return payload;
1541
+ }
1542
+ if (payload !== null && typeof payload === "object") {
1543
+ const obj = payload;
1544
+ const candidate = obj.paymentProof ?? obj.proofHeader;
1545
+ if (typeof candidate === "string" && candidate.length > 0) {
1546
+ return candidate;
1547
+ }
1548
+ }
1549
+ throw new Error(
1550
+ "alipay payment payload must be a Base64URL string or {paymentProof: string} / {proofHeader: string}"
1551
+ );
1552
+ }
1553
+ function decodeProof(proofHeader) {
1554
+ let parsed;
1555
+ try {
1556
+ parsed = JSON.parse(decodeBase64UrlWithPadFix(proofHeader));
1557
+ } catch (e) {
1558
+ throw new Error(
1559
+ `failed to decode Payment-Proof: ${e instanceof Error ? e.message : String(e)}`
1560
+ );
1561
+ }
1562
+ if (parsed === null || typeof parsed !== "object") {
1563
+ throw new Error("decoded Payment-Proof is not an object");
1564
+ }
1565
+ const obj = parsed;
1566
+ const protocol = obj.protocol;
1567
+ const method = obj.method;
1568
+ if (!protocol || typeof protocol.payment_proof !== "string") {
1569
+ throw new Error("decoded Payment-Proof missing protocol.payment_proof");
1570
+ }
1571
+ if (typeof protocol.trade_no !== "string") {
1572
+ throw new Error("decoded Payment-Proof missing protocol.trade_no");
1573
+ }
1574
+ if (!method || typeof method.client_session !== "string") {
1575
+ throw new Error("decoded Payment-Proof missing method.client_session");
1576
+ }
1577
+ return parsed;
1578
+ }
1579
+
1221
1580
  // src/facilitators/registry.ts
1222
1581
  import { Keypair as Keypair2 } from "@solana/web3.js";
1223
1582
  import bs58 from "bs58";
@@ -1242,6 +1601,7 @@ var FacilitatorRegistry = class {
1242
1601
  }
1243
1602
  return new SolanaFacilitator({ feePayerKeypair });
1244
1603
  });
1604
+ this.registerFactory("alipay", (config) => new AlipayFacilitator(config));
1245
1605
  this.selection = selection || { primary: "cdp", fallback: ["tempo", "bnb", "solana"], strategy: "failover" };
1246
1606
  }
1247
1607
  /**
@@ -1468,6 +1828,11 @@ function createRegistry(selection) {
1468
1828
  return new FacilitatorRegistry(selection);
1469
1829
  }
1470
1830
  export {
1831
+ ALIPAY_GATEWAY_PROD,
1832
+ ALIPAY_GATEWAY_SANDBOX,
1833
+ ALIPAY_NETWORK,
1834
+ ALIPAY_SCHEME,
1835
+ AlipayFacilitator,
1471
1836
  BNBFacilitator,
1472
1837
  BaseFacilitator,
1473
1838
  CDPFacilitator,