@prismshadow/penguin-server 0.2.2 → 0.2.4

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 (302) hide show
  1. package/README.md +3 -0
  2. package/dist/api/types.d.ts +552 -49
  3. package/dist/chunk-KQQ3HSTK.js +568 -0
  4. package/dist/chunk-KQQ3HSTK.js.map +1 -0
  5. package/dist/hmr/manifest.d.ts +54 -0
  6. package/dist/hmr/manifest.js +27 -0
  7. package/dist/hmr/manifest.js.map +1 -0
  8. package/dist/index.js +4495 -1041
  9. package/dist/index.js.map +1 -1
  10. package/dist/reset-admin-password.d.ts +28 -0
  11. package/dist/reset-admin-password.js +39 -0
  12. package/dist/reset-admin-password.js.map +1 -0
  13. package/package.json +15 -3
  14. package/web-dist/assets/addon-fit-ClUHZ6NU.js +1 -0
  15. package/web-dist/assets/addon-web-links-BKMSMMvN.js +1 -0
  16. package/web-dist/assets/cpp-DIPi6g--.js +1 -0
  17. package/web-dist/assets/highlighter-Cp5vYdaX.js +152 -0
  18. package/web-dist/assets/index-BJNmFD1m.js +187 -0
  19. package/web-dist/assets/index-BneOZQwC.css +1 -0
  20. package/web-dist/assets/ruby-B13GW9FM.js +1 -0
  21. package/web-dist/assets/xterm-j28bzvOQ.js +9 -0
  22. package/web-dist/index.html +2 -2
  23. package/web-dist/assets/abap-BdImnpbu.js +0 -1
  24. package/web-dist/assets/actionscript-3-CoDkCxhg.js +0 -1
  25. package/web-dist/assets/ada-bCR0ucgS.js +0 -1
  26. package/web-dist/assets/andromeeda-C4gqWexZ.js +0 -1
  27. package/web-dist/assets/angular-html-DA-rfuFy.js +0 -1
  28. package/web-dist/assets/angular-ts-BrjP3tb8.js +0 -1
  29. package/web-dist/assets/apache-Pmp26Uib.js +0 -1
  30. package/web-dist/assets/apex-Dqspr-GT.js +0 -1
  31. package/web-dist/assets/apl-CORt7UWP.js +0 -1
  32. package/web-dist/assets/applescript-Co6uUVPk.js +0 -1
  33. package/web-dist/assets/ara-BRHolxvo.js +0 -1
  34. package/web-dist/assets/asciidoc-Ve4PFQV2.js +0 -1
  35. package/web-dist/assets/asm-D_Q5rh1f.js +0 -1
  36. package/web-dist/assets/astro-HNnZUWAn.js +0 -1
  37. package/web-dist/assets/aurora-x-D-2ljcwZ.js +0 -1
  38. package/web-dist/assets/awk-DMzUqQB5.js +0 -1
  39. package/web-dist/assets/ayu-dark-DYE7WIF3.js +0 -1
  40. package/web-dist/assets/ayu-light-BA47KaF1.js +0 -1
  41. package/web-dist/assets/ayu-mirage-32ctXXKs.js +0 -1
  42. package/web-dist/assets/ballerina-BFfxhgS-.js +0 -1
  43. package/web-dist/assets/bat-BkioyH1T.js +0 -1
  44. package/web-dist/assets/beancount-k_qm7-4y.js +0 -1
  45. package/web-dist/assets/berry-uYugtg8r.js +0 -1
  46. package/web-dist/assets/bibtex-CHM0blh-.js +0 -1
  47. package/web-dist/assets/bicep-Bmn6On1c.js +0 -1
  48. package/web-dist/assets/bird2-BIv1doCn.js +0 -1
  49. package/web-dist/assets/blade-2xfisSek.js +0 -1
  50. package/web-dist/assets/bsl-BO_Y6i37.js +0 -1
  51. package/web-dist/assets/c3-MRO5bC_T.js +0 -1
  52. package/web-dist/assets/cadence-Bv_4Rxtq.js +0 -1
  53. package/web-dist/assets/cairo-KRGpt6FW.js +0 -1
  54. package/web-dist/assets/catppuccin-frappe-DFWUc33u.js +0 -1
  55. package/web-dist/assets/catppuccin-latte-C9dUb6Cb.js +0 -1
  56. package/web-dist/assets/catppuccin-macchiato-DQyhUUbL.js +0 -1
  57. package/web-dist/assets/catppuccin-mocha-D87Tk5Gz.js +0 -1
  58. package/web-dist/assets/clarity-D53aC0YG.js +0 -1
  59. package/web-dist/assets/clojure-P80f7IUj.js +0 -1
  60. package/web-dist/assets/cmake-D1j8_8rp.js +0 -1
  61. package/web-dist/assets/cobol-nBiQ_Alo.js +0 -1
  62. package/web-dist/assets/codeowners-Bp6g37R7.js +0 -1
  63. package/web-dist/assets/codeql-DsOJ9woJ.js +0 -1
  64. package/web-dist/assets/coffee-Ch7k5sss.js +0 -1
  65. package/web-dist/assets/common-lisp-Cg-RD9OK.js +0 -1
  66. package/web-dist/assets/coq-DkFqJrB1.js +0 -1
  67. package/web-dist/assets/cpp-UfJy6YNI.js +0 -1
  68. package/web-dist/assets/crystal-DGywbUpC.js +0 -1
  69. package/web-dist/assets/csharp-DSvCPggb.js +0 -1
  70. package/web-dist/assets/csv-fuZLfV_i.js +0 -1
  71. package/web-dist/assets/cue-D82EKSYY.js +0 -1
  72. package/web-dist/assets/cypher-COkxafJQ.js +0 -1
  73. package/web-dist/assets/d-85-TOEBH.js +0 -1
  74. package/web-dist/assets/dark-plus-C3mMm8J8.js +0 -1
  75. package/web-dist/assets/dart-bE4Kk8sk.js +0 -1
  76. package/web-dist/assets/dax-CEL-wOlO.js +0 -1
  77. package/web-dist/assets/desktop-BmXAJ9_W.js +0 -1
  78. package/web-dist/assets/docker-BcOcwvcX.js +0 -1
  79. package/web-dist/assets/dotenv-Da5cRb03.js +0 -1
  80. package/web-dist/assets/dracula-BzJJZx-M.js +0 -1
  81. package/web-dist/assets/dracula-soft-BXkSAIEj.js +0 -1
  82. package/web-dist/assets/dream-maker-BtqSS_iP.js +0 -1
  83. package/web-dist/assets/edge-FbVlp4U3.js +0 -1
  84. package/web-dist/assets/elixir-CkH2-t6x.js +0 -1
  85. package/web-dist/assets/elm-DbKCFpqz.js +0 -1
  86. package/web-dist/assets/emacs-lisp-CXvaQtF9.js +0 -1
  87. package/web-dist/assets/erb-Dm6A9KJ5.js +0 -1
  88. package/web-dist/assets/erlang-DsQrWhSR.js +0 -1
  89. package/web-dist/assets/everforest-dark-BgDCqdQA.js +0 -1
  90. package/web-dist/assets/everforest-light-C8M2exoo.js +0 -1
  91. package/web-dist/assets/fennel-BYunw83y.js +0 -1
  92. package/web-dist/assets/fish-BvzEVeQv.js +0 -1
  93. package/web-dist/assets/fluent-C4IJs8-o.js +0 -1
  94. package/web-dist/assets/fortran-fixed-form-CkoXwp7k.js +0 -1
  95. package/web-dist/assets/fortran-free-form-BxgE0vQu.js +0 -1
  96. package/web-dist/assets/fsharp-CXgrBDvD.js +0 -1
  97. package/web-dist/assets/gdresource-BOOCDP_w.js +0 -1
  98. package/web-dist/assets/gdscript-C5YyOfLZ.js +0 -1
  99. package/web-dist/assets/gdshader-DkwncUOv.js +0 -1
  100. package/web-dist/assets/genie-D0YGMca9.js +0 -1
  101. package/web-dist/assets/gherkin-DyxjwDmM.js +0 -1
  102. package/web-dist/assets/git-commit-F4YmCXRG.js +0 -1
  103. package/web-dist/assets/git-rebase-r7XF79zn.js +0 -1
  104. package/web-dist/assets/github-dark-default-Cuk6v7N8.js +0 -1
  105. package/web-dist/assets/github-dark-dimmed-DH5Ifo-i.js +0 -1
  106. package/web-dist/assets/github-dark-high-contrast-E3gJ1_iC.js +0 -1
  107. package/web-dist/assets/github-light-default-D7oLnXFd.js +0 -1
  108. package/web-dist/assets/github-light-high-contrast-BfjtVDDH.js +0 -1
  109. package/web-dist/assets/gleam-BspZqrRM.js +0 -1
  110. package/web-dist/assets/glimmer-js-ByusRIyA.js +0 -1
  111. package/web-dist/assets/glimmer-ts-BfAWNZQY.js +0 -1
  112. package/web-dist/assets/glsl-DplSGwfg.js +0 -1
  113. package/web-dist/assets/gn-n2N0HUVH.js +0 -1
  114. package/web-dist/assets/gnuplot-DdkO51Og.js +0 -1
  115. package/web-dist/assets/graphql-ChdNCCLP.js +0 -1
  116. package/web-dist/assets/groovy-gcz8RCvz.js +0 -1
  117. package/web-dist/assets/gruvbox-dark-hard-CFHQjOhq.js +0 -1
  118. package/web-dist/assets/gruvbox-dark-medium-GsRaNv29.js +0 -1
  119. package/web-dist/assets/gruvbox-dark-soft-CVdnzihN.js +0 -1
  120. package/web-dist/assets/gruvbox-light-hard-CH1njM8p.js +0 -1
  121. package/web-dist/assets/gruvbox-light-medium-DRw_LuNl.js +0 -1
  122. package/web-dist/assets/gruvbox-light-soft-hJgmCMqR.js +0 -1
  123. package/web-dist/assets/hack-DbPARsA_.js +0 -1
  124. package/web-dist/assets/haml-D5jkg6IW.js +0 -1
  125. package/web-dist/assets/handlebars-BpdQsYii.js +0 -1
  126. package/web-dist/assets/haskell-Df6bDoY_.js +0 -1
  127. package/web-dist/assets/haxe-CzTSHFRz.js +0 -1
  128. package/web-dist/assets/hcl-BWvSN4gD.js +0 -1
  129. package/web-dist/assets/hjson-D5-asLiD.js +0 -1
  130. package/web-dist/assets/hlsl-D3lLCCz7.js +0 -1
  131. package/web-dist/assets/horizon-BUw7H-hv.js +0 -1
  132. package/web-dist/assets/horizon-bright-CUuTKBJd.js +0 -1
  133. package/web-dist/assets/houston-DnULxvSX.js +0 -1
  134. package/web-dist/assets/html-derivative-DlHx6ybY.js +0 -1
  135. package/web-dist/assets/http-jrhK8wxY.js +0 -1
  136. package/web-dist/assets/hurl-irOxFIW8.js +0 -1
  137. package/web-dist/assets/hxml-Bvhsp5Yf.js +0 -1
  138. package/web-dist/assets/hy-DFXneXwc.js +0 -1
  139. package/web-dist/assets/imba-DGztddWO.js +0 -1
  140. package/web-dist/assets/index-B3puu-Hr.js +0 -153
  141. package/web-dist/assets/index-CaDuyrN0.css +0 -1
  142. package/web-dist/assets/index-rgHg3m6g.js +0 -181
  143. package/web-dist/assets/jinja-f2NsQr07.js +0 -1
  144. package/web-dist/assets/jison-wvAkD_A8.js +0 -1
  145. package/web-dist/assets/json5-C9tS-k6U.js +0 -1
  146. package/web-dist/assets/jsonc-Des-eS-w.js +0 -1
  147. package/web-dist/assets/jsonl-DcaNXYhu.js +0 -1
  148. package/web-dist/assets/jsonnet-DFQXde-d.js +0 -1
  149. package/web-dist/assets/jssm-C2t-YnRu.js +0 -1
  150. package/web-dist/assets/julia-D7OTSIA_.js +0 -1
  151. package/web-dist/assets/just-CUsbIsdP.js +0 -1
  152. package/web-dist/assets/kanagawa-dragon-CkXjmgJE.js +0 -1
  153. package/web-dist/assets/kanagawa-lotus-CfQXZHmo.js +0 -1
  154. package/web-dist/assets/kanagawa-wave-DWedfzmr.js +0 -1
  155. package/web-dist/assets/kdl-DV7GczEv.js +0 -1
  156. package/web-dist/assets/kotlin-BdnUsdx6.js +0 -1
  157. package/web-dist/assets/kusto-wEQ09or8.js +0 -1
  158. package/web-dist/assets/laserwave-DUszq2jm.js +0 -1
  159. package/web-dist/assets/latex-CaSxy8MP.js +0 -1
  160. package/web-dist/assets/lean-BZvkOJ9d.js +0 -1
  161. package/web-dist/assets/less-B1dDrJ26.js +0 -1
  162. package/web-dist/assets/light-plus-B7mTdjB0.js +0 -1
  163. package/web-dist/assets/liquid-C0sCDyMI.js +0 -1
  164. package/web-dist/assets/llvm-DjAJT7YJ.js +0 -1
  165. package/web-dist/assets/logo-BtOb2qkB.js +0 -1
  166. package/web-dist/assets/lua-BaeVxFsk.js +0 -1
  167. package/web-dist/assets/luau-KW6xsasC.js +0 -1
  168. package/web-dist/assets/make-CHLpvVh8.js +0 -1
  169. package/web-dist/assets/marko-DjSrsDqO.js +0 -1
  170. package/web-dist/assets/material-theme-D5KoaKCx.js +0 -1
  171. package/web-dist/assets/material-theme-darker-BfHTSMKl.js +0 -1
  172. package/web-dist/assets/material-theme-lighter-B0m2ddpp.js +0 -1
  173. package/web-dist/assets/material-theme-ocean-CyktbL80.js +0 -1
  174. package/web-dist/assets/material-theme-palenight-Csfq5Kiy.js +0 -1
  175. package/web-dist/assets/matlab-D7o27uSR.js +0 -1
  176. package/web-dist/assets/mdc-DTYItulj.js +0 -1
  177. package/web-dist/assets/mdx-Cmh6b_Ma.js +0 -1
  178. package/web-dist/assets/mermaid-mWjccvbQ.js +0 -1
  179. package/web-dist/assets/min-dark-CafNBF8u.js +0 -1
  180. package/web-dist/assets/min-light-CTRr51gU.js +0 -1
  181. package/web-dist/assets/mipsasm-CKIfxQSi.js +0 -1
  182. package/web-dist/assets/mojo-rZm6bMo-.js +0 -1
  183. package/web-dist/assets/monokai-D4h5O-jR.js +0 -1
  184. package/web-dist/assets/moonbit-_H4v1dQx.js +0 -1
  185. package/web-dist/assets/move-IF9eRakj.js +0 -1
  186. package/web-dist/assets/narrat-DRg8JJMk.js +0 -1
  187. package/web-dist/assets/nextflow-C-mBbutL.js +0 -1
  188. package/web-dist/assets/nextflow-groovy-vE_lwT2v.js +0 -1
  189. package/web-dist/assets/nginx-BpAMiNFr.js +0 -1
  190. package/web-dist/assets/night-owl-C39BiMTA.js +0 -1
  191. package/web-dist/assets/night-owl-light-CMTm3GFP.js +0 -1
  192. package/web-dist/assets/nim-BIad80T-.js +0 -1
  193. package/web-dist/assets/nix-CwoSXNpI.js +0 -1
  194. package/web-dist/assets/nord-Ddv68eIx.js +0 -1
  195. package/web-dist/assets/nushell-Cz2AlsmD.js +0 -1
  196. package/web-dist/assets/objective-c-DXmwc3jG.js +0 -1
  197. package/web-dist/assets/objective-cpp-CLxacb5B.js +0 -1
  198. package/web-dist/assets/ocaml-C0hk2d4L.js +0 -1
  199. package/web-dist/assets/odin-BBf5iR-q.js +0 -1
  200. package/web-dist/assets/one-dark-pro-DVMEJ2y_.js +0 -1
  201. package/web-dist/assets/one-light-C3Wv6jpd.js +0 -1
  202. package/web-dist/assets/openscad-C4EeE6gA.js +0 -1
  203. package/web-dist/assets/pascal-D93ZcfNL.js +0 -1
  204. package/web-dist/assets/perl-B9cMNwum.js +0 -1
  205. package/web-dist/assets/pkl-u5AG7uiY.js +0 -1
  206. package/web-dist/assets/plastic-3e1v2bzS.js +0 -1
  207. package/web-dist/assets/plsql-ChMvpjG-.js +0 -1
  208. package/web-dist/assets/po-BTJTHyun.js +0 -1
  209. package/web-dist/assets/poimandres-CS3Unz2-.js +0 -1
  210. package/web-dist/assets/polar-C0HS_06l.js +0 -1
  211. package/web-dist/assets/postcss-CXtECtnM.js +0 -1
  212. package/web-dist/assets/powerquery-CEu0bR-o.js +0 -1
  213. package/web-dist/assets/powershell-Dpen1YoG.js +0 -1
  214. package/web-dist/assets/prisma-Dd19v3D-.js +0 -1
  215. package/web-dist/assets/prolog-CbFg5uaA.js +0 -1
  216. package/web-dist/assets/proto-C7zT0LnQ.js +0 -1
  217. package/web-dist/assets/pug-DKIMFp6K.js +0 -1
  218. package/web-dist/assets/puppet-BMWR74SV.js +0 -1
  219. package/web-dist/assets/purescript-CklMAg4u.js +0 -1
  220. package/web-dist/assets/qml-3beO22l8.js +0 -1
  221. package/web-dist/assets/qmldir-C8lEn-DE.js +0 -1
  222. package/web-dist/assets/qss-IeuSbFQv.js +0 -1
  223. package/web-dist/assets/r-Dspwwk_N.js +0 -1
  224. package/web-dist/assets/racket-BqYA7rlc.js +0 -1
  225. package/web-dist/assets/raku-DXvB9xmW.js +0 -1
  226. package/web-dist/assets/razor-BjBPvh-w.js +0 -1
  227. package/web-dist/assets/red-bN70gL4F.js +0 -1
  228. package/web-dist/assets/reg-C-SQnVFl.js +0 -1
  229. package/web-dist/assets/regexp-CDVJQ6XC.js +0 -1
  230. package/web-dist/assets/rel-C3B-1QV4.js +0 -1
  231. package/web-dist/assets/riscv-BM1_JUlF.js +0 -1
  232. package/web-dist/assets/ron-D8l8udqQ.js +0 -1
  233. package/web-dist/assets/rose-pine-dawn-DHQR4-dF.js +0 -1
  234. package/web-dist/assets/rose-pine-moon-D4_iv3hh.js +0 -1
  235. package/web-dist/assets/rose-pine-qdsjHGoJ.js +0 -1
  236. package/web-dist/assets/rosmsg-BJDFO7_C.js +0 -1
  237. package/web-dist/assets/rst-CpCqk9r5.js +0 -1
  238. package/web-dist/assets/ruby-DyJCeAvU.js +0 -1
  239. package/web-dist/assets/sas-DEy46yEz.js +0 -1
  240. package/web-dist/assets/sass-Cj5Yp3dK.js +0 -1
  241. package/web-dist/assets/scala-C151Ov-r.js +0 -1
  242. package/web-dist/assets/scheme-C98Dy4si.js +0 -1
  243. package/web-dist/assets/scss-D5BDwBP9.js +0 -1
  244. package/web-dist/assets/sdbl-DVxCFoDh.js +0 -1
  245. package/web-dist/assets/shaderlab-Dg9Lc6iA.js +0 -1
  246. package/web-dist/assets/shellsession-BADoaaVG.js +0 -1
  247. package/web-dist/assets/slack-dark-BthQWCQV.js +0 -1
  248. package/web-dist/assets/slack-ochin-DqwNpetd.js +0 -1
  249. package/web-dist/assets/smalltalk-BERRCDM3.js +0 -1
  250. package/web-dist/assets/snazzy-light-Bw305WKR.js +0 -1
  251. package/web-dist/assets/solarized-dark-DXbdFlpD.js +0 -1
  252. package/web-dist/assets/solarized-light-L9t79GZl.js +0 -1
  253. package/web-dist/assets/solidity-rGO070M0.js +0 -1
  254. package/web-dist/assets/soy-8wufbnw4.js +0 -1
  255. package/web-dist/assets/sparql-rVzFXLq3.js +0 -1
  256. package/web-dist/assets/splunk-BtCnVYZw.js +0 -1
  257. package/web-dist/assets/ssh-config-_ykCGR6B.js +0 -1
  258. package/web-dist/assets/stata-DI20mbqo.js +0 -1
  259. package/web-dist/assets/stylus-BEDo0Tqx.js +0 -1
  260. package/web-dist/assets/surrealql-Bq5Q-fJD.js +0 -1
  261. package/web-dist/assets/svelte-Cy7k_4gC.js +0 -1
  262. package/web-dist/assets/swift-D82vCrfD.js +0 -1
  263. package/web-dist/assets/synthwave-84-CbfX1IO0.js +0 -1
  264. package/web-dist/assets/system-verilog-CnnmHF94.js +0 -1
  265. package/web-dist/assets/systemd-4A_iFExJ.js +0 -1
  266. package/web-dist/assets/talonscript-CkByrt1z.js +0 -1
  267. package/web-dist/assets/tasl-QIJgUcNo.js +0 -1
  268. package/web-dist/assets/tcl-dwOrl1Do.js +0 -1
  269. package/web-dist/assets/templ-DhtptRzy.js +0 -1
  270. package/web-dist/assets/terraform-BETggiCN.js +0 -1
  271. package/web-dist/assets/tex-idrVyKtj.js +0 -1
  272. package/web-dist/assets/tokyo-night-hegEt444.js +0 -1
  273. package/web-dist/assets/ts-tags-D351s5mN.js +0 -1
  274. package/web-dist/assets/tsv-B_m7g4N7.js +0 -1
  275. package/web-dist/assets/turtle-BsS91CYL.js +0 -1
  276. package/web-dist/assets/twig-CW1WmMYd.js +0 -1
  277. package/web-dist/assets/typespec-CAFt9gP4.js +0 -1
  278. package/web-dist/assets/typst-DHCkPAjA.js +0 -1
  279. package/web-dist/assets/v-BcVCzyr7.js +0 -1
  280. package/web-dist/assets/vala-CsfeWuGM.js +0 -1
  281. package/web-dist/assets/vb-D17OF-Vu.js +0 -1
  282. package/web-dist/assets/verilog-BQ8w6xss.js +0 -1
  283. package/web-dist/assets/vesper-DRje8inN.js +0 -1
  284. package/web-dist/assets/vhdl-CeAyd5Ju.js +0 -1
  285. package/web-dist/assets/viml-CJc9bBzg.js +0 -1
  286. package/web-dist/assets/vitesse-black-Bkuqu6BP.js +0 -1
  287. package/web-dist/assets/vitesse-dark-D0r3Knsf.js +0 -1
  288. package/web-dist/assets/vitesse-light-CVO1_9PV.js +0 -1
  289. package/web-dist/assets/vue-D2xRrEX4.js +0 -1
  290. package/web-dist/assets/vue-html-AaS7Mt5G.js +0 -1
  291. package/web-dist/assets/vue-vine-BoDAl6tE.js +0 -1
  292. package/web-dist/assets/vyper-CDx5xZoG.js +0 -1
  293. package/web-dist/assets/wasm-CG6Dc4jp.js +0 -1
  294. package/web-dist/assets/wasm-MzD3tlZU.js +0 -1
  295. package/web-dist/assets/wenyan-BV7otONQ.js +0 -1
  296. package/web-dist/assets/wgsl-Dx-B1_4e.js +0 -1
  297. package/web-dist/assets/wikitext-BhOHFoWU.js +0 -1
  298. package/web-dist/assets/wit-5i3qLPDT.js +0 -1
  299. package/web-dist/assets/wolfram-lXgVvXCa.js +0 -1
  300. package/web-dist/assets/xsl-CtQFsRM5.js +0 -1
  301. package/web-dist/assets/zenscript-DVFEvuxE.js +0 -1
  302. package/web-dist/assets/zig-VOosw3JB.js +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/db/database.ts","../src/db/schema.ts","../src/db/repos/auth-sessions.ts","../src/db/repos/users.ts","../src/auth/password.ts","../src/auth/service.ts","../src/http/errors.ts"],"sourcesContent":["/**\n * SQLite connection & initialization (node:sqlite DatabaseSync).\n *\n * Single process, single writer: a synchronous API is sufficient and avoids a connection\n * pool; WAL mode and foreign key constraints are enabled. Table-creation SQL runs on open\n * (idempotent), with no migration branches (product not yet released).\n */\nimport { mkdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { SCHEMA_SQL } from \"./schema.js\";\n\n// Fetch the runtime module via process.getBuiltinModule (node >=22.3): avoids static\n// resolution of `node:sqlite` by bundlers/vite (some tools' builtin lists don't yet\n// recognize this experimental module).\nconst sqlite = process.getBuiltinModule(\"node:sqlite\");\n\n/** Open (creating if necessary) the database: ensure the parent directory exists, set PRAGMAs, run table creation. */\nexport function openDatabase(dbPath: string): DatabaseSync {\n if (dbPath !== \":memory:\") {\n mkdirSync(path.dirname(dbPath), { recursive: true });\n }\n const db = new sqlite.DatabaseSync(dbPath);\n db.exec(\"PRAGMA journal_mode = WAL;\");\n db.exec(\"PRAGMA foreign_keys = ON;\");\n db.exec(SCHEMA_SQL);\n // Columns added to the schema after a web.db was formed: CREATE TABLE IF NOT EXISTS never\n // touches an existing table, so they are ALTERed in here. Keep the list in sync with\n // schema.ts; drop entries only in a release allowed to break existing web.db files.\n ensureColumn(db, \"sessions\", \"client\", \"TEXT\");\n ensureColumn(db, \"sessions\", \"has_trace\", \"INTEGER NOT NULL DEFAULT 0\");\n ensureColumn(db, \"sessions\", \"fork_count\", \"INTEGER NOT NULL DEFAULT 0\");\n ensureColumn(db, \"sessions\", \"thinking_level\", \"TEXT\");\n ensureColumn(db, \"auth_sessions\", \"via\", \"TEXT\");\n ensureColumn(db, \"trace_files\", \"page_stats\", \"TEXT\");\n // Superseded by idx_usage_session_ts (session_id, ts), which SCHEMA_SQL just created on\n // this database: the old index is a strict prefix of it, so every query it served is\n // served identically. Dropping is safe — an index is derived, never data.\n db.exec(\"DROP INDEX IF EXISTS idx_usage_session\");\n upgradeLastActiveAt(db);\n return db;\n}\n\n/**\n * One-time `sessions.last_active_at` upgrade, ALTER + backfill in a single transaction.\n *\n * The backfill runs **only in the open that actually adds the column** (SQLite's ALTER\n * TABLE ADD COLUMN is transactional, so a crash mid-upgrade rolls back to \"no column\" and\n * the next open redoes both halves — never a half-migrated table, and never a full\n * `sessions` scan on the millions of opens that follow). Legacy rows take the session's\n * most recent request timestamp — usage_records, covered by idx_usage_session_ts, the\n * closest persisted proxy for \"last Trace activity\" — else their own created_at.\n */\nfunction upgradeLastActiveAt(db: DatabaseSync): void {\n db.exec(\"BEGIN\");\n try {\n if (ensureColumn(db, \"sessions\", \"last_active_at\", \"TEXT\")) {\n db.exec(\n `UPDATE sessions SET last_active_at = COALESCE(\n (SELECT MAX(ts) FROM usage_records WHERE usage_records.session_id = sessions.session_id),\n created_at\n )`,\n );\n }\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw err;\n }\n}\n\n/**\n * Idempotent per-column upgrade for databases formed before the column existed.\n * Returns whether this call actually ALTERed the table (false = the column was already\n * there), so a caller can gate one-time backfill work on it.\n */\nfunction ensureColumn(db: DatabaseSync, table: string, column: string, ddl: string): boolean {\n const cols = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];\n if (cols.some((c) => c.name === column)) return false;\n db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${ddl}`);\n return true;\n}\n","/**\n * SQLite table-creation SQL.\n *\n * SQLite stores only indexes and aggregates: users / login sessions / Project authorization /\n * Agent & Session indexes / usage summaries / error records / UI preferences. Agent State,\n * Trace, and Workspace still follow the local directory-based storage rules.\n * Product not yet released: no migration branches — everything is CREATE IF NOT EXISTS, formed\n * once. The one exception: columns added to an existing table after release of a web.db are\n * ALTERed in by the idempotent per-column guard in database.ts (ensureColumn), since CREATE\n * TABLE IF NOT EXISTS never touches an existing table. A *reshaped* index follows the same\n * rule under a new name, with the superseded one dropped on open (idx_usage_session →\n * idx_usage_session_ts): CREATE INDEX IF NOT EXISTS never rebuilds an existing index either.\n */\n\nexport const SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS users (\n user_id TEXT PRIMARY KEY, -- semantic id doubles as login name: ^[a-z][a-z0-9_-]{1,31}$\n password_hash TEXT NOT NULL, -- scrypt$N$r$p$salt$hash(base64)\n is_admin INTEGER NOT NULL DEFAULT 0, -- 1 for the built-in admin (seeded at startup)\n password_is_initial INTEGER NOT NULL DEFAULT 0, -- 1=initial password (seeded/admin-set); cleared once the user changes it\n created_at TEXT NOT NULL\n);\nCREATE TABLE IF NOT EXISTS auth_sessions (\n token_hash TEXT PRIMARY KEY, -- sha256(token) hex; the cookie stores only the raw token\n user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,\n created_at TEXT NOT NULL,\n expires_at TEXT NOT NULL, -- 7-day sliding renewal (topped up when <6 days remain)\n via TEXT -- 'password' | 'desktop'; NULL = legacy row (password)\n);\nCREATE TABLE IF NOT EXISTS projects (\n project_id TEXT PRIMARY KEY, -- directory name doubles as id; display name lives in project_config.toml\n owner_user_id TEXT NOT NULL REFERENCES users(user_id),\n created_at TEXT NOT NULL\n);\nCREATE TABLE IF NOT EXISTS project_members ( -- member grants only; owners are not stored here\n project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,\n user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,\n created_at TEXT NOT NULL,\n PRIMARY KEY (project_id, user_id)\n);\nCREATE TABLE IF NOT EXISTS agents ( -- index only; name/description live in system_config.yaml\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n created_at TEXT NOT NULL,\n PRIMARY KEY (project_id, agent_id)\n);\nCREATE TABLE IF NOT EXISTS sessions (\n session_id TEXT PRIMARY KEY,\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n provider TEXT NOT NULL, -- provider group of the session model (paired with model_id as a model reference)\n model_id TEXT NOT NULL, -- upstream model id (sent to AgentHub as-is; never concatenate <provider>/<id>)\n workspace TEXT NOT NULL,\n approval_mode TEXT NOT NULL DEFAULT 'allow-all', -- allow-all|deny-all|read-only|always-ask\n thinking_level TEXT, -- level pinned for THIS session (none|low|medium|high|xhigh|max); NULL=not pinned, runs follow the Agent config\n title TEXT, -- auto-generated by the model after the first exchange; NULL=not yet (frontend shows \"New chat\")\n archived_at TEXT, -- archive time; NULL=not archived (shown by default; archived ones move under \"Archived\")\n client TEXT, -- creating client: 'web' (created via the Web App) | 'cli' (adopted from a CLI Trace); NULL = legacy row, treated as web\n has_trace INTEGER NOT NULL DEFAULT 0, -- cache: a Trace record exists (set at task start / adoption / subagent registration; lazily backfilled by list hydration)\n fork_count INTEGER NOT NULL DEFAULT 0, -- monotonically allocated child-fork number for this source Session; never decremented when a fork is deleted\n last_active_at TEXT, -- last activity this server drove for the session (ISO; stamped once when a run starts and once when it ends, initialized to created_at); monotonic, never moves backwards; NULL only before openDatabase's one-time backfill\n created_at TEXT NOT NULL\n); -- the schedule/subagent SOURCE is NOT stored: session_meta in the Trace is the single source of truth (see runtime/session-sources.ts); \"client\" is a different, DB-only axis (who created the row)\nCREATE INDEX IF NOT EXISTS idx_sessions_agent_created ON sessions(project_id, agent_id, created_at DESC);\nCREATE TABLE IF NOT EXISTS usage_records (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n ts TEXT NOT NULL,\n date TEXT NOT NULL, -- local date yyyy-mm-dd (aggregation key; same convention as Trace date directories)\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n session_id TEXT NOT NULL, -- top-level Session (child-session usage counts toward its main Session)\n origin_session_id TEXT, -- immediate source child Session (last of the origin chain); NULL=main session\n provider TEXT NOT NULL, -- provider group: paired with model_id as the attribution key; always GROUP BY provider, model_id\n model_id TEXT NOT NULL, -- upstream model id (paired with provider; same model_id across providers aggregates separately)\n cache_read INTEGER NOT NULL,\n cache_write INTEGER NOT NULL,\n output INTEGER NOT NULL,\n total INTEGER NOT NULL, -- from token_usage.request (one row per Request)\n status TEXT NOT NULL DEFAULT 'completed' -- request outcome: completed=success (with tokens); others=failure (0 tokens, for success rate)\n); -- cost is not stored: computed at query time from current pricing\nCREATE INDEX IF NOT EXISTS idx_usage_project_date ON usage_records(project_id, date);\nCREATE INDEX IF NOT EXISTS idx_usage_session_ts ON usage_records(session_id, ts); -- (session_id) alone was idx_usage_session (dropped on open): ts makes the last_active_at backfill's MAX(ts) a covering index scan instead of a random row lookup per usage record\nCREATE TABLE IF NOT EXISTS error_records ( -- server-side error capture (the Costs page's \"Errors\" tab)\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n ts TEXT NOT NULL,\n date TEXT NOT NULL, -- local date yyyy-mm-dd (same convention as usage_records)\n project_id TEXT, -- nullable: sign-in/registration and process-level errors have no Project context\n agent_id TEXT,\n session_id TEXT,\n source TEXT NOT NULL, -- http | session | usage | title | subagent | process | llm | environment | compaction | schedule\n kind TEXT NOT NULL, -- expected (HttpError, business 4xx) | unexpected (500/runtime)\n code TEXT NOT NULL, -- HttpError.code / internal / session_run_failed / ...\n status INTEGER, -- HTTP status code; NULL for non-HTTP sources\n message TEXT NOT NULL -- truncated to 500 chars (no stack stored: stacks go to logs only)\n);\nCREATE INDEX IF NOT EXISTS idx_error_project_date ON error_records(project_id, date);\nCREATE TABLE IF NOT EXISTS schedule_state ( -- schedule runtime state (files are declarative intent; the system never writes back)\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n name TEXT NOT NULL, -- file name (without .toml) doubles as the identifier\n creator_user_id TEXT, -- creator (recorded on API create; hand-edited file reconciliation falls back to the Project owner)\n start_at_ms INTEGER NOT NULL, -- defines identity: a start_at change counts as a new task instance, resetting fire state\n def_hash TEXT NOT NULL, -- file content fingerprint: any change clears the invalid flag (the file takes effect again after edits)\n last_slot_ms INTEGER, -- latest due slot already consumed (advances on fire or skip; no re-fire across restarts)\n last_fired_at TEXT, -- last actual fire time (for display)\n fired_once INTEGER NOT NULL DEFAULT 0, -- one-shot task has fired\n missed INTEGER NOT NULL DEFAULT 0, -- one-shot task was missed (flagged by startup/registration reconciliation; not backfilled)\n invalid_reason TEXT, -- invalidation reason (e.g. the bound Session was deleted); NULL=healthy\n PRIMARY KEY (project_id, agent_id, name)\n);\nCREATE TABLE IF NOT EXISTS goal_state ( -- goal-mode runtime state (GOAL.yaml on disk is the model-facing protocol; this row is what the UI reads)\n id INTEGER PRIMARY KEY AUTOINCREMENT, -- one row per goal run; a Session may run goals repeatedly, latest row wins for display\n session_id TEXT NOT NULL,\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n objective TEXT NOT NULL,\n status TEXT NOT NULL, -- active | complete | blocked | budget_limited | aborted (aborted is server-side only; on-disk status stays active)\n budget INTEGER NOT NULL, -- token budget; -1 = unlimited\n used INTEGER NOT NULL DEFAULT 0, -- uncached input + output, refreshed per round (mirrors the runner's accounting)\n rounds INTEGER NOT NULL DEFAULT 0,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_goal_session ON goal_state(session_id);\nCREATE TABLE IF NOT EXISTS ui_prefs (\n user_id TEXT PRIMARY KEY REFERENCES users(user_id) ON DELETE CASCADE,\n prefs_json TEXT NOT NULL -- {theme?, lastProjectId?, ...} free-form JSON\n);\nCREATE TABLE IF NOT EXISTS server_settings ( -- admin-level server-global settings (GET/PUT /api/admin/settings)\n key TEXT PRIMARY KEY, -- setting name, e.g. 'proxy_for_app'\n value TEXT NOT NULL -- JSON-encoded value; an absent row means the setting's built-in default\n);\nCREATE TABLE IF NOT EXISTS trace_files ( -- DERIVED CACHE of the on-disk Trace tree (services/trace-index.ts): the directories stay the single source of truth, every row is rebuildable from disk, and a row is never authority for absence — consumers reconcile + retry on a miss, so a stale index costs one extra scan, never a false 404\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n file_index INTEGER NOT NULL, -- shard index NNN of <session_id>_NNN.jsonl (name/path are reconstructed from the row, never stored: the data root may move)\n date TEXT NOT NULL, -- date directory name (local yyyy-mm-dd)\n size_bytes INTEGER NOT NULL, -- last observed size (listings stat-refresh the returned page and write back; an actively-appended shard may lag in between)\n page_stats TEXT, -- cached message-window scan state at this shard's END (services/message-window.ts ShardPrefixRecord JSON); immutable shards only, NULL = not yet computed, nulled whenever size_bytes changes\n PRIMARY KEY (project_id, agent_id, session_id, file_index)\n);\nCREATE INDEX IF NOT EXISTS idx_trace_files_agent_date ON trace_files(project_id, agent_id, date);\nCREATE INDEX IF NOT EXISTS idx_trace_files_session ON trace_files(session_id);\nCREATE TABLE IF NOT EXISTS trace_sessions ( -- per-session facts read ONCE at registration from the earliest shard's head (same derived-cache rules as trace_files; listing needs zero head-reads)\n session_id TEXT PRIMARY KEY,\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n source TEXT, -- session_meta origin: 'subagent' | 'schedule' | NULL = user-created (or head not yet readable)\n workspace TEXT NOT NULL DEFAULT '',\n title TEXT, -- first-prompt fallback title (sessions.title always wins when present)\n provider TEXT, -- model reference from session_meta (CLI adoption reads it from here; NULL = meta unreadable / legacy without provider)\n model_id TEXT,\n first_ts TEXT, -- first record's timestamp (adoption's createdAt fallback when the id embeds no time)\n meta_read INTEGER NOT NULL DEFAULT 0 -- 1 once the head parsed; 0 = facts unknown, retried by the next reconcile that touches the session\n);\nCREATE INDEX IF NOT EXISTS idx_trace_sessions_agent ON trace_sessions(project_id, agent_id);\n`;\n","/**\n * auth_sessions table repo (server-side sessions backing the HttpOnly cookie).\n *\n * Stores only the sha256(token) hex hash; the raw token appears only in the cookie.\n */\nimport type { DatabaseSync } from \"node:sqlite\";\n\nexport interface AuthSessionRow {\n tokenHash: string;\n userId: string;\n createdAt: string;\n expiresAt: string;\n /** How the session was established (\"password\" | \"desktop\"); null on rows formed before the column existed (treated as \"password\"). */\n via: string | null;\n}\n\nexport class AuthSessionsRepo {\n constructor(private readonly db: DatabaseSync) {}\n\n insert(row: AuthSessionRow): void {\n this.db\n .prepare(\n \"INSERT INTO auth_sessions (token_hash, user_id, created_at, expires_at, via) VALUES (?, ?, ?, ?, ?)\",\n )\n .run(row.tokenHash, row.userId, row.createdAt, row.expiresAt, row.via);\n }\n\n findByTokenHash(tokenHash: string): AuthSessionRow | null {\n const r = this.db.prepare(\"SELECT * FROM auth_sessions WHERE token_hash = ?\").get(tokenHash);\n if (!r) return null;\n return {\n tokenHash: r.token_hash as string,\n userId: r.user_id as string,\n createdAt: r.created_at as string,\n expiresAt: r.expires_at as string,\n via: (r.via as string | null) ?? null,\n };\n }\n\n /** Sliding renewal: update the expiration time. */\n touch(tokenHash: string, expiresAt: string): void {\n this.db\n .prepare(\"UPDATE auth_sessions SET expires_at = ? WHERE token_hash = ?\")\n .run(expiresAt, tokenHash);\n }\n\n delete(tokenHash: string): void {\n this.db.prepare(\"DELETE FROM auth_sessions WHERE token_hash = ?\").run(tokenHash);\n }\n\n /** Opportunistically clean up expired sessions (called during login/validation). */\n deleteExpired(nowIso: string): void {\n this.db.prepare(\"DELETE FROM auth_sessions WHERE expires_at < ?\").run(nowIso);\n }\n\n /** Clear all sessions for a user (forces re-login after an admin resets the password). */\n deleteByUser(userId: string): void {\n this.db.prepare(\"DELETE FROM auth_sessions WHERE user_id = ?\").run(userId);\n }\n}\n","/**\n * users table repo: pure SQL wrapper, no business rules.\n * user_id is the login name (a semantic id, specified at creation, immutable).\n */\nimport type { DatabaseSync } from \"node:sqlite\";\n\nexport interface UserRow {\n userId: string;\n passwordHash: string;\n isAdmin: boolean;\n /** Still using the initial password (seeded / set by an admin); cleared to 0 once the user changes it. */\n passwordIsInitial: boolean;\n createdAt: string;\n}\n\nfunction mapRow(r: Record<string, unknown>): UserRow {\n return {\n userId: r.user_id as string,\n passwordHash: r.password_hash as string,\n isAdmin: (r.is_admin as number) === 1,\n passwordIsInitial: (r.password_is_initial as number) === 1,\n createdAt: r.created_at as string,\n };\n}\n\nexport class UsersRepo {\n constructor(private readonly db: DatabaseSync) {}\n\n insert(row: UserRow): void {\n this.db\n .prepare(\n \"INSERT INTO users (user_id, password_hash, is_admin, password_is_initial, created_at) VALUES (?, ?, ?, ?, ?)\",\n )\n .run(\n row.userId,\n row.passwordHash,\n row.isAdmin ? 1 : 0,\n row.passwordIsInitial ? 1 : 0,\n row.createdAt,\n );\n }\n\n findById(userId: string): UserRow | null {\n const r = this.db.prepare(\"SELECT * FROM users WHERE user_id = ?\").get(userId);\n return r ? mapRow(r) : null;\n }\n\n /** All users (for the admin user backend), ordered by creation time ascending. */\n list(): UserRow[] {\n const rows = this.db.prepare(\"SELECT * FROM users ORDER BY created_at ASC, user_id ASC\").all();\n return rows.map(mapRow);\n }\n\n count(): number {\n const r = this.db.prepare(\"SELECT COUNT(*) AS n FROM users\").get();\n return (r?.n as number) ?? 0;\n }\n\n /** Update the password hash; isInitial marks whether the password was set by someone else (seed / admin). */\n updatePassword(userId: string, passwordHash: string, isInitial: boolean): void {\n this.db\n .prepare(\"UPDATE users SET password_hash = ?, password_is_initial = ? WHERE user_id = ?\")\n .run(passwordHash, isInitial ? 1 : 0, userId);\n }\n\n /** Used by admin user deletion and account-creation compensation paths (owned Projects must be cleaned up first). */\n delete(userId: string): void {\n this.db.prepare(\"DELETE FROM users WHERE user_id = ?\").run(userId);\n }\n}\n","/**\n * Password hashing (slow-hash storage).\n *\n * Uses node:crypto's scrypt (built-in, no extra dependency, meets the same\n * slow-hash requirement as bcrypt/argon2). Storage format:\n * `scrypt$N$r$p$<salt b64>$<hash b64>` — parameters are stored alongside the hash,\n * so old hashes remain verifiable after future parameter tuning; comparison uses\n * timingSafeEqual to guard against timing side-channels.\n */\nimport { randomBytes, scrypt, timingSafeEqual } from \"node:crypto\";\n\n/**\n * Work factor for new hashes. `hashPassword` takes it as a defaulted argument so the server's\n * own test suite can hash at a token cost: almost every case there seeds an admin, provisions\n * users and logs them in, and one derivation at this strength costs on the order of 100ms.\n * Nothing on the production path passes the argument, and no configuration reaches it —\n * `buildAppDeps`, which carries the test override, is not part of this package's exports.\n */\nexport const SCRYPT_COST = 16384;\nconst SCRYPT_R = 8;\nconst SCRYPT_P = 1;\nconst SALT_BYTES = 16;\nconst KEY_BYTES = 64;\n\nfunction scryptAsync(\n password: string,\n salt: Buffer,\n keyLen: number,\n n: number,\n r: number,\n p: number,\n): Promise<Buffer> {\n return new Promise((resolve, reject) => {\n scrypt(password, salt, keyLen, { N: n, r, p, maxmem: 128 * 1024 * 1024 }, (err, key) => {\n if (err) reject(err);\n else resolve(key);\n });\n });\n}\n\n/**\n * Generates a password hash in `scrypt$N$r$p$salt$hash` format. `cost` is scrypt's N and\n * is recorded in the hash, so `verifyPassword` re-derives at whatever cost produced the\n * stored string.\n */\nexport async function hashPassword(password: string, cost: number = SCRYPT_COST): Promise<string> {\n const salt = randomBytes(SALT_BYTES);\n const key = await scryptAsync(password, salt, KEY_BYTES, cost, SCRYPT_R, SCRYPT_P);\n return [\n \"scrypt\",\n String(cost),\n String(SCRYPT_R),\n String(SCRYPT_P),\n salt.toString(\"base64\"),\n key.toString(\"base64\"),\n ].join(\"$\");\n}\n\n/** Verifies a password; returns false if the stored string has an invalid format (never throws, so the login path can uniformly treat it as a credential error). */\nexport async function verifyPassword(password: string, stored: string): Promise<boolean> {\n const parts = stored.split(\"$\");\n if (parts.length !== 6 || parts[0] !== \"scrypt\") return false;\n const n = Number(parts[1]);\n const r = Number(parts[2]);\n const p = Number(parts[3]);\n if (!Number.isInteger(n) || !Number.isInteger(r) || !Number.isInteger(p)) return false;\n let salt: Buffer;\n let expected: Buffer;\n try {\n salt = Buffer.from(parts[4]!, \"base64\");\n expected = Buffer.from(parts[5]!, \"base64\");\n } catch {\n return false;\n }\n if (salt.length === 0 || expected.length === 0) return false;\n let actual: Buffer;\n try {\n actual = await scryptAsync(password, salt, expected.length, n, r, p);\n } catch {\n return false;\n }\n return actual.length === expected.length && timingSafeEqual(actual, expected);\n}\n","/**\n * Auth service: built-in admin seeding /\n * login / logout / password change / session validation.\n *\n * - No open registration: on startup, if there are no users at all, the built-in\n * admin `admin` is seeded with a random `penguin-<4 digits>` initial password\n * (printed once by the startup entrypoint; PENGUIN_SEED_ADMIN_PASSWORD injects\n * a fixed one for tests/e2e), and it adopts `default_project`; all other users\n * are created by an admin via the user backend (admin-service).\n * - An initial password (whether seeded or set by an admin) is flagged with\n * password_is_initial, which the frontend uses to prompt for a password change soon.\n * - Sessions: a 32-byte random token, with only its sha256 hash stored in the DB;\n * valid for 7 days, with sliding renewal once less than 6 days remain.\n */\nimport { createHash, randomBytes, randomInt } from \"node:crypto\";\nimport type { UserInfo } from \"../api/types.js\";\nimport { HttpError } from \"../http/errors.js\";\nimport type { AuthSessionsRepo } from \"../db/repos/auth-sessions.js\";\nimport type { UserRow, UsersRepo } from \"../db/repos/users.js\";\nimport { SCRYPT_COST, hashPassword, verifyPassword } from \"./password.js\";\n\nexport const MIN_PASSWORD_LENGTH = 8;\n\n/** Built-in admin user_id. */\nexport const ADMIN_USER_ID = \"admin\";\n\n/**\n * Login throttling (per userId): the seeded initial password is `penguin-<4 digits>` —\n * 10,000 combinations — so unthrottled guessing would enumerate it in minutes. After\n * LOGIN_FREE_ATTEMPTS consecutive failures, the next attempt is admitted only after an\n * exponentially growing delay from the last failure (1s, 2s, … capped at 60s; attempts\n * inside the window are 429 `too_many_attempts` and do not extend it). Beyond ~40\n * failures that is one guess per minute, so the 10k space stops being enumerable, while\n * a legitimate user who mistyped a few times never waits more than the cap. A successful\n * login clears the counter. Counters are process memory (a restart clears them —\n * restarting is slower than waiting out the cap) and are kept for nonexistent userIds\n * too, so throttling is not an account-existence oracle. Known limit: a concurrent burst\n * can slip in before its first failure is recorded; the steady-state backoff still\n * dominates the search space.\n */\nconst LOGIN_FREE_ATTEMPTS = 5;\nconst LOGIN_BACKOFF_START_MS = 1000;\nconst LOGIN_BACKOFF_CAP_MS = 60_000;\n/** Failure entries idle longer than this are swept (bounds the map; far above the cap). */\nconst LOGIN_FAILURE_IDLE_MS = 15 * 60_000;\n\n/**\n * Random initial password for the seeded admin: `penguin-<4 digits>` — brand-related and\n * easy to type, shown once in the server startup output (the README, docs and login-page\n * hint all describe this form).\n */\nexport function generateInitialAdminPassword(): string {\n return \"penguin-\" + String(randomInt(0, 10000)).padStart(4, \"0\");\n}\n\nfunction sha256Hex(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\n/**\n * How a session was established: \"password\" via the login form, \"desktop\" via the\n * desktop shell's one-shot token. Persisted per session so desktop-specific allowances\n * (password change without the old password) apply only to sessions the shell itself\n * opened. Legacy rows (NULL) read as \"password\".\n */\nexport type SessionVia = \"password\" | \"desktop\";\n\nexport function toUserInfo(row: UserRow): UserInfo {\n return {\n userId: row.userId,\n isAdmin: row.isAdmin,\n passwordIsInitial: row.passwordIsInitial,\n createdAt: row.createdAt,\n };\n}\n\nexport interface AuthServiceDeps {\n users: UsersRepo;\n authSessions: AuthSessionsRepo;\n /** Provisions the initial Project at signup (injected by project-service, to avoid a circular dependency). */\n provisionInitialProject: (user: UserRow, isAdmin: boolean) => Promise<void>;\n /** Fixed initial password for the seeded admin (config.seedAdminPassword); null generates a random one at seed time. */\n seedAdminPassword: string | null;\n /**\n * Fired after any successful password update (self change / desktop set). The server\n * wires it to drop the stored initial-password plaintext once it goes stale (see\n * initial-password.ts); standalone/test constructions may omit it.\n */\n onPasswordChanged?: (userId: string) => void;\n sessionTtlMs: number;\n sessionRenewMs: number;\n /**\n * Test double: scrypt work factor for hashes this service writes. Omitted in\n * production, where {@link SCRYPT_COST} applies.\n */\n passwordHashCost?: number;\n now?: () => Date;\n}\n\nexport class AuthService {\n private readonly now: () => Date;\n private readonly hashCost: number;\n\n constructor(private readonly deps: AuthServiceDeps) {\n this.now = deps.now ?? (() => new Date());\n this.hashCost = deps.passwordHashCost ?? SCRYPT_COST;\n }\n\n /**\n * Startup seeding (idempotent): creates the built-in admin and adopts\n * default_project when the users table is empty; if the initial Project fails,\n * the user row is rolled back and the server retries on next startup.\n * Returns the initial password when it actually seeded — the caller prints it,\n * the only place a generated password is ever shown — and null when users\n * already exist.\n */\n async seedAdmin(): Promise<string | null> {\n if (this.deps.users.count() > 0) return null;\n const password = this.deps.seedAdminPassword ?? generateInitialAdminPassword();\n // The override (PENGUIN_SEED_ADMIN_PASSWORD) must meet the same policy as every\n // other initial/reset password; rejecting it here, before any insert, keeps a\n // configuration typo from creating a trivially weak privileged account. Generated\n // passwords are always 12 characters and never trip this.\n if (password.length < MIN_PASSWORD_LENGTH) {\n throw new Error(\n `PENGUIN_SEED_ADMIN_PASSWORD must be at least ${MIN_PASSWORD_LENGTH} characters.`,\n );\n }\n const user: UserRow = {\n userId: ADMIN_USER_ID,\n passwordHash: await hashPassword(password, this.hashCost),\n isAdmin: true,\n passwordIsInitial: true,\n createdAt: this.now().toISOString(),\n };\n this.deps.users.insert(user);\n try {\n await this.deps.provisionInitialProject(user, true);\n } catch (err) {\n this.deps.users.delete(user.userId);\n throw err;\n }\n return password;\n }\n\n /** Whether the built-in admin still runs on its initial password (drives the startup reminder notice). */\n adminPasswordIsInitial(): boolean {\n return this.deps.users.findById(ADMIN_USER_ID)?.passwordIsInitial === true;\n }\n\n /** Consecutive login failures per userId (see the throttling comment on the constants). */\n private readonly loginFailures = new Map<string, { failures: number; lastFailureAt: number }>();\n\n /** The wait imposed after `failures` consecutive failures (0 while within the free attempts). */\n private loginDelayMs(failures: number): number {\n const excess = failures - LOGIN_FREE_ATTEMPTS;\n if (excess <= 0) return 0;\n return Math.min(LOGIN_BACKOFF_START_MS * 2 ** (excess - 1), LOGIN_BACKOFF_CAP_MS);\n }\n\n async login(userId: string, password: string): Promise<{ user: UserInfo; token: string }> {\n const nowMs = this.now().getTime();\n for (const [key, entry] of this.loginFailures) {\n if (nowMs - entry.lastFailureAt > LOGIN_FAILURE_IDLE_MS) this.loginFailures.delete(key);\n }\n const failed = this.loginFailures.get(userId);\n if (failed) {\n const readyAt = failed.lastFailureAt + this.loginDelayMs(failed.failures);\n if (nowMs < readyAt) {\n throw new HttpError(\n 429,\n \"too_many_attempts\",\n `Too many failed sign-in attempts. Try again in ${Math.ceil((readyAt - nowMs) / 1000)}s.`,\n );\n }\n }\n const row = this.deps.users.findById(userId);\n const ok = row !== null && (await verifyPassword(password, row.passwordHash));\n if (!row || !ok) {\n this.loginFailures.set(userId, {\n failures: (failed?.failures ?? 0) + 1,\n lastFailureAt: this.now().getTime(),\n });\n throw new HttpError(401, \"invalid_credentials\", \"Incorrect username or password.\");\n }\n this.loginFailures.delete(userId);\n this.deps.authSessions.deleteExpired(this.now().toISOString());\n return { user: toUserInfo(row), token: this.issueSession(row.userId, \"password\") };\n }\n\n /**\n * Desktop-mode sign-in: issues an admin session WITHOUT a password check — the caller\n * (the desktop-login route) has already redeemed the shell's one-shot token, which is\n * the credential here. Throws if the admin has not been seeded yet (desktop-login runs\n * after startup seeding, so this only trips on a broken deployment).\n */\n loginDesktop(): { user: UserInfo; token: string } {\n const row = this.deps.users.findById(ADMIN_USER_ID);\n if (!row) {\n throw new HttpError(500, \"internal\", \"Built-in admin has not been seeded.\");\n }\n this.deps.authSessions.deleteExpired(this.now().toISOString());\n return { user: toUserInfo(row), token: this.issueSession(row.userId, \"desktop\") };\n }\n\n /** Self password change (user settings): validates the old password, and on success clears the initial-password flag; the current session remains valid. */\n async changePassword(userId: string, oldPassword: string, newPassword: string): Promise<void> {\n const row = this.deps.users.findById(userId);\n if (!row || !(await verifyPassword(oldPassword, row.passwordHash))) {\n throw new HttpError(400, \"password_mismatch\", \"Current password is incorrect.\");\n }\n if (newPassword.length < MIN_PASSWORD_LENGTH) {\n throw new HttpError(400, \"invalid_password\", \"Password must be at least 8 characters.\");\n }\n this.deps.users.updatePassword(userId, await hashPassword(newPassword, this.hashCost), false);\n this.deps.onPasswordChanged?.(userId);\n }\n\n /**\n * Desktop-session password set: no old-password check. Only reachable for sessions\n * established via desktop-login (the me route gates on sessionVia) — the seed password\n * of a desktop-created root is random and never shown, so its holder has nothing to\n * type into an old-password field; the shell's token already proved machine ownership.\n */\n async setPasswordDesktop(userId: string, newPassword: string): Promise<void> {\n if (newPassword.length < MIN_PASSWORD_LENGTH) {\n throw new HttpError(400, \"invalid_password\", \"Password must be at least 8 characters.\");\n }\n this.deps.users.updatePassword(userId, await hashPassword(newPassword, this.hashCost), false);\n this.deps.onPasswordChanged?.(userId);\n }\n\n logout(token: string): void {\n this.deps.authSessions.delete(sha256Hex(token));\n }\n\n /** Validates the cookie token: returns null if expired/unknown; sliding renewal once less than 6 days remain. */\n authenticateWithMeta(token: string): { user: UserRow; via: SessionVia } | null {\n const tokenHash = sha256Hex(token);\n const session = this.deps.authSessions.findByTokenHash(tokenHash);\n if (!session) return null;\n const now = this.now();\n const expiresAt = Date.parse(session.expiresAt);\n if (!(expiresAt > now.getTime())) {\n this.deps.authSessions.delete(tokenHash);\n return null;\n }\n if (expiresAt - now.getTime() < this.deps.sessionRenewMs) {\n this.deps.authSessions.touch(\n tokenHash,\n new Date(now.getTime() + this.deps.sessionTtlMs).toISOString(),\n );\n }\n const user = this.deps.users.findById(session.userId);\n if (!user) return null;\n return { user, via: session.via === \"desktop\" ? \"desktop\" : \"password\" };\n }\n\n private issueSession(userId: string, via: SessionVia): string {\n const token = randomBytes(32).toString(\"base64url\");\n const now = this.now();\n this.deps.authSessions.insert({\n tokenHash: sha256Hex(token),\n userId,\n createdAt: now.toISOString(),\n expiresAt: new Date(now.getTime() + this.deps.sessionTtlMs).toISOString(),\n via,\n });\n return token;\n }\n}\n","/**\n * Unified HTTP error: `{error: {code, message}}` response body,\n * with message in English.\n *\n * Routes and services express business errors via throw HttpError; app-level onError\n * uniformly converges these into a JSON response, with unknown errors converged to 500\n * (never leaking internal details to the client).\n */\nimport type { Context } from \"hono\";\nimport type { ErrorBody } from \"../api/types.js\";\n\nexport class HttpError extends Error {\n constructor(\n readonly status: number,\n readonly code: string,\n message: string,\n ) {\n super(message);\n this.name = \"HttpError\";\n }\n}\n\nexport function errorBody(code: string, message: string): ErrorBody {\n return { error: { code, message } };\n}\n\n/**\n * Model missing a credential: the provider SDK throws this at **client-construction\n * time** (hit by both creating a Session and resuming a Session); the original message\n * is full of environment variable names, meaningless to a user — uniformly replaced\n * with a single actionable sentence. The frontend produces localized text by code\n * (message is only a fallback); see web's lib/api-error.ts.\n */\nexport function isMissingCredential(err: unknown): boolean {\n const message = err instanceof Error ? err.message : String(err);\n return /missing credentials|api[_ ]?key/i.test(message);\n}\n\nexport function modelCredentialMissing(modelId: string): HttpError {\n return new HttpError(\n 400,\n \"model_credential_missing\",\n `Model ${modelId} has no API key yet. Configure it on the Models page first.`,\n );\n}\n\n/** app.onError handler: maps HttpError through as-is; everything else is logged and converged to 500. */\nexport function handleError(err: Error, c: Context): Response {\n if (err instanceof HttpError) {\n return c.json(errorBody(err.code, err.message), err.status as 400);\n }\n // Unknown error: print the stack for diagnosis, but never expose details externally.\n console.error(`[server] Unhandled exception: ${err.stack ?? err.message}`);\n return c.json(errorBody(\"internal\", \"Internal server error.\"), 500);\n}\n"],"mappings":";AAOA,SAAS,iBAAiB;AAC1B,OAAO,UAAU;;;ACMV,IAAM,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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K,aAAa;AAAA,QACrB;AAAA,QACA,IAAI,KAAK,IAAI,QAAQ,IAAI,KAAK,KAAK,YAAY,EAAE,YAAY;AAAA,MAC/D;AAAA,IACF;AACA,UAAM,OAAO,KAAK,KAAK,MAAM,SAAS,QAAQ,MAAM;AACpD,QAAI,CAAC,KAAM,QAAO;AAClB,WAAO,EAAE,MAAM,KAAK,QAAQ,QAAQ,YAAY,YAAY,WAAW;AAAA,EACzE;AAAA,EAEQ,aAAa,QAAgB,KAAyB;AAC5D,UAAM,QAAQC,aAAY,EAAE,EAAE,SAAS,WAAW;AAClD,UAAM,MAAM,KAAK,IAAI;AACrB,SAAK,KAAK,aAAa,OAAO;AAAA,MAC5B,WAAW,UAAU,KAAK;AAAA,MAC1B;AAAA,MACA,WAAW,IAAI,YAAY;AAAA,MAC3B,WAAW,IAAI,KAAK,IAAI,QAAQ,IAAI,KAAK,KAAK,YAAY,EAAE,YAAY;AAAA,MACxE;AAAA,IACF,CAAC;AACD,WAAO;AAAA,EACT;AACF;","names":["randomBytes","randomBytes"]}
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The committed on-disk record: a runtime restart resumes exactly this CODE (platform,
3
+ * cli, web). It carries no STATE — a restart always boots the resumed platform bundle
4
+ * against its own fresh initial context (bundle.context, see host.ts's PlatformBundle),
5
+ * never a document parked from a previous run (see host.ts's module doc for why: a
6
+ * parked doc's live-resource handles die with the process anyway, so resuming one could
7
+ * only ever produce handles that fail to reclaim). Paths are relative to hmrDir
8
+ * (`<root>/hmr`).
9
+ */
10
+ interface Manifest {
11
+ platform?: {
12
+ bundle: string;
13
+ };
14
+ /**
15
+ * The CLI's own bundle pointer — its own independent file (a different sha from
16
+ * `platform.bundle`; the two are separately compiled artifacts), kept as its own
17
+ * field so a reader that only wants "which bundle does the CLI load right now"
18
+ * never has to reach into `platform` at all.
19
+ */
20
+ cli?: {
21
+ bundle: string;
22
+ };
23
+ /** One gzip(JSON.stringify({ files })) artifact, restored straight into memory. */
24
+ web?: {
25
+ manifest: string;
26
+ };
27
+ /**
28
+ * Files the pushed platform needs as REAL files on disk, unpacked under this directory
29
+ * (relative to hmrDir). The web artifact stays in memory because it is only ever served
30
+ * as bytes; an asset is something the platform hands to the OS — a native `.node` the
31
+ * loader must resolve by path, a helper binary it execs — so it has to exist on the
32
+ * filesystem, with its exec bit intact.
33
+ */
34
+ assets?: {
35
+ dir: string;
36
+ };
37
+ }
38
+ /** Reads and parses `<root>/hmr/harness.json`; null when missing or corrupt (nothing committed yet). */
39
+ declare function readManifest(root: string): Promise<Manifest | null>;
40
+ /**
41
+ * Resolves the current CLI bundle's absolute path from a data root, or null when
42
+ * nothing has been pushed yet: a fresh root, a missing/corrupt manifest, no `cli`
43
+ * entry, a `cli.bundle` that isn't a non-empty string (e.g. `{"cli":{}}` — a
44
+ * hand-edited or truncated harness.json), a path that resolves outside `<root>/hmr/`
45
+ * (defense in depth: `manifest.cli.bundle` is trusted content today, written only by
46
+ * this same process's persistVersion, but a reader must never let a malformed or
47
+ * malicious manifest value walk it out of the store directory via `..` segments), or
48
+ * a referenced file that no longer exists (e.g. pruned from the store — see host.ts's
49
+ * pruneStore). A null return means "use the packaged default" to every caller;
50
+ * nothing here ever throws for an ordinary unconfigured or malformed root.
51
+ */
52
+ declare function resolveCliBundlePath(root: string): Promise<string | null>;
53
+
54
+ export { type Manifest, readManifest, resolveCliBundlePath };
@@ -0,0 +1,27 @@
1
+ // src/hmr/manifest.ts
2
+ import fs from "fs";
3
+ import fsp from "fs/promises";
4
+ import path from "path";
5
+ async function readManifest(root) {
6
+ try {
7
+ const raw = await fsp.readFile(path.join(root, "hmr", "harness.json"), "utf8");
8
+ return JSON.parse(raw);
9
+ } catch {
10
+ return null;
11
+ }
12
+ }
13
+ async function resolveCliBundlePath(root) {
14
+ const manifest = await readManifest(root);
15
+ const bundle = manifest?.cli?.bundle;
16
+ if (typeof bundle !== "string" || bundle.length === 0) return null;
17
+ const hmrDir = path.join(root, "hmr");
18
+ const abs = path.resolve(hmrDir, bundle);
19
+ const withinHmrDir = abs === hmrDir || abs.startsWith(hmrDir + path.sep);
20
+ if (!withinHmrDir) return null;
21
+ return fs.existsSync(abs) ? abs : null;
22
+ }
23
+ export {
24
+ readManifest,
25
+ resolveCliBundlePath
26
+ };
27
+ //# sourceMappingURL=manifest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/hmr/manifest.ts"],"sourcesContent":["/**\n * The harness.json shape (`<root>/hmr/harness.json`) and pure readers over it.\n *\n * Split out of host.ts so a reader never needs a running HmrHost: `penguin` is a\n * separate, short-lived process per invocation (see packages/cli/src/index.ts) — it\n * has no host instance to ask, only the data root's own harness.json on disk.\n * `resolveCliBundlePath` is that reader: a plain disk read, no HTTP, no boot, no\n * in-memory state.\n *\n * ONE atomic version, THREE independent artifacts: `platform`, `cli`, and `web` are\n * always written together by HmrHost's single merged upgrade path (see host.ts's\n * persistVersion), but each is content-addressed and stored on its own — a push to\n * POST /api/hmr/upgrade carries `platform` and `cli` as two separate single-file ESM\n * sources, so `cli.bundle` points at its OWN file, a different sha from\n * `platform.bundle`. They are read back together too (see host.ts's restore): a\n * partial record (e.g. `platform` present but `web` or `cli` missing) is never\n * trusted — the whole version is treated as absent instead of partially applied.\n */\nimport fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/**\n * The committed on-disk record: a runtime restart resumes exactly this CODE (platform,\n * cli, web). It carries no STATE — a restart always boots the resumed platform bundle\n * against its own fresh initial context (bundle.context, see host.ts's PlatformBundle),\n * never a document parked from a previous run (see host.ts's module doc for why: a\n * parked doc's live-resource handles die with the process anyway, so resuming one could\n * only ever produce handles that fail to reclaim). Paths are relative to hmrDir\n * (`<root>/hmr`).\n */\nexport interface Manifest {\n platform?: { bundle: string };\n /**\n * The CLI's own bundle pointer — its own independent file (a different sha from\n * `platform.bundle`; the two are separately compiled artifacts), kept as its own\n * field so a reader that only wants \"which bundle does the CLI load right now\"\n * never has to reach into `platform` at all.\n */\n cli?: { bundle: string };\n /** One gzip(JSON.stringify({ files })) artifact, restored straight into memory. */\n web?: { manifest: string };\n /**\n * Files the pushed platform needs as REAL files on disk, unpacked under this directory\n * (relative to hmrDir). The web artifact stays in memory because it is only ever served\n * as bytes; an asset is something the platform hands to the OS — a native `.node` the\n * loader must resolve by path, a helper binary it execs — so it has to exist on the\n * filesystem, with its exec bit intact.\n */\n assets?: { dir: string };\n}\n\n/** Reads and parses `<root>/hmr/harness.json`; null when missing or corrupt (nothing committed yet). */\nexport async function readManifest(root: string): Promise<Manifest | null> {\n try {\n const raw = await fsp.readFile(path.join(root, \"hmr\", \"harness.json\"), \"utf8\");\n return JSON.parse(raw) as Manifest;\n } catch {\n return null;\n }\n}\n\n/**\n * Resolves the current CLI bundle's absolute path from a data root, or null when\n * nothing has been pushed yet: a fresh root, a missing/corrupt manifest, no `cli`\n * entry, a `cli.bundle` that isn't a non-empty string (e.g. `{\"cli\":{}}` — a\n * hand-edited or truncated harness.json), a path that resolves outside `<root>/hmr/`\n * (defense in depth: `manifest.cli.bundle` is trusted content today, written only by\n * this same process's persistVersion, but a reader must never let a malformed or\n * malicious manifest value walk it out of the store directory via `..` segments), or\n * a referenced file that no longer exists (e.g. pruned from the store — see host.ts's\n * pruneStore). A null return means \"use the packaged default\" to every caller;\n * nothing here ever throws for an ordinary unconfigured or malformed root.\n */\nexport async function resolveCliBundlePath(root: string): Promise<string | null> {\n const manifest = await readManifest(root);\n const bundle = manifest?.cli?.bundle;\n if (typeof bundle !== \"string\" || bundle.length === 0) return null;\n const hmrDir = path.join(root, \"hmr\");\n const abs = path.resolve(hmrDir, bundle);\n const withinHmrDir = abs === hmrDir || abs.startsWith(hmrDir + path.sep);\n if (!withinHmrDir) return null;\n return fs.existsSync(abs) ? abs : null;\n}\n"],"mappings":";AAkBA,OAAO,QAAQ;AACf,OAAO,SAAS;AAChB,OAAO,UAAU;AAiCjB,eAAsB,aAAa,MAAwC;AACzE,MAAI;AACF,UAAM,MAAM,MAAM,IAAI,SAAS,KAAK,KAAK,MAAM,OAAO,cAAc,GAAG,MAAM;AAC7E,WAAO,KAAK,MAAM,GAAG;AAAA,EACvB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAcA,eAAsB,qBAAqB,MAAsC;AAC/E,QAAM,WAAW,MAAM,aAAa,IAAI;AACxC,QAAM,SAAS,UAAU,KAAK;AAC9B,MAAI,OAAO,WAAW,YAAY,OAAO,WAAW,EAAG,QAAO;AAC9D,QAAM,SAAS,KAAK,KAAK,MAAM,KAAK;AACpC,QAAM,MAAM,KAAK,QAAQ,QAAQ,MAAM;AACvC,QAAM,eAAe,QAAQ,UAAU,IAAI,WAAW,SAAS,KAAK,GAAG;AACvE,MAAI,CAAC,aAAc,QAAO;AAC1B,SAAO,GAAG,WAAW,GAAG,IAAI,MAAM;AACpC;","names":[]}