@geekmidas/cli 10.0.0-alpha.157 → 10.0.0-alpha.159

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 (181) hide show
  1. package/dist/{EndpointGenerator-CusLH-9S.mjs → EndpointGenerator-B5BKAoLz.mjs} +4 -2
  2. package/dist/EndpointGenerator-B5BKAoLz.mjs.map +1 -0
  3. package/dist/{EndpointGenerator-DyLMYClE.cjs → EndpointGenerator-DxrRqfJ3.cjs} +4 -2
  4. package/dist/EndpointGenerator-DxrRqfJ3.cjs.map +1 -0
  5. package/dist/{GoDaddyProvider-CRDZ574t.cjs → GoDaddyProvider-CKDquvxI.cjs} +2 -2
  6. package/dist/{GoDaddyProvider-CRDZ574t.cjs.map → GoDaddyProvider-CKDquvxI.cjs.map} +1 -1
  7. package/dist/{GoDaddyProvider-DplVl6PV.mjs → GoDaddyProvider-DwyQXxO9.mjs} +2 -2
  8. package/dist/{GoDaddyProvider-DplVl6PV.mjs.map → GoDaddyProvider-DwyQXxO9.mjs.map} +1 -1
  9. package/dist/{HostingerProvider-B4pWxtNL.mjs → HostingerProvider-BZIKJDKU.mjs} +2 -2
  10. package/dist/{HostingerProvider-B4pWxtNL.mjs.map → HostingerProvider-BZIKJDKU.mjs.map} +1 -1
  11. package/dist/{HostingerProvider-Car70UOZ.cjs → HostingerProvider-CRDllmxA.cjs} +2 -2
  12. package/dist/{HostingerProvider-Car70UOZ.cjs.map → HostingerProvider-CRDllmxA.cjs.map} +1 -1
  13. package/dist/{LegacyStateStore-DLfjqri1.mjs → LegacyStateStore-BwnVnaHW.mjs} +2 -2
  14. package/dist/{LegacyStateStore-DLfjqri1.mjs.map → LegacyStateStore-BwnVnaHW.mjs.map} +1 -1
  15. package/dist/{LegacyStateStore--HvaCD_x.cjs → LegacyStateStore-CQ1J1rpx.cjs} +2 -2
  16. package/dist/{LegacyStateStore--HvaCD_x.cjs.map → LegacyStateStore-CQ1J1rpx.cjs.map} +1 -1
  17. package/dist/{LocalStateStore-Bck7bNAu.cjs → LocalStateStore-BvlLiIO_.cjs} +2 -2
  18. package/dist/{LocalStateStore-Bck7bNAu.cjs.map → LocalStateStore-BvlLiIO_.cjs.map} +1 -1
  19. package/dist/{LocalStateStore-BxvEMGIg.mjs → LocalStateStore-vA76-rrz.mjs} +2 -2
  20. package/dist/{LocalStateStore-BxvEMGIg.mjs.map → LocalStateStore-vA76-rrz.mjs.map} +1 -1
  21. package/dist/{OpenApiTsGenerator-CI-tceXV.cjs → OpenApiTsGenerator-DOTLKBFf.cjs} +2 -2
  22. package/dist/{OpenApiTsGenerator-CI-tceXV.cjs.map → OpenApiTsGenerator-DOTLKBFf.cjs.map} +1 -1
  23. package/dist/{OpenApiTsGenerator-BTMuu1WS.mjs → OpenApiTsGenerator-Vaf0pI8u.mjs} +2 -2
  24. package/dist/{OpenApiTsGenerator-BTMuu1WS.mjs.map → OpenApiTsGenerator-Vaf0pI8u.mjs.map} +1 -1
  25. package/dist/{S3StateStore-BFJ3KaNH.cjs → S3StateStore-BxeAk09j.cjs} +4 -4
  26. package/dist/{S3StateStore-BFJ3KaNH.cjs.map → S3StateStore-BxeAk09j.cjs.map} +1 -1
  27. package/dist/{S3StateStore-Ba9zrMWD.mjs → S3StateStore-DnJHHDPk.mjs} +4 -4
  28. package/dist/{S3StateStore-Ba9zrMWD.mjs.map → S3StateStore-DnJHHDPk.mjs.map} +1 -1
  29. package/dist/{SSMStateStore-C0xhLKD2.mjs → SSMStateStore-DXzyEcIH.mjs} +2 -2
  30. package/dist/{SSMStateStore-C0xhLKD2.mjs.map → SSMStateStore-DXzyEcIH.mjs.map} +1 -1
  31. package/dist/{SSMStateStore-a5oX3zgi.cjs → SSMStateStore-DzXyEoBx.cjs} +2 -2
  32. package/dist/{SSMStateStore-a5oX3zgi.cjs.map → SSMStateStore-DzXyEoBx.cjs.map} +1 -1
  33. package/dist/{SubscriberGenerator-CzPrixYu.mjs → SubscriberGenerator-BybB6uez.mjs} +2 -2
  34. package/dist/{SubscriberGenerator-CzPrixYu.mjs.map → SubscriberGenerator-BybB6uez.mjs.map} +1 -1
  35. package/dist/{SubscriberGenerator-BNJyPmXJ.cjs → SubscriberGenerator-mZpSuSU7.cjs} +2 -2
  36. package/dist/{SubscriberGenerator-BNJyPmXJ.cjs.map → SubscriberGenerator-mZpSuSU7.cjs.map} +1 -1
  37. package/dist/{add-5QcLsP3H.cjs → add-C_adddD3.cjs} +4 -4
  38. package/dist/{add-5QcLsP3H.cjs.map → add-C_adddD3.cjs.map} +1 -1
  39. package/dist/{add-CO16e9iI.mjs → add-WRwjtnks.mjs} +4 -4
  40. package/dist/{add-CO16e9iI.mjs.map → add-WRwjtnks.mjs.map} +1 -1
  41. package/dist/{apps-BVcA1Hy7.mjs → apps-BHiqiigd.mjs} +5 -5
  42. package/dist/{apps-BVcA1Hy7.mjs.map → apps-BHiqiigd.mjs.map} +1 -1
  43. package/dist/{apps-BRzZ5pIa.cjs → apps-Cri_aQvD.cjs} +5 -5
  44. package/dist/{apps-BRzZ5pIa.cjs.map → apps-Cri_aQvD.cjs.map} +1 -1
  45. package/dist/{bundler-CrNow5yF.mjs → bundler-Bh5MoDSl.mjs} +6 -6
  46. package/dist/{bundler-CrNow5yF.mjs.map → bundler-Bh5MoDSl.mjs.map} +1 -1
  47. package/dist/{bundler-Bo4JMtRH.cjs → bundler-CP0Nw6_V.cjs} +6 -6
  48. package/dist/{bundler-Bo4JMtRH.cjs.map → bundler-CP0Nw6_V.cjs.map} +1 -1
  49. package/dist/{cli-CEbLgLW5.cjs → cli-D8hr5lr4.cjs} +4 -4
  50. package/dist/{cli-CEbLgLW5.cjs.map → cli-D8hr5lr4.cjs.map} +1 -1
  51. package/dist/{cli-BsiiOIVE.mjs → cli-LI1NhjE5.mjs} +4 -4
  52. package/dist/{cli-BsiiOIVE.mjs.map → cli-LI1NhjE5.mjs.map} +1 -1
  53. package/dist/{compose-DZroNh2I.cjs → compose-CQPisITP.cjs} +4 -4
  54. package/dist/{compose-DZroNh2I.cjs.map → compose-CQPisITP.cjs.map} +1 -1
  55. package/dist/{compose-BSLOkoX8.mjs → compose-CS6WIN-0.mjs} +4 -4
  56. package/dist/{compose-BSLOkoX8.mjs.map → compose-CS6WIN-0.mjs.map} +1 -1
  57. package/dist/{compose-CtL6-1af.mjs → compose-D1rST6pU.mjs} +7 -7
  58. package/dist/{compose-CtL6-1af.mjs.map → compose-D1rST6pU.mjs.map} +1 -1
  59. package/dist/{compose-RtLoPN86.cjs → compose-DWgccYYU.cjs} +7 -7
  60. package/dist/{compose-RtLoPN86.cjs.map → compose-DWgccYYU.cjs.map} +1 -1
  61. package/dist/{credentials-C69J5G91.mjs → credentials-CKCKknMs.mjs} +5 -5
  62. package/dist/{credentials-C69J5G91.mjs.map → credentials-CKCKknMs.mjs.map} +1 -1
  63. package/dist/{credentials-D4XclzQZ.cjs → credentials-i6NycDXd.cjs} +5 -5
  64. package/dist/{credentials-D4XclzQZ.cjs.map → credentials-i6NycDXd.cjs.map} +1 -1
  65. package/dist/deploy/public.cjs +10 -10
  66. package/dist/deploy/public.mjs +10 -10
  67. package/dist/{deploy-uxEAC6Vv.cjs → deploy-DGjYbiqq.cjs} +12 -12
  68. package/dist/{deploy-uxEAC6Vv.cjs.map → deploy-DGjYbiqq.cjs.map} +1 -1
  69. package/dist/{deploy-RD6J-w2h.mjs → deploy-EopBQqnJ.mjs} +12 -12
  70. package/dist/{deploy-RD6J-w2h.mjs.map → deploy-EopBQqnJ.mjs.map} +1 -1
  71. package/dist/{docker-C2WagkrW.cjs → docker-2PN6JmUz.cjs} +6 -6
  72. package/dist/{docker-C2WagkrW.cjs.map → docker-2PN6JmUz.cjs.map} +1 -1
  73. package/dist/{docker-Db0TnF9j.mjs → docker-Br4lwU8K.mjs} +6 -6
  74. package/dist/{docker-Db0TnF9j.mjs.map → docker-Br4lwU8K.mjs.map} +1 -1
  75. package/dist/{dokploy-Ds1AvRQa.mjs → dokploy-Bq06k6hU.mjs} +2 -2
  76. package/dist/{dokploy-Ds1AvRQa.mjs.map → dokploy-Bq06k6hU.mjs.map} +1 -1
  77. package/dist/{dokploy-Ds-dwYjG.cjs → dokploy-DP07onK9.cjs} +2 -2
  78. package/dist/{dokploy-Ds-dwYjG.cjs.map → dokploy-DP07onK9.cjs.map} +1 -1
  79. package/dist/{eas-C_96kJG8.mjs → eas-e1TJSqsO.mjs} +2 -2
  80. package/dist/{eas-C_96kJG8.mjs.map → eas-e1TJSqsO.mjs.map} +1 -1
  81. package/dist/{eas-BgC-aXgY.cjs → eas-hSOnAjM1.cjs} +2 -2
  82. package/dist/{eas-BgC-aXgY.cjs.map → eas-hSOnAjM1.cjs.map} +1 -1
  83. package/dist/{encryption-KErhFgTQ.cjs → encryption-5g0QMUXJ.cjs} +2 -2
  84. package/dist/{encryption-KErhFgTQ.cjs.map → encryption-5g0QMUXJ.cjs.map} +1 -1
  85. package/dist/{encryption-DfoPAQ06.mjs → encryption-Bkiis13Q.mjs} +2 -2
  86. package/dist/{encryption-DfoPAQ06.mjs.map → encryption-Bkiis13Q.mjs.map} +1 -1
  87. package/dist/{engine-eaVZpdsY.mjs → engine-DB08e1EB.mjs} +8 -8
  88. package/dist/{engine-eaVZpdsY.mjs.map → engine-DB08e1EB.mjs.map} +1 -1
  89. package/dist/{engine-CgkVqYY-.cjs → engine-g86XmSu-.cjs} +8 -8
  90. package/dist/{engine-CgkVqYY-.cjs.map → engine-g86XmSu-.cjs.map} +1 -1
  91. package/dist/{github-DWgux2Mc.mjs → github-BuDZaqTQ.mjs} +6 -6
  92. package/dist/{github-DWgux2Mc.mjs.map → github-BuDZaqTQ.mjs.map} +1 -1
  93. package/dist/{github-hZ_qJn2O.cjs → github-Dx_XSH19.cjs} +6 -6
  94. package/dist/{github-hZ_qJn2O.cjs.map → github-Dx_XSH19.cjs.map} +1 -1
  95. package/dist/{googlePlay-BneaYZYU.cjs → googlePlay-BY9o6t23.cjs} +4 -4
  96. package/dist/{googlePlay-BneaYZYU.cjs.map → googlePlay-BY9o6t23.cjs.map} +1 -1
  97. package/dist/{googlePlay-CcDoKDlM.mjs → googlePlay-ewWbA1n2.mjs} +4 -4
  98. package/dist/{googlePlay-CcDoKDlM.mjs.map → googlePlay-ewWbA1n2.mjs.map} +1 -1
  99. package/dist/index.cjs +63 -63
  100. package/dist/index.cjs.map +1 -1
  101. package/dist/index.mjs +63 -63
  102. package/dist/index.mjs.map +1 -1
  103. package/dist/{local-DX5F9mI1.cjs → local-B_-OnfQ3.cjs} +2 -2
  104. package/dist/{local-DX5F9mI1.cjs.map → local-B_-OnfQ3.cjs.map} +1 -1
  105. package/dist/{local-CSkxxmZ5.mjs → local-DdqiukDq.mjs} +2 -2
  106. package/dist/{local-CSkxxmZ5.mjs.map → local-DdqiukDq.mjs.map} +1 -1
  107. package/dist/{migrate-T0b6IPf-.cjs → migrate-39p-DRKn.cjs} +4 -4
  108. package/dist/{migrate-T0b6IPf-.cjs.map → migrate-39p-DRKn.cjs.map} +1 -1
  109. package/dist/{migrate-Y_QjN95a.mjs → migrate-77UvdtrA.mjs} +4 -4
  110. package/dist/{migrate-Y_QjN95a.mjs.map → migrate-77UvdtrA.mjs.map} +1 -1
  111. package/dist/{migrate-Hi5BARdP.mjs → migrate-BhvmnG65.mjs} +2 -2
  112. package/dist/{migrate-Hi5BARdP.mjs.map → migrate-BhvmnG65.mjs.map} +1 -1
  113. package/dist/{migrate-BA2AgnvW.cjs → migrate-Dwdxal87.cjs} +2 -2
  114. package/dist/{migrate-BA2AgnvW.cjs.map → migrate-Dwdxal87.cjs.map} +1 -1
  115. package/dist/{notes-CjFVW8bn.cjs → notes-BI7Dnyrp.cjs} +2 -2
  116. package/dist/{notes-CjFVW8bn.cjs.map → notes-BI7Dnyrp.cjs.map} +1 -1
  117. package/dist/{notes-C5LmC9-z.mjs → notes-DdNcS5q5.mjs} +2 -2
  118. package/dist/{notes-C5LmC9-z.mjs.map → notes-DdNcS5q5.mjs.map} +1 -1
  119. package/dist/openapi.cjs +2 -2
  120. package/dist/openapi.mjs +2 -2
  121. package/dist/{projectBucket-BokyGleo.cjs → projectBucket-BxLoiySR.cjs} +2 -2
  122. package/dist/{projectBucket-BokyGleo.cjs.map → projectBucket-BxLoiySR.cjs.map} +1 -1
  123. package/dist/{projectBucket-CJC-C3cD.mjs → projectBucket-q4M_7rYh.mjs} +2 -2
  124. package/dist/{projectBucket-CJC-C3cD.mjs.map → projectBucket-q4M_7rYh.mjs.map} +1 -1
  125. package/dist/{publish-CxQyLRhO.mjs → publish-Bfr2okmd.mjs} +2 -2
  126. package/dist/{publish-CxQyLRhO.mjs.map → publish-Bfr2okmd.mjs.map} +1 -1
  127. package/dist/{publish-CKuhnFwH.cjs → publish-DqnMTMq0.cjs} +2 -2
  128. package/dist/{publish-CKuhnFwH.cjs.map → publish-DqnMTMq0.cjs.map} +1 -1
  129. package/dist/{ready-Dkw_Xt4P.mjs → ready-BjFMu_1J.mjs} +4 -4
  130. package/dist/{ready-Dkw_Xt4P.mjs.map → ready-BjFMu_1J.mjs.map} +1 -1
  131. package/dist/{ready-DV-_oK_O.cjs → ready-eVMJIcWn.cjs} +4 -4
  132. package/dist/{ready-DV-_oK_O.cjs.map → ready-eVMJIcWn.cjs.map} +1 -1
  133. package/dist/{resolve-CenYGcnj.mjs → resolve-DQ3QsMGK.mjs} +4 -4
  134. package/dist/{resolve-CenYGcnj.mjs.map → resolve-DQ3QsMGK.mjs.map} +1 -1
  135. package/dist/{resolve-mS7fO8YL.cjs → resolve-Ysdv1y9t.cjs} +4 -4
  136. package/dist/{resolve-mS7fO8YL.cjs.map → resolve-Ysdv1y9t.cjs.map} +1 -1
  137. package/dist/{rollback-DfJ0Rpkb.mjs → rollback-CbpKGQGn.mjs} +5 -5
  138. package/dist/{rollback-DfJ0Rpkb.mjs.map → rollback-CbpKGQGn.mjs.map} +1 -1
  139. package/dist/{rollback-D5rjIQwJ.cjs → rollback-D8-jEiQa.cjs} +5 -5
  140. package/dist/{rollback-D5rjIQwJ.cjs.map → rollback-D8-jEiQa.cjs.map} +1 -1
  141. package/dist/{s3-jtCO7o69.mjs → s3-Di_aCl0q.mjs} +2 -2
  142. package/dist/{s3-jtCO7o69.mjs.map → s3-Di_aCl0q.mjs.map} +1 -1
  143. package/dist/{s3-AIH2NmEI.cjs → s3-DtLAvo4D.cjs} +2 -2
  144. package/dist/{s3-AIH2NmEI.cjs.map → s3-DtLAvo4D.cjs.map} +1 -1
  145. package/dist/{serverSetup-6bczKo49.mjs → serverSetup-CrCEhS0g.mjs} +42 -9
  146. package/dist/serverSetup-CrCEhS0g.mjs.map +1 -0
  147. package/dist/{serverSetup-CVeRKNXR.cjs → serverSetup-WWrNW3Md.cjs} +42 -9
  148. package/dist/serverSetup-WWrNW3Md.cjs.map +1 -0
  149. package/dist/{sniffer-CzjFwmlR.mjs → sniffer-CEw1spoV.mjs} +6 -6
  150. package/dist/{sniffer-CzjFwmlR.mjs.map → sniffer-CEw1spoV.mjs.map} +1 -1
  151. package/dist/{sniffer-3Wix1Bez.cjs → sniffer-CvsdmfuV.cjs} +6 -6
  152. package/dist/{sniffer-3Wix1Bez.cjs.map → sniffer-CvsdmfuV.cjs.map} +1 -1
  153. package/dist/{snsSubscriptions-ByM_a0-4.mjs → snsSubscriptions-CB-WnmUi.mjs} +2 -2
  154. package/dist/{snsSubscriptions-ByM_a0-4.mjs.map → snsSubscriptions-CB-WnmUi.mjs.map} +1 -1
  155. package/dist/{snsSubscriptions-CDFlapU9.cjs → snsSubscriptions-G-FNGLvt.cjs} +2 -2
  156. package/dist/{snsSubscriptions-CDFlapU9.cjs.map → snsSubscriptions-G-FNGLvt.cjs.map} +1 -1
  157. package/dist/{sst-DykouxeI.cjs → sst-B3DBmq5F.cjs} +4 -4
  158. package/dist/{sst-DykouxeI.cjs.map → sst-B3DBmq5F.cjs.map} +1 -1
  159. package/dist/{sst-Bsf-6bw5.mjs → sst-CjiSTuNU.mjs} +4 -4
  160. package/dist/{sst-Bsf-6bw5.mjs.map → sst-CjiSTuNU.mjs.map} +1 -1
  161. package/dist/{stack-DbM4Z8XX.mjs → stack--9_32IOM.mjs} +7 -7
  162. package/dist/{stack-DbM4Z8XX.mjs.map → stack--9_32IOM.mjs.map} +1 -1
  163. package/dist/{stack-wBYoBpNL.cjs → stack-B4PwA10G.cjs} +7 -7
  164. package/dist/{stack-wBYoBpNL.cjs.map → stack-B4PwA10G.cjs.map} +1 -1
  165. package/dist/{stage-BAeoWlaT.cjs → stage-Dk52SAc3.cjs} +5 -5
  166. package/dist/{stage-BAeoWlaT.cjs.map → stage-Dk52SAc3.cjs.map} +1 -1
  167. package/dist/{stage-C9OePz1T.mjs → stage-sirtVzDQ.mjs} +5 -5
  168. package/dist/{stage-C9OePz1T.mjs.map → stage-sirtVzDQ.mjs.map} +1 -1
  169. package/dist/target/public.cjs +1 -1
  170. package/dist/target/public.mjs +1 -1
  171. package/dist/{terminal-vsCCECku.cjs → terminal-BBjilWid.cjs} +2 -2
  172. package/dist/{terminal-vsCCECku.cjs.map → terminal-BBjilWid.cjs.map} +1 -1
  173. package/dist/{terminal-cYD0PvkL.mjs → terminal-CEORTJyM.mjs} +2 -2
  174. package/dist/{terminal-cYD0PvkL.mjs.map → terminal-CEORTJyM.mjs.map} +1 -1
  175. package/dist/vitest.cjs +1 -1
  176. package/dist/vitest.mjs +1 -1
  177. package/package.json +15 -15
  178. package/dist/EndpointGenerator-CusLH-9S.mjs.map +0 -1
  179. package/dist/EndpointGenerator-DyLMYClE.cjs.map +0 -1
  180. package/dist/serverSetup-6bczKo49.mjs.map +0 -1
  181. package/dist/serverSetup-CVeRKNXR.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"EndpointGenerator-DyLMYClE.cjs","names":["GkmError","resolve","dirname","join","existsSync","realpathSync","GkmError","relative","mkdir","writeFile","relative","ConstructGenerator","Endpoint","join","mkdir","dirname","writeFile"],"sources":["../src/generators/clientTelemetry.ts","../src/generators/telemetry.ts","../src/generators/EndpointGenerator.ts"],"sourcesContent":["/**\n * Whether a generated client propagates trace context by default.\n *\n * `false` (the default) prints a client that sends no trace headers unless\n * its caller passes `telemetry`. Anything else prints that default into\n * `createApi`: `true`, or `{ sampleRate }` — the stage's rate, for the page\n * views no OpenTelemetry SDK is tracing. A caller's own `telemetry` option\n * still wins.\n */\n\nimport { GkmError } from '../errors';\nexport type ClientTelemetryDefault = boolean | { sampleRate: number };\n\n/** A `sampleRate` outside 0–1, which no sampler can honour. */\nexport class InvalidClientTelemetrySampleRate extends GkmError {\n\tconstructor(readonly sampleRate: number) {\n\t\tsuper(\n\t\t\t`The client's telemetry sample rate must be a number from 0 to 1, got ${sampleRate}. Pass the stage's rate, such as 0.1, or leave it out for 1.`,\n\t\t);\n\t\tthis.name = 'InvalidClientTelemetrySampleRate';\n\t}\n}\n\n/** The `telemetry` default as the generated module prints it. */\nexport function printTelemetryDefault(\n\ttelemetry: ClientTelemetryDefault,\n): string {\n\tif (typeof telemetry === 'boolean') return String(telemetry);\n\tconst { sampleRate } = telemetry;\n\tif (!Number.isFinite(sampleRate) || sampleRate < 0 || sampleRate > 1) {\n\t\tthrow new InvalidClientTelemetrySampleRate(sampleRate);\n\t}\n\treturn `{ sampleRate: ${sampleRate} }`;\n}\n\n/**\n * `--telemetry [rate]` for a client default, as `gkm openapi` takes it — and\n * as a site's Dockerfile passes it to the `gkm openapi --app` it runs.\n */\nexport function telemetryArgs(telemetry?: ClientTelemetryDefault): string[] {\n\tif (!telemetry) return [];\n\tif (telemetry === true) return ['--telemetry'];\n\treturn ['--telemetry', String(telemetry.sampleRate)];\n}\n\n/** What `--telemetry [rate]` parsed to: on, at a rate when one was given. */\nexport function parseTelemetryFlag(\n\tvalue: boolean | string | undefined,\n): ClientTelemetryDefault | undefined {\n\tif (value === undefined || value === false) return undefined;\n\tif (value === true) return true;\n\treturn { sampleRate: Number(value) };\n}\n","import { existsSync, realpathSync } from 'node:fs';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative, resolve } from 'node:path';\nimport type { TelemetryDeclaration } from '@geekmidas/manifest';\nimport { GkmError } from '../errors';\n\n/**\n * One route's own telemetry — an endpoint's `.telemetry({ ignore, attributes })`.\n */\nexport interface TelemetryRoute {\n\tmethod: string;\n\t/** The route as the surface serves it — `/users/:id`. */\n\tpath: string;\n\tignore?: boolean;\n\tattributes?: Readonly<Record<string, string>>;\n}\n\n/** Each endpoint's own `.telemetry({ ignore, attributes })`, as routes. */\nexport function routeTelemetry(\n\tendpoints: readonly {\n\t\tmethod: string;\n\t\troute: string;\n\t\ttelemetry?: Omit<TelemetryRoute, 'method' | 'path'>;\n\t}[],\n): TelemetryRoute[] {\n\treturn endpoints.flatMap((endpoint) =>\n\t\tendpoint.telemetry\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tmethod: endpoint.method,\n\t\t\t\t\t\tpath: endpoint.route,\n\t\t\t\t\t\t...endpoint.telemetry,\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: [],\n\t);\n}\n\n/**\n * What an entry starts OpenTelemetry with, decided at build time from the\n * process's edge to a `Telemetry` node.\n *\n * Only built for a process with that edge — every other process gets the\n * stub, which loads nothing — and only once the packages it needs resolve:\n * a process that uses the node and cannot load them fails the build with\n * {@link TelemetryPackagesMissing}.\n */\nexport interface TelemetryContext {\n\t/** `service.name` — the surface or worker; `OTEL_SERVICE_NAME` overrides it. */\n\tserviceName: string;\n\t/** `service.namespace` — the workspace the app is part of. */\n\tserviceNamespace?: string;\n\t/** The node's `ignorePaths`. */\n\tignorePaths: readonly string[];\n\t/** The node's `attributes`, on every span and log record. */\n\tattributes: Readonly<Record<string, string>>;\n\t/** Each route that says something of its own. */\n\troutes: readonly TelemetryRoute[];\n}\n\n/**\n * Every package `@geekmidas/telescope/instrumentation` loads at runtime.\n *\n * All of them, rather than one as a proxy: the production bundle follows each\n * import, and a single missing one fails the build rather than the telemetry.\n */\nexport const TELEMETRY_PACKAGES = [\n\t'@opentelemetry/api',\n\t'@opentelemetry/auto-instrumentations-node',\n\t'@opentelemetry/exporter-logs-otlp-http',\n\t'@opentelemetry/exporter-trace-otlp-http',\n\t'@opentelemetry/instrumentation-pino',\n\t'@opentelemetry/resources',\n\t'@opentelemetry/sdk-logs',\n\t'@opentelemetry/sdk-node',\n\t'@opentelemetry/sdk-trace-base',\n\t'@opentelemetry/sdk-trace-node',\n\t'@opentelemetry/semantic-conventions',\n] as const;\n\n/**\n * The directory of `name` as `node_modules` lookup finds it from `fromDir`,\n * symlinks resolved — or undefined.\n *\n * The directory walk alone, not `require.resolve`: that also searches\n * `NODE_PATH`, which a package manager's bin shim sets to its own store, so a\n * `gkm build` run through one would find packages the app never installed —\n * and the bundler, which does not look there, would then fail on them.\n */\nfunction packageDir(fromDir: string, name: string): string | undefined {\n\tfor (let dir = resolve(fromDir); ; dir = dirname(dir)) {\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\tif (dirname(dir) === dir) return undefined;\n\t}\n}\n\n/**\n * The telemetry packages that do not resolve the way the bundler will resolve\n * them — telescope from the app, and the OpenTelemetry packages from\n * telescope, where a peer is linked under pnpm, which need not be where the\n * app sees it. Empty when every one does.\n */\nexport function missingTelemetryPackages(appRoot: string): string[] {\n\tconst telescope = packageDir(appRoot, '@geekmidas/telescope');\n\tif (!telescope) return ['@geekmidas/telescope', ...TELEMETRY_PACKAGES];\n\n\treturn TELEMETRY_PACKAGES.filter((pkg) => !packageDir(telescope, pkg));\n}\n\n/**\n * An app uses a `Telemetry` construct and cannot load what it needs to.\n *\n * Failed at build, not at startup: a process that was given telemetry and\n * quietly ran without it is an outage nobody can see into.\n */\nexport class TelemetryPackagesMissing extends GkmError {\n\treadonly command: string;\n\n\tconstructor(\n\t\treadonly app: string,\n\t\treadonly missing: readonly string[],\n\t\t/** The app's directory, relative to where the command is run. */\n\t\treadonly dir: string,\n\t) {\n\t\tconst command = `pnpm --dir ${dir || '.'} add ${missing.join(' ')}`;\n\t\tsuper(\n\t\t\t`'${app}' uses a Telemetry construct, and ${missing.join(', ')} ` +\n\t\t\t\t`${missing.length === 1 ? 'does' : 'do'} not resolve from it — its ` +\n\t\t\t\t'server would start without exporting a span. Add them to the app ' +\n\t\t\t\t`and build again:\\n\\n ${command}\\n`,\n\t\t);\n\t\tthis.name = 'TelemetryPackagesMissing';\n\t\tthis.command = command;\n\t}\n}\n\n/**\n * The telemetry half of a build context: undefined for a process with no\n * edge to a `Telemetry` node, and — for one with an edge — what its entry\n * starts with, once every package it needs resolves.\n */\nexport function telemetryFor(options: {\n\t/** The node the process emits through — see `telemetryOf`. */\n\tnode: TelemetryDeclaration | undefined;\n\tappRoot: string;\n\t/** The app's name, for the error. */\n\tapp: string;\n\t/** Where `pnpm` is run from, for the error's command. */\n\tcwd?: string;\n\tserviceName: string;\n\tworkspaceName?: string;\n\troutes?: readonly TelemetryRoute[];\n}): TelemetryContext | undefined {\n\tconst { node } = options;\n\tif (!node) return undefined;\n\n\tconst missing = missingTelemetryPackages(options.appRoot);\n\tif (missing.length > 0) {\n\t\tthrow new TelemetryPackagesMissing(\n\t\t\toptions.app,\n\t\t\tmissing,\n\t\t\trelative(options.cwd ?? process.cwd(), options.appRoot),\n\t\t);\n\t}\n\n\treturn {\n\t\tserviceName: options.serviceName,\n\t\t...(options.workspaceName && { serviceNamespace: options.workspaceName }),\n\t\tignorePaths: [...(node.ignorePaths ?? [])],\n\t\tattributes: { ...node.attributes },\n\t\troutes: [...(options.routes ?? [])],\n\t};\n}\n\nconst HEADER = `/**\n * Generated by gkm, for the production entry and the \\`gkm dev\\` one alike.\n *\n * Starts OpenTelemetry when OTEL_EXPORTER_OTLP_ENDPOINT names a collector, and\n * does nothing otherwise: without it, the telemetry packages are not loaded.\n * The standard OTEL_* variables (OTEL_TRACES_SAMPLER, OTEL_TRACES_SAMPLER_ARG,\n * OTEL_EXPORTER_OTLP_HEADERS, OTEL_RESOURCE_ATTRIBUTES, OTEL_SERVICE_NAME)\n * configure the rest.\n */\n\nimport type { MiddlewareHandler } from 'hono';\n\nexport interface StartTelemetryOptions {\n /** Requests whose spans would only be noise: health checks, by default. */\n ignorePaths?: string[];\n /**\n * The API's own sites — the origins its CORS allows — read on each request.\n * Their \\`traceparent\\` is continued, as is an internal caller's; anyone\n * else's starts a new trace linked to the one it claimed.\n */\n trustedOrigins?: () => readonly string[];\n}\n`;\n\n/** `/users/:id` as a pattern over a request's path. */\nfunction routePattern(path: string): string {\n\tconst body = path\n\t\t.split('/')\n\t\t.map((segment) => {\n\t\t\tif (segment.startsWith(':')) return '[^/]+';\n\t\t\tif (segment === '*') return '.*';\n\t\t\treturn segment.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\t\t})\n\t\t.join('/');\n\treturn `^${body}/?$`;\n}\n\n/**\n * The entry's `telemetry.ts`: a `startTelemetry()` the server awaits before it\n * imports the app, so the libraries the app loads are instrumented. It returns\n * the Hono middleware that traces each request, or undefined when telemetry is\n * off — the server mounts it ahead of every route.\n *\n * Without a context — a process with no edge to a `Telemetry` node — it is a\n * stub that loads nothing and says nothing: telemetry is not something that\n * process was given.\n *\n * Failing to start telemetry warns (a named `TelemetryUnavailable`, through\n * `process.emitWarning`) and never stops the server: an outage in observability\n * is not a reason to have an outage in the service.\n */\nexport function generateTelemetryModule(\n\ttelemetry: TelemetryContext | undefined,\n): string {\n\tif (!telemetry) {\n\t\treturn `${HEADER}\n// This process has no Telemetry construct, so there is nothing to start.\nexport async function startTelemetry(\n _options: StartTelemetryOptions = {},\n): Promise<MiddlewareHandler | undefined> {\n return undefined;\n}\n`;\n\t}\n\n\tconst options = [\n\t\t`serviceName: ${JSON.stringify(telemetry.serviceName)},`,\n\t\t...(telemetry.serviceNamespace\n\t\t\t? [`serviceNamespace: ${JSON.stringify(telemetry.serviceNamespace)},`]\n\t\t\t: []),\n\t\t// The stage the deploy set, so one service's stages stay apart.\n\t\t'deploymentEnvironment: process.env.STAGE,',\n\t\t...(Object.keys(telemetry.attributes).length\n\t\t\t? [`resourceAttributes: ${JSON.stringify(telemetry.attributes)},`]\n\t\t\t: []),\n\t\t// The exporters read OTEL_EXPORTER_OTLP_* themselves, and the SDK reads\n\t\t// OTEL_TRACES_SAMPLER — so no endpoint and no ratio are printed here.\n\t\t// The server's own shutdown decides when the process exits.\n\t\t'handleSignals: false,',\n\t\t// Neither is left to module-load hooks, which see nothing inside a\n\t\t// bundle: @geekmidas/logger emits each record through the logs API\n\t\t// itself, and the middleware returned below opens each request's span.\n\t\t// Hooked as well where they can be, every record and request would be\n\t\t// sent twice.\n\t\t'instrumentPino: false,',\n\t\t'incomingHttpSpans: false,',\n\t];\n\n\tconst routes = telemetry.routes.map((route) => ({\n\t\tmethod: route.method.toUpperCase(),\n\t\tpattern: routePattern(route.path),\n\t\t...(route.ignore ? { ignore: true } : {}),\n\t\t...(route.attributes && Object.keys(route.attributes).length\n\t\t\t? { attributes: route.attributes }\n\t\t\t: {}),\n\t}));\n\tconst withAttributes = routes.some((route) => 'attributes' in route);\n\n\treturn `${HEADER}\n/** Telemetry was asked for and cannot start. The server runs without it. */\nexport class TelemetryUnavailable extends Error {\n constructor(readonly reason: string, options?: { cause?: unknown }) {\n super(\n \\`OTEL_EXPORTER_OTLP_ENDPOINT is set, but \\${reason} This server exports no traces or logs until that is fixed.\\`,\n options,\n );\n this.name = 'TelemetryUnavailable';\n }\n}\n\n/** The Telemetry construct's own ignored paths, beside the entry's. */\nconst IGNORE_PATHS: string[] = ${JSON.stringify(telemetry.ignorePaths)};\n\n/** Each route's own .telemetry({ ignore, attributes }). */\nconst ROUTES: {\n method: string;\n pattern: string;\n ignore?: boolean;\n attributes?: Record<string, string>;\n}[] = ${JSON.stringify(routes)};\n\nconst MATCHERS = ROUTES.map((route) => ({ ...route, regex: new RegExp(route.pattern) }));\n\nfunction routeOf(method: string, path: string) {\n return MATCHERS.find(\n (route) => (route.method === method || route.method === 'ALL' || route.method === 'ANY') && route.regex.test(path),\n );\n}\n\nexport async function startTelemetry(\n options: StartTelemetryOptions = {},\n): Promise<MiddlewareHandler | undefined> {\n if (!process.env.OTEL_EXPORTER_OTLP_ENDPOINT) return undefined;\n\n let instrumentation;\n try {\n instrumentation = await import('@geekmidas/telescope/instrumentation');\n } catch (cause) {\n process.emitWarning(\n new TelemetryUnavailable(\n '@geekmidas/telescope/instrumentation or an @opentelemetry package it needs could not be loaded. Install them in the app and rebuild.',\n { cause },\n ),\n );\n return undefined;\n }\n\n instrumentation.setupTelemetry({\n ${options.join('\\n ')}\n });\n\n // Flush what is buffered when the process is told to stop. When nothing\n // else handles the signal, re-raise it once flushed, so the process still\n // stops the way it would have without this listener.\n for (const signal of ['SIGTERM', 'SIGINT'] as const) {\n process.once(signal, () => {\n void instrumentation.flushTelemetry().finally(() => {\n if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);\n });\n });\n }\n\n // A SERVER span per request, opened by the app itself rather than by\n // hooking node:http: \\`GET /users/:id\\`, continuing an incoming traceparent\n // from the API's own sites and internal callers (a new, linked trace from\n // anyone else), with the handler — its logs, fetches and queries — running\n // inside it.\n const spans = instrumentation.honoTelemetryMiddleware({\n ignorePaths: [...(options.ignorePaths ?? []), ...IGNORE_PATHS],\n trustedOrigins: options.trustedOrigins,\n ...(MATCHERS.some((route) => route.ignore)\n ? { shouldSkip: (c) => routeOf(c.req.method, c.req.path)?.ignore === true }\n : {}),\n });\n${\n\twithAttributes\n\t\t? `\n // A route's own attributes, on the span the middleware just opened.\n const { trace } = await import('@opentelemetry/api');\n return (c, next) =>\n spans(c, async () => {\n const attributes = routeOf(c.req.method, c.req.path)?.attributes;\n if (attributes) trace.getActiveSpan()?.setAttributes(attributes);\n await next();\n });\n`\n\t\t: ` return spans;\n`\n}}\n`;\n}\n\n/**\n * What an entry starts telemetry with, before it imports the app — shared by\n * the production server, a self-serving surface's server and the `gkm dev`\n * entry, so the three cannot start it differently. Defines `requestSpans`.\n */\nexport function startTelemetryCode(ignorePaths: readonly string[]): string {\n\treturn `// The API's own sites, known once the app has read its configuration: the\n// origins its CORS allows are the ones whose trace context is continued.\nlet trustedOrigins: readonly string[] = [];\n\n// Before the app is imported, so the libraries it loads are instrumented.\nconst { startTelemetry } = await import('./telemetry.js');\nconst requestSpans = await startTelemetry({\n ignorePaths: ${JSON.stringify(ignorePaths)},\n trustedOrigins: () => trustedOrigins,\n});\n`;\n}\n\n/** Mounts `requestSpans` on `app` ahead of every route. */\nexport function mountRequestSpansCode(app: string): string {\n\treturn `// The span middleware goes on before any route, so every request runs in it.\nif (requestSpans) ${app}.use('*', requestSpans);\n`;\n}\n\n/** Writes the entry's `telemetry.ts` beside it. */\nexport async function writeTelemetryModule(\n\toutputDir: string,\n\ttelemetry: TelemetryContext | undefined,\n): Promise<void> {\n\tawait mkdir(outputDir, { recursive: true });\n\tawait writeFile(\n\t\tjoin(outputDir, 'telemetry.ts'),\n\t\tgenerateTelemetryModule(telemetry),\n\t);\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Endpoint } from '@geekmidas/constructs/endpoints';\nimport type { BuildContext } from '../build/types';\nimport type { RouteInfo } from '../types';\nimport type { StorageDrivers } from './drivers';\nimport {\n\tConstructGenerator,\n\ttype GeneratedConstruct,\n\ttype GeneratorOptions,\n} from './Generator';\nimport {\n\tmountRequestSpansCode,\n\tstartTelemetryCode,\n\twriteTelemetryModule,\n} from './telemetry';\n\n/**\n * How a generated entry gets its logger and environment parser.\n *\n * From the surface it serves, when there is one: the surface holds both as\n * *objects*, and discovery already recorded which module declares it, so the\n * entry imports that module and reads them off it.\n *\n * The alternative — the shape this replaces — was naming both in config as\n * module paths, `envParser: './config/env#envParser'`, and printing an import\n * for each. Two strings per app, checked by nothing, describing files the\n * surface was already holding the contents of.\n *\n * Falls back to the configured paths for an app that declares no surface.\n */\nexport function runtimeFor(\n\tcontext: BuildContext,\n\tfromDir: string,\n\t/**\n\t * The construct that owns the thing being generated.\n\t *\n\t * An endpoint's surface, or the worker that handed out the cron factory.\n\t * Omitted for the app entry itself, which belongs to the primary surface.\n\t */\n\towner?: string,\n): { imports: string; bindings: string } {\n\tconst module = owner\n\t\t? (context.owners?.[owner] ?? context.surface?.module)\n\t\t: context.surface?.module;\n\n\tif (module) {\n\t\tconst specifier = importSpecifier(fromDir, module.specifier);\n\n\t\t// Bound to the same names the rest of the entry already uses, so what\n\t\t// changes is where they come from and nothing else.\n\t\treturn {\n\t\t\timports: `import { ${module.exportName} as __surface } from '${specifier}';`,\n\t\t\tbindings: [\n\t\t\t\t'// What this construct was declared with. Objects, not module paths:',\n\t\t\t\t'// the entry imports the owner, so there is nothing to print.',\n\t\t\t\t'const envParser = __surface.envParser;',\n\t\t\t\t'const logger = __surface.logger;',\n\t\t\t].join('\\n'),\n\t\t};\n\t}\n\n\t// No fallback. Every runnable comes from a factory a `RestApi` or a `Worker`\n\t// handed out, and that construct holds the objects — so there is no longer a\n\t// case where the only thing we know about a logger is a module path somebody\n\t// typed into config.\n\tthrow new Error(\n\t\t`No owner to take a logger and an environment parser from${\n\t\t\towner ? ` for \"${owner}\"` : ''\n\t\t}. Build it from a \\`RestApi\\` or a \\`Worker\\`.`,\n\t);\n}\n\n/** A relative specifier ESM will accept: always prefixed, never bare. */\nfunction importSpecifier(fromDir: string, target: string): string {\n\tconst rel = relative(fromDir, target).replace(/\\.ts$/, '.js');\n\n\treturn rel.startsWith('.') ? rel : `./${rel}`;\n}\n\n/**\n * CORS for a surface, derived rather than hand-written.\n *\n * Who may call a surface is already in the graph — every construct that\n * declared an edge to it — and reaches the process as one comma-separated\n * value. An application that maintained this by hand maintained a list that was\n * wrong in two directions at once: it trusted origins nothing was serving, and\n * it could not name hosts a deploy had not chosen yet.\n *\n * Only the parts a graph cannot answer are configurable, and every one has a\n * default: a surface that says nothing about CORS still gets it.\n */\nexport function corsFor(surface: BuildContext['surface']): {\n\timports: string;\n\tsetup: string;\n} {\n\tif (!surface) return { imports: '', setup: '' };\n\n\tconst cors = surface.cors ?? {};\n\t// `traceparent` and `tracestate` always: a site's client sends them when\n\t// its telemetry is on, and a preflight that refused them would fail every\n\t// request it makes rather than only its tracing. The API decides whether\n\t// to continue the trace (it does only for these same origins), so allowing\n\t// the headers grants nothing on its own.\n\tconst allowHeaders = [\n\t\t...new Set([\n\t\t\t'content-type',\n\t\t\t'authorization',\n\t\t\t'traceparent',\n\t\t\t'tracestate',\n\t\t\t...(cors.allowHeaders ?? []),\n\t\t]),\n\t];\n\n\treturn {\n\t\timports: `import { cors } from 'hono/cors';\nimport { trustsOrigin } from '@geekmidas/constructs/endpoints';`,\n\t\tsetup: `\n // Who may call ${surface.id}, read off the graph rather than listed here.\n {\n const { origins } = envParser\n .create((get) => ({\n origins: get('${surface.trustedOriginsKey}')\n .string()\n .default('')\n .transform((value: string) =>\n value.split(',').map((origin) => origin.trim()).filter(Boolean),\n ),\n }))\n .parse();\n\n // The same origins are the ones whose trace context the request spans\n // continue — the server reads them back from \\`createApp\\`.\n trustedOrigins.push(...origins);\n\n // An exact origin, or any one label in place of a wildcard site's \\`*\\`.\n honoApp.use('*', cors({\n origin: (origin) => (trustsOrigin(origin, origins) ? origin : null),\n allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],\n allowHeaders: ${JSON.stringify(allowHeaders)},${\n\t\t\t\tcors.exposeHeaders\n\t\t\t\t\t? `\\n exposeHeaders: ${JSON.stringify(cors.exposeHeaders)},`\n\t\t\t\t\t: ''\n\t\t\t}\n credentials: ${cors.credentials ?? true},\n maxAge: ${cors.maxAge ?? 86400},\n }));\n }\n`,\n\t};\n}\n\nexport class EndpointGenerator extends ConstructGenerator<\n\tEndpoint<any, any, any, any, any, any, any, any, any, any, any, any>,\n\tRouteInfo[]\n> {\n\tisConstruct(\n\t\tvalue: any,\n\t): value is Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany\n\t> {\n\t\treturn Endpoint.isEndpoint(value);\n\t}\n\n\tasync build(\n\t\tcontext: BuildContext,\n\t\tconstructs: GeneratedConstruct<\n\t\t\tEndpoint<any, any, any, any, any, any, any, any, any, any, any, any>\n\t\t>[],\n\t\toutputDir: string,\n\t\toptions?: GeneratorOptions,\n\t): Promise<RouteInfo[]> {\n\t\tconst target = options?.target ?? 'aws';\n\t\tconst root = options?.root ?? process.cwd();\n\t\tconst enableOpenApi = options?.enableOpenApi || false;\n\t\tconst logger = console;\n\t\tconst routes: RouteInfo[] = [];\n\n\t\tif (constructs.length === 0) {\n\t\t\treturn routes;\n\t\t}\n\n\t\tif (target === 'server') {\n\t\t\t// Generate endpoints.ts and app.ts\n\t\t\tawait this.generateEndpointsFile(outputDir, constructs);\n\t\t\tconst appFile = await this.generateAppFile(outputDir, context);\n\n\t\t\troutes.push({\n\t\t\t\tpath: '*',\n\t\t\t\tmethod: 'ALL',\n\t\t\t\thandler: relative(root, appFile),\n\t\t\t\tauthorizer: 'none',\n\t\t\t});\n\n\t\t\tlogger.log(\n\t\t\t\t`Generated server with ${constructs.length} endpoints${enableOpenApi ? ' (OpenAPI enabled)' : ''}`,\n\t\t\t);\n\n\t\t\treturn routes;\n\t\t}\n\n\t\t// One Lambda per endpoint, behind an HTTP API.\n\t\tconst routesDir = join(outputDir, 'routes');\n\t\tawait mkdir(routesDir, { recursive: true });\n\n\t\tfor (const { key, construct, path } of constructs) {\n\t\t\tconst handlerFile = await this.generateHandlerFile(\n\t\t\t\troutesDir,\n\t\t\t\tpath.relative,\n\t\t\t\tkey,\n\t\t\t\tcontext,\n\t\t\t);\n\n\t\t\tconst routeInfo: RouteInfo = {\n\t\t\t\tpath: construct._path,\n\t\t\t\tmethod: construct.method,\n\t\t\t\thandler: relative(root, handlerFile).replace(/\\.ts$/, '.handler'),\n\t\t\t\ttimeout: construct.timeout,\n\t\t\t\tmemorySize: construct.memorySize,\n\t\t\t\tenvironment: await construct.getEnvironment({\n\t\t\t\t\tmarkOptional: context.markOptional,\n\t\t\t\t}),\n\t\t\t\tdependencies: construct.constructs,\n\t\t\t\tauthorizer: construct.authorizer?.name ?? 'none',\n\t\t\t};\n\n\t\t\troutes.push(routeInfo);\n\t\t\tlogger.log(`Generated handler for ${routeInfo.method} ${routeInfo.path}`);\n\t\t}\n\n\t\treturn routes;\n\t}\n\n\tprivate async generateHandlerFile(\n\t\toutputDir: string,\n\t\tsourceFile: string,\n\t\texportName: string,\n\t\tcontext: BuildContext,\n\t): Promise<string> {\n\t\tconst handlerPath = join(outputDir, `${exportName}.ts`);\n\n\t\tconst relativePath = relative(dirname(handlerPath), sourceFile);\n\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\tawait writeFile(\n\t\t\thandlerPath,\n\t\t\tthis.generateAWSApiGatewayV2Handler(\n\t\t\t\timportPath,\n\t\t\t\texportName,\n\t\t\t\tcontext.storageDrivers,\n\t\t\t),\n\t\t);\n\t\treturn handlerPath;\n\t}\n\n\tprivate async generateEndpointsFile(\n\t\toutputDir: string,\n\t\tendpoints: GeneratedConstruct<\n\t\t\tEndpoint<any, any, any, any, any, any, any, any, any, any, any, any>\n\t\t>[],\n\t): Promise<string> {\n\t\tconst endpointsFileName = 'endpoints.ts';\n\t\tconst endpointsPath = join(outputDir, endpointsFileName);\n\n\t\t// Group imports by file\n\t\tconst importsByFile = new Map<string, string[]>();\n\n\t\tfor (const { path, key } of endpoints) {\n\t\t\tconst relativePath = relative(dirname(endpointsPath), path.relative);\n\t\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\t\tif (!importsByFile.has(importPath)) {\n\t\t\t\timportsByFile.set(importPath, []);\n\t\t\t}\n\t\t\timportsByFile.get(importPath)?.push(key);\n\t\t}\n\n\t\t// Generate import statements for endpoints\n\t\tconst endpointImports = Array.from(importsByFile.entries())\n\t\t\t.map(\n\t\t\t\t([importPath, exports]) =>\n\t\t\t\t\t`import { ${exports.join(', ')} } from '${importPath}';`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\tconst allExportNames = endpoints.map(({ key }) => key);\n\n\t\t// One registration for every build, production included: each endpoint\n\t\t// is served by HonoEndpoint, which is what `gkm dev` and a feature test\n\t\t// serve it with. Production used to generate its own handlers per\n\t\t// \"tier\", and each was a hand-copy of the adaptor that drifted from it —\n\t\t// a session left undefined, an HttpError answered 500, an auditor\n\t\t// hard-coded to undefined, cookies a handler set never sent.\n\t\tconst content = `import type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { HonoEndpoint } from '@geekmidas/constructs/hono';\nimport { Endpoint } from '@geekmidas/constructs/endpoints';\nimport { ServiceDiscovery } from '@geekmidas/services';\nimport type { Hono } from 'hono';\n${endpointImports}\n\nexport const endpoints: Endpoint<any, any, any, any, any, any, any, any, any, any, any, any>[] = [\n ${allExportNames.join(',\\n ')}\n];\n\nexport async function setupEndpoints(\n app: Hono,\n envParser: EnvironmentParser<any>,\n logger: Logger,\n enableOpenApi: boolean = true,\n): Promise<void> {\n const serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n\n // Configure OpenAPI options based on enableOpenApi flag\n const openApiOptions: any = enableOpenApi ? {\n docsPath: '/__docs',\n openApiOptions: {\n title: 'API Documentation',\n version: '1.0.0',\n description: 'Generated API documentation'\n }\n } : { docsPath: false };\n\n HonoEndpoint.addRoutes(endpoints, serviceDiscovery, app, openApiOptions);\n\n // Add Swagger UI if OpenAPI is enabled\n if (enableOpenApi) {\n try {\n const { swaggerUI } = await import('@hono/swagger-ui');\n app.get('/__docs/ui', swaggerUI({ url: '/__docs' }));\n } catch {\n // @hono/swagger-ui not installed, skip Swagger UI\n }\n }\n}\n`;\n\n\t\tawait writeFile(endpointsPath, content);\n\n\t\treturn endpointsPath;\n\t}\n\n\tprivate async generateAppFile(\n\t\toutputDir: string,\n\t\tcontext: BuildContext,\n\t): Promise<string> {\n\t\t// What both entries start telemetry from — the production server and\n\t\t// `gkm dev`'s — decided by the surface's edge to a `Telemetry` node.\n\t\tawait writeTelemetryModule(outputDir, context.telemetry);\n\n\t\t// Use production generator if in production mode\n\t\tif (context.production?.enabled) {\n\t\t\treturn this.generateProductionAppFile(outputDir, context);\n\t\t}\n\n\t\tconst appFileName = 'app.ts';\n\t\tconst appPath = join(outputDir, appFileName);\n\n\t\t// The logger and the env parser, from the surface that already holds them.\n\t\tconst runtime = runtimeFor(context, dirname(appPath));\n\n\t\t// Generate telescope imports and setup if enabled\n\t\tconst telescopeEnabled = context.telescope?.enabled;\n\t\tconst telescopeWebSocketEnabled = context.telescope?.websocket;\n\t\tconst usesExternalTelescope = !!context.telescope?.telescopePath;\n\n\t\t// Generate imports based on whether telescope is external or inline\n\t\tconst telescopeFromSurface =\n\t\t\t!!context.surface?.module && !usesExternalTelescope;\n\n\t\tlet telescopeImports = '';\n\t\tif (telescopeEnabled) {\n\t\t\tif (telescopeFromSurface) {\n\t\t\t\t// The entry already imports the surface, which may or may not have\n\t\t\t\t// been given a Telescope — an object, so only the running entry can\n\t\t\t\t// tell. The inline one stands in when it was not.\n\t\t\t\ttelescopeImports = `import { Telescope, InMemoryStorage } from '@geekmidas/telescope';\nimport { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;\n\t\t\t} else if (usesExternalTelescope) {\n\t\t\t\tconst relativeTelescopePath = relative(\n\t\t\t\t\tdirname(appPath),\n\t\t\t\t\tcontext.telescope?.telescopePath!,\n\t\t\t\t);\n\t\t\t\ttelescopeImports = `import ${context.telescope?.telescopeImportPattern} from '${relativeTelescopePath}';\nimport { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;\n\t\t\t} else {\n\t\t\t\ttelescopeImports = `import { Telescope, InMemoryStorage } from '@geekmidas/telescope';\nimport { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;\n\t\t\t}\n\t\t}\n\n\t\t// The database's read-only JSON API, from the declared database. The\n\t\t// client comes from the construct, so what it reads is by definition what\n\t\t// the handlers write to.\n\t\tconst databaseApi = context.databaseApi;\n\t\tconst databaseApiImports = databaseApi\n\t\t\t? `import { snifferContext } from '@geekmidas/constructs';\nimport { createIntrospectionHandler } from '@geekmidas/db/introspect';\nimport { ${databaseApi.database.exportName} as __introspectedDb } from '${importSpecifier(dirname(appPath), databaseApi.database.specifier)}';`\n\t\t\t: '';\n\n\t\t// Generate imports for server hooks\n\t\tconst cors = corsFor(context.surface);\n\t\tlet hooksImports = '';\n\t\tlet beforeSetupCall = '';\n\t\tlet afterSetupCall = '';\n\t\tif (context.hooks?.serverHooksPath) {\n\t\t\tconst relativeHooksPath = relative(\n\t\t\t\tdirname(appPath),\n\t\t\t\tcontext.hooks.serverHooksPath,\n\t\t\t);\n\t\t\thooksImports = `import * as serverHooks from '${relativeHooksPath}';`;\n\t\t\tbeforeSetupCall = `\n // Call beforeSetup hook if defined\n if (typeof serverHooks.beforeSetup === 'function') {\n await serverHooks.beforeSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t\tafterSetupCall = `\n // Call afterSetup hook if defined\n if (typeof serverHooks.afterSetup === 'function') {\n await serverHooks.afterSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t}\n\n\t\tconst telescopeWebSocketSetupCode = telescopeWebSocketEnabled\n\t\t\t? `\n // Setup WebSocket for real-time telescope updates\n try {\n const { createNodeWebSocket } = await import('@hono/node-ws');\n const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app: honoApp });\n // Add WebSocket route directly to main app (sub-app routes don't support WS upgrade)\n honoApp.get('${context.telescope?.path}/ws', upgradeWebSocket(() => ({\n onOpen: (_event: Event, ws: any) => {\n telescope.addWsClient(ws);\n },\n onClose: (_event: Event, ws: any) => {\n telescope.removeWsClient(ws);\n },\n onMessage: (event: MessageEvent, ws: any) => {\n try {\n const data = JSON.parse(event.data);\n if (data.type === 'ping') {\n ws.send(JSON.stringify({ type: 'pong' }));\n }\n } catch {\n // Ignore invalid messages\n }\n },\n })));\n // Store injectWebSocket for server entry to call after serve()\n (honoApp as any).__injectWebSocket = injectWebSocket;\n logger.info('Telescope WebSocket enabled');\n } catch (e) {\n logger.warn({ err: e }, 'WebSocket support not available - install @hono/node-ws for real-time updates');\n }\n`\n\t\t\t: '';\n\n\t\t// Generate telescope setup - either use external instance or create inline\n\t\tlet telescopeSetup = '';\n\t\tif (telescopeEnabled) {\n\t\t\tif (telescopeFromSurface || usesExternalTelescope) {\n\t\t\t\t// Use external telescope instance - no need to create one\n\t\t\t\ttelescopeSetup = `\n${telescopeWebSocketSetupCode}\n // Add telescope middleware (before endpoints to capture all requests)\n honoApp.use('*', createMiddleware(telescope));\n\n // Mount Telescope's JSON API\n const telescopeApi = createApi(telescope);\n honoApp.route('${context.telescope?.path}', telescopeApi);\n`;\n\t\t\t} else {\n\t\t\t\t// Create inline telescope instance\n\t\t\t\ttelescopeSetup = `\n // Setup Telescope for debugging/monitoring\n const telescopeStorage = new InMemoryStorage({ maxEntries: ${context.telescope?.maxEntries} });\n const telescope = new Telescope({\n enabled: true,\n path: '${context.telescope?.path}',\n ignorePatterns: ${JSON.stringify(context.telescope?.ignore)},\n recordBody: ${context.telescope?.recordBody},\n storage: telescopeStorage,\n });\n${telescopeWebSocketSetupCode}\n // Add telescope middleware (before endpoints to capture all requests)\n honoApp.use('*', createMiddleware(telescope));\n\n // Mount Telescope's JSON API\n const telescopeApi = createApi(telescope);\n honoApp.route('${context.telescope?.path}', telescopeApi);\n`;\n\t\t\t}\n\t\t}\n\n\t\tconst databaseApiSetup = databaseApi\n\t\t\t? `\n // The database's structure and rows as JSON, read-only, for whatever tool\n // the developer points at it. Dev only: it answers anyone who can reach the\n // port.\n const databaseApi = createIntrospectionHandler({\n db: await __introspectedDb.service.register({ envParser, context: snifferContext }),\n basePath: '${databaseApi.path}',\n });\n honoApp.all('${databaseApi.path}/*', (c) => databaseApi(c.req.raw));\n`\n\t\t\t: '';\n\n\t\tconst content = `/**\n * Generated server application\n *\n * ⚠️ WARNING: This is for LOCAL DEVELOPMENT ONLY\n * The subscriber polling mechanism is not production-ready.\n * For production, use AWS Lambda with SQS/SNS event sources.\n */\nimport { Hono } from 'hono';\nimport type { Hono as HonoType } from 'hono';\nimport { setupEndpoints } from './endpoints.js';\nimport { setupSubscribers } from './subscribers.js';\nimport { setupQueues } from './queues.js';\nimport { setupCrons } from './crons.js';\n${context.devProcessors ? \"import { setupProcessors } from './processors.js';\\n\" : ''}${runtime.imports}\n${telescopeImports}\n${databaseApiImports}\n${hooksImports}\n${cors.imports}\n${context.storageDrivers?.imports ?? ''}\n\n${runtime.bindings}\n${\n\ttelescopeEnabled && telescopeFromSurface\n\t\t? `// The surface's own Telescope, or the one \\`telescope\\` config describes.\nconst telescope =\n __surface.telescope ??\n new Telescope({\n enabled: true,\n path: '${context.telescope?.path}',\n ignorePatterns: ${JSON.stringify(context.telescope?.ignore)},\n recordBody: ${context.telescope?.recordBody},\n storage: new InMemoryStorage({ maxEntries: ${context.telescope?.maxEntries} }),\n });`\n\t\t: ''\n}\n\n${\n\tcontext.storageDrivers?.setup\n\t\t? `// Which drivers exist — storage, cache, events — is the entry point's\n// decision: the scheme in each injected URL picks one, so no construct and no\n// application module names a provider.\n${context.storageDrivers.setup}\n`\n\t\t: ''\n}\n${\n\tcontext.surface\n\t\t? `// Who this server is to Postgres: application_name on every connection.\nprocess.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};\n\n`\n\t\t: ''\n}export interface ServerApp {\n app: HonoType;\n /** The origins this API's CORS allows: its own sites. */\n trustedOrigins: readonly string[];\n start: (options?: {\n port?: number;\n /** Returns the server, so a shutdown can stop it taking requests. */\n serve: (app: HonoType, port: number) => unknown;\n }) => Promise<void>;\n}\n\n/**\n * Create and configure the Hono application\n *\n * @param app - Optional Hono app instance to configure (creates new one if not provided)\n * @param enableOpenApi - Enable OpenAPI documentation (default: true)\n * @returns Server app with configured Hono app and start function\n *\n * @example\n * // With Bun\n * import { createApp } from './.gkm/server/app.js';\n *\n * const { app, start } = await createApp();\n *\n * await start({\n * port: 3000,\n * serve: (app, port) => {\n * Bun.serve({ port, fetch: app.fetch });\n * }\n * });\n *\n * @example\n * // With Node.js (using @hono/node-server)\n * import { serve } from '@hono/node-server';\n * import { createApp } from './.gkm/server/app.js';\n *\n * const { app, start } = await createApp();\n *\n * await start({\n * port: 3000,\n * serve: (app, port) => {\n * serve({ fetch: app.fetch, port });\n * }\n * });\n */\nexport async function createApp(app?: HonoType, enableOpenApi: boolean = true): Promise<ServerApp> {\n const honoApp = app || new Hono();\n const trustedOrigins: string[] = [];\n${telescopeSetup}${cors.setup}${beforeSetupCall}${databaseApiSetup}${\n\tcontext.devProcessors\n\t\t? `\n // The file servers' processors this app holds, where the local edge sends\n // each pattern on their hosts. Ahead of the endpoints, so none shadows them.\n setupProcessors(honoApp, envParser);\n`\n\t\t: ''\n}\n // Setup HTTP endpoints\n await setupEndpoints(honoApp, envParser, logger, enableOpenApi);\n${afterSetupCall}\n\n return {\n app: honoApp,\n trustedOrigins,\n async start(options) {\n if (!options?.serve) {\n throw new Error(\n 'serve function is required. Pass a serve function for your runtime:\\\\n' +\n ' - Bun: (app, port) => Bun.serve({ port, fetch: app.fetch })\\\\n' +\n ' - Node: (app, port) => serve({ fetch: app.fetch, port })'\n );\n }\n\n const port = options.port ?? 3000;\n\n // Mount pushed subscribers' routes and start polled ones. What comes\n // back subscribes the routes, once the server can answer them.\n const subscribeForPush = await setupSubscribers(honoApp, envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start subscribers');\n return async (_port: number) => {};\n });\n\n // Start queue workers in background (non-blocking, local development only)\n await setupQueues(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start queue workers');\n });\n\n // Schedule this app's crons. Caught like the others: a scheduler that\n // cannot start is not a reason for the HTTP server not to.\n await setupCrons(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to schedule crons');\n });\n\n logger.info({ port }, 'Starting server');\n\n // Start HTTP server using provided serve function\n await options.serve(honoApp, port);\n\n logger.info({ port }, 'Server started');\n\n await subscribeForPush(port);\n }\n };\n}\n\n// Default export for convenience\nexport default createApp;\n`;\n\n\t\tawait writeFile(appPath, content);\n\n\t\treturn appPath;\n\t}\n\n\t/**\n\t * One Lambda, one endpoint — and no environment import.\n\t *\n\t * The endpoint was built from its surface, so it carries the parser the\n\t * adaptor needs. This used to read\n\t * `import { envParser } from '../../config/env'`, a line the build wrote\n\t * because a generator can print a module specifier and cannot print an\n\t * object. Nothing has to be printed now, which is also why nothing has to be\n\t * named in config.\n\t */\n\tprivate generateAWSApiGatewayV2Handler(\n\t\timportPath: string,\n\t\texportName: string,\n\t\tdrivers?: StorageDrivers,\n\t): string {\n\t\treturn `import { AmazonApiGatewayV2Endpoint } from '@geekmidas/constructs/aws';\nimport { ${exportName} } from '${importPath}';\n${drivers?.imports ?? ''}\n${drivers?.setup ? `\\n// The handler registers the drivers its target needs.\\n${drivers.setup}\\n` : ''}\nconst adapter = new AmazonApiGatewayV2Endpoint(${exportName});\n\nexport const handler = adapter.handler;\n`;\n\t}\n\n\t/**\n\t * Generate a production-optimized app.ts file\n\t * No dev tools (Telescope, Studio, WebSocket), includes health checks and graceful shutdown\n\t */\n\tprivate async generateProductionAppFile(\n\t\toutputDir: string,\n\t\tcontext: BuildContext,\n\t): Promise<string> {\n\t\tconst appFileName = 'app.ts';\n\t\tconst appPath = join(outputDir, appFileName);\n\n\t\t// The app entry belongs to the primary surface, so no owner is named.\n\t\tconst runtime = runtimeFor(context, dirname(appPath));\n\n\t\tconst production = context.production!;\n\t\tconst healthCheckPath = production.healthCheck;\n\t\tconst enableGracefulShutdown = production.gracefulShutdown;\n\t\tconst enableOpenApi = production.openapi;\n\t\tconst includeSubscribers = production.subscribers === 'include';\n\n\t\t// Generate imports for server hooks\n\t\tconst cors = corsFor(context.surface);\n\t\tlet hooksImports = '';\n\t\tlet beforeSetupCall = '';\n\t\tlet afterSetupCall = '';\n\t\tif (context.hooks?.serverHooksPath) {\n\t\t\tconst relativeHooksPath = relative(\n\t\t\t\tdirname(appPath),\n\t\t\t\tcontext.hooks.serverHooksPath,\n\t\t\t);\n\t\t\thooksImports = `import * as serverHooks from '${relativeHooksPath}';`;\n\t\t\tbeforeSetupCall = `\n // Call beforeSetup hook if defined\n if (typeof serverHooks.beforeSetup === 'function') {\n await serverHooks.beforeSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t\tafterSetupCall = `\n // Call afterSetup hook if defined\n if (typeof serverHooks.afterSetup === 'function') {\n await serverHooks.afterSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t}\n\n\t\t// Subscriber + queue setup code (background workers share the same flag)\n\t\tconst subscriberSetup = includeSubscribers\n\t\t\t? `\n // Mount pushed subscribers' routes and start polled ones. What comes\n // back subscribes the routes, once the server can answer them.\n const subscribeForPush = await setupSubscribers(honoApp, envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start subscribers');\n return async (_port: number) => {};\n });\n\n // Start queue workers in background\n await setupQueues(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start queue workers');\n });\n\n // Schedule this app's crons. Caught like the others: a scheduler that\n // cannot start is not a reason for the HTTP server not to.\n await setupCrons(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to schedule crons');\n });\n`\n\t\t\t: '';\n\n\t\tconst subscriberImport = includeSubscribers\n\t\t\t? `import { setupSubscribers } from './subscribers.js';\nimport { setupQueues } from './queues.js';\nimport { setupCrons } from './crons.js';`\n\t\t\t: '';\n\n\t\t// Graceful shutdown code\n\t\tconst gracefulShutdownCode = enableGracefulShutdown\n\t\t\t? `\n // Graceful shutdown: stop taking requests, let in-flight ones finish, then\n // close what constructs opened (database pools) — so a rolling deploy does\n // not leave the old task holding connections. Bounded by\n // GKM_SHUTDOWN_TIMEOUT_MS, 8s by default: under Docker's 10s stop timeout,\n // so the process exits on its own terms rather than being killed mid-drain.\n let isShuttingDown = false;\n\n const shutdown = async () => {\n if (isShuttingDown) return;\n isShuttingDown = true;\n const deadline = Number(process.env.GKM_SHUTDOWN_TIMEOUT_MS) || 8000;\n logger.info({ deadline }, 'Graceful shutdown initiated');\n setTimeout(() => {\n logger.warn({ deadline }, 'Shutdown deadline reached, exiting');\n process.exit(1);\n }, deadline).unref();\n await new Promise<void>((resolve) => {\n const close = (server as { close?: (done: () => void) => void } | undefined)?.close;\n if (typeof close === 'function') close.call(server, () => resolve());\n else resolve();\n });\n await runShutdownHooks((error) => logger.error({ err: error }, 'Shutdown hook failed'));\n process.exit(0);\n };\n\n process.on('SIGTERM', shutdown);\n process.on('SIGINT', shutdown);\n`\n\t\t\t: '';\n\n\t\tconst content = `/**\n * Generated production server application\n *\n * This is a production-optimized build without dev tools.\n * - No Telescope debugging dashboard\n * - No Studio database browser\n * - No WebSocket updates\n * - Includes health checks and graceful shutdown\n */\nimport { Hono } from 'hono';\nimport type { Hono as HonoType } from 'hono';\n${enableGracefulShutdown ? \"import { runShutdownHooks } from '@geekmidas/constructs';\\n\" : ''}import { setupEndpoints } from './endpoints.js';\n${subscriberImport}\n${runtime.imports}\n${runtime.bindings}\n${hooksImports}\n${cors.imports}\n${context.storageDrivers?.imports ?? ''}\n\n${\n\tcontext.storageDrivers?.setup\n\t\t? `// The entry point registers the drivers its target needs.\n${context.storageDrivers.setup}\n`\n\t\t: ''\n}\n${\n\tcontext.surface\n\t\t? `// Who this server is to Postgres: application_name on every connection.\nprocess.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};\n\n`\n\t\t: ''\n}export interface ServerApp {\n app: HonoType;\n /** The origins this API's CORS allows: its own sites. */\n trustedOrigins: readonly string[];\n start: (options?: {\n port?: number;\n serve: (app: HonoType, port: number) => void | Promise<void>;\n }) => Promise<void>;\n}\n\n/**\n * Create and configure the production Hono application\n */\nexport async function createApp(app?: HonoType): Promise<ServerApp> {\n const honoApp = app || new Hono();\n const trustedOrigins: string[] = [];\n\n // Health check endpoint (always first)\n honoApp.get('${healthCheckPath}', (c) => c.json({ status: 'ok', timestamp: Date.now() }));\n honoApp.get('/ready', (c) => c.json({ ready: true }));\n\n // An HttpError a handler or a session callback throws — a 401, a 404 —\n // answers with its own status, as it does under gkm dev. The optimized\n // handlers do not catch, so without this every one of them was a 500.\n // Anything else is a 500 that says nothing about why, and is logged.\n honoApp.onError((error, c) => {\n const http = error as {\n isHttpError?: boolean;\n statusCode?: number;\n statusMessage?: string;\n code?: string;\n details?: unknown;\n };\n if (http.isHttpError === true && typeof http.statusCode === 'number') {\n return c.json(\n {\n name: error.name,\n message: error.message,\n statusCode: http.statusCode,\n statusMessage: http.statusMessage,\n code: http.code,\n details: http.details,\n },\n http.statusCode as 500,\n );\n }\n logger.error({ err: error }, 'Unhandled error');\n return c.json({ message: 'Internal Server Error' }, 500);\n });\n${cors.setup}${beforeSetupCall}\n // Setup HTTP endpoints (OpenAPI: ${enableOpenApi})\n await setupEndpoints(honoApp, envParser, logger, ${enableOpenApi});\n${afterSetupCall}\n return {\n app: honoApp,\n trustedOrigins,\n async start(options) {\n if (!options?.serve) {\n throw new Error(\n 'serve function is required. Pass a serve function for your runtime:\\\\n' +\n ' - Bun: (app, port) => Bun.serve({ port, fetch: app.fetch })\\\\n' +\n ' - Node: (app, port) => serve({ fetch: app.fetch, port })'\n );\n }\n\n const port = options.port ?? Number(process.env.PORT) ?? 3000;\n let server: unknown;\n${gracefulShutdownCode}${subscriberSetup}\n logger.info({ port }, 'Starting production server');\n\n // Start HTTP server using provided serve function\n server = await options.serve(honoApp, port);\n\n logger.info({ port }, 'Production server started');\n${includeSubscribers ? '\\n await subscribeForPush(port);' : ''}\n }\n };\n}\n\n// Default export for convenience\nexport default createApp;\n`;\n\n\t\tawait writeFile(appPath, content);\n\n\t\t// Also generate the production server entry point\n\t\tawait this.generateProductionServerEntry(outputDir, context);\n\n\t\treturn appPath;\n\t}\n\n\t/**\n\t * Generate production server.ts entry point\n\t */\n\tprivate async generateProductionServerEntry(\n\t\toutputDir: string,\n\t\tcontext: BuildContext,\n\t): Promise<void> {\n\t\tconst serverPath = join(outputDir, 'server.ts');\n\n\t\t// `telemetry.ts` beside it was written with `app.ts`, for this entry\n\t\t// and the `gkm dev` one alike, which start it the same way.\n\t\tconst content = `#!/usr/bin/env node\n/**\n * Production server entry point\n * Generated by 'gkm build --production'\n */\nimport { serve } from '@hono/node-server';\nimport { Hono } from 'hono';\n\n${startTelemetryCode([context.production?.healthCheck ?? '/health', '/ready'])}\nconst { createApp } = await import('./app.js');\n\nconst port = Number(process.env.PORT) || 3000;\n\nconst app = new Hono();\n${mountRequestSpansCode('app')}\nconst created = await createApp(app);\ntrustedOrigins = created.trustedOrigins;\nconst { start } = created;\n\nawait start({\n port,\n serve: (app, port) => serve({ fetch: app.fetch, port }),\n});\n`;\n\n\t\tawait writeFile(serverPath, content);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAcA,IAAa,mCAAb,cAAsDA,eAAAA,SAAS;CACzC;CAArB,YAAY,YAA6B;EACxC,MACC,wEAAwE,WAAW,6DACpF;EAHoB,KAAA,aAAA;EAIpB,KAAK,OAAO;CACb;AACD;;AAGA,SAAgB,sBACf,WACS;CACT,IAAI,OAAO,cAAc,WAAW,OAAO,OAAO,SAAS;CAC3D,MAAM,EAAE,eAAe;CACvB,IAAI,CAAC,OAAO,SAAS,UAAU,KAAK,aAAa,KAAK,aAAa,GAClE,MAAM,IAAI,iCAAiC,UAAU;CAEtD,OAAO,iBAAiB,WAAW;AACpC;;;;;AAMA,SAAgB,cAAc,WAA8C;CAC3E,IAAI,CAAC,WAAW,OAAO,CAAC;CACxB,IAAI,cAAc,MAAM,OAAO,CAAC,aAAa;CAC7C,OAAO,CAAC,eAAe,OAAO,UAAU,UAAU,CAAC;AACpD;;AAGA,SAAgB,mBACf,OACqC;CACrC,IAAI,UAAU,KAAA,KAAa,UAAU,OAAO,OAAO,KAAA;CACnD,IAAI,UAAU,MAAM,OAAO;CAC3B,OAAO,EAAE,YAAY,OAAO,KAAK,EAAE;AACpC;;;;AClCA,SAAgB,eACf,WAKmB;CACnB,OAAO,UAAU,SAAS,aACzB,S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,QAAQ,CAAC,EAAE;;;;;;EAM7E,sBAAsB,KAAK,EAAE;;;;;;;;;;EAW7B,OAAA,GAAMG,iBAAAA,UAAAA,CAAU,YAAY,OAAO;CACpC;AACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"serverSetup-6bczKo49.mjs","names":[],"sources":["../src/compose/serverScript.ts","../src/compose/serverSetup.ts"],"sourcesContent":["/**\n * What `gkm compose:server` runs on the server, as root (through the admin\n * user's sudo). Plain bash, so `--dry-run` can print exactly what will run,\n * and safe to run again: every step changes only what is missing or wrong.\n *\n * Arguments, in order: the admin user (the one running sudo), the deploy\n * user, the SSH port, the deploy key's public line, and its comment.\n *\n * The last line it prints is `HOSTKEY=<fingerprint>` — the server's own\n * ed25519 host key, which the command checks the network's against before\n * pinning it for CI.\n */\nexport const SERVER_SCRIPT = String.raw`set -euo pipefail\nexport DEBIAN_FRONTEND=noninteractive\nADMIN=\"$1\"; DEPLOY=\"$2\"; SSH_PORT=\"$3\"; PUB=\"$4\"; COMMENT=\"$5\"\nsay() { echo \" $*\"; }\nfail() { echo \" ✗ $*\" >&2; exit 1; }\n\n. /etc/os-release\ncase \"$ID\" in\n\tubuntu | debian) ;;\n\t*) fail \"gkm sets up Ubuntu and Debian servers; this one is $ID.\" ;;\nesac\n\n# ── SSH: keys only, no root ────────────────────────────────────────────────\n# Before password logins are turned off, the admin must have a key to come\n# back with — otherwise this would lock them out.\nADMIN_HOME=\"$(getent passwd \"$ADMIN\" | cut -d: -f6)\"\n[ -s \"$ADMIN_HOME/.ssh/authorized_keys\" ] ||\n\tfail \"$ADMIN has no key in $ADMIN_HOME/.ssh/authorized_keys; turning off password logins would lock them out.\"\n# First match wins in sshd_config, and 00- sorts before what a provider ships\n# (cloud-init's 50-cloud-init.conf turns password logins back on).\ncat > /etc/ssh/sshd_config.d/00-gkm-hardening.conf <<'EOF'\n# Written by gkm compose:server.\nPermitRootLogin no\nPasswordAuthentication no\nKbdInteractiveAuthentication no\nEOF\n# The deploy migrates through an SSH tunnel to the server's loopback.\ncat > /etc/ssh/sshd_config.d/60-gkm-deploy.conf <<EOF\n# Written by gkm compose:server.\nMatch User $DEPLOY\n AllowTcpForwarding local\nEOF\nsshd -t\nsystemctl reload ssh 2>/dev/null || systemctl reload sshd\n# What sshd actually does now, whatever else is in its config.\nEFFECTIVE=\"$(sshd -T)\"\nfor setting in 'permitrootlogin no' 'passwordauthentication no' 'kbdinteractiveauthentication no'; do\n\tgrep -qx \"$setting\" <<<\"$EFFECTIVE\" || fail \"sshd still does not say '$setting'; another file in /etc/ssh overrides it.\"\ndone\nFORWARD=\"$(sshd -T -C \"user=$DEPLOY,host=localhost,addr=127.0.0.1\" | sed -n 's/^allowtcpforwarding //p')\"\ncase \"$FORWARD\" in\n\tyes | all | local) ;;\n\t*) fail \"sshd does not let $DEPLOY forward ports (allowtcpforwarding $FORWARD).\" ;;\nesac\nsay \"sshd: keys only, no root login; $DEPLOY may open local tunnels\"\n# Root is reached through the admin's sudo, which this script is running\n# under — so its password, the one a provider mails out, can go.\npasswd -l root >/dev/null\nsay \"root's password locked; $ADMIN's sudo is the way to root\"\n\n# ── Firewall: SSH, HTTP, HTTPS ─────────────────────────────────────────────\ncommand -v ufw >/dev/null || { apt-get update -qq && apt-get install -y -qq ufw >/dev/null; }\nufw default deny incoming >/dev/null\nufw default allow outgoing >/dev/null\nufw allow \"$SSH_PORT/tcp\" >/dev/null\nufw allow 80/tcp >/dev/null\nufw allow 443/tcp >/dev/null\nufw --force enable >/dev/null\nsay \"firewall: $SSH_PORT, 80, 443 in; everything out\"\nEXTRA=\"$(ufw status | awk 'NR > 4 && $1 != \"\" { print $1 }' | grep -vxE \"(($SSH_PORT|80|443)(/tcp)?|OpenSSH)\" | sort -u || true)\"\nif [ -n \"$EXTRA\" ]; then\n\tsay \"⚠ also open: $(echo $EXTRA). gkm uses none of them; close each with: sudo ufw delete allow <port>\"\nfi\n\n# ── Updates and bans ───────────────────────────────────────────────────────\napt-get update -qq\napt-get install -y -qq unattended-upgrades fail2ban >/dev/null\ncat > /etc/apt/apt.conf.d/20auto-upgrades <<'EOF'\nAPT::Periodic::Update-Package-Lists \"1\";\nAPT::Periodic::Unattended-Upgrade \"1\";\nEOF\ncat > /etc/fail2ban/jail.d/gkm.local <<EOF\n# Written by gkm compose:server.\n[sshd]\nenabled = true\nport = $SSH_PORT\nEOF\nsystemctl enable --now unattended-upgrades fail2ban >/dev/null 2>&1\nsystemctl restart fail2ban\nsay \"security updates install daily; fail2ban watches sshd\"\n\n# ── Docker, from Docker's own repository ───────────────────────────────────\nif ! command -v docker >/dev/null || ! docker compose version >/dev/null 2>&1; then\n\tsay \"installing Docker…\"\n\tapt-get install -y -qq ca-certificates curl >/dev/null\n\tinstall -m 0755 -d /etc/apt/keyrings\n\tcurl -fsSL \"https://download.docker.com/linux/$ID/gpg\" -o /etc/apt/keyrings/docker.asc\n\tchmod a+r /etc/apt/keyrings/docker.asc\n\techo \"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/$ID $VERSION_CODENAME stable\" \\\n\t\t> /etc/apt/sources.list.d/docker.list\n\tapt-get update -qq\n\tapt-get install -y -qq docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin >/dev/null\nfi\nsystemctl enable --now docker >/dev/null 2>&1\nsay \"docker $(docker version --format '{{.Server.Version}}')\"\n\n# ── Kernel: room for many open connections ─────────────────────────────────\n# Each client behind the edge is tracked twice by conntrack — the published\n# port, then the bridge to the app — and the default table, sized from memory,\n# fills long before memory does. When it is full, new connections are dropped\n# with nothing logged where anyone looks.\ncat > /etc/sysctl.d/60-gkm-connections.conf <<'EOF'\n# Written by gkm compose:server.\nnet.netfilter.nf_conntrack_max = 1048576\nnet.core.somaxconn = 65535\nnet.ipv4.tcp_max_syn_backlog = 65535\nfs.file-max = 2097152\nEOF\n# Buckets for the table, a quarter of its entries: from the next boot on, and\n# now.\necho \"options nf_conntrack hashsize=262144\" > /etc/modprobe.d/gkm-conntrack.conf\nmodprobe nf_conntrack\necho 262144 > /sys/module/nf_conntrack/parameters/hashsize 2>/dev/null || true\nsysctl --quiet --system\nsay \"kernel: $(sysctl -n net.netfilter.nf_conntrack_max) tracked connections, a backlog of $(sysctl -n net.core.somaxconn)\"\n\n# ── The deploy user: no password, no sudo, in the docker group ─────────────\nid \"$DEPLOY\" >/dev/null 2>&1 || adduser --disabled-password --gecos \"\" \"$DEPLOY\" >/dev/null\nusermod -aG docker \"$DEPLOY\"\nDEPLOY_HOME=\"$(getent passwd \"$DEPLOY\" | cut -d: -f6)\"\ninstall -d -m 700 -o \"$DEPLOY\" -g \"$DEPLOY\" \"$DEPLOY_HOME/.ssh\"\nAUTH=\"$DEPLOY_HOME/.ssh/authorized_keys\"\ntouch \"$AUTH\"\n# One managed line: this key (or an earlier one by the same name) replaced,\n# with nothing allowed but the commands and the tunnel the deploy uses.\nKEYBODY=\"$(awk '{ print $2 }' <<<\"$PUB\")\"\ngrep -v -F -e \"$KEYBODY\" -e \" $COMMENT\" \"$AUTH\" > \"$AUTH.new\" || true\necho \"restrict,port-forwarding $PUB\" >> \"$AUTH.new\"\nmv \"$AUTH.new\" \"$AUTH\"\nchown \"$DEPLOY:$DEPLOY\" \"$AUTH\"\nchmod 600 \"$AUTH\"\nsay \"user $DEPLOY (docker group), deploy key authorized with restrict,port-forwarding\"\nOTHERS=\"$(grep -v -F -e \"$KEYBODY\" \"$AUTH\" | grep -c . || true)\"\nif [ \"$OTHERS\" -gt 0 ]; then\n\tsay \"⚠ $AUTH holds $OTHERS other key(s). Review: sudo cat $AUTH\"\nfi\n\necho \"HOSTKEY=$(ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub | awk '{ print $2 }')\"\n`;\n\n/**\n * What runs as root to give a fresh server its admin — the guide's first\n * step, for a server only root can log in to yet: a sudo user, with root's\n * keys so the same key logs in. `adduser` asks for its password, which sudo\n * will ask for.\n */\nexport const ADMIN_SCRIPT = `set -euo pipefail\nADMIN=\"$1\"\nif ! id \"$ADMIN\" >/dev/null 2>&1; then\n\techo \" creating $ADMIN — choose the password sudo will ask for:\"\n\tadduser --gecos \"\" \"$ADMIN\"\nfi\nusermod -aG sudo \"$ADMIN\"\nHOME_DIR=\"$(getent passwd \"$ADMIN\" | cut -d: -f6)\"\ninstall -d -m 700 -o \"$ADMIN\" -g \"$ADMIN\" \"$HOME_DIR/.ssh\"\nAUTH=\"$HOME_DIR/.ssh/authorized_keys\"\ntouch \"$AUTH\"\n# The keys alone: a provider's options on root's lines (a command=\"…\" that\n# says \"log in as ubuntu\") would stop the admin's login too. A server root\n# logs in to with a password has none; ssh-copy-id brings the admin's.\n{ grep -oE '(ssh|ecdsa|sk)-[^ ]+ [A-Za-z0-9+/=]+( .*)?$' /root/.ssh/authorized_keys 2>/dev/null || true; } |\n\twhile IFS= read -r key; do\n\t\tgrep -qxF \"$key\" \"$AUTH\" || echo \"$key\" >> \"$AUTH\"\n\tdone\nchown \"$ADMIN:$ADMIN\" \"$AUTH\"\nchmod 600 \"$AUTH\"\necho \" $ADMIN is a sudo user, with root's SSH keys (if root had any)\"\n`;\n","/**\n * `gkm compose:server` — make a VPS ready for a stage's compose deploys, from\n * this machine, in one go.\n *\n * It logs in as the server's admin — a sudo user, never root — and, through\n * sudo, sets the server up the way a production VPS should be: SSH by key\n * only with root's login off, a firewall open on SSH, 80 and 443 alone,\n * security updates installed daily, fail2ban on sshd, and Docker from\n * Docker's own repository. It then creates the stage's deploy user (in the\n * docker group, no sudo, no password) and authorizes a deploy key on it that\n * may run commands and open the tunnel migrations use, nothing more.\n *\n * Off the server: it makes the deploy key pair here, pins the server's host\n * key — checked against the fingerprint the server reports of itself — and\n * gives both to the stage's GitHub environment as `DEPLOY_SSH_KEY` and\n * `DEPLOY_KNOWN_HOSTS`, which the generated deploy workflow reads. Last, it\n * logs in exactly as CI will, and checks Docker and the tunnel answer.\n *\n * A fresh server only root can log in to gets its admin first: as root —\n * with root's key, or its password on a brand-new server — it creates the\n * user, and `ssh-copy-id` puts your key on it when root had none to give.\n * Root's password is locked once the admin's sudo works.\n *\n * Once it has, the stage's state records that it is done (`server:compose`,\n * stamped with who and when) — nothing personal: the admin is whoever runs\n * it, with their own key.\n * Safe to run again: each step changes only what is missing or wrong.\n */\n\nimport { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join, resolve } from 'node:path';\nimport { loadWorkspaceConfig } from '../config';\nimport { describeActor } from '../deploy/actor';\nimport { type Gh, ghCli } from '../deploy/github';\nimport { DeployJournal } from '../deploy/journal';\nimport { createStateStore, type StateStore } from '../deploy/StateStore';\nimport { createComposeState } from '../deploy/state';\nimport { GkmError } from '../errors';\nimport { prompt } from '../prompt';\nimport { secretsStoreFor } from '../secrets/store.js';\nimport { assertDeployedStage } from '../workspace/stages.js';\nimport { type ComposeServer, composeServer } from './server';\nimport { ADMIN_SCRIPT, SERVER_SCRIPT } from './serverScript';\n\nexport interface ComposeServerSetupOptions {\n\t/** The deployed stage whose server this is. */\n\tstage: string;\n\t/**\n\t * The server's sudo user. Absent, the user `ssh` logs in to the server as\n\t * by default (`~/.ssh/config`, else this machine's) — asked for only when\n\t * that is root.\n\t */\n\tadmin?: string;\n\t/** The key the admin logs in with. Absent, `ssh`'s own choice. */\n\tidentity?: string;\n\t/** The deploy key pair. Default `~/.ssh/gkm-<project>-<stage>`. */\n\tkeyFile?: string;\n\t/** `owner/name`; defaults to the repository `gh` sees here. */\n\trepo?: string;\n\t/** `--no-github`: leave the GitHub environment alone. */\n\tgithub?: boolean;\n\t/** Print the plan and the script; connect to nothing. */\n\tdryRun?: boolean;\n\t/** Apply without asking first. */\n\tyes?: boolean;\n\tcwd?: string;\n}\n\n/** What a finished command ran: output kept, its exit code. */\nexport interface Ran {\n\tcode: number;\n\tstdout: string;\n\tstderr: string;\n}\n\n/**\n * Runs a program. `interactive` gives it this terminal's stdin and stderr —\n * for a password sudo or adduser asks — while stdout is still kept, and\n * echoed as it comes.\n */\nexport type Runner = (\n\tcommand: string,\n\targs: readonly string[],\n\toptions?: { input?: string; interactive?: boolean },\n) => Promise<Ran>;\n\nexport interface ComposeServerSetupDeps {\n\trun: Runner;\n\tgh: Gh;\n\t/** Ask the person at the terminal. */\n\task: (question: string) => Promise<string>;\n\t/** The stage's state; the workspace's own store when absent. */\n\tstate: StateStore;\n}\n\n/** The stage's record of its server, as `compose:server` last set it up. */\nexport const SERVER_RECORD = 'server:compose';\n\n/**\n * What `server:compose` holds: which server was set up. Who set it up, and\n * when, are the record's own `updatedBy` and `updatedAt`.\n */\nexport interface ServerRecordData {\n\thost: string;\n}\n\nexport interface ComposeServerSetupResult {\n\tserver: ComposeServer;\n\tadmin: string;\n\tkeyFile: string;\n\t/** The pinned host key line, as `known_hosts` holds it. Absent on a dry run. */\n\tknownHosts?: string;\n\t/** The repository whose environment was given the key. */\n\trepo?: string;\n}\n\n/** The admin named is root, whose login this command turns off. */\nexport class ComposeServerAdminIsRoot extends GkmError {\n\tconstructor() {\n\t\tsuper(\n\t\t\t\"The admin can't be root: setting up the server turns root's SSH login \" +\n\t\t\t\t'off. Name the sudo user you log in as (--admin <user>). A fresh ' +\n\t\t\t\t'server with only root gets one: run this again with the name it ' +\n\t\t\t\t\"should have, and gkm offers to create it with root's key.\",\n\t\t);\n\t\tthis.name = 'ComposeServerAdminIsRoot';\n\t}\n}\n\n/** The admin named is the deploy user, which has no sudo. */\nexport class ComposeServerAdminIsDeployUser extends GkmError {\n\tconstructor(readonly user: string) {\n\t\tsuper(\n\t\t\t`'${user}' is the stage's deploy user (deploy.compose.server), which ` +\n\t\t\t\t'gkm creates without sudo. Name the sudo user you log in as with --admin.',\n\t\t);\n\t\tthis.name = 'ComposeServerAdminIsDeployUser';\n\t}\n}\n\n/** No key logs the admin in, and nothing was done to make one. */\nexport class ComposeServerAdminUnreachable extends GkmError {\n\tconstructor(\n\t\treadonly target: string,\n\t\treadonly stderr: string,\n\t) {\n\t\tsuper(\n\t\t\t`Could not log in as ${target} with a key (ssh said: ${stderr.trim() || 'nothing'}). ` +\n\t\t\t\t`Check \\`ssh ${target}\\` works without a password — copy your key with ` +\n\t\t\t\t`\\`ssh-copy-id ${target}\\` — then run this again.`,\n\t\t);\n\t\tthis.name = 'ComposeServerAdminUnreachable';\n\t}\n}\n\n/**\n * The server was set up already, and this person cannot log in to it as\n * the admin they named. Root's login and passwords are off there, so only\n * an admin can let them in.\n */\nexport class ComposeServerAccessNeeded extends GkmError {\n\tconstructor(\n\t\treadonly target: string,\n\t\treadonly setUpBy: string,\n\t\treadonly setUpOn: string,\n\t) {\n\t\tsuper(\n\t\t\t`${target} can't log in with your key, and the server was set up by ${setUpBy} on ${setUpOn} — ` +\n\t\t\t\t'root and password logins are off there. Ask them, or another admin, to add your ' +\n\t\t\t\t`public key to ${target.split('@')[0]}'s ~/.ssh/authorized_keys (or create you a sudo ` +\n\t\t\t\t'user with it), then run this again.',\n\t\t);\n\t\tthis.name = 'ComposeServerAccessNeeded';\n\t}\n}\n\n/** `ssh-keygen` could not make the deploy key pair. */\nexport class DeployKeyNotMade extends GkmError {\n\tconstructor(\n\t\treadonly keyFile: string,\n\t\treadonly stderr: string,\n\t) {\n\t\tsuper(\n\t\t\t`Could not make the deploy key ${keyFile} (ssh-keygen said: ${stderr.trim() || 'nothing'}). ` +\n\t\t\t\t'Pass another path with --key-file.',\n\t\t);\n\t\tthis.name = 'DeployKeyNotMade';\n\t}\n}\n\n/** The script on the server stopped before it finished. */\nexport class ComposeServerSetupFailed extends GkmError {\n\tconstructor(\n\t\treadonly target: string,\n\t\treadonly code: number,\n\t) {\n\t\tsuper(\n\t\t\t`Setting up ${target} stopped (exit ${code}); its output is above. ` +\n\t\t\t\t'Fix what it names and run this again — every step it already ' +\n\t\t\t\t'finished is left as it is.',\n\t\t);\n\t\tthis.name = 'ComposeServerSetupFailed';\n\t}\n}\n\n/** The host key the network shows is not the one the server holds. */\nexport class ComposeServerHostKeyMismatch extends GkmError {\n\tconstructor(\n\t\treadonly host: string,\n\t\treadonly server: string,\n\t\treadonly scanned: string,\n\t) {\n\t\tsuper(\n\t\t\t`${host}'s host key is ${server} on the server, but ${scanned || 'nothing'} ` +\n\t\t\t\t'over the network. Something between here and the server answered for ' +\n\t\t\t\t'it, or the server is not the one you logged in to. Nothing was given ' +\n\t\t\t\t'to GitHub; find out why before running this again.',\n\t\t);\n\t\tthis.name = 'ComposeServerHostKeyMismatch';\n\t}\n}\n\n/** The deploy key logged in, but cannot do what a deploy does. */\nexport class ComposeServerCheckFailed extends GkmError {\n\tconstructor(\n\t\treadonly target: string,\n\t\treadonly check: 'docker' | 'tunnel',\n\t\treadonly output: string,\n\t) {\n\t\tsuper(\n\t\t\tcheck === 'docker'\n\t\t\t\t? `The deploy key can't run docker as ${target} (ssh said: ${output.trim() || 'nothing'}).`\n\t\t\t\t: `The deploy key can't open a tunnel as ${target} (got: ${output.trim() || 'nothing'}). ` +\n\t\t\t\t\t\t\"Check its line in the deploy user's authorized_keys says \" +\n\t\t\t\t\t\t'restrict,port-forwarding, and that sshd allows it forwarding.',\n\t\t);\n\t\tthis.name = 'ComposeServerCheckFailed';\n\t}\n}\n\n/** `'…'`, for a value in a command line the remote shell reads. */\nfunction shellQuote(value: string): string {\n\treturn `'${value.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\n/**\n * The remote command that runs `script` with `args`: written to a temporary\n * file (so the script keeps the terminal for any password it asks), run,\n * and removed. `sudo` for everything but root.\n */\nexport function remoteCommand(\n\tscript: string,\n\targs: readonly string[],\n\tsudo: boolean,\n): string {\n\tconst encoded = Buffer.from(script).toString('base64');\n\treturn [\n\t\t`f=\"$(mktemp)\"`,\n\t\t`echo ${encoded} | base64 -d > \"$f\"`,\n\t\t`${sudo ? 'sudo ' : ''}bash \"$f\" ${args.map(shellQuote).join(' ')}; s=$?`,\n\t\t`rm -f \"$f\"`,\n\t\t'exit $s',\n\t].join('; ');\n}\n\nfunction sshOptions(server: ComposeServer): string[] {\n\treturn ['-o', 'ConnectTimeout=20', '-p', String(server.port)];\n}\n\n/** How the admin (or root) logs in: the server's options and their key. */\nfunction loginOptions(server: ComposeServer, identity?: string): string[] {\n\treturn [\n\t\t...sshOptions(server),\n\t\t...(identity ? ['-i', identity, '-o', 'IdentitiesOnly=yes'] : []),\n\t];\n}\n\n/** `user@host`, as `ssh` takes it. */\nfunction at(user: string, host: string): string {\n\treturn `${user}@${host}`;\n}\n\n/** The real runner: the system's programs. */\nexport const systemRunner: Runner = (command, args, options = {}) =>\n\tnew Promise((resolve, reject) => {\n\t\tconst child = spawn(command, args, {\n\t\t\tstdio: [\n\t\t\t\toptions.interactive ? 'inherit' : 'pipe',\n\t\t\t\t'pipe',\n\t\t\t\toptions.interactive ? 'inherit' : 'pipe',\n\t\t\t],\n\t\t\ttimeout: options.interactive ? undefined : 60_000,\n\t\t});\n\t\tlet stdout = '';\n\t\tlet stderr = '';\n\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\tstdout += chunk.toString();\n\t\t\tif (options.interactive) process.stdout.write(chunk);\n\t\t});\n\t\tchild.stderr?.on('data', (chunk: Buffer) => {\n\t\t\tstderr += chunk.toString();\n\t\t});\n\t\tchild.on('error', reject);\n\t\tchild.on('close', (code) => resolve({ code: code ?? 1, stdout, stderr }));\n\t\t// A program that exits without reading all its input closes the pipe\n\t\t// under the write: EPIPE. Its exit code already says how it went, and\n\t\t// unheard, the error would be thrown from nowhere.\n\t\tchild.stdin?.on('error', () => {});\n\t\tif (child.stdin) child.stdin.end(options.input ?? '');\n\t});\n\n/** Whether `answer` is a yes, `fallback` when nothing was typed. */\nfunction isYes(answer: string, fallback: boolean): boolean {\n\tconst value = answer.trim().toLowerCase();\n\treturn value === '' ? fallback : value === 'y' || value === 'yes';\n}\n\n/** The SHA256 fingerprint of each key in `keys`, by `ssh-keygen -lf -`. */\nasync function fingerprints(run: Runner, keys: string): Promise<string[]> {\n\tconst { stdout } = await run('ssh-keygen', ['-lf', '-'], { input: keys });\n\treturn stdout\n\t\t.split('\\n')\n\t\t.map((line) => line.split(' ')[1])\n\t\t.filter((value): value is string => Boolean(value));\n}\n\n/** The default deploy key pair for a stage. */\nexport function defaultKeyFile(project: string, stage: string): string {\n\treturn join(homedir(), '.ssh', `gkm-${project}-${stage}`);\n}\n\n/** `gkm compose:server`. */\nexport async function composeServerCommand(\n\toptions: ComposeServerSetupOptions,\n\tdeps: Partial<ComposeServerSetupDeps> = {},\n): Promise<ComposeServerSetupResult> {\n\tconst run = deps.run ?? systemRunner;\n\tconst gh = deps.gh ?? ghCli;\n\tconst ask =\n\t\tdeps.ask ??\n\t\t((question: string) =>\n\t\t\tprompt(question, {\n\t\t\t\tinstead: 'Name the server user with --admin and pass --yes.',\n\t\t\t}));\n\tconst github = options.github !== false;\n\tconst { stage } = options;\n\n\tconst cwd = resolve(options.cwd ?? process.cwd());\n\tconst { workspace } = await loadWorkspaceConfig(cwd);\n\tassertDeployedStage(workspace.stages, stage);\n\tconst server = composeServer({\n\t\tstage,\n\t\tlocal: false,\n\t\tconfig: workspace.deploy?.compose?.server,\n\t\tcustom: (await (await secretsStoreFor(workspace, stage)).read(stage))\n\t\t\t?.custom,\n\t})!;\n\n\t// Whether this server was set up before, by whom and when.\n\tconst state =\n\t\tdeps.state ??\n\t\t(await createStateStore({\n\t\t\tconfig: workspace.state,\n\t\t\tworkspaceRoot: workspace.root,\n\t\t\tworkspaceName: workspace.name,\n\t\t\tnamespace: workspace.deploy?.namespace,\n\t\t}));\n\tconst record = (await state.read(stage))?.resources[SERVER_RECORD];\n\tconst done =\n\t\t(record?.data as ServerRecordData | undefined)?.host === server.host\n\t\t\t? record\n\t\t\t: undefined;\n\n\t// The admin's login: `--admin`/`--identity`, or what `ssh` itself would\n\t// use for this host — read with `ssh -G`, which connects to nothing.\n\tconst identity = options.identity ? resolve(options.identity) : undefined;\n\tconst asAdmin = loginOptions(server, identity);\n\tconst sshUser =\n\t\t(await run('ssh', ['-G', ...asAdmin, server.host])).stdout.match(\n\t\t\t/^user (\\S+)$/m,\n\t\t)?.[1] ?? '';\n\tconst admin = (\n\t\toptions.admin ??\n\t\t(sshUser && sshUser !== 'root'\n\t\t\t? sshUser\n\t\t\t: await ask(`The sudo user you log in to ${server.host} as (not root): `))\n\t).trim();\n\tif (!admin || admin === 'root') throw new ComposeServerAdminIsRoot();\n\tif (admin === server.user) throw new ComposeServerAdminIsDeployUser(admin);\n\n\tconst keyFile = resolve(\n\t\toptions.keyFile ?? defaultKeyFile(workspace.name, stage),\n\t);\n\tconst comment = `gkm-${workspace.name}-${stage}-deploy`;\n\tconst repo = github\n\t\t? (options.repo ??\n\t\t\tgh(['repo', 'view', '--json', 'nameWithOwner', '-q', '.nameWithOwner']))\n\t\t: undefined;\n\tconst adminTarget = at(admin, server.host);\n\tconst deployTarget = at(server.user, server.host);\n\n\tconsole.log(`\\n🖥 Server for stage \"${stage}\"\\n`);\n\tconsole.log(` Server: ${server.host} (ssh port ${server.port})`);\n\tconsole.log(\n\t\t` Admin: ${admin} — logs in with ${identity ?? 'your SSH key'}, runs sudo${options.admin ? '' : ' (your SSH login)'}`,\n\t);\n\tconsole.log(\n\t\t` Deploy user: ${server.user} — docker group, no sudo, no password`,\n\t);\n\tconsole.log(\n\t\t` Deploy key: ${keyFile}${existsSync(keyFile) ? '' : ' (new, made here)'}`,\n\t);\n\tconsole.log(\n\t\t` GitHub: ${repo ? `environment \"${stage}\" of ${repo}: DEPLOY_SSH_KEY, DEPLOY_KNOWN_HOSTS` : 'left alone (--no-github)'}`,\n\t);\n\tif (done) {\n\t\tconsole.log(\n\t\t\t`\\n Already set up by ${describeActor(done.updatedBy)} on ${done.updatedAt.slice(0, 10)}; running again changes only what is missing or wrong.`,\n\t\t);\n\t}\n\tconsole.log('\\n On the server, through sudo:');\n\tfor (const step of [\n\t\t\"SSH: keys only, root's login off (and nothing else may turn passwords back on)\",\n\t\t`root's password locked — ${admin}'s sudo is the way to root`,\n\t\t`firewall: ${server.port}, 80 and 443 in, everything out`,\n\t\t'security updates installed daily (unattended-upgrades); fail2ban on sshd',\n\t\t\"Docker and its compose plugin, from Docker's repository\",\n\t\t`user ${server.user}, the deploy key authorized with restrict,port-forwarding`,\n\t]) {\n\t\tconsole.log(` · ${step}`);\n\t}\n\n\tif (options.dryRun) {\n\t\tconsole.log(\n\t\t\t`\\n The script, run as: sudo bash setup.sh ${[admin, server.user, String(server.port), '<deploy key>', comment].map(shellQuote).join(' ')}\\n`,\n\t\t);\n\t\tconsole.log(SERVER_SCRIPT.replace(/^/gm, ' '));\n\t\tconsole.log(' --dry-run: nothing changed.\\n');\n\t\treturn { server, admin, keyFile, ...(repo ? { repo } : {}) };\n\t}\n\n\tif (\n\t\t!options.yes &&\n\t\t!isYes(await ask(`\\n Set up ${server.host}? [y/N] `), false)\n\t) {\n\t\tconsole.log(' Nothing changed.\\n');\n\t\treturn { server, admin, keyFile, ...(repo ? { repo } : {}) };\n\t}\n\n\t// ── The deploy key pair, here ──────────────────────────────────────────\n\tif (!existsSync(keyFile)) {\n\t\tawait mkdir(dirname(keyFile), { recursive: true, mode: 0o700 });\n\t\tconst made = await run('ssh-keygen', [\n\t\t\t'-t',\n\t\t\t'ed25519',\n\t\t\t'-N',\n\t\t\t'',\n\t\t\t'-C',\n\t\t\tcomment,\n\t\t\t'-f',\n\t\t\tkeyFile,\n\t\t]);\n\t\tif (made.code !== 0) throw new DeployKeyNotMade(keyFile, made.stderr);\n\t\tconsole.log(`\\n ✓ Made the deploy key ${keyFile}`);\n\t}\n\tconst publicKey = (await readFile(`${keyFile}.pub`, 'utf-8')).trim();\n\n\t// ── The admin's login ──────────────────────────────────────────────────\n\t// Key only, and the host key accepted on first sight — as the first\n\t// `ssh` to a new server does. CI's is pinned and checked below.\n\tconst probe = (user: string) =>\n\t\trun('ssh', [\n\t\t\t'-o',\n\t\t\t'BatchMode=yes',\n\t\t\t'-o',\n\t\t\t'StrictHostKeyChecking=accept-new',\n\t\t\t...asAdmin,\n\t\t\tat(user, server.host),\n\t\t\t'true',\n\t\t]);\n\tlet login = await probe(admin);\n\t// A server already set up has no root or password login left to make\n\t// one with: an admin there has to let this person in.\n\tif (login.code !== 0 && done) {\n\t\tthrow new ComposeServerAccessNeeded(\n\t\t\tadminTarget,\n\t\t\tdescribeActor(done.updatedBy),\n\t\t\tdone.updatedAt.slice(0, 10),\n\t\t);\n\t}\n\tif (login.code !== 0) {\n\t\t// A server only root can log in to yet: root creates the admin — with\n\t\t// its key, or on a brand-new server with the password the provider\n\t\t// gave it, which this is the last time anything asks for.\n\t\tconst rootHasKey = (await probe('root')).code === 0;\n\t\tconst createAsRoot = isYes(\n\t\t\tawait ask(\n\t\t\t\trootHasKey\n\t\t\t\t\t? `\\n ${admin} can't log in with a key, but root can. Create ${admin} as a sudo user with root's keys? [Y/n] `\n\t\t\t\t\t: `\\n ${admin} can't log in with a key. Is this a new server, where ${admin} still has to be created? Log in as root with its password to create it [y/N] `,\n\t\t\t),\n\t\t\trootHasKey,\n\t\t);\n\t\tif (createAsRoot) {\n\t\t\tconst created = await run(\n\t\t\t\t'ssh',\n\t\t\t\t[\n\t\t\t\t\t'-t',\n\t\t\t\t\t...asAdmin,\n\t\t\t\t\tat('root', server.host),\n\t\t\t\t\tremoteCommand(ADMIN_SCRIPT, [admin], false),\n\t\t\t\t],\n\t\t\t\t{ interactive: true },\n\t\t\t);\n\t\t\tif (created.code !== 0) {\n\t\t\t\tthrow new ComposeServerSetupFailed(\n\t\t\t\t\tat('root', server.host),\n\t\t\t\t\tcreated.code,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlogin = await probe(admin);\n\t\t}\n\t\t// Root had no key to hand on — a server set up with a password — so\n\t\t// yours goes on with the admin's.\n\t\tif (\n\t\t\tlogin.code !== 0 &&\n\t\t\tisYes(\n\t\t\t\tawait ask(\n\t\t\t\t\t`\\n ${admin} can't log in with a key. Copy yours there with ssh-copy-id (asks ${admin}'s password)? [Y/n] `,\n\t\t\t\t),\n\t\t\t\ttrue,\n\t\t\t)\n\t\t) {\n\t\t\tconst copied = await run(\n\t\t\t\t'ssh-copy-id',\n\t\t\t\t[\n\t\t\t\t\t...(identity ? ['-i', identity] : []),\n\t\t\t\t\t'-p',\n\t\t\t\t\tString(server.port),\n\t\t\t\t\tadminTarget,\n\t\t\t\t],\n\t\t\t\t{ interactive: true },\n\t\t\t);\n\t\t\tif (copied.code !== 0) {\n\t\t\t\tthrow new ComposeServerAdminUnreachable(adminTarget, copied.stderr);\n\t\t\t}\n\t\t}\n\t\tlogin = await probe(admin);\n\t\tif (login.code !== 0) {\n\t\t\tthrow new ComposeServerAdminUnreachable(adminTarget, login.stderr);\n\t\t}\n\t}\n\tconsole.log(` ✓ ${adminTarget} logs in with a key\\n`);\n\n\t// ── The server ─────────────────────────────────────────────────────────\n\tconst setup = await run(\n\t\t'ssh',\n\t\t[\n\t\t\t'-t',\n\t\t\t...asAdmin,\n\t\t\tadminTarget,\n\t\t\tremoteCommand(\n\t\t\t\tSERVER_SCRIPT,\n\t\t\t\t[admin, server.user, String(server.port), publicKey, comment],\n\t\t\t\ttrue,\n\t\t\t),\n\t\t],\n\t\t{ interactive: true },\n\t);\n\tif (setup.code !== 0) {\n\t\tthrow new ComposeServerSetupFailed(adminTarget, setup.code);\n\t}\n\tconst serverFingerprint = setup.stdout\n\t\t.replaceAll('\\r', '')\n\t\t.match(/^HOSTKEY=(\\S+)$/m)?.[1];\n\tif (!serverFingerprint) {\n\t\tthrow new ComposeServerSetupFailed(adminTarget, setup.code);\n\t}\n\n\t// ── The host key, pinned ───────────────────────────────────────────────\n\tconst scan = await run('ssh-keyscan', [\n\t\t'-t',\n\t\t'ed25519',\n\t\t'-p',\n\t\tString(server.port),\n\t\tserver.host,\n\t]);\n\tconst knownHosts = scan.stdout\n\t\t.split('\\n')\n\t\t.filter((line) => line.trim() && !line.startsWith('#'))\n\t\t.join('\\n');\n\tconst [scanned = ''] = await fingerprints(run, knownHosts);\n\tif (scanned !== serverFingerprint) {\n\t\tthrow new ComposeServerHostKeyMismatch(\n\t\t\tserver.host,\n\t\t\tserverFingerprint,\n\t\t\tscanned,\n\t\t);\n\t}\n\tconsole.log(`\\n ✓ Host key ${scanned}, as the server reports it`);\n\n\tif (repo) {\n\t\tgh(['api', '--method', 'PUT', `repos/${repo}/environments/${stage}`]);\n\t\tgh([\n\t\t\t'variable',\n\t\t\t'set',\n\t\t\t'DEPLOY_KNOWN_HOSTS',\n\t\t\t'--env',\n\t\t\tstage,\n\t\t\t'--repo',\n\t\t\trepo,\n\t\t\t'--body',\n\t\t\tknownHosts,\n\t\t]);\n\t\t// Through stdin, so the key is never an argument a process list shows.\n\t\tgh(\n\t\t\t['secret', 'set', 'DEPLOY_SSH_KEY', '--env', stage, '--repo', repo],\n\t\t\tawait readFile(keyFile, 'utf-8'),\n\t\t);\n\t\tconsole.log(\n\t\t\t` ✓ GitHub: environment \"${stage}\", DEPLOY_SSH_KEY and DEPLOY_KNOWN_HOSTS`,\n\t\t);\n\t}\n\n\t// ── Logged in as CI will be ────────────────────────────────────────────\n\tconst known = join(dirname(keyFile), `.gkm-known-${workspace.name}-${stage}`);\n\tawait writeFile(known, `${knownHosts}\\n`);\n\ttry {\n\t\tconst asCi = [\n\t\t\t'-i',\n\t\t\tkeyFile,\n\t\t\t'-o',\n\t\t\t'IdentitiesOnly=yes',\n\t\t\t'-o',\n\t\t\t'BatchMode=yes',\n\t\t\t'-o',\n\t\t\t`UserKnownHostsFile=${known}`,\n\t\t\t'-o',\n\t\t\t'StrictHostKeyChecking=yes',\n\t\t\t...sshOptions(server),\n\t\t];\n\t\tconst docker = await run('ssh', [\n\t\t\t...asCi,\n\t\t\tdeployTarget,\n\t\t\t'docker',\n\t\t\t'version',\n\t\t\t'--format',\n\t\t\t'{{.Server.Version}}',\n\t\t]);\n\t\tif (docker.code !== 0) {\n\t\t\tthrow new ComposeServerCheckFailed(deployTarget, 'docker', docker.stderr);\n\t\t}\n\t\tconsole.log(\n\t\t\t` ✓ ${deployTarget} runs docker (engine ${docker.stdout.trim()})`,\n\t\t);\n\t\t// The server's own sshd, through a tunnel: what a migration does to\n\t\t// reach Postgres on the server's loopback.\n\t\tconst tunnel = await run('ssh', [\n\t\t\t...asCi,\n\t\t\t'-W',\n\t\t\t`127.0.0.1:${server.port}`,\n\t\t\tdeployTarget,\n\t\t]);\n\t\tif (!tunnel.stdout.startsWith('SSH-2.0')) {\n\t\t\tthrow new ComposeServerCheckFailed(\n\t\t\t\tdeployTarget,\n\t\t\t\t'tunnel',\n\t\t\t\ttunnel.stdout.slice(0, 80) || tunnel.stderr,\n\t\t\t);\n\t\t}\n\t\tconsole.log(` ✓ ${deployTarget} opens tunnels (migrations)`);\n\t} finally {\n\t\tawait rm(known, { force: true });\n\t}\n\n\t// Done: the stage's state says so, and who did it.\n\tconst journal = await DeployJournal.open(state, stage, () =>\n\t\tcreateComposeState(stage),\n\t);\n\tawait journal.ready(\n\t\t{\n\t\t\tkey: SERVER_RECORD,\n\t\t\ttype: 'server',\n\t\t\tdata: { host: server.host } satisfies ServerRecordData,\n\t\t},\n\t\tserver.host,\n\t);\n\tconsole.log(` ✓ Recorded in the \"${stage}\" state`);\n\n\tconsole.log(\n\t\t`\\n✅ ${server.host} is ready for \"${stage}\".${repo ? ' CI deploys it with the key it was given.' : ''} ` +\n\t\t\t`To deploy from here, load the key first: ssh-add ${keyFile}\\n`,\n\t);\n\treturn {\n\t\tserver,\n\t\tadmin,\n\t\tkeyFile,\n\t\tknownHosts,\n\t\t...(repo ? { repo } : {}),\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,MAAa,gBAAgB,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkJvC,MAAa,eAAe;;;;;;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,GACA,OAAO,IACR;CACA,QAAQ,IAAI,wBAAwB,MAAM,QAAQ;CAElD,QAAQ,IACP,OAAO,OAAO,KAAK,iBAAiB,MAAM,IAAI,OAAO,8CAA8C,GAAG,oDACjD,QAAQ,GAC9D;CACA,OAAO;EACN;EACA;EACA;EACA;EACA,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;CACxB;AACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"serverSetup-CVeRKNXR.cjs","names":["GkmError","spawn","join","homedir","ghCli","prompt","resolve","loadWorkspaceConfig","composeServer","secretsStoreFor","createStateStore","existsSync","describeActor","mkdir","dirname","readFile","writeFile","rm","DeployJournal","createComposeState"],"sources":["../src/compose/serverScript.ts","../src/compose/serverSetup.ts"],"sourcesContent":["/**\n * What `gkm compose:server` runs on the server, as root (through the admin\n * user's sudo). Plain bash, so `--dry-run` can print exactly what will run,\n * and safe to run again: every step changes only what is missing or wrong.\n *\n * Arguments, in order: the admin user (the one running sudo), the deploy\n * user, the SSH port, the deploy key's public line, and its comment.\n *\n * The last line it prints is `HOSTKEY=<fingerprint>` — the server's own\n * ed25519 host key, which the command checks the network's against before\n * pinning it for CI.\n */\nexport const SERVER_SCRIPT = String.raw`set -euo pipefail\nexport DEBIAN_FRONTEND=noninteractive\nADMIN=\"$1\"; DEPLOY=\"$2\"; SSH_PORT=\"$3\"; PUB=\"$4\"; COMMENT=\"$5\"\nsay() { echo \" $*\"; }\nfail() { echo \" ✗ $*\" >&2; exit 1; }\n\n. /etc/os-release\ncase \"$ID\" in\n\tubuntu | debian) ;;\n\t*) fail \"gkm sets up Ubuntu and Debian servers; this one is $ID.\" ;;\nesac\n\n# ── SSH: keys only, no root ────────────────────────────────────────────────\n# Before password logins are turned off, the admin must have a key to come\n# back with — otherwise this would lock them out.\nADMIN_HOME=\"$(getent passwd \"$ADMIN\" | cut -d: -f6)\"\n[ -s \"$ADMIN_HOME/.ssh/authorized_keys\" ] ||\n\tfail \"$ADMIN has no key in $ADMIN_HOME/.ssh/authorized_keys; turning off password logins would lock them out.\"\n# First match wins in sshd_config, and 00- sorts before what a provider ships\n# (cloud-init's 50-cloud-init.conf turns password logins back on).\ncat > /etc/ssh/sshd_config.d/00-gkm-hardening.conf <<'EOF'\n# Written by gkm compose:server.\nPermitRootLogin no\nPasswordAuthentication no\nKbdInteractiveAuthentication no\nEOF\n# The deploy migrates through an SSH tunnel to the server's loopback.\ncat > /etc/ssh/sshd_config.d/60-gkm-deploy.conf <<EOF\n# Written by gkm compose:server.\nMatch User $DEPLOY\n AllowTcpForwarding local\nEOF\nsshd -t\nsystemctl reload ssh 2>/dev/null || systemctl reload sshd\n# What sshd actually does now, whatever else is in its config.\nEFFECTIVE=\"$(sshd -T)\"\nfor setting in 'permitrootlogin no' 'passwordauthentication no' 'kbdinteractiveauthentication no'; do\n\tgrep -qx \"$setting\" <<<\"$EFFECTIVE\" || fail \"sshd still does not say '$setting'; another file in /etc/ssh overrides it.\"\ndone\nFORWARD=\"$(sshd -T -C \"user=$DEPLOY,host=localhost,addr=127.0.0.1\" | sed -n 's/^allowtcpforwarding //p')\"\ncase \"$FORWARD\" in\n\tyes | all | local) ;;\n\t*) fail \"sshd does not let $DEPLOY forward ports (allowtcpforwarding $FORWARD).\" ;;\nesac\nsay \"sshd: keys only, no root login; $DEPLOY may open local tunnels\"\n# Root is reached through the admin's sudo, which this script is running\n# under — so its password, the one a provider mails out, can go.\npasswd -l root >/dev/null\nsay \"root's password locked; $ADMIN's sudo is the way to root\"\n\n# ── Firewall: SSH, HTTP, HTTPS ─────────────────────────────────────────────\ncommand -v ufw >/dev/null || { apt-get update -qq && apt-get install -y -qq ufw >/dev/null; }\nufw default deny incoming >/dev/null\nufw default allow outgoing >/dev/null\nufw allow \"$SSH_PORT/tcp\" >/dev/null\nufw allow 80/tcp >/dev/null\nufw allow 443/tcp >/dev/null\nufw --force enable >/dev/null\nsay \"firewall: $SSH_PORT, 80, 443 in; everything out\"\nEXTRA=\"$(ufw status | awk 'NR > 4 && $1 != \"\" { print $1 }' | grep -vxE \"(($SSH_PORT|80|443)(/tcp)?|OpenSSH)\" | sort -u || true)\"\nif [ -n \"$EXTRA\" ]; then\n\tsay \"⚠ also open: $(echo $EXTRA). gkm uses none of them; close each with: sudo ufw delete allow <port>\"\nfi\n\n# ── Updates and bans ───────────────────────────────────────────────────────\napt-get update -qq\napt-get install -y -qq unattended-upgrades fail2ban >/dev/null\ncat > /etc/apt/apt.conf.d/20auto-upgrades <<'EOF'\nAPT::Periodic::Update-Package-Lists \"1\";\nAPT::Periodic::Unattended-Upgrade \"1\";\nEOF\ncat > /etc/fail2ban/jail.d/gkm.local <<EOF\n# Written by gkm compose:server.\n[sshd]\nenabled = true\nport = $SSH_PORT\nEOF\nsystemctl enable --now unattended-upgrades fail2ban >/dev/null 2>&1\nsystemctl restart fail2ban\nsay \"security updates install daily; fail2ban watches sshd\"\n\n# ── Docker, from Docker's own repository ───────────────────────────────────\nif ! command -v docker >/dev/null || ! docker compose version >/dev/null 2>&1; then\n\tsay \"installing Docker…\"\n\tapt-get install -y -qq ca-certificates curl >/dev/null\n\tinstall -m 0755 -d /etc/apt/keyrings\n\tcurl -fsSL \"https://download.docker.com/linux/$ID/gpg\" -o /etc/apt/keyrings/docker.asc\n\tchmod a+r /etc/apt/keyrings/docker.asc\n\techo \"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/$ID $VERSION_CODENAME stable\" \\\n\t\t> /etc/apt/sources.list.d/docker.list\n\tapt-get update -qq\n\tapt-get install -y -qq docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin >/dev/null\nfi\nsystemctl enable --now docker >/dev/null 2>&1\nsay \"docker $(docker version --format '{{.Server.Version}}')\"\n\n# ── Kernel: room for many open connections ─────────────────────────────────\n# Each client behind the edge is tracked twice by conntrack — the published\n# port, then the bridge to the app — and the default table, sized from memory,\n# fills long before memory does. When it is full, new connections are dropped\n# with nothing logged where anyone looks.\ncat > /etc/sysctl.d/60-gkm-connections.conf <<'EOF'\n# Written by gkm compose:server.\nnet.netfilter.nf_conntrack_max = 1048576\nnet.core.somaxconn = 65535\nnet.ipv4.tcp_max_syn_backlog = 65535\nfs.file-max = 2097152\nEOF\n# Buckets for the table, a quarter of its entries: from the next boot on, and\n# now.\necho \"options nf_conntrack hashsize=262144\" > /etc/modprobe.d/gkm-conntrack.conf\nmodprobe nf_conntrack\necho 262144 > /sys/module/nf_conntrack/parameters/hashsize 2>/dev/null || true\nsysctl --quiet --system\nsay \"kernel: $(sysctl -n net.netfilter.nf_conntrack_max) tracked connections, a backlog of $(sysctl -n net.core.somaxconn)\"\n\n# ── The deploy user: no password, no sudo, in the docker group ─────────────\nid \"$DEPLOY\" >/dev/null 2>&1 || adduser --disabled-password --gecos \"\" \"$DEPLOY\" >/dev/null\nusermod -aG docker \"$DEPLOY\"\nDEPLOY_HOME=\"$(getent passwd \"$DEPLOY\" | cut -d: -f6)\"\ninstall -d -m 700 -o \"$DEPLOY\" -g \"$DEPLOY\" \"$DEPLOY_HOME/.ssh\"\nAUTH=\"$DEPLOY_HOME/.ssh/authorized_keys\"\ntouch \"$AUTH\"\n# One managed line: this key (or an earlier one by the same name) replaced,\n# with nothing allowed but the commands and the tunnel the deploy uses.\nKEYBODY=\"$(awk '{ print $2 }' <<<\"$PUB\")\"\ngrep -v -F -e \"$KEYBODY\" -e \" $COMMENT\" \"$AUTH\" > \"$AUTH.new\" || true\necho \"restrict,port-forwarding $PUB\" >> \"$AUTH.new\"\nmv \"$AUTH.new\" \"$AUTH\"\nchown \"$DEPLOY:$DEPLOY\" \"$AUTH\"\nchmod 600 \"$AUTH\"\nsay \"user $DEPLOY (docker group), deploy key authorized with restrict,port-forwarding\"\nOTHERS=\"$(grep -v -F -e \"$KEYBODY\" \"$AUTH\" | grep -c . || true)\"\nif [ \"$OTHERS\" -gt 0 ]; then\n\tsay \"⚠ $AUTH holds $OTHERS other key(s). Review: sudo cat $AUTH\"\nfi\n\necho \"HOSTKEY=$(ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub | awk '{ print $2 }')\"\n`;\n\n/**\n * What runs as root to give a fresh server its admin — the guide's first\n * step, for a server only root can log in to yet: a sudo user, with root's\n * keys so the same key logs in. `adduser` asks for its password, which sudo\n * will ask for.\n */\nexport const ADMIN_SCRIPT = `set -euo pipefail\nADMIN=\"$1\"\nif ! id \"$ADMIN\" >/dev/null 2>&1; then\n\techo \" creating $ADMIN — choose the password sudo will ask for:\"\n\tadduser --gecos \"\" \"$ADMIN\"\nfi\nusermod -aG sudo \"$ADMIN\"\nHOME_DIR=\"$(getent passwd \"$ADMIN\" | cut -d: -f6)\"\ninstall -d -m 700 -o \"$ADMIN\" -g \"$ADMIN\" \"$HOME_DIR/.ssh\"\nAUTH=\"$HOME_DIR/.ssh/authorized_keys\"\ntouch \"$AUTH\"\n# The keys alone: a provider's options on root's lines (a command=\"…\" that\n# says \"log in as ubuntu\") would stop the admin's login too. A server root\n# logs in to with a password has none; ssh-copy-id brings the admin's.\n{ grep -oE '(ssh|ecdsa|sk)-[^ ]+ [A-Za-z0-9+/=]+( .*)?$' /root/.ssh/authorized_keys 2>/dev/null || true; } |\n\twhile IFS= read -r key; do\n\t\tgrep -qxF \"$key\" \"$AUTH\" || echo \"$key\" >> \"$AUTH\"\n\tdone\nchown \"$ADMIN:$ADMIN\" \"$AUTH\"\nchmod 600 \"$AUTH\"\necho \" $ADMIN is a sudo user, with root's SSH keys (if root had any)\"\n`;\n","/**\n * `gkm compose:server` — make a VPS ready for a stage's compose deploys, from\n * this machine, in one go.\n *\n * It logs in as the server's admin — a sudo user, never root — and, through\n * sudo, sets the server up the way a production VPS should be: SSH by key\n * only with root's login off, a firewall open on SSH, 80 and 443 alone,\n * security updates installed daily, fail2ban on sshd, and Docker from\n * Docker's own repository. It then creates the stage's deploy user (in the\n * docker group, no sudo, no password) and authorizes a deploy key on it that\n * may run commands and open the tunnel migrations use, nothing more.\n *\n * Off the server: it makes the deploy key pair here, pins the server's host\n * key — checked against the fingerprint the server reports of itself — and\n * gives both to the stage's GitHub environment as `DEPLOY_SSH_KEY` and\n * `DEPLOY_KNOWN_HOSTS`, which the generated deploy workflow reads. Last, it\n * logs in exactly as CI will, and checks Docker and the tunnel answer.\n *\n * A fresh server only root can log in to gets its admin first: as root —\n * with root's key, or its password on a brand-new server — it creates the\n * user, and `ssh-copy-id` puts your key on it when root had none to give.\n * Root's password is locked once the admin's sudo works.\n *\n * Once it has, the stage's state records that it is done (`server:compose`,\n * stamped with who and when) — nothing personal: the admin is whoever runs\n * it, with their own key.\n * Safe to run again: each step changes only what is missing or wrong.\n */\n\nimport { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join, resolve } from 'node:path';\nimport { loadWorkspaceConfig } from '../config';\nimport { describeActor } from '../deploy/actor';\nimport { type Gh, ghCli } from '../deploy/github';\nimport { DeployJournal } from '../deploy/journal';\nimport { createStateStore, type StateStore } from '../deploy/StateStore';\nimport { createComposeState } from '../deploy/state';\nimport { GkmError } from '../errors';\nimport { prompt } from '../prompt';\nimport { secretsStoreFor } from '../secrets/store.js';\nimport { assertDeployedStage } from '../workspace/stages.js';\nimport { type ComposeServer, composeServer } from './server';\nimport { ADMIN_SCRIPT, SERVER_SCRIPT } from './serverScript';\n\nexport interface ComposeServerSetupOptions {\n\t/** The deployed stage whose server this is. */\n\tstage: string;\n\t/**\n\t * The server's sudo user. Absent, the user `ssh` logs in to the server as\n\t * by default (`~/.ssh/config`, else this machine's) — asked for only when\n\t * that is root.\n\t */\n\tadmin?: string;\n\t/** The key the admin logs in with. Absent, `ssh`'s own choice. */\n\tidentity?: string;\n\t/** The deploy key pair. Default `~/.ssh/gkm-<project>-<stage>`. */\n\tkeyFile?: string;\n\t/** `owner/name`; defaults to the repository `gh` sees here. */\n\trepo?: string;\n\t/** `--no-github`: leave the GitHub environment alone. */\n\tgithub?: boolean;\n\t/** Print the plan and the script; connect to nothing. */\n\tdryRun?: boolean;\n\t/** Apply without asking first. */\n\tyes?: boolean;\n\tcwd?: string;\n}\n\n/** What a finished command ran: output kept, its exit code. */\nexport interface Ran {\n\tcode: number;\n\tstdout: string;\n\tstderr: string;\n}\n\n/**\n * Runs a program. `interactive` gives it this terminal's stdin and stderr —\n * for a password sudo or adduser asks — while stdout is still kept, and\n * echoed as it comes.\n */\nexport type Runner = (\n\tcommand: string,\n\targs: readonly string[],\n\toptions?: { input?: string; interactive?: boolean },\n) => Promise<Ran>;\n\nexport interface ComposeServerSetupDeps {\n\trun: Runner;\n\tgh: Gh;\n\t/** Ask the person at the terminal. */\n\task: (question: string) => Promise<string>;\n\t/** The stage's state; the workspace's own store when absent. */\n\tstate: StateStore;\n}\n\n/** The stage's record of its server, as `compose:server` last set it up. */\nexport const SERVER_RECORD = 'server:compose';\n\n/**\n * What `server:compose` holds: which server was set up. Who set it up, and\n * when, are the record's own `updatedBy` and `updatedAt`.\n */\nexport interface ServerRecordData {\n\thost: string;\n}\n\nexport interface ComposeServerSetupResult {\n\tserver: ComposeServer;\n\tadmin: string;\n\tkeyFile: string;\n\t/** The pinned host key line, as `known_hosts` holds it. Absent on a dry run. */\n\tknownHosts?: string;\n\t/** The repository whose environment was given the key. */\n\trepo?: string;\n}\n\n/** The admin named is root, whose login this command turns off. */\nexport class ComposeServerAdminIsRoot extends GkmError {\n\tconstructor() {\n\t\tsuper(\n\t\t\t\"The admin can't be root: setting up the server turns root's SSH login \" +\n\t\t\t\t'off. Name the sudo user you log in as (--admin <user>). A fresh ' +\n\t\t\t\t'server with only root gets one: run this again with the name it ' +\n\t\t\t\t\"should have, and gkm offers to create it with root's key.\",\n\t\t);\n\t\tthis.name = 'ComposeServerAdminIsRoot';\n\t}\n}\n\n/** The admin named is the deploy user, which has no sudo. */\nexport class ComposeServerAdminIsDeployUser extends GkmError {\n\tconstructor(readonly user: string) {\n\t\tsuper(\n\t\t\t`'${user}' is the stage's deploy user (deploy.compose.server), which ` +\n\t\t\t\t'gkm creates without sudo. Name the sudo user you log in as with --admin.',\n\t\t);\n\t\tthis.name = 'ComposeServerAdminIsDeployUser';\n\t}\n}\n\n/** No key logs the admin in, and nothing was done to make one. */\nexport class ComposeServerAdminUnreachable extends GkmError {\n\tconstructor(\n\t\treadonly target: string,\n\t\treadonly stderr: string,\n\t) {\n\t\tsuper(\n\t\t\t`Could not log in as ${target} with a key (ssh said: ${stderr.trim() || 'nothing'}). ` +\n\t\t\t\t`Check \\`ssh ${target}\\` works without a password — copy your key with ` +\n\t\t\t\t`\\`ssh-copy-id ${target}\\` — then run this again.`,\n\t\t);\n\t\tthis.name = 'ComposeServerAdminUnreachable';\n\t}\n}\n\n/**\n * The server was set up already, and this person cannot log in to it as\n * the admin they named. Root's login and passwords are off there, so only\n * an admin can let them in.\n */\nexport class ComposeServerAccessNeeded extends GkmError {\n\tconstructor(\n\t\treadonly target: string,\n\t\treadonly setUpBy: string,\n\t\treadonly setUpOn: string,\n\t) {\n\t\tsuper(\n\t\t\t`${target} can't log in with your key, and the server was set up by ${setUpBy} on ${setUpOn} — ` +\n\t\t\t\t'root and password logins are off there. Ask them, or another admin, to add your ' +\n\t\t\t\t`public key to ${target.split('@')[0]}'s ~/.ssh/authorized_keys (or create you a sudo ` +\n\t\t\t\t'user with it), then run this again.',\n\t\t);\n\t\tthis.name = 'ComposeServerAccessNeeded';\n\t}\n}\n\n/** `ssh-keygen` could not make the deploy key pair. */\nexport class DeployKeyNotMade extends GkmError {\n\tconstructor(\n\t\treadonly keyFile: string,\n\t\treadonly stderr: string,\n\t) {\n\t\tsuper(\n\t\t\t`Could not make the deploy key ${keyFile} (ssh-keygen said: ${stderr.trim() || 'nothing'}). ` +\n\t\t\t\t'Pass another path with --key-file.',\n\t\t);\n\t\tthis.name = 'DeployKeyNotMade';\n\t}\n}\n\n/** The script on the server stopped before it finished. */\nexport class ComposeServerSetupFailed extends GkmError {\n\tconstructor(\n\t\treadonly target: string,\n\t\treadonly code: number,\n\t) {\n\t\tsuper(\n\t\t\t`Setting up ${target} stopped (exit ${code}); its output is above. ` +\n\t\t\t\t'Fix what it names and run this again — every step it already ' +\n\t\t\t\t'finished is left as it is.',\n\t\t);\n\t\tthis.name = 'ComposeServerSetupFailed';\n\t}\n}\n\n/** The host key the network shows is not the one the server holds. */\nexport class ComposeServerHostKeyMismatch extends GkmError {\n\tconstructor(\n\t\treadonly host: string,\n\t\treadonly server: string,\n\t\treadonly scanned: string,\n\t) {\n\t\tsuper(\n\t\t\t`${host}'s host key is ${server} on the server, but ${scanned || 'nothing'} ` +\n\t\t\t\t'over the network. Something between here and the server answered for ' +\n\t\t\t\t'it, or the server is not the one you logged in to. Nothing was given ' +\n\t\t\t\t'to GitHub; find out why before running this again.',\n\t\t);\n\t\tthis.name = 'ComposeServerHostKeyMismatch';\n\t}\n}\n\n/** The deploy key logged in, but cannot do what a deploy does. */\nexport class ComposeServerCheckFailed extends GkmError {\n\tconstructor(\n\t\treadonly target: string,\n\t\treadonly check: 'docker' | 'tunnel',\n\t\treadonly output: string,\n\t) {\n\t\tsuper(\n\t\t\tcheck === 'docker'\n\t\t\t\t? `The deploy key can't run docker as ${target} (ssh said: ${output.trim() || 'nothing'}).`\n\t\t\t\t: `The deploy key can't open a tunnel as ${target} (got: ${output.trim() || 'nothing'}). ` +\n\t\t\t\t\t\t\"Check its line in the deploy user's authorized_keys says \" +\n\t\t\t\t\t\t'restrict,port-forwarding, and that sshd allows it forwarding.',\n\t\t);\n\t\tthis.name = 'ComposeServerCheckFailed';\n\t}\n}\n\n/** `'…'`, for a value in a command line the remote shell reads. */\nfunction shellQuote(value: string): string {\n\treturn `'${value.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\n/**\n * The remote command that runs `script` with `args`: written to a temporary\n * file (so the script keeps the terminal for any password it asks), run,\n * and removed. `sudo` for everything but root.\n */\nexport function remoteCommand(\n\tscript: string,\n\targs: readonly string[],\n\tsudo: boolean,\n): string {\n\tconst encoded = Buffer.from(script).toString('base64');\n\treturn [\n\t\t`f=\"$(mktemp)\"`,\n\t\t`echo ${encoded} | base64 -d > \"$f\"`,\n\t\t`${sudo ? 'sudo ' : ''}bash \"$f\" ${args.map(shellQuote).join(' ')}; s=$?`,\n\t\t`rm -f \"$f\"`,\n\t\t'exit $s',\n\t].join('; ');\n}\n\nfunction sshOptions(server: ComposeServer): string[] {\n\treturn ['-o', 'ConnectTimeout=20', '-p', String(server.port)];\n}\n\n/** How the admin (or root) logs in: the server's options and their key. */\nfunction loginOptions(server: ComposeServer, identity?: string): string[] {\n\treturn [\n\t\t...sshOptions(server),\n\t\t...(identity ? ['-i', identity, '-o', 'IdentitiesOnly=yes'] : []),\n\t];\n}\n\n/** `user@host`, as `ssh` takes it. */\nfunction at(user: string, host: string): string {\n\treturn `${user}@${host}`;\n}\n\n/** The real runner: the system's programs. */\nexport const systemRunner: Runner = (command, args, options = {}) =>\n\tnew Promise((resolve, reject) => {\n\t\tconst child = spawn(command, args, {\n\t\t\tstdio: [\n\t\t\t\toptions.interactive ? 'inherit' : 'pipe',\n\t\t\t\t'pipe',\n\t\t\t\toptions.interactive ? 'inherit' : 'pipe',\n\t\t\t],\n\t\t\ttimeout: options.interactive ? undefined : 60_000,\n\t\t});\n\t\tlet stdout = '';\n\t\tlet stderr = '';\n\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\tstdout += chunk.toString();\n\t\t\tif (options.interactive) process.stdout.write(chunk);\n\t\t});\n\t\tchild.stderr?.on('data', (chunk: Buffer) => {\n\t\t\tstderr += chunk.toString();\n\t\t});\n\t\tchild.on('error', reject);\n\t\tchild.on('close', (code) => resolve({ code: code ?? 1, stdout, stderr }));\n\t\t// A program that exits without reading all its input closes the pipe\n\t\t// under the write: EPIPE. Its exit code already says how it went, and\n\t\t// unheard, the error would be thrown from nowhere.\n\t\tchild.stdin?.on('error', () => {});\n\t\tif (child.stdin) child.stdin.end(options.input ?? '');\n\t});\n\n/** Whether `answer` is a yes, `fallback` when nothing was typed. */\nfunction isYes(answer: string, fallback: boolean): boolean {\n\tconst value = answer.trim().toLowerCase();\n\treturn value === '' ? fallback : value === 'y' || value === 'yes';\n}\n\n/** The SHA256 fingerprint of each key in `keys`, by `ssh-keygen -lf -`. */\nasync function fingerprints(run: Runner, keys: string): Promise<string[]> {\n\tconst { stdout } = await run('ssh-keygen', ['-lf', '-'], { input: keys });\n\treturn stdout\n\t\t.split('\\n')\n\t\t.map((line) => line.split(' ')[1])\n\t\t.filter((value): value is string => Boolean(value));\n}\n\n/** The default deploy key pair for a stage. */\nexport function defaultKeyFile(project: string, stage: string): string {\n\treturn join(homedir(), '.ssh', `gkm-${project}-${stage}`);\n}\n\n/** `gkm compose:server`. */\nexport async function composeServerCommand(\n\toptions: ComposeServerSetupOptions,\n\tdeps: Partial<ComposeServerSetupDeps> = {},\n): Promise<ComposeServerSetupResult> {\n\tconst run = deps.run ?? systemRunner;\n\tconst gh = deps.gh ?? ghCli;\n\tconst ask =\n\t\tdeps.ask ??\n\t\t((question: string) =>\n\t\t\tprompt(question, {\n\t\t\t\tinstead: 'Name the server user with --admin and pass --yes.',\n\t\t\t}));\n\tconst github = options.github !== false;\n\tconst { stage } = options;\n\n\tconst cwd = resolve(options.cwd ?? process.cwd());\n\tconst { workspace } = await loadWorkspaceConfig(cwd);\n\tassertDeployedStage(workspace.stages, stage);\n\tconst server = composeServer({\n\t\tstage,\n\t\tlocal: false,\n\t\tconfig: workspace.deploy?.compose?.server,\n\t\tcustom: (await (await secretsStoreFor(workspace, stage)).read(stage))\n\t\t\t?.custom,\n\t})!;\n\n\t// Whether this server was set up before, by whom and when.\n\tconst state =\n\t\tdeps.state ??\n\t\t(await createStateStore({\n\t\t\tconfig: workspace.state,\n\t\t\tworkspaceRoot: workspace.root,\n\t\t\tworkspaceName: workspace.name,\n\t\t\tnamespace: workspace.deploy?.namespace,\n\t\t}));\n\tconst record = (await state.read(stage))?.resources[SERVER_RECORD];\n\tconst done =\n\t\t(record?.data as ServerRecordData | undefined)?.host === server.host\n\t\t\t? record\n\t\t\t: undefined;\n\n\t// The admin's login: `--admin`/`--identity`, or what `ssh` itself would\n\t// use for this host — read with `ssh -G`, which connects to nothing.\n\tconst identity = options.identity ? resolve(options.identity) : undefined;\n\tconst asAdmin = loginOptions(server, identity);\n\tconst sshUser =\n\t\t(await run('ssh', ['-G', ...asAdmin, server.host])).stdout.match(\n\t\t\t/^user (\\S+)$/m,\n\t\t)?.[1] ?? '';\n\tconst admin = (\n\t\toptions.admin ??\n\t\t(sshUser && sshUser !== 'root'\n\t\t\t? sshUser\n\t\t\t: await ask(`The sudo user you log in to ${server.host} as (not root): `))\n\t).trim();\n\tif (!admin || admin === 'root') throw new ComposeServerAdminIsRoot();\n\tif (admin === server.user) throw new ComposeServerAdminIsDeployUser(admin);\n\n\tconst keyFile = resolve(\n\t\toptions.keyFile ?? defaultKeyFile(workspace.name, stage),\n\t);\n\tconst comment = `gkm-${workspace.name}-${stage}-deploy`;\n\tconst repo = github\n\t\t? (options.repo ??\n\t\t\tgh(['repo', 'view', '--json', 'nameWithOwner', '-q', '.nameWithOwner']))\n\t\t: undefined;\n\tconst adminTarget = at(admin, server.host);\n\tconst deployTarget = at(server.user, server.host);\n\n\tconsole.log(`\\n🖥 Server for stage \"${stage}\"\\n`);\n\tconsole.log(` Server: ${server.host} (ssh port ${server.port})`);\n\tconsole.log(\n\t\t` Admin: ${admin} — logs in with ${identity ?? 'your SSH key'}, runs sudo${options.admin ? '' : ' (your SSH login)'}`,\n\t);\n\tconsole.log(\n\t\t` Deploy user: ${server.user} — docker group, no sudo, no password`,\n\t);\n\tconsole.log(\n\t\t` Deploy key: ${keyFile}${existsSync(keyFile) ? '' : ' (new, made here)'}`,\n\t);\n\tconsole.log(\n\t\t` GitHub: ${repo ? `environment \"${stage}\" of ${repo}: DEPLOY_SSH_KEY, DEPLOY_KNOWN_HOSTS` : 'left alone (--no-github)'}`,\n\t);\n\tif (done) {\n\t\tconsole.log(\n\t\t\t`\\n Already set up by ${describeActor(done.updatedBy)} on ${done.updatedAt.slice(0, 10)}; running again changes only what is missing or wrong.`,\n\t\t);\n\t}\n\tconsole.log('\\n On the server, through sudo:');\n\tfor (const step of [\n\t\t\"SSH: keys only, root's login off (and nothing else may turn passwords back on)\",\n\t\t`root's password locked — ${admin}'s sudo is the way to root`,\n\t\t`firewall: ${server.port}, 80 and 443 in, everything out`,\n\t\t'security updates installed daily (unattended-upgrades); fail2ban on sshd',\n\t\t\"Docker and its compose plugin, from Docker's repository\",\n\t\t`user ${server.user}, the deploy key authorized with restrict,port-forwarding`,\n\t]) {\n\t\tconsole.log(` · ${step}`);\n\t}\n\n\tif (options.dryRun) {\n\t\tconsole.log(\n\t\t\t`\\n The script, run as: sudo bash setup.sh ${[admin, server.user, String(server.port), '<deploy key>', comment].map(shellQuote).join(' ')}\\n`,\n\t\t);\n\t\tconsole.log(SERVER_SCRIPT.replace(/^/gm, ' '));\n\t\tconsole.log(' --dry-run: nothing changed.\\n');\n\t\treturn { server, admin, keyFile, ...(repo ? { repo } : {}) };\n\t}\n\n\tif (\n\t\t!options.yes &&\n\t\t!isYes(await ask(`\\n Set up ${server.host}? [y/N] `), false)\n\t) {\n\t\tconsole.log(' Nothing changed.\\n');\n\t\treturn { server, admin, keyFile, ...(repo ? { repo } : {}) };\n\t}\n\n\t// ── The deploy key pair, here ──────────────────────────────────────────\n\tif (!existsSync(keyFile)) {\n\t\tawait mkdir(dirname(keyFile), { recursive: true, mode: 0o700 });\n\t\tconst made = await run('ssh-keygen', [\n\t\t\t'-t',\n\t\t\t'ed25519',\n\t\t\t'-N',\n\t\t\t'',\n\t\t\t'-C',\n\t\t\tcomment,\n\t\t\t'-f',\n\t\t\tkeyFile,\n\t\t]);\n\t\tif (made.code !== 0) throw new DeployKeyNotMade(keyFile, made.stderr);\n\t\tconsole.log(`\\n ✓ Made the deploy key ${keyFile}`);\n\t}\n\tconst publicKey = (await readFile(`${keyFile}.pub`, 'utf-8')).trim();\n\n\t// ── The admin's login ──────────────────────────────────────────────────\n\t// Key only, and the host key accepted on first sight — as the first\n\t// `ssh` to a new server does. CI's is pinned and checked below.\n\tconst probe = (user: string) =>\n\t\trun('ssh', [\n\t\t\t'-o',\n\t\t\t'BatchMode=yes',\n\t\t\t'-o',\n\t\t\t'StrictHostKeyChecking=accept-new',\n\t\t\t...asAdmin,\n\t\t\tat(user, server.host),\n\t\t\t'true',\n\t\t]);\n\tlet login = await probe(admin);\n\t// A server already set up has no root or password login left to make\n\t// one with: an admin there has to let this person in.\n\tif (login.code !== 0 && done) {\n\t\tthrow new ComposeServerAccessNeeded(\n\t\t\tadminTarget,\n\t\t\tdescribeActor(done.updatedBy),\n\t\t\tdone.updatedAt.slice(0, 10),\n\t\t);\n\t}\n\tif (login.code !== 0) {\n\t\t// A server only root can log in to yet: root creates the admin — with\n\t\t// its key, or on a brand-new server with the password the provider\n\t\t// gave it, which this is the last time anything asks for.\n\t\tconst rootHasKey = (await probe('root')).code === 0;\n\t\tconst createAsRoot = isYes(\n\t\t\tawait ask(\n\t\t\t\trootHasKey\n\t\t\t\t\t? `\\n ${admin} can't log in with a key, but root can. Create ${admin} as a sudo user with root's keys? [Y/n] `\n\t\t\t\t\t: `\\n ${admin} can't log in with a key. Is this a new server, where ${admin} still has to be created? Log in as root with its password to create it [y/N] `,\n\t\t\t),\n\t\t\trootHasKey,\n\t\t);\n\t\tif (createAsRoot) {\n\t\t\tconst created = await run(\n\t\t\t\t'ssh',\n\t\t\t\t[\n\t\t\t\t\t'-t',\n\t\t\t\t\t...asAdmin,\n\t\t\t\t\tat('root', server.host),\n\t\t\t\t\tremoteCommand(ADMIN_SCRIPT, [admin], false),\n\t\t\t\t],\n\t\t\t\t{ interactive: true },\n\t\t\t);\n\t\t\tif (created.code !== 0) {\n\t\t\t\tthrow new ComposeServerSetupFailed(\n\t\t\t\t\tat('root', server.host),\n\t\t\t\t\tcreated.code,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlogin = await probe(admin);\n\t\t}\n\t\t// Root had no key to hand on — a server set up with a password — so\n\t\t// yours goes on with the admin's.\n\t\tif (\n\t\t\tlogin.code !== 0 &&\n\t\t\tisYes(\n\t\t\t\tawait ask(\n\t\t\t\t\t`\\n ${admin} can't log in with a key. Copy yours there with ssh-copy-id (asks ${admin}'s password)? [Y/n] `,\n\t\t\t\t),\n\t\t\t\ttrue,\n\t\t\t)\n\t\t) {\n\t\t\tconst copied = await run(\n\t\t\t\t'ssh-copy-id',\n\t\t\t\t[\n\t\t\t\t\t...(identity ? ['-i', identity] : []),\n\t\t\t\t\t'-p',\n\t\t\t\t\tString(server.port),\n\t\t\t\t\tadminTarget,\n\t\t\t\t],\n\t\t\t\t{ interactive: true },\n\t\t\t);\n\t\t\tif (copied.code !== 0) {\n\t\t\t\tthrow new ComposeServerAdminUnreachable(adminTarget, copied.stderr);\n\t\t\t}\n\t\t}\n\t\tlogin = await probe(admin);\n\t\tif (login.code !== 0) {\n\t\t\tthrow new ComposeServerAdminUnreachable(adminTarget, login.stderr);\n\t\t}\n\t}\n\tconsole.log(` ✓ ${adminTarget} logs in with a key\\n`);\n\n\t// ── The server ─────────────────────────────────────────────────────────\n\tconst setup = await run(\n\t\t'ssh',\n\t\t[\n\t\t\t'-t',\n\t\t\t...asAdmin,\n\t\t\tadminTarget,\n\t\t\tremoteCommand(\n\t\t\t\tSERVER_SCRIPT,\n\t\t\t\t[admin, server.user, String(server.port), publicKey, comment],\n\t\t\t\ttrue,\n\t\t\t),\n\t\t],\n\t\t{ interactive: true },\n\t);\n\tif (setup.code !== 0) {\n\t\tthrow new ComposeServerSetupFailed(adminTarget, setup.code);\n\t}\n\tconst serverFingerprint = setup.stdout\n\t\t.replaceAll('\\r', '')\n\t\t.match(/^HOSTKEY=(\\S+)$/m)?.[1];\n\tif (!serverFingerprint) {\n\t\tthrow new ComposeServerSetupFailed(adminTarget, setup.code);\n\t}\n\n\t// ── The host key, pinned ───────────────────────────────────────────────\n\tconst scan = await run('ssh-keyscan', [\n\t\t'-t',\n\t\t'ed25519',\n\t\t'-p',\n\t\tString(server.port),\n\t\tserver.host,\n\t]);\n\tconst knownHosts = scan.stdout\n\t\t.split('\\n')\n\t\t.filter((line) => line.trim() && !line.startsWith('#'))\n\t\t.join('\\n');\n\tconst [scanned = ''] = await fingerprints(run, knownHosts);\n\tif (scanned !== serverFingerprint) {\n\t\tthrow new ComposeServerHostKeyMismatch(\n\t\t\tserver.host,\n\t\t\tserverFingerprint,\n\t\t\tscanned,\n\t\t);\n\t}\n\tconsole.log(`\\n ✓ Host key ${scanned}, as the server reports it`);\n\n\tif (repo) {\n\t\tgh(['api', '--method', 'PUT', `repos/${repo}/environments/${stage}`]);\n\t\tgh([\n\t\t\t'variable',\n\t\t\t'set',\n\t\t\t'DEPLOY_KNOWN_HOSTS',\n\t\t\t'--env',\n\t\t\tstage,\n\t\t\t'--repo',\n\t\t\trepo,\n\t\t\t'--body',\n\t\t\tknownHosts,\n\t\t]);\n\t\t// Through stdin, so the key is never an argument a process list shows.\n\t\tgh(\n\t\t\t['secret', 'set', 'DEPLOY_SSH_KEY', '--env', stage, '--repo', repo],\n\t\t\tawait readFile(keyFile, 'utf-8'),\n\t\t);\n\t\tconsole.log(\n\t\t\t` ✓ GitHub: environment \"${stage}\", DEPLOY_SSH_KEY and DEPLOY_KNOWN_HOSTS`,\n\t\t);\n\t}\n\n\t// ── Logged in as CI will be ────────────────────────────────────────────\n\tconst known = join(dirname(keyFile), `.gkm-known-${workspace.name}-${stage}`);\n\tawait writeFile(known, `${knownHosts}\\n`);\n\ttry {\n\t\tconst asCi = [\n\t\t\t'-i',\n\t\t\tkeyFile,\n\t\t\t'-o',\n\t\t\t'IdentitiesOnly=yes',\n\t\t\t'-o',\n\t\t\t'BatchMode=yes',\n\t\t\t'-o',\n\t\t\t`UserKnownHostsFile=${known}`,\n\t\t\t'-o',\n\t\t\t'StrictHostKeyChecking=yes',\n\t\t\t...sshOptions(server),\n\t\t];\n\t\tconst docker = await run('ssh', [\n\t\t\t...asCi,\n\t\t\tdeployTarget,\n\t\t\t'docker',\n\t\t\t'version',\n\t\t\t'--format',\n\t\t\t'{{.Server.Version}}',\n\t\t]);\n\t\tif (docker.code !== 0) {\n\t\t\tthrow new ComposeServerCheckFailed(deployTarget, 'docker', docker.stderr);\n\t\t}\n\t\tconsole.log(\n\t\t\t` ✓ ${deployTarget} runs docker (engine ${docker.stdout.trim()})`,\n\t\t);\n\t\t// The server's own sshd, through a tunnel: what a migration does to\n\t\t// reach Postgres on the server's loopback.\n\t\tconst tunnel = await run('ssh', [\n\t\t\t...asCi,\n\t\t\t'-W',\n\t\t\t`127.0.0.1:${server.port}`,\n\t\t\tdeployTarget,\n\t\t]);\n\t\tif (!tunnel.stdout.startsWith('SSH-2.0')) {\n\t\t\tthrow new ComposeServerCheckFailed(\n\t\t\t\tdeployTarget,\n\t\t\t\t'tunnel',\n\t\t\t\ttunnel.stdout.slice(0, 80) || tunnel.stderr,\n\t\t\t);\n\t\t}\n\t\tconsole.log(` ✓ ${deployTarget} opens tunnels (migrations)`);\n\t} finally {\n\t\tawait rm(known, { force: true });\n\t}\n\n\t// Done: the stage's state says so, and who did it.\n\tconst journal = await DeployJournal.open(state, stage, () =>\n\t\tcreateComposeState(stage),\n\t);\n\tawait journal.ready(\n\t\t{\n\t\t\tkey: SERVER_RECORD,\n\t\t\ttype: 'server',\n\t\t\tdata: { host: server.host } satisfies ServerRecordData,\n\t\t},\n\t\tserver.host,\n\t);\n\tconsole.log(` ✓ Recorded in the \"${stage}\" state`);\n\n\tconsole.log(\n\t\t`\\n✅ ${server.host} is ready for \"${stage}\".${repo ? ' CI deploys it with the key it was given.' : ''} ` +\n\t\t\t`To deploy from here, load the key first: ssh-add ${keyFile}\\n`,\n\t);\n\treturn {\n\t\tserver,\n\t\tadmin,\n\t\tkeyFile,\n\t\tknownHosts,\n\t\t...(repo ? { repo } : {}),\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;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