Cotton code
149 lines · 7.4 KB · TypeScriptRaw
/** * The Worker under `wrangler dev` for an end-to-end script: a free port, its * storage in the script's temp dir, every binding local (no account token), the fixed code 123456, a fresh admin token * and vault key; the personal object onboarded under import-personal's default slug for an invented owner * and entered in the directory (the address is the open host, as cottondb.com * is), and the owner signed in. Nothing here reaches a deployed object. */import { spawn, spawnSync, type ChildProcess } from "node:child_process";import { randomBytes } from "node:crypto";import { openSync, readFileSync } from "node:fs";import { createServer } from "node:net";import { join, resolve } from "node:path";import { fileURLToPath } from "node:url";import { personalSlug } from "../dev-server";export const APP = resolve(fileURLToPath(import.meta.url), "../../..");export const OWNER = "+919000000009";export function check(ok: unknown, what: string): void {  if (!ok) throw new Error(`FAILED: ${what}`);  console.log(`  ok  ${what}`);}async function freePort(): Promise<number> {  return new Promise((done, fail) => {    const s = createServer();    s.once("error", fail);    s.listen(0, "127.0.0.1", () => {      const port = (s.address() as { port: number }).port;      s.close(() => done(port));    });  });}/** Stop a process group: SIGTERM, a grace of five seconds, then SIGKILL. */export function stop(child: ChildProcess | null): void {  if (!child?.pid) return;  try {    process.kill(-child.pid, "SIGTERM");  } catch {    return;  }  const until = Date.now() + 5000;  while (Date.now() < until) {    try {      process.kill(-child.pid, 0);    } catch {      return;    }    spawnSync("sleep", ["0.2"]);  }  try {    process.kill(-child.pid, "SIGKILL");  } catch {    /* gone */  }}export function pnpm(args: string[], env: Record<string, string> = {}): { status: number; out: string; err: string } {  const r = spawnSync("pnpm", ["-s", ...args], { cwd: APP, env: { ...process.env, ...env }, encoding: "utf8" });  return { status: r.status ?? -1, out: r.stdout, err: r.stderr };}export type Api = <T = Record<string, unknown>>(method: string, path: string, body?: unknown, bearer?: string) => Promise<T>;export interface DevWorker {  child: ChildProcess;  base: string;  /** A call to the personal object, refused calls thrown with their answer. */  api: Api;  /** The local Worker's admin token (a dev wrangler's own, never a real one). */  admin: string;  /** The owner's credential, from the fixed code. */  credential: string;}/** * `wrangler dev` up with nothing onboarded: its address (the open host), its * admin token and the child. `started` is handed the child as soon as it is * spawned, so the caller's cleanup stops it however this ends. */export async function startWrangler(tmp: string, started: (child: ChildProcess) => void, vars: Record<string, string> = {}, again?: { admin: string; vault: string; service: string; port: number }): Promise<{ child: ChildProcess; base: string; admin: string; vault: string; service: string; port: number }> {  // Started again on the same storage (a run that kills it midway): the same keys and port, or the directory's numbers no longer open.  const admin = again?.admin ?? `adm-${randomBytes(12).toString("hex")}`;  const vault = again?.vault ?? randomBytes(32).toString("base64url");  const service = again?.service ?? randomBytes(32).toString("base64url");  const port = again?.port ?? (await freePort());  const base = `http://127.0.0.1:${port}`;  const log = openSync(join(tmp, "wrangler.log"), again ? "a" : "w");  const child = spawn(    "pnpm",    // --local: no remote binding (AI, the calendar's embedder, would need the account's token); an event's kind is left unjudged.    ["-s", "wrangler", "dev", "--local", "--port", String(port), "--ip", "127.0.0.1", "--persist-to", join(tmp, "state"), "--show-interactive-dev-session=false",      "--var", `ADMIN_TOKEN:${admin}`, "--var", `VAULT_KEY:${vault}`, "--var", `SERVICE_TOKEN_KEY:${service}`, "--var", "OTP_MODE:fixed", "--var", "OTP_FIXED_CODE:123456",      // A local Worker is a dev one: `fixed` runs only where ENV_LABEL is dev (src/auth.ts `otpMode`), and this reads the live config.      "--var", "ENV_LABEL:dev",      // The open host is this address: the phone reaches its object by its credential, the scripts by /b/<personalSlug> (config/dev-server.json).      // wrangler dev otherwise hands the Worker its first route's host (cottondb.com), the live open host.      "--var", "OPEN_HOST:127.0.0.1", "--local-upstream", `127.0.0.1:${port}`, "--upstream-protocol", "http",      // A script's own vars (a fake Spotify's address, its client).      ...Object.entries(vars).flatMap(([k, v]) => ["--var", `${k}:${v}`])],    { cwd: APP, detached: true, stdio: ["ignore", log, log], env: { ...process.env, CI: "1", WRANGLER_SEND_METRICS: "false" } },  );  started(child);  const until = Date.now() + 120_000;  for (;;) {    try {      if ((await fetch(`${base}/health`)).ok) break;    } catch {      /* not up yet */    }    if (Date.now() > until || child.exitCode !== null) throw new Error(`wrangler dev did not come up:\n${readFileSync(join(tmp, "wrangler.log"), "utf8").slice(-3000)}`);    await new Promise((r) => setTimeout(r, 500));  }  console.log(`wrangler dev at ${base}`);  return { child, base, admin, vault, service, port };}/** * `wrangler dev` up, the personal object onboarded for `database`, the owner signed in. * `started` is handed the child as soon as it is spawned, so the caller's * cleanup stops it however this ends. */export async function startDevWorker(tmp: string, database: string, started: (child: ChildProcess) => void, vars: Record<string, string> = {}): Promise<DevWorker> {  const { child, base, admin } = await startWrangler(tmp, started, vars);  const onboard = pnpm(["onboard", personalSlug(), "--base", base, "--owner", OWNER, "--database-id", database], { BUSINESS_ADMIN_TOKEN: admin });  check(onboard.status === 0, `onboard the personal object${onboard.status ? `\n${onboard.out}${onboard.err}` : ""}`);  const entered = await fetch(`${base}/v1/admin/directory`, {    method: "POST",    headers: { "content-type": "application/json", authorization: `Bearer ${admin}` },    body: JSON.stringify({ database_id: database, slug: personalSlug(), phone: OWNER }),  });  check(entered.ok, `the personal object is entered in the directory${entered.ok ? "" : `\n${await entered.text()}`}`);  const api: Api = async <T = Record<string, unknown>>(method: string, path: string, body?: unknown, bearer?: string): Promise<T> => {    const r = await fetch(`${base}/b/${personalSlug()}${path}`, {      method,      headers: { "content-type": "application/json", ...(bearer ? { authorization: `Bearer ${bearer}` } : {}) },      body: body === undefined ? undefined : JSON.stringify(body),    });    const text = await r.text();    if (!r.ok) throw new Error(`${method} ${path} → ${r.status} ${text.slice(0, 300)}`);    return JSON.parse(text) as T;  };  const code = await api<{ challenge_id: string }>("POST", "/v1/code", { phone: OWNER, device_id: "e2e" });  const signed = await api<{ credential: string; person: { role: string } }>("POST", "/v1/sign-in", { challenge_id: code.challenge_id, code: "123456", device_id: "e2e" });  check(signed.person.role === "owner", "the owner signs in with the fixed code");  return { child, base, api, admin, credential: signed.credential };}