import type { SessionAttachmentReadAccess } from "./session-file-attachments.js"; import { type SQL } from "drizzle-orm"; import type { PgDatabase, PgTransactionConfig } from "drizzle-orm/pg-core"; import type { Settings } from "@opengeni/config"; import postgres from "postgres"; import { type DatabaseCredentialEventListener, type DatabasePasswordFiles } from "./database-credentials.js"; import { type IdempotentPersistenceTransactionOptions } from "./persistence-errors.js"; import { type SessionListChangeSource } from "./session-list-notifications.js"; export type Database = Omit, "query" | "transaction"> & { transaction(run: (tx: DatabaseTransaction) => Promise, config?: PgTransactionConfig): Promise; }; type DatabaseTransaction = Database & { rollback(): never; }; declare const sessionActivityDatabaseBrand: unique symbol; /** * A workspace-scoped session writer transaction. The BEFORE row trigger stamps * activity in the same write; the brand retains the writer/tenancy boundary. */ export type SessionActivityDatabase = Database & { readonly [sessionActivityDatabaseBrand]: true; }; export type DbClient = { db: Database; close: () => Promise; }; export type RlsContext = { accountId: string; workspaceId?: string | null; }; /** The requested tenant no longer exists. Other scope/setup failures stay errors. */ export declare class WorkspaceNotFoundError extends Error { readonly workspaceId: string; constructor(workspaceId: string); } export type SessionRlsActorContext = { /** Server-authorized session attachment scope; never taken from request JSON. */ sessionAttachmentReadAccess?: SessionAttachmentReadAccess; subjectId: string; /** Host-verified personal file ownership, never a request-supplied subject. */ privateFileOwnerSubjectId?: string | null; initiatingHumanSubjectId?: string | null; /** Root reconstructed from a verified live agent attempt, never page input. */ agentRootSessionId?: string | null; }; /** Request-local proof from the signed published-Site gateway and live viewer cookie. */ export type SiteViewerRlsContext = Readonly<{ siteId: string; principal: string; }>; export declare function currentSiteViewerRlsContext(): SiteViewerRlsContext | undefined; export declare function withSiteViewerRlsContext(context: SiteViewerRlsContext, run: () => T): T; export declare function currentSessionAttachmentReadAccess(): SessionAttachmentReadAccess | undefined; /** * The ambient session RLS actor established by the caller, if any. Read-only: * helpers use it to decide whether the caller already owns session access and * must never mutate it. */ export declare function currentSessionRlsActorContext(): Readonly | undefined; /** * Runs `fn` with no session RLS actor, so its reads see the tenant as the * system does (private chats included). Only for narrow reads whose result is * never disclosed to the request, or whose disclosure a durable binding * already authorizes (a chat's own agent, read for its system prompt); not * re-exported from the package. */ export declare function withoutSessionRlsActor(fn: () => Promise): Promise; /** * Stable identity of the ambient session RLS actor: every field that * `setRlsContext` turns into database-visible GUCs or that scoped reads * consult. Two callers with equal keys see exactly the same rows, so the key * is safe for sharing a read result between them; `null` means no actor, in * which case the subject GUC stays empty for every such caller. */ export declare function currentSessionRlsActorIdentityKey(): string | null; /** * The ambient session RLS actor's frozen initiating human: `undefined` when * there is no actor, `null` when the actor has no human. Reads that must act * for the turn's human take it from here, never from a caller argument. */ export declare function currentSessionRlsActorInitiatingHumanSubjectId(): string | null | undefined; export declare function withSessionRlsActorContext(actor: SessionRlsActorContext, fn: () => Promise): Promise; /** * RLS posture for the connection Opengeni's query layer runs over (Step I, §7.7). * * - `"force"` (DEFAULT — today's standalone behavior, byte-for-byte): Opengeni * connects as a NON-OWNER role (`opengeni_app`) and every table carries * `FORCE ROW LEVEL SECURITY`, so the workspace/account GUCs set by * `setRlsContext` are the ONLY thing that admits rows — even the table owner * is subject to RLS. This is the Fork-A isolation guarantee. * - `"scoped"` (embedded Fork-B opt-in): the host runs Opengeni's queries over a * role that OWNS the dedicated schema (RLS need not be forced for that role), * relying on the host's own tenant boundary. Opengeni STILL emits the * `set_config('opengeni.account_id'/'workspace_id', …)` GUCs defensively on * every scoped query, so the application query path is byte-identical between * the two strategies and the app code is RLS-mode-agnostic. The strategy is a * declared posture (consumed by `provisionRoles` and as a documented * invariant), NOT a query-path branch — there is deliberately no `if * (strategy === …)` anywhere in the helpers below. Picking `"scoped"` does not * relax any GUC; it only changes which DB role the host provisions/connects as * and asserts that the host accepts owning the isolation boundary. */ export type RlsStrategy = "force" | "scoped"; /** * Resolve a host-IdP/Better-Auth user *identifier* by email. Injected via * `createDb({ userLookup })` (Step I). UNSET → today's raw parameterized select * against Better Auth's `auth_users` table (see `getManagedUserByEmail`), which * relies on the postgres-js array-shaped `db.execute` result. An embedded host * whose identity lives elsewhere (a different IdP table, a different driver, or * a non-`auth_users` user store) injects this closure so Opengeni never touches * `auth_users` directly. Returns the user id, or null when no such user exists. */ export type UserLookup = (db: Database, email: string) => Promise; export type ManagedUserProfile = { id: string; name: string | null; email: string; /** * The host has verified that this person controls `email`. Only verified * addresses are bound for Site SQL's `:viewer_email`; omitted means unknown. */ emailVerified?: boolean; }; /** Host identity projection used by organization administration rosters. */ export type UserProfileLookup = (db: Database, userIds: readonly string[]) => Promise; export type CreateDbOptions = { /** Direct or session-pooled PostgreSQL URL for API list invalidations. Lazy; never a transaction pooler. */ notificationDatabaseUrl?: string; /** * The Postgres `search_path` for this connection (Step I, §7.8 runtime half). * UNSET → today's behavior: NO `search_path` startup parameter is sent, so the * server default applies (`public` for standalone, where every table + the * `vector` extension + `gen_random_uuid()` live). For an embedded dedicated * schema, pass e.g. `"opengeni,opengeni_private,public"` — postgres-js sends * it as a per-session startup parameter (the supported, query-param-free way; * URL `?search_path=` is IGNORED by postgres-js). Keep `public` LAST so the * `vector` type and `gen_random_uuid()` (which live in `public` on the * pgvector image) still resolve — the schema-isolation contract live footgun. */ searchPath?: string; /** RLS posture; defaults to `"force"` (today's standalone). */ rlsStrategy?: RlsStrategy; /** Host-provided user-by-email resolver; unset → today's raw `auth_users` query. */ userLookup?: UserLookup; /** Host-provided user profile projection; unset → standalone `auth_users`. */ userProfileLookup?: UserProfileLookup; /** postgres-js pool size; defaults to today's `10`. */ max?: number; /** * How long a refused first connection is retried while the client has never * reached the server; defaults to the boot grace. 0 fails immediately. */ bootConnectGraceMs?: number; /** * Use named prepared statements. Unset → {@link defaultDatabasePreparedStatements}: * on for a direct connection, off behind PgBouncer's port. Pass `false` for any * other transaction-pooling proxy. */ preparedStatements?: boolean; /** * Seconds an idle pooled connection stays open before it closes. Unset → * {@link DEFAULT_DATABASE_POOL_IDLE_TIMEOUT_SECONDS}; 0 keeps idle connections * open until their lifetime ends. */ idleTimeoutSeconds?: number; /** * Upper bound, in seconds, on a pooled connection's age. Each connection slot * draws its own lifetime between 75% and 100% of this, so connections opened * together do not all reconnect together. Unset → * {@link DEFAULT_DATABASE_POOL_MAX_LIFETIME_SECONDS}; 0 never recycles. */ maxLifetimeSeconds?: number; /** * Connection-local default transaction isolation sent in the postgres-js * startup parameters. This is intentionally not a role/database default: * tests and embedded callers can exercise a different ambient isolation * without mutating a shared PostgreSQL role or affecting other connections. */ isolationLevel?: postgres.ConnectionParameters["default_transaction_isolation"]; /** * Read the login's password from mounted files on every connection attempt * instead of from the URL, so it can be rotated while the process runs (see * `RotatingDatabasePassword`). Unset (or no file configured) → today's * behavior: the URL password, no password function, no added retry. Also * applies to the session-list LISTEN connection when * `notificationDatabaseUrl` logs in as the same user. */ passwordFiles?: DatabasePasswordFiles; /** * Content-free credential events (switches, reloads) of the pool and of its * LISTEN connection; defaults to a console line. */ onCredentialEvent?: DatabaseCredentialEventListener; }; /** * The active RLS strategy + userLookup for an injected `Database`, recorded in a * side WeakMap so helpers (and `getManagedUserByEmail`) can consult the host's * binding without changing every call signature. A handle with no recorded * config (e.g. one built outside `createDb`, or in a test) falls back to the * standalone defaults: `rlsStrategy: "force"`, raw `auth_users` lookup. */ type DbBinding = { rlsStrategy: RlsStrategy; userLookup?: UserLookup; userProfileLookup?: UserProfileLookup; sessionListChanges?: SessionListChangeSource; cancellableTransactions?: boolean; }; /** Absent for externally constructed handles or transaction-only connections. */ export declare function sessionListChangesFor(db: Database): SessionListChangeSource | undefined; /** The strategy bound to a handle (or the `"force"` default). */ export declare function rlsStrategyFor(db: Database): RlsStrategy; /** * Run a raw SQL query and read its rows as a typed array. * * Why this exists: the Step I driver widening (`Database = PgDatabase`) * deliberately sets the query-result HKT to `any` so `db.execute(…)` is callable * across drivers whose raw-result shapes differ (postgres-js → row array; * node-postgres → `{ rows }`). A side effect is that `db.execute(…)` now * resolves to `any`, erasing the per-row element type at the call site. Opengeni's * OWN internal raw queries usually run over the postgres-js handle `createDb` * builds (array result), while an embedded host may inject a node-postgres style * driver (`{ rows }`). Normalize those two standard shapes in one place; reject * an unknown driver result rather than silently treating it as an empty query. */ export declare function rawRows>(executor: Pick, query: SQL): Promise; export type SandboxProviderReadLockIdentity = { workspaceId: string; sandboxGroupId: string; leaseEpoch: number; instanceId: string; }; export declare class SandboxProviderReadLockUnavailableError extends Error { constructor(); } /** * Cross-process exclusive boundary for one exact live provider instance's * API-direct read request. Modal accepts concurrent commands from one attached * handle, but independent API replicas reconstruct different handles; issuing * overlapping command groups through those handles can make an otherwise valid * read fail transiently. Keep concurrency inside one batched request while * serializing only separate requests that target the same lease identity. * * The callback intentionally runs while one transaction-pinned DB connection * holds the advisory lock. The direct lease holder separately prevents drain, * and the abort-aware bounded poll prevents a disconnected HTTP request from * occupying the connection indefinitely. */ export declare function withSandboxProviderReadLock(db: Database, identity: SandboxProviderReadLockIdentity, signal: AbortSignal | undefined, fn: () => Promise): Promise; /** Jittered reconnect delay in seconds after `retries` consecutive connection failures. */ export declare function databaseReconnectBackoffSeconds(retries: number): number; /** * Whether a pool should use named prepared statements when the operator has not * said. A direct Postgres connection should: postgres-js otherwise sends every * parameterized statement unnamed and must wait for a Describe reply before it * can Bind, so each such statement costs two round trips instead of one, and the * server re-parses and re-plans it every time. A transaction-pooling PgBouncer * must not: named statements live on one backend, the pooler hands the next * transaction a different one, and execution intermittently fails with * `prepared statement "s_N" does not exist`. Port 6432 is the only signal the URL * carries; other poolers need `preparedStatements: false` explicitly. */ export declare function defaultDatabasePreparedStatements(databaseUrl: string): boolean; /** * Each PostgreSQL backend keeps its catalog cache, and the plans of every * statement it has prepared, until the connection closes. Measured on the * migrated schema as the FORCE-RLS runtime role, a backend that has run the * app's statements holds about 45 MB unprepared and 125-220 MB prepared, and an * idle one keeps all of it. Close idle connections after 30 seconds: reopening * costs the next query a connection handshake (tens of milliseconds) and about * 0.25 ms of cache warmup per statement it runs again. */ export declare const DEFAULT_DATABASE_POOL_IDLE_TIMEOUT_SECONDS = 30; /** * The pool reuses the most recently idle connection first, so a busy * connection never reaches the idle timeout. Its memory keeps growing with * every new statement text, every generic plan, and every IN-list or multi-row * VALUES arity it prepares. Recycling at most every ten minutes bounds that * growth; a new backend pays its warmup again (well under a second for every * statement the app runs), about 0.05% of the lifetime. */ export declare const DEFAULT_DATABASE_POOL_MAX_LIFETIME_SECONDS = 600; /** * The longest timer the runtime can arm (2^31 - 1 ms). A longer delay does not * wait longer: Node and Bun fire it after 1 ms, which would close every * connection right after it opens or goes idle. Use 0 to turn a timer off. */ export declare const MAX_DATABASE_POOL_TIMER_SECONDS = 2147483; /** * postgres.js evaluates a function `max_lifetime` once per connection slot, * which is how its own default (30-60 minutes) is jittered. Draw from the top * quarter below the configured bound so the bound holds. */ export declare function jitteredDatabaseMaxLifetime(maxSeconds: number): () => number; /** Pool options taken from deployment settings; unset fields keep the pool defaults. */ export declare function databasePoolOptions(settings: Pick): Pick; /** * Postgres refuses to reuse a prepared statement whose result columns changed * since it was prepared: SQLSTATE 0A000, "cached plan must not change result * type", raised from `RevalidateCachedQuery` before the statement runs. A * rolling migration that adds a column causes it for every statement that * expands the table's row (`select *`, `table.*`, `returning *`, a CTE or * function over that row) on connections the running release prepared earlier. * Found directly or through a wrapping error's `cause` (Drizzle wraps query * failures). Other 0A000 errors are unrelated features and do not match. */ export declare function isStalePreparedResultError(error: unknown): boolean; export declare function createDb(databaseUrl: string, options?: CreateDbOptions): DbClient; /** Run maintenance within its caller's existing deadline, not a new timeout. * Keep any shorter configured statement timeout. A disconnected caller is * detected during execution, including an abrupt process exit. A network * partition remains subject to TCP failure detection and the server deadline. * Unsupported injected drivers are explicit rather than silently detached. */ export declare function withDatabaseMaintenanceLifetime(db: Database, lifetime: { signal: AbortSignal; deadlineAtMs?: number; }, run: (scoped: Database) => Promise): Promise; /** * Cancel the server-side statements of `run` when `signal` aborts, for * example when the HTTP client that asked for a read has gone away. Each * statement on a transaction connection that is still executing gets a * protocol cancel, so PostgreSQL stops working for nobody and the transaction * rolls back. Queries outside a transaction are not cancelled. A surrounding * cancellation scope still applies: either signal cancels. * * Use it for reads, or for writes that may safely roll back when the caller * leaves. Injected drivers without joined cancellation run `run` unchanged. */ export declare function withDatabaseQueryCancellation(db: Database, signal: AbortSignal | undefined, run: () => Promise): Promise; /** * Register a host's `rlsStrategy`/`userLookup` against an externally-constructed * `Database` handle (e.g. one the embedded host built from its own driver and * injected, rather than via `createDb`). Lets the same WeakMap-backed lookups * work for injected handles. Standalone never calls this (it uses `createDb`). */ export declare function registerDbBinding(db: Database, binding: { rlsStrategy?: RlsStrategy; userLookup?: UserLookup; userProfileLookup?: UserProfileLookup; }): void; export declare function setRlsContext(db: Database, context: RlsContext): Promise; /** An advisory transaction lock taken while a scope is established. `key` is * either a literal key or a prefix completed with the scope's account id. */ export type RlsScopeLock = { key: string | { accountPrefix: string; }; mode: "shared" | "exclusive"; hash: "extended" | "text"; }; export type RlsScopeInput = { /** The tenant account, or null to resolve it from `workspaceId` within the * same statement. */ accountId: string | null; workspaceId: string | null; /** Authenticated subject for actor-private rows; overrides the ambient * session actor's subject. */ subjectId?: string; /** Locks taken in this order, after the context is set. */ locks: readonly RlsScopeLock[]; /** Return the enclosing scope's settings so a nested scope can restore them. */ readParent: boolean; }; /** Every value an RLS scope statement binds; the rest of its text is its shape. */ export type RlsScopeValues = { accountId: string | null; workspaceId: string | null; settingsWorkspaceId: string; agentRootSessionId: string; siteId: string; siteViewerPrincipal: string; /** Defined exactly when the subject GUC is set. */ subjectId: string | undefined; /** Defined exactly when a session actor is in scope. */ privateFileOwner: string | undefined; initiatingHumanSubjectId: string | undefined; /** Each lock's literal key or account prefix, in lock order. */ lockKeys: string[]; }; type RlsScopeSlots = { [K in Exclude]: unknown; } & { lockKeys: unknown[]; }; /** @internal The reference builder; exported for statement equivalence tests. */ export declare function buildRlsScopeStatement(input: RlsScopeInput, values: RlsScopeSlots): SQL; /** @internal The statement `applyRlsScope` runs; exported for equivalence tests. */ export declare function rlsScopeStatement(db: Database, input: RlsScopeInput, values: RlsScopeValues): SQL; export declare function withRlsContext(db: Database, context: RlsContext, fn: (db: Database) => Promise, transactionConfig?: PgTransactionConfig, sessionTenancyFence?: "shared" | "none"): Promise; /** * Run one bounded database operation on a transaction-pinned backend. * * Callers that also have an application deadline should check their abort * signal before returning from `fn`; throwing there rolls the transaction back * even when the application deadline won a surrounding Promise race. */ export declare function withDatabaseStatementTimeout(db: Database, timeoutMs: number, fn: (db: Database) => Promise): Promise; export declare function rlsContextForWorkspace(db: Database, workspaceId: string): Promise; export declare function withWorkspaceRls(db: Database, workspaceId: string, fn: (db: Database) => Promise, transactionConfig?: PgTransactionConfig): Promise; /** True for an open transaction (or savepoint) handle rather than a pool handle. */ export declare function isTransactionHandle(db: Database): boolean; /** Session activity is stamped by the row trigger; retain the scoped writer API. */ export declare function withSessionActivityRlsContext(db: Database, context: RlsContext & { workspaceId: string; }, fn: (db: SessionActivityDatabase) => Promise, transactionConfig?: PgTransactionConfig, fenceMode?: "shared" | "none", organizationMembershipFence?: boolean): Promise; /** * `organizationMembershipFence` is required when the callback takes the * organization-membership lifecycle lock (for example external-actor * reauthorization): that lock precedes the session-tenancy fence and the * canonical control/workspace/session prefix, never follows it. */ export declare function withWorkspaceSessionActivityRls(db: Database, workspaceId: string, fn: (db: SessionActivityDatabase) => Promise, transactionConfig?: PgTransactionConfig, organizationMembershipFence?: boolean): Promise; /** * Run one of several ordered workspace activity scopes inside a caller-owned * transaction. Tenant and actor settings are restored before the next scope. */ export declare function withRestoredSessionActivityRlsContext(db: Database, context: RlsContext & { workspaceId: string; }, fn: (db: SessionActivityDatabase) => Promise): Promise; /** * Open one nested savepoint without losing the scoped writer brand. */ export declare function withSessionActivitySavepoint(db: SessionActivityDatabase, fn: (db: SessionActivityDatabase) => Promise): Promise; export declare function retrySessionActivityRls(db: Database, workspaceId: string, options: IdempotentPersistenceTransactionOptions, fn: (db: SessionActivityDatabase) => Promise): Promise; export declare function retryWorkspacePersistence(db: Database, workspaceId: string, options: IdempotentPersistenceTransactionOptions, fn: (db: Database) => Promise): Promise; export declare function retryRlsPersistence(db: Database, context: RlsContext, options: IdempotentPersistenceTransactionOptions, fn: (db: Database) => Promise): Promise; /** * Personal workspace data needs both tenant and authenticated-principal GUCs. * `session_pins` uses this helper so FORCE RLS rejects another member's rows * even if a future query accidentally omits its explicit subject predicate. */ export declare function withWorkspaceSubjectRls(db: Database, workspaceId: string, subjectId: string, fn: (db: Database) => Promise, transactionConfig?: PgTransactionConfig, sessionTenancyFence?: "shared" | "none"): Promise; export declare function withWorkspaceSubjectSessionActivityRls(db: Database, workspaceId: string, subjectId: string, fn: (db: SessionActivityDatabase) => Promise, transactionConfig?: PgTransactionConfig, fenceMode?: "shared" | "none", organizationMembershipFence?: boolean): Promise; /** Apply and verify actor-private RLS on an already transaction-pinned handle, * in one statement that sets the subject and reads it back. */ export declare function setSubjectRlsContext(db: Database, subjectId: string): Promise; export declare function withWorkspaceUsageLock(db: Database, workspaceId: string, fn: (db: Database) => Promise): Promise; export declare function withAccountRls(db: Database, accountId: string, fn: (db: Database) => Promise): Promise; /** Internal lookup for the host binding attached to a database handle. */ export declare function dbBindingFor(db: Database): DbBinding | undefined; export {};