acebase-server 1.16.2 → 1.18.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 (252) hide show
  1. package/README.md +180 -10
  2. package/bin/acebase-server.js +8 -0
  3. package/build-vars.js +2 -1
  4. package/dist/cjs/auth.js +88 -88
  5. package/dist/cjs/cluster.js +6 -56
  6. package/dist/cjs/index.d.ts +1 -1
  7. package/dist/cjs/index.js +24 -24
  8. package/dist/cjs/logger.js +73 -73
  9. package/dist/cjs/middleware/404.js +14 -14
  10. package/dist/cjs/middleware/admin-only.js +28 -28
  11. package/dist/cjs/middleware/cache.js +14 -14
  12. package/dist/cjs/middleware/connection.js +49 -49
  13. package/dist/cjs/middleware/context.js +20 -20
  14. package/dist/cjs/middleware/cors.js +50 -50
  15. package/dist/cjs/middleware/swagger.js +17 -17
  16. package/dist/cjs/middleware/user.js +57 -57
  17. package/dist/cjs/oauth-providers/dropbox.js +109 -109
  18. package/dist/cjs/oauth-providers/facebook.js +85 -85
  19. package/dist/cjs/oauth-providers/google.js +119 -119
  20. package/dist/cjs/oauth-providers/index.js +26 -26
  21. package/dist/cjs/oauth-providers/instagram.js +80 -80
  22. package/dist/cjs/oauth-providers/oauth-provider.js +20 -20
  23. package/dist/cjs/oauth-providers/spotify.js +113 -113
  24. package/dist/cjs/routes/auth-change-password.js +87 -87
  25. package/dist/cjs/routes/auth-delete.js +52 -52
  26. package/dist/cjs/routes/auth-forgot-password.js +77 -77
  27. package/dist/cjs/routes/auth-reset-password.js +97 -97
  28. package/dist/cjs/routes/auth-signin.js +46 -46
  29. package/dist/cjs/routes/auth-signout.js +61 -61
  30. package/dist/cjs/routes/auth-signup.js +142 -142
  31. package/dist/cjs/routes/auth-state.js +25 -25
  32. package/dist/cjs/routes/auth-update.js +131 -131
  33. package/dist/cjs/routes/auth-verify-email.js +71 -71
  34. package/dist/cjs/routes/auth.js +57 -54
  35. package/dist/cjs/routes/data-exists.js +33 -33
  36. package/dist/cjs/routes/data-export.js +48 -48
  37. package/dist/cjs/routes/data-get.js +70 -66
  38. package/dist/cjs/routes/data-import.js +54 -54
  39. package/dist/cjs/routes/data-index-create.js +42 -42
  40. package/dist/cjs/routes/data-index-delete.js +33 -33
  41. package/dist/cjs/routes/data-index-list.js +31 -31
  42. package/dist/cjs/routes/data-query.js +80 -70
  43. package/dist/cjs/routes/data-reflect.js +97 -86
  44. package/dist/cjs/routes/data-schema-get.js +36 -36
  45. package/dist/cjs/routes/data-schema-set.js +30 -30
  46. package/dist/cjs/routes/data-schema-test.js +43 -43
  47. package/dist/cjs/routes/data-schemas-list.js +32 -32
  48. package/dist/cjs/routes/data-set.js +85 -75
  49. package/dist/cjs/routes/data-sync-changes.js +81 -67
  50. package/dist/cjs/routes/data-sync-mutations.js +81 -67
  51. package/dist/cjs/routes/data-transaction.js +159 -139
  52. package/dist/cjs/routes/data-update.js +86 -75
  53. package/dist/cjs/routes/data.js +62 -62
  54. package/dist/cjs/routes/docs.js +258 -251
  55. package/dist/cjs/routes/meta-info.js +63 -63
  56. package/dist/cjs/routes/meta-logs.js +49 -49
  57. package/dist/cjs/routes/meta-ping.js +11 -11
  58. package/dist/cjs/routes/meta-stats.js +27 -27
  59. package/dist/cjs/routes/meta.js +19 -19
  60. package/dist/cjs/routes/oauth2-init.js +54 -54
  61. package/dist/cjs/routes/oauth2-refresh.js +42 -42
  62. package/dist/cjs/routes/oauth2-signin.js +265 -265
  63. package/dist/cjs/routes/webmanager.js +26 -26
  64. package/dist/cjs/rules.js +380 -167
  65. package/dist/cjs/sandbox.js +28 -0
  66. package/dist/cjs/schema/user.js +24 -24
  67. package/dist/cjs/server.js +410 -407
  68. package/dist/cjs/settings/email.js +2 -2
  69. package/dist/cjs/settings/index.js +175 -172
  70. package/dist/cjs/shared/clients.js +26 -26
  71. package/dist/cjs/shared/email.js +2 -2
  72. package/dist/cjs/shared/env.js +2 -2
  73. package/dist/cjs/shared/error.js +33 -33
  74. package/dist/cjs/shared/http.js +28 -28
  75. package/dist/cjs/shared/password.js +45 -45
  76. package/dist/cjs/shared/rootpath.js +16 -16
  77. package/dist/cjs/shared/signin.js +143 -143
  78. package/dist/cjs/shared/simple-fetch.js +76 -76
  79. package/dist/cjs/shared/tokens.js +79 -79
  80. package/dist/cjs/shared/validate.js +61 -61
  81. package/dist/cjs/start.js +119 -53
  82. package/dist/cjs/test.js +10 -10
  83. package/dist/cjs/websocket/index.js +331 -319
  84. package/dist/cjs/websocket/manager.js +15 -15
  85. package/dist/cjs/websocket/socket.io.js +76 -76
  86. package/dist/esm/auth.js +75 -75
  87. package/dist/esm/cluster.js +6 -54
  88. package/dist/esm/index.d.ts +1 -1
  89. package/dist/esm/index.js +4 -4
  90. package/dist/esm/logger.js +51 -51
  91. package/dist/esm/middleware/404.js +10 -10
  92. package/dist/esm/middleware/admin-only.js +24 -24
  93. package/dist/esm/middleware/cache.js +10 -10
  94. package/dist/esm/middleware/connection.js +45 -45
  95. package/dist/esm/middleware/context.js +16 -16
  96. package/dist/esm/middleware/cors.js +44 -44
  97. package/dist/esm/middleware/swagger.js +13 -13
  98. package/dist/esm/middleware/user.js +44 -44
  99. package/dist/esm/oauth-providers/dropbox.js +90 -90
  100. package/dist/esm/oauth-providers/facebook.js +66 -66
  101. package/dist/esm/oauth-providers/google.js +96 -96
  102. package/dist/esm/oauth-providers/index.js +18 -18
  103. package/dist/esm/oauth-providers/instagram.js +61 -61
  104. package/dist/esm/oauth-providers/oauth-provider.js +16 -16
  105. package/dist/esm/oauth-providers/spotify.js +92 -92
  106. package/dist/esm/routes/auth-change-password.js +72 -72
  107. package/dist/esm/routes/auth-delete.js +37 -37
  108. package/dist/esm/routes/auth-forgot-password.js +62 -62
  109. package/dist/esm/routes/auth-reset-password.js +81 -81
  110. package/dist/esm/routes/auth-signin.js +33 -33
  111. package/dist/esm/routes/auth-signout.js +47 -47
  112. package/dist/esm/routes/auth-signup.js +127 -127
  113. package/dist/esm/routes/auth-state.js +12 -12
  114. package/dist/esm/routes/auth-update.js +116 -116
  115. package/dist/esm/routes/auth-verify-email.js +57 -57
  116. package/dist/esm/routes/auth.js +53 -50
  117. package/dist/esm/routes/data-exists.js +20 -20
  118. package/dist/esm/routes/data-export.js +35 -35
  119. package/dist/esm/routes/data-get.js +56 -52
  120. package/dist/esm/routes/data-import.js +41 -41
  121. package/dist/esm/routes/data-index-create.js +28 -28
  122. package/dist/esm/routes/data-index-delete.js +20 -20
  123. package/dist/esm/routes/data-index-list.js +18 -18
  124. package/dist/esm/routes/data-query.js +66 -56
  125. package/dist/esm/routes/data-reflect.js +83 -72
  126. package/dist/esm/routes/data-schema-get.js +23 -23
  127. package/dist/esm/routes/data-schema-set.js +17 -17
  128. package/dist/esm/routes/data-schema-test.js +29 -29
  129. package/dist/esm/routes/data-schemas-list.js +19 -19
  130. package/dist/esm/routes/data-set.js +70 -60
  131. package/dist/esm/routes/data-sync-changes.js +67 -53
  132. package/dist/esm/routes/data-sync-mutations.js +67 -53
  133. package/dist/esm/routes/data-transaction.js +142 -123
  134. package/dist/esm/routes/data-update.js +71 -60
  135. package/dist/esm/routes/data.js +58 -58
  136. package/dist/esm/routes/docs.js +252 -245
  137. package/dist/esm/routes/meta-info.js +59 -59
  138. package/dist/esm/routes/meta-logs.js +35 -35
  139. package/dist/esm/routes/meta-ping.js +7 -7
  140. package/dist/esm/routes/meta-stats.js +14 -14
  141. package/dist/esm/routes/meta.js +15 -15
  142. package/dist/esm/routes/oauth2-init.js +41 -41
  143. package/dist/esm/routes/oauth2-refresh.js +29 -29
  144. package/dist/esm/routes/oauth2-signin.js +251 -251
  145. package/dist/esm/routes/webmanager.js +22 -22
  146. package/dist/esm/rules.js +374 -163
  147. package/dist/esm/sandbox.js +12 -0
  148. package/dist/esm/schema/user.js +19 -19
  149. package/dist/esm/server.js +395 -387
  150. package/dist/esm/settings/email.js +1 -1
  151. package/dist/esm/settings/index.js +168 -165
  152. package/dist/esm/shared/clients.js +22 -22
  153. package/dist/esm/shared/email.js +1 -1
  154. package/dist/esm/shared/env.js +1 -1
  155. package/dist/esm/shared/error.js +25 -25
  156. package/dist/esm/shared/http.js +22 -22
  157. package/dist/esm/shared/password.js +38 -38
  158. package/dist/esm/shared/rootpath.js +13 -13
  159. package/dist/esm/shared/signin.js +128 -128
  160. package/dist/esm/shared/simple-fetch.js +59 -59
  161. package/dist/esm/shared/tokens.js +72 -72
  162. package/dist/esm/shared/validate.js +41 -41
  163. package/dist/esm/start.js +116 -50
  164. package/dist/esm/test.js +8 -8
  165. package/dist/esm/websocket/index.js +313 -302
  166. package/dist/esm/websocket/manager.js +11 -11
  167. package/dist/esm/websocket/socket.io.js +71 -71
  168. package/dist/types/auth.d.ts +3 -3
  169. package/dist/types/cluster.d.ts +6 -1
  170. package/dist/types/index.d.ts +4 -4
  171. package/dist/types/logger.d.ts +35 -35
  172. package/dist/types/middleware/404.d.ts +7 -7
  173. package/dist/types/middleware/admin-only.d.ts +19 -19
  174. package/dist/types/middleware/cache.d.ts +3 -3
  175. package/dist/types/middleware/connection.d.ts +7 -7
  176. package/dist/types/middleware/context.d.ts +3 -3
  177. package/dist/types/middleware/cors.d.ts +25 -25
  178. package/dist/types/middleware/swagger.d.ts +3 -3
  179. package/dist/types/middleware/user.d.ts +2 -2
  180. package/dist/types/oauth-providers/dropbox.d.ts +52 -52
  181. package/dist/types/oauth-providers/facebook.d.ts +41 -41
  182. package/dist/types/oauth-providers/google.d.ts +43 -43
  183. package/dist/types/oauth-providers/index.d.ts +10 -10
  184. package/dist/types/oauth-providers/instagram.d.ts +50 -50
  185. package/dist/types/oauth-providers/oauth-provider.d.ts +74 -74
  186. package/dist/types/oauth-providers/spotify.d.ts +53 -53
  187. package/dist/types/routes/auth-change-password.d.ts +20 -20
  188. package/dist/types/routes/auth-delete.d.ts +16 -16
  189. package/dist/types/routes/auth-forgot-password.d.ts +16 -16
  190. package/dist/types/routes/auth-reset-password.d.ts +23 -23
  191. package/dist/types/routes/auth-signin.d.ts +24 -24
  192. package/dist/types/routes/auth-signout.d.ts +14 -14
  193. package/dist/types/routes/auth-signup.d.ts +32 -32
  194. package/dist/types/routes/auth-state.d.ts +13 -13
  195. package/dist/types/routes/auth-update.d.ts +33 -33
  196. package/dist/types/routes/auth-verify-email.d.ts +21 -21
  197. package/dist/types/routes/auth.d.ts +6 -6
  198. package/dist/types/routes/data-exists.d.ts +9 -9
  199. package/dist/types/routes/data-export.d.ts +10 -10
  200. package/dist/types/routes/data-get.d.ts +14 -14
  201. package/dist/types/routes/data-import.d.ts +13 -13
  202. package/dist/types/routes/data-index-create.d.ts +51 -51
  203. package/dist/types/routes/data-index-delete.d.ts +17 -17
  204. package/dist/types/routes/data-index-list.d.ts +21 -21
  205. package/dist/types/routes/data-query.d.ts +49 -49
  206. package/dist/types/routes/data-reflect.d.ts +29 -29
  207. package/dist/types/routes/data-schema-get.d.ts +11 -11
  208. package/dist/types/routes/data-schema-set.d.ts +20 -19
  209. package/dist/types/routes/data-schema-test.d.ts +19 -19
  210. package/dist/types/routes/data-schemas-list.d.ts +11 -11
  211. package/dist/types/routes/data-set.d.ts +27 -27
  212. package/dist/types/routes/data-sync-changes.d.ts +25 -28
  213. package/dist/types/routes/data-sync-mutations.d.ts +25 -28
  214. package/dist/types/routes/data-transaction.d.ts +34 -34
  215. package/dist/types/routes/data-update.d.ts +27 -27
  216. package/dist/types/routes/data.d.ts +3 -3
  217. package/dist/types/routes/docs.d.ts +3 -3
  218. package/dist/types/routes/meta-info.d.ts +11 -11
  219. package/dist/types/routes/meta-logs.d.ts +20 -20
  220. package/dist/types/routes/meta-ping.d.ts +7 -7
  221. package/dist/types/routes/meta-stats.d.ts +13 -13
  222. package/dist/types/routes/meta.d.ts +3 -3
  223. package/dist/types/routes/oauth2-init.d.ts +13 -13
  224. package/dist/types/routes/oauth2-refresh.d.ts +17 -17
  225. package/dist/types/routes/oauth2-signin.d.ts +15 -15
  226. package/dist/types/routes/webmanager.d.ts +3 -3
  227. package/dist/types/rules.d.ts +73 -34
  228. package/dist/types/sandbox.d.ts +3 -0
  229. package/dist/types/schema/user.d.ts +85 -85
  230. package/dist/types/server.d.ts +117 -111
  231. package/dist/types/settings/email.d.ts +14 -14
  232. package/dist/types/settings/index.d.ts +195 -187
  233. package/dist/types/shared/clients.d.ts +46 -46
  234. package/dist/types/shared/email.d.ts +34 -34
  235. package/dist/types/shared/env.d.ts +47 -44
  236. package/dist/types/shared/error.d.ts +15 -15
  237. package/dist/types/shared/http.d.ts +22 -21
  238. package/dist/types/shared/password.d.ts +19 -19
  239. package/dist/types/shared/rootpath.d.ts +2 -2
  240. package/dist/types/shared/signin.d.ts +31 -31
  241. package/dist/types/shared/simple-fetch.d.ts +21 -21
  242. package/dist/types/shared/tokens.d.ts +24 -24
  243. package/dist/types/shared/validate.d.ts +22 -22
  244. package/dist/types/start.d.ts +1 -1
  245. package/dist/types/test.d.ts +1 -1
  246. package/dist/types/websocket/index.d.ts +6 -6
  247. package/dist/types/websocket/manager.d.ts +99 -99
  248. package/dist/types/websocket/socket.io.d.ts +10 -10
  249. package/package.json +7 -4
  250. package/src/routes/data-schema-set.yaml +4 -0
  251. package/src/routes/data-set.yaml +5 -5
  252. package/src/routes/data-update.yaml +4 -4
@@ -1,388 +1,396 @@
1
- import { ColorStyle, DebugLogger, SimpleEventEmitter } from 'acebase-core';
2
- import { AceBaseServerConfig } from './settings/index.js';
3
- import { createApp, createRouter } from './shared/http.js';
4
- import { addWebsocketServer } from './websocket/index.js';
5
- import { AceBase } from 'acebase';
6
- import { createServer } from 'http';
7
- import { createServer as createSecureServer } from 'https';
8
- import oAuth2Providers from './oauth-providers/index.js';
9
- import { PathBasedRules } from './rules.js';
10
- import addConnectionMiddleware from './middleware/connection.js';
11
- import addCorsMiddleware from './middleware/cors.js';
12
- import addAuthenticionRoutes from './routes/auth.js';
13
- import setupAuthentication from './auth.js';
14
- import addDataRoutes from './routes/data.js';
15
- import addWebManagerRoutes from './routes/webmanager.js';
16
- import addMetadataRoutes from './routes/meta.js';
17
- import addCacheMiddleware from './middleware/cache.js';
18
- import { DatabaseLog } from './logger.js';
19
- // type PrivateLocalSettings = AceBaseLocalSettings & { storage: PrivateStorageSettings };
20
- export class AceBaseServerNotReadyError extends Error {
21
- constructor() { super('Server is not ready yet'); }
22
- }
23
- export class AceBaseExternalServerError extends Error {
24
- constructor() { super('This method is not available with an external server'); }
25
- }
26
- export class AceBaseServer extends SimpleEventEmitter {
27
- constructor(dbname, options) {
28
- super();
29
- this._ready = false;
30
- this.authProviders = {};
31
- this.config = new AceBaseServerConfig(options);
32
- this.debug = new DebugLogger(this.config.logLevel, `[${dbname}]`.colorize(ColorStyle.green));
33
- if (this.config.auth.enabled && !this.config.https.enabled) {
34
- this.debug.warn(`WARNING: Authentication is enabled, but the server is not using https. Any password and other data transmitted may be intercepted!`.colorize(ColorStyle.red));
35
- }
36
- else if (!this.config.https.enabled) {
37
- this.debug.warn(`WARNING: Server is not using https, any data transmitted may be intercepted!`.colorize(ColorStyle.red));
38
- }
39
- if (!this.config.auth.enabled) {
40
- this.debug.warn(`WARNING: Authentication is disabled, *anyone* can do *anything* with your data!`.colorize(ColorStyle.red));
41
- }
42
- // Open database(s)
43
- const dbOptions = {
44
- logLevel: this.config.logLevel,
45
- info: 'realtime database server',
46
- // NEW: Allow storage setting like AceBaseLocalSettings - could allow using other db backend (typed, but undocumented)
47
- storage: this.config.storage || {
48
- path: this.config.path,
49
- removeVoidProperties: true,
50
- },
51
- transactions: this.config.transactions,
52
- ipc: this.config.ipc,
53
- sponsor: this.config.sponsor,
54
- logColors: this.config.logColors,
55
- };
56
- this.db = new AceBase(dbname, dbOptions);
57
- const otherDbsPath = `${this.config.path}/${this.db.name}.acebase`;
58
- const authDb = (() => {
59
- if (!this.config.auth.enabled) {
60
- return null;
61
- }
62
- switch (this.config.auth.separateDb) {
63
- case true: return new AceBase('auth', { logLevel: dbOptions.logLevel, storage: { path: otherDbsPath, removeVoidProperties: true, info: `${dbname} auth database` } });
64
- case 'v2': /*NOT TESTED YET*/ return new AceBase(dbname, { logLevel: dbOptions.logLevel, storage: { type: 'auth', path: this.config.path, removeVoidProperties: true, info: `${dbname} auth database` } });
65
- default: return this.db;
66
- }
67
- })();
68
- // Create Express app
69
- this.app = createApp({ trustProxy: true, maxPayloadSize: this.config.maxPayloadSize });
70
- // Initialize and start server
71
- this.init({ authDb });
72
- }
73
- get isReady() { return this._ready; }
74
- /**
75
- * Wait for the server to be ready to accept incoming connections
76
- * @param callback (optional) callback function that is called when ready. You can also use the returned promise
77
- * @returns returns a promise that resolves when ready
78
- */
79
- async ready(callback) {
80
- if (!this._ready) {
81
- await this.once('ready');
82
- }
83
- callback?.();
84
- }
85
- /**
86
- * Gets the url the server is running at
87
- */
88
- get url() {
89
- return `http${this.config.https.enabled ? 's' : ''}://${this.config.host}:${this.config.port}/${this.config.rootPath}`;
90
- }
91
- async init(env) {
92
- const config = this.config;
93
- const db = this.db;
94
- const authDb = env.authDb;
95
- // Wait for databases to be ready to use
96
- await Promise.all([
97
- db.ready(),
98
- authDb?.ready(),
99
- ]);
100
- // Create http server
101
- const app = this.app;
102
- this.config.server?.on('request', app);
103
- const server = this.config.server || (config.https.enabled ? createSecureServer(config.https, app) : createServer(app));
104
- const clients = new Map();
105
- const securityRef = authDb ? authDb === db ? db.ref('__auth__/security') : authDb.ref('security') : null;
106
- const authRef = authDb ? authDb === db ? db.ref('__auth__/accounts') : authDb.ref('accounts') : null;
107
- const logRef = authDb ? authDb === db ? db.ref('__log__') : authDb.ref('log') : null;
108
- const logger = new DatabaseLog(logRef);
109
- // Setup rules
110
- const rulesFilePath = `${this.config.path}/${this.db.name}.acebase/rules.json`;
111
- const rules = new PathBasedRules(rulesFilePath, config.auth.defaultAccessRule, { db, debug: this.debug, authEnabled: this.config.auth.enabled });
112
- const router = createRouter();
113
- const routeEnv = {
114
- config: this.config,
115
- server,
116
- db: db,
117
- authDb,
118
- app: router,
119
- rootPath: this.config.rootPath,
120
- debug: this.debug,
121
- securityRef,
122
- authRef,
123
- log: logger,
124
- tokenSalt: null,
125
- clients,
126
- authCache: null,
127
- authProviders: this.authProviders,
128
- rules,
129
- };
130
- // Add connection middleware
131
- const killConnections = addConnectionMiddleware(routeEnv);
132
- // Add CORS middleware
133
- addCorsMiddleware(routeEnv);
134
- // Add cache middleware
135
- addCacheMiddleware(routeEnv);
136
- if (config.auth.enabled) {
137
- // Setup auth database
138
- await setupAuthentication(routeEnv);
139
- // Add auth endpoints
140
- const { resetPassword, verifyEmailAddress } = addAuthenticionRoutes(routeEnv);
141
- this.resetPassword = resetPassword;
142
- this.verifyEmailAddress = verifyEmailAddress;
143
- }
144
- // Add metadata endpoints
145
- addMetadataRoutes(routeEnv);
146
- // If environment is development, add API docs
147
- if (process.env.NODE_ENV && process.env.NODE_ENV.trim() === 'development') {
148
- this.debug.warn('DEVELOPMENT MODE: adding API docs endpoint at /docs');
149
- (await import('./routes/docs.js')).addRoute(routeEnv);
150
- (await import('./middleware/swagger.js')).addMiddleware(routeEnv);
151
- }
152
- // Add data endpoints
153
- addDataRoutes(routeEnv);
154
- // Add webmanager endpoints
155
- addWebManagerRoutes(routeEnv);
156
- // Allow adding custom routes
157
- this.extend = (method, ext_path, handler) => {
158
- const route = `/ext/${db.name}/${ext_path}`;
159
- this.debug.log(`Extending server: `, method, route);
160
- routeEnv.app[method.toLowerCase()](route, handler);
161
- };
162
- // Create websocket server
163
- addWebsocketServer(routeEnv);
164
- // Register all the routes for the app
165
- app.use(`/${this.config.rootPath}`, router);
166
- // Last but not least, add 404 handler
167
- // DISABLED because it causes server extension routes through server.extend (see above) not be be executed
168
- // add404Middleware(routeEnv);
169
- // Start listening, if no external server
170
- if (!this.config.server) {
171
- server.listen(config.port, config.host, () => {
172
- // Ready!!
173
- this.debug.log(`"${db.name}" database server running at ${this.url}`);
174
- this._ready = true;
175
- this.emitOnce(`ready`);
176
- });
177
- }
178
- // Setup pause and resume methods
179
- let paused = false;
180
- this.pause = async () => {
181
- if (this.config.server) {
182
- throw new AceBaseExternalServerError();
183
- }
184
- if (paused) {
185
- throw new Error('Server is already paused');
186
- }
187
- server.close();
188
- this.debug.warn(`Paused "${db.name}" database server at ${this.url}`);
189
- this.emit('pause');
190
- paused = true;
191
- };
192
- this.resume = async () => {
193
- if (this.config.server) {
194
- throw new AceBaseExternalServerError();
195
- }
196
- if (!paused) {
197
- throw new Error('Server is not paused');
198
- }
199
- return new Promise(resolve => {
200
- server.listen(config.port, config.host, () => {
201
- this.debug.warn(`Resumed "${db.name}" database server at ${this.url}`);
202
- this.emit('resume');
203
- paused = false;
204
- resolve();
205
- });
206
- });
207
- };
208
- // Handle SIGINT and shutdown requests
209
- const shutdown = async (request) => {
210
- this.debug.warn('shutting down server');
211
- routeEnv.rules.stop();
212
- const getConnectionsCount = () => {
213
- return new Promise((resolve, reject) => {
214
- server.getConnections((err, connections) => {
215
- if (err) {
216
- reject(err);
217
- }
218
- else {
219
- resolve(connections);
220
- }
221
- });
222
- });
223
- };
224
- const connections = await getConnectionsCount();
225
- this.debug.log(`Server has ${connections} connections`);
226
- await new Promise((resolve) => {
227
- // const interval = setInterval(async () => {
228
- // const connections = await getConnectionsCount();
229
- // this.debug.log(`Server still has ${connections} connections`);
230
- // }, 5000);
231
- // interval.unref();
232
- server.close(err => {
233
- if (err) {
234
- this.debug.error(`server.close() error: ${err.message}`);
235
- }
236
- else {
237
- this.debug.log(`server.close() success`);
238
- }
239
- resolve();
240
- });
241
- // If for some reason connection aren't broken in time - do proceed with shutdown sequence
242
- const timeout = setTimeout(() => {
243
- if (clients.size === 0) {
244
- return;
245
- }
246
- this.debug.warn(`server.close() timed out, there are still open connections`);
247
- killConnections();
248
- }, 5000);
249
- timeout.unref();
250
- this.debug.log(`Closing ${clients.size} websocket connections`);
251
- clients.forEach((client, id) => {
252
- const socket = client.socket;
253
- socket.once('disconnect', reason => {
254
- this.debug.log(`Socket ${socket.id} disconnected: ${reason}`);
255
- });
256
- socket.disconnect(true);
257
- });
258
- });
259
- this.debug.warn('closing database');
260
- await db.close();
261
- this.debug.warn('shutdown complete');
262
- // Emit events to let the outside world know we shut down.
263
- // This is especially important if this instance was running in a Node.js cluster: the process will
264
- // not exit automatically after this shutdown because Node.js' IPC channel between worker and master is still open.
265
- // By sending these events, the cluster manager can determine if it should (and when to) execute process.exit()
266
- // process.emit('acebase-server-shutdown'); // Emit on process
267
- process.emit('beforeExit', request.sigint ? 130 : 0); // Emit on process
268
- try {
269
- process.send && process.send('acebase-server-shutdown'); // Send to master process when running in a Node.js cluster
270
- }
271
- catch (err) {
272
- // IPC Channel has apparently been closed already
273
- }
274
- this.emit('shutdown'); // Emit on AceBaseServer instance
275
- };
276
- this.shutdown = async () => {
277
- if (this.config.server) {
278
- throw new AceBaseExternalServerError();
279
- }
280
- await shutdown({ sigint: false });
281
- };
282
- // Offload shutdown control to an external server
283
- if (this.config.server) {
284
- server.on('close', function close() {
285
- server.off('request', app);
286
- server.off('close', close);
287
- shutdown({ sigint: false });
288
- });
289
- const ready = () => {
290
- this.debug.log(`"${db.name}" database server running at ${this.url}`);
291
- this._ready = true;
292
- this.emitOnce(`ready`);
293
- server.off('listening', ready);
294
- };
295
- if (server.listening) {
296
- ready();
297
- }
298
- else {
299
- server.on('listening', ready);
300
- }
301
- }
302
- else {
303
- process.on('SIGINT', () => shutdown({ sigint: true }));
304
- }
305
- }
306
- /**
307
- * Reset a user's password. This can also be done using the auth/reset_password API endpoint
308
- * @param clientIp ip address of the user
309
- * @param code reset code that was sent to the user's email address
310
- * @param newPassword new password chosen by the user
311
- */
312
- resetPassword(clientIp, code, newPassword) {
313
- throw new AceBaseServerNotReadyError();
314
- }
315
- /**
316
- * Marks a user account's email address as validated. This can also be done using the auth/verify_email API endpoint
317
- * @param clientIp ip address of the user
318
- * @param code verification code sent to the user's email address
319
- */
320
- verifyEmailAddress(clientIp, code) {
321
- throw new AceBaseServerNotReadyError();
322
- }
323
- /**
324
- * Shuts down the server. Stops listening for incoming connections, breaks current connections and closes the database.
325
- * Is automatically executed when a "SIGINT" process event is received.
326
- *
327
- * Once the shutdown procedure is completed, it emits a "shutdown" event on the server instance, "acebase-server-shutdown" event on the `process`, and sends an 'acebase-server-shutdown' IPC message if Node.js clustering is used.
328
- * These events can be handled by cluster managing code to `kill` or `exit` the process safely.
329
- */
330
- shutdown() {
331
- throw new AceBaseServerNotReadyError();
332
- }
333
- /**
334
- * Temporarily stops the server from handling incoming connections, but keeps existing connections open
335
- */
336
- pause() {
337
- throw new AceBaseServerNotReadyError();
338
- }
339
- /**
340
- * Resumes handling incoming connections
341
- */
342
- resume() {
343
- throw new AceBaseServerNotReadyError();
344
- }
345
- /**
346
- * Extend the server API with your own custom functions. Your handler will be listening
347
- * on path /ext/[db name]/[ext_path].
348
- * @example
349
- * // Server side:
350
- * const _quotes = [...];
351
- * server.extend('get', 'quotes/random', (req, res) => {
352
- * let index = Math.round(Math.random() * _quotes.length);
353
- * res.send(quotes[index]);
354
- * })
355
- * // Client side:
356
- * client.callExtension('get', 'quotes/random')
357
- * .then(quote => {
358
- * console.log(`Got random quote: ${quote}`);
359
- * })
360
- * @param method http method to bind to
361
- * @param ext_path path to bind to (appended to /ext/)
362
- * @param handler your Express request handler callback
363
- */
364
- extend(method, ext_path, handler) {
365
- throw new AceBaseServerNotReadyError();
366
- }
367
- /**
368
- * Configure an auth provider to allow users to sign in with Facebook, Google, etc
369
- * @param providerName name of the third party OAuth provider. Eg: "Facebook", "Google", "spotify" etc
370
- * @param settings API key & secret for the OAuth provider
371
- * @returns Returns the created auth provider instance, which can be used to call non-user specific methods the provider might support. (example: the Spotify auth provider supports getClientAuthToken, which allows API calls to be made to the core (non-user) spotify service)
372
- */
373
- configAuthProvider(providerName, settings) {
374
- if (!this.config.auth.enabled) {
375
- throw new Error(`Authentication is not enabled`);
376
- }
377
- try {
378
- const AuthProvider = oAuth2Providers[providerName];
379
- const provider = new AuthProvider(settings);
380
- this.authProviders[providerName] = provider;
381
- return provider;
382
- }
383
- catch (err) {
384
- throw new Error(`Failed to configure provider ${providerName}: ${err.message}`);
385
- }
386
- }
387
- }
1
+ import { ColorStyle, DebugLogger, SimpleEventEmitter } from 'acebase-core';
2
+ import { AceBaseServerConfig } from './settings/index.js';
3
+ import { createApp, createRouter } from './shared/http.js';
4
+ import { addWebsocketServer } from './websocket/index.js';
5
+ import { AceBase } from 'acebase';
6
+ import { createServer } from 'http';
7
+ import { createServer as createSecureServer } from 'https';
8
+ import oAuth2Providers from './oauth-providers/index.js';
9
+ import { PathBasedRules } from './rules.js';
10
+ import addConnectionMiddleware from './middleware/connection.js';
11
+ import addCorsMiddleware from './middleware/cors.js';
12
+ import addAuthenticionRoutes from './routes/auth.js';
13
+ import setupAuthentication from './auth.js';
14
+ import addDataRoutes from './routes/data.js';
15
+ import addWebManagerRoutes from './routes/webmanager.js';
16
+ import addMetadataRoutes from './routes/meta.js';
17
+ import add404Middleware from './middleware/404.js';
18
+ import addCacheMiddleware from './middleware/cache.js';
19
+ import { DatabaseLog } from './logger.js';
20
+ // type PrivateLocalSettings = AceBaseLocalSettings & { storage: PrivateStorageSettings };
21
+ export class AceBaseServerNotReadyError extends Error {
22
+ constructor() { super('Server is not ready yet'); }
23
+ }
24
+ export class AceBaseExternalServerError extends Error {
25
+ constructor() { super('This method is not available with an external server'); }
26
+ }
27
+ export class AceBaseServer extends SimpleEventEmitter {
28
+ get isReady() { return this._ready; }
29
+ /**
30
+ * Wait for the server to be ready to accept incoming connections
31
+ * @param callback (optional) callback function that is called when ready. You can also use the returned promise
32
+ * @returns returns a promise that resolves when ready
33
+ */
34
+ async ready(callback) {
35
+ if (!this._ready) {
36
+ await this.once('ready');
37
+ }
38
+ callback?.();
39
+ }
40
+ /**
41
+ * Gets the url the server is running at
42
+ */
43
+ get url() {
44
+ return `http${this.config.https.enabled ? 's' : ''}://${this.config.host}:${this.config.port}/${this.config.rootPath}`;
45
+ }
46
+ constructor(dbname, options) {
47
+ super();
48
+ this._ready = false;
49
+ this.authProviders = {};
50
+ this.config = new AceBaseServerConfig(options);
51
+ this.debug = new DebugLogger(this.config.logLevel, `[${dbname}]`.colorize(ColorStyle.green));
52
+ if (this.config.auth.enabled && !this.config.https.enabled) {
53
+ this.debug.warn(`WARNING: Authentication is enabled, but the server is not using https. Any password and other data transmitted may be intercepted!`.colorize(ColorStyle.red));
54
+ }
55
+ else if (!this.config.https.enabled) {
56
+ this.debug.warn(`WARNING: Server is not using https, any data transmitted may be intercepted!`.colorize(ColorStyle.red));
57
+ }
58
+ if (!this.config.auth.enabled) {
59
+ this.debug.warn(`WARNING: Authentication is disabled, *anyone* can do *anything* with your data!`.colorize(ColorStyle.red));
60
+ }
61
+ // Open database(s)
62
+ const dbOptions = {
63
+ logLevel: this.config.logLevel,
64
+ info: 'realtime database server',
65
+ storage: {
66
+ path: this.config.path,
67
+ removeVoidProperties: true,
68
+ ipc: this.config.ipc,
69
+ ...this.config.storage, // Allow overriding storage settings - allows using other db backends (typed, but undocumented)
70
+ },
71
+ transactions: this.config.transactions,
72
+ sponsor: this.config.sponsor,
73
+ logColors: this.config.logColors,
74
+ };
75
+ this.db = new AceBase(dbname, dbOptions);
76
+ const otherDbsPath = `${this.config.path}/${this.db.name}.acebase`;
77
+ const authDb = (() => {
78
+ if (!this.config.auth.enabled) {
79
+ return null;
80
+ }
81
+ switch (this.config.auth.separateDb) {
82
+ case true: return new AceBase('auth', { logLevel: dbOptions.logLevel, storage: { path: otherDbsPath, removeVoidProperties: true, info: `${dbname} auth database` } });
83
+ case 'v2': /*NOT TESTED YET*/ return new AceBase(dbname, { logLevel: dbOptions.logLevel, storage: { type: 'auth', path: this.config.path, removeVoidProperties: true, info: `${dbname} auth database` } });
84
+ default: return this.db;
85
+ }
86
+ })();
87
+ // Create Express app
88
+ this.app = createApp({ trustProxy: true, maxPayloadSize: this.config.maxPayloadSize });
89
+ this.router = createRouter();
90
+ this.app.use(`/${this.config.rootPath}`, this.router);
91
+ // Initialize and start server
92
+ this.init({ authDb });
93
+ }
94
+ async init(env) {
95
+ const config = this.config;
96
+ const db = this.db;
97
+ const authDb = env.authDb;
98
+ // Wait for databases to be ready to use
99
+ await Promise.all([
100
+ db.ready(),
101
+ authDb?.ready(),
102
+ ]);
103
+ // Create http server
104
+ this.config.server?.on('request', this.app);
105
+ const server = this.config.server || (config.https.enabled ? createSecureServer(config.https, this.app) : createServer(this.app));
106
+ const clients = new Map();
107
+ const securityRef = authDb ? authDb === db ? db.ref('__auth__/security') : authDb.ref('security') : null;
108
+ const authRef = authDb ? authDb === db ? db.ref('__auth__/accounts') : authDb.ref('accounts') : null;
109
+ const logRef = authDb ? authDb === db ? db.ref('__log__') : authDb.ref('log') : null;
110
+ const logger = new DatabaseLog(logRef);
111
+ // Setup rules
112
+ const rulesFilePath = `${this.config.path}/${this.db.name}.acebase/rules.json`;
113
+ const rules = new PathBasedRules(rulesFilePath, config.auth.defaultAccessRule, { db, debug: this.debug, authEnabled: this.config.auth.enabled });
114
+ this.setRule = (rulePath, ruleType, callback) => {
115
+ return rules.add(rulePath, ruleType, callback);
116
+ };
117
+ const routeEnv = {
118
+ config: this.config,
119
+ server,
120
+ db: db,
121
+ authDb,
122
+ app: this.app,
123
+ router: this.router,
124
+ rootPath: this.config.rootPath,
125
+ debug: this.debug,
126
+ securityRef,
127
+ authRef,
128
+ log: logger,
129
+ tokenSalt: null,
130
+ clients,
131
+ authCache: null,
132
+ authProviders: this.authProviders,
133
+ rules,
134
+ instance: this,
135
+ };
136
+ // Add connection middleware
137
+ const killConnections = addConnectionMiddleware(routeEnv);
138
+ // Add CORS middleware
139
+ addCorsMiddleware(routeEnv);
140
+ // Add cache middleware
141
+ addCacheMiddleware(routeEnv);
142
+ if (config.auth.enabled) {
143
+ // Setup auth database
144
+ await setupAuthentication(routeEnv);
145
+ // Add auth endpoints
146
+ const { resetPassword, verifyEmailAddress } = addAuthenticionRoutes(routeEnv);
147
+ this.resetPassword = resetPassword;
148
+ this.verifyEmailAddress = verifyEmailAddress;
149
+ }
150
+ // Add metadata endpoints
151
+ addMetadataRoutes(routeEnv);
152
+ // If environment is development, add API docs
153
+ if (process.env.NODE_ENV && process.env.NODE_ENV.trim() === 'development') {
154
+ this.debug.warn('DEVELOPMENT MODE: adding API docs endpoint at /docs');
155
+ (await import('./routes/docs.js')).addRoute(routeEnv);
156
+ (await import('./middleware/swagger.js')).addMiddleware(routeEnv);
157
+ }
158
+ // Add data endpoints
159
+ addDataRoutes(routeEnv);
160
+ // Add webmanager endpoints
161
+ addWebManagerRoutes(routeEnv);
162
+ // Allow adding custom routes
163
+ this.extend = (method, ext_path, handler) => {
164
+ const route = `/ext/${db.name}/${ext_path}`;
165
+ this.debug.log(`Extending server: `, method, route);
166
+ this.router[method.toLowerCase()](route, handler);
167
+ };
168
+ // Create websocket server
169
+ addWebsocketServer(routeEnv);
170
+ // Run init callback to allow user code to call `server.extend`, `server.router.[method]`, `server.setRule` etc before the server starts listening
171
+ await this.config.init?.(this);
172
+ // If we own the server, add 404 handler
173
+ if (!this.config.server) {
174
+ add404Middleware(routeEnv);
175
+ }
176
+ // Setup pause and resume methods
177
+ let paused = false;
178
+ this.pause = async () => {
179
+ if (this.config.server) {
180
+ throw new AceBaseExternalServerError();
181
+ }
182
+ if (paused) {
183
+ throw new Error('Server is already paused');
184
+ }
185
+ server.close();
186
+ this.debug.warn(`Paused "${db.name}" database server at ${this.url}`);
187
+ this.emit('pause');
188
+ paused = true;
189
+ };
190
+ this.resume = async () => {
191
+ if (this.config.server) {
192
+ throw new AceBaseExternalServerError();
193
+ }
194
+ if (!paused) {
195
+ throw new Error('Server is not paused');
196
+ }
197
+ return new Promise(resolve => {
198
+ server.listen(config.port, config.host, () => {
199
+ this.debug.warn(`Resumed "${db.name}" database server at ${this.url}`);
200
+ this.emit('resume');
201
+ paused = false;
202
+ resolve();
203
+ });
204
+ });
205
+ };
206
+ // Handle SIGINT and shutdown requests
207
+ const shutdown = async (request) => {
208
+ this.debug.warn('shutting down server');
209
+ routeEnv.rules.stop();
210
+ const getConnectionsCount = () => {
211
+ return new Promise((resolve, reject) => {
212
+ server.getConnections((err, connections) => {
213
+ if (err) {
214
+ reject(err);
215
+ }
216
+ else {
217
+ resolve(connections);
218
+ }
219
+ });
220
+ });
221
+ };
222
+ const connections = await getConnectionsCount();
223
+ this.debug.log(`Server has ${connections} connections`);
224
+ await new Promise((resolve) => {
225
+ // const interval = setInterval(async () => {
226
+ // const connections = await getConnectionsCount();
227
+ // this.debug.log(`Server still has ${connections} connections`);
228
+ // }, 5000);
229
+ // interval.unref();
230
+ server.close(err => {
231
+ if (err) {
232
+ this.debug.error(`server.close() error: ${err.message}`);
233
+ }
234
+ else {
235
+ this.debug.log(`server.close() success`);
236
+ }
237
+ resolve();
238
+ });
239
+ // If for some reason connection aren't broken in time - do proceed with shutdown sequence
240
+ const timeout = setTimeout(() => {
241
+ if (clients.size === 0) {
242
+ return;
243
+ }
244
+ this.debug.warn(`server.close() timed out, there are still open connections`);
245
+ killConnections();
246
+ }, 5000);
247
+ timeout.unref();
248
+ this.debug.log(`Closing ${clients.size} websocket connections`);
249
+ clients.forEach((client, id) => {
250
+ const socket = client.socket;
251
+ socket.once('disconnect', reason => {
252
+ this.debug.log(`Socket ${socket.id} disconnected: ${reason}`);
253
+ });
254
+ socket.disconnect(true);
255
+ });
256
+ });
257
+ this.debug.warn('closing database');
258
+ await db.close();
259
+ this.debug.warn('shutdown complete');
260
+ // Emit events to let the outside world know we shut down.
261
+ // This is especially important if this instance was running in a Node.js cluster: the process will
262
+ // not exit automatically after this shutdown because Node.js' IPC channel between worker and master is still open.
263
+ // By sending these events, the cluster manager can determine if it should (and when to) execute process.exit()
264
+ // process.emit('acebase-server-shutdown'); // Emit on process
265
+ process.emit('beforeExit', request.sigint ? 130 : 0); // Emit on process
266
+ try {
267
+ process.send && process.send('acebase-server-shutdown'); // Send to master process when running in a Node.js cluster
268
+ }
269
+ catch (err) {
270
+ // IPC Channel has apparently been closed already
271
+ }
272
+ this.emit('shutdown'); // Emit on AceBaseServer instance
273
+ };
274
+ this.shutdown = async () => {
275
+ if (this.config.server) {
276
+ throw new AceBaseExternalServerError();
277
+ }
278
+ await shutdown({ sigint: false });
279
+ };
280
+ if (this.config.server) {
281
+ // Offload shutdown control to an external server
282
+ server.on('close', function close() {
283
+ server.off('request', this.app);
284
+ server.off('close', close);
285
+ shutdown({ sigint: false });
286
+ });
287
+ const ready = () => {
288
+ this.debug.log(`"${db.name}" database server running at ${this.url}`);
289
+ this._ready = true;
290
+ this.emitOnce(`ready`);
291
+ server.off('listening', ready);
292
+ };
293
+ if (server.listening) {
294
+ ready();
295
+ }
296
+ else {
297
+ server.on('listening', ready);
298
+ }
299
+ }
300
+ else {
301
+ // Start listening
302
+ server.listen(config.port, config.host, () => {
303
+ // Ready!!
304
+ this.debug.log(`"${db.name}" database server running at ${this.url}`);
305
+ this._ready = true;
306
+ this.emitOnce(`ready`);
307
+ });
308
+ process.on('SIGINT', () => shutdown({ sigint: true }));
309
+ }
310
+ }
311
+ /**
312
+ * Reset a user's password. This can also be done using the auth/reset_password API endpoint
313
+ * @param clientIp ip address of the user
314
+ * @param code reset code that was sent to the user's email address
315
+ * @param newPassword new password chosen by the user
316
+ */
317
+ resetPassword(clientIp, code, newPassword) {
318
+ throw new AceBaseServerNotReadyError();
319
+ }
320
+ /**
321
+ * Marks a user account's email address as validated. This can also be done using the auth/verify_email API endpoint
322
+ * @param clientIp ip address of the user
323
+ * @param code verification code sent to the user's email address
324
+ */
325
+ verifyEmailAddress(clientIp, code) {
326
+ throw new AceBaseServerNotReadyError();
327
+ }
328
+ /**
329
+ * Shuts down the server. Stops listening for incoming connections, breaks current connections and closes the database.
330
+ * Is automatically executed when a "SIGINT" process event is received.
331
+ *
332
+ * Once the shutdown procedure is completed, it emits a "shutdown" event on the server instance, "acebase-server-shutdown" event on the `process`, and sends an 'acebase-server-shutdown' IPC message if Node.js clustering is used.
333
+ * These events can be handled by cluster managing code to `kill` or `exit` the process safely.
334
+ */
335
+ shutdown() {
336
+ throw new AceBaseServerNotReadyError();
337
+ }
338
+ /**
339
+ * Temporarily stops the server from handling incoming connections, but keeps existing connections open
340
+ */
341
+ pause() {
342
+ throw new AceBaseServerNotReadyError();
343
+ }
344
+ /**
345
+ * Resumes handling incoming connections
346
+ */
347
+ resume() {
348
+ throw new AceBaseServerNotReadyError();
349
+ }
350
+ /**
351
+ * Extend the server API with your own custom functions. Your handler will be listening
352
+ * on path /ext/[db name]/[ext_path].
353
+ * @example
354
+ * // Server side:
355
+ * const _quotes = [...];
356
+ * server.extend('get', 'quotes/random', (req, res) => {
357
+ * let index = Math.round(Math.random() * _quotes.length);
358
+ * res.send(quotes[index]);
359
+ * })
360
+ * // Client side:
361
+ * client.callExtension('get', 'quotes/random')
362
+ * .then(quote => {
363
+ * console.log(`Got random quote: ${quote}`);
364
+ * })
365
+ * @param method http method to bind to
366
+ * @param ext_path path to bind to (appended to /ext/)
367
+ * @param handler your Express request handler callback
368
+ */
369
+ extend(method, ext_path, handler) {
370
+ throw new AceBaseServerNotReadyError();
371
+ }
372
+ /**
373
+ * Configure an auth provider to allow users to sign in with Facebook, Google, etc
374
+ * @param providerName name of the third party OAuth provider. Eg: "Facebook", "Google", "spotify" etc
375
+ * @param settings API key & secret for the OAuth provider
376
+ * @returns Returns the created auth provider instance, which can be used to call non-user specific methods the provider might support. (example: the Spotify auth provider supports getClientAuthToken, which allows API calls to be made to the core (non-user) spotify service)
377
+ */
378
+ configAuthProvider(providerName, settings) {
379
+ if (!this.config.auth.enabled) {
380
+ throw new Error(`Authentication is not enabled`);
381
+ }
382
+ try {
383
+ const AuthProvider = oAuth2Providers[providerName];
384
+ const provider = new AuthProvider(settings);
385
+ this.authProviders[providerName] = provider;
386
+ return provider;
387
+ }
388
+ catch (err) {
389
+ throw new Error(`Failed to configure provider ${providerName}: ${err.message}`);
390
+ }
391
+ }
392
+ setRule(paths, types, callback) {
393
+ throw new AceBaseServerNotReadyError();
394
+ }
395
+ }
388
396
  //# sourceMappingURL=server.js.map