@fiderail/seller 0.0.0-stage → 2.3.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 FideRail Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,52 @@
1
- # Temporary Holding Version
1
+ # @fiderail/seller
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Non-custodial seller-side HTTP 402 adapter and `x402#2299` `Trust-Provider` (`onBeforeSettle`) behavioral risk hook for [FideRail](https://fiderail.com). Issues x402 v2 payment challenges across Base, Solana, Arbitrum, and Polygon directly to seller wallets, screens incoming payers for reciprocal loops and sybil concentration without blocking legitimate pure payers, and serves `/.well-known/fiderail-service.json`.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @fiderail/seller
9
+ ```
10
+
11
+ ## Quick Usage
12
+
13
+ ```ts
14
+ import http from "node:http";
15
+ import { createRemoteTrustClient } from "@fiderail/core";
16
+ import { createFideRailSellerGuard, createTrustProviderHook } from "@fiderail/seller";
17
+
18
+ const engine = createRemoteTrustClient({ apiBaseUrl: "https://api.fiderail.com" });
19
+ const trustHook = createTrustProviderHook({ engine, blockLoops: true });
20
+
21
+ const sellerGuard = createFideRailSellerGuard({
22
+ payToBase: "0x7284d41b5b852f2bd4c99bdf95043d84452d299c",
23
+ priceUsdc: 0.01,
24
+ engine,
25
+ });
26
+
27
+ const server = http.createServer((req, res) => sellerGuard.handleRequest(req, res));
28
+ // Standalone x402#2299 hook usage:
29
+ // const verdict = await trustHook.onBeforeSettle({ chain: "base", payer, amountUsdc: 0.01 });
30
+ server.listen(8787);
31
+ ```
32
+
33
+ ## Key Exports
34
+
35
+ - **`createTrustProviderHook`**: Creates an `x402#2299` `onBeforeSettle` screening hook returning `BeforeSettleVerdict` with `payerRole` (`PAYEE_INDEXED` | `PURE_PAYER` | `UNVERIFIED`), `payerActivity`, and `riskFlags`.
36
+ - **`createFideRailSellerGuard`**: Creates a non-custodial HTTP 402 middleware (`handleRequest`, `buildServiceDescriptor`) supporting all 4 chains and `/.well-known/fiderail-service.json`.
37
+ - **Types**: `TrustProviderHookOptions`, `BeforeSettleContext`, `BeforeSettleVerdict`, `PayerRole`, `SellerGuardOptions`.
38
+
39
+ ## Runtime Requirements
40
+
41
+ Requires **Node.js `>= 22.13.0`**. 100% non-custodial: payment challenges route directly to the seller's own wallet addresses.
42
+
43
+ ## Links
44
+
45
+ - Portal: [https://fiderail.com](https://fiderail.com)
46
+ - Documentation: [https://fiderail.com/docs](https://fiderail.com/docs)
47
+ - Source (GitLab): [https://gitlab.com/fiderail/fiderail](https://gitlab.com/fiderail/fiderail)
48
+ - Mirror (GitHub): [https://github.com/fiderail/fiderail](https://github.com/fiderail/fiderail)
49
+
50
+ ## License
51
+
52
+ [MIT](./LICENSE)
@@ -0,0 +1,79 @@
1
+ import type http from "node:http";
2
+ import { type ChainKey } from "@fiderail/spec";
3
+ import type { AgentTrustLookupResult, PayerActivitySummary, TrustEngine } from "@fiderail/core";
4
+ export interface TrustProviderHookOptions {
5
+ engine: TrustEngine;
6
+ minTrustScore?: number;
7
+ blockLoops?: boolean;
8
+ blockConcentratedAboveUsdc?: number;
9
+ allowUnknown?: boolean;
10
+ allowUnknownMaxUsdc?: number;
11
+ }
12
+ export interface BeforeSettleContext {
13
+ chain?: string;
14
+ network?: string;
15
+ payer?: string;
16
+ buyer?: string;
17
+ from?: string;
18
+ amountUsdc?: number | string | null;
19
+ amountAtomic?: number | string | null;
20
+ }
21
+ export type PayerRole = "PAYEE_INDEXED" | "PURE_PAYER" | "UNVERIFIED";
22
+ export interface BeforeSettleVerdict {
23
+ allow: boolean;
24
+ decision: "ALLOW" | "WARN" | "REJECT";
25
+ reason: string;
26
+ chain: ChainKey;
27
+ payer: string;
28
+ payerRole: PayerRole;
29
+ payerActivity: PayerActivitySummary | null;
30
+ trustScore: number | null;
31
+ tier: string;
32
+ riskFlags: string[];
33
+ trustProfile: AgentTrustLookupResult;
34
+ provider: "fiderail";
35
+ spec: "x402-trust-provider-2299";
36
+ checkedAt: string;
37
+ }
38
+ /**
39
+ * x402#2299 Trust-Provider adapter (`onBeforeSettle` behavioral risk screening).
40
+ * Supports all 4 locked chains (Base, Solana, Arbitrum, Polygon) with zero custody.
41
+ */
42
+ export declare function createTrustProviderHook({ engine, minTrustScore, blockLoops, blockConcentratedAboveUsdc, allowUnknown, allowUnknownMaxUsdc, }: TrustProviderHookOptions): {
43
+ onBeforeSettle: (context?: BeforeSettleContext) => Promise<BeforeSettleVerdict>;
44
+ };
45
+ export interface SellerGuardOptions {
46
+ payToBase?: string;
47
+ payToSolana?: string;
48
+ payToArbitrum?: string;
49
+ payToPolygon?: string;
50
+ priceUsdc?: number;
51
+ resourceUrl?: string;
52
+ serviceName?: string;
53
+ description?: string;
54
+ tags?: string[];
55
+ engine?: TrustEngine | null;
56
+ facilitatorVerifyUrl?: string | null;
57
+ verifyPayment?: ((proof: string, req: http.IncomingMessage) => Promise<boolean> | boolean) | null;
58
+ blockFlaggedBuyers?: boolean;
59
+ minBuyerTrustScore?: number;
60
+ fetchImpl?: typeof globalThis.fetch;
61
+ }
62
+ /**
63
+ * Non-custodial seller-side HTTP 402 adapter across all 4 locked chains.
64
+ * Issues x402 challenges directly to the seller's own wallets, filters sybil buyers via
65
+ * x402#2299 Trust-Provider, and exposes `/.well-known/fiderail-service.json`.
66
+ */
67
+ export declare function createFideRailSellerGuard({ payToBase, payToSolana, payToArbitrum, payToPolygon, priceUsdc, resourceUrl, serviceName, description, tags, engine, facilitatorVerifyUrl, verifyPayment, blockFlaggedBuyers, minBuyerTrustScore, fetchImpl, }?: SellerGuardOptions): {
68
+ buildServiceDescriptor: () => {
69
+ x402Version: number;
70
+ type: string;
71
+ serviceName: string;
72
+ description: string;
73
+ resource: string;
74
+ tags: string[];
75
+ accepts: Record<string, unknown>[];
76
+ };
77
+ handleRequest: (req: http.IncomingMessage, res: http.ServerResponse, next?: () => Promise<void> | void) => Promise<void>;
78
+ };
79
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,281 @@
1
+ import { getChainSpec, getPrimaryAssetContract, normalizeChainAddress, normalizeChainName, } from "@fiderail/spec";
2
+ function sendJson(res, statusCode, payload, extraHeaders = {}) {
3
+ res.writeHead(statusCode, {
4
+ "Content-Type": "application/json; charset=utf-8",
5
+ ...extraHeaders,
6
+ });
7
+ res.end(JSON.stringify(payload, null, 2));
8
+ }
9
+ /**
10
+ * x402#2299 Trust-Provider adapter (`onBeforeSettle` behavioral risk screening).
11
+ * Supports all 4 locked chains (Base, Solana, Arbitrum, Polygon) with zero custody.
12
+ */
13
+ export function createTrustProviderHook({ engine, minTrustScore = 0, blockLoops = true, blockConcentratedAboveUsdc = 0.05, allowUnknown = true, allowUnknownMaxUsdc = 0.05, }) {
14
+ if (!engine || typeof engine.getAgentTrust !== "function") {
15
+ throw new Error("A valid FideRail trust engine instance is required for Trust-Provider.");
16
+ }
17
+ async function onBeforeSettle(context = {}) {
18
+ const chainInput = context.chain || context.network;
19
+ const chain = normalizeChainName(chainInput);
20
+ if (!chain) {
21
+ throw new Error(`Unsupported chain/network "${chainInput}". Expected Base, Solana, Arbitrum, or Polygon.`);
22
+ }
23
+ const payerInput = context.payer || context.buyer || context.from;
24
+ const payer = normalizeChainAddress(chain, payerInput);
25
+ if (!payer) {
26
+ throw new Error("A non-empty payer/buyer wallet address is required.");
27
+ }
28
+ const amountUsdc = context.amountUsdc !== undefined && context.amountUsdc !== null
29
+ ? Number(context.amountUsdc)
30
+ : context.amountAtomic !== undefined && context.amountAtomic !== null
31
+ ? Number(context.amountAtomic) / 1e6
32
+ : 0;
33
+ const [profile, payerActivity] = await Promise.all([
34
+ engine.getAgentTrust(chain, payer),
35
+ typeof engine.getPayerActivity === "function"
36
+ ? engine.getPayerActivity(chain, payer)
37
+ : Promise.resolve(null),
38
+ ]);
39
+ const flags = [...(profile.riskFlags || [])];
40
+ const hasActivePayerHistory = Boolean(payerActivity && payerActivity.txCount > 0);
41
+ const payerRole = profile.found
42
+ ? "PAYEE_INDEXED"
43
+ : hasActivePayerHistory
44
+ ? "PURE_PAYER"
45
+ : "UNVERIFIED";
46
+ let allow = true;
47
+ let decision = "ALLOW";
48
+ let reason = "TRUST_PROVIDER_APPROVED";
49
+ if (!profile.found && hasActivePayerHistory && payerActivity) {
50
+ if (blockLoops && payerActivity.hasReciprocalLoop) {
51
+ if (!flags.includes("RECIPROCAL_LOOP")) {
52
+ flags.push("RECIPROCAL_LOOP");
53
+ }
54
+ allow = false;
55
+ decision = "REJECT";
56
+ reason = "RECIPROCAL_LOOP_DETECTED";
57
+ }
58
+ else if (payerActivity.distinctPayees >= 2 && payerActivity.txCount >= 3) {
59
+ allow = true;
60
+ decision = "ALLOW";
61
+ reason = "PURE_PAYER_CROSS_ECOSYSTEM_VERIFIED";
62
+ }
63
+ else if (minTrustScore === 0) {
64
+ allow = true;
65
+ decision = "ALLOW";
66
+ reason = "PURE_PAYER_ACTIVITY_VERIFIED";
67
+ }
68
+ else if (!allowUnknown ||
69
+ (Number.isFinite(amountUsdc) && amountUsdc > 0 && amountUsdc > allowUnknownMaxUsdc)) {
70
+ allow = false;
71
+ decision = "REJECT";
72
+ reason = "PURE_PAYER_NO_PAYEE_SCORE_ABOVE_CAP";
73
+ }
74
+ else {
75
+ allow = true;
76
+ decision = "WARN";
77
+ reason = "PURE_PAYER_NO_PAYEE_SCORE_MICRO_ALLOWED";
78
+ }
79
+ }
80
+ else if (!profile.found) {
81
+ if (!allowUnknown ||
82
+ (Number.isFinite(amountUsdc) && amountUsdc > 0 && amountUsdc > allowUnknownMaxUsdc)) {
83
+ allow = false;
84
+ decision = "REJECT";
85
+ reason = "UNKNOWN_PAYER_ABOVE_CAP";
86
+ }
87
+ else {
88
+ allow = true;
89
+ decision = "WARN";
90
+ reason = "UNKNOWN_PAYER_WITHIN_MICRO_CAP";
91
+ }
92
+ }
93
+ else if (blockLoops &&
94
+ (flags.includes("RECIPROCAL_LOOP") || Boolean(payerActivity?.hasReciprocalLoop))) {
95
+ if (!flags.includes("RECIPROCAL_LOOP")) {
96
+ flags.push("RECIPROCAL_LOOP");
97
+ }
98
+ allow = false;
99
+ decision = "REJECT";
100
+ reason = "RECIPROCAL_LOOP_DETECTED";
101
+ }
102
+ else if (flags.includes("SINGLE_PAYER_CONCENTRATED") &&
103
+ Number.isFinite(amountUsdc) &&
104
+ amountUsdc > blockConcentratedAboveUsdc) {
105
+ allow = false;
106
+ decision = "REJECT";
107
+ reason = "SINGLE_PAYER_CONCENTRATED_ABOVE_CAP";
108
+ }
109
+ else if (flags.includes("ISOLATED_PAYER_FARM") &&
110
+ Number.isFinite(amountUsdc) &&
111
+ amountUsdc > blockConcentratedAboveUsdc) {
112
+ allow = false;
113
+ decision = "REJECT";
114
+ reason = "ISOLATED_PAYER_FARM_ABOVE_CAP";
115
+ }
116
+ else if (minTrustScore > 0 && (profile.creditScore ?? 0) < minTrustScore) {
117
+ allow = false;
118
+ decision = "REJECT";
119
+ reason = "TRUST_SCORE_BELOW_THRESHOLD";
120
+ }
121
+ return {
122
+ allow,
123
+ decision,
124
+ reason,
125
+ chain,
126
+ payer,
127
+ payerRole,
128
+ payerActivity,
129
+ trustScore: profile.creditScore ?? null,
130
+ tier: profile.tier,
131
+ riskFlags: flags,
132
+ trustProfile: profile,
133
+ provider: "fiderail",
134
+ spec: "x402-trust-provider-2299",
135
+ checkedAt: new Date().toISOString(),
136
+ };
137
+ }
138
+ return { onBeforeSettle };
139
+ }
140
+ /**
141
+ * Non-custodial seller-side HTTP 402 adapter across all 4 locked chains.
142
+ * Issues x402 challenges directly to the seller's own wallets, filters sybil buyers via
143
+ * x402#2299 Trust-Provider, and exposes `/.well-known/fiderail-service.json`.
144
+ */
145
+ export function createFideRailSellerGuard({ payToBase = "", payToSolana = "", payToArbitrum = "", payToPolygon = "", priceUsdc = 0.01, resourceUrl, serviceName = "FideRail Protected API", description = "x402 protected service endpoint", tags = [], engine = null, facilitatorVerifyUrl = null, verifyPayment = null, blockFlaggedBuyers = true, minBuyerTrustScore = 0, fetchImpl = globalThis.fetch, } = {}) {
146
+ const payees = {};
147
+ if (payToBase)
148
+ payees.base = normalizeChainAddress("base", payToBase);
149
+ if (payToSolana)
150
+ payees.solana = normalizeChainAddress("solana", payToSolana);
151
+ if (payToArbitrum)
152
+ payees.arbitrum = normalizeChainAddress("arbitrum", payToArbitrum);
153
+ if (payToPolygon)
154
+ payees.polygon = normalizeChainAddress("polygon", payToPolygon);
155
+ if (Object.keys(payees).length === 0) {
156
+ throw new Error("At least one seller receiving wallet (payToBase, payToSolana, payToArbitrum, or payToPolygon) is required.");
157
+ }
158
+ const trustHook = engine && blockFlaggedBuyers
159
+ ? createTrustProviderHook({
160
+ engine,
161
+ minTrustScore: minBuyerTrustScore,
162
+ blockLoops: true,
163
+ blockConcentratedAboveUsdc: Number.POSITIVE_INFINITY,
164
+ allowUnknown: true,
165
+ allowUnknownMaxUsdc: Number.POSITIVE_INFINITY,
166
+ })
167
+ : null;
168
+ const atomicAmount = String(Math.round(Number(priceUsdc) * 1e6));
169
+ function buildAccepts() {
170
+ const accepts = [];
171
+ for (const [chainKey, payTo] of Object.entries(payees)) {
172
+ const chainSpec = getChainSpec(chainKey);
173
+ const asset = getPrimaryAssetContract(chainKey);
174
+ accepts.push({
175
+ scheme: "exact",
176
+ network: chainSpec.caip2,
177
+ amount: atomicAmount,
178
+ asset,
179
+ payTo,
180
+ maxTimeoutSeconds: 60,
181
+ ...(chainSpec.vm === "evm" ? { extra: { name: "USD Coin", version: "2" } } : {}),
182
+ });
183
+ }
184
+ return accepts;
185
+ }
186
+ function buildServiceDescriptor() {
187
+ return {
188
+ x402Version: 2,
189
+ type: "http",
190
+ serviceName,
191
+ description,
192
+ resource: resourceUrl || "/",
193
+ tags,
194
+ accepts: buildAccepts(),
195
+ };
196
+ }
197
+ async function verifyProof(proof, req) {
198
+ if (typeof verifyPayment === "function") {
199
+ return Boolean(await verifyPayment(proof, req));
200
+ }
201
+ if (facilitatorVerifyUrl) {
202
+ const res = await fetchImpl(facilitatorVerifyUrl, {
203
+ method: "POST",
204
+ headers: { "Content-Type": "application/json" },
205
+ body: JSON.stringify({
206
+ x402Version: 2,
207
+ paymentHeader: proof,
208
+ accepts: buildAccepts(),
209
+ }),
210
+ signal: AbortSignal.timeout(10000),
211
+ });
212
+ if (!res.ok)
213
+ return false;
214
+ const data = (await res.json().catch(() => ({})));
215
+ return Boolean(data.isValid ?? data.valid ?? true);
216
+ }
217
+ return Boolean(proof && String(proof).trim().length > 0);
218
+ }
219
+ async function handleRequest(req, res, next) {
220
+ const url = new URL(req.url || "/", "http://localhost");
221
+ if (req.method === "GET" && url.pathname === "/.well-known/fiderail-service.json") {
222
+ sendJson(res, 200, buildServiceDescriptor());
223
+ return;
224
+ }
225
+ if (trustHook) {
226
+ const buyerAddr = req.headers["x-buyer-address"];
227
+ const buyerChain = normalizeChainName(req.headers["x-buyer-chain"]);
228
+ if (buyerAddr && buyerChain) {
229
+ const verdict = await trustHook.onBeforeSettle({
230
+ chain: buyerChain,
231
+ payer: String(buyerAddr),
232
+ amountUsdc: Number(priceUsdc),
233
+ });
234
+ if (!verdict.allow) {
235
+ sendJson(res, 403, {
236
+ error: "Buyer wallet blocked by FideRail anti-sybil seller guard",
237
+ reason: verdict.reason,
238
+ riskFlags: verdict.riskFlags,
239
+ trustProfile: verdict.trustProfile,
240
+ });
241
+ return;
242
+ }
243
+ }
244
+ }
245
+ const proofHeader = req.headers["x-payment"] || req.headers["payment-signature"];
246
+ const proof = Array.isArray(proofHeader) ? proofHeader[0] : proofHeader;
247
+ const challenge = {
248
+ x402Version: 2,
249
+ error: "Payment Required",
250
+ resource: { url: resourceUrl || url.pathname, description },
251
+ accepts: buildAccepts(),
252
+ };
253
+ if (!proof) {
254
+ const encoded = Buffer.from(JSON.stringify(challenge)).toString("base64");
255
+ sendJson(res, 402, challenge, {
256
+ "X-PAYMENT-REQUIRED": encoded,
257
+ "PAYMENT-REQUIRED": encoded,
258
+ });
259
+ return;
260
+ }
261
+ const valid = await verifyProof(proof, req);
262
+ if (!valid) {
263
+ const encoded = Buffer.from(JSON.stringify(challenge)).toString("base64");
264
+ sendJson(res, 402, { ...challenge, error: "Invalid payment proof" }, {
265
+ "X-PAYMENT-REQUIRED": encoded,
266
+ "PAYMENT-REQUIRED": encoded,
267
+ });
268
+ return;
269
+ }
270
+ if (typeof next === "function") {
271
+ await next();
272
+ return;
273
+ }
274
+ sendJson(res, 200, { ok: true, paid: true });
275
+ }
276
+ return {
277
+ buildServiceDescriptor,
278
+ handleRequest,
279
+ };
280
+ }
281
+ //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@fiderail/seller",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.3.1",
4
+ "description": "Non-custodial seller-side HTTP 402 adapter and x402#2299 Trust-Provider onBeforeSettle hook (supports 4 chains x 2 stablecoins).",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "README.md",
16
+ "LICENSE",
17
+ "dist",
18
+ "!dist/**/*.map",
19
+ "!dist/**/*.tsbuildinfo"
20
+ ],
21
+ "scripts": {
22
+ "prepublishOnly": "tsc -b"
23
+ },
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "engines": {
28
+ "node": ">=22.13.0"
29
+ },
30
+ "homepage": "https://fiderail.com",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "https://gitlab.com/fiderail/fiderail.git",
34
+ "directory": "packages/seller"
35
+ },
36
+ "bugs": {
37
+ "url": "https://gitlab.com/fiderail/fiderail/-/issues"
38
+ },
39
+ "keywords": [
40
+ "fiderail",
41
+ "ai-agent",
42
+ "x402",
43
+ "http-402",
44
+ "trust-provider",
45
+ "anti-sybil",
46
+ "payment-control-plane",
47
+ "stablecoin"
48
+ ],
49
+ "dependencies": {
50
+ "@fiderail/core": "2.3.1",
51
+ "@fiderail/spec": "2.3.1"
52
+ },
53
+ "license": "MIT"
54
+ }