mirror of
https://github.com/Patiun/com.gregkilmer.www.git
synced 2026-11-08 04:08:24 +00:00
Form Update
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
---
|
||||
/**
|
||||
* ObfuscatedEmail.astro
|
||||
* ---------------------------------------------------------------------------
|
||||
* Renders an email address as a clickable link without ever putting the
|
||||
* plaintext address into the HTML source. The address is base64-encoded at
|
||||
* render time and stored in a data attribute; a tiny inline script decodes it
|
||||
* on click and builds the mailto: href at that moment. Scrapers that simply
|
||||
* grep the HTML for `@` or `mailto:` see nothing useful.
|
||||
*
|
||||
* This is not cryptographically secure obfuscation (base64 is trivially
|
||||
* reversible), but it defeats the vast majority of dumb harvesters that don't
|
||||
* run JS. Combined with robots.txt + noindex on /contact, it raises the cost
|
||||
* of harvesting enough to be worthwhile.
|
||||
*
|
||||
* <noscript> fallback shows a non-clickable prompt directing visitors to the
|
||||
* contact form, so the page isn't broken for the rare no-JS visitor.
|
||||
*
|
||||
* Usage: <ObfuscatedEmail address="contact@gregkilmer.com" />
|
||||
*/
|
||||
interface Props {
|
||||
address: string;
|
||||
/** Optional visible label; defaults to the address (decoded client-side). */
|
||||
label?: string;
|
||||
class?: string;
|
||||
style?: string;
|
||||
}
|
||||
|
||||
const { address, label, class: className, style } = Astro.props;
|
||||
|
||||
// Encode at render time. btoa needs a binary-safe string; email addresses are
|
||||
// ASCII so this is fine. We also reverse the string first so even a base64
|
||||
// decoder doesn't immediately yield the address — a small extra speed bump.
|
||||
const encoded = btoa(address.split("").reverse().join(""));
|
||||
const displayLabel = label ?? " "; // placeholder; JS fills the real address
|
||||
---
|
||||
|
||||
<a
|
||||
href="#"
|
||||
data-mail={encoded}
|
||||
class={className}
|
||||
style={style}
|
||||
onclick="return false;"
|
||||
aria-label="Email address (decoded on click)"
|
||||
>
|
||||
{displayLabel}
|
||||
</a>
|
||||
<noscript>
|
||||
<span class={className} style={style}>
|
||||
Enable JavaScript to see the email address, or use the contact form.
|
||||
</span>
|
||||
</noscript>
|
||||
|
||||
<script is:inline>
|
||||
// Decode and wire up every obfuscated email link on the page. Runs on initial
|
||||
// load and again after Astro View Transitions swap the DOM (astro:page-load).
|
||||
function initObfuscatedEmail() {
|
||||
document.querySelectorAll("a[data-mail]").forEach((el) => {
|
||||
const a = el;
|
||||
const encoded = a.getAttribute("data-mail");
|
||||
if (!encoded) return;
|
||||
// Reverse the base64 we encoded at render time, then decode.
|
||||
const reversed = atob(encoded).split("").reverse().join("");
|
||||
a.setAttribute("href", "mailto:" + reversed);
|
||||
// If no explicit label was provided, show the address as the link text.
|
||||
if (!a.textContent || a.textContent.trim() === "") {
|
||||
a.textContent = reversed;
|
||||
}
|
||||
});
|
||||
}
|
||||
initObfuscatedEmail();
|
||||
document.addEventListener("astro:page-load", initObfuscatedEmail);
|
||||
</script>
|
||||
@@ -4,12 +4,18 @@
|
||||
* Accessible contact form island. Posts to /api/contact, which either sends an
|
||||
* email via SMTP or fires a webhook. Manages idle / submitting / success / error
|
||||
* states, does lightweight client validation, and includes a honeypot field for
|
||||
* crude spam defense (the server also rate-limits).
|
||||
* crude spam defense (the server also rate-limits and verifies a Turnstile
|
||||
* token when configured).
|
||||
*
|
||||
* The form is keyboard-accessible, labels every field, and announces status
|
||||
* changes via an aria-live region.
|
||||
*
|
||||
* Turnstile: when `turnstileSiteKey` is provided, Cloudflare's invisible
|
||||
* challenge is rendered. The token it produces is sent with the submission and
|
||||
* verified server-side. If no key is configured (local dev), Turnstile is
|
||||
* skipped entirely so the form still works.
|
||||
*/
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { useState, useRef, useEffect, type FormEvent } from 'react';
|
||||
|
||||
type Status = 'idle' | 'submitting' | 'success' | 'error';
|
||||
|
||||
@@ -21,10 +27,77 @@ interface FieldErrors {
|
||||
|
||||
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
|
||||
export default function ContactForm() {
|
||||
// Declared by the Turnstile script on window once loaded.
|
||||
declare global {
|
||||
interface Window {
|
||||
turnstile?: {
|
||||
render: (el: string | HTMLElement, opts: Record<string, unknown>) => string;
|
||||
reset: (id?: string) => void;
|
||||
remove: (id: string) => void;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
interface Props {
|
||||
/** Public Cloudflare Turnstile site key. Omit to skip Turnstile (e.g. dev). */
|
||||
turnstileSiteKey?: string;
|
||||
}
|
||||
|
||||
export default function ContactForm({ turnstileSiteKey }: Props) {
|
||||
const [status, setStatus] = useState<Status>('idle');
|
||||
const [errors, setErrors] = useState<FieldErrors>({});
|
||||
const [errorMsg, setErrorMsg] = useState<string>('');
|
||||
const [turnstileReady, setTurnstileReady] = useState<boolean>(!turnstileSiteKey);
|
||||
|
||||
// Holds the live Turnstile token between renders (cleared on reset/expiry).
|
||||
const turnstileTokenRef = useRef<string>('');
|
||||
// Widget ID returned by turnstile.render(); used to reset on failure.
|
||||
const turnstileWidgetIdRef = useRef<string | null>(null);
|
||||
// Container div the widget mounts into.
|
||||
const turnstileContainerRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
// Load the Turnstile script once when a site key is configured.
|
||||
useEffect(() => {
|
||||
if (!turnstileSiteKey) return;
|
||||
if (document.getElementById('cf-turnstile-script')) return;
|
||||
|
||||
const script = document.createElement('script');
|
||||
script.id = 'cf-turnstile-script';
|
||||
script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js';
|
||||
script.async = true;
|
||||
script.defer = true;
|
||||
document.head.appendChild(script);
|
||||
}, [turnstileSiteKey]);
|
||||
|
||||
// Once the script + container are present, render the widget.
|
||||
useEffect(() => {
|
||||
if (!turnstileSiteKey) return;
|
||||
if (!window.turnstile || !turnstileContainerRef.current) return;
|
||||
|
||||
// Avoid double-rendering if the effect fires twice in StrictMode/dev.
|
||||
if (turnstileWidgetIdRef.current) return;
|
||||
|
||||
turnstileWidgetIdRef.current = window.turnstile.render(
|
||||
turnstileContainerRef.current,
|
||||
{
|
||||
sitekey: turnstileSiteKey,
|
||||
// Called by Turnstile once it has a token (success) or on expiry.
|
||||
callback: (token: string) => {
|
||||
turnstileTokenRef.current = token;
|
||||
setTurnstileReady(true);
|
||||
},
|
||||
'expired-callback': () => {
|
||||
turnstileTokenRef.current = '';
|
||||
setTurnstileReady(false);
|
||||
},
|
||||
'error-callback': () => {
|
||||
turnstileTokenRef.current = '';
|
||||
setTurnstileReady(false);
|
||||
},
|
||||
theme: 'dark',
|
||||
},
|
||||
);
|
||||
}, [turnstileSiteKey]);
|
||||
|
||||
function validate(values: { name: string; email: string; message: string }): FieldErrors {
|
||||
const e: FieldErrors = {};
|
||||
@@ -46,9 +119,15 @@ export default function ContactForm() {
|
||||
message: String(data.get('message') ?? '').trim(),
|
||||
// Honeypot: bots fill this, humans never see it.
|
||||
company: String(data.get('company') ?? ''),
|
||||
// Turnstile token (empty string if Turnstile is not configured).
|
||||
turnstileToken: turnstileTokenRef.current,
|
||||
};
|
||||
|
||||
const found = validate(values);
|
||||
// If Turnstile is configured, require a token before we even hit the server.
|
||||
if (turnstileSiteKey && !values.turnstileToken) {
|
||||
found.message = found.message ?? 'Please complete the bot check and try again.';
|
||||
}
|
||||
setErrors(found);
|
||||
if (Object.keys(found).length > 0) return;
|
||||
|
||||
@@ -62,10 +141,22 @@ export default function ContactForm() {
|
||||
});
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
// Reset the Turnstile widget so the user can re-verify after a failure.
|
||||
if (turnstileSiteKey && turnstileWidgetIdRef.current) {
|
||||
window.turnstile?.reset(turnstileWidgetIdRef.current);
|
||||
turnstileTokenRef.current = '';
|
||||
setTurnstileReady(false);
|
||||
}
|
||||
throw new Error(body.error || 'Something went wrong. Please try again.');
|
||||
}
|
||||
setStatus('success');
|
||||
form.reset();
|
||||
// Fresh widget for the next submission.
|
||||
if (turnstileSiteKey && turnstileWidgetIdRef.current) {
|
||||
window.turnstile?.reset(turnstileWidgetIdRef.current);
|
||||
turnstileTokenRef.current = '';
|
||||
setTurnstileReady(false);
|
||||
}
|
||||
} catch (err) {
|
||||
setStatus('error');
|
||||
setErrorMsg(err instanceof Error ? err.message : 'Something went wrong. Please try again.');
|
||||
@@ -176,9 +267,16 @@ export default function ContactForm() {
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Cloudflare Turnstile widget. Rendered by the script via the ref.
|
||||
Hidden container; Turnstile injects its iframe here. Skipped entirely
|
||||
when no site key is configured (turnstileSiteKey is undefined). */}
|
||||
{turnstileSiteKey && (
|
||||
<div ref={turnstileContainerRef} className="min-h-[65px]" aria-label="Bot check" />
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={status === 'submitting'}
|
||||
disabled={status === 'submitting' || (Boolean(turnstileSiteKey) && !turnstileReady)}
|
||||
className="btn btn-primary self-start disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
{status === 'submitting' ? 'Sending…' : 'Send message'}
|
||||
|
||||
@@ -34,6 +34,9 @@ interface Props {
|
||||
surface?: Surface;
|
||||
/** Override default OG image path. */
|
||||
ogImage?: string;
|
||||
/** When true, emit <meta name="robots" content="noindex, nofollow">. Use on
|
||||
pages that shouldn't be indexed (e.g. /contact, to reduce scraping). */
|
||||
noindex?: boolean;
|
||||
}
|
||||
|
||||
const {
|
||||
@@ -41,6 +44,7 @@ const {
|
||||
description = "Greg Kilmer is a software developer, maker, and tabletop gamemaster based in Philadelphia. This is where his professional and personal worlds meet.",
|
||||
surface = "neutral",
|
||||
ogImage,
|
||||
noindex = false,
|
||||
} = Astro.props;
|
||||
|
||||
// True on the Home page. Used to switch the NavBar's view-transition-name so
|
||||
@@ -79,6 +83,7 @@ const ogImageUrl = ogImage
|
||||
<title>{fullTitle}</title>
|
||||
<meta name="description" content={description} />
|
||||
<link rel="canonical" href={canonical} />
|
||||
{noindex && <meta name="robots" content="noindex, nofollow" />}
|
||||
<meta name="theme-color" content="#0b1026" />
|
||||
|
||||
<!-- Open Graph / social cards -->
|
||||
|
||||
@@ -5,9 +5,10 @@
|
||||
* 1. Reject non-POST.
|
||||
* 2. Validate JSON body with Zod (name, email, message; honeypot must be empty).
|
||||
* 3. Rate-limit per IP (in-memory windowed counter).
|
||||
* 4. Deliver: SMTP via nodemailer if configured, else POST to a webhook if
|
||||
* 4. Verify Cloudflare Turnstile token (if TURNSTILE_SECRET_KEY is set).
|
||||
* 5. Deliver: SMTP via nodemailer if configured, else POST to a webhook if
|
||||
* configured, else return 503 so delivery can be wired later.
|
||||
* 5. Always return JSON { ok } or { error }.
|
||||
* 6. Always return JSON { ok } or { error }.
|
||||
*
|
||||
* Secrets come from env (see .env.example). Nothing secret ships to the client.
|
||||
* This runs server-side only via the @astrojs/node adapter.
|
||||
@@ -22,6 +23,9 @@ const schema = z.object({
|
||||
message: z.string().min(10).max(5000),
|
||||
// Honeypot: must be absent/empty. Bots tend to fill every field.
|
||||
company: z.string().max(0).optional().or(z.literal('')),
|
||||
// Turnstile token. Required when TURNSTILE_SECRET_KEY is set; ignored
|
||||
// otherwise (dev). Validated against Cloudflare's siteverify endpoint below.
|
||||
turnstileToken: z.string().optional(),
|
||||
});
|
||||
|
||||
// --- In-memory rate limiter (per worker) ------------------------------------
|
||||
@@ -57,6 +61,36 @@ function clientIp(request: Request): string {
|
||||
return request.headers.get('x-real-ip') ?? 'unknown';
|
||||
}
|
||||
|
||||
// --- Turnstile verification -------------------------------------------------
|
||||
// Skipped entirely when TURNSTILE_SECRET_KEY is unset (local dev). When set,
|
||||
// the token from the client is POSTed to Cloudflare's siteverify endpoint
|
||||
// along with the visitor's IP for fraud scoring. Only valid tokens proceed.
|
||||
async function verifyTurnstile(token: string | undefined, ip: string): Promise<boolean> {
|
||||
const secret = process.env.TURNSTILE_SECRET_KEY;
|
||||
if (!secret) return true; // Turnstile not configured -> skip.
|
||||
|
||||
if (!token) return false;
|
||||
|
||||
try {
|
||||
const form = new URLSearchParams();
|
||||
form.set('secret', secret);
|
||||
form.set('response', token);
|
||||
if (ip && ip !== 'unknown') form.set('remoteip', ip);
|
||||
|
||||
const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
|
||||
method: 'POST',
|
||||
body: form,
|
||||
});
|
||||
const data = (await res.json()) as { success: boolean };
|
||||
return Boolean(data.success);
|
||||
} catch (err) {
|
||||
// Network error talking to Cloudflare. Fail closed: reject the submission
|
||||
// rather than letting a bot through on a transient outage.
|
||||
console.error('[contact] turnstile verification failed:', err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// --- Route handler ----------------------------------------------------------
|
||||
export const POST: APIRoute = async ({ request }) => {
|
||||
if (request.method !== 'POST') {
|
||||
@@ -74,7 +108,7 @@ export const POST: APIRoute = async ({ request }) => {
|
||||
if (!parsed.success) {
|
||||
return json({ error: 'Please complete all fields correctly.', issues: parsed.error.issues }, 400);
|
||||
}
|
||||
const { name, email, message } = parsed.data;
|
||||
const { name, email, message, turnstileToken } = parsed.data;
|
||||
|
||||
// Rate limit.
|
||||
const ip = clientIp(request);
|
||||
@@ -82,6 +116,13 @@ export const POST: APIRoute = async ({ request }) => {
|
||||
return json({ error: 'Too many submissions. Please try again later.' }, 429);
|
||||
}
|
||||
|
||||
// Turnstile. Skipped when no secret is configured (dev). Fails closed on
|
||||
// network errors so a Cloudflare outage can't open the door to bots.
|
||||
const turnstileOk = await verifyTurnstile(turnstileToken, ip);
|
||||
if (!turnstileOk) {
|
||||
return json({ error: 'Bot check failed. Please refresh and try again.' }, 400);
|
||||
}
|
||||
|
||||
// Deliver.
|
||||
try {
|
||||
const delivered = await deliver({ name, email, message });
|
||||
|
||||
+41
-7
@@ -16,14 +16,13 @@ import Icon from "@components/Icon.astro";
|
||||
import SectionHeader from "@components/layout/SectionHeader.astro";
|
||||
import Placeholder from "@components/layout/Placeholder.astro";
|
||||
import ContactForm from "@components/professional/ContactForm.tsx";
|
||||
import ObfuscatedEmail from "@components/ObfuscatedEmail.astro";
|
||||
|
||||
// Email is rendered separately via <ObfuscatedEmail> so the plaintext address
|
||||
// never appears in the HTML source. The other entries are plain links.
|
||||
const emailAddress = "contact@gregkilmer.com";
|
||||
|
||||
const professional = [
|
||||
{
|
||||
icon: "email-outline",
|
||||
label: "Email",
|
||||
href: "",
|
||||
hint: "Kilmer.GM@Gmail.com",
|
||||
},
|
||||
{
|
||||
icon: "linkedin",
|
||||
label: "LinkedIn",
|
||||
@@ -56,11 +55,19 @@ const social = [
|
||||
hint: "Server link, if public.",
|
||||
},
|
||||
];
|
||||
|
||||
// Turnstile site key. Public per Cloudflare (safe to ship to the client), but
|
||||
// read here server-side and passed as a prop so it never needs the PUBLIC_
|
||||
// prefix and stays consistent with TURNSTILE_SECRET_KEY. Undefined when
|
||||
// Turnstile is not configured, which makes ContactForm skip the widget entirely.
|
||||
const turnstileSiteKey = import.meta.env.TURNSTILE_SITE_KEY as
|
||||
string | undefined;
|
||||
---
|
||||
|
||||
<BaseLayout
|
||||
title="Contact"
|
||||
description="Reach Greg Kilmer for cloud development, SAP BTP, technical leadership, or just to debate the best Gundam series or find a fourth for game night."
|
||||
noindex={true}
|
||||
>
|
||||
<section class="container-prose flex flex-col gap-10 pt-28 sm:pt-32">
|
||||
<Reveal>
|
||||
@@ -86,6 +93,33 @@ const social = [
|
||||
Professional
|
||||
</h2>
|
||||
<ul class="flex flex-col gap-3">
|
||||
{
|
||||
/* Email: rendered via ObfuscatedEmail so the address is not in
|
||||
the HTML source. JS decodes it into a mailto: on click. */
|
||||
}
|
||||
<li class="card flex items-center gap-3">
|
||||
<span
|
||||
class="inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg"
|
||||
style="background: color-mix(in srgb, var(--color-accent) 16%, transparent); color: var(--color-accent);"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<Icon name="email-outline" class="h-5 w-5" />
|
||||
</span>
|
||||
<span class="flex flex-col gap-0.5">
|
||||
<span
|
||||
class="font-sans text-sm font-semibold"
|
||||
style="color: var(--color-text);"
|
||||
>
|
||||
Email
|
||||
</span>
|
||||
<span class="text-xs" style="color: var(--color-text-subtle);">
|
||||
<ObfuscatedEmail
|
||||
address={emailAddress}
|
||||
class="font-mono uppercase tracking-[0.1em]"
|
||||
/>
|
||||
</span>
|
||||
</span>
|
||||
</li>
|
||||
{
|
||||
professional.map((item) => (
|
||||
<li class="card flex items-center gap-3">
|
||||
@@ -193,7 +227,7 @@ const social = [
|
||||
Prefer a form? Drop a note and it will land in my inbox.
|
||||
</p>
|
||||
</div>
|
||||
<ContactForm client:idle />
|
||||
<ContactForm client:idle turnstileSiteKey={turnstileSiteKey} />
|
||||
</section>
|
||||
</Reveal>
|
||||
</div>
|
||||
|
||||
@@ -24,6 +24,7 @@ import AlchemicalDivider from "@components/mystic/AlchemicalDivider.astro";
|
||||
import Astrolabe from "@components/mystic/Astrolabe.astro";
|
||||
import CircuitField from "@components/mystic/CircuitField.tsx";
|
||||
import CelestialFrame from "@components/mystic/CelestialFrame.astro";
|
||||
import ObfuscatedEmail from "@components/ObfuscatedEmail.astro";
|
||||
import { getCollection } from "astro:content";
|
||||
|
||||
const experience = (await getCollection("experience")).sort(
|
||||
@@ -270,12 +271,11 @@ const projects = (await getCollection("projects")).sort(
|
||||
class="h-5 w-5"
|
||||
style="color: var(--color-accent);"
|
||||
/>
|
||||
<span
|
||||
<ObfuscatedEmail
|
||||
address="contact@gregkilmer.com"
|
||||
class="font-mono text-xs uppercase tracking-[0.18em]"
|
||||
style="color: var(--color-accent);"
|
||||
>
|
||||
Kilmer.GM@Gmail.com
|
||||
</span>
|
||||
/>
|
||||
</li>
|
||||
<li class="flex items-center gap-2">
|
||||
<Icon
|
||||
|
||||
Reference in New Issue
Block a user