Files
2026-11-16 17:26:44 -08:00

107 lines
5.5 KiB
TypeScript

/** Real control API + PostgreSQL + full web app, with local-only authentication.
* No production entrypoint/auth changes. No external integrations or satellites.
* DATABASE_URL must name a dedicated local streamline_profiles_dev database.
*/
import path from "node:path";
const root = path.resolve(import.meta.dir, "..");
const databaseUrl = process.env.DATABASE_URL;
if (!databaseUrl) throw new Error("Set DATABASE_URL to the isolated local development database");
const dbUrl = new URL(databaseUrl);
if (dbUrl.hostname !== "127.0.0.1" || dbUrl.pathname !== "/streamline_profiles_dev") {
throw new Error("Local runner only accepts 127.0.0.1/streamline_profiles_dev; refusing other databases");
}
const webPort = 63868;
const apiPort = 63869;
const webOrigin = `http://127.0.0.1:${webPort}`;
if (!process.argv.includes("--server")) {
// Child processes never inherit production .env credentials, and Bun/Vite
// automatic env-file loading is disabled as well.
const env = {
PATH: process.env.PATH || "/opt/homebrew/bin:/usr/bin:/bin",
TMPDIR: process.env.TMPDIR || "/tmp",
NODE_ENV: "development",
DATABASE_URL: databaseUrl,
LOCAL_DEV_SESSION_TOKEN: crypto.randomUUID(),
APP_BASE_URL: webOrigin,
LARK_CLI_BIN: "/usr/bin/false",
CLUSTER_SECRET: crypto.randomUUID(),
BITS_SKIP_USER_TOKEN: "1",
};
const children = [
Bun.spawn([process.execPath, "--no-env-file", import.meta.path, "--server"], { cwd: root, env, stdout: "inherit", stderr: "inherit" }),
Bun.spawn([process.execPath, "--no-env-file", path.join(root, "control-web/node_modules/vite/bin/vite.js"), "--config", "vite.local.config.ts"], { cwd: path.join(root, "control-web"), env, stdout: "inherit", stderr: "inherit" }),
];
let stopping = false;
const stop = () => {
if (stopping) return;
stopping = true;
for (const child of children) try { child.kill("SIGTERM"); } catch { /* exited */ }
};
process.on("SIGINT", stop);
process.on("SIGTERM", stop);
const code = await Promise.race(children.map((child) => child.exited));
stop();
await Promise.all(children.map((child) => child.exited));
process.exit(code);
} else {
const token = process.env.LOCAL_DEV_SESSION_TOKEN;
if (!token || process.env.NODE_ENV !== "development") throw new Error("Start through the local launcher");
// Only identity is substituted; the real SSO resolver, admin guard and every
// task/configuration handler still run. All other outbound fetches are denied.
globalThis.fetch = (async (input: string | Request | URL, init?: RequestInit) => {
const url = new URL(input instanceof Request ? input.url : String(input));
const headers = new Headers(init?.headers || (input instanceof Request ? input.headers : undefined));
if (url.origin === "https://cloudapi.bytedance.net" && url.pathname === "/faas/services/ttuae2/invoke/getUserInfo" && headers.get("x-tt-session-v2") === token) {
return Response.json({ data: { email: "streamline-local@bytedance.com", name: "本地测试管理员" } });
}
throw new Error(`External integrations are disabled in local development (${url.hostname})`);
}) as typeof fetch;
const { Hono } = await import(Bun.resolveSync("hono", path.join(root, "control-server"))) as typeof import("../control-server/node_modules/hono");
const { api } = await import("../control-server/src/routes");
const { attach, detach } = await import("../control-server/src/bus");
const { readAdminPrefixes, setAdminPrefixes } = await import("../control-server/src/admin_db");
const { closePool } = await import("../control-server/src/db_client");
await setAdminPrefixes([...await readAdminPrefixes(), "streamline-local"]);
const app = new Hono();
app.use("*", async (c, next) => {
// Bind only loopback and reject DNS-rebinding/foreign-site write requests.
if (c.req.header("host") !== `127.0.0.1:${apiPort}`) return c.json({ error: "Local host only" }, 403);
const origin = c.req.header("origin");
if (origin && origin !== webOrigin) return c.json({ error: "Local origin only" }, 403);
const pathname = c.req.path;
if (/^\/api\/(internal|deploy|rsi|lab|lark|openapi)(\/|$)/.test(pathname)) return c.json({ error: "External integrations and execution are disabled locally" }, 403);
const read = c.req.method === "GET" || c.req.method === "HEAD";
const allowedWrite = ["/api/import", "/api/features", "/api/admin/product-profiles", "/api/me/prefs", "/api/me/groups"].includes(pathname);
if (!read && !allowedWrite) return c.json({ error: "Local testing supports product settings, preferences and task creation only" }, 403);
return next();
});
app.route("/api", api);
const server = Bun.serve({
hostname: "127.0.0.1", port: apiPort,
fetch(req, srv) {
if (new URL(req.url).pathname === "/ws") {
if (req.headers.get("origin") !== webOrigin) return new Response("Local origin only", { status: 403 });
if (srv.upgrade(req)) return;
return new Response("Upgrade failed", { status: 400 });
}
return app.fetch(req);
},
websocket: { open(ws) { attach(ws); }, close(ws) { detach(ws); }, message() {} },
});
console.log(`[local] Real API: http://127.0.0.1:${server.port}; UI: ${webOrigin}`);
console.log("[local] PostgreSQL: streamline_profiles_dev. Local test admin. No production data, external calls, job runners or MR submission.");
let stopping = false;
const stop = async () => {
if (stopping) return;
stopping = true;
server.stop(true);
await closePool();
process.exit(0);
};
process.on("SIGINT", stop);
process.on("SIGTERM", stop);
}