@sharadox/protection-web-library 0.0.0-stage → 0.1.0-development.3

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 (45) hide show
  1. package/LICENCA.md +76 -0
  2. package/LICENSE.md +76 -0
  3. package/NOTICE.md +3 -0
  4. package/README.md +83 -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 +48 -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/sha-256/index.d.ts +10 -0
  34. package/distribution/sha-256/index.d.ts.map +1 -0
  35. package/distribution/sha-256/index.js +71 -0
  36. package/distribution/sha-256/index.js.map +1 -0
  37. package/distribution/token-bucket/index.d.ts +12 -0
  38. package/distribution/token-bucket/index.d.ts.map +1 -0
  39. package/distribution/token-bucket/index.js +23 -0
  40. package/distribution/token-bucket/index.js.map +1 -0
  41. package/distribution/token-bucket/type.d.ts +17 -0
  42. package/distribution/token-bucket/type.d.ts.map +1 -0
  43. package/distribution/token-bucket/type.js +2 -0
  44. package/distribution/token-bucket/type.js.map +1 -0
  45. package/package.json +85 -3
package/LICENCA.md ADDED
@@ -0,0 +1,76 @@
1
+ # Licença Sharadox de Código Aberto
2
+
3
+ Versão 0.1.0
4
+
5
+ O texto em língua portuguesa é o único texto original e vinculativo desta licença. A tradução para inglês (`LICENSE.md`) é meramente informativa; em caso de divergência prevalece o texto em português.
6
+
7
+ ## 1. Definições
8
+
9
+ Para efeitos desta licença:
10
+
11
+ 1. **«Obra»** — o programa de computador, a sua documentação e quaisquer outros conteúdos disponibilizados pelo Licenciante ao abrigo desta licença, em código-fonte ou em qualquer outra forma.
12
+ 2. **«Licenciante»** — o titular dos direitos de autor identificado no aviso de direitos de autor que acompanha a Obra.
13
+ 3. **«Licenciado»** — qualquer pessoa, singular ou coletiva, que exerça os direitos concedidos por esta licença.
14
+ 4. **«Obra Derivada»** — qualquer obra baseada na Obra ou que a incorpore, total ou parcialmente, com ou sem modificações, incluindo traduções, adaptações e programas que a integrem.
15
+ 5. **«Aviso»** — o aviso de direitos de autor do Licenciante e a indicação de que a Obra está licenciada ao abrigo desta licença, incluindo a respetiva versão.
16
+
17
+ ## 2. Concessão de direitos
18
+
19
+ 1. Nos termos desta licença, o Licenciante concede ao Licenciado uma licença mundial, gratuita, não exclusiva e por todo o prazo de proteção dos direitos de autor para:
20
+ 1. utilizar a Obra para qualquer finalidade, incluindo finalidades comerciais;
21
+ 2. reproduzir a Obra, total ou parcialmente, por qualquer meio e sob qualquer forma;
22
+ 3. modificar, traduzir, adaptar e transformar a Obra e criar Obras Derivadas;
23
+ 4. distribuir, publicar, comunicar ao público, colocar à disposição, vender e sublicenciar a Obra e as Obras Derivadas.
24
+ 2. Na medida em que o Licenciante seja titular de patentes necessariamente infringidas pela Obra tal como por si disponibilizada, concede igualmente ao Licenciado, nos mesmos termos, uma licença para utilizar essas patentes no exercício dos direitos previstos no número anterior.
25
+ 3. Esta licença não transmite a titularidade de quaisquer direitos, que permanecem do Licenciante.
26
+
27
+ ## 3. Condições
28
+
29
+ O exercício dos direitos concedidos fica sujeito às seguintes condições:
30
+
31
+ 1. Todas as cópias da Obra, ou de partes substanciais da mesma, e todas as Obras Derivadas distribuídas devem incluir o Aviso e uma cópia desta licença ou uma ligação estável para o seu texto.
32
+ 2. Quem distribuir uma versão modificada da Obra deve indicar de forma visível que a mesma foi modificada, não podendo apresentá-la como versão original do Licenciante.
33
+ 3. O Licenciado pode licenciar as suas próprias modificações ao abrigo de outros termos, desde que a parte da Obra que delas faça parte continue sujeita às condições desta licença.
34
+
35
+ ## 4. Nomes e marcas
36
+
37
+ Esta licença não concede qualquer direito sobre o nome, as marcas, os logótipos ou outros sinais distintivos do Licenciante, incluindo a designação «Sharadox», salvo na medida estritamente necessária para cumprir o dever de incluir o Aviso. É proibido utilizá-los para promover ou sugerir o apoio do Licenciante a Obras Derivadas ou a quaisquer produtos ou serviços sem autorização prévia e escrita.
38
+
39
+ ## 5. Exclusão de garantias
40
+
41
+ A Obra é disponibilizada «tal como está» e «conforme disponível», sem qualquer garantia, expressa ou tácita, incluindo, designadamente, garantias de comerciabilidade, de adequação a um fim específico, de ausência de erros ou de não violação de direitos de terceiros, na medida máxima permitida pela lei aplicável.
42
+
43
+ ## 6. Limitação de responsabilidade
44
+
45
+ 1. Na medida máxima permitida pela lei aplicável, o Licenciante não é responsável por quaisquer danos, diretos ou indiretos, incluindo lucros cessantes, perda de dados ou interrupção de atividade, resultantes da utilização ou da impossibilidade de utilização da Obra, ainda que tenha sido avisado da possibilidade da sua ocorrência.
46
+ 2. Nada nesta licença exclui ou limita a responsabilidade do Licenciante nos casos em que tal exclusão ou limitação não seja permitida por lei, designadamente por atos praticados com dolo ou culpa grave, nos termos do artigo 809.º e do n.º 2 do artigo 800.º do Código Civil, nem afeta os direitos que a lei imperativamente reconheça aos consumidores.
47
+
48
+ ## 7. Cessação
49
+
50
+ 1. Os direitos concedidos por esta licença cessam automaticamente se o Licenciado violar qualquer das suas condições.
51
+ 2. Os direitos são repostos se a violação for sanada no prazo de 30 dias a contar do momento em que o Licenciado dela tome conhecimento, salvo se o Licenciante tiver entretanto comunicado por escrito a sua oposição.
52
+ 3. A cessação não afeta as licenças validamente concedidas pelo Licenciado a terceiros que cumpram esta licença.
53
+
54
+ ## 8. Lei aplicável e foro
55
+
56
+ 1. Esta licença rege-se pela lei portuguesa, designadamente pelo Código do Direito de Autor e dos Direitos Conexos, aprovado pelo Decreto-Lei n.º 63/85, de 14 de março, e pelo Decreto-Lei n.º 252/94, de 20 de outubro, relativo à proteção jurídica dos programas de computador.
57
+ 2. Para a resolução de quaisquer litígios emergentes desta licença é competente o Tribunal Judicial da Comarca de Faro, sem prejuízo das normas imperativas de competência aplicáveis, nomeadamente as que protegem os consumidores.
58
+
59
+ ## 9. Versões da licença
60
+
61
+ O Licenciante pode publicar novas versões desta licença, identificadas por um número de versão. A Obra fica sujeita à versão indicada no Aviso. O Licenciado pode, se o Aviso o permitir, optar por qualquer versão posterior.
62
+
63
+ ## 10. Disposições finais
64
+
65
+ 1. Se alguma disposição desta licença for considerada inválida ou ineficaz, as restantes mantêm-se em vigor, devendo a disposição afetada ser interpretada de forma a aproximar-se, tanto quanto possível, da intenção original.
66
+ 2. A não exigência, em qualquer momento, do cumprimento de uma disposição desta licença não constitui renúncia ao direito de o exigir posteriormente.
67
+
68
+ ## Como aplicar esta licença
69
+
70
+ Inclua na Obra um ficheiro `LICENCA.md` com este texto, a tradução `LICENSE.md` e o seguinte aviso, preenchendo o ano e o titular:
71
+
72
+ ```
73
+ Direitos de autor © <ano> <titular>.
74
+ Licenciado ao abrigo da Licença Sharadox de Código Aberto, versão 0.1.0.
75
+ https://github.com/Sharadox/sharadox-open-source-license
76
+ ```
package/LICENSE.md ADDED
@@ -0,0 +1,76 @@
1
+ # Sharadox Open Source Licence
2
+
3
+ Version 0.1.0
4
+
5
+ This is an informative English translation. The Portuguese text (`LICENCA.md`) is the only original and binding text of this licence; if the two differ, the Portuguese text prevails.
6
+
7
+ ## 1. Definitions
8
+
9
+ For the purposes of this licence:
10
+
11
+ 1. **"Work"** — the computer program, its documentation and any other content made available by the Licensor under this licence, in source code or in any other form.
12
+ 2. **"Licensor"** — the copyright holder identified in the copyright notice that accompanies the Work.
13
+ 3. **"Licensee"** — any natural or legal person exercising the rights granted by this licence.
14
+ 4. **"Derivative Work"** — any work based on or incorporating the Work, in whole or in part, with or without modifications, including translations, adaptations and programs that integrate it.
15
+ 5. **"Notice"** — the Licensor's copyright notice and the statement that the Work is licensed under this licence, including its version.
16
+
17
+ ## 2. Grant of rights
18
+
19
+ 1. Under this licence, the Licensor grants the Licensee a worldwide, royalty-free, non-exclusive licence, for the whole term of copyright protection, to:
20
+ 1. use the Work for any purpose, including commercial purposes;
21
+ 2. reproduce the Work, in whole or in part, by any means and in any form;
22
+ 3. modify, translate, adapt and transform the Work and create Derivative Works;
23
+ 4. distribute, publish, communicate to the public, make available, sell and sublicense the Work and Derivative Works.
24
+ 2. To the extent the Licensor holds patents necessarily infringed by the Work as made available by it, the Licensor also grants the Licensee, on the same terms, a licence to use those patents in exercising the rights in the previous paragraph.
25
+ 3. This licence does not transfer ownership of any rights, which remain with the Licensor.
26
+
27
+ ## 3. Conditions
28
+
29
+ The exercise of the rights granted is subject to the following conditions:
30
+
31
+ 1. Every copy of the Work, or of substantial parts of it, and every distributed Derivative Work must include the Notice and a copy of this licence or a stable link to its text.
32
+ 2. Anyone distributing a modified version of the Work must state visibly that it has been modified and may not present it as the Licensor's original version.
33
+ 3. The Licensee may license their own modifications under other terms, provided the part of the Work included in them remains subject to the conditions of this licence.
34
+
35
+ ## 4. Names and trademarks
36
+
37
+ This licence grants no rights to the Licensor's name, trademarks, logos or other distinctive signs, including the name "Sharadox", except as strictly necessary to comply with the duty to include the Notice. Using them to promote or suggest the Licensor's endorsement of Derivative Works or of any products or services without prior written permission is prohibited.
38
+
39
+ ## 5. Disclaimer of warranties
40
+
41
+ The Work is provided "as is" and "as available", without any warranty, express or implied, including in particular warranties of merchantability, fitness for a particular purpose, absence of errors or non-infringement of third-party rights, to the maximum extent permitted by applicable law.
42
+
43
+ ## 6. Limitation of liability
44
+
45
+ 1. To the maximum extent permitted by applicable law, the Licensor is not liable for any damages, direct or indirect, including loss of profits, loss of data or business interruption, arising from the use of or inability to use the Work, even if advised of the possibility of such damages.
46
+ 2. Nothing in this licence excludes or limits the Licensor's liability where such exclusion or limitation is not permitted by law, in particular for acts committed with intent or gross negligence, under article 809 and article 800(2) of the Portuguese Civil Code, nor does it affect rights that the law mandatorily grants to consumers.
47
+
48
+ ## 7. Termination
49
+
50
+ 1. The rights granted by this licence terminate automatically if the Licensee breaches any of its conditions.
51
+ 2. The rights are reinstated if the breach is remedied within 30 days of the Licensee becoming aware of it, unless the Licensor has meanwhile objected in writing.
52
+ 3. Termination does not affect licences validly granted by the Licensee to third parties who comply with this licence.
53
+
54
+ ## 8. Governing law and jurisdiction
55
+
56
+ 1. This licence is governed by Portuguese law, in particular the Code of Copyright and Related Rights, approved by Decree-Law no. 63/85 of 14 March, and Decree-Law no. 252/94 of 20 October on the legal protection of computer programs.
57
+ 2. The Judicial Court of the District of Faro has jurisdiction over any dispute arising from this licence, without prejudice to applicable mandatory rules of jurisdiction, in particular those protecting consumers.
58
+
59
+ ## 9. Licence versions
60
+
61
+ The Licensor may publish new versions of this licence, identified by a version number. The Work is subject to the version stated in the Notice. If the Notice allows it, the Licensee may choose any later version.
62
+
63
+ ## 10. Final provisions
64
+
65
+ 1. If any provision of this licence is held invalid or unenforceable, the remaining provisions stay in force, and the affected provision shall be interpreted as closely as possible to its original intent.
66
+ 2. Failure to enforce any provision of this licence at any time does not waive the right to enforce it later.
67
+
68
+ ## How to apply this licence
69
+
70
+ Include in the Work a `LICENCA.md` file with the Portuguese text, this translation as `LICENSE.md`, and the following notice, filling in the year and holder:
71
+
72
+ ```
73
+ Direitos de autor © <ano> <titular>.
74
+ Licenciado ao abrigo da Licença Sharadox de Código Aberto, versão 0.1.0.
75
+ https://github.com/Sharadox/sharadox-open-source-license
76
+ ```
package/NOTICE.md ADDED
@@ -0,0 +1,3 @@
1
+ Direitos de autor © 2026 Micael Pires (Sharadox).
2
+ Licenciado ao abrigo da Licença Sharadox de Código Aberto, versão 0.1.0.
3
+ https://github.com/Sharadox/sharadox-open-source-license
package/README.md CHANGED
@@ -1,3 +1,84 @@
1
- # Temporary Holding Version
1
+ # @sharadox/protection-web-library
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Protection for web forms and APIs against repeated tries, bots and attacks on the bill. It provides:
4
+
5
+ - token-bucket rate limits;
6
+ - address groups that treat a whole IPv6 /64 as one visitor;
7
+ - an invisible proof-of-work challenge (no third-party captcha, no puzzle);
8
+ - difficulty that rises with each strike.
9
+
10
+ Everything is pure or stateless: the caller decides where buckets and used challenge ids are stored.
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ pnpm add @sharadox/protection-web-library
16
+ ```
17
+
18
+ ## Configuration
19
+
20
+ | Variable | Meaning |
21
+ | ---------------------- | ------------------------------------------------------------------------------------------------------------------ |
22
+ | `PROOF_OF_WORK_SECRET` | At least 32 random characters, server only. It signs challenges (suggested name: the library only takes `secret`). |
23
+
24
+ ## API
25
+
26
+ Each export has its own entry point (`@sharadox/protection-web-library/<name>`).
27
+
28
+ ### `token-bucket`: `takeToken(bucket | undefined, { capacity, refillPerSecond }, now, cost = 1)`
29
+
30
+ Returns `{ allowed, bucket, retryAfterSeconds }`.
31
+
32
+ - A new key starts full.
33
+ - Each action costs `cost` tokens.
34
+ - Tokens come back at `refillPerSecond`, never above `capacity`.
35
+ - A clock that goes backwards refills nothing.
36
+
37
+ ```ts
38
+ const rule = { capacity: 5, refillPerSecond: 1 / 60 }; // 5 at once, then one a minute
39
+ const { allowed, bucket, retryAfterSeconds } = takeToken(stored, rule, Date.now());
40
+ ```
41
+
42
+ Layer several buckets per action: per contact, per account, per `addressGroup`, and one global bucket.
43
+
44
+ ### `address-group`: `addressGroup(address)` → group
45
+
46
+ - An IPv4 address is its own group.
47
+ - An IPv6 address counts as its `/64` (`2001:db8:1:2::/64`).
48
+ - `::ffff:203.0.113.7` counts as IPv4.
49
+ - Anything else is `"unknown"`.
50
+
51
+ Use it with `clientAddress` from `@sharadox/web-library/client-address`.
52
+
53
+ ### `proof-of-work`: `createChallenge({ secret, difficulty, now?, lifetimeSeconds = 300 })`, `verifySolution({ challenge, nonce }, { secret, now? })`
54
+
55
+ A challenge asks for a nonce such that SHA-256(`salt:nonce`) starts with `difficulty` zero bits.
56
+
57
+ - **Signed:** the server keeps nothing until a solution comes back.
58
+ - **Verification** returns `{ valid: true, id }` or `{ valid: false, reason: "signature" | "expired" | "work" }`. The
59
+ signature is compared in constant time, so the difficulty can't be lowered.
60
+ - **One use per challenge:** store `id` until `expiresAt` and refuse it after that.
61
+
62
+ ### `proof-of-work-solver`: `solveChallenge({ salt, difficulty })` → nonce
63
+
64
+ Runs in the browser and pauses every 2,000 attempts so the page stays responsive. A default 14-bit challenge takes a
65
+ small fraction of a second.
66
+
67
+ ```ts
68
+ const challenge = await (await fetch("/api/challenge")).json();
69
+ const nonce = await solveChallenge(challenge);
70
+ await fetch("/api/code", { method: "POST", body: JSON.stringify({ email, proof: { challenge, nonce } }) });
71
+ ```
72
+
73
+ ### `adaptive-difficulty`: `adaptiveDifficulty(strikes, { base = 14, maximum = 22 })`
74
+
75
+ Adds one bit per strike, which doubles the work, from `base` up to `maximum`.
76
+
77
+ ### `leading-zero-bits`: `leadingZeroBits(bytes)`, `sha-256`: `sha256(bytes)`
78
+
79
+ The building blocks of the solver. `sha256` is a synchronous FIPS 180-4 SHA-256, made for many small hashes. It is
80
+ not for secrets.
81
+
82
+ ## License
83
+
84
+ Sharadox Open Source License 0.1.0 (see `LICENSE.md`).
@@ -0,0 +1,11 @@
1
+ import type { AdaptiveDifficultyOptions } from "@sharadox/protection-web-library/adaptive-difficulty/type";
2
+ /**
3
+ * The proof-of-work difficulty for a source with `strikes` (recent refusals, failures or limits hit): one more bit,
4
+ * twice the work, per strike, between `base` (14 bits: a moment on a phone) and `maximum` (22 bits: several seconds,
5
+ * costly by the thousand for a bot).
6
+ *
7
+ * @example
8
+ * createChallenge({ secret, difficulty: adaptiveDifficulty(strikes) });
9
+ */
10
+ export declare function adaptiveDifficulty(strikes: number, { base, maximum }?: AdaptiveDifficultyOptions): number;
11
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/adaptive-difficulty/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,2DAA2D,CAAC;AAE3G;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,MAAM,EACf,EAAE,IAAS,EAAE,OAAY,EAAE,GAAE,yBAA8B,GAC1D,MAAM,CAER"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The proof-of-work difficulty for a source with `strikes` (recent refusals, failures or limits hit): one more bit,
3
+ * twice the work, per strike, between `base` (14 bits: a moment on a phone) and `maximum` (22 bits: several seconds,
4
+ * costly by the thousand for a bot).
5
+ *
6
+ * @example
7
+ * createChallenge({ secret, difficulty: adaptiveDifficulty(strikes) });
8
+ */
9
+ export function adaptiveDifficulty(strikes, { base = 14, maximum = 22 } = {}) {
10
+ return Math.min(maximum, base + Math.max(0, strikes));
11
+ }
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/adaptive-difficulty/index.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AACH,MAAM,UAAU,kBAAkB,CAChC,OAAe,EACf,EAAE,IAAI,GAAG,EAAE,EAAE,OAAO,GAAG,EAAE,KAAgC,EAAE;IAE3D,OAAO,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;AACxD,CAAC"}
@@ -0,0 +1,6 @@
1
+ /** The difficulty for a visitor with no strikes (`base`, 14 bits by default) and the most ever asked (22). */
2
+ export interface AdaptiveDifficultyOptions {
3
+ base?: number;
4
+ maximum?: number;
5
+ }
6
+ //# sourceMappingURL=type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/adaptive-difficulty/type.ts"],"names":[],"mappings":"AAAA,8GAA8G;AAC9G,MAAM,WAAW,yBAAyB;IACxC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/adaptive-difficulty/type.ts"],"names":[],"mappings":""}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The group of addresses one visitor most likely controls, for rate limits: an IPv4 address alone, and an IPv6
3
+ * address's whole /64 (a home or a server usually gets a /64, so counting single IPv6 addresses would let one
4
+ * visitor change address at will). IPv4 written as IPv6 (`::ffff:203.0.113.7`) counts as IPv4; anything else is
5
+ * "unknown", one shared group.
6
+ *
7
+ * @example
8
+ * addressGroup(clientAddress(await headers())); // "2001:db8:1:2::/64"
9
+ */
10
+ export declare function addressGroup(address: string): string;
11
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/address-group/index.ts"],"names":[],"mappings":"AAWA;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CASpD"}
@@ -0,0 +1,33 @@
1
+ import { isIPv4, isIPv6 } from "node:net";
2
+ /** The eight 16-bit groups of an IPv6 address, `::` expanded. */
3
+ function groups(address) {
4
+ const [head, tail] = address.toLowerCase().split("::");
5
+ const left = head ? head.split(":") : [];
6
+ if (tail === undefined)
7
+ return left;
8
+ const right = tail ? tail.split(":") : [];
9
+ return [...left, ...Array(8 - left.length - right.length).fill("0"), ...right];
10
+ }
11
+ /**
12
+ * The group of addresses one visitor most likely controls, for rate limits: an IPv4 address alone, and an IPv6
13
+ * address's whole /64 (a home or a server usually gets a /64, so counting single IPv6 addresses would let one
14
+ * visitor change address at will). IPv4 written as IPv6 (`::ffff:203.0.113.7`) counts as IPv4; anything else is
15
+ * "unknown", one shared group.
16
+ *
17
+ * @example
18
+ * addressGroup(clientAddress(await headers())); // "2001:db8:1:2::/64"
19
+ */
20
+ export function addressGroup(address) {
21
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address)?.[1];
22
+ if (mapped && isIPv4(mapped))
23
+ return mapped;
24
+ if (isIPv4(address))
25
+ return address;
26
+ if (!isIPv6(address))
27
+ return "unknown";
28
+ return `${groups(address)
29
+ .slice(0, 4)
30
+ .map((group) => group.replace(/^0+(?=.)/, ""))
31
+ .join(":")}::/64`;
32
+ }
33
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/address-group/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAE1C,iEAAiE;AACjE,SAAS,MAAM,CAAC,OAAe;IAC7B,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,IAAI,CAAiC,CAAC;IACvF,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACzC,IAAI,IAAI,KAAK,SAAS;QAAE,OAAO,IAAI,CAAC;IACpC,MAAM,KAAK,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC1C,OAAO,CAAC,GAAG,IAAI,EAAE,GAAG,KAAK,CAAS,CAAC,GAAG,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,KAAK,CAAC,CAAC;AACzF,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,YAAY,CAAC,OAAe;IAC1C,MAAM,MAAM,GAAG,gCAAgC,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IACnE,IAAI,MAAM,IAAI,MAAM,CAAC,MAAM,CAAC;QAAE,OAAO,MAAM,CAAC;IAC5C,IAAI,MAAM,CAAC,OAAO,CAAC;QAAE,OAAO,OAAO,CAAC;IACpC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC;QAAE,OAAO,SAAS,CAAC;IACvC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;SACtB,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;SACX,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;SAC7C,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC;AACtB,CAAC"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * How many zero bits a hash starts with: the measure of a proof of work (each bit doubles the work to find one).
3
+ *
4
+ * @example
5
+ * leadingZeroBits(new Uint8Array([0, 0b0001_0000])); // 11
6
+ */
7
+ export declare function leadingZeroBits(bytes: Uint8Array): number;
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/leading-zero-bits/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAUzD"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * How many zero bits a hash starts with: the measure of a proof of work (each bit doubles the work to find one).
3
+ *
4
+ * @example
5
+ * leadingZeroBits(new Uint8Array([0, 0b0001_0000])); // 11
6
+ */
7
+ export function leadingZeroBits(bytes) {
8
+ let count = 0;
9
+ for (const byte of bytes) {
10
+ if (byte === 0) {
11
+ count += 8;
12
+ continue;
13
+ }
14
+ return count + Math.clz32(byte) - 24;
15
+ }
16
+ return count;
17
+ }
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/leading-zero-bits/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,UAAU,eAAe,CAAC,KAAiB;IAC/C,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,IAAI,IAAI,KAAK,CAAC,EAAE,CAAC;YACf,KAAK,IAAI,CAAC,CAAC;YACX,SAAS;QACX,CAAC;QACD,OAAO,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;IACvC,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -0,0 +1,20 @@
1
+ import type { Challenge, CreateChallengeOptions, Solution, Verification, VerifySolutionOptions } from "@sharadox/protection-web-library/proof-of-work/type";
2
+ /**
3
+ * A new proof-of-work challenge for a form or an API call: invisible work for a person's browser (a moment at 14
4
+ * bits), real cost for a bot sending thousands. Signed, so the server keeps nothing until a solution comes back.
5
+ *
6
+ * @example
7
+ * const challenge = createChallenge({ secret: process.env.PROOF_OF_WORK_SECRET!, difficulty: adaptiveDifficulty(strikes) });
8
+ */
9
+ export declare function createChallenge({ secret, difficulty, now, lifetimeSeconds, }: CreateChallengeOptions): Challenge;
10
+ /**
11
+ * Checks a solution: the server's own signature (compared in constant time, so the difficulty can't be lowered), not
12
+ * expired, and the work done. On success, store the returned `id` as used until the challenge expires, and refuse it
13
+ * after: this function keeps no state.
14
+ *
15
+ * @example
16
+ * const result = verifySolution(body.proof, { secret: process.env.PROOF_OF_WORK_SECRET! });
17
+ * if (!result.valid || (await alreadyUsed(result.id))) return refuse();
18
+ */
19
+ export declare function verifySolution({ challenge, nonce }: Solution, { secret, now }: VerifySolutionOptions): Verification;
20
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +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"}
@@ -0,0 +1,48 @@
1
+ import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
+ import { leadingZeroBits } from "@sharadox/protection-web-library/leading-zero-bits";
3
+ function checkSecret(secret) {
4
+ if (secret.length < 32)
5
+ throw new Error("the proof-of-work secret must have at least 32 characters");
6
+ }
7
+ const sign = (secret, { id, salt, difficulty, expiresAt }) => createHmac("sha256", secret).update(`${id}.${salt}.${difficulty}.${expiresAt}`).digest("base64url");
8
+ /**
9
+ * A new proof-of-work challenge for a form or an API call: invisible work for a person's browser (a moment at 14
10
+ * bits), real cost for a bot sending thousands. Signed, so the server keeps nothing until a solution comes back.
11
+ *
12
+ * @example
13
+ * const challenge = createChallenge({ secret: process.env.PROOF_OF_WORK_SECRET!, difficulty: adaptiveDifficulty(strikes) });
14
+ */
15
+ export function createChallenge({ secret, difficulty, now = Date.now(), lifetimeSeconds = 300, }) {
16
+ checkSecret(secret);
17
+ const fields = {
18
+ id: randomUUID(),
19
+ salt: randomBytes(16).toString("base64url"),
20
+ difficulty,
21
+ expiresAt: now + lifetimeSeconds * 1000,
22
+ };
23
+ return { ...fields, signature: sign(secret, fields) };
24
+ }
25
+ /**
26
+ * Checks a solution: the server's own signature (compared in constant time, so the difficulty can't be lowered), not
27
+ * expired, and the work done. On success, store the returned `id` as used until the challenge expires, and refuse it
28
+ * after: this function keeps no state.
29
+ *
30
+ * @example
31
+ * const result = verifySolution(body.proof, { secret: process.env.PROOF_OF_WORK_SECRET! });
32
+ * if (!result.valid || (await alreadyUsed(result.id))) return refuse();
33
+ */
34
+ export function verifySolution({ challenge, nonce }, { secret, now = Date.now() }) {
35
+ checkSecret(secret);
36
+ const { signature, ...fields } = challenge;
37
+ const expected = Buffer.from(sign(secret, fields));
38
+ const given = Buffer.from(String(signature));
39
+ if (expected.length !== given.length || !timingSafeEqual(expected, given))
40
+ return { valid: false, reason: "signature" };
41
+ if (now > challenge.expiresAt)
42
+ return { valid: false, reason: "expired" };
43
+ const hash = createHash("sha256").update(`${challenge.salt}:${nonce}`).digest();
44
+ if (leadingZeroBits(hash) < challenge.difficulty)
45
+ return { valid: false, reason: "work" };
46
+ return { valid: true, id: challenge.id };
47
+ }
48
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/proof-of-work/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UA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,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,37 @@
1
+ /** A proof-of-work challenge, signed by the server: find a nonce so SHA-256(`salt:nonce`) starts with `difficulty` zero bits. */
2
+ export interface Challenge {
3
+ /** Unique: remember used ids until `expiresAt` so a solution counts once. */
4
+ id: string;
5
+ salt: string;
6
+ difficulty: number;
7
+ /** Milliseconds since 1970. */
8
+ expiresAt: number;
9
+ /** HMAC-SHA-256 of the fields above (base64url). */
10
+ signature: string;
11
+ }
12
+ /** What the browser sends back. */
13
+ export interface Solution {
14
+ challenge: Challenge;
15
+ nonce: string;
16
+ }
17
+ /** A valid solution (with the id to mark as used) or why not. */
18
+ export type Verification = {
19
+ valid: true;
20
+ id: string;
21
+ } | {
22
+ valid: false;
23
+ reason: "signature" | "expired" | "work";
24
+ };
25
+ export interface CreateChallengeOptions {
26
+ /** At least 32 characters, from the environment; never sent to the browser. */
27
+ secret: string;
28
+ difficulty: number;
29
+ now?: number;
30
+ /** 300 by default. */
31
+ lifetimeSeconds?: number;
32
+ }
33
+ export interface VerifySolutionOptions {
34
+ secret: string;
35
+ now?: number;
36
+ }
37
+ //# sourceMappingURL=type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/proof-of-work/type.ts"],"names":[],"mappings":"AAAA,iIAAiI;AACjI,MAAM,WAAW,SAAS;IACxB,6EAA6E;IAC7E,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;IACnB,+BAA+B;IAC/B,SAAS,EAAE,MAAM,CAAC;IAClB,oDAAoD;IACpD,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,mCAAmC;AACnC,MAAM,WAAW,QAAQ;IACvB,SAAS,EAAE,SAAS,CAAC;IACrB,KAAK,EAAE,MAAM,CAAC;CACf;AAED,iEAAiE;AACjE,MAAM,MAAM,YAAY,GAAG;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,CAAA;CAAE,CAAC;AAEpH,MAAM,WAAW,sBAAsB;IACrC,+EAA+E;IAC/E,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,sBAAsB;IACtB,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,qBAAqB;IACpC,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,CAAC,EAAE,MAAM,CAAC;CACd"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/proof-of-work/type.ts"],"names":[],"mappings":""}
@@ -0,0 +1,12 @@
1
+ import type { Challenge } from "@sharadox/protection-web-library/proof-of-work/type";
2
+ /**
3
+ * Does a challenge's work in the browser (or anywhere): tries nonces 0, 1, 2… until SHA-256(`salt:nonce`) starts
4
+ * with the challenge's zero bits, and returns the nonce to send back. No puzzle for the person to solve. It pauses
5
+ * every few thousand attempts so the page stays responsive; at high difficulties run it in a Web Worker.
6
+ *
7
+ * @example
8
+ * const nonce = await solveChallenge(challenge);
9
+ * await fetch("/api/code", { method: "POST", body: JSON.stringify({ email, proof: { challenge, nonce } }) });
10
+ */
11
+ export declare function solveChallenge({ salt, difficulty }: Pick<Challenge, "salt" | "difficulty">): Promise<string>;
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/proof-of-work-solver/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qDAAqD,CAAC;AAQrF;;;;;;;;GAQG;AACH,wBAAsB,cAAc,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,IAAI,CAAC,SAAS,EAAE,MAAM,GAAG,YAAY,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,CAKlH"}
@@ -0,0 +1,23 @@
1
+ import { leadingZeroBits } from "@sharadox/protection-web-library/leading-zero-bits";
2
+ import { sha256 } from "@sharadox/protection-web-library/sha-256";
3
+ const encoder = new TextEncoder();
4
+ /** Attempts between two pauses, so a page doing the work stays responsive. */
5
+ const BATCH = 2_000;
6
+ /**
7
+ * Does a challenge's work in the browser (or anywhere): tries nonces 0, 1, 2… until SHA-256(`salt:nonce`) starts
8
+ * with the challenge's zero bits, and returns the nonce to send back. No puzzle for the person to solve. It pauses
9
+ * every few thousand attempts so the page stays responsive; at high difficulties run it in a Web Worker.
10
+ *
11
+ * @example
12
+ * const nonce = await solveChallenge(challenge);
13
+ * await fetch("/api/code", { method: "POST", body: JSON.stringify({ email, proof: { challenge, nonce } }) });
14
+ */
15
+ export async function solveChallenge({ salt, difficulty }) {
16
+ for (let nonce = 0;; nonce++) {
17
+ if (leadingZeroBits(sha256(encoder.encode(`${salt}:${nonce}`))) >= difficulty)
18
+ return String(nonce);
19
+ if (nonce % BATCH === BATCH - 1)
20
+ await new Promise((resolve) => setTimeout(resolve, 0));
21
+ }
22
+ }
23
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/proof-of-work-solver/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,oDAAoD,CAAC;AAErF,OAAO,EAAE,MAAM,EAAE,MAAM,0CAA0C,CAAC;AAElE,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC,8EAA8E;AAC9E,MAAM,KAAK,GAAG,KAAK,CAAC;AAEpB;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,EAAE,IAAI,EAAE,UAAU,EAA0C;IAC/F,KAAK,IAAI,KAAK,GAAG,CAAC,GAAI,KAAK,EAAE,EAAE,CAAC;QAC9B,IAAI,eAAe,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,IAAI,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,UAAU;YAAE,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;QACpG,IAAI,KAAK,GAAG,KAAK,KAAK,KAAK,GAAG,CAAC;YAAE,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC;IAC1F,CAAC;AACH,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,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE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okenBucketRule } 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"}
@@ -0,0 +1,17 @@
1
+ /** How many actions a key may take: `capacity` at once, then `refillPerSecond` more each second. */
2
+ export interface TokenBucketRule {
3
+ capacity: number;
4
+ refillPerSecond: number;
5
+ }
6
+ /** What is remembered per key: tokens left and when (milliseconds since 1970). */
7
+ export interface TokenBucket {
8
+ tokens: number;
9
+ updatedAt: number;
10
+ }
11
+ /** Whether the action may go ahead, the bucket to store, and how long to wait when it may not. */
12
+ export interface TokenBucketResult {
13
+ allowed: boolean;
14
+ bucket: TokenBucket;
15
+ retryAfterSeconds: number;
16
+ }
17
+ //# sourceMappingURL=type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/token-bucket/type.ts"],"names":[],"mappings":"AAAA,oGAAoG;AACpG,MAAM,WAAW,eAAe;IAC9B,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe,EAAE,MAAM,CAAC;CACzB;AAED,kFAAkF;AAClF,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,kGAAkG;AAClG,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,EAAE,WAAW,CAAC;IACpB,iBAAiB,EAAE,MAAM,CAAC;CAC3B"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/token-bucket/type.ts"],"names":[],"mappings":""}
package/package.json CHANGED
@@ -1,6 +1,88 @@
1
1
  {
2
2
  "name": "@sharadox/protection-web-library",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-development.3",
4
+ "description": "Protection for web forms and APIs: layered rate limits, proof-of-work challenges and spending caps.",
5
+ "private": false,
6
+ "license": "SEE LICENSE IN LICENCA.md",
7
+ "author": "Sharadox <contact@sharadox.com>",
8
+ "type": "module",
9
+ "exports": {
10
+ "./*/type": {
11
+ "sharadox-source": "./source/*/type.ts",
12
+ "types": "./distribution/*/type.d.ts"
13
+ },
14
+ "./*": {
15
+ "sharadox-source": [
16
+ "./source/*/index.ts"
17
+ ],
18
+ "types": "./distribution/*/index.d.ts",
19
+ "default": "./distribution/*/index.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "distribution",
24
+ "LICENCA.md",
25
+ "LICENSE.md",
26
+ "NOTICE.md"
27
+ ],
28
+ "sideEffects": false,
29
+ "engines": {
30
+ "node": ">=26"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "lint-staged": {
36
+ "*.{ts,js,mjs,cjs}": [
37
+ "prettier --write",
38
+ "eslint --fix --max-warnings=0"
39
+ ],
40
+ "*.{json,md,yml,yaml}": "prettier --write"
41
+ },
42
+ "dependencies": {
43
+ "@sharadox/web-library": "^0.11.1"
44
+ },
45
+ "devDependencies": {
46
+ "@sharadox/es-lint-configuration-web-library": "^0.1.3",
47
+ "@sharadox/library-build-web-library": "^0.2.1",
48
+ "@sharadox/prettier-configuration-web-library": "^0.1.2",
49
+ "@sharadox/turborepo-configuration-web-library": "^0.1.4",
50
+ "@sharadox/type-script-configuration-web-library": "^0.2.3",
51
+ "@sharadox/vitest-configuration-web-library": "^0.2.1",
52
+ "@types/node": "^26.6.6",
53
+ "@vitest/coverage-v8": "^5.1.1",
54
+ "eslint": "9.39.5",
55
+ "happy-dom": "^21.0.4",
56
+ "husky": "^9.1.7",
57
+ "lint-staged": "^17.6.2",
58
+ "prettier": "^3.10.1",
59
+ "turbo": "^2.11.13",
60
+ "typedoc": "^0.28.20",
61
+ "typescript": "6.0.3",
62
+ "vitest": "^5.1.1"
63
+ },
64
+ "repository": {
65
+ "type": "git",
66
+ "url": "git+https://github.com/Sharadox/protection-web-library.git"
67
+ },
68
+ "homepage": "https://github.com/Sharadox/protection-web-library#readme",
69
+ "keywords": [
70
+ "rate-limit",
71
+ "proof-of-work",
72
+ "abuse",
73
+ "denial-of-wallet",
74
+ "security",
75
+ "forms"
76
+ ],
77
+ "scripts": {
78
+ "build": "library-build",
79
+ "lint": "eslint --max-warnings=0 .",
80
+ "format": "prettier --write .",
81
+ "format:check": "prettier --check .",
82
+ "type-check": "tsc --noEmit",
83
+ "test:unit": "vitest run --coverage",
84
+ "test:benchmark": "vitest bench --run --passWithNoTests",
85
+ "documentation": "typedoc",
86
+ "verify": "turbo run format:check lint type-check test:unit test:benchmark build"
87
+ }
6
88
  }