Files
Epicnabbo-Catalogus-Updated…/src/actions/register.ts
T
openhands c3ff497050 feat(referrals): add referral attribution and daily login rewards
- Track referral attribution at registration via ?ref code with
  same-IP and duplicate-pair guards
- Add daily login rewards with streak tracking, claim flow and
  sendCurrency payout backed by RCON with DB fallback
- Add admin pages for referral settings and the daily reward schedule
- Add migration 0033 with tables, seed schedule, settings and ACL grants
- Add admin.referrals.* and admin.dailyrewards.* permission slugs
- Localize new copy in en, nl and it
2026-09-20 12:29:01 +02:00

199 lines
5.9 KiB
TypeScript

"use server";
import { count, eq } from "drizzle-orm";
import { after } from "next/server";
import { z } from "zod";
import { sendVerification } from "@/lib/auth/email-verification";
import { hashPassword } from "@/lib/auth/password";
import { invalidateKey } from "@/lib/cached-db";
import { db, User } from "@/lib/db";
import { logger } from "@/lib/logger";
import { clientIp, rateLimit } from "@/lib/rate-limit";
import { captchaConfig, verifyCaptcha } from "@/lib/services/captcha";
import { checkVpn } from "@/lib/services/ip-lookup";
import { recordReferral } from "@/lib/services/referrals";
import { siteSettings } from "@/lib/services/site-settings";
const registerSchema = z.object({
username: z
.string()
.min(3, "Username must be at least 3 characters")
.max(25, "Username must be at most 25 characters")
.regex(/^[A-Za-z0-9_\-=?!@:.,]+$/, "Username contains invalid characters"),
mail: z
.string()
.email("Enter a valid email address")
.optional()
.or(z.literal("")),
password: z
.string()
.min(8, "Password must be at least 8 characters")
.regex(/[A-Z]/, "Password must contain at least one uppercase letter")
.regex(/[a-z]/, "Password must contain at least one lowercase letter")
.regex(/[0-9]/, "Password must contain at least one digit"),
passwordConfirmation: z.string(),
look: z.string().optional(),
});
// A valid starter Habbo figure so the avatar renders in-client immediately.
const DEFAULT_LOOK = "hr-100-.hd-180-1.ch-255-66.lg-280-110.sh-305-62";
export interface RegisterState {
error: string | null;
ok: boolean;
}
export async function register(
_prevState: RegisterState,
formData: FormData,
): Promise<RegisterState> {
const fail = (error: string): RegisterState => ({ error, ok: false });
const raw = {
username: String(formData.get("username") ?? "")
.normalize("NFC")
.trim(),
mail: String(formData.get("mail") ?? "")
.normalize("NFC")
.trim()
.toLowerCase(),
password: String(formData.get("password") ?? "").normalize("NFC"),
passwordConfirmation: String(
formData.get("password_confirmation") ?? "",
).normalize("NFC"),
look:
String(formData.get("look") ?? "")
.normalize("NFC")
.trim() || DEFAULT_LOOK,
termsAccepted: formData.get("terms") === "on",
};
const parsed = registerSchema.safeParse(raw);
if (!parsed.success) {
return fail(parsed.error.issues[0]?.message ?? "Invalid input");
}
if (parsed.data.password !== parsed.data.passwordConfirmation) {
return fail("Passwords do not match");
}
const { username, mail, password, look } = parsed.data;
const hasEmail = !!mail;
const ip = await clientIp();
// Throttle sign-ups per IP (5 per 10 minutes) to curb account spam.
if (!(await rateLimit(`register:${ip}`, 5, 10 * 60_000)).ok) {
return fail(
"Too many sign-up attempts. Please wait a few minutes and try again.",
);
}
// CAPTCHA (Turnstile / reCAPTCHA) — only enforced when configured in settings.
const cfg = await captchaConfig();
if (cfg.provider !== "none") {
const token = String(formData.get(cfg.field) ?? "").normalize("NFC");
if (!(await verifyCaptcha(token, ip)))
return fail("Captcha verification failed. Please try again.");
}
// Terms acceptance check.
if (!raw.termsAccepted)
return fail("You must accept the terms and conditions to register.");
// VPN/proxy block (only when enabled in /admin/vpn).
if ((await checkVpn(ip)).blocked) {
return fail(
(await siteSettings.get("vpn_block_message", "")) ||
"Registrations from VPN/proxy connections are not allowed.",
);
}
// Max accounts per IP (0 / unset = unlimited), mirrors AtomCMS.
const max = Number(await siteSettings.get("max_accounts_per_ip", "0")) || 0;
if (max > 0) {
const [row] = await db
.select({ total: count() })
.from(User)
.where(eq(User.ipRegister, ip))
.catch(() => [{ total: 0 }]);
if (Number(row?.total ?? 0) >= max)
return fail(
"You have reached the maximum number of accounts for your connection.",
);
}
// Uniqueness check.
try {
const [existing] = await db
.select({ id: User.id })
.from(User)
.where(eq(User.username, username))
.limit(1);
if (existing) return fail("That username is already taken");
} catch {
logger.warn("Username uniqueness check failed during registration");
return fail("Registration is temporarily unavailable");
}
const now = Math.floor(Date.now() / 1000);
let inviteeId = 0;
try {
const [result] = await db.insert(User).values({
username,
password: await hashPassword(password),
mail: hasEmail ? mail : null,
accountCreated: now,
ipRegister: ip,
ipCurrent: ip,
look,
termsAccepted: raw.termsAccepted,
});
inviteeId = Number(result.insertId);
} catch (err) {
const code = (err as { cause?: { code?: string } }).cause?.code;
if (code === "ER_DUP_ENTRY") {
return fail("That username is already taken");
}
logger.error("Account creation failed", {
code,
message: err instanceof Error ? err.message : String(err),
});
return fail(
"Could not create the account. Please try again or contact staff.",
);
}
// The login lookup is cached for 15s — drop any stale entry so the
// immediate auto sign-in sees the fresh row.
await invalidateKey(`login:user:${username}`);
// Referral attribution (`/register?ref=<username>`). Best-effort: a broken
// referral must never fail the account creation.
if (inviteeId > 0) {
const invitedBy = String(formData.get("ref") ?? "")
.normalize("NFC")
.trim();
if (invitedBy) {
await recordReferral({
inviterUsername: invitedBy,
inviteeId,
inviteeIp: ip,
});
}
}
// Verification email must never block the sign-up response — it is sent
// after the response is flushed (no-op when mail is unconfigured).
if (hasEmail) {
after(async () => {
try {
await sendVerification(mail);
} catch {
logger.warn("Failed to send verification email after registration");
}
});
}
// Client auto signs in with these credentials and navigates to /me.
return { error: null, ok: true };
}