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/config.ts ADDED
@@ -0,0 +1,33 @@
1
+ import {getBigIntEnv, getCooldowns, type Env} from './env.js';
2
+ import {checkArbitraryCallsConfig, type ConfigIssues} from './calls.js';
3
+
4
+ /**
5
+ * Every configuration check the server can make without touching the network,
6
+ * so a typo in a spending limit stops the process instead of surfacing as a
7
+ * failed claim later.
8
+ *
9
+ * Cloudflare Workers has no boot hook, so there the same problems surface as a
10
+ * 500 plus a console error on the first request that reads them.
11
+ */
12
+ export function checkConfig(env: Env): ConfigIssues {
13
+ const issues = checkArbitraryCallsConfig(env);
14
+
15
+ // A malformed ceiling used to throw out of BigInt() on every claim, which
16
+ // reached the error handler as an unhandled exception: a 500 with a stack
17
+ // instead of a clear answer, on a faucet that had started up happily.
18
+ const maxRecipientBalance = getBigIntEnv(env.MAX_RECIPIENT_BALANCE);
19
+ if (maxRecipientBalance.status === 'invalid') {
20
+ issues.errors.push(
21
+ `MAX_RECIPIENT_BALANCE must be a wei amount, got "${env.MAX_RECIPIENT_BALANCE}"`,
22
+ );
23
+ }
24
+
25
+ // These used to go through parseInt, which partial parses: '1h' meant one
26
+ // second, so a plausible looking typo removed the cooldown almost entirely.
27
+ const cooldowns = getCooldowns(env);
28
+ if (cooldowns.status === 'invalid') {
29
+ issues.errors.push(cooldowns.details);
30
+ }
31
+
32
+ return issues;
33
+ }
package/src/env.ts CHANGED
@@ -1,9 +1,138 @@
1
1
  export type Env = {
2
+ // 'true' includes the cause and stack of an unhandled error in the response.
3
+ // Development only, and set as a flag rather than an env entry: the node cli
4
+ // has --dev, the worker dev script passes --var DEV:true, so it cannot follow
5
+ // you into a deployment.
2
6
  DEV?: string;
3
7
  PROSOPO_SITE_PRIVATE_KEY?: string;
4
8
  FAUCET_PRIVATE_KEY?: string;
5
9
  // Set to 'true' to disable captcha verification (useful for localhost development)
6
10
  DISABLE_CAPTCHA?: string;
11
+ // Set to 'true' to keep dispensing when the captcha provider is unreachable.
12
+ // Default is to fail closed: an unreachable provider means no funds go out.
13
+ CAPTCHA_FAIL_OPEN?: string;
14
+ // Comma separated list of origins allowed to call the API cross-origin,
15
+ // or '*' to allow any. Defaults to DEFAULT_CORS_ORIGINS.
16
+ CORS_ORIGINS?: string;
17
+ // Cooldown in seconds between two claims for the same address (default: 1 day)
18
+ CLAIM_COOLDOWN_SECONDS?: string;
19
+ // Cooldown in seconds between two claims from the same ip (default: CLAIM_COOLDOWN_SECONDS)
20
+ IP_COOLDOWN_SECONDS?: string;
21
+ // Refuse to top up a recipient already holding this much (in wei).
22
+ // Defaults to 10x the chain amount, set to '0' to disable the check.
23
+ MAX_RECIPIENT_BALANCE?: string;
24
+ // 'off' (default), 'allowlist' or 'unrestricted'. Anything but 'off' lets
25
+ // callers choose what the faucet key signs, see docs/specs/arbitrary-calls.md
26
+ ENABLE_ARBITRARY_CALLS?: string;
27
+ // Absolute gas limit granted to an arbitrary call, whatever the budget says.
28
+ MAX_CALL_GAS?: string;
7
29
  // Dynamic env variables: CHAIN_<CHAIN_ID>=<amount>:<rpc_endpoint> for chain config
8
30
  [key: `CHAIN_${string}`]: string | undefined;
31
+ // CALL_ALLOWLIST_<CHAIN_ID>=<contract>:<selector>,<selector>;<contract>:...
32
+ [key: `CALL_ALLOWLIST_${string}`]: string | undefined;
33
+ // MAX_CALL_TOTAL_SPEND_<CHAIN_ID>=<wei>, ceiling on value + gas for one call
34
+ [key: `MAX_CALL_TOTAL_SPEND_${string}`]: string | undefined;
35
+ // MAX_CALL_VALUE_<CHAIN_ID>=<wei>, ceiling on the value attached to a call
36
+ [key: `MAX_CALL_VALUE_${string}`]: string | undefined;
9
37
  };
38
+
39
+ export const DEFAULT_CORS_ORIGINS = ['https://jolly-roger.eth.limo'];
40
+
41
+ // one day
42
+ export const DEFAULT_CLAIM_COOLDOWN_SECONDS = 24 * 60 * 60;
43
+
44
+ // how long a captcha token stays burnt before being garbage collected.
45
+ // Prosopo tokens are short lived, an hour is plenty to block replays.
46
+ export const USED_TOKEN_RETENTION_SECONDS = 60 * 60;
47
+
48
+ // how long claim history is kept around, past every plausible cooldown
49
+ export const CLAIM_RETENTION_SECONDS = 30 * 24 * 60 * 60;
50
+
51
+ // how long a claim may hold the per chain send lock
52
+ export const CHAIN_LOCK_TIMEOUT_SECONDS = 30;
53
+
54
+ /**
55
+ * Parses a non-negative integer, refusing anything else.
56
+ *
57
+ * Deliberately not parseInt: that partial parses, so CLAIM_COOLDOWN_SECONDS=1h
58
+ * used to mean ONE SECOND rather than the 86400 default. A typo in a limit has
59
+ * to be refused, not silently turned into a much weaker limit.
60
+ */
61
+ export function getIntEnv(
62
+ value: string | undefined,
63
+ ): {status: 'unset'} | {status: 'ok'; value: number} | {status: 'invalid'} {
64
+ if (value === undefined || value.trim() === '') {
65
+ return {status: 'unset'};
66
+ }
67
+ const trimmed = value.trim();
68
+ if (!/^[0-9]+$/.test(trimmed)) {
69
+ return {status: 'invalid'};
70
+ }
71
+ const parsed = Number(trimmed);
72
+ if (!Number.isSafeInteger(parsed)) {
73
+ return {status: 'invalid'};
74
+ }
75
+ return {status: 'ok', value: parsed};
76
+ }
77
+
78
+ export type Cooldowns =
79
+ | {status: 'ok'; addressCooldown: number; ipCooldown: number}
80
+ | {status: 'invalid'; details: string};
81
+
82
+ /**
83
+ * The two rate limiting windows. The ip window defaults to the address one, so
84
+ * they are resolved together.
85
+ */
86
+ export function getCooldowns(env: Env): Cooldowns {
87
+ const claim = getIntEnv(env.CLAIM_COOLDOWN_SECONDS);
88
+ if (claim.status === 'invalid') {
89
+ return {
90
+ status: 'invalid',
91
+ details: `CLAIM_COOLDOWN_SECONDS must be a whole number of seconds, got "${env.CLAIM_COOLDOWN_SECONDS}"`,
92
+ };
93
+ }
94
+ const addressCooldown =
95
+ claim.status === 'ok' ? claim.value : DEFAULT_CLAIM_COOLDOWN_SECONDS;
96
+
97
+ const ip = getIntEnv(env.IP_COOLDOWN_SECONDS);
98
+ if (ip.status === 'invalid') {
99
+ return {
100
+ status: 'invalid',
101
+ details: `IP_COOLDOWN_SECONDS must be a whole number of seconds, got "${env.IP_COOLDOWN_SECONDS}"`,
102
+ };
103
+ }
104
+ const ipCooldown = ip.status === 'ok' ? ip.value : addressCooldown;
105
+
106
+ return {status: 'ok', addressCooldown, ipCooldown};
107
+ }
108
+
109
+ /**
110
+ * Parses a wei amount, refusing a malformed value instead of falling back:
111
+ * every caller here is a spending limit and a typo must not silently widen it.
112
+ */
113
+ export function getBigIntEnv(
114
+ value: string | undefined,
115
+ ): {status: 'unset'} | {status: 'ok'; value: bigint} | {status: 'invalid'} {
116
+ if (value === undefined || value.trim() === '') {
117
+ return {status: 'unset'};
118
+ }
119
+ const trimmed = value.trim();
120
+ if (!/^[0-9]+$/.test(trimmed)) {
121
+ return {status: 'invalid'};
122
+ }
123
+ return {status: 'ok', value: BigInt(trimmed)};
124
+ }
125
+
126
+ export function getCorsOrigins(env: Env): string[] | '*' {
127
+ const configured = env.CORS_ORIGINS;
128
+ if (configured === undefined || configured.trim() === '') {
129
+ return DEFAULT_CORS_ORIGINS;
130
+ }
131
+ if (configured.trim() === '*') {
132
+ return '*';
133
+ }
134
+ return configured
135
+ .split(',')
136
+ .map((v) => v.trim())
137
+ .filter((v) => v.length > 0);
138
+ }
package/src/index.ts CHANGED
@@ -3,26 +3,44 @@ import {cors} from 'hono/cors';
3
3
  import {ServerOptions} from './types.js';
4
4
  import {hc} from 'hono/client';
5
5
  import {HTTPException} from 'hono/http-exception';
6
- import {Env} from './env.js';
6
+ import {Env, getCorsOrigins} from './env.js';
7
7
  import {getAPI} from './api/index.js';
8
+ import {RemoteSQL} from 'remote-sql';
9
+ import {RemoteSQLStorage} from './storage/RemoteSQLStorage.js';
8
10
 
9
11
  export type {Env};
12
+ export {RemoteSQLStorage};
13
+ export {verifyProsopoCaptcha} from './captcha.js';
14
+ export type {CaptchaVerification} from './captcha.js';
15
+ export {DEFAULT_CORS_ORIGINS, DEFAULT_CLAIM_COOLDOWN_SECONDS} from './env.js';
16
+ export {
17
+ getArbitraryCallsMode,
18
+ getCallAllowlist,
19
+ getCallLimits,
20
+ isCallAllowed,
21
+ parseCallRequest,
22
+ planGas,
23
+ selectorOf,
24
+ DEFAULT_MAX_CALL_GAS,
25
+ GAS_BUFFER_PERCENT,
26
+ SIMPLE_TRANSFER_GAS,
27
+ } from './calls.js';
28
+ export type {
29
+ ArbitraryCallsMode,
30
+ CallLimits,
31
+ ConfigIssues,
32
+ GasPlan,
33
+ } from './calls.js';
34
+ export {checkConfig} from './config.js';
35
+ export {parseChainId} from './chains.js';
36
+ export type {ChainConfig} from './chains.js';
10
37
 
11
- // export type {Storage} from './storage/index.js';
12
-
13
- const corsSetup = cors({
14
- origin: '*',
15
- allowHeaders: [
16
- 'X-Custom-Header',
17
- 'Upgrade-Insecure-Requests',
18
- 'Content-Type',
19
- 'SIGNATURE',
20
- ],
21
- allowMethods: ['POST', 'GET', 'HEAD', 'OPTIONS'],
22
- exposeHeaders: ['Content-Length', 'X-Kuma-Revision'],
23
- maxAge: 600,
24
- credentials: true,
25
- });
38
+ /**
39
+ * Creates the tables the faucet needs. Idempotent, safe to call on every boot.
40
+ */
41
+ export async function setupDB(db: RemoteSQL): Promise<void> {
42
+ await new RemoteSQLStorage(db).setup();
43
+ }
26
44
 
27
45
  export function createServer<CustomEnv extends Env>(
28
46
  options: ServerOptions<CustomEnv>,
@@ -31,6 +49,28 @@ export function createServer<CustomEnv extends Env>(
31
49
 
32
50
  const api = getAPI(options);
33
51
 
52
+ // The frontend is served from the same origin as the api, so this only
53
+ // controls which OTHER sites may drive the faucet from a browser.
54
+ const corsSetup = cors({
55
+ origin: (origin, c) => {
56
+ const allowed = getCorsOrigins(options.getEnv(c as any));
57
+ if (allowed === '*') {
58
+ return origin || '*';
59
+ }
60
+ return allowed.includes(origin) ? origin : null;
61
+ },
62
+ allowHeaders: [
63
+ 'X-Custom-Header',
64
+ 'Upgrade-Insecure-Requests',
65
+ 'Content-Type',
66
+ 'SIGNATURE',
67
+ ],
68
+ allowMethods: ['POST', 'GET', 'HEAD', 'OPTIONS'],
69
+ exposeHeaders: ['Content-Length', 'X-Kuma-Revision', 'Retry-After'],
70
+ maxAge: 600,
71
+ credentials: true,
72
+ });
73
+
34
74
  return app
35
75
  .use('/api/*', corsSetup)
36
76
  .route('/api/', api)
@@ -53,8 +93,10 @@ export function createServer<CustomEnv extends Env>(
53
93
  code: 'code' in err ? err.code : 5000,
54
94
  status: 'status' in err ? err.status : undefined,
55
95
  message: err.message,
56
- cause: env.DEV ? err.cause : undefined,
57
- stack: env.DEV ? err.stack : undefined,
96
+ // an explicit 'true', so that DEV=false does not read as
97
+ // truthy and leak stack traces
98
+ cause: env.DEV === 'true' ? err.cause : undefined,
99
+ stack: env.DEV === 'true' ? err.stack : undefined,
58
100
  },
59
101
  ],
60
102
  },
@@ -1,5 +1,26 @@
1
- CREATE TABLE IF NOT EXISTS Users (
2
- id TEXT PRIMARY KEY,
3
- email TEXT NOT NULL UNIQUE,
4
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
1
+ CREATE TABLE IF NOT EXISTS Claims (
2
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
3
+ chain_id TEXT NOT NULL,
4
+ address TEXT NOT NULL,
5
+ ip TEXT NOT NULL DEFAULT '',
6
+ amount TEXT NOT NULL,
7
+ tx_hash TEXT,
8
+ claimed_at INTEGER NOT NULL
5
9
  );
10
+
11
+ CREATE INDEX IF NOT EXISTS idx_claims_address ON Claims (chain_id, address, claimed_at);
12
+
13
+ CREATE INDEX IF NOT EXISTS idx_claims_ip ON Claims (chain_id, ip, claimed_at);
14
+
15
+ CREATE TABLE IF NOT EXISTS ChainLocks (
16
+ chain_id TEXT PRIMARY KEY,
17
+ locked_until INTEGER NOT NULL DEFAULT 0,
18
+ last_nonce INTEGER
19
+ );
20
+
21
+ CREATE TABLE IF NOT EXISTS UsedTokens (
22
+ token_hash TEXT PRIMARY KEY,
23
+ used_at INTEGER NOT NULL
24
+ );
25
+
26
+ CREATE INDEX IF NOT EXISTS idx_used_tokens_used_at ON UsedTokens (used_at);
@@ -1,6 +1,27 @@
1
- export default `CREATE TABLE IF NOT EXISTS Users (
2
- id TEXT PRIMARY KEY,
3
- email TEXT NOT NULL UNIQUE,
4
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
1
+ export default `CREATE TABLE IF NOT EXISTS Claims (
2
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
3
+ chain_id TEXT NOT NULL,
4
+ address TEXT NOT NULL,
5
+ ip TEXT NOT NULL DEFAULT '',
6
+ amount TEXT NOT NULL,
7
+ tx_hash TEXT,
8
+ claimed_at INTEGER NOT NULL
5
9
  );
10
+
11
+ CREATE INDEX IF NOT EXISTS idx_claims_address ON Claims (chain_id, address, claimed_at);
12
+
13
+ CREATE INDEX IF NOT EXISTS idx_claims_ip ON Claims (chain_id, ip, claimed_at);
14
+
15
+ CREATE TABLE IF NOT EXISTS ChainLocks (
16
+ chain_id TEXT PRIMARY KEY,
17
+ locked_until INTEGER NOT NULL DEFAULT 0,
18
+ last_nonce INTEGER
19
+ );
20
+
21
+ CREATE TABLE IF NOT EXISTS UsedTokens (
22
+ token_hash TEXT PRIMARY KEY,
23
+ used_at INTEGER NOT NULL
24
+ );
25
+
26
+ CREATE INDEX IF NOT EXISTS idx_used_tokens_used_at ON UsedTokens (used_at);
6
27
  `
package/src/setup.ts CHANGED
@@ -1,14 +1,15 @@
1
1
  import {MiddlewareHandler} from 'hono/types';
2
2
  import {ServerOptions} from './types.js';
3
3
  import {Env} from './env.js';
4
- // import {RemoteSQLStorage} from './storage/RemoteSQLStorage.js';
4
+ import {RemoteSQLStorage} from './storage/RemoteSQLStorage.js';
5
+ import {checkConfig} from './config.js';
5
6
 
6
7
  export type SetupOptions<CustomEnv extends Env> = {
7
8
  serverOptions: ServerOptions<CustomEnv>;
8
9
  };
9
10
 
10
11
  export type Config<CustomEnv extends Env> = {
11
- // storage: RemoteSQLStorage;
12
+ storage: RemoteSQLStorage;
12
13
  env: CustomEnv;
13
14
  };
14
15
 
@@ -18,6 +19,28 @@ declare module 'hono' {
18
19
  }
19
20
  }
20
21
 
22
+ // Cloudflare Workers has no boot hook, so the configuration is reported once
23
+ // per isolate instead: an operator gets the same errors and warnings the node
24
+ // cli prints at startup, on the first request the isolate serves.
25
+ let configReported = false;
26
+
27
+ function reportConfigOnce(env: Env): void {
28
+ if (configReported) {
29
+ return;
30
+ }
31
+ configReported = true;
32
+ const issues = checkConfig(env);
33
+ for (const line of issues.info) {
34
+ console.log(line);
35
+ }
36
+ for (const warning of issues.warnings) {
37
+ console.warn(`WARNING: ${warning}`);
38
+ }
39
+ for (const error of issues.errors) {
40
+ console.error(`ERROR: ${error}`);
41
+ }
42
+ }
43
+
21
44
  export function setup<CustomEnv extends Env>(
22
45
  options: SetupOptions<CustomEnv>,
23
46
  ): MiddlewareHandler {
@@ -25,21 +48,15 @@ export function setup<CustomEnv extends Env>(
25
48
 
26
49
  return async (c, next) => {
27
50
  const env = getEnv(c);
28
-
51
+ reportConfigOnce(env);
29
52
  const db = getDB(c);
30
- // use db
31
- // const storage = new RemoteSQLStorage(db);
53
+ const storage = new RemoteSQLStorage(db);
32
54
 
33
55
  c.set('config', {
34
- // storage,
56
+ storage,
35
57
  env,
36
58
  });
37
59
 
38
- // // auto setup
39
- // if (c.req.query('_initDB') == 'true') {
40
- // await storage.setup();
41
- // }
42
-
43
60
  return next();
44
61
  };
45
62
  }
@@ -0,0 +1,252 @@
1
+ import {RemoteSQL} from 'remote-sql';
2
+ import schema from '../schema/ts/db.sql.js';
3
+
4
+ export type ClaimRow = {
5
+ id: number;
6
+ chain_id: string;
7
+ address: string;
8
+ ip: string;
9
+ amount: string;
10
+ tx_hash: string | null;
11
+ claimed_at: number;
12
+ };
13
+
14
+ export type ChainLockAcquisition = {
15
+ acquired: boolean;
16
+ // last nonce this faucet is known to have used on that chain, if any
17
+ lastNonce: number | null;
18
+ };
19
+
20
+ export type RateLimitHit = {
21
+ // which bucket was hit
22
+ reason: 'address' | 'ip';
23
+ // seconds the caller has to wait before trying again
24
+ retryAfter: number;
25
+ };
26
+
27
+ // A statement chunk that only contains comments cannot be executed on its own.
28
+ function isExecutable(statement: string): boolean {
29
+ return statement
30
+ .split('\n')
31
+ .some((line) => line.trim().length > 0 && !line.trim().startsWith('--'));
32
+ }
33
+
34
+ export class RemoteSQLStorage {
35
+ constructor(protected db: RemoteSQL) {}
36
+
37
+ // ------------------------------------------------------------------------
38
+ // schema
39
+ // ------------------------------------------------------------------------
40
+
41
+ // Idempotent: every statement in db.sql is a CREATE ... IF NOT EXISTS.
42
+ async setup(): Promise<void> {
43
+ const statements = schema
44
+ .split(';')
45
+ .map((v) => v.trim())
46
+ .filter((v) => v.length > 0 && isExecutable(v))
47
+ .map((v) => this.db.prepare(`${v};`));
48
+ await this.db.batch(statements);
49
+ }
50
+
51
+ // ------------------------------------------------------------------------
52
+ // captcha token replay protection
53
+ // ------------------------------------------------------------------------
54
+
55
+ // Burns a captcha token. Returns false when that token was already used,
56
+ // which means the request is a replay of an earlier successful verification.
57
+ async burnToken(tokenHash: string, now: number): Promise<boolean> {
58
+ const {results} = await this.db
59
+ .prepare(
60
+ `INSERT INTO UsedTokens (token_hash, used_at) VALUES (?, ?)
61
+ ON CONFLICT (token_hash) DO NOTHING
62
+ RETURNING token_hash;`,
63
+ )
64
+ .bind(tokenHash, now)
65
+ .all<{token_hash: string}>();
66
+ return results.length > 0;
67
+ }
68
+
69
+ // ------------------------------------------------------------------------
70
+ // rate limiting
71
+ // ------------------------------------------------------------------------
72
+
73
+ // Atomically reserves a claim slot: the row is only inserted when no recent
74
+ // claim exists for that address or that ip. A single INSERT ... SELECT
75
+ // WHERE NOT EXISTS statement is atomic in SQLite, so two concurrent requests
76
+ // cannot both reserve. An empty `ip` disables the ip bucket, and an empty
77
+ // `address` disables the address bucket (used by /api/execute, whose `to` is
78
+ // a shared contract and so cannot be a rate limiting key: without the
79
+ // `address <> ''` guard every such row would collide with every other one
80
+ // and the first call would lock out every caller for a whole cooldown).
81
+ async reserveClaim(params: {
82
+ chainId: string;
83
+ address: string;
84
+ ip: string;
85
+ amount: string;
86
+ now: number;
87
+ addressCutoff: number;
88
+ ipCutoff: number;
89
+ }): Promise<number | null> {
90
+ const {chainId, address, ip, amount, now, addressCutoff, ipCutoff} = params;
91
+ const {results} = await this.db
92
+ .prepare(
93
+ `INSERT INTO Claims (chain_id, address, ip, amount, claimed_at)
94
+ SELECT ?, ?, ?, ?, ?
95
+ WHERE NOT EXISTS (
96
+ SELECT 1 FROM Claims
97
+ WHERE chain_id = ?
98
+ AND (
99
+ (address <> '' AND address = ? AND claimed_at > ?)
100
+ OR (ip <> '' AND ip = ? AND claimed_at > ?)
101
+ )
102
+ )
103
+ RETURNING id;`,
104
+ )
105
+ .bind(
106
+ chainId,
107
+ address,
108
+ ip,
109
+ amount,
110
+ now,
111
+ chainId,
112
+ address,
113
+ addressCutoff,
114
+ ip,
115
+ ipCutoff,
116
+ )
117
+ .all<{id: number}>();
118
+ if (results.length === 0) {
119
+ return null;
120
+ }
121
+ return results[0].id;
122
+ }
123
+
124
+ // Only called when reserveClaim returned null, to explain why.
125
+ async getRateLimitHit(params: {
126
+ chainId: string;
127
+ address: string;
128
+ ip: string;
129
+ now: number;
130
+ addressCutoff: number;
131
+ ipCutoff: number;
132
+ addressCooldown: number;
133
+ ipCooldown: number;
134
+ }): Promise<RateLimitHit> {
135
+ const {
136
+ chainId,
137
+ address,
138
+ ip,
139
+ now,
140
+ addressCutoff,
141
+ ipCutoff,
142
+ addressCooldown,
143
+ ipCooldown,
144
+ } = params;
145
+ const {results} = await this.db
146
+ .prepare(
147
+ `SELECT address, ip, claimed_at FROM Claims
148
+ WHERE chain_id = ?
149
+ AND (
150
+ (address <> '' AND address = ? AND claimed_at > ?)
151
+ OR (ip <> '' AND ip = ? AND claimed_at > ?)
152
+ )
153
+ ORDER BY claimed_at DESC LIMIT 1;`,
154
+ )
155
+ .bind(chainId, address, addressCutoff, ip, ipCutoff)
156
+ .all<{address: string; ip: string; claimed_at: number}>();
157
+
158
+ if (results.length === 0) {
159
+ // the offending claim expired between the two queries, ask for an immediate retry
160
+ return {reason: 'address', retryAfter: 1};
161
+ }
162
+ const row = results[0];
163
+ // `address !== ''` matters: an /api/execute row also has an empty address,
164
+ // so a plain `row.address === address` would call an ip hit an address hit
165
+ // and report the wrong cooldown.
166
+ const matchedAddress = address !== '' && row.address === address;
167
+ const cooldown = matchedAddress ? addressCooldown : ipCooldown;
168
+ const retryAfter = Math.max(1, row.claimed_at + cooldown - now);
169
+ return {reason: matchedAddress ? 'address' : 'ip', retryAfter};
170
+ }
171
+
172
+ // Releases a reservation when the claim ended up not being dispensed.
173
+ async cancelClaim(id: number): Promise<void> {
174
+ await this.db.prepare(`DELETE FROM Claims WHERE id = ?;`).bind(id).all();
175
+ }
176
+
177
+ async recordClaimTx(id: number, txHash: string): Promise<void> {
178
+ await this.db
179
+ .prepare(`UPDATE Claims SET tx_hash = ? WHERE id = ?;`)
180
+ .bind(txHash, id)
181
+ .all();
182
+ }
183
+
184
+ // ------------------------------------------------------------------------
185
+ // per chain send lock (nonce serialisation)
186
+ // ------------------------------------------------------------------------
187
+
188
+ // Takes the per chain lock so only one claim at a time picks a nonce.
189
+ // The lock is time boxed, so a crashed request cannot wedge the faucet.
190
+ async acquireChainLock(
191
+ chainId: string,
192
+ now: number,
193
+ lockedUntil: number,
194
+ ): Promise<ChainLockAcquisition> {
195
+ await this.db
196
+ .prepare(
197
+ `INSERT INTO ChainLocks (chain_id, locked_until, last_nonce)
198
+ VALUES (?, 0, NULL)
199
+ ON CONFLICT (chain_id) DO NOTHING;`,
200
+ )
201
+ .bind(chainId)
202
+ .all();
203
+
204
+ const {results} = await this.db
205
+ .prepare(
206
+ `UPDATE ChainLocks SET locked_until = ?
207
+ WHERE chain_id = ? AND locked_until < ?
208
+ RETURNING last_nonce;`,
209
+ )
210
+ .bind(lockedUntil, chainId, now)
211
+ .all<{last_nonce: number | null}>();
212
+
213
+ if (results.length === 0) {
214
+ return {acquired: false, lastNonce: null};
215
+ }
216
+ return {acquired: true, lastNonce: results[0].last_nonce ?? null};
217
+ }
218
+
219
+ async releaseChainLock(
220
+ chainId: string,
221
+ nonceUsed?: number | null,
222
+ ): Promise<void> {
223
+ if (typeof nonceUsed === 'number') {
224
+ await this.db
225
+ .prepare(
226
+ `UPDATE ChainLocks SET locked_until = 0, last_nonce = ? WHERE chain_id = ?;`,
227
+ )
228
+ .bind(nonceUsed, chainId)
229
+ .all();
230
+ } else {
231
+ await this.db
232
+ .prepare(`UPDATE ChainLocks SET locked_until = 0 WHERE chain_id = ?;`)
233
+ .bind(chainId)
234
+ .all();
235
+ }
236
+ }
237
+
238
+ // ------------------------------------------------------------------------
239
+ // housekeeping
240
+ // ------------------------------------------------------------------------
241
+
242
+ async cleanup(tokenCutoff: number, claimCutoff: number): Promise<void> {
243
+ await this.db.batch([
244
+ this.db
245
+ .prepare(`DELETE FROM UsedTokens WHERE used_at < ?;`)
246
+ .bind(tokenCutoff),
247
+ this.db
248
+ .prepare(`DELETE FROM Claims WHERE claimed_at < ?;`)
249
+ .bind(claimCutoff),
250
+ ]);
251
+ }
252
+ }