superfactory 0.0.0-stage → 0.4.30

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 (308) hide show
  1. package/README.md +34 -2
  2. package/THIRD-PARTY-NOTICES.md +27604 -0
  3. package/bin/superfactory.js +57 -0
  4. package/cli/agent-rf446fr1.js +2 -0
  5. package/cli/agent-state-wv62c1td.js +2 -0
  6. package/cli/bin-0cvfmkhh.js +33 -0
  7. package/cli/bin-0t68hf99.js +3 -0
  8. package/cli/bin-19vpzq7g.js +4 -0
  9. package/cli/bin-37w316c6.js +3 -0
  10. package/cli/bin-3dsqxzbz.js +3 -0
  11. package/cli/bin-4j0jjd8g.js +3 -0
  12. package/cli/bin-4tdqjbbd.js +229 -0
  13. package/cli/bin-4zvje4sn.js +502 -0
  14. package/cli/bin-674kd343.js +7 -0
  15. package/cli/bin-8jdkg4ke.js +3 -0
  16. package/cli/bin-d99yte0j.js +5 -0
  17. package/cli/bin-fgvkq9cq.js +867 -0
  18. package/cli/bin-fkp3j5f3.js +3 -0
  19. package/cli/bin-fypan1f6.js +951 -0
  20. package/cli/bin-gg19acwr.js +4 -0
  21. package/cli/bin-ghp5x0x5.js +139 -0
  22. package/cli/bin-gk00mnmn.js +5 -0
  23. package/cli/bin-gne2w036.js +29 -0
  24. package/cli/bin-grxzwpe8.js +3 -0
  25. package/cli/bin-h57gajkz.js +8 -0
  26. package/cli/bin-mbpvzx2b.js +8 -0
  27. package/cli/bin-nnq8kd9z.js +4 -0
  28. package/cli/bin-ven2efjq.js +3 -0
  29. package/cli/bin-yqb1d1mw.js +22 -0
  30. package/cli/bin-z5b3tt05.js +20 -0
  31. package/cli/bin-za1by1n5.js +3 -0
  32. package/cli/bin-zpfe0pxz.js +1 -0
  33. package/cli/bin.js +3 -0
  34. package/cli/child-agent-qgeqvs03.js +4 -0
  35. package/cli/connect-chn8pxyf.js +2 -0
  36. package/cli/container-j6zr9gww.js +4 -0
  37. package/cli/dev-gsaehf19.js +7 -0
  38. package/cli/health-nqzge5kh.js +2 -0
  39. package/cli/home-lock-5seng0k3.js +2 -0
  40. package/cli/host-7dfjhf0z.js +1507 -0
  41. package/cli/index-1wseh1tm.js +2 -0
  42. package/cli/index-axfe8zef.js +2 -0
  43. package/cli/index-s9pw90xe.js +2 -0
  44. package/cli/install-17r8t45e.js +2 -0
  45. package/cli/join-551zg7yr.js +31 -0
  46. package/cli/local-server-2smsafvg.js +2 -0
  47. package/cli/machine-zfjmpw7h.js +2 -0
  48. package/cli/main-0mxhd968.js +33 -0
  49. package/cli/main-53qmhxmd.js +303 -0
  50. package/cli/move-to-xrr2b135.js +2 -0
  51. package/cli/npm-package.json +1 -0
  52. package/cli/pair-phone-070c9ztt.js +5 -0
  53. package/cli/prompt-psc4drtd.js +2 -0
  54. package/cli/reached-vwzx2cdg.js +2 -0
  55. package/cli/sessions-bm4mk37y.js +3 -0
  56. package/cli/sf-cli-s42gkp0b.js +2 -0
  57. package/cli/sf-db-r8f1a20b.js +23 -0
  58. package/cli/sf-deploy-wqaa4fdm.js +21 -0
  59. package/cli/sf-pr-rg3q3tn6.js +13 -0
  60. package/cli/sf-test-pff158qc.js +10 -0
  61. package/cli/tart-isolation-wr3xwfmw.js +3 -0
  62. package/cli/tray-4rr0y1dv.png +0 -0
  63. package/cli/tray-mac-offline-89dva0gs.png +0 -0
  64. package/cli/tray-mac-paused-hq3a1cxv.png +0 -0
  65. package/cli/tray-mac-tvtavf0g.png +0 -0
  66. package/cli/tray-offline-xj6b5ta4.png +0 -0
  67. package/cli/tray-paused-6pzdv5ze.png +0 -0
  68. package/cli/vm-keeper-p0ggcw3z.js +3 -0
  69. package/package.json +50 -4
  70. package/plugins/sf-video-review/.claude-plugin/plugin.json +17 -0
  71. package/plugins/sf-video-review/.mcp.json +9 -0
  72. package/plugins/sf-video-review/dist/video-review.mjs +135 -0
  73. package/plugins/sf-video-review/skills/video-review/SKILL.md +65 -0
  74. package/plugins/sf-video-studio/.claude-plugin/plugin.json +17 -0
  75. package/plugins/sf-video-studio/.mcp.json +19 -0
  76. package/plugins/sf-video-studio/dist/demo-video.mjs +139 -0
  77. package/plugins/sf-video-studio/dist/narration-voice.mjs +134 -0
  78. package/plugins/sf-video-studio/dist/video-generation.mjs +131 -0
  79. package/plugins/sf-video-studio/fonts/DejaVuSansMono-Bold.ttf +0 -0
  80. package/plugins/sf-video-studio/fonts/DejaVuSansMono.ttf +0 -0
  81. package/plugins/sf-video-studio/fonts/LICENSE-DejaVu +187 -0
  82. package/plugins/sf-video-studio/hooks/hooks.json +17 -0
  83. package/plugins/sf-video-studio/hooks/no-robot-voice.sh +77 -0
  84. package/plugins/sf-video-studio/kokoro/package-lock.json +1137 -0
  85. package/plugins/sf-video-studio/kokoro/package.json +11 -0
  86. package/plugins/sf-video-studio/skills/demo-video/SKILL.md +101 -0
  87. package/plugins/sf-video-studio/skills/narration-voice/SKILL.md +49 -0
  88. package/plugins/sf-video-studio/skills/video-generation/SKILL.md +30 -0
  89. package/server/dist/account.js +3 -0
  90. package/server/dist/backup-process.js +2 -0
  91. package/server/dist/backup.js +3 -0
  92. package/server/dist/chunk-0tbq288f.js +3055 -0
  93. package/server/dist/chunk-18n7tr66.js +3 -0
  94. package/server/dist/chunk-1kgfrgmv.js +3 -0
  95. package/server/dist/chunk-1rnmxaav.js +209 -0
  96. package/server/dist/chunk-26zhqbyn.js +25 -0
  97. package/server/dist/chunk-34mn2zj2.js +2 -0
  98. package/server/dist/chunk-3psgsw9t.js +2 -0
  99. package/server/dist/chunk-8zbwppny.js +391 -0
  100. package/server/dist/chunk-9pn7q001.js +3 -0
  101. package/server/dist/chunk-9y7a9gkf.js +2 -0
  102. package/server/dist/chunk-bhm6jzch.js +8 -0
  103. package/server/dist/chunk-dbzjsqvb.js +17 -0
  104. package/server/dist/chunk-fxn504n0.js +2 -0
  105. package/server/dist/chunk-g6pwaap3.js +2 -0
  106. package/server/dist/chunk-gefgv8rg.js +7 -0
  107. package/server/dist/chunk-jg8b833v.js +2 -0
  108. package/server/dist/chunk-jy148bhn.js +3 -0
  109. package/server/dist/chunk-ky4nz39j.js +7 -0
  110. package/server/dist/chunk-mbd1y9qk.js +2 -0
  111. package/server/dist/chunk-neyhk32g.js +13 -0
  112. package/server/dist/chunk-nrz953bx.js +2 -0
  113. package/server/dist/chunk-padvv31s.js +2 -0
  114. package/server/dist/chunk-q1s2ez77.js +3 -0
  115. package/server/dist/chunk-q403h2bh.js +10 -0
  116. package/server/dist/chunk-t64r6enn.js +4 -0
  117. package/server/dist/chunk-vccappg7.js +59 -0
  118. package/server/dist/chunk-vj60fbhw.js +2 -0
  119. package/server/dist/chunk-xj26rwda.js +3 -0
  120. package/server/dist/chunk-xyw98jst.js +5 -0
  121. package/server/dist/main.js +43 -0
  122. package/server/dist/move.js +3 -0
  123. package/server/drizzle/pg/0000_baseline.sql +632 -0
  124. package/server/drizzle/pg/0001_transcripts_packed.sql +2 -0
  125. package/server/drizzle/pg/0002_vm_server_origin.sql +1 -0
  126. package/server/drizzle/pg/0003_reached_machines.sql +1 -0
  127. package/server/drizzle/pg/0004_link_records.sql +2 -0
  128. package/server/drizzle/pg/0005_task_columns.sql +7 -0
  129. package/server/drizzle/pg/0006_task_bundle.sql +3 -0
  130. package/server/drizzle/pg/0007_server_log.sql +9 -0
  131. package/server/drizzle/pg/0008_notification_pauses.sql +6 -0
  132. package/server/drizzle/pg/0009_vm_replaces.sql +1 -0
  133. package/server/drizzle/pg/0010_question_told_once.sql +10 -0
  134. package/server/drizzle/pg/0011_node_next_key.sql +3 -0
  135. package/server/drizzle/pg/0012_task_work.sql +8 -0
  136. package/server/drizzle/pg/0013_task_secret_grants.sql +9 -0
  137. package/server/drizzle/pg/0014_node_paused.sql +2 -0
  138. package/server/drizzle/pg/0015_ssh_machines.sql +19 -0
  139. package/server/drizzle/pg/0016_node_wake.sql +1 -0
  140. package/server/drizzle/pg/0017_node_uninstall_key.sql +1 -0
  141. package/server/drizzle/pg/0018_release_starts.sql +6 -0
  142. package/server/drizzle/pg/0019_session_memory.sql +7 -0
  143. package/server/drizzle/pg/meta/_journal.json +146 -0
  144. package/server/drizzle/sqlite/0000_pre_drizzle_schema.sql +351 -0
  145. package/server/drizzle/sqlite/0001_cluster.sql +36 -0
  146. package/server/drizzle/sqlite/0002_task_records.sql +22 -0
  147. package/server/drizzle/sqlite/0003_indexes.sql +12 -0
  148. package/server/drizzle/sqlite/0004_project_machines.sql +19 -0
  149. package/server/drizzle/sqlite/0005_session_events.sql +7 -0
  150. package/server/drizzle/sqlite/0006_task_platforms.sql +8 -0
  151. package/server/drizzle/sqlite/0007_session_event_tags.sql +7 -0
  152. package/server/drizzle/sqlite/0008_sprints.sql +7 -0
  153. package/server/drizzle/sqlite/0009_project_vms.sql +19 -0
  154. package/server/drizzle/sqlite/0010_server_repairs.sql +4 -0
  155. package/server/drizzle/sqlite/0011_drop_todos.sql +2 -0
  156. package/server/drizzle/sqlite/0012_hypervisors.sql +14 -0
  157. package/server/drizzle/sqlite/0013_manager_leads.sql +2 -0
  158. package/server/drizzle/sqlite/0014_session_text.sql +35 -0
  159. package/server/drizzle/sqlite/0015_vm_resize_machine_instructions_access.sql +22 -0
  160. package/server/drizzle/sqlite/0016_tunnel.sql +23 -0
  161. package/server/drizzle/sqlite/0017_session_secret_grants.sql +7 -0
  162. package/server/drizzle/sqlite/0018_https.sql +18 -0
  163. package/server/drizzle/sqlite/0019_secret_grant_runs.sql +1 -0
  164. package/server/drizzle/sqlite/0020_session_transcripts.sql +16 -0
  165. package/server/drizzle/sqlite/0021_claude_signed_out.sql +2 -0
  166. package/server/drizzle/sqlite/0022_machine_disabled.sql +1 -0
  167. package/server/drizzle/sqlite/0023_machine_access_granted_by.sql +1 -0
  168. package/server/drizzle/sqlite/0024_machine_vms.sql +27 -0
  169. package/server/drizzle/sqlite/0025_machine_tunnel_fallback.sql +1 -0
  170. package/server/drizzle/sqlite/0026_tunnel_peer_linked.sql +3 -0
  171. package/server/drizzle/sqlite/0027_tunnel_upgrade_grace.sql +2 -0
  172. package/server/drizzle/sqlite/0028_dialed_machines.sql +2 -0
  173. package/server/drizzle/sqlite/0029_node_link.sql +3 -0
  174. package/server/drizzle/sqlite/0030_sprint_calendar.sql +1 -0
  175. package/server/drizzle/sqlite/0031_transcripts_packed.sql +2 -0
  176. package/server/drizzle/sqlite/0032_vm_server_origin.sql +1 -0
  177. package/server/drizzle/sqlite/meta/_journal.json +237 -0
  178. package/server/src/account.ts +2 -0
  179. package/server/src/backup.ts +2 -0
  180. package/server/src/features/backups/backup-process.ts +2 -0
  181. package/server/src/main.ts +2 -0
  182. package/server/src/move.ts +2 -0
  183. package/ui/dist/_expo/static/css/global-d378e211074d97e633bc15418ccf57d4.css +2 -0
  184. package/ui/dist/_expo/static/css/xterm-8a7c4e0dca731c11dbe6bdff98fb667c.css +1 -0
  185. package/ui/dist/_expo/static/js/web/Network-f300a5960620f5029c91c06cae29dba5.js +3 -0
  186. package/ui/dist/_expo/static/js/web/[...rest]-9e454d985f211f5c983f42bec15b6ad9.js +1 -0
  187. package/ui/dist/_expo/static/js/web/[managerId]-2580b90e8d862ad66197eecb1dc04a12.js +1 -0
  188. package/ui/dist/_expo/static/js/web/[managerId]-39308153b42eed025c0abb9242ae6c71.js +1 -0
  189. package/ui/dist/_expo/static/js/web/[managerId]-8b7a94ec818e50a371b6b2750b73df6a.js +1 -0
  190. package/ui/dist/_expo/static/js/web/[managerId]-ac3a14c7607e4576d7e6c39c1014bcaf.js +1 -0
  191. package/ui/dist/_expo/static/js/web/[managerId]-e8549b2313a119437c373e30207518c0.js +1 -0
  192. package/ui/dist/_expo/static/js/web/[ref]-9b46f1ec4348f980e9838b68d47c34bf.js +2 -0
  193. package/ui/dist/_expo/static/js/web/[sessionId]-09e376674fb8b3edc4ae8aa9b3a189d7.js +1 -0
  194. package/ui/dist/_expo/static/js/web/[sessionId]-0e5fdba25c9f78220cea4cb66227743d.js +1 -0
  195. package/ui/dist/_expo/static/js/web/[sessionId]-104af3c3885009e6a8d204b6fd6e2c3a.js +1 -0
  196. package/ui/dist/_expo/static/js/web/[sessionId]-863a34ca3835b469134ddbc4ebc6fafc.js +1 -0
  197. package/ui/dist/_expo/static/js/web/[taskId]-1218e1dd3ecf175ffb7701fc886d62c9.js +1 -0
  198. package/ui/dist/_expo/static/js/web/[taskId]-31a48c7017dbd096f8ece9dc102a9762.js +1 -0
  199. package/ui/dist/_expo/static/js/web/[taskId]-a56cf85bcfd14f2d6b5d4180ea17e8d7.js +1 -0
  200. package/ui/dist/_expo/static/js/web/[taskId]-f2a157b3cb676b3c5d04c8eadfe90cdd.js +1 -0
  201. package/ui/dist/_expo/static/js/web/__common-1ad58e53e08528a67b99f53a1690b669.js +2078 -0
  202. package/ui/dist/_expo/static/js/web/__expo-metro-runtime-1f8f5d3ca6b7f58204d51e14506d73fb.js +5 -0
  203. package/ui/dist/_expo/static/js/web/_layout-057457e97e0af20433ed41b39cb5e809.js +1 -0
  204. package/ui/dist/_expo/static/js/web/_layout-2a7d73d5356823e1f7d2dab23e440d09.js +7 -0
  205. package/ui/dist/_expo/static/js/web/_layout-42e6a6b7855655d456015ce41aefdd39.js +1 -0
  206. package/ui/dist/_expo/static/js/web/_layout-a5e5a5b2fb3bfbfcc2914131976679e7.js +1 -0
  207. package/ui/dist/_expo/static/js/web/_layout-b2cbba92506f66815a5d744fd7cd5d8c.js +1 -0
  208. package/ui/dist/_expo/static/js/web/_layout-b4d13dc52bbcb65b18b4e52813d53883.js +198 -0
  209. package/ui/dist/_expo/static/js/web/_layout-fb0f75b354800de2e1582dc963f5c148.js +1 -0
  210. package/ui/dist/_expo/static/js/web/index-41299a961569cc8e5410ec53ba2b87c4.js +4 -0
  211. package/ui/dist/_expo/static/js/web/index-6c2bb0d3b6d00c5c007a663e9f4ce108.js +1 -0
  212. package/ui/dist/_expo/static/js/web/index-70484f7d2769d9ae01dac1fdb22aef1d.js +14 -0
  213. package/ui/dist/_expo/static/js/web/index-7d764cb7cefe0a217728c24d44990057.js +14 -0
  214. package/ui/dist/_expo/static/js/web/index-a5eb3d0c6aa4c483674beb5de428634c.js +12 -0
  215. package/ui/dist/_expo/static/js/web/index-b1c2543003cba86eeb3abfa4d21fd8da.js +14 -0
  216. package/ui/dist/_expo/static/js/web/index-d200aded5448966e5e05d9ccb77b56a4.js +5 -0
  217. package/ui/dist/_expo/static/js/web/index-ea43f51ceec4a981c942fc6dce9cedc4.js +2378 -0
  218. package/ui/dist/_expo/static/js/web/index-efa68d817a7febbf8c0163303bf4cd49.js +29 -0
  219. package/ui/dist/_expo/static/js/web/licenses-30f8c0555f7f4d434a68ee4706fa433d.js +1 -0
  220. package/ui/dist/_expo/static/js/web/pair-3f6f72208023894f43f4f07db5116cca.js +1 -0
  221. package/ui/dist/_expo/static/js/web/rich-markdown-editor-dea9c0f7c0306da4146e54ee44cce173.js +228 -0
  222. package/ui/dist/_expo/static/js/web/sign-in-67d2a0c00232e0e6f40efade1a83dc4b.js +4 -0
  223. package/ui/dist/_expo/static/js/web/terminal-view-32db8e6f8a21dd073f6a310862d36db8.js +90 -0
  224. package/ui/dist/apple-touch-icon.png +0 -0
  225. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/100Thin/GeistMono_100Thin.95eed4519d8c395e41b3b837ca97edea.ttf +0 -0
  226. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/100Thin_Italic/GeistMono_100Thin_Italic.2e50fb9a43d70ceb4925a2c54502097c.ttf +0 -0
  227. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/200ExtraLight/GeistMono_200ExtraLight.0714ea94ac265d76bc16698dd1808599.ttf +0 -0
  228. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/200ExtraLight_Italic/GeistMono_200ExtraLight_Italic.107f2670e94507223548f1d38eb14087.ttf +0 -0
  229. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/300Light/GeistMono_300Light.d6a3533adfd5834dd9f68ee37faa1e2d.ttf +0 -0
  230. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/300Light_Italic/GeistMono_300Light_Italic.09420cdceda8d1f1612daceae1e4890e.ttf +0 -0
  231. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/400Regular/GeistMono_400Regular.3656dcb247d3a6cd141f7601c2101125.ttf +0 -0
  232. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/400Regular_Italic/GeistMono_400Regular_Italic.88343c321b266476ad3bc56735cc6ac7.ttf +0 -0
  233. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/500Medium/GeistMono_500Medium.a298cd61aebdb709299e2a7deb73ed93.ttf +0 -0
  234. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/500Medium_Italic/GeistMono_500Medium_Italic.e149441dd9360bd7dbffeb1de9aa1685.ttf +0 -0
  235. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/600SemiBold/GeistMono_600SemiBold.cae945cb3b6156e396a1008b6252af21.ttf +0 -0
  236. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/600SemiBold_Italic/GeistMono_600SemiBold_Italic.e939ba436795ee2f0a379e7271bb957d.ttf +0 -0
  237. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/700Bold/GeistMono_700Bold.7fcc8478bc1dcadc865d97626ba3206b.ttf +0 -0
  238. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/700Bold_Italic/GeistMono_700Bold_Italic.8cc57ff1f3c45e7ed84e74853c141e06.ttf +0 -0
  239. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/800ExtraBold/GeistMono_800ExtraBold.b09b5457204e06ea7bacff03f0880065.ttf +0 -0
  240. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/800ExtraBold_Italic/GeistMono_800ExtraBold_Italic.0b4dd8c1b0e6d8791ea34c8f1417edfd.ttf +0 -0
  241. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/900Black/GeistMono_900Black.9ec025adf049c8a476588eeac81a36e4.ttf +0 -0
  242. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/900Black_Italic/GeistMono_900Black_Italic.8dfe24b2fef43fb3d535316e2412be7d.ttf +0 -0
  243. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/100Thin/HankenGrotesk_100Thin.2d9c9415d97b66fb3bbca06b538f11d8.ttf +0 -0
  244. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/100Thin_Italic/HankenGrotesk_100Thin_Italic.5ad53da9f1ff702f55cf870763a159ff.ttf +0 -0
  245. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/200ExtraLight/HankenGrotesk_200ExtraLight.2cae1a1078b5af081aff084011b07522.ttf +0 -0
  246. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/200ExtraLight_Italic/HankenGrotesk_200ExtraLight_Italic.5d4eff887cdb33164b4fba2066c687e3.ttf +0 -0
  247. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/300Light/HankenGrotesk_300Light.2be9fd730ff95b91631e3f99bc449709.ttf +0 -0
  248. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/300Light_Italic/HankenGrotesk_300Light_Italic.4ae6910889ffdf69093da607b369b0a8.ttf +0 -0
  249. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/400Regular/HankenGrotesk_400Regular.2e544d6119b4e635f6cc5a47800523bb.ttf +0 -0
  250. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/400Regular_Italic/HankenGrotesk_400Regular_Italic.ed9d322cffe9e614205ce9512f144834.ttf +0 -0
  251. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/500Medium/HankenGrotesk_500Medium.a822d33614b51eb05478e0e29cf757f3.ttf +0 -0
  252. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/500Medium_Italic/HankenGrotesk_500Medium_Italic.bc71c45237e12974e52335b615fab7da.ttf +0 -0
  253. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/600SemiBold/HankenGrotesk_600SemiBold.b016ff502f15ce9b59c453304c74fb48.ttf +0 -0
  254. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/600SemiBold_Italic/HankenGrotesk_600SemiBold_Italic.94428d43b74e372dc47910fd4fc6b552.ttf +0 -0
  255. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/700Bold/HankenGrotesk_700Bold.14d2af6df606492d846389d2108dae50.ttf +0 -0
  256. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/700Bold_Italic/HankenGrotesk_700Bold_Italic.d075966aaf26126d8aaac0802735e310.ttf +0 -0
  257. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/800ExtraBold/HankenGrotesk_800ExtraBold.b419489745bc870b4e4288e969945f31.ttf +0 -0
  258. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/800ExtraBold_Italic/HankenGrotesk_800ExtraBold_Italic.ea7ac4778026e067a5d637f4a494b2d2.ttf +0 -0
  259. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/900Black/HankenGrotesk_900Black.55e860e6549b53fa530d9eda7c7518a2.ttf +0 -0
  260. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/900Black_Italic/HankenGrotesk_900Black_Italic.dcad6f722a66aae93f70a72604112754.ttf +0 -0
  261. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/200ExtraLight/Newsreader_200ExtraLight.1ee07dc260606863f8bf8101308d85f2.ttf +0 -0
  262. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/200ExtraLight_Italic/Newsreader_200ExtraLight_Italic.52c51abab458715d1205b8732b55735f.ttf +0 -0
  263. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/300Light/Newsreader_300Light.bf0dfa126654b01f65e1c53a4507ec12.ttf +0 -0
  264. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/300Light_Italic/Newsreader_300Light_Italic.03190fe46aa9b7083610981ac13b10f3.ttf +0 -0
  265. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/400Regular/Newsreader_400Regular.b1d919187d5645f84124ef065868ba9e.ttf +0 -0
  266. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/400Regular_Italic/Newsreader_400Regular_Italic.f7b81d92eb42d85de96b6dc1c72d2c36.ttf +0 -0
  267. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/500Medium/Newsreader_500Medium.df89e83cfd4e37176dda53076a01b3b7.ttf +0 -0
  268. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/500Medium_Italic/Newsreader_500Medium_Italic.fb45099c4fb3c395e8f12e181475230c.ttf +0 -0
  269. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/600SemiBold/Newsreader_600SemiBold.20bce29dc5180892ce1fbf4a563737a0.ttf +0 -0
  270. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/600SemiBold_Italic/Newsreader_600SemiBold_Italic.93e2816e201fa363d3289e741f757ff0.ttf +0 -0
  271. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/700Bold/Newsreader_700Bold.bf7c54edbd2afe9b289d5da777f489e9.ttf +0 -0
  272. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/700Bold_Italic/Newsreader_700Bold_Italic.e2f5e5260513d7d4f9f3edbdcbc9f43f.ttf +0 -0
  273. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/800ExtraBold/Newsreader_800ExtraBold.702211ca77927e4c276b28169dc3694c.ttf +0 -0
  274. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/800ExtraBold_Italic/Newsreader_800ExtraBold_Italic.9b9eacc7d72e5152e692cb144ef7a9fd.ttf +0 -0
  275. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png +0 -0
  276. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png +0 -0
  277. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png +0 -0
  278. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png +0 -0
  279. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png +0 -0
  280. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/drawer/toggle-drawer-icon.ae74bb20586a731af545e6b00fe14a09.png +0 -0
  281. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png +0 -0
  282. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png +0 -0
  283. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png +0 -0
  284. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png +0 -0
  285. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png +0 -0
  286. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png +0 -0
  287. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png +0 -0
  288. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png +0 -0
  289. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png +0 -0
  290. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png +0 -0
  291. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png +0 -0
  292. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png +0 -0
  293. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png +0 -0
  294. package/ui/dist/favicon.ico +0 -0
  295. package/ui/dist/favicon.svg +10 -0
  296. package/ui/dist/icon-192.png +0 -0
  297. package/ui/dist/icon-512.png +0 -0
  298. package/ui/dist/index.html +45 -0
  299. package/ui/dist/legal/privacy-policy.md +174 -0
  300. package/ui/dist/legal/terms-of-use.md +76 -0
  301. package/ui/dist/load-again.js +42 -0
  302. package/ui/dist/manifest.webmanifest +12 -0
  303. package/ui/dist/metadata.json +1 -0
  304. package/ui/dist/sounds/bell.wav +0 -0
  305. package/ui/dist/sounds/chime.wav +0 -0
  306. package/ui/dist/sounds/knock.wav +0 -0
  307. package/ui/dist/sounds/pop.wav +0 -0
  308. package/ui/dist/sw.js +121 -0
@@ -0,0 +1,1507 @@
1
+ // @bun
2
+ import{A,ru,au,gu,l,r,g}from"./bin-h57gajkz.js";import{_r,le,tn,Lt,Cp}from"./main-53qmhxmd.js";import{e,la,J,i,n,o,t,d,Bc,xs}from"./bin-4tdqjbbd.js";import{lo,Ht,us,un,zt,pn,Ki,Yi,ls,Ji}from"./bin-4j0jjd8g.js";import{go}from"./bin-ghp5x0x5.js";import{chmodSync as Bs,closeSync as Qt,constants as Se,existsSync as Xt,fchmodSync as Vs,lstatSync as Ks,mkdirSync as Le,openSync as es,readFileSync as qs,readSync as zs,statSync as Jt,writeFileSync as Zt,writeSync as Ws}from"fs";import{homedir as Xs}from"os";import{join as ue,resolve as ye}from"path";import{readFileSync as rs,statSync as os}from"fs";var Ge="ghcr.io/cloudnative-pg/postgresql:18.7-system-trixie@sha256:5a5dfbde88d5909fd4938189c141f53fb153f53c519f14907dce9e7c04baa153",Me="docker.io/library/registry:3.1.2@sha256:82f6ff4a7f982960c8aa51617fea3aabc485df6e55cce80d22deb1de36f1bc3c",je="https://acme-v02.api.letsencrypt.org/directory";var Ye=e().trim().toLowerCase().regex(/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,"a DNS name, like sf.example.com"),pe=e().trim().regex(/^[0-9a-f.:]+(\/\d{1,3})?$/i,"an address or network, like 10.20.40.0/24"),fe=e().trim().regex(/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/,"an S3 bucket's name"),me=e().trim().transform((s)=>s.replace(/^\/+|\/+$/g,"")).refine((s)=>!/[\s\\]|\/\//.test(s),"a path like superfactory/backups"),ns=e().trim().regex(/^[\w][\w.-]{0,127}$/),Be=e().trim().regex(/^[a-z0-9.-]+(:\d+)?(\/[a-z0-9._-]+)+(:[\w][\w.-]{0,127})?@sha256:[0-9a-f]{64}$/,"repository@sha256:\u2026"),he=t({domain:Ye,previewsDomain:Ye.optional(),acme:t({email:la(),solver:d(["cloudflare","http"]).default("http"),server:J().default(je),caBundle:e().optional()}),s3:t({endpoint:J(),region:e().trim().min(1).default("us-east-1")}),files:t({bucket:fe,prefix:me.default("")}),backups:t({bucket:fe.optional(),prefix:me.default("backups")}).default({prefix:"backups"}),postgres:t({bucket:fe,path:me.default(""),serverName:e().regex(/^[a-z0-9][a-z0-9-]{0,62}$/).optional(),retention:e().regex(/^\d+[dwm]$/).default("30d"),backupAt:e().regex(/^([01]\d|2[0-3]):[0-5]\d$/,"HH:MM, UTC").default("03:00"),image:Be.optional(),restore:t({bucket:fe.optional(),path:me.optional(),serverName:e().regex(/^[a-z0-9][a-z0-9-]{0,62}$/),endpoint:J().optional()}).optional()}),image:t({repository:e().trim().regex(/^[a-z0-9.-]+(:\d+)?(\/[a-z0-9._-]+)+$/).optional(),tag:ns.optional(),username:e().trim().min(1).optional(),from:e().trim().regex(/^[a-z0-9.-]+(:\d+)?(\/[a-z0-9._-]+)+:[\w][\w.-]{0,127}$/,"repository:tag").optional()}).default({}),registry:t({port:i().min(1024).max(65535).default(5000),keep:i().min(0).max(100).default(5),image:Be.optional()}).default({port:5000,keep:5}),owner:t({email:la()}).optional(),network:Bc((s)=>{if(!s||typeof s!=="object")return s;let{apiAllowFrom:a,apiAddress:c,...u}=s;return{deployFrom:a,address:c,...u}},t({allowFrom:o(pe).default([]),tunnelAllowFrom:o(pe).min(1).optional(),deployFrom:o(pe).default([]),sshFrom:o(pe).default([]),address:e().trim().min(1).optional(),firewall:n().default(!0)}).default({allowFrom:[],deployFrom:[],sshFrom:[],firewall:!0})),vm:t({name:e().trim().min(1).max(63).optional(),hypervisor:e().trim().min(1).max(100).optional()}).default({}),harvester:xs.optional(),standby:n().optional()}),ee={SF_HOST_S3_ACCESS_KEY_ID:"the S3 access key id",SF_HOST_S3_SECRET_ACCESS_KEY:"the S3 secret access key",SF_HOST_CLOUDFLARE_API_TOKEN:"a Cloudflare API token that may edit the zone's DNS (DNS-01)",SF_HOST_REGISTRY_PASSWORD:"the registry password (Harbor robot's secret)",SF_HOST_OWNER_PASSWORD:"the owner's password (at least 12 characters)",SF_HOST_MASTER_KEY:"the master key of the server being moved (else a new one is made on the VM)",SF_HOST_AUTH_SECRET:"the auth secret of the server being moved (else a new one is made on the VM)",SF_HOST_ENROLL_TOKEN:"the agents' enrollment token of the server being moved (else a new one is made)",SF_HOST_VAPID_PUBLIC_KEY:"the Web Push public key of the server being moved (else browsers subscribe again)",SF_HOST_VAPID_PRIVATE_KEY:"its Web Push private key",SF_HOST_HARVESTER_KUBECONFIG:"a kubeconfig that may make VMs in the Harvester namespace of the projects' VMs, as it is or base64 on one line",SF_HOST_CLOUDFLARE_TUNNEL_TOKEN:"the Cloudflare tunnel token of the server being moved (public access)",SF_HOST_POSTGRES_S3_ACCESS_KEY_ID:"the S3 access key id of Postgres's own bucket (its WAL and base backups), when other keys reach it (default the S3 one)",SF_HOST_POSTGRES_S3_SECRET_ACCESS_KEY:"its secret access key",SF_HOST_RESTORE_S3_ACCESS_KEY_ID:"the S3 access key id of the backups to recover from (default the S3 one)",SF_HOST_RESTORE_S3_SECRET_ACCESS_KEY:"its secret access key",SF_HOST_REPORT_TOKEN:"the VM's one-time token for --report (the server that made it gives it)"};function Ve(s){let a=["SF_HOST_S3_ACCESS_KEY_ID","SF_HOST_S3_SECRET_ACCESS_KEY"];if(s.acme.solver==="cloudflare")a.push("SF_HOST_CLOUDFLARE_API_TOKEN");if(s.image.username)a.push("SF_HOST_REGISTRY_PASSWORD");if(s.owner)a.push("SF_HOST_OWNER_PASSWORD");if(s.harvester)a.push("SF_HOST_HARVESTER_KUBECONFIG");let c=["SF_HOST_MASTER_KEY","SF_HOST_AUTH_SECRET","SF_HOST_ENROLL_TOKEN","SF_HOST_VAPID_PUBLIC_KEY","SF_HOST_VAPID_PRIVATE_KEY",...s.harvester?[]:["SF_HOST_HARVESTER_KUBECONFIG"],"SF_HOST_CLOUDFLARE_TUNNEL_TOKEN","SF_HOST_POSTGRES_S3_ACCESS_KEY_ID","SF_HOST_POSTGRES_S3_SECRET_ACCESS_KEY"];if(s.postgres.restore)c.push("SF_HOST_RESTORE_S3_ACCESS_KEY_ID","SF_HOST_RESTORE_S3_SECRET_ACCESS_KEY");return{required:a,optional:c}}function ve(s){let a=[];if(s.previewsDomain&&s.acme.solver!=="cloudflare")a.push("previews need a wildcard certificate, so DNS-01: acme.solver cloudflare (or no previewsDomain)");if(s.previewsDomain&&(s.previewsDomain===s.domain||s.domain.endsWith(`.${s.previewsDomain}`)))a.push("previewsDomain must sit beside the server's domain, not be it or under it");let{image:c}=s;if(c.repository&&!c.tag)a.push("image.repository needs image.tag");if(c.repository&&c.from)a.push("image.from is for the VM's own registry: not with image.repository");if(c.username&&!Te(s))a.push("image.username logs in to image.repository's registry, or a mirror's (postgres.image, registry.image): none is set");return a}function as(s){let a=s.split("/")[0];return s.includes("/")&&(/[.:]/.test(a)||a==="localhost")?a:"docker.io"}var U=(s)=>!s.image.repository;function Te(s){let a=s.image.repository??s.postgres.image??s.registry.image;return a?as(a):void 0}var B=(s)=>s.image.repository??`127.0.0.1:${s.registry.port}/superfactory-server`;function be(s){let a=he.safeParse(s);if(!a.success)throw Error(`the config: ${a.error.issues.map((u)=>`${u.path.join(".")||"(top)"}: ${u.message}`).join("; ")}`);let c=ve(a.data);if(c.length)throw Error(`the config: ${c.join("; ")}`);return a.data}function Ke(s){let a=os(s).mode&511;if(a&63)throw Error(`${s} is readable by others (mode ${a.toString(8)}): chmod 600 it`);return is(rs(s,"utf8"),s)}function is(s,a="the secrets"){let c={};for(let[u,f]of s.split(/\r?\n/).entries()){let p=f.trim();if(!p||p.startsWith("#"))continue;let h=p.indexOf("="),m=p.slice(0,h).trim();if(h<1||!(m in ee))throw Error(`${a}, line ${u+1}: not one of SF_HOST_*=\u2026`);let E=p.slice(h+1).trim();if(/^(['"]).*\1$/.test(E))E=E.slice(1,-1);if(E)c[m]=E}return c}function qe(s=process.env){let a={};for(let c of Object.keys(ee))if(s[c])a[c]=s[c];return a}var Re=(s)=>Object.values(s).filter((a)=>!!a&&a.length>=4).sort((a,c)=>c.length-a.length);var _="/opt/superfactory",y=`${_}/secrets`,O="/srv/superfactory",I=`${O}/state`,Xe=`${I}/lock`,Je=`${I}/paused`,x=`${O}/status`,X=`${O}/registry`,re=`${_}/registry`,se=2002,ze=6442450944,we="/run/superfactory/pg",$e="superfactory",oe="superfactory_readonly",M=2000,q=2001,We=1000,ge=26,Ae=102;var te={blue:{ready:8090,peer:8091,cloudflare:8094},green:{ready:8092,peer:8093,cloudflare:8095}},Oe=(s)=>`https://${s.domain}`,z=(s,a)=>(a.pgData?a.serverName:void 0)??s.postgres.serverName??`superfactory-pg-${a.hostname}`.slice(0,63),Ze=(s,a)=>`s3://${s}${a?`/${a}`:""}`,cs=(s)=>{let a={d:"DAYS",w:"WEEKS",m:"MONTHS"}[s.slice(-1)]??"DAYS";return`RECOVERY WINDOW OF ${s.slice(0,-1)} ${a}`},Ie=[{name:"master_key",group:"server",env:"SF_MASTER_KEY_FILE"},{name:"auth_secret",group:"server",env:"BETTER_AUTH_SECRET_FILE"},{name:"enroll_token",group:"server",env:"SF_AGENT_ENROLL_TOKEN_FILE"},{name:"setup_token",group:"server",env:"SF_SETUP_TOKEN_FILE"},{name:"db_url",group:"server",env:"SF_DATABASE_URL_FILE"},{name:"db_readonly_url",group:"server",env:"SF_DATABASE_READONLY_URL_FILE"},{name:"s3_access_key_id",group:"server",env:"SF_S3_ACCESS_KEY_ID_FILE"},{name:"s3_secret_access_key",group:"server",env:"SF_S3_SECRET_ACCESS_KEY_FILE"},{name:"dns_token",group:"server",env:"SF_HTTPS_DNS_TOKEN_FILE"},{name:"acme_ca",group:"server",env:"SF_ACME_CA_FILE"},{name:"owner_password",group:"server",env:"SF_OWNER_PASSWORD_FILE"},{name:"vapid_public_key",group:"server",env:"SF_VAPID_PUBLIC_KEY_FILE"},{name:"vapid_private_key",group:"server",env:"SF_VAPID_PRIVATE_KEY_FILE"},{name:"cloudflare_tunnel_token",group:"server",env:"CLOUDFLARE_TUNNEL_TOKEN_FILE"},{name:"harvester_kubeconfig",group:"server",env:"SF_HARVESTER_KUBECONFIG_FILE",target:"/run/secrets/superfactory/harvester_kubeconfig"},{name:"deploy_ssh",group:"server",env:"SF_DEPLOY_SSH_KEY_FILE"},{name:"deploy_registry_token",group:"server",env:"SF_DEPLOY_REGISTRY_TOKEN_FILE"},{name:"barman_s3",group:"pg"},{name:"registry_password",group:"root"},{name:"pg_owner_password",group:"pg"},{name:"pg_readonly_password",group:"pg"}],ds=(s)=>s.target??`/run/secrets/${s.name}`;function Ne(s,a){let c={},u=(h,m)=>{if(m)c[h]=m};u("s3_access_key_id",a.SF_HOST_S3_ACCESS_KEY_ID),u("s3_secret_access_key",a.SF_HOST_S3_SECRET_ACCESS_KEY);let f=a.SF_HOST_POSTGRES_S3_ACCESS_KEY_ID??a.SF_HOST_S3_ACCESS_KEY_ID,p=a.SF_HOST_POSTGRES_S3_SECRET_ACCESS_KEY??a.SF_HOST_S3_SECRET_ACCESS_KEY;if(f&&p){let h=a.SF_HOST_RESTORE_S3_ACCESS_KEY_ID??f,m=a.SF_HOST_RESTORE_S3_SECRET_ACCESS_KEY??p;c.barman_s3=["[default]",`aws_access_key_id = ${f}`,`aws_secret_access_key = ${p}`,"[origin]",`aws_access_key_id = ${h}`,`aws_secret_access_key = ${m}`,""].join(`
3
+ `)}if(s.acme.solver==="cloudflare")u("dns_token",a.SF_HOST_CLOUDFLARE_API_TOKEN);if(s.acme.caBundle)c.acme_ca=s.acme.caBundle;if(s.owner)u("owner_password",a.SF_HOST_OWNER_PASSWORD);if(s.image.username)u("registry_password",a.SF_HOST_REGISTRY_PASSWORD),u("deploy_registry_token",a.SF_HOST_REGISTRY_PASSWORD);if(a.SF_HOST_VAPID_PUBLIC_KEY&&a.SF_HOST_VAPID_PRIVATE_KEY)c.vapid_public_key=a.SF_HOST_VAPID_PUBLIC_KEY,c.vapid_private_key=a.SF_HOST_VAPID_PRIVATE_KEY;if(a.SF_HOST_HARVESTER_KUBECONFIG)c.harvester_kubeconfig=ps(a.SF_HOST_HARVESTER_KUBECONFIG);return u("cloudflare_tunnel_token",a.SF_HOST_CLOUDFLARE_TUNNEL_TOKEN),c}var ps=(s)=>/^[A-Za-z0-9+/=\s]+$/.test(s)?Buffer.from(s,"base64").toString("utf8"):s,Qe={s3_secret_access_key:["SF_HOST_S3_ACCESS_KEY_ID","SF_HOST_S3_SECRET_ACCESS_KEY"],dns_token:["SF_HOST_CLOUDFLARE_API_TOKEN"],owner_password:["SF_HOST_OWNER_PASSWORD"],registry_password:["SF_HOST_REGISTRY_PASSWORD"],deploy_registry_token:["SF_HOST_REGISTRY_PASSWORD"],vapid_private_key:["SF_HOST_VAPID_PUBLIC_KEY","SF_HOST_VAPID_PRIVATE_KEY"],harvester_kubeconfig:["SF_HOST_HARVESTER_KUBECONFIG"],cloudflare_tunnel_token:["SF_HOST_CLOUDFLARE_TUNNEL_TOKEN"]};function et(s,a){let c={SF_HOST:"0.0.0.0",SF_PORT:"443",SF_REUSE_PORT:"1",SF_PUBLIC_URL:Oe(s),SF_LAN_HOSTS:s.domain,SF_PEER_HOST:"127.0.0.1",SF_INGRESS_HOST:"127.0.0.1",SF_PREVIEW_HOSTS:s.previewsDomain?`*.${s.previewsDomain}`:"off",SF_TUNNEL_ENDPOINTS:`${a.address}:51820,${s.domain}:51820`,SF_HTTPS_MODE:"letsencrypt",SF_HTTPS_DOMAIN:s.domain,SF_HTTPS_EMAIL:s.acme.email,SF_HTTPS_CHALLENGE:s.acme.solver==="cloudflare"?"dns-01":"http-01",SF_HTTPS_PREVIEWS:s.previewsDomain?"1":"0",SF_ACME_DIRECTORY:s.acme.server,SF_S3_ENDPOINT:s.s3.endpoint,SF_S3_REGION:s.s3.region,SF_S3_BUCKET:s.files.bucket,SF_S3_PREFIX:s.files.prefix,SF_BACKUP_S3_PREFIX:s.backups.prefix,SF_HOSTING:"vm",SF_HOSTING_VM:s.vm.name??a.hostname,SF_HOSTING_HYPERVISOR:s.vm.hypervisor??"",SF_HOSTING_STATUS_DIR:"/run/superfactory-host"};if(s.backups.bucket)c.SF_BACKUP_S3_BUCKET=s.backups.bucket;if(s.owner)c.SF_OWNER_EMAIL=s.owner.email;if(s.standby)c.SF_STANDBY="1";if(s.harvester)c.SF_HARVESTER_NAMESPACE=s.harvester.namespace,c.SF_HARVESTER_IMAGE=s.harvester.image,c.SF_HARVESTER_NETWORK=s.harvester.network,c.SF_HARVESTER_STORAGE_CLASS=s.harvester.storageClass;return c}function ke(s,a){let c=s.postgres;return{PGDATA:"/var/lib/postgresql/data/pgdata",AWS_SHARED_CREDENTIALS_FILE:"/run/secrets/barman_s3",AWS_DEFAULT_REGION:s.s3.region,BARMAN_ENDPOINT:s.s3.endpoint,BARMAN_DESTINATION:Ze(c.bucket,c.path),BARMAN_SERVER:z(s,a)}}var fs=(s)=>go(s,{version:"1.1",lineWidth:0,aliasDuplicateObjects:!1});function tt(s,a,c){let u=(S)=>c.includes(S),f=Ie.filter((S)=>u(S.name)&&S.group!=="root"),p=[`${O}/postgres:/var/lib/postgresql/data`,`${_}/postgres:/etc/superfactory:ro`,`${we}:/run/postgresql`],h={network_mode:"host",read_only:!0,cap_drop:["ALL"],security_opt:["no-new-privileges:true"],tmpfs:["/tmp"],logging:{driver:"json-file",options:{"max-size":"20m","max-file":"5"}}},m={image:s.postgres.image??Ge,...h,user:`${ge}:${Ae}`,group_add:[String(q)],environment:ke(s,a),secrets:["barman_s3"].filter(u)},E=(S)=>({image:`\${SERVER_IMAGE}:\${${S.toUpperCase()}_TAG:-none}`,...h,tmpfs:["/tmp:size=4g"],user:`${We}:${We}`,group_add:[String(M)],restart:"unless-stopped",stop_grace_period:"75s",env_file:["server.env"],environment:{SF_INGRESS_PORT:String(te[S].ready),SF_PEER_PORT:String(te[S].peer),SF_HTTP_PORT:String(te[S].cloudflare),SF_HOSTING_COLOR:S,...Object.fromEntries(f.filter((b)=>b.group==="server"&&b.env).map((b)=>[b.env,ds(b)]))},secrets:f.filter((b)=>b.group==="server").map((b)=>b.target?{source:b.name,target:b.target}:b.name),volumes:[`${x}:/run/superfactory-host:ro`]});return fs({name:"superfactory",services:{postgres:{...m,restart:"unless-stopped",stop_grace_period:"90s",entrypoint:["/etc/superfactory/pg-run.sh"],volumes:p,healthcheck:{test:["CMD","pg_isready","-h","/run/postgresql","-U","postgres"],interval:"5s",timeout:"5s",retries:60}},"pg-backup":{...m,restart:"unless-stopped",entrypoint:["python3","/etc/superfactory/pg-backup.py"],environment:{...ke(s,a),BACKUP_AT:s.postgres.backupAt,RETENTION:cs(s.postgres.retention)},volumes:[`${O}/postgres:/var/lib/postgresql/data:ro`,`${_}/postgres:/etc/superfactory:ro`,`${we}:/run/postgresql`,`${x}/backup:/status`],depends_on:{postgres:{condition:"service_healthy"}}},"pg-restore":{...m,profiles:["restore"],entrypoint:["/etc/superfactory/pg-restore.sh"],environment:{...ke(s,a),...s.postgres.restore?{ORIGIN_ENDPOINT:s.postgres.restore.endpoint??s.s3.endpoint,ORIGIN_DESTINATION:Ze(s.postgres.restore.bucket??s.postgres.bucket,s.postgres.restore.path??s.postgres.path),ORIGIN_SERVER:s.postgres.restore.serverName}:{}},volumes:p},"server-blue":E("blue"),"server-green":E("green"),...U(s)?{registry:{image:s.registry.image??Me,...h,user:`${se}:${se}`,restart:"unless-stopped",entrypoint:["registry"],command:["serve","/etc/registry/config.yml"],volumes:[`${X}:/var/lib/registry`,`${re}:/etc/registry:ro`]}}:{}},secrets:Object.fromEntries(f.map((S)=>[S.name,{file:`${y}/${S.name}`}]))})}function st(s){return{SERVER_IMAGE:B(s),SERVER_REGISTRY:U(s)?"local":"remote",...U(s)?{REGISTRY_PORT:String(s.registry.port),REGISTRY_KEEP:String(s.registry.keep)}:{}}}function rt(s){return`# superfactory host (T-369): the VM's own registry, on loopback only.
4
+ version: 0.1
5
+ log:
6
+ level: info
7
+ fields:
8
+ service: registry
9
+ storage:
10
+ delete:
11
+ enabled: true
12
+ filesystem:
13
+ rootdirectory: /var/lib/registry
14
+ maintenance:
15
+ uploadpurging:
16
+ enabled: true
17
+ age: 24h
18
+ interval: 24h
19
+ dryrun: false
20
+ http:
21
+ addr: 127.0.0.1:${s.registry.port}
22
+ health:
23
+ storagedriver:
24
+ enabled: true
25
+ interval: 10s
26
+ threshold: 3
27
+ `}var Ce=(s)=>`${Object.entries(s).map(([a,c])=>`${a}=${c}`).join(`
28
+ `)}
29
+ `;function ot(){return`# superfactory host (T-367): Postgres in its container, on this VM's loopback only.
30
+ data_directory = '/var/lib/postgresql/data/pgdata'
31
+ hba_file = '/etc/superfactory/pg_hba.conf'
32
+ ident_file = '/etc/superfactory/pg_ident.conf'
33
+ listen_addresses = '127.0.0.1'
34
+ port = 5432
35
+ unix_socket_directories = '/run/postgresql'
36
+ ssl = off
37
+ max_connections = 100
38
+ shared_buffers = 256MB
39
+ effective_cache_size = 768MB
40
+ work_mem = 16MB
41
+ maintenance_work_mem = 128MB
42
+ random_page_cost = 1.1
43
+ log_min_duration_statement = 2000
44
+ logging_collector = off
45
+ log_destination = 'stderr'
46
+ wal_level = replica
47
+ # Recovering a CloudNativePG backup needs these at least as high as on its primary (CNPG's defaults:
48
+ # 32 workers, 10 WAL senders), or the replay stops at once ("insufficient parameter settings").
49
+ max_worker_processes = 32
50
+ max_wal_senders = 10
51
+ max_locks_per_transaction = 64
52
+ max_prepared_transactions = 0
53
+ archive_mode = on
54
+ archive_timeout = 5min
55
+ # Every WAL segment to the bucket as it closes (barman-cloud, keys from its credentials file).
56
+ archive_command = 'barman-cloud-wal-archive --cloud-provider aws-s3 --endpoint-url "$BARMAN_ENDPOINT" --gzip "$BARMAN_DESTINATION" "$BARMAN_SERVER" "%p"'
57
+ # A recovery's restore_command, while one runs (pg-restore writes it).
58
+ include_if_exists = '/var/lib/postgresql/data/pgdata/superfactory-recovery.conf'
59
+ `}var nt=`# superfactory host: the postgres role by its socket (the backup, the install), the rest by password.
60
+ local all postgres peer
61
+ host all all 127.0.0.1/32 scram-sha-256
62
+ `,at=`#!/bin/sh
63
+ set -eu
64
+ if [ ! -s "$PGDATA/PG_VERSION" ]; then
65
+ if [ -e /var/lib/postgresql/data/restoring ]; then
66
+ echo "pg-run: a restore didn't finish: run superfactory host again" >&2
67
+ exit 1
68
+ fi
69
+ mkdir -p "$PGDATA"
70
+ chmod 700 "$PGDATA"
71
+ initdb -D "$PGDATA" --username=postgres --auth-local=peer --auth-host=scram-sha-256 --encoding=UTF8 --locale=C >/dev/null
72
+ echo "pg-run: a new database folder"
73
+ fi
74
+ exec postgres -c config_file=/etc/superfactory/postgresql.conf
75
+ `,it=`#!/bin/sh
76
+ set -eu
77
+ if [ -s "$PGDATA/PG_VERSION" ]; then
78
+ echo "pg-restore: Postgres has data already: nothing restored"
79
+ exit 0
80
+ fi
81
+ [ -n "\${ORIGIN_SERVER:-}" ] || { echo "pg-restore: no postgres.restore in the config" >&2; exit 2; }
82
+ touch /var/lib/postgresql/data/restoring
83
+ rm -rf "$PGDATA"
84
+ mkdir -p "$PGDATA"
85
+ chmod 700 "$PGDATA"
86
+ echo "pg-restore: $ORIGIN_SERVER's latest base backup"
87
+ barman-cloud-restore --cloud-provider aws-s3 --endpoint-url "$ORIGIN_ENDPOINT" --profile origin "$ORIGIN_DESTINATION" "$ORIGIN_SERVER" latest "$PGDATA"
88
+ # What CloudNativePG kept in the folder is its own: ours decide (postgresql.conf above).
89
+ : > "$PGDATA/postgresql.auto.conf"
90
+ cat > "$PGDATA/superfactory-recovery.conf" <<EOF
91
+ restore_command = 'barman-cloud-wal-restore --cloud-provider aws-s3 --endpoint-url "$ORIGIN_ENDPOINT" --profile origin "$ORIGIN_DESTINATION" "$ORIGIN_SERVER" %f %p'
92
+ recovery_target_timeline = 'latest'
93
+ EOF
94
+ touch "$PGDATA/recovery.signal"
95
+ rm -f /var/lib/postgresql/data/restoring
96
+ echo "pg-restore: restored; its WAL replays when Postgres starts"
97
+ `,ct=`import datetime, json, os, subprocess, sys, time
98
+
99
+ common = ["--cloud-provider", "aws-s3", "--endpoint-url", os.environ["BARMAN_ENDPOINT"]]
100
+ where = [os.environ["BARMAN_DESTINATION"], os.environ["BARMAN_SERVER"]]
101
+ status_file = "/status/backup.json"
102
+
103
+
104
+ def run(args):
105
+ done = subprocess.run(args, capture_output=True, text=True)
106
+ return done.returncode, (done.stdout + done.stderr).strip()
107
+
108
+
109
+ def listed():
110
+ code, out = run(["barman-cloud-backup-list", *common, "--format", "json", *where])
111
+ if code != 0:
112
+ return None
113
+ try:
114
+ return json.loads(out).get("backups_list", [])
115
+ except ValueError:
116
+ return None
117
+
118
+
119
+ def write(status):
120
+ tmp = status_file + ".part"
121
+ with open(tmp, "w") as f:
122
+ json.dump(status, f)
123
+ os.replace(tmp, status_file)
124
+
125
+
126
+ def read():
127
+ try:
128
+ with open(status_file) as f:
129
+ return json.load(f)
130
+ except (OSError, ValueError):
131
+ return {}
132
+
133
+
134
+ def now():
135
+ return datetime.datetime.now(datetime.timezone.utc)
136
+
137
+
138
+ def iso(backup, key):
139
+ """A backup's time as ISO 8601 (UTC): barman gives a timestamp beside it, else the time as ctime."""
140
+ stamp = backup.get(key + "_timestamp")
141
+ try:
142
+ if stamp is not None:
143
+ return datetime.datetime.fromtimestamp(float(stamp), datetime.timezone.utc).isoformat()
144
+ text = backup.get(key)
145
+ if text:
146
+ parsed = datetime.datetime.strptime(" ".join(str(text).split()), "%a %b %d %H:%M:%S %Y")
147
+ return parsed.replace(tzinfo=datetime.timezone.utc).isoformat()
148
+ except (TypeError, ValueError):
149
+ pass
150
+ return None
151
+
152
+
153
+ def backup():
154
+ started = now().isoformat()
155
+ print("pg-backup: a base backup", flush=True)
156
+ code, out = run(["barman-cloud-backup", *common, "--gzip", "-h", "/run/postgresql", "-U", "postgres", *where])
157
+ status = read()
158
+ status.update({"lastStartedAt": started, "lastEndedAt": now().isoformat(), "lastResult": "done" if code == 0 else "failed"})
159
+ if code == 0:
160
+ status.pop("lastError", None)
161
+ status["lastDoneAt"] = status["lastEndedAt"]
162
+ code, out = run(["barman-cloud-backup-delete", *common, "--retention-policy", os.environ["RETENTION"], *where])
163
+ if code != 0:
164
+ print("pg-backup: deleting the old ones failed: " + out[-400:], flush=True)
165
+ else:
166
+ status["lastError"] = out[-400:]
167
+ print("pg-backup: failed: " + out[-400:], file=sys.stderr, flush=True)
168
+ backups = listed()
169
+ if backups is not None:
170
+ status["backups"] = [
171
+ {"id": b.get("backup_id"), "status": str(b.get("status", "")).lower(), "beginAt": iso(b, "begin_time"), "endAt": iso(b, "end_time"), "error": b.get("error")}
172
+ for b in backups[-30:]
173
+ ]
174
+ status["destination"] = "/".join(where)
175
+ status["retention"] = os.environ["RETENTION"]
176
+ status["at"] = os.environ["BACKUP_AT"]
177
+ write(status)
178
+
179
+
180
+ def next_run():
181
+ hour, minute = (int(x) for x in os.environ["BACKUP_AT"].split(":"))
182
+ at = now().replace(hour=hour, minute=minute, second=0, microsecond=0)
183
+ return at if at > now() else at + datetime.timedelta(days=1)
184
+
185
+
186
+ backups = listed()
187
+ if backups is not None and not any(b.get("status") == "DONE" for b in backups):
188
+ backup()
189
+ while True:
190
+ upcoming = next_run()
191
+ status = read()
192
+ status["nextAt"] = upcoming.isoformat()
193
+ write(status)
194
+ time.sleep(max(1, (upcoming - now()).total_seconds()))
195
+ backup()
196
+ `;function lt(){let s=(a)=>te[a].ready;return`#!/bin/sh
197
+ # superfactory-vm (superfactory host, T-367): the server's blue and green replicas on this VM.
198
+ # deploy <tag> the other color started on <tag>; once its /readyz answers, the live one stops (it
199
+ # hands its agents over first): the other is live. One that never gets ready is stopped,
200
+ # and the live one stays.
201
+ # rollback deploy the tag that was live before
202
+ # load <tag> (the VM's own registry) stdin: a line "superfactory-load 1 <its scan, JSON in base64>",
203
+ # then the image as docker save wrote it, at most ${ze/1073741824} GiB; its one tag must be
204
+ # <tag> of the server's repository. Loaded, pushed to the registry, deployed, then gc
205
+ # gc the registry's tags but the live, the previous and the newest REGISTRY_KEEP loaded deleted,
206
+ # its blobs collected, and Docker's copies of them removed
207
+ # prune Docker's copies of the server's image but the live tag and the one before (the rollback's)
208
+ # removed: each deploy leaves one, about a GB packed and several unpacked, on the root disk
209
+ # (T-524). A deploy that pulls or loads with less room than it needs prunes first, and stops
210
+ # before the pull when that wasn't enough, with the live color still live
211
+ # status the live color and tag, the one before, each container's state, and the room Docker's
212
+ # disk has against what a pull needs (JSON)
213
+ # check the health check (every minute): a live server whose /readyz fails 3 times in a row is
214
+ # restarted, unless a deploy holds the lock or the server is paused; what it saw goes to
215
+ # ${x}/host.json for the server's Hosting page
216
+ # pause (root only) both colors stopped on purpose, and kept so: the health check starts
217
+ # nothing and deploys are refused, until resume (superfactory host's own deploy resumes too)
218
+ # resume the pause ended: the live color started again
219
+ # Deploy, load, rollback, gc, prune, pause and resume take the lock first and read the state only then: one queued
220
+ # behind another sees the color that one left live. The env: AGAIN=1 (deploy) the same tag started again,
221
+ # blue to green; RESUME=1 (deploy) a pause ended first, as superfactory host's server step does.
222
+ set -eu
223
+ export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
224
+ DIR=${_}
225
+ STATE=${I}
226
+ mkdir -p "$STATE"
227
+ LOAD_MAX=${ze}
228
+ compose() { docker compose --project-directory "$DIR" -f "$DIR/compose.yaml" "$@"; }
229
+ ready_port() { if [ "$1" = blue ]; then echo ${s("blue")}; else echo ${s("green")}; fi; }
230
+ # The color's ready port is held by its own container's processes alone: whatever else answers there (a
231
+ # session's listener) is never the server's readiness.
232
+ holds_port() {
233
+ pids=$(ss -Hltnp "sport = :$(ready_port "$1")" 2>/dev/null | grep -o 'pid=[0-9]*' | cut -d= -f2 | sort -u)
234
+ [ -n "$pids" ] || return 1
235
+ own=$(docker top "superfactory-server-$1-1" -eo pid 2>/dev/null | awk 'NR > 1 { print $1 }')
236
+ for pid in $pids; do printf '%s\\n' "$own" | grep -qxF "$pid" || return 1; done
237
+ }
238
+ ready() { holds_port "$1" && curl -fsS -m 3 "http://127.0.0.1:$(ready_port "$1")/readyz" >/dev/null 2>&1; }
239
+ other() { if [ "$1" = blue ]; then echo green; else echo blue; fi; }
240
+ # Read only once the lock is held (locked), or by what changes nothing (status, check).
241
+ live=""
242
+ read_state() { live=$(cat "$STATE/live" 2>/dev/null || true); }
243
+ tag_of() { cat "$STATE/$1.tag" 2>/dev/null || true; }
244
+ # The compose project's .env: the image, and each color's tag.
245
+ write_env() {
246
+ { cat "$DIR/image.env"; printf 'BLUE_TAG=%s\\nGREEN_TAG=%s\\n' "$(tag_of blue)" "$(tag_of green)"; } > "$DIR/.env.part"
247
+ chmod 600 "$DIR/.env.part"
248
+ mv "$DIR/.env.part" "$DIR/.env"
249
+ }
250
+ setting() { sed -n "s/^$1=//p" "$DIR/image.env"; }
251
+ image() { setting SERVER_IMAGE; }
252
+ registry_kind() { r=$(setting SERVER_REGISTRY); printf %s "\${r:-remote}"; }
253
+ valid_tag() { printf '%s' "$1" | grep -Eqx '[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}' || { echo "not an image tag: $1" >&2; exit 2; }; }
254
+ running() { [ "$(docker inspect -f '{{.State.Running}}' "superfactory-server-$1-1" 2>/dev/null || true)" = true ]; }
255
+ # Room where root's Docker and containerd keep images (the root disk), in bytes: the least of theirs.
256
+ free_bytes() {
257
+ set -- /var/lib/docker /var/lib/containerd
258
+ for d; do shift; [ -d "$d" ] && set -- "$@" "$d"; done
259
+ [ $# -gt 0 ] || set -- /
260
+ df -Pk "$@" 2>/dev/null | awk 'NR > 1 && (min == "" || $4 < min) {min = $4} END {if (min != "") print min * 1024}'
261
+ }
262
+ # What a pull or load of the next image needs: the live image's size and a quarter more (its packed
263
+ # layers land before they unpack), plus 2 GiB; at least 4 GiB, and 10 GiB when the live one's is unknown.
264
+ need_bytes() {
265
+ live_size=$([ -n "$live" ] && docker image inspect -f '{{.Size}}' "$(image):$(tag_of "$live")" 2>/dev/null | tr -d '\\n' || true)
266
+ case "$live_size" in ''|*[!0-9]*|0) echo 10737418240; return ;; esac
267
+ need=$((live_size + live_size / 4 + 2147483648))
268
+ [ "$need" -ge 4294967296 ] || need=4294967296
269
+ echo "$need"
270
+ }
271
+ mib_of() { echo "$(($1 / 1048576)) MiB"; }
272
+ number() { case "$1" in ''|*[!0-9]*) printf null ;; *) printf %s "$1" ;; esac; }
273
+ # Before a pull or a load: room enough, pruned first if not; else stop before it, the live color live.
274
+ room_for() {
275
+ need=$(need_bytes)
276
+ free=$(free_bytes)
277
+ [ -n "$free" ] || return 0
278
+ [ "$free" -lt "$need" ] || return 0
279
+ echo "the root disk has $(mib_of "$free") free, $1 needs about $(mib_of "$need"): pruning old server images first" >&2
280
+ prune >&2
281
+ free=$(free_bytes)
282
+ [ "$free" -lt "$need" ] || return 0
283
+ echo "not enough room on the root disk for $1: $(mib_of "$free") free after pruning, about $(mib_of "$need") needed; \${live:-nothing} stays live. Free some there (docker system df) or grow the disk" >&2
284
+ exit 1
285
+ }
286
+ # Started again by Docker since this deploy started it: it ended once, so it won't get ready.
287
+ restarted() { [ "$(docker inspect -f '{{.RestartCount}}' "superfactory-server-$1-1" 2>/dev/null || echo 0)" -gt 0 ]; }
288
+
289
+ deploy() {
290
+ tag=$1
291
+ valid_tag "$tag"
292
+ next=blue
293
+ [ "$live" = blue ] && next=green
294
+ # AGAIN=1 (superfactory host, after its settings changed): the same tag started again, blue to green.
295
+ if [ -z "\${AGAIN:-}" ] && [ -n "$live" ] && [ "$(tag_of "$live")" = "$tag" ] && running "$live"; then
296
+ echo "live: $live $tag (already)"
297
+ return 0
298
+ fi
299
+ if ! docker image inspect "$(image):$tag" >/dev/null 2>&1; then
300
+ room_for "$(image):$tag"
301
+ docker pull -q "$(image):$tag" >/dev/null || { echo "couldn't pull $(image):$tag" >&2; exit 1; }
302
+ fi
303
+ printf '%s\\n' "$tag" > "$STATE/$next.tag"
304
+ write_env
305
+ if ! compose up -d --no-deps --force-recreate "server-$next" >/dev/null 2>"$STATE/up.log"; then
306
+ cat "$STATE/up.log" >&2
307
+ echo "$tag didn't start: $live stays live" >&2
308
+ exit 1
309
+ fi
310
+ end=$(($(date +%s) + 300))
311
+ # Ready counts only from a container that runs and never ended since this deploy started it.
312
+ until ready "$next" && running "$next" && ! restarted "$next"; do
313
+ if [ "$(date +%s)" -ge "$end" ] || ! running "$next" || restarted "$next"; then
314
+ compose logs --no-color --tail 30 "server-$next" >&2 || true
315
+ compose stop "server-$next" >/dev/null 2>&1 || true
316
+ echo "$tag didn't get ready: $live stays live" >&2
317
+ exit 1
318
+ fi
319
+ sleep 2
320
+ done
321
+ if [ -n "$live" ]; then tag_of "$live" > "$STATE/previous.tag"; fi
322
+ printf '%s\\n' "$next" > "$STATE/live"
323
+ if [ -n "$live" ] && [ "$live" != "$next" ]; then compose stop -t 75 "server-$live" >/dev/null 2>&1 || true; fi
324
+ live=$next
325
+ scan_status
326
+ echo "live: $next $tag"
327
+ }
328
+
329
+ # The Hosting page's scan: the live tag's, as its load brought it (none: copied in, or pulled from Harbor).
330
+ # Status files are written to a .part of this run's own (its pid) and moved in whole: the health check's
331
+ # timer and a deploy or a check by hand may write one at once.
332
+ scan_status() {
333
+ mkdir -p ${x}
334
+ if [ -n "$live" ] && [ -f "$STATE/scans/$(tag_of "$live").json" ]; then
335
+ cp "$STATE/scans/$(tag_of "$live").json" ${x}/scan.json.part.$$
336
+ chmod 644 ${x}/scan.json.part.$$
337
+ mv ${x}/scan.json.part.$$ ${x}/scan.json
338
+ else
339
+ rm -f ${x}/scan.json
340
+ fi
341
+ }
342
+
343
+ registry_url() { echo "http://127.0.0.1:$(setting REGISTRY_PORT)/v2/$(image | sed 's|^[^/]*/||')"; }
344
+ registry_up() {
345
+ compose up -d registry >/dev/null 2>"$STATE/up.log" || { cat "$STATE/up.log" >&2; echo "the registry didn't start" >&2; exit 1; }
346
+ end=$(($(date +%s) + 60))
347
+ until curl -fsS -m 3 "http://127.0.0.1:$(setting REGISTRY_PORT)/v2/" >/dev/null 2>&1; do
348
+ [ "$(date +%s)" -lt "$end" ] || { compose logs --no-color --tail 20 registry >&2 || true; echo "the registry doesn't answer" >&2; exit 1; }
349
+ sleep 1
350
+ done
351
+ }
352
+
353
+ load() {
354
+ tag=$1
355
+ valid_tag "$tag"
356
+ [ "$(registry_kind)" = local ] || { echo "this VM pulls $(image) from its registry: push there (load is for the VM's own)" >&2; exit 2; }
357
+ # The header line: read by sh a byte at a time, so the image after it stays on stdin.
358
+ IFS= read -r header || { echo "load: nothing came" >&2; exit 2; }
359
+ case "$header" in "superfactory-load 1 "*) ;; *) echo "load: not a superfactory-load stream" >&2; exit 2 ;; esac
360
+ scan=\${header#superfactory-load 1 }
361
+ if [ "\${#scan}" -gt 1048576 ] || ! printf '%s' "$scan" | grep -Eqx '[A-Za-z0-9+/]*={0,2}'; then
362
+ echo "load: its scan isn't base64" >&2; exit 2
363
+ fi
364
+ inbox=${O}/incoming
365
+ rm -rf "$inbox"
366
+ mkdir -m 700 "$inbox"
367
+ trap 'rm -rf "$inbox"' EXIT
368
+ printf '%s' "$scan" | base64 -d > "$inbox/scan.json" 2>/dev/null || { echo "load: its scan isn't base64" >&2; exit 2; }
369
+ python3 -c 'import json, sys; assert isinstance(json.load(open(sys.argv[1])), dict)' "$inbox/scan.json" 2>/dev/null || { echo "load: its scan isn't a JSON object" >&2; exit 2; }
370
+ head -c $((LOAD_MAX + 1)) > "$inbox/image.tar"
371
+ size=$(stat -c %s "$inbox/image.tar")
372
+ [ "$size" -le "$LOAD_MAX" ] || { echo "load: the image is over $((LOAD_MAX / 1048576)) MiB: refused" >&2; exit 2; }
373
+ [ "$size" -gt 0 ] || { echo "load: no image came after the header" >&2; exit 2; }
374
+ ref="$(image):$tag"
375
+ # Its tags, before anything is loaded: exactly the one asked for, never another image's name.
376
+ tags=$(tar -xOf "$inbox/image.tar" manifest.json 2>/dev/null | python3 -c 'import json, sys; print(" ".join(t for m in json.load(sys.stdin) for t in (m.get("RepoTags") or [])))' 2>/dev/null) || { echo "load: not a docker save stream (no manifest.json)" >&2; exit 2; }
377
+ [ "$tags" = "$ref" ] || { echo "load: the image is tagged \${tags:-nothing}, not $ref: refused" >&2; exit 2; }
378
+ room_for "$ref"
379
+ docker load -q -i "$inbox/image.tar" >"$inbox/load.log" 2>&1 || { tail -n 5 "$inbox/load.log" >&2; echo "load: docker load failed" >&2; exit 1; }
380
+ rm -f "$inbox/image.tar"
381
+ registry_up
382
+ docker push -q "$ref" >"$inbox/push.log" 2>&1 || { tail -n 5 "$inbox/push.log" >&2; echo "load: the push to the VM's registry failed" >&2; exit 1; }
383
+ mkdir -p "$STATE/scans"
384
+ mv "$inbox/scan.json" "$STATE/scans/$tag.json"
385
+ printf '%s\\n' "$tag" >> "$STATE/loaded"
386
+ echo "loaded: $ref ($((size / 1048576)) MiB), in the VM's registry"
387
+ deploy "$tag"
388
+ gc || echo "gc failed (the deploy stands): superfactory-vm gc again" >&2
389
+ }
390
+
391
+ # The tags the registry keeps: both colors', the previous one, and the newest REGISTRY_KEEP loaded.
392
+ kept() {
393
+ keep=$(setting REGISTRY_KEEP)
394
+ { tag_of blue; tag_of green; cat "$STATE/previous.tag" 2>/dev/null || true
395
+ [ -f "$STATE/loaded" ] && tac "$STATE/loaded" | awk '!seen[$0]++' | head -n "\${keep:-5}"; } | grep -v '^$' | sort -u
396
+ }
397
+
398
+ digest_of() {
399
+ curl -fsS -m 10 -I \\
400
+ -H 'Accept: application/vnd.oci.image.index.v1+json' -H 'Accept: application/vnd.oci.image.manifest.v1+json' \\
401
+ -H 'Accept: application/vnd.docker.distribution.manifest.list.v2+json' -H 'Accept: application/vnd.docker.distribution.manifest.v2+json' \\
402
+ "$(registry_url)/manifests/$1" 2>/dev/null | tr -d '\\r' | sed -n 's/^[Dd]ocker-[Cc]ontent-[Dd]igest: //p'
403
+ }
404
+
405
+ gc() {
406
+ [ "$(registry_kind)" = local ] || { echo "gc: the VM has no registry of its own"; return 0; }
407
+ registry_up
408
+ keep=$(kept)
409
+ # None yet: the registry answers 404 for a repository it never had.
410
+ list=$(curl -fsS -m 10 "$(registry_url)/tags/list" 2>/dev/null) || list='{}'
411
+ tags=$(printf '%s' "$list" | python3 -c 'import json, sys; print("\\n".join(json.load(sys.stdin).get("tags") or []))') || { echo "gc: the registry's tags can't be read" >&2; return 1; }
412
+ # A digest a kept tag has stays, whatever other tag has it too (deleting a manifest deletes its every tag).
413
+ kept_digests=$(for t in $keep; do printf '%s' "$tags" | grep -qxF "$t" && digest_of "$t"; done | sort -u)
414
+ removed=0
415
+ for t in $tags; do
416
+ printf '%s\\n' "$keep" | grep -qxF "$t" && continue
417
+ d=$(digest_of "$t")
418
+ if [ -n "$d" ] && ! printf '%s\\n' "$kept_digests" | grep -qxF "$d"; then
419
+ curl -fsS -m 30 -X DELETE "$(registry_url)/manifests/$d" >/dev/null 2>&1 && removed=$((removed + 1))
420
+ fi
421
+ docker image rm "$(image):$t" >/dev/null 2>&1 || true
422
+ rm -f "$STATE/scans/$t.json"
423
+ done
424
+ # Docker's own copies too: the live and the previous tag's alone (the registry keeps the rest to pull).
425
+ prune >/dev/null
426
+ if [ -f "$STATE/loaded" ]; then
427
+ grep -xF "$keep" "$STATE/loaded" > "$STATE/loaded.part" || true
428
+ mv "$STATE/loaded.part" "$STATE/loaded"
429
+ fi
430
+ if [ "$removed" -gt 0 ]; then
431
+ # Its blobs collected with nothing pushing: the registry stopped meanwhile (pulls wait for the lock too).
432
+ compose stop registry >/dev/null 2>&1 || true
433
+ compose run --rm -T --no-deps registry garbage-collect --delete-untagged /etc/registry/config.yml </dev/null >"$STATE/gc.log" 2>&1 || { tail -n 5 "$STATE/gc.log" >&2; echo "gc: garbage-collect failed" >&2; }
434
+ registry_up
435
+ fi
436
+ echo "gc: $removed removed; kept $(printf '%s' "$keep" | tr '\\n' ' ')"
437
+ }
438
+
439
+ # Docker's copies of the server's image but the live tag and the previous one, and what nothing names now.
440
+ # One a container uses (the stopped color's) stays: Docker refuses to remove it.
441
+ prune() {
442
+ prune_keep=$({ [ -n "$live" ] && tag_of "$live"; cat "$STATE/previous.tag" 2>/dev/null || true; } | grep -v '^$' | sort -u)
443
+ before=$(free_bytes)
444
+ pruned=0
445
+ for t in $(docker image ls --format '{{.Tag}}' "$(image)" 2>/dev/null); do
446
+ printf '%s\\n' "$prune_keep" | grep -qxF "$t" && continue
447
+ docker image rm "$(image):$t" >/dev/null 2>&1 && pruned=$((pruned + 1))
448
+ done
449
+ docker image prune -f >/dev/null 2>&1 || true
450
+ after=$(free_bytes)
451
+ freed=""
452
+ [ -n "$before" ] && [ -n "$after" ] && [ "$after" -gt "$before" ] && freed=", $(mib_of $((after - before))) freed"
453
+ echo "prune: $pruned old server images removed$freed; kept $(printf '%s' "$prune_keep" | tr '\\n' ' ')"
454
+ }
455
+
456
+ # One word: a container that isn't there is missing (docker inspect prints an empty line for it).
457
+ state_of() {
458
+ s=$(docker inspect -f '{{.State.Status}}' "superfactory-$1-1" 2>/dev/null | tr -d '
459
+ ') || true
460
+ printf %s "\${s:-missing}"
461
+ }
462
+
463
+ # Docker's restarts of a color's container since it was made (a deploy makes it again: 0).
464
+ restarts_of() {
465
+ n=$(docker inspect -f '{{.RestartCount}}' "superfactory-server-$1-1" 2>/dev/null | tr -d '\\n') || true
466
+ printf %s "\${n:-0}"
467
+ }
468
+
469
+ status() {
470
+ printf '{"live":"%s","tag":"%s","previous":"%s","image":"%s","registry":"%s","blue":{"tag":"%s","state":"%s","restarts":%s},"green":{"tag":"%s","state":"%s","restarts":%s},"postgres":"%s","pgBackup":"%s","registryState":"%s","disk":{"free":%s,"need":%s}}\\n' \\
471
+ "$live" "$( [ -n "$live" ] && tag_of "$live")" "$(cat "$STATE/previous.tag" 2>/dev/null || true)" "$(image)" "$(registry_kind)" \\
472
+ "$(tag_of blue)" "$(state_of server-blue)" "$(restarts_of blue)" \\
473
+ "$(tag_of green)" "$(state_of server-green)" "$(restarts_of green)" \\
474
+ "$(state_of postgres)" "$(state_of pg-backup)" "$(state_of registry)" "$(number "$(free_bytes)")" "$(need_bytes)"
475
+ }
476
+
477
+ check() {
478
+ mkdir -p ${x}
479
+ # Never waits: a deploy (or a restore) holding the lock is changing the colors, and a paused server was
480
+ # stopped on purpose. Either way nothing is started, and the failures start again from 0.
481
+ exec 9>"$STATE/lock"
482
+ skip=""
483
+ if ! flock -n 9; then skip="a deploy holds the lock"; elif [ -f "$STATE/paused" ]; then skip="paused"; fi
484
+ read_state
485
+ if [ -n "$skip" ]; then
486
+ echo 0 > "$STATE/failures"
487
+ elif [ -n "$live" ]; then
488
+ if ready "$live"; then
489
+ echo 0 > "$STATE/failures"
490
+ else
491
+ failures=$(($(cat "$STATE/failures" 2>/dev/null || echo 0) + 1))
492
+ echo "$failures" > "$STATE/failures"
493
+ if [ "$failures" -ge 3 ]; then
494
+ echo "superfactory-vm: $live hasn't answered /readyz 3 times: restarting it" >&2
495
+ compose up -d --no-deps "server-$live" >/dev/null 2>&1 || true
496
+ compose restart "server-$live" >/dev/null 2>&1 || true
497
+ echo 0 > "$STATE/failures"
498
+ date -u +%FT%TZ > "$STATE/restarted"
499
+ fi
500
+ fi
501
+ fi
502
+ disk() { df -P "$1" 2>/dev/null | awk 'NR == 2 {sub("%", "", $5); print $5}'; }
503
+ reboot=false
504
+ [ -f /var/run/reboot-required ] && reboot=true
505
+ { printf '{"checkedAt":"%s","status":' "$(date -u +%FT%TZ)"; status | tr -d '\\n'
506
+ printf ',"failures":%s,"restartedAt":"%s","disk":{"root":%s,"data":%s},"rebootRequired":%s}\\n' \\
507
+ "$(cat "$STATE/failures" 2>/dev/null || echo 0)" "$(cat "$STATE/restarted" 2>/dev/null || true)" \\
508
+ "$(disk /)" "$(disk ${O})" "$reboot"; } > ${x}/host.json.part.$$
509
+ chmod 644 ${x}/host.json.part.$$
510
+ mv ${x}/host.json.part.$$ ${x}/host.json
511
+ }
512
+
513
+ pause() {
514
+ date -u +%FT%TZ > "$STATE/paused"
515
+ compose stop -t 75 server-blue server-green >/dev/null 2>&1 || true
516
+ echo "paused: both colors stopped; the health check starts nothing and deploys are refused until superfactory-vm resume"
517
+ }
518
+
519
+ resume() {
520
+ rm -f "$STATE/paused"
521
+ [ -n "$live" ] || { echo "resumed: nothing was live"; return 0; }
522
+ write_env
523
+ compose up -d --no-deps "server-$live" >/dev/null 2>"$STATE/up.log" || { cat "$STATE/up.log" >&2; echo "$live didn't start" >&2; exit 1; }
524
+ end=$(($(date +%s) + 300))
525
+ until ready "$live"; do
526
+ [ "$(date +%s)" -lt "$end" ] || { compose logs --no-color --tail 30 "server-$live" >&2 || true; echo "$live didn't get ready" >&2; exit 1; }
527
+ sleep 2
528
+ done
529
+ echo "live: $live $(tag_of "$live") (resumed)"
530
+ }
531
+
532
+ # Paused: nothing starts the server, but superfactory host's own deploy (RESUME=1), which ends the pause.
533
+ not_paused() {
534
+ [ -f "$STATE/paused" ] || return 0
535
+ if [ -n "\${RESUME:-}" ]; then
536
+ rm -f "$STATE/paused"
537
+ echo "the pause is over"
538
+ return 0
539
+ fi
540
+ echo "the server is paused (since $(cat "$STATE/paused")): superfactory-vm resume first" >&2
541
+ exit 1
542
+ }
543
+
544
+ # One deploy, load, gc, prune, pause or resume at a time, and the state read only then.
545
+ locked() { exec 9>"$STATE/lock"; flock -w 1800 9 || { echo "another deploy holds the VM for 30 minutes" >&2; exit 1; }; read_state; }
546
+
547
+ case "\${1:-}" in
548
+ deploy) [ $# -eq 2 ] || { echo "usage: superfactory-vm deploy <tag>" >&2; exit 2; }; locked; not_paused; deploy "$2" ;;
549
+ load) [ $# -eq 2 ] || { echo "usage: superfactory-vm load <tag> < stream" >&2; exit 2; }; locked; not_paused; load "$2" ;;
550
+ rollback)
551
+ locked
552
+ not_paused
553
+ previous=$(cat "$STATE/previous.tag" 2>/dev/null || true)
554
+ [ -n "$previous" ] || { echo "nothing to roll back to" >&2; exit 1; }
555
+ deploy "$previous" ;;
556
+ gc) locked; gc ;;
557
+ prune) locked; prune ;;
558
+ pause) locked; pause ;;
559
+ resume) locked; resume ;;
560
+ status) read_state; status ;;
561
+ check) check ;;
562
+ env) write_env ;;
563
+ *) echo "usage: superfactory-vm deploy <tag> | load <tag> | rollback | gc | prune | status | check | pause | resume" >&2; exit 2 ;;
564
+ esac
565
+ `}var dt=`#!/bin/sh
566
+ set -euf
567
+ # Words only, never a pattern (set -f): what the key may run is these, and nothing else.
568
+ set -- \${SSH_ORIGINAL_COMMAND:-}
569
+ case "\${1:-}" in
570
+ deploy|load) [ $# -eq 2 ] && exec sudo -n /opt/superfactory/bin/superfactory-vm "$1" "$2" ;;
571
+ rollback|status|prune) [ $# -eq 1 ] && exec sudo -n /opt/superfactory/bin/superfactory-vm "$1" ;;
572
+ esac
573
+ echo "this key runs only: deploy <tag> | load <tag> | rollback | prune | status" >&2
574
+ exit 2
575
+ `,ut=`# superfactory host (T-367, T-369): the deployer runs superfactory-vm and nothing else.
576
+ deployer ALL=(root) NOPASSWD: /opt/superfactory/bin/superfactory-vm deploy *, /opt/superfactory/bin/superfactory-vm load *, /opt/superfactory/bin/superfactory-vm rollback, /opt/superfactory/bin/superfactory-vm prune, /opt/superfactory/bin/superfactory-vm status
577
+ `,pt=`[Unit]
578
+ Description=Superfactory: the server's health check (superfactory host)
579
+ After=docker.service
580
+
581
+ [Service]
582
+ Type=oneshot
583
+ ExecStart=/opt/superfactory/bin/superfactory-vm check
584
+ `,ft=`[Unit]
585
+ Description=Superfactory: the server's health check, every minute
586
+
587
+ [Timer]
588
+ OnBootSec=2min
589
+ OnUnitActiveSec=1min
590
+
591
+ [Install]
592
+ WantedBy=timers.target
593
+ `;function ne(s,a){let c=s.network;if(!c.sshFrom.length)return;let u=[...c.sshFrom,...c.deployFrom,...a.peer?[a.peer]:[]];return[...new Set(u.map((f)=>f.replace(/\/(32|128)$/,"")))]}function mt(s,a){let c=(m)=>({v4:m.filter((E)=>!E.includes(":")),v6:m.filter((E)=>E.includes(":"))}),u=(m,E,S)=>{if(!S)return[` ${m} dport ${E} accept`];let{v4:b,v6:v}=c(S);return[...b.length?[` ip saddr { ${b.join(", ")} } ${m} dport ${E} accept`]:[],...v.length?[` ip6 saddr { ${v.join(", ")} } ${m} dport ${E} accept`]:[]]},f=s.network,p=f.allowFrom.length?f.allowFrom:void 0,h=ne(s,a);return`#!/usr/sbin/nft -f
594
+ # superfactory host (T-367): what reaches this VM. Its own table, made again whole each time.
595
+ table inet superfactory
596
+ delete table inet superfactory
597
+ table inet superfactory {
598
+ chain input {
599
+ type filter hook input priority 0; policy drop;
600
+ iif lo accept
601
+ ct state established,related accept
602
+ ct state invalid drop
603
+ ip protocol icmp accept
604
+ meta l4proto ipv6-icmp accept
605
+ udp sport 67 udp dport 68 accept
606
+ ${[...u("tcp",443,p),...s.acme.solver==="http"?u("tcp",80,void 0):[],...u("udp",51820,f.tunnelAllowFrom),...u("tcp",22,h)].join(`
607
+ `)}
608
+ }
609
+ # The server's machine's users (T-389): never the registry, Postgres or the server's own loopback ports,
610
+ # whose callers are trusted to be root's (their uids are put in as the rules are).
611
+ chain output {
612
+ type filter hook output priority 0; policy accept;
613
+ meta skuid { ${xe} } ip daddr 127.0.0.0/8 tcp dport { ${_e(s).join(", ")} } reject with tcp reset
614
+ }
615
+ }
616
+ `}var xe="@MACHINE_UIDS@";function _e(s){let a=Object.values(te).flatMap((c)=>[c.ready,c.peer,c.cloudflare]);return["5432",...U(s)?[String(s.registry.port)]:[],`${Math.min(...a)}-${Math.max(...a)}`]}var ht=`[Unit]
617
+ Description=Superfactory: the VM's firewall (superfactory host)
618
+ Wants=network-pre.target
619
+ Before=network-pre.target
620
+
621
+ [Service]
622
+ Type=oneshot
623
+ RemainAfterExit=yes
624
+ ExecStart=/usr/sbin/nft -f /opt/superfactory/nftables.conf
625
+ ExecStop=/usr/sbin/nft delete table inet superfactory
626
+
627
+ [Install]
628
+ WantedBy=multi-user.target
629
+ `,$t=`d ${we} 0770 ${ge} ${q} -
630
+ `,gt=`net.ipv4.ip_unprivileged_port_start = 80
631
+ net.ipv4.ip_local_reserved_ports = 51820
632
+ # The server's blue and green share 443 (SO_REUSEPORT): the connections the color stopping had not yet
633
+ # accepted go to the other one instead of being reset (T-374).
634
+ net.ipv4.tcp_migrate_req = 1
635
+ `,k="sf",_t=`${O}/agent`,St="sf-session",j=Array.from({length:8},(s,a)=>`${St}-${a+1}`),yt="/var/lib/superfactory/session-homes",F="superfactory-agent.service",ae=`/etc/systemd/system/${F}.d/server-machine.conf`,ms=[y,"/run/docker.sock","/run/containerd","/var/lib/docker","/var/lib/containerd",`${O}/postgres`,X,I,"/home/deployer"],De="/etc/ssl/certs/ca-certificates.crt",Y="/usr/local/sbin/superfactory-root",Pe=`${Ji}=${Y}`,He=`${_}/bin/superfactory-root-run`,Fe=`${_}/bin/redact-secrets`,Et=`# superfactory host (T-389): the server's machine's agent runs its task sessions as their own users;
636
+ # (T-397) and a lead's machine_run root through the root entry, which runs only for the agent itself.
637
+ Defaults:${k} !pam_session
638
+ ${k} ALL=(${j.join(", ")}) NOPASSWD: ALL
639
+ ${k} ALL=(root) NOPASSWD: ${Y}
640
+ `,vt=`#!/bin/sh
641
+ # superfactory-root (superfactory host, T-397): a lead's machine_run root on the server's own machine.
642
+ set -eu
643
+ export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
644
+ [ "\${1:-}" = -c ] && [ $# -eq 2 ] || { echo "usage: superfactory-root -c <command line>" >&2; exit 2; }
645
+ # Called by the agent's main process, through sudo (and its monitor, with use_pty): nothing else.
646
+ agent=$(systemctl show -p MainPID --value ${F} 2>/dev/null || echo 0)
647
+ p=$PPID
648
+ ok=""
649
+ for _ in 1 2 3 4; do
650
+ [ "$p" -gt 1 ] 2>/dev/null || break
651
+ if [ "$p" = "$agent" ]; then ok=1; break; fi
652
+ [ "$(cat "/proc/$p/comm" 2>/dev/null)" = sudo ] || break
653
+ p=$(awk '{ print $4 }' "/proc/$p/stat")
654
+ done
655
+ if [ -z "$ok" ]; then
656
+ logger -t superfactory-root -p auth.warning "refused: not the agent (caller $PPID)"
657
+ echo "superfactory-root runs a lead's machine_run root, from the agent only" >&2
658
+ exit 126
659
+ fi
660
+ logger -t superfactory-root -p auth.notice -- "machine_run root: $2"
661
+ exec systemd-run --quiet --pipe --wait --collect --service-type=exec --unit="superfactory-root-$$" \\
662
+ --property=WorkingDirectory=/root --setenv=HOME=/root -- ${He} "$2"
663
+ `,Tt=`#!/bin/bash
664
+ # superfactory-root-run (superfactory host, T-397): the root command, what it prints without a secret's value.
665
+ set -uo pipefail
666
+ /bin/bash -l -c "$1" </dev/null 2>&1 | /usr/bin/python3 -I ${Fe}
667
+ exit "\${PIPESTATUS[0]}"
668
+ `,bt=`# redact-secrets (superfactory host, T-397): stdin with every secret file's value taken out.
669
+ import base64, json, os, re, sys
670
+ from urllib.parse import unquote
671
+
672
+ SECRETS = "${y}"
673
+ MIN_KNOWN, MIN_PART = 6, 16
674
+
675
+ def forms(value):
676
+ whole = value.strip()
677
+ bases = [whole]
678
+ def leaves(node):
679
+ if isinstance(node, str):
680
+ bases.append(node.strip())
681
+ elif isinstance(node, dict):
682
+ for v in node.values(): leaves(v)
683
+ elif isinstance(node, list):
684
+ for v in node: leaves(v)
685
+ if whole[:1] in "[{":
686
+ try: leaves(json.loads(whole))
687
+ except ValueError: pass
688
+ out = set()
689
+ for base in bases:
690
+ if len(base) < MIN_KNOWN: continue
691
+ out.add(base)
692
+ for line in base.splitlines():
693
+ line = line.strip()
694
+ if len(line) >= MIN_PART and not line.startswith("-----"): out.add(line)
695
+ url = re.match(r"^[a-z][a-z0-9+.-]*://[^\\s/@:]+:([^\\s@/]+)@", base, re.I)
696
+ if url:
697
+ out.add(url.group(1))
698
+ out.add(unquote(url.group(1)))
699
+ raw = base.encode()
700
+ b64 = base64.b64encode(raw).decode()
701
+ out.add(b64)
702
+ parts = [b64[at:at + 76] for at in range(0, len(b64), 76)]
703
+ # Inside a longer stream: 0, 1 or 2 bytes into a group, followed by anything.
704
+ for lead in (0, 1, 2):
705
+ padded = bytes(lead) + raw
706
+ parts.append(base64.b64encode(padded).decode()[4 if lead else 0:len(padded) // 3 * 4])
707
+ hexed = raw.hex()
708
+ out.add(hexed)
709
+ parts += [hexed[at:at + 60] for at in range(0, len(hexed), 60)]
710
+ out.update(p for p in parts if len(p) >= MIN_PART)
711
+ return {f for f in out if len(f) >= MIN_KNOWN}
712
+
713
+ known = set()
714
+ for root, _, names in os.walk(SECRETS):
715
+ for name in names:
716
+ path = os.path.join(root, name)
717
+ try:
718
+ if os.path.getsize(path) <= 1024 * 1024:
719
+ with open(path, encoding="utf-8", errors="replace") as f: known |= forms(f.read())
720
+ except OSError: pass
721
+ known = sorted(known, key=len, reverse=True)
722
+ out = sys.stdout
723
+ for raw in sys.stdin.buffer:
724
+ line = raw.decode("utf-8", "replace")
725
+ for value in known:
726
+ if value in line: line = line.replace(value, "[redacted]")
727
+ out.write(line)
728
+ out.flush()
729
+ `;function Rt(s){return`# superfactory host (T-389): the server's own machine.
730
+ ${At}[Service]
731
+ Environment=SUPERFACTORY_CLAUDE_ISOLATED=1
732
+ Environment=SUPERFACTORY_SESSION_USER=${St}
733
+ Environment=SUPERFACTORY_SESSION_ISOLATION=user
734
+ Environment=DOCKER_HOST=unix:///run/user/${s}/docker.sock
735
+ Environment=NODE_EXTRA_CA_CERTS=${De}
736
+ Environment=${ls}=${Yi}
737
+ Environment=${Pe}
738
+ ${wt}`}var kt=()=>`# superfactory host (T-389): the server's machine's user, its rootless Docker.
739
+ ${At}[Service]
740
+ ${wt}`;function Ue(s){return["tcp:80","tcp:443",..._e(s).map((a)=>`tcp:${a}`),"udp:51820"]}var wt=`InaccessiblePaths=${ms.map((s)=>`-${s}`).join(" ")}
741
+ MemoryHigh=40%
742
+ MemoryMax=50%
743
+ CPUWeight=20
744
+ IOWeight=20
745
+ OOMScoreAdjust=500
746
+ `,ie=`${_}/bin/superfactory-bind-guard`,G="superfactory-bind-guard.service",At=`[Unit]
747
+ Requires=${G}
748
+ After=${G}
749
+
750
+ `,Ot=`[Unit]
751
+ Description=Superfactory: the server's ports refused to its machine's users (superfactory host)
752
+ DefaultDependencies=no
753
+ After=local-fs.target
754
+ Before=sysinit.target shutdown.target
755
+ Conflicts=shutdown.target
756
+
757
+ [Service]
758
+ Type=oneshot
759
+ RemainAfterExit=yes
760
+ ExecStart=${ie}
761
+
762
+ [Install]
763
+ WantedBy=sysinit.target
764
+ `;function It(s){let a=Ue(s).map((c)=>{let[u,f]=c.split(":"),[p,h=p]=f.split("-").map(Number);return[u,p,h]});return`#!/usr/bin/python3 -I
765
+ # superfactory-bind-guard (superfactory host, T-541): the server's ports, refused to its machine's users by
766
+ # the kernel, from the cgroup tree's root (files.ts, BIND_GUARD).
767
+ RULES = ${JSON.stringify(a)}
768
+ USERS = ${JSON.stringify([k,...j])}
769
+ ${hs}`}var hs=`import ctypes, os, platform, pwd, socket, struct, sys
770
+
771
+ NAME = b"sf_bind_guard"
772
+ SYS_BPF = {"x86_64": 321, "aarch64": 280}[platform.machine()]
773
+ PROG_LOAD, PROG_ATTACH, PROG_DETACH, PROG_GET_FD_BY_ID, OBJ_GET_INFO_BY_FD, PROG_QUERY = 5, 8, 9, 13, 15, 16
774
+ CGROUP_SOCK_ADDR, INET4_BIND, INET6_BIND = 18, 8, 9
775
+ ALLOW_MULTI = 2
776
+ GET_CURRENT_UID_GID, GET_NETNS_COOKIE = 15, 122
777
+ SO_NETNS_COOKIE = 71
778
+ PROTO = {"tcp": socket.IPPROTO_TCP, "udp": socket.IPPROTO_UDP}
779
+ libc = ctypes.CDLL(None, use_errno=True)
780
+ libc.syscall.restype = ctypes.c_long
781
+
782
+
783
+ def fail(message):
784
+ sys.exit(f"superfactory-bind-guard: {message}")
785
+
786
+
787
+ def bpf(cmd, attr):
788
+ buf = ctypes.create_string_buffer(attr, 128)
789
+ fd = libc.syscall(SYS_BPF, cmd, buf, 128)
790
+ if fd < 0:
791
+ e = ctypes.get_errno()
792
+ raise OSError(e, os.strerror(e))
793
+ return fd, buf.raw
794
+
795
+
796
+ def ids():
797
+ """The machine's users' ids and their subordinate ones (/etc/subuid), as (first, last) ranges."""
798
+ try:
799
+ with open("/etc/subuid") as f:
800
+ subuids = [line.strip().split(":") for line in f]
801
+ except FileNotFoundError:
802
+ subuids = []
803
+ out = []
804
+ for name in USERS:
805
+ try:
806
+ uid = pwd.getpwnam(name).pw_uid
807
+ except KeyError:
808
+ fail(f"no user {name}")
809
+ if uid == 0:
810
+ fail(f"{name} is root")
811
+ out.append((uid, uid))
812
+ for entry in subuids:
813
+ if len(entry) == 3 and entry[0] in (name, str(uid)) and entry[1].isdigit() and entry[2].isdigit():
814
+ first, count = int(entry[1]), int(entry[2])
815
+ if first == 0:
816
+ fail(f"{name}'s subordinate ids hold root")
817
+ if count > 0:
818
+ out.append((first, min(first + count - 1, 2**32 - 2)))
819
+ return out
820
+
821
+
822
+ def program(cookie, uids):
823
+ """A server port, bound by one of them in the host's network namespace: refused (0), else allowed (1)."""
824
+ code, fix, labels = [], [], {}
825
+
826
+ def op(c, dst=0, src=0, off=0, imm=0):
827
+ code.append([c, dst, src, off, imm])
828
+
829
+ def jump(c, dst, imm, label, src=0):
830
+ fix.append((len(code), label))
831
+ op(c, dst, src, 0, imm)
832
+
833
+ op(0xBF, 6, 1) # r6 = ctx (struct bpf_sock_addr)
834
+ op(0x61, 7, 6, 24) # r7 = ctx->user_port, in network order
835
+ op(0xDC, 7, imm=16) # r7 = be16(r7): the port
836
+ op(0x61, 8, 6, 36) # r8 = ctx->protocol
837
+ for i, (proto, first, last) in enumerate(RULES):
838
+ jump(0x55, 8, PROTO[proto], f"r{i}") # another protocol: the next rule
839
+ jump(0xA5, 7, first, f"r{i}") # port < first
840
+ jump(0x25, 7, last, f"r{i}") # port > last
841
+ jump(0x05, 0, 0, "port")
842
+ labels[f"r{i}"] = len(code)
843
+ jump(0x05, 0, 0, "allow")
844
+ labels["port"] = len(code)
845
+ op(0x85, imm=GET_CURRENT_UID_GID)
846
+ op(0xBC, 0, 0) # w0 = w0: the uid
847
+ for i, (first, last) in enumerate(uids):
848
+ jump(0xA6, 0, first, f"u{i}") # uid < first (32 bits, unsigned)
849
+ jump(0x26, 0, last, f"u{i}") # uid > last
850
+ jump(0x05, 0, 0, "user")
851
+ labels[f"u{i}"] = len(code)
852
+ jump(0x05, 0, 0, "allow")
853
+ labels["user"] = len(code)
854
+ op(0xBF, 1, 6) # r1 = ctx
855
+ op(0x85, imm=GET_NETNS_COOKIE)
856
+ op(0x18, 1, imm=cookie & 0xFFFFFFFF) # r1 = the host's network namespace's cookie
857
+ op(0, imm=cookie >> 32)
858
+ jump(0x5D, 0, 0, "allow", src=1) # another namespace: its ports are its own
859
+ op(0xB7, 0, imm=0) # refused: EPERM
860
+ op(0x95)
861
+ labels["allow"] = len(code)
862
+ op(0xB7, 0, imm=1)
863
+ op(0x95)
864
+ for at, label in fix:
865
+ code[at][3] = labels[label] - at - 1
866
+ return b"".join(
867
+ struct.pack("<BBhi", c, (src << 4) | dst, off, imm - 2**32 if imm >= 2**31 else imm)
868
+ for c, dst, src, off, imm in code
869
+ )
870
+
871
+
872
+ def load(insns, attach_type):
873
+ log = ctypes.create_string_buffer(65536)
874
+ lic = ctypes.create_string_buffer(b"GPL")
875
+ ins = ctypes.create_string_buffer(insns)
876
+ attr = struct.pack("<IIQQIIQII16sII", CGROUP_SOCK_ADDR, len(insns) // 8, ctypes.addressof(ins),
877
+ ctypes.addressof(lic), 1, len(log), ctypes.addressof(log), 0, 0, NAME, 0, attach_type)
878
+ try:
879
+ return bpf(PROG_LOAD, attr)[0]
880
+ except OSError as e:
881
+ fail(f"the kernel refused its program: {e}\\n{log.value.decode(errors='replace')}")
882
+
883
+
884
+ def ours(cgroup, attach_type):
885
+ """The guard's programs attached there now, as fds."""
886
+ found = ctypes.create_string_buffer(4 * 64)
887
+ _, out = bpf(PROG_QUERY, struct.pack("<IIIIQI", cgroup, attach_type, 0, 0, ctypes.addressof(found), 64))
888
+ fds = []
889
+ for (prog,) in struct.iter_unpack("<I", found.raw[: 4 * struct.unpack_from("<I", out, 24)[0]]):
890
+ fd, _ = bpf(PROG_GET_FD_BY_ID, struct.pack("<III", prog, 0, 0))
891
+ info = ctypes.create_string_buffer(80)
892
+ bpf(OBJ_GET_INFO_BY_FD, struct.pack("<IIQ", fd, 80, ctypes.addressof(info)))
893
+ if info.raw[64:80].rstrip(b"\\0") == NAME:
894
+ fds.append(fd)
895
+ else:
896
+ os.close(fd)
897
+ return fds
898
+
899
+
900
+ def main():
901
+ with socket.socket() as s:
902
+ cookie = struct.unpack("<Q", s.getsockopt(socket.SOL_SOCKET, SO_NETNS_COOKIE, 8))[0]
903
+ insns = program(cookie, ids())
904
+ cgroup = os.open("/sys/fs/cgroup", os.O_RDONLY | os.O_DIRECTORY)
905
+ for attach_type in (INET4_BIND, INET6_BIND):
906
+ before = ours(cgroup, attach_type)
907
+ fd = load(insns, attach_type)
908
+ # The new program first, then the ones it replaces: never a moment without one.
909
+ bpf(PROG_ATTACH, struct.pack("<IIIII", cgroup, fd, attach_type, ALLOW_MULTI, 0))
910
+ for old in before:
911
+ bpf(PROG_DETACH, struct.pack("<III", cgroup, old, attach_type))
912
+ rules = ", ".join(f"{p}:{a}" if a == b else f"{p}:{a}-{b}" for p, a, b in RULES)
913
+ print(f"{rules} refused to {', '.join(USERS)} and their subordinate ids, on the host's network")
914
+
915
+
916
+ try:
917
+ main()
918
+ except OSError as e:
919
+ fail(str(e))
920
+ `,ce=`${_}/bin/superfactory-machine-tools`,Nt=Yi.replace(/\.timer$/,"");function Ct(){let s=lo.map((c)=>`command -v ${c.command} >/dev/null 2>&1 || missing="$missing ${(c.apt??[]).join(" ")}"`).join(`
921
+ `),a=Ki.map((c)=>c.npm).join(" ");return`#!/bin/sh
922
+ # superfactory host (T-396): the server's own machine's tools, as root, from the agent's own list. Run by
923
+ # ${Yi} hourly, and by superfactory host before the machine's agent joins.
924
+ set -eu
925
+ umask 022
926
+ export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
927
+ export DEBIAN_FRONTEND=noninteractive
928
+ say() { printf 'machine tools: %s\\n' "$*"; }
929
+ fail() { printf 'machine tools: %s\\n' "$*" >&2; exit 1; }
930
+ # One run at a time: the timer's and superfactory host's.
931
+ exec 9>/run/lock/${Nt}.lock
932
+ flock 9
933
+ case "$(uname -m)" in
934
+ x86_64) arch=x64 gh_arch=amd64 ;;
935
+ aarch64) arch=arm64 gh_arch=arm64 ;;
936
+ *) fail "no tools for $(uname -m)" ;;
937
+ esac
938
+ work=$(mktemp -d)
939
+ trap 'rm -rf "$work"' EXIT
940
+ get() { curl -fsSL --retry 3 --max-time 600 "$@"; }
941
+ # check <sha256> <file> <what>: the file is what its release says, or it fails.
942
+ check() { echo "$1 $2" | sha256sum -c --quiet - >/dev/null 2>&1 || fail "$3 doesn't match its release's checksum"; }
943
+
944
+ # What apt gives (unattended-upgrades keeps what's there patched).
945
+ missing=""
946
+ ${s}
947
+ if [ -n "$missing" ]; then
948
+ say "installing$missing"
949
+ apt-get -o DPkg::Lock::Timeout=600 update -q >/dev/null
950
+ # shellcheck disable=SC2086
951
+ apt-get -o DPkg::Lock::Timeout=600 install -y -q --no-install-recommends $missing >/dev/null
952
+ fi
953
+
954
+ # Claude Code first, above all (its agent can't update it): its native build from Anthropic's releases, a
955
+ # version folder each, \`claude\` switched to it in one rename.
956
+ claude=$(get ${Ht}/latest | tr -d '[:space:]')
957
+ printf %s "$claude" | grep -Eq '^[0-9]+\\.[0-9]+\\.[0-9]+$' || fail "Claude Code's releases didn't say which is the newest"
958
+ had=$(readlink ${un} 2>/dev/null | sed -n 's|^${us}/\\([0-9.]*\\)/bin/claude$|\\1|p')
959
+ if [ "$had" != "$claude" ]; then
960
+ platform=linux-$arch
961
+ sum=$(get "${Ht}/$claude/manifest.json" | jq -r --arg p "$platform" '.platforms[$p].checksum // empty')
962
+ [ -n "$sum" ] || fail "Claude Code $claude has no $platform build"
963
+ get "${Ht}/$claude/$platform/claude" -o "$work/claude"
964
+ check "$sum" "$work/claude" "Claude Code $claude"
965
+ staged=${us}/$claude/bin/claude
966
+ install -D -m 0755 "$work/claude" "$staged"
967
+ ran=$(HOME="$work" "$staged" --version 2>/dev/null | awk '{ print $1 }' || true)
968
+ [ "$ran" = "$claude" ] || { rm -rf "${us}/$claude"; fail "Claude Code $claude doesn't run"; }
969
+ ln -sfn "$staged" ${un}.superfactory-new
970
+ mv -fT ${un}.superfactory-new ${un}
971
+ for dir in ${us}/*/; do
972
+ version=$(basename "$dir")
973
+ [ "$version" = "$claude" ] || [ "$version" = "$had" ] || rm -rf "$dir"
974
+ done
975
+ say "Claude Code $claude (was \${had:-none})"
976
+ fi
977
+ # Node.js: ${pn}'s newest, from nodejs.org, into /usr/local.
978
+ base=https://nodejs.org/dist/${pn}
979
+ line=$(get "$base/SHASUMS256.txt" | grep -E " node-v[0-9.]+-linux-$arch\\.tar\\.xz$" | head -n 1 || true)
980
+ [ -n "$line" ] || fail "nodejs.org lists no Linux $arch build in ${pn}"
981
+ file=\${line##* }
982
+ node=$(printf %s "$file" | sed -E 's/^node-(v[0-9.]+)-.*/\\1/')
983
+ had=$(/usr/local/bin/node --version 2>/dev/null || true)
984
+ if [ "$had" != "$node" ]; then
985
+ get "$base/$file" -o "$work/$file"
986
+ check "\${line%% *}" "$work/$file" "$file"
987
+ top=\${file%.tar.xz}
988
+ tar --extract --xz --no-same-owner --file "$work/$file" --directory /usr/local --strip-components 1 \\
989
+ "$top/bin" "$top/include" "$top/lib" "$top/share"
990
+ say "Node.js $node (was \${had:-none})"
991
+ fi
992
+
993
+ # gh: GitHub's newest release (never apt's, too old), into /usr/local/bin.
994
+ gh=$(curl -fsSLI -o /dev/null -w '%{url_effective}' --max-time 60 ${zt}/latest | sed -n 's|.*/tag/v\\([0-9.]*\\)$|\\1|p')
995
+ [ -n "$gh" ] || fail "${zt}/latest didn't say which release is the newest"
996
+ had=$(/usr/local/bin/gh --version 2>/dev/null | sed -n 's/^gh version \\([0-9.]*\\).*/\\1/p')
997
+ if [ "$had" != "$gh" ]; then
998
+ top=gh_\${gh}_linux_$gh_arch
999
+ get "${zt}/download/v$gh/$top.tar.gz" -o "$work/$top.tar.gz"
1000
+ sum=$(get "${zt}/download/v$gh/gh_\${gh}_checksums.txt" | awk -v f="$top.tar.gz" '$2 == f { print $1 }')
1001
+ [ -n "$sum" ] || fail "gh $gh has no Linux $gh_arch build"
1002
+ check "$sum" "$work/$top.tar.gz" "$top.tar.gz"
1003
+ tar --extract --gzip --no-same-owner --file "$work/$top.tar.gz" --directory /usr/local --strip-components 1 "$top/bin/gh"
1004
+ say "gh $gh (was \${had:-none})"
1005
+ fi
1006
+ if dpkg -s gh >/dev/null 2>&1; then apt-get -o DPkg::Lock::Timeout=600 remove -y -q gh >/dev/null; fi
1007
+
1008
+ # The projects' toolchains npm installs: ${a}.
1009
+ for tool in ${a}; do
1010
+ want=$(npm view "$tool" version 2>/dev/null) || fail "npm didn't say $tool's newest version"
1011
+ had=$("$tool" --version 2>/dev/null || true)
1012
+ [ "$had" != "$want" ] || continue
1013
+ npm install -g --no-audit --no-fund "$tool@$want" >/dev/null 2>&1 || fail "npm couldn't install $tool $want"
1014
+ say "$tool $want (was \${had:-none})"
1015
+ done
1016
+
1017
+ say "current: Claude Code $claude, gh $gh, Node.js $node, $(for tool in ${a}; do printf '%s %s ' "$tool" "$("$tool" --version)"; done)"
1018
+ `}var xt=`[Unit]
1019
+ Description=Superfactory: the server's machine's tools, as root (superfactory host)
1020
+ Wants=network-online.target
1021
+ After=network-online.target
1022
+
1023
+ [Service]
1024
+ Type=oneshot
1025
+ ExecStart=${ce}
1026
+ TimeoutStartSec=30min
1027
+ Nice=10
1028
+ `,Dt=`[Unit]
1029
+ Description=Superfactory: the server's machine's tools kept current, hourly
1030
+
1031
+ [Timer]
1032
+ OnBootSec=10min
1033
+ OnUnitActiveSec=1h
1034
+ RandomizedDelaySec=5min
1035
+ Persistent=true
1036
+
1037
+ [Install]
1038
+ WantedBy=timers.target
1039
+ `,Z={service:`${Nt}.service`,timer:Yi};import{randomBytes as gs}from"crypto";var _s=`set -eu
1040
+ umask 077
1041
+ export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
1042
+ export DEBIAN_FRONTEND=noninteractive
1043
+ say() { printf 'host: %s\\n' "$*"; }
1044
+ fail() { printf 'host: %s\\n' "$*" >&2; exit 1; }
1045
+ compose() { docker compose --project-directory ${_} -f ${_}/compose.yaml "$@"; }
1046
+ # waitfor <seconds> <what> <command\u2026>: tries the command every 2 s until it works.
1047
+ waitfor() {
1048
+ secs=$1 what=$2
1049
+ shift 2
1050
+ end=$(($(date +%s) + secs))
1051
+ until "$@" >/dev/null 2>&1; do
1052
+ [ "$(date +%s)" -lt "$end" ] || fail "$what: not after $secs s"
1053
+ sleep 2
1054
+ done
1055
+ }
1056
+ # quiet <command\u2026>: its output only when it fails (Compose says much on its way).
1057
+ quiet() {
1058
+ log=$(mktemp)
1059
+ if "$@" >"$log" 2>&1; then rm -f "$log"; return 0; fi
1060
+ code=$?
1061
+ tail -n 20 "$log" >&2
1062
+ rm -f "$log"
1063
+ return "$code"
1064
+ }
1065
+ # A step's script is sh's stdin: whatever runs from it reads </dev/null, or it eats the rest of the script.
1066
+ # prefixed <command\u2026>: its lines as they come, each as host's, and its own exit status (sh has no pipefail).
1067
+ prefixed() {
1068
+ st=$(mktemp)
1069
+ # In an && list, a failure doesn't end the subshell (set -e): its status is kept.
1070
+ { "$@" 2>&1 && echo 0 > "$st" || echo $? > "$st"; } | sed -u 's/^/host: /'
1071
+ code=$(cat "$st")
1072
+ rm -f "$st"
1073
+ return "$code"
1074
+ }
1075
+ # put <file> <mode> <owner:group>: stdin into the file, replaced whole only when it changed; says so (0/1).
1076
+ put() {
1077
+ tmp="$1.part.$$"
1078
+ cat > "$tmp"
1079
+ chmod "$2" "$tmp"
1080
+ chown "$3" "$tmp"
1081
+ if [ -f "$1" ] && cmp -s "$tmp" "$1" && [ "$(stat -c '%a %u:%g' "$1")" = "$(stat -c '%a %u:%g' "$tmp")" ]; then
1082
+ rm -f "$tmp"
1083
+ return 1
1084
+ fi
1085
+ mv "$tmp" "$1"
1086
+ }
1087
+ `,P=(s)=>({text:`${_s}
1088
+ ${typeof s==="string"?s:s.text}`,__script:!0});function de(s,a,c=""){let u=`SF_HOST_${gs(9).toString("hex")}`;return`${s} <<'${u}'${c?` ${c}`:""}
1089
+ ${a.endsWith(`
1090
+ `)?a:`${a}
1091
+ `}${u}`}var V=(s,a,c,u,f="|| true")=>de(`put ${s} ${a} ${c}`,u,f),w=(s,a,c,u)=>V(s,a,c,u);class K extends Error{}async function H(s,a,c,u,f=900000){u(`\u2500\u2500 ${a}`);let p=await s.sh(c,{timeoutMs:f,onLine:u});if(!p.ok){if(p.timedOut)throw new K(`${a}: timed out on ${s.name}`);let h=`${p.stderr}`.trim().split(`
1092
+ `).slice(-8).join(`
1093
+ `);throw new K(`${a} failed on ${s.name}${h?`:
1094
+ ${h}`:""}`)}return p.stdout}async function Ut(s,a){let c=await H(s,"facts",P(`
1095
+ [ -r /etc/os-release ] && . /etc/os-release
1096
+ [ "\${ID:-}" = ubuntu ] || fail "superfactory host runs on Ubuntu (this is \${PRETTY_NAME:-unknown})"
1097
+ case "$(uname -m)" in x86_64|aarch64) ;; *) fail "the server's image is for x86_64 or aarch64" ;; esac
1098
+ mem=$(awk '/MemTotal/ {print int($2/1024/1024)}' /proc/meminfo)
1099
+ [ "$mem" -ge 3 ] || fail "the VM has $mem GiB of memory: give it 4 GiB or more"
1100
+ fact() { printf 'fact %s %s\\n' "$1" "$(printf %s "$2" | base64 -w0)"; }
1101
+ fact hostname "$(hostname -s | tr 'A-Z' 'a-z')"
1102
+ fact address "$(ip -4 route get 1.1.1.1 2>/dev/null | awk '{for (i = 1; i < NF; i++) if ($i == "src") print $(i + 1)}')"
1103
+ fact peer "\${SF_HOST_PEER:-}"
1104
+ [ -f ${_}/host.json ] && fact config "$(cat ${_}/host.json)"
1105
+ if [ -f ${I}/live ]; then
1106
+ live=$(cat ${I}/live)
1107
+ fact live "$live $(cat ${I}/$live.tag 2>/dev/null || true)"
1108
+ fi
1109
+ [ -s ${O}/postgres/pgdata/PG_VERSION ] && fact pgdata yes
1110
+ [ -f ${I}/server-name ] && fact servername "$(cat ${I}/server-name)"
1111
+ fact secrets "$(ls ${y} 2>/dev/null | tr '\\n' ' ')"
1112
+ `),(h)=>{if(!h.startsWith("fact "))a(h)}),u={};for(let h of c.split(`
1113
+ `)){let m=/^fact (\w+) (\S*)$/.exec(h.trim());if(m)u[m[1]]=Buffer.from(m[2],"base64").toString("utf8")}if(!u.hostname||!u.address)throw new K("facts: the VM's hostname or address is unknown");let[f,p]=(u.live??"").split(" ");return{hostname:u.hostname,address:u.address,...u.peer?{peer:u.peer}:{},...(f==="blue"||f==="green")&&p?{live:{color:f,tag:p}}:{},pgData:u.pgdata==="yes",...u.servername?{serverName:u.servername}:{},secrets:(u.secrets??"").split(" ").filter((h)=>h&&!h.includes(".")),config:u.config?JSON.parse(u.config):void 0}}function Ss(){return P(`
1114
+ missing=""
1115
+ # The server's machine (T-389) besides: access lists for its sessions' users, what its rootless Docker needs.
1116
+ for p in docker:docker.io nft:nftables unattended-upgrade:unattended-upgrades curl:curl openssl:openssl python3:python3 ip:iproute2 ssh-keygen:openssh-client setfacl:acl sudo:sudo newuidmap:uidmap rootlesskit:rootlesskit slirp4netns:slirp4netns; do
1117
+ command -v "\${p%%:*}" >/dev/null 2>&1 || missing="$missing \${p#*:}"
1118
+ done
1119
+ [ -e /usr/lib/systemd/user/dbus.socket ] || missing="$missing dbus-user-session"
1120
+ docker compose version >/dev/null 2>&1 || case "$missing" in *docker-compose-v2*) ;; *) missing="$missing docker-compose-v2" ;; esac
1121
+ if [ -n "$missing" ]; then
1122
+ say "installing$missing"
1123
+ apt-get -o DPkg::Lock::Timeout=300 update -q >/dev/null
1124
+ # shellcheck disable=SC2086
1125
+ apt-get -o DPkg::Lock::Timeout=300 install -y -q --no-install-recommends $missing >/dev/null
1126
+ fi
1127
+ systemctl enable --now docker >/dev/null 2>&1
1128
+ waitfor 60 "Docker" docker info
1129
+ # Security updates every day, by themselves (Docker's and Postgres's images go by their tags instead).
1130
+ ${w("/etc/apt/apt.conf.d/20auto-upgrades","644","root:root",`APT::Periodic::Update-Package-Lists "1";
1131
+ APT::Periodic::Unattended-Upgrade "1";
1132
+ `)}
1133
+ systemctl enable --now unattended-upgrades >/dev/null 2>&1 || true
1134
+ say "Docker $(docker version --format '{{.Server.Version}}'), $(docker compose version --short 2>/dev/null | sed 's/^/Compose /'), unattended-upgrades on"
1135
+ `)}function ys(s,a){if(!s.network.firewall)return P(`${Pt()}
1136
+ say "the firewall is left as it is (network.firewall false)"`);let c=`ssh from ${ne(s,a)?.join(", ")??"anywhere"}`;return P(`
1137
+ mkdir -p ${_}
1138
+ chmod 755 ${_}
1139
+ ${Pt()}
1140
+ uids=$(for u in ${[k,...j].join(" ")}; do id -u "$u"; done | paste -sd, - | sed 's/,/, /g')
1141
+ ${de(`sed "s/${xe}/$uids/"`,mt(s,a),`| put ${_}/nftables.conf 600 root:root || true`)}
1142
+ nft -c -f ${_}/nftables.conf || fail "the firewall's rules don't parse"
1143
+ ${w("/etc/systemd/system/superfactory-firewall.service","644","root:root",ht)}
1144
+ systemctl daemon-reload
1145
+ systemctl enable superfactory-firewall >/dev/null 2>&1
1146
+ nft -f ${_}/nftables.conf
1147
+ say "firewall: 443${s.acme.solver==="http"?", 80":""}, UDP 51820${s.network.tunnelAllowFrom?" from its list":""}, ${c}; nothing else"
1148
+ `)}function Pt(){let s=yt;return`install -d -m 755 ${O} /var/lib/superfactory ${s}
1149
+ getent passwd ${k} >/dev/null || useradd --user-group --create-home --home-dir ${_t} --shell /bin/bash ${k}
1150
+ for u in ${j.join(" ")}; do
1151
+ getent passwd "$u" >/dev/null || useradd --user-group --no-create-home --home-dir "${s}/$u" --shell /usr/sbin/nologin "$u"
1152
+ install -d -m 700 -o "$u" -g "$u" "${s}/$u"
1153
+ done
1154
+ for u in ${[k,...j].join(" ")}; do
1155
+ [ "$(id -G "$u" | wc -w)" -eq 1 ] || { usermod -G '' "$u"; say "$u: in no group but its own now"; }
1156
+ passwd -l "$u" >/dev/null 2>&1 || true
1157
+ done`}function Es(s,a){let c=`${ge}:${Ae}`;return P(`
1158
+ mkdir -p ${_}/bin ${_}/postgres ${y} ${I} ${x}/backup ${O}/postgres
1159
+ chmod 755 ${_} ${_}/bin ${_}/postgres ${O} ${x}
1160
+ chmod 711 ${y}
1161
+ chmod 700 ${I}
1162
+ chown ${c} ${O}/postgres ${x}/backup
1163
+ chmod 700 ${O}/postgres
1164
+ chmod 755 ${x}/backup
1165
+ ${w(`${_}/postgres/postgresql.conf`,"644","root:root",ot())}
1166
+ ${w(`${_}/postgres/pg_hba.conf`,"644","root:root",nt)}
1167
+ ${w(`${_}/postgres/pg_ident.conf`,"644","root:root","")}
1168
+ ${w(`${_}/postgres/pg-run.sh`,"755","root:root",at)}
1169
+ ${w(`${_}/postgres/pg-restore.sh`,"755","root:root",it)}
1170
+ ${w(`${_}/postgres/pg-backup.py`,"644","root:root",ct)}
1171
+ ${w(`${_}/bin/superfactory-vm`,"755","root:root",lt())}
1172
+ ${w(`${_}/bin/deployer-ssh`,"755","root:root",dt)}
1173
+ ${w("/etc/tmpfiles.d/superfactory.conf","644","root:root",$t)}
1174
+ systemd-tmpfiles --create /etc/tmpfiles.d/superfactory.conf
1175
+ ${w("/etc/sysctl.d/60-superfactory.conf","644","root:root",gt)}
1176
+ sysctl -q -p /etc/sysctl.d/60-superfactory.conf
1177
+ ${w("/etc/systemd/system/superfactory-check.service","644","root:root",pt)}
1178
+ ${w("/etc/systemd/system/superfactory-check.timer","644","root:root",ft)}
1179
+ systemctl daemon-reload
1180
+ systemctl enable --now superfactory-check.timer >/dev/null 2>&1
1181
+ # The config, kept: the next run starts from it. Nothing secret is in it.
1182
+ ${w(`${_}/host.json`,"644","root:root",`${JSON.stringify(s,null,2)}
1183
+ `)}
1184
+ ${w(`${_}/server.env`,"644","root:root",Ce(et(s,a)))}
1185
+ ${w(`${_}/image.env`,"644","root:root",Ce(st(s)))}
1186
+ ${U(s)?`mkdir -p ${X} ${re}
1187
+ chown ${se}:${se} ${X}
1188
+ chmod 700 ${X}
1189
+ chmod 755 ${re}
1190
+ ${w(`${re}/config.yml`,"644","root:root",rt(s))}`:""}
1191
+ say "files in ${_}, data in ${O}"
1192
+ # The data disk is the VM's to mount (cloud-init, fstab); without one the data stays on the root disk.
1193
+ mountpoint -q ${O} || say "warning: no disk is mounted at ${O}: Postgres's data is on the root disk"
1194
+ `)}var vs=["master_key","auth_secret","enroll_token","setup_token","pg_owner_password","pg_readonly_password","db_url","db_readonly_url"];function Ts(s,a,c){return[...new Set([...c.secrets??[],...Object.keys(Ne(s,a)),...vs,"deploy_ssh"])]}function bs(s,a,c){let u=Ne(s,a),f=(v)=>({pg:q,root:0,server:M})[Ie.find((N)=>N.name===v)?.group??"server"],p=(v)=>`root:${f(v)}`,h=(v)=>f(v)===q?`{ say "${v}: given"; touch ${I}/pg-secrets-changed; }`:`say "${v}: given"`,m=Object.entries(u).map(([v,N])=>V(`${y}/${v}`,"440",p(v),N,`&& ${h(v)} || true`)).join(`
1195
+ `),E=(v,N,R)=>{let T=N?Buffer.from(N).toString("base64"):"";return`
1196
+ if [ -n '${T}' ]; then
1197
+ printf %s '${T}' | base64 -d | put ${y}/${v} 440 ${p(v)} && say "${v}: the moved server's" || true
1198
+ elif [ ! -s ${y}/${v} ]; then
1199
+ ${R} | put ${y}/${v} 440 ${p(v)} || true
1200
+ say "${v}: made"
1201
+ fi`},S=a.SF_HOST_MASTER_KEY?Buffer.from(a.SF_HOST_MASTER_KEY).toString("base64"):"",b=(v,N)=>`printf 'postgresql://%s:%s@127.0.0.1:5432/${$e}' ${v} "$(cat ${y}/${N})"`;return P(`
1202
+ getent group ${M} >/dev/null || groupadd -g ${M} superfactory-server
1203
+ getent group ${q} >/dev/null || groupadd -g ${q} superfactory-pg
1204
+ if [ -n '${S}' ] && [ -s ${y}/master_key ] && [ "$(base64 -w0 < ${y}/master_key)" != '${S}' ]; then
1205
+ fail "the VM has another master key already: what it sealed would no longer open. To start over, remove ${y} and ${O} first"
1206
+ fi
1207
+ ${m}
1208
+ ${E("master_key",a.SF_HOST_MASTER_KEY,"openssl rand -base64 32 | tr -d '\\n'")}
1209
+ ${E("auth_secret",a.SF_HOST_AUTH_SECRET,"openssl rand -hex 32 | tr -d '\\n'")}
1210
+ ${E("enroll_token",a.SF_HOST_ENROLL_TOKEN,"openssl rand -hex 32 | tr -d '\\n'")}
1211
+ ${E("setup_token",void 0,"openssl rand -hex 24 | tr -d '\\n'")}
1212
+ ${E("pg_owner_password",void 0,"openssl rand -hex 32 | tr -d '\\n'")}
1213
+ ${E("pg_readonly_password",void 0,"openssl rand -hex 32 | tr -d '\\n'")}
1214
+ ${b("superfactory","pg_owner_password")} | put ${y}/db_url 440 root:${M} || true
1215
+ ${b(oe,"pg_readonly_password")} | put ${y}/db_readonly_url 440 root:${M} || true
1216
+ # The deployer's, until its step makes it: the compose file lists it.
1217
+ [ -e ${y}/deploy_ssh ] || printf '{}' | put ${y}/deploy_ssh 440 root:${M} || true
1218
+ ${w(`${_}/compose.yaml`,"644","root:root",tt(s,c,Ts(s,a,c)))}
1219
+ ${_}/bin/superfactory-vm env
1220
+ compose config --quiet || fail "the compose file doesn't check"
1221
+ `)}function Rs(s,a){let c=z(s,a),u=s.postgres.restore,f=`
1222
+ DO $$ BEGIN
1223
+ IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'superfactory') THEN CREATE ROLE superfactory LOGIN; END IF;
1224
+ IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '${oe}') THEN CREATE ROLE ${oe} LOGIN; END IF;
1225
+ END $$;
1226
+ SELECT 'CREATE DATABASE ${$e} OWNER superfactory' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '${$e}')\\gexec
1227
+ `;return P(`
1228
+ if [ ! -s ${O}/postgres/pgdata/PG_VERSION ]; then
1229
+ ${u?`say "Postgres: recovering from ${u.serverName}'s Barman backups (as long as the backup and its WAL take)"
1230
+ prefixed compose --profile restore run -T --rm --no-deps pg-restore </dev/null || fail "the recovery failed (above)"`:'say "Postgres: a new database"'}
1231
+ fi
1232
+ printf '%s\\n' '${c}' | put ${I}/server-name 600 root:root || true
1233
+ recreate=""
1234
+ [ -e ${I}/pg-secrets-changed ] && recreate=--force-recreate
1235
+ quiet compose up -d $recreate postgres
1236
+ end=$(($(date +%s) + 3600))
1237
+ # Ready once it takes writes: a recovery's Postgres answers (hot standby) while it still replays the WAL.
1238
+ in_recovery() { compose exec -T postgres psql -X -tA -h /run/postgresql -U postgres -d postgres -c 'select pg_is_in_recovery()' </dev/null 2>/dev/null || true; }
1239
+ until [ "$(docker inspect -f '{{.State.Health.Status}}' superfactory-postgres-1 2>/dev/null)" = healthy ] && [ "$(in_recovery)" = f ]; do
1240
+ [ "$(docker inspect -f '{{.State.Running}}' superfactory-postgres-1 2>/dev/null)" = true ] || { compose logs --no-color --tail 20 postgres >&2; fail "Postgres stopped"; }
1241
+ # Started again and again (an image for another platform, a setting it refuses): it won't get ready.
1242
+ [ "$(docker inspect -f '{{.RestartCount}}' superfactory-postgres-1 2>/dev/null || echo 0)" -lt 3 ] || { compose logs --no-color --tail 20 postgres >&2; fail "Postgres keeps stopping (its log is above): fix what it says, then run superfactory host again"; }
1243
+ [ "$(date +%s)" -lt "$end" ] || fail "Postgres isn't ready after an hour: docker logs superfactory-postgres-1"
1244
+ sleep 3
1245
+ done
1246
+ psql() { compose exec -T postgres psql -X -q -v ON_ERROR_STOP=1 -h /run/postgresql -U postgres -d postgres "$@"; }
1247
+ ${de("psql",f,">/dev/null")}
1248
+ # The passwords: from their files to psql's stdin, never on a command line, and never in Postgres's log:
1249
+ # this session logs no statement, not one that fails nor a slow one (its text holds the password).
1250
+ {
1251
+ printf "SET log_min_error_statement = panic;\\nSET log_statement = none;\\nSET log_min_duration_statement = -1;\\n"
1252
+ printf "ALTER ROLE superfactory LOGIN PASSWORD '%s';\\n" "$(cat ${y}/pg_owner_password)"
1253
+ printf "ALTER ROLE ${oe} LOGIN PASSWORD '%s';\\n" "$(cat ${y}/pg_readonly_password)"
1254
+ } | psql >/dev/null
1255
+ quiet compose up -d $recreate pg-backup
1256
+ rm -f ${I}/pg-secrets-changed
1257
+ say "Postgres ready, archiving to ${c}, a base backup daily at ${s.postgres.backupAt} UTC (${s.postgres.retention} kept)"
1258
+ `)}function ks(s,a){let c=s.network.deployFrom.length?[...new Set([...s.network.deployFrom,...[a.address,s.network.address].filter((p)=>!!p),"127.0.0.1","::1"])]:[],u=["restrict",`command="${_}/bin/deployer-ssh"`,...c.length?[`from="${c.join(",")}"`]:[]].join(","),f=s.network.address??a.address;return P(`
1259
+ id deployer >/dev/null 2>&1 || useradd --system --create-home --shell /bin/sh deployer
1260
+ passwd -l deployer >/dev/null 2>&1 || true
1261
+ ${w("/etc/sudoers.d/superfactory-deployer","440","root:root",ut)}
1262
+ visudo -cqf /etc/sudoers.d/superfactory-deployer || { rm -f /etc/sudoers.d/superfactory-deployer; fail "the deployer's sudoers doesn't check"; }
1263
+ [ -s ${y}/deploy_key ] || ssh-keygen -q -t ed25519 -N '' -C superfactory-deployer -f ${y}/deploy_key
1264
+ chmod 600 ${y}/deploy_key ${y}/deploy_key.pub
1265
+ mkdir -p /home/deployer/.ssh
1266
+ chmod 755 /home/deployer/.ssh
1267
+ printf '%s %s\\n' ${l`${u}`.text} "$(cat ${y}/deploy_key.pub)" | put /home/deployer/.ssh/authorized_keys 644 root:root || true
1268
+ host_key=$(cut -d' ' -f1,2 /etc/ssh/ssh_host_ed25519_key.pub)
1269
+ python3 - ${y}/deploy_key ${l`deployer@${f}`.text} ${l`${f}`.text} "$host_key" <<'PY' | put ${y}/deploy_ssh 440 root:${M} && say "the deployer's key is with the server" || say "the deployer's key is with the server (as before)"
1270
+ import json, sys
1271
+ key_file, target, address, host_key = sys.argv[1:5]
1272
+ print(json.dumps({"target": target, "knownHosts": address + " " + host_key, "key": open(key_file).read()}))
1273
+ PY
1274
+ say "deployer: deployer@${f}, ${c.length?`from ${c.join(", ")}`:"from anywhere the firewall lets ssh in"}, superfactory-vm deploy|rollback|status only"
1275
+ `)}function ws(s,a){return P(`
1276
+ exec 9>${Xe}
1277
+ flock -w 1800 9 || fail "a deploy has held the VM for 30 minutes: try again once it's done"
1278
+ date -u +%FT%TZ > ${Je}
1279
+ say "stopping the server for the restore (paused until it's deployed again)"
1280
+ compose stop -t 75 server-blue server-green >/dev/null 2>&1 || true
1281
+ say "restoring the server's backup ${a}"
1282
+ log=$(mktemp)
1283
+ if BLUE_TAG=${l`${s}`.text} compose run -T --rm --no-deps --entrypoint bun server-blue src/backup.ts restore ${l`${a}`.text} --replace --data /tmp/restore </dev/null >"$log" 2>&1; then
1284
+ tail -n 30 "$log" | sed 's/^/host: restore: /'
1285
+ rm -f "$log"
1286
+ else
1287
+ tail -n 30 "$log" | sed 's/^/host: restore: /' >&2
1288
+ rm -f "$log"
1289
+ fail "the restore failed (its log is above)"
1290
+ fi
1291
+ `)}function As(s,a){let c=Te(s),u=s.registry.port,f=B(s),p=s.image.from,h=p&&a===Gt(p)?`
1292
+ if curl -fsS -m 10 -o /dev/null -I -H 'Accept: application/vnd.oci.image.index.v1+json' -H 'Accept: application/vnd.oci.image.manifest.v1+json' -H 'Accept: application/vnd.docker.distribution.manifest.v2+json' -H 'Accept: application/vnd.docker.distribution.manifest.list.v2+json' http://127.0.0.1:${u}/v2/superfactory-server/manifests/${l`${a}`.text}; then
1293
+ say "the VM's registry has ${a} already"
1294
+ else
1295
+ say "copying ${p} into the VM's registry"
1296
+ docker image inspect ${l`${p}`.text} >/dev/null 2>&1 || quiet docker pull -q ${l`${p}`.text} </dev/null || fail "couldn't pull ${p}"
1297
+ docker tag ${l`${p}`.text} ${l`${f}:${a}`.text}
1298
+ quiet docker push -q ${l`${f}:${a}`.text} </dev/null || fail "couldn't push ${f}:${a} into the VM's registry"
1299
+ printf '%s\\n' ${l`${a}`.text} >> ${I}/loaded
1300
+ fi`:"";return P(`
1301
+ ${s.image.username&&c?`docker login ${l`${c}`.text} -u ${l`${s.image.username}`.text} --password-stdin < ${y}/registry_password >/dev/null 2>&1 || fail "${c} refused "${l`${s.image.username}`.text}
1302
+ say "logged in to ${c} as "${l`${s.image.username}`.text}`:""}
1303
+ ${U(s)?`quiet compose up -d registry </dev/null
1304
+ waitfor 60 "the VM's registry" curl -fsS -m 3 http://127.0.0.1:${u}/v2/
1305
+ say "the VM's registry: ${f}, on 127.0.0.1 only, the newest ${s.registry.keep} loaded kept besides the live and previous"${h}`:`say "images from ${f}${s.image.username?"":" (public)"}"`}
1306
+ `)}function Os(s){return P(`
1307
+ # What the server is started with now; a change (a secret, its settings) starts it again, blue to green.
1308
+ applied=$(cat ${_}/compose.yaml ${_}/server.env ${y}/* 2>/dev/null | sha256sum | cut -d' ' -f1)
1309
+ again=""
1310
+ [ "$(cat ${I}/applied 2>/dev/null || true)" = "$applied" ] || again=1
1311
+ export AGAIN=$again
1312
+ # A pause (a restore, superfactory-vm pause before a recovery) ends with this deploy.
1313
+ export RESUME=1
1314
+ prefixed ${_}/bin/superfactory-vm deploy ${l`${s}`.text} </dev/null || fail "the server didn't start (above)"
1315
+ printf '%s\\n' "$applied" > ${I}/applied
1316
+ `)}function Is(s){let a=`--resolve ${s.domain}:443:127.0.0.1 https://${s.domain}`;return P(`
1317
+ waitfor 300 "the server on 443" curl -fsSk ${a}/readyz
1318
+ # Its own certificate: Let's Encrypt's (or the ACME server's) once issued, the self-signed one until then.
1319
+ # Checked against the VM's CA store, never by its looks: whatever else could listen on 443 has no such one.
1320
+ end=$(($(date +%s) + 900))
1321
+ until curl -fsS -m 10 -o /dev/null ${a}/readyz 2>/dev/null; do
1322
+ if [ "$(date +%s)" -ge "$end" ]; then
1323
+ curl -fsSk ${a}/api/server/https 2>/dev/null | head -c 300 >&2 || true
1324
+ fail "the certificate for ${s.domain} isn't issued, or the VM's CA store doesn't trust its issuer, after 15 minutes: docker logs superfactory-server-$(cat ${I}/live)-1 | grep HTTPS"
1325
+ fi
1326
+ sleep 5
1327
+ done
1328
+ cert=$(echo | openssl s_client -connect 127.0.0.1:443 -servername ${s.domain} 2>/dev/null | openssl x509 -noout -issuer -enddate 2>/dev/null || true)
1329
+ say "certificate for ${s.domain}: $(printf '%s\\n' "$cert" | sed -n 's/^issuer=//p'), until $(printf '%s\\n' "$cert" | sed -n 's/^notAfter=//p')"
1330
+ say "the server answers on https://${s.domain}: $(curl -fsS ${a}/api/version)"
1331
+ live=$(cat ${I}/live)
1332
+ if docker logs superfactory-server-$live-1 2>&1 | grep -q 'No account yet'; then
1333
+ printf 'setup %s\\n' "$(cat ${y}/setup_token)"
1334
+ fi
1335
+ `)}function Ns(){let{service:s,timer:a}=Z;return P(`
1336
+ mkdir -p ${_}/bin
1337
+ ${w(ce,"755","root:root",Ct())}
1338
+ ${w(`/etc/systemd/system/${s}`,"644","root:root",xt)}
1339
+ ${w(`/etc/systemd/system/${a}`,"644","root:root",Dt)}
1340
+ systemctl daemon-reload
1341
+ prefixed ${ce} </dev/null || fail "the server's machine's tools didn't install (above): run superfactory host again"
1342
+ systemctl enable --now ${a} >/dev/null 2>&1
1343
+ say "the server's machine: its tools as root, kept current by ${a}"
1344
+ `)}function Cs(s,a){let c=`--resolve ${s.domain}:443:127.0.0.1 https://${s.domain}`,u=s.vm.name??a.hostname;return P(`
1345
+ home=$(getent passwd ${k} | cut -d: -f6)
1346
+ uid=$(id -u ${k})
1347
+ [ -n "$home" ] && [ "$uid" -gt 0 ] || fail "the server's machine's user ${k} isn't there"
1348
+ # T-397: the root entry for a lead's machine_run root, before the sudo rule that names it. Any of them
1349
+ # changed, the agent starts again (below): it keeps root to the entry from its start on.
1350
+ changed=""
1351
+ mkdir -p ${_}/bin
1352
+ ${V(Fe,"755","root:root",bt,"&& changed=1 || true")}
1353
+ ${V(He,"755","root:root",Tt,"&& changed=1 || true")}
1354
+ ${V(Y,"755","root:root",vt,"&& changed=1 || true")}
1355
+ ${V("/etc/sudoers.d/superfactory-agent","440","root:root",Et,"&& changed=1 || true")}
1356
+ visudo -cqf /etc/sudoers.d/superfactory-agent || { rm -f /etc/sudoers.d/superfactory-agent; fail "the agent's sudoers doesn't check"; }
1357
+ # T-541: the bind guard, before the drop-ins that require it: attached now (in place of the one there), and
1358
+ # at each boot by its unit.
1359
+ ${V(ie,"755","root:root",It(s))}
1360
+ ${V(`/etc/systemd/system/${G}`,"644","root:root",Ot)}
1361
+ systemctl daemon-reload
1362
+ systemctl enable -q ${G}
1363
+ guard=$(${ie} 2>&1) || fail "the bind guard didn't attach: $guard"
1364
+ systemctl is-active -q ${G} || systemctl start ${G} || fail "${G} didn't start: journalctl -u ${G}"
1365
+ say "the server's machine: $guard"
1366
+ # Readable by the agent, as systemd's own folders are (SF-467): it reads how its unit stops. Under umask 077
1367
+ # mkdir made them root's alone; one made so before is opened too.
1368
+ install -d -m 755 ${ae.replace(/\/[^/]+$/,"")} "/etc/systemd/system/user@$uid.service.d"
1369
+ ${de('sed "s/@UID@/$uid/"',Rt("@UID@"),`| put ${ae} 644 root:root && changed=1 || true`)}
1370
+ manager_changed=""
1371
+ ${de('put "/etc/systemd/system/user@$uid.service.d/server-machine.conf" 644 root:root',kt(),"&& manager_changed=1 || true")}
1372
+ systemctl daemon-reload
1373
+ # A unit's limits apply from its next start: its user's systemd (and its Docker) started again for them.
1374
+ if [ -n "$manager_changed" ] && systemctl is-active -q "user@$uid.service"; then systemctl restart "user@$uid.service"; fi
1375
+ getent hosts ${s.domain} >/dev/null || fail "${s.domain} doesn't resolve on the VM: its agent links to that name"
1376
+ work=$(mktemp -d)
1377
+ trap 'rm -rf "$work"' EXIT
1378
+ # Run as root below: only from the server's own certificate, as the ready step checked it (never -k).
1379
+ curl -fsS ${c}/join.sh -o "$work/join.sh" || fail "couldn't get join.sh from the server"
1380
+ # The agent trusts what the VM trusts, as its service does (its drop-in).
1381
+ export NODE_EXTRA_CA_CERTS=${De}
1382
+ # Joined already: to the server its agent says, the agent brought to this server's build. Read as its user:
1383
+ # root follows no link in that user's home.
1384
+ joined=$(runuser -u ${k} -- python3 - "$home/.superfactory/agent.json" <<'PY' 2>/dev/null || true
1385
+ import json, sys
1386
+ state = json.load(open(sys.argv[1]))
1387
+ if state.get("nodeKey") and state.get("serverUrl"):
1388
+ print(state["serverUrl"])
1389
+ PY
1390
+ )
1391
+ if [ -n "$joined" ]; then
1392
+ SUPERFACTORY_SERVER_URL=$joined prefixed sh "$work/join.sh" </dev/null || fail "the agent's update failed (above)"
1393
+ say "the server's machine: joined to $joined already, its agent at the server's build"
1394
+ else
1395
+ install -m 600 /dev/null "$work/token"
1396
+ cat ${y}/enroll_token >"$work/token"
1397
+ prefixed sh "$work/join.sh" --token-file "$work/token" --name ${l`${u}`.text} --server-machine </dev/null || fail "the server's machine didn't join (above)"
1398
+ say "the server's machine: ${u} joined as the server's own"
1399
+ fi
1400
+ rm -f "$home/.superfactory/enroll-token"
1401
+ if [ -n "$changed" ]; then systemctl restart ${F}; fi
1402
+ systemctl is-active -q ${F} || fail "its agent isn't running: journalctl -u ${F}"
1403
+ `)}function Ds(){return P(`
1404
+ user=${k}
1405
+ uid=$(id -u $user)
1406
+ home=$(getent passwd $user | cut -d: -f6)
1407
+ touch /etc/subuid /etc/subgid
1408
+ if ! grep -q "^$user:" /etc/subuid || ! grep -q "^$user:" /etc/subgid; then
1409
+ first=$(awk -F: 'BEGIN { m = 100000 } { if ($2 + $3 > m) m = $2 + $3 } END { print m }' /etc/subuid /etc/subgid)
1410
+ usermod --add-subuids "$first-$((first + 65535))" --add-subgids "$first-$((first + 65535))" "$user"
1411
+ # Its subordinate ids are its own too: the bind guard refuses them the server's ports from now on.
1412
+ guard=$(${ie} 2>&1) || fail "the bind guard didn't attach: $guard"
1413
+ fi
1414
+ version=$(dockerd --version | awk '{ sub(",", "", $3); print $3 }')
1415
+ if [ "$(cat /usr/local/lib/superfactory/rootless-docker/version 2>/dev/null)" != "$version" ]; then
1416
+ t=$(mktemp -d)
1417
+ curl -fsSL "https://download.docker.com/linux/static/stable/$(uname -m)/docker-rootless-extras-$version.tgz" |
1418
+ tar -xz -C "$t" docker-rootless-extras/dockerd-rootless.sh docker-rootless-extras/dockerd-rootless-setuptool.sh ||
1419
+ { rm -rf "$t"; fail "couldn't get Docker's rootless scripts for $version"; }
1420
+ install -d /usr/local/lib/superfactory/rootless-docker
1421
+ install -m 755 "$t"/docker-rootless-extras/*.sh /usr/local/lib/superfactory/rootless-docker/
1422
+ ln -sf "$(command -v docker)" /usr/local/lib/superfactory/rootless-docker/docker
1423
+ echo "$version" >/usr/local/lib/superfactory/rootless-docker/version
1424
+ rm -rf "$t"
1425
+ fi
1426
+ loginctl enable-linger $user 2>/dev/null || { mkdir -p /var/lib/systemd/linger && touch /var/lib/systemd/linger/$user; }
1427
+ systemctl start "user@$uid.service"
1428
+ as_user() {
1429
+ runuser -u $user -- env -i HOME="$home" USER=$user LOGNAME=$user XDG_RUNTIME_DIR="/run/user/$uid" DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$uid/bus" PATH="/usr/local/lib/superfactory/rootless-docker:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" "$@"
1430
+ }
1431
+ # Its log is root's own, never a file in that user's home.
1432
+ setup_log=$(mktemp)
1433
+ if ! as_user systemctl --user is-active -q docker.service; then
1434
+ as_user systemctl --user reset-failed docker.service >/dev/null 2>&1 || :
1435
+ as_user systemd-run --user --wait --pipe --quiet --setenv=PATH="/usr/local/lib/superfactory/rootless-docker:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" -- /usr/local/lib/superfactory/rootless-docker/dockerd-rootless-setuptool.sh install </dev/null >/dev/null 2>"$setup_log" ||
1436
+ fail "its rootless Docker didn't set up: $(tail -n 5 "$setup_log" | tr '\\n' ' ')"
1437
+ fi
1438
+ rm -f "$setup_log"
1439
+ waitfor 60 "its rootless Docker" as_user env DOCKER_CONFIG=/nonexistent docker --host "unix:///run/user/$uid/docker.sock" info
1440
+ say "the server's machine: its own Docker, rootless as $user (unix:///run/user/$uid/docker.sock)"
1441
+ `)}function Ps(s){let a=_e(s).flatMap(Ft).join(" "),c=Ue(s).flatMap((u)=>{let[f,p]=u.split(":");return Ft(p).map((h)=>`${f}:${h}`)}).join(" ");return P(`
1442
+ status() { if "$@" >/dev/null 2>&1 </dev/null; then echo 0; else echo $?; fi; }
1443
+ for u in ${[k,j[0]].join(" ")}; do
1444
+ as() { runuser -u "$u" -- "$@" </dev/null >/dev/null 2>&1; }
1445
+ for file in ${y}/master_key ${y}/enroll_token ${y}/deploy_key ${y}/db_url; do
1446
+ [ ! -e "$file" ] || ! as cat "$file" || fail "$u reads $file"
1447
+ done
1448
+ ! as ls ${y} || fail "$u lists ${y}"
1449
+ ! as curl -fsS -m 3 --unix-socket /run/docker.sock http://docker/_ping || fail "$u uses root's Docker"
1450
+ ! as test -w /run/containerd/containerd.sock || fail "$u writes containerd's socket"
1451
+ ${s.network.firewall?`for port in ${a}; do
1452
+ # curl's 7: nothing let it connect. Root connects where something listens; the user mustn't.
1453
+ [ "$(status curl -s -m 3 -o /dev/null "http://127.0.0.1:$port/")" != 7 ] || continue
1454
+ [ "$(status runuser -u "$u" -- curl -s -m 3 -o /dev/null "http://127.0.0.1:$port/")" = 7 ] || fail "$u reaches 127.0.0.1:$port"
1455
+ done`:""}
1456
+ done
1457
+ # The server's ports: the kernel refuses each bind there, as the agent and as a session, from the agent's
1458
+ # cgroup (where its sessions run). One bound, or refused only for being in use, is the server's to lose.
1459
+ cgroup=/sys/fs/cgroup$(systemctl show -p ControlGroup --value ${F})
1460
+ for u in ${[k,j[0]].join(" ")}; do
1461
+ open=$(sh -c 'echo $$ > "$1/cgroup.procs" && shift && exec runuser -u "$@"' sh "$cgroup" "$u" -- python3 -I - ${c} <<'PY' 2>&1
1462
+ ${Hs}PY
1463
+ ) || fail "couldn't check $u's binds from the agent's cgroup: $open"
1464
+ [ -z "$open" ] || fail "$u may bind the server's ports: $open"
1465
+ done
1466
+ for u in ${j[0]}; do ! sudo -l -U "$u" 2>/dev/null | grep -q NOPASSWD || fail "$u may sudo"; done
1467
+ # T-397: as root, the agent runs the root entry alone, and the entry runs for the agent alone.
1468
+ sudo -l -U ${k} | grep -E '\\((ALL|root)' | grep -vqE ' ${Y}$' && fail "${k} may run something as root besides ${Y}"
1469
+ runuser -u ${k} -- sudo -n ${Y} -c id </dev/null >/dev/null 2>&1 && fail "${Y} runs for another process than the agent"
1470
+ # The agent running now keeps root to the entry: what it starts but its own sudo gains no privilege.
1471
+ agent_pid=$(systemctl show -p MainPID --value ${F})
1472
+ tr '\\0' '\\n' <"/proc/$agent_pid/environ" | grep -qx "${Pe}" || fail "the agent running now doesn't keep root to ${Y}: systemctl restart ${F}"
1473
+ # What root runs and installs for it (T-396): none of it ${k}'s to change.
1474
+ for file in ${Fs().join(" ")}; do
1475
+ [ "$(stat -c %u "$file")" = 0 ] || fail "$file isn't root's"
1476
+ ! runuser -u ${k} -- test -w "$file" || fail "${k} may change $file"
1477
+ done
1478
+ systemctl is-enabled -q ${Z.timer} || fail "${Z.timer} isn't on"
1479
+ # SF-467: the agent reads its own unit and drop-ins (how it stops): root's alone, it refused every session.
1480
+ runuser -u ${k} -- cat /etc/systemd/system/${F} ${ae} </dev/null >/dev/null 2>&1 || fail "${k} can't read its unit or ${ae}: chmod 644 /etc/systemd/system/${F}; chmod 755 /etc/systemd/system/${F}.d"
1481
+ say "the server's machine: ${k} and its sessions' users read no secret, use neither root's Docker nor Postgres, and run nothing as root but a lead's machine_run root, through its agent; root keeps its tools"
1482
+ `)}var Ft=(s)=>{let[a,c=a]=s.split("-").map(Number);return Array.from({length:(c??a)-a+1},(u,f)=>a+f)},Hs=`import errno, socket, sys
1483
+ for rule in sys.argv[1:]:
1484
+ proto, port = rule.split(":")
1485
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM if proto == "udp" else socket.SOCK_STREAM)
1486
+ try:
1487
+ s.bind(("127.0.0.1", int(port)))
1488
+ except OSError as e:
1489
+ if e.errno == errno.EPERM:
1490
+ continue
1491
+ finally:
1492
+ s.close()
1493
+ print(rule)
1494
+ `,Fs=()=>[ce,`/etc/systemd/system/${Z.service}`,`/etc/systemd/system/${Z.timer}`,"/usr/local/bin","/usr/local/bin/claude",us],Gt=(s)=>s.slice(s.lastIndexOf(":")+1);function Us(s,a,c){if(a.live&&!c)return a.live.tag;if(s.image.from)return Gt(s.image.from);return s.image.tag??a.live?.tag}function Ls(s,a){let c=s.postgres.restore,u=z(s,a);if(c&&(c.bucket??s.postgres.bucket)===s.postgres.bucket&&(c.path??s.postgres.path)===s.postgres.path&&c.serverName===u){let f=a.pgData&&a.serverName?"the one Postgres's data was set up with":s.postgres.serverName?"postgres.serverName":"the default, from the VM's hostname";throw new K(`Postgres would archive to ${u} (${f}), the folder it recovers from (postgres.restore.serverName): set another postgres.serverName`)}}async function Mt(s,a,c,u,f){let{progress:p}=f;Ls(a,u);let h=Us(a,u,f.imageGiven);if(u.live&&h&&u.live.tag!==h)p(`host: the server goes from ${u.live.tag} to ${h}`);await H(s,"packages",Ss(),p),await H(s,"firewall",ys(a,u),p),await H(s,"files",Es(a,u),p),await H(s,"secrets",bs(a,c,u),p),await H(s,"images",As(a,h),p,1800000),await H(s,"postgres",Rs(a,u),p,3900000),await H(s,"deployer",ks(a,u),p);let m=Oe(a),E=z(a,u);if(!h)return p("host: the VM's registry has no server image yet: `bun run deploy` loads one (its VM target), or run this again with --image <a public image>"),{url:m,serverName:E};if(f.restoreBackup)await H(s,"restore",ws(h,f.restoreBackup),p,3900000);await H(s,"server",Os(h),p,1200000);let S;if(await H(s,"ready",Is(a),(b)=>{let v=/^setup (\S+)$/.exec(b);if(v)S=v[1];else p(b)},1200000),a.standby)p("host: the server's machine joins at the cutover's run (standing by)");else if(S)p("host: the server's machine joins at the next run of superfactory host, once the owner exists");else await H(s,"machine tools",Ns(),p,1800000),await H(s,"machine",Cs(a,u),p,1200000),await H(s,"machine docker",Ds(),p,900000).catch((b)=>p(`host: warning: no Docker of its own on the server's machine yet: ${b.message}`)),await H(s,"machine check",Ps(a),p);return{url:m,tag:h,serverName:E,...S?{setupLink:`${m}/setup#token=${S}`}:{}}}async function jt(s){let a=await s.sh(P(`
1495
+ printf 'master %s\\n' "$(base64 -w0 < ${y}/master_key)"
1496
+ printf 'auth %s\\n' "$(base64 -w0 < ${y}/auth_secret)"
1497
+ `)),c=(u)=>{let f=new RegExp(`^${u} (\\S+)$`,"m").exec(a.stdout);return f?Buffer.from(f[1],"base64").toString("utf8"):""};if(!a.ok||!c("master"))throw new K(`couldn't read the server's keys on ${s.name}`);return{masterKey:c("master"),authSecret:c("auth")}}function Yt(s,a){if(!s||!a)return;let c=[],u=Promise.resolve(),f=(m)=>fetch(s,{method:"POST",headers:{authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(m),signal:AbortSignal.timeout(15000)}).then(()=>{return},()=>{return}),p=()=>{if(!c.length)return u;let m=c;return c=[],u=u.then(()=>f({lines:m})),u},h=setInterval(p,2000);return{line(m){c.push(m)},async end(m){clearInterval(h),await p(),await f({end:m})}}}import{mkdtempSync as Gs,rmSync as Ms}from"fs";import{tmpdir as js}from"os";import{join as Bt}from"path";var Vt=(s)=>(a)=>s.reduce((c,u)=>c.split(u).join("[redacted]"),a);function Ys(s,a){let c="";return{take(u){if(!s)return;c+=u;let f=c.split(`
1498
+ `);c=f.pop()??"";for(let p of f)s(a(p))},end(){if(s&&c)s(a(c));c=""}}}async function Kt(s,a,c,u={}){let f=Ys(u.onLine,c),p=await g(s(u.timeoutMs??600000),{input:`${a.text}
1499
+ `,onStdout:(h)=>f.take(h),onStderr:(h)=>f.take(h)});return f.end(),{ok:p.exitCode===0,stdout:c(p.stdout),stderr:c(p.stderr),timedOut:p.timedOut}}function qt(s){let a=Vt(s),c=process.getuid?.()===0;return{name:"this machine",sh:(u,f)=>Kt((p)=>{let h=r(ru).flag("-s").timeoutMs(p).build();return c?h:r(A).flag("-n").wrap(h).timeoutMs(p).build()},u,a,f),close(){}}}function Wt(s,a){let c=/^(?:([a-z_][a-z0-9_.-]*)@)?([a-zA-Z0-9.-]+|\[[0-9a-fA-F:]+\])(?::(\d+))?$/.exec(s);if(!c)throw Error(`--ssh: ${s} is not user@host[:port]`);let[,u,f,p]=c,h=Vt(a),m=Gs(Bt(js(),"sf-host-ssh-")),E=Bt(m,"c"),S="SF_HOST_PEER=${SSH_CONNECTION%% *}",b=u==="root"?["env",S,"sh","-s"]:["sudo","-n","env",S,"sh","-s"],v=(N)=>{let R=r(au);if(process.env.SF_HOST_SSH_CONFIG)R=R.flag("-F",process.env.SF_HOST_SSH_CONFIG);if(R=R.flag("-T").flag("-o","BatchMode=yes").flag("-o","StrictHostKeyChecking=accept-new").flag("-o","ControlMaster=auto").flag("-o",`ControlPath=${E}`).flag("-o","ControlPersist=120").flag("-o","ServerAliveInterval=15"),p)R=R.flag("-p",p);R=R.endOptions().arg(u?`${u}@${f}`:f);for(let T of b)R=R.arg(T);return R.timeoutMs(N).build()};return{name:u?`${u}@${f}`:f,sh:(N,R)=>Kt(v,N,h,R),close(){Ms(m,{recursive:!0,force:!0})}}}var Ee="/var/lib/superfactory",W=`${Ee}/host-run.log`;function Js(s){Le(Ee,{recursive:!0,mode:493});let a=Ks(Ee);if(!a.isDirectory()||a.uid!==0||(a.mode&18)!==0)throw Error(`${Ee} isn't root's own folder: fix it, or run with --foreground`);let c=es(W,Se.O_WRONLY|Se.O_APPEND|Se.O_CREAT|Se.O_NOFOLLOW,384);try{Vs(c,384),Ws(c,s)}finally{Qt(c)}}function ts(s,a){if(s.yes||process.stdin.isTTY)return;let c=s.restoreBackup?`restores the backup ${s.restoreBackup} over the server's database`:!a?"installs the server for the first time":void 0;return c&&`superfactory host ${c}: with no terminal to ask at, give --yes to go ahead`}async function Zs(s,a){if(s.ssh||s.foreground||process.env.SF_HOST_DETACHED==="1")return;if(process.stdin.isTTY)return;if(process.platform!=="linux"||process.getuid?.()!==0)return;if(Re(a).length||s.secrets||s.report)return;if(!Xt("/run/systemd/system")||!Bun.which("systemd-run"))return;let c=ts(s,Xt(`${_}/host.json`));if(c)return console.error(c),2;let u=`superfactory-host-${Date.now()}`;Js(`\u2500\u2500 ${new Date().toISOString()} ${u}
1500
+ `);let f=Jt(W).size,h=(process.argv[1]??"").startsWith("/$bunfs/")?[process.execPath]:[process.execPath,process.argv[1]],m=r(gu).flag("--unit",u).flag("--collect").flag("--quiet").flag("--wait").flag("--service-type","exec").flag("--property",`StandardOutput=append:${W}`).flag("--property",`StandardError=append:${W}`).flag("--property",`WorkingDirectory=${process.cwd()}`).flag("--setenv","SF_HOST_DETACHED=1").endOptions();for(let T of[...h,...process.argv.slice(2)])m.arg(T);console.log(`Running as the unit ${u}, its log in ${W}: it carries on if this command ends (the agent's restart).`);let E=g(m.timeoutMs(10800000).build()),S=f,b=()=>{let T=Jt(W).size;if(T<=S)return;let D=es(W,"r"),L=Buffer.alloc(T-S);zs(D,L,0,L.length,S),Qt(D),S=T,process.stdout.write(L)},v=setInterval(b,500),{exitCode:N,stderr:R}=await E;if(clearInterval(v),b(),R.trim())console.error(R.trim());return N}var Q,C=(s)=>{console.log(s),Q?.line(s)};async function Ur(s){let a={...qe(),...s.secrets?Ke(ye(s.secrets)):{}};if(!s.ssh&&process.platform!=="linux")return console.error("superfactory host installs on an Ubuntu VM: run it there, or here with --ssh user@host"),2;let c=await Zs(s,a);if(c!==void 0)return c;Q=Yt(s.report,a.SF_HOST_REPORT_TOKEN);let u=Re(a),f=s.ssh?Wt(s.ssh,u):qt(u);try{C(`Superfactory host on ${f.name}`);let p=await Ut(f,C),h=p.config?he.safeParse(p.config):void 0,m;if(s.config)m=be(JSON.parse(qs(ye(s.config),"utf8")));else if(h?.success)m=h.data,C(`Its config is on the VM (${m.domain}): bringing it up to date.`);else if(process.stdin.isTTY)m=await sr();else throw Error("no config on the VM yet: give --config <file.json> (docs/operations/vm-host.md)");let E=!!s.config&&h?.success===!0&&Qs(h.data,m)===!1;if(s.image){let T=s.image.lastIndexOf(":");if(T<=s.image.lastIndexOf("/"))throw Error("--image: repository:tag");m=be({...m,image:U(m)?{...m.image,from:s.image}:{...m.image,repository:s.image.slice(0,T),tag:s.image.slice(T+1)}}),E=!0}if(!p.live)E=!0;let{required:S}=Ve(m),b=new Set(p.secrets??[]),v=S.filter((T)=>!a[T]&&!Object.entries(Qe).some(([D,L])=>L.includes(T)&&b.has(D)));for(let T of v){if(!process.stdin.isTTY)throw Error(`${T} isn't set (${ee[T]}): put it in the environment or --secrets`);let D=await Cp(`${ee[T]} (${T}, not shown): `);if(!D)throw Error(`${T} is needed`);a[T]=D,u.push(D)}if(!a.SF_HOST_VAPID_PUBLIC_KEY!==!a.SF_HOST_VAPID_PRIVATE_KEY)throw Error("give both SF_HOST_VAPID_PUBLIC_KEY and SF_HOST_VAPID_PRIVATE_KEY, or neither");if(u.sort((T,D)=>D.length-T.length),er(m,p),s.restoreBackup)C(` It restores the server's backup ${s.restoreBackup} from its backups first, replacing its database.
1501
+ `);let N=ts(s,h?.success===!0);if(N)throw Error(N);if(!s.yes&&process.stdin.isTTY&&!await tn("Install it?"))return 1;if(s.restoreBackup&&!/^(latest|[\w.:-]+\.sfbackup)$/.test(s.restoreBackup))throw Error("--restore-backup: latest, or a backup's name (<time>.pg.sfbackup)");let R=await Mt(f,m,a,p,{imageGiven:E,progress:C,restoreBackup:s.restoreBackup});if(C(""),!R.tag)return C(`Superfactory is installed on ${f.name}, waiting for its first image (${B(m)}).`),C(" `bun run deploy` loads one into the VM's registry, scanned first (the deployer's key: the server's DEPLOY_SSH_KEY_SECRET once it runs; read /opt/superfactory/secrets/deploy_ssh on the VM until then), or: superfactory host --image <a public image>."),await Q?.end({ok:!0,url:R.url}),0;if(C(`Superfactory runs on ${R.url} (${B(m)}:${R.tag}).`),C(` Postgres: WAL to S3 all the time, a base backup daily at ${m.postgres.backupAt} UTC, ${m.postgres.retention} kept (${R.serverName}).`),C(m.standby?" Standing by: no leader job, backup, Cloudflare tunnel or notification until the cutover runs this again with a config without standby.":` The server's own backups: every 6 hours (Settings \u203A Backups) to ${m.backups.bucket??m.files.bucket}/${[m.files.prefix,m.backups.prefix].filter(Boolean).join("/")}.`),C(" `bun run deploy` can deploy it: the deployer's ssh key is the server's DEPLOY_SSH_KEY_SECRET (superfactory-vm deploy, blue or green)."),s.saveKeys){let T=await jt(f),D=ye(s.saveKeys);Le(D,{recursive:!0,mode:448});for(let[L,ss]of[["master-key",T.masterKey],["auth-secret",T.authSecret]])Zt(ue(D,L),`${ss}
1502
+ `,{mode:384}),Bs(ue(D,L),384);C(` Its master key and auth secret are in ${D}: keep them off the VM (no backup opens without the key).`)}else C(" Keep its master key off the VM: superfactory host --save-keys <dir> (no backup opens without it).");if(await Q?.end({ok:!0,url:R.url,setupLink:R.setupLink}),R.setupLink)if(Q)C(`
1503
+ Create the owner with the setup link the server that made this VM shows.`);else if(process.stdout.isTTY)C(`
1504
+ Create the owner: ${R.setupLink}`);else{let T=ue(s.saveKeys?ye(s.saveKeys):ue(Xs(),".superfactory"),"setup-link");Le(ue(T,".."),{recursive:!0,mode:448}),Zt(T,`${R.setupLink}
1505
+ `,{mode:384}),C(`
1506
+ Create the owner with the setup link in ${T} (it works once).`)}return 0}catch(p){if(await Q?.end({ok:!1,error:p.message}),p instanceof K)return console.error(`superfactory host: ${p.message}`),console.error("Run it again once that's fixed: it picks up where it stopped."),1;throw p}finally{f.close()}}var Qs=(s,a)=>s.image.repository===a.image.repository&&s.image.tag===a.image.tag&&s.image.from===a.image.from;function er(s,a){let c=s.postgres.restore,u=s.network;C(["",` Server https://${s.domain} (blue and green, in Docker)${s.previewsDomain?`, previews *.${s.previewsDomain}`:""}`,` VM ${a.hostname} (${a.address})`,` Certificate ${s.acme.solver==="cloudflare"?"DNS-01 (Cloudflare)":"HTTP-01"}, ${s.acme.server}`,` Postgres s3://${s.postgres.bucket}/${s.postgres.path?`${s.postgres.path}/`:""}${z(s,a)}${c&&!a.pgData?`, recovered from ${c.serverName}`:""}`,` Files s3://${s.files.bucket}/${s.files.prefix}`,` Image ${tr(s,a)}`,` Deploys from ${u.deployFrom.join(", ")||"anywhere ssh may come from"} (the deployer's key)`,` ssh from ${ne(s,a)?.join(", ")??"anywhere"}`,""].join(`
1507
+ `))}function tr(s,a){if(!U(s))return`${s.image.repository}:${s.image.tag}, pulled${s.image.username?` as ${s.image.username}`:""}`;let c=a.live?`${a.live.tag} live`:s.image.from?`${s.image.from} copied in`:s.image.tag?s.image.tag:"none yet: the first deploy loads one";return`the VM's own registry, ${B(s)} (${c}); deploys load into it, scanned`}async function sr(){for(;;){let s=await rr(),a=he.safeParse(s);if(!a.success){C(`That doesn't work: ${a.error.issues.map((u)=>`${u.path.join(".")}: ${u.message}`).join("; ")}`);continue}let c=ve(a.data);if(!c.length)return a.data;C(`That doesn't work: ${c.join("; ")}`)}}async function rr(){let s=(D)=>D.split(/[\s,]+/).map((L)=>L.trim()).filter(Boolean),a=await le("The server's address (a DNS name pointing at this VM, e.g. superfactory.example.com): "),c=await Lt("How should Let's Encrypt check the name?",[{key:"cloudflare",label:"DNS-01 through Cloudflare (a private address, or previews)"},{key:"http",label:"HTTP-01 (port 80 reachable from the internet)"}]),u=c==="cloudflare"?await le("The previews' domain (*.<it>; empty: no previews), e.g. sf-pv.example.com: "):"",f=await le("The email Let's Encrypt writes to about the certificate: "),p=await le("The S3 endpoint for backups and files (https://\u2026): "),h=await le("Its region [us-east-1]: ")||"us-east-1",m=await le("The bucket for the server's files: "),E=await le("The bucket for Postgres's backups (WAL and base backups): "),S=await le("The server's image repository, a registry of yours like Harbor (empty: the VM's own registry, which deploys load into): "),b=S?await le(`Its tag [${_r.version}]: `)||_r.version:"",v=S?"":await le(`A public image to start from [ghcr.io/bringes/superfactory-server:${_r.version}] ("none": the first deploy loads one): `)||`ghcr.io/bringes/superfactory-server:${_r.version}`,N=S?await le("The registry user that pulls it (empty: a public image): "):"",R=s(await le("Addresses that deploy it by ssh (the Superfactory project's VM; comma-separated; empty: any): ")),T=s(await le("Addresses allowed on HTTPS (comma-separated; empty: everyone): "));return{domain:a,...u?{previewsDomain:u}:{},acme:{email:f,solver:c},s3:{endpoint:p,region:h},files:{bucket:m},postgres:{bucket:E},image:S?{repository:S,tag:b,...N?{username:N}:{}}:v==="none"?{}:{from:v},network:{allowFrom:T,deployFrom:R}}}export{Ur as host};