@mysten-incubation/suipay-buyer 0.4.0-dev.10 → 0.4.0-dev.12
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 +8 -0
- package/dist/{chunk-RWUAPD7K.js → chunk-FWLPQH4N.js} +301 -16
- package/dist/index.d.ts +21 -12
- package/dist/index.js +292 -68
- package/dist/{native-transfer-DWs55Mse.d.ts → native-transfer-D0UoteMk.d.ts} +83 -4
- package/dist/native-transfer.d.ts +1 -1
- package/dist/native-transfer.js +3 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,48 +1,31 @@
|
|
|
1
1
|
import {
|
|
2
|
+
DEFINITE_PRE_BROADCAST_REFUSALS,
|
|
2
3
|
ERROR_CODE_HEADER,
|
|
3
4
|
NativeTransferError,
|
|
4
5
|
SuiPayError,
|
|
6
|
+
buildMcpPaymentPayload,
|
|
5
7
|
buildNativeTransferBytes,
|
|
6
8
|
createNativeTransferSigner,
|
|
7
9
|
definitionOf,
|
|
8
10
|
deriveNextAction,
|
|
9
11
|
deriveRetryable,
|
|
10
12
|
inspectNativeTransfer,
|
|
13
|
+
isDefinitePreBroadcastRefusal,
|
|
11
14
|
isErrorCode,
|
|
15
|
+
isValidatedProblemRefusal,
|
|
12
16
|
logError,
|
|
13
17
|
parseErrorPayload,
|
|
14
18
|
stricterPaymentState,
|
|
15
19
|
toErrorFields
|
|
16
|
-
} from "./chunk-
|
|
17
|
-
|
|
18
|
-
// src/mcp.ts
|
|
19
|
-
async function buildMcpPaymentPayload(paymentRequired, signer) {
|
|
20
|
-
const accept = paymentRequired.accepts.find(
|
|
21
|
-
(a) => a.scheme === "exact" && a.network.startsWith("sui:")
|
|
22
|
-
);
|
|
23
|
-
if (!accept) {
|
|
24
|
-
throw SuiPayError.of("payment.method_unsupported", "not_charged", {
|
|
25
|
-
detail: "no sui:* exact accept in PaymentRequired"
|
|
26
|
-
});
|
|
27
|
-
}
|
|
28
|
-
const signed = await signer.buildNativeTransfer(accept);
|
|
29
|
-
const payload = {
|
|
30
|
-
x402Version: 2,
|
|
31
|
-
resource: paymentRequired.resource,
|
|
32
|
-
accepted: accept,
|
|
33
|
-
payload: {
|
|
34
|
-
transaction: signed.transaction,
|
|
35
|
-
signature: signed.signature
|
|
36
|
-
}
|
|
37
|
-
};
|
|
38
|
-
return { payload, meta: { "x402/payment": payload } };
|
|
39
|
-
}
|
|
20
|
+
} from "./chunk-FWLPQH4N.js";
|
|
40
21
|
|
|
41
22
|
// ../sdk/dist/buyer/legacy-control-codes.js
|
|
42
23
|
var LEGACY_CONTROL_PLANE_CODES = {
|
|
43
24
|
CAP_EXCEEDED: "account.limit_exceeded",
|
|
44
25
|
CONFLICT: "request.conflict",
|
|
45
26
|
CROSS_ASSET_FORBIDDEN: "account.asset_unsupported",
|
|
27
|
+
DEPOSIT_CAP_EXCEEDED: "account.deposit_cap_exceeded",
|
|
28
|
+
DEPOSITS_PAUSED: "account.deposits_paused",
|
|
46
29
|
EXPIRED: "request.expired",
|
|
47
30
|
FINALIZE_MISMATCH: "account.finalize_mismatch",
|
|
48
31
|
FINALIZE_UNVERIFIED: "chain.tx_unverified",
|
|
@@ -68,6 +51,12 @@ var LEGACY_CONTROL_PLANE_CODES = {
|
|
|
68
51
|
UNVERIFIED: "chain.tx_unverified"
|
|
69
52
|
};
|
|
70
53
|
|
|
54
|
+
// ../sdk/dist/protocol/redirect.js
|
|
55
|
+
var NO_REDIRECT = { redirect: "manual" };
|
|
56
|
+
function isRedirectResponse(res) {
|
|
57
|
+
return res.type === "opaqueredirect" || res.status >= 300 && res.status < 400;
|
|
58
|
+
}
|
|
59
|
+
|
|
71
60
|
// ../sdk/dist/buyer/transport.js
|
|
72
61
|
var FORBIDDEN_SECRET_KEYS = [
|
|
73
62
|
"privateKey",
|
|
@@ -278,8 +267,18 @@ function createTransport(options) {
|
|
|
278
267
|
const response = await fetchImpl(joinUrl(options.baseUrl, path), {
|
|
279
268
|
method: init.method ?? (init.body !== void 0 ? "POST" : "GET"),
|
|
280
269
|
headers,
|
|
281
|
-
body: init.body === void 0 ? void 0 : typeof init.body === "string" ? init.body : JSON.stringify(init.body)
|
|
270
|
+
body: init.body === void 0 ? void 0 : typeof init.body === "string" ? init.body : JSON.stringify(init.body),
|
|
271
|
+
...NO_REDIRECT
|
|
282
272
|
});
|
|
273
|
+
if (isRedirectResponse(response)) {
|
|
274
|
+
return {
|
|
275
|
+
status: 0,
|
|
276
|
+
body: localErrorBody(localClientError("request.redirect_refused", "not_charged", {
|
|
277
|
+
message: "SuiPay answered with a redirect, which is refused."
|
|
278
|
+
})),
|
|
279
|
+
headers: new Headers()
|
|
280
|
+
};
|
|
281
|
+
}
|
|
283
282
|
const body = await response.json().catch(() => null);
|
|
284
283
|
return { status: response.status, body, headers: response.headers };
|
|
285
284
|
} catch {
|
|
@@ -765,23 +764,35 @@ function verifyOwnerTransaction(input) {
|
|
|
765
764
|
throw new TransactionVerificationError("target");
|
|
766
765
|
}
|
|
767
766
|
const bCall = lastCmd.MoveCall;
|
|
768
|
-
const
|
|
769
|
-
|
|
767
|
+
const limitedFn = op.kind === "create_pool" ? "create_account_limited" : "fund_account_limited";
|
|
768
|
+
const legacyFn = op.kind === "create_pool" ? "create_account" : "fund_account";
|
|
769
|
+
if (bCall.module !== "spend_account" || bCall.function !== limitedFn && bCall.function !== legacyFn) {
|
|
770
770
|
throw new TransactionVerificationError("target");
|
|
771
771
|
}
|
|
772
|
+
const useLimited = bCall.function === limitedFn;
|
|
772
773
|
const bTypeArgs = bCall.typeArguments;
|
|
773
774
|
if (bTypeArgs.length !== 1 || safeNormalizeStructTag(bTypeArgs[0]) !== normCoinType) {
|
|
774
775
|
throw new TransactionVerificationError("coinType");
|
|
775
776
|
}
|
|
776
777
|
const bArgs = bCall.arguments;
|
|
777
|
-
const bExpectedArgCount = op.kind === "create_pool" ? 1 : 2;
|
|
778
|
+
const bExpectedArgCount = useLimited ? op.kind === "create_pool" ? 2 : 3 : op.kind === "create_pool" ? 1 : 2;
|
|
778
779
|
if (bArgs.length !== bExpectedArgCount) {
|
|
779
780
|
throw new TransactionVerificationError("target");
|
|
780
781
|
}
|
|
781
|
-
if (
|
|
782
|
+
if (useLimited) {
|
|
783
|
+
const dirIdx = markInput(bArgs[0]);
|
|
784
|
+
const dirInput = data.inputs[dirIdx];
|
|
785
|
+
const dirObj = dirInput?.Object;
|
|
786
|
+
if (!dirObj?.SharedObject) {
|
|
787
|
+
throw new TransactionVerificationError("target");
|
|
788
|
+
}
|
|
789
|
+
if (op.kind === "top_up") {
|
|
790
|
+
assertPoolInput(bArgs[1], expectedPool);
|
|
791
|
+
}
|
|
792
|
+
} else if (op.kind === "top_up") {
|
|
782
793
|
assertPoolInput(bArgs[0], expectedPool);
|
|
783
794
|
}
|
|
784
|
-
const coinArg = op.kind === "create_pool" ? bArgs[0] : bArgs[1];
|
|
795
|
+
const coinArg = useLimited ? op.kind === "create_pool" ? bArgs[1] : bArgs[2] : op.kind === "create_pool" ? bArgs[0] : bArgs[1];
|
|
785
796
|
const splitCmdIdx = commands.findIndex((c) => c.$kind === "SplitCoins");
|
|
786
797
|
if (splitCmdIdx === -1) {
|
|
787
798
|
throw new TransactionVerificationError("funding");
|
|
@@ -3358,22 +3369,38 @@ function createSpendAccountChain(options) {
|
|
|
3358
3369
|
const tx = new Transaction2();
|
|
3359
3370
|
tx.setSender(input.owner);
|
|
3360
3371
|
const funding = await fundingCoin(tx, input.owner, input.coinType, BigInt(input.funding));
|
|
3361
|
-
|
|
3362
|
-
|
|
3363
|
-
|
|
3364
|
-
|
|
3365
|
-
|
|
3372
|
+
if (input.exclusionDirectoryId) {
|
|
3373
|
+
tx.moveCall({
|
|
3374
|
+
target: target("create_account_limited"),
|
|
3375
|
+
typeArguments: [input.coinType],
|
|
3376
|
+
arguments: [tx.object(input.exclusionDirectoryId), funding]
|
|
3377
|
+
});
|
|
3378
|
+
} else {
|
|
3379
|
+
tx.moveCall({
|
|
3380
|
+
target: target("create_account"),
|
|
3381
|
+
typeArguments: [input.coinType],
|
|
3382
|
+
arguments: [funding]
|
|
3383
|
+
});
|
|
3384
|
+
}
|
|
3366
3385
|
return kindBytes(tx);
|
|
3367
3386
|
},
|
|
3368
3387
|
async buildTopUpKind(input) {
|
|
3369
3388
|
const tx = new Transaction2();
|
|
3370
3389
|
tx.setSender(input.owner);
|
|
3371
3390
|
const funding = await fundingCoin(tx, input.owner, input.coinType, BigInt(input.amount));
|
|
3372
|
-
|
|
3373
|
-
|
|
3374
|
-
|
|
3375
|
-
|
|
3376
|
-
|
|
3391
|
+
if (input.exclusionDirectoryId) {
|
|
3392
|
+
tx.moveCall({
|
|
3393
|
+
target: target("fund_account_limited"),
|
|
3394
|
+
typeArguments: [input.coinType],
|
|
3395
|
+
arguments: [tx.object(input.exclusionDirectoryId), tx.object(input.poolObjectId), funding]
|
|
3396
|
+
});
|
|
3397
|
+
} else {
|
|
3398
|
+
tx.moveCall({
|
|
3399
|
+
target: target("fund_account"),
|
|
3400
|
+
typeArguments: [input.coinType],
|
|
3401
|
+
arguments: [tx.object(input.poolObjectId), funding]
|
|
3402
|
+
});
|
|
3403
|
+
}
|
|
3377
3404
|
return kindBytes(tx);
|
|
3378
3405
|
},
|
|
3379
3406
|
async buildWithdrawKind(input) {
|
|
@@ -5303,6 +5330,8 @@ function addressBalanceGasExpiration(input) {
|
|
|
5303
5330
|
// ../sdk/dist/delegated-signer/pay-gas.js
|
|
5304
5331
|
var DEFAULT_GAS_BUDGET = 10000000n;
|
|
5305
5332
|
var DEFAULT_GAS_PRICE = 1000n;
|
|
5333
|
+
var MAX_SPONSOR_GAS_BUDGET = 50000000n;
|
|
5334
|
+
var MAX_SPONSOR_GAS_PRICE = 10000n;
|
|
5306
5335
|
var X402_EXPIRATION_EPOCHS = 32n;
|
|
5307
5336
|
async function readChainBound(read) {
|
|
5308
5337
|
try {
|
|
@@ -5345,8 +5374,16 @@ function assertPayGas(data, delegate, policy = {}) {
|
|
|
5345
5374
|
if (policy.mode === "agent") {
|
|
5346
5375
|
if (!pinned)
|
|
5347
5376
|
throw new Error("agent gas requires caller-owned gas inputs");
|
|
5348
|
-
} else
|
|
5349
|
-
|
|
5377
|
+
} else {
|
|
5378
|
+
if (owner === agent) {
|
|
5379
|
+
throw new Error("sponsored transaction gas owner must not be the delegate");
|
|
5380
|
+
}
|
|
5381
|
+
if (actual.budget == null || actual.price == null) {
|
|
5382
|
+
throw new Error("sponsored transaction gas budget and price must be pinned");
|
|
5383
|
+
}
|
|
5384
|
+
if (BigInt(actual.budget) > MAX_SPONSOR_GAS_BUDGET || BigInt(actual.price) > MAX_SPONSOR_GAS_PRICE) {
|
|
5385
|
+
throw new Error("sponsored transaction gas budget or price exceeds the cap");
|
|
5386
|
+
}
|
|
5350
5387
|
}
|
|
5351
5388
|
if (pinned) {
|
|
5352
5389
|
const expectedOwner = normalizeSuiAddress6(pinned.owner ?? delegate);
|
|
@@ -6229,6 +6266,8 @@ var X402_ERROR_REASON = {
|
|
|
6229
6266
|
INSUFFICIENT_FUNDS: "insufficient_funds",
|
|
6230
6267
|
PAYER_MISMATCH: "invalid_payload",
|
|
6231
6268
|
SETTLEMENT_REJECTED: "invalid_transaction_state",
|
|
6269
|
+
SPEND_PAUSED: "unexpected_settle_error",
|
|
6270
|
+
SPEND_PAUSE_UNAVAILABLE: "unexpected_settle_error",
|
|
6232
6271
|
SETTLEMENT_MISMATCH: "unexpected_settle_error",
|
|
6233
6272
|
AMBIGUOUS: "settlement_pending",
|
|
6234
6273
|
VERSION_UNSUPPORTED: "invalid_x402_version",
|
|
@@ -7502,10 +7541,13 @@ async function fetchGatewayOfferKeys(gatewayUrl, options = {}) {
|
|
|
7502
7541
|
const targetUrl = `${normalizedBase}${SUIPAY_OFFER_KEYS_PATH}`;
|
|
7503
7542
|
let response;
|
|
7504
7543
|
try {
|
|
7505
|
-
response = await fetchImpl(targetUrl);
|
|
7544
|
+
response = await fetchImpl(targetUrl, NO_REDIRECT);
|
|
7506
7545
|
} catch (err) {
|
|
7507
7546
|
throw new OfferKeysFetchError(`failed to fetch gateway offer keys: ${err instanceof Error ? err.message : String(err)}`);
|
|
7508
7547
|
}
|
|
7548
|
+
if (isRedirectResponse(response)) {
|
|
7549
|
+
throw new OfferKeysFetchError("failed to fetch gateway offer keys: redirect refused", response.status);
|
|
7550
|
+
}
|
|
7509
7551
|
if (response.status === 404) {
|
|
7510
7552
|
throw new OfferKeysGatewayUnavailableError();
|
|
7511
7553
|
}
|
|
@@ -7605,6 +7647,29 @@ import { isValidPersonalMessageSignature as isValidPersonalMessageSignature2, ve
|
|
|
7605
7647
|
import { normalizeSuiAddress as normalizeSuiAddress9 } from "@mysten/sui/utils";
|
|
7606
7648
|
var SIGNED_REQUEST_DOMAIN = "suipay:signed-request:v1";
|
|
7607
7649
|
var BOOTSTRAP_REQUEST_DOMAIN = "suipay:bootstrap-request:v1";
|
|
7650
|
+
var SIGNED_REQUEST_DOMAIN_V2 = "suipay:signed-request:v2";
|
|
7651
|
+
var BOOTSTRAP_REQUEST_DOMAIN_V2 = "suipay:bootstrap-request:v2";
|
|
7652
|
+
function canonicalOrigin(urlOrOrigin) {
|
|
7653
|
+
if (typeof urlOrOrigin !== "string" || urlOrOrigin.trim() === "") {
|
|
7654
|
+
throw new Error("origin must be a non-empty http(s) URL");
|
|
7655
|
+
}
|
|
7656
|
+
let url;
|
|
7657
|
+
try {
|
|
7658
|
+
url = new URL(urlOrOrigin.trim());
|
|
7659
|
+
} catch {
|
|
7660
|
+
throw new Error("origin must be an absolute http(s) URL");
|
|
7661
|
+
}
|
|
7662
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
|
7663
|
+
throw new Error("origin must use http or https");
|
|
7664
|
+
}
|
|
7665
|
+
if (url.username !== "" || url.password !== "") {
|
|
7666
|
+
throw new Error("origin must not carry userinfo");
|
|
7667
|
+
}
|
|
7668
|
+
if (url.hostname === "" || url.origin === "null") {
|
|
7669
|
+
throw new Error("origin must name a host");
|
|
7670
|
+
}
|
|
7671
|
+
return url.origin;
|
|
7672
|
+
}
|
|
7608
7673
|
var SIGNED_REQUEST_MAX_AGE_MS = 3e5;
|
|
7609
7674
|
var SIGNED_REQUEST_MAX_FUTURE_SKEW_MS = 3e4;
|
|
7610
7675
|
var SIGNED_REQUEST_NONCE_TTL_MS = SIGNED_REQUEST_MAX_AGE_MS + 2 * SIGNED_REQUEST_MAX_FUTURE_SKEW_MS;
|
|
@@ -7629,6 +7694,61 @@ function hexToBytes32(hex) {
|
|
|
7629
7694
|
}
|
|
7630
7695
|
return Uint8Array.from(Buffer.from(h, "hex"));
|
|
7631
7696
|
}
|
|
7697
|
+
var utf8VecBytes = (s) => bcs6.vector(bcs6.u8()).serialize([...Buffer.from(s, "utf8")]).toBytes();
|
|
7698
|
+
var addressBytes = (a) => bcs6.Address.serialize(normalizeSuiAddress9(a)).toBytes();
|
|
7699
|
+
function assertCanonicalOrigin(origin) {
|
|
7700
|
+
if (typeof origin !== "string" || canonicalOrigin(origin) !== origin) {
|
|
7701
|
+
throw new Error("origin must be a canonical http(s) origin");
|
|
7702
|
+
}
|
|
7703
|
+
return origin;
|
|
7704
|
+
}
|
|
7705
|
+
function encodeSignedRequestV2(payload) {
|
|
7706
|
+
if (payload.domain !== SIGNED_REQUEST_DOMAIN_V2) {
|
|
7707
|
+
throw new Error(`domain must be ${SIGNED_REQUEST_DOMAIN_V2}`);
|
|
7708
|
+
}
|
|
7709
|
+
const origin = assertCanonicalOrigin(payload.origin);
|
|
7710
|
+
const parts = [
|
|
7711
|
+
utf8VecBytes(payload.domain),
|
|
7712
|
+
utf8VecBytes(payload.network),
|
|
7713
|
+
addressBytes(payload.packageId),
|
|
7714
|
+
utf8VecBytes(origin),
|
|
7715
|
+
addressBytes(payload.grantObjectId),
|
|
7716
|
+
addressBytes(payload.delegate),
|
|
7717
|
+
utf8VecBytes(payload.method),
|
|
7718
|
+
utf8VecBytes(payload.path),
|
|
7719
|
+
utf8VecBytes(payload.query),
|
|
7720
|
+
bcs6.vector(bcs6.u8()).serialize([...hexToBytes32(payload.bodyHash)]).toBytes(),
|
|
7721
|
+
bcs6.u64().serialize(BigInt(payload.timestampMs)).toBytes(),
|
|
7722
|
+
utf8VecBytes(payload.nonce)
|
|
7723
|
+
];
|
|
7724
|
+
return Buffer.concat(parts.map((p) => Buffer.from(p)));
|
|
7725
|
+
}
|
|
7726
|
+
function encodeBootstrapRequestV2(payload) {
|
|
7727
|
+
if (payload.domain !== BOOTSTRAP_REQUEST_DOMAIN_V2) {
|
|
7728
|
+
throw new Error(`domain must be ${BOOTSTRAP_REQUEST_DOMAIN_V2}`);
|
|
7729
|
+
}
|
|
7730
|
+
const origin = assertCanonicalOrigin(payload.origin);
|
|
7731
|
+
const parts = [
|
|
7732
|
+
utf8VecBytes(payload.domain),
|
|
7733
|
+
utf8VecBytes(payload.network),
|
|
7734
|
+
addressBytes(payload.packageId),
|
|
7735
|
+
utf8VecBytes(origin),
|
|
7736
|
+
addressBytes(payload.delegate),
|
|
7737
|
+
utf8VecBytes(payload.method),
|
|
7738
|
+
utf8VecBytes(payload.path),
|
|
7739
|
+
utf8VecBytes(payload.query),
|
|
7740
|
+
bcs6.vector(bcs6.u8()).serialize([...hexToBytes32(payload.bodyHash)]).toBytes(),
|
|
7741
|
+
bcs6.u64().serialize(BigInt(payload.timestampMs)).toBytes(),
|
|
7742
|
+
utf8VecBytes(payload.nonce)
|
|
7743
|
+
];
|
|
7744
|
+
return Buffer.concat(parts.map((p) => Buffer.from(p)));
|
|
7745
|
+
}
|
|
7746
|
+
function encodeAnySignedRequest(payload) {
|
|
7747
|
+
return payload.domain === SIGNED_REQUEST_DOMAIN_V2 ? encodeSignedRequestV2(payload) : encodeSignedRequest(payload);
|
|
7748
|
+
}
|
|
7749
|
+
function encodeAnyBootstrapRequest(payload) {
|
|
7750
|
+
return payload.domain === BOOTSTRAP_REQUEST_DOMAIN_V2 ? encodeBootstrapRequestV2(payload) : encodeBootstrapRequest(payload);
|
|
7751
|
+
}
|
|
7632
7752
|
function encodeBootstrapRequest(payload) {
|
|
7633
7753
|
if (payload.domain !== BOOTSTRAP_REQUEST_DOMAIN) {
|
|
7634
7754
|
throw new Error(`domain must be ${BOOTSTRAP_REQUEST_DOMAIN}`);
|
|
@@ -7761,10 +7881,10 @@ function validateNonceFormat(nonce) {
|
|
|
7761
7881
|
return bytes >= SIGNED_REQUEST_NONCE_MIN_ENTROPY_BYTES;
|
|
7762
7882
|
}
|
|
7763
7883
|
async function signSignedRequest(input) {
|
|
7764
|
-
return input.signPersonalMessage(
|
|
7884
|
+
return input.signPersonalMessage(encodeAnySignedRequest(input.payload));
|
|
7765
7885
|
}
|
|
7766
7886
|
async function signBootstrapRequest(input) {
|
|
7767
|
-
return input.signPersonalMessage(
|
|
7887
|
+
return input.signPersonalMessage(encodeAnyBootstrapRequest(input.payload));
|
|
7768
7888
|
}
|
|
7769
7889
|
|
|
7770
7890
|
// ../sdk/dist/agent-sdk/signed-headers.js
|
|
@@ -7790,6 +7910,17 @@ function splitPathAndQuery(target) {
|
|
|
7790
7910
|
return { path: noFragment.slice(0, q), query: noFragment.slice(q + 1) };
|
|
7791
7911
|
}
|
|
7792
7912
|
}
|
|
7913
|
+
function assertTargetOrigin(url, signedOrigin) {
|
|
7914
|
+
let target;
|
|
7915
|
+
try {
|
|
7916
|
+
target = new URL(url);
|
|
7917
|
+
} catch {
|
|
7918
|
+
return;
|
|
7919
|
+
}
|
|
7920
|
+
if (canonicalOrigin(target.href) !== canonicalOrigin(signedOrigin)) {
|
|
7921
|
+
throw new Error("request URL origin does not match the signed origin");
|
|
7922
|
+
}
|
|
7923
|
+
}
|
|
7793
7924
|
function buildSignedRequestPayload(context, request, fields) {
|
|
7794
7925
|
if (!validateNonceFormat(fields.nonce)) {
|
|
7795
7926
|
throw new Error("nonce must be base64url with at least 128 bits of entropy");
|
|
@@ -7798,9 +7929,10 @@ function buildSignedRequestPayload(context, request, fields) {
|
|
|
7798
7929
|
throw new Error("timestampMs must be a positive integer (epoch ms)");
|
|
7799
7930
|
}
|
|
7800
7931
|
return {
|
|
7801
|
-
domain:
|
|
7932
|
+
domain: SIGNED_REQUEST_DOMAIN_V2,
|
|
7802
7933
|
network: context.network,
|
|
7803
7934
|
packageId: context.packageId,
|
|
7935
|
+
origin: canonicalOrigin(context.origin),
|
|
7804
7936
|
grantObjectId: context.grantObjectId,
|
|
7805
7937
|
delegate: context.delegateAddress,
|
|
7806
7938
|
method: request.method.toUpperCase(),
|
|
@@ -7837,6 +7969,7 @@ async function signSessionRequest(input) {
|
|
|
7837
7969
|
};
|
|
7838
7970
|
}
|
|
7839
7971
|
async function signSessionRequestForUrl(input) {
|
|
7972
|
+
assertTargetOrigin(input.url, input.context.origin);
|
|
7840
7973
|
const { path, query } = splitPathAndQuery(input.url);
|
|
7841
7974
|
return signSessionRequest({
|
|
7842
7975
|
context: input.context,
|
|
@@ -7861,9 +7994,10 @@ function buildBootstrapRequestPayload(context, request, fields) {
|
|
|
7861
7994
|
throw new Error("timestampMs must be a positive integer (epoch ms)");
|
|
7862
7995
|
}
|
|
7863
7996
|
return {
|
|
7864
|
-
domain:
|
|
7997
|
+
domain: BOOTSTRAP_REQUEST_DOMAIN_V2,
|
|
7865
7998
|
network: context.network,
|
|
7866
7999
|
packageId: context.packageId,
|
|
8000
|
+
origin: canonicalOrigin(context.origin),
|
|
7867
8001
|
delegate: context.delegateAddress,
|
|
7868
8002
|
method: request.method.toUpperCase(),
|
|
7869
8003
|
path: canonicalizePath(request.path),
|
|
@@ -7899,6 +8033,7 @@ async function signBootstrapSessionRequest(input) {
|
|
|
7899
8033
|
};
|
|
7900
8034
|
}
|
|
7901
8035
|
async function signBootstrapSessionRequestForUrl(input) {
|
|
8036
|
+
assertTargetOrigin(input.url, input.context.origin);
|
|
7902
8037
|
const { path, query } = splitPathAndQuery(input.url);
|
|
7903
8038
|
return signBootstrapSessionRequest({
|
|
7904
8039
|
context: input.context,
|
|
@@ -7917,6 +8052,9 @@ async function signBootstrapSessionRequestForUrl(input) {
|
|
|
7917
8052
|
function classifyReadFailure(status) {
|
|
7918
8053
|
return status >= 500 ? "unavailable" : "rejected";
|
|
7919
8054
|
}
|
|
8055
|
+
function redirectRefused() {
|
|
8056
|
+
return { ok: false, status: 0, error: "unavailable", code: "request.redirect_refused" };
|
|
8057
|
+
}
|
|
7920
8058
|
function joinUrl2(gatewayUrl, basePath, suffix) {
|
|
7921
8059
|
const origin = gatewayUrl.replace(/\/$/, "");
|
|
7922
8060
|
let base = basePath.replace(/\/$/, "");
|
|
@@ -7951,7 +8089,7 @@ function createReader(options) {
|
|
|
7951
8089
|
let signed;
|
|
7952
8090
|
try {
|
|
7953
8091
|
signed = await signSessionRequestForUrl({
|
|
7954
|
-
context: options.context,
|
|
8092
|
+
context: { ...options.context, origin: canonicalOrigin(options.gatewayUrl) },
|
|
7955
8093
|
method: "GET",
|
|
7956
8094
|
url,
|
|
7957
8095
|
signPersonalMessage: options.signPersonalMessage,
|
|
@@ -7964,11 +8102,14 @@ function createReader(options) {
|
|
|
7964
8102
|
try {
|
|
7965
8103
|
res = await fetchImpl(url, {
|
|
7966
8104
|
method: "GET",
|
|
7967
|
-
headers: { ...signed.headers, accept: "application/json" }
|
|
8105
|
+
headers: { ...signed.headers, accept: "application/json" },
|
|
8106
|
+
...NO_REDIRECT
|
|
7968
8107
|
});
|
|
7969
8108
|
} catch {
|
|
7970
8109
|
return { ok: false, status: 0, error: "unavailable" };
|
|
7971
8110
|
}
|
|
8111
|
+
if (isRedirectResponse(res))
|
|
8112
|
+
return redirectRefused();
|
|
7972
8113
|
const body = await readJsonBody(res);
|
|
7973
8114
|
if (res.status >= 200 && res.status < 300) {
|
|
7974
8115
|
return { ok: true, status: res.status, data: body };
|
|
@@ -8050,6 +8191,12 @@ async function readPublicSessionState(getObjectJson, grantObjectId) {
|
|
|
8050
8191
|
revoked: asBool(g.revoked)
|
|
8051
8192
|
};
|
|
8052
8193
|
}
|
|
8194
|
+
function isRevokedBootstrap(data) {
|
|
8195
|
+
if (!data || typeof data !== "object")
|
|
8196
|
+
return false;
|
|
8197
|
+
const dto = data;
|
|
8198
|
+
return Array.isArray(dto.grants) && dto.grants.length === 0 && dto.grantStatus === "revoked";
|
|
8199
|
+
}
|
|
8053
8200
|
async function bootstrapPayerSessions(options) {
|
|
8054
8201
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
8055
8202
|
const basePath = options.basePath ?? "/v1/delegate";
|
|
@@ -8057,7 +8204,7 @@ async function bootstrapPayerSessions(options) {
|
|
|
8057
8204
|
let signed;
|
|
8058
8205
|
try {
|
|
8059
8206
|
signed = await signBootstrapSessionRequestForUrl({
|
|
8060
|
-
context: options.context,
|
|
8207
|
+
context: { ...options.context, origin: canonicalOrigin(options.gatewayUrl) },
|
|
8061
8208
|
method: "GET",
|
|
8062
8209
|
url,
|
|
8063
8210
|
signPersonalMessage: options.signPersonalMessage,
|
|
@@ -8070,11 +8217,14 @@ async function bootstrapPayerSessions(options) {
|
|
|
8070
8217
|
try {
|
|
8071
8218
|
res = await fetchImpl(url, {
|
|
8072
8219
|
method: "GET",
|
|
8073
|
-
headers: { ...signed.headers, accept: "application/json" }
|
|
8220
|
+
headers: { ...signed.headers, accept: "application/json" },
|
|
8221
|
+
...NO_REDIRECT
|
|
8074
8222
|
});
|
|
8075
8223
|
} catch {
|
|
8076
8224
|
return { ok: false, status: 0, error: "unavailable" };
|
|
8077
8225
|
}
|
|
8226
|
+
if (isRedirectResponse(res))
|
|
8227
|
+
return redirectRefused();
|
|
8078
8228
|
const body = await readJsonBody(res);
|
|
8079
8229
|
if (res.status >= 200 && res.status < 300) {
|
|
8080
8230
|
return { ok: true, status: res.status, data: body };
|
|
@@ -8371,14 +8521,33 @@ function gatewayFailure(answer, local, extras) {
|
|
|
8371
8521
|
txDigest: error.txDigest ?? extras.txDigest
|
|
8372
8522
|
});
|
|
8373
8523
|
}
|
|
8374
|
-
var
|
|
8375
|
-
|
|
8376
|
-
|
|
8377
|
-
|
|
8378
|
-
|
|
8379
|
-
|
|
8524
|
+
var PRE_SIGN_SPONSOR_REFUSALS = /* @__PURE__ */ new Set([
|
|
8525
|
+
...DEFINITE_PRE_BROADCAST_REFUSALS,
|
|
8526
|
+
"auth.spend_daily_limit_reached",
|
|
8527
|
+
// Unreadable pause / other pre-sign unavailability: safe on challenge and
|
|
8528
|
+
// sponsor create only. Execute keeps this ambiguous (see DEFINITE set).
|
|
8529
|
+
"service.unavailable",
|
|
8530
|
+
"limit.rate_limited",
|
|
8531
|
+
"limit.gas_quota_exceeded",
|
|
8532
|
+
"sponsor.would_abort",
|
|
8533
|
+
"sponsor.kind_rejected",
|
|
8534
|
+
"sponsor.target_not_allowed",
|
|
8535
|
+
"account.grant_revoked",
|
|
8536
|
+
"account.grant_paused",
|
|
8537
|
+
"account.grant_expired",
|
|
8538
|
+
"account.grant_not_active"
|
|
8539
|
+
]);
|
|
8540
|
+
function isPreSignSponsorRefusal(parsed) {
|
|
8541
|
+
return isValidatedProblemRefusal(parsed, PRE_SIGN_SPONSOR_REFUSALS);
|
|
8542
|
+
}
|
|
8543
|
+
var BYO_SPONSOR_EXECUTE_PRE_BROADCAST_REFUSALS = /* @__PURE__ */ new Set([
|
|
8544
|
+
"auth.spend_daily_limit_reached",
|
|
8545
|
+
"sponsor.sponsorship_not_found",
|
|
8546
|
+
"sponsor.unavailable"
|
|
8547
|
+
]);
|
|
8548
|
+
async function sponsorProblemRefusal(response, paymentId, admit) {
|
|
8380
8549
|
const parsed = parseErrorPayload(await readGatewayAnswer(response));
|
|
8381
|
-
if (parsed
|
|
8550
|
+
if (!admit(parsed)) {
|
|
8382
8551
|
return null;
|
|
8383
8552
|
}
|
|
8384
8553
|
const detail = parsed.detail?.trim();
|
|
@@ -9036,6 +9205,11 @@ async function payDelegatedSpendAccount(args) {
|
|
|
9036
9205
|
detail: "the gateway could not be reached; nothing was signed"
|
|
9037
9206
|
});
|
|
9038
9207
|
}
|
|
9208
|
+
if (isRedirectResponse(first)) {
|
|
9209
|
+
return resultError("request.redirect_refused", "not_charged", {
|
|
9210
|
+
detail: "the gateway answered with a redirect; nothing was signed"
|
|
9211
|
+
});
|
|
9212
|
+
}
|
|
9039
9213
|
if (first.status !== 402) {
|
|
9040
9214
|
let body2;
|
|
9041
9215
|
try {
|
|
@@ -9475,9 +9649,18 @@ async function payDelegatedSpendAccount(args) {
|
|
|
9475
9649
|
grantId: resolved.grantObjectId,
|
|
9476
9650
|
network: session.network,
|
|
9477
9651
|
packageId: session.packageId
|
|
9478
|
-
})
|
|
9652
|
+
}),
|
|
9653
|
+
...NO_REDIRECT
|
|
9479
9654
|
});
|
|
9655
|
+
if (isRedirectResponse(challengeRes)) {
|
|
9656
|
+
return abortBeforeSign("SPONSOR_UNAVAILABLE", PUBLIC_DETAIL.SPONSOR_UNAVAILABLE);
|
|
9657
|
+
}
|
|
9480
9658
|
if (!challengeRes.ok) {
|
|
9659
|
+
const refused = await sponsorProblemRefusal(challengeRes, paymentId, isPreSignSponsorRefusal);
|
|
9660
|
+
if (refused) {
|
|
9661
|
+
await releaseReservation(ledger, ownedPaymentId, log);
|
|
9662
|
+
return refused;
|
|
9663
|
+
}
|
|
9481
9664
|
return abortBeforeSign("SPONSOR_UNAVAILABLE", PUBLIC_DETAIL.SPONSOR_UNAVAILABLE);
|
|
9482
9665
|
}
|
|
9483
9666
|
const body2 = await challengeRes.json();
|
|
@@ -9545,10 +9728,14 @@ async function payDelegatedSpendAccount(args) {
|
|
|
9545
9728
|
packageId: challenge.packageId,
|
|
9546
9729
|
requestId: paymentId
|
|
9547
9730
|
}
|
|
9548
|
-
})
|
|
9731
|
+
}),
|
|
9732
|
+
...NO_REDIRECT
|
|
9549
9733
|
});
|
|
9734
|
+
if (isRedirectResponse(createRes)) {
|
|
9735
|
+
return abortBeforeSign("SPONSOR_UNAVAILABLE", PUBLIC_DETAIL.SPONSOR_UNAVAILABLE);
|
|
9736
|
+
}
|
|
9550
9737
|
if (!createRes.ok) {
|
|
9551
|
-
const refused = await
|
|
9738
|
+
const refused = await sponsorProblemRefusal(createRes, paymentId, isPreSignSponsorRefusal);
|
|
9552
9739
|
if (refused) {
|
|
9553
9740
|
await releaseReservation(ledger, ownedPaymentId, log);
|
|
9554
9741
|
return refused;
|
|
@@ -9642,10 +9829,11 @@ async function payDelegatedSpendAccount(args) {
|
|
|
9642
9829
|
signature,
|
|
9643
9830
|
executeToken: sponsoredExecuteToken,
|
|
9644
9831
|
...sponsoredBackendToken ? { sponsorBackendToken: sponsoredBackendToken } : {}
|
|
9645
|
-
})
|
|
9832
|
+
}),
|
|
9833
|
+
...NO_REDIRECT
|
|
9646
9834
|
});
|
|
9647
9835
|
if (!execRes.ok) {
|
|
9648
|
-
const refused = await
|
|
9836
|
+
const refused = isRedirectResponse(execRes) ? null : await sponsorProblemRefusal(execRes, paymentId, (parsed) => isDefinitePreBroadcastRefusal(parsed) || isValidatedProblemRefusal(parsed, BYO_SPONSOR_EXECUTE_PRE_BROADCAST_REFUSALS));
|
|
9649
9837
|
if (refused) {
|
|
9650
9838
|
await releaseReservation(ledger, ownedPaymentId, log);
|
|
9651
9839
|
return refused;
|
|
@@ -9754,6 +9942,8 @@ async function payDelegatedSpendAccount(args) {
|
|
|
9754
9942
|
let second;
|
|
9755
9943
|
try {
|
|
9756
9944
|
second = await fetchImpl(resourceUrl, paidRequestInit(request, { [MPP_CREDENTIAL_HEADER]: proof }));
|
|
9945
|
+
if (isRedirectResponse(second))
|
|
9946
|
+
throw new Error("proof presentation refused a redirect");
|
|
9757
9947
|
} catch (err) {
|
|
9758
9948
|
logInternal(log, { code: "client.gateway_unreachable", msg: "proof presentation failed" }, err);
|
|
9759
9949
|
return completeAttempt(ledger, paymentId, ambiguous("PROOF_PRESENTATION_FAILED", PUBLIC_DETAIL.PROOF_PRESENTATION_FAILED, {
|
|
@@ -9935,6 +10125,9 @@ async function presentX402Credential(ctx, header) {
|
|
|
9935
10125
|
let response;
|
|
9936
10126
|
try {
|
|
9937
10127
|
response = await ctx.fetchImpl(ctx.resourceUrl, paidRequestInit(ctx.request, { [X402_PAYMENT_HEADER]: header }));
|
|
10128
|
+
if (isRedirectResponse(response)) {
|
|
10129
|
+
throw new Error("x402 credential presentation refused a redirect");
|
|
10130
|
+
}
|
|
9938
10131
|
} catch (err) {
|
|
9939
10132
|
logInternal(ctx.deps.log, { code: "client.gateway_unreachable", msg: "x402 credential presentation failed" }, err);
|
|
9940
10133
|
return { kind: "unresolved", txDigest };
|
|
@@ -9961,7 +10154,8 @@ async function presentX402Credential(ctx, header) {
|
|
|
9961
10154
|
const settledReceipt = receipt && receipt.challengeId === ctx.offer.challengeId ? receipt : null;
|
|
9962
10155
|
const pending = decoded !== null && isX402Failure(decoded) && decoded.errorReason === "settlement_pending";
|
|
9963
10156
|
const answer = await readGatewayAnswer(response);
|
|
9964
|
-
const
|
|
10157
|
+
const parsed = parseErrorPayload(answer);
|
|
10158
|
+
const stated = parsed?.paymentState;
|
|
9965
10159
|
if (settledReceipt || pending || stated === "charged" || stated === "unknown") {
|
|
9966
10160
|
return {
|
|
9967
10161
|
kind: "undelivered",
|
|
@@ -9970,6 +10164,12 @@ async function presentX402Credential(ctx, header) {
|
|
|
9970
10164
|
txDigest: settledReceipt?.txDigest ?? txDigest
|
|
9971
10165
|
};
|
|
9972
10166
|
}
|
|
10167
|
+
if (parsed?.source === "problem" && (parsed.code === "service.halted" || parsed.code === "service.unavailable") && answer.body.paymentState === "not_charged" && decoded && isX402Failure(decoded) && decoded.errorReason === "unexpected_settle_error") {
|
|
10168
|
+
txDigest = parsed.txDigest ?? txDigest;
|
|
10169
|
+
if (attempt === 1 && !txDigest)
|
|
10170
|
+
return { kind: "refused", answer };
|
|
10171
|
+
return { kind: "unresolved", txDigest };
|
|
10172
|
+
}
|
|
9973
10173
|
if (attempt < attempts)
|
|
9974
10174
|
await sleep(X402_PRESENT_DELAY_MS);
|
|
9975
10175
|
}
|
|
@@ -10745,7 +10945,8 @@ async function fetchGatewayDeployment(options) {
|
|
|
10745
10945
|
try {
|
|
10746
10946
|
res = await fetchImpl(`${origin}${base}/deployment`, {
|
|
10747
10947
|
method: "GET",
|
|
10748
|
-
headers: { accept: "application/json" }
|
|
10948
|
+
headers: { accept: "application/json" },
|
|
10949
|
+
...NO_REDIRECT
|
|
10749
10950
|
});
|
|
10750
10951
|
} catch {
|
|
10751
10952
|
return {
|
|
@@ -10753,6 +10954,12 @@ async function fetchGatewayDeployment(options) {
|
|
|
10753
10954
|
error: manifestError(MANIFEST_ERROR_CODES.MALFORMED_MANIFEST, "gateway deployment identity could not be reached", "client.gateway_unreachable")
|
|
10754
10955
|
};
|
|
10755
10956
|
}
|
|
10957
|
+
if (isRedirectResponse(res)) {
|
|
10958
|
+
return {
|
|
10959
|
+
ok: false,
|
|
10960
|
+
error: manifestError(MANIFEST_ERROR_CODES.MALFORMED_MANIFEST, "gateway deployment identity refused a redirect", "request.redirect_refused")
|
|
10961
|
+
};
|
|
10962
|
+
}
|
|
10756
10963
|
if (res.status < 200 || res.status >= 300) {
|
|
10757
10964
|
return {
|
|
10758
10965
|
ok: false,
|
|
@@ -10886,6 +11093,15 @@ async function resolvePayerSession(options) {
|
|
|
10886
11093
|
});
|
|
10887
11094
|
if (whole.ok)
|
|
10888
11095
|
return { ok: true, value: { ...whole.value, deployment } };
|
|
11096
|
+
if (whole.error.reason === MANIFEST_ERROR_CODES.NO_GRANTS) {
|
|
11097
|
+
if (isRevokedBootstrap(bootstrap.data)) {
|
|
11098
|
+
return {
|
|
11099
|
+
ok: false,
|
|
11100
|
+
error: manifestError(MANIFEST_ERROR_CODES.NO_GRANTS, "this delegate key has been revoked", "account.grant_revoked")
|
|
11101
|
+
};
|
|
11102
|
+
}
|
|
11103
|
+
return whole;
|
|
11104
|
+
}
|
|
10889
11105
|
const data = bootstrap.data;
|
|
10890
11106
|
const rawGrants = Array.isArray(data.grants) ? data.grants : [];
|
|
10891
11107
|
const usable = [];
|
|
@@ -10918,7 +11134,9 @@ async function resolvePayerSession(options) {
|
|
|
10918
11134
|
if (usable.length === 0) {
|
|
10919
11135
|
const scoped = blocked.find((b) => b.error.reason === MANIFEST_ERROR_CODES.MISSING_POLICY_BINDING);
|
|
10920
11136
|
const pick2 = scoped ?? blocked[0];
|
|
10921
|
-
|
|
11137
|
+
if (pick2)
|
|
11138
|
+
return { ok: false, error: explainBlockedGrant(pick2.raw, pick2.error) };
|
|
11139
|
+
return whole;
|
|
10922
11140
|
}
|
|
10923
11141
|
const resolved = manifestToSession({
|
|
10924
11142
|
manifest: { ...data, grants: usable },
|
|
@@ -10982,10 +11200,16 @@ async function verifyGrantOnChain(input) {
|
|
|
10982
11200
|
return notVerified(`grant ${input.grantObjectId} draws on a different pool than the one resolved`);
|
|
10983
11201
|
}
|
|
10984
11202
|
if (state.revoked === true) {
|
|
10985
|
-
return
|
|
11203
|
+
return {
|
|
11204
|
+
ok: false,
|
|
11205
|
+
error: manifestError(MANIFEST_ERROR_CODES.GRANT_NOT_VERIFIED, `grant ${input.grantObjectId} is revoked on chain`, "account.grant_revoked")
|
|
11206
|
+
};
|
|
10986
11207
|
}
|
|
10987
11208
|
if (state.paused === true) {
|
|
10988
|
-
return
|
|
11209
|
+
return {
|
|
11210
|
+
ok: false,
|
|
11211
|
+
error: manifestError(MANIFEST_ERROR_CODES.GRANT_NOT_VERIFIED, `grant ${input.grantObjectId} is paused on chain`, "account.grant_paused")
|
|
11212
|
+
};
|
|
10989
11213
|
}
|
|
10990
11214
|
return { ok: true, value: null };
|
|
10991
11215
|
}
|