@opengeni/db 0.12.1 → 0.13.0

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 (37) hide show
  1. package/dist/chunk-ELMUCYZF.js +906 -0
  2. package/dist/chunk-ELMUCYZF.js.map +1 -0
  3. package/dist/chunk-N4WTE6SB.js +4033 -0
  4. package/dist/chunk-N4WTE6SB.js.map +1 -0
  5. package/dist/index.d.ts +2 -2
  6. package/dist/index.js +3594 -2059
  7. package/dist/index.js.map +1 -1
  8. package/dist/provision-roles.d.ts +472 -43
  9. package/dist/provision-roles.js +1 -1
  10. package/dist/{schema-BejThLcd.d.ts → schema-Bh1Hr7xY.d.ts} +2507 -970
  11. package/dist/schema.d.ts +1 -1
  12. package/dist/schema.js +9 -1
  13. package/drizzle/0122_codex_capacity_same_turn.sql +59 -0
  14. package/drizzle/0123_session_tool_policy_version.sql +14 -0
  15. package/drizzle/0124_session_event_duplicate_lookup.sql +4 -0
  16. package/drizzle/0125_document_drops_visibility.sql +29 -0
  17. package/drizzle/0126_document_access_constraints.sql +138 -0
  18. package/drizzle/0127_document_default_base_index.sql +5 -0
  19. package/drizzle/0128_github_installation_authority.sql +69 -0
  20. package/drizzle/0129_retained_process_reconciliation.sql +356 -0
  21. package/drizzle/0130_workspace_instruction_policies.sql +330 -0
  22. package/drizzle/0131_slack_bot_install_and_post_idempotency.sql +133 -0
  23. package/package.json +4 -3
  24. package/src/event-payload-sanitizer.ts +167 -55
  25. package/src/index.ts +1850 -264
  26. package/src/new-session-drafts.ts +127 -6
  27. package/src/provision-roles.ts +184 -2
  28. package/src/runtime-posture-cli.ts +57 -0
  29. package/src/runtime-posture.ts +770 -0
  30. package/src/schema.ts +243 -3
  31. package/src/session-control.ts +1 -0
  32. package/src/workspace-instruction-policies-schema.ts +140 -0
  33. package/src/workspace-instruction-policies.ts +624 -0
  34. package/dist/chunk-BMFDXFPA.js +0 -155
  35. package/dist/chunk-BMFDXFPA.js.map +0 -1
  36. package/dist/chunk-VUKRIBO5.js +0 -3679
  37. package/dist/chunk-VUKRIBO5.js.map +0 -1
@@ -0,0 +1,906 @@
1
+ // src/provision-roles.ts
2
+ import postgres from "postgres";
3
+
4
+ // src/runtime-posture.ts
5
+ import { sql } from "drizzle-orm";
6
+ var FORCE_RLS_TABLES = [
7
+ "agent_run_states",
8
+ "api_keys",
9
+ "audit_events",
10
+ "billing_customers",
11
+ "capability_catalog_items",
12
+ "capability_installations",
13
+ "codex_capacity_waiters",
14
+ "codex_credential_leases",
15
+ "codex_reset_redemption_attempts",
16
+ "codex_rotation_settings",
17
+ "codex_subscription_credentials",
18
+ "composer_drafts",
19
+ "connections",
20
+ "credit_ledger_entries",
21
+ "device_enrollment_requests",
22
+ "document_bases",
23
+ "document_chunks",
24
+ "documents",
25
+ "enrollments",
26
+ "file_uploads",
27
+ "files",
28
+ "github_installation_repositories",
29
+ "github_installations",
30
+ "host_export_config",
31
+ "host_export_consumers",
32
+ "host_export_cursor_state",
33
+ "host_export_dead_letters",
34
+ "host_export_outbox",
35
+ "import_batches",
36
+ "integration_oauth_state_nonces",
37
+ "knowledge_memories",
38
+ "machine_metrics_latest",
39
+ "machine_metrics_series",
40
+ "new_session_drafts",
41
+ "pack_installations",
42
+ "rig_changes",
43
+ "rig_versions",
44
+ "rigs",
45
+ "sandbox_lease_holders",
46
+ "sandbox_leases",
47
+ "sandbox_pty_sessions",
48
+ "sandbox_retained_processes",
49
+ "sandbox_session_envelopes",
50
+ "sandbox_workspace_mutation_admissions",
51
+ "sandboxes",
52
+ "scheduled_task_runs",
53
+ "scheduled_tasks",
54
+ "session_attempt_interruptions",
55
+ "session_command_receipts",
56
+ "session_events",
57
+ "session_goals",
58
+ "session_history_items",
59
+ "session_human_input_requests",
60
+ "session_list_snapshots",
61
+ "session_mcp_servers",
62
+ "session_pending_tool_calls",
63
+ "session_pins",
64
+ "session_recordings",
65
+ "session_spawn_denials",
66
+ "session_stream_acknowledgments",
67
+ "session_system_update_outbox",
68
+ "session_system_updates",
69
+ "session_turn_attempts",
70
+ "session_turns",
71
+ "session_workflow_wake_outbox",
72
+ "sessions",
73
+ "slack_bot_post_operations",
74
+ "social_connections",
75
+ "social_posts",
76
+ "usage_events",
77
+ "workspace_captures",
78
+ "workspace_control_events",
79
+ "workspace_inference_controls",
80
+ "workspace_instruction_policy_activation_events",
81
+ "workspace_instruction_policy_heads",
82
+ "workspace_instruction_policy_revisions",
83
+ "workspace_model_policies",
84
+ "workspace_packs",
85
+ "workspace_session_activity_revisions",
86
+ "workspace_variable_set_variables",
87
+ "workspace_variable_sets"
88
+ ];
89
+ var NON_RLS_RUNTIME_TABLES = [
90
+ "auth_identities",
91
+ "auth_rate_limits",
92
+ "auth_sessions",
93
+ "auth_users",
94
+ "auth_verifications",
95
+ "integration_oauth_clients",
96
+ "managed_accounts",
97
+ "nested_agent_depth_configuration",
98
+ "stripe_webhook_events",
99
+ "workspace_memberships",
100
+ "workspaces"
101
+ ];
102
+ var RUNTIME_FULL_DML_TABLES = [
103
+ "agent_run_states",
104
+ "api_keys",
105
+ "audit_events",
106
+ "auth_identities",
107
+ "auth_rate_limits",
108
+ "auth_sessions",
109
+ "auth_users",
110
+ "auth_verifications",
111
+ "billing_customers",
112
+ "capability_catalog_items",
113
+ "capability_installations",
114
+ "codex_capacity_waiters",
115
+ "codex_credential_leases",
116
+ "codex_reset_redemption_attempts",
117
+ "codex_rotation_settings",
118
+ "codex_subscription_credentials",
119
+ "composer_drafts",
120
+ "connections",
121
+ "credit_ledger_entries",
122
+ "device_enrollment_requests",
123
+ "document_bases",
124
+ "document_chunks",
125
+ "documents",
126
+ "enrollments",
127
+ "file_uploads",
128
+ "files",
129
+ "github_installation_repositories",
130
+ "github_installations",
131
+ "import_batches",
132
+ "integration_oauth_clients",
133
+ "integration_oauth_state_nonces",
134
+ "knowledge_memories",
135
+ "machine_metrics_latest",
136
+ "machine_metrics_series",
137
+ "managed_accounts",
138
+ "new_session_drafts",
139
+ "pack_installations",
140
+ "rig_changes",
141
+ "rig_versions",
142
+ "rigs",
143
+ "sandbox_lease_holders",
144
+ "sandbox_leases",
145
+ "sandbox_pty_sessions",
146
+ "sandbox_retained_processes",
147
+ "sandbox_session_envelopes",
148
+ "sandbox_workspace_mutation_admissions",
149
+ "sandboxes",
150
+ "scheduled_task_runs",
151
+ "scheduled_tasks",
152
+ "session_attempt_interruptions",
153
+ "session_command_receipts",
154
+ "session_events",
155
+ "session_goals",
156
+ "session_history_items",
157
+ "session_human_input_requests",
158
+ "session_list_snapshots",
159
+ "session_mcp_servers",
160
+ "session_pending_tool_calls",
161
+ "session_pins",
162
+ "session_recordings",
163
+ "session_stream_acknowledgments",
164
+ "session_system_update_outbox",
165
+ "session_system_updates",
166
+ "session_turn_attempts",
167
+ "session_turns",
168
+ "session_workflow_wake_outbox",
169
+ "sessions",
170
+ "slack_bot_post_operations",
171
+ "social_connections",
172
+ "social_posts",
173
+ "stripe_webhook_events",
174
+ "usage_events",
175
+ "workspace_captures",
176
+ "workspace_control_events",
177
+ "workspace_inference_controls",
178
+ "workspace_instruction_policy_heads",
179
+ "workspace_memberships",
180
+ "workspace_model_policies",
181
+ "workspace_packs",
182
+ "workspace_session_activity_revisions",
183
+ "workspace_variable_set_variables",
184
+ "workspace_variable_sets",
185
+ "workspaces"
186
+ ];
187
+ var RUNTIME_READ_ONLY_TABLES = ["nested_agent_depth_configuration"];
188
+ var RUNTIME_READ_INSERT_TABLES = [
189
+ "session_spawn_denials",
190
+ "workspace_instruction_policy_activation_events",
191
+ "workspace_instruction_policy_revisions"
192
+ ];
193
+ var PROTECTED_NO_DIRECT_DML_TABLES = [
194
+ "host_export_config",
195
+ "host_export_consumers",
196
+ "host_export_cursor_state",
197
+ "host_export_dead_letters",
198
+ "host_export_outbox"
199
+ ];
200
+ var FULL_DML_PRIVILEGES = ["SELECT", "INSERT", "UPDATE", "DELETE"];
201
+ var RUNTIME_TABLE_PRIVILEGES = Object.freeze({
202
+ ...Object.fromEntries(RUNTIME_FULL_DML_TABLES.map((table) => [table, FULL_DML_PRIVILEGES])),
203
+ ...Object.fromEntries(RUNTIME_READ_ONLY_TABLES.map((table) => [table, ["SELECT"]])),
204
+ ...Object.fromEntries(
205
+ RUNTIME_READ_INSERT_TABLES.map((table) => [table, ["SELECT", "INSERT"]])
206
+ )
207
+ });
208
+ var RUNTIME_DML_TABLES = Object.freeze(
209
+ Object.keys(RUNTIME_TABLE_PRIVILEGES).sort((a, b) => a.localeCompare(b))
210
+ );
211
+ var RuntimeDatabasePostureError = class extends Error {
212
+ violations;
213
+ constructor(violations) {
214
+ super(`Runtime database posture check failed: ${violations.join("; ")}`);
215
+ this.name = "RuntimeDatabasePostureError";
216
+ this.violations = violations;
217
+ }
218
+ };
219
+ function resultRows(result) {
220
+ if (Array.isArray(result)) {
221
+ return result;
222
+ }
223
+ const rows = result?.rows;
224
+ if (Array.isArray(rows)) {
225
+ return rows;
226
+ }
227
+ throw new Error("Runtime database posture query returned an unsupported result shape");
228
+ }
229
+ function sorted(values) {
230
+ return [...values].sort((a, b) => a.localeCompare(b));
231
+ }
232
+ function difference(left, right) {
233
+ return sorted([...left].filter((value) => !right.has(value)));
234
+ }
235
+ async function inspectRuntimeDatabasePosture(db, options) {
236
+ const targetSchema = options.targetSchema?.trim() || "public";
237
+ return await db.transaction(
238
+ async (tx) => {
239
+ const identityRows = resultRows(
240
+ await tx.execute(sql`
241
+ select
242
+ current_user::text as current_user,
243
+ session_user::text as session_user,
244
+ pg_get_userbyid(d.datdba)::text as database_owner,
245
+ has_database_privilege(current_user, d.oid, 'CONNECT') as can_connect_database,
246
+ has_database_privilege(current_user, d.oid, 'CREATE') as can_create_in_database,
247
+ current_setting('row_security')::text as row_security,
248
+ r.rolcanlogin,
249
+ r.rolsuper,
250
+ r.rolinherit,
251
+ r.rolcreaterole,
252
+ r.rolcreatedb,
253
+ r.rolreplication,
254
+ r.rolbypassrls
255
+ from pg_roles r
256
+ join pg_database d on d.datname = current_database()
257
+ where r.rolname = current_user
258
+ `)
259
+ );
260
+ const identity = identityRows[0];
261
+ if (!identity) {
262
+ throw new Error("Runtime database posture could not resolve the current PostgreSQL role");
263
+ }
264
+ const mappedIdentity = {
265
+ currentUser: identity.current_user,
266
+ sessionUser: identity.session_user,
267
+ databaseOwner: identity.database_owner,
268
+ canConnectDatabase: identity.can_connect_database,
269
+ canCreateInDatabase: identity.can_create_in_database,
270
+ rowSecurity: identity.row_security,
271
+ canLogin: identity.rolcanlogin,
272
+ superuser: identity.rolsuper,
273
+ inherit: identity.rolinherit,
274
+ createRole: identity.rolcreaterole,
275
+ createDatabase: identity.rolcreatedb,
276
+ replication: identity.rolreplication,
277
+ bypassRls: identity.rolbypassrls
278
+ };
279
+ if (options.rlsStrategy === "scoped") {
280
+ return {
281
+ identity: mappedIdentity,
282
+ memberships: [],
283
+ schemas: [],
284
+ ownedSchemas: [],
285
+ ownedRelations: [],
286
+ tables: [],
287
+ privateRoutines: []
288
+ };
289
+ }
290
+ const memberships = resultRows(
291
+ await tx.execute(sql`
292
+ with recursive inherited_roles(oid, rolname) as (
293
+ select parent.oid, parent.rolname
294
+ from pg_auth_members membership
295
+ join pg_roles member on member.oid = membership.member
296
+ join pg_roles parent on parent.oid = membership.roleid
297
+ where member.rolname = current_user
298
+ union
299
+ select parent.oid, parent.rolname
300
+ from inherited_roles inherited
301
+ join pg_auth_members membership on membership.member = inherited.oid
302
+ join pg_roles parent on parent.oid = membership.roleid
303
+ )
304
+ select ('inherits:' || rolname)::text as relationship from inherited_roles
305
+ union
306
+ select ('member:' || member.rolname)::text as relationship
307
+ from pg_auth_members membership
308
+ join pg_roles parent on parent.oid = membership.roleid
309
+ join pg_roles member on member.oid = membership.member
310
+ where parent.rolname = current_user
311
+ order by relationship
312
+ `)
313
+ ).map((row) => row.relationship);
314
+ const schemas = resultRows(
315
+ await tx.execute(sql`
316
+ select
317
+ n.nspname::text as name,
318
+ pg_get_userbyid(n.nspowner)::text as owner,
319
+ has_schema_privilege(current_user, n.oid, 'USAGE') as usage,
320
+ has_schema_privilege(current_user, n.oid, 'CREATE') as create
321
+ from pg_namespace n
322
+ where n.nspname in (${targetSchema}, 'opengeni_private')
323
+ order by n.nspname
324
+ `)
325
+ );
326
+ const ownedSchemas = resultRows(
327
+ await tx.execute(sql`
328
+ select n.nspname::text as name
329
+ from pg_namespace n
330
+ join pg_roles r on r.oid = n.nspowner
331
+ where r.rolname = current_user
332
+ and n.nspname <> 'information_schema'
333
+ and n.nspname !~ '^pg_'
334
+ order by n.nspname
335
+ `)
336
+ ).map((row) => row.name);
337
+ const ownedRelations = resultRows(
338
+ await tx.execute(sql`
339
+ select (n.nspname || '.' || c.relname)::text as name
340
+ from pg_class c
341
+ join pg_namespace n on n.oid = c.relnamespace
342
+ join pg_roles r on r.oid = c.relowner
343
+ where r.rolname = current_user
344
+ and c.relkind in ('r', 'p', 'S', 'v', 'm', 'f')
345
+ and n.nspname <> 'information_schema'
346
+ and n.nspname !~ '^pg_'
347
+ order by n.nspname, c.relname
348
+ `)
349
+ ).map((row) => row.name);
350
+ const tables = resultRows(
351
+ await tx.execute(sql`
352
+ select
353
+ c.relname::text as name,
354
+ pg_get_userbyid(c.relowner)::text as owner,
355
+ c.relrowsecurity as rls_enabled,
356
+ c.relforcerowsecurity as rls_forced,
357
+ row_security_active(c.oid) as rls_active,
358
+ (select count(*)::int from pg_policy policy where policy.polrelid = c.oid) as policy_count,
359
+ has_table_privilege(current_user, c.oid, 'SELECT') as can_select,
360
+ has_table_privilege(current_user, c.oid, 'INSERT') as can_insert,
361
+ has_table_privilege(current_user, c.oid, 'UPDATE') as can_update,
362
+ has_table_privilege(current_user, c.oid, 'DELETE') as can_delete,
363
+ has_table_privilege(current_user, c.oid, 'TRUNCATE') as can_truncate,
364
+ has_table_privilege(current_user, c.oid, 'REFERENCES') as can_references,
365
+ has_table_privilege(current_user, c.oid, 'TRIGGER') as can_trigger
366
+ from pg_class c
367
+ join pg_namespace n on n.oid = c.relnamespace
368
+ where n.nspname = ${targetSchema}
369
+ and c.relkind in ('r', 'p')
370
+ order by c.relname
371
+ `)
372
+ ).map((row) => ({
373
+ name: row.name,
374
+ owner: row.owner,
375
+ rlsEnabled: row.rls_enabled,
376
+ rlsForced: row.rls_forced,
377
+ rlsActive: row.rls_active,
378
+ policyCount: row.policy_count,
379
+ select: row.can_select,
380
+ insert: row.can_insert,
381
+ update: row.can_update,
382
+ delete: row.can_delete,
383
+ truncate: row.can_truncate,
384
+ references: row.can_references,
385
+ trigger: row.can_trigger
386
+ }));
387
+ const privateRoutines = resultRows(
388
+ await tx.execute(sql`
389
+ select
390
+ (p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')')::text as name,
391
+ pg_get_userbyid(p.proowner)::text as owner,
392
+ has_function_privilege(current_user, p.oid, 'EXECUTE') as can_execute
393
+ from pg_proc p
394
+ join pg_namespace n on n.oid = p.pronamespace
395
+ where n.nspname = 'opengeni_private'
396
+ and p.prokind in ('f', 'p')
397
+ order by p.proname, pg_get_function_identity_arguments(p.oid)
398
+ `)
399
+ ).map((row) => ({ name: row.name, owner: row.owner, execute: row.can_execute }));
400
+ return {
401
+ identity: mappedIdentity,
402
+ memberships,
403
+ schemas,
404
+ ownedSchemas,
405
+ ownedRelations,
406
+ tables,
407
+ privateRoutines
408
+ };
409
+ },
410
+ { isolationLevel: "repeatable read", accessMode: "read only" }
411
+ );
412
+ }
413
+ function evaluateRuntimeDatabasePosture(posture, options) {
414
+ const violations = [];
415
+ const identity = posture.identity;
416
+ if (!identity.currentUser || !identity.sessionUser) {
417
+ violations.push("database identity is empty");
418
+ }
419
+ if (identity.currentUser !== identity.sessionUser) {
420
+ violations.push(
421
+ `current_user ${identity.currentUser} does not match session_user ${identity.sessionUser}`
422
+ );
423
+ }
424
+ if (!identity.canConnectDatabase) {
425
+ violations.push("runtime role lacks CONNECT on the current database");
426
+ }
427
+ if (options.rlsStrategy === "scoped") {
428
+ return violations;
429
+ }
430
+ const expectedRole = options.expectedRole?.trim() || "opengeni_app";
431
+ const targetSchema = options.targetSchema?.trim() || "public";
432
+ const protectedTables = new Set(options.protectedTables ?? FORCE_RLS_TABLES);
433
+ const tablePrivileges = options.tablePrivileges ?? RUNTIME_TABLE_PRIVILEGES;
434
+ const directRuntimeTables = new Set(Object.keys(tablePrivileges));
435
+ const protectedNoDirectDmlTables = new Set(
436
+ options.protectedNoDirectDmlTables ?? (options.protectedTables ? [] : PROTECTED_NO_DIRECT_DML_TABLES)
437
+ );
438
+ if (identity.currentUser !== expectedRole || identity.sessionUser !== expectedRole) {
439
+ violations.push(
440
+ `runtime identity must be ${expectedRole} (current_user=${identity.currentUser}, session_user=${identity.sessionUser})`
441
+ );
442
+ }
443
+ if (!identity.canLogin) violations.push("runtime role is not LOGIN");
444
+ if (identity.superuser) violations.push("runtime role is SUPERUSER");
445
+ if (identity.bypassRls) violations.push("runtime role has BYPASSRLS");
446
+ if (identity.createRole) violations.push("runtime role has CREATEROLE");
447
+ if (identity.createDatabase) violations.push("runtime role has CREATEDB");
448
+ if (identity.replication) violations.push("runtime role has REPLICATION");
449
+ if (identity.inherit) violations.push("runtime role must be NOINHERIT");
450
+ if (identity.databaseOwner === expectedRole) violations.push("runtime role owns the database");
451
+ if (identity.canCreateInDatabase) {
452
+ violations.push("runtime role has CREATE on the current database");
453
+ }
454
+ if (identity.rowSecurity.toLowerCase() !== "on") {
455
+ violations.push(`row_security is ${identity.rowSecurity}, expected on`);
456
+ }
457
+ if (posture.memberships.length > 0) {
458
+ violations.push(`runtime role has memberships: ${sorted(posture.memberships).join(", ")}`);
459
+ }
460
+ if (posture.ownedSchemas.length > 0) {
461
+ violations.push(`runtime role owns schemas: ${sorted(posture.ownedSchemas).join(", ")}`);
462
+ }
463
+ if (posture.ownedRelations.length > 0) {
464
+ violations.push(`runtime role owns relations: ${sorted(posture.ownedRelations).join(", ")}`);
465
+ }
466
+ for (const schemaName of /* @__PURE__ */ new Set([targetSchema, "opengeni_private"])) {
467
+ const schema = posture.schemas.find((candidate) => candidate.name === schemaName);
468
+ if (!schema) {
469
+ violations.push(`required schema ${schemaName} is missing`);
470
+ continue;
471
+ }
472
+ if (schema.owner === expectedRole) {
473
+ violations.push(`runtime role owns schema ${schemaName}`);
474
+ }
475
+ if (!schema.usage) violations.push(`runtime role lacks USAGE on schema ${schemaName}`);
476
+ if (schema.create) violations.push(`runtime role has CREATE on schema ${schemaName}`);
477
+ }
478
+ const tableByName = new Map(posture.tables.map((table) => [table.name, table]));
479
+ const actualRlsTables = new Set(
480
+ posture.tables.filter((table) => table.rlsEnabled).map((table) => table.name)
481
+ );
482
+ const classifiedProtectedTables = /* @__PURE__ */ new Set([
483
+ ...directRuntimeTables,
484
+ ...protectedNoDirectDmlTables
485
+ ]);
486
+ const unclassifiedProtectedTables = difference(protectedTables, classifiedProtectedTables);
487
+ if (unclassifiedProtectedTables.length > 0) {
488
+ violations.push(
489
+ `protected tables lack an explicit privilege class: ${unclassifiedProtectedTables.join(", ")}`
490
+ );
491
+ }
492
+ const protectedNoDirectDmlOverlap = difference(
493
+ protectedNoDirectDmlTables,
494
+ new Set([...protectedNoDirectDmlTables].filter((table) => !directRuntimeTables.has(table)))
495
+ );
496
+ if (protectedNoDirectDmlOverlap.length > 0) {
497
+ violations.push(
498
+ `protected no-direct-DML tables also declare runtime privileges: ${protectedNoDirectDmlOverlap.join(", ")}`
499
+ );
500
+ }
501
+ const nonProtectedNoDirectDmlTables = difference(protectedNoDirectDmlTables, protectedTables);
502
+ if (nonProtectedNoDirectDmlTables.length > 0) {
503
+ violations.push(
504
+ `no-direct-DML tables are absent from the protected contract: ${nonProtectedNoDirectDmlTables.join(", ")}`
505
+ );
506
+ }
507
+ const catalogTables = new Set(tableByName.keys());
508
+ const missingRuntimeTables = difference(directRuntimeTables, catalogTables);
509
+ if (missingRuntimeTables.length > 0) {
510
+ violations.push(`runtime privilege tables are missing: ${missingRuntimeTables.join(", ")}`);
511
+ }
512
+ const missingTables = difference(protectedTables, catalogTables);
513
+ if (missingTables.length > 0) {
514
+ violations.push(`protected tables are missing: ${missingTables.join(", ")}`);
515
+ }
516
+ const undeclaredRlsTables = difference(actualRlsTables, protectedTables);
517
+ if (undeclaredRlsTables.length > 0) {
518
+ violations.push(
519
+ `RLS tables are absent from the declared contract: ${undeclaredRlsTables.join(", ")}`
520
+ );
521
+ }
522
+ for (const table of posture.tables) {
523
+ const privileges = [
524
+ ["SELECT", table.select],
525
+ ["INSERT", table.insert],
526
+ ["UPDATE", table.update],
527
+ ["DELETE", table.delete],
528
+ ["TRUNCATE", table.truncate],
529
+ ["REFERENCES", table.references],
530
+ ["TRIGGER", table.trigger]
531
+ ];
532
+ const expectedPrivileges = new Set(tablePrivileges[table.name] ?? []);
533
+ if (table.owner === expectedRole) {
534
+ violations.push(`runtime role owns table ${table.name}`);
535
+ }
536
+ const missingPrivileges = privileges.filter(([privilege, granted]) => expectedPrivileges.has(privilege) && !granted).map(([privilege]) => privilege);
537
+ if (missingPrivileges.length > 0) {
538
+ violations.push(
539
+ `table ${table.name} lacks required runtime privileges: ${missingPrivileges.join(", ")}`
540
+ );
541
+ }
542
+ const excessPrivileges = privileges.filter(([privilege, granted]) => !expectedPrivileges.has(privilege) && granted).map(([privilege]) => privilege);
543
+ if (excessPrivileges.length > 0) {
544
+ violations.push(
545
+ `table ${table.name} grants excess runtime privileges: ${excessPrivileges.join(", ")}`
546
+ );
547
+ }
548
+ }
549
+ for (const tableName of protectedTables) {
550
+ const table = tableByName.get(tableName);
551
+ if (!table) continue;
552
+ if (!table.rlsEnabled) violations.push(`table ${tableName} does not ENABLE RLS`);
553
+ if (!table.rlsForced) violations.push(`table ${tableName} does not FORCE RLS`);
554
+ if (!table.rlsActive) violations.push(`table ${tableName} has inactive RLS for runtime role`);
555
+ if (table.policyCount < 1) violations.push(`table ${tableName} has no RLS policy`);
556
+ }
557
+ if (posture.privateRoutines.length === 0) {
558
+ violations.push("opengeni_private has no helper routines");
559
+ }
560
+ for (const routine of posture.privateRoutines) {
561
+ if (routine.owner === expectedRole) {
562
+ violations.push(`runtime role owns private routine ${routine.name}`);
563
+ }
564
+ if (!routine.execute) {
565
+ violations.push(`runtime role lacks EXECUTE on private routine ${routine.name}`);
566
+ }
567
+ }
568
+ return violations;
569
+ }
570
+ async function assertRuntimeDatabasePosture(db, options) {
571
+ const posture = await inspectRuntimeDatabasePosture(db, options);
572
+ const violations = evaluateRuntimeDatabasePosture(posture, options);
573
+ if (violations.length > 0) {
574
+ throw new RuntimeDatabasePostureError(violations);
575
+ }
576
+ return posture;
577
+ }
578
+ function runtimeDatabaseReadyCheck(db, options) {
579
+ return async () => {
580
+ await assertRuntimeDatabasePosture(db, options);
581
+ };
582
+ }
583
+
584
+ // src/provision-roles.ts
585
+ async function provisionRoles(adminConnection, options = {}) {
586
+ const schema = validateIdentifier("targetSchema", options.targetSchema ?? "public");
587
+ const rlsStrategy = options.rlsStrategy ?? "force";
588
+ const appRole = validateIdentifier(
589
+ "appRole",
590
+ options.appRole ?? (process.env.OPENGENI_APP_DATABASE_USER?.trim() || "opengeni_app")
591
+ );
592
+ const appPassword = options.appPassword ?? process.env.OPENGENI_APP_DATABASE_PASSWORD;
593
+ const hostExportRole = validateIdentifier(
594
+ "hostExportRole",
595
+ options.hostExportRole ?? (process.env.OPENGENI_HOST_EXPORT_DATABASE_USER?.trim() || "opengeni_host_exporter")
596
+ );
597
+ const hostExportPassword = options.hostExportPassword ?? process.env.OPENGENI_HOST_EXPORT_DATABASE_PASSWORD;
598
+ const temporalRole = validateIdentifier(
599
+ "temporalRole",
600
+ options.temporalRole ?? (process.env.OPENGENI_TEMPORAL_DATABASE_USER?.trim() || "opengeni_temporal")
601
+ );
602
+ const temporalPassword = options.temporalPassword ?? process.env.OPENGENI_TEMPORAL_DATABASE_PASSWORD;
603
+ const temporalDatabases = (options.temporalDatabases ?? commaSeparated(process.env.OPENGENI_TEMPORAL_DATABASES ?? "temporal,temporal_visibility")).map((name) => validateIdentifier("temporalDatabases", name));
604
+ const sql2 = postgres(adminConnection, { max: 1 });
605
+ try {
606
+ let provisionedAppRole = null;
607
+ if (rlsStrategy === "force") {
608
+ if (!appPassword) {
609
+ throw new Error(
610
+ "OPENGENI_APP_DATABASE_PASSWORD (or appPassword) is required for rlsStrategy 'force'"
611
+ );
612
+ }
613
+ await assertAppRoleSafeToNormalize(sql2, appRole);
614
+ await ensureRestrictedAppLoginRole(sql2, appRole, appPassword);
615
+ provisionedAppRole = appRole;
616
+ }
617
+ if (temporalPassword) {
618
+ await ensureLoginRole(sql2, temporalRole, temporalPassword);
619
+ for (const database of temporalDatabases) {
620
+ await ensureDatabase(sql2, database, temporalRole);
621
+ await grantTemporalRoleInDatabase(adminConnection, database, temporalRole);
622
+ }
623
+ }
624
+ if (hostExportPassword) {
625
+ await ensureLoginRole(sql2, hostExportRole, hostExportPassword);
626
+ await grantHostExportRoleIfSchemaExists(sql2, hostExportRole);
627
+ }
628
+ if (rlsStrategy === "force") {
629
+ await grantAppRoleIfSchemaExists(sql2, appRole, schema);
630
+ }
631
+ return {
632
+ appRole: provisionedAppRole,
633
+ hostExportRole: hostExportPassword ? hostExportRole : null,
634
+ temporalRole: temporalPassword ? temporalRole : null,
635
+ temporalDatabases: temporalPassword ? temporalDatabases : [],
636
+ schema,
637
+ rlsStrategy
638
+ };
639
+ } finally {
640
+ await sql2.end();
641
+ }
642
+ }
643
+ async function grantHostExportRoleIfSchemaExists(sql2, role) {
644
+ await sql2.unsafe(`
645
+ DO $$
646
+ BEGIN
647
+ IF EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = 'opengeni_host_export') THEN
648
+ EXECUTE format('GRANT USAGE ON SCHEMA opengeni_host_export TO %I', ${literal(role)});
649
+ EXECUTE format('GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA opengeni_host_export TO %I', ${literal(role)});
650
+ EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA opengeni_host_export GRANT EXECUTE ON FUNCTIONS TO %I', ${literal(role)});
651
+ END IF;
652
+ END $$;
653
+ `);
654
+ }
655
+ async function ensureLoginRole(sql2, role, password) {
656
+ await sql2.unsafe(`
657
+ DO $$
658
+ BEGIN
659
+ IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${literal(role)}) THEN
660
+ EXECUTE format('CREATE ROLE %I LOGIN PASSWORD %L', ${literal(role)}, ${literal(password)});
661
+ ELSE
662
+ EXECUTE format('ALTER ROLE %I LOGIN PASSWORD %L', ${literal(role)}, ${literal(password)});
663
+ END IF;
664
+ END $$;
665
+ `);
666
+ }
667
+ async function ensureRestrictedAppLoginRole(sql2, role, password) {
668
+ await sql2.unsafe(`
669
+ DO $$
670
+ BEGIN
671
+ IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${literal(role)}) THEN
672
+ EXECUTE format(
673
+ 'CREATE ROLE %I WITH LOGIN NOSUPERUSER NOBYPASSRLS NOCREATEROLE NOCREATEDB NOREPLICATION NOINHERIT PASSWORD %L',
674
+ ${literal(role)},
675
+ ${literal(password)}
676
+ );
677
+ ELSE
678
+ EXECUTE format(
679
+ 'ALTER ROLE %I WITH LOGIN NOSUPERUSER NOBYPASSRLS NOCREATEROLE NOCREATEDB NOREPLICATION NOINHERIT PASSWORD %L',
680
+ ${literal(role)},
681
+ ${literal(password)}
682
+ );
683
+ END IF;
684
+ END $$;
685
+ `);
686
+ }
687
+ async function assertAppRoleSafeToNormalize(sql2, role) {
688
+ const exists = await sql2`
689
+ select exists(select 1 from pg_roles where rolname = ${role}) as exists
690
+ `;
691
+ if (!exists[0]?.exists) {
692
+ return;
693
+ }
694
+ const memberships = await sql2`
695
+ select ('inherits:' || parent.rolname)::text as relationship
696
+ from pg_auth_members membership
697
+ join pg_roles member on member.oid = membership.member
698
+ join pg_roles parent on parent.oid = membership.roleid
699
+ where member.rolname = ${role}
700
+ union all
701
+ select ('member:' || member.rolname)::text as relationship
702
+ from pg_auth_members membership
703
+ join pg_roles member on member.oid = membership.member
704
+ join pg_roles parent on parent.oid = membership.roleid
705
+ where parent.rolname = ${role}
706
+ order by relationship
707
+ `;
708
+ if (memberships.length > 0) {
709
+ throw new Error(
710
+ `Refusing to normalize app role ${role}: remove role relationships first (${memberships.map((row) => row.relationship).join(", ")})`
711
+ );
712
+ }
713
+ const ownedObjects = await sql2`
714
+ select ('database:' || d.datname)::text as object_name
715
+ from pg_database d
716
+ join pg_roles owner on owner.oid = d.datdba
717
+ where owner.rolname = ${role}
718
+ union all
719
+ select ('schema:' || n.nspname)::text as object_name
720
+ from pg_namespace n
721
+ join pg_roles owner on owner.oid = n.nspowner
722
+ where owner.rolname = ${role}
723
+ and n.nspname <> 'information_schema'
724
+ and n.nspname !~ '^pg_'
725
+ union all
726
+ select ('relation:' || n.nspname || '.' || c.relname)::text as object_name
727
+ from pg_class c
728
+ join pg_namespace n on n.oid = c.relnamespace
729
+ join pg_roles owner on owner.oid = c.relowner
730
+ where owner.rolname = ${role}
731
+ and n.nspname <> 'information_schema'
732
+ and n.nspname !~ '^pg_'
733
+ union all
734
+ select (
735
+ 'routine:' || n.nspname || '.' || p.proname || '(' ||
736
+ pg_get_function_identity_arguments(p.oid) || ')'
737
+ )::text as object_name
738
+ from pg_proc p
739
+ join pg_namespace n on n.oid = p.pronamespace
740
+ join pg_roles owner on owner.oid = p.proowner
741
+ where owner.rolname = ${role}
742
+ and n.nspname <> 'information_schema'
743
+ and n.nspname !~ '^pg_'
744
+ order by object_name
745
+ `;
746
+ if (ownedObjects.length > 0) {
747
+ throw new Error(
748
+ `Refusing to normalize app role ${role}: transfer owned objects first (${ownedObjects.map((row) => row.object_name).join(", ")})`
749
+ );
750
+ }
751
+ }
752
+ async function ensureDatabase(sql2, database, owner) {
753
+ const existing = await sql2`
754
+ select exists(select 1 from pg_database where datname = ${database}) as exists
755
+ `;
756
+ if (!existing[0]?.exists) {
757
+ await sql2.unsafe(`CREATE DATABASE ${identifier(database)} OWNER ${identifier(owner)}`);
758
+ }
759
+ await sql2.unsafe(
760
+ `GRANT ALL PRIVILEGES ON DATABASE ${identifier(database)} TO ${identifier(owner)}`
761
+ );
762
+ }
763
+ async function grantTemporalRoleInDatabase(adminConnection, database, role) {
764
+ const databaseUrl = databaseUrlFor(adminConnection, database);
765
+ const databaseSql = postgres(databaseUrl, { max: 1 });
766
+ try {
767
+ await databaseSql.unsafe(`GRANT USAGE, CREATE ON SCHEMA public TO ${identifier(role)}`);
768
+ } finally {
769
+ await databaseSql.end();
770
+ }
771
+ }
772
+ async function grantAppRoleIfSchemaExists(sql2, role, schema) {
773
+ const runtimeFullDmlTables = `ARRAY[${RUNTIME_FULL_DML_TABLES.map(literal).join(", ")}]`;
774
+ const runtimeReadOnlyTables = `ARRAY[${RUNTIME_READ_ONLY_TABLES.map(literal).join(", ")}]`;
775
+ const runtimeReadInsertTables = `ARRAY[${RUNTIME_READ_INSERT_TABLES.map(literal).join(", ")}]`;
776
+ await sql2.unsafe(`
777
+ DO $$
778
+ DECLARE
779
+ owner_role text := current_user;
780
+ runtime_table text;
781
+ BEGIN
782
+ EXECUTE format('REVOKE CREATE ON DATABASE %I FROM %I', current_database(), ${literal(role)});
783
+ IF EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = ${literal(schema)}) THEN
784
+ EXECUTE format('GRANT USAGE ON SCHEMA %I TO %I', ${literal(schema)}, ${literal(role)});
785
+ EXECUTE format('REVOKE CREATE ON SCHEMA %I FROM %I', ${literal(schema)}, ${literal(role)});
786
+ EXECUTE format('REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA %I FROM %I', ${literal(schema)}, ${literal(role)});
787
+ FOREACH runtime_table IN ARRAY ${runtimeFullDmlTables} LOOP
788
+ IF to_regclass(format('%I.%I', ${literal(schema)}, runtime_table)) IS NOT NULL THEN
789
+ EXECUTE format(
790
+ 'GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE %I.%I TO %I',
791
+ ${literal(schema)},
792
+ runtime_table,
793
+ ${literal(role)}
794
+ );
795
+ END IF;
796
+ END LOOP;
797
+ FOREACH runtime_table IN ARRAY ${runtimeReadOnlyTables} LOOP
798
+ IF to_regclass(format('%I.%I', ${literal(schema)}, runtime_table)) IS NOT NULL THEN
799
+ EXECUTE format(
800
+ 'GRANT SELECT ON TABLE %I.%I TO %I',
801
+ ${literal(schema)},
802
+ runtime_table,
803
+ ${literal(role)}
804
+ );
805
+ END IF;
806
+ END LOOP;
807
+ FOREACH runtime_table IN ARRAY ${runtimeReadInsertTables} LOOP
808
+ IF to_regclass(format('%I.%I', ${literal(schema)}, runtime_table)) IS NOT NULL THEN
809
+ EXECUTE format(
810
+ 'GRANT SELECT, INSERT ON TABLE %I.%I TO %I',
811
+ ${literal(schema)},
812
+ runtime_table,
813
+ ${literal(role)}
814
+ );
815
+ END IF;
816
+ END LOOP;
817
+ -- Migration 0110 creates this target-schema-local SECURITY DEFINER
818
+ -- capability before opengeni_app may exist. Re-converge its exact EXECUTE
819
+ -- grant here so the supported migrate-then-provision order is equivalent to
820
+ -- provisioning the role before that migration.
821
+ IF to_regprocedure(
822
+ format('%I.lock_nested_agent_depth_configuration()', ${literal(schema)})
823
+ ) IS NOT NULL THEN
824
+ EXECUTE format(
825
+ 'GRANT EXECUTE ON FUNCTION %I.lock_nested_agent_depth_configuration() TO %I',
826
+ ${literal(schema)},
827
+ ${literal(role)}
828
+ );
829
+ END IF;
830
+ EXECUTE format('GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA %I TO %I', ${literal(schema)}, ${literal(role)});
831
+ EXECUTE format(
832
+ 'ALTER DEFAULT PRIVILEGES FOR ROLE %I IN SCHEMA %I REVOKE ALL PRIVILEGES ON TABLES FROM %I',
833
+ owner_role,
834
+ ${literal(schema)},
835
+ ${literal(role)}
836
+ );
837
+ EXECUTE format(
838
+ 'ALTER DEFAULT PRIVILEGES FOR ROLE %I IN SCHEMA %I GRANT USAGE, SELECT ON SEQUENCES TO %I',
839
+ owner_role,
840
+ ${literal(schema)},
841
+ ${literal(role)}
842
+ );
843
+ END IF;
844
+ IF EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = 'opengeni_private') THEN
845
+ EXECUTE format('GRANT USAGE ON SCHEMA opengeni_private TO %I', ${literal(role)});
846
+ EXECUTE format('REVOKE CREATE ON SCHEMA opengeni_private FROM %I', ${literal(role)});
847
+ EXECUTE format('GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA opengeni_private TO %I', ${literal(role)});
848
+ EXECUTE format(
849
+ 'ALTER DEFAULT PRIVILEGES FOR ROLE %I IN SCHEMA opengeni_private GRANT EXECUTE ON FUNCTIONS TO %I',
850
+ owner_role,
851
+ ${literal(role)}
852
+ );
853
+ END IF;
854
+ END $$;
855
+ `);
856
+ }
857
+ function commaSeparated(value) {
858
+ return value.split(",").map((item) => item.trim()).filter(Boolean);
859
+ }
860
+ function validateIdentifier(name, value) {
861
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) {
862
+ throw new Error(`${name} contains an invalid Postgres identifier: ${value}`);
863
+ }
864
+ return value;
865
+ }
866
+ function identifier(value) {
867
+ return `"${value.replace(/"/g, '""')}"`;
868
+ }
869
+ function literal(value) {
870
+ return `'${value.replace(/'/g, "''")}'`;
871
+ }
872
+ function databaseUrlFor(value, database) {
873
+ const url = new URL(value);
874
+ url.pathname = `/${database}`;
875
+ return url.toString();
876
+ }
877
+ if (import.meta.main) {
878
+ const adminUrl = process.env.OPENGENI_MIGRATIONS_DATABASE_URL ?? process.env.OPENGENI_DATABASE_ADMIN_URL ?? process.env.OPENGENI_DATABASE_URL;
879
+ if (!adminUrl) {
880
+ throw new Error(
881
+ "OPENGENI_MIGRATIONS_DATABASE_URL, OPENGENI_DATABASE_ADMIN_URL, or OPENGENI_DATABASE_URL is required"
882
+ );
883
+ }
884
+ const result = await provisionRoles(adminUrl, {
885
+ ...process.env.OPENGENI_DB_SCHEMA?.trim() ? { targetSchema: process.env.OPENGENI_DB_SCHEMA.trim() } : {}
886
+ });
887
+ console.log(JSON.stringify(result, null, 2));
888
+ }
889
+
890
+ export {
891
+ FORCE_RLS_TABLES,
892
+ NON_RLS_RUNTIME_TABLES,
893
+ RUNTIME_FULL_DML_TABLES,
894
+ RUNTIME_READ_ONLY_TABLES,
895
+ RUNTIME_READ_INSERT_TABLES,
896
+ PROTECTED_NO_DIRECT_DML_TABLES,
897
+ RUNTIME_TABLE_PRIVILEGES,
898
+ RUNTIME_DML_TABLES,
899
+ RuntimeDatabasePostureError,
900
+ inspectRuntimeDatabasePosture,
901
+ evaluateRuntimeDatabasePosture,
902
+ assertRuntimeDatabasePosture,
903
+ runtimeDatabaseReadyCheck,
904
+ provisionRoles
905
+ };
906
+ //# sourceMappingURL=chunk-ELMUCYZF.js.map