@agent-score/commerce 2.0.1 → 2.1.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/README.md +26 -11
- package/dist/_core-kI7FRAiZ.d.mts +10 -0
- package/dist/_core-kI7FRAiZ.d.ts +10 -0
- package/dist/challenge/index.d.mts +3 -3
- package/dist/challenge/index.d.ts +3 -3
- package/dist/challenge/index.js +21 -14
- package/dist/challenge/index.js.map +1 -1
- package/dist/challenge/index.mjs +21 -14
- package/dist/challenge/index.mjs.map +1 -1
- package/dist/{checkout-B1JuEcbx.d.ts → checkout-BH-I_Ns8.d.ts} +19 -12
- package/dist/{checkout-BN5i1Fi7.d.mts → checkout-Bd_4aQ6c.d.mts} +19 -12
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/dist/core.mjs +1 -1
- package/dist/core.mjs.map +1 -1
- package/dist/default_rails-BWAquZeu.d.mts +188 -0
- package/dist/default_rails-BxBzcCA1.d.ts +188 -0
- package/dist/discovery/index.d.mts +5 -5
- package/dist/discovery/index.d.ts +5 -5
- package/dist/discovery/index.js +14 -1
- package/dist/discovery/index.js.map +1 -1
- package/dist/discovery/index.mjs +14 -1
- package/dist/discovery/index.mjs.map +1 -1
- package/dist/identity/express.d.mts +7 -3
- package/dist/identity/express.d.ts +7 -3
- package/dist/identity/express.js +39 -96
- package/dist/identity/express.js.map +1 -1
- package/dist/identity/express.mjs +37 -87
- package/dist/identity/express.mjs.map +1 -1
- package/dist/identity/fastify.d.mts +4 -4
- package/dist/identity/fastify.d.ts +4 -4
- package/dist/identity/fastify.js +60 -96
- package/dist/identity/fastify.js.map +1 -1
- package/dist/identity/fastify.mjs +58 -87
- package/dist/identity/fastify.mjs.map +1 -1
- package/dist/identity/hono.d.mts +11 -3
- package/dist/identity/hono.d.ts +11 -3
- package/dist/identity/hono.js +39 -93
- package/dist/identity/hono.js.map +1 -1
- package/dist/identity/hono.mjs +37 -84
- package/dist/identity/hono.mjs.map +1 -1
- package/dist/identity/nextjs.d.mts +10 -3
- package/dist/identity/nextjs.d.ts +10 -3
- package/dist/identity/nextjs.js +49 -93
- package/dist/identity/nextjs.js.map +1 -1
- package/dist/identity/nextjs.mjs +46 -84
- package/dist/identity/nextjs.mjs.map +1 -1
- package/dist/identity/policy.js +220 -129
- package/dist/identity/policy.js.map +1 -1
- package/dist/identity/policy.mjs +222 -131
- package/dist/identity/policy.mjs.map +1 -1
- package/dist/identity/web.d.mts +9 -3
- package/dist/identity/web.d.ts +9 -3
- package/dist/identity/web.js +45 -93
- package/dist/identity/web.js.map +1 -1
- package/dist/identity/web.mjs +42 -84
- package/dist/identity/web.mjs.map +1 -1
- package/dist/index.d.mts +554 -90
- package/dist/index.d.ts +554 -90
- package/dist/index.js +951 -152
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +939 -152
- package/dist/index.mjs.map +1 -1
- package/dist/middleware/express.d.mts +10 -0
- package/dist/middleware/express.d.ts +10 -0
- package/dist/middleware/express.js +128 -0
- package/dist/middleware/express.js.map +1 -0
- package/dist/middleware/express.mjs +91 -0
- package/dist/middleware/express.mjs.map +1 -0
- package/dist/middleware/fastify.d.mts +10 -0
- package/dist/middleware/fastify.d.ts +10 -0
- package/dist/middleware/fastify.js +127 -0
- package/dist/middleware/fastify.js.map +1 -0
- package/dist/middleware/fastify.mjs +90 -0
- package/dist/middleware/fastify.mjs.map +1 -0
- package/dist/middleware/hono.d.mts +10 -0
- package/dist/middleware/hono.d.ts +10 -0
- package/dist/middleware/hono.js +122 -0
- package/dist/middleware/hono.js.map +1 -0
- package/dist/middleware/hono.mjs +85 -0
- package/dist/middleware/hono.mjs.map +1 -0
- package/dist/middleware/nextjs.d.mts +22 -0
- package/dist/middleware/nextjs.d.ts +22 -0
- package/dist/middleware/nextjs.js +143 -0
- package/dist/middleware/nextjs.js.map +1 -0
- package/dist/middleware/nextjs.mjs +105 -0
- package/dist/middleware/nextjs.mjs.map +1 -0
- package/dist/middleware/web.d.mts +25 -0
- package/dist/middleware/web.d.ts +25 -0
- package/dist/middleware/web.js +128 -0
- package/dist/middleware/web.js.map +1 -0
- package/dist/middleware/web.mjs +91 -0
- package/dist/middleware/web.mjs.map +1 -0
- package/dist/payment/index.d.mts +21 -6
- package/dist/payment/index.d.ts +21 -6
- package/dist/payment/index.js +136 -9
- package/dist/payment/index.js.map +1 -1
- package/dist/payment/index.mjs +127 -9
- package/dist/payment/index.mjs.map +1 -1
- package/dist/{pricing-CxzwyiO6.d.mts → pricing-4n5Ota0D.d.mts} +14 -4
- package/dist/{pricing-CQ9DIFaw.d.ts → pricing-DHfH3ogG.d.ts} +14 -4
- package/dist/{rail_spec-XP0wKgJV.d.mts → rail_spec-D6qzh3J0.d.mts} +1 -1
- package/dist/{rail_spec-XP0wKgJV.d.ts → rail_spec-D6qzh3J0.d.ts} +1 -1
- package/dist/stripe-multichain/index.d.mts +150 -47
- package/dist/stripe-multichain/index.d.ts +150 -47
- package/dist/stripe-multichain/index.js +19749 -42
- package/dist/stripe-multichain/index.js.map +1 -1
- package/dist/stripe-multichain/index.mjs +19758 -27
- package/dist/stripe-multichain/index.mjs.map +1 -1
- package/dist/{x402_server-hgQzWQwB.d.mts → x402_server-Ciz2mls2.d.mts} +1 -1
- package/dist/{x402_server-hgQzWQwB.d.ts → x402_server-Ciz2mls2.d.ts} +1 -1
- package/package.json +43 -5
- package/dist/_response-BFYN3b6i.d.mts +0 -142
- package/dist/_response-_iPD5AIj.d.ts +0 -142
- package/dist/solana-Cds87OTu.d.mts +0 -67
- package/dist/solana-Cds87OTu.d.ts +0 -67
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/middleware/web.ts
|
|
31
|
+
var web_exports = {};
|
|
32
|
+
__export(web_exports, {
|
|
33
|
+
createRateLimit: () => createRateLimit
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(web_exports);
|
|
36
|
+
|
|
37
|
+
// src/_redis.ts
|
|
38
|
+
async function tryCreateRedis(opts) {
|
|
39
|
+
const url = opts.url ?? process.env.REDIS_URL;
|
|
40
|
+
if (!url) return null;
|
|
41
|
+
try {
|
|
42
|
+
const mod = await import("ioredis");
|
|
43
|
+
const client = new mod.default(url, {
|
|
44
|
+
connectTimeout: opts.connectTimeout ?? 3e3,
|
|
45
|
+
maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,
|
|
46
|
+
tls: url.startsWith("rediss://") ? {} : void 0
|
|
47
|
+
});
|
|
48
|
+
client.on("error", (err) => console.error(`[${opts.label}] Redis error:`, err.message));
|
|
49
|
+
return client;
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function memoizedRedis(opts) {
|
|
55
|
+
let promise = null;
|
|
56
|
+
return () => {
|
|
57
|
+
if (!promise) promise = tryCreateRedis(opts);
|
|
58
|
+
return promise;
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// src/middleware/_core.ts
|
|
63
|
+
function createRateLimiter(opts = {}) {
|
|
64
|
+
const windowSeconds = opts.windowSeconds ?? 60;
|
|
65
|
+
const maxRequests = opts.maxRequests ?? 60;
|
|
66
|
+
const keyPrefix = opts.keyPrefix ?? "rl:";
|
|
67
|
+
const memMap = /* @__PURE__ */ new Map();
|
|
68
|
+
const getRedis = memoizedRedis({ url: opts.redisUrl, label: "rate-limit" });
|
|
69
|
+
const checkMem = (key) => {
|
|
70
|
+
const now = Date.now();
|
|
71
|
+
const entry = memMap.get(key);
|
|
72
|
+
if (!entry || entry.resetAt < now) {
|
|
73
|
+
memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1e3 });
|
|
74
|
+
return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };
|
|
75
|
+
}
|
|
76
|
+
entry.count++;
|
|
77
|
+
const remaining = Math.max(0, maxRequests - entry.count);
|
|
78
|
+
return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };
|
|
79
|
+
};
|
|
80
|
+
return {
|
|
81
|
+
async check(key) {
|
|
82
|
+
const r = await getRedis();
|
|
83
|
+
if (!r) return checkMem(key);
|
|
84
|
+
try {
|
|
85
|
+
const fullKey = `${keyPrefix}${key}`;
|
|
86
|
+
const count = await r.incr(fullKey);
|
|
87
|
+
if (count === 1) await r.expire(fullKey, windowSeconds);
|
|
88
|
+
const remaining = Math.max(0, maxRequests - count);
|
|
89
|
+
return { allowed: count <= maxRequests, remaining, limit: maxRequests };
|
|
90
|
+
} catch {
|
|
91
|
+
return checkMem(key);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
var RATE_LIMIT_JSON_BODY = {
|
|
97
|
+
error: { code: "rate_limited", message: "Too many requests" }
|
|
98
|
+
};
|
|
99
|
+
function defaultKeyFromForwardedFor(forwardedFor) {
|
|
100
|
+
if (!forwardedFor) return "unknown";
|
|
101
|
+
return forwardedFor.split(",")[0]?.trim() || "unknown";
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// src/middleware/web.ts
|
|
105
|
+
function createRateLimit(opts = {}) {
|
|
106
|
+
const limiter = createRateLimiter(opts);
|
|
107
|
+
const keyResolver = opts.keyResolver ?? ((req) => defaultKeyFromForwardedFor(req.headers.get("x-forwarded-for")));
|
|
108
|
+
return async (req) => {
|
|
109
|
+
const { allowed, remaining, limit } = await limiter.check(keyResolver(req));
|
|
110
|
+
const baseHeaders = {
|
|
111
|
+
"X-RateLimit-Limit": String(limit),
|
|
112
|
+
"X-RateLimit-Remaining": String(remaining)
|
|
113
|
+
};
|
|
114
|
+
if (!allowed) {
|
|
115
|
+
const response = new Response(JSON.stringify(RATE_LIMIT_JSON_BODY), {
|
|
116
|
+
status: 429,
|
|
117
|
+
headers: { ...baseHeaders, "Content-Type": "application/json", "Cache-Control": "no-store" }
|
|
118
|
+
});
|
|
119
|
+
return { allowed: false, remaining, limit, response };
|
|
120
|
+
}
|
|
121
|
+
return { allowed: true, remaining, limit };
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
125
|
+
0 && (module.exports = {
|
|
126
|
+
createRateLimit
|
|
127
|
+
});
|
|
128
|
+
//# sourceMappingURL=web.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/middleware/web.ts","../../src/_redis.ts","../../src/middleware/_core.ts"],"sourcesContent":["import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\n\nexport interface RateLimitWebOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `'unknown'`. */\n keyResolver?: (req: Request) => string;\n}\n\nexport type RateLimitGuardResult =\n | { allowed: true; remaining: number; limit: number; response?: undefined }\n | { allowed: false; remaining: number; limit: number; response: Response };\n\nexport type RateLimitGuard = (req: Request) => Promise<RateLimitGuardResult>;\n\n/**\n * Build a rate-limit guard for Web Fetch–style handlers. Call `guard(req)` at the top\n * of your route. When `allowed === false`, return `result.response` directly.\n */\nexport function createRateLimit(opts: RateLimitWebOptions = {}): RateLimitGuard {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ?? ((req: Request) => defaultKeyFromForwardedFor(req.headers.get('x-forwarded-for')));\n\n return async (req: Request) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n const baseHeaders = {\n 'X-RateLimit-Limit': String(limit),\n 'X-RateLimit-Remaining': String(remaining),\n };\n if (!allowed) {\n const response = new Response(JSON.stringify(RATE_LIMIT_JSON_BODY), {\n status: 429,\n headers: { ...baseHeaders, 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },\n });\n return { allowed: false, remaining, limit, response };\n }\n return { allowed: true, remaining, limit };\n };\n}\n","/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\nexport interface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n"],"mappings":"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","names":[]}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// src/_redis.ts
|
|
2
|
+
async function tryCreateRedis(opts) {
|
|
3
|
+
const url = opts.url ?? process.env.REDIS_URL;
|
|
4
|
+
if (!url) return null;
|
|
5
|
+
try {
|
|
6
|
+
const mod = await import("ioredis");
|
|
7
|
+
const client = new mod.default(url, {
|
|
8
|
+
connectTimeout: opts.connectTimeout ?? 3e3,
|
|
9
|
+
maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,
|
|
10
|
+
tls: url.startsWith("rediss://") ? {} : void 0
|
|
11
|
+
});
|
|
12
|
+
client.on("error", (err) => console.error(`[${opts.label}] Redis error:`, err.message));
|
|
13
|
+
return client;
|
|
14
|
+
} catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function memoizedRedis(opts) {
|
|
19
|
+
let promise = null;
|
|
20
|
+
return () => {
|
|
21
|
+
if (!promise) promise = tryCreateRedis(opts);
|
|
22
|
+
return promise;
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// src/middleware/_core.ts
|
|
27
|
+
function createRateLimiter(opts = {}) {
|
|
28
|
+
const windowSeconds = opts.windowSeconds ?? 60;
|
|
29
|
+
const maxRequests = opts.maxRequests ?? 60;
|
|
30
|
+
const keyPrefix = opts.keyPrefix ?? "rl:";
|
|
31
|
+
const memMap = /* @__PURE__ */ new Map();
|
|
32
|
+
const getRedis = memoizedRedis({ url: opts.redisUrl, label: "rate-limit" });
|
|
33
|
+
const checkMem = (key) => {
|
|
34
|
+
const now = Date.now();
|
|
35
|
+
const entry = memMap.get(key);
|
|
36
|
+
if (!entry || entry.resetAt < now) {
|
|
37
|
+
memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1e3 });
|
|
38
|
+
return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };
|
|
39
|
+
}
|
|
40
|
+
entry.count++;
|
|
41
|
+
const remaining = Math.max(0, maxRequests - entry.count);
|
|
42
|
+
return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };
|
|
43
|
+
};
|
|
44
|
+
return {
|
|
45
|
+
async check(key) {
|
|
46
|
+
const r = await getRedis();
|
|
47
|
+
if (!r) return checkMem(key);
|
|
48
|
+
try {
|
|
49
|
+
const fullKey = `${keyPrefix}${key}`;
|
|
50
|
+
const count = await r.incr(fullKey);
|
|
51
|
+
if (count === 1) await r.expire(fullKey, windowSeconds);
|
|
52
|
+
const remaining = Math.max(0, maxRequests - count);
|
|
53
|
+
return { allowed: count <= maxRequests, remaining, limit: maxRequests };
|
|
54
|
+
} catch {
|
|
55
|
+
return checkMem(key);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
var RATE_LIMIT_JSON_BODY = {
|
|
61
|
+
error: { code: "rate_limited", message: "Too many requests" }
|
|
62
|
+
};
|
|
63
|
+
function defaultKeyFromForwardedFor(forwardedFor) {
|
|
64
|
+
if (!forwardedFor) return "unknown";
|
|
65
|
+
return forwardedFor.split(",")[0]?.trim() || "unknown";
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// src/middleware/web.ts
|
|
69
|
+
function createRateLimit(opts = {}) {
|
|
70
|
+
const limiter = createRateLimiter(opts);
|
|
71
|
+
const keyResolver = opts.keyResolver ?? ((req) => defaultKeyFromForwardedFor(req.headers.get("x-forwarded-for")));
|
|
72
|
+
return async (req) => {
|
|
73
|
+
const { allowed, remaining, limit } = await limiter.check(keyResolver(req));
|
|
74
|
+
const baseHeaders = {
|
|
75
|
+
"X-RateLimit-Limit": String(limit),
|
|
76
|
+
"X-RateLimit-Remaining": String(remaining)
|
|
77
|
+
};
|
|
78
|
+
if (!allowed) {
|
|
79
|
+
const response = new Response(JSON.stringify(RATE_LIMIT_JSON_BODY), {
|
|
80
|
+
status: 429,
|
|
81
|
+
headers: { ...baseHeaders, "Content-Type": "application/json", "Cache-Control": "no-store" }
|
|
82
|
+
});
|
|
83
|
+
return { allowed: false, remaining, limit, response };
|
|
84
|
+
}
|
|
85
|
+
return { allowed: true, remaining, limit };
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
export {
|
|
89
|
+
createRateLimit
|
|
90
|
+
};
|
|
91
|
+
//# sourceMappingURL=web.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/_redis.ts","../../src/middleware/_core.ts","../../src/middleware/web.ts"],"sourcesContent":["/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\nexport interface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n","import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\n\nexport interface RateLimitWebOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `'unknown'`. */\n keyResolver?: (req: Request) => string;\n}\n\nexport type RateLimitGuardResult =\n | { allowed: true; remaining: number; limit: number; response?: undefined }\n | { allowed: false; remaining: number; limit: number; response: Response };\n\nexport type RateLimitGuard = (req: Request) => Promise<RateLimitGuardResult>;\n\n/**\n * Build a rate-limit guard for Web Fetch–style handlers. Call `guard(req)` at the top\n * of your route. When `allowed === false`, return `result.response` directly.\n */\nexport function createRateLimit(opts: RateLimitWebOptions = {}): RateLimitGuard {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ?? ((req: Request) => defaultKeyFromForwardedFor(req.headers.get('x-forwarded-for')));\n\n return async (req: Request) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n const baseHeaders = {\n 'X-RateLimit-Limit': String(limit),\n 'X-RateLimit-Remaining': String(remaining),\n };\n if (!allowed) {\n const response = new Response(JSON.stringify(RATE_LIMIT_JSON_BODY), {\n status: 429,\n headers: { ...baseHeaders, 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },\n });\n return { allowed: false, remaining, limit, response };\n }\n return { allowed: true, remaining, limit };\n };\n}\n"],"mappings":"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","names":[]}
|
package/dist/payment/index.d.mts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { T as TempoRailSpec, S as SolanaMppRailSpec,
|
|
2
|
-
export { R as RAIL_SPEC_DEFAULTS,
|
|
3
|
-
import {
|
|
4
|
-
export { B as BuildX402AcceptsForOptions, C as CreateX402ServerOptions,
|
|
1
|
+
import { T as TempoRailSpec, S as SolanaMppRailSpec, c as TempoSessionRailSpec, b as StripeRailSpec, X as X402BaseRailSpec } from '../rail_spec-D6qzh3J0.mjs';
|
|
2
|
+
export { R as RAIL_SPEC_DEFAULTS, a as RecipientLike, r as resolveRecipient } from '../rail_spec-D6qzh3J0.mjs';
|
|
3
|
+
import { a as X402Server } from '../x402_server-Ciz2mls2.mjs';
|
|
4
|
+
export { B as BuildX402AcceptsForOptions, C as CreateX402ServerOptions, X as X402FacilitatorChoice, b as X402SymbolicRail, c as buildX402AcceptsFor402, d as createX402Server } from '../x402_server-Ciz2mls2.mjs';
|
|
5
5
|
export { a as aliasAmountFields, p as paymentRequiredHeader, w as wwwAuthenticateHeader } from '../wwwauthenticate-D_FMnPgU.mjs';
|
|
6
6
|
import { S as SignerNetwork } from '../signer-3FAit11j.mjs';
|
|
7
7
|
export { P as PaymentSigner, e as extractPaymentSigner, a as extractPaymentSignerFromAuth, b as extractSignerForPrecheck, r as readX402PaymentHeader } from '../signer-3FAit11j.mjs';
|
|
8
|
-
export { f as formatUsdCents, l as loadSolanaFeePayer, u as usdToAtomic } from '../
|
|
8
|
+
export { B as BuildDefaultCheckoutRailsOptions, a as BuildMppxComposeRailsOptions, H as HeadersLike, b as asHeaders, c as buildDefaultCheckoutRails, d as buildMppxComposeRails, f as formatUsdCents, h as hasMppxHeader, e as hasPaymentHeader, g as hasX402Header, l as loadSolanaFeePayer, r as readHeader, u as usdToAtomic } from '../default_rails-BWAquZeu.mjs';
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* Build the base64-encoded `request` blob for an MPP Payment directive (per the
|
|
@@ -879,4 +879,19 @@ declare function lazyMppxServer(opts: {
|
|
|
879
879
|
secretKey: string;
|
|
880
880
|
}): () => Promise<unknown>;
|
|
881
881
|
|
|
882
|
-
|
|
882
|
+
/** CAIP-2 prefix discriminators. Replaces the ad-hoc `startsWith('eip155:')` /
|
|
883
|
+
* `startsWith('solana:')` calls scattered across `checkout`, `checkout_compute_first`,
|
|
884
|
+
* `payment/lazy`, and `identity/ucp` so the prefix strings live in one place.
|
|
885
|
+
*
|
|
886
|
+
* Accepts the bare network spec `'eip155:8453'` or a rail-spec object with a
|
|
887
|
+
* `network` field. Pure functions; no peer-dep imports.
|
|
888
|
+
*/
|
|
889
|
+
type NetworkLike = string | object | null | undefined;
|
|
890
|
+
/** True when the network is a CAIP-2 EVM chain (`eip155:<chainId>`). */
|
|
891
|
+
declare function isEvmNetwork(input: NetworkLike): boolean;
|
|
892
|
+
/** True when the network is a CAIP-2 Solana chain (`solana:<genesis-hash>`).
|
|
893
|
+
* Note: `'solana'` bare (no `:`) is the mppx-internal label, NOT a CAIP-2
|
|
894
|
+
* network spec — this helper treats it as false. */
|
|
895
|
+
declare function isSolanaNetwork(input: NetworkLike): boolean;
|
|
896
|
+
|
|
897
|
+
export { type ClassifiedX402Error, type MppxComposeResult, type MppxRailSpec, type NetworkFamily, type PaymentHeadersRail, type PaymentHeadersResult, type ProcessX402SettleResult, type RailDefinition, type RailName, SETTLEMENT_OVERRIDES_HEADER, type SettlementHandlers, type SettlementOverrides, type SettlementPayloadLike, SignerNetwork, SolanaMppRailSpec, StripeRailSpec, TempoRailSpec, TempoSessionRailSpec, USDC, type VerifyX402RequestResult, X402BaseRailSpec, X402Server, type X402ServerLike, X402_SUPPORTED_BASE_NETWORKS, type ZeroSettleRail, type ZeroSettleResult, buildIdempotencyKey, buildPaymentDirective, buildPaymentHeaders, buildPaymentRequestBlob, classifyOrchestrationError, classifyX402SettleResult, composeMppxRequest, createMppxServer, detectRailFromHeaders, dispatchSettlementByNetwork, isEvmNetwork, isSolanaNetwork, lazyMppxServer, lazyX402Server, lookupRail, mppxChallengeHeaders, networkFamily, networks, paymentDirective, processX402Settle, rails, registerX402SchemesV1V2, settlementOverrideHeader, validateX402NetworkConfig, verifyX402Request, wrapSolanaChargeWithFinalizedBlockhash, zeroAmountCarveOut };
|
package/dist/payment/index.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { T as TempoRailSpec, S as SolanaMppRailSpec,
|
|
2
|
-
export { R as RAIL_SPEC_DEFAULTS,
|
|
3
|
-
import {
|
|
4
|
-
export { B as BuildX402AcceptsForOptions, C as CreateX402ServerOptions,
|
|
1
|
+
import { T as TempoRailSpec, S as SolanaMppRailSpec, c as TempoSessionRailSpec, b as StripeRailSpec, X as X402BaseRailSpec } from '../rail_spec-D6qzh3J0.js';
|
|
2
|
+
export { R as RAIL_SPEC_DEFAULTS, a as RecipientLike, r as resolveRecipient } from '../rail_spec-D6qzh3J0.js';
|
|
3
|
+
import { a as X402Server } from '../x402_server-Ciz2mls2.js';
|
|
4
|
+
export { B as BuildX402AcceptsForOptions, C as CreateX402ServerOptions, X as X402FacilitatorChoice, b as X402SymbolicRail, c as buildX402AcceptsFor402, d as createX402Server } from '../x402_server-Ciz2mls2.js';
|
|
5
5
|
export { a as aliasAmountFields, p as paymentRequiredHeader, w as wwwAuthenticateHeader } from '../wwwauthenticate-D_FMnPgU.js';
|
|
6
6
|
import { S as SignerNetwork } from '../signer-3FAit11j.js';
|
|
7
7
|
export { P as PaymentSigner, e as extractPaymentSigner, a as extractPaymentSignerFromAuth, b as extractSignerForPrecheck, r as readX402PaymentHeader } from '../signer-3FAit11j.js';
|
|
8
|
-
export { f as formatUsdCents, l as loadSolanaFeePayer, u as usdToAtomic } from '../
|
|
8
|
+
export { B as BuildDefaultCheckoutRailsOptions, a as BuildMppxComposeRailsOptions, H as HeadersLike, b as asHeaders, c as buildDefaultCheckoutRails, d as buildMppxComposeRails, f as formatUsdCents, h as hasMppxHeader, e as hasPaymentHeader, g as hasX402Header, l as loadSolanaFeePayer, r as readHeader, u as usdToAtomic } from '../default_rails-BxBzcCA1.js';
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* Build the base64-encoded `request` blob for an MPP Payment directive (per the
|
|
@@ -879,4 +879,19 @@ declare function lazyMppxServer(opts: {
|
|
|
879
879
|
secretKey: string;
|
|
880
880
|
}): () => Promise<unknown>;
|
|
881
881
|
|
|
882
|
-
|
|
882
|
+
/** CAIP-2 prefix discriminators. Replaces the ad-hoc `startsWith('eip155:')` /
|
|
883
|
+
* `startsWith('solana:')` calls scattered across `checkout`, `checkout_compute_first`,
|
|
884
|
+
* `payment/lazy`, and `identity/ucp` so the prefix strings live in one place.
|
|
885
|
+
*
|
|
886
|
+
* Accepts the bare network spec `'eip155:8453'` or a rail-spec object with a
|
|
887
|
+
* `network` field. Pure functions; no peer-dep imports.
|
|
888
|
+
*/
|
|
889
|
+
type NetworkLike = string | object | null | undefined;
|
|
890
|
+
/** True when the network is a CAIP-2 EVM chain (`eip155:<chainId>`). */
|
|
891
|
+
declare function isEvmNetwork(input: NetworkLike): boolean;
|
|
892
|
+
/** True when the network is a CAIP-2 Solana chain (`solana:<genesis-hash>`).
|
|
893
|
+
* Note: `'solana'` bare (no `:`) is the mppx-internal label, NOT a CAIP-2
|
|
894
|
+
* network spec — this helper treats it as false. */
|
|
895
|
+
declare function isSolanaNetwork(input: NetworkLike): boolean;
|
|
896
|
+
|
|
897
|
+
export { type ClassifiedX402Error, type MppxComposeResult, type MppxRailSpec, type NetworkFamily, type PaymentHeadersRail, type PaymentHeadersResult, type ProcessX402SettleResult, type RailDefinition, type RailName, SETTLEMENT_OVERRIDES_HEADER, type SettlementHandlers, type SettlementOverrides, type SettlementPayloadLike, SignerNetwork, SolanaMppRailSpec, StripeRailSpec, TempoRailSpec, TempoSessionRailSpec, USDC, type VerifyX402RequestResult, X402BaseRailSpec, X402Server, type X402ServerLike, X402_SUPPORTED_BASE_NETWORKS, type ZeroSettleRail, type ZeroSettleResult, buildIdempotencyKey, buildPaymentDirective, buildPaymentHeaders, buildPaymentRequestBlob, classifyOrchestrationError, classifyX402SettleResult, composeMppxRequest, createMppxServer, detectRailFromHeaders, dispatchSettlementByNetwork, isEvmNetwork, isSolanaNetwork, lazyMppxServer, lazyX402Server, lookupRail, mppxChallengeHeaders, networkFamily, networks, paymentDirective, processX402Settle, rails, registerX402SchemesV1V2, settlementOverrideHeader, validateX402NetworkConfig, verifyX402Request, wrapSolanaChargeWithFinalizedBlockhash, zeroAmountCarveOut };
|
package/dist/payment/index.js
CHANGED
|
@@ -25,7 +25,10 @@ __export(payment_exports, {
|
|
|
25
25
|
USDC: () => USDC,
|
|
26
26
|
X402_SUPPORTED_BASE_NETWORKS: () => X402_SUPPORTED_BASE_NETWORKS,
|
|
27
27
|
aliasAmountFields: () => aliasAmountFields,
|
|
28
|
+
asHeaders: () => asHeaders,
|
|
29
|
+
buildDefaultCheckoutRails: () => buildDefaultCheckoutRails,
|
|
28
30
|
buildIdempotencyKey: () => buildIdempotencyKey,
|
|
31
|
+
buildMppxComposeRails: () => buildMppxComposeRails,
|
|
29
32
|
buildPaymentDirective: () => buildPaymentDirective,
|
|
30
33
|
buildPaymentHeaders: () => buildPaymentHeaders,
|
|
31
34
|
buildPaymentRequestBlob: () => buildPaymentRequestBlob,
|
|
@@ -41,6 +44,11 @@ __export(payment_exports, {
|
|
|
41
44
|
extractPaymentSignerFromAuth: () => extractPaymentSignerFromAuth,
|
|
42
45
|
extractSignerForPrecheck: () => extractSignerForPrecheck,
|
|
43
46
|
formatUsdCents: () => formatUsdCents,
|
|
47
|
+
hasMppxHeader: () => hasMppxHeader,
|
|
48
|
+
hasPaymentHeader: () => hasPaymentHeader,
|
|
49
|
+
hasX402Header: () => hasX402Header,
|
|
50
|
+
isEvmNetwork: () => isEvmNetwork,
|
|
51
|
+
isSolanaNetwork: () => isSolanaNetwork,
|
|
44
52
|
lazyMppxServer: () => lazyMppxServer,
|
|
45
53
|
lazyX402Server: () => lazyX402Server,
|
|
46
54
|
loadSolanaFeePayer: () => loadSolanaFeePayer,
|
|
@@ -52,6 +60,7 @@ __export(payment_exports, {
|
|
|
52
60
|
paymentRequiredHeader: () => paymentRequiredHeader,
|
|
53
61
|
processX402Settle: () => processX402Settle,
|
|
54
62
|
rails: () => rails,
|
|
63
|
+
readHeader: () => readHeader,
|
|
55
64
|
readX402PaymentHeader: () => readX402PaymentHeader,
|
|
56
65
|
registerX402SchemesV1V2: () => registerX402SchemesV1V2,
|
|
57
66
|
resolveRecipient: () => resolveRecipient,
|
|
@@ -666,7 +675,8 @@ function isSolanaMppRailSpec(s) {
|
|
|
666
675
|
return s.network?.startsWith("solana:") ?? false;
|
|
667
676
|
}
|
|
668
677
|
function solanaNetworkFromCAIP2(caip2) {
|
|
669
|
-
if (caip2 === networks.solana.devnet.caip2) return "devnet";
|
|
678
|
+
if (caip2 === "devnet" || caip2 === networks.solana.devnet.caip2) return "devnet";
|
|
679
|
+
if (caip2 === "localnet") return "localnet";
|
|
670
680
|
return "mainnet-beta";
|
|
671
681
|
}
|
|
672
682
|
function solanaDefaultRpcUrl(network) {
|
|
@@ -953,6 +963,13 @@ function clampKey(key) {
|
|
|
953
963
|
return key;
|
|
954
964
|
}
|
|
955
965
|
|
|
966
|
+
// src/_headers.ts
|
|
967
|
+
function normalizeHeadersToLowercase(headers) {
|
|
968
|
+
const out = {};
|
|
969
|
+
for (const [k, v] of Object.entries(headers)) out[k.toLowerCase()] = v;
|
|
970
|
+
return out;
|
|
971
|
+
}
|
|
972
|
+
|
|
956
973
|
// src/signer.ts
|
|
957
974
|
var TOKEN_PROGRAM = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
|
|
958
975
|
var TOKEN_2022_PROGRAM = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb";
|
|
@@ -1035,13 +1052,8 @@ async function extractPaymentSignerFromAuth(authHeader, x402PaymentHeader) {
|
|
|
1035
1052
|
function readX402PaymentHeader(request) {
|
|
1036
1053
|
return request.headers.get("payment-signature") ?? request.headers.get("x-payment") ?? void 0;
|
|
1037
1054
|
}
|
|
1038
|
-
function lowerHeaders(headers) {
|
|
1039
|
-
const out = {};
|
|
1040
|
-
for (const [k, v] of Object.entries(headers)) out[k.toLowerCase()] = v;
|
|
1041
|
-
return out;
|
|
1042
|
-
}
|
|
1043
1055
|
async function extractSignerForPrecheck(headers) {
|
|
1044
|
-
const lower =
|
|
1056
|
+
const lower = normalizeHeadersToLowercase(headers);
|
|
1045
1057
|
const x402 = lower["payment-signature"] ?? lower["x-payment"];
|
|
1046
1058
|
if (x402) {
|
|
1047
1059
|
const signer = await extractPaymentSignerFromAuth(void 0, x402);
|
|
@@ -1098,8 +1110,8 @@ function usdToAtomic(usd, opts) {
|
|
|
1098
1110
|
}
|
|
1099
1111
|
return result;
|
|
1100
1112
|
}
|
|
1101
|
-
function formatUsdCents(cents) {
|
|
1102
|
-
return (cents / 100).toFixed(
|
|
1113
|
+
function formatUsdCents(cents, decimals = 2) {
|
|
1114
|
+
return (cents / 100).toFixed(decimals);
|
|
1103
1115
|
}
|
|
1104
1116
|
|
|
1105
1117
|
// src/payment/zero-settle.ts
|
|
@@ -1235,6 +1247,112 @@ async function loadSolanaFeePayer(opts) {
|
|
|
1235
1247
|
}
|
|
1236
1248
|
return kit.createKeyPairSignerFromPrivateKeyBytes(bytes);
|
|
1237
1249
|
}
|
|
1250
|
+
|
|
1251
|
+
// src/payment/compose_rails.ts
|
|
1252
|
+
function buildMppxComposeRails(opts) {
|
|
1253
|
+
const rails2 = [];
|
|
1254
|
+
if (opts.tempoRecipient) {
|
|
1255
|
+
rails2.push(["tempo/charge", {
|
|
1256
|
+
amount: opts.amountUsd,
|
|
1257
|
+
currency: opts.tempoTokenAddress ?? USDC.tempo.mainnet.address,
|
|
1258
|
+
decimals: 6,
|
|
1259
|
+
recipient: opts.tempoRecipient
|
|
1260
|
+
}]);
|
|
1261
|
+
}
|
|
1262
|
+
if (opts.solanaRecipient) {
|
|
1263
|
+
const atomic = usdToAtomic(opts.amountUsd, { decimals: 6 });
|
|
1264
|
+
rails2.push(["solana/charge", {
|
|
1265
|
+
amount: atomic.toString(),
|
|
1266
|
+
currency: opts.solanaTokenMint ?? USDC.solana.mainnet.mint,
|
|
1267
|
+
decimals: 6,
|
|
1268
|
+
recipient: opts.solanaRecipient,
|
|
1269
|
+
network: opts.solanaNetwork ?? "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"
|
|
1270
|
+
}]);
|
|
1271
|
+
}
|
|
1272
|
+
if (opts.includeStripe !== false) {
|
|
1273
|
+
rails2.push(["stripe/charge", { amount: opts.amountUsd, currency: "usd", decimals: 2 }]);
|
|
1274
|
+
}
|
|
1275
|
+
return rails2;
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
// src/payment/default_rails.ts
|
|
1279
|
+
function buildDefaultCheckoutRails(opts) {
|
|
1280
|
+
const out = {};
|
|
1281
|
+
if (opts.tempo) {
|
|
1282
|
+
out.tempo = { recipient: "", ...RAIL_SPEC_DEFAULTS.tempo, ...opts.tempo };
|
|
1283
|
+
}
|
|
1284
|
+
if (opts.x402Base) {
|
|
1285
|
+
const merged = { recipient: "", ...RAIL_SPEC_DEFAULTS.x402Base, ...opts.x402Base };
|
|
1286
|
+
if (merged.network === networks.base.sepolia.caip2) {
|
|
1287
|
+
if (opts.x402Base.chainId === void 0) merged.chainId = networks.base.sepolia.chainId;
|
|
1288
|
+
if (opts.x402Base.token === void 0) merged.token = USDC.base.sepolia.address;
|
|
1289
|
+
} else if (merged.network === networks.base.mainnet.caip2) {
|
|
1290
|
+
if (opts.x402Base.chainId === void 0) merged.chainId = networks.base.mainnet.chainId;
|
|
1291
|
+
if (opts.x402Base.token === void 0) merged.token = USDC.base.mainnet.address;
|
|
1292
|
+
}
|
|
1293
|
+
out.x402_base = merged;
|
|
1294
|
+
}
|
|
1295
|
+
if (opts.solanaMpp) {
|
|
1296
|
+
const merged = { recipient: "", ...RAIL_SPEC_DEFAULTS.solanaMpp, ...opts.solanaMpp };
|
|
1297
|
+
const isDevnet = merged.network === "devnet" || merged.network === networks.solana.devnet.caip2;
|
|
1298
|
+
if (isDevnet && opts.solanaMpp.token === void 0) {
|
|
1299
|
+
merged.token = USDC.solana.devnet.mint;
|
|
1300
|
+
}
|
|
1301
|
+
out.solana_mpp = merged;
|
|
1302
|
+
}
|
|
1303
|
+
if (opts.stripe) {
|
|
1304
|
+
out.stripe = { ...RAIL_SPEC_DEFAULTS.stripe, ...opts.stripe };
|
|
1305
|
+
}
|
|
1306
|
+
return out;
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
// src/payment/payment_header.ts
|
|
1310
|
+
function toTitleCase(name) {
|
|
1311
|
+
return name.replace(/(^|-)([a-z])/g, (_m, sep, c) => sep + c.toUpperCase());
|
|
1312
|
+
}
|
|
1313
|
+
function readHeader(headers, name) {
|
|
1314
|
+
if (typeof headers.get === "function") {
|
|
1315
|
+
return headers.get(name);
|
|
1316
|
+
}
|
|
1317
|
+
const rec = headers;
|
|
1318
|
+
const v = rec[name] ?? rec[name.toLowerCase()] ?? rec[toTitleCase(name)];
|
|
1319
|
+
if (typeof v === "string") return v;
|
|
1320
|
+
if (Array.isArray(v) && typeof v[0] === "string") return v[0];
|
|
1321
|
+
return null;
|
|
1322
|
+
}
|
|
1323
|
+
function asHeaders(input) {
|
|
1324
|
+
return typeof input.headers === "object" && input instanceof Request ? input.headers : input;
|
|
1325
|
+
}
|
|
1326
|
+
function hasPaymentHeader(input) {
|
|
1327
|
+
const headers = asHeaders(input);
|
|
1328
|
+
return Boolean(
|
|
1329
|
+
readHeader(headers, "payment-signature") || readHeader(headers, "x-payment") || readHeader(headers, "authorization")?.startsWith("Payment ")
|
|
1330
|
+
);
|
|
1331
|
+
}
|
|
1332
|
+
function hasX402Header(input) {
|
|
1333
|
+
const headers = asHeaders(input);
|
|
1334
|
+
return Boolean(readHeader(headers, "payment-signature") || readHeader(headers, "x-payment"));
|
|
1335
|
+
}
|
|
1336
|
+
function hasMppxHeader(input) {
|
|
1337
|
+
const headers = asHeaders(input);
|
|
1338
|
+
return Boolean(readHeader(headers, "authorization")?.startsWith("Payment "));
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
// src/payment/network_kind.ts
|
|
1342
|
+
function readNetwork(input) {
|
|
1343
|
+
if (typeof input === "string") return input;
|
|
1344
|
+
if (input && typeof input === "object") {
|
|
1345
|
+
const network = input.network;
|
|
1346
|
+
return typeof network === "string" ? network : "";
|
|
1347
|
+
}
|
|
1348
|
+
return "";
|
|
1349
|
+
}
|
|
1350
|
+
function isEvmNetwork(input) {
|
|
1351
|
+
return readNetwork(input).startsWith("eip155:");
|
|
1352
|
+
}
|
|
1353
|
+
function isSolanaNetwork(input) {
|
|
1354
|
+
return readNetwork(input).startsWith("solana:");
|
|
1355
|
+
}
|
|
1238
1356
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1239
1357
|
0 && (module.exports = {
|
|
1240
1358
|
RAIL_SPEC_DEFAULTS,
|
|
@@ -1242,7 +1360,10 @@ async function loadSolanaFeePayer(opts) {
|
|
|
1242
1360
|
USDC,
|
|
1243
1361
|
X402_SUPPORTED_BASE_NETWORKS,
|
|
1244
1362
|
aliasAmountFields,
|
|
1363
|
+
asHeaders,
|
|
1364
|
+
buildDefaultCheckoutRails,
|
|
1245
1365
|
buildIdempotencyKey,
|
|
1366
|
+
buildMppxComposeRails,
|
|
1246
1367
|
buildPaymentDirective,
|
|
1247
1368
|
buildPaymentHeaders,
|
|
1248
1369
|
buildPaymentRequestBlob,
|
|
@@ -1258,6 +1379,11 @@ async function loadSolanaFeePayer(opts) {
|
|
|
1258
1379
|
extractPaymentSignerFromAuth,
|
|
1259
1380
|
extractSignerForPrecheck,
|
|
1260
1381
|
formatUsdCents,
|
|
1382
|
+
hasMppxHeader,
|
|
1383
|
+
hasPaymentHeader,
|
|
1384
|
+
hasX402Header,
|
|
1385
|
+
isEvmNetwork,
|
|
1386
|
+
isSolanaNetwork,
|
|
1261
1387
|
lazyMppxServer,
|
|
1262
1388
|
lazyX402Server,
|
|
1263
1389
|
loadSolanaFeePayer,
|
|
@@ -1269,6 +1395,7 @@ async function loadSolanaFeePayer(opts) {
|
|
|
1269
1395
|
paymentRequiredHeader,
|
|
1270
1396
|
processX402Settle,
|
|
1271
1397
|
rails,
|
|
1398
|
+
readHeader,
|
|
1272
1399
|
readX402PaymentHeader,
|
|
1273
1400
|
registerX402SchemesV1V2,
|
|
1274
1401
|
resolveRecipient,
|