// The Baserow API client — baserow's own code, living in the module (novox/hq ADR 0039). Both this // module's tools and anything else baserow-specific import it; nothing outside baserow does. // // Baserow authenticates a person with email + password, exchanged for a JWT at /api/user/token-auth/. // The standard image creates no admin from env, so the account is one a person made in Baserow: its // password is the module's `admin` secret, accepted from the operator, and its email and the public // host Baserow answers to reach the runtime config file the mesh mounts (the email from the // assignment's settings). Until both are there fromEnv throws and the module exposes no tools — the // same dormant-until-configured shape gitea uses for its token. import { readFileSync } from "node:fs"; import { request as httpRequest } from "node:http"; import { request as httpsRequest } from "node:https"; export interface BaserowApplication { id: number; name: string; type: string; } export interface BaserowRow { id: number; [key: string]: unknown; } function meshConfig(file?: string): Record { if (!file) return {}; try { return JSON.parse(readFileSync(file, "utf8")) as Record; } catch { return {}; } } export class BaserowClient { readonly baseUrl: string; private token: string | null = null; constructor( url: string, private readonly email: string, private readonly password: string, private readonly hostHeader?: string, ) { this.baseUrl = url.replace(/\/+$/, ""); } /** * Build from the module's resolved environment. URL, credentials and an optional Host override * come from the runtime config file first (MESH_BASEROW_CONFIG_FILE), then the mesh's own env * names, then the bare BASEROW_* names. Credentials are required — without them there is no * authenticated call to make, so this throws rather than hand back a client that fails on first use. */ static fromEnv(env: NodeJS.ProcessEnv = process.env): BaserowClient { const cfg = meshConfig(env.MESH_BASEROW_CONFIG_FILE); const url = cfg.url ?? env.MESH_BASEROW_URL ?? env.BASEROW_URL ?? "http://127.0.0.1:80"; const email = cfg.email ?? env.MESH_BASEROW_EMAIL ?? env.BASEROW_EMAIL; const password = cfg.password ?? env.MESH_BASEROW_PASSWORD ?? env.BASEROW_PASSWORD; // Baserow's bundled Caddy routes by the Host header against BASEROW_PUBLIC_URL; a co-located // caller reaching it over the container network may need to present that host. const hostHeader = cfg.host ?? env.MESH_BASEROW_HOST; if (!email || !password) { throw new Error("no Baserow credentials — set MESH_BASEROW_EMAIL and MESH_BASEROW_PASSWORD"); } return new BaserowClient(url, email, password, hostHeader); } private headers(extra: Record = {}): Record { const h: Record = { "Content-Type": "application/json", ...extra }; if (this.hostHeader) h.Host = this.hostHeader; return h; } /** * One HTTP exchange. Not `fetch`: Node's fetch drops a caller's Host header and sends the URL's * own, and Baserow answers only the host of its BASEROW_PUBLIC_URL — any other Host is looked up * as a published builder site and gets 404, `/api/_health/` included. A co-located caller reaching * it by container name must present the public host, so the request is made with node:http, which * sends the Host it is given. */ private send(path: string, method: string, headers: Record, body?: string): Promise<{ status: number; text: string }> { const url = new URL(`${this.baseUrl}${path}`); const request = url.protocol === "https:" ? httpsRequest : httpRequest; // A length, never chunked: Baserow's server reads a chunked body as empty. const sent = body === undefined ? headers : { ...headers, "Content-Length": String(Buffer.byteLength(body)) }; return new Promise((resolve, reject) => { const req = request(url, { method, headers: sent }, (res) => { let text = ""; res.setEncoding("utf8"); res.on("data", (chunk: string) => (text += chunk)); res.on("end", () => resolve({ status: res.statusCode ?? 0, text })); res.on("error", reject); }); req.on("error", reject); if (body !== undefined) req.write(body); req.end(); }); } /** Exchange email + password for a JWT, caching it until Baserow refuses it. Handles both the * older `{ token }` and the newer `{ access_token }` response shapes. */ async authenticate(): Promise { if (this.token) return this.token; const res = await this.send( "/api/user/token-auth/", "POST", this.headers(), JSON.stringify({ email: this.email, password: this.password }), ); if (res.status < 200 || res.status >= 300) throw new Error(`baserow auth failed: ${res.status} ${res.text}`); const data = JSON.parse(res.text) as { token?: string; access_token?: string }; const token = data.access_token ?? data.token; if (!token) throw new Error("baserow auth returned no token"); this.token = token; return token; } /** An authenticated GET. A refused token is dropped and the call made once more with a fresh one: * Baserow's access tokens expire after minutes, and the runtime lives for weeks. */ private async authed(path: string): Promise { for (let attempt = 0; ; attempt++) { const token = await this.authenticate(); const res = await this.send(path, "GET", this.headers({ Authorization: `JWT ${token}` })); if (res.status === 401 && attempt === 0) { this.token = null; continue; } if (res.status < 200 || res.status >= 300) throw new Error(`baserow ${path}: ${res.status} ${res.text}`); return (res.text ? JSON.parse(res.text) : null) as T; } } /** The applications (databases) the account can see, across all its workspaces. */ async listApplications(): Promise { return (await this.authed(`/api/applications/`)) ?? []; } /** Rows of a table, by numeric table id, with human field names. */ async listRows(tableId: number, size = 100): Promise { const data = await this.authed<{ results: BaserowRow[] }>( `/api/database/rows/table/${tableId}/?size=${size}&user_field_names=true`, ); return data?.results ?? []; } }