release: 2026-08-01

This commit is contained in:
moaljumaa
2026-08-01 14:01:17 +02:00
commit 7d8b930bc3
137 changed files with 34695 additions and 0 deletions
+89
View File
@@ -0,0 +1,89 @@
import type { Page } from "playwright";
export class WeeklyLimitError extends Error {}
export class AlreadyConnectedError extends Error {}
export class PendingInviteError extends Error {}
/**
* Sends a LinkedIn connection request without a note.
* Navigates to the profile page and clicks the Connect button.
* Throws WeeklyLimitError if the weekly limit popup appears.
* Throws AlreadyConnectedError / PendingInviteError if already in that state.
*/
export async function sendConnectionRequest(page: Page, linkedinUrl: string): Promise<void> {
await page.goto(linkedinUrl, { waitUntil: "domcontentloaded", timeout: 30000 });
await page.waitForTimeout(2000 + Math.random() * 1000);
// Already connected? Primary signal: presence of the profile's "Message" link
// (only shown to 1st-degree connections) — an href attribute, not a CSS class
// or translated text, so it survives LinkedIn's class-name hashing and non-
// English UI languages. Falls back to the old text-scrape for accounts/layouts
// where that link isn't found as a plain <a href>.
//
// MUST be scoped to the visited person's own intro/top card — a page-wide
// search also matches "Message" links / "1st" badges belonging to OTHER
// people rendered elsewhere on the page (sidebar modules like "People also
// viewed"). For a non-connected target this false-positived AlreadyConnected,
// which skipped the real invite AND (via the message step that follows) sent
// a message to a random unrelated 1st-degree connection instead of the
// target — see CLAUDE.md / memory for the Jul 2026 incident. The top card is
// identified structurally as the section containing the page's own <h1> name
// heading, robust to class-name hashing. Mirrors the same fix in visit.ts.
const topCard = page.locator("main section").filter({ has: page.locator("h1") }).first();
const hasMessageLink = await topCard.locator('a[href*="/messaging/compose"]').first().count() > 0;
if (hasMessageLink) throw new AlreadyConnectedError("Already connected");
const pageText = await topCard.innerText().catch(() => "");
if (/\b1st\b/.test(pageText)) throw new AlreadyConnectedError("Already connected");
// Pending?
if (/\bPending\b/.test(pageText)) throw new PendingInviteError("Invitation already pending");
const pendingBtn = page.locator('button[aria-label*="Pending"]:visible');
if (await pendingBtn.count() > 0) throw new PendingInviteError("Invitation already pending");
// Case 1: Direct Connect link (primary CTA) — navigate to its href directly.
// Clicking fails because the Sales Nav overlay SVG intercepts pointer events.
const directConnect = page.locator('a[aria-label*="Invite"][aria-label*="to connect"]:visible, a[href*="custom-invite"]:visible').first();
if (await directConnect.count() > 0) {
const href = await directConnect.getAttribute("href");
if (!href) throw new Error("Connect link has no href");
const inviteUrl = href.startsWith("http") ? href : `https://www.linkedin.com${href}`;
await page.goto(inviteUrl, { waitUntil: "domcontentloaded", timeout: 30000 });
await page.waitForTimeout(1000);
} else {
// Case 2: Connect is inside the "..." More menu
// LinkedIn has two "More" buttons on page: [0] = nav bar, [1] = profile card
const moreBtn = page.locator('button[aria-label="More"]:visible').nth(1);
await moreBtn.click();
await page.waitForTimeout(800);
// Check for Pending in the menu — means invite was already sent
const pendingMenuItem = page.locator('[role="menuitem"]:has-text("Pending"):visible');
if (await pendingMenuItem.count() > 0) throw new PendingInviteError("Invitation already pending (found in More menu)");
const connectOption = page.locator('[role="menuitem"]:has-text("Connect"):visible');
if (await connectOption.count() === 0) throw new Error("Connect option not found in More menu");
await connectOption.first().click();
}
await page.waitForTimeout(1000);
// Click "Send without a note" / "Send now"
const sendBtn = page.locator(
'button:has-text("Send now"), button[aria-label*="Send without"], button[aria-label*="Send invitation"]:not([aria-label*="note"])'
);
if (await sendBtn.count() > 0) {
await sendBtn.first().click({ force: true });
await page.waitForTimeout(1500);
}
// Check for weekly limit popup
const limitPopup = page.locator('div[class*="ip-fuse-limit-alert__warning"]');
if (await limitPopup.count() > 0) throw new WeeklyLimitError("Weekly connection limit reached");
// Check for error toast
const errorToast = page.locator('div[data-test-artdeco-toast-item-type="error"]:visible');
if (await errorToast.count() > 0) {
const msg = await errorToast.innerText();
throw new Error(`Connection error: ${msg.trim()}`);
}
}
+161
View File
@@ -0,0 +1,161 @@
/**
* Profile enrichment via Sales Navigator profile page intercept.
*
* Strategy: navigate to the lead's sales_nav_url. Sales Nav automatically
* fires a salesApiProfiles call that returns the full profile — headline,
* all positions with descriptions, degree, flagshipProfileUrl, summary.
* We intercept that response instead of making extra API calls.
*
* Weight: ~5-8s per profile (one real browser page load). Run fire-and-forget
* after import — do not await in API routes.
*/
import type { BrowserContext } from "playwright";
import { getDb } from "@/lib/db";
interface EnrichedPosition {
title: string;
companyName: string;
current: boolean;
startedOn?: { year?: number; month?: number };
endedOn?: { year?: number; month?: number };
description?: string;
}
interface SalesNavProfileData {
entityUrn?: string;
firstName?: string;
lastName?: string;
fullName?: string;
headline?: string;
summary?: string;
location?: string;
degree?: number;
flagshipProfileUrl?: string;
objectUrn?: string;
positions?: EnrichedPosition[];
skills?: Array<{ name?: string }>;
}
interface InterceptedResponse {
data?: SalesNavProfileData;
[key: string]: unknown;
}
export async function enrichProfile(
ctx: BrowserContext,
target: { id: string; sales_nav_url: string; full_name: string }
): Promise<boolean> {
const db = getDb();
const page = await ctx.newPage();
try {
// Box it so the async response listener can mutate it (TS can't narrow across async callbacks)
const box: { data: SalesNavProfileData | null } = { data: null };
// Intercept the salesApiProfiles call that Sales Nav fires automatically on profile load.
// Two calls fire per page load:
// 1st — flat object with entityUrn, headline, positions, flagshipProfileUrl (what we want)
// 2nd — flat object with educations, skills, numOfConnections (supplementary)
// Both are flat — no .data wrapper. Accept the first one that has entityUrn.
page.on("response", async (resp) => {
if (box.data) return;
if (!resp.url().includes("salesApiProfiles")) return;
if (resp.status() !== 200) return;
try {
const json = await resp.json() as Record<string, unknown>;
if ("entityUrn" in json && "firstName" in json) {
box.data = json as unknown as SalesNavProfileData;
}
} catch { /* ignore */ }
});
await page.goto(target.sales_nav_url, { waitUntil: "domcontentloaded", timeout: 30000 });
await page.waitForTimeout(8000);
const intercepted = box.data;
if (!intercepted) {
console.log(`[enrich] No profile data intercepted for ${target.full_name} — skipping`);
return false;
}
// Extract positions — include all, not just current
const positions: EnrichedPosition[] = (intercepted.positions ?? []).map((p) => ({
title: p.title ?? "",
companyName: p.companyName ?? "",
current: p.current ?? false,
startedOn: p.startedOn,
endedOn: p.endedOn,
description: p.description ?? undefined,
}));
// Skills come from a separate decoration call — if not in intercept, skip for now
// (the page-load intercept does not include skills; they'd need a second fetch)
const skills: string[] = (intercepted.skills ?? [])
.map((s) => s.name)
.filter((n): n is string => !!n);
db.prepare(`
UPDATE targets SET
headline = COALESCE(?, headline),
summary = COALESCE(?, summary),
positions_json = ?,
skills_json = CASE WHEN ? IS NOT NULL THEN ? ELSE skills_json END,
enriched_profile_at = datetime('now')
WHERE id = ?
`).run(
intercepted.headline ?? null,
intercepted.summary ?? null,
positions.length > 0 ? JSON.stringify(positions) : null,
skills.length > 0 ? "1" : null,
skills.length > 0 ? JSON.stringify(skills) : null,
target.id
);
console.log(`[enrich] ${target.full_name} — ${positions.length} positions, ${skills.length} skills, headline: ${!!intercepted.headline}`);
return true;
} catch (err) {
console.error(`[enrich] Error enriching ${target.full_name}:`, err instanceof Error ? err.message : err);
return false;
} finally {
await page.close();
}
}
export async function enrichList(
ctx: BrowserContext,
listId: string,
delayMs = 2000,
onProgress?: (count: number, total: number) => void
): Promise<{ enriched: number; failed: number }> {
const db = getDb();
// Only targets with a sales_nav_url that haven't been enriched yet
const targets = db.prepare(`
SELECT t.id, t.sales_nav_url, t.full_name
FROM targets t
JOIN list_targets lt ON lt.target_id = t.id
WHERE lt.list_id = ?
AND t.sales_nav_url IS NOT NULL
AND t.enriched_profile_at IS NULL
ORDER BY t.created_at ASC
`).all(listId) as Array<{ id: string; sales_nav_url: string; full_name: string }>;
const total = targets.length;
console.log(`[enrich] Starting enrichment for ${total} profiles in list ${listId}`);
let enriched = 0;
let failed = 0;
for (let i = 0; i < targets.length; i++) {
const target = targets[i];
console.log(`[enrich] ${i + 1}/${total} — ${target.full_name}`);
const ok = await enrichProfile(ctx, target);
if (ok) enriched++; else failed++;
console.log(`[enrich] ${i + 1}/${total} done (${enriched} ok, ${failed} failed)`);
onProgress?.(i + 1, total);
if (delayMs > 0) await new Promise((r) => setTimeout(r, delayMs));
}
console.log(`[enrich] Done — ${enriched} enriched, ${failed} failed`);
return { enriched, failed };
}
+60
View File
@@ -0,0 +1,60 @@
import type { Page } from "playwright";
export interface LinkedInStats {
connections: number;
pending: number;
profile_views: number;
}
function parseNum(str: string): number {
return parseInt(str.replace(/[^0-9]/g, ""), 10) || 0;
}
export async function scrapeLinkedInStats(page: Page): Promise<LinkedInStats> {
// ── Connections ───────────────────────────────────────────
await page.goto("https://www.linkedin.com/mynetwork/invite-connect/connections/", {
waitUntil: "domcontentloaded",
timeout: 30000,
});
await page.waitForTimeout(2500);
const connectionsTexts = await page.evaluate(() =>
[...document.querySelectorAll("h1,h2,h3,span,p")]
.map(el => ((el as HTMLElement).innerText ?? "").trim())
.filter(t => /\d.*connection/i.test(t))
);
const connections = parseNum(connectionsTexts[0] ?? "0");
// ── Pending sent ──────────────────────────────────────────
await page.goto("https://www.linkedin.com/mynetwork/invitation-manager/sent/", {
waitUntil: "domcontentloaded",
timeout: 30000,
});
await page.waitForTimeout(2500);
const pendingTexts = await page.evaluate(() =>
[...document.querySelectorAll("button,a,span,h1,h2,h3")]
.map(el => ((el as HTMLElement).innerText ?? "").trim())
.filter(t => /People\s*\(\d+\)/i.test(t))
);
const pendingMatch = (pendingTexts[0] ?? "").match(/\((\d+)\)/);
const pending = pendingMatch ? parseInt(pendingMatch[1], 10) : 0;
// ── Profile views ─────────────────────────────────────────
await page.goto("https://www.linkedin.com/analytics/profile-views/", {
waitUntil: "domcontentloaded",
timeout: 30000,
});
await page.waitForTimeout(3000);
const profileViewsTexts = await page.evaluate(() =>
[...document.querySelectorAll("*")]
.map(el => ((el as HTMLElement).innerText ?? "").trim())
.filter(t => /Profile viewers/i.test(t) && t.length < 100)
);
// The block looks like "185\n\nProfile viewers\n\n30% previous week"
const pvBlock = profileViewsTexts[0] ?? "";
const profile_views = parseNum(pvBlock.split("\n")[0]);
return { connections, pending, profile_views };
}
+138
View File
@@ -0,0 +1,138 @@
import type { Page } from "playwright";
import { visitProfile } from "./visit";
export class NotConnectedError extends Error {}
export interface SendMessageResult {
messagingUrn: string | null;
isFirstDegree: boolean;
}
/**
* Sends a message to a LinkedIn 1st-degree connection.
*
* Self-contained URN resolution — does NOT depend on a prior 'visit' workflow
* step. If messagingUrn is already cached, it's used directly (no extra page
* load). Otherwise this does its own live profile check (the same top-card-
* scoped logic as the 'visit' step, see visit.ts) to fetch a fresh URN and
* verify the target is still actually connected, immediately before sending.
* Only if that live check finds no URN despite confirming 1st-degree does it
* fall back to the connections-only name-search typeahead — a rare last
* resort now, not the default path for every contact that lacks a cached URN.
*
* Throws NotConnectedError if the live check finds the target is NOT 1st-
* degree, instead of guessing via typeahead search (which can silently hit
* an unrelated connection with a similar/truncated name — see CLAUDE.md /
* memory for the Jul 2026 incident this replaced).
*
* Returns the resolved { messagingUrn, isFirstDegree } so the caller can
* persist it to the target record, same as the 'visit' step does.
*/
export async function sendMessage(
page: Page,
fullName: string,
text: string,
linkedinUrl: string,
messagingUrn?: string | null
): Promise<SendMessageResult> {
if (messagingUrn) {
const opened = await openComposeByUrn(page, messagingUrn);
if (opened) {
await sendFromComposeBox(page, text);
return { messagingUrn, isFirstDegree: true };
}
}
const resolved = await visitProfile(page, linkedinUrl);
if (resolved.messagingUrn) {
const opened = await openComposeByUrn(page, resolved.messagingUrn);
if (opened) {
await sendFromComposeBox(page, text);
return resolved;
}
}
if (!resolved.isFirstDegree) {
throw new NotConnectedError(`${fullName} is not a 1st-degree connection — refusing to message`);
}
// Connected, but no message link could be resolved live (unusual layout) —
// last-resort fallback to name search.
await sendMessageViaTypeahead(page, fullName, text);
return resolved;
}
async function openComposeByUrn(page: Page, messagingUrn: string): Promise<boolean> {
try {
const recipientId = messagingUrn.split(":").pop();
const composeUrl = `https://www.linkedin.com/messaging/compose/?profileUrn=${encodeURIComponent(messagingUrn)}&recipient=${recipientId}`;
await page.goto(composeUrl, { waitUntil: "domcontentloaded", timeout: 30000 });
await page.waitForTimeout(1500 + Math.random() * 1000);
const msgInput = page.locator("div.msg-form__contenteditable").first();
await msgInput.waitFor({ timeout: 8000 });
return true;
} catch {
return false;
}
}
async function sendMessageViaTypeahead(page: Page, fullName: string, text: string): Promise<void> {
await page.goto("https://www.linkedin.com/messaging/thread/new/", {
waitUntil: "domcontentloaded",
timeout: 30000,
});
await page.waitForTimeout(1500 + Math.random() * 1000);
// Search for recipient by name
const searchField = page.locator("input.msg-connections-typeahead__search-field").first();
await searchField.waitFor({ timeout: 10000 });
await searchField.click();
await searchField.type(fullName, { delay: 60 + Math.random() * 40 });
await page.waitForTimeout(1500);
// Select first result — but verify it's actually the intended person first.
// This search only returns 1st-degree connections; if the real target isn't
// connected, LinkedIn will still happily return a same/similar-named
// connection as the top result, and we'd silently message a stranger.
const firstResult = page.locator('div[class*="msg-connections-typeahead__search-result-row"]').first();
await firstResult.waitFor({ timeout: 8000 });
const resultText = (await firstResult.innerText().catch(() => "")).trim();
if (!resultNameMatches(resultText, fullName)) {
throw new Error(
`Typeahead search for "${fullName}" returned a non-matching result ("${resultText.replace(/\s+/g, " ")}") — refusing to send to avoid messaging the wrong person`
);
}
await firstResult.click({ delay: 100 });
await page.waitForTimeout(800);
await sendFromComposeBox(page, text);
}
function resultNameMatches(resultText: string, fullName: string): boolean {
const normalize = (s: string) =>
s.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/[^a-z\s]/g, " ").replace(/\s+/g, " ").trim();
const target = normalize(fullName);
if (!target) return false;
return normalize(resultText).includes(target);
}
async function sendFromComposeBox(page: Page, text: string): Promise<void> {
// Paste message into compose area
const msgInput = page.locator("div.msg-form__contenteditable").first();
await msgInput.waitFor({ timeout: 8000 });
await msgInput.click();
try {
await page.evaluate((t) => navigator.clipboard.writeText(t), text);
await page.waitForTimeout(300);
await msgInput.press("Control+V");
} catch {
// Clipboard blocked in headless — fall back to keyboard typing
await msgInput.pressSequentially(text, { delay: 20 });
}
await page.waitForTimeout(500);
// Send
const sendBtn = page.locator("button.msg-form__send-button:visible").first();
await sendBtn.waitFor({ timeout: 5000 });
await sendBtn.click({ delay: 100 });
await page.waitForTimeout(2000);
}
+61
View File
@@ -0,0 +1,61 @@
import type { Page } from "playwright";
/**
* Scrapes the full list of vanity names from the sent invitations page.
* Returns a Set of lowercase vanity names that are STILL pending on LinkedIn.
*
* Strategy: navigate to invitation-manager/sent/, scroll the #workspace container
* until the count stabilises, then extract all /in/ links.
*
* Works headless — the scrollable element is <main id="workspace">, not window.
*/
export async function scrapePendingInvitationVanityNames(page: Page): Promise<Set<string>> {
await page.goto("https://www.linkedin.com/mynetwork/invitation-manager/sent/", {
waitUntil: "domcontentloaded",
timeout: 30000,
});
await page.waitForTimeout(3000);
// Scroll #workspace until link count stabilises
let lastCount = 0;
let stableRounds = 0;
for (let round = 0; round < 40; round++) {
await page.evaluate(() => {
const workspace = document.getElementById("workspace");
if (workspace) {
workspace.scrollTop = workspace.scrollHeight;
} else {
// Fallback: scroll window + body
window.scrollTo(0, document.body.scrollHeight);
document.documentElement.scrollTop = document.documentElement.scrollHeight;
}
});
await page.waitForTimeout(1200);
const currentCount = await page.evaluate(() =>
document.querySelectorAll("a[href*='/in/']").length
);
if (currentCount === lastCount) {
stableRounds++;
if (stableRounds >= 3) break;
} else {
stableRounds = 0;
lastCount = currentCount;
}
}
// Extract unique vanity names from all /in/ links
const vanityNames = await page.evaluate(() => {
const seen = new Set<string>();
for (const link of document.querySelectorAll<HTMLAnchorElement>("a[href*='/in/']")) {
const href = link.getAttribute("href") ?? "";
const match = href.match(/\/in\/([^/?#]+)/);
if (match) seen.add(match[1].toLowerCase());
}
return [...seen];
});
return new Set(vanityNames);
}
+298
View File
@@ -0,0 +1,298 @@
/**
* Live profile scrape → clean structured JSON for an LLM.
*
* Two confirmed sources (probed against prod, Jun 2026 — see docs §18):
* 1. Sales Nav `salesApiProfiles` intercept (navigate the lead's sales_nav_url):
* two flat responses give headline, summary, positions, educations, skills,
* languages, connections, contactInfo, inmailRestriction, memberBadges, degree.
* 2. Voyager `feed/updates?q=memberShareFeed` on the /in/ publicId:
* the 10 most recent authored posts (text + media type + engagement counts)
* plus the comments left on those posts. (q=memberComments → 400, not used.)
*
* Read-only. ~10-12s per profile (one Sales Nav page load + one Voyager fetch).
*/
import type { BrowserContext } from "playwright";
export interface ProfilePost {
activityUrn: string;
text: string;
postedAt: string | null; // ISO, when derivable from the activity id
mediaType: "video" | "image" | "article" | "text";
reactions: number;
comments: number;
shares: number;
}
export interface ProfileScrape {
full_name: string | null;
first_name: string | null;
last_name: string | null;
headline: string | null;
summary: string | null;
location: string | null;
degree: number | null; // network distance (1/2/3)
linkedin_url: string | null; // real /in/ URL
num_connections: number | null;
num_shared_connections: number | null;
is_premium: boolean;
is_open_profile: boolean; // openLink — can be messaged free (note: API often under-reports)
can_inmail: boolean; // inmailRestriction === NO_RESTRICTION
pending_invitation: boolean;
websites: string[];
positions: Array<{
title: string;
company: string;
current: boolean;
started: { year?: number; month?: number } | null;
ended: { year?: number; month?: number } | null;
description: string | null;
}>;
educations: Array<{ school: string | null; degree: string | null; field: string | null }>;
skills: string[];
languages: string[];
recent_posts: ProfilePost[]; // up to 10, most recent first
}
// ─── helpers ──────────────────────────────────────────────────────────────────
function textOf(v: unknown): string | null {
if (typeof v === "string") return v;
if (v && typeof v === "object" && "text" in v && typeof (v as { text: unknown }).text === "string") {
return (v as { text: string }).text;
}
return null;
}
// LinkedIn activity/ugcPost ids encode the creation epoch-ms in the high 41 bits
// (the low 22 bits are a sequence). Shift right 22 = divide by 2^22, via float
// math to avoid BigInt (tsconfig targets < ES2020).
const SHIFT_22 = 4194304; // 2^22
function timeFromActivityUrn(urn: string): string | null {
const m = urn.match(/(\d{18,})/);
if (!m) return null;
const ms = Math.floor(Number(m[1]) / SHIFT_22);
return ms > 1_000_000_000_000 ? new Date(ms).toISOString() : null;
}
interface SalesPosition {
title?: string; companyName?: string; current?: boolean;
startedOn?: { year?: number; month?: number };
endedOn?: { year?: number; month?: number };
description?: string;
}
interface SalesProfileFlat {
entityUrn?: string; firstName?: string; lastName?: string; fullName?: string;
headline?: string; summary?: string; location?: string; degree?: number;
flagshipProfileUrl?: string; pendingInvitation?: boolean;
positions?: SalesPosition[];
contactInfo?: { websites?: Array<{ url?: string }> };
educations?: Array<{ schoolName?: string; degreeName?: string; fieldOfStudy?: string }>;
skills?: Array<{ name?: string }>;
languages?: Array<{ name?: string }>;
numOfConnections?: number; numOfSharedConnections?: number;
inmailRestriction?: string;
memberBadges?: { premium?: boolean; openLink?: boolean };
}
// ─── Sales Nav career ─────────────────────────────────────────────────────────
async function scrapeSalesCareer(
ctx: BrowserContext,
salesNavUrl: string
): Promise<Partial<ProfileScrape>> {
const page = await ctx.newPage();
const responses: SalesProfileFlat[] = [];
page.on("response", async (resp) => {
if (!resp.url().includes("salesApiProfiles") || resp.status() !== 200) return;
try {
const j = (await resp.json()) as Record<string, unknown>;
// Only the two flat profile responses (have entityUrn); ignore the data/included one.
if ("entityUrn" in j && ("firstName" in j || "educations" in j || "skills" in j)) {
responses.push(j as unknown as SalesProfileFlat);
}
} catch { /* ignore */ }
});
try {
await page.goto(salesNavUrl, { waitUntil: "domcontentloaded", timeout: 35000 });
await page.waitForTimeout(9000);
} finally {
await page.close();
}
// Merge the (typically two) flat responses — first carries the core profile,
// second carries educations/skills/languages/connections/inmailRestriction.
const core = responses.find((r) => r.firstName || r.positions) ?? {};
const extra = responses.find((r) => r.educations || r.skills || r.numOfConnections != null) ?? {};
const positions = (core.positions ?? []).map((p) => ({
title: p.title ?? "",
company: p.companyName ?? "",
current: p.current ?? false,
started: p.startedOn ?? null,
ended: p.endedOn ?? null,
description: p.description?.trim() ? p.description : null,
}));
return {
full_name: core.fullName ?? null,
first_name: core.firstName ?? null,
last_name: core.lastName ?? null,
headline: core.headline ?? null,
summary: core.summary ?? null,
location: core.location ?? null,
degree: core.degree ?? null,
linkedin_url: core.flagshipProfileUrl ?? null,
pending_invitation: core.pendingInvitation ?? false,
websites: (core.contactInfo?.websites ?? []).map((w) => w.url).filter((u): u is string => !!u),
positions,
num_connections: extra.numOfConnections ?? null,
num_shared_connections: extra.numOfSharedConnections ?? null,
is_premium: extra.memberBadges?.premium ?? false,
is_open_profile: extra.memberBadges?.openLink ?? false,
can_inmail: (extra.inmailRestriction ?? core.inmailRestriction) === "NO_RESTRICTION",
educations: (extra.educations ?? []).map((e) => ({
school: e.schoolName ?? null, degree: e.degreeName ?? null, field: e.fieldOfStudy ?? null,
})),
skills: (extra.skills ?? []).map((s) => s.name).filter((n): n is string => !!n),
languages: (extra.languages ?? []).map((l) => l.name).filter((n): n is string => !!n),
};
}
// ─── Voyager posts ────────────────────────────────────────────────────────────
function publicIdFromUrl(url: string | null | undefined): string | null {
const m = url && url.match(/\/in\/([^/?#]+)/);
return m ? decodeURIComponent(m[1]) : null;
}
async function scrapePosts(
ctx: BrowserContext,
publicId: string
): Promise<ProfilePost[]> {
const page = await ctx.newPage();
try {
await page.goto("https://www.linkedin.com/feed/", { waitUntil: "domcontentloaded", timeout: 25000 });
const cookies = await ctx.cookies();
const csrf = (cookies.find((c) => c.name === "JSESSIONID")?.value || "").replace(/"/g, "");
if (!csrf) return [];
const url =
`https://www.linkedin.com/voyager/api/feed/updates` +
`?profileId=${encodeURIComponent(publicId)}&q=memberShareFeed&count=10&start=0`;
const raw = await page.evaluate(
async ({ url, csrf }: { url: string; csrf: string }) => {
const r = await fetch(url, {
headers: {
accept: "application/vnd.linkedin.normalized+json+2.1",
"csrf-token": csrf,
"x-restli-protocol-version": "2.0.0",
},
credentials: "include",
});
return r.status === 200 ? r.text() : "";
},
{ url, csrf }
);
if (!raw) return [];
const j = JSON.parse(raw) as { included?: Array<Record<string, unknown>> };
const inc = j.included ?? [];
// Engagement counts keyed by the post's ugcPost/share urn.
const countsByUrn = new Map<string, { reactions: number; comments: number; shares: number }>();
for (const x of inc) {
if (!String(x["$type"]).endsWith("SocialActivityCounts")) continue;
const urn = String(x.urn ?? "");
if (!urn.includes("ugcPost") && !urn.includes("activity")) continue;
countsByUrn.set(urn, {
reactions: Number(x.numLikes ?? 0),
comments: Number(x.numComments ?? 0),
shares: Number(x.numShares ?? 0),
});
}
const posts: ProfilePost[] = [];
for (const x of inc) {
if (!String(x["$type"]).endsWith("UpdateV2")) continue;
const commentary = x.commentary as { text?: unknown } | undefined;
const text = commentary ? textOf(commentary.text) : null;
if (!text) continue;
const meta = x.updateMetadata as { urn?: string } | undefined;
const activityUrn = meta?.urn ?? "";
// Find the matching counts (the SocialActivityCounts urn references the backing ugcPost).
let counts = { reactions: 0, comments: 0, shares: 0 };
for (const [urn, c] of countsByUrn) {
const idActivity = activityUrn.match(/(\d{18,})/)?.[1];
if (idActivity && urn.includes(idActivity)) { counts = c; break; }
}
const content = x.content as Record<string, unknown> | undefined;
const ctype = content ? String(Object.keys(content)[0] ?? "").toLowerCase() : "";
const mediaType: ProfilePost["mediaType"] =
ctype.includes("video") ? "video" :
ctype.includes("image") ? "image" :
ctype.includes("article") ? "article" : "text";
posts.push({
activityUrn,
text,
postedAt: timeFromActivityUrn(activityUrn),
mediaType,
reactions: counts.reactions,
comments: counts.comments,
shares: counts.shares,
});
}
// Most recent first (by encoded time when available).
posts.sort((a, b) => (b.postedAt ?? "").localeCompare(a.postedAt ?? ""));
return posts.slice(0, 10);
} catch {
return [];
} finally {
await page.close();
}
}
// ─── public ───────────────────────────────────────────────────────────────────
export async function scrapeProfile(
ctx: BrowserContext,
target: { sales_nav_url: string | null; linkedin_url: string | null }
): Promise<ProfileScrape> {
if (!target.sales_nav_url) {
throw new Error("Contact has no sales_nav_url — cannot scrape the Sales Nav profile.");
}
const career = await scrapeSalesCareer(ctx, target.sales_nav_url);
// Prefer the flagship /in/ URL from the career scrape; fall back to the stored one.
const inUrl = career.linkedin_url ?? target.linkedin_url ?? null;
const publicId = publicIdFromUrl(inUrl);
const recent_posts = publicId ? await scrapePosts(ctx, publicId) : [];
return {
full_name: career.full_name ?? null,
first_name: career.first_name ?? null,
last_name: career.last_name ?? null,
headline: career.headline ?? null,
summary: career.summary ?? null,
location: career.location ?? null,
degree: career.degree ?? null,
linkedin_url: inUrl,
num_connections: career.num_connections ?? null,
num_shared_connections: career.num_shared_connections ?? null,
is_premium: career.is_premium ?? false,
is_open_profile: career.is_open_profile ?? false,
can_inmail: career.can_inmail ?? false,
pending_invitation: career.pending_invitation ?? false,
websites: career.websites ?? [],
positions: career.positions ?? [],
educations: career.educations ?? [],
skills: career.skills ?? [],
languages: career.languages ?? [],
recent_posts,
};
}
+50
View File
@@ -0,0 +1,50 @@
import type DatabaseType from "better-sqlite3";
type DB = DatabaseType.Database;
export interface ResolvedAccount { id: string; email: string }
/**
* Resolve which authenticated LinkedIn account to act through for a contact.
* Order: explicit id → the contact's most recent run assignment → the sole
* authenticated account. Only ever returns an `is_authenticated = 1` account
* so callers never drive a dead session.
*/
export function resolveLinkedInAccount(db: DB, targetId: string, explicitId?: string): ResolvedAccount | null {
const byId = (aid: string) =>
db.prepare("SELECT id, email FROM accounts WHERE id = ? AND is_authenticated = 1").get(aid) as
| ResolvedAccount
| undefined;
if (explicitId) return byId(explicitId) ?? null;
const assigned = db.prepare(`
SELECT r.account_id FROM run_profiles rp
JOIN runs r ON r.id = rp.run_id
WHERE rp.target_id = ?
ORDER BY rp.created_at DESC LIMIT 1
`).get(targetId) as { account_id: string } | undefined;
if (assigned?.account_id) {
const a = byId(assigned.account_id);
if (a) return a;
}
const all = db.prepare("SELECT id, email FROM accounts WHERE is_authenticated = 1").all() as ResolvedAccount[];
return all.length === 1 ? all[0] : null;
}
/**
* Resolve an authenticated LinkedIn account when there's no target/contact to
* anchor the lookup to (e.g. Sales Navigator search, which runs before any
* lead exists locally). Order: explicit id → the sole authenticated account.
*/
export function resolveAnyAuthenticatedAccount(db: DB, explicitId?: string): ResolvedAccount | null {
const byId = (aid: string) =>
db.prepare("SELECT id, email FROM accounts WHERE id = ? AND is_authenticated = 1").get(aid) as
| ResolvedAccount
| undefined;
if (explicitId) return byId(explicitId) ?? null;
const all = db.prepare("SELECT id, email FROM accounts WHERE is_authenticated = 1").all() as ResolvedAccount[];
return all.length === 1 ? all[0] : null;
}
File diff suppressed because it is too large Load Diff
+453
View File
@@ -0,0 +1,453 @@
/**
* Sales Navigator list scraper using the internal Sales API.
* Uses Playwright's browser context request (inherits browser TLS fingerprint).
*
* Response format discovery (from capture scripts):
* - ctx.request returns normalized JSON: { data: { metadata: { totalDisplayCount: "106" } }, included: [...] }
* - Profiles are in `included` filtered by entityUrn containing "salesProfile"
* - Browser-intercepted first page returns flat: { elements: [...], paging: { total } }
* - Query format: parentheses/commas unencoded, colons in URN encoded as %3A
*
* IMPORTANT — vanityName is gone from salesApiPeopleSearch (dropped by LinkedIn ~March 2026):
* The list API no longer returns vanityName. To get the real /in/ URL we call
* salesApiProfiles per batch of 25 after scraping, using flagshipProfileUrl.
* See docs/linkedin-api-learnings.md for the full investigation.
*/
import type { BrowserContext, Page } from "playwright";
export interface ScrapedProfile {
salesNavUrn: string;
salesNavUrl: string;
linkedinUrl: string | null; // regular /in/ URL
fullName: string | null;
firstName: string | null;
lastName: string | null;
title: string | null;
company: string | null;
location: string | null;
degree: number | null;
// Extended fields
objectUrn: string | null; // urn:li:member:XXXX — stable LinkedIn member ID
summary: string | null; // About / bio text
openLink: boolean; // can message without connecting
companyIndustry: string | null;
companyLocation: string | null; // company HQ location
tenureMonths: number | null; // months in current role
spotlightBadges: string | null; // JSON array of badge displayValues
}
interface SalesProfile {
entityUrn: string;
objectUrn?: string;
firstName?: string;
lastName?: string;
fullName?: string;
vanityName?: string;
geoRegion?: string;
degree?: number;
summary?: string;
openLink?: boolean;
premium?: boolean;
pendingInvitation?: boolean;
currentPositions?: Array<{
title?: string;
companyName?: string;
companyUrn?: string;
current?: boolean;
description?: string;
startedOn?: { year?: number; month?: number };
tenureAtPosition?: { numYears?: number; numMonths?: number };
tenureAtCompany?: { numYears?: number; numMonths?: number };
companyUrnResolutionResult?: {
name?: string;
industry?: string;
location?: string;
entityUrn?: string;
};
}>;
leadAssociatedAccount?: { name?: string } | null;
spotlightBadges?: Array<{ displayValue?: string; id?: string }>;
}
// Flat response intercepted from browser
interface FlatResponse {
elements?: SalesProfile[];
paging?: { total: number; count: number; start: number };
}
// salesApiProfiles single-profile response
interface ProfileDetailResponse {
entityUrn?: string;
flagshipProfileUrl?: string;
fullName?: string;
}
function extractListId(url: string): string | null {
const match = url.match(/\/sales\/lists\/people\/(\d+)/);
return match ? match[1] : null;
}
function extractSavedSearchId(url: string): string | null {
const match = url.match(/[?&]savedSearchId=(\d+)/);
return match ? match[1] : null;
}
function urnToSalesNavUrl(urn: string): string {
const match = urn.match(/\(([^)]+)\)/);
if (!match) return "";
return `https://www.linkedin.com/sales/lead/${match[1]}`;
}
/**
* Parse profileId, authType, authToken out of a salesProfile URN.
* urn:li:fs_salesProfile:(ACwAAEIY-4YB25mKP6R5AKfkFjhO9isSbvsVlag,NAME_SEARCH,22wq)
*/
function parseUrn(entityUrn: string): { profileId: string; authType: string; authToken: string } | null {
const match = entityUrn.match(/\(([^,]+),([^,]+),([^)]+)\)/);
if (!match) return null;
return { profileId: match[1], authType: match[2], authToken: match[3] };
}
function profileToResult(el: SalesProfile, linkedinUrl: string | null): ScrapedProfile {
const currentPos = el.currentPositions?.find((p) => p.current) ?? el.currentPositions?.[0];
const company = currentPos?.companyUrnResolutionResult ?? null;
// Tenure in months at current position
let tenureMonths: number | null = null;
const t = currentPos?.tenureAtPosition;
if (t) tenureMonths = (t.numYears ?? 0) * 12 + (t.numMonths ?? 0);
// Spotlight badge labels as a compact JSON array e.g. ["Changed jobs", "Mentioned in news"]
const badges = (el.spotlightBadges ?? [])
.map((b) => b.displayValue)
.filter(Boolean) as string[];
return {
salesNavUrn: el.entityUrn,
salesNavUrl: urnToSalesNavUrl(el.entityUrn),
linkedinUrl,
fullName: el.fullName ?? null,
firstName: el.firstName ?? null,
lastName: el.lastName ?? null,
title: currentPos?.title ?? null,
company: el.leadAssociatedAccount?.name ?? company?.name ?? currentPos?.companyName ?? null,
location: el.geoRegion ?? null,
degree: el.degree ?? null,
objectUrn: el.objectUrn ?? null,
summary: el.summary ?? null,
openLink: el.openLink ?? false,
companyIndustry: company?.industry ?? null,
companyLocation: company?.location ?? null,
tenureMonths,
spotlightBadges: badges.length > 0 ? JSON.stringify(badges) : null,
};
}
/**
* Enrich profiles with their real /in/ URL via salesApiProfiles (flagshipProfileUrl).
*
* Uses page.evaluate fetch with JSESSIONID csrf-token. On 429 (rate limit),
* backs off for 30s and retries. Delay between calls: 2s normally, 30s after 429.
*
* For 100 profiles at 2s/call = ~3.5 minutes. Happens once at import time.
*/
async function enrichWithFlagshipUrls(
page: Page,
profiles: SalesProfile[],
onProgress?: (p: ImportProgress) => void
): Promise<Map<string, string>> {
const urlMap = new Map<string, string>(); // entityUrn → flagshipProfileUrl
const cookies = await page.context().cookies("https://www.linkedin.com");
const jsessionid = cookies.find(c => c.name === "JSESSIONID")?.value?.replace(/"/g, "") ?? "";
if (!jsessionid) {
console.log("[scraper] JSESSIONID not found — skipping flagshipProfileUrl enrichment");
return urlMap;
}
let done = 0;
for (const el of profiles) {
const parts = parseUrn(el.entityUrn);
if (!parts) continue;
const { profileId, authType, authToken } = parts;
const apiUrl = `https://www.linkedin.com/sales-api/salesApiProfiles/(profileId:${profileId},authType:${authType},authToken:${authToken})?decoration=%28entityUrn%2CflagshipProfileUrl%29`;
let attempts = 0;
while (attempts < 3) {
const evaluatePromise = page.evaluate(async ({ url, csrfToken }: { url: string; csrfToken: string }) => {
try {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 12000);
const resp = await fetch(url, {
credentials: "include",
signal: controller.signal,
headers: {
"csrf-token": csrfToken,
"x-restli-protocol-version": "2.0.0",
"accept": "application/json",
},
});
clearTimeout(timer);
return { status: resp.status, body: await resp.text() };
} catch (e: unknown) {
return { status: -1, body: (e as Error).message };
}
}, { url: apiUrl, csrfToken: jsessionid });
const timeoutPromise = new Promise<{ status: number; body: string }>((resolve) =>
setTimeout(() => resolve({ status: -1, body: 'timeout' }), 15000)
);
const result = await Promise.race([evaluatePromise, timeoutPromise]);
if (result.status === 200) {
try {
const data = JSON.parse(result.body) as ProfileDetailResponse;
if (data.flagshipProfileUrl) {
const normalized = data.flagshipProfileUrl.endsWith("/")
? data.flagshipProfileUrl
: data.flagshipProfileUrl + "/";
urlMap.set(el.entityUrn, normalized);
}
} catch { /* ignore parse errors */ }
break;
} else if (result.status === 429) {
attempts++;
console.log(`[scraper] 429 rate limit — waiting 30s before retry (attempt ${attempts}/3)`);
await page.waitForTimeout(30000);
} else {
const reason = result.body === 'timeout' ? 'timeout' : result.status;
console.log(`[scraper] enrichment ${reason} for ${el.fullName ?? el.entityUrn.substring(0, 30)} — skipping`);
break;
}
}
// 2s between calls — slow enough to stay under rate limits
await page.waitForTimeout(2000);
done++;
console.log(`[scraper] flagship URLs: ${done}/${profiles.length} resolved`);
onProgress?.({ phase: 'enriching', count: done, total: profiles.length });
}
console.log(`[scraper] enrichment done: ${urlMap.size}/${profiles.length} profiles resolved`);
return urlMap;
}
export interface ImportProgress {
phase: 'scraping' | 'enriching' | 'visiting';
page?: number;
totalPages?: number;
count: number;
total: number;
}
export interface ScrapeOptions {
/** 1-based page to begin this window at (for batched imports). Default 1. */
startPage?: number;
/** Max pages to fetch in THIS window, starting at startPage. Default 50. */
maxPages?: number;
onProgress?: (p: ImportProgress) => void;
/** Polled between pages; return true to stop early (cancel / deleted list). */
isCanceled?: () => boolean | Promise<boolean>;
}
export interface WindowedScrapeResult {
profiles: ScrapedProfile[];
/** Last page actually fetched in this window. */
lastPage: number;
/** Total profiles available in the whole search. */
knownTotal: number;
/** True if this window reached the end of the search (nothing left to batch). */
exhausted: boolean;
}
export async function scrapeNavigatorList(
ctx: BrowserContext,
salesNavUrl: string,
opts: ScrapeOptions = {}
): Promise<WindowedScrapeResult> {
const { startPage = 1, maxPages = 50, onProgress, isCanceled } = opts;
const listId = extractListId(salesNavUrl);
if (!listId) throw new Error(`Invalid Sales Navigator URL: ${salesNavUrl}`);
const allElements: SalesProfile[] = [];
const seen = new Set<string>();
const PAGE_SIZE = 25;
const buildUrl = (n: number) =>
`https://www.linkedin.com/sales/lists/people/${listId}?${n > 1 ? `page=${n}&` : ""}sortCriteria=CREATED_TIME&sortOrder=DESCENDING`;
const page = await ctx.newPage();
let knownTotal = 0;
let intercepted: FlatResponse | null = null;
const waitForIntercept = async (url: string, waitMs: number): Promise<FlatResponse | null> => {
intercepted = null;
page.removeAllListeners("response");
page.on("response", async (response) => {
if (intercepted) return;
if (response.url().includes("salesApiPeopleSearch") && response.status() === 200) {
try { intercepted = await response.json() as FlatResponse; } catch { /* ignore */ }
}
});
await page.goto(url, { waitUntil: "domcontentloaded", timeout: 30000 });
await page.waitForTimeout(waitMs);
return intercepted;
};
// First page of the window
const firstData = await waitForIntercept(buildUrl(startPage), 15000);
if (!firstData) {
const finalUrl = page.url();
console.error(`[scraper] no intercept after 15s. Final URL: ${finalUrl}`);
await page.close();
throw new Error("No data intercepted from Sales Nav — session may need re-authentication");
}
knownTotal = firstData.paging?.total ?? 0;
for (const el of firstData.elements ?? []) {
if (!el.entityUrn || seen.has(el.entityUrn)) continue;
seen.add(el.entityUrn);
allElements.push(el);
}
console.log(`[scraper] page ${startPage}: ${allElements.length} elements, total=${knownTotal}`);
const totalPages = Math.ceil(knownTotal / PAGE_SIZE);
const endPage = Math.min(totalPages, startPage + maxPages - 1);
let lastPage = startPage;
onProgress?.({ phase: 'scraping', page: startPage, totalPages: endPage, count: allElements.length, total: knownTotal });
for (let pageNum = startPage + 1; pageNum <= endPage; pageNum++) {
if (isCanceled && (await isCanceled())) break;
const delayMs = 60000 + Math.random() * 60000;
console.log(`[scraper] waiting ${Math.round(delayMs / 1000)}s before page ${pageNum}...`);
await page.waitForTimeout(delayMs);
if (isCanceled && (await isCanceled())) break;
let pageData = await waitForIntercept(buildUrl(pageNum), 15000);
if (!pageData || (pageData.elements?.length ?? 0) === 0) {
console.log(`[scraper] page ${pageNum} empty on first try — retrying with 15s wait`);
pageData = await waitForIntercept(buildUrl(pageNum), 15000);
}
if (pageData) {
for (const el of pageData.elements ?? []) {
if (!el.entityUrn || seen.has(el.entityUrn)) continue;
seen.add(el.entityUrn);
allElements.push(el);
}
}
lastPage = pageNum;
console.log(`[scraper] page ${pageNum}/${endPage}: ${allElements.length} (total ${knownTotal})`);
onProgress?.({ phase: 'scraping', page: pageNum, totalPages: endPage, count: allElements.length, total: knownTotal });
}
await page.close();
return {
profiles: allElements.map(el => profileToResult(el, null)),
lastPage,
knownTotal,
exhausted: lastPage >= totalPages,
};
}
export async function scrapeSavedSearch(
ctx: BrowserContext,
savedSearchUrl: string,
opts: ScrapeOptions = {}
): Promise<WindowedScrapeResult> {
const { startPage = 1, maxPages = 50, onProgress, isCanceled } = opts;
const savedSearchId = extractSavedSearchId(savedSearchUrl);
if (!savedSearchId) throw new Error(`Invalid Sales Navigator saved search URL: ${savedSearchUrl}`);
const allElements: SalesProfile[] = [];
const seen = new Set<string>();
const PAGE_SIZE = 25;
const buildUrl = (n: number) =>
`https://www.linkedin.com/sales/search/people?savedSearchId=${savedSearchId}${n > 1 ? `&page=${n}` : ""}`;
const page = await ctx.newPage();
let knownTotal = 0;
const waitForIntercept = async (url: string, waitMs: number): Promise<FlatResponse | null> => {
let intercepted: FlatResponse | null = null;
page.removeAllListeners("response");
page.on("response", async (response) => {
if (intercepted) return;
if (response.url().includes("salesApiLeadSearch") && response.status() === 200) {
try { intercepted = await response.json() as FlatResponse; } catch { /* ignore */ }
}
});
await page.goto(url, { waitUntil: "domcontentloaded", timeout: 30000 });
await page.waitForTimeout(waitMs);
return intercepted;
};
// First page of the window
const firstData = await waitForIntercept(buildUrl(startPage), 15000);
if (!firstData) {
await page.close();
throw new Error("No data intercepted from saved search — session may need re-authentication");
}
knownTotal = firstData.paging?.total ?? 0;
for (const el of firstData.elements ?? []) {
if (!el.entityUrn || seen.has(el.entityUrn)) continue;
seen.add(el.entityUrn);
allElements.push(el);
}
console.log(`[scraper:saved-search] page ${startPage}: ${allElements.length} elements, total=${knownTotal}`);
const totalPages = Math.ceil(knownTotal / PAGE_SIZE);
const endPage = Math.min(totalPages, startPage + maxPages - 1);
let lastPage = startPage;
onProgress?.({ phase: 'scraping', page: startPage, totalPages: endPage, count: allElements.length, total: knownTotal });
for (let pageNum = startPage + 1; pageNum <= endPage; pageNum++) {
if (isCanceled && (await isCanceled())) break;
const delayMs = 60000 + Math.random() * 60000;
console.log(`[scraper:saved-search] waiting ${Math.round(delayMs / 1000)}s before page ${pageNum}...`);
await page.waitForTimeout(delayMs);
if (isCanceled && (await isCanceled())) break;
let pageData = await waitForIntercept(buildUrl(pageNum), 15000);
if (!pageData || (pageData.elements?.length ?? 0) === 0) {
console.log(`[scraper:saved-search] page ${pageNum} empty on first try — retrying with 15s wait`);
pageData = await waitForIntercept(buildUrl(pageNum), 15000);
}
if (pageData) {
for (const el of pageData.elements ?? []) {
if (!el.entityUrn || seen.has(el.entityUrn)) continue;
seen.add(el.entityUrn);
allElements.push(el);
}
}
lastPage = pageNum;
console.log(`[scraper:saved-search] page ${pageNum}/${endPage}: ${allElements.length} (total ${knownTotal})`);
onProgress?.({ phase: 'scraping', page: pageNum, totalPages: endPage, count: allElements.length, total: knownTotal });
}
await page.close();
return {
profiles: allElements.map(el => profileToResult(el, null)),
lastPage,
knownTotal,
exhausted: lastPage >= totalPages,
};
}
/**
* Dispatcher — accepts either a lead list URL or a saved search URL.
* Callers don't need to know which type they're dealing with.
*/
export async function scrapeNavigatorUrl(
ctx: BrowserContext,
url: string,
opts: ScrapeOptions = {}
): Promise<WindowedScrapeResult> {
if (extractSavedSearchId(url)) {
return scrapeSavedSearch(ctx, url, opts);
}
if (extractListId(url)) {
return scrapeNavigatorList(ctx, url, opts);
}
throw new Error(`Unrecognized Sales Navigator URL. Expected a list URL (/sales/lists/people/...) or saved search URL (?savedSearchId=...)`);
}
File diff suppressed because it is too large Load Diff
+256
View File
@@ -0,0 +1,256 @@
import type { Page } from "playwright";
import { getDb } from "@/lib/db";
import { getSessionPage, saveSessionState, markNeedsReauth } from "@/lib/linkedin/session";
/**
* Accepted-connection sync via the authoritative Voyager connections API.
*
* Replaces the old absence-inference (scroll the SENT list, treat a vanished
* invite as "accepted"). That was measurably wrong: of 1,600 contacts it had
* marked degree=1, only 325 were genuinely connected — 1,275 were phantoms
* (invites that expired/withdrew/were ignored, not accepted). See docs §19.
*
* Sources — all proved against prod (Jul 2026), NO scrolling:
* - DATA: GET /voyager/api/relationships/dash/connections
* ?decorationId=…ConnectionListWithProfile-16&q=search
* &sortType=RECENTLY_ADDED&start=N&count=100
* → data["*elements"] (newest-first) + included[]: Connection { createdAt(ms),
* connectedMember } and Profile { publicIdentifier (vanity), entityUrn }.
* The API paginates to the end (30 pages for ~2947) in ~60s. It does NOT
* expose a grand total.
* - TOTAL (checksum): the connections PAGE header "<N> connections" <p>. Read
* once per full pass via a single navigation (NO scroll). A full pass is
* "verified complete" only when unique-pulled == declared total (matched ±0
* in prod). Presence in the list = 100% proof of a 1st-degree connection.
*
* Behaviour:
* - First run (boundary NULL) → FULL pass: page to the end, stamp degree=1 +
* connected_at from createdAt for every matched contact. If the pass is
* checksum-verified complete, ALSO un-mark phantom degree=1 contacts whose
* vanity is absent from the authoritative list (resets degree/connected_at).
* - Later runs → incremental: page from start=0 and STOP at the first
* connection older than the stored boundary (minus a 24h overlap margin).
* Incremental/incomplete passes are ADD-ONLY — they never un-mark (a partial
* pull must not wipe real accepts). Un-marking happens ONLY on a verified
* full pass.
* - Reuses the runner's shared browser (getSessionPage) — never a 2nd browser.
*/
const ACCEPTED_SYNC_INTERVAL_MS = 8 * 60 * 60 * 1000; // 8h — 3x per day
const PAGE_SIZE = 100;
const MAX_PAGES = 60; // safety cap (60 * 100 = 6000)
const OVERLAP_MARGIN_MS = 24 * 60 * 60 * 1000; // re-check a day of overlap (idempotent)
const DECORATION = "com.linkedin.voyager.dash.deco.web.mynetwork.ConnectionListWithProfile-16";
export function shouldSyncAccepted(accountId: string): boolean {
const db = getDb();
const row = db.prepare("SELECT accepted_sync_at FROM accounts WHERE id = ?").get(accountId) as
| { accepted_sync_at: string | null }
| undefined;
if (!row?.accepted_sync_at) return true;
return Date.now() - new Date(row.accepted_sync_at).getTime() >= ACCEPTED_SYNC_INTERVAL_MS;
}
interface ApiConnection {
vanity: string | null;
createdAt: number; // epoch ms
}
export async function syncAcceptedConnections(accountId: string): Promise<number> {
const db = getDb();
const page = await getSessionPage(accountId);
let stamped = 0;
try {
const boundaryRow = db.prepare("SELECT connections_synced_through_ms FROM accounts WHERE id = ?").get(accountId) as
| { connections_synced_through_ms: number | null }
| undefined;
const boundary = boundaryRow?.connections_synced_through_ms ?? null;
const isFullPass = boundary === null;
const stopBefore = boundary === null ? null : boundary - OVERLAP_MARGIN_MS;
// Read the declared total from the connections PAGE header (single nav, NO
// scroll). This is also our login-wall check and the completeness checksum.
await page.goto("https://www.linkedin.com/mynetwork/invite-connect/connections/", {
waitUntil: "domcontentloaded",
timeout: 35000,
});
await page.waitForTimeout(3500 + Math.random() * 1500);
if (/\/login|\/authwall|\/checkpoint|\/uas\//.test(page.url())) {
console.warn(`[sync-accepted] Session looks logged out (${page.url()}) — skipping`);
return 0;
}
const declaredTotal = await page.evaluate(() => {
const m = document.body.innerText.match(/([\d.,]+)\s+connections?/i);
return m ? parseInt(m[1].replace(/[.,]/g, ""), 10) : null;
});
const findByVanity = db.prepare(
`SELECT id, full_name, connected_at, degree FROM targets
WHERE linkedin_url LIKE ? AND connection_requested_at IS NOT NULL`
);
const stampAccepted = db.prepare(
"UPDATE targets SET degree = 1, connected_at = COALESCE(connected_at, ?) WHERE id = ?"
);
const seenVanities = new Set<string>(); // full-pass phantom check
let uniquePulled = 0;
let newestSeen: number | null = null;
let reachedBoundary = false;
for (let pageIdx = 0; pageIdx < MAX_PAGES; pageIdx++) {
const conns = await fetchConnectionsPage(page, pageIdx * PAGE_SIZE, PAGE_SIZE);
if (conns === null) {
console.warn(`[sync-accepted] connections API failed at start=${pageIdx * PAGE_SIZE} — stopping`);
break;
}
if (conns.length === 0) break; // end of list
for (const c of conns) {
uniquePulled++;
if (c.vanity) seenVanities.add(c.vanity);
if (newestSeen === null || c.createdAt > newestSeen) newestSeen = c.createdAt;
// Incremental early-exit (list is newest-first).
if (stopBefore !== null && c.createdAt < stopBefore) {
reachedBoundary = true;
break;
}
if (!c.vanity) continue;
for (const m of findByVanity.all(`%/in/${c.vanity}/%`) as Array<{
id: string; full_name: string | null; connected_at: string | null; degree: number | null;
}>) {
if (m.degree === 1 && m.connected_at) continue; // already correct
stampAccepted.run(msToSqlite(c.createdAt), m.id);
console.log(`[sync-accepted] Accepted: ${m.full_name ?? c.vanity}`);
stamped++;
}
}
if (reachedBoundary) break;
await page.waitForTimeout(900 + Math.random() * 700); // gentle, API-only
}
// Completeness checksum: a full pass is trustworthy only if what we pulled
// matches LinkedIn's own declared total (±5 slack for live churn).
const verifiedComplete =
isFullPass && declaredTotal !== null && Math.abs(uniquePulled - declaredTotal) <= 5;
// Correction: ONLY on a verified-complete full pass, un-mark phantom
// degree=1 contacts (present nowhere in the authoritative list). Never on an
// incremental/incomplete pass — a partial pull must not wipe real accepts.
let unmarked = 0;
if (verifiedComplete) {
const deg1 = db.prepare(
"SELECT id, full_name, linkedin_url FROM targets WHERE degree = 1 AND linkedin_url LIKE '%/in/%'"
).all() as Array<{ id: string; full_name: string | null; linkedin_url: string }>;
const unmark = db.prepare("UPDATE targets SET degree = NULL, connected_at = NULL WHERE id = ?");
const tx = db.transaction((rows: typeof deg1) => {
for (const t of rows) {
const mm = t.linkedin_url.match(/\/in\/([^/?#]+)/);
const v = mm ? decodeURIComponent(mm[1]).toLowerCase() : null;
if (!v || !seenVanities.has(v)) {
unmark.run(t.id);
unmarked++;
}
}
});
tx(deg1);
console.log(`[sync-accepted] Verified full pass (pulled ${uniquePulled} == declared ${declaredTotal}). Un-marked ${unmarked} phantom degree=1.`);
} else if (isFullPass) {
console.warn(`[sync-accepted] Full pass NOT verified complete (pulled ${uniquePulled}, declared ${declaredTotal}) — add-only, no un-marking.`);
}
// Advance the boundary to the newest connection seen this run.
if (newestSeen !== null) {
db.prepare("UPDATE accounts SET connections_synced_through_ms = ? WHERE id = ?").run(newestSeen, accountId);
}
// Store the declared total for visibility (Settings shows LinkedIn's count).
if (declaredTotal !== null) {
db.prepare("UPDATE accounts SET li_connections = ? WHERE id = ?").run(declaredTotal, accountId);
}
console.log(`[sync-accepted] Stamped ${stamped} accepted, un-marked ${unmarked} phantom (boundary=${newestSeen}).`);
} finally {
// B5 safety: only persist the session if still on a valid page.
let url = "";
try { url = page.url(); } catch { /* gone */ }
try { await page.close(); } catch { /* ignore */ }
if (/\/login|\/authwall|\/checkpoint|\/uas\//.test(url)) {
console.warn(`[sync-accepted] Ended on a wall (${url}) — not persisting; flagging re-auth`);
try { await markNeedsReauth(accountId); } catch { /* ignore */ }
} else {
try { await saveSessionState(accountId); } catch { /* ignore */ }
}
db.prepare("UPDATE accounts SET accepted_sync_at = datetime('now') WHERE id = ?").run(accountId);
}
return stamped;
}
// ── helpers ──────────────────────────────────────────────────────────────────
function msToSqlite(ms: number): string {
return new Date(ms).toISOString().replace("T", " ").slice(0, 19);
}
async function fetchConnectionsPage(page: Page, start: number, count: number): Promise<ApiConnection[] | null> {
return page.evaluate(
async ({ start, count, decoration }): Promise<ApiConnection[] | null> => {
const cookies = document.cookie.split("; ").reduce((a: Record<string, string>, c) => {
const i = c.indexOf("=");
if (i > 0) a[c.slice(0, i)] = c.slice(i + 1);
return a;
}, {});
const csrf = (cookies["JSESSIONID"] || "").replace(/"/g, "");
const url =
`https://www.linkedin.com/voyager/api/relationships/dash/connections` +
`?decorationId=${decoration}&count=${count}&q=search&sortType=RECENTLY_ADDED&start=${start}`;
let json: {
included?: Array<{
$type?: string;
entityUrn?: string;
createdAt?: number;
connectedMember?: string;
publicIdentifier?: string;
}>;
};
try {
const r = await fetch(url, {
headers: {
"csrf-token": csrf,
"accept": "application/vnd.linkedin.normalized+json+2.1",
"x-restli-protocol-version": "2.0.0",
"x-li-lang": "en_US",
},
credentials: "include",
});
if (!r.ok) return null;
json = await r.json();
} catch {
return null;
}
const included = json.included || [];
const vanityByUrn: Record<string, string> = {};
for (const x of included) {
if ((x.$type || "").includes("identity.profile.Profile") && x.entityUrn && x.publicIdentifier) {
vanityByUrn[x.entityUrn] = x.publicIdentifier;
}
}
const out: ApiConnection[] = [];
for (const x of included) {
if ((x.$type || "").includes("relationships.Connection") && typeof x.createdAt === "number") {
const memberUrn = x.connectedMember || null;
out.push({
createdAt: x.createdAt,
vanity: memberUrn ? vanityByUrn[memberUrn] ?? null : null,
});
}
}
out.sort((a, b) => b.createdAt - a.createdAt);
return out;
},
{ start, count, decoration: DECORATION }
);
}
+48
View File
@@ -0,0 +1,48 @@
import type { Page } from "playwright";
/**
* Visits a LinkedIn profile page. This registers as a profile view on LinkedIn.
* Navigates and waits, then reports whether the page shows a 1st-degree badge —
* lets the runner backfill degree=1 for contacts that were already connected
* before Linki ever sent them a connection request (e.g. manually added leads).
*
* Primary-degree signal: presence of the profile's primary "Message" link
* (a[href*="/messaging/compose"]) — only shown to 1st-degree connections, reads
* an href attribute rather than a CSS class or translated text, so it survives
* both LinkedIn's periodic class-name hashing and non-English UI languages.
*
* MUST be scoped to the visited person's own intro/top card — a page-wide
* search also matches "Message" links belonging to OTHER people rendered
* elsewhere on the page (sidebar modules like "People also viewed" / suggested
* connections). For a non-connected target, THEIR page has no such link, but
* the sidebar still does — a page-wide `.first()` silently grabbed a random
* unrelated 1st-degree connection's link, wrongly marked the target degree=1,
* and stored that stranger's messaging URN, causing messages to go to the
* wrong person entirely (incident: Jul 2026, see CLAUDE.md/memory). The top
* card is identified structurally as the section containing the page's own
* <h1> name heading, which is robust to LinkedIn's class-name hashing.
*
* Falls back to the old text-scrape (/\b1st\b/ within that same top card)
* when the link isn't found, in case the current account's profile layout
* doesn't render it as a plain link (e.g. buried behind a click/menu).
*
* The same link's href carries the messaging URN (urn:li:fsd_profile:ACoAA...)
* needed to message this person directly later without a name-search typeahead
* — see lib/linkedin/message.ts. Returned as messagingUrn when found.
*/
export async function visitProfile(page: Page, linkedinUrl: string): Promise<{ isFirstDegree: boolean; messagingUrn: string | null }> {
await page.goto(linkedinUrl, { waitUntil: "domcontentloaded", timeout: 30000 });
await page.waitForTimeout(3000 + Math.random() * 2000);
const topCard = page.locator("main section").filter({ has: page.locator("h1") }).first();
const messageLink = topCard.locator('a[href*="/messaging/compose"]').first();
const messageHref = (await messageLink.count()) > 0 ? await messageLink.getAttribute("href").catch(() => null) : null;
const urnMatch = messageHref?.match(/profileUrn=([^&]+)/);
const messagingUrn = urnMatch ? decodeURIComponent(urnMatch[1]) : null;
if (messageHref) return { isFirstDegree: true, messagingUrn };
const pageText = await topCard.innerText().catch(() => "");
return { isFirstDegree: /\b1st\b/.test(pageText), messagingUrn: null };
}