@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.
@@ -0,0 +1,94 @@
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_degraded" | "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 interface Vet402RejectedAssessment extends AssessmentBase {
47
+ kind: "rejected";
48
+ httpStatus?: number;
49
+ }
50
+ export type Vet402Assessment = Vet402VerdictAssessment | Vet402NotInCatalogAssessment | Vet402RejectedAssessment | Vet402PrivacyUnmeasurableAssessment | Vet402UnavailableAssessment;
51
+ export type TermsMatchResult = "match" | "mismatch" | "uncomparable" | "unmeasured";
52
+ export interface TermsFieldDiff {
53
+ verified: string;
54
+ offered: string;
55
+ }
56
+ export interface TermsMatch {
57
+ result: TermsMatchResult;
58
+ reason?: string;
59
+ diff?: Partial<Record<keyof NormalizedTerms, TermsFieldDiff>>;
60
+ }
61
+ export interface PaymentDecision {
62
+ action: CounterpartyVerdict;
63
+ reasonCode: CounterpartyReasonCode;
64
+ holdHint?: Extract<ApprovalReason, "counterparty_warn" | "counterparty_unmeasured">;
65
+ }
66
+ export interface CounterpartyCheckInput {
67
+ resourceUrl: string;
68
+ signal?: AbortSignal;
69
+ wallet?: string;
70
+ }
71
+ export interface CounterpartyChecker {
72
+ check(input: CounterpartyCheckInput): Promise<Vet402Assessment>;
73
+ }
74
+ export interface CounterpartyPolicy {
75
+ evaluate(input: {
76
+ assessment: Vet402Assessment;
77
+ termsMatch: TermsMatch;
78
+ }): PaymentDecision;
79
+ }
80
+ export type SanitizeUrlBlock = "unparseable" | "non_https_scheme" | "credentials" | "query" | "fragment" | "secret_path_segment" | "secret_hostname_label";
81
+ export type SanitizeUrlResult = {
82
+ ok: true;
83
+ url: string;
84
+ } | {
85
+ ok: false;
86
+ block: SanitizeUrlBlock;
87
+ segmentLength?: number;
88
+ };
89
+ export interface DealFingerprintInput {
90
+ wallet: string;
91
+ url: string;
92
+ offer: OfferedTerms;
93
+ }
94
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,53 @@
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
+ perWalletRpm?: number;
12
+ connectTimeoutMs?: number;
13
+ totalTimeoutMs?: number;
14
+ resolveCacheSize?: number;
15
+ decisionCacheSize?: number;
16
+ metrics?: CounterpartyMetricsHooks;
17
+ }
18
+ export interface CounterpartyMetricsHooks {
19
+ onCheck?(outcome: "allow" | "hold" | "deny" | "unavailable", ms: number): void;
20
+ onCache?(result: "hit" | "miss"): void;
21
+ onRateLimited?(endpoint: "resolve" | "decision"): void;
22
+ }
23
+ export declare function vet402ClientOptionsFromEnv(env: Record<string, string | undefined>): Pick<Vet402ClientOptions, "decisionTtlMs" | "blockTtlMs" | "maxRpm" | "perWalletRpm" | "connectTimeoutMs" | "totalTimeoutMs">;
24
+ export declare class Vet402Client implements CounterpartyChecker {
25
+ private baseUrl;
26
+ private fetch;
27
+ private now;
28
+ private sleep;
29
+ private decisionTtlMs;
30
+ private blockTtlMs;
31
+ private connectTimeoutMs;
32
+ private totalTimeoutMs;
33
+ private metrics?;
34
+ private resolveCache;
35
+ private decisionCache;
36
+ private inflight;
37
+ private bucket;
38
+ private perWalletRpm;
39
+ private walletBuckets;
40
+ constructor(opts?: Vet402ClientOptions);
41
+ private walletBucketFor;
42
+ check(input: CounterpartyCheckInput): Promise<Vet402Assessment>;
43
+ private runCheck;
44
+ private emitCheck;
45
+ private resolveResourceId;
46
+ private fetchDecision;
47
+ private parseVerifiedTerms;
48
+ private unavailable;
49
+ private rejected;
50
+ private iso;
51
+ private outbound;
52
+ }
53
+ export {};
@@ -0,0 +1,407 @@
1
+ import { sanitizeUrlForCheck } from "./sanitize-url.js";
2
+ import { normalizeNetwork } from "./terms.js";
3
+ export function vet402ClientOptionsFromEnv(env) {
4
+ const int = (k) => {
5
+ const v = env[k];
6
+ if (v === undefined || v === "")
7
+ return undefined;
8
+ const n = Number(v);
9
+ return Number.isFinite(n) && n > 0 ? n : undefined;
10
+ };
11
+ return {
12
+ decisionTtlMs: int("COUNTERPARTY_DECISION_TTL_MS"),
13
+ blockTtlMs: int("COUNTERPARTY_BLOCK_TTL_MS"),
14
+ maxRpm: int("COUNTERPARTY_MAX_RPM"),
15
+ perWalletRpm: int("COUNTERPARTY_WALLET_RPM"),
16
+ connectTimeoutMs: int("COUNTERPARTY_CONNECT_TIMEOUT_MS"),
17
+ totalTimeoutMs: int("COUNTERPARTY_TOTAL_TIMEOUT_MS"),
18
+ };
19
+ }
20
+ class LruCache {
21
+ maxSize;
22
+ map = new Map();
23
+ constructor(maxSize) {
24
+ this.maxSize = maxSize;
25
+ }
26
+ get(k) {
27
+ const v = this.map.get(k);
28
+ if (v !== undefined) {
29
+ this.map.delete(k);
30
+ this.map.set(k, v);
31
+ }
32
+ return v;
33
+ }
34
+ set(k, v) {
35
+ this.map.delete(k);
36
+ this.map.set(k, v);
37
+ if (this.map.size > this.maxSize) {
38
+ this.map.delete(this.map.keys().next().value);
39
+ }
40
+ }
41
+ delete(k) {
42
+ this.map.delete(k);
43
+ }
44
+ }
45
+ class TokenBucket {
46
+ capacity;
47
+ now;
48
+ tokens;
49
+ lastRefill;
50
+ constructor(capacity, now) {
51
+ this.capacity = capacity;
52
+ this.now = now;
53
+ this.tokens = capacity;
54
+ this.lastRefill = now();
55
+ }
56
+ refill() {
57
+ const t = this.now();
58
+ const rate = this.capacity / 60_000;
59
+ this.tokens = Math.min(this.capacity, this.tokens + (t - this.lastRefill) * rate);
60
+ this.lastRefill = t;
61
+ }
62
+ tryAcquire() {
63
+ this.refill();
64
+ if (this.tokens >= 1) {
65
+ this.tokens -= 1;
66
+ return { ok: true };
67
+ }
68
+ const rate = this.capacity / 60_000;
69
+ return { ok: false, waitMs: Math.ceil((1 - this.tokens) / rate) };
70
+ }
71
+ peekWaitMs() {
72
+ this.refill();
73
+ if (this.tokens >= 1)
74
+ return 0;
75
+ const rate = this.capacity / 60_000;
76
+ return Math.ceil((1 - this.tokens) / rate);
77
+ }
78
+ }
79
+ const LEDGER_UNIT_FACTOR = {
80
+ "eip155:56": 10n ** 12n,
81
+ "stellar:pubnet": 10n,
82
+ "stellar:testnet": 10n,
83
+ };
84
+ const RESOURCE_ID_RE = /^[0-9a-f]{64}$/;
85
+ export class Vet402Client {
86
+ baseUrl;
87
+ fetch;
88
+ now;
89
+ sleep;
90
+ decisionTtlMs;
91
+ blockTtlMs;
92
+ connectTimeoutMs;
93
+ totalTimeoutMs;
94
+ metrics;
95
+ resolveCache;
96
+ decisionCache;
97
+ inflight = new Map();
98
+ bucket;
99
+ perWalletRpm;
100
+ walletBuckets;
101
+ constructor(opts = {}) {
102
+ this.baseUrl = (opts.baseUrl ?? "https://vet402.com").replace(/\/+$/, "");
103
+ this.fetch = opts.fetchImpl ?? fetch;
104
+ this.now = opts.now ?? Date.now;
105
+ this.sleep =
106
+ opts.sleepImpl ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
107
+ this.decisionTtlMs = opts.decisionTtlMs ?? 5 * 60_000;
108
+ this.blockTtlMs = Math.max(opts.blockTtlMs ?? this.decisionTtlMs, this.decisionTtlMs);
109
+ this.connectTimeoutMs = opts.connectTimeoutMs ?? 2_000;
110
+ this.totalTimeoutMs = opts.totalTimeoutMs ?? 8_000;
111
+ this.metrics = opts.metrics;
112
+ this.resolveCache = new LruCache(opts.resolveCacheSize ?? 1024);
113
+ this.decisionCache = new LruCache(opts.decisionCacheSize ?? 1024);
114
+ this.bucket = new TokenBucket(Math.max(1, opts.maxRpm ?? 11), this.now);
115
+ this.perWalletRpm = Math.max(1, opts.perWalletRpm ?? 4);
116
+ this.walletBuckets = new LruCache(opts.decisionCacheSize ?? 1024);
117
+ }
118
+ walletBucketFor(wallet) {
119
+ if (!wallet)
120
+ return undefined;
121
+ const key = wallet.toLowerCase();
122
+ let b = this.walletBuckets.get(key);
123
+ if (!b) {
124
+ b = new TokenBucket(this.perWalletRpm, this.now);
125
+ this.walletBuckets.set(key, b);
126
+ }
127
+ return b;
128
+ }
129
+ async check(input) {
130
+ const t0 = this.now();
131
+ const s = sanitizeUrlForCheck(input.resourceUrl);
132
+ if (!s.ok) {
133
+ const a = {
134
+ kind: "privacy_unmeasurable",
135
+ sanitizeBlock: s.block,
136
+ checkedAt: new Date(t0).toISOString(),
137
+ };
138
+ this.metrics?.onCheck?.("hold", this.now() - t0);
139
+ return a;
140
+ }
141
+ const key = s.url;
142
+ const existing = this.inflight.get(key);
143
+ if (existing) {
144
+ const a = await existing;
145
+ this.emitCheck(a, t0, true);
146
+ return a;
147
+ }
148
+ const p = this.runCheck(s.url, t0, input.signal, input.wallet)
149
+ .finally(() => this.inflight.delete(key));
150
+ this.inflight.set(key, p);
151
+ return p;
152
+ }
153
+ async runCheck(url, t0, callerSignal, wallet) {
154
+ const deadline = t0 + this.totalTimeoutMs;
155
+ let rereolved = false;
156
+ for (;;) {
157
+ const resolved = await this.resolveResourceId(url, deadline, callerSignal, wallet);
158
+ if (resolved.assessment) {
159
+ this.emitCheck(resolved.assessment, t0, resolved.cacheHit === true);
160
+ return resolved.assessment;
161
+ }
162
+ const resourceId = resolved.resourceId;
163
+ const cached = this.decisionCache.get(resourceId);
164
+ if (cached && cached.expiresAt > this.now()) {
165
+ const a = { ...cached.assessment, cacheHit: true };
166
+ this.emitCheck(a, t0, true);
167
+ return a;
168
+ }
169
+ const out = await this.fetchDecision(resourceId, url, deadline, callerSignal, wallet);
170
+ if (out.assessment) {
171
+ if (out.assessment.kind === "unavailable" &&
172
+ out.assessment.failure === "invalid_response" &&
173
+ out.unknownResource &&
174
+ !rereolved) {
175
+ rereolved = true;
176
+ this.resolveCache.delete(url);
177
+ continue;
178
+ }
179
+ this.emitCheck(out.assessment, t0, false);
180
+ return out.assessment;
181
+ }
182
+ const a = out.verdict;
183
+ const ttl = a.verdict === "BLOCK" ? this.blockTtlMs : this.decisionTtlMs;
184
+ this.decisionCache.set(resourceId, {
185
+ assessment: a,
186
+ expiresAt: this.now() + ttl,
187
+ });
188
+ this.emitCheck(a, t0, false);
189
+ return a;
190
+ }
191
+ }
192
+ emitCheck(a, t0, cacheHit) {
193
+ const outcome = a.kind === "unavailable"
194
+ ? "unavailable"
195
+ : a.kind === "verdict"
196
+ ? a.verdict === "ALLOW"
197
+ ? "allow"
198
+ : a.verdict === "BLOCK"
199
+ ? "deny"
200
+ : "hold"
201
+ : "hold";
202
+ this.metrics?.onCheck?.(outcome, this.now() - t0);
203
+ this.metrics?.onCache?.(cacheHit ? "hit" : "miss");
204
+ }
205
+ async resolveResourceId(url, deadline, callerSignal, wallet) {
206
+ const cached = this.resolveCache.get(url);
207
+ if (cached && cached.expiresAt > this.now()) {
208
+ if (cached.notInCatalog) {
209
+ return {
210
+ assessment: { kind: "not_in_catalog", checkedAt: this.iso(), cacheHit: true },
211
+ cacheHit: true,
212
+ };
213
+ }
214
+ return { resourceId: cached.resourceId, cacheHit: true };
215
+ }
216
+ const r = await this.outbound(`${this.baseUrl}/api/v1/resolve?q=${encodeURIComponent(url)}`, "resolve", deadline, callerSignal, wallet);
217
+ if (r.failure)
218
+ return { assessment: this.unavailable(r.failure) };
219
+ if (r.status !== 200) {
220
+ const st = r.status ?? 0;
221
+ return {
222
+ assessment: st >= 400 && st < 500
223
+ ? this.rejected(st)
224
+ : this.unavailable("invalid_response"),
225
+ };
226
+ }
227
+ const body = r.body;
228
+ if (body?.not_found?.reason === "not_in_catalog") {
229
+ this.resolveCache.set(url, {
230
+ notInCatalog: true,
231
+ expiresAt: this.now() + this.decisionTtlMs,
232
+ });
233
+ return { assessment: { kind: "not_in_catalog", checkedAt: this.iso() } };
234
+ }
235
+ const id = body?.resource?.resource_id;
236
+ if (typeof id === "string" && RESOURCE_ID_RE.test(id)) {
237
+ this.resolveCache.set(url, { resourceId: id, expiresAt: Infinity });
238
+ return { resourceId: id };
239
+ }
240
+ return { assessment: this.unavailable("invalid_response") };
241
+ }
242
+ async fetchDecision(resourceId, url, deadline, callerSignal, wallet) {
243
+ const qs = new URLSearchParams({ role: "payer", url });
244
+ const r = await this.outbound(`${this.baseUrl}/api/v1/resources/${resourceId}/decision?${qs}`, "decision", deadline, callerSignal, wallet);
245
+ if (r.failure)
246
+ return { assessment: this.unavailable(r.failure) };
247
+ if (r.status === 404) {
248
+ const b = r.body;
249
+ if (b?.error === "not_found") {
250
+ return {
251
+ assessment: this.unavailable("invalid_response"),
252
+ unknownResource: true,
253
+ };
254
+ }
255
+ return { assessment: this.unavailable("invalid_response") };
256
+ }
257
+ if (r.status !== 200) {
258
+ const st = r.status ?? 0;
259
+ return {
260
+ assessment: st >= 400 && st < 500
261
+ ? this.rejected(st)
262
+ : this.unavailable("invalid_response"),
263
+ };
264
+ }
265
+ const b = r.body;
266
+ if (b?.recommendation !== "ALLOW" && b?.recommendation !== "WARN" && b?.recommendation !== "BLOCK") {
267
+ return { assessment: this.unavailable("invalid_response") };
268
+ }
269
+ const vt = this.parseVerifiedTerms(b.verified_terms);
270
+ if (vt === "invalid")
271
+ return { assessment: this.unavailable("invalid_response") };
272
+ return {
273
+ verdict: {
274
+ kind: "verdict",
275
+ verdict: b.recommendation,
276
+ reasonCodes: Array.isArray(b.reason_codes)
277
+ ? b.reason_codes
278
+ .filter((c) => typeof c === "string")
279
+ .map((c) => c.replace(/[\u0000-\u001F\u007F]+/g, " ").slice(0, 200))
280
+ : [],
281
+ verifiedTerms: vt,
282
+ evidenceAgeSeconds: typeof b.evidence_age?.days_since_last_delivery === "number"
283
+ ? b.evidence_age.days_since_last_delivery * 86_400
284
+ : undefined,
285
+ degraded: b.degraded === true,
286
+ checkedAt: this.iso(),
287
+ },
288
+ };
289
+ }
290
+ parseVerifiedTerms(v) {
291
+ if (v === null || v === undefined)
292
+ return null;
293
+ if (typeof v !== "object")
294
+ return "invalid";
295
+ const t = v;
296
+ const { pay_to, asset, amount, network, scheme } = t;
297
+ if (typeof pay_to !== "string" ||
298
+ typeof asset !== "string" ||
299
+ typeof amount !== "string" ||
300
+ !/^\d+$/.test(amount) ||
301
+ amount.length > 78 ||
302
+ typeof network !== "string" ||
303
+ typeof scheme !== "string") {
304
+ return "invalid";
305
+ }
306
+ let factor = 1n;
307
+ try {
308
+ factor = LEDGER_UNIT_FACTOR[normalizeNetwork(network)] ?? 1n;
309
+ }
310
+ catch {
311
+ return "invalid";
312
+ }
313
+ return {
314
+ payTo: pay_to,
315
+ asset,
316
+ amount: (BigInt(amount) * factor).toString(),
317
+ network,
318
+ scheme,
319
+ };
320
+ }
321
+ unavailable(failure) {
322
+ return { kind: "unavailable", failure, checkedAt: this.iso() };
323
+ }
324
+ rejected(httpStatus) {
325
+ return { kind: "rejected", httpStatus, checkedAt: this.iso() };
326
+ }
327
+ iso() {
328
+ return new Date(this.now()).toISOString();
329
+ }
330
+ async outbound(url, endpoint, deadline, callerSignal, wallet) {
331
+ const wb = this.walletBucketFor(wallet);
332
+ for (;;) {
333
+ const remaining = deadline - this.now();
334
+ if (remaining <= 0)
335
+ return { failure: "timeout" };
336
+ const waitMs = Math.max(this.bucket.peekWaitMs(), wb?.peekWaitMs() ?? 0);
337
+ if (waitMs === 0) {
338
+ this.bucket.tryAcquire();
339
+ wb?.tryAcquire();
340
+ break;
341
+ }
342
+ if (this.now() + waitMs > deadline)
343
+ return { failure: "rate_limited" };
344
+ await this.sleep(waitMs);
345
+ }
346
+ const remaining = deadline - this.now();
347
+ if (remaining <= 0)
348
+ return { failure: "timeout" };
349
+ const perRequest = Math.min(this.connectTimeoutMs, remaining);
350
+ const signals = [AbortSignal.timeout(perRequest)];
351
+ if (callerSignal)
352
+ signals.push(callerSignal);
353
+ const signal = typeof AbortSignal.any === "function"
354
+ ? AbortSignal.any(signals)
355
+ : signals[0];
356
+ let res;
357
+ try {
358
+ res = await this.fetch(url, {
359
+ method: "GET",
360
+ headers: { accept: "application/json" },
361
+ signal,
362
+ });
363
+ }
364
+ catch (e) {
365
+ const name = e?.name;
366
+ return {
367
+ failure: name === "AbortError" || name === "TimeoutError"
368
+ ? "timeout"
369
+ : "network_error",
370
+ };
371
+ }
372
+ if (res.status === 429) {
373
+ this.metrics?.onRateLimited?.(endpoint);
374
+ const ra = Number(res.headers.get("retry-after"));
375
+ if (Number.isFinite(ra) && ra > 0 && ra * 1000 < deadline - this.now()) {
376
+ await this.sleep(ra * 1000);
377
+ try {
378
+ res = await this.fetch(url, {
379
+ method: "GET",
380
+ headers: { accept: "application/json" },
381
+ signal: AbortSignal.timeout(Math.max(0, deadline - this.now())),
382
+ });
383
+ }
384
+ catch {
385
+ return { failure: "rate_limited" };
386
+ }
387
+ if (res.status === 429)
388
+ return { failure: "rate_limited" };
389
+ }
390
+ else {
391
+ return { failure: "rate_limited" };
392
+ }
393
+ }
394
+ if (res.status === 503)
395
+ return { failure: "degraded" };
396
+ if (res.status >= 500)
397
+ return { failure: "upstream_5xx" };
398
+ let body;
399
+ try {
400
+ body = await res.json();
401
+ }
402
+ catch {
403
+ return { failure: "invalid_response" };
404
+ }
405
+ return { status: res.status, body };
406
+ }
407
+ }