@celo/buy-gateway 0.5.1 → 0.6.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 +132 -0
- package/dist/config.d.ts +62 -2
- package/dist/config.js +319 -33
- package/dist/config.js.map +1 -1
- package/dist/credentials.d.ts +30 -0
- package/dist/credentials.js +153 -0
- package/dist/credentials.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/rate-limit.d.ts +64 -0
- package/dist/rate-limit.js +129 -0
- package/dist/rate-limit.js.map +1 -0
- package/dist/server.d.ts +44 -38
- package/dist/server.js +500 -133
- package/dist/server.js.map +1 -1
- package/package.json +5 -10
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Boot-time checks on injected upstream credentials, shared by `buy gate` and
|
|
3
|
+
* any host that mounts a gateway in-process.
|
|
4
|
+
*
|
|
5
|
+
* Both exist because settlement happens BEFORE the upstream call. A missing or
|
|
6
|
+
* revoked credential does not fail a request — it charges the caller and then
|
|
7
|
+
* hands them the upstream's 401, and x402 has no refund primitive.
|
|
8
|
+
*/
|
|
9
|
+
import { isHeaderValue } from './config.js';
|
|
10
|
+
/** A provider that never settles must not hang the boot. */
|
|
11
|
+
function withDeadline(promise, ms) {
|
|
12
|
+
let timer;
|
|
13
|
+
return Promise.race([
|
|
14
|
+
promise,
|
|
15
|
+
new Promise((_, reject) => {
|
|
16
|
+
timer = setTimeout(() => reject(new Error(`timed out after ${ms}ms`)), ms);
|
|
17
|
+
}),
|
|
18
|
+
]).finally(() => clearTimeout(timer));
|
|
19
|
+
}
|
|
20
|
+
function proxyServices(config) {
|
|
21
|
+
return [config.routing, ...Object.values(config.services ?? {})].filter((svc) => svc?.mode === 'proxy');
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Resolve every `injectHeaders` env var across all proxy services, throwing on
|
|
25
|
+
* any that is unset. The map is keyed by ENV VAR NAME, not header name: two
|
|
26
|
+
* services may both inject `Authorization` from different variables, and a
|
|
27
|
+
* header-keyed map could hold only one value for both of them.
|
|
28
|
+
*/
|
|
29
|
+
export function resolveInjectedHeaders(config, env = process.env, providers = {}) {
|
|
30
|
+
const resolved = {};
|
|
31
|
+
const missing = [];
|
|
32
|
+
for (const svc of proxyServices(config)) {
|
|
33
|
+
for (const [header, envVar] of Object.entries(svc.injectHeaders)) {
|
|
34
|
+
const value = env[envVar];
|
|
35
|
+
if (value === undefined || value === '') {
|
|
36
|
+
// A provider is a source too — just not a static one, so it is not
|
|
37
|
+
// in the map; the gateway asks it per request.
|
|
38
|
+
if (!providers[envVar])
|
|
39
|
+
missing.push(`${header} <- $${envVar}`);
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
// A newline pasted after a key is an ordinary mistake, and `Headers.set`
|
|
43
|
+
// would throw on it per request — after settlement.
|
|
44
|
+
if (!isHeaderValue(value)) {
|
|
45
|
+
throw new Error(`${header} <- $${envVar} is not a valid header value (a newline or control character in the secret?)`);
|
|
46
|
+
}
|
|
47
|
+
resolved[envVar] = value;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (missing.length > 0) {
|
|
51
|
+
throw new Error(`injectHeaders references unset environment variables:\n ${missing.join('\n ')}`);
|
|
52
|
+
}
|
|
53
|
+
return resolved;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Prove each injected credential is ACCEPTED before serving, not merely present.
|
|
57
|
+
*
|
|
58
|
+
* Every proxy upstream is probed with a GET of its origin carrying ONLY the
|
|
59
|
+
* headers that service injects — one key per provider is the normal shape, and
|
|
60
|
+
* a Google key sent to Alchemy proves nothing either way. Only a definitive
|
|
61
|
+
* auth rejection is fatal. A 404 or 405 means the credential was accepted and
|
|
62
|
+
* the path simply is not a route — that is a pass. A network failure is NOT a
|
|
63
|
+
* pass and NOT a failure: it proves nothing about the credential, so it warns
|
|
64
|
+
* and continues rather than letting a blip block a deploy.
|
|
65
|
+
*/
|
|
66
|
+
export async function verifyUpstreamCredentials(config, resolvedHeaders, log, providers = {}) {
|
|
67
|
+
for (const svc of proxyServices(config)) {
|
|
68
|
+
const headers = new Headers();
|
|
69
|
+
const names = [];
|
|
70
|
+
for (const [header, envVar] of Object.entries(svc.injectHeaders)) {
|
|
71
|
+
let value = resolvedHeaders[envVar];
|
|
72
|
+
if (!value && providers[envVar]) {
|
|
73
|
+
// Minting at boot is the check that the provider works at all — the
|
|
74
|
+
// metadata server is reachable, ADC exists — before the first caller
|
|
75
|
+
// finds out after paying.
|
|
76
|
+
try {
|
|
77
|
+
value = await withDeadline(providers[envVar](), 10_000);
|
|
78
|
+
if (!value)
|
|
79
|
+
throw new Error('the provider returned no credential');
|
|
80
|
+
}
|
|
81
|
+
catch (err) {
|
|
82
|
+
throw new Error(`could not obtain ${header} <- $${envVar} from its provider: ${err instanceof Error ? err.message : String(err)}`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (!value)
|
|
86
|
+
continue;
|
|
87
|
+
headers.set(header, value);
|
|
88
|
+
names.push(header);
|
|
89
|
+
}
|
|
90
|
+
if (names.length === 0)
|
|
91
|
+
continue;
|
|
92
|
+
const origin = new URL(svc.upstream).origin;
|
|
93
|
+
const target = svc.probe ? new URL(svc.probe.path, origin) : new URL(origin);
|
|
94
|
+
// The parser already refuses a path that could do this; checked again here
|
|
95
|
+
// because this is the line that would send the credential elsewhere.
|
|
96
|
+
if (target.origin !== origin) {
|
|
97
|
+
throw new Error(`probe path "${svc.probe?.path}" resolves outside ${origin}: ${target.origin}`);
|
|
98
|
+
}
|
|
99
|
+
const shown = svc.probe ? target.toString() : origin;
|
|
100
|
+
let status;
|
|
101
|
+
let text = '';
|
|
102
|
+
try {
|
|
103
|
+
const res = await fetch(shown, {
|
|
104
|
+
method: svc.probe?.method ?? 'GET',
|
|
105
|
+
headers,
|
|
106
|
+
signal: AbortSignal.timeout(10_000),
|
|
107
|
+
});
|
|
108
|
+
status = res.status;
|
|
109
|
+
// A 400 needs its body to be classified (see below); a 401/403 carries
|
|
110
|
+
// the reason an operator needs ("API not enabled in project …"). Nothing
|
|
111
|
+
// else is read, and an unread body is simply discarded.
|
|
112
|
+
if (status === 400 || status === 401 || status === 403) {
|
|
113
|
+
try {
|
|
114
|
+
text = (await res.text()).slice(0, 4096);
|
|
115
|
+
}
|
|
116
|
+
catch (err) {
|
|
117
|
+
if (status !== 401 && status !== 403)
|
|
118
|
+
throw err;
|
|
119
|
+
log(`could not read HTTP ${status} diagnostics from ${shown} (${err instanceof Error ? err.message : String(err)}); retaining credential rejection`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
catch (err) {
|
|
124
|
+
log(`could not reach ${shown} to check the upstream credential (${err instanceof Error ? err.message : String(err)}); serving anyway`);
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
// Google authenticates only on real API paths — the origin is 404 for any
|
|
128
|
+
// key — and a bad key there is 400 INVALID_ARGUMENT, the same status as a
|
|
129
|
+
// malformed body. The message tells them apart, so the message is checked.
|
|
130
|
+
const keyRejected = status === 400 && /api key not valid/i.test(text);
|
|
131
|
+
if (status === 401 || status === 403 || keyRejected) {
|
|
132
|
+
const message = (() => {
|
|
133
|
+
try {
|
|
134
|
+
const m = JSON.parse(text).error?.message;
|
|
135
|
+
return typeof m === 'string' ? m : undefined;
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
return undefined;
|
|
139
|
+
}
|
|
140
|
+
})();
|
|
141
|
+
const detail = keyRejected
|
|
142
|
+
? `${status} (API key not valid)`
|
|
143
|
+
: message
|
|
144
|
+
? `${status}: ${message.slice(0, 300)}`
|
|
145
|
+
: String(status);
|
|
146
|
+
throw new Error(`the upstream rejected the injected credential (${shown} answered ${detail}).
|
|
147
|
+
${names.join(', ')} is set but not accepted — check the value and that the key is still active.
|
|
148
|
+
Refusing to start: settlement happens before the upstream call, so every request would be charged and then fail.`);
|
|
149
|
+
}
|
|
150
|
+
log(`upstream credential accepted by ${origin}`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
//# sourceMappingURL=credentials.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"credentials.js","sourceRoot":"","sources":["../src/credentials.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAA0C,aAAa,EAAE,MAAM,aAAa,CAAC;AAIpF,4DAA4D;AAC5D,SAAS,YAAY,CAAI,OAAmB,EAAE,EAAU;IACtD,IAAI,KAAqB,CAAC;IAC1B,OAAO,OAAO,CAAC,IAAI,CAAC;QAClB,OAAO;QACP,IAAI,OAAO,CAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE;YAC/B,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,mBAAmB,EAAE,IAAI,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QAC7E,CAAC,CAAC;KACH,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC;AACxC,CAAC;AAKD,SAAS,aAAa,CAAC,MAAqB;IAC1C,OAAO,CAAC,MAAM,CAAC,OAAO,EAAE,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC,CAAC,MAAM,CACrE,CAAC,GAAG,EAAuB,EAAE,CAAC,GAAG,EAAE,IAAI,KAAK,OAAO,CACpD,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CACpC,MAAqB,EACrB,MAA0C,OAAO,CAAC,GAAG,EACrD,YAA6B,EAAE;IAE/B,MAAM,QAAQ,GAA2B,EAAE,CAAC;IAC5C,MAAM,OAAO,GAAa,EAAE,CAAC;IAC7B,KAAK,MAAM,GAAG,IAAI,aAAa,CAAC,MAAM,CAAC,EAAE,CAAC;QACxC,KA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,CAAC,GAAG,CACjD,mBAAmB,CACpB,CAAC;YACF,SAAS;QACX,CAAC;QAED,0EAA0E;QAC1E,0EAA0E;QAC1E,2EAA2E;QAC3E,MAAM,WAAW,GAAG,MAAM,KAAK,GAAG,IAAI,oBAAoB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACtE,IAAI,MAAM,KAAK,GAAG,IAAI,MAAM,KAAK,GAAG,IAAI,WAAW,EAAE,CAAC;YACpD,MAAM,OAAO,GAAG,CAAC,GAAG,EAAE;gBACpB,IAAI,CAAC;oBACH,MAAM,CAAC,GAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAsC,CAAC,KAAK,EAAE,OAAO,CAAC;oBAChF,OAAO,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;gBAC/C,CAAC;gBAAC,MAAM,CAAC;oBACP,OAAO,SAAS,CAAC;gBACnB,CAAC;YACH,CAAC,CAAC,EAAE,CAAC;YACL,MAAM,MAAM,GAAG,WAAW;gBACxB,CAAC,CAAC,GAAG,MAAM,sBAAsB;gBACjC,CAAC,CAAC,OAAO;oBACP,CAAC,CAAC,GAAG,MAAM,KAAK,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE;oBACvC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACrB,MAAM,IAAI,KAAK,CACb,kDAAkD,KAAK,aAAa,MAAM;IAC9E,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC;mHAC+F,CAC5G,CAAC;QACJ,CAAC;QACD,GAAG,CAAC,mCAAmC,MAAM,EAAE,CAAC,CAAC;IACnD,CAAC;AACH,CAAC"}
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,kBAAkB,CAAC;AACjC,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,OAAO,EAAE,sBAAsB,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory token-bucket rate limiter supporting multiple scoping strategies:
|
|
3
|
+
* - `ip`: per client IP address.
|
|
4
|
+
* - `payer`: per verified paying wallet address.
|
|
5
|
+
* - `service`: one bucket for an upstream service across all clients.
|
|
6
|
+
*
|
|
7
|
+
* Enforces requests-per-minute and burst caps. Idle buckets are pruned on a
|
|
8
|
+
* background sweep and the map is bounded, because every key here is chosen
|
|
9
|
+
* by a caller — an IP, a wallet — and a map that only grows is a memory
|
|
10
|
+
* budget the caller controls.
|
|
11
|
+
*/
|
|
12
|
+
export type RateLimitScope = 'ip' | 'payer' | 'service';
|
|
13
|
+
export type RateLimitConfig = {
|
|
14
|
+
/** Target scope: 'ip' (default), 'payer' (verified wallet), or 'service' (upstream cap). */
|
|
15
|
+
scope?: RateLimitScope;
|
|
16
|
+
/** Maximum sustained requests allowed per minute. Minimum is 1. */
|
|
17
|
+
requestsPerMinute?: number;
|
|
18
|
+
/** Maximum burst capacity of tokens. Defaults to requestsPerMinute. */
|
|
19
|
+
burst?: number;
|
|
20
|
+
};
|
|
21
|
+
export type RateLimiterOptions = {
|
|
22
|
+
/** A bucket untouched for this long is dropped by the sweep. Default 10 min. */
|
|
23
|
+
idleMs?: number;
|
|
24
|
+
/** Hard ceiling on tracked keys; the least recently seen is evicted past it. */
|
|
25
|
+
maxBuckets?: number;
|
|
26
|
+
/** Sweep cadence. Default 60 s. */
|
|
27
|
+
sweepMs?: number;
|
|
28
|
+
};
|
|
29
|
+
export declare const DEFAULT_IDLE_MS = 600000;
|
|
30
|
+
export declare const DEFAULT_MAX_BUCKETS = 10000;
|
|
31
|
+
export declare class RateLimiter {
|
|
32
|
+
readonly scope: RateLimitScope;
|
|
33
|
+
private readonly capacity;
|
|
34
|
+
private readonly refillRatePerMs;
|
|
35
|
+
private readonly idleMs;
|
|
36
|
+
private readonly maxBuckets;
|
|
37
|
+
private readonly buckets;
|
|
38
|
+
private readonly cleanupInterval;
|
|
39
|
+
constructor(config?: RateLimitConfig, options?: RateLimiterOptions);
|
|
40
|
+
/** Number of keys currently tracked. Exposed so memory behaviour is testable. */
|
|
41
|
+
get size(): number;
|
|
42
|
+
/** Tokens the bucket would hold if refilled up to `now`. */
|
|
43
|
+
private refilledAt;
|
|
44
|
+
/**
|
|
45
|
+
* Drop buckets no caller has touched within `idleMs` — once they are full.
|
|
46
|
+
* Dropping hands the owner a fresh bucket, which is only harmless when the
|
|
47
|
+
* old one would be full by now anyway; with `burst` well above the
|
|
48
|
+
* per-minute rate, ten idle minutes are worth ten tokens, not a burst.
|
|
49
|
+
* Public and given an injectable clock so a test can prove pruning happens
|
|
50
|
+
* without waiting on the interval.
|
|
51
|
+
*/
|
|
52
|
+
sweep(now?: number): number;
|
|
53
|
+
/**
|
|
54
|
+
* Check if a request for the given key is allowed.
|
|
55
|
+
* Decrements a token if available and returns retry-after seconds if exhausted.
|
|
56
|
+
*/
|
|
57
|
+
consume(key: string, now?: number): {
|
|
58
|
+
allowed: boolean;
|
|
59
|
+
remaining: number;
|
|
60
|
+
retryAfterSeconds?: number;
|
|
61
|
+
};
|
|
62
|
+
private evictOne;
|
|
63
|
+
dispose(): void;
|
|
64
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory token-bucket rate limiter supporting multiple scoping strategies:
|
|
3
|
+
* - `ip`: per client IP address.
|
|
4
|
+
* - `payer`: per verified paying wallet address.
|
|
5
|
+
* - `service`: one bucket for an upstream service across all clients.
|
|
6
|
+
*
|
|
7
|
+
* Enforces requests-per-minute and burst caps. Idle buckets are pruned on a
|
|
8
|
+
* background sweep and the map is bounded, because every key here is chosen
|
|
9
|
+
* by a caller — an IP, a wallet — and a map that only grows is a memory
|
|
10
|
+
* budget the caller controls.
|
|
11
|
+
*/
|
|
12
|
+
export const DEFAULT_IDLE_MS = 600_000;
|
|
13
|
+
export const DEFAULT_MAX_BUCKETS = 10_000;
|
|
14
|
+
export class RateLimiter {
|
|
15
|
+
scope;
|
|
16
|
+
capacity;
|
|
17
|
+
refillRatePerMs;
|
|
18
|
+
idleMs;
|
|
19
|
+
maxBuckets;
|
|
20
|
+
buckets = new Map();
|
|
21
|
+
cleanupInterval;
|
|
22
|
+
constructor(config, options) {
|
|
23
|
+
this.scope = config?.scope ?? 'ip';
|
|
24
|
+
const rpm = Math.max(1, config?.requestsPerMinute ?? 60);
|
|
25
|
+
this.capacity = Math.max(1, config?.burst ?? rpm);
|
|
26
|
+
this.refillRatePerMs = rpm / 60_000;
|
|
27
|
+
this.idleMs = options?.idleMs ?? DEFAULT_IDLE_MS;
|
|
28
|
+
this.maxBuckets = Math.max(1, options?.maxBuckets ?? DEFAULT_MAX_BUCKETS);
|
|
29
|
+
this.cleanupInterval = setInterval(() => this.sweep(), options?.sweepMs ?? 60_000);
|
|
30
|
+
// Allow process to exit without waiting on interval.
|
|
31
|
+
if (this.cleanupInterval.unref) {
|
|
32
|
+
this.cleanupInterval.unref();
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/** Number of keys currently tracked. Exposed so memory behaviour is testable. */
|
|
36
|
+
get size() {
|
|
37
|
+
return this.buckets.size;
|
|
38
|
+
}
|
|
39
|
+
/** Tokens the bucket would hold if refilled up to `now`. */
|
|
40
|
+
refilledAt(bucket, now) {
|
|
41
|
+
return Math.min(this.capacity, bucket.tokens + Math.max(0, now - bucket.lastRefillMs) * this.refillRatePerMs);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Drop buckets no caller has touched within `idleMs` — once they are full.
|
|
45
|
+
* Dropping hands the owner a fresh bucket, which is only harmless when the
|
|
46
|
+
* old one would be full by now anyway; with `burst` well above the
|
|
47
|
+
* per-minute rate, ten idle minutes are worth ten tokens, not a burst.
|
|
48
|
+
* Public and given an injectable clock so a test can prove pruning happens
|
|
49
|
+
* without waiting on the interval.
|
|
50
|
+
*/
|
|
51
|
+
sweep(now = Date.now()) {
|
|
52
|
+
let dropped = 0;
|
|
53
|
+
for (const [key, bucket] of this.buckets) {
|
|
54
|
+
if (now - bucket.lastSeenMs > this.idleMs && this.refilledAt(bucket, now) >= this.capacity) {
|
|
55
|
+
this.buckets.delete(key);
|
|
56
|
+
dropped += 1;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return dropped;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Check if a request for the given key is allowed.
|
|
63
|
+
* Decrements a token if available and returns retry-after seconds if exhausted.
|
|
64
|
+
*/
|
|
65
|
+
consume(key, now = Date.now()) {
|
|
66
|
+
let bucket = this.buckets.get(key);
|
|
67
|
+
if (!bucket) {
|
|
68
|
+
// Map iteration is insertion order and a touched key is re-inserted
|
|
69
|
+
// below, so scanning from the front visits least-recently-seen first.
|
|
70
|
+
// Evict the first bucket that is FULL: it holds no state a fresh bucket
|
|
71
|
+
// would not, so nothing is lost. Otherwise the fullest bucket goes —
|
|
72
|
+
// the one that gains least from a reset — so a caller with enough
|
|
73
|
+
// distinct keys cannot flood the map to reset their own throttled
|
|
74
|
+
// limit. Bounded memory outranks that fairness only at the very end.
|
|
75
|
+
if (this.buckets.size >= this.maxBuckets)
|
|
76
|
+
this.evictOne(now);
|
|
77
|
+
bucket = { tokens: this.capacity, lastRefillMs: now, lastSeenMs: now };
|
|
78
|
+
}
|
|
79
|
+
else {
|
|
80
|
+
const elapsed = Math.max(0, now - bucket.lastRefillMs);
|
|
81
|
+
bucket.tokens = Math.min(this.capacity, bucket.tokens + elapsed * this.refillRatePerMs);
|
|
82
|
+
bucket.lastRefillMs = now;
|
|
83
|
+
bucket.lastSeenMs = now;
|
|
84
|
+
// Move to the end so eviction order stays least-recently-seen.
|
|
85
|
+
this.buckets.delete(key);
|
|
86
|
+
}
|
|
87
|
+
this.buckets.set(key, bucket);
|
|
88
|
+
if (bucket.tokens >= 1) {
|
|
89
|
+
bucket.tokens -= 1;
|
|
90
|
+
return {
|
|
91
|
+
allowed: true,
|
|
92
|
+
remaining: Math.floor(bucket.tokens),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
const missingTokens = 1 - bucket.tokens;
|
|
96
|
+
const retryAfterSeconds = Math.max(1, Math.ceil(missingTokens / (this.refillRatePerMs * 1000)));
|
|
97
|
+
return {
|
|
98
|
+
allowed: false,
|
|
99
|
+
remaining: 0,
|
|
100
|
+
retryAfterSeconds,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
evictOne(now) {
|
|
104
|
+
// Evicting hands the owner a fresh, full bucket, so the victim is the one
|
|
105
|
+
// that gains the least from it: a full bucket gains nothing and goes at
|
|
106
|
+
// once; otherwise the fullest goes (oldest among equals). A throttled
|
|
107
|
+
// bucket, the one a flooder wants reset, is therefore always the last.
|
|
108
|
+
let victim;
|
|
109
|
+
let victimTokens = -1;
|
|
110
|
+
for (const [key, bucket] of this.buckets) {
|
|
111
|
+
const tokens = this.refilledAt(bucket, now);
|
|
112
|
+
if (tokens >= this.capacity) {
|
|
113
|
+
this.buckets.delete(key);
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
if (tokens > victimTokens) {
|
|
117
|
+
victim = key;
|
|
118
|
+
victimTokens = tokens;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (victim !== undefined)
|
|
122
|
+
this.buckets.delete(victim);
|
|
123
|
+
}
|
|
124
|
+
dispose() {
|
|
125
|
+
clearInterval(this.cleanupInterval);
|
|
126
|
+
this.buckets.clear();
|
|
127
|
+
}
|
|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CAAC;IAEO,QAAQ,CAAC,GAAW;QAC1B,0EAA0E;QAC1E,wEAAwE;QACxE,sEAAsE;QACtE,uEAAuE;QACvE,IAAI,MAA0B,CAAC;QAC/B,IAAI,YAAY,GAAG,CAAC,CAAC,CAAC;QACtB,KAAK,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACzC,MAAM,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;YAC5C,IAAI,MAAM,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;gBAC5B,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBACzB,OAAO;YACT,CAAC;YACD,IAAI,MAAM,GAAG,YAAY,EAAE,CAAC;gBAC1B,MAAM,GAAG,GAAG,CAAC;gBACb,YAAY,GAAG,MAAM,CAAC;YACxB,CAAC;QACH,CAAC;QACD,IAAI,MAAM,KAAK,SAAS;YAAE,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACxD,CAAC;IAEM,OAAO;QACZ,aAAa,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;QACpC,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;IACvB,CAAC;CACF"}
|
package/dist/server.d.ts
CHANGED
|
@@ -1,68 +1,74 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The gateway: one HTTP server that turns a PaywallConfig into a working x402
|
|
3
|
-
* paywall.
|
|
4
|
-
*
|
|
5
|
-
* The request flow is the one the four `examples/*.mjs` demo servers all
|
|
6
|
-
* hand-wrote — match route → 402 challenge → verify → optional Self gate →
|
|
7
|
-
* settle → serve — plus the hardening those servers accumulated the hard way
|
|
8
|
-
* and which a generic replacement must not silently drop:
|
|
9
|
-
*
|
|
10
|
-
* - an `unhandledRejection` backstop, because a throw inside an async
|
|
11
|
-
* handler is an unhandled rejection and Node exits on those by default:
|
|
12
|
-
* one malformed request could take down the whole gateway;
|
|
13
|
-
* - a PER-REQUEST boundary too, since the process-level handler cannot see
|
|
14
|
-
* `res` and would otherwise trade a crash for a hung client and a leaked
|
|
15
|
-
* socket — slow exhaustion instead of a fast death;
|
|
16
|
-
* - request/header timeouts, so a trickled body cannot hold a handler slot
|
|
17
|
-
* for Node's 300s default;
|
|
18
|
-
* - a body cap, since an unbounded upload is free memory for an anonymous
|
|
19
|
-
* caller;
|
|
20
|
-
* - `releaseNonce` on every rejection BEFORE settlement, so a refused payer
|
|
21
|
-
* is not locked out of their own signed authorization for the claim's TTL
|
|
22
|
-
* and their corrected retry does not read as a replay.
|
|
3
|
+
* paywall with multi-service routing, scoped rate limiting, and request restrictions.
|
|
23
4
|
*/
|
|
24
5
|
import http from 'node:http';
|
|
25
6
|
import type { PaymentRequirements } from '@celo/buy-core';
|
|
26
7
|
import { type FacilitatorEvents } from '@celo/buy-facilitator';
|
|
27
8
|
import type { LocalAccount } from 'viem';
|
|
28
|
-
import { type EndpointConfig, type PaywallConfig } from './config.js';
|
|
9
|
+
import { type EndpointConfig, type PaywallConfig, type ServiceConfig } from './config.js';
|
|
29
10
|
import { type UsageStats } from './usage.js';
|
|
30
11
|
export type GatewayOptions = {
|
|
31
12
|
config: PaywallConfig;
|
|
32
13
|
/**
|
|
33
|
-
* Gas sponsor. Omit for MOCK MODE: payments are verified but never settled
|
|
34
|
-
* which is how the demo servers let someone try the flow with no funds. A
|
|
35
|
-
* mock-mode response carries `transaction: null`.
|
|
14
|
+
* Gas sponsor. Omit for MOCK MODE: payments are verified but never settled.
|
|
36
15
|
*/
|
|
37
16
|
sponsor?: LocalAccount;
|
|
38
17
|
/**
|
|
39
|
-
* Re-run the Self proof server-side and ignore
|
|
40
|
-
* attributes. Off by default to match `verifySelfAttestation`, but a
|
|
41
|
-
* deployment taking real money wants it on — without it the attestation
|
|
42
|
-
* header is unauthenticated JSON the caller writes.
|
|
18
|
+
* Re-run the Self proof server-side and ignore client's claimed attributes.
|
|
43
19
|
*/
|
|
44
20
|
reverify?: boolean;
|
|
45
21
|
events?: FacilitatorEvents;
|
|
46
|
-
/**
|
|
22
|
+
/**
|
|
23
|
+
* Credential values keyed by the ENV VAR NAME an `injectHeaders` entry
|
|
24
|
+
* points at, for callers that resolve them out of band (tests, embedders).
|
|
25
|
+
* Keyed by env var rather than header name because two services may both
|
|
26
|
+
* inject `Authorization` from different variables; a header-keyed map can
|
|
27
|
+
* only hold one of them and would hand it to both.
|
|
28
|
+
*/
|
|
47
29
|
resolvedHeaders?: Record<string, string>;
|
|
30
|
+
/**
|
|
31
|
+
* Credentials minted per request rather than read once, keyed like
|
|
32
|
+
* `resolvedHeaders` (by env var name). For an OAuth access token from a
|
|
33
|
+
* service account: it expires hourly, so a value fixed at boot would 401
|
|
34
|
+
* after an hour. A static value (env or `resolvedHeaders`) wins over a
|
|
35
|
+
* provider. Resolved BEFORE settlement, and a failure is a 503 that costs
|
|
36
|
+
* the caller nothing.
|
|
37
|
+
*/
|
|
38
|
+
headerProviders?: Record<string, () => Promise<string>>;
|
|
39
|
+
/** How long a provider may take before the request is refused. Default 10s. */
|
|
40
|
+
providerTimeoutMs?: number;
|
|
48
41
|
log?: (line: string) => void;
|
|
49
42
|
};
|
|
50
43
|
export type Gateway = {
|
|
51
44
|
server: http.Server;
|
|
45
|
+
/**
|
|
46
|
+
* The request handler behind `server`, for a host that owns the socket and
|
|
47
|
+
* mounts the gateway under a prefix (the GCE server does this for Google).
|
|
48
|
+
* Rejects on a thrown handler, and the caller decides what the client sees.
|
|
49
|
+
*/
|
|
50
|
+
handler: (req: http.IncomingMessage, res: http.ServerResponse) => Promise<void>;
|
|
52
51
|
usage: () => UsageStats;
|
|
53
52
|
};
|
|
53
|
+
export declare function codingsUndiciDecodes(): Promise<Set<string>>;
|
|
54
|
+
/**
|
|
55
|
+
* Where a proxied request goes, resolved BEFORE any payment is verified so a
|
|
56
|
+
* request that would escape the upstream is refused while it is still free.
|
|
57
|
+
*
|
|
58
|
+
* The prefix-stripped remainder is attacker-influenced. Handing it to
|
|
59
|
+
* `new URL()` as a reference — the natural thing — lets it re-parse the whole
|
|
60
|
+
* target: `http://evil.test/x` ignores the base entirely, `//evil.test/x` is
|
|
61
|
+
* protocol-relative and swaps the host, and a bare `/x` is root-relative and
|
|
62
|
+
* discards the upstream's own path. Each of those went out with the service's
|
|
63
|
+
* injected credentials attached. Assigning it to `pathname` percent-encodes
|
|
64
|
+
* rather than reparses, so a scheme or host inside it can only ever be path
|
|
65
|
+
* text; the origin and base-path checks after are tripwires that should now
|
|
66
|
+
* be unreachable, kept because "should" is not a security boundary.
|
|
67
|
+
*/
|
|
68
|
+
export declare function upstreamTarget(service: ServiceConfig, endpoint: EndpointConfig, pathname: string, search: string): URL | undefined;
|
|
54
69
|
/** One x402 offer per token the endpoint accepts, at the same price, in config order. */
|
|
55
70
|
export declare function offersFor(config: PaywallConfig, endpoint: EndpointConfig, resource: string): PaymentRequirements[];
|
|
56
71
|
/** Build the x402 requirements for one endpoint in one token (default: its price currency). */
|
|
57
72
|
export declare function requirementsFor(config: PaywallConfig, endpoint: EndpointConfig, resource: string, symbol?: string): PaymentRequirements;
|
|
58
|
-
/**
|
|
59
|
-
* Refuse a config whose currencies cannot actually settle, at BOOT.
|
|
60
|
-
*
|
|
61
|
-
* Without this the failure surfaces on the first real payment: the payer signs
|
|
62
|
-
* an authorization the token can never honour, and the operator learns their
|
|
63
|
-
* paywall is broken from a customer. `tokenBySymbol` returns undefined for a
|
|
64
|
-
* symbol that does not exist on the network (there is no USDT on sepolia), and
|
|
65
|
-
* a token without EIP-712 domain metadata does not implement EIP-3009.
|
|
66
|
-
*/
|
|
67
73
|
export declare function validateTokens(config: PaywallConfig): void;
|
|
68
74
|
export declare function createGateway(opts: GatewayOptions): Gateway;
|