faucet-server-app 0.0.6 → 0.1.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 +34 -15
- package/dist/esm/api/index.d.ts.map +1 -1
- package/dist/esm/api/index.js +247 -75
- package/dist/esm/api/index.js.map +1 -1
- 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 +17521 -0
- package/dist/esm/chains.d.ts.map +1 -0
- package/dist/esm/chains.js +88 -0
- package/dist/esm/chains.js.map +1 -0
- package/dist/esm/env.d.ts +12 -0
- package/dist/esm/env.d.ts.map +1 -1
- package/dist/esm/env.js +33 -1
- package/dist/esm/env.js.map +1 -1
- package/dist/esm/index.d.ts +97 -43
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +32 -14
- 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 +3 -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 +151 -0
- package/dist/esm/storage/RemoteSQLStorage.js.map +1 -0
- package/package.json +1 -1
- package/src/api/index.ts +327 -106
- package/src/captcha.ts +92 -0
- package/src/chains.ts +110 -0
- package/src/env.ts +56 -0
- package/src/index.ts +35 -16
- package/src/schema/sql/db.sql +25 -4
- package/src/schema/ts/db.sql.ts +25 -4
- package/src/setup.ts +4 -11
- package/src/storage/RemoteSQLStorage.ts +245 -0
package/src/api/index.ts
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
import {Hono} from 'hono';
|
|
1
|
+
import {Context, Hono} from 'hono';
|
|
2
2
|
import {ServerOptions} from '../types.js';
|
|
3
3
|
import {setup} from '../setup.js';
|
|
4
|
-
import {Env} from '../env.js';
|
|
5
4
|
import {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
} from '
|
|
5
|
+
CHAIN_LOCK_TIMEOUT_SECONDS,
|
|
6
|
+
CLAIM_RETENTION_SECONDS,
|
|
7
|
+
DEFAULT_CLAIM_COOLDOWN_SECONDS,
|
|
8
|
+
Env,
|
|
9
|
+
USED_TOKEN_RETENTION_SECONDS,
|
|
10
|
+
getNumberEnv,
|
|
11
|
+
} from '../env.js';
|
|
12
|
+
import {isAddress, type Hex, type Address} from 'viem';
|
|
13
13
|
import {privateKeyToAccount} from 'viem/accounts';
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
};
|
|
14
|
+
import {
|
|
15
|
+
estimateTransferCost,
|
|
16
|
+
getChainConfig,
|
|
17
|
+
getPublicClient,
|
|
18
|
+
getWalletClient,
|
|
19
|
+
} from '../chains.js';
|
|
20
|
+
import {hashToken, verifyProsopoCaptcha} from '../captcha.js';
|
|
21
21
|
|
|
22
22
|
type ClaimRequest = {
|
|
23
23
|
token: string;
|
|
@@ -25,41 +25,69 @@ type ClaimRequest = {
|
|
|
25
25
|
address: string;
|
|
26
26
|
};
|
|
27
27
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
28
|
+
const TX_HASH_REGEX = /^0x[0-9a-fA-F]{64}$/;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Best effort ip of the caller, used as a rate limiting bucket.
|
|
32
|
+
* Returns '' when the server sits behind no proxy that tells us: in that case
|
|
33
|
+
* the ip bucket is skipped entirely rather than lumping every user together.
|
|
34
|
+
*/
|
|
35
|
+
function getClientIp(c: Context): string {
|
|
36
|
+
const headers = ['cf-connecting-ip', 'x-real-ip', 'x-forwarded-for'];
|
|
37
|
+
for (const header of headers) {
|
|
38
|
+
const value = c.req.header(header);
|
|
39
|
+
if (value) {
|
|
40
|
+
// x-forwarded-for is a list, the left most entry is the client
|
|
41
|
+
const ip = value.split(',')[0].trim();
|
|
42
|
+
if (ip) {
|
|
43
|
+
return ip;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return '';
|
|
47
48
|
}
|
|
48
49
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
50
|
+
// Waits for the per chain send lock instead of turning the caller away: a
|
|
51
|
+
// dispense takes a few hundred milliseconds, so concurrent claims queue rather
|
|
52
|
+
// than fail. Gives up after LOCK_WAIT_MS so a request never hangs.
|
|
53
|
+
const LOCK_WAIT_MS = 12000;
|
|
54
|
+
const LOCK_RETRY_INTERVAL_MS = 300;
|
|
55
|
+
|
|
56
|
+
async function acquireChainLockWaiting(
|
|
57
|
+
storage: {
|
|
58
|
+
acquireChainLock: (
|
|
59
|
+
chainId: string,
|
|
60
|
+
now: number,
|
|
61
|
+
lockedUntil: number,
|
|
62
|
+
) => Promise<{acquired: boolean; lastNonce: number | null}>;
|
|
63
|
+
},
|
|
64
|
+
chainId: string,
|
|
65
|
+
): Promise<{acquired: boolean; lastNonce: number | null}> {
|
|
66
|
+
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
67
|
+
for (;;) {
|
|
68
|
+
const now = Math.floor(Date.now() / 1000);
|
|
69
|
+
const lock = await storage.acquireChainLock(
|
|
70
|
+
chainId,
|
|
71
|
+
now,
|
|
72
|
+
now + CHAIN_LOCK_TIMEOUT_SECONDS,
|
|
73
|
+
);
|
|
74
|
+
if (lock.acquired || Date.now() >= deadline) {
|
|
75
|
+
return lock;
|
|
76
|
+
}
|
|
77
|
+
await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_INTERVAL_MS));
|
|
56
78
|
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Runs a promise outside of the response path, on platforms that support it.
|
|
82
|
+
function background(c: Context, promise: Promise<unknown>): void {
|
|
83
|
+
const safe = promise.catch((err) => {
|
|
84
|
+
console.error('background task failed', err);
|
|
85
|
+
});
|
|
86
|
+
try {
|
|
87
|
+
c.executionCtx.waitUntil(safe);
|
|
88
|
+
} catch (err) {
|
|
89
|
+
// no execution context (node), the promise just runs on its own
|
|
61
90
|
}
|
|
62
|
-
return {amount, rpcUrl};
|
|
63
91
|
}
|
|
64
92
|
|
|
65
93
|
export function getAPI<CustomEnv extends Env>(
|
|
@@ -76,142 +104,335 @@ export function getAPI<CustomEnv extends Env>(
|
|
|
76
104
|
.get('/chain/:chainId', async (c) => {
|
|
77
105
|
const config = c.get('config');
|
|
78
106
|
const env = config.env;
|
|
79
|
-
const chainId = c.req.param('chainId');
|
|
80
107
|
|
|
81
|
-
|
|
82
|
-
const chainIdNum = parseInt(chainId, 10);
|
|
108
|
+
const chainIdNum = parseInt(c.req.param('chainId'), 10);
|
|
83
109
|
if (isNaN(chainIdNum) || chainIdNum <= 0) {
|
|
84
110
|
return c.json({error: 'Invalid chainId'}, 400);
|
|
85
111
|
}
|
|
86
112
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
const chainConfigValue = env[chainConfigKey];
|
|
90
|
-
|
|
91
|
-
if (!chainConfigValue) {
|
|
113
|
+
const lookup = getChainConfig(env, chainIdNum);
|
|
114
|
+
if (lookup.status === 'not-configured') {
|
|
92
115
|
return c.json(
|
|
93
|
-
{error: `Faucet not configured for chain ${
|
|
116
|
+
{error: `Faucet not configured for chain ${chainIdNum}`},
|
|
94
117
|
404,
|
|
95
118
|
);
|
|
96
119
|
}
|
|
120
|
+
if (lookup.status === 'invalid') {
|
|
121
|
+
console.error(
|
|
122
|
+
`invalid config for chain ${chainIdNum}: ${lookup.details}`,
|
|
123
|
+
);
|
|
124
|
+
return c.json({error: `Faucet misconfigured`}, 500);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Note: the rpc endpoint is deliberately NOT returned, it is a server
|
|
128
|
+
// side secret. Clients follow their transaction through /tx instead.
|
|
129
|
+
return c.json({
|
|
130
|
+
chainId: chainIdNum,
|
|
131
|
+
amount: lookup.config.amount.toString(),
|
|
132
|
+
});
|
|
133
|
+
})
|
|
134
|
+
.get('/tx/:chainId/:txHash', async (c) => {
|
|
135
|
+
const config = c.get('config');
|
|
136
|
+
const env = config.env;
|
|
137
|
+
|
|
138
|
+
const chainIdNum = parseInt(c.req.param('chainId'), 10);
|
|
139
|
+
if (isNaN(chainIdNum) || chainIdNum <= 0) {
|
|
140
|
+
return c.json({error: 'Invalid chainId'}, 400);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const txHash = c.req.param('txHash');
|
|
144
|
+
if (!TX_HASH_REGEX.test(txHash)) {
|
|
145
|
+
return c.json({error: 'Invalid transaction hash'}, 400);
|
|
146
|
+
}
|
|
97
147
|
|
|
98
|
-
const
|
|
99
|
-
if (
|
|
148
|
+
const lookup = getChainConfig(env, chainIdNum);
|
|
149
|
+
if (lookup.status !== 'ok') {
|
|
100
150
|
return c.json(
|
|
101
|
-
{error: `
|
|
102
|
-
|
|
151
|
+
{error: `Faucet not configured for chain ${chainIdNum}`},
|
|
152
|
+
404,
|
|
103
153
|
);
|
|
104
154
|
}
|
|
105
155
|
|
|
106
|
-
|
|
156
|
+
const publicClient = getPublicClient(lookup.config);
|
|
157
|
+
try {
|
|
158
|
+
const receipt = await publicClient.getTransactionReceipt({
|
|
159
|
+
hash: txHash as Hex,
|
|
160
|
+
});
|
|
161
|
+
return c.json({
|
|
162
|
+
status: receipt.status === 'success' ? 'success' : 'failed',
|
|
163
|
+
blockNumber: receipt.blockNumber.toString(),
|
|
164
|
+
});
|
|
165
|
+
} catch (err) {
|
|
166
|
+
// viem throws when the receipt is not available yet
|
|
167
|
+
return c.json({status: 'pending'});
|
|
168
|
+
}
|
|
107
169
|
})
|
|
108
170
|
.post('/claim', async (c) => {
|
|
109
171
|
const config = c.get('config');
|
|
110
|
-
const env = config
|
|
172
|
+
const {env, storage} = config;
|
|
111
173
|
|
|
112
|
-
// Check if captcha is disabled (for localhost development)
|
|
113
174
|
const captchaDisabled = env.DISABLE_CAPTCHA === 'true';
|
|
114
|
-
|
|
115
|
-
// Validate PROSOPO secret (only required if captcha is enabled)
|
|
116
175
|
const secret = env.PROSOPO_SITE_PRIVATE_KEY;
|
|
117
176
|
if (!captchaDisabled && !secret) {
|
|
118
177
|
return c.json({error: 'PROSOPO_SITE_PRIVATE_KEY not configured'}, 500);
|
|
119
178
|
}
|
|
120
179
|
|
|
121
|
-
// Validate FAUCET_PRIVATE_KEY
|
|
122
180
|
const faucetPrivateKey = env.FAUCET_PRIVATE_KEY;
|
|
123
181
|
if (!faucetPrivateKey) {
|
|
124
182
|
return c.json({error: 'FAUCET_PRIVATE_KEY not configured'}, 500);
|
|
125
183
|
}
|
|
126
184
|
|
|
127
|
-
|
|
185
|
+
let body: ClaimRequest;
|
|
186
|
+
try {
|
|
187
|
+
body = await c.req.json<ClaimRequest>();
|
|
188
|
+
} catch (err) {
|
|
189
|
+
return c.json({error: 'Invalid JSON body'}, 400);
|
|
190
|
+
}
|
|
128
191
|
const {token, chainId, address} = body;
|
|
129
192
|
|
|
130
|
-
// Validate required fields
|
|
131
193
|
if (!token) {
|
|
132
194
|
return c.json({error: 'Missing token'}, 400);
|
|
133
195
|
}
|
|
134
|
-
|
|
135
196
|
if (!chainId) {
|
|
136
197
|
return c.json({error: 'Missing chainId'}, 400);
|
|
137
198
|
}
|
|
138
|
-
|
|
139
199
|
if (!address) {
|
|
140
200
|
return c.json({error: 'Missing address'}, 400);
|
|
141
201
|
}
|
|
142
|
-
|
|
143
|
-
// Validate address format
|
|
144
202
|
if (!isAddress(address)) {
|
|
145
203
|
return c.json({error: 'Invalid Ethereum address'}, 400);
|
|
146
204
|
}
|
|
147
205
|
|
|
148
|
-
// Parse chainId
|
|
149
206
|
const chainIdNum = parseInt(chainId, 10);
|
|
150
207
|
if (isNaN(chainIdNum) || chainIdNum <= 0) {
|
|
151
208
|
return c.json({error: 'Invalid chainId'}, 400);
|
|
152
209
|
}
|
|
153
210
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
const chainConfigValue = env[chainConfigKey];
|
|
157
|
-
|
|
158
|
-
if (!chainConfigValue) {
|
|
211
|
+
const lookup = getChainConfig(env, chainIdNum);
|
|
212
|
+
if (lookup.status === 'not-configured') {
|
|
159
213
|
return c.json(
|
|
160
|
-
{error: `Faucet not configured for chain ${
|
|
214
|
+
{error: `Faucet not configured for chain ${chainIdNum}`},
|
|
161
215
|
400,
|
|
162
216
|
);
|
|
163
217
|
}
|
|
218
|
+
if (lookup.status === 'invalid') {
|
|
219
|
+
console.error(
|
|
220
|
+
`invalid config for chain ${chainIdNum}: ${lookup.details}`,
|
|
221
|
+
);
|
|
222
|
+
return c.json({error: 'Faucet misconfigured'}, 500);
|
|
223
|
+
}
|
|
224
|
+
const chainConfig = lookup.config;
|
|
225
|
+
|
|
226
|
+
const now = Math.floor(Date.now() / 1000);
|
|
227
|
+
const ip = getClientIp(c);
|
|
228
|
+
const normalizedAddress = address.toLowerCase();
|
|
229
|
+
const chainIdKey = String(chainIdNum);
|
|
164
230
|
|
|
165
|
-
|
|
166
|
-
|
|
231
|
+
// ---------------------------------------------------------------
|
|
232
|
+
// 1. captcha: single use token, then provider verification
|
|
233
|
+
// ---------------------------------------------------------------
|
|
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
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const publicClient = getPublicClient(chainConfig);
|
|
261
|
+
|
|
262
|
+
// ---------------------------------------------------------------
|
|
263
|
+
// 2. do not top up an address that already holds enough
|
|
264
|
+
// ---------------------------------------------------------------
|
|
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
|
+
if (maxRecipientBalance > 0n) {
|
|
271
|
+
try {
|
|
272
|
+
const recipientBalance = await publicClient.getBalance({
|
|
273
|
+
address: address as Address,
|
|
274
|
+
});
|
|
275
|
+
if (recipientBalance >= maxRecipientBalance) {
|
|
276
|
+
return c.json(
|
|
277
|
+
{
|
|
278
|
+
error:
|
|
279
|
+
'This address already holds enough funds on this chain, the faucet is for empty accounts',
|
|
280
|
+
},
|
|
281
|
+
400,
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
} catch (err) {
|
|
285
|
+
console.error('could not read recipient balance', err);
|
|
286
|
+
return c.json({error: 'Could not reach the chain rpc'}, 503);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// ---------------------------------------------------------------
|
|
291
|
+
// 3. rate limit: atomically reserve a slot for this address / ip
|
|
292
|
+
// ---------------------------------------------------------------
|
|
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
|
+
const claimId = await storage.reserveClaim({
|
|
300
|
+
chainId: chainIdKey,
|
|
301
|
+
address: normalizedAddress,
|
|
302
|
+
ip,
|
|
303
|
+
amount: chainConfig.amount.toString(),
|
|
304
|
+
now,
|
|
305
|
+
addressCutoff: now - addressCooldown,
|
|
306
|
+
ipCutoff: now - ipCooldown,
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
if (claimId === null) {
|
|
310
|
+
const hit = await storage.getRateLimitHit({
|
|
311
|
+
chainId: chainIdKey,
|
|
312
|
+
address: normalizedAddress,
|
|
313
|
+
ip,
|
|
314
|
+
now,
|
|
315
|
+
addressCutoff: now - addressCooldown,
|
|
316
|
+
ipCutoff: now - ipCooldown,
|
|
317
|
+
addressCooldown,
|
|
318
|
+
ipCooldown,
|
|
319
|
+
});
|
|
320
|
+
const subject = hit.reason === 'address' ? 'This address' : 'You';
|
|
167
321
|
return c.json(
|
|
168
322
|
{
|
|
169
|
-
error:
|
|
323
|
+
error: `${subject} already claimed recently, please wait ${formatDuration(
|
|
324
|
+
hit.retryAfter,
|
|
325
|
+
)}`,
|
|
326
|
+
retryAfter: hit.retryAfter,
|
|
170
327
|
},
|
|
171
|
-
|
|
328
|
+
429,
|
|
329
|
+
{'Retry-After': String(hit.retryAfter)},
|
|
172
330
|
);
|
|
173
331
|
}
|
|
174
332
|
|
|
175
|
-
//
|
|
176
|
-
|
|
177
|
-
|
|
333
|
+
// From here on, any failure must give the reservation back.
|
|
334
|
+
const abort = async (
|
|
335
|
+
message: string,
|
|
336
|
+
status: 400 | 500 | 503,
|
|
337
|
+
): Promise<Response> => {
|
|
338
|
+
await storage.cancelClaim(claimId).catch((err) => {
|
|
339
|
+
console.error('could not cancel claim reservation', err);
|
|
340
|
+
});
|
|
341
|
+
return c.json({error: message}, status);
|
|
342
|
+
};
|
|
178
343
|
|
|
179
|
-
|
|
180
|
-
|
|
344
|
+
const account = privateKeyToAccount(faucetPrivateKey as Hex);
|
|
345
|
+
|
|
346
|
+
// ---------------------------------------------------------------
|
|
347
|
+
// 4. can the faucet still pay?
|
|
348
|
+
// ---------------------------------------------------------------
|
|
349
|
+
try {
|
|
350
|
+
const faucetBalance = await publicClient.getBalance({
|
|
351
|
+
address: account.address,
|
|
352
|
+
});
|
|
353
|
+
const gasCost = await estimateTransferCost(publicClient);
|
|
354
|
+
if (faucetBalance < chainConfig.amount + gasCost) {
|
|
355
|
+
console.error(
|
|
356
|
+
`faucet ${account.address} is out of funds on chain ${chainIdNum}: balance ${faucetBalance}, needs ${
|
|
357
|
+
chainConfig.amount + gasCost
|
|
358
|
+
}`,
|
|
359
|
+
);
|
|
360
|
+
return abort(
|
|
361
|
+
'The faucet is temporarily out of funds, please try again later',
|
|
362
|
+
503,
|
|
363
|
+
);
|
|
181
364
|
}
|
|
365
|
+
} catch (err) {
|
|
366
|
+
console.error('could not check faucet balance', err);
|
|
367
|
+
return abort('Could not reach the chain rpc', 503);
|
|
182
368
|
}
|
|
183
369
|
|
|
370
|
+
// ---------------------------------------------------------------
|
|
371
|
+
// 5. serialise sending so concurrent claims cannot reuse a nonce
|
|
372
|
+
// ---------------------------------------------------------------
|
|
373
|
+
const lock = await acquireChainLockWaiting(storage, chainIdKey);
|
|
374
|
+
if (!lock.acquired) {
|
|
375
|
+
return abort(
|
|
376
|
+
'The faucet is busy dispensing other claims, please try again in a few seconds',
|
|
377
|
+
503,
|
|
378
|
+
);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
let nonceUsed: number | null = null;
|
|
184
382
|
try {
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
const walletClient = createWalletClient({
|
|
190
|
-
account,
|
|
191
|
-
chain: {
|
|
192
|
-
id: chainIdNum,
|
|
193
|
-
name: `Chain ${chainIdNum}`,
|
|
194
|
-
nativeCurrency: {name: 'ETH', symbol: 'ETH', decimals: 18},
|
|
195
|
-
rpcUrls: {
|
|
196
|
-
default: {http: [rpcUrl]},
|
|
197
|
-
},
|
|
198
|
-
},
|
|
199
|
-
transport: http(rpcUrl),
|
|
383
|
+
const pendingNonce = await publicClient.getTransactionCount({
|
|
384
|
+
address: account.address,
|
|
385
|
+
blockTag: 'pending',
|
|
200
386
|
});
|
|
201
|
-
|
|
387
|
+
// the chain is the source of truth, our own counter only guards
|
|
388
|
+
// against two claims reading the same pending nonce
|
|
389
|
+
const nonce =
|
|
390
|
+
lock.lastNonce === null
|
|
391
|
+
? pendingNonce
|
|
392
|
+
: Math.max(lock.lastNonce + 1, pendingNonce);
|
|
393
|
+
|
|
394
|
+
const walletClient = getWalletClient(chainConfig, account);
|
|
202
395
|
const txHash = await walletClient.sendTransaction({
|
|
203
396
|
to: address as Address,
|
|
204
|
-
value:
|
|
397
|
+
value: chainConfig.amount,
|
|
398
|
+
nonce,
|
|
205
399
|
});
|
|
400
|
+
nonceUsed = nonce;
|
|
401
|
+
|
|
402
|
+
await storage.releaseChainLock(chainIdKey, nonceUsed);
|
|
403
|
+
await storage.recordClaimTx(claimId, txHash);
|
|
404
|
+
|
|
405
|
+
background(
|
|
406
|
+
c,
|
|
407
|
+
storage.cleanup(
|
|
408
|
+
now - USED_TOKEN_RETENTION_SECONDS,
|
|
409
|
+
now - CLAIM_RETENTION_SECONDS,
|
|
410
|
+
),
|
|
411
|
+
);
|
|
206
412
|
|
|
207
413
|
return c.json({success: true, txHash});
|
|
208
414
|
} catch (err) {
|
|
209
415
|
console.error('Transaction error:', err);
|
|
416
|
+
await storage.releaseChainLock(chainIdKey, nonceUsed).catch((e) => {
|
|
417
|
+
console.error('could not release chain lock', e);
|
|
418
|
+
});
|
|
210
419
|
const errorMessage =
|
|
211
420
|
err instanceof Error ? err.message : 'Transaction failed';
|
|
212
|
-
return
|
|
421
|
+
return abort(errorMessage, 500);
|
|
213
422
|
}
|
|
214
423
|
});
|
|
215
424
|
|
|
216
425
|
return app;
|
|
217
426
|
}
|
|
427
|
+
|
|
428
|
+
function formatDuration(seconds: number): string {
|
|
429
|
+
if (seconds < 60) {
|
|
430
|
+
return `${seconds} second${seconds === 1 ? '' : 's'}`;
|
|
431
|
+
}
|
|
432
|
+
const minutes = Math.ceil(seconds / 60);
|
|
433
|
+
if (minutes < 60) {
|
|
434
|
+
return `${minutes} minute${minutes === 1 ? '' : 's'}`;
|
|
435
|
+
}
|
|
436
|
+
const hours = Math.ceil(minutes / 60);
|
|
437
|
+
return `${hours} hour${hours === 1 ? '' : 's'}`;
|
|
438
|
+
}
|
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
|
+
}
|