@foldset/cloudflare 0.0.1 → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -30
- package/dist/index.js +75 -149
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,36 +1,7 @@
|
|
|
1
|
-
import { Hono
|
|
2
|
-
import { PaywallConfig, PaywallProvider, x402ResourceServer } from '@x402/hono';
|
|
3
|
-
import type { RoutesConfig } from '@x402/core/http';
|
|
1
|
+
import { Hono } from 'hono';
|
|
4
2
|
type Env = {
|
|
5
3
|
FOLDSET_API_KEY: string;
|
|
6
4
|
};
|
|
7
|
-
/**
|
|
8
|
-
* Hono payment middleware for x402 protocol (direct server instance).
|
|
9
|
-
*
|
|
10
|
-
* Use this when you want to pass a pre-configured x402ResourceServer instance.
|
|
11
|
-
* This provides more flexibility for testing, custom configuration, and reusing
|
|
12
|
-
* server instances across multiple middlewares.
|
|
13
|
-
*
|
|
14
|
-
* @param routes - Route configurations for protected endpoints
|
|
15
|
-
* @param server - Pre-configured x402ResourceServer instance
|
|
16
|
-
* @param paywallConfig - Optional configuration for the built-in paywall UI
|
|
17
|
-
* @param paywall - Optional custom paywall provider (overrides default)
|
|
18
|
-
* @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)
|
|
19
|
-
* @returns Hono middleware handler
|
|
20
|
-
*
|
|
21
|
-
* @example
|
|
22
|
-
* ```typescript
|
|
23
|
-
* import { paymentMiddleware } from "@x402/hono";
|
|
24
|
-
* import { x402ResourceServer } from "@x402/core/server";
|
|
25
|
-
* import { registerExactEvmScheme } from "@x402/evm/exact/server";
|
|
26
|
-
*
|
|
27
|
-
* const server = new x402ResourceServer(myFacilitatorClient);
|
|
28
|
-
* registerExactEvmScheme(server, {});
|
|
29
|
-
*
|
|
30
|
-
* app.use(paymentMiddleware(routes, server, paywallConfig));
|
|
31
|
-
* ```
|
|
32
|
-
*/
|
|
33
|
-
export declare function paymentMiddleware(routes: RoutesConfig, server: x402ResourceServer, paywallConfig?: PaywallConfig, paywall?: PaywallProvider, syncFacilitatorOnStart?: boolean): MiddlewareHandler;
|
|
34
5
|
declare const app: Hono<{
|
|
35
6
|
Bindings: Env;
|
|
36
7
|
}, import("hono/types").BlankSchema, "/">;
|
package/dist/index.js
CHANGED
|
@@ -3,9 +3,8 @@ import { Hono } from 'hono';
|
|
|
3
3
|
import { x402ResourceServer, x402HTTPResourceServer } from '@x402/hono';
|
|
4
4
|
import { registerExactEvmScheme } from '@x402/evm/exact/server';
|
|
5
5
|
import { HTTPFacilitatorClient } from '@x402/core/server';
|
|
6
|
-
import pMemoize from 'p-memoize';
|
|
7
6
|
import { HonoAdapter } from './adapter';
|
|
8
|
-
async function
|
|
7
|
+
async function fetchFoldsetAPI(endpoint, env) {
|
|
9
8
|
const res = await fetch(`https://api.foldset.com/v1/${endpoint}`, {
|
|
10
9
|
method: 'GET',
|
|
11
10
|
headers: {
|
|
@@ -18,15 +17,6 @@ async function _fetchFoldsetAPI(endpoint, env) {
|
|
|
18
17
|
}
|
|
19
18
|
return (await res.json());
|
|
20
19
|
}
|
|
21
|
-
const cacheTTL = 60000; // 60 seconds
|
|
22
|
-
// This is an in memory cache. Cloudflare also has a cache but it is not
|
|
23
|
-
// in memory, so it would survive cold starts (this won't). I think in-memory
|
|
24
|
-
// makes more sense here for now.
|
|
25
|
-
// TODO rfradkin: Also make sure this caching works, didn't test it
|
|
26
|
-
const fetchFoldsetAPI = pMemoize(_fetchFoldsetAPI, {
|
|
27
|
-
maxAge: cacheTTL,
|
|
28
|
-
cacheKey: ([endpoint]) => endpoint,
|
|
29
|
-
});
|
|
30
20
|
async function getRestrictions(env) {
|
|
31
21
|
const restrictionList = await fetchFoldsetAPI('restrictions', env);
|
|
32
22
|
const restrictions = {};
|
|
@@ -35,6 +25,7 @@ async function getRestrictions(env) {
|
|
|
35
25
|
}
|
|
36
26
|
return restrictions;
|
|
37
27
|
}
|
|
28
|
+
// TODO rfradkin: Should change to get addresses...
|
|
38
29
|
async function getEVMAddress(env) {
|
|
39
30
|
const data = await fetchFoldsetAPI('get-address', env);
|
|
40
31
|
return data.address;
|
|
@@ -63,7 +54,9 @@ let server = null;
|
|
|
63
54
|
// Right now, load times are like 800ms, which is pretty slow since
|
|
64
55
|
// static site is 200ms. Look into later, this call probably takes most of the time.
|
|
65
56
|
// This is like this cause can'd do async calls at module level in cloudflare
|
|
66
|
-
function
|
|
57
|
+
async function getHttpServer(routes, env) {
|
|
58
|
+
// At some point allow users to dynamically choose facilitator
|
|
59
|
+
// Setup endpoint for that
|
|
67
60
|
if (!server) {
|
|
68
61
|
// TODO rfradkin: Hard coded for now but consider making it configurable
|
|
69
62
|
const facilitatorClient = new HTTPFacilitatorClient({
|
|
@@ -72,153 +65,86 @@ function getServer() {
|
|
|
72
65
|
server = new x402ResourceServer(facilitatorClient);
|
|
73
66
|
registerExactEvmScheme(server);
|
|
74
67
|
}
|
|
75
|
-
return server;
|
|
76
|
-
}
|
|
77
|
-
/**
|
|
78
|
-
* Hono payment middleware for x402 protocol (direct server instance).
|
|
79
|
-
*
|
|
80
|
-
* Use this when you want to pass a pre-configured x402ResourceServer instance.
|
|
81
|
-
* This provides more flexibility for testing, custom configuration, and reusing
|
|
82
|
-
* server instances across multiple middlewares.
|
|
83
|
-
*
|
|
84
|
-
* @param routes - Route configurations for protected endpoints
|
|
85
|
-
* @param server - Pre-configured x402ResourceServer instance
|
|
86
|
-
* @param paywallConfig - Optional configuration for the built-in paywall UI
|
|
87
|
-
* @param paywall - Optional custom paywall provider (overrides default)
|
|
88
|
-
* @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)
|
|
89
|
-
* @returns Hono middleware handler
|
|
90
|
-
*
|
|
91
|
-
* @example
|
|
92
|
-
* ```typescript
|
|
93
|
-
* import { paymentMiddleware } from "@x402/hono";
|
|
94
|
-
* import { x402ResourceServer } from "@x402/core/server";
|
|
95
|
-
* import { registerExactEvmScheme } from "@x402/evm/exact/server";
|
|
96
|
-
*
|
|
97
|
-
* const server = new x402ResourceServer(myFacilitatorClient);
|
|
98
|
-
* registerExactEvmScheme(server, {});
|
|
99
|
-
*
|
|
100
|
-
* app.use(paymentMiddleware(routes, server, paywallConfig));
|
|
101
|
-
* ```
|
|
102
|
-
*/
|
|
103
|
-
export function paymentMiddleware(routes, server, paywallConfig, paywall, syncFacilitatorOnStart = true) {
|
|
104
|
-
// Create the x402 HTTP server instance with the resource server
|
|
105
68
|
const httpServer = new x402HTTPResourceServer(server, routes);
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
httpServer.registerPaywallProvider(paywall);
|
|
109
|
-
}
|
|
110
|
-
// Store initialization promise (not the result)
|
|
111
|
-
// httpServer.initialize() fetches facilitator support and validates routes
|
|
112
|
-
let initPromise = syncFacilitatorOnStart ? httpServer.initialize() : null;
|
|
113
|
-
// TODO rfradkin: Add bazaar extension
|
|
114
|
-
// // Dynamically register bazaar extension if routes declare it
|
|
115
|
-
// let bazaarPromise: Promise<void> | null = null;
|
|
116
|
-
// if (checkIfBazaarNeeded(routes)) {
|
|
117
|
-
// bazaarPromise = import("@x402/extensions/bazaar")
|
|
118
|
-
// .then(({ bazaarResourceServerExtension }) => {
|
|
119
|
-
// server.registerExtension(bazaarResourceServerExtension);
|
|
120
|
-
// })
|
|
121
|
-
// .catch(err => {
|
|
122
|
-
// console.error("Failed to load bazaar extension:", err);
|
|
123
|
-
// });
|
|
124
|
-
// }
|
|
125
|
-
return async (c, next) => {
|
|
126
|
-
// Create adapter and context
|
|
127
|
-
const adapter = new HonoAdapter(c);
|
|
128
|
-
const context = {
|
|
129
|
-
adapter,
|
|
130
|
-
path: c.req.path,
|
|
131
|
-
method: c.req.method,
|
|
132
|
-
paymentHeader: adapter.getHeader("payment-signature") || adapter.getHeader("x-payment"),
|
|
133
|
-
};
|
|
134
|
-
// Check if route requires payment before initializing facilitator
|
|
135
|
-
if (!httpServer.requiresPayment(context)) {
|
|
136
|
-
return next();
|
|
137
|
-
}
|
|
138
|
-
// Only initialize when processing a protected route
|
|
139
|
-
if (initPromise) {
|
|
140
|
-
await initPromise;
|
|
141
|
-
initPromise = null; // Clear after first await
|
|
142
|
-
}
|
|
143
|
-
// // Await bazaar extension loading if needed
|
|
144
|
-
// if (bazaarPromise) {
|
|
145
|
-
// await bazaarPromise;
|
|
146
|
-
// bazaarPromise = null;
|
|
147
|
-
// }
|
|
148
|
-
// Process payment requirement check
|
|
149
|
-
const result = await httpServer.processHTTPRequest(context, paywallConfig);
|
|
150
|
-
// Handle the different result types
|
|
151
|
-
switch (result.type) {
|
|
152
|
-
case "no-payment-required":
|
|
153
|
-
// No payment needed, proceed directly to the route handler
|
|
154
|
-
return next();
|
|
155
|
-
case "payment-error":
|
|
156
|
-
// Payment required but not provided or invalid
|
|
157
|
-
const { response } = result;
|
|
158
|
-
Object.entries(response.headers).forEach(([key, value]) => {
|
|
159
|
-
c.header(key, value);
|
|
160
|
-
});
|
|
161
|
-
if (response.isHtml) {
|
|
162
|
-
return c.html(response.body, response.status);
|
|
163
|
-
}
|
|
164
|
-
else {
|
|
165
|
-
return c.json(response.body || {}, response.status);
|
|
166
|
-
}
|
|
167
|
-
case "payment-verified":
|
|
168
|
-
// Payment is valid, need to wrap response for settlement
|
|
169
|
-
const { paymentPayload, paymentRequirements } = result;
|
|
170
|
-
// Proceed to the next middleware or route handler
|
|
171
|
-
await next();
|
|
172
|
-
// Get the current response
|
|
173
|
-
let res = c.res;
|
|
174
|
-
// If the response from the protected route is >= 400, do not settle payment
|
|
175
|
-
if (res.status >= 400) {
|
|
176
|
-
return;
|
|
177
|
-
}
|
|
178
|
-
// Clear the response so we can modify headers
|
|
179
|
-
c.res = undefined;
|
|
180
|
-
try {
|
|
181
|
-
const settleResult = await httpServer.processSettlement(paymentPayload, paymentRequirements);
|
|
182
|
-
if (!settleResult.success) {
|
|
183
|
-
// Settlement failed - do not return the protected resource
|
|
184
|
-
res = c.json({
|
|
185
|
-
error: "Settlement failed",
|
|
186
|
-
details: settleResult.errorReason,
|
|
187
|
-
}, 402);
|
|
188
|
-
}
|
|
189
|
-
else {
|
|
190
|
-
// Settlement succeeded - add headers to response
|
|
191
|
-
Object.entries(settleResult.headers).forEach(([key, value]) => {
|
|
192
|
-
res.headers.set(key, value);
|
|
193
|
-
});
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
catch (error) {
|
|
197
|
-
console.error(error);
|
|
198
|
-
// If settlement fails, return an error response
|
|
199
|
-
res = c.json({
|
|
200
|
-
error: "Settlement failed",
|
|
201
|
-
details: error instanceof Error ? error.message : "Unknown error",
|
|
202
|
-
}, 402);
|
|
203
|
-
}
|
|
204
|
-
// Restore the response (potentially modified with settlement headers)
|
|
205
|
-
c.res = res;
|
|
206
|
-
return;
|
|
207
|
-
}
|
|
208
|
-
};
|
|
69
|
+
await httpServer.initialize();
|
|
70
|
+
return httpServer;
|
|
209
71
|
}
|
|
210
72
|
const app = new Hono();
|
|
211
73
|
// TODO rfradkin: This is still potentially quite slow since it is getting
|
|
212
74
|
// each of these on each request regardless of whether the request is in
|
|
213
75
|
// the restrictions or not. Should find a better solution down the road
|
|
214
76
|
app.use('*', async (c, next) => {
|
|
215
|
-
const [restrictions, payTo
|
|
77
|
+
const [restrictions, payTo] = await Promise.all([
|
|
216
78
|
getRestrictions(c.env),
|
|
217
79
|
getEVMAddress(c.env),
|
|
218
|
-
getServer(),
|
|
219
80
|
]);
|
|
220
|
-
const
|
|
221
|
-
|
|
81
|
+
const routes = buildRoutesConfig(restrictions, payTo);
|
|
82
|
+
const httpServer = await getHttpServer(routes, c.env);
|
|
83
|
+
const adapter = new HonoAdapter(c);
|
|
84
|
+
const context = {
|
|
85
|
+
adapter,
|
|
86
|
+
path: c.req.path,
|
|
87
|
+
method: c.req.method,
|
|
88
|
+
paymentHeader: adapter.getHeader("payment-signature") || adapter.getHeader("x-payment"),
|
|
89
|
+
};
|
|
90
|
+
if (!httpServer.requiresPayment(context)) {
|
|
91
|
+
return next();
|
|
92
|
+
}
|
|
93
|
+
const result = await httpServer.processHTTPRequest(context);
|
|
94
|
+
switch (result.type) {
|
|
95
|
+
case "no-payment-required":
|
|
96
|
+
return next();
|
|
97
|
+
case "payment-error":
|
|
98
|
+
// Payment required but not provided or invalid
|
|
99
|
+
const { response } = result;
|
|
100
|
+
Object.entries(response.headers).forEach(([key, value]) => {
|
|
101
|
+
c.header(key, value);
|
|
102
|
+
});
|
|
103
|
+
if (response.isHtml) {
|
|
104
|
+
return c.html(response.body, response.status);
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
return c.json(response.body || {}, response.status);
|
|
108
|
+
}
|
|
109
|
+
case "payment-verified":
|
|
110
|
+
// Payment is valid, need to wrap response for settlement
|
|
111
|
+
const { paymentPayload, paymentRequirements } = result;
|
|
112
|
+
await next();
|
|
113
|
+
let res = c.res;
|
|
114
|
+
// If the response from the protected route is >= 400, do not settle payment
|
|
115
|
+
if (res.status >= 400) {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
// Clear the response so we can modify headers
|
|
119
|
+
c.res = undefined;
|
|
120
|
+
try {
|
|
121
|
+
const settleResult = await httpServer.processSettlement(paymentPayload, paymentRequirements);
|
|
122
|
+
if (!settleResult.success) {
|
|
123
|
+
// Settlement failed - do not return the protected resource
|
|
124
|
+
res = c.json({
|
|
125
|
+
error: "Settlement failed",
|
|
126
|
+
details: settleResult.errorReason,
|
|
127
|
+
}, 402);
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
// Settlement succeeded - add headers to response
|
|
131
|
+
Object.entries(settleResult.headers).forEach(([key, value]) => {
|
|
132
|
+
res.headers.set(key, value);
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
console.error(error);
|
|
138
|
+
// If settlement fails, return an error response
|
|
139
|
+
res = c.json({
|
|
140
|
+
error: "Settlement failed",
|
|
141
|
+
details: error instanceof Error ? error.message : "Unknown error",
|
|
142
|
+
}, 402);
|
|
143
|
+
}
|
|
144
|
+
// Restore the response (potentially modified with settlement headers)
|
|
145
|
+
c.res = res;
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
222
148
|
});
|
|
223
149
|
app.all('*', async (c) => {
|
|
224
150
|
const req = c.req.raw;
|