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.
- package/dist/esm/api/index.d.ts +51 -16
- package/dist/esm/api/index.d.ts.map +1 -1
- package/dist/esm/api/index.js +567 -79
- package/dist/esm/api/index.js.map +1 -1
- package/dist/esm/calls.d.ts +107 -0
- package/dist/esm/calls.d.ts.map +1 -0
- package/dist/esm/calls.js +304 -0
- package/dist/esm/calls.js.map +1 -0
- package/dist/esm/captcha.d.ts +28 -0
- package/dist/esm/captcha.d.ts.map +1 -0
- package/dist/esm/captcha.js +58 -0
- package/dist/esm/captcha.js.map +1 -0
- package/dist/esm/chains.d.ts +17552 -0
- package/dist/esm/chains.d.ts.map +1 -0
- package/dist/esm/chains.js +137 -0
- package/dist/esm/chains.js.map +1 -0
- package/dist/esm/config.d.ts +12 -0
- package/dist/esm/config.d.ts.map +1 -0
- package/dist/esm/config.js +28 -0
- package/dist/esm/config.js.map +1 -0
- package/dist/esm/env.d.ts +56 -0
- package/dist/esm/env.d.ts.map +1 -1
- package/dist/esm/env.js +81 -1
- package/dist/esm/env.js.map +1 -1
- package/dist/esm/index.d.ts +135 -42
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +39 -16
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/schema/ts/db.sql.d.ts +1 -1
- package/dist/esm/schema/ts/db.sql.d.ts.map +1 -1
- package/dist/esm/schema/ts/db.sql.js +25 -4
- package/dist/esm/schema/ts/db.sql.js.map +1 -1
- package/dist/esm/setup.d.ts +2 -0
- package/dist/esm/setup.d.ts.map +1 -1
- package/dist/esm/setup.js +25 -7
- package/dist/esm/setup.js.map +1 -1
- package/dist/esm/storage/RemoteSQLStorage.d.ts +49 -0
- package/dist/esm/storage/RemoteSQLStorage.d.ts.map +1 -0
- package/dist/esm/storage/RemoteSQLStorage.js +158 -0
- package/dist/esm/storage/RemoteSQLStorage.js.map +1 -0
- package/package.json +1 -1
- package/src/api/index.ts +752 -105
- package/src/calls.ts +447 -0
- package/src/captcha.ts +92 -0
- package/src/chains.ts +175 -0
- package/src/config.ts +33 -0
- package/src/env.ts +129 -0
- package/src/index.ts +60 -18
- package/src/schema/sql/db.sql +25 -4
- package/src/schema/ts/db.sql.ts +25 -4
- package/src/setup.ts +28 -11
- package/src/storage/RemoteSQLStorage.ts +252 -0
package/dist/esm/api/index.js
CHANGED
|
@@ -1,35 +1,89 @@
|
|
|
1
1
|
import { Hono } from 'hono';
|
|
2
2
|
import { setup } from '../setup.js';
|
|
3
|
-
import {
|
|
3
|
+
import { CHAIN_LOCK_TIMEOUT_SECONDS, CLAIM_RETENTION_SECONDS, USED_TOKEN_RETENTION_SECONDS, getBigIntEnv, getCooldowns, } from '../env.js';
|
|
4
|
+
import { isAddress } from 'viem';
|
|
4
5
|
import { privateKeyToAccount } from 'viem/accounts';
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
6
|
+
import { estimateTransferCost, feePerGas, getChainConfig, getFeeParams, getPublicClient, getWalletClient, parseChainId, } from '../chains.js';
|
|
7
|
+
import { hashToken, verifyProsopoCaptcha } from '../captcha.js';
|
|
8
|
+
import { getArbitraryCallsMode, getCallAllowlist, getCallLimits, isCallAllowed, parseCallRequest, planGas, } from '../calls.js';
|
|
9
|
+
/**
|
|
10
|
+
* Burns the captcha token so it cannot be replayed, then verifies it with the
|
|
11
|
+
* provider. Shared by /claim and /execute. Returns null when the caller may
|
|
12
|
+
* proceed. A disabled captcha skips both.
|
|
13
|
+
*/
|
|
14
|
+
async function checkCaptcha(params) {
|
|
15
|
+
const { env, storage, token, ip, now } = params;
|
|
16
|
+
if (env.DISABLE_CAPTCHA === 'true') {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
const tokenHash = await hashToken(token);
|
|
20
|
+
const fresh = await storage.burnToken(tokenHash, now);
|
|
21
|
+
if (!fresh) {
|
|
22
|
+
return { error: 'Captcha token already used', status: 401 };
|
|
23
|
+
}
|
|
24
|
+
const verification = await verifyProsopoCaptcha(token, env.PROSOPO_SITE_PRIVATE_KEY, {
|
|
25
|
+
failOpen: env.CAPTCHA_FAIL_OPEN === 'true',
|
|
26
|
+
ip: ip || undefined,
|
|
17
27
|
});
|
|
18
|
-
|
|
19
|
-
|
|
28
|
+
if (!verification.ok) {
|
|
29
|
+
if (verification.reason === 'unavailable') {
|
|
30
|
+
console.error(`captcha unavailable: ${verification.details}`);
|
|
31
|
+
return {
|
|
32
|
+
error: 'Captcha verification is temporarily unavailable, please try again later',
|
|
33
|
+
status: 503,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
return { error: 'Captcha verification failed', status: 401 };
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
20
39
|
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
40
|
+
const TX_HASH_REGEX = /^0x[0-9a-fA-F]{64}$/;
|
|
41
|
+
/**
|
|
42
|
+
* Best effort ip of the caller, used as a rate limiting bucket.
|
|
43
|
+
* Returns '' when the server sits behind no proxy that tells us: in that case
|
|
44
|
+
* the ip bucket is skipped entirely rather than lumping every user together.
|
|
45
|
+
*/
|
|
46
|
+
function getClientIp(c) {
|
|
47
|
+
const headers = ['cf-connecting-ip', 'x-real-ip', 'x-forwarded-for'];
|
|
48
|
+
for (const header of headers) {
|
|
49
|
+
const value = c.req.header(header);
|
|
50
|
+
if (value) {
|
|
51
|
+
// x-forwarded-for is a list, the left most entry is the client
|
|
52
|
+
const ip = value.split(',')[0].trim();
|
|
53
|
+
if (ip) {
|
|
54
|
+
return ip;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
26
57
|
}
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
58
|
+
return '';
|
|
59
|
+
}
|
|
60
|
+
// Waits for the per chain send lock instead of turning the caller away: a
|
|
61
|
+
// dispense takes a few hundred milliseconds, so concurrent claims queue rather
|
|
62
|
+
// than fail. Gives up after LOCK_WAIT_MS so a request never hangs.
|
|
63
|
+
const LOCK_WAIT_MS = 12000;
|
|
64
|
+
const LOCK_RETRY_INTERVAL_MS = 300;
|
|
65
|
+
async function acquireChainLockWaiting(storage, chainId) {
|
|
66
|
+
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
67
|
+
for (;;) {
|
|
68
|
+
const now = Math.floor(Date.now() / 1000);
|
|
69
|
+
const lock = await storage.acquireChainLock(chainId, now, now + CHAIN_LOCK_TIMEOUT_SECONDS);
|
|
70
|
+
if (lock.acquired || Date.now() >= deadline) {
|
|
71
|
+
return lock;
|
|
72
|
+
}
|
|
73
|
+
await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_INTERVAL_MS));
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
// Runs a promise outside of the response path, on platforms that support it.
|
|
77
|
+
function background(c, promise) {
|
|
78
|
+
const safe = promise.catch((err) => {
|
|
79
|
+
console.error('background task failed', err);
|
|
80
|
+
});
|
|
81
|
+
try {
|
|
82
|
+
c.executionCtx.waitUntil(safe);
|
|
83
|
+
}
|
|
84
|
+
catch (err) {
|
|
85
|
+
// no execution context (node), the promise just runs on its own
|
|
31
86
|
}
|
|
32
|
-
return { amount, rpcUrl };
|
|
33
87
|
}
|
|
34
88
|
export function getAPI(options) {
|
|
35
89
|
const app = new Hono()
|
|
@@ -38,47 +92,103 @@ export function getAPI(options) {
|
|
|
38
92
|
const config = c.get('config');
|
|
39
93
|
const env = config.env;
|
|
40
94
|
const captchaDisabled = env.DISABLE_CAPTCHA === 'true';
|
|
41
|
-
|
|
95
|
+
const modeLookup = getArbitraryCallsMode(env);
|
|
96
|
+
if (modeLookup.status === 'invalid') {
|
|
97
|
+
// same answer as /execute gives, rather than quietly reporting 'off'
|
|
98
|
+
// for a mode the operator clearly meant to set
|
|
99
|
+
console.error(`invalid ENABLE_ARBITRARY_CALLS: "${env.ENABLE_ARBITRARY_CALLS}"`);
|
|
100
|
+
return c.json({ error: 'Faucet misconfigured' }, 500);
|
|
101
|
+
}
|
|
102
|
+
const mode = modeLookup.mode;
|
|
103
|
+
// only advertised when enabled, so a faucet that never turns this on
|
|
104
|
+
// answers exactly what it always did
|
|
105
|
+
if (mode === 'off') {
|
|
106
|
+
return c.json({ captchaDisabled });
|
|
107
|
+
}
|
|
108
|
+
// the address a call is signed by is what the user is really lending,
|
|
109
|
+
// so the popup can show it. It is public: every dispensed transaction
|
|
110
|
+
// carries it as the sender.
|
|
111
|
+
let faucetAddress;
|
|
112
|
+
try {
|
|
113
|
+
faucetAddress = privateKeyToAccount(env.FAUCET_PRIVATE_KEY).address;
|
|
114
|
+
}
|
|
115
|
+
catch (err) {
|
|
116
|
+
// a missing or malformed key is reported by the claim path instead
|
|
117
|
+
}
|
|
118
|
+
return c.json({ captchaDisabled, arbitraryCalls: mode, faucetAddress });
|
|
42
119
|
})
|
|
43
120
|
.get('/chain/:chainId', async (c) => {
|
|
44
121
|
const config = c.get('config');
|
|
45
122
|
const env = config.env;
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
const chainIdNum = parseInt(chainId, 10);
|
|
49
|
-
if (isNaN(chainIdNum) || chainIdNum <= 0) {
|
|
123
|
+
const chainIdNum = parseChainId(c.req.param('chainId'));
|
|
124
|
+
if (chainIdNum === null) {
|
|
50
125
|
return c.json({ error: 'Invalid chainId' }, 400);
|
|
51
126
|
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
if (!chainConfigValue) {
|
|
56
|
-
return c.json({ error: `Faucet not configured for chain ${chainId}` }, 404);
|
|
127
|
+
const lookup = getChainConfig(env, chainIdNum);
|
|
128
|
+
if (lookup.status === 'not-configured') {
|
|
129
|
+
return c.json({ error: `Faucet not configured for chain ${chainIdNum}` }, 404);
|
|
57
130
|
}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
return c.json({ error: `
|
|
131
|
+
if (lookup.status === 'invalid') {
|
|
132
|
+
console.error(`invalid config for chain ${chainIdNum}: ${lookup.details}`);
|
|
133
|
+
return c.json({ error: `Faucet misconfigured` }, 500);
|
|
61
134
|
}
|
|
62
|
-
|
|
135
|
+
// Note: the rpc endpoint is deliberately NOT returned, it is a server
|
|
136
|
+
// side secret. Clients follow their transaction through /tx instead.
|
|
137
|
+
return c.json({
|
|
138
|
+
chainId: chainIdNum,
|
|
139
|
+
amount: lookup.config.amount.toString(),
|
|
140
|
+
});
|
|
63
141
|
})
|
|
64
|
-
.
|
|
142
|
+
.get('/tx/:chainId/:txHash', async (c) => {
|
|
65
143
|
const config = c.get('config');
|
|
66
144
|
const env = config.env;
|
|
67
|
-
|
|
145
|
+
const chainIdNum = parseChainId(c.req.param('chainId'));
|
|
146
|
+
if (chainIdNum === null) {
|
|
147
|
+
return c.json({ error: 'Invalid chainId' }, 400);
|
|
148
|
+
}
|
|
149
|
+
const txHash = c.req.param('txHash');
|
|
150
|
+
if (!TX_HASH_REGEX.test(txHash)) {
|
|
151
|
+
return c.json({ error: 'Invalid transaction hash' }, 400);
|
|
152
|
+
}
|
|
153
|
+
const lookup = getChainConfig(env, chainIdNum);
|
|
154
|
+
if (lookup.status !== 'ok') {
|
|
155
|
+
return c.json({ error: `Faucet not configured for chain ${chainIdNum}` }, 404);
|
|
156
|
+
}
|
|
157
|
+
const publicClient = getPublicClient(lookup.config);
|
|
158
|
+
try {
|
|
159
|
+
const receipt = await publicClient.getTransactionReceipt({
|
|
160
|
+
hash: txHash,
|
|
161
|
+
});
|
|
162
|
+
return c.json({
|
|
163
|
+
status: receipt.status === 'success' ? 'success' : 'failed',
|
|
164
|
+
blockNumber: receipt.blockNumber.toString(),
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
catch (err) {
|
|
168
|
+
// viem throws when the receipt is not available yet
|
|
169
|
+
return c.json({ status: 'pending' });
|
|
170
|
+
}
|
|
171
|
+
})
|
|
172
|
+
.post('/claim', async (c) => {
|
|
173
|
+
const config = c.get('config');
|
|
174
|
+
const { env, storage } = config;
|
|
68
175
|
const captchaDisabled = env.DISABLE_CAPTCHA === 'true';
|
|
69
|
-
// Validate PROSOPO secret (only required if captcha is enabled)
|
|
70
176
|
const secret = env.PROSOPO_SITE_PRIVATE_KEY;
|
|
71
177
|
if (!captchaDisabled && !secret) {
|
|
72
178
|
return c.json({ error: 'PROSOPO_SITE_PRIVATE_KEY not configured' }, 500);
|
|
73
179
|
}
|
|
74
|
-
// Validate FAUCET_PRIVATE_KEY
|
|
75
180
|
const faucetPrivateKey = env.FAUCET_PRIVATE_KEY;
|
|
76
181
|
if (!faucetPrivateKey) {
|
|
77
182
|
return c.json({ error: 'FAUCET_PRIVATE_KEY not configured' }, 500);
|
|
78
183
|
}
|
|
79
|
-
|
|
184
|
+
let body;
|
|
185
|
+
try {
|
|
186
|
+
body = await c.req.json();
|
|
187
|
+
}
|
|
188
|
+
catch (err) {
|
|
189
|
+
return c.json({ error: 'Invalid JSON body' }, 400);
|
|
190
|
+
}
|
|
80
191
|
const { token, chainId, address } = body;
|
|
81
|
-
// Validate required fields
|
|
82
192
|
if (!token) {
|
|
83
193
|
return c.json({ error: 'Missing token' }, 400);
|
|
84
194
|
}
|
|
@@ -88,62 +198,440 @@ export function getAPI(options) {
|
|
|
88
198
|
if (!address) {
|
|
89
199
|
return c.json({ error: 'Missing address' }, 400);
|
|
90
200
|
}
|
|
91
|
-
// Validate address format
|
|
92
201
|
if (!isAddress(address)) {
|
|
93
202
|
return c.json({ error: 'Invalid Ethereum address' }, 400);
|
|
94
203
|
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
if (isNaN(chainIdNum) || chainIdNum <= 0) {
|
|
204
|
+
const chainIdNum = parseChainId(chainId);
|
|
205
|
+
if (chainIdNum === null) {
|
|
98
206
|
return c.json({ error: 'Invalid chainId' }, 400);
|
|
99
207
|
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
208
|
+
const lookup = getChainConfig(env, chainIdNum);
|
|
209
|
+
if (lookup.status === 'not-configured') {
|
|
210
|
+
return c.json({ error: `Faucet not configured for chain ${chainIdNum}` }, 400);
|
|
211
|
+
}
|
|
212
|
+
if (lookup.status === 'invalid') {
|
|
213
|
+
console.error(`invalid config for chain ${chainIdNum}: ${lookup.details}`);
|
|
214
|
+
return c.json({ error: 'Faucet misconfigured' }, 500);
|
|
105
215
|
}
|
|
106
|
-
const chainConfig =
|
|
107
|
-
|
|
216
|
+
const chainConfig = lookup.config;
|
|
217
|
+
// ---------------------------------------------------------------
|
|
218
|
+
// 0. the limits this faucet runs under. Parsed up front, before any
|
|
219
|
+
// network work: a typo in one of them is a refusal, never a
|
|
220
|
+
// quietly weaker limit.
|
|
221
|
+
// ---------------------------------------------------------------
|
|
222
|
+
const maxRecipientBalanceEnv = getBigIntEnv(env.MAX_RECIPIENT_BALANCE);
|
|
223
|
+
if (maxRecipientBalanceEnv.status === 'invalid') {
|
|
224
|
+
console.error(`MAX_RECIPIENT_BALANCE is not a wei amount: "${env.MAX_RECIPIENT_BALANCE}"`);
|
|
225
|
+
return c.json({ error: 'Faucet misconfigured' }, 500);
|
|
226
|
+
}
|
|
227
|
+
const maxRecipientBalance = maxRecipientBalanceEnv.status === 'ok'
|
|
228
|
+
? maxRecipientBalanceEnv.value
|
|
229
|
+
: chainConfig.amount * 10n;
|
|
230
|
+
const cooldowns = getCooldowns(env);
|
|
231
|
+
if (cooldowns.status === 'invalid') {
|
|
232
|
+
console.error(cooldowns.details);
|
|
233
|
+
return c.json({ error: 'Faucet misconfigured' }, 500);
|
|
234
|
+
}
|
|
235
|
+
const { addressCooldown, ipCooldown } = cooldowns;
|
|
236
|
+
const now = Math.floor(Date.now() / 1000);
|
|
237
|
+
const ip = getClientIp(c);
|
|
238
|
+
const normalizedAddress = address.toLowerCase();
|
|
239
|
+
const chainIdKey = String(chainIdNum);
|
|
240
|
+
// ---------------------------------------------------------------
|
|
241
|
+
// 1. captcha: single use token, then provider verification
|
|
242
|
+
// ---------------------------------------------------------------
|
|
243
|
+
const refusal = await checkCaptcha({ env, storage, token, ip, now });
|
|
244
|
+
if (refusal) {
|
|
245
|
+
return c.json({ error: refusal.error }, refusal.status);
|
|
246
|
+
}
|
|
247
|
+
const publicClient = getPublicClient(chainConfig);
|
|
248
|
+
// ---------------------------------------------------------------
|
|
249
|
+
// 2. do not top up an address that already holds enough
|
|
250
|
+
// ---------------------------------------------------------------
|
|
251
|
+
if (maxRecipientBalance > 0n) {
|
|
252
|
+
try {
|
|
253
|
+
const recipientBalance = await publicClient.getBalance({
|
|
254
|
+
address: address,
|
|
255
|
+
});
|
|
256
|
+
if (recipientBalance >= maxRecipientBalance) {
|
|
257
|
+
return c.json({
|
|
258
|
+
error: 'This address already holds enough funds on this chain, the faucet is for empty accounts',
|
|
259
|
+
}, 400);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
catch (err) {
|
|
263
|
+
console.error('could not read recipient balance', err);
|
|
264
|
+
return c.json({ error: 'Could not reach the chain rpc' }, 503);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
// ---------------------------------------------------------------
|
|
268
|
+
// 3. rate limit: atomically reserve a slot for this address / ip
|
|
269
|
+
// ---------------------------------------------------------------
|
|
270
|
+
const claimId = await storage.reserveClaim({
|
|
271
|
+
chainId: chainIdKey,
|
|
272
|
+
address: normalizedAddress,
|
|
273
|
+
ip,
|
|
274
|
+
amount: chainConfig.amount.toString(),
|
|
275
|
+
now,
|
|
276
|
+
addressCutoff: now - addressCooldown,
|
|
277
|
+
ipCutoff: now - ipCooldown,
|
|
278
|
+
});
|
|
279
|
+
if (claimId === null) {
|
|
280
|
+
const hit = await storage.getRateLimitHit({
|
|
281
|
+
chainId: chainIdKey,
|
|
282
|
+
address: normalizedAddress,
|
|
283
|
+
ip,
|
|
284
|
+
now,
|
|
285
|
+
addressCutoff: now - addressCooldown,
|
|
286
|
+
ipCutoff: now - ipCooldown,
|
|
287
|
+
addressCooldown,
|
|
288
|
+
ipCooldown,
|
|
289
|
+
});
|
|
290
|
+
const subject = hit.reason === 'address' ? 'This address' : 'You';
|
|
108
291
|
return c.json({
|
|
109
|
-
error:
|
|
110
|
-
|
|
292
|
+
error: `${subject} already claimed recently, please wait ${formatDuration(hit.retryAfter)}`,
|
|
293
|
+
retryAfter: hit.retryAfter,
|
|
294
|
+
}, 429, { 'Retry-After': String(hit.retryAfter) });
|
|
111
295
|
}
|
|
112
|
-
//
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
296
|
+
// From here on, any failure must give the reservation back.
|
|
297
|
+
const abort = async (message, status) => {
|
|
298
|
+
await storage.cancelClaim(claimId).catch((err) => {
|
|
299
|
+
console.error('could not cancel claim reservation', err);
|
|
300
|
+
});
|
|
301
|
+
return c.json({ error: message }, status);
|
|
302
|
+
};
|
|
303
|
+
const account = privateKeyToAccount(faucetPrivateKey);
|
|
304
|
+
// ---------------------------------------------------------------
|
|
305
|
+
// 4. can the faucet still pay?
|
|
306
|
+
// ---------------------------------------------------------------
|
|
307
|
+
try {
|
|
308
|
+
const faucetBalance = await publicClient.getBalance({
|
|
309
|
+
address: account.address,
|
|
310
|
+
});
|
|
311
|
+
const gasCost = await estimateTransferCost(publicClient);
|
|
312
|
+
if (faucetBalance < chainConfig.amount + gasCost) {
|
|
313
|
+
console.error(`faucet ${account.address} is out of funds on chain ${chainIdNum}: balance ${faucetBalance}, needs ${chainConfig.amount + gasCost}`);
|
|
314
|
+
return abort('The faucet is temporarily out of funds, please try again later', 503);
|
|
117
315
|
}
|
|
118
316
|
}
|
|
317
|
+
catch (err) {
|
|
318
|
+
console.error('could not check faucet balance', err);
|
|
319
|
+
return abort('Could not reach the chain rpc', 503);
|
|
320
|
+
}
|
|
321
|
+
// ---------------------------------------------------------------
|
|
322
|
+
// 5. serialise sending so concurrent claims cannot reuse a nonce
|
|
323
|
+
// ---------------------------------------------------------------
|
|
324
|
+
const lock = await acquireChainLockWaiting(storage, chainIdKey);
|
|
325
|
+
if (!lock.acquired) {
|
|
326
|
+
return abort('The faucet is busy dispensing other claims, please try again in a few seconds', 503);
|
|
327
|
+
}
|
|
328
|
+
let nonceUsed = null;
|
|
119
329
|
try {
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
const walletClient = createWalletClient({
|
|
124
|
-
account,
|
|
125
|
-
chain: {
|
|
126
|
-
id: chainIdNum,
|
|
127
|
-
name: `Chain ${chainIdNum}`,
|
|
128
|
-
nativeCurrency: { name: 'ETH', symbol: 'ETH', decimals: 18 },
|
|
129
|
-
rpcUrls: {
|
|
130
|
-
default: { http: [rpcUrl] },
|
|
131
|
-
},
|
|
132
|
-
},
|
|
133
|
-
transport: http(rpcUrl),
|
|
330
|
+
const pendingNonce = await publicClient.getTransactionCount({
|
|
331
|
+
address: account.address,
|
|
332
|
+
blockTag: 'pending',
|
|
134
333
|
});
|
|
334
|
+
// the chain is the source of truth, our own counter only guards
|
|
335
|
+
// against two claims reading the same pending nonce
|
|
336
|
+
const nonce = lock.lastNonce === null
|
|
337
|
+
? pendingNonce
|
|
338
|
+
: Math.max(lock.lastNonce + 1, pendingNonce);
|
|
339
|
+
const walletClient = getWalletClient(chainConfig, account);
|
|
135
340
|
const txHash = await walletClient.sendTransaction({
|
|
136
341
|
to: address,
|
|
137
|
-
value:
|
|
342
|
+
value: chainConfig.amount,
|
|
343
|
+
nonce,
|
|
138
344
|
});
|
|
345
|
+
nonceUsed = nonce;
|
|
346
|
+
await storage.releaseChainLock(chainIdKey, nonceUsed);
|
|
347
|
+
await storage.recordClaimTx(claimId, txHash);
|
|
348
|
+
background(c, storage.cleanup(now - USED_TOKEN_RETENTION_SECONDS, now - CLAIM_RETENTION_SECONDS));
|
|
139
349
|
return c.json({ success: true, txHash });
|
|
140
350
|
}
|
|
141
351
|
catch (err) {
|
|
142
352
|
console.error('Transaction error:', err);
|
|
353
|
+
await storage.releaseChainLock(chainIdKey, nonceUsed).catch((e) => {
|
|
354
|
+
console.error('could not release chain lock', e);
|
|
355
|
+
});
|
|
143
356
|
const errorMessage = err instanceof Error ? err.message : 'Transaction failed';
|
|
144
|
-
return
|
|
357
|
+
return abort(errorMessage, 500);
|
|
358
|
+
}
|
|
359
|
+
})
|
|
360
|
+
/**
|
|
361
|
+
* Executes a caller chosen call, paid for by the faucet.
|
|
362
|
+
*
|
|
363
|
+
* Off unless ENABLE_ARBITRARY_CALLS says otherwise, because this lends the
|
|
364
|
+
* faucet key's authority to whoever passes the captcha. See
|
|
365
|
+
* docs/specs/arbitrary-calls.md for the threat model.
|
|
366
|
+
*/
|
|
367
|
+
.post('/execute', async (c) => {
|
|
368
|
+
const config = c.get('config');
|
|
369
|
+
const { env, storage } = config;
|
|
370
|
+
const modeLookup = getArbitraryCallsMode(env);
|
|
371
|
+
if (modeLookup.status === 'invalid') {
|
|
372
|
+
console.error(`invalid ENABLE_ARBITRARY_CALLS: "${env.ENABLE_ARBITRARY_CALLS}"`);
|
|
373
|
+
return c.json({ error: 'Faucet misconfigured' }, 500);
|
|
374
|
+
}
|
|
375
|
+
const mode = modeLookup.mode;
|
|
376
|
+
if (mode === 'off') {
|
|
377
|
+
return c.json({ error: 'Arbitrary calls are not enabled on this faucet' }, 404);
|
|
378
|
+
}
|
|
379
|
+
const captchaDisabled = env.DISABLE_CAPTCHA === 'true';
|
|
380
|
+
const secret = env.PROSOPO_SITE_PRIVATE_KEY;
|
|
381
|
+
if (!captchaDisabled && !secret) {
|
|
382
|
+
return c.json({ error: 'PROSOPO_SITE_PRIVATE_KEY not configured' }, 500);
|
|
383
|
+
}
|
|
384
|
+
const faucetPrivateKey = env.FAUCET_PRIVATE_KEY;
|
|
385
|
+
if (!faucetPrivateKey) {
|
|
386
|
+
return c.json({ error: 'FAUCET_PRIVATE_KEY not configured' }, 500);
|
|
387
|
+
}
|
|
388
|
+
let body;
|
|
389
|
+
try {
|
|
390
|
+
body = await c.req.json();
|
|
391
|
+
}
|
|
392
|
+
catch (err) {
|
|
393
|
+
return c.json({ error: 'Invalid JSON body' }, 400);
|
|
394
|
+
}
|
|
395
|
+
const { token, chainId } = body;
|
|
396
|
+
if (!token && !captchaDisabled) {
|
|
397
|
+
return c.json({ error: 'Missing token' }, 400);
|
|
398
|
+
}
|
|
399
|
+
if (!chainId) {
|
|
400
|
+
return c.json({ error: 'Missing chainId' }, 400);
|
|
401
|
+
}
|
|
402
|
+
const chainIdNum = parseChainId(chainId);
|
|
403
|
+
if (chainIdNum === null) {
|
|
404
|
+
return c.json({ error: 'Invalid chainId' }, 400);
|
|
405
|
+
}
|
|
406
|
+
const parsed = parseCallRequest(body);
|
|
407
|
+
if (parsed.status === 'invalid') {
|
|
408
|
+
return c.json({ error: parsed.error }, 400);
|
|
409
|
+
}
|
|
410
|
+
const { to, data, value } = parsed.call;
|
|
411
|
+
const lookup = getChainConfig(env, chainIdNum);
|
|
412
|
+
if (lookup.status === 'not-configured') {
|
|
413
|
+
return c.json({ error: `Faucet not configured for chain ${chainIdNum}` }, 400);
|
|
414
|
+
}
|
|
415
|
+
if (lookup.status === 'invalid') {
|
|
416
|
+
console.error(`invalid config for chain ${chainIdNum}: ${lookup.details}`);
|
|
417
|
+
return c.json({ error: 'Faucet misconfigured' }, 500);
|
|
418
|
+
}
|
|
419
|
+
const chainConfig = lookup.config;
|
|
420
|
+
// parsed before any network work, so a typo in a limit is a refusal
|
|
421
|
+
const cooldowns = getCooldowns(env);
|
|
422
|
+
if (cooldowns.status === 'invalid') {
|
|
423
|
+
console.error(cooldowns.details);
|
|
424
|
+
return c.json({ error: 'Faucet misconfigured' }, 500);
|
|
425
|
+
}
|
|
426
|
+
const { addressCooldown, ipCooldown } = cooldowns;
|
|
427
|
+
// ---------------------------------------------------------------
|
|
428
|
+
// 1. is this call permitted at all
|
|
429
|
+
// ---------------------------------------------------------------
|
|
430
|
+
if (mode === 'allowlist') {
|
|
431
|
+
const allowlistLookup = getCallAllowlist(env, chainIdNum);
|
|
432
|
+
if (allowlistLookup.status !== 'ok') {
|
|
433
|
+
console.error(`CALL_ALLOWLIST_${chainIdNum} is ${allowlistLookup.status === 'invalid'
|
|
434
|
+
? `invalid: ${allowlistLookup.details}`
|
|
435
|
+
: 'not set, every call on this chain is refused'}`);
|
|
436
|
+
return c.json({ error: 'Faucet misconfigured' }, 500);
|
|
437
|
+
}
|
|
438
|
+
if (!isCallAllowed(allowlistLookup.allowlist, to, data)) {
|
|
439
|
+
return c.json({
|
|
440
|
+
error: 'This faucet does not allow that contract and function combination',
|
|
441
|
+
}, 400);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
const now = Math.floor(Date.now() / 1000);
|
|
445
|
+
const ip = getClientIp(c);
|
|
446
|
+
const chainIdKey = String(chainIdNum);
|
|
447
|
+
// `to` is a shared contract, so it cannot be a rate limiting key: the ip
|
|
448
|
+
// is the only one this endpoint has. Without it there is no limit at
|
|
449
|
+
// all, so an unknown ip is refused rather than served.
|
|
450
|
+
if (!captchaDisabled && ip === '') {
|
|
451
|
+
console.error('refusing /execute: no client ip, so no rate limit would apply. Put the server behind a proxy that sets X-Forwarded-For.');
|
|
452
|
+
return c.json({
|
|
453
|
+
error: 'This faucet cannot determine your ip, and refuses to execute calls it cannot rate limit',
|
|
454
|
+
}, 503);
|
|
455
|
+
}
|
|
456
|
+
// ---------------------------------------------------------------
|
|
457
|
+
// 2. captcha: single use token, then provider verification
|
|
458
|
+
// ---------------------------------------------------------------
|
|
459
|
+
const refusal = await checkCaptcha({ env, storage, token, ip, now });
|
|
460
|
+
if (refusal) {
|
|
461
|
+
return c.json({ error: refusal.error }, refusal.status);
|
|
462
|
+
}
|
|
463
|
+
// ---------------------------------------------------------------
|
|
464
|
+
// 3. rate limit, on the ip alone. A disabled captcha means localhost,
|
|
465
|
+
// where every account shares one ip, so the bucket is skipped.
|
|
466
|
+
// ---------------------------------------------------------------
|
|
467
|
+
let claimId = null;
|
|
468
|
+
if (!captchaDisabled) {
|
|
469
|
+
// an empty address disables the address bucket, see RemoteSQLStorage
|
|
470
|
+
claimId = await storage.reserveClaim({
|
|
471
|
+
chainId: chainIdKey,
|
|
472
|
+
address: '',
|
|
473
|
+
ip,
|
|
474
|
+
amount: value.toString(),
|
|
475
|
+
now,
|
|
476
|
+
addressCutoff: now,
|
|
477
|
+
ipCutoff: now - ipCooldown,
|
|
478
|
+
});
|
|
479
|
+
if (claimId === null) {
|
|
480
|
+
const hit = await storage.getRateLimitHit({
|
|
481
|
+
chainId: chainIdKey,
|
|
482
|
+
address: '',
|
|
483
|
+
ip,
|
|
484
|
+
now,
|
|
485
|
+
addressCutoff: now,
|
|
486
|
+
ipCutoff: now - ipCooldown,
|
|
487
|
+
addressCooldown,
|
|
488
|
+
ipCooldown,
|
|
489
|
+
});
|
|
490
|
+
return c.json({
|
|
491
|
+
error: `You already used this faucet recently, try again in ${formatDuration(hit.retryAfter)}`,
|
|
492
|
+
retryAfter: hit.retryAfter,
|
|
493
|
+
}, 429, { 'Retry-After': String(hit.retryAfter) });
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
// From here on, any failure must give the reservation back.
|
|
497
|
+
const reservedId = claimId;
|
|
498
|
+
const abort = async (message, status) => {
|
|
499
|
+
if (reservedId !== null) {
|
|
500
|
+
await storage.cancelClaim(reservedId).catch((err) => {
|
|
501
|
+
console.error('could not cancel claim reservation', err);
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
return c.json({ error: message }, status);
|
|
505
|
+
};
|
|
506
|
+
const publicClient = getPublicClient(chainConfig);
|
|
507
|
+
const account = privateKeyToAccount(faucetPrivateKey);
|
|
508
|
+
// ---------------------------------------------------------------
|
|
509
|
+
// 4. budget: turn a wei ceiling into a gas limit
|
|
510
|
+
// ---------------------------------------------------------------
|
|
511
|
+
// ONE fee reading feeds the budget, the division and the transaction:
|
|
512
|
+
// re-reading would let a bare transfer fail on a fee tick.
|
|
513
|
+
let fees;
|
|
514
|
+
try {
|
|
515
|
+
fees = await getFeeParams(publicClient);
|
|
516
|
+
}
|
|
517
|
+
catch (err) {
|
|
518
|
+
console.error('could not read gas price', err);
|
|
519
|
+
return abort('Could not reach the chain rpc', 503);
|
|
520
|
+
}
|
|
521
|
+
const fee = feePerGas(fees);
|
|
522
|
+
const limitsLookup = getCallLimits(env, chainConfig, fee);
|
|
523
|
+
if (limitsLookup.status === 'invalid') {
|
|
524
|
+
console.error(`invalid call limits: ${limitsLookup.details}`);
|
|
525
|
+
return abort('Faucet misconfigured', 500);
|
|
526
|
+
}
|
|
527
|
+
const limits = limitsLookup.limits;
|
|
528
|
+
if (value > limits.maxValue) {
|
|
529
|
+
return abort(`This faucet sends at most ${limits.maxValue} wei with a call, asked for ${value}`, 400);
|
|
530
|
+
}
|
|
531
|
+
// A revert is free here. Refusing now also avoids broadcasting a call
|
|
532
|
+
// that would run out of gas, which would burn the whole limit.
|
|
533
|
+
let estimated;
|
|
534
|
+
try {
|
|
535
|
+
estimated = await publicClient.estimateGas({
|
|
536
|
+
account,
|
|
537
|
+
to,
|
|
538
|
+
data,
|
|
539
|
+
value,
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
catch (err) {
|
|
543
|
+
const details = err instanceof Error && 'shortMessage' in err
|
|
544
|
+
? String(err.shortMessage)
|
|
545
|
+
: err instanceof Error
|
|
546
|
+
? err.message
|
|
547
|
+
: 'unknown error';
|
|
548
|
+
return abort(`This call cannot be executed: ${details}`, 400);
|
|
549
|
+
}
|
|
550
|
+
const plan = planGas({ limits, value, estimated, feePerGas: fee });
|
|
551
|
+
if (plan.status === 'does-not-fit') {
|
|
552
|
+
return abort(plan.details, 400);
|
|
553
|
+
}
|
|
554
|
+
// ---------------------------------------------------------------
|
|
555
|
+
// 5. can the faucet still pay the worst case?
|
|
556
|
+
// ---------------------------------------------------------------
|
|
557
|
+
try {
|
|
558
|
+
const faucetBalance = await publicClient.getBalance({
|
|
559
|
+
address: account.address,
|
|
560
|
+
});
|
|
561
|
+
if (faucetBalance < plan.ceiling) {
|
|
562
|
+
console.error(`faucet ${account.address} is out of funds on chain ${chainIdNum}: balance ${faucetBalance}, needs ${plan.ceiling}`);
|
|
563
|
+
return abort('The faucet is temporarily out of funds, please try again later', 503);
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
catch (err) {
|
|
567
|
+
console.error('could not check faucet balance', err);
|
|
568
|
+
return abort('Could not reach the chain rpc', 503);
|
|
569
|
+
}
|
|
570
|
+
// ---------------------------------------------------------------
|
|
571
|
+
// 6. serialise sending so concurrent calls cannot reuse a nonce
|
|
572
|
+
// ---------------------------------------------------------------
|
|
573
|
+
const lock = await acquireChainLockWaiting(storage, chainIdKey);
|
|
574
|
+
if (!lock.acquired) {
|
|
575
|
+
return abort('The faucet is busy dispensing other claims, please try again in a few seconds', 503);
|
|
576
|
+
}
|
|
577
|
+
let nonceUsed = null;
|
|
578
|
+
try {
|
|
579
|
+
const pendingNonce = await publicClient.getTransactionCount({
|
|
580
|
+
address: account.address,
|
|
581
|
+
blockTag: 'pending',
|
|
582
|
+
});
|
|
583
|
+
const nonce = lock.lastNonce === null
|
|
584
|
+
? pendingNonce
|
|
585
|
+
: Math.max(lock.lastNonce + 1, pendingNonce);
|
|
586
|
+
const walletClient = getWalletClient(chainConfig, account);
|
|
587
|
+
// gas and fee are both explicit: the ceiling is only a real bound
|
|
588
|
+
// because the server picked both numbers.
|
|
589
|
+
const txHash = fees.type === 'eip1559'
|
|
590
|
+
? await walletClient.sendTransaction({
|
|
591
|
+
to,
|
|
592
|
+
data,
|
|
593
|
+
value,
|
|
594
|
+
nonce,
|
|
595
|
+
gas: plan.gasLimit,
|
|
596
|
+
maxFeePerGas: fees.maxFeePerGas,
|
|
597
|
+
maxPriorityFeePerGas: fees.maxPriorityFeePerGas,
|
|
598
|
+
})
|
|
599
|
+
: await walletClient.sendTransaction({
|
|
600
|
+
to,
|
|
601
|
+
data,
|
|
602
|
+
value,
|
|
603
|
+
nonce,
|
|
604
|
+
gas: plan.gasLimit,
|
|
605
|
+
gasPrice: fees.gasPrice,
|
|
606
|
+
});
|
|
607
|
+
nonceUsed = nonce;
|
|
608
|
+
await storage.releaseChainLock(chainIdKey, nonceUsed);
|
|
609
|
+
if (reservedId !== null) {
|
|
610
|
+
await storage.recordClaimTx(reservedId, txHash);
|
|
611
|
+
}
|
|
612
|
+
background(c, storage.cleanup(now - USED_TOKEN_RETENTION_SECONDS, now - CLAIM_RETENTION_SECONDS));
|
|
613
|
+
return c.json({ success: true, txHash });
|
|
614
|
+
}
|
|
615
|
+
catch (err) {
|
|
616
|
+
console.error('Transaction error:', err);
|
|
617
|
+
await storage.releaseChainLock(chainIdKey, nonceUsed).catch((e) => {
|
|
618
|
+
console.error('could not release chain lock', e);
|
|
619
|
+
});
|
|
620
|
+
const errorMessage = err instanceof Error ? err.message : 'Transaction failed';
|
|
621
|
+
return abort(errorMessage, 500);
|
|
145
622
|
}
|
|
146
623
|
});
|
|
147
624
|
return app;
|
|
148
625
|
}
|
|
626
|
+
function formatDuration(seconds) {
|
|
627
|
+
if (seconds < 60) {
|
|
628
|
+
return `${seconds} second${seconds === 1 ? '' : 's'}`;
|
|
629
|
+
}
|
|
630
|
+
const minutes = Math.ceil(seconds / 60);
|
|
631
|
+
if (minutes < 60) {
|
|
632
|
+
return `${minutes} minute${minutes === 1 ? '' : 's'}`;
|
|
633
|
+
}
|
|
634
|
+
const hours = Math.ceil(minutes / 60);
|
|
635
|
+
return `${hours} hour${hours === 1 ? '' : 's'}`;
|
|
636
|
+
}
|
|
149
637
|
//# sourceMappingURL=index.js.map
|