File size: 12,644 Bytes
587459d
 
 
 
 
 
 
 
 
 
 
d3e44c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
587459d
 
d3e44c7
587459d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3e44c7
 
 
587459d
 
 
 
 
 
 
 
d3e44c7
 
 
 
 
 
 
 
 
 
 
 
587459d
 
 
 
 
 
 
 
 
 
 
 
d3e44c7
587459d
d3e44c7
 
 
 
 
 
587459d
 
 
 
 
 
 
 
 
6be5db6
 
 
 
587459d
 
 
 
 
6be5db6
 
 
 
 
587459d
 
6be5db6
587459d
6be5db6
587459d
 
 
6be5db6
 
 
 
 
587459d
 
6be5db6
 
587459d
6be5db6
 
587459d
6be5db6
 
 
 
587459d
6be5db6
 
587459d
6be5db6
 
 
 
587459d
6be5db6
 
587459d
6be5db6
 
 
 
 
 
 
587459d
 
 
6be5db6
 
587459d
 
 
 
 
 
6be5db6
 
 
587459d
 
6be5db6
 
 
 
 
587459d
6be5db6
587459d
 
 
 
 
 
6be5db6
 
587459d
 
6be5db6
 
 
 
587459d
 
6be5db6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
587459d
 
6be5db6
 
587459d
d3e44c7
6be5db6
 
587459d
 
6be5db6
 
 
587459d
 
6be5db6
 
b50322f
587459d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6be5db6
587459d
 
 
 
6be5db6
587459d
6be5db6
587459d
6be5db6
d3e44c7
 
 
587459d
d3e44c7
 
 
 
587459d
 
 
d3e44c7
 
 
587459d
 
 
 
 
 
 
 
 
 
 
 
 
d3e44c7
 
 
6be5db6
d3e44c7
 
 
 
 
 
 
 
 
 
 
 
 
 
6817f18
6be5db6
 
587459d
d3e44c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
587459d
 
6be5db6
587459d
6be5db6
 
587459d
 
6be5db6
 
d3e44c7
587459d
 
6be5db6
 
d3e44c7
 
 
 
587459d
 
6be5db6
 
 
d3e44c7
6be5db6
587459d
 
6be5db6
 
587459d
 
 
 
6be5db6
d3e44c7
 
 
 
587459d
 
6be5db6
 
d3e44c7
 
 
 
 
587459d
 
6be5db6
 
 
 
d3e44c7
6be5db6
587459d
6be5db6
d3e44c7
587459d
 
 
 
 
6be5db6
 
 
 
 
 
 
587459d
 
d3e44c7
 
587459d
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
"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.",
    };
  }
}