HubAPI / app /actions /waitlist.ts
samirhosninet's picture
feat: update icon system with LobeHub provider logos
d3e44c7
Raw History Blame Contribute Delete
12.6 kB
"use server";
import { headers } from "next/headers";
import crypto from "crypto";
import mysql from "mysql2/promise";
export interface RegistrationResult {
success: boolean;
error?: string;
}
const IS_PRODUCTION = process.env.NODE_ENV === "production";
const SITE_URL = (
process.env.NEXT_PUBLIC_SITE_URL ??
"https://darkslategrey-nightingale-132659.hostingersite.com"
).replace(/\/$/, "");
const getEmailLogId = (emailStr: string): string =>
crypto
.createHash("sha256")
.update(emailStr.trim().toLowerCase())
.digest("hex")
.slice(0, 12);
const getIpHash = (rawIp: string): string | null => {
const salt = process.env.IP_HASH_SALT;
if (!salt && IS_PRODUCTION) {
return null;
}
return crypto
.createHash("sha256")
.update(`${salt ?? "development-only-ip-salt"}:${rawIp}`)
.digest("hex");
};
// Set up MySQL connection pool if environment variables are provided
let pool: mysql.Pool | null = null;
if (process.env.DB_HOST && process.env.DB_USER && process.env.DB_NAME) {
try {
pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
waitForConnections: true,
connectionLimit: 5,
queueLimit: 0,
connectTimeout: 10000,
});
console.log("Successfully initialized MySQL connection pool.");
} catch (err) {
console.error("Failed to initialize MySQL pool:", err);
}
}
// Generate stable ticket number purely based on email
const getTicketNumber = (emailStr: string): string => {
let hash = 0;
for (let i = 0; i < emailStr.length; i++) {
hash = emailStr.charCodeAt(i) + ((hash << 5) - hash);
}
const number = Math.abs(hash % 90000) + 10000;
return `00${number}`.slice(-6).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};
// Ensure MySQL waitlist table exists
async function ensureMySQLTable(connection: mysql.PoolConnection) {
await connection.query(`
CREATE TABLE IF NOT EXISTS waitlist (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
timestamp VARCHAR(255) NOT NULL,
ip_hash VARCHAR(64) NOT NULL,
variant VARCHAR(50) DEFAULT 'classic'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
`);
try {
await connection.query(
"ALTER TABLE waitlist ADD COLUMN variant VARCHAR(50) DEFAULT 'classic'",
);
} catch {
// Column might already exist or table can be altered in older MySQL
}
}
function escapeHtml(unsafe: string): string {
return unsafe.replace(/[&<>"']/g, (m) => {
switch (m) {
case "&":
return "&amp;";
case "<":
return "&lt;";
case ">":
return "&gt;";
case '"':
return "&quot;";
case "'":
return "&#039;";
default:
return m;
}
});
}
// Resend REST email dispatcher
async function sendWelcomeEmail(email: string, ticketNo: string) {
const apiKey = process.env.RESEND_API_KEY;
if (!apiKey) {
console.log("Resend API Key is missing. Skipping email dispatch.");
return;
}
const emailLogId = getEmailLogId(email);
const cleanTicketNo = escapeHtml(ticketNo);
const referralLink = escapeHtml(
`${SITE_URL}?ref=HUBAPI-${ticketNo.replace(",", "")}`,
);
const accessCode = escapeHtml(
`HUBAPI-ACC-${ticketNo.replace(",", "")}-${email.split("@")[0].toUpperCase()}`,
);
const emailHtml = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HUBAPI ACCESS PASS APPROVED</title>
<style>
body {
background-color: #030303;
color: #f5f5f5;
font-family: 'Courier New', Courier, monospace;
padding: 24px;
margin: 0;
}
.container {
max-width: 600px;
margin: 0 auto;
border: 1px solid #1a1a1a;
background-color: #070708;
padding: 32px;
border-radius: 4px;
box-shadow: 0 4px 20px rgba(0,0,0,0.8);
}
.header {
border-bottom: 1px solid #222;
padding-bottom: 20px;
margin-bottom: 24px;
text-align: center;
}
.logo {
font-size: 24px;
font-weight: 900;
letter-spacing: 0.3em;
color: #ff9d00;
margin: 0;
}
.title {
font-size: 14px;
color: #888;
text-transform: uppercase;
letter-spacing: 0.15em;
margin-top: 6px;
}
.pass-card {
border: 1px dashed #ff9d00;
background: rgba(255, 157, 0, 0.03);
border-radius: 4px;
padding: 20px;
margin: 24px 0;
font-family: monospace;
}
.field {
margin-bottom: 12px;
display: flex;
justify-content: space-between;
font-size: 12px;
border-bottom: 1px dotted #1a1a1a;
padding-bottom: 4px;
}
.field-label {
color: #666;
text-transform: uppercase;
}
.field-val {
color: #ff9d00;
font-weight: bold;
}
.btn {
display: inline-block;
background-color: #ff9d00;
color: #000;
text-decoration: none;
padding: 12px 24px;
font-weight: bold;
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.1em;
border-radius: 2px;
text-align: center;
margin-top: 10px;
}
.footer {
margin-top: 32px;
border-top: 1px solid #1a1a1a;
padding-top: 16px;
font-size: 10px;
color: #444;
text-align: center;
line-height: 1.6;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1 class="logo">HUBAPI</h1>
<div class="title">Waitlist Confirmation Voucher</div>
</div>
<p style="font-size: 13px; line-height: 1.6; color: #ccc;">
Greetings Agent,
<br><br>
Your neural synchronization handshake with Hostinger gateways was successful. You have officially secured a node position on the HUBAPI waitlist. Your verified cryptographic ticket has been registered on the distributed ledger.
</p>
<div class="pass-card">
<div class="field">
<span class="field-label">Registry Node</span>
<span class="field-val">HUBAPI-PROD-01</span>
</div>
<div class="field">
<span class="field-label">Assigned Ticket</span>
<span class="field-val">#${cleanTicketNo}</span>
</div>
<div class="field">
<span class="field-label">Access Token</span>
<span class="field-val" style="font-size: 10px;">${accessCode}</span>
</div>
<div class="field" style="border: none; margin: 0; padding: 0;">
<span class="field-label">System Priority</span>
<span class="field-val" style="color: #00ff66;">EARLY_ADOPTER_NOMINAL</span>
</div>
</div>
<p style="font-size: 12px; line-height: 1.5; color: #888;">
Refer your network peers to bypass standard throttling gates and secure priority allocation metrics:
</p>
<div style="background-color: #09090b; padding: 12px; border: 1px solid #141417; border-radius: 2px; font-size: 11px; margin-bottom: 20px; word-break: break-all; text-align: center;">
<a href="${referralLink}" style="color: #ff9d00; text-decoration: none;">${referralLink}</a>
</div>
<div style="text-align: center;">
<a href="${referralLink}" class="btn">Elevate Access Node</a>
</div>
<div class="footer">
This is an automated encrypted transmission. Response is unmonitored.
<br>
© 2026 HUBAPI. Pre-launch preview. Planned secure API key controls.
</div>
</div>
</body>
</html>
`;
try {
const res = await fetch("https://api.resend.com/emails", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
from: "HUBAPI <onboarding@resend.dev>",
to: email,
subject: `[HUBAPI] SECURE TICKET VERIFIED - #${ticketNo}`,
html: emailHtml,
}),
});
if (!res.ok) {
const errText = await res.text();
throw new Error(`Resend API returned status ${res.status}: ${errText}`);
}
console.log(
`[Resend] Successfully dispatched welcome email for user hash: ${emailLogId}`,
);
} catch (err) {
console.error(
`[Resend] Failed to send welcome email for user hash: ${emailLogId}`,
err,
);
}
}
export async function registerWaitlist(
formData: FormData,
): Promise<RegistrationResult> {
const email = formData.get("email")?.toString().trim();
const variant = formData.get("variant")?.toString().trim() || "classic";
if (!email) {
return { success: false, error: "Email address is required." };
}
// Basic email pattern check
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
return { success: false, error: "Please enter a valid email address." };
}
const emailLogId = getEmailLogId(email);
// If DB is unavailable, only allow fake success during local development.
if (!pool) {
if (IS_PRODUCTION) {
console.error(
`[WAITLIST] Hostinger DB unavailable. Registration rejected for user hash: ${emailLogId}`,
);
return {
success: false,
error:
"Waitlist service is temporarily unavailable. Please try again later.",
};
}
console.warn(
`[WAITLIST] DB unavailable. Development fallback accepted registration for user hash: ${emailLogId}`,
);
return { success: true };
}
const headerList = await headers();
const rawIp =
headerList.get("x-forwarded-for")?.split(",")[0] ||
headerList.get("x-real-ip") ||
"127.0.0.1";
const ipHash = getIpHash(rawIp);
if (!ipHash) {
console.error(
`[WAITLIST] IP hash salt missing. Registration rejected for user hash: ${emailLogId}`,
);
return {
success: false,
error:
"Waitlist service is temporarily unavailable. Please try again later.",
};
}
const ticketNo = getTicketNumber(email);
let connection: mysql.PoolConnection | null = null;
try {
connection = await pool.getConnection();
await ensureMySQLTable(connection);
// Check if email already registered
const [emailCheck] = await connection.query<mysql.RowDataPacket[]>(
"SELECT id FROM waitlist WHERE LOWER(email) = LOWER(?) LIMIT 1",
[email],
);
if (emailCheck.length > 0) {
connection.release();
return {
success: false,
error: "This email is already registered on the waitlist.",
};
}
// Rate Limiting checks
const [ipCheck] = await connection.query<mysql.RowDataPacket[]>(
"SELECT timestamp FROM waitlist WHERE ip_hash = ? ORDER BY timestamp DESC",
[ipHash],
);
const now = Date.now();
const tooFast = ipCheck.some((row) => {
const diff = now - new Date(row.timestamp).getTime();
return diff < 60000; // 60 seconds
});
if (tooFast) {
connection.release();
return {
success: false,
error: "Please wait 60 seconds before submitting another request.",
};
}
if (ipCheck.length >= 5) {
connection.release();
return {
success: false,
error:
"Limit reached. You have reached the maximum number of registrations allowed from this device.",
};
}
// Insert new registration
const timestamp = new Date().toISOString();
await connection.query(
"INSERT INTO waitlist (email, timestamp, ip_hash, variant) VALUES (?, ?, ?, ?)",
[email, timestamp, ipHash, variant],
);
connection.release();
console.log(`[MySQL] Registered waitlist user hash: ${emailLogId}`);
// Dispatch welcome email asynchronously via Resend
sendWelcomeEmail(email, ticketNo);
return { success: true };
} catch (dbErr) {
console.error("[MySQL] Database registration error:", dbErr);
if (connection) {
try {
connection.release();
} catch {}
}
return {
success: false,
error:
"Failed to save registration to the database. Please try again later.",
};
}
}