@keelcodes/x402-gate 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +19 -3
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -59,10 +59,13 @@ function buildAccepts(opts, amount) {
|
|
|
59
59
|
const target = a.payTo ?? opts.payTo;
|
|
60
60
|
if (!target)
|
|
61
61
|
throw new Error('x402 gate: payTo is required (top-level or per accept)');
|
|
62
|
+
const priced = a.amount ?? amount;
|
|
63
|
+
if (!priced)
|
|
64
|
+
throw new Error('x402 gate: every accept needs an `amount` (or a top-level amount)');
|
|
62
65
|
const base = {
|
|
63
66
|
scheme: 'exact',
|
|
64
67
|
network: a.network,
|
|
65
|
-
amount:
|
|
68
|
+
amount: priced,
|
|
66
69
|
asset: a.asset,
|
|
67
70
|
payTo: target,
|
|
68
71
|
maxTimeoutSeconds: a.maxTimeoutSeconds ?? 300,
|
|
@@ -206,6 +209,15 @@ function hasPlatformCredential(req, extra) {
|
|
|
206
209
|
return typeof v === 'string' && v.trim().length > 0;
|
|
207
210
|
});
|
|
208
211
|
}
|
|
212
|
+
/**
|
|
213
|
+
* 本次调用的价格(最小单位)。
|
|
214
|
+
* 优先级:`amountFor(path)` > 顶层 `amount` > 第一个带价格的 accept。
|
|
215
|
+
* 只配 `accepts`(多币种)而不写顶层 `amount` 是文档里的标准用法,必须从 accept 取价,
|
|
216
|
+
* 否则 `amount` 为 undefined 会命中下面的「不收费」分支,等于整站免费。
|
|
217
|
+
*/
|
|
218
|
+
function resolveAmount(opts) {
|
|
219
|
+
return opts.amount ?? opts.accepts?.find((a) => a.amount)?.amount;
|
|
220
|
+
}
|
|
209
221
|
/**
|
|
210
222
|
* 网关核心:返回「放行」或「402 挑战」,与框架无关。
|
|
211
223
|
* 结算失败一律 402(携带原因),避免把上游错误变成 500。
|
|
@@ -216,9 +228,13 @@ async function authorizeX402(opts, req) {
|
|
|
216
228
|
return { action: 'pass' };
|
|
217
229
|
if (hasPlatformCredential(req, opts.passthroughHeaders ?? []))
|
|
218
230
|
return { action: 'pass' };
|
|
219
|
-
const amount = opts.amountFor ? opts.amountFor(req.path) : opts
|
|
220
|
-
|
|
231
|
+
const amount = opts.amountFor ? opts.amountFor(req.path) : resolveAmount(opts);
|
|
232
|
+
// `amountFor` 返回 null = 该路径明确免费;但「压根没配价格」必须报错,
|
|
233
|
+
// 不能静默放行(否则漏配一个 amount 就等于整站免费)。
|
|
234
|
+
if (amount === null)
|
|
221
235
|
return { action: 'pass' };
|
|
236
|
+
if (!amount)
|
|
237
|
+
throw new Error('x402 gate: no price configured (set `amount` or a priced accept)');
|
|
222
238
|
const signature = paymentSignature(req);
|
|
223
239
|
// 免费额度:只对「本来要收费、且没带付款凭证」的请求计数;已付款的正常走结算。
|
|
224
240
|
if (opts.freeQuota && !signature) {
|
package/package.json
CHANGED