@kabmo-labs/kabmo 0.33.0 → 0.34.0

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 (211) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +785 -624
  3. package/dist/client/static/js/{CsvGrid-fncjbg6j.js → CsvGrid-vze4m5ag.js} +1 -1
  4. package/dist/client/static/js/{DocxView-c9v2vr3r.js → DocxView-jbf21gmh.js} +5 -5
  5. package/dist/client/static/js/{DrawioView-vxjksm12.js → DrawioView-b52qybx5.js} +2 -2
  6. package/dist/client/static/js/{ImageView-a3g5k226.js → ImageView-mdgzj8px.js} +1 -1
  7. package/dist/client/static/js/{LayoutWrapper-hnjfwsjh.js → LayoutWrapper-3c49dvtt.js} +2 -2
  8. package/dist/client/static/js/Modal-sqp864vd.js +38 -0
  9. package/dist/client/static/js/{PdfView-ksaes53y.js → PdfView-g06rxqb1.js} +1 -1
  10. package/dist/client/static/js/{SessionsView-30vcr95v.js → SessionsView-521adxyr.js} +1 -1
  11. package/dist/client/static/js/{SheetView-vc484scg.js → SheetView-h8xmsz7q.js} +22 -22
  12. package/dist/client/static/js/{SvgPreview-tph89jet.js → SvgPreview-1j4jvcvz.js} +1 -1
  13. package/dist/client/static/js/{abnfDiagram-O67JEVCF-xbar278c.js → abnfDiagram-O67JEVCF-pasxh4b6.js} +1 -1
  14. package/dist/client/static/js/architecture-7GRP2DOG-fc9kmq1w.js +1 -0
  15. package/dist/client/static/js/{architectureDiagram-NJMV4G6O-s171n2z6.js → architectureDiagram-NJMV4G6O-ms14g0bm.js} +4 -4
  16. package/dist/client/static/js/{blockDiagram-BEXU5L5S-gzx6rv9n.js → blockDiagram-BEXU5L5S-ycn78fcq.js} +4 -4
  17. package/dist/client/static/js/{c4Diagram-YGBWAQC7-7f00skch.js → c4Diagram-YGBWAQC7-vn2gpjfm.js} +5 -5
  18. package/dist/client/static/js/{classDiagram-v2-NBCMYWYE-j79v95nc.js → classDiagram-v2-NBCMYWYE-fyrm1pr5.js} +4 -4
  19. package/dist/client/static/js/{cose-bilkent-JH36ORCC-5fkn7ee5.js → cose-bilkent-JH36ORCC-ea5nwvgq.js} +1 -1
  20. package/dist/client/static/js/cynefin-OW5HDTMX-a4t8992q.js +1 -0
  21. package/dist/client/static/js/{cynefinDiagram-VND7K2PF-cfs1yvrd.js → cynefinDiagram-VND7K2PF-j6bsjpre.js} +1 -1
  22. package/dist/client/static/js/{dagre-6A5THRUB-44bgc48p.js → dagre-6A5THRUB-4smdkwv8.js} +2 -2
  23. package/dist/client/static/js/{diagram-22UHCM2B-a4g4x83k.js → diagram-22UHCM2B-9sm4kqwc.js} +11 -11
  24. package/dist/client/static/js/{diagram-3UASUU5V-gm4rg5na.js → diagram-3UASUU5V-2h3qxaed.js} +1 -1
  25. package/dist/client/static/js/{diagram-ATOU4E4O-a95y41vk.js → diagram-ATOU4E4O-1981bc94.js} +3 -3
  26. package/dist/client/static/js/{diagram-CDSNMT55-t3j93mmc.js → diagram-CDSNMT55-3vgsxavc.js} +4 -4
  27. package/dist/client/static/js/{diagram-MLGK6HIB-c2wdez02.js → diagram-MLGK6HIB-c9gf2r3f.js} +2 -2
  28. package/dist/client/static/js/{diagram-MPIPVDR6-gya9jhs5.js → diagram-MPIPVDR6-gjqeq92d.js} +2 -2
  29. package/dist/client/static/js/{dockerfile-a7q6174s.js → dockerfile-8v935dkn.js} +1 -1
  30. package/dist/client/static/js/{ebnfDiagram-ZINNZB2B-jjhkza6t.js → ebnfDiagram-ZINNZB2B-4vbsgh99.js} +1 -1
  31. package/dist/client/static/js/{elixir-rpa1g4gy.js → elixir-vcbg60wv.js} +1 -1
  32. package/dist/client/static/js/{elk-276RUBZZ-f7re45mw.js → elk-276RUBZZ-nca3t891.js} +1 -1
  33. package/dist/client/static/js/{erDiagram-OPXOYQCR-tpm9g5te.js → erDiagram-OPXOYQCR-5kfkev03.js} +2 -2
  34. package/dist/client/static/js/eventmodeling-NTZA5JFV-18bdrkv5.js +1 -0
  35. package/dist/client/static/js/flowDiagram-KWPJA3E3-fg0yqx0h.js +1 -0
  36. package/dist/client/static/js/{ganttDiagram-FUAMR5RP-fz43n12d.js → ganttDiagram-FUAMR5RP-mxc73wmq.js} +3 -3
  37. package/dist/client/static/js/gitGraph-4MIJSDKK-8fa6y40p.js +1 -0
  38. package/dist/client/static/js/{gitGraphDiagram-X574FWY7-f61hgbn6.js → gitGraphDiagram-X574FWY7-7en3ag0e.js} +12 -12
  39. package/dist/client/static/js/html-dbrwss36.js +1 -0
  40. package/dist/client/static/js/{index-m73za75e.js → index-0vm41je9.js} +3 -3
  41. package/dist/client/static/js/{index-eyzeya95.js → index-1b0t1428.js} +5 -5
  42. package/dist/client/static/js/{index-2x5f66t6.js → index-1ksg88qf.js} +1 -1
  43. package/dist/client/static/js/{index-sffjtm5w.js → index-231241f4.js} +9 -9
  44. package/dist/client/static/js/index-2mx9ej4k.css +1 -0
  45. package/dist/client/static/js/{index-8239j2v1.js → index-4g46wbdw.js} +1 -1
  46. package/dist/client/static/js/{index-1xqs14fr.js → index-4qwzxj81.js} +1 -1
  47. package/dist/client/static/js/{index-gcs49f3p.js → index-52rqxgya.js} +1 -1
  48. package/dist/client/static/js/{index-at6bhjyf.js → index-6sf2vsp2.js} +1 -1
  49. package/dist/client/static/js/{index-q2w6s8n7.js → index-7a64yjrm.js} +4 -4
  50. package/dist/client/static/js/{index-rg8jpbsw.js → index-8acv5b77.js} +2 -2
  51. package/dist/client/static/js/{index-js7t1vb1.js → index-a0fmsv1d.js} +5 -5
  52. package/dist/client/static/js/{index-w0fwb80e.js → index-ag2rmtas.js} +1 -1
  53. package/dist/client/static/js/{index-djmg1d7h.js → index-b29afsjh.js} +1 -1
  54. package/dist/client/static/js/{index-e4p4cd3r.js → index-c3ek61zv.js} +1 -1
  55. package/dist/client/static/js/{index-0e40xskg.js → index-cd65zqba.js} +1 -1
  56. package/dist/client/static/js/{index-zt75xpq0.js → index-cgzrpvzj.js} +204 -204
  57. package/dist/client/static/js/{index-0n5wwe60.js → index-ev3yt353.js} +2 -2
  58. package/dist/client/static/js/{index-9y3gjdj7.js → index-eyfcm0cy.js} +1 -1
  59. package/dist/client/static/js/{index-qsm2z36d.js → index-f7jhhqtk.js} +1 -1
  60. package/dist/client/static/js/{index-vw5k8csz.js → index-fta1y9pc.js} +50 -50
  61. package/dist/client/static/js/{index-ajs3jj6j.js → index-fvmfge3p.js} +1 -1
  62. package/dist/client/static/js/{index-pxv2nw9w.js → index-g2dyfze9.js} +1 -1
  63. package/dist/client/static/js/{index-bkye8mz4.js → index-h5bn97p6.js} +1 -1
  64. package/dist/client/static/js/{index-trm9x02n.js → index-j51d5a5m.js} +6 -6
  65. package/dist/client/static/js/{index-pbe4yed4.js → index-jsyekbx9.js} +2 -2
  66. package/dist/client/static/js/{index-gs6f0qwa.js → index-nccwxv0s.js} +2 -2
  67. package/dist/client/static/js/{index-d495kfm0.js → index-p0nz38bm.js} +1 -1
  68. package/dist/client/static/js/{index-sdtye3jy.js → index-pm6xxwz1.js} +2 -2
  69. package/dist/client/static/js/{index-3rcjx70v.js → index-ptcrwswj.js} +1 -1
  70. package/dist/client/static/js/{index-14vndmcr.js → index-ptcwae2n.js} +1 -1
  71. package/dist/client/static/js/{index-5tgq7aqx.js → index-r014brzs.js} +2 -2
  72. package/dist/client/static/js/{index-xj9649ac.js → index-ray2czf6.js} +7 -7
  73. package/dist/client/static/js/{index-apvkd37e.js → index-rs80cwsv.js} +3 -3
  74. package/dist/client/static/js/{index-vw4brsdx.js → index-rzxcj7cg.js} +1 -1
  75. package/dist/client/static/js/{index-a293pdg7.js → index-s7gkkkyz.js} +2 -2
  76. package/dist/client/static/js/{index-1a0zkj8h.js → index-sd66wv26.js} +2 -2
  77. package/dist/client/static/js/{index-ypx3qmhq.js → index-vhqe0y82.js} +1 -1
  78. package/dist/client/static/js/{index-9fjt5anh.js → index-vy6termr.js} +1 -1
  79. package/dist/client/static/js/{index-0tf0arsp.js → index-xx6mqpxm.js} +3 -3
  80. package/dist/client/static/js/{index-03h3bkcf.js → index-ybm2x4vh.js} +1 -1
  81. package/dist/client/static/js/info-A6RAGUB7-3hk844f7.js +1 -0
  82. package/dist/client/static/js/{infoDiagram-VRGFBTTK-1qj804sn.js → infoDiagram-VRGFBTTK-sef80132.js} +2 -2
  83. package/dist/client/static/js/{ishikawaDiagram-OU5B5YK6-4j4qsnzw.js → ishikawaDiagram-OU5B5YK6-yhvepp1q.js} +6 -6
  84. package/dist/client/static/js/{journeyDiagram-ZHPQQLJL-j0brnfft.js → journeyDiagram-ZHPQQLJL-5w77y95w.js} +5 -5
  85. package/dist/client/static/js/{julia-4ghmfy3e.js → julia-d4j6wgvf.js} +1 -1
  86. package/dist/client/static/js/{kanban-definition-PNTS6WVX-qqc22br0.js → kanban-definition-PNTS6WVX-02znqtna.js} +6 -6
  87. package/dist/client/static/js/{mermaid.core-vv3wbe65.js → mermaid.core-a6e6vck4.js} +5 -5
  88. package/dist/client/static/js/{mindmap-definition-NLK3R4M7-y5b2z8zp.js → mindmap-definition-NLK3R4M7-y4n74q9x.js} +8 -8
  89. package/dist/client/static/js/one-dark-pro-vwhfpzr8.js +1 -0
  90. package/dist/client/static/js/one-light-y5t9x6zh.js +1 -0
  91. package/dist/client/static/js/packet-AYTQ26CC-4nj2yy10.js +1 -0
  92. package/dist/client/static/js/{pegDiagram-GJSIUBJH-0be07mqs.js → pegDiagram-GJSIUBJH-pr7ehgzb.js} +1 -1
  93. package/dist/client/static/js/{perl-sd00t4b4.js → perl-srptw5vm.js} +1 -1
  94. package/dist/client/static/js/{php-2zfyqa61.js → php-n89g3fk7.js} +1 -1
  95. package/dist/client/static/js/pie-WAS4IAKB-k7rde3f9.js +1 -0
  96. package/dist/client/static/js/{pieDiagram-5QR66LMP-544w86jk.js → pieDiagram-5QR66LMP-39wpsk08.js} +2 -2
  97. package/dist/client/static/js/{quadrantDiagram-O4NWA36T-p09e7z5s.js → quadrantDiagram-O4NWA36T-esm913km.js} +5 -5
  98. package/dist/client/static/js/radar-RG4KPBEZ-513dpw4f.js +1 -0
  99. package/dist/client/static/js/railroad-74A4TZTK-9bqnst9c.js +1 -0
  100. package/dist/client/static/js/railroad-abnf-HS5TGJTU-7367d5bv.js +1 -0
  101. package/dist/client/static/js/railroad-ebnf-LZEXJU2U-b806b1mj.js +1 -0
  102. package/dist/client/static/js/railroad-peg-WCYAUIDC-5a67rwf8.js +1 -0
  103. package/dist/client/static/js/{railroadDiagram-XR7U4H2S-de830ed2.js → railroadDiagram-XR7U4H2S-wy2mgya6.js} +1 -1
  104. package/dist/client/static/js/{requirementDiagram-PLB6GJNP-b47d74p1.js → requirementDiagram-PLB6GJNP-6z9xdgbq.js} +2 -2
  105. package/dist/client/static/js/{ruby-v9qaqhby.js → ruby-r81ytgcm.js} +1 -1
  106. package/dist/client/static/js/{rust-fkt0qyrs.js → rust-frn3szvc.js} +1 -1
  107. package/dist/client/static/js/{sankeyDiagram-IPEJSGJF-6ezc2fpj.js → sankeyDiagram-IPEJSGJF-rtmxk3ys.js} +4 -4
  108. package/dist/client/static/js/{sequenceDiagram-PO4LG4MO-by5zqj6w.js → sequenceDiagram-PO4LG4MO-awzcrafg.js} +18 -18
  109. package/dist/client/static/js/{sizeCapture-INFHLROL-q85r06j6.js → sizeCapture-INFHLROL-03gy196j.js} +1 -1
  110. package/dist/client/static/js/sql-0e9mnrda.js +1 -0
  111. package/dist/client/static/js/{stateDiagram-v2-GCMORJYK-ep5pyexs.js → stateDiagram-v2-GCMORJYK-an8v3q5n.js} +3 -3
  112. package/dist/client/static/js/{swimlanes-2SLR337P-95fcqkh8.js → swimlanes-2SLR337P-n9yb4wcs.js} +1 -1
  113. package/dist/client/static/js/{swimlanesDiagram-TC7HE7FX-xs2en5dv.js → swimlanesDiagram-TC7HE7FX-nx5nfnf0.js} +1 -1
  114. package/dist/client/static/js/{timeline-definition-EJHVYXUP-461e615g.js → timeline-definition-EJHVYXUP-jceb575g.js} +4 -4
  115. package/dist/client/static/js/treeView-Q6P3EWNA-kcy40evb.js +1 -0
  116. package/dist/client/static/js/treemap-WGGIJYW6-fsrvqxf4.js +1 -0
  117. package/dist/client/static/js/{usecaseDiagram-POWQR4AR-ftqfnvhg.js → usecaseDiagram-POWQR4AR-888h3100.js} +13 -13
  118. package/dist/client/static/js/{vennDiagram-UO4OBE2U-7t96h6ez.js → vennDiagram-UO4OBE2U-wbfz0rzv.js} +7 -7
  119. package/dist/client/static/js/{vue-j8vb9d7r.js → vue-c0rtg1wf.js} +1 -1
  120. package/dist/client/static/js/wardley-WFR3VGLG-36dmxww4.js +1 -0
  121. package/dist/client/static/js/{wardleyDiagram-VNRHLVJA-0de8w8c6.js → wardleyDiagram-VNRHLVJA-rn8c5qf9.js} +4 -4
  122. package/dist/client/static/js/{xychartDiagram-PMCCYNJV-dez9phkf.js → xychartDiagram-PMCCYNJV-8sn1apt6.js} +5 -5
  123. package/package.json +4 -1
  124. package/src/client/components/auth/login-screen/index.tsx +1 -0
  125. package/src/client/components/common/MarkdownRenderer.tsx +9 -12
  126. package/src/client/components/settings/Modal.tsx +14 -84
  127. package/src/client/components/settings/Sidebar.tsx +3 -1
  128. package/src/client/components/settings/categories/ConnectSettings.tsx +105 -0
  129. package/src/client/components/settings/categories/connect-settings/DeviceTable.tsx +145 -0
  130. package/src/client/components/settings/categories/connect-settings/PairDialog.tsx +160 -0
  131. package/src/client/components/settings/categories/connect-settings/QrCode.tsx +73 -0
  132. package/src/client/components/settings/categories/connect-settings/ServerCard.tsx +94 -0
  133. package/src/client/components/settings/categories/connect-settings/TunnelRow.tsx +127 -0
  134. package/src/client/components/settings/category-content.tsx +116 -0
  135. package/src/client/components/workspace/chat-timeline/ChangedFilesSummary.test.tsx +120 -0
  136. package/src/client/components/workspace/chat-timeline/ChangedFilesSummary.tsx +56 -20
  137. package/src/client/components/workspace/chat-timeline/RunFooter.tsx +1 -0
  138. package/src/client/hooks/chat/timeline/change-stats.ts +57 -0
  139. package/src/client/hooks/connect/use-connect-status.ts +116 -0
  140. package/src/client/hooks/connect/use-pairing.ts +100 -0
  141. package/src/client/hooks/ui/clipboard.ts +26 -0
  142. package/src/client/tailwind.css +5 -0
  143. package/src/server/index.ts +2 -0
  144. package/src/server/lib/assets/font-css.server.test.ts +19 -0
  145. package/src/server/lib/auth/client-address.test.ts +58 -0
  146. package/src/server/lib/auth/client-address.ts +37 -3
  147. package/src/server/lib/auth/guard.ts +31 -4
  148. package/src/server/lib/auth/rate-limit.test.ts +25 -8
  149. package/src/server/lib/auth/rate-limit.ts +8 -5
  150. package/src/server/lib/connect/cloudflared.lifecycle.test.ts +88 -0
  151. package/src/server/lib/connect/cloudflared.server.test.ts +65 -0
  152. package/src/server/lib/connect/cloudflared.server.ts +206 -0
  153. package/src/server/lib/connect/devices.server.ts +192 -0
  154. package/src/server/lib/connect/identity.server.ts +81 -0
  155. package/src/server/lib/connect/pairing.server.test.ts +56 -0
  156. package/src/server/lib/connect/pairing.server.ts +113 -0
  157. package/src/server/lib/connect/qr.roundtrip.test.ts +106 -0
  158. package/src/server/lib/connect/qr.server.ts +36 -0
  159. package/src/server/lib/connect/run.server.ts +101 -0
  160. package/src/server/lib/connect/status.server.ts +177 -0
  161. package/src/server/lib/connect/tailscale.server.test.ts +117 -0
  162. package/src/server/lib/connect/tailscale.server.ts +172 -0
  163. package/src/server/lib/db/schema.ts +4 -0
  164. package/src/server/lib/omp/session/changes.test.ts +64 -1
  165. package/src/server/lib/omp/session/changes.ts +94 -1
  166. package/src/server/routes/connect/devices.ts +56 -0
  167. package/src/server/routes/connect/index.ts +15 -0
  168. package/src/server/routes/connect/pair-page.ts +177 -0
  169. package/src/server/routes/connect/pair.ts +158 -0
  170. package/src/server/routes/connect/status.ts +19 -0
  171. package/src/server/routes/connect/tunnels.ts +76 -0
  172. package/src/server/routes/health/probe.ts +5 -0
  173. package/src/server/routes/index.ts +2 -0
  174. package/src/server/routes/sessions/changes.test.ts +12 -3
  175. package/src/server/routes/sessions/changes.ts +27 -3
  176. package/src/server/routes/sessions/index.ts +2 -1
  177. package/src/shared/lib/connect/payload.test.ts +144 -0
  178. package/src/shared/lib/connect/payload.ts +229 -0
  179. package/src/shared/lib/connect/tier.test.ts +73 -0
  180. package/src/shared/lib/connect/tier.ts +105 -0
  181. package/src/shared/lib/connect/types.ts +99 -0
  182. package/src/shared/lib/markdown/fira-code-fonts.css +65 -6
  183. package/src/shared/lib/markdown/marked.ts +7 -4
  184. package/src/shared/lib/markdown/mermaid-actions.test.ts +78 -0
  185. package/src/shared/lib/markdown/mermaid-actions.ts +45 -0
  186. package/src/shared/lib/markdown/mermaid.ts +41 -7
  187. package/src/shared/lib/settings/sections.ts +6 -1
  188. package/src/shared/types/session-changes.ts +6 -0
  189. package/src/shared/types/settings/state.ts +2 -0
  190. package/dist/client/static/js/Modal-qtftcp2t.js +0 -38
  191. package/dist/client/static/js/architecture-7GRP2DOG-tavtgb8a.js +0 -1
  192. package/dist/client/static/js/cynefin-OW5HDTMX-cdh3n2z2.js +0 -1
  193. package/dist/client/static/js/eventmodeling-NTZA5JFV-as97tpyp.js +0 -1
  194. package/dist/client/static/js/flowDiagram-KWPJA3E3-ggm06d12.js +0 -1
  195. package/dist/client/static/js/gitGraph-4MIJSDKK-eqz7p9ng.js +0 -1
  196. package/dist/client/static/js/html-pv88ny12.js +0 -1
  197. package/dist/client/static/js/index-e94a1en0.css +0 -1
  198. package/dist/client/static/js/info-A6RAGUB7-4pkzh1qx.js +0 -1
  199. package/dist/client/static/js/one-dark-pro-hm3f56n1.js +0 -1
  200. package/dist/client/static/js/one-light-xrz49rct.js +0 -1
  201. package/dist/client/static/js/packet-AYTQ26CC-yg71sp88.js +0 -1
  202. package/dist/client/static/js/pie-WAS4IAKB-89wd6np0.js +0 -1
  203. package/dist/client/static/js/radar-RG4KPBEZ-avn0b8r9.js +0 -1
  204. package/dist/client/static/js/railroad-74A4TZTK-de27xv5w.js +0 -1
  205. package/dist/client/static/js/railroad-abnf-HS5TGJTU-rg4zzj7x.js +0 -1
  206. package/dist/client/static/js/railroad-ebnf-LZEXJU2U-d84fhj8v.js +0 -1
  207. package/dist/client/static/js/railroad-peg-WCYAUIDC-dvf8xrmc.js +0 -1
  208. package/dist/client/static/js/sql-g8wcshpc.js +0 -1
  209. package/dist/client/static/js/treeView-Q6P3EWNA-mham0bh6.js +0 -1
  210. package/dist/client/static/js/treemap-WGGIJYW6-mxrxax86.js +0 -1
  211. package/dist/client/static/js/wardley-WFR3VGLG-8vrvh9p3.js +0 -1
@@ -0,0 +1,100 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Minting a pairing code, and the countdown that makes its life visible.
8
+ *
9
+ * The code is single-use and expires in two minutes, so the dialog has to say
10
+ * both things and show the clock. A code that silently stops working is
11
+ * indistinguishable from a broken camera, and the user's next move — rescan,
12
+ * restart the app — is the wrong one.
13
+ */
14
+
15
+ import { useCallback, useEffect, useState } from 'preact/hooks';
16
+ import type { ConnectCandidate } from '@/shared/lib/connect/types';
17
+
18
+ export interface PairingCode {
19
+ pairingId: string;
20
+ expiresAt: string;
21
+ /** The `kabmo://` deep link, for a native shell that registers the scheme. */
22
+ link: string;
23
+ /** The `https://…/pair#…` link a browser can open. This is what the QR holds. */
24
+ webLink: string;
25
+ candidates: ConnectCandidate[];
26
+ qr: { size: number; rows: string[] };
27
+ }
28
+
29
+ export interface UsePairingResult {
30
+ code: PairingCode | null;
31
+ error: string | null;
32
+ busy: boolean;
33
+ /** Seconds left before the code stops working; 0 once it has. */
34
+ secondsLeft: number;
35
+ create: () => Promise<void>;
36
+ reset: () => void;
37
+ }
38
+
39
+ interface PairingEnvelope extends Partial<PairingCode> {
40
+ error?: string;
41
+ }
42
+
43
+ export function usePairing(): UsePairingResult {
44
+ const [code, setCode] = useState<PairingCode | null>(null);
45
+ const [error, setError] = useState<string | null>(null);
46
+ const [busy, setBusy] = useState(false);
47
+ const [secondsLeft, setSecondsLeft] = useState(0);
48
+
49
+ const create = useCallback(async () => {
50
+ setBusy(true);
51
+ setError(null);
52
+ try {
53
+ const response = await fetch('/api/connect/pair', {
54
+ method: 'POST',
55
+ headers: { 'content-type': 'application/json' },
56
+ body: JSON.stringify({ action: 'create' }),
57
+ });
58
+ const payload = (await response.json().catch(() => null)) as PairingEnvelope | null;
59
+ if (!response.ok || !payload?.qr || !payload.link) {
60
+ setError(payload?.error ?? `Could not create a pairing code (HTTP ${response.status}).`);
61
+ setCode(null);
62
+ return;
63
+ }
64
+ setCode({
65
+ pairingId: payload.pairingId ?? '',
66
+ expiresAt: payload.expiresAt ?? '',
67
+ link: payload.link,
68
+ webLink: payload.webLink ?? payload.link,
69
+ candidates: payload.candidates ?? [],
70
+ qr: payload.qr,
71
+ });
72
+ } catch (cause) {
73
+ setError(cause instanceof Error ? cause.message : 'Could not create a pairing code.');
74
+ setCode(null);
75
+ } finally {
76
+ setBusy(false);
77
+ }
78
+ }, []);
79
+
80
+ const reset = useCallback(() => {
81
+ setCode(null);
82
+ setError(null);
83
+ setSecondsLeft(0);
84
+ }, []);
85
+
86
+ // The countdown is derived from the server's own `expiresAt`, not from a
87
+ // local two-minute timer: a clock that started when the dialog opened would
88
+ // keep counting through a slow request and claim time the code never had.
89
+ useEffect(() => {
90
+ if (!code) return;
91
+ const deadline = Date.parse(code.expiresAt);
92
+ if (!Number.isFinite(deadline)) return;
93
+ const tick = () => setSecondsLeft(Math.max(0, Math.round((deadline - Date.now()) / 1000)));
94
+ tick();
95
+ const timer = setInterval(tick, 1_000);
96
+ return () => clearInterval(timer);
97
+ }, [code]);
98
+
99
+ return { code, error, busy, secondsLeft, create, reset };
100
+ }
@@ -48,3 +48,29 @@ export async function readClipboardText(): Promise<string | null> {
48
48
  return null;
49
49
  }
50
50
  }
51
+
52
+ const COPY_ICON =
53
+ '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
54
+ const CHECK_ICON =
55
+ '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';
56
+
57
+ /**
58
+ * Copy a code block's text and flash the checkmark on its button.
59
+ *
60
+ * The button is markup the markdown renderer injected, so the swap is DOM work
61
+ * rather than component state — and it belongs next to the clipboard call it
62
+ * reports, not in the renderer's delegated click handler.
63
+ */
64
+ export function copyFromButton(button: HTMLButtonElement): void {
65
+ const text = button.dataset.copy ?? '';
66
+ if (!text) return;
67
+ void copyToClipboard(text).then((ok) => {
68
+ if (!ok) return;
69
+ button.setAttribute('data-copied', 'true');
70
+ button.innerHTML = CHECK_ICON;
71
+ setTimeout(() => {
72
+ button.removeAttribute('data-copied');
73
+ button.innerHTML = COPY_ICON;
74
+ }, 2000);
75
+ });
76
+ }
@@ -1018,6 +1018,11 @@ html[data-theme-variant="dark"] .shiki span { color: var(--shiki-dark); }
1018
1018
  .prose-content .mermaid-block .code-copy-float {
1019
1019
  z-index: 1;
1020
1020
  }
1021
+ /* Refresh sits left of copy: a blank diagram is the one state where the reader
1022
+ needs it, and it must not cover the copy button they already know. */
1023
+ .prose-content .mermaid-block .code-copy-float.mermaid-refresh-float {
1024
+ right: 2.125rem;
1025
+ }
1021
1026
  .prose-content .mermaid-block[data-mermaid-state='error'] pre {
1022
1027
  color: var(--theme-error);
1023
1028
  }
@@ -11,6 +11,7 @@ import { ssrRoutes } from '@/server/plugins/ssr';
11
11
  import { setListener } from '@/server/lib/lifecycle/listener';
12
12
  import { getDatabasePath } from '@/server/db.server';
13
13
  import { initAgentTokens } from '@/server/lib/sessions/agent-token.server';
14
+ import { initDeviceTokens } from '@/server/lib/connect/devices.server';
14
15
  import { logDetectedRegistry } from '@/server/lib/models/detected-registry.server';
15
16
  import { ompStartupError, ompStartupLogLines } from '@/server/lib/omp/core/startup';
16
17
  import { readInstanceRecord, removeInstanceRecord, writeInstanceRecord } from '@/server/lib/lifecycle/instance';
@@ -76,6 +77,7 @@ console.log(`[kabmo] ui auth: ${authNotice}${runPassword.source === 'argv
76
77
  for (const line of ompStartupLogLines()) console.log(`[kabmo] ${line}`);
77
78
  console.log(`[kabmo] db: ${await getDatabasePath()}`);
78
79
  await initAgentTokens();
80
+ await initDeviceTokens();
79
81
 
80
82
  const port = Number(Bun.env.PORT) || 3000;
81
83
  const host = Bun.env.HOST || 'localhost';
@@ -50,6 +50,25 @@ describe('/fonts.css is assembled from source, not from a build artifact', () =>
50
50
  expect(urls(sheet)).toContain('/fonts/fira-code-latin-400-normal.woff2');
51
51
  });
52
52
 
53
+ /**
54
+ * The `symbols2` subset is the ONLY face carrying U+2500-259F, and it is not
55
+ * a language subset — so a "drop the unused subsets" pass removes it and
56
+ * every ASCII box in a markdown code block silently skews. Measured in
57
+ * WebKit at 12px with the face absent: `M` 7.2px, `─`/`│`/`┌` 8.502px, so a
58
+ * `─` border overshoots its own `│` corner by 1.3px per column. With it
59
+ * declared, all four measure 7.2px and a 42-column box renders every line at
60
+ * exactly 302.4px.
61
+ */
62
+ test('it declares the box-drawing subset, which no language subset carries', () => {
63
+ expect(urls(sheet)).toContain('/fonts/fira-code-symbols2-400-normal.woff2');
64
+ expect(urls(sheet)).toContain('/fonts/fira-code-symbols2-700-normal.woff2');
65
+ // The range is what keeps the 4 kB files off the wire on a page that lays
66
+ // out no box-drawing glyph, so a face without it is a different contract.
67
+ const symbols2 = [...sheet.matchAll(/@font-face\s*\{[^{}]*symbols2[^{}]*\}/g)].map(([block]) => block);
68
+ expect(symbols2.length).toBe(4);
69
+ for (const block of symbols2) expect(block).toContain('U+2500-259F');
70
+ });
71
+
53
72
  test('every url is rewritten to the served route — no relative or node_modules path survives', () => {
54
73
  const targets = urls(sheet);
55
74
  expect(targets.length).toBeGreaterThan(20);
@@ -0,0 +1,58 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Which address the login throttle keys on.
8
+ *
9
+ * Two failures are being prevented, and they point in opposite directions:
10
+ *
11
+ * - trusting `x-forwarded-for` from a DIRECT remote connection lets one attacker
12
+ * present a fresh identity per guess and walk through the budget;
13
+ * - ignoring it behind a tunnel makes every client share `127.0.0.1`, so ten
14
+ * failures from anywhere lock the owner out for fifteen minutes.
15
+ *
16
+ * The socket address is what separates the two cases, so that is what these
17
+ * tests vary.
18
+ */
19
+
20
+ import { describe, expect, test } from 'bun:test';
21
+ import { effectiveClientAddress } from '@/server/lib/auth/client-address';
22
+ import { UNKNOWN_CLIENT_KEY } from '@/server/lib/auth/rate-limit';
23
+
24
+ function request(headers: Record<string, string> = {}): Request {
25
+ return new Request('http://localhost:3000/api/auth/login', { method: 'POST', headers });
26
+ }
27
+
28
+ describe('effectiveClientAddress', () => {
29
+ test('uses the socket address for a direct remote connection', () => {
30
+ const address = effectiveClientAddress(request({ 'x-forwarded-for': '1.2.3.4' }), '192.168.18.50');
31
+ expect(address).toBe('192.168.18.50');
32
+ });
33
+
34
+ test('uses the forwarded address when the socket is loopback', () => {
35
+ const address = effectiveClientAddress(request({ 'x-forwarded-for': '203.0.113.9' }), '127.0.0.1');
36
+ expect(address).toBe('203.0.113.9');
37
+ });
38
+
39
+ test('takes the first entry of a forwarded chain', () => {
40
+ const address = effectiveClientAddress(
41
+ request({ 'x-forwarded-for': '203.0.113.9, 10.0.0.1, 127.0.0.1' }),
42
+ '::1',
43
+ );
44
+ expect(address).toBe('203.0.113.9');
45
+ });
46
+
47
+ test('keeps loopback when a tunnel sent no forwarded header', () => {
48
+ expect(effectiveClientAddress(request(), '127.0.0.1')).toBe('127.0.0.1');
49
+ });
50
+
51
+ test('falls back to the shared unknown key when there is no socket address', () => {
52
+ expect(effectiveClientAddress(request({ 'x-forwarded-for': '203.0.113.9' }), undefined)).toBe(UNKNOWN_CLIENT_KEY);
53
+ });
54
+
55
+ test('treats an empty forwarded value as absent', () => {
56
+ expect(effectiveClientAddress(request({ 'x-forwarded-for': ' ' }), '127.0.0.1')).toBe('127.0.0.1');
57
+ });
58
+ });
@@ -16,8 +16,20 @@
16
16
  * and the handler are handed the SAME object (verified on Elysia 1.4.30). It is
17
17
  * also self-cleaning: the entry disappears with the request.
18
18
  *
19
- * This is the socket address, never `x-forwarded-for` — that header is
20
- * caller-supplied, so a rate limit keyed on it would be trivially evaded.
19
+ * ## Why `x-forwarded-for` is read, and only from loopback
20
+ *
21
+ * The header is caller-supplied, so a rate limit keyed on it unconditionally is
22
+ * trivially evaded — that was the original rule, and it is still right for a
23
+ * direct connection. But a tunnel breaks the other way: `cloudflared` and
24
+ * `tailscale serve` both connect to this server from `127.0.0.1`, so EVERY
25
+ * client behind a tunnel shares one socket address. Ten failed logins from an
26
+ * attacker anywhere on the internet then locked the owner out for fifteen
27
+ * minutes — a denial of service against the person the limit exists to protect.
28
+ *
29
+ * The condition is therefore the socket, not the header: the forwarded value is
30
+ * used only when the connection itself came from loopback. A remote attacker
31
+ * cannot make their own socket address loopback, and a local process that can
32
+ * forge the header already has the machine.
21
33
  *
22
34
  * NOTE: there is deliberately no `clientAddressFromContext(context)` here.
23
35
  *
@@ -38,9 +50,31 @@ import { UNKNOWN_CLIENT_KEY } from '@/server/lib/auth/rate-limit';
38
50
 
39
51
  const addresses = new WeakMap<Request, string>();
40
52
 
53
+ /** Whether a socket address is this machine talking to itself. */
54
+ function isLoopback(address: string): boolean {
55
+ return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1';
56
+ }
57
+
58
+ /**
59
+ * The address a rate limit should key on.
60
+ *
61
+ * Behind a tunnel the socket is loopback for every client, so the forwarded
62
+ * value is the only thing that distinguishes them. It is trusted ONLY in that
63
+ * case — see the module comment for why the socket, not the header, is the
64
+ * condition.
65
+ */
66
+ export function effectiveClientAddress(request: Request, socketAddress: string | undefined): string {
67
+ if (!socketAddress) return UNKNOWN_CLIENT_KEY;
68
+ if (!isLoopback(socketAddress)) return socketAddress;
69
+ const forwarded = request.headers.get('x-forwarded-for');
70
+ if (!forwarded) return socketAddress;
71
+ const first = forwarded.split(',')[0]?.trim();
72
+ return first || socketAddress;
73
+ }
74
+
41
75
  /** Record the socket address for `request`. Called by the auth gate. */
42
76
  export function rememberClientAddress(request: Request, address: string | undefined): void {
43
- addresses.set(request, address && address.length > 0 ? address : UNKNOWN_CLIENT_KEY);
77
+ addresses.set(request, effectiveClientAddress(request, address));
44
78
  }
45
79
 
46
80
  /**
@@ -30,6 +30,7 @@
30
30
  import { hashPassword, deriveCredentialKey, readSessionSecret, writeSessionSecret, type ActiveAuthConfig } from '@/server/lib/auth/config';
31
31
  import { readSessionCookie, verifySessionToken } from '@/server/lib/auth/token';
32
32
  import { agentTokenScopeForPath, bearerToken, verifyAgentToken } from '@/server/lib/sessions/agent-token.server';
33
+ import { verifyDeviceToken, readDeviceCookie } from '@/server/lib/connect/devices.server';
33
34
  import { rememberClientAddress } from '@/server/lib/auth/client-address';
34
35
  import type { CredentialHandover } from '@/shared/lib/auth/handover';
35
36
 
@@ -56,6 +57,13 @@ const PUBLIC_EXACT = new Set([
56
57
  '/api/auth/state',
57
58
  '/api/auth/login',
58
59
  '/api/auth/logout',
60
+ // A device redeeming a pairing code has no cookie yet — the one-time secret in
61
+ // the code IS its credential. Minting a code stays gated; only the redemption
62
+ // is public, and it is single-use with a two-minute life.
63
+ '/api/connect/pair/claim',
64
+ // The page a phone's camera opens. It carries no session and no data of its
65
+ // own: it reads the pairing payload from the URL fragment and posts it once.
66
+ '/pair',
59
67
  LOGIN_PATH,
60
68
  '/robots.txt',
61
69
  '/sw.js',
@@ -237,10 +245,20 @@ export function isAuthEnabled(): boolean {
237
245
  */
238
246
  export function isAuthenticatedRequest(request: Request): boolean {
239
247
  if (!active) return true;
240
- return verifySessionToken(readSessionCookie(request), {
241
- sessionSecret: active.sessionSecret,
242
- credentialKey: active.credentialKey,
243
- });
248
+ if (
249
+ verifySessionToken(readSessionCookie(request), {
250
+ sessionSecret: active.sessionSecret,
251
+ credentialKey: active.credentialKey,
252
+ })
253
+ ) {
254
+ return true;
255
+ }
256
+ // A paired device carries its own token, and the gate accepts it for every
257
+ // path — so this must agree, or the shell renders the login screen to a device
258
+ // that is already authenticated. Measured: after pairing, the cookie was set
259
+ // and every API call answered 200, while the document still drew the password
260
+ // form because this function only knew about session cookies.
261
+ return verifyDeviceToken(bearerToken(request)) !== null || verifyDeviceToken(readDeviceCookie(request)) !== null;
244
262
  }
245
263
 
246
264
  /** JSON body for a rejected API call, or a redirect for a document request. */
@@ -305,6 +323,15 @@ export function authGate(request: Request, clientAddress?: string): Response | u
305
323
  if (agentSession && (scope === 'any' || scope === agentSession)) return undefined;
306
324
  }
307
325
 
326
+ // A paired device carries its own token, and it is good for the whole console
327
+ // rather than one path: the device is a browser, not a subprocess. Revoking
328
+ // the device removes the hash from the cache, so the next request fails here.
329
+ // The cookie form is what a webview can actually send — it cannot attach a
330
+ // header to its own page requests or to a WebSocket upgrade.
331
+ if (verifyDeviceToken(bearerToken(request)) || verifyDeviceToken(readDeviceCookie(request))) {
332
+ return undefined;
333
+ }
334
+
308
335
  const wantsHtml = (request.headers.get('accept') ?? '').includes('text/html');
309
336
  return rejectionResponse(pathname, wantsHtml);
310
337
  }
@@ -91,10 +91,15 @@ describe('login rate limit', () => {
91
91
  describe('the rate limit cannot be evaded by a forged forwarding header', () => {
92
92
  // Verified against a live server: 8 attempts with rotating `x-forwarded-for`
93
93
  // and `x-real-ip` values all answered 429. This pins the REASON, against the
94
- // real gate rather than a stand-in: the key is the socket address the gate
95
- // records, and a caller-supplied header is never consulted. If that ever
96
- // changed, a caller could present a fresh identity per attempt and walk
97
- // straight through the budget — invisible until exploited.
94
+ // real gate rather than a stand-in: for a DIRECT connection the key is the
95
+ // socket address the gate records, and a caller-supplied header is never
96
+ // consulted. If that ever changed, a caller could present a fresh identity per
97
+ // attempt and walk straight through the budget — invisible until exploited.
98
+ //
99
+ // The socket here is a LAN address on purpose. A loopback socket is the one
100
+ // case where the header IS read (see the tunnel test below), because a tunnel
101
+ // connects from 127.0.0.1 and every client behind it would otherwise share one
102
+ // budget — which let an attacker anywhere lock the owner out for 15 minutes.
98
103
  const loginRequest = (forwardedFor: string) => new Request('http://127.0.0.1/api/auth/login', {
99
104
  method: 'POST',
100
105
  headers: { 'content-type': 'application/json', 'x-forwarded-for': forwardedFor, 'x-real-ip': forwardedFor },
@@ -103,9 +108,9 @@ describe('the rate limit cannot be evaded by a forged forwarding header', () =>
103
108
  test('a forged forwarding header does not become the rate-limit key', async () => {
104
109
  const request = loginRequest('10.0.0.1');
105
110
  // The gate records the socket address it was handed…
106
- await authGate(request, '127.0.0.1');
111
+ await authGate(request, '192.168.18.50');
107
112
  // …and that is what the login route throttles on, not the header.
108
- expect(clientAddressFor(request)).toBe('127.0.0.1');
113
+ expect(clientAddressFor(request)).toBe('192.168.18.50');
109
114
  expect(clientAddressFor(request)).not.toBe('10.0.0.1');
110
115
  });
111
116
 
@@ -113,12 +118,24 @@ describe('the rate limit cannot be evaded by a forged forwarding header', () =>
113
118
  const keys = new Set<string>();
114
119
  for (let attempt = 0; attempt < 5; attempt += 1) {
115
120
  const request = loginRequest(`10.0.0.${attempt}`);
116
- await authGate(request, '127.0.0.1');
121
+ await authGate(request, '192.168.18.50');
117
122
  keys.add(clientAddressFor(request));
118
123
  }
119
124
  // Five different forged identities, one key.
120
125
  expect(keys.size).toBe(1);
121
- expect([...keys][0]).toBe('127.0.0.1');
126
+ expect([...keys][0]).toBe('192.168.18.50');
127
+ });
128
+
129
+ test('behind a tunnel the forwarded address IS the key, so one client cannot lock out the rest', async () => {
130
+ // `cloudflared` and `tailscale serve` both connect from loopback. Keying on
131
+ // the socket there gave every client on the internet one shared budget: ten
132
+ // failures from an attacker locked the owner out for fifteen minutes.
133
+ const attacker = loginRequest('203.0.113.9');
134
+ const owner = loginRequest('198.51.100.4');
135
+ await authGate(attacker, '127.0.0.1');
136
+ await authGate(owner, '127.0.0.1');
137
+ expect(clientAddressFor(attacker)).toBe('203.0.113.9');
138
+ expect(clientAddressFor(owner)).toBe('198.51.100.4');
122
139
  });
123
140
 
124
141
  test('an unidentifiable caller falls back to the shared key, not a fresh one', async () => {
@@ -16,11 +16,14 @@
16
16
  * cleared by hand after a restart, and the process is only reachable at all
17
17
  * because someone chose to expose it.
18
18
  *
19
- * The key is the SOCKET address (`requestIP`), never `x-forwarded-for`: that
20
- * header is caller-supplied, so trusting it would let one client present a fresh
21
- * identity per attempt and walk straight through the budget. Behind a reverse
22
- * proxy every client shares the proxy's socket address, which throttles them
23
- * together — the conservative direction for a limit whose job is to fail closed.
19
+ * The key is the SOCKET address (`requestIP`), except when the socket is
20
+ * loopback — the case a tunnel creates. `cloudflared` and `tailscale serve`
21
+ * connect from `127.0.0.1`, so every client behind one shares a single address
22
+ * and ten failures from an attacker anywhere would lock the owner out. In that
23
+ * one case the forwarded address is used instead; see
24
+ * `effectiveClientAddress` in `client-address.ts` for why the socket, not the
25
+ * header, is the condition. A direct remote connection still keys on its own
26
+ * socket address, which a caller cannot forge.
24
27
  */
25
28
 
26
29
  /** Sliding window an attempt count is measured over. */
@@ -0,0 +1,88 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The cloudflared lifecycle, driven through a stand-in.
8
+ *
9
+ * A real named tunnel needs an account, a domain and a credentials file, so the
10
+ * start path is unreachable on a machine that has none — which is exactly the
11
+ * path that would otherwise ship untested. The stand-in is a script that stays
12
+ * alive, which is all `startCloudflared` requires: it records the process, derives
13
+ * the public URL from the config's hostname, and reports liveness from the
14
+ * process's own exit code.
15
+ */
16
+
17
+ import { afterEach, describe, expect, test } from 'bun:test';
18
+ import fs from 'fs';
19
+ import os from 'os';
20
+ import path from 'path';
21
+ import {
22
+ cloudflaredAlive,
23
+ runningTunnelUrl,
24
+ startCloudflared,
25
+ stopCloudflared,
26
+ } from '@/server/lib/connect/cloudflared.server';
27
+
28
+ // The stand-in is a `#!/bin/sh` script, so the cases that spawn it are
29
+ // POSIX-only: Windows cannot execute it, and they would fail on the spawn
30
+ // instead of on the lifecycle they exist to measure. The Linux gate covers it.
31
+ const posixOnly = process.platform !== 'win32';
32
+
33
+ const dirs: string[] = [];
34
+
35
+ function fakeCloudflared(): string {
36
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kabmo-cf-bin-'));
37
+ dirs.push(dir);
38
+ const file = path.join(dir, 'cloudflared');
39
+ // Stays alive until killed, like the real `tunnel run`.
40
+ fs.writeFileSync(file, '#!/bin/sh\nexec sleep 30\n');
41
+ fs.chmodSync(file, 0o755);
42
+ return file;
43
+ }
44
+
45
+ afterEach(() => {
46
+ for (const dir of dirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
47
+ });
48
+
49
+ describe('cloudflared lifecycle', () => {
50
+ test.skipIf(!posixOnly)('starting records the public URL and reports the process alive', async () => {
51
+ const binary = fakeCloudflared();
52
+ const port = 39_101;
53
+ const outcome = await startCloudflared(binary, '/tmp/config.yml', 'kabmo.example.com', port);
54
+
55
+ expect(outcome.ok).toBe(true);
56
+ expect(outcome.url).toBe('https://kabmo.example.com');
57
+ expect(runningTunnelUrl(port)).toBe('https://kabmo.example.com');
58
+ expect(cloudflaredAlive(port)).toBe(true);
59
+
60
+ stopCloudflared(port);
61
+ expect(cloudflaredAlive(port)).toBe(false);
62
+ expect(runningTunnelUrl(port)).toBeNull();
63
+ });
64
+
65
+ test.skipIf(!posixOnly)('starting twice for one port reuses the running tunnel', async () => {
66
+ const binary = fakeCloudflared();
67
+ const port = 39_102;
68
+ await startCloudflared(binary, '/tmp/config.yml', 'a.example.com', port);
69
+ const second = await startCloudflared(binary, '/tmp/config.yml', 'b.example.com', port);
70
+
71
+ // The second call must not spawn a second process, and must not claim a
72
+ // different hostname than the one actually running.
73
+ expect(second.url).toBe('https://a.example.com');
74
+ stopCloudflared(port);
75
+ });
76
+
77
+ test('stopping a tunnel that was never started is not an error', () => {
78
+ expect(stopCloudflared(39_103)).toEqual({ ok: true, reason: null });
79
+ expect(cloudflaredAlive(39_103)).toBe(false);
80
+ });
81
+
82
+ test('a binary that cannot be spawned reports the reason', async () => {
83
+ const outcome = await startCloudflared('/nonexistent/cloudflared', '/tmp/config.yml', 'x.example.com', 39_104);
84
+ expect(outcome.ok).toBe(false);
85
+ expect(outcome.reason).toBeTruthy();
86
+ expect(cloudflaredAlive(39_104)).toBe(false);
87
+ });
88
+ });
@@ -0,0 +1,65 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The cloudflared config scan.
8
+ *
9
+ * A line scan is only safe if it refuses the shapes it cannot read. The case
10
+ * that matters is a config with an ingress block but no hostname: reporting a
11
+ * tunnel as configured there would put a URL on the page that does not exist.
12
+ */
13
+
14
+ import { describe, expect, test } from 'bun:test';
15
+ import fs from 'fs';
16
+ import os from 'os';
17
+ import path from 'path';
18
+ import { readCloudflaredConfig } from '@/server/lib/connect/cloudflared.server';
19
+
20
+ function writeConfig(text: string): string {
21
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kabmo-cf-'));
22
+ const file = path.join(dir, 'config.yml');
23
+ fs.writeFileSync(file, text);
24
+ return file;
25
+ }
26
+
27
+ describe('readCloudflaredConfig', () => {
28
+ test('reads the tunnel name and the first ingress hostname', () => {
29
+ const file = writeConfig(
30
+ [
31
+ 'tunnel: 6ff42ae2-765d-4adf-8112-31c55c1551ef',
32
+ 'credentials-file: /home/me/.cloudflared/6ff42ae2.json',
33
+ '',
34
+ 'ingress:',
35
+ ' - hostname: kabmo.example.com',
36
+ ' service: http://localhost:3000',
37
+ ' - service: http_status:404',
38
+ '',
39
+ ].join('\n'),
40
+ );
41
+ expect(readCloudflaredConfig(file)).toEqual({
42
+ tunnel: '6ff42ae2-765d-4adf-8112-31c55c1551ef',
43
+ hostname: 'kabmo.example.com',
44
+ });
45
+ });
46
+
47
+ test('strips quotes around a value', () => {
48
+ const file = writeConfig(['tunnel: "my-tunnel"', 'ingress:', ' - hostname: "a.example.com"'].join('\n'));
49
+ expect(readCloudflaredConfig(file)).toEqual({ tunnel: 'my-tunnel', hostname: 'a.example.com' });
50
+ });
51
+
52
+ test('answers null for a file with neither field', () => {
53
+ const file = writeConfig('metrics: 127.0.0.1:20241\n');
54
+ expect(readCloudflaredConfig(file)).toBeNull();
55
+ });
56
+
57
+ test('answers null for a missing file', () => {
58
+ expect(readCloudflaredConfig(path.join(os.tmpdir(), 'kabmo-does-not-exist.yml'))).toBeNull();
59
+ });
60
+
61
+ test('does not read a hostname from outside the ingress block', () => {
62
+ const file = writeConfig(['tunnel: t', 'hostname: not-ingress.example.com', 'ingress:', ' - service: http_status:404'].join('\n'));
63
+ expect(readCloudflaredConfig(file)).toEqual({ tunnel: 't', hostname: null });
64
+ });
65
+ });