@opengeni/db 0.12.0 → 0.12.6

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