@vandenberghinc/volt 1.2.5 → 1.2.6

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 (489) hide show
  1. package/frontend/assets/admin/admin.png +0 -0
  2. package/frontend/assets/admin/password.webp +0 -0
  3. package/frontend/assets/icons/arrow.v1.webp +0 -0
  4. package/frontend/assets/icons/copy.webp +0 -0
  5. package/frontend/assets/payments/arrow.long.webp +0 -0
  6. package/frontend/assets/payments/arrow.long2.webp +0 -0
  7. package/frontend/assets/payments/cancelled.webp +0 -0
  8. package/frontend/assets/payments/check.sign.webp +0 -0
  9. package/frontend/assets/payments/check.webp +0 -0
  10. package/frontend/assets/payments/close.webp +0 -0
  11. package/frontend/assets/payments/error.webp +0 -0
  12. package/frontend/assets/payments/exclamation.webp +0 -0
  13. package/frontend/assets/payments/minus.webp +0 -0
  14. package/frontend/assets/payments/party.webp +0 -0
  15. package/frontend/assets/payments/plus.webp +0 -0
  16. package/frontend/assets/payments/shopping_cart.webp +0 -0
  17. package/frontend/assets/payments/trash.webp +0 -0
  18. package/package.json +5 -1
  19. package/.libris/config.json +0 -82
  20. package/backend/dist/cjs/backend/src/blacklist.d.ts +0 -12
  21. package/backend/dist/cjs/backend/src/blacklist.js +0 -78
  22. package/backend/dist/cjs/backend/src/cli.d.ts +0 -2
  23. package/backend/dist/cjs/backend/src/cli.js +0 -198
  24. package/backend/dist/cjs/backend/src/database/collection.d.ts +0 -1765
  25. package/backend/dist/cjs/backend/src/database/collection.js +0 -3301
  26. package/backend/dist/cjs/backend/src/database/database.d.ts +0 -92
  27. package/backend/dist/cjs/backend/src/database/database.js +0 -170
  28. package/backend/dist/cjs/backend/src/database/document.d.ts +0 -1
  29. package/backend/dist/cjs/backend/src/database/document.js +0 -15
  30. package/backend/dist/cjs/backend/src/database/filters/filters.d.ts +0 -6
  31. package/backend/dist/cjs/backend/src/database/filters/filters.js +0 -15
  32. package/backend/dist/cjs/backend/src/database/filters/strict_filter.d.ts +0 -223
  33. package/backend/dist/cjs/backend/src/database/filters/strict_filter.js +0 -15
  34. package/backend/dist/cjs/backend/src/database/filters/strict_filter_test.d.ts +0 -1
  35. package/backend/dist/cjs/backend/src/database/filters/strict_filter_test.js +0 -443
  36. package/backend/dist/cjs/backend/src/database/filters/strict_filter_test_v0.d.ts +0 -1
  37. package/backend/dist/cjs/backend/src/database/filters/strict_filter_test_v0.js +0 -15
  38. package/backend/dist/cjs/backend/src/database/filters/strict_filter_v0.d.ts +0 -50
  39. package/backend/dist/cjs/backend/src/database/filters/strict_filter_v0.js +0 -15
  40. package/backend/dist/cjs/backend/src/database/filters/strict_filter_v1.d.ts +0 -76
  41. package/backend/dist/cjs/backend/src/database/filters/strict_filter_v1.js +0 -15
  42. package/backend/dist/cjs/backend/src/database/filters/strict_filter_v2.d.ts +0 -75
  43. package/backend/dist/cjs/backend/src/database/filters/strict_filter_v2.js +0 -15
  44. package/backend/dist/cjs/backend/src/database/filters/strict_filter_v3.d.ts +0 -219
  45. package/backend/dist/cjs/backend/src/database/filters/strict_filter_v3.js +0 -15
  46. package/backend/dist/cjs/backend/src/database/filters/strict_update_filter.d.ts +0 -165
  47. package/backend/dist/cjs/backend/src/database/filters/strict_update_filter.js +0 -15
  48. package/backend/dist/cjs/backend/src/database/filters/strict_update_filter_test.d.ts +0 -5
  49. package/backend/dist/cjs/backend/src/database/filters/strict_update_filter_test.js +0 -355
  50. package/backend/dist/cjs/backend/src/database/flatten.d.ts +0 -78
  51. package/backend/dist/cjs/backend/src/database/flatten.js +0 -53
  52. package/backend/dist/cjs/backend/src/database/flatten_test.d.ts +0 -1
  53. package/backend/dist/cjs/backend/src/database/flatten_test.js +0 -175
  54. package/backend/dist/cjs/backend/src/database/quota/quoata_v2.d.ts +0 -533
  55. package/backend/dist/cjs/backend/src/database/quota/quoata_v2.js +0 -1046
  56. package/backend/dist/cjs/backend/src/database/quota/quota.d.ts +0 -551
  57. package/backend/dist/cjs/backend/src/database/quota/quota.js +0 -1108
  58. package/backend/dist/cjs/backend/src/database/quota/quota_v1.d.ts +0 -534
  59. package/backend/dist/cjs/backend/src/database/quota/quota_v1.js +0 -1087
  60. package/backend/dist/cjs/backend/src/database/quota/safe_int.d.ts +0 -412
  61. package/backend/dist/cjs/backend/src/database/quota/safe_int.js +0 -745
  62. package/backend/dist/cjs/backend/src/endpoint.d.ts +0 -346
  63. package/backend/dist/cjs/backend/src/endpoint.js +0 -468
  64. package/backend/dist/cjs/backend/src/errors/index.d.ts +0 -7
  65. package/backend/dist/cjs/backend/src/errors/index.js +0 -25
  66. package/backend/dist/cjs/backend/src/errors/internal_external.d.ts +0 -52
  67. package/backend/dist/cjs/backend/src/errors/internal_external.js +0 -95
  68. package/backend/dist/cjs/backend/src/errors/invalid_usage_error.d.ts +0 -41
  69. package/backend/dist/cjs/backend/src/errors/invalid_usage_error.js +0 -47
  70. package/backend/dist/cjs/backend/src/errors/system_error.d.ts +0 -261
  71. package/backend/dist/cjs/backend/src/errors/system_error.js +0 -436
  72. package/backend/dist/cjs/backend/src/events.d.ts +0 -97
  73. package/backend/dist/cjs/backend/src/events.js +0 -15
  74. package/backend/dist/cjs/backend/src/frontend.d.ts +0 -11
  75. package/backend/dist/cjs/backend/src/frontend.js +0 -37
  76. package/backend/dist/cjs/backend/src/image_endpoint.d.ts +0 -44
  77. package/backend/dist/cjs/backend/src/image_endpoint.js +0 -185
  78. package/backend/dist/cjs/backend/src/index.d.ts +0 -23
  79. package/backend/dist/cjs/backend/src/index.js +0 -70
  80. package/backend/dist/cjs/backend/src/logger.d.ts +0 -5
  81. package/backend/dist/cjs/backend/src/logger.js +0 -15
  82. package/backend/dist/cjs/backend/src/meta.d.ts +0 -112
  83. package/backend/dist/cjs/backend/src/meta.js +0 -181
  84. package/backend/dist/cjs/backend/src/payments/paddle.d.ts +0 -329
  85. package/backend/dist/cjs/backend/src/payments/paddle.js +0 -1996
  86. package/backend/dist/cjs/backend/src/payments/stripe/checkout.d.ts +0 -113
  87. package/backend/dist/cjs/backend/src/payments/stripe/checkout.js +0 -295
  88. package/backend/dist/cjs/backend/src/payments/stripe/customers.d.ts +0 -17
  89. package/backend/dist/cjs/backend/src/payments/stripe/customers.js +0 -164
  90. package/backend/dist/cjs/backend/src/payments/stripe/error.d.ts +0 -74
  91. package/backend/dist/cjs/backend/src/payments/stripe/error.js +0 -64
  92. package/backend/dist/cjs/backend/src/payments/stripe/events.d.ts +0 -155
  93. package/backend/dist/cjs/backend/src/payments/stripe/events.js +0 -15
  94. package/backend/dist/cjs/backend/src/payments/stripe/meters.d.ts +0 -105
  95. package/backend/dist/cjs/backend/src/payments/stripe/meters.js +0 -230
  96. package/backend/dist/cjs/backend/src/payments/stripe/payment_methods.d.ts +0 -58
  97. package/backend/dist/cjs/backend/src/payments/stripe/payment_methods.js +0 -109
  98. package/backend/dist/cjs/backend/src/payments/stripe/products.d.ts +0 -519
  99. package/backend/dist/cjs/backend/src/payments/stripe/products.js +0 -650
  100. package/backend/dist/cjs/backend/src/payments/stripe/stripe.d.ts +0 -215
  101. package/backend/dist/cjs/backend/src/payments/stripe/stripe.js +0 -468
  102. package/backend/dist/cjs/backend/src/payments/stripe/subscriptions.d.ts +0 -172
  103. package/backend/dist/cjs/backend/src/payments/stripe/subscriptions.js +0 -557
  104. package/backend/dist/cjs/backend/src/payments/stripe/utils.d.ts +0 -63
  105. package/backend/dist/cjs/backend/src/payments/stripe/utils.js +0 -118
  106. package/backend/dist/cjs/backend/src/payments/stripe/webhooks.d.ts +0 -105
  107. package/backend/dist/cjs/backend/src/payments/stripe/webhooks.js +0 -627
  108. package/backend/dist/cjs/backend/src/plugins/browser.d.ts +0 -1
  109. package/backend/dist/cjs/backend/src/plugins/browser.js +0 -15
  110. package/backend/dist/cjs/backend/src/plugins/communication.d.ts +0 -70
  111. package/backend/dist/cjs/backend/src/plugins/communication.js +0 -196
  112. package/backend/dist/cjs/backend/src/plugins/mail/mail.d.ts +0 -255
  113. package/backend/dist/cjs/backend/src/plugins/mail/mail.js +0 -381
  114. package/backend/dist/cjs/backend/src/plugins/mail/ui.d.ts +0 -297
  115. package/backend/dist/cjs/backend/src/plugins/mail/ui.js +0 -1370
  116. package/backend/dist/cjs/backend/src/plugins/pdf.d.ts +0 -1
  117. package/backend/dist/cjs/backend/src/plugins/pdf.js +0 -1456
  118. package/backend/dist/cjs/backend/src/plugins/thread_monitor.d.ts +0 -18
  119. package/backend/dist/cjs/backend/src/plugins/thread_monitor.js +0 -116
  120. package/backend/dist/cjs/backend/src/rate_limit.d.ts +0 -148
  121. package/backend/dist/cjs/backend/src/rate_limit.js +0 -543
  122. package/backend/dist/cjs/backend/src/route.d.ts +0 -39
  123. package/backend/dist/cjs/backend/src/route.js +0 -172
  124. package/backend/dist/cjs/backend/src/server.d.ts +0 -502
  125. package/backend/dist/cjs/backend/src/server.js +0 -1713
  126. package/backend/dist/cjs/backend/src/server.old.d.ts +0 -594
  127. package/backend/dist/cjs/backend/src/server.old.js +0 -2058
  128. package/backend/dist/cjs/backend/src/splash_screen.d.ts +0 -93
  129. package/backend/dist/cjs/backend/src/splash_screen.js +0 -119
  130. package/backend/dist/cjs/backend/src/status.d.ts +0 -89
  131. package/backend/dist/cjs/backend/src/status.js +0 -211
  132. package/backend/dist/cjs/backend/src/stream.d.ts +0 -494
  133. package/backend/dist/cjs/backend/src/stream.js +0 -1370
  134. package/backend/dist/cjs/backend/src/users.d.ts +0 -926
  135. package/backend/dist/cjs/backend/src/users.js +0 -2223
  136. package/backend/dist/cjs/backend/src/utils.d.ts +0 -22
  137. package/backend/dist/cjs/backend/src/utils.js +0 -626
  138. package/backend/dist/cjs/backend/src/view.d.ts +0 -115
  139. package/backend/dist/cjs/backend/src/view.js +0 -519
  140. package/backend/dist/cjs/backend/src/vinc.d.ts +0 -6
  141. package/backend/dist/cjs/backend/src/vinc.js +0 -40
  142. package/backend/dist/cjs/backend/src/volt.d.ts +0 -24
  143. package/backend/dist/cjs/backend/src/volt.js +0 -72
  144. package/backend/dist/cjs/frontend/src/modules/request.d.ts +0 -70
  145. package/backend/dist/cjs/frontend/src/modules/request.js +0 -99
  146. package/backend/dist/cjs/package.json +0 -1
  147. package/backend/dist/esm/backend/src/blacklist.d.ts +0 -12
  148. package/backend/dist/esm/backend/src/blacklist.js +0 -52
  149. package/backend/dist/esm/backend/src/cli.d.ts +0 -2
  150. package/backend/dist/esm/backend/src/cli.js +0 -211
  151. package/backend/dist/esm/backend/src/database/collection.d.ts +0 -1765
  152. package/backend/dist/esm/backend/src/database/collection.js +0 -3779
  153. package/backend/dist/esm/backend/src/database/database.d.ts +0 -92
  154. package/backend/dist/esm/backend/src/database/database.js +0 -214
  155. package/backend/dist/esm/backend/src/database/document.d.ts +0 -1
  156. package/backend/dist/esm/backend/src/database/document.js +0 -558
  157. package/backend/dist/esm/backend/src/database/filters/filters.d.ts +0 -6
  158. package/backend/dist/esm/backend/src/database/filters/filters.js +0 -1
  159. package/backend/dist/esm/backend/src/database/filters/strict_filter.d.ts +0 -223
  160. package/backend/dist/esm/backend/src/database/filters/strict_filter.js +0 -3
  161. package/backend/dist/esm/backend/src/database/filters/strict_filter_test.d.ts +0 -1
  162. package/backend/dist/esm/backend/src/database/filters/strict_filter_test.js +0 -505
  163. package/backend/dist/esm/backend/src/database/filters/strict_filter_test_v0.d.ts +0 -1
  164. package/backend/dist/esm/backend/src/database/filters/strict_filter_test_v0.js +0 -712
  165. package/backend/dist/esm/backend/src/database/filters/strict_filter_v0.d.ts +0 -50
  166. package/backend/dist/esm/backend/src/database/filters/strict_filter_v0.js +0 -5
  167. package/backend/dist/esm/backend/src/database/filters/strict_filter_v1.d.ts +0 -76
  168. package/backend/dist/esm/backend/src/database/filters/strict_filter_v1.js +0 -44
  169. package/backend/dist/esm/backend/src/database/filters/strict_filter_v2.d.ts +0 -75
  170. package/backend/dist/esm/backend/src/database/filters/strict_filter_v2.js +0 -5
  171. package/backend/dist/esm/backend/src/database/filters/strict_filter_v3.d.ts +0 -219
  172. package/backend/dist/esm/backend/src/database/filters/strict_filter_v3.js +0 -1
  173. package/backend/dist/esm/backend/src/database/filters/strict_update_filter.d.ts +0 -165
  174. package/backend/dist/esm/backend/src/database/filters/strict_update_filter.js +0 -5
  175. package/backend/dist/esm/backend/src/database/filters/strict_update_filter_test.d.ts +0 -5
  176. package/backend/dist/esm/backend/src/database/filters/strict_update_filter_test.js +0 -415
  177. package/backend/dist/esm/backend/src/database/flatten.d.ts +0 -78
  178. package/backend/dist/esm/backend/src/database/flatten.js +0 -22
  179. package/backend/dist/esm/backend/src/database/flatten_test.d.ts +0 -1
  180. package/backend/dist/esm/backend/src/database/flatten_test.js +0 -174
  181. package/backend/dist/esm/backend/src/database/quota/quoata_v2.d.ts +0 -533
  182. package/backend/dist/esm/backend/src/database/quota/quoata_v2.js +0 -1155
  183. package/backend/dist/esm/backend/src/database/quota/quota.d.ts +0 -551
  184. package/backend/dist/esm/backend/src/database/quota/quota.js +0 -1219
  185. package/backend/dist/esm/backend/src/database/quota/quota_v1.d.ts +0 -534
  186. package/backend/dist/esm/backend/src/database/quota/quota_v1.js +0 -1242
  187. package/backend/dist/esm/backend/src/database/quota/safe_int.d.ts +0 -412
  188. package/backend/dist/esm/backend/src/database/quota/safe_int.js +0 -810
  189. package/backend/dist/esm/backend/src/endpoint.d.ts +0 -346
  190. package/backend/dist/esm/backend/src/endpoint.js +0 -479
  191. package/backend/dist/esm/backend/src/errors/index.d.ts +0 -7
  192. package/backend/dist/esm/backend/src/errors/index.js +0 -7
  193. package/backend/dist/esm/backend/src/errors/internal_external.d.ts +0 -52
  194. package/backend/dist/esm/backend/src/errors/internal_external.js +0 -86
  195. package/backend/dist/esm/backend/src/errors/invalid_usage_error.d.ts +0 -41
  196. package/backend/dist/esm/backend/src/errors/invalid_usage_error.js +0 -33
  197. package/backend/dist/esm/backend/src/errors/system_error.d.ts +0 -261
  198. package/backend/dist/esm/backend/src/errors/system_error.js +0 -444
  199. package/backend/dist/esm/backend/src/events.d.ts +0 -97
  200. package/backend/dist/esm/backend/src/events.js +0 -5
  201. package/backend/dist/esm/backend/src/frontend.d.ts +0 -11
  202. package/backend/dist/esm/backend/src/frontend.js +0 -12
  203. package/backend/dist/esm/backend/src/image_endpoint.d.ts +0 -44
  204. package/backend/dist/esm/backend/src/image_endpoint.js +0 -196
  205. package/backend/dist/esm/backend/src/index.d.ts +0 -23
  206. package/backend/dist/esm/backend/src/index.js +0 -26
  207. package/backend/dist/esm/backend/src/logger.d.ts +0 -5
  208. package/backend/dist/esm/backend/src/logger.js +0 -8
  209. package/backend/dist/esm/backend/src/meta.d.ts +0 -112
  210. package/backend/dist/esm/backend/src/meta.js +0 -152
  211. package/backend/dist/esm/backend/src/payments/paddle.d.ts +0 -329
  212. package/backend/dist/esm/backend/src/payments/paddle.js +0 -2276
  213. package/backend/dist/esm/backend/src/payments/stripe/checkout.d.ts +0 -113
  214. package/backend/dist/esm/backend/src/payments/stripe/checkout.js +0 -356
  215. package/backend/dist/esm/backend/src/payments/stripe/customers.d.ts +0 -17
  216. package/backend/dist/esm/backend/src/payments/stripe/customers.js +0 -193
  217. package/backend/dist/esm/backend/src/payments/stripe/error.d.ts +0 -74
  218. package/backend/dist/esm/backend/src/payments/stripe/error.js +0 -51
  219. package/backend/dist/esm/backend/src/payments/stripe/events.d.ts +0 -155
  220. package/backend/dist/esm/backend/src/payments/stripe/events.js +0 -5
  221. package/backend/dist/esm/backend/src/payments/stripe/meters.d.ts +0 -105
  222. package/backend/dist/esm/backend/src/payments/stripe/meters.js +0 -318
  223. package/backend/dist/esm/backend/src/payments/stripe/payment_methods.d.ts +0 -58
  224. package/backend/dist/esm/backend/src/payments/stripe/payment_methods.js +0 -135
  225. package/backend/dist/esm/backend/src/payments/stripe/products.d.ts +0 -519
  226. package/backend/dist/esm/backend/src/payments/stripe/products.js +0 -896
  227. package/backend/dist/esm/backend/src/payments/stripe/stripe.d.ts +0 -215
  228. package/backend/dist/esm/backend/src/payments/stripe/stripe.js +0 -464
  229. package/backend/dist/esm/backend/src/payments/stripe/subscriptions.d.ts +0 -172
  230. package/backend/dist/esm/backend/src/payments/stripe/subscriptions.js +0 -754
  231. package/backend/dist/esm/backend/src/payments/stripe/utils.d.ts +0 -63
  232. package/backend/dist/esm/backend/src/payments/stripe/utils.js +0 -131
  233. package/backend/dist/esm/backend/src/payments/stripe/webhooks.d.ts +0 -105
  234. package/backend/dist/esm/backend/src/payments/stripe/webhooks.js +0 -752
  235. package/backend/dist/esm/backend/src/plugins/browser.d.ts +0 -1
  236. package/backend/dist/esm/backend/src/plugins/browser.js +0 -170
  237. package/backend/dist/esm/backend/src/plugins/communication.d.ts +0 -70
  238. package/backend/dist/esm/backend/src/plugins/communication.js +0 -169
  239. package/backend/dist/esm/backend/src/plugins/mail/mail.d.ts +0 -255
  240. package/backend/dist/esm/backend/src/plugins/mail/mail.js +0 -396
  241. package/backend/dist/esm/backend/src/plugins/mail/ui.d.ts +0 -297
  242. package/backend/dist/esm/backend/src/plugins/mail/ui.js +0 -1400
  243. package/backend/dist/esm/backend/src/plugins/pdf.d.ts +0 -1
  244. package/backend/dist/esm/backend/src/plugins/pdf.js +0 -1694
  245. package/backend/dist/esm/backend/src/plugins/thread_monitor.d.ts +0 -18
  246. package/backend/dist/esm/backend/src/plugins/thread_monitor.js +0 -120
  247. package/backend/dist/esm/backend/src/rate_limit.d.ts +0 -148
  248. package/backend/dist/esm/backend/src/rate_limit.js +0 -667
  249. package/backend/dist/esm/backend/src/route.d.ts +0 -39
  250. package/backend/dist/esm/backend/src/route.js +0 -222
  251. package/backend/dist/esm/backend/src/server.d.ts +0 -502
  252. package/backend/dist/esm/backend/src/server.js +0 -2034
  253. package/backend/dist/esm/backend/src/server.old.d.ts +0 -594
  254. package/backend/dist/esm/backend/src/server.old.js +0 -2630
  255. package/backend/dist/esm/backend/src/splash_screen.d.ts +0 -93
  256. package/backend/dist/esm/backend/src/splash_screen.js +0 -156
  257. package/backend/dist/esm/backend/src/status.d.ts +0 -89
  258. package/backend/dist/esm/backend/src/status.js +0 -213
  259. package/backend/dist/esm/backend/src/stream.d.ts +0 -494
  260. package/backend/dist/esm/backend/src/stream.js +0 -1611
  261. package/backend/dist/esm/backend/src/users.d.ts +0 -926
  262. package/backend/dist/esm/backend/src/users.js +0 -2423
  263. package/backend/dist/esm/backend/src/utils.d.ts +0 -22
  264. package/backend/dist/esm/backend/src/utils.js +0 -463
  265. package/backend/dist/esm/backend/src/view.d.ts +0 -115
  266. package/backend/dist/esm/backend/src/view.js +0 -584
  267. package/backend/dist/esm/backend/src/vinc.d.ts +0 -6
  268. package/backend/dist/esm/backend/src/vinc.js +0 -6
  269. package/backend/dist/esm/backend/src/volt.d.ts +0 -24
  270. package/backend/dist/esm/backend/src/volt.js +0 -27
  271. package/backend/dist/esm/frontend/src/modules/request.d.ts +0 -70
  272. package/backend/dist/esm/frontend/src/modules/request.js +0 -117
  273. package/backend/old/file_watcher.ts +0 -359
  274. package/backend/old/request.deprc.js +0 -626
  275. package/backend/old/response.deprc.js +0 -354
  276. package/frontend/dist/backend/src/database/collection.d.ts +0 -1765
  277. package/frontend/dist/backend/src/database/collection.js +0 -3779
  278. package/frontend/dist/backend/src/database/database.d.ts +0 -92
  279. package/frontend/dist/backend/src/database/database.js +0 -214
  280. package/frontend/dist/backend/src/database/filters/filters.d.ts +0 -6
  281. package/frontend/dist/backend/src/database/filters/filters.js +0 -1
  282. package/frontend/dist/backend/src/database/filters/strict_filter.d.ts +0 -223
  283. package/frontend/dist/backend/src/database/filters/strict_filter.js +0 -3
  284. package/frontend/dist/backend/src/database/filters/strict_update_filter.d.ts +0 -165
  285. package/frontend/dist/backend/src/database/filters/strict_update_filter.js +0 -5
  286. package/frontend/dist/backend/src/database/flatten.d.ts +0 -78
  287. package/frontend/dist/backend/src/database/flatten.js +0 -22
  288. package/frontend/dist/backend/src/endpoint.d.ts +0 -346
  289. package/frontend/dist/backend/src/endpoint.js +0 -479
  290. package/frontend/dist/backend/src/errors/index.d.ts +0 -7
  291. package/frontend/dist/backend/src/errors/index.js +0 -7
  292. package/frontend/dist/backend/src/errors/internal_external.d.ts +0 -52
  293. package/frontend/dist/backend/src/errors/internal_external.js +0 -86
  294. package/frontend/dist/backend/src/errors/invalid_usage_error.d.ts +0 -41
  295. package/frontend/dist/backend/src/errors/invalid_usage_error.js +0 -33
  296. package/frontend/dist/backend/src/errors/system_error.d.ts +0 -261
  297. package/frontend/dist/backend/src/errors/system_error.js +0 -444
  298. package/frontend/dist/backend/src/events.d.ts +0 -97
  299. package/frontend/dist/backend/src/events.js +0 -5
  300. package/frontend/dist/backend/src/frontend.d.ts +0 -11
  301. package/frontend/dist/backend/src/frontend.js +0 -12
  302. package/frontend/dist/backend/src/image_endpoint.d.ts +0 -44
  303. package/frontend/dist/backend/src/image_endpoint.js +0 -196
  304. package/frontend/dist/backend/src/meta.d.ts +0 -112
  305. package/frontend/dist/backend/src/meta.js +0 -152
  306. package/frontend/dist/backend/src/payments/paddle.d.ts +0 -329
  307. package/frontend/dist/backend/src/payments/paddle.js +0 -2276
  308. package/frontend/dist/backend/src/payments/stripe/checkout.d.ts +0 -113
  309. package/frontend/dist/backend/src/payments/stripe/checkout.js +0 -356
  310. package/frontend/dist/backend/src/payments/stripe/customers.d.ts +0 -17
  311. package/frontend/dist/backend/src/payments/stripe/customers.js +0 -193
  312. package/frontend/dist/backend/src/payments/stripe/error.d.ts +0 -74
  313. package/frontend/dist/backend/src/payments/stripe/error.js +0 -51
  314. package/frontend/dist/backend/src/payments/stripe/events.d.ts +0 -155
  315. package/frontend/dist/backend/src/payments/stripe/events.js +0 -5
  316. package/frontend/dist/backend/src/payments/stripe/meters.d.ts +0 -105
  317. package/frontend/dist/backend/src/payments/stripe/meters.js +0 -318
  318. package/frontend/dist/backend/src/payments/stripe/payment_methods.d.ts +0 -58
  319. package/frontend/dist/backend/src/payments/stripe/payment_methods.js +0 -135
  320. package/frontend/dist/backend/src/payments/stripe/products.d.ts +0 -519
  321. package/frontend/dist/backend/src/payments/stripe/products.js +0 -896
  322. package/frontend/dist/backend/src/payments/stripe/stripe.d.ts +0 -215
  323. package/frontend/dist/backend/src/payments/stripe/stripe.js +0 -464
  324. package/frontend/dist/backend/src/payments/stripe/subscriptions.d.ts +0 -172
  325. package/frontend/dist/backend/src/payments/stripe/subscriptions.js +0 -754
  326. package/frontend/dist/backend/src/payments/stripe/utils.d.ts +0 -63
  327. package/frontend/dist/backend/src/payments/stripe/utils.js +0 -131
  328. package/frontend/dist/backend/src/payments/stripe/webhooks.d.ts +0 -105
  329. package/frontend/dist/backend/src/payments/stripe/webhooks.js +0 -752
  330. package/frontend/dist/backend/src/plugins/mail/mail.d.ts +0 -255
  331. package/frontend/dist/backend/src/plugins/mail/mail.js +0 -396
  332. package/frontend/dist/backend/src/plugins/mail/ui.d.ts +0 -297
  333. package/frontend/dist/backend/src/plugins/mail/ui.js +0 -1400
  334. package/frontend/dist/backend/src/rate_limit.d.ts +0 -148
  335. package/frontend/dist/backend/src/rate_limit.js +0 -667
  336. package/frontend/dist/backend/src/route.d.ts +0 -39
  337. package/frontend/dist/backend/src/route.js +0 -222
  338. package/frontend/dist/backend/src/server.d.ts +0 -502
  339. package/frontend/dist/backend/src/server.js +0 -2034
  340. package/frontend/dist/backend/src/splash_screen.d.ts +0 -93
  341. package/frontend/dist/backend/src/splash_screen.js +0 -156
  342. package/frontend/dist/backend/src/status.d.ts +0 -89
  343. package/frontend/dist/backend/src/status.js +0 -213
  344. package/frontend/dist/backend/src/stream.d.ts +0 -494
  345. package/frontend/dist/backend/src/stream.js +0 -1611
  346. package/frontend/dist/backend/src/users.d.ts +0 -926
  347. package/frontend/dist/backend/src/users.js +0 -2423
  348. package/frontend/dist/backend/src/utils.d.ts +0 -22
  349. package/frontend/dist/backend/src/utils.js +0 -463
  350. package/frontend/dist/backend/src/view.d.ts +0 -115
  351. package/frontend/dist/backend/src/view.js +0 -584
  352. package/frontend/dist/frontend/src/elements/base.d.ts +0 -3743
  353. package/frontend/dist/frontend/src/elements/base.js +0 -12151
  354. package/frontend/dist/frontend/src/elements/module.d.ts +0 -95
  355. package/frontend/dist/frontend/src/elements/module.js +0 -216
  356. package/frontend/dist/frontend/src/elements/register_element.d.ts +0 -3
  357. package/frontend/dist/frontend/src/elements/register_element.js +0 -22
  358. package/frontend/dist/frontend/src/elements/resize_query_manager.d.ts +0 -0
  359. package/frontend/dist/frontend/src/elements/resize_query_manager.js +0 -150
  360. package/frontend/dist/frontend/src/elements/types.d.ts +0 -52
  361. package/frontend/dist/frontend/src/elements/types.js +0 -5
  362. package/frontend/dist/frontend/src/index.d.ts +0 -21
  363. package/frontend/dist/frontend/src/index.js +0 -29
  364. package/frontend/dist/frontend/src/modules/attachment.d.ts +0 -126
  365. package/frontend/dist/frontend/src/modules/attachment.js +0 -306
  366. package/frontend/dist/frontend/src/modules/auth.d.ts +0 -44
  367. package/frontend/dist/frontend/src/modules/auth.js +0 -80
  368. package/frontend/dist/frontend/src/modules/color.d.ts +0 -160
  369. package/frontend/dist/frontend/src/modules/color.js +0 -316
  370. package/frontend/dist/frontend/src/modules/compression.d.ts +0 -39
  371. package/frontend/dist/frontend/src/modules/compression.js +0 -102
  372. package/frontend/dist/frontend/src/modules/cookies.d.ts +0 -44
  373. package/frontend/dist/frontend/src/modules/cookies.js +0 -143
  374. package/frontend/dist/frontend/src/modules/events.d.ts +0 -31
  375. package/frontend/dist/frontend/src/modules/events.js +0 -79
  376. package/frontend/dist/frontend/src/modules/google.d.ts +0 -23
  377. package/frontend/dist/frontend/src/modules/google.js +0 -52
  378. package/frontend/dist/frontend/src/modules/meta.d.ts +0 -14
  379. package/frontend/dist/frontend/src/modules/meta.js +0 -48
  380. package/frontend/dist/frontend/src/modules/paddle.d.ts +0 -1207
  381. package/frontend/dist/frontend/src/modules/paddle.js +0 -2594
  382. package/frontend/dist/frontend/src/modules/request.d.ts +0 -70
  383. package/frontend/dist/frontend/src/modules/request.js +0 -117
  384. package/frontend/dist/frontend/src/modules/settings.d.ts +0 -3
  385. package/frontend/dist/frontend/src/modules/settings.js +0 -5
  386. package/frontend/dist/frontend/src/modules/statics.d.ts +0 -21
  387. package/frontend/dist/frontend/src/modules/statics.js +0 -43
  388. package/frontend/dist/frontend/src/modules/stripe/cart.d.ts +0 -112
  389. package/frontend/dist/frontend/src/modules/stripe/cart.js +0 -321
  390. package/frontend/dist/frontend/src/modules/stripe/checkout.d.ts +0 -7
  391. package/frontend/dist/frontend/src/modules/stripe/checkout.js +0 -37
  392. package/frontend/dist/frontend/src/modules/stripe/index.m.d.ts +0 -6
  393. package/frontend/dist/frontend/src/modules/stripe/index.m.js +0 -6
  394. package/frontend/dist/frontend/src/modules/stripe/payments.d.ts +0 -58
  395. package/frontend/dist/frontend/src/modules/stripe/payments.js +0 -92
  396. package/frontend/dist/frontend/src/modules/support.d.ts +0 -30
  397. package/frontend/dist/frontend/src/modules/support.js +0 -53
  398. package/frontend/dist/frontend/src/modules/theme.d.ts +0 -133
  399. package/frontend/dist/frontend/src/modules/theme.js +0 -406
  400. package/frontend/dist/frontend/src/modules/themes.d.ts +0 -12
  401. package/frontend/dist/frontend/src/modules/themes.js +0 -22
  402. package/frontend/dist/frontend/src/modules/user.d.ts +0 -164
  403. package/frontend/dist/frontend/src/modules/user.js +0 -270
  404. package/frontend/dist/frontend/src/modules/utils.d.ts +0 -176
  405. package/frontend/dist/frontend/src/modules/utils.js +0 -569
  406. package/frontend/dist/frontend/src/types/gradient.d.ts +0 -29
  407. package/frontend/dist/frontend/src/types/gradient.js +0 -79
  408. package/frontend/dist/frontend/src/ui/border_button.d.ts +0 -94
  409. package/frontend/dist/frontend/src/ui/border_button.js +0 -228
  410. package/frontend/dist/frontend/src/ui/button.d.ts +0 -241
  411. package/frontend/dist/frontend/src/ui/button.js +0 -682
  412. package/frontend/dist/frontend/src/ui/canvas.d.ts +0 -138
  413. package/frontend/dist/frontend/src/ui/canvas.js +0 -444
  414. package/frontend/dist/frontend/src/ui/checkbox.d.ts +0 -74
  415. package/frontend/dist/frontend/src/ui/checkbox.js +0 -321
  416. package/frontend/dist/frontend/src/ui/code.d.ts +0 -235
  417. package/frontend/dist/frontend/src/ui/code.js +0 -1007
  418. package/frontend/dist/frontend/src/ui/context_menu.d.ts +0 -36
  419. package/frontend/dist/frontend/src/ui/context_menu.js +0 -205
  420. package/frontend/dist/frontend/src/ui/css.d.ts +0 -16
  421. package/frontend/dist/frontend/src/ui/css.js +0 -48
  422. package/frontend/dist/frontend/src/ui/divider.d.ts +0 -15
  423. package/frontend/dist/frontend/src/ui/divider.js +0 -78
  424. package/frontend/dist/frontend/src/ui/dropdown.d.ts +0 -176
  425. package/frontend/dist/frontend/src/ui/dropdown.js +0 -481
  426. package/frontend/dist/frontend/src/ui/for_each.d.ts +0 -37
  427. package/frontend/dist/frontend/src/ui/for_each.js +0 -92
  428. package/frontend/dist/frontend/src/ui/form.d.ts +0 -34
  429. package/frontend/dist/frontend/src/ui/form.js +0 -233
  430. package/frontend/dist/frontend/src/ui/frame_modes.d.ts +0 -37
  431. package/frontend/dist/frontend/src/ui/frame_modes.js +0 -108
  432. package/frontend/dist/frontend/src/ui/google_map.d.ts +0 -24
  433. package/frontend/dist/frontend/src/ui/google_map.js +0 -106
  434. package/frontend/dist/frontend/src/ui/gradient.d.ts +0 -25
  435. package/frontend/dist/frontend/src/ui/gradient.js +0 -131
  436. package/frontend/dist/frontend/src/ui/image.d.ts +0 -111
  437. package/frontend/dist/frontend/src/ui/image.js +0 -576
  438. package/frontend/dist/frontend/src/ui/input.d.ts +0 -392
  439. package/frontend/dist/frontend/src/ui/input.js +0 -1201
  440. package/frontend/dist/frontend/src/ui/link.d.ts +0 -25
  441. package/frontend/dist/frontend/src/ui/link.js +0 -140
  442. package/frontend/dist/frontend/src/ui/list.d.ts +0 -37
  443. package/frontend/dist/frontend/src/ui/list.js +0 -170
  444. package/frontend/dist/frontend/src/ui/loader_button.d.ts +0 -80
  445. package/frontend/dist/frontend/src/ui/loader_button.js +0 -193
  446. package/frontend/dist/frontend/src/ui/loaders.d.ts +0 -57
  447. package/frontend/dist/frontend/src/ui/loaders.js +0 -157
  448. package/frontend/dist/frontend/src/ui/popup.d.ts +0 -94
  449. package/frontend/dist/frontend/src/ui/popup.js +0 -510
  450. package/frontend/dist/frontend/src/ui/pseudo.d.ts +0 -44
  451. package/frontend/dist/frontend/src/ui/pseudo.js +0 -154
  452. package/frontend/dist/frontend/src/ui/scroller.d.ts +0 -105
  453. package/frontend/dist/frontend/src/ui/scroller.js +0 -1253
  454. package/frontend/dist/frontend/src/ui/slider.d.ts +0 -45
  455. package/frontend/dist/frontend/src/ui/slider.js +0 -217
  456. package/frontend/dist/frontend/src/ui/spacer.d.ts +0 -15
  457. package/frontend/dist/frontend/src/ui/spacer.js +0 -78
  458. package/frontend/dist/frontend/src/ui/span.d.ts +0 -15
  459. package/frontend/dist/frontend/src/ui/span.js +0 -73
  460. package/frontend/dist/frontend/src/ui/stack.d.ts +0 -66
  461. package/frontend/dist/frontend/src/ui/stack.js +0 -335
  462. package/frontend/dist/frontend/src/ui/steps.d.ts +0 -131
  463. package/frontend/dist/frontend/src/ui/steps.js +0 -308
  464. package/frontend/dist/frontend/src/ui/style.d.ts +0 -17
  465. package/frontend/dist/frontend/src/ui/style.js +0 -73
  466. package/frontend/dist/frontend/src/ui/switch.d.ts +0 -69
  467. package/frontend/dist/frontend/src/ui/switch.js +0 -357
  468. package/frontend/dist/frontend/src/ui/table.d.ts +0 -100
  469. package/frontend/dist/frontend/src/ui/table.js +0 -405
  470. package/frontend/dist/frontend/src/ui/tabs.d.ts +0 -111
  471. package/frontend/dist/frontend/src/ui/tabs.js +0 -424
  472. package/frontend/dist/frontend/src/ui/text.d.ts +0 -15
  473. package/frontend/dist/frontend/src/ui/text.js +0 -83
  474. package/frontend/dist/frontend/src/ui/title.d.ts +0 -91
  475. package/frontend/dist/frontend/src/ui/title.js +0 -272
  476. package/frontend/dist/frontend/src/ui/ui.d.ts +0 -35
  477. package/frontend/dist/frontend/src/ui/ui.js +0 -38
  478. package/frontend/dist/frontend/src/ui/view.d.ts +0 -15
  479. package/frontend/dist/frontend/src/ui/view.js +0 -88
  480. package/frontend/dist/frontend/src/volt.d.ts +0 -20
  481. package/frontend/dist/frontend/src/volt.js +0 -27
  482. package/frontend/examples/theme/theme.ts +0 -58
  483. package/frontend/tools/bundle_d_ts.js +0 -71
  484. package/frontend/tools/convert_to_jsdoc_input.txt +0 -9452
  485. package/frontend/tools/convert_to_jsdoc_output.txt +0 -7626
  486. package/frontend/tools/convert_to_jsdoc_tmp.js +0 -345
  487. package/frontend/tools/scan_mixed_imports.js +0 -69
  488. /package/frontend/{dist/frontend/src/css → css}/adyen.css +0 -0
  489. /package/frontend/{dist/frontend/src/css → css}/volt.css +0 -0
@@ -1,2423 +0,0 @@
1
- /**
2
- * @author Daan van den Bergh
3
- * @copyright © 2022 - 2025 Daan van den Bergh.
4
- */
5
- // ---------------------------------------------------------
6
- // Imports.
7
- // ---------------------------------------------------------
8
- import * as crypto from "crypto";
9
- import * as vlib from "@vandenberghinc/vlib";
10
- import * as MailUI from "./plugins/mail/ui.js";
11
- import { Mail } from "./plugins/mail/mail.js";
12
- import { Status } from "./status.js";
13
- import { ExternalError } from "./errors/index.js";
14
- import { Collection } from "./database/collection.js";
15
- // ---------------------------------------------------------
16
- // The users manager.
17
- // ---------------------------------------------------------
18
- /**
19
- * The users class, used for user management, authentication, and user data storage.
20
- * @note This class is accessible via `Server.users`.
21
- * @nav Server
22
- * @docs
23
- */
24
- export class Users {
25
- // ---------------------------------------------------------
26
- // Readonly settings.
27
- // ---------------------------------------------------------
28
- /**
29
- * Number of random characters after `<prefix>_<uid>_`.
30
- * @warning If you change this, also update:
31
- * - {@link Users.LEGACY_TOKEN_SUFFIX_LENS} to include old size(s).
32
- * - Generators {@link _generate_api_key} and {@link _generate_token}.
33
- * - Parser {@link _parse_uid_from_token_api_key}.
34
- */
35
- static TOKEN_SUFFIX_LEN = 64;
36
- /** Accepted legacy suffix lengths; add old sizes here when rotating. */
37
- static LEGACY_TOKEN_SUFFIX_LENS = [];
38
- /**
39
- * Allowed characters for the random suffix.
40
- * @warning MUST NOT include `_` (delimiter). ASCII only for fast-path validation.
41
- */
42
- static TOKEN_SUFFIX_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
43
- /**
44
- * UID length used by the generator.
45
- * @warning If you change this, add the old value to {@link Users.LEGACY_UID_LENGTHS}.
46
- */
47
- static UID_LENGTH = 16;
48
- /** Accepted legacy UID lengths; add old sizes here when rotating. */
49
- static LEGACY_UID_LENGTHS = [];
50
- /**
51
- * UID character set (ASCII). MUST NOT include `_`.
52
- */
53
- static UID_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
54
- /**
55
- * Build an ASCII allow table for fast membership checks.
56
- * Index is charCode (0..127), value is 1 if allowed else 0.
57
- */
58
- static _build_ascii_allow(cs) {
59
- const tbl = new Uint8Array(128);
60
- for (let i = 0; i < cs.length; i++) {
61
- const c = cs.charCodeAt(i);
62
- if (c < 128)
63
- tbl[c] = 1;
64
- else
65
- throw new Error("Non-ASCII char in allowed charset; use ASCII-only here.");
66
- }
67
- return tbl;
68
- }
69
- /** ASCII allow table for token suffix validation (built from TOKEN_SUFFIX_CHARSET). */
70
- static TOKEN_SUFFIX_ALLOW = Users._build_ascii_allow(Users.TOKEN_SUFFIX_CHARSET);
71
- /** ASCII allow table for UID validation (built from UID_CHARSET). */
72
- static UID_ALLOW = Users._build_ascii_allow(Users.UID_CHARSET);
73
- // ---------------------------------------------------------
74
- // Attributes.
75
- // ---------------------------------------------------------
76
- /** The parent server instance. */
77
- server;
78
- /** The recipient email for support submit emails, defaults to `Server.smtp_sender`. */
79
- support_recipient;
80
- /** The avg wait time when sending 2FA codes. */
81
- avg_send_2fa_time = [];
82
- /** The database collection for token documents. */
83
- _tokens_db;
84
- /** The database collection for 2fa token documents. */
85
- _2fa_tokens_db;
86
- /** The database collection for user documents. */
87
- _users_db;
88
- /** Enable 2FA for user sign in. */
89
- enable_2fa;
90
- /** Enable 2FA account activation for user sign up. */
91
- enable_account_activation;
92
- /** The token expiration in seconds */
93
- token_expiration;
94
- /** Database collection for public (read:public, write:public) user documents. */
95
- public;
96
- /** Database collection for protected (read:public, write:private) user documents. */
97
- protected;
98
- /** Database collection for private (read:private, write:private) user documents. */
99
- private;
100
- // ---------------------------------------------------------
101
- // Constructor.
102
- // ---------------------------------------------------------
103
- /** Construct the users manager. */
104
- constructor(opts) {
105
- this.server = opts._server;
106
- this.enable_2fa = opts.enable_2fa ?? false;
107
- this.enable_account_activation = opts.enable_account_activation ?? true;
108
- this.token_expiration = opts.token_expiration ?? 86400;
109
- this.support_recipient = opts.support_recipient ?? this.server.mail?.sender;
110
- // Database collections.
111
- this._tokens_db = this.server.db.collection({
112
- name: "Volt.Server.Users.Tokens",
113
- indexes: ["uid", "token"],
114
- ttl: 1000 * 3600 * 24 * 30, // 30 days.
115
- });
116
- this._2fa_tokens_db = this.server.db.collection({
117
- name: "Volt.Server.Users.TwoFactorAuth",
118
- indexes: ["uid", "code"],
119
- ttl: 1000 * 3600 * 24, // 1 day.
120
- });
121
- this._users_db = this.server.db.collection({
122
- name: "Volt.Server.Users.Users",
123
- indexes: [
124
- { key: "uid", unique: true, forced: true },
125
- { key: "email", unique: true, forced: true },
126
- { key: "username", unique: true, forced: true },
127
- {
128
- key: "api_key", sparse: true, // api_key index sparse/partial so documents without api_key don’t bloat the index
129
- forced: true
130
- // hashed; non-unique is fine if you only store one per user, and we dont retrieve uid's alike by api key, but extract from raw api key string instead.
131
- }
132
- ],
133
- });
134
- // Public database collections.
135
- this.public = this.server.db.collection({
136
- name: "Volt.Server.Users.Public",
137
- indexes: ["uid", "query"],
138
- });
139
- this.protected = this.server.db.collection({
140
- name: "Volt.Server.Users.Protected",
141
- indexes: ["uid", "query"],
142
- });
143
- this.private = this.server.db.collection({
144
- name: "Volt.Server.Users.Private",
145
- indexes: ["uid", "query"],
146
- });
147
- // Set default 2fa mail event.
148
- this.set_default_2fa_event();
149
- }
150
- // ---------------------------------------------------------
151
- // Utils.
152
- // ---------------------------------------------------------
153
- /** Generate a code. */
154
- _generate_code(length = 6) {
155
- const charset = "0123456789";
156
- let out = "";
157
- for (let i = 0; i < length; i++)
158
- out += charset[crypto.randomInt(charset.length)];
159
- return out;
160
- }
161
- /**
162
- * Generate a crypto str.
163
- * @warning ENSURE this does not add `_` to the charset, as this is used as a delimiter for tokens/api keys.
164
- */
165
- _generate_crypto_str(length = 32, charset) {
166
- let out = "";
167
- for (let i = 0; i < length; i++)
168
- out += charset[crypto.randomInt(charset.length)];
169
- return out;
170
- }
171
- /**
172
- * Derive a key with the async `crypto.scrypt` to avoid blocking the event loop.
173
- * Using the sync variant is CPU-bound and can stall Node’s main thread, enabling
174
- * trivial DoS via many concurrent hash ops. The async call runs in libuv’s
175
- * thread pool, preserving responsiveness under load with the same security.
176
- *
177
- * @param password - Secret/password or input buffer.
178
- * @param salt - Per-secret random salt.
179
- * @param keylen - Desired key length in bytes (default 64).
180
- * @returns Promise resolving to the derived key buffer.
181
- */
182
- _crypto_scrypt(password, salt, keylen = 64) {
183
- return new Promise((res, rej) => crypto.scrypt(password, salt, keylen, (e, dk) => (e ? rej(e) : res(dk))));
184
- }
185
- /** Hash a password. */
186
- async _hash_password(plain) {
187
- const salt = crypto.randomBytes(16);
188
- const hash = await this._crypto_scrypt(plain, salt, 64);
189
- return `${salt.toString("hex")}:${hash.toString("hex")}`;
190
- }
191
- /** Verify a plain password vs stored hashed password. */
192
- async _verify_password(plain, stored) {
193
- const [saltHex, hashHex] = stored.split(":");
194
- const salt = Buffer.from(saltHex, "hex");
195
- const expected = Buffer.from(hashHex, "hex");
196
- const actual = await this._crypto_scrypt(plain, salt, expected.length);
197
- return crypto.timingSafeEqual(actual, expected);
198
- }
199
- /** Generate a unique user ID. */
200
- async _generate_uid() {
201
- let attempts = 0;
202
- const max_attempts = 10_000;
203
- while (attempts < max_attempts) {
204
- const uid = this._generate_crypto_str(Users.UID_LENGTH, Users.UID_CHARSET);
205
- if ((await this.uid_exists(uid)) === false)
206
- return uid;
207
- attempts++;
208
- }
209
- throw new Error("Failed to generate a unique uid after maximum attempts.");
210
- }
211
- /** Generate an API key. Format: `ak_<uid>_<suffix>` */
212
- _generate_api_key(uid) {
213
- /**
214
- * @warning Do not change the `ak_` prefix or `_` delimiters.
215
- * If you change suffix length/charset, update:
216
- * - {@link Users.TOKEN_SUFFIX_LEN} / {@link Users.LEGACY_TOKEN_SUFFIX_LENS}
217
- * - {@link Users.TOKEN_SUFFIX_CHARSET}
218
- * - {@link _parse_uid_from_token_api_key}
219
- */
220
- return `ak_${uid}_${this._generate_crypto_str(Users.TOKEN_SUFFIX_LEN, Users.TOKEN_SUFFIX_CHARSET)}`;
221
- }
222
- /** Generate a token. Format: `tk_<uid>_<suffix>` */
223
- _generate_token(uid) {
224
- /**
225
- * @warning Do not change the `tk_` prefix or `_` delimiters.
226
- * Keep the parser and constants in sync if you rotate length/charset.
227
- */
228
- return `tk_${uid}_${this._generate_crypto_str(Users.TOKEN_SUFFIX_LEN, Users.TOKEN_SUFFIX_CHARSET)}`;
229
- }
230
- /**
231
- * Parse the uid from `<prefix>_<uid>_<suffix>`, where prefix is `ak_` or `tk_`,
232
- * `<uid>` passes {@link Users.is_valid_uid}, and `<suffix>`:
233
- * - length equals {@link Users.TOKEN_SUFFIX_LEN} or a legacy size; and
234
- * - every char is in {@link Users.TOKEN_SUFFIX_CHARSET} (ASCII).
235
- *
236
- * @warning If you change suffix length, add old sizes to
237
- * {@link Users.LEGACY_TOKEN_SUFFIX_LENS}. If you change charset, update
238
- * {@link Users.TOKEN_SUFFIX_CHARSET} (this table rebuilds automatically).
239
- * If you change delimiters/prefixes, update this and the generators together.
240
- */
241
- _parse_uid_from_token_api_key(input, expected_prefix) {
242
- if (typeof input !== "string" || !input.startsWith(expected_prefix))
243
- return undefined;
244
- const pfxLen = expected_prefix.length; // 3
245
- const delimPos = input.indexOf("_", pfxLen);
246
- if (delimPos === -1)
247
- return undefined;
248
- const uid = input.slice(pfxLen, delimPos);
249
- if (uid.length === 0 || !this.is_valid_uid(uid))
250
- return undefined;
251
- const suffix = input.slice(delimPos + 1);
252
- const slen = suffix.length; // ASCII-only assumption
253
- if (slen !== Users.TOKEN_SUFFIX_LEN) {
254
- let ok = false;
255
- for (let i = 0; i < Users.LEGACY_TOKEN_SUFFIX_LENS.length; i++) {
256
- if (slen === Users.LEGACY_TOKEN_SUFFIX_LENS[i]) {
257
- ok = true;
258
- break;
259
- }
260
- }
261
- if (!ok)
262
- return undefined;
263
- }
264
- const allow = Users.TOKEN_SUFFIX_ALLOW;
265
- for (let i = 0; i < slen; i++) {
266
- const code = suffix.charCodeAt(i);
267
- if (code >= 128 || allow[code] === 0)
268
- return undefined;
269
- }
270
- return uid;
271
- }
272
- /**
273
- * Validate a proposed new password against basic rules and confirmation.
274
- * @param pass The new password to validate.
275
- * @param verify_pass The repeated password to confirm.
276
- * @returns An object with optional error message and invalid_fields mapping.
277
- */
278
- _verify_new_pass(pass, verify_pass) {
279
- let error = undefined;
280
- if (pass !== verify_pass) {
281
- error = "Passwords do not match.";
282
- }
283
- else if (pass.length < 8) {
284
- error = "The password should at least include eight characters.";
285
- }
286
- else if (pass.toLowerCase() === pass) {
287
- error = "The password should at least include one capital letter.";
288
- }
289
- else if (!/\d|[!@#$%^&*]/.test(pass)) {
290
- error = "The password should at least include one numeric or special character.";
291
- }
292
- if (error) {
293
- return { error, invalid_fields: { password: error, verify_password: error } };
294
- }
295
- else {
296
- return { error: undefined, invalid_fields: undefined };
297
- }
298
- }
299
- // ---------------------------------------------------------
300
- // Authentication (private).
301
- // ---------------------------------------------------------
302
- /**
303
- * Generate and persist a new auth token for the given uid.
304
- * @param uid The user ID.
305
- * @returns The plaintext token string.
306
- */
307
- async _create_token(uid) {
308
- // @todo create uid & type index.
309
- const token = this._generate_token(uid);
310
- await this._tokens_db.set({ uid }, {
311
- expiration: Date.now() + this.token_expiration * 1000,
312
- token: await this._hash_password(token),
313
- active: true,
314
- });
315
- return token;
316
- }
317
- /**
318
- * Deactivate the current token for the given uid.
319
- * @param uid The user ID.
320
- */
321
- async _deactivate_token(uid) {
322
- await this._tokens_db.set({ uid }, { active: false });
323
- }
324
- /**
325
- * Create and store a short-lived 2FA token (code).
326
- * @param uid_or_email The uid or email key used for the 2FA record.
327
- * @param expiration Expiration in seconds from now.
328
- * @returns The generated 2FA code.
329
- */
330
- async _create_2fa_token(uid_or_email, expiration) {
331
- const code = this._generate_code(6);
332
- await this._2fa_tokens_db.set({ uid: uid_or_email }, {
333
- expiration: Date.now() + expiration * 1000,
334
- code: code,
335
- active: true,
336
- });
337
- return code;
338
- }
339
- /**
340
- * Deactivate a stored 2FA token by uid/email key.
341
- * @param uid_or_email The uid or email key used for the 2FA record.
342
- */
343
- async _deactivate_2fa_token(uid_or_email) {
344
- await this._2fa_tokens_db.set({ uid: uid_or_email }, { active: false });
345
- }
346
- /**
347
- * Perform authentication on a request.
348
- * @returns An object on refusal, undefined on success.
349
- */
350
- async _authenticate(stream) {
351
- const authorization = stream.headers["authorization"];
352
- if (authorization !== undefined) {
353
- if (typeof authorization !== "string") {
354
- return {
355
- status: Status.bad_request,
356
- data: "Invalid authorization header.",
357
- };
358
- }
359
- const match = authorization.match(/^Bearer\s+(\S+)$/i);
360
- if (!match) {
361
- return {
362
- status: Status.bad_request,
363
- data: "Invalid authorization scheme, the authorization scheme must be \"Bearer\".",
364
- };
365
- }
366
- const api_key = match[1];
367
- const uid = this.get_uid_by_api_key(api_key);
368
- if (!uid) {
369
- return { status: Status.unauthorized, data: "Unauthorized." };
370
- }
371
- if ((await this.verify_api_key_by_uid(uid, api_key)) !== true) {
372
- return {
373
- status: Status.unauthorized,
374
- data: "Unauthorized.",
375
- };
376
- }
377
- stream.uid = uid;
378
- return;
379
- }
380
- else {
381
- if (stream.cookies.T == null || stream.cookies.T.value == null) {
382
- return {
383
- status: 302,
384
- headers: { Location: `/signin?next=${encodeURIComponent(stream.endpoint)}` },
385
- data: "Permission denied.",
386
- };
387
- }
388
- const token = stream.cookies.T.value;
389
- const uid = this.get_uid_by_token(token);
390
- if (!uid) {
391
- return {
392
- status: 302,
393
- headers: { Location: `/signin?next=${encodeURIComponent(stream.endpoint)}` },
394
- data: "Permission denied.",
395
- };
396
- }
397
- if ((await this.verify_token_by_uid(uid, token)) !== true) {
398
- return {
399
- status: 302,
400
- headers: { Location: `/signin?next=${encodeURIComponent(stream.endpoint)}` },
401
- data: "Permission denied.",
402
- };
403
- }
404
- stream.uid = uid;
405
- return;
406
- }
407
- }
408
- /**
409
- * Sign a user in, set cookies, and optionally send the success response.
410
- * @param stream The request stream.
411
- * @param uid The authenticated user's ID.
412
- * @param opts Optional settings (e.g., send: false to skip sending the response).
413
- */
414
- async _sign_in_response(stream, uid, opts) {
415
- // Generate token.
416
- const token = await this._create_token(uid);
417
- // Create headers.
418
- this._create_token_cookie(stream, token);
419
- await this._create_user_cookie(stream, uid);
420
- await this._create_detailed_user_cookie(stream, uid);
421
- // Response.
422
- if (opts?.send !== false) {
423
- stream.send({
424
- status: 200,
425
- data: { message: "Successfully signed in." },
426
- });
427
- }
428
- }
429
- // ---------------------------------------------------------
430
- // Cookies (private).
431
- // ---------------------------------------------------------
432
- /**
433
- * Create the auth token cookie on the response.
434
- * `T` is treated as a real authentication credential.
435
- *
436
- * @param stream The request stream.
437
- * @param token The token string or Token object.
438
- */
439
- _create_token_cookie(stream, token) {
440
- stream.set_header("Cache-Control", "max-age=0, no-cache, no-store, must-revalidate, proxy-revalidate");
441
- stream.set_header("Access-Control-Allow-Credentials", "true");
442
- const token_value = typeof token === "object" ? token.token : token;
443
- const max_age = this.token_expiration; // seconds
444
- stream.set_cookie({
445
- name: "T",
446
- value: token_value,
447
- path: "/",
448
- max_age,
449
- secure: true,
450
- http_only: true,
451
- same_site: "Lax", // REQUIRED for Stripe success/cancel redirects
452
- });
453
- }
454
- /**
455
- * Create user cookies (ID and activation flag).
456
- * These are user-state cookies, NOT auth credentials.
457
- *
458
- * @param stream The request stream.
459
- * @param uid The user ID, or invalid to clear.
460
- */
461
- async _create_user_cookie(stream, uid) {
462
- if (typeof uid === "string" && uid.length > 0) {
463
- stream.set_cookie({
464
- name: "UserID",
465
- value: uid,
466
- path: "/",
467
- secure: true,
468
- same_site: "Lax",
469
- });
470
- const is_activated = this.enable_account_activation
471
- ? await this.is_activated(uid)
472
- : true;
473
- stream.set_cookie({
474
- name: "UserActivated",
475
- value: is_activated ? "1" : "0",
476
- path: "/",
477
- secure: true,
478
- same_site: "Lax",
479
- });
480
- }
481
- else {
482
- stream.set_cookie({
483
- name: "UserID",
484
- value: "",
485
- path: "/",
486
- max_age: 0,
487
- secure: true,
488
- same_site: "Lax",
489
- });
490
- stream.set_cookie({
491
- name: "UserActivated",
492
- value: "0",
493
- path: "/",
494
- max_age: 0,
495
- secure: true,
496
- same_site: "Lax",
497
- });
498
- }
499
- }
500
- /**
501
- * Create non-HttpOnly cookies with detailed user info for frontend usage.
502
- * These are UI convenience cookies only.
503
- *
504
- * @param stream The request stream.
505
- * @param uid The user ID.
506
- */
507
- async _create_detailed_user_cookie(stream, uid) {
508
- const user = await this.get(uid);
509
- stream.set_cookie({
510
- name: "UserName",
511
- value: user.username ?? "",
512
- path: "/",
513
- secure: true,
514
- same_site: "Lax",
515
- });
516
- stream.set_cookie({
517
- name: "UserFirstName",
518
- value: user.first_name ?? "",
519
- path: "/",
520
- secure: true,
521
- same_site: "Lax",
522
- });
523
- stream.set_cookie({
524
- name: "UserLastName",
525
- value: user.last_name ?? "",
526
- path: "/",
527
- secure: true,
528
- same_site: "Lax",
529
- });
530
- stream.set_cookie({
531
- name: "UserEmail",
532
- value: user.email ?? "",
533
- path: "/",
534
- secure: true,
535
- same_site: "Lax",
536
- });
537
- }
538
- /**
539
- * Clear all default auth and user-related cookies.
540
- *
541
- * @param stream The request stream.
542
- */
543
- _reset_cookies(stream) {
544
- const clear = {
545
- path: "/",
546
- max_age: 0,
547
- secure: true,
548
- same_site: "Lax",
549
- };
550
- stream.set_cookie({ name: "T", value: "", http_only: true, ...clear });
551
- stream.set_cookie({ name: "UserID", value: "", ...clear });
552
- stream.set_cookie({ name: "UserActivated", value: "", ...clear });
553
- stream.set_cookie({ name: "UserName", value: "", ...clear });
554
- stream.set_cookie({ name: "UserFirstName", value: "", ...clear });
555
- stream.set_cookie({ name: "UserLastName", value: "", ...clear });
556
- stream.set_cookie({ name: "UserEmail", value: "", ...clear });
557
- }
558
- // ---------------------------------------------------------
559
- // 2FA mail.
560
- // Mail template.
561
- /** Build the base email layout used by the various transactional email builders. */
562
- _2fa_mail_template({ max_width = 400, children = [], }) {
563
- this.server.assert_mail();
564
- const style = this.server.mail.style;
565
- const { Title, Text, Image, Table, TableRow, TableData, VStack } = MailUI;
566
- // Create header.
567
- let header;
568
- if (this.server.company.stroke_icon != null) {
569
- header = [
570
- Image(`${this.server.full_domain}${this.server.company.stroke_icon ?? ""}`).height(16),
571
- ];
572
- }
573
- else if (this.server.company.icon != null) {
574
- header = [
575
- Image(`${this.server.full_domain}${this.server.company.icon ?? ""}`).frame(20, 40),
576
- ];
577
- }
578
- if (header) {
579
- header = Table(TableRow(...header)
580
- .wrap(true)
581
- .center()
582
- .center_vertical()).margin_bottom(15);
583
- }
584
- // Create mail.
585
- return MailUI.Mail(Table(TableData(Table(
586
- // Header.
587
- header,
588
- // Widget.
589
- Table(...children)
590
- .background_color(style.widget_bg ?? "")
591
- .border(`1px solid ${style.widget_border ?? ""}`)
592
- .border_radius("10px")
593
- .padding(40, 25, 25, 25)
594
- .margin(0),
595
- // Copyright.
596
- Table(TableRow(Text(`Copyright © ${new Date().getFullYear()} ${this.server.company.name}, ${this.server.company.legal_name} All Rights Included.\n` +
597
- `${this.server.company.street} ${this.server.company.house_number}, ${this.server.company.postal_code}, ${this.server.company.city}, ${this.server.company.province}, ${this.server.company.country}.\n` +
598
- (this.server.company.tax_id == null ? "" : `VAT ID ${this.server.company.tax_id}`))
599
- .white_space("pre")
600
- .display("inline-block")
601
- .font_size(11)
602
- .color(style.footer_fg)
603
- .margin(0)).center().center_vertical()).margin(0, 0, 10, 0)).max_width(max_width)).center()).padding(25, 20, 25, 20)).font_family(style.font).background(style.bg);
604
- }
605
- /**
606
- * Build the 2FA verification email content.
607
- */
608
- set_default_2fa_event() {
609
- this.server.on("2fa_mail", ({ code, username, email, date, ip, device }) => {
610
- this.server.assert_mail();
611
- const style = this.server.mail.style;
612
- const { Title, Text, Image, Table, TableRow, TableData, VStack } = MailUI;
613
- return this._2fa_mail_template({
614
- max_width: 400,
615
- children: [
616
- // Title.
617
- TableRow(Title("Verification Required")
618
- .color(style.title_fg)
619
- .width("fit-content")
620
- .font_size(26)).center(),
621
- // Text.
622
- TableRow(Text("Please confirm your request with this 2FA code.")
623
- .center()
624
- .margin(10, 0, 20, 0)
625
- .color(style.text_fg)
626
- .font_size(18)),
627
- // Auth info.
628
- [
629
- ["Username", username],
630
- ["Email", email],
631
- ["Date", date],
632
- ["Ip Address", ip],
633
- ["Device", device],
634
- ].map((item) => {
635
- return [
636
- TableRow(VStack()
637
- .margin_right(7.5)
638
- // .background("linear-gradient(135deg, #4830C4, #6E399E, #421959)")
639
- .background_color(style.text_fg)
640
- .border_radius("50%")
641
- .frame(5, 5), Text(`<span style='font-weight: 600'>${item[0]}:</span> ${item[1]}`)
642
- .color(style.text_fg)
643
- .font_size(16)
644
- .text_wrap("wrap")
645
- .overflow_wrap("break-word")
646
- .word_wrap("break-word")).wrap(true).center_vertical(),
647
- TableRow().fixed_frame(5, 5),
648
- ];
649
- }),
650
- // 2FA code.
651
- TableRow(Text(code)
652
- .background(style.button_bg)
653
- .border_radius("10px")
654
- .padding(10, 15)
655
- .center()
656
- .color(style.button_fg)
657
- .width("100%")
658
- .margin(20, 0, 0, 0)),
659
- // Text.
660
- TableRow(Text("This 2FA code will be valid for 5 minutes.")
661
- .color(style.text_fg)
662
- .font_style("italic")
663
- .font_size(12)
664
- .margin_top(20)
665
- .center()),
666
- ],
667
- });
668
- });
669
- }
670
- // ---------------------------------------------------------
671
- // Initialization (private).
672
- // ---------------------------------------------------------
673
- /**
674
- * Initialize default authentication, user, and support endpoints.
675
- */
676
- async _initialize({ worker = false, } = {}) {
677
- if (!worker) {
678
- // ---------------------------------------------------------
679
- // Default auth endpoints.
680
- // Send 2fa.
681
- this.server.endpoint({
682
- method: "POST",
683
- endpoint: "/volt/api/v1/auth/2fa",
684
- content_type: "application/json",
685
- rate_limit: "global",
686
- params: {
687
- email: "string",
688
- },
689
- callback: async (stream, params) => {
690
- // Get uid.
691
- let uid;
692
- if ((uid = await this.get_uid_by_email(params.email)) == null) {
693
- return stream.success({
694
- data: { message: "A 2FA code was sent if the specified email exists." },
695
- });
696
- }
697
- // Send.
698
- await this.send_2fa({ uid: uid, stream });
699
- return stream.success({
700
- data: { message: "A 2FA code was sent if the specified email exists." },
701
- });
702
- }
703
- });
704
- // Sign in.
705
- this.server.endpoint({
706
- method: "POST",
707
- endpoint: "/volt/api/v1/auth/signin",
708
- content_type: "application/json",
709
- rate_limit: {
710
- limit: 10,
711
- interval: 60,
712
- group: "volt.auth"
713
- },
714
- callback: async (stream) => {
715
- // console.log("signin 1")
716
- // Uniform delay on failure.
717
- // Basically wait for the same time as it would time on avg to send a mail, since this causes a very slow response.
718
- const uniform_delay = async () => {
719
- if (this.avg_send_2fa_time.length >= 10) {
720
- const sorted = [...this.avg_send_2fa_time].sort((a, b) => a - b);
721
- const mid = Math.floor(sorted.length / 2);
722
- const median = (sorted.length % 2 === 0)
723
- ? Math.floor((sorted[mid - 1] + sorted[mid]) / 2)
724
- : sorted[mid];
725
- await new Promise(res => setTimeout(res, median));
726
- }
727
- };
728
- // Get params.
729
- let email, email_err, username, username_err, password, uid, code;
730
- try {
731
- email = stream.param("email");
732
- }
733
- catch (err) {
734
- email_err = err;
735
- }
736
- try {
737
- username = stream.param("username");
738
- }
739
- catch (err) {
740
- username_err = err;
741
- }
742
- if (email_err && username_err) {
743
- await uniform_delay();
744
- return stream.error({
745
- status: Status.bad_request,
746
- type: "InvalidParams",
747
- message: email_err.message,
748
- });
749
- }
750
- try {
751
- password = stream.param("password");
752
- }
753
- catch (err) {
754
- await uniform_delay();
755
- return stream.error({
756
- status: Status.bad_request,
757
- type: "InvalidParams",
758
- message: err.message,
759
- });
760
- }
761
- // console.log("signin 2", { email, username })
762
- // Revert email to username etc.
763
- if (email && email.indexOf("@") === -1) {
764
- username = email;
765
- email = undefined;
766
- }
767
- else if (username && username.indexOf("@") !== -1) {
768
- email = username;
769
- username = undefined;
770
- }
771
- // Get uid.
772
- // console.log("signin 3" ,{ email, username })
773
- if (email) {
774
- if ((uid = await this.get_uid_by_email(email)) == null) {
775
- await uniform_delay();
776
- return stream.error({
777
- status: Status.unauthorized,
778
- type: "Unauthorized",
779
- message: "Unauthorized.",
780
- invalid_fields: {
781
- "email": "Invalid or unrecognized email",
782
- "password": "Invalid or unrecognized password",
783
- },
784
- });
785
- }
786
- }
787
- else if (username) {
788
- if ((uid = await this.get_uid(username)) == null) {
789
- await uniform_delay();
790
- return stream.error({
791
- status: Status.unauthorized,
792
- type: "Unauthorized",
793
- message: "Unauthorized.",
794
- invalid_fields: {
795
- "username": "Invalid or unrecognized username",
796
- "password": "Invalid or unrecognized password",
797
- },
798
- });
799
- }
800
- }
801
- else {
802
- await uniform_delay();
803
- return stream.error({
804
- status: Status.unauthorized,
805
- type: "Unauthorized",
806
- message: "Unauthorized.",
807
- invalid_fields: {
808
- "username": "Invalid or unrecognized username",
809
- "password": "Invalid or unrecognized password",
810
- },
811
- });
812
- }
813
- // Verify password.
814
- if (await this.verify_password(uid, password)) {
815
- // Verify 2fa.
816
- if (this.enable_2fa) {
817
- // Get 2FA.
818
- try {
819
- code = stream.param("code");
820
- }
821
- catch (err) {
822
- // Send 2fa and add to avg time tracking.
823
- const start_time = Date.now();
824
- await this.send_2fa({ uid: uid, stream });
825
- // Add to avg time tracking.
826
- if (this.avg_send_2fa_time.length >= 10000) {
827
- this.avg_send_2fa_time.shift();
828
- }
829
- this.avg_send_2fa_time.push(Date.now() - start_time);
830
- // Send error.
831
- return stream.error({
832
- status: Status.two_factor_auth_required,
833
- message: "2FA required.",
834
- type: "2FARequired",
835
- data: { error: "2FA required." }
836
- });
837
- }
838
- // Verify 2FA.
839
- const err = await this.verify_2fa(uid, code);
840
- if (err) {
841
- return stream.error({
842
- status: Status.unauthorized,
843
- message: "Invalid 2FA code.",
844
- type: "Invalid2FACode",
845
- invalid_fields: {
846
- "code": err,
847
- },
848
- });
849
- }
850
- }
851
- // Sign in.
852
- return await this._sign_in_response(stream, uid);
853
- }
854
- // console.log("singin 4 failed password");
855
- // Wait for the same time as it would time on avg to send a mail.
856
- await uniform_delay();
857
- // Unauthorized.
858
- return stream.error({
859
- status: Status.unauthorized,
860
- type: "Unauthorized",
861
- message: "Unauthorized.",
862
- invalid_fields: {
863
- "username": "Invalid or unrecognized username",
864
- "password": "Invalid or unrecognized password",
865
- }
866
- });
867
- }
868
- });
869
- // Sign out.
870
- this.server.endpoint({
871
- method: "POST",
872
- endpoint: "/volt/api/v1/auth/signout",
873
- content_type: "application/json",
874
- authenticated: true,
875
- rate_limit: "global",
876
- callback: async (stream) => {
877
- // Delete token.
878
- await this._deactivate_token(stream.uid);
879
- // Create headers.
880
- this._reset_cookies(stream);
881
- // Response.
882
- return stream.success({
883
- data: { message: "Successfully signed out." },
884
- });
885
- }
886
- });
887
- // Sign up.
888
- this.server.endpoint({
889
- method: "POST",
890
- endpoint: "/volt/api/v1/auth/signup",
891
- content_type: "application/json",
892
- rate_limit: [
893
- "global",
894
- { limit: 5, interval: 60 * 10, group: "volt/Users/signup" }
895
- ],
896
- params: {
897
- username: { type: "string", allow_empty: false },
898
- first_name: { type: "string", allow_empty: false },
899
- last_name: { type: "string", allow_empty: false },
900
- email: { type: "string", allow_empty: false },
901
- password: { type: "string", allow_empty: false },
902
- verify_password: { type: "string", allow_empty: false },
903
- phone_number: { type: "string", required: false },
904
- code: { type: "string", required: false },
905
- },
906
- callback: async (stream, params) => {
907
- console.log("signup 1", params);
908
- // Verify password.
909
- const { error, invalid_fields } = this._verify_new_pass(params.password, params.verify_password);
910
- if (error) {
911
- return stream.error({
912
- status: Status.bad_request,
913
- type: "InvalidParams",
914
- message: error,
915
- invalid_fields: invalid_fields ?? undefined,
916
- });
917
- }
918
- // Verify username and email.
919
- if (await this.username_exists(params.username)) {
920
- throw new ExternalError({
921
- type: "UsernameAlreadyExists",
922
- message: `Username "${params.username}" is already registered.`,
923
- status: Status.bad_request,
924
- invalid_fields: { "username": "Username is already registered" },
925
- });
926
- }
927
- if (await this.email_exists(params.email)) {
928
- throw new ExternalError({
929
- type: "EmailAlreadyExists",
930
- message: `Email "${params.email}" is already registered.`,
931
- status: Status.bad_request,
932
- invalid_fields: { "email": "Email is already registered" }
933
- });
934
- }
935
- // Verify 2fa.
936
- if (this.enable_2fa) {
937
- // Send 2FA.
938
- if (params.code == null || params.code == "") {
939
- // Send 2fa and add to avg time tracking.
940
- const start_time = Date.now();
941
- await this.send_2fa({
942
- _email: params.email,
943
- _username: params.username,
944
- stream,
945
- uid: undefined, // keep uid required param but use _email sys arg here.
946
- });
947
- // Add to avg time tracking.
948
- if (this.avg_send_2fa_time.length >= 10000) {
949
- this.avg_send_2fa_time.shift();
950
- }
951
- this.avg_send_2fa_time.push(Date.now() - start_time);
952
- // Send error.
953
- return stream.error({
954
- status: Status.two_factor_auth_required,
955
- message: "2FA required.",
956
- type: "TwoFactorAuthRequired",
957
- });
958
- }
959
- // Verify 2FA.
960
- const err = await this.verify_2fa(params.email, params.code);
961
- if (err) {
962
- return stream.error({
963
- status: Status.unauthorized,
964
- type: "Invalid2FACode",
965
- message: "Invalid 2FA code.",
966
- invalid_fields: {
967
- "code": err,
968
- },
969
- });
970
- }
971
- }
972
- // Create.
973
- let uid;
974
- try {
975
- uid = await this.create({
976
- // dont unpack params since we are performing param validation inside create().
977
- first_name: params.first_name,
978
- last_name: params.last_name,
979
- username: params.username,
980
- email: params.email,
981
- password: params.password,
982
- verify_password: params.verify_password,
983
- phone_number: params.phone_number,
984
- is_activated: true, // already verified by 2fa or no 2fa is enabled.
985
- _check_username_email: false, // already checked.
986
- });
987
- }
988
- catch (err) {
989
- return stream.error({
990
- status: Status.bad_request,
991
- type: "InvalidParams",
992
- message: err.message,
993
- invalid_fields: err.invalid_fields || {},
994
- });
995
- }
996
- // Sign in.
997
- return await this._sign_in_response(stream, uid);
998
- }
999
- });
1000
- // Activate account.
1001
- this.server.endpoint({
1002
- method: "POST",
1003
- endpoint: "/volt/api/v1/auth/activate",
1004
- content_type: "application/json",
1005
- rate_limit: "global",
1006
- params: {
1007
- code: "string",
1008
- },
1009
- callback: async (stream, params) => {
1010
- // Vars.
1011
- let uid = stream.uid;
1012
- // Get uid by cookie.
1013
- if (uid == null) {
1014
- uid = stream.cookies.UserID?.value; // ensure cookie is http-only since we rely on this for account activation before signin after signup.
1015
- if (!uid || uid === "null" || uid === "undefined" || uid === "-1") {
1016
- uid = undefined;
1017
- }
1018
- }
1019
- // Check uid.
1020
- if (uid == null) {
1021
- return stream.error({ status: Status.forbidden, message: "Permission denied." });
1022
- }
1023
- // Verify.
1024
- const err = await this.verify_2fa(uid, params.code);
1025
- if (err) {
1026
- return stream.error({
1027
- status: Status.forbidden,
1028
- message: "Permission denied.",
1029
- invalid_fields: {
1030
- "code": err,
1031
- },
1032
- });
1033
- }
1034
- // Set activated.
1035
- await this.set_activated(uid, true);
1036
- // Response.
1037
- await this._create_user_cookie(stream, uid);
1038
- return stream.success({ data: { message: "Successfully activated your account." } });
1039
- }
1040
- });
1041
- // Forgot password.
1042
- this.server.endpoint({
1043
- method: "POST",
1044
- endpoint: "/volt/api/v1/auth/forgot_password",
1045
- content_type: "application/json",
1046
- rate_limit: "global",
1047
- params: {
1048
- email: { type: "string", allow_empty: false },
1049
- code: { type: "string", allow_empty: false },
1050
- password: { type: "string", allow_empty: false },
1051
- verify_password: { type: "string", allow_empty: false },
1052
- },
1053
- callback: async (stream, params) => {
1054
- // Verify password.
1055
- const { error, invalid_fields } = this._verify_new_pass(params.password, params.verify_password);
1056
- if (error) {
1057
- return stream.error({
1058
- status: Status.bad_request,
1059
- message: error,
1060
- invalid_fields: invalid_fields ?? undefined,
1061
- });
1062
- }
1063
- // Get uid.
1064
- let uid;
1065
- if ((uid = await this.get_uid_by_email(params.email)) == null) {
1066
- return stream.error({ status: Status.forbidden, message: "Invalid email." });
1067
- }
1068
- // Verify 2fa.
1069
- const err = await this.verify_2fa(uid, params.code);
1070
- if (err) {
1071
- return stream.error({
1072
- status: Status.forbidden,
1073
- message: "Invalid 2FA code.",
1074
- invalid_fields: {
1075
- "code": "Invalid code"
1076
- },
1077
- });
1078
- }
1079
- // Set password.
1080
- await this.set_password(uid, params.password);
1081
- // Sign in.
1082
- return await this._sign_in_response(stream, uid);
1083
- }
1084
- });
1085
- // ---------------------------------------------------------
1086
- // Default user endpoints.
1087
- // Get user.
1088
- this.server.endpoint({
1089
- method: "GET",
1090
- endpoint: "/volt/api/v1/user",
1091
- content_type: "application/json",
1092
- authenticated: true,
1093
- rate_limit: "global",
1094
- params: {
1095
- // detailed: { type: "boolean", default: false },
1096
- },
1097
- callback: async (stream) => {
1098
- const user = await this.get(stream.uid);
1099
- // Mask sensitive data.
1100
- if (user.password) {
1101
- user.password = "*".repeat(user.password.length);
1102
- }
1103
- if (user.api_key) {
1104
- user.api_key = "*".repeat(user.api_key.length);
1105
- }
1106
- // Ensure string type for frontend scheme.
1107
- user.first_name ??= "";
1108
- user.last_name ??= "";
1109
- user.username ??= "";
1110
- user.email ??= "";
1111
- user.password ??= "";
1112
- // user.phone_number ??= ""; // its optional in response interface.
1113
- // user.api_key ??= ""; // its optional in response interface.
1114
- user.support_pin ??= "";
1115
- const frontend = {
1116
- uid: user.uid,
1117
- username: user.username ?? "",
1118
- first_name: user.first_name ?? "",
1119
- last_name: user.last_name ?? "",
1120
- email: user.email ?? "",
1121
- phone_number: user.phone_number, // optional
1122
- created_at: user.created_at,
1123
- support_pin: user.support_pin ?? "",
1124
- is_activated: user.is_activated === true,
1125
- has_api_key: Boolean(user.api_key),
1126
- };
1127
- return stream.success({ data: frontend });
1128
- }
1129
- });
1130
- // Set user.
1131
- this.server.endpoint({
1132
- method: "POST",
1133
- endpoint: "/volt/api/v1/user",
1134
- content_type: "application/json",
1135
- authenticated: true,
1136
- rate_limit: "global",
1137
- params: {
1138
- first_name: { type: "string", required: false, allow_empty: false },
1139
- last_name: { type: "string", required: false, allow_empty: false },
1140
- phone_number: { type: "string", required: false, allow_empty: false },
1141
- // is_activated:{ type: "boolean", required: false },
1142
- // password:{ type: "string", required: false }, // dont allow password.
1143
- username: { type: "string", required: false, allow_empty: false },
1144
- email: { type: "string", required: false, allow_empty: false },
1145
- },
1146
- callback: async (stream, params) => {
1147
- if (params.password != null) {
1148
- return stream.error({
1149
- status: Status.unauthorized,
1150
- message: "This endpoint does not allow for password changes.",
1151
- invalid_fields: {
1152
- password: "This endpoint does not allow for password changes.",
1153
- }
1154
- });
1155
- }
1156
- if (params.is_activated != null) {
1157
- return stream.error({
1158
- status: Status.unauthorized,
1159
- message: "This endpoint does not allow for user activation changes.",
1160
- invalid_fields: {
1161
- is_activated: "This endpoint does not allow for user activation changes.",
1162
- }
1163
- });
1164
- }
1165
- await this.set(stream.uid, {
1166
- first_name: params.first_name,
1167
- last_name: params.last_name,
1168
- phone_number: params.phone_number,
1169
- username: params.username,
1170
- email: params.email,
1171
- });
1172
- await this._sign_in_response(stream, stream.uid, { send: false });
1173
- return stream.success({ data: { message: "Successfully updated your account." } });
1174
- }
1175
- });
1176
- // Change password.
1177
- this.server.endpoint({
1178
- method: "POST",
1179
- endpoint: "/volt/api/v1/user/change_password",
1180
- content_type: "application/json",
1181
- authenticated: true,
1182
- rate_limit: "global",
1183
- params: {
1184
- current_password: { type: "string", allow_empty: false },
1185
- password: { type: "string", allow_empty: false },
1186
- verify_password: { type: "string", allow_empty: false },
1187
- },
1188
- callback: async (stream, params) => {
1189
- // Verify old password.
1190
- if (await this.verify_password(stream.uid, params.current_password) !== true) {
1191
- return stream.error({
1192
- status: Status.unauthorized,
1193
- message: "Incorrect password.",
1194
- invalid_fields: {
1195
- current_password: "Incorrect password.",
1196
- }
1197
- });
1198
- }
1199
- // Verify new password.
1200
- const { error, invalid_fields } = this._verify_new_pass(params.password, params.verify_password);
1201
- if (error) {
1202
- return stream.error({
1203
- status: Status.bad_request,
1204
- message: error,
1205
- invalid_fields: invalid_fields ?? undefined,
1206
- });
1207
- }
1208
- // Set password.
1209
- await this.set_password(stream.uid, params.password);
1210
- // Success.
1211
- return stream.success({
1212
- status: Status.success,
1213
- data: { message: "Successfully updated your password." },
1214
- });
1215
- }
1216
- });
1217
- // Delete account.
1218
- this.server.endpoint({
1219
- method: "DELETE",
1220
- endpoint: "/volt/api/v1/user",
1221
- content_type: "application/json",
1222
- authenticated: true,
1223
- rate_limit: "global",
1224
- callback: async (stream) => {
1225
- // Delete.
1226
- await this.delete(stream.uid);
1227
- // Reset cookies.
1228
- this._reset_cookies(stream);
1229
- // Success.
1230
- return stream.success({
1231
- status: Status.success,
1232
- data: { message: "Successfully deleted your account." },
1233
- });
1234
- }
1235
- });
1236
- // Generate API key.
1237
- this.server.endpoint({
1238
- method: "POST",
1239
- endpoint: "/volt/api/v1/user/api_key",
1240
- content_type: "application/json",
1241
- authenticated: true,
1242
- rate_limit: "global",
1243
- callback: async (stream) => {
1244
- return stream.success({
1245
- data: {
1246
- message: "Successfully generated an API key.",
1247
- api_key: await this.generate_api_key(stream.uid),
1248
- }
1249
- });
1250
- }
1251
- });
1252
- // Has API key.
1253
- this.server.endpoint({
1254
- method: "GET",
1255
- endpoint: "/volt/api/v1/user/has_api_key",
1256
- content_type: "application/json",
1257
- authenticated: true,
1258
- rate_limit: "global",
1259
- callback: async (stream) => {
1260
- return stream.success({
1261
- data: {
1262
- message: "Successfully checked your API key.",
1263
- has_api_key: await this.has_api_key(stream.uid),
1264
- }
1265
- });
1266
- }
1267
- });
1268
- // Revoke API key.
1269
- this.server.endpoint({
1270
- method: "DELETE",
1271
- endpoint: "/volt/api/v1/user/api_key",
1272
- content_type: "application/json",
1273
- authenticated: true,
1274
- rate_limit: "global",
1275
- callback: async (stream) => {
1276
- await this.revoke_api_key(stream.uid);
1277
- return stream.send({
1278
- status: Status.success,
1279
- data: { message: "Successfully revoked your API key." },
1280
- });
1281
- }
1282
- });
1283
- /**
1284
- * Initialize a document query for the public/protected/private user data.
1285
- * @returns The initialzied query upon success, or `false` is an error has been sent through the stream.
1286
- */
1287
- const init_user_data_query = (stream, uid, query) => {
1288
- if (typeof query === "object") {
1289
- if ("uid" in query) {
1290
- return stream.error({
1291
- message: "Invalid query parameter, the 'uid' field is not allowed.",
1292
- type: "invalid_query_parameter",
1293
- status: Status.bad_request,
1294
- invalid_fields: {
1295
- query: "Invalid query parameter, the 'uid' field is not allowed.",
1296
- }
1297
- });
1298
- }
1299
- if ("data" in query) {
1300
- return stream.error({
1301
- message: "Invalid query parameter, the 'data' field is not allowed.",
1302
- type: "invalid_query_parameter",
1303
- status: Status.bad_request,
1304
- invalid_fields: {
1305
- query: "Invalid query parameter, the 'data' field is not allowed.",
1306
- }
1307
- });
1308
- }
1309
- if ("query" in query) {
1310
- return stream.error({
1311
- message: "Invalid query parameter, the 'query' field is not allowed.",
1312
- type: "invalid_query_parameter",
1313
- status: Status.bad_request,
1314
- invalid_fields: {
1315
- query: "Invalid query parameter, the 'query' field is not allowed.",
1316
- }
1317
- });
1318
- }
1319
- if ("_id" in query) {
1320
- return stream.error({
1321
- message: "Invalid query parameter, the '_id' field is not allowed.",
1322
- type: "invalid_query_parameter",
1323
- status: Status.bad_request,
1324
- invalid_fields: {
1325
- query: "Invalid query parameter, the '_id' field is not allowed.",
1326
- }
1327
- });
1328
- }
1329
- }
1330
- return typeof query === "string"
1331
- ? { uid, query: query }
1332
- : { ...query, uid: uid };
1333
- };
1334
- // Load data.
1335
- this.server.endpoint({
1336
- method: "GET",
1337
- endpoint: "/volt/api/v1/user/data",
1338
- content_type: "application/json",
1339
- authenticated: true,
1340
- rate_limit: "global",
1341
- params: {
1342
- query: { type: ["string", "object"], allow_empty: false },
1343
- default: { type: Users.Endpoints.JsonValueSchemaType, required: false },
1344
- },
1345
- callback: async (stream, params) => {
1346
- const query = init_user_data_query(stream, stream.uid, params.query);
1347
- if (!query)
1348
- return;
1349
- try {
1350
- const document = await this.public.load(query, {
1351
- default: params.default
1352
- ? { ...query, data: params.default }
1353
- : undefined,
1354
- retry: 3,
1355
- });
1356
- return stream.send({
1357
- status: Status.success,
1358
- data: {
1359
- message: "Successfully loaded the requested document.",
1360
- data: document.data,
1361
- },
1362
- });
1363
- }
1364
- catch (e) {
1365
- if (e instanceof Collection.NotFoundError) {
1366
- return stream.error({
1367
- message: "Document not found.",
1368
- type: "document_not_found",
1369
- status: Status.not_found,
1370
- });
1371
- }
1372
- throw e;
1373
- }
1374
- }
1375
- });
1376
- // Set data.
1377
- this.server.endpoint({
1378
- method: "POST",
1379
- endpoint: "/volt/api/v1/user/data",
1380
- content_type: "application/json",
1381
- authenticated: true,
1382
- rate_limit: "global",
1383
- params: {
1384
- query: { type: ["string", "object"], allow_empty: false },
1385
- data: { type: Users.Endpoints.JsonValueSchemaType },
1386
- },
1387
- callback: async (stream, params) => {
1388
- const query = init_user_data_query(stream, stream.uid, params.query);
1389
- if (!query)
1390
- return;
1391
- await this.public.set(query, { data: params.data }, { retry: 3, flatten: true });
1392
- return stream.send({
1393
- status: Status.success,
1394
- data: { message: "Successfully saved." },
1395
- });
1396
- }
1397
- });
1398
- // Delete data.
1399
- this.server.endpoint({
1400
- method: "DELETE",
1401
- endpoint: "/volt/api/v1/user/data",
1402
- content_type: "application/json",
1403
- authenticated: true,
1404
- rate_limit: "global",
1405
- params: {
1406
- query: { type: ["string", "object"], allow_empty: false },
1407
- },
1408
- callback: async (stream, params) => {
1409
- const query = init_user_data_query(stream, stream.uid, params.query);
1410
- if (!query)
1411
- return;
1412
- await this.public.delete(query);
1413
- return stream.send({
1414
- status: Status.success,
1415
- data: { message: "Successfully deleted." },
1416
- });
1417
- }
1418
- });
1419
- // Load protected data.
1420
- this.server.endpoint({
1421
- method: "GET",
1422
- endpoint: "/volt/api/v1/user/data/protected",
1423
- content_type: "application/json",
1424
- authenticated: true,
1425
- rate_limit: "global",
1426
- params: {
1427
- query: { type: ["string", "object"], allow_empty: false },
1428
- default: { type: Users.Endpoints.JsonValueSchemaType, required: false },
1429
- },
1430
- callback: async (stream, params) => {
1431
- const query = init_user_data_query(stream, stream.uid, params.query);
1432
- if (!query)
1433
- return;
1434
- try {
1435
- const document = await this.protected.load(query, {
1436
- default: params.default
1437
- ? { ...query, data: params.default }
1438
- : undefined,
1439
- retry: 3,
1440
- });
1441
- return stream.send({
1442
- status: Status.success,
1443
- data: {
1444
- message: "Successfully loaded the requested document.",
1445
- data: document.data,
1446
- },
1447
- });
1448
- }
1449
- catch (e) {
1450
- if (e instanceof Collection.NotFoundError) {
1451
- return stream.error({
1452
- message: "Document not found.",
1453
- type: "document_not_found",
1454
- status: Status.not_found,
1455
- });
1456
- }
1457
- throw e;
1458
- }
1459
- }
1460
- });
1461
- // ---------------------------------------------------------
1462
- // Default support endpoints.
1463
- // Get PIN.
1464
- this.server.endpoint({
1465
- method: "GET",
1466
- endpoint: "/volt/api/v1/support/pin",
1467
- content_type: "application/json",
1468
- authenticated: true,
1469
- rate_limit: "global",
1470
- callback: async (stream) => {
1471
- // Sign in.
1472
- const pin = await this.get_support_pin(stream.uid);
1473
- return stream.success({
1474
- data: {
1475
- message: "Successfully retrieved your support PIN.",
1476
- pin: pin,
1477
- }
1478
- });
1479
- }
1480
- });
1481
- // Support.
1482
- this.server.endpoint({
1483
- method: "POST",
1484
- endpoint: "/volt/api/v1/support/submit",
1485
- content_type: "application/json",
1486
- rate_limit: [
1487
- "global",
1488
- {
1489
- interval: 3600 * 24,
1490
- limit: 5,
1491
- },
1492
- ],
1493
- params: {
1494
- subject: { type: "string", required: false, allow_empty: false },
1495
- type: { type: "string", required: false, allow_empty: false },
1496
- support_pin: { type: "string", required: false, allow_empty: false },
1497
- email: { type: "string", required: false, allow_empty: false },
1498
- first_name: { type: "string", required: false, allow_empty: false },
1499
- last_name: { type: "string", required: false, allow_empty: false },
1500
- summary: { type: "string", required: true, allow_empty: false },
1501
- detailed: { type: "string", required: false, allow_empty: false },
1502
- attachments: { type: "array", required: false, value_schema: {
1503
- type: "object",
1504
- schema: Mail.Attachment.RestAPI.Schema
1505
- } },
1506
- },
1507
- callback: async (stream, params) => {
1508
- // Check recipient.
1509
- if (!this.support_recipient) {
1510
- throw new ExternalError({
1511
- status: Status.unavailable_for_legal_reasons,
1512
- type: "NoSMTPSender", message: "This server does not have a SMTP sender configured."
1513
- });
1514
- }
1515
- this.server.assert_mail();
1516
- // When unauthenticated get contact params.
1517
- let user = null, email, first_name, last_name;
1518
- if (stream.uid == null) {
1519
- try {
1520
- email = stream.param("email");
1521
- first_name = stream.param("first_name");
1522
- last_name = stream.param("last_name");
1523
- }
1524
- catch (err) {
1525
- return stream.error({ status: Status.bad_request, message: err.message });
1526
- }
1527
- }
1528
- else {
1529
- user = await this.get(stream.uid);
1530
- email = user.email;
1531
- first_name = user.first_name;
1532
- last_name = user.last_name;
1533
- }
1534
- // Create mail body.
1535
- let body = "";
1536
- const subject = params.subject || (params.type == null ? "Support" : `Support ${params.type}`);
1537
- body += `<h1>${subject}</h1>`;
1538
- if (params.type) {
1539
- body += `<span style='font-weight: bold'>Type</span>: ${params.type}<br>`;
1540
- }
1541
- if (user) {
1542
- body += `<span style='font-weight: bold'>UID</span>: ${stream.uid}<br>`;
1543
- body += `<span style='font-weight: bold'>User</span>: ${user.username}<br>`;
1544
- }
1545
- body += `<span style='font-weight: bold'>Email</span>: ${email}<br>`;
1546
- body += `<span style='font-weight: bold'>First Name</span>: ${first_name}<br>`;
1547
- body += `<span style='font-weight: bold'>Last Name</span>: ${last_name}<br>`;
1548
- if (stream.uid != null) {
1549
- const support_pin = await this.get_support_pin(stream.uid);
1550
- body += `<span style='font-weight: bold'>Support PIN</span>: ${support_pin} <span style='color: green'>verified</span><br>`;
1551
- }
1552
- else if (params.support_pin) {
1553
- body += `<span style='font-weight: bold'>Support PIN</span>: ${params.support_pin} <span style='color: red'>not yet verified</span><br>`;
1554
- }
1555
- else {
1556
- body += `<span style='font-weight: bold'>Support PIN</span>: Unknown<br>`;
1557
- }
1558
- if (params.summary) {
1559
- body += `<br><span style='font-weight: bold'>Summary</span>:<br>${params.summary}<br>`;
1560
- }
1561
- if (params.detailed) {
1562
- body += `<br><span style='font-weight: bold'>Detailed</span>:<br>${params.detailed}<br>`;
1563
- }
1564
- for (const key of Object.keys(params)) {
1565
- switch (key) {
1566
- case "subject":
1567
- case "type":
1568
- case "support_pin":
1569
- case "summary":
1570
- case "detailed":
1571
- case "attachments":
1572
- case "recipient":
1573
- continue;
1574
- default:
1575
- body += `<br><span style='font-weight: bold'>${key}</span>: ${params[key]}<br>`;
1576
- }
1577
- }
1578
- body += "<br>";
1579
- // Send email.
1580
- await this.server.mail.send({
1581
- // Only send to support_recipient since we dont want users/people to send emails to random people.
1582
- recipients: [this.support_recipient],
1583
- subject: subject,
1584
- body: body,
1585
- attachments: params.attachments,
1586
- max_attachments_size: 5 * 1024 * 1024, // 5 MB
1587
- allow_untrusted_urls: false,
1588
- });
1589
- // Sign in.
1590
- return stream.success({
1591
- data: { message: "Successfully sent your request." }
1592
- });
1593
- }
1594
- });
1595
- }
1596
- }
1597
- // ---------------------------------------------------------
1598
- // Public methods.
1599
- // ---------------------------------------------------------
1600
- /**
1601
- * Validate a UID against ASCII charset and allowed lengths (current + legacy).
1602
- * @dev_warning
1603
- * If you change {@link Users.UID_CHARSET} or {@link Users.UID_LENGTH},
1604
- * update {@link Users.LEGACY_UID_LENGTHS} for backward compatibility.
1605
- *
1606
- * @docs
1607
- */
1608
- is_valid_uid(uid) {
1609
- const len = uid.length; // ASCII-only, so code units == chars
1610
- if (len !== Users.UID_LENGTH) {
1611
- let ok = false;
1612
- for (let i = 0; i < Users.LEGACY_UID_LENGTHS.length; i++) {
1613
- if (len === Users.LEGACY_UID_LENGTHS[i]) {
1614
- ok = true;
1615
- break;
1616
- }
1617
- }
1618
- if (!ok)
1619
- return false;
1620
- }
1621
- const allow = Users.UID_ALLOW;
1622
- for (let i = 0; i < len; i++) {
1623
- const code = uid.charCodeAt(i);
1624
- if (code >= 128 || allow[code] === 0)
1625
- return false;
1626
- }
1627
- return true;
1628
- }
1629
- /**
1630
- * Check if a uid exists.
1631
- * @param uid The user ID to check.
1632
- * @returns True if a user with the given uid exists.
1633
- *
1634
- * @docs
1635
- */
1636
- async uid_exists(uid) {
1637
- return await this._users_db.exists({ uid });
1638
- }
1639
- /**
1640
- * Check if a username exists.
1641
- * @returns Returns a boolean indicating whether the username exists or not.
1642
- * @param username The username to check.
1643
- * @example
1644
- * const exists = await server.users.username_exists("someusername");
1645
- *
1646
- * @docs
1647
- */
1648
- async username_exists(username) {
1649
- return await this._users_db.exists({ username });
1650
- }
1651
- /**
1652
- * Check if an email exists.
1653
- * @returns Returns a boolean indicating whether the email exists or not.
1654
- * @param email The email to check.
1655
- * @example
1656
- * const exists = await server.users.email_exists("some@email.com");
1657
- *
1658
- * @docs
1659
- */
1660
- async email_exists(email) {
1661
- return await this._users_db.exists({ email });
1662
- }
1663
- /**
1664
- * Check if a user account is activated.
1665
- * @returns Returns a boolean indicating whether the account is activated or not.
1666
- * @param uid The id of the user.
1667
- * @example
1668
- * const activated = await server.users.is_activated("0");
1669
- *
1670
- * @docs
1671
- */
1672
- async is_activated(uid) {
1673
- return (await this.get(uid)).is_activated === true;
1674
- }
1675
- /**
1676
- * Set the activated status of a user account.
1677
- * @param uid The user id.
1678
- * @param is_activated The boolean with the new activated status.
1679
- * @example
1680
- * await server.users.set_activated("1", true);
1681
- *
1682
- * @docs
1683
- */
1684
- async set_activated(uid, is_activated) {
1685
- await this._sys_set(uid, { is_activated: is_activated });
1686
- }
1687
- /**
1688
- * Create a user account. Only the hashed password will be saved.
1689
- * @returns Returns the uid of the newly created user.
1690
- * @param first_name The user's first name.
1691
- * @param last_name The user's last name.
1692
- * @param username The username of the new account.
1693
- * @param email The email of the new account.
1694
- * @param password The password of the new account.
1695
- * @param verify_password An optional second password input to check against the first input to ensure its the same.
1696
- * @param phone_number The phone number of the user account.
1697
- * @param is_activated Whether the account should be set to activated; by default `!Server.enable_account_activation`.
1698
- * @example
1699
- * const uid = await server.users.create({
1700
- * first_name: "John",
1701
- * last_name: "Doe",
1702
- * username: "johndoe",
1703
- * email: "johndoe@email.com",
1704
- * password: "HelloWorld!"
1705
- * });
1706
- *
1707
- * @docs
1708
- */
1709
- async create({ first_name, last_name, username, email, password, verify_password, phone_number = "", is_activated = undefined, _check_username_email = false, }) {
1710
- // Verify params.
1711
- vlib.schema.validate(arguments[0], {
1712
- unknown: false,
1713
- throw: true,
1714
- schema: {
1715
- first_name: "string",
1716
- last_name: "string",
1717
- username: "string",
1718
- email: "string",
1719
- password: "string",
1720
- verify_password: { type: "string", required: false },
1721
- phone_number: { type: "string", required: false },
1722
- is_activated: { type: "boolean", required: false },
1723
- _check_username_email: { type: "boolean", required: false },
1724
- }
1725
- });
1726
- // Verify password.
1727
- const { error, invalid_fields } = this._verify_new_pass(password, verify_password ?? password);
1728
- if (error) {
1729
- throw new ExternalError({
1730
- type: "InvalidPassword",
1731
- message: `Invalid password: ${error}.`,
1732
- status: Status.bad_request,
1733
- invalid_fields,
1734
- });
1735
- }
1736
- // Check if username & email already exist.
1737
- if (_check_username_email) {
1738
- if (await this.username_exists(username)) {
1739
- throw new ExternalError({
1740
- type: "UsernameAlreadyExists",
1741
- message: `Username "${username}" is already registered.`,
1742
- status: Status.bad_request,
1743
- invalid_fields: { "username": "Username is already registered" },
1744
- });
1745
- }
1746
- if (await this.email_exists(email)) {
1747
- throw new ExternalError({
1748
- type: "EmailAlreadyExists",
1749
- message: `Email "${email}" is already registered.`,
1750
- status: Status.bad_request,
1751
- invalid_fields: { "email": "Email is already registered" }
1752
- });
1753
- }
1754
- }
1755
- // Generate a uid.
1756
- const uid = await this._generate_uid();
1757
- // Create the user.
1758
- const user = {
1759
- uid,
1760
- first_name,
1761
- last_name,
1762
- username,
1763
- email,
1764
- password: await this._hash_password(password),
1765
- phone_number,
1766
- created_at: Date.now(),
1767
- api_key: undefined, // api key can be undefined, it doesnt have to be set.
1768
- support_pin: this._generate_code(8),
1769
- is_activated: is_activated ?? !this.enable_account_activation,
1770
- };
1771
- await this._users_db.set({ uid }, user);
1772
- // Execute event callbacks.
1773
- for (const cb of this.server.events.get("create_user")) {
1774
- try {
1775
- await cb({ user });
1776
- }
1777
- catch (err) {
1778
- this.server.log.error(new Error(`Encountered an error in event callback "create_user".`, { cause: err }));
1779
- }
1780
- }
1781
- // Response.
1782
- return uid;
1783
- }
1784
- /**
1785
- * Delete a user account and associated data.
1786
- * @param uid The user id.
1787
- * @example
1788
- * await server.users.delete("0");
1789
- *
1790
- * @docs
1791
- */
1792
- async delete(uid) {
1793
- // Load the user to verify it exists and to pass it to the callback.
1794
- const user = await this.get(uid);
1795
- if (!user) {
1796
- throw new ExternalError({ status: Status.not_found, type: "UserNotFound", message: `User with uid "${uid}" not found.` });
1797
- }
1798
- // Delete the user from all collections.
1799
- await this._users_db.delete_many({ uid });
1800
- await this._tokens_db.delete_many({ uid });
1801
- await this._2fa_tokens_db.delete_many({ uid });
1802
- await this.public.delete_many({ uid });
1803
- await this.protected.delete_many({ uid });
1804
- await this.private.delete_many({ uid });
1805
- if (this.server.payments !== undefined) {
1806
- await this.server.payments.delete_user(uid);
1807
- }
1808
- // Execute event callbacks.
1809
- for (const cb of this.server.events.get("delete_user")) {
1810
- try {
1811
- await cb({ user });
1812
- }
1813
- catch (err) {
1814
- this.server.log.error(new Error(`Encountered an error in event callback "delete_user".`, { cause: err }));
1815
- }
1816
- }
1817
- }
1818
- /**
1819
- * Set a user's first name. Throws if uid does not exist.
1820
- * @param uid The user id.
1821
- * @param first_name The new first name.
1822
- * @example
1823
- * await server.users.set_first_name("1", "John");
1824
- *
1825
- * @docs
1826
- */
1827
- async set_first_name(uid, first_name) {
1828
- await this._sys_set(uid, { first_name });
1829
- }
1830
- /**
1831
- * Set a user's last name. Throws if uid does not exist.
1832
- * @param uid The user id.
1833
- * @param last_name The new last name.
1834
- * @example
1835
- * await server.users.set_last_name("1", "Doe");
1836
- *
1837
- * @docs
1838
- */
1839
- async set_last_name(uid, last_name) {
1840
- await this._sys_set(uid, { last_name });
1841
- }
1842
- /**
1843
- * Set a user's username. Throws if uid does not exist.
1844
- * @param uid The user id.
1845
- * @param username The new username.
1846
- * @example
1847
- * await server.users.set_username("1", "newusername");
1848
- *
1849
- * @docs
1850
- */
1851
- async set_username(uid, username) {
1852
- if (await this.username_exists(username)) {
1853
- throw Error(`Username "${username}" already exists.`);
1854
- }
1855
- await this._sys_set(uid, { username });
1856
- }
1857
- /**
1858
- * Set a user's email. Throws if uid does not exist.
1859
- * @param uid The user id.
1860
- * @param email The new email.
1861
- * @example
1862
- * await server.users.set_email("1", "new@email.com");
1863
- *
1864
- * @docs
1865
- */
1866
- async set_email(uid, email) {
1867
- if (await this.email_exists(email)) {
1868
- throw Error(`Email "${email}" already exists.`);
1869
- }
1870
- await this._sys_set(uid, { email });
1871
- }
1872
- /**
1873
- * Set a user's password. Throws on invalid input or unknown uid.
1874
- * @param uid The user id.
1875
- * @param password The new password.
1876
- * @example
1877
- * await server.users.set_password("1", "XXXXXX");
1878
- *
1879
- * @docs
1880
- */
1881
- async set_password(uid, password, verify_password) {
1882
- const { error } = this._verify_new_pass(password, verify_password ?? password);
1883
- if (error) {
1884
- throw Error(`Invalid password "${password}": ${error}.`);
1885
- }
1886
- await this._sys_set(uid, { password: await this._hash_password(password) });
1887
- }
1888
- /**
1889
- * Update an existing user object.
1890
- *
1891
- * This function only updates the passed user attributes, unpresent attributes will not be deleted.
1892
- *
1893
- * If the uid does not exist an `Error` will be thrown.
1894
- *
1895
- * A password will automatically be hashed if passed.
1896
- *
1897
- * Updating the API key through this function is not allowed (wont work).
1898
- *
1899
- * @warning Does not upsert documents.
1900
- *
1901
- * @docs
1902
- */
1903
- async set(uid, data) {
1904
- let old_data;
1905
- const set_data = {};
1906
- for (const key of Object.keys(data)) {
1907
- if (data[key] === undefined)
1908
- continue;
1909
- switch (key) {
1910
- case "first_name":
1911
- case "last_name":
1912
- case "phone_number":
1913
- if (!data[key]) {
1914
- throw Error(`Invalid ${key.replaceAll("_", " ")} "${data[key]}".`);
1915
- }
1916
- set_data[key] = data[key];
1917
- break;
1918
- case "is_activated":
1919
- set_data[key] = data[key];
1920
- break;
1921
- case "password": {
1922
- if (!data[key]) {
1923
- throw Error(`Password may not be empty.`);
1924
- }
1925
- const { error } = this._verify_new_pass(data[key], data[key]);
1926
- if (error) {
1927
- throw Error(`Invalid password "${data[key]}": ${error}.`);
1928
- }
1929
- set_data[key] = await this._hash_password(data[key]);
1930
- break;
1931
- }
1932
- case "username":
1933
- if (!data.username) {
1934
- throw Error(`Invalid username "${data.username}".`);
1935
- }
1936
- if (old_data === undefined) {
1937
- old_data = await this.get(uid);
1938
- }
1939
- if (old_data.username !== data.username) {
1940
- if (await this.username_exists(data.username)) {
1941
- throw Error(`Username "${data.username}" already exists.`);
1942
- }
1943
- set_data[key] = data[key];
1944
- }
1945
- break;
1946
- case "email":
1947
- if (!data.email) {
1948
- throw Error(`Invalid email "${data.email}".`);
1949
- }
1950
- if (old_data === undefined) {
1951
- old_data = await this.get(uid);
1952
- }
1953
- if (old_data.email !== data.email) {
1954
- if (await this.email_exists(data.email)) {
1955
- throw Error(`Email "${data.email}" already exists.`);
1956
- }
1957
- set_data[key] = data[key];
1958
- }
1959
- break;
1960
- default:
1961
- // delete all other keys, such as uid, api_key etc.
1962
- delete set_data[key];
1963
- break;
1964
- }
1965
- }
1966
- await this._users_db.set({ uid }, set_data, { upsert: false });
1967
- }
1968
- /**
1969
- * Insert new data into an EXISTING user.
1970
- * @warning Does not upsert documents.
1971
- */
1972
- async _sys_set(uid, data) {
1973
- await this._users_db.set({ uid }, data, { upsert: false });
1974
- }
1975
- /**
1976
- * Get a user by uid. Throws if the uid does not exist.
1977
- * @returns Returns a User object.
1978
- * @param uid The user id.
1979
- * @throws {Collection.NotFoundError} If the user id does not exist.
1980
- * @example
1981
- * const user = await server.users.get("0");
1982
- *
1983
- * @docs
1984
- */
1985
- async get(uid) {
1986
- return await this._users_db.load({ uid });
1987
- }
1988
- /**
1989
- * Get a user by username. Throws if the username does not exist.
1990
- * @returns Returns a User object.
1991
- * @param username The username of the user to fetch.
1992
- * @throws {Collection.NotFoundError} If the username does not exist.
1993
- * @example
1994
- * const user = await server.users.get_by_username("myusername");
1995
- *
1996
- * @docs
1997
- */
1998
- async get_by_username(username) {
1999
- return await this._users_db.load({ username });
2000
- }
2001
- /**
2002
- * Get a user by uid or username.
2003
- * This function can be used if you have a variable which can be both.
2004
- * Throws if the username does not exist.
2005
- * @returns Returns a User object.
2006
- * @param username The username of the user to fetch.
2007
- * @throws {Collection.NotFoundError} If the username or uid does not exist.
2008
- * @example
2009
- * const user = await server.users.get_by_username("myusername");
2010
- *
2011
- * @docs
2012
- */
2013
- async get_by_uid_or_username(uid_or_username) {
2014
- return await this._users_db.load({
2015
- $or: [
2016
- { uid: uid_or_username },
2017
- { username: uid_or_username },
2018
- ],
2019
- });
2020
- }
2021
- /**
2022
- * Get a user by email. Throws if the email does not exist.
2023
- * @returns Returns a User object.
2024
- * @param email The email of the user to fetch.
2025
- * @throws {Collection.NotFoundError} If the email does not exist.
2026
- * @example
2027
- * const user = await server.users.get_by_email("my@email.com");
2028
- *
2029
- * @docs
2030
- */
2031
- async get_by_email(email) {
2032
- return await this._users_db.load({ email });
2033
- }
2034
- /**
2035
- * Get a user by API key. Throws if invalid.
2036
- * @returns Returns a User object.
2037
- * @param api_key The API key of the user to fetch.
2038
- * @example
2039
- * const user = await server.users.get_by_api_key("XXXXXX");
2040
- *
2041
- * @docs
2042
- */
2043
- async get_by_api_key(api_key) {
2044
- const uid = this.get_uid_by_api_key(api_key);
2045
- if (!uid)
2046
- throw new Error("Unable to find a user by api key.");
2047
- const user = await this.get(uid);
2048
- const ok = await this.verify_api_key_by_uid(uid, api_key);
2049
- if (!ok)
2050
- throw new Error("Unable to find a user by api key.");
2051
- return user;
2052
- // DELETED Cannot search by re-hash ofcourse.
2053
- // const data = await this._users_db.find({ api_key: await this._hash_password(api_key) });
2054
- // if (data == null) { throw new Error(`Unable to find a user by api key "${api_key}".`); }
2055
- // return data;
2056
- }
2057
- /**
2058
- * Get a user by token. Throws if invalid.
2059
- * @returns Returns a User object.
2060
- * @param token The authentication token of the user to fetch.
2061
- * @example
2062
- * const user = await server.users.get_by_token("XXXXXX");
2063
- *
2064
- * @docs
2065
- */
2066
- async get_by_token(token) {
2067
- const uid = this.get_uid_by_token(token);
2068
- if (!uid)
2069
- throw new Error("Unable to find a user by token.");
2070
- const ok = await this.verify_token_by_uid(uid, token);
2071
- if (!ok)
2072
- throw new Error("Unable to find a user by token.");
2073
- return await this.get(uid);
2074
- // DELETED Cannot search by re-hash ofcourse.
2075
- // const data = await this._tokens_db.find({ token: await this._hash_password(token) });
2076
- // if (data == null) { throw new Error(`Unable to find a user by token "${token}".`); }
2077
- // return await this.get(data.uid);
2078
- }
2079
- /**
2080
- * Get a uid by username.
2081
- * @returns Returns the uid of the username, or undefined if not found.
2082
- * @param username The username of the uid to fetch.
2083
- * @example
2084
- * const uid = await server.users.get_uid("myusername");
2085
- *
2086
- * @docs
2087
- */
2088
- async get_uid(username) {
2089
- try {
2090
- return (await this.get_by_username(username)).uid;
2091
- }
2092
- catch (e) {
2093
- return undefined;
2094
- }
2095
- }
2096
- /**
2097
- * Get a uid by username.
2098
- * @returns Returns the uid of the username, or undefined if not found.
2099
- * @param username The username of the uid to fetch.
2100
- * @example
2101
- * const uid = await server.users.get_uid_by_username("myuser");
2102
- *
2103
- * @docs
2104
- */
2105
- async get_uid_by_username(username) {
2106
- try {
2107
- return (await this.get_by_username(username)).uid;
2108
- }
2109
- catch (e) {
2110
- return undefined;
2111
- }
2112
- }
2113
- /**
2114
- * Get a uid by email.
2115
- * @returns Returns the uid of the email, or undefined if not found.
2116
- * @param email The email of the uid to fetch.
2117
- * @example
2118
- * const uid = await server.users.get_uid_by_email("my@email.com");
2119
- *
2120
- * @docs
2121
- */
2122
- async get_uid_by_email(email) {
2123
- try {
2124
- return (await this.get_by_email(email)).uid;
2125
- }
2126
- catch (e) {
2127
- return undefined;
2128
- }
2129
- }
2130
- /**
2131
- * Get a uid by API key.
2132
- * @returns Returns the uid for the API key, or undefined if not valid.
2133
- * @param api_key The API key to parse.
2134
- * @example
2135
- * const uid = server.users.get_uid_by_api_key("XXXXXXXXXX");
2136
- *
2137
- * @docs
2138
- */
2139
- get_uid_by_api_key(api_key) {
2140
- return this._parse_uid_from_token_api_key(api_key, "ak_");
2141
- }
2142
- /**
2143
- * Get a uid by token.
2144
- * @returns Returns the uid for the token, or undefined if not valid.
2145
- * @param token The token to parse.
2146
- * @example
2147
- * const uid = server.users.get_uid_by_token("XXXXXXXXXX");
2148
- *
2149
- * @docs
2150
- */
2151
- get_uid_by_token(token) {
2152
- return this._parse_uid_from_token_api_key(token, "tk_");
2153
- }
2154
- /**
2155
- * Get a user's support pin by uid.
2156
- * @returns Returns the support PIN string.
2157
- * @param uid The user id.
2158
- * @example
2159
- * const pin = await server.users.get_support_pin("1");
2160
- *
2161
- * @docs
2162
- */
2163
- async get_support_pin(uid) {
2164
- return (await this.get(uid)).support_pin;
2165
- }
2166
- /**
2167
- * Generate an API key for a user and store its hash. Overwrites existing keys.
2168
- * @returns Returns the API key string (plaintext).
2169
- * @param uid The user id.
2170
- * @example
2171
- * const api_key = await server.users.generate_api_key("0");
2172
- *
2173
- * @docs
2174
- */
2175
- async generate_api_key(uid) {
2176
- const api_key = this._generate_api_key(uid);
2177
- await this._sys_set(uid, { api_key: await this._hash_password(api_key) });
2178
- return api_key;
2179
- }
2180
- /**
2181
- * Check if a user has a generated API key.
2182
- * @returns Returns a boolean indicating whether the user has an API key.
2183
- * @param uid The user id.
2184
- * @throws {Collection.NotFoundError} If the user id does not exist.
2185
- * @example
2186
- * const has_api_key = await server.users.has_api_key("0");
2187
- *
2188
- * @docs
2189
- */
2190
- async has_api_key(uid) {
2191
- const data = await this._users_db.load({ uid }, {
2192
- projection: { api_key: 1 }
2193
- });
2194
- return data.api_key != null && data.api_key.length > 0;
2195
- }
2196
- /**
2197
- * Revoke the API key of a user.
2198
- * @param uid The user id.
2199
- * @example
2200
- * await server.users.revoke_api_key("0");
2201
- *
2202
- * @docs
2203
- */
2204
- async revoke_api_key(uid) {
2205
- await this._users_db.save({ uid }, { $unset: { api_key: "" } }, { upsert: false });
2206
- }
2207
- /**
2208
- * Verify a plaintext password.
2209
- * @returns Returns a boolean indicating whether the verification was successful.
2210
- * @param uid The user id.
2211
- * @param password The plaintext password.
2212
- * @example
2213
- * const success = await server.users.verify_password("1", "XXXXXX");
2214
- *
2215
- * @docs
2216
- */
2217
- async verify_password(uid, password) {
2218
- try {
2219
- const user = await this.get(uid);
2220
- return user.uid != null && await this._verify_password(password, user.password);
2221
- }
2222
- catch (err) {
2223
- return false;
2224
- }
2225
- }
2226
- /**
2227
- * Verify a plaintext API key.
2228
- * @returns Returns a boolean indicating whether the verification was successful.
2229
- * @param api_key The api key to verify.
2230
- * @example
2231
- * const success = await server.users.verify_api_key("XXXXXX");
2232
- *
2233
- * @docs
2234
- */
2235
- async verify_api_key(api_key) {
2236
- return await this.verify_api_key_by_uid(this.get_uid_by_api_key(api_key), api_key);
2237
- }
2238
- /**
2239
- * Verify a plaintext API key by uid.
2240
- * @returns Returns a boolean indicating whether the verification was successful.
2241
- * @param uid The user id.
2242
- * @param api_key The api key to verify.
2243
- * @example
2244
- * const success = await server.users.verify_api_key_by_uid("1", "XXXXXX");
2245
- *
2246
- * @docs
2247
- */
2248
- async verify_api_key_by_uid(uid, api_key) {
2249
- try {
2250
- if (!uid)
2251
- return false;
2252
- const user = await this.get(uid);
2253
- return user.uid != null && user.api_key != null && user.api_key?.length > 0
2254
- && await this._verify_password(api_key, user.api_key);
2255
- }
2256
- catch (err) {
2257
- return false;
2258
- }
2259
- }
2260
- /**
2261
- * Verify a plaintext token.
2262
- * @returns Returns a boolean indicating whether the verification was successful.
2263
- * @param token The token to verify.
2264
- * @example
2265
- * const success = await server.users.verify_token("XXXXXX");
2266
- *
2267
- * @docs
2268
- */
2269
- async verify_token(token) {
2270
- return await this.verify_token_by_uid(this.get_uid_by_token(token), token);
2271
- }
2272
- /**
2273
- * Verify a plaintext token by uid.
2274
- * @returns Returns a boolean indicating whether the verification was successful.
2275
- * @param uid The user id.
2276
- * @param token The token to verify.
2277
- * @example
2278
- * const success = await server.users.verify_token_by_uid("1", "XXXXXX");
2279
- *
2280
- * @docs
2281
- */
2282
- async verify_token_by_uid(uid, token) {
2283
- try {
2284
- if (!uid)
2285
- return false;
2286
- const correct_token = await this._tokens_db.load({ uid });
2287
- return (correct_token != null &&
2288
- correct_token.token != null &&
2289
- correct_token.active !== false &&
2290
- Date.now() < correct_token.expiration &&
2291
- await this._verify_password(token, correct_token.token));
2292
- }
2293
- catch (err) {
2294
- if (err instanceof Collection.NotFoundError) {
2295
- return false;
2296
- }
2297
- throw err;
2298
- }
2299
- }
2300
- /**
2301
- * Verify a 2FA code by user id/email key.
2302
- * @param uid The UID or email used when creating the 2FA token.
2303
- * @param code The 2FA code.
2304
- * @returns Returns undefined on success, otherwise a string describing the error.
2305
- * @example
2306
- * await server.users.verify_2fa("1", "123456");
2307
- *
2308
- * @docs
2309
- */
2310
- async verify_2fa(uid, code) {
2311
- try {
2312
- const auth = await this._2fa_tokens_db.load({ uid });
2313
- const now = Date.now();
2314
- if (now >= auth.expiration) {
2315
- await this._deactivate_2fa_token(uid);
2316
- return "The 2FA code has expired.";
2317
- }
2318
- const status = (auth != null &&
2319
- auth.code != null &&
2320
- now < auth.expiration &&
2321
- auth.code == code &&
2322
- auth.active !== false);
2323
- if (status === false) {
2324
- return "Invalid 2FA code.";
2325
- }
2326
- await this._deactivate_2fa_token(uid); // single use.
2327
- return;
2328
- }
2329
- catch (err) {
2330
- if (err instanceof Collection.NotFoundError) {
2331
- return "Invalid 2FA code.";
2332
- }
2333
- this.server.log.error(`${err}.`);
2334
- return "Unknown error.";
2335
- }
2336
- }
2337
- /**
2338
- * Send a 2FA code to a user by user id.
2339
- * By default the 2FA code will be valid for 5 minutes.
2340
- * The mail body is generated via `Server.on_2fa_mail({code, username, email, date, ip, device})`.
2341
- * @returns Returns a promise that resolves when the 2FA mail has been sent.
2342
- * @param uid The user id (or use _email with internal flow).
2343
- * @param stream The stream object from the client request.
2344
- * @param expiration The amount of seconds in which the code will expire.
2345
- * @example
2346
- * await server.users.send_2fa({ uid: "0", stream });
2347
- *
2348
- * @docs
2349
- */
2350
- async send_2fa({ uid, stream, expiration = 300, _user_agent = undefined, _username = undefined, _email = undefined, }) {
2351
- // Generate 2fa and get user email.
2352
- let code;
2353
- if (_username == null && _email == null) {
2354
- code = await this._create_2fa_token(uid, expiration);
2355
- const user = await this.get(uid);
2356
- _username = user.username;
2357
- _email = user.email;
2358
- }
2359
- else {
2360
- code = await this._create_2fa_token(_email, expiration);
2361
- }
2362
- // Get device.
2363
- const user_agent = _user_agent ?? (stream.headers["user-agent"] ?? "Unknown");
2364
- // Replace body.
2365
- const on_2fa_mail = this.server.events.get("2fa_mail");
2366
- if (!on_2fa_mail?.length) {
2367
- throw Error("Define server callback \"Server.on_2fa_mail\" to generate the HTML mail body.");
2368
- }
2369
- const mail = await on_2fa_mail[0]({
2370
- code: code,
2371
- username: _username,
2372
- email: _email,
2373
- date: new Date().toUTCString(),
2374
- ip: stream.ip,
2375
- device: user_agent,
2376
- });
2377
- let body, subject;
2378
- if (mail instanceof MailUI.MailElement) {
2379
- body = mail.html();
2380
- subject = mail.subject();
2381
- }
2382
- else if (typeof mail === "string") {
2383
- body = mail;
2384
- }
2385
- else {
2386
- throw new Error("Invalid return value from server callback \"Server.on('2fa_mail')\", expected string or MailUI.MailElement.");
2387
- }
2388
- // Send mail.
2389
- this.server.assert_mail();
2390
- await this.server.mail.send({
2391
- recipients: [_email],
2392
- subject: subject ?? "Two Factor Authentication Code",
2393
- body,
2394
- });
2395
- }
2396
- /**
2397
- * List all users.
2398
- * @returns An array of User objects.
2399
- *
2400
- * @docs
2401
- */
2402
- async list() {
2403
- return await this._users_db.list_all();
2404
- }
2405
- }
2406
- /** Nested types for the {@link User} class. */
2407
- (function (Users) {
2408
- /** The types for the frontend endpoints. */
2409
- let Endpoints;
2410
- (function (Endpoints) {
2411
- // ---------------------------------------------
2412
- // Users.
2413
- // ---------------------------------------------
2414
- Endpoints.JsonValueSchemaType = [
2415
- "string",
2416
- "number",
2417
- "boolean",
2418
- "null",
2419
- "array",
2420
- "object"
2421
- ];
2422
- })(Endpoints = Users.Endpoints || (Users.Endpoints = {}));
2423
- })(Users || (Users = {}));