faucet-server 0.0.7 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,31 +4,26 @@ A configurable EVM faucet server that dispenses testnet/devnet tokens with Proso
4
4
 
5
5
  ## Quick Start
6
6
 
7
- Run a local faucet server with a single command:
7
+ Run a local faucet server against your local chain, without captcha:
8
8
 
9
9
  ```bash
10
- npx faucet-server serve --port 3000
10
+ npx faucet-server --port 3000 --no-captcha
11
11
  ```
12
12
 
13
13
  Or install globally:
14
14
 
15
15
  ```bash
16
16
  npm install -g faucet-server
17
- serve --port 3000
17
+ faucet --port 3000 --no-captcha
18
18
  ```
19
19
 
20
- For local development without internet (disables captcha verification):
21
-
22
- ```bash
23
- npx faucet-server serve --port 3000 --no-captcha
24
- ```
20
+ The published package ships a prebuilt frontend, and a Prosopo **site key** can only be inlined at build time, so the captcha protected mode needs your own build. See [Deploy your own faucet](#deploy-your-own-faucet).
25
21
 
26
22
  **Configure via environment variables:**
27
23
 
28
24
  ```bash
29
- # Required: Prosopo captcha keys (get from https://prosopo.io/)
25
+ # Required unless --no-captcha: Prosopo secret key (get from https://prosopo.io/)
30
26
  export PROSOPO_SITE_PRIVATE_KEY=your_secret_key
31
- export VITE_PROSOPO_SITE_KEY=your_site_key
32
27
 
33
28
  # Required: Wallet with funds to dispense
34
29
  export FAUCET_PRIVATE_KEY=0x...your_wallet_private_key
@@ -36,18 +31,23 @@ export FAUCET_PRIVATE_KEY=0x...your_wallet_private_key
36
31
  # Required: Configure chains (format: amount_in_wei:rpc_endpoint)
37
32
  export CHAIN_31337=10000000000000000:http://localhost:8545
38
33
  export CHAIN_11155111=10000000000000000:https://eth-sepolia.g.alchemy.com/v2/KEY
34
+
35
+ # Recommended: persist rate limits across restarts (default is :memory:)
36
+ export DB=./faucet.db
39
37
  ```
40
38
 
41
39
  Then access the faucet at: `http://localhost:3000?chainId=31337&address=0x...`
42
40
 
43
41
  ## Features
44
42
 
45
- - 🔗 **Multi-chain support** — Configure any EVM chain via environment variables
46
- - 🤖 **Bot protection** — Integrated [Prosopo](https://prosopo.io/) captcha verification
47
- - 🚀 **Multiple deployment targets** — Cloudflare Workers or Node.js
48
- - ⚡ **Modern stack** — Svelte frontend, Hono API server, Viem for transactions
49
- - 📦 **Monorepo architecture** — Clean separation of frontend, server, and platform concerns
50
- - 🔧 **Development mode** — Disable captcha for localhost testing without internet
43
+ - 🔗 **Multi-chain support**: Configure any EVM chain via environment variables
44
+ - 🤖 **Bot protection**: Integrated [Prosopo](https://prosopo.io/) captcha verification, fail closed, single use tokens
45
+ - 🚰 **Abuse control**: Per address and per ip cooldowns, plus a recipient balance ceiling
46
+ - 🔒 **Secret rpc**: The rpc endpoint never leaves the server, clients follow their transaction through the api
47
+ - 🚀 **Multiple deployment targets**: Cloudflare Workers or Node.js
48
+ - ⚡ **Modern stack**: Svelte frontend, Hono API server, Viem for transactions
49
+ - 📦 **Monorepo architecture**: Clean separation of frontend, server, and platform concerns
50
+ - 🔧 **Development mode**: Disable captcha for localhost testing without internet
51
51
 
52
52
  ---
53
53
 
@@ -80,23 +80,28 @@ pnpm install
80
80
  The faucet requires configuration via environment variables. Copy the example files and fill in your values:
81
81
 
82
82
  **Frontend** ([`packages/frontend/.env`](packages/frontend/.env)):
83
+
83
84
  ```bash
84
85
  VITE_PROSOPO_SITE_KEY=your_prosopo_site_key
85
86
  ```
86
87
 
88
+ This one is inlined into the bundle at **build time**, not read at runtime. `pnpm build` refuses to produce a bundle without it (build with `ALLOW_NO_CAPTCHA=true` if the server runs with `DISABLE_CAPTCHA=true`). Remember to allowlist the domain you deploy to in the Prosopo portal for that site key.
89
+
87
90
  **Server** (choose your platform):
88
91
 
89
92
  For Node.js ([`platforms/nodejs/.env`](platforms/nodejs/.env)):
93
+
90
94
  ```bash
91
95
  PROSOPO_SITE_PRIVATE_KEY=your_prosopo_secret_key
92
96
  FAUCET_PRIVATE_KEY=0x...your_wallet_private_key
93
97
  CHAIN_31337=10000000000000000:http://localhost:8545
94
-
95
- # Optional: Disable captcha for localhost development (or use --no-captcha flag)
96
- DISABLE_CAPTCHA=true
98
+ DB=./faucet.db
97
99
  ```
98
100
 
101
+ For localhost development, pass `--no-captcha` on the command line (`pnpm nodejs:dev` already does) rather than putting `DISABLE_CAPTCHA=true` in a committed `.env`, so it can never follow you into a deployment.
102
+
99
103
  For Cloudflare Workers ([`platforms/cf-worker/.dev.vars`](platforms/cf-worker/.dev.vars.default)):
104
+
100
105
  ```bash
101
106
  PROSOPO_SITE_PRIVATE_KEY=your_prosopo_secret_key
102
107
  FAUCET_PRIVATE_KEY=0x...your_wallet_private_key
@@ -106,6 +111,26 @@ CHAIN_31337=10000000000000000:http://localhost:8545
106
111
  DISABLE_CAPTCHA=true
107
112
  ```
108
113
 
114
+ ##### All server variables
115
+
116
+ | Variable | Required | Default | Description |
117
+ |----------|----------|---------|-------------|
118
+ | `FAUCET_PRIVATE_KEY` | yes | | Wallet dispensing the funds |
119
+ | `PROSOPO_SITE_PRIVATE_KEY` | yes (unless captcha disabled) | | Prosopo secret key |
120
+ | `CHAIN_<CHAIN_ID>` | yes, at least one | | `<amount_in_wei>:<rpc_endpoint>` |
121
+ | `DB` (node only) | no | `:memory:` | libsql url or file path. In memory means rate limits reset on restart |
122
+ | `DISABLE_CAPTCHA` | no | `false` | `true` skips captcha entirely. Meant for localhost, but nothing enforces that: the server warns and serves anyway |
123
+ | `CAPTCHA_FAIL_OPEN` | no | `false` | `true` keeps dispensing when Prosopo is unreachable |
124
+ | `CORS_ORIGINS` | no | `https://jolly-roger.eth.limo` | Comma separated origins allowed to call the api cross-origin, or `*` |
125
+ | `CLAIM_COOLDOWN_SECONDS` | no | `86400` | Cooldown between two claims for the same address on the same chain |
126
+ | `IP_COOLDOWN_SECONDS` | no | same as above | Cooldown for the same ip |
127
+ | `MAX_RECIPIENT_BALANCE` | no | 10x the chain amount | Refuse addresses already holding this much (wei). `0` disables |
128
+ | `ENABLE_ARBITRARY_CALLS` | no | `off` | `off`, `allowlist` or `unrestricted`. See [Arbitrary calls](#arbitrary-calls) |
129
+ | `CALL_ALLOWLIST_<CHAIN_ID>` | in `allowlist` mode | | `<contract>:<selector>,<selector>;<contract>:...` |
130
+ | `MAX_CALL_TOTAL_SPEND_<CHAIN_ID>` | no | amount + 21000 * gas price | Ceiling in wei on `value + gas` for one call |
131
+ | `MAX_CALL_VALUE_<CHAIN_ID>` | no | the chain amount | Ceiling in wei on the value attached to a call |
132
+ | `MAX_CALL_GAS` | no | `2000000` | Absolute gas limit for one call |
133
+
109
134
  #### Chain Configuration
110
135
 
111
136
  Chains are configured using the `CHAIN_<CHAIN_ID>` environment variable format:
@@ -115,6 +140,7 @@ CHAIN_<CHAIN_ID>=<amount_in_wei>:<rpc_endpoint>
115
140
  ```
116
141
 
117
142
  **Examples:**
143
+
118
144
  ```bash
119
145
  # Local development (anvil/hardhat)
120
146
  CHAIN_31337=10000000000000000:http://localhost:8545
@@ -126,6 +152,54 @@ CHAIN_11155111=10000000000000000:https://eth-sepolia.g.alchemy.com/v2/YOUR_KEY
126
152
  CHAIN_421614=10000000000000000:https://sepolia-rollup.arbitrum.io/rpc
127
153
  ```
128
154
 
155
+ The rpc endpoint is treated as a **secret**: it is never returned to clients, so it is safe to embed a provider api key in it. Set it with `pnpm exec wrangler secret put` rather than as a plain var.
156
+
157
+ #### Arbitrary calls
158
+
159
+ Off by default. When enabled, the faucet can execute a **call you choose** and pay for it, instead of only sending funds. The use case is emulating a credit card purchase provider, which executes a call on the buyer's behalf against an allow-list.
160
+
161
+ ```bash
162
+ # a flag rather than an env var, so it cannot follow you into a deployment
163
+ npx faucet-server --port 3000 --no-captcha --arbitrary-calls unrestricted
164
+ ```
165
+
166
+ That combination binds `127.0.0.1` instead of every interface, because an unrestricted executor with no captcha has nothing in front of it and must not be reachable from the network. Pass `--host 0.0.0.0` if you really mean to expose it.
167
+
168
+ ```bash
169
+ # on Cloudflare Workers, which has no command line
170
+ ENABLE_ARBITRARY_CALLS=allowlist
171
+ CALL_ALLOWLIST_11155111=0xYourContract:0x1249c58b
172
+ ```
173
+
174
+ **Read this before enabling it.** Every call executes with `msg.sender` equal to the faucet address, so whoever passes the captcha borrows that address's authority. Not just its ERC20 balance: also every approval it granted, every role it holds, every contract it owns, and anything it is granted *in the future*. Use a key that does nothing else, ever.
175
+
176
+ | Mode | Meaning |
177
+ |------|---------|
178
+ | `off` | Default. `/api/execute` answers `404` and nothing else changes |
179
+ | `allowlist` | Only `(contract, selector)` pairs from `CALL_ALLOWLIST_<CHAIN_ID>` are executed |
180
+ | `unrestricted` | Any contract, any calldata. The faucet key's whole authority is on offer |
181
+
182
+ The allow-list is `(contract, selector)` pairs on purpose. Allow-listing a whole contract would make `transfer` reachable on a token, so a bare contract with no selector is refused at startup. For the same reason **the faucet address should hold no ERC20 in either mode**: dispense tokens by allow-listing a `mint` selector on a contract you control, not by letting the faucet hold a balance.
183
+
184
+ Spending is bounded per call by `MAX_CALL_TOTAL_SPEND_<CHAIN_ID>`, which defaults to what the equivalent claim would have cost, `amount + 21000 * gas price`. So turning this on does not change the faucet's worst case spend per request. Since value and gas share that budget, the value a call can carry is `amount - (gas beyond 21000) * gas price`: a plain transfer is unaffected by congestion, while a 200k gas call gets less room as gas gets expensive, and is refused outright when it no longer fits. Raise `MAX_CALL_TOTAL_SPEND_<CHAIN_ID>` if your calls need both value and a lot of gas.
185
+
186
+ Rate limiting is weaker here than on `/api/claim`. The `to` of a call is a shared contract, so it cannot be a cooldown key, which leaves **only the ip** (a self-declared beneficiary was considered and rejected: nothing binds it to the call, so it enforces nothing). A request whose client ip cannot be determined is refused with `503`, so this feature needs a proxy that forwards the ip. With `--no-captcha` the ip cooldown is skipped entirely, since every local account shares one ip.
187
+
188
+ The full design, including the threat model and what was rejected, is in [`docs/specs/arbitrary-calls.md`](docs/specs/arbitrary-calls.md).
189
+
190
+ #### Abuse protection
191
+
192
+ Every claim goes through, in order:
193
+
194
+ 1. **Captcha token replay check**: each Procaptcha token can only be spent once.
195
+ 2. **Captcha verification**: Prosopo answers `verified: true, score: 0` when *their* provider times out, which is a fail open. The server treats that as "unavailable" and refuses to dispense unless `CAPTCHA_FAIL_OPEN=true`. Prosopo Premium customers also get a real `score` of 0 for genuine humans, so those accounts should set `CAPTCHA_FAIL_OPEN=true` and lean on the rate limiter.
196
+ 3. **Recipient balance ceiling**: addresses already holding `MAX_RECIPIENT_BALANCE` are turned away.
197
+ 4. **Rate limit**: one claim per address and per ip per `CLAIM_COOLDOWN_SECONDS`, reserved atomically before the transaction is sent and released if it fails.
198
+ 5. **Faucet balance preflight**: an empty faucet answers `503` with a clear message instead of a raw rpc error.
199
+ 6. **Per chain send lock**: concurrent claims cannot pick the same nonce. The lock is time boxed (30s) so a crashed request cannot wedge the faucet.
200
+
201
+ Steps 1, 4 and 6 need the database, so a faucet without a real `DB` (node) or D1 binding (workers) will not start dispensing.
202
+
129
203
  ### Running Locally
130
204
 
131
205
  Start the full development environment using Zellij:
@@ -162,29 +236,151 @@ pnpm build:server
162
236
 
163
237
  ### Deployment
164
238
 
165
- #### Cloudflare Workers
239
+ See [Deploy your own faucet](#deploy-your-own-faucet).
166
240
 
167
- 1. Configure your [`wrangler.toml`](platforms/cf-worker/wrangler.toml)
168
- 2. Set secrets in Cloudflare dashboard or via CLI:
169
- ```bash
170
- wrangler secret put PROSOPO_SITE_PRIVATE_KEY
171
- wrangler secret put FAUCET_PRIVATE_KEY
172
- ```
173
- 3. Deploy:
174
- ```bash
175
- pnpm deploy:cf
176
- ```
241
+ ---
177
242
 
178
- #### Node.js
243
+ ## Deploy your own faucet
179
244
 
180
- Build and run the Node.js server:
245
+ This walks through a public deployment from nothing, on Cloudflare Workers or on any Node.js host. Budget about 20 minutes.
246
+
247
+ ### What you need first
248
+
249
+ | Thing | Why | Where |
250
+ |-------|-----|-------|
251
+ | A dedicated wallet | It dispenses the funds, and its private key lives in your deployment. Never reuse a wallet that holds anything you care about | any wallet, or `cast wallet new` |
252
+ | Testnet funds | The faucet can only give away what it holds | a public faucet for the chain, or your own funds |
253
+ | A Prosopo account | Bot protection. You need both the **site key** (public, goes in the frontend) and the **secret key** (server side) | [portal.prosopo.io](https://portal.prosopo.io) |
254
+ | An rpc endpoint per chain | To send transactions and read balances | any provider, or a public endpoint |
255
+ | A Cloudflare account | Only for the Workers path | [dash.cloudflare.com](https://dash.cloudflare.com) |
256
+
257
+ ### 1. Get the code
181
258
 
182
259
  ```bash
183
- pnpm build
260
+ git clone https://github.com/wighawag/faucet.git
261
+ cd faucet
262
+ pnpm install
263
+ ```
264
+
265
+ ### 2. Prepare the wallet
266
+
267
+ ```bash
268
+ cast wallet new # or any tool you trust
269
+ ```
270
+
271
+ Keep the private key for step 5 and send the address the funds you want to give away. The faucet stops dispensing (and answers `503`) as soon as its balance can no longer cover one claim plus gas, so top it up before it runs dry.
272
+
273
+ ### 3. Prepare the captcha keys
274
+
275
+ In the Prosopo portal, create a site and **allowlist the domain you will deploy to**. A site key that does not list your domain renders a widget that never returns a token, and nobody can claim. Note both keys down.
276
+
277
+ ### 4. Decide what each chain gives away
278
+
279
+ One variable per chain, `CHAIN_<CHAIN_ID>=<amount_in_wei>:<rpc_endpoint>`. For example 0.01 ETH on Sepolia:
280
+
281
+ ```
282
+ CHAIN_11155111=10000000000000000:https://eth-sepolia.example.com/v2/YOUR_KEY
283
+ ```
284
+
285
+ The rpc endpoint never leaves the server, so an api key in that url is safe. Treat the whole variable as a secret anyway.
286
+
287
+ ### 5a. Deploy to Cloudflare Workers
288
+
289
+ Log in to Cloudflare first, everything below talks to your account:
290
+
291
+ ```bash
292
+ pnpm --filter faucet-server-cf-worker exec wrangler login
293
+ ```
294
+
295
+ The faucet needs a D1 database for its rate limits. Create it once:
296
+
297
+ ```bash
298
+ pnpm cf-worker:create-db
299
+ ```
300
+
301
+ Paste the id it prints into [`wrangler.toml`](platforms/cf-worker/wrangler.toml), under `env.production.d1_databases[0].database_id`, then create the tables in it:
302
+
303
+ ```bash
304
+ pnpm cf-worker:init-db
305
+ ```
306
+
307
+ Set the secrets. They are environment scoped, and every script here deploys with `-e production`, so the `--env production` flag is not optional. Wrangler is a devDependency, so use `pnpm exec` from inside the `cf-worker` package to run it:
308
+
309
+ ```bash
310
+ cd platforms/cf-worker
311
+ pnpm exec wrangler secret put PROSOPO_SITE_PRIVATE_KEY --env production
312
+ pnpm exec wrangler secret put FAUCET_PRIVATE_KEY --env production
313
+ pnpm exec wrangler secret put CHAIN_11155111 --env production # 10000000000000000:https://...
314
+ cd ../..
315
+ ```
316
+
317
+ Point `CORS_ORIGINS` at the site that will open the faucet popup, in `[env.production.vars]` of `wrangler.toml`. Leave it out entirely if only the faucet page itself calls the api.
318
+
319
+ Build and deploy. The captcha site key is inlined into the bundle at build time, so it has to be present in either `packages/frontend/.env.local` or as `VITE_PROSOPO_SITE_KEY` in the environment. The `deploy:cf` script runs the full build first, so there is no way to deploy without the site key being set:
320
+
321
+ ```bash
322
+ pnpm deploy:cf
323
+ ```
324
+
325
+ ### 5b. Deploy to Node.js
326
+
327
+ ```bash
328
+ VITE_PROSOPO_SITE_KEY=your_site_key pnpm build
184
329
  cd platforms/nodejs
185
- node dist/cli.js
330
+
331
+ DB=./faucet.db \
332
+ PROSOPO_SITE_PRIVATE_KEY=your_secret_key \
333
+ FAUCET_PRIVATE_KEY=0x... \
334
+ CHAIN_11155111=10000000000000000:https://... \
335
+ CORS_ORIGINS=https://your-dapp.example.com \
336
+ node dist/cli.js --port 3000
186
337
  ```
187
338
 
339
+ Two things matter in production here. Set `DB` to a real path or libsql url: the default `:memory:` forgets every rate limit when the process restarts. And put the server behind a proxy that sets `X-Forwarded-For` (or `CF-Connecting-IP`), otherwise the per ip limit is skipped and only the per address one applies.
340
+
341
+ The published package takes the same variables without cloning anything, though you then get the frontend that was built at publish time, with the site key of whoever published it. That path only makes sense with `--no-captcha` on localhost:
342
+
343
+ ```bash
344
+ npx faucet-server --port 3000 --no-captcha
345
+ ```
346
+
347
+ ### 6. Check it actually works
348
+
349
+ Replace `FAUCET` with your deployed url:
350
+
351
+ ```bash
352
+ # captcha must be ON in production
353
+ curl -s $FAUCET/api/config # {"captchaDisabled":false}
354
+
355
+ # the chain must be configured, and the rpc must NOT be in the answer
356
+ curl -s $FAUCET/api/chain/11155111 # {"chainId":11155111,"amount":"10000000000000000"}
357
+
358
+ # a claim without a real captcha token must be refused
359
+ curl -s -X POST $FAUCET/api/claim -H 'Content-Type: application/json' \
360
+ -d '{"token":"nope","chainId":"11155111","address":"0x0000000000000000000000000000000000000001"}'
361
+ ```
362
+
363
+ Then open `$FAUCET/?chainId=11155111&address=0xYourAddress` in a browser, solve the captcha, and claim. If the button stays greyed out, the captcha widget never returned a token: check the site key and its domain allowlist.
364
+
365
+ ### 7. Running it
366
+
367
+ - **Funding.** Watch the faucet balance. When it can no longer cover a claim plus gas, users get a clear `503` and the server logs `faucet 0x... is out of funds on chain ...`.
368
+ - **Tuning the limits.** `CLAIM_COOLDOWN_SECONDS`, `IP_COOLDOWN_SECONDS` and `MAX_RECIPIENT_BALANCE` decide how fast the faucet can be drained. The defaults give one claim per address and per ip per day, and refuse addresses already holding ten times the dispensed amount.
369
+ - **Rotating the wallet.** Set the new `FAUCET_PRIVATE_KEY` secret and redeploy. Nothing else stores the address.
370
+ - **Adding a chain.** Add another `CHAIN_<id>` secret and redeploy. No code change, no database change.
371
+
372
+ ### If something is wrong
373
+
374
+ | Symptom | Cause |
375
+ |---------|-------|
376
+ | Build fails with `VITE_PROSOPO_SITE_KEY is not set` | Working as intended: set the site key in `packages/frontend/.env.local` or pass `VITE_PROSOPO_SITE_KEY=...` to `pnpm build`. The `deploy:cf` script runs the build first, so there is no way to deploy without it. Use `ALLOW_NO_CAPTCHA=true` only if the server runs with `DISABLE_CAPTCHA=true` |
377
+ | Claim button never enables | The captcha widget got no token: wrong site key, or your domain is not allowlisted in the Prosopo portal |
378
+ | `the D1 binding "DB" is missing` | `database_id` was never filled in, or the binding is not under `[env.production]` |
379
+ | `no such table: Claims` | `pnpm cf-worker:init-db` was not run against the remote database |
380
+ | Every claim answers `503` about the captcha provider | Prosopo is unreachable and the faucet fails closed by design. Set `CAPTCHA_FAIL_OPEN=true` only if you accept that bots get through during outages |
381
+ | Rate limits reset all the time (node) | `DB` is still `:memory:` |
382
+ | Everyone shares one ip bucket, or nobody is ip limited | The proxy in front does not forward the client ip |
383
+
188
384
  ---
189
385
 
190
386
  ## Usage
@@ -203,11 +399,68 @@ https://your-faucet.example.com?chainId=11155111&address=0x...
203
399
 
204
400
  ## API Reference
205
401
 
402
+ ### GET `/api/config`
403
+
404
+ ```json
405
+ {"captchaDisabled": false}
406
+ ```
407
+
408
+ `arbitraryCalls` and `faucetAddress` are added only when arbitrary calls are enabled, so a faucet that leaves the feature off answers exactly what it always did. `faucetAddress` is the address a call is signed by, which the popup shows: it is public, being the sender of every dispensed transaction.
409
+
410
+ ```json
411
+ {"captchaDisabled": false, "arbitraryCalls": "allowlist", "faucetAddress": "0x..."}
412
+ ```
413
+
414
+ ### GET `/api/chain/:chainId`
415
+
416
+ Amount dispensed on that chain, in wei. `404` when the chain is not configured. The rpc endpoint is deliberately not exposed.
417
+
418
+ ```json
419
+ {"chainId": 11155111, "amount": "10000000000000000"}
420
+ ```
421
+
422
+ ### GET `/api/tx/:chainId/:txHash`
423
+
424
+ Follows a dispensed transaction server side.
425
+
426
+ ```json
427
+ {"status": "pending"}
428
+ {"status": "success", "blockNumber": "5123456"}
429
+ {"status": "failed", "blockNumber": "5123456"}
430
+ ```
431
+
432
+ ### POST `/api/execute`
433
+
434
+ Only when arbitrary calls are enabled, otherwise `404`. Executes a call and pays for it.
435
+
436
+ **Request Body:**
437
+
438
+ ```json
439
+ {
440
+ "token": "prosopo_captcha_token",
441
+ "chainId": "11155111",
442
+ "to": "0x...",
443
+ "data": "0x1249c58b",
444
+ "value": "0"
445
+ }
446
+ ```
447
+
448
+ `data` defaults to `0x` and `value` is a decimal wei string defaulting to `0`. Success and errors have the same shape as `/api/claim`, so the transaction is followed through `/api/tx/:chainId/:txHash` in the same way.
449
+
450
+ | Status | Meaning |
451
+ |--------|---------|
452
+ | `404` | Arbitrary calls are not enabled on this faucet |
453
+ | `400` | Bad input, unconfigured chain, contract or selector not allow-listed, value over the ceiling, call reverts, or the call does not fit the budget |
454
+ | `401` | Captcha failed or token already used |
455
+ | `429` | ip cooldown still running |
456
+ | `503` | Captcha provider unreachable, client ip unknown, rpc unreachable, faucet empty, or faucet busy |
457
+
206
458
  ### POST `/api/claim`
207
459
 
208
460
  Request funds from the faucet.
209
461
 
210
462
  **Request Body:**
463
+
211
464
  ```json
212
465
  {
213
466
  "token": "prosopo_captcha_token",
@@ -217,6 +470,7 @@ Request funds from the faucet.
217
470
  ```
218
471
 
219
472
  **Success Response:**
473
+
220
474
  ```json
221
475
  {
222
476
  "success": true,
@@ -225,17 +479,26 @@ Request funds from the faucet.
225
479
  ```
226
480
 
227
481
  **Error Response:**
482
+
228
483
  ```json
229
484
  {
230
485
  "error": "Error message"
231
486
  }
232
487
  ```
233
488
 
489
+ | Status | Meaning |
490
+ |--------|---------|
491
+ | `400` | Bad input, unconfigured chain, or recipient already funded |
492
+ | `401` | Captcha failed or token already used |
493
+ | `429` | Cooldown still running, see the `Retry-After` header and `retryAfter` field |
494
+ | `503` | Captcha provider unreachable, rpc unreachable, faucet empty, or faucet busy |
495
+
234
496
  ## Project Structure
235
497
 
236
498
  ```
237
499
  faucet/
238
500
  ├── packages/
501
+ │ ├── client/ # Popup client library for dapps
239
502
  │ ├── frontend/ # Svelte SPA with captcha integration
240
503
  │ └── server/ # Hono API server (platform-agnostic)
241
504
  ├── platforms/
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import "named-logs-context";
3
- import { createServer } from "faucet-server-app";
3
+ import { createServer, setupDB, checkConfig, getArbitraryCallsMode, } from "faucet-server-app";
4
4
  import { serve } from "@hono/node-server";
5
5
  import { serveStatic } from "@hono/node-server/serve-static";
6
6
  import { RemoteLibSQL } from "remote-sql-libsql";
@@ -24,7 +24,10 @@ async function main() {
24
24
  .usage(`${binName} [--port ${defaultPort}]`)
25
25
  .description("a server that gives token, protected by captcha")
26
26
  .option("-p, --port <port>")
27
- .option("--no-captcha", "Disable captcha verification (for localhost development)");
27
+ .option("--no-captcha", "Disable captcha verification (for localhost development)")
28
+ .option("--arbitrary-calls <mode>", "Let callers choose what the faucet signs: 'off' (default), 'allowlist' or 'unrestricted'. A flag rather than an env var so it cannot follow you into a deployment")
29
+ .option("--dev", "Development mode: include the cause and stack of unhandled errors in api responses")
30
+ .option("--host <host>", "Interface to bind. Defaults to every interface, except when captcha is disabled AND arbitrary calls are unrestricted, which binds localhost only");
28
31
  program.parse(process.argv);
29
32
  const options = program.opts();
30
33
  const port = options.port ? parseInt(options.port) : defaultPort;
@@ -32,12 +35,47 @@ async function main() {
32
35
  if (options.captcha === false) {
33
36
  process.env.DISABLE_CAPTCHA = "true";
34
37
  }
38
+ if (options.arbitraryCalls !== undefined) {
39
+ process.env.ENABLE_ARBITRARY_CALLS = options.arbitraryCalls;
40
+ }
41
+ if (options.dev) {
42
+ process.env.DEV = "true";
43
+ }
35
44
  const env = process.env;
45
+ if (env.DISABLE_CAPTCHA === "true") {
46
+ console.warn(`WARNING: captcha verification is DISABLED, anyone can drain this faucet. Never do this outside localhost.`);
47
+ }
48
+ // A broken configuration must stop the server rather than be discovered one
49
+ // failed claim at a time, all the more so for the limits that decide how fast
50
+ // the faucet can be drained.
51
+ const issues = checkConfig(env);
52
+ for (const line of issues.info) {
53
+ console.log(line);
54
+ }
55
+ for (const warning of issues.warnings) {
56
+ console.warn(`WARNING: ${warning}`);
57
+ }
58
+ if (issues.errors.length > 0) {
59
+ for (const error of issues.errors) {
60
+ console.error(`ERROR: ${error}`);
61
+ }
62
+ process.exit(1);
63
+ }
36
64
  const db = env.DB || ":memory:";
65
+ // libsql wants a url: accept a plain file path too (DB=./faucet.db)
66
+ const dbUrl = db === ":memory:" || db.includes("://") || db.startsWith("file:")
67
+ ? db
68
+ : `file:${db}`;
37
69
  const client = createClient({
38
- url: db,
70
+ url: dbUrl,
39
71
  });
40
72
  const remoteSQL = new RemoteLibSQL(client);
73
+ // rate limiting, captcha replay protection and nonce serialisation all need
74
+ // these tables, and they are cheap to (re)create on every boot
75
+ await setupDB(remoteSQL);
76
+ if (db === ":memory:") {
77
+ console.warn(`WARNING: using an in-memory database, every rate limit is forgotten on restart. Set DB to a file path (DB=./faucet.db) or a libsql url for a public deployment.`);
78
+ }
41
79
  // Create server app (includes API routes under /api)
42
80
  const app = createServer({
43
81
  getDB: () => remoteSQL,
@@ -51,15 +89,24 @@ async function main() {
51
89
  // Fallback to index.html for SPA (any request that didn't match static files)
52
90
  app.get("*", serveStatic({ root: staticDir, path: "/index.html" }));
53
91
  }
54
- if (db === ":memory:") {
55
- // console.log(`executing setup...`);
56
- // can fetch an admin route with the token if needed
92
+ // An unrestricted executor with no captcha has nothing in front of it, and
93
+ // the default bind is every interface, so it would be reachable from the
94
+ // whole network. Bind localhost instead unless the operator says otherwise.
95
+ // Only this brand new combination changes, so no existing setup moves.
96
+ const callsMode = getArbitraryCallsMode(env);
97
+ const unmetered = env.DISABLE_CAPTCHA === "true" &&
98
+ callsMode.status === "ok" &&
99
+ callsMode.mode === "unrestricted";
100
+ const hostname = options.host ?? (unmetered ? "127.0.0.1" : undefined);
101
+ if (unmetered && hostname === "127.0.0.1" && options.host === undefined) {
102
+ console.warn(`WARNING: binding 127.0.0.1 only, because an unrestricted executor with no captcha must not be reachable from the network. Pass --host 0.0.0.0 to override.`);
57
103
  }
58
104
  serve({
59
105
  fetch: app.fetch,
60
106
  port,
107
+ ...(hostname ? { hostname } : {}),
61
108
  });
62
- console.log(`Server is running on http://localhost:${port}`);
109
+ console.log(`Server is running on http://${hostname ?? "localhost"}:${port}${hostname ? "" : " (bound to every interface)"}`);
63
110
  }
64
111
  main();
65
112
  //# sourceMappingURL=cli.js.map
package/dist/cli.js.map CHANGED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AQ,KAAK,WAAW,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;QACxE,OAAO,CAAC,IAAI,CACV,4JAA4J,CAC7J,CAAC;IACJ,CAAC;IAED,KAAK,CAAC;QACJ,KAAK,EAAE,GAAG,CAAC,KAAK;QAChB,IAAI;QACJ,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAClC,CAAC,CAAC;IAEH,OAAO,CAAC,GAAG,CACT,+BAA+B,QAAQ,IAAI,WAAW,IAAI,IAAI,GAC5D,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,6BAClB,EAAE,CACH,CAAC;AACJ,CAAC;AACD,IAAI,EAAE,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "faucet-server",
3
- "version": "0.0.7",
3
+ "version": "0.2.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -14,13 +14,13 @@
14
14
  "static"
15
15
  ],
16
16
  "dependencies": {
17
- "@hono/node-server": "^1.19.12",
17
+ "@hono/node-server": "^2.0.12",
18
18
  "@libsql/client": "^0.17.2",
19
19
  "commander": "^14.0.3",
20
20
  "ldenv": "^0.5.0",
21
21
  "named-logs-context": "^0.1.1",
22
22
  "remote-sql-libsql": "^0.0.7",
23
- "faucet-server-app": "0.0.6"
23
+ "faucet-server-app": "0.2.0"
24
24
  },
25
25
  "devDependencies": {
26
26
  "@types/node": "^25.5.0",
@@ -30,7 +30,7 @@
30
30
  "typescript": "^5.9.3"
31
31
  },
32
32
  "scripts": {
33
- "dev": "tsx watch src/cli.ts --port 30042",
33
+ "dev": "tsx watch src/cli.ts --port 30042 --no-captcha --dev",
34
34
  "build": "tsc",
35
35
  "build:watch": "as-soon -w src tsc"
36
36
  }