import type postgres from 'postgres'; import type { RepositorySql } from '../repositories/db'; /** A scoped transaction is not a user authorization or payment verification. */ export async function withCreditTenant( sql: RepositorySql, tenantId: string, action: (tx: postgres.TransactionSql) => Promise, ): Promise { if (typeof tenantId !== 'string' || !tenantId.trim() || tenantId.length > 256) throw new Error('Invalid credit tenant'); return sql.begin(async (tx) => { const roles = await tx<{ rolsuper: boolean; rolbypassrls: boolean }[]>` SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user`; if (!roles[0] || roles[0].rolsuper || roles[0].rolbypassrls) throw new Error('Credits require an RLS-enforced database role'); // Do not silently run against pre-migration credit tables. Policy bodies // themselves remain a trusted migration/database-administrator boundary. const gates = await tx<{ enabled: boolean }[]>` SELECT COUNT(*) = 4 AS enabled FROM (VALUES ('opt_credit_accounts', 'opt_credit_accounts_tenant'), ('opt_credit_reservations', 'opt_credit_reservations_tenant'), ('opt_credit_events', 'opt_credit_events_tenant'), ('opt_credit_purchases', 'opt_credit_purchases_tenant') ) AS expected(table_name, policy_name) JOIN pg_class AS c ON c.oid = to_regclass(expected.table_name) WHERE c.relrowsecurity AND c.relforcerowsecurity AND (SELECT COUNT(*) FROM pg_policy AS p WHERE p.polrelid = c.oid) = 1 AND EXISTS (SELECT 1 FROM pg_policy AS p WHERE p.polrelid = c.oid AND p.polname = expected.policy_name)`; if (gates[0]?.enabled !== true) throw new Error('Credit tenant isolation migration is not active'); await tx`SELECT set_config('app.opt_credit_tenant_id', ${tenantId}, true)`; return action(tx); }) as Promise; }