@relai-fi/x402 0.5.31 → 0.5.33
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 +102 -0
- package/dist/index.cjs +61 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +61 -1
- package/dist/index.js.map +1 -1
- package/dist/plugins.cjs +150 -0
- package/dist/plugins.cjs.map +1 -0
- package/dist/plugins.d.cts +2 -0
- package/dist/plugins.d.ts +2 -0
- package/dist/plugins.js +125 -0
- package/dist/plugins.js.map +1 -0
- package/dist/server-BAPqyEka.d.cts +229 -0
- package/dist/server-BRSLRU_Y.d.ts +229 -0
- package/dist/server.cjs +61 -1
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +2 -138
- package/dist/server.d.ts +2 -138
- package/dist/server.js +61 -1
- package/dist/server.js.map +1 -1
- package/package.json +6 -1
package/dist/plugins.cjs
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/plugins.ts
|
|
21
|
+
var plugins_exports = {};
|
|
22
|
+
__export(plugins_exports, {
|
|
23
|
+
freeTier: () => freeTier
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(plugins_exports);
|
|
26
|
+
var RELAI_API_BASE = "https://api.relai.fi";
|
|
27
|
+
function freeTier(config) {
|
|
28
|
+
const base = (config.baseUrl ?? RELAI_API_BASE).replace(/\/$/, "");
|
|
29
|
+
const cacheTtl = config.cacheTtlMs ?? 5e3;
|
|
30
|
+
const cache = /* @__PURE__ */ new Map();
|
|
31
|
+
function resolveHeaders() {
|
|
32
|
+
return {
|
|
33
|
+
"X-Service-Key": config.serviceKey,
|
|
34
|
+
"Content-Type": "application/json"
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
function resolveBuyerId(req) {
|
|
38
|
+
try {
|
|
39
|
+
const auth = req.headers?.authorization || "";
|
|
40
|
+
if (auth.startsWith("Bearer ")) {
|
|
41
|
+
const token = auth.slice(7).trim();
|
|
42
|
+
const payload = JSON.parse(Buffer.from(token.split(".")[1], "base64").toString());
|
|
43
|
+
if (payload?.sub) return `user:${payload.sub}`;
|
|
44
|
+
}
|
|
45
|
+
} catch {
|
|
46
|
+
}
|
|
47
|
+
const wallet = req.headers?.["x-wallet-address"] || req.headers?.["x-buyer-address"];
|
|
48
|
+
if (wallet) return `wallet:${wallet}`;
|
|
49
|
+
const ip = (req.headers?.["x-forwarded-for"] || "").split(",")[0].trim() || req.socket?.remoteAddress || req.ip || "unknown";
|
|
50
|
+
return `ip:${ip}`;
|
|
51
|
+
}
|
|
52
|
+
function cacheKey(path, buyerId) {
|
|
53
|
+
return `${config.serviceKey}:${path}:${buyerId}`;
|
|
54
|
+
}
|
|
55
|
+
async function checkFreeTier(path, buyerId) {
|
|
56
|
+
const key = cacheKey(path, buyerId);
|
|
57
|
+
const now = Date.now();
|
|
58
|
+
const cached = cache.get(key);
|
|
59
|
+
if (cached && cached.expiresAt > now) {
|
|
60
|
+
return cached.result;
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
const res = await fetch(`${base}/v1/plugins/free-tier/check`, {
|
|
64
|
+
method: "POST",
|
|
65
|
+
headers: resolveHeaders(),
|
|
66
|
+
body: JSON.stringify({ path, buyerId })
|
|
67
|
+
});
|
|
68
|
+
if (!res.ok) {
|
|
69
|
+
return { free: false, reason: `api_error_${res.status}` };
|
|
70
|
+
}
|
|
71
|
+
const result = await res.json();
|
|
72
|
+
cache.set(key, { result, expiresAt: now + cacheTtl });
|
|
73
|
+
return result;
|
|
74
|
+
} catch (err) {
|
|
75
|
+
return { free: false, reason: "network_error" };
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
async function recordCall(path, buyerId) {
|
|
79
|
+
try {
|
|
80
|
+
await fetch(`${base}/v1/plugins/free-tier/record`, {
|
|
81
|
+
method: "POST",
|
|
82
|
+
headers: resolveHeaders(),
|
|
83
|
+
body: JSON.stringify({ path, buyerId })
|
|
84
|
+
});
|
|
85
|
+
cache.delete(cacheKey(path, buyerId));
|
|
86
|
+
} catch {
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
async function syncConfig() {
|
|
90
|
+
try {
|
|
91
|
+
const paths = config.paths ?? ["*"];
|
|
92
|
+
await fetch(`${base}/v1/plugins/free-tier/config`, {
|
|
93
|
+
method: "PUT",
|
|
94
|
+
headers: resolveHeaders(),
|
|
95
|
+
body: JSON.stringify({
|
|
96
|
+
perBuyerLimit: config.perBuyerLimit,
|
|
97
|
+
resetPeriod: config.resetPeriod ?? "never",
|
|
98
|
+
globalCap: config.globalCap ?? null,
|
|
99
|
+
paths
|
|
100
|
+
})
|
|
101
|
+
});
|
|
102
|
+
} catch (err) {
|
|
103
|
+
console.warn(`[relai:freeTier] Failed to sync config to RelAI: ${err}`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
name: "free-tier",
|
|
108
|
+
async onInit() {
|
|
109
|
+
await syncConfig();
|
|
110
|
+
},
|
|
111
|
+
async beforePaymentCheck(req, ctx) {
|
|
112
|
+
const requestPath = ctx.path || "/";
|
|
113
|
+
const paths = config.paths ?? ["*"];
|
|
114
|
+
const pathMatches = paths.includes("*") || paths.some((p) => {
|
|
115
|
+
const normalized = p.toLowerCase().replace(/\/+$/, "") || "/";
|
|
116
|
+
const reqNormalized = requestPath.toLowerCase().replace(/\/+$/, "") || "/";
|
|
117
|
+
return normalized === reqNormalized || normalized === "*";
|
|
118
|
+
});
|
|
119
|
+
if (!pathMatches) {
|
|
120
|
+
return {};
|
|
121
|
+
}
|
|
122
|
+
const buyerId = resolveBuyerId(req);
|
|
123
|
+
const result = await checkFreeTier(requestPath, buyerId);
|
|
124
|
+
if (result.free) {
|
|
125
|
+
recordCall(requestPath, buyerId).catch(() => {
|
|
126
|
+
});
|
|
127
|
+
return {
|
|
128
|
+
skip: true,
|
|
129
|
+
headers: {
|
|
130
|
+
"X-Free-Calls-Remaining": String(result.remaining ?? 0),
|
|
131
|
+
"X-Free-Calls-Total": String(result.total ?? config.perBuyerLimit),
|
|
132
|
+
...result.globalRemaining != null ? { "X-Free-Calls-Global-Remaining": String(result.globalRemaining) } : {}
|
|
133
|
+
},
|
|
134
|
+
meta: {
|
|
135
|
+
freeTier: true,
|
|
136
|
+
buyerId,
|
|
137
|
+
remaining: result.remaining,
|
|
138
|
+
total: result.total ?? config.perBuyerLimit
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
return {};
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
147
|
+
0 && (module.exports = {
|
|
148
|
+
freeTier
|
|
149
|
+
});
|
|
150
|
+
//# sourceMappingURL=plugins.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/plugins.ts"],"sourcesContent":["// src/plugins.ts\n// RelAI Plugin System - extensible middleware hooks for Relai.protect()\n\nimport type { RelaiNetwork } from './types';\nimport type { SettleResult } from './server';\n\nconst RELAI_API_BASE = 'https://api.relai.fi';\n\n// ============================================================================\n// Plugin Interface\n// ============================================================================\n\nexport interface PluginContext {\n /** Network for this endpoint */\n network: RelaiNetwork;\n /** Price in USD */\n price: number;\n /** Request path */\n path: string;\n /** HTTP method */\n method: string;\n}\n\nexport interface PluginResult {\n /** If true, skip payment and serve content for free */\n skip?: boolean;\n /** Extra response headers to set */\n headers?: Record<string, string>;\n /** Metadata attached to req.pluginMeta */\n meta?: Record<string, unknown>;\n}\n\nexport interface RelaiPlugin {\n /** Unique plugin name */\n name: string;\n\n /**\n * Called before the 402 payment check.\n * Return { skip: true } to bypass payment entirely.\n */\n beforePaymentCheck?(req: any, ctx: PluginContext): Promise<PluginResult>;\n\n /**\n * Called after a successful payment settlement.\n * Use for analytics, logging, webhooks, etc.\n */\n afterSettled?(req: any, result: SettleResult, ctx: PluginContext): Promise<void>;\n\n /**\n * Called once when the Relai instance initializes (server start).\n * Use to sync config to RelAI backend or validate credentials.\n */\n onInit?(): Promise<void>;\n}\n\n// ============================================================================\n// Free Tier Plugin\n// ============================================================================\n\nexport interface FreeTierPluginConfig {\n /** Service key (sk_live_...) for authenticating with RelAI API */\n serviceKey: string;\n /** Max free calls per buyer per period */\n perBuyerLimit: number;\n /** Reset period for per-buyer counters */\n resetPeriod?: 'never' | 'daily' | 'monthly';\n /** Optional global cap across all buyers */\n globalCap?: number;\n /** Specific paths to apply free tier to (default: '*' = all) */\n paths?: string[];\n /** Override RelAI API base URL (default: https://api.relai.fi) */\n baseUrl?: string;\n /** Cache TTL in ms for check results (default: 5000) */\n cacheTtlMs?: number;\n}\n\ninterface FreeTierCheckResponse {\n free: boolean;\n remaining?: number;\n total?: number;\n reason?: string;\n globalRemaining?: number;\n}\n\n/**\n * Free Tier plugin - gives buyers a number of free API calls\n * before requiring payment.\n *\n * State is stored in the RelAI backend, keyed by your service key.\n * Config can be set here (SDK-side) or overridden in the relai.fi dashboard.\n *\n * @example\n * ```typescript\n * import Relai from '@relai-fi/x402/server';\n * import { freeTier } from '@relai-fi/x402/plugins';\n *\n * const relai = new Relai({\n * network: 'base',\n * plugins: [\n * freeTier({\n * serviceKey: process.env.RELAI_SERVICE_KEY!,\n * perBuyerLimit: 10,\n * resetPeriod: 'daily',\n * }),\n * ],\n * });\n *\n * app.get('/api/data', relai.protect({\n * payTo: '0xYourWallet',\n * price: 0.01,\n * }), (req, res) => {\n * res.json({ data: 'paid content' });\n * });\n * ```\n */\nexport function freeTier(config: FreeTierPluginConfig): RelaiPlugin {\n const base = (config.baseUrl ?? RELAI_API_BASE).replace(/\\/$/, '');\n const cacheTtl = config.cacheTtlMs ?? 5000;\n\n // Simple in-memory cache: \"serviceKey:path:buyerId\" -> { result, expiresAt }\n const cache = new Map<string, { result: FreeTierCheckResponse; expiresAt: number }>();\n\n function resolveHeaders(): Record<string, string> {\n return {\n 'X-Service-Key': config.serviceKey,\n 'Content-Type': 'application/json',\n };\n }\n\n /**\n * Resolve buyer identity from the request.\n * Priority: JWT sub > x-wallet-address > IP fallback\n */\n function resolveBuyerId(req: any): string {\n // 1. JWT Bearer token\n try {\n const auth = req.headers?.authorization || '';\n if (auth.startsWith('Bearer ')) {\n const token = auth.slice(7).trim();\n const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());\n if (payload?.sub) return `user:${payload.sub}`;\n }\n } catch { /* ignore */ }\n\n // 2. Explicit wallet header\n const wallet = req.headers?.['x-wallet-address'] || req.headers?.['x-buyer-address'];\n if (wallet) return `wallet:${wallet}`;\n\n // 3. IP fallback\n const ip =\n (req.headers?.['x-forwarded-for'] || '').split(',')[0].trim() ||\n req.socket?.remoteAddress ||\n req.ip ||\n 'unknown';\n return `ip:${ip}`;\n }\n\n function cacheKey(path: string, buyerId: string): string {\n return `${config.serviceKey}:${path}:${buyerId}`;\n }\n\n async function checkFreeTier(path: string, buyerId: string): Promise<FreeTierCheckResponse> {\n const key = cacheKey(path, buyerId);\n const now = Date.now();\n const cached = cache.get(key);\n if (cached && cached.expiresAt > now) {\n return cached.result;\n }\n\n try {\n const res = await fetch(`${base}/v1/plugins/free-tier/check`, {\n method: 'POST',\n headers: resolveHeaders(),\n body: JSON.stringify({ path, buyerId }),\n });\n\n if (!res.ok) {\n // Non-blocking: if API unreachable, default to not-free\n return { free: false, reason: `api_error_${res.status}` };\n }\n\n const result = await res.json() as FreeTierCheckResponse;\n cache.set(key, { result, expiresAt: now + cacheTtl });\n return result;\n } catch (err) {\n // Network error - non-blocking, default to paid\n return { free: false, reason: 'network_error' };\n }\n }\n\n async function recordCall(path: string, buyerId: string): Promise<void> {\n try {\n await fetch(`${base}/v1/plugins/free-tier/record`, {\n method: 'POST',\n headers: resolveHeaders(),\n body: JSON.stringify({ path, buyerId }),\n });\n // Invalidate cache for this buyer+path after recording\n cache.delete(cacheKey(path, buyerId));\n } catch {\n // Fire-and-forget\n }\n }\n\n async function syncConfig(): Promise<void> {\n try {\n const paths = config.paths ?? ['*'];\n await fetch(`${base}/v1/plugins/free-tier/config`, {\n method: 'PUT',\n headers: resolveHeaders(),\n body: JSON.stringify({\n perBuyerLimit: config.perBuyerLimit,\n resetPeriod: config.resetPeriod ?? 'never',\n globalCap: config.globalCap ?? null,\n paths,\n }),\n });\n } catch (err) {\n console.warn(`[relai:freeTier] Failed to sync config to RelAI: ${err}`);\n }\n }\n\n return {\n name: 'free-tier',\n\n async onInit() {\n await syncConfig();\n },\n\n async beforePaymentCheck(req, ctx) {\n const requestPath = ctx.path || '/';\n\n // Check if this path is covered by the plugin\n const paths = config.paths ?? ['*'];\n const pathMatches = paths.includes('*') || paths.some((p) => {\n const normalized = p.toLowerCase().replace(/\\/+$/, '') || '/';\n const reqNormalized = requestPath.toLowerCase().replace(/\\/+$/, '') || '/';\n return normalized === reqNormalized || normalized === '*';\n });\n\n if (!pathMatches) {\n return {};\n }\n\n const buyerId = resolveBuyerId(req);\n const result = await checkFreeTier(requestPath, buyerId);\n\n if (result.free) {\n // Record the call (fire-and-forget)\n recordCall(requestPath, buyerId).catch(() => {});\n\n return {\n skip: true,\n headers: {\n 'X-Free-Calls-Remaining': String(result.remaining ?? 0),\n 'X-Free-Calls-Total': String(result.total ?? config.perBuyerLimit),\n ...(result.globalRemaining != null\n ? { 'X-Free-Calls-Global-Remaining': String(result.globalRemaining) }\n : {}),\n },\n meta: {\n freeTier: true,\n buyerId,\n remaining: result.remaining,\n total: result.total ?? config.perBuyerLimit,\n },\n };\n }\n\n return {};\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,IAAM,iBAAiB;AA6GhB,SAAS,SAAS,QAA2C;AAClE,QAAM,QAAQ,OAAO,WAAW,gBAAgB,QAAQ,OAAO,EAAE;AACjE,QAAM,WAAW,OAAO,cAAc;AAGtC,QAAM,QAAQ,oBAAI,IAAkE;AAEpF,WAAS,iBAAyC;AAChD,WAAO;AAAA,MACL,iBAAiB,OAAO;AAAA,MACxB,gBAAgB;AAAA,IAClB;AAAA,EACF;AAMA,WAAS,eAAe,KAAkB;AAExC,QAAI;AACF,YAAM,OAAO,IAAI,SAAS,iBAAiB;AAC3C,UAAI,KAAK,WAAW,SAAS,GAAG;AAC9B,cAAM,QAAQ,KAAK,MAAM,CAAC,EAAE,KAAK;AACjC,cAAM,UAAU,KAAK,MAAM,OAAO,KAAK,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,QAAQ,EAAE,SAAS,CAAC;AAChF,YAAI,SAAS,IAAK,QAAO,QAAQ,QAAQ,GAAG;AAAA,MAC9C;AAAA,IACF,QAAQ;AAAA,IAAe;AAGvB,UAAM,SAAS,IAAI,UAAU,kBAAkB,KAAK,IAAI,UAAU,iBAAiB;AACnF,QAAI,OAAQ,QAAO,UAAU,MAAM;AAGnC,UAAM,MACH,IAAI,UAAU,iBAAiB,KAAK,IAAI,MAA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UACP;AAAA,UACA,MAAM;AAAA,YACJ,UAAU;AAAA,YACV;AAAA,YACA,WAAW,OAAO;AAAA,YAClB,OAAO,OAAO,SAAS,OAAO;AAAA,UAChC;AAAA,QACF;AAAA,MACF;AAEA,aAAO,CAAC;AAAA,IACV;AAAA,EACF;AACF;","names":[]}
|
package/dist/plugins.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// src/plugins.ts
|
|
2
|
+
var RELAI_API_BASE = "https://api.relai.fi";
|
|
3
|
+
function freeTier(config) {
|
|
4
|
+
const base = (config.baseUrl ?? RELAI_API_BASE).replace(/\/$/, "");
|
|
5
|
+
const cacheTtl = config.cacheTtlMs ?? 5e3;
|
|
6
|
+
const cache = /* @__PURE__ */ new Map();
|
|
7
|
+
function resolveHeaders() {
|
|
8
|
+
return {
|
|
9
|
+
"X-Service-Key": config.serviceKey,
|
|
10
|
+
"Content-Type": "application/json"
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
function resolveBuyerId(req) {
|
|
14
|
+
try {
|
|
15
|
+
const auth = req.headers?.authorization || "";
|
|
16
|
+
if (auth.startsWith("Bearer ")) {
|
|
17
|
+
const token = auth.slice(7).trim();
|
|
18
|
+
const payload = JSON.parse(Buffer.from(token.split(".")[1], "base64").toString());
|
|
19
|
+
if (payload?.sub) return `user:${payload.sub}`;
|
|
20
|
+
}
|
|
21
|
+
} catch {
|
|
22
|
+
}
|
|
23
|
+
const wallet = req.headers?.["x-wallet-address"] || req.headers?.["x-buyer-address"];
|
|
24
|
+
if (wallet) return `wallet:${wallet}`;
|
|
25
|
+
const ip = (req.headers?.["x-forwarded-for"] || "").split(",")[0].trim() || req.socket?.remoteAddress || req.ip || "unknown";
|
|
26
|
+
return `ip:${ip}`;
|
|
27
|
+
}
|
|
28
|
+
function cacheKey(path, buyerId) {
|
|
29
|
+
return `${config.serviceKey}:${path}:${buyerId}`;
|
|
30
|
+
}
|
|
31
|
+
async function checkFreeTier(path, buyerId) {
|
|
32
|
+
const key = cacheKey(path, buyerId);
|
|
33
|
+
const now = Date.now();
|
|
34
|
+
const cached = cache.get(key);
|
|
35
|
+
if (cached && cached.expiresAt > now) {
|
|
36
|
+
return cached.result;
|
|
37
|
+
}
|
|
38
|
+
try {
|
|
39
|
+
const res = await fetch(`${base}/v1/plugins/free-tier/check`, {
|
|
40
|
+
method: "POST",
|
|
41
|
+
headers: resolveHeaders(),
|
|
42
|
+
body: JSON.stringify({ path, buyerId })
|
|
43
|
+
});
|
|
44
|
+
if (!res.ok) {
|
|
45
|
+
return { free: false, reason: `api_error_${res.status}` };
|
|
46
|
+
}
|
|
47
|
+
const result = await res.json();
|
|
48
|
+
cache.set(key, { result, expiresAt: now + cacheTtl });
|
|
49
|
+
return result;
|
|
50
|
+
} catch (err) {
|
|
51
|
+
return { free: false, reason: "network_error" };
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
async function recordCall(path, buyerId) {
|
|
55
|
+
try {
|
|
56
|
+
await fetch(`${base}/v1/plugins/free-tier/record`, {
|
|
57
|
+
method: "POST",
|
|
58
|
+
headers: resolveHeaders(),
|
|
59
|
+
body: JSON.stringify({ path, buyerId })
|
|
60
|
+
});
|
|
61
|
+
cache.delete(cacheKey(path, buyerId));
|
|
62
|
+
} catch {
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
async function syncConfig() {
|
|
66
|
+
try {
|
|
67
|
+
const paths = config.paths ?? ["*"];
|
|
68
|
+
await fetch(`${base}/v1/plugins/free-tier/config`, {
|
|
69
|
+
method: "PUT",
|
|
70
|
+
headers: resolveHeaders(),
|
|
71
|
+
body: JSON.stringify({
|
|
72
|
+
perBuyerLimit: config.perBuyerLimit,
|
|
73
|
+
resetPeriod: config.resetPeriod ?? "never",
|
|
74
|
+
globalCap: config.globalCap ?? null,
|
|
75
|
+
paths
|
|
76
|
+
})
|
|
77
|
+
});
|
|
78
|
+
} catch (err) {
|
|
79
|
+
console.warn(`[relai:freeTier] Failed to sync config to RelAI: ${err}`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return {
|
|
83
|
+
name: "free-tier",
|
|
84
|
+
async onInit() {
|
|
85
|
+
await syncConfig();
|
|
86
|
+
},
|
|
87
|
+
async beforePaymentCheck(req, ctx) {
|
|
88
|
+
const requestPath = ctx.path || "/";
|
|
89
|
+
const paths = config.paths ?? ["*"];
|
|
90
|
+
const pathMatches = paths.includes("*") || paths.some((p) => {
|
|
91
|
+
const normalized = p.toLowerCase().replace(/\/+$/, "") || "/";
|
|
92
|
+
const reqNormalized = requestPath.toLowerCase().replace(/\/+$/, "") || "/";
|
|
93
|
+
return normalized === reqNormalized || normalized === "*";
|
|
94
|
+
});
|
|
95
|
+
if (!pathMatches) {
|
|
96
|
+
return {};
|
|
97
|
+
}
|
|
98
|
+
const buyerId = resolveBuyerId(req);
|
|
99
|
+
const result = await checkFreeTier(requestPath, buyerId);
|
|
100
|
+
if (result.free) {
|
|
101
|
+
recordCall(requestPath, buyerId).catch(() => {
|
|
102
|
+
});
|
|
103
|
+
return {
|
|
104
|
+
skip: true,
|
|
105
|
+
headers: {
|
|
106
|
+
"X-Free-Calls-Remaining": String(result.remaining ?? 0),
|
|
107
|
+
"X-Free-Calls-Total": String(result.total ?? config.perBuyerLimit),
|
|
108
|
+
...result.globalRemaining != null ? { "X-Free-Calls-Global-Remaining": String(result.globalRemaining) } : {}
|
|
109
|
+
},
|
|
110
|
+
meta: {
|
|
111
|
+
freeTier: true,
|
|
112
|
+
buyerId,
|
|
113
|
+
remaining: result.remaining,
|
|
114
|
+
total: result.total ?? config.perBuyerLimit
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
return {};
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
export {
|
|
123
|
+
freeTier
|
|
124
|
+
};
|
|
125
|
+
//# sourceMappingURL=plugins.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/plugins.ts"],"sourcesContent":["// src/plugins.ts\n// RelAI Plugin System - extensible middleware hooks for Relai.protect()\n\nimport type { RelaiNetwork } from './types';\nimport type { SettleResult } from './server';\n\nconst RELAI_API_BASE = 'https://api.relai.fi';\n\n// ============================================================================\n// Plugin Interface\n// ============================================================================\n\nexport interface PluginContext {\n /** Network for this endpoint */\n network: RelaiNetwork;\n /** Price in USD */\n price: number;\n /** Request path */\n path: string;\n /** HTTP method */\n method: string;\n}\n\nexport interface PluginResult {\n /** If true, skip payment and serve content for free */\n skip?: boolean;\n /** Extra response headers to set */\n headers?: Record<string, string>;\n /** Metadata attached to req.pluginMeta */\n meta?: Record<string, unknown>;\n}\n\nexport interface RelaiPlugin {\n /** Unique plugin name */\n name: string;\n\n /**\n * Called before the 402 payment check.\n * Return { skip: true } to bypass payment entirely.\n */\n beforePaymentCheck?(req: any, ctx: PluginContext): Promise<PluginResult>;\n\n /**\n * Called after a successful payment settlement.\n * Use for analytics, logging, webhooks, etc.\n */\n afterSettled?(req: any, result: SettleResult, ctx: PluginContext): Promise<void>;\n\n /**\n * Called once when the Relai instance initializes (server start).\n * Use to sync config to RelAI backend or validate credentials.\n */\n onInit?(): Promise<void>;\n}\n\n// ============================================================================\n// Free Tier Plugin\n// ============================================================================\n\nexport interface FreeTierPluginConfig {\n /** Service key (sk_live_...) for authenticating with RelAI API */\n serviceKey: string;\n /** Max free calls per buyer per period */\n perBuyerLimit: number;\n /** Reset period for per-buyer counters */\n resetPeriod?: 'never' | 'daily' | 'monthly';\n /** Optional global cap across all buyers */\n globalCap?: number;\n /** Specific paths to apply free tier to (default: '*' = all) */\n paths?: string[];\n /** Override RelAI API base URL (default: https://api.relai.fi) */\n baseUrl?: string;\n /** Cache TTL in ms for check results (default: 5000) */\n cacheTtlMs?: number;\n}\n\ninterface FreeTierCheckResponse {\n free: boolean;\n remaining?: number;\n total?: number;\n reason?: string;\n globalRemaining?: number;\n}\n\n/**\n * Free Tier plugin - gives buyers a number of free API calls\n * before requiring payment.\n *\n * State is stored in the RelAI backend, keyed by your service key.\n * Config can be set here (SDK-side) or overridden in the relai.fi dashboard.\n *\n * @example\n * ```typescript\n * import Relai from '@relai-fi/x402/server';\n * import { freeTier } from '@relai-fi/x402/plugins';\n *\n * const relai = new Relai({\n * network: 'base',\n * plugins: [\n * freeTier({\n * serviceKey: process.env.RELAI_SERVICE_KEY!,\n * perBuyerLimit: 10,\n * resetPeriod: 'daily',\n * }),\n * ],\n * });\n *\n * app.get('/api/data', relai.protect({\n * payTo: '0xYourWallet',\n * price: 0.01,\n * }), (req, res) => {\n * res.json({ data: 'paid content' });\n * });\n * ```\n */\nexport function freeTier(config: FreeTierPluginConfig): RelaiPlugin {\n const base = (config.baseUrl ?? RELAI_API_BASE).replace(/\\/$/, '');\n const cacheTtl = config.cacheTtlMs ?? 5000;\n\n // Simple in-memory cache: \"serviceKey:path:buyerId\" -> { result, expiresAt }\n const cache = new Map<string, { result: FreeTierCheckResponse; expiresAt: number }>();\n\n function resolveHeaders(): Record<string, string> {\n return {\n 'X-Service-Key': config.serviceKey,\n 'Content-Type': 'application/json',\n };\n }\n\n /**\n * Resolve buyer identity from the request.\n * Priority: JWT sub > x-wallet-address > IP fallback\n */\n function resolveBuyerId(req: any): string {\n // 1. JWT Bearer token\n try {\n const auth = req.headers?.authorization || '';\n if (auth.startsWith('Bearer ')) {\n const token = auth.slice(7).trim();\n const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());\n if (payload?.sub) return `user:${payload.sub}`;\n }\n } catch { /* ignore */ }\n\n // 2. Explicit wallet header\n const wallet = req.headers?.['x-wallet-address'] || req.headers?.['x-buyer-address'];\n if (wallet) return `wallet:${wallet}`;\n\n // 3. IP fallback\n const ip =\n (req.headers?.['x-forwarded-for'] || '').split(',')[0].trim() ||\n req.socket?.remoteAddress ||\n req.ip ||\n 'unknown';\n return `ip:${ip}`;\n }\n\n function cacheKey(path: string, buyerId: string): string {\n return `${config.serviceKey}:${path}:${buyerId}`;\n }\n\n async function checkFreeTier(path: string, buyerId: string): Promise<FreeTierCheckResponse> {\n const key = cacheKey(path, buyerId);\n const now = Date.now();\n const cached = cache.get(key);\n if (cached && cached.expiresAt > now) {\n return cached.result;\n }\n\n try {\n const res = await fetch(`${base}/v1/plugins/free-tier/check`, {\n method: 'POST',\n headers: resolveHeaders(),\n body: JSON.stringify({ path, buyerId }),\n });\n\n if (!res.ok) {\n // Non-blocking: if API unreachable, default to not-free\n return { free: false, reason: `api_error_${res.status}` };\n }\n\n const result = await res.json() as FreeTierCheckResponse;\n cache.set(key, { result, expiresAt: now + cacheTtl });\n return result;\n } catch (err) {\n // Network error - non-blocking, default to paid\n return { free: false, reason: 'network_error' };\n }\n }\n\n async function recordCall(path: string, buyerId: string): Promise<void> {\n try {\n await fetch(`${base}/v1/plugins/free-tier/record`, {\n method: 'POST',\n headers: resolveHeaders(),\n body: JSON.stringify({ path, buyerId }),\n });\n // Invalidate cache for this buyer+path after recording\n cache.delete(cacheKey(path, buyerId));\n } catch {\n // Fire-and-forget\n }\n }\n\n async function syncConfig(): Promise<void> {\n try {\n const paths = config.paths ?? ['*'];\n await fetch(`${base}/v1/plugins/free-tier/config`, {\n method: 'PUT',\n headers: resolveHeaders(),\n body: JSON.stringify({\n perBuyerLimit: config.perBuyerLimit,\n resetPeriod: config.resetPeriod ?? 'never',\n globalCap: config.globalCap ?? null,\n paths,\n }),\n });\n } catch (err) {\n console.warn(`[relai:freeTier] Failed to sync config to RelAI: ${err}`);\n }\n }\n\n return {\n name: 'free-tier',\n\n async onInit() {\n await syncConfig();\n },\n\n async beforePaymentCheck(req, ctx) {\n const requestPath = ctx.path || '/';\n\n // Check if this path is covered by the plugin\n const paths = config.paths ?? ['*'];\n const pathMatches = paths.includes('*') || paths.some((p) => {\n const normalized = p.toLowerCase().replace(/\\/+$/, '') || '/';\n const reqNormalized = requestPath.toLowerCase().replace(/\\/+$/, '') || '/';\n return normalized === reqNormalized || normalized === '*';\n });\n\n if (!pathMatches) {\n return {};\n }\n\n const buyerId = resolveBuyerId(req);\n const result = await checkFreeTier(requestPath, buyerId);\n\n if (result.free) {\n // Record the call (fire-and-forget)\n recordCall(requestPath, buyerId).catch(() => {});\n\n return {\n skip: true,\n headers: {\n 'X-Free-Calls-Remaining': String(result.remaining ?? 0),\n 'X-Free-Calls-Total': String(result.total ?? config.perBuyerLimit),\n ...(result.globalRemaining != null\n ? { 'X-Free-Calls-Global-Remaining': String(result.globalRemaining) }\n : {}),\n },\n meta: {\n freeTier: true,\n buyerId,\n remaining: result.remaining,\n total: result.total ?? config.perBuyerLimit,\n },\n };\n }\n\n return {};\n },\n };\n}\n"],"mappings":";AAMA,IAAM,iBAAiB;AA6GhB,SAAS,SAAS,QAA2C;AAClE,QAAM,QAAQ,OAAO,WAAW,gBAAgB,QAAQ,OAAO,EAAE;AACjE,QAAM,WAAW,OAAO,cAAc;AAGtC,QAAM,QAAQ,oBAAI,IAAkE;AAEpF,WAAS,iBAAyC;AAChD,WAAO;AAAA,MACL,iBAAiB,OAAO;AAAA,MACxB,gBAAgB;AAAA,IAClB;AAAA,EACF;AAMA,WAAS,eAAe,KAAkB;AAExC,QAAI;AACF,YAAM,OAAO,IAAI,SAAS,iBAAiB;AAC3C,UAAI,KAAK,WAAW,SAAS,GAAG;AAC9B,cAAM,QAAQ,KAAK,MAAM,CAAC,EAAE,KAAK;AACjC,cAAM,UAAU,KAAK,MAAM,OAAO,KAAK,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,QAAQ,EAAE,SAAS,CAAC;AAChF,YAAI,SAAS,IAAK,QAAO,QAAQ,QAAQ,GAAG;AAAA,MAC9C;AAAA,IACF,QAAQ;AAAA,IAAe;AAGvB,UAAM,SAAS,IAAI,UAAU,kBAAkB,KAAK,IAAI,UAAU,iBAAiB;AACnF,QAAI,OAAQ,QAAO,UAAU,MAAM;AAGnC,UAAM,MACH,IAAI,UAAU,iBAAiB,KAAK,IAAI,MAAM,GAAG,EAAE,CAAC,EAAE,KAAK,KAC5D,I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AAA,YACV;AAAA,YACA,WAAW,OAAO;AAAA,YAClB,OAAO,OAAO,SAAS,OAAO;AAAA,UAChC;AAAA,QACF;AAAA,MACF;AAEA,aAAO,CAAC;AAAA,IACV;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { a as RelaiNetwork } from './types-Y9ni5XwY.cjs';
|
|
2
|
+
|
|
3
|
+
interface PluginContext {
|
|
4
|
+
/** Network for this endpoint */
|
|
5
|
+
network: RelaiNetwork;
|
|
6
|
+
/** Price in USD */
|
|
7
|
+
price: number;
|
|
8
|
+
/** Request path */
|
|
9
|
+
path: string;
|
|
10
|
+
/** HTTP method */
|
|
11
|
+
method: string;
|
|
12
|
+
}
|
|
13
|
+
interface PluginResult {
|
|
14
|
+
/** If true, skip payment and serve content for free */
|
|
15
|
+
skip?: boolean;
|
|
16
|
+
/** Extra response headers to set */
|
|
17
|
+
headers?: Record<string, string>;
|
|
18
|
+
/** Metadata attached to req.pluginMeta */
|
|
19
|
+
meta?: Record<string, unknown>;
|
|
20
|
+
}
|
|
21
|
+
interface RelaiPlugin {
|
|
22
|
+
/** Unique plugin name */
|
|
23
|
+
name: string;
|
|
24
|
+
/**
|
|
25
|
+
* Called before the 402 payment check.
|
|
26
|
+
* Return { skip: true } to bypass payment entirely.
|
|
27
|
+
*/
|
|
28
|
+
beforePaymentCheck?(req: any, ctx: PluginContext): Promise<PluginResult>;
|
|
29
|
+
/**
|
|
30
|
+
* Called after a successful payment settlement.
|
|
31
|
+
* Use for analytics, logging, webhooks, etc.
|
|
32
|
+
*/
|
|
33
|
+
afterSettled?(req: any, result: SettleResult, ctx: PluginContext): Promise<void>;
|
|
34
|
+
/**
|
|
35
|
+
* Called once when the Relai instance initializes (server start).
|
|
36
|
+
* Use to sync config to RelAI backend or validate credentials.
|
|
37
|
+
*/
|
|
38
|
+
onInit?(): Promise<void>;
|
|
39
|
+
}
|
|
40
|
+
interface FreeTierPluginConfig {
|
|
41
|
+
/** Service key (sk_live_...) for authenticating with RelAI API */
|
|
42
|
+
serviceKey: string;
|
|
43
|
+
/** Max free calls per buyer per period */
|
|
44
|
+
perBuyerLimit: number;
|
|
45
|
+
/** Reset period for per-buyer counters */
|
|
46
|
+
resetPeriod?: 'never' | 'daily' | 'monthly';
|
|
47
|
+
/** Optional global cap across all buyers */
|
|
48
|
+
globalCap?: number;
|
|
49
|
+
/** Specific paths to apply free tier to (default: '*' = all) */
|
|
50
|
+
paths?: string[];
|
|
51
|
+
/** Override RelAI API base URL (default: https://api.relai.fi) */
|
|
52
|
+
baseUrl?: string;
|
|
53
|
+
/** Cache TTL in ms for check results (default: 5000) */
|
|
54
|
+
cacheTtlMs?: number;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Free Tier plugin - gives buyers a number of free API calls
|
|
58
|
+
* before requiring payment.
|
|
59
|
+
*
|
|
60
|
+
* State is stored in the RelAI backend, keyed by your service key.
|
|
61
|
+
* Config can be set here (SDK-side) or overridden in the relai.fi dashboard.
|
|
62
|
+
*
|
|
63
|
+
* @example
|
|
64
|
+
* ```typescript
|
|
65
|
+
* import Relai from '@relai-fi/x402/server';
|
|
66
|
+
* import { freeTier } from '@relai-fi/x402/plugins';
|
|
67
|
+
*
|
|
68
|
+
* const relai = new Relai({
|
|
69
|
+
* network: 'base',
|
|
70
|
+
* plugins: [
|
|
71
|
+
* freeTier({
|
|
72
|
+
* serviceKey: process.env.RELAI_SERVICE_KEY!,
|
|
73
|
+
* perBuyerLimit: 10,
|
|
74
|
+
* resetPeriod: 'daily',
|
|
75
|
+
* }),
|
|
76
|
+
* ],
|
|
77
|
+
* });
|
|
78
|
+
*
|
|
79
|
+
* app.get('/api/data', relai.protect({
|
|
80
|
+
* payTo: '0xYourWallet',
|
|
81
|
+
* price: 0.01,
|
|
82
|
+
* }), (req, res) => {
|
|
83
|
+
* res.json({ data: 'paid content' });
|
|
84
|
+
* });
|
|
85
|
+
* ```
|
|
86
|
+
*/
|
|
87
|
+
declare function freeTier(config: FreeTierPluginConfig): RelaiPlugin;
|
|
88
|
+
|
|
89
|
+
interface RelaiServerConfig {
|
|
90
|
+
/** Network to accept payments on */
|
|
91
|
+
network: RelaiNetwork;
|
|
92
|
+
/** RelAI facilitator URL (default: https://facilitator.x402.fi) */
|
|
93
|
+
facilitatorUrl?: string;
|
|
94
|
+
/** Plugins to extend protect() behavior (e.g. freeTier, rateLimit) */
|
|
95
|
+
plugins?: RelaiPlugin[];
|
|
96
|
+
}
|
|
97
|
+
type DynamicPrice = number | ((req: any) => number | Promise<number>);
|
|
98
|
+
type RelaiIntegritasFlow = 'single' | 'dual';
|
|
99
|
+
interface RelaiIntegritasOptions {
|
|
100
|
+
/** Enable Integritas by default for this endpoint */
|
|
101
|
+
enabled?: boolean;
|
|
102
|
+
/** Default flow when Integritas is enabled */
|
|
103
|
+
flow?: RelaiIntegritasFlow;
|
|
104
|
+
}
|
|
105
|
+
interface ProtectOptions {
|
|
106
|
+
/** Price in USD (e.g., 0.01 for 1 cent) */
|
|
107
|
+
price: DynamicPrice;
|
|
108
|
+
/** Optional token asset address for networks supporting multiple tokens */
|
|
109
|
+
asset?: string;
|
|
110
|
+
/** Wallet address to receive payments, or stripePayTo() for Stripe settlement */
|
|
111
|
+
payTo: string | StripePayTo;
|
|
112
|
+
/** Description shown to payer */
|
|
113
|
+
description?: string;
|
|
114
|
+
/** MIME type of the response (default: application/json) */
|
|
115
|
+
mimeType?: string;
|
|
116
|
+
/** Maximum timeout in seconds (default: 60) */
|
|
117
|
+
maxTimeoutSeconds?: number;
|
|
118
|
+
/** Integritas options (or simple boolean enable flag) */
|
|
119
|
+
integritas?: boolean | RelaiIntegritasOptions;
|
|
120
|
+
/** Override network for this endpoint */
|
|
121
|
+
network?: RelaiNetwork;
|
|
122
|
+
/** Override feePayer address (Solana only) — bypasses facilitator /supported fetch */
|
|
123
|
+
feePayer?: string;
|
|
124
|
+
/** Custom validation after payment is settled */
|
|
125
|
+
customRules?: (req: any) => boolean | Promise<boolean>;
|
|
126
|
+
/** Callback when 402 is returned (no payment provided) */
|
|
127
|
+
onPaymentRequired?: (req: any, info: {
|
|
128
|
+
price: number;
|
|
129
|
+
network: RelaiNetwork;
|
|
130
|
+
}) => void;
|
|
131
|
+
/** Callback when payment is settled successfully */
|
|
132
|
+
onPaymentSettled?: (req: any, result: SettleResult) => void;
|
|
133
|
+
/** Callback on error */
|
|
134
|
+
onError?: (req: any, error: unknown) => void;
|
|
135
|
+
}
|
|
136
|
+
interface SettleResult {
|
|
137
|
+
success: boolean;
|
|
138
|
+
transaction?: string;
|
|
139
|
+
payer?: string;
|
|
140
|
+
network?: string;
|
|
141
|
+
splitTransfers?: Record<string, unknown>;
|
|
142
|
+
integritasFeePaid?: boolean;
|
|
143
|
+
provenance?: Record<string, unknown>;
|
|
144
|
+
integritas?: Record<string, unknown>;
|
|
145
|
+
error?: string;
|
|
146
|
+
errorReason?: string;
|
|
147
|
+
}
|
|
148
|
+
interface PaymentInfo {
|
|
149
|
+
verified: boolean;
|
|
150
|
+
transactionId?: string;
|
|
151
|
+
payer?: string;
|
|
152
|
+
network: RelaiNetwork;
|
|
153
|
+
amount: number;
|
|
154
|
+
}
|
|
155
|
+
/** Config returned by stripePayTo() - used by protect() to create Stripe deposit addresses */
|
|
156
|
+
interface StripePayTo {
|
|
157
|
+
readonly __brand: 'stripePayTo';
|
|
158
|
+
readonly secretKey: string;
|
|
159
|
+
/** Stripe crypto deposits network (default: 'base') */
|
|
160
|
+
readonly stripeNetwork: string;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Create a Stripe pay-to configuration for x402 payments.
|
|
164
|
+
* Payments settle as USD in your Stripe Dashboard - no crypto knowledge required.
|
|
165
|
+
*
|
|
166
|
+
* Stripe creates a fresh PaymentIntent + deposit address per request.
|
|
167
|
+
* Network is auto-set to Base (Stripe settles USDC on Base).
|
|
168
|
+
*
|
|
169
|
+
* @example
|
|
170
|
+
* ```typescript
|
|
171
|
+
* import Relai, { stripePayTo } from '@relai-fi/x402/server';
|
|
172
|
+
*
|
|
173
|
+
* const relai = new Relai({ network: 'base' });
|
|
174
|
+
*
|
|
175
|
+
* app.get('/api/data', relai.protect({
|
|
176
|
+
* price: 0.01,
|
|
177
|
+
* payTo: stripePayTo(process.env.STRIPE_SECRET_KEY!),
|
|
178
|
+
* }), (req, res) => {
|
|
179
|
+
* res.json({ data: 'paid content' });
|
|
180
|
+
* });
|
|
181
|
+
* ```
|
|
182
|
+
*/
|
|
183
|
+
declare function stripePayTo(stripeSecretKey: string, options?: {
|
|
184
|
+
network?: string;
|
|
185
|
+
}): StripePayTo;
|
|
186
|
+
/**
|
|
187
|
+
* Server-side SDK for protecting Express endpoints with x402 micropayments.
|
|
188
|
+
* Settles payments through the RelAI facilitator (zero gas fees for users).
|
|
189
|
+
*
|
|
190
|
+
* Supports: Solana, Base, Avalanche, SKALE Base, SKALE Base Sepolia, SKALE BITE, Polygon, and Ethereum.
|
|
191
|
+
*
|
|
192
|
+
* @example
|
|
193
|
+
* ```typescript
|
|
194
|
+
* import Relai from '@relai-fi/x402/server';
|
|
195
|
+
*
|
|
196
|
+
* const relai = new Relai({ network: 'base' });
|
|
197
|
+
*
|
|
198
|
+
* app.get('/api/data', relai.protect({
|
|
199
|
+
* payTo: '0xYourWallet',
|
|
200
|
+
* price: 0.01, // $0.01 USDC
|
|
201
|
+
* }), (req, res) => {
|
|
202
|
+
* res.json({ data: 'Protected content', payment: req.payment });
|
|
203
|
+
* });
|
|
204
|
+
* ```
|
|
205
|
+
*/
|
|
206
|
+
declare class Relai {
|
|
207
|
+
private network;
|
|
208
|
+
private facilitatorUrl;
|
|
209
|
+
private feePayerCache;
|
|
210
|
+
private plugins;
|
|
211
|
+
private pluginInitPromise;
|
|
212
|
+
constructor(config: RelaiServerConfig);
|
|
213
|
+
private runPluginInit;
|
|
214
|
+
/**
|
|
215
|
+
* Get feePayer address for a network (cached)
|
|
216
|
+
*/
|
|
217
|
+
private getFeePayer;
|
|
218
|
+
/**
|
|
219
|
+
* Express middleware to protect an endpoint with x402 micropayments.
|
|
220
|
+
*
|
|
221
|
+
* Flow:
|
|
222
|
+
* 1. No payment header → returns 402 with payment requirements
|
|
223
|
+
* 2. Payment header present → calls RelAI facilitator `/settle`
|
|
224
|
+
* 3. Settlement success → sets `PAYMENT-RESPONSE` header, attaches `req.payment`, calls `next()`
|
|
225
|
+
*/
|
|
226
|
+
protect(options: ProtectOptions): (req: any, res: any, next: any) => Promise<any>;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export { type DynamicPrice as D, type FreeTierPluginConfig as F, type ProtectOptions as P, Relai as R, type SettleResult as S, type RelaiServerConfig as a, type PaymentInfo as b, type StripePayTo as c, type RelaiIntegritasFlow as d, type RelaiIntegritasOptions as e, type RelaiPlugin as f, type PluginContext as g, type PluginResult as h, freeTier as i, stripePayTo as s };
|