Switch to Cap invisible widget, add form drafts to middleware, and improve OTP

validation

Use the Cap client widget in the contact UI with status icons and auto-solve,
replacing the capwidget element. Normalize and tighten phone validation by
splitting
normalizePhone and isValidPhone in the Otp lib and use it in contact action
validation. Replace loose text validation with a character-stripper helper.
Also bump several dependencies and adjust middleware to save and restore form
data for
form actions.
This commit is contained in:
badblocks 2026-01-27 09:49:06 -08:00
parent f7bdfd3cb8
commit 8e35387841
No known key found for this signature in database
7 changed files with 261 additions and 222 deletions

View file

@ -10,20 +10,10 @@ import {
ANDROID_SMS_GATEWAY_RECIPIENT_PHONE,
} from "astro:env/server";
const isValidCaptcha: [(data: string) => any, { message: string }] = [
async (value: string) =>
typeof console.log(value) &&
/^[a-fA-F0-9]{16}:[a-fA-F0-9]{30}$/.test(value) &&
(await CapServer.validateToken(value)),
{
message: "Invalid captcha token.",
},
];
const stripLow = (value: string) => validator.stripLow(value);
const isMobilePhone: [(data: string) => any, { message: string }] = [
(value: string) => validator.isMobilePhone(value, ["en-US", "en-CA"]),
const isValidMobilePhone: [(data: string) => any, { message: string }] = [
(value: string) =>
validator.isMobilePhone(value, ["en-US", "en-CA"]) &&
Otp.isValidPhone(value),
{ message: "Invalid phone number" },
];
@ -38,45 +28,30 @@ const noExcessiveRepetitions: [(data: string) => any, { message: string }] = [
{ message: "No excessive repetitions!" },
];
const acceptableText: [(data: string) => any, { message: string }] = [
(value: string) =>
/^[\p{Letter}\p{Mark}\p{General_Category=Decimal_Number}\p{General_Category=Punctuation}\p{General_Category=Space_Separator}\p{General_Category=Symbol}\p{RGI_Emoji}]*$/v.test(
value,
),
{
message:
"Only letters, numbers, punctuation, spaces, symbols, and emojis are allowed.",
},
];
const stripDisallowedCharacters = (value: string) =>
value
.match(
/(?:[\p{Letter}\p{Mark}\p{General_Category=Decimal_Number}\p{General_Category=Punctuation}\p{General_Category=Space_Separator}\p{General_Category=Symbol}]|\p{RGI_Emoji})/gv,
)
?.join("") ?? "";
const captcha_input = z
.string()
.trim()
.nonempty()
.refine(...isValidCaptcha);
const captcha_input = z.string().trim().nonempty();
const sendOtpAction = z.object({
action: z.literal("send_otp"),
name: z
.string()
.trim()
.min(5)
.max(32)
.transform(stripLow)
.refine(...acceptableText),
name: z.string().trim().min(5).max(32).transform(stripDisallowedCharacters),
phone: z
.string()
.trim()
.refine(...isMobilePhone),
.refine(...isValidMobilePhone),
msg: z
.string()
.trim()
.min(25)
.max(512)
.transform(stripLow)
.transform(stripDisallowedCharacters)
.refine(...noYelling)
.refine(...noExcessiveRepetitions)
.refine(...acceptableText),
.refine(...noExcessiveRepetitions),
captcha: captcha_input,
});
@ -95,49 +70,41 @@ const submitActionDefinition = {
input: formAction,
handler: async (input: any, context: ActionAPIContext) => {
if (!OTP_SUPER_SECRET_SALT || !ANDROID_SMS_GATEWAY_RECIPIENT_PHONE) {
console.log("Server variables are missing.");
throw new ActionError({
code: "INTERNAL_SERVER_ERROR",
message: "Server variables are missing.",
});
}
if (
!(
/^[a-fA-F0-9]{16}:[a-fA-F0-9]{30}$/.test(input.captcha) &&
(await CapServer.validateToken(input.captcha))
)
) {
console.log("Invalid Captcha Token");
throw new ActionError({
code: "BAD_REQUEST",
message: "Invalid Captcha Token",
});
}
if (input.action === "send_otp") {
const { name, phone, msg } = input;
if (!phone || !Otp.validatePhoneNumber(phone)) {
throw new ActionError({
code: "BAD_REQUEST",
message: "Invalid phone number.",
});
}
if (Otp.isRateLimitedForOtp(phone)) {
throw new ActionError({
code: "TOO_MANY_REQUESTS",
message: "Too many OTP requests. Please try again later.",
});
}
if (Otp.isRateLimitedForMsgs(phone)) {
throw new ActionError({
code: "TOO_MANY_REQUESTS",
message: "Too many message requests. Please try again later.",
});
}
const otp = Otp.generateOtp(phone, OTP_SUPER_SECRET_SALT);
const stepSeconds = Otp.getOtpStep();
const stepMinutes = Math.floor(stepSeconds / 60);
const remainingSeconds = stepSeconds % 60;
const api = new SmsClient();
const message = `${otp} is your verification code. This code is valid for ${stepMinutes} minutes${
remainingSeconds != 0 ? " " + remainingSeconds + " seconds." : "."
}`;
const result = await api.sendSMS(phone, message);
const result = await new SmsClient().sendSMS(phone, message);
console.log(JSON.stringify(result));
if (result.success) {
Otp.recordOtpRequest(phone);
context.session?.set("phone", phone);
context.session?.set("name", name);
context.session?.set("msg", msg);
@ -146,6 +113,9 @@ const submitActionDefinition = {
nextAction: "send_msg",
};
} else {
console.log(
"Verification code failed to send. Please try again later.",
);
throw new ActionError({
code: "SERVICE_UNAVAILABLE",
message: "Verification code failed to send. Please try again later.",
@ -158,6 +128,7 @@ const submitActionDefinition = {
const msg = await context.session?.get("msg");
if (!name || !otp || !msg || !phone) {
console.log("Missing required fields.");
throw new ActionError({
code: "BAD_REQUEST",
message: "Missing required fields.",
@ -166,6 +137,7 @@ const submitActionDefinition = {
const isVerified = verifyOtp(phone, OTP_SUPER_SECRET_SALT, otp);
if (!isVerified) {
console.log("Invalid or expired verification code.");
throw new ActionError({
code: "BAD_REQUEST",
message: "Invalid or expired verification code.",
@ -192,6 +164,7 @@ const submitActionDefinition = {
};
}
console.log("Message failed to send.");
throw new ActionError({
code: "SERVICE_UNAVAILABLE",
message: "Message failed to send.",

View file

@ -29,33 +29,36 @@ function getUserSecret(phoneNumber: string, salt: string): string {
.digest("hex");
}
export function validatePhoneNumber(unsafePhoneNum: string) {
if (typeof unsafePhoneNum !== "string") {
return { success: false, message: "Invalid phone number." };
export function normalizePhone(phone: string) {
const result = phone.replace(/[^\d]/g, "").trim().startsWith("1")
? phone.substring(1)
: phone;
if (result.length !== 10) {
throw new Error("Invalid phone number.");
}
unsafePhoneNum = unsafePhoneNum.replace(/[^0-9]/g, "").trim();
const cleanedNumber = unsafePhoneNum.startsWith("1")
? unsafePhoneNum.substring(1)
: unsafePhoneNum;
return result;
}
const isValidFormat = /^[2-7][0-8][0-9][2-9][0-9]{6}$/.test(cleanedNumber);
const isNotAllSameDigit = !/^(.)\1{9}$/.test(cleanedNumber);
const isNot911Number = !/^[0-9]{3}911[0-9]{4}$/.test(cleanedNumber);
const isNot555Number = !/^[0-9]{3}555[0-9]{4}$/.test(cleanedNumber);
const isNotPopSongNumber = !/^[0-9]{3}8675309$/.test(cleanedNumber);
export function isValidPhone(phone: string): boolean {
phone = normalizePhone(phone);
const match = phone.match(/(\d{3})(\d{3})(\d{4})/);
const [, prefix, exchange, station] = match ?? [];
const isValidNANPFormat =
/^[2-7][0-8][0-9]$/.test(prefix) && /^[2-9][0-9]{2}$/.test(exchange);
const isNotAllSameDigit = !/^(.)\1{6}$/.test(exchange + station);
const isNot911Number = prefix !== "911" && exchange !== "911";
const isNot555Number = prefix !== "555" && exchange !== "555";
const isNotPopSongNumber = exchange !== "867" && station !== "5309";
if (
isValidFormat &&
return (
isValidNANPFormat &&
isNotAllSameDigit &&
isNot911Number &&
isNot555Number &&
isNotPopSongNumber
) {
return { success: true, validatedPhoneNumber: cleanedNumber };
}
return { success: false, validatedPhoneNumber: undefined };
);
}
export function generateOtp(phoneNumber: string, salt: string): string {
@ -141,7 +144,8 @@ export function recordOtpRequest(phoneNumber: string) {
}
export default {
validatePhoneNumber,
normalizePhone,
isValidPhone,
generateOtp,
verifyOtp,
getOtpStep,

View file

@ -1,6 +1,5 @@
import { defineMiddleware } from "astro:middleware";
import { getActionContext } from "astro:actions";
import { randomUUID } from "node:crypto";
export const onRequest = defineMiddleware(async (context, next) => {
if (context.isPrerendered) return next();
@ -19,6 +18,7 @@ export const onRequest = defineMiddleware(async (context, next) => {
}
if (action?.calledFrom === "form") {
const formData = await context.request.clone().formData();
const actionResult = await action.handler();
context.session?.set(
@ -30,6 +30,15 @@ export const onRequest = defineMiddleware(async (context, next) => {
);
if (actionResult.error) {
const draft = {
action: formData.get("action")?.toString() ?? "",
name: formData.get("name")?.toString() ?? "",
phone: formData.get("phone")?.toString() ?? "",
msg: formData.get("msg")?.toString() ?? "",
};
context.session?.set("contactFormDraft", draft);
const referer = context.request.headers.get("Referer");
if (!referer) {
throw new Error(
@ -39,6 +48,7 @@ export const onRequest = defineMiddleware(async (context, next) => {
return context.redirect(referer);
}
context.session?.delete("contactFormDraft");
return context.redirect(context.originPathname);
}

View file

@ -4,9 +4,12 @@ export const prerender = false;
export const POST: APIRoute = async () => {
try {
return new Response(JSON.stringify(await cap.createChallenge()), {
status: 200,
});
return new Response(
JSON.stringify(await cap.createChallenge({ challengeDifficulty: 4 })),
{
status: 200,
},
);
} catch {
return new Response(JSON.stringify({ success: false }), { status: 400 });
}

View file

@ -4,88 +4,103 @@ import { actions, isInputError } from "astro:actions";
export const prerender = false;
const result = Astro.getActionResult(actions.contact.submitForm);
// FIX (might be fixed with below change): if user types in invalid otp code, it returns an error
// and then nextAction is set to "send_otp". It needs to be set
// to "send_msg" if the error is caused by invalid otp code
//
// ALSO: change it maybe so user can always fill out all fields
// in one go, including otp code (have verify number swap with code field when sent)
// text me button should be disabled if otp code is invalid or missing
const nextAction = result?.data?.nextAction || "send_otp";
const error = isInputError(result?.error) ? result.error.fields : {};
const formDraft = (await Astro.session?.get("contactFormDraft")) ?? undefined;
if (formDraft && Object.keys(formDraft).length) {
Astro.session?.delete("contactFormDraft");
}
const pickValue = (key: string) =>
typeof formDraft?.[key] === "string" ? formDraft[key] : undefined;
const nameValue = pickValue("name");
const phoneValue = pickValue("phone");
const msgValue = pickValue("msg");
---
<script>
import CapWidget from "@cap.js/widget";
import Cap from "@cap.js/widget";
import "iconify-icon";
const widget = document.querySelector("cap-widget");
if (widget) {
const credits = widget?.shadowRoot?.querySelector('[part="attribution"]');
const captchaInput = document.querySelector("input[id='captcha']");
const captchaStatus = document.querySelector("#captchaStatus");
const statusText = captchaStatus?.querySelector("#statusText");
const initIcon = captchaStatus?.querySelector("#initIcon");
const completeIcon = captchaStatus?.querySelector("#completeIcon");
const errorIcon = captchaStatus?.querySelector("#errorIcon");
const progressIcon = captchaStatus?.querySelector("#progressIcon");
const cap = new Cap({
apiEndpoint: "/cap/",
});
if (credits) {
const clone = credits.cloneNode(true);
const poweredByTextBefore = document.createTextNode("(by ");
const poweredByTextAfter = document.createTextNode(")");
document
.querySelector("#captcha-credits")
?.appendChild(poweredByTextBefore);
document.querySelector("#captcha-credits")?.appendChild(clone);
document
.querySelector("#captcha-credits")
?.appendChild(poweredByTextAfter);
widget?.style.setProperty("--cap-credits-display", "none");
}
widget.addEventListener("solve", function (e) {
const token = e.detail.token;
const hiddenInput = document.querySelector("input[id='captcha']");
if (hiddenInput && "value" in hiddenInput) {
hiddenInput.value = token;
}
if (
captchaStatus &&
statusText &&
initIcon &&
completeIcon &&
errorIcon &&
progressIcon
) {
cap.addEventListener("solve", function (e) {
statusText.textContent = "You seem human enough!";
progressIcon.classList.add("hidden");
errorIcon.classList.add("hidden");
initIcon.classList.add("hidden");
completeIcon.classList.remove("hidden");
});
cap.addEventListener("error", function (e) {
statusText.textContent = "Oops! We crashed!";
progressIcon.classList.add("hidden");
completeIcon.classList.add("hidden");
initIcon.classList.add("hidden");
errorIcon.classList.remove("hidden");
});
cap.addEventListener("progress", (event) => {
statusText.textContent = `Weighing your humanity... ${event.detail.progress}%`;
errorIcon.classList.add("hidden");
completeIcon.classList.add("hidden");
initIcon.classList.add("hidden");
progressIcon.classList.remove("hidden");
});
}
if (captchaInput && "value" in captchaInput) {
const {token} = await cap.solve();
captchaInput.value = token;
}
</script>
<style>
cap-widget {
--cap-background: var(--bg-color);
--cap-border-color: rgba(255, 255, 255, 0);
--cap-border-radius: 0;
--cap-widget-height: initial;
--cap-widget-width: 100%;
--cap-widget-padding: 0 0 11px 0;
--cap-gap: 3ch;
--cap-color: var(--text-color);
--cap-checkbox-size: 32px;
--cap-checkbox-border: 2px solid var(--border-color);
--cap-checkbox-border-radius: 4px;
--cap-checkbox-background: var(--input-bg);
--cap-checkbox-margin: 4px;
--cap-font: "Courier New", Courier, monospace;
--cap-spinner-color: var(--text-color);
--cap-spinner-background-color: var(--input-bg);
--cap-spinner-thickness: 2px;
--cap-credits-display: inline;
margin: 0;
display: block;
}
cap-widget::part(attribution) {
display: var(--cap-credits-display);
}
form {
display: grid;
gap: 1rem;
width: 100%;
margin: 0 auto;
grid-template-columns: repeat(2, 1fr);
grid-template-areas:
"header header header header "
"name name phone phone"
"msg msg msg msg"
"captcha captcha verify verify"
"otp otp submit submit";
"header header"
"name phone"
"msg msg"
"otp captcha"
"send_otp send_msg";
}
form fieldset {
display: contents;
.hidden {
display: none;
visibility: hidden;
}
#captcha-credits {
font-size: x-small;
}
div {
#header {
grid-area: header;
}
label {
text-align: left;
}
label[for="name"] {
grid-area: name;
}
@ -95,96 +110,142 @@ const error = isInputError(result?.error) ? result.error.fields : {};
label[for="msg"] {
grid-area: msg;
}
label[for="otp"] {
grid-area: otp;
}
label[for="captcha"] {
grid-area: captcha;
margin-bottom: 0;
}
#captchaStatus {
padding: 0.8rem 0;
font-size: small;
}
button {
height: 39px;
margin: 29px 0 10px 0;
padding: 8px 12px;
}
button#send_otp {
grid-area: verify;
grid-area: send_otp;
}
button#send_msg {
grid-area: submit;
grid-area: send_msg;
}
.spin {
animation: spin 4s linear infinite;
position: relative;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
<Layout>
<title slot="head">Home</title>
<Fragment slot="content">
<h2>
Contact <iconify-icon
icon="streamline-sharp-color:chat-bubble-typing-oval"></iconify-icon>
</h2>
<h2>Contact</h2>
{
(nextAction != "complete" && (
<form method="post" x-data="{}" action={actions.contact.submitForm}>
<div>
<div id="header">
{(result?.error && (
<p class="error">
Unable to send {nextAction == "send_otp" ? "OTP" : "message"}.
Please correct any errors and try again.
{result?.error.message}
Please correct any errors and try again.
</p>
)) || <p>Use the below form to shoot me a quick text!</p>}
</div>
<fieldset id="send_otp" disabled={nextAction != "send_otp"}>
<label for="name">
Name
<input
type="text"
id="name"
name="name"
aria-describedby="name"
placeholder="Bad Blocks"
<label for="name">
Name
<input
type="text"
id="name"
name="name"
aria-describedby="name"
value="Bad Blocks"
/><!-- value={nameValue} -->
{error.name && <p id="error_name">{error.name.join(",")}</p>}
</label>
<label for="captcha">
<a href="https://capjs.js.org/">Cap</a>tcha
<input type="hidden" id="captcha" name="captcha" />
<div id="captchaStatus">
<iconify-icon id="initIcon" icon="line-md:loading-loop" />
<iconify-icon
id="completeIcon"
icon="line-md:circle-to-confirm-circle-transition"
class="hidden"
/>
{error.name && <p id="error_name">{error.name.join(",")}</p>}
</label>
<label for="phone">
Phone
<input
type="text"
id="phone"
name="phone"
aria-describedby="error_phone"
placeholder="555-555-5555"
<iconify-icon
id="errorIcon"
icon="line-md:alert-circle-loop"
class="hidden"
/>
{error.phone && <p id="error_phone">{error.phone.join(",")}</p>}
</label>
<label for="msg">
Msg
<textarea
id="msg"
name="msg"
aria-describedby="error_msg"
placeholder="I think badblocks rocks!"
<iconify-icon
id="progressIcon"
icon="line-md:speedometer-loop"
class="hidden"
/>
{error.msg && <p id="error_msg">{error.msg.join(",")}</p>}
</label>
</fieldset>
&nbsp;<span id="statusText">Loading...</span>
</div>
{error.captcha && <p id="error_name">{error.captcha.join(",")}</p>}
</label>
<label for="phone">
Phone
<input
type="text"
id="phone"
name="phone"
aria-describedby="error_phone"
value="2067452154"
/><!-- value={phoneValue} -->
{error.phone && <p id="error_phone">{error.phone.join(",")}</p>}
</label>
<label for="msg">
Msg
<textarea
id="msg"
name="msg"
aria-describedby="error_msg"
>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi augue eros, maximus nec ex sit amet, scelerisque interdum leo. Sed eu turpis sit amet dui congue efficitur. Duis eu laoreet risus, eget vestibulum lectus.
</textarea>
<!-- <textarea
id="msg"
name="msg"
aria-describedby="error_msg"
placeholder="I think badblocks rocks!"
>
{msgValue}
</textarea> -->
{error.msg && <p id="error_msg">{error.msg.join(",")}</p>}
</label>
<button
id="send_otp"
name="action"
value="send_otp"
type="submit"
disabled={nextAction != "send_otp"}
class={nextAction != "send_otp" ? "hidden" : undefined}
>
Verify Your Number!
Send Verification Code!
</button>
<fieldset id="send_msg" disabled={nextAction != "send_msg"}>
<label for="otp">
Code
<input
type="text"
id="otp"
name="otp"
aria-describedby="error_otp"
placeholder="123456"
/>
{error.otp && <p id="error_otp">{error.otp.join(",")}</p>}
</label>
</fieldset>
<label for="otp">
Verification Code
<input
type="text"
id="otp"
name="otp"
aria-describedby="error_otp"
placeholder="123456"
disabled={nextAction != "send_msg"}
/>
{error.otp && <p id="error_otp">{error.otp.join(",")}</p>}
</label>
<button
id="send_msg"
name="action"
@ -194,18 +255,6 @@ const error = isInputError(result?.error) ? result.error.fields : {};
>
Text Me!
</button>
<label for="captcha">
Captcha <span id="captcha-credits" />
<cap-widget
id="captcha"
data-cap-api-endpoint="/cap/"
aria-describedby="error_captcha"
/>
{error.captcha && (
<p id="error_captcha">{error.captcha.join(",")}</p>
)}
<input type="hidden" id="captcha" name="captcha" />
</label>
</form>
)) || <p>Your message has been sent successfully!</p>
}