File size: 14,520 Bytes
062a991
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
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 <verified@example.com>",
      to: [email],
      subject: "LinkedIn verification code",
      html: `<p>Your LinkedIn verification code is:</p><p>${deliveredCode}</p><p>This code expires in 5 minutes.</p><p>If you did not request it, you can ignore this message.</p>`,
      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 });
  }
});