import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { readFile, readdir } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import test from "node:test";
import { promisify } from "node:util";
const root = fileURLToPath(new URL("..", import.meta.url));
const execFileAsync = promisify(execFile);
async function filesUnder(dir) {
const entries = await readdir(dir, { withFileTypes: true });
const nested = await Promise.all(entries.map(async (entry) => {
const path = join(dir, entry.name);
if (entry.isDirectory()) return filesUnder(path);
return path;
}));
return nested.flat();
}
test("package exposes enterprise validation and database commands", async () => {
const pkg = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
for (const script of ["dev", "build", "start", "typecheck", "lint", "test", "test:e2e:registration", "test:e2e:public-main", "preflight", "verify", "db:migrate", "db:seed"]) {
assert.ok(pkg.scripts[script], `missing ${script}`);
}
});
test("database migration covers core product tables", async () => {
const migrationFiles = (await readdir(join(root, "drizzle"))).filter((file) => file.endsWith(".sql")).sort();
const migration = (await Promise.all(migrationFiles.map((file) => readFile(join(root, "drizzle", file), "utf8")))).join("\n");
for (const table of ["users", "email_verification_tokens", "subscriptions", "organizations", "memberships", "posts", "post_likes", "comments", "connections", "follows", "messages", "notifications", "jobs", "job_applications", "saved_jobs", "audit_logs"]) {
assert.match(migration, new RegExp(`CREATE TABLE [\\x60]?${table}[\\x60]?\\b`), `missing ${table}`);
}
assert.match(migration, /'northstar-systems'/);
assert.match(migration, /'maya@example\.com'/);
assert.match(migration, /'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'/);
});
test("database adapter is SQLite/D1-only and public registration uses an atomic D1 batch", async () => {
const db = await readFile(join(root, "db", "index.ts"), "utf8");
const schema = await readFile(join(root, "db", "schema.ts"), "utf8");
const registration = await readFile(join(root, "app", "public-register", "route.ts"), "utf8");
assert.match(db, /drizzle-orm\/d1/);
assert.match(db, /LINKEDIN_D1_PROXY_URL/);
assert.match(db, /LINKEDIN_SQLITE_PATH/);
assert.doesNotMatch(db + schema, /postgres-js|pg-core/);
assert.match(schema, /sqliteTable/);
assert.match(registration, /await db\.batch\(\[/);
assert.doesNotMatch(registration, /db\.transaction/);
});
test("auth UI keeps a quiet account-boundary disclosure", async () => {
const authForm = await readFile(join(root, "components", "AuthForm.tsx"), "utf8");
const notice = await readFile(join(root, "components", "ReplicaSafetyNotice.tsx"), "utf8");
assert.match(authForm, /ReplicaSafetyNotice/);
assert.match(notice, /WebsiteBench account/);
assert.match(notice, /Not affiliated with LinkedIn/);
assert.match(notice, /Use a unique password here/);
assert.doesNotMatch(authForm, /local test/i);
});
test("registration requires email verification before session issuance", async () => {
const registerRoute = await readFile(join(root, "app", "api", "auth", "register", "route.ts"), "utf8");
const loginRoute = await readFile(join(root, "app", "api", "auth", "login", "route.ts"), "utf8");
const verificationLib = await readFile(join(root, "lib", "email-verification.ts"), "utf8");
assert.match(registerRoute, /sendVerificationEmail/);
assert.match(registerRoute, /requiresVerification/);
assert.doesNotMatch(registerRoute, /issueSession/);
assert.match(loginRoute, /email_unverified/);
assert.match(verificationLib, /set\(\{ consumedAt: issuedAt \}\)/);
assert.match(verificationLib, /eq\(emailVerificationTokens\.userId, user\.id\)/);
assert.match(verificationLib, /isNull\(emailVerificationTokens\.consumedAt\)/);
});
test("auth mutations enforce bounded rate limits", async () => {
const rateLimit = await readFile(join(root, "lib", "rate-limit.ts"), "utf8");
const registerRoute = await readFile(join(root, "app", "api", "auth", "register", "route.ts"), "utf8");
const loginRoute = await readFile(join(root, "app", "api", "auth", "login", "route.ts"), "utf8");
const confirmRoute = await readFile(join(root, "app", "api", "auth", "verification", "confirm", "route.ts"), "utf8");
const resendRoute = await readFile(join(root, "app", "api", "auth", "verification", "resend", "route.ts"), "utf8");
assert.match(rateLimit, /rate_limited/);
assert.match(rateLimit, /hashIdentifier/);
assert.match(rateLimit, /x-forwarded-for/);
assert.match(registerRoute, /auth\.register\.ip/);
assert.match(registerRoute, /auth\.register\.email/);
assert.match(loginRoute, /auth\.login\.ip/);
assert.match(loginRoute, /auth\.login\.email/);
assert.match(confirmRoute, /auth\.verification\.confirm\.ip/);
assert.match(confirmRoute, /auth\.verification\.confirm\.token/);
assert.match(resendRoute, /auth\.verification\.resend\.ip/);
assert.match(resendRoute, /auth\.verification\.resend\.email/);
});
test("same-origin mutations respect forwarded and host headers", async () => {
const api = await readFile(join(root, "lib", "api.ts"), "utf8");
const origin = await readFile(join(root, "lib", "request-origin.ts"), "utf8");
assert.match(api, /requestOrigin\(request\)/);
assert.doesNotMatch(api, /new URL\(request\.url\)\.origin/);
assert.match(origin, /x-forwarded-host/);
assert.match(origin, /hostHeader/);
});
test("local preview sessions can reach protected pages after public registration", async () => {
const proxy = await readFile(join(root, "proxy.ts"), "utf8");
assert.match(proxy, /PUBLIC_CLONE_AUTH_MODE === "local-dev"/);
assert.match(proxy, /linkedin_local_session/);
assert.match(proxy, /hasSession = .*hasLocalPreviewSession/);
});
test("sessions prune expired rows and track last seen activity", async () => {
const sessionLib = await readFile(join(root, "lib", "session.ts"), "utf8");
assert.match(sessionLib, /function pruneExpiredSessions/);
assert.match(sessionLib, /delete\(sessions\)\.where\(lt\(sessions\.expiresAt, now\)\)/);
assert.match(sessionLib, /await pruneExpiredSessions\(\)/);
assert.match(sessionLib, /set\(\{ lastSeenAt: new Date\(\) \}\)/);
assert.match(sessionLib, /where\(eq\(sessions\.id, session\.sessionId\)\)/);
});
test("billing integration is locked to Stripe test mode", async () => {
const stripeLib = await readFile(join(root, "lib", "stripe.ts"), "utf8");
const premium = await readFile(join(root, "components", "Premium.tsx"), "utf8");
const cardForm = await readFile(join(root, "components", "StripeCardForm.tsx"), "utf8");
const webhookRoute = await readFile(join(root, "app", "api", "billing", "webhook", "route.ts"), "utf8");
assert.match(stripeLib, /sk_test_/);
assert.match(stripeLib, /STRIPE_TEST_PROXY_URL/);
assert.match(stripeLib, /payment_method: "pm_card_visa"/);
assert.match(stripeLib, /STRIPE_TEST_AMOUNT_MINOR = 2999/);
assert.match(stripeLib, /livemode !== false/);
assert.match(stripeLib, /\/v1\/setup_intents/);
assert.match(stripeLib, /setupIntents\.create/);
assert.match(stripeLib, /subscriptions\.create/);
assert.match(stripeLib, /save_default_payment_method/);
assert.match(stripeLib, /status: "incomplete"/);
assert.match(cardForm, /inputMode="numeric"/);
assert.match(cardForm, /placeholder="MM \/ YY"/);
assert.match(cardForm, /placeholder="CVC"/);
assert.match(cardForm, /body: JSON\.stringify\(\{ setupIntentId \}\)/);
assert.doesNotMatch(cardForm, /JSON\.stringify\(\{[^}]*card(?:holder|Number)|billing_details/iu);
assert.doesNotMatch(cardForm, /postal|address|phone/iu);
assert.match(webhookRoute, /webhooks\.constructEvent/);
assert.match(webhookRoute, /constructStripeEvent/);
assert.match(webhookRoute, /stripe_signature_missing/);
assert.match(webhookRoute, /stripe_signature_invalid/);
assert.match(webhookRoute, /StripeSignatureVerificationError/);
assert.match(premium, /Stripe Test Mode/);
});
test("public billing uses the isolated Stripe sandbox and still fails closed when disabled", async () => {
const stripe = await readFile(join(root, "lib", "stripe.ts"), "utf8");
const premium = await readFile(join(root, "components", "Premium.tsx"), "utf8");
const subscription = await readFile(join(root, "app", "api", "billing", "subscription", "route.ts"), "utf8");
assert.match(stripe, /PUBLIC_DEPLOYMENT_DISABLE_STRIPE/);
assert.match(stripe, /billing_not_available/);
assert.doesNotMatch(stripe, /PUBLIC_DEPLOYMENT_DISABLE_STRIPE === "true"\s*\|\|/u);
assert.match(subscription, /billingAvailable:\s*false/u);
assert.match(premium, /Add a test card/);
assert.match(premium, /No card is attached to this account/);
assert.match(premium, /Stripe sandbox payment verified/);
const completion = await readFile(join(root, "app", "api", "billing", "complete", "route.ts"), "utf8");
assert.match(completion, /completeStripeCardSubscription/);
assert.match(completion, /setupIntentId/);
assert.match(completion, /requireSameOrigin/);
assert.match(completion, /requireUser/);
});
test("shipped media is local and the deployed migration repairs existing rows", async () => {
const source = [
await readFile(join(root, "lib", "demo-data.ts"), "utf8"),
await readFile(join(root, "scripts", "seed.ts"), "utf8"),
await readFile(join(root, "components", "Profile.tsx"), "utf8"),
await readFile(join(root, "app", "companies", "[slug]", "page.tsx"), "utf8"),
].join("\n");
assert.doesNotMatch(source, /images\.unsplash\.com/u);
for (const file of ["maya-chen.jpg", "jordan-lee.jpg", "priya-raman.jpg", "noah-williams.jpg", "workshop.jpg", "company-office.jpg", "profile-cover.jpg"]) {
assert.ok((await readFile(join(root, "public", "media", file))).length > 1_000, `${file} is missing or empty`);
}
const migration = await readFile(join(root, "drizzle", "0002_local_media.sql"), "utf8");
assert.match(migration, /UPDATE users SET avatar_url = '\/media\/maya-chen\.jpg'/u);
assert.match(migration, /UPDATE posts SET media_url = '\/media\/workshop\.jpg'/u);
});
test("legacy automatic Stripe test activations are removed without touching accounts", async () => {
const migration = await readFile(join(root, "drizzle", "0003_remove_automatic_test_payments.sql"), "utf8");
assert.match(migration, /DELETE FROM subscriptions/u);
assert.match(migration, /stripe_price_id = 'price_linkedin_premium_test_2999'/u);
assert.match(migration, /checkout_session_id LIKE 'pi_%'/u);
assert.doesNotMatch(migration, /DELETE FROM users|DELETE FROM posts/u);
});
test("network invitations are removed after response", async () => {
const network = await readFile(join(root, "components", "Network.tsx"), "utf8");
assert.match(network, /const \[invitations, setInvitations\]/);
assert.match(network, /fetch\("\/api\/connections", \{ cache: "no-store" \}\)/);
assert.match(network, /if \(!response\.ok \|\| !result\.connection\?\.id\) throw/);
assert.match(network, /setInvitations\(\(items\) => items\.filter\(\(invitation\) => invitation\.connectionId !== id\)\)/);
assert.match(network, /const pending = invitations\.length/);
assert.doesNotMatch(network, /fetch\("\/api\/connections"[\s\S]*?\.catch\(\(\) => \{\}\)/);
});
test("profile connection requests wait for API confirmation", async () => {
const profile = await readFile(join(root, "components", "Profile.tsx"), "utf8");
assert.match(profile, /async function requestConnection/);
assert.match(profile, /fetch\("\/api\/connections"/);
assert.match(profile, /if \(!response\.ok \|\| !result\.connection\?\.id\) throw/);
assert.match(profile, /setConnectionStatusById\(\(items\) => \(\{ \.\.\.items, \[recipientId\]: status \}\)\)/);
assert.match(profile, /connectionLabel\(recipientId: string\)/);
assert.match(profile, /suggestionPeople\.map/);
assert.doesNotMatch(profile, /setConnected\(true\)/);
});
test("member identity and profile details come from the signed-in session", async () => {
const sessionHook = await readFile(join(root, "lib", "client-session.ts"), "utf8");
const shell = await readFile(join(root, "components", "AppShell.tsx"), "utf8");
const sidebar = await readFile(join(root, "components", "Sidebar.tsx"), "utf8");
const profile = await readFile(join(root, "components", "Profile.tsx"), "utf8");
assert.match(sessionHook, /fetch\("\/api\/auth\/session"/);
assert.match(shell, /useCurrentUser/);
assert.match(sidebar, /useCurrentUser/);
assert.match(profile, /fetch\(`\/api\/profile\/\$\{encodeURIComponent\(username\)\}`/);
assert.match(profile, /fetch\("\/api\/profile", \{ method: "PATCH"/);
assert.match(profile, /fetch\("\/api\/profile\/experiences", \{ method: "POST"/);
assert.match(profile, /Edit intro/);
assert.match(profile, /Add experience/);
});
test("feed follows persist and supplementary member menus are available", async () => {
const feed = await readFile(join(root, "components", "Feed.tsx"), "utf8");
const followRoute = await readFile(join(root, "app", "api", "follows", "route.ts"), "utf8");
const shell = await readFile(join(root, "components", "AppShell.tsx"), "utf8");
const sidebar = await readFile(join(root, "components", "Sidebar.tsx"), "utf8");
assert.match(feed, /fetch\("\/api\/follows", \{ method: "POST"/);
assert.match(feed, /fetch\("\/api\/follows", \{ cache: "no-store"/);
assert.match(feed, /onFollowingChange\(post\.author\.id, result\.following\)/);
assert.match(followRoute, /targetUserIds/);
assert.match(followRoute, /member\.followed/);
assert.match(followRoute, /member\.unfollowed/);
for (const label of ["Puzzle games", "Groups", "Events", "Newsletters"]) assert.match(shell, new RegExp(label));
assert.match(sidebar, /Today's puzzles/);
});
test("messaging keeps sent messages scoped to the active conversation", async () => {
const messaging = await readFile(join(root, "components", "Messaging.tsx"), "utf8");
assert.match(messaging, /messagesByPerson/);
assert.match(messaging, /async function send/);
assert.match(messaging, /if \(!response\.ok \|\| !result\.message\?\.id\) throw/);
assert.match(messaging, /\[active\.id\]: \[\.\.\.\(items\[active\.id\] \?\? \[\]\), \{ mine: true, body, time: "Now" \}\]/);
assert.match(messaging, /activeMessages\.map/);
assert.match(messaging, /filteredConversations/);
assert.match(messaging, /Search messages/);
for (const label of ["Focused", "Unread", "Jobs", "Connections", "InMail", "Starred"]) assert.match(messaging, new RegExp(label));
assert.doesNotMatch(messaging, /fetch\("\/api\/messages"[\s\S]*?\.catch\(\(\) => \{\}\)/);
});
test("notifications filters do not nest menu buttons inside row links", async () => {
const notifications = await readFile(join(root, "components", "Notifications.tsx"), "utf8");
assert.match(notifications, /const \[activeFilter, setActiveFilter\]/);
assert.match(notifications, /filteredNotifications/);
assert.match(notifications, /setOpenMenuId\(open \? null : item\.id\)/);
assert.match(notifications, / {
const jobs = await readFile(join(root, "components", "Jobs.tsx"), "utf8");
assert.match(jobs, /const \[applicationJobId, setApplicationJobId\]/);
assert.match(jobs, /function openApplication\(jobId: string\)/);
assert.match(jobs, /async function submitApplication/);
assert.match(jobs, /role="dialog"/);
assert.match(jobs, /Submit application/);
assert.doesNotMatch(jobs, /onClick=\{\(\) => apply\(selected\.id\)\}/);
});
test("saved jobs are persisted only after API confirmation", async () => {
const jobsView = await readFile(join(root, "components", "Jobs.tsx"), "utf8");
const jobsRoute = await readFile(join(root, "app", "api", "jobs", "route.ts"), "utf8");
assert.match(jobsRoute, /saveJobSchema/);
assert.match(jobsRoute, /action: z\.literal\("save"\)/);
assert.match(jobsRoute, /savedJobs/);
assert.match(jobsRoute, /action: "job\.saved"/);
assert.match(jobsView, /async function saveJob\(jobId: string\)/);
assert.match(jobsView, /JSON\.stringify\(\{ action: "save", jobId \}\)/);
assert.match(jobsView, /result\.savedJob\?\.jobId !== jobId/);
assert.match(jobsView, /setSaved\(\(items\) => items\.includes\(jobId\) \? items : \[\.\.\.items, jobId\]\)/);
assert.doesNotMatch(jobsView, /setSaved\(\(items\) => \[\.\.\.items, (job|selected)\.id\]\)/);
});
test("registration e2e submits the Easy Apply modal", async () => {
const e2e = await readFile(join(root, "scripts", "e2e-registration.mjs"), "utf8");
assert.match(e2e, /getByRole\("dialog", \{ name: \/Apply to\/i \}\)/);
assert.match(e2e, /getByRole\("button", \{ name: "Submit application" \}\)\.click\(\)/);
assert.match(e2e, /appliedButton\.waitFor/);
assert.doesNotMatch(e2e, /getByRole\("button", \{ name: "Easy Apply" \}\)\.click\(\);\n\s*await page\.getByRole\("button", \{ name: \/Applied\/i \}\)/);
});
test("feed interactions update UI only after API confirmation", async () => {
const feed = await readFile(join(root, "components", "Feed.tsx"), "utf8");
assert.match(feed, /async function submit/);
assert.match(feed, /async function toggleLike/);
assert.match(feed, /async function addComment/);
assert.match(feed, /if \(!response\.ok \|\| !result\.post\?\.id\) throw/);
assert.match(feed, /if \(!response\.ok \|\| typeof result\.liked !== "boolean"\) throw/);
assert.match(feed, /if \(!response\.ok \|\| !result\.comment\?\.id\) throw/);
assert.match(feed, /onPost\(value, result\.post\.id\)/);
assert.match(feed, /setLiked\(result\.liked\)/);
assert.match(feed, /const likeDelta = liked === post\.liked \? 0 : liked \? 1 : -1/);
assert.doesNotMatch(feed, /catch\(\(\) => \{\}\)/);
});
test("deployment preflight validates production readiness without printing secrets", async () => {
const script = await readFile(join(root, "scripts", "preflight.mjs"), "utf8");
assert.match(script, /STRIPE_SECRET_KEY/);
assert.match(script, /sk_test_/);
assert.match(script, /SESSION_COOKIE_SECURE/);
assert.match(script, /EMAIL_DELIVERY_MODE/);
const secret = "a".repeat(40);
const stripeKey = "sk_test_1234567890abcdef1234567890";
const webhookSecret = "whsec_" + "1234567890abcdef";
const { stdout } = await execFileAsync(process.execPath, [join(root, "scripts", "preflight.mjs"), "--production"], {
env: {
PATH: process.env.PATH,
NODE_ENV: "production",
APP_ENV: "production",
LINKEDIN_D1_PROXY_URL: "http://d1.internal/linkedin-db",
SESSION_SECRET: secret,
EMAIL_VERIFICATION_SECRET: "b".repeat(40),
SESSION_COOKIE_SECURE: "true",
APP_URL: "https://linkedin.example.test",
DEFAULT_TENANT_SLUG: "northstar-systems",
EMAIL_DELIVERY_MODE: "smtp",
MAIL_FROM: "LinkedIn ",
SMTP_HOST: "smtp.linkedin.example.test",
SMTP_PORT: "587",
SMTP_SECURE: "false",
STRIPE_SECRET_KEY: stripeKey,
STRIPE_PREMIUM_PRICE_ID: "price_1234567890abcdef",
STRIPE_WEBHOOK_SECRET: webhookSecret,
},
});
const result = JSON.parse(stdout);
assert.equal(result.ok, true);
assert.equal(result.mode, "production");
assert.match(stdout, /STRIPE_SECRET_KEY/);
assert.doesNotMatch(stdout, new RegExp(secret));
assert.doesNotMatch(stdout, new RegExp(stripeKey));
});
test("application source does not link to linkedin.com", async () => {
const sourceFiles = (await filesUnder(join(root, "app"))).concat(await filesUnder(join(root, "components")), await filesUnder(join(root, "lib")));
const offenders = [];
for (const file of sourceFiles.filter((path) => /\.(ts|tsx|css)$/.test(path))) {
const text = await readFile(file, "utf8");
if (/linkedin\.com/i.test(text)) offenders.push(file.replace(root, ""));
}
assert.deepEqual(offenders, []);
});