faucet-server-app 0.1.0 → 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/src/api/index.ts CHANGED
@@ -4,20 +4,31 @@ import {setup} from '../setup.js';
4
4
  import {
5
5
  CHAIN_LOCK_TIMEOUT_SECONDS,
6
6
  CLAIM_RETENTION_SECONDS,
7
- DEFAULT_CLAIM_COOLDOWN_SECONDS,
8
7
  Env,
9
8
  USED_TOKEN_RETENTION_SECONDS,
10
- getNumberEnv,
9
+ getBigIntEnv,
10
+ getCooldowns,
11
11
  } from '../env.js';
12
12
  import {isAddress, type Hex, type Address} from 'viem';
13
13
  import {privateKeyToAccount} from 'viem/accounts';
14
14
  import {
15
15
  estimateTransferCost,
16
+ feePerGas,
16
17
  getChainConfig,
18
+ getFeeParams,
17
19
  getPublicClient,
18
20
  getWalletClient,
21
+ parseChainId,
19
22
  } from '../chains.js';
20
23
  import {hashToken, verifyProsopoCaptcha} from '../captcha.js';
24
+ import {
25
+ getArbitraryCallsMode,
26
+ getCallAllowlist,
27
+ getCallLimits,
28
+ isCallAllowed,
29
+ parseCallRequest,
30
+ planGas,
31
+ } from '../calls.js';
21
32
 
22
33
  type ClaimRequest = {
23
34
  token: string;
@@ -25,6 +36,63 @@ type ClaimRequest = {
25
36
  address: string;
26
37
  };
27
38
 
39
+ type ExecuteRequest = {
40
+ token: string;
41
+ chainId: string;
42
+ to: string;
43
+ data?: string;
44
+ value?: string;
45
+ };
46
+
47
+ // A refusal, kept as data so shared checks can be reused across endpoints
48
+ // without fighting hono's response typing.
49
+ type Refusal = {error: string; status: 401 | 500 | 503};
50
+
51
+ /**
52
+ * Burns the captcha token so it cannot be replayed, then verifies it with the
53
+ * provider. Shared by /claim and /execute. Returns null when the caller may
54
+ * proceed. A disabled captcha skips both.
55
+ */
56
+ async function checkCaptcha(params: {
57
+ env: Env;
58
+ storage: {burnToken: (hash: string, now: number) => Promise<boolean>};
59
+ token: string;
60
+ ip: string;
61
+ now: number;
62
+ }): Promise<Refusal | null> {
63
+ const {env, storage, token, ip, now} = params;
64
+ if (env.DISABLE_CAPTCHA === 'true') {
65
+ return null;
66
+ }
67
+
68
+ const tokenHash = await hashToken(token);
69
+ const fresh = await storage.burnToken(tokenHash, now);
70
+ if (!fresh) {
71
+ return {error: 'Captcha token already used', status: 401};
72
+ }
73
+
74
+ const verification = await verifyProsopoCaptcha(
75
+ token,
76
+ env.PROSOPO_SITE_PRIVATE_KEY!,
77
+ {
78
+ failOpen: env.CAPTCHA_FAIL_OPEN === 'true',
79
+ ip: ip || undefined,
80
+ },
81
+ );
82
+ if (!verification.ok) {
83
+ if (verification.reason === 'unavailable') {
84
+ console.error(`captcha unavailable: ${verification.details}`);
85
+ return {
86
+ error:
87
+ 'Captcha verification is temporarily unavailable, please try again later',
88
+ status: 503,
89
+ };
90
+ }
91
+ return {error: 'Captcha verification failed', status: 401};
92
+ }
93
+ return null;
94
+ }
95
+
28
96
  const TX_HASH_REGEX = /^0x[0-9a-fA-F]{64}$/;
29
97
 
30
98
  /**
@@ -99,14 +167,40 @@ export function getAPI<CustomEnv extends Env>(
99
167
  const config = c.get('config');
100
168
  const env = config.env;
101
169
  const captchaDisabled = env.DISABLE_CAPTCHA === 'true';
102
- return c.json({captchaDisabled});
170
+ const modeLookup = getArbitraryCallsMode(env);
171
+ if (modeLookup.status === 'invalid') {
172
+ // same answer as /execute gives, rather than quietly reporting 'off'
173
+ // for a mode the operator clearly meant to set
174
+ console.error(
175
+ `invalid ENABLE_ARBITRARY_CALLS: "${env.ENABLE_ARBITRARY_CALLS}"`,
176
+ );
177
+ return c.json({error: 'Faucet misconfigured'}, 500);
178
+ }
179
+ const mode = modeLookup.mode;
180
+ // only advertised when enabled, so a faucet that never turns this on
181
+ // answers exactly what it always did
182
+ if (mode === 'off') {
183
+ return c.json({captchaDisabled});
184
+ }
185
+ // the address a call is signed by is what the user is really lending,
186
+ // so the popup can show it. It is public: every dispensed transaction
187
+ // carries it as the sender.
188
+ let faucetAddress: string | undefined;
189
+ try {
190
+ faucetAddress = privateKeyToAccount(
191
+ env.FAUCET_PRIVATE_KEY as Hex,
192
+ ).address;
193
+ } catch (err) {
194
+ // a missing or malformed key is reported by the claim path instead
195
+ }
196
+ return c.json({captchaDisabled, arbitraryCalls: mode, faucetAddress});
103
197
  })
104
198
  .get('/chain/:chainId', async (c) => {
105
199
  const config = c.get('config');
106
200
  const env = config.env;
107
201
 
108
- const chainIdNum = parseInt(c.req.param('chainId'), 10);
109
- if (isNaN(chainIdNum) || chainIdNum <= 0) {
202
+ const chainIdNum = parseChainId(c.req.param('chainId'));
203
+ if (chainIdNum === null) {
110
204
  return c.json({error: 'Invalid chainId'}, 400);
111
205
  }
112
206
 
@@ -135,8 +229,8 @@ export function getAPI<CustomEnv extends Env>(
135
229
  const config = c.get('config');
136
230
  const env = config.env;
137
231
 
138
- const chainIdNum = parseInt(c.req.param('chainId'), 10);
139
- if (isNaN(chainIdNum) || chainIdNum <= 0) {
232
+ const chainIdNum = parseChainId(c.req.param('chainId'));
233
+ if (chainIdNum === null) {
140
234
  return c.json({error: 'Invalid chainId'}, 400);
141
235
  }
142
236
 
@@ -203,8 +297,8 @@ export function getAPI<CustomEnv extends Env>(
203
297
  return c.json({error: 'Invalid Ethereum address'}, 400);
204
298
  }
205
299
 
206
- const chainIdNum = parseInt(chainId, 10);
207
- if (isNaN(chainIdNum) || chainIdNum <= 0) {
300
+ const chainIdNum = parseChainId(chainId);
301
+ if (chainIdNum === null) {
208
302
  return c.json({error: 'Invalid chainId'}, 400);
209
303
  }
210
304
 
@@ -223,6 +317,30 @@ export function getAPI<CustomEnv extends Env>(
223
317
  }
224
318
  const chainConfig = lookup.config;
225
319
 
320
+ // ---------------------------------------------------------------
321
+ // 0. the limits this faucet runs under. Parsed up front, before any
322
+ // network work: a typo in one of them is a refusal, never a
323
+ // quietly weaker limit.
324
+ // ---------------------------------------------------------------
325
+ const maxRecipientBalanceEnv = getBigIntEnv(env.MAX_RECIPIENT_BALANCE);
326
+ if (maxRecipientBalanceEnv.status === 'invalid') {
327
+ console.error(
328
+ `MAX_RECIPIENT_BALANCE is not a wei amount: "${env.MAX_RECIPIENT_BALANCE}"`,
329
+ );
330
+ return c.json({error: 'Faucet misconfigured'}, 500);
331
+ }
332
+ const maxRecipientBalance =
333
+ maxRecipientBalanceEnv.status === 'ok'
334
+ ? maxRecipientBalanceEnv.value
335
+ : chainConfig.amount * 10n;
336
+
337
+ const cooldowns = getCooldowns(env);
338
+ if (cooldowns.status === 'invalid') {
339
+ console.error(cooldowns.details);
340
+ return c.json({error: 'Faucet misconfigured'}, 500);
341
+ }
342
+ const {addressCooldown, ipCooldown} = cooldowns;
343
+
226
344
  const now = Math.floor(Date.now() / 1000);
227
345
  const ip = getClientIp(c);
228
346
  const normalizedAddress = address.toLowerCase();
@@ -231,30 +349,9 @@ export function getAPI<CustomEnv extends Env>(
231
349
  // ---------------------------------------------------------------
232
350
  // 1. captcha: single use token, then provider verification
233
351
  // ---------------------------------------------------------------
234
- if (!captchaDisabled) {
235
- const tokenHash = await hashToken(token);
236
- const fresh = await storage.burnToken(tokenHash, now);
237
- if (!fresh) {
238
- return c.json({error: 'Captcha token already used'}, 401);
239
- }
240
-
241
- const verification = await verifyProsopoCaptcha(token, secret!, {
242
- failOpen: env.CAPTCHA_FAIL_OPEN === 'true',
243
- ip: ip || undefined,
244
- });
245
- if (!verification.ok) {
246
- if (verification.reason === 'unavailable') {
247
- console.error(`captcha unavailable: ${verification.details}`);
248
- return c.json(
249
- {
250
- error:
251
- 'Captcha verification is temporarily unavailable, please try again later',
252
- },
253
- 503,
254
- );
255
- }
256
- return c.json({error: 'Captcha verification failed'}, 401);
257
- }
352
+ const refusal = await checkCaptcha({env, storage, token, ip, now});
353
+ if (refusal) {
354
+ return c.json({error: refusal.error}, refusal.status);
258
355
  }
259
356
 
260
357
  const publicClient = getPublicClient(chainConfig);
@@ -262,11 +359,6 @@ export function getAPI<CustomEnv extends Env>(
262
359
  // ---------------------------------------------------------------
263
360
  // 2. do not top up an address that already holds enough
264
361
  // ---------------------------------------------------------------
265
- const maxRecipientBalance =
266
- env.MAX_RECIPIENT_BALANCE === undefined ||
267
- env.MAX_RECIPIENT_BALANCE === ''
268
- ? chainConfig.amount * 10n
269
- : BigInt(env.MAX_RECIPIENT_BALANCE);
270
362
  if (maxRecipientBalance > 0n) {
271
363
  try {
272
364
  const recipientBalance = await publicClient.getBalance({
@@ -290,12 +382,6 @@ export function getAPI<CustomEnv extends Env>(
290
382
  // ---------------------------------------------------------------
291
383
  // 3. rate limit: atomically reserve a slot for this address / ip
292
384
  // ---------------------------------------------------------------
293
- const addressCooldown = getNumberEnv(
294
- env.CLAIM_COOLDOWN_SECONDS,
295
- DEFAULT_CLAIM_COOLDOWN_SECONDS,
296
- );
297
- const ipCooldown = getNumberEnv(env.IP_COOLDOWN_SECONDS, addressCooldown);
298
-
299
385
  const claimId = await storage.reserveClaim({
300
386
  chainId: chainIdKey,
301
387
  address: normalizedAddress,
@@ -410,6 +496,346 @@ export function getAPI<CustomEnv extends Env>(
410
496
  ),
411
497
  );
412
498
 
499
+ return c.json({success: true, txHash});
500
+ } catch (err) {
501
+ console.error('Transaction error:', err);
502
+ await storage.releaseChainLock(chainIdKey, nonceUsed).catch((e) => {
503
+ console.error('could not release chain lock', e);
504
+ });
505
+ const errorMessage =
506
+ err instanceof Error ? err.message : 'Transaction failed';
507
+ return abort(errorMessage, 500);
508
+ }
509
+ })
510
+ /**
511
+ * Executes a caller chosen call, paid for by the faucet.
512
+ *
513
+ * Off unless ENABLE_ARBITRARY_CALLS says otherwise, because this lends the
514
+ * faucet key's authority to whoever passes the captcha. See
515
+ * docs/specs/arbitrary-calls.md for the threat model.
516
+ */
517
+ .post('/execute', async (c) => {
518
+ const config = c.get('config');
519
+ const {env, storage} = config;
520
+
521
+ const modeLookup = getArbitraryCallsMode(env);
522
+ if (modeLookup.status === 'invalid') {
523
+ console.error(
524
+ `invalid ENABLE_ARBITRARY_CALLS: "${env.ENABLE_ARBITRARY_CALLS}"`,
525
+ );
526
+ return c.json({error: 'Faucet misconfigured'}, 500);
527
+ }
528
+ const mode = modeLookup.mode;
529
+ if (mode === 'off') {
530
+ return c.json(
531
+ {error: 'Arbitrary calls are not enabled on this faucet'},
532
+ 404,
533
+ );
534
+ }
535
+
536
+ const captchaDisabled = env.DISABLE_CAPTCHA === 'true';
537
+ const secret = env.PROSOPO_SITE_PRIVATE_KEY;
538
+ if (!captchaDisabled && !secret) {
539
+ return c.json({error: 'PROSOPO_SITE_PRIVATE_KEY not configured'}, 500);
540
+ }
541
+
542
+ const faucetPrivateKey = env.FAUCET_PRIVATE_KEY;
543
+ if (!faucetPrivateKey) {
544
+ return c.json({error: 'FAUCET_PRIVATE_KEY not configured'}, 500);
545
+ }
546
+
547
+ let body: ExecuteRequest;
548
+ try {
549
+ body = await c.req.json<ExecuteRequest>();
550
+ } catch (err) {
551
+ return c.json({error: 'Invalid JSON body'}, 400);
552
+ }
553
+ const {token, chainId} = body;
554
+
555
+ if (!token && !captchaDisabled) {
556
+ return c.json({error: 'Missing token'}, 400);
557
+ }
558
+ if (!chainId) {
559
+ return c.json({error: 'Missing chainId'}, 400);
560
+ }
561
+ const chainIdNum = parseChainId(chainId);
562
+ if (chainIdNum === null) {
563
+ return c.json({error: 'Invalid chainId'}, 400);
564
+ }
565
+
566
+ const parsed = parseCallRequest(body);
567
+ if (parsed.status === 'invalid') {
568
+ return c.json({error: parsed.error}, 400);
569
+ }
570
+ const {to, data, value} = parsed.call;
571
+
572
+ const lookup = getChainConfig(env, chainIdNum);
573
+ if (lookup.status === 'not-configured') {
574
+ return c.json(
575
+ {error: `Faucet not configured for chain ${chainIdNum}`},
576
+ 400,
577
+ );
578
+ }
579
+ if (lookup.status === 'invalid') {
580
+ console.error(
581
+ `invalid config for chain ${chainIdNum}: ${lookup.details}`,
582
+ );
583
+ return c.json({error: 'Faucet misconfigured'}, 500);
584
+ }
585
+ const chainConfig = lookup.config;
586
+
587
+ // parsed before any network work, so a typo in a limit is a refusal
588
+ const cooldowns = getCooldowns(env);
589
+ if (cooldowns.status === 'invalid') {
590
+ console.error(cooldowns.details);
591
+ return c.json({error: 'Faucet misconfigured'}, 500);
592
+ }
593
+ const {addressCooldown, ipCooldown} = cooldowns;
594
+
595
+ // ---------------------------------------------------------------
596
+ // 1. is this call permitted at all
597
+ // ---------------------------------------------------------------
598
+ if (mode === 'allowlist') {
599
+ const allowlistLookup = getCallAllowlist(env, chainIdNum);
600
+ if (allowlistLookup.status !== 'ok') {
601
+ console.error(
602
+ `CALL_ALLOWLIST_${chainIdNum} is ${
603
+ allowlistLookup.status === 'invalid'
604
+ ? `invalid: ${allowlistLookup.details}`
605
+ : 'not set, every call on this chain is refused'
606
+ }`,
607
+ );
608
+ return c.json({error: 'Faucet misconfigured'}, 500);
609
+ }
610
+ if (!isCallAllowed(allowlistLookup.allowlist, to, data)) {
611
+ return c.json(
612
+ {
613
+ error:
614
+ 'This faucet does not allow that contract and function combination',
615
+ },
616
+ 400,
617
+ );
618
+ }
619
+ }
620
+
621
+ const now = Math.floor(Date.now() / 1000);
622
+ const ip = getClientIp(c);
623
+ const chainIdKey = String(chainIdNum);
624
+
625
+ // `to` is a shared contract, so it cannot be a rate limiting key: the ip
626
+ // is the only one this endpoint has. Without it there is no limit at
627
+ // all, so an unknown ip is refused rather than served.
628
+ if (!captchaDisabled && ip === '') {
629
+ console.error(
630
+ 'refusing /execute: no client ip, so no rate limit would apply. Put the server behind a proxy that sets X-Forwarded-For.',
631
+ );
632
+ return c.json(
633
+ {
634
+ error:
635
+ 'This faucet cannot determine your ip, and refuses to execute calls it cannot rate limit',
636
+ },
637
+ 503,
638
+ );
639
+ }
640
+
641
+ // ---------------------------------------------------------------
642
+ // 2. captcha: single use token, then provider verification
643
+ // ---------------------------------------------------------------
644
+ const refusal = await checkCaptcha({env, storage, token, ip, now});
645
+ if (refusal) {
646
+ return c.json({error: refusal.error}, refusal.status);
647
+ }
648
+
649
+ // ---------------------------------------------------------------
650
+ // 3. rate limit, on the ip alone. A disabled captcha means localhost,
651
+ // where every account shares one ip, so the bucket is skipped.
652
+ // ---------------------------------------------------------------
653
+ let claimId: number | null = null;
654
+ if (!captchaDisabled) {
655
+ // an empty address disables the address bucket, see RemoteSQLStorage
656
+ claimId = await storage.reserveClaim({
657
+ chainId: chainIdKey,
658
+ address: '',
659
+ ip,
660
+ amount: value.toString(),
661
+ now,
662
+ addressCutoff: now,
663
+ ipCutoff: now - ipCooldown,
664
+ });
665
+ if (claimId === null) {
666
+ const hit = await storage.getRateLimitHit({
667
+ chainId: chainIdKey,
668
+ address: '',
669
+ ip,
670
+ now,
671
+ addressCutoff: now,
672
+ ipCutoff: now - ipCooldown,
673
+ addressCooldown,
674
+ ipCooldown,
675
+ });
676
+ return c.json(
677
+ {
678
+ error: `You already used this faucet recently, try again in ${formatDuration(
679
+ hit.retryAfter,
680
+ )}`,
681
+ retryAfter: hit.retryAfter,
682
+ },
683
+ 429,
684
+ {'Retry-After': String(hit.retryAfter)},
685
+ );
686
+ }
687
+ }
688
+
689
+ // From here on, any failure must give the reservation back.
690
+ const reservedId = claimId;
691
+ const abort = async (
692
+ message: string,
693
+ status: 400 | 500 | 503,
694
+ ): Promise<Response> => {
695
+ if (reservedId !== null) {
696
+ await storage.cancelClaim(reservedId).catch((err) => {
697
+ console.error('could not cancel claim reservation', err);
698
+ });
699
+ }
700
+ return c.json({error: message}, status);
701
+ };
702
+
703
+ const publicClient = getPublicClient(chainConfig);
704
+ const account = privateKeyToAccount(faucetPrivateKey as Hex);
705
+
706
+ // ---------------------------------------------------------------
707
+ // 4. budget: turn a wei ceiling into a gas limit
708
+ // ---------------------------------------------------------------
709
+ // ONE fee reading feeds the budget, the division and the transaction:
710
+ // re-reading would let a bare transfer fail on a fee tick.
711
+ let fees;
712
+ try {
713
+ fees = await getFeeParams(publicClient);
714
+ } catch (err) {
715
+ console.error('could not read gas price', err);
716
+ return abort('Could not reach the chain rpc', 503);
717
+ }
718
+ const fee = feePerGas(fees);
719
+
720
+ const limitsLookup = getCallLimits(env, chainConfig, fee);
721
+ if (limitsLookup.status === 'invalid') {
722
+ console.error(`invalid call limits: ${limitsLookup.details}`);
723
+ return abort('Faucet misconfigured', 500);
724
+ }
725
+ const limits = limitsLookup.limits;
726
+
727
+ if (value > limits.maxValue) {
728
+ return abort(
729
+ `This faucet sends at most ${limits.maxValue} wei with a call, asked for ${value}`,
730
+ 400,
731
+ );
732
+ }
733
+
734
+ // A revert is free here. Refusing now also avoids broadcasting a call
735
+ // that would run out of gas, which would burn the whole limit.
736
+ let estimated: bigint;
737
+ try {
738
+ estimated = await publicClient.estimateGas({
739
+ account,
740
+ to,
741
+ data,
742
+ value,
743
+ });
744
+ } catch (err) {
745
+ const details =
746
+ err instanceof Error && 'shortMessage' in err
747
+ ? String((err as {shortMessage: unknown}).shortMessage)
748
+ : err instanceof Error
749
+ ? err.message
750
+ : 'unknown error';
751
+ return abort(`This call cannot be executed: ${details}`, 400);
752
+ }
753
+
754
+ const plan = planGas({limits, value, estimated, feePerGas: fee});
755
+ if (plan.status === 'does-not-fit') {
756
+ return abort(plan.details, 400);
757
+ }
758
+
759
+ // ---------------------------------------------------------------
760
+ // 5. can the faucet still pay the worst case?
761
+ // ---------------------------------------------------------------
762
+ try {
763
+ const faucetBalance = await publicClient.getBalance({
764
+ address: account.address,
765
+ });
766
+ if (faucetBalance < plan.ceiling) {
767
+ console.error(
768
+ `faucet ${account.address} is out of funds on chain ${chainIdNum}: balance ${faucetBalance}, needs ${plan.ceiling}`,
769
+ );
770
+ return abort(
771
+ 'The faucet is temporarily out of funds, please try again later',
772
+ 503,
773
+ );
774
+ }
775
+ } catch (err) {
776
+ console.error('could not check faucet balance', err);
777
+ return abort('Could not reach the chain rpc', 503);
778
+ }
779
+
780
+ // ---------------------------------------------------------------
781
+ // 6. serialise sending so concurrent calls cannot reuse a nonce
782
+ // ---------------------------------------------------------------
783
+ const lock = await acquireChainLockWaiting(storage, chainIdKey);
784
+ if (!lock.acquired) {
785
+ return abort(
786
+ 'The faucet is busy dispensing other claims, please try again in a few seconds',
787
+ 503,
788
+ );
789
+ }
790
+
791
+ let nonceUsed: number | null = null;
792
+ try {
793
+ const pendingNonce = await publicClient.getTransactionCount({
794
+ address: account.address,
795
+ blockTag: 'pending',
796
+ });
797
+ const nonce =
798
+ lock.lastNonce === null
799
+ ? pendingNonce
800
+ : Math.max(lock.lastNonce + 1, pendingNonce);
801
+
802
+ const walletClient = getWalletClient(chainConfig, account);
803
+ // gas and fee are both explicit: the ceiling is only a real bound
804
+ // because the server picked both numbers.
805
+ const txHash =
806
+ fees.type === 'eip1559'
807
+ ? await walletClient.sendTransaction({
808
+ to,
809
+ data,
810
+ value,
811
+ nonce,
812
+ gas: plan.gasLimit,
813
+ maxFeePerGas: fees.maxFeePerGas,
814
+ maxPriorityFeePerGas: fees.maxPriorityFeePerGas,
815
+ })
816
+ : await walletClient.sendTransaction({
817
+ to,
818
+ data,
819
+ value,
820
+ nonce,
821
+ gas: plan.gasLimit,
822
+ gasPrice: fees.gasPrice,
823
+ });
824
+ nonceUsed = nonce;
825
+
826
+ await storage.releaseChainLock(chainIdKey, nonceUsed);
827
+ if (reservedId !== null) {
828
+ await storage.recordClaimTx(reservedId, txHash);
829
+ }
830
+
831
+ background(
832
+ c,
833
+ storage.cleanup(
834
+ now - USED_TOKEN_RETENTION_SECONDS,
835
+ now - CLAIM_RETENTION_SECONDS,
836
+ ),
837
+ );
838
+
413
839
  return c.json({success: true, txHash});
414
840
  } catch (err) {
415
841
  console.error('Transaction error:', err);