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,303 +1,314 @@
1
- import { ColorStyle, Transport } from 'acebase-core';
2
- import { ConnectedClient } from '../shared/clients.js';
3
- import { decodePublicAccessToken } from '../shared/tokens.js';
4
- import { createServer } from './socket.io.js';
5
- export class SocketRequestError extends Error {
6
- constructor(code, message) {
7
- super(message);
8
- this.code = code;
9
- }
10
- }
11
- export const addWebsocketServer = (env) => {
12
- // TODO: Allow using uWebSockets.js server instead of Socket.IO
13
- const serverManager = createServer(env);
14
- const getClientBySocketId = (id, event) => {
15
- const client = env.clients.get(id);
16
- if (!client) {
17
- env.debug.error(`Cannot find client "${id}" for socket event "${event}"`);
18
- }
19
- return client;
20
- };
21
- serverManager.on('connect', event => {
22
- const client = new ConnectedClient(event.socket);
23
- env.clients.set(client.id, client);
24
- env.debug.warn(`New socket connected, total: ${env.clients.size}`);
25
- serverManager.send(event.socket, 'welcome');
26
- });
27
- serverManager.on('disconnect', event => {
28
- // We lost one
29
- const client = getClientBySocketId(event.socket_id, 'disconnect');
30
- if (!client) {
31
- return;
32
- } // Disconnected a client we did not know? Don't crash, just ignore.
33
- const subscribedPaths = Object.keys(client.subscriptions);
34
- if (subscribedPaths.length > 0) {
35
- // TODO: Substitute the original callbacks to cache them
36
- // if the client then reconnects within a certain time,
37
- // we can send the missed notifications
38
- //
39
- // subscribedPaths.forEach(path => {
40
- // client.subscriptions[path].forEach(subscr => {
41
- // subscr.callback
42
- // })
43
- // });
44
- const remove = [];
45
- subscribedPaths.forEach(path => {
46
- remove.push(...client.subscriptions[path]);
47
- });
48
- remove.forEach(subscr => {
49
- // Unsubscribe them at db level and remove from our list
50
- env.db.api.unsubscribe(subscr.path, subscr.event, subscr.callback); //db.ref(subscr.path).off(subscr.event, subscr.callback);
51
- const pathSubs = client.subscriptions[subscr.path];
52
- pathSubs.splice(pathSubs.indexOf(subscr), 1);
53
- });
54
- }
55
- env.clients.delete(client.id);
56
- env.debug.verbose(`Socket disconnected, total: ${env.clients.size}`);
57
- });
58
- serverManager.on('signin', event => {
59
- // client sends this request once user has been signed in, binds the user to the socket,
60
- // deprecated since client v0.9.4, which sends client_id with signin api call
61
- // const client = clients.get(socket.id);
62
- const client = getClientBySocketId(event.socket_id, 'signin');
63
- if (!client) {
64
- return;
65
- }
66
- try {
67
- const uid = decodePublicAccessToken(event.data.accessToken, env.tokenSalt).uid;
68
- client.user = env.authCache.get(uid) || null;
69
- }
70
- catch (err) {
71
- // no way to bind the user
72
- env.debug.error(`websocket: invalid access token passed to signin: ${event.data.accessToken}`);
73
- }
74
- });
75
- serverManager.on('signout', event => {
76
- // deprecated since client v0.9.4, which sends client_id with signout api call
77
- // const client = clients.get(socket.id);
78
- const client = getClientBySocketId(event.socket_id, 'signout');
79
- if (!client) {
80
- return;
81
- }
82
- client.user = null;
83
- });
84
- serverManager.on('oauth2-signin', async (event) => {
85
- // acebase-client does not use socket oauth flow yet
86
- const client = getClientBySocketId(event.socket_id, 'oauth2-signin');
87
- if (!client) {
88
- return;
89
- }
90
- const request = event.data;
91
- const providerName = typeof request === 'string' ? request : request.provider;
92
- try {
93
- const provider = env.authProviders[providerName];
94
- const state = Buffer.from(JSON.stringify({ flow: 'socket', provider: providerName, client_id: client.id })).toString('base64');
95
- const clientAuthUrl = await provider.init({ redirect_url: `${request.server.protocol}://${request.server.host}:${request.server.port}/ouath2/${env.db.name}/signin`, state, options: request.options });
96
- serverManager.send(event.socket, 'oauth2-signin', { action: 'auth', url: clientAuthUrl });
97
- }
98
- catch (err) {
99
- env.debug.error(`websocket: cannot sign in with oauth provider ${providerName}`);
100
- serverManager.send(event.socket, 'oauth2-signin', { error: err.message });
101
- }
102
- });
103
- const acknowledgeRequest = (socket, requestId) => {
104
- // Send acknowledgement
105
- serverManager.send(socket, 'result', {
106
- success: true,
107
- req_id: requestId,
108
- });
109
- };
110
- const failRequest = (socket, requestId, code) => {
111
- // Send error
112
- serverManager.send(socket, 'result', {
113
- success: false,
114
- reason: code,
115
- req_id: requestId,
116
- });
117
- };
118
- serverManager.on('subscribe', event => {
119
- // Client wants to subscribe to events on a node
120
- const client = getClientBySocketId(event.socket_id, 'subscribe');
121
- if (!client) {
122
- return;
123
- }
124
- env.debug.verbose(`Client ${event.socket_id} subscribes to event "${event.data.event}" on path "/${event.data.path}"`.colorize([ColorStyle.bgWhite, ColorStyle.black]));
125
- const subscriptionPath = event.data.path;
126
- const isSubscribed = () => subscriptionPath in client.subscriptions && client.subscriptions[subscriptionPath].some(s => s.event === event.data.event);
127
- if (isSubscribed()) {
128
- return acknowledgeRequest(event.socket, event.data.req_id);
129
- }
130
- // Get client
131
- // const client = clients.get(socket.id);
132
- if (!env.rules.userHasAccess(client.user, subscriptionPath, false)) {
133
- env.log.error('event.subscribe', 'access_denied', { uid: client.user?.uid ?? 'anonymous', path: subscriptionPath });
134
- return failRequest(event.socket, event.data.req_id, 'access_denied');
135
- }
136
- const callback = (err, path, currentValue, previousValue, context) => {
137
- if (!isSubscribed()) {
138
- // Not subscribed anymore. Cancel sending
139
- return;
140
- }
141
- if (!env.rules.userHasAccess(client.user, path, false)) {
142
- if (!subscriptionPath.includes('*') && !subscriptionPath.includes('$')) {
143
- // Could potentially be very many callbacks, so
144
- // DISABLED: logRef.push({ action: `access_revoked`, uid: client.user ? client.user.uid : '-', path: subscriptionPath });
145
- // Only log when user subscribes again
146
- failRequest(event.socket, event.data.req_id, 'access_denied');
147
- }
148
- return;
149
- }
150
- if (err) {
151
- return;
152
- }
153
- const val = Transport.serialize({
154
- current: currentValue,
155
- previous: previousValue,
156
- });
157
- env.debug.verbose(`Sending data event "${event.data.event}" for path "/${path}" to client ${event.socket_id}`.colorize([ColorStyle.bgWhite, ColorStyle.black]));
158
- // TODO: let large data events notify the client, then let them download the data manually so it doesn't have to be transmitted through the websocket
159
- serverManager.send(event.socket, 'data-event', {
160
- subscr_path: subscriptionPath,
161
- path,
162
- event: event.data.event,
163
- val,
164
- context,
165
- });
166
- };
167
- let pathSubs = client.subscriptions[subscriptionPath];
168
- if (!pathSubs) {
169
- pathSubs = client.subscriptions[subscriptionPath] = [];
170
- }
171
- const subscr = { path: subscriptionPath, event: event.data.event, callback };
172
- pathSubs.push(subscr);
173
- env.db.api.subscribe(subscriptionPath, event.data.event, callback);
174
- acknowledgeRequest(event.socket, event.data.req_id);
175
- });
176
- serverManager.on('unsubscribe', event => {
177
- // Client unsubscribes from events on a node
178
- const client = getClientBySocketId(event.socket_id, 'unsubscribe');
179
- if (!client) {
180
- return;
181
- }
182
- env.debug.verbose(`Client ${event.socket_id} is unsubscribing from event "${event.data.event || '(any)'}" on path "/${event.data.path}"`.colorize([ColorStyle.bgWhite, ColorStyle.black]));
183
- // const client = clients.get(socket.id);
184
- const pathSubs = client.subscriptions[event.data.path];
185
- if (!pathSubs) {
186
- // We have no knowledge of any active subscriptions on this path
187
- return acknowledgeRequest(event.socket, event.data.req_id);
188
- }
189
- let remove = pathSubs;
190
- if (event.data.event) {
191
- // Unsubscribe from a specific event
192
- remove = pathSubs.filter(subscr => subscr.event === event.data.event);
193
- }
194
- remove.forEach(subscr => {
195
- // Unsubscribe them at db level and remove from our list
196
- //this.debug.verbose(` - unsubscribing from event ${subscr.event} with${subscr.callback ? "" : "out"} callback on path "${data.path}"`);
197
- env.db.api.unsubscribe(subscr.path, subscr.event, subscr.callback); //db.api.unsubscribe(data.path, subscr.event, subscr.callback);
198
- pathSubs.splice(pathSubs.indexOf(subscr), 1);
199
- });
200
- if (pathSubs.length === 0) {
201
- // No subscriptions left on this path, remove the path entry
202
- delete client.subscriptions[event.data.path];
203
- }
204
- return acknowledgeRequest(event.socket, event.data.req_id);
205
- });
206
- serverManager.on('query-unsubscribe', event => {
207
- // Client unsubscribing from realtime query events
208
- const client = getClientBySocketId(event.socket_id, 'query-unsubscribe');
209
- if (!client) {
210
- return;
211
- }
212
- env.debug.verbose(`Client ${event.socket_id} is unsubscribing from realtime query "${event.data.query_id}"`);
213
- // const client = clients.get(socket.id);
214
- delete client.realtimeQueries[event.data.query_id];
215
- acknowledgeRequest(event.socket, event.data.req_id);
216
- });
217
- const TRANSACTION_TIMEOUT_MS = 10000; // 10s to finish a started transaction
218
- serverManager.on('transaction-start', event => {
219
- // Start transaction
220
- const client = getClientBySocketId(event.socket_id, 'transaction-start');
221
- if (!client || !event.data) {
222
- return;
223
- }
224
- const LOG_ACTION = 'socket.transaction.start';
225
- const LOG_DETAILS = { ip: event.socket.conn.remoteAddress, uid: client.user?.uid ?? null, path: event.data.path };
226
- env.debug.verbose(`Client ${event.socket_id} is sending transaction start request on path "${event.data.path}"`);
227
- const data = event.data;
228
- const tx = {
229
- id: data.id,
230
- started: Date.now(),
231
- path: data.path,
232
- context: data.context,
233
- finish: undefined,
234
- timeout: setTimeout(() => {
235
- delete client.transactions[tx.id];
236
- tx.finish(); // Finish without value cancels the transaction
237
- env.log.error(LOG_ACTION, 'timeout', LOG_DETAILS);
238
- serverManager.send(event.socket, 'tx_error', { id: tx.id, reason: 'timeout' });
239
- }, TRANSACTION_TIMEOUT_MS),
240
- };
241
- const access = env.rules.userHasAccess(client.user, data.path, true);
242
- if (!access.allow) {
243
- // throw new AccessDeniedError(`access_denied`);
244
- env.log.error(LOG_ACTION, 'unauthorized', { ...LOG_DETAILS, rule_code: access.code, rule_path: access.rulePath ?? null }, access.details);
245
- return serverManager.send(event.socket, 'tx_error', { id: tx.id, reason: 'access_denied' });
246
- }
247
- // Bind to client
248
- client.transactions[data.id] = tx;
249
- // Start transaction
250
- env.debug.verbose(`Transaction ${tx.id} starting...`);
251
- const donePromise = env.db.api.transaction(tx.path, val => {
252
- env.debug.verbose(`Transaction ${tx.id} started with value: `, val);
253
- const currentValue = Transport.serialize(val);
254
- const promise = new Promise((resolve) => {
255
- tx.finish = (val) => {
256
- env.debug.verbose(`Transaction ${tx.id} finishing with value: `, val);
257
- resolve(val);
258
- return donePromise;
259
- };
260
- });
261
- serverManager.send(event.socket, 'tx_started', { id: tx.id, value: currentValue });
262
- return promise;
263
- }, { context: tx.context });
264
- });
265
- serverManager.on('transaction-finish', async (event) => {
266
- // Finish transaction
267
- const client = getClientBySocketId(event.socket_id, 'transaction-finish');
268
- if (!client || !event.data) {
269
- return;
270
- }
271
- const LOG_ACTION = 'socket.transaction.finish';
272
- const LOG_DETAILS = { ip: event.socket.conn.remoteAddress, uid: client.user?.uid ?? null, path: event.data.path };
273
- const data = event.data;
274
- const tx = client.transactions[data.id];
275
- try {
276
- if (!tx || data.path !== tx.path) {
277
- env.log.error(LOG_ACTION, tx ? 'wrong_path' : 'not_found', { ...LOG_DETAILS, id: data.id, tx_path: tx?.path ?? null });
278
- throw new SocketRequestError('transaction_not_found', 'Transaction not found');
279
- }
280
- clearTimeout(tx.timeout);
281
- delete client.transactions[data.id];
282
- const access = env.rules.userHasAccess(client.user, data.path, true);
283
- if (!access.allow) {
284
- env.log.error(LOG_ACTION, 'unauthorized', { ...LOG_DETAILS, rule_code: access.code, rule_path: access.rulePath ?? null }, access.details);
285
- throw new SocketRequestError('access_denied', 'Access denied');
286
- }
287
- const newValue = 'val' in data.value ? Transport.deserialize(data.value) : undefined;
288
- const { cursor } = await tx.finish(newValue);
289
- env.debug.verbose(`Transaction ${tx.id} finished`);
290
- serverManager.send(event.socket, 'tx_completed', { id: tx.id, context: { cursor } });
291
- }
292
- catch (err) {
293
- if (!(err instanceof SocketRequestError)) {
294
- // Other errors have been logged already
295
- env.log.error(LOG_ACTION, 'unexpected', LOG_DETAILS, err);
296
- }
297
- serverManager.send(event.socket, 'tx_error', { id: tx.id, reason: err.code ?? err.message, data });
298
- tx.finish(); // Finish with undefined, canceling the transaction
299
- }
300
- });
301
- return serverManager;
302
- };
1
+ import { ColorStyle, Transport } from 'acebase-core';
2
+ import { ConnectedClient } from '../shared/clients.js';
3
+ import { decodePublicAccessToken } from '../shared/tokens.js';
4
+ import { createServer } from './socket.io.js';
5
+ export class SocketRequestError extends Error {
6
+ constructor(code, message) {
7
+ super(message);
8
+ this.code = code;
9
+ }
10
+ }
11
+ export const addWebsocketServer = (env) => {
12
+ // TODO: Allow using uWebSockets.js server instead of Socket.IO
13
+ const serverManager = createServer(env);
14
+ const getClientBySocketId = (id, event) => {
15
+ const client = env.clients.get(id);
16
+ if (!client) {
17
+ env.debug.error(`Cannot find client "${id}" for socket event "${event}"`);
18
+ }
19
+ return client;
20
+ };
21
+ serverManager.on('connect', event => {
22
+ const client = new ConnectedClient(event.socket);
23
+ env.clients.set(client.id, client);
24
+ env.debug.warn(`New socket connected, total: ${env.clients.size}`);
25
+ serverManager.send(event.socket, 'welcome');
26
+ });
27
+ serverManager.on('disconnect', event => {
28
+ // We lost one
29
+ const client = getClientBySocketId(event.socket_id, 'disconnect');
30
+ if (!client) {
31
+ return;
32
+ } // Disconnected a client we did not know? Don't crash, just ignore.
33
+ const subscribedPaths = Object.keys(client.subscriptions);
34
+ if (subscribedPaths.length > 0) {
35
+ // TODO: Substitute the original callbacks to cache them
36
+ // if the client then reconnects within a certain time,
37
+ // we can send the missed notifications
38
+ //
39
+ // subscribedPaths.forEach(path => {
40
+ // client.subscriptions[path].forEach(subscr => {
41
+ // subscr.callback
42
+ // })
43
+ // });
44
+ const remove = [];
45
+ subscribedPaths.forEach(path => {
46
+ remove.push(...client.subscriptions[path]);
47
+ });
48
+ remove.forEach(subscr => {
49
+ // Unsubscribe them at db level and remove from our list
50
+ env.db.api.unsubscribe(subscr.path, subscr.event, subscr.callback); //db.ref(subscr.path).off(subscr.event, subscr.callback);
51
+ const pathSubs = client.subscriptions[subscr.path];
52
+ pathSubs.splice(pathSubs.indexOf(subscr), 1);
53
+ });
54
+ }
55
+ env.clients.delete(client.id);
56
+ env.debug.verbose(`Socket disconnected, total: ${env.clients.size}`);
57
+ });
58
+ serverManager.on('signin', event => {
59
+ // client sends this request once user has been signed in, binds the user to the socket,
60
+ // deprecated since client v0.9.4, which sends client_id with signin api call
61
+ // const client = clients.get(socket.id);
62
+ const client = getClientBySocketId(event.socket_id, 'signin');
63
+ if (!client) {
64
+ return;
65
+ }
66
+ try {
67
+ const uid = decodePublicAccessToken(event.data.accessToken, env.tokenSalt).uid;
68
+ client.user = env.authCache.get(uid) || null;
69
+ }
70
+ catch (err) {
71
+ // no way to bind the user
72
+ env.debug.error(`websocket: invalid access token passed to signin: ${event.data.accessToken}`);
73
+ }
74
+ });
75
+ serverManager.on('signout', event => {
76
+ // deprecated since client v0.9.4, which sends client_id with signout api call
77
+ // const client = clients.get(socket.id);
78
+ const client = getClientBySocketId(event.socket_id, 'signout');
79
+ if (!client) {
80
+ return;
81
+ }
82
+ client.user = null;
83
+ });
84
+ serverManager.on('oauth2-signin', async (event) => {
85
+ // acebase-client does not use socket oauth flow yet
86
+ const client = getClientBySocketId(event.socket_id, 'oauth2-signin');
87
+ if (!client) {
88
+ return;
89
+ }
90
+ const request = event.data;
91
+ const providerName = typeof request === 'string' ? request : request.provider;
92
+ try {
93
+ const provider = env.authProviders[providerName];
94
+ const state = Buffer.from(JSON.stringify({ flow: 'socket', provider: providerName, client_id: client.id })).toString('base64');
95
+ const clientAuthUrl = await provider.init({ redirect_url: `${request.server.protocol}://${request.server.host}:${request.server.port}/ouath2/${env.db.name}/signin`, state, options: request.options });
96
+ serverManager.send(event.socket, 'oauth2-signin', { action: 'auth', url: clientAuthUrl });
97
+ }
98
+ catch (err) {
99
+ env.debug.error(`websocket: cannot sign in with oauth provider ${providerName}`);
100
+ serverManager.send(event.socket, 'oauth2-signin', { error: err.message });
101
+ }
102
+ });
103
+ const acknowledgeRequest = (socket, requestId) => {
104
+ // Send acknowledgement
105
+ serverManager.send(socket, 'result', {
106
+ success: true,
107
+ req_id: requestId,
108
+ });
109
+ };
110
+ const failRequest = (socket, requestId, code) => {
111
+ // Send error
112
+ serverManager.send(socket, 'result', {
113
+ success: false,
114
+ reason: code,
115
+ req_id: requestId,
116
+ });
117
+ };
118
+ serverManager.on('subscribe', async (event) => {
119
+ // Client wants to subscribe to events on a node
120
+ const client = getClientBySocketId(event.socket_id, 'subscribe');
121
+ if (!client) {
122
+ return;
123
+ }
124
+ const eventName = event.data.event;
125
+ const subscriptionPath = event.data.path;
126
+ env.debug.verbose(`Client ${event.socket_id} subscribes to event "${eventName}" on path "/${subscriptionPath}"`.colorize([ColorStyle.bgWhite, ColorStyle.black]));
127
+ const isSubscribed = () => subscriptionPath in client.subscriptions && client.subscriptions[subscriptionPath].some(s => s.event === eventName);
128
+ if (isSubscribed()) {
129
+ return acknowledgeRequest(event.socket, event.data.req_id);
130
+ }
131
+ // Get client
132
+ // const client = clients.get(socket.id);
133
+ if (!await env.rules.isOperationAllowed(client.user, subscriptionPath, 'get')) {
134
+ env.log.error('event.subscribe', 'access_denied', { uid: client.user?.uid ?? 'anonymous', path: subscriptionPath });
135
+ return failRequest(event.socket, event.data.req_id, 'access_denied');
136
+ }
137
+ const callback = async (err, path, currentValue, previousValue, context) => {
138
+ if (!isSubscribed()) {
139
+ // Not subscribed anymore. Cancel sending
140
+ return;
141
+ }
142
+ if (err) {
143
+ return;
144
+ }
145
+ if (!await env.rules.isOperationAllowed(client.user, path, 'get', { value: currentValue, context })) { // 'event', { eventName, subscriptionPath, currentValue, previousValue, context })
146
+ if (!subscriptionPath.includes('*') && !subscriptionPath.includes('$')) {
147
+ // Could potentially be very many callbacks, so
148
+ // DISABLED: logRef.push({ action: `access_revoked`, uid: client.user ? client.user.uid : '-', path: subscriptionPath });
149
+ // Only log when user subscribes again
150
+ failRequest(event.socket, event.data.req_id, 'access_denied');
151
+ }
152
+ return;
153
+ }
154
+ const val = Transport.serialize({
155
+ current: currentValue,
156
+ previous: previousValue,
157
+ });
158
+ env.debug.verbose(`Sending data event "${eventName}" for path "/${path}" to client ${event.socket_id}`.colorize([ColorStyle.bgWhite, ColorStyle.black]));
159
+ // TODO: let large data events notify the client, then let them download the data manually so it doesn't have to be transmitted through the websocket
160
+ serverManager.send(event.socket, 'data-event', {
161
+ subscr_path: subscriptionPath,
162
+ path,
163
+ event: eventName,
164
+ val,
165
+ context,
166
+ });
167
+ };
168
+ let pathSubs = client.subscriptions[subscriptionPath];
169
+ if (!pathSubs) {
170
+ pathSubs = client.subscriptions[subscriptionPath] = [];
171
+ }
172
+ const subscr = { path: subscriptionPath, event: eventName, callback };
173
+ pathSubs.push(subscr);
174
+ env.db.api.subscribe(subscriptionPath, eventName, callback);
175
+ acknowledgeRequest(event.socket, event.data.req_id);
176
+ });
177
+ serverManager.on('unsubscribe', event => {
178
+ // Client unsubscribes from events on a node
179
+ const client = getClientBySocketId(event.socket_id, 'unsubscribe');
180
+ if (!client) {
181
+ return;
182
+ }
183
+ const eventName = event.data.event;
184
+ const subscriptionPath = event.data.path;
185
+ env.debug.verbose(`Client ${event.socket_id} is unsubscribing from event "${eventName || '(any)'}" on path "/${subscriptionPath}"`.colorize([ColorStyle.bgWhite, ColorStyle.black]));
186
+ // const client = clients.get(socket.id);
187
+ const pathSubs = client.subscriptions[subscriptionPath];
188
+ if (!pathSubs) {
189
+ // We have no knowledge of any active subscriptions on this path
190
+ return acknowledgeRequest(event.socket, event.data.req_id);
191
+ }
192
+ let remove = pathSubs;
193
+ if (eventName) {
194
+ // Unsubscribe from a specific event
195
+ remove = pathSubs.filter(subscr => subscr.event === eventName);
196
+ }
197
+ remove.forEach(subscr => {
198
+ // Unsubscribe them at db level and remove from our list
199
+ //this.debug.verbose(` - unsubscribing from event ${subscr.event} with${subscr.callback ? "" : "out"} callback on path "${data.path}"`);
200
+ env.db.api.unsubscribe(subscr.path, subscr.event, subscr.callback); //db.api.unsubscribe(data.path, subscr.event, subscr.callback);
201
+ pathSubs.splice(pathSubs.indexOf(subscr), 1);
202
+ });
203
+ if (pathSubs.length === 0) {
204
+ // No subscriptions left on this path, remove the path entry
205
+ delete client.subscriptions[subscriptionPath];
206
+ }
207
+ return acknowledgeRequest(event.socket, event.data.req_id);
208
+ });
209
+ serverManager.on('query-unsubscribe', event => {
210
+ // Client unsubscribing from realtime query events
211
+ const client = getClientBySocketId(event.socket_id, 'query-unsubscribe');
212
+ if (!client) {
213
+ return;
214
+ }
215
+ env.debug.verbose(`Client ${event.socket_id} is unsubscribing from realtime query "${event.data.query_id}"`);
216
+ // const client = clients.get(socket.id);
217
+ delete client.realtimeQueries[event.data.query_id];
218
+ acknowledgeRequest(event.socket, event.data.req_id);
219
+ });
220
+ const TRANSACTION_TIMEOUT_MS = 10000; // 10s to finish a started transaction
221
+ serverManager.on('transaction-start', async (event) => {
222
+ // Start transaction
223
+ const client = getClientBySocketId(event.socket_id, 'transaction-start');
224
+ if (!client || !event.data) {
225
+ return;
226
+ }
227
+ const LOG_ACTION = 'socket.transaction.start';
228
+ const LOG_DETAILS = { ip: event.socket.conn.remoteAddress, uid: client.user?.uid ?? null, path: event.data.path };
229
+ env.debug.verbose(`Client ${event.socket_id} is sending transaction start request on path "${event.data.path}"`);
230
+ const data = event.data;
231
+ // Pre-check if reading AND writing is allowed (special transact operation)
232
+ const access = await env.rules.isOperationAllowed(client.user, data.path, 'transact');
233
+ if (!access.allow) {
234
+ env.log.error(LOG_ACTION, 'unauthorized', { ...LOG_DETAILS, rule_code: access.code, rule_path: access.rulePath ?? null }, access.details);
235
+ return serverManager.send(event.socket, 'tx_error', { id: data.id, reason: 'access_denied' });
236
+ }
237
+ const tx = {
238
+ id: data.id,
239
+ started: Date.now(),
240
+ path: data.path,
241
+ context: data.context,
242
+ finish: undefined,
243
+ timeout: setTimeout(() => {
244
+ delete client.transactions[tx.id];
245
+ tx.finish(); // Finish without value cancels the transaction
246
+ env.log.error(LOG_ACTION, 'timeout', LOG_DETAILS);
247
+ serverManager.send(event.socket, 'tx_error', { id: tx.id, reason: 'timeout' });
248
+ }, TRANSACTION_TIMEOUT_MS),
249
+ };
250
+ // Bind to client
251
+ client.transactions[data.id] = tx;
252
+ // Start transaction
253
+ env.debug.verbose(`Transaction ${tx.id} starting...`);
254
+ const donePromise = env.db.api.transaction(tx.path, async (val) => {
255
+ env.debug.verbose(`Transaction ${tx.id} started with value: `, val);
256
+ const access = await env.rules.isOperationAllowed(client.user, data.path, 'get', { value: val, context: tx.context });
257
+ if (!access.allow) {
258
+ env.log.error(LOG_ACTION, 'unauthorized', { ...LOG_DETAILS, rule_code: access.code, rule_path: access.rulePath ?? null }, access.details);
259
+ serverManager.send(event.socket, 'tx_error', { id: tx.id, reason: 'access_denied' });
260
+ return; // Return undefined to cancel transaction
261
+ }
262
+ const currentValue = Transport.serialize(val);
263
+ const promise = new Promise((resolve) => {
264
+ tx.finish = (val) => {
265
+ env.debug.verbose(`Transaction ${tx.id} finishing with value: `, val);
266
+ resolve(val);
267
+ return donePromise;
268
+ };
269
+ });
270
+ serverManager.send(event.socket, 'tx_started', { id: tx.id, value: currentValue });
271
+ return promise;
272
+ }, { context: tx.context });
273
+ });
274
+ serverManager.on('transaction-finish', async (event) => {
275
+ // Finish transaction
276
+ const client = getClientBySocketId(event.socket_id, 'transaction-finish');
277
+ if (!client || !event.data) {
278
+ return;
279
+ }
280
+ const LOG_ACTION = 'socket.transaction.finish';
281
+ const LOG_DETAILS = { ip: event.socket.conn.remoteAddress, uid: client.user?.uid ?? null, path: event.data.path };
282
+ const data = event.data;
283
+ const tx = client.transactions[data.id];
284
+ try {
285
+ if (!tx || data.path !== tx.path) {
286
+ env.log.error(LOG_ACTION, tx ? 'wrong_path' : 'not_found', { ...LOG_DETAILS, id: data.id, tx_path: tx?.path ?? null });
287
+ throw new SocketRequestError('transaction_not_found', 'Transaction not found');
288
+ }
289
+ clearTimeout(tx.timeout);
290
+ delete client.transactions[data.id];
291
+ const newValue = 'val' in data.value ? Transport.deserialize(data.value) : undefined;
292
+ if (typeof newValue !== 'undefined') {
293
+ const access = await env.rules.isOperationAllowed(client.user, data.path, 'set', { value: newValue, context: tx.context });
294
+ if (!access.allow) {
295
+ env.log.error(LOG_ACTION, 'unauthorized', { ...LOG_DETAILS, rule_code: access.code, rule_path: access.rulePath ?? null }, access.details);
296
+ throw new SocketRequestError('access_denied', 'Access denied');
297
+ }
298
+ }
299
+ const { cursor } = await tx.finish(newValue);
300
+ env.debug.verbose(`Transaction ${tx.id} finished`);
301
+ serverManager.send(event.socket, 'tx_completed', { id: tx.id, context: { cursor } });
302
+ }
303
+ catch (err) {
304
+ if (!(err instanceof SocketRequestError)) {
305
+ // Other errors have been logged already
306
+ env.log.error(LOG_ACTION, 'unexpected', LOG_DETAILS, err);
307
+ }
308
+ serverManager.send(event.socket, 'tx_error', { id: tx.id, reason: err.code ?? err.message, data });
309
+ tx.finish(); // Finish with undefined, canceling the transaction
310
+ }
311
+ });
312
+ return serverManager;
313
+ };
303
314
  //# sourceMappingURL=index.js.map