texlite 0.24.0 → 0.25.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 (241) hide show
  1. package/DESIGN.md +85 -2
  2. package/NPM_TESTING.md +46 -2
  3. package/OPERATIONS.md +136 -6
  4. package/README.md +1 -2
  5. package/README.zh-CN.md +2 -2
  6. package/THIRD_PARTY_NOTICES.md +12 -0
  7. package/dist/client/assets/AdminUsers-D4ljqr_D.js +1 -0
  8. package/dist/client/assets/AdminUsers-D4ljqr_D.js.br +0 -0
  9. package/dist/client/assets/AdminUsers-D4ljqr_D.js.gz +0 -0
  10. package/dist/client/assets/AgentManagement-DwRMP_nD.js +1 -0
  11. package/dist/client/assets/AgentManagement-DwRMP_nD.js.br +0 -0
  12. package/dist/client/assets/AgentManagement-DwRMP_nD.js.gz +0 -0
  13. package/dist/client/assets/AgentTerminal-CSsr21PC.js +2 -0
  14. package/dist/client/assets/AgentTerminal-CSsr21PC.js.br +0 -0
  15. package/dist/client/assets/AgentTerminal-CSsr21PC.js.gz +0 -0
  16. package/dist/client/assets/{AgentTerminalSurface-DliOcop5.js → AgentTerminalSurface-BLroKMGe.js} +1 -1
  17. package/dist/client/assets/{AgentTerminalSurface-DliOcop5.js.br → AgentTerminalSurface-BLroKMGe.js.br} +0 -0
  18. package/dist/client/assets/AgentTerminalSurface-BLroKMGe.js.gz +0 -0
  19. package/dist/client/assets/{AvatarSettingsDialog-iuEbMO4a.js → AvatarSettingsDialog-BgVGfSzn.js} +1 -1
  20. package/dist/client/assets/AvatarSettingsDialog-BgVGfSzn.js.br +0 -0
  21. package/dist/client/assets/AvatarSettingsDialog-BgVGfSzn.js.gz +0 -0
  22. package/dist/client/assets/CitationBibtexEditor-DLPom-qx.js +1 -0
  23. package/dist/client/assets/CitationLibraryDialog-Cn-kFi8E.js +3 -0
  24. package/dist/client/assets/CitationLibraryDialog-Cn-kFi8E.js.br +0 -0
  25. package/dist/client/assets/CitationLibraryDialog-Cn-kFi8E.js.gz +0 -0
  26. package/dist/client/assets/Dashboard-7JrR0t6C.js +5 -0
  27. package/dist/client/assets/Dashboard-7JrR0t6C.js.br +0 -0
  28. package/dist/client/assets/Dashboard-7JrR0t6C.js.gz +0 -0
  29. package/dist/client/assets/DrawioEditor-CYQnzKDd.js +1 -0
  30. package/dist/client/assets/DrawioEditor-CYQnzKDd.js.br +0 -0
  31. package/dist/client/assets/DrawioEditor-CYQnzKDd.js.gz +0 -0
  32. package/dist/client/assets/GitDialog-DMCVR8QK.js +4 -0
  33. package/dist/client/assets/GitDialog-DMCVR8QK.js.br +0 -0
  34. package/dist/client/assets/GitDialog-DMCVR8QK.js.gz +0 -0
  35. package/dist/client/assets/GitHubAccountDialog-BbJpR9Vq.js +1 -0
  36. package/dist/client/assets/GitHubAccountDialog-BbJpR9Vq.js.br +0 -0
  37. package/dist/client/assets/GitHubAccountDialog-BbJpR9Vq.js.gz +0 -0
  38. package/dist/client/assets/{HistoryDialog-upkR8E0L.js → HistoryDialog-CcPWpTLn.js} +3 -3
  39. package/dist/client/assets/HistoryDialog-CcPWpTLn.js.br +0 -0
  40. package/dist/client/assets/HistoryDialog-CcPWpTLn.js.gz +0 -0
  41. package/dist/client/assets/LatexEditor-D7C9jpJO.js +25 -0
  42. package/dist/client/assets/LatexEditor-D7C9jpJO.js.br +0 -0
  43. package/dist/client/assets/LatexEditor-D7C9jpJO.js.gz +0 -0
  44. package/dist/client/assets/{MarkdownPreview-_AXp5G7f.js → MarkdownPreview-Txs5upCY.js} +1 -1
  45. package/dist/client/assets/MarkdownPreview-Txs5upCY.js.br +0 -0
  46. package/dist/client/assets/MarkdownPreview-Txs5upCY.js.gz +0 -0
  47. package/dist/client/assets/{ProjectIconPickerDialog-BxjEYsau.js → ProjectIconPickerDialog-CUlPlfmL.js} +1 -1
  48. package/dist/client/assets/ProjectIconPickerDialog-CUlPlfmL.js.br +0 -0
  49. package/dist/client/assets/ProjectIconPickerDialog-CUlPlfmL.js.gz +0 -0
  50. package/dist/client/assets/ProjectSearchDialog-Bt6NyHIJ.js +1 -0
  51. package/dist/client/assets/ProjectSearchDialog-Bt6NyHIJ.js.br +0 -0
  52. package/dist/client/assets/ProjectSearchDialog-Bt6NyHIJ.js.gz +0 -0
  53. package/dist/client/assets/ProjectSettings-B6e7EAxq.js +4 -0
  54. package/dist/client/assets/ProjectSettings-B6e7EAxq.js.br +0 -0
  55. package/dist/client/assets/ProjectSettings-B6e7EAxq.js.gz +0 -0
  56. package/dist/client/assets/ProjectWorkspace-D0EMITec.js +25 -0
  57. package/dist/client/assets/ProjectWorkspace-D0EMITec.js.br +0 -0
  58. package/dist/client/assets/ProjectWorkspace-D0EMITec.js.gz +0 -0
  59. package/dist/client/assets/{QuickOpenDialog-HlkWqVR9.js → QuickOpenDialog-D6yjnquG.js} +1 -1
  60. package/dist/client/assets/QuickOpenDialog-D6yjnquG.js.br +0 -0
  61. package/dist/client/assets/QuickOpenDialog-D6yjnquG.js.gz +0 -0
  62. package/dist/client/assets/{ReadOnlySource-BIdN1YP_.js → ReadOnlySource-BOAnB5L0.js} +1 -1
  63. package/dist/client/assets/{SelectionHistoryDialog-Cb8I-G6m.js → SelectionHistoryDialog-D6ql9E0j.js} +2 -2
  64. package/dist/client/assets/SelectionHistoryDialog-D6ql9E0j.js.br +0 -0
  65. package/dist/client/assets/SelectionHistoryDialog-D6ql9E0j.js.gz +0 -0
  66. package/dist/client/assets/SharedProjectPage-DuscqDx5.js +2 -0
  67. package/dist/client/assets/SharedProjectPage-DuscqDx5.js.br +0 -0
  68. package/dist/client/assets/SharedProjectPage-DuscqDx5.js.gz +0 -0
  69. package/dist/client/assets/SystemMetricsDialog-KiKZOF2N.js +1 -0
  70. package/dist/client/assets/SystemMetricsDialog-KiKZOF2N.js.br +0 -0
  71. package/dist/client/assets/SystemMetricsDialog-KiKZOF2N.js.gz +0 -0
  72. package/dist/client/assets/TagManagementDialog-BHbqvu3K.js +1 -0
  73. package/dist/client/assets/TagManagementDialog-BHbqvu3K.js.br +0 -0
  74. package/dist/client/assets/TagManagementDialog-BHbqvu3K.js.gz +0 -0
  75. package/dist/client/assets/ThemeSwitcher-5cgNbWiG.js +1 -0
  76. package/dist/client/assets/{TikzGalleryDialog-cPUDQ5Wj.js → TikzGalleryDialog-CFbLjNTt.js} +1 -1
  77. package/dist/client/assets/TikzGalleryDialog-CFbLjNTt.js.br +0 -0
  78. package/dist/client/assets/TikzGalleryDialog-CFbLjNTt.js.gz +0 -0
  79. package/dist/client/assets/{WordCountDialog-AiuR3rra.js → WordCountDialog-hXC-cpPs.js} +1 -1
  80. package/dist/client/assets/WordCountDialog-hXC-cpPs.js.br +0 -0
  81. package/dist/client/assets/WordCountDialog-hXC-cpPs.js.gz +0 -0
  82. package/dist/client/assets/{chktex--32C-Pkl.js → chktex-CLzMD_9a.js} +1 -1
  83. package/dist/client/assets/file-down-DA4jGFrF.js +1 -0
  84. package/dist/client/assets/i18n-B8sR-BXw.js +13 -0
  85. package/dist/client/assets/i18n-B8sR-BXw.js.br +0 -0
  86. package/dist/client/assets/i18n-B8sR-BXw.js.gz +0 -0
  87. package/dist/client/assets/index-D6faTuJe.css +1 -0
  88. package/dist/client/assets/index-D6faTuJe.css.br +0 -0
  89. package/dist/client/assets/index-D6faTuJe.css.gz +0 -0
  90. package/dist/client/assets/index-dScQ5LCu.js +2 -0
  91. package/dist/client/assets/index-dScQ5LCu.js.br +0 -0
  92. package/dist/client/assets/index-dScQ5LCu.js.gz +0 -0
  93. package/dist/client/assets/relativeTime-zIVNCN0k.js +1 -0
  94. package/dist/client/assets/relativeTime-zIVNCN0k.js.br +0 -0
  95. package/dist/client/assets/relativeTime-zIVNCN0k.js.gz +0 -0
  96. package/dist/client/assets/sourceCursorStore-DWCXVKvp.js +2 -0
  97. package/dist/client/assets/sourceCursorStore-DWCXVKvp.js.br +0 -0
  98. package/dist/client/assets/sourceCursorStore-DWCXVKvp.js.gz +0 -0
  99. package/dist/client/assets/{spellCheck-DpWPgtM7.js → spellCheck-DpyzDbmq.js} +1 -1
  100. package/dist/client/assets/spellCheck-DpyzDbmq.js.br +0 -0
  101. package/dist/client/assets/spellCheck-DpyzDbmq.js.gz +0 -0
  102. package/dist/client/assets/useDeletionTransitions-Bm4I5qej.js +1 -0
  103. package/dist/client/assets/useDeletionTransitions-Bm4I5qej.js.br +0 -0
  104. package/dist/client/assets/useDeletionTransitions-Bm4I5qej.js.gz +0 -0
  105. package/dist/client/index.html +3 -4
  106. package/dist/server/agents/adapters/claude.js +5 -2
  107. package/dist/server/agents/adapters/common.js +18 -5
  108. package/dist/server/agents/execution.js +25 -4
  109. package/dist/server/agents/launcher.js +5 -2
  110. package/dist/server/agents/processIdentity.js +1 -1
  111. package/dist/server/agents/terminal.js +5 -2
  112. package/dist/server/agents/windowsJob.js +141 -0
  113. package/dist/server/app.js +24 -6
  114. package/dist/server/auth.js +3 -2
  115. package/dist/server/browserOrigin.js +15 -0
  116. package/dist/server/chktex.js +23 -11
  117. package/dist/server/collaboration.js +2 -1
  118. package/dist/server/compileDiagnostics.js +13 -9
  119. package/dist/server/compiler.js +70 -25
  120. package/dist/server/config.js +5 -1
  121. package/dist/server/db.js +4 -0
  122. package/dist/server/drawioLocks.js +114 -0
  123. package/dist/server/drawioOwnedBrowser.js +122 -0
  124. package/dist/server/drawioPdf.js +182 -0
  125. package/dist/server/environment.js +17 -8
  126. package/dist/server/files.js +86 -20
  127. package/dist/server/git.js +20 -16
  128. package/dist/server/harper.js +29 -10
  129. package/dist/server/history.js +62 -15
  130. package/dist/server/i18n.js +15 -0
  131. package/dist/server/index.js +15 -8
  132. package/dist/server/locales/zh-Hant.js +9 -0
  133. package/dist/server/pdfFonts.js +78 -0
  134. package/dist/server/pm2.js +2 -1
  135. package/dist/server/processTree.js +128 -7
  136. package/dist/server/projectDeletionCleanup.js +62 -0
  137. package/dist/server/projectMutations.js +3 -0
  138. package/dist/server/projectReplace.js +2 -2
  139. package/dist/server/projectSearch.js +2 -1
  140. package/dist/server/projectTemplateCache.js +94 -0
  141. package/dist/server/projectTemplateDownload.js +75 -0
  142. package/dist/server/projectTextSave.js +56 -0
  143. package/dist/server/routes/agents.js +2 -15
  144. package/dist/server/routes/compile.js +67 -9
  145. package/dist/server/routes/drawio.js +192 -0
  146. package/dist/server/routes/projectFiles.js +106 -20
  147. package/dist/server/routes/projects.js +81 -20
  148. package/dist/server/routes/users.js +10 -14
  149. package/dist/server/synctex.js +20 -3
  150. package/dist/server/texcount.js +27 -23
  151. package/dist/server/zip.js +37 -11
  152. package/dist/shared/drawio.js +79 -0
  153. package/dist/shared/fileTypes.js +1 -1
  154. package/dist/shared/pdfFonts.js +14 -0
  155. package/dist/shared/projectImport.js +21 -0
  156. package/package.json +3 -1
  157. package/dist/client/assets/AdminUsers-C-8tXzvj.js +0 -1
  158. package/dist/client/assets/AdminUsers-C-8tXzvj.js.br +0 -0
  159. package/dist/client/assets/AdminUsers-C-8tXzvj.js.gz +0 -0
  160. package/dist/client/assets/AgentManagement-DXgfP7l_.js +0 -1
  161. package/dist/client/assets/AgentManagement-DXgfP7l_.js.br +0 -0
  162. package/dist/client/assets/AgentManagement-DXgfP7l_.js.gz +0 -0
  163. package/dist/client/assets/AgentTerminal-DD4sskCS.js +0 -2
  164. package/dist/client/assets/AgentTerminal-DD4sskCS.js.br +0 -0
  165. package/dist/client/assets/AgentTerminal-DD4sskCS.js.gz +0 -0
  166. package/dist/client/assets/AgentTerminalSurface-DliOcop5.js.gz +0 -0
  167. package/dist/client/assets/AvatarSettingsDialog-iuEbMO4a.js.br +0 -0
  168. package/dist/client/assets/AvatarSettingsDialog-iuEbMO4a.js.gz +0 -0
  169. package/dist/client/assets/CitationBibtexEditor-CDiYDj3M.js +0 -1
  170. package/dist/client/assets/CitationLibraryDialog-CJlL-Ytx.js +0 -3
  171. package/dist/client/assets/CitationLibraryDialog-CJlL-Ytx.js.br +0 -0
  172. package/dist/client/assets/CitationLibraryDialog-CJlL-Ytx.js.gz +0 -0
  173. package/dist/client/assets/Dashboard-DqwGd9wd.js +0 -5
  174. package/dist/client/assets/Dashboard-DqwGd9wd.js.br +0 -0
  175. package/dist/client/assets/Dashboard-DqwGd9wd.js.gz +0 -0
  176. package/dist/client/assets/GitDialog-DUGAigLx.js +0 -4
  177. package/dist/client/assets/GitDialog-DUGAigLx.js.br +0 -0
  178. package/dist/client/assets/GitDialog-DUGAigLx.js.gz +0 -0
  179. package/dist/client/assets/GitHubAccountDialog-B4eD622i.js +0 -1
  180. package/dist/client/assets/GitHubAccountDialog-B4eD622i.js.br +0 -0
  181. package/dist/client/assets/GitHubAccountDialog-B4eD622i.js.gz +0 -0
  182. package/dist/client/assets/HistoryDialog-upkR8E0L.js.br +0 -0
  183. package/dist/client/assets/HistoryDialog-upkR8E0L.js.gz +0 -0
  184. package/dist/client/assets/InfoPopover-CQ3Q10tN.js +0 -1
  185. package/dist/client/assets/LatexEditor-DvDYTc0r.js +0 -25
  186. package/dist/client/assets/LatexEditor-DvDYTc0r.js.br +0 -0
  187. package/dist/client/assets/LatexEditor-DvDYTc0r.js.gz +0 -0
  188. package/dist/client/assets/MarkdownPreview-_AXp5G7f.js.br +0 -0
  189. package/dist/client/assets/MarkdownPreview-_AXp5G7f.js.gz +0 -0
  190. package/dist/client/assets/ProjectIconPickerDialog-BxjEYsau.js.br +0 -0
  191. package/dist/client/assets/ProjectIconPickerDialog-BxjEYsau.js.gz +0 -0
  192. package/dist/client/assets/ProjectSearchDialog-BB8thfK9.js +0 -1
  193. package/dist/client/assets/ProjectSearchDialog-BB8thfK9.js.br +0 -0
  194. package/dist/client/assets/ProjectSearchDialog-BB8thfK9.js.gz +0 -0
  195. package/dist/client/assets/ProjectSettings-Dx-b26uN.js +0 -4
  196. package/dist/client/assets/ProjectSettings-Dx-b26uN.js.br +0 -0
  197. package/dist/client/assets/ProjectSettings-Dx-b26uN.js.gz +0 -0
  198. package/dist/client/assets/ProjectWorkspace-DiurYeU1.js +0 -25
  199. package/dist/client/assets/ProjectWorkspace-DiurYeU1.js.br +0 -0
  200. package/dist/client/assets/ProjectWorkspace-DiurYeU1.js.gz +0 -0
  201. package/dist/client/assets/QuickOpenDialog-HlkWqVR9.js.br +0 -0
  202. package/dist/client/assets/QuickOpenDialog-HlkWqVR9.js.gz +0 -0
  203. package/dist/client/assets/SelectionHistoryDialog-Cb8I-G6m.js.br +0 -0
  204. package/dist/client/assets/SelectionHistoryDialog-Cb8I-G6m.js.gz +0 -0
  205. package/dist/client/assets/SharedProjectPage-BBLOLjnD.js +0 -2
  206. package/dist/client/assets/SharedProjectPage-BBLOLjnD.js.br +0 -0
  207. package/dist/client/assets/SharedProjectPage-BBLOLjnD.js.gz +0 -0
  208. package/dist/client/assets/SystemMetricsDialog-Dr4pYWG6.js +0 -1
  209. package/dist/client/assets/SystemMetricsDialog-Dr4pYWG6.js.br +0 -0
  210. package/dist/client/assets/SystemMetricsDialog-Dr4pYWG6.js.gz +0 -0
  211. package/dist/client/assets/TagManagementDialog-D4fYVboy.js +0 -1
  212. package/dist/client/assets/TagManagementDialog-D4fYVboy.js.br +0 -0
  213. package/dist/client/assets/TagManagementDialog-D4fYVboy.js.gz +0 -0
  214. package/dist/client/assets/ThemeSwitcher-BgzkYTeA.js +0 -1
  215. package/dist/client/assets/TikzGalleryDialog-cPUDQ5Wj.js.br +0 -0
  216. package/dist/client/assets/TikzGalleryDialog-cPUDQ5Wj.js.gz +0 -0
  217. package/dist/client/assets/WordCountDialog-AiuR3rra.js.br +0 -0
  218. package/dist/client/assets/WordCountDialog-AiuR3rra.js.gz +0 -0
  219. package/dist/client/assets/dist-DdUqlCPw.js +0 -1
  220. package/dist/client/assets/dist-DdUqlCPw.js.br +0 -0
  221. package/dist/client/assets/dist-DdUqlCPw.js.gz +0 -0
  222. package/dist/client/assets/i18n-Dpk6KCs6.js +0 -13
  223. package/dist/client/assets/i18n-Dpk6KCs6.js.br +0 -0
  224. package/dist/client/assets/i18n-Dpk6KCs6.js.gz +0 -0
  225. package/dist/client/assets/index-B1vejuOw.js +0 -2
  226. package/dist/client/assets/index-B1vejuOw.js.br +0 -0
  227. package/dist/client/assets/index-B1vejuOw.js.gz +0 -0
  228. package/dist/client/assets/index-Blr4J_Pq.css +0 -1
  229. package/dist/client/assets/index-Blr4J_Pq.css.br +0 -0
  230. package/dist/client/assets/index-Blr4J_Pq.css.gz +0 -0
  231. package/dist/client/assets/relativeTime-CcP1IEvr.js +0 -1
  232. package/dist/client/assets/relativeTime-CcP1IEvr.js.br +0 -0
  233. package/dist/client/assets/relativeTime-CcP1IEvr.js.gz +0 -0
  234. package/dist/client/assets/sourceCursorStore-EycYBVxj.js +0 -1
  235. package/dist/client/assets/sourceCursorStore-EycYBVxj.js.br +0 -0
  236. package/dist/client/assets/sourceCursorStore-EycYBVxj.js.gz +0 -0
  237. package/dist/client/assets/spellCheck-DpWPgtM7.js.br +0 -0
  238. package/dist/client/assets/spellCheck-DpWPgtM7.js.gz +0 -0
  239. package/dist/client/assets/useDeletionTransitions-DvxVkRuo.js +0 -1
  240. package/dist/client/assets/useDeletionTransitions-DvxVkRuo.js.br +0 -0
  241. package/dist/client/assets/useDeletionTransitions-DvxVkRuo.js.gz +0 -0
@@ -3,8 +3,14 @@ import { suggestionMessages } from "../../shared/suggestionMessages.js";
3
3
  import { viewLinkMessages } from "../../shared/projectViewLinks.js";
4
4
  import { citationCollectionMessages } from "../../shared/citationCollections.js";
5
5
  import { projectSearchMessages } from "../../shared/projectSearch.js";
6
+ import { projectImportMessages } from "../../shared/projectImport.js";
7
+ import { pdfFontMessages } from "../../shared/pdfFonts.js";
8
+ import { drawioMessages } from "../../shared/drawio.js";
6
9
  /** Traditional Chinese API messages, using the same stable error codes. */
7
10
  export const zhHantMessages = {
11
+ ...drawioMessages["zh-Hant"].errors,
12
+ ...pdfFontMessages["zh-Hant"],
13
+ ...projectImportMessages["zh-Hant"],
8
14
  ...viewLinkMessages["zh-Hant"],
9
15
  ...citationCollectionMessages["zh-Hant"],
10
16
  ...projectSearchMessages["zh-Hant"],
@@ -43,6 +49,7 @@ export const zhHantMessages = {
43
49
  COMPILE_ARTIFACTS_NOT_FOUND: "尚無可用的編譯產出。",
44
50
  COMPILE_CLEAN_BUSY: "目前主文件正在編譯,請完成後再執行故障排除。",
45
51
  COMPILE_FORBIDDEN: "你沒有編譯此專案的權限。",
52
+ LATEX_ENGINE_UNAVAILABLE: "此伺服器上的 {{engine}} 無法使用。請在 LaTeX 設定中切換引擎,或聯絡管理員啟用。",
46
53
  TIKZ_GALLERY_DISABLED: "此伺服器未啟用 TikZ 圖庫。",
47
54
  TIKZ_GALLERY_UNAVAILABLE: "此伺服器上找不到 TikZ 圖庫外掛,請聯絡管理員安裝。",
48
55
  TIKZ_GALLERY_INCOMPATIBLE: "已安裝的 TikZ 圖庫與目前 TexLite 版本不相容,請聯絡管理員更新。",
@@ -95,6 +102,7 @@ export const zhHantMessages = {
95
102
  OWNER_MEMBER_FORBIDDEN: "專案擁有者不能作為成員新增。",
96
103
  PASSWORD_TOO_SHORT: "密碼至少需要 {{minLength}} 個字元。",
97
104
  PATH_EXISTS: "目標路徑已被檔案或資料夾佔用。",
105
+ PROJECT_PATH_BUSY: "檔案或資料夾可能正在使用,或無法存取。請關閉後重試。",
98
106
  PATH_NOT_FOUND: "檔案或資料夾不存在。",
99
107
  PDF_NOT_FOUND: "尚未產生 PDF。",
100
108
  PROJECT_BUSY: "專案正在執行原始檔操作,請稍後再試一次。",
@@ -136,6 +144,7 @@ export const zhHantMessages = {
136
144
  WORD_COUNT_SOURCE_TOO_LARGE: "所選原始碼過大,無法統計。",
137
145
  WORD_COUNT_UNAVAILABLE: "伺服器尚未安裝 TeX Live 的 texcount 套件,請安裝後再試一次。",
138
146
  ZIP_DUPLICATE_ENTRY: "ZIP 壓縮檔包含重複檔名:{{path}}。",
147
+ ZIP_PATH_CONFLICT: "ZIP 壓縮檔中的路徑在 Windows 上發生衝突:{{path}}。",
139
148
  ZIP_ENTRY_READ_FAILED: "無法讀取 ZIP 壓縮檔中的檔案。",
140
149
  ZIP_ENTRY_TOO_LARGE: "ZIP 壓縮檔中存在超過限制的檔案。",
141
150
  ZIP_INVALID: "無法匯入 ZIP 壓縮檔。",
@@ -0,0 +1,78 @@
1
+ import { spawn } from "node:child_process";
2
+ import { httpError } from "./http.js";
3
+ import { afterProcessStop, detachedProcessGroup, stopProcessTree } from "./processTree.js";
4
+ const timeoutMs = 15_000;
5
+ const maxOutputBytes = 1024 * 1024;
6
+ /** Poppler's columns contain spaces in font names and types; read the fixed trailing fields. */
7
+ export function parsePdfFonts(output) {
8
+ const lines = output.trim().split(/\r?\n/);
9
+ if (!/^name\s+type\s+encoding\s+emb\s+sub\s+uni\s+object ID\s*$/.test(lines[0] ?? "")
10
+ || !/^-+(?:\s+-+)+\s*$/.test(lines[1] ?? ""))
11
+ throw httpError(422, "PDF_FONTS_FAILED");
12
+ return lines.slice(2).filter((line) => line.trim()).map((line) => {
13
+ const match = /^(.+?)\s+((?:CID )?(?:Type [013]C?|TrueType)(?: \(OT\))?|unknown)\s+(\S+)\s+(yes|no)\s+(yes|no)\s+(yes|no)\s+\d+\s+\d+\s*$/.exec(line);
14
+ if (!match)
15
+ throw httpError(422, "PDF_FONTS_FAILED");
16
+ return { name: match[1].trim(), type: match[2], encoding: match[3],
17
+ embedded: match[4] === "yes", subset: match[5] === "yes", unicode: match[6] === "yes" };
18
+ });
19
+ }
20
+ /** Read-only, optional host tool. Never invoked at startup or as part of compilation. */
21
+ export function inspectPdfFonts(pdfPath, signal) {
22
+ if (signal?.aborted)
23
+ return Promise.reject(new DOMException("Aborted", "AbortError"));
24
+ return new Promise((resolve, reject) => {
25
+ const child = spawn("pdffonts", [pdfPath], {
26
+ shell: false, detached: detachedProcessGroup(), stdio: ["ignore", "pipe", "pipe"],
27
+ env: { ...process.env, LC_ALL: "C", LANG: "C" }
28
+ });
29
+ const stdout = [];
30
+ let bytes = 0, hasWarnings = false, limited = false, settled = false;
31
+ const abort = () => { void stopProcessTree(child).catch(() => finish(httpError(422, "PDF_FONTS_FAILED"))); };
32
+ const timer = setTimeout(() => { limited = true; abort(); }, timeoutMs);
33
+ const finish = (error) => {
34
+ if (settled)
35
+ return;
36
+ settled = true;
37
+ clearTimeout(timer);
38
+ signal?.removeEventListener("abort", abort);
39
+ if (error) {
40
+ reject(error);
41
+ return;
42
+ }
43
+ try {
44
+ resolve({ fonts: parsePdfFonts(Buffer.concat(stdout).toString("utf8")), hasWarnings });
45
+ }
46
+ catch (reason) {
47
+ reject(reason);
48
+ }
49
+ };
50
+ const collect = (chunk, keep) => {
51
+ bytes += chunk.length;
52
+ if (bytes > maxOutputBytes) {
53
+ if (!limited) {
54
+ limited = true;
55
+ abort();
56
+ }
57
+ return;
58
+ }
59
+ if (keep)
60
+ stdout.push(chunk);
61
+ else if (chunk.toString("utf8").trim())
62
+ hasWarnings = true;
63
+ };
64
+ child.stdout.on("data", (chunk) => collect(chunk, true));
65
+ child.stderr.on("data", (chunk) => collect(chunk, false));
66
+ child.once("error", () => finish(signal?.aborted
67
+ ? new DOMException("Aborted", "AbortError")
68
+ : httpError(503, "PDF_FONTS_UNAVAILABLE")));
69
+ child.once("close", (code) => {
70
+ clearTimeout(timer);
71
+ afterProcessStop(child, () => finish(signal?.aborted ? new DOMException("Aborted", "AbortError")
72
+ : limited || code !== 0 ? httpError(422, "PDF_FONTS_FAILED") : undefined), () => finish(httpError(422, "PDF_FONTS_FAILED")));
73
+ });
74
+ signal?.addEventListener("abort", abort, { once: true });
75
+ if (signal?.aborted)
76
+ abort();
77
+ });
78
+ }
@@ -94,7 +94,8 @@ function startOptions(config) {
94
94
  max_restarts: 5,
95
95
  restart_delay: 500,
96
96
  max_memory_restart: "512M",
97
- kill_timeout: 10_000,
97
+ kill_timeout: process.platform === "win32" ? 20_000 : 10_000,
98
+ ...(process.platform === "win32" ? { shutdown_with_message: true } : {}),
98
99
  env: environment
99
100
  };
100
101
  }
@@ -1,3 +1,97 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import path from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { attachWindowsJob, stopWindowsJob } from "./agents/windowsJob.js";
6
+ const run = promisify(execFile);
7
+ const windowsCommands = new WeakMap();
8
+ // No command runs before the parent assigns this launcher to the job. The
9
+ // launcher owns the last job handle and exits even if its IPC parent crashes.
10
+ const gatedCommand = `
11
+ const { spawn } = require('node:child_process');
12
+ process.once('disconnect', () => process.exit(1));
13
+ process.once('message', ({ command, args, devtoolsPipe }) => {
14
+ // Keep the Chrome protocol descriptors at 3 and 4 through both spawns.
15
+ const stdio = devtoolsPipe ? ['inherit', 'inherit', 'inherit', 3, 4] : 'inherit';
16
+ const worker = spawn(command, args, { windowsHide: true, stdio });
17
+ worker.once('error', ({ message, code }) => {
18
+ process.send({ message, code }, () => process.exit(1));
19
+ });
20
+ worker.once('exit', (code) => process.exit(code ?? 1));
21
+ });
22
+ `;
23
+ /** For commands that can leave work behind even after the main process exits. */
24
+ export function spawnOwnedCommand(command, args, options = {}) {
25
+ const { devtoolsPipe, ...spawnOptions } = options;
26
+ const stdio = ["ignore", "pipe", "pipe"];
27
+ if (devtoolsPipe)
28
+ stdio.push("pipe", "pipe");
29
+ if (process.platform !== "win32") {
30
+ return spawn(command, args, { ...spawnOptions, detached: true, stdio });
31
+ }
32
+ const id = randomUUID();
33
+ const child = spawn(process.execPath, ["--input-type=commonjs", "-e", gatedCommand, "--", id], {
34
+ ...spawnOptions, windowsHide: true, stdio: [...stdio, "ipc"]
35
+ }); // Node's overloads only type the three standard streams.
36
+ const closed = new Promise((resolve) => child.once("close", () => resolve()));
37
+ let attached = false;
38
+ let stopping;
39
+ let draining;
40
+ let launchError;
41
+ const drain = () => draining ??= stopWindowsJob(id, "Command");
42
+ child.on("message", (message) => {
43
+ launchError = Object.assign(new Error(message.message), { code: message.code });
44
+ });
45
+ const ready = (async () => {
46
+ if (!child.pid)
47
+ return; // Direct spawn errors still reach the usual listener.
48
+ await attachWindowsJob(child.pid, id, "Command");
49
+ attached = true;
50
+ if (!stopping && child.connected) {
51
+ // Pass arguments over IPC, not through a shell or the launcher's command line.
52
+ await new Promise((resolve, reject) => child.send({ command, args, devtoolsPipe }, (error) => error ? reject(error) : resolve()));
53
+ }
54
+ })().catch((error) => {
55
+ launchError = error;
56
+ child.kill();
57
+ });
58
+ const complete = closed.then(async () => {
59
+ await ready;
60
+ if (attached)
61
+ await drain();
62
+ if (launchError)
63
+ throw launchError;
64
+ });
65
+ void complete.catch(() => undefined);
66
+ const stop = async () => {
67
+ await ready;
68
+ if (attached) {
69
+ try {
70
+ await drain();
71
+ }
72
+ catch (error) {
73
+ child.kill();
74
+ await closed;
75
+ throw error;
76
+ }
77
+ }
78
+ await closed;
79
+ };
80
+ windowsCommands.set(child, { stop: () => stopping ??= stop(), complete });
81
+ return child;
82
+ }
83
+ /** For a still-owned Windows root. A failed tree kill is not a successful exit. */
84
+ async function killWindowsProcessTree(pid) {
85
+ if (!Number.isSafeInteger(pid) || pid <= 0)
86
+ throw new Error("Invalid Windows process ID");
87
+ try {
88
+ const executable = path.win32.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "taskkill.exe");
89
+ await run(executable, ["/PID", String(pid), "/T", "/F"], { windowsHide: true, timeout: 5_000, maxBuffer: 128 * 1024 });
90
+ }
91
+ catch (error) {
92
+ throw new Error("Could not terminate the Windows process tree", { cause: error });
93
+ }
94
+ }
1
95
  /**
2
96
  * Start long-running external commands in their own process group on POSIX.
3
97
  * A negative PID can then be used to signal the command and all descendants
@@ -6,13 +100,8 @@
6
100
  export function detachedProcessGroup() {
7
101
  return process.platform !== "win32";
8
102
  }
9
- /**
10
- * Terminate an external command and its descendants when the platform
11
- * supports process groups. The child-only fallback keeps this safe on
12
- * Windows and for processes that have already exited.
13
- */
14
- export function killProcessGroup(child, signal = "SIGKILL") {
15
- if (process.platform !== "win32" && child.pid) {
103
+ function signalPosixGroup(child, signal) {
104
+ if (child.pid) {
16
105
  try {
17
106
  process.kill(-child.pid, signal);
18
107
  return;
@@ -29,3 +118,35 @@ export function killProcessGroup(child, signal = "SIGKILL") {
29
118
  }
30
119
  catch { /* the process may have exited already */ }
31
120
  }
121
+ /** Only Windows requires an asynchronous, forced tree kill. */
122
+ const windowsTerminations = new WeakMap();
123
+ export function stopProcessTree(child, signal = "SIGKILL") {
124
+ if (process.platform !== "win32") {
125
+ // Don't memoize POSIX signals: a later timeout can escalate a SIGTERM.
126
+ signalPosixGroup(child, signal);
127
+ return Promise.resolve();
128
+ }
129
+ const owned = windowsCommands.get(child);
130
+ if (owned)
131
+ return owned.stop();
132
+ const pending = windowsTerminations.get(child);
133
+ if (pending)
134
+ return pending;
135
+ if (!child.pid)
136
+ return Promise.resolve();
137
+ // A PID may have been recycled once Node observed the original exit.
138
+ const stopped = child.exitCode !== null || child.signalCode !== null
139
+ ? Promise.reject(new Error("Windows process exited before its tree could be terminated"))
140
+ : killWindowsProcessTree(child.pid);
141
+ windowsTerminations.set(child, stopped);
142
+ // The owning operation observes failures; event listeners may fire and forget.
143
+ void stopped.catch(() => undefined);
144
+ return stopped;
145
+ }
146
+ export function afterProcessStop(child, complete, fail) {
147
+ const stopped = windowsCommands.get(child)?.complete ?? windowsTerminations.get(child);
148
+ if (stopped)
149
+ void stopped.then(complete, fail);
150
+ else
151
+ complete();
152
+ }
@@ -0,0 +1,62 @@
1
+ import { safePathSegment } from "./files.js";
2
+ const retryIntervalMs = 60_000;
3
+ /** Retries physical cleanup after the transaction that hid deleted projects. */
4
+ export class ProjectDeletionCleanup {
5
+ db;
6
+ remove;
7
+ onError;
8
+ active = new Map();
9
+ timer;
10
+ sweep;
11
+ closed = false;
12
+ constructor(db, remove, onError) {
13
+ this.db = db;
14
+ this.remove = remove;
15
+ this.onError = onError;
16
+ }
17
+ /** Call inside the same transaction that deletes the project rows. */
18
+ enqueue(projectId) {
19
+ if (safePathSegment(projectId) !== projectId)
20
+ throw new Error("Invalid project directory ID");
21
+ this.db.prepare("INSERT INTO pending_project_deletions (project_id) VALUES (?)").run(projectId);
22
+ }
23
+ clean(projectId) {
24
+ if (this.closed)
25
+ return Promise.resolve();
26
+ const active = this.active.get(projectId);
27
+ if (active)
28
+ return active;
29
+ const cleanup = Promise.resolve().then(async () => {
30
+ if (!this.db.prepare("SELECT 1 FROM pending_project_deletions WHERE project_id = ?").get(projectId))
31
+ return;
32
+ if (safePathSegment(projectId) !== projectId || this.db.prepare("SELECT 1 FROM projects WHERE id = ?").get(projectId)) {
33
+ throw new Error("Refusing to clean an invalid or live project directory");
34
+ }
35
+ await this.remove(projectId);
36
+ this.db.prepare("DELETE FROM pending_project_deletions WHERE project_id = ?").run(projectId);
37
+ }).catch((error) => this.onError(error, projectId))
38
+ .finally(() => this.active.delete(projectId));
39
+ this.active.set(projectId, cleanup);
40
+ return cleanup;
41
+ }
42
+ retryPending() {
43
+ return this.sweep ??= Promise.resolve().then(async () => {
44
+ const pending = this.db.prepare("SELECT project_id FROM pending_project_deletions").all();
45
+ for (const { project_id } of pending) {
46
+ if (this.closed)
47
+ break;
48
+ await this.clean(project_id);
49
+ }
50
+ }).catch((error) => this.onError(error)).finally(() => { this.sweep = undefined; });
51
+ }
52
+ start() {
53
+ this.timer ??= setInterval(() => { void this.retryPending(); }, retryIntervalMs);
54
+ this.timer.unref();
55
+ }
56
+ async close() {
57
+ this.closed = true;
58
+ if (this.timer)
59
+ clearInterval(this.timer);
60
+ await Promise.all([this.sweep, ...this.active.values()]);
61
+ }
62
+ }
@@ -1,4 +1,5 @@
1
1
  import { SourceFlushError } from "./http.js";
2
+ import { DrawioLocks } from "./drawioLocks.js";
2
3
  /**
3
4
  * Serializes operations that replace or move a project's source tree.
4
5
  *
@@ -8,6 +9,7 @@ import { SourceFlushError } from "./http.js";
8
9
  */
9
10
  export class ProjectMutationCoordinator {
10
11
  collaboration;
12
+ drawioLocks = new DrawioLocks();
11
13
  externalWriters = new Map();
12
14
  exclusivePending = new Map();
13
15
  /** Source-tree replacement ends external writers before reserving the short queue. */
@@ -61,6 +63,7 @@ export class ProjectMutationCoordinator {
61
63
  try {
62
64
  await this.collaboration.waitForReady?.(projectId);
63
65
  options.preflight?.();
66
+ this.drawioLocks.revokeProject(projectId);
64
67
  // This call is synchronous. No WebSocket event can interleave between
65
68
  // the final flush and the maintenance flag being installed.
66
69
  if (options.flush !== false)
@@ -2,7 +2,7 @@ import fs from "node:fs";
2
2
  import { createHash } from "node:crypto";
3
3
  import { isTextContent, resourceFileKind } from "../shared/fileTypes.js";
4
4
  import { PROJECT_SEARCH_MAX_MATCHES } from "../shared/projectSearch.js";
5
- import { maxCollaborativeFileBytes } from "./collaboration.js";
5
+ import { isCollaborativeTextFile, maxCollaborativeFileBytes } from "./collaboration.js";
6
6
  import { resolveSourcePath } from "./files.js";
7
7
  import { httpError } from "./http.js";
8
8
  import { searchPattern } from "./projectSearch.js";
@@ -11,7 +11,7 @@ export function prepareProjectReplacement(config, projectId, options, replacemen
11
11
  let replaced = 0;
12
12
  let totalBytes = 0;
13
13
  const files = targets.map((target) => {
14
- if (resourceFileKind(target.path) !== "text")
14
+ if (resourceFileKind(target.path) !== "text" || !isCollaborativeTextFile(target.path))
15
15
  throw httpError(400, "FILE_CONTENT_INVALID");
16
16
  const absolute = resolveSourcePath(config, projectId, target.path);
17
17
  let bytes;
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs/promises";
2
2
  import { createHash } from "node:crypto";
3
3
  import { isTextContent, resourceFileKind } from "../shared/fileTypes.js";
4
+ import { isDrawioFile } from "../shared/drawio.js";
4
5
  import { PROJECT_SEARCH_MAX_MATCHES } from "../shared/projectSearch.js";
5
6
  import { maxCollaborativeFileBytes } from "./collaboration.js";
6
7
  import { listProjectFilesAsync, resolveSourcePath } from "./files.js";
@@ -15,7 +16,7 @@ export function searchPattern(options) {
15
16
  /** The caller holds a consistent-read barrier so collaborative buffers are flushed first. */
16
17
  export async function searchProject(config, projectId, options) {
17
18
  const candidates = (await listProjectFilesAsync(config, projectId))
18
- .filter((entry) => entry.type === "file" && resourceFileKind(entry.path) === "text")
19
+ .filter((entry) => entry.type === "file" && resourceFileKind(entry.path) === "text" && !isDrawioFile(entry.path))
19
20
  .sort((a, b) => a.path.localeCompare(b.path));
20
21
  const result = { matches: [], limited: candidates.length > maxFiles };
21
22
  const pattern = searchPattern(options);
@@ -0,0 +1,94 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { downloadProjectTemplate, templateUrl } from "./projectTemplateDownload.js";
5
+ const WEEK_MS = 7 * 24 * 60 * 60_000;
6
+ const digest = (value) => createHash("sha256").update(value).digest("hex");
7
+ /** Unauthenticated ZIPs. Cache lifetime is not a remote freshness check. */
8
+ export class ProjectTemplateCache {
9
+ directory;
10
+ maxBytes;
11
+ fileWork = Promise.resolve();
12
+ nextCleanup = 0;
13
+ constructor(directory, maxBytes) {
14
+ this.directory = directory;
15
+ this.maxBytes = maxBytes;
16
+ }
17
+ // Keep local reads, publication and expiry cleanup consistent; network requests
18
+ // remain independent so a slow template does not block other downloads.
19
+ files(work) {
20
+ const result = this.fileWork.then(work);
21
+ this.fileWork = result.catch(() => undefined);
22
+ return result;
23
+ }
24
+ async download(value, signal) {
25
+ const url = templateUrl(value).href;
26
+ const key = digest(url); // Do not put URLs or signed query strings in filenames.
27
+ signal?.throwIfAborted();
28
+ const cached = await this.files(async () => {
29
+ const now = Date.now();
30
+ if (now >= this.nextCleanup) {
31
+ this.nextCleanup = now + 60 * 60_000;
32
+ await this.cleanup(now);
33
+ }
34
+ try {
35
+ const entry = JSON.parse(await fs.readFile(path.join(this.directory, `${key}.json`), "utf8"));
36
+ if (!(entry.expiresAt > now) || !(entry.size > 0 && entry.size <= this.maxBytes))
37
+ return null;
38
+ const file = path.join(this.directory, `${key}.zip`);
39
+ if ((await fs.stat(file)).size !== entry.size)
40
+ return null;
41
+ const archive = await fs.readFile(file);
42
+ return digest(archive) === entry.sha256 ? archive : null;
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ });
48
+ signal?.throwIfAborted();
49
+ if (cached)
50
+ return { archive: cached, cached: true };
51
+ return { archive: await downloadProjectTemplate(url, this.maxBytes, signal), cached: false };
52
+ }
53
+ /** Publish only after the archive has successfully passed project import. */
54
+ async store(value, archive) {
55
+ const key = digest(templateUrl(value).href);
56
+ // Caching is optional: a cache write failure must not discard a valid import.
57
+ await this.files(async () => {
58
+ await fs.mkdir(this.directory, { recursive: true, mode: 0o700 });
59
+ const temp = path.join(this.directory, `${key}-${randomUUID()}.tmp`);
60
+ try {
61
+ await fs.writeFile(temp, archive, { mode: 0o600 });
62
+ await fs.rename(temp, path.join(this.directory, `${key}.zip`));
63
+ const entry = { expiresAt: Date.now() + WEEK_MS, size: archive.length, sha256: digest(archive) };
64
+ await fs.writeFile(temp, JSON.stringify(entry), { mode: 0o600 });
65
+ await fs.rename(temp, path.join(this.directory, `${key}.json`));
66
+ }
67
+ finally {
68
+ await fs.rm(temp, { force: true });
69
+ }
70
+ }).catch(() => undefined);
71
+ }
72
+ async cleanup(now) {
73
+ const entries = await fs.readdir(this.directory).catch(() => []);
74
+ for (const file of entries) {
75
+ // A crash between publication steps can leave a temp file or a ZIP with
76
+ // no index. No writer runs concurrently with this serialized cleanup.
77
+ if (/^[a-f0-9]{64}-[a-f0-9-]{36}\.tmp$/.test(file)
78
+ || (/^[a-f0-9]{64}\.zip$/.test(file) && !entries.includes(file.slice(0, -4) + ".json"))) {
79
+ await fs.rm(path.join(this.directory, file), { force: true }).catch(() => undefined);
80
+ continue;
81
+ }
82
+ if (!/^[a-f0-9]{64}\.json$/.test(file))
83
+ continue;
84
+ try {
85
+ const entry = JSON.parse(await fs.readFile(path.join(this.directory, file), "utf8"));
86
+ if (entry.expiresAt > now)
87
+ continue;
88
+ await fs.rm(path.join(this.directory, file.slice(0, -5) + ".zip"), { force: true });
89
+ await fs.rm(path.join(this.directory, file), { force: true });
90
+ }
91
+ catch { /* A missing or unreadable cache is a normal cache miss. */ }
92
+ }
93
+ }
94
+ }
@@ -0,0 +1,75 @@
1
+ import http from "node:http";
2
+ import https from "node:https";
3
+ import { httpError, HttpError } from "./http.js";
4
+ const DOWNLOAD_TIMEOUT_MS = 30_000;
5
+ const MAX_REDIRECTS = 5;
6
+ export function templateUrl(value) {
7
+ if (typeof value !== "string" || value.length > 4096)
8
+ throw httpError(400, "TEMPLATE_URL_INVALID");
9
+ let url;
10
+ try {
11
+ url = new URL(value.trim());
12
+ }
13
+ catch {
14
+ throw httpError(400, "TEMPLATE_URL_INVALID");
15
+ }
16
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password)
17
+ throw httpError(400, "TEMPLATE_URL_INVALID");
18
+ url.hash = "";
19
+ return url;
20
+ }
21
+ /** Network access follows host policy; no browser cookies or host credentials are forwarded. */
22
+ export async function downloadProjectTemplate(value, maxBytes, cancellation) {
23
+ let url = templateUrl(value);
24
+ const timeout = AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS);
25
+ const signal = cancellation ? AbortSignal.any([timeout, cancellation]) : timeout;
26
+ const tooLarge = () => httpError(400, "TEMPLATE_DOWNLOAD_TOO_LARGE", { size: Math.floor(maxBytes / 1024 / 1024) });
27
+ try {
28
+ for (let redirects = 0; redirects <= MAX_REDIRECTS; redirects++) {
29
+ signal.throwIfAborted();
30
+ const response = await new Promise((resolve, reject) => {
31
+ const request = (url.protocol === "https:" ? https : http).request(url, {
32
+ signal,
33
+ headers: { Accept: "application/zip, application/octet-stream;q=0.9, */*;q=0.1", "User-Agent": "TexLite" }
34
+ }, resolve);
35
+ request.on("error", reject);
36
+ request.end();
37
+ });
38
+ if ([301, 302, 303, 307, 308].includes(response.statusCode ?? 0)) {
39
+ const location = response.headers.location;
40
+ response.destroy();
41
+ if (!location || redirects === MAX_REDIRECTS)
42
+ throw httpError(400, "TEMPLATE_DOWNLOAD_FAILED");
43
+ url = templateUrl(new URL(location, url).href);
44
+ continue;
45
+ }
46
+ if (response.statusCode !== 200) {
47
+ response.destroy();
48
+ throw httpError(400, "TEMPLATE_DOWNLOAD_FAILED");
49
+ }
50
+ if (Number(response.headers["content-length"]) > maxBytes) {
51
+ response.destroy();
52
+ throw tooLarge();
53
+ }
54
+ const chunks = [];
55
+ let bytes = 0;
56
+ for await (const chunk of response) {
57
+ bytes += chunk.length;
58
+ if (bytes > maxBytes) {
59
+ response.destroy();
60
+ throw tooLarge();
61
+ }
62
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
63
+ }
64
+ return Buffer.concat(chunks, bytes);
65
+ }
66
+ throw httpError(400, "TEMPLATE_DOWNLOAD_FAILED");
67
+ }
68
+ catch (error) {
69
+ if (timeout.aborted)
70
+ throw httpError(408, "TEMPLATE_DOWNLOAD_TIMEOUT");
71
+ if (error instanceof HttpError)
72
+ throw error;
73
+ throw httpError(400, "TEMPLATE_DOWNLOAD_FAILED");
74
+ }
75
+ }
@@ -0,0 +1,56 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { renameProjectPath } from "./files.js";
4
+ /**
5
+ * Stage outside the source tree. SQLite rolls back metadata if installation
6
+ * fails; if COMMIT fails after installation, restore the old bytes instead.
7
+ * The caller must hold the project write lock throughout this operation.
8
+ */
9
+ export function saveProjectText(db, outputDirectory, target, content, previous, updateMetadata, reportCleanupFailure) {
10
+ const stagingRoot = path.join(outputDirectory, ".texlite");
11
+ fs.mkdirSync(stagingRoot, { recursive: true, mode: 0o700 });
12
+ const staging = fs.mkdtempSync(path.join(stagingRoot, "source-save-"));
13
+ const replacement = path.join(staging, "replacement");
14
+ const backup = path.join(staging, "previous");
15
+ let installed = false;
16
+ let keepBackup = false;
17
+ try {
18
+ if (previous)
19
+ fs.copyFileSync(target, backup);
20
+ fs.writeFileSync(replacement, content, { mode: 0o600 });
21
+ if (previous && process.platform !== "win32")
22
+ fs.chmodSync(replacement, previous.mode & 0o777);
23
+ db.transaction(() => {
24
+ // A metadata error here does not touch the original file. Nothing
25
+ // outside this synchronous transaction observes the uncommitted rows.
26
+ updateMetadata();
27
+ renameProjectPath(replacement, target);
28
+ installed = true;
29
+ }).immediate();
30
+ }
31
+ catch (error) {
32
+ if (installed) {
33
+ try {
34
+ if (previous)
35
+ renameProjectPath(backup, target);
36
+ else
37
+ fs.unlinkSync(target);
38
+ }
39
+ catch (rollbackError) {
40
+ keepBackup = true;
41
+ throw new AggregateError([error, rollbackError], `Could not roll back source save for ${target}; recovery directory: ${staging}`);
42
+ }
43
+ }
44
+ throw error;
45
+ }
46
+ finally {
47
+ if (!keepBackup) {
48
+ try {
49
+ fs.rmSync(staging, { recursive: true, force: true });
50
+ }
51
+ catch (error) {
52
+ reportCleanupFailure(error, staging);
53
+ }
54
+ }
55
+ }
56
+ }
@@ -1,3 +1,4 @@
1
+ import { browserOriginAllowed } from "../browserOrigin.js";
1
2
  import { currentUser, requireAdmin, requireUser } from "../auth.js";
2
3
  import { apiError, httpError } from "../http.js";
3
4
  import { isAgentId } from "../../shared/agentProtocol.js";
@@ -9,20 +10,6 @@ function title(value, optional = false) {
9
10
  throw httpError(400, "REQUEST_INVALID");
10
11
  return value.trim();
11
12
  }
12
- function terminalOriginAllowed(request) {
13
- const origin = request.headers.origin;
14
- if (!origin)
15
- return false;
16
- try {
17
- const parsed = new URL(origin);
18
- const forwarded = request.headers["x-forwarded-proto"];
19
- const protocol = forwarded === "https" || forwarded === "http" ? forwarded : request.protocol;
20
- return parsed.host === request.headers.host && parsed.protocol === `${protocol}:` && parsed.origin === origin;
21
- }
22
- catch {
23
- return false;
24
- }
25
- }
26
13
  /** Task owners get terminal access; administrators get separate metadata/cleanup routes. */
27
14
  export function registerAgentRoutes(app, { db, agents }) {
28
15
  app.get("/api/agents/access", async (request, reply) => {
@@ -114,7 +101,7 @@ export function registerAgentRoutes(app, { db, agents }) {
114
101
  });
115
102
  app.get("/api/agent-tasks/:taskId/terminal", { websocket: true }, (socket, request) => {
116
103
  const user = currentUser(request, db);
117
- if (!user || !terminalOriginAllowed(request)) {
104
+ if (!user || !browserOriginAllowed(request)) {
118
105
  socket.close(1008, "Access denied");
119
106
  return;
120
107
  }