import { getDbClient, type DbClient } from "@hivegrid/db/client.server"; import { runWithRlsContext } from "@hivegrid/db/rls-context.server"; const DATABASE_COMMANDS = new Set([ "audit", "dsgvo", "feature-flags", "forms", "leads", "marketing", "outbox", "search", "sequences", ]); const OPERATOR_PLUGIN_COMMANDS = new Set(["list", "enable", "disable", "uninstall", "verify-audit-chain"]); const OPERATOR_TENANT_COMMANDS = new Set(["snapshot", "restore"]); type OperatorDbClient = Pick; export type RunCliWithRlsOptions = { rawArgs: readonly string[]; env?: NodeJS.ProcessEnv; execute: () => Promise; client?: OperatorDbClient; }; /** * Runs database-backed operator commands with the same authenticated identity * contract as the admin application. Authoring, scaffolding and backup tools * stay usable without opening a database connection. */ export async function runCliWithRls(options: RunCliWithRlsOptions): Promise { if (!requiresOperatorIdentity(options.rawArgs)) { await options.execute(); return; } const env = options.env ?? process.env; const userId = requireIdentifier(env.HIVEGRID_CLI_OPERATOR_USER_ID, "HIVEGRID_CLI_OPERATOR_USER_ID"); const tenantId = readTenantArgument(options.rawArgs); await runWithRlsContext({ userId, ...(tenantId ? { tenantId } : {}) }, async () => { const client = options.client ?? getDbClient(); const operator = await client.adminUser.findUnique({ where: { id: userId }, select: { id: true, status: true, }, }); if (operator?.status !== "active") { throw new Error("HIVEGRID_CLI_OPERATOR_USER_ID must reference an active HiveGrid AdminUser"); } await options.execute(); }); } export function requiresOperatorIdentity(rawArgs: readonly string[]): boolean { if (rawArgs.some((argument) => argument === "--help" || argument === "-h" || argument === "--version" || argument === "-v")) { return false; } const [command, subcommand] = readCommandPath(rawArgs); if (!command) return false; if (DATABASE_COMMANDS.has(command)) return true; if (command === "plugins") return subcommand ? OPERATOR_PLUGIN_COMMANDS.has(subcommand) : false; if (command === "tenant") return subcommand ? OPERATOR_TENANT_COMMANDS.has(subcommand) : false; return command === "ops" && (subcommand === "impersonate" || subcommand === "product-acquisition-recovery"); } export function readTenantArgument(rawArgs: readonly string[]): string | undefined { for (let index = 0; index < rawArgs.length; index += 1) { const argument = rawArgs[index]; const inline = argument.match(/^--(?:tenant|tenantId|tenant-id)=(.+)$/u)?.[1]; const candidate = inline ?? (argument === "--tenant" || argument === "--tenantId" || argument === "--tenant-id" ? rawArgs[index + 1] : undefined); if (!candidate || candidate === "all" || candidate === "__platform__" || candidate.startsWith("-")) continue; return requireIdentifier(candidate, "tenant argument"); } const positional = rawArgs.filter((argument) => !argument.startsWith("-")); if (positional[0] === "ops" && positional[1] === "impersonate" && positional[2]) { return requireIdentifier(positional[2], "tenant argument"); } return undefined; } function readCommandPath(rawArgs: readonly string[]): [string | undefined, string | undefined] { const commandIndex = rawArgs.findIndex((argument) => !argument.startsWith("-")); if (commandIndex < 0) return [undefined, undefined]; const command = rawArgs[commandIndex]; const subcommand = rawArgs.slice(commandIndex + 1).find((argument) => !argument.startsWith("-")); return [command, subcommand]; } function requireIdentifier(value: string | undefined, name: string): string { const normalized = value?.trim() ?? ""; if (normalized.length === 0 || normalized.length > 191 || normalized.includes("\u0000")) { throw new Error(`${name} must be a non-empty database identifier`); } return normalized; }