@agentbadge/circle-payments 0.1.20 → 0.1.27
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 +0 -31
- package/dist/buyer/client.d.ts +2 -3
- package/dist/buyer/client.js +9 -15
- package/dist/buyer/counterparty.d.ts +27 -0
- package/dist/buyer/counterparty.js +35 -0
- package/dist/cli/pay.js +39 -16
- 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 +3 -0
- package/dist/counterparty/policy.js +59 -0
- package/dist/counterparty/sanitize-url.d.ts +2 -0
- package/dist/counterparty/sanitize-url.js +87 -0
- package/dist/counterparty/terms.d.ts +17 -0
- package/dist/counterparty/terms.js +134 -0
- package/dist/counterparty/types.d.ts +94 -0
- package/dist/counterparty/types.js +1 -0
- package/dist/counterparty/vet402-client.d.ts +53 -0
- package/dist/counterparty/vet402-client.js +407 -0
- package/dist/escrow/erc8183.d.ts +1 -215
- package/dist/escrow/erc8183.js +12 -181
- package/dist/index.d.ts +3 -2
- package/dist/index.js +3 -2
- package/dist/middleware.js +10 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -260,37 +260,6 @@ const items = await paginateAll(async (cursor) =>
|
|
|
260
260
|
Errors: `PaymentRefusedError{field,value}` (challenge refused),
|
|
261
261
|
`CapExceededError`, `BudgetExhaustedError`, `PaymentNotAcceptedError`.
|
|
262
262
|
|
|
263
|
-
### Pre-payment risk guard (EPIC-204)
|
|
264
|
-
|
|
265
|
-
`beforePayment` vets every `payTo` advertised in the 402 BEFORE signing —
|
|
266
|
-
a `{block: reason}` becomes `PaymentRefusedError` and no money moves.
|
|
267
|
-
`createRiskGuard` wraps a payment-forensics risk API
|
|
268
|
-
(`GET /api/v1/risk/:address`); the endpoint is pluggable (ours on Arc or
|
|
269
|
-
any compatible service).
|
|
270
|
-
|
|
271
|
-
```ts
|
|
272
|
-
import { createPayingClient, createRiskGuard, viemSigner }
|
|
273
|
-
from "@agentbadge/circle-payments";
|
|
274
|
-
|
|
275
|
-
const client = createPayingClient({
|
|
276
|
-
caps,
|
|
277
|
-
signer: viemSigner(walletClient),
|
|
278
|
-
beforePayment: createRiskGuard({
|
|
279
|
-
endpoint: "https://agentbadge.xyz/api/v1/risk", // or any compatible API
|
|
280
|
-
minOrganicShare: 0.3, // organic revenue floor
|
|
281
|
-
allowNoData: true, // new sellers have to start somewhere
|
|
282
|
-
onRiskError: "allow", // "block" = fail-closed
|
|
283
|
-
timeoutMs: 2000, // never hang the 402-loop
|
|
284
|
-
}),
|
|
285
|
-
checkAllOffers: true, // default: vet every accepts[] payTo
|
|
286
|
-
});
|
|
287
|
-
```
|
|
288
|
-
|
|
289
|
-
Verdicts: `block` (or `caution` below the floor) refuses; `no_data`
|
|
290
|
-
follows `allowNoData`; endpoint errors/429s follow `onRiskError`.
|
|
291
|
-
CLI: `agentbadge pay <url> --risk-check`
|
|
292
|
-
(`AGENTBADGE_RISK_ENDPOINT` to override).
|
|
293
|
-
|
|
294
263
|
### CLI: `agentbadge pay`
|
|
295
264
|
|
|
296
265
|
```bash
|
package/dist/buyer/client.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type PaymentCaps } from "./caps.js";
|
|
2
|
-
import type
|
|
2
|
+
import { type CounterpartyGateOptions } from "./counterparty.js";
|
|
3
3
|
import { type SpendTracker } from "./session.js";
|
|
4
4
|
import { type DepositResult } from "../gateway/deposit.js";
|
|
5
5
|
export interface BuyerSigner {
|
|
@@ -48,9 +48,8 @@ export interface PayingClientOptions {
|
|
|
48
48
|
scheme?: string;
|
|
49
49
|
resource?: string;
|
|
50
50
|
}) => void;
|
|
51
|
+
counterparty?: CounterpartyGateOptions;
|
|
51
52
|
gateway?: GatewayFundingOptions;
|
|
52
|
-
beforePayment?: BeforePaymentFn;
|
|
53
|
-
checkAllOffers?: boolean;
|
|
54
53
|
}
|
|
55
54
|
export interface PayingClient {
|
|
56
55
|
request(url: string, init?: RequestInit): Promise<Response>;
|
package/dist/buyer/client.js
CHANGED
|
@@ -4,6 +4,8 @@ import { decode402 } from "../identity/verify-passport.js";
|
|
|
4
4
|
import { signPayerChallenge } from "../payer-bind.js";
|
|
5
5
|
import { assertCaps, PaymentNotAcceptedError, } from "./caps.js";
|
|
6
6
|
import { 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) {
|
|
@@ -219,21 +221,13 @@ export function createPayingClient(opts) {
|
|
|
219
221
|
throw new PaymentRefusedError(verdict.field, verdict.value, verdict.reason);
|
|
220
222
|
}
|
|
221
223
|
const req = verdict.requirements;
|
|
222
|
-
if (opts.
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
}
|
|
230
|
-
targets.set(`${req.payTo}:${req.network}`, { payTo: req.payTo, accept: req });
|
|
231
|
-
for (const { payTo, accept } of targets.values()) {
|
|
232
|
-
const decision = await opts.beforePayment(payTo, accept);
|
|
233
|
-
if (decision !== "allow") {
|
|
234
|
-
throw new PaymentRefusedError("payTo", payTo, decision.block);
|
|
235
|
-
}
|
|
236
|
-
}
|
|
224
|
+
if (opts.counterparty) {
|
|
225
|
+
await applyCounterpartyGate({
|
|
226
|
+
opts: opts.counterparty,
|
|
227
|
+
policy: opts.counterparty.policy ?? createCounterpartyPolicy(),
|
|
228
|
+
resourceUrl: url,
|
|
229
|
+
requirements: req,
|
|
230
|
+
});
|
|
237
231
|
}
|
|
238
232
|
tracker.tryReserve(req.amount);
|
|
239
233
|
if (req.scheme === "gateway-batch") {
|
|
@@ -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
|
@@ -6,7 +6,8 @@ import { decode402 } from "../identity/verify-passport.js";
|
|
|
6
6
|
import { assertCaps, BudgetExhaustedError, CapExceededError, PaymentNotAcceptedError, } from "../buyer/caps.js";
|
|
7
7
|
import { atomicToUsd, validateAccepts, } from "../buyer/accepts.js";
|
|
8
8
|
import { createPayingClient, PaymentRefusedError, } from "../buyer/client.js";
|
|
9
|
-
import {
|
|
9
|
+
import { createCounterpartyPolicy } from "../counterparty/policy.js";
|
|
10
|
+
import { Vet402Client, vet402ClientOptionsFromEnv, } from "../counterparty/vet402-client.js";
|
|
10
11
|
import { gatewayBalance } from "../gateway/deposit.js";
|
|
11
12
|
const EXIT_OK = 0;
|
|
12
13
|
const EXIT_REFUSED = 2;
|
|
@@ -22,8 +23,10 @@ Optional:
|
|
|
22
23
|
--body <json> request body
|
|
23
24
|
--network <caip2> restrict to one network (e.g. eip155:5042002)
|
|
24
25
|
--auto-deposit <usd> auto top-up Gateway balance when short
|
|
25
|
-
--
|
|
26
|
-
(
|
|
26
|
+
--skip-counterparty-check
|
|
27
|
+
skip the vet402 counterparty check (default on;
|
|
28
|
+
COUNTERPARTY_CHECK_MODE=off|shadow|enforce,
|
|
29
|
+
COUNTERPARTY_VET402_BASE_URL to override)
|
|
27
30
|
--print-only show payment details, never sign
|
|
28
31
|
--help this text
|
|
29
32
|
|
|
@@ -32,7 +35,7 @@ Secrets:
|
|
|
32
35
|
|
|
33
36
|
Exit codes: 0 ok · 2 refusal/cap/budget/usage · 3 transport`;
|
|
34
37
|
function parseArgs(argv) {
|
|
35
|
-
const args = { method: "GET", printOnly: false, help: false,
|
|
38
|
+
const args = { method: "GET", printOnly: false, help: false, skipCounterpartyCheck: false };
|
|
36
39
|
const takeValue = (i, flag) => {
|
|
37
40
|
const v = argv[i + 1];
|
|
38
41
|
if (v === undefined || v.startsWith("--")) {
|
|
@@ -63,8 +66,8 @@ function parseArgs(argv) {
|
|
|
63
66
|
case "--auto-deposit":
|
|
64
67
|
args.autoDeposit = takeValue(i++, a);
|
|
65
68
|
break;
|
|
66
|
-
case "--
|
|
67
|
-
args.
|
|
69
|
+
case "--skip-counterparty-check":
|
|
70
|
+
args.skipCounterpartyCheck = true;
|
|
68
71
|
break;
|
|
69
72
|
case "--print-only":
|
|
70
73
|
args.printOnly = true;
|
|
@@ -225,6 +228,35 @@ export async function runPay(argv, env = process.env, io = {}) {
|
|
|
225
228
|
return wc.writeContract(wcArgs);
|
|
226
229
|
},
|
|
227
230
|
};
|
|
231
|
+
let counterparty;
|
|
232
|
+
if (args.skipCounterpartyCheck) {
|
|
233
|
+
err("counterparty check skipped (--skip-counterparty-check)");
|
|
234
|
+
}
|
|
235
|
+
else {
|
|
236
|
+
const mode = (env.COUNTERPARTY_CHECK_MODE ??
|
|
237
|
+
"enforce");
|
|
238
|
+
if (mode !== "off") {
|
|
239
|
+
counterparty = {
|
|
240
|
+
checker: new Vet402Client({
|
|
241
|
+
...vet402ClientOptionsFromEnv(env),
|
|
242
|
+
...(env.COUNTERPARTY_VET402_BASE_URL
|
|
243
|
+
? { baseUrl: env.COUNTERPARTY_VET402_BASE_URL }
|
|
244
|
+
: {}),
|
|
245
|
+
fetchImpl,
|
|
246
|
+
}),
|
|
247
|
+
policy: createCounterpartyPolicy(),
|
|
248
|
+
mode,
|
|
249
|
+
onDecision: (rec) => {
|
|
250
|
+
const verdict = rec.assessment.kind === "verdict"
|
|
251
|
+
? rec.assessment.verdict
|
|
252
|
+
: rec.assessment.kind;
|
|
253
|
+
err(`[counterparty:${mode}] ${verdict} → ${rec.decision.action}` +
|
|
254
|
+
` (${rec.decision.reasonCode}) terms=${rec.termsMatch.result}` +
|
|
255
|
+
` cacheHit=${rec.assessment.cacheHit}`);
|
|
256
|
+
},
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
}
|
|
228
260
|
const client = createPayingClient({
|
|
229
261
|
caps,
|
|
230
262
|
signer,
|
|
@@ -232,16 +264,7 @@ export async function runPay(argv, env = process.env, io = {}) {
|
|
|
232
264
|
...(args.autoDeposit
|
|
233
265
|
? { gateway: { autoDepositUsd: args.autoDeposit } }
|
|
234
266
|
: {}),
|
|
235
|
-
...(
|
|
236
|
-
? {
|
|
237
|
-
beforePayment: createRiskGuard({
|
|
238
|
-
...(env.AGENTBADGE_RISK_ENDPOINT
|
|
239
|
-
? { endpoint: env.AGENTBADGE_RISK_ENDPOINT }
|
|
240
|
-
: {}),
|
|
241
|
-
fetchImpl,
|
|
242
|
-
}),
|
|
243
|
-
}
|
|
244
|
-
: {}),
|
|
267
|
+
...(counterparty ? { counterparty } : {}),
|
|
245
268
|
});
|
|
246
269
|
try {
|
|
247
270
|
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,59 @@
|
|
|
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 DEGRADED = {
|
|
7
|
+
action: "hold",
|
|
8
|
+
reasonCode: "counterparty_degraded",
|
|
9
|
+
holdHint: "counterparty_unmeasured",
|
|
10
|
+
};
|
|
11
|
+
export const EVIDENCE_STALE_SECONDS = 30 * 86_400;
|
|
12
|
+
const BLOCK_DENY = { action: "deny", reasonCode: "counterparty_blocked" };
|
|
13
|
+
const UNAVAILABLE = {
|
|
14
|
+
action: "unavailable",
|
|
15
|
+
reasonCode: "counterparty_unavailable",
|
|
16
|
+
};
|
|
17
|
+
const ALLOW = { action: "allow", reasonCode: "allowed" };
|
|
18
|
+
function fromTerms(t) {
|
|
19
|
+
switch (t.result) {
|
|
20
|
+
case "mismatch":
|
|
21
|
+
return TERMS_DENY;
|
|
22
|
+
case "uncomparable":
|
|
23
|
+
return TERMS_UNCOMPARABLE;
|
|
24
|
+
default:
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function fromVerdict(a, termsMatch) {
|
|
29
|
+
if (a.verdict === "BLOCK")
|
|
30
|
+
return BLOCK_DENY;
|
|
31
|
+
const terms = fromTerms(termsMatch);
|
|
32
|
+
if (terms)
|
|
33
|
+
return terms;
|
|
34
|
+
if (a.degraded || (a.evidenceAgeSeconds ?? 0) > EVIDENCE_STALE_SECONDS)
|
|
35
|
+
return DEGRADED;
|
|
36
|
+
if (a.verdict === "WARN")
|
|
37
|
+
return WARN;
|
|
38
|
+
if (termsMatch.result === "unmeasured")
|
|
39
|
+
return UNMEASURED;
|
|
40
|
+
return ALLOW;
|
|
41
|
+
}
|
|
42
|
+
class CounterpartyPolicyImpl {
|
|
43
|
+
evaluate(input) {
|
|
44
|
+
const { assessment, termsMatch } = input;
|
|
45
|
+
switch (assessment.kind) {
|
|
46
|
+
case "unavailable":
|
|
47
|
+
return UNAVAILABLE;
|
|
48
|
+
case "rejected":
|
|
49
|
+
case "not_in_catalog":
|
|
50
|
+
case "privacy_unmeasurable":
|
|
51
|
+
return UNMEASURED;
|
|
52
|
+
case "verdict":
|
|
53
|
+
return fromVerdict(assessment, termsMatch);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
export function createCounterpartyPolicy() {
|
|
58
|
+
return new CounterpartyPolicyImpl();
|
|
59
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
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
|
+
const B64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
5
|
+
const TOKEN_PREFIX_RE = /^(?:sk[-_]|xox[abprs]?[-_]|gh[opsur]_|github_pat_|AKIA[0-9A-Z]{16}|AIza|ya29\.|npm_[A-Za-z0-9]{30,}|dop_v1_|eyJ[A-Za-z0-9_-]{8,}\.)/;
|
|
6
|
+
const PARAM_NAME_RE = /(?:^|;)\s*(?:jsessionid|key|token|sig|signature|auth|secret|passwd|password|session|sid|api[-_]?key|access[-_]?token|bearer)\s*=/i;
|
|
7
|
+
function looksSecretValue(s) {
|
|
8
|
+
if (s === "")
|
|
9
|
+
return false;
|
|
10
|
+
if (JWT_RE.test(s))
|
|
11
|
+
return true;
|
|
12
|
+
if (TOKEN_PREFIX_RE.test(s))
|
|
13
|
+
return true;
|
|
14
|
+
if (HEX_LIKE_RE.test(s))
|
|
15
|
+
return true;
|
|
16
|
+
if (s.length >= 32) {
|
|
17
|
+
if (B64URL_RE.test(s) &&
|
|
18
|
+
/\d/.test(s) &&
|
|
19
|
+
(/[A-Z]/.test(s) || /^[a-z0-9]+$/.test(s))) {
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
if (B64_RE.test(s) && /[a-zA-Z]/.test(s) && /\d/.test(s))
|
|
23
|
+
return true;
|
|
24
|
+
const parts = s.split(".");
|
|
25
|
+
if (parts.length >= 3 &&
|
|
26
|
+
parts.every((p) => p.length >= 8 && B64URL_RE.test(p))) {
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
function looksSecretSegment(segment) {
|
|
33
|
+
if (segment === "")
|
|
34
|
+
return false;
|
|
35
|
+
let s = segment;
|
|
36
|
+
try {
|
|
37
|
+
s = decodeURIComponent(segment);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
}
|
|
41
|
+
if (PARAM_NAME_RE.test(s) || s.includes(";"))
|
|
42
|
+
return true;
|
|
43
|
+
return looksSecretValue(s);
|
|
44
|
+
}
|
|
45
|
+
function looksSecretHostname(hostname) {
|
|
46
|
+
let h = hostname;
|
|
47
|
+
try {
|
|
48
|
+
h = decodeURIComponent(hostname);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
}
|
|
52
|
+
return h.split(".").some((label) => looksSecretValue(label));
|
|
53
|
+
}
|
|
54
|
+
export function sanitizeUrlForCheck(raw) {
|
|
55
|
+
let u;
|
|
56
|
+
try {
|
|
57
|
+
u = new URL(raw);
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return { ok: false, block: "unparseable" };
|
|
61
|
+
}
|
|
62
|
+
if (u.protocol !== "https:") {
|
|
63
|
+
return { ok: false, block: "non_https_scheme" };
|
|
64
|
+
}
|
|
65
|
+
if (u.username !== "" || u.password !== "") {
|
|
66
|
+
return { ok: false, block: "credentials" };
|
|
67
|
+
}
|
|
68
|
+
if (raw.includes("?")) {
|
|
69
|
+
return { ok: false, block: "query" };
|
|
70
|
+
}
|
|
71
|
+
if (raw.includes("#")) {
|
|
72
|
+
return { ok: false, block: "fragment" };
|
|
73
|
+
}
|
|
74
|
+
if (looksSecretHostname(u.hostname)) {
|
|
75
|
+
return {
|
|
76
|
+
ok: false,
|
|
77
|
+
block: "secret_hostname_label",
|
|
78
|
+
segmentLength: u.hostname.length,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
for (const seg of u.pathname.split("/")) {
|
|
82
|
+
if (looksSecretSegment(seg)) {
|
|
83
|
+
return { ok: false, block: "secret_path_segment", segmentLength: seg.length };
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return { ok: true, url: `${u.origin}${u.pathname}` };
|
|
87
|
+
}
|
|
@@ -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{1,78}$/.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
|
+
}
|