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.
- package/README.md +1 -0
- package/dist/cdp/index.js.map +1 -1
- package/dist/cdp/index.mjs.map +1 -1
- package/dist/{cdp-DeohBe1o.d.ts → cdp-B5PhDUTC.d.ts} +1 -1
- package/dist/{cdp-p_eHuQpb.d.mts → cdp-D-5Hg3y_.d.mts} +1 -1
- package/dist/chains/index.d.mts +37 -1
- package/dist/chains/index.d.ts +37 -1
- package/dist/chains/index.js +22 -0
- package/dist/chains/index.js.map +1 -1
- package/dist/chains/index.mjs +19 -0
- package/dist/chains/index.mjs.map +1 -1
- package/dist/cli/index.js +1466 -61
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/index.mjs +1466 -61
- package/dist/cli/index.mjs.map +1 -1
- package/dist/client/index.d.mts +41 -0
- package/dist/client/index.d.ts +41 -0
- package/dist/client/index.js +824 -10
- package/dist/client/index.js.map +1 -1
- package/dist/client/index.mjs +824 -10
- package/dist/client/index.mjs.map +1 -1
- package/dist/client/web/index.d.mts +17 -1
- package/dist/client/web/index.mjs +11 -0
- package/dist/client/web/index.mjs.map +1 -1
- package/dist/facilitators/index.d.mts +161 -4
- package/dist/facilitators/index.d.ts +161 -4
- package/dist/facilitators/index.js +370 -0
- package/dist/facilitators/index.js.map +1 -1
- package/dist/facilitators/index.mjs +365 -0
- package/dist/facilitators/index.mjs.map +1 -1
- package/dist/index.d.mts +77 -2
- package/dist/index.d.ts +77 -2
- package/dist/index.js +1412 -31
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1406 -31
- package/dist/index.mjs.map +1 -1
- package/dist/mcp/index.js +828 -14
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/index.mjs +828 -14
- package/dist/mcp/index.mjs.map +1 -1
- package/dist/{registry-OsEO2dOu.d.mts → registry-DIo0WNoO.d.mts} +8 -1
- package/dist/{registry-OsEO2dOu.d.ts → registry-DIo0WNoO.d.ts} +8 -1
- package/dist/server/index.d.mts +95 -2
- package/dist/server/index.d.ts +95 -2
- package/dist/server/index.js +554 -14
- package/dist/server/index.js.map +1 -1
- package/dist/server/index.mjs +554 -14
- package/dist/server/index.mjs.map +1 -1
- package/dist/verify/index.js.map +1 -1
- package/dist/verify/index.mjs.map +1 -1
- package/dist/wallet/index.js.map +1 -1
- package/dist/wallet/index.mjs.map +1 -1
- package/package.json +7 -1
- package/schemas/moltspay.services.schema.json +100 -6
- package/scripts/postinstall.js +91 -0
package/dist/client/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// src/client/node/index.ts
|
|
2
2
|
import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2, mkdirSync as mkdirSync2, statSync, chmodSync } from "fs";
|
|
3
|
-
import { homedir as
|
|
4
|
-
import { join as
|
|
3
|
+
import { homedir as homedir3 } from "os";
|
|
4
|
+
import { join as join3 } from "path";
|
|
5
5
|
import { Wallet as Wallet2, ethers as ethers2 } from "ethers";
|
|
6
6
|
|
|
7
7
|
// src/chains/index.ts
|
|
@@ -328,6 +328,16 @@ function networkToChainName(network) {
|
|
|
328
328
|
// src/client/core/base64.ts
|
|
329
329
|
var BufferCtor = globalThis.Buffer;
|
|
330
330
|
|
|
331
|
+
// src/client/core/errors.ts
|
|
332
|
+
var MoltsPayError = class extends Error {
|
|
333
|
+
code;
|
|
334
|
+
constructor(code, message) {
|
|
335
|
+
super(message);
|
|
336
|
+
this.name = "MoltsPayError";
|
|
337
|
+
this.code = code;
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
|
|
331
341
|
// src/client/core/eip3009.ts
|
|
332
342
|
var EIP3009_TYPES = {
|
|
333
343
|
TransferWithAuthorization: [
|
|
@@ -464,6 +474,733 @@ function findChainByChainId(chainId) {
|
|
|
464
474
|
return void 0;
|
|
465
475
|
}
|
|
466
476
|
|
|
477
|
+
// src/client/alipay/index.ts
|
|
478
|
+
import { randomUUID } from "crypto";
|
|
479
|
+
import { mkdir, writeFile } from "fs/promises";
|
|
480
|
+
import { homedir as homedir2 } from "os";
|
|
481
|
+
import { join as join2 } from "path";
|
|
482
|
+
|
|
483
|
+
// src/client/alipay/cli.ts
|
|
484
|
+
import { spawn } from "child_process";
|
|
485
|
+
|
|
486
|
+
// src/client/alipay/log.ts
|
|
487
|
+
var RANK = { off: 0, info: 1, debug: 2 };
|
|
488
|
+
function normalizeLevel(v) {
|
|
489
|
+
const s = (v ?? "").toLowerCase();
|
|
490
|
+
return s === "info" || s === "debug" ? s : "off";
|
|
491
|
+
}
|
|
492
|
+
var level = normalizeLevel(process.env.MOLTSPAY_ALIPAY_LOG);
|
|
493
|
+
var sink = (line) => {
|
|
494
|
+
process.stderr.write(line + "\n");
|
|
495
|
+
};
|
|
496
|
+
function enabledFor(want) {
|
|
497
|
+
return RANK[level] >= RANK[want];
|
|
498
|
+
}
|
|
499
|
+
function render(event, fields) {
|
|
500
|
+
const parts = ["[moltspay:alipay]", String(fields.ts), event];
|
|
501
|
+
if (fields.flow) parts.push(`flow=${fields.flow}`);
|
|
502
|
+
if (fields.step) parts.push(`step=${fields.step}`);
|
|
503
|
+
if (typeof fields.ms === "number") parts.push(`${fields.ms}ms`);
|
|
504
|
+
for (const [k, v] of Object.entries(fields)) {
|
|
505
|
+
if (["ts", "level", "event", "flow", "step", "ms"].includes(k)) continue;
|
|
506
|
+
parts.push(`${k}=${typeof v === "string" ? v : JSON.stringify(v)}`);
|
|
507
|
+
}
|
|
508
|
+
return parts.join(" ");
|
|
509
|
+
}
|
|
510
|
+
function emit(lvl, event, fields) {
|
|
511
|
+
if (!enabledFor(lvl)) return;
|
|
512
|
+
const full = { ts: (/* @__PURE__ */ new Date()).toISOString(), level: lvl, event, ...fields };
|
|
513
|
+
try {
|
|
514
|
+
sink(render(event, full), full);
|
|
515
|
+
} catch {
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
var alipayLog = {
|
|
519
|
+
info: (event, fields = {}) => emit("info", event, fields),
|
|
520
|
+
debug: (event, fields = {}) => emit("debug", event, fields),
|
|
521
|
+
/** True if anything at all would be logged (cheap guard for hot paths). */
|
|
522
|
+
enabled: () => level !== "off"
|
|
523
|
+
};
|
|
524
|
+
async function timeStep(step, flow, fn) {
|
|
525
|
+
if (!alipayLog.enabled()) return fn();
|
|
526
|
+
const t0 = Date.now();
|
|
527
|
+
alipayLog.debug("step.start", { flow, step });
|
|
528
|
+
try {
|
|
529
|
+
const out = await fn();
|
|
530
|
+
alipayLog.info("step.end", { flow, step, ms: Date.now() - t0, ok: true });
|
|
531
|
+
return out;
|
|
532
|
+
} catch (err) {
|
|
533
|
+
alipayLog.info("step.end", {
|
|
534
|
+
flow,
|
|
535
|
+
step,
|
|
536
|
+
ms: Date.now() - t0,
|
|
537
|
+
ok: false,
|
|
538
|
+
err: err instanceof Error ? err.message : String(err)
|
|
539
|
+
});
|
|
540
|
+
throw err;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// src/client/alipay/cli.ts
|
|
545
|
+
var ALLOWED_ENV = /* @__PURE__ */ new Set([
|
|
546
|
+
"AIPAY_OUTPUT_CHANNEL",
|
|
547
|
+
"AIPAY_SESSION_ID",
|
|
548
|
+
"AIPAY_FRAMEWORK",
|
|
549
|
+
"AIPAY_MODEL",
|
|
550
|
+
"AIPAY_OS",
|
|
551
|
+
// Minimal survival set for spawn to find the binary and a home dir.
|
|
552
|
+
"PATH",
|
|
553
|
+
"HOME"
|
|
554
|
+
]);
|
|
555
|
+
function filterEnv(env) {
|
|
556
|
+
return Object.fromEntries(
|
|
557
|
+
Object.entries(env).filter(([k]) => ALLOWED_ENV.has(k))
|
|
558
|
+
);
|
|
559
|
+
}
|
|
560
|
+
function makeLineSplitter(onLine) {
|
|
561
|
+
let buf = "";
|
|
562
|
+
return (chunk) => {
|
|
563
|
+
buf += chunk.toString("utf-8");
|
|
564
|
+
let nl;
|
|
565
|
+
while ((nl = buf.indexOf("\n")) !== -1) {
|
|
566
|
+
onLine(buf.slice(0, nl));
|
|
567
|
+
buf = buf.slice(nl + 1);
|
|
568
|
+
}
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
function profileEnv(step, flow) {
|
|
572
|
+
const want = process.env.MOLTSPAY_ALIPAY_CLI_PROFILE;
|
|
573
|
+
const hook = process.env.MOLTSPAY_ALIPAY_CLI_PROFILE_HOOK;
|
|
574
|
+
if (!want || !hook) return {};
|
|
575
|
+
const steps = want.split(",").map((s) => s.trim());
|
|
576
|
+
if (!steps.includes("all") && !steps.includes(step)) return {};
|
|
577
|
+
const dir = process.env.MOLTSPAY_ALIPAY_CLI_PROFILE_DIR || "/tmp";
|
|
578
|
+
const safe = `${flow ?? "noflow"}-${step}-${Date.now()}`.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
579
|
+
const out = `${dir}/cli-profile-${safe}.json`;
|
|
580
|
+
alipayLog.info("cli.profile", { flow, step, out });
|
|
581
|
+
return {
|
|
582
|
+
NODE_OPTIONS: `--require=${hook}`,
|
|
583
|
+
MOLTSPAY_CLI_PROFILE_OUT: out
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
var runCli = (args, opts = {}) => {
|
|
587
|
+
const bin = opts.bin ?? "alipay-bot";
|
|
588
|
+
const step = opts.step ?? args[0] ?? "(no-arg)";
|
|
589
|
+
const startedAt = Date.now();
|
|
590
|
+
const lines = [];
|
|
591
|
+
const collect = (line) => {
|
|
592
|
+
lines.push(line);
|
|
593
|
+
alipayLog.debug("cli.line", {
|
|
594
|
+
flow: opts.flow,
|
|
595
|
+
step,
|
|
596
|
+
ms: Date.now() - startedAt,
|
|
597
|
+
preview: line.slice(0, 120)
|
|
598
|
+
});
|
|
599
|
+
opts.onLine?.(line);
|
|
600
|
+
};
|
|
601
|
+
alipayLog.debug("step.start", { flow: opts.flow, step });
|
|
602
|
+
return new Promise((resolve, reject) => {
|
|
603
|
+
const child = spawn(bin, args, {
|
|
604
|
+
env: { ...filterEnv(process.env), ...profileEnv(step, opts.flow), ...opts.env ?? {} }
|
|
605
|
+
});
|
|
606
|
+
if (opts.signal) {
|
|
607
|
+
if (opts.signal.aborted) child.kill("SIGTERM");
|
|
608
|
+
opts.signal.addEventListener("abort", () => child.kill("SIGTERM"), { once: true });
|
|
609
|
+
}
|
|
610
|
+
let sawByte = false;
|
|
611
|
+
const onChunk = (stream) => (chunk) => {
|
|
612
|
+
const ms = Date.now() - startedAt;
|
|
613
|
+
if (!sawByte) {
|
|
614
|
+
sawByte = true;
|
|
615
|
+
alipayLog.debug("cli.firstbyte", { flow: opts.flow, step, ms });
|
|
616
|
+
}
|
|
617
|
+
alipayLog.debug("cli.chunk", { flow: opts.flow, step, ms, stream, bytes: chunk.length });
|
|
618
|
+
};
|
|
619
|
+
const onStdout = makeLineSplitter(collect);
|
|
620
|
+
const onStderr = makeLineSplitter(collect);
|
|
621
|
+
child.stdout?.on("data", onChunk("out"));
|
|
622
|
+
child.stderr?.on("data", onChunk("err"));
|
|
623
|
+
child.stdout?.on("data", onStdout);
|
|
624
|
+
child.stderr?.on("data", onStderr);
|
|
625
|
+
child.on("error", (err) => {
|
|
626
|
+
alipayLog.info("cli.exit", {
|
|
627
|
+
flow: opts.flow,
|
|
628
|
+
step,
|
|
629
|
+
ms: Date.now() - startedAt,
|
|
630
|
+
ok: false,
|
|
631
|
+
err: err.message
|
|
632
|
+
});
|
|
633
|
+
reject(err);
|
|
634
|
+
});
|
|
635
|
+
child.on("close", (code) => {
|
|
636
|
+
alipayLog.info("cli.exit", {
|
|
637
|
+
flow: opts.flow,
|
|
638
|
+
step,
|
|
639
|
+
ms: Date.now() - startedAt,
|
|
640
|
+
ok: (code ?? 1) === 0,
|
|
641
|
+
code: code ?? 1
|
|
642
|
+
});
|
|
643
|
+
resolve({ exitCode: code ?? 1, lines });
|
|
644
|
+
});
|
|
645
|
+
});
|
|
646
|
+
};
|
|
647
|
+
|
|
648
|
+
// src/client/alipay/install.ts
|
|
649
|
+
import { execFile } from "child_process";
|
|
650
|
+
import { promisify } from "util";
|
|
651
|
+
|
|
652
|
+
// src/client/alipay/errors.ts
|
|
653
|
+
var AlipayCliNotFoundError = class extends MoltsPayError {
|
|
654
|
+
constructor(message) {
|
|
655
|
+
super("ALIPAY_CLI_NOT_FOUND", message);
|
|
656
|
+
this.name = "AlipayCliNotFoundError";
|
|
657
|
+
}
|
|
658
|
+
};
|
|
659
|
+
var AlipayCliVersionError = class extends MoltsPayError {
|
|
660
|
+
constructor(message) {
|
|
661
|
+
super("ALIPAY_CLI_VERSION", message);
|
|
662
|
+
this.name = "AlipayCliVersionError";
|
|
663
|
+
}
|
|
664
|
+
};
|
|
665
|
+
var NeedsWalletSetupError = class extends MoltsPayError {
|
|
666
|
+
constructor(message = "Alipay wallet not set up. Run: moltspay alipay apply") {
|
|
667
|
+
super("ALIPAY_NEEDS_WALLET_SETUP", message);
|
|
668
|
+
this.name = "NeedsWalletSetupError";
|
|
669
|
+
}
|
|
670
|
+
};
|
|
671
|
+
var AlipayPaymentRejectedError = class extends MoltsPayError {
|
|
672
|
+
constructor(message) {
|
|
673
|
+
super("ALIPAY_PAYMENT_REJECTED", message);
|
|
674
|
+
this.name = "AlipayPaymentRejectedError";
|
|
675
|
+
}
|
|
676
|
+
};
|
|
677
|
+
var AlipayPaymentTimeoutError = class extends MoltsPayError {
|
|
678
|
+
constructor(message) {
|
|
679
|
+
super("ALIPAY_PAYMENT_TIMEOUT", message);
|
|
680
|
+
this.name = "AlipayPaymentTimeoutError";
|
|
681
|
+
}
|
|
682
|
+
};
|
|
683
|
+
var AlipayProtocolError = class extends MoltsPayError {
|
|
684
|
+
constructor(message) {
|
|
685
|
+
super("ALIPAY_PROTOCOL", message);
|
|
686
|
+
this.name = "AlipayProtocolError";
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
var UnsupportedRailError = class extends MoltsPayError {
|
|
690
|
+
constructor(rail, message) {
|
|
691
|
+
super("UNSUPPORTED_RAIL", message ?? `Rail not supported by server: ${rail}`);
|
|
692
|
+
this.rail = rail;
|
|
693
|
+
this.name = "UnsupportedRailError";
|
|
694
|
+
}
|
|
695
|
+
};
|
|
696
|
+
|
|
697
|
+
// src/client/alipay/install.ts
|
|
698
|
+
var execFileAsync = promisify(execFile);
|
|
699
|
+
var MIN_CLI_VERSION = "0.3.15";
|
|
700
|
+
function semverLt(a, b) {
|
|
701
|
+
const pa = a.split(".").map((n) => parseInt(n, 10));
|
|
702
|
+
const pb = b.split(".").map((n) => parseInt(n, 10));
|
|
703
|
+
for (let i = 0; i < 3; i++) {
|
|
704
|
+
const x = pa[i] ?? 0;
|
|
705
|
+
const y = pb[i] ?? 0;
|
|
706
|
+
if (x !== y) return x < y;
|
|
707
|
+
}
|
|
708
|
+
return false;
|
|
709
|
+
}
|
|
710
|
+
function parseVersion(stdout) {
|
|
711
|
+
return stdout.match(/v?(\d+\.\d+\.\d+)/)?.[1] ?? null;
|
|
712
|
+
}
|
|
713
|
+
var defaultGetVersion = async () => {
|
|
714
|
+
const { stdout } = await execFileAsync("alipay-bot", ["--version"]);
|
|
715
|
+
return stdout;
|
|
716
|
+
};
|
|
717
|
+
async function ensureCliUncached(getVersion) {
|
|
718
|
+
let stdout;
|
|
719
|
+
try {
|
|
720
|
+
stdout = await getVersion();
|
|
721
|
+
} catch (e) {
|
|
722
|
+
if (e?.code === "ENOENT") {
|
|
723
|
+
throw new AlipayCliNotFoundError(
|
|
724
|
+
"alipay-bot not installed. Run: npx -y @alipay/agent-payment install-cli"
|
|
725
|
+
);
|
|
726
|
+
}
|
|
727
|
+
throw e;
|
|
728
|
+
}
|
|
729
|
+
const version = parseVersion(stdout);
|
|
730
|
+
if (!version || semverLt(version, MIN_CLI_VERSION)) {
|
|
731
|
+
throw new AlipayCliVersionError(
|
|
732
|
+
`alipay-bot ${version ?? "?"} found, need \u2265 ${MIN_CLI_VERSION}. Run: npx -y @alipay/agent-payment@latest update`
|
|
733
|
+
);
|
|
734
|
+
}
|
|
735
|
+
return version;
|
|
736
|
+
}
|
|
737
|
+
var cachedVersion = null;
|
|
738
|
+
var inflight = null;
|
|
739
|
+
async function ensureCli(getVersion = defaultGetVersion) {
|
|
740
|
+
if (getVersion !== defaultGetVersion) {
|
|
741
|
+
return ensureCliUncached(getVersion);
|
|
742
|
+
}
|
|
743
|
+
if (cachedVersion) return cachedVersion;
|
|
744
|
+
if (!inflight) {
|
|
745
|
+
inflight = ensureCliUncached(getVersion).then((v) => {
|
|
746
|
+
cachedVersion = v;
|
|
747
|
+
return v;
|
|
748
|
+
}).finally(() => {
|
|
749
|
+
inflight = null;
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
return inflight;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
// src/client/alipay/poll.ts
|
|
756
|
+
var POLL_INTERVAL_MS = 3e3;
|
|
757
|
+
var POLL_MAX_INFLIGHT = 2;
|
|
758
|
+
function resolveMaxInflight(override) {
|
|
759
|
+
if (override !== void 0) return Math.max(1, Math.floor(override));
|
|
760
|
+
const raw = process.env.MOLTSPAY_ALIPAY_POLL_MAX_INFLIGHT;
|
|
761
|
+
if (raw !== void 0 && raw.trim() !== "") {
|
|
762
|
+
const n = Number(raw);
|
|
763
|
+
if (Number.isFinite(n) && n >= 1) return Math.floor(n);
|
|
764
|
+
}
|
|
765
|
+
return POLL_MAX_INFLIGHT;
|
|
766
|
+
}
|
|
767
|
+
function resolveLaunchGap(override) {
|
|
768
|
+
if (override !== void 0) return Math.max(0, override);
|
|
769
|
+
const raw = process.env.MOLTSPAY_ALIPAY_POLL_LAUNCH_MS;
|
|
770
|
+
if (raw !== void 0 && raw.trim() !== "") {
|
|
771
|
+
const n = Number(raw);
|
|
772
|
+
if (Number.isFinite(n) && n >= 0) return n;
|
|
773
|
+
}
|
|
774
|
+
return POLL_INTERVAL_MS;
|
|
775
|
+
}
|
|
776
|
+
function parseStatus(lines) {
|
|
777
|
+
const raw = lines.join("\n").trim();
|
|
778
|
+
try {
|
|
779
|
+
const json = JSON.parse(raw);
|
|
780
|
+
if (json && typeof json === "object") {
|
|
781
|
+
if (typeof json.success === "boolean") {
|
|
782
|
+
if (json.success) return "paid";
|
|
783
|
+
const err = String(json.errorCode ?? "").toUpperCase();
|
|
784
|
+
if (/UNPAID|WAIT|PENDING|PROCESS|NOTPAY/.test(err)) return "pending";
|
|
785
|
+
if (/CLOSED|CANCEL|FAIL|REJECT|REFUSE|TIMEOUT|EXPIRE/.test(err)) return "rejected";
|
|
786
|
+
return "pending";
|
|
787
|
+
}
|
|
788
|
+
if (typeof json.code !== "undefined") {
|
|
789
|
+
if (Number(json.code) === 200) return "paid";
|
|
790
|
+
const msg = `${json.message ?? ""}${json.reason ?? ""}`;
|
|
791
|
+
if (/关闭|失败|拒绝|取消|超时|已撤销/.test(msg)) return "rejected";
|
|
792
|
+
return "pending";
|
|
793
|
+
}
|
|
794
|
+
if (typeof json.body === "string") {
|
|
795
|
+
return classifyReportText(json.body);
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
} catch {
|
|
799
|
+
}
|
|
800
|
+
return classifyReportText(raw);
|
|
801
|
+
}
|
|
802
|
+
function classifyReportText(s) {
|
|
803
|
+
const text = s.toUpperCase();
|
|
804
|
+
if (/查询支付状态成功并获取资源/.test(s) || /资源响应状态[^0-9\n]{0,8}200/.test(s) || /TRADE_SUCCESS|TRADE_FINISHED|"STATUS":\s*"FULFILLED"/.test(text)) return "paid";
|
|
805
|
+
if (/TRADE_CLOSED|REJECTED|REFUSE|CANCEL/.test(text) || /交易关闭|支付失败|已拒绝|已取消|已撤销|交易超时/.test(s)) return "rejected";
|
|
806
|
+
if (/WAIT_BUYER_PAY|UNPAID|PENDING|WAITING/.test(text) || /交易未支付|等待付款|待支付|未支付/.test(s)) return "pending";
|
|
807
|
+
return "unknown";
|
|
808
|
+
}
|
|
809
|
+
function defaultSleep(ms, signal) {
|
|
810
|
+
return new Promise((resolve, reject) => {
|
|
811
|
+
if (signal?.aborted) return reject(new Error("aborted"));
|
|
812
|
+
const t = setTimeout(resolve, ms);
|
|
813
|
+
signal?.addEventListener(
|
|
814
|
+
"abort",
|
|
815
|
+
() => {
|
|
816
|
+
clearTimeout(t);
|
|
817
|
+
reject(new Error("aborted"));
|
|
818
|
+
},
|
|
819
|
+
{ once: true }
|
|
820
|
+
);
|
|
821
|
+
});
|
|
822
|
+
}
|
|
823
|
+
var LAUNCH = /* @__PURE__ */ Symbol("launch");
|
|
824
|
+
async function pollUntil(tradeNo, resourceUrl, opts) {
|
|
825
|
+
const runner = opts.runner ?? runCli;
|
|
826
|
+
const sleep = opts.sleep ?? defaultSleep;
|
|
827
|
+
const now = opts.now ?? Date.now;
|
|
828
|
+
const maxInflight = resolveMaxInflight(opts.maxInflight);
|
|
829
|
+
const launchGap = resolveLaunchGap(opts.launchIntervalMs);
|
|
830
|
+
const args = [
|
|
831
|
+
"402-query-payment-status",
|
|
832
|
+
"-t",
|
|
833
|
+
tradeNo,
|
|
834
|
+
"-r",
|
|
835
|
+
resourceUrl,
|
|
836
|
+
...opts.method ? ["-m", opts.method] : [],
|
|
837
|
+
...opts.data ? ["-d", opts.data] : []
|
|
838
|
+
];
|
|
839
|
+
const internal = new AbortController();
|
|
840
|
+
const signal = opts.signal ? AbortSignal.any([opts.signal, internal.signal]) : internal.signal;
|
|
841
|
+
let tick = 0;
|
|
842
|
+
let lastLaunch = -Infinity;
|
|
843
|
+
const inflight2 = /* @__PURE__ */ new Set();
|
|
844
|
+
const launch = () => {
|
|
845
|
+
tick += 1;
|
|
846
|
+
const myTick = tick;
|
|
847
|
+
lastLaunch = now();
|
|
848
|
+
const run = (async () => {
|
|
849
|
+
const { lines } = await runner(args, {
|
|
850
|
+
signal,
|
|
851
|
+
step: "query-payment-status",
|
|
852
|
+
flow: tradeNo
|
|
853
|
+
});
|
|
854
|
+
const status = parseStatus(lines);
|
|
855
|
+
alipayLog.debug("poll.tick", { flow: tradeNo, tick: myTick, status });
|
|
856
|
+
return { status, lines };
|
|
857
|
+
})();
|
|
858
|
+
const tracked = run.finally(() => {
|
|
859
|
+
inflight2.delete(tracked);
|
|
860
|
+
});
|
|
861
|
+
inflight2.add(tracked);
|
|
862
|
+
};
|
|
863
|
+
try {
|
|
864
|
+
for (; ; ) {
|
|
865
|
+
if (opts.signal?.aborted) throw new Error("aborted");
|
|
866
|
+
const expired = now() >= opts.deadline;
|
|
867
|
+
if (expired && inflight2.size === 0) {
|
|
868
|
+
throw new AlipayPaymentTimeoutError(
|
|
869
|
+
`Payment ${tradeNo} not completed before pay_before deadline`
|
|
870
|
+
);
|
|
871
|
+
}
|
|
872
|
+
while (!expired && inflight2.size < maxInflight && now() - lastLaunch >= launchGap) {
|
|
873
|
+
launch();
|
|
874
|
+
}
|
|
875
|
+
const waiters = [...inflight2];
|
|
876
|
+
if (!expired && inflight2.size < maxInflight) {
|
|
877
|
+
const untilNext = Math.max(0, launchGap - (now() - lastLaunch));
|
|
878
|
+
waiters.push(sleep(untilNext, signal).then(() => LAUNCH, () => LAUNCH));
|
|
879
|
+
}
|
|
880
|
+
const winner = await Promise.race(waiters);
|
|
881
|
+
if (winner === LAUNCH) continue;
|
|
882
|
+
if (winner.status === "paid") return { status: "paid", lines: winner.lines };
|
|
883
|
+
if (winner.status === "rejected") {
|
|
884
|
+
throw new AlipayPaymentRejectedError(`Payment ${tradeNo} was rejected`);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
} finally {
|
|
888
|
+
internal.abort();
|
|
889
|
+
for (const p of inflight2) p.catch(() => void 0);
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
// src/client/alipay/index.ts
|
|
894
|
+
var TRADE_NO_RE = /^\d{32}$/;
|
|
895
|
+
function resolveSessionId(explicit, envSession) {
|
|
896
|
+
return explicit ?? envSession ?? randomUUID();
|
|
897
|
+
}
|
|
898
|
+
function assertTradeNo(t) {
|
|
899
|
+
if (!TRADE_NO_RE.test(t)) {
|
|
900
|
+
throw new AlipayProtocolError(`invalid tradeNo (expect 32 digits): ${t}`);
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
function parseTradeNo(lines) {
|
|
904
|
+
for (const line of lines) {
|
|
905
|
+
const labeled = line.match(/trade[_-]?no["'\s:=]+(\d{32})/i);
|
|
906
|
+
if (labeled) return labeled[1];
|
|
907
|
+
const bare = line.match(/\b(\d{32})\b/);
|
|
908
|
+
if (bare) return bare[1];
|
|
909
|
+
}
|
|
910
|
+
return null;
|
|
911
|
+
}
|
|
912
|
+
function parsePaymentUrl(lines) {
|
|
913
|
+
let paymentUrl;
|
|
914
|
+
let shortenUrl;
|
|
915
|
+
for (const line of lines) {
|
|
916
|
+
const m = line.match(/(alipays?:\/\/\S+|https?:\/\/\S+)/i);
|
|
917
|
+
if (!m) continue;
|
|
918
|
+
const url = m[1].replace(/[)\]`>]+$/, "");
|
|
919
|
+
if (/short|qr\.alipay|surl|\/s\//i.test(line) && !shortenUrl) shortenUrl = url;
|
|
920
|
+
else if (!paymentUrl) paymentUrl = url;
|
|
921
|
+
}
|
|
922
|
+
if (!paymentUrl && shortenUrl) paymentUrl = shortenUrl;
|
|
923
|
+
return { paymentUrl, shortenUrl };
|
|
924
|
+
}
|
|
925
|
+
function extractMedia(line) {
|
|
926
|
+
const m = line.match(/^\s*MEDIA:\s*(.+?)\s*$/);
|
|
927
|
+
return m ? m[1] : null;
|
|
928
|
+
}
|
|
929
|
+
function isWalletReady(lines) {
|
|
930
|
+
const text = lines.join("\n").trim();
|
|
931
|
+
try {
|
|
932
|
+
const json = JSON.parse(text);
|
|
933
|
+
if (json && typeof json.code !== "undefined") return Number(json.code) === 200;
|
|
934
|
+
} catch {
|
|
935
|
+
}
|
|
936
|
+
return !/未开通|未开启|NOT[_\s-]*(OPEN|BOUND|SET)|NEEDS?[_\s-]*SETUP|NO[_\s-]*WALLET/i.test(text);
|
|
937
|
+
}
|
|
938
|
+
function extractResourceFromReport(report) {
|
|
939
|
+
const label = report.search(/资源响应体/);
|
|
940
|
+
const start = report.indexOf("{", label === -1 ? 0 : label);
|
|
941
|
+
if (start === -1) return void 0;
|
|
942
|
+
let depth = 0, inStr = false, esc = false;
|
|
943
|
+
for (let i = start; i < report.length; i++) {
|
|
944
|
+
const ch = report[i];
|
|
945
|
+
if (inStr) {
|
|
946
|
+
if (esc) esc = false;
|
|
947
|
+
else if (ch === "\\") esc = true;
|
|
948
|
+
else if (ch === '"') inStr = false;
|
|
949
|
+
continue;
|
|
950
|
+
}
|
|
951
|
+
if (ch === '"') inStr = true;
|
|
952
|
+
else if (ch === "{") depth++;
|
|
953
|
+
else if (ch === "}" && --depth === 0) {
|
|
954
|
+
const slice = report.slice(start, i + 1);
|
|
955
|
+
try {
|
|
956
|
+
const obj = JSON.parse(slice);
|
|
957
|
+
const r = obj?.resourceResponse ?? obj?.result ?? obj?.data ?? obj?.body ?? obj;
|
|
958
|
+
return typeof r === "string" ? r : JSON.stringify(r);
|
|
959
|
+
} catch {
|
|
960
|
+
return slice;
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
return void 0;
|
|
965
|
+
}
|
|
966
|
+
function extractBody(lines) {
|
|
967
|
+
const text = lines.join("\n").trim();
|
|
968
|
+
try {
|
|
969
|
+
const json = JSON.parse(text);
|
|
970
|
+
if (json && typeof json === "object") {
|
|
971
|
+
if (json.resourceResponse !== void 0 && json.resourceResponse !== null) {
|
|
972
|
+
const rr = json.resourceResponse;
|
|
973
|
+
const r = typeof rr === "object" ? rr.result ?? rr.data ?? rr.body ?? rr : rr;
|
|
974
|
+
return typeof r === "string" ? r : JSON.stringify(r);
|
|
975
|
+
}
|
|
976
|
+
if (typeof json.body === "string") {
|
|
977
|
+
const inner = extractResourceFromReport(json.body);
|
|
978
|
+
return inner ?? json.body;
|
|
979
|
+
}
|
|
980
|
+
const body = json.data ?? json.result ?? json.body ?? json.resource;
|
|
981
|
+
if (body !== void 0) return typeof body === "string" ? body : JSON.stringify(body);
|
|
982
|
+
return text;
|
|
983
|
+
}
|
|
984
|
+
} catch {
|
|
985
|
+
}
|
|
986
|
+
const idx = lines.findIndex((l) => /^\s*BODY:/.test(l));
|
|
987
|
+
if (idx !== -1) {
|
|
988
|
+
const first = lines[idx].replace(/^\s*BODY:\s*/, "");
|
|
989
|
+
return [first, ...lines.slice(idx + 1)].join("\n").trim();
|
|
990
|
+
}
|
|
991
|
+
return lines.filter((l) => !/^\s*(MEDIA|STATUS|INFO):/.test(l)).join("\n").trim();
|
|
992
|
+
}
|
|
993
|
+
var DEFAULT_WALLET_TTL_MS = 10 * 60 * 1e3;
|
|
994
|
+
function resolveWalletTtlMs() {
|
|
995
|
+
const raw = process.env.MOLTSPAY_ALIPAY_WALLET_TTL_MS;
|
|
996
|
+
if (raw === void 0 || raw.trim() === "") return DEFAULT_WALLET_TTL_MS;
|
|
997
|
+
const n = Number(raw);
|
|
998
|
+
return Number.isFinite(n) && n >= 0 ? n : DEFAULT_WALLET_TTL_MS;
|
|
999
|
+
}
|
|
1000
|
+
var walletReadyUntil = /* @__PURE__ */ new Map();
|
|
1001
|
+
var DEFAULT_INTENT_TTL_MS = 10 * 60 * 1e3;
|
|
1002
|
+
function resolveIntentTtlMs() {
|
|
1003
|
+
const raw = process.env.MOLTSPAY_ALIPAY_INTENT_TTL_MS;
|
|
1004
|
+
if (raw === void 0 || raw.trim() === "") return DEFAULT_INTENT_TTL_MS;
|
|
1005
|
+
const n = Number(raw);
|
|
1006
|
+
return Number.isFinite(n) && n >= 0 ? n : DEFAULT_INTENT_TTL_MS;
|
|
1007
|
+
}
|
|
1008
|
+
var intentDoneUntil = /* @__PURE__ */ new Map();
|
|
1009
|
+
var AlipayClient = class {
|
|
1010
|
+
sessionId;
|
|
1011
|
+
configDir;
|
|
1012
|
+
framework;
|
|
1013
|
+
runner;
|
|
1014
|
+
getVersion;
|
|
1015
|
+
now;
|
|
1016
|
+
/** Only the default runner may use the process-level wallet cache. */
|
|
1017
|
+
walletCacheable;
|
|
1018
|
+
/** Only the default runner may use the process-level payment-intent cache. */
|
|
1019
|
+
intentCacheable;
|
|
1020
|
+
constructor(opts = {}) {
|
|
1021
|
+
this.sessionId = resolveSessionId(opts.sessionId, process.env.AIPAY_SESSION_ID);
|
|
1022
|
+
this.configDir = opts.configDir ?? join2(homedir2(), ".moltspay");
|
|
1023
|
+
this.framework = opts.framework ?? process.env.AIPAY_FRAMEWORK ?? "openclaw";
|
|
1024
|
+
this.runner = opts.runner ?? runCli;
|
|
1025
|
+
this.getVersion = opts.getVersion;
|
|
1026
|
+
this.now = opts.now ?? Date.now;
|
|
1027
|
+
this.walletCacheable = opts.cacheWallet ?? !opts.runner;
|
|
1028
|
+
this.intentCacheable = opts.cacheIntent ?? !opts.runner;
|
|
1029
|
+
}
|
|
1030
|
+
/**
|
|
1031
|
+
* Throws NeedsWalletSetupError unless alipay-bot reports an opened wallet.
|
|
1032
|
+
*
|
|
1033
|
+
* Skips the ~22s `check-wallet` spawn entirely when a prior call cached a
|
|
1034
|
+
* "ready" verdict within the TTL (see {@link DEFAULT_WALLET_TTL_MS}).
|
|
1035
|
+
*/
|
|
1036
|
+
async checkWallet(signal, flow) {
|
|
1037
|
+
const ttlMs = resolveWalletTtlMs();
|
|
1038
|
+
const cacheKey = `${this.configDir}::${this.framework}`;
|
|
1039
|
+
const useCache = this.walletCacheable && ttlMs > 0;
|
|
1040
|
+
if (useCache) {
|
|
1041
|
+
const until = walletReadyUntil.get(cacheKey);
|
|
1042
|
+
if (until !== void 0 && this.now() < until) {
|
|
1043
|
+
alipayLog.info("wallet.cache", { flow, step: "check-wallet", hit: true, ttlMsLeft: until - this.now() });
|
|
1044
|
+
return;
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
const { lines } = await this.runner(["check-wallet"], { signal, step: "check-wallet", flow });
|
|
1048
|
+
if (!isWalletReady(lines)) {
|
|
1049
|
+
if (this.walletCacheable) walletReadyUntil.delete(cacheKey);
|
|
1050
|
+
throw new NeedsWalletSetupError(
|
|
1051
|
+
"Alipay wallet not opened. Run: moltspay alipay apply (then: moltspay alipay bind)"
|
|
1052
|
+
);
|
|
1053
|
+
}
|
|
1054
|
+
if (useCache) {
|
|
1055
|
+
walletReadyUntil.set(cacheKey, this.now() + ttlMs);
|
|
1056
|
+
alipayLog.info("wallet.cache", { flow, step: "check-wallet", hit: false, cachedForMs: ttlMs });
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
/** Run the full 8-step flow and resolve with the resource body. */
|
|
1060
|
+
async pay402(opts) {
|
|
1061
|
+
const { resourceUrl, requirement, signal } = opts;
|
|
1062
|
+
const extra = requirement.extra ?? {};
|
|
1063
|
+
const paymentNeededHeader = String(extra.payment_needed_header ?? "");
|
|
1064
|
+
if (!paymentNeededHeader) {
|
|
1065
|
+
throw new AlipayProtocolError("alipay requirement missing extra.payment_needed_header");
|
|
1066
|
+
}
|
|
1067
|
+
const flow = this.sessionId;
|
|
1068
|
+
const flowStart = this.now();
|
|
1069
|
+
alipayLog.info("flow.start", { flow, resource: resourceUrl });
|
|
1070
|
+
const media = [];
|
|
1071
|
+
const onLine = (line) => {
|
|
1072
|
+
const m = extractMedia(line);
|
|
1073
|
+
if (m) media.push(m);
|
|
1074
|
+
else opts.onLine?.(line);
|
|
1075
|
+
};
|
|
1076
|
+
const intentSummary = opts.intentSummary?.trim() || `\u652F\u4ED8 ${requirement.amount ?? ""} ${requirement.asset ?? "CNY"}`.trim();
|
|
1077
|
+
await timeStep("ensure-cli", flow, () => ensureCli(this.getVersion));
|
|
1078
|
+
const intentTtlMs = resolveIntentTtlMs();
|
|
1079
|
+
const intentKey = `${this.configDir}::${this.framework}`;
|
|
1080
|
+
const useIntentCache = this.intentCacheable && intentTtlMs > 0;
|
|
1081
|
+
const intentUntil = useIntentCache ? intentDoneUntil.get(intentKey) : void 0;
|
|
1082
|
+
if (intentUntil !== void 0 && this.now() < intentUntil) {
|
|
1083
|
+
alipayLog.info("intent.cache", { flow, step: "payment-intent", hit: true, ttlMsLeft: intentUntil - this.now() });
|
|
1084
|
+
} else {
|
|
1085
|
+
await this.runner(
|
|
1086
|
+
[
|
|
1087
|
+
"payment-intent",
|
|
1088
|
+
"--session-id",
|
|
1089
|
+
this.sessionId,
|
|
1090
|
+
"--intent-summary",
|
|
1091
|
+
intentSummary,
|
|
1092
|
+
"--framework",
|
|
1093
|
+
this.framework
|
|
1094
|
+
],
|
|
1095
|
+
{ onLine, signal, step: "payment-intent", flow }
|
|
1096
|
+
);
|
|
1097
|
+
if (useIntentCache) {
|
|
1098
|
+
intentDoneUntil.set(intentKey, this.now() + intentTtlMs);
|
|
1099
|
+
alipayLog.info("intent.cache", { flow, step: "payment-intent", hit: false, cachedForMs: intentTtlMs });
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
await this.checkWallet(signal, flow);
|
|
1103
|
+
const reqId = String(extra.out_trade_no ?? randomUUID());
|
|
1104
|
+
const dir = join2(this.configDir, "alipay");
|
|
1105
|
+
await mkdir(dir, { recursive: true });
|
|
1106
|
+
const challengeFile = join2(dir, `402_${reqId}.txt`);
|
|
1107
|
+
await writeFile(challengeFile, paymentNeededHeader, "utf-8");
|
|
1108
|
+
const payArgs = [
|
|
1109
|
+
"402-buyer-pay",
|
|
1110
|
+
"-f",
|
|
1111
|
+
challengeFile,
|
|
1112
|
+
"-r",
|
|
1113
|
+
resourceUrl,
|
|
1114
|
+
"-s",
|
|
1115
|
+
this.sessionId,
|
|
1116
|
+
"-i",
|
|
1117
|
+
intentSummary,
|
|
1118
|
+
"-w",
|
|
1119
|
+
this.framework
|
|
1120
|
+
];
|
|
1121
|
+
if (opts.method) payArgs.push("-m", opts.method);
|
|
1122
|
+
if (opts.data) payArgs.push("-d", opts.data);
|
|
1123
|
+
const payRun = await this.runner(payArgs, { onLine, signal, step: "402-buyer-pay", flow });
|
|
1124
|
+
const tradeNo = parseTradeNo(payRun.lines);
|
|
1125
|
+
if (!tradeNo) {
|
|
1126
|
+
throw new AlipayProtocolError("402-buyer-pay did not return a tradeNo");
|
|
1127
|
+
}
|
|
1128
|
+
assertTradeNo(tradeNo);
|
|
1129
|
+
const { paymentUrl, shortenUrl } = parsePaymentUrl(payRun.lines);
|
|
1130
|
+
if (paymentUrl) {
|
|
1131
|
+
alipayLog.info("flow.pending", { flow, tradeNo, ms: this.now() - flowStart });
|
|
1132
|
+
opts.onPaymentPending?.({ paymentUrl, shortenUrl, tradeNo });
|
|
1133
|
+
}
|
|
1134
|
+
const pendingAt = this.now();
|
|
1135
|
+
const windowMs = (requirement.maxTimeoutSeconds ?? 30 * 60) * 1e3;
|
|
1136
|
+
const deadline = this.now() + (opts.timeoutMs ?? windowMs);
|
|
1137
|
+
const poll = await pollUntil(tradeNo, resourceUrl, {
|
|
1138
|
+
// No onLine: the status-poll output embeds the resource and must not reach
|
|
1139
|
+
// the log stream — the body is surfaced via the return value below (§9.3).
|
|
1140
|
+
deadline,
|
|
1141
|
+
signal,
|
|
1142
|
+
runner: this.runner,
|
|
1143
|
+
now: this.now,
|
|
1144
|
+
// Re-fetch the resource the same way it was paid (POST + body), else the
|
|
1145
|
+
// status poll defaults to GET and 404s on a POST-only `/execute`.
|
|
1146
|
+
method: opts.method,
|
|
1147
|
+
data: opts.data
|
|
1148
|
+
});
|
|
1149
|
+
alipayLog.info("flow.settled", { flow, tradeNo, ms: this.now() - pendingAt });
|
|
1150
|
+
const body = extractBody(poll.lines);
|
|
1151
|
+
void this.runner(["402-buyer-fulfillment-ack", "-t", tradeNo], {
|
|
1152
|
+
onLine,
|
|
1153
|
+
signal,
|
|
1154
|
+
step: "402-buyer-fulfillment-ack",
|
|
1155
|
+
flow
|
|
1156
|
+
}).catch(() => void 0);
|
|
1157
|
+
return { body, payment: { tradeNo, outTradeNo: reqId }, media };
|
|
1158
|
+
}
|
|
1159
|
+
};
|
|
1160
|
+
|
|
1161
|
+
// src/client/alipay/router.ts
|
|
1162
|
+
var ALIPAY_RAIL = "alipay";
|
|
1163
|
+
function railOf(req) {
|
|
1164
|
+
if (req.scheme === "alipay-aipay" || req.network === ALIPAY_RAIL) return ALIPAY_RAIL;
|
|
1165
|
+
return networkToChainName(req.network) ?? req.network;
|
|
1166
|
+
}
|
|
1167
|
+
function findRail(accepts, rail) {
|
|
1168
|
+
const requirement = accepts.find((r) => railOf(r) === rail);
|
|
1169
|
+
return requirement ? { rail, requirement } : null;
|
|
1170
|
+
}
|
|
1171
|
+
function selectRail(input) {
|
|
1172
|
+
const { serverAccepts, explicitRail, preference, availability } = input;
|
|
1173
|
+
if (!serverAccepts || serverAccepts.length === 0) {
|
|
1174
|
+
throw new UnsupportedRailError(explicitRail ?? "unknown", "Server offered no payment options");
|
|
1175
|
+
}
|
|
1176
|
+
if (explicitRail) {
|
|
1177
|
+
const hit = findRail(serverAccepts, explicitRail);
|
|
1178
|
+
if (!hit) {
|
|
1179
|
+
const offered = serverAccepts.map(railOf);
|
|
1180
|
+
throw new UnsupportedRailError(
|
|
1181
|
+
explicitRail,
|
|
1182
|
+
`Server doesn't accept rail '${explicitRail}'. Offered: ${offered.join(", ")}`
|
|
1183
|
+
);
|
|
1184
|
+
}
|
|
1185
|
+
return hit;
|
|
1186
|
+
}
|
|
1187
|
+
if (preference) {
|
|
1188
|
+
for (const pref of preference) {
|
|
1189
|
+
const hit = findRail(serverAccepts, pref);
|
|
1190
|
+
if (hit) return hit;
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
if (availability?.evmReady) {
|
|
1194
|
+
const evm = serverAccepts.find((r) => railOf(r) !== ALIPAY_RAIL);
|
|
1195
|
+
if (evm) return { rail: railOf(evm), requirement: evm };
|
|
1196
|
+
}
|
|
1197
|
+
if (availability?.alipayReady) {
|
|
1198
|
+
const hit = findRail(serverAccepts, ALIPAY_RAIL);
|
|
1199
|
+
if (hit) return hit;
|
|
1200
|
+
}
|
|
1201
|
+
return { rail: railOf(serverAccepts[0]), requirement: serverAccepts[0] };
|
|
1202
|
+
}
|
|
1203
|
+
|
|
467
1204
|
// src/client/node/index.ts
|
|
468
1205
|
var DEFAULT_CONFIG = {
|
|
469
1206
|
chain: "base",
|
|
@@ -480,9 +1217,13 @@ var MoltsPayClient = class {
|
|
|
480
1217
|
signer = null;
|
|
481
1218
|
todaySpending = 0;
|
|
482
1219
|
lastSpendingReset = 0;
|
|
1220
|
+
railPreference;
|
|
1221
|
+
alipaySessionId;
|
|
483
1222
|
constructor(options = {}) {
|
|
484
|
-
this.configDir = options.configDir ||
|
|
1223
|
+
this.configDir = options.configDir || join3(homedir3(), ".moltspay");
|
|
485
1224
|
this.config = this.loadConfig();
|
|
1225
|
+
this.railPreference = options.railPreference ?? this.config.railPreference;
|
|
1226
|
+
this.alipaySessionId = options.alipaySessionId;
|
|
486
1227
|
this.walletData = this.loadWallet();
|
|
487
1228
|
this.loadSpending();
|
|
488
1229
|
if (this.walletData) {
|
|
@@ -560,6 +1301,9 @@ var MoltsPayClient = class {
|
|
|
560
1301
|
* @param options - Payment options (token selection)
|
|
561
1302
|
*/
|
|
562
1303
|
async pay(serverUrl, service, params, options = {}) {
|
|
1304
|
+
if (options.rail === ALIPAY_RAIL) {
|
|
1305
|
+
return this.payViaAlipay(serverUrl, service, params, options);
|
|
1306
|
+
}
|
|
563
1307
|
if (!this.wallet || !this.walletData) {
|
|
564
1308
|
throw new Error("Client not initialized. Run: npx moltspay init");
|
|
565
1309
|
}
|
|
@@ -751,6 +1495,76 @@ Please specify: --chain <chain_name>`
|
|
|
751
1495
|
console.log(`[MoltsPay] Success! Payment: ${result.payment?.status || "claimed"}`);
|
|
752
1496
|
return result.result || result;
|
|
753
1497
|
}
|
|
1498
|
+
/**
|
|
1499
|
+
* Pay for a service over the Alipay fiat rail (2.0.0).
|
|
1500
|
+
*
|
|
1501
|
+
* Unlike the crypto path this needs no EVM wallet — it shells out to
|
|
1502
|
+
* alipay-bot via {@link AlipayClient}. Flow: hit the resource with no
|
|
1503
|
+
* payment to get the 402 challenge, confirm the server actually offers the
|
|
1504
|
+
* alipay rail (selectRail), then run the 8-step state machine and return the
|
|
1505
|
+
* resource body.
|
|
1506
|
+
*/
|
|
1507
|
+
async payViaAlipay(serverUrl, service, params, options) {
|
|
1508
|
+
const flow = this.alipaySessionId;
|
|
1509
|
+
let executeUrl = `${serverUrl}/execute`;
|
|
1510
|
+
try {
|
|
1511
|
+
const services = await timeStep(
|
|
1512
|
+
"discover-services",
|
|
1513
|
+
flow,
|
|
1514
|
+
() => this.getServices(serverUrl)
|
|
1515
|
+
);
|
|
1516
|
+
const svc = services.services?.find((s) => s.id === service);
|
|
1517
|
+
if (svc?.endpoint) executeUrl = `${serverUrl}${svc.endpoint}`;
|
|
1518
|
+
} catch {
|
|
1519
|
+
}
|
|
1520
|
+
const requestBody = options.rawData ? { service, ...params } : { service, params };
|
|
1521
|
+
const bodyJson = JSON.stringify(requestBody);
|
|
1522
|
+
const res = await timeStep(
|
|
1523
|
+
"challenge-402",
|
|
1524
|
+
flow,
|
|
1525
|
+
() => fetch(executeUrl, {
|
|
1526
|
+
method: "POST",
|
|
1527
|
+
headers: { "Content-Type": "application/json" },
|
|
1528
|
+
body: bodyJson
|
|
1529
|
+
})
|
|
1530
|
+
);
|
|
1531
|
+
if (res.status !== 402) {
|
|
1532
|
+
const data = await res.json().catch(() => ({}));
|
|
1533
|
+
if (res.ok && data.result) return data.result;
|
|
1534
|
+
throw new Error(data.error || `Expected 402, got ${res.status}`);
|
|
1535
|
+
}
|
|
1536
|
+
const header = res.headers.get(PAYMENT_REQUIRED_HEADER);
|
|
1537
|
+
if (!header) throw new Error("Missing x-payment-required header on 402");
|
|
1538
|
+
const parsed = JSON.parse(Buffer.from(header, "base64").toString("utf-8"));
|
|
1539
|
+
const accepts = Array.isArray(parsed) ? parsed : parsed.accepts ?? [parsed];
|
|
1540
|
+
const { requirement } = selectRail({
|
|
1541
|
+
serverAccepts: accepts,
|
|
1542
|
+
explicitRail: ALIPAY_RAIL,
|
|
1543
|
+
preference: this.railPreference,
|
|
1544
|
+
availability: { evmReady: this.isInitialized }
|
|
1545
|
+
});
|
|
1546
|
+
const onLine = options.onLine ?? ((line) => process.stdout.write(line + "\n"));
|
|
1547
|
+
const alipay = new AlipayClient({
|
|
1548
|
+
sessionId: this.alipaySessionId,
|
|
1549
|
+
configDir: this.configDir
|
|
1550
|
+
});
|
|
1551
|
+
const result = await alipay.pay402({
|
|
1552
|
+
resourceUrl: executeUrl,
|
|
1553
|
+
requirement,
|
|
1554
|
+
method: "POST",
|
|
1555
|
+
data: bodyJson,
|
|
1556
|
+
onLine,
|
|
1557
|
+
onPaymentPending: options.onPaymentPending,
|
|
1558
|
+
timeoutMs: options.timeoutMs,
|
|
1559
|
+
signal: options.signal
|
|
1560
|
+
});
|
|
1561
|
+
try {
|
|
1562
|
+
const json = JSON.parse(result.body);
|
|
1563
|
+
return json.result ?? json;
|
|
1564
|
+
} catch {
|
|
1565
|
+
return { body: result.body, payment: result.payment, media: result.media };
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
754
1568
|
/**
|
|
755
1569
|
* Handle MPP (Machine Payments Protocol) payment flow
|
|
756
1570
|
* Called when pay() detects WWW-Authenticate header in 402 response
|
|
@@ -1091,7 +1905,7 @@ Run: npx moltspay approve --chain ${chainName} --spender ${spender}`
|
|
|
1091
1905
|
}
|
|
1092
1906
|
// --- Config & Wallet Management ---
|
|
1093
1907
|
loadConfig() {
|
|
1094
|
-
const configPath =
|
|
1908
|
+
const configPath = join3(this.configDir, "config.json");
|
|
1095
1909
|
if (existsSync2(configPath)) {
|
|
1096
1910
|
const content = readFileSync2(configPath, "utf-8");
|
|
1097
1911
|
return { ...DEFAULT_CONFIG, ...JSON.parse(content) };
|
|
@@ -1100,14 +1914,14 @@ Run: npx moltspay approve --chain ${chainName} --spender ${spender}`
|
|
|
1100
1914
|
}
|
|
1101
1915
|
saveConfig() {
|
|
1102
1916
|
mkdirSync2(this.configDir, { recursive: true });
|
|
1103
|
-
const configPath =
|
|
1917
|
+
const configPath = join3(this.configDir, "config.json");
|
|
1104
1918
|
writeFileSync2(configPath, JSON.stringify(this.config, null, 2));
|
|
1105
1919
|
}
|
|
1106
1920
|
/**
|
|
1107
1921
|
* Load spending data from disk
|
|
1108
1922
|
*/
|
|
1109
1923
|
loadSpending() {
|
|
1110
|
-
const spendingPath =
|
|
1924
|
+
const spendingPath = join3(this.configDir, "spending.json");
|
|
1111
1925
|
if (existsSync2(spendingPath)) {
|
|
1112
1926
|
try {
|
|
1113
1927
|
const data = JSON.parse(readFileSync2(spendingPath, "utf-8"));
|
|
@@ -1130,7 +1944,7 @@ Run: npx moltspay approve --chain ${chainName} --spender ${spender}`
|
|
|
1130
1944
|
*/
|
|
1131
1945
|
saveSpending() {
|
|
1132
1946
|
mkdirSync2(this.configDir, { recursive: true });
|
|
1133
|
-
const spendingPath =
|
|
1947
|
+
const spendingPath = join3(this.configDir, "spending.json");
|
|
1134
1948
|
const data = {
|
|
1135
1949
|
date: this.lastSpendingReset || (/* @__PURE__ */ new Date()).setHours(0, 0, 0, 0),
|
|
1136
1950
|
amount: this.todaySpending,
|
|
@@ -1139,7 +1953,7 @@ Run: npx moltspay approve --chain ${chainName} --spender ${spender}`
|
|
|
1139
1953
|
writeFileSync2(spendingPath, JSON.stringify(data, null, 2));
|
|
1140
1954
|
}
|
|
1141
1955
|
loadWallet() {
|
|
1142
|
-
const walletPath =
|
|
1956
|
+
const walletPath = join3(this.configDir, "wallet.json");
|
|
1143
1957
|
if (existsSync2(walletPath)) {
|
|
1144
1958
|
if (process.platform !== "win32") {
|
|
1145
1959
|
try {
|
|
@@ -1169,7 +1983,7 @@ Run: npx moltspay approve --chain ${chainName} --spender ${spender}`
|
|
|
1169
1983
|
privateKey: wallet.privateKey,
|
|
1170
1984
|
createdAt: Date.now()
|
|
1171
1985
|
};
|
|
1172
|
-
const walletPath =
|
|
1986
|
+
const walletPath = join3(configDir, "wallet.json");
|
|
1173
1987
|
writeFileSync2(walletPath, JSON.stringify(walletData, null, 2), { mode: 384 });
|
|
1174
1988
|
const config = {
|
|
1175
1989
|
chain: options.chain,
|
|
@@ -1178,7 +1992,7 @@ Run: npx moltspay approve --chain ${chainName} --spender ${spender}`
|
|
|
1178
1992
|
maxPerDay: options.maxPerDay
|
|
1179
1993
|
}
|
|
1180
1994
|
};
|
|
1181
|
-
const configPath =
|
|
1995
|
+
const configPath = join3(configDir, "config.json");
|
|
1182
1996
|
writeFileSync2(configPath, JSON.stringify(config, null, 2));
|
|
1183
1997
|
return { address: wallet.address, configDir };
|
|
1184
1998
|
}
|