@webpresso/forms 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/LICENSE +104 -0
- package/README.md +83 -2
- package/dist/adapters/turnstile.d.ts +5 -0
- package/dist/adapters/turnstile.js +40 -0
- package/dist/contact-form.d.ts +73 -0
- package/dist/contact-form.js +186 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/package.json +46 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
Elastic License 2.0
|
|
2
|
+
===================
|
|
3
|
+
|
|
4
|
+
Copyright (c) 2026 Webpresso, Inc.
|
|
5
|
+
|
|
6
|
+
Acceptance
|
|
7
|
+
----------
|
|
8
|
+
|
|
9
|
+
By using the software, you agree to all of the terms and conditions below.
|
|
10
|
+
|
|
11
|
+
Copyright License
|
|
12
|
+
-----------------
|
|
13
|
+
|
|
14
|
+
The licensor grants you a non-exclusive, royalty-free, worldwide,
|
|
15
|
+
non-sublicensable, non-transferable license to use, copy, distribute, make
|
|
16
|
+
available, and prepare derivative works of the software, in each case subject
|
|
17
|
+
to the limitations and conditions below.
|
|
18
|
+
|
|
19
|
+
Limitations
|
|
20
|
+
-----------
|
|
21
|
+
|
|
22
|
+
You may not provide the software to third parties as a hosted or managed
|
|
23
|
+
service, where the service provides users with access to any substantial set of
|
|
24
|
+
the features or functionality of the software.
|
|
25
|
+
|
|
26
|
+
You may not move, change, disable, or circumvent the license key
|
|
27
|
+
functionality in the software, and you may not remove or obscure any
|
|
28
|
+
functionality in the software that is protected by the license key.
|
|
29
|
+
|
|
30
|
+
You may not alter, remove, or obscure any licensing, copyright, or other
|
|
31
|
+
notices of the licensor in the software. Any use of the licensor's trademarks
|
|
32
|
+
is subject to applicable law.
|
|
33
|
+
|
|
34
|
+
Patents
|
|
35
|
+
-------
|
|
36
|
+
|
|
37
|
+
The licensor grants you a license, under any patent claims the licensor can
|
|
38
|
+
license, or becomes able to license, to make, have made, use, sell, offer for
|
|
39
|
+
sale, import and have imported the software, in each case subject to the
|
|
40
|
+
limitations and conditions in this license. This license does not cover any
|
|
41
|
+
patent claims that you cause to be infringed by modifications or additions to
|
|
42
|
+
the software.
|
|
43
|
+
|
|
44
|
+
If you or your company make any written claim that the software infringes or
|
|
45
|
+
contributes to infringement of any patent, your patent license for the software
|
|
46
|
+
granted under these terms ends immediately. If your company makes such a claim,
|
|
47
|
+
your patent license ends immediately for work on behalf of your company.
|
|
48
|
+
|
|
49
|
+
Notices
|
|
50
|
+
-------
|
|
51
|
+
|
|
52
|
+
You must ensure that anyone who gets a copy of any part of the software from
|
|
53
|
+
you also gets a copy of these terms.
|
|
54
|
+
|
|
55
|
+
If you modify the software, you must include in any modified copies of the
|
|
56
|
+
software prominent notices stating that you have modified the software.
|
|
57
|
+
|
|
58
|
+
No Other Rights
|
|
59
|
+
---------------
|
|
60
|
+
|
|
61
|
+
These terms do not imply any licenses other than those expressly granted in
|
|
62
|
+
these terms.
|
|
63
|
+
|
|
64
|
+
Termination
|
|
65
|
+
-----------
|
|
66
|
+
|
|
67
|
+
If you use the software in violation of these terms, such use is not licensed,
|
|
68
|
+
and your licenses will automatically terminate. If the licensor provides you
|
|
69
|
+
with a notice of your violation, and you cease all violation of this license no
|
|
70
|
+
later than 30 days after you receive that notice, your licenses will be
|
|
71
|
+
reinstated retroactively. However, if you violate these terms after such
|
|
72
|
+
reinstatement, any additional violation of these terms will cause your licenses
|
|
73
|
+
to terminate automatically and permanently.
|
|
74
|
+
|
|
75
|
+
No Liability
|
|
76
|
+
------------
|
|
77
|
+
|
|
78
|
+
As far as the law allows, the software comes as is, without any warranty or
|
|
79
|
+
condition, and the licensor will not be liable to you for any damages arising
|
|
80
|
+
out of these terms or the use or nature of the software, under any kind of
|
|
81
|
+
legal claim.
|
|
82
|
+
|
|
83
|
+
Definitions
|
|
84
|
+
-----------
|
|
85
|
+
|
|
86
|
+
The licensor is the entity offering these terms, and the software is the
|
|
87
|
+
software the licensor makes available under these terms, including any portion
|
|
88
|
+
of it.
|
|
89
|
+
|
|
90
|
+
you refers to the individual or entity agreeing to these terms.
|
|
91
|
+
|
|
92
|
+
your company is any legal entity, sole proprietorship, or other kind of
|
|
93
|
+
organization that you work for, plus all organizations that have control over,
|
|
94
|
+
are under the control of, or are under common control with that organization.
|
|
95
|
+
control means ownership of substantially all the assets of an entity, or the
|
|
96
|
+
power to direct its management and policies by vote, contract, or otherwise.
|
|
97
|
+
Control can be direct or indirect.
|
|
98
|
+
|
|
99
|
+
your licenses are all the licenses granted to you for the software under these
|
|
100
|
+
terms.
|
|
101
|
+
|
|
102
|
+
use means anything you do with the software requiring one of your licenses.
|
|
103
|
+
|
|
104
|
+
trademark means trademarks, service marks, and similar rights.
|
package/README.md
CHANGED
|
@@ -1,3 +1,84 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @webpresso/forms
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Contact-form submission handling for Workers: field validation and sanitization, captcha gating, internal + confirmation email dispatch, and redirect responses with a status vocabulary. Provider-neutral root surface; the captcha vendor is confined to a single adapter subpath.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
vp add @webpresso/forms
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
The public package names and release policy are defined by `.webpresso/package-surface.json` in the framework repository.
|
|
12
|
+
|
|
13
|
+
## Config shape
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import type { ContactFormConfig } from '@webpresso/forms'
|
|
17
|
+
|
|
18
|
+
const config: ContactFormConfig = {
|
|
19
|
+
siteName: 'Example',
|
|
20
|
+
from: 'no-reply@example.com',
|
|
21
|
+
internalRecipients: ['team@example.com'],
|
|
22
|
+
fields: [
|
|
23
|
+
{ name: 'name', label: 'Name', type: 'text', required: true },
|
|
24
|
+
{ name: 'email', label: 'Email', type: 'email', required: true },
|
|
25
|
+
{ name: 'message', label: 'Message', type: 'textarea', required: true },
|
|
26
|
+
],
|
|
27
|
+
customerEmailField: 'email',
|
|
28
|
+
customerNameField: 'name',
|
|
29
|
+
redirectPath: '/contact',
|
|
30
|
+
subjects: { internal: 'New contact request', confirmation: 'We received your message' },
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Field types are `text | email | textarea | tel`; values are control-character-stripped, whitespace-collapsed, length-capped (`maxLength`, default 2000), and email-typed fields are lowercased. Required fields and the customer email field are validated before any email is sent.
|
|
35
|
+
|
|
36
|
+
## Usage
|
|
37
|
+
|
|
38
|
+
Mount the handler in a Worker with an email binding and a captcha verifier:
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
import { createContactFormHandler } from '@webpresso/forms'
|
|
42
|
+
import { createTurnstileVerifier } from '@webpresso/forms/adapters/turnstile'
|
|
43
|
+
|
|
44
|
+
const contact = createContactFormHandler(config, {
|
|
45
|
+
captcha: createTurnstileVerifier({ secret: env.TURNSTILE_SECRET }),
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
export default {
|
|
49
|
+
fetch: (request, env) => {
|
|
50
|
+
const url = new URL(request.url)
|
|
51
|
+
if (url.pathname === '/api/contact' && request.method === 'POST') {
|
|
52
|
+
return contact(request, { email: env.SEND_EMAIL })
|
|
53
|
+
}
|
|
54
|
+
return new Response('Not found', { status: 404 })
|
|
55
|
+
},
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
`context.email` is an `EmailBinding` (`send(message)`); when it is absent the handler redirects with the `email` status instead of sending. A custom `CaptchaVerifier` can replace the adapter at the neutral `captcha` option.
|
|
60
|
+
|
|
61
|
+
## Redirect status vocabulary
|
|
62
|
+
|
|
63
|
+
The handler answers with a `303` redirect to the form path (or the form's hidden `redirect` field when present) carrying a `contact` query parameter:
|
|
64
|
+
|
|
65
|
+
| Value | Meaning |
|
|
66
|
+
| --------- | --------------------------------------------- |
|
|
67
|
+
| `success` | Validation, captcha, and both emails accepted |
|
|
68
|
+
| `invalid` | Wrong method, unparsable form, or bad fields |
|
|
69
|
+
| `captcha` | Captcha failed or the verifier errored |
|
|
70
|
+
| `email` | No email binding, or the internal send failed |
|
|
71
|
+
|
|
72
|
+
The confirmation email is best-effort: its failure is logged, never fails the request.
|
|
73
|
+
|
|
74
|
+
## Adapter-confined naming
|
|
75
|
+
|
|
76
|
+
The root surface stays provider-neutral: vendor names appear only where the adapter subpath is documented. `@webpresso/forms/adapters/turnstile` is the single subpath naming the captcha vendor, its siteverify endpoint, and its form field name — mirroring how the runtime documents its auth adapter imports. Import the adapter explicitly; nothing vendor-specific is re-exported from the root.
|
|
77
|
+
|
|
78
|
+
## Provenance
|
|
79
|
+
|
|
80
|
+
Logic ported from the in-org public `ozby/cloudflare-utils` repository, pinned at commit `dd4cb995c8b786f30b5b2993cd40b05e2a73bb56`. The source repository carries no LICENSE file and the module is authored in-org by the rights holder, so this port is licensed Elastic-2.0 as part of the framework inventory.
|
|
81
|
+
|
|
82
|
+
## License
|
|
83
|
+
|
|
84
|
+
Elastic-2.0
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { sanitizeContactValue } from '../contact-form.js';
|
|
2
|
+
// Vendor-confined constants: the Turnstile siteverify endpoint and form field
|
|
3
|
+
// name appear nowhere else in the package — the root surface stays
|
|
4
|
+
// provider-neutral.
|
|
5
|
+
const SITEVERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
|
|
6
|
+
const TOKEN_FIELD = 'cf-turnstile-response';
|
|
7
|
+
function errorCodes(value) {
|
|
8
|
+
if (!Array.isArray(value))
|
|
9
|
+
return [];
|
|
10
|
+
return value.filter((item) => typeof item === 'string');
|
|
11
|
+
}
|
|
12
|
+
export function createTurnstileVerifier(options) {
|
|
13
|
+
const fetcher = options.fetcher ?? fetch;
|
|
14
|
+
return {
|
|
15
|
+
async verify({ request, data }) {
|
|
16
|
+
const token = sanitizeContactValue(data.get(TOKEN_FIELD));
|
|
17
|
+
if (options.secret.length === 0 || token.length === 0) {
|
|
18
|
+
return { ok: false, codes: ['missing-input'] };
|
|
19
|
+
}
|
|
20
|
+
try {
|
|
21
|
+
const body = { secret: options.secret, response: token };
|
|
22
|
+
const remoteIp = request.headers.get('CF-Connecting-IP') ?? request.headers.get('X-Forwarded-For');
|
|
23
|
+
if (remoteIp != null && remoteIp.length > 0)
|
|
24
|
+
body.remoteip = remoteIp;
|
|
25
|
+
const response = await fetcher(SITEVERIFY_URL, {
|
|
26
|
+
method: 'POST',
|
|
27
|
+
headers: { 'content-type': 'application/json' },
|
|
28
|
+
body: JSON.stringify(body),
|
|
29
|
+
});
|
|
30
|
+
const result = (await response.json());
|
|
31
|
+
if (result.success === true)
|
|
32
|
+
return { ok: true };
|
|
33
|
+
return { ok: false, codes: errorCodes(result['error-codes']) };
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return { ok: false, codes: ['internal-error'] };
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
export type ContactFieldType = 'text' | 'email' | 'textarea' | 'tel';
|
|
2
|
+
export type ContactFieldConfig = {
|
|
3
|
+
readonly name: string;
|
|
4
|
+
readonly label: string;
|
|
5
|
+
readonly required?: boolean;
|
|
6
|
+
readonly type?: ContactFieldType;
|
|
7
|
+
readonly maxLength?: number;
|
|
8
|
+
};
|
|
9
|
+
export type EmailAddress = string | {
|
|
10
|
+
email: string;
|
|
11
|
+
name?: string;
|
|
12
|
+
};
|
|
13
|
+
export type EmailMessageBuilder = {
|
|
14
|
+
readonly to: EmailAddress | readonly EmailAddress[];
|
|
15
|
+
readonly from: EmailAddress;
|
|
16
|
+
readonly subject: string;
|
|
17
|
+
readonly html?: string;
|
|
18
|
+
readonly text?: string;
|
|
19
|
+
readonly cc?: EmailAddress | readonly EmailAddress[];
|
|
20
|
+
readonly bcc?: EmailAddress | readonly EmailAddress[];
|
|
21
|
+
readonly replyTo?: EmailAddress;
|
|
22
|
+
readonly headers?: Record<string, string>;
|
|
23
|
+
};
|
|
24
|
+
export type EmailBinding = {
|
|
25
|
+
send(message: EmailMessageBuilder): Promise<unknown>;
|
|
26
|
+
};
|
|
27
|
+
export type ContactFormContext = {
|
|
28
|
+
readonly email?: EmailBinding;
|
|
29
|
+
};
|
|
30
|
+
export type ContactFormConfig = {
|
|
31
|
+
readonly siteName: string;
|
|
32
|
+
readonly from: string;
|
|
33
|
+
readonly internalRecipients: readonly string[];
|
|
34
|
+
readonly fields: readonly ContactFieldConfig[];
|
|
35
|
+
readonly customerEmailField: string;
|
|
36
|
+
readonly customerNameField?: string;
|
|
37
|
+
readonly redirectPath: string;
|
|
38
|
+
readonly subjects: {
|
|
39
|
+
readonly internal: string;
|
|
40
|
+
readonly confirmation: string;
|
|
41
|
+
};
|
|
42
|
+
readonly internalIntro?: string;
|
|
43
|
+
readonly confirmationText?: (values: Record<string, string>) => string;
|
|
44
|
+
};
|
|
45
|
+
export type ContactValidationResult = {
|
|
46
|
+
readonly ok: true;
|
|
47
|
+
readonly values: Record<string, string>;
|
|
48
|
+
} | {
|
|
49
|
+
readonly ok: false;
|
|
50
|
+
readonly error: 'invalid_fields';
|
|
51
|
+
readonly fields: readonly string[];
|
|
52
|
+
};
|
|
53
|
+
export type CaptchaVerification = {
|
|
54
|
+
readonly ok: true;
|
|
55
|
+
} | {
|
|
56
|
+
readonly ok: false;
|
|
57
|
+
readonly codes: readonly string[];
|
|
58
|
+
};
|
|
59
|
+
export type CaptchaVerifier = {
|
|
60
|
+
verify(input: {
|
|
61
|
+
readonly request: Request;
|
|
62
|
+
readonly data: FormData;
|
|
63
|
+
}): Promise<CaptchaVerification>;
|
|
64
|
+
};
|
|
65
|
+
export type ContactFormHandlerOptions = {
|
|
66
|
+
readonly captcha: CaptchaVerifier;
|
|
67
|
+
readonly logger?: Pick<Console, 'warn'>;
|
|
68
|
+
};
|
|
69
|
+
export declare function sanitizeContactValue(value: FormDataEntryValue | null, field?: ContactFieldConfig): string;
|
|
70
|
+
export declare function validateContactForm(config: ContactFormConfig, data: FormData): ContactValidationResult;
|
|
71
|
+
export declare function buildInternalContactEmail(config: ContactFormConfig, values: Record<string, string>): EmailMessageBuilder;
|
|
72
|
+
export declare function buildContactConfirmationEmail(config: ContactFormConfig, values: Record<string, string>): EmailMessageBuilder;
|
|
73
|
+
export declare function createContactFormHandler(config: ContactFormConfig, options: ContactFormHandlerOptions): (request: Request, context: ContactFormContext) => Promise<Response>;
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
const DEFAULT_MAX_LENGTH = 2_000;
|
|
2
|
+
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/u;
|
|
3
|
+
// Strip C0 controls (keeping \t and \n) plus DEL by codepoint, not by a regex
|
|
4
|
+
// literal: `no-control-regex` rejects the literal form outright, and the
|
|
5
|
+
// behaviour is identical — tab and newline survive for whitespace handling.
|
|
6
|
+
const CONTROL_FREE_PATTERN = new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(8)}${String.fromCharCode(11)}${String.fromCharCode(12)}${String.fromCharCode(14)}-${String.fromCharCode(31)}${String.fromCharCode(127)}]`, 'gu');
|
|
7
|
+
function collapseInlineWhitespace(value) {
|
|
8
|
+
return value.replace(/[\t ]+/gu, ' ');
|
|
9
|
+
}
|
|
10
|
+
export function sanitizeContactValue(value, field) {
|
|
11
|
+
if (typeof value !== 'string')
|
|
12
|
+
return '';
|
|
13
|
+
const withoutControls = value.replace(CONTROL_FREE_PATTERN, '');
|
|
14
|
+
const normalized = field?.type === 'textarea'
|
|
15
|
+
? withoutControls
|
|
16
|
+
.replace(/\r\n?/gu, '\n')
|
|
17
|
+
.split('\n')
|
|
18
|
+
.map((line) => collapseInlineWhitespace(line).trim())
|
|
19
|
+
.join('\n')
|
|
20
|
+
: collapseInlineWhitespace(withoutControls.replace(/[\r\n]+/gu, ' '));
|
|
21
|
+
const trimmed = normalized.trim();
|
|
22
|
+
const capped = trimmed.slice(0, field?.maxLength ?? DEFAULT_MAX_LENGTH);
|
|
23
|
+
return field?.type === 'email' ? capped.toLowerCase() : capped;
|
|
24
|
+
}
|
|
25
|
+
export function validateContactForm(config, data) {
|
|
26
|
+
const invalid = [];
|
|
27
|
+
const values = {};
|
|
28
|
+
for (const field of config.fields) {
|
|
29
|
+
const value = sanitizeContactValue(data.get(field.name), field);
|
|
30
|
+
values[field.name] = value;
|
|
31
|
+
if (field.required === true && value.length === 0)
|
|
32
|
+
invalid.push(field.name);
|
|
33
|
+
if (field.type === 'email' && value.length > 0 && !EMAIL_PATTERN.test(value))
|
|
34
|
+
invalid.push(field.name);
|
|
35
|
+
}
|
|
36
|
+
const customerEmail = values[config.customerEmailField] ?? '';
|
|
37
|
+
if (customerEmail.length === 0 || !EMAIL_PATTERN.test(customerEmail)) {
|
|
38
|
+
if (!invalid.includes(config.customerEmailField))
|
|
39
|
+
invalid.push(config.customerEmailField);
|
|
40
|
+
}
|
|
41
|
+
return invalid.length > 0
|
|
42
|
+
? { ok: false, error: 'invalid_fields', fields: invalid }
|
|
43
|
+
: { ok: true, values };
|
|
44
|
+
}
|
|
45
|
+
function escapeHtml(value) {
|
|
46
|
+
return value
|
|
47
|
+
.replace(/&/gu, '&')
|
|
48
|
+
.replace(/</gu, '<')
|
|
49
|
+
.replace(/>/gu, '>')
|
|
50
|
+
.replace(/"/gu, '"')
|
|
51
|
+
.replace(/'/gu, ''');
|
|
52
|
+
}
|
|
53
|
+
function fieldText(config, values) {
|
|
54
|
+
return config.fields.map((field) => `${field.label}: ${values[field.name] ?? ''}`).join('\n');
|
|
55
|
+
}
|
|
56
|
+
export function buildInternalContactEmail(config, values) {
|
|
57
|
+
const intro = config.internalIntro ?? `New contact form submission from ${config.siteName}.`;
|
|
58
|
+
const rows = config.fields
|
|
59
|
+
.map((field) => `<tr><th align="left" valign="top">${escapeHtml(field.label)}</th><td>${escapeHtml(values[field.name] ?? '').replace(/\n/gu, '<br>')}</td></tr>`)
|
|
60
|
+
.join('');
|
|
61
|
+
return {
|
|
62
|
+
to: [...config.internalRecipients],
|
|
63
|
+
from: config.from,
|
|
64
|
+
replyTo: values[config.customerEmailField],
|
|
65
|
+
subject: config.subjects.internal,
|
|
66
|
+
text: `${intro}\n\n${fieldText(config, values)}`,
|
|
67
|
+
html: `<p>${escapeHtml(intro)}</p><table>${rows}</table>`,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
export function buildContactConfirmationEmail(config, values) {
|
|
71
|
+
const customerName = config.customerNameField ? values[config.customerNameField] : '';
|
|
72
|
+
const greeting = customerName ? `Hi ${customerName},` : 'Hello,';
|
|
73
|
+
const text = config.confirmationText?.(values) ??
|
|
74
|
+
[
|
|
75
|
+
greeting,
|
|
76
|
+
'',
|
|
77
|
+
`We received your message to ${config.siteName}.`,
|
|
78
|
+
'We will review it and reply as soon as possible.',
|
|
79
|
+
].join('\n');
|
|
80
|
+
return {
|
|
81
|
+
to: values[config.customerEmailField] ?? '',
|
|
82
|
+
from: config.from,
|
|
83
|
+
replyTo: config.from,
|
|
84
|
+
subject: config.subjects.confirmation,
|
|
85
|
+
text,
|
|
86
|
+
html: `<p>${escapeHtml(greeting)}</p><p>We received your message to ${escapeHtml(config.siteName)}. We will review it and reply as soon as possible.</p>`,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
function redirectWithStatus(path, status) {
|
|
90
|
+
const url = new URL(path, 'https://local.invalid');
|
|
91
|
+
url.searchParams.set('contact', status);
|
|
92
|
+
return new Response(null, {
|
|
93
|
+
status: 303,
|
|
94
|
+
headers: { location: `${url.pathname}${url.search}${url.hash}` },
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Decides whether a decoded `_redirect` value is safe to send back as a
|
|
99
|
+
* `Location` target. Hardened beyond the source (which accepted any value
|
|
100
|
+
* starting with `/` and not `//`):
|
|
101
|
+
*
|
|
102
|
+
* - The value must start with `/` and its second character must be neither
|
|
103
|
+
* `/` nor `\`. The WHATWG URL parser reads `/\` as `//`, so `/\evil.com`
|
|
104
|
+
* would otherwise parse as a protocol-relative reference to evil.com.
|
|
105
|
+
* - The value must contain no `\` and no control character (U+0000-U+001F or
|
|
106
|
+
* U+007F) anywhere. The WHATWG URL parser strips tab/LF/CR before parsing,
|
|
107
|
+
* so a decoded value carrying a literal tab or LF next to a slash can
|
|
108
|
+
* re-form a protocol-relative reference.
|
|
109
|
+
*
|
|
110
|
+
* The check runs on the raw decoded field value: whitespace normalization in
|
|
111
|
+
* `sanitizeContactValue` would erase the control bytes before they could be
|
|
112
|
+
* rejected. Any rejected target falls back to `config.redirectPath`.
|
|
113
|
+
*/
|
|
114
|
+
function isSafeRedirectTarget(target) {
|
|
115
|
+
if (!target.startsWith('/'))
|
|
116
|
+
return false;
|
|
117
|
+
const second = target.charCodeAt(1);
|
|
118
|
+
if (second === 0x2f /* / */ || second === 0x5c /* \ */)
|
|
119
|
+
return false;
|
|
120
|
+
for (let index = 0; index < target.length; index++) {
|
|
121
|
+
const code = target.charCodeAt(index);
|
|
122
|
+
if (code === 0x5c /* \ */)
|
|
123
|
+
return false;
|
|
124
|
+
if (code <= 0x1f || code === 0x7f)
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
return true;
|
|
128
|
+
}
|
|
129
|
+
function redirectTarget(config, data) {
|
|
130
|
+
const raw = data.get('_redirect');
|
|
131
|
+
if (typeof raw === 'string' && isSafeRedirectTarget(raw))
|
|
132
|
+
return sanitizeContactValue(raw);
|
|
133
|
+
return config.redirectPath;
|
|
134
|
+
}
|
|
135
|
+
function errorCode(error) {
|
|
136
|
+
if (typeof error === 'object' &&
|
|
137
|
+
error !== null &&
|
|
138
|
+
'code' in error &&
|
|
139
|
+
typeof error.code === 'string')
|
|
140
|
+
return error.code;
|
|
141
|
+
return 'unknown';
|
|
142
|
+
}
|
|
143
|
+
export function createContactFormHandler(config, options) {
|
|
144
|
+
return async (request, context) => {
|
|
145
|
+
if (request.method !== 'POST')
|
|
146
|
+
return redirectWithStatus(config.redirectPath, 'invalid');
|
|
147
|
+
let data;
|
|
148
|
+
try {
|
|
149
|
+
data = await request.formData();
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
return redirectWithStatus(config.redirectPath, 'invalid');
|
|
153
|
+
}
|
|
154
|
+
const target = redirectTarget(config, data);
|
|
155
|
+
const validation = validateContactForm(config, data);
|
|
156
|
+
if (!validation.ok)
|
|
157
|
+
return redirectWithStatus(target, 'invalid');
|
|
158
|
+
let verification;
|
|
159
|
+
try {
|
|
160
|
+
verification = await options.captcha.verify({ request, data });
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
return redirectWithStatus(target, 'captcha');
|
|
164
|
+
}
|
|
165
|
+
if (!verification.ok)
|
|
166
|
+
return redirectWithStatus(target, 'captcha');
|
|
167
|
+
if (context.email == null)
|
|
168
|
+
return redirectWithStatus(target, 'email');
|
|
169
|
+
try {
|
|
170
|
+
await context.email.send(buildInternalContactEmail(config, validation.values));
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
return redirectWithStatus(target, 'email');
|
|
174
|
+
}
|
|
175
|
+
try {
|
|
176
|
+
await context.email.send(buildContactConfirmationEmail(config, validation.values));
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
options.logger?.warn('contact_confirmation_failed', {
|
|
180
|
+
code: errorCode(error),
|
|
181
|
+
site: config.siteName,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
return redirectWithStatus(target, 'success');
|
|
185
|
+
};
|
|
186
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './contact-form.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './contact-form.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpresso/forms",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Webpresso drop-in form components: a provider-neutral contact-form handler for edge workers.",
|
|
5
|
+
"license": "Elastic-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/webpresso/framework.git",
|
|
9
|
+
"directory": "packages/forms"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist",
|
|
13
|
+
"package.json"
|
|
14
|
+
],
|
|
15
|
+
"type": "module",
|
|
16
|
+
"sideEffects": false,
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"default": "./dist/index.js"
|
|
21
|
+
},
|
|
22
|
+
"./adapters/turnstile": {
|
|
23
|
+
"types": "./dist/adapters/turnstile.d.ts",
|
|
24
|
+
"default": "./dist/adapters/turnstile.js"
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public",
|
|
29
|
+
"provenance": true
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@mergifyio/vitest": "^2026.10.5",
|
|
33
|
+
"@repo/build-tools": "0.1.0",
|
|
34
|
+
"@types/node": "^25.6.2",
|
|
35
|
+
"@webpresso/app-config": "0.5.2",
|
|
36
|
+
"publint": "^0.3.18",
|
|
37
|
+
"typescript": "^7.0.2",
|
|
38
|
+
"vitest": "^4.1.5"
|
|
39
|
+
},
|
|
40
|
+
"engines": {
|
|
41
|
+
"node": ">=24"
|
|
42
|
+
},
|
|
43
|
+
"scripts": {
|
|
44
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json && add-js-extensions dist",
|
|
45
|
+
"typecheck": "tsc --noEmit -p tsconfig.build.json",
|
|
46
|
+
"test": "vitest run",
|
|
47
|
+
"lint:pkg": "publint --pack false"
|
|
48
|
+
}
|
|
6
49
|
}
|