@geekmidas/cli 10.0.0-alpha.145 → 10.0.0-alpha.146

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 (185) hide show
  1. package/dist/{GoDaddyProvider-IVuFcWyc.mjs → GoDaddyProvider-BESq24p-.mjs} +2 -2
  2. package/dist/{GoDaddyProvider-IVuFcWyc.mjs.map → GoDaddyProvider-BESq24p-.mjs.map} +1 -1
  3. package/dist/{GoDaddyProvider-DAJIa64i.cjs → GoDaddyProvider-BK5N6-fx.cjs} +2 -2
  4. package/dist/{GoDaddyProvider-DAJIa64i.cjs.map → GoDaddyProvider-BK5N6-fx.cjs.map} +1 -1
  5. package/dist/{HostingerProvider-BtLb-jkn.mjs → HostingerProvider-BV30wTNI.mjs} +2 -2
  6. package/dist/{HostingerProvider-BtLb-jkn.mjs.map → HostingerProvider-BV30wTNI.mjs.map} +1 -1
  7. package/dist/{HostingerProvider-DdikWVRy.cjs → HostingerProvider-BbQod5OB.cjs} +2 -2
  8. package/dist/{HostingerProvider-DdikWVRy.cjs.map → HostingerProvider-BbQod5OB.cjs.map} +1 -1
  9. package/dist/{LegacyStateStore-CmgUY9kR.mjs → LegacyStateStore-Ck3HI28A.mjs} +2 -2
  10. package/dist/{LegacyStateStore-CmgUY9kR.mjs.map → LegacyStateStore-Ck3HI28A.mjs.map} +1 -1
  11. package/dist/{LegacyStateStore-CWwT7Mj5.cjs → LegacyStateStore-OEno6vIb.cjs} +2 -2
  12. package/dist/{LegacyStateStore-CWwT7Mj5.cjs.map → LegacyStateStore-OEno6vIb.cjs.map} +1 -1
  13. package/dist/{LocalStateStore-NOmS4QyA.mjs → LocalStateStore-Fa54CpLw.mjs} +2 -2
  14. package/dist/{LocalStateStore-NOmS4QyA.mjs.map → LocalStateStore-Fa54CpLw.mjs.map} +1 -1
  15. package/dist/{LocalStateStore-BkeQg1ga.cjs → LocalStateStore-ukDFg6GM.cjs} +2 -2
  16. package/dist/{LocalStateStore-BkeQg1ga.cjs.map → LocalStateStore-ukDFg6GM.cjs.map} +1 -1
  17. package/dist/{S3StateStore-Cw2nwI5C.cjs → S3StateStore-Cjuft2Lk.cjs} +4 -4
  18. package/dist/{S3StateStore-Cw2nwI5C.cjs.map → S3StateStore-Cjuft2Lk.cjs.map} +1 -1
  19. package/dist/{S3StateStore-SjIxuWHM.mjs → S3StateStore-D53985SR.mjs} +4 -4
  20. package/dist/{S3StateStore-SjIxuWHM.mjs.map → S3StateStore-D53985SR.mjs.map} +1 -1
  21. package/dist/{SSMStateStore-DGqzo4Ob.mjs → SSMStateStore-CRjV2h2G.mjs} +2 -2
  22. package/dist/{SSMStateStore-DGqzo4Ob.mjs.map → SSMStateStore-CRjV2h2G.mjs.map} +1 -1
  23. package/dist/{SSMStateStore-DC1N1Baw.cjs → SSMStateStore-CnJgw3_-.cjs} +2 -2
  24. package/dist/{SSMStateStore-DC1N1Baw.cjs.map → SSMStateStore-CnJgw3_-.cjs.map} +1 -1
  25. package/dist/{add-BwC_EH0e.cjs → add-CG_4mNir.cjs} +7 -7
  26. package/dist/{add-BwC_EH0e.cjs.map → add-CG_4mNir.cjs.map} +1 -1
  27. package/dist/{add-Bnd7vuUN.mjs → add-D0-1UyFj.mjs} +7 -7
  28. package/dist/{add-Bnd7vuUN.mjs.map → add-D0-1UyFj.mjs.map} +1 -1
  29. package/dist/{apps-D1svw9OG.cjs → apps-DHi6E_yH.cjs} +416 -51
  30. package/dist/apps-DHi6E_yH.cjs.map +1 -0
  31. package/dist/{apps-Xrlvir2-.mjs → apps-DWALM-8s.mjs} +389 -49
  32. package/dist/apps-DWALM-8s.mjs.map +1 -0
  33. package/dist/{bundler-CoRIF5bx.mjs → bundler-Cb5ynXXS.mjs} +6 -6
  34. package/dist/{bundler-CoRIF5bx.mjs.map → bundler-Cb5ynXXS.mjs.map} +1 -1
  35. package/dist/{bundler-CgWYsgqb.cjs → bundler-Co_7zpYC.cjs} +6 -6
  36. package/dist/{bundler-CgWYsgqb.cjs.map → bundler-Co_7zpYC.cjs.map} +1 -1
  37. package/dist/{cli-DsPHbC7p.cjs → cli-C5M_7Kux.cjs} +4 -4
  38. package/dist/{cli-DsPHbC7p.cjs.map → cli-C5M_7Kux.cjs.map} +1 -1
  39. package/dist/{cli-CKlTRVwo.mjs → cli-D_9WqN6C.mjs} +4 -4
  40. package/dist/{cli-CKlTRVwo.mjs.map → cli-D_9WqN6C.mjs.map} +1 -1
  41. package/dist/{compose-BMTnoIek.mjs → compose-7p0-3ogo.mjs} +5 -5
  42. package/dist/compose-7p0-3ogo.mjs.map +1 -0
  43. package/dist/{compose-ChUQHKG3.cjs → compose-BeQ01iYk.cjs} +27 -25
  44. package/dist/compose-BeQ01iYk.cjs.map +1 -0
  45. package/dist/{compose-CVAoA04l.cjs → compose-C10hkeHU.cjs} +5 -5
  46. package/dist/compose-C10hkeHU.cjs.map +1 -0
  47. package/dist/{compose-CkvPmijw.mjs → compose-DxmEMeTu.mjs} +27 -25
  48. package/dist/compose-DxmEMeTu.mjs.map +1 -0
  49. package/dist/{config-BKpzKP6W.mjs → config-B-wza0Xk.mjs} +2 -2
  50. package/dist/{config-BKpzKP6W.mjs.map → config-B-wza0Xk.mjs.map} +1 -1
  51. package/dist/{config-QAqAEgb0.cjs → config-CWExbDxA.cjs} +2 -2
  52. package/dist/{config-QAqAEgb0.cjs.map → config-CWExbDxA.cjs.map} +1 -1
  53. package/dist/config.cjs +2 -2
  54. package/dist/config.mjs +2 -2
  55. package/dist/{credentials-Jx1Vdisc.mjs → credentials-B5Oe4fLE.mjs} +7 -7
  56. package/dist/{credentials-Jx1Vdisc.mjs.map → credentials-B5Oe4fLE.mjs.map} +1 -1
  57. package/dist/{credentials-CCIXh-cq.cjs → credentials-Csnd7M8M.cjs} +7 -7
  58. package/dist/{credentials-CCIXh-cq.cjs.map → credentials-Csnd7M8M.cjs.map} +1 -1
  59. package/dist/deploy/public.cjs +12 -12
  60. package/dist/deploy/public.mjs +12 -12
  61. package/dist/{deploy-8wsaNpPW.mjs → deploy-6DDEG4Ai.mjs} +13 -13
  62. package/dist/{deploy-8wsaNpPW.mjs.map → deploy-6DDEG4Ai.mjs.map} +1 -1
  63. package/dist/{deploy-CEX0YRdq.cjs → deploy-BwNxJ3ZI.cjs} +13 -13
  64. package/dist/{deploy-CEX0YRdq.cjs.map → deploy-BwNxJ3ZI.cjs.map} +1 -1
  65. package/dist/{docker-M_-xKiFU.cjs → docker-BZnNUJCy.cjs} +5 -5
  66. package/dist/{docker-M_-xKiFU.cjs.map → docker-BZnNUJCy.cjs.map} +1 -1
  67. package/dist/{docker-M4kCqczV.mjs → docker-Ch5aPQ04.mjs} +5 -5
  68. package/dist/{docker-M4kCqczV.mjs.map → docker-Ch5aPQ04.mjs.map} +1 -1
  69. package/dist/{dokploy-BsAPW8K1.mjs → dokploy-CTWw3WSo.mjs} +2 -2
  70. package/dist/{dokploy-BsAPW8K1.mjs.map → dokploy-CTWw3WSo.mjs.map} +1 -1
  71. package/dist/{dokploy-Djm8QIQZ.cjs → dokploy-Cn7dQqmE.cjs} +2 -2
  72. package/dist/{dokploy-Djm8QIQZ.cjs.map → dokploy-Cn7dQqmE.cjs.map} +1 -1
  73. package/dist/{eas-zEpuiYYj.mjs → eas-D0B8H7hT.mjs} +3 -3
  74. package/dist/{eas-zEpuiYYj.mjs.map → eas-D0B8H7hT.mjs.map} +1 -1
  75. package/dist/{eas-B-Ac5NjL.cjs → eas-IPjz0PWK.cjs} +3 -3
  76. package/dist/{eas-B-Ac5NjL.cjs.map → eas-IPjz0PWK.cjs.map} +1 -1
  77. package/dist/{encryption-EOEhb95p.mjs → encryption-C9auXcSV.mjs} +4 -4
  78. package/dist/{encryption-EOEhb95p.mjs.map → encryption-C9auXcSV.mjs.map} +1 -1
  79. package/dist/{encryption-B4LCEdXH.cjs → encryption-vK64UP4M.cjs} +4 -4
  80. package/dist/{encryption-B4LCEdXH.cjs.map → encryption-vK64UP4M.cjs.map} +1 -1
  81. package/dist/{engine-Ci-uU3kt.mjs → engine-C3N2WhbC.mjs} +10 -10
  82. package/dist/{engine-Ci-uU3kt.mjs.map → engine-C3N2WhbC.mjs.map} +1 -1
  83. package/dist/{engine-6NLOikTQ.cjs → engine-Icqv5JI6.cjs} +10 -10
  84. package/dist/{engine-6NLOikTQ.cjs.map → engine-Icqv5JI6.cjs.map} +1 -1
  85. package/dist/{github-C0oLDg5G.mjs → github-D24wTOe2.mjs} +9 -9
  86. package/dist/{github-C0oLDg5G.mjs.map → github-D24wTOe2.mjs.map} +1 -1
  87. package/dist/{github-u9sfpl0l.cjs → github-DUuNInc0.cjs} +9 -9
  88. package/dist/{github-u9sfpl0l.cjs.map → github-DUuNInc0.cjs.map} +1 -1
  89. package/dist/{googlePlay-DfLH_sPa.cjs → googlePlay-BGDKlnPx.cjs} +5 -5
  90. package/dist/{googlePlay-DfLH_sPa.cjs.map → googlePlay-BGDKlnPx.cjs.map} +1 -1
  91. package/dist/{googlePlay-3nfA-wWh.mjs → googlePlay-Cy-MaYr2.mjs} +5 -5
  92. package/dist/{googlePlay-3nfA-wWh.mjs.map → googlePlay-Cy-MaYr2.mjs.map} +1 -1
  93. package/dist/index.cjs +71 -79
  94. package/dist/index.cjs.map +1 -1
  95. package/dist/index.mjs +71 -79
  96. package/dist/index.mjs.map +1 -1
  97. package/dist/{local-CtzKG55y.cjs → local-B4xobzh-.cjs} +2 -2
  98. package/dist/{local-CtzKG55y.cjs.map → local-B4xobzh-.cjs.map} +1 -1
  99. package/dist/{local-uvqZDwZ9.mjs → local-CdpBgn3d.mjs} +2 -2
  100. package/dist/{local-uvqZDwZ9.mjs.map → local-CdpBgn3d.mjs.map} +1 -1
  101. package/dist/{migrate-C6V9bEVY.cjs → migrate--hMBtpx-.cjs} +4 -4
  102. package/dist/{migrate-C6V9bEVY.cjs.map → migrate--hMBtpx-.cjs.map} +1 -1
  103. package/dist/{migrate-CA1GWA4t.mjs → migrate-DVrXTq58.mjs} +4 -4
  104. package/dist/{migrate-CA1GWA4t.mjs.map → migrate-DVrXTq58.mjs.map} +1 -1
  105. package/dist/{migrate-s9lVmF98.mjs → migrate-DhZfvCkJ.mjs} +6 -6
  106. package/dist/{migrate-s9lVmF98.mjs.map → migrate-DhZfvCkJ.mjs.map} +1 -1
  107. package/dist/{migrate-FKPFIzwd.cjs → migrate-DwQ-zaMy.cjs} +6 -6
  108. package/dist/{migrate-FKPFIzwd.cjs.map → migrate-DwQ-zaMy.cjs.map} +1 -1
  109. package/dist/{notes-BjxySbyH.cjs → notes-C2b5RzGl.cjs} +4 -4
  110. package/dist/{notes-BjxySbyH.cjs.map → notes-C2b5RzGl.cjs.map} +1 -1
  111. package/dist/{notes-Dz1M9_q9.mjs → notes-z5OOMqm4.mjs} +4 -4
  112. package/dist/{notes-Dz1M9_q9.mjs.map → notes-z5OOMqm4.mjs.map} +1 -1
  113. package/dist/openapi.cjs +2 -2
  114. package/dist/openapi.mjs +2 -2
  115. package/dist/{projectBucket-2XgQSnLw.mjs → projectBucket-DPD0_B8N.mjs} +2 -2
  116. package/dist/{projectBucket-2XgQSnLw.mjs.map → projectBucket-DPD0_B8N.mjs.map} +1 -1
  117. package/dist/{projectBucket-DsXNW1Yc.cjs → projectBucket-Dk_aZ1cD.cjs} +2 -2
  118. package/dist/{projectBucket-DsXNW1Yc.cjs.map → projectBucket-Dk_aZ1cD.cjs.map} +1 -1
  119. package/dist/{publish-Dmy_OhvF.mjs → publish-Bmc1Wfs3.mjs} +2 -2
  120. package/dist/{publish-Dmy_OhvF.mjs.map → publish-Bmc1Wfs3.mjs.map} +1 -1
  121. package/dist/{publish-7-dwP5TL.cjs → publish-CDvh-9OG.cjs} +2 -2
  122. package/dist/{publish-7-dwP5TL.cjs.map → publish-CDvh-9OG.cjs.map} +1 -1
  123. package/dist/{resolve-DhsUJwm8.cjs → resolve-CuxPZ3ga.cjs} +4 -4
  124. package/dist/{resolve-DhsUJwm8.cjs.map → resolve-CuxPZ3ga.cjs.map} +1 -1
  125. package/dist/{resolve-BK7mzDBb.mjs → resolve-DHARlMdl.mjs} +4 -4
  126. package/dist/{resolve-BK7mzDBb.mjs.map → resolve-DHARlMdl.mjs.map} +1 -1
  127. package/dist/{rollback-8qHgyadV.mjs → rollback-DZq_dIbl.mjs} +7 -7
  128. package/dist/{rollback-8qHgyadV.mjs.map → rollback-DZq_dIbl.mjs.map} +1 -1
  129. package/dist/{rollback-DP2iDjc9.cjs → rollback-DxHut8C-.cjs} +7 -7
  130. package/dist/{rollback-DP2iDjc9.cjs.map → rollback-DxHut8C-.cjs.map} +1 -1
  131. package/dist/{s3-DxCex5Fx.mjs → s3-Cd7UK2y8.mjs} +3 -3
  132. package/dist/{s3-DxCex5Fx.mjs.map → s3-Cd7UK2y8.mjs.map} +1 -1
  133. package/dist/{s3-DSPbU5gN.cjs → s3-Dhy58V_y.cjs} +3 -3
  134. package/dist/{s3-DSPbU5gN.cjs.map → s3-Dhy58V_y.cjs.map} +1 -1
  135. package/dist/{serverSetup-BSuHk2t2.cjs → serverSetup-DYiKHMVp.cjs} +7 -7
  136. package/dist/{serverSetup-BSuHk2t2.cjs.map → serverSetup-DYiKHMVp.cjs.map} +1 -1
  137. package/dist/{serverSetup-CeFpl5VJ.mjs → serverSetup-qe5bdBhO.mjs} +7 -7
  138. package/dist/{serverSetup-CeFpl5VJ.mjs.map → serverSetup-qe5bdBhO.mjs.map} +1 -1
  139. package/dist/{sniffer-BfNl8jn-.mjs → sniffer-BNcLP8MO.mjs} +7 -7
  140. package/dist/{sniffer-BfNl8jn-.mjs.map → sniffer-BNcLP8MO.mjs.map} +1 -1
  141. package/dist/{sniffer-Cb3n63dY.cjs → sniffer-DFix2ORf.cjs} +7 -7
  142. package/dist/{sniffer-Cb3n63dY.cjs.map → sniffer-DFix2ORf.cjs.map} +1 -1
  143. package/dist/{snsSubscriptions-DoZ0Q1n6.mjs → snsSubscriptions-BwX28_Kl.mjs} +3 -3
  144. package/dist/{snsSubscriptions-DoZ0Q1n6.mjs.map → snsSubscriptions-BwX28_Kl.mjs.map} +1 -1
  145. package/dist/{snsSubscriptions-Bd40ebt6.cjs → snsSubscriptions-Dr-gJWtR.cjs} +3 -3
  146. package/dist/{snsSubscriptions-Bd40ebt6.cjs.map → snsSubscriptions-Dr-gJWtR.cjs.map} +1 -1
  147. package/dist/{sst-B6RbJp8g.mjs → sst-Bvtx6uZ9.mjs} +5 -5
  148. package/dist/{sst-B6RbJp8g.mjs.map → sst-Bvtx6uZ9.mjs.map} +1 -1
  149. package/dist/{sst-DKNyfTpw.cjs → sst-CoKFPW7f.cjs} +5 -5
  150. package/dist/{sst-DKNyfTpw.cjs.map → sst-CoKFPW7f.cjs.map} +1 -1
  151. package/dist/{stack-DwQ62dKK.mjs → stack-BeSbt_7k.mjs} +100 -45
  152. package/dist/stack-BeSbt_7k.mjs.map +1 -0
  153. package/dist/{stack-UcV-V6Qk.cjs → stack-DbaKGKnI.cjs} +100 -45
  154. package/dist/stack-DbaKGKnI.cjs.map +1 -0
  155. package/dist/{stage-52sKecmS.mjs → stage-BblkSR2C.mjs} +7 -7
  156. package/dist/{stage-52sKecmS.mjs.map → stage-BblkSR2C.mjs.map} +1 -1
  157. package/dist/{stage-C2v5890I.cjs → stage-DI5mzoAi.cjs} +7 -7
  158. package/dist/{stage-C2v5890I.cjs.map → stage-DI5mzoAi.cjs.map} +1 -1
  159. package/dist/{stages-CFI0OiLj.cjs → stages-C-bVwvJZ.cjs} +3 -3
  160. package/dist/{stages-CFI0OiLj.cjs.map → stages-C-bVwvJZ.cjs.map} +1 -1
  161. package/dist/{stages-DoYa81kN.mjs → stages-DBsDvEbo.mjs} +3 -3
  162. package/dist/{stages-DoYa81kN.mjs.map → stages-DBsDvEbo.mjs.map} +1 -1
  163. package/dist/target/public.cjs +1 -1
  164. package/dist/target/public.mjs +1 -1
  165. package/dist/{terminal-DkXWdU0E.cjs → terminal-Bxy_A8iP.cjs} +2 -2
  166. package/dist/{terminal-DkXWdU0E.cjs.map → terminal-Bxy_A8iP.cjs.map} +1 -1
  167. package/dist/{terminal-BDEqpkbO.mjs → terminal-DDqusYW0.mjs} +2 -2
  168. package/dist/{terminal-BDEqpkbO.mjs.map → terminal-DDqusYW0.mjs.map} +1 -1
  169. package/dist/workspace/index.cjs +1 -1
  170. package/dist/workspace/index.mjs +1 -1
  171. package/dist/{workspace-Dkm3HL9e.cjs → workspace-BbbkJDUU.cjs} +5 -5
  172. package/dist/workspace-BbbkJDUU.cjs.map +1 -0
  173. package/dist/{workspace-BbfBFtjn.mjs → workspace-CZGJdcTs.mjs} +5 -5
  174. package/dist/workspace-CZGJdcTs.mjs.map +1 -0
  175. package/package.json +17 -15
  176. package/dist/apps-D1svw9OG.cjs.map +0 -1
  177. package/dist/apps-Xrlvir2-.mjs.map +0 -1
  178. package/dist/compose-BMTnoIek.mjs.map +0 -1
  179. package/dist/compose-CVAoA04l.cjs.map +0 -1
  180. package/dist/compose-ChUQHKG3.cjs.map +0 -1
  181. package/dist/compose-CkvPmijw.mjs.map +0 -1
  182. package/dist/stack-DwQ62dKK.mjs.map +0 -1
  183. package/dist/stack-UcV-V6Qk.cjs.map +0 -1
  184. package/dist/workspace-BbfBFtjn.mjs.map +0 -1
  185. package/dist/workspace-Dkm3HL9e.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"credentials-CCIXh-cq.cjs","names":["resolve","join","homedir","join","existsSync","readFile","writeFile","spawn","GkmError","kebabCase","scopedName","GkmError","join","homedir","mkdir","randomBytes","writeFile","chmod","existsSync","copyFile","constants","readFile","basename","join","existsSync","readFile","mkdir","writeFile","GkmError","readFileSync","randomBytes","createCipheriv","createDecipheriv","readFileSync","join","existsSync","realpathSync","dirname","readdirSync","sep","isReservedStageKey","s3SecretsLocation","UnknownSecretsStoreProvider","runtimeOf","DEFAULT_CACHE","DEFAULT_STORAGE","DEFAULT_EVENTS","appKey","provideKey","randomBytes","GkmError","output","lookup","GkmError"],"sources":["../src/home.ts","../src/auth/credentials.ts","../src/run.ts","../src/deploy/identity.ts","../src/secrets/keystore.ts","../src/secrets/file.ts","../src/build/native.ts","../src/secrets/storage.ts","../src/secrets/store.ts","../src/workspace/backends.ts","../src/providers/processorOrigin.ts","../src/deploy/state.ts","../src/target/dokploy/dns/DnsProvider.ts","../src/target/dokploy/dns/index.ts","../src/deploy/credentials.ts"],"sourcesContent":["/**\n * Where the CLI keeps what belongs to a person rather than a project: stage\n * keys and stored provider credentials.\n *\n * `GKM_HOME` names it, so a CI job, a shared build runner or a test can give\n * every run its own instead of reaching into whoever's home directory the\n * process happens to have. Unset, it is `~/.gkm`, where it has always been.\n */\n\nimport { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\n\n/** The environment variable that moves the CLI's home. */\nexport const GKM_HOME_ENV = 'GKM_HOME';\n\n/** The CLI's home: `GKM_HOME` if set, else `~/.gkm`. */\nexport function gkmHome(env: NodeJS.ProcessEnv = process.env): string {\n\tconst configured = env[GKM_HOME_ENV];\n\treturn configured ? resolve(configured) : join(homedir(), '.gkm');\n}\n","import { existsSync, mkdirSync } from 'node:fs';\nimport { readFile, unlink, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { gkmHome } from '../home';\n\n/**\n * Stored credentials for various services\n */\nexport interface StoredCredentials {\n\tdokploy?: {\n\t\t/** API token */\n\t\ttoken: string;\n\t\t/** Dokploy endpoint URL */\n\t\tendpoint: string;\n\t\t/** Registry ID in Dokploy (for Docker image pulls) */\n\t\tregistryId?: string;\n\t\t/** When the credentials were stored */\n\t\tstoredAt: string;\n\t};\n\thostinger?: {\n\t\t/** API token from hpanel.hostinger.com/profile/api */\n\t\ttoken: string;\n\t\t/** When the credentials were stored */\n\t\tstoredAt: string;\n\t};\n\tgodaddy?: {\n\t\t/** A Personal Access Token, scoped to domains.dns:update */\n\t\ttoken: string;\n\t\t/** When the credentials were stored */\n\t\tstoredAt: string;\n\t};\n}\n\n/**\n * Options for credential operations\n */\nexport interface CredentialOptions {\n\t/**\n\t * A directory whose `.gkm` holds the credentials. Default: the CLI's home\n\t * (`GKM_HOME`, else `~/.gkm`).\n\t */\n\troot?: string;\n\t/** The CLI's home itself, holding `credentials.json`. Wins over `root`. */\n\thome?: string;\n}\n\n/**\n * Get the path to the credentials directory\n */\nexport function getCredentialsDir(options?: CredentialOptions): string {\n\tif (options?.home) return options.home;\n\treturn options?.root ? join(options.root, '.gkm') : gkmHome();\n}\n\n/**\n * Get the path to the credentials file\n */\nexport function getCredentialsPath(options?: CredentialOptions): string {\n\treturn join(getCredentialsDir(options), 'credentials.json');\n}\n\n/**\n * Ensure the credentials directory exists\n */\nfunction ensureCredentialsDir(options?: CredentialOptions): void {\n\tconst dir = getCredentialsDir(options);\n\tif (!existsSync(dir)) {\n\t\tmkdirSync(dir, { recursive: true, mode: 0o700 });\n\t}\n}\n\n/**\n * Read stored credentials from disk\n */\nexport async function readCredentials(\n\toptions?: CredentialOptions,\n): Promise<StoredCredentials> {\n\tconst path = getCredentialsPath(options);\n\n\tif (!existsSync(path)) {\n\t\treturn {};\n\t}\n\n\ttry {\n\t\tconst content = await readFile(path, 'utf-8');\n\t\treturn JSON.parse(content) as StoredCredentials;\n\t} catch {\n\t\treturn {};\n\t}\n}\n\n/**\n * Write credentials to disk\n */\nexport async function writeCredentials(\n\tcredentials: StoredCredentials,\n\toptions?: CredentialOptions,\n): Promise<void> {\n\tensureCredentialsDir(options);\n\tconst path = getCredentialsPath(options);\n\n\tawait writeFile(path, JSON.stringify(credentials, null, 2), {\n\t\tmode: 0o600, // Owner read/write only\n\t});\n}\n\n/**\n * Store Dokploy credentials\n */\nexport async function storeDokployCredentials(\n\ttoken: string,\n\tendpoint: string,\n\toptions?: CredentialOptions,\n): Promise<void> {\n\tconst credentials = await readCredentials(options);\n\n\tcredentials.dokploy = {\n\t\ttoken,\n\t\tendpoint,\n\t\tstoredAt: new Date().toISOString(),\n\t};\n\n\tawait writeCredentials(credentials, options);\n}\n\n/**\n * Get stored Dokploy credentials\n */\nexport async function getDokployCredentials(\n\toptions?: CredentialOptions,\n): Promise<{\n\ttoken: string;\n\tendpoint: string;\n\tregistryId?: string;\n} | null> {\n\tconst credentials = await readCredentials(options);\n\n\t// The environment first, and each half independently.\n\t//\n\t// `getDokployToken` has always read `DOKPLOY_API_TOKEN` while this — the\n\t// function the deploy path actually calls — read only the file. So a CI job\n\t// given the token as a secret had a token and nowhere to send it, and the\n\t// only way through was committing a credentials file or running an\n\t// interactive login on the runner.\n\t//\n\t// Read separately rather than as a pair because they arrive separately: a\n\t// token is a secret and belongs in the environment, while an endpoint is\n\t// configuration and usually belongs in `deploy.dokploy.endpoint`. Requiring\n\t// both from the same place is what made either one useless alone.\n\tconst token = process.env.DOKPLOY_API_TOKEN ?? credentials.dokploy?.token;\n\tconst endpoint =\n\t\tprocess.env.DOKPLOY_ENDPOINT ?? credentials.dokploy?.endpoint;\n\n\tif (!token || !endpoint) return null;\n\n\treturn {\n\t\ttoken,\n\t\tendpoint: endpoint.replace(/\\/$/, ''),\n\t\t...(credentials.dokploy?.registryId\n\t\t\t? { registryId: credentials.dokploy.registryId }\n\t\t\t: {}),\n\t};\n}\n\n/**\n * Remove Dokploy credentials\n */\nexport async function removeDokployCredentials(\n\toptions?: CredentialOptions,\n): Promise<boolean> {\n\tconst credentials = await readCredentials(options);\n\n\tif (!credentials.dokploy) {\n\t\treturn false;\n\t}\n\n\tdelete credentials.dokploy;\n\tawait writeCredentials(credentials, options);\n\treturn true;\n}\n\n/**\n * Remove all stored credentials\n */\nexport async function removeAllCredentials(\n\toptions?: CredentialOptions,\n): Promise<void> {\n\tconst path = getCredentialsPath(options);\n\n\tif (existsSync(path)) {\n\t\tawait unlink(path);\n\t}\n}\n\n/**\n * Get Dokploy API token, checking stored credentials first, then environment\n */\nexport async function getDokployToken(\n\toptions?: CredentialOptions,\n): Promise<string | null> {\n\t// First check environment variable (takes precedence)\n\tconst envToken = process.env.DOKPLOY_API_TOKEN;\n\tif (envToken) {\n\t\treturn envToken;\n\t}\n\n\t// Then check stored credentials\n\tconst stored = await getDokployCredentials(options);\n\tif (stored) {\n\t\treturn stored.token;\n\t}\n\n\treturn null;\n}\n\n/**\n * Get Dokploy endpoint from stored credentials\n */\nexport async function getDokployEndpoint(\n\toptions?: CredentialOptions,\n): Promise<string | null> {\n\tconst stored = await getDokployCredentials(options);\n\treturn stored?.endpoint ?? null;\n}\n\n/**\n * Store Dokploy registry ID\n */\nexport async function storeDokployRegistryId(\n\tregistryId: string,\n\toptions?: CredentialOptions,\n): Promise<void> {\n\tconst credentials = await readCredentials(options);\n\n\tif (!credentials.dokploy) {\n\t\tthrow new Error(\n\t\t\t'Dokploy credentials not found. Run \"gkm login --service dokploy\" first.',\n\t\t);\n\t}\n\n\tcredentials.dokploy.registryId = registryId;\n\tawait writeCredentials(credentials, options);\n}\n\n/**\n * Get Dokploy registry ID from stored credentials\n */\nexport async function getDokployRegistryId(\n\toptions?: CredentialOptions,\n): Promise<string | undefined> {\n\tconst stored = await getDokployCredentials(options);\n\treturn stored?.registryId ?? undefined;\n}\n\n// ============================================\n// Hostinger credentials\n// ============================================\n\n/**\n * Store Hostinger API token\n *\n * @param token - API token from hpanel.hostinger.com/profile/api\n */\nexport async function storeHostingerToken(\n\ttoken: string,\n\toptions?: CredentialOptions,\n): Promise<void> {\n\tconst credentials = await readCredentials(options);\n\n\tcredentials.hostinger = {\n\t\ttoken,\n\t\tstoredAt: new Date().toISOString(),\n\t};\n\n\tawait writeCredentials(credentials, options);\n}\n\n/**\n * Get stored Hostinger API token\n *\n * Checks environment variable first (HOSTINGER_API_TOKEN),\n * then falls back to stored credentials.\n */\nexport async function getHostingerToken(\n\toptions?: CredentialOptions,\n): Promise<string | null> {\n\t// First check environment variable (takes precedence)\n\tconst envToken = process.env.HOSTINGER_API_TOKEN;\n\tif (envToken) {\n\t\treturn envToken;\n\t}\n\n\t// Then check stored credentials\n\tconst credentials = await readCredentials(options);\n\treturn credentials.hostinger?.token ?? null;\n}\n\n/**\n * Remove Hostinger credentials\n */\nexport async function removeHostingerCredentials(\n\toptions?: CredentialOptions,\n): Promise<boolean> {\n\tconst credentials = await readCredentials(options);\n\n\tif (!credentials.hostinger) {\n\t\treturn false;\n\t}\n\n\tdelete credentials.hostinger;\n\tawait writeCredentials(credentials, options);\n\treturn true;\n}\n\n// ============================================\n// GoDaddy credentials\n// ============================================\n\n/**\n * Store a GoDaddy Personal Access Token.\n */\nexport async function storeGoDaddyToken(\n\ttoken: string,\n\toptions?: CredentialOptions,\n): Promise<void> {\n\tconst credentials = await readCredentials(options);\n\n\tcredentials.godaddy = {\n\t\ttoken,\n\t\tstoredAt: new Date().toISOString(),\n\t};\n\n\tawait writeCredentials(credentials, options);\n}\n\n/**\n * Remove GoDaddy credentials\n */\nexport async function removeGoDaddyCredentials(\n\toptions?: CredentialOptions,\n): Promise<boolean> {\n\tconst credentials = await readCredentials(options);\n\n\tif (!credentials.godaddy) {\n\t\treturn false;\n\t}\n\n\tdelete credentials.godaddy;\n\tawait writeCredentials(credentials, options);\n\treturn true;\n}\n","/**\n * Start a program with an argument array, never a shell string.\n *\n * `gkm build`, `gkm docker` and `gkm deploy` pass values that come from the\n * workspace — image refs, tags, build args, package names — to `docker` and\n * `turbo`. Joined into a string and handed to a shell, a package named\n * `x;curl …|sh` or a tag holding `$(…)` became part of the command line, which\n * matters most where the CLI builds a repository it didn't write: a CI job for a\n * fork, a shared build runner. Here every value reaches the program as one\n * `argv` element, whatever it contains.\n */\n\nimport { type SpawnOptions, spawn } from 'node:child_process';\n\n/** Long enough for a cold image build; short enough that a hung one ends. */\nexport const DEFAULT_TIMEOUT_MS = 30 * 60_000;\n\n/** How long a timed-out child has to exit on SIGTERM before it is killed. */\nconst KILL_GRACE_MS = 5_000;\n\nexport interface RunOptions {\n\tcwd?: string;\n\tenv?: NodeJS.ProcessEnv;\n\tstdio?: SpawnOptions['stdio'];\n\t/** Kill the child after this long. Defaults to {@link DEFAULT_TIMEOUT_MS}. */\n\ttimeoutMs?: number;\n\t/**\n\t * Kills the child when aborted, and rejects with the signal's reason — the\n\t * same as a stopped deploy's other calls.\n\t */\n\tsignal?: AbortSignal;\n}\n\n/** The command line as a person would read it — for messages, never to run. */\nfunction display(command: string, args: readonly string[]): string {\n\treturn [command, ...args].join(' ');\n}\n\n/** The program ran and exited unsuccessfully; its own output said why. */\nexport class CommandFailed extends Error {\n\tconstructor(\n\t\treadonly command: string,\n\t\treadonly args: readonly string[],\n\t\treadonly exitCode: number | null,\n\t\treadonly signal: NodeJS.Signals | null,\n\t) {\n\t\tsuper(\n\t\t\t`\\`${display(command, args)}\\` ${exitCode === null ? `was stopped by ${signal ?? 'a signal'}` : `exited with code ${exitCode}`}. Its output above says why; run it by hand to see it again.`,\n\t\t);\n\t\tthis.name = 'CommandFailed';\n\t}\n}\n\n/** The program ran past its timeout and was killed. */\nexport class CommandTimedOut extends Error {\n\tconstructor(\n\t\treadonly command: string,\n\t\treadonly args: readonly string[],\n\t\treadonly timeoutMs: number,\n\t) {\n\t\tsuper(\n\t\t\t`\\`${display(command, args)}\\` was still running after ${Math.round(timeoutMs / 1000)}s and was stopped. Check what it was waiting on — a registry, the Docker daemon, a prompt — and run it again.`,\n\t\t);\n\t\tthis.name = 'CommandTimedOut';\n\t}\n}\n\n/**\n * Run `command` with `args`, resolving when it exits 0.\n *\n * Rejects with {@link CommandFailed} on any other exit, {@link CommandTimedOut}\n * once `timeoutMs` passes (after the child is gone), and with the spawn error\n * itself when the program cannot be started at all — `ENOENT` already names it.\n */\nexport async function run(\n\tcommand: string,\n\targs: readonly string[],\n\toptions: RunOptions = {},\n): Promise<void> {\n\tawait spawnChild(command, args, options, false);\n}\n\n/**\n * {@link run}, resolving with what the program wrote to stdout — for a value\n * the CLI reads back, such as the digest `docker inspect` reports. stderr still\n * reaches the terminal, so a failure explains itself the same way.\n */\nexport function runOutput(\n\tcommand: string,\n\targs: readonly string[],\n\toptions: Omit<RunOptions, 'stdio'> = {},\n): Promise<string> {\n\treturn spawnChild(command, args, options, true);\n}\n\nfunction spawnChild(\n\tcommand: string,\n\targs: readonly string[],\n\toptions: RunOptions,\n\tcapture: boolean,\n): Promise<string> {\n\tconst { timeoutMs = DEFAULT_TIMEOUT_MS, ...spawnOptions } = options;\n\n\treturn new Promise<string>((resolve, reject) => {\n\t\tconst child = spawn(command, [...args], {\n\t\t\tstdio: 'inherit',\n\t\t\t...spawnOptions,\n\t\t\t...(capture ? { stdio: ['ignore', 'pipe', 'inherit'] } : {}),\n\t\t\tshell: false,\n\t\t});\n\n\t\tlet stdout = '';\n\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\tstdout += chunk.toString();\n\t\t});\n\n\t\tlet timedOut = false;\n\t\tlet killer: NodeJS.Timeout | undefined;\n\t\tconst timer = setTimeout(() => {\n\t\t\ttimedOut = true;\n\t\t\tchild.kill('SIGTERM');\n\t\t\t// A child that ignores SIGTERM would hold the deploy open forever.\n\t\t\tkiller = setTimeout(() => child.kill('SIGKILL'), KILL_GRACE_MS);\n\t\t\tkiller.unref?.();\n\t\t}, timeoutMs);\n\t\ttimer.unref?.();\n\n\t\tconst settle = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tif (killer) clearTimeout(killer);\n\t\t};\n\n\t\tchild.on('error', (error) => {\n\t\t\tsettle();\n\t\t\t// Node reports an abort as its own `AbortError`; the caller asked\n\t\t\t// with a reason, and that is what it should get back.\n\t\t\treject(spawnOptions.signal?.aborted ? spawnOptions.signal.reason : error);\n\t\t});\n\n\t\tchild.on('close', (code: number | null, signal: NodeJS.Signals | null) => {\n\t\t\tsettle();\n\t\t\tif (spawnOptions.signal?.aborted) reject(spawnOptions.signal.reason);\n\t\t\telse if (timedOut) reject(new CommandTimedOut(command, args, timeoutMs));\n\t\t\telse if (code === 0) resolve(stdout);\n\t\t\telse reject(new CommandFailed(command, args, code, signal));\n\t\t});\n\t});\n}\n","/**\n * Who a deploy is, on a target it shares with other workspaces.\n *\n * A Dokploy server is one flat namespace of projects, images and Docker\n * service names. Deploys used to identify everything they made by the\n * workspace name alone, so two workspaces called `shop` — or `Shop` and\n * `shop` — deploying to one server landed in the same project, pushed over\n * each other's images and redeployed each other's applications. A\n * `DeployIdentity` is what a deploy names and claims its resources by instead.\n */\n\nimport { kebabCase, scopedName } from '@geekmidas/manifest';\nimport { GkmError } from '../errors';\n\nexport interface DeployIdentity {\n\t/**\n\t * Whose deploy this is — an organisation, a team, a repository. Two\n\t * workspaces with the same name are told apart by it. Defaults to the\n\t * kebab-cased workspace name; set `deploy.namespace` to choose one.\n\t */\n\treadonly namespace: string;\n\t/** The workspace name as the target spells it: lowercase, `[a-z0-9-]`. */\n\treadonly project: string;\n\treadonly stage: string;\n\t/**\n\t * `<namespace>/<project>`: what a Dokploy project is claimed by.\n\t *\n\t * The stage is not part of it because one Dokploy project holds every stage\n\t * of a workspace, each as an environment — the key has to be the same from\n\t * every stage that deploys into it.\n\t */\n\treadonly key: string;\n\t/**\n\t * The prefix every name on the target carries: the project alone in the\n\t * default namespace, `<namespace>-<project>` in any other.\n\t *\n\t * The default adds nothing so that a workspace that never set a namespace\n\t * keeps the names it was already deployed under — a Postgres is found by\n\t * its name, and a new name would be a new, empty database.\n\t */\n\treadonly scope: string;\n}\n\n/** A namespace that cannot be part of a Dokploy name or an image path. */\nexport class DeployNamespaceInvalid extends GkmError {\n\tconstructor(readonly namespace: string) {\n\t\tsuper(\n\t\t\t`deploy.namespace '${namespace}' is not usable as a name: use lowercase letters, digits and single '-' between them (e.g. 'acme' or 'acme-platform') in gkm.config.ts.`,\n\t\t);\n\t\tthis.name = 'DeployNamespaceInvalid';\n\t}\n}\n\n/** A workspace name with nothing a target can name a resource by. */\nexport class DeployProjectNameInvalid extends GkmError {\n\tconstructor(readonly workspaceName: string) {\n\t\tsuper(\n\t\t\t`The workspace name '${workspaceName}' has no letters or digits to name deployed resources by. Set \"name\" in gkm.config.ts.`,\n\t\t);\n\t\tthis.name = 'DeployProjectNameInvalid';\n\t}\n}\n\nconst NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n/**\n * Lowercase `[a-z0-9-]`, runs of anything else collapsed to one `-`: valid as\n * a Docker image path component, a Docker service name and a Dokploy name.\n */\nfunction slug(value: string): string {\n\treturn value\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9]+/g, '-')\n\t\t.replace(/^-+|-+$/g, '');\n}\n\n/** The namespace a workspace is in when it does not name one. */\nexport function defaultNamespace(workspaceName: string): string {\n\treturn slug(kebabCase(workspaceName));\n}\n\n/** What an identity is derived from: a workspace's name and namespace. */\nexport interface IdentitySource {\n\tname: string;\n\tdeploy?: { namespace?: string };\n}\n\nexport function deployIdentity(\n\tworkspace: IdentitySource,\n\tstage: string,\n): DeployIdentity {\n\t// Lowercased rather than kebab-cased: the names a workspace was already\n\t// deployed under were `${stage}-${name}`.toLowerCase(), and this has to\n\t// reproduce them for the databases it finds by name.\n\tconst project = slug(workspace.name);\n\tif (!project) throw new DeployProjectNameInvalid(workspace.name);\n\n\tconst fallback = defaultNamespace(workspace.name);\n\tconst namespace = workspace.deploy?.namespace ?? fallback;\n\tif (!NAME.test(namespace)) throw new DeployNamespaceInvalid(namespace);\n\n\treturn {\n\t\tnamespace,\n\t\tproject,\n\t\tstage,\n\t\tkey: `${namespace}/${project}`,\n\t\tscope: namespace === fallback ? project : `${namespace}-${project}`,\n\t};\n}\n\n/**\n * The token a Dokploy project's description carries to say which identity\n * created it. A project with the right name and no marker belongs to someone\n * else, and a deploy never adopts it.\n */\nexport function ownershipMarker(identity: DeployIdentity): string {\n\treturn `gkm:${identity.key}`;\n}\n\n/** Whether a project description carries `identity`'s marker. */\nexport function isOwnedBy(\n\tdescription: string | null | undefined,\n\tidentity: DeployIdentity,\n): boolean {\n\tconst marker = ownershipMarker(identity);\n\treturn (description ?? '').split(/\\s+/).includes(marker);\n}\n\n/** Any `gkm:` marker a description carries — whoever's it is. */\nexport function markerOf(\n\tdescription: string | null | undefined,\n): string | undefined {\n\treturn (description ?? '').split(/\\s+/).find((t) => t.startsWith('gkm:'));\n}\n\n/** What the Dokploy project is called. */\nexport function projectName(identity: DeployIdentity): string {\n\treturn identity.scope;\n}\n\n/**\n * The repository an app's image is pushed to, below the registry:\n * `<namespace>/<project>-<app>`.\n *\n * The namespace is a path segment of its own so that a registry that maps\n * paths to owners (an organisation's packages, a Harbor project) can grant it\n * as one; the app is joined to the project so the two read as one name.\n */\nexport function imageName(identity: DeployIdentity, app: string): string {\n\treturn `${identity.namespace}/${identity.project}-${slug(kebabCase(app))}`;\n}\n\n/** The full image ref an app is built, pushed and deployed as. */\nexport function imageRef(\n\tidentity: DeployIdentity,\n\tapp: string,\n\tregistry: string | undefined,\n\ttag: string,\n): string {\n\tconst name = imageName(identity, app);\n\treturn registry\n\t\t? `${registry.replace(/\\/+$/, '')}/${name}:${tag}`\n\t\t: `${name}:${tag}`;\n}\n\n/**\n * What one application is called on the target.\n *\n * The same rule the constructs use, through the same `scopedName`, scoped by\n * the stage and the identity: the application beside\n * `production-kitchen-sink-database` is `production-kitchen-sink-api`. A\n * Dokploy application's name is also its Docker service name, which is unique\n * on the whole server, so the namespace has to be in it too — `acme`'s and\n * `globex`'s `shop` would otherwise both run `production-shop-api`.\n *\n * The app id is dropped when it repeats the project, so a project named for its\n * one application is `production-kitchen-sink` rather than\n * `production-kitchen-sink-kitchen-sink`.\n */\nexport function applicationName(identity: DeployIdentity, app: string): string {\n\treturn slug(app) === identity.project\n\t\t? `${identity.stage}-${identity.scope}`\n\t\t: scopedName([identity.stage, identity.scope], app);\n}\n","/**\n * The keys that open each stage's encrypted secrets file, kept outside the\n * project in the CLI's home.\n *\n * Keys were kept at `~/.gkm/<folder>/<stage>.key`, named after the project\n * directory — so two checkouts in folders with the same name (`~/work/api`\n * and `~/oss/api`) shared one key, and the second `gkm secrets:init`\n * overwrote the first project's. They are now kept under the project's\n * identity, `<home>/keys/<namespace>/<project>/<stage>.key`, the same\n * `<namespace>/<project>` a deploy claims its Dokploy project by. A key still\n * at the old place is copied to the new one the first time it is read; the\n * old file stays, so an older CLI on the same machine keeps working.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport { constants, existsSync } from 'node:fs';\nimport {\n\tchmod,\n\tcopyFile,\n\tmkdir,\n\treadFile,\n\trm,\n\twriteFile,\n} from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { deployIdentity, type IdentitySource } from '../deploy/identity';\nimport { GkmError } from '../errors';\nimport { gkmHome } from '../home';\n\n/** Key length for AES-256 encryption */\nconst KEY_LENGTH = 32; // 256 bits\n\n/** Whose keys, and where the CLI's home is. */\nexport interface KeystoreProject {\n\t/** `<namespace>/<project>`, as `DeployIdentity.key` spells it. */\n\tkey: string;\n\t/**\n\t * The names the project's keys were kept under, `~/.gkm/<name>/`, before\n\t * they were keyed by identity: its directory's basename, which the secrets\n\t * file used, and its workspace name, which `gkm init` and the generated CI\n\t * workflow wrote to. Looked in, and copied from, when the project has no\n\t * key of its own yet.\n\t */\n\tlegacy?: readonly string[];\n\t/**\n\t * Other project keys this project's keys may be copied from when it has\n\t * none: the default namespace's, for a workspace that has just set\n\t * `deploy.namespace` — the secrets file in the checkout is the same one.\n\t */\n\taliases?: string[];\n\t/** The CLI's home. Defaults to `GKM_HOME`, else `~/.gkm`. */\n\thome?: string;\n}\n\n/** A keystore project key that is not `<namespace>/<project>`. */\nexport class KeystoreProjectInvalid extends GkmError {\n\tconstructor(readonly key: string) {\n\t\tsuper(\n\t\t\t`'${key}' is not a keystore project: expected '<namespace>/<project>' in lowercase letters, digits and '-', as deployIdentity() produces. Pass the workspace's identity key.`,\n\t\t);\n\t\tthis.name = 'KeystoreProjectInvalid';\n\t}\n}\n\n/** A stage has no key, here or at the place keys used to be kept. */\nexport class KeyNotFound extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly project: string,\n\t\treadonly path: string,\n\t) {\n\t\tsuper(\n\t\t\t`Encryption key not found for stage \"${stage}\" in project \"${project}\". ` +\n\t\t\t\t`Expected key at: ${path}. Run \\`gkm secrets:init --stage ${stage}\\` to create one, or copy the stage's key there.`,\n\t\t);\n\t\tthis.name = 'KeyNotFound';\n\t}\n}\n\nconst PROJECT_KEY = /^[a-z0-9]+(?:-[a-z0-9]+)*\\/[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n/**\n * The keystore key of a workspace: its deploy identity without the stage, so\n * a project's keys and its Dokploy project are named by the same thing.\n */\nexport function projectKey(workspace: IdentitySource): string {\n\treturn deployIdentity(workspace, '').key;\n}\n\n/** The keystore project of a loaded workspace. */\nexport function keystoreProject(\n\tworkspace: IdentitySource & { root: string },\n\thome?: string,\n): KeystoreProject {\n\tconst key = projectKey(workspace);\n\tconst unscoped = projectKey({ name: workspace.name });\n\tconst legacy = [\n\t\t...new Set([folderName(workspace.root), workspace.name]),\n\t].filter((name): name is string => !!name);\n\treturn {\n\t\tkey,\n\t\tlegacy,\n\t\t...(unscoped !== key ? { aliases: [unscoped] } : {}),\n\t\t...(home ? { home } : {}),\n\t};\n}\n\n/**\n * Whether `name` stays inside the home it is joined to. A workspace name was\n * joined as is — `@acme/shop` is `~/.gkm/@acme/shop` — but never upwards.\n */\nfunction isLegacyName(name: string): boolean {\n\treturn name.split(/[\\\\/]/).every((part) => part !== '..' && part !== '');\n}\n\n/** The last segment of a path, as the old keystore named projects. */\nfunction folderName(path: string): string | undefined {\n\tconst name = path.split(/[\\\\/]/).filter(Boolean).at(-1);\n\treturn name && name !== '.' && name !== '..' ? name : undefined;\n}\n\n/**\n * Get the keystore directory for a project:\n * `<home>/keys/<namespace>/<project>`.\n */\nexport function getKeystoreDir(project: KeystoreProject): string {\n\tif (!PROJECT_KEY.test(project.key)) {\n\t\tthrow new KeystoreProjectInvalid(project.key);\n\t}\n\tconst [namespace, name] = project.key.split('/') as [string, string];\n\treturn join(project.home ?? gkmHome(), 'keys', namespace, name);\n}\n\n/** Get the path to a stage's encryption key. */\nexport function getKeyPath(stage: string, project: KeystoreProject): string {\n\treturn join(getKeystoreDir(project), `${stage}.key`);\n}\n\n/**\n * Where else a stage's key may be, most likely first: under an alias of the\n * project, then where keys were kept before they were keyed by identity —\n * under the configured home, then under `~/.gkm`, which is where every CLI\n * before `GKM_HOME` wrote.\n */\nfunction legacyKeyPaths(stage: string, project: KeystoreProject): string[] {\n\tconst aliases = (project.aliases ?? []).map((key) =>\n\t\tgetKeyPath(stage, { key, home: project.home }),\n\t);\n\tconst homes = [\n\t\t...new Set([project.home ?? gkmHome(), join(homedir(), '.gkm')]),\n\t];\n\tconst names = (project.legacy ?? []).filter(isLegacyName);\n\treturn [\n\t\t...aliases,\n\t\t...names.flatMap((name) =>\n\t\t\thomes.map((home) => join(home, name, `${stage}.key`)),\n\t\t),\n\t];\n}\n\n/** Check if a key exists for a stage, here or where it used to be kept. */\nexport function keyExists(stage: string, project: KeystoreProject): boolean {\n\treturn (\n\t\texistsSync(getKeyPath(stage, project)) ||\n\t\tlegacyKeyPaths(stage, project).some((path) => existsSync(path))\n\t);\n}\n\n/**\n * Generate a new encryption key for a stage, stored owner-only at\n * `<home>/keys/<namespace>/<project>/<stage>.key`.\n */\nexport async function generateKey(\n\tstage: string,\n\tproject: KeystoreProject,\n\t/** `wx` to refuse replacing a key that is already there. */\n\tflag: 'w' | 'wx' = 'w',\n): Promise<string> {\n\tconst keyDir = getKeystoreDir(project);\n\tconst keyPath = getKeyPath(stage, project);\n\n\t// Ensure keystore directory exists with restricted permissions\n\tawait mkdir(keyDir, { recursive: true, mode: 0o700 });\n\n\t// Generate random key\n\tconst key = randomBytes(KEY_LENGTH).toString('hex');\n\n\t// Write key with restricted permissions (owner read/write only)\n\tawait writeFile(keyPath, key, { mode: 0o600, encoding: 'utf-8', flag });\n\n\t// Ensure permissions are set correctly (in case file existed)\n\tawait chmod(keyPath, 0o600);\n\n\treturn key;\n}\n\n/**\n * Copy a key from where it used to be kept to where it is kept now.\n *\n * Copied, not moved: an older CLI on the same machine still reads the old\n * place. Exclusive, so two processes migrating at once cannot overwrite a key\n * one of them already put there.\n */\nasync function migrateLegacyKey(\n\tstage: string,\n\tproject: KeystoreProject,\n): Promise<boolean> {\n\tconst legacy = legacyKeyPaths(stage, project).find((path) =>\n\t\texistsSync(path),\n\t);\n\tif (!legacy) return false;\n\n\tconst keyPath = getKeyPath(stage, project);\n\tawait mkdir(getKeystoreDir(project), { recursive: true, mode: 0o700 });\n\ttry {\n\t\tawait copyFile(legacy, keyPath, constants.COPYFILE_EXCL);\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n\t}\n\tawait chmod(keyPath, 0o600);\n\treturn true;\n}\n\n/**\n * Read an encryption key for a stage, or `null` when there is none — after\n * copying it over from where keys used to be kept, if it is still there.\n */\nexport async function readKey(\n\tstage: string,\n\tproject: KeystoreProject,\n): Promise<string | null> {\n\tconst keyPath = getKeyPath(stage, project);\n\n\tif (!existsSync(keyPath) && !(await migrateLegacyKey(stage, project))) {\n\t\treturn null;\n\t}\n\n\tconst key = await readFile(keyPath, 'utf-8');\n\treturn key.trim();\n}\n\n/**\n * Read an encryption key for a stage, throwing {@link KeyNotFound} if there\n * is none.\n */\nexport async function requireKey(\n\tstage: string,\n\tproject: KeystoreProject,\n): Promise<string> {\n\tconst key = await readKey(stage, project);\n\n\tif (!key) {\n\t\tthrow new KeyNotFound(stage, project.key, getKeyPath(stage, project));\n\t}\n\n\treturn key;\n}\n\n/**\n * Delete a key for a stage. Only the current one: a key left at the old place\n * belongs to whichever older CLI still reads it.\n */\nexport async function deleteKey(\n\tstage: string,\n\tproject: KeystoreProject,\n): Promise<void> {\n\tawait rm(getKeyPath(stage, project), { force: true });\n}\n\n/**\n * Get or create a key for a stage.\n * If the key already exists, it is returned. Otherwise, a new key is generated.\n */\nexport async function getOrCreateKey(\n\tstage: string,\n\tproject: KeystoreProject,\n): Promise<string> {\n\tconst existingKey = await readKey(stage, project);\n\n\tif (existingKey) {\n\t\treturn existingKey;\n\t}\n\n\t// Exclusively: a key is now shared by every checkout of one project, and\n\t// two commands creating it at once must not each keep a different one.\n\ttry {\n\t\treturn await generateKey(stage, project, 'wx');\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n\t\treturn requireKey(stage, project);\n\t}\n}\n","import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { basename, join } from 'node:path';\nimport { GkmError } from '../errors';\nimport {\n\tgetKeyPath,\n\tgetOrCreateKey,\n\ttype KeystoreProject,\n\tprojectKey,\n\treadKey,\n} from './keystore';\nimport type { SecretsStore } from './store.js';\nimport type { StageSecrets } from './types';\n\n/** Where the files live, relative to the project root. */\nconst SECRETS_DIR = '.gkm/secrets';\n\n/** AES-256-GCM configuration */\nconst ALGORITHM = 'aes-256-gcm';\nconst IV_LENGTH = 12; // 96 bits for GCM\nconst AUTH_TAG_LENGTH = 16; // 128 bits\n\n/** Encrypted secrets file structure */\nexport interface EncryptedSecretsFile {\n\t/** Version for future format changes */\n\tversion: 1;\n\t/** Base64 encoded encrypted data (ciphertext + auth tag) */\n\tencrypted: string;\n\t/** Hex encoded IV */\n\tiv: string;\n}\n\n/**\n * A stage's secrets as an encrypted file on this machine:\n * `.gkm/secrets/<stage>.json`, with its key in the CLI's home at\n * `keys/<namespace>/<project>/<stage>.key`.\n *\n * The local stage's store, always — its secrets belong to the machine running\n * `gkm dev` — and a deployed stage's when `secrets.store` is `'file'`.\n */\nexport class FileSecretsStore implements SecretsStore {\n\treadonly name = 'file';\n\tprivate readonly project: KeystoreProject;\n\n\t/**\n\t * @param project - Whose keys: a workspace's `keystoreProject()`. Outside a\n\t * workspace there is no config to name the project, so it is named the\n\t * way a workspace without `name` is — its package name, else its folder.\n\t */\n\tconstructor(\n\t\tprivate readonly root: string,\n\t\tproject?: KeystoreProject,\n\t) {\n\t\tthis.project = project ?? {\n\t\t\tkey: projectKey({ name: packageName(root) ?? basename(root) }),\n\t\t\tlegacy: [basename(root)],\n\t\t};\n\t}\n\n\t/** The file a stage's secrets are kept in. */\n\tpath(stage: string): string {\n\t\treturn join(this.root, SECRETS_DIR, `${stage}.json`);\n\t}\n\n\tasync read(stage: string): Promise<StageSecrets | null> {\n\t\tconst path = this.path(stage);\n\t\tif (!existsSync(path)) return null;\n\n\t\tconst data = JSON.parse(await readFile(path, 'utf-8'));\n\n\t\t// Legacy: unencrypted format (for backwards compatibility)\n\t\tif (!(data.version === 1 && data.encrypted && data.iv)) {\n\t\t\treturn data as StageSecrets;\n\t\t}\n\n\t\tconst key = await readKey(stage, this.project);\n\t\tif (!key) {\n\t\t\tthrow new MissingSecretsKey(\n\t\t\t\tstage,\n\t\t\t\tthis.project.key,\n\t\t\t\tgetKeyPath(stage, this.project),\n\t\t\t);\n\t\t}\n\n\t\treturn decrypt(data as EncryptedSecretsFile, key);\n\t}\n\n\tasync write(stage: string, secrets: StageSecrets): Promise<void> {\n\t\tawait mkdir(join(this.root, SECRETS_DIR), { recursive: true });\n\n\t\tconst key = await getOrCreateKey(stage, this.project);\n\t\tawait writeFile(\n\t\t\tthis.path(stage),\n\t\t\tJSON.stringify(encrypt(secrets, key), null, 2),\n\t\t\t'utf-8',\n\t\t);\n\t}\n}\n\n/** A stage's secrets file exists, and the key that opens it does not. */\nexport class MissingSecretsKey extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly project: string,\n\t\treadonly path: string,\n\t) {\n\t\tsuper(\n\t\t\t`Decryption key not found for stage \"${stage}\". ` +\n\t\t\t\t`Expected key at: ${path}. Copy the stage's key there from whoever created it, or set secrets.store to a store this machine can reach.`,\n\t\t);\n\t\tthis.name = 'MissingSecretsKey';\n\t}\n}\n\n/** A project's package name without its scope, as a workspace name reads it. */\nfunction packageName(root: string): string | undefined {\n\ttry {\n\t\tconst pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf-8'));\n\t\treturn typeof pkg.name === 'string'\n\t\t\t? pkg.name.replace(/^@[^/]+\\//, '')\n\t\t\t: undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Encrypt a JSON value with a stage key: AES-256-GCM, the file format every\n * stage's secrets are kept in.\n */\nexport function encrypt(\n\tsecrets: unknown,\n\tkeyHex: string,\n): EncryptedSecretsFile {\n\tconst key = Buffer.from(keyHex, 'hex');\n\tconst iv = randomBytes(IV_LENGTH);\n\n\tconst cipher = createCipheriv(ALGORITHM, key, iv);\n\tconst ciphertext = Buffer.concat([\n\t\tcipher.update(JSON.stringify(secrets), 'utf-8'),\n\t\tcipher.final(),\n\t]);\n\n\t// Ciphertext and auth tag, together\n\tconst combined = Buffer.concat([ciphertext, cipher.getAuthTag()]);\n\n\treturn {\n\t\tversion: 1,\n\t\tencrypted: combined.toString('base64'),\n\t\tiv: iv.toString('hex'),\n\t};\n}\n\n/** Decrypt what {@link encrypt} wrote. */\nexport function decrypt<T = StageSecrets>(\n\tdata: EncryptedSecretsFile,\n\tkeyHex: string,\n): T {\n\tconst key = Buffer.from(keyHex, 'hex');\n\tconst combined = Buffer.from(data.encrypted, 'base64');\n\n\tconst decipher = createDecipheriv(\n\t\tALGORITHM,\n\t\tkey,\n\t\tBuffer.from(data.iv, 'hex'),\n\t);\n\tdecipher.setAuthTag(combined.subarray(-AUTH_TAG_LENGTH));\n\n\tconst plaintext = Buffer.concat([\n\t\tdecipher.update(combined.subarray(0, -AUTH_TAG_LENGTH)),\n\t\tdecipher.final(),\n\t]);\n\n\treturn JSON.parse(plaintext.toString('utf-8')) as T;\n}\n","import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs';\nimport { dirname, join, sep } from 'node:path';\n\n/**\n * A package left out of a bundle, at the version the build resolved — what\n * an image installs beside the bundle, for its own platform.\n */\nexport type ExternalPackages = Record<string, string>;\n\n/**\n * The file beside a bundle naming the packages it left out, each at the\n * version the build resolved: a `package.json` an image installs, for its own\n * platform, next to the bundle. `server.mjs` → `server.externals.json`.\n */\nexport function externalsManifestName(outfile: string): string {\n\treturn `${outfile.replace(/\\.mjs$/, '')}.externals.json`;\n}\n\n/**\n * Asked to leave a package out of the bundle, and nothing the app depends on\n * provides it: there is no version to install in the image.\n */\nexport class ExternalNotInstalled extends Error {\n\tconstructor(\n\t\treadonly packageName: string,\n\t\treadonly root: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${packageName}' is left out of the bundle, to be installed beside it, but it is not installed for the app at ${root}: add it to the app's dependencies.`,\n\t\t);\n\t\tthis.name = 'ExternalNotInstalled';\n\t}\n}\n\ninterface PackageJson {\n\tname?: string;\n\tversion?: string;\n\tdependencies?: Record<string, string>;\n\toptionalDependencies?: Record<string, string>;\n\tgypfile?: boolean;\n\tbinary?: unknown;\n\tnapi?: unknown;\n\tos?: string[];\n}\n\n/** Packages whose job is loading a compiled addon. */\nconst NATIVE_LOADERS = new Set([\n\t'bindings',\n\t'node-gyp-build',\n\t'node-gyp-build-optional-packages',\n\t'node-pre-gyp',\n\t'@mapbox/node-pre-gyp',\n\t'prebuild-install',\n\t'@neon-rs/load',\n]);\n\n/** A per-platform binary package: `@node-rs/argon2-linux-x64-gnu`, `@img/sharp-darwin-arm64`. */\nconst PLATFORM_PACKAGE =\n\t/(?:^|[-/])(?:linux|darwin|win32|freebsd|android)-(?:x64|arm64|arm|ia32)\\b/;\n\nfunction readPackage(dir: string): PackageJson | undefined {\n\ttry {\n\t\treturn JSON.parse(readFileSync(join(dir, 'package.json'), 'utf-8'));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Where `name` resolves from `from`, the way Node finds it: the nearest\n * `node_modules/<name>` walking up. Followed through symlinks, so a pnpm\n * store package resolves its own dependencies beside it.\n */\nfunction locate(name: string, from: string): string | undefined {\n\tlet dir = from;\n\tfor (;;) {\n\t\tconst candidate = join(dir, 'node_modules', name);\n\t\tif (existsSync(join(candidate, 'package.json'))) {\n\t\t\treturn realpathSync(candidate);\n\t\t}\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) return undefined;\n\t\tdir = parent;\n\t}\n}\n\n/**\n * Whether a package carries compiled code: a `binding.gyp` or prebuilt\n * binaries of its own, a loader for them, or a binary package per platform.\n * Such a package cannot be inlined into a bundle — it loads a `.node` file\n * from beside its own source, for the platform it was installed on.\n */\nexport function isNativePackage(dir: string, pkg: PackageJson): boolean {\n\tif (pkg.gypfile || pkg.binary || pkg.napi) return true;\n\tconst deps = Object.keys({\n\t\t...pkg.dependencies,\n\t\t...pkg.optionalDependencies,\n\t});\n\tif (deps.some((dep) => NATIVE_LOADERS.has(dep))) return true;\n\tif (\n\t\tObject.keys(pkg.optionalDependencies ?? {}).some((dep) =>\n\t\t\tPLATFORM_PACKAGE.test(dep),\n\t\t)\n\t) {\n\t\treturn true;\n\t}\n\tif (existsSync(join(dir, 'binding.gyp'))) return true;\n\tif (existsSync(join(dir, 'prebuilds'))) return true;\n\ttry {\n\t\treturn readdirSync(dir).some((file) => file.endsWith('.node'));\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * The packages with native code an app's bundle would otherwise inline, each\n * at the version installed for it.\n *\n * Walks what the app depends on at runtime — `dependencies`, never\n * `devDependencies` — through workspace packages and installed ones alike,\n * since anything reached is bundled. A native package is where the walk\n * stops: installing it brings what it depends on.\n */\nexport function nativeDependencies(root: string): ExternalPackages {\n\tconst found: ExternalPackages = {};\n\tconst seen = new Set<string>();\n\tconst queue = [realpathSync(root)];\n\n\twhile (queue.length > 0) {\n\t\tconst dir = queue.shift()!;\n\t\tif (seen.has(dir)) continue;\n\t\tseen.add(dir);\n\n\t\tconst pkg = readPackage(dir);\n\t\tif (!pkg) continue;\n\t\tconst isRoot = seen.size === 1;\n\t\tconst installed = dir.split(sep).includes('node_modules');\n\n\t\tif (!isRoot && installed && isNativePackage(dir, pkg)) {\n\t\t\t// One that cannot install on Linux — fsevents — is never in an image;\n\t\t\t// whatever loads it does without.\n\t\t\tconst linux =\n\t\t\t\t!pkg.os ||\n\t\t\t\tpkg.os.includes('linux') ||\n\t\t\t\t(pkg.os.every((os) => os.startsWith('!')) &&\n\t\t\t\t\t!pkg.os.includes('!linux'));\n\t\t\tif (linux && pkg.name && pkg.version && !(pkg.name in found)) {\n\t\t\t\tfound[pkg.name] = pkg.version;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tfor (const dep of Object.keys({\n\t\t\t...pkg.dependencies,\n\t\t\t...pkg.optionalDependencies,\n\t\t})) {\n\t\t\tconst location = locate(dep, dir);\n\t\t\tif (location && !seen.has(location)) queue.push(location);\n\t\t}\n\t}\n\n\treturn Object.fromEntries(\n\t\tObject.entries(found).sort(([a], [b]) => a.localeCompare(b)),\n\t);\n}\n\n/**\n * What a bundle leaves out, with the version of each to install: the native\n * packages found under `root`, and any it was asked to leave out besides,\n * at the version installed for the app.\n */\nexport function bundleExternals(\n\troot: string,\n\tdeclared: readonly string[],\n): ExternalPackages {\n\tconst externals = nativeDependencies(root);\n\tfor (const name of declared) {\n\t\tif (name in externals) continue;\n\t\tconst location = locate(name, root);\n\t\tconst version = location ? readPackage(location)?.version : undefined;\n\t\tif (!version) throw new ExternalNotInstalled(name, root);\n\t\texternals[name] = version;\n\t}\n\treturn Object.fromEntries(\n\t\tObject.entries(externals).sort(([a], [b]) => a.localeCompare(b)),\n\t);\n}\n\n/** The package a bare specifier names: `argon2/lib` → `argon2`, `@a/b/c` → `@a/b`. */\nfunction packageOf(specifier: string): string {\n\tconst parts = specifier.split('/');\n\treturn specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]!;\n}\n\n/**\n * The packages a bundle imports at runtime rather than inlining, read from\n * esbuild's metafile. Nothing when there is no metafile.\n */\nexport function importedPackages(metafile: string): Set<string> {\n\tlet meta: {\n\t\toutputs?: Record<\n\t\t\tstring,\n\t\t\t{ imports?: { path: string; external?: boolean }[] }\n\t\t>;\n\t};\n\ttry {\n\t\tmeta = JSON.parse(readFileSync(metafile, 'utf-8'));\n\t} catch {\n\t\treturn new Set();\n\t}\n\tconst imported = new Set<string>();\n\tfor (const output of Object.values(meta.outputs ?? {})) {\n\t\tfor (const { path, external } of output.imports ?? []) {\n\t\t\tif (external && !path.startsWith('.') && !path.startsWith('node:')) {\n\t\t\t\timported.add(packageOf(path));\n\t\t\t}\n\t\t}\n\t}\n\treturn imported;\n}\n","/**\n * What a stage's secrets are, independent of where they are kept: building\n * them, changing them, and handing them to a process. Where they are kept is a\n * {@link SecretsStore}'s business — see `secretsStoreFor`.\n */\n\nimport { isReservedStageKey } from '../compose/dnsConfig.js';\nimport type { SecretsStore } from './store.js';\nimport type { EmbeddableSecrets, StageSecrets } from './types';\n\n/**\n * Initialize an empty StageSecrets object for a stage.\n */\nexport function initStageSecrets(stage: string): StageSecrets {\n\tconst now = new Date().toISOString();\n\treturn {\n\t\tstage,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tservices: {},\n\t\turls: {},\n\t\tcustom: {},\n\t};\n}\n\n/**\n * Convert StageSecrets to embeddable format (flat key-value pairs).\n * This is what gets encrypted and embedded in the bundle.\n */\nexport function toEmbeddableSecrets(secrets: StageSecrets): EmbeddableSecrets {\n\treturn {\n\t\t...secrets.urls,\n\t\t// The server's address (`GKM_SERVER_*`) is gkm's own, never an app's.\n\t\t...Object.fromEntries(\n\t\t\tObject.entries(secrets.custom).filter(\n\t\t\t\t([key]) => !isReservedStageKey(key),\n\t\t\t),\n\t\t),\n\t\t// Also include individual service credentials if needed\n\t\t...(secrets.services.postgres && {\n\t\t\tPOSTGRES_USER: secrets.services.postgres.username,\n\t\t\tPOSTGRES_PASSWORD: secrets.services.postgres.password,\n\t\t\tPOSTGRES_DB: secrets.services.postgres.database ?? 'app',\n\t\t\tPOSTGRES_HOST: secrets.services.postgres.host,\n\t\t\tPOSTGRES_PORT: String(secrets.services.postgres.port),\n\t\t}),\n\t\t...(secrets.services.redis && {\n\t\t\tREDIS_PASSWORD: secrets.services.redis.password,\n\t\t\tREDIS_HOST: secrets.services.redis.host,\n\t\t\tREDIS_PORT: String(secrets.services.redis.port),\n\t\t}),\n\t\t...(secrets.services.minio && {\n\t\t\tSTORAGE_ACCESS_KEY_ID: secrets.services.minio.username,\n\t\t\tSTORAGE_SECRET_ACCESS_KEY: secrets.services.minio.password,\n\t\t\tSTORAGE_BUCKET: secrets.services.minio.bucket ?? 'app',\n\t\t\tSTORAGE_REGION: 'eu-west-1',\n\t\t\tSTORAGE_FORCE_PATH_STYLE: 'true',\n\t\t}),\n\t\t...(secrets.services.mailpit && {\n\t\t\tSMTP_HOST: secrets.services.mailpit.host,\n\t\t\tSMTP_PORT: String(secrets.services.mailpit.port),\n\t\t\tSMTP_USER: secrets.services.mailpit.username,\n\t\t\tSMTP_PASS: secrets.services.mailpit.password,\n\t\t\tSMTP_SECURE: 'false',\n\t\t\tMAIL_FROM: 'noreply@localhost',\n\t\t}),\n\t\t...(secrets.services.localstack && {\n\t\t\tAWS_ACCESS_KEY_ID:\n\t\t\t\tsecrets.services.localstack.accessKeyId ??\n\t\t\t\tsecrets.services.localstack.username,\n\t\t\tAWS_SECRET_ACCESS_KEY: secrets.services.localstack.password,\n\t\t\tAWS_REGION: secrets.services.localstack.region ?? 'us-east-1',\n\t\t\tAWS_ENDPOINT_URL: `http://${secrets.services.localstack.host}:${secrets.services.localstack.port}`,\n\t\t}),\n\t};\n}\n\n/** The same secrets with one custom value set, and `updatedAt` moved on. */\nexport function withCustomSecret(\n\tsecrets: StageSecrets,\n\tkey: string,\n\tvalue: string,\n): StageSecrets {\n\treturn {\n\t\t...secrets,\n\t\tupdatedAt: new Date().toISOString(),\n\t\tcustom: { ...secrets.custom, [key]: value },\n\t};\n}\n\n/**\n * Mask a password for display (show first 4 and last 2 chars).\n */\nexport function maskPassword(password: string): string {\n\tif (password.length <= 8) {\n\t\treturn '********';\n\t}\n\treturn `${password.slice(0, 4)}${'*'.repeat(password.length - 6)}${password.slice(-2)}`;\n}\n\n/**\n * Result of environment variable validation.\n */\nexport interface EnvValidationResult {\n\t/** Whether all required environment variables are present */\n\tvalid: boolean;\n\t/** List of missing environment variable names */\n\tmissing: string[];\n\t/** List of environment variables that are provided */\n\tprovided: string[];\n\t/** List of environment variables that were required */\n\trequired: string[];\n}\n\n/**\n * Validate that all required environment variables are present in secrets.\n *\n * @param requiredVars - Array of environment variable names required by the application\n * @param secrets - Stage secrets to validate against\n * @returns Validation result with missing and provided variables\n *\n * @example\n * ```typescript\n * const required = ['DATABASE_URL', 'API_KEY', 'JWT_SECRET'];\n * const secrets = await secretsStoreFor(workspace, 'production').then((s) => s.read('production'));\n * const result = validateEnvironmentVariables(required, secrets);\n *\n * if (!result.valid) {\n * console.error(`Missing environment variables: ${result.missing.join(', ')}`);\n * }\n * ```\n */\nexport function validateEnvironmentVariables(\n\trequiredVars: string[],\n\tsecrets: StageSecrets,\n): EnvValidationResult {\n\tconst embeddable = toEmbeddableSecrets(secrets);\n\tconst availableVars = new Set(Object.keys(embeddable));\n\n\tconst missing: string[] = [];\n\tconst provided: string[] = [];\n\n\tfor (const varName of requiredVars) {\n\t\tif (availableVars.has(varName)) {\n\t\t\tprovided.push(varName);\n\t\t} else {\n\t\t\tmissing.push(varName);\n\t\t}\n\t}\n\n\treturn {\n\t\tvalid: missing.length === 0,\n\t\tmissing: missing.sort(),\n\t\tprovided: provided.sort(),\n\t\trequired: [...requiredVars].sort(),\n\t};\n}\n","/**\n * Where a stage's secrets are kept.\n *\n * Every command that needs a stage's secrets — `gkm dev`, `test`, `deploy`,\n * `build`, `setup`, `secrets:*` — asks {@link secretsStoreFor} for that\n * stage's store and reads or writes it. None of them knows whether that is a\n * file on this machine, or S3, SSM or Secrets Manager in the stage's account: the local stage is\n * always the file, and a deployed stage is whatever `secrets.store` names.\n *\n * The same shape deploy state has (`StateProvider`): one interface, a backend\n * per place, and a custom object for any place this package does not ship.\n */\n\nimport type { NormalizedWorkspace } from '../workspace/types.js';\nimport { FileSecretsStore } from './file.js';\nimport { keystoreProject } from './keystore.js';\nimport { s3SecretsLocation, UnknownSecretsStoreProvider } from './providers.js';\nimport type { StageSecrets } from './types.js';\n\nexport interface SecretsStore {\n\t/**\n\t * Which kind of store this is — `'file'`, `'s3'`, `'ssm'`,\n\t * `'secrets-manager'`, or a custom one's.\n\t */\n\treadonly name: string;\n\t/** The stage's secrets, or null when it has none here. */\n\tread(stage: string): Promise<StageSecrets | null>;\n\t/** Replace the stage's secrets. */\n\twrite(stage: string, secrets: StageSecrets): Promise<void>;\n}\n\n/** Secrets in SSM Parameter Store, in the account of the active credentials. */\nexport interface SsmSecretsStoreConfig {\n\tprovider: 'ssm';\n\tregion: string;\n}\n\n/**\n * Secrets in AWS Secrets Manager, in the account of the active credentials:\n * one secret per stage, `gkm/<project>/<stage>/secrets`. Up to 64 KB where\n * SSM holds 8 KB, at a monthly price per secret.\n */\nexport interface SecretsManagerSecretsStoreConfig {\n\tprovider: 'secrets-manager';\n\tregion: string;\n\t/**\n\t * The KMS key (id, ARN or alias) a stage's secret is created with. Unset,\n\t * it is the account's AWS-managed `aws/secretsmanager` key.\n\t */\n\tkmsKeyId?: string;\n}\n\n/**\n * Secrets in S3, one object per stage —\n * `<prefix>/<project>/<stage>/secrets.json` — in the project bucket beside the\n * deploy state and backups, or in a bucket that exists. Encrypted with SSE-S3,\n * every past document kept by the bucket's versioning, and no size limit.\n */\nexport interface S3SecretsStoreConfig {\n\tprovider: 's3';\n\t/**\n\t * A bucket that already exists. Omitted, the project bucket —\n\t * `gkm-<project>-<account id>`, created by the first write.\n\t */\n\tbucket?: string;\n\t/** The bucket's region. Omitted, the deploy state's, when it is in S3. */\n\tregion?: string;\n\t/** Key prefix inside the bucket. Omitted, the S3 state's, else `gkm`. */\n\tprefix?: string;\n}\n\n/** Any other backend: an object implementing {@link SecretsStore}. */\nexport interface CustomSecretsStoreConfig {\n\tprovider: SecretsStore;\n}\n\n/**\n * `secrets.store` in gkm.config.ts.\n *\n * `'file'` — the default — keeps each stage's secrets in the encrypted\n * `.gkm/secrets/<stage>.json`, its key in the CLI's home (`GKM_HOME`, else\n * `~/.gkm`). It cannot serve a\n * deploy from CI while `.gkm/` is gitignored; `s3`, `ssm`, `secrets-manager`\n * or a custom store can.\n */\nexport type SecretsStoreConfig =\n\t| 'file'\n\t| S3SecretsStoreConfig\n\t| SsmSecretsStoreConfig\n\t| SecretsManagerSecretsStoreConfig\n\t| CustomSecretsStoreConfig;\n\nexport interface SecretsStoreOptions {\n\t/**\n\t * The AWS profile for the stage's account. Only that profile is used —\n\t * never AWS_* from the environment — so a store cannot quietly land in\n\t * whichever account the shell was exported for.\n\t */\n\tprofile?: string;\n\t/**\n\t * The CLI's home, where a file store's keys are kept. Defaults to\n\t * `GKM_HOME`, else `~/.gkm`.\n\t */\n\thome?: string;\n}\n\n/**\n * The store a stage's secrets are kept in — what every command reads and\n * writes, for the stage it acts on.\n *\n * The local stage is always the file: its secrets belong to the machine\n * running `gkm dev`. A deployed stage uses `secrets.store`.\n */\nexport async function secretsStoreFor(\n\tworkspace: NormalizedWorkspace,\n\tstage: string,\n\toptions: SecretsStoreOptions = {},\n): Promise<SecretsStore> {\n\tconst configured = workspace.secrets.store ?? 'file';\n\n\tif (stage === workspace.stages.local || configured === 'file') {\n\t\treturn new FileSecretsStore(\n\t\t\tworkspace.root,\n\t\t\tkeystoreProject(workspace, options.home),\n\t\t);\n\t}\n\n\treturn storeFromConfig(workspace, configured, options);\n}\n\n/**\n * The store a `secrets.store` value describes, for any stage — what\n * {@link secretsStoreFor} answers for a deployed stage, and what\n * `gkm secrets:migrate` builds for the store it copies to.\n */\nexport async function storeFromConfig(\n\tworkspace: NormalizedWorkspace,\n\tconfig: SecretsStoreConfig,\n\toptions: SecretsStoreOptions = {},\n): Promise<SecretsStore> {\n\tif (config === 'file') {\n\t\treturn new FileSecretsStore(\n\t\t\tworkspace.root,\n\t\t\tkeystoreProject(workspace, options.home),\n\t\t);\n\t}\n\n\tconst profile = options.profile ? { profile: options.profile } : {};\n\n\tswitch (config.provider) {\n\t\tcase 's3': {\n\t\t\tconst { S3SecretsStore } = await import('./s3.js');\n\t\t\tconst { deployIdentity } = await import('../deploy/identity.js');\n\t\t\tconst location = s3SecretsLocation(\n\t\t\t\tconfig as S3SecretsStoreConfig,\n\t\t\t\tworkspace.state,\n\t\t\t);\n\t\t\treturn new S3SecretsStore({\n\t\t\t\tproject: workspace.name,\n\t\t\t\tidentity: deployIdentity(workspace, ''),\n\t\t\t\tregion: location.region,\n\t\t\t\tprefix: location.prefix,\n\t\t\t\t...(location.bucket ? { bucket: location.bucket } : {}),\n\t\t\t\t...profile,\n\t\t\t});\n\t\t}\n\t\tcase 'ssm': {\n\t\t\tconst { AwsSecretsStore } = await import('./aws.js');\n\t\t\treturn new AwsSecretsStore({\n\t\t\t\tproject: workspace.name,\n\t\t\t\tregion: config.region,\n\t\t\t\t...profile,\n\t\t\t});\n\t\t}\n\t\tcase 'secrets-manager': {\n\t\t\tconst { kmsKeyId } = config as SecretsManagerSecretsStoreConfig;\n\t\t\tconst { SecretsManagerSecretsStore } = await import(\n\t\t\t\t'./secretsManager.js'\n\t\t\t);\n\t\t\treturn new SecretsManagerSecretsStore({\n\t\t\t\tproject: workspace.name,\n\t\t\t\tregion: config.region,\n\t\t\t\t...(kmsKeyId ? { kmsKeyId } : {}),\n\t\t\t\t...profile,\n\t\t\t});\n\t\t}\n\t\tdefault: {\n\t\t\t// Typed as a SecretsStore, but a config assembled by hand may name\n\t\t\t// a provider that is not one.\n\t\t\tconst provider: unknown = config.provider;\n\t\t\tif (typeof provider === 'object' && provider !== null) {\n\t\t\t\treturn provider as SecretsStore;\n\t\t\t}\n\t\t\tthrow new UnknownSecretsStoreProvider(provider);\n\t\t}\n\t}\n}\n\n/** Whether a stage's secrets live somewhere other than this machine. */\nexport function isRemoteStore(\n\tworkspace: NormalizedWorkspace,\n\tstage: string,\n): boolean {\n\tconst configured = workspace.secrets.store ?? 'file';\n\treturn stage !== workspace.stages.local && configured !== 'file';\n}\n\nexport { FileSecretsStore };\nexport {\n\tassertKnownSecretsStore,\n\tS3SecretsStoreNeedsRegion,\n\tSECRETS_STORE_PROVIDERS,\n\ttype SecretsStoreProvider,\n\ts3SecretsLocation,\n\tUnknownSecretsStoreProvider,\n} from './providers.js';\n","/**\n * Which backend each declared kind resolves to — decided by where the project\n * deploys, and by nothing else.\n *\n * These used to be read out of a `services:` block, where one key answered two\n * questions: *does this exist* and *what backs it*. The first is the manifest's\n * — a declared `Cache` is why there is a cache — and the second is the deploy\n * target's, because the right cache for a Lambda is not the right cache for a\n * box already running Postgres. With both answered elsewhere there was nothing\n * left for the block to say, so it is gone and these read the target.\n *\n * Mail has no answer here at all: every provider speaks SMTP, so the provider\n * is whichever one the stage's mail URL points at.\n */\n\nimport { runtimeOf, type TargetSource } from '../target/runtime.js';\nimport {\n\tDEFAULT_CACHE,\n\tDEFAULT_EVENTS,\n\tDEFAULT_STORAGE,\n\ttype EventsBackend,\n\ttype MainProvider,\n\ttype StorageBackend,\n\ttype TargetCacheBackend,\n} from '../types.js';\n\n/**\n * Which family of defaults a workspace's deploy target belongs to.\n *\n * One question, asked once: **does this target run containers the project\n * controls?** Dokploy does, so a bucket or a cache can live beside the app;\n * AWS, Vercel and Cloudflare do not, so the default has to be something\n * managed. That is the whole of the distinction, and it is why `MainProvider`\n * is the right axis rather than the deploy target's own name — targets share\n * answers.\n *\n * Each target declares its answer as its `runtime` — a target package in its\n * `package.json`, so this never loads one. A workspace that names no target\n * is on AWS: an SST project predates `deploy.default: 'sst'`.\n */\nexport function providerOf(workspace: TargetSource): MainProvider {\n\tconst target = workspace.deploy?.default;\n\treturn target ? runtimeOf(target, workspace) : 'aws';\n}\n\n/**\n * The cache backend a target implies.\n *\n * The same answer locally and deployed: a local `gkm dev` for an AWS app still\n * uses the Upstash protocol, because a backend that differed between the two\n * would be worse than a slower one.\n */\nexport function cacheBackendFor(on: MainProvider): TargetCacheBackend {\n\treturn DEFAULT_CACHE[on];\n}\n\n/** Where a declared bucket lives on a target. */\nexport function storageBackendFor(on: MainProvider): StorageBackend {\n\treturn DEFAULT_STORAGE[on];\n}\n\n/**\n * Which broker carries declared queues and topics on a target.\n *\n * Only consulted when something declares one; a project with no `Topic` or\n * `Queue` has no events at all, whatever the target.\n */\nexport function eventsBackendFor(on: MainProvider): EventsBackend {\n\treturn DEFAULT_EVENTS[on];\n}\n","/**\n * A file server's processors as a CDN origin: the names both sides agree on.\n *\n * On a compose stage whose bucket is on S3, the CDN serves the bucket and\n * sends each processor pattern to the stack's processor unit, at a host of\n * its own. That host is public — a CDN reaches its origin over the internet —\n * so the CDN adds a secret header and the edge refuses any request without\n * it. One definition, read by the CDN that sends the header and by the stack\n * whose edge checks it, so the two cannot drift.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport { provideKey } from '@geekmidas/manifest';\nimport { appKey } from '../workspace/derive.js';\n\n/** The header the CDN adds to every request it sends a processor. */\nexport const ORIGIN_VERIFY_HEADER = 'X-Gkm-Origin-Verify';\n\n/** Where a file server's processors answer the CDN: `<fileserver>-processors.<domain>`. */\nexport function processorOriginHost(serverId: string, domain: string): string {\n\treturn `${appKey(serverId)}-processors.${domain}`.toLowerCase();\n}\n\n/** The stage secret holding the header's value: `ASSETS_SERVER_ORIGIN_SECRET`. */\nexport function originSecretKey(serverId: string): string {\n\treturn provideKey(serverId, 'originSecret');\n}\n\n/**\n * What the processor unit reads that secret from. Set wherever the CDN fronts\n * it, so the unit refuses a request without the header itself — on Dokploy,\n * whose edge cannot match a header, the only check; behind the stack's own\n * edge, a second one.\n */\nexport const PROCESSOR_ORIGIN_SECRET_ENV = 'GKM_PROCESSOR_ORIGIN_SECRET';\n\n/** A new value for that secret: random, generated once, kept in the stage. */\nexport function newOriginSecret(): string {\n\treturn randomBytes(32).toString('base64url');\n}\n","/**\n * A stage's deploy state.\n *\n * Every target records the same core — when the stage was last deployed, by\n * which identity, and each app's releases — and a target that keeps ids of\n * its own adds them in a shape of its own, told apart by `provider`:\n *\n * - `dokploy`: the project, applications, services and credentials Dokploy\n * gave the stage, so a later deploy updates them rather than making more.\n * - `compose`: nothing beyond the core. A compose stage is one stack on one\n * server; what it created elsewhere (DNS records) is a resource record.\n */\n\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { output } from '../output';\nimport type { Actor } from './actor';\n\n/**\n * Per-app database credentials\n */\nexport interface AppDbCredentials {\n\tdbUser: string;\n\tdbPassword: string;\n}\n\n/**\n * DNS verification record for a hostname\n */\nexport interface DnsVerificationRecord {\n\tserverIp: string;\n\tverifiedAt: string;\n}\n\n/**\n * A DNS record that was created during deploy\n */\nexport interface CreatedDnsRecord {\n\t/** The domain this record belongs to (e.g., 'example.com') */\n\tdomain: string;\n\t/** Record name/subdomain (e.g., 'api' or '@' for root) */\n\tname: string;\n\t/** Record type (A, CNAME, etc.) */\n\ttype: string;\n\t/** Record value (IP address, hostname, etc.) */\n\tvalue: string;\n\t/** TTL in seconds */\n\tttl: number;\n\t/** When this record was created */\n\tcreatedAt: string;\n}\n\n/**\n * Backup destination state\n */\nexport interface BackupState {\n\t/** S3 bucket name for backups */\n\tbucketName: string;\n\t/** S3 bucket ARN */\n\tbucketArn: string;\n\t/** IAM user name created for backup access */\n\tiamUserName: string;\n\t/** IAM access key ID */\n\tiamAccessKeyId: string;\n\t/** IAM secret access key */\n\tiamSecretAccessKey: string;\n\t/** Dokploy destination ID */\n\tdestinationId: string;\n\t/** Dokploy backup schedule ID for postgres (if configured) */\n\tpostgresBackupId?: string;\n\t/** AWS region where bucket was created */\n\tregion: string;\n\t/** Timestamp when backup was configured */\n\tcreatedAt: string;\n}\n\n/** What every target's state for a stage holds. */\nexport interface StageStateCore {\n\tstage: string;\n\tlastDeployedAt: string;\n\t/**\n\t * The deploy identity's key (`<namespace>/<project>`) that last deployed\n\t * this stage — what the project's ownership marker says.\n\t */\n\tidentity?: string;\n\t/**\n\t * Each app's releases, keyed by app name: what runs now, what ran before\n\t * it — which `gkm deploy:rollback` restores — and the history behind both.\n\t */\n\treleases?: Record<string, AppReleases>;\n}\n\n/** A compose stage's state: the core, and nothing Dokploy-specific. */\nexport interface ComposeStageState extends StageStateCore {\n\tprovider: 'compose';\n}\n\n/**\n * State for a single stage deployment\n */\nexport interface DokployStageState extends StageStateCore {\n\tprovider: 'dokploy';\n\t/** Dokploy project ID - created on first deploy */\n\tprojectId: string;\n\tenvironmentId: string;\n\tapplications: Record<string, string>; // appName -> applicationId\n\tservices: {\n\t\tpostgresId?: string;\n\t\tredisId?: string;\n\t};\n\t/** Per-app database credentials for reuse on subsequent deploys */\n\tappCredentials?: Record<string, AppDbCredentials>;\n\t/** Auto-generated secrets per app (e.g., BETTER_AUTH_SECRET) */\n\tgeneratedSecrets?: Record<string, Record<string, string>>;\n\t/** DNS verification state per hostname */\n\tdnsVerified?: Record<string, DnsVerificationRecord>;\n\t/** DNS records created during deploy (keyed by \"name:type\", e.g., \"api:A\") */\n\tdnsRecords?: Record<string, CreatedDnsRecord>;\n\t/** Backup destination state */\n\tbackups?: BackupState;\n\t/**\n\t * The Dokploy registry the stage's images are pulled through. Kept per\n\t * stage rather than once per machine, so a stage keeps the registry it was\n\t * deployed with whoever deploys it next.\n\t */\n\tregistryId?: string;\n}\n\n/** A stage's state, whichever target wrote it. */\nexport type StageState = DokployStageState | ComposeStageState;\n\n/** An image a stage runs: the ref it was pushed as, and what it resolved to. */\nexport interface DeployedImage {\n\tref: string;\n\t/**\n\t * The tag it was released under — a site's carries its stage\n\t * (`v1.4.0-production`). Recorded by targets that pull a release by tag.\n\t */\n\ttag?: string;\n\t/** The registry's digest, `sha256:…` — absent if it could not be read. */\n\tdigest?: string;\n}\n\n/**\n * Get the state file path for a stage\n */\nfunction getStateFilePath(workspaceRoot: string, stage: string): string {\n\treturn join(workspaceRoot, '.gkm', `deploy-${stage}.json`);\n}\n\n/**\n * Read the deploy state for a stage\n * Returns null if state file doesn't exist\n */\nexport async function readStageState(\n\tworkspaceRoot: string,\n\tstage: string,\n): Promise<StageState | null> {\n\tconst filePath = getStateFilePath(workspaceRoot, stage);\n\n\ttry {\n\t\tconst content = await readFile(filePath, 'utf-8');\n\t\treturn JSON.parse(content) as StageState;\n\t} catch (error) {\n\t\t// File doesn't exist or is invalid - return null\n\t\tif ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n\t\t\treturn null;\n\t\t}\n\t\t// Log other errors but don't fail\n\t\toutput.warn(`Warning: Could not read deploy state: ${error}`);\n\t\treturn null;\n\t}\n}\n\n/**\n * Write the deploy state for a stage\n */\nexport async function writeStageState(\n\tworkspaceRoot: string,\n\tstage: string,\n\tstate: StageState,\n): Promise<void> {\n\tconst filePath = getStateFilePath(workspaceRoot, stage);\n\tconst dir = join(workspaceRoot, '.gkm');\n\n\t// Ensure .gkm directory exists\n\tawait mkdir(dir, { recursive: true });\n\n\t// Update last deployed timestamp\n\tstate.lastDeployedAt = new Date().toISOString();\n\n\tawait writeFile(filePath, JSON.stringify(state, null, 2));\n}\n\n/**\n * Create a new empty state for a stage\n */\nexport function createEmptyState(\n\tstage: string,\n\tprojectId: string,\n\tenvironmentId: string,\n): DokployStageState {\n\treturn {\n\t\tprovider: 'dokploy',\n\t\tstage,\n\t\tprojectId,\n\t\tenvironmentId,\n\t\tapplications: {},\n\t\tservices: {},\n\t\tlastDeployedAt: new Date().toISOString(),\n\t};\n}\n\n/** A new compose stage's state. */\nexport function createComposeState(stage: string): ComposeStageState {\n\treturn {\n\t\tprovider: 'compose',\n\t\tstage,\n\t\tlastDeployedAt: new Date().toISOString(),\n\t};\n}\n\n/**\n * `state` as the Dokploy target keeps it. A stage whose state another target\n * wrote — one moved from compose to Dokploy — keeps its core (releases,\n * identity) and starts with no Dokploy ids, as a first deploy would.\n */\nexport function asDokployState(state: StageState): DokployStageState {\n\tif (state.provider === 'dokploy') return state;\n\tconst { provider: _provider, ...core } = state;\n\treturn {\n\t\t...core,\n\t\tprovider: 'dokploy',\n\t\tprojectId: '',\n\t\tenvironmentId: '',\n\t\tapplications: {},\n\t\tservices: {},\n\t};\n}\n\n/**\n * Get application ID from state\n */\nexport function getApplicationId(\n\tstate: DokployStageState | null,\n\tappName: string,\n): string | undefined {\n\treturn state?.applications[appName];\n}\n\n/**\n * Set application ID in state (mutates state)\n */\nexport function setApplicationId(\n\tstate: DokployStageState,\n\tappName: string,\n\tapplicationId: string,\n): void {\n\tstate.applications[appName] = applicationId;\n}\n\n/** An image that went live, and when. */\nexport interface ReleasedImage extends DeployedImage {\n\t/** The image tag the deploy released under. */\n\ttag?: string;\n\treleasedAt: string;\n\t/** Who released it — absent on a release recorded before it was kept. */\n\treleasedBy?: Actor;\n\t/** Set when a rollback replaced it: it is never rolled back *to*. */\n\trolledBack?: true;\n}\n\n/** An app's releases: what runs, what ran before it, and what ran before that. */\nexport interface AppReleases {\n\tcurrent: ReleasedImage;\n\t/** What a rollback restores; absent until a second release. */\n\tprevious?: ReleasedImage;\n\t/** Every release, newest first, at most {@link RELEASE_HISTORY} of them. */\n\thistory: ReleasedImage[];\n}\n\n/** How many releases an app's history keeps. */\nexport const RELEASE_HISTORY = 10;\n\n/** Two records naming the same image: by digest when both have one. */\nfunction sameImage(a: DeployedImage, b: DeployedImage): boolean {\n\treturn a.digest && b.digest ? a.digest === b.digest : a.ref === b.ref;\n}\n\n/** The newest release in `history` after `index` that a rollback may restore. */\nfunction restorable(\n\thistory: readonly ReleasedImage[],\n\tindex: number,\n\tcurrent: DeployedImage,\n): ReleasedImage | undefined {\n\treturn history\n\t\t.slice(index + 1)\n\t\t.find((entry) => !entry.rolledBack && !sameImage(entry, current));\n}\n\n/**\n * Record that `image` went live for `appName` (mutates state): it becomes\n * `current`, and what was current becomes `previous`. Releasing what already\n * runs — a redeploy of the same digest — changes nothing.\n */\nexport function recordRelease(\n\tstate: StageStateCore,\n\tappName: string,\n\timage: Omit<ReleasedImage, 'releasedAt' | 'releasedBy' | 'rolledBack'>,\n\tby: Actor,\n\treleasedAt: Date = new Date(),\n): void {\n\tconst releases = state.releases?.[appName];\n\tif (releases && sameImage(releases.current, image)) return;\n\n\tconst entry: ReleasedImage = {\n\t\t...image,\n\t\treleasedAt: releasedAt.toISOString(),\n\t\treleasedBy: by,\n\t};\n\tconst history = [entry, ...(releases?.history ?? [])].slice(\n\t\t0,\n\t\tRELEASE_HISTORY,\n\t);\n\tconst previous = releases?.current;\n\tstate.releases = {\n\t\t...state.releases,\n\t\t[appName]: { current: entry, ...(previous ? { previous } : {}), history },\n\t};\n}\n\n/**\n * Record that `appName` was rolled back to `to` (mutates state): every\n * release newer than it is marked rolled back, so neither this rollback nor\n * a later one restores it, and `previous` moves to the release before `to`.\n */\nexport function recordRollback(\n\tstate: StageStateCore,\n\tappName: string,\n\tto: DeployedImage,\n): void {\n\tconst releases = state.releases?.[appName];\n\tif (!releases) return;\n\n\tconst index = releases.history.findIndex(\n\t\t(entry) => !entry.rolledBack && sameImage(entry, to),\n\t);\n\tif (index === -1) return;\n\n\tconst history = releases.history.map((entry, i) =>\n\t\ti < index ? { ...entry, rolledBack: true as const } : entry,\n\t);\n\tconst current = history[index]!;\n\tconst previous = restorable(history, index, current);\n\tstate.releases = {\n\t\t...state.releases,\n\t\t[appName]: { current, ...(previous ? { previous } : {}), history },\n\t};\n}\n\n/**\n * Get postgres ID from state\n */\nexport function getPostgresId(\n\tstate: DokployStageState | null,\n): string | undefined {\n\treturn state?.services.postgresId;\n}\n\n/**\n * Set postgres ID in state (mutates state)\n */\nexport function setPostgresId(\n\tstate: DokployStageState,\n\tpostgresId: string,\n): void {\n\tstate.services.postgresId = postgresId;\n}\n\n/**\n * Get redis ID from state\n */\nexport function getRedisId(\n\tstate: DokployStageState | null,\n): string | undefined {\n\treturn state?.services.redisId;\n}\n\n/**\n * Set redis ID in state (mutates state)\n */\nexport function setRedisId(state: DokployStageState, redisId: string): void {\n\tstate.services.redisId = redisId;\n}\n\n/**\n * Get app credentials from state\n */\nexport function getAppCredentials(\n\tstate: DokployStageState | null,\n\tappName: string,\n): AppDbCredentials | undefined {\n\treturn state?.appCredentials?.[appName];\n}\n\n/**\n * Set app credentials in state (mutates state)\n */\nexport function setAppCredentials(\n\tstate: DokployStageState,\n\tappName: string,\n\tcredentials: AppDbCredentials,\n): void {\n\tif (!state.appCredentials) {\n\t\tstate.appCredentials = {};\n\t}\n\tstate.appCredentials[appName] = credentials;\n}\n\n/**\n * Get all app credentials from state\n */\nexport function getAllAppCredentials(\n\tstate: DokployStageState | null,\n): Record<string, AppDbCredentials> {\n\treturn state?.appCredentials ?? {};\n}\n\n// ============================================================================\n// Generated Secrets\n// ============================================================================\n\n/**\n * Get a generated secret for an app\n */\nexport function getGeneratedSecret(\n\tstate: DokployStageState | null,\n\tappName: string,\n\tsecretName: string,\n): string | undefined {\n\treturn state?.generatedSecrets?.[appName]?.[secretName];\n}\n\n/**\n * Set a generated secret for an app (mutates state)\n */\nexport function setGeneratedSecret(\n\tstate: DokployStageState,\n\tappName: string,\n\tsecretName: string,\n\tvalue: string,\n): void {\n\tif (!state.generatedSecrets) {\n\t\tstate.generatedSecrets = {};\n\t}\n\tif (!state.generatedSecrets[appName]) {\n\t\tstate.generatedSecrets[appName] = {};\n\t}\n\tstate.generatedSecrets[appName][secretName] = value;\n}\n\n/**\n * Get all generated secrets for an app\n */\nexport function getAppGeneratedSecrets(\n\tstate: DokployStageState | null,\n\tappName: string,\n): Record<string, string> {\n\treturn state?.generatedSecrets?.[appName] ?? {};\n}\n\n/**\n * Get all generated secrets from state\n */\nexport function getAllGeneratedSecrets(\n\tstate: DokployStageState | null,\n): Record<string, Record<string, string>> {\n\treturn state?.generatedSecrets ?? {};\n}\n\n// ============================================================================\n// DNS Verification\n// ============================================================================\n\n/**\n * Get DNS verification record for a hostname\n */\nexport function getDnsVerification(\n\tstate: DokployStageState | null,\n\thostname: string,\n): DnsVerificationRecord | undefined {\n\treturn state?.dnsVerified?.[hostname];\n}\n\n/**\n * Set DNS verification record for a hostname (mutates state)\n */\nexport function setDnsVerification(\n\tstate: DokployStageState,\n\thostname: string,\n\tserverIp: string,\n): void {\n\tif (!state.dnsVerified) {\n\t\tstate.dnsVerified = {};\n\t}\n\tstate.dnsVerified[hostname] = {\n\t\tserverIp,\n\t\tverifiedAt: new Date().toISOString(),\n\t};\n}\n\n/**\n * Check if a hostname is already verified with the given IP\n */\nexport function isDnsVerified(\n\tstate: DokployStageState | null,\n\thostname: string,\n\tserverIp: string,\n): boolean {\n\tconst record = state?.dnsVerified?.[hostname];\n\treturn record?.serverIp === serverIp;\n}\n\n/**\n * Get all DNS verification records from state\n */\nexport function getAllDnsVerifications(\n\tstate: DokployStageState | null,\n): Record<string, DnsVerificationRecord> {\n\treturn state?.dnsVerified ?? {};\n}\n\n// ============================================================================\n// DNS Records\n// ============================================================================\n\n/**\n * Get the key for a DNS record in state\n */\nfunction getDnsRecordKey(name: string, type: string): string {\n\treturn `${name}:${type}`;\n}\n\n/**\n * Get a created DNS record from state\n */\nexport function getDnsRecord(\n\tstate: DokployStageState | null,\n\tname: string,\n\ttype: string,\n): CreatedDnsRecord | undefined {\n\treturn state?.dnsRecords?.[getDnsRecordKey(name, type)];\n}\n\n/**\n * Set a created DNS record in state (mutates state)\n */\nexport function setDnsRecord(\n\tstate: DokployStageState,\n\trecord: Omit<CreatedDnsRecord, 'createdAt'>,\n): void {\n\tif (!state.dnsRecords) {\n\t\tstate.dnsRecords = {};\n\t}\n\tconst key = getDnsRecordKey(record.name, record.type);\n\tstate.dnsRecords[key] = {\n\t\t...record,\n\t\tcreatedAt: new Date().toISOString(),\n\t};\n}\n\n/**\n * Remove a DNS record from state (mutates state)\n */\nexport function removeDnsRecord(\n\tstate: DokployStageState,\n\tname: string,\n\ttype: string,\n): void {\n\tif (state.dnsRecords) {\n\t\tdelete state.dnsRecords[getDnsRecordKey(name, type)];\n\t}\n}\n\n/**\n * Get all created DNS records from state\n */\nexport function getAllDnsRecords(\n\tstate: DokployStageState | null,\n): CreatedDnsRecord[] {\n\tif (!state?.dnsRecords) {\n\t\treturn [];\n\t}\n\treturn Object.values(state.dnsRecords);\n}\n\n/**\n * Clear all DNS records from state (mutates state)\n */\nexport function clearDnsRecords(state: DokployStageState): void {\n\tstate.dnsRecords = {};\n\tstate.dnsVerified = {};\n}\n\n// ============================================================================\n// Backup State\n// ============================================================================\n\n/**\n * Get backup state from state\n */\nexport function getBackupState(\n\tstate: DokployStageState | null,\n): BackupState | undefined {\n\treturn state?.backups;\n}\n\n/**\n * Set backup state (mutates state)\n */\nexport function setBackupState(\n\tstate: DokployStageState,\n\tbackupState: BackupState,\n): void {\n\tstate.backups = backupState;\n}\n\n/**\n * Get backup destination ID from state\n */\nexport function getBackupDestinationId(\n\tstate: DokployStageState | null,\n): string | undefined {\n\treturn state?.backups?.destinationId;\n}\n\n/**\n * Get postgres backup ID from state\n */\nexport function getPostgresBackupId(\n\tstate: DokployStageState | null,\n): string | undefined {\n\treturn state?.backups?.postgresBackupId;\n}\n\n/**\n * Set postgres backup ID in state (mutates state)\n */\nexport function setPostgresBackupId(\n\tstate: DokployStageState,\n\tbackupId: string,\n): void {\n\tif (state.backups) {\n\t\tstate.backups.postgresBackupId = backupId;\n\t}\n}\n","/**\n * DNS Provider Interface\n *\n * Abstracts DNS operations for different providers.\n * Built-in providers: HostingerProvider, Route53Provider, GoDaddyProvider\n * Users can also supply custom implementations.\n *\n * Every value is the record's zone-file form, read and written alike: an MX\n * record's is `<priority> <host>` (see {@link mxValue}).\n */\n\nimport type { z } from 'zod/v4';\nimport { GkmError } from '../../../errors';\nimport type {\n\tCloudflareDnsProviderSchema,\n\tCustomDnsProviderSchema,\n\tDnsProviderSchema,\n\tDnsRecordSchema,\n\tDnsRecordTypeSchema,\n\tGoDaddyDnsProviderSchema,\n\tHostingerDnsProviderSchema,\n\tManualDnsProviderSchema,\n\tRoute53DnsProviderSchema,\n\tUpsertDnsRecordSchema,\n\tUpsertResultSchema,\n} from '../../../workspace/schema';\n\n// =============================================================================\n// DNS Record Types (derived from Zod schemas)\n// =============================================================================\n\n/**\n * DNS record types supported across providers.\n */\nexport type DnsRecordType = z.infer<typeof DnsRecordTypeSchema>;\n\n/**\n * A DNS record as returned by the provider.\n */\nexport type DnsRecord = z.infer<typeof DnsRecordSchema>;\n\n/**\n * A DNS record to create or update.\n */\nexport type UpsertDnsRecord = z.infer<typeof UpsertDnsRecordSchema>;\n\n/**\n * Result of an upsert operation.\n */\nexport type UpsertResult = z.infer<typeof UpsertResultSchema>;\n\n// =============================================================================\n// MX values\n// =============================================================================\n\n/**\n * An MX record's value as every provider here reads and writes it — the zone\n * file's `<priority> <host>`, which is what Route53 and Hostinger take as is.\n * A provider whose API keeps the priority apart (GoDaddy) splits it with\n * {@link parseMxValue}.\n */\nexport function mxValue(priority: number, host: string): string {\n\treturn `${priority} ${host.trim().replace(/\\.$/, '')}`;\n}\n\n/** An MX value that is not `<priority> <host>`. */\nexport class MxValueInvalid extends GkmError {\n\tconstructor(readonly value: string) {\n\t\tsuper(\n\t\t\t`'${value}' is not an MX record's value: it is written ` +\n\t\t\t\t\"'<priority> <host>', like '10 inbound-smtp.eu-west-1.amazonaws.com'. \" +\n\t\t\t\t'Build it with mxValue(priority, host).',\n\t\t);\n\t\tthis.name = 'MxValueInvalid';\n\t}\n}\n\n/**\n * The priority and host of an MX value.\n *\n * @throws {MxValueInvalid} for a value that is not `<priority> <host>`\n */\nexport function parseMxValue(value: string): {\n\tpriority: number;\n\thost: string;\n} {\n\tconst match = value.trim().match(/^(\\d{1,5})\\s+(\\S+)$/);\n\tconst priority = match ? Number(match[1]) : Number.NaN;\n\tif (!match || priority > 65535) throw new MxValueInvalid(value);\n\treturn { priority, host: match[2]!.replace(/\\.$/, '') };\n}\n\n// =============================================================================\n// DNS Provider Interface\n// =============================================================================\n\n/**\n * A record to delete from DNS.\n */\nexport interface DeleteDnsRecord {\n\t/** Record name/subdomain (e.g., 'api' or '@' for root) */\n\tname: string;\n\t/** Record type (A, CNAME, etc.) */\n\ttype: DnsRecordType;\n}\n\n/**\n * Result of a delete operation.\n */\nexport interface DeleteResult {\n\t/** The record that was requested for deletion */\n\trecord: DeleteDnsRecord;\n\t/** Whether the record was deleted */\n\tdeleted: boolean;\n\t/** Whether the record was not found (already deleted) */\n\tnotFound: boolean;\n\t/** Error message if deletion failed */\n\terror?: string;\n}\n\n/**\n * Interface for DNS providers.\n *\n * Implementations must handle:\n * - Getting all records for a domain\n * - Creating or updating records for a domain\n * - Deleting records from a domain\n */\nexport interface DnsProvider {\n\t/** Provider name for logging */\n\treadonly name: string;\n\n\t/**\n\t * Get all DNS records for a domain.\n\t *\n\t * @param domain - Root domain (e.g., 'example.com')\n\t * @returns Array of DNS records\n\t */\n\tgetRecords(domain: string): Promise<DnsRecord[]>;\n\n\t/**\n\t * The records of exactly these names and types, where the provider can\n\t * read them one at a time — cheaper than the whole zone on an API that\n\t * counts requests. Optional: without it, `getRecords` is filtered.\n\t * Throws {@link DnsRecordsUnreadable} when the credentials can only write.\n\t *\n\t * @param domain - Root domain (e.g., 'example.com')\n\t * @param wanted - The names ('@' for the root) and types to read\n\t */\n\treadRecords?(\n\t\tdomain: string,\n\t\twanted: readonly DeleteDnsRecord[],\n\t): Promise<DnsRecord[]>;\n\n\t/**\n\t * Create or update DNS records.\n\t *\n\t * @param domain - Root domain (e.g., 'example.com')\n\t * @param records - Records to create or update\n\t * @returns Results of the upsert operations\n\t */\n\tupsertRecords(\n\t\tdomain: string,\n\t\trecords: UpsertDnsRecord[],\n\t): Promise<UpsertResult[]>;\n\n\t/**\n\t * Delete DNS records.\n\t *\n\t * @param domain - Root domain (e.g., 'example.com')\n\t * @param records - Records to delete\n\t * @returns Results of the delete operations\n\t */\n\tdeleteRecords(\n\t\tdomain: string,\n\t\trecords: DeleteDnsRecord[],\n\t): Promise<DeleteResult[]>;\n}\n\n// =============================================================================\n// DNS Provider Config Types (derived from Zod schemas)\n// =============================================================================\n\nexport type HostingerDnsConfig = z.infer<typeof HostingerDnsProviderSchema>;\nexport type Route53DnsConfig = z.infer<typeof Route53DnsProviderSchema>;\nexport type GoDaddyDnsConfig = z.infer<typeof GoDaddyDnsProviderSchema>;\nexport type CloudflareDnsConfig = z.infer<typeof CloudflareDnsProviderSchema>;\nexport type ManualDnsConfig = z.infer<typeof ManualDnsProviderSchema>;\nexport type CustomDnsConfig = z.infer<typeof CustomDnsProviderSchema>;\n/** Single DNS provider config (for one domain) */\nexport type DnsConfig = z.infer<typeof DnsProviderSchema>;\n\n// =============================================================================\n// DNS Provider Factory\n// =============================================================================\n\n/**\n * Check if value is a DnsProvider implementation.\n */\nexport function isDnsProvider(value: unknown): value is DnsProvider {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\ttypeof (value as DnsProvider).name === 'string' &&\n\t\ttypeof (value as DnsProvider).getRecords === 'function' &&\n\t\ttypeof (value as DnsProvider).upsertRecords === 'function' &&\n\t\ttypeof (value as DnsProvider).deleteRecords === 'function'\n\t);\n}\n\nexport interface CreateDnsProviderOptions {\n\t/** DNS config from workspace */\n\tconfig: DnsConfig;\n\t/** Where the GoDaddy provider reads its key — the environment and the CLI's home. */\n\tgodaddy?: import('./GoDaddyProvider').GoDaddyProviderOptions;\n\t/** The Hostinger token, when the caller already has it. */\n\thostinger?: import('../../../deploy/credentials').HostingerCredential;\n}\n\n/**\n * Create a DNS provider based on configuration.\n *\n * - 'hostinger': HostingerProvider\n * - 'route53': Route53Provider\n * - 'godaddy': GoDaddyProvider\n * - 'manual': Returns null (user handles DNS)\n * - Custom: Use provided DnsProvider implementation\n */\nexport async function createDnsProvider(\n\toptions: CreateDnsProviderOptions,\n): Promise<DnsProvider | null> {\n\tconst { config } = options;\n\n\t// Manual mode - no provider needed\n\tif (config.provider === 'manual') {\n\t\treturn null;\n\t}\n\n\t// Custom provider implementation\n\tif (isDnsProvider(config.provider)) {\n\t\treturn config.provider;\n\t}\n\n\t// Built-in providers\n\tconst provider = config.provider;\n\n\tif (provider === 'hostinger') {\n\t\tconst { HostingerProvider } = await import('./HostingerProvider');\n\t\treturn new HostingerProvider(options.hostinger);\n\t}\n\n\tif (provider === 'route53') {\n\t\tconst { Route53Provider } = await import('./Route53Provider');\n\t\tconst route53Config = config as Route53DnsConfig;\n\t\treturn new Route53Provider({\n\t\t\tregion: route53Config.region,\n\t\t\tprofile: route53Config.profile,\n\t\t\thostedZoneId: route53Config.hostedZoneId,\n\t\t});\n\t}\n\n\tif (provider === 'godaddy') {\n\t\tconst { GoDaddyProvider } = await import('./GoDaddyProvider');\n\t\treturn new GoDaddyProvider(options.godaddy ?? {});\n\t}\n\n\tif (provider === 'cloudflare') {\n\t\tthrow new DnsProviderNotImplemented('cloudflare');\n\t}\n\n\tthrow new DnsProviderUnknown(config);\n}\n\n/**\n * The provider's credentials can write records and not read them — a key\n * scoped to updates only. What reads them falls back to writing every record,\n * which is idempotent, without a diff.\n */\nexport class DnsRecordsUnreadable extends GkmError {\n\tconstructor(\n\t\treadonly provider: string,\n\t\treadonly domain: string,\n\t\treadonly reason: string,\n\t) {\n\t\tsuper(\n\t\t\t`The ${provider} key cannot read ${domain}'s DNS records (${reason}), so ` +\n\t\t\t\t'changes cannot be compared with what is there: every record is ' +\n\t\t\t\t'written, which leaves one that already has its value as it was.',\n\t\t);\n\t\tthis.name = 'DnsRecordsUnreadable';\n\t}\n}\n\n/** A DNS provider gkm names and does not have yet. */\nexport class DnsProviderNotImplemented extends Error {\n\tconstructor(readonly provider: string) {\n\t\tsuper(\n\t\t\t`The ${provider} DNS provider is not implemented yet. Use 'route53', ` +\n\t\t\t\t\"'godaddy', 'hostinger' or 'manual' for this domain in dns, or \" +\n\t\t\t\t'pass your own DnsProvider object.',\n\t\t);\n\t\tthis.name = 'DnsProviderNotImplemented';\n\t}\n}\n\n/** A `provider:` that is none of the built-ins, nor a DnsProvider object. */\nexport class DnsProviderUnknown extends GkmError {\n\tconstructor(readonly config: unknown) {\n\t\tsuper(\n\t\t\t`Unknown DNS provider: ${JSON.stringify(config)}. dns takes ` +\n\t\t\t\t\"'route53', 'godaddy', 'hostinger', 'manual', or an object implementing DnsProvider.\",\n\t\t);\n\t\tthis.name = 'DnsProviderUnknown';\n\t}\n}\n","/**\n * DNS orchestration for deployments\n *\n * Handles automatic DNS record creation for deployed applications.\n */\n\nimport { lookup } from 'node:dns/promises';\nimport {\n\ttype DokployStageState,\n\tisDnsVerified,\n\tsetDnsRecord,\n\tsetDnsVerification,\n} from '../../../deploy/state';\nimport { output } from '../../../output';\nimport type {\n\tDnsConfig,\n\tDnsProvider as DnsProviderConfig,\n} from '../../../workspace/types';\nimport {\n\tcreateDnsProvider,\n\ttype DnsProvider,\n\ttype DnsConfig as SchemaDnsConfig,\n\ttype UpsertDnsRecord,\n} from './DnsProvider';\n\nconst logger = output;\n\n/**\n * Check if DNS config is legacy format (single domain with `domain` property)\n */\nexport function isLegacyDnsConfig(\n\tconfig: DnsConfig,\n): config is SchemaDnsConfig & { domain: string } {\n\treturn (\n\t\ttypeof config === 'object' &&\n\t\tconfig !== null &&\n\t\t'provider' in config &&\n\t\t'domain' in config\n\t);\n}\n\n/**\n * Normalize DNS config to new multi-domain format\n */\nexport function normalizeDnsConfig(\n\tconfig: DnsConfig,\n): Record<string, DnsProviderConfig> {\n\tif (isLegacyDnsConfig(config)) {\n\t\t// Convert legacy format to new format\n\t\tconst { domain, ...providerConfig } = config;\n\t\treturn { [domain]: providerConfig as DnsProviderConfig };\n\t}\n\treturn config as Record<string, DnsProviderConfig>;\n}\n\n/**\n * Find the root domain for a hostname from available DNS configs\n *\n * @example\n * findRootDomain('api.geekmidas.com', { 'geekmidas.com': {...}, 'geekmidas.dev': {...} })\n * // Returns 'geekmidas.com'\n */\nexport function findRootDomain(\n\thostname: string,\n\tdnsConfig: Record<string, DnsProviderConfig>,\n): string | null {\n\t// Sort domains by length descending to match most specific first\n\tconst domains = Object.keys(dnsConfig).sort((a, b) => b.length - a.length);\n\n\tfor (const domain of domains) {\n\t\tif (hostname === domain || hostname.endsWith(`.${domain}`)) {\n\t\t\treturn domain;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n/**\n * Group hostnames by their root domain\n */\nexport function groupHostnamesByDomain(\n\tappHostnames: Map<string, string>,\n\tdnsConfig: Record<string, DnsProviderConfig>,\n): Map<string, Map<string, string>> {\n\tconst grouped = new Map<string, Map<string, string>>();\n\n\tfor (const [appName, hostname] of appHostnames) {\n\t\tconst rootDomain = findRootDomain(hostname, dnsConfig);\n\t\tif (!rootDomain) {\n\t\t\tlogger.log(` ⚠ No DNS config found for hostname: ${hostname}`);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!grouped.has(rootDomain)) {\n\t\t\tgrouped.set(rootDomain, new Map());\n\t\t}\n\t\tgrouped.get(rootDomain)!.set(appName, hostname);\n\t}\n\n\treturn grouped;\n}\n\n/**\n * Required DNS record for an app\n */\nexport interface RequiredDnsRecord {\n\t/** Full hostname (e.g., 'api.joemoer.traflabs.io') */\n\thostname: string;\n\t/** Subdomain part for the DNS provider (e.g., 'api.joemoer') */\n\tsubdomain: string;\n\t/** Record type */\n\ttype: 'A' | 'CNAME';\n\t/** Target value (IP or hostname) */\n\tvalue: string;\n\t/** App name */\n\tappName: string;\n\t/** Whether the record was created */\n\tcreated?: boolean;\n\t/** Whether the record already existed */\n\texisted?: boolean;\n\t/** Error if creation failed */\n\terror?: string;\n}\n\n/**\n * Result of DNS record creation\n */\nexport interface DnsCreationResult {\n\trecords: RequiredDnsRecord[];\n\tsuccess: boolean;\n\tserverIp: string;\n}\n\n/**\n * Resolve IP address from a hostname\n */\nexport async function resolveHostnameToIp(hostname: string): Promise<string> {\n\ttry {\n\t\tconst addresses = await lookup(hostname, { family: 4 });\n\t\treturn addresses.address;\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Failed to resolve IP for ${hostname}: ${error instanceof Error ? error.message : 'Unknown error'}`,\n\t\t);\n\t}\n}\n\n/**\n * Extract subdomain from full hostname relative to root domain\n *\n * @example\n * extractSubdomain('api.joemoer.traflabs.io', 'traflabs.io') => 'api.joemoer'\n * extractSubdomain('joemoer.traflabs.io', 'traflabs.io') => 'joemoer'\n */\nexport function extractSubdomain(hostname: string, rootDomain: string): string {\n\tif (!hostname.endsWith(rootDomain)) {\n\t\tthrow new Error(\n\t\t\t`Hostname ${hostname} is not under root domain ${rootDomain}`,\n\t\t);\n\t}\n\n\tconst subdomain = hostname.slice(0, -(rootDomain.length + 1)); // +1 for the dot\n\treturn subdomain || '@'; // '@' represents the root domain itself\n}\n\n/**\n * Generate required DNS records for a deployment\n */\nexport function generateRequiredRecords(\n\tappHostnames: Map<string, string>, // appName -> hostname\n\trootDomain: string,\n\tserverIp: string,\n): RequiredDnsRecord[] {\n\tconst records: RequiredDnsRecord[] = [];\n\n\tfor (const [appName, hostname] of appHostnames) {\n\t\tconst subdomain = extractSubdomain(hostname, rootDomain);\n\t\trecords.push({\n\t\t\thostname,\n\t\t\tsubdomain,\n\t\t\ttype: 'A',\n\t\t\tvalue: serverIp,\n\t\t\tappName,\n\t\t});\n\t}\n\n\treturn records;\n}\n\n/**\n * Print DNS records table\n */\nexport function printDnsRecordsTable(\n\trecords: RequiredDnsRecord[],\n\trootDomain: string,\n): void {\n\tlogger.log(`\\n 📋 DNS Records for ${rootDomain}:`);\n\tlogger.log(\n\t\t' ┌─────────────────────────────────────┬──────┬─────────────────┬────────┐',\n\t);\n\tlogger.log(\n\t\t' │ Subdomain │ Type │ Value │ Status │',\n\t);\n\tlogger.log(\n\t\t' ├─────────────────────────────────────┼──────┼─────────────────┼────────┤',\n\t);\n\n\tfor (const record of records) {\n\t\tconst subdomain = record.subdomain.padEnd(35);\n\t\tconst type = record.type.padEnd(4);\n\t\tconst value = record.value.padEnd(15);\n\t\tlet status: string;\n\n\t\tif (record.error) {\n\t\t\tstatus = '✗';\n\t\t} else if (record.created) {\n\t\t\tstatus = '✓ new';\n\t\t} else if (record.existed) {\n\t\t\tstatus = '✓';\n\t\t} else {\n\t\t\tstatus = '?';\n\t\t}\n\n\t\tlogger.log(\n\t\t\t` │ ${subdomain} │ ${type} │ ${value} │ ${status.padEnd(6)} │`,\n\t\t);\n\t}\n\n\tlogger.log(\n\t\t' └─────────────────────────────────────┴──────┴─────────────────┴────────┘',\n\t);\n}\n\n/**\n * Print DNS records in a simple format for manual setup\n */\nexport function printDnsRecordsSimple(\n\trecords: RequiredDnsRecord[],\n\trootDomain: string,\n): void {\n\tlogger.log('\\n 📋 Required DNS Records:');\n\tlogger.log(` Add these A records to your DNS provider (${rootDomain}):\\n`);\n\n\tfor (const record of records) {\n\t\tlogger.log(` ${record.subdomain} → ${record.value} (A record)`);\n\t}\n\n\tlogger.log('');\n}\n\n/**\n * Create DNS records for a single domain using its configured provider\n */\nexport async function createDnsRecordsForDomain(\n\trecords: RequiredDnsRecord[],\n\trootDomain: string,\n\tproviderConfig: DnsProviderConfig,\n): Promise<RequiredDnsRecord[]> {\n\t// Get TTL from config, default to 300. Manual mode doesn't have ttl property.\n\tconst ttl =\n\t\t'ttl' in providerConfig && providerConfig.ttl ? providerConfig.ttl : 300;\n\n\t// Get DNS provider from factory\n\tlet provider: DnsProvider | null;\n\ttry {\n\t\t// Cast to schema-derived DnsConfig for provider factory\n\t\tprovider = await createDnsProvider({\n\t\t\tconfig: providerConfig as SchemaDnsConfig,\n\t\t});\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : 'Unknown error';\n\t\tlogger.log(\n\t\t\t` ⚠ Failed to create DNS provider for ${rootDomain}: ${message}`,\n\t\t);\n\t\treturn records.map((r) => ({ ...r, error: message }));\n\t}\n\n\t// Manual mode - no provider, just mark records as needing manual creation\n\tif (!provider) {\n\t\treturn records.map((r) => ({ ...r, created: false, existed: false }));\n\t}\n\n\tconst results: RequiredDnsRecord[] = [];\n\n\t// Convert RequiredDnsRecord to UpsertDnsRecord format\n\tconst upsertRecords: UpsertDnsRecord[] = records.map((r) => ({\n\t\tname: r.subdomain,\n\t\ttype: r.type,\n\t\tttl,\n\t\tvalue: r.value,\n\t}));\n\n\ttry {\n\t\t// Use provider to upsert records\n\t\tconst upsertResults = await provider.upsertRecords(\n\t\t\trootDomain,\n\t\t\tupsertRecords,\n\t\t);\n\n\t\t// Map results back to RequiredDnsRecord format\n\t\tfor (const [i, record] of records.entries()) {\n\t\t\tconst result = upsertResults[i];\n\n\t\t\t// Handle case where upsertResults has fewer items (shouldn't happen but be safe)\n\t\t\tif (!result) {\n\t\t\t\tresults.push({\n\t\t\t\t\thostname: record.hostname,\n\t\t\t\t\tsubdomain: record.subdomain,\n\t\t\t\t\ttype: record.type,\n\t\t\t\t\tvalue: record.value,\n\t\t\t\t\tappName: record.appName,\n\t\t\t\t\terror: 'No result returned from provider',\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (result.unchanged) {\n\t\t\t\tresults.push({\n\t\t\t\t\thostname: record.hostname,\n\t\t\t\t\tsubdomain: record.subdomain,\n\t\t\t\t\ttype: record.type,\n\t\t\t\t\tvalue: record.value,\n\t\t\t\t\tappName: record.appName,\n\t\t\t\t\texisted: true,\n\t\t\t\t\tcreated: false,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tresults.push({\n\t\t\t\t\thostname: record.hostname,\n\t\t\t\t\tsubdomain: record.subdomain,\n\t\t\t\t\ttype: record.type,\n\t\t\t\t\tvalue: record.value,\n\t\t\t\t\tappName: record.appName,\n\t\t\t\t\tcreated: result.created,\n\t\t\t\t\texisted: !result.created,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : 'Unknown error';\n\t\tlogger.log(\n\t\t\t` ⚠ Failed to create DNS records for ${rootDomain}: ${message}`,\n\t\t);\n\t\treturn records.map((r) => ({\n\t\t\thostname: r.hostname,\n\t\t\tsubdomain: r.subdomain,\n\t\t\ttype: r.type,\n\t\t\tvalue: r.value,\n\t\t\tappName: r.appName,\n\t\t\terror: message,\n\t\t}));\n\t}\n\n\treturn results;\n}\n\n/**\n * Create DNS records using the configured provider\n * @deprecated Use createDnsRecordsForDomain for multi-domain support\n */\nexport async function createDnsRecords(\n\trecords: RequiredDnsRecord[],\n\tdnsConfig: DnsConfig,\n): Promise<RequiredDnsRecord[]> {\n\t// Handle legacy config format\n\tif (!isLegacyDnsConfig(dnsConfig)) {\n\t\tthrow new Error(\n\t\t\t'createDnsRecords requires legacy DnsConfig with domain property. Use createDnsRecordsForDomain instead.',\n\t\t);\n\t}\n\tconst { domain: rootDomain, ...providerConfig } = dnsConfig;\n\treturn createDnsRecordsForDomain(\n\t\trecords,\n\t\trootDomain,\n\t\tproviderConfig as DnsProviderConfig,\n\t);\n}\n\n/**\n * Main DNS orchestration function for deployments\n *\n * Supports both legacy single-domain format and new multi-domain format:\n * - Legacy: { provider: 'hostinger', domain: 'example.com' }\n * - Multi: { 'example.com': { provider: 'hostinger' }, 'example.dev': { provider: 'route53' } }\n *\n * @param appHostnames - Map of app names to hostnames\n * @param dnsConfig - DNS configuration (legacy or multi-domain)\n * @param dokployEndpoint - Dokploy server endpoint to resolve IP from\n * @param state - Optional state to save created records for later deletion\n */\nexport async function orchestrateDns(\n\tappHostnames: Map<string, string>, // appName -> hostname\n\tdnsConfig: DnsConfig | undefined,\n\tdokployEndpoint: string,\n\tstate?: DokployStageState,\n): Promise<DnsCreationResult | null> {\n\tif (!dnsConfig) {\n\t\treturn null;\n\t}\n\n\t// Normalize config to multi-domain format\n\tconst normalizedConfig = normalizeDnsConfig(dnsConfig);\n\n\t// Resolve Dokploy server IP from endpoint\n\tlogger.log('\\n🌐 Setting up DNS records...');\n\tlet serverIp: string;\n\n\ttry {\n\t\tconst endpointUrl = new URL(dokployEndpoint);\n\t\tserverIp = await resolveHostnameToIp(endpointUrl.hostname);\n\t\tlogger.log(` Server IP: ${serverIp} (from ${endpointUrl.hostname})`);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : 'Unknown error';\n\t\tlogger.log(` ⚠ Failed to resolve server IP: ${message}`);\n\t\treturn null;\n\t}\n\n\t// Group hostnames by their root domain\n\tconst groupedHostnames = groupHostnamesByDomain(\n\t\tappHostnames,\n\t\tnormalizedConfig,\n\t);\n\n\tif (groupedHostnames.size === 0) {\n\t\tlogger.log(\n\t\t\t' No DNS records needed (no hostnames match configured domains)',\n\t\t);\n\t\treturn { records: [], success: true, serverIp };\n\t}\n\n\tconst allRecords: RequiredDnsRecord[] = [];\n\tlet hasFailures = false;\n\n\t// Process each domain group with its specific provider\n\tfor (const [rootDomain, domainHostnames] of groupedHostnames) {\n\t\tconst providerConfig = normalizedConfig[rootDomain];\n\t\tif (!providerConfig) {\n\t\t\tlogger.log(` ⚠ No provider config for ${rootDomain}`);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst providerName =\n\t\t\ttypeof providerConfig.provider === 'string'\n\t\t\t\t? providerConfig.provider\n\t\t\t\t: 'custom';\n\n\t\t// Generate required records for this domain\n\t\tconst requiredRecords = generateRequiredRecords(\n\t\t\tdomainHostnames,\n\t\t\trootDomain,\n\t\t\tserverIp,\n\t\t);\n\n\t\tif (requiredRecords.length === 0) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Create records for this domain\n\t\tlogger.log(\n\t\t\t` Creating DNS records for ${rootDomain} (${providerName})...`,\n\t\t);\n\t\tconst domainRecords = await createDnsRecordsForDomain(\n\t\t\trequiredRecords,\n\t\t\trootDomain,\n\t\t\tproviderConfig,\n\t\t);\n\n\t\tallRecords.push(...domainRecords);\n\n\t\tconst created = domainRecords.filter((r) => r.created).length;\n\t\tconst existed = domainRecords.filter((r) => r.existed).length;\n\t\tconst failed = domainRecords.filter((r) => r.error).length;\n\n\t\tif (created > 0) {\n\t\t\tlogger.log(` ✓ Created ${created} DNS record(s) for ${rootDomain}`);\n\t\t}\n\t\tif (existed > 0) {\n\t\t\tlogger.log(` ✓ ${existed} record(s) already exist for ${rootDomain}`);\n\t\t}\n\t\tif (failed > 0) {\n\t\t\tlogger.log(` ⚠ ${failed} record(s) failed for ${rootDomain}`);\n\t\t\thasFailures = true;\n\t\t}\n\n\t\t// Save created/existing records to state for later deletion during undeploy\n\t\tif (state) {\n\t\t\tfor (const record of domainRecords) {\n\t\t\t\tif (record.created || record.existed) {\n\t\t\t\t\tsetDnsRecord(state, {\n\t\t\t\t\t\tdomain: rootDomain,\n\t\t\t\t\t\tname: record.subdomain,\n\t\t\t\t\t\ttype: record.type,\n\t\t\t\t\t\tvalue: record.value,\n\t\t\t\t\t\tttl:\n\t\t\t\t\t\t\t'ttl' in providerConfig && providerConfig.ttl\n\t\t\t\t\t\t\t\t? providerConfig.ttl\n\t\t\t\t\t\t\t\t: 300,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Print summary table for this domain\n\t\tprintDnsRecordsTable(domainRecords, rootDomain);\n\n\t\t// If manual mode or some failed, print simple instructions\n\t\tif (providerConfig.provider === 'manual' || failed > 0) {\n\t\t\tprintDnsRecordsSimple(\n\t\t\t\tdomainRecords.filter((r) => !r.created && !r.existed),\n\t\t\t\trootDomain,\n\t\t\t);\n\t\t}\n\t}\n\n\treturn {\n\t\trecords: allRecords,\n\t\tsuccess: !hasFailures,\n\t\tserverIp,\n\t};\n}\n\n/**\n * Result of DNS verification for a single hostname\n */\nexport interface DnsVerificationResult {\n\thostname: string;\n\tappName: string;\n\tverified: boolean;\n\tresolvedIp?: string;\n\texpectedIp: string;\n\terror?: string;\n\tskipped?: boolean; // True if already verified in state\n}\n\n/**\n * Verify DNS records resolve correctly after deployment.\n *\n * This function:\n * 1. Checks state for previously verified hostnames (skips if already verified with same IP)\n * 2. Attempts to resolve each hostname to an IP\n * 3. Compares resolved IP with expected server IP\n * 4. Updates state with verification results\n *\n * @param appHostnames - Map of app names to hostnames\n * @param serverIp - Expected IP address the hostnames should resolve to\n * @param state - Deploy state for caching verification results\n * @returns Array of verification results\n */\nexport async function verifyDnsRecords(\n\tappHostnames: Map<string, string>,\n\tserverIp: string,\n\tstate: DokployStageState,\n): Promise<DnsVerificationResult[]> {\n\tconst results: DnsVerificationResult[] = [];\n\n\tlogger.log('\\n🔍 Verifying DNS records...');\n\n\tfor (const [appName, hostname] of appHostnames) {\n\t\t// Check if already verified with same IP\n\t\tif (isDnsVerified(state, hostname, serverIp)) {\n\t\t\tlogger.log(` ✓ ${hostname} (previously verified)`);\n\t\t\tresults.push({\n\t\t\t\thostname,\n\t\t\t\tappName,\n\t\t\t\tverified: true,\n\t\t\t\texpectedIp: serverIp,\n\t\t\t\tskipped: true,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Attempt to resolve hostname\n\t\ttry {\n\t\t\tconst resolvedIp = await resolveHostnameToIp(hostname);\n\n\t\t\tif (resolvedIp === serverIp) {\n\t\t\t\t// DNS verified successfully\n\t\t\t\tsetDnsVerification(state, hostname, serverIp);\n\t\t\t\tlogger.log(` ✓ ${hostname} → ${resolvedIp}`);\n\t\t\t\tresults.push({\n\t\t\t\t\thostname,\n\t\t\t\t\tappName,\n\t\t\t\t\tverified: true,\n\t\t\t\t\tresolvedIp,\n\t\t\t\t\texpectedIp: serverIp,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\t// DNS resolves but to wrong IP\n\t\t\t\tlogger.log(\n\t\t\t\t\t` ⚠ ${hostname} resolves to ${resolvedIp}, expected ${serverIp}`,\n\t\t\t\t);\n\t\t\t\tresults.push({\n\t\t\t\t\thostname,\n\t\t\t\t\tappName,\n\t\t\t\t\tverified: false,\n\t\t\t\t\tresolvedIp,\n\t\t\t\t\texpectedIp: serverIp,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// DNS resolution failed\n\t\t\tconst message = error instanceof Error ? error.message : 'Unknown error';\n\t\t\tlogger.log(` ⚠ ${hostname} DNS not propagated (${message})`);\n\t\t\tresults.push({\n\t\t\t\thostname,\n\t\t\t\tappName,\n\t\t\t\tverified: false,\n\t\t\t\texpectedIp: serverIp,\n\t\t\t\terror: message,\n\t\t\t});\n\t\t}\n\t}\n\n\t// Summary\n\tconst verified = results.filter((r) => r.verified).length;\n\tconst skipped = results.filter((r) => r.skipped).length;\n\tconst pending = results.filter((r) => !r.verified).length;\n\n\tif (pending > 0) {\n\t\tlogger.log(`\\n ${verified} verified, ${pending} pending propagation`);\n\t\tlogger.log(' DNS changes may take 5-30 minutes to propagate');\n\t} else if (skipped > 0) {\n\t\tlogger.log(` ${verified} verified (${skipped} from cache)`);\n\t}\n\n\treturn results;\n}\n","/**\n * How a deploy gets the credentials it acts with.\n *\n * `deploy()` never prompts and never reads a terminal: it asks a\n * `CredentialProvider` and, when the provider has nothing, stops with\n * `MissingCredential` naming what it needed and how to supply it. Whether to\n * ask a person, read a vault or fail is the caller's decision — `gkm deploy`\n * prompts at a terminal and stores what was typed; a CI job sets the\n * environment; a host passes its own provider.\n */\n\nimport { readCredentials } from '../auth/credentials';\nimport { GkmError } from '../errors';\n\n/**\n * What each kind of credential is asked for with, and what it is.\n *\n * A target that needs a kind the CLI does not know declares it by augmenting\n * this interface, and lists it in its `credentials`:\n *\n * ```ts\n * declare module '@geekmidas/cli/target' {\n * interface CredentialKinds {\n * fly: { request: { org: string }; value: { token: string } };\n * }\n * }\n * ```\n */\nexport interface CredentialKinds {\n\t/** The Dokploy API a stage deploys through. */\n\tdokploy: {\n\t\t/** `deploy.dokploy.endpoint`, when the config names one. */\n\t\trequest: { endpoint?: string };\n\t\tvalue: { endpoint: string; token: string };\n\t};\n\t/**\n\t * A container registry login, for Dokploy to pull with. Asked for only when\n\t * Dokploy has no registry for `deploy.registry` and one has to be\n\t * created.\n\t */\n\tregistry: {\n\t\t/** `deploy.registry`. */\n\t\trequest: { url: string };\n\t\tvalue: { username: string; password: string };\n\t};\n\t/**\n\t * The AWS account a stage deploys to, for the SST target's `sst deploy`.\n\t * Handed to that one command's environment and to nothing else.\n\t */\n\taws: {\n\t\t/** The stage, for a provider that keeps one account per stage. */\n\t\trequest: { stage: string };\n\t\tvalue: AwsCredential;\n\t};\n\t/**\n\t * A GoDaddy Personal Access Token, for a `dns` domain whose provider is\n\t * `godaddy`. Read on the machine that writes the records — never the\n\t * server's.\n\t */\n\tgodaddy: {\n\t\trequest: Record<never, never>;\n\t\tvalue: GoDaddyCredential;\n\t};\n\t/**\n\t * A Hostinger API token, for a `dns` domain whose provider is\n\t * `hostinger`. Like GoDaddy's, read where the records are written.\n\t */\n\thostinger: {\n\t\trequest: Record<never, never>;\n\t\tvalue: HostingerCredential;\n\t};\n}\n\n/** A Hostinger API token, from hpanel.hostinger.com/profile/api. */\nexport interface HostingerCredential {\n\ttoken: string;\n}\n\n/** A GoDaddy Personal Access Token, sent as `Authorization: Bearer <token>`. */\nexport interface GoDaddyCredential {\n\ttoken: string;\n}\n\n/**\n * Who to act as on AWS: a named profile, or keys.\n *\n * Never both. Given both, every AWS SDK takes the keys and ignores the\n * profile, so `--profile prod` with staging's keys still exported would deploy\n * production's stack into staging's account — the reason `secretsStoreFor`\n * resolves a named profile on its own, and why this cannot express the mix.\n */\nexport type AwsCredential =\n\t| {\n\t\t\t/** A profile in `~/.aws/config` — keys, SSO, an assumed role. */\n\t\t\tprofile: string;\n\t\t\tregion?: string;\n\t }\n\t| {\n\t\t\taccessKeyId: string;\n\t\t\tsecretAccessKey: string;\n\t\t\t/** Present for temporary keys: an assumed role, GitHub's OIDC. */\n\t\t\tsessionToken?: string;\n\t\t\tregion?: string;\n\t };\n\nexport type CredentialKind = keyof CredentialKinds;\n\n/** What a deploy asks a provider for. */\nexport type CredentialRequest<K extends CredentialKind = CredentialKind> = {\n\t[P in K]: { kind: P } & CredentialKinds[P]['request'];\n}[K];\n\n/** What a provider answers with. */\nexport type Credential<K extends CredentialKind> = CredentialKinds[K]['value'];\n\nexport interface CredentialProvider {\n\t/**\n\t * The credential `request` asks for, or `undefined` when this provider has\n\t * none — the deploy then raises {@link MissingCredential}.\n\t */\n\tget<K extends CredentialKind>(\n\t\trequest: CredentialRequest<K>,\n\t\toptions?: { signal?: AbortSignal },\n\t): Promise<Credential<K> | undefined>;\n}\n\n/**\n * How to supply each kind the CLI knows, for the error that says it is\n * missing. A target's own kinds are its to explain.\n */\nconst HOW_TO_PROVIDE: Partial<Record<CredentialKind, string>> = {\n\tdokploy:\n\t\t\"Set DOKPLOY_API_TOKEN (and DOKPLOY_ENDPOINT, or deploy.dokploy.endpoint in gkm.config.ts), run `gkm login --provider dokploy`, or pass them through the deploy's CredentialProvider.\",\n\tregistry:\n\t\t'Add the registry in Dokploy (Settings → Docker Registry) and set deploy.dokploy.registryId, set DOCKER_REGISTRY_USERNAME and DOCKER_REGISTRY_PASSWORD, or run `gkm deploy` at a terminal to be asked for them.',\n\tgodaddy:\n\t\t'Set GODADDY_API_TOKEN to a Personal Access Token scoped to domains.dns:update (create one in the GoDaddy developer dashboard), or run `gkm login --provider godaddy`.',\n\thostinger:\n\t\t'Set HOSTINGER_API_TOKEN to a token from hpanel.hostinger.com/profile/api, or run `gkm login --provider hostinger`.',\n\taws: \"Set AWS_PROFILE to the stage account's profile, or AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (and AWS_SESSION_TOKEN) — in CI, the keys aws-actions/configure-aws-credentials exports — or pass them through the deploy's CredentialProvider.\",\n};\n\n/** A deploy needed a credential, and its provider had none. */\nexport class MissingCredential extends GkmError {\n\tconstructor(\n\t\treadonly kind: CredentialKind,\n\t\t/** What it was for: the Dokploy endpoint or the registry URL. */\n\t\treadonly target: string | undefined,\n\t\t/** How to supply it. */\n\t\treadonly howToProvide: string = HOW_TO_PROVIDE[kind] ??\n\t\t\t\"Pass it through the deploy's CredentialProvider.\",\n\t) {\n\t\tconst what =\n\t\t\tkind === 'dokploy'\n\t\t\t\t? `No Dokploy credentials${target ? ` for ${target}` : ''}.`\n\t\t\t\t: kind === 'registry'\n\t\t\t\t\t? `Dokploy has no registry for ${target ?? 'the configured registry'}, and there are no credentials to create one with.`\n\t\t\t\t\t: kind === 'aws'\n\t\t\t\t\t\t? `No AWS credentials${target ? ` for the \"${target}\" stage` : ''}.`\n\t\t\t\t\t\t: kind === 'godaddy'\n\t\t\t\t\t\t\t? `No GoDaddy API token${target ? ` for ${target}` : ''}.`\n\t\t\t\t\t\t\t: kind === 'hostinger'\n\t\t\t\t\t\t\t\t? `No Hostinger API token${target ? ` for ${target}` : ''}.`\n\t\t\t\t\t\t\t\t: `No \"${String(kind)}\" credentials${target ? ` for ${target}` : ''}.`;\n\t\tsuper(`${what} ${howToProvide}`);\n\t\tthis.name = 'MissingCredential';\n\t}\n}\n\n/** Whatever was asked for, from the first provider that has it. */\nexport function chainCredentials(\n\t...providers: CredentialProvider[]\n): CredentialProvider {\n\treturn {\n\t\tasync get(request, options) {\n\t\t\tfor (const provider of providers) {\n\t\t\t\tconst found = await provider.get(request, options);\n\t\t\t\tif (found) return found;\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t};\n}\n\nexport interface StoredCredentialsOptions {\n\t/** Where to read the variables from. Defaults to `process.env`. */\n\tenv?: NodeJS.ProcessEnv;\n\t/**\n\t * The CLI's home, whose `credentials.json` holds stored logins. Defaults\n\t * to `GKM_HOME`, else `~/.gkm`.\n\t */\n\thome?: string;\n}\n\n/**\n * Credentials from the environment, then from what `gkm login` stored. What\n * `deploy()` uses when it is handed no provider.\n *\n * - Dokploy: `DOKPLOY_API_TOKEN` / `DOKPLOY_ENDPOINT`, each falling back to\n * the stored login, and the endpoint finally to `deploy.dokploy.endpoint`.\n * Each half is read on its own: a token is a secret and belongs in the\n * environment, an endpoint is configuration and belongs in the config.\n * - Registry: `DOCKER_REGISTRY_USERNAME` / `DOCKER_REGISTRY_PASSWORD`.\n * - AWS: `AWS_PROFILE` when it is set, and then nothing else; otherwise\n * `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` / `AWS_SESSION_TOKEN`. The\n * profile winning is `secretsStoreFor`'s rule: a profile is a choice of\n * account someone made, exported keys may be left over from another.\n * Read here, by name, and handed only to the command that deploys — the\n * sandbox every other step runs in passes no `AWS_*` on.\n */\nexport function storedCredentials(\n\toptions: StoredCredentialsOptions = {},\n): CredentialProvider {\n\tconst env = options.env ?? process.env;\n\n\treturn {\n\t\tasync get(asked) {\n\t\t\t// The union, so a switch on `kind` narrows it: `K` itself never is.\n\t\t\tconst request = asked as CredentialRequest;\n\t\t\tswitch (request.kind) {\n\t\t\t\tcase 'dokploy': {\n\t\t\t\t\tconst stored = (\n\t\t\t\t\t\tawait readCredentials(\n\t\t\t\t\t\t\toptions.home ? { home: options.home } : undefined,\n\t\t\t\t\t\t)\n\t\t\t\t\t).dokploy;\n\t\t\t\t\tconst token = env.DOKPLOY_API_TOKEN ?? stored?.token;\n\t\t\t\t\tconst endpoint =\n\t\t\t\t\t\tenv.DOKPLOY_ENDPOINT ?? stored?.endpoint ?? request.endpoint;\n\t\t\t\t\tif (!token || !endpoint) return undefined;\n\t\t\t\t\treturn { endpoint: endpoint.replace(/\\/$/, ''), token } as never;\n\t\t\t\t}\n\t\t\t\tcase 'registry': {\n\t\t\t\t\tconst username = env.DOCKER_REGISTRY_USERNAME;\n\t\t\t\t\tconst password = env.DOCKER_REGISTRY_PASSWORD;\n\t\t\t\t\tif (!username || !password) return undefined;\n\t\t\t\t\treturn { username, password } as never;\n\t\t\t\t}\n\t\t\t\tcase 'godaddy': {\n\t\t\t\t\t// The environment first, then the stored login.\n\t\t\t\t\tconst token =\n\t\t\t\t\t\tenv.GODADDY_API_TOKEN ||\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tawait readCredentials(\n\t\t\t\t\t\t\t\toptions.home ? { home: options.home } : undefined,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t).godaddy?.token;\n\t\t\t\t\tif (!token) return undefined;\n\t\t\t\t\treturn { token } as never;\n\t\t\t\t}\n\t\t\t\tcase 'hostinger': {\n\t\t\t\t\tconst token =\n\t\t\t\t\t\tenv.HOSTINGER_API_TOKEN ||\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tawait readCredentials(\n\t\t\t\t\t\t\t\toptions.home ? { home: options.home } : undefined,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t).hostinger?.token;\n\t\t\t\t\tif (!token) return undefined;\n\t\t\t\t\treturn { token } as never;\n\t\t\t\t}\n\t\t\t\tcase 'aws': {\n\t\t\t\t\tconst region = env.AWS_REGION ?? env.AWS_DEFAULT_REGION;\n\t\t\t\t\tconst where = region ? { region } : {};\n\t\t\t\t\tif (env.AWS_PROFILE) {\n\t\t\t\t\t\treturn { profile: env.AWS_PROFILE, ...where } as never;\n\t\t\t\t\t}\n\t\t\t\t\tconst accessKeyId = env.AWS_ACCESS_KEY_ID;\n\t\t\t\t\tconst secretAccessKey = env.AWS_SECRET_ACCESS_KEY;\n\t\t\t\t\tif (!accessKeyId || !secretAccessKey) return undefined;\n\t\t\t\t\treturn {\n\t\t\t\t\t\taccessKeyId,\n\t\t\t\t\t\tsecretAccessKey,\n\t\t\t\t\t\t...(env.AWS_SESSION_TOKEN\n\t\t\t\t\t\t\t? { sessionToken: env.AWS_SESSION_TOKEN }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t...where,\n\t\t\t\t\t} as never;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// A kind a target declared: nothing stored here can answer it.\n\t\t\treturn undefined;\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAaA,MAAa,eAAe;;AAG5B,SAAgB,QAAQ,MAAyB,QAAQ,KAAa;CACrE,MAAM,aAAa,IAAI;CACvB,OAAO,cAAA,GAAaA,UAAAA,QAAAA,CAAQ,UAAU,KAAA,GAAIC,UAAAA,KAAAA,EAAAA,GAAKC,QAAAA,QAAAA,CAAQ,GAAG,MAAM;AACjE;;;;;;AC8BA,SAAgB,kBAAkB,SAAqC;CACtE,IAAI,SAAS,MAAM,OAAO,QAAQ;CAClC,OAAO,SAAS,QAAA,GAAOC,UAAAA,KAAAA,CAAK,QAAQ,MAAM,MAAM,IAAI,QAAQ;AAC7D;;;;AAKA,SAAgB,mBAAmB,SAAqC;CACvE,QAAA,GAAOA,UAAAA,KAAAA,CAAK,kBAAkB,OAAO,GAAG,kBAAkB;AAC3D;;;;AAKA,SAAS,qBAAqB,SAAmC;CAChE,MAAM,MAAM,kBAAkB,OAAO;CACrC,IAAI,EAAA,GAACC,QAAAA,WAAAA,CAAW,GAAG,GAClB,CA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;IACrC,MAAM,QAAQ,SAAS,EAAE,OAAO,IAAI,CAAC;IACrC,IAAI,IAAI,aACP,OAAO;KAAE,SAAS,IAAI;KAAa,GAAG;IAAM;IAE7C,MAAM,cAAc,IAAI;IACxB,MAAM,kBAAkB,IAAI;IAC5B,IAAI,CAAC,eAAe,CAAC,iBAAiB,OAAO,KAAA;IAC7C,OAAO;KACN;KACA;KACA,GAAI,IAAI,oBACL,EAAE,cAAc,IAAI,kBAAkB,IACtC,CAAC;KACJ,GAAG;IACJ;GACD;EACD;CAGD,EACD;AACD"}
1
+ {"version":3,"file":"credentials-Csnd7M8M.cjs","names":["resolve","join","homedir","join","existsSync","readFile","writeFile","spawn","GkmError","kebabCase","scopedName","GkmError","join","homedir","mkdir","randomBytes","writeFile","chmod","existsSync","copyFile","constants","readFile","basename","join","existsSync","readFile","mkdir","writeFile","GkmError","readFileSync","randomBytes","createCipheriv","createDecipheriv","readFileSync","join","existsSync","realpathSync","dirname","readdirSync","sep","isReservedStageKey","s3SecretsLocation","UnknownSecretsStoreProvider","runtimeOf","DEFAULT_CACHE","DEFAULT_STORAGE","DEFAULT_EVENTS","appKey","provideKey","randomBytes","GkmError","output","lookup","GkmError"],"sources":["../src/home.ts","../src/auth/credentials.ts","../src/run.ts","../src/deploy/identity.ts","../src/secrets/keystore.ts","../src/secrets/file.ts","../src/build/native.ts","../src/secrets/storage.ts","../src/secrets/store.ts","../src/workspace/backends.ts","../src/providers/processorOrigin.ts","../src/deploy/state.ts","../src/target/dokploy/dns/DnsProvider.ts","../src/target/dokploy/dns/index.ts","../src/deploy/credentials.ts"],"sourcesContent":["/**\n * Where the CLI keeps what belongs to a person rather than a project: stage\n * keys and stored provider credentials.\n *\n * `GKM_HOME` names it, so a CI job, a shared build runner or a test can give\n * every run its own instead of reaching into whoever's home directory the\n * process happens to have. Unset, it is `~/.gkm`, where it has always been.\n */\n\nimport { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\n\n/** The environment variable that moves the CLI's home. */\nexport const GKM_HOME_ENV = 'GKM_HOME';\n\n/** The CLI's home: `GKM_HOME` if set, else `~/.gkm`. */\nexport function gkmHome(env: NodeJS.ProcessEnv = process.env): string {\n\tconst configured = env[GKM_HOME_ENV];\n\treturn configured ? resolve(configured) : join(homedir(), '.gkm');\n}\n","import { existsSync, mkdirSync } from 'node:fs';\nimport { readFile, unlink, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { gkmHome } from '../home';\n\n/**\n * Stored credentials for various services\n */\nexport interface StoredCredentials {\n\tdokploy?: {\n\t\t/** API token */\n\t\ttoken: string;\n\t\t/** Dokploy endpoint URL */\n\t\tendpoint: string;\n\t\t/** Registry ID in Dokploy (for Docker image pulls) */\n\t\tregistryId?: string;\n\t\t/** When the credentials were stored */\n\t\tstoredAt: string;\n\t};\n\thostinger?: {\n\t\t/** API token from hpanel.hostinger.com/profile/api */\n\t\ttoken: string;\n\t\t/** When the credentials were stored */\n\t\tstoredAt: string;\n\t};\n\tgodaddy?: {\n\t\t/** A Personal Access Token, scoped to domains.dns:update */\n\t\ttoken: string;\n\t\t/** When the credentials were stored */\n\t\tstoredAt: string;\n\t};\n}\n\n/**\n * Options for credential operations\n */\nexport interface CredentialOptions {\n\t/**\n\t * A directory whose `.gkm` holds the credentials. Default: the CLI's home\n\t * (`GKM_HOME`, else `~/.gkm`).\n\t */\n\troot?: string;\n\t/** The CLI's home itself, holding `credentials.json`. Wins over `root`. */\n\thome?: string;\n}\n\n/**\n * Get the path to the credentials directory\n */\nexport function getCredentialsDir(options?: CredentialOptions): string {\n\tif (options?.home) return options.home;\n\treturn options?.root ? join(options.root, '.gkm') : gkmHome();\n}\n\n/**\n * Get the path to the credentials file\n */\nexport function getCredentialsPath(options?: CredentialOptions): string {\n\treturn join(getCredentialsDir(options), 'credentials.json');\n}\n\n/**\n * Ensure the credentials directory exists\n */\nfunction ensureCredentialsDir(options?: CredentialOptions): void {\n\tconst dir = getCredentialsDir(options);\n\tif (!existsSync(dir)) {\n\t\tmkdirSync(dir, { recursive: true, mode: 0o700 });\n\t}\n}\n\n/**\n * Read stored credentials from disk\n */\nexport async function readCredentials(\n\toptions?: CredentialOptions,\n): Promise<StoredCredentials> {\n\tconst path = getCredentialsPath(options);\n\n\tif (!existsSync(path)) {\n\t\treturn {};\n\t}\n\n\ttry {\n\t\tconst content = await readFile(path, 'utf-8');\n\t\treturn JSON.parse(content) as StoredCredentials;\n\t} catch {\n\t\treturn {};\n\t}\n}\n\n/**\n * Write credentials to disk\n */\nexport async function writeCredentials(\n\tcredentials: StoredCredentials,\n\toptions?: CredentialOptions,\n): Promise<void> {\n\tensureCredentialsDir(options);\n\tconst path = getCredentialsPath(options);\n\n\tawait writeFile(path, JSON.stringify(credentials, null, 2), {\n\t\tmode: 0o600, // Owner read/write only\n\t});\n}\n\n/**\n * Store Dokploy credentials\n */\nexport async function storeDokployCredentials(\n\ttoken: string,\n\tendpoint: string,\n\toptions?: CredentialOptions,\n): Promise<void> {\n\tconst credentials = await readCredentials(options);\n\n\tcredentials.dokploy = {\n\t\ttoken,\n\t\tendpoint,\n\t\tstoredAt: new Date().toISOString(),\n\t};\n\n\tawait writeCredentials(credentials, options);\n}\n\n/**\n * Get stored Dokploy credentials\n */\nexport async function getDokployCredentials(\n\toptions?: CredentialOptions,\n): Promise<{\n\ttoken: string;\n\tendpoint: string;\n\tregistryId?: string;\n} | null> {\n\tconst credentials = await readCredentials(options);\n\n\t// The environment first, and each half independently.\n\t//\n\t// `getDokployToken` has always read `DOKPLOY_API_TOKEN` while this — the\n\t// function the deploy path actually calls — read only the file. So a CI job\n\t// given the token as a secret had a token and nowhere to send it, and the\n\t// only way through was committing a credentials file or running an\n\t// interactive login on the runner.\n\t//\n\t// Read separately rather than as a pair because they arrive separately: a\n\t// token is a secret and belongs in the environment, while an endpoint is\n\t// configuration and usually belongs in `deploy.dokploy.endpoint`. Requiring\n\t// both from the same place is what made either one useless alone.\n\tconst token = process.env.DOKPLOY_API_TOKEN ?? credentials.dokploy?.token;\n\tconst endpoint =\n\t\tprocess.env.DOKPLOY_ENDPOINT ?? credentials.dokploy?.endpoint;\n\n\tif (!token || !endpoint) return null;\n\n\treturn {\n\t\ttoken,\n\t\tendpoint: endpoint.replace(/\\/$/, ''),\n\t\t...(credentials.dokploy?.registryId\n\t\t\t? { registryId: credentials.dokploy.registryId }\n\t\t\t: {}),\n\t};\n}\n\n/**\n * Remove Dokploy credentials\n */\nexport async function removeDokployCredentials(\n\toptions?: CredentialOptions,\n): Promise<boolean> {\n\tconst credentials = await readCredentials(options);\n\n\tif (!credentials.dokploy) {\n\t\treturn false;\n\t}\n\n\tdelete credentials.dokploy;\n\tawait writeCredentials(credentials, options);\n\treturn true;\n}\n\n/**\n * Remove all stored credentials\n */\nexport async function removeAllCredentials(\n\toptions?: CredentialOptions,\n): Promise<void> {\n\tconst path = getCredentialsPath(options);\n\n\tif (existsSync(path)) {\n\t\tawait unlink(path);\n\t}\n}\n\n/**\n * Get Dokploy API token, checking stored credentials first, then environment\n */\nexport async function getDokployToken(\n\toptions?: CredentialOptions,\n): Promise<string | null> {\n\t// First check environment variable (takes precedence)\n\tconst envToken = process.env.DOKPLOY_API_TOKEN;\n\tif (envToken) {\n\t\treturn envToken;\n\t}\n\n\t// Then check stored credentials\n\tconst stored = await getDokployCredentials(options);\n\tif (stored) {\n\t\treturn stored.token;\n\t}\n\n\treturn null;\n}\n\n/**\n * Get Dokploy endpoint from stored credentials\n */\nexport async function getDokployEndpoint(\n\toptions?: CredentialOptions,\n): Promise<string | null> {\n\tconst stored = await getDokployCredentials(options);\n\treturn stored?.endpoint ?? null;\n}\n\n/**\n * Store Dokploy registry ID\n */\nexport async function storeDokployRegistryId(\n\tregistryId: string,\n\toptions?: CredentialOptions,\n): Promise<void> {\n\tconst credentials = await readCredentials(options);\n\n\tif (!credentials.dokploy) {\n\t\tthrow new Error(\n\t\t\t'Dokploy credentials not found. Run \"gkm login --service dokploy\" first.',\n\t\t);\n\t}\n\n\tcredentials.dokploy.registryId = registryId;\n\tawait writeCredentials(credentials, options);\n}\n\n/**\n * Get Dokploy registry ID from stored credentials\n */\nexport async function getDokployRegistryId(\n\toptions?: CredentialOptions,\n): Promise<string | undefined> {\n\tconst stored = await getDokployCredentials(options);\n\treturn stored?.registryId ?? undefined;\n}\n\n// ============================================\n// Hostinger credentials\n// ============================================\n\n/**\n * Store Hostinger API token\n *\n * @param token - API token from hpanel.hostinger.com/profile/api\n */\nexport async function storeHostingerToken(\n\ttoken: string,\n\toptions?: CredentialOptions,\n): Promise<void> {\n\tconst credentials = await readCredentials(options);\n\n\tcredentials.hostinger = {\n\t\ttoken,\n\t\tstoredAt: new Date().toISOString(),\n\t};\n\n\tawait writeCredentials(credentials, options);\n}\n\n/**\n * Get stored Hostinger API token\n *\n * Checks environment variable first (HOSTINGER_API_TOKEN),\n * then falls back to stored credentials.\n */\nexport async function getHostingerToken(\n\toptions?: CredentialOptions,\n): Promise<string | null> {\n\t// First check environment variable (takes precedence)\n\tconst envToken = process.env.HOSTINGER_API_TOKEN;\n\tif (envToken) {\n\t\treturn envToken;\n\t}\n\n\t// Then check stored credentials\n\tconst credentials = await readCredentials(options);\n\treturn credentials.hostinger?.token ?? null;\n}\n\n/**\n * Remove Hostinger credentials\n */\nexport async function removeHostingerCredentials(\n\toptions?: CredentialOptions,\n): Promise<boolean> {\n\tconst credentials = await readCredentials(options);\n\n\tif (!credentials.hostinger) {\n\t\treturn false;\n\t}\n\n\tdelete credentials.hostinger;\n\tawait writeCredentials(credentials, options);\n\treturn true;\n}\n\n// ============================================\n// GoDaddy credentials\n// ============================================\n\n/**\n * Store a GoDaddy Personal Access Token.\n */\nexport async function storeGoDaddyToken(\n\ttoken: string,\n\toptions?: CredentialOptions,\n): Promise<void> {\n\tconst credentials = await readCredentials(options);\n\n\tcredentials.godaddy = {\n\t\ttoken,\n\t\tstoredAt: new Date().toISOString(),\n\t};\n\n\tawait writeCredentials(credentials, options);\n}\n\n/**\n * Remove GoDaddy credentials\n */\nexport async function removeGoDaddyCredentials(\n\toptions?: CredentialOptions,\n): Promise<boolean> {\n\tconst credentials = await readCredentials(options);\n\n\tif (!credentials.godaddy) {\n\t\treturn false;\n\t}\n\n\tdelete credentials.godaddy;\n\tawait writeCredentials(credentials, options);\n\treturn true;\n}\n","/**\n * Start a program with an argument array, never a shell string.\n *\n * `gkm build`, `gkm docker` and `gkm deploy` pass values that come from the\n * workspace — image refs, tags, build args, package names — to `docker` and\n * `turbo`. Joined into a string and handed to a shell, a package named\n * `x;curl …|sh` or a tag holding `$(…)` became part of the command line, which\n * matters most where the CLI builds a repository it didn't write: a CI job for a\n * fork, a shared build runner. Here every value reaches the program as one\n * `argv` element, whatever it contains.\n */\n\nimport { type SpawnOptions, spawn } from 'node:child_process';\n\n/** Long enough for a cold image build; short enough that a hung one ends. */\nexport const DEFAULT_TIMEOUT_MS = 30 * 60_000;\n\n/** How long a timed-out child has to exit on SIGTERM before it is killed. */\nconst KILL_GRACE_MS = 5_000;\n\nexport interface RunOptions {\n\tcwd?: string;\n\tenv?: NodeJS.ProcessEnv;\n\tstdio?: SpawnOptions['stdio'];\n\t/** Kill the child after this long. Defaults to {@link DEFAULT_TIMEOUT_MS}. */\n\ttimeoutMs?: number;\n\t/**\n\t * Kills the child when aborted, and rejects with the signal's reason — the\n\t * same as a stopped deploy's other calls.\n\t */\n\tsignal?: AbortSignal;\n}\n\n/** The command line as a person would read it — for messages, never to run. */\nfunction display(command: string, args: readonly string[]): string {\n\treturn [command, ...args].join(' ');\n}\n\n/** The program ran and exited unsuccessfully; its own output said why. */\nexport class CommandFailed extends Error {\n\tconstructor(\n\t\treadonly command: string,\n\t\treadonly args: readonly string[],\n\t\treadonly exitCode: number | null,\n\t\treadonly signal: NodeJS.Signals | null,\n\t) {\n\t\tsuper(\n\t\t\t`\\`${display(command, args)}\\` ${exitCode === null ? `was stopped by ${signal ?? 'a signal'}` : `exited with code ${exitCode}`}. Its output above says why; run it by hand to see it again.`,\n\t\t);\n\t\tthis.name = 'CommandFailed';\n\t}\n}\n\n/** The program ran past its timeout and was killed. */\nexport class CommandTimedOut extends Error {\n\tconstructor(\n\t\treadonly command: string,\n\t\treadonly args: readonly string[],\n\t\treadonly timeoutMs: number,\n\t) {\n\t\tsuper(\n\t\t\t`\\`${display(command, args)}\\` was still running after ${Math.round(timeoutMs / 1000)}s and was stopped. Check what it was waiting on — a registry, the Docker daemon, a prompt — and run it again.`,\n\t\t);\n\t\tthis.name = 'CommandTimedOut';\n\t}\n}\n\n/**\n * Run `command` with `args`, resolving when it exits 0.\n *\n * Rejects with {@link CommandFailed} on any other exit, {@link CommandTimedOut}\n * once `timeoutMs` passes (after the child is gone), and with the spawn error\n * itself when the program cannot be started at all — `ENOENT` already names it.\n */\nexport async function run(\n\tcommand: string,\n\targs: readonly string[],\n\toptions: RunOptions = {},\n): Promise<void> {\n\tawait spawnChild(command, args, options, false);\n}\n\n/**\n * {@link run}, resolving with what the program wrote to stdout — for a value\n * the CLI reads back, such as the digest `docker inspect` reports. stderr still\n * reaches the terminal, so a failure explains itself the same way.\n */\nexport function runOutput(\n\tcommand: string,\n\targs: readonly string[],\n\toptions: Omit<RunOptions, 'stdio'> = {},\n): Promise<string> {\n\treturn spawnChild(command, args, options, true);\n}\n\nfunction spawnChild(\n\tcommand: string,\n\targs: readonly string[],\n\toptions: RunOptions,\n\tcapture: boolean,\n): Promise<string> {\n\tconst { timeoutMs = DEFAULT_TIMEOUT_MS, ...spawnOptions } = options;\n\n\treturn new Promise<string>((resolve, reject) => {\n\t\tconst child = spawn(command, [...args], {\n\t\t\tstdio: 'inherit',\n\t\t\t...spawnOptions,\n\t\t\t...(capture ? { stdio: ['ignore', 'pipe', 'inherit'] } : {}),\n\t\t\tshell: false,\n\t\t});\n\n\t\tlet stdout = '';\n\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\tstdout += chunk.toString();\n\t\t});\n\n\t\tlet timedOut = false;\n\t\tlet killer: NodeJS.Timeout | undefined;\n\t\tconst timer = setTimeout(() => {\n\t\t\ttimedOut = true;\n\t\t\tchild.kill('SIGTERM');\n\t\t\t// A child that ignores SIGTERM would hold the deploy open forever.\n\t\t\tkiller = setTimeout(() => child.kill('SIGKILL'), KILL_GRACE_MS);\n\t\t\tkiller.unref?.();\n\t\t}, timeoutMs);\n\t\ttimer.unref?.();\n\n\t\tconst settle = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tif (killer) clearTimeout(killer);\n\t\t};\n\n\t\tchild.on('error', (error) => {\n\t\t\tsettle();\n\t\t\t// Node reports an abort as its own `AbortError`; the caller asked\n\t\t\t// with a reason, and that is what it should get back.\n\t\t\treject(spawnOptions.signal?.aborted ? spawnOptions.signal.reason : error);\n\t\t});\n\n\t\tchild.on('close', (code: number | null, signal: NodeJS.Signals | null) => {\n\t\t\tsettle();\n\t\t\tif (spawnOptions.signal?.aborted) reject(spawnOptions.signal.reason);\n\t\t\telse if (timedOut) reject(new CommandTimedOut(command, args, timeoutMs));\n\t\t\telse if (code === 0) resolve(stdout);\n\t\t\telse reject(new CommandFailed(command, args, code, signal));\n\t\t});\n\t});\n}\n","/**\n * Who a deploy is, on a target it shares with other workspaces.\n *\n * A Dokploy server is one flat namespace of projects, images and Docker\n * service names. Deploys used to identify everything they made by the\n * workspace name alone, so two workspaces called `shop` — or `Shop` and\n * `shop` — deploying to one server landed in the same project, pushed over\n * each other's images and redeployed each other's applications. A\n * `DeployIdentity` is what a deploy names and claims its resources by instead.\n */\n\nimport { kebabCase, scopedName } from '@geekmidas/manifest';\nimport { GkmError } from '../errors';\n\nexport interface DeployIdentity {\n\t/**\n\t * Whose deploy this is — an organisation, a team, a repository. Two\n\t * workspaces with the same name are told apart by it. Defaults to the\n\t * kebab-cased workspace name; set `deploy.namespace` to choose one.\n\t */\n\treadonly namespace: string;\n\t/** The workspace name as the target spells it: lowercase, `[a-z0-9-]`. */\n\treadonly project: string;\n\treadonly stage: string;\n\t/**\n\t * `<namespace>/<project>`: what a Dokploy project is claimed by.\n\t *\n\t * The stage is not part of it because one Dokploy project holds every stage\n\t * of a workspace, each as an environment — the key has to be the same from\n\t * every stage that deploys into it.\n\t */\n\treadonly key: string;\n\t/**\n\t * The prefix every name on the target carries: the project alone in the\n\t * default namespace, `<namespace>-<project>` in any other.\n\t *\n\t * The default adds nothing so that a workspace that never set a namespace\n\t * keeps the names it was already deployed under — a Postgres is found by\n\t * its name, and a new name would be a new, empty database.\n\t */\n\treadonly scope: string;\n}\n\n/** A namespace that cannot be part of a Dokploy name or an image path. */\nexport class DeployNamespaceInvalid extends GkmError {\n\tconstructor(readonly namespace: string) {\n\t\tsuper(\n\t\t\t`deploy.namespace '${namespace}' is not usable as a name: use lowercase letters, digits and single '-' between them (e.g. 'acme' or 'acme-platform') in gkm.config.ts.`,\n\t\t);\n\t\tthis.name = 'DeployNamespaceInvalid';\n\t}\n}\n\n/** A workspace name with nothing a target can name a resource by. */\nexport class DeployProjectNameInvalid extends GkmError {\n\tconstructor(readonly workspaceName: string) {\n\t\tsuper(\n\t\t\t`The workspace name '${workspaceName}' has no letters or digits to name deployed resources by. Set \"name\" in gkm.config.ts.`,\n\t\t);\n\t\tthis.name = 'DeployProjectNameInvalid';\n\t}\n}\n\nconst NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n/**\n * Lowercase `[a-z0-9-]`, runs of anything else collapsed to one `-`: valid as\n * a Docker image path component, a Docker service name and a Dokploy name.\n */\nfunction slug(value: string): string {\n\treturn value\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9]+/g, '-')\n\t\t.replace(/^-+|-+$/g, '');\n}\n\n/** The namespace a workspace is in when it does not name one. */\nexport function defaultNamespace(workspaceName: string): string {\n\treturn slug(kebabCase(workspaceName));\n}\n\n/** What an identity is derived from: a workspace's name and namespace. */\nexport interface IdentitySource {\n\tname: string;\n\tdeploy?: { namespace?: string };\n}\n\nexport function deployIdentity(\n\tworkspace: IdentitySource,\n\tstage: string,\n): DeployIdentity {\n\t// Lowercased rather than kebab-cased: the names a workspace was already\n\t// deployed under were `${stage}-${name}`.toLowerCase(), and this has to\n\t// reproduce them for the databases it finds by name.\n\tconst project = slug(workspace.name);\n\tif (!project) throw new DeployProjectNameInvalid(workspace.name);\n\n\tconst fallback = defaultNamespace(workspace.name);\n\tconst namespace = workspace.deploy?.namespace ?? fallback;\n\tif (!NAME.test(namespace)) throw new DeployNamespaceInvalid(namespace);\n\n\treturn {\n\t\tnamespace,\n\t\tproject,\n\t\tstage,\n\t\tkey: `${namespace}/${project}`,\n\t\tscope: namespace === fallback ? project : `${namespace}-${project}`,\n\t};\n}\n\n/**\n * The token a Dokploy project's description carries to say which identity\n * created it. A project with the right name and no marker belongs to someone\n * else, and a deploy never adopts it.\n */\nexport function ownershipMarker(identity: DeployIdentity): string {\n\treturn `gkm:${identity.key}`;\n}\n\n/** Whether a project description carries `identity`'s marker. */\nexport function isOwnedBy(\n\tdescription: string | null | undefined,\n\tidentity: DeployIdentity,\n): boolean {\n\tconst marker = ownershipMarker(identity);\n\treturn (description ?? '').split(/\\s+/).includes(marker);\n}\n\n/** Any `gkm:` marker a description carries — whoever's it is. */\nexport function markerOf(\n\tdescription: string | null | undefined,\n): string | undefined {\n\treturn (description ?? '').split(/\\s+/).find((t) => t.startsWith('gkm:'));\n}\n\n/** What the Dokploy project is called. */\nexport function projectName(identity: DeployIdentity): string {\n\treturn identity.scope;\n}\n\n/**\n * The repository an app's image is pushed to, below the registry:\n * `<namespace>/<project>-<app>`.\n *\n * The namespace is a path segment of its own so that a registry that maps\n * paths to owners (an organisation's packages, a Harbor project) can grant it\n * as one; the app is joined to the project so the two read as one name.\n */\nexport function imageName(identity: DeployIdentity, app: string): string {\n\treturn `${identity.namespace}/${identity.project}-${slug(kebabCase(app))}`;\n}\n\n/** The full image ref an app is built, pushed and deployed as. */\nexport function imageRef(\n\tidentity: DeployIdentity,\n\tapp: string,\n\tregistry: string | undefined,\n\ttag: string,\n): string {\n\tconst name = imageName(identity, app);\n\treturn registry\n\t\t? `${registry.replace(/\\/+$/, '')}/${name}:${tag}`\n\t\t: `${name}:${tag}`;\n}\n\n/**\n * What one application is called on the target.\n *\n * The same rule the constructs use, through the same `scopedName`, scoped by\n * the stage and the identity: the application beside\n * `production-kitchen-sink-database` is `production-kitchen-sink-api`. A\n * Dokploy application's name is also its Docker service name, which is unique\n * on the whole server, so the namespace has to be in it too — `acme`'s and\n * `globex`'s `shop` would otherwise both run `production-shop-api`.\n *\n * The app id is dropped when it repeats the project, so a project named for its\n * one application is `production-kitchen-sink` rather than\n * `production-kitchen-sink-kitchen-sink`.\n */\nexport function applicationName(identity: DeployIdentity, app: string): string {\n\treturn slug(app) === identity.project\n\t\t? `${identity.stage}-${identity.scope}`\n\t\t: scopedName([identity.stage, identity.scope], app);\n}\n","/**\n * The keys that open each stage's encrypted secrets file, kept outside the\n * project in the CLI's home.\n *\n * Keys were kept at `~/.gkm/<folder>/<stage>.key`, named after the project\n * directory — so two checkouts in folders with the same name (`~/work/api`\n * and `~/oss/api`) shared one key, and the second `gkm secrets:init`\n * overwrote the first project's. They are now kept under the project's\n * identity, `<home>/keys/<namespace>/<project>/<stage>.key`, the same\n * `<namespace>/<project>` a deploy claims its Dokploy project by. A key still\n * at the old place is copied to the new one the first time it is read; the\n * old file stays, so an older CLI on the same machine keeps working.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport { constants, existsSync } from 'node:fs';\nimport {\n\tchmod,\n\tcopyFile,\n\tmkdir,\n\treadFile,\n\trm,\n\twriteFile,\n} from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { deployIdentity, type IdentitySource } from '../deploy/identity';\nimport { GkmError } from '../errors';\nimport { gkmHome } from '../home';\n\n/** Key length for AES-256 encryption */\nconst KEY_LENGTH = 32; // 256 bits\n\n/** Whose keys, and where the CLI's home is. */\nexport interface KeystoreProject {\n\t/** `<namespace>/<project>`, as `DeployIdentity.key` spells it. */\n\tkey: string;\n\t/**\n\t * The names the project's keys were kept under, `~/.gkm/<name>/`, before\n\t * they were keyed by identity: its directory's basename, which the secrets\n\t * file used, and its workspace name, which `gkm init` and the generated CI\n\t * workflow wrote to. Looked in, and copied from, when the project has no\n\t * key of its own yet.\n\t */\n\tlegacy?: readonly string[];\n\t/**\n\t * Other project keys this project's keys may be copied from when it has\n\t * none: the default namespace's, for a workspace that has just set\n\t * `deploy.namespace` — the secrets file in the checkout is the same one.\n\t */\n\taliases?: string[];\n\t/** The CLI's home. Defaults to `GKM_HOME`, else `~/.gkm`. */\n\thome?: string;\n}\n\n/** A keystore project key that is not `<namespace>/<project>`. */\nexport class KeystoreProjectInvalid extends GkmError {\n\tconstructor(readonly key: string) {\n\t\tsuper(\n\t\t\t`'${key}' is not a keystore project: expected '<namespace>/<project>' in lowercase letters, digits and '-', as deployIdentity() produces. Pass the workspace's identity key.`,\n\t\t);\n\t\tthis.name = 'KeystoreProjectInvalid';\n\t}\n}\n\n/** A stage has no key, here or at the place keys used to be kept. */\nexport class KeyNotFound extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly project: string,\n\t\treadonly path: string,\n\t) {\n\t\tsuper(\n\t\t\t`Encryption key not found for stage \"${stage}\" in project \"${project}\". ` +\n\t\t\t\t`Expected key at: ${path}. Run \\`gkm secrets:init --stage ${stage}\\` to create one, or copy the stage's key there.`,\n\t\t);\n\t\tthis.name = 'KeyNotFound';\n\t}\n}\n\nconst PROJECT_KEY = /^[a-z0-9]+(?:-[a-z0-9]+)*\\/[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n/**\n * The keystore key of a workspace: its deploy identity without the stage, so\n * a project's keys and its Dokploy project are named by the same thing.\n */\nexport function projectKey(workspace: IdentitySource): string {\n\treturn deployIdentity(workspace, '').key;\n}\n\n/** The keystore project of a loaded workspace. */\nexport function keystoreProject(\n\tworkspace: IdentitySource & { root: string },\n\thome?: string,\n): KeystoreProject {\n\tconst key = projectKey(workspace);\n\tconst unscoped = projectKey({ name: workspace.name });\n\tconst legacy = [\n\t\t...new Set([folderName(workspace.root), workspace.name]),\n\t].filter((name): name is string => !!name);\n\treturn {\n\t\tkey,\n\t\tlegacy,\n\t\t...(unscoped !== key ? { aliases: [unscoped] } : {}),\n\t\t...(home ? { home } : {}),\n\t};\n}\n\n/**\n * Whether `name` stays inside the home it is joined to. A workspace name was\n * joined as is — `@acme/shop` is `~/.gkm/@acme/shop` — but never upwards.\n */\nfunction isLegacyName(name: string): boolean {\n\treturn name.split(/[\\\\/]/).every((part) => part !== '..' && part !== '');\n}\n\n/** The last segment of a path, as the old keystore named projects. */\nfunction folderName(path: string): string | undefined {\n\tconst name = path.split(/[\\\\/]/).filter(Boolean).at(-1);\n\treturn name && name !== '.' && name !== '..' ? name : undefined;\n}\n\n/**\n * Get the keystore directory for a project:\n * `<home>/keys/<namespace>/<project>`.\n */\nexport function getKeystoreDir(project: KeystoreProject): string {\n\tif (!PROJECT_KEY.test(project.key)) {\n\t\tthrow new KeystoreProjectInvalid(project.key);\n\t}\n\tconst [namespace, name] = project.key.split('/') as [string, string];\n\treturn join(project.home ?? gkmHome(), 'keys', namespace, name);\n}\n\n/** Get the path to a stage's encryption key. */\nexport function getKeyPath(stage: string, project: KeystoreProject): string {\n\treturn join(getKeystoreDir(project), `${stage}.key`);\n}\n\n/**\n * Where else a stage's key may be, most likely first: under an alias of the\n * project, then where keys were kept before they were keyed by identity —\n * under the configured home, then under `~/.gkm`, which is where every CLI\n * before `GKM_HOME` wrote.\n */\nfunction legacyKeyPaths(stage: string, project: KeystoreProject): string[] {\n\tconst aliases = (project.aliases ?? []).map((key) =>\n\t\tgetKeyPath(stage, { key, home: project.home }),\n\t);\n\tconst homes = [\n\t\t...new Set([project.home ?? gkmHome(), join(homedir(), '.gkm')]),\n\t];\n\tconst names = (project.legacy ?? []).filter(isLegacyName);\n\treturn [\n\t\t...aliases,\n\t\t...names.flatMap((name) =>\n\t\t\thomes.map((home) => join(home, name, `${stage}.key`)),\n\t\t),\n\t];\n}\n\n/** Check if a key exists for a stage, here or where it used to be kept. */\nexport function keyExists(stage: string, project: KeystoreProject): boolean {\n\treturn (\n\t\texistsSync(getKeyPath(stage, project)) ||\n\t\tlegacyKeyPaths(stage, project).some((path) => existsSync(path))\n\t);\n}\n\n/**\n * Generate a new encryption key for a stage, stored owner-only at\n * `<home>/keys/<namespace>/<project>/<stage>.key`.\n */\nexport async function generateKey(\n\tstage: string,\n\tproject: KeystoreProject,\n\t/** `wx` to refuse replacing a key that is already there. */\n\tflag: 'w' | 'wx' = 'w',\n): Promise<string> {\n\tconst keyDir = getKeystoreDir(project);\n\tconst keyPath = getKeyPath(stage, project);\n\n\t// Ensure keystore directory exists with restricted permissions\n\tawait mkdir(keyDir, { recursive: true, mode: 0o700 });\n\n\t// Generate random key\n\tconst key = randomBytes(KEY_LENGTH).toString('hex');\n\n\t// Write key with restricted permissions (owner read/write only)\n\tawait writeFile(keyPath, key, { mode: 0o600, encoding: 'utf-8', flag });\n\n\t// Ensure permissions are set correctly (in case file existed)\n\tawait chmod(keyPath, 0o600);\n\n\treturn key;\n}\n\n/**\n * Copy a key from where it used to be kept to where it is kept now.\n *\n * Copied, not moved: an older CLI on the same machine still reads the old\n * place. Exclusive, so two processes migrating at once cannot overwrite a key\n * one of them already put there.\n */\nasync function migrateLegacyKey(\n\tstage: string,\n\tproject: KeystoreProject,\n): Promise<boolean> {\n\tconst legacy = legacyKeyPaths(stage, project).find((path) =>\n\t\texistsSync(path),\n\t);\n\tif (!legacy) return false;\n\n\tconst keyPath = getKeyPath(stage, project);\n\tawait mkdir(getKeystoreDir(project), { recursive: true, mode: 0o700 });\n\ttry {\n\t\tawait copyFile(legacy, keyPath, constants.COPYFILE_EXCL);\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n\t}\n\tawait chmod(keyPath, 0o600);\n\treturn true;\n}\n\n/**\n * Read an encryption key for a stage, or `null` when there is none — after\n * copying it over from where keys used to be kept, if it is still there.\n */\nexport async function readKey(\n\tstage: string,\n\tproject: KeystoreProject,\n): Promise<string | null> {\n\tconst keyPath = getKeyPath(stage, project);\n\n\tif (!existsSync(keyPath) && !(await migrateLegacyKey(stage, project))) {\n\t\treturn null;\n\t}\n\n\tconst key = await readFile(keyPath, 'utf-8');\n\treturn key.trim();\n}\n\n/**\n * Read an encryption key for a stage, throwing {@link KeyNotFound} if there\n * is none.\n */\nexport async function requireKey(\n\tstage: string,\n\tproject: KeystoreProject,\n): Promise<string> {\n\tconst key = await readKey(stage, project);\n\n\tif (!key) {\n\t\tthrow new KeyNotFound(stage, project.key, getKeyPath(stage, project));\n\t}\n\n\treturn key;\n}\n\n/**\n * Delete a key for a stage. Only the current one: a key left at the old place\n * belongs to whichever older CLI still reads it.\n */\nexport async function deleteKey(\n\tstage: string,\n\tproject: KeystoreProject,\n): Promise<void> {\n\tawait rm(getKeyPath(stage, project), { force: true });\n}\n\n/**\n * Get or create a key for a stage.\n * If the key already exists, it is returned. Otherwise, a new key is generated.\n */\nexport async function getOrCreateKey(\n\tstage: string,\n\tproject: KeystoreProject,\n): Promise<string> {\n\tconst existingKey = await readKey(stage, project);\n\n\tif (existingKey) {\n\t\treturn existingKey;\n\t}\n\n\t// Exclusively: a key is now shared by every checkout of one project, and\n\t// two commands creating it at once must not each keep a different one.\n\ttry {\n\t\treturn await generateKey(stage, project, 'wx');\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n\t\treturn requireKey(stage, project);\n\t}\n}\n","import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { basename, join } from 'node:path';\nimport { GkmError } from '../errors';\nimport {\n\tgetKeyPath,\n\tgetOrCreateKey,\n\ttype KeystoreProject,\n\tprojectKey,\n\treadKey,\n} from './keystore';\nimport type { SecretsStore } from './store.js';\nimport type { StageSecrets } from './types';\n\n/** Where the files live, relative to the project root. */\nconst SECRETS_DIR = '.gkm/secrets';\n\n/** AES-256-GCM configuration */\nconst ALGORITHM = 'aes-256-gcm';\nconst IV_LENGTH = 12; // 96 bits for GCM\nconst AUTH_TAG_LENGTH = 16; // 128 bits\n\n/** Encrypted secrets file structure */\nexport interface EncryptedSecretsFile {\n\t/** Version for future format changes */\n\tversion: 1;\n\t/** Base64 encoded encrypted data (ciphertext + auth tag) */\n\tencrypted: string;\n\t/** Hex encoded IV */\n\tiv: string;\n}\n\n/**\n * A stage's secrets as an encrypted file on this machine:\n * `.gkm/secrets/<stage>.json`, with its key in the CLI's home at\n * `keys/<namespace>/<project>/<stage>.key`.\n *\n * The local stage's store, always — its secrets belong to the machine running\n * `gkm dev` — and a deployed stage's when `secrets.store` is `'file'`.\n */\nexport class FileSecretsStore implements SecretsStore {\n\treadonly name = 'file';\n\tprivate readonly project: KeystoreProject;\n\n\t/**\n\t * @param project - Whose keys: a workspace's `keystoreProject()`. Outside a\n\t * workspace there is no config to name the project, so it is named the\n\t * way a workspace without `name` is — its package name, else its folder.\n\t */\n\tconstructor(\n\t\tprivate readonly root: string,\n\t\tproject?: KeystoreProject,\n\t) {\n\t\tthis.project = project ?? {\n\t\t\tkey: projectKey({ name: packageName(root) ?? basename(root) }),\n\t\t\tlegacy: [basename(root)],\n\t\t};\n\t}\n\n\t/** The file a stage's secrets are kept in. */\n\tpath(stage: string): string {\n\t\treturn join(this.root, SECRETS_DIR, `${stage}.json`);\n\t}\n\n\tasync read(stage: string): Promise<StageSecrets | null> {\n\t\tconst path = this.path(stage);\n\t\tif (!existsSync(path)) return null;\n\n\t\tconst data = JSON.parse(await readFile(path, 'utf-8'));\n\n\t\t// Legacy: unencrypted format (for backwards compatibility)\n\t\tif (!(data.version === 1 && data.encrypted && data.iv)) {\n\t\t\treturn data as StageSecrets;\n\t\t}\n\n\t\tconst key = await readKey(stage, this.project);\n\t\tif (!key) {\n\t\t\tthrow new MissingSecretsKey(\n\t\t\t\tstage,\n\t\t\t\tthis.project.key,\n\t\t\t\tgetKeyPath(stage, this.project),\n\t\t\t);\n\t\t}\n\n\t\treturn decrypt(data as EncryptedSecretsFile, key);\n\t}\n\n\tasync write(stage: string, secrets: StageSecrets): Promise<void> {\n\t\tawait mkdir(join(this.root, SECRETS_DIR), { recursive: true });\n\n\t\tconst key = await getOrCreateKey(stage, this.project);\n\t\tawait writeFile(\n\t\t\tthis.path(stage),\n\t\t\tJSON.stringify(encrypt(secrets, key), null, 2),\n\t\t\t'utf-8',\n\t\t);\n\t}\n}\n\n/** A stage's secrets file exists, and the key that opens it does not. */\nexport class MissingSecretsKey extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly project: string,\n\t\treadonly path: string,\n\t) {\n\t\tsuper(\n\t\t\t`Decryption key not found for stage \"${stage}\". ` +\n\t\t\t\t`Expected key at: ${path}. Copy the stage's key there from whoever created it, or set secrets.store to a store this machine can reach.`,\n\t\t);\n\t\tthis.name = 'MissingSecretsKey';\n\t}\n}\n\n/** A project's package name without its scope, as a workspace name reads it. */\nfunction packageName(root: string): string | undefined {\n\ttry {\n\t\tconst pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf-8'));\n\t\treturn typeof pkg.name === 'string'\n\t\t\t? pkg.name.replace(/^@[^/]+\\//, '')\n\t\t\t: undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Encrypt a JSON value with a stage key: AES-256-GCM, the file format every\n * stage's secrets are kept in.\n */\nexport function encrypt(\n\tsecrets: unknown,\n\tkeyHex: string,\n): EncryptedSecretsFile {\n\tconst key = Buffer.from(keyHex, 'hex');\n\tconst iv = randomBytes(IV_LENGTH);\n\n\tconst cipher = createCipheriv(ALGORITHM, key, iv);\n\tconst ciphertext = Buffer.concat([\n\t\tcipher.update(JSON.stringify(secrets), 'utf-8'),\n\t\tcipher.final(),\n\t]);\n\n\t// Ciphertext and auth tag, together\n\tconst combined = Buffer.concat([ciphertext, cipher.getAuthTag()]);\n\n\treturn {\n\t\tversion: 1,\n\t\tencrypted: combined.toString('base64'),\n\t\tiv: iv.toString('hex'),\n\t};\n}\n\n/** Decrypt what {@link encrypt} wrote. */\nexport function decrypt<T = StageSecrets>(\n\tdata: EncryptedSecretsFile,\n\tkeyHex: string,\n): T {\n\tconst key = Buffer.from(keyHex, 'hex');\n\tconst combined = Buffer.from(data.encrypted, 'base64');\n\n\tconst decipher = createDecipheriv(\n\t\tALGORITHM,\n\t\tkey,\n\t\tBuffer.from(data.iv, 'hex'),\n\t);\n\tdecipher.setAuthTag(combined.subarray(-AUTH_TAG_LENGTH));\n\n\tconst plaintext = Buffer.concat([\n\t\tdecipher.update(combined.subarray(0, -AUTH_TAG_LENGTH)),\n\t\tdecipher.final(),\n\t]);\n\n\treturn JSON.parse(plaintext.toString('utf-8')) as T;\n}\n","import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs';\nimport { dirname, join, sep } from 'node:path';\n\n/**\n * A package left out of a bundle, at the version the build resolved — what\n * an image installs beside the bundle, for its own platform.\n */\nexport type ExternalPackages = Record<string, string>;\n\n/**\n * The file beside a bundle naming the packages it left out, each at the\n * version the build resolved: a `package.json` an image installs, for its own\n * platform, next to the bundle. `server.mjs` → `server.externals.json`.\n */\nexport function externalsManifestName(outfile: string): string {\n\treturn `${outfile.replace(/\\.mjs$/, '')}.externals.json`;\n}\n\n/**\n * Asked to leave a package out of the bundle, and nothing the app depends on\n * provides it: there is no version to install in the image.\n */\nexport class ExternalNotInstalled extends Error {\n\tconstructor(\n\t\treadonly packageName: string,\n\t\treadonly root: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${packageName}' is left out of the bundle, to be installed beside it, but it is not installed for the app at ${root}: add it to the app's dependencies.`,\n\t\t);\n\t\tthis.name = 'ExternalNotInstalled';\n\t}\n}\n\ninterface PackageJson {\n\tname?: string;\n\tversion?: string;\n\tdependencies?: Record<string, string>;\n\toptionalDependencies?: Record<string, string>;\n\tgypfile?: boolean;\n\tbinary?: unknown;\n\tnapi?: unknown;\n\tos?: string[];\n}\n\n/** Packages whose job is loading a compiled addon. */\nconst NATIVE_LOADERS = new Set([\n\t'bindings',\n\t'node-gyp-build',\n\t'node-gyp-build-optional-packages',\n\t'node-pre-gyp',\n\t'@mapbox/node-pre-gyp',\n\t'prebuild-install',\n\t'@neon-rs/load',\n]);\n\n/** A per-platform binary package: `@node-rs/argon2-linux-x64-gnu`, `@img/sharp-darwin-arm64`. */\nconst PLATFORM_PACKAGE =\n\t/(?:^|[-/])(?:linux|darwin|win32|freebsd|android)-(?:x64|arm64|arm|ia32)\\b/;\n\nfunction readPackage(dir: string): PackageJson | undefined {\n\ttry {\n\t\treturn JSON.parse(readFileSync(join(dir, 'package.json'), 'utf-8'));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Where `name` resolves from `from`, the way Node finds it: the nearest\n * `node_modules/<name>` walking up. Followed through symlinks, so a pnpm\n * store package resolves its own dependencies beside it.\n */\nfunction locate(name: string, from: string): string | undefined {\n\tlet dir = from;\n\tfor (;;) {\n\t\tconst candidate = join(dir, 'node_modules', name);\n\t\tif (existsSync(join(candidate, 'package.json'))) {\n\t\t\treturn realpathSync(candidate);\n\t\t}\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) return undefined;\n\t\tdir = parent;\n\t}\n}\n\n/**\n * Whether a package carries compiled code: a `binding.gyp` or prebuilt\n * binaries of its own, a loader for them, or a binary package per platform.\n * Such a package cannot be inlined into a bundle — it loads a `.node` file\n * from beside its own source, for the platform it was installed on.\n */\nexport function isNativePackage(dir: string, pkg: PackageJson): boolean {\n\tif (pkg.gypfile || pkg.binary || pkg.napi) return true;\n\tconst deps = Object.keys({\n\t\t...pkg.dependencies,\n\t\t...pkg.optionalDependencies,\n\t});\n\tif (deps.some((dep) => NATIVE_LOADERS.has(dep))) return true;\n\tif (\n\t\tObject.keys(pkg.optionalDependencies ?? {}).some((dep) =>\n\t\t\tPLATFORM_PACKAGE.test(dep),\n\t\t)\n\t) {\n\t\treturn true;\n\t}\n\tif (existsSync(join(dir, 'binding.gyp'))) return true;\n\tif (existsSync(join(dir, 'prebuilds'))) return true;\n\ttry {\n\t\treturn readdirSync(dir).some((file) => file.endsWith('.node'));\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * The packages with native code an app's bundle would otherwise inline, each\n * at the version installed for it.\n *\n * Walks what the app depends on at runtime — `dependencies`, never\n * `devDependencies` — through workspace packages and installed ones alike,\n * since anything reached is bundled. A native package is where the walk\n * stops: installing it brings what it depends on.\n */\nexport function nativeDependencies(root: string): ExternalPackages {\n\tconst found: ExternalPackages = {};\n\tconst seen = new Set<string>();\n\tconst queue = [realpathSync(root)];\n\n\twhile (queue.length > 0) {\n\t\tconst dir = queue.shift()!;\n\t\tif (seen.has(dir)) continue;\n\t\tseen.add(dir);\n\n\t\tconst pkg = readPackage(dir);\n\t\tif (!pkg) continue;\n\t\tconst isRoot = seen.size === 1;\n\t\tconst installed = dir.split(sep).includes('node_modules');\n\n\t\tif (!isRoot && installed && isNativePackage(dir, pkg)) {\n\t\t\t// One that cannot install on Linux — fsevents — is never in an image;\n\t\t\t// whatever loads it does without.\n\t\t\tconst linux =\n\t\t\t\t!pkg.os ||\n\t\t\t\tpkg.os.includes('linux') ||\n\t\t\t\t(pkg.os.every((os) => os.startsWith('!')) &&\n\t\t\t\t\t!pkg.os.includes('!linux'));\n\t\t\tif (linux && pkg.name && pkg.version && !(pkg.name in found)) {\n\t\t\t\tfound[pkg.name] = pkg.version;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tfor (const dep of Object.keys({\n\t\t\t...pkg.dependencies,\n\t\t\t...pkg.optionalDependencies,\n\t\t})) {\n\t\t\tconst location = locate(dep, dir);\n\t\t\tif (location && !seen.has(location)) queue.push(location);\n\t\t}\n\t}\n\n\treturn Object.fromEntries(\n\t\tObject.entries(found).sort(([a], [b]) => a.localeCompare(b)),\n\t);\n}\n\n/**\n * What a bundle leaves out, with the version of each to install: the native\n * packages found under `root`, and any it was asked to leave out besides,\n * at the version installed for the app.\n */\nexport function bundleExternals(\n\troot: string,\n\tdeclared: readonly string[],\n): ExternalPackages {\n\tconst externals = nativeDependencies(root);\n\tfor (const name of declared) {\n\t\tif (name in externals) continue;\n\t\tconst location = locate(name, root);\n\t\tconst version = location ? readPackage(location)?.version : undefined;\n\t\tif (!version) throw new ExternalNotInstalled(name, root);\n\t\texternals[name] = version;\n\t}\n\treturn Object.fromEntries(\n\t\tObject.entries(externals).sort(([a], [b]) => a.localeCompare(b)),\n\t);\n}\n\n/** The package a bare specifier names: `argon2/lib` → `argon2`, `@a/b/c` → `@a/b`. */\nfunction packageOf(specifier: string): string {\n\tconst parts = specifier.split('/');\n\treturn specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]!;\n}\n\n/**\n * The packages a bundle imports at runtime rather than inlining, read from\n * esbuild's metafile. Nothing when there is no metafile.\n */\nexport function importedPackages(metafile: string): Set<string> {\n\tlet meta: {\n\t\toutputs?: Record<\n\t\t\tstring,\n\t\t\t{ imports?: { path: string; external?: boolean }[] }\n\t\t>;\n\t};\n\ttry {\n\t\tmeta = JSON.parse(readFileSync(metafile, 'utf-8'));\n\t} catch {\n\t\treturn new Set();\n\t}\n\tconst imported = new Set<string>();\n\tfor (const output of Object.values(meta.outputs ?? {})) {\n\t\tfor (const { path, external } of output.imports ?? []) {\n\t\t\tif (external && !path.startsWith('.') && !path.startsWith('node:')) {\n\t\t\t\timported.add(packageOf(path));\n\t\t\t}\n\t\t}\n\t}\n\treturn imported;\n}\n","/**\n * What a stage's secrets are, independent of where they are kept: building\n * them, changing them, and handing them to a process. Where they are kept is a\n * {@link SecretsStore}'s business — see `secretsStoreFor`.\n */\n\nimport { isReservedStageKey } from '../compose/dnsConfig.js';\nimport type { SecretsStore } from './store.js';\nimport type { EmbeddableSecrets, StageSecrets } from './types';\n\n/**\n * Initialize an empty StageSecrets object for a stage.\n */\nexport function initStageSecrets(stage: string): StageSecrets {\n\tconst now = new Date().toISOString();\n\treturn {\n\t\tstage,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tservices: {},\n\t\turls: {},\n\t\tcustom: {},\n\t};\n}\n\n/**\n * Convert StageSecrets to embeddable format (flat key-value pairs).\n * This is what gets encrypted and embedded in the bundle.\n */\nexport function toEmbeddableSecrets(secrets: StageSecrets): EmbeddableSecrets {\n\treturn {\n\t\t...secrets.urls,\n\t\t// The server's address (`GKM_SERVER_*`) is gkm's own, never an app's.\n\t\t...Object.fromEntries(\n\t\t\tObject.entries(secrets.custom).filter(\n\t\t\t\t([key]) => !isReservedStageKey(key),\n\t\t\t),\n\t\t),\n\t\t// Also include individual service credentials if needed\n\t\t...(secrets.services.postgres && {\n\t\t\tPOSTGRES_USER: secrets.services.postgres.username,\n\t\t\tPOSTGRES_PASSWORD: secrets.services.postgres.password,\n\t\t\tPOSTGRES_DB: secrets.services.postgres.database ?? 'app',\n\t\t\tPOSTGRES_HOST: secrets.services.postgres.host,\n\t\t\tPOSTGRES_PORT: String(secrets.services.postgres.port),\n\t\t}),\n\t\t...(secrets.services.redis && {\n\t\t\tREDIS_PASSWORD: secrets.services.redis.password,\n\t\t\tREDIS_HOST: secrets.services.redis.host,\n\t\t\tREDIS_PORT: String(secrets.services.redis.port),\n\t\t}),\n\t\t...(secrets.services.minio && {\n\t\t\tSTORAGE_ACCESS_KEY_ID: secrets.services.minio.username,\n\t\t\tSTORAGE_SECRET_ACCESS_KEY: secrets.services.minio.password,\n\t\t\tSTORAGE_BUCKET: secrets.services.minio.bucket ?? 'app',\n\t\t\tSTORAGE_REGION: 'eu-west-1',\n\t\t\tSTORAGE_FORCE_PATH_STYLE: 'true',\n\t\t}),\n\t\t...(secrets.services.mailpit && {\n\t\t\tSMTP_HOST: secrets.services.mailpit.host,\n\t\t\tSMTP_PORT: String(secrets.services.mailpit.port),\n\t\t\tSMTP_USER: secrets.services.mailpit.username,\n\t\t\tSMTP_PASS: secrets.services.mailpit.password,\n\t\t\tSMTP_SECURE: 'false',\n\t\t\tMAIL_FROM: 'noreply@localhost',\n\t\t}),\n\t\t...(secrets.services.localstack && {\n\t\t\tAWS_ACCESS_KEY_ID:\n\t\t\t\tsecrets.services.localstack.accessKeyId ??\n\t\t\t\tsecrets.services.localstack.username,\n\t\t\tAWS_SECRET_ACCESS_KEY: secrets.services.localstack.password,\n\t\t\tAWS_REGION: secrets.services.localstack.region ?? 'us-east-1',\n\t\t\tAWS_ENDPOINT_URL: `http://${secrets.services.localstack.host}:${secrets.services.localstack.port}`,\n\t\t}),\n\t};\n}\n\n/** The same secrets with one custom value set, and `updatedAt` moved on. */\nexport function withCustomSecret(\n\tsecrets: StageSecrets,\n\tkey: string,\n\tvalue: string,\n): StageSecrets {\n\treturn {\n\t\t...secrets,\n\t\tupdatedAt: new Date().toISOString(),\n\t\tcustom: { ...secrets.custom, [key]: value },\n\t};\n}\n\n/**\n * Mask a password for display (show first 4 and last 2 chars).\n */\nexport function maskPassword(password: string): string {\n\tif (password.length <= 8) {\n\t\treturn '********';\n\t}\n\treturn `${password.slice(0, 4)}${'*'.repeat(password.length - 6)}${password.slice(-2)}`;\n}\n\n/**\n * Result of environment variable validation.\n */\nexport interface EnvValidationResult {\n\t/** Whether all required environment variables are present */\n\tvalid: boolean;\n\t/** List of missing environment variable names */\n\tmissing: string[];\n\t/** List of environment variables that are provided */\n\tprovided: string[];\n\t/** List of environment variables that were required */\n\trequired: string[];\n}\n\n/**\n * Validate that all required environment variables are present in secrets.\n *\n * @param requiredVars - Array of environment variable names required by the application\n * @param secrets - Stage secrets to validate against\n * @returns Validation result with missing and provided variables\n *\n * @example\n * ```typescript\n * const required = ['DATABASE_URL', 'API_KEY', 'JWT_SECRET'];\n * const secrets = await secretsStoreFor(workspace, 'production').then((s) => s.read('production'));\n * const result = validateEnvironmentVariables(required, secrets);\n *\n * if (!result.valid) {\n * console.error(`Missing environment variables: ${result.missing.join(', ')}`);\n * }\n * ```\n */\nexport function validateEnvironmentVariables(\n\trequiredVars: string[],\n\tsecrets: StageSecrets,\n): EnvValidationResult {\n\tconst embeddable = toEmbeddableSecrets(secrets);\n\tconst availableVars = new Set(Object.keys(embeddable));\n\n\tconst missing: string[] = [];\n\tconst provided: string[] = [];\n\n\tfor (const varName of requiredVars) {\n\t\tif (availableVars.has(varName)) {\n\t\t\tprovided.push(varName);\n\t\t} else {\n\t\t\tmissing.push(varName);\n\t\t}\n\t}\n\n\treturn {\n\t\tvalid: missing.length === 0,\n\t\tmissing: missing.sort(),\n\t\tprovided: provided.sort(),\n\t\trequired: [...requiredVars].sort(),\n\t};\n}\n","/**\n * Where a stage's secrets are kept.\n *\n * Every command that needs a stage's secrets — `gkm dev`, `test`, `deploy`,\n * `build`, `setup`, `secrets:*` — asks {@link secretsStoreFor} for that\n * stage's store and reads or writes it. None of them knows whether that is a\n * file on this machine, or S3, SSM or Secrets Manager in the stage's account: the local stage is\n * always the file, and a deployed stage is whatever `secrets.store` names.\n *\n * The same shape deploy state has (`StateProvider`): one interface, a backend\n * per place, and a custom object for any place this package does not ship.\n */\n\nimport type { NormalizedWorkspace } from '../workspace/types.js';\nimport { FileSecretsStore } from './file.js';\nimport { keystoreProject } from './keystore.js';\nimport { s3SecretsLocation, UnknownSecretsStoreProvider } from './providers.js';\nimport type { StageSecrets } from './types.js';\n\nexport interface SecretsStore {\n\t/**\n\t * Which kind of store this is — `'file'`, `'s3'`, `'ssm'`,\n\t * `'secrets-manager'`, or a custom one's.\n\t */\n\treadonly name: string;\n\t/** The stage's secrets, or null when it has none here. */\n\tread(stage: string): Promise<StageSecrets | null>;\n\t/** Replace the stage's secrets. */\n\twrite(stage: string, secrets: StageSecrets): Promise<void>;\n}\n\n/** Secrets in SSM Parameter Store, in the account of the active credentials. */\nexport interface SsmSecretsStoreConfig {\n\tprovider: 'ssm';\n\tregion: string;\n}\n\n/**\n * Secrets in AWS Secrets Manager, in the account of the active credentials:\n * one secret per stage, `gkm/<project>/<stage>/secrets`. Up to 64 KB where\n * SSM holds 8 KB, at a monthly price per secret.\n */\nexport interface SecretsManagerSecretsStoreConfig {\n\tprovider: 'secrets-manager';\n\tregion: string;\n\t/**\n\t * The KMS key (id, ARN or alias) a stage's secret is created with. Unset,\n\t * it is the account's AWS-managed `aws/secretsmanager` key.\n\t */\n\tkmsKeyId?: string;\n}\n\n/**\n * Secrets in S3, one object per stage —\n * `<prefix>/<project>/<stage>/secrets.json` — in the project bucket beside the\n * deploy state and backups, or in a bucket that exists. Encrypted with SSE-S3,\n * every past document kept by the bucket's versioning, and no size limit.\n */\nexport interface S3SecretsStoreConfig {\n\tprovider: 's3';\n\t/**\n\t * A bucket that already exists. Omitted, the project bucket —\n\t * `gkm-<project>-<account id>`, created by the first write.\n\t */\n\tbucket?: string;\n\t/** The bucket's region. Omitted, the deploy state's, when it is in S3. */\n\tregion?: string;\n\t/** Key prefix inside the bucket. Omitted, the S3 state's, else `gkm`. */\n\tprefix?: string;\n}\n\n/** Any other backend: an object implementing {@link SecretsStore}. */\nexport interface CustomSecretsStoreConfig {\n\tprovider: SecretsStore;\n}\n\n/**\n * `secrets.store` in gkm.config.ts.\n *\n * `'file'` — the default — keeps each stage's secrets in the encrypted\n * `.gkm/secrets/<stage>.json`, its key in the CLI's home (`GKM_HOME`, else\n * `~/.gkm`). It cannot serve a\n * deploy from CI while `.gkm/` is gitignored; `s3`, `ssm`, `secrets-manager`\n * or a custom store can.\n */\nexport type SecretsStoreConfig =\n\t| 'file'\n\t| S3SecretsStoreConfig\n\t| SsmSecretsStoreConfig\n\t| SecretsManagerSecretsStoreConfig\n\t| CustomSecretsStoreConfig;\n\nexport interface SecretsStoreOptions {\n\t/**\n\t * The AWS profile for the stage's account. Only that profile is used —\n\t * never AWS_* from the environment — so a store cannot quietly land in\n\t * whichever account the shell was exported for.\n\t */\n\tprofile?: string;\n\t/**\n\t * The CLI's home, where a file store's keys are kept. Defaults to\n\t * `GKM_HOME`, else `~/.gkm`.\n\t */\n\thome?: string;\n}\n\n/**\n * The store a stage's secrets are kept in — what every command reads and\n * writes, for the stage it acts on.\n *\n * The local stage is always the file: its secrets belong to the machine\n * running `gkm dev`. A deployed stage uses `secrets.store`.\n */\nexport async function secretsStoreFor(\n\tworkspace: NormalizedWorkspace,\n\tstage: string,\n\toptions: SecretsStoreOptions = {},\n): Promise<SecretsStore> {\n\tconst configured = workspace.secrets.store ?? 'file';\n\n\tif (stage === workspace.stages.local || configured === 'file') {\n\t\treturn new FileSecretsStore(\n\t\t\tworkspace.root,\n\t\t\tkeystoreProject(workspace, options.home),\n\t\t);\n\t}\n\n\treturn storeFromConfig(workspace, configured, options);\n}\n\n/**\n * The store a `secrets.store` value describes, for any stage — what\n * {@link secretsStoreFor} answers for a deployed stage, and what\n * `gkm secrets:migrate` builds for the store it copies to.\n */\nexport async function storeFromConfig(\n\tworkspace: NormalizedWorkspace,\n\tconfig: SecretsStoreConfig,\n\toptions: SecretsStoreOptions = {},\n): Promise<SecretsStore> {\n\tif (config === 'file') {\n\t\treturn new FileSecretsStore(\n\t\t\tworkspace.root,\n\t\t\tkeystoreProject(workspace, options.home),\n\t\t);\n\t}\n\n\tconst profile = options.profile ? { profile: options.profile } : {};\n\n\tswitch (config.provider) {\n\t\tcase 's3': {\n\t\t\tconst { S3SecretsStore } = await import('./s3.js');\n\t\t\tconst { deployIdentity } = await import('../deploy/identity.js');\n\t\t\tconst location = s3SecretsLocation(\n\t\t\t\tconfig as S3SecretsStoreConfig,\n\t\t\t\tworkspace.state,\n\t\t\t);\n\t\t\treturn new S3SecretsStore({\n\t\t\t\tproject: workspace.name,\n\t\t\t\tidentity: deployIdentity(workspace, ''),\n\t\t\t\tregion: location.region,\n\t\t\t\tprefix: location.prefix,\n\t\t\t\t...(location.bucket ? { bucket: location.bucket } : {}),\n\t\t\t\t...profile,\n\t\t\t});\n\t\t}\n\t\tcase 'ssm': {\n\t\t\tconst { AwsSecretsStore } = await import('./aws.js');\n\t\t\treturn new AwsSecretsStore({\n\t\t\t\tproject: workspace.name,\n\t\t\t\tregion: config.region,\n\t\t\t\t...profile,\n\t\t\t});\n\t\t}\n\t\tcase 'secrets-manager': {\n\t\t\tconst { kmsKeyId } = config as SecretsManagerSecretsStoreConfig;\n\t\t\tconst { SecretsManagerSecretsStore } = await import(\n\t\t\t\t'./secretsManager.js'\n\t\t\t);\n\t\t\treturn new SecretsManagerSecretsStore({\n\t\t\t\tproject: workspace.name,\n\t\t\t\tregion: config.region,\n\t\t\t\t...(kmsKeyId ? { kmsKeyId } : {}),\n\t\t\t\t...profile,\n\t\t\t});\n\t\t}\n\t\tdefault: {\n\t\t\t// Typed as a SecretsStore, but a config assembled by hand may name\n\t\t\t// a provider that is not one.\n\t\t\tconst provider: unknown = config.provider;\n\t\t\tif (typeof provider === 'object' && provider !== null) {\n\t\t\t\treturn provider as SecretsStore;\n\t\t\t}\n\t\t\tthrow new UnknownSecretsStoreProvider(provider);\n\t\t}\n\t}\n}\n\n/** Whether a stage's secrets live somewhere other than this machine. */\nexport function isRemoteStore(\n\tworkspace: NormalizedWorkspace,\n\tstage: string,\n): boolean {\n\tconst configured = workspace.secrets.store ?? 'file';\n\treturn stage !== workspace.stages.local && configured !== 'file';\n}\n\nexport { FileSecretsStore };\nexport {\n\tassertKnownSecretsStore,\n\tS3SecretsStoreNeedsRegion,\n\tSECRETS_STORE_PROVIDERS,\n\ttype SecretsStoreProvider,\n\ts3SecretsLocation,\n\tUnknownSecretsStoreProvider,\n} from './providers.js';\n","/**\n * Which backend each declared kind resolves to — decided by where the project\n * deploys, and by nothing else.\n *\n * These used to be read out of a `services:` block, where one key answered two\n * questions: *does this exist* and *what backs it*. The first is the manifest's\n * — a declared `Cache` is why there is a cache — and the second is the deploy\n * target's, because the right cache for a Lambda is not the right cache for a\n * box already running Postgres. With both answered elsewhere there was nothing\n * left for the block to say, so it is gone and these read the target.\n *\n * Mail has no answer here at all: every provider speaks SMTP, so the provider\n * is whichever one the stage's mail URL points at.\n */\n\nimport { runtimeOf, type TargetSource } from '../target/runtime.js';\nimport {\n\tDEFAULT_CACHE,\n\tDEFAULT_EVENTS,\n\tDEFAULT_STORAGE,\n\ttype EventsBackend,\n\ttype MainProvider,\n\ttype StorageBackend,\n\ttype TargetCacheBackend,\n} from '../types.js';\n\n/**\n * Which family of defaults a workspace's deploy target belongs to.\n *\n * One question, asked once: **does this target run containers the project\n * controls?** Dokploy does, so a bucket or a cache can live beside the app;\n * AWS, Vercel and Cloudflare do not, so the default has to be something\n * managed. That is the whole of the distinction, and it is why `MainProvider`\n * is the right axis rather than the deploy target's own name — targets share\n * answers.\n *\n * Each target declares its answer as its `runtime` — a target package in its\n * `package.json`, so this never loads one. A workspace that names no target\n * is on AWS: an SST project predates `deploy.default: 'sst'`.\n */\nexport function providerOf(workspace: TargetSource): MainProvider {\n\tconst target = workspace.deploy?.default;\n\treturn target ? runtimeOf(target, workspace) : 'aws';\n}\n\n/**\n * The cache backend a target implies.\n *\n * The same answer locally and deployed: a local `gkm dev` for an AWS app still\n * uses the Upstash protocol, because a backend that differed between the two\n * would be worse than a slower one.\n */\nexport function cacheBackendFor(on: MainProvider): TargetCacheBackend {\n\treturn DEFAULT_CACHE[on];\n}\n\n/** Where a declared bucket lives on a target. */\nexport function storageBackendFor(on: MainProvider): StorageBackend {\n\treturn DEFAULT_STORAGE[on];\n}\n\n/**\n * Which broker carries declared queues and topics on a target.\n *\n * Only consulted when something declares one; a project with no `Topic` or\n * `Queue` has no events at all, whatever the target.\n */\nexport function eventsBackendFor(on: MainProvider): EventsBackend {\n\treturn DEFAULT_EVENTS[on];\n}\n","/**\n * A file server's processors as a CDN origin: the names both sides agree on.\n *\n * On a compose stage whose bucket is on S3, the CDN serves the bucket and\n * sends each processor pattern to the stack's processor unit, at a host of\n * its own. That host is public — a CDN reaches its origin over the internet —\n * so the CDN adds a secret header and the edge refuses any request without\n * it. One definition, read by the CDN that sends the header and by the stack\n * whose edge checks it, so the two cannot drift.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport { provideKey } from '@geekmidas/manifest';\nimport { appKey } from '../workspace/derive.js';\n\n/** The header the CDN adds to every request it sends a processor. */\nexport const ORIGIN_VERIFY_HEADER = 'X-Gkm-Origin-Verify';\n\n/** Where a file server's processors answer the CDN: `<fileserver>-processors.<domain>`. */\nexport function processorOriginHost(serverId: string, domain: string): string {\n\treturn `${appKey(serverId)}-processors.${domain}`.toLowerCase();\n}\n\n/** The stage secret holding the header's value: `ASSETS_SERVER_ORIGIN_SECRET`. */\nexport function originSecretKey(serverId: string): string {\n\treturn provideKey(serverId, 'originSecret');\n}\n\n/**\n * What the processor unit reads that secret from. Set wherever the CDN fronts\n * it, so the unit refuses a request without the header itself — on Dokploy,\n * whose edge cannot match a header, the only check; behind the stack's own\n * edge, a second one.\n */\nexport const PROCESSOR_ORIGIN_SECRET_ENV = 'GKM_PROCESSOR_ORIGIN_SECRET';\n\n/** A new value for that secret: random, generated once, kept in the stage. */\nexport function newOriginSecret(): string {\n\treturn randomBytes(32).toString('base64url');\n}\n","/**\n * A stage's deploy state.\n *\n * Every target records the same core — when the stage was last deployed, by\n * which identity, and each app's releases — and a target that keeps ids of\n * its own adds them in a shape of its own, told apart by `provider`:\n *\n * - `dokploy`: the project, applications, services and credentials Dokploy\n * gave the stage, so a later deploy updates them rather than making more.\n * - `compose`: nothing beyond the core. A compose stage is one stack on one\n * server; what it created elsewhere (DNS records) is a resource record.\n */\n\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { output } from '../output';\nimport type { Actor } from './actor';\n\n/**\n * Per-app database credentials\n */\nexport interface AppDbCredentials {\n\tdbUser: string;\n\tdbPassword: string;\n}\n\n/**\n * DNS verification record for a hostname\n */\nexport interface DnsVerificationRecord {\n\tserverIp: string;\n\tverifiedAt: string;\n}\n\n/**\n * A DNS record that was created during deploy\n */\nexport interface CreatedDnsRecord {\n\t/** The domain this record belongs to (e.g., 'example.com') */\n\tdomain: string;\n\t/** Record name/subdomain (e.g., 'api' or '@' for root) */\n\tname: string;\n\t/** Record type (A, CNAME, etc.) */\n\ttype: string;\n\t/** Record value (IP address, hostname, etc.) */\n\tvalue: string;\n\t/** TTL in seconds */\n\tttl: number;\n\t/** When this record was created */\n\tcreatedAt: string;\n}\n\n/**\n * Backup destination state\n */\nexport interface BackupState {\n\t/** S3 bucket name for backups */\n\tbucketName: string;\n\t/** S3 bucket ARN */\n\tbucketArn: string;\n\t/** IAM user name created for backup access */\n\tiamUserName: string;\n\t/** IAM access key ID */\n\tiamAccessKeyId: string;\n\t/** IAM secret access key */\n\tiamSecretAccessKey: string;\n\t/** Dokploy destination ID */\n\tdestinationId: string;\n\t/** Dokploy backup schedule ID for postgres (if configured) */\n\tpostgresBackupId?: string;\n\t/** AWS region where bucket was created */\n\tregion: string;\n\t/** Timestamp when backup was configured */\n\tcreatedAt: string;\n}\n\n/** What every target's state for a stage holds. */\nexport interface StageStateCore {\n\tstage: string;\n\tlastDeployedAt: string;\n\t/**\n\t * The deploy identity's key (`<namespace>/<project>`) that last deployed\n\t * this stage — what the project's ownership marker says.\n\t */\n\tidentity?: string;\n\t/**\n\t * Each app's releases, keyed by app name: what runs now, what ran before\n\t * it — which `gkm deploy:rollback` restores — and the history behind both.\n\t */\n\treleases?: Record<string, AppReleases>;\n}\n\n/** A compose stage's state: the core, and nothing Dokploy-specific. */\nexport interface ComposeStageState extends StageStateCore {\n\tprovider: 'compose';\n}\n\n/**\n * State for a single stage deployment\n */\nexport interface DokployStageState extends StageStateCore {\n\tprovider: 'dokploy';\n\t/** Dokploy project ID - created on first deploy */\n\tprojectId: string;\n\tenvironmentId: string;\n\tapplications: Record<string, string>; // appName -> applicationId\n\tservices: {\n\t\tpostgresId?: string;\n\t\tredisId?: string;\n\t};\n\t/** Per-app database credentials for reuse on subsequent deploys */\n\tappCredentials?: Record<string, AppDbCredentials>;\n\t/** Auto-generated secrets per app (e.g., BETTER_AUTH_SECRET) */\n\tgeneratedSecrets?: Record<string, Record<string, string>>;\n\t/** DNS verification state per hostname */\n\tdnsVerified?: Record<string, DnsVerificationRecord>;\n\t/** DNS records created during deploy (keyed by \"name:type\", e.g., \"api:A\") */\n\tdnsRecords?: Record<string, CreatedDnsRecord>;\n\t/** Backup destination state */\n\tbackups?: BackupState;\n\t/**\n\t * The Dokploy registry the stage's images are pulled through. Kept per\n\t * stage rather than once per machine, so a stage keeps the registry it was\n\t * deployed with whoever deploys it next.\n\t */\n\tregistryId?: string;\n}\n\n/** A stage's state, whichever target wrote it. */\nexport type StageState = DokployStageState | ComposeStageState;\n\n/** An image a stage runs: the ref it was pushed as, and what it resolved to. */\nexport interface DeployedImage {\n\tref: string;\n\t/**\n\t * The tag it was released under — a site's carries its stage\n\t * (`v1.4.0-production`). Recorded by targets that pull a release by tag.\n\t */\n\ttag?: string;\n\t/** The registry's digest, `sha256:…` — absent if it could not be read. */\n\tdigest?: string;\n}\n\n/**\n * Get the state file path for a stage\n */\nfunction getStateFilePath(workspaceRoot: string, stage: string): string {\n\treturn join(workspaceRoot, '.gkm', `deploy-${stage}.json`);\n}\n\n/**\n * Read the deploy state for a stage\n * Returns null if state file doesn't exist\n */\nexport async function readStageState(\n\tworkspaceRoot: string,\n\tstage: string,\n): Promise<StageState | null> {\n\tconst filePath = getStateFilePath(workspaceRoot, stage);\n\n\ttry {\n\t\tconst content = await readFile(filePath, 'utf-8');\n\t\treturn JSON.parse(content) as StageState;\n\t} catch (error) {\n\t\t// File doesn't exist or is invalid - return null\n\t\tif ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n\t\t\treturn null;\n\t\t}\n\t\t// Log other errors but don't fail\n\t\toutput.warn(`Warning: Could not read deploy state: ${error}`);\n\t\treturn null;\n\t}\n}\n\n/**\n * Write the deploy state for a stage\n */\nexport async function writeStageState(\n\tworkspaceRoot: string,\n\tstage: string,\n\tstate: StageState,\n): Promise<void> {\n\tconst filePath = getStateFilePath(workspaceRoot, stage);\n\tconst dir = join(workspaceRoot, '.gkm');\n\n\t// Ensure .gkm directory exists\n\tawait mkdir(dir, { recursive: true });\n\n\t// Update last deployed timestamp\n\tstate.lastDeployedAt = new Date().toISOString();\n\n\tawait writeFile(filePath, JSON.stringify(state, null, 2));\n}\n\n/**\n * Create a new empty state for a stage\n */\nexport function createEmptyState(\n\tstage: string,\n\tprojectId: string,\n\tenvironmentId: string,\n): DokployStageState {\n\treturn {\n\t\tprovider: 'dokploy',\n\t\tstage,\n\t\tprojectId,\n\t\tenvironmentId,\n\t\tapplications: {},\n\t\tservices: {},\n\t\tlastDeployedAt: new Date().toISOString(),\n\t};\n}\n\n/** A new compose stage's state. */\nexport function createComposeState(stage: string): ComposeStageState {\n\treturn {\n\t\tprovider: 'compose',\n\t\tstage,\n\t\tlastDeployedAt: new Date().toISOString(),\n\t};\n}\n\n/**\n * `state` as the Dokploy target keeps it. A stage whose state another target\n * wrote — one moved from compose to Dokploy — keeps its core (releases,\n * identity) and starts with no Dokploy ids, as a first deploy would.\n */\nexport function asDokployState(state: StageState): DokployStageState {\n\tif (state.provider === 'dokploy') return state;\n\tconst { provider: _provider, ...core } = state;\n\treturn {\n\t\t...core,\n\t\tprovider: 'dokploy',\n\t\tprojectId: '',\n\t\tenvironmentId: '',\n\t\tapplications: {},\n\t\tservices: {},\n\t};\n}\n\n/**\n * Get application ID from state\n */\nexport function getApplicationId(\n\tstate: DokployStageState | null,\n\tappName: string,\n): string | undefined {\n\treturn state?.applications[appName];\n}\n\n/**\n * Set application ID in state (mutates state)\n */\nexport function setApplicationId(\n\tstate: DokployStageState,\n\tappName: string,\n\tapplicationId: string,\n): void {\n\tstate.applications[appName] = applicationId;\n}\n\n/** An image that went live, and when. */\nexport interface ReleasedImage extends DeployedImage {\n\t/** The image tag the deploy released under. */\n\ttag?: string;\n\treleasedAt: string;\n\t/** Who released it — absent on a release recorded before it was kept. */\n\treleasedBy?: Actor;\n\t/** Set when a rollback replaced it: it is never rolled back *to*. */\n\trolledBack?: true;\n}\n\n/** An app's releases: what runs, what ran before it, and what ran before that. */\nexport interface AppReleases {\n\tcurrent: ReleasedImage;\n\t/** What a rollback restores; absent until a second release. */\n\tprevious?: ReleasedImage;\n\t/** Every release, newest first, at most {@link RELEASE_HISTORY} of them. */\n\thistory: ReleasedImage[];\n}\n\n/** How many releases an app's history keeps. */\nexport const RELEASE_HISTORY = 10;\n\n/** Two records naming the same image: by digest when both have one. */\nfunction sameImage(a: DeployedImage, b: DeployedImage): boolean {\n\treturn a.digest && b.digest ? a.digest === b.digest : a.ref === b.ref;\n}\n\n/** The newest release in `history` after `index` that a rollback may restore. */\nfunction restorable(\n\thistory: readonly ReleasedImage[],\n\tindex: number,\n\tcurrent: DeployedImage,\n): ReleasedImage | undefined {\n\treturn history\n\t\t.slice(index + 1)\n\t\t.find((entry) => !entry.rolledBack && !sameImage(entry, current));\n}\n\n/**\n * Record that `image` went live for `appName` (mutates state): it becomes\n * `current`, and what was current becomes `previous`. Releasing what already\n * runs — a redeploy of the same digest — changes nothing.\n */\nexport function recordRelease(\n\tstate: StageStateCore,\n\tappName: string,\n\timage: Omit<ReleasedImage, 'releasedAt' | 'releasedBy' | 'rolledBack'>,\n\tby: Actor,\n\treleasedAt: Date = new Date(),\n): void {\n\tconst releases = state.releases?.[appName];\n\tif (releases && sameImage(releases.current, image)) return;\n\n\tconst entry: ReleasedImage = {\n\t\t...image,\n\t\treleasedAt: releasedAt.toISOString(),\n\t\treleasedBy: by,\n\t};\n\tconst history = [entry, ...(releases?.history ?? [])].slice(\n\t\t0,\n\t\tRELEASE_HISTORY,\n\t);\n\tconst previous = releases?.current;\n\tstate.releases = {\n\t\t...state.releases,\n\t\t[appName]: { current: entry, ...(previous ? { previous } : {}), history },\n\t};\n}\n\n/**\n * Record that `appName` was rolled back to `to` (mutates state): every\n * release newer than it is marked rolled back, so neither this rollback nor\n * a later one restores it, and `previous` moves to the release before `to`.\n */\nexport function recordRollback(\n\tstate: StageStateCore,\n\tappName: string,\n\tto: DeployedImage,\n): void {\n\tconst releases = state.releases?.[appName];\n\tif (!releases) return;\n\n\tconst index = releases.history.findIndex(\n\t\t(entry) => !entry.rolledBack && sameImage(entry, to),\n\t);\n\tif (index === -1) return;\n\n\tconst history = releases.history.map((entry, i) =>\n\t\ti < index ? { ...entry, rolledBack: true as const } : entry,\n\t);\n\tconst current = history[index]!;\n\tconst previous = restorable(history, index, current);\n\tstate.releases = {\n\t\t...state.releases,\n\t\t[appName]: { current, ...(previous ? { previous } : {}), history },\n\t};\n}\n\n/**\n * Get postgres ID from state\n */\nexport function getPostgresId(\n\tstate: DokployStageState | null,\n): string | undefined {\n\treturn state?.services.postgresId;\n}\n\n/**\n * Set postgres ID in state (mutates state)\n */\nexport function setPostgresId(\n\tstate: DokployStageState,\n\tpostgresId: string,\n): void {\n\tstate.services.postgresId = postgresId;\n}\n\n/**\n * Get redis ID from state\n */\nexport function getRedisId(\n\tstate: DokployStageState | null,\n): string | undefined {\n\treturn state?.services.redisId;\n}\n\n/**\n * Set redis ID in state (mutates state)\n */\nexport function setRedisId(state: DokployStageState, redisId: string): void {\n\tstate.services.redisId = redisId;\n}\n\n/**\n * Get app credentials from state\n */\nexport function getAppCredentials(\n\tstate: DokployStageState | null,\n\tappName: string,\n): AppDbCredentials | undefined {\n\treturn state?.appCredentials?.[appName];\n}\n\n/**\n * Set app credentials in state (mutates state)\n */\nexport function setAppCredentials(\n\tstate: DokployStageState,\n\tappName: string,\n\tcredentials: AppDbCredentials,\n): void {\n\tif (!state.appCredentials) {\n\t\tstate.appCredentials = {};\n\t}\n\tstate.appCredentials[appName] = credentials;\n}\n\n/**\n * Get all app credentials from state\n */\nexport function getAllAppCredentials(\n\tstate: DokployStageState | null,\n): Record<string, AppDbCredentials> {\n\treturn state?.appCredentials ?? {};\n}\n\n// ============================================================================\n// Generated Secrets\n// ============================================================================\n\n/**\n * Get a generated secret for an app\n */\nexport function getGeneratedSecret(\n\tstate: DokployStageState | null,\n\tappName: string,\n\tsecretName: string,\n): string | undefined {\n\treturn state?.generatedSecrets?.[appName]?.[secretName];\n}\n\n/**\n * Set a generated secret for an app (mutates state)\n */\nexport function setGeneratedSecret(\n\tstate: DokployStageState,\n\tappName: string,\n\tsecretName: string,\n\tvalue: string,\n): void {\n\tif (!state.generatedSecrets) {\n\t\tstate.generatedSecrets = {};\n\t}\n\tif (!state.generatedSecrets[appName]) {\n\t\tstate.generatedSecrets[appName] = {};\n\t}\n\tstate.generatedSecrets[appName][secretName] = value;\n}\n\n/**\n * Get all generated secrets for an app\n */\nexport function getAppGeneratedSecrets(\n\tstate: DokployStageState | null,\n\tappName: string,\n): Record<string, string> {\n\treturn state?.generatedSecrets?.[appName] ?? {};\n}\n\n/**\n * Get all generated secrets from state\n */\nexport function getAllGeneratedSecrets(\n\tstate: DokployStageState | null,\n): Record<string, Record<string, string>> {\n\treturn state?.generatedSecrets ?? {};\n}\n\n// ============================================================================\n// DNS Verification\n// ============================================================================\n\n/**\n * Get DNS verification record for a hostname\n */\nexport function getDnsVerification(\n\tstate: DokployStageState | null,\n\thostname: string,\n): DnsVerificationRecord | undefined {\n\treturn state?.dnsVerified?.[hostname];\n}\n\n/**\n * Set DNS verification record for a hostname (mutates state)\n */\nexport function setDnsVerification(\n\tstate: DokployStageState,\n\thostname: string,\n\tserverIp: string,\n): void {\n\tif (!state.dnsVerified) {\n\t\tstate.dnsVerified = {};\n\t}\n\tstate.dnsVerified[hostname] = {\n\t\tserverIp,\n\t\tverifiedAt: new Date().toISOString(),\n\t};\n}\n\n/**\n * Check if a hostname is already verified with the given IP\n */\nexport function isDnsVerified(\n\tstate: DokployStageState | null,\n\thostname: string,\n\tserverIp: string,\n): boolean {\n\tconst record = state?.dnsVerified?.[hostname];\n\treturn record?.serverIp === serverIp;\n}\n\n/**\n * Get all DNS verification records from state\n */\nexport function getAllDnsVerifications(\n\tstate: DokployStageState | null,\n): Record<string, DnsVerificationRecord> {\n\treturn state?.dnsVerified ?? {};\n}\n\n// ============================================================================\n// DNS Records\n// ============================================================================\n\n/**\n * Get the key for a DNS record in state\n */\nfunction getDnsRecordKey(name: string, type: string): string {\n\treturn `${name}:${type}`;\n}\n\n/**\n * Get a created DNS record from state\n */\nexport function getDnsRecord(\n\tstate: DokployStageState | null,\n\tname: string,\n\ttype: string,\n): CreatedDnsRecord | undefined {\n\treturn state?.dnsRecords?.[getDnsRecordKey(name, type)];\n}\n\n/**\n * Set a created DNS record in state (mutates state)\n */\nexport function setDnsRecord(\n\tstate: DokployStageState,\n\trecord: Omit<CreatedDnsRecord, 'createdAt'>,\n): void {\n\tif (!state.dnsRecords) {\n\t\tstate.dnsRecords = {};\n\t}\n\tconst key = getDnsRecordKey(record.name, record.type);\n\tstate.dnsRecords[key] = {\n\t\t...record,\n\t\tcreatedAt: new Date().toISOString(),\n\t};\n}\n\n/**\n * Remove a DNS record from state (mutates state)\n */\nexport function removeDnsRecord(\n\tstate: DokployStageState,\n\tname: string,\n\ttype: string,\n): void {\n\tif (state.dnsRecords) {\n\t\tdelete state.dnsRecords[getDnsRecordKey(name, type)];\n\t}\n}\n\n/**\n * Get all created DNS records from state\n */\nexport function getAllDnsRecords(\n\tstate: DokployStageState | null,\n): CreatedDnsRecord[] {\n\tif (!state?.dnsRecords) {\n\t\treturn [];\n\t}\n\treturn Object.values(state.dnsRecords);\n}\n\n/**\n * Clear all DNS records from state (mutates state)\n */\nexport function clearDnsRecords(state: DokployStageState): void {\n\tstate.dnsRecords = {};\n\tstate.dnsVerified = {};\n}\n\n// ============================================================================\n// Backup State\n// ============================================================================\n\n/**\n * Get backup state from state\n */\nexport function getBackupState(\n\tstate: DokployStageState | null,\n): BackupState | undefined {\n\treturn state?.backups;\n}\n\n/**\n * Set backup state (mutates state)\n */\nexport function setBackupState(\n\tstate: DokployStageState,\n\tbackupState: BackupState,\n): void {\n\tstate.backups = backupState;\n}\n\n/**\n * Get backup destination ID from state\n */\nexport function getBackupDestinationId(\n\tstate: DokployStageState | null,\n): string | undefined {\n\treturn state?.backups?.destinationId;\n}\n\n/**\n * Get postgres backup ID from state\n */\nexport function getPostgresBackupId(\n\tstate: DokployStageState | null,\n): string | undefined {\n\treturn state?.backups?.postgresBackupId;\n}\n\n/**\n * Set postgres backup ID in state (mutates state)\n */\nexport function setPostgresBackupId(\n\tstate: DokployStageState,\n\tbackupId: string,\n): void {\n\tif (state.backups) {\n\t\tstate.backups.postgresBackupId = backupId;\n\t}\n}\n","/**\n * DNS Provider Interface\n *\n * Abstracts DNS operations for different providers.\n * Built-in providers: HostingerProvider, Route53Provider, GoDaddyProvider\n * Users can also supply custom implementations.\n *\n * Every value is the record's zone-file form, read and written alike: an MX\n * record's is `<priority> <host>` (see {@link mxValue}).\n */\n\nimport type { z } from 'zod/v4';\nimport { GkmError } from '../../../errors';\nimport type {\n\tCloudflareDnsProviderSchema,\n\tCustomDnsProviderSchema,\n\tDnsProviderSchema,\n\tDnsRecordSchema,\n\tDnsRecordTypeSchema,\n\tGoDaddyDnsProviderSchema,\n\tHostingerDnsProviderSchema,\n\tManualDnsProviderSchema,\n\tRoute53DnsProviderSchema,\n\tUpsertDnsRecordSchema,\n\tUpsertResultSchema,\n} from '../../../workspace/schema';\n\n// =============================================================================\n// DNS Record Types (derived from Zod schemas)\n// =============================================================================\n\n/**\n * DNS record types supported across providers.\n */\nexport type DnsRecordType = z.infer<typeof DnsRecordTypeSchema>;\n\n/**\n * A DNS record as returned by the provider.\n */\nexport type DnsRecord = z.infer<typeof DnsRecordSchema>;\n\n/**\n * A DNS record to create or update.\n */\nexport type UpsertDnsRecord = z.infer<typeof UpsertDnsRecordSchema>;\n\n/**\n * Result of an upsert operation.\n */\nexport type UpsertResult = z.infer<typeof UpsertResultSchema>;\n\n// =============================================================================\n// MX values\n// =============================================================================\n\n/**\n * An MX record's value as every provider here reads and writes it — the zone\n * file's `<priority> <host>`, which is what Route53 and Hostinger take as is.\n * A provider whose API keeps the priority apart (GoDaddy) splits it with\n * {@link parseMxValue}.\n */\nexport function mxValue(priority: number, host: string): string {\n\treturn `${priority} ${host.trim().replace(/\\.$/, '')}`;\n}\n\n/** An MX value that is not `<priority> <host>`. */\nexport class MxValueInvalid extends GkmError {\n\tconstructor(readonly value: string) {\n\t\tsuper(\n\t\t\t`'${value}' is not an MX record's value: it is written ` +\n\t\t\t\t\"'<priority> <host>', like '10 inbound-smtp.eu-west-1.amazonaws.com'. \" +\n\t\t\t\t'Build it with mxValue(priority, host).',\n\t\t);\n\t\tthis.name = 'MxValueInvalid';\n\t}\n}\n\n/**\n * The priority and host of an MX value.\n *\n * @throws {MxValueInvalid} for a value that is not `<priority> <host>`\n */\nexport function parseMxValue(value: string): {\n\tpriority: number;\n\thost: string;\n} {\n\tconst match = value.trim().match(/^(\\d{1,5})\\s+(\\S+)$/);\n\tconst priority = match ? Number(match[1]) : Number.NaN;\n\tif (!match || priority > 65535) throw new MxValueInvalid(value);\n\treturn { priority, host: match[2]!.replace(/\\.$/, '') };\n}\n\n// =============================================================================\n// DNS Provider Interface\n// =============================================================================\n\n/**\n * A record to delete from DNS.\n */\nexport interface DeleteDnsRecord {\n\t/** Record name/subdomain (e.g., 'api' or '@' for root) */\n\tname: string;\n\t/** Record type (A, CNAME, etc.) */\n\ttype: DnsRecordType;\n}\n\n/**\n * Result of a delete operation.\n */\nexport interface DeleteResult {\n\t/** The record that was requested for deletion */\n\trecord: DeleteDnsRecord;\n\t/** Whether the record was deleted */\n\tdeleted: boolean;\n\t/** Whether the record was not found (already deleted) */\n\tnotFound: boolean;\n\t/** Error message if deletion failed */\n\terror?: string;\n}\n\n/**\n * Interface for DNS providers.\n *\n * Implementations must handle:\n * - Getting all records for a domain\n * - Creating or updating records for a domain\n * - Deleting records from a domain\n */\nexport interface DnsProvider {\n\t/** Provider name for logging */\n\treadonly name: string;\n\n\t/**\n\t * Get all DNS records for a domain.\n\t *\n\t * @param domain - Root domain (e.g., 'example.com')\n\t * @returns Array of DNS records\n\t */\n\tgetRecords(domain: string): Promise<DnsRecord[]>;\n\n\t/**\n\t * The records of exactly these names and types, where the provider can\n\t * read them one at a time — cheaper than the whole zone on an API that\n\t * counts requests. Optional: without it, `getRecords` is filtered.\n\t * Throws {@link DnsRecordsUnreadable} when the credentials can only write.\n\t *\n\t * @param domain - Root domain (e.g., 'example.com')\n\t * @param wanted - The names ('@' for the root) and types to read\n\t */\n\treadRecords?(\n\t\tdomain: string,\n\t\twanted: readonly DeleteDnsRecord[],\n\t): Promise<DnsRecord[]>;\n\n\t/**\n\t * Create or update DNS records.\n\t *\n\t * @param domain - Root domain (e.g., 'example.com')\n\t * @param records - Records to create or update\n\t * @returns Results of the upsert operations\n\t */\n\tupsertRecords(\n\t\tdomain: string,\n\t\trecords: UpsertDnsRecord[],\n\t): Promise<UpsertResult[]>;\n\n\t/**\n\t * Delete DNS records.\n\t *\n\t * @param domain - Root domain (e.g., 'example.com')\n\t * @param records - Records to delete\n\t * @returns Results of the delete operations\n\t */\n\tdeleteRecords(\n\t\tdomain: string,\n\t\trecords: DeleteDnsRecord[],\n\t): Promise<DeleteResult[]>;\n}\n\n// =============================================================================\n// DNS Provider Config Types (derived from Zod schemas)\n// =============================================================================\n\nexport type HostingerDnsConfig = z.infer<typeof HostingerDnsProviderSchema>;\nexport type Route53DnsConfig = z.infer<typeof Route53DnsProviderSchema>;\nexport type GoDaddyDnsConfig = z.infer<typeof GoDaddyDnsProviderSchema>;\nexport type CloudflareDnsConfig = z.infer<typeof CloudflareDnsProviderSchema>;\nexport type ManualDnsConfig = z.infer<typeof ManualDnsProviderSchema>;\nexport type CustomDnsConfig = z.infer<typeof CustomDnsProviderSchema>;\n/** Single DNS provider config (for one domain) */\nexport type DnsConfig = z.infer<typeof DnsProviderSchema>;\n\n// =============================================================================\n// DNS Provider Factory\n// =============================================================================\n\n/**\n * Check if value is a DnsProvider implementation.\n */\nexport function isDnsProvider(value: unknown): value is DnsProvider {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\ttypeof (value as DnsProvider).name === 'string' &&\n\t\ttypeof (value as DnsProvider).getRecords === 'function' &&\n\t\ttypeof (value as DnsProvider).upsertRecords === 'function' &&\n\t\ttypeof (value as DnsProvider).deleteRecords === 'function'\n\t);\n}\n\nexport interface CreateDnsProviderOptions {\n\t/** DNS config from workspace */\n\tconfig: DnsConfig;\n\t/** Where the GoDaddy provider reads its key — the environment and the CLI's home. */\n\tgodaddy?: import('./GoDaddyProvider').GoDaddyProviderOptions;\n\t/** The Hostinger token, when the caller already has it. */\n\thostinger?: import('../../../deploy/credentials').HostingerCredential;\n}\n\n/**\n * Create a DNS provider based on configuration.\n *\n * - 'hostinger': HostingerProvider\n * - 'route53': Route53Provider\n * - 'godaddy': GoDaddyProvider\n * - 'manual': Returns null (user handles DNS)\n * - Custom: Use provided DnsProvider implementation\n */\nexport async function createDnsProvider(\n\toptions: CreateDnsProviderOptions,\n): Promise<DnsProvider | null> {\n\tconst { config } = options;\n\n\t// Manual mode - no provider needed\n\tif (config.provider === 'manual') {\n\t\treturn null;\n\t}\n\n\t// Custom provider implementation\n\tif (isDnsProvider(config.provider)) {\n\t\treturn config.provider;\n\t}\n\n\t// Built-in providers\n\tconst provider = config.provider;\n\n\tif (provider === 'hostinger') {\n\t\tconst { HostingerProvider } = await import('./HostingerProvider');\n\t\treturn new HostingerProvider(options.hostinger);\n\t}\n\n\tif (provider === 'route53') {\n\t\tconst { Route53Provider } = await import('./Route53Provider');\n\t\tconst route53Config = config as Route53DnsConfig;\n\t\treturn new Route53Provider({\n\t\t\tregion: route53Config.region,\n\t\t\tprofile: route53Config.profile,\n\t\t\thostedZoneId: route53Config.hostedZoneId,\n\t\t});\n\t}\n\n\tif (provider === 'godaddy') {\n\t\tconst { GoDaddyProvider } = await import('./GoDaddyProvider');\n\t\treturn new GoDaddyProvider(options.godaddy ?? {});\n\t}\n\n\tif (provider === 'cloudflare') {\n\t\tthrow new DnsProviderNotImplemented('cloudflare');\n\t}\n\n\tthrow new DnsProviderUnknown(config);\n}\n\n/**\n * The provider's credentials can write records and not read them — a key\n * scoped to updates only. What reads them falls back to writing every record,\n * which is idempotent, without a diff.\n */\nexport class DnsRecordsUnreadable extends GkmError {\n\tconstructor(\n\t\treadonly provider: string,\n\t\treadonly domain: string,\n\t\treadonly reason: string,\n\t) {\n\t\tsuper(\n\t\t\t`The ${provider} key cannot read ${domain}'s DNS records (${reason}), so ` +\n\t\t\t\t'changes cannot be compared with what is there: every record is ' +\n\t\t\t\t'written, which leaves one that already has its value as it was.',\n\t\t);\n\t\tthis.name = 'DnsRecordsUnreadable';\n\t}\n}\n\n/** A DNS provider gkm names and does not have yet. */\nexport class DnsProviderNotImplemented extends Error {\n\tconstructor(readonly provider: string) {\n\t\tsuper(\n\t\t\t`The ${provider} DNS provider is not implemented yet. Use 'route53', ` +\n\t\t\t\t\"'godaddy', 'hostinger' or 'manual' for this domain in dns, or \" +\n\t\t\t\t'pass your own DnsProvider object.',\n\t\t);\n\t\tthis.name = 'DnsProviderNotImplemented';\n\t}\n}\n\n/** A `provider:` that is none of the built-ins, nor a DnsProvider object. */\nexport class DnsProviderUnknown extends GkmError {\n\tconstructor(readonly config: unknown) {\n\t\tsuper(\n\t\t\t`Unknown DNS provider: ${JSON.stringify(config)}. dns takes ` +\n\t\t\t\t\"'route53', 'godaddy', 'hostinger', 'manual', or an object implementing DnsProvider.\",\n\t\t);\n\t\tthis.name = 'DnsProviderUnknown';\n\t}\n}\n","/**\n * DNS orchestration for deployments\n *\n * Handles automatic DNS record creation for deployed applications.\n */\n\nimport { lookup } from 'node:dns/promises';\nimport {\n\ttype DokployStageState,\n\tisDnsVerified,\n\tsetDnsRecord,\n\tsetDnsVerification,\n} from '../../../deploy/state';\nimport { output } from '../../../output';\nimport type {\n\tDnsConfig,\n\tDnsProvider as DnsProviderConfig,\n} from '../../../workspace/types';\nimport {\n\tcreateDnsProvider,\n\ttype DnsProvider,\n\ttype DnsConfig as SchemaDnsConfig,\n\ttype UpsertDnsRecord,\n} from './DnsProvider';\n\nconst logger = output;\n\n/**\n * Check if DNS config is legacy format (single domain with `domain` property)\n */\nexport function isLegacyDnsConfig(\n\tconfig: DnsConfig,\n): config is SchemaDnsConfig & { domain: string } {\n\treturn (\n\t\ttypeof config === 'object' &&\n\t\tconfig !== null &&\n\t\t'provider' in config &&\n\t\t'domain' in config\n\t);\n}\n\n/**\n * Normalize DNS config to new multi-domain format\n */\nexport function normalizeDnsConfig(\n\tconfig: DnsConfig,\n): Record<string, DnsProviderConfig> {\n\tif (isLegacyDnsConfig(config)) {\n\t\t// Convert legacy format to new format\n\t\tconst { domain, ...providerConfig } = config;\n\t\treturn { [domain]: providerConfig as DnsProviderConfig };\n\t}\n\treturn config as Record<string, DnsProviderConfig>;\n}\n\n/**\n * Find the root domain for a hostname from available DNS configs\n *\n * @example\n * findRootDomain('api.geekmidas.com', { 'geekmidas.com': {...}, 'geekmidas.dev': {...} })\n * // Returns 'geekmidas.com'\n */\nexport function findRootDomain(\n\thostname: string,\n\tdnsConfig: Record<string, DnsProviderConfig>,\n): string | null {\n\t// Sort domains by length descending to match most specific first\n\tconst domains = Object.keys(dnsConfig).sort((a, b) => b.length - a.length);\n\n\tfor (const domain of domains) {\n\t\tif (hostname === domain || hostname.endsWith(`.${domain}`)) {\n\t\t\treturn domain;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n/**\n * Group hostnames by their root domain\n */\nexport function groupHostnamesByDomain(\n\tappHostnames: Map<string, string>,\n\tdnsConfig: Record<string, DnsProviderConfig>,\n): Map<string, Map<string, string>> {\n\tconst grouped = new Map<string, Map<string, string>>();\n\n\tfor (const [appName, hostname] of appHostnames) {\n\t\tconst rootDomain = findRootDomain(hostname, dnsConfig);\n\t\tif (!rootDomain) {\n\t\t\tlogger.log(` ⚠ No DNS config found for hostname: ${hostname}`);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!grouped.has(rootDomain)) {\n\t\t\tgrouped.set(rootDomain, new Map());\n\t\t}\n\t\tgrouped.get(rootDomain)!.set(appName, hostname);\n\t}\n\n\treturn grouped;\n}\n\n/**\n * Required DNS record for an app\n */\nexport interface RequiredDnsRecord {\n\t/** Full hostname (e.g., 'api.joemoer.traflabs.io') */\n\thostname: string;\n\t/** Subdomain part for the DNS provider (e.g., 'api.joemoer') */\n\tsubdomain: string;\n\t/** Record type */\n\ttype: 'A' | 'CNAME';\n\t/** Target value (IP or hostname) */\n\tvalue: string;\n\t/** App name */\n\tappName: string;\n\t/** Whether the record was created */\n\tcreated?: boolean;\n\t/** Whether the record already existed */\n\texisted?: boolean;\n\t/** Error if creation failed */\n\terror?: string;\n}\n\n/**\n * Result of DNS record creation\n */\nexport interface DnsCreationResult {\n\trecords: RequiredDnsRecord[];\n\tsuccess: boolean;\n\tserverIp: string;\n}\n\n/**\n * Resolve IP address from a hostname\n */\nexport async function resolveHostnameToIp(hostname: string): Promise<string> {\n\ttry {\n\t\tconst addresses = await lookup(hostname, { family: 4 });\n\t\treturn addresses.address;\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Failed to resolve IP for ${hostname}: ${error instanceof Error ? error.message : 'Unknown error'}`,\n\t\t);\n\t}\n}\n\n/**\n * Extract subdomain from full hostname relative to root domain\n *\n * @example\n * extractSubdomain('api.joemoer.traflabs.io', 'traflabs.io') => 'api.joemoer'\n * extractSubdomain('joemoer.traflabs.io', 'traflabs.io') => 'joemoer'\n */\nexport function extractSubdomain(hostname: string, rootDomain: string): string {\n\tif (!hostname.endsWith(rootDomain)) {\n\t\tthrow new Error(\n\t\t\t`Hostname ${hostname} is not under root domain ${rootDomain}`,\n\t\t);\n\t}\n\n\tconst subdomain = hostname.slice(0, -(rootDomain.length + 1)); // +1 for the dot\n\treturn subdomain || '@'; // '@' represents the root domain itself\n}\n\n/**\n * Generate required DNS records for a deployment\n */\nexport function generateRequiredRecords(\n\tappHostnames: Map<string, string>, // appName -> hostname\n\trootDomain: string,\n\tserverIp: string,\n): RequiredDnsRecord[] {\n\tconst records: RequiredDnsRecord[] = [];\n\n\tfor (const [appName, hostname] of appHostnames) {\n\t\tconst subdomain = extractSubdomain(hostname, rootDomain);\n\t\trecords.push({\n\t\t\thostname,\n\t\t\tsubdomain,\n\t\t\ttype: 'A',\n\t\t\tvalue: serverIp,\n\t\t\tappName,\n\t\t});\n\t}\n\n\treturn records;\n}\n\n/**\n * Print DNS records table\n */\nexport function printDnsRecordsTable(\n\trecords: RequiredDnsRecord[],\n\trootDomain: string,\n): void {\n\tlogger.log(`\\n 📋 DNS Records for ${rootDomain}:`);\n\tlogger.log(\n\t\t' ┌─────────────────────────────────────┬──────┬─────────────────┬────────┐',\n\t);\n\tlogger.log(\n\t\t' │ Subdomain │ Type │ Value │ Status │',\n\t);\n\tlogger.log(\n\t\t' ├─────────────────────────────────────┼──────┼─────────────────┼────────┤',\n\t);\n\n\tfor (const record of records) {\n\t\tconst subdomain = record.subdomain.padEnd(35);\n\t\tconst type = record.type.padEnd(4);\n\t\tconst value = record.value.padEnd(15);\n\t\tlet status: string;\n\n\t\tif (record.error) {\n\t\t\tstatus = '✗';\n\t\t} else if (record.created) {\n\t\t\tstatus = '✓ new';\n\t\t} else if (record.existed) {\n\t\t\tstatus = '✓';\n\t\t} else {\n\t\t\tstatus = '?';\n\t\t}\n\n\t\tlogger.log(\n\t\t\t` │ ${subdomain} │ ${type} │ ${value} │ ${status.padEnd(6)} │`,\n\t\t);\n\t}\n\n\tlogger.log(\n\t\t' └─────────────────────────────────────┴──────┴─────────────────┴────────┘',\n\t);\n}\n\n/**\n * Print DNS records in a simple format for manual setup\n */\nexport function printDnsRecordsSimple(\n\trecords: RequiredDnsRecord[],\n\trootDomain: string,\n): void {\n\tlogger.log('\\n 📋 Required DNS Records:');\n\tlogger.log(` Add these A records to your DNS provider (${rootDomain}):\\n`);\n\n\tfor (const record of records) {\n\t\tlogger.log(` ${record.subdomain} → ${record.value} (A record)`);\n\t}\n\n\tlogger.log('');\n}\n\n/**\n * Create DNS records for a single domain using its configured provider\n */\nexport async function createDnsRecordsForDomain(\n\trecords: RequiredDnsRecord[],\n\trootDomain: string,\n\tproviderConfig: DnsProviderConfig,\n): Promise<RequiredDnsRecord[]> {\n\t// Get TTL from config, default to 300. Manual mode doesn't have ttl property.\n\tconst ttl =\n\t\t'ttl' in providerConfig && providerConfig.ttl ? providerConfig.ttl : 300;\n\n\t// Get DNS provider from factory\n\tlet provider: DnsProvider | null;\n\ttry {\n\t\t// Cast to schema-derived DnsConfig for provider factory\n\t\tprovider = await createDnsProvider({\n\t\t\tconfig: providerConfig as SchemaDnsConfig,\n\t\t});\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : 'Unknown error';\n\t\tlogger.log(\n\t\t\t` ⚠ Failed to create DNS provider for ${rootDomain}: ${message}`,\n\t\t);\n\t\treturn records.map((r) => ({ ...r, error: message }));\n\t}\n\n\t// Manual mode - no provider, just mark records as needing manual creation\n\tif (!provider) {\n\t\treturn records.map((r) => ({ ...r, created: false, existed: false }));\n\t}\n\n\tconst results: RequiredDnsRecord[] = [];\n\n\t// Convert RequiredDnsRecord to UpsertDnsRecord format\n\tconst upsertRecords: UpsertDnsRecord[] = records.map((r) => ({\n\t\tname: r.subdomain,\n\t\ttype: r.type,\n\t\tttl,\n\t\tvalue: r.value,\n\t}));\n\n\ttry {\n\t\t// Use provider to upsert records\n\t\tconst upsertResults = await provider.upsertRecords(\n\t\t\trootDomain,\n\t\t\tupsertRecords,\n\t\t);\n\n\t\t// Map results back to RequiredDnsRecord format\n\t\tfor (const [i, record] of records.entries()) {\n\t\t\tconst result = upsertResults[i];\n\n\t\t\t// Handle case where upsertResults has fewer items (shouldn't happen but be safe)\n\t\t\tif (!result) {\n\t\t\t\tresults.push({\n\t\t\t\t\thostname: record.hostname,\n\t\t\t\t\tsubdomain: record.subdomain,\n\t\t\t\t\ttype: record.type,\n\t\t\t\t\tvalue: record.value,\n\t\t\t\t\tappName: record.appName,\n\t\t\t\t\terror: 'No result returned from provider',\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (result.unchanged) {\n\t\t\t\tresults.push({\n\t\t\t\t\thostname: record.hostname,\n\t\t\t\t\tsubdomain: record.subdomain,\n\t\t\t\t\ttype: record.type,\n\t\t\t\t\tvalue: record.value,\n\t\t\t\t\tappName: record.appName,\n\t\t\t\t\texisted: true,\n\t\t\t\t\tcreated: false,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tresults.push({\n\t\t\t\t\thostname: record.hostname,\n\t\t\t\t\tsubdomain: record.subdomain,\n\t\t\t\t\ttype: record.type,\n\t\t\t\t\tvalue: record.value,\n\t\t\t\t\tappName: record.appName,\n\t\t\t\t\tcreated: result.created,\n\t\t\t\t\texisted: !result.created,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : 'Unknown error';\n\t\tlogger.log(\n\t\t\t` ⚠ Failed to create DNS records for ${rootDomain}: ${message}`,\n\t\t);\n\t\treturn records.map((r) => ({\n\t\t\thostname: r.hostname,\n\t\t\tsubdomain: r.subdomain,\n\t\t\ttype: r.type,\n\t\t\tvalue: r.value,\n\t\t\tappName: r.appName,\n\t\t\terror: message,\n\t\t}));\n\t}\n\n\treturn results;\n}\n\n/**\n * Create DNS records using the configured provider\n * @deprecated Use createDnsRecordsForDomain for multi-domain support\n */\nexport async function createDnsRecords(\n\trecords: RequiredDnsRecord[],\n\tdnsConfig: DnsConfig,\n): Promise<RequiredDnsRecord[]> {\n\t// Handle legacy config format\n\tif (!isLegacyDnsConfig(dnsConfig)) {\n\t\tthrow new Error(\n\t\t\t'createDnsRecords requires legacy DnsConfig with domain property. Use createDnsRecordsForDomain instead.',\n\t\t);\n\t}\n\tconst { domain: rootDomain, ...providerConfig } = dnsConfig;\n\treturn createDnsRecordsForDomain(\n\t\trecords,\n\t\trootDomain,\n\t\tproviderConfig as DnsProviderConfig,\n\t);\n}\n\n/**\n * Main DNS orchestration function for deployments\n *\n * Supports both legacy single-domain format and new multi-domain format:\n * - Legacy: { provider: 'hostinger', domain: 'example.com' }\n * - Multi: { 'example.com': { provider: 'hostinger' }, 'example.dev': { provider: 'route53' } }\n *\n * @param appHostnames - Map of app names to hostnames\n * @param dnsConfig - DNS configuration (legacy or multi-domain)\n * @param dokployEndpoint - Dokploy server endpoint to resolve IP from\n * @param state - Optional state to save created records for later deletion\n */\nexport async function orchestrateDns(\n\tappHostnames: Map<string, string>, // appName -> hostname\n\tdnsConfig: DnsConfig | undefined,\n\tdokployEndpoint: string,\n\tstate?: DokployStageState,\n): Promise<DnsCreationResult | null> {\n\tif (!dnsConfig) {\n\t\treturn null;\n\t}\n\n\t// Normalize config to multi-domain format\n\tconst normalizedConfig = normalizeDnsConfig(dnsConfig);\n\n\t// Resolve Dokploy server IP from endpoint\n\tlogger.log('\\n🌐 Setting up DNS records...');\n\tlet serverIp: string;\n\n\ttry {\n\t\tconst endpointUrl = new URL(dokployEndpoint);\n\t\tserverIp = await resolveHostnameToIp(endpointUrl.hostname);\n\t\tlogger.log(` Server IP: ${serverIp} (from ${endpointUrl.hostname})`);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : 'Unknown error';\n\t\tlogger.log(` ⚠ Failed to resolve server IP: ${message}`);\n\t\treturn null;\n\t}\n\n\t// Group hostnames by their root domain\n\tconst groupedHostnames = groupHostnamesByDomain(\n\t\tappHostnames,\n\t\tnormalizedConfig,\n\t);\n\n\tif (groupedHostnames.size === 0) {\n\t\tlogger.log(\n\t\t\t' No DNS records needed (no hostnames match configured domains)',\n\t\t);\n\t\treturn { records: [], success: true, serverIp };\n\t}\n\n\tconst allRecords: RequiredDnsRecord[] = [];\n\tlet hasFailures = false;\n\n\t// Process each domain group with its specific provider\n\tfor (const [rootDomain, domainHostnames] of groupedHostnames) {\n\t\tconst providerConfig = normalizedConfig[rootDomain];\n\t\tif (!providerConfig) {\n\t\t\tlogger.log(` ⚠ No provider config for ${rootDomain}`);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst providerName =\n\t\t\ttypeof providerConfig.provider === 'string'\n\t\t\t\t? providerConfig.provider\n\t\t\t\t: 'custom';\n\n\t\t// Generate required records for this domain\n\t\tconst requiredRecords = generateRequiredRecords(\n\t\t\tdomainHostnames,\n\t\t\trootDomain,\n\t\t\tserverIp,\n\t\t);\n\n\t\tif (requiredRecords.length === 0) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Create records for this domain\n\t\tlogger.log(\n\t\t\t` Creating DNS records for ${rootDomain} (${providerName})...`,\n\t\t);\n\t\tconst domainRecords = await createDnsRecordsForDomain(\n\t\t\trequiredRecords,\n\t\t\trootDomain,\n\t\t\tproviderConfig,\n\t\t);\n\n\t\tallRecords.push(...domainRecords);\n\n\t\tconst created = domainRecords.filter((r) => r.created).length;\n\t\tconst existed = domainRecords.filter((r) => r.existed).length;\n\t\tconst failed = domainRecords.filter((r) => r.error).length;\n\n\t\tif (created > 0) {\n\t\t\tlogger.log(` ✓ Created ${created} DNS record(s) for ${rootDomain}`);\n\t\t}\n\t\tif (existed > 0) {\n\t\t\tlogger.log(` ✓ ${existed} record(s) already exist for ${rootDomain}`);\n\t\t}\n\t\tif (failed > 0) {\n\t\t\tlogger.log(` ⚠ ${failed} record(s) failed for ${rootDomain}`);\n\t\t\thasFailures = true;\n\t\t}\n\n\t\t// Save created/existing records to state for later deletion during undeploy\n\t\tif (state) {\n\t\t\tfor (const record of domainRecords) {\n\t\t\t\tif (record.created || record.existed) {\n\t\t\t\t\tsetDnsRecord(state, {\n\t\t\t\t\t\tdomain: rootDomain,\n\t\t\t\t\t\tname: record.subdomain,\n\t\t\t\t\t\ttype: record.type,\n\t\t\t\t\t\tvalue: record.value,\n\t\t\t\t\t\tttl:\n\t\t\t\t\t\t\t'ttl' in providerConfig && providerConfig.ttl\n\t\t\t\t\t\t\t\t? providerConfig.ttl\n\t\t\t\t\t\t\t\t: 300,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Print summary table for this domain\n\t\tprintDnsRecordsTable(domainRecords, rootDomain);\n\n\t\t// If manual mode or some failed, print simple instructions\n\t\tif (providerConfig.provider === 'manual' || failed > 0) {\n\t\t\tprintDnsRecordsSimple(\n\t\t\t\tdomainRecords.filter((r) => !r.created && !r.existed),\n\t\t\t\trootDomain,\n\t\t\t);\n\t\t}\n\t}\n\n\treturn {\n\t\trecords: allRecords,\n\t\tsuccess: !hasFailures,\n\t\tserverIp,\n\t};\n}\n\n/**\n * Result of DNS verification for a single hostname\n */\nexport interface DnsVerificationResult {\n\thostname: string;\n\tappName: string;\n\tverified: boolean;\n\tresolvedIp?: string;\n\texpectedIp: string;\n\terror?: string;\n\tskipped?: boolean; // True if already verified in state\n}\n\n/**\n * Verify DNS records resolve correctly after deployment.\n *\n * This function:\n * 1. Checks state for previously verified hostnames (skips if already verified with same IP)\n * 2. Attempts to resolve each hostname to an IP\n * 3. Compares resolved IP with expected server IP\n * 4. Updates state with verification results\n *\n * @param appHostnames - Map of app names to hostnames\n * @param serverIp - Expected IP address the hostnames should resolve to\n * @param state - Deploy state for caching verification results\n * @returns Array of verification results\n */\nexport async function verifyDnsRecords(\n\tappHostnames: Map<string, string>,\n\tserverIp: string,\n\tstate: DokployStageState,\n): Promise<DnsVerificationResult[]> {\n\tconst results: DnsVerificationResult[] = [];\n\n\tlogger.log('\\n🔍 Verifying DNS records...');\n\n\tfor (const [appName, hostname] of appHostnames) {\n\t\t// Check if already verified with same IP\n\t\tif (isDnsVerified(state, hostname, serverIp)) {\n\t\t\tlogger.log(` ✓ ${hostname} (previously verified)`);\n\t\t\tresults.push({\n\t\t\t\thostname,\n\t\t\t\tappName,\n\t\t\t\tverified: true,\n\t\t\t\texpectedIp: serverIp,\n\t\t\t\tskipped: true,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Attempt to resolve hostname\n\t\ttry {\n\t\t\tconst resolvedIp = await resolveHostnameToIp(hostname);\n\n\t\t\tif (resolvedIp === serverIp) {\n\t\t\t\t// DNS verified successfully\n\t\t\t\tsetDnsVerification(state, hostname, serverIp);\n\t\t\t\tlogger.log(` ✓ ${hostname} → ${resolvedIp}`);\n\t\t\t\tresults.push({\n\t\t\t\t\thostname,\n\t\t\t\t\tappName,\n\t\t\t\t\tverified: true,\n\t\t\t\t\tresolvedIp,\n\t\t\t\t\texpectedIp: serverIp,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\t// DNS resolves but to wrong IP\n\t\t\t\tlogger.log(\n\t\t\t\t\t` ⚠ ${hostname} resolves to ${resolvedIp}, expected ${serverIp}`,\n\t\t\t\t);\n\t\t\t\tresults.push({\n\t\t\t\t\thostname,\n\t\t\t\t\tappName,\n\t\t\t\t\tverified: false,\n\t\t\t\t\tresolvedIp,\n\t\t\t\t\texpectedIp: serverIp,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// DNS resolution failed\n\t\t\tconst message = error instanceof Error ? error.message : 'Unknown error';\n\t\t\tlogger.log(` ⚠ ${hostname} DNS not propagated (${message})`);\n\t\t\tresults.push({\n\t\t\t\thostname,\n\t\t\t\tappName,\n\t\t\t\tverified: false,\n\t\t\t\texpectedIp: serverIp,\n\t\t\t\terror: message,\n\t\t\t});\n\t\t}\n\t}\n\n\t// Summary\n\tconst verified = results.filter((r) => r.verified).length;\n\tconst skipped = results.filter((r) => r.skipped).length;\n\tconst pending = results.filter((r) => !r.verified).length;\n\n\tif (pending > 0) {\n\t\tlogger.log(`\\n ${verified} verified, ${pending} pending propagation`);\n\t\tlogger.log(' DNS changes may take 5-30 minutes to propagate');\n\t} else if (skipped > 0) {\n\t\tlogger.log(` ${verified} verified (${skipped} from cache)`);\n\t}\n\n\treturn results;\n}\n","/**\n * How a deploy gets the credentials it acts with.\n *\n * `deploy()` never prompts and never reads a terminal: it asks a\n * `CredentialProvider` and, when the provider has nothing, stops with\n * `MissingCredential` naming what it needed and how to supply it. Whether to\n * ask a person, read a vault or fail is the caller's decision — `gkm deploy`\n * prompts at a terminal and stores what was typed; a CI job sets the\n * environment; a host passes its own provider.\n */\n\nimport { readCredentials } from '../auth/credentials';\nimport { GkmError } from '../errors';\n\n/**\n * What each kind of credential is asked for with, and what it is.\n *\n * A target that needs a kind the CLI does not know declares it by augmenting\n * this interface, and lists it in its `credentials`:\n *\n * ```ts\n * declare module '@geekmidas/cli/target' {\n * interface CredentialKinds {\n * fly: { request: { org: string }; value: { token: string } };\n * }\n * }\n * ```\n */\nexport interface CredentialKinds {\n\t/** The Dokploy API a stage deploys through. */\n\tdokploy: {\n\t\t/** `deploy.dokploy.endpoint`, when the config names one. */\n\t\trequest: { endpoint?: string };\n\t\tvalue: { endpoint: string; token: string };\n\t};\n\t/**\n\t * A container registry login, for Dokploy to pull with. Asked for only when\n\t * Dokploy has no registry for `deploy.registry` and one has to be\n\t * created.\n\t */\n\tregistry: {\n\t\t/** `deploy.registry`. */\n\t\trequest: { url: string };\n\t\tvalue: { username: string; password: string };\n\t};\n\t/**\n\t * The AWS account a stage deploys to, for the SST target's `sst deploy`.\n\t * Handed to that one command's environment and to nothing else.\n\t */\n\taws: {\n\t\t/** The stage, for a provider that keeps one account per stage. */\n\t\trequest: { stage: string };\n\t\tvalue: AwsCredential;\n\t};\n\t/**\n\t * A GoDaddy Personal Access Token, for a `dns` domain whose provider is\n\t * `godaddy`. Read on the machine that writes the records — never the\n\t * server's.\n\t */\n\tgodaddy: {\n\t\trequest: Record<never, never>;\n\t\tvalue: GoDaddyCredential;\n\t};\n\t/**\n\t * A Hostinger API token, for a `dns` domain whose provider is\n\t * `hostinger`. Like GoDaddy's, read where the records are written.\n\t */\n\thostinger: {\n\t\trequest: Record<never, never>;\n\t\tvalue: HostingerCredential;\n\t};\n}\n\n/** A Hostinger API token, from hpanel.hostinger.com/profile/api. */\nexport interface HostingerCredential {\n\ttoken: string;\n}\n\n/** A GoDaddy Personal Access Token, sent as `Authorization: Bearer <token>`. */\nexport interface GoDaddyCredential {\n\ttoken: string;\n}\n\n/**\n * Who to act as on AWS: a named profile, or keys.\n *\n * Never both. Given both, every AWS SDK takes the keys and ignores the\n * profile, so `--profile prod` with staging's keys still exported would deploy\n * production's stack into staging's account — the reason `secretsStoreFor`\n * resolves a named profile on its own, and why this cannot express the mix.\n */\nexport type AwsCredential =\n\t| {\n\t\t\t/** A profile in `~/.aws/config` — keys, SSO, an assumed role. */\n\t\t\tprofile: string;\n\t\t\tregion?: string;\n\t }\n\t| {\n\t\t\taccessKeyId: string;\n\t\t\tsecretAccessKey: string;\n\t\t\t/** Present for temporary keys: an assumed role, GitHub's OIDC. */\n\t\t\tsessionToken?: string;\n\t\t\tregion?: string;\n\t };\n\nexport type CredentialKind = keyof CredentialKinds;\n\n/** What a deploy asks a provider for. */\nexport type CredentialRequest<K extends CredentialKind = CredentialKind> = {\n\t[P in K]: { kind: P } & CredentialKinds[P]['request'];\n}[K];\n\n/** What a provider answers with. */\nexport type Credential<K extends CredentialKind> = CredentialKinds[K]['value'];\n\nexport interface CredentialProvider {\n\t/**\n\t * The credential `request` asks for, or `undefined` when this provider has\n\t * none — the deploy then raises {@link MissingCredential}.\n\t */\n\tget<K extends CredentialKind>(\n\t\trequest: CredentialRequest<K>,\n\t\toptions?: { signal?: AbortSignal },\n\t): Promise<Credential<K> | undefined>;\n}\n\n/**\n * How to supply each kind the CLI knows, for the error that says it is\n * missing. A target's own kinds are its to explain.\n */\nconst HOW_TO_PROVIDE: Partial<Record<CredentialKind, string>> = {\n\tdokploy:\n\t\t\"Set DOKPLOY_API_TOKEN (and DOKPLOY_ENDPOINT, or deploy.dokploy.endpoint in gkm.config.ts), run `gkm login --provider dokploy`, or pass them through the deploy's CredentialProvider.\",\n\tregistry:\n\t\t'Add the registry in Dokploy (Settings → Docker Registry) and set deploy.dokploy.registryId, set DOCKER_REGISTRY_USERNAME and DOCKER_REGISTRY_PASSWORD, or run `gkm deploy` at a terminal to be asked for them.',\n\tgodaddy:\n\t\t'Set GODADDY_API_TOKEN to a Personal Access Token scoped to domains.dns:update (create one in the GoDaddy developer dashboard), or run `gkm login --provider godaddy`.',\n\thostinger:\n\t\t'Set HOSTINGER_API_TOKEN to a token from hpanel.hostinger.com/profile/api, or run `gkm login --provider hostinger`.',\n\taws: \"Set AWS_PROFILE to the stage account's profile, or AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (and AWS_SESSION_TOKEN) — in CI, the keys aws-actions/configure-aws-credentials exports — or pass them through the deploy's CredentialProvider.\",\n};\n\n/** A deploy needed a credential, and its provider had none. */\nexport class MissingCredential extends GkmError {\n\tconstructor(\n\t\treadonly kind: CredentialKind,\n\t\t/** What it was for: the Dokploy endpoint or the registry URL. */\n\t\treadonly target: string | undefined,\n\t\t/** How to supply it. */\n\t\treadonly howToProvide: string = HOW_TO_PROVIDE[kind] ??\n\t\t\t\"Pass it through the deploy's CredentialProvider.\",\n\t) {\n\t\tconst what =\n\t\t\tkind === 'dokploy'\n\t\t\t\t? `No Dokploy credentials${target ? ` for ${target}` : ''}.`\n\t\t\t\t: kind === 'registry'\n\t\t\t\t\t? `Dokploy has no registry for ${target ?? 'the configured registry'}, and there are no credentials to create one with.`\n\t\t\t\t\t: kind === 'aws'\n\t\t\t\t\t\t? `No AWS credentials${target ? ` for the \"${target}\" stage` : ''}.`\n\t\t\t\t\t\t: kind === 'godaddy'\n\t\t\t\t\t\t\t? `No GoDaddy API token${target ? ` for ${target}` : ''}.`\n\t\t\t\t\t\t\t: kind === 'hostinger'\n\t\t\t\t\t\t\t\t? `No Hostinger API token${target ? ` for ${target}` : ''}.`\n\t\t\t\t\t\t\t\t: `No \"${String(kind)}\" credentials${target ? ` for ${target}` : ''}.`;\n\t\tsuper(`${what} ${howToProvide}`);\n\t\tthis.name = 'MissingCredential';\n\t}\n}\n\n/** Whatever was asked for, from the first provider that has it. */\nexport function chainCredentials(\n\t...providers: CredentialProvider[]\n): CredentialProvider {\n\treturn {\n\t\tasync get(request, options) {\n\t\t\tfor (const provider of providers) {\n\t\t\t\tconst found = await provider.get(request, options);\n\t\t\t\tif (found) return found;\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t};\n}\n\nexport interface StoredCredentialsOptions {\n\t/** Where to read the variables from. Defaults to `process.env`. */\n\tenv?: NodeJS.ProcessEnv;\n\t/**\n\t * The CLI's home, whose `credentials.json` holds stored logins. Defaults\n\t * to `GKM_HOME`, else `~/.gkm`.\n\t */\n\thome?: string;\n}\n\n/**\n * Credentials from the environment, then from what `gkm login` stored. What\n * `deploy()` uses when it is handed no provider.\n *\n * - Dokploy: `DOKPLOY_API_TOKEN` / `DOKPLOY_ENDPOINT`, each falling back to\n * the stored login, and the endpoint finally to `deploy.dokploy.endpoint`.\n * Each half is read on its own: a token is a secret and belongs in the\n * environment, an endpoint is configuration and belongs in the config.\n * - Registry: `DOCKER_REGISTRY_USERNAME` / `DOCKER_REGISTRY_PASSWORD`.\n * - AWS: `AWS_PROFILE` when it is set, and then nothing else; otherwise\n * `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` / `AWS_SESSION_TOKEN`. The\n * profile winning is `secretsStoreFor`'s rule: a profile is a choice of\n * account someone made, exported keys may be left over from another.\n * Read here, by name, and handed only to the command that deploys — the\n * sandbox every other step runs in passes no `AWS_*` on.\n */\nexport function storedCredentials(\n\toptions: StoredCredentialsOptions = {},\n): CredentialProvider {\n\tconst env = options.env ?? process.env;\n\n\treturn {\n\t\tasync get(asked) {\n\t\t\t// The union, so a switch on `kind` narrows it: `K` itself never is.\n\t\t\tconst request = asked as CredentialRequest;\n\t\t\tswitch (request.kind) {\n\t\t\t\tcase 'dokploy': {\n\t\t\t\t\tconst stored = (\n\t\t\t\t\t\tawait readCredentials(\n\t\t\t\t\t\t\toptions.home ? { home: options.home } : undefined,\n\t\t\t\t\t\t)\n\t\t\t\t\t).dokploy;\n\t\t\t\t\tconst token = env.DOKPLOY_API_TOKEN ?? stored?.token;\n\t\t\t\t\tconst endpoint =\n\t\t\t\t\t\tenv.DOKPLOY_ENDPOINT ?? stored?.endpoint ?? request.endpoint;\n\t\t\t\t\tif (!token || !endpoint) return undefined;\n\t\t\t\t\treturn { endpoint: endpoint.replace(/\\/$/, ''), token } as never;\n\t\t\t\t}\n\t\t\t\tcase 'registry': {\n\t\t\t\t\tconst username = env.DOCKER_REGISTRY_USERNAME;\n\t\t\t\t\tconst password = env.DOCKER_REGISTRY_PASSWORD;\n\t\t\t\t\tif (!username || !password) return undefined;\n\t\t\t\t\treturn { username, password } as never;\n\t\t\t\t}\n\t\t\t\tcase 'godaddy': {\n\t\t\t\t\t// The environment first, then the stored login.\n\t\t\t\t\tconst token =\n\t\t\t\t\t\tenv.GODADDY_API_TOKEN ||\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tawait readCredentials(\n\t\t\t\t\t\t\t\toptions.home ? { home: options.home } : undefined,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t).godaddy?.token;\n\t\t\t\t\tif (!token) return undefined;\n\t\t\t\t\treturn { token } as never;\n\t\t\t\t}\n\t\t\t\tcase 'hostinger': {\n\t\t\t\t\tconst token =\n\t\t\t\t\t\tenv.HOSTINGER_API_TOKEN ||\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tawait readCredentials(\n\t\t\t\t\t\t\t\toptions.home ? { home: options.home } : undefined,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t).hostinger?.token;\n\t\t\t\t\tif (!token) return undefined;\n\t\t\t\t\treturn { token } as never;\n\t\t\t\t}\n\t\t\t\tcase 'aws': {\n\t\t\t\t\tconst region = env.AWS_REGION ?? env.AWS_DEFAULT_REGION;\n\t\t\t\t\tconst where = region ? { region } : {};\n\t\t\t\t\tif (env.AWS_PROFILE) {\n\t\t\t\t\t\treturn { profile: env.AWS_PROFILE, ...where } as never;\n\t\t\t\t\t}\n\t\t\t\t\tconst accessKeyId = env.AWS_ACCESS_KEY_ID;\n\t\t\t\t\tconst secretAccessKey = env.AWS_SECRET_ACCESS_KEY;\n\t\t\t\t\tif (!accessKeyId || !secretAccessKey) return undefined;\n\t\t\t\t\treturn {\n\t\t\t\t\t\taccessKeyId,\n\t\t\t\t\t\tsecretAccessKey,\n\t\t\t\t\t\t...(env.AWS_SESSION_TOKEN\n\t\t\t\t\t\t\t? { sessionToken: env.AWS_SESSION_TOKEN }\n\t\t\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