@agentbadge/circle-payments 0.1.19 → 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/escrow/erc8183.d.ts +215 -1
- package/dist/escrow/erc8183.js +181 -12
- 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 +3 -3
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;
|