@celo/buy-gateway 0.3.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 ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,108 @@
1
+ /**
2
+ * The paywall config: schema, parsing and validation.
3
+ *
4
+ * This file is the security boundary of the gateway. `endpoints` is an
5
+ * ALLOWLIST — a path that does not match an entry is never proxied, never
6
+ * priced, and never reaches the upstream. Getting the matching wrong exposes
7
+ * an upstream the operator believed was private, so the matcher below is
8
+ * deliberately dull: literal segments and a single trailing `*`, no regex, no
9
+ * backtracking, no user-supplied patterns compiled at runtime.
10
+ *
11
+ * Validation fails LOUDLY and completely. A merchant config is authored once
12
+ * and then serves money; a silently-ignored typo (`prise:` for `price:`) would
13
+ * mean an endpoint served free, so unknown keys are errors rather than being
14
+ * dropped.
15
+ */
16
+ export type EndpointScheme = 'exact' | 'upto';
17
+ export type EndpointConfig = {
18
+ /** Path pattern: literal, or literal prefix ending in `/*`. */
19
+ path: string;
20
+ /** Free endpoints are served without a 402. Mutually exclusive with a price. */
21
+ free: boolean;
22
+ scheme: EndpointScheme;
23
+ /**
24
+ * Price in ATOMIC units, as a decimal string.
25
+ *
26
+ * For `exact` this is what the payer pays. For `upto` it is the CEILING the
27
+ * payer authorizes — and, because EIP-3009 signs the value, also what is
28
+ * actually captured. See the note on `scheme` in the README: `upto` does not
29
+ * enable metered billing.
30
+ */
31
+ amount: string;
32
+ /** Token symbol, e.g. 'USDC'. */
33
+ currency: string;
34
+ /** Human-readable, surfaced in the 402 challenge. */
35
+ description: string;
36
+ /** Optional Self.xyz gate for this endpoint. */
37
+ self?: SelfGateConfig;
38
+ };
39
+ export type SelfGateConfig = {
40
+ scope: string;
41
+ minimumAge?: number;
42
+ ofac?: boolean;
43
+ excludedCountries?: string[];
44
+ /**
45
+ * The Self receiver this attestation must have been produced against.
46
+ *
47
+ * Worth pinning: Self hashes the endpoint into the scope, and the nullifier
48
+ * is unique per human per scope, so an unpinned endpoint lets one human mint
49
+ * unlimited distinct identities. Per-human controls are not sound without it.
50
+ */
51
+ endpoint?: string;
52
+ endpointType?: 'https' | 'staging_https' | 'celo' | 'staging_celo';
53
+ };
54
+ /**
55
+ * Headers that frame the connection rather than describe the request.
56
+ *
57
+ * `fetch` computes or forbids all of these, so a configured value is either
58
+ * ignored or produces an illegal message. `connection` is here for a second
59
+ * reason: it NAMES other headers as hop-by-hop, and the proxy honours that
60
+ * list — letting config set it would let config decide what gets dropped.
61
+ */
62
+ export declare const PROTECTED_HEADERS: ReadonlySet<string>;
63
+ export type RoutingConfig = {
64
+ mode: 'respond';
65
+ body: string;
66
+ contentType: string;
67
+ } | {
68
+ mode: 'proxy';
69
+ upstream: string;
70
+ /** Header name → env var holding its value. Resolved at boot, not per-request. */
71
+ injectHeaders: Record<string, string>;
72
+ };
73
+ export type PaywallConfig = {
74
+ name: string;
75
+ version: 1;
76
+ network: 'celo' | 'celo-sepolia';
77
+ /** Address that receives payment. */
78
+ payTo: string;
79
+ routing: RoutingConfig;
80
+ endpoints: EndpointConfig[];
81
+ };
82
+ /** A validation failure, with the config path that caused it. */
83
+ export declare class ConfigError extends Error {
84
+ constructor(message: string);
85
+ }
86
+ /**
87
+ * Parse `"0.01 USDC"` into atomic units plus a symbol.
88
+ *
89
+ * Decimal-string arithmetic rather than `Number`: `0.07 * 1e6` is
90
+ * 70000.00000000001 in IEEE-754, and a price is money. Padding the fraction
91
+ * digits keeps it exact.
92
+ */
93
+ export declare function parsePrice(raw: string, at: string): {
94
+ amount: string;
95
+ currency: string;
96
+ };
97
+ /** Parse and validate a paywall config from YAML source. */
98
+ export declare function parseConfig(source: string): PaywallConfig;
99
+ /**
100
+ * Find the endpoint governing `pathname`, or undefined when none does — which
101
+ * the server must treat as 404.
102
+ *
103
+ * Exact matches win over wildcards, and longer wildcard prefixes win over
104
+ * shorter ones, so `/a/b/*` beats `/a/*` regardless of config order. Order-
105
+ * independence matters: an operator adding a specific rule should not have to
106
+ * know it must go above a general one.
107
+ */
108
+ export declare function matchEndpoint(config: PaywallConfig, pathname: string): EndpointConfig | undefined;
package/dist/config.js ADDED
@@ -0,0 +1,333 @@
1
+ /**
2
+ * The paywall config: schema, parsing and validation.
3
+ *
4
+ * This file is the security boundary of the gateway. `endpoints` is an
5
+ * ALLOWLIST — a path that does not match an entry is never proxied, never
6
+ * priced, and never reaches the upstream. Getting the matching wrong exposes
7
+ * an upstream the operator believed was private, so the matcher below is
8
+ * deliberately dull: literal segments and a single trailing `*`, no regex, no
9
+ * backtracking, no user-supplied patterns compiled at runtime.
10
+ *
11
+ * Validation fails LOUDLY and completely. A merchant config is authored once
12
+ * and then serves money; a silently-ignored typo (`prise:` for `price:`) would
13
+ * mean an endpoint served free, so unknown keys are errors rather than being
14
+ * dropped.
15
+ */
16
+ import { parse as parseYaml } from 'yaml';
17
+ /** Atomic units per whole token. Both USDC and USDT use 6 decimals on Celo. */
18
+ const DECIMALS = 6;
19
+ /** RFC 9110 token: what a header name may contain. */
20
+ const VALID_HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
21
+ /**
22
+ * Headers that frame the connection rather than describe the request.
23
+ *
24
+ * `fetch` computes or forbids all of these, so a configured value is either
25
+ * ignored or produces an illegal message. `connection` is here for a second
26
+ * reason: it NAMES other headers as hop-by-hop, and the proxy honours that
27
+ * list — letting config set it would let config decide what gets dropped.
28
+ */
29
+ export const PROTECTED_HEADERS = new Set([
30
+ 'host',
31
+ 'connection',
32
+ 'content-length',
33
+ 'transfer-encoding',
34
+ 'keep-alive',
35
+ 'upgrade',
36
+ 'te',
37
+ 'trailer',
38
+ 'proxy-authorization',
39
+ 'proxy-connection',
40
+ 'expect',
41
+ ]);
42
+ /** A validation failure, with the config path that caused it. */
43
+ export class ConfigError extends Error {
44
+ constructor(message) {
45
+ super(message);
46
+ this.name = 'ConfigError';
47
+ }
48
+ }
49
+ function fail(at, message) {
50
+ throw new ConfigError(`${at}: ${message}`);
51
+ }
52
+ function asRecord(value, at) {
53
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
54
+ fail(at, 'expected a mapping');
55
+ }
56
+ return value;
57
+ }
58
+ /**
59
+ * Reject keys the schema does not define.
60
+ *
61
+ * A merchant config serves money, and the failure mode of silently dropping an
62
+ * unknown key is an endpoint that charges nothing because `price` was spelled
63
+ * `prise`. Better to refuse to start.
64
+ */
65
+ function rejectUnknownKeys(obj, allowed, at) {
66
+ for (const key of Object.keys(obj)) {
67
+ if (!allowed.includes(key)) {
68
+ fail(at, `unknown key "${key}" (expected one of: ${allowed.join(', ')})`);
69
+ }
70
+ }
71
+ }
72
+ function requireString(obj, key, at) {
73
+ const value = obj[key];
74
+ if (typeof value !== 'string' || value.trim() === '') {
75
+ fail(`${at}.${key}`, 'must be a non-empty string');
76
+ }
77
+ return value.trim();
78
+ }
79
+ /**
80
+ * Parse `"0.01 USDC"` into atomic units plus a symbol.
81
+ *
82
+ * Decimal-string arithmetic rather than `Number`: `0.07 * 1e6` is
83
+ * 70000.00000000001 in IEEE-754, and a price is money. Padding the fraction
84
+ * digits keeps it exact.
85
+ */
86
+ export function parsePrice(raw, at) {
87
+ const match = /^([0-9]+(?:\.[0-9]+)?)\s+([A-Za-z]{2,10})$/.exec(raw.trim());
88
+ if (!match) {
89
+ fail(at, `expected "<amount> <CURRENCY>", e.g. "0.01 USDC" (got "${raw}")`);
90
+ }
91
+ const [, numeric, currency] = match;
92
+ const [whole, fraction = ''] = numeric.split('.');
93
+ if (fraction.length > DECIMALS) {
94
+ fail(at, `more than ${DECIMALS} decimal places (got "${numeric}")`);
95
+ }
96
+ const atomic = `${whole}${fraction.padEnd(DECIMALS, '0')}`.replace(/^0+(?=\d)/, '');
97
+ if (BigInt(atomic) <= 0n) {
98
+ // A zero price is not a free endpoint: it would emit a 402 that settles
99
+ // nothing, so the payer signs an authorization for 0 and the token
100
+ // transfer is a no-op. Say `free: true` and mean it.
101
+ fail(at, `price must be greater than zero (use "free: true" for a free endpoint)`);
102
+ }
103
+ return { amount: atomic, currency: currency.toUpperCase() };
104
+ }
105
+ function parseSelf(raw, at) {
106
+ const obj = asRecord(raw, at);
107
+ rejectUnknownKeys(obj, ['scope', 'minimumAge', 'ofac', 'excludedCountries', 'endpoint', 'endpointType'], at);
108
+ const gate = { scope: requireString(obj, 'scope', at) };
109
+ if (obj.minimumAge !== undefined) {
110
+ if (typeof obj.minimumAge !== 'number' || !Number.isInteger(obj.minimumAge)) {
111
+ fail(`${at}.minimumAge`, 'must be an integer');
112
+ }
113
+ gate.minimumAge = obj.minimumAge;
114
+ }
115
+ if (obj.ofac !== undefined) {
116
+ if (typeof obj.ofac !== 'boolean')
117
+ fail(`${at}.ofac`, 'must be true or false');
118
+ gate.ofac = obj.ofac;
119
+ }
120
+ if (obj.excludedCountries !== undefined) {
121
+ const list = obj.excludedCountries;
122
+ if (!Array.isArray(list) || list.some((v) => typeof v !== 'string')) {
123
+ fail(`${at}.excludedCountries`, 'must be a list of ISO-3 country codes');
124
+ }
125
+ gate.excludedCountries = list.map((v) => v.toUpperCase());
126
+ }
127
+ if (obj.endpoint !== undefined)
128
+ gate.endpoint = requireString(obj, 'endpoint', at);
129
+ if (obj.endpointType !== undefined) {
130
+ const t = obj.endpointType;
131
+ if (t !== 'https' && t !== 'staging_https' && t !== 'celo' && t !== 'staging_celo') {
132
+ fail(`${at}.endpointType`, 'must be https | staging_https | celo | staging_celo');
133
+ }
134
+ gate.endpointType = t;
135
+ }
136
+ return gate;
137
+ }
138
+ function parseEndpoint(raw, index) {
139
+ const at = `endpoints[${index}]`;
140
+ const obj = asRecord(raw, at);
141
+ rejectUnknownKeys(obj, ['path', 'price', 'maxPrice', 'scheme', 'free', 'description', 'self'], at);
142
+ const path = requireString(obj, 'path', at);
143
+ if (!path.startsWith('/'))
144
+ fail(`${at}.path`, `must start with "/" (got "${path}")`);
145
+ // One trailing `*` only. A `*` anywhere else would need real glob semantics,
146
+ // and this is an allowlist — an operator must be able to read a pattern and
147
+ // know exactly what it admits.
148
+ const starCount = (path.match(/\*/g) ?? []).length;
149
+ if (starCount > 1 || (starCount === 1 && !path.endsWith('/*'))) {
150
+ fail(`${at}.path`, `only a single trailing "/*" wildcard is supported (got "${path}")`);
151
+ }
152
+ const free = obj.free === true;
153
+ if (obj.free !== undefined && typeof obj.free !== 'boolean') {
154
+ fail(`${at}.free`, 'must be true or false');
155
+ }
156
+ const hasPrice = obj.price !== undefined;
157
+ const hasMaxPrice = obj.maxPrice !== undefined;
158
+ if (free) {
159
+ if (hasPrice || hasMaxPrice)
160
+ fail(at, 'a free endpoint must not also set price/maxPrice');
161
+ return {
162
+ path,
163
+ free: true,
164
+ scheme: 'exact',
165
+ amount: '0',
166
+ currency: '',
167
+ description: typeof obj.description === 'string' ? obj.description : '',
168
+ };
169
+ }
170
+ let scheme = 'exact';
171
+ if (obj.scheme !== undefined) {
172
+ if (obj.scheme !== 'exact' && obj.scheme !== 'upto') {
173
+ fail(`${at}.scheme`, `must be "exact" or "upto" (got "${String(obj.scheme)}")`);
174
+ }
175
+ scheme = obj.scheme;
176
+ }
177
+ // `price` pairs with exact, `maxPrice` with upto — enforced so the config
178
+ // reads as what it does. Accepting either for both would let a config say
179
+ // `maxPrice` on an exact endpoint, implying a cap that is really the price.
180
+ if (hasPrice && hasMaxPrice)
181
+ fail(at, 'set either price or maxPrice, not both');
182
+ if (scheme === 'exact' && !hasPrice)
183
+ fail(at, 'an exact endpoint needs "price"');
184
+ if (scheme === 'upto' && !hasMaxPrice)
185
+ fail(at, 'an upto endpoint needs "maxPrice"');
186
+ const priceKey = scheme === 'exact' ? 'price' : 'maxPrice';
187
+ const rawPrice = obj[priceKey];
188
+ if (typeof rawPrice !== 'string')
189
+ fail(`${at}.${priceKey}`, 'must be a string like "0.01 USDC"');
190
+ const { amount, currency } = parsePrice(rawPrice, `${at}.${priceKey}`);
191
+ const endpoint = {
192
+ path,
193
+ free: false,
194
+ scheme,
195
+ amount,
196
+ currency,
197
+ description: typeof obj.description === 'string' ? obj.description : `${rawPrice} — ${path}`,
198
+ };
199
+ if (obj.self !== undefined)
200
+ endpoint.self = parseSelf(obj.self, `${at}.self`);
201
+ return endpoint;
202
+ }
203
+ function parseRouting(raw) {
204
+ const obj = asRecord(raw, 'routing');
205
+ rejectUnknownKeys(obj, ['mode', 'upstream', 'injectHeaders', 'body', 'contentType'], 'routing');
206
+ const mode = obj.mode;
207
+ if (mode !== 'proxy' && mode !== 'respond') {
208
+ fail('routing.mode', `must be "proxy" or "respond" (got "${String(mode)}")`);
209
+ }
210
+ if (mode === 'respond') {
211
+ return {
212
+ mode: 'respond',
213
+ body: typeof obj.body === 'string' ? obj.body : '{"ok":true}',
214
+ contentType: typeof obj.contentType === 'string' ? obj.contentType : 'application/json',
215
+ };
216
+ }
217
+ const upstream = requireString(obj, 'upstream', 'routing');
218
+ let parsed;
219
+ try {
220
+ parsed = new URL(upstream);
221
+ }
222
+ catch {
223
+ fail('routing.upstream', `is not a valid URL (got "${upstream}")`);
224
+ }
225
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
226
+ fail('routing.upstream', 'must be an http(s) URL');
227
+ }
228
+ const injectHeaders = {};
229
+ if (obj.injectHeaders !== undefined) {
230
+ const headers = asRecord(obj.injectHeaders, 'routing.injectHeaders');
231
+ const seen = new Map();
232
+ for (const [header, envVar] of Object.entries(headers)) {
233
+ if (typeof envVar !== 'string' || envVar.trim() === '') {
234
+ fail(`routing.injectHeaders.${header}`, 'must name an environment variable');
235
+ }
236
+ const lower = header.toLowerCase();
237
+ if (!VALID_HEADER_NAME.test(header)) {
238
+ fail(`routing.injectHeaders.${header}`, 'is not a valid HTTP header name');
239
+ }
240
+ // Framing and hop-by-hop headers describe THIS connection, not the
241
+ // request: injecting one either corrupts the upstream message or is
242
+ // silently dropped. Refused at load rather than ignored at request time,
243
+ // so an operator learns about it once instead of never.
244
+ if (PROTECTED_HEADERS.has(lower)) {
245
+ fail(`routing.injectHeaders.${header}`, 'cannot be set — it frames the connection');
246
+ }
247
+ // The gateway strips these from the caller before proxying; letting the
248
+ // config re-add them would hand the upstream a payment proof the caller
249
+ // never sent.
250
+ if (lower === 'x-payment' || lower === 'x-self-attestation') {
251
+ fail(`routing.injectHeaders.${header}`, 'is a payment header the gateway strips');
252
+ }
253
+ // Two spellings of one header are one header to HTTP, and which value
254
+ // wins would depend on object key order.
255
+ const prior = seen.get(lower);
256
+ if (prior !== undefined) {
257
+ fail(`routing.injectHeaders.${header}`, `duplicates "${prior}" — header names are case-insensitive`);
258
+ }
259
+ seen.set(lower, header);
260
+ // The config stores the env var NAME, never the secret itself — a
261
+ // paywall.yml is checked into a repo.
262
+ injectHeaders[header] = envVar.trim();
263
+ }
264
+ }
265
+ return { mode: 'proxy', upstream, injectHeaders };
266
+ }
267
+ /** Parse and validate a paywall config from YAML source. */
268
+ export function parseConfig(source) {
269
+ let doc;
270
+ try {
271
+ doc = parseYaml(source);
272
+ }
273
+ catch (err) {
274
+ throw new ConfigError(`invalid YAML: ${err instanceof Error ? err.message : String(err)}`);
275
+ }
276
+ const root = asRecord(doc, 'config');
277
+ rejectUnknownKeys(root, ['name', 'version', 'network', 'payTo', 'routing', 'endpoints'], 'config');
278
+ if (root.version !== 1) {
279
+ fail('config.version', `must be 1 (got ${JSON.stringify(root.version)})`);
280
+ }
281
+ const name = requireString(root, 'name', 'config');
282
+ const network = root.network;
283
+ if (network !== 'celo' && network !== 'celo-sepolia') {
284
+ fail('config.network', `must be "celo" or "celo-sepolia" (got "${String(network)}")`);
285
+ }
286
+ const payTo = requireString(root, 'payTo', 'config');
287
+ if (!/^0x[0-9a-fA-F]{40}$/.test(payTo)) {
288
+ fail('config.payTo', `must be a 0x-prefixed 20-byte address (got "${payTo}")`);
289
+ }
290
+ const routing = parseRouting(root.routing);
291
+ if (!Array.isArray(root.endpoints) || root.endpoints.length === 0) {
292
+ fail('config.endpoints', 'must be a non-empty list');
293
+ }
294
+ const endpoints = root.endpoints.map(parseEndpoint);
295
+ // Duplicate paths are ambiguous — first-match would silently win and the
296
+ // operator would be reading the wrong line when a price looks wrong.
297
+ const seen = new Set();
298
+ for (const ep of endpoints) {
299
+ if (seen.has(ep.path))
300
+ fail('config.endpoints', `duplicate path "${ep.path}"`);
301
+ seen.add(ep.path);
302
+ }
303
+ return { name, version: 1, network, payTo, routing, endpoints };
304
+ }
305
+ /**
306
+ * Find the endpoint governing `pathname`, or undefined when none does — which
307
+ * the server must treat as 404.
308
+ *
309
+ * Exact matches win over wildcards, and longer wildcard prefixes win over
310
+ * shorter ones, so `/a/b/*` beats `/a/*` regardless of config order. Order-
311
+ * independence matters: an operator adding a specific rule should not have to
312
+ * know it must go above a general one.
313
+ */
314
+ export function matchEndpoint(config, pathname) {
315
+ let best;
316
+ let bestPrefixLength = -1;
317
+ for (const ep of config.endpoints) {
318
+ if (!ep.path.endsWith('/*')) {
319
+ if (ep.path === pathname)
320
+ return ep; // exact match is unambiguous
321
+ continue;
322
+ }
323
+ const prefix = ep.path.slice(0, -1); // keep the trailing slash: '/a/*' -> '/a/'
324
+ // The prefix must end at a SEGMENT boundary, which the retained slash
325
+ // guarantees: '/quote/*' must not match '/quoteXYZ'.
326
+ if (pathname.startsWith(prefix) && prefix.length > bestPrefixLength) {
327
+ best = ep;
328
+ bestPrefixLength = prefix.length;
329
+ }
330
+ }
331
+ return best;
332
+ }
333
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,KAAK,IAAI,SAAS,EAAE,MAAM,MAAM,CAAC;AAE1C,+EAA+E;AAC/E,MAAM,QAAQ,GAAG,CAAC,CAAC;AA2CnB,sDAAsD;AACtD,MAAM,iBAAiB,GAAG,gCAAgC,CAAC;AAE3D;;;;;;;GAOG;AACH,MA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AC;IACrC,IAAI,gBAAgB,GAAG,CAAC,CAAC,CAAC;IAE1B,KAAK,MAAM,EAAE,IAAI,MAAM,CAAC,SAAS,EAAE,CAAC;QAClC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;YAC5B,IAAI,EAAE,CAAC,IAAI,KAAK,QAAQ;gBAAE,OAAO,EAAE,CAAC,CAAC,6BAA6B;YAClE,SAAS;QACX,CAAC;QACD,MAAM,MAAM,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,2CAA2C;QAChF,sEAAsE;QACtE,qDAAqD;QACrD,IAAI,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,MAAM,GAAG,gBAAgB,EAAE,CAAC;YACpE,IAAI,GAAG,EAAE,CAAC;YACV,gBAAgB,GAAG,MAAM,CAAC,MAAM,CAAC;QACnC,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,3 @@
1
+ export * from './config.js';
2
+ export * from './server.js';
3
+ export * from './usage.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from './config.js';
2
+ export * from './server.js';
3
+ export * from './usage.js';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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"}
@@ -0,0 +1,66 @@
1
+ /**
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.
23
+ */
24
+ import http from 'node:http';
25
+ import type { PaymentRequirements } from '@celo/buy-core';
26
+ import { type FacilitatorEvents } from '@celo/buy-facilitator';
27
+ import type { LocalAccount } from 'viem';
28
+ import { type EndpointConfig, type PaywallConfig } from './config.js';
29
+ import { type UsageStats } from './usage.js';
30
+ export type GatewayOptions = {
31
+ config: PaywallConfig;
32
+ /**
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`.
36
+ */
37
+ sponsor?: LocalAccount;
38
+ /**
39
+ * Re-run the Self proof server-side and ignore the client's claimed
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.
43
+ */
44
+ reverify?: boolean;
45
+ events?: FacilitatorEvents;
46
+ /** Resolved header values for proxy mode, injected per request. */
47
+ resolvedHeaders?: Record<string, string>;
48
+ log?: (line: string) => void;
49
+ };
50
+ export type Gateway = {
51
+ server: http.Server;
52
+ usage: () => UsageStats;
53
+ };
54
+ /** Build the x402 requirements for one endpoint. */
55
+ export declare function requirementsFor(config: PaywallConfig, endpoint: EndpointConfig, resource: string): PaymentRequirements;
56
+ /**
57
+ * Refuse a config whose currencies cannot actually settle, at BOOT.
58
+ *
59
+ * Without this the failure surfaces on the first real payment: the payer signs
60
+ * an authorization the token can never honour, and the operator learns their
61
+ * paywall is broken from a customer. `tokenBySymbol` returns undefined for a
62
+ * symbol that does not exist on the network (there is no USDT on sepolia), and
63
+ * a token without EIP-712 domain metadata does not implement EIP-3009.
64
+ */
65
+ export declare function validateTokens(config: PaywallConfig): void;
66
+ export declare function createGateway(opts: GatewayOptions): Gateway;
package/dist/server.js ADDED
@@ -0,0 +1,370 @@
1
+ /**
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.
23
+ */
24
+ import { randomBytes } from 'node:crypto';
25
+ import http from 'node:http';
26
+ import { chainFor, tokenBySymbol } from '@celo/buy-core';
27
+ import { settleX402Payment, verifySelfAttestation, verifyX402Payment, } from '@celo/buy-facilitator';
28
+ import { PROTECTED_HEADERS, matchEndpoint, } from './config.js';
29
+ import { createUsageRecorder } from './usage.js';
30
+ /** Anonymous callers can reach the body reader, so it must be bounded. */
31
+ const MAX_BODY_BYTES = 64 * 1024;
32
+ function json(res, status, body) {
33
+ res.writeHead(status, { 'Content-Type': 'application/json' });
34
+ res.end(JSON.stringify(body));
35
+ }
36
+ function decodeHeader(raw) {
37
+ return JSON.parse(Buffer.from(raw, 'base64').toString('utf8'));
38
+ }
39
+ function encodeHeader(value) {
40
+ return Buffer.from(JSON.stringify(value)).toString('base64');
41
+ }
42
+ /** Absolute URL of the resource being requested, for the 402 envelope. */
43
+ function resourceUrl(req, pathname) {
44
+ const proto = req.headers['x-forwarded-proto'] ?? 'http';
45
+ const host = req.headers['x-forwarded-host'] ?? req.headers.host ?? 'localhost';
46
+ return `${proto}://${host}${pathname}`;
47
+ }
48
+ /** Build the x402 requirements for one endpoint. */
49
+ export function requirementsFor(config, endpoint, resource) {
50
+ const token = tokenBySymbol(config.network, endpoint.currency);
51
+ if (!token) {
52
+ throw new Error(`${endpoint.currency} is not a known token on ${config.network} — check the endpoint's price currency`);
53
+ }
54
+ // Not every listed token implements EIP-3009 (USDm does not), and one that
55
+ // does not can never settle a signed authorization. `validateTokens` refuses
56
+ // such a config at BOOT; this is the belt-and-braces for a caller building
57
+ // requirements directly.
58
+ if (!token.eip712Name || !token.eip712Version) {
59
+ throw new Error(`${endpoint.currency} on ${config.network} cannot be used for x402: the token does not implement EIP-3009`);
60
+ }
61
+ const requirements = {
62
+ scheme: endpoint.scheme,
63
+ network: config.network,
64
+ maxAmountRequired: endpoint.amount,
65
+ resource,
66
+ description: endpoint.description,
67
+ mimeType: 'application/json',
68
+ payTo: config.payTo,
69
+ maxTimeoutSeconds: 60,
70
+ asset: token.address,
71
+ // The EIP-712 domain comes from the TOKEN, and the two differ between
72
+ // networks — USDC is "USD Coin" on mainnet but "USDC" on sepolia. Getting
73
+ // this wrong produces a signature the token rejects at settlement.
74
+ extra: { name: token.eip712Name, version: token.eip712Version },
75
+ };
76
+ if (endpoint.self) {
77
+ requirements.extra = {
78
+ ...requirements.extra,
79
+ selfRequirements: {
80
+ scope: endpoint.self.scope,
81
+ ...(endpoint.self.endpoint ? { endpoint: endpoint.self.endpoint } : {}),
82
+ ...(endpoint.self.endpointType ? { endpointType: endpoint.self.endpointType } : {}),
83
+ disclosures: {
84
+ ...(endpoint.self.minimumAge !== undefined
85
+ ? { minimumAge: endpoint.self.minimumAge }
86
+ : {}),
87
+ ...(endpoint.self.ofac !== undefined ? { ofac: endpoint.self.ofac } : {}),
88
+ ...(endpoint.self.excludedCountries
89
+ ? { excludedCountries: endpoint.self.excludedCountries }
90
+ : {}),
91
+ },
92
+ },
93
+ };
94
+ }
95
+ return requirements;
96
+ }
97
+ /**
98
+ * Refuse a config whose currencies cannot actually settle, at BOOT.
99
+ *
100
+ * Without this the failure surfaces on the first real payment: the payer signs
101
+ * an authorization the token can never honour, and the operator learns their
102
+ * paywall is broken from a customer. `tokenBySymbol` returns undefined for a
103
+ * symbol that does not exist on the network (there is no USDT on sepolia), and
104
+ * a token without EIP-712 domain metadata does not implement EIP-3009.
105
+ */
106
+ export function validateTokens(config) {
107
+ for (const endpoint of config.endpoints) {
108
+ if (endpoint.free)
109
+ continue;
110
+ const token = tokenBySymbol(config.network, endpoint.currency);
111
+ if (!token) {
112
+ throw new Error(`endpoint "${endpoint.path}": ${endpoint.currency} is not a known token on ${config.network}`);
113
+ }
114
+ if (!token.eip712Name || !token.eip712Version) {
115
+ throw new Error(`endpoint "${endpoint.path}": ${endpoint.currency} on ${config.network} does not implement EIP-3009, so it cannot be used for x402 payments`);
116
+ }
117
+ }
118
+ }
119
+ /** Read a bounded request body, answering 413 and returning undefined if oversized. */
120
+ async function readBody(req, res) {
121
+ const chunks = [];
122
+ let size = 0;
123
+ for await (const chunk of req) {
124
+ size += chunk.length;
125
+ if (size > MAX_BODY_BYTES) {
126
+ json(res, 413, { error: `request body too large (max ${MAX_BODY_BYTES} bytes)` });
127
+ req.destroy();
128
+ return undefined;
129
+ }
130
+ chunks.push(chunk);
131
+ }
132
+ return Buffer.concat(chunks);
133
+ }
134
+ export function createGateway(opts) {
135
+ const { config, sponsor, events } = opts;
136
+ const log = opts.log ?? (() => { });
137
+ const chain = chainFor(config.network);
138
+ const usage = createUsageRecorder();
139
+ const handle = async (req, res) => {
140
+ const parsed = new URL(req.url ?? '/', 'http://placeholder');
141
+ const pathname = parsed.pathname;
142
+ if (pathname === '/healthz') {
143
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
144
+ res.end('ok');
145
+ return;
146
+ }
147
+ if (pathname === '/__buy/usage') {
148
+ json(res, 200, usage.snapshot());
149
+ return;
150
+ }
151
+ // THE ALLOWLIST. A path with no matching endpoint is not merely unpriced —
152
+ // it does not exist as far as this gateway is concerned, and in proxy mode
153
+ // it is never forwarded. That is what stops a paywall from accidentally
154
+ // exposing everything behind it.
155
+ const endpoint = matchEndpoint(config, pathname);
156
+ if (!endpoint) {
157
+ json(res, 404, { error: 'not_found' });
158
+ return;
159
+ }
160
+ const body = await readBody(req, res);
161
+ if (body === undefined)
162
+ return; // 413 already sent
163
+ if (endpoint.free) {
164
+ await serve(req, res, pathname, body, null, undefined);
165
+ return;
166
+ }
167
+ const cid = randomBytes(6).toString('hex');
168
+ const requirements = requirementsFor(config, endpoint, resourceUrl(req, pathname));
169
+ const challenge = { x402Version: 1, accepts: [requirements], error: '' };
170
+ const paymentHeader = req.headers['x-payment'];
171
+ if (!paymentHeader) {
172
+ json(res, 402, challenge);
173
+ return;
174
+ }
175
+ let payment;
176
+ try {
177
+ payment = decodeHeader(String(paymentHeader));
178
+ }
179
+ catch (err) {
180
+ json(res, 402, {
181
+ ...challenge,
182
+ error: `malformed X-PAYMENT: ${err instanceof Error ? err.message : String(err)}`,
183
+ });
184
+ return;
185
+ }
186
+ const verified = await verifyX402Payment({
187
+ requirements,
188
+ // biome-ignore lint/suspicious/noExplicitAny: verified inside; anything may arrive on the wire
189
+ payment: payment,
190
+ chainId: chain.id,
191
+ ...(events ? { events } : {}),
192
+ });
193
+ if (!verified.ok) {
194
+ usage.recordRejection(endpoint.path, verified.reason);
195
+ json(res, 402, { ...challenge, error: `verify_payment_failed: ${verified.reason}` });
196
+ return;
197
+ }
198
+ if (endpoint.self) {
199
+ const selfHeader = req.headers['x-self-attestation'];
200
+ const selfResult = await verifySelfAttestation({
201
+ requirements: requirements.extra?.selfRequirements,
202
+ attestationHeader: selfHeader ? String(selfHeader) : undefined,
203
+ expectedAddress: verified.from,
204
+ ...(opts.reverify ? { reverify: { mockPassport: true, appName: config.name } } : {}),
205
+ ...(events ? { events } : {}),
206
+ });
207
+ if (!selfResult.ok) {
208
+ // Nothing settled, so hand the nonce back. Without this a KYC refusal
209
+ // locks the payer out of their own authorization until the claim's TTL
210
+ // expires, and their corrected retry comes back as `nonce_already_seen`
211
+ // — a replay error for a payment that never paid.
212
+ await verified.releaseNonce();
213
+ usage.recordRejection(endpoint.path, selfResult.reason);
214
+ json(res, 402, {
215
+ ...challenge,
216
+ error: `verify_self_failed: ${selfResult.reason}${selfResult.detail ? ` (${selfResult.detail})` : ''}`,
217
+ });
218
+ return;
219
+ }
220
+ }
221
+ let transaction = null;
222
+ if (sponsor) {
223
+ try {
224
+ const settled = await settleX402Payment({
225
+ requirements,
226
+ // biome-ignore lint/suspicious/noExplicitAny: already verified above
227
+ payment: payment,
228
+ chain,
229
+ sponsor,
230
+ ...(events ? { events } : {}),
231
+ });
232
+ transaction = settled.tx;
233
+ log(`settled cid=${cid} ${verified.from} → ${config.payTo} tx=${settled.tx}`);
234
+ }
235
+ catch (err) {
236
+ // Deliberately NOT releasing the nonce: settle broadcasts before it
237
+ // awaits the receipt, so a throw does not mean the transfer failed —
238
+ // it may be mined moments later. Releasing would invite a retry of an
239
+ // authorization that is already spending.
240
+ const message = err instanceof Error ? err.message : String(err);
241
+ log(`SETTLE FAILED cid=${cid} payer=${verified.from} err=${message}`);
242
+ usage.recordRejection(endpoint.path, 'settle_failed');
243
+ json(res, 402, {
244
+ ...challenge,
245
+ error: `settle_failed: ${message} (correlation id: ${cid})`,
246
+ });
247
+ return;
248
+ }
249
+ }
250
+ usage.recordPayment(endpoint.path, endpoint.amount, endpoint.currency);
251
+ await serve(req, res, pathname, body, transaction, verified.from);
252
+ };
253
+ /** Deliver the paid resource: proxy upstream, or answer from config. */
254
+ const serve = async (req, res, pathname, body, transaction, payer) => {
255
+ const paymentResponse = payer === undefined
256
+ ? undefined
257
+ : encodeHeader({
258
+ success: true,
259
+ network: config.network,
260
+ payer,
261
+ transaction,
262
+ });
263
+ if (config.routing.mode === 'respond') {
264
+ const headers = { 'Content-Type': config.routing.contentType };
265
+ if (paymentResponse)
266
+ headers['X-PAYMENT-RESPONSE'] = paymentResponse;
267
+ res.writeHead(200, headers);
268
+ res.end(config.routing.body);
269
+ return;
270
+ }
271
+ const target = new URL(pathname.replace(/^\//, ''), `${config.routing.upstream.replace(/\/$/, '')}/`);
272
+ const search = new URL(req.url ?? '/', 'http://placeholder').search;
273
+ if (search)
274
+ target.search = search;
275
+ // A plain object keyed by header name is the wrong shape here: HTTP header
276
+ // names are case-insensitive, so a caller's `authorization` and a
277
+ // configured `Authorization` are two keys in an object but one header on
278
+ // the wire — and merging them concatenated the caller's value with the
279
+ // trusted one ("Bearer caller, Bearer trusted"). `Headers` folds case for
280
+ // us, so `set()` genuinely replaces whatever the caller sent.
281
+ const forwarded = new Headers();
282
+ // `Connection` names further headers as hop-by-hop. Honouring that list is
283
+ // not politeness: it is how a caller says "this header ends at the proxy",
284
+ // and ignoring it forwards per-connection state to a different connection.
285
+ const hopByHop = new Set();
286
+ const connection = req.headers.connection;
287
+ if (typeof connection === 'string') {
288
+ for (const name of connection.split(',')) {
289
+ const trimmed = name.trim().toLowerCase();
290
+ if (trimmed !== '')
291
+ hopByHop.add(trimmed);
292
+ }
293
+ }
294
+ for (const [key, value] of Object.entries(req.headers)) {
295
+ const lower = key.toLowerCase();
296
+ // Framing headers stop here because we re-frame the request ourselves;
297
+ // the payment headers stop here because the upstream neither needs the
298
+ // payment proof nor should be able to see the caller's attestation.
299
+ if (PROTECTED_HEADERS.has(lower) ||
300
+ lower === 'x-payment' ||
301
+ lower === 'x-self-attestation' ||
302
+ hopByHop.has(lower)) {
303
+ continue;
304
+ }
305
+ if (typeof value === 'string')
306
+ forwarded.append(key, value);
307
+ else if (Array.isArray(value))
308
+ for (const v of value)
309
+ forwarded.append(key, v);
310
+ }
311
+ // Last, and with `set`: a configured credential must win over anything the
312
+ // caller sent under any spelling of the same name.
313
+ for (const [key, value] of Object.entries(opts.resolvedHeaders ?? {})) {
314
+ forwarded.set(key, value);
315
+ }
316
+ const upstreamRes = await fetch(target, {
317
+ method: req.method ?? 'GET',
318
+ headers: forwarded,
319
+ // Buffer -> Uint8Array: a Node Buffer is not a DOM BodyInit, and passing
320
+ // one relies on undici's tolerance rather than the typed contract.
321
+ ...(body.length > 0 && req.method !== 'GET' && req.method !== 'HEAD'
322
+ ? { body: new Uint8Array(body) }
323
+ : {}),
324
+ });
325
+ const outHeaders = {};
326
+ upstreamRes.headers.forEach((value, key) => {
327
+ const lower = key.toLowerCase();
328
+ // Drop the upstream's framing and encoding headers. `fetch` has already
329
+ // decoded the body and we re-frame it with our own content-length below,
330
+ // so forwarding these describes a body that no longer exists: a
331
+ // `transfer-encoding: chunked` alongside our content-length is illegal
332
+ // per RFC 9112, and undici rejects the response outright with
333
+ // "Content-Length can't be present with Transfer-Encoding" — the client
334
+ // sees a failed fetch even though the payment settled.
335
+ if (lower === 'content-encoding' ||
336
+ lower === 'transfer-encoding' ||
337
+ lower === 'content-length') {
338
+ return;
339
+ }
340
+ // Hop-by-hop headers are per-connection and must not be relayed.
341
+ if (lower === 'connection' || lower === 'keep-alive')
342
+ return;
343
+ outHeaders[key] = value;
344
+ });
345
+ if (paymentResponse)
346
+ outHeaders['X-PAYMENT-RESPONSE'] = paymentResponse;
347
+ const buf = Buffer.from(await upstreamRes.arrayBuffer());
348
+ outHeaders['content-length'] = String(buf.length);
349
+ res.writeHead(upstreamRes.status, outHeaders);
350
+ res.end(buf);
351
+ };
352
+ const server = http.createServer((req, res) => {
353
+ // Per-request boundary: answer this request rather than letting the throw
354
+ // reach the process handler, which cannot see `res` and would leave the
355
+ // client hanging on a socket that is never released.
356
+ handle(req, res).catch((err) => {
357
+ log(`request failed: ${err instanceof Error ? err.message : String(err)}`);
358
+ if (res.headersSent) {
359
+ res.destroy();
360
+ return;
361
+ }
362
+ json(res, 500, { error: 'internal_error' });
363
+ });
364
+ });
365
+ // A trickled body would otherwise hold a handler slot for Node's 300s default.
366
+ server.requestTimeout = 30_000;
367
+ server.headersTimeout = 20_000;
368
+ return { server, usage: () => usage.snapshot() };
369
+ }
370
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AACzD,OAAO,EAEL,iBAAiB,EACjB,qBAAqB,EACrB,iBAAiB,GAClB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAEL,iBAAiB,EAEjB,aAAa,GACd,MAAM,aAAa,CAAC;AACrB,OAAO,EAAmB,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAElE,0EAA0E;AAC1E,MAAM,cAAc,GAAG,EAAE,GAAG,IAAI,CAAC;AA4BjC,SAAS,IAAI,CAAC,GAAwB,EAAE,MAAc,EAAE,IAAa;IACnE,GAAG,CAAC,SAAS,CAAC,MAAM,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE,CAAC,CAAC;IAC9D,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;AAChC,CAAC;AAED,SAAS,YAAY,CAAC,GAAW;IAC/B,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;AACjE,CAAC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E,gBAAgB,EAAE,CAAC,CAAC;QAC9C,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,+EAA+E;IAC/E,MAAM,CAAC,cAAc,GAAG,MAAM,CAAC;IAC/B,MAAM,CAAC,cAAc,GAAG,MAAM,CAAC;IAE/B,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,QAAQ,EAAE,EAAE,CAAC;AACnD,CAAC"}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Per-endpoint revenue and rejection counters, served at `/__buy/usage`.
3
+ *
4
+ * Deliberately in-memory and deliberately small: the issue asked for "a
5
+ * minimal built-in usage view … no separate dashboard product". It resets on
6
+ * restart, which is honest for what it is — an operator's sanity check that
7
+ * money is arriving and which endpoint is earning it, not an accounting
8
+ * record. The receipts file and the chain are the durable sources of truth.
9
+ */
10
+ export type EndpointUsage = {
11
+ path: string;
12
+ /** Payments that reached settlement (or mock-mode completion). */
13
+ payments: number;
14
+ /** Summed atomic units, as a decimal string — revenue can exceed 2^53. */
15
+ revenue: string;
16
+ currency: string;
17
+ /** Rejections by reason, e.g. `{ nonce_already_seen: 3 }`. */
18
+ rejections: Record<string, number>;
19
+ };
20
+ export type UsageStats = {
21
+ startedAt: string;
22
+ totalPayments: number;
23
+ endpoints: EndpointUsage[];
24
+ };
25
+ export type UsageRecorder = {
26
+ recordPayment(path: string, atomicAmount: string, currency: string): void;
27
+ recordRejection(path: string, reason: string): void;
28
+ snapshot(): UsageStats;
29
+ };
30
+ export declare function createUsageRecorder(now?: () => Date): UsageRecorder;
package/dist/usage.js ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Per-endpoint revenue and rejection counters, served at `/__buy/usage`.
3
+ *
4
+ * Deliberately in-memory and deliberately small: the issue asked for "a
5
+ * minimal built-in usage view … no separate dashboard product". It resets on
6
+ * restart, which is honest for what it is — an operator's sanity check that
7
+ * money is arriving and which endpoint is earning it, not an accounting
8
+ * record. The receipts file and the chain are the durable sources of truth.
9
+ */
10
+ export function createUsageRecorder(now = () => new Date()) {
11
+ const startedAt = now().toISOString();
12
+ const byPath = new Map();
13
+ const entryFor = (path) => {
14
+ let entry = byPath.get(path);
15
+ if (!entry) {
16
+ entry = { path, payments: 0, revenue: '0', currency: '', rejections: {} };
17
+ byPath.set(path, entry);
18
+ }
19
+ return entry;
20
+ };
21
+ return {
22
+ recordPayment(path, atomicAmount, currency) {
23
+ const entry = entryFor(path);
24
+ entry.payments += 1;
25
+ // BigInt, not Number: atomic units are 6-decimal, so a busy endpoint
26
+ // crosses 2^53 well before it crosses anything interesting in dollars.
27
+ entry.revenue = (BigInt(entry.revenue) + BigInt(atomicAmount)).toString();
28
+ entry.currency = currency;
29
+ },
30
+ recordRejection(path, reason) {
31
+ const entry = entryFor(path);
32
+ entry.rejections[reason] = (entry.rejections[reason] ?? 0) + 1;
33
+ },
34
+ snapshot() {
35
+ const endpoints = [...byPath.values()].map((e) => ({
36
+ ...e,
37
+ rejections: { ...e.rejections },
38
+ }));
39
+ return {
40
+ startedAt,
41
+ totalPayments: endpoints.reduce((sum, e) => sum + e.payments, 0),
42
+ endpoints,
43
+ };
44
+ },
45
+ };
46
+ }
47
+ //# sourceMappingURL=usage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage.js","sourceRoot":"","sources":["../src/usage.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAyBH,MAAM,UAAU,mBAAmB,CAAC,MAAkB,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE;IACpE,MAAM,SAAS,GAAG,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC;IACtC,MAAM,MAAM,GAAG,IAAI,GAAG,EAAyB,CAAC;IAEhD,MAAM,QAAQ,GAAG,CAAC,IAAY,EAAiB,EAAE;QAC/C,IAAI,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC7B,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,KAAK,GAA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,CAAC;gBAChE,SAAS;aACV,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC"}
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@celo/buy-gateway",
3
+ "version": "0.3.0",
4
+ "description": "buy gateway — serve an x402 paywall from a declarative YAML config",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": "./dist/index.js"
11
+ },
12
+ "files": [
13
+ "dist",
14
+ "LICENSE"
15
+ ],
16
+ "dependencies": {
17
+ "viem": "^2.21.55",
18
+ "yaml": "^2.6.1",
19
+ "@celo/buy-core": "0.3.0",
20
+ "@celo/buy-facilitator": "0.3.0"
21
+ },
22
+ "devDependencies": {
23
+ "@types/node": "^22.10.0"
24
+ },
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/celo-org/cpay.git",
28
+ "directory": "packages/gateway"
29
+ },
30
+ "homepage": "https://github.com/celo-org/cpay/tree/main/packages/gateway#readme",
31
+ "bugs": {
32
+ "url": "https://github.com/celo-org/cpay/issues"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public",
36
+ "registry": "https://registry.npmjs.org"
37
+ },
38
+ "scripts": {
39
+ "build": "tsc -p tsconfig.json",
40
+ "test": "vitest run"
41
+ }
42
+ }