@geekmidas/cli 10.0.0-alpha.160 → 10.0.0-alpha.161

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 (219) hide show
  1. package/dist/{GoDaddyProvider-DkUMcMYy.cjs → GoDaddyProvider-CBqsvbER.cjs} +2 -2
  2. package/dist/{GoDaddyProvider-DkUMcMYy.cjs.map → GoDaddyProvider-CBqsvbER.cjs.map} +1 -1
  3. package/dist/{GoDaddyProvider-C9dDlH9I.mjs → GoDaddyProvider-CwqdLM1E.mjs} +2 -2
  4. package/dist/{GoDaddyProvider-C9dDlH9I.mjs.map → GoDaddyProvider-CwqdLM1E.mjs.map} +1 -1
  5. package/dist/{HostingerProvider-9faYOQnQ.cjs → HostingerProvider-DtOtsFkM.cjs} +2 -2
  6. package/dist/{HostingerProvider-9faYOQnQ.cjs.map → HostingerProvider-DtOtsFkM.cjs.map} +1 -1
  7. package/dist/{HostingerProvider-BEuKG2gz.mjs → HostingerProvider-gD4uqzMN.mjs} +2 -2
  8. package/dist/{HostingerProvider-BEuKG2gz.mjs.map → HostingerProvider-gD4uqzMN.mjs.map} +1 -1
  9. package/dist/{LegacyStateStore-DPKhjUR6.mjs → LegacyStateStore-6xsGADme.mjs} +3 -3
  10. package/dist/{LegacyStateStore-DPKhjUR6.mjs.map → LegacyStateStore-6xsGADme.mjs.map} +1 -1
  11. package/dist/{LegacyStateStore-C44jUnMH.cjs → LegacyStateStore-C0rm5slD.cjs} +3 -3
  12. package/dist/{LegacyStateStore-C44jUnMH.cjs.map → LegacyStateStore-C0rm5slD.cjs.map} +1 -1
  13. package/dist/{LocalStateStore-BU3fWkcT.mjs → LocalStateStore-G0JHXOVW.mjs} +2 -2
  14. package/dist/{LocalStateStore-BU3fWkcT.mjs.map → LocalStateStore-G0JHXOVW.mjs.map} +1 -1
  15. package/dist/{LocalStateStore-B95WE99i.cjs → LocalStateStore-NBMF3zCb.cjs} +2 -2
  16. package/dist/{LocalStateStore-B95WE99i.cjs.map → LocalStateStore-NBMF3zCb.cjs.map} +1 -1
  17. package/dist/{S3StateStore-zU5kClhd.cjs → S3StateStore-7n6gIYEJ.cjs} +4 -4
  18. package/dist/{S3StateStore-zU5kClhd.cjs.map → S3StateStore-7n6gIYEJ.cjs.map} +1 -1
  19. package/dist/{S3StateStore-Cpbeijr5.mjs → S3StateStore-B7IPTvu0.mjs} +4 -4
  20. package/dist/{S3StateStore-Cpbeijr5.mjs.map → S3StateStore-B7IPTvu0.mjs.map} +1 -1
  21. package/dist/{SSMStateStore-BxkKMBi_.mjs → SSMStateStore-CWEShHLS.mjs} +2 -2
  22. package/dist/{SSMStateStore-BxkKMBi_.mjs.map → SSMStateStore-CWEShHLS.mjs.map} +1 -1
  23. package/dist/{SSMStateStore-D9uviQ3T.cjs → SSMStateStore-O12NeGEg.cjs} +2 -2
  24. package/dist/{SSMStateStore-D9uviQ3T.cjs.map → SSMStateStore-O12NeGEg.cjs.map} +1 -1
  25. package/dist/{add-Dj-gtqTO.mjs → add-C-nlqQgN.mjs} +4 -4
  26. package/dist/{add-Dj-gtqTO.mjs.map → add-C-nlqQgN.mjs.map} +1 -1
  27. package/dist/{add-Bb2IL3Yq.cjs → add-ktNZmJb-.cjs} +4 -4
  28. package/dist/{add-Bb2IL3Yq.cjs.map → add-ktNZmJb-.cjs.map} +1 -1
  29. package/dist/{apps-FRNlECwi.mjs → apps-C7SujLV-.mjs} +3 -3
  30. package/dist/{apps-FRNlECwi.mjs.map → apps-C7SujLV-.mjs.map} +1 -1
  31. package/dist/{apps-0vc4Oz9_.cjs → apps-CtjYJS9e.cjs} +3 -3
  32. package/dist/{apps-0vc4Oz9_.cjs.map → apps-CtjYJS9e.cjs.map} +1 -1
  33. package/dist/{aws-8QQ8n-t6.mjs → aws-C5LAU_Ii.mjs} +10 -2
  34. package/dist/aws-C5LAU_Ii.mjs.map +1 -0
  35. package/dist/{aws-DY9NqQIT.cjs → aws-DKC2m3sT.cjs} +9 -1
  36. package/dist/aws-DKC2m3sT.cjs.map +1 -0
  37. package/dist/{bundler-Bg2eEFEh.cjs → bundler-DGwgZmim.cjs} +6 -6
  38. package/dist/{bundler-Bg2eEFEh.cjs.map → bundler-DGwgZmim.cjs.map} +1 -1
  39. package/dist/{bundler-9EM4ZHcu.mjs → bundler-DnHKVaZz.mjs} +6 -6
  40. package/dist/{bundler-9EM4ZHcu.mjs.map → bundler-DnHKVaZz.mjs.map} +1 -1
  41. package/dist/{cli-CmoSOzNq.mjs → cli-CI9v138l.mjs} +4 -4
  42. package/dist/{cli-CmoSOzNq.mjs.map → cli-CI9v138l.mjs.map} +1 -1
  43. package/dist/{cli-YtLjcAZT.cjs → cli-k2G7rG15.cjs} +4 -4
  44. package/dist/{cli-YtLjcAZT.cjs.map → cli-k2G7rG15.cjs.map} +1 -1
  45. package/dist/{compose-CW1DGfYc.cjs → compose-BD2rwRfn.cjs} +4 -4
  46. package/dist/{compose-CW1DGfYc.cjs.map → compose-BD2rwRfn.cjs.map} +1 -1
  47. package/dist/{compose-3AtZF7ul.mjs → compose-Co-Dt-a4.mjs} +4 -4
  48. package/dist/{compose-3AtZF7ul.mjs.map → compose-Co-Dt-a4.mjs.map} +1 -1
  49. package/dist/{compose-D7gOSspy.cjs → compose-nGgRylPu.cjs} +16 -10
  50. package/dist/compose-nGgRylPu.cjs.map +1 -0
  51. package/dist/{compose-CnXZAYNM.mjs → compose-reJW9x-G.mjs} +16 -10
  52. package/dist/compose-reJW9x-G.mjs.map +1 -0
  53. package/dist/{config-CkuiD9Jv.d.cts → config-C60T2h98.d.cts} +3 -3
  54. package/dist/{config-BNmLn0dw.d.mts.map → config-C60T2h98.d.cts.map} +1 -1
  55. package/dist/{config-BNmLn0dw.d.mts → config-CfI2g_Ho.d.mts} +3 -3
  56. package/dist/{config-CkuiD9Jv.d.cts.map → config-CfI2g_Ho.d.mts.map} +1 -1
  57. package/dist/config.d.cts +3 -3
  58. package/dist/config.d.mts +3 -3
  59. package/dist/{credentials-CjFtNBVH.mjs → credentials-BG1KOq9I.mjs} +11 -7
  60. package/dist/credentials-BG1KOq9I.mjs.map +1 -0
  61. package/dist/{credentials-DwIRfeBL.cjs → credentials-UlL1n_Rd.cjs} +11 -7
  62. package/dist/credentials-UlL1n_Rd.cjs.map +1 -0
  63. package/dist/deploy/public.cjs +11 -11
  64. package/dist/deploy/public.d.cts +4 -4
  65. package/dist/deploy/public.d.mts +4 -4
  66. package/dist/deploy/public.mjs +11 -11
  67. package/dist/{deploy-3bsiWJxj.cjs → deploy-CqIULk0k.cjs} +57 -557
  68. package/dist/deploy-CqIULk0k.cjs.map +1 -0
  69. package/dist/{deploy-BI3fHnyb.mjs → deploy-DRkCNV7f.mjs} +16 -516
  70. package/dist/deploy-DRkCNV7f.mjs.map +1 -0
  71. package/dist/destroy-CMldkiX-.cjs +789 -0
  72. package/dist/destroy-CMldkiX-.cjs.map +1 -0
  73. package/dist/destroy-DXIAL8nF.mjs +788 -0
  74. package/dist/destroy-DXIAL8nF.mjs.map +1 -0
  75. package/dist/{docker-DPdn7tYJ.mjs → docker-DFFzQe2f.mjs} +4 -4
  76. package/dist/{docker-DPdn7tYJ.mjs.map → docker-DFFzQe2f.mjs.map} +1 -1
  77. package/dist/{docker-CwayjAF2.cjs → docker-LwJW3dx_.cjs} +4 -4
  78. package/dist/{docker-CwayjAF2.cjs.map → docker-LwJW3dx_.cjs.map} +1 -1
  79. package/dist/{dokploy-tmnH0Du_.mjs → dokploy-DYm0D6Tp.mjs} +2 -2
  80. package/dist/{dokploy-tmnH0Du_.mjs.map → dokploy-DYm0D6Tp.mjs.map} +1 -1
  81. package/dist/{dokploy-BMBL-_Xu.cjs → dokploy-wTsJqG-N.cjs} +2 -2
  82. package/dist/{dokploy-BMBL-_Xu.cjs.map → dokploy-wTsJqG-N.cjs.map} +1 -1
  83. package/dist/{eas-BVGQAUDc.mjs → eas-BJ_Zlvm8.mjs} +2 -2
  84. package/dist/{eas-BVGQAUDc.mjs.map → eas-BJ_Zlvm8.mjs.map} +1 -1
  85. package/dist/{eas-meN1xady.cjs → eas-C4EkjTGJ.cjs} +2 -2
  86. package/dist/{eas-meN1xady.cjs.map → eas-C4EkjTGJ.cjs.map} +1 -1
  87. package/dist/{encryption-DvFVZdGz.cjs → encryption-BQEqqrGq.cjs} +2 -2
  88. package/dist/{encryption-DvFVZdGz.cjs.map → encryption-BQEqqrGq.cjs.map} +1 -1
  89. package/dist/{encryption-C8AMbomA.mjs → encryption-Cu5YTs9V.mjs} +2 -2
  90. package/dist/{encryption-C8AMbomA.mjs.map → encryption-Cu5YTs9V.mjs.map} +1 -1
  91. package/dist/{engine-BmiIUVWa.cjs → engine-DdRauUQC.cjs} +9 -9
  92. package/dist/{engine-BmiIUVWa.cjs.map → engine-DdRauUQC.cjs.map} +1 -1
  93. package/dist/{engine-BbWj0w3F.mjs → engine-q8aCVbLH.mjs} +9 -9
  94. package/dist/{engine-BbWj0w3F.mjs.map → engine-q8aCVbLH.mjs.map} +1 -1
  95. package/dist/{github-Dc1daUbH.mjs → github-CoXirRes.mjs} +9 -8
  96. package/dist/{github-Dc1daUbH.mjs.map → github-CoXirRes.mjs.map} +1 -1
  97. package/dist/{github-BWqQr8q6.cjs → github-OVZF2k0L.cjs} +13 -12
  98. package/dist/{github-BWqQr8q6.cjs.map → github-OVZF2k0L.cjs.map} +1 -1
  99. package/dist/{googlePlay-CdVCdfU8.cjs → googlePlay-CUeTUT7s.cjs} +4 -4
  100. package/dist/{googlePlay-CdVCdfU8.cjs.map → googlePlay-CUeTUT7s.cjs.map} +1 -1
  101. package/dist/{googlePlay-ByaFUly7.mjs → googlePlay-HXRRVq0l.mjs} +4 -4
  102. package/dist/{googlePlay-ByaFUly7.mjs.map → googlePlay-HXRRVq0l.mjs.map} +1 -1
  103. package/dist/iam-6LH6wptf.cjs +618 -0
  104. package/dist/iam-6LH6wptf.cjs.map +1 -0
  105. package/dist/iam-c0e8m04X.mjs +509 -0
  106. package/dist/iam-c0e8m04X.mjs.map +1 -0
  107. package/dist/{index-Dv1Zj86i.d.mts → index-DDY0cZCo.d.cts} +2 -2
  108. package/dist/{index-B35vTdAW.d.cts.map → index-DDY0cZCo.d.cts.map} +1 -1
  109. package/dist/{index-B35vTdAW.d.cts → index-DWNwkcy7.d.mts} +2 -2
  110. package/dist/{index-Dv1Zj86i.d.mts.map → index-DWNwkcy7.d.mts.map} +1 -1
  111. package/dist/index.cjs +98 -77
  112. package/dist/index.cjs.map +1 -1
  113. package/dist/index.mjs +98 -77
  114. package/dist/index.mjs.map +1 -1
  115. package/dist/{local-CnVFHJjS.mjs → local-CCJ-T37d.mjs} +2 -2
  116. package/dist/{local-CnVFHJjS.mjs.map → local-CCJ-T37d.mjs.map} +1 -1
  117. package/dist/{local-qevrV6dZ.cjs → local-Dx0o6vfp.cjs} +2 -2
  118. package/dist/{local-qevrV6dZ.cjs.map → local-Dx0o6vfp.cjs.map} +1 -1
  119. package/dist/{migrate-DgfKZB41.mjs → migrate-BkwSXhxv.mjs} +4 -4
  120. package/dist/{migrate-DgfKZB41.mjs.map → migrate-BkwSXhxv.mjs.map} +1 -1
  121. package/dist/{migrate-CU8_ZWP1.cjs → migrate-CJoKOCGY.cjs} +4 -4
  122. package/dist/{migrate-CU8_ZWP1.cjs.map → migrate-CJoKOCGY.cjs.map} +1 -1
  123. package/dist/{migrate-CRRps1i6.cjs → migrate-DEsYfgzn.cjs} +4 -4
  124. package/dist/{migrate-CRRps1i6.cjs.map → migrate-DEsYfgzn.cjs.map} +1 -1
  125. package/dist/{migrate-BEuCcCwN.mjs → migrate-Dr0BeWsY.mjs} +4 -4
  126. package/dist/{migrate-BEuCcCwN.mjs.map → migrate-Dr0BeWsY.mjs.map} +1 -1
  127. package/dist/{notes-CIzrdBKE.mjs → notes-BOyzuPqr.mjs} +2 -2
  128. package/dist/{notes-CIzrdBKE.mjs.map → notes-BOyzuPqr.mjs.map} +1 -1
  129. package/dist/{notes-BrBnyZz5.cjs → notes-VFPa51Pd.cjs} +2 -2
  130. package/dist/{notes-BrBnyZz5.cjs.map → notes-VFPa51Pd.cjs.map} +1 -1
  131. package/dist/openapi.d.cts +1 -1
  132. package/dist/openapi.d.mts +1 -1
  133. package/dist/{projectBucket-CDJd3prK.mjs → projectBucket-B26ucBRI.mjs} +2 -2
  134. package/dist/{projectBucket-CDJd3prK.mjs.map → projectBucket-B26ucBRI.mjs.map} +1 -1
  135. package/dist/{projectBucket-CKr_zObJ.cjs → projectBucket-CWpY3Vxv.cjs} +2 -2
  136. package/dist/{projectBucket-CKr_zObJ.cjs.map → projectBucket-CWpY3Vxv.cjs.map} +1 -1
  137. package/dist/{publish-Bq96_QnK.mjs → publish-Bg4iffje.mjs} +2 -2
  138. package/dist/{publish-Bq96_QnK.mjs.map → publish-Bg4iffje.mjs.map} +1 -1
  139. package/dist/{publish-DMKXh1Tb.cjs → publish-IjcRoorJ.cjs} +2 -2
  140. package/dist/{publish-DMKXh1Tb.cjs.map → publish-IjcRoorJ.cjs.map} +1 -1
  141. package/dist/reconcile/public.d.cts +1 -1
  142. package/dist/reconcile/public.d.mts +1 -1
  143. package/dist/{resolve-DF9GrosZ.cjs → resolve-CgVDhWW8.cjs} +4 -4
  144. package/dist/{resolve-DF9GrosZ.cjs.map → resolve-CgVDhWW8.cjs.map} +1 -1
  145. package/dist/{resolve-CSsE7frp.mjs → resolve-rw7mLp5E.mjs} +4 -4
  146. package/dist/{resolve-CSsE7frp.mjs.map → resolve-rw7mLp5E.mjs.map} +1 -1
  147. package/dist/{rollback-CZthwqus.mjs → rollback-Cv02Cnky.mjs} +6 -6
  148. package/dist/{rollback-CZthwqus.mjs.map → rollback-Cv02Cnky.mjs.map} +1 -1
  149. package/dist/{rollback-BBFGGmMa.cjs → rollback-vdkPi_Rm.cjs} +6 -6
  150. package/dist/{rollback-BBFGGmMa.cjs.map → rollback-vdkPi_Rm.cjs.map} +1 -1
  151. package/dist/{runtime-CFvcLEJW.d.cts → runtime-D-rOcRoq.d.cts} +2 -2
  152. package/dist/{runtime-CFvcLEJW.d.cts.map → runtime-D-rOcRoq.d.cts.map} +1 -1
  153. package/dist/{runtime-dwsH6ddo.d.mts → runtime-DG1mNh_5.d.mts} +2 -2
  154. package/dist/{runtime-dwsH6ddo.d.mts.map → runtime-DG1mNh_5.d.mts.map} +1 -1
  155. package/dist/{s3-CI2QYgXH.cjs → s3-DIvAtJwk.cjs} +27 -2
  156. package/dist/s3-DIvAtJwk.cjs.map +1 -0
  157. package/dist/{s3-BBRkezf7.mjs → s3-DmsM_V2R.mjs} +28 -3
  158. package/dist/s3-DmsM_V2R.mjs.map +1 -0
  159. package/dist/{secretsManager-CQORubp9.mjs → secretsManager-CJyxFcBH.mjs} +18 -2
  160. package/dist/secretsManager-CJyxFcBH.mjs.map +1 -0
  161. package/dist/{secretsManager-RAGcEDX1.cjs → secretsManager-D8on44WI.cjs} +17 -1
  162. package/dist/secretsManager-D8on44WI.cjs.map +1 -0
  163. package/dist/{seeds-B3xvUAQf.cjs → seeds-D7q1zKCJ.cjs} +7 -1
  164. package/dist/{seeds-B3xvUAQf.cjs.map → seeds-D7q1zKCJ.cjs.map} +1 -1
  165. package/dist/{seeds-BCC8vAXR.mjs → seeds-y1rzXlAc.mjs} +2 -2
  166. package/dist/{seeds-BCC8vAXR.mjs.map → seeds-y1rzXlAc.mjs.map} +1 -1
  167. package/dist/{serverSetup-C4iAABtI.mjs → serverSetup-CvcN4zJQ.mjs} +6 -6
  168. package/dist/{serverSetup-C4iAABtI.mjs.map → serverSetup-CvcN4zJQ.mjs.map} +1 -1
  169. package/dist/{serverSetup-Dt2DTlwa.cjs → serverSetup-qXIRRhgw.cjs} +6 -6
  170. package/dist/{serverSetup-Dt2DTlwa.cjs.map → serverSetup-qXIRRhgw.cjs.map} +1 -1
  171. package/dist/{sniffer-bTrGuu9z.cjs → sniffer-CGfL25Bc.cjs} +7 -7
  172. package/dist/{sniffer-bTrGuu9z.cjs.map → sniffer-CGfL25Bc.cjs.map} +1 -1
  173. package/dist/{sniffer-C2Ot1IbK.mjs → sniffer-DuKVVAs_.mjs} +7 -7
  174. package/dist/{sniffer-C2Ot1IbK.mjs.map → sniffer-DuKVVAs_.mjs.map} +1 -1
  175. package/dist/{snsSubscriptions-CFKb7fv0.cjs → snsSubscriptions-DPfGjpuB.cjs} +8 -2
  176. package/dist/{snsSubscriptions-CFKb7fv0.cjs.map → snsSubscriptions-DPfGjpuB.cjs.map} +1 -1
  177. package/dist/{snsSubscriptions-QDDDn9Qi.mjs → snsSubscriptions-nnSUW2Eh.mjs} +3 -3
  178. package/dist/{snsSubscriptions-QDDDn9Qi.mjs.map → snsSubscriptions-nnSUW2Eh.mjs.map} +1 -1
  179. package/dist/{sst-DDRWlXdv.mjs → sst-Bw7686br.mjs} +4 -4
  180. package/dist/{sst-DDRWlXdv.mjs.map → sst-Bw7686br.mjs.map} +1 -1
  181. package/dist/{sst-iRdMlGKd.cjs → sst-Md7c1UC_.cjs} +4 -4
  182. package/dist/{sst-iRdMlGKd.cjs.map → sst-Md7c1UC_.cjs.map} +1 -1
  183. package/dist/{stack-CIOY44aC.mjs → stack-D2cLLaO-.mjs} +6 -6
  184. package/dist/{stack-CIOY44aC.mjs.map → stack-D2cLLaO-.mjs.map} +1 -1
  185. package/dist/{stack-B9iDYMrq.cjs → stack-DTcnynGb.cjs} +6 -6
  186. package/dist/{stack-B9iDYMrq.cjs.map → stack-DTcnynGb.cjs.map} +1 -1
  187. package/dist/{stage-DA74aD_V.mjs → stage-Bw3bJ7Au.mjs} +5 -5
  188. package/dist/{stage-DA74aD_V.mjs.map → stage-Bw3bJ7Au.mjs.map} +1 -1
  189. package/dist/{stage-ycFS9mVn.cjs → stage-RLOenlHV.cjs} +5 -5
  190. package/dist/{stage-ycFS9mVn.cjs.map → stage-RLOenlHV.cjs.map} +1 -1
  191. package/dist/target/public.cjs +1 -1
  192. package/dist/target/public.d.cts +2 -2
  193. package/dist/target/public.d.mts +2 -2
  194. package/dist/target/public.mjs +1 -1
  195. package/dist/{terminal-RxfbNUwl.cjs → terminal-C-_cMKTY.cjs} +2 -2
  196. package/dist/{terminal-RxfbNUwl.cjs.map → terminal-C-_cMKTY.cjs.map} +1 -1
  197. package/dist/{terminal-DX22WLvT.mjs → terminal-Dq29bK3u.mjs} +2 -2
  198. package/dist/{terminal-DX22WLvT.mjs.map → terminal-Dq29bK3u.mjs.map} +1 -1
  199. package/dist/{types-Dk--xVOT.d.cts → types-CvucX3yD.d.mts} +7 -2
  200. package/dist/types-CvucX3yD.d.mts.map +1 -0
  201. package/dist/{types-DwQYpd_0.d.mts → types-D1C8pUyh.d.cts} +8 -1
  202. package/dist/types-D1C8pUyh.d.cts.map +1 -0
  203. package/dist/workspace/index.d.cts +2 -2
  204. package/dist/workspace/index.d.mts +2 -2
  205. package/package.json +15 -15
  206. package/dist/aws-8QQ8n-t6.mjs.map +0 -1
  207. package/dist/aws-DY9NqQIT.cjs.map +0 -1
  208. package/dist/compose-CnXZAYNM.mjs.map +0 -1
  209. package/dist/compose-D7gOSspy.cjs.map +0 -1
  210. package/dist/credentials-CjFtNBVH.mjs.map +0 -1
  211. package/dist/credentials-DwIRfeBL.cjs.map +0 -1
  212. package/dist/deploy-3bsiWJxj.cjs.map +0 -1
  213. package/dist/deploy-BI3fHnyb.mjs.map +0 -1
  214. package/dist/s3-BBRkezf7.mjs.map +0 -1
  215. package/dist/s3-CI2QYgXH.cjs.map +0 -1
  216. package/dist/secretsManager-CQORubp9.mjs.map +0 -1
  217. package/dist/secretsManager-RAGcEDX1.cjs.map +0 -1
  218. package/dist/types-Dk--xVOT.d.cts.map +0 -1
  219. package/dist/types-DwQYpd_0.d.mts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"iam-6LH6wptf.cjs","names":["GkmError","kebabCase","randomInt","IamUserNotOwned","s3Url","BucketKeySetElsewhere","RotationInProgress","AccessKeyLimit"],"sources":["../src/providers/s3/naming.ts","../src/providers/s3/policy.ts","../src/providers/iam.ts"],"sourcesContent":["/**\n * What the `s3` provider names a bucket and its IAM user.\n *\n * A bucket name is global across every AWS account, so the good name — the\n * one a person reading the console would guess — is tried first and a random\n * suffix is the fallback for a clash. Whatever name is created is recorded in\n * the stage's state and read back on every later run: a name is never\n * regenerated, because a new name is a new, empty bucket.\n */\n\nimport { randomInt } from 'node:crypto';\nimport { kebabCase } from '@geekmidas/manifest';\nimport { GkmError } from '../../errors';\n\n/** S3's limit on a bucket name. */\nexport const BUCKET_NAME_MAX = 63;\n/** IAM's limit on a user name. */\nexport const IAM_USER_NAME_MAX = 64;\n/** `-` and six characters: what a clash appends. */\nexport const SUFFIX_LENGTH = 7;\n/** How many suffixed names are tried after the good one. */\nexport const SUFFIX_ATTEMPTS = 5;\n\nconst SUFFIX_ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789';\n\n/** A name that S3 would refuse — what the name builder never returns. */\nexport class InvalidBucketName extends GkmError {\n\tconstructor(\n\t\treadonly bucket: string,\n\t\treadonly reason: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${bucket}' is not a valid S3 bucket name: ${reason}. Rename the ` +\n\t\t\t\t'construct or set deploy.namespace in gkm.config.ts to something ' +\n\t\t\t\t'that leaves room for it.',\n\t\t);\n\t\tthis.name = 'InvalidBucketName';\n\t}\n}\n\n/** Lowercase `[a-z0-9-]`, runs of anything else one `-`, no edge dashes. */\nfunction part(value: string): string {\n\treturn kebabCase(value)\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9]+/g, '-')\n\t\t.replace(/^-+|-+$/g, '');\n}\n\n/**\n * `parts` joined by `-`, shortened to `max` characters by trimming the longest\n * part one character at a time — so a long construct id gives way before a\n * short stage name does, and every part keeps its start.\n */\nexport function fitParts(parts: readonly string[], max: number): string {\n\tconst kept = parts.map(part).filter(Boolean);\n\tconst length = () =>\n\t\tkept.reduce((sum, p) => sum + p.length, 0) + kept.length - 1;\n\twhile (length() > max) {\n\t\tlet longest = 0;\n\t\tfor (let i = 1; i < kept.length; i++) {\n\t\t\tif (kept[i]!.length > kept[longest]!.length) longest = i;\n\t\t}\n\t\tif (kept[longest]!.length <= 1) break;\n\t\tkept[longest] = kept[longest]!.slice(0, -1).replace(/-+$/, '');\n\t}\n\treturn kept.join('-');\n}\n\n/** Why `name` is not a valid bucket name, or undefined when it is. */\nexport function bucketNameProblem(name: string): string | undefined {\n\tif (name.length < 3 || name.length > BUCKET_NAME_MAX) {\n\t\treturn `it is ${name.length} characters, and S3 takes 3 to ${BUCKET_NAME_MAX}`;\n\t}\n\tif (!/^[a-z0-9-]+$/.test(name)) {\n\t\treturn 'it may hold only lowercase letters, digits and -';\n\t}\n\tif (!/^[a-z0-9].*[a-z0-9]$/.test(name)) {\n\t\treturn 'it must start and end with a letter or a digit';\n\t}\n\tif (name.startsWith('xn--') || name.startsWith('sthree-')) {\n\t\treturn \"it starts with a prefix S3 reserves ('xn--', 'sthree-')\";\n\t}\n\tif (name.endsWith('-s3alias') || name.endsWith('--ol-s3')) {\n\t\treturn \"it ends with a suffix S3 reserves ('-s3alias', '--ol-s3')\";\n\t}\n\treturn undefined;\n}\n\n/** What a bucket is named from. */\nexport interface BucketNameInput {\n\t/** The deploy identity's scope: `<namespace>-<project>`, or the project. */\n\tscope: string;\n\tstage: string;\n\t/** The `ObjectStorage` construct's id. */\n\tid: string;\n}\n\n/**\n * The good name: `<namespace>-<project>-<stage>-<bucket id>`, lowercased, no\n * dots, shortened to leave room for a clash's suffix.\n *\n * @throws {InvalidBucketName} when nothing usable is left\n */\nexport function bucketName(input: BucketNameInput): string {\n\tconst name = fitParts(\n\t\t[input.scope, input.stage, input.id],\n\t\tBUCKET_NAME_MAX - SUFFIX_LENGTH,\n\t);\n\tconst problem = bucketNameProblem(name);\n\tif (problem) throw new InvalidBucketName(name, problem);\n\treturn name;\n}\n\n/** Six random `[a-z0-9]` characters. */\nexport function randomSuffix(random: (max: number) => number = randomInt) {\n\tlet suffix = '';\n\tfor (let i = 0; i < 6; i++) {\n\t\tsuffix += SUFFIX_ALPHABET[random(SUFFIX_ALPHABET.length)];\n\t}\n\treturn suffix;\n}\n\n/** The good name with a clash's suffix. */\nexport function suffixedBucketName(good: string, suffix: string): string {\n\treturn `${good}-${suffix}`;\n}\n\n/**\n * The IAM user a bucket is reached with on a stage:\n * `gkm-<project>-<stage>-<bucket id>`, at most 64 characters.\n */\nexport function iamUserName(input: BucketNameInput): string {\n\treturn fitParts(\n\t\t['gkm', input.scope, input.stage, input.id],\n\t\tIAM_USER_NAME_MAX,\n\t);\n}\n\n/** The path every user gkm creates is under, so it finds its own. */\nexport const IAM_USER_PATH = '/gkm/';\n\n/** The inline policy each user is given. */\nexport const IAM_POLICY_NAME = 'gkm-bucket';\n","/**\n * The documents the `s3` provider writes: the user's inline policy, the\n * bucket's policy, its CORS rule and its public access block.\n *\n * Pure, so each is tested as JSON and compared with what AWS holds on every\n * run — a document that differs is drift, and is put back.\n */\n\n/** One IAM or bucket policy statement. */\nexport interface PolicyStatement {\n\tSid: string;\n\tEffect: 'Allow' | 'Deny';\n\tPrincipal?: '*' | { AWS: string | string[] } | { Service: string };\n\tAction: string | string[];\n\tResource: string | string[];\n\tCondition?: Record<string, Record<string, string | string[]>>;\n}\n\nexport interface PolicyDocument {\n\tVersion: '2012-10-17';\n\tStatement: PolicyStatement[];\n}\n\nconst bucketArn = (bucket: string) => `arn:aws:s3:::${bucket}`;\n\n/**\n * What the app's key may do: objects in this bucket, and listing it — and\n * nothing else in the account.\n *\n * Multipart uploads are in it because a presigned upload of a large file is\n * one, and an abandoned one is cleaned up by the app. Reading old versions is\n * added only when the bucket keeps them.\n */\nexport function userPolicy(\n\tbucket: string,\n\toptions: {\n\t\tversioning?: boolean;\n\t\t/**\n\t\t * The bucket's events topic, when a subscriber watches it: the worker\n\t\t * confirms the subscriptions the deploy made with this key, and does\n\t\t * nothing else to the topic.\n\t\t */\n\t\teventsTopicArn?: string;\n\t} = {},\n): PolicyDocument {\n\treturn {\n\t\tVersion: '2012-10-17',\n\t\tStatement: [\n\t\t\t{\n\t\t\t\tSid: 'GkmObjects',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: [\n\t\t\t\t\t's3:GetObject',\n\t\t\t\t\t's3:PutObject',\n\t\t\t\t\t's3:DeleteObject',\n\t\t\t\t\t's3:AbortMultipartUpload',\n\t\t\t\t\t's3:ListMultipartUploadParts',\n\t\t\t\t\t...(options.versioning ? ['s3:GetObjectVersion'] : []),\n\t\t\t\t],\n\t\t\t\tResource: `${bucketArn(bucket)}/*`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tSid: 'GkmBucket',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: [\n\t\t\t\t\t's3:ListBucket',\n\t\t\t\t\t's3:GetBucketLocation',\n\t\t\t\t\t's3:ListBucketMultipartUploads',\n\t\t\t\t],\n\t\t\t\tResource: bucketArn(bucket),\n\t\t\t},\n\t\t\t...(options.eventsTopicArn\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSid: 'GkmEvents',\n\t\t\t\t\t\t\tEffect: 'Allow' as const,\n\t\t\t\t\t\t\tAction: 'sns:ConfirmSubscription',\n\t\t\t\t\t\t\tResource: options.eventsTopicArn,\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: []),\n\t\t],\n\t};\n}\n\n/**\n * One open pattern as the resource it is public on. A `**` is S3's `*`; a\n * single `*` is too, which crosses `/` where the construct's own check does\n * not — the construct is the stricter of the two (see `bucketPolicy` in\n * reconcile, which the local MinIO is given the same way).\n */\nexport function openResource(bucket: string, pattern: string): string {\n\tconst path = pattern.replace(/^\\/+/, '').replace(/\\*\\*/g, '*');\n\treturn `${bucketArn(bucket)}/${path}`;\n}\n\n/**\n * The bucket's own policy: every request refused unless it came over TLS,\n * and — only when a file server opens paths on it — `s3:GetObject` on\n * exactly those prefixes: to anyone, or, when a CDN serves them, to\n * CloudFront alone, for exactly the stage's distributions. Behind a CDN the\n * bucket is never public: a key outside the open prefixes is refused to\n * CloudFront too, so the edge answers it 403.\n */\nexport function bucketPolicy(\n\tbucket: string,\n\topen: readonly string[] = [],\n\toptions: {\n\t\tcdn?: { distributionArns: readonly string[] };\n\t\t/**\n\t\t * SES may write received mail under this prefix — the bucket an inbox\n\t\t * owns — and only for this account's receipt rules.\n\t\t */\n\t\tsesWrite?: { prefix: string; account: string };\n\t} = {},\n): PolicyDocument {\n\tconst statements: PolicyStatement[] = [\n\t\t{\n\t\t\tSid: 'GkmDenyInsecureTransport',\n\t\t\tEffect: 'Deny',\n\t\t\tPrincipal: '*',\n\t\t\tAction: 's3:*',\n\t\t\tResource: [bucketArn(bucket), `${bucketArn(bucket)}/*`],\n\t\t\tCondition: { Bool: { 'aws:SecureTransport': 'false' } },\n\t\t},\n\t];\n\tconst resources = [\n\t\t...new Set(open.map((p) => openResource(bucket, p))),\n\t].sort();\n\tif (open.length > 0 && options.cdn) {\n\t\tstatements.push({\n\t\t\tSid: 'GkmCdnRead',\n\t\t\tEffect: 'Allow',\n\t\t\tPrincipal: { Service: 'cloudfront.amazonaws.com' },\n\t\t\tAction: 's3:GetObject',\n\t\t\tResource: resources,\n\t\t\tCondition: {\n\t\t\t\tStringEquals: {\n\t\t\t\t\t'AWS:SourceArn': [...new Set(options.cdn.distributionArns)].sort(),\n\t\t\t\t},\n\t\t\t},\n\t\t});\n\t} else if (open.length > 0) {\n\t\tstatements.push({\n\t\t\tSid: 'GkmOpenPaths',\n\t\t\tEffect: 'Allow',\n\t\t\tPrincipal: '*',\n\t\t\tAction: 's3:GetObject',\n\t\t\tResource: resources,\n\t\t});\n\t}\n\tif (options.sesWrite) {\n\t\tstatements.push({\n\t\t\tSid: 'GkmSesWritesMail',\n\t\t\tEffect: 'Allow',\n\t\t\tPrincipal: { Service: 'ses.amazonaws.com' },\n\t\t\tAction: 's3:PutObject',\n\t\t\tResource: `${bucketArn(bucket)}/${options.sesWrite.prefix}*`,\n\t\t\tCondition: {\n\t\t\t\tStringEquals: { 'aws:SourceAccount': options.sesWrite.account },\n\t\t\t},\n\t\t});\n\t}\n\treturn { Version: '2012-10-17', Statement: statements };\n}\n\n/**\n * Block Public Access. All four flags on, unless the bucket has open paths:\n * then a *policy* may make it public (`BlockPublicPolicy`,\n * `RestrictPublicBuckets` off), and ACLs still may not.\n */\nexport function publicAccessBlock(open: boolean): {\n\tBlockPublicAcls: boolean;\n\tIgnorePublicAcls: boolean;\n\tBlockPublicPolicy: boolean;\n\tRestrictPublicBuckets: boolean;\n} {\n\treturn {\n\t\tBlockPublicAcls: true,\n\t\tIgnorePublicAcls: true,\n\t\tBlockPublicPolicy: !open,\n\t\tRestrictPublicBuckets: !open,\n\t};\n}\n\n/** The one CORS rule: browsers on the stage's sites upload and read. */\nexport interface CorsRule {\n\tAllowedMethods: string[];\n\tAllowedOrigins: string[];\n\tAllowedHeaders: string[];\n\tExposeHeaders: string[];\n\tMaxAgeSeconds: number;\n}\n\nexport function corsRule(origins: readonly string[]): CorsRule {\n\treturn {\n\t\tAllowedMethods: ['GET', 'HEAD', 'POST', 'PUT'],\n\t\tAllowedOrigins: [...new Set(origins)].sort(),\n\t\tAllowedHeaders: ['*'],\n\t\tExposeHeaders: ['ETag'],\n\t\tMaxAgeSeconds: 3000,\n\t};\n}\n\n/**\n * A policy document in one canonical form — keys sorted, a lone string a\n * one-element list, lists sorted — so one AWS reformatted reads as the same\n * document rather than as drift.\n */\nexport function canonicalPolicy(value: unknown): string {\n\treturn JSON.stringify(canonical(value));\n}\n\nfunction canonical(value: unknown, key?: string): unknown {\n\tif (Array.isArray(value)) {\n\t\tconst items = value.map((v) => canonical(v));\n\t\treturn key === 'Statement'\n\t\t\t? items\n\t\t\t: items.map((v) => JSON.stringify(v)).sort();\n\t}\n\tif (value && typeof value === 'object') {\n\t\treturn Object.fromEntries(\n\t\t\tObject.keys(value)\n\t\t\t\t.sort()\n\t\t\t\t.map((k) => {\n\t\t\t\t\tconst v = (value as Record<string, unknown>)[k];\n\t\t\t\t\tconst listy =\n\t\t\t\t\t\tk === 'Action' ||\n\t\t\t\t\t\tk === 'Resource' ||\n\t\t\t\t\t\tk === 'AWS' ||\n\t\t\t\t\t\tk === 'AWS:SourceArn'\n\t\t\t\t\t\t\t? Array.isArray(v)\n\t\t\t\t\t\t\t\t? v\n\t\t\t\t\t\t\t\t: [v]\n\t\t\t\t\t\t\t: v;\n\t\t\t\t\treturn [k, canonical(listy, k)];\n\t\t\t\t}),\n\t\t);\n\t}\n\treturn value;\n}\n","/**\n * An IAM user gkm creates for one thing on a stage, its inline policy, and\n * the access key written into the stage's secrets as an `s3://` URL — what\n * the `s3` provider gives each bucket, and the deploy gives a stage's\n * backups.\n *\n * - **The user** is under `/gkm/`, tagged with the deploy identity, the stage\n * and what it is for. One that exists without those tags is someone\n * else's, and is refused rather than taken over.\n * - **Its policy** is read on every run and put back when it drifted.\n * - **Its key**: one, written into the stage's secrets the moment IAM shows\n * its secret. `--rotate-keys` issues a successor and keeps the old one\n * active until the stage has deployed with the new one; the next run after\n * that — or `--retire-old-keys` — deletes it.\n * - **A new key** takes IAM seconds to become usable: the state records when\n * it was issued, and a check made with it waits that out\n * ({@link whileKeyIsNew}).\n */\n\nimport * as s3Url from '@geekmidas/storage/s3-url';\nimport type { ResourceRecord } from '../deploy/StateStore.js';\nimport {\n\tAccessKeyLimit,\n\tBucketKeySetElsewhere,\n\tIamUserNotOwned,\n\tRotationInProgress,\n} from './s3/errors.js';\nimport { IAM_USER_PATH } from './s3/naming.js';\nimport { canonicalPolicy } from './s3/policy.js';\nimport type { EnsureContext, ProviderConfig, StateEntry } from './types.js';\n\ntype IamModule = typeof import('@aws-sdk/client-iam');\n\n/** The tags gkm finds its own buckets and users by. */\nexport const TAG_PROJECT = 'gkm:project';\nexport const TAG_STAGE = 'gkm:stage';\nexport const TAG_CONSTRUCT = 'gkm:construct';\n\n/** What creating a user and its key is done through. */\nexport interface IamClients {\n\tIAM: IamModule;\n\tiam: InstanceType<IamModule['IAMClient']>;\n\t/** The region the key's URL names. */\n\tregion: string;\n\t/** An emulator's endpoint, written into the URL when there is one. */\n\tendpoint?: string;\n}\n\n/** What creating a user and its key reads from a provisioning run. */\nexport type KeyContext = Pick<\n\tEnsureContext<ProviderConfig, unknown>,\n\t| 'identity'\n\t| 'stage'\n\t| 'state'\n\t| 'change'\n\t| 'dryRun'\n\t| 'secrets'\n\t| 'writeSecrets'\n\t| 'rotateKeys'\n\t| 'retireOldKeys'\n\t| 'log'\n>;\n\n/** The keys gkm tags a bucket and a user with. */\nexport function identityTags(\n\tctx: Pick<KeyContext, 'identity' | 'stage'>,\n\tid: string,\n) {\n\treturn [\n\t\t{ Key: TAG_PROJECT, Value: ctx.identity.key },\n\t\t{ Key: TAG_STAGE, Value: ctx.stage },\n\t\t{ Key: TAG_CONSTRUCT, Value: id },\n\t];\n}\n\n/** A read whose \"there is none\" answer is one of `missing`. */\nasync function readOr<T>(\n\tread: () => Promise<T>,\n\tmissing: readonly string[],\n): Promise<T | undefined> {\n\ttry {\n\t\treturn await read();\n\t} catch (error) {\n\t\tconst e = error as { name?: string; Code?: string };\n\t\tif (missing.includes(e?.Code ?? e?.name ?? '')) return undefined;\n\t\tthrow error;\n\t}\n}\n\n/** IAM returns a policy document URL-encoded; an emulator may not. */\nfunction decodePolicy(document: string): string {\n\ttry {\n\t\treturn decodeURIComponent(document);\n\t} catch {\n\t\treturn document;\n\t}\n}\n\nexport interface IamUserInput {\n\t/** What it is for: a bucket construct's id, or `backups`. */\n\tid: string;\n\t/** `gkm-<project>-<stage>-<id>`. */\n\tuser: string;\n\t/** The inline policy's name. */\n\tpolicyName: string;\n\tpolicy: object;\n\t/** The policy's change line: `this bucket only`. */\n\tdescribe: string;\n}\n\n/**\n * The user and its inline policy: found — and refused when it is not this\n * stage's — or created, and the policy put back when it drifted.\n *\n * @throws {IamUserNotOwned}\n */\nexport async function ensureIamUser(\n\tctx: KeyContext,\n\tclients: IamClients,\n\tinput: IamUserInput,\n): Promise<{ user: string; exists: boolean }> {\n\tconst { IAM, iam } = clients;\n\tconst { id, user, policy } = input;\n\tconst entry: StateEntry = { key: `iam-user:${id}`, type: 'iam-user' };\n\tconst found = await readOr(\n\t\t() => iam.send(new IAM.GetUserCommand({ UserName: user })),\n\t\t['NoSuchEntity', 'NoSuchEntityException'],\n\t);\n\n\tif (found?.User) {\n\t\tconst tags = await iam.send(\n\t\t\tnew IAM.ListUserTagsCommand({ UserName: user }),\n\t\t);\n\t\tconst tag = (key: string) => tags.Tags?.find((t) => t.Key === key)?.Value;\n\t\tif (\n\t\t\tfound.User.Path !== IAM_USER_PATH ||\n\t\t\ttag(TAG_PROJECT) !== ctx.identity.key ||\n\t\t\ttag(TAG_STAGE) !== ctx.stage\n\t\t) {\n\t\t\tthrow new IamUserNotOwned(user, ctx.identity.key, ctx.stage);\n\t\t}\n\t\tawait ctx.state.ready(entry, user);\n\t} else {\n\t\tawait ctx.change(\n\t\t\t{\n\t\t\t\tconstruct: id,\n\t\t\t\tresource: `IAM user ${user}`,\n\t\t\t\tchange: `create under ${IAM_USER_PATH}`,\n\t\t\t},\n\t\t\tasync () => {\n\t\t\t\tawait ctx.state.pending(entry);\n\t\t\t\tawait iam.send(\n\t\t\t\t\tnew IAM.CreateUserCommand({\n\t\t\t\t\t\tUserName: user,\n\t\t\t\t\t\tPath: IAM_USER_PATH,\n\t\t\t\t\t\tTags: identityTags(ctx, id),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tawait ctx.state.ready(entry, user);\n\t\t\t},\n\t\t);\n\t}\n\n\tconst exists = Boolean(found?.User) || !ctx.dryRun;\n\tconst current = exists\n\t\t? await readOr(\n\t\t\t\t() =>\n\t\t\t\t\tiam.send(\n\t\t\t\t\t\tnew IAM.GetUserPolicyCommand({\n\t\t\t\t\t\t\tUserName: user,\n\t\t\t\t\t\t\tPolicyName: input.policyName,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t['NoSuchEntity', 'NoSuchEntityException'],\n\t\t\t)\n\t\t: undefined;\n\tconst document = current?.PolicyDocument\n\t\t? JSON.parse(decodePolicy(current.PolicyDocument))\n\t\t: undefined;\n\tif (!document || canonicalPolicy(document) !== canonicalPolicy(policy)) {\n\t\tawait ctx.change(\n\t\t\t{\n\t\t\t\tconstruct: id,\n\t\t\t\tresource: `IAM user ${user}`,\n\t\t\t\tchange: `policy ${input.policyName}: ${input.describe}`,\n\t\t\t},\n\t\t\tasync () => {\n\t\t\t\tawait iam.send(\n\t\t\t\t\tnew IAM.PutUserPolicyCommand({\n\t\t\t\t\t\tUserName: user,\n\t\t\t\t\t\tPolicyName: input.policyName,\n\t\t\t\t\t\tPolicyDocument: JSON.stringify(policy),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t},\n\t\t);\n\t}\n\treturn { user, exists };\n}\n\nexport interface AccessKeyInput {\n\t/** What it is for, as {@link IamUserInput.id}. */\n\tid: string;\n\tuser: string;\n\t/** Whether the user exists yet — false in a dry run that would create it. */\n\texists: boolean;\n\t/** The bucket the URL addresses. */\n\tbucket: string;\n\t/** The secret the URL is written to: `UPLOADS_URL`, `BACKUPS_URL`. */\n\turlKey: string;\n}\n\n/**\n * The user's access key, in the stage's secrets as the bucket's URL.\n *\n * - First run: one key, written into the stage's secrets.\n * - `--rotate-keys`: a second key, written in place of the first; the first\n * stays active until the stage has deployed with the second, and the next\n * run after that deploy — or `--retire-old-keys` — deletes it.\n * - A key the secrets no longer hold (a store emptied by hand): replaced the\n * same way, since its secret cannot be read back.\n *\n * @throws {BucketKeySetElsewhere} when the secret names another bucket\n * @throws {RotationInProgress} on `--rotate-keys` with the last rotation's old key still active\n * @throws {AccessKeyLimit} when the user has two keys gkm did not record\n */\nexport async function ensureAccessKey(\n\tctx: KeyContext,\n\tclients: IamClients,\n\tinput: AccessKeyInput,\n): Promise<void> {\n\tconst { IAM, iam } = clients;\n\tconst { id, bucket, user, urlKey } = input;\n\tconst entryKey = `iam-access-key:${id}`;\n\tconst record = ctx.state.record(entryKey);\n\n\tconst given = ctx.secrets[urlKey];\n\tlet inUrl: string | undefined;\n\tlet parsed: s3Url.S3Address | undefined;\n\tif (given !== undefined) {\n\t\ttry {\n\t\t\tparsed = s3Url.parse(given);\n\t\t} catch {\n\t\t\tparsed = undefined;\n\t\t}\n\t\tif (parsed?.bucket !== bucket) {\n\t\t\tthrow new BucketKeySetElsewhere(\n\t\t\t\turlKey,\n\t\t\t\tbucket,\n\t\t\t\tparsed?.bucket ?? given.replace(/\\/\\/[^@]*@/, '//'),\n\t\t\t\tctx.stage,\n\t\t\t);\n\t\t}\n\t\tinUrl = parsed.accessKeyId;\n\t}\n\n\tconst listed = input.exists\n\t\t? ((\n\t\t\t\tawait iam.send(new IAM.ListAccessKeysCommand({ UserName: user }))\n\t\t\t).AccessKeyMetadata?.map((k) => k.AccessKeyId!) ?? [])\n\t\t: [];\n\n\tlet current = record?.status === 'ready' ? record.id : undefined;\n\tlet previous =\n\t\ttypeof record?.data?.previous === 'string'\n\t\t\t? record.data.previous\n\t\t\t: undefined;\n\tconst rotatedAt =\n\t\ttypeof record?.data?.rotatedAt === 'string'\n\t\t\t? record.data.rotatedAt\n\t\t\t: undefined;\n\tconst entry = (data: Record<string, unknown> = {}): StateEntry => ({\n\t\tkey: entryKey,\n\t\ttype: 'iam-access-key',\n\t\tdata: { user, ...data },\n\t});\n\n\t// The old key of a rotation: deleted once the stage deployed after it.\n\tif (previous && current) {\n\t\tconst deployed =\n\t\t\trotatedAt !== undefined &&\n\t\t\tctx.state.lastDeployedAt !== undefined &&\n\t\t\tctx.state.lastDeployedAt > rotatedAt;\n\t\tif (ctx.retireOldKeys || deployed) {\n\t\t\tconst old = previous;\n\t\t\tconst keep = current;\n\t\t\tawait ctx.change(\n\t\t\t\t{\n\t\t\t\t\tconstruct: id,\n\t\t\t\t\tresource: `IAM user ${user}`,\n\t\t\t\t\tchange: `delete the rotated-out access key ${old}`,\n\t\t\t\t},\n\t\t\t\tasync () => {\n\t\t\t\t\tif (listed.includes(old)) {\n\t\t\t\t\t\tawait iam.send(\n\t\t\t\t\t\t\tnew IAM.DeleteAccessKeyCommand({\n\t\t\t\t\t\t\t\tUserName: user,\n\t\t\t\t\t\t\t\tAccessKeyId: old,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tawait ctx.state.ready(entry(), keep);\n\t\t\t\t},\n\t\t\t);\n\t\t\tprevious = undefined;\n\t\t} else {\n\t\t\tctx.log(\n\t\t\t\t` ${id}: the old access key ${previous} stays active until '${ctx.stage}' is deployed with the new one; the next deploy after that deletes it (or pass --retire-old-keys)`,\n\t\t\t);\n\t\t}\n\t}\n\n\t// No record, and the secrets hold a key of this user's: adopt it.\n\tif (!current && inUrl && listed.includes(inUrl)) {\n\t\tawait ctx.state.ready(entry(), inUrl);\n\t\tcurrent = inUrl;\n\t}\n\n\tconst valid =\n\t\tcurrent !== undefined && listed.includes(current) && inUrl === current;\n\tif (valid && !ctx.rotateKeys) {\n\t\t// The key is good; the address must name where the bucket is.\n\t\tif (parsed && parsed.region !== clients.region) {\n\t\t\tconst address = parsed;\n\t\t\tawait ctx.change(\n\t\t\t\t{\n\t\t\t\t\tconstruct: id,\n\t\t\t\t\tresource: urlKey,\n\t\t\t\t\tchange: `name ${clients.region}, the bucket's region (it said ${address.region ?? 'none'})`,\n\t\t\t\t},\n\t\t\t\t() =>\n\t\t\t\t\tctx.writeSecrets({\n\t\t\t\t\t\t[urlKey]: s3Url.build({ ...address, region: clients.region }),\n\t\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\treturn;\n\t}\n\tif (ctx.rotateKeys && previous) {\n\t\tthrow new RotationInProgress(id, previous, ctx.stage);\n\t}\n\n\tconst outgoing = current && listed.includes(current) ? current : undefined;\n\tif (listed.length >= 2) throw new AccessKeyLimit(user, listed);\n\n\tconst why = !current\n\t\t? 'create an access key'\n\t\t: ctx.rotateKeys\n\t\t\t? 'rotate: issue a new access key'\n\t\t\t: 'issue a new access key (the secrets no longer hold the recorded one)';\n\tawait ctx.change(\n\t\t{ construct: id, resource: `IAM user ${user}`, change: why },\n\t\tasync () => {\n\t\t\tawait ctx.state.pending(entry(outgoing ? { previous: outgoing } : {}));\n\t\t\tconst created = await iam.send(\n\t\t\t\tnew IAM.CreateAccessKeyCommand({ UserName: user }),\n\t\t\t);\n\t\t\tconst key = created.AccessKey!;\n\t\t\t// Into the stage's secrets before anything else: IAM shows a secret\n\t\t\t// once, and a key whose secret is lost is a key to replace.\n\t\t\tawait ctx.writeSecrets({\n\t\t\t\t[urlKey]: s3Url.build({\n\t\t\t\t\tbucket,\n\t\t\t\t\tregion: clients.region,\n\t\t\t\t\t...(clients.endpoint\n\t\t\t\t\t\t? { endpoint: clients.endpoint, forcePathStyle: true }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\taccessKeyId: key.AccessKeyId!,\n\t\t\t\t\tsecretAccessKey: key.SecretAccessKey!,\n\t\t\t\t}),\n\t\t\t});\n\t\t\t// When it was issued: IAM takes seconds to make a new key usable,\n\t\t\t// and the deploy's check waits for one this young.\n\t\t\tconst issuedAt = new Date().toISOString();\n\t\t\tawait ctx.state.ready(\n\t\t\t\tentry(\n\t\t\t\t\toutgoing\n\t\t\t\t\t\t? { previous: outgoing, rotatedAt: issuedAt, issuedAt }\n\t\t\t\t\t\t: { issuedAt },\n\t\t\t\t),\n\t\t\t\tkey.AccessKeyId!,\n\t\t\t);\n\t\t},\n\t);\n\tif (outgoing) {\n\t\tctx.log(\n\t\t\t` ${urlKey} holds the new key. This deploy moves '${ctx.stage}' onto it; the next deploy after it deletes the old key ${outgoing}`,\n\t\t);\n\t}\n}\n\n/** How long a key issued this recently counts as new to IAM. */\nconst NEW_KEY_WINDOW_MS = 10 * 60 * 1000;\n\n/** The waits between asks while a new key becomes usable: about a minute. */\nlet newKeyWaits: readonly number[] = [2000, 4000, 8000, 15000, 15000, 15000];\n\n/** For tests: the waits for a new key. Returns the old ones. */\nexport function useNewKeyWaits(waits: readonly number[]): readonly number[] {\n\tconst previous = newKeyWaits;\n\tnewKeyWaits = waits;\n\treturn previous;\n}\n\n/**\n * When the key in a URL was issued, if the stage's state says it was just\n * now — the record of `id`'s key naming that very key.\n */\nexport function issuedJustNow(\n\tresources: Readonly<Record<string, ResourceRecord>> | undefined,\n\tid: string,\n\taccessKeyId: string,\n): string | undefined {\n\tconst record = resources?.[`iam-access-key:${id}`];\n\tconst issuedAt = record?.data?.issuedAt;\n\tif (record?.id !== accessKeyId || typeof issuedAt !== 'string') {\n\t\treturn undefined;\n\t}\n\tconst age = Date.now() - Date.parse(issuedAt);\n\treturn age >= 0 && age < NEW_KEY_WINDOW_MS ? issuedAt : undefined;\n}\n\n/**\n * `ask` again, for about a minute, while it is `refused` and the key was\n * issued just now — IAM refuses a key for seconds after making it. Returns\n * the last answer and how long was waited.\n */\nexport async function whileKeyIsNew<T>(\n\tfirst: T,\n\toptions: {\n\t\tissuedAt: string | undefined;\n\t\trefused: (answer: T) => boolean;\n\t\task: () => Promise<T>;\n\t\t/** Said once, before the first wait. */\n\t\tonWait?: () => void;\n\t},\n): Promise<{ answer: T; waited: number }> {\n\tlet answer = first;\n\tlet waited = 0;\n\tif (!options.issuedAt || !options.refused(answer)) return { answer, waited };\n\toptions.onWait?.();\n\tfor (const wait of newKeyWaits) {\n\t\tawait new Promise((resolve) => setTimeout(resolve, wait));\n\t\twaited += wait;\n\t\tanswer = await options.ask();\n\t\tif (!options.refused(answer)) break;\n\t}\n\treturn { answer, waited };\n}\n"],"mappings":";;;;;;;AAuBA,MAAM,kBAAkB;;AAGxB,IAAa,oBAAb,cAAuCA,eAAAA,SAAS;CAErC;CACA;CAFV,YACC,QACA,QACC;EACD,MACC,IAAI,OAAO,mCAAmC,OAAO,sGAGtD;EAPS,KAAA,SAAA;EACA,KAAA,SAAA;EAOT,KAAK,OAAO;CACb;AACD;;AAGA,SAAS,KAAK,OAAuB;CACpC,QAAA,GAAOC,oBAAAA,UAAAA,CAAU,KAAK,CAAC,CACrB,YAAY,CAAC,CACb,QAAQ,eAAe,GAAG,CAAC,CAC3B,QAAQ,YAA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;CAAO;CAC3E,QAAQ,SAAS;CACjB,KAAK,MAAM,QAAQ,aAAa;EAC/B,MAAM,IAAI,SAAS,YAAY,WAAW,SAAS,IAAI,CAAC;EACxD,UAAU;EACV,SAAS,MAAM,QAAQ,IAAI;EAC3B,IAAI,CAAC,QAAQ,QAAQ,MAAM,GAAG;CAC/B;CACA,OAAO;EAAE;EAAQ;CAAO;AACzB"}
@@ -0,0 +1,509 @@
1
+ import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
2
+ import { X as AccessKeyLimit, Z as BucketKeySetElsewhere, ot as RotationInProgress, rt as IamUserNotOwned } from "./workspace-DFGsrjGD.mjs";
3
+ import { randomInt } from "node:crypto";
4
+ import { kebabCase } from "@geekmidas/manifest";
5
+ import * as s3Url from "@geekmidas/storage/s3-url";
6
+ const SUFFIX_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
7
+ /** A name that S3 would refuse — what the name builder never returns. */
8
+ var InvalidBucketName = class extends GkmError {
9
+ bucket;
10
+ reason;
11
+ constructor(bucket, reason) {
12
+ super(`'${bucket}' is not a valid S3 bucket name: ${reason}. Rename the construct or set deploy.namespace in gkm.config.ts to something that leaves room for it.`);
13
+ this.bucket = bucket;
14
+ this.reason = reason;
15
+ this.name = "InvalidBucketName";
16
+ }
17
+ };
18
+ /** Lowercase `[a-z0-9-]`, runs of anything else one `-`, no edge dashes. */
19
+ function part(value) {
20
+ return kebabCase(value).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
21
+ }
22
+ /**
23
+ * `parts` joined by `-`, shortened to `max` characters by trimming the longest
24
+ * part one character at a time — so a long construct id gives way before a
25
+ * short stage name does, and every part keeps its start.
26
+ */
27
+ function fitParts(parts, max) {
28
+ const kept = parts.map(part).filter(Boolean);
29
+ const length = () => kept.reduce((sum, p) => sum + p.length, 0) + kept.length - 1;
30
+ while (length() > max) {
31
+ let longest = 0;
32
+ for (let i = 1; i < kept.length; i++) if (kept[i].length > kept[longest].length) longest = i;
33
+ if (kept[longest].length <= 1) break;
34
+ kept[longest] = kept[longest].slice(0, -1).replace(/-+$/, "");
35
+ }
36
+ return kept.join("-");
37
+ }
38
+ /** Why `name` is not a valid bucket name, or undefined when it is. */
39
+ function bucketNameProblem(name) {
40
+ if (name.length < 3 || name.length > 63) return `it is ${name.length} characters, and S3 takes 3 to 63`;
41
+ if (!/^[a-z0-9-]+$/.test(name)) return "it may hold only lowercase letters, digits and -";
42
+ if (!/^[a-z0-9].*[a-z0-9]$/.test(name)) return "it must start and end with a letter or a digit";
43
+ if (name.startsWith("xn--") || name.startsWith("sthree-")) return "it starts with a prefix S3 reserves ('xn--', 'sthree-')";
44
+ if (name.endsWith("-s3alias") || name.endsWith("--ol-s3")) return "it ends with a suffix S3 reserves ('-s3alias', '--ol-s3')";
45
+ }
46
+ /**
47
+ * The good name: `<namespace>-<project>-<stage>-<bucket id>`, lowercased, no
48
+ * dots, shortened to leave room for a clash's suffix.
49
+ *
50
+ * @throws {InvalidBucketName} when nothing usable is left
51
+ */
52
+ function bucketName(input) {
53
+ const name = fitParts([
54
+ input.scope,
55
+ input.stage,
56
+ input.id
57
+ ], 56);
58
+ const problem = bucketNameProblem(name);
59
+ if (problem) throw new InvalidBucketName(name, problem);
60
+ return name;
61
+ }
62
+ /** Six random `[a-z0-9]` characters. */
63
+ function randomSuffix(random = randomInt) {
64
+ let suffix = "";
65
+ for (let i = 0; i < 6; i++) suffix += SUFFIX_ALPHABET[random(36)];
66
+ return suffix;
67
+ }
68
+ /** The good name with a clash's suffix. */
69
+ function suffixedBucketName(good, suffix) {
70
+ return `${good}-${suffix}`;
71
+ }
72
+ /**
73
+ * The IAM user a bucket is reached with on a stage:
74
+ * `gkm-<project>-<stage>-<bucket id>`, at most 64 characters.
75
+ */
76
+ function iamUserName(input) {
77
+ return fitParts([
78
+ "gkm",
79
+ input.scope,
80
+ input.stage,
81
+ input.id
82
+ ], 64);
83
+ }
84
+ /** The path every user gkm creates is under, so it finds its own. */
85
+ const IAM_USER_PATH = "/gkm/";
86
+ /** The inline policy each user is given. */
87
+ const IAM_POLICY_NAME = "gkm-bucket";
88
+ //#endregion
89
+ //#region src/providers/s3/policy.ts
90
+ const bucketArn = (bucket) => `arn:aws:s3:::${bucket}`;
91
+ /**
92
+ * What the app's key may do: objects in this bucket, and listing it — and
93
+ * nothing else in the account.
94
+ *
95
+ * Multipart uploads are in it because a presigned upload of a large file is
96
+ * one, and an abandoned one is cleaned up by the app. Reading old versions is
97
+ * added only when the bucket keeps them.
98
+ */
99
+ function userPolicy(bucket, options = {}) {
100
+ return {
101
+ Version: "2012-10-17",
102
+ Statement: [
103
+ {
104
+ Sid: "GkmObjects",
105
+ Effect: "Allow",
106
+ Action: [
107
+ "s3:GetObject",
108
+ "s3:PutObject",
109
+ "s3:DeleteObject",
110
+ "s3:AbortMultipartUpload",
111
+ "s3:ListMultipartUploadParts",
112
+ ...options.versioning ? ["s3:GetObjectVersion"] : []
113
+ ],
114
+ Resource: `${bucketArn(bucket)}/*`
115
+ },
116
+ {
117
+ Sid: "GkmBucket",
118
+ Effect: "Allow",
119
+ Action: [
120
+ "s3:ListBucket",
121
+ "s3:GetBucketLocation",
122
+ "s3:ListBucketMultipartUploads"
123
+ ],
124
+ Resource: bucketArn(bucket)
125
+ },
126
+ ...options.eventsTopicArn ? [{
127
+ Sid: "GkmEvents",
128
+ Effect: "Allow",
129
+ Action: "sns:ConfirmSubscription",
130
+ Resource: options.eventsTopicArn
131
+ }] : []
132
+ ]
133
+ };
134
+ }
135
+ /**
136
+ * One open pattern as the resource it is public on. A `**` is S3's `*`; a
137
+ * single `*` is too, which crosses `/` where the construct's own check does
138
+ * not — the construct is the stricter of the two (see `bucketPolicy` in
139
+ * reconcile, which the local MinIO is given the same way).
140
+ */
141
+ function openResource(bucket, pattern) {
142
+ const path = pattern.replace(/^\/+/, "").replace(/\*\*/g, "*");
143
+ return `${bucketArn(bucket)}/${path}`;
144
+ }
145
+ /**
146
+ * The bucket's own policy: every request refused unless it came over TLS,
147
+ * and — only when a file server opens paths on it — `s3:GetObject` on
148
+ * exactly those prefixes: to anyone, or, when a CDN serves them, to
149
+ * CloudFront alone, for exactly the stage's distributions. Behind a CDN the
150
+ * bucket is never public: a key outside the open prefixes is refused to
151
+ * CloudFront too, so the edge answers it 403.
152
+ */
153
+ function bucketPolicy(bucket, open = [], options = {}) {
154
+ const statements = [{
155
+ Sid: "GkmDenyInsecureTransport",
156
+ Effect: "Deny",
157
+ Principal: "*",
158
+ Action: "s3:*",
159
+ Resource: [bucketArn(bucket), `${bucketArn(bucket)}/*`],
160
+ Condition: { Bool: { "aws:SecureTransport": "false" } }
161
+ }];
162
+ const resources = [...new Set(open.map((p) => openResource(bucket, p)))].sort();
163
+ if (open.length > 0 && options.cdn) statements.push({
164
+ Sid: "GkmCdnRead",
165
+ Effect: "Allow",
166
+ Principal: { Service: "cloudfront.amazonaws.com" },
167
+ Action: "s3:GetObject",
168
+ Resource: resources,
169
+ Condition: { StringEquals: { "AWS:SourceArn": [...new Set(options.cdn.distributionArns)].sort() } }
170
+ });
171
+ else if (open.length > 0) statements.push({
172
+ Sid: "GkmOpenPaths",
173
+ Effect: "Allow",
174
+ Principal: "*",
175
+ Action: "s3:GetObject",
176
+ Resource: resources
177
+ });
178
+ if (options.sesWrite) statements.push({
179
+ Sid: "GkmSesWritesMail",
180
+ Effect: "Allow",
181
+ Principal: { Service: "ses.amazonaws.com" },
182
+ Action: "s3:PutObject",
183
+ Resource: `${bucketArn(bucket)}/${options.sesWrite.prefix}*`,
184
+ Condition: { StringEquals: { "aws:SourceAccount": options.sesWrite.account } }
185
+ });
186
+ return {
187
+ Version: "2012-10-17",
188
+ Statement: statements
189
+ };
190
+ }
191
+ /**
192
+ * Block Public Access. All four flags on, unless the bucket has open paths:
193
+ * then a *policy* may make it public (`BlockPublicPolicy`,
194
+ * `RestrictPublicBuckets` off), and ACLs still may not.
195
+ */
196
+ function publicAccessBlock(open) {
197
+ return {
198
+ BlockPublicAcls: true,
199
+ IgnorePublicAcls: true,
200
+ BlockPublicPolicy: !open,
201
+ RestrictPublicBuckets: !open
202
+ };
203
+ }
204
+ function corsRule(origins) {
205
+ return {
206
+ AllowedMethods: [
207
+ "GET",
208
+ "HEAD",
209
+ "POST",
210
+ "PUT"
211
+ ],
212
+ AllowedOrigins: [...new Set(origins)].sort(),
213
+ AllowedHeaders: ["*"],
214
+ ExposeHeaders: ["ETag"],
215
+ MaxAgeSeconds: 3e3
216
+ };
217
+ }
218
+ /**
219
+ * A policy document in one canonical form — keys sorted, a lone string a
220
+ * one-element list, lists sorted — so one AWS reformatted reads as the same
221
+ * document rather than as drift.
222
+ */
223
+ function canonicalPolicy(value) {
224
+ return JSON.stringify(canonical(value));
225
+ }
226
+ function canonical(value, key) {
227
+ if (Array.isArray(value)) {
228
+ const items = value.map((v) => canonical(v));
229
+ return key === "Statement" ? items : items.map((v) => JSON.stringify(v)).sort();
230
+ }
231
+ if (value && typeof value === "object") return Object.fromEntries(Object.keys(value).sort().map((k) => {
232
+ const v = value[k];
233
+ return [k, canonical(k === "Action" || k === "Resource" || k === "AWS" || k === "AWS:SourceArn" ? Array.isArray(v) ? v : [v] : v, k)];
234
+ }));
235
+ return value;
236
+ }
237
+ //#endregion
238
+ //#region src/providers/iam.ts
239
+ /**
240
+ * An IAM user gkm creates for one thing on a stage, its inline policy, and
241
+ * the access key written into the stage's secrets as an `s3://` URL — what
242
+ * the `s3` provider gives each bucket, and the deploy gives a stage's
243
+ * backups.
244
+ *
245
+ * - **The user** is under `/gkm/`, tagged with the deploy identity, the stage
246
+ * and what it is for. One that exists without those tags is someone
247
+ * else's, and is refused rather than taken over.
248
+ * - **Its policy** is read on every run and put back when it drifted.
249
+ * - **Its key**: one, written into the stage's secrets the moment IAM shows
250
+ * its secret. `--rotate-keys` issues a successor and keeps the old one
251
+ * active until the stage has deployed with the new one; the next run after
252
+ * that — or `--retire-old-keys` — deletes it.
253
+ * - **A new key** takes IAM seconds to become usable: the state records when
254
+ * it was issued, and a check made with it waits that out
255
+ * ({@link whileKeyIsNew}).
256
+ */
257
+ /** The tags gkm finds its own buckets and users by. */
258
+ const TAG_PROJECT = "gkm:project";
259
+ const TAG_STAGE = "gkm:stage";
260
+ const TAG_CONSTRUCT = "gkm:construct";
261
+ /** The keys gkm tags a bucket and a user with. */
262
+ function identityTags(ctx, id) {
263
+ return [
264
+ {
265
+ Key: TAG_PROJECT,
266
+ Value: ctx.identity.key
267
+ },
268
+ {
269
+ Key: TAG_STAGE,
270
+ Value: ctx.stage
271
+ },
272
+ {
273
+ Key: TAG_CONSTRUCT,
274
+ Value: id
275
+ }
276
+ ];
277
+ }
278
+ /** A read whose "there is none" answer is one of `missing`. */
279
+ async function readOr(read, missing) {
280
+ try {
281
+ return await read();
282
+ } catch (error) {
283
+ const e = error;
284
+ if (missing.includes(e?.Code ?? e?.name ?? "")) return void 0;
285
+ throw error;
286
+ }
287
+ }
288
+ /** IAM returns a policy document URL-encoded; an emulator may not. */
289
+ function decodePolicy(document) {
290
+ try {
291
+ return decodeURIComponent(document);
292
+ } catch {
293
+ return document;
294
+ }
295
+ }
296
+ /**
297
+ * The user and its inline policy: found — and refused when it is not this
298
+ * stage's — or created, and the policy put back when it drifted.
299
+ *
300
+ * @throws {IamUserNotOwned}
301
+ */
302
+ async function ensureIamUser(ctx, clients, input) {
303
+ const { IAM, iam } = clients;
304
+ const { id, user, policy } = input;
305
+ const entry = {
306
+ key: `iam-user:${id}`,
307
+ type: "iam-user"
308
+ };
309
+ const found = await readOr(() => iam.send(new IAM.GetUserCommand({ UserName: user })), ["NoSuchEntity", "NoSuchEntityException"]);
310
+ if (found?.User) {
311
+ const tags = await iam.send(new IAM.ListUserTagsCommand({ UserName: user }));
312
+ const tag = (key) => tags.Tags?.find((t) => t.Key === key)?.Value;
313
+ if (found.User.Path !== "/gkm/" || tag("gkm:project") !== ctx.identity.key || tag("gkm:stage") !== ctx.stage) throw new IamUserNotOwned(user, ctx.identity.key, ctx.stage);
314
+ await ctx.state.ready(entry, user);
315
+ } else await ctx.change({
316
+ construct: id,
317
+ resource: `IAM user ${user}`,
318
+ change: `create under ${IAM_USER_PATH}`
319
+ }, async () => {
320
+ await ctx.state.pending(entry);
321
+ await iam.send(new IAM.CreateUserCommand({
322
+ UserName: user,
323
+ Path: IAM_USER_PATH,
324
+ Tags: identityTags(ctx, id)
325
+ }));
326
+ await ctx.state.ready(entry, user);
327
+ });
328
+ const exists = Boolean(found?.User) || !ctx.dryRun;
329
+ const current = exists ? await readOr(() => iam.send(new IAM.GetUserPolicyCommand({
330
+ UserName: user,
331
+ PolicyName: input.policyName
332
+ })), ["NoSuchEntity", "NoSuchEntityException"]) : void 0;
333
+ const document = current?.PolicyDocument ? JSON.parse(decodePolicy(current.PolicyDocument)) : void 0;
334
+ if (!document || canonicalPolicy(document) !== canonicalPolicy(policy)) await ctx.change({
335
+ construct: id,
336
+ resource: `IAM user ${user}`,
337
+ change: `policy ${input.policyName}: ${input.describe}`
338
+ }, async () => {
339
+ await iam.send(new IAM.PutUserPolicyCommand({
340
+ UserName: user,
341
+ PolicyName: input.policyName,
342
+ PolicyDocument: JSON.stringify(policy)
343
+ }));
344
+ });
345
+ return {
346
+ user,
347
+ exists
348
+ };
349
+ }
350
+ /**
351
+ * The user's access key, in the stage's secrets as the bucket's URL.
352
+ *
353
+ * - First run: one key, written into the stage's secrets.
354
+ * - `--rotate-keys`: a second key, written in place of the first; the first
355
+ * stays active until the stage has deployed with the second, and the next
356
+ * run after that deploy — or `--retire-old-keys` — deletes it.
357
+ * - A key the secrets no longer hold (a store emptied by hand): replaced the
358
+ * same way, since its secret cannot be read back.
359
+ *
360
+ * @throws {BucketKeySetElsewhere} when the secret names another bucket
361
+ * @throws {RotationInProgress} on `--rotate-keys` with the last rotation's old key still active
362
+ * @throws {AccessKeyLimit} when the user has two keys gkm did not record
363
+ */
364
+ async function ensureAccessKey(ctx, clients, input) {
365
+ const { IAM, iam } = clients;
366
+ const { id, bucket, user, urlKey } = input;
367
+ const entryKey = `iam-access-key:${id}`;
368
+ const record = ctx.state.record(entryKey);
369
+ const given = ctx.secrets[urlKey];
370
+ let inUrl;
371
+ let parsed;
372
+ if (given !== void 0) {
373
+ try {
374
+ parsed = s3Url.parse(given);
375
+ } catch {
376
+ parsed = void 0;
377
+ }
378
+ if (parsed?.bucket !== bucket) throw new BucketKeySetElsewhere(urlKey, bucket, parsed?.bucket ?? given.replace(/\/\/[^@]*@/, "//"), ctx.stage);
379
+ inUrl = parsed.accessKeyId;
380
+ }
381
+ const listed = input.exists ? (await iam.send(new IAM.ListAccessKeysCommand({ UserName: user }))).AccessKeyMetadata?.map((k) => k.AccessKeyId) ?? [] : [];
382
+ let current = record?.status === "ready" ? record.id : void 0;
383
+ let previous = typeof record?.data?.previous === "string" ? record.data.previous : void 0;
384
+ const rotatedAt = typeof record?.data?.rotatedAt === "string" ? record.data.rotatedAt : void 0;
385
+ const entry = (data = {}) => ({
386
+ key: entryKey,
387
+ type: "iam-access-key",
388
+ data: {
389
+ user,
390
+ ...data
391
+ }
392
+ });
393
+ if (previous && current) {
394
+ const deployed = rotatedAt !== void 0 && ctx.state.lastDeployedAt !== void 0 && ctx.state.lastDeployedAt > rotatedAt;
395
+ if (ctx.retireOldKeys || deployed) {
396
+ const old = previous;
397
+ const keep = current;
398
+ await ctx.change({
399
+ construct: id,
400
+ resource: `IAM user ${user}`,
401
+ change: `delete the rotated-out access key ${old}`
402
+ }, async () => {
403
+ if (listed.includes(old)) await iam.send(new IAM.DeleteAccessKeyCommand({
404
+ UserName: user,
405
+ AccessKeyId: old
406
+ }));
407
+ await ctx.state.ready(entry(), keep);
408
+ });
409
+ previous = void 0;
410
+ } else ctx.log(` ${id}: the old access key ${previous} stays active until '${ctx.stage}' is deployed with the new one; the next deploy after that deletes it (or pass --retire-old-keys)`);
411
+ }
412
+ if (!current && inUrl && listed.includes(inUrl)) {
413
+ await ctx.state.ready(entry(), inUrl);
414
+ current = inUrl;
415
+ }
416
+ if (current !== void 0 && listed.includes(current) && inUrl === current && !ctx.rotateKeys) {
417
+ if (parsed && parsed.region !== clients.region) {
418
+ const address = parsed;
419
+ await ctx.change({
420
+ construct: id,
421
+ resource: urlKey,
422
+ change: `name ${clients.region}, the bucket's region (it said ${address.region ?? "none"})`
423
+ }, () => ctx.writeSecrets({ [urlKey]: s3Url.build({
424
+ ...address,
425
+ region: clients.region
426
+ }) }));
427
+ }
428
+ return;
429
+ }
430
+ if (ctx.rotateKeys && previous) throw new RotationInProgress(id, previous, ctx.stage);
431
+ const outgoing = current && listed.includes(current) ? current : void 0;
432
+ if (listed.length >= 2) throw new AccessKeyLimit(user, listed);
433
+ const why = !current ? "create an access key" : ctx.rotateKeys ? "rotate: issue a new access key" : "issue a new access key (the secrets no longer hold the recorded one)";
434
+ await ctx.change({
435
+ construct: id,
436
+ resource: `IAM user ${user}`,
437
+ change: why
438
+ }, async () => {
439
+ await ctx.state.pending(entry(outgoing ? { previous: outgoing } : {}));
440
+ const key = (await iam.send(new IAM.CreateAccessKeyCommand({ UserName: user }))).AccessKey;
441
+ await ctx.writeSecrets({ [urlKey]: s3Url.build({
442
+ bucket,
443
+ region: clients.region,
444
+ ...clients.endpoint ? {
445
+ endpoint: clients.endpoint,
446
+ forcePathStyle: true
447
+ } : {},
448
+ accessKeyId: key.AccessKeyId,
449
+ secretAccessKey: key.SecretAccessKey
450
+ }) });
451
+ const issuedAt = (/* @__PURE__ */ new Date()).toISOString();
452
+ await ctx.state.ready(entry(outgoing ? {
453
+ previous: outgoing,
454
+ rotatedAt: issuedAt,
455
+ issuedAt
456
+ } : { issuedAt }), key.AccessKeyId);
457
+ });
458
+ if (outgoing) ctx.log(` ${urlKey} holds the new key. This deploy moves '${ctx.stage}' onto it; the next deploy after it deletes the old key ${outgoing}`);
459
+ }
460
+ /** How long a key issued this recently counts as new to IAM. */
461
+ const NEW_KEY_WINDOW_MS = 6e5;
462
+ /** The waits between asks while a new key becomes usable: about a minute. */
463
+ let newKeyWaits = [
464
+ 2e3,
465
+ 4e3,
466
+ 8e3,
467
+ 15e3,
468
+ 15e3,
469
+ 15e3
470
+ ];
471
+ /**
472
+ * When the key in a URL was issued, if the stage's state says it was just
473
+ * now — the record of `id`'s key naming that very key.
474
+ */
475
+ function issuedJustNow(resources, id, accessKeyId) {
476
+ const record = resources?.[`iam-access-key:${id}`];
477
+ const issuedAt = record?.data?.issuedAt;
478
+ if (record?.id !== accessKeyId || typeof issuedAt !== "string") return;
479
+ const age = Date.now() - Date.parse(issuedAt);
480
+ return age >= 0 && age < NEW_KEY_WINDOW_MS ? issuedAt : void 0;
481
+ }
482
+ /**
483
+ * `ask` again, for about a minute, while it is `refused` and the key was
484
+ * issued just now — IAM refuses a key for seconds after making it. Returns
485
+ * the last answer and how long was waited.
486
+ */
487
+ async function whileKeyIsNew(first, options) {
488
+ let answer = first;
489
+ let waited = 0;
490
+ if (!options.issuedAt || !options.refused(answer)) return {
491
+ answer,
492
+ waited
493
+ };
494
+ options.onWait?.();
495
+ for (const wait of newKeyWaits) {
496
+ await new Promise((resolve) => setTimeout(resolve, wait));
497
+ waited += wait;
498
+ answer = await options.ask();
499
+ if (!options.refused(answer)) break;
500
+ }
501
+ return {
502
+ answer,
503
+ waited
504
+ };
505
+ }
506
+ //#endregion
507
+ export { randomSuffix as _, identityTags as a, bucketPolicy as c, publicAccessBlock as d, userPolicy as f, iamUserName as g, bucketName as h, ensureIamUser as i, canonicalPolicy as l, IAM_USER_PATH as m, TAG_STAGE as n, issuedJustNow as o, IAM_POLICY_NAME as p, ensureAccessKey as r, whileKeyIsNew as s, TAG_PROJECT as t, corsRule as u, suffixedBucketName as v };
508
+
509
+ //# sourceMappingURL=iam-c0e8m04X.mjs.map