@routedock/routedock 0.1.2 → 0.2.0
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 +21 -0
- package/README.md +227 -4
- package/dist/MppSessionHandler-B4TyD7Xg.d.cts +121 -0
- package/dist/MppSessionHandler-CLB5SzgN.d.ts +121 -0
- package/dist/ProviderRegistry-BJ9oJLVz.d.cts +142 -0
- package/dist/ProviderRegistry-C50nyhaF.d.ts +142 -0
- package/dist/RouteDockClient-B1roCa8h.d.cts +455 -0
- package/dist/RouteDockClient-BbkqjhMG.d.ts +455 -0
- package/dist/SessionReconciler-Dscw43F3.d.ts +125 -0
- package/dist/SessionReconciler-bi0z2qtN.d.cts +125 -0
- package/dist/SessionStore-BpK8vv0L.d.cts +111 -0
- package/dist/SessionStore-DvkZv8-E.d.ts +111 -0
- package/dist/client.cjs +2419 -202
- package/dist/client.d.cts +50 -81
- package/dist/client.d.ts +50 -81
- package/dist/client.js +2373 -203
- package/dist/index.cjs +3080 -298
- package/dist/index.d.cts +12 -3
- package/dist/index.d.ts +12 -3
- package/dist/index.js +3026 -298
- package/dist/provider/fastify.cjs +882 -0
- package/dist/provider/fastify.d.cts +35 -0
- package/dist/provider/fastify.d.ts +35 -0
- package/dist/provider/fastify.js +880 -0
- package/dist/provider/hono.cjs +948 -0
- package/dist/provider/hono.d.cts +99 -0
- package/dist/provider/hono.d.ts +99 -0
- package/dist/provider/hono.js +938 -0
- package/dist/provider.cjs +827 -97
- package/dist/provider.d.cts +32 -25
- package/dist/provider.d.ts +32 -25
- package/dist/provider.js +810 -99
- package/dist/react.cjs +2641 -0
- package/dist/react.d.cts +107 -0
- package/dist/react.d.ts +107 -0
- package/dist/react.js +2634 -0
- package/dist/routedockMiddleware-BlDsHuPl.d.ts +59 -0
- package/dist/routedockMiddleware-D97A5ptQ.d.cts +59 -0
- package/dist/schema.cjs +364 -0
- package/dist/schema.d.cts +3 -0
- package/dist/schema.d.ts +3 -0
- package/dist/schema.js +359 -0
- package/dist/sign-CUf3rhTx.d.cts +53 -0
- package/dist/sign-Dpj2Mp7k.d.ts +53 -0
- package/dist/testing.cjs +57 -0
- package/dist/testing.d.cts +95 -0
- package/dist/testing.d.ts +95 -0
- package/dist/testing.js +54 -0
- package/dist/types-DmhmfLzP.d.cts +410 -0
- package/dist/types-DmhmfLzP.d.ts +410 -0
- package/package.json +143 -23
- package/PUBLISH_CHECKLIST.md +0 -70
- package/dist/SessionStore-CCVO0PHM.d.cts +0 -152
- package/dist/SessionStore-CCVO0PHM.d.ts +0 -152
- package/dist/routedockMiddleware-B7WTB3LT.d.cts +0 -53
- package/dist/routedockMiddleware-DRgdrycG.d.ts +0 -53
- package/src/client/ModeRouter.ts +0 -104
- package/src/client/MppChargeClient.ts +0 -44
- package/src/client/MppSessionClient.ts +0 -144
- package/src/client/RouteDockClient.ts +0 -124
- package/src/client/index.ts +0 -8
- package/src/client/x402Client.ts +0 -84
- package/src/index.ts +0 -9
- package/src/provider/MppChargeHandler.ts +0 -90
- package/src/provider/MppSessionHandler.ts +0 -157
- package/src/provider/index.ts +0 -7
- package/src/provider/routedockMiddleware.ts +0 -154
- package/src/provider/x402Handler.ts +0 -164
- package/src/schemas/routedock.schema.json +0 -159
- package/src/store/SessionStore.ts +0 -90
- package/src/tests/smoke.test.ts +0 -228
- package/src/types.ts +0 -165
- package/tsconfig.json +0 -14
- package/tsup.config.ts +0 -15
|
@@ -0,0 +1,882 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var stellarSdk = require('@stellar/stellar-sdk');
|
|
4
|
+
var facilitator = require('@x402/stellar/exact/facilitator');
|
|
5
|
+
var server$1 = require('@x402/stellar/exact/server');
|
|
6
|
+
var server = require('@x402/core/server');
|
|
7
|
+
var stellar = require('@x402/stellar');
|
|
8
|
+
var http = require('@x402/core/http');
|
|
9
|
+
var nulthSdk = require('@routedock/nulth-sdk');
|
|
10
|
+
var server$3 = require('@stellar/mpp/charge/server');
|
|
11
|
+
var server$2 = require('mppx/server');
|
|
12
|
+
var server$4 = require('@stellar/mpp/channel/server');
|
|
13
|
+
var mppx = require('mppx');
|
|
14
|
+
var crypto$1 = require('crypto');
|
|
15
|
+
|
|
16
|
+
// src/provider/x402Handler.ts
|
|
17
|
+
|
|
18
|
+
// src/provider/payee.ts
|
|
19
|
+
function resolvePayee(manifest, mode) {
|
|
20
|
+
const override = manifest.pricing[mode]?.payee;
|
|
21
|
+
return override ?? manifest.payee;
|
|
22
|
+
}
|
|
23
|
+
var usdcToUnits = nulthSdk.usdcToStroops;
|
|
24
|
+
function extractPayerAddress(key) {
|
|
25
|
+
if (typeof key !== "string") return null;
|
|
26
|
+
return stellarSdk.StrKey.isValidEd25519PublicKey(key) || stellarSdk.StrKey.isValidMed25519PublicKey(key) ? key : null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// src/provider/SeenTxStore.ts
|
|
30
|
+
var InMemorySeenTxStore = class {
|
|
31
|
+
map = /* @__PURE__ */ new Map();
|
|
32
|
+
order = [];
|
|
33
|
+
constructor(maxEntriesOrOptions = 1e4) {
|
|
34
|
+
const options = typeof maxEntriesOrOptions === "number" ? { maxEntries: maxEntriesOrOptions } : maxEntriesOrOptions;
|
|
35
|
+
this.maxEntries = options.maxEntries ?? 1e4;
|
|
36
|
+
if (options.warn !== false) {
|
|
37
|
+
const isServerless = typeof globalThis.navigator !== "undefined" && globalThis.navigator.userAgent === "Cloudflare-Workers";
|
|
38
|
+
if (isServerless) {
|
|
39
|
+
console.warn(
|
|
40
|
+
"[RouteDock] Using in-memory SeenTxStore: settlement deduplication is NOT durable and resets on every isolate restart. Supply a SupabaseSeenTxStore (or other durable SeenTxStore) for production safety."
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
maxEntries;
|
|
46
|
+
get(key) {
|
|
47
|
+
return this.map.get(key);
|
|
48
|
+
}
|
|
49
|
+
set(key, record) {
|
|
50
|
+
if (!this.map.has(key)) {
|
|
51
|
+
this.order.push(key);
|
|
52
|
+
if (this.order.length > this.maxEntries) {
|
|
53
|
+
const evicted = this.order.shift();
|
|
54
|
+
if (evicted !== void 0) this.map.delete(evicted);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
this.map.set(key, record);
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
async function sha256Hex(input) {
|
|
61
|
+
const buf = new TextEncoder().encode(input);
|
|
62
|
+
const digest = await crypto.subtle.digest("SHA-256", buf);
|
|
63
|
+
return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
64
|
+
}
|
|
65
|
+
async function paymentIdempotencyKey(getHeader) {
|
|
66
|
+
const material = getHeader("payment-signature") ?? getHeader("x-payment") ?? getHeader("authorization");
|
|
67
|
+
if (!material) return null;
|
|
68
|
+
return sha256Hex(material);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// src/provider/x402Handler.ts
|
|
72
|
+
var CAIP2 = {
|
|
73
|
+
testnet: "stellar:testnet",
|
|
74
|
+
mainnet: "stellar:pubnet"
|
|
75
|
+
};
|
|
76
|
+
var OZ_FACILITATOR_URL = "https://channels.openzeppelin.com/x402";
|
|
77
|
+
function createX402Handler(opts) {
|
|
78
|
+
const caip2 = CAIP2[opts.network];
|
|
79
|
+
const payeeKeypair = stellarSdk.Keypair.fromSecret(opts.payeeSecretKey);
|
|
80
|
+
const signer = stellar.createEd25519Signer(opts.payeeSecretKey, caip2);
|
|
81
|
+
const seenTxStore = opts.seenTxStore ?? new InMemorySeenTxStore();
|
|
82
|
+
const useOzFacilitator = opts.network === "mainnet" && opts.facilitatorApiKey;
|
|
83
|
+
const localFacilitator = new facilitator.ExactStellarScheme([signer], {
|
|
84
|
+
areFeesSponsored: true
|
|
85
|
+
});
|
|
86
|
+
let ozServer = null;
|
|
87
|
+
if (useOzFacilitator) {
|
|
88
|
+
const apiKey = opts.facilitatorApiKey;
|
|
89
|
+
const facilitator = new server.HTTPFacilitatorClient({
|
|
90
|
+
url: OZ_FACILITATOR_URL,
|
|
91
|
+
createAuthHeaders: async () => ({
|
|
92
|
+
verify: { Authorization: `Bearer ${apiKey}` },
|
|
93
|
+
settle: { Authorization: `Bearer ${apiKey}` },
|
|
94
|
+
supported: { Authorization: `Bearer ${apiKey}` }
|
|
95
|
+
})
|
|
96
|
+
});
|
|
97
|
+
ozServer = new server.x402ResourceServer(facilitator);
|
|
98
|
+
ozServer.register(caip2, new server$1.ExactStellarScheme());
|
|
99
|
+
}
|
|
100
|
+
const amountInBaseUnits = String(usdcToUnits(opts.amount));
|
|
101
|
+
const payTo = resolvePayee(opts.manifest, "x402");
|
|
102
|
+
const requirements = {
|
|
103
|
+
scheme: "exact",
|
|
104
|
+
network: caip2,
|
|
105
|
+
asset: opts.assetContract,
|
|
106
|
+
amount: amountInBaseUnits,
|
|
107
|
+
payTo,
|
|
108
|
+
maxTimeoutSeconds: 60,
|
|
109
|
+
extra: {
|
|
110
|
+
areFeesSponsored: true,
|
|
111
|
+
...useOzFacilitator ? {} : { facilitatorAddresses: [payeeKeypair.publicKey()] }
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
return async (req, res, next) => {
|
|
115
|
+
try {
|
|
116
|
+
const paymentHeader = req.headers["payment-signature"] ?? req.headers["x-payment"];
|
|
117
|
+
if (!paymentHeader) {
|
|
118
|
+
if (ozServer) {
|
|
119
|
+
const resourceInfo = {
|
|
120
|
+
url: `${req.protocol}://${req.get("host") ?? ""}${req.originalUrl}`,
|
|
121
|
+
description: opts.manifest.name
|
|
122
|
+
};
|
|
123
|
+
const paymentRequired = await ozServer.createPaymentRequiredResponse(
|
|
124
|
+
[requirements],
|
|
125
|
+
resourceInfo
|
|
126
|
+
);
|
|
127
|
+
res.status(402).setHeader("Content-Type", "application/json").setHeader("X-Payment-Requirements", http.encodePaymentRequiredHeader(paymentRequired)).json({ error: "Payment Required" });
|
|
128
|
+
} else {
|
|
129
|
+
const x402Response = {
|
|
130
|
+
x402Version: 2,
|
|
131
|
+
resource: {
|
|
132
|
+
url: `${req.protocol}://${req.get("host") ?? ""}${req.originalUrl}`,
|
|
133
|
+
description: opts.manifest.name
|
|
134
|
+
},
|
|
135
|
+
accepts: [requirements]
|
|
136
|
+
};
|
|
137
|
+
res.status(402).setHeader("Content-Type", "application/json").setHeader("X-Payment-Requirements", http.encodePaymentRequiredHeader(x402Response)).json({ error: "Payment Required" });
|
|
138
|
+
}
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
const idempotencyKey = await paymentIdempotencyKey((name) => {
|
|
142
|
+
const v = req.headers[name.toLowerCase()];
|
|
143
|
+
return Array.isArray(v) ? v[0] : v;
|
|
144
|
+
});
|
|
145
|
+
if (idempotencyKey) {
|
|
146
|
+
const cached = await seenTxStore.get(idempotencyKey);
|
|
147
|
+
if (cached) {
|
|
148
|
+
if (cached.headers) {
|
|
149
|
+
for (const [k, val] of Object.entries(cached.headers)) {
|
|
150
|
+
res.setHeader(k, val);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
next();
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const payload = http.decodePaymentSignatureHeader(paymentHeader);
|
|
158
|
+
let txHash = null;
|
|
159
|
+
let payerAddress = null;
|
|
160
|
+
try {
|
|
161
|
+
const creds = payload.authorization?.credentials;
|
|
162
|
+
const key = Array.isArray(creds) ? creds[0]?.publicKey : void 0;
|
|
163
|
+
payerAddress = extractPayerAddress(key);
|
|
164
|
+
} catch {
|
|
165
|
+
}
|
|
166
|
+
if (ozServer) {
|
|
167
|
+
const settleResult = await ozServer.settlePayment(payload, requirements);
|
|
168
|
+
txHash = settleResult.transaction ?? null;
|
|
169
|
+
if (settleResult) {
|
|
170
|
+
res.setHeader(
|
|
171
|
+
"X-Payment-Response",
|
|
172
|
+
http.encodePaymentResponseHeader(
|
|
173
|
+
settleResult
|
|
174
|
+
)
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
} else {
|
|
178
|
+
const verifyResult = await localFacilitator.verify(
|
|
179
|
+
payload,
|
|
180
|
+
requirements
|
|
181
|
+
);
|
|
182
|
+
if (!verifyResult.isValid) {
|
|
183
|
+
res.status(401).json({
|
|
184
|
+
error: "Payment verification failed",
|
|
185
|
+
reason: verifyResult.invalidReason
|
|
186
|
+
});
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const settleResult = await localFacilitator.settle(
|
|
190
|
+
payload,
|
|
191
|
+
requirements
|
|
192
|
+
);
|
|
193
|
+
txHash = settleResult.transaction ?? null;
|
|
194
|
+
if (settleResult) {
|
|
195
|
+
res.setHeader(
|
|
196
|
+
"X-Payment-Response",
|
|
197
|
+
http.encodePaymentResponseHeader(
|
|
198
|
+
settleResult
|
|
199
|
+
)
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (idempotencyKey) {
|
|
204
|
+
const headers = {};
|
|
205
|
+
const paymentResponse = res.getHeader("X-Payment-Response");
|
|
206
|
+
if (typeof paymentResponse === "string") {
|
|
207
|
+
headers["X-Payment-Response"] = paymentResponse;
|
|
208
|
+
}
|
|
209
|
+
await seenTxStore.set(idempotencyKey, { txHash, headers });
|
|
210
|
+
}
|
|
211
|
+
if (txHash && opts.onSettled) {
|
|
212
|
+
Promise.resolve().then(() => opts.onSettled(txHash, opts.amount, "x402", payerAddress)).catch((err) => {
|
|
213
|
+
console.error("[x402] onSettled callback error:", err);
|
|
214
|
+
opts.onCallbackError?.(err, "onSettled");
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
next();
|
|
218
|
+
} catch (err) {
|
|
219
|
+
console.error("[x402] Settlement error:", err);
|
|
220
|
+
res.status(500).json({ error: "Payment settlement failed" });
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
var MPP_NETWORK = {
|
|
225
|
+
testnet: "stellar:testnet",
|
|
226
|
+
mainnet: "stellar:pubnet"
|
|
227
|
+
};
|
|
228
|
+
function createMppChargeHandler(opts) {
|
|
229
|
+
const networkId = MPP_NETWORK[opts.network];
|
|
230
|
+
const amountHumanReadable = opts.amount;
|
|
231
|
+
const recipient = resolvePayee(opts.manifest, "mpp-charge");
|
|
232
|
+
const seenTxStore = opts.seenTxStore ?? new InMemorySeenTxStore();
|
|
233
|
+
const mppx = server$2.Mppx.create({
|
|
234
|
+
secretKey: opts.payeeSecretKey,
|
|
235
|
+
methods: [
|
|
236
|
+
server$3.stellar.charge({
|
|
237
|
+
recipient,
|
|
238
|
+
currency: opts.assetContract,
|
|
239
|
+
network: networkId,
|
|
240
|
+
feePayer: { envelopeSigner: opts.payeeSecretKey }
|
|
241
|
+
})
|
|
242
|
+
]
|
|
243
|
+
});
|
|
244
|
+
return async (req, res, next) => {
|
|
245
|
+
try {
|
|
246
|
+
let payerAddress = null;
|
|
247
|
+
try {
|
|
248
|
+
const authHeader = req.headers["authorization"];
|
|
249
|
+
if (typeof authHeader === "string" && authHeader.startsWith("Payment ")) {
|
|
250
|
+
const credPart = authHeader.replace(/^Payment\s+/, "").split(",").find((p) => p.trim().startsWith("credential="));
|
|
251
|
+
if (credPart) {
|
|
252
|
+
const b64 = credPart.split("=").slice(1).join("=").replace(/^"|"$/g, "");
|
|
253
|
+
const credJson = Buffer.from(b64, "base64").toString("utf8");
|
|
254
|
+
const cred = JSON.parse(credJson);
|
|
255
|
+
const key = cred.sender ?? cred.payload?.sender ?? cred.payload?.from;
|
|
256
|
+
payerAddress = extractPayerAddress(key);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
} catch {
|
|
260
|
+
}
|
|
261
|
+
const idempotencyKey = await paymentIdempotencyKey((name) => {
|
|
262
|
+
const v = req.headers[name.toLowerCase()];
|
|
263
|
+
return Array.isArray(v) ? v[0] : v;
|
|
264
|
+
});
|
|
265
|
+
if (idempotencyKey) {
|
|
266
|
+
const cached = await seenTxStore.get(idempotencyKey);
|
|
267
|
+
if (cached) {
|
|
268
|
+
if (cached.headers) {
|
|
269
|
+
for (const [k, val] of Object.entries(cached.headers)) {
|
|
270
|
+
res.setHeader(k, val);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
next();
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
const fetchReq = server$2.Request.fromNodeListener(req, res);
|
|
278
|
+
const handler = mppx["stellar/charge"];
|
|
279
|
+
const result = await handler({
|
|
280
|
+
amount: amountHumanReadable,
|
|
281
|
+
currency: opts.assetContract,
|
|
282
|
+
recipient,
|
|
283
|
+
description: opts.manifest.name
|
|
284
|
+
})(fetchReq);
|
|
285
|
+
if (result.status === 402) {
|
|
286
|
+
const challenge = result.challenge;
|
|
287
|
+
res.status(402);
|
|
288
|
+
challenge.headers.forEach((v, k) => res.setHeader(k, v));
|
|
289
|
+
res.send(await challenge.text());
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
const receipt = result.withReceipt(new Response(""));
|
|
293
|
+
const receiptHeaders = {};
|
|
294
|
+
receipt.headers.forEach((v, k) => {
|
|
295
|
+
res.setHeader(k, v);
|
|
296
|
+
receiptHeaders[k] = v;
|
|
297
|
+
});
|
|
298
|
+
const receiptHeader = receipt.headers.get("payment-receipt");
|
|
299
|
+
let reference;
|
|
300
|
+
if (receiptHeader) {
|
|
301
|
+
try {
|
|
302
|
+
const parsed = JSON.parse(
|
|
303
|
+
Buffer.from(receiptHeader, "base64").toString("utf8")
|
|
304
|
+
);
|
|
305
|
+
reference = parsed.reference;
|
|
306
|
+
} catch {
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
if (idempotencyKey) {
|
|
310
|
+
await seenTxStore.set(idempotencyKey, {
|
|
311
|
+
txHash: reference ?? null,
|
|
312
|
+
headers: receiptHeaders
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
if (reference && opts.onSettled) {
|
|
316
|
+
Promise.resolve().then(() => opts.onSettled(reference, opts.amount, "mpp-charge", payerAddress)).catch((err) => {
|
|
317
|
+
console.error("[mpp-charge] onSettled callback error:", err);
|
|
318
|
+
opts.onCallbackError?.(err, "onSettled");
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
next();
|
|
322
|
+
} catch (err) {
|
|
323
|
+
next(err);
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
function resolveVaultSettlementAddresses(payer, payee) {
|
|
328
|
+
if (!payer) return null;
|
|
329
|
+
return { payer, payee };
|
|
330
|
+
}
|
|
331
|
+
function buildSessionSettlementTransaction(source, vaultContractId, channelId, addresses, amount, voucherCount, networkPassphrase) {
|
|
332
|
+
const vault = new stellarSdk.Contract(vaultContractId);
|
|
333
|
+
const op = vault.call(
|
|
334
|
+
"record_session_settlement",
|
|
335
|
+
stellarSdk.nativeToScVal(channelId, { type: "address" }),
|
|
336
|
+
stellarSdk.nativeToScVal(addresses.payer, { type: "address" }),
|
|
337
|
+
stellarSdk.nativeToScVal(addresses.payee, { type: "address" }),
|
|
338
|
+
stellarSdk.nativeToScVal(amount, { type: "i128" }),
|
|
339
|
+
stellarSdk.nativeToScVal(voucherCount, { type: "u32" })
|
|
340
|
+
);
|
|
341
|
+
return new stellarSdk.TransactionBuilder(source, {
|
|
342
|
+
fee: stellarSdk.BASE_FEE,
|
|
343
|
+
networkPassphrase
|
|
344
|
+
}).addOperation(op).setTimeout(30).build();
|
|
345
|
+
}
|
|
346
|
+
function channelAuthorizer(envelopeSigner) {
|
|
347
|
+
return { envelopeSigner };
|
|
348
|
+
}
|
|
349
|
+
function formatMppError(error) {
|
|
350
|
+
if (error instanceof Error) return error.message;
|
|
351
|
+
if (typeof error === "string") return error;
|
|
352
|
+
try {
|
|
353
|
+
const serialized = JSON.stringify(error);
|
|
354
|
+
return serialized === void 0 ? String(error) : serialized;
|
|
355
|
+
} catch {
|
|
356
|
+
return String(error);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
function withTypedChannelErrors(method) {
|
|
360
|
+
return {
|
|
361
|
+
...method,
|
|
362
|
+
async verify(parameters) {
|
|
363
|
+
try {
|
|
364
|
+
return await method.verify(parameters);
|
|
365
|
+
} catch (error) {
|
|
366
|
+
throw mapChannelError(error);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
function onVerifiedCredential(method, commit) {
|
|
372
|
+
return {
|
|
373
|
+
...method,
|
|
374
|
+
async verify(parameters) {
|
|
375
|
+
const receipt = await method.verify(parameters);
|
|
376
|
+
await commit(parameters.credential);
|
|
377
|
+
return receipt;
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
function mapChannelError(error) {
|
|
382
|
+
const message = formatMppError(error);
|
|
383
|
+
const details = error && typeof error === "object" && "details" in error ? error.details : void 0;
|
|
384
|
+
const reason = details && Object.keys(details).length > 0 ? `${message} (${JSON.stringify(details)})` : message;
|
|
385
|
+
if (/signer mismatch|authori[sz]er|unauthori[sz]ed/i.test(message)) {
|
|
386
|
+
return new mppx.Errors.SignerMismatchError({ reason });
|
|
387
|
+
}
|
|
388
|
+
if (/already used|replay|challenge/i.test(message)) {
|
|
389
|
+
return new mppx.Errors.InvalidChallengeError({ reason });
|
|
390
|
+
}
|
|
391
|
+
if (/channel has been closed|channel is closed|finalized/i.test(message)) {
|
|
392
|
+
return new mppx.Errors.ChannelClosedError({ reason });
|
|
393
|
+
}
|
|
394
|
+
if (/exceeds channel balance|exceeds.*deposit/i.test(message)) {
|
|
395
|
+
return new mppx.Errors.AmountExceedsDepositError({ reason });
|
|
396
|
+
}
|
|
397
|
+
if (/channel not found|no channel/i.test(message)) {
|
|
398
|
+
return new mppx.Errors.ChannelNotFoundError({ reason });
|
|
399
|
+
}
|
|
400
|
+
if (/must be greater|does not cover|below.*minimum/i.test(message)) {
|
|
401
|
+
return new mppx.Errors.DeltaTooSmallError({ reason });
|
|
402
|
+
}
|
|
403
|
+
if (/signature/i.test(message)) {
|
|
404
|
+
return new mppx.Errors.InvalidSignatureError({ reason });
|
|
405
|
+
}
|
|
406
|
+
return new mppx.Errors.VerificationFailedError({ reason });
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// src/provider/MppSessionHandler.ts
|
|
410
|
+
var MPP_NETWORK2 = {
|
|
411
|
+
testnet: "stellar:testnet",
|
|
412
|
+
mainnet: "stellar:pubnet"
|
|
413
|
+
};
|
|
414
|
+
function createMppSessionHandler(opts) {
|
|
415
|
+
const networkId = MPP_NETWORK2[opts.network];
|
|
416
|
+
const rateHuman = opts.rate;
|
|
417
|
+
const payeeKeypair = stellarSdk.Keypair.fromSecret(opts.payeeSecretKey);
|
|
418
|
+
const voucherRecordKey = `routedock:session:voucher:${opts.channelFactory}`;
|
|
419
|
+
const innerStore = server$4.Store.memory();
|
|
420
|
+
let record = null;
|
|
421
|
+
let voucherCount = 0;
|
|
422
|
+
let sessionOpened = false;
|
|
423
|
+
let idleTimer = null;
|
|
424
|
+
let settledCleanly = false;
|
|
425
|
+
let closeListenerArmed = false;
|
|
426
|
+
function clearIdleTimer() {
|
|
427
|
+
if (idleTimer) {
|
|
428
|
+
clearTimeout(idleTimer);
|
|
429
|
+
idleTimer = null;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
function armIdleTimer() {
|
|
433
|
+
if (!opts.idleTimeoutMs) return;
|
|
434
|
+
clearIdleTimer();
|
|
435
|
+
idleTimer = setTimeout(() => {
|
|
436
|
+
void flagOrphan("idle-timeout");
|
|
437
|
+
}, opts.idleTimeoutMs);
|
|
438
|
+
if (typeof idleTimer.unref === "function") idleTimer.unref();
|
|
439
|
+
}
|
|
440
|
+
async function loadPersistedRecord() {
|
|
441
|
+
if (record) return record;
|
|
442
|
+
try {
|
|
443
|
+
const stored = await innerStore.get(voucherRecordKey);
|
|
444
|
+
if (!stored || typeof stored.amount !== "string" || typeof stored.signature !== "string") {
|
|
445
|
+
return null;
|
|
446
|
+
}
|
|
447
|
+
record = { amount: BigInt(stored.amount), signature: stored.signature, payer: stored.payer ?? null };
|
|
448
|
+
} catch {
|
|
449
|
+
return null;
|
|
450
|
+
}
|
|
451
|
+
return record;
|
|
452
|
+
}
|
|
453
|
+
async function flagOrphan(reason) {
|
|
454
|
+
await loadPersistedRecord();
|
|
455
|
+
if (!sessionOpened || settledCleanly) return;
|
|
456
|
+
sessionOpened = false;
|
|
457
|
+
closeListenerArmed = false;
|
|
458
|
+
clearIdleTimer();
|
|
459
|
+
const cumulativeAmount = record ? (Number(record.amount) / 1e7).toFixed(7) : "0.0000000";
|
|
460
|
+
if (opts.onOrphaned) {
|
|
461
|
+
try {
|
|
462
|
+
await opts.onOrphaned(opts.channelFactory, {
|
|
463
|
+
cumulativeAmount,
|
|
464
|
+
lastSignature: record?.signature ?? "",
|
|
465
|
+
voucherCount,
|
|
466
|
+
reason
|
|
467
|
+
});
|
|
468
|
+
} catch (err) {
|
|
469
|
+
console.error("[mpp-session] onOrphaned handler failed:", err);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
const wrappedStore = {
|
|
474
|
+
async get(key) {
|
|
475
|
+
return innerStore.get(key);
|
|
476
|
+
},
|
|
477
|
+
async put(key, value) {
|
|
478
|
+
return innerStore.put(key, value);
|
|
479
|
+
},
|
|
480
|
+
async delete(key) {
|
|
481
|
+
return innerStore.delete(key);
|
|
482
|
+
},
|
|
483
|
+
async update(key, fn) {
|
|
484
|
+
const storeWithUpdate = innerStore;
|
|
485
|
+
if (typeof storeWithUpdate.update === "function") {
|
|
486
|
+
return storeWithUpdate.update(key, fn);
|
|
487
|
+
}
|
|
488
|
+
throw new Error("Store does not support atomic update operations");
|
|
489
|
+
}
|
|
490
|
+
};
|
|
491
|
+
async function commit(credential) {
|
|
492
|
+
await loadPersistedRecord();
|
|
493
|
+
const payload = credential.payload;
|
|
494
|
+
if (typeof payload?.amount !== "string" || typeof payload.signature !== "string") return;
|
|
495
|
+
let amount;
|
|
496
|
+
try {
|
|
497
|
+
amount = BigInt(payload.amount);
|
|
498
|
+
} catch {
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
if (record && amount < record.amount) return;
|
|
502
|
+
const payer = record?.payer ?? extractPayerAddress(credential.source);
|
|
503
|
+
record = { amount, signature: payload.signature, payer };
|
|
504
|
+
await innerStore.put(voucherRecordKey, {
|
|
505
|
+
amount: record.amount.toString(),
|
|
506
|
+
signature: record.signature,
|
|
507
|
+
payer: record.payer
|
|
508
|
+
});
|
|
509
|
+
voucherCount++;
|
|
510
|
+
settledCleanly = false;
|
|
511
|
+
armIdleTimer();
|
|
512
|
+
if (!sessionOpened) {
|
|
513
|
+
sessionOpened = true;
|
|
514
|
+
if (opts.onSessionOpen) {
|
|
515
|
+
Promise.resolve().then(() => opts.onSessionOpen(opts.channelFactory, record.payer)).catch((err) => {
|
|
516
|
+
console.error("[mpp-session] onSessionOpen callback error:", err);
|
|
517
|
+
opts.onCallbackError?.(err, "onSessionOpen");
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
if (opts.onVoucher) {
|
|
522
|
+
const humanAmount = (Number(record.amount) / 1e7).toFixed(7);
|
|
523
|
+
Promise.resolve().then(() => opts.onVoucher(opts.channelFactory, voucherCount, humanAmount, record.signature)).catch((err) => {
|
|
524
|
+
console.error("[mpp-session] onVoucher callback error:", err);
|
|
525
|
+
opts.onCallbackError?.(err, "onVoucher");
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
const mppx = server$2.Mppx.create({
|
|
530
|
+
secretKey: opts.payeeSecretKey,
|
|
531
|
+
methods: [
|
|
532
|
+
withTypedChannelErrors(
|
|
533
|
+
onVerifiedCredential(
|
|
534
|
+
server$4.stellar.channel({
|
|
535
|
+
channel: opts.channelFactory,
|
|
536
|
+
commitmentKey: opts.commitmentPublicKey,
|
|
537
|
+
network: networkId,
|
|
538
|
+
store: wrappedStore,
|
|
539
|
+
sourceAccount: payeeKeypair.publicKey(),
|
|
540
|
+
feePayer: channelAuthorizer(payeeKeypair)
|
|
541
|
+
}),
|
|
542
|
+
commit
|
|
543
|
+
)
|
|
544
|
+
)
|
|
545
|
+
]
|
|
546
|
+
});
|
|
547
|
+
return async (req, res, next) => {
|
|
548
|
+
try {
|
|
549
|
+
if (req.method === "DELETE") {
|
|
550
|
+
await loadPersistedRecord();
|
|
551
|
+
const body = req.body;
|
|
552
|
+
const bodyAmount = body?.amount ? BigInt(body.amount) : 0n;
|
|
553
|
+
const recordAmount = record?.amount ?? 0n;
|
|
554
|
+
let closeAmount;
|
|
555
|
+
let closeSig;
|
|
556
|
+
if (bodyAmount > recordAmount) {
|
|
557
|
+
closeAmount = bodyAmount;
|
|
558
|
+
closeSig = body?.signature ?? record?.signature ?? "";
|
|
559
|
+
} else {
|
|
560
|
+
closeAmount = recordAmount;
|
|
561
|
+
closeSig = record?.signature ?? "";
|
|
562
|
+
}
|
|
563
|
+
if (closeAmount > 0n && closeSig) {
|
|
564
|
+
const closePayer = record?.payer ?? null;
|
|
565
|
+
const closeTxHash = await server$4.close({
|
|
566
|
+
channel: opts.channelFactory,
|
|
567
|
+
amount: closeAmount,
|
|
568
|
+
signature: Buffer.from(closeSig, "hex"),
|
|
569
|
+
feePayer: channelAuthorizer(payeeKeypair),
|
|
570
|
+
network: networkId
|
|
571
|
+
});
|
|
572
|
+
settledCleanly = true;
|
|
573
|
+
clearIdleTimer();
|
|
574
|
+
if (opts.onSettled) {
|
|
575
|
+
const totalPaid = (Number(closeAmount) / 1e7).toFixed(7);
|
|
576
|
+
Promise.resolve().then(() => opts.onSettled(closeTxHash, totalPaid, "mpp-session", closePayer)).catch((err) => {
|
|
577
|
+
console.error("[mpp-session] onSettled callback error:", err);
|
|
578
|
+
opts.onCallbackError?.(err, "onSettled");
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
const vaultContract = process.env.AGENT_VAULT_CONTRACT;
|
|
582
|
+
if (vaultContract) {
|
|
583
|
+
const settlementAddresses = resolveVaultSettlementAddresses(
|
|
584
|
+
closePayer,
|
|
585
|
+
payeeKeypair.publicKey()
|
|
586
|
+
);
|
|
587
|
+
if (!settlementAddresses) {
|
|
588
|
+
console.error("[mpp-session] skipped session_settled vault record: payer address unavailable");
|
|
589
|
+
} else {
|
|
590
|
+
try {
|
|
591
|
+
const { Networks } = await import('@stellar/stellar-sdk');
|
|
592
|
+
const { Server } = await import('@stellar/stellar-sdk/rpc');
|
|
593
|
+
const networkPassphrase = opts.network === "mainnet" ? Networks.PUBLIC : Networks.TESTNET;
|
|
594
|
+
const rpcUrl = opts.network === "mainnet" ? "https://mainnet.sorobanrpc.com" : "https://soroban-testnet.stellar.org";
|
|
595
|
+
const server = new Server(rpcUrl);
|
|
596
|
+
const payeePublicKey = payeeKeypair.publicKey();
|
|
597
|
+
const sourceAccount = await server.getAccount(payeePublicKey);
|
|
598
|
+
const tx = buildSessionSettlementTransaction(
|
|
599
|
+
sourceAccount,
|
|
600
|
+
vaultContract,
|
|
601
|
+
opts.channelFactory,
|
|
602
|
+
settlementAddresses,
|
|
603
|
+
closeAmount,
|
|
604
|
+
voucherCount,
|
|
605
|
+
networkPassphrase
|
|
606
|
+
);
|
|
607
|
+
const preparedTx = await server.prepareTransaction(tx);
|
|
608
|
+
preparedTx.sign(payeeKeypair);
|
|
609
|
+
await server.sendTransaction(preparedTx);
|
|
610
|
+
} catch (recordErr) {
|
|
611
|
+
console.error("[mpp-session] failed to record session_settled on vault:", recordErr);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
res.json({ closeTxHash });
|
|
616
|
+
} else {
|
|
617
|
+
res.json({ closeTxHash: null, message: "no vouchers received" });
|
|
618
|
+
}
|
|
619
|
+
sessionOpened = false;
|
|
620
|
+
voucherCount = 0;
|
|
621
|
+
record = null;
|
|
622
|
+
await innerStore.delete(voucherRecordKey);
|
|
623
|
+
closeListenerArmed = false;
|
|
624
|
+
clearIdleTimer();
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
const fetchReq = server$2.Request.fromNodeListener(req, res);
|
|
628
|
+
const result = await mppx.channel({
|
|
629
|
+
amount: rateHuman,
|
|
630
|
+
description: opts.manifest.name
|
|
631
|
+
})(fetchReq);
|
|
632
|
+
if (result.status === 402) {
|
|
633
|
+
const challenge = result.challenge;
|
|
634
|
+
res.status(402);
|
|
635
|
+
challenge.headers.forEach((v, k) => res.setHeader(k, v));
|
|
636
|
+
const body = await challenge.text();
|
|
637
|
+
res.send(body);
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
if (!closeListenerArmed) {
|
|
641
|
+
closeListenerArmed = true;
|
|
642
|
+
req.on("close", () => {
|
|
643
|
+
void flagOrphan("connection-closed");
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
next();
|
|
647
|
+
} catch (err) {
|
|
648
|
+
next(err);
|
|
649
|
+
}
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
var MANIFEST_SIGNATURE_VERSION = "2";
|
|
653
|
+
function canonicalize(value) {
|
|
654
|
+
if (Array.isArray(value)) {
|
|
655
|
+
return value.map(canonicalize);
|
|
656
|
+
}
|
|
657
|
+
if (value !== null && typeof value === "object") {
|
|
658
|
+
return Object.fromEntries(
|
|
659
|
+
Object.keys(value).sort().map((key) => [key, canonicalize(value[key])])
|
|
660
|
+
);
|
|
661
|
+
}
|
|
662
|
+
return value;
|
|
663
|
+
}
|
|
664
|
+
function manifestDigest(manifest) {
|
|
665
|
+
const { signature: _omit, ...rest } = manifest;
|
|
666
|
+
const canonical = JSON.stringify(canonicalize(rest));
|
|
667
|
+
return crypto$1.createHash("sha256").update(canonical, "utf8").digest();
|
|
668
|
+
}
|
|
669
|
+
function signManifest(manifest, payeeSecretKey) {
|
|
670
|
+
const keypair = stellarSdk.Keypair.fromSecret(payeeSecretKey);
|
|
671
|
+
const versionedManifest = {
|
|
672
|
+
...manifest,
|
|
673
|
+
signature_version: MANIFEST_SIGNATURE_VERSION
|
|
674
|
+
};
|
|
675
|
+
const digest = manifestDigest(versionedManifest);
|
|
676
|
+
const sig = keypair.sign(digest);
|
|
677
|
+
return { ...versionedManifest, signature: Buffer.from(sig).toString("base64") };
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
// src/provider/fastify.ts
|
|
681
|
+
function buildExpressShims(rawReq, rawRes, fastifyRequest, fastifyReply) {
|
|
682
|
+
const req = rawReq;
|
|
683
|
+
const urlStr = rawReq.url ?? "/";
|
|
684
|
+
const parsedUrl = new URL(urlStr, "http://placeholder");
|
|
685
|
+
const reqGet = (name) => {
|
|
686
|
+
const val = rawReq.headers[name.toLowerCase()];
|
|
687
|
+
return Array.isArray(val) ? val[0] : val;
|
|
688
|
+
};
|
|
689
|
+
if (!("get" in req && typeof req.get === "function")) {
|
|
690
|
+
Object.defineProperty(req, "get", { value: reqGet, configurable: true });
|
|
691
|
+
Object.defineProperty(req, "header", { value: reqGet, configurable: true });
|
|
692
|
+
}
|
|
693
|
+
if (!("protocol" in req)) {
|
|
694
|
+
Object.defineProperty(req, "protocol", {
|
|
695
|
+
get: () => fastifyRequest.protocol ?? "http",
|
|
696
|
+
configurable: true
|
|
697
|
+
});
|
|
698
|
+
}
|
|
699
|
+
if (!("originalUrl" in req)) {
|
|
700
|
+
Object.defineProperty(req, "originalUrl", { value: urlStr, configurable: true });
|
|
701
|
+
}
|
|
702
|
+
if (!("path" in req)) {
|
|
703
|
+
Object.defineProperty(req, "path", { value: parsedUrl.pathname, configurable: true });
|
|
704
|
+
}
|
|
705
|
+
if (!("query" in req)) {
|
|
706
|
+
const q = {};
|
|
707
|
+
parsedUrl.searchParams.forEach((v, k) => {
|
|
708
|
+
q[k] = v;
|
|
709
|
+
});
|
|
710
|
+
Object.defineProperty(req, "query", { value: q, configurable: true });
|
|
711
|
+
}
|
|
712
|
+
const res = rawRes;
|
|
713
|
+
const nativeSetHeader = rawRes.setHeader.bind(rawRes);
|
|
714
|
+
const nativeGetHeader = rawRes.getHeader.bind(rawRes);
|
|
715
|
+
const nativeEnd = rawRes.end.bind(rawRes);
|
|
716
|
+
const extraHeaders = {};
|
|
717
|
+
const resSend = (body) => {
|
|
718
|
+
if (!rawRes.headersSent) {
|
|
719
|
+
for (const [k, v] of Object.entries(extraHeaders)) {
|
|
720
|
+
nativeSetHeader(k, v);
|
|
721
|
+
}
|
|
722
|
+
if (typeof body === "string") {
|
|
723
|
+
nativeEnd(body);
|
|
724
|
+
} else if (body !== void 0 && body !== null) {
|
|
725
|
+
if (!nativeGetHeader("content-type")) {
|
|
726
|
+
nativeSetHeader("Content-Type", "application/json");
|
|
727
|
+
}
|
|
728
|
+
nativeEnd(JSON.stringify(body));
|
|
729
|
+
} else {
|
|
730
|
+
nativeEnd();
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
return res;
|
|
734
|
+
};
|
|
735
|
+
const resJson = (data) => {
|
|
736
|
+
if (!nativeGetHeader("content-type")) {
|
|
737
|
+
nativeSetHeader("Content-Type", "application/json");
|
|
738
|
+
}
|
|
739
|
+
return resSend(data);
|
|
740
|
+
};
|
|
741
|
+
const resStatus = (code) => {
|
|
742
|
+
rawRes.statusCode = code;
|
|
743
|
+
return res;
|
|
744
|
+
};
|
|
745
|
+
const resSet = (field, val) => {
|
|
746
|
+
if (typeof field === "object") {
|
|
747
|
+
for (const [k, v] of Object.entries(field)) nativeSetHeader(k, v);
|
|
748
|
+
} else if (val !== void 0) {
|
|
749
|
+
extraHeaders[field] = val;
|
|
750
|
+
nativeSetHeader(field, val);
|
|
751
|
+
}
|
|
752
|
+
return res;
|
|
753
|
+
};
|
|
754
|
+
const resSetHeader = (name, value) => {
|
|
755
|
+
nativeSetHeader(name, value);
|
|
756
|
+
return res;
|
|
757
|
+
};
|
|
758
|
+
if (!("status" in res && typeof res.status === "function")) {
|
|
759
|
+
Object.defineProperty(res, "status", { value: resStatus, configurable: true });
|
|
760
|
+
Object.defineProperty(res, "json", { value: resJson, configurable: true });
|
|
761
|
+
Object.defineProperty(res, "send", { value: resSend, configurable: true });
|
|
762
|
+
Object.defineProperty(res, "set", { value: resSet, configurable: true });
|
|
763
|
+
Object.defineProperty(res, "setHeader", { value: resSetHeader, configurable: true });
|
|
764
|
+
Object.defineProperty(res, "end", {
|
|
765
|
+
value: (data) => {
|
|
766
|
+
nativeEnd(data);
|
|
767
|
+
},
|
|
768
|
+
configurable: true
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
return { req, res };
|
|
772
|
+
}
|
|
773
|
+
function runExpressHandler(handler, fastifyRequest, fastifyReply) {
|
|
774
|
+
const rawRes = fastifyReply.raw;
|
|
775
|
+
const { req, res } = buildExpressShims(
|
|
776
|
+
fastifyRequest.raw,
|
|
777
|
+
rawRes,
|
|
778
|
+
fastifyRequest);
|
|
779
|
+
return new Promise((resolve, reject) => {
|
|
780
|
+
let settled = false;
|
|
781
|
+
const finish = (err) => {
|
|
782
|
+
if (settled) return;
|
|
783
|
+
settled = true;
|
|
784
|
+
if (err != null) return reject(err);
|
|
785
|
+
if (rawRes.writableEnded || rawRes.headersSent) fastifyReply.hijack();
|
|
786
|
+
resolve();
|
|
787
|
+
};
|
|
788
|
+
Promise.resolve(handler(req, res, (err) => finish(err))).then(() => finish(), finish);
|
|
789
|
+
});
|
|
790
|
+
}
|
|
791
|
+
var MPP_MODES = ["mpp-session", "mpp-charge"];
|
|
792
|
+
function routedockFastify(opts) {
|
|
793
|
+
const signedManifest = signManifest(opts.manifest, opts.payeeSecretKey);
|
|
794
|
+
const handlerMap = /* @__PURE__ */ new Map();
|
|
795
|
+
if (opts.modes.includes("x402")) {
|
|
796
|
+
const x402Price = opts.pricing.x402;
|
|
797
|
+
if (x402Price) {
|
|
798
|
+
handlerMap.set(
|
|
799
|
+
"x402",
|
|
800
|
+
createX402Handler({
|
|
801
|
+
payeeSecretKey: opts.payeeSecretKey,
|
|
802
|
+
network: opts.network,
|
|
803
|
+
amount: x402Price,
|
|
804
|
+
assetContract: opts.assetContract,
|
|
805
|
+
...opts.facilitatorApiKey ? { facilitatorApiKey: opts.facilitatorApiKey } : {},
|
|
806
|
+
manifest: signedManifest,
|
|
807
|
+
...opts.onSettled ? { onSettled: opts.onSettled } : {},
|
|
808
|
+
...opts.onCallbackError ? { onCallbackError: opts.onCallbackError } : {},
|
|
809
|
+
...opts.seenTxStore ? { seenTxStore: opts.seenTxStore } : {}
|
|
810
|
+
})
|
|
811
|
+
);
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
if (opts.modes.includes("mpp-charge")) {
|
|
815
|
+
const chargePrice = opts.pricing["mpp-charge"];
|
|
816
|
+
if (chargePrice) {
|
|
817
|
+
handlerMap.set(
|
|
818
|
+
"mpp-charge",
|
|
819
|
+
createMppChargeHandler({
|
|
820
|
+
payeeSecretKey: opts.payeeSecretKey,
|
|
821
|
+
network: opts.network,
|
|
822
|
+
amount: chargePrice,
|
|
823
|
+
assetContract: opts.assetContract,
|
|
824
|
+
manifest: signedManifest,
|
|
825
|
+
...opts.onSettled ? { onSettled: opts.onSettled } : {},
|
|
826
|
+
...opts.onCallbackError ? { onCallbackError: opts.onCallbackError } : {},
|
|
827
|
+
...opts.seenTxStore ? { seenTxStore: opts.seenTxStore } : {}
|
|
828
|
+
})
|
|
829
|
+
);
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
if (opts.modes.includes("mpp-session")) {
|
|
833
|
+
const sessionPricing = opts.pricing["mpp-session"];
|
|
834
|
+
if (sessionPricing) {
|
|
835
|
+
if (!opts.commitmentPublicKey) {
|
|
836
|
+
throw new Error("routedockFastify: mpp-session mode requires commitmentPublicKey");
|
|
837
|
+
}
|
|
838
|
+
handlerMap.set(
|
|
839
|
+
"mpp-session",
|
|
840
|
+
createMppSessionHandler({
|
|
841
|
+
payeeSecretKey: opts.payeeSecretKey,
|
|
842
|
+
network: opts.network,
|
|
843
|
+
channelFactory: sessionPricing.channelFactory,
|
|
844
|
+
rate: sessionPricing.rate,
|
|
845
|
+
assetContract: opts.assetContract,
|
|
846
|
+
manifest: signedManifest,
|
|
847
|
+
commitmentPublicKey: opts.commitmentPublicKey,
|
|
848
|
+
...opts.onSettled ? { onSettled: opts.onSettled } : {},
|
|
849
|
+
...opts.onSessionOpen ? { onSessionOpen: opts.onSessionOpen } : {},
|
|
850
|
+
...opts.onVoucher ? { onVoucher: opts.onVoucher } : {},
|
|
851
|
+
...opts.onCallbackError ? { onCallbackError: opts.onCallbackError } : {},
|
|
852
|
+
...opts.onOrphaned ? { onOrphaned: opts.onOrphaned } : {},
|
|
853
|
+
...opts.idleTimeoutMs != null ? { idleTimeoutMs: opts.idleTimeoutMs } : {}
|
|
854
|
+
})
|
|
855
|
+
);
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
const defaultMode = MPP_MODES.find((mode) => handlerMap.has(mode)) ?? (handlerMap.has("x402") ? "x402" : void 0);
|
|
859
|
+
const plugin = async (fastify) => {
|
|
860
|
+
fastify.addHook("onRequest", async (request, reply) => {
|
|
861
|
+
if (request.url === "/.well-known/routedock.json") {
|
|
862
|
+
reply.hijack();
|
|
863
|
+
const body = JSON.stringify(signedManifest);
|
|
864
|
+
reply.raw.setHeader("Content-Type", "application/json");
|
|
865
|
+
reply.raw.setHeader("Content-Length", Buffer.byteLength(body));
|
|
866
|
+
reply.raw.end(body);
|
|
867
|
+
return;
|
|
868
|
+
}
|
|
869
|
+
if (handlerMap.size === 0) return;
|
|
870
|
+
const prefersX402 = !!(request.headers["payment-signature"] || request.headers["x-payment"]) || request.headers["x-preferred-mode"] === "x402";
|
|
871
|
+
const selectedMode = prefersX402 ? handlerMap.has("x402") ? "x402" : defaultMode : defaultMode;
|
|
872
|
+
if (!selectedMode) return;
|
|
873
|
+
const handler = handlerMap.get(selectedMode);
|
|
874
|
+
if (!handler) return;
|
|
875
|
+
await runExpressHandler(handler, request, reply);
|
|
876
|
+
});
|
|
877
|
+
};
|
|
878
|
+
Object.defineProperty(plugin, /* @__PURE__ */ Symbol.for("skip-override"), { value: true });
|
|
879
|
+
return plugin;
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
exports.routedockFastify = routedockFastify;
|