@sharadox/protection-web-library 0.1.0-development.3 → 0.1.0-development.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -2
- package/distribution/protection-database/type.d.ts +24 -0
- package/distribution/protection-database/type.d.ts.map +1 -0
- package/distribution/protection-database/type.js +2 -0
- package/distribution/protection-database/type.js.map +1 -0
- package/distribution/protection-migration/index.d.ts +15 -0
- package/distribution/protection-migration/index.d.ts.map +1 -0
- package/distribution/protection-migration/index.js +44 -0
- package/distribution/protection-migration/index.js.map +1 -0
- package/distribution/rate-limit/index.d.ts +18 -0
- package/distribution/rate-limit/index.d.ts.map +1 -0
- package/distribution/rate-limit/index.js +68 -0
- package/distribution/rate-limit/index.js.map +1 -0
- package/distribution/rate-limit/type.d.ts +22 -0
- package/distribution/rate-limit/type.d.ts.map +1 -0
- package/distribution/rate-limit/type.js +2 -0
- package/distribution/rate-limit/type.js.map +1 -0
- package/distribution/rate-limit-prune/index.d.ts +14 -0
- package/distribution/rate-limit-prune/index.d.ts.map +1 -0
- package/distribution/rate-limit-prune/index.js +13 -0
- package/distribution/rate-limit-prune/index.js.map +1 -0
- package/distribution/solution-redemption/index.d.ts +19 -0
- package/distribution/solution-redemption/index.d.ts.map +1 -0
- package/distribution/solution-redemption/index.js +22 -0
- package/distribution/solution-redemption/index.js.map +1 -0
- package/distribution/spending-cap/index.d.ts +14 -0
- package/distribution/spending-cap/index.d.ts.map +1 -0
- package/distribution/spending-cap/index.js +38 -0
- package/distribution/spending-cap/index.js.map +1 -0
- package/distribution/spending-cap/type.d.ts +21 -0
- package/distribution/spending-cap/type.d.ts.map +1 -0
- package/distribution/spending-cap/type.js +2 -0
- package/distribution/spending-cap/type.js.map +1 -0
- package/distribution/used-challenge-prune/index.d.ts +13 -0
- package/distribution/used-challenge-prune/index.d.ts.map +1 -0
- package/distribution/used-challenge-prune/index.js +12 -0
- package/distribution/used-challenge-prune/index.js.map +1 -0
- package/package.json +5 -2
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
|
-
|
|
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,46 @@ 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`. Type a Kysely instance with `ProtectionDatabase`
|
|
90
|
+
(`protection-database/type`), or include it in the application's own schema type.
|
|
91
|
+
|
|
92
|
+
### `rate-limit`: `limitRate(database, layers, { secret, now? })` → `{ allowed, retryAfterSeconds, blockedBy }`
|
|
93
|
+
|
|
94
|
+
Every layer must have the tokens, or nothing is taken from any of them.
|
|
95
|
+
|
|
96
|
+
- One transaction, rows locked in a fixed order: concurrent requests never pass a capacity and never deadlock.
|
|
97
|
+
- `blockedBy` lists the keys that blocked, as given: count strikes with it for `adaptiveDifficulty`.
|
|
98
|
+
- The same key twice is refused.
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
const result = await limitRate(
|
|
102
|
+
database,
|
|
103
|
+
[
|
|
104
|
+
{ key: `contact:${email}`, rule: { capacity: 5, refillPerSecond: 1 / 600 } },
|
|
105
|
+
{ key: `address:${addressGroup(ip)}`, rule: { capacity: 20, refillPerSecond: 1 / 60 } },
|
|
106
|
+
{ key: "global:sign-in", rule: { capacity: 500, refillPerSecond: 1 } },
|
|
107
|
+
],
|
|
108
|
+
{ secret: process.env.RATE_LIMIT_SECRET! },
|
|
109
|
+
);
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### `solution-redemption`: `redeemSolution(database, solution, { secret, now? })`
|
|
113
|
+
|
|
114
|
+
`verifySolution` plus spending it: a valid solution counts once (its challenge id is kept until the challenge
|
|
115
|
+
expires), so a solved challenge can't be replayed. Reasons: `signature`, `expired`, `work`, `used`.
|
|
116
|
+
`pruneUsedChallenges(database, { now? })` (`used-challenge-prune`) forgets expired ones, from a daily job.
|
|
117
|
+
|
|
118
|
+
### `rate-limit-prune`: `pruneRateLimits(database, { before })` → deleted count
|
|
119
|
+
|
|
120
|
+
For a daily job. Pick `before` so that every bucket untouched since then would be full again.
|
|
121
|
+
|
|
122
|
+
### `spending-cap`: `spendFromCap(database, { name, limit, period: "day" | "month" }, { now?, cost = 1 })` → `{ allowed, used, remaining, resetsAt }`
|
|
123
|
+
|
|
124
|
+
A hard cap per UTC day or month on anything that costs money. Past the limit it refuses: pause and alert, never
|
|
125
|
+
spend. It is one atomic statement, and a refused spend uses nothing.
|
|
126
|
+
|
|
82
127
|
## License
|
|
83
128
|
|
|
84
129
|
Sharadox Open Source License 0.1.0 (see `LICENSE.md`).
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** One rate-limit bucket: its key (an HMAC, never the raw contact or address), tokens left and when last changed. */
|
|
2
|
+
export interface RateLimitBucketTable {
|
|
3
|
+
key: string;
|
|
4
|
+
tokens: number;
|
|
5
|
+
updated_at: Date;
|
|
6
|
+
}
|
|
7
|
+
/** How much of a spending cap one period has used. */
|
|
8
|
+
export interface SpendingCapUsageTable {
|
|
9
|
+
name: string;
|
|
10
|
+
period_start: Date;
|
|
11
|
+
used: number;
|
|
12
|
+
}
|
|
13
|
+
/** A proof-of-work challenge already answered, kept until it expires so its solution counts once. */
|
|
14
|
+
export interface UsedChallengeTable {
|
|
15
|
+
id: string;
|
|
16
|
+
expires_at: Date;
|
|
17
|
+
}
|
|
18
|
+
/** The tables `protectionMigrations` creates, for typing a Kysely instance. */
|
|
19
|
+
export interface ProtectionDatabase {
|
|
20
|
+
rate_limit_bucket: RateLimitBucketTable;
|
|
21
|
+
spending_cap_usage: SpendingCapUsageTable;
|
|
22
|
+
used_challenge: UsedChallengeTable;
|
|
23
|
+
}
|
|
24
|
+
//# 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,qHAAqH;AACrH,MAAM,WAAW,oBAAoB;IACnC,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,IAAI,CAAC;CAClB;AAED,sDAAsD;AACtD,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,IAAI,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;CACd;AAED,qGAAqG;AACrG,MAAM,WAAW,kBAAkB;IACjC,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 @@
|
|
|
1
|
+
{"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/protection-database/type.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,15 @@
|
|
|
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
|
+
/** The protection tables, forward only: rate-limit buckets, spending-cap usage and used challenges. */
|
|
6
|
+
export declare const protectionMigrations: Migration[];
|
|
7
|
+
/**
|
|
8
|
+
* Creates or updates the protection tables, tracked in their own migration table so they never clash with the
|
|
9
|
+
* application's migrations. Returns the names applied.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* await migrateProtection(database);
|
|
13
|
+
*/
|
|
14
|
+
export declare function migrateProtection<Schema>(database: Kysely<Schema>): Promise<string[]>;
|
|
15
|
+
//# 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,uGAAuG;AACvG,eAAO,MAAM,oBAAoB,EAAE,SAAS,EA4B3C,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,44 @@
|
|
|
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
|
+
/** The protection tables, forward only: rate-limit buckets, spending-cap usage and used challenges. */
|
|
5
|
+
export const protectionMigrations = [
|
|
6
|
+
{
|
|
7
|
+
name: "0001-rate-limit-and-spending-cap",
|
|
8
|
+
sql: `
|
|
9
|
+
create table rate_limit_bucket (
|
|
10
|
+
key text primary key,
|
|
11
|
+
tokens double precision not null check (tokens >= 0),
|
|
12
|
+
updated_at timestamptz not null
|
|
13
|
+
);
|
|
14
|
+
create index rate_limit_bucket_updated_at on rate_limit_bucket (updated_at);
|
|
15
|
+
create table spending_cap_usage (
|
|
16
|
+
name text not null,
|
|
17
|
+
period_start timestamptz not null,
|
|
18
|
+
used integer not null check (used >= 0),
|
|
19
|
+
primary key (name, period_start)
|
|
20
|
+
);
|
|
21
|
+
`,
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
name: "0002-used-challenge",
|
|
25
|
+
sql: `
|
|
26
|
+
create table used_challenge (
|
|
27
|
+
id text primary key check (length(id) <= 100),
|
|
28
|
+
expires_at timestamptz not null
|
|
29
|
+
);
|
|
30
|
+
create index used_challenge_expires_at on used_challenge (expires_at);
|
|
31
|
+
`,
|
|
32
|
+
},
|
|
33
|
+
];
|
|
34
|
+
/**
|
|
35
|
+
* Creates or updates the protection tables, tracked in their own migration table so they never clash with the
|
|
36
|
+
* application's migrations. Returns the names applied.
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* await migrateProtection(database);
|
|
40
|
+
*/
|
|
41
|
+
export function migrateProtection(database) {
|
|
42
|
+
return migrate(database, protectionMigrations, { table: PROTECTION_MIGRATION_TABLE });
|
|
43
|
+
}
|
|
44
|
+
//# 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,uGAAuG;AACvG,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;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/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gBACd,iBAAiB,EAAE,IAAI,CAAC,GAAG,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 @@
|
|
|
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,U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,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 @@
|
|
|
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.
|
|
3
|
+
"version": "0.1.0-development.9",
|
|
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",
|
|
@@ -40,9 +40,12 @@
|
|
|
40
40
|
"*.{json,md,yml,yaml}": "prettier --write"
|
|
41
41
|
},
|
|
42
42
|
"dependencies": {
|
|
43
|
-
"@sharadox/web-library": "
|
|
43
|
+
"@sharadox/database-web-library": "0.1.0-development.6",
|
|
44
|
+
"@sharadox/web-library": "^0.11.1",
|
|
45
|
+
"kysely": "^0.28.19"
|
|
44
46
|
},
|
|
45
47
|
"devDependencies": {
|
|
48
|
+
"@electric-sql/pglite": "0.5.16",
|
|
46
49
|
"@sharadox/es-lint-configuration-web-library": "^0.1.3",
|
|
47
50
|
"@sharadox/library-build-web-library": "^0.2.1",
|
|
48
51
|
"@sharadox/prettier-configuration-web-library": "^0.1.2",
|