satsgate-proxy 0.14.1__tar.gz

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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,222 @@
1
+ Metadata-Version: 2.4
2
+ Name: satsgate-proxy
3
+ Version: 0.14.1
4
+ Summary: Charge AI agents in Lightning and USDC on the same 402. 500 free unlocks per UTC month. Self-hosted reverse proxy. Cobrale a agentes de IA en Lightning y USDC, en el mismo 402.
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/Mike-io-hash/satsgate
7
+ Project-URL: Issues, https://github.com/Mike-io-hash/satsgate/issues
8
+ Project-URL: Changelog, https://github.com/Mike-io-hash/satsgate/blob/main/CHANGELOG.md
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: starlette>=0.37.0
18
+ Requires-Dist: uvicorn>=0.30.0
19
+ Requires-Dist: httpx>=0.27.0
20
+ Requires-Dist: pyyaml>=6.0.1
21
+ Requires-Dist: pymacaroons>=0.13.0
22
+ Dynamic: license-file
23
+
24
+ # satsgate-proxy
25
+
26
+ A reverse proxy a merchant runs beside an existing HTTP API. The buyer hits the proxy. The proxy sells the request through [satsgate](https://api.satsgate.org) and forwards only a paid request to the origin. The merchant does not write paywall code.
27
+
28
+ The proxy is version **0.14.1**. It works with core 0.20.3 or later and with gate 0.15.2 or later. Default `mode: paywall` talks to the satsgate core paywall (challenge, verify, status, charge, and x402 verify/settle). `mode: receipt` does not call core and does not use an API key. It checks `Satsgate-Receipt` with the site secret and forwards a successful check to the origin. The proxy does not sell prepaid balance and does not call the facilitator. Top up on the core with `POST /v1/topup/lightning` or `POST /v1/topup/usdc`. While the operator CDP switch is on, a USDC top-up is Base mainnet USDC only. The hosted gate is a separate program and only sells receipts. Buyer USDC on a proxied paywall route goes to the merchant's verified `payTo`. In receipt mode the buyer already paid the gate.
29
+
30
+ ## Install
31
+
32
+ ```bash
33
+ pip install satsgate-proxy
34
+ uvx --env-file .env satsgate-proxy --config satsgate-proxy.yaml
35
+ docker pull ghcr.io/mike-io-hash/satsgate-proxy:0.14.1
36
+ ```
37
+
38
+ From a checkout: `pip install -e proxy`.
39
+
40
+ ## USDC payments: Base network only
41
+
42
+ USDC payments use Base only. Ethereum mainnet, Polygon, Solana, Arbitrum, and any other chain are not accepted.
43
+
44
+ | Network | Network id | Circle USDC contract | Status |
45
+ | --- | --- | --- | --- |
46
+ | Base Sepolia (testnet) | `eip155:84532` | [`0x036CbD53842c5426634e7929541eC2318f3dCF7e`](https://sepolia.basescan.org/token/0x036CbD53842c5426634e7929541eC2318f3dCF7e) | Testing. `x402: true` without `x402_mode`, or `x402_mode: test`, offers only this USDC. It is not a network for real buyers. |
47
+ | Base | `eip155:8453` | [`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`](https://basescan.org/token/0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913) | `x402_mode: live`. Available only when the operator sets `SATSGATE_X402_CDP=1` and both CDP credentials. The 402 offers only this USDC. |
48
+
49
+ Merchants: `payTo` must be an address you control on Base. Prove it with the same EVM challenge the hosted gate uses. The USDC is paid to that address on the one network the route is in. Try on Base Sepolia with your agent first, then switch the site to live. Buyers: USDC sent on another network will not be accepted. A balance on Ethereum, Polygon, Solana, or Arbitrum does not pay this proxy.
50
+
51
+ Satsgate never custodies, receives, forwards, or refunds buyer funds. The USDC moves from the buyer to the merchant's `payTo`. The proxy does not hold a buyer wallet and does not run its own facilitator.
52
+
53
+ ## Run it
54
+
55
+ 1. On the core, with the account key (`sg_...`), set the Lightning Address that should be paid. Then mint a restricted key. The proxy refuses any key that does not start with `sgr_`.
56
+
57
+ Resources are `route:<name>` or `site`. A prefix of `route:` covers every route-scoped route in the example config. Omit `resource_prefix` if you also use `scope: site`.
58
+
59
+ ```bash
60
+ curl -s -X POST https://api.satsgate.org/v1/api-keys \
61
+ -H 'Content-Type: application/json' \
62
+ -H 'X-Api-Key: sg_...ACCOUNT_KEY...' \
63
+ -d '{"label":"shop-proxy","resource_prefix":"route:"}'
64
+ ```
65
+
66
+ 2. Generate one origin secret and give it to both the proxy and the origin. `openssl rand -hex 32` is a good value. Shorter than 16 characters refuses to start. Shorter than 32 logs a warning.
67
+
68
+ 3. Copy `satsgate-proxy.example.yaml` to `satsgate-proxy.yaml`. Set `upstream.base_url` to the origin (no path, no userinfo). Put the `sgr_` key and the origin secret in the environment, not in the file. Upstream credentials, if you inject any, are also environment variables and are never logged.
69
+
70
+ 4. Add an origin check from `snippets/` (FastAPI, Express, or nginx). Reject a missing or bad `X-Satsgate-Signature`. A client who can reach the origin directly must not skip the paywall. Stock Caddy does not verify HMAC; `snippets/Caddyfile` only shows a network gate in front of that check.
71
+
72
+ 5. Start the proxy and do not publish the origin port.
73
+
74
+ ```bash
75
+ export SATSGATE_API_KEY='sgr_...'
76
+ export SATSGATE_ORIGIN_SECRET="$(openssl rand -hex 32)"
77
+ docker compose -f proxy/docker-compose.yml up --build
78
+ ```
79
+
80
+ Buyers use the proxy's published port. `GET /healthz` is the proxy (`{"ok":true,"component":"satsgate-proxy","version":"0.14.1"}`). It is not forwarded.
81
+
82
+ Startup logs `key fp` and 12 hex characters. That is the start of SHA-256 of the API key. It is not a prefix of the key, and the key itself is not written to the log.
83
+
84
+ From a checkout: `pip install -e proxy`.
85
+
86
+ The image listens as uid 65532. Build it from the repo root: `docker build -f proxy/Dockerfile -t satsgate-proxy:0.14.1 .`
87
+
88
+ ## Receipt mode
89
+
90
+ Set `mode: receipt` and a `receipt` block. There is no `core` block and no `sgr_` key. The buyer pays `https://gate.satsgate.org/<site><path>`, then calls this proxy with `Satsgate-Receipt`. A 2xx from the origin commits one use. The origin still sees the HMAC in `X-Satsgate-Signature`.
91
+
92
+ ```yaml
93
+ mode: receipt
94
+ core:
95
+ base_url: https://api.satsgate.org
96
+ upstream:
97
+ base_url: https://origin.example
98
+ origin:
99
+ secret_env: SATSGATE_ORIGIN_SECRET
100
+ receipt:
101
+ site: my-shop
102
+ gate_base: https://gate.satsgate.org
103
+ store: /data/receipts.sqlite3
104
+ routes:
105
+ - path: /blog/post
106
+ price_sats: 21
107
+ ```
108
+
109
+ `core.base_url` is still required by the config parser. Receipt mode does not call it and does not read `SATSGATE_API_KEY`. `price_sats` is stored on the route and is not charged here. The buyer already paid the gate.
110
+
111
+ `proxy/snippets/fastapi_receipt.py` is the five-line SDK wrapper. `proxy/snippets/express_receipt.js` checks the same test vectors in `tests/fixtures/receipt_vectors.json` with Node's `crypto` module and no npm dependency.
112
+
113
+ ## What a buyer sees
114
+
115
+ An unpaid request gets **402** and:
116
+
117
+ ```
118
+ WWW-Authenticate: L402 macaroon="<standard base64>", invoice="<bolt11>"
119
+ ```
120
+
121
+ `macaroon` comes before `invoice`, which is what lnget and Alby `fetch402` parse. The JSON body has `amount_sats`, `payment_hash`, `invoice`, `invoice_expires_at`, `max_uses`, `access_seconds` (null when that side is unset), and a `hint` for the no-preimage path.
122
+
123
+ A paid retry is `Authorization: L402 <macaroon>:<64-hex-preimage>` (`LSAT` is accepted too). The proxy calls `POST /v1/paywall/verify` with `consume=true`.
124
+
125
+ `Authorization: L402 <macaroon>` with no preimage calls `GET /v1/paywall/status/{payment_hash}?consume=true`. That is the phone-wallet path: the wallet pays the invoice and does not return a preimage. While the invoice is unpaid the proxy answers **402** `payment_pending` with `Retry-After` and does **not** mint a second invoice. Pending does not consume a use.
126
+
127
+ A token for another route, a used-up bundle, or an expired pass becomes a **fresh 402**, not 401, so a standard client can pay again. The body includes `reason` (`token_used_up`, `token_expired`, `resource mismatch`, and the other core reject strings).
128
+
129
+ Core **429** (`buyer_rate_limited`, `too_many_open_challenges_for_buyer`, `rate_limited`, `too_many_open_challenges`) is passed through with `Retry-After`. A revoked key, a missing payee, an empty credit balance, or a resource outside the key prefix is **502** `paywall_unavailable` for the buyer. The core error code is logged on the proxy only.
130
+
131
+ ## Routes
132
+
133
+ First match wins. Anything that is not a free path or a route is **404**. A path that matches with the wrong method is **405** and does not mint an invoice. `OPTIONS` is not special: list it, or put the path in `free_paths`, if a browser must call it.
134
+
135
+ | `access` | Core policy | Meaning |
136
+ | --- | --- | --- |
137
+ | `per_request` | `max_uses: 1` | One payment, one request |
138
+ | `uses:N` | `max_uses: N` | A bundle of N requests (N is 1 to 100000) |
139
+ | `pass:<seconds>` | `access_seconds` | A time pass starting at settlement (1 to 604800 seconds) |
140
+
141
+ `scope: route` binds the macaroon to `route:<name>`. A token for one route does not open another. `scope: site` binds every site-scoped route to the resource `site`. Those routes must share `price_sats` and `access`, because one macaroon has one amount. Startup fails if they differ.
142
+
143
+ `free_paths` are forwarded with no challenge. Globs: `*` is one segment, a trailing `/**` is that prefix and anything under it (including the prefix). `path_regex` is a full match. A route has one of `path` or `path_regex`.
144
+
145
+ `description` is sent as the challenge memo, trimmed to 250 characters.
146
+
147
+ ## Price
148
+
149
+ A new account gets **500 free unlocks per UTC month**. After that, each unlock is **2 sats**, with a **10%** cap. The fee is taken once per payment, and only after the origin returns 2xx. `uses:N` and `pass:<seconds>` still bundle requests inside that one payment. `pricing.sats_per_credit` in an old config is ignored.
150
+
151
+ The Lightning payment goes to the merchant's payee when the invoice is paid, before the origin runs. A failed origin takes no fee and no use. The buyer retries the same macaroon or signature. Any remedy for that failed origin is between the buyer and the merchant. USDC test payments through this proxy do not use the free unlocks or the prepaid balance.
152
+
153
+ ## Buyer IP
154
+
155
+ When the proxy resolved a real IP, it sends `X-Satsgate-Buyer-Ip` on challenge create. `X-Forwarded-For` is used only when the TCP peer is in this proxy's `server.trusted_proxies`. Otherwise the peer is the buyer. A non-IP peer (the test client, for example) is omitted rather than sent.
156
+
157
+ **Hosted `https://api.satsgate.org` ignores that header unless the proxy's egress IP is listed in the core's `SATSGATE_TRUSTED_PROXIES`.** The core's Caddyfile also deletes `X-Satsgate-Buyer-Ip` on public requests, because Caddy is the trusted peer. Until an operator trusts the proxy and stops stripping the header, per-buyer limits do not apply. The merchant's per-client caps still do. Self-hosting the core: set `SATSGATE_TRUSTED_PROXIES` to the proxy egress IP and let the header through only from that address.
158
+
159
+ The core stores an HMAC of a truncated address (IPv4 /24, IPv6 /64), not the raw IP.
160
+
161
+ ## What the origin receives
162
+
163
+ When the payment is confirmed, the proxy forwards the original method, raw path, and raw query. The credit and the use are taken only after a 2xx. It does not follow redirects.
164
+
165
+ Headers added:
166
+
167
+ | Header | Value |
168
+ | --- | --- |
169
+ | `X-Satsgate-Signature` | `t=<unix>, v1=<hex hmac-sha256>` |
170
+ | `X-Satsgate-Payment-Hash` | lowercase payment hash |
171
+ | `X-Satsgate-Resource` | `route:<name>` or `site` |
172
+ | `X-Satsgate-Paid-Sats` | sats for this challenge |
173
+
174
+ The signed message is:
175
+
176
+ ```
177
+ {unix}|{METHOD}|{target}|{payment_hash}
178
+ ```
179
+
180
+ `target` is the raw path, then `?` and the raw query string when a query is present. Percent-encoding is kept and the query is not reordered. The method is uppercased. Default skew is 300 seconds (`origin.max_skew_seconds`).
181
+
182
+ Client `X-Satsgate-*` headers are stripped before this, so a buyer cannot forge the signature. `Authorization` is removed when the scheme is `L402` or `LSAT`. Other schemes, such as `Bearer`, are forwarded unless `inject_headers` replaces that name. Hop-by-hop headers are dropped. `Accept-Encoding` is set to `identity`.
183
+
184
+ `inject_headers` reads the value from `value_env`. The name cannot be hop-by-hop or `X-Satsgate-*`. The value is not logged. Startup fails if the variable is unset.
185
+
186
+ Responses drop `Server`, `Via`, `X-Powered-By`, `Location`, and `Content-Encoding`. A **3xx** from the origin becomes **502** `upstream_redirect` with no `Location`, so an internal host does not leak. The proxy does not follow the redirect.
187
+
188
+ The response is buffered up to `limits.max_response_bytes` (default 10 MiB, max 64 MiB). Over that, the buyer gets **502** `upstream_response_too_large` instead of a truncated 200. A request larger than `limits.max_request_bytes` (default 1 MiB, max 32 MiB) is **413** before any core call, so it does not mint an invoice or consume a use.
189
+
190
+ ## If the origin fails
191
+
192
+ The proxy confirms the payment first and calls the origin next. A credit is taken only when that response is 2xx. An origin **4xx** or **5xx** is passed through with the host headers removed, and nothing is debited. The same macaroon can be retried. If the origin times out, refuses the connection, redirects, or returns a body over the cap, the buyer gets a proxy error with `use_spent: false`. Do not put internal hostnames in an origin error body.
193
+
194
+ A route may set `x402: true`. Without `x402_mode`, that is test mode (Base Sepolia only). `x402_mode: live` is Base only, and core rejects it while `SATSGATE_X402_CDP` is off. `x402_mode` without `x402: true` refuses to start. The two networks are never in the same 402. Try on Base Sepolia with your agent first, then switch the site to live. See [USDC payments: Base network only](#usdc-payments-base-network-only). x402 also requires `server.public_base`, the `http://` or `https://` origin buyers pay (no path). The account needs a verified EVM payee on Base, the same challenge used by the hosted gate. The 402 then includes `PAYMENT-REQUIRED`. Test mode is labeled `testing: true`. `PAYMENT-SIGNATURE` is verified, the origin is called with `X-Satsgate-Paid-Usd-Atomic` and no `X-Satsgate-Paid-Sats`, and settle runs only after a 2xx. `PAYMENT-RESPONSE` carries `success`, `transaction`, `network`, `payer`, and `tx`. An origin 4xx or 5xx does not settle and does not debit. The buyer retries the same `PAYMENT-SIGNATURE`. Sending both `Authorization: L402` and `PAYMENT-SIGNATURE` is 400 `one_rail_only`. The proxy never calls the facilitator. The settle call uses the restricted `sgr_` key, and core records that key's id on the new ledger debit. The key string is not stored.
195
+
196
+ A retry of the same token takes another use when the bundle still has one. A `per_request` token is then `token_used_up`, and the next call is a new 402. Pending polls do not consume.
197
+
198
+ ## Known limitations
199
+
200
+ - Hosted core ignores `X-Satsgate-Buyer-Ip` unless the proxy egress IP is trusted and the edge does not strip the header. Per-buyer limits are then off. Per-client caps remain.
201
+ - The query string is signed only as part of `target`. An origin that checks the path and ignores the query is not checking what the buyer paid for.
202
+ - Responses are buffered up to the size cap. This is not an unbounded stream. WebSockets are not supported.
203
+ - There is no CORS middleware. A browser preflight needs `OPTIONS` on the route or a free path.
204
+ - `Accept-Encoding` is forced to `identity`. The proxy does not gzip.
205
+ - `Location` is always removed. An origin that redirects the buyer has to use a URL in the body, or not redirect.
206
+ - An origin failure does not burn the use. A retry after a lost 2xx can take another use if the first charge succeeded and the buyer did not see it. Credits are never refunded. There is no idempotency key.
207
+ - Aperture cannot verify satsgate macaroons. lnget and `fetch402` can, using the 402 header and `mac:preimage`. A phone wallet uses the macaroon-only poll.
208
+ - Replicas of the proxy do not need shared state. Uses, buyer limits, and challenge reuse live in the core database. The core's in-memory challenge rate limit is per core process.
209
+ - The macaroon-only path decodes the macaroon to learn the payment hash. A garbage token becomes a fresh 402.
210
+ - `scope: site` cannot mix prices. `scope: route` tokens do not unlock other routes.
211
+ - The restricted key's `resource_prefix` is a case-sensitive prefix of the resource id the proxy sends.
212
+
213
+ ## Mainnet check with a small payment
214
+
215
+ Use 1 to 21 sats on a test route. Pay from a different wallet than the payee.
216
+
217
+ - **lnget.** The 402 header parses, the macaroon is standard base64, the payment hash is in the L402 identifier, payment succeeds, and the retry is `L402 <macaroon>:<preimage>`. The origin sees the request and the signature verifies. A tampered path, a tampered payment hash, or a stale `t=` is rejected.
218
+ - **Alby `fetch402`.** The macaroon is treated as opaque. The retry includes the preimage. The macaroon base64 does not contain the substrings `L402` or `LSAT` (the core re-rolls those).
219
+ - **Phone wallet.** Pay the invoice without a preimage. Retry `Authorization: L402 <macaroon>` until `payment_pending` stops and the origin responds. `Retry-After` is present while pending, and a second invoice is not minted.
220
+ - A used `per_request` token gets a new **402**, not 401.
221
+ - The payee receives the sats when the invoice is paid. The account loses **one** credit on the first successful delivery only, after the origin returns 2xx. A second use of a bundle does not charge another credit. A failed origin takes no credit.
222
+ - Against hosted core, the proxy sends `X-Satsgate-Buyer-Ip` and it is ignored unless that egress IP was added to `SATSGATE_TRUSTED_PROXIES`. Record what you observed.
@@ -0,0 +1,199 @@
1
+ # satsgate-proxy
2
+
3
+ A reverse proxy a merchant runs beside an existing HTTP API. The buyer hits the proxy. The proxy sells the request through [satsgate](https://api.satsgate.org) and forwards only a paid request to the origin. The merchant does not write paywall code.
4
+
5
+ The proxy is version **0.14.1**. It works with core 0.20.3 or later and with gate 0.15.2 or later. Default `mode: paywall` talks to the satsgate core paywall (challenge, verify, status, charge, and x402 verify/settle). `mode: receipt` does not call core and does not use an API key. It checks `Satsgate-Receipt` with the site secret and forwards a successful check to the origin. The proxy does not sell prepaid balance and does not call the facilitator. Top up on the core with `POST /v1/topup/lightning` or `POST /v1/topup/usdc`. While the operator CDP switch is on, a USDC top-up is Base mainnet USDC only. The hosted gate is a separate program and only sells receipts. Buyer USDC on a proxied paywall route goes to the merchant's verified `payTo`. In receipt mode the buyer already paid the gate.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install satsgate-proxy
11
+ uvx --env-file .env satsgate-proxy --config satsgate-proxy.yaml
12
+ docker pull ghcr.io/mike-io-hash/satsgate-proxy:0.14.1
13
+ ```
14
+
15
+ From a checkout: `pip install -e proxy`.
16
+
17
+ ## USDC payments: Base network only
18
+
19
+ USDC payments use Base only. Ethereum mainnet, Polygon, Solana, Arbitrum, and any other chain are not accepted.
20
+
21
+ | Network | Network id | Circle USDC contract | Status |
22
+ | --- | --- | --- | --- |
23
+ | Base Sepolia (testnet) | `eip155:84532` | [`0x036CbD53842c5426634e7929541eC2318f3dCF7e`](https://sepolia.basescan.org/token/0x036CbD53842c5426634e7929541eC2318f3dCF7e) | Testing. `x402: true` without `x402_mode`, or `x402_mode: test`, offers only this USDC. It is not a network for real buyers. |
24
+ | Base | `eip155:8453` | [`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`](https://basescan.org/token/0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913) | `x402_mode: live`. Available only when the operator sets `SATSGATE_X402_CDP=1` and both CDP credentials. The 402 offers only this USDC. |
25
+
26
+ Merchants: `payTo` must be an address you control on Base. Prove it with the same EVM challenge the hosted gate uses. The USDC is paid to that address on the one network the route is in. Try on Base Sepolia with your agent first, then switch the site to live. Buyers: USDC sent on another network will not be accepted. A balance on Ethereum, Polygon, Solana, or Arbitrum does not pay this proxy.
27
+
28
+ Satsgate never custodies, receives, forwards, or refunds buyer funds. The USDC moves from the buyer to the merchant's `payTo`. The proxy does not hold a buyer wallet and does not run its own facilitator.
29
+
30
+ ## Run it
31
+
32
+ 1. On the core, with the account key (`sg_...`), set the Lightning Address that should be paid. Then mint a restricted key. The proxy refuses any key that does not start with `sgr_`.
33
+
34
+ Resources are `route:<name>` or `site`. A prefix of `route:` covers every route-scoped route in the example config. Omit `resource_prefix` if you also use `scope: site`.
35
+
36
+ ```bash
37
+ curl -s -X POST https://api.satsgate.org/v1/api-keys \
38
+ -H 'Content-Type: application/json' \
39
+ -H 'X-Api-Key: sg_...ACCOUNT_KEY...' \
40
+ -d '{"label":"shop-proxy","resource_prefix":"route:"}'
41
+ ```
42
+
43
+ 2. Generate one origin secret and give it to both the proxy and the origin. `openssl rand -hex 32` is a good value. Shorter than 16 characters refuses to start. Shorter than 32 logs a warning.
44
+
45
+ 3. Copy `satsgate-proxy.example.yaml` to `satsgate-proxy.yaml`. Set `upstream.base_url` to the origin (no path, no userinfo). Put the `sgr_` key and the origin secret in the environment, not in the file. Upstream credentials, if you inject any, are also environment variables and are never logged.
46
+
47
+ 4. Add an origin check from `snippets/` (FastAPI, Express, or nginx). Reject a missing or bad `X-Satsgate-Signature`. A client who can reach the origin directly must not skip the paywall. Stock Caddy does not verify HMAC; `snippets/Caddyfile` only shows a network gate in front of that check.
48
+
49
+ 5. Start the proxy and do not publish the origin port.
50
+
51
+ ```bash
52
+ export SATSGATE_API_KEY='sgr_...'
53
+ export SATSGATE_ORIGIN_SECRET="$(openssl rand -hex 32)"
54
+ docker compose -f proxy/docker-compose.yml up --build
55
+ ```
56
+
57
+ Buyers use the proxy's published port. `GET /healthz` is the proxy (`{"ok":true,"component":"satsgate-proxy","version":"0.14.1"}`). It is not forwarded.
58
+
59
+ Startup logs `key fp` and 12 hex characters. That is the start of SHA-256 of the API key. It is not a prefix of the key, and the key itself is not written to the log.
60
+
61
+ From a checkout: `pip install -e proxy`.
62
+
63
+ The image listens as uid 65532. Build it from the repo root: `docker build -f proxy/Dockerfile -t satsgate-proxy:0.14.1 .`
64
+
65
+ ## Receipt mode
66
+
67
+ Set `mode: receipt` and a `receipt` block. There is no `core` block and no `sgr_` key. The buyer pays `https://gate.satsgate.org/<site><path>`, then calls this proxy with `Satsgate-Receipt`. A 2xx from the origin commits one use. The origin still sees the HMAC in `X-Satsgate-Signature`.
68
+
69
+ ```yaml
70
+ mode: receipt
71
+ core:
72
+ base_url: https://api.satsgate.org
73
+ upstream:
74
+ base_url: https://origin.example
75
+ origin:
76
+ secret_env: SATSGATE_ORIGIN_SECRET
77
+ receipt:
78
+ site: my-shop
79
+ gate_base: https://gate.satsgate.org
80
+ store: /data/receipts.sqlite3
81
+ routes:
82
+ - path: /blog/post
83
+ price_sats: 21
84
+ ```
85
+
86
+ `core.base_url` is still required by the config parser. Receipt mode does not call it and does not read `SATSGATE_API_KEY`. `price_sats` is stored on the route and is not charged here. The buyer already paid the gate.
87
+
88
+ `proxy/snippets/fastapi_receipt.py` is the five-line SDK wrapper. `proxy/snippets/express_receipt.js` checks the same test vectors in `tests/fixtures/receipt_vectors.json` with Node's `crypto` module and no npm dependency.
89
+
90
+ ## What a buyer sees
91
+
92
+ An unpaid request gets **402** and:
93
+
94
+ ```
95
+ WWW-Authenticate: L402 macaroon="<standard base64>", invoice="<bolt11>"
96
+ ```
97
+
98
+ `macaroon` comes before `invoice`, which is what lnget and Alby `fetch402` parse. The JSON body has `amount_sats`, `payment_hash`, `invoice`, `invoice_expires_at`, `max_uses`, `access_seconds` (null when that side is unset), and a `hint` for the no-preimage path.
99
+
100
+ A paid retry is `Authorization: L402 <macaroon>:<64-hex-preimage>` (`LSAT` is accepted too). The proxy calls `POST /v1/paywall/verify` with `consume=true`.
101
+
102
+ `Authorization: L402 <macaroon>` with no preimage calls `GET /v1/paywall/status/{payment_hash}?consume=true`. That is the phone-wallet path: the wallet pays the invoice and does not return a preimage. While the invoice is unpaid the proxy answers **402** `payment_pending` with `Retry-After` and does **not** mint a second invoice. Pending does not consume a use.
103
+
104
+ A token for another route, a used-up bundle, or an expired pass becomes a **fresh 402**, not 401, so a standard client can pay again. The body includes `reason` (`token_used_up`, `token_expired`, `resource mismatch`, and the other core reject strings).
105
+
106
+ Core **429** (`buyer_rate_limited`, `too_many_open_challenges_for_buyer`, `rate_limited`, `too_many_open_challenges`) is passed through with `Retry-After`. A revoked key, a missing payee, an empty credit balance, or a resource outside the key prefix is **502** `paywall_unavailable` for the buyer. The core error code is logged on the proxy only.
107
+
108
+ ## Routes
109
+
110
+ First match wins. Anything that is not a free path or a route is **404**. A path that matches with the wrong method is **405** and does not mint an invoice. `OPTIONS` is not special: list it, or put the path in `free_paths`, if a browser must call it.
111
+
112
+ | `access` | Core policy | Meaning |
113
+ | --- | --- | --- |
114
+ | `per_request` | `max_uses: 1` | One payment, one request |
115
+ | `uses:N` | `max_uses: N` | A bundle of N requests (N is 1 to 100000) |
116
+ | `pass:<seconds>` | `access_seconds` | A time pass starting at settlement (1 to 604800 seconds) |
117
+
118
+ `scope: route` binds the macaroon to `route:<name>`. A token for one route does not open another. `scope: site` binds every site-scoped route to the resource `site`. Those routes must share `price_sats` and `access`, because one macaroon has one amount. Startup fails if they differ.
119
+
120
+ `free_paths` are forwarded with no challenge. Globs: `*` is one segment, a trailing `/**` is that prefix and anything under it (including the prefix). `path_regex` is a full match. A route has one of `path` or `path_regex`.
121
+
122
+ `description` is sent as the challenge memo, trimmed to 250 characters.
123
+
124
+ ## Price
125
+
126
+ A new account gets **500 free unlocks per UTC month**. After that, each unlock is **2 sats**, with a **10%** cap. The fee is taken once per payment, and only after the origin returns 2xx. `uses:N` and `pass:<seconds>` still bundle requests inside that one payment. `pricing.sats_per_credit` in an old config is ignored.
127
+
128
+ The Lightning payment goes to the merchant's payee when the invoice is paid, before the origin runs. A failed origin takes no fee and no use. The buyer retries the same macaroon or signature. Any remedy for that failed origin is between the buyer and the merchant. USDC test payments through this proxy do not use the free unlocks or the prepaid balance.
129
+
130
+ ## Buyer IP
131
+
132
+ When the proxy resolved a real IP, it sends `X-Satsgate-Buyer-Ip` on challenge create. `X-Forwarded-For` is used only when the TCP peer is in this proxy's `server.trusted_proxies`. Otherwise the peer is the buyer. A non-IP peer (the test client, for example) is omitted rather than sent.
133
+
134
+ **Hosted `https://api.satsgate.org` ignores that header unless the proxy's egress IP is listed in the core's `SATSGATE_TRUSTED_PROXIES`.** The core's Caddyfile also deletes `X-Satsgate-Buyer-Ip` on public requests, because Caddy is the trusted peer. Until an operator trusts the proxy and stops stripping the header, per-buyer limits do not apply. The merchant's per-client caps still do. Self-hosting the core: set `SATSGATE_TRUSTED_PROXIES` to the proxy egress IP and let the header through only from that address.
135
+
136
+ The core stores an HMAC of a truncated address (IPv4 /24, IPv6 /64), not the raw IP.
137
+
138
+ ## What the origin receives
139
+
140
+ When the payment is confirmed, the proxy forwards the original method, raw path, and raw query. The credit and the use are taken only after a 2xx. It does not follow redirects.
141
+
142
+ Headers added:
143
+
144
+ | Header | Value |
145
+ | --- | --- |
146
+ | `X-Satsgate-Signature` | `t=<unix>, v1=<hex hmac-sha256>` |
147
+ | `X-Satsgate-Payment-Hash` | lowercase payment hash |
148
+ | `X-Satsgate-Resource` | `route:<name>` or `site` |
149
+ | `X-Satsgate-Paid-Sats` | sats for this challenge |
150
+
151
+ The signed message is:
152
+
153
+ ```
154
+ {unix}|{METHOD}|{target}|{payment_hash}
155
+ ```
156
+
157
+ `target` is the raw path, then `?` and the raw query string when a query is present. Percent-encoding is kept and the query is not reordered. The method is uppercased. Default skew is 300 seconds (`origin.max_skew_seconds`).
158
+
159
+ Client `X-Satsgate-*` headers are stripped before this, so a buyer cannot forge the signature. `Authorization` is removed when the scheme is `L402` or `LSAT`. Other schemes, such as `Bearer`, are forwarded unless `inject_headers` replaces that name. Hop-by-hop headers are dropped. `Accept-Encoding` is set to `identity`.
160
+
161
+ `inject_headers` reads the value from `value_env`. The name cannot be hop-by-hop or `X-Satsgate-*`. The value is not logged. Startup fails if the variable is unset.
162
+
163
+ Responses drop `Server`, `Via`, `X-Powered-By`, `Location`, and `Content-Encoding`. A **3xx** from the origin becomes **502** `upstream_redirect` with no `Location`, so an internal host does not leak. The proxy does not follow the redirect.
164
+
165
+ The response is buffered up to `limits.max_response_bytes` (default 10 MiB, max 64 MiB). Over that, the buyer gets **502** `upstream_response_too_large` instead of a truncated 200. A request larger than `limits.max_request_bytes` (default 1 MiB, max 32 MiB) is **413** before any core call, so it does not mint an invoice or consume a use.
166
+
167
+ ## If the origin fails
168
+
169
+ The proxy confirms the payment first and calls the origin next. A credit is taken only when that response is 2xx. An origin **4xx** or **5xx** is passed through with the host headers removed, and nothing is debited. The same macaroon can be retried. If the origin times out, refuses the connection, redirects, or returns a body over the cap, the buyer gets a proxy error with `use_spent: false`. Do not put internal hostnames in an origin error body.
170
+
171
+ A route may set `x402: true`. Without `x402_mode`, that is test mode (Base Sepolia only). `x402_mode: live` is Base only, and core rejects it while `SATSGATE_X402_CDP` is off. `x402_mode` without `x402: true` refuses to start. The two networks are never in the same 402. Try on Base Sepolia with your agent first, then switch the site to live. See [USDC payments: Base network only](#usdc-payments-base-network-only). x402 also requires `server.public_base`, the `http://` or `https://` origin buyers pay (no path). The account needs a verified EVM payee on Base, the same challenge used by the hosted gate. The 402 then includes `PAYMENT-REQUIRED`. Test mode is labeled `testing: true`. `PAYMENT-SIGNATURE` is verified, the origin is called with `X-Satsgate-Paid-Usd-Atomic` and no `X-Satsgate-Paid-Sats`, and settle runs only after a 2xx. `PAYMENT-RESPONSE` carries `success`, `transaction`, `network`, `payer`, and `tx`. An origin 4xx or 5xx does not settle and does not debit. The buyer retries the same `PAYMENT-SIGNATURE`. Sending both `Authorization: L402` and `PAYMENT-SIGNATURE` is 400 `one_rail_only`. The proxy never calls the facilitator. The settle call uses the restricted `sgr_` key, and core records that key's id on the new ledger debit. The key string is not stored.
172
+
173
+ A retry of the same token takes another use when the bundle still has one. A `per_request` token is then `token_used_up`, and the next call is a new 402. Pending polls do not consume.
174
+
175
+ ## Known limitations
176
+
177
+ - Hosted core ignores `X-Satsgate-Buyer-Ip` unless the proxy egress IP is trusted and the edge does not strip the header. Per-buyer limits are then off. Per-client caps remain.
178
+ - The query string is signed only as part of `target`. An origin that checks the path and ignores the query is not checking what the buyer paid for.
179
+ - Responses are buffered up to the size cap. This is not an unbounded stream. WebSockets are not supported.
180
+ - There is no CORS middleware. A browser preflight needs `OPTIONS` on the route or a free path.
181
+ - `Accept-Encoding` is forced to `identity`. The proxy does not gzip.
182
+ - `Location` is always removed. An origin that redirects the buyer has to use a URL in the body, or not redirect.
183
+ - An origin failure does not burn the use. A retry after a lost 2xx can take another use if the first charge succeeded and the buyer did not see it. Credits are never refunded. There is no idempotency key.
184
+ - Aperture cannot verify satsgate macaroons. lnget and `fetch402` can, using the 402 header and `mac:preimage`. A phone wallet uses the macaroon-only poll.
185
+ - Replicas of the proxy do not need shared state. Uses, buyer limits, and challenge reuse live in the core database. The core's in-memory challenge rate limit is per core process.
186
+ - The macaroon-only path decodes the macaroon to learn the payment hash. A garbage token becomes a fresh 402.
187
+ - `scope: site` cannot mix prices. `scope: route` tokens do not unlock other routes.
188
+ - The restricted key's `resource_prefix` is a case-sensitive prefix of the resource id the proxy sends.
189
+
190
+ ## Mainnet check with a small payment
191
+
192
+ Use 1 to 21 sats on a test route. Pay from a different wallet than the payee.
193
+
194
+ - **lnget.** The 402 header parses, the macaroon is standard base64, the payment hash is in the L402 identifier, payment succeeds, and the retry is `L402 <macaroon>:<preimage>`. The origin sees the request and the signature verifies. A tampered path, a tampered payment hash, or a stale `t=` is rejected.
195
+ - **Alby `fetch402`.** The macaroon is treated as opaque. The retry includes the preimage. The macaroon base64 does not contain the substrings `L402` or `LSAT` (the core re-rolls those).
196
+ - **Phone wallet.** Pay the invoice without a preimage. Retry `Authorization: L402 <macaroon>` until `payment_pending` stops and the origin responds. `Retry-After` is present while pending, and a second invoice is not minted.
197
+ - A used `per_request` token gets a new **402**, not 401.
198
+ - The payee receives the sats when the invoice is paid. The account loses **one** credit on the first successful delivery only, after the origin returns 2xx. A second use of a bundle does not charge another credit. A failed origin takes no credit.
199
+ - Against hosted core, the proxy sends `X-Satsgate-Buyer-Ip` and it is ignored unless that egress IP was added to `SATSGATE_TRUSTED_PROXIES`. Record what you observed.