import Head from "next/head"; import { useState, useEffect } from "react"; import { useRouter } from "next/router"; import { GetServerSideProps } from "next"; import { useSession } from "next-auth/react"; import { getDb } from "@/lib/db"; import { toast } from "sonner"; import { RiAddLine, RiDeleteBinLine, RiEditLine, RiMailLine, RiShieldCheckLine, RiShieldKeyholeLine, RiSmartphoneLine, RiDownloadLine, RiCheckLine, RiCloseLine, RiLockPasswordLine, RiPlugLine, RiLinkedinBoxLine, RiMessage2Line, RiSettings3Line, RiFileCopyLine, RiLockLine, RiLockUnlockLine, RiFlashlightLine, RiArrowDownSLine, RiCompassLine, } from "react-icons/ri"; import { ALL_TOUR_PAGES, TOUR_PAGE_LABELS, replayPageTour, type TourPage } from "@/lib/tour"; // ─── Types ──────────────────────────────────────────────────────────────────── type Tab = "linkedin" | "email" | "templates" | "integrations" | "general"; interface LiAccount { id: string; name: string; email: string; is_authenticated: number; daily_connection_limit: number; daily_message_limit: number; daily_inmail_limit: number; active_hours_start: number; active_hours_end: number; timezone: string; working_days: string; created_at: string; active_run_count: number; } interface EmailAccount { id: string; name: string; from_email: string; from_name: string | null; reply_to: string | null; smtp_host: string; smtp_port: number; smtp_secure: number; imap_host: string | null; imap_port: number; username: string; imap_username: string | null; daily_email_limit: number; active_hours_start: number; active_hours_end: number; timezone: string; working_days: string; is_verified: number; signature: string | null; ramp_up_enabled: number; ramp_start_date: string | null; created_at: string; active_run_count: number; } interface Template { id: number; name: string; body: string; created_at: string; } // ─── Server-side data ───────────────────────────────────────────────────────── export const getServerSideProps: GetServerSideProps = async ({ query }) => { const db = getDb(); const liAccounts = db .prepare( `SELECT a.id, a.name, a.email, a.is_authenticated, a.daily_connection_limit, a.daily_message_limit, a.daily_inmail_limit, a.active_hours_start, a.active_hours_end, a.timezone, a.working_days, a.created_at, (SELECT COUNT(*) FROM runs r WHERE r.account_id = a.id AND r.status IN ('running', 'paused')) AS active_run_count FROM accounts a ORDER BY a.created_at DESC` ) .all(); const emailAccounts = db .prepare("SELECT id, name, from_email, from_name, reply_to, smtp_host, smtp_port, smtp_secure, imap_host, imap_port, username, daily_email_limit, active_hours_start, active_hours_end, timezone, working_days, is_verified, signature, ramp_up_enabled, ramp_start_date, created_at FROM email_accounts ORDER BY created_at DESC") .all(); const templates = db.prepare("SELECT * FROM templates ORDER BY created_at DESC").all(); const validTabs: Tab[] = ["linkedin", "email", "templates", "integrations", "general"]; const tab: Tab = validTabs.includes(query.tab as Tab) ? (query.tab as Tab) : "linkedin"; return { props: { liAccounts, emailAccounts, templates, initialTab: tab } }; }; // ─── Helpers ───────────────────────────────────────────────────────────────── const TABS: { key: Tab; label: string; icon: React.ElementType }[] = [ { key: "linkedin", label: "LinkedIn", icon: RiLinkedinBoxLine }, { key: "email", label: "Email", icon: RiMailLine }, { key: "templates", label: "Templates", icon: RiMessage2Line }, { key: "integrations", label: "Integrations", icon: RiPlugLine }, { key: "general", label: "General", icon: RiSettings3Line }, ]; const PRESET_CONFIGS: Record = { gmail: { smtp_host: "smtp.gmail.com", smtp_port: 587, smtp_secure: 0, imap_host: "imap.gmail.com", imap_port: 993 }, outlook: { smtp_host: "smtp-mail.outlook.com", smtp_port: 587, smtp_secure: 0, imap_host: "outlook.office365.com", imap_port: 993 }, custom: { smtp_host: "", smtp_port: 587, smtp_secure: 0, imap_host: "", imap_port: 993 }, }; const BLANK_EMAIL_FORM = { preset: "custom", name: "", from_email: "", from_name: "", reply_to: "", smtp_host: "", smtp_port: 587, smtp_secure: 0, imap_host: "", imap_port: 993, username: "", password: "", imap_username: "", imap_password: "", daily_email_limit: 50, active_hours_start: 9, active_hours_end: 18, timezone: "Europe/Berlin", working_days: "1,2,3,4,5", signature: "", ramp_up_enabled: true, ramp_start_date: new Date().toISOString().slice(0, 10), }; const TIMEZONES = [ { value: "Pacific/Midway", label: "UTC−11 — Midway Island" }, { value: "Pacific/Honolulu", label: "UTC−10 — Hawaii" }, { value: "America/Anchorage", label: "UTC−9 — Alaska" }, { value: "America/Los_Angeles", label: "UTC−8 — Pacific Time (US)" }, { value: "America/Denver", label: "UTC−7 — Mountain Time (US)" }, { value: "America/Chicago", label: "UTC−6 — Central Time (US)" }, { value: "America/New_York", label: "UTC−5 — Eastern Time (US)" }, { value: "America/Caracas", label: "UTC−4 — Caracas, La Paz" }, { value: "America/Sao_Paulo", label: "UTC−3 — São Paulo, Buenos Aires" }, { value: "America/Noronha", label: "UTC−2 — Mid-Atlantic" }, { value: "Atlantic/Azores", label: "UTC−1 — Azores" }, { value: "UTC", label: "UTC+0 — London (no DST)" }, { value: "Europe/London", label: "UTC+0/+1 — London (BST)" }, { value: "Europe/Paris", label: "UTC+1/+2 — Paris, Berlin, Amsterdam" }, { value: "Europe/Helsinki", label: "UTC+2/+3 — Helsinki, Kyiv, Tallinn" }, { value: "Europe/Moscow", label: "UTC+3 — Moscow, Istanbul" }, { value: "Asia/Dubai", label: "UTC+4 — Dubai, Abu Dhabi" }, { value: "Asia/Karachi", label: "UTC+5 — Karachi, Islamabad" }, { value: "Asia/Kolkata", label: "UTC+5:30 — India" }, { value: "Asia/Dhaka", label: "UTC+6 — Dhaka, Almaty" }, { value: "Asia/Bangkok", label: "UTC+7 — Bangkok, Jakarta, Hanoi" }, { value: "Asia/Shanghai", label: "UTC+8 — Beijing, Singapore, HK" }, { value: "Asia/Tokyo", label: "UTC+9 — Tokyo, Seoul" }, { value: "Australia/Sydney", label: "UTC+10/+11 — Sydney" }, { value: "Pacific/Auckland", label: "UTC+12/+13 — Auckland" }, ]; const WEEKDAYS = [ { iso: 1, short: "Mon" }, { iso: 2, short: "Tue" }, { iso: 3, short: "Wed" }, { iso: 4, short: "Thu" }, { iso: 5, short: "Fri" }, { iso: 6, short: "Sat" }, { iso: 7, short: "Sun" }, ]; const HOURS = Array.from({ length: 24 }, (_, i) => i); function fmtHour(h: number) { if (h === 0) return "12 AM"; if (h < 12) return `${h} AM`; if (h === 12) return "12 PM"; return `${h - 12} PM`; } const TEMPLATE_VARS = ["{{first_name}}", "{{last_name}}", "{{company}}", "{{title}}"]; // ─── Main Page ──────────────────────────────────────────────────────────────── export default function SettingsPage({ liAccounts: initialLi, emailAccounts: initialEmail, templates: initialTemplates, initialTab, }: { liAccounts: LiAccount[]; emailAccounts: EmailAccount[]; templates: Template[]; initialTab: Tab; }) { const router = useRouter(); const [tab, setTab] = useState(initialTab); // Open-core: the Integrations tab holds Apollo (free) + OpenRouter/Claude (premium AI) // keys. Apollo enrichment is open-core, so the tab is always shown; the premium AI // providers inside it are filtered out of the free build (see IntegrationsTab). const [hasPremium, setHasPremium] = useState(true); useEffect(() => { fetch("/api/premium-status").then((r) => r.ok ? r.json() : null) .then((d) => { if (d) setHasPremium(!!d.hasPremium); }).catch(() => {}); }, []); const visibleTabs = TABS; function switchTab(t: Tab) { setTab(t); router.replace(`/settings?tab=${t}`, undefined, { shallow: true }); } return ( <> Settings — Linki
{/* Page header */}

Settings

Accounts, integrations, and preferences

{/* Tabs */}
{visibleTabs.map(({ key, label, icon: Icon }) => ( ))}
{/* Tab content */} {tab === "linkedin" && } {tab === "email" && } {tab === "templates" && } {tab === "integrations" && } {tab === "general" && }
); } // ─── LinkedIn Tab ───────────────────────────────────────────────────────────── const BLANK_LI_FORM = { name: "", email: "", daily_connection_limit: 20, daily_message_limit: 50, daily_inmail_limit: 15, active_hours_start: 9, active_hours_end: 18, timezone: "Europe/Berlin", working_days: "1,2,3,4,5", }; function LinkedInTab({ initialAccounts }: { initialAccounts: LiAccount[] }) { const [accounts, setAccounts] = useState(initialAccounts); const [showModal, setShowModal] = useState(false); const [editingAccount, setEditingAccount] = useState(null); const [form, setForm] = useState(BLANK_LI_FORM); const [loading, setLoading] = useState(false); const [authModal, setAuthModal] = useState(null); const [authMode, setAuthMode] = useState<"login" | "cookies">("login"); const [authForm, setAuthForm] = useState({ li_at: "", document_cookie: "" }); const [loginForm, setLoginForm] = useState({ email: "", password: "", code: "" }); const [loginStage, setLoginStage] = useState<"creds" | "code" | "approve">("creds"); const [challengeMsg, setChallengeMsg] = useState(""); const [authLoading, setAuthLoading] = useState(false); function openAuthModal(account: LiAccount) { setAuthModal(account.id); setAuthMode("login"); setLoginStage("creds"); setChallengeMsg(""); setLoginForm({ email: account.email ?? "", password: "", code: "" }); setAuthForm({ li_at: "", document_cookie: "" }); } function closeAuthModal() { setAuthModal(null); setLoginStage("creds"); setChallengeMsg(""); setLoginForm({ email: "", password: "", code: "" }); setAuthForm({ li_at: "", document_cookie: "" }); } async function submitLogin(e: React.FormEvent) { e.preventDefault(); if (!authModal) return; setAuthLoading(true); const body = loginStage === "creds" ? { step: "start", email: loginForm.email, password: loginForm.password } : loginStage === "approve" ? { step: "await" } : { step: "verify", code: loginForm.code }; const res = await fetch(`/api/accounts/${authModal}/login`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); const data = await res.json(); setAuthLoading(false); if (!res.ok) { toast.error(data.error ?? "Login failed"); return; } if (data.status === "authenticated") { toast.success("Logged in successfully"); closeAuthModal(); refresh(); } else if (data.status === "challenge" && data.kind === "captcha") { toast.error(data.message); setAuthMode("cookies"); } else if (data.status === "challenge") { setChallengeMsg(data.message ?? ""); if (data.kind === "app") { if (loginStage === "approve") toast.error("Still waiting — approve the request in your LinkedIn app, then click Continue."); setLoginStage("approve"); } else { setLoginStage("code"); setLoginForm((f) => ({ ...f, code: "" })); } } else { toast.error(data.message ?? "Login failed"); } } async function refresh() { const res = await fetch("/api/accounts"); setAccounts(await res.json()); } function openCreate() { setEditingAccount(null); setForm(BLANK_LI_FORM); setShowModal(true); } function openEdit(a: LiAccount) { setEditingAccount(a); setForm({ name: a.name, email: a.email, daily_connection_limit: a.daily_connection_limit, daily_message_limit: a.daily_message_limit, daily_inmail_limit: a.daily_inmail_limit, active_hours_start: a.active_hours_start, active_hours_end: a.active_hours_end, timezone: a.timezone ?? "Europe/Berlin", working_days: a.working_days ?? "1,2,3,4,5", }); setShowModal(true); } async function save(e: React.FormEvent) { e.preventDefault(); setLoading(true); const res = editingAccount ? await fetch(`/api/accounts/${editingAccount.id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(form), }) : await fetch("/api/accounts", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(form), }); setLoading(false); if (!res.ok) { toast.error((await res.json()).error ?? "Failed"); return; } toast.success(editingAccount ? "Account updated" : "Account created"); setShowModal(false); setEditingAccount(null); setForm(BLANK_LI_FORM); refresh(); } async function deleteAccount(id: string) { if (!confirm("Delete this LinkedIn account?")) return; await fetch(`/api/accounts/${id}`, { method: "DELETE" }); toast.success("Deleted"); setAccounts((prev) => prev.filter((a) => a.id !== id)); } async function submitAuth(e: React.FormEvent) { e.preventDefault(); if (!authModal) return; setAuthLoading(true); const res = await fetch(`/api/accounts/${authModal}/authenticate`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(authForm), }); setAuthLoading(false); if (!res.ok) { toast.error((await res.json()).error ?? "Authentication failed"); return; } toast.success("Account authenticated"); closeAuthModal(); refresh(); } return (

LinkedIn accounts used for browser automation

{accounts.length === 0 ? (
No LinkedIn accounts yet.
) : (
{accounts.map((a) => (
{a.name.charAt(0).toUpperCase()}

{a.name}

{a.email} · {a.daily_connection_limit} conn/day · {a.daily_message_limit} msg/day · {a.daily_inmail_limit} inmail/day {" · "}{fmtHour(a.active_hours_start ?? 9)}–{fmtHour(a.active_hours_end ?? 18)} ({a.timezone ?? "UTC"})

{a.active_run_count > 0 ? ( In use ) : null} {a.is_authenticated ? <> Auth : "Unauth"}
))}
)} {/* Add/Edit modal */} {showModal && (

{editingAccount ? "Edit LinkedIn Account" : "Add LinkedIn Account"}

setForm({ ...form, name: e.target.value })} required />
setForm({ ...form, email: e.target.value })} required />
setForm({ ...form, daily_connection_limit: Number(e.target.value) })} min={1} max={100} />
setForm({ ...form, daily_message_limit: Number(e.target.value) })} min={1} max={200} />
setForm({ ...form, daily_inmail_limit: Number(e.target.value) })} min={1} max={100} />

Working Hours

{form.active_hours_start >= form.active_hours_end ?

Start must be before end

:

{fmtHour(form.active_hours_start)} – {fmtHour(form.active_hours_end)} ({form.active_hours_end - form.active_hours_start}h window)

}
{WEEKDAYS.map(day => { const active = form.working_days.split(",").map(Number).includes(day.iso); return ( ); })}
setShowModal(false)} />
)} {/* Auth modal */} {authModal && (

Authenticate LinkedIn Account

{/* Mode toggle */}
{authMode === "login" ? (

Logs in on the server under the runner's exact browser fingerprint and captures all cookies. LinkedIn may ask for a code or a device approval.

{loginStage === "creds" ? ( <>
setLoginForm({ ...loginForm, email: e.target.value })} required />
setLoginForm({ ...loginForm, password: e.target.value })} required />
) : loginStage === "approve" ? (
{challengeMsg || "Approve the sign-in request in your LinkedIn mobile app, then click Continue."}
) : (
{challengeMsg}
setLoginForm({ ...loginForm, code: e.target.value })} required />
)}
) : ( <>

How to get your cookies:

1. Open linkedin.com in Chrome and make sure you are logged in

2. Open DevTools → Application → Cookies → https://www.linkedin.com

3. Find li_at → double-click the Value cell → copy it → paste below

4. Open the DevTools Console tab → run document.cookie → copy the output → paste below

setAuthForm({ ...authForm, li_at: e.target.value })} required />