@takuhon/contact 0.24.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 +202 -0
- package/NOTICE +7 -0
- package/README.md +32 -0
- package/dist/contact-widget.css +2 -0
- package/dist/contact-widget.js +1 -0
- package/dist/index.d.ts +159 -0
- package/dist/index.js +134 -0
- package/dist/index.js.map +1 -0
- package/package.json +51 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Takuhon contributors
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# @takuhon/contact
|
|
2
|
+
|
|
3
|
+
Portable, framework-agnostic core for a lightweight contact form — input
|
|
4
|
+
validation, a stateless request pipeline, and the challenge/email transport
|
|
5
|
+
seams an adapter fills.
|
|
6
|
+
|
|
7
|
+
> **Status:** early skeleton (private, unpublished). Host wiring (e.g. Cloudflare
|
|
8
|
+
> Turnstile + `send_email`) lives in the adapters. This package carries no
|
|
9
|
+
> Cloudflare, Node, or framework dependency, so the same core runs anywhere.
|
|
10
|
+
|
|
11
|
+
## What this package is
|
|
12
|
+
|
|
13
|
+
- **`handleContact(request, deps)`** — a Web-standard `(Request) => Response`
|
|
14
|
+
pipeline: method / content-type / origin guards, a size-bounded JSON parse,
|
|
15
|
+
validation, challenge verification, then delivery via an `EmailTransport`. It
|
|
16
|
+
is stateless: no database, no admin UI, no auto-reply.
|
|
17
|
+
- **`validateSubmission(raw, config)`** — strict, pure validation. The email
|
|
18
|
+
rules reject any CR/LF and only accept a single address, so the value is safe
|
|
19
|
+
to place in a `Reply-To` header (no email header injection). Length limits and
|
|
20
|
+
a honeypot are enforced too.
|
|
21
|
+
- **`ChallengeVerifier` / `EmailTransport`** — the two interfaces an adapter
|
|
22
|
+
implements (e.g. a Turnstile verifier and a `send_email` transport).
|
|
23
|
+
|
|
24
|
+
## Design
|
|
25
|
+
|
|
26
|
+
See the design notes for the full plan (dogfood on two sites, then publish for
|
|
27
|
+
reuse). The deliberate non-goals are realtime chat, storage, an admin UI, and
|
|
28
|
+
auto-replies to the visitor; the received inbox is the history.
|
|
29
|
+
|
|
30
|
+
## License
|
|
31
|
+
|
|
32
|
+
Apache-2.0 (see [LICENSE](./LICENSE) and [NOTICE](./NOTICE)).
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
.tkc-root{z-index:2147483000;font-family:system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Noto Sans,Ubuntu,Cantarell,Helvetica Neue,sans-serif;font-size:14px;line-height:1.5;position:fixed;bottom:1rem;right:1rem}.tkc-launcher{color:#fff;cursor:pointer;background:#1e1888;border:none;border-radius:50%;justify-content:center;align-items:center;width:3.5rem;height:3.5rem;padding:0;transition:transform .15s,background .15s;display:inline-flex;box-shadow:0 6px 20px #00000038}.tkc-launcher:hover{background:#2a23a8;transform:scale(1.06)}.tkc-launcher:focus-visible{outline-offset:2px;outline:2px solid #818cf8}.tkc-send:focus-visible{outline-offset:2px;outline:2px solid #818cf8}.tkc-input:focus-visible{outline-offset:2px;outline:2px solid #818cf8}.tkc-close:focus-visible{outline-offset:2px;outline:2px solid #818cf8}.tkc-panel{color:#1f2430;background:#fff;border-radius:14px;flex-direction:column;width:min(22rem,100vw - 2rem);height:min(30rem,100vh - 4rem);display:flex;overflow:hidden;box-shadow:0 12px 40px #00000038}.tkc-header{color:#fff;background:#1e1888;justify-content:space-between;align-items:center;padding:.75rem 1rem;font-weight:600;display:flex}.tkc-close{color:inherit;cursor:pointer;background:0 0;border:none;padding:0 .25rem;font-size:1.3rem;line-height:1}.tkc-log{background:#f6f7fb;flex-direction:column;flex:1;gap:.5rem;padding:.9rem;display:flex;overflow-y:auto}.tkc-msg{white-space:pre-wrap;word-break:break-word;border-radius:12px;max-width:85%;padding:.5rem .75rem}.tkc-msg-bot{background:#fff;border:1px solid #e4e6ef;align-self:flex-start}.tkc-msg-user{color:#fff;background:#1e1888;align-self:flex-end}.tkc-turnstile{padding:0 .9rem}.tkc-turnstile:empty{display:none}.tkc-form{border-top:1px solid #e4e6ef;gap:.5rem;padding:.75rem;display:flex}.tkc-input{min-width:0;font:inherit;border:1px solid #c8ccda;border-radius:8px;flex:1;padding:.55rem .7rem}.tkc-honeypot{opacity:0;width:1px;height:1px;position:absolute;left:-9999px}.tkc-send{color:#fff;font:inherit;cursor:pointer;background:#1e1888;border:none;border-radius:8px;padding:.55rem 1rem;font-weight:600}.tkc-send:disabled{opacity:.55;cursor:default}.tkc-hidden{display:none!important}@media (prefers-color-scheme:dark){.tkc-panel{color:#e6e8f0;background:#1a1d29}.tkc-log{background:#11131c}.tkc-msg-bot{color:#e6e8f0;background:#232737;border-color:#2f3550}.tkc-form{border-top-color:#2f3550}.tkc-input{color:#e6e8f0;background:#232737;border-color:#3a4060}}
|
|
2
|
+
/*$vite$:1*/
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var TakuhonContact=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=[`ja`,`en`];function n(e){if(typeof e==`string`){let n=e.trim().toLowerCase().split(`-`)[0];if(n!==void 0&&t.includes(n))return n}return`ja`}var r=`/api/contact`;function i(e){let t=typeof e.endpoint==`string`&&e.endpoint.trim()!==``?e.endpoint.trim():r;return{siteKey:e.siteKey,endpoint:t,locale:n(e.locale??e.lang),...e.pageUrl?{pageUrl:e.pageUrl}:{}}}var a={ja:{launcher:`お問い合わせ`,title:`お問い合わせ`,close:`閉じる`,greeting:`こんにちは。お問い合わせ内容をお送りください。確認後、メールで返信します。`,askEmail:`まず、返信先のメールアドレスを入力してください。`,askMessage:`ありがとうございます。次にお問い合わせ内容を入力してください。`,confirm:`送信してよろしいですか?`,send:`送信`,sending:`送信中…`,verifying:`確認中…`,done:`お問い合わせを受け付けました。確認後、メールで返信します。`,retry:`もう一度送信する`,challengePrompt:`送信前に確認にお答えください。`,emailPlaceholder:`you@example.com`,messagePlaceholder:`お問い合わせ内容`,errorEmail:`メールアドレスの形式が正しくないようです。`,errorChallenge:`確認に失敗しました。もう一度お試しください。`,errorGeneric:`送信に失敗しました。時間をおいて再度お試しください。`},en:{launcher:`Contact`,title:`Contact`,close:`Close`,greeting:`Hi! Send your question below and we'll reply by email.`,askEmail:`First, what email address should we reply to?`,askMessage:`Thanks! Now, what would you like to ask?`,confirm:`Ready to send?`,send:`Send`,sending:`Sending…`,verifying:`Verifying…`,done:`Got it — we'll review your message and reply by email.`,retry:`Try again`,challengePrompt:`Please complete the check before sending.`,emailPlaceholder:`you@example.com`,messagePlaceholder:`Your message`,errorEmail:`That email address doesn't look right.`,errorChallenge:`Verification failed. Please try again.`,errorGeneric:`Something went wrong. Please try again later.`}};function o(e,t){return a[e][t]}function s(e){return{email:e.email,message:e.message,locale:e.locale,token:e.token,hp:e.honeypot,...e.pageUrl?{pageUrl:e.pageUrl}:{}}}function c(e){switch(e){case`email_invalid`:case`email_missing`:case`email_too_long`:return`errorEmail`;case`challenge_failed`:return`errorChallenge`;default:return`errorGeneric`}}function l(e){"@babel/helpers - typeof";return l=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},l(e)}function u(e,t){if(l(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(l(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function d(e){var t=u(e,`string`);return l(t)==`symbol`?t:t+``}function f(e,t,n){return(t=d(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var p=`https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit`;function m(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.trim())}function h(){return globalThis.turnstile}var g;function _(){let e=h();return e?Promise.resolve(e):g||(g=new Promise((e,t)=>{let n=document.createElement(`script`);n.src=p,n.async=!0,n.addEventListener(`load`,()=>{let n=h();n?e(n):t(Error(`turnstile unavailable after load`))}),n.addEventListener(`error`,()=>t(Error(`turnstile script failed to load`))),document.head.appendChild(n)}),g)}function v(e,t,n){let r=document.createElement(e);return t&&(r.className=t),n!==void 0&&(r.textContent=n),r}var y=`http://www.w3.org/2000/svg`;function b(){let e=document.createElementNS(y,`svg`);e.setAttribute(`viewBox`,`0 0 24 24`),e.setAttribute(`width`,`26`),e.setAttribute(`height`,`26`),e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`focusable`,`false`);let t=document.createElementNS(y,`path`);return t.setAttribute(`fill`,`currentColor`),t.setAttribute(`d`,`M12 3C6.5 3 2 6.58 2 11c0 2.4 1.32 4.56 3.4 6.04L5 21l3.9-2.05c.98.26 2.02.4 3.1.4 5.5 0 10-3.58 10-8s-4.5-8-10-8z`),e.appendChild(t),e}var x=class{constructor(e){f(this,`cfg`,void 0),f(this,`state`,void 0),f(this,`step`,`email`),f(this,`opened`,!1),f(this,`greeted`,!1),f(this,`turnstileRendered`,!1),f(this,`pendingSubmit`,!1),f(this,`root`,void 0),f(this,`launcher`,void 0),f(this,`panel`,void 0),f(this,`log`,void 0),f(this,`turnstileHost`,void 0),f(this,`form`,void 0),f(this,`input`,void 0),f(this,`honeypot`,void 0),f(this,`send`,void 0),this.cfg=i(e),this.state={email:``,message:``,token:``,honeypot:``,locale:this.cfg.locale,...this.cfg.pageUrl?{pageUrl:this.cfg.pageUrl}:{}}}tr(e){return o(this.cfg.locale,e)}mount(e=document.body){this.root=v(`div`,`tkc-root`),this.launcher=v(`button`,`tkc-launcher`),this.launcher.type=`button`,this.launcher.setAttribute(`aria-haspopup`,`dialog`),this.launcher.setAttribute(`aria-label`,this.tr(`launcher`)),this.launcher.append(b()),this.launcher.addEventListener(`click`,()=>this.open()),this.panel=v(`div`,`tkc-panel tkc-hidden`),this.panel.setAttribute(`role`,`dialog`),this.panel.setAttribute(`aria-label`,this.tr(`title`));let t=v(`div`,`tkc-header`);t.append(v(`span`,void 0,this.tr(`title`)));let n=v(`button`,`tkc-close`,`×`);n.type=`button`,n.setAttribute(`aria-label`,this.tr(`close`)),n.addEventListener(`click`,()=>this.close()),t.append(n),this.log=v(`div`,`tkc-log`),this.log.setAttribute(`role`,`log`),this.log.setAttribute(`aria-live`,`polite`),this.turnstileHost=v(`div`,`tkc-turnstile`),this.form=v(`form`,`tkc-form`),this.honeypot=v(`input`,`tkc-honeypot`),this.honeypot.type=`text`,this.honeypot.tabIndex=-1,this.honeypot.autocomplete=`off`,this.honeypot.setAttribute(`aria-hidden`,`true`),this.honeypot.name=`company`,this.input=v(`input`,`tkc-input`),this.input.type=`text`,this.input.autocomplete=`off`,this.input.setAttribute(`aria-label`,this.tr(`title`)),this.send=v(`button`,`tkc-send`,this.tr(`send`)),this.send.type=`submit`,this.form.append(this.honeypot,this.input,this.send),this.form.addEventListener(`submit`,e=>{e.preventDefault(),this.onSubmit()}),this.panel.append(t,this.log,this.turnstileHost,this.form),this.root.append(this.launcher,this.panel),e.append(this.root),document.addEventListener(`click`,e=>{if(!this.opened)return;let t=e.target;t instanceof Node&&this.root.contains(t)||this.close(!1)}),document.addEventListener(`keydown`,e=>{this.opened&&e.key===`Escape`&&this.close()})}open(){this.opened||(this.opened=!0,this.launcher.classList.add(`tkc-hidden`),this.panel.classList.remove(`tkc-hidden`),this.greeted||(this.greeted=!0,this.botSay(`greeting`),this.botSay(`askEmail`)),this.setStep(`email`),this.input.focus())}close(e=!0){this.opened=!1,this.panel.classList.add(`tkc-hidden`),this.launcher.classList.remove(`tkc-hidden`),e&&this.launcher.focus()}botSay(e){this.appendMessage(`tkc-msg-bot`,this.tr(e))}appendMessage(e,t){let n=v(`div`,`tkc-msg ${e}`,t);this.log.append(n),this.log.scrollTop=this.log.scrollHeight}setStep(e){this.step=e;let t=e===`email`||e===`message`;this.input.classList.toggle(`tkc-hidden`,!t),this.input.placeholder=e===`email`?this.tr(`emailPlaceholder`):this.tr(`messagePlaceholder`),this.input.value=``,this.send.disabled=e===`sending`,this.send.textContent=e===`sending`?this.tr(`sending`):this.tr(`send`),this.form.classList.toggle(`tkc-hidden`,e===`done`)}async onSubmit(){switch(this.step){case`email`:{let e=this.input.value.trim();if(!m(e)){this.botSay(`errorEmail`);return}this.state.email=e,this.appendMessage(`tkc-msg-user`,e),this.botSay(`askMessage`),this.setStep(`message`),this.input.focus();return}case`message`:{let e=this.input.value.trim();if(e===``)return;this.state.message=e,this.appendMessage(`tkc-msg-user`,e),this.botSay(`confirm`),this.setStep(`confirm`);return}case`confirm`:if(this.state.token){await this.submitInquiry();return}this.pendingSubmit=!0,this.send.disabled=!0,this.send.textContent=this.tr(`verifying`),this.renderTurnstile();return;default:return}}renderTurnstile(){this.turnstileRendered||(this.turnstileRendered=!0,_().then(e=>{e.render(this.turnstileHost,{sitekey:this.cfg.siteKey,theme:`auto`,language:this.cfg.locale,appearance:`interaction-only`,callback:e=>{this.state.token=e,this.pendingSubmit&&(this.pendingSubmit=!1,this.submitInquiry())},"expired-callback":()=>{this.state.token=``},"error-callback":()=>{this.state.token=``,this.pendingSubmit&&(this.botSay(`errorChallenge`),this.resetSendButton())}})}).catch(()=>{this.botSay(`errorGeneric`),this.resetSendButton()}))}resetSendButton(){this.pendingSubmit=!1,this.send.disabled=!1,this.send.textContent=this.tr(`retry`)}async submitInquiry(){this.state.honeypot=this.honeypot.value,this.setStep(`sending`),this.botSay(`sending`);let e=!1,t;try{let n=await fetch(this.cfg.endpoint,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(s(this.state))}),r=await n.json().catch(()=>null);e=n.ok&&r?.ok===!0,t=r?.error}catch{}if(e){this.botSay(`done`),this.setStep(`done`);return}this.botSay(c(t)),this.state.token=``;let n=h();n&&n.reset(),this.send.textContent=this.tr(`retry`),this.send.disabled=!1,this.step=`confirm`}};function S(e,t){let n=new x(e);return n.mount(t),n}function C(){let e=window.TAKUHON_CONTACT;e?.siteKey&&S({siteKey:e.siteKey,endpoint:e.endpoint,locale:e.locale,lang:e.lang??document.documentElement.lang,pageUrl:e.pageUrl??window.location.href})}return document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,C,{once:!0}):C(),e.mountContactWidget=S,e})({});
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core types for the takuhon contact-form pipeline.
|
|
3
|
+
*
|
|
4
|
+
* These are runtime-agnostic: no Cloudflare, Node, or framework imports. The
|
|
5
|
+
* two interfaces ({@link ChallengeVerifier}, {@link EmailTransport}) are the
|
|
6
|
+
* seams an adapter fills — e.g. a Cloudflare adapter provides a Turnstile
|
|
7
|
+
* verifier and a `send_email` transport. Keeping them abstract is what lets the
|
|
8
|
+
* same contact core run on any host (the takuhon "host anywhere" promise).
|
|
9
|
+
*/
|
|
10
|
+
/** Locales the widget and emails support. */
|
|
11
|
+
type ContactLocale = 'ja' | 'en';
|
|
12
|
+
/** Server-derived metadata attached to an inquiry for triage. Never trusted for security. */
|
|
13
|
+
interface InquiryMeta {
|
|
14
|
+
/** Visitor country (e.g. from `request.cf.country`), if known. */
|
|
15
|
+
country?: string;
|
|
16
|
+
/** Visitor IP (e.g. from `CF-Connecting-IP`), if known. */
|
|
17
|
+
ip?: string;
|
|
18
|
+
/** ISO 8601 timestamp the inquiry was received. */
|
|
19
|
+
receivedAt?: string;
|
|
20
|
+
}
|
|
21
|
+
/** A validated inquiry, ready to be delivered to the site owner. */
|
|
22
|
+
interface Inquiry {
|
|
23
|
+
/**
|
|
24
|
+
* The visitor's reply-to email address. Validated to be a single address
|
|
25
|
+
* with no CR/LF, so it is safe to place in a `Reply-To` header.
|
|
26
|
+
*/
|
|
27
|
+
email: string;
|
|
28
|
+
/** Free-text message body. Untrusted — render as plain text, escape for HTML. */
|
|
29
|
+
message: string;
|
|
30
|
+
/** UI locale the widget was shown in. */
|
|
31
|
+
locale: ContactLocale;
|
|
32
|
+
/** URL of the page the widget was embedded on, if the client provided it. */
|
|
33
|
+
pageUrl?: string;
|
|
34
|
+
/** The visitor's user agent, if available. */
|
|
35
|
+
userAgent?: string;
|
|
36
|
+
/** Best-effort, server-derived metadata. */
|
|
37
|
+
meta?: InquiryMeta;
|
|
38
|
+
}
|
|
39
|
+
/** Optional context passed to a {@link ChallengeVerifier}. */
|
|
40
|
+
interface ChallengeContext {
|
|
41
|
+
/** The visitor's IP, if the host can supply it (improves Turnstile scoring). */
|
|
42
|
+
remoteIp?: string;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Verifies an anti-abuse challenge token (e.g. Cloudflare Turnstile).
|
|
46
|
+
* Implementations MUST verify server-side; never trust a client claim of success.
|
|
47
|
+
*/
|
|
48
|
+
interface ChallengeVerifier {
|
|
49
|
+
verify(token: string, context?: ChallengeContext): Promise<boolean>;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Delivers a validated {@link Inquiry} to its destination — for the MVP, the
|
|
53
|
+
* site owner's verified inbox. Implementations set `From` / `Reply-To` / subject.
|
|
54
|
+
*/
|
|
55
|
+
interface EmailTransport {
|
|
56
|
+
send(inquiry: Inquiry): Promise<void>;
|
|
57
|
+
}
|
|
58
|
+
/** Tunable limits and policy for {@link validateSubmission} and the handler. */
|
|
59
|
+
interface ContactConfig {
|
|
60
|
+
/** Max message length in characters. Default 5000. */
|
|
61
|
+
maxMessageLength?: number;
|
|
62
|
+
/** Max email length in characters. Default 254 (RFC 5321 path limit). */
|
|
63
|
+
maxEmailLength?: number;
|
|
64
|
+
/** Max request body size in bytes. Default 16384 (16 KiB). */
|
|
65
|
+
maxBodyBytes?: number;
|
|
66
|
+
/**
|
|
67
|
+
* Allowed page origins for the Origin/Referer check (e.g.
|
|
68
|
+
* `['https://me.tak3.jp']`). Empty or omitted disables the check — use that
|
|
69
|
+
* for same-origin deployments where the host already constrains callers.
|
|
70
|
+
*/
|
|
71
|
+
allowedOrigins?: string[];
|
|
72
|
+
}
|
|
73
|
+
/** Dependencies injected into {@link handleContact}. */
|
|
74
|
+
interface ContactDeps {
|
|
75
|
+
/** Verifies the anti-abuse challenge (e.g. Turnstile). */
|
|
76
|
+
verifier: ChallengeVerifier;
|
|
77
|
+
/** Delivers the validated inquiry (e.g. via `send_email`). */
|
|
78
|
+
transport: EmailTransport;
|
|
79
|
+
/** Limits and policy. */
|
|
80
|
+
config?: ContactConfig;
|
|
81
|
+
/**
|
|
82
|
+
* Optional extractor for server-derived metadata (e.g. country/IP from
|
|
83
|
+
* `request.cf`). Runs after validation; its result is best-effort only.
|
|
84
|
+
*/
|
|
85
|
+
readMeta?: (request: Request) => InquiryMeta;
|
|
86
|
+
/** Clock injection for tests. Defaults to `() => new Date()`. */
|
|
87
|
+
now?: () => Date;
|
|
88
|
+
}
|
|
89
|
+
/** The raw, untrusted JSON body a widget POSTs. Every field is unknown. */
|
|
90
|
+
interface RawSubmission {
|
|
91
|
+
email?: unknown;
|
|
92
|
+
message?: unknown;
|
|
93
|
+
locale?: unknown;
|
|
94
|
+
pageUrl?: unknown;
|
|
95
|
+
/** Anti-bot honeypot: must be empty/absent for a human submission. */
|
|
96
|
+
hp?: unknown;
|
|
97
|
+
/** Challenge token, verified separately by a {@link ChallengeVerifier}. */
|
|
98
|
+
token?: unknown;
|
|
99
|
+
}
|
|
100
|
+
/** The clean subset extracted from a {@link RawSubmission} once validated. */
|
|
101
|
+
interface ValidSubmission {
|
|
102
|
+
email: string;
|
|
103
|
+
message: string;
|
|
104
|
+
locale: ContactLocale;
|
|
105
|
+
pageUrl?: string;
|
|
106
|
+
}
|
|
107
|
+
/** Machine-readable validation failure reasons. */
|
|
108
|
+
type ValidationError = 'email_missing' | 'email_invalid' | 'email_too_long' | 'message_missing' | 'message_too_long' | 'honeypot';
|
|
109
|
+
/** Result of {@link validateSubmission}. */
|
|
110
|
+
type ValidationResult = {
|
|
111
|
+
ok: true;
|
|
112
|
+
value: ValidSubmission;
|
|
113
|
+
} | {
|
|
114
|
+
ok: false;
|
|
115
|
+
error: ValidationError;
|
|
116
|
+
spam?: boolean;
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Framework-agnostic contact-form request handler.
|
|
121
|
+
*
|
|
122
|
+
* Pipeline: method / content-type / origin guards → size-bounded JSON parse →
|
|
123
|
+
* {@link validateSubmission} → challenge verification → {@link EmailTransport}
|
|
124
|
+
* delivery. Returns a small JSON {@link Response}. It is intentionally stateless
|
|
125
|
+
* (no storage) and mountable on any Web-standard runtime; adapters supply the
|
|
126
|
+
* verifier and transport.
|
|
127
|
+
*/
|
|
128
|
+
|
|
129
|
+
declare function handleContact(request: Request, deps: ContactDeps): Promise<Response>;
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Pure, synchronous validation for an untrusted contact submission.
|
|
133
|
+
*
|
|
134
|
+
* No I/O and no challenge check (that is the verifier's job). The email rules
|
|
135
|
+
* are deliberately strict — a single address with no CR/LF — so the result is
|
|
136
|
+
* safe to drop into a `Reply-To` header without enabling email header
|
|
137
|
+
* injection, the most important security invariant of this feature.
|
|
138
|
+
*/
|
|
139
|
+
|
|
140
|
+
/** Default limits, exported so adapters and the handler share one source of truth. */
|
|
141
|
+
declare const DEFAULT_MAX_MESSAGE_LENGTH = 5000;
|
|
142
|
+
declare const DEFAULT_MAX_EMAIL_LENGTH = 254;
|
|
143
|
+
declare const DEFAULT_MAX_BODY_BYTES = 16384;
|
|
144
|
+
/** True if the string contains a CR or LF (an email header-injection vector). */
|
|
145
|
+
declare function hasLineBreak(value: string): boolean;
|
|
146
|
+
/**
|
|
147
|
+
* Normalize an unknown locale claim to a supported {@link ContactLocale},
|
|
148
|
+
* defaulting to `'ja'` (the house default locale).
|
|
149
|
+
*/
|
|
150
|
+
declare function normalizeLocale(value: unknown): ContactLocale;
|
|
151
|
+
/**
|
|
152
|
+
* Validate a raw, untrusted submission into a {@link ValidationResult}.
|
|
153
|
+
*
|
|
154
|
+
* A tripped honeypot returns `{ ok: false, error: 'honeypot', spam: true }` so
|
|
155
|
+
* the caller can choose to feign success rather than reveal the trap.
|
|
156
|
+
*/
|
|
157
|
+
declare function validateSubmission(raw: RawSubmission, config?: ContactConfig): ValidationResult;
|
|
158
|
+
|
|
159
|
+
export { type ChallengeContext, type ChallengeVerifier, type ContactConfig, type ContactDeps, type ContactLocale, DEFAULT_MAX_BODY_BYTES, DEFAULT_MAX_EMAIL_LENGTH, DEFAULT_MAX_MESSAGE_LENGTH, type EmailTransport, type Inquiry, type InquiryMeta, type RawSubmission, type ValidSubmission, type ValidationError, type ValidationResult, handleContact, hasLineBreak, normalizeLocale, validateSubmission };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// src/validate.ts
|
|
2
|
+
var DEFAULT_MAX_MESSAGE_LENGTH = 5e3;
|
|
3
|
+
var DEFAULT_MAX_EMAIL_LENGTH = 254;
|
|
4
|
+
var DEFAULT_MAX_BODY_BYTES = 16384;
|
|
5
|
+
var SUPPORTED_LOCALES = ["ja", "en"];
|
|
6
|
+
var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
7
|
+
function hasLineBreak(value) {
|
|
8
|
+
return /[\r\n]/.test(value);
|
|
9
|
+
}
|
|
10
|
+
function normalizeLocale(value) {
|
|
11
|
+
if (typeof value === "string") {
|
|
12
|
+
const primary = value.trim().toLowerCase().split("-")[0];
|
|
13
|
+
if (primary !== void 0 && SUPPORTED_LOCALES.includes(primary)) {
|
|
14
|
+
return primary;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
return "ja";
|
|
18
|
+
}
|
|
19
|
+
function validateSubmission(raw, config) {
|
|
20
|
+
if (typeof raw.hp === "string" && raw.hp.trim() !== "") {
|
|
21
|
+
return { ok: false, error: "honeypot", spam: true };
|
|
22
|
+
}
|
|
23
|
+
const maxEmail = config?.maxEmailLength ?? DEFAULT_MAX_EMAIL_LENGTH;
|
|
24
|
+
const maxMessage = config?.maxMessageLength ?? DEFAULT_MAX_MESSAGE_LENGTH;
|
|
25
|
+
if (typeof raw.email !== "string") return { ok: false, error: "email_missing" };
|
|
26
|
+
const email = raw.email.trim();
|
|
27
|
+
if (email === "") return { ok: false, error: "email_missing" };
|
|
28
|
+
if (email.length > maxEmail) return { ok: false, error: "email_too_long" };
|
|
29
|
+
if (hasLineBreak(email) || !EMAIL_RE.test(email)) return { ok: false, error: "email_invalid" };
|
|
30
|
+
if (typeof raw.message !== "string") return { ok: false, error: "message_missing" };
|
|
31
|
+
const message = raw.message.trim();
|
|
32
|
+
if (message === "") return { ok: false, error: "message_missing" };
|
|
33
|
+
if (message.length > maxMessage) return { ok: false, error: "message_too_long" };
|
|
34
|
+
const pageUrl = typeof raw.pageUrl === "string" ? raw.pageUrl.trim() : "";
|
|
35
|
+
return {
|
|
36
|
+
ok: true,
|
|
37
|
+
value: {
|
|
38
|
+
email,
|
|
39
|
+
message,
|
|
40
|
+
locale: normalizeLocale(raw.locale),
|
|
41
|
+
...pageUrl !== "" ? { pageUrl } : {}
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// src/handler.ts
|
|
47
|
+
function json(status, body) {
|
|
48
|
+
return new Response(JSON.stringify(body), {
|
|
49
|
+
status,
|
|
50
|
+
headers: {
|
|
51
|
+
"content-type": "application/json; charset=utf-8",
|
|
52
|
+
"cache-control": "no-store"
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
function originAllowed(request, allowed) {
|
|
57
|
+
if (!allowed || allowed.length === 0) return true;
|
|
58
|
+
const origin = request.headers.get("origin");
|
|
59
|
+
if (origin) return allowed.includes(origin);
|
|
60
|
+
const referer = request.headers.get("referer");
|
|
61
|
+
if (referer) {
|
|
62
|
+
try {
|
|
63
|
+
return allowed.includes(new URL(referer).origin);
|
|
64
|
+
} catch {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
function remoteIp(request) {
|
|
71
|
+
const direct = request.headers.get("cf-connecting-ip");
|
|
72
|
+
if (direct) return direct;
|
|
73
|
+
const forwarded = request.headers.get("x-forwarded-for");
|
|
74
|
+
if (!forwarded) return void 0;
|
|
75
|
+
const first = forwarded.split(",")[0]?.trim();
|
|
76
|
+
return first !== void 0 && first !== "" ? first : void 0;
|
|
77
|
+
}
|
|
78
|
+
async function handleContact(request, deps) {
|
|
79
|
+
if (request.method !== "POST") return json(405, { ok: false, error: "method_not_allowed" });
|
|
80
|
+
const contentType = request.headers.get("content-type") ?? "";
|
|
81
|
+
if (!contentType.includes("application/json")) {
|
|
82
|
+
return json(415, { ok: false, error: "unsupported_media_type" });
|
|
83
|
+
}
|
|
84
|
+
if (!originAllowed(request, deps.config?.allowedOrigins)) {
|
|
85
|
+
return json(403, { ok: false, error: "forbidden_origin" });
|
|
86
|
+
}
|
|
87
|
+
const maxBytes = deps.config?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
|
|
88
|
+
const buffer = await request.arrayBuffer();
|
|
89
|
+
if (buffer.byteLength > maxBytes) return json(413, { ok: false, error: "payload_too_large" });
|
|
90
|
+
let raw;
|
|
91
|
+
try {
|
|
92
|
+
const parsed = JSON.parse(new TextDecoder().decode(buffer));
|
|
93
|
+
if (typeof parsed !== "object" || parsed === null) {
|
|
94
|
+
return json(400, { ok: false, error: "invalid_json" });
|
|
95
|
+
}
|
|
96
|
+
raw = parsed;
|
|
97
|
+
} catch {
|
|
98
|
+
return json(400, { ok: false, error: "invalid_json" });
|
|
99
|
+
}
|
|
100
|
+
const validation = validateSubmission(raw, deps.config);
|
|
101
|
+
if (!validation.ok) {
|
|
102
|
+
if (validation.spam) return json(200, { ok: true });
|
|
103
|
+
return json(422, { ok: false, error: validation.error });
|
|
104
|
+
}
|
|
105
|
+
const token = typeof raw.token === "string" ? raw.token : "";
|
|
106
|
+
const passed = token.length > 0 && await deps.verifier.verify(token, { remoteIp: remoteIp(request) });
|
|
107
|
+
if (!passed) return json(422, { ok: false, error: "challenge_failed" });
|
|
108
|
+
const meta = {
|
|
109
|
+
...deps.readMeta?.(request),
|
|
110
|
+
receivedAt: (deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString()
|
|
111
|
+
};
|
|
112
|
+
const userAgent = request.headers.get("user-agent") ?? void 0;
|
|
113
|
+
const inquiry = {
|
|
114
|
+
...validation.value,
|
|
115
|
+
...userAgent ? { userAgent } : {},
|
|
116
|
+
meta
|
|
117
|
+
};
|
|
118
|
+
try {
|
|
119
|
+
await deps.transport.send(inquiry);
|
|
120
|
+
} catch {
|
|
121
|
+
return json(502, { ok: false, error: "send_failed" });
|
|
122
|
+
}
|
|
123
|
+
return json(200, { ok: true });
|
|
124
|
+
}
|
|
125
|
+
export {
|
|
126
|
+
DEFAULT_MAX_BODY_BYTES,
|
|
127
|
+
DEFAULT_MAX_EMAIL_LENGTH,
|
|
128
|
+
DEFAULT_MAX_MESSAGE_LENGTH,
|
|
129
|
+
handleContact,
|
|
130
|
+
hasLineBreak,
|
|
131
|
+
normalizeLocale,
|
|
132
|
+
validateSubmission
|
|
133
|
+
};
|
|
134
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/validate.ts","../src/handler.ts"],"sourcesContent":["/**\n * Pure, synchronous validation for an untrusted contact submission.\n *\n * No I/O and no challenge check (that is the verifier's job). The email rules\n * are deliberately strict — a single address with no CR/LF — so the result is\n * safe to drop into a `Reply-To` header without enabling email header\n * injection, the most important security invariant of this feature.\n */\n\nimport type { ContactConfig, ContactLocale, RawSubmission, ValidationResult } from './types.js';\n\n/** Default limits, exported so adapters and the handler share one source of truth. */\nexport const DEFAULT_MAX_MESSAGE_LENGTH = 5000;\nexport const DEFAULT_MAX_EMAIL_LENGTH = 254;\nexport const DEFAULT_MAX_BODY_BYTES = 16384;\n\nconst SUPPORTED_LOCALES: readonly string[] = ['ja', 'en'];\n\n/**\n * A deliberately strict, single-address email check. Rejects whitespace\n * (including CR/LF) and anything with more than one `@`.\n */\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\n/** True if the string contains a CR or LF (an email header-injection vector). */\nexport function hasLineBreak(value: string): boolean {\n return /[\\r\\n]/.test(value);\n}\n\n/**\n * Normalize an unknown locale claim to a supported {@link ContactLocale},\n * defaulting to `'ja'` (the house default locale).\n */\nexport function normalizeLocale(value: unknown): ContactLocale {\n if (typeof value === 'string') {\n const primary = value.trim().toLowerCase().split('-')[0];\n if (primary !== undefined && SUPPORTED_LOCALES.includes(primary)) {\n return primary as ContactLocale;\n }\n }\n return 'ja';\n}\n\n/**\n * Validate a raw, untrusted submission into a {@link ValidationResult}.\n *\n * A tripped honeypot returns `{ ok: false, error: 'honeypot', spam: true }` so\n * the caller can choose to feign success rather than reveal the trap.\n */\nexport function validateSubmission(raw: RawSubmission, config?: ContactConfig): ValidationResult {\n // Honeypot: any non-empty value means a bot filled a hidden field.\n if (typeof raw.hp === 'string' && raw.hp.trim() !== '') {\n return { ok: false, error: 'honeypot', spam: true };\n }\n\n const maxEmail = config?.maxEmailLength ?? DEFAULT_MAX_EMAIL_LENGTH;\n const maxMessage = config?.maxMessageLength ?? DEFAULT_MAX_MESSAGE_LENGTH;\n\n // Email — required, single address, no CR/LF, within length, well-formed.\n if (typeof raw.email !== 'string') return { ok: false, error: 'email_missing' };\n const email = raw.email.trim();\n if (email === '') return { ok: false, error: 'email_missing' };\n if (email.length > maxEmail) return { ok: false, error: 'email_too_long' };\n if (hasLineBreak(email) || !EMAIL_RE.test(email)) return { ok: false, error: 'email_invalid' };\n\n // Message — required, non-empty after trim, within length. Newlines allowed in the body.\n if (typeof raw.message !== 'string') return { ok: false, error: 'message_missing' };\n const message = raw.message.trim();\n if (message === '') return { ok: false, error: 'message_missing' };\n if (message.length > maxMessage) return { ok: false, error: 'message_too_long' };\n\n const pageUrl = typeof raw.pageUrl === 'string' ? raw.pageUrl.trim() : '';\n return {\n ok: true,\n value: {\n email,\n message,\n locale: normalizeLocale(raw.locale),\n ...(pageUrl !== '' ? { pageUrl } : {}),\n },\n };\n}\n","/**\n * Framework-agnostic contact-form request handler.\n *\n * Pipeline: method / content-type / origin guards → size-bounded JSON parse →\n * {@link validateSubmission} → challenge verification → {@link EmailTransport}\n * delivery. Returns a small JSON {@link Response}. It is intentionally stateless\n * (no storage) and mountable on any Web-standard runtime; adapters supply the\n * verifier and transport.\n */\n\nimport type { ContactDeps, Inquiry, InquiryMeta, RawSubmission } from './types.js';\nimport { DEFAULT_MAX_BODY_BYTES, validateSubmission } from './validate.js';\n\nfunction json(status: number, body: Record<string, unknown>): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-store',\n },\n });\n}\n\n/** True if the request's Origin (or Referer origin) is allowed, or no allowlist is set. */\nfunction originAllowed(request: Request, allowed?: string[]): boolean {\n if (!allowed || allowed.length === 0) return true;\n const origin = request.headers.get('origin');\n if (origin) return allowed.includes(origin);\n // Fall back to the Referer's origin when Origin is absent.\n const referer = request.headers.get('referer');\n if (referer) {\n try {\n return allowed.includes(new URL(referer).origin);\n } catch {\n return false;\n }\n }\n return false;\n}\n\n/** Best-effort visitor IP from common edge headers (used only for challenge scoring). */\nfunction remoteIp(request: Request): string | undefined {\n const direct = request.headers.get('cf-connecting-ip');\n if (direct) return direct;\n const forwarded = request.headers.get('x-forwarded-for');\n if (!forwarded) return undefined;\n const first = forwarded.split(',')[0]?.trim();\n return first !== undefined && first !== '' ? first : undefined;\n}\n\nexport async function handleContact(request: Request, deps: ContactDeps): Promise<Response> {\n if (request.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });\n\n const contentType = request.headers.get('content-type') ?? '';\n if (!contentType.includes('application/json')) {\n return json(415, { ok: false, error: 'unsupported_media_type' });\n }\n\n if (!originAllowed(request, deps.config?.allowedOrigins)) {\n return json(403, { ok: false, error: 'forbidden_origin' });\n }\n\n const maxBytes = deps.config?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;\n const buffer = await request.arrayBuffer();\n if (buffer.byteLength > maxBytes) return json(413, { ok: false, error: 'payload_too_large' });\n\n let raw: RawSubmission;\n try {\n const parsed: unknown = JSON.parse(new TextDecoder().decode(buffer));\n if (typeof parsed !== 'object' || parsed === null) {\n return json(400, { ok: false, error: 'invalid_json' });\n }\n raw = parsed;\n } catch {\n return json(400, { ok: false, error: 'invalid_json' });\n }\n\n const validation = validateSubmission(raw, deps.config);\n if (!validation.ok) {\n // Honeypot: feign success so a bot cannot learn it was caught.\n if (validation.spam) return json(200, { ok: true });\n return json(422, { ok: false, error: validation.error });\n }\n\n const token = typeof raw.token === 'string' ? raw.token : '';\n const passed =\n token.length > 0 && (await deps.verifier.verify(token, { remoteIp: remoteIp(request) }));\n if (!passed) return json(422, { ok: false, error: 'challenge_failed' });\n\n const meta: InquiryMeta = {\n ...deps.readMeta?.(request),\n receivedAt: (deps.now?.() ?? new Date()).toISOString(),\n };\n const userAgent = request.headers.get('user-agent') ?? undefined;\n const inquiry: Inquiry = {\n ...validation.value,\n ...(userAgent ? { userAgent } : {}),\n meta,\n };\n\n try {\n await deps.transport.send(inquiry);\n } catch {\n return json(502, { ok: false, error: 'send_failed' });\n }\n\n return json(200, { ok: true });\n}\n"],"mappings":";AAYO,IAAM,6BAA6B;AACnC,IAAM,2BAA2B;AACjC,IAAM,yBAAyB;AAEtC,IAAM,oBAAuC,CAAC,MAAM,IAAI;AAMxD,IAAM,WAAW;AAGV,SAAS,aAAa,OAAwB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A,QAAM,YAAY,QAAQ,QAAQ,IAAI,YAAY,KAAK;AACvD,QAAM,UAAmB;AAAA,IACvB,GAAG,WAAW;AAAA,IACd,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;AAAA,IACjC;AAAA,EACF;AAEA,MAAI;AACF,UAAM,KAAK,UAAU,KAAK,OAAO;AAAA,EACnC,QAAQ;AACN,WAAO,KAAK,KAAK,EAAE,IAAI,OAAO,OAAO,cAAc,CAAC;AAAA,EACtD;AAEA,SAAO,KAAK,KAAK,EAAE,IAAI,KAAK,CAAC;AAC/B;","names":[]}
|
package/package.json
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@takuhon/contact",
|
|
3
|
+
"version": "0.24.0",
|
|
4
|
+
"description": "Portable, framework-agnostic contact-form core for takuhon — validation, a stateless inquiry pipeline, and challenge/email transport interfaces. Host wiring (e.g. Cloudflare Turnstile + send_email) lives in the adapters.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"author": "Takuhon contributors",
|
|
7
|
+
"homepage": "https://github.com/takuhon-dev/takuhon/tree/main/packages/contact#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/takuhon-dev/takuhon.git",
|
|
11
|
+
"directory": "packages/contact"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/takuhon-dev/takuhon/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"takuhon",
|
|
18
|
+
"contact",
|
|
19
|
+
"form",
|
|
20
|
+
"turnstile",
|
|
21
|
+
"portable"
|
|
22
|
+
],
|
|
23
|
+
"type": "module",
|
|
24
|
+
"main": "./dist/index.js",
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"import": "./dist/index.js"
|
|
30
|
+
},
|
|
31
|
+
"./package.json": "./package.json"
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist",
|
|
35
|
+
"README.md",
|
|
36
|
+
"LICENSE",
|
|
37
|
+
"NOTICE"
|
|
38
|
+
],
|
|
39
|
+
"publishConfig": {
|
|
40
|
+
"access": "public",
|
|
41
|
+
"provenance": true
|
|
42
|
+
},
|
|
43
|
+
"engines": {
|
|
44
|
+
"node": ">=22.0.0"
|
|
45
|
+
},
|
|
46
|
+
"scripts": {
|
|
47
|
+
"typecheck": "tsc",
|
|
48
|
+
"build": "tsup src/index.ts --format esm --dts --clean --sourcemap && vite build",
|
|
49
|
+
"test": "vitest run"
|
|
50
|
+
}
|
|
51
|
+
}
|