@agentbadge/circle-payments 0.1.20 → 0.1.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/buyer/accepts.js +8 -0
- package/dist/buyer/client.d.ts +14 -0
- package/dist/buyer/client.js +53 -21
- package/dist/buyer/counterparty.d.ts +27 -0
- package/dist/buyer/counterparty.js +35 -0
- package/dist/cli/pay.js +59 -5
- package/dist/counterparty/fingerprint.d.ts +3 -0
- package/dist/counterparty/fingerprint.js +43 -0
- package/dist/counterparty/index.d.ts +5 -0
- package/dist/counterparty/index.js +5 -0
- package/dist/counterparty/policy.d.ts +2 -0
- package/dist/counterparty/policy.js +50 -0
- package/dist/counterparty/sanitize-url.d.ts +2 -0
- package/dist/counterparty/sanitize-url.js +54 -0
- package/dist/counterparty/terms.d.ts +17 -0
- package/dist/counterparty/terms.js +134 -0
- package/dist/counterparty/types.d.ts +89 -0
- package/dist/counterparty/types.js +1 -0
- package/dist/counterparty/vet402-client.d.ts +48 -0
- package/dist/counterparty/vet402-client.js +337 -0
- package/dist/gateway/deposit.d.ts +9 -0
- package/dist/gateway/deposit.js +33 -6
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/middleware.js +10 -2
- package/package.json +1 -1
package/dist/buyer/accepts.js
CHANGED
|
@@ -99,6 +99,14 @@ function checkEntry(e, caps, allowedNetworks, allowedSchemes, capAtomic) {
|
|
|
99
99
|
reason: `amount ${JSON.stringify(e.amount)} is not an atomic integer string`,
|
|
100
100
|
};
|
|
101
101
|
}
|
|
102
|
+
if (amount <= 0n) {
|
|
103
|
+
return {
|
|
104
|
+
ok: false,
|
|
105
|
+
field: "amount",
|
|
106
|
+
value: e.amount,
|
|
107
|
+
reason: `amount ${e.amount} is not positive — refusing zero-amount charge`,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
102
110
|
if (amount > capAtomic) {
|
|
103
111
|
return {
|
|
104
112
|
ok: false,
|
package/dist/buyer/client.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type PaymentCaps } from "./caps.js";
|
|
2
2
|
import type { BeforePaymentFn } from "./guard.js";
|
|
3
|
+
import { type CounterpartyGateOptions } from "./counterparty.js";
|
|
3
4
|
import { type SpendTracker } from "./session.js";
|
|
4
5
|
import { type DepositResult } from "../gateway/deposit.js";
|
|
5
6
|
export interface BuyerSigner {
|
|
@@ -19,6 +20,15 @@ export interface BuyerSigner {
|
|
|
19
20
|
signMessage?: (args: {
|
|
20
21
|
message: string;
|
|
21
22
|
}) => Promise<`0x${string}`>;
|
|
23
|
+
readContract?: (args: {
|
|
24
|
+
address: `0x${string}`;
|
|
25
|
+
abi: unknown;
|
|
26
|
+
functionName: string;
|
|
27
|
+
args: readonly unknown[];
|
|
28
|
+
}) => Promise<unknown>;
|
|
29
|
+
waitForTransactionReceipt?: (args: {
|
|
30
|
+
hash: `0x${string}`;
|
|
31
|
+
}) => Promise<unknown>;
|
|
22
32
|
}
|
|
23
33
|
export declare function viemSigner(client: {
|
|
24
34
|
account?: {
|
|
@@ -27,6 +37,8 @@ export declare function viemSigner(client: {
|
|
|
27
37
|
signTypedData?: BuyerSigner["signTypedData"];
|
|
28
38
|
writeContract?: BuyerSigner["writeContract"];
|
|
29
39
|
signMessage?: BuyerSigner["signMessage"];
|
|
40
|
+
readContract?: BuyerSigner["readContract"];
|
|
41
|
+
waitForTransactionReceipt?: BuyerSigner["waitForTransactionReceipt"];
|
|
30
42
|
}): BuyerSigner;
|
|
31
43
|
export declare class PaymentRefusedError extends Error {
|
|
32
44
|
readonly field: string;
|
|
@@ -37,6 +49,7 @@ export interface GatewayFundingOptions {
|
|
|
37
49
|
autoDepositUsd?: string;
|
|
38
50
|
minDepositUsd?: string;
|
|
39
51
|
apiUrl?: string;
|
|
52
|
+
creditTimeoutSec?: number;
|
|
40
53
|
}
|
|
41
54
|
export interface PayingClientOptions {
|
|
42
55
|
caps: PaymentCaps;
|
|
@@ -51,6 +64,7 @@ export interface PayingClientOptions {
|
|
|
51
64
|
gateway?: GatewayFundingOptions;
|
|
52
65
|
beforePayment?: BeforePaymentFn;
|
|
53
66
|
checkAllOffers?: boolean;
|
|
67
|
+
counterparty?: CounterpartyGateOptions;
|
|
54
68
|
}
|
|
55
69
|
export interface PayingClient {
|
|
56
70
|
request(url: string, init?: RequestInit): Promise<Response>;
|
package/dist/buyer/client.js
CHANGED
|
@@ -2,8 +2,10 @@ import { BatchEvmScheme } from "@circle-fin/x402-batching/client";
|
|
|
2
2
|
import { getChain } from "../chains.js";
|
|
3
3
|
import { decode402 } from "../identity/verify-passport.js";
|
|
4
4
|
import { signPayerChallenge } from "../payer-bind.js";
|
|
5
|
-
import { assertCaps, PaymentNotAcceptedError, } from "./caps.js";
|
|
6
|
-
import { validateAccepts } from "./accepts.js";
|
|
5
|
+
import { assertCaps, PaymentNotAcceptedError, usdToAtomic, } from "./caps.js";
|
|
6
|
+
import { isGatewayBatch, validateAccepts, } from "./accepts.js";
|
|
7
|
+
import { applyCounterpartyGate, } from "./counterparty.js";
|
|
8
|
+
import { createCounterpartyPolicy } from "../counterparty/policy.js";
|
|
7
9
|
import { createSpendTracker } from "./session.js";
|
|
8
10
|
import { depositToGateway, gatewayBalance } from "../gateway/deposit.js";
|
|
9
11
|
export function viemSigner(client) {
|
|
@@ -17,6 +19,8 @@ export function viemSigner(client) {
|
|
|
17
19
|
signTypedData: client.signTypedData?.bind(client),
|
|
18
20
|
writeContract: client.writeContract?.bind(client),
|
|
19
21
|
signMessage: client.signMessage?.bind(client),
|
|
22
|
+
readContract: client.readContract?.bind(client),
|
|
23
|
+
waitForTransactionReceipt: client.waitForTransactionReceipt?.bind(client),
|
|
20
24
|
};
|
|
21
25
|
}
|
|
22
26
|
export class PaymentRefusedError extends Error {
|
|
@@ -126,25 +130,31 @@ async function broadcastTransferAuth(signer, req, signature, authorization) {
|
|
|
126
130
|
],
|
|
127
131
|
});
|
|
128
132
|
}
|
|
133
|
+
async function signGatewayBatch(signer, req) {
|
|
134
|
+
if (!signer.signTypedData) {
|
|
135
|
+
throw new PaymentRefusedError("signer", undefined, "signer lacks signTypedData — cannot sign gateway-batch authorization");
|
|
136
|
+
}
|
|
137
|
+
const scheme = new BatchEvmScheme({
|
|
138
|
+
address: signer.address,
|
|
139
|
+
signTypedData: signer.signTypedData.bind(signer),
|
|
140
|
+
});
|
|
141
|
+
const { payload } = await scheme.createPaymentPayload(2, req);
|
|
142
|
+
return {
|
|
143
|
+
payload: payload,
|
|
144
|
+
committed: false,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
129
147
|
async function buildPayment(signer, req) {
|
|
130
148
|
switch (req.scheme) {
|
|
131
149
|
case "exact": {
|
|
150
|
+
if (isGatewayBatch(req)) {
|
|
151
|
+
return signGatewayBatch(signer, req);
|
|
152
|
+
}
|
|
132
153
|
const { signature, authorization } = await signTransferAuth(signer, req);
|
|
133
154
|
return { payload: { signature, authorization }, committed: false };
|
|
134
155
|
}
|
|
135
156
|
case "gateway-batch": {
|
|
136
|
-
|
|
137
|
-
throw new PaymentRefusedError("signer", undefined, "signer lacks signTypedData — cannot sign gateway-batch authorization");
|
|
138
|
-
}
|
|
139
|
-
const scheme = new BatchEvmScheme({
|
|
140
|
-
address: signer.address,
|
|
141
|
-
signTypedData: signer.signTypedData.bind(signer),
|
|
142
|
-
});
|
|
143
|
-
const { payload } = await scheme.createPaymentPayload(2, req);
|
|
144
|
-
return {
|
|
145
|
-
payload: payload,
|
|
146
|
-
committed: false,
|
|
147
|
-
};
|
|
157
|
+
return signGatewayBatch(signer, req);
|
|
148
158
|
}
|
|
149
159
|
case "eip3009-client-broadcast": {
|
|
150
160
|
const { signature, authorization } = await signTransferAuth(signer, req);
|
|
@@ -180,18 +190,17 @@ export function createPayingClient(opts) {
|
|
|
180
190
|
if (!g?.autoDepositUsd)
|
|
181
191
|
return;
|
|
182
192
|
const chain = getChain(req.network);
|
|
183
|
-
if (!chain
|
|
193
|
+
if (!chain || chain.domain === undefined)
|
|
184
194
|
return;
|
|
185
|
-
const
|
|
195
|
+
const readBalance = () => gatewayBalance({
|
|
186
196
|
depositor: signer.address,
|
|
187
197
|
chain,
|
|
188
198
|
...(g.apiUrl ? { apiUrl: g.apiUrl } : {}),
|
|
189
199
|
fetchImpl,
|
|
190
200
|
});
|
|
191
|
-
|
|
192
|
-
return;
|
|
201
|
+
const info = await readBalance();
|
|
193
202
|
const need = BigInt(req.amount);
|
|
194
|
-
const available = BigInt(info
|
|
203
|
+
const available = BigInt(usdToAtomic(info?.available ?? "0"));
|
|
195
204
|
if (available >= need)
|
|
196
205
|
return;
|
|
197
206
|
if (!signer.writeContract) {
|
|
@@ -206,6 +215,16 @@ export function createPayingClient(opts) {
|
|
|
206
215
|
amountUsd: g.autoDepositUsd,
|
|
207
216
|
});
|
|
208
217
|
deposits.push(result);
|
|
218
|
+
const creditTimeoutSec = g.creditTimeoutSec ?? 120;
|
|
219
|
+
const deadline = Date.now() + creditTimeoutSec * 1000;
|
|
220
|
+
while (Date.now() < deadline) {
|
|
221
|
+
const next = await readBalance();
|
|
222
|
+
if (next && BigInt(usdToAtomic(next.available ?? "0")) >= need) {
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
await new Promise((r) => setTimeout(r, 3000));
|
|
226
|
+
}
|
|
227
|
+
throw new PaymentRefusedError("gatewayBalance", info?.available ?? null, `gateway deposit ${result.txHash} not credited within ${creditTimeoutSec}s — retry later`);
|
|
209
228
|
}
|
|
210
229
|
async function request(url, init = {}) {
|
|
211
230
|
const first = await fetchImpl(url, init);
|
|
@@ -235,8 +254,16 @@ export function createPayingClient(opts) {
|
|
|
235
254
|
}
|
|
236
255
|
}
|
|
237
256
|
}
|
|
257
|
+
if (opts.counterparty) {
|
|
258
|
+
await applyCounterpartyGate({
|
|
259
|
+
opts: opts.counterparty,
|
|
260
|
+
policy: opts.counterparty.policy ?? createCounterpartyPolicy(),
|
|
261
|
+
resourceUrl: url,
|
|
262
|
+
requirements: req,
|
|
263
|
+
});
|
|
264
|
+
}
|
|
238
265
|
tracker.tryReserve(req.amount);
|
|
239
|
-
if (req.scheme === "gateway-batch") {
|
|
266
|
+
if (req.scheme === "gateway-batch" || isGatewayBatch(req)) {
|
|
240
267
|
await ensureGatewayFunds(req);
|
|
241
268
|
}
|
|
242
269
|
const signed = await buildPayment(signer, req);
|
|
@@ -244,7 +271,12 @@ export function createPayingClient(opts) {
|
|
|
244
271
|
recordSpend(req, url);
|
|
245
272
|
}
|
|
246
273
|
const headers = new Headers(init.headers);
|
|
247
|
-
headers.set("payment-signature", b64encode({
|
|
274
|
+
headers.set("payment-signature", b64encode({
|
|
275
|
+
x402Version: 2,
|
|
276
|
+
accepted: req,
|
|
277
|
+
...(pr?.resource ? { resource: pr.resource } : {}),
|
|
278
|
+
payload: signed.payload,
|
|
279
|
+
}));
|
|
248
280
|
if (req.extra?.payerBinding && signed.txHash && signer.signMessage) {
|
|
249
281
|
const timestamp = Math.floor(Date.now() / 1000);
|
|
250
282
|
const msgSigner = signer;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { PaymentRequirements } from "../chains.js";
|
|
2
|
+
import { type CounterpartyChecker, type CounterpartyCheckMode, type CounterpartyPolicy, type OfferedTerms, type PaymentDecision, type TermsMatch, type Vet402Assessment } from "../counterparty/index.js";
|
|
3
|
+
export interface CounterpartyGateOptions {
|
|
4
|
+
checker?: CounterpartyChecker;
|
|
5
|
+
policy?: CounterpartyPolicy;
|
|
6
|
+
mode?: CounterpartyCheckMode;
|
|
7
|
+
onDecision?: (rec: CounterpartyDecisionRecord) => void;
|
|
8
|
+
}
|
|
9
|
+
export interface CounterpartyDecisionRecord {
|
|
10
|
+
resourceUrl: string;
|
|
11
|
+
assessment: Vet402Assessment;
|
|
12
|
+
termsMatch: TermsMatch;
|
|
13
|
+
decision: PaymentDecision;
|
|
14
|
+
mode: CounterpartyCheckMode;
|
|
15
|
+
}
|
|
16
|
+
export declare function evaluateCounterparty(input: {
|
|
17
|
+
checker: CounterpartyChecker;
|
|
18
|
+
policy: CounterpartyPolicy;
|
|
19
|
+
resourceUrl: string;
|
|
20
|
+
offer: OfferedTerms;
|
|
21
|
+
}): Promise<Omit<CounterpartyDecisionRecord, "mode">>;
|
|
22
|
+
export declare function applyCounterpartyGate(input: {
|
|
23
|
+
opts: CounterpartyGateOptions;
|
|
24
|
+
policy: CounterpartyPolicy;
|
|
25
|
+
resourceUrl: string;
|
|
26
|
+
requirements: PaymentRequirements;
|
|
27
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { matchTerms, offeredTermsFromRequirements, } from "../counterparty/index.js";
|
|
2
|
+
import { PaymentRefusedError } from "./client.js";
|
|
3
|
+
export async function evaluateCounterparty(input) {
|
|
4
|
+
const assessment = await input.checker.check({
|
|
5
|
+
resourceUrl: input.resourceUrl,
|
|
6
|
+
});
|
|
7
|
+
const termsMatch = matchTerms(assessment.kind === "verdict" ? assessment.verifiedTerms : null, input.offer);
|
|
8
|
+
const decision = input.policy.evaluate({ assessment, termsMatch });
|
|
9
|
+
return {
|
|
10
|
+
resourceUrl: input.resourceUrl,
|
|
11
|
+
assessment,
|
|
12
|
+
termsMatch,
|
|
13
|
+
decision,
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export async function applyCounterpartyGate(input) {
|
|
17
|
+
const { opts, policy, resourceUrl, requirements } = input;
|
|
18
|
+
const mode = opts.mode ?? "enforce";
|
|
19
|
+
if (mode === "off" || !opts.checker)
|
|
20
|
+
return;
|
|
21
|
+
const offer = offeredTermsFromRequirements(requirements);
|
|
22
|
+
const rec = {
|
|
23
|
+
...(await evaluateCounterparty({
|
|
24
|
+
checker: opts.checker,
|
|
25
|
+
policy,
|
|
26
|
+
resourceUrl,
|
|
27
|
+
offer,
|
|
28
|
+
})),
|
|
29
|
+
mode,
|
|
30
|
+
};
|
|
31
|
+
opts.onDecision?.(rec);
|
|
32
|
+
if (mode === "shadow" || rec.decision.action === "allow")
|
|
33
|
+
return;
|
|
34
|
+
throw new PaymentRefusedError("counterparty", { payTo: requirements.payTo, holdHint: rec.decision.holdHint }, rec.decision.reasonCode);
|
|
35
|
+
}
|
package/dist/cli/pay.js
CHANGED
|
@@ -4,9 +4,12 @@ import { privateKeyToAccount } from "viem/accounts";
|
|
|
4
4
|
import { getChain } from "../chains.js";
|
|
5
5
|
import { decode402 } from "../identity/verify-passport.js";
|
|
6
6
|
import { assertCaps, BudgetExhaustedError, CapExceededError, PaymentNotAcceptedError, } from "../buyer/caps.js";
|
|
7
|
-
import { atomicToUsd, validateAccepts, } from "../buyer/accepts.js";
|
|
7
|
+
import { atomicToUsd, isGatewayBatch, validateAccepts, } from "../buyer/accepts.js";
|
|
8
|
+
import { usdToAtomic } from "../buyer/caps.js";
|
|
8
9
|
import { createPayingClient, PaymentRefusedError, } from "../buyer/client.js";
|
|
9
10
|
import { createRiskGuard } from "../buyer/risk-guard.js";
|
|
11
|
+
import { createCounterpartyPolicy } from "../counterparty/policy.js";
|
|
12
|
+
import { Vet402Client, vet402ClientOptionsFromEnv, } from "../counterparty/vet402-client.js";
|
|
10
13
|
import { gatewayBalance } from "../gateway/deposit.js";
|
|
11
14
|
const EXIT_OK = 0;
|
|
12
15
|
const EXIT_REFUSED = 2;
|
|
@@ -24,6 +27,10 @@ Optional:
|
|
|
24
27
|
--auto-deposit <usd> auto top-up Gateway balance when short
|
|
25
28
|
--risk-check vet every payTo via risk API before signing
|
|
26
29
|
(AGENTBADGE_RISK_ENDPOINT to override)
|
|
30
|
+
--skip-counterparty-check
|
|
31
|
+
skip the vet402 counterparty check (default on;
|
|
32
|
+
COUNTERPARTY_CHECK_MODE=off|shadow|enforce,
|
|
33
|
+
COUNTERPARTY_VET402_BASE_URL to override)
|
|
27
34
|
--print-only show payment details, never sign
|
|
28
35
|
--help this text
|
|
29
36
|
|
|
@@ -32,7 +39,7 @@ Secrets:
|
|
|
32
39
|
|
|
33
40
|
Exit codes: 0 ok · 2 refusal/cap/budget/usage · 3 transport`;
|
|
34
41
|
function parseArgs(argv) {
|
|
35
|
-
const args = { method: "GET", printOnly: false, help: false, riskCheck: false };
|
|
42
|
+
const args = { method: "GET", printOnly: false, help: false, riskCheck: false, skipCounterpartyCheck: false };
|
|
36
43
|
const takeValue = (i, flag) => {
|
|
37
44
|
const v = argv[i + 1];
|
|
38
45
|
if (v === undefined || v.startsWith("--")) {
|
|
@@ -66,6 +73,9 @@ function parseArgs(argv) {
|
|
|
66
73
|
case "--risk-check":
|
|
67
74
|
args.riskCheck = true;
|
|
68
75
|
break;
|
|
76
|
+
case "--skip-counterparty-check":
|
|
77
|
+
args.skipCounterpartyCheck = true;
|
|
78
|
+
break;
|
|
69
79
|
case "--print-only":
|
|
70
80
|
args.printOnly = true;
|
|
71
81
|
break;
|
|
@@ -193,22 +203,30 @@ export async function runPay(argv, env = process.env, io = {}) {
|
|
|
193
203
|
return EXIT_REFUSED;
|
|
194
204
|
}
|
|
195
205
|
const account = privateKeyToAccount((key.startsWith("0x") ? key : `0x${key}`));
|
|
196
|
-
if (req.scheme === "gateway-batch"
|
|
206
|
+
if ((req.scheme === "gateway-batch" || isGatewayBatch(req)) &&
|
|
207
|
+
!args.autoDeposit &&
|
|
208
|
+
chain) {
|
|
197
209
|
const gw = await gatewayBalance({
|
|
198
210
|
depositor: account.address,
|
|
199
211
|
chain,
|
|
200
212
|
fetchImpl,
|
|
201
213
|
});
|
|
202
214
|
const need = BigInt(req.amount);
|
|
203
|
-
if (gw && BigInt(gw.available ?? "0") < need) {
|
|
215
|
+
if (gw && BigInt(usdToAtomic(gw.available ?? "0")) < need) {
|
|
204
216
|
const eoa = await eoaUsdcBalance(chain, account.address);
|
|
205
217
|
const suggestion = eoa !== undefined && eoa >= need
|
|
206
|
-
? `run
|
|
218
|
+
? `re-run with --auto-deposit ${verdict.priceUsd}`
|
|
207
219
|
: `deposit USDC to GatewayWallet ${chain.gatewayWallet} on ${chain.name}`;
|
|
208
220
|
err(`gateway balance ${gw.available} < price ${req.amount} — ${suggestion}`);
|
|
209
221
|
return EXIT_REFUSED;
|
|
210
222
|
}
|
|
211
223
|
}
|
|
224
|
+
const publicClient = chain
|
|
225
|
+
? createPublicClient({
|
|
226
|
+
chain: toViemChain(chain),
|
|
227
|
+
transport: http(chain.rpcUrl),
|
|
228
|
+
})
|
|
229
|
+
: undefined;
|
|
212
230
|
const signer = {
|
|
213
231
|
address: account.address,
|
|
214
232
|
signTypedData: (a) => account.signTypedData(a),
|
|
@@ -224,7 +242,42 @@ export async function runPay(argv, env = process.env, io = {}) {
|
|
|
224
242
|
});
|
|
225
243
|
return wc.writeContract(wcArgs);
|
|
226
244
|
},
|
|
245
|
+
...(publicClient
|
|
246
|
+
? {
|
|
247
|
+
readContract: (rcArgs) => publicClient.readContract(rcArgs),
|
|
248
|
+
waitForTransactionReceipt: (rArgs) => publicClient.waitForTransactionReceipt(rArgs),
|
|
249
|
+
}
|
|
250
|
+
: {}),
|
|
227
251
|
};
|
|
252
|
+
let counterparty;
|
|
253
|
+
if (args.skipCounterpartyCheck) {
|
|
254
|
+
err("counterparty check skipped (--skip-counterparty-check)");
|
|
255
|
+
}
|
|
256
|
+
else {
|
|
257
|
+
const mode = (env.COUNTERPARTY_CHECK_MODE ??
|
|
258
|
+
"enforce");
|
|
259
|
+
if (mode !== "off") {
|
|
260
|
+
counterparty = {
|
|
261
|
+
checker: new Vet402Client({
|
|
262
|
+
...vet402ClientOptionsFromEnv(env),
|
|
263
|
+
...(env.COUNTERPARTY_VET402_BASE_URL
|
|
264
|
+
? { baseUrl: env.COUNTERPARTY_VET402_BASE_URL }
|
|
265
|
+
: {}),
|
|
266
|
+
fetchImpl,
|
|
267
|
+
}),
|
|
268
|
+
policy: createCounterpartyPolicy(),
|
|
269
|
+
mode,
|
|
270
|
+
onDecision: (rec) => {
|
|
271
|
+
const verdict = rec.assessment.kind === "verdict"
|
|
272
|
+
? rec.assessment.verdict
|
|
273
|
+
: rec.assessment.kind;
|
|
274
|
+
err(`[counterparty:${mode}] ${verdict} → ${rec.decision.action}` +
|
|
275
|
+
` (${rec.decision.reasonCode}) terms=${rec.termsMatch.result}` +
|
|
276
|
+
` cacheHit=${rec.assessment.cacheHit}`);
|
|
277
|
+
},
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
}
|
|
228
281
|
const client = createPayingClient({
|
|
229
282
|
caps,
|
|
230
283
|
signer,
|
|
@@ -242,6 +295,7 @@ export async function runPay(argv, env = process.env, io = {}) {
|
|
|
242
295
|
}),
|
|
243
296
|
}
|
|
244
297
|
: {}),
|
|
298
|
+
...(counterparty ? { counterparty } : {}),
|
|
245
299
|
});
|
|
246
300
|
try {
|
|
247
301
|
const res = await client.request(args.url, init);
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { normalizeAddress, normalizeTerms } from "./terms.js";
|
|
3
|
+
export const DEAL_FINGERPRINT_VERSION = 1;
|
|
4
|
+
function canonicalize(v) {
|
|
5
|
+
if (Array.isArray(v))
|
|
6
|
+
return v.map(canonicalize);
|
|
7
|
+
if (v && typeof v === "object") {
|
|
8
|
+
const o = v;
|
|
9
|
+
return Object.fromEntries(Object.keys(o)
|
|
10
|
+
.sort()
|
|
11
|
+
.map((k) => [k, canonicalize(o[k])]));
|
|
12
|
+
}
|
|
13
|
+
return v;
|
|
14
|
+
}
|
|
15
|
+
function canonicalJson(v) {
|
|
16
|
+
return JSON.stringify(canonicalize(v));
|
|
17
|
+
}
|
|
18
|
+
function normalizeUrlForFingerprint(url) {
|
|
19
|
+
try {
|
|
20
|
+
const u = new URL(url);
|
|
21
|
+
return `${u.origin}${u.pathname}${u.search}`;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return url.trim();
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
export function dealFingerprint(input) {
|
|
28
|
+
const t = normalizeTerms(input.offer);
|
|
29
|
+
const wallet = normalizeAddress(input.wallet, t.network);
|
|
30
|
+
const url = normalizeUrlForFingerprint(input.url);
|
|
31
|
+
const canonical = canonicalJson({
|
|
32
|
+
amount: t.amount,
|
|
33
|
+
asset: t.asset,
|
|
34
|
+
network: t.network,
|
|
35
|
+
payTo: t.payTo,
|
|
36
|
+
scheme: t.scheme,
|
|
37
|
+
url,
|
|
38
|
+
wallet,
|
|
39
|
+
});
|
|
40
|
+
return `sha256:v${DEAL_FINGERPRINT_VERSION}:${createHash("sha256")
|
|
41
|
+
.update(canonical)
|
|
42
|
+
.digest("hex")}`;
|
|
43
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
const hold = (reasonCode, holdHint) => ({ action: "hold", reasonCode, holdHint });
|
|
2
|
+
const UNMEASURED = hold("counterparty_unmeasured", "counterparty_unmeasured");
|
|
3
|
+
const TERMS_UNCOMPARABLE = hold("terms_uncomparable", "counterparty_unmeasured");
|
|
4
|
+
const WARN = hold("counterparty_warn", "counterparty_warn");
|
|
5
|
+
const TERMS_DENY = { action: "deny", reasonCode: "terms_mismatch" };
|
|
6
|
+
const BLOCK_DENY = { action: "deny", reasonCode: "counterparty_blocked" };
|
|
7
|
+
const UNAVAILABLE = {
|
|
8
|
+
action: "unavailable",
|
|
9
|
+
reasonCode: "counterparty_unavailable",
|
|
10
|
+
};
|
|
11
|
+
const ALLOW = { action: "allow", reasonCode: "allowed" };
|
|
12
|
+
function fromTerms(t) {
|
|
13
|
+
switch (t.result) {
|
|
14
|
+
case "mismatch":
|
|
15
|
+
return TERMS_DENY;
|
|
16
|
+
case "uncomparable":
|
|
17
|
+
return TERMS_UNCOMPARABLE;
|
|
18
|
+
default:
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function fromVerdict(a, termsMatch) {
|
|
23
|
+
if (a.verdict === "BLOCK")
|
|
24
|
+
return BLOCK_DENY;
|
|
25
|
+
const terms = fromTerms(termsMatch);
|
|
26
|
+
if (terms)
|
|
27
|
+
return terms;
|
|
28
|
+
if (a.verdict === "WARN")
|
|
29
|
+
return WARN;
|
|
30
|
+
if (termsMatch.result === "unmeasured")
|
|
31
|
+
return UNMEASURED;
|
|
32
|
+
return ALLOW;
|
|
33
|
+
}
|
|
34
|
+
class CounterpartyPolicyImpl {
|
|
35
|
+
evaluate(input) {
|
|
36
|
+
const { assessment, termsMatch } = input;
|
|
37
|
+
switch (assessment.kind) {
|
|
38
|
+
case "unavailable":
|
|
39
|
+
return UNAVAILABLE;
|
|
40
|
+
case "not_in_catalog":
|
|
41
|
+
case "privacy_unmeasurable":
|
|
42
|
+
return UNMEASURED;
|
|
43
|
+
case "verdict":
|
|
44
|
+
return fromVerdict(assessment, termsMatch);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export function createCounterpartyPolicy() {
|
|
49
|
+
return new CounterpartyPolicyImpl();
|
|
50
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
const JWT_RE = /^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
|
|
2
|
+
const HEX_LIKE_RE = /^(?:0x)?[0-9a-f]{32,}$/i;
|
|
3
|
+
const B64URL_RE = /^[A-Za-z0-9_-]+$/;
|
|
4
|
+
function looksSecretSegment(segment) {
|
|
5
|
+
if (segment === "")
|
|
6
|
+
return false;
|
|
7
|
+
let s = segment;
|
|
8
|
+
try {
|
|
9
|
+
s = decodeURIComponent(segment);
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
}
|
|
13
|
+
if (JWT_RE.test(s))
|
|
14
|
+
return true;
|
|
15
|
+
if (HEX_LIKE_RE.test(s))
|
|
16
|
+
return true;
|
|
17
|
+
if (s.length >= 32 && B64URL_RE.test(s) && /[A-Z]/.test(s) && /\d/.test(s)) {
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
const parts = s.split(".");
|
|
21
|
+
if (parts.length >= 3 &&
|
|
22
|
+
s.length >= 30 &&
|
|
23
|
+
parts.every((p) => p.length >= 8 && B64URL_RE.test(p))) {
|
|
24
|
+
return true;
|
|
25
|
+
}
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
export function sanitizeUrlForCheck(raw) {
|
|
29
|
+
let u;
|
|
30
|
+
try {
|
|
31
|
+
u = new URL(raw);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return { ok: false, block: "unparseable" };
|
|
35
|
+
}
|
|
36
|
+
if (u.protocol !== "https:") {
|
|
37
|
+
return { ok: false, block: "non_https_scheme" };
|
|
38
|
+
}
|
|
39
|
+
if (u.username !== "" || u.password !== "") {
|
|
40
|
+
return { ok: false, block: "credentials" };
|
|
41
|
+
}
|
|
42
|
+
if (raw.includes("?")) {
|
|
43
|
+
return { ok: false, block: "query" };
|
|
44
|
+
}
|
|
45
|
+
if (raw.includes("#")) {
|
|
46
|
+
return { ok: false, block: "fragment" };
|
|
47
|
+
}
|
|
48
|
+
for (const seg of u.pathname.split("/")) {
|
|
49
|
+
if (looksSecretSegment(seg)) {
|
|
50
|
+
return { ok: false, block: "secret_path_segment", segmentLength: seg.length };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return { ok: true, url: `${u.origin}${u.pathname}` };
|
|
54
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { PaymentRequirements } from "../chains.js";
|
|
2
|
+
import type { NormalizedTerms, OfferedTerms, DealTerms, TermsMatch, VerifiedTerms } from "./types.js";
|
|
3
|
+
export declare class TermsUncomparableError extends Error {
|
|
4
|
+
readonly detail: string;
|
|
5
|
+
constructor(detail: string);
|
|
6
|
+
}
|
|
7
|
+
export declare function parseCaip2(network: string): {
|
|
8
|
+
namespace: string;
|
|
9
|
+
reference: string;
|
|
10
|
+
};
|
|
11
|
+
export declare function normalizeNetwork(network: string): string;
|
|
12
|
+
export declare function normalizeAddress(addr: string, network: string): string;
|
|
13
|
+
export declare function normalizeAmount(amount: string): string;
|
|
14
|
+
export declare function normalizeScheme(scheme: string): string;
|
|
15
|
+
export declare function normalizeTerms(terms: DealTerms): NormalizedTerms;
|
|
16
|
+
export declare function matchTerms(verified: VerifiedTerms | null | undefined, offered: OfferedTerms): TermsMatch;
|
|
17
|
+
export declare function offeredTermsFromRequirements(req: Pick<PaymentRequirements, "payTo" | "asset" | "network" | "scheme" | "amount" | "maxAmountRequired">): OfferedTerms;
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { getAddress, isAddress } from "viem";
|
|
2
|
+
export class TermsUncomparableError extends Error {
|
|
3
|
+
detail;
|
|
4
|
+
constructor(detail) {
|
|
5
|
+
super(`terms_uncomparable: ${detail}`);
|
|
6
|
+
this.name = "TermsUncomparableError";
|
|
7
|
+
this.detail = detail;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
const CAIP2_NAMESPACE_RE = /^[-a-z0-9]{3,8}$/i;
|
|
11
|
+
const CAIP2_REFERENCE_RE = /^[-_a-zA-Z0-9]{1,64}$/;
|
|
12
|
+
export function parseCaip2(network) {
|
|
13
|
+
const idx = network.indexOf(":");
|
|
14
|
+
if (idx <= 0) {
|
|
15
|
+
throw new TermsUncomparableError(`network ${JSON.stringify(network)} is not CAIP-2`);
|
|
16
|
+
}
|
|
17
|
+
const namespace = network.slice(0, idx).toLowerCase();
|
|
18
|
+
const reference = network.slice(idx + 1);
|
|
19
|
+
if (!CAIP2_NAMESPACE_RE.test(namespace) || !CAIP2_REFERENCE_RE.test(reference)) {
|
|
20
|
+
throw new TermsUncomparableError(`network ${JSON.stringify(network)} is not a valid CAIP-2 id`);
|
|
21
|
+
}
|
|
22
|
+
return { namespace, reference };
|
|
23
|
+
}
|
|
24
|
+
export function normalizeNetwork(network) {
|
|
25
|
+
const { namespace, reference } = parseCaip2(network);
|
|
26
|
+
if (namespace === "eip155") {
|
|
27
|
+
if (!/^\d+$/.test(reference)) {
|
|
28
|
+
throw new TermsUncomparableError(`eip155 reference ${JSON.stringify(reference)} is not numeric`);
|
|
29
|
+
}
|
|
30
|
+
return `eip155:${BigInt(reference).toString()}`;
|
|
31
|
+
}
|
|
32
|
+
return `${namespace}:${reference}`;
|
|
33
|
+
}
|
|
34
|
+
const EVM_ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
|
|
35
|
+
const BASE58_ADDRESS_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
|
|
36
|
+
export function normalizeAddress(addr, network) {
|
|
37
|
+
const { namespace } = parseCaip2(network);
|
|
38
|
+
const trimmed = addr.trim();
|
|
39
|
+
if (namespace === "eip155") {
|
|
40
|
+
if (!EVM_ADDRESS_RE.test(trimmed)) {
|
|
41
|
+
throw new TermsUncomparableError(`payTo/asset ${JSON.stringify(addr)} is not an EVM address`);
|
|
42
|
+
}
|
|
43
|
+
const body = trimmed.slice(2);
|
|
44
|
+
const mixedCase = /[a-f]/.test(body) && /[A-F]/.test(body);
|
|
45
|
+
if (mixedCase && !isAddress(trimmed)) {
|
|
46
|
+
throw new TermsUncomparableError(`EVM address ${JSON.stringify(addr)} fails EIP-55 checksum`);
|
|
47
|
+
}
|
|
48
|
+
try {
|
|
49
|
+
return getAddress(trimmed).toLowerCase();
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
throw new TermsUncomparableError(`EVM address ${JSON.stringify(addr)} fails EIP-55 checksum`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (namespace === "solana") {
|
|
56
|
+
if (!BASE58_ADDRESS_RE.test(trimmed)) {
|
|
57
|
+
throw new TermsUncomparableError(`payTo/asset ${JSON.stringify(addr)} is not a Base58 address`);
|
|
58
|
+
}
|
|
59
|
+
return trimmed;
|
|
60
|
+
}
|
|
61
|
+
throw new TermsUncomparableError(`no address rule for network namespace ${JSON.stringify(namespace)}`);
|
|
62
|
+
}
|
|
63
|
+
export function normalizeAmount(amount) {
|
|
64
|
+
const t = amount.trim();
|
|
65
|
+
if (!/^\d+$/.test(t)) {
|
|
66
|
+
throw new TermsUncomparableError(`amount ${JSON.stringify(amount)} is not an atomic integer string`);
|
|
67
|
+
}
|
|
68
|
+
return BigInt(t).toString();
|
|
69
|
+
}
|
|
70
|
+
export function normalizeScheme(scheme) {
|
|
71
|
+
const t = scheme.trim().toLowerCase();
|
|
72
|
+
if (t === "") {
|
|
73
|
+
throw new TermsUncomparableError("scheme is empty");
|
|
74
|
+
}
|
|
75
|
+
return t;
|
|
76
|
+
}
|
|
77
|
+
export function normalizeTerms(terms) {
|
|
78
|
+
const network = normalizeNetwork(terms.network);
|
|
79
|
+
return {
|
|
80
|
+
payTo: normalizeAddress(terms.payTo, network),
|
|
81
|
+
asset: normalizeAddress(terms.asset, network),
|
|
82
|
+
amount: normalizeAmount(terms.amount),
|
|
83
|
+
network,
|
|
84
|
+
scheme: normalizeScheme(terms.scheme),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
const TERMS_FIELDS = ["payTo", "asset", "amount", "network", "scheme"];
|
|
88
|
+
export function matchTerms(verified, offered) {
|
|
89
|
+
if (verified == null) {
|
|
90
|
+
return { result: "unmeasured" };
|
|
91
|
+
}
|
|
92
|
+
let v;
|
|
93
|
+
let o;
|
|
94
|
+
try {
|
|
95
|
+
v = normalizeTerms(verified);
|
|
96
|
+
}
|
|
97
|
+
catch (e) {
|
|
98
|
+
return {
|
|
99
|
+
result: "uncomparable",
|
|
100
|
+
reason: `verified terms: ${e instanceof Error ? e.message : String(e)}`,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
try {
|
|
104
|
+
o = normalizeTerms(offered);
|
|
105
|
+
}
|
|
106
|
+
catch (e) {
|
|
107
|
+
return {
|
|
108
|
+
result: "uncomparable",
|
|
109
|
+
reason: `offered terms: ${e instanceof Error ? e.message : String(e)}`,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
const diff = {};
|
|
113
|
+
for (const f of TERMS_FIELDS) {
|
|
114
|
+
if (v[f] !== o[f]) {
|
|
115
|
+
diff[f] = { verified: v[f], offered: o[f] };
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return Object.keys(diff).length === 0
|
|
119
|
+
? { result: "match" }
|
|
120
|
+
: { result: "mismatch", diff };
|
|
121
|
+
}
|
|
122
|
+
export function offeredTermsFromRequirements(req) {
|
|
123
|
+
const amount = req.amount ?? req.maxAmountRequired;
|
|
124
|
+
if (amount === undefined) {
|
|
125
|
+
throw new TermsUncomparableError("offer has neither amount nor maxAmountRequired");
|
|
126
|
+
}
|
|
127
|
+
return {
|
|
128
|
+
payTo: req.payTo,
|
|
129
|
+
asset: req.asset,
|
|
130
|
+
amount,
|
|
131
|
+
network: req.network,
|
|
132
|
+
scheme: req.scheme,
|
|
133
|
+
};
|
|
134
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
export type Vet402Verdict = "ALLOW" | "WARN" | "BLOCK";
|
|
2
|
+
export type CounterpartyVerdict = "allow" | "hold" | "deny" | "unavailable";
|
|
3
|
+
export type CounterpartyReasonCode = "allowed" | "terms_mismatch" | "terms_uncomparable" | "counterparty_blocked" | "counterparty_warn" | "counterparty_unmeasured" | "counterparty_unavailable";
|
|
4
|
+
export type ApprovalReason = "amount_threshold" | "counterparty_warn" | "counterparty_unmeasured";
|
|
5
|
+
export type CounterpartyCheckMode = "off" | "shadow" | "enforce";
|
|
6
|
+
export interface DealTerms {
|
|
7
|
+
payTo: string;
|
|
8
|
+
asset: string;
|
|
9
|
+
amount: string;
|
|
10
|
+
network: string;
|
|
11
|
+
scheme: string;
|
|
12
|
+
}
|
|
13
|
+
export type OfferedTerms = DealTerms;
|
|
14
|
+
export type VerifiedTerms = DealTerms;
|
|
15
|
+
export interface NormalizedTerms {
|
|
16
|
+
payTo: string;
|
|
17
|
+
asset: string;
|
|
18
|
+
amount: string;
|
|
19
|
+
network: string;
|
|
20
|
+
scheme: string;
|
|
21
|
+
}
|
|
22
|
+
interface AssessmentBase {
|
|
23
|
+
checkedAt: string;
|
|
24
|
+
cacheHit?: boolean;
|
|
25
|
+
}
|
|
26
|
+
export interface Vet402VerdictAssessment extends AssessmentBase {
|
|
27
|
+
kind: "verdict";
|
|
28
|
+
verdict: Vet402Verdict;
|
|
29
|
+
reasonCodes: readonly string[];
|
|
30
|
+
verifiedTerms: VerifiedTerms | null;
|
|
31
|
+
evidenceAgeSeconds?: number;
|
|
32
|
+
degraded?: boolean;
|
|
33
|
+
}
|
|
34
|
+
export interface Vet402NotInCatalogAssessment extends AssessmentBase {
|
|
35
|
+
kind: "not_in_catalog";
|
|
36
|
+
}
|
|
37
|
+
export interface Vet402PrivacyUnmeasurableAssessment extends AssessmentBase {
|
|
38
|
+
kind: "privacy_unmeasurable";
|
|
39
|
+
sanitizeBlock?: SanitizeUrlBlock;
|
|
40
|
+
}
|
|
41
|
+
export type Vet402UnavailableFailure = "timeout" | "rate_limited" | "upstream_5xx" | "network_error" | "invalid_response" | "degraded";
|
|
42
|
+
export interface Vet402UnavailableAssessment extends AssessmentBase {
|
|
43
|
+
kind: "unavailable";
|
|
44
|
+
failure: Vet402UnavailableFailure;
|
|
45
|
+
}
|
|
46
|
+
export type Vet402Assessment = Vet402VerdictAssessment | Vet402NotInCatalogAssessment | Vet402PrivacyUnmeasurableAssessment | Vet402UnavailableAssessment;
|
|
47
|
+
export type TermsMatchResult = "match" | "mismatch" | "uncomparable" | "unmeasured";
|
|
48
|
+
export interface TermsFieldDiff {
|
|
49
|
+
verified: string;
|
|
50
|
+
offered: string;
|
|
51
|
+
}
|
|
52
|
+
export interface TermsMatch {
|
|
53
|
+
result: TermsMatchResult;
|
|
54
|
+
reason?: string;
|
|
55
|
+
diff?: Partial<Record<keyof NormalizedTerms, TermsFieldDiff>>;
|
|
56
|
+
}
|
|
57
|
+
export interface PaymentDecision {
|
|
58
|
+
action: CounterpartyVerdict;
|
|
59
|
+
reasonCode: CounterpartyReasonCode;
|
|
60
|
+
holdHint?: Extract<ApprovalReason, "counterparty_warn" | "counterparty_unmeasured">;
|
|
61
|
+
}
|
|
62
|
+
export interface CounterpartyCheckInput {
|
|
63
|
+
resourceUrl: string;
|
|
64
|
+
signal?: AbortSignal;
|
|
65
|
+
}
|
|
66
|
+
export interface CounterpartyChecker {
|
|
67
|
+
check(input: CounterpartyCheckInput): Promise<Vet402Assessment>;
|
|
68
|
+
}
|
|
69
|
+
export interface CounterpartyPolicy {
|
|
70
|
+
evaluate(input: {
|
|
71
|
+
assessment: Vet402Assessment;
|
|
72
|
+
termsMatch: TermsMatch;
|
|
73
|
+
}): PaymentDecision;
|
|
74
|
+
}
|
|
75
|
+
export type SanitizeUrlBlock = "unparseable" | "non_https_scheme" | "credentials" | "query" | "fragment" | "secret_path_segment";
|
|
76
|
+
export type SanitizeUrlResult = {
|
|
77
|
+
ok: true;
|
|
78
|
+
url: string;
|
|
79
|
+
} | {
|
|
80
|
+
ok: false;
|
|
81
|
+
block: SanitizeUrlBlock;
|
|
82
|
+
segmentLength?: number;
|
|
83
|
+
};
|
|
84
|
+
export interface DealFingerprintInput {
|
|
85
|
+
wallet: string;
|
|
86
|
+
url: string;
|
|
87
|
+
offer: OfferedTerms;
|
|
88
|
+
}
|
|
89
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { CounterpartyCheckInput, CounterpartyChecker, Vet402Assessment } from "./types.js";
|
|
2
|
+
type FetchImpl = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
3
|
+
export interface Vet402ClientOptions {
|
|
4
|
+
baseUrl?: string;
|
|
5
|
+
fetchImpl?: FetchImpl;
|
|
6
|
+
now?: () => number;
|
|
7
|
+
sleepImpl?: (ms: number) => Promise<void>;
|
|
8
|
+
decisionTtlMs?: number;
|
|
9
|
+
blockTtlMs?: number;
|
|
10
|
+
maxRpm?: number;
|
|
11
|
+
connectTimeoutMs?: number;
|
|
12
|
+
totalTimeoutMs?: number;
|
|
13
|
+
resolveCacheSize?: number;
|
|
14
|
+
decisionCacheSize?: number;
|
|
15
|
+
metrics?: CounterpartyMetricsHooks;
|
|
16
|
+
}
|
|
17
|
+
export interface CounterpartyMetricsHooks {
|
|
18
|
+
onCheck?(outcome: "allow" | "hold" | "deny" | "unavailable", ms: number): void;
|
|
19
|
+
onCache?(result: "hit" | "miss"): void;
|
|
20
|
+
onRateLimited?(endpoint: "resolve" | "decision"): void;
|
|
21
|
+
}
|
|
22
|
+
export declare function vet402ClientOptionsFromEnv(env: Record<string, string | undefined>): Pick<Vet402ClientOptions, "decisionTtlMs" | "blockTtlMs" | "maxRpm" | "connectTimeoutMs" | "totalTimeoutMs">;
|
|
23
|
+
export declare class Vet402Client implements CounterpartyChecker {
|
|
24
|
+
private baseUrl;
|
|
25
|
+
private fetch;
|
|
26
|
+
private now;
|
|
27
|
+
private sleep;
|
|
28
|
+
private decisionTtlMs;
|
|
29
|
+
private blockTtlMs;
|
|
30
|
+
private connectTimeoutMs;
|
|
31
|
+
private totalTimeoutMs;
|
|
32
|
+
private metrics?;
|
|
33
|
+
private resolveCache;
|
|
34
|
+
private decisionCache;
|
|
35
|
+
private inflight;
|
|
36
|
+
private bucket;
|
|
37
|
+
constructor(opts?: Vet402ClientOptions);
|
|
38
|
+
check(input: CounterpartyCheckInput): Promise<Vet402Assessment>;
|
|
39
|
+
private runCheck;
|
|
40
|
+
private emitCheck;
|
|
41
|
+
private resolveResourceId;
|
|
42
|
+
private fetchDecision;
|
|
43
|
+
private parseVerifiedTerms;
|
|
44
|
+
private unavailable;
|
|
45
|
+
private iso;
|
|
46
|
+
private outbound;
|
|
47
|
+
}
|
|
48
|
+
export {};
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
import { sanitizeUrlForCheck } from "./sanitize-url.js";
|
|
2
|
+
export function vet402ClientOptionsFromEnv(env) {
|
|
3
|
+
const int = (k) => {
|
|
4
|
+
const v = env[k];
|
|
5
|
+
if (v === undefined || v === "")
|
|
6
|
+
return undefined;
|
|
7
|
+
const n = Number(v);
|
|
8
|
+
return Number.isFinite(n) && n > 0 ? n : undefined;
|
|
9
|
+
};
|
|
10
|
+
return {
|
|
11
|
+
decisionTtlMs: int("COUNTERPARTY_DECISION_TTL_MS"),
|
|
12
|
+
blockTtlMs: int("COUNTERPARTY_BLOCK_TTL_MS"),
|
|
13
|
+
maxRpm: int("COUNTERPARTY_MAX_RPM"),
|
|
14
|
+
connectTimeoutMs: int("COUNTERPARTY_CONNECT_TIMEOUT_MS"),
|
|
15
|
+
totalTimeoutMs: int("COUNTERPARTY_TOTAL_TIMEOUT_MS"),
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
class LruCache {
|
|
19
|
+
maxSize;
|
|
20
|
+
map = new Map();
|
|
21
|
+
constructor(maxSize) {
|
|
22
|
+
this.maxSize = maxSize;
|
|
23
|
+
}
|
|
24
|
+
get(k) {
|
|
25
|
+
const v = this.map.get(k);
|
|
26
|
+
if (v !== undefined) {
|
|
27
|
+
this.map.delete(k);
|
|
28
|
+
this.map.set(k, v);
|
|
29
|
+
}
|
|
30
|
+
return v;
|
|
31
|
+
}
|
|
32
|
+
set(k, v) {
|
|
33
|
+
this.map.delete(k);
|
|
34
|
+
this.map.set(k, v);
|
|
35
|
+
if (this.map.size > this.maxSize) {
|
|
36
|
+
this.map.delete(this.map.keys().next().value);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
delete(k) {
|
|
40
|
+
this.map.delete(k);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
class TokenBucket {
|
|
44
|
+
capacity;
|
|
45
|
+
now;
|
|
46
|
+
tokens;
|
|
47
|
+
lastRefill;
|
|
48
|
+
constructor(capacity, now) {
|
|
49
|
+
this.capacity = capacity;
|
|
50
|
+
this.now = now;
|
|
51
|
+
this.tokens = capacity;
|
|
52
|
+
this.lastRefill = now();
|
|
53
|
+
}
|
|
54
|
+
refill() {
|
|
55
|
+
const t = this.now();
|
|
56
|
+
const rate = this.capacity / 60_000;
|
|
57
|
+
this.tokens = Math.min(this.capacity, this.tokens + (t - this.lastRefill) * rate);
|
|
58
|
+
this.lastRefill = t;
|
|
59
|
+
}
|
|
60
|
+
tryAcquire() {
|
|
61
|
+
this.refill();
|
|
62
|
+
if (this.tokens >= 1) {
|
|
63
|
+
this.tokens -= 1;
|
|
64
|
+
return { ok: true };
|
|
65
|
+
}
|
|
66
|
+
const rate = this.capacity / 60_000;
|
|
67
|
+
return { ok: false, waitMs: Math.ceil((1 - this.tokens) / rate) };
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const LEDGER_UNIT_FACTOR = {
|
|
71
|
+
"eip155:56": 10n ** 12n,
|
|
72
|
+
"stellar:pubnet": 10n,
|
|
73
|
+
"stellar:testnet": 10n,
|
|
74
|
+
};
|
|
75
|
+
const RESOURCE_ID_RE = /^[0-9a-f]{64}$/;
|
|
76
|
+
export class Vet402Client {
|
|
77
|
+
baseUrl;
|
|
78
|
+
fetch;
|
|
79
|
+
now;
|
|
80
|
+
sleep;
|
|
81
|
+
decisionTtlMs;
|
|
82
|
+
blockTtlMs;
|
|
83
|
+
connectTimeoutMs;
|
|
84
|
+
totalTimeoutMs;
|
|
85
|
+
metrics;
|
|
86
|
+
resolveCache;
|
|
87
|
+
decisionCache;
|
|
88
|
+
inflight = new Map();
|
|
89
|
+
bucket;
|
|
90
|
+
constructor(opts = {}) {
|
|
91
|
+
this.baseUrl = (opts.baseUrl ?? "https://vet402.com").replace(/\/+$/, "");
|
|
92
|
+
this.fetch = opts.fetchImpl ?? fetch;
|
|
93
|
+
this.now = opts.now ?? Date.now;
|
|
94
|
+
this.sleep =
|
|
95
|
+
opts.sleepImpl ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
96
|
+
this.decisionTtlMs = opts.decisionTtlMs ?? 5 * 60_000;
|
|
97
|
+
this.blockTtlMs = opts.blockTtlMs ?? 60_000;
|
|
98
|
+
this.connectTimeoutMs = opts.connectTimeoutMs ?? 2_000;
|
|
99
|
+
this.totalTimeoutMs = opts.totalTimeoutMs ?? 8_000;
|
|
100
|
+
this.metrics = opts.metrics;
|
|
101
|
+
this.resolveCache = new LruCache(opts.resolveCacheSize ?? 1024);
|
|
102
|
+
this.decisionCache = new LruCache(opts.decisionCacheSize ?? 1024);
|
|
103
|
+
this.bucket = new TokenBucket(Math.max(1, opts.maxRpm ?? 11), this.now);
|
|
104
|
+
}
|
|
105
|
+
async check(input) {
|
|
106
|
+
const t0 = this.now();
|
|
107
|
+
const s = sanitizeUrlForCheck(input.resourceUrl);
|
|
108
|
+
if (!s.ok) {
|
|
109
|
+
const a = {
|
|
110
|
+
kind: "privacy_unmeasurable",
|
|
111
|
+
sanitizeBlock: s.block,
|
|
112
|
+
checkedAt: new Date(t0).toISOString(),
|
|
113
|
+
};
|
|
114
|
+
this.metrics?.onCheck?.("hold", this.now() - t0);
|
|
115
|
+
return a;
|
|
116
|
+
}
|
|
117
|
+
const key = s.url;
|
|
118
|
+
const existing = this.inflight.get(key);
|
|
119
|
+
if (existing) {
|
|
120
|
+
const a = await existing;
|
|
121
|
+
this.emitCheck(a, t0, true);
|
|
122
|
+
return a;
|
|
123
|
+
}
|
|
124
|
+
const p = this.runCheck(s.url, t0, input.signal)
|
|
125
|
+
.finally(() => this.inflight.delete(key));
|
|
126
|
+
this.inflight.set(key, p);
|
|
127
|
+
return p;
|
|
128
|
+
}
|
|
129
|
+
async runCheck(url, t0, callerSignal) {
|
|
130
|
+
const deadline = t0 + this.totalTimeoutMs;
|
|
131
|
+
let rereolved = false;
|
|
132
|
+
for (;;) {
|
|
133
|
+
const resolved = await this.resolveResourceId(url, deadline, callerSignal);
|
|
134
|
+
if (resolved.assessment) {
|
|
135
|
+
this.emitCheck(resolved.assessment, t0, resolved.cacheHit === true);
|
|
136
|
+
return resolved.assessment;
|
|
137
|
+
}
|
|
138
|
+
const resourceId = resolved.resourceId;
|
|
139
|
+
const cached = this.decisionCache.get(resourceId);
|
|
140
|
+
if (cached && cached.expiresAt > this.now()) {
|
|
141
|
+
const a = { ...cached.assessment, cacheHit: true };
|
|
142
|
+
this.emitCheck(a, t0, true);
|
|
143
|
+
return a;
|
|
144
|
+
}
|
|
145
|
+
const out = await this.fetchDecision(resourceId, url, deadline, callerSignal);
|
|
146
|
+
if (out.assessment) {
|
|
147
|
+
if (out.assessment.kind === "unavailable" &&
|
|
148
|
+
out.assessment.failure === "invalid_response" &&
|
|
149
|
+
out.unknownResource &&
|
|
150
|
+
!rereolved) {
|
|
151
|
+
rereolved = true;
|
|
152
|
+
this.resolveCache.delete(url);
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
this.emitCheck(out.assessment, t0, false);
|
|
156
|
+
return out.assessment;
|
|
157
|
+
}
|
|
158
|
+
const a = out.verdict;
|
|
159
|
+
const ttl = a.verdict === "BLOCK" ? this.blockTtlMs : this.decisionTtlMs;
|
|
160
|
+
this.decisionCache.set(resourceId, {
|
|
161
|
+
assessment: a,
|
|
162
|
+
expiresAt: this.now() + ttl,
|
|
163
|
+
});
|
|
164
|
+
this.emitCheck(a, t0, false);
|
|
165
|
+
return a;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
emitCheck(a, t0, cacheHit) {
|
|
169
|
+
const outcome = a.kind === "unavailable"
|
|
170
|
+
? "unavailable"
|
|
171
|
+
: a.kind === "verdict"
|
|
172
|
+
? a.verdict === "ALLOW"
|
|
173
|
+
? "allow"
|
|
174
|
+
: a.verdict === "BLOCK"
|
|
175
|
+
? "deny"
|
|
176
|
+
: "hold"
|
|
177
|
+
: "hold";
|
|
178
|
+
this.metrics?.onCheck?.(outcome, this.now() - t0);
|
|
179
|
+
this.metrics?.onCache?.(cacheHit ? "hit" : "miss");
|
|
180
|
+
}
|
|
181
|
+
async resolveResourceId(url, deadline, callerSignal) {
|
|
182
|
+
const cached = this.resolveCache.get(url);
|
|
183
|
+
if (cached && cached.expiresAt > this.now()) {
|
|
184
|
+
if (cached.notInCatalog) {
|
|
185
|
+
return {
|
|
186
|
+
assessment: { kind: "not_in_catalog", checkedAt: this.iso(), cacheHit: true },
|
|
187
|
+
cacheHit: true,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
return { resourceId: cached.resourceId, cacheHit: true };
|
|
191
|
+
}
|
|
192
|
+
const r = await this.outbound(`${this.baseUrl}/api/v1/resolve?q=${encodeURIComponent(url)}`, "resolve", deadline, callerSignal);
|
|
193
|
+
if (r.failure)
|
|
194
|
+
return { assessment: this.unavailable(r.failure) };
|
|
195
|
+
if (r.status !== 200)
|
|
196
|
+
return { assessment: this.unavailable("invalid_response") };
|
|
197
|
+
const body = r.body;
|
|
198
|
+
if (body?.not_found?.reason === "not_in_catalog") {
|
|
199
|
+
this.resolveCache.set(url, {
|
|
200
|
+
notInCatalog: true,
|
|
201
|
+
expiresAt: this.now() + this.decisionTtlMs,
|
|
202
|
+
});
|
|
203
|
+
return { assessment: { kind: "not_in_catalog", checkedAt: this.iso() } };
|
|
204
|
+
}
|
|
205
|
+
const id = body?.resource?.resource_id;
|
|
206
|
+
if (typeof id === "string" && RESOURCE_ID_RE.test(id)) {
|
|
207
|
+
this.resolveCache.set(url, { resourceId: id, expiresAt: Infinity });
|
|
208
|
+
return { resourceId: id };
|
|
209
|
+
}
|
|
210
|
+
return { assessment: this.unavailable("invalid_response") };
|
|
211
|
+
}
|
|
212
|
+
async fetchDecision(resourceId, url, deadline, callerSignal) {
|
|
213
|
+
const qs = new URLSearchParams({ role: "payer", url });
|
|
214
|
+
const r = await this.outbound(`${this.baseUrl}/api/v1/resources/${resourceId}/decision?${qs}`, "decision", deadline, callerSignal);
|
|
215
|
+
if (r.failure)
|
|
216
|
+
return { assessment: this.unavailable(r.failure) };
|
|
217
|
+
if (r.status === 404) {
|
|
218
|
+
const b = r.body;
|
|
219
|
+
if (b?.error === "not_found") {
|
|
220
|
+
return {
|
|
221
|
+
assessment: this.unavailable("invalid_response"),
|
|
222
|
+
unknownResource: true,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
return { assessment: this.unavailable("invalid_response") };
|
|
226
|
+
}
|
|
227
|
+
if (r.status !== 200)
|
|
228
|
+
return { assessment: this.unavailable("invalid_response") };
|
|
229
|
+
const b = r.body;
|
|
230
|
+
if (b?.recommendation !== "ALLOW" && b?.recommendation !== "WARN" && b?.recommendation !== "BLOCK") {
|
|
231
|
+
return { assessment: this.unavailable("invalid_response") };
|
|
232
|
+
}
|
|
233
|
+
const vt = this.parseVerifiedTerms(b.verified_terms);
|
|
234
|
+
if (vt === "invalid")
|
|
235
|
+
return { assessment: this.unavailable("invalid_response") };
|
|
236
|
+
return {
|
|
237
|
+
verdict: {
|
|
238
|
+
kind: "verdict",
|
|
239
|
+
verdict: b.recommendation,
|
|
240
|
+
reasonCodes: Array.isArray(b.reason_codes)
|
|
241
|
+
? b.reason_codes.filter((c) => typeof c === "string")
|
|
242
|
+
: [],
|
|
243
|
+
verifiedTerms: vt,
|
|
244
|
+
evidenceAgeSeconds: typeof b.evidence_age?.days_since_last_delivery === "number"
|
|
245
|
+
? b.evidence_age.days_since_last_delivery * 86_400
|
|
246
|
+
: undefined,
|
|
247
|
+
degraded: b.degraded === true,
|
|
248
|
+
checkedAt: this.iso(),
|
|
249
|
+
},
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
parseVerifiedTerms(v) {
|
|
253
|
+
if (v === null || v === undefined)
|
|
254
|
+
return null;
|
|
255
|
+
if (typeof v !== "object")
|
|
256
|
+
return "invalid";
|
|
257
|
+
const t = v;
|
|
258
|
+
const { pay_to, asset, amount, network, scheme } = t;
|
|
259
|
+
if (typeof pay_to !== "string" ||
|
|
260
|
+
typeof asset !== "string" ||
|
|
261
|
+
typeof amount !== "string" ||
|
|
262
|
+
!/^\d+$/.test(amount) ||
|
|
263
|
+
typeof network !== "string" ||
|
|
264
|
+
typeof scheme !== "string") {
|
|
265
|
+
return "invalid";
|
|
266
|
+
}
|
|
267
|
+
const factor = LEDGER_UNIT_FACTOR[network] ?? 1n;
|
|
268
|
+
return {
|
|
269
|
+
payTo: pay_to,
|
|
270
|
+
asset,
|
|
271
|
+
amount: (BigInt(amount) * factor).toString(),
|
|
272
|
+
network,
|
|
273
|
+
scheme,
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
unavailable(failure) {
|
|
277
|
+
return { kind: "unavailable", failure, checkedAt: this.iso() };
|
|
278
|
+
}
|
|
279
|
+
iso() {
|
|
280
|
+
return new Date(this.now()).toISOString();
|
|
281
|
+
}
|
|
282
|
+
async outbound(url, endpoint, deadline, callerSignal) {
|
|
283
|
+
for (;;) {
|
|
284
|
+
const remaining = deadline - this.now();
|
|
285
|
+
if (remaining <= 0)
|
|
286
|
+
return { failure: "timeout" };
|
|
287
|
+
const t = this.bucket.tryAcquire();
|
|
288
|
+
if (t.ok)
|
|
289
|
+
break;
|
|
290
|
+
if (this.now() + t.waitMs > deadline)
|
|
291
|
+
return { failure: "rate_limited" };
|
|
292
|
+
await this.sleep(t.waitMs);
|
|
293
|
+
}
|
|
294
|
+
const remaining = deadline - this.now();
|
|
295
|
+
if (remaining <= 0)
|
|
296
|
+
return { failure: "timeout" };
|
|
297
|
+
const perRequest = Math.min(this.connectTimeoutMs, remaining);
|
|
298
|
+
const signals = [AbortSignal.timeout(perRequest)];
|
|
299
|
+
if (callerSignal)
|
|
300
|
+
signals.push(callerSignal);
|
|
301
|
+
const signal = typeof AbortSignal.any === "function"
|
|
302
|
+
? AbortSignal.any(signals)
|
|
303
|
+
: signals[0];
|
|
304
|
+
let res;
|
|
305
|
+
try {
|
|
306
|
+
res = await this.fetch(url, {
|
|
307
|
+
method: "GET",
|
|
308
|
+
headers: { accept: "application/json" },
|
|
309
|
+
signal,
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
catch (e) {
|
|
313
|
+
const name = e?.name;
|
|
314
|
+
return {
|
|
315
|
+
failure: name === "AbortError" || name === "TimeoutError"
|
|
316
|
+
? "timeout"
|
|
317
|
+
: "network_error",
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
if (res.status === 429) {
|
|
321
|
+
this.metrics?.onRateLimited?.(endpoint);
|
|
322
|
+
return { failure: "rate_limited" };
|
|
323
|
+
}
|
|
324
|
+
if (res.status === 503)
|
|
325
|
+
return { failure: "degraded" };
|
|
326
|
+
if (res.status >= 500)
|
|
327
|
+
return { failure: "upstream_5xx" };
|
|
328
|
+
let body;
|
|
329
|
+
try {
|
|
330
|
+
body = await res.json();
|
|
331
|
+
}
|
|
332
|
+
catch {
|
|
333
|
+
return { failure: "invalid_response" };
|
|
334
|
+
}
|
|
335
|
+
return { status: res.status, body };
|
|
336
|
+
}
|
|
337
|
+
}
|
|
@@ -10,6 +10,15 @@ export interface DepositWalletClient {
|
|
|
10
10
|
functionName: string;
|
|
11
11
|
args: readonly unknown[];
|
|
12
12
|
}): Promise<`0x${string}`>;
|
|
13
|
+
readContract?(args: {
|
|
14
|
+
address: `0x${string}`;
|
|
15
|
+
abi: unknown;
|
|
16
|
+
functionName: string;
|
|
17
|
+
args: readonly unknown[];
|
|
18
|
+
}): Promise<unknown>;
|
|
19
|
+
waitForTransactionReceipt?(args: {
|
|
20
|
+
hash: `0x${string}`;
|
|
21
|
+
}): Promise<unknown>;
|
|
13
22
|
}
|
|
14
23
|
export interface DepositResult {
|
|
15
24
|
txHash: `0x${string}`;
|
package/dist/gateway/deposit.js
CHANGED
|
@@ -50,18 +50,45 @@ export async function depositToGateway(args) {
|
|
|
50
50
|
if (amount <= 0n) {
|
|
51
51
|
throw new Error(`deposit amount must be > 0 (got ${args.amountUsd})`);
|
|
52
52
|
}
|
|
53
|
-
const
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
53
|
+
const depositor = typeof wallet.account === "string"
|
|
54
|
+
? wallet.account
|
|
55
|
+
: wallet.account?.address;
|
|
56
|
+
let needsApproval = true;
|
|
57
|
+
if (wallet.readContract && depositor) {
|
|
58
|
+
try {
|
|
59
|
+
const allowance = (await wallet.readContract({
|
|
60
|
+
address: chain.usdc,
|
|
61
|
+
abi: erc20Abi,
|
|
62
|
+
functionName: "allowance",
|
|
63
|
+
args: [depositor, chain.gatewayWallet],
|
|
64
|
+
}));
|
|
65
|
+
needsApproval = allowance < amount;
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
needsApproval = true;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
let approvalTxHash;
|
|
72
|
+
if (needsApproval) {
|
|
73
|
+
approvalTxHash = await wallet.writeContract({
|
|
74
|
+
address: chain.usdc,
|
|
75
|
+
abi: erc20Abi,
|
|
76
|
+
functionName: "approve",
|
|
77
|
+
args: [chain.gatewayWallet, amount],
|
|
78
|
+
});
|
|
79
|
+
if (wallet.waitForTransactionReceipt) {
|
|
80
|
+
await wallet.waitForTransactionReceipt({ hash: approvalTxHash });
|
|
81
|
+
}
|
|
82
|
+
}
|
|
59
83
|
const txHash = await wallet.writeContract({
|
|
60
84
|
address: chain.gatewayWallet,
|
|
61
85
|
abi: GATEWAY_WALLET_ABI,
|
|
62
86
|
functionName: "deposit",
|
|
63
87
|
args: [chain.usdc, amount],
|
|
64
88
|
});
|
|
89
|
+
if (wallet.waitForTransactionReceipt) {
|
|
90
|
+
await wallet.waitForTransactionReceipt({ hash: txHash });
|
|
91
|
+
}
|
|
65
92
|
const eta = new Date(Date.now() + estimateFor(chain) * 1000);
|
|
66
93
|
return {
|
|
67
94
|
txHash,
|
package/dist/index.d.ts
CHANGED
|
@@ -33,3 +33,6 @@ export * from "./buyer/client.js";
|
|
|
33
33
|
export * from "./buyer/guard.js";
|
|
34
34
|
export * from "./buyer/risk-guard.js";
|
|
35
35
|
export * from "./buyer/paginate.js";
|
|
36
|
+
export * from "./buyer/counterparty.js";
|
|
37
|
+
export * from "./counterparty/index.js";
|
|
38
|
+
export * from "./counterparty/vet402-client.js";
|
package/dist/index.js
CHANGED
|
@@ -33,3 +33,6 @@ export * from "./buyer/client.js";
|
|
|
33
33
|
export * from "./buyer/guard.js";
|
|
34
34
|
export * from "./buyer/risk-guard.js";
|
|
35
35
|
export * from "./buyer/paginate.js";
|
|
36
|
+
export * from "./buyer/counterparty.js";
|
|
37
|
+
export * from "./counterparty/index.js";
|
|
38
|
+
export * from "./counterparty/vet402-client.js";
|
package/dist/middleware.js
CHANGED
|
@@ -72,7 +72,9 @@ export function requirePayment(price, opts) {
|
|
|
72
72
|
const router = opts.router ?? createPaymentRouter(opts);
|
|
73
73
|
const methods = opts.methods?.map((m) => m.toUpperCase());
|
|
74
74
|
return async (c, next) => {
|
|
75
|
-
|
|
75
|
+
const reqMethod = c.req.method.toUpperCase();
|
|
76
|
+
if (methods &&
|
|
77
|
+
!methods.includes(reqMethod === "HEAD" ? "GET" : reqMethod)) {
|
|
76
78
|
return next();
|
|
77
79
|
}
|
|
78
80
|
if (opts.onBeforeChallenge) {
|
|
@@ -179,7 +181,13 @@ export function requirePayment(price, opts) {
|
|
|
179
181
|
amount: requirements.amount,
|
|
180
182
|
};
|
|
181
183
|
c.set("payment", payment);
|
|
182
|
-
|
|
184
|
+
try {
|
|
185
|
+
await opts.onSettleResult?.({ c, ok: true, payment });
|
|
186
|
+
}
|
|
187
|
+
catch (hookErr) {
|
|
188
|
+
console.error(`[x402] onSettleResult hook error (post-settle, swallowed): ` +
|
|
189
|
+
(hookErr instanceof Error ? hookErr.message : String(hookErr)));
|
|
190
|
+
}
|
|
183
191
|
await next();
|
|
184
192
|
if (c.error && opts.failureStore) {
|
|
185
193
|
await recordFailure(opts.failureStore, {
|
package/package.json
CHANGED