@opengeni/db 0.27.8 → 0.27.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/{chunk-M6EOXYHK.js → chunk-JYQPJ6Y5.js} +59 -50
  2. package/dist/chunk-JYQPJ6Y5.js.map +1 -0
  3. package/dist/{chunk-IHPCI4GV.js → chunk-RPHPNVWW.js} +3 -1
  4. package/dist/chunk-RPHPNVWW.js.map +1 -0
  5. package/dist/codex-token-resolver.d.ts +50 -8
  6. package/dist/connection-token-resolver.d.ts +45 -7
  7. package/dist/database.d.ts +137 -0
  8. package/dist/index.d.ts +83 -184
  9. package/dist/index.js +2983 -2691
  10. package/dist/index.js.map +1 -1
  11. package/dist/insights.d.ts +1 -1
  12. package/dist/memory-governance.d.ts +1 -1
  13. package/dist/new-session-drafts.d.ts +1 -1
  14. package/dist/preference-registry.d.ts +1 -1
  15. package/dist/provision-roles.d.ts +1 -1
  16. package/dist/provision-roles.js +1 -1
  17. package/dist/runtime-posture.d.ts +3 -3
  18. package/dist/schema.d.ts +155 -96
  19. package/dist/schema.js +3 -1
  20. package/dist/scoped-knowledge.d.ts +1 -1
  21. package/dist/session-control.d.ts +1 -1
  22. package/dist/session-queue-commands.d.ts +1 -1
  23. package/dist/session-realtime-context.d.ts +1 -1
  24. package/dist/session-realtime-ledger.d.ts +1 -1
  25. package/dist/session-realtime-mirror.d.ts +1 -1
  26. package/dist/session-realtime-state.d.ts +1 -1
  27. package/dist/session-realtime-terminal.d.ts +1 -1
  28. package/dist/session-realtime.d.ts +1 -1
  29. package/dist/session-tool-call-settlement.d.ts +1 -1
  30. package/dist/turn-initiator.d.ts +1 -1
  31. package/dist/workspace-artifacts.d.ts +1 -1
  32. package/dist/workspace-instruction-policies.d.ts +1 -1
  33. package/drizzle/0171_social_connection_subject_ownership.sql +53 -0
  34. package/drizzle/0172_retire_model_visible_github_token.sql +86 -0
  35. package/drizzle/0173_codex_auth_boundaries.sql +107 -0
  36. package/drizzle/0174_session_wake_live_interruption.sql +80 -0
  37. package/package.json +4 -4
  38. package/src/codex-token-resolver.ts +102 -49
  39. package/src/connection-token-resolver.ts +67 -26
  40. package/src/database.ts +393 -0
  41. package/src/index.ts +747 -645
  42. package/src/insights.ts +2 -2
  43. package/src/memory-governance.ts +2 -2
  44. package/src/new-session-drafts.ts +1 -1
  45. package/src/preference-registry.ts +2 -2
  46. package/src/provision-roles.ts +1 -1
  47. package/src/runtime-posture.ts +3 -1
  48. package/src/schema.ts +70 -50
  49. package/src/scoped-knowledge.ts +2 -2
  50. package/src/session-control.ts +1 -1
  51. package/src/session-queue-commands.ts +1 -1
  52. package/src/session-realtime-context.ts +1 -1
  53. package/src/session-realtime-ledger.ts +1 -1
  54. package/src/session-realtime-mirror.ts +1 -1
  55. package/src/session-realtime-state.ts +1 -1
  56. package/src/session-realtime-terminal.ts +1 -1
  57. package/src/session-realtime.ts +1 -1
  58. package/src/session-tool-call-settlement.ts +1 -1
  59. package/src/turn-initiator.ts +1 -1
  60. package/src/workspace-artifacts.ts +2 -2
  61. package/src/workspace-instruction-policies.ts +2 -2
  62. package/dist/chunk-IHPCI4GV.js.map +0 -1
  63. package/dist/chunk-M6EOXYHK.js.map +0 -1
@@ -96,6 +96,7 @@ var FORCE_RLS_TABLES = [
96
96
  "billing_customers",
97
97
  "capability_catalog_items",
98
98
  "capability_installations",
99
+ "codex_apps_settings",
99
100
  "codex_capacity_waiters",
100
101
  "codex_credential_leases",
101
102
  "codex_reset_redemption_attempts",
@@ -238,6 +239,7 @@ var RUNTIME_FULL_DML_TABLES = [
238
239
  "billing_customers",
239
240
  "capability_catalog_items",
240
241
  "capability_installations",
242
+ "codex_apps_settings",
241
243
  "codex_capacity_waiters",
242
244
  "codex_credential_leases",
243
245
  "codex_reset_redemption_attempts",
@@ -1200,4 +1202,4 @@ export {
1200
1202
  runtimeDatabaseReadyCheck,
1201
1203
  provisionRoles
1202
1204
  };
1203
- //# sourceMappingURL=chunk-IHPCI4GV.js.map
1205
+ //# sourceMappingURL=chunk-RPHPNVWW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/provision-roles.ts","../src/runtime-posture.ts","../src/role-relationships.ts"],"sourcesContent":["import postgres from \"postgres\";\nimport type { RlsStrategy } from \"./database\";\nimport {\n RUNTIME_FULL_DML_TABLES,\n RUNTIME_READ_INSERT_TABLES,\n RUNTIME_READ_ONLY_TABLES,\n} from \"./runtime-posture\";\nimport {\n classifyRoleRelationships,\n roleRelationshipsCatalogQuery,\n type RoleRelationshipCatalogRow,\n} from \"./role-relationships\";\n\nexport type ProvisionResult = {\n appRole: string | null;\n hostExportRole: string | null;\n temporalRole: string | null;\n temporalDatabases: string[];\n schema: string;\n rlsStrategy: RlsStrategy;\n};\n\nexport type ProvisionRolesOptions = {\n /**\n * The schema OpenGeni's tables live in. The app-role GRANTs target this\n * schema + `opengeni_private`. Defaults to `public` (standalone).\n */\n targetSchema?: string;\n /**\n * RLS posture (Step I). `\"force\"` (default) provisions the non-owner\n * `opengeni_app` login role and GRANTs it table DML in the target schema —\n * the role OpenGeni connects as under FORCE-RLS. `\"scoped\"` SKIPS the app-role\n * provisioning entirely: the embedded host runs OpenGeni's queries over a role\n * IT owns/manages (typically the schema owner), so OpenGeni neither creates\n * nor grants the `opengeni_app` role. Temporal-role provisioning is unaffected\n * by strategy.\n */\n rlsStrategy?: RlsStrategy;\n appRole?: string;\n appPassword?: string;\n /**\n * Optional cross-workspace projection role. It receives schema USAGE and\n * EXECUTE only on the host-export API; it receives no table privileges.\n * Provision it after the first migration run so the schema exists. The\n * provisioner also registers same-owner default privileges for future\n * host-export functions; shipped migrations preserve existing exporter ACLs\n * when a migration-only upgrade adds a function.\n */\n hostExportRole?: string;\n hostExportPassword?: string;\n temporalRole?: string;\n temporalPassword?: string;\n temporalDatabases?: string[];\n};\n\n/**\n * SDK entry point (Step I): provision the OpenGeni database roles + grants over\n * a host-supplied admin connection. This is the named, parameterized form of the\n * historical env-driven `provision-roles` script (which still works as a CLI via\n * the `import.meta.main` block at the bottom — it just reads env into these\n * options).\n *\n * STANDALONE (default): `provisionRoles(adminConnection)` with no options →\n * `targetSchema: \"public\"`, `rlsStrategy: \"force\"`, reads `opengeni_app` creds\n * from env. Byte-for-byte the historical script behavior.\n *\n * EMBEDDED: `provisionRoles(adminConnection, { targetSchema, rlsStrategy })` lets\n * a host provision the app role over a dedicated schema (force) OR skip the\n * app role entirely and own the connection role itself (scoped).\n */\nexport async function provisionRoles(\n adminConnection: string,\n options: ProvisionRolesOptions = {},\n): Promise<ProvisionResult> {\n const schema = validateIdentifier(\"targetSchema\", options.targetSchema ?? \"public\");\n const rlsStrategy: RlsStrategy = options.rlsStrategy ?? \"force\";\n\n const appRole = validateIdentifier(\n \"appRole\",\n options.appRole ?? (process.env.OPENGENI_APP_DATABASE_USER?.trim() || \"opengeni_app\"),\n );\n const appPassword = options.appPassword ?? process.env.OPENGENI_APP_DATABASE_PASSWORD;\n const hostExportRole = validateIdentifier(\n \"hostExportRole\",\n options.hostExportRole ??\n (process.env.OPENGENI_HOST_EXPORT_DATABASE_USER?.trim() || \"opengeni_host_exporter\"),\n );\n const hostExportPassword =\n options.hostExportPassword ?? process.env.OPENGENI_HOST_EXPORT_DATABASE_PASSWORD;\n const temporalRole = validateIdentifier(\n \"temporalRole\",\n options.temporalRole ??\n (process.env.OPENGENI_TEMPORAL_DATABASE_USER?.trim() || \"opengeni_temporal\"),\n );\n const temporalPassword =\n options.temporalPassword ?? process.env.OPENGENI_TEMPORAL_DATABASE_PASSWORD;\n const temporalDatabases = (\n options.temporalDatabases ??\n commaSeparated(process.env.OPENGENI_TEMPORAL_DATABASES ?? \"temporal,temporal_visibility\")\n ).map((name) => validateIdentifier(\"temporalDatabases\", name));\n\n const sql = postgres(adminConnection, { max: 1 });\n try {\n // FORCE strategy provisions the non-owner app role OpenGeni connects as.\n // SCOPED strategy: the host owns the connection role; OpenGeni provisions no\n // app role (skipped here), only the optional Temporal role.\n let provisionedAppRole: string | null = null;\n if (rlsStrategy === \"force\") {\n if (!appPassword) {\n throw new Error(\n \"OPENGENI_APP_DATABASE_PASSWORD (or appPassword) is required for rlsStrategy 'force'\",\n );\n }\n // Ownership and privilege-bearing role-graph edges cannot be safely\n // guessed away. Refuse to mutate an existing role until an operator has\n // explicitly transferred objects/removed those memberships; role\n // attributes and direct grants, however, are deterministic and are\n // converged below on every run. PostgreSQL 16+'s exact non-runtime-bearing\n // creator-management edge is classified separately.\n await assertAppRoleSafeToNormalize(sql, appRole);\n await ensureRestrictedAppLoginRole(sql, appRole, appPassword);\n provisionedAppRole = appRole;\n }\n\n if (temporalPassword) {\n await ensureLoginRole(sql, temporalRole, temporalPassword);\n for (const database of temporalDatabases) {\n await ensureDatabase(sql, database, temporalRole);\n await grantTemporalRoleInDatabase(adminConnection, database, temporalRole);\n }\n }\n\n if (hostExportPassword) {\n await ensureLoginRole(sql, hostExportRole, hostExportPassword);\n await grantHostExportRoleIfSchemaExists(sql, hostExportRole);\n }\n\n if (rlsStrategy === \"force\") {\n await grantAppRoleIfSchemaExists(sql, appRole, schema);\n }\n\n return {\n appRole: provisionedAppRole,\n hostExportRole: hostExportPassword ? hostExportRole : null,\n temporalRole: temporalPassword ? temporalRole : null,\n temporalDatabases: temporalPassword ? temporalDatabases : [],\n schema,\n rlsStrategy,\n };\n } finally {\n await sql.end();\n }\n}\n\n/**\n * The exporter is intentionally separate from `opengeni_app`: its functions\n * project every workspace into a host-owned sink and therefore cannot be made\n * available to the tenant-scoped application role.\n */\nasync function grantHostExportRoleIfSchemaExists(sql: postgres.Sql, role: string): Promise<void> {\n await sql.unsafe(`\nDO $$\nBEGIN\n IF EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = 'opengeni_host_export') THEN\n EXECUTE format('GRANT USAGE ON SCHEMA opengeni_host_export TO %I', ${literal(role)});\n EXECUTE format('GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA opengeni_host_export TO %I', ${literal(role)});\n EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA opengeni_host_export GRANT EXECUTE ON FUNCTIONS TO %I', ${literal(role)});\n END IF;\nEND $$;\n`);\n}\n\nasync function ensureLoginRole(sql: postgres.Sql, role: string, password: string): Promise<void> {\n await sql.unsafe(`\nDO $$\nBEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${literal(role)}) THEN\n EXECUTE format('CREATE ROLE %I LOGIN PASSWORD %L', ${literal(role)}, ${literal(password)});\n ELSE\n EXECUTE format('ALTER ROLE %I LOGIN PASSWORD %L', ${literal(role)}, ${literal(password)});\n END IF;\nEND $$;\n`);\n}\n\nasync function ensureRestrictedAppLoginRole(\n sql: postgres.Sql,\n role: string,\n password: string,\n): Promise<void> {\n await sql.unsafe(`\nDO $$\nBEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${literal(role)}) THEN\n EXECUTE format(\n 'CREATE ROLE %I WITH LOGIN NOSUPERUSER NOBYPASSRLS NOCREATEROLE NOCREATEDB NOREPLICATION NOINHERIT PASSWORD %L',\n ${literal(role)},\n ${literal(password)}\n );\n ELSIF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = current_user AND rolsuper) THEN\n EXECUTE format(\n 'ALTER ROLE %I WITH LOGIN NOSUPERUSER NOBYPASSRLS NOCREATEROLE NOCREATEDB NOREPLICATION NOINHERIT PASSWORD %L',\n ${literal(role)},\n ${literal(password)}\n );\n ELSE\n -- PostgreSQL requires elevated attributes merely to name SUPERUSER,\n -- BYPASSRLS, REPLICATION, or CREATEDB in ALTER ROLE, even when setting them\n -- false. The preflight has already proved those protected attributes are\n -- false, so a managed CREATEROLE administrator converges only the\n -- attributes it may change.\n EXECUTE format(\n 'ALTER ROLE %I WITH LOGIN NOCREATEROLE NOINHERIT PASSWORD %L',\n ${literal(role)},\n ${literal(password)}\n );\n END IF;\nEND $$;\n`);\n}\n\n/**\n * Fail rather than silently revoking role relationships or transferring owned\n * objects. Those operations have effects outside OpenGeni's runtime grant\n * contract and require an explicit, audited operator decision.\n */\nasync function assertAppRoleSafeToNormalize(sql: postgres.Sql, role: string): Promise<void> {\n const exists = await sql<{ exists: boolean }[]>`\n select exists(select 1 from pg_roles where rolname = ${role}) as exists\n `;\n if (!exists[0]?.exists) {\n return;\n }\n\n const [roleAttributes] = await sql<\n {\n administrator_superuser: boolean;\n app_superuser: boolean;\n app_bypass_rls: boolean;\n app_create_database: boolean;\n app_replication: boolean;\n }[]\n >`\n select\n administrator.rolsuper as administrator_superuser,\n app.rolsuper as app_superuser,\n app.rolbypassrls as app_bypass_rls,\n app.rolcreatedb as app_create_database,\n app.rolreplication as app_replication\n from pg_roles app\n join pg_roles administrator on administrator.rolname = current_user\n where app.rolname = ${role}\n `;\n if (roleAttributes && !roleAttributes.administrator_superuser) {\n const protectedAttributes = [\n roleAttributes.app_superuser ? \"SUPERUSER\" : null,\n roleAttributes.app_bypass_rls ? \"BYPASSRLS\" : null,\n roleAttributes.app_create_database ? \"CREATEDB\" : null,\n roleAttributes.app_replication ? \"REPLICATION\" : null,\n ].filter((attribute): attribute is string => attribute !== null);\n if (protectedAttributes.length > 0) {\n throw new Error(\n `Refusing to normalize app role ${role}: a non-superuser administrator cannot clear protected attributes (${protectedAttributes.join(\", \")})`,\n );\n }\n }\n\n const relationshipRows = await sql.unsafe<RoleRelationshipCatalogRow[]>(\n roleRelationshipsCatalogQuery(\"$1\"),\n [role],\n );\n const { unsafeRelationships } = classifyRoleRelationships(relationshipRows);\n if (unsafeRelationships.length > 0) {\n throw new Error(\n `Refusing to normalize app role ${role}: remove privilege-bearing role relationships first (${unsafeRelationships.join(\", \")})`,\n );\n }\n\n const ownedObjects = await sql<{ object_name: string }[]>`\n select ('database:' || d.datname)::text as object_name\n from pg_database d\n join pg_roles owner on owner.oid = d.datdba\n where owner.rolname = ${role}\n union all\n select ('schema:' || n.nspname)::text as object_name\n from pg_namespace n\n join pg_roles owner on owner.oid = n.nspowner\n where owner.rolname = ${role}\n and n.nspname <> 'information_schema'\n and n.nspname !~ '^pg_'\n union all\n select ('relation:' || n.nspname || '.' || c.relname)::text as object_name\n from pg_class c\n join pg_namespace n on n.oid = c.relnamespace\n join pg_roles owner on owner.oid = c.relowner\n where owner.rolname = ${role}\n and n.nspname <> 'information_schema'\n and n.nspname !~ '^pg_'\n union all\n select (\n 'routine:' || n.nspname || '.' || p.proname || '(' ||\n pg_get_function_identity_arguments(p.oid) || ')'\n )::text as object_name\n from pg_proc p\n join pg_namespace n on n.oid = p.pronamespace\n join pg_roles owner on owner.oid = p.proowner\n where owner.rolname = ${role}\n and n.nspname <> 'information_schema'\n and n.nspname !~ '^pg_'\n order by object_name\n `;\n if (ownedObjects.length > 0) {\n throw new Error(\n `Refusing to normalize app role ${role}: transfer owned objects first (${ownedObjects\n .map((row) => row.object_name)\n .join(\", \")})`,\n );\n }\n}\n\nasync function ensureDatabase(sql: postgres.Sql, database: string, owner: string): Promise<void> {\n const existing = await sql<{ exists: boolean }[]>`\n select exists(select 1 from pg_database where datname = ${database}) as exists\n `;\n if (!existing[0]?.exists) {\n await sql.unsafe(`CREATE DATABASE ${identifier(database)} OWNER ${identifier(owner)}`);\n }\n await sql.unsafe(\n `GRANT ALL PRIVILEGES ON DATABASE ${identifier(database)} TO ${identifier(owner)}`,\n );\n}\n\nasync function grantTemporalRoleInDatabase(\n adminConnection: string,\n database: string,\n role: string,\n): Promise<void> {\n const databaseUrl = databaseUrlFor(adminConnection, database);\n const databaseSql = postgres(databaseUrl, { max: 1 });\n try {\n await databaseSql.unsafe(`GRANT USAGE, CREATE ON SCHEMA public TO ${identifier(role)}`);\n } finally {\n await databaseSql.end();\n }\n}\n\n/**\n * Grant the app role table DML in the OpenGeni data schema + EXECUTE on the\n * `opengeni_private` helper functions. Schema-parameterized (Step I): standalone\n * passes `public`; embedded passes the dedicated schema. The grants are guarded\n * on schema existence so provisioning before migrate is a safe no-op.\n */\nasync function grantAppRoleIfSchemaExists(\n sql: postgres.Sql,\n role: string,\n schema: string,\n): Promise<void> {\n const runtimeFullDmlTables = `ARRAY[${RUNTIME_FULL_DML_TABLES.map(literal).join(\", \")}]`;\n const runtimeReadOnlyTables = `ARRAY[${RUNTIME_READ_ONLY_TABLES.map(literal).join(\", \")}]`;\n const runtimeReadInsertTables = `ARRAY[${RUNTIME_READ_INSERT_TABLES.map(literal).join(\", \")}]`;\n await sql.unsafe(`\nDO $$\nDECLARE\n owner_role text := current_user;\n runtime_table text;\nBEGIN\n EXECUTE format('REVOKE CREATE ON DATABASE %I FROM %I', current_database(), ${literal(role)});\n IF EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = ${literal(schema)}) THEN\n EXECUTE format('GRANT USAGE ON SCHEMA %I TO %I', ${literal(schema)}, ${literal(role)});\n EXECUTE format('REVOKE CREATE ON SCHEMA %I FROM %I', ${literal(schema)}, ${literal(role)});\n EXECUTE format('REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA %I FROM %I', ${literal(schema)}, ${literal(role)});\n FOREACH runtime_table IN ARRAY ${runtimeFullDmlTables} LOOP\n IF to_regclass(format('%I.%I', ${literal(schema)}, runtime_table)) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE %I.%I TO %I',\n ${literal(schema)},\n runtime_table,\n ${literal(role)}\n );\n END IF;\n END LOOP;\n FOREACH runtime_table IN ARRAY ${runtimeReadOnlyTables} LOOP\n IF to_regclass(format('%I.%I', ${literal(schema)}, runtime_table)) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT SELECT ON TABLE %I.%I TO %I',\n ${literal(schema)},\n runtime_table,\n ${literal(role)}\n );\n END IF;\n END LOOP;\n FOREACH runtime_table IN ARRAY ${runtimeReadInsertTables} LOOP\n IF to_regclass(format('%I.%I', ${literal(schema)}, runtime_table)) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT SELECT, INSERT ON TABLE %I.%I TO %I',\n ${literal(schema)},\n runtime_table,\n ${literal(role)}\n );\n END IF;\n END LOOP;\n -- Migration 0110 creates this target-schema-local SECURITY DEFINER\n -- capability before opengeni_app may exist. Re-converge its exact EXECUTE\n -- grant here so the supported migrate-then-provision order is equivalent to\n -- provisioning the role before that migration.\n IF to_regprocedure(\n format('%I.lock_nested_agent_depth_configuration()', ${literal(schema)})\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.lock_nested_agent_depth_configuration() TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF to_regprocedure(\n format(\n '%I.preference_registry_apply_lifecycle(text,uuid,integer,uuid,uuid,text,uuid,text,text)',\n ${literal(schema)}\n )\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.preference_registry_apply_lifecycle(text, uuid, integer, uuid, uuid, text, uuid, text, text) TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF to_regprocedure(\n format('%I.preference_registry_lock_heads(uuid[])', ${literal(schema)})\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.preference_registry_lock_heads(uuid[]) TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF to_regprocedure(\n format(\n '%I.knowledge_memory_apply_operation(jsonb,text,text,text,uuid,uuid,uuid,integer)',\n ${literal(schema)}\n )\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.knowledge_memory_apply_operation(jsonb, text, text, text, uuid, uuid, uuid, integer) TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF to_regprocedure(\n format(\n '%I.knowledge_memory_revert_operation(uuid,uuid,text,text,text,uuid,uuid,uuid,integer)',\n ${literal(schema)}\n )\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.knowledge_memory_revert_operation(uuid, uuid, text, text, text, uuid, uuid, uuid, integer) TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF to_regprocedure(\n format(\n '%I.preference_registry_get_or_create_snapshot(uuid,uuid,uuid,uuid,uuid,integer)',\n ${literal(schema)}\n )\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.preference_registry_get_or_create_snapshot(uuid, uuid, uuid, uuid, uuid, integer) TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF to_regprocedure(\n format(\n '%I.workspace_instruction_policy_get_or_create_snapshot(uuid,uuid,uuid,uuid,uuid,integer)',\n ${literal(schema)}\n )\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.workspace_instruction_policy_get_or_create_snapshot(uuid, uuid, uuid, uuid, uuid, integer) TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF to_regprocedure(\n format(\n '%I.scoped_knowledge_apply_lifecycle(uuid,text,uuid,text,bigint,text,text,text,text,text,text)',\n ${literal(schema)}\n )\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.scoped_knowledge_apply_lifecycle(uuid, text, uuid, text, bigint, text, text, text, text, text, text) TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF to_regprocedure(\n format(\n '%I.scoped_knowledge_advance_source_acl(uuid,uuid,bigint,bigint,uuid,text,text,text,text,text,text)',\n ${literal(schema)}\n )\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.scoped_knowledge_advance_source_acl(uuid, uuid, bigint, bigint, uuid, text, text, text, text, text, text) TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF to_regprocedure(\n format(\n '%I.scoped_knowledge_complete_sync(uuid,uuid,text,text,timestamptz,jsonb,text,text,text)',\n ${literal(schema)}\n )\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.scoped_knowledge_complete_sync(uuid, uuid, text, text, timestamptz, jsonb, text, text, text) TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF to_regprocedure(\n format(\n '%I.scoped_knowledge_advance_object_version(uuid,uuid,bigint,bigint,uuid,text,text,text,text,text,text)',\n ${literal(schema)}\n )\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.scoped_knowledge_advance_object_version(uuid, uuid, bigint, bigint, uuid, text, text, text, text, text, text) TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n EXECUTE format('GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA %I TO %I', ${literal(schema)}, ${literal(role)});\n EXECUTE format(\n 'ALTER DEFAULT PRIVILEGES FOR ROLE %I IN SCHEMA %I REVOKE ALL PRIVILEGES ON TABLES FROM %I',\n owner_role,\n ${literal(schema)},\n ${literal(role)}\n );\n EXECUTE format(\n 'ALTER DEFAULT PRIVILEGES FOR ROLE %I IN SCHEMA %I GRANT USAGE, SELECT ON SEQUENCES TO %I',\n owner_role,\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = 'opengeni_private') THEN\n EXECUTE format('GRANT USAGE ON SCHEMA opengeni_private TO %I', ${literal(role)});\n EXECUTE format('REVOKE CREATE ON SCHEMA opengeni_private FROM %I', ${literal(role)});\n EXECUTE format('GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA opengeni_private TO %I', ${literal(role)});\n EXECUTE format(\n 'ALTER DEFAULT PRIVILEGES FOR ROLE %I IN SCHEMA opengeni_private GRANT EXECUTE ON FUNCTIONS TO %I',\n owner_role,\n ${literal(role)}\n );\n END IF;\nEND $$;\n`);\n}\n\nfunction commaSeparated(value: string): string[] {\n return value\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean);\n}\n\nfunction validateIdentifier(name: string, value: string): string {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) {\n throw new Error(`${name} contains an invalid Postgres identifier: ${value}`);\n }\n return value;\n}\n\nfunction identifier(value: string): string {\n return `\"${value.replace(/\"/g, '\"\"')}\"`;\n}\n\nfunction literal(value: string): string {\n return `'${value.replace(/'/g, \"''\")}'`;\n}\n\nfunction databaseUrlFor(value: string, database: string): string {\n const url = new URL(value);\n url.pathname = `/${database}`;\n return url.toString();\n}\n\n// CLI form (unchanged behavior): read env into the SDK options and run. This is\n// what `bun src/provision-roles.ts` / the `provision-roles` package script\n// invokes — standalone byte-for-byte the historical script (public schema,\n// force strategy, env-driven creds).\nif (import.meta.main) {\n const adminUrl =\n process.env.OPENGENI_MIGRATIONS_DATABASE_URL ??\n process.env.OPENGENI_DATABASE_ADMIN_URL ??\n process.env.OPENGENI_DATABASE_URL;\n if (!adminUrl) {\n throw new Error(\n \"OPENGENI_MIGRATIONS_DATABASE_URL, OPENGENI_DATABASE_ADMIN_URL, or OPENGENI_DATABASE_URL is required\",\n );\n }\n const result = await provisionRoles(adminUrl, {\n ...(process.env.OPENGENI_DB_SCHEMA?.trim()\n ? { targetSchema: process.env.OPENGENI_DB_SCHEMA.trim() }\n : {}),\n });\n console.log(JSON.stringify(result, null, 2));\n}\n","import { sql } from \"drizzle-orm\";\nimport type { Database, RlsStrategy } from \"./database\";\nimport {\n classifyRoleRelationships,\n roleRelationshipsCatalogQuery,\n type RoleRelationshipCatalogRow,\n} from \"./role-relationships\";\n\n/**\n * The complete standalone tenant-table contract. Adding or removing a\n * FORCE-RLS table is an architectural change: update this list in the same\n * commit as the migration so startup cannot silently accept an unreviewed gap.\n */\nexport const FORCE_RLS_TABLES = [\n \"agent_run_states\",\n \"api_keys\",\n \"audit_events\",\n \"billing_customers\",\n \"capability_catalog_items\",\n \"capability_installations\",\n \"codex_apps_settings\",\n \"codex_capacity_waiters\",\n \"codex_credential_leases\",\n \"codex_reset_redemption_attempts\",\n \"codex_rotation_settings\",\n \"codex_subscription_credentials\",\n \"composer_drafts\",\n \"connection_disconnect_operations\",\n \"connections\",\n \"connector_action_policies\",\n \"connector_action_requests\",\n \"credit_ledger_entries\",\n \"device_enrollment_requests\",\n \"document_bases\",\n \"document_chunks\",\n \"documents\",\n \"enrollments\",\n \"file_uploads\",\n \"files\",\n \"github_installation_repositories\",\n \"github_installations\",\n \"host_export_config\",\n \"host_export_consumers\",\n \"host_export_cursor_state\",\n \"host_export_dead_letters\",\n \"host_export_outbox\",\n \"import_batches\",\n \"integration_oauth_state_nonces\",\n \"knowledge_change_proposals\",\n \"knowledge_claim_evidence\",\n \"knowledge_claim_relations\",\n \"knowledge_claim_reviews\",\n \"knowledge_claims\",\n \"knowledge_document_versions\",\n \"knowledge_entities\",\n \"knowledge_entity_aliases\",\n \"knowledge_facts\",\n \"knowledge_lifecycle_events\",\n \"knowledge_memories\",\n \"knowledge_memory_lifecycle_events\",\n \"knowledge_memory_relationships\",\n \"knowledge_operation_receipts\",\n \"knowledge_providers\",\n \"knowledge_source_acl_versions\",\n \"knowledge_source_objects\",\n \"knowledge_sources\",\n \"knowledge_sync_runs\",\n \"machine_metrics_latest\",\n \"machine_metrics_series\",\n \"model_call_facts\",\n \"new_session_drafts\",\n \"pack_installations\",\n \"preference_registry_events\",\n \"preference_registry_preferences\",\n \"preference_registry_revisions\",\n \"preference_registry_snapshots\",\n \"rig_changes\",\n \"rig_versions\",\n \"rigs\",\n \"sandbox_checkpoint_artifacts\",\n \"sandbox_lease_holders\",\n \"sandbox_leases\",\n \"sandbox_pty_sessions\",\n \"sandbox_retained_processes\",\n \"sandbox_session_envelopes\",\n \"sandbox_workspace_mutation_admissions\",\n \"sandboxes\",\n \"scheduled_task_runs\",\n \"scheduled_tasks\",\n \"session_attempt_interruptions\",\n \"session_command_receipts\",\n \"session_events\",\n \"session_goals\",\n \"session_history_items\",\n \"session_human_input_requests\",\n \"session_list_snapshots\",\n \"session_mcp_servers\",\n \"session_pending_tool_calls\",\n \"session_pins\",\n \"session_realtime_connections\",\n \"session_realtime_context_projections\",\n \"session_realtime_entries\",\n \"session_realtime_modes\",\n \"session_recordings\",\n \"session_spawn_denials\",\n \"session_stream_acknowledgments\",\n \"session_system_update_outbox\",\n \"session_system_updates\",\n \"session_turn_attempts\",\n \"session_turns\",\n \"session_workflow_wake_outbox\",\n \"sessions\",\n \"slack_bot_delete_operations\",\n \"slack_bot_post_operations\",\n \"slack_bot_user_links\",\n \"slack_interaction_inbox\",\n \"slack_interaction_progress_deliveries\",\n \"slack_interactions\",\n \"social_connections\",\n \"social_posts\",\n \"usage_events\",\n \"workspace_artifact_events\",\n \"workspace_artifact_versions\",\n \"workspace_artifacts\",\n \"workspace_captures\",\n \"workspace_control_events\",\n \"workspace_inference_controls\",\n \"workspace_instruction_policy_activation_events\",\n \"workspace_instruction_policy_heads\",\n \"workspace_instruction_policy_onboarding_proposals\",\n \"workspace_instruction_policy_revisions\",\n \"workspace_instruction_policy_snapshots\",\n \"workspace_model_policies\",\n \"workspace_packs\",\n \"workspace_session_activity_revisions\",\n \"workspace_variable_set_variables\",\n \"workspace_variable_sets\",\n] as const;\n\n/**\n * Deployment-global and authentication tables used by ordinary API/worker\n * traffic. They intentionally do not carry workspace RLS: their access model\n * is implemented by the authentication/access layer or by exact global keys.\n */\nexport const NON_RLS_RUNTIME_TABLES = [\n \"auth_identities\",\n \"auth_rate_limits\",\n \"auth_sessions\",\n \"auth_users\",\n \"auth_verifications\",\n \"integration_oauth_clients\",\n \"managed_accounts\",\n \"nested_agent_depth_configuration\",\n \"stripe_webhook_events\",\n \"workspace_memberships\",\n \"workspaces\",\n] as const;\n\n/**\n * Exact full-CRUD class for the standalone runtime role. This is deliberately\n * explicit instead of being derived from FORCE_RLS_TABLES: adding a protected\n * table must not silently grant it broader DML than its migration intended.\n */\nexport const RUNTIME_FULL_DML_TABLES = [\n \"agent_run_states\",\n \"api_keys\",\n \"audit_events\",\n \"auth_identities\",\n \"auth_rate_limits\",\n \"auth_sessions\",\n \"auth_users\",\n \"auth_verifications\",\n \"billing_customers\",\n \"capability_catalog_items\",\n \"capability_installations\",\n \"codex_apps_settings\",\n \"codex_capacity_waiters\",\n \"codex_credential_leases\",\n \"codex_reset_redemption_attempts\",\n \"codex_rotation_settings\",\n \"codex_subscription_credentials\",\n \"composer_drafts\",\n \"connection_disconnect_operations\",\n \"connections\",\n \"connector_action_policies\",\n \"connector_action_requests\",\n \"credit_ledger_entries\",\n \"device_enrollment_requests\",\n \"document_bases\",\n \"document_chunks\",\n \"documents\",\n \"enrollments\",\n \"file_uploads\",\n \"files\",\n \"github_installation_repositories\",\n \"github_installations\",\n \"import_batches\",\n \"integration_oauth_clients\",\n \"integration_oauth_state_nonces\",\n \"knowledge_memories\",\n \"machine_metrics_latest\",\n \"machine_metrics_series\",\n \"managed_accounts\",\n \"model_call_facts\",\n \"new_session_drafts\",\n \"pack_installations\",\n \"rig_changes\",\n \"rig_versions\",\n \"rigs\",\n \"sandbox_checkpoint_artifacts\",\n \"sandbox_lease_holders\",\n \"sandbox_leases\",\n \"sandbox_pty_sessions\",\n \"sandbox_retained_processes\",\n \"sandbox_session_envelopes\",\n \"sandbox_workspace_mutation_admissions\",\n \"sandboxes\",\n \"scheduled_task_runs\",\n \"scheduled_tasks\",\n \"session_attempt_interruptions\",\n \"session_command_receipts\",\n \"session_events\",\n \"session_goals\",\n \"session_history_items\",\n \"session_human_input_requests\",\n \"session_list_snapshots\",\n \"session_mcp_servers\",\n \"session_pending_tool_calls\",\n \"session_pins\",\n \"session_realtime_connections\",\n \"session_realtime_context_projections\",\n \"session_realtime_entries\",\n \"session_realtime_modes\",\n \"session_recordings\",\n \"session_stream_acknowledgments\",\n \"session_system_update_outbox\",\n \"session_system_updates\",\n \"session_turn_attempts\",\n \"session_turns\",\n \"session_workflow_wake_outbox\",\n \"sessions\",\n \"slack_bot_delete_operations\",\n \"slack_bot_post_operations\",\n \"slack_bot_user_links\",\n \"slack_interaction_inbox\",\n \"slack_interaction_progress_deliveries\",\n \"slack_interactions\",\n \"social_connections\",\n \"social_posts\",\n \"stripe_webhook_events\",\n \"usage_events\",\n \"workspace_artifacts\",\n \"workspace_captures\",\n \"workspace_control_events\",\n \"workspace_inference_controls\",\n \"workspace_instruction_policy_heads\",\n \"workspace_memberships\",\n \"workspace_model_policies\",\n \"workspace_packs\",\n \"workspace_session_activity_revisions\",\n \"workspace_variable_set_variables\",\n \"workspace_variable_sets\",\n \"workspaces\",\n] as const;\n\n/** Configuration and lifecycle-owned audit rows are read-only at runtime. */\nexport const RUNTIME_READ_ONLY_TABLES = [\n \"knowledge_lifecycle_events\",\n \"knowledge_memory_lifecycle_events\",\n \"knowledge_memory_relationships\",\n \"nested_agent_depth_configuration\",\n \"preference_registry_events\",\n \"preference_registry_snapshots\",\n \"workspace_instruction_policy_snapshots\",\n] as const;\n\n/** Append-only evidence/revision tables are insertable and queryable, never mutable. */\nexport const RUNTIME_READ_INSERT_TABLES = [\n \"knowledge_change_proposals\",\n \"knowledge_claim_evidence\",\n \"knowledge_claim_relations\",\n \"knowledge_claim_reviews\",\n \"knowledge_claims\",\n \"knowledge_document_versions\",\n \"knowledge_entities\",\n \"knowledge_entity_aliases\",\n \"knowledge_facts\",\n \"knowledge_operation_receipts\",\n \"knowledge_providers\",\n \"knowledge_source_acl_versions\",\n \"knowledge_source_objects\",\n \"knowledge_sources\",\n \"knowledge_sync_runs\",\n \"preference_registry_preferences\",\n \"preference_registry_revisions\",\n \"session_spawn_denials\",\n \"workspace_artifact_events\",\n \"workspace_artifact_versions\",\n \"workspace_instruction_policy_activation_events\",\n \"workspace_instruction_policy_onboarding_proposals\",\n \"workspace_instruction_policy_revisions\",\n] as const;\n\n/**\n * These FORCE-RLS tables are owned by security-definer host-export routines.\n * The ordinary application role must have no direct table privileges on them.\n */\nexport const PROTECTED_NO_DIRECT_DML_TABLES = [\n \"host_export_config\",\n \"host_export_consumers\",\n \"host_export_cursor_state\",\n \"host_export_dead_letters\",\n \"host_export_outbox\",\n] as const;\n\nexport type RuntimeTableDmlPrivilege = \"SELECT\" | \"INSERT\" | \"UPDATE\" | \"DELETE\";\nexport type RuntimeTablePrivilegeContract = Readonly<\n Record<string, readonly RuntimeTableDmlPrivilege[]>\n>;\n\nconst FULL_DML_PRIVILEGES = [\"SELECT\", \"INSERT\", \"UPDATE\", \"DELETE\"] as const;\n\n/** Exact per-table DML contract. Absence means no direct table privileges. */\nexport const RUNTIME_TABLE_PRIVILEGES: RuntimeTablePrivilegeContract = Object.freeze({\n ...Object.fromEntries(RUNTIME_FULL_DML_TABLES.map((table) => [table, FULL_DML_PRIVILEGES])),\n ...Object.fromEntries(RUNTIME_READ_ONLY_TABLES.map((table) => [table, [\"SELECT\"] as const])),\n ...Object.fromEntries(\n RUNTIME_READ_INSERT_TABLES.map((table) => [table, [\"SELECT\", \"INSERT\"] as const]),\n ),\n});\n\n/** All tables with any direct runtime DML; retained as the aggregate public contract. */\nexport const RUNTIME_DML_TABLES = Object.freeze(\n Object.keys(RUNTIME_TABLE_PRIVILEGES).sort((a, b) => a.localeCompare(b)),\n);\n\nexport type RuntimeDatabasePostureOptions = {\n rlsStrategy: RlsStrategy;\n expectedRole?: string;\n targetSchema?: string;\n protectedTables?: readonly string[];\n tablePrivileges?: RuntimeTablePrivilegeContract;\n protectedNoDirectDmlTables?: readonly string[];\n};\n\nexport type RuntimeDatabaseIdentity = {\n currentUser: string;\n sessionUser: string;\n databaseOwner: string;\n canConnectDatabase: boolean;\n canCreateInDatabase: boolean;\n rowSecurity: string;\n canLogin: boolean;\n superuser: boolean;\n inherit: boolean;\n createRole: boolean;\n createDatabase: boolean;\n replication: boolean;\n bypassRls: boolean;\n};\n\nexport type RuntimeSchemaPosture = {\n name: string;\n owner: string;\n usage: boolean;\n create: boolean;\n};\n\nexport type RuntimeTablePosture = {\n name: string;\n owner: string;\n rlsEnabled: boolean;\n rlsForced: boolean;\n rlsActive: boolean;\n policyCount: number;\n select: boolean;\n insert: boolean;\n update: boolean;\n delete: boolean;\n truncate: boolean;\n references: boolean;\n trigger: boolean;\n};\n\nexport type RuntimeRoutinePosture = {\n name: string;\n owner: string;\n execute: boolean;\n};\n\nexport type RuntimeDatabasePosture = {\n identity: RuntimeDatabaseIdentity;\n /** Privilege-bearing role relationships; exact PG16+ management-only grants are excluded. */\n memberships: string[];\n schemas: RuntimeSchemaPosture[];\n ownedSchemas: string[];\n ownedRelations: string[];\n tables: RuntimeTablePosture[];\n privateRoutines: RuntimeRoutinePosture[];\n};\n\nexport class RuntimeDatabasePostureError extends Error {\n readonly violations: readonly string[];\n\n constructor(violations: readonly string[]) {\n super(`Runtime database posture check failed: ${violations.join(\"; \")}`);\n this.name = \"RuntimeDatabasePostureError\";\n this.violations = violations;\n }\n}\n\ntype IdentityRow = {\n current_user: string;\n session_user: string;\n database_owner: string;\n can_connect_database: boolean;\n can_create_in_database: boolean;\n row_security: string;\n rolcanlogin: boolean;\n rolsuper: boolean;\n rolinherit: boolean;\n rolcreaterole: boolean;\n rolcreatedb: boolean;\n rolreplication: boolean;\n rolbypassrls: boolean;\n};\n\nfunction resultRows<T>(result: unknown): T[] {\n if (Array.isArray(result)) {\n return result as T[];\n }\n const rows = (result as { rows?: unknown } | null)?.rows;\n if (Array.isArray(rows)) {\n return rows as T[];\n }\n throw new Error(\"Runtime database posture query returned an unsupported result shape\");\n}\n\nfunction sorted(values: Iterable<string>): string[] {\n return [...values].sort((a, b) => a.localeCompare(b));\n}\n\nfunction difference(left: ReadonlySet<string>, right: ReadonlySet<string>): string[] {\n return sorted([...left].filter((value) => !right.has(value)));\n}\n\n/** Inspect only PostgreSQL catalogs and privilege functions; no tenant rows. */\nexport async function inspectRuntimeDatabasePosture(\n db: Database,\n options: RuntimeDatabasePostureOptions,\n): Promise<RuntimeDatabasePosture> {\n const targetSchema = options.targetSchema?.trim() || \"public\";\n\n return await db.transaction(\n async (tx) => {\n const identityRows = resultRows<IdentityRow>(\n await tx.execute(sql`\n select\n current_user::text as current_user,\n session_user::text as session_user,\n pg_get_userbyid(d.datdba)::text as database_owner,\n has_database_privilege(current_user, d.oid, 'CONNECT') as can_connect_database,\n has_database_privilege(current_user, d.oid, 'CREATE') as can_create_in_database,\n current_setting('row_security')::text as row_security,\n r.rolcanlogin,\n r.rolsuper,\n r.rolinherit,\n r.rolcreaterole,\n r.rolcreatedb,\n r.rolreplication,\n r.rolbypassrls\n from pg_roles r\n join pg_database d on d.datname = current_database()\n where r.rolname = current_user\n `),\n );\n const identity = identityRows[0];\n if (!identity) {\n throw new Error(\"Runtime database posture could not resolve the current PostgreSQL role\");\n }\n\n const mappedIdentity: RuntimeDatabaseIdentity = {\n currentUser: identity.current_user,\n sessionUser: identity.session_user,\n databaseOwner: identity.database_owner,\n canConnectDatabase: identity.can_connect_database,\n canCreateInDatabase: identity.can_create_in_database,\n rowSecurity: identity.row_security,\n canLogin: identity.rolcanlogin,\n superuser: identity.rolsuper,\n inherit: identity.rolinherit,\n createRole: identity.rolcreaterole,\n createDatabase: identity.rolcreatedb,\n replication: identity.rolreplication,\n bypassRls: identity.rolbypassrls,\n };\n\n // Scoped/embedded topology deliberately leaves ownership and isolation to\n // the host. Prove the connection identity is coherent, but do not impose\n // the standalone opengeni_app object/grant contract on the host's role.\n if (options.rlsStrategy === \"scoped\") {\n return {\n identity: mappedIdentity,\n memberships: [],\n schemas: [],\n ownedSchemas: [],\n ownedRelations: [],\n tables: [],\n privateRoutines: [],\n };\n }\n\n const relationshipRows = resultRows<RoleRelationshipCatalogRow>(\n await tx.execute(sql.raw(roleRelationshipsCatalogQuery(\"current_user\"))),\n );\n const memberships = classifyRoleRelationships(relationshipRows).unsafeRelationships;\n\n const schemas = resultRows<{\n name: string;\n owner: string;\n usage: boolean;\n create: boolean;\n }>(\n await tx.execute(sql`\n select\n n.nspname::text as name,\n pg_get_userbyid(n.nspowner)::text as owner,\n has_schema_privilege(current_user, n.oid, 'USAGE') as usage,\n has_schema_privilege(current_user, n.oid, 'CREATE') as create\n from pg_namespace n\n where n.nspname in (${targetSchema}, 'opengeni_private')\n order by n.nspname\n `),\n );\n\n const ownedSchemas = resultRows<{ name: string }>(\n await tx.execute(sql`\n select n.nspname::text as name\n from pg_namespace n\n join pg_roles r on r.oid = n.nspowner\n where r.rolname = current_user\n and n.nspname <> 'information_schema'\n and n.nspname !~ '^pg_'\n order by n.nspname\n `),\n ).map((row) => row.name);\n\n const ownedRelations = resultRows<{ name: string }>(\n await tx.execute(sql`\n select (n.nspname || '.' || c.relname)::text as name\n from pg_class c\n join pg_namespace n on n.oid = c.relnamespace\n join pg_roles r on r.oid = c.relowner\n where r.rolname = current_user\n and c.relkind in ('r', 'p', 'S', 'v', 'm', 'f')\n and n.nspname <> 'information_schema'\n and n.nspname !~ '^pg_'\n order by n.nspname, c.relname\n `),\n ).map((row) => row.name);\n\n const tables = resultRows<{\n name: string;\n owner: string;\n rls_enabled: boolean;\n rls_forced: boolean;\n rls_active: boolean;\n policy_count: number;\n can_select: boolean;\n can_insert: boolean;\n can_update: boolean;\n can_delete: boolean;\n can_truncate: boolean;\n can_references: boolean;\n can_trigger: boolean;\n }>(\n await tx.execute(sql`\n select\n c.relname::text as name,\n pg_get_userbyid(c.relowner)::text as owner,\n c.relrowsecurity as rls_enabled,\n c.relforcerowsecurity as rls_forced,\n row_security_active(c.oid) as rls_active,\n (select count(*)::int from pg_policy policy where policy.polrelid = c.oid) as policy_count,\n has_table_privilege(current_user, c.oid, 'SELECT') as can_select,\n has_table_privilege(current_user, c.oid, 'INSERT') as can_insert,\n has_table_privilege(current_user, c.oid, 'UPDATE') as can_update,\n has_table_privilege(current_user, c.oid, 'DELETE') as can_delete,\n has_table_privilege(current_user, c.oid, 'TRUNCATE') as can_truncate,\n has_table_privilege(current_user, c.oid, 'REFERENCES') as can_references,\n has_table_privilege(current_user, c.oid, 'TRIGGER') as can_trigger\n from pg_class c\n join pg_namespace n on n.oid = c.relnamespace\n where n.nspname = ${targetSchema}\n and c.relkind in ('r', 'p')\n order by c.relname\n `),\n ).map((row) => ({\n name: row.name,\n owner: row.owner,\n rlsEnabled: row.rls_enabled,\n rlsForced: row.rls_forced,\n rlsActive: row.rls_active,\n policyCount: row.policy_count,\n select: row.can_select,\n insert: row.can_insert,\n update: row.can_update,\n delete: row.can_delete,\n truncate: row.can_truncate,\n references: row.can_references,\n trigger: row.can_trigger,\n }));\n\n const privateRoutines = resultRows<{\n name: string;\n owner: string;\n can_execute: boolean;\n }>(\n await tx.execute(sql`\n select\n (p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')')::text as name,\n pg_get_userbyid(p.proowner)::text as owner,\n has_function_privilege(current_user, p.oid, 'EXECUTE') as can_execute\n from pg_proc p\n join pg_namespace n on n.oid = p.pronamespace\n where n.nspname = 'opengeni_private'\n and p.prokind in ('f', 'p')\n order by p.proname, pg_get_function_identity_arguments(p.oid)\n `),\n ).map((row) => ({\n name: row.name,\n owner: row.owner,\n execute: row.can_execute,\n }));\n\n return {\n identity: mappedIdentity,\n memberships,\n schemas,\n ownedSchemas,\n ownedRelations,\n tables,\n privateRoutines,\n };\n },\n { isolationLevel: \"repeatable read\", accessMode: \"read only\" },\n );\n}\n\n/** Pure deterministic evaluator used by startup/readiness and unit tests. */\nexport function evaluateRuntimeDatabasePosture(\n posture: RuntimeDatabasePosture,\n options: RuntimeDatabasePostureOptions,\n): string[] {\n const violations: string[] = [];\n const identity = posture.identity;\n\n if (!identity.currentUser || !identity.sessionUser) {\n violations.push(\"database identity is empty\");\n }\n if (identity.currentUser !== identity.sessionUser) {\n violations.push(\n `current_user ${identity.currentUser} does not match session_user ${identity.sessionUser}`,\n );\n }\n if (!identity.canConnectDatabase) {\n violations.push(\"runtime role lacks CONNECT on the current database\");\n }\n\n if (options.rlsStrategy === \"scoped\") {\n return violations;\n }\n\n const expectedRole = options.expectedRole?.trim() || \"opengeni_app\";\n const targetSchema = options.targetSchema?.trim() || \"public\";\n const protectedTables = new Set(options.protectedTables ?? FORCE_RLS_TABLES);\n const tablePrivileges = options.tablePrivileges ?? RUNTIME_TABLE_PRIVILEGES;\n const directRuntimeTables = new Set(Object.keys(tablePrivileges));\n const protectedNoDirectDmlTables = new Set(\n options.protectedNoDirectDmlTables ??\n (options.protectedTables ? [] : PROTECTED_NO_DIRECT_DML_TABLES),\n );\n\n if (identity.currentUser !== expectedRole || identity.sessionUser !== expectedRole) {\n violations.push(\n `runtime identity must be ${expectedRole} (current_user=${identity.currentUser}, session_user=${identity.sessionUser})`,\n );\n }\n if (!identity.canLogin) violations.push(\"runtime role is not LOGIN\");\n if (identity.superuser) violations.push(\"runtime role is SUPERUSER\");\n if (identity.bypassRls) violations.push(\"runtime role has BYPASSRLS\");\n if (identity.createRole) violations.push(\"runtime role has CREATEROLE\");\n if (identity.createDatabase) violations.push(\"runtime role has CREATEDB\");\n if (identity.replication) violations.push(\"runtime role has REPLICATION\");\n if (identity.inherit) violations.push(\"runtime role must be NOINHERIT\");\n if (identity.databaseOwner === expectedRole) violations.push(\"runtime role owns the database\");\n if (identity.canCreateInDatabase) {\n violations.push(\"runtime role has CREATE on the current database\");\n }\n if (identity.rowSecurity.toLowerCase() !== \"on\") {\n violations.push(`row_security is ${identity.rowSecurity}, expected on`);\n }\n if (posture.memberships.length > 0) {\n violations.push(`runtime role has memberships: ${sorted(posture.memberships).join(\", \")}`);\n }\n if (posture.ownedSchemas.length > 0) {\n violations.push(`runtime role owns schemas: ${sorted(posture.ownedSchemas).join(\", \")}`);\n }\n if (posture.ownedRelations.length > 0) {\n violations.push(`runtime role owns relations: ${sorted(posture.ownedRelations).join(\", \")}`);\n }\n\n for (const schemaName of new Set([targetSchema, \"opengeni_private\"])) {\n const schema = posture.schemas.find((candidate) => candidate.name === schemaName);\n if (!schema) {\n violations.push(`required schema ${schemaName} is missing`);\n continue;\n }\n if (schema.owner === expectedRole) {\n violations.push(`runtime role owns schema ${schemaName}`);\n }\n if (!schema.usage) violations.push(`runtime role lacks USAGE on schema ${schemaName}`);\n if (schema.create) violations.push(`runtime role has CREATE on schema ${schemaName}`);\n }\n\n const tableByName = new Map(posture.tables.map((table) => [table.name, table]));\n const actualRlsTables = new Set(\n posture.tables.filter((table) => table.rlsEnabled).map((table) => table.name),\n );\n const classifiedProtectedTables = new Set([\n ...directRuntimeTables,\n ...protectedNoDirectDmlTables,\n ]);\n const unclassifiedProtectedTables = difference(protectedTables, classifiedProtectedTables);\n if (unclassifiedProtectedTables.length > 0) {\n violations.push(\n `protected tables lack an explicit privilege class: ${unclassifiedProtectedTables.join(\", \")}`,\n );\n }\n const protectedNoDirectDmlOverlap = difference(\n protectedNoDirectDmlTables,\n new Set([...protectedNoDirectDmlTables].filter((table) => !directRuntimeTables.has(table))),\n );\n if (protectedNoDirectDmlOverlap.length > 0) {\n violations.push(\n `protected no-direct-DML tables also declare runtime privileges: ${protectedNoDirectDmlOverlap.join(\", \")}`,\n );\n }\n const nonProtectedNoDirectDmlTables = difference(protectedNoDirectDmlTables, protectedTables);\n if (nonProtectedNoDirectDmlTables.length > 0) {\n violations.push(\n `no-direct-DML tables are absent from the protected contract: ${nonProtectedNoDirectDmlTables.join(\", \")}`,\n );\n }\n const catalogTables = new Set(tableByName.keys());\n const missingRuntimeTables = difference(directRuntimeTables, catalogTables);\n if (missingRuntimeTables.length > 0) {\n violations.push(`runtime privilege tables are missing: ${missingRuntimeTables.join(\", \")}`);\n }\n const missingTables = difference(protectedTables, catalogTables);\n if (missingTables.length > 0) {\n violations.push(`protected tables are missing: ${missingTables.join(\", \")}`);\n }\n const undeclaredRlsTables = difference(actualRlsTables, protectedTables);\n if (undeclaredRlsTables.length > 0) {\n violations.push(\n `RLS tables are absent from the declared contract: ${undeclaredRlsTables.join(\", \")}`,\n );\n }\n\n for (const table of posture.tables) {\n const privileges = [\n [\"SELECT\", table.select],\n [\"INSERT\", table.insert],\n [\"UPDATE\", table.update],\n [\"DELETE\", table.delete],\n [\"TRUNCATE\", table.truncate],\n [\"REFERENCES\", table.references],\n [\"TRIGGER\", table.trigger],\n ] as const;\n const expectedPrivileges = new Set<string>(tablePrivileges[table.name] ?? []);\n if (table.owner === expectedRole) {\n violations.push(`runtime role owns table ${table.name}`);\n }\n const missingPrivileges = privileges\n .filter(([privilege, granted]) => expectedPrivileges.has(privilege) && !granted)\n .map(([privilege]) => privilege);\n if (missingPrivileges.length > 0) {\n violations.push(\n `table ${table.name} lacks required runtime privileges: ${missingPrivileges.join(\", \")}`,\n );\n }\n const excessPrivileges = privileges\n .filter(([privilege, granted]) => !expectedPrivileges.has(privilege) && granted)\n .map(([privilege]) => privilege);\n if (excessPrivileges.length > 0) {\n violations.push(\n `table ${table.name} grants excess runtime privileges: ${excessPrivileges.join(\", \")}`,\n );\n }\n }\n\n for (const tableName of protectedTables) {\n const table = tableByName.get(tableName);\n if (!table) continue;\n if (!table.rlsEnabled) violations.push(`table ${tableName} does not ENABLE RLS`);\n if (!table.rlsForced) violations.push(`table ${tableName} does not FORCE RLS`);\n if (!table.rlsActive) violations.push(`table ${tableName} has inactive RLS for runtime role`);\n if (table.policyCount < 1) violations.push(`table ${tableName} has no RLS policy`);\n }\n\n if (posture.privateRoutines.length === 0) {\n violations.push(\"opengeni_private has no helper routines\");\n }\n for (const routine of posture.privateRoutines) {\n if (routine.owner === expectedRole) {\n violations.push(`runtime role owns private routine ${routine.name}`);\n }\n if (!routine.execute) {\n violations.push(`runtime role lacks EXECUTE on private routine ${routine.name}`);\n }\n }\n\n return violations;\n}\n\nexport async function assertRuntimeDatabasePosture(\n db: Database,\n options: RuntimeDatabasePostureOptions,\n): Promise<RuntimeDatabasePosture> {\n const posture = await inspectRuntimeDatabasePosture(db, options);\n const violations = evaluateRuntimeDatabasePosture(posture, options);\n if (violations.length > 0) {\n throw new RuntimeDatabasePostureError(violations);\n }\n return posture;\n}\n\nexport function runtimeDatabaseReadyCheck(\n db: Database,\n options: RuntimeDatabasePostureOptions,\n): () => Promise<void> {\n return async () => {\n await assertRuntimeDatabasePosture(db, options);\n };\n}\n","export type RoleRelationshipDirection = \"inherits\" | \"member\";\n\nexport type RoleRelationshipCatalogRow = {\n relationship: string;\n direction: RoleRelationshipDirection;\n server_version_num: number;\n admin_option: boolean | null;\n inherit_option: boolean | null;\n set_option: boolean | null;\n member_is_superuser: boolean | null;\n member_can_create_role: boolean | null;\n grantor_role: string | null;\n grantor_is_superuser: boolean | null;\n};\n\nexport type ClassifiedRoleRelationships = {\n relationships: string[];\n managementOnlyRelationships: string[];\n unsafeRelationships: string[];\n};\n\ntype RoleTargetExpression = \"current_user\" | \"$1\";\n\n/**\n * One PostgreSQL 15-compatible catalog query for both provisioning and runtime\n * posture. PostgreSQL 16 added per-membership INHERIT and SET columns; reading\n * the catalog row through to_jsonb keeps this statement parseable on 15 while\n * leaving the missing options null and therefore fail-closed.\n */\nexport function roleRelationshipsCatalogQuery(targetRole: RoleTargetExpression): string {\n return `\nwith recursive target_role(oid, rolname) as (\n select oid, rolname\n from pg_roles\n where rolname = ${targetRole}\n), inherited_roles(oid, rolname) as (\n select parent.oid, parent.rolname\n from pg_auth_members membership\n join target_role target on target.oid = membership.member\n join pg_roles parent on parent.oid = membership.roleid\n union\n select parent.oid, parent.rolname\n from inherited_roles inherited\n join pg_auth_members membership on membership.member = inherited.oid\n join pg_roles parent on parent.oid = membership.roleid\n), relationships as (\n select\n ('inherits:' || inherited.rolname)::text as relationship,\n 'inherits'::text as direction,\n null::boolean as admin_option,\n null::boolean as inherit_option,\n null::boolean as set_option,\n null::boolean as member_is_superuser,\n null::boolean as member_can_create_role,\n null::text as grantor_role,\n null::boolean as grantor_is_superuser\n from inherited_roles inherited\n union all\n select\n ('member:' || member.rolname)::text as relationship,\n 'member'::text as direction,\n membership.admin_option,\n case\n when current_setting('server_version_num')::integer >= 160000\n then (to_jsonb(membership) ->> 'inherit_option')::boolean\n else null::boolean\n end as inherit_option,\n case\n when current_setting('server_version_num')::integer >= 160000\n then (to_jsonb(membership) ->> 'set_option')::boolean\n else null::boolean\n end as set_option,\n member.rolsuper as member_is_superuser,\n member.rolcreaterole as member_can_create_role,\n grantor.rolname::text as grantor_role,\n grantor.rolsuper as grantor_is_superuser\n from pg_auth_members membership\n join target_role target on target.oid = membership.roleid\n join pg_roles member on member.oid = membership.member\n left join pg_roles grantor on grantor.oid = membership.grantor\n)\nselect\n relationship,\n direction,\n current_setting('server_version_num')::integer as server_version_num,\n admin_option,\n inherit_option,\n set_option,\n member_is_superuser,\n member_can_create_role,\n grantor_role,\n grantor_is_superuser\nfrom relationships\norder by relationship, direction, grantor_role nulls first\n`;\n}\n\n/**\n * PostgreSQL 16+ automatically gives a non-superuser CREATEROLE principal an\n * ADMIN-only grant on a role it creates. The exact edge below permits role\n * management but cannot inherit the app role's privileges or SET ROLE into it.\n */\nexport function isManagementOnlyRoleRelationship(row: RoleRelationshipCatalogRow): boolean {\n return (\n row.direction === \"member\" &&\n row.server_version_num >= 160000 &&\n row.admin_option === true &&\n row.inherit_option === false &&\n row.set_option === false &&\n row.member_is_superuser === false &&\n row.member_can_create_role === true &&\n row.grantor_is_superuser === true\n );\n}\n\nfunction sortedUnique(values: Iterable<string>): string[] {\n return [...new Set(values)].sort((a, b) => a.localeCompare(b));\n}\n\n/** Classify exact management-only reverse grants while rejecting every other edge. */\nexport function classifyRoleRelationships(\n rows: readonly RoleRelationshipCatalogRow[],\n): ClassifiedRoleRelationships {\n const managementOnlyRows = rows.filter(isManagementOnlyRoleRelationship);\n const unsafeRows = rows.filter((row) => !isManagementOnlyRoleRelationship(row));\n\n return {\n relationships: sortedUnique(rows.map((row) => row.relationship)),\n managementOnlyRelationships: sortedUnique(managementOnlyRows.map((row) => row.relationship)),\n unsafeRelationships: sortedUnique(unsafeRows.map((row) => row.relationship)),\n };\n}\n"],"mappings":";AAAA,OAAO,cAAc;;;ACArB,SAAS,WAAW;;;AC6Bb,SAAS,8BAA8B,YAA0C;AACtF,SAAO;AAAA;AAAA;AAAA;AAAA,oBAIW,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAOO,IAAM,yBAAyB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAOO,IAAM,0BAA0B;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,IAAM,2BAA2B;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,IAAM,6BAA6B;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,E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AAO,OAAO;AACnB;AAEA,SAAS,mBAAmB,MAAc,OAAuB;AAC/D,MAAI,CAAC,2BAA2B,KAAK,KAAK,GAAG;AAC3C,UAAM,IAAI,MAAM,GAAG,IAAI,6CAA6C,KAAK,EAAE;AAAA,EAC7E;AACA,SAAO;AACT;AAEA,SAAS,WAAW,OAAuB;AACzC,SAAO,IAAI,MAAM,QAAQ,MAAM,IAAI,CAAC;AACtC;AAEA,SAAS,QAAQ,OAAuB;AACtC,SAAO,IAAI,MAAM,QAAQ,MAAM,IAAI,CAAC;AACtC;AAEA,SAAS,eAAe,OAAe,UAA0B;AAC/D,QAAM,MAAM,IAAI,IAAI,KAAK;AACzB,MAAI,WAAW,IAAI,QAAQ;AAC3B,SAAO,IAAI,SAAS;AACtB;AAMA,IAAI,YAAY,MAAM;AACpB,QAAM,WACJ,QAAQ,IAAI,oCACZ,QAAQ,IAAI,+BACZ,QAAQ,IAAI;AACd,MAAI,CAAC,UAAU;AACb,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,QAAM,SAAS,MAAM,eAAe,UAAU;AAAA,IAC5C,GAAI,QAAQ,IAAI,oBAAoB,KAAK,IACrC,EAAE,cAAc,QAAQ,IAAI,mBAAmB,KAAK,EAAE,IACtD,CAAC;AAAA,EACP,CAAC;AACD,UAAQ,IAAI,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;AAC7C;","names":["sql"]}
@@ -1,7 +1,47 @@
1
1
  import { environmentsEncryptionKeyBytes, type Settings } from "@opengeni/config";
2
2
  import { type CodexTokenSnapshot, type CodexUsagePayload, type CodexFetch, type CodexRateLimitResetCreditsDetails, type ResetCreditFetchFailureReason, refreshCodexToken } from "@opengeni/codex";
3
3
  import { encryptEnvironmentValue } from "./environment-crypto";
4
- import { loadCodexCredentialForRun, recordCodexTokenRefresh, setCodexCredentialStatus, withCodexCredentialRefreshLock, type Database } from "./index";
4
+ import type { Database } from "./database";
5
+ export type CodexCredentialTokens = {
6
+ accessToken: string;
7
+ refreshToken: string;
8
+ idToken: string;
9
+ };
10
+ export type CodexCredentialForRun = {
11
+ id: string;
12
+ version: number;
13
+ workspaceId: string;
14
+ tokens: CodexCredentialTokens;
15
+ chatgptAccountId: string | null;
16
+ scopes: string | null;
17
+ planType: string | null;
18
+ isFedramp: boolean;
19
+ expiresAt: Date | null;
20
+ lastRefreshAt: Date | null;
21
+ status: string;
22
+ lastError: string | null;
23
+ };
24
+ export type CodexAccountUsageSnapshot = {
25
+ primaryUsedPercent?: number | null;
26
+ primaryResetAt?: Date | null;
27
+ secondaryUsedPercent?: number | null;
28
+ secondaryResetAt?: Date | null;
29
+ checkedAt?: Date;
30
+ resetCreditAvailableCount?: number | null;
31
+ resetCreditsCheckedAt?: Date | null;
32
+ };
33
+ type CodexCredentialRefreshInput = {
34
+ id: string;
35
+ version: number;
36
+ workspaceId: string;
37
+ credentialEncrypted: string;
38
+ expiresAt: Date | null;
39
+ lastRefreshAt: Date;
40
+ };
41
+ type CodexCredentialStatusTarget = {
42
+ id: string;
43
+ version: number;
44
+ };
5
45
  export type CodexTokenDeadlineClock = {
6
46
  setTimeout: (callback: () => void, delayMs: number) => ReturnType<typeof globalThis.setTimeout>;
7
47
  clearTimeout: (handle: ReturnType<typeof globalThis.setTimeout>) => void;
@@ -19,15 +59,16 @@ export type CodexTokenDeadlineOptions = {
19
59
  */
20
60
  export declare function withCodexTokenDeadline<T>(operation: Promise<T>, options?: CodexTokenDeadlineOptions): Promise<T>;
21
61
  export type CodexAuthDeps = {
22
- loadCredential: typeof loadCodexCredentialForRun;
23
- recordRefresh: typeof recordCodexTokenRefresh;
24
- setStatus: typeof setCodexCredentialStatus;
62
+ loadCredential: (db: Database, settings: Settings, workspaceId: string, credentialId: string) => Promise<CodexCredentialForRun | null>;
63
+ recordRefresh: (db: Database, input: CodexCredentialRefreshInput) => Promise<boolean>;
64
+ setStatus: (db: Database, workspaceId: string, status: "active" | "needs_relogin" | "error", lastError: string | null, target: CodexCredentialStatusTarget) => Promise<boolean>;
25
65
  refresh: typeof refreshCodexToken;
26
66
  encrypt: typeof encryptEnvironmentValue;
27
67
  keyBytes: typeof environmentsEncryptionKeyBytes;
28
- withRefreshLock: typeof withCodexCredentialRefreshLock;
68
+ withRefreshLock: <T>(db: Database, workspaceId: string, credentialId: string, fn: (lockedDb: Database) => Promise<T>) => Promise<T>;
69
+ recordUsage?: (db: Database, workspaceId: string, credentialId: string, snapshot: CodexAccountUsageSnapshot) => Promise<boolean>;
29
70
  };
30
- export declare function buildCodexTokenResolver(db: Database, settings: Settings, workspaceId: string, credentialId: string, deps?: CodexAuthDeps): {
71
+ export declare function buildCodexTokenResolver(db: Database, settings: Settings, workspaceId: string, credentialId: string, deps: CodexAuthDeps): {
31
72
  getToken: () => Promise<CodexTokenSnapshot>;
32
73
  refresh: () => Promise<CodexTokenSnapshot>;
33
74
  };
@@ -45,7 +86,7 @@ export declare function buildCodexTokenResolver(db: Database, settings: Settings
45
86
  * A refresh that stamps needs_relogin returns { status:"error", reason } and never
46
87
  * hits the provider; a transient refresh error returns a plain error payload.
47
88
  */
48
- export declare function fetchCodexUsageForAccount(db: Database, settings: Settings, workspaceId: string, credentialId: string, fetchImpl?: CodexFetch): Promise<CodexUsagePayload>;
89
+ export declare function fetchCodexUsageForAccount(db: Database, settings: Settings, workspaceId: string, credentialId: string, deps: CodexAuthDeps, fetchImpl?: CodexFetch): Promise<CodexUsagePayload>;
49
90
  export type CodexRateLimitResetCreditsAccountResult = {
50
91
  ok: true;
51
92
  status: number;
@@ -61,4 +102,5 @@ export type CodexRateLimitResetCreditsAccountResult = {
61
102
  * this server-side function. Detailed rows are returned to the route only and
62
103
  * are never persisted as redemption authority.
63
104
  */
64
- export declare function fetchCodexRateLimitResetCreditsForAccount(db: Database, settings: Settings, workspaceId: string, credentialId: string, fetchImpl?: CodexFetch): Promise<CodexRateLimitResetCreditsAccountResult>;
105
+ export declare function fetchCodexRateLimitResetCreditsForAccount(db: Database, settings: Settings, workspaceId: string, credentialId: string, deps: CodexAuthDeps, fetchImpl?: CodexFetch): Promise<CodexRateLimitResetCreditsAccountResult>;
106
+ export {};
@@ -1,9 +1,47 @@
1
1
  import { environmentsEncryptionKeyBytes, type McpServerConnectionRef, type Settings } from "@opengeni/config";
2
- import type { ConnectionCredentialsPort, McpConnectionResourceScope, McpCredentialAuthNeededReason, McpCredentialsRequest, TurnInitiator, TurnInitiatorContext } from "@opengeni/contracts";
2
+ import type { ConnectionKind, ConnectionCredentialsPort, ConnectionStatus, McpConnectionResourceScope, McpCredentialAuthNeededReason, McpCredentialsRequest, TurnInitiator, TurnInitiatorContext } from "@opengeni/contracts";
3
3
  import { type DnsLookup, type FetchLike } from "@opengeni/network";
4
4
  export { isPrivateAddress } from "@opengeni/network";
5
5
  import { encryptEnvironmentValue } from "./environment-crypto";
6
- import { loadConnectionCredentialForBroker, recordConnectionTokenRefresh, recordConnectionUsed, setConnectionStatus, type ConnectionCredentialForBroker, type Database } from "./index";
6
+ import type { Database } from "./database";
7
+ export type ConnectionCredentialForBroker = {
8
+ id: string;
9
+ accountId: string;
10
+ workspaceId: string;
11
+ subjectId: string | null;
12
+ providerDomain: string;
13
+ kind: ConnectionKind;
14
+ status: ConnectionStatus;
15
+ credential: Record<string, unknown>;
16
+ grantedScopes: string[];
17
+ expiresAt: Date | null;
18
+ lastRefreshAt: Date | null;
19
+ version: number;
20
+ metadata: Record<string, unknown>;
21
+ };
22
+ export type ConnectionCredentialLookupInput = {
23
+ workspaceId: string;
24
+ connectionId?: string;
25
+ providerDomain: string;
26
+ kind?: ConnectionKind;
27
+ subjectId?: string | null;
28
+ allowSubjectOwned?: boolean;
29
+ };
30
+ export type ConnectionTokenRefreshInput = {
31
+ id: string;
32
+ version: number;
33
+ workspaceId: string;
34
+ credentialEncrypted: string;
35
+ expiresAt: Date | null;
36
+ grantedScopes?: string[];
37
+ lastRefreshAt: Date;
38
+ subjectId?: string | null;
39
+ };
40
+ export type ConnectionStatusGuard = {
41
+ id: string;
42
+ version: number;
43
+ subjectId?: string | null;
44
+ };
7
45
  export type ResolveConnectionCredentialResult = {
8
46
  status: "ok";
9
47
  headers: Record<string, string>;
@@ -60,10 +98,10 @@ export declare class HostMcpCredentialBindingError extends Error {
60
98
  */
61
99
  export declare function buildHostConnectionTokenResolver(resolve: NonNullable<ConnectionCredentialsPort["mcpCredentials"]>, context: HostMcpCredentialResolverContext): (input: ResolveConnectionCredentialInput) => Promise<ResolveConnectionCredentialResult>;
62
100
  export type ConnectionBrokerDeps = {
63
- loadCredential: typeof loadConnectionCredentialForBroker;
64
- recordRefresh: typeof recordConnectionTokenRefresh;
65
- setStatus: typeof setConnectionStatus;
66
- recordUsed: typeof recordConnectionUsed;
101
+ loadCredential: (db: Database, settings: Settings, input: ConnectionCredentialLookupInput) => Promise<ConnectionCredentialForBroker | null>;
102
+ recordRefresh: (db: Database, input: ConnectionTokenRefreshInput) => Promise<boolean>;
103
+ setStatus: (db: Database, workspaceId: string, status: ConnectionStatus, lastError: string | null, guard: ConnectionStatusGuard) => Promise<boolean>;
104
+ recordUsed: (db: Database, workspaceId: string, connectionId: string, subjectId?: string | null) => Promise<void>;
67
105
  refresh: typeof refreshOAuthConnectionCredential;
68
106
  encrypt: typeof encryptEnvironmentValue;
69
107
  keyBytes: typeof environmentsEncryptionKeyBytes;
@@ -92,7 +130,7 @@ export type RefreshTransportOptions = {
92
130
  fetchImpl?: FetchLike;
93
131
  dnsLookup?: DnsLookup;
94
132
  };
95
- export declare function buildConnectionTokenResolver(db: Database, settings: Settings, deps?: ConnectionBrokerDeps, options?: ConnectionTokenResolverOptions): (input: ResolveConnectionCredentialInput) => Promise<ResolveConnectionCredentialResult>;
133
+ export declare function buildConnectionTokenResolver(db: Database, settings: Settings, deps: ConnectionBrokerDeps, options?: ConnectionTokenResolverOptions): (input: ResolveConnectionCredentialInput) => Promise<ResolveConnectionCredentialResult>;
96
134
  export declare class ConnectionRefreshHttpError extends Error {
97
135
  readonly httpStatus: number;
98
136
  readonly oauthErrorCode: string | null;
@@ -0,0 +1,137 @@
1
+ import { type SQL } from "drizzle-orm";
2
+ import type { PgDatabase, PgTransactionConfig } from "drizzle-orm/pg-core";
3
+ import postgres from "postgres";
4
+ import { type IdempotentPersistenceTransactionOptions } from "./persistence-errors";
5
+ import * as schema from "./schema";
6
+ export type Database = PgDatabase<any, typeof schema>;
7
+ export type DbClient = {
8
+ db: Database;
9
+ close: () => Promise<void>;
10
+ };
11
+ export type RlsContext = {
12
+ accountId: string;
13
+ workspaceId?: string | null;
14
+ };
15
+ /**
16
+ * RLS posture for the connection OpenGeni's query layer runs over (Step I, §7.7).
17
+ *
18
+ * - `"force"` (DEFAULT — today's standalone behavior, byte-for-byte): OpenGeni
19
+ * connects as a NON-OWNER role (`opengeni_app`) and every table carries
20
+ * `FORCE ROW LEVEL SECURITY`, so the workspace/account GUCs set by
21
+ * `setRlsContext` are the ONLY thing that admits rows — even the table owner
22
+ * is subject to RLS. This is the Fork-A isolation guarantee.
23
+ * - `"scoped"` (embedded Fork-B opt-in): the host runs OpenGeni's queries over a
24
+ * role that OWNS the dedicated schema (RLS need not be forced for that role),
25
+ * relying on the host's own tenant boundary. OpenGeni STILL emits the
26
+ * `set_config('opengeni.account_id'/'workspace_id', …)` GUCs defensively on
27
+ * every scoped query, so the application query path is byte-identical between
28
+ * the two strategies and the app code is RLS-mode-agnostic. The strategy is a
29
+ * declared posture (consumed by `provisionRoles` and as a documented
30
+ * invariant), NOT a query-path branch — there is deliberately no `if
31
+ * (strategy === …)` anywhere in the helpers below. Picking `"scoped"` does not
32
+ * relax any GUC; it only changes which DB role the host provisions/connects as
33
+ * and asserts that the host accepts owning the isolation boundary.
34
+ */
35
+ export type RlsStrategy = "force" | "scoped";
36
+ /**
37
+ * Resolve a host-IdP/Better-Auth user *identifier* by email. Injected via
38
+ * `createDb({ userLookup })` (Step I). UNSET → today's raw parameterized select
39
+ * against Better Auth's `auth_users` table (see `getManagedUserByEmail`), which
40
+ * relies on the postgres-js array-shaped `db.execute` result. An embedded host
41
+ * whose identity lives elsewhere (a different IdP table, a different driver, or
42
+ * a non-`auth_users` user store) injects this closure so OpenGeni never touches
43
+ * `auth_users` directly. Returns the user id, or null when no such user exists.
44
+ */
45
+ export type UserLookup = (db: Database, email: string) => Promise<string | null>;
46
+ export type CreateDbOptions = {
47
+ /**
48
+ * The Postgres `search_path` for this connection (Step I, §7.8 runtime half).
49
+ * UNSET → today's behavior: NO `search_path` startup parameter is sent, so the
50
+ * server default applies (`public` for standalone, where every table + the
51
+ * `vector` extension + `gen_random_uuid()` live). For an embedded dedicated
52
+ * schema, pass e.g. `"opengeni,opengeni_private,public"` — postgres-js sends
53
+ * it as a per-session startup parameter (the supported, query-param-free way;
54
+ * URL `?search_path=` is IGNORED by postgres-js). Keep `public` LAST so the
55
+ * `vector` type and `gen_random_uuid()` (which live in `public` on the
56
+ * pgvector image) still resolve — the schema-isolation contract live footgun.
57
+ */
58
+ searchPath?: string;
59
+ /** RLS posture; defaults to `"force"` (today's standalone). */
60
+ rlsStrategy?: RlsStrategy;
61
+ /** Host-provided user-by-email resolver; unset → today's raw `auth_users` query. */
62
+ userLookup?: UserLookup;
63
+ /** postgres-js pool size; defaults to today's `10`. */
64
+ max?: number;
65
+ /**
66
+ * Connection-local default transaction isolation sent in the postgres-js
67
+ * startup parameters. This is intentionally not a role/database default:
68
+ * tests and embedded callers can exercise a different ambient isolation
69
+ * without mutating a shared PostgreSQL role or affecting other connections.
70
+ */
71
+ isolationLevel?: postgres.ConnectionParameters["default_transaction_isolation"];
72
+ };
73
+ /**
74
+ * The active RLS strategy + userLookup for an injected `Database`, recorded in a
75
+ * side WeakMap so helpers (and `getManagedUserByEmail`) can consult the host's
76
+ * binding without changing every call signature. A handle with no recorded
77
+ * config (e.g. one built outside `createDb`, or in a test) falls back to the
78
+ * standalone defaults: `rlsStrategy: "force"`, raw `auth_users` lookup.
79
+ */
80
+ type DbBinding = {
81
+ rlsStrategy: RlsStrategy;
82
+ userLookup?: UserLookup;
83
+ };
84
+ /** The strategy bound to a handle (or the `"force"` default). */
85
+ export declare function rlsStrategyFor(db: Database): RlsStrategy;
86
+ /**
87
+ * Run a raw SQL query and read its rows as a typed array.
88
+ *
89
+ * Why this exists: the Step I driver widening (`Database = PgDatabase<any, …>`)
90
+ * deliberately sets the query-result HKT to `any` so `db.execute(…)` is callable
91
+ * across drivers whose raw-result shapes differ (postgres-js → row array;
92
+ * node-postgres → `{ rows }`). A side effect is that `db.execute<T>(…)` now
93
+ * resolves to `any`, erasing the per-row element type at the call site. OpenGeni's
94
+ * OWN internal raw queries usually run over the postgres-js handle `createDb`
95
+ * builds (array result), while an embedded host may inject a node-postgres style
96
+ * driver (`{ rows }`). Normalize those two standard shapes in one place; reject
97
+ * an unknown driver result rather than silently treating it as an empty query.
98
+ */
99
+ export declare function rawRows<T extends Record<string, unknown>>(executor: Pick<Database, "execute">, query: SQL): Promise<T[]>;
100
+ export declare function createDb(databaseUrl: string, options?: CreateDbOptions): DbClient;
101
+ /**
102
+ * Register a host's `rlsStrategy`/`userLookup` against an externally-constructed
103
+ * `Database` handle (e.g. one the embedded host built from its own driver and
104
+ * injected, rather than via `createDb`). Lets the same WeakMap-backed lookups
105
+ * work for injected handles. Standalone never calls this (it uses `createDb`).
106
+ */
107
+ export declare function registerDbBinding(db: Database, binding: {
108
+ rlsStrategy?: RlsStrategy;
109
+ userLookup?: UserLookup;
110
+ }): void;
111
+ export declare function setRlsContext(db: Database, context: RlsContext): Promise<void>;
112
+ export declare function withRlsContext<T>(db: Database, context: RlsContext, fn: (db: Database) => Promise<T>, transactionConfig?: PgTransactionConfig): Promise<T>;
113
+ /**
114
+ * Run one bounded database operation on a transaction-pinned backend.
115
+ *
116
+ * Callers that also have an application deadline should check their abort
117
+ * signal before returning from `fn`; throwing there rolls the transaction back
118
+ * even when the application deadline won a surrounding Promise race.
119
+ */
120
+ export declare function withDatabaseStatementTimeout<T>(db: Database, timeoutMs: number, fn: (db: Database) => Promise<T>): Promise<T>;
121
+ export declare function rlsContextForWorkspace(db: Database, workspaceId: string): Promise<RlsContext>;
122
+ export declare function withWorkspaceRls<T>(db: Database, workspaceId: string, fn: (db: Database) => Promise<T>): Promise<T>;
123
+ export declare function retryWorkspacePersistence<T>(db: Database, workspaceId: string, options: IdempotentPersistenceTransactionOptions, fn: (db: Database) => Promise<T>): Promise<T>;
124
+ export declare function retryRlsPersistence<T>(db: Database, context: RlsContext, options: IdempotentPersistenceTransactionOptions, fn: (db: Database) => Promise<T>): Promise<T>;
125
+ /**
126
+ * Personal workspace data needs both tenant and authenticated-principal GUCs.
127
+ * `session_pins` uses this helper so FORCE RLS rejects another member's rows
128
+ * even if a future query accidentally omits its explicit subject predicate.
129
+ */
130
+ export declare function withWorkspaceSubjectRls<T>(db: Database, workspaceId: string, subjectId: string, fn: (db: Database) => Promise<T>, transactionConfig?: PgTransactionConfig): Promise<T>;
131
+ /** Apply and verify actor-private RLS on an already transaction-pinned handle. */
132
+ export declare function setSubjectRlsContext(db: Database, subjectId: string): Promise<void>;
133
+ export declare function withWorkspaceUsageLock<T>(db: Database, workspaceId: string, fn: (db: Database) => Promise<T>): Promise<T>;
134
+ export declare function withAccountRls<T>(db: Database, accountId: string, fn: (db: Database) => Promise<T>): Promise<T>;
135
+ /** Internal lookup for the host binding attached to a database handle. */
136
+ export declare function dbBindingFor(db: Database): DbBinding | undefined;
137
+ export {};