void 1.10.0 → 1.12.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 (355) hide show
  1. package/dist/{account-cmd-CZhbDfp4.mjs → account-cmd-D_0qJ9fx.mjs} +6 -6
  2. package/dist/{agents-DRo8gzni.mjs → agents-64FnLwxP.mjs} +6 -5
  3. package/dist/{application-analysis-Do1WaGAY.mjs → application-analysis-Cx2S63z5.mjs} +48 -22
  4. package/dist/{application-routing-DrOFahHO.mjs → application-routing-BAXpnawu.mjs} +1 -1
  5. package/dist/{assets-DZBd7yqh.mjs → assets-Br6_BeFJ.mjs} +34 -27
  6. package/dist/{ast-Cv0JwXqb.mjs → ast-BkPQu7A0.mjs} +5 -1
  7. package/dist/{auth-BN0NU9dz.mjs → auth-Boz0lrb3.mjs} +1 -1
  8. package/dist/{auth-CCk9Seol.mjs → auth-DlLDymuc.mjs} +24 -12
  9. package/dist/{auth-link-DFQTA1jN.mjs → auth-link-C97r9p2N.mjs} +6 -6
  10. package/dist/{auth-router-BOiaDmcQ.mjs → auth-router-BmzEgzYx.mjs} +5 -5
  11. package/dist/{better-auth-shared-BqsMzU14.d.mts → better-auth-shared-BS3pDQbT.d.mts} +11 -6
  12. package/dist/{better-auth-shared-DRHo5FoG.mjs → better-auth-shared-BcqDt-37.mjs} +7 -2
  13. package/dist/{build-cmd-BCiXgjn9.mjs → build-cmd-BaFsyZrz.mjs} +13 -12
  14. package/dist/{cache-CUulshOu.mjs → cache-xO711ATQ.mjs} +6 -6
  15. package/dist/{cancel-deploy-BHGZo6KC.mjs → cancel-deploy-Di11ynsr.mjs} +5 -5
  16. package/dist/{cf-access-pejlJmuy.mjs → cf-access-DmkKPcAI.mjs} +0 -8
  17. package/dist/{cf-access-Dnyw8KFY.mjs → cf-access-FaIm95jA.mjs} +8 -4
  18. package/dist/{cf-build-output-bBx1gDll.mjs → cf-build-output-Ca201_n1.mjs} +27 -25
  19. package/dist/cf-build-output-Dy7N0hQN.mjs +1 -0
  20. package/dist/{cf-command-values-Ccl-zRhl.mjs → cf-command-values-5BPBRc9Z.mjs} +1 -1
  21. package/dist/cf-config-migrate-D271BTiw.mjs +1664 -0
  22. package/dist/{cf-worker-settings-CARs4Wy9.mjs → cf-worker-settings-BBdlhm9U.mjs} +1 -1
  23. package/dist/cli/cli.mjs +1 -1
  24. package/dist/cli/cloudflare-operation-process.mjs +223 -16
  25. package/dist/cli/env-schema-probe.d.mts +3 -1
  26. package/dist/cli/env-schema-probe.mjs +7 -8
  27. package/dist/{cli-main-hM7rhIbB.mjs → cli-main-DlW6lB8s.mjs} +153 -91
  28. package/dist/{client-BEYbgqZw.mjs → client-DkYzDEC0.mjs} +1 -1
  29. package/dist/{client-aIv5UQf3.mjs → client-ImIe7Mjq.mjs} +192 -17
  30. package/dist/{cloudflare-auth-pNvmT6kL.mjs → cloudflare-auth-eWfhdZCk.mjs} +1 -1
  31. package/dist/{cloudflare-cmd-DLcgInCa.mjs → cloudflare-cmd-SsFlJe2B.mjs} +7 -8
  32. package/dist/{cloudflare-config-BfEfIEuY.mjs → cloudflare-config-D9UFH_A5.mjs} +2 -2
  33. package/dist/{cloudflare-connect-CMcKtA02.mjs → cloudflare-connect-BgpHcSg3.mjs} +3 -3
  34. package/dist/{cloudflare-operations-DLhn_Bom.mjs → cloudflare-operations-BF0PSErW.mjs} +40 -24
  35. package/dist/cloudflare-operations-dpRD-2Px.mjs +1 -0
  36. package/dist/cloudflare-process-60r4Z2Zf.mjs +671 -0
  37. package/dist/cloudflare-user-output-CCR99eQY.mjs +19 -0
  38. package/dist/collect-B6nlSnsb.mjs +1 -0
  39. package/dist/{collect-C6Blu9yw.mjs → collect-rNLybAnF.mjs} +3 -3
  40. package/dist/{config-Do7gJI3T.mjs → config-BFX5ZB1J.mjs} +5 -4
  41. package/dist/{config-CbKmMpHK.mjs → config-BSoW3QCB.mjs} +5 -5
  42. package/dist/{config-DuiDZbq7.d.mts → config-DA6ZbLXO.d.mts} +3 -1
  43. package/dist/{config-CtkCfPpv.mjs → config-DtjrUtPo.mjs} +1 -1
  44. package/dist/{config-qgt863GH.mjs → config-Dv5jri1-.mjs} +10 -6
  45. package/dist/config-entry.d.mts +1 -1
  46. package/dist/{connect-DM3yCNPG.mjs → connect-DDRQGfFE.mjs} +9 -9
  47. package/dist/{create-project-BkVGXGNt.mjs → create-project-CY7sP8sI.mjs} +7 -6
  48. package/dist/{create-project-C-hNdYvD.mjs → create-project-Dro3K-az.mjs} +1 -1
  49. package/dist/{db-DQAi7Ckr.mjs → db-DmlaWVBu.mjs} +166 -121
  50. package/dist/db-seed-loader-Bcz_SutQ.mjs +253 -0
  51. package/dist/{db-types-BpPYAx0B.mjs → db-types-B4Cf9dzR.mjs} +8 -2
  52. package/dist/{delete-BtVnPGO2.mjs → delete-Uuq9ch6o.mjs} +6 -6
  53. package/dist/{deploy-Cs93Af-d.mjs → deploy-B9E7_rHC.mjs} +235 -558
  54. package/dist/deploy-BB3rsZbP.mjs +2 -0
  55. package/dist/{deploy-managed-static-CZIx3cc1.mjs → deploy-managed-static-IKZyuc1W.mjs} +123 -198
  56. package/dist/deploy-security-notice-C3LalelR.mjs +192 -0
  57. package/dist/{deploy-transport-DT-ALuDj.mjs → deploy-transport-BKP_oV9q.mjs} +4 -4
  58. package/dist/deploy.mjs +10 -9
  59. package/dist/{dev-inbox-BiamQEAa.mjs → dev-inbox-ClVjKEHy.mjs} +1 -1
  60. package/dist/direct-r2-upload-DFXLWfXV.mjs +204 -0
  61. package/dist/discover-D2KGP3cR.mjs +1 -0
  62. package/dist/{discover-Vd18lHsj.mjs → discover-IcspacCg.mjs} +1 -1
  63. package/dist/{dispatch-DPEuEblR.mjs → dispatch-DIhDA3NI.mjs} +38 -17
  64. package/dist/{dist-Cp4b1_T9.mjs → dist-C47zy_kJ.mjs} +1 -1
  65. package/dist/{dist-STQXl8ck.mjs → dist-Cr_xGE_K.mjs} +73 -38
  66. package/dist/{domain-cOhYYiHU.mjs → domain-B_xY1yZ5.mjs} +8 -10
  67. package/dist/{dotenv-CEI8hapP.mjs → dotenv-BG6RQavH.mjs} +2 -2
  68. package/dist/{drizzle-DBSpPpU1.mjs → drizzle-BJDMPrj7.mjs} +35 -30
  69. package/dist/{drizzle-D4V_06-B.mjs → drizzle-CQ5jWuDL.mjs} +1 -1
  70. package/dist/{email-CnnDqvXV.mjs → email-BIC15L7a.mjs} +47 -32
  71. package/dist/{email-cloudflare-CCIoQueP.mjs → email-cloudflare-C447nOqq.mjs} +195 -109
  72. package/dist/{email-pattern-BYr-EFq5.mjs → email-pattern-bRna9MOJ.mjs} +2 -2
  73. package/dist/{entry-DMgR7XOf.mjs → entry-Bwb9ev8K.mjs} +13 -10
  74. package/dist/{env-5bphL5mV.mjs → env-DJPZYHT5.mjs} +8 -8
  75. package/dist/{env-UqS-21xi.mjs → env-EjHqc7m9.mjs} +1 -1
  76. package/dist/{env-types-WEZw5D-r.mjs → env-types-D2hBodXP.mjs} +2 -19
  77. package/dist/{env-validation-DfJ9Fzfa.mjs → env-validation-D-v5_CWL.mjs} +13 -13
  78. package/dist/{env-validation-ly_Q9Kgd.mjs → env-validation-j9pjCDfA.mjs} +1 -1
  79. package/dist/{error-pages-QNeBXiRR.mjs → error-pages-GORL6F_e.mjs} +1 -1
  80. package/dist/{fetch-CbI6lNnk.d.mts → fetch-CczQyIed.d.mts} +1 -1
  81. package/dist/{fetch-DdK9eGin.mjs → fetch-CiEsvjpP.mjs} +1 -1
  82. package/dist/{fetch-stream-DQAavFdm.mjs → fetch-stream-BIG5lHW6.mjs} +3 -4
  83. package/dist/{fetch-stream-DoED9atq.d.mts → fetch-stream-DRX8-83b.d.mts} +2 -2
  84. package/dist/gen-CQDiPi8m.mjs +1 -0
  85. package/dist/{gen-CjcH6DJS.mjs → gen-DiTZlDx8.mjs} +21 -18
  86. package/dist/{generate-BOp1g1H_.mjs → generate-C3ZAqCy-.mjs} +1 -1
  87. package/dist/{generate-CWb8aOsm.mjs → generate-Dq2Bgw75.mjs} +6 -6
  88. package/dist/{git-metadata-Cukp5kV5.mjs → git-metadata-BEokJ6US.mjs} +1 -1
  89. package/dist/{github-cmd-CVDLb51-.mjs → github-cmd-DPmby8x-.mjs} +14 -9
  90. package/dist/{handler-w_FAiIRu.mjs → handler-DCrDLzw2.mjs} +3 -3
  91. package/dist/has-own-key-D9QEnAkF.mjs +5 -0
  92. package/dist/{head-0o0QoREY.mjs → head-BwQ5kgqt.mjs} +5 -4
  93. package/dist/{head-CVO92KEx.d.mts → head-fUp8n_QJ.d.mts} +9 -4
  94. package/dist/{headers-Cyr87J6Z.mjs → headers-DqBsjDxg.mjs} +7 -7
  95. package/dist/{help-B1cH8518.mjs → help-9wfMyXHb.mjs} +146 -69
  96. package/dist/help-Dy3w4rPq.mjs +1 -0
  97. package/dist/{inbound-BHt4dIlL.d.mts → inbound-CwgZSqFI.d.mts} +9 -3
  98. package/dist/{inbound--OF7zkwX.mjs → inbound-feMn1Rxx.mjs} +7 -7
  99. package/dist/{index-CmqHYj2R.d.mts → index-8cAgNdb6.d.mts} +1 -1
  100. package/dist/{index-BTmhCDbw.d.mts → index-BQ5qYiAw.d.mts} +2 -2
  101. package/dist/{index-BESZTC1z.d.mts → index-BYcWajVp.d.mts} +2 -1
  102. package/dist/{index-BXdP39qx.d.mts → index-Dn2mkPr2.d.mts} +24 -23
  103. package/dist/index.d.mts +2 -2
  104. package/dist/index.mjs +351 -444
  105. package/dist/{info-BE3snw2_.mjs → info-BWEWaOBo.mjs} +4 -4
  106. package/dist/{init-BrS5MAiJ.mjs → init-BuTPVLPO.mjs} +737 -546
  107. package/dist/{isr-config-Czzb4mIq.mjs → isr-config-DiTnL9Tb.mjs} +5 -5
  108. package/dist/{link-BbzyrCBD.mjs → link-BiesPyT4.mjs} +7 -7
  109. package/dist/{list-DmppHjVc.mjs → list-CkonftPQ.mjs} +11 -7
  110. package/dist/{live-DvtxTUhW.mjs → live-dvGThbwy.mjs} +14 -17
  111. package/dist/{load-user-env-BltIJLtl.mjs → load-user-env-B8qC0Q2Y.mjs} +1 -1
  112. package/dist/{local-d1-DLxsKmkw.mjs → local-d1-CYOYkVwO.mjs} +3 -3
  113. package/dist/{login-Cihxnu7m.mjs → login-BSOSah1j.mjs} +8 -6
  114. package/dist/login-DWCZeCX9.mjs +1 -0
  115. package/dist/{logs-BCgLeLNd.mjs → logs-HOBUnroa.mjs} +9 -9
  116. package/dist/{migrate-DOK67gE-.mjs → migrate-BNZL1hee.mjs} +9 -10
  117. package/dist/migrate-C9aoWLvY.mjs +1 -0
  118. package/dist/{migrations-ByS7r3HV.mjs → migrations-CUHhX65Y.mjs} +15 -12
  119. package/dist/{mime-BGoZ8ZLL.mjs → mime-Btw9R3CC.mjs} +26 -12
  120. package/dist/{mysql-sql-SlpS6OMg.mjs → mysql-sql-CB52k8tQ.mjs} +45 -22
  121. package/dist/nitro.d.mts +3 -0
  122. package/dist/nitro.mjs +14 -5
  123. package/dist/{node-qXD3FbIU.mjs → node-DVJWfV6s.mjs} +6 -6
  124. package/dist/node-buffer-D7kgjaDs.mjs +4 -0
  125. package/dist/{operator-ai-logging-CNuX5uKg.mjs → operator-ai-logging-ZDqqhnIq.mjs} +11 -10
  126. package/dist/operator-args-DCkWbgT-.mjs +1499 -0
  127. package/dist/{operator-auth-CD3pap65.mjs → operator-auth-BjoPLgja.mjs} +2 -2
  128. package/dist/{operator-client-XvXTkea6.mjs → operator-client-DzebIntv.mjs} +3 -3
  129. package/dist/{operator-cmd-D0vSUVle.mjs → operator-cmd-AZoeI9Pl.mjs} +28 -12
  130. package/dist/operator-cmd-DEnHFmJF.mjs +1 -0
  131. package/dist/operator-security-Bo26FP01.mjs +263 -0
  132. package/dist/{output-DNVILSz2.mjs → output-BZLnu0z8.mjs} +39 -4
  133. package/dist/output-D7K9TWIA.mjs +1 -0
  134. package/dist/{package-json-DvS6IFRv.mjs → package-json-4xUI3xLz.mjs} +1 -1
  135. package/dist/pages/client.d.mts +53 -30
  136. package/dist/pages/client.mjs +93 -31
  137. package/dist/pages/head.d.mts +1 -1
  138. package/dist/pages/head.mjs +1 -1
  139. package/dist/pages/index.d.mts +2 -2
  140. package/dist/pages/index.mjs +7 -7
  141. package/dist/pages/islands-plugin.d.mts +26 -8
  142. package/dist/pages/islands-plugin.mjs +61 -22
  143. package/dist/pages/protocol.d.mts +2 -2
  144. package/dist/pages/protocol.mjs +1 -1
  145. package/dist/pages/serialize.mjs +1 -1
  146. package/dist/{pgpass-CEtnBOZO.mjs → pgpass-BLPoYN9_.mjs} +3 -2
  147. package/dist/platform-args-DNbNZ_RR.mjs +1 -0
  148. package/dist/{platform-args-DQSMW4EP.mjs → platform-args-lwCyQ6Xy.mjs} +37 -9
  149. package/dist/{platform-auth-config-V2ifSLQ-.mjs → platform-auth-config-DLRMPw1G.mjs} +26 -23
  150. package/dist/{platform-auth-protection-BybVCUzi.mjs → platform-auth-protection-HSmLmD3d.mjs} +10 -10
  151. package/dist/{platform-auth-recovery-kH1-h8Ch.mjs → platform-auth-recovery-BXPhTlKa.mjs} +11 -9
  152. package/dist/{platform-cmd-B1jtqXnu.mjs → platform-cmd-CqRjxFEU.mjs} +1 -1
  153. package/dist/{platform-cmd-BHWdh1Hx.mjs → platform-cmd-DJ-fOYhL.mjs} +11 -11
  154. package/dist/{platform-discovery-B0eZjZ3B.mjs → platform-discovery-CLxtixHJ.mjs} +1 -1
  155. package/dist/{platform-domain-DB_KpVhg.mjs → platform-domain-CRsRJOws.mjs} +14 -10
  156. package/dist/{platform-lifecycle-BoOTmH6H.mjs → platform-lifecycle-bx_kpqo7.mjs} +1 -1
  157. package/dist/{platform-lifecycle-C6fUuj4y.mjs → platform-lifecycle-fau3VKv6.mjs} +773 -206
  158. package/dist/platform-management-BRGhD-oF.mjs +1 -0
  159. package/dist/{platform-management-B8-pOxoJ.mjs → platform-management-CnKBdDx5.mjs} +227 -58
  160. package/dist/{platform-plans-config-iczSDkQK.mjs → platform-plans-config-2C3_5EDs.mjs} +112 -35
  161. package/dist/{platform-recovery-ZAXin6WK.mjs → platform-recovery-poxgOOAY.mjs} +5 -5
  162. package/dist/{platform-registry-DZ_2Xuqd.mjs → platform-registry-DHH6fivm.mjs} +6 -5
  163. package/dist/{platform-setup-CpcHLI-0.mjs → platform-setup-DYylapHD.mjs} +26 -12
  164. package/dist/{plugin-inference-BGamcCqB.mjs → plugin-inference-7O11_E4H.mjs} +26 -26
  165. package/dist/{prepare-BrAkXTTB.mjs → prepare-BbvlKreR.mjs} +12 -12
  166. package/dist/prepare-BmG2E6TI.mjs +1 -0
  167. package/dist/{prepare-Cjt6EM0d.mjs → prepare-DWjn1Lzd.mjs} +3 -3
  168. package/dist/{project-cmd-wtCuc8Ln.mjs → project-cmd-DyUEFi2b.mjs} +30 -24
  169. package/dist/{project-CLwxcEdq.mjs → project-dh9431bN.mjs} +2 -2
  170. package/dist/{project-paths-CUhCPMpK.mjs → project-paths-2ENfCCih.mjs} +4 -3
  171. package/dist/project-security--tYGFPGo.mjs +1340 -0
  172. package/dist/project-security-DZEQgnsS.mjs +1 -0
  173. package/dist/{project-team-CZFvPIJ-.mjs → project-team-BszTHgzC.mjs} +8 -8
  174. package/dist/{project-token-C3TxkWeC.mjs → project-token-DBDy4NdV.mjs} +6 -6
  175. package/dist/{project-tsconfig-MyRJgufB.mjs → project-tsconfig-BOA4ym99.mjs} +25 -5
  176. package/dist/{project-DVsTAWFh.mjs → project-uXKua1it.mjs} +1 -1
  177. package/dist/project-zero-trust-D9sUouij.mjs +210 -0
  178. package/dist/{protocol-W5EQcIzN.mjs → protocol-CE3wP-H1.mjs} +5 -5
  179. package/dist/{protocol-BlAiF-hc.d.mts → protocol-ERy-n3jf.d.mts} +7 -4
  180. package/dist/{provision-CknEbPuw.mjs → provision-Bh44omGA.mjs} +39 -29
  181. package/dist/provision-DFv7SJDn.mjs +1 -0
  182. package/dist/{public-B80SwOFp.d.mts → public-DB9C2Cy_.d.mts} +5 -2
  183. package/dist/{raw-7pQirZpQ.mjs → raw-5rak34QN.mjs} +2 -1
  184. package/dist/{redirect-Dqb4fEc5.mjs → redirect-DD825Stf.mjs} +1 -1
  185. package/dist/{requests-FaA9M3RX.mjs → requests-CBokjiOi.mjs} +6 -6
  186. package/dist/{resolve-project-Da3OgCU1.mjs → resolve-project-8WZ3iVmr.mjs} +3 -3
  187. package/dist/resolve-project-YsTH-U9I.mjs +1 -0
  188. package/dist/{rollback-DM6pZ23Y.mjs → rollback-CEeHNFUn.mjs} +16 -7
  189. package/dist/route-types-CSed9-Dp.mjs +435 -0
  190. package/dist/{route-url-BBdkU7rb.mjs → route-url-B41eQ8QI.mjs} +1 -1
  191. package/dist/{route-url-Di1kB8D_.d.mts → route-url-Bd6IX-JZ.d.mts} +2 -1
  192. package/dist/routes-stub.d.mts +1 -1
  193. package/dist/routes-stub.mjs +1 -1
  194. package/dist/{runner-CTk21HrO.mjs → runner-Bf94YVJK.mjs} +1 -1
  195. package/dist/{runner-CMZb7jNU.mjs → runner-CeguHWJx.mjs} +3 -2
  196. package/dist/{runner-mysql-CJ-HyqxV.mjs → runner-mysql-3XDKrn-g.mjs} +13 -9
  197. package/dist/{runner-mysql-C_PrAUTm.mjs → runner-mysql-r688x6Y9.mjs} +1 -1
  198. package/dist/{runner-pg-mYc75KfH.mjs → runner-pg-Buzw17hl.mjs} +1 -1
  199. package/dist/{runner-pg-2pjltt0t.mjs → runner-pg-DMJquR3d.mjs} +1 -1
  200. package/dist/runtime/ai/index.d.mts +1 -0
  201. package/dist/runtime/ai/index.mjs +26 -11
  202. package/dist/runtime/auth/better-auth-d1.d.mts +1 -1
  203. package/dist/runtime/auth/better-auth-d1.mjs +2 -2
  204. package/dist/runtime/auth/better-auth-mysql.d.mts +1 -1
  205. package/dist/runtime/auth/better-auth-mysql.mjs +2 -2
  206. package/dist/runtime/auth/better-auth-postgres.d.mts +1 -1
  207. package/dist/runtime/auth/better-auth-postgres.mjs +3 -3
  208. package/dist/runtime/client/fetch-server.d.mts +1 -1
  209. package/dist/runtime/client/fetch-server.mjs +2 -2
  210. package/dist/runtime/client/fetch-stream.d.mts +2 -2
  211. package/dist/runtime/client/fetch-stream.mjs +1 -1
  212. package/dist/runtime/client/fetch.d.mts +1 -1
  213. package/dist/runtime/client/fetch.mjs +1 -1
  214. package/dist/runtime/client/index.d.mts +2 -2
  215. package/dist/runtime/client/index.mjs +2 -2
  216. package/dist/runtime/client/react.d.mts +2 -2
  217. package/dist/runtime/client/react.mjs +2 -2
  218. package/dist/runtime/client/solid.d.mts +2 -2
  219. package/dist/runtime/client/solid.mjs +2 -2
  220. package/dist/runtime/client/svelte.d.mts +2 -2
  221. package/dist/runtime/client/svelte.mjs +2 -2
  222. package/dist/runtime/client/vue.d.mts +2 -2
  223. package/dist/runtime/client/vue.mjs +2 -2
  224. package/dist/runtime/db/index.d.mts +8 -2
  225. package/dist/runtime/db/index.mjs +21 -8
  226. package/dist/runtime/db/migrations/mysql-handler.mjs +1 -1
  227. package/dist/runtime/db/migrations/postgres-handler.mjs +1 -1
  228. package/dist/runtime/db/session.d.mts +2 -0
  229. package/dist/runtime/db/session.mjs +1 -0
  230. package/dist/runtime/durable/index.mjs +7 -5
  231. package/dist/runtime/email/index.d.mts +1 -1
  232. package/dist/runtime/email/index.mjs +14 -11
  233. package/dist/runtime/email/testing.d.mts +1 -1
  234. package/dist/runtime/email/testing.mjs +4 -4
  235. package/dist/runtime/env/public-client.d.mts +4 -1
  236. package/dist/runtime/env/public.d.mts +1 -1
  237. package/dist/runtime/env/public.mjs +2 -2
  238. package/dist/runtime/env/runtime.mjs +1 -1
  239. package/dist/runtime/handler/index.d.mts +1 -1
  240. package/dist/runtime/handler/index.mjs +1 -1
  241. package/dist/runtime/handler/validator.d.mts +1 -1
  242. package/dist/runtime/handler/validator.mjs +1 -1
  243. package/dist/runtime/isr/index.mjs +1 -1
  244. package/dist/runtime/kv/index.mjs +1 -1
  245. package/dist/runtime/live/client.d.mts +2 -2
  246. package/dist/runtime/live/client.mjs +7 -7
  247. package/dist/runtime/live/index.d.mts +1 -1
  248. package/dist/runtime/live/index.mjs +1 -1
  249. package/dist/runtime/live/server.mjs +3 -3
  250. package/dist/runtime/queues/index.mjs +2 -2
  251. package/dist/runtime/remote/index.d.mts +5 -1
  252. package/dist/runtime/remote/index.mjs +10 -9
  253. package/dist/runtime/routing/index.d.mts +11 -12
  254. package/dist/runtime/routing/index.mjs +69 -65
  255. package/dist/runtime/routing/route-url.d.mts +1 -1
  256. package/dist/runtime/routing/route-url.mjs +1 -1
  257. package/dist/runtime/sandbox/index.d.mts +1 -1
  258. package/dist/runtime/sandbox/index.mjs +2 -2
  259. package/dist/runtime/sse/client.d.mts +1 -1
  260. package/dist/runtime/sse/index.mjs +1 -1
  261. package/dist/runtime/storage/index.mjs +1 -1
  262. package/dist/runtime/ws/index.d.mts +1 -1
  263. package/dist/runtime/ws/index.mjs +3 -2
  264. package/dist/runtime/ws/room.d.mts +1 -1
  265. package/dist/runtime/ws/room.mjs +2 -2
  266. package/dist/runtime/ws/server.d.mts +2 -2
  267. package/dist/runtime/ws/server.mjs +1 -1
  268. package/dist/{runtime-zDDinDI5.mjs → runtime-C_VPIJBF.mjs} +1 -1
  269. package/dist/{scan-tDExXbA1.mjs → scan-Ct_SEzH4.mjs} +36 -29
  270. package/dist/{secret-DDNLIQOT.mjs → secret-Deqo3n_N.mjs} +11 -10
  271. package/dist/security-api-types-CU7zQtr_.mjs +9 -0
  272. package/dist/security-sarif-ClyYwtAW.mjs +123 -0
  273. package/dist/{serialize-Pf-CIQK_.mjs → serialize-BmB4BfKu.mjs} +1 -1
  274. package/dist/{server-CfUbeOjx.mjs → server-T-4mn8zy.mjs} +5 -4
  275. package/dist/session-BT8XDkvL.mjs +45 -0
  276. package/dist/session-ouZYD7zb.d.mts +18 -0
  277. package/dist/{skills-CoBB9_Ao.mjs → skills-C-csz78e.mjs} +10 -17
  278. package/dist/{sse-BXnTfcf3.mjs → sse-D3ab0YQT.mjs} +16 -13
  279. package/dist/{static-exports-DFkzL-NX.mjs → static-exports-s7P86Ngp.mjs} +3 -3
  280. package/dist/{subcommand-prompt-0yIARXf2.mjs → subcommand-prompt-B4LOLosl.mjs} +31 -21
  281. package/dist/sveltekit.mjs +1 -1
  282. package/dist/{terminal-log-text-DNsWJREL.mjs → terminal-log-text-CfS2JKM6.mjs} +1 -1
  283. package/dist/{url-DaehRGKR.mjs → url-DBQluotE.mjs} +4 -1
  284. package/dist/validate-CZYUIfR-.mjs +1 -0
  285. package/dist/{validate-Ddzl-IwT.mjs → validate-CtBWCzez.mjs} +7 -4
  286. package/dist/{validator-Duafcnh7.mjs → validator-Dfh9kCDm.mjs} +5 -5
  287. package/dist/{version-metadata-DEmItNdS.mjs → version-metadata-DqgLa6gc.mjs} +1 -1
  288. package/dist/{wrangler-D1zq1rXr.mjs → wrangler-DVe5KV5G.mjs} +49 -46
  289. package/dist/wrangler-Dq269bjx.mjs +1 -0
  290. package/dist/{wrapper-C2gMY432.mjs → wrapper-CcMYpOS8.mjs} +45 -171
  291. package/docs/guide/ai.md +13 -0
  292. package/docs/guide/app-types.md +1 -1
  293. package/docs/guide/auth.md +2 -16
  294. package/docs/guide/database/d1.md +283 -3
  295. package/docs/guide/database.md +2 -0
  296. package/docs/guide/email/domains.md +8 -6
  297. package/docs/guide/email/sending.md +18 -1
  298. package/docs/guide/pages-routing/actions-and-forms.md +4 -4
  299. package/docs/guide/pages-routing/head.md +20 -2
  300. package/docs/guide/platform/administration/plans.md +13 -0
  301. package/docs/guide/platform/administration/security-audits.md +213 -0
  302. package/docs/guide/platform/administration/zero-trust.md +6 -0
  303. package/docs/guide/platform/development/local.md +3 -5
  304. package/docs/guide/platform/installation/ci.md +1 -1
  305. package/docs/guide/platform/installation/credentials.md +23 -20
  306. package/docs/guide/platform/installation/maintenance.md +8 -2
  307. package/docs/guide/platform/installation/prerequisites.md +1 -1
  308. package/docs/guide/platform/installation/uninstall.md +2 -0
  309. package/docs/guide/platform-administration.md +1 -0
  310. package/docs/guide/self-hosted-platform.md +14 -13
  311. package/docs/guide/type-safety.md +1 -1
  312. package/docs/integrations/cloudflare.md +5 -3
  313. package/docs/reference/api/database.md +42 -2
  314. package/docs/reference/api/handlers.md +3 -3
  315. package/docs/reference/api/types.md +11 -1
  316. package/docs/reference/api.md +1 -1
  317. package/docs/reference/cli/database.md +6 -3
  318. package/docs/reference/cli/deploy.md +17 -13
  319. package/docs/reference/cli/domains.md +1 -1
  320. package/docs/reference/cli/email.md +3 -3
  321. package/docs/reference/cli/platform-config.md +5 -3
  322. package/docs/reference/cli/platform-installation.md +29 -28
  323. package/docs/reference/cli/platform-security.md +98 -0
  324. package/docs/reference/cli/platform-zero-trust.md +2 -0
  325. package/docs/reference/cli/platform.md +1 -0
  326. package/docs/reference/cli/project.md +57 -0
  327. package/docs/reference/cli.md +3 -1
  328. package/docs/reference/config.md +7 -6
  329. package/package.json +31 -27
  330. package/schema.json +7 -1
  331. package/skills/void/SKILL.md +8 -0
  332. package/dist/cf-build-output-D3_x71H6.mjs +0 -1
  333. package/dist/cf-config-migrate-CHtnM3_C.mjs +0 -348
  334. package/dist/cloudflare-operations-C5RTQNnh.mjs +0 -1
  335. package/dist/cloudflare-process-wcnaQ5JG.mjs +0 -392
  336. package/dist/cloudflare-user-output-zEwuGrEJ.mjs +0 -19
  337. package/dist/collect-8i0wU63d.mjs +0 -1
  338. package/dist/deploy-rUunHBNJ.mjs +0 -2
  339. package/dist/discover-Diq0l6TZ.mjs +0 -1
  340. package/dist/gen-BQ7itmK7.mjs +0 -1
  341. package/dist/help-Ld6XFol7.mjs +0 -1
  342. package/dist/login-C-n1rA0s.mjs +0 -1
  343. package/dist/migrate-CKn30rmw.mjs +0 -1
  344. package/dist/operator-args-BCCohcz3.mjs +0 -722
  345. package/dist/operator-cmd-BnLoIO2A.mjs +0 -1
  346. package/dist/output-BsdnNpxa.mjs +0 -1
  347. package/dist/platform-args-Rgp86xa7.mjs +0 -1
  348. package/dist/platform-management-7Bf_OgS5.mjs +0 -1
  349. package/dist/prepare-CI7_C9Xf.mjs +0 -1
  350. package/dist/project-zero-trust-DrRyAHW1.mjs +0 -64
  351. package/dist/provision-DdWqRmmr.mjs +0 -1
  352. package/dist/resolve-project-C5wC-Hoi.mjs +0 -1
  353. package/dist/route-types-CrODgORq.mjs +0 -655
  354. package/dist/validate-DY1U9rET.mjs +0 -1
  355. package/dist/wrangler-DM3GOqck.mjs +0 -1
@@ -1,15 +1,17 @@
1
- import { A as confirm, H as outro, K as select, L as log, U as password, X as text$1, tt as isCancel, z as multiselect } from "./dist-STQXl8ck.mjs";
1
+ import { A as confirm, H as outro, K as select, L as log, U as password, X as text$1, tt as isCancel, z as multiselect } from "./dist-Cr_xGE_K.mjs";
2
2
  import { a as join, c as resolve, n as dirname } from "./dist-DMYe8CZJ.mjs";
3
- import { f as import_picocolors, l as formatUrl, m as printSuccess, n as cliCommandName, p as note, r as createSpinner, u as getErrorMessage } from "./output-DNVILSz2.mjs";
4
- import { t as cfAccessHeaders } from "./cf-access-pejlJmuy.mjs";
5
- import { o as createDefaultRunWrangler, v as resolvePinnedApiBaseUrl } from "./provision-CknEbPuw.mjs";
6
- import { a as platformManagementSetupPage, c as platformSetupLink, d as planWritesDns, i as platformInstallCommandArguments, l as platformSetupPages, n as formatPlatformSetupPlan, o as platformPromptAnswer, r as openPlatformSetupPage, s as platformSetupFieldHelp, t as formatPlatformInstallCommand, u as planCreatesZone } from "./platform-setup-CpcHLI-0.mjs";
7
- import { o as runCloudflareAuthCommand } from "./cloudflare-auth-pNvmT6kL.mjs";
8
- import { l as resolveCloudflareOperationArgv } from "./cloudflare-process-wcnaQ5JG.mjs";
9
- import { S as writePendingInstallationSecrets, a as latestPlatformWorkerCutoverGeneration, c as normalizePlatformApiUrl, d as platformRegistryDirectory, f as platformWorkerSecretUpdateIntentState, h as readPendingInstallationSecrets, m as readInstallationRecoverySecrets, n as assertPlatformInstallationSlugAvailable, o as listInstallationManifests, p as promoteInstallationSecrets, t as acquirePlatformLifecycleLock, v as resolveInstallationManifest, x as writeInstallationManifest, y as savePlatformConnection } from "./platform-registry-DZ_2Xuqd.mjs";
10
- import { t as ensurePlatformAccessToken } from "./cf-access-Dnyw8KFY.mjs";
3
+ import { t as Buffer } from "./node-buffer-D7kgjaDs.mjs";
4
+ import { a as createSpinner, f as formatUrl, g as note, h as import_picocolors, i as cliCommandName, p as getErrorMessage, y as printSuccess } from "./output-BZLnu0z8.mjs";
5
+ import { t as cfAccessHeaders } from "./cf-access-DmkKPcAI.mjs";
6
+ import { _ as resolvePinnedApiBaseUrl, o as createDefaultRunWrangler } from "./provision-Bh44omGA.mjs";
7
+ import { a as platformManagementSetupPage, c as platformSetupLink, d as planWritesDns, i as platformInstallCommandArguments, l as platformSetupPages, n as formatPlatformSetupPlan, o as platformPromptAnswer, r as openPlatformSetupPage, s as platformSetupFieldHelp, t as formatPlatformInstallCommand, u as planCreatesZone } from "./platform-setup-DYylapHD.mjs";
8
+ import { o as runCloudflareAuthCommand } from "./cloudflare-auth-eWfhdZCk.mjs";
9
+ import { l as resolveCloudflareOperationArgv } from "./cloudflare-process-60r4Z2Zf.mjs";
10
+ import { S as writePendingInstallationSecrets, a as latestPlatformWorkerCutoverGeneration, c as normalizePlatformApiUrl, d as platformRegistryDirectory, f as platformWorkerSecretUpdateIntentState, h as readPendingInstallationSecrets, m as readInstallationRecoverySecrets, n as assertPlatformInstallationSlugAvailable, o as listInstallationManifests, p as promoteInstallationSecrets, t as acquirePlatformLifecycleLock, v as resolveInstallationManifest, x as writeInstallationManifest, y as savePlatformConnection } from "./platform-registry-DHH6fivm.mjs";
11
+ import { t as hasOwnKey } from "./has-own-key-D9QEnAkF.mjs";
12
+ import { t as ensurePlatformAccessToken } from "./cf-access-FaIm95jA.mjs";
11
13
  import { i as updateProjectWorkerRuntimeLogs, n as assertPlatformRuntimeLogsSupported, r as shouldUpdateProjectWorkerRuntimeLogs } from "./platform-runtime-logs-CdJGnk3f.mjs";
12
- import { r as assertPlatformStorageSupported, t as parsePlatformArgs } from "./platform-args-DQSMW4EP.mjs";
14
+ import { r as assertPlatformStorageSupported, t as parsePlatformArgs } from "./platform-args-lwCyQ6Xy.mjs";
13
15
  import { t as writeFileAtomic } from "./atomic-write-DA6eD1Kp.mjs";
14
16
  import { copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
15
17
  import { fileURLToPath } from "node:url";
@@ -21,20 +23,111 @@ import { stripVTControlCharacters } from "node:util";
21
23
  import { readFile } from "node:fs/promises";
22
24
  import { cloudflareCommandDiagnostic, encodeCloudflareVersionMessage, parseCloudflareVersionMessage, readCloudflareTriggerConfig, readCloudflareVersionMigrationTag, stabilizeCloudflareVersionTriggers } from "@void/deploy-cloudflare";
23
25
  import { createServer, request } from "node:http";
24
- import { createDefaultPlanCatalog, parsePlatformPlanCatalog } from "@void/platform/plans";
25
26
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
27
+ import { createDefaultPlanCatalog, parsePlatformPlanCatalog } from "@void/platform/plans";
26
28
  import { AI_LOGGING_ORPHAN_GRACE_MS, PLAN_AI_LOGGING_SETTING, aiLoggingClearedKey, aiLoggingClearedMarker, aiLoggingKey, isPublishedAiLoggingMode, parseAiLoggingKeyMetadata, parsePlanAiLoggingSettings, planAiLogging, resolveAiLogging } from "@void/platform/ai-logging";
27
29
  import { PLATFORM_ADMIN_ASSETS_DIRECTORY, platformDatabaseSchemaDigest, resolvePlatformRuntime } from "@void/platform/installer";
28
30
  import { request as request$1 } from "node:https";
31
+ // src/cli/platform-credential-label.ts
32
+ const PLATFORM_RUNTIME_TOKEN_VARIABLE = "VOID_PLATFORM_RUNTIME_CLOUDFLARE_API_TOKEN";
33
+ const PLATFORM_AI_GATEWAY_PERMISSION = "Account → AI Gateway → Edit";
34
+ const PLATFORM_WORKERS_PERMISSION = "Account → Workers → Admin";
35
+ /** For example `management token from CLOUDFLARE_API_TOKEN`. */
36
+ function describePlatformCredential(label) {
37
+ if (label.source === "oauth") return "Cloudflare browser login";
38
+ const kind = credentialKind(label);
39
+ switch (label.source) {
40
+ case "environment": return `${kind} from ${fixVariable(label)}`;
41
+ case "saved": return `${kind} saved on this machine`;
42
+ case "entered": return `${kind} you entered`;
43
+ default: return kind;
44
+ }
45
+ }
46
+ /**
47
+ * What to tell the operator after Cloudflare answered 401 or 403 to one
48
+ * request made with this credential.
49
+ */
50
+ function platformCredentialHelp(label, status, requestPath) {
51
+ const permission = requestPath ? cloudflarePermissionForPath(requestPath) : void 0;
52
+ if (label.aiGatewayFor) return `${aiGatewayStandIn(label)} ${credentialAdvice(label, status, permission ? [permission] : [])}`;
53
+ if (label.source === "oauth" && permission === "Account → AI Gateway → Edit") return browserLoginAiGatewayHelp();
54
+ return `Void used the ${describePlatformCredential(label)}. ${credentialAdvice(label, status, permission ? [permission] : [])}`;
55
+ }
56
+ /**
57
+ * One message for every check Cloudflare denied to one credential: the list
58
+ * of missing permissions, then what to do.
59
+ */
60
+ function formatPlatformCredentialDenials(label, denials) {
61
+ const lines = [...new Set(denials.map((denial) => `- ${denial.permission} (HTTP ${denial.status}${denial.request ? `; ${denial.request}` : ""})`))];
62
+ const help = [];
63
+ if (label.aiGatewayFor) help.push(aiGatewayStandIn(label));
64
+ const rest = label.source === "oauth" ? denials.filter((denial) => denial.permission !== PLATFORM_AI_GATEWAY_PERMISSION) : denials;
65
+ if (rest.length < denials.length) help.push(browserLoginAiGatewayHelp());
66
+ if (rest.some((denial) => denial.status === 401)) help.push(credentialAdvice(label, 401, []));
67
+ const forbidden = [...new Set(rest.filter((denial) => denial.status !== 401).map((denial) => denial.permission))];
68
+ if (forbidden.length > 0) help.push(credentialAdvice(label, 403, forbidden));
69
+ return `Cloudflare denied the ${describePlatformCredential(label)}:\n${lines.join("\n")}\n${help.join(" ")}`;
70
+ }
71
+ /** The Cloudflare permission a request path needs, when Void knows it. */
72
+ function cloudflarePermissionForPath(requestPath) {
73
+ const parts = requestPath.split("?")[0].split("/").filter(Boolean);
74
+ if (parts[0] === "accounts") {
75
+ if (parts.length === 1) return "Account → Account Settings → Read";
76
+ const area = parts[2];
77
+ if (area === "ai-gateway") return PLATFORM_AI_GATEWAY_PERMISSION;
78
+ if (area === "storage" && parts[3] === "kv") return "Account → Workers KV Storage → Edit";
79
+ if (area === "r2") return "Account → Workers R2 Storage → Edit";
80
+ if (area === "queues") return "Account → Queues → Edit";
81
+ if (area === "hyperdrive") return "Account → Hyperdrive → Edit";
82
+ if (area === "workers") return PLATFORM_WORKERS_PERMISSION;
83
+ if (area === "email" && parts[3] === "routing") return "Account → Email Routing Addresses → Edit";
84
+ return;
85
+ }
86
+ if (parts[0] === "zones") {
87
+ if (parts.length <= 2) return "Zone → Zone → Read";
88
+ const area = parts[2];
89
+ if (area === "workers" && parts[3] === "routes") return "Zone → Workers Routes → Write";
90
+ if (area === "dns_records") return "Zone → DNS → Edit";
91
+ if (area === "purge_cache") return "Zone → Cache Purge → Purge";
92
+ if (area === "custom_hostnames") return "Zone → SSL and Certificates → Edit";
93
+ if (area === "email" && parts[3] === "routing") return parts[4] === "rules" ? "Zone → Email Routing Rules → Edit" : "Zone → Zone Settings → Edit";
94
+ }
95
+ }
96
+ function credentialKind(label) {
97
+ return label.role === "runtime" ? "runtime token" : "management token";
98
+ }
99
+ /** The variable that replaces this credential. */
100
+ function fixVariable(label) {
101
+ if (label.role === "runtime") return PLATFORM_RUNTIME_TOKEN_VARIABLE;
102
+ return label.source === "environment" && label.environmentVariable || "CLOUDFLARE_API_TOKEN";
103
+ }
104
+ function credentialAdvice(label, status, permissions) {
105
+ const variable = fixVariable(label);
106
+ const kind = credentialKind(label);
107
+ if (status === 401) return label.source === "oauth" ? "HTTP 401 means the browser login is no longer valid. Run `void cloudflare login` again, or set CLOUDFLARE_API_TOKEN to a management token for this account, then retry." : `HTTP 401 means Cloudflare did not accept the token: it is not valid, has expired, or was replaced. Set ${variable} to a valid ${kind}, then retry.`;
108
+ const missing = permissions.length > 1 ? "the permissions listed above" : permissions[0] ?? "a permission this request needs";
109
+ const them = permissions.length > 1 ? "them" : "it";
110
+ return label.source === "oauth" ? `HTTP 403 means browser login does not grant ${missing}. Set CLOUDFLARE_API_TOKEN to a management token with ${them} for this account, then retry.` : `HTTP 403 means the token works but is missing ${missing}, or is not scoped to this account or zone. Add ${them} to the token in the Cloudflare dashboard (the token value stays the same), or set ${variable} to a ${kind} that has ${them}, then retry.`;
111
+ }
112
+ function aiGatewayStandIn(label) {
113
+ const name = describePlatformCredential(label);
114
+ return label.aiGatewayFor?.source === "oauth" ? `Browser login cannot use AI Gateway, so Void used the ${name} for it. Fix the runtime token (${PLATFORM_RUNTIME_TOKEN_VARIABLE}), or set CLOUDFLARE_API_TOKEN to a management token with ${PLATFORM_AI_GATEWAY_PERMISSION}.` : `Void used the ${name} for AI Gateway. Fix the runtime token.`;
115
+ }
116
+ function browserLoginAiGatewayHelp() {
117
+ return `Browser login cannot use AI Gateway. Set ${PLATFORM_RUNTIME_TOKEN_VARIABLE} to the platform runtime token, or set CLOUDFLARE_API_TOKEN to a management token with ${PLATFORM_AI_GATEWAY_PERMISSION}, then retry.`;
118
+ }
29
119
  // src/cli/platform-cloudflare.ts
30
120
  var PlatformCloudflareApiError = class extends Error {
31
121
  status;
32
122
  requestPath;
33
- constructor(message, status, requestPath) {
123
+ /** The credential Cloudflare rejected, when the client knows it. */
124
+ credential;
125
+ constructor(message, status, requestPath, credential) {
34
126
  super(message);
35
127
  this.name = "PlatformCloudflareApiError";
36
128
  this.status = status;
37
129
  this.requestPath = requestPath;
130
+ if (credential) this.credential = credential;
38
131
  }
39
132
  };
40
133
  var PlatformCloudflarePrerequisiteError = class extends PlatformCloudflareApiError {
@@ -64,39 +157,59 @@ var PlatformWorkerRoutesChangedError = class extends Error {
64
157
  var PlatformRuntimeTokenEmailPermissionError = class extends Error {
65
158
  /** Cloudflare answered HTTP 401 at least once: it did not accept the token. */
66
159
  tokenNotValid;
67
- constructor(message, tokenNotValid, options) {
160
+ /** Each email check Cloudflare denied. */
161
+ denials;
162
+ constructor(message, tokenNotValid, options, denials = []) {
68
163
  super(message, options);
69
164
  this.name = "PlatformRuntimeTokenEmailPermissionError";
70
165
  this.tokenNotValid = tokenNotValid;
166
+ this.denials = denials;
71
167
  }
72
168
  };
73
169
  /** Largest number of pairs or keys one KV bulk request accepts. */
74
170
  const KV_BULK_LIMIT = 1e4;
75
171
  async function verifyPlatformRuntimeTokenPermissions(client, input) {
76
- try {
77
- await client.listHyperdriveConfigs(input.accountId);
172
+ const credential = input.credential ?? { role: "runtime" };
173
+ const denials = [];
174
+ let emailDenial;
175
+ const deniedError = () => denials.length === 0 ? emailDenial : new Error(`platform: ${formatPlatformCredentialDenials(credential, [...denials, ...emailDenial?.denials ?? []])}`, { cause: denials[0].error });
176
+ const check = async (permission, action) => {
177
+ try {
178
+ await action();
179
+ } catch (error) {
180
+ if (error instanceof PlatformCloudflareApiError && (error.status === 401 || error.status === 403)) {
181
+ denials.push({
182
+ error,
183
+ permission,
184
+ status: error.status
185
+ });
186
+ return;
187
+ }
188
+ throw deniedError() ?? runtimeTokenPreflightError(permission, error, credential);
189
+ }
190
+ };
191
+ await check("Account → Hyperdrive → Write", () => client.listHyperdriveConfigs(input.accountId));
192
+ if (input.emailZoneId) try {
193
+ await verifyPlatformRuntimeTokenEmailPermissions(client, {
194
+ accountId: input.accountId,
195
+ credential,
196
+ zoneId: input.emailZoneId
197
+ });
78
198
  } catch (error) {
79
- throw runtimeTokenPreflightError("Account → Hyperdrive → Write", error);
199
+ if (!(error instanceof PlatformRuntimeTokenEmailPermissionError)) throw error;
200
+ emailDenial = error;
80
201
  }
81
- if (input.emailZoneId) await verifyPlatformRuntimeTokenEmailPermissions(client, {
82
- accountId: input.accountId,
83
- zoneId: input.emailZoneId
84
- });
85
- if (!input.zoneId) return;
86
- const probeUrl = `https://${input.applicationDomain}/.well-known/void/runtime-token-preflight-${randomUUID()}`;
87
- try {
88
- await client.request(`/zones/${encodeURIComponent(input.zoneId)}/purge_cache`, {
202
+ if (input.zoneId) {
203
+ const zoneId = input.zoneId;
204
+ const probeUrl = `https://${input.applicationDomain}/.well-known/void/runtime-token-preflight-${randomUUID()}`;
205
+ await check("Zone → Cache Purge → Purge", () => client.request(`/zones/${encodeURIComponent(zoneId)}/purge_cache`, {
89
206
  body: JSON.stringify({ files: [probeUrl] }),
90
207
  method: "POST"
91
- });
92
- } catch (error) {
93
- throw runtimeTokenPreflightError("Zone → Cache Purge → Purge", error);
94
- }
95
- if (input.customDomains) try {
96
- await client.request(`/zones/${encodeURIComponent(input.zoneId)}/custom_hostnames?per_page=1`);
97
- } catch (error) {
98
- throw runtimeTokenPreflightError("Zone → SSL and Certificates → Edit", error);
208
+ }));
209
+ if (input.customDomains) await check("Zone → SSL and Certificates → Edit", () => client.request(`/zones/${encodeURIComponent(zoneId)}/custom_hostnames?per_page=1`));
99
210
  }
211
+ const denied = deniedError();
212
+ if (denied) throw denied;
100
213
  }
101
214
  /**
102
215
  * Shared email setup uses the runtime token after the platform pauses traffic.
@@ -112,26 +225,34 @@ async function verifyPlatformRuntimeTokenEmailPermissions(client, input) {
112
225
  ["Zone → Email Routing Rules → Edit", `${zone}/email/routing/rules?per_page=5`],
113
226
  ["Account → Email Routing Addresses → Edit", `/accounts/${encodeURIComponent(input.accountId)}/email/routing/addresses?per_page=5`]
114
227
  ];
115
- const missing = [];
228
+ const denials = [];
116
229
  let denial;
117
230
  let tokenNotValid = false;
118
231
  for (const [permission, path] of probes) try {
119
232
  await client.request(path);
120
233
  } catch (error) {
121
234
  if (error instanceof PlatformCloudflareApiError && (error.status === 401 || error.status === 403)) {
122
- missing.push(permission);
235
+ denials.push({
236
+ permission,
237
+ status: error.status
238
+ });
123
239
  denial ??= error;
124
240
  tokenNotValid ||= error.status === 401;
125
241
  }
126
242
  }
127
243
  if (denial) {
128
- const denied = `Cloudflare denied: ${missing.join(", ")} (HTTP ${denial.status}).`;
129
- throw new PlatformRuntimeTokenEmailPermissionError(input.savedToken ? `platform: The runtime API token saved on this machine cannot use platform email. ${denied} Void checked this token because VOID_PLATFORM_RUNTIME_CLOUDFLARE_API_TOKEN is not set. If the platform uses a different runtime token, set VOID_PLATFORM_RUNTIME_CLOUDFLARE_API_TOKEN to that token, and Void checks that token instead. Otherwise, check that the zone permissions of the saved token include the email zone ${input.zoneId}. To add a missing permission, edit the token in the Cloudflare dashboard. The token value stays the same. Then run the command again.` : `platform: The runtime API token cannot use platform email. ${denied} Check that the token is valid and that its zone permissions include the email zone ${input.zoneId}. To add a missing permission, edit the token in the Cloudflare dashboard. The token value stays the same. Or set VOID_PLATFORM_RUNTIME_CLOUDFLARE_API_TOKEN to a valid token that has these permissions. Then run the command again.`, tokenNotValid, { cause: denial });
244
+ const denied = `Cloudflare denied: ${denials.map((entry) => entry.permission).join(", ")} (HTTP ${denial.status}).`;
245
+ const name = describePlatformCredential(input.savedToken ? {
246
+ role: "runtime",
247
+ source: "saved"
248
+ } : input.credential ?? { role: "runtime" });
249
+ throw new PlatformRuntimeTokenEmailPermissionError(input.savedToken ? `platform: The ${name} cannot use platform email. ${denied} Void checked this token because VOID_PLATFORM_RUNTIME_CLOUDFLARE_API_TOKEN is not set. If the platform uses a different runtime token, set VOID_PLATFORM_RUNTIME_CLOUDFLARE_API_TOKEN to that token, and Void checks that token instead. Otherwise, check that the zone permissions of the saved token include the email zone ${input.zoneId}. To add a missing permission, edit the token in the Cloudflare dashboard. The token value stays the same. Then run the command again.` : `platform: The ${name} cannot use platform email. ${denied} Check that the token is valid and that its zone permissions include the email zone ${input.zoneId}. To add a missing permission, edit the token in the Cloudflare dashboard. The token value stays the same. Or set VOID_PLATFORM_RUNTIME_CLOUDFLARE_API_TOKEN to a valid token that has these permissions. Then run the command again.`, tokenNotValid, { cause: denial }, denials);
130
250
  }
131
251
  }
132
- function runtimeTokenPreflightError(permission, cause) {
252
+ function runtimeTokenPreflightError(permission, cause, credential) {
133
253
  const status = cause instanceof PlatformCloudflareApiError ? cause.status : null;
134
- const message = status === 401 || status === 403 ? `Cloudflare denied the runtime-token check (HTTP ${status}). Check that the token is valid, scoped to this account, and includes ${permission}.` : status === 429 ? `Cloudflare rate-limited the runtime-token check for ${permission} (HTTP 429). Retry shortly; this does not mean the token is missing a permission.` : `Could not complete the runtime-token check for ${permission}${status === null ? "" : ` (Cloudflare HTTP ${status})`}. Retry the check; this failure does not establish that a permission is missing.`;
254
+ const name = describePlatformCredential(credential);
255
+ const message = status === 429 ? `Cloudflare rate-limited the check of the ${name} for ${permission} (HTTP 429). Retry shortly; this does not mean the token is missing a permission.` : `Could not complete the check of the ${name} for ${permission}${status === null ? "" : ` (Cloudflare HTTP ${status})`}. Retry the check; this failure does not establish that a permission is missing.`;
135
256
  return new Error(`platform: ${message}`, { cause });
136
257
  }
137
258
  var PlatformCloudflareClient = class PlatformCloudflareClient {
@@ -139,36 +260,46 @@ var PlatformCloudflareClient = class PlatformCloudflareClient {
139
260
  #fetcher;
140
261
  #token;
141
262
  #aiGatewayClient;
263
+ #credential;
142
264
  constructor(token, options) {
143
265
  if (!token) throw new Error("platform: CLOUDFLARE_API_TOKEN is required. The installed control plane also uses this scoped token to provision app resources.");
144
266
  this.#token = token;
145
267
  this.apiBaseUrl = (options?.apiBase ?? resolvePinnedApiBaseUrl()).replace(/\/+$/, "");
146
268
  this.#fetcher = options?.fetcher ?? fetch;
147
- if (options?.aiGatewayToken) this.#aiGatewayClient = new PlatformCloudflareClient(options.aiGatewayToken, {
148
- apiBase: this.apiBaseUrl,
149
- fetcher: this.#fetcher
150
- });
269
+ this.#credential = options?.credential;
270
+ if (options?.aiGatewayToken) {
271
+ const aiGatewayCredential = options.aiGatewayCredential ?? { role: "runtime" };
272
+ this.#aiGatewayClient = new PlatformCloudflareClient(options.aiGatewayToken, {
273
+ apiBase: this.apiBaseUrl,
274
+ fetcher: this.#fetcher,
275
+ credential: {
276
+ ...aiGatewayCredential,
277
+ aiGatewayFor: this.#credential ?? { role: "management" }
278
+ }
279
+ });
280
+ }
151
281
  }
152
282
  /** Keep operator auth for infrastructure; use the existing runtime credential only for AI Gateway. */
153
- withAiGatewayToken(token) {
283
+ withAiGatewayToken(token, credential) {
154
284
  return new PlatformCloudflareClient(this.#token, {
155
285
  apiBase: this.apiBaseUrl,
156
286
  fetcher: this.#fetcher,
157
- aiGatewayToken: token
287
+ aiGatewayToken: token,
288
+ ...credential ? { aiGatewayCredential: credential } : {},
289
+ ...this.#credential ? { credential: this.#credential } : {}
158
290
  });
159
291
  }
160
292
  async request(path, init) {
161
293
  return (await this.#requestEnvelope(path, init)).result;
162
294
  }
163
295
  async #requestEnvelope(path, init) {
296
+ const headers = new Headers(init?.headers);
297
+ if (!headers.has("Accept")) headers.set("Accept", "application/json");
298
+ if (!headers.has("Authorization")) headers.set("Authorization", `Bearer ${this.#token}`);
299
+ if (typeof init?.body === "string" && !headers.has("Content-Type")) headers.set("Content-Type", "application/json");
164
300
  const response = await this.#fetcher(`${this.apiBaseUrl}${path}`, {
165
301
  ...init,
166
- headers: {
167
- Accept: "application/json",
168
- Authorization: `Bearer ${this.#token}`,
169
- ...typeof init?.body === "string" ? { "Content-Type": "application/json" } : {},
170
- ...init?.headers
171
- },
302
+ headers,
172
303
  signal: init?.signal ?? AbortSignal.timeout(3e4),
173
304
  redirect: "manual"
174
305
  });
@@ -181,7 +312,7 @@ var PlatformCloudflareClient = class PlatformCloudflareClient {
181
312
  if (!response.ok || envelope.success !== true || envelope.result === void 0) {
182
313
  const details = cloudflareErrorDetails(envelope, response.status);
183
314
  const requestPath = path.split("?")[0];
184
- const error = new PlatformCloudflareApiError(`Cloudflare API error: ${details} (HTTP ${response.status}; ${init?.method ?? "GET"} ${requestPath}).`, response.status, requestPath);
315
+ const error = this.#apiError(`Cloudflare API error: ${details} (HTTP ${response.status}; ${init?.method ?? "GET"} ${requestPath}).`, response.status, requestPath);
185
316
  const prerequisite = cloudflarePrerequisiteHelp(envelope, response.status, requestPath);
186
317
  if (prerequisite) throw new PlatformCloudflarePrerequisiteError(prerequisite, error);
187
318
  throw error;
@@ -191,6 +322,15 @@ var PlatformCloudflareClient = class PlatformCloudflareClient {
191
322
  resultInfo: envelope.result_info
192
323
  };
193
324
  }
325
+ /**
326
+ * An API error that, on 401 or 403, names the credential Cloudflare
327
+ * rejected and how to fix it. The error keeps its class, status and path:
328
+ * callers decide on those.
329
+ */
330
+ #apiError(message, status, requestPath) {
331
+ const credential = this.#credential && (status === 401 || status === 403) ? this.#credential : void 0;
332
+ return new PlatformCloudflareApiError(credential ? `${message} ${platformCredentialHelp(credential, status, requestPath)}` : message, status, requestPath, credential);
333
+ }
194
334
  async listAccounts() {
195
335
  const entries = [];
196
336
  for (let page = 1;; page++) {
@@ -209,9 +349,10 @@ var PlatformCloudflareClient = class PlatformCloudflareClient {
209
349
  try {
210
350
  result = await this.request(`/accounts/${encodeURIComponent(accountId)}/workers/subdomain`);
211
351
  } catch (error) {
212
- const status = error instanceof PlatformCloudflareApiError ? error.status : null;
352
+ const apiError = error instanceof PlatformCloudflareApiError ? error : void 0;
353
+ const status = apiError?.status ?? null;
213
354
  const reason = status === null ? "the request failed" : `HTTP ${status}`;
214
- const guidance = status === 401 || status === 403 ? "Check your Cloudflare login or API token permissions for this account, then rerun the command." : status === 404 ? `Open ${setupUrl} once to provision your account for Workers automatically, then retry the install.` : "Rerun the command. If the dashboard already shows a subdomain, no Workers onboarding change is needed.";
355
+ const guidance = status === 401 || status === 403 ? apiError?.credential ? platformCredentialHelp(apiError.credential, status, apiError.requestPath) : "Check your Cloudflare login or API token permissions for this account, then rerun the command." : status === 404 ? `Open ${setupUrl} once to provision your account for Workers automatically, then retry the install.` : "Rerun the command. If the dashboard already shows a subdomain, no Workers onboarding change is needed.";
215
356
  throw new Error(`platform: Could not read the workers.dev subdomain for account ${accountId} (${reason}). ${guidance}`, { cause: error });
216
357
  }
217
358
  if (typeof result?.subdomain !== "string" || result.subdomain.trim() === "") throw new Error(`platform: This Cloudflare account does not have a workers.dev subdomain. Open ${setupUrl}, finish Workers onboarding, choose a subdomain, and rerun the command.`);
@@ -553,6 +694,12 @@ var PlatformCloudflareClient = class PlatformCloudflareClient {
553
694
  body: JSON.stringify({ caching: { disabled: true } })
554
695
  });
555
696
  }
697
+ async setHyperdriveOriginConnectionLimit(accountId, id, limit) {
698
+ await this.request(`/accounts/${encodeURIComponent(accountId)}/hyperdrive/configs/${encodeURIComponent(id)}`, {
699
+ method: "PATCH",
700
+ body: JSON.stringify({ origin_connection_limit: limit })
701
+ });
702
+ }
556
703
  async putKvValue(accountId, namespaceId, key, value) {
557
704
  await this.request(`/accounts/${encodeURIComponent(accountId)}/storage/kv/namespaces/${encodeURIComponent(namespaceId)}/values/${encodeURIComponent(key)}`, {
558
705
  method: "PUT",
@@ -602,16 +749,18 @@ var PlatformCloudflareClient = class PlatformCloudflareClient {
602
749
  }), "delete");
603
750
  }
604
751
  async getKvValue(accountId, namespaceId, key) {
605
- const response = await this.#fetcher(`${this.apiBaseUrl}/accounts/${encodeURIComponent(accountId)}/storage/kv/namespaces/${encodeURIComponent(namespaceId)}/values/${encodeURIComponent(key)}`, {
752
+ const path = `/accounts/${encodeURIComponent(accountId)}/storage/kv/namespaces/${encodeURIComponent(namespaceId)}/values/${encodeURIComponent(key)}`;
753
+ const response = await this.#fetcher(`${this.apiBaseUrl}${path}`, {
606
754
  headers: { Authorization: `Bearer ${this.#token}` },
607
755
  signal: AbortSignal.timeout(3e4)
608
756
  });
609
757
  if (response.status === 404) return null;
610
- if (!response.ok) throw new PlatformCloudflareApiError(`Cloudflare API error reading the installation manifest (HTTP ${response.status}).`, response.status);
758
+ if (!response.ok) throw this.#apiError(`Cloudflare API error reading the installation manifest (HTTP ${response.status}).`, response.status, path);
611
759
  return response.text();
612
760
  }
613
761
  async putR2Object(accountId, bucketName, key, value) {
614
- const response = await this.#fetcher(`${this.apiBaseUrl}/accounts/${encodeURIComponent(accountId)}/r2/buckets/${encodeURIComponent(bucketName)}/objects/${encodeR2ObjectKey(key)}`, {
762
+ const path = `/accounts/${encodeURIComponent(accountId)}/r2/buckets/${encodeURIComponent(bucketName)}/objects/${encodeR2ObjectKey(key)}`;
763
+ const response = await this.#fetcher(`${this.apiBaseUrl}${path}`, {
615
764
  body: value,
616
765
  headers: {
617
766
  Authorization: `Bearer ${this.#token}`,
@@ -620,15 +769,16 @@ var PlatformCloudflareClient = class PlatformCloudflareClient {
620
769
  method: "PUT",
621
770
  signal: AbortSignal.timeout(3e4)
622
771
  });
623
- if (!response.ok) throw new PlatformCloudflareApiError(`Cloudflare API error writing the R2 ownership marker (HTTP ${response.status}).`, response.status);
772
+ if (!response.ok) throw this.#apiError(`Cloudflare API error writing the R2 ownership marker (HTTP ${response.status}).`, response.status, path);
624
773
  }
625
774
  async getR2Object(accountId, bucketName, key) {
626
- const response = await this.#fetcher(`${this.apiBaseUrl}/accounts/${encodeURIComponent(accountId)}/r2/buckets/${encodeURIComponent(bucketName)}/objects/${encodeR2ObjectKey(key)}`, {
775
+ const path = `/accounts/${encodeURIComponent(accountId)}/r2/buckets/${encodeURIComponent(bucketName)}/objects/${encodeR2ObjectKey(key)}`;
776
+ const response = await this.#fetcher(`${this.apiBaseUrl}${path}`, {
627
777
  headers: { Authorization: `Bearer ${this.#token}` },
628
778
  signal: AbortSignal.timeout(3e4)
629
779
  });
630
780
  if (response.status === 404) return null;
631
- if (!response.ok) throw new PlatformCloudflareApiError(`Cloudflare API error reading the R2 ownership marker (HTTP ${response.status}).`, response.status);
781
+ if (!response.ok) throw this.#apiError(`Cloudflare API error reading the R2 ownership marker (HTTP ${response.status}).`, response.status, path);
632
782
  return response.text();
633
783
  }
634
784
  async deleteR2Object(accountId, bucketName, key) {
@@ -675,7 +825,8 @@ var PlatformCloudflareClient = class PlatformCloudflareClient {
675
825
  for (;;) {
676
826
  const query = new URLSearchParams({ per_page: "1000" });
677
827
  if (cursor) query.set("cursor", cursor);
678
- const response = await this.#fetcher(`${this.apiBaseUrl}/accounts/${encodeURIComponent(accountId)}/r2/buckets/${encodeURIComponent(bucketName)}/objects?${query}`, {
828
+ const path = `/accounts/${encodeURIComponent(accountId)}/r2/buckets/${encodeURIComponent(bucketName)}/objects`;
829
+ const response = await this.#fetcher(`${this.apiBaseUrl}${path}?${query}`, {
679
830
  headers: {
680
831
  Accept: "application/json",
681
832
  Authorization: `Bearer ${this.#token}`
@@ -684,7 +835,10 @@ var PlatformCloudflareClient = class PlatformCloudflareClient {
684
835
  });
685
836
  if (response.status === 404) return;
686
837
  const envelope = await response.json();
687
- if (!response.ok || envelope.success !== true || !Array.isArray(envelope.result)) throw new PlatformCloudflareApiError(`Cloudflare API error listing R2 objects: ${envelope.errors?.map((error) => error.message).filter(Boolean).join(", ") || `HTTP ${response.status}`}`, response.status);
838
+ if (!response.ok || envelope.success !== true || !Array.isArray(envelope.result)) {
839
+ const details = envelope.errors?.map((error) => error.message).filter(Boolean).join(", ") || `HTTP ${response.status}`;
840
+ throw this.#apiError(`Cloudflare API error listing R2 objects: ${details}`, response.status, path);
841
+ }
688
842
  const keys = envelope.result.map((object) => requiredString(object.key, "R2 object key")).filter((key) => !preservedKeys.has(key));
689
843
  if (keys.length > 0) await beforeDelete?.();
690
844
  for (let offset = 0; offset < keys.length; offset += 1e3) await this.deleteR2Objects(accountId, bucketName, keys.slice(offset, offset + 1e3));
@@ -728,13 +882,13 @@ var PlatformCloudflareClient = class PlatformCloudflareClient {
728
882
  signal: AbortSignal.timeout(3e4)
729
883
  });
730
884
  if (response.status === 404) return;
731
- let envelope = {};
885
+ let envelope;
732
886
  try {
733
887
  envelope = await response.json();
734
888
  } catch {
735
889
  envelope = { success: response.ok };
736
890
  }
737
- if (!response.ok || envelope.success !== true) throw new PlatformCloudflareApiError(`Cloudflare API error: ${cloudflareErrorDetails(envelope, response.status)} (HTTP ${response.status}; DELETE ${path}).`, response.status, path);
891
+ if (!response.ok || envelope.success !== true) throw this.#apiError(`Cloudflare API error: ${cloudflareErrorDetails(envelope, response.status)} (HTTP ${response.status}; DELETE ${path}).`, response.status, path);
738
892
  }
739
893
  async deleteWorkerRoute(zoneId, routeId) {
740
894
  await this.#deleteIfPresent(`/zones/${encodeURIComponent(zoneId)}/workers/routes/${encodeURIComponent(routeId)}`);
@@ -819,10 +973,10 @@ var PlatformCloudflareClient = class PlatformCloudflareClient {
819
973
  entries.push(...result);
820
974
  if (result.length < 50) break;
821
975
  }
822
- return entries.filter((entry) => !(Array.isArray(entry.matchers) ? entry.matchers : []).some((matcher) => matcher?.type === "all")).map((entry) => ({
976
+ return entries.flatMap((entry) => !(Array.isArray(entry.matchers) ? entry.matchers : []).some((matcher) => matcher?.type === "all") ? [{
823
977
  id: requiredString(entry.id ?? entry.tag, "Email Routing rule id"),
824
978
  ...parseEmailRoutingTarget(entry)
825
- }));
979
+ }] : []);
826
980
  }
827
981
  async deleteEmailRoutingRule(zoneId, ruleId) {
828
982
  await this.#deleteIfPresent(`/zones/${encodeURIComponent(zoneId)}/email/routing/rules/${encodeURIComponent(ruleId)}`);
@@ -993,16 +1147,16 @@ function parseHyperdriveConfig(value) {
993
1147
  user: typeof record.user === "string" && record.user ? record.user : null
994
1148
  };
995
1149
  let parsedOrigin;
996
- if (record.service_id != null) {
1150
+ if (record.service_id !== null && record.service_id !== void 0) {
997
1151
  const serviceId = requiredString(record.service_id, "Hyperdrive origin service ID");
998
- if (record.host != null || record.port != null || record.access_client_id != null) throw new Error("platform: Cloudflare Hyperdrive config mixes Workers VPC and host origin fields.");
1152
+ if (record.host !== null && record.host !== void 0 || record.port !== null && record.port !== void 0 || record.access_client_id !== null && record.access_client_id !== void 0) throw new Error("platform: Cloudflare Hyperdrive config mixes Workers VPC and host origin fields.");
999
1153
  parsedOrigin = {
1000
1154
  ...database,
1001
1155
  serviceId
1002
1156
  };
1003
1157
  } else {
1004
1158
  const accessClientId = typeof record.access_client_id === "string" && record.access_client_id ? record.access_client_id : void 0;
1005
- const port = accessClientId && record.port == null ? null : typeof record.port === "number" || typeof record.port === "string" ? Number(record.port) : NaN;
1159
+ const port = accessClientId && (record.port === null || record.port === void 0) ? null : typeof record.port === "number" || typeof record.port === "string" ? Number(record.port) : NaN;
1006
1160
  if (port !== null && (!Number.isInteger(port) || port <= 0 || port > 65535)) throw new Error("platform: Cloudflare Hyperdrive config has an invalid origin port.");
1007
1161
  parsedOrigin = {
1008
1162
  ...database,
@@ -1015,7 +1169,8 @@ function parseHyperdriveConfig(value) {
1015
1169
  id: requiredString(value.id, "Hyperdrive id"),
1016
1170
  name: requiredString(value.name, "Hyperdrive name"),
1017
1171
  cachingDisabled: !!value.caching && typeof value.caching === "object" && !Array.isArray(value.caching) && value.caching.disabled === true,
1018
- origin: parsedOrigin
1172
+ origin: parsedOrigin,
1173
+ ...typeof value.origin_connection_limit === "number" && Number.isInteger(value.origin_connection_limit) && value.origin_connection_limit > 0 ? { originConnectionLimit: value.origin_connection_limit } : {}
1019
1174
  };
1020
1175
  }
1021
1176
  // src/cli/platform-access-provision.ts
@@ -1032,7 +1187,7 @@ function platformAccessIdentityProvider(provider) {
1032
1187
  const name = provider.name;
1033
1188
  return {
1034
1189
  id,
1035
- name: name == null || typeof name === "string" && !name.trim() ? id : text(name, "identity provider name")
1190
+ name: name === null || name === void 0 || typeof name === "string" && !name.trim() ? id : text(name, "identity provider name")
1036
1191
  };
1037
1192
  }
1038
1193
  function ids(value) {
@@ -1143,7 +1298,7 @@ function platformAccessPublicDestinations(application) {
1143
1298
  })];
1144
1299
  }
1145
1300
  function platformAccessOverlapsOrigin(destination, origin) {
1146
- const pattern = "^" + destination.split("/")[0].split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*") + "$";
1301
+ const pattern = "^" + destination.split("/")[0].split("*").map((part) => part.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`)).join(".*") + "$";
1147
1302
  return new RegExp(pattern, "i").test(new URL(origin).hostname);
1148
1303
  }
1149
1304
  /** Whether an application path-covers, or exactly covers, any protected platform origin. */
@@ -1212,16 +1367,17 @@ async function provisionPlatformAccess(client, input, previous, save) {
1212
1367
  const inventory = await client.list("apps");
1213
1368
  const tokenInventory = input.protection ? await client.list("service_tokens") : [];
1214
1369
  if (input.protection?.applicationId && !input.serviceToken) throw new Error("platform: Connecting an existing protection application requires its admitted service token.");
1215
- if (input.serviceToken) {
1216
- const token = tokenInventory.find((token) => token.id === input.serviceToken.id);
1217
- if (!token || token.client_id !== input.serviceToken.clientId || token.enabled === false || typeof token.expires_at === "string" && Date.parse(token.expires_at) <= Date.now()) throw new Error("platform: The selected Access service token is unavailable, expired, or belongs to another client.");
1370
+ const { serviceToken } = input;
1371
+ if (serviceToken) {
1372
+ const token = tokenInventory.find((token) => token.id === serviceToken.id);
1373
+ if (!token || token.client_id !== serviceToken.clientId || token.enabled === false || typeof token.expires_at === "string" && Date.parse(token.expires_at) <= Date.now()) throw new Error("platform: The selected Access service token is unavailable, expired, or belongs to another client.");
1218
1374
  const prior = state.resources["service-token"];
1219
1375
  state.resources["service-token"] = {
1220
- id: input.serviceToken.id,
1376
+ id: serviceToken.id,
1221
1377
  name: text(token.name, "service token name"),
1222
1378
  fingerprint: fingerprint({ origins }),
1223
1379
  pending: false,
1224
- adopted: prior?.id === input.serviceToken.id ? prior.adopted : true
1380
+ adopted: prior?.id === serviceToken.id ? prior.adopted : true
1225
1381
  };
1226
1382
  save(state);
1227
1383
  }
@@ -1399,13 +1555,15 @@ async function provisionPlatformAccess(client, input, previous, save) {
1399
1555
  const covered = platformAccessPublicDestinations(app);
1400
1556
  if (origins.some((origin) => !covered.includes(new URL(origin).hostname))) throw new Error("platform: Access must protect both the API and proxy origins without path exclusions.");
1401
1557
  const audience = text(app.aud, "application audience");
1402
- output.protection = parsePlatformAccessProtection({
1558
+ const protection = parsePlatformAccessProtection({
1403
1559
  teamDomain: inspected.teamDomain,
1404
1560
  applications: origins.map((origin) => ({
1405
1561
  origin,
1406
1562
  audience
1407
1563
  }))
1408
1564
  });
1565
+ if (!protection) throw new Error("platform: The Access protection configuration is missing.");
1566
+ output.protection = protection;
1409
1567
  output.credentials = Object.fromEntries(origins.map((origin) => [origin, {
1410
1568
  CF_ACCESS_CLIENT_ID: service.clientId,
1411
1569
  CF_ACCESS_CLIENT_SECRET: service.clientSecret
@@ -1497,6 +1655,7 @@ async function selectCompanyAccessPolicies(client, initialPolicies, accountId, m
1497
1655
  placeholder: "example.com",
1498
1656
  validate: (value) => companyEmailDomains(value ?? "") ? void 0 : "Enter up to 10 email domains, such as example.com."
1499
1657
  })));
1658
+ if (!domains) throw new Error("platform: Enter up to 10 email domains, such as example.com.");
1500
1659
  const name = `Emails ending in @${domains[0]}${domains.length > 1 ? ` and ${domains.length - 1} more` : ""}`;
1501
1660
  try {
1502
1661
  const created = await client.create("policies", {
@@ -1825,27 +1984,50 @@ async function preparePlatformAccessSetup(input) {
1825
1984
  return result;
1826
1985
  }
1827
1986
  // src/cli/platform-auth.ts
1987
+ /** The label of the operator credential, so Cloudflare errors can name it. */
1988
+ function platformOperatorCredentialLabel(credential) {
1989
+ return {
1990
+ role: "management",
1991
+ source: credential.source,
1992
+ ...credential.environmentVariable ? { environmentVariable: credential.environmentVariable } : {}
1993
+ };
1994
+ }
1828
1995
  /** Use the selected credential for read-only checks before taking lifecycle locks. */
1829
1996
  async function verifyPlatformCloudflareCredential(client, input) {
1830
- const source = input.source === "saved" ? "saved management token" : input.source === "environment" ? "environment API token" : "Cloudflare browser login";
1831
- const retry = input.source === "oauth" ? "Run `void cloudflare login`, or set CLOUDFLARE_API_TOKEN for this account, then retry." : "Set CLOUDFLARE_API_TOKEN for this account, then retry.";
1832
- const check = async (label, permission, action, allowMissing = false) => {
1997
+ const label = platformOperatorCredentialLabel(input);
1998
+ const name = describePlatformCredential(label);
1999
+ const retry = input.source === "oauth" ? "Run `void cloudflare login`, or set CLOUDFLARE_API_TOKEN for this account, then retry." : `Set ${input.environmentVariable ?? "CLOUDFLARE_API_TOKEN"} for this account, then retry.`;
2000
+ const denials = [];
2001
+ let firstDenial;
2002
+ const deniedError = (denial) => new Error(`platform: ${formatPlatformCredentialDenials(label, denials)}`, { cause: denial });
2003
+ const check = async (what, permission, action, allowMissing = false) => {
1833
2004
  try {
1834
2005
  await action();
2006
+ return true;
1835
2007
  } catch (cause) {
1836
2008
  const status = cause instanceof PlatformCloudflareApiError ? cause.status : null;
1837
- if (status === 404 && allowMissing) return;
1838
- const detail = status === 401 || status === 403 ? `Check that the credential is valid, scoped to this account, and includes ${permission}. ${retry}` : status === 404 ? "Check the bucket name and account scope before retrying." : status === 429 ? "Cloudflare rate-limited this check. Retry shortly." : "Retry the command after Cloudflare connectivity is restored.";
1839
- throw new Error(`platform: ${label} is unavailable${status === null ? "" : ` (HTTP ${status})`} using the ${source}. ${detail}`, { cause });
2009
+ if (status === 404 && allowMissing) return true;
2010
+ if (status === 401 || status === 403) {
2011
+ denials.push({
2012
+ permission,
2013
+ request: what,
2014
+ status
2015
+ });
2016
+ firstDenial ??= cause;
2017
+ return false;
2018
+ }
2019
+ const detail = status === 404 ? "Check the bucket name and account scope before retrying." : status === 429 ? "Cloudflare rate-limited this check. Retry shortly." : "Retry the command after Cloudflare connectivity is restored.";
2020
+ if (firstDenial) throw deniedError(firstDenial);
2021
+ throw new Error(`platform: ${what} is unavailable${status === null ? "" : ` (HTTP ${status})`} using the ${name}. ${detail}`, { cause });
1840
2022
  }
1841
2023
  };
1842
2024
  let accounts = [];
1843
- await check("Cloudflare account access", "Account → Account Settings → Read", async () => {
2025
+ if (await check("Cloudflare account access", "Account → Account Settings → Read", async () => {
1844
2026
  accounts = await client.listAccounts();
1845
- });
1846
- if (!accounts.some((account) => account.id === input.account.id)) throw new Error(`platform: The ${source} cannot access Cloudflare account ${JSON.stringify(input.account.name)} (${input.account.id}). ${retry}`);
1847
- await check("Cloudflare Workers access", "Account → Workers Scripts → Edit", () => client.listWorkerNames(input.account.id));
1848
- for (const name of new Set(input.r2Buckets)) await check(`R2 bucket ${JSON.stringify(name)}`, "Account → Workers R2 Storage → Edit", () => client.request(`/accounts/${encodeURIComponent(input.account.id)}/r2/buckets/${encodeURIComponent(name)}`), input.allowMissingR2Buckets);
2027
+ }) && !accounts.some((account) => account.id === input.account.id)) throw new Error(`platform: The ${name} cannot access Cloudflare account ${JSON.stringify(input.account.name)} (${input.account.id}). ${retry}`);
2028
+ await check("Cloudflare Workers access", PLATFORM_WORKERS_PERMISSION, () => client.listWorkerNames(input.account.id));
2029
+ for (const bucket of new Set(input.r2Buckets)) await check(`R2 bucket ${JSON.stringify(bucket)}`, "Account → Workers R2 Storage → Edit", () => client.request(`/accounts/${encodeURIComponent(input.account.id)}/r2/buckets/${encodeURIComponent(bucket)}`), input.allowMissingR2Buckets);
2030
+ if (firstDenial) throw deniedError(firstDenial);
1849
2031
  }
1850
2032
  /** Check Access inventory permissions before the installer starts provisioning. */
1851
2033
  async function verifyPlatformManagementAccess(client, accountId, access) {
@@ -1925,11 +2107,14 @@ async function resolvePlatformCloudflareCredentialWithInput(readInput, dependenc
1925
2107
  }
1926
2108
  }
1927
2109
  async function readExistingCredential(dependencies, runWrangler) {
1928
- const environmentToken = process.env.CLOUDFLARE_API_TOKEN?.trim() || process.env.CF_API_TOKEN?.trim() || "";
1929
- if (environmentToken) return {
1930
- source: "environment",
1931
- token: environmentToken
1932
- };
2110
+ for (const environmentVariable of ["CLOUDFLARE_API_TOKEN", "CF_API_TOKEN"]) {
2111
+ const environmentToken = process.env[environmentVariable]?.trim();
2112
+ if (environmentToken) return {
2113
+ source: "environment",
2114
+ environmentVariable,
2115
+ token: environmentToken
2116
+ };
2117
+ }
1933
2118
  const savedManagementToken = dependencies.savedManagementToken?.trim();
1934
2119
  if (savedManagementToken) return {
1935
2120
  source: "saved",
@@ -1963,7 +2148,7 @@ async function readInputs(client) {
1963
2148
  catalog = savedCatalog === void 0 || savedCatalog === null ? createDefaultPlanCatalog("custom") : parsePlatformPlanCatalog(savedCatalog);
1964
2149
  settings = parsePlanAiLoggingSettings(saved.get(PLAN_AI_LOGGING_SETTING));
1965
2150
  } catch (error) {
1966
- throw new Error(`platform: The saved plan settings are not valid for this platform version, so AI logging settings cannot be published. If a newer platform release saved them, upgrade to that release again. (${error instanceof Error ? error.message : String(error)})`);
2151
+ throw new Error(`platform: The saved plan settings are not valid for this platform version, so AI logging settings cannot be published. If a newer platform release saved them, upgrade to that release again. (${error instanceof Error ? error.message : String(error)})`, { cause: error });
1967
2152
  }
1968
2153
  return {
1969
2154
  catalog,
@@ -2387,13 +2572,16 @@ function readPlatformHyperdriveSelection(checkpoint) {
2387
2572
  }
2388
2573
  return parsePlatformHyperdriveSelection(value);
2389
2574
  }
2575
+ const nonempty = (value) => typeof value === "string" && value.trim() !== "";
2390
2576
  function parsePlatformHyperdriveSelection(value) {
2391
2577
  const selected = value;
2392
- const nonempty = (value) => typeof value === "string" && value.trim() !== "";
2393
- if (!selected || typeof selected !== "object" || Array.isArray(selected) || !nonempty(selected.id) || (nonempty(selected.serviceId) ? selected.host !== void 0 : selected.serviceId !== void 0 || !nonempty(selected.host)) || !nonempty(selected.user) || selected.name !== void 0 && (typeof selected.name !== "string" || !selected.name) || selected.database !== void 0 && (typeof selected.database !== "string" || !selected.database)) throw new Error("platform: The saved Hyperdrive selection is invalid.");
2578
+ if (!selected || typeof selected !== "object" || Array.isArray(selected) || !nonempty(selected.id) || !nonempty(selected.user) || selected.name !== void 0 && (typeof selected.name !== "string" || !selected.name) || selected.database !== void 0 && (typeof selected.database !== "string" || !selected.database)) throw new Error("platform: The saved Hyperdrive selection is invalid.");
2579
+ const { host, serviceId } = selected;
2580
+ const origin = serviceId === void 0 && typeof host === "string" && host.trim() !== "" ? { host } : typeof serviceId === "string" && serviceId.trim() !== "" && host === void 0 ? { serviceId } : void 0;
2581
+ if (!origin) throw new Error("platform: The saved Hyperdrive selection is invalid.");
2394
2582
  return {
2395
2583
  id: selected.id,
2396
- ...selected.serviceId !== void 0 ? { serviceId: selected.serviceId } : { host: selected.host },
2584
+ ...origin,
2397
2585
  user: selected.user,
2398
2586
  ...selected.name ? { name: selected.name } : {},
2399
2587
  ...selected.database ? { database: selected.database } : {}
@@ -2521,7 +2709,7 @@ async function startConditionalWorkerCreateProxy(upstreamApiBaseUrl, accountId,
2521
2709
  const createQuery = [...incomingUrl.searchParams];
2522
2710
  const supportedCreateQuery = new Set(createQuery.map(([key]) => key)).size === createQuery.length && createQuery.every(([key, value]) => key === "excludeScript" && value === "true" || key === "bindings_inherit" && value === "strict");
2523
2711
  const isConditionalCreate = incoming.method === "PUT" && incomingUrl.pathname === expectedPath && supportedCreateQuery;
2524
- const isTopLevelWorkerUpload = incoming.method === "PUT" && new RegExp(`^${basePath.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/accounts/[^/]+/workers/scripts/[^/]+$`).test(incomingUrl.pathname);
2712
+ const isTopLevelWorkerUpload = incoming.method === "PUT" && new RegExp(`^${basePath.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`)}/accounts/[^/]+/workers/scripts/[^/]+$`).test(incomingUrl.pathname);
2525
2713
  const isReadOnly = incoming.method === "GET" || incoming.method === "HEAD" || incoming.method === "OPTIONS";
2526
2714
  const isAssetUploadSession = incoming.method === "POST" && incomingUrl.pathname === `${expectedPath}/assets-upload-session` && incomingUrl.search === "";
2527
2715
  const isAssetUpload = incoming.method === "POST" && state.assetSessionStarted && (incomingUrl.pathname === assetUploadPath && incomingUrl.search === "?base64=true" || incomingUrl.search === "" && incomingUrl.pathname.startsWith(`${assetUploadPath}/`) && /^[0-9a-f]{32}$/.test(incomingUrl.pathname.slice(assetUploadPath.length + 1)));
@@ -2593,6 +2781,24 @@ async function runPlatformWranglerForConditionalCreate(operation, accountId, cwd
2593
2781
  return withConditionalPlatformWorkerCreate(accountId, workerName, (apiBaseUrl) => runPlatformWranglerAtApiBase(operation, accountId, cwd, capture, apiBaseUrl, false, apiToken), upstreamApiBaseUrl);
2594
2782
  }
2595
2783
  // src/cli/platform-plan.ts
2784
+ /** Group denied plan reads by the credential Cloudflare rejected. */
2785
+ function formatPlanDenials(denied) {
2786
+ const groups = /* @__PURE__ */ new Map();
2787
+ for (const error of denied) {
2788
+ const key = error.credential ? JSON.stringify(error.credential) : "";
2789
+ const group = groups.get(key) ?? {
2790
+ label: error.credential,
2791
+ errors: []
2792
+ };
2793
+ group.errors.push(error);
2794
+ groups.set(key, group);
2795
+ }
2796
+ return [...groups.values()].map(({ label, errors }) => label ? formatPlatformCredentialDenials(label, errors.map((error) => ({
2797
+ permission: (error.requestPath ? cloudflarePermissionForPath(error.requestPath) : void 0) ?? "a permission this read needs",
2798
+ request: `GET ${error.requestPath ?? ""}`,
2799
+ status: error.status
2800
+ }))) : [...new Set(errors.map((error) => error.message))].join("\n"));
2801
+ }
2596
2802
  async function createPlatformInstallPlan(client, input, existing, options) {
2597
2803
  const dashboardUrl = input.dashboardUrl !== void 0 ? normalizePlatformDashboardUrl(input.dashboardUrl) : existing ? existing.deployment.controlPlane.dashboardUrl ?? (existing.endpoints.dashboardUrl ? normalizePlatformDashboardUrl(existing.endpoints.dashboardUrl) : null) ?? platformDashboardUrl(existing.deployment) : null;
2598
2804
  const account = resolveAccount(await client.listAccounts(), input.accountId);
@@ -2629,7 +2835,8 @@ async function createPlatformInstallPlan(client, input, existing, options) {
2629
2835
  googleOAuth: input.authentication.providers.includes("google")
2630
2836
  } : {},
2631
2837
  ...enableEmail ? { email: true } : {},
2632
- ...input.customDomains ? { customDomains: true } : {}
2838
+ ...input.customDomains ? { customDomains: true } : {},
2839
+ ...input.securityAudits ? { securityAudits: true } : {}
2633
2840
  };
2634
2841
  if (capabilities.customDomains && (testing || !input.dedicatedZone)) throw new Error("platform: Custom domains need a dedicated application zone. Install with a domain and --dedicated-zone.");
2635
2842
  if (capabilities.email && options?.includeEmailGateway !== false && !enableEmail) throw new Error("platform: Email-enabled installations require VOID_EMAIL_SENDER_DOMAIN and VOID_EMAIL_SHARED_ZONE_ID before deploying this runtime.");
@@ -2692,6 +2899,14 @@ async function createPlatformInstallPlan(client, input, existing, options) {
2692
2899
  email: true
2693
2900
  }
2694
2901
  } : existingWithCustomDomains;
2902
+ const existingWithSecurityAudits = existing && deployment.capabilities.securityAudits && !existing.deployment.capabilities.securityAudits ? {
2903
+ ...existingWithEmail,
2904
+ capabilities: {
2905
+ ...existingWithEmail.capabilities,
2906
+ securityAudits: true
2907
+ },
2908
+ schemaVersion: deployment.schemaVersion
2909
+ } : existingWithEmail;
2695
2910
  const comparable = (value) => {
2696
2911
  if (!options?.allowRuntimeLogsChange && !options?.allowStorageLocationChange) return JSON.stringify(value);
2697
2912
  const comparableValue = { ...value };
@@ -2702,7 +2917,7 @@ async function createPlatformInstallPlan(client, input, existing, options) {
2702
2917
  schemaVersion: void 0
2703
2918
  });
2704
2919
  };
2705
- if (existing && (comparable(existingWithEmail) !== comparable(deploymentWithoutEmailZone) || recordedEmailZone !== void 0 && recordedEmailZone !== configuredEmailZone || recordedSenderDomain !== void 0 && recordedSenderDomain !== configuredSenderDomain)) throw new Error(`platform: --resume inputs do not match installation ${existing.id}. Use its recorded configuration.`);
2920
+ if (existing && (comparable(existingWithSecurityAudits) !== comparable(deploymentWithoutEmailZone) || recordedEmailZone !== void 0 && recordedEmailZone !== configuredEmailZone || recordedSenderDomain !== void 0 && recordedSenderDomain !== configuredSenderDomain)) throw new Error(`platform: --resume inputs do not match installation ${existing.id}. Use its recorded configuration.`);
2706
2921
  const names = deployment.resources;
2707
2922
  const wildcardHostname = `*.${deployment.application.baseDomain}`;
2708
2923
  const zone = testing ? null : await client.findZone(account.id, deployment.application.zoneName);
@@ -2726,24 +2941,31 @@ async function createPlatformInstallPlan(client, input, existing, options) {
2726
2941
  throw error;
2727
2942
  });
2728
2943
  const prerequisites = [];
2729
- const collectPrerequisite = (error) => {
2730
- if (!(error instanceof PlatformCloudflarePrerequisiteError)) throw error;
2731
- prerequisites.push(error);
2944
+ const denials = [];
2945
+ const settle = (slot, read) => read.catch((error) => {
2946
+ if (error instanceof PlatformCloudflarePrerequisiteError) prerequisites.push(error);
2947
+ else if (error instanceof PlatformCloudflareApiError && (error.status === 401 || error.status === 403)) denials[slot] = error;
2948
+ else throw error;
2732
2949
  return [];
2733
- };
2950
+ });
2734
2951
  const [aiGateways, routingKv, isrKv, legacyKv, r2Buckets, usageQueues, cronQueues, deploymentQueues, dispatchNamespaces, hyperdrives, workers] = await Promise.all([
2735
- gatewayInventory,
2736
- client.listKvNamespaces(account.id, names.routingKv),
2737
- client.listKvNamespaces(account.id, names.isrCacheKv),
2738
- client.listKvNamespaces(account.id, names.legacyAssetsKv),
2739
- client.listR2Buckets(account.id).catch(collectPrerequisite),
2740
- client.listQueues(account.id, names.usageQueue),
2741
- client.listQueues(account.id, names.cronQueue),
2742
- options?.deploymentExecution ?? existing?.resources.some((resource) => resource.key === "deployment-queue") ? client.listQueues(account.id, names.deploymentQueue) : Promise.resolve([]),
2743
- client.listDispatchNamespaces(account.id).catch(collectPrerequisite),
2744
- client.listHyperdriveConfigs(account.id),
2745
- client.listWorkerNames(account.id)
2952
+ settle(0, gatewayInventory),
2953
+ settle(1, client.listKvNamespaces(account.id, names.routingKv)),
2954
+ settle(2, client.listKvNamespaces(account.id, names.isrCacheKv)),
2955
+ settle(3, client.listKvNamespaces(account.id, names.legacyAssetsKv)),
2956
+ settle(4, client.listR2Buckets(account.id)),
2957
+ settle(5, client.listQueues(account.id, names.usageQueue)),
2958
+ settle(6, client.listQueues(account.id, names.cronQueue)),
2959
+ options?.deploymentExecution ?? existing?.resources.some((resource) => resource.key === "deployment-queue") ? settle(7, client.listQueues(account.id, names.deploymentQueue)) : Promise.resolve([]),
2960
+ settle(8, client.listDispatchNamespaces(account.id)),
2961
+ settle(9, client.listHyperdriveConfigs(account.id)),
2962
+ settle(10, client.listWorkerNames(account.id))
2746
2963
  ]);
2964
+ const denied = denials.filter((error) => error !== void 0);
2965
+ if (denied.length > 0) {
2966
+ if (denied.length === 1 && prerequisites.length === 0) throw denied[0];
2967
+ throw new AggregateError([...denied, ...prerequisites], `platform: Cloudflare denied reads the plan needs.\n\n${[...formatPlanDenials(denied), ...prerequisites.map((error) => error.message)].join("\n\n")}`, { cause: denied[0] });
2968
+ }
2747
2969
  if (prerequisites.length === 1) throw prerequisites[0];
2748
2970
  if (prerequisites.length > 1) throw new AggregateError(prerequisites, `platform: Cloudflare account prerequisites are missing:\n\n${prerequisites.map((error) => error.message).join("\n\n")}`);
2749
2971
  const dnsRecords = zone ? await listZoneDnsRecords(client, zone, wildcardHostname) : [];
@@ -2932,7 +3154,7 @@ async function createPlatformInstallPlan(client, input, existing, options) {
2932
3154
  });
2933
3155
  const resolvedResources = { ...deployment.resources };
2934
3156
  for (const action of actions) {
2935
- const resourceKey = RESOURCE_NAME_KEY_BY_ACTION[action.key];
3157
+ const resourceKey = hasOwnKey(RESOURCE_NAME_KEY_BY_ACTION, action.key) ? RESOURCE_NAME_KEY_BY_ACTION[action.key] : void 0;
2936
3158
  if (resourceKey && action.name !== resolvedResources[resourceKey]) resolvedResources[resourceKey] = action.name;
2937
3159
  }
2938
3160
  const resolvedDeployment = createPlatformDeploymentManifest({
@@ -3094,7 +3316,7 @@ function addNamedPlan(context, target) {
3094
3316
  });
3095
3317
  return;
3096
3318
  }
3097
- if (recorded && recorded.state === "ready") {
3319
+ if (existing && recorded?.state === "ready") {
3098
3320
  if (options?.repairMissing && recorded.ownership === "created") {
3099
3321
  actions.push({
3100
3322
  action: "create",
@@ -3191,7 +3413,7 @@ function isLegacyUniqueProvisionAttempt(manifest, key, kind, name) {
3191
3413
  const resourceSlug = resourceSlugForManifest(manifest);
3192
3414
  if (resourceSlug === manifest.deployment.installationSlug) return false;
3193
3415
  const expectedNames = createPlatformResourceNames(resourceSlug);
3194
- const resourceKey = RESOURCE_NAME_KEY_BY_ACTION[key];
3416
+ const resourceKey = hasOwnKey(RESOURCE_NAME_KEY_BY_ACTION, key) ? RESOURCE_NAME_KEY_BY_ACTION[key] : void 0;
3195
3417
  if (!resourceKey) return false;
3196
3418
  const expectedName = expectedNames[resourceKey];
3197
3419
  const uniquePrefix = expectedName.slice(0, expectedName.lastIndexOf("-") + 1);
@@ -3664,12 +3886,16 @@ var PlatformWorkerRecoveryIncompleteError = class extends Error {
3664
3886
  }
3665
3887
  };
3666
3888
  // src/cli/platform-installer-secrets.ts
3889
+ const required = (value, name) => {
3890
+ if (!value) throw new Error(`platform: ${name} is required to install the platform.`);
3891
+ return value;
3892
+ };
3667
3893
  function createPlatformInstallationSecrets(input) {
3668
3894
  const checkpoint = input.checkpoint ?? {};
3669
- const required = (value, name) => {
3670
- if (!value) throw new Error(`platform: ${name} is required to install the platform.`);
3671
- return value;
3672
- };
3895
+ if (!input.r2AccessKeyId !== !input.r2SecretAccessKey) {
3896
+ const [given, missing] = input.r2AccessKeyId ? ["VOID_PLATFORM_R2_ACCESS_KEY_ID", "VOID_PLATFORM_R2_SECRET_ACCESS_KEY"] : ["VOID_PLATFORM_R2_SECRET_ACCESS_KEY", "VOID_PLATFORM_R2_ACCESS_KEY_ID"];
3897
+ throw new Error(`platform: ${given} is set but ${missing} is not. Set VOID_PLATFORM_R2_ACCESS_KEY_ID and VOID_PLATFORM_R2_SECRET_ACCESS_KEY together, even if only the secret changed.`);
3898
+ }
3673
3899
  const existingInstallation = input.existingInstallation === true;
3674
3900
  const generateIdentityKeys = input.generateIdentityKeys === true && !existingInstallation;
3675
3901
  const restoredIdentity = (explicit, name) => existingInstallation ? checkpoint[name] || explicit || "" : explicit || checkpoint[name] || "";
@@ -4079,9 +4305,9 @@ async function readPlatformWorkerDeployments(configPath, accountId, workerName,
4079
4305
  versions
4080
4306
  }));
4081
4307
  }
4308
+ const normalize = (deployment) => deployment.versions.filter((version) => version.percentage > 0).map((version) => `${version.versionId}@${version.percentage}`).sort();
4082
4309
  function samePlatformWorkerTraffic(left, right) {
4083
4310
  if (!left) return false;
4084
- const normalize = (deployment) => deployment.versions.filter((version) => version.percentage > 0).map((version) => `${version.versionId}@${version.percentage}`).sort();
4085
4311
  return JSON.stringify(normalize(left)) === JSON.stringify(normalize(right));
4086
4312
  }
4087
4313
  function deploymentRunsOnlyVersion(deployment, versionId) {
@@ -4419,13 +4645,13 @@ async function platformWorkerLiveTriggersMatch(options) {
4419
4645
  const worker = record(workerValue);
4420
4646
  const subdomain = record(worker?.subdomain);
4421
4647
  const schedules = record(schedulesValue)?.schedules;
4422
- if (worker?.name !== workerName || !subdomain || !desired.preserveWorkersDev && subdomain.enabled !== desired.workers_dev || !desired.preservePreviewUrls && subdomain.previews_enabled !== desired.preview_urls || !Array.isArray(schedules) || !Array.isArray(worker.references && record(worker.references)?.queues) || !Array.isArray(workflowsValue) || workflowsValue.length >= 100 || !Array.isArray(nextWorkflowsValue) || nextWorkflowsValue.length !== 0) return false;
4648
+ const references = record(worker?.references)?.queues;
4649
+ if (worker?.name !== workerName || !subdomain || !desired.preserveWorkersDev && subdomain.enabled !== desired.workers_dev || !desired.preservePreviewUrls && subdomain.previews_enabled !== desired.preview_urls || !Array.isArray(schedules) || !Array.isArray(references) || !Array.isArray(workflowsValue) || workflowsValue.length >= 100 || !Array.isArray(nextWorkflowsValue) || nextWorkflowsValue.length !== 0) return false;
4423
4650
  const liveCrons = schedules.map((entry) => record(entry)?.cron);
4424
4651
  if (!liveCrons.every((cron) => typeof cron === "string") || !sameStrings(liveCrons, desired.crons) || workflowsValue.some((entry) => {
4425
4652
  const workflow = record(entry);
4426
4653
  return !workflow || typeof workflow.script_name !== "string" || workflow.script_name === workerName;
4427
4654
  })) return false;
4428
- const references = record(worker.references).queues;
4429
4655
  if (references.length !== queues.length) return false;
4430
4656
  const matched = /* @__PURE__ */ new Set();
4431
4657
  const consumers = await Promise.all(references.map(async (value) => {
@@ -4473,8 +4699,9 @@ async function recoverInterruptedPlatformWorkerCutover(input) {
4473
4699
  "emailGateway",
4474
4700
  "proxy",
4475
4701
  "api"
4476
- ].filter((key) => interruptedCutover.staged.has(key))) {
4702
+ ]) {
4477
4703
  const snapshot = interruptedCutover.staged.get(key);
4704
+ if (!snapshot) continue;
4478
4705
  const preservedRoutes = dependencies.recoverWorkerCutover ? [] : await inventoryUnmanagedPlatformWorkerTraffic(dependencies.client, plan, snapshot.workerName);
4479
4706
  const recoveryConfig = mergePlatformWorkerTrafficConfig({
4480
4707
  ...configs[key],
@@ -4830,9 +5057,11 @@ async function deployPlatformWorker(config, secrets, options) {
4830
5057
  await options.onStaged(previousVersionId, uploadedVersionId, previousTriggers);
4831
5058
  await options.onReadyForActivation?.();
4832
5059
  await options.waitForPriorWorker?.();
5060
+ const knownDeploymentIds = /* @__PURE__ */ new Set();
4833
5061
  if (options.workerExisted) {
4834
5062
  const deploymentsBeforeActivation = await readPlatformWorkerDeployments(configPath, accountId, workerName, readRunner);
4835
5063
  if (deploymentsBeforeActivation[0]?.id !== previousDeploymentId || !deploymentRunsOnlyVersion(deploymentsBeforeActivation[0], previousVersionId)) throw new Error(`platform: Worker ${workerName} changed concurrently before activation; refusing to overwrite it.`);
5064
+ for (const deployment of deploymentsBeforeActivation) knownDeploymentIds.add(deployment.id);
4836
5065
  activatedVersionId = uploadedVersionId;
4837
5066
  assertCleanPlatformWrangler(await options.runner({
4838
5067
  type: "versions.deploy",
@@ -4844,7 +5073,31 @@ async function deployPlatformWorker(config, secrets, options) {
4844
5073
  message: `Void platform activation ${uploadedVersionId}`
4845
5074
  }, accountId, directory, true), `activate ${workerName}`, accountId);
4846
5075
  }
4847
- const deploymentsAfterActivation = await readPlatformWorkerDeployments(configPath, accountId, workerName, readRunner);
5076
+ const readDeploymentHistory = () => readPlatformWorkerDeployments(configPath, accountId, workerName, readRunner);
5077
+ let deploymentsAfterActivation = await readDeploymentHistory();
5078
+ const headIsStale = () => {
5079
+ const head = deploymentsAfterActivation[0];
5080
+ return head === void 0 || knownDeploymentIds.has(head.id);
5081
+ };
5082
+ for (const wait of [
5083
+ 250,
5084
+ 500,
5085
+ 1e3
5086
+ ]) {
5087
+ if (!headIsStale()) break;
5088
+ await setTimeout$1(wait);
5089
+ try {
5090
+ deploymentsAfterActivation = await readDeploymentHistory();
5091
+ } catch (cause) {
5092
+ activatedVersionId = null;
5093
+ throw new PlatformWorkerRecoveryIncompleteError(`platform: Void could not confirm activation of ${workerName} because rereading its deployment history failed: ${getErrorMessage(cause)}`, { cause });
5094
+ }
5095
+ }
5096
+ if (headIsStale()) {
5097
+ const head = deploymentsAfterActivation[0];
5098
+ activatedVersionId = null;
5099
+ throw new PlatformWorkerRecoveryIncompleteError(`platform: Void could not confirm activation of ${workerName} because Cloudflare ${head === void 0 ? "lists no deployments for it yet" : head.id === previousDeploymentId ? "still reports the previous deployment" : `still reports older deployment ${head.id}`}.`);
5100
+ }
4848
5101
  const lineage = classifyPlatformWorkerDeploymentLineage(deploymentsAfterActivation, uploadedVersionId, previousDeploymentId);
4849
5102
  if (lineage.kind === "concurrent-after") {
4850
5103
  activatedVersionId = null;
@@ -4894,10 +5147,11 @@ async function deployPlatformWorker(config, secrets, options) {
4894
5147
  if (nextTraffic.customDomains.length > 0) await options.publishCustomDomains(workerName, nextTraffic.customDomains);
4895
5148
  if (options.managedRoutes.length > 0) await options.publishRoutes(workerName, options.managedRoutes);
4896
5149
  await options.onTrafficPublished();
5150
+ const committedVersionId = uploadedVersionId;
4897
5151
  const rollback = () => rollbackPlatformWorker({
4898
5152
  accountId,
4899
5153
  activatedDeploymentId,
4900
- activatedVersionId: uploadedVersionId,
5154
+ activatedVersionId: committedVersionId,
4901
5155
  config,
4902
5156
  nextTriggers,
4903
5157
  previousConfig: options.previousConfig,
@@ -5075,7 +5329,10 @@ async function restorePlatformWorkerDeployment(input) {
5075
5329
  }
5076
5330
  // src/cli/platform-install-workers.ts
5077
5331
  function platformWorkerAction(workerActions, key) {
5078
- return workerActions.find((entry) => entry.key === platformWorkerResourceKey(key));
5332
+ const resourceKey = platformWorkerResourceKey(key);
5333
+ const action = workerActions.find((entry) => entry.key === resourceKey);
5334
+ if (!action) throw new Error(`platform: The plan is missing the ${resourceKey} Worker action.`);
5335
+ return action;
5079
5336
  }
5080
5337
  /** Deploy callbacks shared by the upload and enable phases for one platform Worker. */
5081
5338
  function platformWorkerDeployCallbacks(input) {
@@ -5149,10 +5406,12 @@ async function uploadInstallationWorkers(input) {
5149
5406
  const uploadWaiters = [];
5150
5407
  const acquireUploadSlot = async () => {
5151
5408
  if (uploadFailure !== void 0) throw uploadFailure;
5152
- if (availableUploadSlots === 0) await new Promise((resolve, reject) => uploadWaiters.push({
5153
- resolve,
5154
- reject
5155
- }));
5409
+ if (availableUploadSlots === 0) await new Promise((resolve, reject) => {
5410
+ uploadWaiters.push({
5411
+ resolve,
5412
+ reject
5413
+ });
5414
+ });
5156
5415
  else availableUploadSlots--;
5157
5416
  return (failure) => {
5158
5417
  if (failure !== void 0 && uploadFailure === void 0) {
@@ -5307,12 +5566,13 @@ async function verifyPlatformHealth(apiUrl, installationId, proxyUrl, applicatio
5307
5566
  }
5308
5567
  };
5309
5568
  const dispatchUrl = dispatchOrigin ?? `https://${PLATFORM_HEALTH_HOSTNAME_LABEL}.${applicationBaseDomain}`;
5569
+ const emailGatewayHealthUrl = context?.emailGatewayUrl ? context.emailGatewayUrl + "/health" : void 0;
5310
5570
  const [health, discovery, proxy, dispatch, emailGateway] = await Promise.all([
5311
5571
  request(`${apiUrl}/health`),
5312
5572
  request(`${apiUrl}/.well-known/void-platform`),
5313
5573
  request(`${proxyUrl}/health`),
5314
5574
  request(`${dispatchUrl}/health`),
5315
- context?.emailGatewayUrl ? request(`${context.emailGatewayUrl}/health`) : void 0
5575
+ emailGatewayHealthUrl ? request(emailGatewayHealthUrl) : void 0
5316
5576
  ]);
5317
5577
  if (!health.ok) throw await platformProbeFailure("Health check", `${apiUrl}/health`, health, context);
5318
5578
  if (!discovery.ok) throw await platformProbeFailure("Discovery check", `${apiUrl}/.well-known/void-platform`, discovery, context);
@@ -5322,8 +5582,8 @@ async function verifyPlatformHealth(apiUrl, installationId, proxyUrl, applicatio
5322
5582
  if ((body.usageProtocolVersion ?? 0) !== usageProtocolVersion) throw new Error("platform: Deployed API usage protocol does not match this runtime. Traffic remains disabled.");
5323
5583
  if (!proxy.ok) throw await platformProbeFailure("Proxy health check", `${proxyUrl}/health`, proxy, context);
5324
5584
  if (!dispatch.ok) throw await platformProbeFailure("Dispatch health check", `${dispatchUrl}/health`, dispatch, context);
5325
- if (emailGateway) {
5326
- if (!emailGateway.ok) throw await platformProbeFailure("Email gateway health check", `${context.emailGatewayUrl}/health`, emailGateway, context);
5585
+ if (emailGateway && emailGatewayHealthUrl) {
5586
+ if (!emailGateway.ok) throw await platformProbeFailure("Email gateway health check", emailGatewayHealthUrl, emailGateway, context);
5327
5587
  const identity = await emailGateway.json();
5328
5588
  if (identity?.installationId !== installationId || identity.platformVersion !== platformVersion || identity.emailProtocolVersion !== 1) throw new Error("platform: Deployed email gateway identity, version, or protocol does not match this installation.");
5329
5589
  }
@@ -5377,6 +5637,7 @@ const sharedEmailStepPermissions = /* @__PURE__ */ new Map([
5377
5637
  ["inbound_probe", "Zone → Zone Settings → Edit"],
5378
5638
  ["sending_onboard", "Account → Email Sending → Edit"]
5379
5639
  ]);
5640
+ const code = (value) => typeof value === "string" && /^[a-z][a-z0-9_-]{0,63}$/.test(value) ? value : null;
5380
5641
  async function bootstrapPlatformSharedEmail(apiUrl, healthProbeToken, fetcher = fetch) {
5381
5642
  const deadline = Date.now() + 3e5;
5382
5643
  let operationId = null;
@@ -5384,7 +5645,9 @@ async function bootstrapPlatformSharedEmail(apiUrl, healthProbeToken, fetcher =
5384
5645
  const waitForProgress = async () => {
5385
5646
  const remaining = deadline - Date.now();
5386
5647
  if (remaining <= 0) throw timedOut();
5387
- await new Promise((resolve) => setTimeout(resolve, Math.min(1e3, remaining)));
5648
+ await new Promise((resolve) => {
5649
+ setTimeout(resolve, Math.min(1e3, remaining));
5650
+ });
5388
5651
  };
5389
5652
  let response;
5390
5653
  let value;
@@ -5429,14 +5692,13 @@ async function bootstrapPlatformSharedEmail(apiUrl, healthProbeToken, fetcher =
5429
5692
  200,
5430
5693
  202,
5431
5694
  503
5432
- ].includes(response.status) && status?.version === 1 && status.state === "incomplete" && observedOperationId && (status.operationStatus === "pending" || status.operationStatus === "running") && status.failureCode == null) {
5695
+ ].includes(response.status) && status?.version === 1 && status.state === "incomplete" && observedOperationId && (status.operationStatus === "pending" || status.operationStatus === "running") && (status.failureCode === null || status.failureCode === void 0)) {
5433
5696
  await waitForProgress();
5434
5697
  continue;
5435
5698
  }
5436
5699
  break;
5437
5700
  }
5438
- if (!response.ok || status?.version !== 1 || status.state !== "ready" || operationId === null || status.operationId !== operationId || status.operationStatus != null && status.operationStatus !== "completed" || status.failureCode != null) {
5439
- const code = (value) => typeof value === "string" && /^[a-z][a-z0-9_-]{0,63}$/.test(value) ? value : null;
5701
+ if (!response.ok || status?.version !== 1 || status.state !== "ready" || operationId === null || status.operationId !== operationId || status.operationStatus !== null && status.operationStatus !== void 0 && status.operationStatus !== "completed" || status.failureCode !== null && status.failureCode !== void 0) {
5440
5702
  const operationStatus = code(status?.operationStatus);
5441
5703
  const operationId = typeof status?.operationId === "string" && /^[A-Za-z0-9_-]{1,100}$/.test(status.operationId) ? status.operationId : null;
5442
5704
  const details = operationId ? [`Operation ${operationId}: ${operationStatus ?? "incomplete"}.`] : operationStatus ? [`Operation status: ${operationStatus}.`] : [];
@@ -5582,7 +5844,7 @@ function platformAccessHealthTargets(plan) {
5582
5844
  }
5583
5845
  async function verifyHealthException(access, app, destination) {
5584
5846
  const destinations = platformAccessPublicDestinations(app);
5585
- if (typeof app.id !== "string" || !app.id || app.type !== "self_hosted" || app.domain !== destination || !destinations.length || destinations.some((value) => value !== destination) || app.destinations !== void 0 && (!Array.isArray(app.destinations) || app.destinations.some((value) => !value || value.type !== "public" || value.uri !== destination)) || app.target_criteria != null && (!Array.isArray(app.target_criteria) || app.target_criteria.length > 0)) throw new Error(`platform: The Access health exception must cover only ${destination}.`);
5847
+ if (typeof app.id !== "string" || !app.id || app.type !== "self_hosted" || app.domain !== destination || !destinations.length || destinations.some((value) => value !== destination) || app.destinations !== void 0 && (!Array.isArray(app.destinations) || app.destinations.some((value) => !value || value.type !== "public" || value.uri !== destination)) || app.target_criteria !== null && app.target_criteria !== void 0 && (!Array.isArray(app.target_criteria) || app.target_criteria.length > 0)) throw new Error(`platform: The Access health exception must cover only ${destination}.`);
5586
5848
  const policies = await access.list(`apps/${encodeURIComponent(app.id)}/policies`);
5587
5849
  const policy = policies[0];
5588
5850
  if (policies.length !== 1 || policy?.decision !== "bypass" || JSON.stringify(policy.include) !== "[{\"everyone\":{}}]" || policy.require !== void 0 && (!Array.isArray(policy.require) || policy.require.length > 0) || policy.exclude !== void 0 && (!Array.isArray(policy.exclude) || policy.exclude.length > 0)) throw new Error(`platform: The Access policy for ${destination} does not match the reserved health-check exception.`);
@@ -5599,8 +5861,9 @@ async function ensurePlatformAccessHealthChecks(input) {
5599
5861
  const accountId = input.plan.account.id;
5600
5862
  const identityAccountId = spec.accountId ?? accountId;
5601
5863
  const token = appAccess?.managed ? appAccess.apiToken : identityAccountId === accountId ? process.env.VOID_PLATFORM_ACCESS_SETUP_TOKEN || input.checkpoint.accessManagementToken : void 0;
5602
- if (!token && !input.client.request) throw new Error("platform: Access management is required to configure the reserved health endpoints.");
5603
- const access = new PlatformAccessClient(token ? new PlatformCloudflareClient(token, { apiBase: input.client.apiBaseUrl }) : { request: input.client.request.bind(input.client) }, accountId);
5864
+ const accessClient = token ? new PlatformCloudflareClient(token, { apiBase: input.client.apiBaseUrl }) : input.client.request ? { request: input.client.request.bind(input.client) } : void 0;
5865
+ if (!accessClient) throw new Error("platform: Access management is required to configure the reserved health endpoints.");
5866
+ const access = new PlatformAccessClient(accessClient, accountId);
5604
5867
  const nonce = createHash("sha256").update(`void-access-health:${input.manifest.ownershipNonce}`).digest("hex").slice(0, 32);
5605
5868
  const state = input.checkpoint.accessHealthProvisioningJson ? JSON.parse(input.checkpoint.accessHealthProvisioningJson) : {
5606
5869
  version: 1,
@@ -5722,7 +5985,7 @@ async function verifyInstalledPlatformAccessProtection(input) {
5722
5985
  }
5723
5986
  const existingWorkers = input.plan.actions.filter((action) => action.kind === "worker" && action.action === "update").map((action) => action.name);
5724
5987
  if (existingWorkers.length) {
5725
- const { verifyProtectionWorkerOrigins } = await import("./platform-auth-protection-BybVCUzi.mjs");
5988
+ const { verifyProtectionWorkerOrigins } = await import("./platform-auth-protection-HSmLmD3d.mjs");
5726
5989
  await verifyProtectionWorkerOrigins({
5727
5990
  request: input.client.request.bind(input.client),
5728
5991
  listWorkerDomains: input.client.listWorkerDomains.bind(input.client),
@@ -5928,6 +6191,32 @@ async function prepareInstallationAuthentication(input) {
5928
6191
  }
5929
6192
  }
5930
6193
  }
6194
+ /** Cloudflare does not accept an origin connection limit below this. */
6195
+ const HYPERDRIVE_MIN_ORIGIN_CONNECTIONS = 5;
6196
+ /** The Hyperdrive origin limit that leaves the direct-connection reserve free. */
6197
+ function platformHyperdriveConnectionLimit(connectionSlots) {
6198
+ return Math.max(HYPERDRIVE_MIN_ORIGIN_CONNECTIONS, connectionSlots - 5);
6199
+ }
6200
+ /**
6201
+ * Hyperdrive's default origin limit can exceed what a small database accepts. Once the
6202
+ * pool fills every slot, direct connections (upgrade, repair, `psql`) fail with 53300.
6203
+ * Lower the limit on the Hyperdrive this installation created; only warn for an adopted one,
6204
+ * which its owner manages. Never raise a limit, so the value stays within the account plan.
6205
+ */
6206
+ async function fitPlatformHyperdriveToDatabase(input) {
6207
+ const { client, accountId, resource, readConnectionSlots, onProgress } = input;
6208
+ if (!readConnectionSlots || resource.kind !== "hyperdrive") return;
6209
+ const connectionSlots = await readConnectionSlots();
6210
+ const limit = platformHyperdriveConnectionLimit(connectionSlots);
6211
+ const current = (await client.getHyperdriveConfig(accountId, resource.id)).originConnectionLimit;
6212
+ if (current === void 0 || current <= limit) return;
6213
+ if (resource.ownership !== "created") {
6214
+ onProgress?.(`Warning: Hyperdrive ${resource.name} may open ${current} database connections, but the database accepts ${connectionSlots}. Set its origin connection limit to ${limit} or lower so upgrades and other direct connections can still connect.`);
6215
+ return;
6216
+ }
6217
+ onProgress?.(`Lowering the Hyperdrive origin connection limit from ${current} to ${limit} to fit the database's ${connectionSlots} connections`);
6218
+ await client.setHyperdriveOriginConnectionLimit(accountId, resource.id, limit);
6219
+ }
5931
6220
  // src/cli/platform-installer-runtime.ts
5932
6221
  function loadPlatformRuntime(customRuntimeDirectory) {
5933
6222
  const runtime = resolvePlatformRuntime(customRuntimeDirectory || void 0);
@@ -5941,7 +6230,7 @@ function verifyRuntimeArtifacts(runtimeDirectory, manifest) {
5941
6230
  try {
5942
6231
  contents = readFileSync(path);
5943
6232
  } catch (error) {
5944
- throw new Error(`platform: Runtime artifact is missing: ${getErrorMessage(error)}`);
6233
+ throw new Error(`platform: Runtime artifact is missing: ${getErrorMessage(error)}`, { cause: error });
5945
6234
  }
5946
6235
  if (contents.byteLength !== artifact.size || hash(contents) !== artifact.sha256) throw new Error(`platform: Runtime artifact failed integrity verification: ${path}.`);
5947
6236
  }
@@ -5953,7 +6242,7 @@ function verifyPlatformDatabaseArtifacts(runtimeDirectory, database) {
5953
6242
  try {
5954
6243
  journal = readFileSync(journalPath);
5955
6244
  } catch (error) {
5956
- throw new Error(`platform: Runtime database migration journal is missing: ${getErrorMessage(error)}`);
6245
+ throw new Error(`platform: Runtime database migration journal is missing: ${getErrorMessage(error)}`, { cause: error });
5957
6246
  }
5958
6247
  if (hash(journal) !== database.journalSha256) throw new Error(`platform: Runtime database migration journal failed integrity verification: ${journalPath}.`);
5959
6248
  for (const migration of database.migrations) {
@@ -5962,7 +6251,7 @@ function verifyPlatformDatabaseArtifacts(runtimeDirectory, database) {
5962
6251
  try {
5963
6252
  contents = readFileSync(path);
5964
6253
  } catch (error) {
5965
- throw new Error(`platform: Runtime database migration is missing: ${getErrorMessage(error)}`);
6254
+ throw new Error(`platform: Runtime database migration is missing: ${getErrorMessage(error)}`, { cause: error });
5966
6255
  }
5967
6256
  if (hash(contents) !== migration.sha256) throw new Error(`platform: Runtime database migration failed integrity verification: ${path}.`);
5968
6257
  }
@@ -6253,14 +6542,14 @@ function platformDatabaseClientUrl(databaseUrl) {
6253
6542
  url.searchParams.set("sslmode", "verify-full");
6254
6543
  return url.toString();
6255
6544
  }
6256
- async function withPlatformDatabasePool(databaseUrl, use) {
6545
+ async function withPlatformDatabasePool(databaseUrl, run) {
6257
6546
  const { Pool } = await import("pg");
6258
6547
  const pool = new Pool({
6259
6548
  connectionString: platformDatabaseClientUrl(databaseUrl),
6260
6549
  max: 1
6261
6550
  });
6262
6551
  try {
6263
- return await use(pool);
6552
+ return await run(pool);
6264
6553
  } finally {
6265
6554
  await pool.end();
6266
6555
  }
@@ -6275,26 +6564,43 @@ function claimPlatformDatabase(databaseUrl, installationId, ownershipNonce) {
6275
6564
  }
6276
6565
  });
6277
6566
  }
6567
+ /** The error a lifecycle-lock operation fails with once pg reported the held client closed. */
6568
+ function lostLockConnectionError(cause) {
6569
+ return new Error(`platform: The PostgreSQL connection that holds the lifecycle lock was closed (${cause.message}). Rerun the command to continue.`, { cause });
6570
+ }
6278
6571
  async function acquirePlatformDatabaseLifecycleLock(databaseUrl, installationId, ownershipNonce) {
6279
6572
  const { Pool } = await import("pg");
6280
6573
  const pool = new Pool({
6281
6574
  connectionString: platformDatabaseClientUrl(databaseUrl),
6282
6575
  max: 1
6283
6576
  });
6577
+ pool.on("error", () => {});
6284
6578
  const client = await pool.connect();
6579
+ let lost;
6580
+ client.on("error", (error) => {
6581
+ lost ??= error;
6582
+ });
6583
+ const connection = { query: async (sql, values) => {
6584
+ if (lost) throw lostLockConnectionError(lost);
6585
+ try {
6586
+ return await client.query(sql, values ? [...values] : void 0);
6587
+ } catch (error) {
6588
+ throw lost ? lostLockConnectionError(lost) : error;
6589
+ }
6590
+ } };
6285
6591
  try {
6286
- const releaseConnectionLock = await acquirePlatformDatabaseLifecycleLockConnection(client, installationId, ownershipNonce);
6592
+ const releaseConnectionLock = await acquirePlatformDatabaseLifecycleLockConnection(connection, installationId, ownershipNonce);
6287
6593
  const release = async () => {
6288
6594
  try {
6289
- await releaseConnectionLock();
6595
+ if (!lost) await releaseConnectionLock();
6290
6596
  } finally {
6291
- client.release();
6597
+ client.release(lost);
6292
6598
  await pool.end();
6293
6599
  }
6294
6600
  };
6295
6601
  return Object.assign(release, releaseConnectionLock);
6296
6602
  } catch (error) {
6297
- client.release();
6603
+ client.release(lost);
6298
6604
  await pool.end();
6299
6605
  throw error;
6300
6606
  }
@@ -6305,7 +6611,7 @@ async function readPlatformDatabaseLifecycleManifest(databaseUrl, installationId
6305
6611
  return await readPlatformDatabaseLifecycleManifestConnection(pool, installationId, ownershipNonce);
6306
6612
  } catch (error) {
6307
6613
  if (error instanceof Error && error.message.startsWith("platform:")) throw error;
6308
- throw new Error(`platform: Could not read the PostgreSQL lifecycle checkpoint: ${error instanceof Error ? error.message : String(error)}`);
6614
+ throw new Error(`platform: Could not read the PostgreSQL lifecycle checkpoint: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
6309
6615
  }
6310
6616
  });
6311
6617
  }
@@ -6342,6 +6648,21 @@ async function readPlatformProjectSlugsConnection(client) {
6342
6648
  if ((await client.query(`SELECT to_regclass('public.projects') IS NOT NULL AS "present"`)).rows[0]?.present !== true) return [];
6343
6649
  return (await client.query("SELECT \"slug\" FROM \"projects\" ORDER BY \"slug\"")).rows.map((row) => row.slug);
6344
6650
  }
6651
+ /**
6652
+ * Connections the server accepts from roles without SUPERUSER. PostgreSQL 16 added
6653
+ * reserved_connections; older servers report it as missing, which counts as zero.
6654
+ */
6655
+ async function readPlatformDatabaseConnectionSlotsConnection(client) {
6656
+ const row = (await client.query(`SELECT current_setting('max_connections')::int AS "max",
6657
+ current_setting('superuser_reserved_connections')::int AS "superuser",
6658
+ COALESCE(current_setting('reserved_connections', true), '0')::int AS "reserved"`)).rows[0];
6659
+ if (!row || ![
6660
+ row.max,
6661
+ row.superuser,
6662
+ row.reserved
6663
+ ].every(Number.isInteger)) throw new Error("platform: Could not read the PostgreSQL connection limit.");
6664
+ return Math.max(0, row.max - row.superuser - row.reserved);
6665
+ }
6345
6666
  async function inspectPlatformDatabaseStateConnection(client, database) {
6346
6667
  const relation = await client.query(`SELECT to_regclass('"drizzle"."__drizzle_migrations"')::text AS "relation"`);
6347
6668
  if (relation.rows.length === 0 || relation.rows[0]?.relation === null) return {
@@ -6447,7 +6768,7 @@ async function acquirePlatformDatabaseLifecycleLockConnection(client, installati
6447
6768
  } catch (error) {
6448
6769
  await client.query("SELECT pg_advisory_unlock(hashtextextended($1, 0))", [lockIdentity]);
6449
6770
  if (error instanceof Error && error.message.startsWith("platform:")) throw error;
6450
- throw new Error(`platform: The PostgreSQL lifecycle checkpoint is invalid: ${error instanceof Error ? error.message : String(error)}`);
6771
+ throw new Error(`platform: The PostgreSQL lifecycle checkpoint is invalid: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
6451
6772
  }
6452
6773
  let released = false;
6453
6774
  const release = async () => {
@@ -6470,6 +6791,7 @@ async function acquirePlatformDatabaseLifecycleLockConnection(client, installati
6470
6791
  release.readAdministratorSetup = () => readPlatformAdministratorSetupConnection(client);
6471
6792
  release.readProjectZeroTrust = () => readPlatformProjectZeroTrustStateConnection(client);
6472
6793
  release.readProjects = () => readPlatformProjectSlugsConnection(client);
6794
+ release.readConnectionSlots = () => readPlatformDatabaseConnectionSlotsConnection(client);
6473
6795
  release.publishAiLogging = (kv, onProgress) => projectPlatformAiLoggingConnection(client, kv, { onProgress });
6474
6796
  release.lockProjectZeroTrust = () => lockPlatformProjectZeroTrustConnection(client);
6475
6797
  release.fenceProjectZeroTrust = () => fencePlatformProjectZeroTrustConnection(client);
@@ -6506,6 +6828,16 @@ async function readSandboxDrainTable(client) {
6506
6828
  AND column_name = 'admission_protocol'
6507
6829
  ) AS "present"`)).rows[0]?.present === true };
6508
6830
  }
6831
+ const classify = (row) => {
6832
+ if (!row) return null;
6833
+ const cursor = row.cursor;
6834
+ if (!row.generation || row.admission_protocol !== 0 && row.admission_protocol !== 2 && row.admission_protocol !== 3 || !row.started_at || !row.updated_at || row.state !== "draining" && row.state !== "complete" || row.phase !== "deployments" && row.phase !== "resources" || !cursor || cursor.pass !== "1" && cursor.pass !== "2" || row.state === "complete" && (!row.completed_at || row.phase !== "resources" || cursor.pass !== "2") || row.state === "draining" && row.completed_at !== null) throw new Error("platform: The authoritative sandbox-drain database checkpoint is invalid. Traffic remains disabled.");
6835
+ return {
6836
+ admissionProtocol: row.admission_protocol,
6837
+ generation: row.generation,
6838
+ state: row.state === "complete" ? "complete" : "pending"
6839
+ };
6840
+ };
6509
6841
  async function preparePlatformSandboxDrainConnection(client, requiredAdmissionProtocol = 0) {
6510
6842
  const table = await readSandboxDrainTable(client);
6511
6843
  if (!table) throw new Error("platform: Runtime declares sandbox-drain safety but its database checkpoint table is missing.");
@@ -6514,17 +6846,8 @@ async function preparePlatformSandboxDrainConnection(client, requiredAdmissionPr
6514
6846
  const readCheckpoint = () => client.query(`SELECT ${hasAdmissionColumn ? "\"admission_protocol\"" : "0 AS \"admission_protocol\""}, "generation", "state", "phase", "cursor", "started_at", "updated_at", "completed_at"
6515
6847
  FROM "sandbox_drain_checkpoints"
6516
6848
  WHERE "singleton" = true`);
6517
- const classify = (row) => {
6518
- if (!row) return null;
6519
- const cursor = row.cursor;
6520
- if (!row.generation || row.admission_protocol !== 0 && row.admission_protocol !== 2 && row.admission_protocol !== 3 || !row.started_at || !row.updated_at || row.state !== "draining" && row.state !== "complete" || row.phase !== "deployments" && row.phase !== "resources" || !cursor || cursor.pass !== "1" && cursor.pass !== "2" || row.state === "complete" && (!row.completed_at || row.phase !== "resources" || cursor.pass !== "2") || row.state === "draining" && row.completed_at !== null) throw new Error("platform: The authoritative sandbox-drain database checkpoint is invalid. Traffic remains disabled.");
6521
- return {
6522
- admissionProtocol: row.admission_protocol,
6523
- generation: row.generation,
6524
- state: row.state === "complete" ? "complete" : "pending"
6525
- };
6526
- };
6527
- const existingState = classify((await readCheckpoint()).rows[0]);
6849
+ const existing = await readCheckpoint();
6850
+ const existingState = classify(existing.rows[0]);
6528
6851
  if (existingState && (requiredAdmissionProtocol === 0 || existingState.admissionProtocol >= requiredAdmissionProtocol)) return existingState;
6529
6852
  if (requiredAdmissionProtocol >= 2) {
6530
6853
  if (existingState && existingState.admissionProtocol >= 2) {
@@ -6603,7 +6926,8 @@ async function preparePlatformSandboxDrainConnection(client, requiredAdmissionPr
6603
6926
  phase,
6604
6927
  cursor
6605
6928
  ]);
6606
- const preparedState = classify((await readCheckpoint()).rows[0]);
6929
+ const checkpoint = await readCheckpoint();
6930
+ const preparedState = classify(checkpoint.rows[0]);
6607
6931
  if (!preparedState) throw new Error("platform: The sandbox-drain database checkpoint could not be established.");
6608
6932
  return preparedState;
6609
6933
  }
@@ -6624,7 +6948,7 @@ async function readRequiredPlatformSafetyProtocols(client) {
6624
6948
  ) AS "required", (SELECT "admission_protocol" FROM "sandbox_drain_checkpoints"
6625
6949
  WHERE "singleton" = true) AS "protocol"`);
6626
6950
  if (admission.rows[0]?.required === true) {
6627
- if (admission.rows[0].protocol != null && admission.rows[0].protocol > 3) throw new Error("platform: The database requires a newer Sandbox controller protocol.");
6951
+ if (admission.rows[0].protocol !== null && admission.rows[0].protocol !== void 0 && admission.rows[0].protocol > 3) throw new Error("platform: The database requires a newer Sandbox controller protocol.");
6628
6952
  return { sandboxDrain: admission.rows[0].protocol === 3 ? 3 : 2 };
6629
6953
  }
6630
6954
  }
@@ -6683,6 +7007,7 @@ async function provisionInstallationServices(input) {
6683
7007
  const { state, now, releaseDatabaseLock, dependencies, writeRemoteInstallationCheckpoint, checkpointOperation, externalHyperdriveOriginHash, runtime, runtimeDirectory, sourcePlatformVersion, hadPriorWorkers } = input;
6684
7008
  const { plan, secrets } = state;
6685
7009
  const routingAction = plan.actions.find((action) => action.key === "routing-kv");
7010
+ if (!routingAction) throw new Error("platform: The plan is missing the routing checkpoint action.");
6686
7011
  if (routingAction.action === "adopt") throw new Error("platform: The routing checkpoint cannot be adopted.");
6687
7012
  if (routingAction.action === "reuse") {
6688
7013
  if (!state.manifest.resources.some((resource) => resource.key === routingAction.key) && routingAction.id) {
@@ -6737,6 +7062,13 @@ async function provisionInstallationServices(input) {
6737
7062
  const authenticationDatabase = state.manifest.resources.find((resource) => resource.key === "hyperdrive");
6738
7063
  if (!authenticationDatabase) throw new Error("platform: The authentication database resource is missing.");
6739
7064
  await verifyPlatformAuthenticationDatabase(dependencies.client, plan.account.id, authenticationDatabase, secrets.databaseUrl);
7065
+ await fitPlatformHyperdriveToDatabase({
7066
+ client: dependencies.client,
7067
+ accountId: plan.account.id,
7068
+ resource: authenticationDatabase,
7069
+ readConnectionSlots: releaseDatabaseLock.readConnectionSlots,
7070
+ onProgress: dependencies.onProgress
7071
+ });
6740
7072
  state.manifest = await preparePlatformDatabaseSchema(state.manifest, runtime, runtimeDirectory, sourcePlatformVersion, hadPriorWorkers, plan, dependencies, releaseDatabaseLock, now, writeRemoteInstallationCheckpoint, (next) => {
6741
7073
  state.manifest = next;
6742
7074
  });
@@ -6751,7 +7083,7 @@ async function provisionInstallationServices(input) {
6751
7083
  const targetSandboxDrainProtocol = runtime.safetyProtocols.sandboxDrain;
6752
7084
  const prepareSandboxDrain = dependencies.prepareSandboxDrain ?? releaseDatabaseLock.prepareSandboxDrain;
6753
7085
  if (targetSandboxDrainProtocol >= 1 && !prepareSandboxDrain) throw new Error("platform: The PostgreSQL lifecycle lock cannot establish the sandbox-drain safety checkpoint.");
6754
- const sandboxDrainPreparation = targetSandboxDrainProtocol >= 1 ? await prepareSandboxDrain(targetSandboxDrainProtocol >= 3 ? 3 : targetSandboxDrainProtocol >= 2 ? 2 : 0) : null;
7086
+ const sandboxDrainPreparation = targetSandboxDrainProtocol >= 1 && prepareSandboxDrain ? await prepareSandboxDrain(targetSandboxDrainProtocol >= 3 ? 3 : targetSandboxDrainProtocol >= 2 ? 2 : 0) : null;
6755
7087
  if (sandboxDrainPreparation && sandboxDrainPreparation.admissionProtocol < targetSandboxDrainProtocol) throw new Error("platform: The database did not arm the Sandbox admission protocol required by this runtime.");
6756
7088
  const sandboxDrainState = sandboxDrainPreparation?.state ?? "complete";
6757
7089
  if (targetSandboxDrainProtocol >= 1 && (state.manifest.safetyProtocols?.sandboxDrain ?? 0) < targetSandboxDrainProtocol) {
@@ -6830,6 +7162,197 @@ function readLatestWorkerGeneration(manifest) {
6830
7162
  function hasCompleteWorkerSecretReplacement(updates, requiresEmailSigningSecret) {
6831
7163
  return PLATFORM_WORKER_SECRET_UPDATE_NAMES.every((name) => name === "EMAIL_SIGNING_SECRET" && !requiresEmailSigningSecret || typeof updates[name] === "string" && updates[name] !== "");
6832
7164
  }
7165
+ // src/cli/platform-security-audits.ts
7166
+ /**
7167
+ * A runtime without the scanner classes must not be paired with the capability: the
7168
+ * API would report security audits as installed and have nothing to run them.
7169
+ */
7170
+ function assertPlatformSecurityAuditsSupported(deployment, runtime) {
7171
+ if (deployment.capabilities.securityAudits && runtime.securityAudits !== 1) throw new Error("platform: This platform runtime does not include security audits. Use a current packaged runtime, or leave out --security-audits.");
7172
+ }
7173
+ const OWNER_BINDING = "__VOID_SECURITY_SCANNER_OWNER";
7174
+ const PROTOCOL = 1;
7175
+ /** Engines A and C each have a container application and a copied image (API M13b). */
7176
+ const ENGINES = [{
7177
+ slug: "engine-a",
7178
+ binding: "SCANNER_ENGINE_A"
7179
+ }, {
7180
+ slug: "engine-c",
7181
+ binding: "SCANNER_ENGINE_C"
7182
+ }];
7183
+ function securityScannerNames(installationId) {
7184
+ const suffix = createHash("sha256").update(`void-security-scanner:${installationId}`).digest("hex").slice(0, 12);
7185
+ const engine = (slug) => ({
7186
+ application: `void-security-scanner-${slug}-${suffix}`,
7187
+ repository: `void-security-scanner-${slug}-${suffix}`
7188
+ });
7189
+ return {
7190
+ worker: `void-security-scanner-${suffix}`,
7191
+ application: `void-security-scanner-${suffix}`,
7192
+ gate: `void-security-scanner-gate-${suffix}`,
7193
+ engines: {
7194
+ "engine-a": engine("engine-a"),
7195
+ "engine-c": engine("engine-c")
7196
+ }
7197
+ };
7198
+ }
7199
+ function ownerMarker(installationId) {
7200
+ return JSON.stringify({
7201
+ protocol: PROTOCOL,
7202
+ installation: installationId
7203
+ });
7204
+ }
7205
+ function plainText(bindings) {
7206
+ return bindings.find((binding) => binding.type === "plain_text" && binding.name === OWNER_BINDING)?.text;
7207
+ }
7208
+ /** `undefined` when Cloudflare answers 404, or 403 too when `forbiddenOk`. */
7209
+ async function optional(read, forbiddenOk = false) {
7210
+ try {
7211
+ return await read();
7212
+ } catch (error) {
7213
+ if (error instanceof PlatformCloudflareApiError && (error.status === 404 || forbiddenOk && error.status === 403)) return;
7214
+ throw error;
7215
+ }
7216
+ }
7217
+ async function deleteIfPresent(client, path) {
7218
+ await optional(() => client.request(path, { method: "DELETE" }));
7219
+ }
7220
+ const REGISTRY = "registry.cloudflare.com";
7221
+ const MANIFEST_ACCEPT = ["application/vnd.oci.image.manifest.v1+json", "application/vnd.docker.distribution.manifest.v2+json"].join(", ");
7222
+ /**
7223
+ * Removes every manifest in the engine image repositories the API copied into this
7224
+ * account (one per engine, named per installation), then the unreferenced layers.
7225
+ * Returns whether anything was removed.
7226
+ */
7227
+ async function deleteScannerImages(client, registryFetch, account, repositories, controllerExists) {
7228
+ const read = () => client.request(`/accounts/${encodeURIComponent(account)}/containers/registries/${REGISTRY}/credentials`, {
7229
+ method: "POST",
7230
+ body: JSON.stringify({
7231
+ expiration_minutes: 15,
7232
+ permissions: ["push", "pull"]
7233
+ })
7234
+ });
7235
+ const credentials = controllerExists ? await read() : await optional(read, true);
7236
+ if (!credentials || typeof credentials.username !== "string" || typeof credentials.password !== "string") return false;
7237
+ const auth = `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString("base64")}`;
7238
+ const call = async (url, init = {}) => {
7239
+ const headers = new Headers(init.headers);
7240
+ if (!headers.has("Authorization")) headers.set("Authorization", auth);
7241
+ if (!headers.has("Accept")) headers.set("Accept", MANIFEST_ACCEPT);
7242
+ return registryFetch(url, {
7243
+ ...init,
7244
+ headers,
7245
+ signal: AbortSignal.timeout(3e4)
7246
+ });
7247
+ };
7248
+ let removed = false;
7249
+ for (const repository of repositories) {
7250
+ const base = `https://${REGISTRY}/v2/${account}/${repository}`;
7251
+ const list = await call(`${base}/tags/list`);
7252
+ if (list.status === 404) {
7253
+ await list.body?.cancel();
7254
+ continue;
7255
+ }
7256
+ if (!list.ok) {
7257
+ await list.body?.cancel();
7258
+ throw new Error(`platform: Listing the security scanner images failed (HTTP ${list.status}).`);
7259
+ }
7260
+ const { tags } = await list.json();
7261
+ for (const tag of Array.isArray(tags) ? tags : []) {
7262
+ if (typeof tag !== "string") continue;
7263
+ const head = await call(`${base}/manifests/${encodeURIComponent(tag)}`, { method: "HEAD" });
7264
+ await head.body?.cancel();
7265
+ if (head.status === 404) continue;
7266
+ const digest = head.headers.get("docker-content-digest");
7267
+ if (head.status !== 200 || !digest) throw new Error(`platform: Reading security scanner image ${repository}:${tag} failed (HTTP ${head.status}).`);
7268
+ const deleted = await call(`${base}/manifests/${digest}`, { method: "DELETE" });
7269
+ await deleted.body?.cancel();
7270
+ if (!deleted.ok && deleted.status !== 404) throw new Error(`platform: Deleting a security scanner image failed (HTTP ${deleted.status}).`);
7271
+ removed = true;
7272
+ }
7273
+ }
7274
+ if (removed) {
7275
+ const gc = await call(`https://${REGISTRY}/v2/gc/layers`, { method: "PUT" });
7276
+ await gc.body?.cancel();
7277
+ if (!gc.ok) throw new Error(`platform: The registry layer cleanup failed (HTTP ${gc.status}).`);
7278
+ }
7279
+ return removed;
7280
+ }
7281
+ /**
7282
+ * Uninstall: the gate first (nothing can call in), then the container applications, the
7283
+ * controller Worker and the engine images. Each must carry this installation's ownership
7284
+ * marker; one that is not ours is left alone and reported.
7285
+ */
7286
+ async function deletePlatformSecurityScanner(client, manifest, registryFetch = (input, init) => fetch(input, init)) {
7287
+ if (!manifest.deployment.capabilities.securityAudits) return {
7288
+ deleted: [],
7289
+ kept: []
7290
+ };
7291
+ const account = encodeURIComponent(manifest.account.id);
7292
+ const names = securityScannerNames(manifest.id);
7293
+ const marker = ownerMarker(manifest.id);
7294
+ const deleted = [];
7295
+ const kept = [];
7296
+ const gatePath = `/accounts/${account}/workers/dispatch/namespaces/${encodeURIComponent(manifest.deployment.resources.dispatchNamespace)}/scripts/${names.gate}`;
7297
+ if (await optional(() => client.request(gatePath)) !== void 0) {
7298
+ if (plainText(await client.request(`${gatePath}/bindings`)) === marker) {
7299
+ await deleteIfPresent(client, gatePath);
7300
+ deleted.push("gate");
7301
+ } else kept.push(`security scanner gate ${names.gate}`);
7302
+ }
7303
+ const workerPath = `/accounts/${account}/workers/scripts/${names.worker}`;
7304
+ const settings = await optional(() => client.request(`${workerPath}/settings`));
7305
+ const targets = [{
7306
+ name: names.application,
7307
+ binding: "SCANNER"
7308
+ }, ...ENGINES.map((engine) => ({
7309
+ name: names.engines[engine.slug].application,
7310
+ binding: engine.binding
7311
+ }))];
7312
+ const found = [];
7313
+ for (const target of targets) {
7314
+ const listApplications = () => client.request(`/accounts/${account}/containers/applications?name=${encodeURIComponent(target.name)}`);
7315
+ const application = (settings ? await listApplications() : await optional(listApplications, true) ?? []).find((entry) => entry.name === target.name);
7316
+ if (application) found.push({
7317
+ ...target,
7318
+ id: application.id,
7319
+ namespace: application.durable_objects?.namespace_id
7320
+ });
7321
+ }
7322
+ const repositories = ENGINES.map((engine) => names.engines[engine.slug].repository);
7323
+ if (!settings) {
7324
+ for (const application of found) kept.push(`security scanner container application ${application.name}`);
7325
+ if (await deleteScannerImages(client, registryFetch, manifest.account.id, repositories, false)) deleted.push("scanner images");
7326
+ return {
7327
+ deleted,
7328
+ kept
7329
+ };
7330
+ }
7331
+ if (plainText(settings.bindings) !== marker) {
7332
+ kept.push(`security scanner controller ${names.worker}`);
7333
+ for (const application of found) kept.push(`security scanner container application ${application.name}`);
7334
+ return {
7335
+ deleted,
7336
+ kept
7337
+ };
7338
+ }
7339
+ let removedApplication = false;
7340
+ for (const application of found) {
7341
+ const namespace = settings.bindings.find((binding) => binding.type === "durable_object_namespace" && binding.name === application.binding)?.namespace_id;
7342
+ if (namespace !== void 0 && application.namespace === namespace) {
7343
+ await deleteIfPresent(client, `/accounts/${account}/containers/applications/${application.id}`);
7344
+ removedApplication = true;
7345
+ } else kept.push(`security scanner container application ${application.name}`);
7346
+ }
7347
+ if (removedApplication) deleted.push("container application");
7348
+ await deleteIfPresent(client, workerPath);
7349
+ deleted.push("controller");
7350
+ if (await deleteScannerImages(client, registryFetch, manifest.account.id, repositories, true)) deleted.push("scanner images");
7351
+ return {
7352
+ deleted,
7353
+ kept
7354
+ };
7355
+ }
6833
7356
  // src/cli/platform-installer.ts
6834
7357
  async function recoverFailedPlatformInstallation(error, state) {
6835
7358
  const { plan, dependencies, workerTrafficGuarded, workerDeploymentCommitted, workerRollbacks, authenticationEnforcementActive, authenticationProtocolTransition, workerCutoverGeneration, previousPublicEndpoints, operationStarted, now, writeRemoteInstallationCheckpoint } = state;
@@ -6883,6 +7406,7 @@ async function installPlatform(plan, secrets, existing, dependencies) {
6883
7406
  const runtime = resolvedRuntime.manifest;
6884
7407
  if (plan.deployment.appAccess && runtime.appAccessSetup !== 1) throw new Error("platform: This runtime does not support the installation’s app access setup.");
6885
7408
  assertPlatformRuntimeLogsSupported(plan.deployment, runtime);
7409
+ assertPlatformSecurityAuditsSupported(plan.deployment, runtime);
6886
7410
  assertPlatformStorageSupported(plan.deployment, runtime);
6887
7411
  const hasEmailGatewayArtifact = runtime.artifacts.emailGateway !== void 0;
6888
7412
  if (existing?.steps.some((step) => step.key === "private-previews-initialized:v1") && runtime.privatePreviews !== 1) throw new Error("platform: This installation has private previews. Use a runtime with private preview support.");
@@ -7105,6 +7629,7 @@ async function installPlatform(plan, secrets, existing, dependencies) {
7105
7629
  deployment: state.plan.deployment,
7106
7630
  deploymentExecution: runtime.deploymentExecution,
7107
7631
  healthProbeToken: createPlatformHealthProbeToken(state.manifest.ownershipNonce),
7632
+ securityScanScheduler: runtime.securityAudits === 1,
7108
7633
  installationId: state.manifest.id,
7109
7634
  ownershipNonce: state.manifest.ownershipNonce,
7110
7635
  platformVersion: version,
@@ -7126,7 +7651,10 @@ async function installPlatform(plan, secrets, existing, dependencies) {
7126
7651
  publicEndpoints: !preserveDisabled,
7127
7652
  trafficState: preserveDisabled ? "staging" : "enabled"
7128
7653
  });
7129
- const outsideChangeConfigs = workerKeys.map((key) => enabledConfigs[key]).filter((config) => dependencies.replaceOutsideChanges?.includes(String(config.name)));
7654
+ const outsideChangeConfigs = workerKeys.flatMap((key) => {
7655
+ const config = enabledConfigs[key];
7656
+ return dependencies.replaceOutsideChanges?.includes(String(config.name)) ? [config] : [];
7657
+ });
7130
7658
  if (outsideChangeConfigs.length > 0) await dependencies.uploadOutsideChanges?.(outsideChangeConfigs);
7131
7659
  if (requiresTrafficGuard) {
7132
7660
  await dependencies.client.putKvValue(state.plan.account.id, requireId(ids, "routing-kv"), PLATFORM_DISABLED_KEY, PLATFORM_DISABLED_VALUE);
@@ -7300,14 +7828,16 @@ async function installPlatform(plan, secrets, existing, dependencies) {
7300
7828
  await writeRemoteInstallationCheckpoint(dependencies.client, state.plan, state.manifest);
7301
7829
  }
7302
7830
  if (state.plan.deployment.appAccess && !state.manifest.steps.some((step) => step.key === "app-access-initialized:v1")) {
7831
+ const { appAccessSetupJson, appAccessSetupToken } = state.secrets;
7832
+ if (!appAccessSetupJson || !appAccessSetupToken) throw new Error("platform: The deployed-app access setup material is missing.");
7303
7833
  dependencies.onProgress?.("Configuring and verifying deployed-app access");
7304
7834
  try {
7305
7835
  await (dependencies.initializeAppAccess ?? initializeInstalledAppAccess)({
7306
7836
  apiUrl: state.plan.apiUrl,
7307
7837
  installationId: state.manifest.id,
7308
7838
  probeToken: createPlatformHealthProbeToken(state.manifest.ownershipNonce),
7309
- setupJson: state.secrets.appAccessSetupJson,
7310
- setupToken: state.secrets.appAccessSetupToken
7839
+ setupJson: appAccessSetupJson,
7840
+ setupToken: appAccessSetupToken
7311
7841
  });
7312
7842
  } catch (error) {
7313
7843
  if (error instanceof PlatformAppAccessCredentialError) {
@@ -7325,7 +7855,7 @@ async function installPlatform(plan, secrets, existing, dependencies) {
7325
7855
  state.manifest = recordInstallationStep(state.manifest, {
7326
7856
  key: "app-access-initialized:v1",
7327
7857
  completedAt: now(),
7328
- resultHash: hash(state.secrets.appAccessSetupJson)
7858
+ resultHash: hash(appAccessSetupJson)
7329
7859
  }, now());
7330
7860
  writeInstallationManifest(state.manifest);
7331
7861
  await writeRemoteInstallationCheckpoint(dependencies.client, state.plan, state.manifest);
@@ -7371,6 +7901,7 @@ async function installPlatform(plan, secrets, existing, dependencies) {
7371
7901
  zoneNameServers: zone?.nameServers ?? []
7372
7902
  };
7373
7903
  }
7904
+ if (!prepareSandboxDrain) throw new Error("platform: No sandbox drain checkpoint. Traffic remains disabled.");
7374
7905
  if ((await prepareSandboxDrain()).state !== "complete") throw new Error("platform: Sandbox drain completion changed while it was being verified. Traffic remains disabled.");
7375
7906
  }
7376
7907
  const emailOperationId = (await enableInstallationServices({
@@ -7464,12 +7995,11 @@ async function selectInstallationAuthentication(file, recorded, choices = {}) {
7464
7995
  if (file) {
7465
7996
  const input = JSON.parse(await readFile(file, "utf8"));
7466
7997
  if (!input || typeof input !== "object" || Array.isArray(input) || !("connections" in input) || !Array.isArray(input.connections) || !input.connections.length || input.connections.length > 32) throw new Error("platform: An authentication file must define between 1 and 32 connections.");
7467
- const entries = input.connections;
7468
- if (entries.some((entry) => !entry || typeof entry !== "object" || !entry.configuration || typeof entry.configuration !== "object" || Array.isArray(entry.configuration) || !PLATFORM_LOGIN_KINDS.includes(entry.configuration.kind) || entry.clientSecret !== void 0 || entry.configuration.clientSecret !== void 0)) throw new Error("platform: Each connection needs a supported configuration and a clientSecretEnv reference; plaintext secrets are not accepted in the file.");
7998
+ if (input.connections.some((entry) => !entry || typeof entry !== "object" || !entry.configuration || typeof entry.configuration !== "object" || Array.isArray(entry.configuration) || !PLATFORM_LOGIN_KINDS.includes(entry.configuration.kind) || entry.clientSecret !== void 0 || entry.configuration.clientSecret !== void 0)) throw new Error("platform: Each connection needs a supported configuration and a clientSecretEnv reference; plaintext secrets are not accepted in the file.");
7469
7999
  const selected = input;
7470
8000
  if (selected.cloudflareAccess !== void 0) selected.cloudflareAccess = parsePlatformAccessSetupSpec(selected.cloudflareAccess);
7471
8001
  const authentication = {
7472
- providers: [...new Set(entries.map((entry) => entry.configuration.kind))],
8002
+ providers: [...new Set(selected.connections.map((entry) => entry.configuration.kind))],
7473
8003
  configurable: true,
7474
8004
  ...selected.protection ? { accessProtection: true } : {}
7475
8005
  };
@@ -7537,9 +8067,11 @@ async function collectInstallationAuthentication(selection, plan, checkpoint, sa
7537
8067
  }));
7538
8068
  const connections = [];
7539
8069
  const accessEntry = entries.find((entry) => entry.configuration.kind === "cloudflare-access");
7540
- const prepared = access && (selection.authentication.accessProtection || accessEntry && (!selection.file || selection.file.cloudflareAccess)) ? await preparePlatformAccessSetup({
8070
+ const prepareAccess = access && (selection.authentication.accessProtection || accessEntry && (!selection.file || selection.file.cloudflareAccess));
8071
+ const dashboardUrl = prepareAccess ? platformDashboardUrl(plan.deployment) : void 0;
8072
+ const prepared = access && prepareAccess ? await preparePlatformAccessSetup({
7541
8073
  plan,
7542
- ...platformDashboardUrl(plan.deployment) ? { additionalOrigins: [platformDashboardUrl(plan.deployment)] } : {},
8074
+ ...dashboardUrl ? { additionalOrigins: [dashboardUrl] } : {},
7543
8075
  ownershipNonce: access.ownershipNonce,
7544
8076
  protection: !!selection.authentication.accessProtection,
7545
8077
  ...accessEntry ? { login: {
@@ -7687,16 +8219,18 @@ function authenticationSetupRequestHash(setupJson) {
7687
8219
  const { resetPending: _, ...configuration } = parsePlatformAuthenticationSetup(JSON.parse(setupJson));
7688
8220
  return createHash("sha256").update(JSON.stringify(configuration)).digest("hex");
7689
8221
  }
8222
+ const connections = (entries) => entries.map(({ configuration: { id, kind } }) => JSON.stringify([id || defaultConnectionId(kind), kind])).sort().join("\n");
7690
8223
  /**
7691
8224
  * Read a repair login file. It may change login settings, not methods or Access
7692
8225
  * protection: it lists the same connection IDs and kinds as the saved setup.
7693
8226
  */
7694
8227
  async function readLoginReplacementFile(file, authentication, setupJson) {
7695
8228
  const selection = await selectInstallationAuthentication(file);
8229
+ const selected = selection.file;
8230
+ if (!selected) throw new Error("platform: Repair requires a login settings file.");
7696
8231
  const installed = parsePlatformAuthenticationSetup(JSON.parse(setupJson)).connections;
7697
- const connections = (entries) => entries.map(({ configuration: { id, kind } }) => JSON.stringify([id || defaultConnectionId(kind), kind])).sort().join("\n");
7698
- if (connections(selection.file.connections) !== connections(installed) || !!selection.authentication.accessProtection !== !!authentication.accessProtection) throw new Error(`platform: Repair changes login settings, not which login methods or Access protection the platform uses. List each installed connection with its ID: ${installed.map(({ configuration }) => configuration.id).join(", ")}.`);
7699
- return selection.file;
8232
+ if (connections(selected.connections) !== connections(installed) || !!selection.authentication.accessProtection !== !!authentication.accessProtection) throw new Error(`platform: Repair changes login settings, not which login methods or Access protection the platform uses. List each installed connection with its ID: ${installed.map(({ configuration }) => configuration.id).join(", ")}.`);
8233
+ return selected;
7700
8234
  }
7701
8235
  /**
7702
8236
  * New login settings for a first administrator setup that is still pending,
@@ -7786,7 +8320,7 @@ function unreadablePlatformWorker(workerName, error) {
7786
8320
  return new Error([
7787
8321
  `platform: Void cannot read the platform Worker ${workerName} (${answer}), so it cannot find changes made outside Void.`,
7788
8322
  NO_WORKER_CHANGED,
7789
- status === 401 || status === 403 ? "Make sure that the Cloudflare API token has Account → Workers Scripts → Edit for this account. Then run the command again." : "Run the command again."
8323
+ status === 401 || status === 403 ? `Make sure that the Cloudflare API token has ${PLATFORM_WORKERS_PERMISSION} for this account. Then run the command again.` : "Run the command again."
7790
8324
  ].join(" "), { cause: error });
7791
8325
  }
7792
8326
  /**
@@ -7988,7 +8522,7 @@ function readSavedPlatformInstallPlan(path, id) {
7988
8522
  return plan;
7989
8523
  } catch (error) {
7990
8524
  if (error.code === "ENOENT") throw error;
7991
- throw new Error(`platform: Invalid saved installation plan ${path}: ${error instanceof Error ? error.message : String(error)}`);
8525
+ throw new Error(`platform: Invalid saved installation plan ${path}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
7992
8526
  }
7993
8527
  }
7994
8528
  function findSavedPlatformInstallPlan(account, name, directory = platformRegistryDirectory()) {
@@ -8081,17 +8615,23 @@ function resolvePlatformInstallDatabaseUrl(checkpoint, manifest = null) {
8081
8615
  }
8082
8616
  return explicit || recorded;
8083
8617
  }
8618
+ const assertNewNameAvailable = (slug) => {
8619
+ const collision = listInstallationManifests().find((manifest) => manifest.status !== "uninstalled" && manifest.deployment.installationSlug === slug);
8620
+ if (collision && !isPlatformInstallInProgress(collision)) throw new Error(`platform: ${collision.deployment.displayName} (${slug}) already exists (${collision.status}). Run \`void platform status ${collision.id}\` to inspect it.`);
8621
+ assertPlatformInstallationSlugAvailable(slug);
8622
+ };
8084
8623
  async function runPlatformLifecycleCommand(commandArgs) {
8085
8624
  if (commandArgs.subcommand === "domain") {
8086
- const { runPlatformDomainCommand } = await import("./platform-domain-DB_KpVhg.mjs");
8625
+ const { runPlatformDomainCommand } = await import("./platform-domain-CRsRJOws.mjs");
8087
8626
  await runPlatformDomainCommand(commandArgs);
8088
8627
  return;
8089
8628
  }
8090
8629
  if (commandArgs.subcommand === "discover") {
8091
8630
  log.step("Preparing platform discovery");
8092
- const client = new PlatformCloudflareClient((await resolvePlatformCloudflareCredential()).token);
8631
+ const credential = await resolvePlatformCloudflareCredential();
8632
+ const client = new PlatformCloudflareClient(credential.token, { credential: platformOperatorCredentialLabel(credential) });
8093
8633
  const accountId = await selectAccount(await withPlatformProgress("Reading Cloudflare accounts", () => readAccounts(client)), commandArgs.account);
8094
- const { recoverPlatformInstallations } = await import("./platform-recovery-ZAXin6WK.mjs");
8634
+ const { recoverPlatformInstallations } = await import("./platform-recovery-poxgOOAY.mjs");
8095
8635
  const recovered = await withPlatformProgress("Discovering platform installations", () => recoverPlatformInstallations(client, accountId, void 0, commandArgs.selector));
8096
8636
  if (recovered.length === 0) {
8097
8637
  log.info(`No recoverable Void platform installations were found in ${accountId}.`);
@@ -8102,7 +8642,7 @@ async function runPlatformLifecycleCommand(commandArgs) {
8102
8642
  return;
8103
8643
  }
8104
8644
  if (commandArgs.subcommand !== "install") {
8105
- const { runInstalledPlatformCommand } = await import("./platform-management-7Bf_OgS5.mjs");
8645
+ const { runInstalledPlatformCommand } = await import("./platform-management-BRGhD-oF.mjs");
8106
8646
  await runInstalledPlatformCommand(commandArgs);
8107
8647
  return;
8108
8648
  }
@@ -8124,15 +8664,10 @@ async function runPlatformLifecycleCommand(commandArgs) {
8124
8664
  selectedInstall = true;
8125
8665
  selectedDraft = isPlatformSetupDraft(manifest);
8126
8666
  };
8127
- const assertNewNameAvailable = (slug) => {
8128
- const collision = listInstallationManifests().find((manifest) => manifest.status !== "uninstalled" && manifest.deployment.installationSlug === slug);
8129
- if (collision && !isPlatformInstallInProgress(collision)) throw new Error(`platform: ${collision.deployment.displayName} (${slug}) already exists (${collision.status}). Run \`void platform status ${collision.id}\` to inspect it.`);
8130
- assertPlatformInstallationSlugAvailable(slug);
8131
- };
8132
8667
  if (!args.resume && process.stdin.isTTY) {
8133
8668
  const installs = resumableInstalls().filter((manifest) => !args.name || manifest.deployment.installationSlug === normalizeInstallationSlug(args.name));
8134
8669
  const manifests = listInstallationManifests();
8135
- const savedPlans = !args.applicationDomain && !args.workersDev && !args.zone && !args.displayName && !args.hyperdrive && !args.controlPlaneDomain && !args.noControlPlaneDomain && !args.authConfig && !args.loginMethods && !args.runtime && args.accessProtection === void 0 && args.appAccess === void 0 && !args.dedicatedZoneSpecified && args.dashboardUrl === void 0 && !args.customDomains && args.runtimeLogs === void 0 && args.storageLocation === void 0 ? listSavedPlatformInstallPlans().filter((saved) => (!args.name || saved.args.name === normalizeInstallationSlug(args.name)) && (!args.account || saved.args.account === args.account || saved.accountName.toLowerCase() === args.account.toLowerCase()) && !manifests.some((manifest) => manifest.status !== "uninstalled" && manifest.account.id === saved.args.account && manifest.deployment.installationSlug === saved.args.name)) : [];
8670
+ const savedPlans = !args.applicationDomain && !args.workersDev && !args.zone && !args.displayName && !args.hyperdrive && !args.controlPlaneDomain && !args.noControlPlaneDomain && !args.authConfig && !args.loginMethods && !args.runtime && args.accessProtection === void 0 && args.appAccess === void 0 && !args.dedicatedZoneSpecified && args.dashboardUrl === void 0 && !args.customDomains && !args.securityAudits && args.runtimeLogs === void 0 && args.storageLocation === void 0 ? listSavedPlatformInstallPlans().filter((saved) => (!args.name || saved.args.name === normalizeInstallationSlug(args.name)) && (!args.account || saved.args.account === args.account || saved.accountName.toLowerCase() === args.account.toLowerCase()) && !manifests.some((manifest) => manifest.status !== "uninstalled" && manifest.account.id === saved.args.account && manifest.deployment.installationSlug === saved.args.name)) : [];
8136
8671
  if (installs.length > 0 || savedPlans.length > 0) {
8137
8672
  const choice = await select({
8138
8673
  message: "Continue a previous platform install?",
@@ -8219,12 +8754,12 @@ async function runPlatformLifecycleCommand(commandArgs) {
8219
8754
  if (existing.endpoints.apiUrl && !readPendingInstallationSecrets(existing)) throw new Error(`platform: Installation ${existing.id} has already been deployed. Use \`void platform repair ${existing.id}\` or \`void platform upgrade ${existing.id}\` instead.`);
8220
8755
  return existing.deployment.installationSlug;
8221
8756
  });
8222
- let client = new PlatformCloudflareClient(operatorCredential.token);
8757
+ let client = new PlatformCloudflareClient(operatorCredential.token, { credential: platformOperatorCredentialLabel(operatorCredential) });
8223
8758
  const accounts = await withPlatformProgress("Reading Cloudflare accounts", () => readAccounts(client));
8224
8759
  const accountId = existing ? existing.account.id : await selectAccount(accounts, args.account);
8225
8760
  if (existing && args.account && await selectAccount(accounts, args.account) !== existing.account.id) throw new Error("platform: The installation belongs to a different Cloudflare account.");
8226
8761
  const recorded = existing?.deployment;
8227
- if (existing && isPlatformSetupDraft(existing) && (args.applicationDomain && normalizeApplicationDomain(args.applicationDomain) !== recorded.application.baseDomain || args.zone && normalizeApplicationDomain(args.zone) !== recorded.application.zoneName || args.workersDev && !!recorded.application.zoneName || args.controlPlaneDomain && normalizeApplicationDomain(args.controlPlaneDomain) !== recorded.controlPlane.apiHostname || args.dedicatedZone && !recorded.application.dedicatedZone)) throw new Error("platform: These options differ from the saved setup. Resume its recorded configuration or choose another installation name.");
8762
+ if (existing && recorded && isPlatformSetupDraft(existing) && (args.applicationDomain && normalizeApplicationDomain(args.applicationDomain) !== recorded.application.baseDomain || args.zone && normalizeApplicationDomain(args.zone) !== recorded.application.zoneName || args.workersDev && !!recorded.application.zoneName || args.controlPlaneDomain && normalizeApplicationDomain(args.controlPlaneDomain) !== recorded.controlPlane.apiHostname || args.dedicatedZone && !recorded.application.dedicatedZone)) throw new Error("platform: These options differ from the saved setup. Resume its recorded configuration or choose another installation name.");
8228
8763
  let workersDev = !!recorded?.application.workersDev && !recorded.application.zoneName || args.workersDev === true;
8229
8764
  if (!recorded && !args.workersDev && !args.applicationDomain && !args.zone && process.stdin.isTTY) {
8230
8765
  const mode = await select({
@@ -8276,7 +8811,7 @@ async function runPlatformLifecycleCommand(commandArgs) {
8276
8811
  progress?.stop("Read the saved installation.");
8277
8812
  progress = void 0;
8278
8813
  if (authoritative) {
8279
- const { selectAuthoritativePlatformManifest } = await import("./platform-management-7Bf_OgS5.mjs");
8814
+ const { selectAuthoritativePlatformManifest } = await import("./platform-management-BRGhD-oF.mjs");
8280
8815
  const selected = selectAuthoritativePlatformManifest(existing, authoritative);
8281
8816
  authoritativeProvisionIntents = true;
8282
8817
  if (!args.plan && JSON.stringify(selected) !== JSON.stringify(existing)) writeInstallationManifest(selected);
@@ -8403,6 +8938,7 @@ async function runPlatformLifecycleCommand(commandArgs) {
8403
8938
  controlPlaneDomain,
8404
8939
  ...args.dashboardUrl !== void 0 ? { dashboardUrl: args.dashboardUrl } : {},
8405
8940
  ...args.customDomains ? { customDomains: true } : {},
8941
+ ...args.securityAudits ? { securityAudits: true } : {},
8406
8942
  dedicatedZone,
8407
8943
  displayName,
8408
8944
  ...externalHyperdrive ? { externalHyperdrive } : {},
@@ -8423,6 +8959,7 @@ async function runPlatformLifecycleCommand(commandArgs) {
8423
8959
  };
8424
8960
  let plan = await withPlatformProgress("Preparing installation plan", () => createPlatformInstallPlan(client, planInput, existing, planOptions));
8425
8961
  assertPlatformRuntimeLogsSupported(plan.deployment, runtime.manifest);
8962
+ assertPlatformSecurityAuditsSupported(plan.deployment, runtime.manifest);
8426
8963
  assertPlatformStorageSupported(plan.deployment, runtime.manifest);
8427
8964
  const commandOptions = {
8428
8965
  commandName: cliCommandName(),
@@ -8434,6 +8971,7 @@ async function runPlatformLifecycleCommand(commandArgs) {
8434
8971
  controlPlaneDomain,
8435
8972
  ...args.dashboardUrl !== void 0 ? { dashboardUrl: args.dashboardUrl } : {},
8436
8973
  ...args.customDomains ? { customDomains: true } : {},
8974
+ ...args.securityAudits ? { securityAudits: true } : {},
8437
8975
  dedicatedZone,
8438
8976
  workersDev,
8439
8977
  authConfig: args.authConfig,
@@ -8480,6 +9018,7 @@ async function runPlatformLifecycleCommand(commandArgs) {
8480
9018
  let managementApiToken = operatorCredential.source === "oauth" ? checkpoint?.managementApiToken || "" : "";
8481
9019
  if (needsManagementToken || managementApiToken) {
8482
9020
  let token = managementApiToken;
9021
+ let tokenSource = token ? "saved" : "entered";
8483
9022
  let openedManagementPage = false;
8484
9023
  const forgetRejectedManagementToken = () => {
8485
9024
  managementApiToken = "";
@@ -8496,8 +9035,15 @@ async function runPlatformLifecycleCommand(commandArgs) {
8496
9035
  openedManagementPage = true;
8497
9036
  }
8498
9037
  token = (await promptSecret("Paste management API token:", true, (value) => value.trim() ? void 0 : "A value is required.")).trim();
9038
+ tokenSource = "entered";
8499
9039
  }
8500
- const management = new PlatformCloudflareClient(token, { apiBase: client.apiBaseUrl });
9040
+ const management = new PlatformCloudflareClient(token, {
9041
+ apiBase: client.apiBaseUrl,
9042
+ credential: {
9043
+ role: "management",
9044
+ source: tokenSource
9045
+ }
9046
+ });
8501
9047
  try {
8502
9048
  if (!(await management.listAccounts()).some((account) => account.id === accountId)) {
8503
9049
  forgetRejectedManagementToken();
@@ -8513,8 +9059,14 @@ async function runPlatformLifecycleCommand(commandArgs) {
8513
9059
  break;
8514
9060
  } catch (error) {
8515
9061
  if (!isPlatformTokenAuthorizationError(error)) throw error;
8516
- const details = /* @__PURE__ */ new Set();
8517
- for (let cause = error, depth = 0; depth < 5 && cause instanceof Error; depth++, cause = cause.cause) details.add(cause.message.replaceAll(token, "[redacted]"));
9062
+ const details = [];
9063
+ const listed = /* @__PURE__ */ new Set();
9064
+ for (let cause = error, depth = 0; depth < 5 && cause instanceof Error; depth++, cause = cause.cause) {
9065
+ if (listed.has(cause)) continue;
9066
+ if (cause instanceof AggregateError) for (const listedError of cause.errors) listed.add(listedError);
9067
+ const message = cause.message.replaceAll(token, "[redacted]");
9068
+ if (!details.some((detail) => detail.includes(message))) details.push(message);
9069
+ }
8518
9070
  forgetRejectedManagementToken();
8519
9071
  log.warn([...details, "Check the token permissions and account/zone scope, then paste a replacement."].join("\n"));
8520
9072
  }
@@ -8558,17 +9110,22 @@ async function runPlatformLifecycleCommand(commandArgs) {
8558
9110
  let rejectedSavedRuntimeToken = false;
8559
9111
  const verifyRuntimeToken = async (token) => {
8560
9112
  let checkingRuntimePermissions = true;
9113
+ const credential = {
9114
+ role: "runtime",
9115
+ source: token === process.env.VOID_PLATFORM_RUNTIME_CLOUDFLARE_API_TOKEN ? "environment" : token === values.cloudflareApiToken ? "saved" : "entered"
9116
+ };
8561
9117
  try {
8562
- await verifyPlatformRuntimeTokenPermissions(new PlatformCloudflareClient(token), {
9118
+ await verifyPlatformRuntimeTokenPermissions(new PlatformCloudflareClient(token, { credential }), {
8563
9119
  accountId,
8564
9120
  applicationDomain,
9121
+ credential,
8565
9122
  customDomains: plan.deployment.capabilities.customDomains,
8566
9123
  ...plan.deployment.capabilities.email && plan.deployment.emailSharedZoneId ? { emailZoneId: plan.deployment.emailSharedZoneId } : {},
8567
9124
  zoneId: plan.zone?.id ?? null
8568
9125
  });
8569
9126
  checkingRuntimePermissions = false;
8570
9127
  if (plan.actions.some((action) => action.action === "inspect")) {
8571
- client = client.withAiGatewayToken(token);
9128
+ client = client.withAiGatewayToken(token, credential);
8572
9129
  plan = await verifyPlatformAiGatewayPlan(client, planInput, existing, plan, authoritativeProvisionIntents);
8573
9130
  }
8574
9131
  } catch (error) {
@@ -8747,7 +9304,7 @@ async function runPlatformLifecycleCommand(commandArgs) {
8747
9304
  })).actions.filter((action) => action.kind === "worker"),
8748
9305
  revalidateBeforeWorkerDeploy: (manifest, action) => revalidatePlatformInstallAction(client, plan, manifest, action),
8749
9306
  verifyExistingOwnership: async (manifest, databaseCheckpointExists) => {
8750
- const { verifyPlatformInstallationOwnership } = await import("./platform-management-7Bf_OgS5.mjs");
9307
+ const { verifyPlatformInstallationOwnership } = await import("./platform-management-BRGhD-oF.mjs");
8751
9308
  const retainedReplacementKeys = new Set(plan.actions.filter((action) => {
8752
9309
  const previous = manifest.resources.find((resource) => resource.key === action.key);
8753
9310
  return action.action === "create" && previous && previous.name !== action.name;
@@ -8812,8 +9369,15 @@ async function runPlatformLifecycleCommand(commandArgs) {
8812
9369
  }
8813
9370
  }
8814
9371
  function isPlatformTokenAuthorizationError(error, requestPathIncludes) {
8815
- for (let depth = 0; depth < 5 && error instanceof Error; depth++, error = error.cause) if (error instanceof PlatformCloudflareApiError && [401, 403].includes(error.status) && (!requestPathIncludes || error.requestPath?.includes(requestPathIncludes))) return true;
8816
- return false;
9372
+ return !!findPlatformTokenAuthorizationError(error, requestPathIncludes);
9373
+ }
9374
+ function findPlatformTokenAuthorizationError(error, requestPathIncludes) {
9375
+ for (let depth = 0; depth < 5 && error instanceof Error; depth++, error = error.cause) if (error instanceof PlatformCloudflareApiError && [401, 403].includes(error.status) && (!requestPathIncludes || error.requestPath?.includes(requestPathIncludes))) return error;
9376
+ }
9377
+ /** What the client said about the AI Gateway credential it used, if it knew it. */
9378
+ function platformCredentialHelpInChain(error) {
9379
+ const denied = findPlatformTokenAuthorizationError(error, "/ai-gateway/");
9380
+ return denied?.credential ? platformCredentialHelp(denied.credential, denied.status, denied.requestPath) : void 0;
8817
9381
  }
8818
9382
  function formatPlatformRuntime(runtime) {
8819
9383
  return [
@@ -8833,7 +9397,10 @@ async function verifyPlatformAiGatewayPlan(client, input, existing, preview, aut
8833
9397
  deploymentExecution: preview.actions.some((entry) => entry.key === "deployment-queue")
8834
9398
  });
8835
9399
  } catch (error) {
8836
- if (isPlatformTokenAuthorizationError(error, "/ai-gateway/")) throw new Error("platform: The runtime token could not verify AI Gateway access. Include Account → AI Gateway → Edit for this account, then retry. No platform resources were created.", { cause: error });
9400
+ if (isPlatformTokenAuthorizationError(error, "/ai-gateway/")) {
9401
+ const help = platformCredentialHelpInChain(error);
9402
+ throw new Error(help ? `platform: The runtime token could not verify AI Gateway access. ${help} No platform resources were created.` : "platform: The runtime token could not verify AI Gateway access. Include Account → AI Gateway → Edit for this account, then retry. No platform resources were created.", { cause: error });
9403
+ }
8837
9404
  throw error;
8838
9405
  }
8839
9406
  assertPlatformInstallPlanUnchanged(preview, verified, "AI Gateway access");
@@ -8914,4 +9481,4 @@ async function promptSecret(message, masked = true, validate, placeholder) {
8914
9481
  if (isCancel(value) || typeof value === "symbol") throw new Error("platform: Cancelled.");
8915
9482
  return value;
8916
9483
  }
8917
- export { hyperdriveOriginConfigHash as $, recordPlatformWorkerTraffic as A, revalidatePlatformInstallAction as B, readPlatformDatabase as C, resolveBootstrapGitHubId as D, createPlatformInstallationSecrets as E, legacyResourceConfigHash as F, verifyPlatformCloudflareCredential as G, turnOffInstalledProjectZeroTrust as H, matchesRecordedR2Fingerprint as I, parsePlatformAccessSetupSpec as J, activatePlatformAccessCredentials as K, platformAdoptionIntentHash as L, dnsRecordConfigHash as M, formatPlatformInstallPlan as N, recordResource as O, hasProvisionIntentStep as P, PlatformRuntimeTokenEmailPermissionError as Q, r2BucketConfigHash as R, formatZeroTrustApplications as S, createPlatformHealthProbeToken as T, assertPlatformOperatorCredentialCanApplyPlan as U, platformDatabaseNameFromOwnerUrl as V, resolvePlatformCloudflareCredential as W, PlatformCloudflareApiError as X, preparePlatformAccessSetup as Y, PlatformCloudflareClient as Z, acquirePlatformDatabaseLifecycleLockConnection as _, createPlatformProgress as a, readPlatformProjectZeroTrustState as b, formatPlatformWorkerOutsideChanges as c, authenticationSetupRequestHash as d, hyperdriveOriginFromConnectionString as et, readLoginReplacementFile as f, acquirePlatformDatabaseLifecycleLock as g, installPlatform as h, verifyPlatformAiGatewayPlan as i, createPlatformInstallPlan as j, platformTrafficAttachmentWorker as k, reviewPlatformWorkerOutsideChanges as l, REMOTE_INSTALLATION_MANIFEST_KEY as m, resolvePlatformInstallDatabaseUrl as n, verifyPlatformRuntimeTokenEmailPermissions as nt, withPlatformProgress as o, replacePendingInstallationAuthentication as p, checkpointPlatformAccessResources as q, runPlatformLifecycleCommand as r, verifyPlatformRuntimeTokenPermissions as rt, findPlatformWorkerOutsideChanges as s, assertNoninteractivePlatformMutationAcknowledged as t, hyperdriveOriginMatches as tt, uploadPlatformWorkerOutsideChanges as u, platformDatabaseClientUrl as v, loadPlatformRuntime as w, assertProjectZeroTrustAllowsUninstall as x, readPlatformProjectSlugs as y, resourceMarkerProblem as z };
9484
+ export { PlatformCloudflareApiError as $, recordResource as A, r2BucketConfigHash as B, assertProjectZeroTrustAllowsUninstall as C, createPlatformHealthProbeToken as D, loadPlatformRuntime as E, formatPlatformInstallPlan as F, assertPlatformOperatorCredentialCanApplyPlan as G, revalidatePlatformInstallAction as H, hasProvisionIntentStep as I, verifyPlatformCloudflareCredential as J, platformOperatorCredentialLabel as K, legacyResourceConfigHash as L, recordPlatformWorkerTraffic as M, createPlatformInstallPlan as N, createPlatformInstallationSecrets as O, dnsRecordConfigHash as P, preparePlatformAccessSetup as Q, matchesRecordedR2Fingerprint as R, readPlatformProjectZeroTrustState as S, readPlatformDatabase as T, platformDatabaseNameFromOwnerUrl as U, resourceMarkerProblem as V, turnOffInstalledProjectZeroTrust as W, checkpointPlatformAccessResources as X, activatePlatformAccessCredentials as Y, parsePlatformAccessSetupSpec as Z, deletePlatformSecurityScanner as _, createPlatformProgress as a, verifyPlatformRuntimeTokenEmailPermissions as at, platformDatabaseClientUrl as b, formatPlatformWorkerOutsideChanges as c, authenticationSetupRequestHash as d, PlatformCloudflareClient as et, readLoginReplacementFile as f, assertPlatformSecurityAuditsSupported as g, installPlatform as h, verifyPlatformAiGatewayPlan as i, hyperdriveOriginMatches as it, platformTrafficAttachmentWorker as j, resolveBootstrapGitHubId as k, reviewPlatformWorkerOutsideChanges as l, REMOTE_INSTALLATION_MANIFEST_KEY as m, resolvePlatformInstallDatabaseUrl as n, hyperdriveOriginConfigHash as nt, withPlatformProgress as o, verifyPlatformRuntimeTokenPermissions as ot, replacePendingInstallationAuthentication as p, resolvePlatformCloudflareCredential as q, runPlatformLifecycleCommand as r, hyperdriveOriginFromConnectionString as rt, findPlatformWorkerOutsideChanges as s, PLATFORM_WORKERS_PERMISSION as st, assertNoninteractivePlatformMutationAcknowledged as t, PlatformRuntimeTokenEmailPermissionError as tt, uploadPlatformWorkerOutsideChanges as u, acquirePlatformDatabaseLifecycleLock as v, formatZeroTrustApplications as w, readPlatformProjectSlugs as x, acquirePlatformDatabaseLifecycleLockConnection as y, platformAdoptionIntentHash as z };