@opengeni/db 0.27.11 → 0.28.9
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.
- package/dist/{chunk-JYQPJ6Y5.js → chunk-P6CUHXQZ.js} +2967 -2272
- package/dist/chunk-P6CUHXQZ.js.map +1 -0
- package/dist/{chunk-RPHPNVWW.js → chunk-VHBFHMPC.js} +15 -1
- package/dist/chunk-VHBFHMPC.js.map +1 -0
- package/dist/environment-crypto.d.ts +8 -4
- package/dist/index.d.ts +272 -26
- package/dist/index.js +7798 -5008
- package/dist/index.js.map +1 -1
- package/dist/lossless-columns.d.ts +58 -0
- package/dist/lossless-json.d.ts +39 -0
- package/dist/memory-domain.d.ts +3 -6
- package/dist/persistence-errors.d.ts +7 -14
- package/dist/provision-roles.js +1 -1
- package/dist/runtime-posture.d.ts +2 -2
- package/dist/schema.d.ts +1420 -271
- package/dist/schema.js +25 -1
- package/dist/session-realtime-terminal.d.ts +7 -0
- package/dist/transcription-recordings-schema.d.ts +1264 -0
- package/dist/transcription-recordings.d.ts +228 -0
- package/drizzle/0065_enrollment_credential_generation.sql +10 -0
- package/drizzle/0140_retained_screenshot_artifacts.sql +192 -0
- package/drizzle/0170_resumable_transcription_recordings.sql +440 -0
- package/drizzle/0175_resumable_transcription_provider_deadline.sql +24 -0
- package/drizzle/0176_lossless_canonical_json.sql +975 -0
- package/drizzle/0177_session_events_workspace_turn_type_index.sql +5 -0
- package/drizzle/0178_permissioned_secret_reads.sql +14 -0
- package/drizzle/0179_slack_private_shortcut_delivery_gate.sql +85 -0
- package/drizzle/0180_retained_screenshot_lifecycle_fences.sql +273 -0
- package/drizzle/0181_connected_machine_removal.sql +52 -0
- package/drizzle/0182_connected_machine_remove_session_default.sql +77 -0
- package/package.json +4 -4
- package/src/database.ts +7 -1
- package/src/environment-crypto.ts +22 -9
- package/src/index.ts +4368 -1678
- package/src/lossless-columns.ts +35 -0
- package/src/lossless-json.ts +322 -0
- package/src/memory-domain.ts +5 -44
- package/src/persistence-errors.ts +29 -34
- package/src/runtime-posture.ts +14 -0
- package/src/schema.ts +264 -42
- package/src/session-control.ts +125 -76
- package/src/session-queue-commands.ts +325 -234
- package/src/session-realtime-context.ts +18 -5
- package/src/session-realtime-ledger.ts +29 -7
- package/src/session-realtime-mirror.ts +4 -2
- package/src/session-realtime-terminal.ts +89 -21
- package/src/session-realtime.ts +3 -2
- package/src/session-tool-call-settlement.ts +29 -15
- package/src/transcription-recordings-schema.ts +253 -0
- package/src/transcription-recordings.ts +1538 -0
- package/dist/chunk-JYQPJ6Y5.js.map +0 -1
- package/dist/chunk-RPHPNVWW.js.map +0 -1
- package/dist/event-payload-sanitizer.d.ts +0 -32
- package/src/event-payload-sanitizer.ts +0 -377
|
@@ -1 +0,0 @@
|
|
|
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;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;AA6D9B;AAOO,SAAS,iCAAiC,KAA0C;AACzF,SACE,IAAI,cAAc,YAClB,IAAI,sBAAsB,QAC1B,IAAI,iBAAiB,QACrB,IAAI,mBAAmB,SACvB,IAAI,eAAe,SACnB,IAAI,wBAAwB,SAC5B,IAAI,2BAA2B,QAC/B,IAAI,yBAAyB;AAEjC;AAEA,SAAS,aAAa,QAAoC;AACxD,SAAO,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,EAAE,cAAc,CAAC,CAAC;AAC/D;AAGO,SAAS,0BACd,MAC6B;AAC7B,QAAM,qBAAqB,KAAK,OAAO,gCAAgC;AACvE,QAAM,aAAa,KAAK,OAAO,CAAC,QAAQ,CAAC,iCAAiC,GAAG,CAAC;AAE9E,SAAO;AAAA,IACL,eAAe,aAAa,KAAK,IAAI,CAAC,QAAQ,IAAI,YAAY,CAAC;AAAA,IAC/D,6BAA6B,aAAa,mBAAmB,IAAI,CAAC,QAAQ,IAAI,YAAY,CAAC;AAAA,IAC3F,qBAAqB,aAAa,WAAW,IAAI,CAAC,QAAQ,IAAI,YAAY,CAAC;AAAA,EAC7E;AACF;;;ADtHO,IAAM,mBAAmB;AAAA,EAC9B;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;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,EAC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UAAQ,IAAI,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;AAC7C;","names":["sql"]}
|
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
import { type SecretForRedaction } from "@opengeni/contracts";
|
|
2
|
-
/**
|
|
3
|
-
* Strip NUL and repair invalid/lone UTF-16 surrogates in a single string.
|
|
4
|
-
* Returns the input unchanged (same reference) when it is already clean, so the
|
|
5
|
-
* common case allocates nothing.
|
|
6
|
-
*/
|
|
7
|
-
export declare function sanitizeEventString(value: string): string;
|
|
8
|
-
/**
|
|
9
|
-
* Deep-walk a session event payload and sanitize every string value. Mirrors the
|
|
10
|
-
* shape of the worker redaction deep-walk: objects, arrays, and nested
|
|
11
|
-
* combinations are traversed; non-string leaves pass through untouched. Object
|
|
12
|
-
* keys are sanitized too -- they are jsonb-constrained the same as values.
|
|
13
|
-
*/
|
|
14
|
-
export type SanitizeEventPayloadOptions = {
|
|
15
|
-
/**
|
|
16
|
-
* Separately trusted, server-created retained-output evidence. Never populate
|
|
17
|
-
* this from a producer-controlled payload field.
|
|
18
|
-
*/
|
|
19
|
-
fullEvidence?: unknown;
|
|
20
|
-
/** Exact runtime credential provenance to remove from keys and values. */
|
|
21
|
-
knownSecrets?: readonly SecretForRedaction[];
|
|
22
|
-
};
|
|
23
|
-
export declare function sanitizeEventPayload<T>(payload: T, options?: SanitizeEventPayloadOptions): T;
|
|
24
|
-
/**
|
|
25
|
-
* Make model-facing conversation data safe for Postgres and secret-redacted.
|
|
26
|
-
*
|
|
27
|
-
* Conversation history is the replay source for the model, so this boundary
|
|
28
|
-
* retains protocol structure and non-sensitive diagnostics while removing
|
|
29
|
-
* credential-bearing fields and text before durable storage. It also performs
|
|
30
|
-
* the database-safety repair (NUL removal and UTF-16 repair).
|
|
31
|
-
*/
|
|
32
|
-
export declare function sanitizeModelPayload<T>(payload: T, knownSecrets?: readonly SecretForRedaction[]): T;
|
|
@@ -1,377 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
boundSessionEventPayload,
|
|
3
|
-
isCredentialHeaderName,
|
|
4
|
-
isSensitiveFieldName,
|
|
5
|
-
redactSensitiveKey,
|
|
6
|
-
redactSensitiveText,
|
|
7
|
-
type SecretForRedaction,
|
|
8
|
-
} from "@opengeni/contracts";
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Last line of defense against a session event crashing a whole turn.
|
|
12
|
-
*
|
|
13
|
-
* Postgres `text`/`jsonb` cannot store a NUL byte (U+0000) nor lone UTF-16
|
|
14
|
-
* surrogates. Raw exec output routinely carries both -- chrome/crashpad logs,
|
|
15
|
-
* `cat` of a binary, random bytes -- and the worker persists that output verbatim
|
|
16
|
-
* inside `agent.toolCall.output` / `sandbox.command.output` event payloads. When
|
|
17
|
-
* such a payload reaches `INSERT INTO session_events`, the driver rejects it
|
|
18
|
-
* ("Failed query: insert into session_events") and the turn dies.
|
|
19
|
-
*
|
|
20
|
-
* `sanitizeEventPayload` deep-walks any payload value (objects, arrays, nested),
|
|
21
|
-
* repairs every string, redacts sensitive fields, then applies the canonical
|
|
22
|
-
* byte-bounded human/audit preview. Conversation truth uses
|
|
23
|
-
* `sanitizeModelPayload` below and remains a separate representation.
|
|
24
|
-
*/
|
|
25
|
-
|
|
26
|
-
const REPLACEMENT = "�";
|
|
27
|
-
const REDACTED = "[redacted]";
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Strip NUL and repair invalid/lone UTF-16 surrogates in a single string.
|
|
31
|
-
* Returns the input unchanged (same reference) when it is already clean, so the
|
|
32
|
-
* common case allocates nothing.
|
|
33
|
-
*/
|
|
34
|
-
export function sanitizeEventString(value: string): string {
|
|
35
|
-
// Fast path: no NUL and no surrogate code unit at all -> nothing to do.
|
|
36
|
-
// Surrogates live in U+D800..U+DFFF; a quick scan avoids the rebuild cost.
|
|
37
|
-
let needsWork = false;
|
|
38
|
-
for (let i = 0; i < value.length; i++) {
|
|
39
|
-
const code = value.charCodeAt(i);
|
|
40
|
-
if (code === 0x0000 || (code >= 0xd800 && code <= 0xdfff)) {
|
|
41
|
-
needsWork = true;
|
|
42
|
-
break;
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
if (!needsWork) {
|
|
46
|
-
return value;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
let out = "";
|
|
50
|
-
for (let i = 0; i < value.length; i++) {
|
|
51
|
-
const code = value.charCodeAt(i);
|
|
52
|
-
if (code === 0x0000) {
|
|
53
|
-
// Drop NUL entirely.
|
|
54
|
-
continue;
|
|
55
|
-
}
|
|
56
|
-
if (code >= 0xd800 && code <= 0xdbff) {
|
|
57
|
-
// High surrogate: valid only when immediately followed by a low surrogate.
|
|
58
|
-
const next = i + 1 < value.length ? value.charCodeAt(i + 1) : 0;
|
|
59
|
-
if (next >= 0xdc00 && next <= 0xdfff) {
|
|
60
|
-
out += value[i]! + value[i + 1]!;
|
|
61
|
-
i += 1;
|
|
62
|
-
continue;
|
|
63
|
-
}
|
|
64
|
-
out += REPLACEMENT;
|
|
65
|
-
continue;
|
|
66
|
-
}
|
|
67
|
-
if (code >= 0xdc00 && code <= 0xdfff) {
|
|
68
|
-
// Lone low surrogate (a valid pair would have been consumed above).
|
|
69
|
-
out += REPLACEMENT;
|
|
70
|
-
continue;
|
|
71
|
-
}
|
|
72
|
-
out += value[i]!;
|
|
73
|
-
}
|
|
74
|
-
return out;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
* Deep-walk a session event payload and sanitize every string value. Mirrors the
|
|
79
|
-
* shape of the worker redaction deep-walk: objects, arrays, and nested
|
|
80
|
-
* combinations are traversed; non-string leaves pass through untouched. Object
|
|
81
|
-
* keys are sanitized too -- they are jsonb-constrained the same as values.
|
|
82
|
-
*/
|
|
83
|
-
export type SanitizeEventPayloadOptions = {
|
|
84
|
-
/**
|
|
85
|
-
* Separately trusted, server-created retained-output evidence. Never populate
|
|
86
|
-
* this from a producer-controlled payload field.
|
|
87
|
-
*/
|
|
88
|
-
fullEvidence?: unknown;
|
|
89
|
-
/** Exact runtime credential provenance to remove from keys and values. */
|
|
90
|
-
knownSecrets?: readonly SecretForRedaction[];
|
|
91
|
-
};
|
|
92
|
-
|
|
93
|
-
export function sanitizeEventPayload<T>(payload: T, options: SanitizeEventPayloadOptions = {}): T {
|
|
94
|
-
// Bound first. The preview walker caps depth/container fan-out and replaces
|
|
95
|
-
// inline media before this sanitizer allocates a deep clone. Reversing this
|
|
96
|
-
// order lets a cyclic, deeply nested, or multi-megabyte tool result exhaust
|
|
97
|
-
// the stack/heap before the durable 64 KiB event boundary can protect it.
|
|
98
|
-
const bounded = boundSessionEventPayload(payload, {
|
|
99
|
-
fullEvidence: options.fullEvidence,
|
|
100
|
-
});
|
|
101
|
-
return sanitizeEventPayloadDeep(
|
|
102
|
-
bounded === payload ? removeProducerTruncationMetadata(bounded) : bounded,
|
|
103
|
-
options.knownSecrets ?? [],
|
|
104
|
-
);
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
/**
|
|
108
|
-
* `truncation` is reserved durable-boundary metadata. An ordinary payload that
|
|
109
|
-
* already fits the envelope otherwise returns by reference, so remove a
|
|
110
|
-
* producer-supplied value before persistence rather than allowing it to forge
|
|
111
|
-
* byte accounting or an available retained-artifact receipt. A payload changed
|
|
112
|
-
* by `boundSessionEventPayload` already carries freshly computed metadata and
|
|
113
|
-
* never reaches this helper.
|
|
114
|
-
*/
|
|
115
|
-
function removeProducerTruncationMetadata<T>(payload: T): T {
|
|
116
|
-
if (!isPlainObject(payload)) return payload;
|
|
117
|
-
const descriptor = Object.getOwnPropertyDescriptor(payload, "truncation");
|
|
118
|
-
if (!descriptor?.enumerable) return payload;
|
|
119
|
-
const cleaned = { ...payload };
|
|
120
|
-
delete cleaned.truncation;
|
|
121
|
-
return cleaned as T;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
function sanitizeEventPayloadDeep<T>(
|
|
125
|
-
payload: T,
|
|
126
|
-
knownSecrets: readonly SecretForRedaction[] = [],
|
|
127
|
-
): T {
|
|
128
|
-
if (typeof payload === "string") {
|
|
129
|
-
return sanitizeEventString(redactSensitiveText(payload, knownSecrets)) as unknown as T;
|
|
130
|
-
}
|
|
131
|
-
if (Array.isArray(payload)) {
|
|
132
|
-
return payload.map((item) => sanitizeEventPayloadDeep(item, knownSecrets)) as unknown as T;
|
|
133
|
-
}
|
|
134
|
-
if (payload instanceof Date) {
|
|
135
|
-
return safeDateIso(payload) as unknown as T;
|
|
136
|
-
}
|
|
137
|
-
if (payload && typeof payload === "object") {
|
|
138
|
-
const usedKeys = new Set<string>();
|
|
139
|
-
const entries = Object.entries(payload as Record<string, unknown>).map(([key, value]) => {
|
|
140
|
-
const safeKey = nextUniqueKey(
|
|
141
|
-
sanitizeEventString(redactSensitiveKey(key, knownSecrets)),
|
|
142
|
-
usedKeys,
|
|
143
|
-
);
|
|
144
|
-
return [safeKey, sanitizeSensitiveEventField(key, value, knownSecrets)] as const;
|
|
145
|
-
});
|
|
146
|
-
return Object.fromEntries(entries) as unknown as T;
|
|
147
|
-
}
|
|
148
|
-
return payload;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/**
|
|
152
|
-
* Make model-facing conversation data safe for Postgres and secret-redacted.
|
|
153
|
-
*
|
|
154
|
-
* Conversation history is the replay source for the model, so this boundary
|
|
155
|
-
* retains protocol structure and non-sensitive diagnostics while removing
|
|
156
|
-
* credential-bearing fields and text before durable storage. It also performs
|
|
157
|
-
* the database-safety repair (NUL removal and UTF-16 repair).
|
|
158
|
-
*/
|
|
159
|
-
export function sanitizeModelPayload<T>(
|
|
160
|
-
payload: T,
|
|
161
|
-
knownSecrets: readonly SecretForRedaction[] = [],
|
|
162
|
-
): T {
|
|
163
|
-
return sanitizeModelPayloadDeep(payload, new WeakSet<object>(), 0, knownSecrets);
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
const MODEL_PAYLOAD_SANITIZE_MAX_DEPTH = 64;
|
|
167
|
-
const MODEL_PAYLOAD_CYCLE_MARKER = "[OpenGeni omitted cyclic model payload]";
|
|
168
|
-
const MODEL_PAYLOAD_DEPTH_MARKER = "[OpenGeni omitted model payload beyond database-safety depth]";
|
|
169
|
-
|
|
170
|
-
function sanitizeModelPayloadDeep<T>(
|
|
171
|
-
payload: T,
|
|
172
|
-
seen: WeakSet<object>,
|
|
173
|
-
depth: number,
|
|
174
|
-
knownSecrets: readonly SecretForRedaction[] = [],
|
|
175
|
-
): T {
|
|
176
|
-
if (typeof payload === "string") {
|
|
177
|
-
return sanitizeEventString(redactSensitiveText(payload, knownSecrets)) as unknown as T;
|
|
178
|
-
}
|
|
179
|
-
if (!payload || typeof payload !== "object") return payload;
|
|
180
|
-
if (payload instanceof Date) {
|
|
181
|
-
return safeDateIso(payload) as unknown as T;
|
|
182
|
-
}
|
|
183
|
-
if (depth >= MODEL_PAYLOAD_SANITIZE_MAX_DEPTH) {
|
|
184
|
-
return MODEL_PAYLOAD_DEPTH_MARKER as unknown as T;
|
|
185
|
-
}
|
|
186
|
-
if (seen.has(payload)) return MODEL_PAYLOAD_CYCLE_MARKER as unknown as T;
|
|
187
|
-
seen.add(payload);
|
|
188
|
-
try {
|
|
189
|
-
if (Array.isArray(payload)) {
|
|
190
|
-
return payload.map((item) =>
|
|
191
|
-
sanitizeModelPayloadDeep(item, seen, depth + 1, knownSecrets),
|
|
192
|
-
) as unknown as T;
|
|
193
|
-
}
|
|
194
|
-
const usedKeys = new Set<string>();
|
|
195
|
-
return Object.fromEntries(
|
|
196
|
-
Object.entries(payload as Record<string, unknown>).map(([key, value]) => {
|
|
197
|
-
const safeKey = nextUniqueKey(
|
|
198
|
-
sanitizeEventString(redactSensitiveKey(key, knownSecrets)),
|
|
199
|
-
usedKeys,
|
|
200
|
-
);
|
|
201
|
-
if (isSensitiveFieldName(key)) {
|
|
202
|
-
return [safeKey, REDACTED] as const;
|
|
203
|
-
}
|
|
204
|
-
if (normalizeFieldName(key) === "headers") {
|
|
205
|
-
return [safeKey, sanitizeModelHeaders(value, seen, depth + 1, knownSecrets)] as const;
|
|
206
|
-
}
|
|
207
|
-
return [safeKey, sanitizeModelPayloadDeep(value, seen, depth + 1, knownSecrets)] as const;
|
|
208
|
-
}),
|
|
209
|
-
) as unknown as T;
|
|
210
|
-
} finally {
|
|
211
|
-
seen.delete(payload);
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
function safeDateIso(value: Date): string | null {
|
|
216
|
-
try {
|
|
217
|
-
const epoch = Date.prototype.getTime.call(value);
|
|
218
|
-
return Number.isFinite(epoch) ? Date.prototype.toISOString.call(value) : null;
|
|
219
|
-
} catch {
|
|
220
|
-
return null;
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
function sanitizeSensitiveEventField(
|
|
225
|
-
key: string,
|
|
226
|
-
value: unknown,
|
|
227
|
-
knownSecrets: readonly SecretForRedaction[],
|
|
228
|
-
): unknown {
|
|
229
|
-
if (key === "mcpServers") {
|
|
230
|
-
return sanitizeSessionMcpServerList(value, knownSecrets);
|
|
231
|
-
}
|
|
232
|
-
if (key === "mcpCredentialUpdates") {
|
|
233
|
-
return sanitizeMcpCredentialUpdateList(value, knownSecrets);
|
|
234
|
-
}
|
|
235
|
-
if (normalizeFieldName(key) === "headers") {
|
|
236
|
-
return sanitizeEventHeaders(value, knownSecrets);
|
|
237
|
-
}
|
|
238
|
-
if (isSensitiveFieldName(key)) {
|
|
239
|
-
return REDACTED;
|
|
240
|
-
}
|
|
241
|
-
return sanitizeEventPayloadDeep(value, knownSecrets);
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
function sanitizeEventHeaders(
|
|
245
|
-
value: unknown,
|
|
246
|
-
knownSecrets: readonly SecretForRedaction[],
|
|
247
|
-
): unknown {
|
|
248
|
-
if (!isPlainObject(value)) {
|
|
249
|
-
return sanitizeEventPayloadDeep(value, knownSecrets);
|
|
250
|
-
}
|
|
251
|
-
const usedKeys = new Set<string>();
|
|
252
|
-
return Object.fromEntries(
|
|
253
|
-
Object.entries(value).map(([key, child]) => {
|
|
254
|
-
const safeKey = nextUniqueKey(
|
|
255
|
-
sanitizeEventString(redactSensitiveKey(key, knownSecrets)),
|
|
256
|
-
usedKeys,
|
|
257
|
-
);
|
|
258
|
-
return [
|
|
259
|
-
safeKey,
|
|
260
|
-
isCredentialHeaderName(key) ? REDACTED : sanitizeEventPayloadDeep(child, knownSecrets),
|
|
261
|
-
];
|
|
262
|
-
}),
|
|
263
|
-
);
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
function sanitizeModelHeaders(
|
|
267
|
-
value: unknown,
|
|
268
|
-
seen: WeakSet<object>,
|
|
269
|
-
depth: number,
|
|
270
|
-
knownSecrets: readonly SecretForRedaction[],
|
|
271
|
-
): unknown {
|
|
272
|
-
if (!isPlainObject(value)) {
|
|
273
|
-
return sanitizeModelPayloadDeep(value, seen, depth, knownSecrets);
|
|
274
|
-
}
|
|
275
|
-
if (depth >= MODEL_PAYLOAD_SANITIZE_MAX_DEPTH) {
|
|
276
|
-
return MODEL_PAYLOAD_DEPTH_MARKER;
|
|
277
|
-
}
|
|
278
|
-
if (seen.has(value)) return MODEL_PAYLOAD_CYCLE_MARKER;
|
|
279
|
-
seen.add(value);
|
|
280
|
-
try {
|
|
281
|
-
const usedKeys = new Set<string>();
|
|
282
|
-
return Object.fromEntries(
|
|
283
|
-
Object.entries(value).map(([key, child]) => {
|
|
284
|
-
const safeKey = nextUniqueKey(
|
|
285
|
-
sanitizeEventString(redactSensitiveKey(key, knownSecrets)),
|
|
286
|
-
usedKeys,
|
|
287
|
-
);
|
|
288
|
-
return [
|
|
289
|
-
safeKey,
|
|
290
|
-
isCredentialHeaderName(key)
|
|
291
|
-
? REDACTED
|
|
292
|
-
: sanitizeModelPayloadDeep(child, seen, depth + 1, knownSecrets),
|
|
293
|
-
];
|
|
294
|
-
}),
|
|
295
|
-
);
|
|
296
|
-
} finally {
|
|
297
|
-
seen.delete(value);
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
function sanitizeSessionMcpServerList(
|
|
302
|
-
value: unknown,
|
|
303
|
-
knownSecrets: readonly SecretForRedaction[],
|
|
304
|
-
): unknown {
|
|
305
|
-
if (!Array.isArray(value)) {
|
|
306
|
-
return sanitizeEventPayloadDeep(value, knownSecrets);
|
|
307
|
-
}
|
|
308
|
-
return value.map((item) => {
|
|
309
|
-
if (!isPlainObject(item)) {
|
|
310
|
-
return sanitizeEventPayloadDeep(item, knownSecrets);
|
|
311
|
-
}
|
|
312
|
-
const { headers, headersEncrypted, ...rest } = item;
|
|
313
|
-
const cleaned = sanitizeEventPayloadDeep(rest, knownSecrets) as Record<string, unknown>;
|
|
314
|
-
const headerNames =
|
|
315
|
-
safeHeaderNames(headers, knownSecrets) ?? safeHeaderNames(headersEncrypted, knownSecrets);
|
|
316
|
-
if (headerNames) {
|
|
317
|
-
cleaned.headerNames = headerNames;
|
|
318
|
-
}
|
|
319
|
-
return cleaned;
|
|
320
|
-
});
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
function sanitizeMcpCredentialUpdateList(
|
|
324
|
-
value: unknown,
|
|
325
|
-
knownSecrets: readonly SecretForRedaction[],
|
|
326
|
-
): unknown {
|
|
327
|
-
if (!Array.isArray(value)) {
|
|
328
|
-
return sanitizeEventPayloadDeep(value, knownSecrets);
|
|
329
|
-
}
|
|
330
|
-
return value.map((item) => {
|
|
331
|
-
if (!isPlainObject(item)) {
|
|
332
|
-
return sanitizeEventPayloadDeep(item, knownSecrets);
|
|
333
|
-
}
|
|
334
|
-
const { headers, headersEncrypted, ...rest } = item;
|
|
335
|
-
const cleaned = sanitizeEventPayloadDeep(rest, knownSecrets) as Record<string, unknown>;
|
|
336
|
-
const headerNames =
|
|
337
|
-
safeHeaderNames(headers, knownSecrets) ?? safeHeaderNames(headersEncrypted, knownSecrets);
|
|
338
|
-
if (headerNames) {
|
|
339
|
-
cleaned.headerNames = headerNames;
|
|
340
|
-
}
|
|
341
|
-
return cleaned;
|
|
342
|
-
});
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
function safeHeaderNames(
|
|
346
|
-
value: unknown,
|
|
347
|
-
knownSecrets: readonly SecretForRedaction[],
|
|
348
|
-
): string[] | null {
|
|
349
|
-
if (!isPlainObject(value)) {
|
|
350
|
-
return null;
|
|
351
|
-
}
|
|
352
|
-
const usedKeys = new Set<string>();
|
|
353
|
-
return Object.keys(value)
|
|
354
|
-
.map((key) =>
|
|
355
|
-
nextUniqueKey(sanitizeEventString(redactSensitiveKey(key, knownSecrets)), usedKeys),
|
|
356
|
-
)
|
|
357
|
-
.sort();
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
function nextUniqueKey(base: string, usedKeys: Set<string>): string {
|
|
361
|
-
let candidate = base;
|
|
362
|
-
let suffix = 2;
|
|
363
|
-
while (usedKeys.has(candidate)) {
|
|
364
|
-
candidate = `${base}#${suffix}`;
|
|
365
|
-
suffix += 1;
|
|
366
|
-
}
|
|
367
|
-
usedKeys.add(candidate);
|
|
368
|
-
return candidate;
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
372
|
-
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
function normalizeFieldName(key: string): string {
|
|
376
|
-
return key.toLowerCase().replace(/[-_]/g, "");
|
|
377
|
-
}
|