@sharadox/protection-web-library 0.0.0-stage → 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 (81) hide show
  1. package/LICENCA.md +76 -0
  2. package/LICENSE.md +76 -0
  3. package/NOTICE.md +3 -0
  4. package/README.md +129 -2
  5. package/distribution/adaptive-difficulty/index.d.ts +11 -0
  6. package/distribution/adaptive-difficulty/index.d.ts.map +1 -0
  7. package/distribution/adaptive-difficulty/index.js +12 -0
  8. package/distribution/adaptive-difficulty/index.js.map +1 -0
  9. package/distribution/adaptive-difficulty/type.d.ts +6 -0
  10. package/distribution/adaptive-difficulty/type.d.ts.map +1 -0
  11. package/distribution/adaptive-difficulty/type.js +2 -0
  12. package/distribution/adaptive-difficulty/type.js.map +1 -0
  13. package/distribution/address-group/index.d.ts +11 -0
  14. package/distribution/address-group/index.d.ts.map +1 -0
  15. package/distribution/address-group/index.js +33 -0
  16. package/distribution/address-group/index.js.map +1 -0
  17. package/distribution/leading-zero-bits/index.d.ts +8 -0
  18. package/distribution/leading-zero-bits/index.d.ts.map +1 -0
  19. package/distribution/leading-zero-bits/index.js +18 -0
  20. package/distribution/leading-zero-bits/index.js.map +1 -0
  21. package/distribution/proof-of-work/index.d.ts +20 -0
  22. package/distribution/proof-of-work/index.d.ts.map +1 -0
  23. package/distribution/proof-of-work/index.js +49 -0
  24. package/distribution/proof-of-work/index.js.map +1 -0
  25. package/distribution/proof-of-work/type.d.ts +37 -0
  26. package/distribution/proof-of-work/type.d.ts.map +1 -0
  27. package/distribution/proof-of-work/type.js +2 -0
  28. package/distribution/proof-of-work/type.js.map +1 -0
  29. package/distribution/proof-of-work-solver/index.d.ts +12 -0
  30. package/distribution/proof-of-work-solver/index.d.ts.map +1 -0
  31. package/distribution/proof-of-work-solver/index.js +23 -0
  32. package/distribution/proof-of-work-solver/index.js.map +1 -0
  33. package/distribution/protection-database/type.d.ts +30 -0
  34. package/distribution/protection-database/type.d.ts.map +1 -0
  35. package/distribution/protection-database/type.js +2 -0
  36. package/distribution/protection-database/type.js.map +1 -0
  37. package/distribution/protection-migration/index.d.ts +18 -0
  38. package/distribution/protection-migration/index.d.ts.map +1 -0
  39. package/distribution/protection-migration/index.js +66 -0
  40. package/distribution/protection-migration/index.js.map +1 -0
  41. package/distribution/rate-limit/index.d.ts +18 -0
  42. package/distribution/rate-limit/index.d.ts.map +1 -0
  43. package/distribution/rate-limit/index.js +68 -0
  44. package/distribution/rate-limit/index.js.map +1 -0
  45. package/distribution/rate-limit/type.d.ts +22 -0
  46. package/distribution/rate-limit/type.d.ts.map +1 -0
  47. package/distribution/rate-limit/type.js +2 -0
  48. package/distribution/rate-limit/type.js.map +1 -0
  49. package/distribution/rate-limit-prune/index.d.ts +14 -0
  50. package/distribution/rate-limit-prune/index.d.ts.map +1 -0
  51. package/distribution/rate-limit-prune/index.js +13 -0
  52. package/distribution/rate-limit-prune/index.js.map +1 -0
  53. package/distribution/sha-256/index.d.ts +10 -0
  54. package/distribution/sha-256/index.d.ts.map +1 -0
  55. package/distribution/sha-256/index.js +71 -0
  56. package/distribution/sha-256/index.js.map +1 -0
  57. package/distribution/solution-redemption/index.d.ts +19 -0
  58. package/distribution/solution-redemption/index.d.ts.map +1 -0
  59. package/distribution/solution-redemption/index.js +22 -0
  60. package/distribution/solution-redemption/index.js.map +1 -0
  61. package/distribution/spending-cap/index.d.ts +14 -0
  62. package/distribution/spending-cap/index.d.ts.map +1 -0
  63. package/distribution/spending-cap/index.js +38 -0
  64. package/distribution/spending-cap/index.js.map +1 -0
  65. package/distribution/spending-cap/type.d.ts +21 -0
  66. package/distribution/spending-cap/type.d.ts.map +1 -0
  67. package/distribution/spending-cap/type.js +2 -0
  68. package/distribution/spending-cap/type.js.map +1 -0
  69. package/distribution/token-bucket/index.d.ts +12 -0
  70. package/distribution/token-bucket/index.d.ts.map +1 -0
  71. package/distribution/token-bucket/index.js +23 -0
  72. package/distribution/token-bucket/index.js.map +1 -0
  73. package/distribution/token-bucket/type.d.ts +17 -0
  74. package/distribution/token-bucket/type.d.ts.map +1 -0
  75. package/distribution/token-bucket/type.js +2 -0
  76. package/distribution/token-bucket/type.js.map +1 -0
  77. package/distribution/used-challenge-prune/index.d.ts +13 -0
  78. package/distribution/used-challenge-prune/index.d.ts.map +1 -0
  79. package/distribution/used-challenge-prune/index.js +12 -0
  80. package/distribution/used-challenge-prune/index.js.map +1 -0
  81. package/package.json +88 -3
@@ -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,I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AAG,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;gBACjF,SAAS,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;aACrG,CAAC;QACJ,CAAC;QACD,KAAK,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,KAAK,EAAE,CAAC;YACpC,MAAM,WAAW;iBACd,WAAW,CAAC,mBAAmB,CAAC;iBAChC,GAAG,CAAC,EAAE,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,10 @@
1
+ /**
2
+ * SHA-256 (FIPS 180-4), synchronous and dependency-free: for the proof-of-work solver, where tens of thousands of
3
+ * small hashes would each wait on an asynchronous `crypto.subtle.digest`. Not for secrets or large data: use
4
+ * `node:crypto` or Web Crypto there.
5
+ *
6
+ * @example
7
+ * sha256(new TextEncoder().encode("abc")); // ba7816bf…f20015ad as bytes
8
+ */
9
+ export declare function sha256(data: Uint8Array): Uint8Array;
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/sha-256/index.ts"],"names":[],"mappings":"AAiBA;;;;;;;GAOG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,UAAU,GAAG,UAAU,CA+CnD"}
@@ -0,0 +1,71 @@
1
+ /** The first 32 bits of the fractional parts of the cube roots of the first 64 primes (FIPS 180-4, 4.2.2). */
2
+ const K = new Uint32Array([
3
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98,
4
+ 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
5
+ 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8,
6
+ 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
7
+ 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
8
+ 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
9
+ 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
10
+ 0xc67178f2,
11
+ ]);
12
+ /** The first 32 bits of the fractional parts of the square roots of the first 8 primes (FIPS 180-4, 5.3.3). */
13
+ const INITIAL = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
14
+ const rotate = (value, bits) => (value >>> bits) | (value << (32 - bits));
15
+ /**
16
+ * SHA-256 (FIPS 180-4), synchronous and dependency-free: for the proof-of-work solver, where tens of thousands of
17
+ * small hashes would each wait on an asynchronous `crypto.subtle.digest`. Not for secrets or large data: use
18
+ * `node:crypto` or Web Crypto there.
19
+ *
20
+ * @example
21
+ * sha256(new TextEncoder().encode("abc")); // ba7816bf…f20015ad as bytes
22
+ */
23
+ export function sha256(data) {
24
+ const blocks = Math.ceil((data.length + 9) / 64);
25
+ const padded = new Uint8Array(blocks * 64);
26
+ padded.set(data);
27
+ padded[data.length] = 0x80;
28
+ const view = new DataView(padded.buffer);
29
+ const bits = data.length * 8;
30
+ view.setUint32(padded.length - 8, Math.floor(bits / 0x1_0000_0000));
31
+ view.setUint32(padded.length - 4, bits >>> 0);
32
+ const hash = [...INITIAL];
33
+ const words = new Uint32Array(64);
34
+ for (let offset = 0; offset < padded.length; offset += 64) {
35
+ for (let t = 0; t < 16; t++)
36
+ words[t] = view.getUint32(offset + t * 4);
37
+ for (let t = 16; t < 64; t++) {
38
+ const w15 = words[t - 15];
39
+ const w2 = words[t - 2];
40
+ const s0 = rotate(w15, 7) ^ rotate(w15, 18) ^ (w15 >>> 3);
41
+ const s1 = rotate(w2, 17) ^ rotate(w2, 19) ^ (w2 >>> 10);
42
+ words[t] = (words[t - 16] + s0 + words[t - 7] + s1) | 0;
43
+ }
44
+ let [a, b, c, d, e, f, g, h] = hash;
45
+ for (let t = 0; t < 64; t++) {
46
+ const t1 = (h + (rotate(e, 6) ^ rotate(e, 11) ^ rotate(e, 25)) + ((e & f) ^ (~e & g)) + K[t] + words[t]) | 0;
47
+ const t2 = ((rotate(a, 2) ^ rotate(a, 13) ^ rotate(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) | 0;
48
+ h = g;
49
+ g = f;
50
+ f = e;
51
+ e = (d + t1) | 0;
52
+ d = c;
53
+ c = b;
54
+ b = a;
55
+ a = (t1 + t2) | 0;
56
+ }
57
+ hash[0] = (hash[0] + a) | 0;
58
+ hash[1] = (hash[1] + b) | 0;
59
+ hash[2] = (hash[2] + c) | 0;
60
+ hash[3] = (hash[3] + d) | 0;
61
+ hash[4] = (hash[4] + e) | 0;
62
+ hash[5] = (hash[5] + f) | 0;
63
+ hash[6] = (hash[6] + g) | 0;
64
+ hash[7] = (hash[7] + h) | 0;
65
+ }
66
+ const digest = new Uint8Array(32);
67
+ const out = new DataView(digest.buffer);
68
+ hash.forEach((word, index) => out.setUint32(index * 4, word >>> 0));
69
+ return digest;
70
+ }
71
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/sha-256/index.ts"],"names":[],"mappings":"AAAA,8GAA8G;AAC9G,MAAM,CAAC,GAAG,IAAI,WAAW,CAAC;IACxB,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;IAC1G,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;IAC1G,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;IAC1G,UAAU,EAAE,U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,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,KAA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AAE,IAAI,EAAE,IAAI,EAAE,CAAC;aACvD,UAAU,CAAC,CAAC,QAAQ,EAAE,EAAE,CACvB,QAAQ,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC,CAAC,WAAW,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,CAAC,CAClG;aACA,SAAS,CAAC,MAAM,CAAC;aACjB,gBAAgB,EAAE,CAAC;QACtB,IAAI,KAAK;YAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,SAAS,EAAE,KAAK,GAAG,KAAK,CAAC,IAAI,EAAE,QAAQ,EAAE,CAAC;IACjG,CAAC;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,12 @@
1
+ import type { TokenBucket, TokenBucketResult, TokenBucketRule } from "@sharadox/protection-web-library/token-bucket/type";
2
+ /**
3
+ * One step of a token bucket, the rate limit every protection here is made of: a new key starts full (`capacity`),
4
+ * each action costs tokens (`cost`, 1 by default), and tokens come back at `refillPerSecond`, never above the
5
+ * capacity. Pure: store the returned bucket (per contact, per address group, per account…) wherever the caller
6
+ * keeps state. A clock that went backwards refills nothing.
7
+ *
8
+ * @example
9
+ * const { allowed, bucket, retryAfterSeconds } = takeToken(stored, { capacity: 5, refillPerSecond: 1 / 60 }, Date.now());
10
+ */
11
+ export declare function takeToken(bucket: TokenBucket | undefined, { capacity, refillPerSecond }: TokenBucketRule, now: number, cost?: number): TokenBucketResult;
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/token-bucket/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,iBAAiB,EACjB,eAAe,EAChB,MAAM,oDAAoD,CAAC;AAE5D;;;;;;;;GAQG;AACH,wBAAgB,SAAS,CACvB,MAAM,EAAE,WAAW,GAAG,SAAS,EAC/B,EAAE,QAAQ,EAAE,eAAe,EAAE,EAAE,eAAe,EAC9C,GAAG,EAAE,MAAM,EACX,IAAI,SAAI,GACP,iBAAiB,CAWnB"}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * One step of a token bucket, the rate limit every protection here is made of: a new key starts full (`capacity`),
3
+ * each action costs tokens (`cost`, 1 by default), and tokens come back at `refillPerSecond`, never above the
4
+ * capacity. Pure: store the returned bucket (per contact, per address group, per account…) wherever the caller
5
+ * keeps state. A clock that went backwards refills nothing.
6
+ *
7
+ * @example
8
+ * const { allowed, bucket, retryAfterSeconds } = takeToken(stored, { capacity: 5, refillPerSecond: 1 / 60 }, Date.now());
9
+ */
10
+ export function takeToken(bucket, { capacity, refillPerSecond }, now, cost = 1) {
11
+ const start = bucket ?? { tokens: capacity, updatedAt: now };
12
+ const elapsed = Math.max(0, now - start.updatedAt) / 1000;
13
+ const tokens = Math.min(capacity, start.tokens + elapsed * refillPerSecond);
14
+ const updatedAt = Math.max(now, start.updatedAt);
15
+ if (tokens >= cost)
16
+ return { allowed: true, bucket: { tokens: tokens - cost, updatedAt }, retryAfterSeconds: 0 };
17
+ return {
18
+ allowed: false,
19
+ bucket: bucket ?? start,
20
+ retryAfterSeconds: Math.ceil((cost - tokens) / refillPerSecond),
21
+ };
22
+ }
23
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/token-bucket/index.ts"],"names":[],"mappings":"AAMA;;;;;;;;GAQG;AACH,MAAM,UAAU,SAAS,CACvB,MAA+B,EAC/B,EAAE,QAAQ,EAAE,eAAe,EAAmB,EAC9C,GAAW,EACX,IAAI,GAAG,CAAC;IAER,MAAM,KAAK,GAAG,MAAM,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC;IAC7D,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,GAAG,KAAK,CAAC,SAAS,CAAC,GAAG,IAAI,CAAC;IAC1D,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,KAAK,CAAC,MAAM,GAAG,OAAO,GAAG,eAAe,CAAC,CAAC;IAC5E,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;IACjD,IAAI,MAAM,IAAI,IAAI;QAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,EAAE,SAAS,EAAE,EAAE,iBAAiB,EAAE,CAAC,EAAE,CAAC;IACjH,OAAO;QACL,OAAO,EAAE,KAAK;QACd,MAAM,EAAE,MAAM,IAAI,KAAK;QACvB,iBAAiB,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,GAAG,MAAM,CAAC,GAAG,eAAe,CAAC;KAChE,CAAC;AACJ,CAAC"}