@sharadox/protection-web-library 0.1.0-development.0 → 0.1.0-development.12

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 (41) hide show
  1. package/README.md +48 -2
  2. package/distribution/proof-of-work/index.d.ts.map +1 -1
  3. package/distribution/proof-of-work/index.js +3 -2
  4. package/distribution/proof-of-work/index.js.map +1 -1
  5. package/distribution/protection-database/type.d.ts +30 -0
  6. package/distribution/protection-database/type.d.ts.map +1 -0
  7. package/distribution/protection-database/type.js +2 -0
  8. package/distribution/protection-database/type.js.map +1 -0
  9. package/distribution/protection-migration/index.d.ts +18 -0
  10. package/distribution/protection-migration/index.d.ts.map +1 -0
  11. package/distribution/protection-migration/index.js +66 -0
  12. package/distribution/protection-migration/index.js.map +1 -0
  13. package/distribution/rate-limit/index.d.ts +18 -0
  14. package/distribution/rate-limit/index.d.ts.map +1 -0
  15. package/distribution/rate-limit/index.js +68 -0
  16. package/distribution/rate-limit/index.js.map +1 -0
  17. package/distribution/rate-limit/type.d.ts +22 -0
  18. package/distribution/rate-limit/type.d.ts.map +1 -0
  19. package/distribution/rate-limit/type.js +2 -0
  20. package/distribution/rate-limit/type.js.map +1 -0
  21. package/distribution/rate-limit-prune/index.d.ts +14 -0
  22. package/distribution/rate-limit-prune/index.d.ts.map +1 -0
  23. package/distribution/rate-limit-prune/index.js +13 -0
  24. package/distribution/rate-limit-prune/index.js.map +1 -0
  25. package/distribution/solution-redemption/index.d.ts +19 -0
  26. package/distribution/solution-redemption/index.d.ts.map +1 -0
  27. package/distribution/solution-redemption/index.js +22 -0
  28. package/distribution/solution-redemption/index.js.map +1 -0
  29. package/distribution/spending-cap/index.d.ts +14 -0
  30. package/distribution/spending-cap/index.d.ts.map +1 -0
  31. package/distribution/spending-cap/index.js +38 -0
  32. package/distribution/spending-cap/index.js.map +1 -0
  33. package/distribution/spending-cap/type.d.ts +21 -0
  34. package/distribution/spending-cap/type.d.ts.map +1 -0
  35. package/distribution/spending-cap/type.js +2 -0
  36. package/distribution/spending-cap/type.js.map +1 -0
  37. package/distribution/used-challenge-prune/index.d.ts +13 -0
  38. package/distribution/used-challenge-prune/index.d.ts.map +1 -0
  39. package/distribution/used-challenge-prune/index.js +12 -0
  40. package/distribution/used-challenge-prune/index.js.map +1 -0
  41. package/package.json +18 -17
package/README.md CHANGED
@@ -5,9 +5,10 @@ Protection for web forms and APIs against repeated tries, bots and attacks on th
5
5
  - token-bucket rate limits;
6
6
  - address groups that treat a whole IPv6 /64 as one visitor;
7
7
  - an invisible proof-of-work challenge (no third-party captcha, no puzzle);
8
- - difficulty that rises with each strike.
8
+ - difficulty that rises with each strike;
9
+ - layered rate limits and hard spending caps kept in Postgres (through `@sharadox/database-web-library`).
9
10
 
10
- Everything is pure or stateless: the caller decides where buckets and used challenge ids are stored.
11
+ The building blocks are pure or stateless; the Postgres parts store only keyed hashes, never contacts or addresses.
11
12
 
12
13
  ## Install
13
14
 
@@ -20,6 +21,10 @@ pnpm add @sharadox/protection-web-library
20
21
  | Variable | Meaning |
21
22
  | ---------------------- | ------------------------------------------------------------------------------------------------------------------ |
22
23
  | `PROOF_OF_WORK_SECRET` | At least 32 random characters, server only. It signs challenges (suggested name: the library only takes `secret`). |
24
+ | `RATE_LIMIT_SECRET` | At least 32 random characters, server only. Rate-limit keys are stored as HMACs under it (suggested name). |
25
+
26
+ The Postgres parts need their tables: run `migrateProtection(database)` when the application migrates. They are
27
+ tracked in their own table (`protection_migration`), apart from the application's migrations.
23
28
 
24
29
  ## API
25
30
 
@@ -79,6 +84,47 @@ Adds one bit per strike, which doubles the work, from `base` up to `maximum`.
79
84
  The building blocks of the solver. `sha256` is a synchronous FIPS 180-4 SHA-256, made for many small hashes. It is
80
85
  not for secrets.
81
86
 
87
+ ### `protection-migration`: `migrateProtection(database)`, `protectionMigrations`, `PROTECTION_MIGRATION_TABLE`
88
+
89
+ Creates `rate_limit_bucket`, `spending_cap_usage` and `used_challenge`, every row with a UUIDv7 `id` (challenge ids
90
+ are UUIDv7 too). Type a Kysely instance with `ProtectionDatabase`
91
+ (`protection-database/type`), or include it in the application's own schema type.
92
+
93
+ ### `rate-limit`: `limitRate(database, layers, { secret, now? })` → `{ allowed, retryAfterSeconds, blockedBy }`
94
+
95
+ Every layer must have the tokens, or nothing is taken from any of them.
96
+
97
+ - One transaction, rows locked in a fixed order: concurrent requests never pass a capacity and never deadlock.
98
+ - `blockedBy` lists the keys that blocked, as given: count strikes with it for `adaptiveDifficulty`.
99
+ - The same key twice is refused.
100
+
101
+ ```ts
102
+ const result = await limitRate(
103
+ database,
104
+ [
105
+ { key: `contact:${email}`, rule: { capacity: 5, refillPerSecond: 1 / 600 } },
106
+ { key: `address:${addressGroup(ip)}`, rule: { capacity: 20, refillPerSecond: 1 / 60 } },
107
+ { key: "global:sign-in", rule: { capacity: 500, refillPerSecond: 1 } },
108
+ ],
109
+ { secret: process.env.RATE_LIMIT_SECRET! },
110
+ );
111
+ ```
112
+
113
+ ### `solution-redemption`: `redeemSolution(database, solution, { secret, now? })`
114
+
115
+ `verifySolution` plus spending it: a valid solution counts once (its challenge id is kept until the challenge
116
+ expires), so a solved challenge can't be replayed. Reasons: `signature`, `expired`, `work`, `used`.
117
+ `pruneUsedChallenges(database, { now? })` (`used-challenge-prune`) forgets expired ones, from a daily job.
118
+
119
+ ### `rate-limit-prune`: `pruneRateLimits(database, { before })` → deleted count
120
+
121
+ For a daily job. Pick `before` so that every bucket untouched since then would be full again.
122
+
123
+ ### `spending-cap`: `spendFromCap(database, { name, limit, period: "day" | "month" }, { now?, cost = 1 })` → `{ allowed, used, remaining, resetsAt }`
124
+
125
+ A hard cap per UTC day or month on anything that costs money. Past the limit it refuses: pause and alert, never
126
+ spend. It is one atomic statement, and a refused spend uses nothing.
127
+
82
128
  ## License
83
129
 
84
130
  Sharadox Open Source License 0.1.0 (see `LICENSE.md`).
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/proof-of-work/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,SAAS,EACT,sBAAsB,EACtB,QAAQ,EACR,YAAY,EACZ,qBAAqB,EACtB,MAAM,qDAAqD,CAAC;AAS7D;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,EAC9B,MAAM,EACN,UAAU,EACV,GAAgB,EAChB,eAAqB,GACtB,EAAE,sBAAsB,GAAG,SAAS,CASpC;AAED;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAC5B,EAAE,SAAS,EAAE,KAAK,EAAE,EAAE,QAAQ,EAC9B,EAAE,MAAM,EAAE,GAAgB,EAAE,EAAE,qBAAqB,GAClD,YAAY,CAWd"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/proof-of-work/index.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,SAAS,EACT,sBAAsB,EACtB,QAAQ,EACR,YAAY,EACZ,qBAAqB,EACtB,MAAM,qDAAqD,CAAC;AAS7D;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,EAC9B,MAAM,EACN,UAAU,EACV,GAAgB,EAChB,eAAqB,GACtB,EAAE,sBAAsB,GAAG,SAAS,CASpC;AAED;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAC5B,EAAE,SAAS,EAAE,KAAK,EAAE,EAAE,QAAQ,EAC9B,EAAE,MAAM,EAAE,GAAgB,EAAE,EAAE,qBAAqB,GAClD,YAAY,CAWd"}
@@ -1,4 +1,5 @@
1
- import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
1
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { uuidVersion7 } from "@sharadox/web-library/identifier/uuid-version-7";
2
3
  import { leadingZeroBits } from "@sharadox/protection-web-library/leading-zero-bits";
3
4
  function checkSecret(secret) {
4
5
  if (secret.length < 32)
@@ -15,7 +16,7 @@ const sign = (secret, { id, salt, difficulty, expiresAt }) => createHmac("sha256
15
16
  export function createChallenge({ secret, difficulty, now = Date.now(), lifetimeSeconds = 300, }) {
16
17
  checkSecret(secret);
17
18
  const fields = {
18
- id: randomUUID(),
19
+ id: uuidVersion7({ now }),
19
20
  salt: randomBytes(16).toString("base64url"),
20
21
  difficulty,
21
22
  expiresAt: now + lifetimeSeconds * 1000,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/proof-of-work/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC/F,OAAO,EAAE,eAAe,EAAE,MAAM,oDAAoD,CAAC;AASrF,SAAS,WAAW,CAAC,MAAc;IACjC,IAAI,MAAM,CAAC,MAAM,GAAG,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,2DAA2D,CAAC,CAAC;AACvG,CAAC;AAED,MAAM,IAAI,GAAG,CAAC,MAAc,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,SAAS,EAAgC,EAAE,EAAE,CACjG,UAAU,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,IAAI,IAAI,UAAU,IAAI,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;AAEtG;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAAC,EAC9B,MAAM,EACN,UAAU,EACV,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,EAChB,eAAe,GAAG,GAAG,GACE;IACvB,WAAW,CAAC,MAAM,CAAC,CAAC;IACpB,MAAM,MAAM,GAAG;QACb,EAAE,EAAE,UAAU,EAAE;QAChB,IAAI,EAAE,WAAW,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC;QAC3C,UAAU;QACV,SAAS,EAAE,GAAG,GAAG,eAAe,GAAG,IAAI;KACxC,CAAC;IACF,OAAO,EAAE,GAAG,MAAM,EA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I,CAAC,GAAG,EAAE,EAAyB;IAEnD,WAAW,CAAC,MAAM,CAAC,CAAC;IACpB,MAAM,EAAE,SAAS,EAAE,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC;IAC3C,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACnD,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC;IAC7C,IAAI,QAAQ,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,QAAQ,EAAE,KAAK,CAAC;QACvE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC;IAC/C,IAAI,GAAG,GAAG,SAAS,CAAC,SAAS;QAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;IAC1E,MAAM,IAAI,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,GAAG,SAAS,CAAC,IAAI,IAAI,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC;IAChF,IAAI,eAAe,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC,UAAU;QAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;IAC1F,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,EAAE,SAAS,CAAC,EAAE,EAAE,CAAC;AAC3C,CAAC"}
@@ -0,0 +1,30 @@
1
+ import type { Generated } from "kysely";
2
+ /** One rate-limit bucket: its key (an HMAC, never the raw contact or address), tokens left and when last changed. */
3
+ export interface RateLimitBucketTable {
4
+ /** UUIDv7, made by the database. */
5
+ id: Generated<string>;
6
+ key: string;
7
+ tokens: number;
8
+ updated_at: Date;
9
+ }
10
+ /** How much of a spending cap one period has used. */
11
+ export interface SpendingCapUsageTable {
12
+ /** UUIDv7, made by the database. */
13
+ id: Generated<string>;
14
+ name: string;
15
+ period_start: Date;
16
+ used: number;
17
+ }
18
+ /** A proof-of-work challenge already answered, kept until it expires so its solution counts once. */
19
+ export interface UsedChallengeTable {
20
+ /** The challenge's UUIDv7. */
21
+ id: string;
22
+ expires_at: Date;
23
+ }
24
+ /** The tables `protectionMigrations` creates, for typing a Kysely instance. */
25
+ export interface ProtectionDatabase {
26
+ rate_limit_bucket: RateLimitBucketTable;
27
+ spending_cap_usage: SpendingCapUsageTable;
28
+ used_challenge: UsedChallengeTable;
29
+ }
30
+ //# sourceMappingURL=type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/protection-database/type.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AAExC,qHAAqH;AACrH,MAAM,WAAW,oBAAoB;IACnC,oCAAoC;IACpC,EAAE,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC;IACtB,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,IAAI,CAAC;CAClB;AAED,sDAAsD;AACtD,MAAM,WAAW,qBAAqB;IACpC,oCAAoC;IACpC,EAAE,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,IAAI,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;CACd;AAED,qGAAqG;AACrG,MAAM,WAAW,kBAAkB;IACjC,8BAA8B;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,UAAU,EAAE,IAAI,CAAC;CAClB;AAED,+EAA+E;AAC/E,MAAM,WAAW,kBAAkB;IACjC,iBAAiB,EAAE,oBAAoB,CAAC;IACxC,kBAAkB,EAAE,qBAAqB,CAAC;IAC1C,cAAc,EAAE,kBAAkB,CAAC;CACpC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/protection-database/type.ts"],"names":[],"mappings":""}
@@ -0,0 +1,18 @@
1
+ import type { Kysely } from "kysely";
2
+ import type { Migration } from "@sharadox/database-web-library/migration/type";
3
+ /** The table that records which protection migrations a database has applied (apart from the application's own). */
4
+ export declare const PROTECTION_MIGRATION_TABLE = "protection_migration";
5
+ /**
6
+ * The protection tables, forward only: rate-limit buckets, spending-cap usage and used challenges, each row with a
7
+ * UUIDv7 `id`.
8
+ */
9
+ export declare const protectionMigrations: Migration[];
10
+ /**
11
+ * Creates or updates the protection tables, tracked in their own migration table so they never clash with the
12
+ * application's migrations. Returns the names applied.
13
+ *
14
+ * @example
15
+ * await migrateProtection(database);
16
+ */
17
+ export declare function migrateProtection<Schema>(database: Kysely<Schema>): Promise<string[]>;
18
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/protection-migration/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAErC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+CAA+C,CAAC;AAE/E,oHAAoH;AACpH,eAAO,MAAM,0BAA0B,yBAAyB,CAAC;AAEjE;;;GAGG;AACH,eAAO,MAAM,oBAAoB,EAAE,SAAS,EA+C3C,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAErF"}
@@ -0,0 +1,66 @@
1
+ import { migrate } from "@sharadox/database-web-library/migration";
2
+ /** The table that records which protection migrations a database has applied (apart from the application's own). */
3
+ export const PROTECTION_MIGRATION_TABLE = "protection_migration";
4
+ /**
5
+ * The protection tables, forward only: rate-limit buckets, spending-cap usage and used challenges, each row with a
6
+ * UUIDv7 `id`.
7
+ */
8
+ export const protectionMigrations = [
9
+ {
10
+ name: "0001-rate-limit-and-spending-cap",
11
+ sql: `
12
+ create table rate_limit_bucket (
13
+ key text primary key,
14
+ tokens double precision not null check (tokens >= 0),
15
+ updated_at timestamptz not null
16
+ );
17
+ create index rate_limit_bucket_updated_at on rate_limit_bucket (updated_at);
18
+ create table spending_cap_usage (
19
+ name text not null,
20
+ period_start timestamptz not null,
21
+ used integer not null check (used >= 0),
22
+ primary key (name, period_start)
23
+ );
24
+ `,
25
+ },
26
+ {
27
+ name: "0002-used-challenge",
28
+ sql: `
29
+ create table used_challenge (
30
+ id text primary key check (length(id) <= 100),
31
+ expires_at timestamptz not null
32
+ );
33
+ create index used_challenge_expires_at on used_challenge (expires_at);
34
+ `,
35
+ },
36
+ {
37
+ name: "0003-identifier-version-7",
38
+ sql: `
39
+ alter table rate_limit_bucket drop constraint rate_limit_bucket_pkey;
40
+ alter table rate_limit_bucket add constraint rate_limit_bucket_key_key unique (key);
41
+ alter table rate_limit_bucket
42
+ add column id uuid primary key default uuidv7() check (uuid_extract_version(id) = 7);
43
+ alter table spending_cap_usage drop constraint spending_cap_usage_pkey;
44
+ alter table spending_cap_usage
45
+ add constraint spending_cap_usage_name_period_start_key unique (name, period_start);
46
+ alter table spending_cap_usage
47
+ add column id uuid primary key default uuidv7() check (uuid_extract_version(id) = 7);
48
+ delete from used_challenge where expires_at < now()
49
+ or id !~ '^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$';
50
+ alter table used_challenge drop constraint used_challenge_id_check;
51
+ alter table used_challenge alter column id type uuid using id::uuid;
52
+ alter table used_challenge add constraint used_challenge_id_check check (uuid_extract_version(id) = 7);
53
+ `,
54
+ },
55
+ ];
56
+ /**
57
+ * Creates or updates the protection tables, tracked in their own migration table so they never clash with the
58
+ * application's migrations. Returns the names applied.
59
+ *
60
+ * @example
61
+ * await migrateProtection(database);
62
+ */
63
+ export function migrateProtection(database) {
64
+ return migrate(database, protectionMigrations, { table: PROTECTION_MIGRATION_TABLE });
65
+ }
66
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/protection-migration/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,0CAA0C,CAAC;AAGnE,oHAAoH;AACpH,MAAM,CAAC,MAAM,0BAA0B,GAAG,sBAAsB,CAAC;AAEjE;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAgB;IAC/C;QACE,IAAI,EAAE,kCAAkC;QACxC,GAAG,EAAE;;;;;;;;;;;;;KAaJ;KACF;IACD;QACE,IAAI,EAAE,qBAAqB;QAC3B,GAAG,EAAE;;;;;;KAMJ;KACF;IACD;QACE,IAAI,EAAE,2BAA2B;QACjC,GAAG,EAAE;;;;;;;;;;;;;;;KAeJ;KACF;CACF,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAAS,QAAwB;IAChE,OAAO,OAAO,CAAC,QAAQ,EAAE,oBAAoB,EAAE,EAAE,KAAK,EAAE,0BAA0B,EAAE,CAAC,CAAC;AACxF,CAAC"}
@@ -0,0 +1,18 @@
1
+ import type { Kysely } from "kysely";
2
+ import type { ProtectionDatabase } from "@sharadox/protection-web-library/protection-database/type";
3
+ import type { RateLimitLayer, RateLimitOptions, RateLimitResult } from "@sharadox/protection-web-library/rate-limit/type";
4
+ /**
5
+ * Layered rate limiting in Postgres: the action goes ahead only when every layer (per contact, per address group,
6
+ * per account, global…) has the tokens for it, and then it takes them from all of them at once; a blocked action
7
+ * takes nothing. One transaction with the rows locked in a fixed order, so concurrent requests never exceed a
8
+ * capacity and never deadlock. Keys are stored as HMACs, so the table holds no contacts or addresses.
9
+ *
10
+ * @example
11
+ * const result = await limitRate(database, [
12
+ * { key: `contact:${email}`, rule: { capacity: 5, refillPerSecond: 1 / 600 } },
13
+ * { key: `address:${addressGroup(ip)}`, rule: { capacity: 20, refillPerSecond: 1 / 60 } },
14
+ * ], { secret: process.env.PROTECTION_SECRET! });
15
+ * if (!result.allowed) return tooManyRequests(result.retryAfterSeconds);
16
+ */
17
+ export declare function limitRate(database: Kysely<ProtectionDatabase>, layers: RateLimitLayer[], { secret, now }: RateLimitOptions): Promise<RateLimitResult>;
18
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/rate-limit/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACrC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2DAA2D,CAAC;AACpG,OAAO,KAAK,EACV,cAAc,EACd,gBAAgB,EAChB,eAAe,EAChB,MAAM,kDAAkD,CAAC;AAG1D;;;;;;;;;;;;GAYG;AACH,wBAAsB,SAAS,CAC7B,QAAQ,EAAE,MAAM,CAAC,kBAAkB,CAAC,EACpC,MAAM,EAAE,cAAc,EAAE,EACxB,EAAE,MAAM,EAAE,GAAgB,EAAE,EAAE,gBAAgB,GAC7C,OAAO,CAAC,eAAe,CAAC,CAoD1B"}
@@ -0,0 +1,68 @@
1
+ import { createHmac } from "node:crypto";
2
+ import { takeToken } from "@sharadox/protection-web-library/token-bucket";
3
+ /**
4
+ * Layered rate limiting in Postgres: the action goes ahead only when every layer (per contact, per address group,
5
+ * per account, global…) has the tokens for it, and then it takes them from all of them at once; a blocked action
6
+ * takes nothing. One transaction with the rows locked in a fixed order, so concurrent requests never exceed a
7
+ * capacity and never deadlock. Keys are stored as HMACs, so the table holds no contacts or addresses.
8
+ *
9
+ * @example
10
+ * const result = await limitRate(database, [
11
+ * { key: `contact:${email}`, rule: { capacity: 5, refillPerSecond: 1 / 600 } },
12
+ * { key: `address:${addressGroup(ip)}`, rule: { capacity: 20, refillPerSecond: 1 / 60 } },
13
+ * ], { secret: process.env.PROTECTION_SECRET! });
14
+ * if (!result.allowed) return tooManyRequests(result.retryAfterSeconds);
15
+ */
16
+ export async function limitRate(database, layers, { secret, now = Date.now() }) {
17
+ if (secret.length < 32)
18
+ throw new Error("limitRate: the secret must be at least 32 characters");
19
+ const seen = new Set();
20
+ for (const { key } of layers) {
21
+ if (seen.has(key))
22
+ throw new Error(`limitRate: the key "${key}" appears twice`);
23
+ seen.add(key);
24
+ }
25
+ if (layers.length === 0)
26
+ return { allowed: true, retryAfterSeconds: 0, blockedBy: [] };
27
+ const hashed = layers
28
+ .map((layer) => ({ ...layer, hash: createHmac("sha256", secret).update(layer.key).digest("base64url") }))
29
+ .sort((a, b) => (a.hash < b.hash ? -1 : 1));
30
+ return database.transaction().execute(async (transaction) => {
31
+ const at = new Date(now);
32
+ await transaction
33
+ .insertInto("rate_limit_bucket")
34
+ .values(hashed.map(({ hash, rule }) => ({ key: hash, tokens: rule.capacity, updated_at: at })))
35
+ .onConflict((conflict) => conflict.column("key").doNothing())
36
+ .execute();
37
+ const rows = await transaction
38
+ .selectFrom("rate_limit_bucket")
39
+ .selectAll()
40
+ .where("key", "in", hashed.map(({ hash }) => hash))
41
+ .orderBy("key")
42
+ .forUpdate()
43
+ .execute();
44
+ const stored = new Map(rows.map((row) => [row.key, { tokens: row.tokens, updatedAt: row.updated_at.getTime() }]));
45
+ const steps = hashed.map((layer) => ({
46
+ layer,
47
+ step: takeToken(stored.get(layer.hash), layer.rule, now, layer.cost),
48
+ }));
49
+ const blocked = steps.filter(({ step }) => !step.allowed);
50
+ if (blocked.length > 0) {
51
+ const order = layers.map(({ key }) => key);
52
+ return {
53
+ allowed: false,
54
+ retryAfterSeconds: Math.max(...blocked.map(({ step }) => step.retryAfterSeconds)),
55
+ blockedBy: blocked.map(({ layer }) => layer.key).sort((a, b) => order.indexOf(a) - order.indexOf(b)),
56
+ };
57
+ }
58
+ for (const { layer, step } of steps) {
59
+ await transaction
60
+ .updateTable("rate_limit_bucket")
61
+ .set({ tokens: step.bucket.tokens, updated_at: new Date(step.bucket.updatedAt) })
62
+ .where("key", "=", layer.hash)
63
+ .execute();
64
+ }
65
+ return { allowed: true, retryAfterSeconds: 0, blockedBy: [] };
66
+ });
67
+ }
68
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/rate-limit/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAQzC,OAAO,EAAE,SAAS,EAAE,MAAM,+CAA+C,CAAC;AAE1E;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAC7B,QAAoC,EACpC,MAAwB,EACxB,EAAE,MAAM,EAAE,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,EAAoB;IAE9C,IAAI,MAAM,CAAC,MAAM,GAAG,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAChG,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,KAAK,MAAM,EAAE,GAAG,EAAE,IAAI,MAAM,EAAE,CAAC;QAC7B,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,uBAAuB,GAAG,iBAAiB,CAAC,CAAC;QAChF,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAChB,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,iBAAiB,EAAE,CAAC,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC;IACvF,MAAM,MAAM,GAAG,MAAM;SAClB,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,UAAU,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAA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MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,UAAU,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC;iBAChF,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE,KAAK,CAAC,IAAI,CAAC;iBAC7B,OAAO,EAAE,CAAC;QACf,CAAC;QACD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,iBAAiB,EAAE,CAAC,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC;IAChE,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,22 @@
1
+ import type { TokenBucketRule } from "@sharadox/protection-web-library/token-bucket/type";
2
+ /** One layer of a rate limit: what is counted (`contact:…`, `address:…`, `account:…`) and how fast. */
3
+ export interface RateLimitLayer {
4
+ key: string;
5
+ rule: TokenBucketRule;
6
+ /** Tokens this action takes from the layer (1 by default). */
7
+ cost?: number;
8
+ }
9
+ export interface RateLimitOptions {
10
+ /** At least 32 characters, kept outside the database: keys are stored only as HMACs under it. */
11
+ secret: string;
12
+ /** Milliseconds since 1970 (now by default). */
13
+ now?: number;
14
+ }
15
+ export interface RateLimitResult {
16
+ allowed: boolean;
17
+ /** Seconds until every blocking layer has enough tokens again (0 when allowed). */
18
+ retryAfterSeconds: number;
19
+ /** The keys of the layers that blocked, as given. */
20
+ blockedBy: string[];
21
+ }
22
+ //# sourceMappingURL=type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/rate-limit/type.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oDAAoD,CAAC;AAE1F,uGAAuG;AACvG,MAAM,WAAW,cAAc;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,eAAe,CAAC;IACtB,8DAA8D;IAC9D,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,gBAAgB;IAC/B,iGAAiG;IACjG,MAAM,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,OAAO,CAAC;IACjB,mFAAmF;IACnF,iBAAiB,EAAE,MAAM,CAAC;IAC1B,qDAAqD;IACrD,SAAS,EAAE,MAAM,EAAE,CAAC;CACrB"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/rate-limit/type.ts"],"names":[],"mappings":""}
@@ -0,0 +1,14 @@
1
+ import type { Kysely } from "kysely";
2
+ import type { ProtectionDatabase } from "@sharadox/protection-web-library/protection-database/type";
3
+ /**
4
+ * Deletes the rate-limit buckets untouched since `before`, from a daily job. Choose `before` so every such bucket
5
+ * would be full again (now minus the slowest layer's capacity ÷ refill): deleting a full bucket changes nothing.
6
+ * Returns how many were deleted.
7
+ *
8
+ * @example
9
+ * await pruneRateLimits(database, { before: new Date(Date.now() - 7 * 86_400_000) });
10
+ */
11
+ export declare function pruneRateLimits(database: Kysely<ProtectionDatabase>, { before }: {
12
+ before: Date;
13
+ }): Promise<number>;
14
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/rate-limit-prune/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACrC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2DAA2D,CAAC;AAEpG;;;;;;;GAOG;AACH,wBAAsB,eAAe,CACnC,QAAQ,EAAE,MAAM,CAAC,kBAAkB,CAAC,EACpC,EAAE,MAAM,EAAE,EAAE;IAAE,MAAM,EAAE,IAAI,CAAA;CAAE,GAC3B,OAAO,CAAC,MAAM,CAAC,CAGjB"}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Deletes the rate-limit buckets untouched since `before`, from a daily job. Choose `before` so every such bucket
3
+ * would be full again (now minus the slowest layer's capacity ÷ refill): deleting a full bucket changes nothing.
4
+ * Returns how many were deleted.
5
+ *
6
+ * @example
7
+ * await pruneRateLimits(database, { before: new Date(Date.now() - 7 * 86_400_000) });
8
+ */
9
+ export async function pruneRateLimits(database, { before }) {
10
+ const result = await database.deleteFrom("rate_limit_bucket").where("updated_at", "<", before).executeTakeFirst();
11
+ return Number(result.numDeletedRows);
12
+ }
13
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/rate-limit-prune/index.ts"],"names":[],"mappings":"AAGA;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,QAAoC,EACpC,EAAE,MAAM,EAAoB;IAE5B,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,UAAU,CAAC,mBAAmB,CAAC,CAAC,KAAK,CAAC,YAAY,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC,gBAAgB,EAAE,CAAC;IAClH,OAAO,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;AACvC,CAAC"}
@@ -0,0 +1,19 @@
1
+ import type { Kysely } from "kysely";
2
+ import type { Solution, VerifySolutionOptions } from "@sharadox/protection-web-library/proof-of-work/type";
3
+ import type { ProtectionDatabase } from "@sharadox/protection-web-library/protection-database/type";
4
+ /**
5
+ * Checks a proof-of-work solution and spends it: a valid one counts once (its challenge id is kept until the
6
+ * challenge expires), so one solved challenge can't be replayed. Nothing is stored for invalid solutions.
7
+ *
8
+ * @example
9
+ * const verification = await redeemSolution(database, solution, { secret: process.env.PROOF_OF_WORK_SECRET! });
10
+ * if (!verification.valid) return refuse(verification.reason);
11
+ */
12
+ export declare function redeemSolution(database: Kysely<ProtectionDatabase>, solution: Solution, options: VerifySolutionOptions): Promise<{
13
+ valid: true;
14
+ id: string;
15
+ } | {
16
+ valid: false;
17
+ reason: "signature" | "expired" | "work" | "used";
18
+ }>;
19
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/solution-redemption/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACrC,OAAO,KAAK,EAAE,QAAQ,EAAE,qBAAqB,EAAE,MAAM,qDAAqD,CAAC;AAE3G,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2DAA2D,CAAC;AAEpG;;;;;;;GAOG;AACH,wBAAsB,cAAc,CAClC,QAAQ,EAAE,MAAM,CAAC,kBAAkB,CAAC,EACpC,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC;IAAE,KAAK,EAAE,IAAI,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,WAAW,GAAG,SAAS,GAAG,MAAM,GAAG,MAAM,CAAA;CAAE,CAAC,CAU5G"}
@@ -0,0 +1,22 @@
1
+ import { verifySolution } from "@sharadox/protection-web-library/proof-of-work";
2
+ /**
3
+ * Checks a proof-of-work solution and spends it: a valid one counts once (its challenge id is kept until the
4
+ * challenge expires), so one solved challenge can't be replayed. Nothing is stored for invalid solutions.
5
+ *
6
+ * @example
7
+ * const verification = await redeemSolution(database, solution, { secret: process.env.PROOF_OF_WORK_SECRET! });
8
+ * if (!verification.valid) return refuse(verification.reason);
9
+ */
10
+ export async function redeemSolution(database, solution, options) {
11
+ const verification = verifySolution(solution, options);
12
+ if (!verification.valid)
13
+ return verification;
14
+ const stored = await database
15
+ .insertInto("used_challenge")
16
+ .values({ id: verification.id, expires_at: new Date(solution.challenge.expiresAt) })
17
+ .onConflict((conflict) => conflict.column("id").doNothing())
18
+ .returning("id")
19
+ .executeTakeFirst();
20
+ return stored ? verification : { valid: false, reason: "used" };
21
+ }
22
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/solution-redemption/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,gDAAgD,CAAC;AAGhF;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,QAAoC,EACpC,QAAkB,EAClB,OAA8B;IAE9B,MAAM,YAAY,GAAG,cAAc,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IACvD,IAAI,CAAC,YAAY,CAAC,KAAK;QAAE,OAAO,YAAY,CAAC;IAC7C,MAAM,MAAM,GAAG,MAAM,QAAQ;SAC1B,UAAU,CAAC,gBAAgB,CAAC;SAC5B,MAAM,CAAC,EAAE,EAAE,EAAE,YAAY,CAAC,EAAE,EAAE,UAAU,EAAE,IAAI,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,SAAS,CAAC,EAAE,CAAC;SACnF,UAAU,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,CAAC;SAC3D,SAAS,CAAC,IAAI,CAAC;SACf,gBAAgB,EAAE,CAAC;IACtB,OAAO,MAAM,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAClE,CAAC"}
@@ -0,0 +1,14 @@
1
+ import { type Kysely } from "kysely";
2
+ import type { ProtectionDatabase } from "@sharadox/protection-web-library/protection-database/type";
3
+ import type { SpendingCap, SpendOptions, SpendResult } from "@sharadox/protection-web-library/spending-cap/type";
4
+ /**
5
+ * Spends from a hard cap before doing something that costs money, so an attack can never run up the bill: past the
6
+ * limit it refuses (pause and alert; never spend). One atomic statement, so concurrent spends never pass the limit,
7
+ * and a refused spend uses nothing.
8
+ *
9
+ * @example
10
+ * const { allowed } = await spendFromCap(database, { name: "email-send", limit: 2_000, period: "day" });
11
+ * if (!allowed) return pauseSending();
12
+ */
13
+ export declare function spendFromCap(database: Kysely<ProtectionDatabase>, { name, limit, period }: SpendingCap, { now, cost }?: SpendOptions): Promise<SpendResult>;
14
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/spending-cap/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAO,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC1C,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2DAA2D,CAAC;AACpG,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,oDAAoD,CAAC;AAEjH;;;;;;;;GAQG;AACH,wBAAsB,YAAY,CAChC,QAAQ,EAAE,MAAM,CAAC,kBAAkB,CAAC,EACpC,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,WAAW,EACpC,EAAE,GAAgB,EAAE,IAAQ,EAAE,GAAE,YAAiB,GAChD,OAAO,CAAC,WAAW,CAAC,CA0BtB"}
@@ -0,0 +1,38 @@
1
+ import { sql } from "kysely";
2
+ /**
3
+ * Spends from a hard cap before doing something that costs money, so an attack can never run up the bill: past the
4
+ * limit it refuses (pause and alert; never spend). One atomic statement, so concurrent spends never pass the limit,
5
+ * and a refused spend uses nothing.
6
+ *
7
+ * @example
8
+ * const { allowed } = await spendFromCap(database, { name: "email-send", limit: 2_000, period: "day" });
9
+ * if (!allowed) return pauseSending();
10
+ */
11
+ export async function spendFromCap(database, { name, limit, period }, { now = Date.now(), cost = 1 } = {}) {
12
+ if (!Number.isInteger(cost) || cost < 1)
13
+ throw new Error("spendFromCap: the cost must be a positive whole number");
14
+ const date = new Date(now);
15
+ const [year, month, day] = [date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()];
16
+ const periodStart = new Date(period === "day" ? Date.UTC(year, month, day) : Date.UTC(year, month, 1));
17
+ const resetsAt = new Date(period === "day" ? Date.UTC(year, month, day + 1) : Date.UTC(year, month + 1, 1));
18
+ if (cost <= limit) {
19
+ const added = sql `spending_cap_usage.used + ${cost}`;
20
+ const spent = await database
21
+ .insertInto("spending_cap_usage")
22
+ .values({ name, period_start: periodStart, used: cost })
23
+ .onConflict((conflict) => conflict.columns(["name", "period_start"]).doUpdateSet({ used: added }).where(added, "<=", limit))
24
+ .returning("used")
25
+ .executeTakeFirst();
26
+ if (spent)
27
+ return { allowed: true, used: spent.used, remaining: limit - spent.used, resetsAt };
28
+ }
29
+ const current = await database
30
+ .selectFrom("spending_cap_usage")
31
+ .select("used")
32
+ .where("name", "=", name)
33
+ .where("period_start", "=", periodStart)
34
+ .executeTakeFirst();
35
+ const used = current?.used ?? 0;
36
+ return { allowed: false, used, remaining: limit - used, resetsAt };
37
+ }
38
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/spending-cap/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAe,MAAM,QAAQ,CAAC;AAI1C;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,QAAoC,EACpC,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAe,EACpC,EAAE,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,EAAE,IAAI,GAAG,CAAC,KAAmB,EAAE;IAEjD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,IAAI,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;IACnH,MAAM,IAAI,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC;IAC3B,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,cAAc,EAAE,EAAE,IAAI,CAAC,WAAW,EAAE,EAAE,IAAI,CAAC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;IACD,MAAM,OAAO,GAAG,MAAM,QAAQ;SAC3B,UAAU,CAAC,oBAAoB,CAAC;SAChC,MAAM,CAAC,MAAM,CAAC;SACd,KAAK,CAAC,MAAM,EAAE,GAAG,EAAE,IAAI,CAAC;SACxB,KAAK,CAAC,cAAc,EAAE,GAAG,EAAE,WAAW,CAAC;SACvC,gBAAgB,EAAE,CAAC;IACtB,MAAM,IAAI,GAAG,OAAO,EAAE,IAAI,IAAI,CAAC,CAAC;IAChC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,GAAG,IAAI,EAAE,QAAQ,EAAE,CAAC;AACrE,CAAC"}
@@ -0,0 +1,21 @@
1
+ /** A hard limit on something that costs money (emails, text messages…) per calendar day or month, in UTC. */
2
+ export interface SpendingCap {
3
+ name: string;
4
+ limit: number;
5
+ period: "day" | "month";
6
+ }
7
+ export interface SpendOptions {
8
+ /** Milliseconds since 1970 (now by default). */
9
+ now?: number;
10
+ /** A positive whole number (1 by default). */
11
+ cost?: number;
12
+ }
13
+ export interface SpendResult {
14
+ allowed: boolean;
15
+ /** Used in this period, after this spend when allowed. */
16
+ used: number;
17
+ remaining: number;
18
+ /** When the period ends and the cap starts again. */
19
+ resetsAt: Date;
20
+ }
21
+ //# sourceMappingURL=type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/spending-cap/type.ts"],"names":[],"mappings":"AAAA,6GAA6G;AAC7G,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,KAAK,GAAG,OAAO,CAAC;CACzB;AAED,MAAM,WAAW,YAAY;IAC3B,gDAAgD;IAChD,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,8CAA8C;IAC9C,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,OAAO,CAAC;IACjB,0DAA0D;IAC1D,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;IAClB,qDAAqD;IACrD,QAAQ,EAAE,IAAI,CAAC;CAChB"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/spending-cap/type.ts"],"names":[],"mappings":""}
@@ -0,0 +1,13 @@
1
+ import type { Kysely } from "kysely";
2
+ import type { ProtectionDatabase } from "@sharadox/protection-web-library/protection-database/type";
3
+ /**
4
+ * Forgets used challenges that have expired (their solutions are refused as expired anyway), from a daily job.
5
+ * Returns how many were deleted.
6
+ *
7
+ * @example
8
+ * await pruneUsedChallenges(database);
9
+ */
10
+ export declare function pruneUsedChallenges(database: Kysely<ProtectionDatabase>, { now }?: {
11
+ now?: number;
12
+ }): Promise<number>;
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/used-challenge-prune/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACrC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2DAA2D,CAAC;AAEpG;;;;;;GAMG;AACH,wBAAsB,mBAAmB,CACvC,QAAQ,EAAE,MAAM,CAAC,kBAAkB,CAAC,EACpC,EAAE,GAAgB,EAAE,GAAE;IAAE,GAAG,CAAC,EAAE,MAAM,CAAA;CAAO,GAC1C,OAAO,CAAC,MAAM,CAAC,CAGjB"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Forgets used challenges that have expired (their solutions are refused as expired anyway), from a daily job.
3
+ * Returns how many were deleted.
4
+ *
5
+ * @example
6
+ * await pruneUsedChallenges(database);
7
+ */
8
+ export async function pruneUsedChallenges(database, { now = Date.now() } = {}) {
9
+ const result = await database.deleteFrom("used_challenge").where("expires_at", "<", new Date(now)).executeTakeFirst();
10
+ return Number(result.numDeletedRows);
11
+ }
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/used-challenge-prune/index.ts"],"names":[],"mappings":"AAGA;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB,CACvC,QAAoC,EACpC,EAAE,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,KAAuB,EAAE;IAE3C,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,UAAU,CAAC,gBAAgB,CAAC,CAAC,KAAK,CAAC,YAAY,EAAE,GAAG,EAAE,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,gBAAgB,EAAE,CAAC;IACtH,OAAO,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;AACvC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sharadox/protection-web-library",
3
- "version": "0.1.0-development.0",
3
+ "version": "0.1.0-development.12",
4
4
  "description": "Protection for web forms and APIs: layered rate limits, proof-of-work challenges and spending caps.",
5
5
  "private": false,
6
6
  "license": "SEE LICENSE IN LICENCA.md",
@@ -29,22 +29,9 @@
29
29
  "engines": {
30
30
  "node": ">=26"
31
31
  },
32
- "packageManager": "pnpm@10.34.9",
33
32
  "publishConfig": {
34
33
  "access": "public"
35
34
  },
36
- "scripts": {
37
- "build": "library-build",
38
- "lint": "eslint --max-warnings=0 .",
39
- "format": "prettier --write .",
40
- "format:check": "prettier --check .",
41
- "type-check": "tsc --noEmit",
42
- "test:unit": "vitest run --coverage",
43
- "test:benchmark": "vitest bench --run --passWithNoTests",
44
- "documentation": "typedoc",
45
- "verify": "turbo run format:check lint type-check test:unit test:benchmark build",
46
- "prepare": "turborepo-configuration library && (husky || true)"
47
- },
48
35
  "lint-staged": {
49
36
  "*.{ts,js,mjs,cjs}": [
50
37
  "prettier --write",
@@ -53,9 +40,12 @@
53
40
  "*.{json,md,yml,yaml}": "prettier --write"
54
41
  },
55
42
  "dependencies": {
56
- "@sharadox/web-library": "^0.11.1"
43
+ "@sharadox/database-web-library": "0.1.0-development.9",
44
+ "@sharadox/web-library": "^0.11.1",
45
+ "kysely": "^0.28.19"
57
46
  },
58
47
  "devDependencies": {
48
+ "@electric-sql/pglite": "0.5.16",
59
49
  "@sharadox/es-lint-configuration-web-library": "^0.1.3",
60
50
  "@sharadox/library-build-web-library": "^0.2.1",
61
51
  "@sharadox/prettier-configuration-web-library": "^0.1.2",
@@ -86,5 +76,16 @@
86
76
  "denial-of-wallet",
87
77
  "security",
88
78
  "forms"
89
- ]
90
- }
79
+ ],
80
+ "scripts": {
81
+ "build": "library-build",
82
+ "lint": "eslint --max-warnings=0 .",
83
+ "format": "prettier --write .",
84
+ "format:check": "prettier --check .",
85
+ "type-check": "tsc --noEmit",
86
+ "test:unit": "vitest run --coverage",
87
+ "test:benchmark": "vitest bench --run --passWithNoTests",
88
+ "documentation": "typedoc",
89
+ "verify": "turbo run format:check lint type-check test:unit test:benchmark build"
90
+ }
91
+ }