@sharadox/form-web-library 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENCA.md +76 -0
- package/LICENSE.md +76 -0
- package/NOTICE.md +3 -0
- package/README.md +63 -2
- package/distribution/bot-check/index.d.ts +4 -0
- package/distribution/bot-check/index.d.ts.map +1 -0
- package/distribution/bot-check/index.js +6 -0
- package/distribution/bot-check/index.js.map +1 -0
- package/distribution/bot-check/type.d.ts +11 -0
- package/distribution/bot-check/type.d.ts.map +1 -0
- package/distribution/bot-check/type.js +2 -0
- package/distribution/bot-check/type.js.map +1 -0
- package/distribution/contact-action/index.d.ts +14 -0
- package/distribution/contact-action/index.d.ts.map +1 -0
- package/distribution/contact-action/index.js +61 -0
- package/distribution/contact-action/index.js.map +1 -0
- package/distribution/contact-action/type.d.ts +31 -0
- package/distribution/contact-action/type.d.ts.map +1 -0
- package/distribution/contact-action/type.js +2 -0
- package/distribution/contact-action/type.js.map +1 -0
- package/distribution/field/index.d.ts +3 -0
- package/distribution/field/index.d.ts.map +1 -0
- package/distribution/field/index.js +7 -0
- package/distribution/field/index.js.map +1 -0
- package/distribution/parse-contact/index.d.ts +11 -0
- package/distribution/parse-contact/index.d.ts.map +1 -0
- package/distribution/parse-contact/index.js +27 -0
- package/distribution/parse-contact/index.js.map +1 -0
- package/distribution/parse-contact/type.d.ts +29 -0
- package/distribution/parse-contact/type.d.ts.map +1 -0
- package/distribution/parse-contact/type.js +2 -0
- package/distribution/parse-contact/type.js.map +1 -0
- package/distribution/rate-limit/index.d.ts +4 -0
- package/distribution/rate-limit/index.d.ts.map +1 -0
- package/distribution/rate-limit/index.js +14 -0
- package/distribution/rate-limit/index.js.map +1 -0
- package/distribution/rate-limit/type.d.ts +9 -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/llms.txt +9 -0
- package/package.json +78 -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
package/README.md
CHANGED
|
@@ -1,3 +1,64 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @sharadox/form-web-library
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Forms on the server, written once for every site:
|
|
4
|
+
|
|
5
|
+
- **Field reading:** trimmed and capped in length.
|
|
6
|
+
- **Bot checks:** a hidden honeypot field, and a minimum time to fill the form.
|
|
7
|
+
- **Rate limiting:** a sliding window per key.
|
|
8
|
+
- **A contact form action:** it validates, fakes success for bots, limits each address, and emails the message in text and HTML with the visitor as reply-to, through `@sharadox/email-web-library`.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
pnpm add @sharadox/form-web-library
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Use
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
// the site's library
|
|
20
|
+
export const sendContact = createContactAction({
|
|
21
|
+
to: "contact@example.com",
|
|
22
|
+
senderName: "Example Web Application",
|
|
23
|
+
site: "example.com",
|
|
24
|
+
subject: (message) =>
|
|
25
|
+
separate("•", "Contact", message.company ? `${message.name} (${message.company})` : message.name),
|
|
26
|
+
choices: { website: "Website", logo: "Logo", other: "Others" },
|
|
27
|
+
});
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
// the application's server action
|
|
32
|
+
"use server";
|
|
33
|
+
export async function sendContactAction(_: ContactState, form: FormData) {
|
|
34
|
+
const ip = (await headers()).get("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown";
|
|
35
|
+
return sendContact(form, ip);
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
The form sends these fields:
|
|
40
|
+
|
|
41
|
+
- **text:** `name`, `email`, `company`, `message`
|
|
42
|
+
- **hidden:** `locale`, and `started-at` (`Date.now()` when the visitor started)
|
|
43
|
+
- **checkboxes:** `need`
|
|
44
|
+
- **honeypot:** `website`, kept off screen
|
|
45
|
+
|
|
46
|
+
The email server comes from `EMAIL_SERVER_*` and `EMAIL_SENDER_ADDRESS`.
|
|
47
|
+
|
|
48
|
+
## API
|
|
49
|
+
|
|
50
|
+
| Import | Export |
|
|
51
|
+
| ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
52
|
+
| `…/contact-action` | `createContactAction(options)` → `(form, ip) => Promise<ContactState>`; `ContactState` and `ContactActionOptions` in `…/contact-action/type` |
|
|
53
|
+
| `…/parse-contact` | `parseContact(form, { choices?, choiceField?, now? })` → `bot`, `invalid` or `valid` |
|
|
54
|
+
| `…/bot-check` | `isLikelyBot(form, { honeypotField?, startedAtField?, minimumFillTime?, now? })` |
|
|
55
|
+
| `…/rate-limit` | `createRateLimiter({ window, maximum })` → `(key, now?) => boolean` (kept in memory, per server instance) |
|
|
56
|
+
| `…/field` | `readField(form, name, maximumLength)` |
|
|
57
|
+
|
|
58
|
+
## Develop
|
|
59
|
+
|
|
60
|
+
`pnpm verify` runs formatting, lint, type-check, tests with 100% coverage and the build. Branches follow `<feature>.development` → `development` → `index`, and releases are `v<version>` tags on `index`.
|
|
61
|
+
|
|
62
|
+
## Licence
|
|
63
|
+
|
|
64
|
+
Licença Sharadox de Código Aberto, versão 0.1.0. See [português](LICENCA.md) (the binding text) and the [English translation](LICENSE.md).
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { BotCheckOptions } from "@sharadox/form-web-library/bot-check/type";
|
|
2
|
+
/** Whether a form submission looks automated: the honeypot is filled, or it was submitted faster than people can. */
|
|
3
|
+
export declare function isLikelyBot(form: FormData, { honeypotField, startedAtField, minimumFillTime, now, }?: BotCheckOptions): boolean;
|
|
4
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/bot-check/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,2CAA2C,CAAC;AAEjF,qHAAqH;AACrH,wBAAgB,WAAW,CACzB,IAAI,EAAE,QAAQ,EACd,EACE,aAAyB,EACzB,cAA6B,EAC7B,eAAsB,EACtB,GAAgB,GACjB,GAAE,eAAoB,GACtB,OAAO,CAGT"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Whether a form submission looks automated: the honeypot is filled, or it was submitted faster than people can. */
|
|
2
|
+
export function isLikelyBot(form, { honeypotField = "website", startedAtField = "started-at", minimumFillTime = 2500, now = Date.now(), } = {}) {
|
|
3
|
+
const started = Number(form.get(startedAtField) ?? 0);
|
|
4
|
+
return Boolean(form.get(honeypotField)) || Boolean(started && now - started < minimumFillTime);
|
|
5
|
+
}
|
|
6
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/bot-check/index.ts"],"names":[],"mappings":"AAEA,qHAAqH;AACrH,MAAM,UAAU,WAAW,CACzB,IAAc,EACd,EACE,aAAa,GAAG,SAAS,EACzB,cAAc,GAAG,YAAY,EAC7B,eAAe,GAAG,IAAI,EACtB,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,MACG,EAAE;IAEvB,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC;IACtD,OAAO,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,IAAI,OAAO,CAAC,OAAO,IAAI,GAAG,GAAG,OAAO,GAAG,eAAe,CAAC,CAAC;AACjG,CAAC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface BotCheckOptions {
|
|
2
|
+
/** A field hidden from people; anything typed in it was typed by a bot. Defaults to "website". */
|
|
3
|
+
honeypotField?: string;
|
|
4
|
+
/** A hidden field holding when the visitor started filling the form (milliseconds). Defaults to "started-at". */
|
|
5
|
+
startedAtField?: string;
|
|
6
|
+
/** People take longer than this to fill a form, in milliseconds. Defaults to 2500. */
|
|
7
|
+
minimumFillTime?: number;
|
|
8
|
+
/** Defaults to now. */
|
|
9
|
+
now?: number;
|
|
10
|
+
}
|
|
11
|
+
//# sourceMappingURL=type.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/bot-check/type.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,eAAe;IAC9B,kGAAkG;IAClG,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,iHAAiH;IACjH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,sFAAsF;IACtF,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,uBAAuB;IACvB,GAAG,CAAC,EAAE,MAAM,CAAC;CACd"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/bot-check/type.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ContactActionOptions, ContactState } from "@sharadox/form-web-library/contact-action/type";
|
|
2
|
+
/**
|
|
3
|
+
* Builds the work of a contact form's server action: checks for bots (they get a fake success), validates, limits
|
|
4
|
+
* each address, then emails the message with the visitor as reply-to, in plain text and HTML (user input escaped).
|
|
5
|
+
* The application's server action reads the visitor's IP address and calls the result.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* const sendContact = createContactAction({ to: "contact@sharadox.com", senderName: "Sharadox Web Application",
|
|
9
|
+
* site: "sharadox.com", subject: (message) => separate("•", "Contact", message.name) });
|
|
10
|
+
* // in a "use server" file:
|
|
11
|
+
* export async function sendContactAction(_: ContactState, form: FormData) { return sendContact(form, ip); }
|
|
12
|
+
*/
|
|
13
|
+
export declare function createContactAction({ to, senderName, senderAddress, subject, choices, site, rateLimit, readConfiguration, createSender, reportError, }: ContactActionOptions): (form: FormData, ip: string) => Promise<ContactState>;
|
|
14
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/contact-action/index.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,oBAAoB,EAAE,YAAY,EAAE,MAAM,gDAAgD,CAAC;AAIzG;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CAAC,EAClC,EAAE,EACF,UAAU,EACV,aAAa,EACb,OAAO,EACP,OAAY,EACZ,IAAI,EACJ,SAAkD,EAClD,iBAAgD,EAChD,YAAgC,EAChC,WAA+D,GAChE,EAAE,oBAAoB,GAAG,CAAC,IAAI,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,YAAY,CAAC,CAqC9E"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { createEmailSender, EmailError, readEmailServerConfiguration } from "@sharadox/email-web-library";
|
|
2
|
+
import { escapeHtml } from "@sharadox/web-library/html/escape";
|
|
3
|
+
import { separate } from "@sharadox/web-library/text/separate";
|
|
4
|
+
import { createRateLimiter } from "@sharadox/form-web-library/rate-limit";
|
|
5
|
+
import { parseContact } from "@sharadox/form-web-library/parse-contact";
|
|
6
|
+
const oneLine = (text) => text.replace(/[\r\n]+/g, " ");
|
|
7
|
+
/**
|
|
8
|
+
* Builds the work of a contact form's server action: checks for bots (they get a fake success), validates, limits
|
|
9
|
+
* each address, then emails the message with the visitor as reply-to, in plain text and HTML (user input escaped).
|
|
10
|
+
* The application's server action reads the visitor's IP address and calls the result.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* const sendContact = createContactAction({ to: "contact@sharadox.com", senderName: "Sharadox Web Application",
|
|
14
|
+
* site: "sharadox.com", subject: (message) => separate("•", "Contact", message.name) });
|
|
15
|
+
* // in a "use server" file:
|
|
16
|
+
* export async function sendContactAction(_: ContactState, form: FormData) { return sendContact(form, ip); }
|
|
17
|
+
*/
|
|
18
|
+
export function createContactAction({ to, senderName, senderAddress, subject, choices = {}, site, rateLimit = { window: 60 * 60 * 1000, maximum: 5 }, readConfiguration = readEmailServerConfiguration, createSender = createEmailSender, reportError = (message, error) => console.error(message, error), }) {
|
|
19
|
+
const allow = createRateLimiter(rateLimit);
|
|
20
|
+
return async (form, ip) => {
|
|
21
|
+
const parsed = parseContact(form, { choices: Object.keys(choices) });
|
|
22
|
+
if (parsed.kind === "bot")
|
|
23
|
+
return { status: "sent" };
|
|
24
|
+
if (parsed.kind === "invalid")
|
|
25
|
+
return { status: "invalid" };
|
|
26
|
+
if (!allow(ip))
|
|
27
|
+
return { status: "rate-limited" };
|
|
28
|
+
const message = parsed.value;
|
|
29
|
+
const named = message.choices.map((choice) => choices[choice]);
|
|
30
|
+
const text = `Name: ${message.name}\nEmail: ${message.email}\nCompany: ${message.company || "—"}\nNeeds: ${named.join(", ") || "—"}\nLanguage: ${message.locale}\nIP: ${ip}\n\n${message.message}`;
|
|
31
|
+
const html = `<div style="font-family:-apple-system,Segoe UI,sans-serif;font-size:15px;line-height:1.6;color:#111">
|
|
32
|
+
<p style="color:#666;font-size:13px;margin:0 0 16px">New message from ${escapeHtml(site)} (${escapeHtml(message.locale)})</p>
|
|
33
|
+
<p style="margin:0">${separate("·", `<b>${escapeHtml(message.name)}</b>`, message.company && escapeHtml(message.company))}<br><a href="mailto:${escapeHtml(message.email)}">${escapeHtml(message.email)}</a></p>
|
|
34
|
+
${named.length ? `<p style="margin:12px 0 0;color:#444">${escapeHtml(named.join(", "))}</p>` : ""}
|
|
35
|
+
<hr style="border:0;border-top:1px solid #eee;margin:18px 0">
|
|
36
|
+
<p style="white-space:pre-wrap;margin:0">${escapeHtml(message.message)}</p></div>`;
|
|
37
|
+
try {
|
|
38
|
+
const configuration = readConfiguration();
|
|
39
|
+
await createSender(configuration).send({
|
|
40
|
+
from: {
|
|
41
|
+
name: senderName,
|
|
42
|
+
address: senderAddress || process.env.EMAIL_SENDER_ADDRESS || configuration.username,
|
|
43
|
+
},
|
|
44
|
+
to,
|
|
45
|
+
// Replying to the email answers the visitor at the address they typed.
|
|
46
|
+
replyTo: { name: oneLine(message.name), address: message.email },
|
|
47
|
+
subject: oneLine(subject(message)).slice(0, 300),
|
|
48
|
+
text,
|
|
49
|
+
html,
|
|
50
|
+
});
|
|
51
|
+
return { status: "sent" };
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
if (error instanceof EmailError && error.code === "invalid-message")
|
|
55
|
+
return { status: "invalid" };
|
|
56
|
+
reportError("contact: sending failed", error);
|
|
57
|
+
return { status: "failed" };
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/contact-action/index.ts"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { EmailSender, EmailServerConfiguration } from "@sharadox/email-web-library";
|
|
2
|
+
import type { ContactMessage } from "@sharadox/form-web-library/parse-contact/type";
|
|
3
|
+
/** What the form shows after a submission. */
|
|
4
|
+
export interface ContactState {
|
|
5
|
+
status: "idle" | "sent" | "invalid" | "rate-limited" | "failed";
|
|
6
|
+
}
|
|
7
|
+
export interface ContactActionOptions {
|
|
8
|
+
/** Where messages go, for example "contact@sharadox.com". */
|
|
9
|
+
to: string;
|
|
10
|
+
/** The sender's display name, for example "Sharadox Web Application". */
|
|
11
|
+
senderName: string;
|
|
12
|
+
/** The sender address (an address the email server may send from); `EMAIL_SENDER_ADDRESS` or the server user. */
|
|
13
|
+
senderAddress?: string;
|
|
14
|
+
/** The email subject for a message, for example `Contact • Ana (Café)`. */
|
|
15
|
+
subject: (message: ContactMessage) => string;
|
|
16
|
+
/** Choices the form may send, and how each is named in the email; none by default. */
|
|
17
|
+
choices?: Readonly<Record<string, string>>;
|
|
18
|
+
/** Where the email says the message came from, for example "sharadox.com". */
|
|
19
|
+
site: string;
|
|
20
|
+
/** Messages per address per window; 5 per hour by default. */
|
|
21
|
+
rateLimit?: {
|
|
22
|
+
window: number;
|
|
23
|
+
maximum: number;
|
|
24
|
+
};
|
|
25
|
+
/** The email server; read from `EMAIL_SERVER_*` by default. */
|
|
26
|
+
readConfiguration?: () => EmailServerConfiguration;
|
|
27
|
+
createSender?: (configuration: EmailServerConfiguration) => EmailSender;
|
|
28
|
+
/** Where failures are reported; `console.error` by default. */
|
|
29
|
+
reportError?: (message: string, error: unknown) => void;
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=type.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/contact-action/type.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACzF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,+CAA+C,CAAC;AAEpF,8CAA8C;AAC9C,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,GAAG,cAAc,GAAG,QAAQ,CAAC;CACjE;AAED,MAAM,WAAW,oBAAoB;IACnC,6DAA6D;IAC7D,EAAE,EAAE,MAAM,CAAC;IACX,yEAAyE;IACzE,UAAU,EAAE,MAAM,CAAC;IACnB,iHAAiH;IACjH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,2EAA2E;IAC3E,OAAO,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,MAAM,CAAC;IAC7C,sFAAsF;IACtF,OAAO,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAC3C,8EAA8E;IAC9E,IAAI,EAAE,MAAM,CAAC;IACb,8DAA8D;IAC9D,SAAS,CAAC,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;IAChD,+DAA+D;IAC/D,iBAAiB,CAAC,EAAE,MAAM,wBAAwB,CAAC;IACnD,YAAY,CAAC,EAAE,CAAC,aAAa,EAAE,wBAAwB,KAAK,WAAW,CAAC;IACxE,+DAA+D;IAC/D,WAAW,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;CACzD"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/contact-action/type.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/field/index.ts"],"names":[],"mappings":"AAAA,8GAA8G;AAC9G,wBAAgB,SAAS,CAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,GAAG,MAAM,CAIrF"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** A text field from submitted form data, trimmed and cut to `maximumLength` characters ("" when missing). */
|
|
2
|
+
export function readField(form, name, maximumLength) {
|
|
3
|
+
return String(form.get(name) ?? "")
|
|
4
|
+
.trim()
|
|
5
|
+
.slice(0, maximumLength);
|
|
6
|
+
}
|
|
7
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/field/index.ts"],"names":[],"mappings":"AAAA,8GAA8G;AAC9G,MAAM,UAAU,SAAS,CAAC,IAAc,EAAE,IAAY,EAAE,aAAqB;IAC3E,OAAO,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;SAChC,IAAI,EAAE;SACN,KAAK,CAAC,CAAC,EAAE,aAAa,CAAC,CAAC;AAC7B,CAAC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { ParseContactOptions, ParsedContact } from "@sharadox/form-web-library/parse-contact/type";
|
|
2
|
+
/**
|
|
3
|
+
* Reads and validates a contact form (`name`, `email`, `company`, `message`, `locale` and checkbox choices), and
|
|
4
|
+
* flags likely bots (honeypot filled or submitted too fast). Fields are trimmed and capped in length.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* const parsed = parseContact(form, { choices: ["website", "logo", "other"] });
|
|
8
|
+
* if (parsed.kind === "valid") console.log(parsed.value.choices);
|
|
9
|
+
*/
|
|
10
|
+
export declare function parseContact(form: FormData, { choices, choiceField, now }?: ParseContactOptions): ParsedContact;
|
|
11
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/parse-contact/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,+CAA+C,CAAC;AAIxG;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAC1B,IAAI,EAAE,QAAQ,EACd,EAAE,OAAY,EAAE,WAAoB,EAAE,GAAgB,EAAE,GAAE,mBAAwB,GACjF,aAAa,CAYf"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { isLikelyBot } from "@sharadox/form-web-library/bot-check";
|
|
2
|
+
import { readField } from "@sharadox/form-web-library/field";
|
|
3
|
+
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
|
|
4
|
+
/**
|
|
5
|
+
* Reads and validates a contact form (`name`, `email`, `company`, `message`, `locale` and checkbox choices), and
|
|
6
|
+
* flags likely bots (honeypot filled or submitted too fast). Fields are trimmed and capped in length.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* const parsed = parseContact(form, { choices: ["website", "logo", "other"] });
|
|
10
|
+
* if (parsed.kind === "valid") console.log(parsed.value.choices);
|
|
11
|
+
*/
|
|
12
|
+
export function parseContact(form, { choices = [], choiceField = "need", now = Date.now() } = {}) {
|
|
13
|
+
if (isLikelyBot(form, { now }))
|
|
14
|
+
return { kind: "bot" };
|
|
15
|
+
const value = {
|
|
16
|
+
name: readField(form, "name", 120),
|
|
17
|
+
email: readField(form, "email", 200),
|
|
18
|
+
company: readField(form, "company", 160),
|
|
19
|
+
message: readField(form, "message", 5000),
|
|
20
|
+
locale: readField(form, "locale", 10) || "en",
|
|
21
|
+
choices: [...new Set(form.getAll(choiceField).map(String))].filter((choice) => choices.includes(choice)),
|
|
22
|
+
};
|
|
23
|
+
if (!value.name || !value.message || !EMAIL.test(value.email))
|
|
24
|
+
return { kind: "invalid" };
|
|
25
|
+
return { kind: "valid", value };
|
|
26
|
+
}
|
|
27
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/parse-contact/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AACnE,OAAO,EAAE,SAAS,EAAE,MAAM,kCAAkC,CAAC;AAG7D,MAAM,KAAK,GAAG,+BAA+B,CAAC;AAE9C;;;;;;;GAOG;AACH,MAAM,UAAU,YAAY,CAC1B,IAAc,EACd,EAAE,OAAO,GAAG,EAAE,EAAE,WAAW,GAAG,MAAM,EAAE,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,KAA0B,EAAE;IAElF,IAAI,WAAW,CAAC,IAAI,EAAE,EAAE,GAAG,EAAE,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;IACvD,MAAM,KAAK,GAAG;QACZ,IAAI,EAAE,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,CAAC;QAClC,KAAK,EAAE,SAAS,CAAC,IAAI,EAAE,OAAO,EAAE,GAAG,CAAC;QACpC,OAAO,EAAE,SAAS,CAAC,IAAI,EAAE,SAAS,EAAE,GAAG,CAAC;QACxC,OAAO,EAAE,SAAS,CAAC,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC;QACzC,MAAM,EAAE,SAAS,CAAC,IAAI,EAAE,QAAQ,EAAE,EAAE,CAAC,IAAI,IAAI;QAC7C,OAAO,EAAE,CAAC,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;KACzG,CAAC;IACF,IAAI,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;IAC1F,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAClC,CAAC"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** A validated contact form submission. */
|
|
2
|
+
export interface ContactMessage {
|
|
3
|
+
name: string;
|
|
4
|
+
email: string;
|
|
5
|
+
/** Optional; "" when not given. */
|
|
6
|
+
company: string;
|
|
7
|
+
message: string;
|
|
8
|
+
/** The page's locale, sent in a hidden field. */
|
|
9
|
+
locale: string;
|
|
10
|
+
/** The ticked choices (for example "what do you need?"), only from the allowed list. */
|
|
11
|
+
choices: string[];
|
|
12
|
+
}
|
|
13
|
+
export type ParsedContact = {
|
|
14
|
+
kind: "bot";
|
|
15
|
+
} | {
|
|
16
|
+
kind: "invalid";
|
|
17
|
+
} | {
|
|
18
|
+
kind: "valid";
|
|
19
|
+
value: ContactMessage;
|
|
20
|
+
};
|
|
21
|
+
export interface ParseContactOptions {
|
|
22
|
+
/** Choice values the form may send; anything else is ignored. None by default. */
|
|
23
|
+
choices?: readonly string[];
|
|
24
|
+
/** The checkbox field holding the choices; "need" by default. */
|
|
25
|
+
choiceField?: string;
|
|
26
|
+
/** Now, for the fill-time check (tests). */
|
|
27
|
+
now?: number;
|
|
28
|
+
}
|
|
29
|
+
//# sourceMappingURL=type.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/parse-contact/type.ts"],"names":[],"mappings":"AAAA,2CAA2C;AAC3C,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,mCAAmC;IACnC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,iDAAiD;IACjD,MAAM,EAAE,MAAM,CAAC;IACf,wFAAwF;IACxF,OAAO,EAAE,MAAM,EAAE,CAAC;CACnB;AAED,MAAM,MAAM,aAAa,GAAG;IAAE,IAAI,EAAE,KAAK,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,cAAc,CAAA;CAAE,CAAC;AAE7G,MAAM,WAAW,mBAAmB;IAClC,kFAAkF;IAClF,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5B,iEAAiE;IACjE,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,4CAA4C;IAC5C,GAAG,CAAC,EAAE,MAAM,CAAC;CACd"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/parse-contact/type.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { RateLimiter, RateLimitOptions } from "@sharadox/form-web-library/rate-limit/type";
|
|
2
|
+
/** In-memory sliding-window rate limiter. Best effort: each server instance keeps its own memory. */
|
|
3
|
+
export declare function createRateLimiter({ window, maximum }: RateLimitOptions): RateLimiter;
|
|
4
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/rate-limit/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,4CAA4C,CAAC;AAEhG,qGAAqG;AACrG,wBAAgB,iBAAiB,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,gBAAgB,GAAG,WAAW,CAWpF"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** In-memory sliding-window rate limiter. Best effort: each server instance keeps its own memory. */
|
|
2
|
+
export function createRateLimiter({ window, maximum }) {
|
|
3
|
+
const hits = new Map();
|
|
4
|
+
return (key, now = Date.now()) => {
|
|
5
|
+
const recent = (hits.get(key) ?? []).filter((time) => now - time < window);
|
|
6
|
+
if (recent.length >= maximum) {
|
|
7
|
+
hits.set(key, recent);
|
|
8
|
+
return false;
|
|
9
|
+
}
|
|
10
|
+
hits.set(key, [...recent, now]);
|
|
11
|
+
return true;
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/rate-limit/index.ts"],"names":[],"mappings":"AAEA,qGAAqG;AACrG,MAAM,UAAU,iBAAiB,CAAC,EAAE,MAAM,EAAE,OAAO,EAAoB;IACrE,MAAM,IAAI,GAAG,IAAI,GAAG,EAAoB,CAAC;IACzC,OAAO,CAAC,GAAG,EAAE,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,EAAE,EAAE;QAC/B,MAAM,MAAM,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,GAAG,IAAI,GAAG,MAAM,CAAC,CAAC;QAC3E,IAAI,MAAM,CAAC,MAAM,IAAI,OAAO,EAAE,CAAC;YAC7B,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;YACtB,OAAO,KAAK,CAAC;QACf,CAAC;QACD,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC;QAChC,OAAO,IAAI,CAAC;IACd,CAAC,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export interface RateLimitOptions {
|
|
2
|
+
/** Window length in milliseconds. */
|
|
3
|
+
window: number;
|
|
4
|
+
/** Allowed hits per key inside the window. */
|
|
5
|
+
maximum: number;
|
|
6
|
+
}
|
|
7
|
+
/** Records a hit for a key; returns false when the key is over its limit. */
|
|
8
|
+
export type RateLimiter = (key: string, now?: number) => boolean;
|
|
9
|
+
//# 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,MAAM,WAAW,gBAAgB;IAC/B,qCAAqC;IACrC,MAAM,EAAE,MAAM,CAAC;IACf,8CAA8C;IAC9C,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,6EAA6E;AAC7E,MAAM,MAAM,WAAW,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/rate-limit/type.ts"],"names":[],"mappings":""}
|
package/llms.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# @sharadox/form-web-library
|
|
2
|
+
|
|
3
|
+
> Server-side forms: bot checks, rate limit, contact action emailing via @sharadox/email-web-library.
|
|
4
|
+
|
|
5
|
+
- /contact-action: createContactAction({ to, senderName, senderAddress?, site, subject(message), choices?: { key: label }, rateLimit? = 5/hour, readConfiguration?, createSender?, reportError? }) → (form, ip) => { status: idle|sent|invalid|rate-limited|failed }. Reply-to = visitor; bots get fake 'sent'.
|
|
6
|
+
- Form fields: name, email, company, message, locale, started-at, website (honeypot), need (checkboxes).
|
|
7
|
+
- /parse-contact: parseContact(form, { choices, choiceField='need', now })
|
|
8
|
+
- /bot-check isLikelyBot; /rate-limit createRateLimiter({ window, maximum }); /field readField(form, name, max)
|
|
9
|
+
- Env: EMAIL_SERVER_HOST/PORT/USERNAME/PASSWORD, EMAIL_SENDER_ADDRESS. Licence: Sharadox Open Source Licence 0.1.0
|
package/package.json
CHANGED
|
@@ -1,6 +1,81 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sharadox/form-web-library",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Forms on the server: field reading, honeypot and fill-time bot checks, rate limiting and a contact form action that emails messages with the visitor as reply-to.",
|
|
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
|
+
"./source/*/index.tsx"
|
|
18
|
+
],
|
|
19
|
+
"types": "./distribution/*/index.d.ts",
|
|
20
|
+
"default": "./distribution/*/index.js"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"distribution",
|
|
25
|
+
"LICENCA.md",
|
|
26
|
+
"LICENSE.md",
|
|
27
|
+
"NOTICE.md",
|
|
28
|
+
"llms.txt"
|
|
29
|
+
],
|
|
30
|
+
"sideEffects": false,
|
|
31
|
+
"engines": {
|
|
32
|
+
"node": ">=24"
|
|
33
|
+
},
|
|
34
|
+
"publishConfig": {
|
|
35
|
+
"access": "public"
|
|
36
|
+
},
|
|
37
|
+
"lint-staged": {
|
|
38
|
+
"*.{ts,tsx,js,mjs,cjs}": [
|
|
39
|
+
"prettier --write",
|
|
40
|
+
"eslint --fix --max-warnings=0"
|
|
41
|
+
],
|
|
42
|
+
"*.{json,md,yml,yaml,scss}": "prettier --write"
|
|
43
|
+
},
|
|
44
|
+
"repository": {
|
|
45
|
+
"type": "git",
|
|
46
|
+
"url": "git+https://github.com/Sharadox/form-web-library.git"
|
|
47
|
+
},
|
|
48
|
+
"homepage": "https://github.com/Sharadox/form-web-library#readme",
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@sharadox/es-lint-configuration-web-library": "^0.1.1",
|
|
51
|
+
"@sharadox/prettier-configuration-web-library": "^0.1.0",
|
|
52
|
+
"@sharadox/turborepo-configuration-web-library": "^0.1.0",
|
|
53
|
+
"@sharadox/type-script-configuration-web-library": "^0.2.0",
|
|
54
|
+
"@sharadox/vitest-configuration-web-library": "^0.1.2",
|
|
55
|
+
"@types/node": "^24.19.2",
|
|
56
|
+
"@vitest/coverage-v8": "^5.1.0",
|
|
57
|
+
"eslint": "9.39.5",
|
|
58
|
+
"husky": "^9.1.7",
|
|
59
|
+
"lint-staged": "^17.6.0",
|
|
60
|
+
"prettier": "^3.10.0",
|
|
61
|
+
"turbo": "^2.11.10",
|
|
62
|
+
"typedoc": "^0.28.20",
|
|
63
|
+
"typescript": "6.0.3",
|
|
64
|
+
"vitest": "^5.1.0"
|
|
65
|
+
},
|
|
66
|
+
"dependencies": {
|
|
67
|
+
"@sharadox/email-web-library": "^0.2.1",
|
|
68
|
+
"@sharadox/web-library": "^0.5.0"
|
|
69
|
+
},
|
|
70
|
+
"scripts": {
|
|
71
|
+
"build": "rm -rf distribution && tsc -p tsconfig.build.json",
|
|
72
|
+
"lint": "eslint --max-warnings=0 .",
|
|
73
|
+
"format": "prettier --write .",
|
|
74
|
+
"format:check": "prettier --check .",
|
|
75
|
+
"type-check": "tsc --noEmit",
|
|
76
|
+
"test:unit": "vitest run --coverage",
|
|
77
|
+
"documentation": "typedoc",
|
|
78
|
+
"verify": "turbo run format:check lint type-check test:unit build",
|
|
79
|
+
"test:benchmark": "vitest bench --run --passWithNoTests"
|
|
80
|
+
}
|
|
6
81
|
}
|