acebase-server 1.10.1 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (378) hide show
  1. package/.vscode/launch.json +24 -0
  2. package/dist/cjs/index.d.ts +1 -0
  3. package/dist/cjs/index.js +16 -0
  4. package/dist/cjs/logger.js +74 -0
  5. package/dist/cjs/middleware/admin-only.js +29 -0
  6. package/dist/cjs/middleware/user.js +4 -4
  7. package/dist/cjs/oauth-providers/dropbox.js +3 -2
  8. package/dist/cjs/oauth-providers/facebook.js +3 -2
  9. package/dist/cjs/oauth-providers/google.js +3 -2
  10. package/dist/cjs/oauth-providers/instagram.js +3 -2
  11. package/dist/cjs/oauth-providers/oauth-provider.js +23 -0
  12. package/dist/cjs/oauth-providers/spotify.js +3 -2
  13. package/dist/cjs/routes/auth-change-password.js +7 -4
  14. package/dist/cjs/routes/auth-delete.js +9 -7
  15. package/dist/cjs/routes/auth-forgot-password.js +9 -6
  16. package/dist/cjs/routes/auth-reset-password.js +5 -3
  17. package/dist/cjs/routes/auth-signout.js +6 -4
  18. package/dist/cjs/routes/auth-signup.js +17 -15
  19. package/dist/cjs/routes/auth-update.js +9 -6
  20. package/dist/cjs/routes/auth-verify-email.js +6 -3
  21. package/dist/cjs/routes/data-index-create.js +3 -5
  22. package/dist/cjs/routes/data-index-delete.js +2 -4
  23. package/dist/cjs/routes/data-index-list.js +2 -4
  24. package/dist/cjs/routes/data-reflect.js +2 -4
  25. package/dist/cjs/routes/data-schema-get.js +2 -4
  26. package/dist/cjs/routes/data-schema-set.js +2 -4
  27. package/dist/cjs/routes/data-schema-test.js +2 -4
  28. package/dist/cjs/routes/data-schemas-list.js +2 -4
  29. package/dist/cjs/routes/data-set.js +11 -7
  30. package/dist/cjs/routes/data-transaction.js +30 -10
  31. package/dist/cjs/routes/data-update.js +11 -6
  32. package/dist/cjs/routes/meta-logs.js +50 -0
  33. package/dist/cjs/routes/meta.js +3 -0
  34. package/dist/cjs/routes/oauth2-signin.js +15 -11
  35. package/dist/cjs/rules.js +5 -5
  36. package/dist/cjs/server.js +6 -4
  37. package/dist/cjs/settings/index.js +6 -7
  38. package/dist/cjs/shared/rootpath.js +2 -0
  39. package/dist/cjs/shared/signin.js +8 -3
  40. package/dist/cjs/start.js +3 -0
  41. package/dist/cjs/websocket/index.js +43 -24
  42. package/dist/cjs/websocket/socket.io.js +8 -11
  43. package/dist/esm/index.d.ts +1 -0
  44. package/dist/esm/index.js +2 -0
  45. package/dist/esm/logger.js +52 -0
  46. package/dist/esm/middleware/admin-only.js +25 -0
  47. package/dist/esm/middleware/user.js +4 -4
  48. package/dist/esm/oauth-providers/dropbox.js +3 -2
  49. package/dist/esm/oauth-providers/facebook.js +3 -2
  50. package/dist/esm/oauth-providers/google.js +3 -2
  51. package/dist/esm/oauth-providers/instagram.js +3 -2
  52. package/dist/esm/oauth-providers/oauth-provider.js +21 -1
  53. package/dist/esm/oauth-providers/spotify.js +3 -2
  54. package/dist/esm/routes/auth-change-password.js +6 -3
  55. package/dist/esm/routes/auth-delete.js +7 -5
  56. package/dist/esm/routes/auth-forgot-password.js +8 -6
  57. package/dist/esm/routes/auth-reset-password.js +4 -2
  58. package/dist/esm/routes/auth-signout.js +4 -2
  59. package/dist/esm/routes/auth-signup.js +12 -10
  60. package/dist/esm/routes/auth-update.js +8 -6
  61. package/dist/esm/routes/auth-verify-email.js +6 -2
  62. package/dist/esm/routes/data-index-create.js +4 -6
  63. package/dist/esm/routes/data-index-delete.js +3 -5
  64. package/dist/esm/routes/data-index-list.js +3 -5
  65. package/dist/esm/routes/data-reflect.js +1 -4
  66. package/dist/esm/routes/data-schema-get.js +3 -5
  67. package/dist/esm/routes/data-schema-set.js +3 -5
  68. package/dist/esm/routes/data-schema-test.js +3 -5
  69. package/dist/esm/routes/data-schemas-list.js +3 -5
  70. package/dist/esm/routes/data-set.js +9 -5
  71. package/dist/esm/routes/data-transaction.js +28 -8
  72. package/dist/esm/routes/data-update.js +9 -4
  73. package/dist/esm/routes/meta-logs.js +36 -0
  74. package/dist/esm/routes/meta.js +3 -0
  75. package/dist/esm/routes/oauth2-signin.js +14 -10
  76. package/dist/esm/rules.js +5 -5
  77. package/dist/esm/server.js +6 -4
  78. package/dist/esm/settings/index.js +5 -6
  79. package/dist/esm/shared/rootpath.js +2 -0
  80. package/dist/esm/shared/signin.js +7 -3
  81. package/dist/esm/start.js +3 -0
  82. package/dist/esm/websocket/index.js +38 -23
  83. package/dist/esm/websocket/socket.io.js +9 -11
  84. package/dist/types/index.d.ts +2 -0
  85. package/dist/types/logger.d.ts +35 -0
  86. package/dist/types/middleware/admin-only.d.ts +19 -0
  87. package/dist/types/oauth-providers/dropbox.d.ts +3 -14
  88. package/dist/types/oauth-providers/facebook.d.ts +3 -7
  89. package/dist/types/oauth-providers/google.d.ts +3 -7
  90. package/dist/types/oauth-providers/index.d.ts +2 -10
  91. package/dist/types/oauth-providers/instagram.d.ts +3 -7
  92. package/dist/types/oauth-providers/oauth-provider.d.ts +25 -21
  93. package/dist/types/oauth-providers/spotify.d.ts +3 -7
  94. package/dist/types/routes/data-query.d.ts +1 -1
  95. package/dist/types/routes/meta-logs.d.ts +20 -0
  96. package/dist/types/rules.d.ts +4 -4
  97. package/dist/types/server.d.ts +9 -7
  98. package/dist/types/settings/email.d.ts +1 -1
  99. package/dist/types/settings/index.d.ts +5 -6
  100. package/dist/types/shared/clients.d.ts +3 -1
  101. package/dist/types/shared/env.d.ts +6 -4
  102. package/dist/types/shared/http.d.ts +2 -0
  103. package/dist/types/shared/signin.d.ts +1 -1
  104. package/dist/types/websocket/index.d.ts +4 -0
  105. package/dist/types/websocket/manager.d.ts +1 -1
  106. package/package.json +8 -8
  107. package/webmanager/acebase-client-browser.min.js +16 -0
  108. package/webmanager/index.html +2 -2
  109. package/webmanager/index.js +3 -6
  110. package/create-package-files +0 -12
  111. package/dist/cjs/auth.js.map +0 -1
  112. package/dist/cjs/cluster.js.map +0 -1
  113. package/dist/cjs/index.js.map +0 -1
  114. package/dist/cjs/middleware/404.js.map +0 -1
  115. package/dist/cjs/middleware/cache.js.map +0 -1
  116. package/dist/cjs/middleware/connection.js.map +0 -1
  117. package/dist/cjs/middleware/context.js.map +0 -1
  118. package/dist/cjs/middleware/cors.js.map +0 -1
  119. package/dist/cjs/middleware/swagger.js.map +0 -1
  120. package/dist/cjs/middleware/user.js.map +0 -1
  121. package/dist/cjs/oauth-providers/dropbox.js.map +0 -1
  122. package/dist/cjs/oauth-providers/facebook.js.map +0 -1
  123. package/dist/cjs/oauth-providers/google.js.map +0 -1
  124. package/dist/cjs/oauth-providers/index.js.map +0 -1
  125. package/dist/cjs/oauth-providers/instagram.js.map +0 -1
  126. package/dist/cjs/oauth-providers/oauth-provider.js.map +0 -1
  127. package/dist/cjs/oauth-providers/spotify.js.map +0 -1
  128. package/dist/cjs/routes/auth-change-password.js.map +0 -1
  129. package/dist/cjs/routes/auth-delete.js.map +0 -1
  130. package/dist/cjs/routes/auth-forgot-password.js.map +0 -1
  131. package/dist/cjs/routes/auth-reset-password.js.map +0 -1
  132. package/dist/cjs/routes/auth-signin.js.map +0 -1
  133. package/dist/cjs/routes/auth-signout.js.map +0 -1
  134. package/dist/cjs/routes/auth-signup.js.map +0 -1
  135. package/dist/cjs/routes/auth-state.js.map +0 -1
  136. package/dist/cjs/routes/auth-update.js.map +0 -1
  137. package/dist/cjs/routes/auth-verify-email.js.map +0 -1
  138. package/dist/cjs/routes/auth.js.map +0 -1
  139. package/dist/cjs/routes/data-exists.js.map +0 -1
  140. package/dist/cjs/routes/data-export.js.map +0 -1
  141. package/dist/cjs/routes/data-get.js.map +0 -1
  142. package/dist/cjs/routes/data-import.js.map +0 -1
  143. package/dist/cjs/routes/data-index-create.js.map +0 -1
  144. package/dist/cjs/routes/data-index-delete.js.map +0 -1
  145. package/dist/cjs/routes/data-index-list.js.map +0 -1
  146. package/dist/cjs/routes/data-query.js.map +0 -1
  147. package/dist/cjs/routes/data-reflect.js.map +0 -1
  148. package/dist/cjs/routes/data-schema-get.js.map +0 -1
  149. package/dist/cjs/routes/data-schema-set.js.map +0 -1
  150. package/dist/cjs/routes/data-schema-test.js.map +0 -1
  151. package/dist/cjs/routes/data-schemas-list.js.map +0 -1
  152. package/dist/cjs/routes/data-set.js.map +0 -1
  153. package/dist/cjs/routes/data-sync-changes.js.map +0 -1
  154. package/dist/cjs/routes/data-sync-mutations.js.map +0 -1
  155. package/dist/cjs/routes/data-transaction.js.map +0 -1
  156. package/dist/cjs/routes/data-update.js.map +0 -1
  157. package/dist/cjs/routes/data.js.map +0 -1
  158. package/dist/cjs/routes/docs.js.map +0 -1
  159. package/dist/cjs/routes/meta-info.js.map +0 -1
  160. package/dist/cjs/routes/meta-ping.js.map +0 -1
  161. package/dist/cjs/routes/meta-stats.js.map +0 -1
  162. package/dist/cjs/routes/meta.js.map +0 -1
  163. package/dist/cjs/routes/oauth2-init.js.map +0 -1
  164. package/dist/cjs/routes/oauth2-refresh.js.map +0 -1
  165. package/dist/cjs/routes/oauth2-signin.js.map +0 -1
  166. package/dist/cjs/routes/webmanager.js.map +0 -1
  167. package/dist/cjs/rules.js.map +0 -1
  168. package/dist/cjs/schema/user.js.map +0 -1
  169. package/dist/cjs/server.js.map +0 -1
  170. package/dist/cjs/settings/email.js.map +0 -1
  171. package/dist/cjs/settings/index.js.map +0 -1
  172. package/dist/cjs/shared/clients.js.map +0 -1
  173. package/dist/cjs/shared/email.js.map +0 -1
  174. package/dist/cjs/shared/env.js.map +0 -1
  175. package/dist/cjs/shared/error.js.map +0 -1
  176. package/dist/cjs/shared/http.js.map +0 -1
  177. package/dist/cjs/shared/password.js.map +0 -1
  178. package/dist/cjs/shared/rootpath.js.map +0 -1
  179. package/dist/cjs/shared/signin.js.map +0 -1
  180. package/dist/cjs/shared/simple-fetch.js.map +0 -1
  181. package/dist/cjs/shared/tokens.js.map +0 -1
  182. package/dist/cjs/shared/validate.js.map +0 -1
  183. package/dist/cjs/start.js.map +0 -1
  184. package/dist/cjs/test.js.map +0 -1
  185. package/dist/cjs/websocket/index.js.map +0 -1
  186. package/dist/cjs/websocket/manager.js.map +0 -1
  187. package/dist/cjs/websocket/socket.io.js.map +0 -1
  188. package/dist/esm/auth.js.map +0 -1
  189. package/dist/esm/cluster.js.map +0 -1
  190. package/dist/esm/index.js.map +0 -1
  191. package/dist/esm/middleware/404.js.map +0 -1
  192. package/dist/esm/middleware/cache.js.map +0 -1
  193. package/dist/esm/middleware/connection.js.map +0 -1
  194. package/dist/esm/middleware/context.js.map +0 -1
  195. package/dist/esm/middleware/cors.js.map +0 -1
  196. package/dist/esm/middleware/swagger.js.map +0 -1
  197. package/dist/esm/middleware/user.js.map +0 -1
  198. package/dist/esm/oauth-providers/dropbox.js.map +0 -1
  199. package/dist/esm/oauth-providers/facebook.js.map +0 -1
  200. package/dist/esm/oauth-providers/google.js.map +0 -1
  201. package/dist/esm/oauth-providers/index.js.map +0 -1
  202. package/dist/esm/oauth-providers/instagram.js.map +0 -1
  203. package/dist/esm/oauth-providers/oauth-provider.js.map +0 -1
  204. package/dist/esm/oauth-providers/spotify.js.map +0 -1
  205. package/dist/esm/routes/auth-change-password.js.map +0 -1
  206. package/dist/esm/routes/auth-delete.js.map +0 -1
  207. package/dist/esm/routes/auth-forgot-password.js.map +0 -1
  208. package/dist/esm/routes/auth-reset-password.js.map +0 -1
  209. package/dist/esm/routes/auth-signin.js.map +0 -1
  210. package/dist/esm/routes/auth-signout.js.map +0 -1
  211. package/dist/esm/routes/auth-signup.js.map +0 -1
  212. package/dist/esm/routes/auth-state.js.map +0 -1
  213. package/dist/esm/routes/auth-update.js.map +0 -1
  214. package/dist/esm/routes/auth-verify-email.js.map +0 -1
  215. package/dist/esm/routes/auth.js.map +0 -1
  216. package/dist/esm/routes/data-exists.js.map +0 -1
  217. package/dist/esm/routes/data-export.js.map +0 -1
  218. package/dist/esm/routes/data-get.js.map +0 -1
  219. package/dist/esm/routes/data-import.js.map +0 -1
  220. package/dist/esm/routes/data-index-create.js.map +0 -1
  221. package/dist/esm/routes/data-index-delete.js.map +0 -1
  222. package/dist/esm/routes/data-index-list.js.map +0 -1
  223. package/dist/esm/routes/data-query.js.map +0 -1
  224. package/dist/esm/routes/data-reflect.js.map +0 -1
  225. package/dist/esm/routes/data-schema-get.js.map +0 -1
  226. package/dist/esm/routes/data-schema-set.js.map +0 -1
  227. package/dist/esm/routes/data-schema-test.js.map +0 -1
  228. package/dist/esm/routes/data-schemas-list.js.map +0 -1
  229. package/dist/esm/routes/data-set.js.map +0 -1
  230. package/dist/esm/routes/data-sync-changes.js.map +0 -1
  231. package/dist/esm/routes/data-sync-mutations.js.map +0 -1
  232. package/dist/esm/routes/data-transaction.js.map +0 -1
  233. package/dist/esm/routes/data-update.js.map +0 -1
  234. package/dist/esm/routes/data.js.map +0 -1
  235. package/dist/esm/routes/docs.js.map +0 -1
  236. package/dist/esm/routes/meta-info.js.map +0 -1
  237. package/dist/esm/routes/meta-ping.js.map +0 -1
  238. package/dist/esm/routes/meta-stats.js.map +0 -1
  239. package/dist/esm/routes/meta.js.map +0 -1
  240. package/dist/esm/routes/oauth2-init.js.map +0 -1
  241. package/dist/esm/routes/oauth2-refresh.js.map +0 -1
  242. package/dist/esm/routes/oauth2-signin.js.map +0 -1
  243. package/dist/esm/routes/webmanager.js.map +0 -1
  244. package/dist/esm/rules.js.map +0 -1
  245. package/dist/esm/schema/user.js.map +0 -1
  246. package/dist/esm/server.js.map +0 -1
  247. package/dist/esm/settings/email.js.map +0 -1
  248. package/dist/esm/settings/index.js.map +0 -1
  249. package/dist/esm/shared/clients.js.map +0 -1
  250. package/dist/esm/shared/email.js.map +0 -1
  251. package/dist/esm/shared/env.js.map +0 -1
  252. package/dist/esm/shared/error.js.map +0 -1
  253. package/dist/esm/shared/http.js.map +0 -1
  254. package/dist/esm/shared/password.js.map +0 -1
  255. package/dist/esm/shared/rootpath.js.map +0 -1
  256. package/dist/esm/shared/signin.js.map +0 -1
  257. package/dist/esm/shared/simple-fetch.js.map +0 -1
  258. package/dist/esm/shared/tokens.js.map +0 -1
  259. package/dist/esm/shared/validate.js.map +0 -1
  260. package/dist/esm/start.js.map +0 -1
  261. package/dist/esm/test.js.map +0 -1
  262. package/dist/esm/websocket/index.js.map +0 -1
  263. package/dist/esm/websocket/manager.js.map +0 -1
  264. package/dist/esm/websocket/socket.io.js.map +0 -1
  265. package/src/auth.ts +0 -87
  266. package/src/cluster.ts +0 -62
  267. package/src/index.ts +0 -2
  268. package/src/middleware/404.ts +0 -13
  269. package/src/middleware/cache.ts +0 -15
  270. package/src/middleware/connection.ts +0 -48
  271. package/src/middleware/context.ts +0 -23
  272. package/src/middleware/cors.ts +0 -49
  273. package/src/middleware/swagger.ts +0 -19
  274. package/src/middleware/user.ts +0 -51
  275. package/src/oauth-providers/dropbox.ts +0 -143
  276. package/src/oauth-providers/facebook.ts +0 -102
  277. package/src/oauth-providers/google.ts +0 -146
  278. package/src/oauth-providers/index.ts +0 -20
  279. package/src/oauth-providers/instagram.ts +0 -97
  280. package/src/oauth-providers/oauth-provider.ts +0 -55
  281. package/src/oauth-providers/spotify.ts +0 -126
  282. package/src/routes/auth-change-password.ts +0 -89
  283. package/src/routes/auth-change-password.yaml +0 -74
  284. package/src/routes/auth-delete.ts +0 -47
  285. package/src/routes/auth-delete.yaml +0 -78
  286. package/src/routes/auth-forgot-password.ts +0 -73
  287. package/src/routes/auth-forgot-password.yaml +0 -50
  288. package/src/routes/auth-reset-password.ts +0 -93
  289. package/src/routes/auth-reset-password.yaml +0 -54
  290. package/src/routes/auth-signin.ts +0 -55
  291. package/src/routes/auth-signin.yaml +0 -130
  292. package/src/routes/auth-signout.ts +0 -61
  293. package/src/routes/auth-signout.yaml +0 -46
  294. package/src/routes/auth-signup.ts +0 -161
  295. package/src/routes/auth-signup.yaml +0 -136
  296. package/src/routes/auth-state.ts +0 -20
  297. package/src/routes/auth-state.yaml +0 -29
  298. package/src/routes/auth-update.ts +0 -147
  299. package/src/routes/auth-update.yaml +0 -152
  300. package/src/routes/auth-verify-email.ts +0 -67
  301. package/src/routes/auth-verify-email.yaml +0 -53
  302. package/src/routes/auth.ts +0 -67
  303. package/src/routes/data-exists.ts +0 -31
  304. package/src/routes/data-exists.yaml +0 -44
  305. package/src/routes/data-export.ts +0 -51
  306. package/src/routes/data-export.yaml +0 -64
  307. package/src/routes/data-get.ts +0 -68
  308. package/src/routes/data-get.yaml +0 -54
  309. package/src/routes/data-import.ts +0 -56
  310. package/src/routes/data-import.yaml +0 -75
  311. package/src/routes/data-index-create.ts +0 -85
  312. package/src/routes/data-index-create.yaml +0 -105
  313. package/src/routes/data-index-delete.ts +0 -39
  314. package/src/routes/data-index-delete.yaml +0 -51
  315. package/src/routes/data-index-list.ts +0 -42
  316. package/src/routes/data-index-list.yaml +0 -80
  317. package/src/routes/data-query.ts +0 -97
  318. package/src/routes/data-query.yaml +0 -166
  319. package/src/routes/data-reflect.ts +0 -94
  320. package/src/routes/data-reflect.yaml +0 -124
  321. package/src/routes/data-schema-get.ts +0 -38
  322. package/src/routes/data-schema-get.yaml +0 -53
  323. package/src/routes/data-schema-set.ts +0 -38
  324. package/src/routes/data-schema-set.yaml +0 -60
  325. package/src/routes/data-schema-test.ts +0 -53
  326. package/src/routes/data-schema-test.yaml +0 -66
  327. package/src/routes/data-schemas-list.ts +0 -33
  328. package/src/routes/data-schemas-list.yaml +0 -41
  329. package/src/routes/data-set.ts +0 -76
  330. package/src/routes/data-set.yaml +0 -71
  331. package/src/routes/data-sync-changes.ts +0 -78
  332. package/src/routes/data-sync-changes.yaml +0 -67
  333. package/src/routes/data-sync-mutations.ts +0 -78
  334. package/src/routes/data-sync-mutations.yaml +0 -67
  335. package/src/routes/data-transaction-finish.yaml +0 -76
  336. package/src/routes/data-transaction-start.yaml +0 -58
  337. package/src/routes/data-transaction.ts +0 -144
  338. package/src/routes/data-update.ts +0 -77
  339. package/src/routes/data-update.yaml +0 -71
  340. package/src/routes/data.ts +0 -79
  341. package/src/routes/docs.ts +0 -249
  342. package/src/routes/meta-info.ts +0 -80
  343. package/src/routes/meta-info.yaml +0 -41
  344. package/src/routes/meta-ping.ts +0 -15
  345. package/src/routes/meta-ping.yaml +0 -23
  346. package/src/routes/meta-stats.ts +0 -31
  347. package/src/routes/meta-stats.yaml +0 -41
  348. package/src/routes/meta.ts +0 -18
  349. package/src/routes/oauth2-init.ts +0 -44
  350. package/src/routes/oauth2-init.yaml +0 -63
  351. package/src/routes/oauth2-refresh.ts +0 -39
  352. package/src/routes/oauth2-refresh.yaml +0 -65
  353. package/src/routes/oauth2-signin.ts +0 -281
  354. package/src/routes/oauth2-signin.yaml +0 -66
  355. package/src/routes/webmanager.ts +0 -29
  356. package/src/rules.ts +0 -196
  357. package/src/schema/user.ts +0 -99
  358. package/src/server.ts +0 -416
  359. package/src/settings/email.ts +0 -18
  360. package/src/settings/index.ts +0 -240
  361. package/src/shared/clients.ts +0 -31
  362. package/src/shared/email.ts +0 -33
  363. package/src/shared/env.ts +0 -38
  364. package/src/shared/error.ts +0 -37
  365. package/src/shared/http.ts +0 -24
  366. package/src/shared/password.ts +0 -41
  367. package/src/shared/rootpath.ts +0 -15
  368. package/src/shared/signin.ts +0 -143
  369. package/src/shared/simple-fetch.ts +0 -65
  370. package/src/shared/tokens.ts +0 -77
  371. package/src/shared/validate.ts +0 -53
  372. package/src/start.ts +0 -45
  373. package/src/test.ts +0 -10
  374. package/src/websocket/index.ts +0 -320
  375. package/src/websocket/manager.ts +0 -46
  376. package/src/websocket/socket.io.ts +0 -91
  377. package/tsconfig-cjs.json +0 -10
  378. package/tsconfig.json +0 -21
@@ -1,240 +0,0 @@
1
- import { AceBaseStorageSettings } from 'acebase';
2
- import { readFileSync } from 'fs';
3
- import { AceBaseServerEmailSettings } from './email';
4
-
5
- export type AceBaseServerHttpsSettings = {
6
- enabled?: boolean;
7
- keyPath?: string;
8
- certPath?: string
9
- pfxPath?: string;
10
- passphrase?: string
11
- } & (
12
- { keyPath: string; certPath: string } |
13
- { pfxPath: string; passphrase: string } |
14
- {}
15
- )
16
-
17
- export class AceBaseServerHttpsConfig {
18
- enabled: boolean = true;
19
- key?: Buffer;
20
- cert?: Buffer;
21
- pfx?: Buffer;
22
- passphrase?: string;
23
-
24
- constructor(settings: AceBaseServerHttpsSettings) {
25
- this.enabled = typeof settings === "object" && settings.enabled !== false;
26
- if (!this.enabled) { return; }
27
- if (settings.keyPath) {
28
- this.key = readFileSync(settings.keyPath);
29
- this.cert = readFileSync(settings.certPath);
30
- }
31
- else if (settings.pfxPath) {
32
- this.pfx = readFileSync(settings.pfxPath);
33
- this.passphrase = settings.passphrase;
34
- }
35
- }
36
- }
37
-
38
- export enum AUTH_ACCESS_DEFAULT {
39
- DENY_ALL = 'deny',
40
- ALLOW_ALL = 'allow',
41
- ALLOW_AUTHENTICATED = 'auth'
42
- }
43
-
44
- export class AceBaseServerAuthenticationSettings {
45
-
46
- /**
47
- * Whether to enable authorization. Without authorization the entire db can be read and written to by anyone (not recommended 🤷🏼‍♂️)
48
- */
49
- readonly enabled: boolean = true;
50
-
51
- /**
52
- * Whether new users creation is allowed for anyone, or just the admin
53
- */
54
- readonly allowUserSignup: boolean = false;
55
-
56
- /**
57
- * How many new users can sign up per hour per IP address. not implemented yet
58
- */
59
- readonly newUserRateLimit: number = 0;
60
-
61
- /**
62
- * How many minutes before access tokens expire. 0 for no expiration. (not implemented yet)
63
- */
64
- readonly tokensExpire: number = 0;
65
-
66
- /**
67
- * When the server runs for the first time, what defaults to use to generate the rules.json file with. Options are: 'auth' (only authenticated access to db, default), 'deny' (deny access to anyone except admin user), 'allow' (allow access to anyone)
68
- */
69
- readonly defaultAccessRule: AUTH_ACCESS_DEFAULT = AUTH_ACCESS_DEFAULT.ALLOW_AUTHENTICATED;
70
-
71
- /**
72
- * When the server runs for the first time, what password to use for the admin user. If not supplied, a generated password will be used and shown ONCE in the console output.
73
- */
74
- readonly defaultAdminPassword?: string;
75
-
76
- /**
77
- * Whether to use a separate database for auth and logging. 'v2' will store data in auth.db, which is NOT TESTED YET!
78
- */
79
- readonly separateDb: boolean|'v2' = false;
80
-
81
- constructor(settings: Partial<AceBaseServerAuthenticationSettings>) {
82
- if (typeof settings !== "object") { settings = {}; }
83
- if (typeof settings.enabled === 'boolean') { this.enabled = settings.enabled; }
84
- if (typeof settings.allowUserSignup === 'boolean') { this.allowUserSignup = settings.allowUserSignup; }
85
- if (typeof settings.newUserRateLimit === 'number') { this.newUserRateLimit = settings.newUserRateLimit; }
86
- if (typeof settings.tokensExpire === 'number') { this.tokensExpire = settings.tokensExpire; }
87
- if (typeof settings.defaultAccessRule === 'string') { this.defaultAccessRule = settings.defaultAccessRule; }
88
- if (typeof settings.defaultAdminPassword === 'string') { this.defaultAdminPassword = settings.defaultAdminPassword; }
89
- if (typeof (settings as any).seperateDb === 'boolean') { this.separateDb = (settings as any).seperateDb; } // Handle previous _wrong_ spelling
90
- if (typeof settings.separateDb === 'boolean') { this.separateDb = settings.separateDb; }
91
- }
92
- }
93
-
94
- /**
95
- * TODO: Use AceBaseTransactionLogSettings from 'acebase/src/storage-acebase.js'
96
- */
97
- export class AceBaseServerTransactionSettings {
98
- /**
99
- * Whether to enable transaction logging
100
- */
101
- log: boolean = false;
102
-
103
- /**
104
- * Max age in days to keep transactions in the log file
105
- */
106
- maxAge: number = 30;
107
-
108
- /**
109
- * Whether database write operations should not wait until transaction has been logged
110
- */
111
- noWait: boolean = false;
112
-
113
- constructor(settings: Partial<AceBaseServerTransactionSettings>) {
114
- if (typeof settings !== 'object') { return; }
115
- if (typeof settings.log === 'boolean') { this.log = settings.log; }
116
- if (typeof settings.maxAge === 'number') { this.maxAge = settings.maxAge; }
117
- if (typeof settings.noWait === 'boolean') { this.noWait = settings.noWait; }
118
- }
119
- }
120
-
121
- export interface IPCClientSettings {
122
- /**
123
- * IPC Server host to connect to. Default is `"localhost"`
124
- */
125
- host?: string;
126
-
127
- /**
128
- * IPC Server port number
129
- */
130
- port: number;
131
-
132
- /**
133
- * Whether to use a secure connection to the server. Strongly recommended if `host` is not `"localhost"`. Default is `false`
134
- */
135
- ssl?: boolean;
136
-
137
- /**
138
- * Token used in the IPC Server configuration (optional). The server will refuse connections using the wrong token.
139
- */
140
- token?: string;
141
-
142
- /**
143
- * Determines the role of this IPC client. Only 1 process can be assigned the 'master' role, all other processes must use the role 'worker'
144
- */
145
- role: 'master'|'worker';
146
- }
147
-
148
- export type AceBaseServerSettings = Partial<{
149
- /**
150
- * Level of messages logged to console
151
- */
152
- logLevel: 'verbose'|'log'|'warn'|'error';
153
-
154
- /**
155
- * ip or hostname to start the server on
156
- */
157
- host: string;
158
-
159
- /**
160
- * port number the server will be listening
161
- */
162
- port: number;
163
-
164
- /**
165
- * target directory path to store/open the database. Default is '.'
166
- */
167
- path: string;
168
-
169
- /**
170
- * Whether to use secure sockets layer (ssl)
171
- */
172
- https: AceBaseServerHttpsSettings;
173
-
174
- /**
175
- * settings that define if and how authentication is used
176
- */
177
- authentication: Partial<AceBaseServerAuthenticationSettings>;
178
-
179
- /**
180
- * maximum size to allow for posted data, eg for updating nodes. Default is '10mb'
181
- */
182
- maxPayloadSize: string;
183
-
184
- /**
185
- * Value to use for Access-Control-Allow-Origin CORS header. Default is '*'
186
- */
187
- allowOrigin: string;
188
-
189
- /**
190
- * Email settings that enable AceBaseServer to send e-mails, eg for welcoming new users, to reset passwords, notify of new sign ins etc
191
- */
192
- email: AceBaseServerEmailSettings;
193
-
194
- /**
195
- * Transaction logging settings. Warning: BETA stage, do NOT use in production yet
196
- */
197
- transactions: Partial<AceBaseServerTransactionSettings>;
198
-
199
- /**
200
- * IPC settings for pm2 or cloud-based clusters. BETA stage, see https://github.com/appy-one/acebase-ipc-server
201
- */
202
- ipc: IPCClientSettings;
203
-
204
- /**
205
- * Allows overriding of default storage settings used by the database. ALPHA stage
206
- */
207
- storage: AceBaseStorageSettings;
208
- }>
209
-
210
- export class AceBaseServerConfig {
211
-
212
- readonly logLevel: 'verbose'|'log'|'warn'|'error' = 'log';
213
- readonly host: string = 'localhost';
214
- readonly port: number = 3000;
215
- readonly path: string = '.';
216
- readonly maxPayloadSize: string = '10mb';
217
- readonly allowOrigin: string = '*';
218
- readonly https: AceBaseServerHttpsConfig;
219
- readonly auth: AceBaseServerAuthenticationSettings;
220
- readonly email: AceBaseServerEmailSettings;
221
- readonly transactions: AceBaseServerTransactionSettings;
222
- readonly ipc: IPCClientSettings;
223
- readonly storage?: AceBaseStorageSettings;
224
-
225
- constructor(settings: AceBaseServerSettings) {
226
- if (typeof settings !== "object") { settings = {}; }
227
- if (typeof settings.logLevel === 'string') { this.logLevel = settings.logLevel; }
228
- if (typeof settings.host === 'string') { this.host = settings.host; }
229
- if (typeof settings.port === 'number') { this.port = settings.port; }
230
- if (typeof settings.path === 'string') { this.path = settings.path; }
231
- this.https = new AceBaseServerHttpsConfig(settings.https);
232
- this.auth = new AceBaseServerAuthenticationSettings(settings.authentication);
233
- if (typeof settings.maxPayloadSize === 'string') { this.maxPayloadSize = settings.maxPayloadSize; }
234
- if (typeof settings.allowOrigin === 'string') { this.allowOrigin = settings.allowOrigin; }
235
- if (typeof settings.email === 'object') { this.email = settings.email; }
236
- this.transactions = new AceBaseServerTransactionSettings(settings.transactions);
237
- this.ipc = settings.ipc;
238
- if (typeof settings.storage === 'object') { this.storage = settings.storage; }
239
- }
240
- }
@@ -1,31 +0,0 @@
1
- import { EventSubscriptionCallback, IApiQuery, IApiQueryOptions } from "acebase-core/src/api";
2
- import { DbUserAccountDetails } from "../schema/user";
3
- import { HttpSocket } from "./http";
4
-
5
- export class ConnectedClient {
6
- readonly id: string;
7
-
8
- /**
9
- *
10
- * @param socket Socket object used by the framework
11
- * @param id optional: use if the socket object does not have an `id` property.
12
- */
13
- constructor (public socket: HttpSocket, id?: string) {
14
- this.id = id ?? socket.id;
15
- if (!this.id) { throw new Error('Socket has no id'); }
16
- }
17
- // get id() { return this.socket.id; };
18
- readonly connectedDate: Date = new Date();
19
-
20
- /** user details if this socket client is signed in */
21
- user?: DbUserAccountDetails;
22
-
23
- /** Active event subscriptions for this client */
24
- subscriptions: { [path: string]: Array<{ path: string, event: string, callback: EventSubscriptionCallback }> } = {};
25
-
26
- /** Active realtime query subscriptions for this client */
27
- realtimeQueries: { [id: string]: { path: string; query: IApiQuery, options: IApiQueryOptions }} = {};
28
-
29
- /** Currently running transactions */
30
- transactions: { [id: string]: { id: string; started: number; path: string; context: any; finish?: (val?: any) => Promise<any>; timeout: NodeJS.Timeout } } = {};
31
- }
@@ -1,33 +0,0 @@
1
- export interface AceBaseEmailRequest {
2
- /** email request type */
3
- type: string;
4
- };
5
-
6
- export interface AceBaseUserEmailRequest extends AceBaseEmailRequest {
7
- user: { uid: string; email: string; username?: string; displayName?: string; settings?: any };
8
- ip: string;
9
- date: Date
10
- };
11
-
12
- export interface AceBaseUserSignupEmailRequest extends AceBaseUserEmailRequest {
13
- type: 'user_signup';
14
- activationCode: string;
15
- emailVerified: boolean;
16
- provider: string;
17
- };
18
-
19
- export interface AceBaseUserSignInEmailRequest extends AceBaseUserEmailRequest {
20
- type: 'user_signin';
21
- activationCode: string;
22
- emailVerified: boolean;
23
- provider: string;
24
- };
25
-
26
- export interface AceBaseUserResetPasswordEmailRequest extends AceBaseUserEmailRequest {
27
- type: 'user_reset_password';
28
- resetCode: string;
29
- }
30
-
31
- export interface AceBaseUserResetPasswordSuccessEmailRequest extends AceBaseUserEmailRequest {
32
- type: 'user_reset_password_success';
33
- }
package/src/shared/env.ts DELETED
@@ -1,38 +0,0 @@
1
- import type { HttpApp, Request } from './http';
2
- import type { AceBase, DataReference } from 'acebase';
3
- import type { AceBaseServerConfig } from '../settings';
4
- import type { DbUserAccountDetails } from '../schema/user';
5
- import type { ConnectedClient } from './clients';
6
- import type { DebugLogger, SimpleCache } from 'acebase-core';
7
- import type { IOAuth2Provider } from '../oauth-providers/oauth-provider';
8
- import type { Server as HttpServer } from 'http';
9
- import type { Server as SecureHttpServer } from 'https';
10
- import type { PathBasedRules } from '../rules';
11
- import { Api } from 'acebase-core/src/api';
12
-
13
- export interface RouteInitEnvironment {
14
- server: HttpServer | SecureHttpServer;
15
- app: HttpApp;
16
- config: AceBaseServerConfig;
17
- db: AceBase & { api: Api };
18
- authDb: AceBase;
19
- debug: DebugLogger;
20
- securityRef: DataReference;
21
- authRef: DataReference;
22
- logRef: DataReference;
23
- tokenSalt: string;
24
- clients: Map<string, ConnectedClient>;
25
- authCache: SimpleCache<string, DbUserAccountDetails>;
26
- authProviders: { [providerName: string]: IOAuth2Provider };
27
- rules: PathBasedRules
28
- };
29
-
30
- export interface RouteRequestEnvironment {
31
- /** If the request has an Authentication: bearer token, the user will be bound to the incoming request */
32
- user?: DbUserAccountDetails;
33
-
34
- /** If context is sent through AceBase-Context header, it will be bound to the incoming request */
35
- context?: { [key: string]: any };
36
- };
37
-
38
- export type RouteRequest<Params = any, ResBody = any, ReqBody = any, ReqQuery = any, Locals extends Record<string, any> = Record<string, any>> = Request<Params, ResBody, ReqBody, ReqQuery, Locals> & RouteRequestEnvironment;
@@ -1,37 +0,0 @@
1
- import { Response } from './http';
2
-
3
- export const sendNotAuthenticatedError = (res: Response, code: string, message: string) => {
4
- res.statusCode = 401; // Unauthorized (not unauthenticated)
5
- res.statusMessage = 'Not Authenticated';
6
- res.contentType('application/json').send({ code, message });
7
- };
8
-
9
- export const sendUnauthorizedError = (res: Response, code: string, message: string) => {
10
- res.statusCode = 403; // Forbidden
11
- res.statusMessage = 'Unauthorized';
12
- res.contentType('application/json').send({ code, message });
13
- };
14
-
15
- interface ErrorLike {
16
- code?: string;
17
- message: string;
18
- stack?: string;
19
- };
20
-
21
- export const sendError = (res: Response, err: ErrorLike) => {
22
- res.contentType('application/json');
23
- if (typeof err.code === 'string') {
24
- sendBadRequestError(res, err as { code: string; message: string }); //res.status(400).send({ code: err.code, message: err.message }); // Bad Request
25
- }
26
- else {
27
- sendUnexpectedError(res, err as Error); // res.status(500).send({ code: 'unknown', message: 'server error', details: err.message }); // Internal server error
28
- }
29
- }
30
-
31
- export const sendBadRequestError = (res: Response, err: { code: string, message: string }) => {
32
- res.status(400).contentType('application/json').send({ code: err.code, message: err.message }); // Bad Request
33
- }
34
-
35
- export const sendUnexpectedError = (res: Response, err: Error) => {
36
- res.status(500).contentType('application/json').send({ code: 'unexpected', message: 'server error', details: err.message }); // Internal server error
37
- }
@@ -1,24 +0,0 @@
1
- import type { Socket } from 'socket.io';
2
- export type { Express, Request, Response } from 'express';
3
- import * as express from 'express';
4
- const createExpress = (express as any).default ?? express; // ESM and CJS compatible approach
5
-
6
- export type HttpApp = express.Express;
7
- export type HttpSocket = Socket;
8
-
9
- /**
10
- * Creates an app that handles http requests, adds json body parsing.
11
- * @param settings
12
- * @returns
13
- */
14
- export const createApp = (settings: { trustProxy: boolean; maxPayloadSize: string }) => {
15
- const app = createExpress();
16
-
17
- // When behind a trusted proxy server, req.ip and req.hostname will be set the right way
18
- app.set('trust proxy', settings.trustProxy);
19
-
20
- // Parse json request bodies
21
- app.use(express.json({ limit: settings.maxPayloadSize })); // , extended: true ?
22
-
23
- return app as HttpApp;
24
- }
@@ -1,41 +0,0 @@
1
- import * as crypto from 'crypto';
2
-
3
- export const generatePassword = () => {
4
- return Array.prototype.reduce.call('abcedefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ012345789!@#$%&', (password, c, i, chars) => {
5
- if (i > 15) { return password; }
6
- return password + chars[Math.floor(Math.random() * chars.length)];
7
- }, '');
8
- };
9
-
10
- /**
11
- * Generates a random salt and hashes the provided password with it. The resulting salt and hash should be stored in the database
12
- * @param password password to hash
13
- */
14
- export const createPasswordHash = (password: string) => {
15
- let length = 16;
16
- let salt = crypto.randomBytes(Math.ceil(length/2)).toString('hex').slice(0,length);
17
- let hash = crypto.createHmac('sha512', salt).update(password).digest('hex');
18
- return {
19
- salt,
20
- hash
21
- }
22
- };
23
-
24
- /**
25
- * For checking passwords: uses given password and salt to get the hash that can be compared to a stored version.
26
- * @param password A password prodived by the user trying to sign in
27
- * @param salt the salt used to generate the hash, must be stored with the hash in the database
28
- */
29
- export const getPasswordHash = (password: string, salt: string) => {
30
- return crypto.createHmac('sha512', salt).update(password).digest('hex');
31
- };
32
-
33
- /**
34
- * Backward compatibility with old saltless md5 passwords. Becomes obsolete once all passwords have been updated (probably already so)
35
- */
36
- export const getOldPasswordHash = (password: string) => {
37
- // Backward compatibility with old saltless md5 passwords.
38
- // Becomes obsolete once all passwords have been updated
39
- return crypto.createHash('md5').update(password).digest('hex');
40
- };
41
-
@@ -1,15 +0,0 @@
1
- import { resolve } from "path";
2
-
3
- // This file is in ./src/shared/rootpath.ts
4
- // When this code runs it is at ./dist/cjs/shared/rootpath.js or ./dist/esm/shared/rootpath.js
5
- // So, the package root is at ../../..
6
- let currentDir = __dirname;
7
-
8
- if (process.platform === 'win32' && currentDir.startsWith('/')) {
9
- // tsc-esm-fix does not handle win32 file urls correctly, the drive letter in import.meta.url is prefixed with a slash: file:///C:/dir/file.js
10
- currentDir = currentDir.slice(1);
11
- }
12
-
13
- export const packageRootPath = resolve(currentDir, '../../..');
14
-
15
- export default packageRootPath;
@@ -1,143 +0,0 @@
1
- import { ID } from "acebase-core";
2
- import { DbUserAccountDetails } from "../schema/user";
3
- import { RouteInitEnvironment, RouteRequest } from "./env";
4
- import { createPasswordHash, getOldPasswordHash, getPasswordHash } from "./password";
5
- import { decodePublicAccessToken } from "./tokens";
6
-
7
- export type SignInCredentials =
8
- { method: 'token'; access_token: string } |
9
- { method: 'private_token'; access_token: string } |
10
- { method: 'email'; email: string; password: string } |
11
- { method: 'account', username: string, password: string };
12
-
13
- export class SignInError extends Error {
14
- constructor(public code: string, message: string, public details: Object = {}) {
15
- super(message);
16
- }
17
- }
18
-
19
- /**
20
- * Signs in a user and logs the request. If successful, adds the user to authCache, binds the user to the http request and returns the user details.
21
- * Throws a `SignInError` if sign in fails for a known reason.
22
- * @param credentials credentials to sign in the user with
23
- * @param env environment state
24
- * @param req current http request
25
- * @returns
26
- */
27
- export const signIn = async (credentials: SignInCredentials, env: RouteInitEnvironment, req: RouteRequest) => {
28
- try {
29
- const query = env.authRef.query();
30
- let tokenDetails: ReturnType<typeof decodePublicAccessToken>;
31
- switch (credentials.method) {
32
- case 'token': {
33
- if (typeof credentials.access_token !== 'string') {
34
- throw new SignInError('invalid_details', 'sign in request has invalid arguments');
35
- }
36
- try {
37
- tokenDetails = decodePublicAccessToken(credentials.access_token, env.tokenSalt);
38
- query.filter('access_token', '==', tokenDetails.access_token);
39
- }
40
- catch (err) {
41
- throw new SignInError('invalid_token', err.message);
42
- }
43
- break;
44
- }
45
- case 'private_token': {
46
- // Method used internally: uses the access token extracted from a public access token (see tokenDetails.access_token in above 'token' case)
47
- if (typeof credentials.access_token !== 'string') {
48
- throw new SignInError('invalid_details', 'sign in request has invalid arguments');
49
- }
50
- query.filter('access_token', '==', credentials.access_token);
51
- break;
52
- }
53
- case 'email': {
54
- if (typeof credentials.email !== 'string' || typeof credentials.password !== 'string') {
55
- throw new SignInError('invalid_details', 'sign in request has invalid arguments');
56
- }
57
- query.filter('email', '==', credentials.email);
58
- break;
59
- }
60
- case 'account': {
61
- if (typeof credentials.username !== 'string' || typeof credentials.password !== 'string') {
62
- throw new SignInError('invalid_details', 'sign in request has invalid arguments');
63
- }
64
- query.filter('username', '==', credentials.username);
65
- break;
66
- }
67
- default: {
68
- throw new SignInError('invalid_method', `Unsupported sign in method ${(credentials as any).method}`);
69
- }
70
- }
71
-
72
- const snaps = await query.get();
73
- if (snaps.length === 0) {
74
- throw new SignInError('not_found', `account not found`);
75
- }
76
- else if (snaps.length > 1) {
77
- throw new SignInError('duplicate', `${snaps.length} users found with the same ${credentials.method}. Contact your database administrator`, { count: snaps.length });
78
- }
79
-
80
- const snap = snaps[0];
81
- const user: DbUserAccountDetails = snap.val();
82
- user.uid = snap.key as string;
83
-
84
- if (user.is_disabled === true) {
85
- throw new SignInError('account_disabled', 'Your account has been disabled. Contact your database administrator');
86
- }
87
- if (credentials.method === 'token' && tokenDetails.uid !== user.uid) {
88
- throw new SignInError('token_mismatch', 'Sign in again');
89
- }
90
- if (credentials.method === 'account' || credentials.method === 'email') {
91
- // Check password
92
- let hash = user.password_salt ? getPasswordHash(credentials.password, user.password_salt) : getOldPasswordHash(credentials.password);
93
- if (user.password !== hash) {
94
- throw new SignInError('wrong_password', 'Incorrect password');
95
- }
96
- }
97
-
98
- // Keep track of properties to update, both in db and in our object
99
- const updates: Partial<DbUserAccountDetails> = {
100
- // Update prev / last sign in stats
101
- prev_signin: user.last_signin,
102
- prev_signin_ip: user.last_signin_ip,
103
- last_signin: new Date(),
104
- last_signin_ip: req.ip
105
- };
106
-
107
- if ('password' in credentials) {
108
- if (!user.password_salt) {
109
- // OLD md5 password hash, convert to new salted hash
110
- let pwd = createPasswordHash(credentials.password);
111
- updates.password = pwd.hash;
112
- updates.password_salt = pwd.salt;
113
- }
114
- if (!user.access_token) {
115
- // Generate access token
116
- updates.access_token = ID.generate();
117
- updates.access_token_created = new Date();
118
- }
119
- }
120
-
121
- // Update user object
122
- Object.assign(user, updates);
123
-
124
- // Update db
125
- await snap.ref.update(updates);
126
-
127
- // Log history item
128
- env.logRef.push({ action: `signin`, type: credentials.method, [credentials.method]: credentials[credentials.method], ip: req.ip, date: new Date(), success: true });
129
-
130
- // Add to cache
131
- env.authCache.set(user.uid, user);
132
-
133
- // Bind user to current request
134
- req.user = user;
135
-
136
- return user;
137
- }
138
- catch (err) {
139
- // Log error
140
- env.logRef.push({ action: 'signin', type: credentials.method, [credentials.method]: credentials[credentials.method], success: false, code: err.code || 'unexpected', message: err.code ? null : err.message, ip: req.ip, date: new Date(), ...err.details });
141
- throw err;
142
- }
143
- }
@@ -1,65 +0,0 @@
1
- import { request } from 'https';
2
- export interface SimpleFetchResponse {
3
- readonly status: number;
4
- readonly headers: { get(name: string): string }
5
- text(): Promise<string>
6
- json(): Promise<any>
7
- arrayBuffer(): Promise<ArrayBuffer>
8
- }
9
- /**
10
- * Very lightweight custom fetch implementation to avoid additional dependencies
11
- * @param url
12
- * @param options
13
- */
14
- export function fetch(url: string, options?: { method?: 'GET'|'POST'|'PUT'|'DELETE', headers?: { [name: string]: string }, body?: string }): Promise<SimpleFetchResponse> {
15
- return new Promise((resolve, reject) => {
16
- const method = options?.method || 'GET';
17
- const headers = options?.headers;
18
- const req = request(url, { method, headers }, res => {
19
-
20
- // res.setEncoding('binary'); // will result in strings!!!!
21
- const ready = new Promise<Buffer>((resolve, reject) => {
22
- let chunks = [];
23
- res.on('data', data => {
24
- chunks.push(data);
25
- });
26
- res.on('end', () => {
27
- const buffer = Buffer.concat(chunks);
28
- resolve(buffer);
29
- });
30
- res.on('error', (err) => {
31
- reject(err);
32
- })
33
- });
34
-
35
- const response: SimpleFetchResponse = {
36
- get status() { return res.statusCode },
37
- get headers() { return {
38
- get(name: string) {
39
- let val = res.headers[name.toLowerCase()];
40
- if (val instanceof Array) { return val.join(', '); }
41
- return val;
42
- }
43
- } },
44
- async text() {
45
- const buffer = await ready;
46
- return buffer.toString('utf8');
47
- },
48
- json() {
49
- // return Promise.resolve(JSON.parse(body));
50
- return this.text().then(json => JSON.parse(json));
51
- },
52
- async arrayBuffer() {
53
- const data = await ready;
54
- const arrayBuffer = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
55
- return arrayBuffer;
56
- }
57
- };
58
-
59
- resolve(response);
60
- });
61
- req.on('error', reject);
62
- options?.body && req.write(options.body, 'utf8');
63
- req.end();
64
- })
65
- }