import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import { mkdtemp, readFile, readdir, rm } from "node:fs/promises"; import http from "node:http"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; import { DatabaseSync } from "node:sqlite"; import { createPublicCloneAuthProxy } from "../../../../deploy/shared/public-clone-auth-proxy.js"; const root = process.cwd(); function listen(server) { return new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", () => resolve(server.address().port)); }); } function close(server) { return new Promise((resolve) => server.close(resolve)); } function cookieHeader(response) { return response.headers.getSetCookie().map((value) => value.split(";", 1)[0]).join("; "); } async function applyMigrations(path) { const sqlite = new DatabaseSync(path); sqlite.exec("PRAGMA foreign_keys = ON;"); const migrations = (await readdir(join(root, "drizzle"))).filter((file) => file.endsWith(".sql")).sort(); for (const migration of migrations) { const source = await readFile(join(root, "drizzle", migration), "utf8"); for (const statement of source.split("--> statement-breakpoint")) { if (statement.trim()) sqlite.exec(statement); } } sqlite.close(); } function d1Result(results = [], changes = 0, lastRowId = 0) { return { success: true, results, meta: { changed_db: changes > 0, changes, duration: 0, last_row_id: lastRowId, rows_read: results.length, rows_written: changes, size_after: 0, }, }; } test("standalone production runtime preserves OTP accounts, sessions, profiles, and posts through D1 restart", { timeout: 120_000 }, async () => { const directory = await mkdtemp(join(tmpdir(), "linkedin-container-runtime-")); const sqlitePath = join(directory, "linkedin.sqlite3"); await applyMigrations(sqlitePath); const sqlite = new DatabaseSync(sqlitePath); sqlite.exec("PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;"); const redis = new Map(); let deliveredCode = ""; let deliveredPayload = null; let mailProxySnapshot = null; const originalFetch = globalThis.fetch; globalThis.fetch = async (input, init) => { const url = input instanceof Request ? input.url : String(input); if (url === "https://api.resend.com/emails") { deliveredPayload = JSON.parse(String(init?.body || "{}")); deliveredCode = /(?:^|\D)([0-9]{6})(?:\D|$)/u.exec(deliveredPayload.text)?.[1] || ""; return new Response(JSON.stringify({ id: "accepted-runtime-mail" }), { status: 200, headers: { "content-type": "application/json" }, }); } return originalFetch(input, init); }; const linkedinAuthProxy = createPublicCloneAuthProxy({ siteId: "linkedin", siteLabel: "LinkedIn", }); const mock = http.createServer(async (request, response) => { let raw = ""; for await (const chunk of request) raw += chunk; response.setHeader("content-type", "application/json"); try { if (request.url === "/emails") { const accepted = await linkedinAuthProxy.resendOutbound(new Request( "http://resend.internal/emails", { method: "POST", headers: { "content-type": request.headers["content-type"] || "", "idempotency-key": request.headers["idempotency-key"] || "", }, body: raw, }, ), { RESEND_API_KEY: "runtime-resend-key", RESEND_FROM_EMAIL: "verified@example.com", }); const acceptedBody = await accepted.text(); mailProxySnapshot = { status: accepted.status, body: acceptedBody }; response.statusCode = accepted.status; response.end(acceptedBody); return; } if (request.url === "/linkedin-db") { const envelope = JSON.parse(raw); assert.equal(envelope.protocol, "linkedin.d1.v1"); const execute = (entry, operation, column) => { const statement = sqlite.prepare(entry.query); const values = entry.values.map((value) => typeof value === "boolean" ? Number(value) : value); if (operation === "run") { const result = statement.run(...values); return d1Result([], Number(result.changes), Number(result.lastInsertRowid)); } if (operation === "raw") { statement.setReturnArrays(true); try { return statement.all(...values); } finally { statement.setReturnArrays(false); } } if (operation === "first") { const row = statement.get(...values) || null; return row && column ? row[column] : row; } return d1Result(statement.all(...values)); }; let result; if (envelope.operation === "batch") { sqlite.exec("BEGIN IMMEDIATE"); try { result = envelope.statements.map((entry) => execute(entry, "all")); sqlite.exec("COMMIT"); } catch (error) { sqlite.exec("ROLLBACK"); throw error; } } else { result = execute(envelope, envelope.operation, envelope.column); } response.end(JSON.stringify({ ok: true, protocol: "linkedin.d1.v1", result })); return; } const commands = JSON.parse(raw); const results = commands.map(([name, key, value, ...options]) => { if (name === "SET") { if (options.includes("NX") && redis.has(key)) return { result: null }; redis.set(key, value); return { result: "OK" }; } if (name === "GET") return { result: redis.has(key) ? redis.get(key) : null }; if (name === "GETDEL") { const result = redis.has(key) ? redis.get(key) : null; redis.delete(key); return { result }; } if (name === "DEL") return { result: redis.delete(key) ? 1 : 0 }; if (name === "INCR") { const result = Number(redis.get(key) || 0) + 1; redis.set(key, String(result)); return { result }; } if (name === "EXPIRE") return { result: 1 }; return { error: "unsupported" }; }); response.end(JSON.stringify(results)); } catch (error) { response.statusCode = 500; response.end(JSON.stringify({ error: error instanceof Error ? error.message : "mock failure" })); } }); const mockPort = await listen(mock); const reservation = http.createServer(); const appPort = await listen(reservation); await close(reservation); const origin = `http://127.0.0.1:${appPort}`; const smokeToken = "c".repeat(64); let child; let logs = ""; function startApp() { const processChild = spawn(process.execPath, ["scripts/start-standalone.mjs"], { cwd: root, env: { ...process.env, APP_URL: origin, DEFAULT_TENANT_SLUG: "northstar-systems", DEPLOYMENT_BUILD_ID: "d".repeat(40), HOSTNAME: "127.0.0.1", LINKEDIN_D1_PROXY_URL: `http://127.0.0.1:${mockPort}/linkedin-db`, NODE_ENV: "production", PORT: String(appPort), PUBLIC_CLONE_AUTH_MODE: "redis-resend", PUBLIC_CLONE_AUTH_REDIS_REST_URL: `http://127.0.0.1:${mockPort}`, PUBLIC_CLONE_AUTH_RESEND_API_URL: `http://127.0.0.1:${mockPort}/emails`, PUBLIC_CLONE_AUTH_SITE_ID: "linkedin", PUBLIC_CLONE_AUTH_SITE_LABEL: "LinkedIn", PUBLIC_CLONE_SMOKE_TOKEN: smokeToken, SESSION_COOKIE_SECURE: "false", SESSION_SECRET: "runtime-session-secret-that-is-long-enough-1234", SOURCE_REF: "d".repeat(40), }, stdio: ["ignore", "pipe", "pipe"], }); processChild.stdout.on("data", (chunk) => { logs = `${logs}${chunk}`.slice(-40_000); }); processChild.stderr.on("data", (chunk) => { logs = `${logs}${chunk}`.slice(-40_000); }); return processChild; } async function stopApp() { if (!child || child.exitCode !== null) return; child.kill("SIGTERM"); await Promise.race([ new Promise((resolve) => child.once("exit", resolve)), new Promise((resolve) => setTimeout(resolve, 3_000)), ]); if (child.exitCode === null) child.kill("SIGKILL"); } async function waitForHealth() { for (let attempt = 0; attempt < 120; attempt += 1) { const response = await fetch(`${origin}/healthz`).catch(() => null); if (response?.status === 200) return response; await new Promise((resolve) => setTimeout(resolve, 250)); } assert.fail(`standalone runtime did not become healthy:\n${logs}`); } try { child = startApp(); const health = await waitForHealth(); assert.equal(health.headers.get("x-websitebench-container-build-id"), "d".repeat(40)); const registration = await fetch(`${origin}/public-register`); const publicCookie = cookieHeader(registration); const email = "runtime-account@example.test"; const username = "runtime-e2e"; const password = "RuntimePassword123"; const sent = await fetch(`${origin}/api/auth/send-code`, { method: "POST", headers: { "content-type": "application/json", cookie: publicCookie, origin, "x-public-clone-smoke-token": smokeToken }, body: JSON.stringify({ email }), }); assert.equal(sent.status, 202, `mail proxy snapshot: ${JSON.stringify(mailProxySnapshot)}`); const sentBody = await sent.json(); assert.match(deliveredCode, /^[0-9]{6}$/u); assert.equal(sentBody.smoke_code, deliveredCode); assert.deepEqual(deliveredPayload, { from: "LinkedIn ", to: [email], subject: "LinkedIn verification code", html: `

Your LinkedIn verification code is:

${deliveredCode}

This code expires in 5 minutes.

If you did not request it, you can ignore this message.

`, text: `Your LinkedIn verification code is:\n\n${deliveredCode}\n\nThis code expires in 5 minutes.\n\nIf you did not request it, you can ignore this message.`, tags: [ { name: "purpose", value: "registration" }, { name: "site", value: "linkedin" }, ], }); const verified = await fetch(`${origin}/api/auth/verify-code`, { method: "POST", headers: { "content-type": "application/json", cookie: publicCookie, origin }, body: JSON.stringify({ email, code: deliveredCode }), }); assert.equal(verified.status, 200); const form = new FormData(); form.set("email", email); form.set("name", "Runtime Account"); form.set("username", username); form.set("password", password); const account = await fetch(`${origin}/public-register`, { method: "POST", headers: { cookie: publicCookie, origin }, body: form, redirect: "manual", }); assert.equal(account.status, 303, `account creation failed:\n${logs}`); assert.equal(account.headers.get("location"), "/feed"); let authenticatedCookie = cookieHeader(account); const replay = await fetch(`${origin}/public-register`, { method: "POST", headers: { cookie: publicCookie, origin }, body: form, redirect: "manual", }); assert.equal(replay.status, 400); assert.match(await replay.text(), /fresh WebsiteBench code/); const me = await fetch(`${origin}/api/me`, { headers: { cookie: authenticatedCookie } }); assert.equal(me.status, 200); assert.equal((await me.json()).user.username, username); const feedPage = await fetch(`${origin}/feed`, { headers: { cookie: authenticatedCookie }, redirect: "manual" }); assert.equal(feedPage.status, 200); const profilePage = await fetch(`${origin}/profile/${username}`, { headers: { cookie: authenticatedCookie }, redirect: "manual" }); assert.equal(profilePage.status, 200); const profile = await fetch(`${origin}/api/profile/${username}`); assert.equal(profile.status, 200); assert.equal((await profile.json()).user.name, "Runtime Account"); const logout = await fetch(`${origin}/api/auth/logout`, { method: "POST", headers: { cookie: authenticatedCookie, origin }, }); assert.equal(logout.status, 200); const loggedOutMe = await fetch(`${origin}/api/me`, { headers: { cookie: cookieHeader(logout) } }); assert.equal(loggedOutMe.status, 401); const login = await fetch(`${origin}/api/auth/login`, { method: "POST", headers: { "content-type": "application/json", origin }, body: JSON.stringify({ email, password }), }); assert.equal(login.status, 200, `password login failed:\n${logs}`); authenticatedCookie = cookieHeader(login); const postText = `Runtime persistent post ${Date.now()}`; const createdPost = await fetch(`${origin}/api/posts`, { method: "POST", headers: { "content-type": "application/json", cookie: authenticatedCookie, origin }, body: JSON.stringify({ content: postText }), }); assert.equal(createdPost.status, 201, `post creation failed:\n${logs}`); const postId = (await createdPost.json()).post.id; assert.ok(postId); const postsBeforeRestart = await fetch(`${origin}/api/posts`); assert.ok((await postsBeforeRestart.json()).posts.some((entry) => entry.post.id === postId)); await stopApp(); child = startApp(); await waitForHealth(); const persistedSession = await fetch(`${origin}/api/me`, { headers: { cookie: authenticatedCookie } }); assert.equal(persistedSession.status, 200); assert.equal((await persistedSession.json()).user.username, username); const postsAfterRestart = await fetch(`${origin}/api/posts`); assert.ok((await postsAfterRestart.json()).posts.some((entry) => entry.post.id === postId && entry.post.content === postText)); assert.equal(sqlite.prepare("SELECT count(*) AS count FROM users WHERE email = ?").get(email).count, 1); assert.equal(sqlite.prepare("SELECT count(*) AS count FROM memberships WHERE user_id = (SELECT id FROM users WHERE email = ?)").get(email).count, 1); assert.equal(sqlite.prepare("SELECT count(*) AS count FROM posts WHERE id = ?").get(postId).count, 1); } finally { globalThis.fetch = originalFetch; await stopApp(); sqlite.close(); await close(mock); await rm(directory, { recursive: true, force: true }); } });