feat: enhance contact form security and add animated hero

This commit is contained in:
badblocks 2025-07-19 22:59:05 -07:00
parent ea18dcdb8e
commit 8497cd819d
No known key found for this signature in database
19 changed files with 320 additions and 112 deletions

View file

@ -1,5 +1,6 @@
NUXT_ANDROID_SMS_GATEWAY_LOGIN="" # Portfolio App Environment Variables
NUXT_ANDROID_SMS_GATEWAY_PASSWORD="" NUXT_ANDROID_SMS_GATEWAY_URL=http://192.168.1.XXX:9090
NUXT_ANDROID_SMS_GATEWAY_URL="" # including http(s):// NUXT_ANDROID_SMS_GATEWAY_LOGIN=your_login
NUXT_MY_PHONE_NUMBER="" NUXT_ANDROID_SMS_GATEWAY_PASSWORD=your_password
NUXT_SUPER_SECRET_SALT="" #openssl rand -base64 60 NUXT_MY_PHONE_NUMBER=your_phone_number
NUXT_SUPER_SECRET_SALT=your_secret_salt

View file

@ -2,11 +2,9 @@
<UApp> <UApp>
<div data-theme="night"> <div data-theme="night">
<main> <main>
<!-- The content of the current page will be rendered here -->
<NuxtPage /> <NuxtPage />
</main> </main>
<!-- Footer -->
<footer class="footer p-10 bg-base-300 text-base-content"> <footer class="footer p-10 bg-base-300 text-base-content">
<div> <div>
<span class="footer-title">Social</span> <span class="footer-title">Social</span>
@ -60,10 +58,6 @@
</UApp> </UApp>
</template> </template>
<script setup> <script setup></script>
/* Global */
</script>
<style> <style></style>
/* Global */
</style>

View file

@ -1,32 +1,52 @@
<template> <template>
<div class="max-w-xl mx-auto"> <div class="max-w-xl mx-auto">
<form @submit.prevent="sendTextMessage"> <form @submit.prevent="sendTextMessage">
<!-- Name Input -->
<div class="form-control mb-4"> <div class="form-control mb-4">
<input <input
v-model="userName" v-model="userName"
type="text" type="text"
placeholder="Your Name" placeholder="Your Name"
aria-label="Your Name" aria-label="Your Name"
pattern="^[\x20-\x7E]*$"
class="input input-bordered w-full" class="input input-bordered w-full"
:disabled="isMessageSent" :disabled="isMessageSent"
required required
@input="trackActivity('k')"
/>
</div>
<div
class="form-control"
style="
position: absolute;
left: -9999px;
opacity: 0;
pointer-events: none;
"
>
<input
v-model="website"
type="text"
name="website"
placeholder="Website"
tabindex="-1"
autocomplete="off"
/> />
</div> </div>
<!-- Message Textarea -->
<div class="form-control mb-4"> <div class="form-control mb-4">
<textarea <textarea
v-model="userMessage" v-model="userMessage"
class="textarea textarea-bordered h-32 w-full" class="textarea textarea-bordered h-32 w-full"
placeholder="Your message..." placeholder="Your message..."
aria-label="Your message..." aria-label="Your message (only printable ASCII characters allowed)"
:disabled="isMessageSent" :disabled="isMessageSent"
maxlength="140" maxlength="140"
pattern="^[\x20-\x7E\n\r]*$" pattern="^[\x20-\x7E\n\r]*$"
title="Only printable ASCII characters are allowed." title="Only printable ASCII characters are allowed."
required required
></textarea> @input="trackActivity('k')"
/>
<div <div
class="text-right text-sm mt-1" class="text-right text-sm mt-1"
:class="{ 'text-error': userMessage.length > 140 }" :class="{ 'text-error': userMessage.length > 140 }"
@ -35,7 +55,6 @@
</div> </div>
</div> </div>
<!-- Phone Number and Verification (conditionally enabled) -->
<div class="flex flex-col md:flex-row gap-4 mb-4"> <div class="flex flex-col md:flex-row gap-4 mb-4">
<div class="form-control w-full md:w-1/2"> <div class="form-control w-full md:w-1/2">
<div class="join w-full"> <div class="join w-full">
@ -59,7 +78,7 @@
" "
@click="sendCode" @click="sendCode"
> >
<span v-if="isSendingCode" class="loading loading-spinner"></span> <span v-if="isSendingCode" class="loading loading-spinner" />
Send Code Send Code
</button> </button>
</div> </div>
@ -80,14 +99,13 @@
:disabled="!isCodeSent || isVerified || isVerifying" :disabled="!isCodeSent || isVerified || isVerifying"
@click="verifyCode" @click="verifyCode"
> >
<span v-if="isVerifying" class="loading loading-spinner"></span> <span v-if="isVerifying" class="loading loading-spinner" />
Verify Verify
</button> </button>
</div> </div>
</div> </div>
</div> </div>
<!-- Submit and Status Messages -->
<div class="text-center"> <div class="text-center">
<div v-if="errorMessage" class="alert alert-error mb-4"> <div v-if="errorMessage" class="alert alert-error mb-4">
<svg <svg
@ -126,7 +144,7 @@
class="btn btn-primary w-full" class="btn btn-primary w-full"
:disabled="!isVerified || isSendingMessage || isMessageSent" :disabled="!isVerified || isSendingMessage || isMessageSent"
> >
<span v-if="isSendingMessage" class="loading loading-spinner"></span> <span v-if="isSendingMessage" class="loading loading-spinner" />
Text Me! (Rob ) Text Me! (Rob )
</button> </button>
</div> </div>
@ -135,15 +153,14 @@
</template> </template>
<script setup> <script setup>
import { ref, computed } from "vue"; import { ref, computed, onMounted } from "vue";
// --- Form State ---
const userName = ref(""); const userName = ref("");
const phoneNumber = ref(""); const phoneNumber = ref("");
const verificationCode = ref(""); const verificationCode = ref("");
const userMessage = ref(""); const userMessage = ref("");
const website = ref("");
// --- UI State ---
const isSendingCode = ref(false); const isSendingCode = ref(false);
const isCodeSent = ref(false); const isCodeSent = ref(false);
const isVerifying = ref(false); const isVerifying = ref(false);
@ -152,24 +169,24 @@ const isSendingMessage = ref(false);
const isMessageSent = ref(false); const isMessageSent = ref(false);
const errorMessage = ref(""); const errorMessage = ref("");
// --- Computed Properties --- const formStartTime = ref(0);
const hasInteracted = ref(false);
const mouseActivity = ref(0);
const keyboardActivity = ref(0);
const isNameAndMessageEntered = computed(() => { const isNameAndMessageEntered = computed(() => {
const printableAsciiRegex = /^[\x20-\x7E\n\r]*$/;
return ( return (
userName.value.trim() !== "" && userName.value.trim() !== "" &&
userMessage.value.trim() !== "" && userMessage.value.trim() !== "" &&
userMessage.value.length <= 140 && userMessage.value.length <= 140
printableAsciiRegex.test(userMessage.value)
); );
}); });
const isPhoneNumberIncomplete = computed(() => { const isPhoneNumberIncomplete = computed(() => {
// Count only the digits in the phone number
const digitCount = (phoneNumber.value.match(/\d/g) || []).length; const digitCount = (phoneNumber.value.match(/\d/g) || []).length;
return digitCount < 10; return digitCount < 10 || digitCount > 11;
}); });
// --- Functions ---
const clearError = () => { const clearError = () => {
errorMessage.value = ""; errorMessage.value = "";
}; };
@ -177,12 +194,14 @@ const clearError = () => {
const sendCode = async () => { const sendCode = async () => {
clearError(); clearError();
if (!phoneNumber.value) { if (!phoneNumber.value) {
errorMessage.value = "Please enter a valid phone number."; errorMessage.value = "Please enter a valid US phone number.";
return; return;
} }
isSendingCode.value = true; isSendingCode.value = true;
try { try {
const response = await $fetch("/api/send-otp", { const endpoint = atob("L2FwaS9zZW5kLW90cA==");
console.log("Using endpoint", endpoint);
const response = await $fetch(endpoint, {
method: "POST", method: "POST",
body: { phoneNumber: phoneNumber.value }, body: { phoneNumber: phoneNumber.value },
}); });
@ -207,7 +226,9 @@ const verifyCode = async () => {
} }
isVerifying.value = true; isVerifying.value = true;
try { try {
const response = await $fetch("/api/verify-otp", { const endpoint = atob("L2FwaS92ZXJpZnktb3Rw");
console.log("Using endpoint", endpoint);
const response = await $fetch(endpoint, {
method: "POST", method: "POST",
body: { body: {
code: verificationCode.value, code: verificationCode.value,
@ -216,7 +237,7 @@ const verifyCode = async () => {
}); });
if (response.success) { if (response.success) {
isVerified.value = true; isVerified.value = true;
errorMessage.value = ""; // Clear error on success errorMessage.value = "";
} }
} catch (error) { } catch (error) {
errorMessage.value = errorMessage.value =
@ -229,6 +250,7 @@ const verifyCode = async () => {
const sendTextMessage = async () => { const sendTextMessage = async () => {
clearError(); clearError();
if (!isNameAndMessageEntered.value) { if (!isNameAndMessageEntered.value) {
errorMessage.value = errorMessage.value =
"Please fill out your name and a valid message before sending."; "Please fill out your name and a valid message before sending.";
@ -237,13 +259,21 @@ const sendTextMessage = async () => {
isSendingMessage.value = true; isSendingMessage.value = true;
try { try {
const response = await $fetch("/api/send-message", { const endpoint = atob("L2FwaS9zZW5kLW1lc3NhZ2U=");
console.log("Using endpoint", endpoint);
const response = await $fetch(endpoint, {
method: "POST", method: "POST",
body: { body: {
name: userName.value, name: userName.value,
message: userMessage.value, message: userMessage.value,
phoneNumber: phoneNumber.value, phoneNumber: phoneNumber.value,
code: verificationCode.value, code: verificationCode.value,
website: website.value,
interactionData: {
timeSpent: Date.now() - formStartTime.value,
mouseActivity: mouseActivity.value,
keyboardActivity: keyboardActivity.value,
},
}, },
}); });
if (response.success) { if (response.success) {
@ -259,4 +289,25 @@ const sendTextMessage = async () => {
isSendingMessage.value = false; isSendingMessage.value = false;
} }
}; };
const trackActivity = (type) => {
if (type === "m") mouseActivity.value++;
if (type === "k") keyboardActivity.value++;
hasInteracted.value = true;
};
onMounted(() => {
formStartTime.value = Date.now();
const events = [
["mousemove", () => trackActivity("m")],
["click", () => trackActivity("m")],
["keydown", () => trackActivity("k")],
["keyup", () => trackActivity("k")],
];
events.forEach(([event, handler]) => {
document.addEventListener(event, handler, { passive: true });
});
});
</script> </script>

View file

@ -1,20 +1,19 @@
<template> <template>
<!-- Project Card -->
<div class="card bg-base-100 shadow-xl"> <div class="card bg-base-100 shadow-xl">
<div class="card-body"> <div class="card-body">
<h2 class="card-title">{{ title }}</h2> <h2 class="card-title">{{ title }}</h2>
<p>{{ description }}</p> <p>{{ description }}</p>
<div class="card-actions justify-end"> <div class="card-actions justify-end">
<button <button
v-if="liveDemoLink" v-if="liveDemoLink"
class="btn btn-primary" class="btn btn-primary"
@click="openLink(liveDemoLink)" @click="openLink(liveDemoLink)"
> >
Live Demo Live Demo
</button> </button>
<button <button
v-if="sourceCodeLink" v-if="sourceCodeLink"
class="btn btn-secondary" class="btn btn-secondary"
@click="openLink(sourceCodeLink)" @click="openLink(sourceCodeLink)"
> >
Source Code Source Code
@ -25,7 +24,7 @@
</template> </template>
<script setup> <script setup>
const props = defineProps({ defineProps({
title: { type: String, default: "Lorem Ipsum" }, title: { type: String, default: "Lorem Ipsum" },
description: { description: {
type: String, type: String,
@ -35,9 +34,7 @@ const props = defineProps({
liveDemoLink: { type: [String, null], default: null }, liveDemoLink: { type: [String, null], default: null },
sourceCodeLink: { type: [String, null], default: null }, sourceCodeLink: { type: [String, null], default: null },
}); });
</script>
<script>
function openLink(url) { function openLink(url) {
window.open(url, "_blank"); window.open(url, "_blank");
} }

View file

@ -1,19 +1,18 @@
<template> <template>
<div> <div>
<!-- Hero Section --> <section class="hero min-h-screen bg-base-200 relative overflow-hidden">
<section class="hero min-h-screen bg-base-200"> <div class="absolute inset-0 z-0 animated-background"></div>
<div class="hero-content text-center"> <div class="hero-content text-center relative z-10">
<div class="max-w-md"> <div class="max-w-md">
<h1 class="text-5xl font-bold"> <h1 class="text-5xl font-bold">
Hi, I'm <span class="text-primary">Rob</span>! Hi, I'm <span class="text-primary">Rob</span>!
</h1> </h1>
<p class="py-6 text-2xl">I'm <span id="typed-text"></span></p> <p class="py-6 text-2xl">I'm <span id="typed-text" /></p>
<button class="btn btn-primary">View My Work</button> <button class="btn btn-primary">View My Work</button>
</div> </div>
</div> </div>
</section> </section>
<!-- About Me Section -->
<section id="about" class="py-20 bg-base-100"> <section id="about" class="py-20 bg-base-100">
<div class="container mx-auto px-4"> <div class="container mx-auto px-4">
<h2 class="text-4xl font-bold text-center mb-12">About Me</h2> <h2 class="text-4xl font-bold text-center mb-12">About Me</h2>
@ -51,7 +50,6 @@
</div> </div>
</div> </div>
</section> </section>
<!-- Current Projects Section -->
<section id="projects" class="py-20 bg-base-200"> <section id="projects" class="py-20 bg-base-200">
<div class="container mx-auto px-4"> <div class="container mx-auto px-4">
<h2 class="text-4xl font-bold text-center mb-12">Current Projects</h2> <h2 class="text-4xl font-bold text-center mb-12">Current Projects</h2>
@ -60,13 +58,16 @@
title="PKMNTradeClub" title="PKMNTradeClub"
description="A web app to facilitate trading between players of Pokémon TCG Pocket, which frustratingly lacks trade matching features. Currently in development!" description="A web app to facilitate trading between players of Pokémon TCG Pocket, which frustratingly lacks trade matching features. Currently in development!"
/> />
<ProjectCard
title="Home Lab & Self-Hosted Solutions"
description="A collection of hardware, projects, and experiments to learn and explore new technologies and concepts, as well as augment and enhance my personal tech space."
/>
</div> </div>
</div> </div>
</section> </section>
<!-- Inactive Projects Section -->
<section id="projects" class="py-20 bg-base-200"> <section id="projects" class="py-20 bg-base-200">
<div class="container mx-auto px-4"> <div class="container mx-auto px-4">
<h2 class="text-4xl font-bold text-center mb-12">Inactive Projects</h2> <h2 class="text-4xl font-bold text-center mb-12">Past Projects</h2>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8"> <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
<ProjectCard <ProjectCard
title="PokeEmerald Mods" title="PokeEmerald Mods"
@ -84,7 +85,6 @@
</div> </div>
</section> </section>
<!-- Contact Section -->
<section id="contact" class="py-20 bg-base-100"> <section id="contact" class="py-20 bg-base-100">
<div class="container mx-auto px-4"> <div class="container mx-auto px-4">
<h2 class="text-4xl font-bold text-center mb-12">Get In Touch</h2> <h2 class="text-4xl font-bold text-center mb-12">Get In Touch</h2>
@ -134,8 +134,18 @@ onMounted(() => {
</script> </script>
<style> <style>
/* Ensuring the hero section takes the full viewport height */
.min-h-screen { .min-h-screen {
min-height: 100vh; min-height: 100vh;
} }
.hero .hero-content {
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.8);
}
.animated-background {
background-image: url("/NZclouds.webp"), url("/NZclouds-static.png");
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
</style> </style>

View file

@ -1,19 +1,16 @@
import ScrollReveal from 'scrollreveal'; import ScrollReveal from "scrollreveal";
export default defineNuxtPlugin((nuxtApp) => { export default defineNuxtPlugin((nuxtApp) => {
const defaultOptions = { const defaultOptions = {
origin: 'bottom', origin: "bottom",
distance: '80px', distance: "80px",
duration: 1000, duration: 1000,
delay: 200, delay: 200,
easing: 'cubic-bezier(0.5, 0, 0, 1)', easing: "cubic-bezier(0.5, 0, 0, 1)",
reset: true, reset: true,
}; };
const sr = ScrollReveal(defaultOptions); const sr = ScrollReveal(defaultOptions);
// You can make it available to the rest of your Nuxt application nuxtApp.provide("sr", sr);
// by returning it in the `provide` object.
// This makes it accessible as `$sr` in your components.
nuxtApp.provide('sr', sr);
}); });

View file

@ -17,6 +17,8 @@
"better-sqlite3": "^12.2.0", "better-sqlite3": "^12.2.0",
"daisyui": "^5.0.46", "daisyui": "^5.0.46",
"eslint": "^9.0.0", "eslint": "^9.0.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.3",
"husky": "^9.1.7", "husky": "^9.1.7",
"nuxt": "^4.0.0", "nuxt": "^4.0.0",
"otplib": "^12.0.1", "otplib": "^12.0.1",
@ -457,6 +459,8 @@
"@pkgjs/parseargs": ["@pkgjs/parseargs@0.11.0", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="], "@pkgjs/parseargs": ["@pkgjs/parseargs@0.11.0", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="],
"@pkgr/core": ["@pkgr/core@0.2.9", "", {}, "sha512-QNqXyfVS2wm9hweSYD2O7F0G06uurj9kZ96TRQE5Y9hU7+tgdZwIkbAKc5Ocy1HxEY2kuDQa6cQ1WRs/O5LFKA=="],
"@polka/url": ["@polka/url@1.0.0-next.29", "", {}, "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww=="], "@polka/url": ["@polka/url@1.0.0-next.29", "", {}, "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww=="],
"@poppinss/colors": ["@poppinss/colors@4.1.5", "", { "dependencies": { "kleur": "^4.1.5" } }, "sha512-FvdDqtcRCtz6hThExcFOgW0cWX+xwSMWcRuQe5ZEb2m7cVQOAVZOIMt+/v9RxGiD9/OY16qJBXK4CVKWAPalBw=="], "@poppinss/colors": ["@poppinss/colors@4.1.5", "", { "dependencies": { "kleur": "^4.1.5" } }, "sha512-FvdDqtcRCtz6hThExcFOgW0cWX+xwSMWcRuQe5ZEb2m7cVQOAVZOIMt+/v9RxGiD9/OY16qJBXK4CVKWAPalBw=="],
@ -1111,6 +1115,8 @@
"eslint-config-flat-gitignore": ["eslint-config-flat-gitignore@2.1.0", "", { "dependencies": { "@eslint/compat": "^1.2.5" }, "peerDependencies": { "eslint": "^9.5.0" } }, "sha512-cJzNJ7L+psWp5mXM7jBX+fjHtBvvh06RBlcweMhKD8jWqQw0G78hOW5tpVALGHGFPsBV+ot2H+pdDGJy6CV8pA=="], "eslint-config-flat-gitignore": ["eslint-config-flat-gitignore@2.1.0", "", { "dependencies": { "@eslint/compat": "^1.2.5" }, "peerDependencies": { "eslint": "^9.5.0" } }, "sha512-cJzNJ7L+psWp5mXM7jBX+fjHtBvvh06RBlcweMhKD8jWqQw0G78hOW5tpVALGHGFPsBV+ot2H+pdDGJy6CV8pA=="],
"eslint-config-prettier": ["eslint-config-prettier@10.1.8", "", { "peerDependencies": { "eslint": ">=7.0.0" }, "bin": { "eslint-config-prettier": "bin/cli.js" } }, "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w=="],
"eslint-flat-config-utils": ["eslint-flat-config-utils@2.1.0", "", { "dependencies": { "pathe": "^2.0.3" } }, "sha512-6fjOJ9tS0k28ketkUcQ+kKptB4dBZY2VijMZ9rGn8Cwnn1SH0cZBoPXT8AHBFHxmHcLFQK9zbELDinZ2Mr1rng=="], "eslint-flat-config-utils": ["eslint-flat-config-utils@2.1.0", "", { "dependencies": { "pathe": "^2.0.3" } }, "sha512-6fjOJ9tS0k28ketkUcQ+kKptB4dBZY2VijMZ9rGn8Cwnn1SH0cZBoPXT8AHBFHxmHcLFQK9zbELDinZ2Mr1rng=="],
"eslint-merge-processors": ["eslint-merge-processors@2.0.0", "", { "peerDependencies": { "eslint": "*" } }, "sha512-sUuhSf3IrJdGooquEUB5TNpGNpBoQccbnaLHsb1XkBLUPPqCNivCpY05ZcpCOiV9uHwO2yxXEWVczVclzMxYlA=="], "eslint-merge-processors": ["eslint-merge-processors@2.0.0", "", { "peerDependencies": { "eslint": "*" } }, "sha512-sUuhSf3IrJdGooquEUB5TNpGNpBoQccbnaLHsb1XkBLUPPqCNivCpY05ZcpCOiV9uHwO2yxXEWVczVclzMxYlA=="],
@ -1119,6 +1125,8 @@
"eslint-plugin-jsdoc": ["eslint-plugin-jsdoc@51.4.1", "", { "dependencies": { "@es-joy/jsdoccomment": "~0.52.0", "are-docs-informative": "^0.0.2", "comment-parser": "1.4.1", "debug": "^4.4.1", "escape-string-regexp": "^4.0.0", "espree": "^10.4.0", "esquery": "^1.6.0", "parse-imports-exports": "^0.2.4", "semver": "^7.7.2", "spdx-expression-parse": "^4.0.0" }, "peerDependencies": { "eslint": "^7.0.0 || ^8.0.0 || ^9.0.0" } }, "sha512-y4CA9OkachG8v5nAtrwvcvjIbdcKgSyS6U//IfQr4FZFFyeBFwZFf/tfSsMr46mWDJgidZjBTqoCRlXywfFBMg=="], "eslint-plugin-jsdoc": ["eslint-plugin-jsdoc@51.4.1", "", { "dependencies": { "@es-joy/jsdoccomment": "~0.52.0", "are-docs-informative": "^0.0.2", "comment-parser": "1.4.1", "debug": "^4.4.1", "escape-string-regexp": "^4.0.0", "espree": "^10.4.0", "esquery": "^1.6.0", "parse-imports-exports": "^0.2.4", "semver": "^7.7.2", "spdx-expression-parse": "^4.0.0" }, "peerDependencies": { "eslint": "^7.0.0 || ^8.0.0 || ^9.0.0" } }, "sha512-y4CA9OkachG8v5nAtrwvcvjIbdcKgSyS6U//IfQr4FZFFyeBFwZFf/tfSsMr46mWDJgidZjBTqoCRlXywfFBMg=="],
"eslint-plugin-prettier": ["eslint-plugin-prettier@5.5.3", "", { "dependencies": { "prettier-linter-helpers": "^1.0.0", "synckit": "^0.11.7" }, "peerDependencies": { "@types/eslint": ">=8.0.0", "eslint": ">=8.0.0", "eslint-config-prettier": ">= 7.0.0 <10.0.0 || >=10.1.0", "prettier": ">=3.0.0" }, "optionalPeers": ["@types/eslint", "eslint-config-prettier"] }, "sha512-NAdMYww51ehKfDyDhv59/eIItUVzU0Io9H2E8nHNGKEeeqlnci+1gCvrHib6EmZdf6GxF+LCV5K7UC65Ezvw7w=="],
"eslint-plugin-regexp": ["eslint-plugin-regexp@2.9.0", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.11.0", "comment-parser": "^1.4.0", "jsdoc-type-pratt-parser": "^4.0.0", "refa": "^0.12.1", "regexp-ast-analysis": "^0.7.1", "scslre": "^0.3.0" }, "peerDependencies": { "eslint": ">=8.44.0" } }, "sha512-9WqJMnOq8VlE/cK+YAo9C9YHhkOtcEtEk9d12a+H7OSZFwlpI6stiHmYPGa2VE0QhTzodJyhlyprUaXDZLgHBw=="], "eslint-plugin-regexp": ["eslint-plugin-regexp@2.9.0", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.11.0", "comment-parser": "^1.4.0", "jsdoc-type-pratt-parser": "^4.0.0", "refa": "^0.12.1", "regexp-ast-analysis": "^0.7.1", "scslre": "^0.3.0" }, "peerDependencies": { "eslint": ">=8.44.0" } }, "sha512-9WqJMnOq8VlE/cK+YAo9C9YHhkOtcEtEk9d12a+H7OSZFwlpI6stiHmYPGa2VE0QhTzodJyhlyprUaXDZLgHBw=="],
"eslint-plugin-unicorn": ["eslint-plugin-unicorn@59.0.1", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.25.9", "@eslint-community/eslint-utils": "^4.5.1", "@eslint/plugin-kit": "^0.2.7", "ci-info": "^4.2.0", "clean-regexp": "^1.0.0", "core-js-compat": "^3.41.0", "esquery": "^1.6.0", "find-up-simple": "^1.0.1", "globals": "^16.0.0", "indent-string": "^5.0.0", "is-builtin-module": "^5.0.0", "jsesc": "^3.1.0", "pluralize": "^8.0.0", "regexp-tree": "^0.1.27", "regjsparser": "^0.12.0", "semver": "^7.7.1", "strip-indent": "^4.0.0" }, "peerDependencies": { "eslint": ">=9.22.0" } }, "sha512-EtNXYuWPUmkgSU2E7Ttn57LbRREQesIP1BiLn7OZLKodopKfDXfBUkC/0j6mpw2JExwf43Uf3qLSvrSvppgy8Q=="], "eslint-plugin-unicorn": ["eslint-plugin-unicorn@59.0.1", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.25.9", "@eslint-community/eslint-utils": "^4.5.1", "@eslint/plugin-kit": "^0.2.7", "ci-info": "^4.2.0", "clean-regexp": "^1.0.0", "core-js-compat": "^3.41.0", "esquery": "^1.6.0", "find-up-simple": "^1.0.1", "globals": "^16.0.0", "indent-string": "^5.0.0", "is-builtin-module": "^5.0.0", "jsesc": "^3.1.0", "pluralize": "^8.0.0", "regexp-tree": "^0.1.27", "regjsparser": "^0.12.0", "semver": "^7.7.1", "strip-indent": "^4.0.0" }, "peerDependencies": { "eslint": ">=9.22.0" } }, "sha512-EtNXYuWPUmkgSU2E7Ttn57LbRREQesIP1BiLn7OZLKodopKfDXfBUkC/0j6mpw2JExwf43Uf3qLSvrSvppgy8Q=="],
@ -1167,6 +1175,8 @@
"fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
"fast-diff": ["fast-diff@1.3.0", "", {}, "sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw=="],
"fast-fifo": ["fast-fifo@1.3.2", "", {}, "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ=="], "fast-fifo": ["fast-fifo@1.3.2", "", {}, "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ=="],
"fast-glob": ["fast-glob@3.3.3", "", { "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.8" } }, "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg=="], "fast-glob": ["fast-glob@3.3.3", "", { "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.8" } }, "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg=="],
@ -1895,6 +1905,8 @@
"prettier": ["prettier@3.6.2", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ=="], "prettier": ["prettier@3.6.2", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ=="],
"prettier-linter-helpers": ["prettier-linter-helpers@1.0.0", "", { "dependencies": { "fast-diff": "^1.1.2" } }, "sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w=="],
"pretty-bytes": ["pretty-bytes@6.1.1", "", {}, "sha512-mQUvGU6aUFQ+rNvTIAcZuWGRT9a6f6Yrg9bHs4ImKF+HZCEK+plBvnAZYSIQztknZF2qnzNtr6F8s0+IuptdlQ=="], "pretty-bytes": ["pretty-bytes@6.1.1", "", {}, "sha512-mQUvGU6aUFQ+rNvTIAcZuWGRT9a6f6Yrg9bHs4ImKF+HZCEK+plBvnAZYSIQztknZF2qnzNtr6F8s0+IuptdlQ=="],
"process": ["process@0.11.10", "", {}, "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A=="], "process": ["process@0.11.10", "", {}, "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A=="],
@ -2139,6 +2151,8 @@
"svgo": ["svgo@3.3.2", "", { "dependencies": { "@trysound/sax": "0.2.0", "commander": "^7.2.0", "css-select": "^5.1.0", "css-tree": "^2.3.1", "css-what": "^6.1.0", "csso": "^5.0.5", "picocolors": "^1.0.0" }, "bin": "./bin/svgo" }, "sha512-OoohrmuUlBs8B8o6MB2Aevn+pRIH9zDALSR+6hhqVfa6fRwG/Qw9VUMSMW9VNg2CFc/MTIfabtdOVl9ODIJjpw=="], "svgo": ["svgo@3.3.2", "", { "dependencies": { "@trysound/sax": "0.2.0", "commander": "^7.2.0", "css-select": "^5.1.0", "css-tree": "^2.3.1", "css-what": "^6.1.0", "csso": "^5.0.5", "picocolors": "^1.0.0" }, "bin": "./bin/svgo" }, "sha512-OoohrmuUlBs8B8o6MB2Aevn+pRIH9zDALSR+6hhqVfa6fRwG/Qw9VUMSMW9VNg2CFc/MTIfabtdOVl9ODIJjpw=="],
"synckit": ["synckit@0.11.11", "", { "dependencies": { "@pkgr/core": "^0.2.9" } }, "sha512-MeQTA1r0litLUf0Rp/iisCaL8761lKAZHaimlbGK4j0HysC4PLfqygQj9srcs0m2RdtDYnF8UuYyKpbjHYp7Jw=="],
"system-architecture": ["system-architecture@0.1.0", "", {}, "sha512-ulAk51I9UVUyJgxlv9M6lFot2WP3e7t8Kz9+IS6D4rVba1tR9kON+Ey69f+1R4Q8cd45Lod6a4IcJIxnzGc/zA=="], "system-architecture": ["system-architecture@0.1.0", "", {}, "sha512-ulAk51I9UVUyJgxlv9M6lFot2WP3e7t8Kz9+IS6D4rVba1tR9kON+Ey69f+1R4Q8cd45Lod6a4IcJIxnzGc/zA=="],
"tailwind-merge": ["tailwind-merge@3.0.2", "", {}, "sha512-l7z+OYZ7mu3DTqrL88RiKrKIqO3NcpEO8V/Od04bNpvk0kiIFndGEoqfuzvj4yuhRkHKjRkII2z+KS2HfPcSxw=="], "tailwind-merge": ["tailwind-merge@3.0.2", "", {}, "sha512-l7z+OYZ7mu3DTqrL88RiKrKIqO3NcpEO8V/Od04bNpvk0kiIFndGEoqfuzvj4yuhRkHKjRkII2z+KS2HfPcSxw=="],

View file

@ -1,6 +1,11 @@
// @ts-check import { fileURLToPath } from "url";
import withNuxt from '.nuxt/eslint.config.mjs' import { dirname, resolve } from "path";
import eslintPluginPrettierRecommended from "eslint-plugin-prettier/recommended";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export default withNuxt( const { withNuxt } = await import(
// Your custom configs here resolve(__dirname, ".nuxt/eslint.config.mjs")
) );
export default withNuxt([eslintPluginPrettierRecommended]);

View file

@ -1,4 +1,3 @@
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({ export default defineNuxtConfig({
compatibilityDate: "2025-05-15", compatibilityDate: "2025-05-15",
devtools: { devtools: {
@ -26,7 +25,6 @@ export default defineNuxtConfig({
myPhoneNumber: process.env.NUXT_MY_PHONE_NUMBER, myPhoneNumber: process.env.NUXT_MY_PHONE_NUMBER,
superSecretSalt: process.env.NUXT_SUPER_SECRET_SALT, superSecretSalt: process.env.NUXT_SUPER_SECRET_SALT,
// Keys within public, will be also exposed to the client-side
public: {}, public: {},
}, },
}); });

View file

@ -23,6 +23,8 @@
"better-sqlite3": "^12.2.0", "better-sqlite3": "^12.2.0",
"daisyui": "^5.0.46", "daisyui": "^5.0.46",
"eslint": "^9.0.0", "eslint": "^9.0.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.3",
"husky": "^9.1.7", "husky": "^9.1.7",
"nuxt": "^4.0.0", "nuxt": "^4.0.0",
"otplib": "^12.0.1", "otplib": "^12.0.1",

BIN
public/NZclouds-static.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 377 KiB

BIN
public/NZclouds.webp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 MiB

View file

@ -10,6 +10,8 @@ export default defineEventHandler(async (event) => {
message: userMessage, message: userMessage,
phoneNumber: rawPhoneNumber, phoneNumber: rawPhoneNumber,
code, code,
interactionData,
website,
} = await readBody(event); } = await readBody(event);
let phoneNumber; let phoneNumber;
@ -19,7 +21,32 @@ export default defineEventHandler(async (event) => {
throw createError({ statusCode: 400, statusMessage: error.message }); throw createError({ statusCode: 400, statusMessage: error.message });
} }
// --- Input Validation --- if (website) {
throw createError({
statusCode: 400,
statusMessage: "Spam detected.",
});
}
if (interactionData) {
if (interactionData.timeSpent < 3000) {
throw createError({
statusCode: 400,
statusMessage: "Submission too fast.",
});
}
if (
interactionData.mouseActivity === 0 &&
interactionData.keyboardActivity === 0
) {
throw createError({
statusCode: 400,
statusMessage: "No user interaction detected.",
});
}
}
if (!name || !userMessage || !code) { if (!name || !userMessage || !code) {
throw createError({ throw createError({
statusCode: 400, statusCode: 400,
@ -27,12 +54,19 @@ export default defineEventHandler(async (event) => {
}); });
} }
// Prevent abuse by checking rate limit before doing anything const nameRegex = /^[a-zA-Z\s'-]{2,50}$/;
if (!nameRegex.test(name.trim())) {
throw createError({
statusCode: 400,
statusMessage: "Name contains invalid characters or format.",
});
}
if (isRateLimited(phoneNumber)) { if (isRateLimited(phoneNumber)) {
throw createError({ throw createError({
statusCode: 429, statusCode: 429,
statusMessage: statusMessage:
"You have already sent a message within the last week. Please try again later.", "You have reached the maximum of 3 messages per week. Please try again later.",
}); });
} }
@ -51,7 +85,50 @@ export default defineEventHandler(async (event) => {
}); });
} }
// --- Server Configuration Check --- if (userMessage.trim().length < 10) {
throw createError({
statusCode: 400,
statusMessage: "Message is too short.",
});
}
const spamKeywords = [
"viagra",
"casino",
"lottery",
"winner",
"click here",
"free money",
"urgent",
"limited time",
];
const hasSpamKeywords = spamKeywords.some((keyword) =>
userMessage.toLowerCase().includes(keyword.toLowerCase()),
);
if (hasSpamKeywords) {
throw createError({
statusCode: 400,
statusMessage: "Message contains inappropriate content.",
});
}
if (/([a-zA-Z])\1{4,}/.test(userMessage)) {
throw createError({
statusCode: 400,
statusMessage: "Message contains excessive repeated characters.",
});
}
const uppercaseRatio =
(userMessage.match(/[A-Z]/g) || []).length / userMessage.length;
if (uppercaseRatio > 0.7 && userMessage.length > 10) {
throw createError({
statusCode: 400,
statusMessage: "Message contains excessive uppercase text.",
});
}
if (!config.myPhoneNumber || !config.superSecretSalt) { if (!config.myPhoneNumber || !config.superSecretSalt) {
console.error( console.error(
"Server is not fully configured. MY_PHONE_NUMBER and SUPER_SECRET_SALT are required.", "Server is not fully configured. MY_PHONE_NUMBER and SUPER_SECRET_SALT are required.",
@ -62,7 +139,6 @@ export default defineEventHandler(async (event) => {
}); });
} }
// --- Verification ---
const isVerified = verifyTOTP(phoneNumber, config.superSecretSalt, code); const isVerified = verifyTOTP(phoneNumber, config.superSecretSalt, code);
if (!isVerified) { if (!isVerified) {
throw createError({ throw createError({
@ -72,7 +148,6 @@ export default defineEventHandler(async (event) => {
}); });
} }
// --- Send Message ---
try { try {
const api = createSmsGatewayClient(config); const api = createSmsGatewayClient(config);
const finalMessage = `New message from ${name} ( ${phoneNumber} ) via your portfolio:\n\n"${userMessage}"`; const finalMessage = `New message from ${name} ( ${phoneNumber} ) via your portfolio:\n\n"${userMessage}"`;
@ -83,7 +158,6 @@ export default defineEventHandler(async (event) => {
const state = await api.send(message); const state = await api.send(message);
// On success, record the submission time to start the rate-limiting period.
recordSubmission(phoneNumber); recordSubmission(phoneNumber);
return { success: true, messageId: state.id }; return { success: true, messageId: state.id };

View file

@ -1,6 +1,10 @@
import { generateTOTP } from "../utils/totp"; import { generateTOTP } from "../utils/totp";
import { createSmsGatewayClient } from "../lib/sms-gateway"; import { createSmsGatewayClient } from "../lib/sms-gateway";
import { isRateLimited } from "../utils/rate-limiter.js"; import {
isRateLimited,
isOtpRateLimited,
recordOtpRequest,
} from "../utils/rate-limiter.js";
import { normalizeAndValidatePhoneNumber } from "../utils/phone-validator.js"; import { normalizeAndValidatePhoneNumber } from "../utils/phone-validator.js";
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
@ -11,16 +15,22 @@ export default defineEventHandler(async (event) => {
try { try {
normalizedPhoneNumber = normalizeAndValidatePhoneNumber(rawPhoneNumber); normalizedPhoneNumber = normalizeAndValidatePhoneNumber(rawPhoneNumber);
} catch (error) { } catch (error) {
// The validator throws an error with a user-friendly message.
throw createError({ statusCode: 400, statusMessage: error.message }); throw createError({ statusCode: 400, statusMessage: error.message });
} }
// Prevent abuse by checking rate limit before sending an SMS if (isOtpRateLimited(normalizedPhoneNumber)) {
throw createError({
statusCode: 429,
statusMessage:
"You have reached the maximum of 3 verification code requests per hour. Please try again later.",
});
}
if (isRateLimited(normalizedPhoneNumber)) { if (isRateLimited(normalizedPhoneNumber)) {
throw createError({ throw createError({
statusCode: 429, statusCode: 429,
statusMessage: statusMessage:
"You have already sent a message within the last week. Please try again later.", "You have reached the maximum of 3 messages per week. Please try again later.",
}); });
} }
@ -44,6 +54,9 @@ export default defineEventHandler(async (event) => {
}; };
const state = await api.send(message); const state = await api.send(message);
recordOtpRequest(normalizedPhoneNumber);
return { success: true, messageId: state.id }; return { success: true, messageId: state.id };
} catch (error) { } catch (error) {
console.error("Failed to send OTP:", error); console.error("Failed to send OTP:", error);

View file

@ -10,7 +10,6 @@ export default defineEventHandler(async (event) => {
try { try {
normalizedPhoneNumber = normalizeAndValidatePhoneNumber(rawPhoneNumber); normalizedPhoneNumber = normalizeAndValidatePhoneNumber(rawPhoneNumber);
} catch (error) { } catch (error) {
// The validator throws an error with a user-friendly message.
throw createError({ statusCode: 400, statusMessage: error.message }); throw createError({ statusCode: 400, statusMessage: error.message });
} }
@ -21,7 +20,6 @@ export default defineEventHandler(async (event) => {
}); });
} }
// Prevent abuse by checking rate limit before doing anything
if (isRateLimited(normalizedPhoneNumber)) { if (isRateLimited(normalizedPhoneNumber)) {
throw createError({ throw createError({
statusCode: 429, statusCode: 429,
@ -30,10 +28,8 @@ export default defineEventHandler(async (event) => {
}); });
} }
// Check for necessary server configuration.
if (!config.superSecretSalt) { if (!config.superSecretSalt) {
console.error("SUPER_SECRET_SALT is not configured on the server."); console.error("SUPER_SECRET_SALT is not configured on the server.");
// This is an internal server error, so we don't expose details to the client.
throw createError({ throw createError({
statusCode: 500, statusCode: 500,
statusMessage: "A server configuration error occurred.", statusMessage: "A server configuration error occurred.",
@ -47,10 +43,8 @@ export default defineEventHandler(async (event) => {
); );
if (isValid) { if (isValid) {
// In a stateful app, one might set a session cookie here.
return { success: true }; return { success: true };
} else { } else {
// The code is incorrect or has expired.
throw createError({ throw createError({
statusCode: 401, // Unauthorized statusCode: 401, // Unauthorized
statusMessage: "Invalid or expired verification code.", statusMessage: "Invalid or expired verification code.",

View file

@ -28,8 +28,6 @@ export function createSmsGatewayClient(config) {
console.error( console.error(
"SMS Gateway service is not configured. Missing required environment variables for the gateway.", "SMS Gateway service is not configured. Missing required environment variables for the gateway.",
); );
// This indicates a critical server misconfiguration. The calling API endpoint
// should handle this and return a generic 500 error to the client.
throw new Error("Server is not configured for sending SMS."); throw new Error("Server is not configured for sending SMS.");
} }

View file

@ -18,16 +18,13 @@ export function normalizeAndValidatePhoneNumber(rawPhoneNumber) {
throw new Error("Phone number is required."); throw new Error("Phone number is required.");
} }
// 1. Strip all non-digit characters.
const digitsOnly = rawPhoneNumber.replace(/\D/g, ""); const digitsOnly = rawPhoneNumber.replace(/\D/g, "");
// 2. If the number starts with a '1', remove it.
let numberToValidate = digitsOnly; let numberToValidate = digitsOnly;
if (numberToValidate.startsWith("1")) { if (numberToValidate.startsWith("1")) {
numberToValidate = numberToValidate.substring(1); numberToValidate = numberToValidate.substring(1);
} }
// 3. Check if the resulting number is exactly 10 digits long.
if (numberToValidate.length !== 10) { if (numberToValidate.length !== 10) {
throw new Error("Please provide a valid 10-digit phone number."); throw new Error("Please provide a valid 10-digit phone number.");
} }

View file

@ -1,33 +1,99 @@
// A shared, in-memory store for tracking submission timestamps.
const submissionTimestamps = new Map(); const submissionTimestamps = new Map();
// The rate-limiting period (1 week in milliseconds). const otpRequestTimestamps = new Map();
const ONE_WEEK_IN_MS = 7 * 24 * 60 * 60 * 1000; const ONE_WEEK_IN_MS = 7 * 24 * 60 * 60 * 1000;
const ONE_HOUR_IN_MS = 60 * 60 * 1000;
const MAX_OTP_REQUESTS_PER_HOUR = 3;
const MAX_MESSAGES_PER_WEEK = 3;
/** /**
* Checks if a given phone number is currently rate-limited. * Checks if a given phone number is currently rate-limited for message submissions.
* A phone number is considered rate-limited if a successful submission * A phone number is considered rate-limited if it has made 3 or more message submissions
* was recorded within the last week. * within the last week.
* *
* @param {string} phoneNumber The phone number to check. * @param {string} phoneNumber The phone number to check.
* @returns {boolean} True if the number is rate-limited, false otherwise. * @returns {boolean} True if the number is rate-limited, false otherwise.
*/ */
export function isRateLimited(phoneNumber) { export function isRateLimited(phoneNumber) {
const lastSubmissionTime = submissionTimestamps.get(phoneNumber); const submissionTimestampsArray = submissionTimestamps.get(phoneNumber);
if (!lastSubmissionTime) { if (!submissionTimestampsArray || submissionTimestampsArray.length === 0) {
return false; // Not in the map, so not rate-limited. return false;
} }
// Check if the time elapsed since the last submission is less than one week. const now = Date.now();
return Date.now() - lastSubmissionTime < ONE_WEEK_IN_MS; const recentSubmissions = submissionTimestampsArray.filter(
(timestamp) => now - timestamp < ONE_WEEK_IN_MS,
);
if (recentSubmissions.length !== submissionTimestampsArray.length) {
submissionTimestamps.set(phoneNumber, recentSubmissions);
}
return recentSubmissions.length >= MAX_MESSAGES_PER_WEEK;
} }
/** /**
* Records a successful submission for a given phone number by setting * Records a successful submission for a given phone number by adding
* the current timestamp. This will start the 1-week rate-limiting period. * the current timestamp to the submission history.
* *
* @param {string} phoneNumber The phone number to record the submission for. * @param {string} phoneNumber The phone number to record the submission for.
*/ */
export function recordSubmission(phoneNumber) { export function recordSubmission(phoneNumber) {
submissionTimestamps.set(phoneNumber, Date.now()); const now = Date.now();
const existingSubmissions = submissionTimestamps.get(phoneNumber) || [];
const recentSubmissions = existingSubmissions.filter(
(timestamp) => now - timestamp < ONE_WEEK_IN_MS,
);
recentSubmissions.push(now);
submissionTimestamps.set(phoneNumber, recentSubmissions);
}
/**
* Checks if a given phone number is currently rate-limited for OTP requests.
* A phone number is considered rate-limited if it has made 3 or more OTP requests
* within the last hour.
*
* @param {string} phoneNumber The phone number to check.
* @returns {boolean} True if the number is rate-limited for OTP, false otherwise.
*/
export function isOtpRateLimited(phoneNumber) {
const requestTimestamps = otpRequestTimestamps.get(phoneNumber);
if (!requestTimestamps || requestTimestamps.length === 0) {
return false;
}
const now = Date.now();
const recentRequests = requestTimestamps.filter(
(timestamp) => now - timestamp < ONE_HOUR_IN_MS,
);
if (recentRequests.length !== requestTimestamps.length) {
otpRequestTimestamps.set(phoneNumber, recentRequests);
}
return recentRequests.length >= MAX_OTP_REQUESTS_PER_HOUR;
}
/**
* Records an OTP request for a given phone number by adding
* the current timestamp to the request history.
*
* @param {string} phoneNumber The phone number to record the OTP request for.
*/
export function recordOtpRequest(phoneNumber) {
const now = Date.now();
const existingRequests = otpRequestTimestamps.get(phoneNumber) || [];
const recentRequests = existingRequests.filter(
(timestamp) => now - timestamp < ONE_HOUR_IN_MS,
);
recentRequests.push(now);
otpRequestTimestamps.set(phoneNumber, recentRequests);
} }

View file

@ -1,10 +1,9 @@
import { authenticator } from "otplib"; import { authenticator } from "otplib";
import { createHash } from "crypto"; import { createHash } from "crypto";
// These settings must be consistent between generation and verification.
authenticator.options = { authenticator.options = {
step: 60, // OTP is valid for 1 minute per window step: 60,
window: [5, 1], // Allow tokens from 5 previous and 1 future time-steps. window: [5, 1],
digits: 6, digits: 6,
}; };
@ -46,8 +45,6 @@ export function generateTOTP(phoneNumber, salt) {
*/ */
export function verifyTOTP(phoneNumber, salt, token) { export function verifyTOTP(phoneNumber, salt, token) {
const userSecret = getUserSecret(phoneNumber, salt); const userSecret = getUserSecret(phoneNumber, salt);
// The `verify` method checks the token against the current and adjacent
// time-steps, as configured in the options.
return authenticator.verify({ token, secret: userSecret }); return authenticator.verify({ token, secret: userSecret });
} }