@geekmidas/cli 10.0.0-alpha.167 → 10.0.0-alpha.169

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 (251) hide show
  1. package/dist/{EndpointGenerator-DxrRqfJ3.cjs → EndpointGenerator-C1h_wExz.cjs} +2 -2
  2. package/dist/{EndpointGenerator-DxrRqfJ3.cjs.map → EndpointGenerator-C1h_wExz.cjs.map} +1 -1
  3. package/dist/{EndpointGenerator-B5BKAoLz.mjs → EndpointGenerator-CSKhAD6W.mjs} +2 -2
  4. package/dist/{EndpointGenerator-B5BKAoLz.mjs.map → EndpointGenerator-CSKhAD6W.mjs.map} +1 -1
  5. package/dist/{GoDaddyProvider-Dci0SlN5.mjs → GoDaddyProvider-Cvmy2SPq.mjs} +2 -2
  6. package/dist/{GoDaddyProvider-Dci0SlN5.mjs.map → GoDaddyProvider-Cvmy2SPq.mjs.map} +1 -1
  7. package/dist/{GoDaddyProvider-o6DJAsBZ.cjs → GoDaddyProvider-KmdZlFSL.cjs} +2 -2
  8. package/dist/{GoDaddyProvider-o6DJAsBZ.cjs.map → GoDaddyProvider-KmdZlFSL.cjs.map} +1 -1
  9. package/dist/{HostingerProvider-BzHPhONW.cjs → HostingerProvider--IyQKlIC.cjs} +2 -2
  10. package/dist/{HostingerProvider-BzHPhONW.cjs.map → HostingerProvider--IyQKlIC.cjs.map} +1 -1
  11. package/dist/{HostingerProvider-Dd5x1zvF.mjs → HostingerProvider-DYf1XT_W.mjs} +2 -2
  12. package/dist/{HostingerProvider-Dd5x1zvF.mjs.map → HostingerProvider-DYf1XT_W.mjs.map} +1 -1
  13. package/dist/{LegacyStateStore-tqY0hM8z.cjs → LegacyStateStore-8GVMHI12.cjs} +2 -2
  14. package/dist/{LegacyStateStore-tqY0hM8z.cjs.map → LegacyStateStore-8GVMHI12.cjs.map} +1 -1
  15. package/dist/{LegacyStateStore-CpF6rmZc.mjs → LegacyStateStore-BOZj8nj1.mjs} +2 -2
  16. package/dist/{LegacyStateStore-CpF6rmZc.mjs.map → LegacyStateStore-BOZj8nj1.mjs.map} +1 -1
  17. package/dist/{LocalStateStore-BYMUEGZN.cjs → LocalStateStore-CfBABk6G.cjs} +2 -2
  18. package/dist/{LocalStateStore-BYMUEGZN.cjs.map → LocalStateStore-CfBABk6G.cjs.map} +1 -1
  19. package/dist/{LocalStateStore-Adp96xPy.mjs → LocalStateStore-D3wY7Qkb.mjs} +2 -2
  20. package/dist/{LocalStateStore-Adp96xPy.mjs.map → LocalStateStore-D3wY7Qkb.mjs.map} +1 -1
  21. package/dist/{OpenApiTsGenerator-Vaf0pI8u.mjs → OpenApiTsGenerator-5xPn-p65.mjs} +2 -2
  22. package/dist/{OpenApiTsGenerator-Vaf0pI8u.mjs.map → OpenApiTsGenerator-5xPn-p65.mjs.map} +1 -1
  23. package/dist/{OpenApiTsGenerator-DOTLKBFf.cjs → OpenApiTsGenerator-CzrLGzC0.cjs} +2 -2
  24. package/dist/{OpenApiTsGenerator-DOTLKBFf.cjs.map → OpenApiTsGenerator-CzrLGzC0.cjs.map} +1 -1
  25. package/dist/{S3StateStore-DjXyhGIP.cjs → S3StateStore-C-Fs7CWD.cjs} +4 -4
  26. package/dist/{S3StateStore-DjXyhGIP.cjs.map → S3StateStore-C-Fs7CWD.cjs.map} +1 -1
  27. package/dist/{S3StateStore-13Go3hfM.mjs → S3StateStore-CO92LBQI.mjs} +4 -4
  28. package/dist/{S3StateStore-13Go3hfM.mjs.map → S3StateStore-CO92LBQI.mjs.map} +1 -1
  29. package/dist/{SSMStateStore-CQHUyH-c.mjs → SSMStateStore-Ns7FpnmB.mjs} +2 -2
  30. package/dist/{SSMStateStore-CQHUyH-c.mjs.map → SSMStateStore-Ns7FpnmB.mjs.map} +1 -1
  31. package/dist/{SSMStateStore-DspMPho-.cjs → SSMStateStore-t6mkXQew.cjs} +2 -2
  32. package/dist/{SSMStateStore-DspMPho-.cjs.map → SSMStateStore-t6mkXQew.cjs.map} +1 -1
  33. package/dist/{SubscriberGenerator-BybB6uez.mjs → SubscriberGenerator-CfZWX0lT.mjs} +6 -6
  34. package/dist/SubscriberGenerator-CfZWX0lT.mjs.map +1 -0
  35. package/dist/{SubscriberGenerator-mZpSuSU7.cjs → SubscriberGenerator-DMi4siph.cjs} +5 -5
  36. package/dist/SubscriberGenerator-DMi4siph.cjs.map +1 -0
  37. package/dist/{add-Dt8QKSOw.mjs → add-Byp8-rRf.mjs} +11 -11
  38. package/dist/add-Byp8-rRf.mjs.map +1 -0
  39. package/dist/{add-DsxJ0Knr.cjs → add-C3oUiBAc.cjs} +10 -10
  40. package/dist/add-C3oUiBAc.cjs.map +1 -0
  41. package/dist/{apps-w2sRQKCr.mjs → apps-C21-TXqR.mjs} +106 -50
  42. package/dist/apps-C21-TXqR.mjs.map +1 -0
  43. package/dist/{apps-C6s-trVp.cjs → apps-D_-DXV0H.cjs} +110 -48
  44. package/dist/apps-D_-DXV0H.cjs.map +1 -0
  45. package/dist/{bundler-AzkSRAuu.cjs → bundler-D43S2YTJ.cjs} +6 -6
  46. package/dist/{bundler-AzkSRAuu.cjs.map → bundler-D43S2YTJ.cjs.map} +1 -1
  47. package/dist/{bundler-BCWWne6N.mjs → bundler-DjfpJ0mX.mjs} +6 -6
  48. package/dist/{bundler-BCWWne6N.mjs.map → bundler-DjfpJ0mX.mjs.map} +1 -1
  49. package/dist/{cli-DSGw0Mw-.mjs → cli-00fMnBFk.mjs} +4 -4
  50. package/dist/{cli-DSGw0Mw-.mjs.map → cli-00fMnBFk.mjs.map} +1 -1
  51. package/dist/{cli-OGss08bZ.cjs → cli-CYBb8rgx.cjs} +4 -4
  52. package/dist/{cli-OGss08bZ.cjs.map → cli-CYBb8rgx.cjs.map} +1 -1
  53. package/dist/{compose-QSBmhr4V.cjs → compose-D9ksPt5H.cjs} +11 -11
  54. package/dist/compose-D9ksPt5H.cjs.map +1 -0
  55. package/dist/{compose-BqTuzitb.cjs → compose-Dgd-yfJT.cjs} +8 -8
  56. package/dist/compose-Dgd-yfJT.cjs.map +1 -0
  57. package/dist/{compose-Csegtvq_.mjs → compose-MwgjPj_A.mjs} +12 -12
  58. package/dist/compose-MwgjPj_A.mjs.map +1 -0
  59. package/dist/{compose-RhuFQmZS.mjs → compose-rn_DWcup.mjs} +9 -9
  60. package/dist/compose-rn_DWcup.mjs.map +1 -0
  61. package/dist/config.cjs +2 -2
  62. package/dist/config.mjs +2 -2
  63. package/dist/{credentialSchemas-mz9QZTYh.mjs → credentialSchemas-BzJiK1nQ.mjs} +4 -4
  64. package/dist/credentialSchemas-BzJiK1nQ.mjs.map +1 -0
  65. package/dist/{credentialSchemas-BAklWDna.cjs → credentialSchemas-OVXofU-r.cjs} +3 -3
  66. package/dist/credentialSchemas-OVXofU-r.cjs.map +1 -0
  67. package/dist/{credentials-CORvhcrO.cjs → credentials-C6n_kdu4.cjs} +7 -7
  68. package/dist/{credentials-CORvhcrO.cjs.map → credentials-C6n_kdu4.cjs.map} +1 -1
  69. package/dist/{credentials-D4DUPPPP.mjs → credentials-kK0X754I.mjs} +7 -7
  70. package/dist/{credentials-D4DUPPPP.mjs.map → credentials-kK0X754I.mjs.map} +1 -1
  71. package/dist/{databases-CrKh5jw6.cjs → databases-CuTL1e7s.cjs} +3 -3
  72. package/dist/databases-CuTL1e7s.cjs.map +1 -0
  73. package/dist/{databases-C1qqNxTu.mjs → databases-zN-gEox0.mjs} +4 -4
  74. package/dist/databases-zN-gEox0.mjs.map +1 -0
  75. package/dist/deploy/public.cjs +12 -12
  76. package/dist/deploy/public.mjs +12 -12
  77. package/dist/{deploy-BwJ7uWXd.cjs → deploy-C1gf4bT-.cjs} +47 -45
  78. package/dist/deploy-C1gf4bT-.cjs.map +1 -0
  79. package/dist/{deploy-DDfnQm8l.mjs → deploy-CFuDCbTq.mjs} +48 -46
  80. package/dist/deploy-CFuDCbTq.mjs.map +1 -0
  81. package/dist/{destroy-nTNRfdy6.cjs → destroy-CMz0BPEe.cjs} +9 -9
  82. package/dist/{destroy-nTNRfdy6.cjs.map → destroy-CMz0BPEe.cjs.map} +1 -1
  83. package/dist/{destroy-DKt8S051.mjs → destroy-UTWZmaGn.mjs} +9 -9
  84. package/dist/{destroy-DKt8S051.mjs.map → destroy-UTWZmaGn.mjs.map} +1 -1
  85. package/dist/{discover-CRywE7yc.cjs → discover-39VKSE2i.cjs} +5 -5
  86. package/dist/discover-39VKSE2i.cjs.map +1 -0
  87. package/dist/{discover-DbDrCQ8h.mjs → discover-B_PDDaVj.mjs} +6 -6
  88. package/dist/discover-B_PDDaVj.mjs.map +1 -0
  89. package/dist/{docker-Ele34O8z.mjs → docker-BIuidyEB.mjs} +11 -11
  90. package/dist/docker-BIuidyEB.mjs.map +1 -0
  91. package/dist/{docker-Dy1ZJUzV.cjs → docker-BrdCdNwm.cjs} +10 -10
  92. package/dist/docker-BrdCdNwm.cjs.map +1 -0
  93. package/dist/{dokploy-BrfA2m5K.mjs → dokploy--ndQ72iu.mjs} +2 -2
  94. package/dist/{dokploy-BrfA2m5K.mjs.map → dokploy--ndQ72iu.mjs.map} +1 -1
  95. package/dist/{dokploy-DN2W1YIH.cjs → dokploy-D7ZChrtZ.cjs} +2 -2
  96. package/dist/{dokploy-DN2W1YIH.cjs.map → dokploy-D7ZChrtZ.cjs.map} +1 -1
  97. package/dist/{eas-CO3ogve5.mjs → eas-BCcpBC4k.mjs} +3 -3
  98. package/dist/{eas-CO3ogve5.mjs.map → eas-BCcpBC4k.mjs.map} +1 -1
  99. package/dist/{eas-BRBdxmwe.cjs → eas-DCvA907G.cjs} +3 -3
  100. package/dist/{eas-BRBdxmwe.cjs.map → eas-DCvA907G.cjs.map} +1 -1
  101. package/dist/{encryption-BZ1zgtF5.cjs → encryption-8TklMCh2.cjs} +4 -4
  102. package/dist/encryption-8TklMCh2.cjs.map +1 -0
  103. package/dist/{encryption-CHmfNBAy.mjs → encryption-C2LzfQp8.mjs} +5 -5
  104. package/dist/encryption-C2LzfQp8.mjs.map +1 -0
  105. package/dist/{engine-DewbDHOq.cjs → engine-BMoNLayn.cjs} +37 -37
  106. package/dist/engine-BMoNLayn.cjs.map +1 -0
  107. package/dist/{engine-B3Gmu8-O.mjs → engine-D-_nkxQL.mjs} +38 -38
  108. package/dist/engine-D-_nkxQL.mjs.map +1 -0
  109. package/dist/{github-DU3iEmJN.mjs → github-B_zfStMR.mjs} +8 -8
  110. package/dist/{github-DU3iEmJN.mjs.map → github-B_zfStMR.mjs.map} +1 -1
  111. package/dist/{github-DPNgIxdc.cjs → github-CZjNDPAp.cjs} +8 -8
  112. package/dist/{github-DPNgIxdc.cjs.map → github-CZjNDPAp.cjs.map} +1 -1
  113. package/dist/{googlePlay-KPHn9H2f.mjs → googlePlay-BcVRYMh4.mjs} +4 -4
  114. package/dist/{googlePlay-KPHn9H2f.mjs.map → googlePlay-BcVRYMh4.mjs.map} +1 -1
  115. package/dist/{googlePlay-C2jnPqYn.cjs → googlePlay-Btn0lut5.cjs} +4 -4
  116. package/dist/{googlePlay-C2jnPqYn.cjs.map → googlePlay-Btn0lut5.cjs.map} +1 -1
  117. package/dist/{iam-C2sf6AUi.cjs → iam-BoYPPNdM.cjs} +2 -2
  118. package/dist/{iam-C2sf6AUi.cjs.map → iam-BoYPPNdM.cjs.map} +1 -1
  119. package/dist/{iam-CW61VcT3.mjs → iam-ra1_Y405.mjs} +2 -2
  120. package/dist/{iam-CW61VcT3.mjs.map → iam-ra1_Y405.mjs.map} +1 -1
  121. package/dist/index.cjs +79 -79
  122. package/dist/index.cjs.map +1 -1
  123. package/dist/index.mjs +80 -80
  124. package/dist/index.mjs.map +1 -1
  125. package/dist/{local-CwR2DW6i.mjs → local-B9Vniy-F.mjs} +3 -3
  126. package/dist/{local-CwR2DW6i.mjs.map → local-B9Vniy-F.mjs.map} +1 -1
  127. package/dist/{local-BxjA0EXj.cjs → local-DxfqOu7A.cjs} +3 -3
  128. package/dist/{local-BxjA0EXj.cjs.map → local-DxfqOu7A.cjs.map} +1 -1
  129. package/dist/{migrate-B0a3WY4X.cjs → migrate-C1u7Tl7D.cjs} +7 -7
  130. package/dist/{migrate-B0a3WY4X.cjs.map → migrate-C1u7Tl7D.cjs.map} +1 -1
  131. package/dist/{migrate-CYtM1UBH.cjs → migrate-CcYfCpMe.cjs} +3 -3
  132. package/dist/{migrate-CYtM1UBH.cjs.map → migrate-CcYfCpMe.cjs.map} +1 -1
  133. package/dist/{migrate-vWy2CUoi.mjs → migrate-b5rcr4sw.mjs} +7 -7
  134. package/dist/{migrate-vWy2CUoi.mjs.map → migrate-b5rcr4sw.mjs.map} +1 -1
  135. package/dist/{migrate-DHWy64pc.mjs → migrate-blnmh2Tm.mjs} +3 -3
  136. package/dist/{migrate-DHWy64pc.mjs.map → migrate-blnmh2Tm.mjs.map} +1 -1
  137. package/dist/{notes-9bOfe08J.mjs → notes-CT1jNLDC.mjs} +13 -12
  138. package/dist/notes-CT1jNLDC.mjs.map +1 -0
  139. package/dist/{notes-DRdlsCYV.cjs → notes-Cw3JQ0Y_.cjs} +12 -11
  140. package/dist/notes-Cw3JQ0Y_.cjs.map +1 -0
  141. package/dist/openapi.cjs +3 -3
  142. package/dist/openapi.mjs +3 -3
  143. package/dist/{projectBucket-gIQUuhGm.cjs → projectBucket-8hJmCusk.cjs} +2 -2
  144. package/dist/{projectBucket-gIQUuhGm.cjs.map → projectBucket-8hJmCusk.cjs.map} +1 -1
  145. package/dist/{projectBucket-Cd7sEDhG.mjs → projectBucket-DJNi2yJL.mjs} +2 -2
  146. package/dist/{projectBucket-Cd7sEDhG.mjs.map → projectBucket-DJNi2yJL.mjs.map} +1 -1
  147. package/dist/{publish-DOxz4mxf.mjs → publish-CMaPsMsT.mjs} +2 -2
  148. package/dist/{publish-DOxz4mxf.mjs.map → publish-CMaPsMsT.mjs.map} +1 -1
  149. package/dist/{publish-BgDFx08y.cjs → publish-Dlb-rrc5.cjs} +2 -2
  150. package/dist/{publish-BgDFx08y.cjs.map → publish-Dlb-rrc5.cjs.map} +1 -1
  151. package/dist/{ready-BjFMu_1J.mjs → ready-COJHr1Yi.mjs} +9 -9
  152. package/dist/ready-COJHr1Yi.mjs.map +1 -0
  153. package/dist/{ready-eVMJIcWn.cjs → ready-DcD0SCnV.cjs} +8 -8
  154. package/dist/ready-DcD0SCnV.cjs.map +1 -0
  155. package/dist/reconcile/public.cjs +1 -1
  156. package/dist/reconcile/public.mjs +1 -1
  157. package/dist/{resolve-BhQd4IkT.cjs → resolve-BKn4TTn3.cjs} +4 -4
  158. package/dist/{resolve-BhQd4IkT.cjs.map → resolve-BKn4TTn3.cjs.map} +1 -1
  159. package/dist/{resolve-CdDyPOE8.mjs → resolve-DrFS2Ivb.mjs} +4 -4
  160. package/dist/{resolve-CdDyPOE8.mjs.map → resolve-DrFS2Ivb.mjs.map} +1 -1
  161. package/dist/{rollback-Brc-_HBJ.cjs → rollback-6ZeoByXd.cjs} +7 -7
  162. package/dist/{rollback-Brc-_HBJ.cjs.map → rollback-6ZeoByXd.cjs.map} +1 -1
  163. package/dist/{rollback-CLBKeSMl.mjs → rollback-B3lHgwkj.mjs} +7 -7
  164. package/dist/{rollback-CLBKeSMl.mjs.map → rollback-B3lHgwkj.mjs.map} +1 -1
  165. package/dist/{s3-CuLmr6Q9.cjs → s3-Cq1_F2J8.cjs} +3 -3
  166. package/dist/{s3-CuLmr6Q9.cjs.map → s3-Cq1_F2J8.cjs.map} +1 -1
  167. package/dist/{s3-D0BIG_ml.mjs → s3-DfAM0soB.mjs} +3 -3
  168. package/dist/{s3-D0BIG_ml.mjs.map → s3-DfAM0soB.mjs.map} +1 -1
  169. package/dist/sandbox/credentials-worker.cjs +2 -2
  170. package/dist/sandbox/credentials-worker.mjs +2 -2
  171. package/dist/sandbox/discover-worker.cjs +1 -1
  172. package/dist/sandbox/discover-worker.mjs +1 -1
  173. package/dist/sandbox/migrate-worker.cjs +2 -2
  174. package/dist/sandbox/migrate-worker.mjs +2 -2
  175. package/dist/{serverSetup-BMpzrB1y.cjs → serverSetup-DMNKsLKq.cjs} +6 -6
  176. package/dist/{serverSetup-BMpzrB1y.cjs.map → serverSetup-DMNKsLKq.cjs.map} +1 -1
  177. package/dist/{serverSetup-An1fE9nd.mjs → serverSetup-lZ7tYUZJ.mjs} +6 -6
  178. package/dist/{serverSetup-An1fE9nd.mjs.map → serverSetup-lZ7tYUZJ.mjs.map} +1 -1
  179. package/dist/{sniffer-9a8wQeeD.cjs → sniffer-CUImZsQL.cjs} +8 -8
  180. package/dist/{sniffer-9a8wQeeD.cjs.map → sniffer-CUImZsQL.cjs.map} +1 -1
  181. package/dist/{sniffer-BObBXR5q.mjs → sniffer-DcT9RrAj.mjs} +8 -8
  182. package/dist/{sniffer-BObBXR5q.mjs.map → sniffer-DcT9RrAj.mjs.map} +1 -1
  183. package/dist/{snsSubscriptions-BRmEdsks.cjs → snsSubscriptions-1lX1ze3u.cjs} +10 -5
  184. package/dist/snsSubscriptions-1lX1ze3u.cjs.map +1 -0
  185. package/dist/{snsSubscriptions-oUTOkG-s.mjs → snsSubscriptions-DFWhEgiA.mjs} +10 -5
  186. package/dist/snsSubscriptions-DFWhEgiA.mjs.map +1 -0
  187. package/dist/{sst-DVIeKWCH.mjs → sst-CB6rX5Zs.mjs} +6 -6
  188. package/dist/{sst-DVIeKWCH.mjs.map → sst-CB6rX5Zs.mjs.map} +1 -1
  189. package/dist/{sst-CJQI9GYW.cjs → sst-ct0Vhta9.cjs} +6 -6
  190. package/dist/{sst-CJQI9GYW.cjs.map → sst-ct0Vhta9.cjs.map} +1 -1
  191. package/dist/{stack-2jMvQfLo.cjs → stack-CkdkfmpN.cjs} +124 -47
  192. package/dist/stack-CkdkfmpN.cjs.map +1 -0
  193. package/dist/{stack-kcxH-2tZ.mjs → stack-Dsl0l3fi.mjs} +120 -49
  194. package/dist/stack-Dsl0l3fi.mjs.map +1 -0
  195. package/dist/{stage-AHgVG7H8.cjs → stage-Cmn0dCV2.cjs} +7 -7
  196. package/dist/{stage-AHgVG7H8.cjs.map → stage-Cmn0dCV2.cjs.map} +1 -1
  197. package/dist/{stage-BQSSMJL4.mjs → stage-DfdUf2sj.mjs} +7 -7
  198. package/dist/{stage-BQSSMJL4.mjs.map → stage-DfdUf2sj.mjs.map} +1 -1
  199. package/dist/{stages-DpF2K3PZ.cjs → stages-BWg3NU3J.cjs} +2 -2
  200. package/dist/{stages-DpF2K3PZ.cjs.map → stages-BWg3NU3J.cjs.map} +1 -1
  201. package/dist/{stages-BsK1Ro4s.mjs → stages-COiipV8N.mjs} +2 -2
  202. package/dist/{stages-BsK1Ro4s.mjs.map → stages-COiipV8N.mjs.map} +1 -1
  203. package/dist/target/public.cjs +1 -1
  204. package/dist/target/public.mjs +1 -1
  205. package/dist/{terminal-DWROY7JE.mjs → terminal-BDKhPIBA.mjs} +3 -3
  206. package/dist/{terminal-DWROY7JE.mjs.map → terminal-BDKhPIBA.mjs.map} +1 -1
  207. package/dist/{terminal-BNjNr7BN.cjs → terminal-CFeiyJxJ.cjs} +3 -3
  208. package/dist/{terminal-BNjNr7BN.cjs.map → terminal-CFeiyJxJ.cjs.map} +1 -1
  209. package/dist/vitest.cjs +1 -1
  210. package/dist/vitest.mjs +1 -1
  211. package/dist/workspace/index.cjs +1 -1
  212. package/dist/workspace/index.mjs +1 -1
  213. package/dist/{workspace-Ciw3SnME.cjs → workspace-CEpojAus.cjs} +42 -15
  214. package/dist/workspace-CEpojAus.cjs.map +1 -0
  215. package/dist/{workspace-9q4TSHlM.mjs → workspace-_aoe8v6u.mjs} +43 -16
  216. package/dist/workspace-_aoe8v6u.mjs.map +1 -0
  217. package/package.json +15 -15
  218. package/dist/SubscriberGenerator-BybB6uez.mjs.map +0 -1
  219. package/dist/SubscriberGenerator-mZpSuSU7.cjs.map +0 -1
  220. package/dist/add-DsxJ0Knr.cjs.map +0 -1
  221. package/dist/add-Dt8QKSOw.mjs.map +0 -1
  222. package/dist/apps-C6s-trVp.cjs.map +0 -1
  223. package/dist/apps-w2sRQKCr.mjs.map +0 -1
  224. package/dist/compose-BqTuzitb.cjs.map +0 -1
  225. package/dist/compose-Csegtvq_.mjs.map +0 -1
  226. package/dist/compose-QSBmhr4V.cjs.map +0 -1
  227. package/dist/compose-RhuFQmZS.mjs.map +0 -1
  228. package/dist/credentialSchemas-BAklWDna.cjs.map +0 -1
  229. package/dist/credentialSchemas-mz9QZTYh.mjs.map +0 -1
  230. package/dist/databases-C1qqNxTu.mjs.map +0 -1
  231. package/dist/databases-CrKh5jw6.cjs.map +0 -1
  232. package/dist/deploy-BwJ7uWXd.cjs.map +0 -1
  233. package/dist/deploy-DDfnQm8l.mjs.map +0 -1
  234. package/dist/discover-CRywE7yc.cjs.map +0 -1
  235. package/dist/discover-DbDrCQ8h.mjs.map +0 -1
  236. package/dist/docker-Dy1ZJUzV.cjs.map +0 -1
  237. package/dist/docker-Ele34O8z.mjs.map +0 -1
  238. package/dist/encryption-BZ1zgtF5.cjs.map +0 -1
  239. package/dist/encryption-CHmfNBAy.mjs.map +0 -1
  240. package/dist/engine-B3Gmu8-O.mjs.map +0 -1
  241. package/dist/engine-DewbDHOq.cjs.map +0 -1
  242. package/dist/notes-9bOfe08J.mjs.map +0 -1
  243. package/dist/notes-DRdlsCYV.cjs.map +0 -1
  244. package/dist/ready-BjFMu_1J.mjs.map +0 -1
  245. package/dist/ready-eVMJIcWn.cjs.map +0 -1
  246. package/dist/snsSubscriptions-BRmEdsks.cjs.map +0 -1
  247. package/dist/snsSubscriptions-oUTOkG-s.mjs.map +0 -1
  248. package/dist/stack-2jMvQfLo.cjs.map +0 -1
  249. package/dist/stack-kcxH-2tZ.mjs.map +0 -1
  250. package/dist/workspace-9q4TSHlM.mjs.map +0 -1
  251. package/dist/workspace-Ciw3SnME.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"googlePlay-C2jnPqYn.cjs","names":["GkmError","GkmError","join","gkmHome","spawn","GkmError","GkmError","createSign","join","existsSync","readFileSync","readdirSync","statSync","extname","GkmError","spawn","join","delimiter","canPrompt","loadWorkspaceConfig","loadStage","chooseMobileApp","mobileStage","existsSync","readFile","withStageProfiles","writeFile"],"sources":["../src/mobile/googlePlay/easApi.ts","../src/mobile/googlePlay/google.ts","../src/mobile/googlePlay/gcp.ts","../src/mobile/googlePlay/play.ts","../src/mobile/googlePlay/index.ts"],"sourcesContent":["/**\n * EAS, as `gkm deploy:google-play` reaches it: the GraphQL API eas-cli itself\n * calls, with an `EXPO_TOKEN` — to upload a Google service account key and\n * assign it to the app's Android credentials for EAS Submit, which is what\n * `eas credentials` does interactively.\n *\n * The documents are eas-cli's own (24.x), each selecting only what gkm reads:\n * eas-cli's credentials fragment also brings back the app's keystore and its\n * passwords, which gkm has no reason to hold.\n */\n\nimport { GkmError } from '../../errors';\n\nexport const EAS_GRAPHQL = 'https://api.expo.dev/graphql';\n\n/** No `EXPO_TOKEN` to call EAS with. */\nexport class ExpoTokenMissing extends GkmError {\n\tconstructor() {\n\t\tsuper(\n\t\t\t'gkm uploads the key to EAS with an access token, and EXPO_TOKEN is not ' +\n\t\t\t\t'set. Create one at https://expo.dev/settings/access-tokens and export ' +\n\t\t\t\t'it as EXPO_TOKEN.',\n\t\t);\n\t\tthis.name = 'ExpoTokenMissing';\n\t}\n}\n\n/** EAS refused a call. */\nexport class EasApiError extends GkmError {\n\tconstructor(\n\t\treadonly operation: string,\n\t\treadonly detail: string,\n\t) {\n\t\tsuper(`EAS refused ${operation}: ${detail}`);\n\t\tthis.name = 'EasApiError';\n\t}\n}\n\n/** A Google service account key, as EAS holds it. */\nexport interface EasGoogleKey {\n\tid: string;\n\tclientEmail: string;\n\tprivateKeyIdentifier: string;\n}\n\nconst KEY_FIELDS = 'id clientEmail privateKeyIdentifier';\n\nexport interface EasApi {\n\t/** The project's owner account. */\n\tproject(projectId: string): Promise<{\n\t\taccountId: string;\n\t\taccountName: string;\n\t\tfullName: string;\n\t}>;\n\t/** The app's Android credentials for a package, created when absent. */\n\tandroidCredentials(\n\t\tproject: { projectId: string; fullName: string },\n\t\tpackageName: string,\n\t): Promise<{ id: string; submissionsKey?: EasGoogleKey }>;\n\t/** Upload a key file's JSON to the account. */\n\tcreateKey(\n\t\taccountId: string,\n\t\tjson: Record<string, unknown>,\n\t): Promise<EasGoogleKey>;\n\t/** Make a key the one EAS Submit uses for the credentials. */\n\tuseForSubmissions(credentialsId: string, keyId: string): Promise<void>;\n\t/** Every key on the account. */\n\tkeys(accountName: string): Promise<EasGoogleKey[]>;\n\tdeleteKey(id: string): Promise<void>;\n}\n\nexport function easApi(\n\ttoken: string | undefined = process.env.EXPO_TOKEN,\n\tendpoint: string = EAS_GRAPHQL,\n): EasApi {\n\tconst call = async <T>(\n\t\toperation: string,\n\t\tquery: string,\n\t\tvariables: Record<string, unknown>,\n\t): Promise<T> => {\n\t\tif (!token) throw new ExpoTokenMissing();\n\t\tconst response = await fetch(endpoint, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {\n\t\t\t\tauthorization: `Bearer ${token}`,\n\t\t\t\t'content-type': 'application/json',\n\t\t\t},\n\t\t\tbody: JSON.stringify({ query, variables, operationName: operation }),\n\t\t});\n\t\tconst body = (await response.json().catch(() => ({}))) as {\n\t\t\tdata?: T;\n\t\t\terrors?: { message: string }[];\n\t\t};\n\t\tif (!response.ok || body.errors?.length || !body.data) {\n\t\t\tthrow new EasApiError(\n\t\t\t\toperation,\n\t\t\t\tbody.errors?.map((error) => error.message).join('; ') ||\n\t\t\t\t\t`HTTP ${response.status}`,\n\t\t\t);\n\t\t}\n\t\treturn body.data;\n\t};\n\n\tconst credentialsFields = `id googleServiceAccountKeyForSubmissions { ${KEY_FIELDS} }`;\n\ttype Credentials = {\n\t\tid: string;\n\t\tgoogleServiceAccountKeyForSubmissions: EasGoogleKey | null;\n\t};\n\tconst asCredentials = (credentials: Credentials) => ({\n\t\tid: credentials.id,\n\t\t...(credentials.googleServiceAccountKeyForSubmissions\n\t\t\t? { submissionsKey: credentials.googleServiceAccountKeyForSubmissions }\n\t\t\t: {}),\n\t});\n\n\treturn {\n\t\tasync project(projectId) {\n\t\t\tconst data = await call<{\n\t\t\t\tapp: {\n\t\t\t\t\tbyId: {\n\t\t\t\t\t\tfullName: string;\n\t\t\t\t\t\townerAccount: { id: string; name: string };\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t}>(\n\t\t\t\t'AppByIdQuery',\n\t\t\t\t`query AppByIdQuery($appId: String!) {\n app { byId(appId: $appId) { id fullName ownerAccount { id name } } }\n}`,\n\t\t\t\t{ appId: projectId },\n\t\t\t);\n\t\t\tconst app = data.app.byId;\n\t\t\treturn {\n\t\t\t\taccountId: app.ownerAccount.id,\n\t\t\t\taccountName: app.ownerAccount.name,\n\t\t\t\tfullName: app.fullName,\n\t\t\t};\n\t\t},\n\n\t\tasync androidCredentials(project, packageName) {\n\t\t\tconst found = await call<{\n\t\t\t\tapp: { byFullName: { androidAppCredentials: Credentials[] } };\n\t\t\t}>(\n\t\t\t\t'AndroidAppCredentialsByApplicationIdentifierQuery',\n\t\t\t\t`query AndroidAppCredentialsByApplicationIdentifierQuery(\n $projectFullName: String!\n $applicationIdentifier: String\n $legacyOnly: Boolean\n) {\n app {\n byFullName(fullName: $projectFullName) {\n id\n androidAppCredentials(\n filter: { applicationIdentifier: $applicationIdentifier, legacyOnly: $legacyOnly }\n ) { ${credentialsFields} }\n }\n }\n}`,\n\t\t\t\t{\n\t\t\t\t\tprojectFullName: project.fullName,\n\t\t\t\t\tapplicationIdentifier: packageName,\n\t\t\t\t\tlegacyOnly: false,\n\t\t\t\t},\n\t\t\t);\n\t\t\tconst existing = found.app.byFullName.androidAppCredentials[0];\n\t\t\tif (existing) return asCredentials(existing);\n\n\t\t\tconst created = await call<{\n\t\t\t\tandroidAppCredentials: { createAndroidAppCredentials: Credentials };\n\t\t\t}>(\n\t\t\t\t'CreateAndroidAppCredentialsMutation',\n\t\t\t\t`mutation CreateAndroidAppCredentialsMutation(\n $androidAppCredentialsInput: AndroidAppCredentialsInput!\n $appId: ID!\n $applicationIdentifier: String!\n) {\n androidAppCredentials {\n createAndroidAppCredentials(\n androidAppCredentialsInput: $androidAppCredentialsInput\n appId: $appId\n applicationIdentifier: $applicationIdentifier\n ) { ${credentialsFields} }\n }\n}`,\n\t\t\t\t{\n\t\t\t\t\tandroidAppCredentialsInput: {},\n\t\t\t\t\tappId: project.projectId,\n\t\t\t\t\tapplicationIdentifier: packageName,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn asCredentials(\n\t\t\t\tcreated.androidAppCredentials.createAndroidAppCredentials,\n\t\t\t);\n\t\t},\n\n\t\tasync createKey(accountId, json) {\n\t\t\tconst data = await call<{\n\t\t\t\tgoogleServiceAccountKey: {\n\t\t\t\t\tcreateGoogleServiceAccountKey: EasGoogleKey;\n\t\t\t\t};\n\t\t\t}>(\n\t\t\t\t'CreateGoogleServiceAccountKeyMutation',\n\t\t\t\t`mutation CreateGoogleServiceAccountKeyMutation(\n $googleServiceAccountKeyInput: GoogleServiceAccountKeyInput!\n $accountId: ID!\n) {\n googleServiceAccountKey {\n createGoogleServiceAccountKey(\n googleServiceAccountKeyInput: $googleServiceAccountKeyInput\n accountId: $accountId\n ) { ${KEY_FIELDS} }\n }\n}`,\n\t\t\t\t{ googleServiceAccountKeyInput: { jsonKey: json }, accountId },\n\t\t\t);\n\t\t\treturn data.googleServiceAccountKey.createGoogleServiceAccountKey;\n\t\t},\n\n\t\tasync useForSubmissions(credentialsId, keyId) {\n\t\t\tawait call(\n\t\t\t\t'SetGoogleServiceAccountKeyForSubmissionsMutation',\n\t\t\t\t`mutation SetGoogleServiceAccountKeyForSubmissionsMutation(\n $androidAppCredentialsId: ID!\n $googleServiceAccountKeyId: ID!\n) {\n androidAppCredentials {\n setGoogleServiceAccountKeyForSubmissions(\n id: $androidAppCredentialsId\n googleServiceAccountKeyId: $googleServiceAccountKeyId\n ) { id }\n }\n}`,\n\t\t\t\t{\n\t\t\t\t\tandroidAppCredentialsId: credentialsId,\n\t\t\t\t\tgoogleServiceAccountKeyId: keyId,\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\n\t\tasync keys(accountName) {\n\t\t\tconst keys: EasGoogleKey[] = [];\n\t\t\tlet after: string | null = null;\n\t\t\tdo {\n\t\t\t\tconst data: {\n\t\t\t\t\taccount: {\n\t\t\t\t\t\tbyName: {\n\t\t\t\t\t\t\tgoogleServiceAccountKeysPaginated: {\n\t\t\t\t\t\t\t\tedges: { node: EasGoogleKey }[];\n\t\t\t\t\t\t\t\tpageInfo: { hasNextPage: boolean; endCursor: string | null };\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} = await call(\n\t\t\t\t\t'GoogleServiceAccountKeysPaginatedByAccountQuery',\n\t\t\t\t\t`query GoogleServiceAccountKeysPaginatedByAccountQuery(\n $accountName: String!\n $after: String\n $first: Int\n) {\n account {\n byName(accountName: $accountName) {\n id\n googleServiceAccountKeysPaginated(after: $after, first: $first) {\n edges { node { ${KEY_FIELDS} } }\n pageInfo { hasNextPage endCursor }\n }\n }\n }\n}`,\n\t\t\t\t\t{ accountName, after, first: 50 },\n\t\t\t\t);\n\t\t\t\tconst page = data.account.byName.googleServiceAccountKeysPaginated;\n\t\t\t\tkeys.push(...page.edges.map((edge) => edge.node));\n\t\t\t\tafter = page.pageInfo.hasNextPage ? page.pageInfo.endCursor : null;\n\t\t\t} while (after);\n\t\t\treturn keys;\n\t\t},\n\n\t\tasync deleteKey(id) {\n\t\t\tawait call(\n\t\t\t\t'DeleteGoogleServiceAccountKeyMutation',\n\t\t\t\t`mutation DeleteGoogleServiceAccountKeyMutation($googleServiceAccountKeyId: ID!) {\n googleServiceAccountKey { deleteGoogleServiceAccountKey(id: $googleServiceAccountKeyId) { id } }\n}`,\n\t\t\t\t{ googleServiceAccountKeyId: id },\n\t\t\t);\n\t\t},\n\t};\n}\n","/**\n * Google, as `gkm deploy:google-play` reaches it: a token for the person\n * running it, and the Cloud APIs that make a project, a service account and\n * its key.\n *\n * The token is gcloud's own application-default credential, with the\n * `cloud-platform` and `androidpublisher` scopes — no OAuth client of gkm's —\n * kept in gkm's own gcloud config (`<gkm home>/gcloud`), so the person's own\n * gcloud setup is never read or changed. Every call carries the project as\n * its quota project (`x-goog-user-project`), which the Play Developer API\n * requires of a user credential.\n */\n\nimport { spawn } from 'node:child_process';\nimport { join } from 'node:path';\nimport { GkmError } from '../../errors';\nimport { gkmHome } from '../../home.js';\n\n/** The scopes the sign-in asks for. */\nexport const GOOGLE_SCOPES = [\n\t'https://www.googleapis.com/auth/cloud-platform',\n\t'https://www.googleapis.com/auth/androidpublisher',\n];\n\n/** `gcloud` is not installed. */\nexport class GcloudMissing extends GkmError {\n\tconstructor() {\n\t\tsuper(\n\t\t\t'gkm signs in to Google with gcloud, and there is no `gcloud` here. ' +\n\t\t\t\t'Install the Google Cloud CLI: https://cloud.google.com/sdk/docs/install.',\n\t\t);\n\t\tthis.name = 'GcloudMissing';\n\t}\n}\n\n/** Not signed in, and no terminal to sign in from. */\nexport class GoogleSignInRequired extends GkmError {\n\tconstructor(readonly config: string) {\n\t\tsuper(\n\t\t\t'Signing in to Google opens a browser, and this run has no terminal. ' +\n\t\t\t\t'Run it once where you can sign in, as a Play Console admin: ' +\n\t\t\t\t`CLOUDSDK_CONFIG=${config} gcloud auth application-default login ` +\n\t\t\t\t`--scopes=${GOOGLE_SCOPES.join(',')}.`,\n\t\t);\n\t\tthis.name = 'GoogleSignInRequired';\n\t}\n}\n\n/** A Google API refused a call. */\nexport class GoogleApiError extends GkmError {\n\tconstructor(\n\t\treadonly method: string,\n\t\treadonly url: string,\n\t\treadonly status: number,\n\t\treadonly detail: string,\n\t) {\n\t\tsuper(`Google answered ${status} to ${method} ${url}: ${detail}`);\n\t\tthis.name = 'GoogleApiError';\n\t}\n}\n\n/** A long-running Google operation did not finish in time. */\nexport class GoogleOperationTimedOut extends GkmError {\n\tconstructor(readonly operation: string) {\n\t\tsuper(\n\t\t\t`Google's operation ${operation} had not finished after a minute. ` +\n\t\t\t\t'Run the command again: what it finished is kept.',\n\t\t);\n\t\tthis.name = 'GoogleOperationTimedOut';\n\t}\n}\n\n/** Where gkm keeps its gcloud sign-in. */\nexport function gcloudConfig(env: NodeJS.ProcessEnv = process.env): string {\n\treturn join(gkmHome(env), 'gcloud');\n}\n\n/** How a token is had: the real one runs gcloud. */\nexport interface GoogleSignIn {\n\t/** An access token for the signed-in person, signing in if allowed. */\n\ttoken(options: { interactive: boolean }): Promise<string>;\n}\n\nfunction gcloud(\n\targs: readonly string[],\n\tconfig: string,\n\tinherit: boolean,\n): Promise<{ code: number | null; stdout: string }> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = spawn('gcloud', [...args], {\n\t\t\tstdio: [\n\t\t\t\t'inherit',\n\t\t\t\tinherit ? 'inherit' : 'pipe',\n\t\t\t\tinherit ? 'inherit' : 'pipe',\n\t\t\t],\n\t\t\tenv: { ...process.env, CLOUDSDK_CONFIG: config },\n\t\t});\n\t\tlet stdout = '';\n\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\tstdout += chunk.toString();\n\t\t});\n\t\tchild.on('error', (error: NodeJS.ErrnoException) =>\n\t\t\treject(error.code === 'ENOENT' ? new GcloudMissing() : error),\n\t\t);\n\t\tchild.on('close', (code) => resolve({ code, stdout }));\n\t});\n}\n\n/** gcloud's application-default credential, in gkm's own gcloud config. */\nexport function gcloudSignIn(config: string = gcloudConfig()): GoogleSignIn {\n\treturn {\n\t\tasync token({ interactive }) {\n\t\t\tconst print = () =>\n\t\t\t\tgcloud(\n\t\t\t\t\t['auth', 'application-default', 'print-access-token'],\n\t\t\t\t\tconfig,\n\t\t\t\t\tfalse,\n\t\t\t\t);\n\t\t\tlet printed = await print();\n\t\t\tif (printed.code !== 0) {\n\t\t\t\tif (!interactive) throw new GoogleSignInRequired(config);\n\t\t\t\tawait gcloud(\n\t\t\t\t\t[\n\t\t\t\t\t\t'auth',\n\t\t\t\t\t\t'application-default',\n\t\t\t\t\t\t'login',\n\t\t\t\t\t\t`--scopes=${GOOGLE_SCOPES.join(',')}`,\n\t\t\t\t\t],\n\t\t\t\t\tconfig,\n\t\t\t\t\ttrue,\n\t\t\t\t);\n\t\t\t\tprinted = await print();\n\t\t\t\tif (printed.code !== 0) throw new GoogleSignInRequired(config);\n\t\t\t}\n\t\t\treturn printed.stdout.trim();\n\t\t},\n\t};\n}\n\n/** One authenticated Google API caller, for one quota project. */\nexport interface GoogleClient {\n\trequest<T>(\n\t\tmethod: string,\n\t\turl: string,\n\t\tbody?: unknown,\n\t\toptions?: { raw?: { contentType: string; data: Uint8Array } },\n\t): Promise<T>;\n}\n\nexport function googleClient(\n\ttoken: string,\n\tquotaProject?: string,\n): GoogleClient {\n\treturn {\n\t\tasync request(method, url, body, options) {\n\t\t\tconst headers: Record<string, string> = {\n\t\t\t\tauthorization: `Bearer ${token}`,\n\t\t\t\t...(quotaProject ? { 'x-goog-user-project': quotaProject } : {}),\n\t\t\t};\n\t\t\tlet payload: string | Uint8Array | undefined;\n\t\t\tif (options?.raw) {\n\t\t\t\theaders['content-type'] = options.raw.contentType;\n\t\t\t\tpayload = options.raw.data;\n\t\t\t} else if (body !== undefined) {\n\t\t\t\theaders['content-type'] = 'application/json';\n\t\t\t\tpayload = JSON.stringify(body);\n\t\t\t}\n\t\t\tconst response = await fetch(url, {\n\t\t\t\tmethod,\n\t\t\t\theaders,\n\t\t\t\t...(payload !== undefined ? { body: payload } : {}),\n\t\t\t});\n\t\t\tconst text = await response.text();\n\t\t\tif (!response.ok) {\n\t\t\t\tlet detail = text;\n\t\t\t\ttry {\n\t\t\t\t\tconst parsed = JSON.parse(text) as { error?: { message?: string } };\n\t\t\t\t\tdetail = parsed.error?.message ?? text;\n\t\t\t\t} catch {\n\t\t\t\t\t// Not JSON: the text is the detail.\n\t\t\t\t}\n\t\t\t\tthrow new GoogleApiError(method, url, response.status, detail);\n\t\t\t}\n\t\t\treturn (text ? JSON.parse(text) : {}) as never;\n\t\t},\n\t};\n}\n\n/** A long-running operation, polled until it is done. */\nexport async function finished(\n\tclient: GoogleClient,\n\tbase: string,\n\toperation: { name?: string; done?: boolean; error?: { message?: string } },\n\toptions: { intervalMs?: number; attempts?: number } = {},\n): Promise<void> {\n\tlet current = operation;\n\tfor (let attempt = 0; !current.done; attempt++) {\n\t\tif (attempt >= (options.attempts ?? 30)) {\n\t\t\tthrow new GoogleOperationTimedOut(current.name ?? '(unnamed)');\n\t\t}\n\t\tawait new Promise((resolve) =>\n\t\t\tsetTimeout(resolve, options.intervalMs ?? 2_000),\n\t\t);\n\t\tcurrent = await client.request('GET', `${base}/${current.name}`);\n\t}\n\tif (current.error) {\n\t\tthrow new GoogleApiError(\n\t\t\t'GET',\n\t\t\t`${base}/${current.name}`,\n\t\t\t500,\n\t\t\tcurrent.error.message ?? 'the operation failed',\n\t\t);\n\t}\n}\n","/**\n * The Google Cloud side of publishing to Play: a project with the Android\n * Publisher API on, and a service account in it whose JSON key EAS Submit\n * uses. Each step finds what is there before it creates anything, so a\n * second run reuses the project and the account and only makes a new key.\n */\n\nimport { GkmError } from '../../errors';\nimport { finished, GoogleApiError, type GoogleClient } from './google.js';\n\nexport const CLOUD_RESOURCE_MANAGER =\n\t'https://cloudresourcemanager.googleapis.com/v3';\nexport const SERVICE_USAGE = 'https://serviceusage.googleapis.com/v1';\nexport const IAM = 'https://iam.googleapis.com/v1';\n\n/** The API EAS Submit and gkm call Play through. */\nexport const ANDROID_PUBLISHER_API = 'androidpublisher.googleapis.com';\n\n/** A project id or service account id gkm would derive is not a valid one. */\nexport class GoogleIdInvalid extends GkmError {\n\tconstructor(\n\t\treadonly kind: 'project' | 'service account',\n\t\treadonly id: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${id}' is not a valid Google ${kind} id: 6 to 30 lowercase letters, ` +\n\t\t\t\t'digits and hyphens, starting with a letter and not ending in a hyphen. ' +\n\t\t\t\t(kind === 'project' ? 'Name one with --project.' : ''),\n\t\t);\n\t\tthis.name = 'GoogleIdInvalid';\n\t}\n}\n\n/** The project could not be created — most often, its id is someone else's. */\nexport class GoogleProjectUnavailable extends GkmError {\n\tconstructor(\n\t\treadonly project: string,\n\t\treadonly detail: string,\n\t) {\n\t\tsuper(\n\t\t\t`Could not create the Google Cloud project '${project}' (${detail}). ` +\n\t\t\t\t'Project ids are global: name another, or one you already have, with --project.',\n\t\t);\n\t\tthis.name = 'GoogleProjectUnavailable';\n\t}\n}\n\nconst ID = /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/;\n\n/**\n * An id Google accepts, from a workspace's name: `shop` → `shop-play`.\n * Lowercased, anything else made a hyphen, cut to 30.\n */\nexport function playId(workspace: string): string {\n\tconst base = workspace\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9]+/g, '-')\n\t\t.replace(/^[^a-z]+|-+$/g, '');\n\treturn `${base.slice(0, 25).replace(/-+$/, '')}-play`;\n}\n\n/** Throws unless `id` is a valid project or service account id. */\nexport function assertGoogleId(\n\tkind: 'project' | 'service account',\n\tid: string,\n): void {\n\tif (!ID.test(id)) throw new GoogleIdInvalid(kind, id);\n}\n\n/**\n * The project, created when it is not there. Answers whether it was made.\n *\n * @throws {GoogleProjectUnavailable}\n */\nexport async function ensureProject(\n\tclient: GoogleClient,\n\tproject: string,\n\tdisplayName: string,\n\toptions: { intervalMs?: number } = {},\n): Promise<boolean> {\n\tassertGoogleId('project', project);\n\ttry {\n\t\tawait client.request(\n\t\t\t'GET',\n\t\t\t`${CLOUD_RESOURCE_MANAGER}/projects/${project}`,\n\t\t);\n\t\treturn false;\n\t} catch (error) {\n\t\t// Absent, or not ours to see — either way, try to create it.\n\t\tif (\n\t\t\t!(error instanceof GoogleApiError) ||\n\t\t\t![403, 404].includes(error.status)\n\t\t) {\n\t\t\tthrow error;\n\t\t}\n\t}\n\ttry {\n\t\tconst operation = await client.request<{ name?: string; done?: boolean }>(\n\t\t\t'POST',\n\t\t\t`${CLOUD_RESOURCE_MANAGER}/projects`,\n\t\t\t{ projectId: project, displayName: displayName.slice(0, 30) },\n\t\t);\n\t\tawait finished(client, CLOUD_RESOURCE_MANAGER, operation, options);\n\t} catch (error) {\n\t\tif (error instanceof GoogleApiError) {\n\t\t\tthrow new GoogleProjectUnavailable(project, error.detail);\n\t\t}\n\t\tthrow error;\n\t}\n\treturn true;\n}\n\n/** The Android Publisher API, on in the project. */\nexport async function enablePublisherApi(\n\tclient: GoogleClient,\n\tproject: string,\n\toptions: { intervalMs?: number } = {},\n): Promise<void> {\n\tconst operation = await client.request<{ name?: string; done?: boolean }>(\n\t\t'POST',\n\t\t`${SERVICE_USAGE}/projects/${project}/services/${ANDROID_PUBLISHER_API}:enable`,\n\t\t{},\n\t);\n\tawait finished(client, SERVICE_USAGE, operation, options);\n}\n\n/** The service account's email, which is what Play and EAS know it by. */\nexport function serviceAccountEmail(project: string, account: string): string {\n\treturn `${account}@${project}.iam.gserviceaccount.com`;\n}\n\n/** The service account, created when it is not there. Answers its email. */\nexport async function ensureServiceAccount(\n\tclient: GoogleClient,\n\tproject: string,\n\taccount: string,\n\tdisplayName: string,\n): Promise<string> {\n\tassertGoogleId('service account', account);\n\tconst email = serviceAccountEmail(project, account);\n\ttry {\n\t\tawait client.request(\n\t\t\t'GET',\n\t\t\t`${IAM}/projects/${project}/serviceAccounts/${email}`,\n\t\t);\n\t\treturn email;\n\t} catch (error) {\n\t\tif (!(error instanceof GoogleApiError) || error.status !== 404) throw error;\n\t}\n\tawait client.request('POST', `${IAM}/projects/${project}/serviceAccounts`, {\n\t\taccountId: account,\n\t\tserviceAccount: { displayName: displayName.slice(0, 100) },\n\t});\n\treturn email;\n}\n\n/** A service account key: its id, and — only when just made — its JSON. */\nexport interface ServiceAccountKey {\n\t/** `projects/<p>/serviceAccounts/<email>/keys/<id>`. */\n\tname: string;\n\t/** The key file's JSON, held in memory and never written anywhere. */\n\tjson?: string;\n}\n\n/** A new key for the account. Its JSON exists only in what this returns. */\nexport async function createKey(\n\tclient: GoogleClient,\n\tproject: string,\n\temail: string,\n): Promise<ServiceAccountKey & { json: string }> {\n\tconst key = await client.request<{ name: string; privateKeyData: string }>(\n\t\t'POST',\n\t\t`${IAM}/projects/${project}/serviceAccounts/${email}/keys`,\n\t\t{},\n\t);\n\treturn {\n\t\tname: key.name,\n\t\tjson: Buffer.from(key.privateKeyData, 'base64').toString('utf8'),\n\t};\n}\n\n/** The account's keys that someone made — not Google's own. */\nexport async function listKeys(\n\tclient: GoogleClient,\n\tproject: string,\n\temail: string,\n): Promise<ServiceAccountKey[]> {\n\tconst { keys = [] } = await client.request<{ keys?: { name: string }[] }>(\n\t\t'GET',\n\t\t`${IAM}/projects/${project}/serviceAccounts/${email}/keys?keyTypes=USER_MANAGED`,\n\t);\n\treturn keys.map(({ name }) => ({ name }));\n}\n\nexport async function deleteKey(\n\tclient: GoogleClient,\n\tkey: ServiceAccountKey,\n): Promise<void> {\n\tawait client.request('DELETE', `${IAM}/${key.name}`);\n}\n\n/** A key's id: the last part of its name. */\nexport function keyId(key: Pick<ServiceAccountKey, 'name'>): string {\n\treturn key.name.split('/').pop()!;\n}\n","/**\n * Play Console, through the Play Developer API (androidpublisher v3): the\n * service account's access to the app, the store listing as code, and a\n * check that the new key can act on the app.\n */\n\nimport { createSign } from 'node:crypto';\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';\nimport { extname, join } from 'node:path';\nimport type { PlayTrack } from '@geekmidas/manifest';\nimport { GkmError } from '../../errors';\nimport { GoogleApiError, type GoogleClient, googleClient } from './google.js';\n\nexport const PLAY =\n\t'https://androidpublisher.googleapis.com/androidpublisher/v3';\nexport const PLAY_UPLOAD =\n\t'https://androidpublisher.googleapis.com/upload/androidpublisher/v3';\n\n/** What Play answers about a package no app in the account has. */\nconst PACKAGE_MISSING = /packages are not available/i;\n\n/** The app is not in Play Console yet, and Play has no API that makes one. */\nexport class PlayAppMissing extends GkmError {\n\tconstructor(\n\t\treadonly packageName: string,\n\t\treadonly developer: string,\n\t) {\n\t\tsuper(\n\t\t\t`Play Console has no app '${packageName}', and Play has no API that ` +\n\t\t\t\t`creates one. Create it at https://play.google.com/console/developers/` +\n\t\t\t\t`${developer}/create-new-app, with ${packageName} as its package, then ` +\n\t\t\t\t'run this again.',\n\t\t);\n\t\tthis.name = 'PlayAppMissing';\n\t}\n}\n\n/** The new key could not open an edit on the app. */\nexport class PlayKeyUnverified extends GkmError {\n\tconstructor(\n\t\treadonly email: string,\n\t\treadonly detail: string,\n\t) {\n\t\tsuper(\n\t\t\t`The new key for ${email} could not open an edit on the app (${detail}). ` +\n\t\t\t\t'Its access can take a few minutes to reach Play: run this again shortly.',\n\t\t);\n\t\tthis.name = 'PlayKeyUnverified';\n\t}\n}\n\n/**\n * The app-level permissions the service account needs: releasing to the\n * testing tracks, to production only where a stage submits there, and the\n * store listing where the workspace keeps one.\n */\nexport function playPermissions(options: {\n\ttracks: readonly PlayTrack[];\n\tlisting: boolean;\n}): string[] {\n\treturn [\n\t\t'CAN_MANAGE_TRACK_APKS',\n\t\t...(options.tracks.includes('production')\n\t\t\t? ['CAN_MANAGE_PUBLIC_APKS']\n\t\t\t: []),\n\t\t...(options.listing ? ['CAN_MANAGE_PUBLIC_LISTING'] : []),\n\t].sort();\n}\n\ninterface PlayUser {\n\temail: string;\n\tgrants?: { packageName: string; appLevelPermissions?: string[] }[];\n}\n\n/**\n * The service account in Play Console with exactly `permissions` on the\n * app: invited with the grant in one call — Play refuses a user with no\n * permission, and a grant for a user not yet there — and, already there,\n * its grant made what it should be. Answers what changed.\n *\n * @throws {PlayAppMissing}\n */\nexport async function ensurePlayAccess(\n\tclient: GoogleClient,\n\toptions: {\n\t\tdeveloper: string;\n\t\temail: string;\n\t\tpackageName: string;\n\t\tpermissions: readonly string[];\n\t},\n): Promise<'invited' | 'granted' | 'updated' | 'unchanged'> {\n\tconst { developer, email, packageName } = options;\n\tconst permissions = [...options.permissions].sort();\n\tconst users = `${PLAY}/developers/${developer}/users`;\n\tconst missing = (error: unknown) =>\n\t\terror instanceof GoogleApiError && PACKAGE_MISSING.test(error.detail)\n\t\t\t? new PlayAppMissing(packageName, developer)\n\t\t\t: error;\n\n\t// Listing takes no paging: Play says \"Pagination is not currently\n\t// available\" unless asked for every user at once.\n\tconst { users: listed = [] } = await client.request<{ users?: PlayUser[] }>(\n\t\t'GET',\n\t\t`${users}?pageSize=-1`,\n\t);\n\tconst user = listed.find((candidate) => candidate.email === email);\n\n\tif (!user) {\n\t\tawait client\n\t\t\t.request('POST', users, {\n\t\t\t\temail,\n\t\t\t\tgrants: [{ packageName, appLevelPermissions: permissions }],\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tthrow missing(error);\n\t\t\t});\n\t\treturn 'invited';\n\t}\n\n\tconst grant = user.grants?.find((g) => g.packageName === packageName);\n\tconst grantPath = `${users}/${encodeURIComponent(email)}/grants`;\n\tif (!grant) {\n\t\tawait client\n\t\t\t.request('POST', grantPath, {\n\t\t\t\tpackageName,\n\t\t\t\tappLevelPermissions: permissions,\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tthrow missing(error);\n\t\t\t});\n\t\treturn 'granted';\n\t}\n\tconst had = [...(grant.appLevelPermissions ?? [])].sort();\n\tif (had.join() === permissions.join()) return 'unchanged';\n\tawait client.request(\n\t\t'PATCH',\n\t\t`${grantPath}/${packageName}?updateMask=appLevelPermissions`,\n\t\t{ appLevelPermissions: permissions },\n\t);\n\treturn 'updated';\n}\n\n/** A service account key file, as Google writes it. */\nexport interface ServiceAccountJson {\n\tclient_email: string;\n\tprivate_key: string;\n\ttoken_uri?: string;\n}\n\n/** An access token for the key itself: a signed JWT, exchanged. */\nexport async function keyToken(key: ServiceAccountJson): Promise<string> {\n\tconst tokenUri = key.token_uri ?? 'https://oauth2.googleapis.com/token';\n\tconst now = Math.floor(Date.now() / 1000);\n\tconst encode = (value: object) =>\n\t\tBuffer.from(JSON.stringify(value)).toString('base64url');\n\tconst unsigned = `${encode({ alg: 'RS256', typ: 'JWT' })}.${encode({\n\t\tiss: key.client_email,\n\t\tscope: 'https://www.googleapis.com/auth/androidpublisher',\n\t\taud: tokenUri,\n\t\tiat: now,\n\t\texp: now + 600,\n\t})}`;\n\tconst signature = createSign('RSA-SHA256')\n\t\t.update(unsigned)\n\t\t.sign(key.private_key)\n\t\t.toString('base64url');\n\tconst response = await fetch(tokenUri, {\n\t\tmethod: 'POST',\n\t\theaders: { 'content-type': 'application/x-www-form-urlencoded' },\n\t\tbody: new URLSearchParams({\n\t\t\tgrant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',\n\t\t\tassertion: `${unsigned}.${signature}`,\n\t\t}),\n\t});\n\tconst body = (await response.json().catch(() => ({}))) as {\n\t\taccess_token?: string;\n\t\terror_description?: string;\n\t};\n\tif (!response.ok || !body.access_token) {\n\t\tthrow new PlayKeyUnverified(\n\t\t\tkey.client_email,\n\t\t\tbody.error_description ?? `token exchange answered ${response.status}`,\n\t\t);\n\t}\n\treturn body.access_token;\n}\n\n/**\n * Proof the key and its grant work: as the key, open an edit on the app and\n * discard it — what EAS Submit's first call is.\n *\n * @throws {PlayKeyUnverified}\n */\nexport async function verifyKey(\n\tkey: ServiceAccountJson,\n\tpackageName: string,\n): Promise<void> {\n\tconst client = googleClient(await keyToken(key));\n\ttry {\n\t\tconst edit = await client.request<{ id: string }>(\n\t\t\t'POST',\n\t\t\t`${PLAY}/applications/${packageName}/edits`,\n\t\t\t{},\n\t\t);\n\t\tawait client.request(\n\t\t\t'DELETE',\n\t\t\t`${PLAY}/applications/${packageName}/edits/${edit.id}`,\n\t\t);\n\t} catch (error) {\n\t\tif (error instanceof GoogleApiError) {\n\t\t\tthrow new PlayKeyUnverified(key.client_email, error.detail);\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/** The image kinds Play's listing takes, as fastlane supply names them. */\nconst IMAGE_TYPES = [\n\t'icon',\n\t'featureGraphic',\n\t'promoGraphic',\n\t'tvBanner',\n\t'phoneScreenshots',\n\t'sevenInchScreenshots',\n\t'tenInchScreenshots',\n\t'tvScreenshots',\n\t'wearScreenshots',\n] as const;\n\n/** One locale's listing, read from `store/play/listings/<locale>/`. */\nexport interface PlayListing {\n\tlanguage: string;\n\ttitle?: string;\n\tshortDescription?: string;\n\tfullDescription?: string;\n\tvideo?: string;\n\t/** Each image kind's files, in order. */\n\timages: Partial<Record<(typeof IMAGE_TYPES)[number], string[]>>;\n}\n\n/** The store listing kept beside the app, in fastlane supply's layout. */\nexport interface PlayStore {\n\tlistings: PlayListing[];\n\t/** `store/play/data-safety.csv`: Play Console's data safety export. */\n\tdataSafety?: string;\n}\n\n/**\n * `<app>/store/play`, read: undefined where there is none.\n *\n * ```\n * store/play/\n * data-safety.csv\n * listings/en-US/title.txt, short_description.txt, full_description.txt, video.txt\n * listings/en-US/images/icon.png, featureGraphic.png\n * listings/en-US/images/phoneScreenshots/1.png, 2.png …\n * ```\n */\nexport function readPlayStore(appDir: string): PlayStore | undefined {\n\tconst root = join(appDir, 'store', 'play');\n\tif (!existsSync(root)) return undefined;\n\tconst text = (path: string) =>\n\t\texistsSync(path) ? readFileSync(path, 'utf8').trim() : undefined;\n\n\tconst listings: PlayListing[] = [];\n\tconst listingsDir = join(root, 'listings');\n\tfor (const language of existsSync(listingsDir)\n\t\t? readdirSync(listingsDir).sort()\n\t\t: []) {\n\t\tconst dir = join(listingsDir, language);\n\t\tif (!statSync(dir).isDirectory()) continue;\n\t\tconst images: PlayListing['images'] = {};\n\t\tconst imagesDir = join(dir, 'images');\n\t\tfor (const type of IMAGE_TYPES) {\n\t\t\tconst single = ['.png', '.jpg', '.jpeg']\n\t\t\t\t.map((ext) => join(imagesDir, `${type}${ext}`))\n\t\t\t\t.find(existsSync);\n\t\t\tconst many = join(imagesDir, type);\n\t\t\tconst files = single\n\t\t\t\t? [single]\n\t\t\t\t: existsSync(many)\n\t\t\t\t\t? readdirSync(many)\n\t\t\t\t\t\t\t.filter((f) => /\\.(png|jpe?g)$/i.test(f))\n\t\t\t\t\t\t\t.sort()\n\t\t\t\t\t\t\t.map((f) => join(many, f))\n\t\t\t\t\t: [];\n\t\t\tif (files.length > 0) images[type] = files;\n\t\t}\n\t\tconst listing: PlayListing = { language, images };\n\t\tconst title = text(join(dir, 'title.txt'));\n\t\tconst shortDescription = text(join(dir, 'short_description.txt'));\n\t\tconst fullDescription = text(join(dir, 'full_description.txt'));\n\t\tconst video = text(join(dir, 'video.txt'));\n\t\tif (title) listing.title = title;\n\t\tif (shortDescription) listing.shortDescription = shortDescription;\n\t\tif (fullDescription) listing.fullDescription = fullDescription;\n\t\tif (video) listing.video = video;\n\t\tlistings.push(listing);\n\t}\n\n\tconst dataSafety = text(join(root, 'data-safety.csv'));\n\treturn { listings, ...(dataSafety ? { dataSafety } : {}) };\n}\n\n/**\n * Push the listing through one edit, committed: each locale's text, and each\n * image kind replaced by the files kept. Then the data safety form, which\n * Play takes outside an edit. Answers whether the listing was pushed: an\n * app that has never had an upload may refuse an edit, and that is left for\n * the next run, not failed.\n */\nexport async function pushPlayStore(\n\tclient: GoogleClient,\n\tpackageName: string,\n\tstore: PlayStore,\n): Promise<{ listing: boolean; dataSafety: boolean; reason?: string }> {\n\tconst app = `${PLAY}/applications/${packageName}`;\n\tlet listing = false;\n\tlet reason: string | undefined;\n\tif (store.listings.length > 0) {\n\t\tlet edit: { id: string } | undefined;\n\t\ttry {\n\t\t\tedit = await client.request<{ id: string }>('POST', `${app}/edits`, {});\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof GoogleApiError)) throw error;\n\t\t\treason = error.detail;\n\t\t}\n\t\tif (edit) {\n\t\t\tconst base = `${app}/edits/${edit.id}/listings`;\n\t\t\tfor (const entry of store.listings) {\n\t\t\t\tconst { images, ...text } = entry;\n\t\t\t\tif (text.title || text.shortDescription || text.fullDescription) {\n\t\t\t\t\tawait client.request('PUT', `${base}/${entry.language}`, text);\n\t\t\t\t}\n\t\t\t\tfor (const [type, files] of Object.entries(images)) {\n\t\t\t\t\tawait client.request('DELETE', `${base}/${entry.language}/${type}`);\n\t\t\t\t\tfor (const file of files ?? []) {\n\t\t\t\t\t\tawait client.request(\n\t\t\t\t\t\t\t'POST',\n\t\t\t\t\t\t\t`${PLAY_UPLOAD}/applications/${packageName}/edits/${edit.id}/listings/${entry.language}/${type}?uploadType=media`,\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\traw: {\n\t\t\t\t\t\t\t\t\tcontentType:\n\t\t\t\t\t\t\t\t\t\textname(file).toLowerCase() === '.png'\n\t\t\t\t\t\t\t\t\t\t\t? 'image/png'\n\t\t\t\t\t\t\t\t\t\t\t: 'image/jpeg',\n\t\t\t\t\t\t\t\t\tdata: readFileSync(file),\n\t\t\t\t\t\t\t\t},\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}\n\t\t\t}\n\t\t\tawait client.request('POST', `${app}/edits/${edit.id}:commit`);\n\t\t\tlisting = true;\n\t\t}\n\t}\n\n\tlet dataSafety = false;\n\tif (store.dataSafety) {\n\t\tawait client.request('POST', `${app}/dataSafety`, {\n\t\t\tsafetyLabels: store.dataSafety,\n\t\t});\n\t\tdataSafety = true;\n\t}\n\treturn { listing, dataSafety, ...(reason ? { reason } : {}) };\n}\n\n/** What Play Console only takes by hand, for the person to tick off. */\nexport const PLAY_CONSOLE_CHECKLIST = [\n\t'App content → Privacy policy: the URL of the published policy',\n\t'App content → App access: how a reviewer signs in',\n\t'App content → Ads: whether the app shows ads',\n\t'App content → Content rating: the questionnaire',\n\t'App content → Target audience and content',\n\t'App content → Health apps / Health Connect, where the app reads health data',\n\t'App content → Sensitive permissions, where the app asks for any',\n\t'Release → the first upload of a new app, by hand',\n];\n","/**\n * `gkm deploy:google-play`: what EAS Submit needs to publish a `MobileApp`\n * to Google Play, set up in one run — the counterpart of `gkm deploy:github`\n * for the AWS side.\n *\n * 1. Each deployed stage's track and release status into `eas.json`\n * (`submit.<stage>.android`), from `mobileStage`.\n * 2. Google: the project (`--project`, else `<workspace>-play`, made when\n * absent) with the Android Publisher API on, and the service account\n * `<workspace>-play` in it, found or made.\n * 3. Play Console: the account invited with a grant on the app alone, its\n * permissions following the stages' tracks — production releases only\n * when a stage submits there. An app not in Play Console yet is a step\n * only a person can take; interactively, the run says so and waits.\n * 4. A new JSON key, held in memory: uploaded to EAS, assigned to the app's\n * Android credentials for EAS Submit, and proved by opening and\n * discarding an edit with it. Only then are the account's older keys\n * deleted, from EAS and from Google — a failed run leaves the old key\n * working.\n * 5. The store listing kept beside the app (`store/play/`), pushed.\n * 6. What Play Console only takes by hand, as a checklist.\n *\n * Running it again rotates the key and pushes the listing.\n */\n\nimport { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { delimiter, join } from 'node:path';\nimport { loadWorkspaceConfig } from '../../config.js';\nimport { GkmError } from '../../errors';\nimport { loadStage } from '../../exec/stage.js';\nimport { canPrompt } from '../../prompt.js';\nimport { chooseMobileApp, withStageProfiles } from '../eas.js';\nimport { mobileStage } from '../stage.js';\nimport { type EasApi, easApi } from './easApi.js';\nimport {\n\tassertGoogleId,\n\tcreateKey,\n\tdeleteKey,\n\tenablePublisherApi,\n\tensureProject,\n\tensureServiceAccount,\n\tkeyId,\n\tlistKeys,\n\tplayId,\n} from './gcp.js';\nimport {\n\ttype GoogleClient,\n\ttype GoogleSignIn,\n\tgcloudSignIn,\n\tgoogleClient,\n} from './google.js';\nimport {\n\tensurePlayAccess,\n\tPLAY_CONSOLE_CHECKLIST,\n\tPlayAppMissing,\n\tPlayKeyUnverified,\n\tplayPermissions,\n\tpushPlayStore,\n\treadPlayStore,\n\ttype ServiceAccountJson,\n\tverifyKey,\n} from './play.js';\n\nconst logger = console;\n\n/** No Play developer account to act in. */\nexport class PlayDeveloperMissing extends GkmError {\n\tconstructor() {\n\t\tsuper(\n\t\t\t'Name the Play developer account: --developer <id>. It is the number in ' +\n\t\t\t\t\"Play Console's address: https://play.google.com/console/developers/<id>/….\",\n\t\t);\n\t\tthis.name = 'PlayDeveloperMissing';\n\t}\n}\n\n/** The app's Expo config has no Android package, or no EAS project. */\nexport class ExpoConfigIncomplete extends GkmError {\n\tconstructor(\n\t\treadonly app: string,\n\t\treadonly missing: 'android.package' | 'extra.eas.projectId',\n\t) {\n\t\tsuper(\n\t\t\tmissing === 'android.package'\n\t\t\t\t? `'${app}' has no android.package in its Expo config: Play knows an app ` +\n\t\t\t\t\t\t\"by its package. Set it in app.config.ts: android: { package: 'com.acme.shop' }.\"\n\t\t\t\t: `'${app}' has no extra.eas.projectId in its Expo config: it is not ` +\n\t\t\t\t\t\t'linked to an EAS project. Run `eas init` in the app.',\n\t\t);\n\t\tthis.name = 'ExpoConfigIncomplete';\n\t}\n}\n\n/** `expo config` could not read the app's config. */\nexport class ExpoConfigFailed extends GkmError {\n\tconstructor(\n\t\treadonly dir: string,\n\t\treadonly detail: string,\n\t) {\n\t\tsuper(\n\t\t\t`Could not read the Expo config in ${dir} (${detail}). Check that ` +\n\t\t\t\t'`npx expo config --json` works there.',\n\t\t);\n\t\tthis.name = 'ExpoConfigFailed';\n\t}\n}\n\n/** The workspace deploys no stage. */\nexport class NoDeployedStage extends GkmError {\n\tconstructor() {\n\t\tsuper(\n\t\t\t'gkm.config.ts deploys no stage, so there is nothing to publish to: add one to stages.deployed.',\n\t\t);\n\t\tthis.name = 'NoDeployedStage';\n\t}\n}\n\n/** What the run needs of the app's Expo config. */\nexport interface ExpoAppConfig {\n\tname?: string;\n\tandroid?: { package?: string };\n\textra?: { eas?: { projectId?: string } };\n}\n\nexport interface GooglePlayDeps {\n\tsignIn: GoogleSignIn;\n\teas: EasApi;\n\t/** The app's Expo config, evaluated with the values its build reads. */\n\texpoConfig: (\n\t\tdir: string,\n\t\troot: string,\n\t\tenv: Readonly<Record<string, string>>,\n\t) => Promise<ExpoAppConfig>;\n\t/** Whether a person is here: to sign in, and to create the app. */\n\tinteractive: boolean;\n\t/** Wait between two looks for the app, and two tries of the new key. */\n\tsleep: (ms: number) => Promise<void>;\n}\n\n/** `expo config --json`, run with the app's Expo — its own, or the workspace's. */\nexport function expoConfig(\n\tdir: string,\n\troot: string,\n\tenv: Readonly<Record<string, string>>,\n): Promise<ExpoAppConfig> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = spawn('expo', ['config', '--json', '--type', 'public'], {\n\t\t\tcwd: dir,\n\t\t\tstdio: ['ignore', 'pipe', 'pipe'],\n\t\t\tenv: {\n\t\t\t\t...process.env,\n\t\t\t\t...env,\n\t\t\t\tPATH: [\n\t\t\t\t\tjoin(dir, 'node_modules', '.bin'),\n\t\t\t\t\tjoin(root, 'node_modules', '.bin'),\n\t\t\t\t\tprocess.env.PATH,\n\t\t\t\t].join(delimiter),\n\t\t\t},\n\t\t});\n\t\tlet stdout = '';\n\t\tlet stderr = '';\n\t\tchild.stdout.on('data', (chunk: Buffer) => {\n\t\t\tstdout += chunk.toString();\n\t\t});\n\t\tchild.stderr.on('data', (chunk: Buffer) => {\n\t\t\tstderr += chunk.toString();\n\t\t});\n\t\tchild.on('error', (error) =>\n\t\t\treject(new ExpoConfigFailed(dir, error.message)),\n\t\t);\n\t\tchild.on('close', (code) => {\n\t\t\tif (code !== 0) {\n\t\t\t\treject(new ExpoConfigFailed(dir, stderr.trim() || `exit ${code}`));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tresolve(JSON.parse(stdout) as ExpoAppConfig);\n\t\t\t} catch {\n\t\t\t\treject(new ExpoConfigFailed(dir, `no JSON: ${stdout.slice(0, 200)}`));\n\t\t\t}\n\t\t});\n\t});\n}\n\nexport const defaultGooglePlayDeps: GooglePlayDeps = {\n\tsignIn: gcloudSignIn(),\n\teas: easApi(),\n\texpoConfig,\n\tinteractive: canPrompt(),\n\tsleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),\n};\n\nexport interface GooglePlayOptions {\n\t/** The mobile app; the one here, or the only one, if not. */\n\tapp?: string;\n\t/** The Google Cloud project: `<workspace>-play` by default. */\n\tproject?: string;\n\t/** The Play developer account's id. */\n\tdeveloper?: string;\n\t/**\n\t * The stage whose values evaluate the app's Expo config: the protected\n\t * one, else the first deployed.\n\t */\n\tstage?: string;\n\t/** The AWS profile for that stage's account, where its secrets are kept. */\n\tprofile?: string;\n\tcwd?: string;\n}\n\nexport interface GooglePlayResult {\n\tpackageName: string;\n\tproject: string;\n\temail: string;\n\tpermissions: string[];\n\taccess: 'invited' | 'granted' | 'updated' | 'unchanged';\n\t/** The new key's id, in Google and in EAS. */\n\tkey: { google: string; eas: string };\n\t/** The older keys deleted. */\n\tdeleted: { google: string[]; eas: string[] };\n\tlisting:\n\t\t| { listing: boolean; dataSafety: boolean; reason?: string }\n\t\t| undefined;\n}\n\n/**\n * Set up publishing a mobile app to Google Play.\n *\n * @throws {PlayDeveloperMissing}, {ExpoConfigIncomplete}, {PlayAppMissing},\n * {PlayKeyUnverified} — and what each step's API throws\n */\nexport async function deployGooglePlay(\n\toptions: GooglePlayOptions,\n\tdeps: GooglePlayDeps = defaultGooglePlayDeps,\n): Promise<GooglePlayResult> {\n\tif (!options.developer) throw new PlayDeveloperMissing();\n\tconst developer = options.developer;\n\n\t// The stage only evaluates the Expo config: any deployed one's values do.\n\tconst declared = (await loadWorkspaceConfig(options.cwd)).workspace.stages;\n\tconst stageName =\n\t\toptions.stage ?? declared.protected?.[0] ?? declared.deployed[0];\n\tif (!stageName) throw new NoDeployedStage();\n\tconst loaded = await loadStage({\n\t\tstage: stageName,\n\t\t...(options.cwd ? { cwd: options.cwd } : {}),\n\t\t...(options.profile ? { profile: options.profile } : {}),\n\t});\n\tconst { workspace, manifest, stack } = loaded;\n\tconst declaration = chooseMobileApp(manifest, options.app, loaded.appName);\n\tconst name = declaration.id;\n\tconst dir = join(workspace.root, declaration.app.path);\n\tconst values =\n\t\tstack.mobileApps.find((candidate) => candidate.id === declaration.id)\n\t\t\t?.values ?? {};\n\n\tconst config = await deps.expoConfig(dir, workspace.root, values);\n\tconst packageName = config.android?.package;\n\tif (!packageName) throw new ExpoConfigIncomplete(name, 'android.package');\n\tconst projectId = config.extra?.eas?.projectId;\n\tif (!projectId) throw new ExpoConfigIncomplete(name, 'extra.eas.projectId');\n\n\t// 1. Each stage's track, in eas.json — and the tracks the grant follows.\n\tconst stages = workspace.stages.deployed.map((stage) =>\n\t\tmobileStage(workspace, declaration, stage),\n\t);\n\tconst easJsonPath = join(dir, 'eas.json');\n\tconst before = existsSync(easJsonPath)\n\t\t? JSON.parse(await readFile(easJsonPath, 'utf8'))\n\t\t: {};\n\tconst after = stages.reduce(withStageProfiles, before);\n\tif (JSON.stringify(before) !== JSON.stringify(after)) {\n\t\tawait writeFile(easJsonPath, `${JSON.stringify(after, null, 2)}\\n`);\n\t\tlogger.log(`📝 ${easJsonPath}: each stage's build and submit profiles`);\n\t}\n\tconst store = readPlayStore(dir);\n\tconst permissions = playPermissions({\n\t\ttracks: stages.map((stage) => stage.android.track),\n\t\tlisting: (store?.listings.length ?? 0) > 0,\n\t});\n\n\t// 2. Google: signed in as a Play Console admin, the project and account.\n\tconst project = options.project ?? playId(workspace.name);\n\tassertGoogleId('project', project);\n\tconst account = playId(workspace.name);\n\tconst token = await deps.signIn.token({ interactive: deps.interactive });\n\tconst bare: GoogleClient = googleClient(token);\n\tconst created = await ensureProject(bare, project, `${workspace.name} Play`);\n\tlogger.log(\n\t\t`☁️ Google Cloud project ${project}${created ? ' (created)' : ''}`,\n\t);\n\tconst client = googleClient(token, project);\n\tawait enablePublisherApi(client, project);\n\tconst email = await ensureServiceAccount(\n\t\tclient,\n\t\tproject,\n\t\taccount,\n\t\t`${workspace.name} publishing (gkm)`,\n\t);\n\tlogger.log(`🤖 Service account ${email}`);\n\n\t// 3. Play Console: the app grant, waiting for the app where someone can\n\t// make it.\n\tlet access: GooglePlayResult['access'] | undefined;\n\tfor (let attempt = 0; !access; attempt++) {\n\t\ttry {\n\t\t\taccess = await ensurePlayAccess(client, {\n\t\t\t\tdeveloper,\n\t\t\t\temail,\n\t\t\t\tpackageName,\n\t\t\t\tpermissions,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof PlayAppMissing) || !deps.interactive) throw error;\n\t\t\tif (attempt === 0) {\n\t\t\t\tlogger.log(`\\n⏳ ${error.message}\\n Waiting for it…`);\n\t\t\t}\n\t\t\tawait deps.sleep(15_000);\n\t\t}\n\t}\n\tlogger.log(\n\t\t`🎟️ Play access on ${packageName}: ${access} (${permissions.join(', ')})`,\n\t);\n\n\t// 4. A new key: to EAS, proved, and only then the old ones gone.\n\tconst older = await listKeys(client, project, email);\n\tconst key = await createKey(client, project, email);\n\tconst json = JSON.parse(key.json) as ServiceAccountJson &\n\t\tRecord<string, unknown>;\n\tconst easProject = await deps.eas.project(projectId);\n\tconst credentials = await deps.eas.androidCredentials(\n\t\t{ projectId, fullName: easProject.fullName },\n\t\tpackageName,\n\t);\n\tconst easKey = await deps.eas.createKey(easProject.accountId, json);\n\tawait deps.eas.useForSubmissions(credentials.id, easKey.id);\n\tlogger.log(\n\t\t`🔑 New key ${keyId(key)} assigned to EAS Submit for ${packageName}`,\n\t);\n\n\t// A new grant takes a moment to reach Play.\n\tfor (let attempt = 0; ; attempt++) {\n\t\ttry {\n\t\t\tawait verifyKey(json, packageName);\n\t\t\tbreak;\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof PlayKeyUnverified) || attempt >= 5) throw error;\n\t\t\tawait deps.sleep(10_000);\n\t\t}\n\t}\n\tlogger.log('✅ The key opens an edit on the app');\n\n\tconst easOlder = (await deps.eas.keys(easProject.accountName)).filter(\n\t\t(candidate) =>\n\t\t\tcandidate.clientEmail === email && candidate.id !== easKey.id,\n\t);\n\tfor (const old of easOlder) await deps.eas.deleteKey(old.id);\n\tfor (const old of older) await deleteKey(client, old);\n\tif (older.length + easOlder.length > 0) {\n\t\tlogger.log(\n\t\t\t`🧹 Deleted ${older.length} older key(s) from Google, ${easOlder.length} from EAS`,\n\t\t);\n\t}\n\n\t// 5. The listing, where the workspace keeps one.\n\tconst listing = store\n\t\t? await pushPlayStore(client, packageName, store)\n\t\t: undefined;\n\tif (listing?.listing) logger.log('🛍️ Store listing pushed');\n\tif (store && !listing?.listing && listing?.reason) {\n\t\tlogger.log(\n\t\t\t`⏭️ Store listing not pushed yet (${listing.reason}): run this again after the app's first upload`,\n\t\t);\n\t}\n\tif (listing?.dataSafety) logger.log('🛡️ Data safety pushed');\n\n\t// 6. What only a person can do.\n\tlogger.log('\\nLeft to do in Play Console, by hand:');\n\tfor (const item of PLAY_CONSOLE_CHECKLIST) logger.log(` [ ] ${item}`);\n\n\treturn {\n\t\tpackageName,\n\t\tproject,\n\t\temail,\n\t\tpermissions,\n\t\taccess,\n\t\tkey: { google: keyId(key), eas: easKey.id },\n\t\tdeleted: {\n\t\t\tgoogle: older.map(keyId),\n\t\t\teas: easOlder.map((candidate) => candidate.id),\n\t\t},\n\t\tlisting,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAaA,MAAa,cAAc;;AAG3B,IAAa,mBAAb,cAAsCA,eAAAA,SAAS;CAC9C,cAAc;EACb,MACC,gKAGD;EACA,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,cAAb,cAAiCA,eAAAA,SAAS;CAE/B;CACA;CAFV,YACC,WACA,QACC;EACD,MAAM,eAAe,UAAU,IAAI,QAAQ;EAHlC,KAAA,YAAA;EACA,KAAA,SAAA;EAGT,KAAK,OAAO;CACb;AACD;AASA,MAAM,aAAa;AA0BnB,SAAgB,OACf,QAA4B,QAAQ,IAAI,YACxC,WAAmB,aACV;CACT,MAAM,OAAO,OACZ,WACA,OACA,cACgB;EAChB,IAAI,CAAC,OAAO,MAAM,IAAI,iBAAiB;EACvC,MAAM,WAAW,MAAM,MAAM,UAAU;GACtC,QAAQ;GACR,SAAS;IACR,eAAe,UAAU;IACzB,gBAAgB;GACjB;GACA,MAAM,KAAK,UAAU;IAAE;IAAO;IAAW,eAAe;GAAU,CAAC;EACpE,CAAC;EACD,MAAM,OAAQ,MAAM,SAAS,KAAK,CAAC,CAAC,aAAa,CAAC,EAAE;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AO,IAAI,SAAS,MAAM;CAErE,OAAO;EACN;EACA;EACA;EACA;EACA;EACA,KAAK;GAAE,QAAQ,MAAM,GAAG;GAAG,KAAK,OAAO;EAAG;EAC1C,SAAS;GACR,QAAQ,MAAM,IAAI,KAAK;GACvB,KAAK,SAAS,KAAK,cAAc,UAAU,EAAE;EAC9C;EACA;CACD;AACD"}
1
+ {"version":3,"file":"googlePlay-Btn0lut5.cjs","names":["GkmError","GkmError","join","gkmHome","spawn","GkmError","GkmError","createSign","join","existsSync","readFileSync","readdirSync","statSync","extname","GkmError","spawn","join","delimiter","canPrompt","loadWorkspaceConfig","loadStage","chooseMobileApp","mobileStage","existsSync","readFile","withStageProfiles","writeFile"],"sources":["../src/mobile/googlePlay/easApi.ts","../src/mobile/googlePlay/google.ts","../src/mobile/googlePlay/gcp.ts","../src/mobile/googlePlay/play.ts","../src/mobile/googlePlay/index.ts"],"sourcesContent":["/**\n * EAS, as `gkm deploy:google-play` reaches it: the GraphQL API eas-cli itself\n * calls, with an `EXPO_TOKEN` — to upload a Google service account key and\n * assign it to the app's Android credentials for EAS Submit, which is what\n * `eas credentials` does interactively.\n *\n * The documents are eas-cli's own (24.x), each selecting only what gkm reads:\n * eas-cli's credentials fragment also brings back the app's keystore and its\n * passwords, which gkm has no reason to hold.\n */\n\nimport { GkmError } from '../../errors';\n\nexport const EAS_GRAPHQL = 'https://api.expo.dev/graphql';\n\n/** No `EXPO_TOKEN` to call EAS with. */\nexport class ExpoTokenMissing extends GkmError {\n\tconstructor() {\n\t\tsuper(\n\t\t\t'gkm uploads the key to EAS with an access token, and EXPO_TOKEN is not ' +\n\t\t\t\t'set. Create one at https://expo.dev/settings/access-tokens and export ' +\n\t\t\t\t'it as EXPO_TOKEN.',\n\t\t);\n\t\tthis.name = 'ExpoTokenMissing';\n\t}\n}\n\n/** EAS refused a call. */\nexport class EasApiError extends GkmError {\n\tconstructor(\n\t\treadonly operation: string,\n\t\treadonly detail: string,\n\t) {\n\t\tsuper(`EAS refused ${operation}: ${detail}`);\n\t\tthis.name = 'EasApiError';\n\t}\n}\n\n/** A Google service account key, as EAS holds it. */\nexport interface EasGoogleKey {\n\tid: string;\n\tclientEmail: string;\n\tprivateKeyIdentifier: string;\n}\n\nconst KEY_FIELDS = 'id clientEmail privateKeyIdentifier';\n\nexport interface EasApi {\n\t/** The project's owner account. */\n\tproject(projectId: string): Promise<{\n\t\taccountId: string;\n\t\taccountName: string;\n\t\tfullName: string;\n\t}>;\n\t/** The app's Android credentials for a package, created when absent. */\n\tandroidCredentials(\n\t\tproject: { projectId: string; fullName: string },\n\t\tpackageName: string,\n\t): Promise<{ id: string; submissionsKey?: EasGoogleKey }>;\n\t/** Upload a key file's JSON to the account. */\n\tcreateKey(\n\t\taccountId: string,\n\t\tjson: Record<string, unknown>,\n\t): Promise<EasGoogleKey>;\n\t/** Make a key the one EAS Submit uses for the credentials. */\n\tuseForSubmissions(credentialsId: string, keyId: string): Promise<void>;\n\t/** Every key on the account. */\n\tkeys(accountName: string): Promise<EasGoogleKey[]>;\n\tdeleteKey(id: string): Promise<void>;\n}\n\nexport function easApi(\n\ttoken: string | undefined = process.env.EXPO_TOKEN,\n\tendpoint: string = EAS_GRAPHQL,\n): EasApi {\n\tconst call = async <T>(\n\t\toperation: string,\n\t\tquery: string,\n\t\tvariables: Record<string, unknown>,\n\t): Promise<T> => {\n\t\tif (!token) throw new ExpoTokenMissing();\n\t\tconst response = await fetch(endpoint, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {\n\t\t\t\tauthorization: `Bearer ${token}`,\n\t\t\t\t'content-type': 'application/json',\n\t\t\t},\n\t\t\tbody: JSON.stringify({ query, variables, operationName: operation }),\n\t\t});\n\t\tconst body = (await response.json().catch(() => ({}))) as {\n\t\t\tdata?: T;\n\t\t\terrors?: { message: string }[];\n\t\t};\n\t\tif (!response.ok || body.errors?.length || !body.data) {\n\t\t\tthrow new EasApiError(\n\t\t\t\toperation,\n\t\t\t\tbody.errors?.map((error) => error.message).join('; ') ||\n\t\t\t\t\t`HTTP ${response.status}`,\n\t\t\t);\n\t\t}\n\t\treturn body.data;\n\t};\n\n\tconst credentialsFields = `id googleServiceAccountKeyForSubmissions { ${KEY_FIELDS} }`;\n\ttype Credentials = {\n\t\tid: string;\n\t\tgoogleServiceAccountKeyForSubmissions: EasGoogleKey | null;\n\t};\n\tconst asCredentials = (credentials: Credentials) => ({\n\t\tid: credentials.id,\n\t\t...(credentials.googleServiceAccountKeyForSubmissions\n\t\t\t? { submissionsKey: credentials.googleServiceAccountKeyForSubmissions }\n\t\t\t: {}),\n\t});\n\n\treturn {\n\t\tasync project(projectId) {\n\t\t\tconst data = await call<{\n\t\t\t\tapp: {\n\t\t\t\t\tbyId: {\n\t\t\t\t\t\tfullName: string;\n\t\t\t\t\t\townerAccount: { id: string; name: string };\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t}>(\n\t\t\t\t'AppByIdQuery',\n\t\t\t\t`query AppByIdQuery($appId: String!) {\n app { byId(appId: $appId) { id fullName ownerAccount { id name } } }\n}`,\n\t\t\t\t{ appId: projectId },\n\t\t\t);\n\t\t\tconst app = data.app.byId;\n\t\t\treturn {\n\t\t\t\taccountId: app.ownerAccount.id,\n\t\t\t\taccountName: app.ownerAccount.name,\n\t\t\t\tfullName: app.fullName,\n\t\t\t};\n\t\t},\n\n\t\tasync androidCredentials(project, packageName) {\n\t\t\tconst found = await call<{\n\t\t\t\tapp: { byFullName: { androidAppCredentials: Credentials[] } };\n\t\t\t}>(\n\t\t\t\t'AndroidAppCredentialsByApplicationIdentifierQuery',\n\t\t\t\t`query AndroidAppCredentialsByApplicationIdentifierQuery(\n $projectFullName: String!\n $applicationIdentifier: String\n $legacyOnly: Boolean\n) {\n app {\n byFullName(fullName: $projectFullName) {\n id\n androidAppCredentials(\n filter: { applicationIdentifier: $applicationIdentifier, legacyOnly: $legacyOnly }\n ) { ${credentialsFields} }\n }\n }\n}`,\n\t\t\t\t{\n\t\t\t\t\tprojectFullName: project.fullName,\n\t\t\t\t\tapplicationIdentifier: packageName,\n\t\t\t\t\tlegacyOnly: false,\n\t\t\t\t},\n\t\t\t);\n\t\t\tconst existing = found.app.byFullName.androidAppCredentials[0];\n\t\t\tif (existing) return asCredentials(existing);\n\n\t\t\tconst created = await call<{\n\t\t\t\tandroidAppCredentials: { createAndroidAppCredentials: Credentials };\n\t\t\t}>(\n\t\t\t\t'CreateAndroidAppCredentialsMutation',\n\t\t\t\t`mutation CreateAndroidAppCredentialsMutation(\n $androidAppCredentialsInput: AndroidAppCredentialsInput!\n $appId: ID!\n $applicationIdentifier: String!\n) {\n androidAppCredentials {\n createAndroidAppCredentials(\n androidAppCredentialsInput: $androidAppCredentialsInput\n appId: $appId\n applicationIdentifier: $applicationIdentifier\n ) { ${credentialsFields} }\n }\n}`,\n\t\t\t\t{\n\t\t\t\t\tandroidAppCredentialsInput: {},\n\t\t\t\t\tappId: project.projectId,\n\t\t\t\t\tapplicationIdentifier: packageName,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn asCredentials(\n\t\t\t\tcreated.androidAppCredentials.createAndroidAppCredentials,\n\t\t\t);\n\t\t},\n\n\t\tasync createKey(accountId, json) {\n\t\t\tconst data = await call<{\n\t\t\t\tgoogleServiceAccountKey: {\n\t\t\t\t\tcreateGoogleServiceAccountKey: EasGoogleKey;\n\t\t\t\t};\n\t\t\t}>(\n\t\t\t\t'CreateGoogleServiceAccountKeyMutation',\n\t\t\t\t`mutation CreateGoogleServiceAccountKeyMutation(\n $googleServiceAccountKeyInput: GoogleServiceAccountKeyInput!\n $accountId: ID!\n) {\n googleServiceAccountKey {\n createGoogleServiceAccountKey(\n googleServiceAccountKeyInput: $googleServiceAccountKeyInput\n accountId: $accountId\n ) { ${KEY_FIELDS} }\n }\n}`,\n\t\t\t\t{ googleServiceAccountKeyInput: { jsonKey: json }, accountId },\n\t\t\t);\n\t\t\treturn data.googleServiceAccountKey.createGoogleServiceAccountKey;\n\t\t},\n\n\t\tasync useForSubmissions(credentialsId, keyId) {\n\t\t\tawait call(\n\t\t\t\t'SetGoogleServiceAccountKeyForSubmissionsMutation',\n\t\t\t\t`mutation SetGoogleServiceAccountKeyForSubmissionsMutation(\n $androidAppCredentialsId: ID!\n $googleServiceAccountKeyId: ID!\n) {\n androidAppCredentials {\n setGoogleServiceAccountKeyForSubmissions(\n id: $androidAppCredentialsId\n googleServiceAccountKeyId: $googleServiceAccountKeyId\n ) { id }\n }\n}`,\n\t\t\t\t{\n\t\t\t\t\tandroidAppCredentialsId: credentialsId,\n\t\t\t\t\tgoogleServiceAccountKeyId: keyId,\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\n\t\tasync keys(accountName) {\n\t\t\tconst keys: EasGoogleKey[] = [];\n\t\t\tlet after: string | null = null;\n\t\t\tdo {\n\t\t\t\tconst data: {\n\t\t\t\t\taccount: {\n\t\t\t\t\t\tbyName: {\n\t\t\t\t\t\t\tgoogleServiceAccountKeysPaginated: {\n\t\t\t\t\t\t\t\tedges: { node: EasGoogleKey }[];\n\t\t\t\t\t\t\t\tpageInfo: { hasNextPage: boolean; endCursor: string | null };\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} = await call(\n\t\t\t\t\t'GoogleServiceAccountKeysPaginatedByAccountQuery',\n\t\t\t\t\t`query GoogleServiceAccountKeysPaginatedByAccountQuery(\n $accountName: String!\n $after: String\n $first: Int\n) {\n account {\n byName(accountName: $accountName) {\n id\n googleServiceAccountKeysPaginated(after: $after, first: $first) {\n edges { node { ${KEY_FIELDS} } }\n pageInfo { hasNextPage endCursor }\n }\n }\n }\n}`,\n\t\t\t\t\t{ accountName, after, first: 50 },\n\t\t\t\t);\n\t\t\t\tconst page = data.account.byName.googleServiceAccountKeysPaginated;\n\t\t\t\tkeys.push(...page.edges.map((edge) => edge.node));\n\t\t\t\tafter = page.pageInfo.hasNextPage ? page.pageInfo.endCursor : null;\n\t\t\t} while (after);\n\t\t\treturn keys;\n\t\t},\n\n\t\tasync deleteKey(id) {\n\t\t\tawait call(\n\t\t\t\t'DeleteGoogleServiceAccountKeyMutation',\n\t\t\t\t`mutation DeleteGoogleServiceAccountKeyMutation($googleServiceAccountKeyId: ID!) {\n googleServiceAccountKey { deleteGoogleServiceAccountKey(id: $googleServiceAccountKeyId) { id } }\n}`,\n\t\t\t\t{ googleServiceAccountKeyId: id },\n\t\t\t);\n\t\t},\n\t};\n}\n","/**\n * Google, as `gkm deploy:google-play` reaches it: a token for the person\n * running it, and the Cloud APIs that make a project, a service account and\n * its key.\n *\n * The token is gcloud's own application-default credential, with the\n * `cloud-platform` and `androidpublisher` scopes — no OAuth client of gkm's —\n * kept in gkm's own gcloud config (`<gkm home>/gcloud`), so the person's own\n * gcloud setup is never read or changed. Every call carries the project as\n * its quota project (`x-goog-user-project`), which the Play Developer API\n * requires of a user credential.\n */\n\nimport { spawn } from 'node:child_process';\nimport { join } from 'node:path';\nimport { GkmError } from '../../errors';\nimport { gkmHome } from '../../home.js';\n\n/** The scopes the sign-in asks for. */\nexport const GOOGLE_SCOPES = [\n\t'https://www.googleapis.com/auth/cloud-platform',\n\t'https://www.googleapis.com/auth/androidpublisher',\n];\n\n/** `gcloud` is not installed. */\nexport class GcloudMissing extends GkmError {\n\tconstructor() {\n\t\tsuper(\n\t\t\t'gkm signs in to Google with gcloud, and there is no `gcloud` here. ' +\n\t\t\t\t'Install the Google Cloud CLI: https://cloud.google.com/sdk/docs/install.',\n\t\t);\n\t\tthis.name = 'GcloudMissing';\n\t}\n}\n\n/** Not signed in, and no terminal to sign in from. */\nexport class GoogleSignInRequired extends GkmError {\n\tconstructor(readonly config: string) {\n\t\tsuper(\n\t\t\t'Signing in to Google opens a browser, and this run has no terminal. ' +\n\t\t\t\t'Run it once where you can sign in, as a Play Console admin: ' +\n\t\t\t\t`CLOUDSDK_CONFIG=${config} gcloud auth application-default login ` +\n\t\t\t\t`--scopes=${GOOGLE_SCOPES.join(',')}.`,\n\t\t);\n\t\tthis.name = 'GoogleSignInRequired';\n\t}\n}\n\n/** A Google API refused a call. */\nexport class GoogleApiError extends GkmError {\n\tconstructor(\n\t\treadonly method: string,\n\t\treadonly url: string,\n\t\treadonly status: number,\n\t\treadonly detail: string,\n\t) {\n\t\tsuper(`Google answered ${status} to ${method} ${url}: ${detail}`);\n\t\tthis.name = 'GoogleApiError';\n\t}\n}\n\n/** A long-running Google operation did not finish in time. */\nexport class GoogleOperationTimedOut extends GkmError {\n\tconstructor(readonly operation: string) {\n\t\tsuper(\n\t\t\t`Google's operation ${operation} had not finished after a minute. ` +\n\t\t\t\t'Run the command again: what it finished is kept.',\n\t\t);\n\t\tthis.name = 'GoogleOperationTimedOut';\n\t}\n}\n\n/** Where gkm keeps its gcloud sign-in. */\nexport function gcloudConfig(env: NodeJS.ProcessEnv = process.env): string {\n\treturn join(gkmHome(env), 'gcloud');\n}\n\n/** How a token is had: the real one runs gcloud. */\nexport interface GoogleSignIn {\n\t/** An access token for the signed-in person, signing in if allowed. */\n\ttoken(options: { interactive: boolean }): Promise<string>;\n}\n\nfunction gcloud(\n\targs: readonly string[],\n\tconfig: string,\n\tinherit: boolean,\n): Promise<{ code: number | null; stdout: string }> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = spawn('gcloud', [...args], {\n\t\t\tstdio: [\n\t\t\t\t'inherit',\n\t\t\t\tinherit ? 'inherit' : 'pipe',\n\t\t\t\tinherit ? 'inherit' : 'pipe',\n\t\t\t],\n\t\t\tenv: { ...process.env, CLOUDSDK_CONFIG: config },\n\t\t});\n\t\tlet stdout = '';\n\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\tstdout += chunk.toString();\n\t\t});\n\t\tchild.on('error', (error: NodeJS.ErrnoException) =>\n\t\t\treject(error.code === 'ENOENT' ? new GcloudMissing() : error),\n\t\t);\n\t\tchild.on('close', (code) => resolve({ code, stdout }));\n\t});\n}\n\n/** gcloud's application-default credential, in gkm's own gcloud config. */\nexport function gcloudSignIn(config: string = gcloudConfig()): GoogleSignIn {\n\treturn {\n\t\tasync token({ interactive }) {\n\t\t\tconst print = () =>\n\t\t\t\tgcloud(\n\t\t\t\t\t['auth', 'application-default', 'print-access-token'],\n\t\t\t\t\tconfig,\n\t\t\t\t\tfalse,\n\t\t\t\t);\n\t\t\tlet printed = await print();\n\t\t\tif (printed.code !== 0) {\n\t\t\t\tif (!interactive) throw new GoogleSignInRequired(config);\n\t\t\t\tawait gcloud(\n\t\t\t\t\t[\n\t\t\t\t\t\t'auth',\n\t\t\t\t\t\t'application-default',\n\t\t\t\t\t\t'login',\n\t\t\t\t\t\t`--scopes=${GOOGLE_SCOPES.join(',')}`,\n\t\t\t\t\t],\n\t\t\t\t\tconfig,\n\t\t\t\t\ttrue,\n\t\t\t\t);\n\t\t\t\tprinted = await print();\n\t\t\t\tif (printed.code !== 0) throw new GoogleSignInRequired(config);\n\t\t\t}\n\t\t\treturn printed.stdout.trim();\n\t\t},\n\t};\n}\n\n/** One authenticated Google API caller, for one quota project. */\nexport interface GoogleClient {\n\trequest<T>(\n\t\tmethod: string,\n\t\turl: string,\n\t\tbody?: unknown,\n\t\toptions?: { raw?: { contentType: string; data: Uint8Array } },\n\t): Promise<T>;\n}\n\nexport function googleClient(\n\ttoken: string,\n\tquotaProject?: string,\n): GoogleClient {\n\treturn {\n\t\tasync request(method, url, body, options) {\n\t\t\tconst headers: Record<string, string> = {\n\t\t\t\tauthorization: `Bearer ${token}`,\n\t\t\t\t...(quotaProject ? { 'x-goog-user-project': quotaProject } : {}),\n\t\t\t};\n\t\t\tlet payload: string | Uint8Array | undefined;\n\t\t\tif (options?.raw) {\n\t\t\t\theaders['content-type'] = options.raw.contentType;\n\t\t\t\tpayload = options.raw.data;\n\t\t\t} else if (body !== undefined) {\n\t\t\t\theaders['content-type'] = 'application/json';\n\t\t\t\tpayload = JSON.stringify(body);\n\t\t\t}\n\t\t\tconst response = await fetch(url, {\n\t\t\t\tmethod,\n\t\t\t\theaders,\n\t\t\t\t...(payload !== undefined ? { body: payload } : {}),\n\t\t\t});\n\t\t\tconst text = await response.text();\n\t\t\tif (!response.ok) {\n\t\t\t\tlet detail = text;\n\t\t\t\ttry {\n\t\t\t\t\tconst parsed = JSON.parse(text) as { error?: { message?: string } };\n\t\t\t\t\tdetail = parsed.error?.message ?? text;\n\t\t\t\t} catch {\n\t\t\t\t\t// Not JSON: the text is the detail.\n\t\t\t\t}\n\t\t\t\tthrow new GoogleApiError(method, url, response.status, detail);\n\t\t\t}\n\t\t\treturn (text ? JSON.parse(text) : {}) as never;\n\t\t},\n\t};\n}\n\n/** A long-running operation, polled until it is done. */\nexport async function finished(\n\tclient: GoogleClient,\n\tbase: string,\n\toperation: { name?: string; done?: boolean; error?: { message?: string } },\n\toptions: { intervalMs?: number; attempts?: number } = {},\n): Promise<void> {\n\tlet current = operation;\n\tfor (let attempt = 0; !current.done; attempt++) {\n\t\tif (attempt >= (options.attempts ?? 30)) {\n\t\t\tthrow new GoogleOperationTimedOut(current.name ?? '(unnamed)');\n\t\t}\n\t\tawait new Promise((resolve) =>\n\t\t\tsetTimeout(resolve, options.intervalMs ?? 2_000),\n\t\t);\n\t\tcurrent = await client.request('GET', `${base}/${current.name}`);\n\t}\n\tif (current.error) {\n\t\tthrow new GoogleApiError(\n\t\t\t'GET',\n\t\t\t`${base}/${current.name}`,\n\t\t\t500,\n\t\t\tcurrent.error.message ?? 'the operation failed',\n\t\t);\n\t}\n}\n","/**\n * The Google Cloud side of publishing to Play: a project with the Android\n * Publisher API on, and a service account in it whose JSON key EAS Submit\n * uses. Each step finds what is there before it creates anything, so a\n * second run reuses the project and the account and only makes a new key.\n */\n\nimport { GkmError } from '../../errors';\nimport { finished, GoogleApiError, type GoogleClient } from './google.js';\n\nexport const CLOUD_RESOURCE_MANAGER =\n\t'https://cloudresourcemanager.googleapis.com/v3';\nexport const SERVICE_USAGE = 'https://serviceusage.googleapis.com/v1';\nexport const IAM = 'https://iam.googleapis.com/v1';\n\n/** The API EAS Submit and gkm call Play through. */\nexport const ANDROID_PUBLISHER_API = 'androidpublisher.googleapis.com';\n\n/** A project id or service account id gkm would derive is not a valid one. */\nexport class GoogleIdInvalid extends GkmError {\n\tconstructor(\n\t\treadonly kind: 'project' | 'service account',\n\t\treadonly id: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${id}' is not a valid Google ${kind} id: 6 to 30 lowercase letters, ` +\n\t\t\t\t'digits and hyphens, starting with a letter and not ending in a hyphen. ' +\n\t\t\t\t(kind === 'project' ? 'Name one with --project.' : ''),\n\t\t);\n\t\tthis.name = 'GoogleIdInvalid';\n\t}\n}\n\n/** The project could not be created — most often, its id is someone else's. */\nexport class GoogleProjectUnavailable extends GkmError {\n\tconstructor(\n\t\treadonly project: string,\n\t\treadonly detail: string,\n\t) {\n\t\tsuper(\n\t\t\t`Could not create the Google Cloud project '${project}' (${detail}). ` +\n\t\t\t\t'Project ids are global: name another, or one you already have, with --project.',\n\t\t);\n\t\tthis.name = 'GoogleProjectUnavailable';\n\t}\n}\n\nconst ID = /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/;\n\n/**\n * An id Google accepts, from a workspace's name: `shop` → `shop-play`.\n * Lowercased, anything else made a hyphen, cut to 30.\n */\nexport function playId(workspace: string): string {\n\tconst base = workspace\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9]+/g, '-')\n\t\t.replace(/^[^a-z]+|-+$/g, '');\n\treturn `${base.slice(0, 25).replace(/-+$/, '')}-play`;\n}\n\n/** Throws unless `id` is a valid project or service account id. */\nexport function assertGoogleId(\n\tkind: 'project' | 'service account',\n\tid: string,\n): void {\n\tif (!ID.test(id)) throw new GoogleIdInvalid(kind, id);\n}\n\n/**\n * The project, created when it is not there. Answers whether it was made.\n *\n * @throws {GoogleProjectUnavailable}\n */\nexport async function ensureProject(\n\tclient: GoogleClient,\n\tproject: string,\n\tdisplayName: string,\n\toptions: { intervalMs?: number } = {},\n): Promise<boolean> {\n\tassertGoogleId('project', project);\n\ttry {\n\t\tawait client.request(\n\t\t\t'GET',\n\t\t\t`${CLOUD_RESOURCE_MANAGER}/projects/${project}`,\n\t\t);\n\t\treturn false;\n\t} catch (error) {\n\t\t// Absent, or not ours to see — either way, try to create it.\n\t\tif (\n\t\t\t!(error instanceof GoogleApiError) ||\n\t\t\t![403, 404].includes(error.status)\n\t\t) {\n\t\t\tthrow error;\n\t\t}\n\t}\n\ttry {\n\t\tconst operation = await client.request<{ name?: string; done?: boolean }>(\n\t\t\t'POST',\n\t\t\t`${CLOUD_RESOURCE_MANAGER}/projects`,\n\t\t\t{ projectId: project, displayName: displayName.slice(0, 30) },\n\t\t);\n\t\tawait finished(client, CLOUD_RESOURCE_MANAGER, operation, options);\n\t} catch (error) {\n\t\tif (error instanceof GoogleApiError) {\n\t\t\tthrow new GoogleProjectUnavailable(project, error.detail);\n\t\t}\n\t\tthrow error;\n\t}\n\treturn true;\n}\n\n/** The Android Publisher API, on in the project. */\nexport async function enablePublisherApi(\n\tclient: GoogleClient,\n\tproject: string,\n\toptions: { intervalMs?: number } = {},\n): Promise<void> {\n\tconst operation = await client.request<{ name?: string; done?: boolean }>(\n\t\t'POST',\n\t\t`${SERVICE_USAGE}/projects/${project}/services/${ANDROID_PUBLISHER_API}:enable`,\n\t\t{},\n\t);\n\tawait finished(client, SERVICE_USAGE, operation, options);\n}\n\n/** The service account's email, which is what Play and EAS know it by. */\nexport function serviceAccountEmail(project: string, account: string): string {\n\treturn `${account}@${project}.iam.gserviceaccount.com`;\n}\n\n/** The service account, created when it is not there. Answers its email. */\nexport async function ensureServiceAccount(\n\tclient: GoogleClient,\n\tproject: string,\n\taccount: string,\n\tdisplayName: string,\n): Promise<string> {\n\tassertGoogleId('service account', account);\n\tconst email = serviceAccountEmail(project, account);\n\ttry {\n\t\tawait client.request(\n\t\t\t'GET',\n\t\t\t`${IAM}/projects/${project}/serviceAccounts/${email}`,\n\t\t);\n\t\treturn email;\n\t} catch (error) {\n\t\tif (!(error instanceof GoogleApiError) || error.status !== 404) throw error;\n\t}\n\tawait client.request('POST', `${IAM}/projects/${project}/serviceAccounts`, {\n\t\taccountId: account,\n\t\tserviceAccount: { displayName: displayName.slice(0, 100) },\n\t});\n\treturn email;\n}\n\n/** A service account key: its id, and — only when just made — its JSON. */\nexport interface ServiceAccountKey {\n\t/** `projects/<p>/serviceAccounts/<email>/keys/<id>`. */\n\tname: string;\n\t/** The key file's JSON, held in memory and never written anywhere. */\n\tjson?: string;\n}\n\n/** A new key for the account. Its JSON exists only in what this returns. */\nexport async function createKey(\n\tclient: GoogleClient,\n\tproject: string,\n\temail: string,\n): Promise<ServiceAccountKey & { json: string }> {\n\tconst key = await client.request<{ name: string; privateKeyData: string }>(\n\t\t'POST',\n\t\t`${IAM}/projects/${project}/serviceAccounts/${email}/keys`,\n\t\t{},\n\t);\n\treturn {\n\t\tname: key.name,\n\t\tjson: Buffer.from(key.privateKeyData, 'base64').toString('utf8'),\n\t};\n}\n\n/** The account's keys that someone made — not Google's own. */\nexport async function listKeys(\n\tclient: GoogleClient,\n\tproject: string,\n\temail: string,\n): Promise<ServiceAccountKey[]> {\n\tconst { keys = [] } = await client.request<{ keys?: { name: string }[] }>(\n\t\t'GET',\n\t\t`${IAM}/projects/${project}/serviceAccounts/${email}/keys?keyTypes=USER_MANAGED`,\n\t);\n\treturn keys.map(({ name }) => ({ name }));\n}\n\nexport async function deleteKey(\n\tclient: GoogleClient,\n\tkey: ServiceAccountKey,\n): Promise<void> {\n\tawait client.request('DELETE', `${IAM}/${key.name}`);\n}\n\n/** A key's id: the last part of its name. */\nexport function keyId(key: Pick<ServiceAccountKey, 'name'>): string {\n\treturn key.name.split('/').pop()!;\n}\n","/**\n * Play Console, through the Play Developer API (androidpublisher v3): the\n * service account's access to the app, the store listing as code, and a\n * check that the new key can act on the app.\n */\n\nimport { createSign } from 'node:crypto';\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';\nimport { extname, join } from 'node:path';\nimport type { PlayTrack } from '@geekmidas/manifest';\nimport { GkmError } from '../../errors';\nimport { GoogleApiError, type GoogleClient, googleClient } from './google.js';\n\nexport const PLAY =\n\t'https://androidpublisher.googleapis.com/androidpublisher/v3';\nexport const PLAY_UPLOAD =\n\t'https://androidpublisher.googleapis.com/upload/androidpublisher/v3';\n\n/** What Play answers about a package no app in the account has. */\nconst PACKAGE_MISSING = /packages are not available/i;\n\n/** The app is not in Play Console yet, and Play has no API that makes one. */\nexport class PlayAppMissing extends GkmError {\n\tconstructor(\n\t\treadonly packageName: string,\n\t\treadonly developer: string,\n\t) {\n\t\tsuper(\n\t\t\t`Play Console has no app '${packageName}', and Play has no API that ` +\n\t\t\t\t`creates one. Create it at https://play.google.com/console/developers/` +\n\t\t\t\t`${developer}/create-new-app, with ${packageName} as its package, then ` +\n\t\t\t\t'run this again.',\n\t\t);\n\t\tthis.name = 'PlayAppMissing';\n\t}\n}\n\n/** The new key could not open an edit on the app. */\nexport class PlayKeyUnverified extends GkmError {\n\tconstructor(\n\t\treadonly email: string,\n\t\treadonly detail: string,\n\t) {\n\t\tsuper(\n\t\t\t`The new key for ${email} could not open an edit on the app (${detail}). ` +\n\t\t\t\t'Its access can take a few minutes to reach Play: run this again shortly.',\n\t\t);\n\t\tthis.name = 'PlayKeyUnverified';\n\t}\n}\n\n/**\n * The app-level permissions the service account needs: releasing to the\n * testing tracks, to production only where a stage submits there, and the\n * store listing where the workspace keeps one.\n */\nexport function playPermissions(options: {\n\ttracks: readonly PlayTrack[];\n\tlisting: boolean;\n}): string[] {\n\treturn [\n\t\t'CAN_MANAGE_TRACK_APKS',\n\t\t...(options.tracks.includes('production')\n\t\t\t? ['CAN_MANAGE_PUBLIC_APKS']\n\t\t\t: []),\n\t\t...(options.listing ? ['CAN_MANAGE_PUBLIC_LISTING'] : []),\n\t].sort();\n}\n\ninterface PlayUser {\n\temail: string;\n\tgrants?: { packageName: string; appLevelPermissions?: string[] }[];\n}\n\n/**\n * The service account in Play Console with exactly `permissions` on the\n * app: invited with the grant in one call — Play refuses a user with no\n * permission, and a grant for a user not yet there — and, already there,\n * its grant made what it should be. Answers what changed.\n *\n * @throws {PlayAppMissing}\n */\nexport async function ensurePlayAccess(\n\tclient: GoogleClient,\n\toptions: {\n\t\tdeveloper: string;\n\t\temail: string;\n\t\tpackageName: string;\n\t\tpermissions: readonly string[];\n\t},\n): Promise<'invited' | 'granted' | 'updated' | 'unchanged'> {\n\tconst { developer, email, packageName } = options;\n\tconst permissions = [...options.permissions].sort();\n\tconst users = `${PLAY}/developers/${developer}/users`;\n\tconst missing = (error: unknown) =>\n\t\terror instanceof GoogleApiError && PACKAGE_MISSING.test(error.detail)\n\t\t\t? new PlayAppMissing(packageName, developer)\n\t\t\t: error;\n\n\t// Listing takes no paging: Play says \"Pagination is not currently\n\t// available\" unless asked for every user at once.\n\tconst { users: listed = [] } = await client.request<{ users?: PlayUser[] }>(\n\t\t'GET',\n\t\t`${users}?pageSize=-1`,\n\t);\n\tconst user = listed.find((candidate) => candidate.email === email);\n\n\tif (!user) {\n\t\tawait client\n\t\t\t.request('POST', users, {\n\t\t\t\temail,\n\t\t\t\tgrants: [{ packageName, appLevelPermissions: permissions }],\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tthrow missing(error);\n\t\t\t});\n\t\treturn 'invited';\n\t}\n\n\tconst grant = user.grants?.find((g) => g.packageName === packageName);\n\tconst grantPath = `${users}/${encodeURIComponent(email)}/grants`;\n\tif (!grant) {\n\t\tawait client\n\t\t\t.request('POST', grantPath, {\n\t\t\t\tpackageName,\n\t\t\t\tappLevelPermissions: permissions,\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tthrow missing(error);\n\t\t\t});\n\t\treturn 'granted';\n\t}\n\tconst had = [...(grant.appLevelPermissions ?? [])].sort();\n\tif (had.join() === permissions.join()) return 'unchanged';\n\tawait client.request(\n\t\t'PATCH',\n\t\t`${grantPath}/${packageName}?updateMask=appLevelPermissions`,\n\t\t{ appLevelPermissions: permissions },\n\t);\n\treturn 'updated';\n}\n\n/** A service account key file, as Google writes it. */\nexport interface ServiceAccountJson {\n\tclient_email: string;\n\tprivate_key: string;\n\ttoken_uri?: string;\n}\n\n/** An access token for the key itself: a signed JWT, exchanged. */\nexport async function keyToken(key: ServiceAccountJson): Promise<string> {\n\tconst tokenUri = key.token_uri ?? 'https://oauth2.googleapis.com/token';\n\tconst now = Math.floor(Date.now() / 1000);\n\tconst encode = (value: object) =>\n\t\tBuffer.from(JSON.stringify(value)).toString('base64url');\n\tconst unsigned = `${encode({ alg: 'RS256', typ: 'JWT' })}.${encode({\n\t\tiss: key.client_email,\n\t\tscope: 'https://www.googleapis.com/auth/androidpublisher',\n\t\taud: tokenUri,\n\t\tiat: now,\n\t\texp: now + 600,\n\t})}`;\n\tconst signature = createSign('RSA-SHA256')\n\t\t.update(unsigned)\n\t\t.sign(key.private_key)\n\t\t.toString('base64url');\n\tconst response = await fetch(tokenUri, {\n\t\tmethod: 'POST',\n\t\theaders: { 'content-type': 'application/x-www-form-urlencoded' },\n\t\tbody: new URLSearchParams({\n\t\t\tgrant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',\n\t\t\tassertion: `${unsigned}.${signature}`,\n\t\t}),\n\t});\n\tconst body = (await response.json().catch(() => ({}))) as {\n\t\taccess_token?: string;\n\t\terror_description?: string;\n\t};\n\tif (!response.ok || !body.access_token) {\n\t\tthrow new PlayKeyUnverified(\n\t\t\tkey.client_email,\n\t\t\tbody.error_description ?? `token exchange answered ${response.status}`,\n\t\t);\n\t}\n\treturn body.access_token;\n}\n\n/**\n * Proof the key and its grant work: as the key, open an edit on the app and\n * discard it — what EAS Submit's first call is.\n *\n * @throws {PlayKeyUnverified}\n */\nexport async function verifyKey(\n\tkey: ServiceAccountJson,\n\tpackageName: string,\n): Promise<void> {\n\tconst client = googleClient(await keyToken(key));\n\ttry {\n\t\tconst edit = await client.request<{ id: string }>(\n\t\t\t'POST',\n\t\t\t`${PLAY}/applications/${packageName}/edits`,\n\t\t\t{},\n\t\t);\n\t\tawait client.request(\n\t\t\t'DELETE',\n\t\t\t`${PLAY}/applications/${packageName}/edits/${edit.id}`,\n\t\t);\n\t} catch (error) {\n\t\tif (error instanceof GoogleApiError) {\n\t\t\tthrow new PlayKeyUnverified(key.client_email, error.detail);\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/** The image kinds Play's listing takes, as fastlane supply names them. */\nconst IMAGE_TYPES = [\n\t'icon',\n\t'featureGraphic',\n\t'promoGraphic',\n\t'tvBanner',\n\t'phoneScreenshots',\n\t'sevenInchScreenshots',\n\t'tenInchScreenshots',\n\t'tvScreenshots',\n\t'wearScreenshots',\n] as const;\n\n/** One locale's listing, read from `store/play/listings/<locale>/`. */\nexport interface PlayListing {\n\tlanguage: string;\n\ttitle?: string;\n\tshortDescription?: string;\n\tfullDescription?: string;\n\tvideo?: string;\n\t/** Each image kind's files, in order. */\n\timages: Partial<Record<(typeof IMAGE_TYPES)[number], string[]>>;\n}\n\n/** The store listing kept beside the app, in fastlane supply's layout. */\nexport interface PlayStore {\n\tlistings: PlayListing[];\n\t/** `store/play/data-safety.csv`: Play Console's data safety export. */\n\tdataSafety?: string;\n}\n\n/**\n * `<app>/store/play`, read: undefined where there is none.\n *\n * ```\n * store/play/\n * data-safety.csv\n * listings/en-US/title.txt, short_description.txt, full_description.txt, video.txt\n * listings/en-US/images/icon.png, featureGraphic.png\n * listings/en-US/images/phoneScreenshots/1.png, 2.png …\n * ```\n */\nexport function readPlayStore(appDir: string): PlayStore | undefined {\n\tconst root = join(appDir, 'store', 'play');\n\tif (!existsSync(root)) return undefined;\n\tconst text = (path: string) =>\n\t\texistsSync(path) ? readFileSync(path, 'utf8').trim() : undefined;\n\n\tconst listings: PlayListing[] = [];\n\tconst listingsDir = join(root, 'listings');\n\tfor (const language of existsSync(listingsDir)\n\t\t? readdirSync(listingsDir).sort()\n\t\t: []) {\n\t\tconst dir = join(listingsDir, language);\n\t\tif (!statSync(dir).isDirectory()) continue;\n\t\tconst images: PlayListing['images'] = {};\n\t\tconst imagesDir = join(dir, 'images');\n\t\tfor (const type of IMAGE_TYPES) {\n\t\t\tconst single = ['.png', '.jpg', '.jpeg']\n\t\t\t\t.map((ext) => join(imagesDir, `${type}${ext}`))\n\t\t\t\t.find(existsSync);\n\t\t\tconst many = join(imagesDir, type);\n\t\t\tconst files = single\n\t\t\t\t? [single]\n\t\t\t\t: existsSync(many)\n\t\t\t\t\t? readdirSync(many)\n\t\t\t\t\t\t\t.filter((f) => /\\.(png|jpe?g)$/i.test(f))\n\t\t\t\t\t\t\t.sort()\n\t\t\t\t\t\t\t.map((f) => join(many, f))\n\t\t\t\t\t: [];\n\t\t\tif (files.length > 0) images[type] = files;\n\t\t}\n\t\tconst listing: PlayListing = { language, images };\n\t\tconst title = text(join(dir, 'title.txt'));\n\t\tconst shortDescription = text(join(dir, 'short_description.txt'));\n\t\tconst fullDescription = text(join(dir, 'full_description.txt'));\n\t\tconst video = text(join(dir, 'video.txt'));\n\t\tif (title) listing.title = title;\n\t\tif (shortDescription) listing.shortDescription = shortDescription;\n\t\tif (fullDescription) listing.fullDescription = fullDescription;\n\t\tif (video) listing.video = video;\n\t\tlistings.push(listing);\n\t}\n\n\tconst dataSafety = text(join(root, 'data-safety.csv'));\n\treturn { listings, ...(dataSafety ? { dataSafety } : {}) };\n}\n\n/**\n * Push the listing through one edit, committed: each locale's text, and each\n * image kind replaced by the files kept. Then the data safety form, which\n * Play takes outside an edit. Answers whether the listing was pushed: an\n * app that has never had an upload may refuse an edit, and that is left for\n * the next run, not failed.\n */\nexport async function pushPlayStore(\n\tclient: GoogleClient,\n\tpackageName: string,\n\tstore: PlayStore,\n): Promise<{ listing: boolean; dataSafety: boolean; reason?: string }> {\n\tconst app = `${PLAY}/applications/${packageName}`;\n\tlet listing = false;\n\tlet reason: string | undefined;\n\tif (store.listings.length > 0) {\n\t\tlet edit: { id: string } | undefined;\n\t\ttry {\n\t\t\tedit = await client.request<{ id: string }>('POST', `${app}/edits`, {});\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof GoogleApiError)) throw error;\n\t\t\treason = error.detail;\n\t\t}\n\t\tif (edit) {\n\t\t\tconst base = `${app}/edits/${edit.id}/listings`;\n\t\t\tfor (const entry of store.listings) {\n\t\t\t\tconst { images, ...text } = entry;\n\t\t\t\tif (text.title || text.shortDescription || text.fullDescription) {\n\t\t\t\t\tawait client.request('PUT', `${base}/${entry.language}`, text);\n\t\t\t\t}\n\t\t\t\tfor (const [type, files] of Object.entries(images)) {\n\t\t\t\t\tawait client.request('DELETE', `${base}/${entry.language}/${type}`);\n\t\t\t\t\tfor (const file of files ?? []) {\n\t\t\t\t\t\tawait client.request(\n\t\t\t\t\t\t\t'POST',\n\t\t\t\t\t\t\t`${PLAY_UPLOAD}/applications/${packageName}/edits/${edit.id}/listings/${entry.language}/${type}?uploadType=media`,\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\traw: {\n\t\t\t\t\t\t\t\t\tcontentType:\n\t\t\t\t\t\t\t\t\t\textname(file).toLowerCase() === '.png'\n\t\t\t\t\t\t\t\t\t\t\t? 'image/png'\n\t\t\t\t\t\t\t\t\t\t\t: 'image/jpeg',\n\t\t\t\t\t\t\t\t\tdata: readFileSync(file),\n\t\t\t\t\t\t\t\t},\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}\n\t\t\t}\n\t\t\tawait client.request('POST', `${app}/edits/${edit.id}:commit`);\n\t\t\tlisting = true;\n\t\t}\n\t}\n\n\tlet dataSafety = false;\n\tif (store.dataSafety) {\n\t\tawait client.request('POST', `${app}/dataSafety`, {\n\t\t\tsafetyLabels: store.dataSafety,\n\t\t});\n\t\tdataSafety = true;\n\t}\n\treturn { listing, dataSafety, ...(reason ? { reason } : {}) };\n}\n\n/** What Play Console only takes by hand, for the person to tick off. */\nexport const PLAY_CONSOLE_CHECKLIST = [\n\t'App content → Privacy policy: the URL of the published policy',\n\t'App content → App access: how a reviewer signs in',\n\t'App content → Ads: whether the app shows ads',\n\t'App content → Content rating: the questionnaire',\n\t'App content → Target audience and content',\n\t'App content → Health apps / Health Connect, where the app reads health data',\n\t'App content → Sensitive permissions, where the app asks for any',\n\t'Release → the first upload of a new app, by hand',\n];\n","/**\n * `gkm deploy:google-play`: what EAS Submit needs to publish a `MobileApp`\n * to Google Play, set up in one run — the counterpart of `gkm deploy:github`\n * for the AWS side.\n *\n * 1. Each deployed stage's track and release status into `eas.json`\n * (`submit.<stage>.android`), from `mobileStage`.\n * 2. Google: the project (`--project`, else `<workspace>-play`, made when\n * absent) with the Android Publisher API on, and the service account\n * `<workspace>-play` in it, found or made.\n * 3. Play Console: the account invited with a grant on the app alone, its\n * permissions following the stages' tracks — production releases only\n * when a stage submits there. An app not in Play Console yet is a step\n * only a person can take; interactively, the run says so and waits.\n * 4. A new JSON key, held in memory: uploaded to EAS, assigned to the app's\n * Android credentials for EAS Submit, and proved by opening and\n * discarding an edit with it. Only then are the account's older keys\n * deleted, from EAS and from Google — a failed run leaves the old key\n * working.\n * 5. The store listing kept beside the app (`store/play/`), pushed.\n * 6. What Play Console only takes by hand, as a checklist.\n *\n * Running it again rotates the key and pushes the listing.\n */\n\nimport { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { delimiter, join } from 'node:path';\nimport { loadWorkspaceConfig } from '../../config.js';\nimport { GkmError } from '../../errors';\nimport { loadStage } from '../../exec/stage.js';\nimport { canPrompt } from '../../prompt.js';\nimport { chooseMobileApp, withStageProfiles } from '../eas.js';\nimport { mobileStage } from '../stage.js';\nimport { type EasApi, easApi } from './easApi.js';\nimport {\n\tassertGoogleId,\n\tcreateKey,\n\tdeleteKey,\n\tenablePublisherApi,\n\tensureProject,\n\tensureServiceAccount,\n\tkeyId,\n\tlistKeys,\n\tplayId,\n} from './gcp.js';\nimport {\n\ttype GoogleClient,\n\ttype GoogleSignIn,\n\tgcloudSignIn,\n\tgoogleClient,\n} from './google.js';\nimport {\n\tensurePlayAccess,\n\tPLAY_CONSOLE_CHECKLIST,\n\tPlayAppMissing,\n\tPlayKeyUnverified,\n\tplayPermissions,\n\tpushPlayStore,\n\treadPlayStore,\n\ttype ServiceAccountJson,\n\tverifyKey,\n} from './play.js';\n\nconst logger = console;\n\n/** No Play developer account to act in. */\nexport class PlayDeveloperMissing extends GkmError {\n\tconstructor() {\n\t\tsuper(\n\t\t\t'Name the Play developer account: --developer <id>. It is the number in ' +\n\t\t\t\t\"Play Console's address: https://play.google.com/console/developers/<id>/….\",\n\t\t);\n\t\tthis.name = 'PlayDeveloperMissing';\n\t}\n}\n\n/** The app's Expo config has no Android package, or no EAS project. */\nexport class ExpoConfigIncomplete extends GkmError {\n\tconstructor(\n\t\treadonly app: string,\n\t\treadonly missing: 'android.package' | 'extra.eas.projectId',\n\t) {\n\t\tsuper(\n\t\t\tmissing === 'android.package'\n\t\t\t\t? `'${app}' has no android.package in its Expo config: Play knows an app ` +\n\t\t\t\t\t\t\"by its package. Set it in app.config.ts: android: { package: 'com.acme.shop' }.\"\n\t\t\t\t: `'${app}' has no extra.eas.projectId in its Expo config: it is not ` +\n\t\t\t\t\t\t'linked to an EAS project. Run `eas init` in the app.',\n\t\t);\n\t\tthis.name = 'ExpoConfigIncomplete';\n\t}\n}\n\n/** `expo config` could not read the app's config. */\nexport class ExpoConfigFailed extends GkmError {\n\tconstructor(\n\t\treadonly dir: string,\n\t\treadonly detail: string,\n\t) {\n\t\tsuper(\n\t\t\t`Could not read the Expo config in ${dir} (${detail}). Check that ` +\n\t\t\t\t'`npx expo config --json` works there.',\n\t\t);\n\t\tthis.name = 'ExpoConfigFailed';\n\t}\n}\n\n/** The workspace deploys no stage. */\nexport class NoDeployedStage extends GkmError {\n\tconstructor() {\n\t\tsuper(\n\t\t\t'gkm.config.ts deploys no stage, so there is nothing to publish to: add one to stages.deployed.',\n\t\t);\n\t\tthis.name = 'NoDeployedStage';\n\t}\n}\n\n/** What the run needs of the app's Expo config. */\nexport interface ExpoAppConfig {\n\tname?: string;\n\tandroid?: { package?: string };\n\textra?: { eas?: { projectId?: string } };\n}\n\nexport interface GooglePlayDeps {\n\tsignIn: GoogleSignIn;\n\teas: EasApi;\n\t/** The app's Expo config, evaluated with the values its build reads. */\n\texpoConfig: (\n\t\tdir: string,\n\t\troot: string,\n\t\tenv: Readonly<Record<string, string>>,\n\t) => Promise<ExpoAppConfig>;\n\t/** Whether a person is here: to sign in, and to create the app. */\n\tinteractive: boolean;\n\t/** Wait between two looks for the app, and two tries of the new key. */\n\tsleep: (ms: number) => Promise<void>;\n}\n\n/** `expo config --json`, run with the app's Expo — its own, or the workspace's. */\nexport function expoConfig(\n\tdir: string,\n\troot: string,\n\tenv: Readonly<Record<string, string>>,\n): Promise<ExpoAppConfig> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = spawn('expo', ['config', '--json', '--type', 'public'], {\n\t\t\tcwd: dir,\n\t\t\tstdio: ['ignore', 'pipe', 'pipe'],\n\t\t\tenv: {\n\t\t\t\t...process.env,\n\t\t\t\t...env,\n\t\t\t\tPATH: [\n\t\t\t\t\tjoin(dir, 'node_modules', '.bin'),\n\t\t\t\t\tjoin(root, 'node_modules', '.bin'),\n\t\t\t\t\tprocess.env.PATH,\n\t\t\t\t].join(delimiter),\n\t\t\t},\n\t\t});\n\t\tlet stdout = '';\n\t\tlet stderr = '';\n\t\tchild.stdout.on('data', (chunk: Buffer) => {\n\t\t\tstdout += chunk.toString();\n\t\t});\n\t\tchild.stderr.on('data', (chunk: Buffer) => {\n\t\t\tstderr += chunk.toString();\n\t\t});\n\t\tchild.on('error', (error) =>\n\t\t\treject(new ExpoConfigFailed(dir, error.message)),\n\t\t);\n\t\tchild.on('close', (code) => {\n\t\t\tif (code !== 0) {\n\t\t\t\treject(new ExpoConfigFailed(dir, stderr.trim() || `exit ${code}`));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tresolve(JSON.parse(stdout) as ExpoAppConfig);\n\t\t\t} catch {\n\t\t\t\treject(new ExpoConfigFailed(dir, `no JSON: ${stdout.slice(0, 200)}`));\n\t\t\t}\n\t\t});\n\t});\n}\n\nexport const defaultGooglePlayDeps: GooglePlayDeps = {\n\tsignIn: gcloudSignIn(),\n\teas: easApi(),\n\texpoConfig,\n\tinteractive: canPrompt(),\n\tsleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),\n};\n\nexport interface GooglePlayOptions {\n\t/** The mobile app; the one here, or the only one, if not. */\n\tapp?: string;\n\t/** The Google Cloud project: `<workspace>-play` by default. */\n\tproject?: string;\n\t/** The Play developer account's id. */\n\tdeveloper?: string;\n\t/**\n\t * The stage whose values evaluate the app's Expo config: the protected\n\t * one, else the first deployed.\n\t */\n\tstage?: string;\n\t/** The AWS profile for that stage's account, where its secrets are kept. */\n\tprofile?: string;\n\tcwd?: string;\n}\n\nexport interface GooglePlayResult {\n\tpackageName: string;\n\tproject: string;\n\temail: string;\n\tpermissions: string[];\n\taccess: 'invited' | 'granted' | 'updated' | 'unchanged';\n\t/** The new key's id, in Google and in EAS. */\n\tkey: { google: string; eas: string };\n\t/** The older keys deleted. */\n\tdeleted: { google: string[]; eas: string[] };\n\tlisting:\n\t\t| { listing: boolean; dataSafety: boolean; reason?: string }\n\t\t| undefined;\n}\n\n/**\n * Set up publishing a mobile app to Google Play.\n *\n * @throws {PlayDeveloperMissing}, {ExpoConfigIncomplete}, {PlayAppMissing},\n * {PlayKeyUnverified} — and what each step's API throws\n */\nexport async function deployGooglePlay(\n\toptions: GooglePlayOptions,\n\tdeps: GooglePlayDeps = defaultGooglePlayDeps,\n): Promise<GooglePlayResult> {\n\tif (!options.developer) throw new PlayDeveloperMissing();\n\tconst developer = options.developer;\n\n\t// The stage only evaluates the Expo config: any deployed one's values do.\n\tconst declared = (await loadWorkspaceConfig(options.cwd)).workspace.stages;\n\tconst stageName =\n\t\toptions.stage ?? declared.protected?.[0] ?? declared.deployed[0];\n\tif (!stageName) throw new NoDeployedStage();\n\tconst loaded = await loadStage({\n\t\tstage: stageName,\n\t\t...(options.cwd ? { cwd: options.cwd } : {}),\n\t\t...(options.profile ? { profile: options.profile } : {}),\n\t});\n\tconst { workspace, manifest, stack } = loaded;\n\tconst declaration = chooseMobileApp(manifest, options.app, loaded.appName);\n\tconst name = declaration.id;\n\tconst dir = join(workspace.root, declaration.app.path);\n\tconst values =\n\t\tstack.mobileApps.find((candidate) => candidate.id === declaration.id)\n\t\t\t?.values ?? {};\n\n\tconst config = await deps.expoConfig(dir, workspace.root, values);\n\tconst packageName = config.android?.package;\n\tif (!packageName) throw new ExpoConfigIncomplete(name, 'android.package');\n\tconst projectId = config.extra?.eas?.projectId;\n\tif (!projectId) throw new ExpoConfigIncomplete(name, 'extra.eas.projectId');\n\n\t// 1. Each stage's track, in eas.json — and the tracks the grant follows.\n\tconst stages = workspace.stages.deployed.map((stage) =>\n\t\tmobileStage(workspace, declaration, stage),\n\t);\n\tconst easJsonPath = join(dir, 'eas.json');\n\tconst before = existsSync(easJsonPath)\n\t\t? JSON.parse(await readFile(easJsonPath, 'utf8'))\n\t\t: {};\n\tconst after = stages.reduce(withStageProfiles, before);\n\tif (JSON.stringify(before) !== JSON.stringify(after)) {\n\t\tawait writeFile(easJsonPath, `${JSON.stringify(after, null, 2)}\\n`);\n\t\tlogger.log(`📝 ${easJsonPath}: each stage's build and submit profiles`);\n\t}\n\tconst store = readPlayStore(dir);\n\tconst permissions = playPermissions({\n\t\ttracks: stages.map((stage) => stage.android.track),\n\t\tlisting: (store?.listings.length ?? 0) > 0,\n\t});\n\n\t// 2. Google: signed in as a Play Console admin, the project and account.\n\tconst project = options.project ?? playId(workspace.name);\n\tassertGoogleId('project', project);\n\tconst account = playId(workspace.name);\n\tconst token = await deps.signIn.token({ interactive: deps.interactive });\n\tconst bare: GoogleClient = googleClient(token);\n\tconst created = await ensureProject(bare, project, `${workspace.name} Play`);\n\tlogger.log(\n\t\t`☁️ Google Cloud project ${project}${created ? ' (created)' : ''}`,\n\t);\n\tconst client = googleClient(token, project);\n\tawait enablePublisherApi(client, project);\n\tconst email = await ensureServiceAccount(\n\t\tclient,\n\t\tproject,\n\t\taccount,\n\t\t`${workspace.name} publishing (gkm)`,\n\t);\n\tlogger.log(`🤖 Service account ${email}`);\n\n\t// 3. Play Console: the app grant, waiting for the app where someone can\n\t// make it.\n\tlet access: GooglePlayResult['access'] | undefined;\n\tfor (let attempt = 0; !access; attempt++) {\n\t\ttry {\n\t\t\taccess = await ensurePlayAccess(client, {\n\t\t\t\tdeveloper,\n\t\t\t\temail,\n\t\t\t\tpackageName,\n\t\t\t\tpermissions,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof PlayAppMissing) || !deps.interactive) throw error;\n\t\t\tif (attempt === 0) {\n\t\t\t\tlogger.log(`\\n⏳ ${error.message}\\n Waiting for it…`);\n\t\t\t}\n\t\t\tawait deps.sleep(15_000);\n\t\t}\n\t}\n\tlogger.log(\n\t\t`🎟️ Play access on ${packageName}: ${access} (${permissions.join(', ')})`,\n\t);\n\n\t// 4. A new key: to EAS, proved, and only then the old ones gone.\n\tconst older = await listKeys(client, project, email);\n\tconst key = await createKey(client, project, email);\n\tconst json = JSON.parse(key.json) as ServiceAccountJson &\n\t\tRecord<string, unknown>;\n\tconst easProject = await deps.eas.project(projectId);\n\tconst credentials = await deps.eas.androidCredentials(\n\t\t{ projectId, fullName: easProject.fullName },\n\t\tpackageName,\n\t);\n\tconst easKey = await deps.eas.createKey(easProject.accountId, json);\n\tawait deps.eas.useForSubmissions(credentials.id, easKey.id);\n\tlogger.log(\n\t\t`🔑 New key ${keyId(key)} assigned to EAS Submit for ${packageName}`,\n\t);\n\n\t// A new grant takes a moment to reach Play.\n\tfor (let attempt = 0; ; attempt++) {\n\t\ttry {\n\t\t\tawait verifyKey(json, packageName);\n\t\t\tbreak;\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof PlayKeyUnverified) || attempt >= 5) throw error;\n\t\t\tawait deps.sleep(10_000);\n\t\t}\n\t}\n\tlogger.log('✅ The key opens an edit on the app');\n\n\tconst easOlder = (await deps.eas.keys(easProject.accountName)).filter(\n\t\t(candidate) =>\n\t\t\tcandidate.clientEmail === email && candidate.id !== easKey.id,\n\t);\n\tfor (const old of easOlder) await deps.eas.deleteKey(old.id);\n\tfor (const old of older) await deleteKey(client, old);\n\tif (older.length + easOlder.length > 0) {\n\t\tlogger.log(\n\t\t\t`🧹 Deleted ${older.length} older key(s) from Google, ${easOlder.length} from EAS`,\n\t\t);\n\t}\n\n\t// 5. The listing, where the workspace keeps one.\n\tconst listing = store\n\t\t? await pushPlayStore(client, packageName, store)\n\t\t: undefined;\n\tif (listing?.listing) logger.log('🛍️ Store listing pushed');\n\tif (store && !listing?.listing && listing?.reason) {\n\t\tlogger.log(\n\t\t\t`⏭️ Store listing not pushed yet (${listing.reason}): run this again after the app's first upload`,\n\t\t);\n\t}\n\tif (listing?.dataSafety) logger.log('🛡️ Data safety pushed');\n\n\t// 6. What only a person can do.\n\tlogger.log('\\nLeft to do in Play Console, by hand:');\n\tfor (const item of PLAY_CONSOLE_CHECKLIST) logger.log(` [ ] ${item}`);\n\n\treturn {\n\t\tpackageName,\n\t\tproject,\n\t\temail,\n\t\tpermissions,\n\t\taccess,\n\t\tkey: { google: keyId(key), eas: easKey.id },\n\t\tdeleted: {\n\t\t\tgoogle: older.map(keyId),\n\t\t\teas: easOlder.map((candidate) => candidate.id),\n\t\t},\n\t\tlisting,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAaA,MAAa,cAAc;;AAG3B,IAAa,mBAAb,cAAsCA,eAAAA,SAAS;CAC9C,cAAc;EACb,MACC,gKAGD;EACA,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,cAAb,cAAiCA,eAAAA,SAAS;CAE/B;CACA;CAFV,YACC,WACA,QACC;EACD,MAAM,eAAe,UAAU,IAAI,QAAQ;EAHlC,KAAA,YAAA;EACA,KAAA,SAAA;EAGT,KAAK,OAAO;CACb;AAC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AI,MAAM,SAAS,SAAS,SAAS,GACpC,OAAO,IACN,cAAc,MAAM,OAAO,6BAA6B,SAAS,OAAO,UACzE;CAID,MAAM,UAAU,QACb,MAAM,cAAc,QAAQ,aAAa,KAAK,IAC9C,KAAA;CACH,IAAI,SAAS,SAAS,OAAO,IAAI,2BAA2B;CAC5D,IAAI,SAAS,CAAC,SAAS,WAAW,SAAS,QAC1C,OAAO,IACN,qCAAqC,QAAQ,OAAO,+CACrD;CAED,IAAI,SAAS,YAAY,OAAO,IAAI,yBAAyB;CAG7D,OAAO,IAAI,wCAAwC;CACnD,KAAK,MAAM,QAAQ,wBAAwB,OAAO,IAAI,SAAS,MAAM;CAErE,OAAO;EACN;EACA;EACA;EACA;EACA;EACA,KAAK;GAAE,QAAQ,MAAM,GAAG;GAAG,KAAK,OAAO;EAAG;EAC1C,SAAS;GACR,QAAQ,MAAM,IAAI,KAAK;GACvB,KAAK,SAAS,KAAK,cAAc,UAAU,EAAE;EAC9C;EACA;CACD;AACD"}
@@ -1,5 +1,5 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
- const require_workspace = require("./workspace-Ciw3SnME.cjs");
2
+ const require_workspace = require("./workspace-CEpojAus.cjs");
3
3
  let _geekmidas_storage_s3_url = require("@geekmidas/storage/s3-url");
4
4
  _geekmidas_storage_s3_url = require_rolldown_runtime.__toESM(_geekmidas_storage_s3_url, 1);
5
5
  //#region src/providers/s3/policy.ts
@@ -518,4 +518,4 @@ Object.defineProperty(exports, "whileKeyIsNew", {
518
518
  }
519
519
  });
520
520
 
521
- //# sourceMappingURL=iam-C2sf6AUi.cjs.map
521
+ //# sourceMappingURL=iam-BoYPPNdM.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"iam-C2sf6AUi.cjs","names":["IamUserNotOwned","IAM_USER_PATH","s3Url","BucketKeySetElsewhere","RotationInProgress","AccessKeyLimit"],"sources":["../src/providers/s3/policy.ts","../src/providers/iam.ts"],"sourcesContent":["/**\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 for\n * what the `s3` provider gives each bucket and the deploy gives a stage's\n * backups, as an `smtp://` one for the `ses` mail provider.\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\n/**\n * The secret a user's access key is written into, and how: an `s3://` URL\n * for a bucket ({@link s3KeySecret}), an `smtp://` one for mail.\n */\nexport interface KeySecret {\n\t/** The secret's key: `UPLOADS_URL`, `BACKUPS_URL`, `MAIL_URL`. */\n\tkey: string;\n\t/**\n\t * The access key a stored value holds — or `undefined` when it holds\n\t * none this user could have issued for it, so a new one is.\n\t *\n\t * @throws when the value is another resource's, set by hand\n\t */\n\tkeyIdOf(value: string): string | undefined;\n\t/** The value for a newly issued key. */\n\tvalue(accessKeyId: string, secretAccessKey: string): string;\n\t/**\n\t * A value holding the right key whose address drifted: what it should\n\t * be, and the change line. `undefined` when it is right.\n\t */\n\trepair?(value: string): { value: string; change: string } | undefined;\n}\n\n/**\n * A bucket's URL as a key's secret: `s3://KEY:SECRET@bucket?region=…`.\n *\n * @throws {BucketKeySetElsewhere} from `keyIdOf`, when the URL names another bucket\n */\nexport function s3KeySecret(\n\tctx: Pick<KeyContext, 'stage'>,\n\tclients: Pick<IamClients, 'region' | 'endpoint'>,\n\tinput: { bucket: string; urlKey: string },\n): KeySecret {\n\tconst { bucket, urlKey } = input;\n\tconst parse = (value: string) => {\n\t\tlet parsed: s3Url.S3Address | undefined;\n\t\ttry {\n\t\t\tparsed = s3Url.parse(value);\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 ?? value.replace(/\\/\\/[^@]*@/, '//'),\n\t\t\t\tctx.stage,\n\t\t\t);\n\t\t}\n\t\treturn parsed;\n\t};\n\treturn {\n\t\tkey: urlKey,\n\t\tkeyIdOf: (value) => parse(value).accessKeyId,\n\t\tvalue: (accessKeyId, secretAccessKey) =>\n\t\t\ts3Url.build({\n\t\t\t\tbucket,\n\t\t\t\tregion: clients.region,\n\t\t\t\t...(clients.endpoint\n\t\t\t\t\t? { endpoint: clients.endpoint, forcePathStyle: true }\n\t\t\t\t\t: {}),\n\t\t\t\taccessKeyId,\n\t\t\t\tsecretAccessKey,\n\t\t\t}),\n\t\trepair(value) {\n\t\t\t// The key is good; the address must name where the bucket is.\n\t\t\tconst address = parse(value);\n\t\t\tif (address.region === clients.region) return undefined;\n\t\t\treturn {\n\t\t\t\tvalue: s3Url.build({ ...address, region: clients.region }),\n\t\t\t\tchange: `name ${clients.region}, the bucket's region (it said ${address.region ?? 'none'})`,\n\t\t\t};\n\t\t},\n\t};\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/** Where the key is written. */\n\tsecret: KeySecret;\n}\n\n/**\n * The user's access key, in the stage's secrets as `secret` writes it.\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 whatever `secret.keyIdOf` throws for a value set elsewhere\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, user, secret } = input;\n\tconst entryKey = `iam-access-key:${id}`;\n\tconst record = ctx.state.record(entryKey);\n\n\tconst given = ctx.secrets[secret.key];\n\tconst inUrl = given !== undefined ? secret.keyIdOf(given) : undefined;\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\tconst repaired = given !== undefined ? secret.repair?.(given) : undefined;\n\t\tif (repaired) {\n\t\t\tawait ctx.change(\n\t\t\t\t{ construct: id, resource: secret.key, change: repaired.change },\n\t\t\t\t() => ctx.writeSecrets({ [secret.key]: repaired.value }),\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[secret.key]: secret.value(key.AccessKeyId!, key.SecretAccessKey!),\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` ${secret.key} 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();\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,MAAM,MAAM,KAAK,IAAI,IAAI,KAAK,MAAM,QAAQ;CAC5C,OAAO,OAAO,KAAK,MAAM,oBAAoB,WAAW,KAAA;AACzD;;;;;;AAOA,eAAsB,cACrB,OACA,SAOyC;CACzC,IAAI,SAAS;CACb,IAAI,SAAS;CACb,IAAI,CAAC,QAAQ,YAAY,CAAC,QAAQ,QAAQ,MAAM,GAAG,OAAO;EAAE;EAAQ;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"}
1
+ {"version":3,"file":"iam-BoYPPNdM.cjs","names":["IamUserNotOwned","IAM_USER_PATH","s3Url","BucketKeySetElsewhere","RotationInProgress","AccessKeyLimit"],"sources":["../src/providers/s3/policy.ts","../src/providers/iam.ts"],"sourcesContent":["/**\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 for\n * what the `s3` provider gives each bucket and the deploy gives a stage's\n * backups, as an `smtp://` one for the `ses` mail provider.\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\n/**\n * The secret a user's access key is written into, and how: an `s3://` URL\n * for a bucket ({@link s3KeySecret}), an `smtp://` one for mail.\n */\nexport interface KeySecret {\n\t/** The secret's key: `UPLOADS_URL`, `BACKUPS_URL`, `MAIL_URL`. */\n\tkey: string;\n\t/**\n\t * The access key a stored value holds — or `undefined` when it holds\n\t * none this user could have issued for it, so a new one is.\n\t *\n\t * @throws when the value is another resource's, set by hand\n\t */\n\tkeyIdOf(value: string): string | undefined;\n\t/** The value for a newly issued key. */\n\tvalue(accessKeyId: string, secretAccessKey: string): string;\n\t/**\n\t * A value holding the right key whose address drifted: what it should\n\t * be, and the change line. `undefined` when it is right.\n\t */\n\trepair?(value: string): { value: string; change: string } | undefined;\n}\n\n/**\n * A bucket's URL as a key's secret: `s3://KEY:SECRET@bucket?region=…`.\n *\n * @throws {BucketKeySetElsewhere} from `keyIdOf`, when the URL names another bucket\n */\nexport function s3KeySecret(\n\tctx: Pick<KeyContext, 'stage'>,\n\tclients: Pick<IamClients, 'region' | 'endpoint'>,\n\tinput: { bucket: string; urlKey: string },\n): KeySecret {\n\tconst { bucket, urlKey } = input;\n\tconst parse = (value: string) => {\n\t\tlet parsed: s3Url.S3Address | undefined;\n\t\ttry {\n\t\t\tparsed = s3Url.parse(value);\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 ?? value.replace(/\\/\\/[^@]*@/, '//'),\n\t\t\t\tctx.stage,\n\t\t\t);\n\t\t}\n\t\treturn parsed;\n\t};\n\treturn {\n\t\tkey: urlKey,\n\t\tkeyIdOf: (value) => parse(value).accessKeyId,\n\t\tvalue: (accessKeyId, secretAccessKey) =>\n\t\t\ts3Url.build({\n\t\t\t\tbucket,\n\t\t\t\tregion: clients.region,\n\t\t\t\t...(clients.endpoint\n\t\t\t\t\t? { endpoint: clients.endpoint, forcePathStyle: true }\n\t\t\t\t\t: {}),\n\t\t\t\taccessKeyId,\n\t\t\t\tsecretAccessKey,\n\t\t\t}),\n\t\trepair(value) {\n\t\t\t// The key is good; the address must name where the bucket is.\n\t\t\tconst address = parse(value);\n\t\t\tif (address.region === clients.region) return undefined;\n\t\t\treturn {\n\t\t\t\tvalue: s3Url.build({ ...address, region: clients.region }),\n\t\t\t\tchange: `name ${clients.region}, the bucket's region (it said ${address.region ?? 'none'})`,\n\t\t\t};\n\t\t},\n\t};\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/** Where the key is written. */\n\tsecret: KeySecret;\n}\n\n/**\n * The user's access key, in the stage's secrets as `secret` writes it.\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 whatever `secret.keyIdOf` throws for a value set elsewhere\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, user, secret } = input;\n\tconst entryKey = `iam-access-key:${id}`;\n\tconst record = ctx.state.record(entryKey);\n\n\tconst given = ctx.secrets[secret.key];\n\tconst inUrl = given !== undefined ? secret.keyIdOf(given) : undefined;\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\tconst repaired = given !== undefined ? secret.repair?.(given) : undefined;\n\t\tif (repaired) {\n\t\t\tawait ctx.change(\n\t\t\t\t{ construct: id, resource: secret.key, change: repaired.change },\n\t\t\t\t() => ctx.writeSecrets({ [secret.key]: repaired.value }),\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[secret.key]: secret.value(key.AccessKeyId!, key.SecretAccessKey!),\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` ${secret.key} 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,aAAa,WAAmB,gBAAgB;;;;;;;;;AAUtD,SAAgB,WACf,QACA,UAQI,CAAC,GACY;CACjB,OAAO;EACN,SAAS;EACT,WAAW;GACV;IACC,KAAK;IACL,QAAQ;IACR,QAAQ;KACP;KACA;KACA;KACA;KACA;KACA,GAAI,QAAQ,aAAa,CAAC,qBAAqB,IAAI,CAAC;IACrD;IACA,UAAU,GAAG,UAAU,MAAM,EAAE;GAChC;GACA;IACC,KAAK;IACL,QAAQ;IACR,QAAQ;KACP;KACA;KACA;IACD;IACA,UAAU,UAAU,MAAM;GAC3B;GACA,GAAI,QAAQ,iBACT,CACA;IACC,KAAK;IACL,QAAQ;IACR,QAAQ;IACR,UAAU,QAAQ;GACnB,CACD,IACC,CAAC;EACL;CACD;AACD;;;;;;;AAQ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, mt as BucketKeySetElsewhere, pt as AccessKeyLimit, tt as IAM_USER_PATH } from "./workspace-9q4TSHlM.mjs";
1
+ import { Ct as RotationInProgress, bt as IamUserNotOwned, mt as BucketKeySetElsewhere, pt as AccessKeyLimit, tt as IAM_USER_PATH } from "./workspace-_aoe8v6u.mjs";
2
2
  import * as s3Url from "@geekmidas/storage/s3-url";
3
3
  //#region src/providers/s3/policy.ts
4
4
  const bucketArn = (bucket) => `arn:aws:s3:::${bucket}`;
@@ -439,4 +439,4 @@ async function whileKeyIsNew(first, options) {
439
439
  //#endregion
440
440
  export { identityTags as a, whileKeyIsNew as c, corsRule as d, publicAccessBlock as f, ensureIamUser as i, bucketPolicy as l, TAG_STAGE as n, issuedJustNow as o, userPolicy as p, ensureAccessKey as r, s3KeySecret as s, TAG_PROJECT as t, canonicalPolicy as u };
441
441
 
442
- //# sourceMappingURL=iam-CW61VcT3.mjs.map
442
+ //# sourceMappingURL=iam-ra1_Y405.mjs.map