Files
ThothII/tools/tht/internal/installapply/import-bindings.mjs
T

41 lines
2.2 KiB
JavaScript

// Fixed client executed inside the released core; protected input arrives only through stdin.
export async function importPreparedBindings(base = "http://core:8787") {
let cookie = "", csrf = "", origin = "", completed = 0, code = "authentication_required";
const request = async (path, body) => fetch(base + path, {
method: body === undefined ? "GET" : "POST", redirect: "error", signal: AbortSignal.timeout(180000),
headers: { "content-type": "application/json", origin, ...(cookie ? { cookie } : {}), ...(csrf ? { "x-thothii-csrf": csrf } : {}) },
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
try {
let input = "";
for await (const chunk of process.stdin) { input += chunk; if (Buffer.byteLength(input) > 16 * 1024 * 1024) throw Error(); }
const prepared = JSON.parse(input); input = ""; origin = prepared.origin;
const login = await request("/auth/local/login", { username: prepared.username, password: prepared.password, remember: false });
prepared.password = "";
if (!login.ok) throw Error();
cookie = login.headers.get("set-cookie")?.split(";")[0] ?? "";
if (!cookie) throw Error();
const me = await request("/me"); if (!me.ok) throw Error();
csrf = (await me.json()).csrfToken; if (!csrf) throw Error();
code = "workspace_reconciliation_required";
const source = await request("/installation/workspace-source", prepared.source);
if (!source.ok) throw Error();
const { revision } = await source.json();
for (const entry of prepared.databases) {
code = "binding_import_failed";
const response = await request("/installation/bindings", { ...entry, revision });
if (response.status === 409) code = "binding_reconciliation_required";
if (response.status === 422) code = "container_connection_failed";
if (!response.ok) throw Error();
const value = await response.json();
if (value.connectionStatus !== "reachable" || !["applied", "unchanged"].includes(value.status)) throw Error();
completed++;
}
code = "bindings_ready";
} catch { process.exitCode = 1; }
finally {
if (cookie && csrf) { try { await request("/auth/logout", {}); } catch {} }
process.stdout.write(JSON.stringify({ ok: code === "bindings_ready", code, completed }));
}
}