@opengeni/db 0.28.9 → 0.36.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 (225) hide show
  1. package/dist/attached-browser-devices.d.ts +42 -0
  2. package/dist/attempt-tool-catalogs.d.ts +16 -0
  3. package/dist/browser-auth.d.ts +299 -0
  4. package/dist/browser-downloads.d.ts +51 -0
  5. package/dist/browser-identities.d.ts +137 -0
  6. package/dist/browser-sessions.d.ts +354 -0
  7. package/dist/browser-state-artifacts.d.ts +91 -0
  8. package/dist/canonical-human-identities.d.ts +48 -0
  9. package/dist/canonical-human-identities.js +28 -0
  10. package/dist/canonical-human-identities.js.map +1 -0
  11. package/dist/capability-components.d.ts +37 -0
  12. package/dist/capability-integrations.d.ts +194 -0
  13. package/dist/chunk-5KTIEDX7.js +13200 -0
  14. package/dist/chunk-5KTIEDX7.js.map +1 -0
  15. package/dist/chunk-CQZ4QSP5.js +995 -0
  16. package/dist/chunk-CQZ4QSP5.js.map +1 -0
  17. package/dist/chunk-F32YT7MP.js +117 -0
  18. package/dist/chunk-F32YT7MP.js.map +1 -0
  19. package/dist/chunk-JC5QPLUM.js +666 -0
  20. package/dist/chunk-JC5QPLUM.js.map +1 -0
  21. package/dist/chunk-P3RE4D2B.js +3535 -0
  22. package/dist/chunk-P3RE4D2B.js.map +1 -0
  23. package/dist/chunk-TAUTWOS5.js +259 -0
  24. package/dist/chunk-TAUTWOS5.js.map +1 -0
  25. package/dist/chunk-VKLB2ZGI.js +2389 -0
  26. package/dist/chunk-VKLB2ZGI.js.map +1 -0
  27. package/dist/codemode-operations.d.ts +117 -0
  28. package/dist/codex-token-resolver.d.ts +2 -2
  29. package/dist/company-profile-schema.d.ts +798 -0
  30. package/dist/company-profile.d.ts +268 -0
  31. package/dist/computer-sessions.d.ts +109 -0
  32. package/dist/connection-token-resolver.d.ts +9 -4
  33. package/dist/database.d.ts +57 -3
  34. package/dist/editable-artifact-durable-export.d.ts +153 -0
  35. package/dist/editable-artifact-durable-export.js +788 -0
  36. package/dist/editable-artifact-durable-export.js.map +1 -0
  37. package/dist/editable-artifact-materialization.d.ts +123 -0
  38. package/dist/editable-artifacts-schema.d.ts +4152 -0
  39. package/dist/editable-artifacts.d.ts +610 -0
  40. package/dist/editable-artifacts.js +26 -0
  41. package/dist/editable-artifacts.js.map +1 -0
  42. package/dist/generated-images.d.ts +139 -0
  43. package/dist/index.d.ts +1122 -126
  44. package/dist/index.js +42329 -18407
  45. package/dist/index.js.map +1 -1
  46. package/dist/insights.d.ts +73 -10
  47. package/dist/integration-bindings.d.ts +70 -0
  48. package/dist/integration-facets.d.ts +99 -0
  49. package/dist/interaction-revisions.d.ts +14 -0
  50. package/dist/interaction-schema.d.ts +6036 -0
  51. package/dist/knowledge-source-sync-schema.d.ts +1679 -0
  52. package/dist/knowledge-source-sync.d.ts +274 -0
  53. package/dist/memory-governance.d.ts +2 -2
  54. package/dist/memory-slack-delivery.d.ts +101 -0
  55. package/dist/new-session-drafts.d.ts +2 -2
  56. package/dist/pack-components.d.ts +76 -0
  57. package/dist/pack-installations.d.ts +86 -0
  58. package/dist/persistence-errors.d.ts +3 -3
  59. package/dist/plugin-packages.d.ts +126 -0
  60. package/dist/preference-registry.d.ts +1 -1
  61. package/dist/provision-roles.d.ts +9 -1
  62. package/dist/provision-roles.js +1 -1
  63. package/dist/runtime-posture.d.ts +19 -6
  64. package/dist/schema.d.ts +22654 -9359
  65. package/dist/schema.js +209 -3
  66. package/dist/scoped-knowledge.d.ts +97 -1
  67. package/dist/session-control.d.ts +33 -7
  68. package/dist/session-queue-commands.d.ts +19 -11
  69. package/dist/session-realtime-context.d.ts +2 -2
  70. package/dist/session-realtime-ledger.d.ts +4 -4
  71. package/dist/session-realtime-mirror.d.ts +2 -2
  72. package/dist/session-realtime-state.d.ts +1 -1
  73. package/dist/session-realtime-terminal.d.ts +1 -1
  74. package/dist/session-realtime.d.ts +7 -7
  75. package/dist/session-tenancy.d.ts +44 -0
  76. package/dist/session-tenancy.js +16 -0
  77. package/dist/session-tenancy.js.map +1 -0
  78. package/dist/session-tool-call-settlement.d.ts +1 -1
  79. package/dist/slack-task-policy-schema.d.ts +847 -0
  80. package/dist/slack-task-policy.d.ts +65 -0
  81. package/dist/slack-user-link-access.d.ts +54 -0
  82. package/dist/task-notes-schema.d.ts +924 -0
  83. package/dist/task-notes.d.ts +85 -0
  84. package/dist/transcription-recordings.d.ts +2 -2
  85. package/dist/turn-initiator.d.ts +2 -2
  86. package/dist/video-generation.d.ts +225 -0
  87. package/dist/video-generation.js +68 -0
  88. package/dist/video-generation.js.map +1 -0
  89. package/dist/workspace-artifacts.d.ts +1 -1
  90. package/dist/workspace-instruction-policies.d.ts +1 -1
  91. package/dist/workspace-learning-policy-schema.d.ts +932 -0
  92. package/dist/workspace-learning-policy.d.ts +161 -0
  93. package/dist/xai-subscription.d.ts +326 -0
  94. package/drizzle/0183_model_call_provider_cost_estimates.sql +39 -0
  95. package/drizzle/0184_sandbox_drain_teardown_fence.sql +682 -0
  96. package/drizzle/0185_temporal_schedule_cleanup_outbox.sql +168 -0
  97. package/drizzle/0186_sandbox_capture_provider_contract.sql +400 -0
  98. package/drizzle/0187_generated_image_artifacts.sql +173 -0
  99. package/drizzle/0188_image_generation_retention_failure.sql +25 -0
  100. package/drizzle/0189_retained_session_image_formats.sql +13 -0
  101. package/drizzle/0190_timeline_annotations.sql +31 -0
  102. package/drizzle/0191_editable_artifact_engine.sql +3853 -0
  103. package/drizzle/0192_editable_artifact_live_tickets.sql +338 -0
  104. package/drizzle/0193_editable_artifact_authorization.sql +190 -0
  105. package/drizzle/0194_editable_artifact_durable_exports.sql +160 -0
  106. package/drizzle/0195_editable_artifact_import_authorization.sql +203 -0
  107. package/drizzle/0196_rig_provider_images.sql +152 -0
  108. package/drizzle/0197_knowledge_source_sync_schedules.sql +523 -0
  109. package/drizzle/0198_memory_slack_publication_delivery.sql +393 -0
  110. package/drizzle/0199_workspace_learning_policy.sql +980 -0
  111. package/drizzle/0201_company_profile_authority.sql +849 -0
  112. package/drizzle/0202_document_index_checkpoints.sql +85 -0
  113. package/drizzle/0203_durable_video_generation.sql +353 -0
  114. package/drizzle/0204_video_generation_funding.sql +44 -0
  115. package/drizzle/0205_attempt_tool_catalogs.sql +230 -0
  116. package/drizzle/0206_browser_sessions.sql +646 -0
  117. package/drizzle/0207_browser_identities.sql +379 -0
  118. package/drizzle/0208_attached_browser_devices.sql +165 -0
  119. package/drizzle/0209_computer_sessions.sql +575 -0
  120. package/drizzle/0210_browser_auth_network_interventions.sql +441 -0
  121. package/drizzle/0211_editable_artifact_session_links.sql +58 -0
  122. package/drizzle/0212_browser_state_transfer_hardening.sql +560 -0
  123. package/drizzle/0212_slack_installation_bindings.sql +348 -0
  124. package/drizzle/0213_browser_interaction_authority.sql +67 -0
  125. package/drizzle/0213_slack_user_link_access_requests.sql +177 -0
  126. package/drizzle/0214_browser_download_saves.sql +34 -0
  127. package/drizzle/0214_session_activity_commit_gate.sql +262 -0
  128. package/drizzle/0215_browser_controller_host.sql +385 -0
  129. package/drizzle/0215_capabilities_platform.sql +980 -0
  130. package/drizzle/0216_browser_auth_health_evidence.sql +137 -0
  131. package/drizzle/0216_pack_component_ownership.sql +235 -0
  132. package/drizzle/0217_capability_definition_delete_authority.sql +32 -0
  133. package/drizzle/0217_external_browser_auth_operations.sql +22 -0
  134. package/drizzle/0218_organization_tenancy_foundation.sql +299 -0
  135. package/drizzle/0219_organization_tenancy_managed_human_provisioning.sql +317 -0
  136. package/drizzle/0219_site_auth_maintenance_sessions.sql +234 -0
  137. package/drizzle/0220_memory_slack_append_only_cascade.sql +38 -0
  138. package/drizzle/0220_session_channels.sql +54 -0
  139. package/drizzle/0221_sessions_channel_index.sql +5 -0
  140. package/drizzle/0222_session_visibility_authority_epochs.sql +158 -0
  141. package/drizzle/0222_sessions_channel_fk.sql +89 -0
  142. package/drizzle/0223_pending_tool_event_output.sql +55 -0
  143. package/drizzle/0223_sessions_channel_fk_validate.sql +118 -0
  144. package/drizzle/0224_slack_post_outcome_reconciliation.sql +123 -0
  145. package/drizzle/0225_session_visibility_fork_activation.sql +1363 -0
  146. package/drizzle/0226_personal_codex_authority_foundation.sql +365 -0
  147. package/drizzle/0227_slack_native_actions.sql +145 -0
  148. package/drizzle/0228_interaction_controller_data_plane.sql +14 -0
  149. package/drizzle/0228_slack_task_policy.sql +400 -0
  150. package/drizzle/0229_slack_inbox_file_fact.sql +10 -0
  151. package/drizzle/0230_user_scoped_variable_sets_rigs.sql +84 -0
  152. package/drizzle/0231_integration_definition_identity_cutover.sql +271 -0
  153. package/drizzle/0232_integration_facet_authority_cutover.sql +610 -0
  154. package/drizzle/0233_skill_and_integration_authority_cutover.sql +1162 -0
  155. package/drizzle/0234_xai_subscription_authority.sql +1139 -0
  156. package/drizzle/0235_canonical_human_login_bindings.sql +920 -0
  157. package/drizzle/0236_browser_identity_lifecycle.sql +39 -0
  158. package/drizzle/0236_session_visibility_slack_policy.sql +72 -0
  159. package/drizzle/0237_interaction_transition_reaper.sql +263 -0
  160. package/drizzle/0238_goal_persistence_policy.sql +471 -0
  161. package/drizzle/0238_supergrok_realtime_model.sql +29 -0
  162. package/drizzle/0239_supergrok_video_funding.sql +50 -0
  163. package/drizzle/0239_task_tree_notes.sql +990 -0
  164. package/package.json +26 -5
  165. package/src/attached-browser-devices.ts +371 -0
  166. package/src/attempt-tool-catalogs.ts +131 -0
  167. package/src/browser-auth.ts +4373 -0
  168. package/src/browser-downloads.ts +517 -0
  169. package/src/browser-identities.ts +1385 -0
  170. package/src/browser-sessions.ts +2294 -0
  171. package/src/browser-state-artifacts.ts +449 -0
  172. package/src/canonical-human-identities.ts +317 -0
  173. package/src/capability-components.ts +166 -0
  174. package/src/capability-integrations.ts +1571 -0
  175. package/src/codemode-operations.ts +674 -0
  176. package/src/company-profile-schema.ts +143 -0
  177. package/src/company-profile.ts +968 -0
  178. package/src/computer-sessions.ts +1130 -0
  179. package/src/connection-token-resolver.ts +270 -25
  180. package/src/database.ts +468 -24
  181. package/src/editable-artifact-durable-export.ts +1201 -0
  182. package/src/editable-artifact-materialization.ts +893 -0
  183. package/src/editable-artifacts-schema.ts +879 -0
  184. package/src/editable-artifacts.ts +5404 -0
  185. package/src/generated-images.ts +740 -0
  186. package/src/index.ts +9963 -1465
  187. package/src/insights.ts +251 -23
  188. package/src/integration-bindings.ts +455 -0
  189. package/src/integration-facets.ts +862 -0
  190. package/src/interaction-revisions.ts +70 -0
  191. package/src/interaction-schema.ts +1606 -0
  192. package/src/knowledge-source-sync-schema.ts +192 -0
  193. package/src/knowledge-source-sync.ts +1922 -0
  194. package/src/memory-slack-delivery.ts +801 -0
  195. package/src/pack-components.ts +954 -0
  196. package/src/pack-installations.ts +886 -0
  197. package/src/persistence-errors.ts +4 -7
  198. package/src/plugin-packages.ts +1186 -0
  199. package/src/provision-roles.ts +534 -1
  200. package/src/runtime-posture-cli.ts +9 -0
  201. package/src/runtime-posture.ts +721 -5
  202. package/src/schema.ts +6270 -3159
  203. package/src/scoped-knowledge-schema.ts +1 -1
  204. package/src/scoped-knowledge.ts +655 -3
  205. package/src/session-control.ts +130 -42
  206. package/src/session-queue-commands.ts +265 -15
  207. package/src/session-realtime-context.ts +2 -2
  208. package/src/session-realtime-ledger.ts +3 -3
  209. package/src/session-realtime.ts +7 -7
  210. package/src/session-tenancy.ts +188 -0
  211. package/src/session-tool-call-settlement.ts +18 -3
  212. package/src/slack-task-policy-schema.ts +130 -0
  213. package/src/slack-task-policy.ts +341 -0
  214. package/src/slack-user-link-access.ts +702 -0
  215. package/src/task-notes-schema.ts +135 -0
  216. package/src/task-notes.ts +178 -0
  217. package/src/video-generation.ts +1530 -0
  218. package/src/workspace-artifacts.ts +1 -1
  219. package/src/workspace-learning-policy-schema.ts +139 -0
  220. package/src/workspace-learning-policy.ts +595 -0
  221. package/src/xai-subscription.ts +1887 -0
  222. package/dist/chunk-P6CUHXQZ.js +0 -7248
  223. package/dist/chunk-P6CUHXQZ.js.map +0 -1
  224. package/dist/chunk-VHBFHMPC.js +0 -1219
  225. package/dist/chunk-VHBFHMPC.js.map +0 -1
@@ -0,0 +1,2389 @@
1
+ // src/provision-roles.ts
2
+ import postgres from "postgres";
3
+
4
+ // src/runtime-posture.ts
5
+ import { sql } from "drizzle-orm";
6
+
7
+ // src/role-relationships.ts
8
+ function roleRelationshipsCatalogQuery(targetRole) {
9
+ return `
10
+ with recursive target_role(oid, rolname) as (
11
+ select oid, rolname
12
+ from pg_roles
13
+ where rolname = ${targetRole}
14
+ ), inherited_roles(oid, rolname) as (
15
+ select parent.oid, parent.rolname
16
+ from pg_auth_members membership
17
+ join target_role target on target.oid = membership.member
18
+ join pg_roles parent on parent.oid = membership.roleid
19
+ union
20
+ select parent.oid, parent.rolname
21
+ from inherited_roles inherited
22
+ join pg_auth_members membership on membership.member = inherited.oid
23
+ join pg_roles parent on parent.oid = membership.roleid
24
+ ), relationships as (
25
+ select
26
+ ('inherits:' || inherited.rolname)::text as relationship,
27
+ 'inherits'::text as direction,
28
+ null::boolean as admin_option,
29
+ null::boolean as inherit_option,
30
+ null::boolean as set_option,
31
+ null::boolean as member_is_superuser,
32
+ null::boolean as member_can_create_role,
33
+ null::text as grantor_role,
34
+ null::boolean as grantor_is_superuser
35
+ from inherited_roles inherited
36
+ union all
37
+ select
38
+ ('member:' || member.rolname)::text as relationship,
39
+ 'member'::text as direction,
40
+ membership.admin_option,
41
+ case
42
+ when current_setting('server_version_num')::integer >= 160000
43
+ then (to_jsonb(membership) ->> 'inherit_option')::boolean
44
+ else null::boolean
45
+ end as inherit_option,
46
+ case
47
+ when current_setting('server_version_num')::integer >= 160000
48
+ then (to_jsonb(membership) ->> 'set_option')::boolean
49
+ else null::boolean
50
+ end as set_option,
51
+ member.rolsuper as member_is_superuser,
52
+ member.rolcreaterole as member_can_create_role,
53
+ grantor.rolname::text as grantor_role,
54
+ grantor.rolsuper as grantor_is_superuser
55
+ from pg_auth_members membership
56
+ join target_role target on target.oid = membership.roleid
57
+ join pg_roles member on member.oid = membership.member
58
+ left join pg_roles grantor on grantor.oid = membership.grantor
59
+ )
60
+ select
61
+ relationship,
62
+ direction,
63
+ current_setting('server_version_num')::integer as server_version_num,
64
+ admin_option,
65
+ inherit_option,
66
+ set_option,
67
+ member_is_superuser,
68
+ member_can_create_role,
69
+ grantor_role,
70
+ grantor_is_superuser
71
+ from relationships
72
+ order by relationship, direction, grantor_role nulls first
73
+ `;
74
+ }
75
+ function isManagementOnlyRoleRelationship(row) {
76
+ return row.direction === "member" && row.server_version_num >= 16e4 && row.admin_option === true && row.inherit_option === false && row.set_option === false && row.member_is_superuser === false && row.member_can_create_role === true && row.grantor_is_superuser === true;
77
+ }
78
+ function sortedUnique(values) {
79
+ return [...new Set(values)].sort((a, b) => a.localeCompare(b));
80
+ }
81
+ function classifyRoleRelationships(rows) {
82
+ const managementOnlyRows = rows.filter(isManagementOnlyRoleRelationship);
83
+ const unsafeRows = rows.filter((row) => !isManagementOnlyRoleRelationship(row));
84
+ return {
85
+ relationships: sortedUnique(rows.map((row) => row.relationship)),
86
+ managementOnlyRelationships: sortedUnique(managementOnlyRows.map((row) => row.relationship)),
87
+ unsafeRelationships: sortedUnique(unsafeRows.map((row) => row.relationship))
88
+ };
89
+ }
90
+
91
+ // src/runtime-posture.ts
92
+ var ARTIFACT_OUTBOX_CAPABILITY_ROUTINES = [
93
+ "claim_editable_artifact_live_outbox(text, integer, integer, name)",
94
+ "mark_editable_artifact_live_outbox_published(text, text, integer, name)",
95
+ "renew_editable_artifact_live_outbox(text, text, integer, integer, name)",
96
+ "retry_editable_artifact_live_outbox(text, text, integer, integer, text, name)",
97
+ "dead_letter_editable_artifact_live_outbox(text, text, integer, text, name)",
98
+ "release_editable_artifact_live_outbox(text, text, integer, name)"
99
+ ];
100
+ var ARTIFACT_MATERIALIZER_CAPABILITY_ROUTINES = [
101
+ "claim_editable_artifact_materializations(text, integer, integer, name)",
102
+ "renew_editable_artifact_materialization(uuid, uuid, text, text, text, integer, integer, name)",
103
+ "succeed_editable_artifact_materialization(uuid, uuid, text, text, text, integer, text, text, text, bigint, text, text, timestamp with time zone, name)",
104
+ "fail_editable_artifact_materialization(uuid, uuid, text, text, text, integer, text, name)"
105
+ ];
106
+ var ARTIFACT_LIVE_TICKET_CAPABILITY_ROUTINES = [
107
+ "put_editable_artifact_live_ticket(text, uuid, uuid, text, text, text, text, text, text, text, text, integer, text, boolean, integer, timestamp with time zone, timestamp with time zone, name)",
108
+ "consume_editable_artifact_live_ticket(text, name)",
109
+ "cleanup_expired_editable_artifact_live_tickets(integer, name)"
110
+ ];
111
+ var ARTIFACT_LIVE_TICKET_INTERNAL_ROUTINES = [
112
+ "resolve_editable_artifact_ticket_data_schema(name)"
113
+ ];
114
+ var ARTIFACT_AUTHORIZATION_CAPABILITY_ROUTINES = [
115
+ "authorize_editable_artifact_actor(uuid, uuid, text, text, text, text, text, text, integer, text, text, name)"
116
+ ];
117
+ var DEDICATED_ARTIFACT_CAPABILITY_ROUTINES = /* @__PURE__ */ new Set([
118
+ ...ARTIFACT_OUTBOX_CAPABILITY_ROUTINES,
119
+ ...ARTIFACT_MATERIALIZER_CAPABILITY_ROUTINES,
120
+ ...ARTIFACT_LIVE_TICKET_INTERNAL_ROUTINES
121
+ ]);
122
+ var KNOWLEDGE_SOURCE_SYNC_LOCK_AUTHORITY_ROUTINE = "knowledge_source_sync_lock_authority(uuid, uuid, uuid)";
123
+ var KNOWLEDGE_SOURCE_SYNC_LOCK_AUTHORITY_TABLES = [
124
+ "knowledge_sources",
125
+ "knowledge_source_objects"
126
+ ];
127
+ var MANAGED_HUMAN_PERSONAL_WORKSPACE_ROUTINE = "ensure_managed_human_personal_workspace(uuid, text, uuid)";
128
+ var MANAGED_HUMAN_PERSONAL_WORKSPACE_AUTHORITY_TABLES = [
129
+ "organization_memberships",
130
+ "organization_user_retention_policies",
131
+ "organization_user_resource_authorities",
132
+ "organization_user_resource_grants"
133
+ ];
134
+ var CANONICAL_HUMAN_IDENTITY_ROUTINES = [
135
+ "ensure_canonical_human_identity(text, text)",
136
+ "validate_canonical_human_session(text, text, boolean)",
137
+ "get_canonical_human_identity_projection(text)",
138
+ "apply_canonical_human_identity_operation(uuid, text, bigint, text, uuid, text, text, text)"
139
+ ];
140
+ var CANONICAL_HUMAN_IDENTITY_AUTHORITY_TABLES = [
141
+ "canonical_human_identities",
142
+ "canonical_human_identity_subjects",
143
+ "canonical_human_login_bindings",
144
+ "canonical_human_identity_operations"
145
+ ];
146
+ var SESSION_PRIVATE_ACTOR_VISIBLE_ROUTINE = "session_private_actor_visible(uuid, uuid, uuid, text)";
147
+ var SESSION_REFERENCE_VISIBLE_ROUTINE = "session_reference_visible(uuid, uuid, uuid)";
148
+ var TASK_NOTE_CAPABILITY_ROUTINES = [
149
+ "create_task_note_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid, text, text, integer)",
150
+ "archive_task_note_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid, uuid, integer, text)",
151
+ "list_task_notes_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, boolean, integer)"
152
+ ];
153
+ var TRANSITION_SESSION_VISIBILITY_ROUTINE = "transition_session_visibility(uuid, uuid, uuid, text, text, integer, text, text)";
154
+ var FORK_SESSION_CONTENT_ROUTINE = "fork_session_content(uuid, uuid, uuid, text, uuid, text, text, text)";
155
+ var SESSION_AUTHORITY_ROUTINES = /* @__PURE__ */ new Set([
156
+ FORK_SESSION_CONTENT_ROUTINE,
157
+ SESSION_PRIVATE_ACTOR_VISIBLE_ROUTINE,
158
+ SESSION_REFERENCE_VISIBLE_ROUTINE,
159
+ TRANSITION_SESSION_VISIBILITY_ROUTINE,
160
+ ...TASK_NOTE_CAPABILITY_ROUTINES
161
+ ]);
162
+ var XAI_CREATE_CREDENTIAL_ROUTINE = "create_xai_subscription_credential(uuid, uuid, text, text, text, text, text, text, text, timestamp with time zone)";
163
+ var XAI_DISCONNECT_CREDENTIAL_ROUTINE = "disconnect_xai_subscription_credential(uuid, uuid, text, uuid, jsonb)";
164
+ var XAI_SNAPSHOT_VALIDATOR_ROUTINE = "xai_provider_account_authority_snapshot_v1_valid(jsonb)";
165
+ var XAI_AUTHORITY_LIVE_ROUTINE = "xai_subscription_authority_live(uuid, uuid, text, uuid, text, uuid, uuid, bigint)";
166
+ var XAI_POOL_VISIBLE_ROUTINE = "xai_subscription_pool_visible(uuid, uuid, text, text, uuid)";
167
+ var XAI_RESOLVE_POOL_ROUTINE = "resolve_xai_authority_pool(uuid, uuid, text, jsonb)";
168
+ var XAI_REVALIDATE_CREDENTIAL_ROUTINE = "revalidate_xai_subscription_authority(uuid, text, uuid, jsonb)";
169
+ var XAI_AUTHORITY_TABLES = [
170
+ "organization_memberships",
171
+ "organization_user_resource_authorities",
172
+ "workspace_memberships",
173
+ "xai_subscription_credentials"
174
+ ];
175
+ var RUNTIME_TARGET_SCHEMA_CAPABILITY_ROUTINES = [
176
+ FORK_SESSION_CONTENT_ROUTINE,
177
+ XAI_AUTHORITY_LIVE_ROUTINE,
178
+ XAI_CREATE_CREDENTIAL_ROUTINE,
179
+ XAI_DISCONNECT_CREDENTIAL_ROUTINE,
180
+ KNOWLEDGE_SOURCE_SYNC_LOCK_AUTHORITY_ROUTINE,
181
+ MANAGED_HUMAN_PERSONAL_WORKSPACE_ROUTINE,
182
+ ...CANONICAL_HUMAN_IDENTITY_ROUTINES,
183
+ SESSION_PRIVATE_ACTOR_VISIBLE_ROUTINE,
184
+ SESSION_REFERENCE_VISIBLE_ROUTINE,
185
+ TRANSITION_SESSION_VISIBILITY_ROUTINE,
186
+ XAI_POOL_VISIBLE_ROUTINE,
187
+ XAI_RESOLVE_POOL_ROUTINE,
188
+ XAI_REVALIDATE_CREDENTIAL_ROUTINE,
189
+ XAI_SNAPSHOT_VALIDATOR_ROUTINE
190
+ ];
191
+ var RUNTIME_TARGET_SCHEMA_INVOKER_ROUTINES = [
192
+ SESSION_REFERENCE_VISIBLE_ROUTINE,
193
+ XAI_SNAPSHOT_VALIDATOR_ROUTINE
194
+ ];
195
+ var RUNTIME_TARGET_SCHEMA_INVOKER_ROUTINE_SET = new Set(
196
+ RUNTIME_TARGET_SCHEMA_INVOKER_ROUTINES
197
+ );
198
+ var FORCE_RLS_TABLES = [
199
+ "agent_run_states",
200
+ "api_keys",
201
+ "attached_browser_devices",
202
+ "attached_browser_inventories",
203
+ "audit_events",
204
+ "auth_runs",
205
+ "billing_customers",
206
+ "browser_identities",
207
+ "browser_revision_components",
208
+ "browser_revisions",
209
+ "browser_session_associations",
210
+ "browser_sessions",
211
+ "browser_state_artifacts",
212
+ "browser_state_uploads",
213
+ "canonical_human_identities",
214
+ "canonical_human_identity_operations",
215
+ "canonical_human_identity_subjects",
216
+ "canonical_human_login_bindings",
217
+ "capability_api_facets",
218
+ "capability_catalog_items",
219
+ "capability_component_owners",
220
+ "capability_facet_installations",
221
+ "capability_facets",
222
+ "capability_installations",
223
+ "capability_integration_facets",
224
+ "capability_mcp_facets",
225
+ "capability_operations",
226
+ "capability_plugin_installations",
227
+ "capability_plugin_versions",
228
+ "capability_plugins",
229
+ "capability_skill_facets",
230
+ "capability_skill_files",
231
+ "channels",
232
+ "codex_apps_settings",
233
+ "codex_capacity_waiters",
234
+ "codex_credential_leases",
235
+ "codex_reset_redemption_attempts",
236
+ "codex_rotation_settings",
237
+ "codex_subscription_credentials",
238
+ "company_profile_activation_events",
239
+ "company_profile_heads",
240
+ "company_profile_revisions",
241
+ "company_profile_snapshots",
242
+ "composer_drafts",
243
+ "computer_session_associations",
244
+ "computer_sessions",
245
+ "connection_disconnect_operations",
246
+ "connections",
247
+ "connector_action_policies",
248
+ "connector_action_requests",
249
+ "credit_ledger_entries",
250
+ "device_enrollment_requests",
251
+ "document_bases",
252
+ "document_chunks",
253
+ "documents",
254
+ "editable_artifact_blob_refs",
255
+ "editable_artifact_idempotency_receipts",
256
+ "editable_artifact_live_outbox",
257
+ "editable_artifact_live_tickets",
258
+ "editable_artifact_materialization_jobs",
259
+ "editable_artifact_materialization_results",
260
+ "editable_artifact_operations",
261
+ "editable_artifact_replica_leases",
262
+ "editable_artifact_scope_authorization_heads",
263
+ "editable_artifact_sequence_checkpoints",
264
+ "editable_artifact_session_links",
265
+ "editable_artifact_snapshots",
266
+ "editable_artifact_transactions",
267
+ "editable_artifact_undo_claims",
268
+ "editable_artifact_versions",
269
+ "editable_artifacts",
270
+ "enrollments",
271
+ "file_uploads",
272
+ "files",
273
+ "generated_image_artifacts",
274
+ "generated_video_artifacts",
275
+ "github_installation_repositories",
276
+ "github_installations",
277
+ "host_export_config",
278
+ "host_export_consumers",
279
+ "host_export_cursor_state",
280
+ "host_export_dead_letters",
281
+ "host_export_outbox",
282
+ "image_generation_operations",
283
+ "import_batches",
284
+ "integration_facet_binding_owners",
285
+ "integration_facet_bindings",
286
+ "integration_facet_definitions",
287
+ "integration_oauth_state_nonces",
288
+ "integration_spec_revisions",
289
+ "integration_tools",
290
+ "interaction_interventions",
291
+ "interaction_operations",
292
+ "interaction_resource_operations",
293
+ "knowledge_change_proposals",
294
+ "knowledge_claim_evidence",
295
+ "knowledge_claim_relations",
296
+ "knowledge_claim_reviews",
297
+ "knowledge_claims",
298
+ "knowledge_document_versions",
299
+ "knowledge_entities",
300
+ "knowledge_entity_aliases",
301
+ "knowledge_facts",
302
+ "knowledge_lifecycle_events",
303
+ "knowledge_memories",
304
+ "knowledge_memory_lifecycle_events",
305
+ "knowledge_memory_relationships",
306
+ "knowledge_operation_receipts",
307
+ "knowledge_providers",
308
+ "knowledge_source_acl_versions",
309
+ "knowledge_source_objects",
310
+ "knowledge_source_sync_index_obligations",
311
+ "knowledge_source_sync_item_outcomes",
312
+ "knowledge_source_sync_object_observations",
313
+ "knowledge_source_sync_states",
314
+ "knowledge_source_sync_wakes",
315
+ "knowledge_sources",
316
+ "knowledge_sync_runs",
317
+ "machine_metrics_latest",
318
+ "machine_metrics_series",
319
+ "machine_removal_operations",
320
+ "memory_slack_publication_configurations",
321
+ "memory_slack_publication_receipts",
322
+ "memory_slack_publications",
323
+ "model_call_facts",
324
+ "network_routes",
325
+ "new_session_drafts",
326
+ "organization_memberships",
327
+ "organization_user_resource_authorities",
328
+ "organization_user_resource_grants",
329
+ "organization_user_retention_policies",
330
+ "pack_installation_components",
331
+ "pack_installations",
332
+ "preference_registry_events",
333
+ "preference_registry_preferences",
334
+ "preference_registry_revisions",
335
+ "preference_registry_snapshots",
336
+ "retained_screenshot_artifacts",
337
+ "rig_changes",
338
+ "rig_versions",
339
+ "rigs",
340
+ "sandbox_checkpoint_artifacts",
341
+ "sandbox_lease_holders",
342
+ "sandbox_leases",
343
+ "sandbox_pty_sessions",
344
+ "sandbox_retained_processes",
345
+ "sandbox_session_envelopes",
346
+ "sandbox_workspace_mutation_admissions",
347
+ "sandboxes",
348
+ "scheduled_task_runs",
349
+ "scheduled_tasks",
350
+ "session_attempt_codemode_calls",
351
+ "session_attempt_interruptions",
352
+ "session_attempt_tool_catalogs",
353
+ "session_command_receipts",
354
+ "session_events",
355
+ "session_goal_revisions",
356
+ "session_goals",
357
+ "session_history_items",
358
+ "session_human_input_requests",
359
+ "session_list_snapshots",
360
+ "session_mcp_servers",
361
+ "session_pending_tool_calls",
362
+ "session_pins",
363
+ "session_realtime_connections",
364
+ "session_realtime_context_projections",
365
+ "session_realtime_entries",
366
+ "session_realtime_modes",
367
+ "session_recordings",
368
+ "session_spawn_denials",
369
+ "session_stream_acknowledgments",
370
+ "session_system_update_outbox",
371
+ "session_system_updates",
372
+ "session_turn_attempts",
373
+ "session_turns",
374
+ "session_visibility_write_capabilities",
375
+ "session_workflow_wake_outbox",
376
+ "sessions",
377
+ "site_auth_connections",
378
+ "slack_bot_delete_operations",
379
+ "slack_bot_post_operations",
380
+ "slack_bot_update_operations",
381
+ "slack_bot_user_links",
382
+ "slack_installation_bindings",
383
+ "slack_interaction_action_handles",
384
+ "slack_interaction_inbox",
385
+ "slack_interaction_progress_deliveries",
386
+ "slack_interactions",
387
+ "slack_shared_task_origins",
388
+ "slack_task_policy_activation_events",
389
+ "slack_task_policy_heads",
390
+ "slack_task_policy_revisions",
391
+ "slack_user_link_access_request_operations",
392
+ "slack_user_link_access_requests",
393
+ "social_connections",
394
+ "social_posts",
395
+ "task_note_events",
396
+ "task_note_write_capabilities",
397
+ "task_notes",
398
+ "temporal_schedule_cleanup_outbox",
399
+ "transcription_recording_chunks",
400
+ "transcription_recording_objects",
401
+ "transcription_recording_segments",
402
+ "transcription_recordings",
403
+ "usage_events",
404
+ "video_generation_operations",
405
+ "video_generation_references",
406
+ "workspace_artifact_events",
407
+ "workspace_artifact_versions",
408
+ "workspace_artifacts",
409
+ "workspace_captures",
410
+ "workspace_control_events",
411
+ "workspace_inference_controls",
412
+ "workspace_instruction_policy_activation_events",
413
+ "workspace_instruction_policy_heads",
414
+ "workspace_instruction_policy_onboarding_proposals",
415
+ "workspace_instruction_policy_revisions",
416
+ "workspace_instruction_policy_snapshots",
417
+ "workspace_interaction_revisions",
418
+ "workspace_learning_policy_activation_events",
419
+ "workspace_learning_policy_heads",
420
+ "workspace_learning_policy_revisions",
421
+ "workspace_learning_policy_snapshots",
422
+ "workspace_model_policies",
423
+ "workspace_packs",
424
+ "workspace_screenshot_quotas",
425
+ "workspace_session_activity_revisions",
426
+ "workspace_variable_set_variables",
427
+ "workspace_variable_sets",
428
+ "workspace_video_generation_policies",
429
+ "workspace_video_generation_quotas",
430
+ "xai_capacity_waiters",
431
+ "xai_credential_leases",
432
+ "xai_rotation_settings",
433
+ "xai_session_account_pins",
434
+ "xai_subscription_credentials"
435
+ ];
436
+ var NON_RLS_RUNTIME_TABLES = [
437
+ "auth_identities",
438
+ "auth_rate_limits",
439
+ "auth_sessions",
440
+ "auth_users",
441
+ "auth_verifications",
442
+ "integration_oauth_clients",
443
+ "managed_accounts",
444
+ "nested_agent_depth_configuration",
445
+ "stripe_webhook_events",
446
+ "workspace_memberships",
447
+ "workspaces"
448
+ ];
449
+ var RUNTIME_FULL_DML_TABLES = [
450
+ "agent_run_states",
451
+ "api_keys",
452
+ "audit_events",
453
+ "auth_identities",
454
+ "auth_rate_limits",
455
+ "auth_sessions",
456
+ "auth_users",
457
+ "auth_verifications",
458
+ "billing_customers",
459
+ "browser_session_associations",
460
+ "capability_catalog_items",
461
+ "capability_component_owners",
462
+ "capability_facet_installations",
463
+ "capability_installations",
464
+ "capability_operations",
465
+ "capability_plugin_installations",
466
+ "channels",
467
+ "codex_apps_settings",
468
+ "codex_capacity_waiters",
469
+ "codex_credential_leases",
470
+ "codex_reset_redemption_attempts",
471
+ "codex_rotation_settings",
472
+ "codex_subscription_credentials",
473
+ "composer_drafts",
474
+ "computer_session_associations",
475
+ "connection_disconnect_operations",
476
+ "connections",
477
+ "connector_action_policies",
478
+ "connector_action_requests",
479
+ "credit_ledger_entries",
480
+ "device_enrollment_requests",
481
+ "document_bases",
482
+ "document_chunks",
483
+ "documents",
484
+ "editable_artifact_replica_leases",
485
+ "enrollments",
486
+ "file_uploads",
487
+ "files",
488
+ "generated_image_artifacts",
489
+ "generated_video_artifacts",
490
+ "github_installation_repositories",
491
+ "github_installations",
492
+ "image_generation_operations",
493
+ "import_batches",
494
+ "integration_facet_binding_owners",
495
+ "integration_facet_bindings",
496
+ "integration_oauth_clients",
497
+ "integration_oauth_state_nonces",
498
+ "knowledge_memories",
499
+ "knowledge_source_sync_index_obligations",
500
+ "knowledge_source_sync_item_outcomes",
501
+ "knowledge_source_sync_object_observations",
502
+ "knowledge_source_sync_states",
503
+ "knowledge_source_sync_wakes",
504
+ "machine_metrics_latest",
505
+ "machine_metrics_series",
506
+ "machine_removal_operations",
507
+ "managed_accounts",
508
+ "memory_slack_publication_configurations",
509
+ "memory_slack_publication_receipts",
510
+ "memory_slack_publications",
511
+ "model_call_facts",
512
+ "new_session_drafts",
513
+ "pack_installation_components",
514
+ "pack_installations",
515
+ "retained_screenshot_artifacts",
516
+ "rig_changes",
517
+ "rig_versions",
518
+ "rigs",
519
+ "sandbox_checkpoint_artifacts",
520
+ "sandbox_lease_holders",
521
+ "sandbox_leases",
522
+ "sandbox_pty_sessions",
523
+ "sandbox_retained_processes",
524
+ "sandbox_session_envelopes",
525
+ "sandbox_workspace_mutation_admissions",
526
+ "sandboxes",
527
+ "scheduled_task_runs",
528
+ "scheduled_tasks",
529
+ "session_attempt_interruptions",
530
+ "session_command_receipts",
531
+ "session_events",
532
+ "session_goals",
533
+ "session_history_items",
534
+ "session_human_input_requests",
535
+ "session_list_snapshots",
536
+ "session_mcp_servers",
537
+ "session_pending_tool_calls",
538
+ "session_pins",
539
+ "session_realtime_connections",
540
+ "session_realtime_context_projections",
541
+ "session_realtime_entries",
542
+ "session_realtime_modes",
543
+ "session_recordings",
544
+ "session_stream_acknowledgments",
545
+ "session_system_update_outbox",
546
+ "session_system_updates",
547
+ "session_turn_attempts",
548
+ "session_turns",
549
+ "session_workflow_wake_outbox",
550
+ "sessions",
551
+ "slack_bot_delete_operations",
552
+ "slack_bot_post_operations",
553
+ "slack_bot_update_operations",
554
+ "slack_bot_user_links",
555
+ "slack_interaction_action_handles",
556
+ "slack_interaction_inbox",
557
+ "slack_interaction_progress_deliveries",
558
+ "slack_interactions",
559
+ "social_connections",
560
+ "social_posts",
561
+ "stripe_webhook_events",
562
+ "transcription_recording_chunks",
563
+ "transcription_recording_objects",
564
+ "transcription_recording_segments",
565
+ "transcription_recordings",
566
+ "usage_events",
567
+ "video_generation_operations",
568
+ "video_generation_references",
569
+ "workspace_artifacts",
570
+ "workspace_captures",
571
+ "workspace_control_events",
572
+ "workspace_inference_controls",
573
+ "workspace_instruction_policy_heads",
574
+ "workspace_memberships",
575
+ "workspace_model_policies",
576
+ "workspace_packs",
577
+ "workspace_screenshot_quotas",
578
+ "workspace_variable_set_variables",
579
+ "workspace_variable_sets",
580
+ "workspace_video_generation_policies",
581
+ "workspace_video_generation_quotas",
582
+ "workspaces",
583
+ "xai_capacity_waiters",
584
+ "xai_credential_leases",
585
+ "xai_rotation_settings",
586
+ "xai_session_account_pins",
587
+ "xai_subscription_credentials"
588
+ ];
589
+ var RUNTIME_READ_ONLY_TABLES = [
590
+ "company_profile_activation_events",
591
+ "company_profile_heads",
592
+ "company_profile_snapshots",
593
+ "knowledge_lifecycle_events",
594
+ "knowledge_memory_lifecycle_events",
595
+ "knowledge_memory_relationships",
596
+ "nested_agent_depth_configuration",
597
+ "preference_registry_events",
598
+ "preference_registry_snapshots",
599
+ "slack_installation_bindings",
600
+ "slack_task_policy_activation_events",
601
+ "slack_task_policy_heads",
602
+ "slack_task_policy_revisions",
603
+ "workspace_instruction_policy_snapshots",
604
+ "workspace_learning_policy_activation_events",
605
+ "workspace_learning_policy_heads",
606
+ "workspace_learning_policy_snapshots"
607
+ ];
608
+ var RUNTIME_READ_UPDATE_TABLES = ["workspace_session_activity_revisions"];
609
+ var RUNTIME_READ_INSERT_TABLES = [
610
+ "browser_revision_components",
611
+ "browser_revisions",
612
+ "company_profile_revisions",
613
+ "editable_artifact_blob_refs",
614
+ "editable_artifact_idempotency_receipts",
615
+ "editable_artifact_live_outbox",
616
+ "editable_artifact_materialization_jobs",
617
+ "editable_artifact_materialization_results",
618
+ "editable_artifact_operations",
619
+ "editable_artifact_sequence_checkpoints",
620
+ "editable_artifact_snapshots",
621
+ "editable_artifact_transactions",
622
+ "editable_artifact_undo_claims",
623
+ "editable_artifact_versions",
624
+ "knowledge_change_proposals",
625
+ "knowledge_claim_evidence",
626
+ "knowledge_claim_relations",
627
+ "knowledge_claim_reviews",
628
+ "knowledge_claims",
629
+ "knowledge_document_versions",
630
+ "knowledge_entities",
631
+ "knowledge_entity_aliases",
632
+ "knowledge_facts",
633
+ "knowledge_operation_receipts",
634
+ "knowledge_providers",
635
+ "knowledge_source_acl_versions",
636
+ "knowledge_source_objects",
637
+ "knowledge_sources",
638
+ "knowledge_sync_runs",
639
+ "preference_registry_preferences",
640
+ "preference_registry_revisions",
641
+ "session_attempt_tool_catalogs",
642
+ "session_goal_revisions",
643
+ "session_spawn_denials",
644
+ "slack_shared_task_origins",
645
+ "slack_user_link_access_request_operations",
646
+ "temporal_schedule_cleanup_outbox",
647
+ "workspace_artifact_events",
648
+ "workspace_artifact_versions",
649
+ "workspace_instruction_policy_activation_events",
650
+ "workspace_instruction_policy_onboarding_proposals",
651
+ "workspace_instruction_policy_revisions",
652
+ "workspace_learning_policy_revisions"
653
+ ];
654
+ var RUNTIME_READ_INSERT_UPDATE_TABLES = [
655
+ "attached_browser_devices",
656
+ "attached_browser_inventories",
657
+ "auth_runs",
658
+ "browser_identities",
659
+ "browser_sessions",
660
+ "browser_state_artifacts",
661
+ "browser_state_uploads",
662
+ "capability_api_facets",
663
+ "capability_facets",
664
+ "capability_integration_facets",
665
+ "capability_mcp_facets",
666
+ "capability_plugin_versions",
667
+ "capability_plugins",
668
+ "capability_skill_facets",
669
+ "capability_skill_files",
670
+ "computer_sessions",
671
+ "editable_artifact_session_links",
672
+ "editable_artifacts",
673
+ "integration_facet_definitions",
674
+ "integration_spec_revisions",
675
+ "integration_tools",
676
+ "interaction_interventions",
677
+ "interaction_operations",
678
+ "interaction_resource_operations",
679
+ "network_routes",
680
+ "session_attempt_codemode_calls",
681
+ "site_auth_connections",
682
+ "slack_user_link_access_requests",
683
+ "workspace_interaction_revisions"
684
+ ];
685
+ var PROTECTED_NO_DIRECT_DML_TABLES = [
686
+ "canonical_human_identities",
687
+ "canonical_human_identity_operations",
688
+ "canonical_human_identity_subjects",
689
+ "canonical_human_login_bindings",
690
+ "editable_artifact_live_tickets",
691
+ "editable_artifact_scope_authorization_heads",
692
+ "host_export_config",
693
+ "host_export_consumers",
694
+ "host_export_cursor_state",
695
+ "host_export_dead_letters",
696
+ "host_export_outbox",
697
+ "organization_memberships",
698
+ "organization_user_resource_authorities",
699
+ "organization_user_resource_grants",
700
+ "organization_user_retention_policies",
701
+ "session_visibility_write_capabilities",
702
+ "task_note_events",
703
+ "task_note_write_capabilities",
704
+ "task_notes"
705
+ ];
706
+ var FULL_DML_PRIVILEGES = ["SELECT", "INSERT", "UPDATE", "DELETE"];
707
+ var RUNTIME_TABLE_PRIVILEGES = Object.freeze({
708
+ ...Object.fromEntries(RUNTIME_FULL_DML_TABLES.map((table) => [table, FULL_DML_PRIVILEGES])),
709
+ ...Object.fromEntries(RUNTIME_READ_ONLY_TABLES.map((table) => [table, ["SELECT"]])),
710
+ ...Object.fromEntries(
711
+ RUNTIME_READ_UPDATE_TABLES.map((table) => [table, ["SELECT", "UPDATE"]])
712
+ ),
713
+ ...Object.fromEntries(
714
+ RUNTIME_READ_INSERT_TABLES.map((table) => [table, ["SELECT", "INSERT"]])
715
+ ),
716
+ ...Object.fromEntries(
717
+ RUNTIME_READ_INSERT_UPDATE_TABLES.map((table) => [
718
+ table,
719
+ ["SELECT", "INSERT", "UPDATE"]
720
+ ])
721
+ )
722
+ });
723
+ var RUNTIME_DML_TABLES = Object.freeze(
724
+ Object.keys(RUNTIME_TABLE_PRIVILEGES).sort((a, b) => a.localeCompare(b))
725
+ );
726
+ var RuntimeDatabasePostureError = class extends Error {
727
+ violations;
728
+ constructor(violations) {
729
+ super(`Runtime database posture check failed: ${violations.join("; ")}`);
730
+ this.name = "RuntimeDatabasePostureError";
731
+ this.violations = violations;
732
+ }
733
+ };
734
+ function resultRows(result) {
735
+ if (Array.isArray(result)) {
736
+ return result;
737
+ }
738
+ const rows = result?.rows;
739
+ if (Array.isArray(rows)) {
740
+ return rows;
741
+ }
742
+ throw new Error("Runtime database posture query returned an unsupported result shape");
743
+ }
744
+ function sorted(values) {
745
+ return [...values].sort((a, b) => a.localeCompare(b));
746
+ }
747
+ function difference(left, right) {
748
+ return sorted([...left].filter((value) => !right.has(value)));
749
+ }
750
+ async function inspectRuntimeDatabasePosture(db, options) {
751
+ const targetSchema = options.targetSchema?.trim() || "public";
752
+ return await db.transaction(
753
+ async (tx) => {
754
+ const identityRows = resultRows(
755
+ await tx.execute(sql`
756
+ select
757
+ current_user::text as current_user,
758
+ session_user::text as session_user,
759
+ pg_get_userbyid(d.datdba)::text as database_owner,
760
+ has_database_privilege(current_user, d.oid, 'CONNECT') as can_connect_database,
761
+ has_database_privilege(current_user, d.oid, 'CREATE') as can_create_in_database,
762
+ current_setting('row_security')::text as row_security,
763
+ r.rolcanlogin,
764
+ r.rolsuper,
765
+ r.rolinherit,
766
+ r.rolcreaterole,
767
+ r.rolcreatedb,
768
+ r.rolreplication,
769
+ r.rolbypassrls
770
+ from pg_roles r
771
+ join pg_database d on d.datname = current_database()
772
+ where r.rolname = current_user
773
+ `)
774
+ );
775
+ const identity = identityRows[0];
776
+ if (!identity) {
777
+ throw new Error("Runtime database posture could not resolve the current PostgreSQL role");
778
+ }
779
+ const mappedIdentity = {
780
+ currentUser: identity.current_user,
781
+ sessionUser: identity.session_user,
782
+ databaseOwner: identity.database_owner,
783
+ canConnectDatabase: identity.can_connect_database,
784
+ canCreateInDatabase: identity.can_create_in_database,
785
+ rowSecurity: identity.row_security,
786
+ canLogin: identity.rolcanlogin,
787
+ superuser: identity.rolsuper,
788
+ inherit: identity.rolinherit,
789
+ createRole: identity.rolcreaterole,
790
+ createDatabase: identity.rolcreatedb,
791
+ replication: identity.rolreplication,
792
+ bypassRls: identity.rolbypassrls
793
+ };
794
+ if (options.rlsStrategy === "scoped") {
795
+ return {
796
+ identity: mappedIdentity,
797
+ memberships: [],
798
+ schemas: [],
799
+ ownedSchemas: [],
800
+ ownedRelations: [],
801
+ tables: [],
802
+ targetRoutines: [],
803
+ privateRoutines: []
804
+ };
805
+ }
806
+ const relationshipRows = resultRows(
807
+ await tx.execute(sql.raw(roleRelationshipsCatalogQuery("current_user")))
808
+ );
809
+ const memberships = classifyRoleRelationships(relationshipRows).unsafeRelationships;
810
+ const schemas = resultRows(
811
+ await tx.execute(sql`
812
+ select
813
+ n.nspname::text as name,
814
+ pg_get_userbyid(n.nspowner)::text as owner,
815
+ has_schema_privilege(current_user, n.oid, 'USAGE') as usage,
816
+ has_schema_privilege(current_user, n.oid, 'CREATE') as create
817
+ from pg_namespace n
818
+ where n.nspname in (${targetSchema}, 'opengeni_private')
819
+ order by n.nspname
820
+ `)
821
+ );
822
+ const ownedSchemas = resultRows(
823
+ await tx.execute(sql`
824
+ select n.nspname::text as name
825
+ from pg_namespace n
826
+ join pg_roles r on r.oid = n.nspowner
827
+ where r.rolname = current_user
828
+ and n.nspname <> 'information_schema'
829
+ and n.nspname !~ '^pg_'
830
+ order by n.nspname
831
+ `)
832
+ ).map((row) => row.name);
833
+ const ownedRelations = resultRows(
834
+ await tx.execute(sql`
835
+ select (n.nspname || '.' || c.relname)::text as name
836
+ from pg_class c
837
+ join pg_namespace n on n.oid = c.relnamespace
838
+ join pg_roles r on r.oid = c.relowner
839
+ where r.rolname = current_user
840
+ and c.relkind in ('r', 'p', 'S', 'v', 'm', 'f')
841
+ and n.nspname <> 'information_schema'
842
+ and n.nspname !~ '^pg_'
843
+ order by n.nspname, c.relname
844
+ `)
845
+ ).map((row) => row.name);
846
+ const tables = resultRows(
847
+ await tx.execute(sql`
848
+ select
849
+ c.relname::text as name,
850
+ pg_get_userbyid(c.relowner)::text as owner,
851
+ c.relrowsecurity as rls_enabled,
852
+ c.relforcerowsecurity as rls_forced,
853
+ row_security_active(c.oid) as rls_active,
854
+ (select count(*)::int from pg_policy policy where policy.polrelid = c.oid) as policy_count,
855
+ exists(
856
+ select 1 from pg_policy policy
857
+ where policy.polrelid = c.oid
858
+ and policy.polname = 'editable_artifact_outbox_dispatcher'
859
+ ) as artifact_outbox_dispatcher_policy,
860
+ exists(
861
+ select 1 from pg_policy policy
862
+ where policy.polrelid = c.oid
863
+ and policy.polname = 'editable_artifact_materializer_owner'
864
+ ) as artifact_materializer_policy,
865
+ has_table_privilege(current_user, c.oid, 'SELECT') as can_select,
866
+ has_table_privilege(current_user, c.oid, 'INSERT') as can_insert,
867
+ has_table_privilege(current_user, c.oid, 'UPDATE') as can_update,
868
+ has_table_privilege(current_user, c.oid, 'DELETE') as can_delete,
869
+ has_table_privilege(current_user, c.oid, 'TRUNCATE') as can_truncate,
870
+ has_table_privilege(current_user, c.oid, 'REFERENCES') as can_references,
871
+ has_table_privilege(current_user, c.oid, 'TRIGGER') as can_trigger
872
+ from pg_class c
873
+ join pg_namespace n on n.oid = c.relnamespace
874
+ where n.nspname = ${targetSchema}
875
+ and c.relkind in ('r', 'p')
876
+ order by c.relname
877
+ `)
878
+ ).map((row) => ({
879
+ name: row.name,
880
+ owner: row.owner,
881
+ rlsEnabled: row.rls_enabled,
882
+ rlsForced: row.rls_forced,
883
+ rlsActive: row.rls_active,
884
+ policyCount: row.policy_count,
885
+ artifactOutboxDispatcherPolicy: row.artifact_outbox_dispatcher_policy,
886
+ artifactMaterializerPolicy: row.artifact_materializer_policy,
887
+ select: row.can_select,
888
+ insert: row.can_insert,
889
+ update: row.can_update,
890
+ delete: row.can_delete,
891
+ truncate: row.can_truncate,
892
+ references: row.can_references,
893
+ trigger: row.can_trigger
894
+ }));
895
+ const targetRoutines = resultRows(
896
+ await tx.execute(sql`
897
+ select
898
+ (p.proname || '(' || pg_catalog.oidvectortypes(p.proargtypes) || ')')::text as name,
899
+ pg_get_userbyid(p.proowner)::text as owner,
900
+ has_function_privilege(current_user, p.oid, 'EXECUTE') as can_execute,
901
+ exists (
902
+ select 1
903
+ from aclexplode(coalesce(p.proacl, acldefault('f', p.proowner))) acl
904
+ where acl.grantee = 0 and acl.privilege_type = 'EXECUTE'
905
+ ) as public_execute,
906
+ p.prosecdef as security_definer
907
+ from pg_proc p
908
+ join pg_namespace n on n.oid = p.pronamespace
909
+ where n.nspname = ${targetSchema}
910
+ and p.prokind in ('f', 'p')
911
+ and (p.proname || '(' || pg_catalog.oidvectortypes(p.proargtypes) || ')') = any(
912
+ array[
913
+ ${sql.join(
914
+ RUNTIME_TARGET_SCHEMA_CAPABILITY_ROUTINES.map((name) => sql`${name}`),
915
+ sql`, `
916
+ )}
917
+ ]::text[]
918
+ )
919
+ order by p.proname, pg_catalog.oidvectortypes(p.proargtypes)
920
+ `)
921
+ ).map((row) => ({
922
+ name: row.name,
923
+ owner: row.owner,
924
+ execute: row.can_execute,
925
+ publicExecute: row.public_execute,
926
+ securityDefiner: row.security_definer
927
+ }));
928
+ const privateRoutines = resultRows(
929
+ await tx.execute(sql`
930
+ select
931
+ (p.proname || '(' || pg_catalog.oidvectortypes(p.proargtypes) || ')')::text as name,
932
+ pg_get_userbyid(p.proowner)::text as owner,
933
+ has_function_privilege(current_user, p.oid, 'EXECUTE') as can_execute,
934
+ p.prosecdef as security_definer
935
+ from pg_proc p
936
+ join pg_namespace n on n.oid = p.pronamespace
937
+ where n.nspname = 'opengeni_private'
938
+ and p.prokind in ('f', 'p')
939
+ order by p.proname, pg_catalog.oidvectortypes(p.proargtypes)
940
+ `)
941
+ ).map((row) => ({
942
+ name: row.name,
943
+ owner: row.owner,
944
+ execute: row.can_execute,
945
+ securityDefiner: row.security_definer
946
+ }));
947
+ return {
948
+ identity: mappedIdentity,
949
+ memberships,
950
+ schemas,
951
+ ownedSchemas,
952
+ ownedRelations,
953
+ tables,
954
+ targetRoutines,
955
+ privateRoutines
956
+ };
957
+ },
958
+ { isolationLevel: "repeatable read", accessMode: "read only" }
959
+ );
960
+ }
961
+ function evaluateRuntimeDatabasePosture(posture, options) {
962
+ const violations = [];
963
+ const identity = posture.identity;
964
+ if (!identity.currentUser || !identity.sessionUser) {
965
+ violations.push("database identity is empty");
966
+ }
967
+ if (identity.currentUser !== identity.sessionUser) {
968
+ violations.push(
969
+ `current_user ${identity.currentUser} does not match session_user ${identity.sessionUser}`
970
+ );
971
+ }
972
+ if (!identity.canConnectDatabase) {
973
+ violations.push("runtime role lacks CONNECT on the current database");
974
+ }
975
+ if (options.rlsStrategy === "scoped") {
976
+ return violations;
977
+ }
978
+ const expectedRole = options.expectedRole?.trim() || "opengeni_app";
979
+ const targetSchema = options.targetSchema?.trim() || "public";
980
+ const protectedTables = new Set(options.protectedTables ?? FORCE_RLS_TABLES);
981
+ const tablePrivileges = options.tablePrivileges ?? RUNTIME_TABLE_PRIVILEGES;
982
+ const directRuntimeTables = new Set(Object.keys(tablePrivileges));
983
+ const protectedNoDirectDmlTables = new Set(
984
+ options.protectedNoDirectDmlTables ?? (options.protectedTables ? [] : PROTECTED_NO_DIRECT_DML_TABLES)
985
+ );
986
+ if (identity.currentUser !== expectedRole || identity.sessionUser !== expectedRole) {
987
+ violations.push(
988
+ `runtime identity must be ${expectedRole} (current_user=${identity.currentUser}, session_user=${identity.sessionUser})`
989
+ );
990
+ }
991
+ if (!identity.canLogin) violations.push("runtime role is not LOGIN");
992
+ if (identity.superuser) violations.push("runtime role is SUPERUSER");
993
+ if (identity.bypassRls) violations.push("runtime role has BYPASSRLS");
994
+ if (identity.createRole) violations.push("runtime role has CREATEROLE");
995
+ if (identity.createDatabase) violations.push("runtime role has CREATEDB");
996
+ if (identity.replication) violations.push("runtime role has REPLICATION");
997
+ if (identity.inherit) violations.push("runtime role must be NOINHERIT");
998
+ if (identity.databaseOwner === expectedRole) violations.push("runtime role owns the database");
999
+ if (identity.canCreateInDatabase) {
1000
+ violations.push("runtime role has CREATE on the current database");
1001
+ }
1002
+ if (identity.rowSecurity.toLowerCase() !== "on") {
1003
+ violations.push(`row_security is ${identity.rowSecurity}, expected on`);
1004
+ }
1005
+ if (posture.memberships.length > 0) {
1006
+ violations.push(`runtime role has memberships: ${sorted(posture.memberships).join(", ")}`);
1007
+ }
1008
+ if (posture.ownedSchemas.length > 0) {
1009
+ violations.push(`runtime role owns schemas: ${sorted(posture.ownedSchemas).join(", ")}`);
1010
+ }
1011
+ if (posture.ownedRelations.length > 0) {
1012
+ violations.push(`runtime role owns relations: ${sorted(posture.ownedRelations).join(", ")}`);
1013
+ }
1014
+ for (const schemaName of /* @__PURE__ */ new Set([targetSchema, "opengeni_private"])) {
1015
+ const schema = posture.schemas.find((candidate) => candidate.name === schemaName);
1016
+ if (!schema) {
1017
+ violations.push(`required schema ${schemaName} is missing`);
1018
+ continue;
1019
+ }
1020
+ if (schema.owner === expectedRole) {
1021
+ violations.push(`runtime role owns schema ${schemaName}`);
1022
+ }
1023
+ if (!schema.usage) violations.push(`runtime role lacks USAGE on schema ${schemaName}`);
1024
+ if (schema.create) violations.push(`runtime role has CREATE on schema ${schemaName}`);
1025
+ }
1026
+ const tableByName = new Map(posture.tables.map((table) => [table.name, table]));
1027
+ const actualRlsTables = new Set(
1028
+ posture.tables.filter((table) => table.rlsEnabled).map((table) => table.name)
1029
+ );
1030
+ const classifiedProtectedTables = /* @__PURE__ */ new Set([
1031
+ ...directRuntimeTables,
1032
+ ...protectedNoDirectDmlTables
1033
+ ]);
1034
+ const unclassifiedProtectedTables = difference(protectedTables, classifiedProtectedTables);
1035
+ if (unclassifiedProtectedTables.length > 0) {
1036
+ violations.push(
1037
+ `protected tables lack an explicit privilege class: ${unclassifiedProtectedTables.join(", ")}`
1038
+ );
1039
+ }
1040
+ const protectedNoDirectDmlOverlap = difference(
1041
+ protectedNoDirectDmlTables,
1042
+ new Set([...protectedNoDirectDmlTables].filter((table) => !directRuntimeTables.has(table)))
1043
+ );
1044
+ if (protectedNoDirectDmlOverlap.length > 0) {
1045
+ violations.push(
1046
+ `protected no-direct-DML tables also declare runtime privileges: ${protectedNoDirectDmlOverlap.join(", ")}`
1047
+ );
1048
+ }
1049
+ const nonProtectedNoDirectDmlTables = difference(protectedNoDirectDmlTables, protectedTables);
1050
+ if (nonProtectedNoDirectDmlTables.length > 0) {
1051
+ violations.push(
1052
+ `no-direct-DML tables are absent from the protected contract: ${nonProtectedNoDirectDmlTables.join(", ")}`
1053
+ );
1054
+ }
1055
+ const catalogTables = new Set(tableByName.keys());
1056
+ const missingRuntimeTables = difference(directRuntimeTables, catalogTables);
1057
+ if (missingRuntimeTables.length > 0) {
1058
+ violations.push(`runtime privilege tables are missing: ${missingRuntimeTables.join(", ")}`);
1059
+ }
1060
+ const missingTables = difference(protectedTables, catalogTables);
1061
+ if (missingTables.length > 0) {
1062
+ violations.push(`protected tables are missing: ${missingTables.join(", ")}`);
1063
+ }
1064
+ const undeclaredRlsTables = difference(actualRlsTables, protectedTables);
1065
+ if (undeclaredRlsTables.length > 0) {
1066
+ violations.push(
1067
+ `RLS tables are absent from the declared contract: ${undeclaredRlsTables.join(", ")}`
1068
+ );
1069
+ }
1070
+ for (const table of posture.tables) {
1071
+ const privileges = [
1072
+ ["SELECT", table.select],
1073
+ ["INSERT", table.insert],
1074
+ ["UPDATE", table.update],
1075
+ ["DELETE", table.delete],
1076
+ ["TRUNCATE", table.truncate],
1077
+ ["REFERENCES", table.references],
1078
+ ["TRIGGER", table.trigger]
1079
+ ];
1080
+ const expectedPrivileges = new Set(tablePrivileges[table.name] ?? []);
1081
+ if (table.owner === expectedRole) {
1082
+ violations.push(`runtime role owns table ${table.name}`);
1083
+ }
1084
+ const missingPrivileges = privileges.filter(([privilege, granted]) => expectedPrivileges.has(privilege) && !granted).map(([privilege]) => privilege);
1085
+ if (missingPrivileges.length > 0) {
1086
+ violations.push(
1087
+ `table ${table.name} lacks required runtime privileges: ${missingPrivileges.join(", ")}`
1088
+ );
1089
+ }
1090
+ const excessPrivileges = privileges.filter(([privilege, granted]) => !expectedPrivileges.has(privilege) && granted).map(([privilege]) => privilege);
1091
+ if (excessPrivileges.length > 0) {
1092
+ violations.push(
1093
+ `table ${table.name} grants excess runtime privileges: ${excessPrivileges.join(", ")}`
1094
+ );
1095
+ }
1096
+ }
1097
+ for (const tableName of protectedTables) {
1098
+ const table = tableByName.get(tableName);
1099
+ if (!table) continue;
1100
+ if (!table.rlsEnabled) violations.push(`table ${tableName} does not ENABLE RLS`);
1101
+ if (!table.rlsForced) violations.push(`table ${tableName} does not FORCE RLS`);
1102
+ if (!table.rlsActive) violations.push(`table ${tableName} has inactive RLS for runtime role`);
1103
+ if (table.policyCount < 1) violations.push(`table ${tableName} has no RLS policy`);
1104
+ }
1105
+ const targetSchemaOwner = posture.schemas.find((schema) => schema.name === targetSchema)?.owner;
1106
+ for (const expectedRoutine of RUNTIME_TARGET_SCHEMA_CAPABILITY_ROUTINES) {
1107
+ const matches = posture.targetRoutines.filter((routine2) => routine2.name === expectedRoutine);
1108
+ if (matches.length !== 1) {
1109
+ violations.push(
1110
+ `target-schema runtime capability ${expectedRoutine} is missing or ambiguous`
1111
+ );
1112
+ continue;
1113
+ }
1114
+ const routine = matches[0];
1115
+ if (RUNTIME_TARGET_SCHEMA_INVOKER_ROUTINE_SET.has(routine.name)) {
1116
+ if (routine.securityDefiner) {
1117
+ violations.push(
1118
+ `target-schema runtime capability ${routine.name} must be SECURITY INVOKER`
1119
+ );
1120
+ }
1121
+ } else if (!routine.securityDefiner) {
1122
+ violations.push(`target-schema runtime capability ${routine.name} is not SECURITY DEFINER`);
1123
+ }
1124
+ if (routine.name === KNOWLEDGE_SOURCE_SYNC_LOCK_AUTHORITY_ROUTINE) {
1125
+ const missingAuthorityTables = KNOWLEDGE_SOURCE_SYNC_LOCK_AUTHORITY_TABLES.filter(
1126
+ (tableName) => !tableByName.has(tableName)
1127
+ );
1128
+ if (missingAuthorityTables.length > 0) {
1129
+ violations.push(
1130
+ `target-schema runtime capability ${routine.name} authority tables are missing: ${missingAuthorityTables.join(", ")}`
1131
+ );
1132
+ } else {
1133
+ const authorityTables = KNOWLEDGE_SOURCE_SYNC_LOCK_AUTHORITY_TABLES.map(
1134
+ (tableName) => tableByName.get(tableName)
1135
+ );
1136
+ const authorityOwners = new Set(authorityTables.map((table) => table.owner));
1137
+ if (authorityOwners.size !== 1) {
1138
+ violations.push(
1139
+ `target-schema runtime capability ${routine.name} authority table owners do not match: ${authorityTables.map((table) => `${table.name}=${table.owner}`).join(", ")}`
1140
+ );
1141
+ } else if (routine.owner !== authorityTables[0].owner) {
1142
+ violations.push(
1143
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match authority table owner ${authorityTables[0].owner}`
1144
+ );
1145
+ }
1146
+ }
1147
+ } else if (routine.name === MANAGED_HUMAN_PERSONAL_WORKSPACE_ROUTINE) {
1148
+ const authorityTables = MANAGED_HUMAN_PERSONAL_WORKSPACE_AUTHORITY_TABLES.filter(
1149
+ (tableName) => tableByName.has(tableName)
1150
+ ).map((tableName) => tableByName.get(tableName));
1151
+ const authorityOwners = new Set(authorityTables.map((table) => table.owner));
1152
+ if (authorityOwners.size > 1) {
1153
+ violations.push(
1154
+ `target-schema runtime capability ${routine.name} authority table owners do not match: ${authorityTables.map((table) => `${table.name}=${table.owner}`).join(", ")}`
1155
+ );
1156
+ } else if (authorityTables[0] && routine.owner !== authorityTables[0].owner) {
1157
+ violations.push(
1158
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match authority table owner ${authorityTables[0].owner}`
1159
+ );
1160
+ }
1161
+ } else if (CANONICAL_HUMAN_IDENTITY_ROUTINES.includes(routine.name)) {
1162
+ const authorityTables = CANONICAL_HUMAN_IDENTITY_AUTHORITY_TABLES.filter(
1163
+ (tableName) => tableByName.has(tableName)
1164
+ ).map((tableName) => tableByName.get(tableName));
1165
+ const authorityOwners = new Set(authorityTables.map((table) => table.owner));
1166
+ if (authorityTables.length !== CANONICAL_HUMAN_IDENTITY_AUTHORITY_TABLES.length) {
1167
+ violations.push(
1168
+ `target-schema runtime capability ${routine.name} canonical identity authority tables are missing`
1169
+ );
1170
+ } else if (authorityOwners.size !== 1) {
1171
+ violations.push(
1172
+ `target-schema runtime capability ${routine.name} authority table owners do not match: ${authorityTables.map((table) => `${table.name}=${table.owner}`).join(", ")}`
1173
+ );
1174
+ } else if (routine.owner !== authorityTables[0].owner) {
1175
+ violations.push(
1176
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match authority table owner ${authorityTables[0].owner}`
1177
+ );
1178
+ }
1179
+ } else if (SESSION_AUTHORITY_ROUTINES.has(routine.name)) {
1180
+ const authorityOwner = tableByName.get("sessions")?.owner ?? targetSchemaOwner;
1181
+ if (authorityOwner && routine.owner !== authorityOwner) {
1182
+ violations.push(
1183
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match session authority owner ${authorityOwner}`
1184
+ );
1185
+ }
1186
+ } else if (routine.name === XAI_SNAPSHOT_VALIDATOR_ROUTINE) {
1187
+ } else if (routine.name === XAI_CREATE_CREDENTIAL_ROUTINE || routine.name === XAI_DISCONNECT_CREDENTIAL_ROUTINE || routine.name === XAI_AUTHORITY_LIVE_ROUTINE || routine.name === XAI_POOL_VISIBLE_ROUTINE || routine.name === XAI_RESOLVE_POOL_ROUTINE || routine.name === XAI_REVALIDATE_CREDENTIAL_ROUTINE) {
1188
+ if (!tableByName.has("xai_subscription_credentials")) {
1189
+ continue;
1190
+ }
1191
+ const missingAuthorityTables = XAI_AUTHORITY_TABLES.filter(
1192
+ (tableName) => !tableByName.has(tableName)
1193
+ );
1194
+ if (missingAuthorityTables.length > 0) {
1195
+ violations.push(
1196
+ `target-schema runtime capability ${routine.name} authority tables are missing: ${missingAuthorityTables.join(", ")}`
1197
+ );
1198
+ } else {
1199
+ const authorityTables = XAI_AUTHORITY_TABLES.map(
1200
+ (tableName) => tableByName.get(tableName)
1201
+ );
1202
+ const authorityOwners = new Set(authorityTables.map((table) => table.owner));
1203
+ if (authorityOwners.size !== 1) {
1204
+ violations.push(
1205
+ `target-schema runtime capability ${routine.name} authority table owners do not match: ${authorityTables.map((table) => `${table.name}=${table.owner}`).join(", ")}`
1206
+ );
1207
+ } else if (routine.owner !== authorityTables[0].owner) {
1208
+ violations.push(
1209
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match authority table owner ${authorityTables[0].owner}`
1210
+ );
1211
+ }
1212
+ }
1213
+ } else if (targetSchemaOwner && routine.owner !== targetSchemaOwner) {
1214
+ violations.push(
1215
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match schema owner ${targetSchemaOwner}`
1216
+ );
1217
+ }
1218
+ if (!routine.execute) {
1219
+ violations.push(`runtime role lacks target-schema capability ${routine.name}`);
1220
+ }
1221
+ if (routine.publicExecute) {
1222
+ violations.push(`PUBLIC has forbidden target-schema capability ${routine.name}`);
1223
+ }
1224
+ }
1225
+ const artifactOutbox = tableByName.get("editable_artifact_live_outbox");
1226
+ if (artifactOutbox) {
1227
+ if (!artifactOutbox.artifactOutboxDispatcherPolicy) {
1228
+ violations.push("table editable_artifact_live_outbox lacks its owner dispatcher RLS policy");
1229
+ }
1230
+ for (const expectedRoutine of ARTIFACT_OUTBOX_CAPABILITY_ROUTINES) {
1231
+ const matches = posture.privateRoutines.filter((routine2) => routine2.name === expectedRoutine);
1232
+ if (matches.length !== 1) {
1233
+ violations.push(`artifact outbox capability ${expectedRoutine} is missing or ambiguous`);
1234
+ continue;
1235
+ }
1236
+ const routine = matches[0];
1237
+ if (!routine.securityDefiner) {
1238
+ violations.push(`artifact outbox capability ${routine.name} is not SECURITY DEFINER`);
1239
+ }
1240
+ if (routine.owner !== artifactOutbox.owner) {
1241
+ violations.push(
1242
+ `artifact outbox capability ${routine.name} owner ${routine.owner} does not match table owner ${artifactOutbox.owner}`
1243
+ );
1244
+ }
1245
+ if (routine.execute) {
1246
+ violations.push(
1247
+ `generic runtime role has forbidden global artifact outbox capability ${routine.name}`
1248
+ );
1249
+ }
1250
+ }
1251
+ }
1252
+ const artifactMaterializationJobs = tableByName.get("editable_artifact_materialization_jobs");
1253
+ if (artifactMaterializationJobs) {
1254
+ for (const tableName of [
1255
+ "editable_artifact_materialization_jobs",
1256
+ "editable_artifact_materialization_results",
1257
+ "editable_artifact_blob_refs",
1258
+ "editable_artifact_sequence_checkpoints",
1259
+ "editable_artifact_versions",
1260
+ "editable_artifact_idempotency_receipts"
1261
+ ]) {
1262
+ const table = tableByName.get(tableName);
1263
+ if (table && !table.artifactMaterializerPolicy) {
1264
+ violations.push(`table ${tableName} lacks its owner materializer RLS policy`);
1265
+ }
1266
+ }
1267
+ for (const expectedRoutine of ARTIFACT_MATERIALIZER_CAPABILITY_ROUTINES) {
1268
+ const matches = posture.privateRoutines.filter((routine2) => routine2.name === expectedRoutine);
1269
+ if (matches.length !== 1) {
1270
+ violations.push(
1271
+ `artifact materializer capability ${expectedRoutine} is missing or ambiguous`
1272
+ );
1273
+ continue;
1274
+ }
1275
+ const routine = matches[0];
1276
+ if (!routine.securityDefiner) {
1277
+ violations.push(`artifact materializer capability ${routine.name} is not SECURITY DEFINER`);
1278
+ }
1279
+ if (routine.owner !== artifactMaterializationJobs.owner) {
1280
+ violations.push(
1281
+ `artifact materializer capability ${routine.name} owner ${routine.owner} does not match table owner ${artifactMaterializationJobs.owner}`
1282
+ );
1283
+ }
1284
+ if (routine.execute) {
1285
+ violations.push(
1286
+ `generic runtime role has forbidden global artifact materializer capability ${routine.name}`
1287
+ );
1288
+ }
1289
+ }
1290
+ }
1291
+ const artifactAuthority = tableByName.get("editable_artifacts");
1292
+ if (artifactAuthority) {
1293
+ const matches = posture.privateRoutines.filter(
1294
+ (routine) => routine.name.startsWith("advance_editable_artifact_authorization_revision(")
1295
+ );
1296
+ if (matches.length !== 1) {
1297
+ violations.push(
1298
+ "editable artifact authorization revision capability is missing or ambiguous"
1299
+ );
1300
+ } else {
1301
+ const routine = matches[0];
1302
+ if (!routine.securityDefiner) {
1303
+ violations.push(
1304
+ `editable artifact authorization revision capability ${routine.name} is not SECURITY DEFINER`
1305
+ );
1306
+ }
1307
+ if (routine.owner !== artifactAuthority.owner) {
1308
+ violations.push(
1309
+ `editable artifact authorization revision capability ${routine.name} owner ${routine.owner} does not match table owner ${artifactAuthority.owner}`
1310
+ );
1311
+ }
1312
+ }
1313
+ for (const expectedRoutine of ARTIFACT_AUTHORIZATION_CAPABILITY_ROUTINES) {
1314
+ const capabilityMatches = posture.privateRoutines.filter(
1315
+ (routine2) => routine2.name === expectedRoutine
1316
+ );
1317
+ if (capabilityMatches.length !== 1) {
1318
+ violations.push(
1319
+ `editable artifact authorization capability ${expectedRoutine} is missing or ambiguous`
1320
+ );
1321
+ continue;
1322
+ }
1323
+ const routine = capabilityMatches[0];
1324
+ if (!routine.securityDefiner) {
1325
+ violations.push(
1326
+ `editable artifact authorization capability ${routine.name} is not SECURITY DEFINER`
1327
+ );
1328
+ }
1329
+ if (routine.owner !== artifactAuthority.owner) {
1330
+ violations.push(
1331
+ `editable artifact authorization capability ${routine.name} owner ${routine.owner} does not match table owner ${artifactAuthority.owner}`
1332
+ );
1333
+ }
1334
+ if (!routine.execute) {
1335
+ violations.push(
1336
+ `runtime role lacks editable artifact authorization capability ${routine.name}`
1337
+ );
1338
+ }
1339
+ }
1340
+ }
1341
+ const artifactLiveTickets = tableByName.get("editable_artifact_live_tickets");
1342
+ if (artifactLiveTickets) {
1343
+ for (const expectedRoutine of ARTIFACT_LIVE_TICKET_CAPABILITY_ROUTINES) {
1344
+ const matches = posture.privateRoutines.filter((routine2) => routine2.name === expectedRoutine);
1345
+ if (matches.length !== 1) {
1346
+ violations.push(
1347
+ `artifact live ticket capability ${expectedRoutine} is missing or ambiguous`
1348
+ );
1349
+ continue;
1350
+ }
1351
+ const routine = matches[0];
1352
+ if (!routine.securityDefiner) {
1353
+ violations.push(`artifact live ticket capability ${routine.name} is not SECURITY DEFINER`);
1354
+ }
1355
+ if (routine.owner !== artifactLiveTickets.owner) {
1356
+ violations.push(
1357
+ `artifact live ticket capability ${routine.name} owner ${routine.owner} does not match table owner ${artifactLiveTickets.owner}`
1358
+ );
1359
+ }
1360
+ if (!routine.execute) {
1361
+ violations.push(`runtime role lacks artifact live ticket capability ${routine.name}`);
1362
+ }
1363
+ }
1364
+ for (const internalRoutine of ARTIFACT_LIVE_TICKET_INTERNAL_ROUTINES) {
1365
+ const matches = posture.privateRoutines.filter((routine2) => routine2.name === internalRoutine);
1366
+ if (matches.length !== 1) {
1367
+ violations.push(
1368
+ `artifact live ticket internal routine ${internalRoutine} is missing or ambiguous`
1369
+ );
1370
+ continue;
1371
+ }
1372
+ const routine = matches[0];
1373
+ if (!routine.securityDefiner) {
1374
+ violations.push(
1375
+ `artifact live ticket internal routine ${routine.name} is not SECURITY DEFINER`
1376
+ );
1377
+ }
1378
+ if (routine.owner !== artifactLiveTickets.owner) {
1379
+ violations.push(
1380
+ `artifact live ticket internal routine ${routine.name} owner ${routine.owner} does not match table owner ${artifactLiveTickets.owner}`
1381
+ );
1382
+ }
1383
+ if (routine.execute) {
1384
+ violations.push(`runtime role has forbidden ticket schema resolver ${routine.name}`);
1385
+ }
1386
+ }
1387
+ }
1388
+ if (posture.privateRoutines.length === 0) {
1389
+ violations.push("opengeni_private has no helper routines");
1390
+ }
1391
+ for (const routine of posture.privateRoutines) {
1392
+ if (routine.owner === expectedRole) {
1393
+ violations.push(`runtime role owns private routine ${routine.name}`);
1394
+ }
1395
+ const dedicatedArtifactCapability = DEDICATED_ARTIFACT_CAPABILITY_ROUTINES.has(routine.name);
1396
+ if (!routine.execute && !dedicatedArtifactCapability) {
1397
+ violations.push(`runtime role lacks EXECUTE on private routine ${routine.name}`);
1398
+ }
1399
+ }
1400
+ return violations;
1401
+ }
1402
+ async function assertRuntimeDatabasePosture(db, options) {
1403
+ const posture = await inspectRuntimeDatabasePosture(db, options);
1404
+ const violations = evaluateRuntimeDatabasePosture(posture, options);
1405
+ if (violations.length > 0) {
1406
+ throw new RuntimeDatabasePostureError(violations);
1407
+ }
1408
+ return posture;
1409
+ }
1410
+ function runtimeDatabaseReadyCheck(db, options) {
1411
+ return async () => {
1412
+ await assertRuntimeDatabasePosture(db, options);
1413
+ };
1414
+ }
1415
+
1416
+ // src/provision-roles.ts
1417
+ async function provisionRoles(adminConnection, options = {}) {
1418
+ const schema = validateIdentifier("targetSchema", options.targetSchema ?? "public");
1419
+ const rlsStrategy = options.rlsStrategy ?? "force";
1420
+ const appRole = validateIdentifier(
1421
+ "appRole",
1422
+ options.appRole ?? (process.env.OPENGENI_APP_DATABASE_USER?.trim() || "opengeni_app")
1423
+ );
1424
+ const appPassword = options.appPassword ?? process.env.OPENGENI_APP_DATABASE_PASSWORD;
1425
+ const artifactOutboxDispatcherRole = validateIdentifier(
1426
+ "artifactOutboxDispatcherRole",
1427
+ options.artifactOutboxDispatcherRole ?? (process.env.OPENGENI_ARTIFACT_OUTBOX_DATABASE_USER?.trim() || "opengeni_artifact_outbox_dispatcher")
1428
+ );
1429
+ const artifactOutboxDispatcherPassword = options.artifactOutboxDispatcherPassword ?? process.env.OPENGENI_ARTIFACT_OUTBOX_DATABASE_PASSWORD;
1430
+ const artifactMaterializerRole = validateIdentifier(
1431
+ "artifactMaterializerRole",
1432
+ options.artifactMaterializerRole ?? (process.env.OPENGENI_ARTIFACT_MATERIALIZER_DATABASE_USER?.trim() || "opengeni_artifact_materializer")
1433
+ );
1434
+ const artifactMaterializerPassword = options.artifactMaterializerPassword ?? process.env.OPENGENI_ARTIFACT_MATERIALIZER_DATABASE_PASSWORD;
1435
+ const hostExportRole = validateIdentifier(
1436
+ "hostExportRole",
1437
+ options.hostExportRole ?? (process.env.OPENGENI_HOST_EXPORT_DATABASE_USER?.trim() || "opengeni_host_exporter")
1438
+ );
1439
+ const hostExportPassword = options.hostExportPassword ?? process.env.OPENGENI_HOST_EXPORT_DATABASE_PASSWORD;
1440
+ const temporalRole = validateIdentifier(
1441
+ "temporalRole",
1442
+ options.temporalRole ?? (process.env.OPENGENI_TEMPORAL_DATABASE_USER?.trim() || "opengeni_temporal")
1443
+ );
1444
+ const temporalPassword = options.temporalPassword ?? process.env.OPENGENI_TEMPORAL_DATABASE_PASSWORD;
1445
+ const temporalDatabases = (options.temporalDatabases ?? commaSeparated(process.env.OPENGENI_TEMPORAL_DATABASES ?? "temporal,temporal_visibility")).map((name) => validateIdentifier("temporalDatabases", name));
1446
+ const sql2 = postgres(adminConnection, { max: 1 });
1447
+ try {
1448
+ let provisionedAppRole = null;
1449
+ if (rlsStrategy === "force") {
1450
+ if (!appPassword) {
1451
+ throw new Error(
1452
+ "OPENGENI_APP_DATABASE_PASSWORD (or appPassword) is required for rlsStrategy 'force'"
1453
+ );
1454
+ }
1455
+ await assertAppRoleSafeToNormalize(sql2, appRole);
1456
+ await ensureRestrictedAppLoginRole(sql2, appRole, appPassword);
1457
+ provisionedAppRole = appRole;
1458
+ }
1459
+ let provisionedArtifactOutboxDispatcherRole = null;
1460
+ if (artifactOutboxDispatcherPassword) {
1461
+ await assertAppRoleSafeToNormalize(sql2, artifactOutboxDispatcherRole);
1462
+ await ensureRestrictedAppLoginRole(
1463
+ sql2,
1464
+ artifactOutboxDispatcherRole,
1465
+ artifactOutboxDispatcherPassword
1466
+ );
1467
+ await grantArtifactCapabilityRoleIfSchemaExists(
1468
+ sql2,
1469
+ artifactOutboxDispatcherRole,
1470
+ schema,
1471
+ "outbox"
1472
+ );
1473
+ provisionedArtifactOutboxDispatcherRole = artifactOutboxDispatcherRole;
1474
+ }
1475
+ let provisionedArtifactMaterializerRole = null;
1476
+ if (artifactMaterializerPassword) {
1477
+ await assertAppRoleSafeToNormalize(sql2, artifactMaterializerRole);
1478
+ await ensureRestrictedAppLoginRole(
1479
+ sql2,
1480
+ artifactMaterializerRole,
1481
+ artifactMaterializerPassword
1482
+ );
1483
+ await grantArtifactCapabilityRoleIfSchemaExists(
1484
+ sql2,
1485
+ artifactMaterializerRole,
1486
+ schema,
1487
+ "materializer"
1488
+ );
1489
+ provisionedArtifactMaterializerRole = artifactMaterializerRole;
1490
+ }
1491
+ if (temporalPassword) {
1492
+ await ensureLoginRole(sql2, temporalRole, temporalPassword);
1493
+ for (const database of temporalDatabases) {
1494
+ await ensureDatabase(sql2, database, temporalRole);
1495
+ await grantTemporalRoleInDatabase(adminConnection, database, temporalRole);
1496
+ }
1497
+ }
1498
+ if (hostExportPassword) {
1499
+ await ensureLoginRole(sql2, hostExportRole, hostExportPassword);
1500
+ await grantHostExportRoleIfSchemaExists(sql2, hostExportRole);
1501
+ }
1502
+ if (rlsStrategy === "force") {
1503
+ await grantAppRoleIfSchemaExists(sql2, appRole, schema);
1504
+ }
1505
+ return {
1506
+ appRole: provisionedAppRole,
1507
+ artifactOutboxDispatcherRole: provisionedArtifactOutboxDispatcherRole,
1508
+ artifactMaterializerRole: provisionedArtifactMaterializerRole,
1509
+ hostExportRole: hostExportPassword ? hostExportRole : null,
1510
+ temporalRole: temporalPassword ? temporalRole : null,
1511
+ temporalDatabases: temporalPassword ? temporalDatabases : [],
1512
+ schema,
1513
+ rlsStrategy
1514
+ };
1515
+ } finally {
1516
+ await sql2.end();
1517
+ }
1518
+ }
1519
+ async function grantHostExportRoleIfSchemaExists(sql2, role) {
1520
+ await sql2.unsafe(`
1521
+ DO $$
1522
+ BEGIN
1523
+ IF EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = 'opengeni_host_export') THEN
1524
+ EXECUTE format('GRANT USAGE ON SCHEMA opengeni_host_export TO %I', ${literal(role)});
1525
+ EXECUTE format('GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA opengeni_host_export TO %I', ${literal(role)});
1526
+ EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA opengeni_host_export GRANT EXECUTE ON FUNCTIONS TO %I', ${literal(role)});
1527
+ END IF;
1528
+ END $$;
1529
+ `);
1530
+ }
1531
+ async function grantArtifactCapabilityRoleIfSchemaExists(sql2, role, dataSchema, capability) {
1532
+ const routines = capability === "outbox" ? [
1533
+ "claim_editable_artifact_live_outbox(text,integer,integer,name)",
1534
+ "mark_editable_artifact_live_outbox_published(text,text,integer,name)",
1535
+ "renew_editable_artifact_live_outbox(text,text,integer,integer,name)",
1536
+ "retry_editable_artifact_live_outbox(text,text,integer,integer,text,name)",
1537
+ "dead_letter_editable_artifact_live_outbox(text,text,integer,text,name)",
1538
+ "release_editable_artifact_live_outbox(text,text,integer,name)"
1539
+ ] : [
1540
+ "claim_editable_artifact_materializations(text,integer,integer,name)",
1541
+ "renew_editable_artifact_materialization(uuid,uuid,text,text,text,integer,integer,name)",
1542
+ "succeed_editable_artifact_materialization(uuid,uuid,text,text,text,integer,text,text,text,bigint,text,text,timestamp with time zone,name)",
1543
+ "fail_editable_artifact_materialization(uuid,uuid,text,text,text,integer,text,name)"
1544
+ ];
1545
+ const routineArray = `ARRAY[${routines.map(literal).join(", ")}]`;
1546
+ await sql2.unsafe(`
1547
+ DO $$
1548
+ DECLARE routine_signature text;
1549
+ BEGIN
1550
+ IF EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = ${literal(dataSchema)})
1551
+ AND EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = 'opengeni_private')
1552
+ THEN
1553
+ EXECUTE format('GRANT CONNECT ON DATABASE %I TO %I', current_database(), ${literal(role)});
1554
+ EXECUTE format('GRANT USAGE ON SCHEMA %I TO %I', ${literal(dataSchema)}, ${literal(role)});
1555
+ EXECUTE format('GRANT USAGE ON SCHEMA opengeni_private TO %I', ${literal(role)});
1556
+ EXECUTE format(
1557
+ 'REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA %I FROM %I',
1558
+ ${literal(dataSchema)}, ${literal(role)}
1559
+ );
1560
+ EXECUTE format(
1561
+ 'REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA %I FROM %I',
1562
+ ${literal(dataSchema)}, ${literal(role)}
1563
+ );
1564
+ EXECUTE format(
1565
+ 'REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA opengeni_private FROM %I',
1566
+ ${literal(role)}
1567
+ );
1568
+ FOREACH routine_signature IN ARRAY ${routineArray} LOOP
1569
+ IF to_regprocedure('opengeni_private.' || routine_signature) IS NOT NULL THEN
1570
+ EXECUTE format(
1571
+ 'GRANT EXECUTE ON FUNCTION opengeni_private.%s TO %I',
1572
+ routine_signature, ${literal(role)}
1573
+ );
1574
+ END IF;
1575
+ END LOOP;
1576
+ END IF;
1577
+ END $$;
1578
+ `);
1579
+ }
1580
+ async function ensureLoginRole(sql2, role, password) {
1581
+ await sql2.unsafe(`
1582
+ DO $$
1583
+ BEGIN
1584
+ IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${literal(role)}) THEN
1585
+ EXECUTE format('CREATE ROLE %I LOGIN PASSWORD %L', ${literal(role)}, ${literal(password)});
1586
+ ELSE
1587
+ EXECUTE format('ALTER ROLE %I LOGIN PASSWORD %L', ${literal(role)}, ${literal(password)});
1588
+ END IF;
1589
+ END $$;
1590
+ `);
1591
+ }
1592
+ async function ensureRestrictedAppLoginRole(sql2, role, password) {
1593
+ await sql2.unsafe(`
1594
+ DO $$
1595
+ BEGIN
1596
+ IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${literal(role)}) THEN
1597
+ EXECUTE format(
1598
+ 'CREATE ROLE %I WITH LOGIN NOSUPERUSER NOBYPASSRLS NOCREATEROLE NOCREATEDB NOREPLICATION NOINHERIT PASSWORD %L',
1599
+ ${literal(role)},
1600
+ ${literal(password)}
1601
+ );
1602
+ ELSIF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = current_user AND rolsuper) THEN
1603
+ EXECUTE format(
1604
+ 'ALTER ROLE %I WITH LOGIN NOSUPERUSER NOBYPASSRLS NOCREATEROLE NOCREATEDB NOREPLICATION NOINHERIT PASSWORD %L',
1605
+ ${literal(role)},
1606
+ ${literal(password)}
1607
+ );
1608
+ ELSE
1609
+ -- PostgreSQL requires elevated attributes merely to name SUPERUSER,
1610
+ -- BYPASSRLS, REPLICATION, or CREATEDB in ALTER ROLE, even when setting them
1611
+ -- false. The preflight has already proved those protected attributes are
1612
+ -- false, so a managed CREATEROLE administrator converges only the
1613
+ -- attributes it may change.
1614
+ EXECUTE format(
1615
+ 'ALTER ROLE %I WITH LOGIN NOCREATEROLE NOINHERIT PASSWORD %L',
1616
+ ${literal(role)},
1617
+ ${literal(password)}
1618
+ );
1619
+ END IF;
1620
+ END $$;
1621
+ `);
1622
+ }
1623
+ async function assertAppRoleSafeToNormalize(sql2, role) {
1624
+ const exists = await sql2`
1625
+ select exists(select 1 from pg_roles where rolname = ${role}) as exists
1626
+ `;
1627
+ if (!exists[0]?.exists) {
1628
+ return;
1629
+ }
1630
+ const [roleAttributes] = await sql2`
1631
+ select
1632
+ administrator.rolsuper as administrator_superuser,
1633
+ app.rolsuper as app_superuser,
1634
+ app.rolbypassrls as app_bypass_rls,
1635
+ app.rolcreatedb as app_create_database,
1636
+ app.rolreplication as app_replication
1637
+ from pg_roles app
1638
+ join pg_roles administrator on administrator.rolname = current_user
1639
+ where app.rolname = ${role}
1640
+ `;
1641
+ if (roleAttributes && !roleAttributes.administrator_superuser) {
1642
+ const protectedAttributes = [
1643
+ roleAttributes.app_superuser ? "SUPERUSER" : null,
1644
+ roleAttributes.app_bypass_rls ? "BYPASSRLS" : null,
1645
+ roleAttributes.app_create_database ? "CREATEDB" : null,
1646
+ roleAttributes.app_replication ? "REPLICATION" : null
1647
+ ].filter((attribute) => attribute !== null);
1648
+ if (protectedAttributes.length > 0) {
1649
+ throw new Error(
1650
+ `Refusing to normalize app role ${role}: a non-superuser administrator cannot clear protected attributes (${protectedAttributes.join(", ")})`
1651
+ );
1652
+ }
1653
+ }
1654
+ const relationshipRows = await sql2.unsafe(
1655
+ roleRelationshipsCatalogQuery("$1"),
1656
+ [role]
1657
+ );
1658
+ const { unsafeRelationships } = classifyRoleRelationships(relationshipRows);
1659
+ if (unsafeRelationships.length > 0) {
1660
+ throw new Error(
1661
+ `Refusing to normalize app role ${role}: remove privilege-bearing role relationships first (${unsafeRelationships.join(", ")})`
1662
+ );
1663
+ }
1664
+ const ownedObjects = await sql2`
1665
+ select ('database:' || d.datname)::text as object_name
1666
+ from pg_database d
1667
+ join pg_roles owner on owner.oid = d.datdba
1668
+ where owner.rolname = ${role}
1669
+ union all
1670
+ select ('schema:' || n.nspname)::text as object_name
1671
+ from pg_namespace n
1672
+ join pg_roles owner on owner.oid = n.nspowner
1673
+ where owner.rolname = ${role}
1674
+ and n.nspname <> 'information_schema'
1675
+ and n.nspname !~ '^pg_'
1676
+ union all
1677
+ select ('relation:' || n.nspname || '.' || c.relname)::text as object_name
1678
+ from pg_class c
1679
+ join pg_namespace n on n.oid = c.relnamespace
1680
+ join pg_roles owner on owner.oid = c.relowner
1681
+ where owner.rolname = ${role}
1682
+ and n.nspname <> 'information_schema'
1683
+ and n.nspname !~ '^pg_'
1684
+ union all
1685
+ select (
1686
+ 'routine:' || n.nspname || '.' || p.proname || '(' ||
1687
+ pg_get_function_identity_arguments(p.oid) || ')'
1688
+ )::text as object_name
1689
+ from pg_proc p
1690
+ join pg_namespace n on n.oid = p.pronamespace
1691
+ join pg_roles owner on owner.oid = p.proowner
1692
+ where owner.rolname = ${role}
1693
+ and n.nspname <> 'information_schema'
1694
+ and n.nspname !~ '^pg_'
1695
+ order by object_name
1696
+ `;
1697
+ if (ownedObjects.length > 0) {
1698
+ throw new Error(
1699
+ `Refusing to normalize app role ${role}: transfer owned objects first (${ownedObjects.map((row) => row.object_name).join(", ")})`
1700
+ );
1701
+ }
1702
+ }
1703
+ async function ensureDatabase(sql2, database, owner) {
1704
+ const existing = await sql2`
1705
+ select exists(select 1 from pg_database where datname = ${database}) as exists
1706
+ `;
1707
+ if (!existing[0]?.exists) {
1708
+ await sql2.unsafe(`CREATE DATABASE ${identifier(database)} OWNER ${identifier(owner)}`);
1709
+ }
1710
+ await sql2.unsafe(
1711
+ `GRANT ALL PRIVILEGES ON DATABASE ${identifier(database)} TO ${identifier(owner)}`
1712
+ );
1713
+ }
1714
+ async function grantTemporalRoleInDatabase(adminConnection, database, role) {
1715
+ const databaseUrl = databaseUrlFor(adminConnection, database);
1716
+ const databaseSql = postgres(databaseUrl, { max: 1 });
1717
+ try {
1718
+ await databaseSql.unsafe(`GRANT USAGE, CREATE ON SCHEMA public TO ${identifier(role)}`);
1719
+ } finally {
1720
+ await databaseSql.end();
1721
+ }
1722
+ }
1723
+ async function grantAppRoleIfSchemaExists(sql2, role, schema) {
1724
+ const runtimeFullDmlTables = `ARRAY[${RUNTIME_FULL_DML_TABLES.map(literal).join(", ")}]`;
1725
+ const runtimeReadOnlyTables = `ARRAY[${RUNTIME_READ_ONLY_TABLES.map(literal).join(", ")}]`;
1726
+ const runtimeReadUpdateTables = `ARRAY[${RUNTIME_READ_UPDATE_TABLES.map(literal).join(", ")}]`;
1727
+ const runtimeReadInsertTables = `ARRAY[${RUNTIME_READ_INSERT_TABLES.map(literal).join(", ")}]`;
1728
+ const runtimeReadInsertUpdateTables = `ARRAY[${RUNTIME_READ_INSERT_UPDATE_TABLES.map(literal).join(", ")}]`;
1729
+ await sql2.unsafe(`
1730
+ DO $$
1731
+ DECLARE
1732
+ owner_role text := current_user;
1733
+ runtime_table text;
1734
+ BEGIN
1735
+ EXECUTE format('REVOKE CREATE ON DATABASE %I FROM %I', current_database(), ${literal(role)});
1736
+ IF EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = ${literal(schema)}) THEN
1737
+ EXECUTE format('GRANT USAGE ON SCHEMA %I TO %I', ${literal(schema)}, ${literal(role)});
1738
+ EXECUTE format('REVOKE CREATE ON SCHEMA %I FROM %I', ${literal(schema)}, ${literal(role)});
1739
+ EXECUTE format('REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA %I FROM %I', ${literal(schema)}, ${literal(role)});
1740
+ FOREACH runtime_table IN ARRAY ${runtimeFullDmlTables} LOOP
1741
+ IF to_regclass(format('%I.%I', ${literal(schema)}, runtime_table)) IS NOT NULL THEN
1742
+ EXECUTE format(
1743
+ 'GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE %I.%I TO %I',
1744
+ ${literal(schema)},
1745
+ runtime_table,
1746
+ ${literal(role)}
1747
+ );
1748
+ END IF;
1749
+ END LOOP;
1750
+ FOREACH runtime_table IN ARRAY ${runtimeReadOnlyTables} LOOP
1751
+ IF to_regclass(format('%I.%I', ${literal(schema)}, runtime_table)) IS NOT NULL THEN
1752
+ EXECUTE format(
1753
+ 'GRANT SELECT ON TABLE %I.%I TO %I',
1754
+ ${literal(schema)},
1755
+ runtime_table,
1756
+ ${literal(role)}
1757
+ );
1758
+ END IF;
1759
+ END LOOP;
1760
+ FOREACH runtime_table IN ARRAY ${runtimeReadUpdateTables} LOOP
1761
+ IF to_regclass(format('%I.%I', ${literal(schema)}, runtime_table)) IS NOT NULL THEN
1762
+ EXECUTE format(
1763
+ 'GRANT SELECT, UPDATE ON TABLE %I.%I TO %I',
1764
+ ${literal(schema)},
1765
+ runtime_table,
1766
+ ${literal(role)}
1767
+ );
1768
+ END IF;
1769
+ END LOOP;
1770
+ FOREACH runtime_table IN ARRAY ${runtimeReadInsertTables} LOOP
1771
+ IF to_regclass(format('%I.%I', ${literal(schema)}, runtime_table)) IS NOT NULL THEN
1772
+ EXECUTE format(
1773
+ 'GRANT SELECT, INSERT ON TABLE %I.%I TO %I',
1774
+ ${literal(schema)},
1775
+ runtime_table,
1776
+ ${literal(role)}
1777
+ );
1778
+ END IF;
1779
+ END LOOP;
1780
+ FOREACH runtime_table IN ARRAY ${runtimeReadInsertUpdateTables} LOOP
1781
+ IF to_regclass(format('%I.%I', ${literal(schema)}, runtime_table)) IS NOT NULL THEN
1782
+ EXECUTE format(
1783
+ 'GRANT SELECT, INSERT, UPDATE ON TABLE %I.%I TO %I',
1784
+ ${literal(schema)},
1785
+ runtime_table,
1786
+ ${literal(role)}
1787
+ );
1788
+ END IF;
1789
+ END LOOP;
1790
+ -- Migration 0110 creates this target-schema-local SECURITY DEFINER
1791
+ -- capability before opengeni_app may exist. Re-converge its exact EXECUTE
1792
+ -- grant here so the supported migrate-then-provision order is equivalent to
1793
+ -- provisioning the role before that migration.
1794
+ IF to_regprocedure(
1795
+ format('%I.lock_nested_agent_depth_configuration()', ${literal(schema)})
1796
+ ) IS NOT NULL THEN
1797
+ EXECUTE format(
1798
+ 'GRANT EXECUTE ON FUNCTION %I.lock_nested_agent_depth_configuration() TO %I',
1799
+ ${literal(schema)},
1800
+ ${literal(role)}
1801
+ );
1802
+ END IF;
1803
+ IF to_regprocedure(
1804
+ format(
1805
+ '%I.preference_registry_apply_lifecycle(text,uuid,integer,uuid,uuid,text,uuid,text,text)',
1806
+ ${literal(schema)}
1807
+ )
1808
+ ) IS NOT NULL THEN
1809
+ EXECUTE format(
1810
+ 'GRANT EXECUTE ON FUNCTION %I.preference_registry_apply_lifecycle(text, uuid, integer, uuid, uuid, text, uuid, text, text) TO %I',
1811
+ ${literal(schema)},
1812
+ ${literal(role)}
1813
+ );
1814
+ END IF;
1815
+ IF to_regprocedure(
1816
+ format('%I.preference_registry_lock_heads(uuid[])', ${literal(schema)})
1817
+ ) IS NOT NULL THEN
1818
+ EXECUTE format(
1819
+ 'GRANT EXECUTE ON FUNCTION %I.preference_registry_lock_heads(uuid[]) TO %I',
1820
+ ${literal(schema)},
1821
+ ${literal(role)}
1822
+ );
1823
+ END IF;
1824
+ IF to_regprocedure(
1825
+ format(
1826
+ '%I.knowledge_memory_apply_operation(jsonb,text,text,text,uuid,uuid,uuid,integer)',
1827
+ ${literal(schema)}
1828
+ )
1829
+ ) IS NOT NULL THEN
1830
+ EXECUTE format(
1831
+ 'GRANT EXECUTE ON FUNCTION %I.knowledge_memory_apply_operation(jsonb, text, text, text, uuid, uuid, uuid, integer) TO %I',
1832
+ ${literal(schema)},
1833
+ ${literal(role)}
1834
+ );
1835
+ END IF;
1836
+ IF to_regprocedure(
1837
+ format(
1838
+ '%I.knowledge_memory_revert_operation(uuid,uuid,text,text,text,uuid,uuid,uuid,integer)',
1839
+ ${literal(schema)}
1840
+ )
1841
+ ) IS NOT NULL THEN
1842
+ EXECUTE format(
1843
+ 'GRANT EXECUTE ON FUNCTION %I.knowledge_memory_revert_operation(uuid, uuid, text, text, text, uuid, uuid, uuid, integer) TO %I',
1844
+ ${literal(schema)},
1845
+ ${literal(role)}
1846
+ );
1847
+ END IF;
1848
+ IF to_regprocedure(
1849
+ format(
1850
+ '%I.preference_registry_get_or_create_snapshot(uuid,uuid,uuid,uuid,uuid,integer)',
1851
+ ${literal(schema)}
1852
+ )
1853
+ ) IS NOT NULL THEN
1854
+ EXECUTE format(
1855
+ 'GRANT EXECUTE ON FUNCTION %I.preference_registry_get_or_create_snapshot(uuid, uuid, uuid, uuid, uuid, integer) TO %I',
1856
+ ${literal(schema)},
1857
+ ${literal(role)}
1858
+ );
1859
+ END IF;
1860
+ IF to_regprocedure(
1861
+ format(
1862
+ '%I.create_task_note_for_attempt(uuid,uuid,uuid,uuid,uuid,integer,uuid,text,text,integer)',
1863
+ ${literal(schema)}
1864
+ )
1865
+ ) IS NOT NULL THEN
1866
+ EXECUTE format(
1867
+ 'GRANT EXECUTE ON FUNCTION %I.create_task_note_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid, text, text, integer) TO %I',
1868
+ ${literal(schema)},
1869
+ ${literal(role)}
1870
+ );
1871
+ EXECUTE format(
1872
+ 'GRANT EXECUTE ON FUNCTION %I.archive_task_note_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid, uuid, integer, text) TO %I',
1873
+ ${literal(schema)},
1874
+ ${literal(role)}
1875
+ );
1876
+ EXECUTE format(
1877
+ 'GRANT EXECUTE ON FUNCTION %I.list_task_notes_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, boolean, integer) TO %I',
1878
+ ${literal(schema)},
1879
+ ${literal(role)}
1880
+ );
1881
+ END IF;
1882
+ IF to_regprocedure(
1883
+ format(
1884
+ '%I.workspace_instruction_policy_get_or_create_snapshot(uuid,uuid,uuid,uuid,uuid,integer)',
1885
+ ${literal(schema)}
1886
+ )
1887
+ ) IS NOT NULL THEN
1888
+ EXECUTE format(
1889
+ 'GRANT EXECUTE ON FUNCTION %I.workspace_instruction_policy_get_or_create_snapshot(uuid, uuid, uuid, uuid, uuid, integer) TO %I',
1890
+ ${literal(schema)},
1891
+ ${literal(role)}
1892
+ );
1893
+ END IF;
1894
+ IF to_regprocedure(
1895
+ format(
1896
+ '%I.company_profile_apply_activation(uuid,text,uuid,uuid,uuid,uuid,bigint,text,text,text,text)',
1897
+ ${literal(schema)}
1898
+ )
1899
+ ) IS NOT NULL THEN
1900
+ EXECUTE format(
1901
+ 'GRANT EXECUTE ON FUNCTION %I.company_profile_apply_activation(uuid, text, uuid, uuid, uuid, uuid, bigint, text, text, text, text) TO %I',
1902
+ ${literal(schema)},
1903
+ ${literal(role)}
1904
+ );
1905
+ END IF;
1906
+ IF to_regprocedure(
1907
+ format(
1908
+ '%I.company_profile_get_or_create_snapshot(uuid,uuid,uuid,uuid,uuid,integer)',
1909
+ ${literal(schema)}
1910
+ )
1911
+ ) IS NOT NULL THEN
1912
+ EXECUTE format(
1913
+ 'GRANT EXECUTE ON FUNCTION %I.company_profile_get_or_create_snapshot(uuid, uuid, uuid, uuid, uuid, integer) TO %I',
1914
+ ${literal(schema)},
1915
+ ${literal(role)}
1916
+ );
1917
+ END IF;
1918
+ IF to_regprocedure(
1919
+ format(
1920
+ '%I.workspace_learning_policy_apply_activation(uuid,text,uuid,uuid,uuid,uuid,bigint,text,text,text)',
1921
+ ${literal(schema)}
1922
+ )
1923
+ ) IS NOT NULL THEN
1924
+ EXECUTE format(
1925
+ 'GRANT EXECUTE ON FUNCTION %I.workspace_learning_policy_apply_activation(uuid, text, uuid, uuid, uuid, uuid, bigint, text, text, text) TO %I',
1926
+ ${literal(schema)},
1927
+ ${literal(role)}
1928
+ );
1929
+ END IF;
1930
+ IF to_regprocedure(
1931
+ format('%I.workspace_learning_policy_source_overrides_valid(jsonb)', ${literal(schema)})
1932
+ ) IS NOT NULL THEN
1933
+ EXECUTE format(
1934
+ 'GRANT EXECUTE ON FUNCTION %I.workspace_learning_policy_source_overrides_valid(jsonb) TO %I',
1935
+ ${literal(schema)},
1936
+ ${literal(role)}
1937
+ );
1938
+ END IF;
1939
+ IF to_regprocedure(
1940
+ format('%I.workspace_learning_policy_hash(text,jsonb)', ${literal(schema)})
1941
+ ) IS NOT NULL THEN
1942
+ EXECUTE format(
1943
+ 'GRANT EXECUTE ON FUNCTION %I.workspace_learning_policy_hash(text, jsonb) TO %I',
1944
+ ${literal(schema)},
1945
+ ${literal(role)}
1946
+ );
1947
+ END IF;
1948
+ IF to_regprocedure(
1949
+ format(
1950
+ '%I.workspace_learning_policy_get_or_create_snapshot(uuid,uuid,uuid,uuid,uuid,integer)',
1951
+ ${literal(schema)}
1952
+ )
1953
+ ) IS NOT NULL THEN
1954
+ EXECUTE format(
1955
+ 'GRANT EXECUTE ON FUNCTION %I.workspace_learning_policy_get_or_create_snapshot(uuid, uuid, uuid, uuid, uuid, integer) TO %I',
1956
+ ${literal(schema)},
1957
+ ${literal(role)}
1958
+ );
1959
+ END IF;
1960
+ IF to_regprocedure(
1961
+ format(
1962
+ '%I.slack_task_policy_update(uuid,text,uuid,uuid,jsonb,uuid,bigint,text,text)',
1963
+ ${literal(schema)}
1964
+ )
1965
+ ) IS NOT NULL THEN
1966
+ EXECUTE format(
1967
+ 'GRANT EXECUTE ON FUNCTION %I.slack_task_policy_update(uuid, text, uuid, uuid, jsonb, uuid, bigint, text, text) TO %I',
1968
+ ${literal(schema)},
1969
+ ${literal(role)}
1970
+ );
1971
+ END IF;
1972
+ IF to_regprocedure(
1973
+ format(
1974
+ '%I.scoped_knowledge_apply_lifecycle(uuid,text,uuid,text,bigint,text,text,text,text,text,text)',
1975
+ ${literal(schema)}
1976
+ )
1977
+ ) IS NOT NULL THEN
1978
+ EXECUTE format(
1979
+ 'GRANT EXECUTE ON FUNCTION %I.scoped_knowledge_apply_lifecycle(uuid, text, uuid, text, bigint, text, text, text, text, text, text) TO %I',
1980
+ ${literal(schema)},
1981
+ ${literal(role)}
1982
+ );
1983
+ END IF;
1984
+ -- Migration 0197 creates this target-schema-local SECURITY DEFINER lock
1985
+ -- before opengeni_app may exist. Re-converge only its exact EXECUTE grant
1986
+ -- for the supported migrate-then-provision install order; keep PUBLIC
1987
+ -- revoked and do not widen table privileges.
1988
+ IF to_regprocedure(
1989
+ format(
1990
+ '%I.knowledge_source_sync_lock_authority(uuid,uuid,uuid)',
1991
+ ${literal(schema)}
1992
+ )
1993
+ ) IS NOT NULL THEN
1994
+ EXECUTE format(
1995
+ 'REVOKE ALL ON FUNCTION %I.knowledge_source_sync_lock_authority(uuid, uuid, uuid) FROM PUBLIC',
1996
+ ${literal(schema)}
1997
+ );
1998
+ EXECUTE format(
1999
+ 'GRANT EXECUTE ON FUNCTION %I.knowledge_source_sync_lock_authority(uuid, uuid, uuid) TO %I',
2000
+ ${literal(schema)},
2001
+ ${literal(role)}
2002
+ );
2003
+ END IF;
2004
+ IF to_regprocedure(
2005
+ format(
2006
+ '%I.ensure_managed_human_personal_workspace(uuid,text,uuid)',
2007
+ ${literal(schema)}
2008
+ )
2009
+ ) IS NOT NULL THEN
2010
+ EXECUTE format(
2011
+ 'REVOKE ALL ON FUNCTION %I.ensure_managed_human_personal_workspace(uuid, text, uuid) FROM PUBLIC',
2012
+ ${literal(schema)}
2013
+ );
2014
+ EXECUTE format(
2015
+ 'GRANT EXECUTE ON FUNCTION %I.ensure_managed_human_personal_workspace(uuid, text, uuid) TO %I',
2016
+ ${literal(schema)},
2017
+ ${literal(role)}
2018
+ );
2019
+ END IF;
2020
+ IF to_regprocedure(format('%I.ensure_canonical_human_identity(text,text)', ${literal(schema)})) IS NOT NULL THEN
2021
+ EXECUTE format(
2022
+ 'REVOKE ALL ON FUNCTION %I.ensure_canonical_human_identity(text, text) FROM PUBLIC',
2023
+ ${literal(schema)}
2024
+ );
2025
+ EXECUTE format(
2026
+ 'GRANT EXECUTE ON FUNCTION %I.ensure_canonical_human_identity(text, text) TO %I',
2027
+ ${literal(schema)},
2028
+ ${literal(role)}
2029
+ );
2030
+ END IF;
2031
+ IF to_regprocedure(format('%I.validate_canonical_human_session(text,text,boolean)', ${literal(schema)})) IS NOT NULL THEN
2032
+ EXECUTE format(
2033
+ 'REVOKE ALL ON FUNCTION %I.validate_canonical_human_session(text, text, boolean) FROM PUBLIC',
2034
+ ${literal(schema)}
2035
+ );
2036
+ EXECUTE format(
2037
+ 'GRANT EXECUTE ON FUNCTION %I.validate_canonical_human_session(text, text, boolean) TO %I',
2038
+ ${literal(schema)},
2039
+ ${literal(role)}
2040
+ );
2041
+ END IF;
2042
+ IF to_regprocedure(format('%I.get_canonical_human_identity_projection(text)', ${literal(schema)})) IS NOT NULL THEN
2043
+ EXECUTE format(
2044
+ 'REVOKE ALL ON FUNCTION %I.get_canonical_human_identity_projection(text) FROM PUBLIC',
2045
+ ${literal(schema)}
2046
+ );
2047
+ EXECUTE format(
2048
+ 'GRANT EXECUTE ON FUNCTION %I.get_canonical_human_identity_projection(text) TO %I',
2049
+ ${literal(schema)},
2050
+ ${literal(role)}
2051
+ );
2052
+ END IF;
2053
+ IF to_regprocedure(format('%I.apply_canonical_human_identity_operation(uuid,text,bigint,text,uuid,text,text,text)', ${literal(schema)})) IS NOT NULL THEN
2054
+ EXECUTE format(
2055
+ 'REVOKE ALL ON FUNCTION %I.apply_canonical_human_identity_operation(uuid, text, bigint, text, uuid, text, text, text) FROM PUBLIC',
2056
+ ${literal(schema)}
2057
+ );
2058
+ EXECUTE format(
2059
+ 'GRANT EXECUTE ON FUNCTION %I.apply_canonical_human_identity_operation(uuid, text, bigint, text, uuid, text, text, text) TO %I',
2060
+ ${literal(schema)},
2061
+ ${literal(role)}
2062
+ );
2063
+ END IF;
2064
+ -- Migration 0225 creates these target-schema-local session visibility
2065
+ -- capabilities before opengeni_app may exist. Re-converge their exact
2066
+ -- EXECUTE grants for migrate-then-provision installs without granting
2067
+ -- blanket execution on target-schema routines.
2068
+ IF to_regprocedure(
2069
+ format(
2070
+ '%I.session_private_actor_visible(uuid,uuid,uuid,text)',
2071
+ ${literal(schema)}
2072
+ )
2073
+ ) IS NOT NULL THEN
2074
+ EXECUTE format(
2075
+ 'REVOKE ALL ON FUNCTION %I.session_private_actor_visible(uuid, uuid, uuid, text) FROM PUBLIC',
2076
+ ${literal(schema)}
2077
+ );
2078
+ EXECUTE format(
2079
+ 'GRANT EXECUTE ON FUNCTION %I.session_private_actor_visible(uuid, uuid, uuid, text) TO %I',
2080
+ ${literal(schema)},
2081
+ ${literal(role)}
2082
+ );
2083
+ END IF;
2084
+ IF to_regprocedure(
2085
+ format(
2086
+ '%I.session_reference_visible(uuid,uuid,uuid)',
2087
+ ${literal(schema)}
2088
+ )
2089
+ ) IS NOT NULL THEN
2090
+ EXECUTE format(
2091
+ 'REVOKE ALL ON FUNCTION %I.session_reference_visible(uuid, uuid, uuid) FROM PUBLIC',
2092
+ ${literal(schema)}
2093
+ );
2094
+ EXECUTE format(
2095
+ 'GRANT EXECUTE ON FUNCTION %I.session_reference_visible(uuid, uuid, uuid) TO %I',
2096
+ ${literal(schema)},
2097
+ ${literal(role)}
2098
+ );
2099
+ END IF;
2100
+ IF to_regprocedure(
2101
+ format(
2102
+ '%I.transition_session_visibility(uuid,uuid,uuid,text,text,integer,text,text)',
2103
+ ${literal(schema)}
2104
+ )
2105
+ ) IS NOT NULL THEN
2106
+ EXECUTE format(
2107
+ 'REVOKE ALL ON FUNCTION %I.transition_session_visibility(uuid, uuid, uuid, text, text, integer, text, text) FROM PUBLIC',
2108
+ ${literal(schema)}
2109
+ );
2110
+ EXECUTE format(
2111
+ 'GRANT EXECUTE ON FUNCTION %I.transition_session_visibility(uuid, uuid, uuid, text, text, integer, text, text) TO %I',
2112
+ ${literal(schema)},
2113
+ ${literal(role)}
2114
+ );
2115
+ END IF;
2116
+ IF to_regprocedure(
2117
+ format(
2118
+ '%I.fork_session_content(uuid,uuid,uuid,text,uuid,text,text,text)',
2119
+ ${literal(schema)}
2120
+ )
2121
+ ) IS NOT NULL THEN
2122
+ EXECUTE format(
2123
+ 'REVOKE ALL ON FUNCTION %I.fork_session_content(uuid, uuid, uuid, text, uuid, text, text, text) FROM PUBLIC',
2124
+ ${literal(schema)}
2125
+ );
2126
+ EXECUTE format(
2127
+ 'GRANT EXECUTE ON FUNCTION %I.fork_session_content(uuid, uuid, uuid, text, uuid, text, text, text) TO %I',
2128
+ ${literal(schema)},
2129
+ ${literal(role)}
2130
+ );
2131
+ END IF;
2132
+ IF to_regprocedure(
2133
+ format(
2134
+ '%I.create_xai_subscription_credential(uuid,uuid,text,text,text,text,text,text,text,timestamptz)',
2135
+ ${literal(schema)}
2136
+ )
2137
+ ) IS NOT NULL THEN
2138
+ EXECUTE format(
2139
+ 'REVOKE ALL ON FUNCTION %I.create_xai_subscription_credential(uuid, uuid, text, text, text, text, text, text, text, timestamptz) FROM PUBLIC',
2140
+ ${literal(schema)}
2141
+ );
2142
+ EXECUTE format(
2143
+ 'GRANT EXECUTE ON FUNCTION %I.create_xai_subscription_credential(uuid, uuid, text, text, text, text, text, text, text, timestamptz) TO %I',
2144
+ ${literal(schema)},
2145
+ ${literal(role)}
2146
+ );
2147
+ EXECUTE format(
2148
+ 'REVOKE ALL ON FUNCTION %I.disconnect_xai_subscription_credential(uuid, uuid, text, uuid, jsonb) FROM PUBLIC',
2149
+ ${literal(schema)}
2150
+ );
2151
+ EXECUTE format(
2152
+ 'GRANT EXECUTE ON FUNCTION %I.disconnect_xai_subscription_credential(uuid, uuid, text, uuid, jsonb) TO %I',
2153
+ ${literal(schema)},
2154
+ ${literal(role)}
2155
+ );
2156
+ EXECUTE format(
2157
+ 'REVOKE ALL ON FUNCTION %I.resolve_xai_authority_pool(uuid, uuid, text, jsonb) FROM PUBLIC',
2158
+ ${literal(schema)}
2159
+ );
2160
+ EXECUTE format(
2161
+ 'GRANT EXECUTE ON FUNCTION %I.resolve_xai_authority_pool(uuid, uuid, text, jsonb) TO %I',
2162
+ ${literal(schema)},
2163
+ ${literal(role)}
2164
+ );
2165
+ EXECUTE format(
2166
+ 'REVOKE ALL ON FUNCTION %I.revalidate_xai_subscription_authority(uuid, text, uuid, jsonb) FROM PUBLIC',
2167
+ ${literal(schema)}
2168
+ );
2169
+ EXECUTE format(
2170
+ 'GRANT EXECUTE ON FUNCTION %I.revalidate_xai_subscription_authority(uuid, text, uuid, jsonb) TO %I',
2171
+ ${literal(schema)},
2172
+ ${literal(role)}
2173
+ );
2174
+ EXECUTE format(
2175
+ 'REVOKE ALL ON FUNCTION %I.xai_provider_account_authority_snapshot_v1_valid(jsonb) FROM PUBLIC',
2176
+ ${literal(schema)}
2177
+ );
2178
+ EXECUTE format(
2179
+ 'GRANT EXECUTE ON FUNCTION %I.xai_provider_account_authority_snapshot_v1_valid(jsonb) TO %I',
2180
+ ${literal(schema)},
2181
+ ${literal(role)}
2182
+ );
2183
+ EXECUTE format(
2184
+ 'REVOKE ALL ON FUNCTION %I.xai_subscription_authority_live(uuid, uuid, text, uuid, text, uuid, uuid, bigint) FROM PUBLIC',
2185
+ ${literal(schema)}
2186
+ );
2187
+ EXECUTE format(
2188
+ 'GRANT EXECUTE ON FUNCTION %I.xai_subscription_authority_live(uuid, uuid, text, uuid, text, uuid, uuid, bigint) TO %I',
2189
+ ${literal(schema)},
2190
+ ${literal(role)}
2191
+ );
2192
+ EXECUTE format(
2193
+ 'REVOKE ALL ON FUNCTION %I.xai_subscription_pool_visible(uuid, uuid, text, text, uuid) FROM PUBLIC',
2194
+ ${literal(schema)}
2195
+ );
2196
+ EXECUTE format(
2197
+ 'GRANT EXECUTE ON FUNCTION %I.xai_subscription_pool_visible(uuid, uuid, text, text, uuid) TO %I',
2198
+ ${literal(schema)},
2199
+ ${literal(role)}
2200
+ );
2201
+ END IF;
2202
+ IF to_regprocedure(
2203
+ format(
2204
+ '%I.scoped_knowledge_advance_source_acl(uuid,uuid,bigint,bigint,uuid,text,text,text,text,text,text)',
2205
+ ${literal(schema)}
2206
+ )
2207
+ ) IS NOT NULL THEN
2208
+ EXECUTE format(
2209
+ 'GRANT EXECUTE ON FUNCTION %I.scoped_knowledge_advance_source_acl(uuid, uuid, bigint, bigint, uuid, text, text, text, text, text, text) TO %I',
2210
+ ${literal(schema)},
2211
+ ${literal(role)}
2212
+ );
2213
+ END IF;
2214
+ IF to_regprocedure(
2215
+ format(
2216
+ '%I.scoped_knowledge_complete_sync(uuid,uuid,text,text,timestamptz,jsonb,text,text,text)',
2217
+ ${literal(schema)}
2218
+ )
2219
+ ) IS NOT NULL THEN
2220
+ EXECUTE format(
2221
+ 'GRANT EXECUTE ON FUNCTION %I.scoped_knowledge_complete_sync(uuid, uuid, text, text, timestamptz, jsonb, text, text, text) TO %I',
2222
+ ${literal(schema)},
2223
+ ${literal(role)}
2224
+ );
2225
+ END IF;
2226
+ IF to_regprocedure(
2227
+ format(
2228
+ '%I.scoped_knowledge_advance_object_version(uuid,uuid,bigint,bigint,uuid,text,text,text,text,text,text)',
2229
+ ${literal(schema)}
2230
+ )
2231
+ ) IS NOT NULL THEN
2232
+ EXECUTE format(
2233
+ 'GRANT EXECUTE ON FUNCTION %I.scoped_knowledge_advance_object_version(uuid, uuid, bigint, bigint, uuid, text, text, text, text, text, text) TO %I',
2234
+ ${literal(schema)},
2235
+ ${literal(role)}
2236
+ );
2237
+ END IF;
2238
+ EXECUTE format('GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA %I TO %I', ${literal(schema)}, ${literal(role)});
2239
+ EXECUTE format(
2240
+ 'ALTER DEFAULT PRIVILEGES FOR ROLE %I IN SCHEMA %I REVOKE ALL PRIVILEGES ON TABLES FROM %I',
2241
+ owner_role,
2242
+ ${literal(schema)},
2243
+ ${literal(role)}
2244
+ );
2245
+ EXECUTE format(
2246
+ 'ALTER DEFAULT PRIVILEGES FOR ROLE %I IN SCHEMA %I GRANT USAGE, SELECT ON SEQUENCES TO %I',
2247
+ owner_role,
2248
+ ${literal(schema)},
2249
+ ${literal(role)}
2250
+ );
2251
+ END IF;
2252
+ IF EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = 'opengeni_private') THEN
2253
+ EXECUTE format('GRANT USAGE ON SCHEMA opengeni_private TO %I', ${literal(role)});
2254
+ EXECUTE format('REVOKE CREATE ON SCHEMA opengeni_private FROM %I', ${literal(role)});
2255
+ EXECUTE format('GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA opengeni_private TO %I', ${literal(role)});
2256
+ EXECUTE format(
2257
+ 'ALTER DEFAULT PRIVILEGES FOR ROLE %I IN SCHEMA opengeni_private REVOKE EXECUTE ON FUNCTIONS FROM %I',
2258
+ owner_role,
2259
+ ${literal(role)}
2260
+ );
2261
+ -- Global cross-workspace artifact workers are separate capabilities. Never
2262
+ -- let the generic tenant-scoped app role inherit them from the historical
2263
+ -- blanket grant of already-installed helpers.
2264
+ IF to_regprocedure('opengeni_private.claim_editable_artifact_live_outbox(text,integer,integer,name)') IS NOT NULL THEN
2265
+ EXECUTE format(
2266
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.claim_editable_artifact_live_outbox(text, integer, integer, name) FROM %I',
2267
+ ${literal(role)}
2268
+ );
2269
+ EXECUTE format(
2270
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.mark_editable_artifact_live_outbox_published(text, text, integer, name) FROM %I',
2271
+ ${literal(role)}
2272
+ );
2273
+ EXECUTE format(
2274
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.renew_editable_artifact_live_outbox(text, text, integer, integer, name) FROM %I',
2275
+ ${literal(role)}
2276
+ );
2277
+ EXECUTE format(
2278
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.retry_editable_artifact_live_outbox(text, text, integer, integer, text, name) FROM %I',
2279
+ ${literal(role)}
2280
+ );
2281
+ EXECUTE format(
2282
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.dead_letter_editable_artifact_live_outbox(text, text, integer, text, name) FROM %I',
2283
+ ${literal(role)}
2284
+ );
2285
+ EXECUTE format(
2286
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.release_editable_artifact_live_outbox(text, text, integer, name) FROM %I',
2287
+ ${literal(role)}
2288
+ );
2289
+ END IF;
2290
+ IF to_regprocedure('opengeni_private.claim_editable_artifact_materializations(text,integer,integer,name)') IS NOT NULL THEN
2291
+ EXECUTE format(
2292
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.claim_editable_artifact_materializations(text, integer, integer, name) FROM %I',
2293
+ ${literal(role)}
2294
+ );
2295
+ EXECUTE format(
2296
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.renew_editable_artifact_materialization(uuid, uuid, text, text, text, integer, integer, name) FROM %I',
2297
+ ${literal(role)}
2298
+ );
2299
+ EXECUTE format(
2300
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.succeed_editable_artifact_materialization(uuid, uuid, text, text, text, integer, text, text, text, bigint, text, text, timestamptz, name) FROM %I',
2301
+ ${literal(role)}
2302
+ );
2303
+ EXECUTE format(
2304
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.fail_editable_artifact_materialization(uuid, uuid, text, text, text, integer, text, name) FROM %I',
2305
+ ${literal(role)}
2306
+ );
2307
+ END IF;
2308
+ IF to_regprocedure('opengeni_private.consume_editable_artifact_live_ticket(text,name)') IS NOT NULL THEN
2309
+ EXECUTE format(
2310
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.resolve_editable_artifact_ticket_data_schema(name) FROM %I',
2311
+ ${literal(role)}
2312
+ );
2313
+ EXECUTE format(
2314
+ 'GRANT EXECUTE ON FUNCTION opengeni_private.put_editable_artifact_live_ticket(text, uuid, uuid, text, text, text, text, text, text, text, text, integer, text, boolean, integer, timestamptz, timestamptz, name) TO %I',
2315
+ ${literal(role)}
2316
+ );
2317
+ EXECUTE format(
2318
+ 'GRANT EXECUTE ON FUNCTION opengeni_private.consume_editable_artifact_live_ticket(text, name) TO %I',
2319
+ ${literal(role)}
2320
+ );
2321
+ EXECUTE format(
2322
+ 'GRANT EXECUTE ON FUNCTION opengeni_private.cleanup_expired_editable_artifact_live_tickets(integer, name) TO %I',
2323
+ ${literal(role)}
2324
+ );
2325
+ END IF;
2326
+ IF to_regprocedure('opengeni_private.authorize_editable_artifact_actor(uuid,uuid,text,text,text,text,text,text,integer,text,text,name)') IS NOT NULL THEN
2327
+ EXECUTE format(
2328
+ 'GRANT EXECUTE ON FUNCTION opengeni_private.authorize_editable_artifact_actor(uuid, uuid, text, text, text, text, text, text, integer, text, text, name) TO %I',
2329
+ ${literal(role)}
2330
+ );
2331
+ END IF;
2332
+ END IF;
2333
+ END $$;
2334
+ `);
2335
+ }
2336
+ function commaSeparated(value) {
2337
+ return value.split(",").map((item) => item.trim()).filter(Boolean);
2338
+ }
2339
+ function validateIdentifier(name, value) {
2340
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) {
2341
+ throw new Error(`${name} contains an invalid Postgres identifier: ${value}`);
2342
+ }
2343
+ return value;
2344
+ }
2345
+ function identifier(value) {
2346
+ return `"${value.replace(/"/g, '""')}"`;
2347
+ }
2348
+ function literal(value) {
2349
+ return `'${value.replace(/'/g, "''")}'`;
2350
+ }
2351
+ function databaseUrlFor(value, database) {
2352
+ const url = new URL(value);
2353
+ url.pathname = `/${database}`;
2354
+ return url.toString();
2355
+ }
2356
+ if (import.meta.main) {
2357
+ const adminUrl = process.env.OPENGENI_MIGRATIONS_DATABASE_URL ?? process.env.OPENGENI_DATABASE_ADMIN_URL ?? process.env.OPENGENI_DATABASE_URL;
2358
+ if (!adminUrl) {
2359
+ throw new Error(
2360
+ "OPENGENI_MIGRATIONS_DATABASE_URL, OPENGENI_DATABASE_ADMIN_URL, or OPENGENI_DATABASE_URL is required"
2361
+ );
2362
+ }
2363
+ const result = await provisionRoles(adminUrl, {
2364
+ ...process.env.OPENGENI_DB_SCHEMA?.trim() ? { targetSchema: process.env.OPENGENI_DB_SCHEMA.trim() } : {}
2365
+ });
2366
+ console.log(JSON.stringify(result, null, 2));
2367
+ }
2368
+
2369
+ export {
2370
+ RUNTIME_TARGET_SCHEMA_CAPABILITY_ROUTINES,
2371
+ RUNTIME_TARGET_SCHEMA_INVOKER_ROUTINES,
2372
+ FORCE_RLS_TABLES,
2373
+ NON_RLS_RUNTIME_TABLES,
2374
+ RUNTIME_FULL_DML_TABLES,
2375
+ RUNTIME_READ_ONLY_TABLES,
2376
+ RUNTIME_READ_UPDATE_TABLES,
2377
+ RUNTIME_READ_INSERT_TABLES,
2378
+ RUNTIME_READ_INSERT_UPDATE_TABLES,
2379
+ PROTECTED_NO_DIRECT_DML_TABLES,
2380
+ RUNTIME_TABLE_PRIVILEGES,
2381
+ RUNTIME_DML_TABLES,
2382
+ RuntimeDatabasePostureError,
2383
+ inspectRuntimeDatabasePosture,
2384
+ evaluateRuntimeDatabasePosture,
2385
+ assertRuntimeDatabasePosture,
2386
+ runtimeDatabaseReadyCheck,
2387
+ provisionRoles
2388
+ };
2389
+ //# sourceMappingURL=chunk-VKLB2ZGI.js.map