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
package/dist/cjs/rules.js CHANGED
@@ -1,168 +1,381 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PathBasedRules = void 0;
4
- const acebase_core_1 = require("acebase-core");
5
- const fs = require("fs");
6
- const settings_1 = require("./settings");
7
- class PathBasedRules {
8
- constructor(rulesFilePath, defaultAccess, env) {
9
- // Reads rules from a file and monitors it
10
- // Check if there is a rules file, load it or generate default
11
- const readRules = () => {
12
- try {
13
- const json = fs.readFileSync(rulesFilePath, 'utf-8');
14
- const obj = JSON.parse(json);
15
- if (typeof obj !== 'object' || typeof obj.rules !== 'object') {
16
- throw new Error(`malformed rules object`);
17
- }
18
- return obj;
19
- }
20
- catch (err) {
21
- env.debug.error(`Failed to read rules from "${rulesFilePath}": ${err.message}`);
22
- return defaultRules;
23
- }
24
- };
25
- const defaultAccessRule = (def => {
26
- switch (def) {
27
- case settings_1.AUTH_ACCESS_DEFAULT.ALLOW_AUTHENTICATED: {
28
- return 'auth !== null';
29
- }
30
- case settings_1.AUTH_ACCESS_DEFAULT.ALLOW_ALL: {
31
- return true;
32
- }
33
- case settings_1.AUTH_ACCESS_DEFAULT.DENY_ALL: {
34
- return false;
35
- }
36
- default: {
37
- env.debug.error(`Unknown defaultAccessRule "${def}"`);
38
- return false;
39
- }
40
- }
41
- })(defaultAccess);
42
- const defaultRules = {
43
- rules: {
44
- '.read': defaultAccessRule,
45
- '.write': defaultAccessRule,
46
- },
47
- };
48
- let accessRules = defaultRules;
49
- if (!fs.existsSync(rulesFilePath)) {
50
- // Write defaults
51
- fs.writeFileSync(rulesFilePath, JSON.stringify(defaultRules, null, 4));
52
- }
53
- else {
54
- accessRules = readRules();
55
- }
56
- // Convert string rules to functions that can be executed
57
- const processRules = (path, parent, variables) => {
58
- Object.keys(parent).forEach(key => {
59
- let rule = parent[key];
60
- if (['.read', '.write', '.validate'].includes(key) && typeof rule === 'string') {
61
- // Convert to function
62
- const text = rule;
63
- rule = eval(`(env => { const { now, root, newData, data, auth, ${variables.join(', ')} } = env; return ${text}; })`);
64
- rule.getText = () => {
65
- return text;
66
- };
67
- return parent[key] = rule;
68
- }
69
- else if (key === '.schema') {
70
- // Add schema
71
- return env.db.schema.set(path, rule)
72
- .catch(err => {
73
- env.debug.error(`Error parsing ${path}/.schema: ${err.message}`);
74
- });
75
- }
76
- else if (key.startsWith('$')) {
77
- variables.push(key);
78
- }
79
- if (typeof rule === 'object') {
80
- processRules(`${path}/${key}`, rule, variables.slice());
81
- }
82
- });
83
- };
84
- processRules('', accessRules.rules, []);
85
- // Watch file for changes. watchFile will poll for changes every (default) 5007ms
86
- const watchFileListener = () => {
87
- // Reload access rules
88
- const accessRules = readRules();
89
- processRules('', accessRules.rules, []);
90
- this.accessRules = accessRules;
91
- };
92
- fs.watchFile(rulesFilePath, watchFileListener);
93
- this.stop = () => {
94
- fs.unwatchFile(rulesFilePath, watchFileListener);
95
- };
96
- process.on('SIGINT', this.stop);
97
- this.authEnabled = env.authEnabled;
98
- this.accessRules = accessRules;
99
- }
100
- stop() { throw new Error('not started yet'); }
101
- userHasAccess(user, path, write = false) {
102
- // Process rules, find out if signed in user is allowed to read/write
103
- // Defaults to false unless a rule is found that tells us otherwise
104
- const allow = { allow: true };
105
- if (!this.authEnabled) {
106
- // Authentication is disabled, anyone can do anything. Not really a smart thing to do!
107
- return allow;
108
- }
109
- else if (user && user.uid === 'admin') {
110
- // Always allow admin access
111
- // TODO: implement user.is_admin, so the default admin account can be disabled
112
- return allow;
113
- }
114
- else if (path.startsWith('__')) {
115
- // NEW: with the auth database now integrated into the main database,
116
- // deny access to private resources starting with '__' for non-admins
117
- return { allow: false, code: 'private', message: `Access to private resource "${path}" not allowed` };
118
- }
119
- const env = { now: Date.now(), auth: user || null }; // IDEA: Add functions like "exists" and "value". These will be async (so that requires refactoring) and can be used like "await exists('./shared/' + auth.uid)" and "await value('./writable') === true"
120
- const pathKeys = acebase_core_1.PathInfo.getPathKeys(path);
121
- let rule = this.accessRules.rules;
122
- const rulePath = [];
123
- while (true) {
124
- if (!rule) {
125
- // TODO: check if this one is redundant with the pathKeys.length === 0 near the end
126
- return { allow: false, code: 'no_rule', message: `No rules set for requested path "${path}", defaulting to false` };
127
- }
128
- const checkRule = write ? rule['.write'] : rule['.read'];
129
- if (typeof checkRule === 'boolean') {
130
- if (!checkRule) {
131
- return { allow: false, code: 'rule', message: `Access denied to path "${path}" by set rule`, rule: checkRule, rulePath: rulePath.join('/') };
132
- }
133
- return allow;
134
- }
135
- if (typeof checkRule === 'function') {
136
- try {
137
- // Execute rule function
138
- if (!checkRule(env)) {
139
- return { allow: false, code: 'rule', message: `Access denied to path "${path}" by set rule`, rule: checkRule.getText(), rulePath: rulePath.join('/') };
140
- }
141
- return allow;
142
- }
143
- catch (err) {
144
- // If rule execution throws an exception, don't allow. Can happen when rule is "auth.uid === '...'", and auth is null because the user is not signed in
145
- return { allow: false, code: 'exception', message: `Access denied to path "${path}" by set rule`, rule: checkRule.getText(), rulePath: rulePath.join('/'), details: err };
146
- }
147
- }
148
- if (pathKeys.length === 0) {
149
- return { allow: false, code: 'no_rule', message: `No rule found for path ${path}` };
150
- }
151
- let nextKey = pathKeys.shift();
152
- // if nextKey is '*' or '$something', rule[nextKey] will be undefined (or match a variable) so there is no
153
- // need to change things here for usage of wildcard paths in subscriptions
154
- if (typeof rule[nextKey] === 'undefined') {
155
- // Check if current rule has a wildcard child
156
- const wildcardKey = Object.keys(rule).find(key => key === '*' || key[0] === '$');
157
- if (wildcardKey) {
158
- env[wildcardKey] = nextKey;
159
- }
160
- nextKey = wildcardKey;
161
- }
162
- nextKey && rulePath.push(nextKey);
163
- rule = rule[nextKey];
164
- }
165
- }
166
- }
167
- exports.PathBasedRules = PathBasedRules;
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.PathBasedRules = exports.AccessRuleValidationError = void 0;
13
+ const acebase_core_1 = require("acebase-core");
14
+ const fs = require("fs");
15
+ const sandbox_1 = require("./sandbox");
16
+ const settings_1 = require("./settings");
17
+ class AccessRuleValidationError extends Error {
18
+ constructor(result) {
19
+ super(result.message);
20
+ this.result = result;
21
+ }
22
+ }
23
+ exports.AccessRuleValidationError = AccessRuleValidationError;
24
+ class PathBasedRules {
25
+ stop() { throw new Error('not started yet'); }
26
+ constructor(rulesFilePath, defaultAccess, env) {
27
+ // Reads rules from a file and monitors it
28
+ // Check if there is a rules file, load it or generate default
29
+ this.codeRules = [];
30
+ this.db = env.db;
31
+ this.debug = env.debug;
32
+ const readRules = () => {
33
+ try {
34
+ // TODO: store in db itself under __rules__ or in separate rules.db storage file
35
+ const json = fs.readFileSync(rulesFilePath, 'utf-8');
36
+ const obj = JSON.parse(json);
37
+ if (typeof obj !== 'object' || typeof obj.rules !== 'object') {
38
+ throw new Error(`malformed rules object`);
39
+ }
40
+ return obj;
41
+ }
42
+ catch (err) {
43
+ env.debug.error(`Failed to read rules from "${rulesFilePath}": ${err.message}`);
44
+ return defaultRules;
45
+ }
46
+ };
47
+ const defaultAccessRule = (def => {
48
+ switch (def) {
49
+ case settings_1.AUTH_ACCESS_DEFAULT.ALLOW_AUTHENTICATED: {
50
+ return 'auth !== null';
51
+ }
52
+ case settings_1.AUTH_ACCESS_DEFAULT.ALLOW_ALL: {
53
+ return true;
54
+ }
55
+ case settings_1.AUTH_ACCESS_DEFAULT.DENY_ALL: {
56
+ return false;
57
+ }
58
+ default: {
59
+ env.debug.error(`Unknown defaultAccessRule "${def}"`);
60
+ return false;
61
+ }
62
+ }
63
+ })(defaultAccess);
64
+ const defaultRules = {
65
+ rules: {
66
+ '.read': defaultAccessRule,
67
+ '.write': defaultAccessRule,
68
+ },
69
+ };
70
+ let accessRules = defaultRules;
71
+ if (!fs.existsSync(rulesFilePath)) {
72
+ // Write defaults
73
+ fs.writeFileSync(rulesFilePath, JSON.stringify(defaultRules, null, 4));
74
+ }
75
+ else {
76
+ accessRules = readRules();
77
+ }
78
+ // Convert string rules to functions that can be executed
79
+ const processRules = (path, parent, variables) => {
80
+ Object.keys(parent).forEach(key => {
81
+ const rule = parent[key];
82
+ if (['.read', '.write', '.validate'].includes(key) && typeof rule === 'string') {
83
+ let ruleCode = rule.includes('return ') ? rule : `return ${rule}`;
84
+ // Add `await`s to `value` and `exists` call expressions
85
+ ruleCode = ruleCode.replace(/(value|exists)\(/g, (m, fn) => `await ${fn}(`);
86
+ // Convert to function
87
+ // rule = eval(
88
+ // `(async (env) => {` +
89
+ // ` const { now, path, ${variables.join(', ')}, operation, data, auth, value, exists } = env;` +
90
+ // ` ${ruleCode};` +
91
+ // `})`);
92
+ // rule.getText = () => {
93
+ // return ruleCode;
94
+ // };
95
+ ruleCode = `(async () => {\n${ruleCode}\n})();`;
96
+ return parent[key] = ruleCode;
97
+ }
98
+ else if (key === '.schema') {
99
+ // Add schema
100
+ return env.db.schema.set(path, rule)
101
+ .catch(err => {
102
+ env.debug.error(`Error parsing ${path}/.schema: ${err.message}`);
103
+ });
104
+ }
105
+ else if (key.startsWith('$')) {
106
+ variables.push(key);
107
+ }
108
+ if (typeof rule === 'object') {
109
+ processRules(`${path}/${key}`, rule, variables.slice());
110
+ }
111
+ });
112
+ };
113
+ processRules('', accessRules.rules, []);
114
+ // Watch file for changes. watchFile will poll for changes every (default) 5007ms
115
+ const watchFileListener = () => {
116
+ // Reload access rules from file
117
+ const accessRules = readRules();
118
+ processRules('', accessRules.rules, []);
119
+ this.accessRules = accessRules;
120
+ // Re-add rules added by code
121
+ const codeRules = this.codeRules.splice(0);
122
+ for (const rule of codeRules) {
123
+ this.add(rule.path, rule.type, rule.callback);
124
+ }
125
+ };
126
+ fs.watchFile(rulesFilePath, watchFileListener);
127
+ this.stop = () => {
128
+ fs.unwatchFile(rulesFilePath, watchFileListener);
129
+ };
130
+ process.on('SIGINT', this.stop);
131
+ this.authEnabled = env.authEnabled;
132
+ this.accessRules = accessRules;
133
+ }
134
+ isOperationAllowed(user, path, operation, data) {
135
+ return __awaiter(this, void 0, void 0, function* () {
136
+ // Process rules, find out if signed in user is allowed to read/write
137
+ // Defaults to false unless a rule is found that tells us otherwise
138
+ const isPreFlight = typeof data === 'undefined';
139
+ const allow = { allow: true };
140
+ if (!this.authEnabled) {
141
+ // Authentication is disabled, anyone can do anything. Not really a smart thing to do!
142
+ return allow;
143
+ }
144
+ else if ((user === null || user === void 0 ? void 0 : user.uid) === 'admin') {
145
+ // Always allow admin access
146
+ // TODO: implement user.is_admin, so the default admin account can be disabled
147
+ return allow;
148
+ }
149
+ else if (path.startsWith('__')) {
150
+ // NEW: with the auth database now integrated into the main database,
151
+ // deny access to private resources starting with '__' for non-admins
152
+ return { allow: false, code: 'private', message: `Access to private resource "${path}" not allowed` };
153
+ }
154
+ const getFullPath = (path, relativePath) => {
155
+ if (relativePath.startsWith('/')) {
156
+ // Absolute path
157
+ return relativePath;
158
+ }
159
+ else if (!relativePath.startsWith('.')) {
160
+ throw new Error('Path must be either absolute (/) or relative (./ or ../)');
161
+ }
162
+ let targetPathInfo = acebase_core_1.PathInfo.get(path);
163
+ const trailKeys = acebase_core_1.PathInfo.getPathKeys(relativePath);
164
+ trailKeys.forEach(key => {
165
+ if (key === '.') { /* no op */ }
166
+ else if (key === '..') {
167
+ targetPathInfo = targetPathInfo.parent;
168
+ }
169
+ else {
170
+ targetPathInfo = targetPathInfo.child(key);
171
+ }
172
+ });
173
+ return targetPathInfo.path;
174
+ };
175
+ const env = {
176
+ now: Date.now(),
177
+ auth: user || null,
178
+ operation,
179
+ vars: {},
180
+ context: typeof (data === null || data === void 0 ? void 0 : data.context) === 'object' && data.context !== null ? Object.assign({}, data.context) : {},
181
+ };
182
+ const pathInfo = acebase_core_1.PathInfo.get(path);
183
+ const pathKeys = pathInfo.keys.slice();
184
+ let rule = this.accessRules.rules;
185
+ const rulePathKeys = [];
186
+ let currentPath = '';
187
+ let isAllowed = false;
188
+ while (rule) {
189
+ // Check read/write access or validate operation
190
+ const checkRules = [];
191
+ const applyRule = (rule) => {
192
+ if (rule && !checkRules.includes(rule)) {
193
+ checkRules.push(rule);
194
+ }
195
+ };
196
+ if (['get', 'exists', 'query', 'reflect', 'export', 'transact'].includes(operation)) {
197
+ // Operations that require 'read' access
198
+ applyRule(rule['.read']);
199
+ }
200
+ if ('.write' in rule && ['update', 'set', 'delete', 'import', 'transact'].includes(operation)) {
201
+ // Operations that require 'write' access
202
+ applyRule(rule['.write']);
203
+ }
204
+ if (`.${operation}` in rule && !isPreFlight) {
205
+ // If there is a dedicated rule (eg ".update" or ".reflect") for this operation, use it.
206
+ applyRule(rule[`.${operation}`]);
207
+ }
208
+ const rulePath = acebase_core_1.PathInfo.get(rulePathKeys).path;
209
+ for (const rule of checkRules) {
210
+ if (typeof rule === 'boolean') {
211
+ if (!rule) {
212
+ return { allow: false, code: 'rule', message: `${operation} operation denied to path "${path}" by set rule`, rule, rulePath };
213
+ }
214
+ isAllowed = true; // return allow;
215
+ }
216
+ if (typeof rule === 'string' || typeof rule === 'function') {
217
+ try {
218
+ // Execute rule function
219
+ const ruleEnv = Object.assign(Object.assign({}, env), { exists: (target) => __awaiter(this, void 0, void 0, function* () { return this.db.ref(getFullPath(currentPath, target)).exists(); }), value: (target, include) => __awaiter(this, void 0, void 0, function* () {
220
+ const snap = yield this.db.ref(getFullPath(currentPath, target)).get({ include });
221
+ return snap.val();
222
+ }) });
223
+ const result = typeof rule === 'function'
224
+ ? yield rule(ruleEnv)
225
+ : yield (0, sandbox_1.executeSandboxed)(rule, ruleEnv);
226
+ if (!['cascade', 'deny', 'allow', true, false].includes(result)) {
227
+ this.debug.warn(`rule for path ${rulePath} possibly returns an unintentional value (${JSON.stringify(result)}) which results in outcome "${result ? 'allow' : 'deny'}"`);
228
+ }
229
+ isAllowed = result === 'allow' || result === true;
230
+ if (!isAllowed && result !== 'cascade') {
231
+ return { allow: false, code: 'rule', message: `${operation} operation denied to path "${path}" by set rule`, rule, rulePath };
232
+ }
233
+ }
234
+ catch (err) {
235
+ // If rule execution throws an exception, don't allow. Can happen when rule is "auth.uid === '...'", and auth is null because the user is not signed in
236
+ return { allow: false, code: 'exception', message: `${operation} operation denied to path "${path}" by set rule`, rule, rulePath, details: err };
237
+ }
238
+ }
239
+ }
240
+ if (isAllowed) {
241
+ break;
242
+ }
243
+ // Proceed with next key in trail
244
+ if (pathKeys.length === 0) {
245
+ break;
246
+ }
247
+ let nextKey = pathKeys.shift();
248
+ currentPath = acebase_core_1.PathInfo.get(currentPath).childPath(nextKey);
249
+ // if nextKey is '*' or '$something', rule[nextKey] will be undefined (or match a variable) so there is no
250
+ // need to change things here for usage of wildcard paths in subscriptions
251
+ if (typeof rule[nextKey] === 'undefined') {
252
+ // Check if current rule has a wildcard child
253
+ const wildcardKey = Object.keys(rule).find(key => key === '*' || key[0] === '$');
254
+ if (wildcardKey) {
255
+ env[wildcardKey] = nextKey;
256
+ env.vars[wildcardKey] = nextKey;
257
+ }
258
+ nextKey = wildcardKey;
259
+ }
260
+ nextKey && rulePathKeys.push(nextKey);
261
+ rule = rule[nextKey];
262
+ }
263
+ // Now dig deeper to check nested .validate rules
264
+ if (isAllowed && ['set', 'update'].includes(operation) && !isPreFlight) {
265
+ // validate rules start at current path being written to
266
+ const startRule = pathInfo.keys.reduce((rule, key) => {
267
+ if (typeof rule !== 'object' || rule === null) {
268
+ return null;
269
+ }
270
+ if (key in rule) {
271
+ return rule[key];
272
+ }
273
+ if ('*' in rule) {
274
+ return rule['*'];
275
+ }
276
+ const variableKey = Object.keys(rule).find(key => typeof key === 'string' && key.startsWith('$'));
277
+ if (variableKey) {
278
+ return rule[variableKey];
279
+ }
280
+ return null;
281
+ }, this.accessRules.rules);
282
+ const getNestedRules = (target, rule) => {
283
+ if (!rule) {
284
+ return [];
285
+ }
286
+ const nested = Object.keys(rule).reduce((arr, key) => {
287
+ if (key === '.validate' && ['string', 'function'].includes(typeof rule[key])) {
288
+ arr.push({ target, validate: rule[key] });
289
+ }
290
+ if (!key.startsWith('.')) {
291
+ const nested = getNestedRules([...target, key], rule[key]);
292
+ arr.push(...nested);
293
+ }
294
+ return arr;
295
+ }, []);
296
+ return nested;
297
+ };
298
+ // Check all that apply for sent data (update requires a different strategy)
299
+ const checkRules = getNestedRules([], startRule);
300
+ for (const check of checkRules) {
301
+ // Keep going as long as rules validate
302
+ const targetData = check.target.reduce((data, key) => {
303
+ if (data !== null && typeof data === 'object' && key in data) {
304
+ return data[key];
305
+ }
306
+ return null;
307
+ }, data.value);
308
+ if (typeof targetData === 'undefined' && operation === 'update' && check.target.length >= 1 && check.target[0] in data) {
309
+ // Ignore, data for direct child path is not being set by update operation
310
+ continue;
311
+ }
312
+ const validateData = typeof targetData === 'undefined' ? null : targetData;
313
+ if (validateData === null) {
314
+ // Do not validate deletes, this should be done by ".write" or ".delete" rule
315
+ continue;
316
+ }
317
+ const validatePath = acebase_core_1.PathInfo.get(path).child(check.target).path;
318
+ const validateEnv = Object.assign(Object.assign({}, env), { operation: operation === 'update' ? (check.target.length === 0 ? 'update' : 'set') : operation, data: validateData, exists: (target) => __awaiter(this, void 0, void 0, function* () { return this.db.ref(getFullPath(validatePath, target)).exists(); }), value: (target, include) => __awaiter(this, void 0, void 0, function* () {
319
+ const snap = yield this.db.ref(getFullPath(validatePath, target)).get({ include });
320
+ return snap.val();
321
+ }) });
322
+ try {
323
+ const result = yield (() => __awaiter(this, void 0, void 0, function* () {
324
+ let result;
325
+ if (typeof check.validate === 'function') {
326
+ result = yield check.validate(validateEnv);
327
+ }
328
+ else if (typeof check.validate === 'string') {
329
+ result = yield (0, sandbox_1.executeSandboxed)(check.validate, validateEnv);
330
+ }
331
+ else if (typeof check.validate === 'boolean') {
332
+ result = check.validate ? 'allow' : 'deny';
333
+ }
334
+ if (result === 'cascade') {
335
+ this.debug.warn(`Rule at path ${validatePath} returned "cascade", but ${validateEnv.operation} rules always cascade`);
336
+ }
337
+ else if (!['cascade', 'deny', 'allow', true, false].includes(result)) {
338
+ this.debug.warn(`${validateEnv.operation} rule for path ${validatePath} possibly returned an unintentional value (${JSON.stringify(result)}) which results in outcome "${result ? 'allow' : 'deny'}"`);
339
+ }
340
+ if (['cascade', 'deny', 'allow'].includes(result)) {
341
+ return result;
342
+ }
343
+ return result ? 'allow' : 'deny';
344
+ }))();
345
+ if (result === 'deny') {
346
+ return { allow: false, code: 'rule', message: `${operation} operation denied to path "${path}" by set rule`, rule: check.validate, rulePath: validatePath };
347
+ }
348
+ }
349
+ catch (err) {
350
+ // If rule execution throws an exception, don't allow. Can happen when rule is "auth.uid === '...'", and auth is null because the user is not signed in
351
+ return { allow: false, code: 'exception', message: `${operation} operation denied to path "${path}" by set rule`, rule: check.validate, rulePath: validatePath, details: err };
352
+ }
353
+ }
354
+ }
355
+ return isAllowed ? allow : { allow: false, code: 'no_rule', message: `No rules set for requested path "${path}", defaulting to false` };
356
+ });
357
+ }
358
+ add(rulePaths, ruleTypes, callback) {
359
+ const paths = Array.isArray(rulePaths) ? rulePaths : [rulePaths];
360
+ const types = Array.isArray(ruleTypes) ? ruleTypes : [ruleTypes];
361
+ for (const path of paths) {
362
+ const keys = acebase_core_1.PathInfo.getPathKeys(path);
363
+ let target = this.accessRules.rules;
364
+ for (const key of keys) {
365
+ if (!(key in target)) {
366
+ target[key] = {};
367
+ }
368
+ target = target[key];
369
+ if (typeof target !== 'object' || target === null) {
370
+ throw new Error(`Cannot add rule because value of key "${key}" is not an object`);
371
+ }
372
+ }
373
+ for (const type of types) {
374
+ target[`.${type}`] = callback;
375
+ this.codeRules.push({ path, type, callback });
376
+ }
377
+ }
378
+ }
379
+ }
380
+ exports.PathBasedRules = PathBasedRules;
168
381
  //# sourceMappingURL=rules.js.map
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.isCodeSafe = exports.executeSandboxed = void 0;
13
+ const vm_1 = require("vm");
14
+ function executeSandboxed(code, env) {
15
+ return __awaiter(this, void 0, void 0, function* () {
16
+ // Using eval to execute code is dangerous, so we have to make sure we run in a sandbox
17
+ // so no globally available objects are accessible.
18
+ const context = (0, vm_1.createContext)(env);
19
+ const result = yield (0, vm_1.runInContext)(code, context, { filename: 'sandbox', timeout: 10000, displayErrors: true, breakOnSigint: true });
20
+ return result;
21
+ });
22
+ }
23
+ exports.executeSandboxed = executeSandboxed;
24
+ function isCodeSafe(code) {
25
+ return /eval|prototype|require|import/.test(code); // Do not allow prototype access, require or import statements
26
+ }
27
+ exports.isCodeSafe = isCodeSafe;
28
+ //# sourceMappingURL=sandbox.js.map
@@ -1,25 +1,25 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getPublicAccountDetails = void 0;
4
- const getPublicAccountDetails = (account) => {
5
- var _a, _b, _c, _d, _e;
6
- return {
7
- uid: account.uid,
8
- username: account.username,
9
- email: account.email,
10
- displayName: account.display_name,
11
- picture: account.picture,
12
- emailVerified: account.email_verified,
13
- created: (_a = account.created) === null || _a === void 0 ? void 0 : _a.toISOString(),
14
- prevSignin: (_b = account.prev_signin) === null || _b === void 0 ? void 0 : _b.toISOString(),
15
- prevSigninIp: account.prev_signin_ip,
16
- lastSignin: (_c = account.last_signin) === null || _c === void 0 ? void 0 : _c.toISOString(),
17
- lastSigninIp: account.last_signin_ip,
18
- changePassword: account.change_password,
19
- changePasswordRequested: (_d = account.change_password_requested) === null || _d === void 0 ? void 0 : _d.toISOString(),
20
- changePasswordBefore: (_e = account.change_password_before) === null || _e === void 0 ? void 0 : _e.toISOString(),
21
- settings: account.settings,
22
- };
23
- };
24
- exports.getPublicAccountDetails = getPublicAccountDetails;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getPublicAccountDetails = void 0;
4
+ const getPublicAccountDetails = (account) => {
5
+ var _a, _b, _c, _d, _e;
6
+ return {
7
+ uid: account.uid,
8
+ username: account.username,
9
+ email: account.email,
10
+ displayName: account.display_name,
11
+ picture: account.picture,
12
+ emailVerified: account.email_verified,
13
+ created: (_a = account.created) === null || _a === void 0 ? void 0 : _a.toISOString(),
14
+ prevSignin: (_b = account.prev_signin) === null || _b === void 0 ? void 0 : _b.toISOString(),
15
+ prevSigninIp: account.prev_signin_ip,
16
+ lastSignin: (_c = account.last_signin) === null || _c === void 0 ? void 0 : _c.toISOString(),
17
+ lastSigninIp: account.last_signin_ip,
18
+ changePassword: account.change_password,
19
+ changePasswordRequested: (_d = account.change_password_requested) === null || _d === void 0 ? void 0 : _d.toISOString(),
20
+ changePasswordBefore: (_e = account.change_password_before) === null || _e === void 0 ? void 0 : _e.toISOString(),
21
+ settings: account.settings,
22
+ };
23
+ };
24
+ exports.getPublicAccountDetails = getPublicAccountDetails;
25
25
  //# sourceMappingURL=user.js.map