faucet-server-app 0.0.6 → 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.
Files changed (52) hide show
  1. package/dist/esm/api/index.d.ts +51 -16
  2. package/dist/esm/api/index.d.ts.map +1 -1
  3. package/dist/esm/api/index.js +567 -79
  4. package/dist/esm/api/index.js.map +1 -1
  5. package/dist/esm/calls.d.ts +107 -0
  6. package/dist/esm/calls.d.ts.map +1 -0
  7. package/dist/esm/calls.js +304 -0
  8. package/dist/esm/calls.js.map +1 -0
  9. package/dist/esm/captcha.d.ts +28 -0
  10. package/dist/esm/captcha.d.ts.map +1 -0
  11. package/dist/esm/captcha.js +58 -0
  12. package/dist/esm/captcha.js.map +1 -0
  13. package/dist/esm/chains.d.ts +17552 -0
  14. package/dist/esm/chains.d.ts.map +1 -0
  15. package/dist/esm/chains.js +137 -0
  16. package/dist/esm/chains.js.map +1 -0
  17. package/dist/esm/config.d.ts +12 -0
  18. package/dist/esm/config.d.ts.map +1 -0
  19. package/dist/esm/config.js +28 -0
  20. package/dist/esm/config.js.map +1 -0
  21. package/dist/esm/env.d.ts +56 -0
  22. package/dist/esm/env.d.ts.map +1 -1
  23. package/dist/esm/env.js +81 -1
  24. package/dist/esm/env.js.map +1 -1
  25. package/dist/esm/index.d.ts +135 -42
  26. package/dist/esm/index.d.ts.map +1 -1
  27. package/dist/esm/index.js +39 -16
  28. package/dist/esm/index.js.map +1 -1
  29. package/dist/esm/schema/ts/db.sql.d.ts +1 -1
  30. package/dist/esm/schema/ts/db.sql.d.ts.map +1 -1
  31. package/dist/esm/schema/ts/db.sql.js +25 -4
  32. package/dist/esm/schema/ts/db.sql.js.map +1 -1
  33. package/dist/esm/setup.d.ts +2 -0
  34. package/dist/esm/setup.d.ts.map +1 -1
  35. package/dist/esm/setup.js +25 -7
  36. package/dist/esm/setup.js.map +1 -1
  37. package/dist/esm/storage/RemoteSQLStorage.d.ts +49 -0
  38. package/dist/esm/storage/RemoteSQLStorage.d.ts.map +1 -0
  39. package/dist/esm/storage/RemoteSQLStorage.js +158 -0
  40. package/dist/esm/storage/RemoteSQLStorage.js.map +1 -0
  41. package/package.json +1 -1
  42. package/src/api/index.ts +752 -105
  43. package/src/calls.ts +447 -0
  44. package/src/captcha.ts +92 -0
  45. package/src/chains.ts +175 -0
  46. package/src/config.ts +33 -0
  47. package/src/env.ts +129 -0
  48. package/src/index.ts +60 -18
  49. package/src/schema/sql/db.sql +25 -4
  50. package/src/schema/ts/db.sql.ts +25 -4
  51. package/src/setup.ts +28 -11
  52. package/src/storage/RemoteSQLStorage.ts +252 -0
package/src/calls.ts ADDED
@@ -0,0 +1,447 @@
1
+ import {isAddress, type Address, type Hex} from 'viem';
2
+ import {privateKeyToAccount} from 'viem/accounts';
3
+ import {getBigIntEnv, type Env} from './env.js';
4
+ import {parseChainId, type ChainConfig} from './chains.js';
5
+
6
+ /**
7
+ * Arbitrary call execution, see docs/specs/arbitrary-calls.md.
8
+ *
9
+ * Anything other than 'off' lets a caller choose what the faucet key signs,
10
+ * which is a different power from dispensing a fixed amount. Everything in
11
+ * this module exists to bound it.
12
+ */
13
+ export type ArbitraryCallsMode = 'off' | 'allowlist' | 'unrestricted';
14
+
15
+ // gas a plain value transfer costs, the yardstick the default budget uses
16
+ export const SIMPLE_TRANSFER_GAS = 21000n;
17
+
18
+ // absolute rail, so a budget divided by a tiny L2 gas price cannot hand out a
19
+ // gas limit past the block limit
20
+ export const DEFAULT_MAX_CALL_GAS = 2_000_000n;
21
+
22
+ // gas granted on top of the estimate, as a percentage. Without it every call
23
+ // is sent with the maximum the budget allows, which a target that burns gas
24
+ // conditionally would happily spend.
25
+ export const GAS_BUFFER_PERCENT = 125n;
26
+
27
+ export function getArbitraryCallsMode(
28
+ env: Env,
29
+ ): {status: 'ok'; mode: ArbitraryCallsMode} | {status: 'invalid'} {
30
+ const raw = env.ENABLE_ARBITRARY_CALLS;
31
+ if (raw === undefined || raw.trim() === '') {
32
+ return {status: 'ok', mode: 'off'};
33
+ }
34
+ const value = raw.trim();
35
+ if (value === 'off' || value === 'allowlist' || value === 'unrestricted') {
36
+ return {status: 'ok', mode: value};
37
+ }
38
+ return {status: 'invalid'};
39
+ }
40
+
41
+ // ---------------------------------------------------------------------------
42
+ // allow-list
43
+ // ---------------------------------------------------------------------------
44
+
45
+ // contract -> set of 4 byte selectors. A contract with no selector is refused
46
+ // at parse time: allow-listing a whole contract is what makes `transfer` on a
47
+ // token reachable, which defeats the point.
48
+ export type CallAllowlist = Map<string, Set<string>>;
49
+
50
+ export type AllowlistLookup =
51
+ | {status: 'ok'; allowlist: CallAllowlist}
52
+ | {status: 'not-configured'}
53
+ | {status: 'invalid'; details: string};
54
+
55
+ const SELECTOR_REGEX = /^0x[0-9a-f]{8}$/;
56
+
57
+ /**
58
+ * CALL_ALLOWLIST_<CHAIN_ID>=<contract>:<selector>,<selector>;<contract>:<selector>
59
+ */
60
+ export function getCallAllowlist(env: Env, chainId: number): AllowlistLookup {
61
+ const key = `CALL_ALLOWLIST_${chainId}` as `CALL_ALLOWLIST_${string}`;
62
+ const value = env[key];
63
+ if (!value || value.trim() === '') {
64
+ return {status: 'not-configured'};
65
+ }
66
+
67
+ const allowlist: CallAllowlist = new Map();
68
+ for (const rawEntry of value.split(';')) {
69
+ const entry = rawEntry.trim();
70
+ if (entry === '') {
71
+ continue;
72
+ }
73
+ const colonIndex = entry.indexOf(':');
74
+ if (colonIndex === -1) {
75
+ return {
76
+ status: 'invalid',
77
+ details: `entry "${entry}" has no selector, expected <contract>:<selector>[,<selector>]`,
78
+ };
79
+ }
80
+ const contract = entry.substring(0, colonIndex).trim().toLowerCase();
81
+ if (!isAddress(contract)) {
82
+ return {status: 'invalid', details: `"${contract}" is not an address`};
83
+ }
84
+ const selectors = entry
85
+ .substring(colonIndex + 1)
86
+ .split(',')
87
+ .map((v) => v.trim().toLowerCase())
88
+ .filter((v) => v !== '');
89
+ if (selectors.length === 0) {
90
+ return {
91
+ status: 'invalid',
92
+ details: `contract ${contract} has no selector`,
93
+ };
94
+ }
95
+ for (const selector of selectors) {
96
+ if (!SELECTOR_REGEX.test(selector)) {
97
+ return {
98
+ status: 'invalid',
99
+ details: `"${selector}" is not a 4 byte selector`,
100
+ };
101
+ }
102
+ }
103
+ const existing = allowlist.get(contract);
104
+ if (existing) {
105
+ for (const selector of selectors) {
106
+ existing.add(selector);
107
+ }
108
+ } else {
109
+ allowlist.set(contract, new Set(selectors));
110
+ }
111
+ }
112
+
113
+ if (allowlist.size === 0) {
114
+ return {status: 'not-configured'};
115
+ }
116
+ return {status: 'ok', allowlist};
117
+ }
118
+
119
+ export function selectorOf(data: Hex): string | null {
120
+ // '0x' + 8 hex chars
121
+ if (data.length < 10) {
122
+ return null;
123
+ }
124
+ return data.substring(0, 10).toLowerCase();
125
+ }
126
+
127
+ export function isCallAllowed(
128
+ allowlist: CallAllowlist,
129
+ to: Address,
130
+ data: Hex,
131
+ ): boolean {
132
+ const selectors = allowlist.get(to.toLowerCase());
133
+ if (!selectors) {
134
+ return false;
135
+ }
136
+ const selector = selectorOf(data);
137
+ if (selector === null) {
138
+ // a call with no selector is a plain transfer, which /api/claim does
139
+ return false;
140
+ }
141
+ return selectors.has(selector);
142
+ }
143
+
144
+ // ---------------------------------------------------------------------------
145
+ // budget
146
+ // ---------------------------------------------------------------------------
147
+
148
+ export type CallLimits = {
149
+ // ceiling on value + gasLimit * feePerGas for one call
150
+ totalSpend: bigint;
151
+ // ceiling on the value attached to the call
152
+ maxValue: bigint;
153
+ // absolute gas rail
154
+ maxGas: bigint;
155
+ };
156
+
157
+ export type CallLimitsLookup =
158
+ | {status: 'ok'; limits: CallLimits}
159
+ | {status: 'invalid'; details: string};
160
+
161
+ /**
162
+ * Defaults make an arbitrary call cost the faucet exactly what the claim it
163
+ * replaces would have cost: `amount` plus the gas of a plain transfer. So
164
+ * turning the feature on does not change the worst case spend per request.
165
+ *
166
+ * `feePerGas` must be the SAME fee reading used to derive the gas limit and to
167
+ * send the transaction, otherwise a bare transfer (which lands exactly on the
168
+ * boundary) can fail on a fee tick.
169
+ */
170
+ export function getCallLimits(
171
+ env: Env,
172
+ chainConfig: ChainConfig,
173
+ feePerGas: bigint,
174
+ ): CallLimitsLookup {
175
+ const chainId = chainConfig.chainId;
176
+
177
+ const totalSpendEnv = getBigIntEnv(
178
+ env[`MAX_CALL_TOTAL_SPEND_${chainId}` as `MAX_CALL_TOTAL_SPEND_${string}`],
179
+ );
180
+ if (totalSpendEnv.status === 'invalid') {
181
+ return {
182
+ status: 'invalid',
183
+ details: `MAX_CALL_TOTAL_SPEND_${chainId} is not a wei amount`,
184
+ };
185
+ }
186
+ const maxValueEnv = getBigIntEnv(
187
+ env[`MAX_CALL_VALUE_${chainId}` as `MAX_CALL_VALUE_${string}`],
188
+ );
189
+ if (maxValueEnv.status === 'invalid') {
190
+ return {
191
+ status: 'invalid',
192
+ details: `MAX_CALL_VALUE_${chainId} is not a wei amount`,
193
+ };
194
+ }
195
+ const maxGasEnv = getBigIntEnv(env.MAX_CALL_GAS);
196
+ if (maxGasEnv.status === 'invalid') {
197
+ return {status: 'invalid', details: `MAX_CALL_GAS is not a number`};
198
+ }
199
+ if (maxGasEnv.status === 'ok' && maxGasEnv.value === 0n) {
200
+ return {
201
+ status: 'invalid',
202
+ details: `MAX_CALL_GAS must be greater than zero`,
203
+ };
204
+ }
205
+
206
+ return {
207
+ status: 'ok',
208
+ limits: {
209
+ totalSpend:
210
+ totalSpendEnv.status === 'ok'
211
+ ? totalSpendEnv.value
212
+ : chainConfig.amount + SIMPLE_TRANSFER_GAS * feePerGas,
213
+ maxValue:
214
+ maxValueEnv.status === 'ok' ? maxValueEnv.value : chainConfig.amount,
215
+ maxGas:
216
+ maxGasEnv.status === 'ok' ? maxGasEnv.value : DEFAULT_MAX_CALL_GAS,
217
+ },
218
+ };
219
+ }
220
+
221
+ export type GasPlan =
222
+ | {status: 'ok'; gasLimit: bigint; ceiling: bigint}
223
+ | {status: 'does-not-fit'; details: string};
224
+
225
+ /**
226
+ * Turns a wei budget into a gas limit, which is the only thing the evm can
227
+ * actually be told.
228
+ *
229
+ * The `gasLimit < estimated` refusal is not a nicety: an out of gas revert
230
+ * consumes the WHOLE gas limit, so sending a call that cannot fit does not
231
+ * save the budget, it guarantees spending it for nothing.
232
+ */
233
+ export function planGas(params: {
234
+ limits: CallLimits;
235
+ value: bigint;
236
+ estimated: bigint;
237
+ feePerGas: bigint;
238
+ }): GasPlan {
239
+ const {limits, value, estimated, feePerGas} = params;
240
+
241
+ const budgetForGas = limits.totalSpend - value;
242
+ if (budgetForGas <= 0n) {
243
+ return {
244
+ status: 'does-not-fit',
245
+ details: `the value alone (${value} wei) uses the whole ${limits.totalSpend} wei budget, leaving nothing for gas`,
246
+ };
247
+ }
248
+
249
+ // a chain reporting a zero fee cannot bound gas by budget, the rail does it
250
+ const budgetRail = feePerGas > 0n ? budgetForGas / feePerGas : limits.maxGas;
251
+ const bufferRail = (estimated * GAS_BUFFER_PERCENT) / 100n;
252
+
253
+ let gasLimit = limits.maxGas;
254
+ if (budgetRail < gasLimit) {
255
+ gasLimit = budgetRail;
256
+ }
257
+ if (bufferRail < gasLimit) {
258
+ gasLimit = bufferRail;
259
+ }
260
+
261
+ if (gasLimit < estimated) {
262
+ return {
263
+ status: 'does-not-fit',
264
+ details: `this call needs ${estimated} gas but the faucet budget only allows ${gasLimit} at the current gas price`,
265
+ };
266
+ }
267
+
268
+ return {status: 'ok', gasLimit, ceiling: value + gasLimit * feePerGas};
269
+ }
270
+
271
+ // ---------------------------------------------------------------------------
272
+ // request validation
273
+ // ---------------------------------------------------------------------------
274
+
275
+ const DATA_REGEX = /^0x([0-9a-fA-F]{2})*$/;
276
+ const DECIMAL_REGEX = /^[0-9]+$/;
277
+
278
+ export type ParsedCall = {to: Address; data: Hex; value: bigint};
279
+
280
+ export function parseCallRequest(body: {
281
+ to?: unknown;
282
+ data?: unknown;
283
+ value?: unknown;
284
+ }): {status: 'ok'; call: ParsedCall} | {status: 'invalid'; error: string} {
285
+ const {to, data, value} = body;
286
+
287
+ if (typeof to !== 'string' || to === '') {
288
+ return {status: 'invalid', error: 'Missing to'};
289
+ }
290
+ if (!isAddress(to)) {
291
+ return {status: 'invalid', error: 'Invalid to address'};
292
+ }
293
+
294
+ const dataValue = data === undefined || data === null ? '0x' : data;
295
+ if (typeof dataValue !== 'string' || !DATA_REGEX.test(dataValue)) {
296
+ return {status: 'invalid', error: 'Invalid data, expected a hex string'};
297
+ }
298
+
299
+ let parsedValue = 0n;
300
+ if (value !== undefined && value !== null && value !== '') {
301
+ if (typeof value !== 'string' || !DECIMAL_REGEX.test(value)) {
302
+ return {
303
+ status: 'invalid',
304
+ error: 'Invalid value, expected a decimal wei string',
305
+ };
306
+ }
307
+ parsedValue = BigInt(value);
308
+ }
309
+
310
+ return {
311
+ status: 'ok',
312
+ call: {to: to as Address, data: dataValue as Hex, value: parsedValue},
313
+ };
314
+ }
315
+
316
+ // ---------------------------------------------------------------------------
317
+ // configuration validation, for boot time
318
+ // ---------------------------------------------------------------------------
319
+
320
+ export type ConfigIssues = {
321
+ errors: string[];
322
+ warnings: string[];
323
+ // one line per fact worth seeing in the first screen of the log
324
+ info: string[];
325
+ };
326
+
327
+ /**
328
+ * Called at boot by the node cli. Cloudflare Workers has no boot hook, so the
329
+ * same problems surface there as a 500 on the endpoint plus a console error.
330
+ */
331
+ export function checkArbitraryCallsConfig(env: Env): ConfigIssues {
332
+ const errors: string[] = [];
333
+ const warnings: string[] = [];
334
+ const info: string[] = [];
335
+
336
+ const modeLookup = getArbitraryCallsMode(env);
337
+ if (modeLookup.status === 'invalid') {
338
+ errors.push(
339
+ `ENABLE_ARBITRARY_CALLS must be 'off', 'allowlist' or 'unrestricted', got "${env.ENABLE_ARBITRARY_CALLS}"`,
340
+ );
341
+ return {errors, warnings, info};
342
+ }
343
+ const mode = modeLookup.mode;
344
+ if (mode === 'off') {
345
+ return {errors, warnings, info};
346
+ }
347
+
348
+ const chainIds: number[] = [];
349
+ for (const key of Object.keys(env)) {
350
+ if (key.startsWith('CHAIN_')) {
351
+ // strict, so CHAIN_1_TEST does not register itself as chain 1
352
+ const chainId = parseChainId(key.substring('CHAIN_'.length));
353
+ if (chainId !== null) {
354
+ chainIds.push(chainId);
355
+ }
356
+ }
357
+ }
358
+
359
+ if (mode === 'allowlist') {
360
+ for (const chainId of chainIds) {
361
+ const lookup = getCallAllowlist(env, chainId);
362
+ if (lookup.status === 'not-configured') {
363
+ errors.push(
364
+ `ENABLE_ARBITRARY_CALLS=allowlist but CALL_ALLOWLIST_${chainId} is not set: every call on chain ${chainId} would be refused`,
365
+ );
366
+ } else if (lookup.status === 'invalid') {
367
+ errors.push(`CALL_ALLOWLIST_${chainId} is invalid: ${lookup.details}`);
368
+ }
369
+ }
370
+ }
371
+
372
+ // One warning per distinct fact, so that the dangerous combination reads as
373
+ // one loud line rather than three overlapping ones.
374
+ const captchaOff = env.DISABLE_CAPTCHA === 'true';
375
+ if (mode === 'unrestricted' && captchaOff) {
376
+ warnings.push(
377
+ `arbitrary calls are UNRESTRICTED and captcha is DISABLED: anyone who can reach this server can make the faucet key call any contract with any calldata, with no rate limit. Never do this outside localhost. That key must hold no ERC20, hold no role, and have granted no approval, now or ever.`,
378
+ );
379
+ } else if (mode === 'unrestricted') {
380
+ warnings.push(
381
+ `arbitrary calls are UNRESTRICTED: anyone passing the captcha can make the faucet key call any contract with any calldata. That key must hold no ERC20, hold no role, and have granted no approval, now or ever.`,
382
+ );
383
+ } else if (captchaOff) {
384
+ warnings.push(
385
+ `captcha is disabled, so /api/execute applies NO rate limit at all (the ip cooldown is the only one it has)`,
386
+ );
387
+ }
388
+
389
+ // The posture in one screen, so a dangerous configuration is impossible to
390
+ // miss in the first lines of the log.
391
+ info.push(
392
+ `arbitrary calls: ${mode}, captcha: ${
393
+ captchaOff ? 'DISABLED' : 'enabled'
394
+ }, rate limit: ${captchaOff ? 'NONE' : 'ip only'}`,
395
+ );
396
+ // the address whose authority is being lent out, which is the thing an
397
+ // operator most needs to recognise in the log
398
+ try {
399
+ const account = privateKeyToAccount(env.FAUCET_PRIVATE_KEY as Hex);
400
+ info.push(` calls are signed by: ${account.address}`);
401
+ } catch (err) {
402
+ info.push(` calls are signed by: <FAUCET_PRIVATE_KEY missing or invalid>`);
403
+ }
404
+ const maxGas = getBigIntEnv(env.MAX_CALL_GAS);
405
+ info.push(
406
+ ` max gas per call: ${
407
+ maxGas.status === 'ok' ? maxGas.value : DEFAULT_MAX_CALL_GAS
408
+ }`,
409
+ );
410
+ for (const chainId of chainIds.sort((a, b) => a - b)) {
411
+ const totalSpend = getBigIntEnv(
412
+ env[
413
+ `MAX_CALL_TOTAL_SPEND_${chainId}` as `MAX_CALL_TOTAL_SPEND_${string}`
414
+ ],
415
+ );
416
+ const maxValue = getBigIntEnv(
417
+ env[`MAX_CALL_VALUE_${chainId}` as `MAX_CALL_VALUE_${string}`],
418
+ );
419
+ // the default is not a constant: it tracks the gas price, so that a call
420
+ // can never cost more than the claim it replaces
421
+ info.push(
422
+ ` chain ${chainId}: spend at most ${
423
+ totalSpend.status === 'ok'
424
+ ? `${totalSpend.value} wei`
425
+ : `amount + ${SIMPLE_TRANSFER_GAS} * gas price (default, varies)`
426
+ } per call, of which at most ${
427
+ maxValue.status === 'ok' ? `${maxValue.value} wei` : 'amount (default)'
428
+ } as value${
429
+ mode === 'allowlist' ? `, ${describeAllowlist(env, chainId)}` : ''
430
+ }`,
431
+ );
432
+ }
433
+
434
+ return {errors, warnings, info};
435
+ }
436
+
437
+ function describeAllowlist(env: Env, chainId: number): string {
438
+ const lookup = getCallAllowlist(env, chainId);
439
+ if (lookup.status !== 'ok') {
440
+ return 'no allow-list';
441
+ }
442
+ let selectors = 0;
443
+ for (const set of lookup.allowlist.values()) {
444
+ selectors += set.size;
445
+ }
446
+ return `${selectors} selector(s) on ${lookup.allowlist.size} contract(s)`;
447
+ }
package/src/captcha.ts ADDED
@@ -0,0 +1,92 @@
1
+ const PROSOPO_VERIFY_ENDPOINT = 'https://api.prosopo.io/siteverify';
2
+ const VERIFY_TIMEOUT_MS = 10000;
3
+
4
+ type VerifyResponse = {
5
+ status?: string;
6
+ verified?: boolean;
7
+ score?: number;
8
+ reason?: string;
9
+ error?: {code?: number; key?: string; message?: string};
10
+ };
11
+
12
+ export type CaptchaVerification =
13
+ | {ok: true}
14
+ // the user did not pass the challenge, telling them so is safe
15
+ | {ok: false; reason: 'failed'}
16
+ // we could not get a trustworthy answer out of the provider
17
+ | {ok: false; reason: 'unavailable'; details: string};
18
+
19
+ /**
20
+ * Verifies a Procaptcha token against the Prosopo API.
21
+ *
22
+ * Prosopo fails OPEN: when their own verification provider times out they
23
+ * answer `{verified: true, score: 0}`, which would let a bot through. We treat
24
+ * that signature as "provider unavailable" and fail CLOSED unless `failOpen`
25
+ * is set.
26
+ *
27
+ * Note for Premium tier accounts: a genuine human also scores 0 (the score
28
+ * grows towards 1 for bots), so those accounts should either set
29
+ * CAPTCHA_FAIL_OPEN=true or rely on the rate limiter alone.
30
+ */
31
+ export async function verifyProsopoCaptcha(
32
+ token: string,
33
+ secret: string,
34
+ options: {failOpen: boolean; ip?: string},
35
+ ): Promise<CaptchaVerification> {
36
+ const {failOpen, ip} = options;
37
+
38
+ const unavailable = (details: string): CaptchaVerification =>
39
+ failOpen ? {ok: true} : {ok: false, reason: 'unavailable', details};
40
+
41
+ let response: Response;
42
+ try {
43
+ response = await fetch(PROSOPO_VERIFY_ENDPOINT, {
44
+ method: 'POST',
45
+ headers: {'Content-Type': 'application/json'},
46
+ body: JSON.stringify(ip ? {token, secret, ip} : {token, secret}),
47
+ signal: AbortSignal.timeout(VERIFY_TIMEOUT_MS),
48
+ });
49
+ } catch (err) {
50
+ const message = err instanceof Error ? err.message : String(err);
51
+ return unavailable(`request to captcha provider failed: ${message}`);
52
+ }
53
+
54
+ let result: VerifyResponse;
55
+ try {
56
+ result = (await response.json()) as VerifyResponse;
57
+ } catch (err) {
58
+ return unavailable(
59
+ `captcha provider returned a non JSON response (status ${response.status})`,
60
+ );
61
+ }
62
+
63
+ if (!response.ok || result.error) {
64
+ // 4xx here means our own integration is wrong (bad secret, malformed body),
65
+ // 5xx means their side is down. Neither is the user's fault.
66
+ return unavailable(
67
+ `captcha provider error (status ${response.status}): ${
68
+ result.error?.key ?? 'unknown'
69
+ } ${result.error?.message ?? ''}`.trim(),
70
+ );
71
+ }
72
+
73
+ if (result.verified !== true) {
74
+ return {ok: false, reason: 'failed'};
75
+ }
76
+
77
+ if (result.score === 0) {
78
+ return unavailable(
79
+ 'captcha provider returned its fail-open signature (verified with score 0)',
80
+ );
81
+ }
82
+
83
+ return {ok: true};
84
+ }
85
+
86
+ export async function hashToken(token: string): Promise<string> {
87
+ const data = new TextEncoder().encode(token);
88
+ const digest = await crypto.subtle.digest('SHA-256', data);
89
+ return Array.from(new Uint8Array(digest))
90
+ .map((b) => b.toString(16).padStart(2, '0'))
91
+ .join('');
92
+ }
package/src/chains.ts ADDED
@@ -0,0 +1,175 @@
1
+ import {createPublicClient, createWalletClient, http, type Chain} from 'viem';
2
+ import type {PrivateKeyAccount} from 'viem/accounts';
3
+ import {Env} from './env.js';
4
+
5
+ export type ChainConfig = {
6
+ chainId: number;
7
+ amount: bigint;
8
+ rpcUrl: string;
9
+ };
10
+
11
+ /**
12
+ * A chain id, from a url segment, a json body or a CHAIN_<id> variable name.
13
+ *
14
+ * Strict for the same reason the limits are: parseInt partial parses, so
15
+ * '31337x' used to resolve to chain 31337, and a CHAIN_1_TEST variable used to
16
+ * register itself as chain 1. Numbers are accepted as well as strings, because
17
+ * a json body may carry either.
18
+ */
19
+ export function parseChainId(value: unknown): number | null {
20
+ if (typeof value === 'number') {
21
+ return Number.isSafeInteger(value) && value > 0 ? value : null;
22
+ }
23
+ if (typeof value !== 'string') {
24
+ return null;
25
+ }
26
+ const trimmed = value.trim();
27
+ if (!/^[0-9]+$/.test(trimmed)) {
28
+ return null;
29
+ }
30
+ const parsed = Number(trimmed);
31
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) {
32
+ return null;
33
+ }
34
+ return parsed;
35
+ }
36
+
37
+ export type ChainConfigLookup =
38
+ | {status: 'ok'; config: ChainConfig}
39
+ | {status: 'not-configured'}
40
+ | {status: 'invalid'; details: string};
41
+
42
+ /**
43
+ * Chains are configured as CHAIN_<CHAIN_ID>=<amount_in_wei>:<rpc_endpoint>.
44
+ *
45
+ * The rpc endpoint is a SERVER side secret: it usually embeds an api key and is
46
+ * never returned to clients.
47
+ */
48
+ export function getChainConfig(env: Env, chainId: number): ChainConfigLookup {
49
+ const key = `CHAIN_${chainId}` as `CHAIN_${string}`;
50
+ const value = env[key];
51
+ if (!value) {
52
+ return {status: 'not-configured'};
53
+ }
54
+
55
+ const colonIndex = value.indexOf(':');
56
+ if (colonIndex === -1) {
57
+ return {
58
+ status: 'invalid',
59
+ details: `expected <amount>:<rpc_endpoint>, got no separator`,
60
+ };
61
+ }
62
+ const amountStr = value.substring(0, colonIndex).trim();
63
+ const rpcUrl = value.substring(colonIndex + 1).trim();
64
+ if (!amountStr || !rpcUrl) {
65
+ return {
66
+ status: 'invalid',
67
+ details: `expected <amount>:<rpc_endpoint>`,
68
+ };
69
+ }
70
+
71
+ let amount: bigint;
72
+ try {
73
+ amount = BigInt(amountStr);
74
+ } catch (err) {
75
+ return {
76
+ status: 'invalid',
77
+ details: `amount "${amountStr}" is not a number`,
78
+ };
79
+ }
80
+ if (amount <= 0n) {
81
+ return {status: 'invalid', details: `amount must be greater than zero`};
82
+ }
83
+
84
+ return {status: 'ok', config: {chainId, amount, rpcUrl}};
85
+ }
86
+
87
+ export function getViemChain(config: ChainConfig): Chain {
88
+ return {
89
+ id: config.chainId,
90
+ name: `Chain ${config.chainId}`,
91
+ nativeCurrency: {name: 'ETH', symbol: 'ETH', decimals: 18},
92
+ rpcUrls: {default: {http: [config.rpcUrl]}},
93
+ };
94
+ }
95
+
96
+ export function getPublicClient(config: ChainConfig) {
97
+ return createPublicClient({
98
+ chain: getViemChain(config),
99
+ transport: http(config.rpcUrl),
100
+ });
101
+ }
102
+
103
+ export function getWalletClient(
104
+ config: ChainConfig,
105
+ account: PrivateKeyAccount,
106
+ ) {
107
+ return createWalletClient({
108
+ account,
109
+ chain: getViemChain(config),
110
+ transport: http(config.rpcUrl),
111
+ });
112
+ }
113
+
114
+ /**
115
+ * One fee reading, used for the whole of a call: the budget default, the gas
116
+ * limit division and the transaction itself.
117
+ *
118
+ * Reading fees twice would let a bare transfer (whose gas limit lands exactly
119
+ * on the budget boundary) fail on a fee tick, so callers must thread a single
120
+ * FeeParams through rather than re-estimating.
121
+ */
122
+ export type FeeParams =
123
+ | {type: 'eip1559'; maxFeePerGas: bigint; maxPriorityFeePerGas?: bigint}
124
+ | {type: 'legacy'; gasPrice: bigint};
125
+
126
+ export async function getFeeParams(
127
+ publicClient: ReturnType<typeof getPublicClient>,
128
+ ): Promise<FeeParams> {
129
+ try {
130
+ const fees = await publicClient.estimateFeesPerGas();
131
+ if (fees.maxFeePerGas) {
132
+ return {
133
+ type: 'eip1559',
134
+ maxFeePerGas: fees.maxFeePerGas,
135
+ maxPriorityFeePerGas: fees.maxPriorityFeePerGas,
136
+ };
137
+ }
138
+ } catch (err) {
139
+ // chain without eip-1559 support, fall through to gas price
140
+ }
141
+ const gasPrice = await publicClient.getGasPrice();
142
+ return {type: 'legacy', gasPrice};
143
+ }
144
+
145
+ /**
146
+ * The per gas price a spending ceiling has to be computed against: the most
147
+ * the chain can charge for one unit of gas on this transaction.
148
+ */
149
+ export function feePerGas(fees: FeeParams): bigint {
150
+ return fees.type === 'eip1559' ? fees.maxFeePerGas : fees.gasPrice;
151
+ }
152
+
153
+ /**
154
+ * Worst case cost of a plain value transfer, used to check the faucet can still
155
+ * pay for the transaction it is about to broadcast.
156
+ */
157
+ export async function estimateTransferCost(
158
+ publicClient: ReturnType<typeof getPublicClient>,
159
+ ): Promise<bigint> {
160
+ const gasLimit = 21000n;
161
+ try {
162
+ const fees = await publicClient.estimateFeesPerGas();
163
+ if (fees.maxFeePerGas) {
164
+ return gasLimit * fees.maxFeePerGas;
165
+ }
166
+ } catch (err) {
167
+ // chain without eip-1559 support, fall through to gas price
168
+ }
169
+ try {
170
+ const gasPrice = await publicClient.getGasPrice();
171
+ return gasLimit * gasPrice;
172
+ } catch (err) {
173
+ return 0n;
174
+ }
175
+ }