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