release: 2026-08-01
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { encryptSecret } from "@/lib/crypto";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "POST") return res.status(405).end();
|
||||
|
||||
const db = getDb();
|
||||
const id = req.query.id as string;
|
||||
|
||||
const account = db.prepare("SELECT * FROM accounts WHERE id = ?").get(id);
|
||||
if (!account) return res.status(404).json({ error: "Account not found" });
|
||||
|
||||
const { li_at, document_cookie } = req.body as { li_at?: string; document_cookie?: string };
|
||||
if (!li_at) return res.status(400).json({ error: "li_at cookie is required" });
|
||||
|
||||
// Parse document.cookie string into cookie objects
|
||||
const extraCookies: { name: string; value: string; domain: string; path: string }[] = [];
|
||||
if (document_cookie) {
|
||||
for (const part of document_cookie.split(";")) {
|
||||
const eqIdx = part.indexOf("=");
|
||||
if (eqIdx === -1) continue;
|
||||
const name = part.slice(0, eqIdx).trim();
|
||||
const value = part.slice(eqIdx + 1).trim();
|
||||
if (name && value) {
|
||||
extraCookies.push({ name, value, domain: ".linkedin.com", path: "/" });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build Playwright-compatible storageState
|
||||
const storageState = {
|
||||
cookies: [
|
||||
{ name: "li_at", value: li_at.trim(), domain: ".linkedin.com", path: "/", httpOnly: true, secure: true, sameSite: "None" as const },
|
||||
...extraCookies.filter((c) => c.name !== "li_at"),
|
||||
],
|
||||
origins: [],
|
||||
};
|
||||
|
||||
db.prepare("UPDATE accounts SET cookies_json = ?, is_authenticated = 1 WHERE id = ?").run(
|
||||
encryptSecret(JSON.stringify(storageState)),
|
||||
id
|
||||
);
|
||||
|
||||
// Evict the cached browser context so next import uses the new cookies
|
||||
const { closeSession } = await import("@/lib/linkedin/session");
|
||||
await closeSession(id);
|
||||
|
||||
return res.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
|
||||
// Excludes cookies_json — the frontend never uses the raw session blob, only
|
||||
// is_authenticated, so there's no reason to ship it (even encrypted) to the client.
|
||||
const ACCOUNT_COLUMNS = `id, name, email, is_authenticated, daily_connection_limit, daily_message_limit, daily_inmail_limit,
|
||||
active_hours_start, active_hours_end, timezone, working_days, created_at,
|
||||
inbox_synced_at, accepted_sync_at, li_connections, li_pending, li_profile_views,
|
||||
li_stats_synced_at, connections_synced_through_ms`;
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const db = getDb();
|
||||
const id = req.query.id as string;
|
||||
|
||||
if (req.method === "GET") {
|
||||
const account = db.prepare(`SELECT ${ACCOUNT_COLUMNS} FROM accounts WHERE id = ?`).get(id);
|
||||
if (!account) return res.status(404).json({ error: "Not found" });
|
||||
return res.json(account);
|
||||
}
|
||||
|
||||
if (req.method === "PUT") {
|
||||
const { name, email, daily_connection_limit, daily_message_limit, daily_inmail_limit, active_hours_start, active_hours_end, timezone, working_days } = req.body;
|
||||
db.prepare(
|
||||
`UPDATE accounts SET
|
||||
name = COALESCE(?, name),
|
||||
email = COALESCE(?, email),
|
||||
daily_connection_limit = COALESCE(?, daily_connection_limit),
|
||||
daily_message_limit = COALESCE(?, daily_message_limit),
|
||||
daily_inmail_limit = COALESCE(?, daily_inmail_limit),
|
||||
active_hours_start = COALESCE(?, active_hours_start),
|
||||
active_hours_end = COALESCE(?, active_hours_end),
|
||||
timezone = COALESCE(?, timezone),
|
||||
working_days = COALESCE(?, working_days)
|
||||
WHERE id = ?`
|
||||
).run(name, email, daily_connection_limit, daily_message_limit, daily_inmail_limit, active_hours_start, active_hours_end, timezone, working_days, id);
|
||||
return res.json(db.prepare(`SELECT ${ACCOUNT_COLUMNS} FROM accounts WHERE id = ?`).get(id));
|
||||
}
|
||||
|
||||
if (req.method === "DELETE") {
|
||||
db.prepare("DELETE FROM accounts WHERE id = ?").run(id);
|
||||
return res.status(204).end();
|
||||
}
|
||||
|
||||
res.setHeader("Allow", ["GET", "PUT", "DELETE"]);
|
||||
res.status(405).end();
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { getSessionPage, saveSessionState } from "@/lib/linkedin/session";
|
||||
import { scrapeLinkedInStats } from "@/lib/linkedin/li-stats";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "POST") return res.status(405).end();
|
||||
|
||||
const accountId = req.query.id as string;
|
||||
const db = getDb();
|
||||
const account = db.prepare("SELECT id, is_authenticated FROM accounts WHERE id = ?").get(accountId) as
|
||||
| { id: string; is_authenticated: number }
|
||||
| undefined;
|
||||
|
||||
if (!account) return res.status(404).json({ error: "Account not found" });
|
||||
if (!account.is_authenticated) return res.status(400).json({ error: "Account not authenticated" });
|
||||
|
||||
let page;
|
||||
try {
|
||||
page = await getSessionPage(accountId);
|
||||
const stats = await scrapeLinkedInStats(page);
|
||||
await saveSessionState(accountId);
|
||||
db.prepare(`
|
||||
UPDATE accounts SET
|
||||
li_connections = ?, li_pending = ?, li_profile_views = ?,
|
||||
li_stats_synced_at = datetime('now')
|
||||
WHERE id = ?
|
||||
`).run(stats.connections, stats.pending, stats.profile_views, accountId);
|
||||
return res.json(stats);
|
||||
} catch (err) {
|
||||
console.error("[li-stats]", err);
|
||||
return res.status(500).json({ error: err instanceof Error ? err.message : "Scrape failed" });
|
||||
} finally {
|
||||
await page?.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { startHeadlessLogin, submitLoginChallenge, awaitLoginApproval } from "@/lib/linkedin/session";
|
||||
|
||||
/**
|
||||
* Server-side headless LinkedIn login.
|
||||
* POST { step: "start", email, password } → begins login (returns authenticated | challenge | error)
|
||||
* POST { step: "verify", code } → submits the email/SMS verification code
|
||||
* POST { step: "await" } → waits for a device/app approval to clear
|
||||
*
|
||||
* The session is born under the same pinned Chromium fingerprint the runner uses
|
||||
* and captures all cookies (incl. httpOnly li_ep_auth_context).
|
||||
*/
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "POST") return res.status(405).end();
|
||||
|
||||
const db = getDb();
|
||||
const id = req.query.id as string;
|
||||
const account = db.prepare("SELECT * FROM accounts WHERE id = ?").get(id) as
|
||||
| { email: string }
|
||||
| undefined;
|
||||
if (!account) return res.status(404).json({ error: "Account not found" });
|
||||
|
||||
const { step } = req.body as { step?: string };
|
||||
|
||||
try {
|
||||
if (step === "verify") {
|
||||
const { code } = req.body as { code?: string };
|
||||
if (!code?.trim()) return res.status(400).json({ error: "code is required" });
|
||||
return res.json(await submitLoginChallenge(id, code.trim()));
|
||||
}
|
||||
|
||||
if (step === "await") {
|
||||
return res.json(await awaitLoginApproval(id));
|
||||
}
|
||||
|
||||
const { email, password } = req.body as { email?: string; password?: string };
|
||||
const loginEmail = (email || account.email || "").trim();
|
||||
if (!loginEmail || !password) {
|
||||
return res.status(400).json({ error: "email and password are required" });
|
||||
}
|
||||
return res.json(await startHeadlessLogin(id, loginEmail, password));
|
||||
} catch (e) {
|
||||
return res.status(500).json({ error: (e as Error).message });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { getSessionPage, saveSessionState } from "@/lib/linkedin/session";
|
||||
import { scrapePendingInvitationVanityNames } from "@/lib/linkedin/pending-invitations";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "POST") return res.status(405).end();
|
||||
|
||||
const accountId = req.query.id as string;
|
||||
const db = getDb();
|
||||
|
||||
const account = db.prepare("SELECT id, is_authenticated FROM accounts WHERE id = ?").get(accountId) as
|
||||
| { id: string; is_authenticated: number }
|
||||
| undefined;
|
||||
|
||||
if (!account) return res.status(404).json({ error: "Account not found" });
|
||||
if (!account.is_authenticated) return res.status(400).json({ error: "Account not authenticated" });
|
||||
|
||||
let page;
|
||||
try {
|
||||
page = await getSessionPage(accountId);
|
||||
const stillPending = await scrapePendingInvitationVanityNames(page);
|
||||
await saveSessionState(accountId);
|
||||
|
||||
// Find all targets that we sent a request to but haven't marked as connected
|
||||
const waiting = db.prepare(`
|
||||
SELECT id, linkedin_url, full_name
|
||||
FROM targets
|
||||
WHERE connection_requested_at IS NOT NULL
|
||||
AND (degree IS NULL OR degree != 1)
|
||||
AND connected_at IS NULL
|
||||
`).all() as { id: string; linkedin_url: string; full_name: string | null }[];
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const accepted: string[] = [];
|
||||
const skipped: string[] = [];
|
||||
|
||||
const markAccepted = db.prepare(
|
||||
"UPDATE targets SET degree = 1, connected_at = ? WHERE id = ?"
|
||||
);
|
||||
|
||||
db.transaction(() => {
|
||||
for (const target of waiting) {
|
||||
const match = target.linkedin_url?.match(/\/in\/([^/?#]+)/);
|
||||
if (!match) continue; // no /in/ URL — can't check
|
||||
const vanity = match[1].toLowerCase();
|
||||
|
||||
if (!stillPending.has(vanity)) {
|
||||
// Not in the pending list anymore → accepted (or expired, but treat as accepted)
|
||||
markAccepted.run(now, target.id);
|
||||
accepted.push(target.full_name ?? vanity);
|
||||
} else {
|
||||
skipped.push(target.full_name ?? vanity);
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return res.json({
|
||||
pending_on_linkedin: stillPending.size,
|
||||
waiting_in_db: waiting.length,
|
||||
newly_accepted: accepted.length,
|
||||
still_pending: skipped.length,
|
||||
accepted_names: accepted,
|
||||
});
|
||||
|
||||
} catch (err) {
|
||||
console.error("[sync-accepted]", err);
|
||||
return res.status(500).json({ error: err instanceof Error ? err.message : "Sync failed" });
|
||||
} finally {
|
||||
await page?.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const db = getDb();
|
||||
|
||||
// Excludes cookies_json — the frontend never uses the raw session blob, only
|
||||
// is_authenticated, so there's no reason to ship it (even encrypted) to the client.
|
||||
const ACCOUNT_COLUMNS = `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,
|
||||
a.inbox_synced_at, a.accepted_sync_at, a.li_connections, a.li_pending, a.li_profile_views,
|
||||
a.li_stats_synced_at, a.connections_synced_through_ms`;
|
||||
|
||||
if (req.method === "GET") {
|
||||
const accounts = db.prepare(`
|
||||
SELECT ${ACCOUNT_COLUMNS},
|
||||
(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();
|
||||
return res.json(accounts);
|
||||
}
|
||||
|
||||
if (req.method === "POST") {
|
||||
const { name, email, daily_connection_limit = 20, daily_message_limit = 50, daily_inmail_limit = 15 } = req.body;
|
||||
if (!name || !email) return res.status(400).json({ error: "name and email required" });
|
||||
try {
|
||||
const id = randomUUID();
|
||||
db
|
||||
.prepare(
|
||||
"INSERT INTO accounts (id, name, email, daily_connection_limit, daily_message_limit, daily_inmail_limit) VALUES (?, ?, ?, ?, ?, ?)"
|
||||
)
|
||||
.run(id, name, email, daily_connection_limit, daily_message_limit, daily_inmail_limit);
|
||||
const account = db.prepare(`SELECT ${ACCOUNT_COLUMNS} FROM accounts a WHERE a.id = ?`).get(id);
|
||||
return res.status(201).json(account);
|
||||
} catch {
|
||||
return res.status(409).json({ error: "Email already exists" });
|
||||
}
|
||||
}
|
||||
|
||||
res.setHeader("Allow", ["GET", "POST"]);
|
||||
res.status(405).end();
|
||||
}
|
||||
Reference in New Issue
Block a user