acebase-server 1.18.1 → 1.19.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 (46) hide show
  1. package/build-vars.js +0 -3
  2. package/dist/cjs/middleware/admin-only.js +2 -1
  3. package/dist/cjs/middleware/user.js +1 -0
  4. package/dist/cjs/oauth-providers/dropbox.js +1 -1
  5. package/dist/cjs/routes/auth-delete.js +3 -2
  6. package/dist/cjs/routes/auth-signup.js +11 -11
  7. package/dist/cjs/routes/auth-update.js +2 -1
  8. package/dist/cjs/routes/auth.js +0 -3
  9. package/dist/cjs/routes/data-reflect.js +2 -2
  10. package/dist/cjs/routes/data-set.js +4 -3
  11. package/dist/cjs/routes/data-transaction.js +4 -3
  12. package/dist/cjs/routes/data-update.js +4 -3
  13. package/dist/cjs/routes/docs.js +1 -1
  14. package/dist/cjs/routes/meta-info.js +3 -2
  15. package/dist/cjs/rules.js +2 -1
  16. package/dist/cjs/schema/user.js +2 -1
  17. package/dist/cjs/server.js +12 -3
  18. package/dist/cjs/settings/index.js +6 -0
  19. package/dist/cjs/shared/admin.js +8 -0
  20. package/dist/cjs/websocket/index.js +2 -1
  21. package/dist/esm/middleware/admin-only.js +2 -1
  22. package/dist/esm/middleware/user.js +1 -0
  23. package/dist/esm/oauth-providers/dropbox.js +1 -1
  24. package/dist/esm/routes/auth-delete.js +3 -2
  25. package/dist/esm/routes/auth-signup.js +4 -4
  26. package/dist/esm/routes/auth-update.js +2 -1
  27. package/dist/esm/routes/auth.js +0 -3
  28. package/dist/esm/routes/data-reflect.js +2 -1
  29. package/dist/esm/routes/data-set.js +2 -1
  30. package/dist/esm/routes/data-transaction.js +2 -1
  31. package/dist/esm/routes/data-update.js +2 -1
  32. package/dist/esm/routes/docs.js +1 -1
  33. package/dist/esm/routes/meta-info.js +3 -2
  34. package/dist/esm/rules.js +2 -1
  35. package/dist/esm/schema/user.js +1 -0
  36. package/dist/esm/server.js +12 -3
  37. package/dist/esm/settings/index.js +6 -0
  38. package/dist/esm/shared/admin.js +4 -0
  39. package/dist/esm/websocket/index.js +1 -1
  40. package/dist/types/middleware/user.d.ts +1 -0
  41. package/dist/types/routes/auth-update.d.ts +2 -0
  42. package/dist/types/rules.d.ts +1 -1
  43. package/dist/types/schema/user.d.ts +4 -0
  44. package/dist/types/settings/index.d.ts +14 -2
  45. package/dist/types/shared/admin.d.ts +3 -0
  46. package/package.json +1 -1
package/build-vars.js CHANGED
@@ -1,6 +1,5 @@
1
1
  // Executed by npm "version" hook
2
2
  const { readFileSync, writeFileSync } = require('fs');
3
- const { execSync } = require('child_process');
4
3
  const packageInfo = require('./package.json');
5
4
 
6
5
  const sources = ['routes/meta-info', 'routes/docs'];
@@ -13,5 +12,3 @@ files.forEach(file => {
13
12
  console.log(`Replaced variable %SERVER_VERSION% with ${packageInfo.version} in ${file}`);
14
13
  }
15
14
  });
16
-
17
- execSync(`git add dist`);
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.adminOnly = void 0;
4
4
  const error_1 = require("../shared/error");
5
+ const admin_1 = require("../shared/admin");
5
6
  /**
6
7
  * Middleware function that checks if the current user is `admin`. An 403 Forbidden error will be sent in the response if
7
8
  * authentication is enabled on the server and the user is not signed in as admin.
@@ -18,7 +19,7 @@ const error_1 = require("../shared/error");
18
19
  */
19
20
  const adminOnly = (env, errorMessage = 'only admin can perform this operation') => {
20
21
  return (req, res, next) => {
21
- if (env.config.auth.enabled && (!req.user || req.user.uid !== 'admin')) {
22
+ if (env.config.auth.enabled && !(0, admin_1.isAdmin)(req.user)) {
22
23
  return (0, error_1.sendUnauthorizedError)(res, 'admin_only', errorMessage);
23
24
  }
24
25
  next();
@@ -55,4 +55,5 @@ const addMiddleware = (env) => {
55
55
  }));
56
56
  };
57
57
  exports.addMiddleware = addMiddleware;
58
+ exports.default = exports.addMiddleware;
58
59
  //# sourceMappingURL=user.js.map
@@ -37,7 +37,7 @@ class DropboxAuthProvider extends oauth_provider_1.OAuth2Provider {
37
37
  return __awaiter(this, void 0, void 0, function* () {
38
38
  // Return url to get authorization code with
39
39
  const options = info.options || {};
40
- const authUrl = `https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${this.settings.client_id}&scope=${encodeURIComponent(this.settings.scopes.join(' '))}&redirect_uri=${encodeURIComponent(info.redirect_url)}&locale=${options.locale || ''}&require_role=${options.require_role || ''}&force_reauthentication=${options.force_reauthentication === true}&force_reapprove=${options.force_reapprove === true}&disable_signup=${options.disable_signup === true}&state=${encodeURIComponent(info.state)}`;
40
+ const authUrl = `https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${this.settings.client_id}&scope=${encodeURIComponent(this.settings.scopes.join(' '))}&redirect_uri=${encodeURIComponent(info.redirect_url)}${options.locale ? `&locale=${options.locale}` : ''}${options.require_role ? `&require_role=${options.require_role}` : ''}&force_reauthentication=${options.force_reauthentication === true}&force_reapprove=${options.force_reapprove === true}&disable_signup=${options.disable_signup === true}&state=${encodeURIComponent(info.state)}`;
41
41
  return authUrl;
42
42
  });
43
43
  }
@@ -10,6 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.addRoute = exports.DeleteError = void 0;
13
+ const admin_1 = require("../shared/admin");
13
14
  const error_1 = require("../shared/error");
14
15
  class DeleteError extends Error {
15
16
  constructor(code, message) {
@@ -28,14 +29,14 @@ const addRoute = (env) => {
28
29
  env.log.error(LOG_ACTION, 'unauthenticated_delete', LOG_DETAILS);
29
30
  return (0, error_1.sendNotAuthenticatedError)(res, 'unauthenticated_delete', 'You are not authorized to perform this operation, your attempt has been logged');
30
31
  }
31
- if (req.user.uid !== 'admin' && details.uid !== req.user.uid) {
32
+ if (!(0, admin_1.isAdmin)(req.user) && details.uid !== req.user.uid) {
32
33
  env.log.error(LOG_ACTION, 'unauthorized_delete', LOG_DETAILS);
33
34
  return (0, error_1.sendUnauthorizedError)(res, 'unauthorized_delete', 'You are not authorized to perform this operation, your attempt has been logged');
34
35
  }
35
36
  const uid = (_c = details.uid) !== null && _c !== void 0 ? _c : req.user.uid;
36
37
  if (uid === 'admin') {
37
38
  env.log.error(LOG_ACTION, 'unauthorized_delete', LOG_DETAILS);
38
- return (0, error_1.sendUnauthorizedError)(res, 'unauthorized_delete', 'The admin account cannot be deleted, your attempt has been logged');
39
+ return (0, error_1.sendUnauthorizedError)(res, 'unauthorized_delete', 'The default admin account cannot be deleted, your attempt has been logged');
39
40
  }
40
41
  try {
41
42
  yield env.authRef.child(uid).remove();
@@ -16,6 +16,7 @@ const password_1 = require("../shared/password");
16
16
  const acebase_core_1 = require("acebase-core");
17
17
  const tokens_1 = require("../shared/tokens");
18
18
  const error_1 = require("../shared/error");
19
+ const admin_1 = require("../shared/admin");
19
20
  class SignupError extends Error {
20
21
  constructor(code, message) {
21
22
  super(message);
@@ -25,12 +26,12 @@ class SignupError extends Error {
25
26
  exports.SignupError = SignupError;
26
27
  const addRoute = (env) => {
27
28
  env.router.post(`/auth/${env.db.name}/signup`, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
28
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
29
+ var _a, _b, _c, _d, _e, _f, _g, _h;
29
30
  const LOG_ACTION = 'auth.signup';
30
31
  const LOG_DETAILS = { ip: req.ip, uid: (_b = (_a = req.user) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null };
31
- if (!env.config.auth.allowUserSignup && ((_c = req.user) === null || _c === void 0 ? void 0 : _c.uid) !== 'admin') {
32
+ if (!env.config.auth.allowUserSignup && !(0, admin_1.isAdmin)(req.user)) {
32
33
  env.log.error(LOG_ACTION, 'user_signup_disabled', LOG_DETAILS);
33
- return (0, error_1.sendUnauthorizedError)(res, 'admin_only', 'Only admin is allowed to create users');
34
+ return (0, error_1.sendUnauthorizedError)(res, 'admin_only', 'Only admins are allowed to create users');
34
35
  }
35
36
  // Create user if it doesn't exist yet.
36
37
  // TODO: Rate-limit nr of signups per IP to prevent abuse
@@ -75,7 +76,7 @@ const addRoute = (env) => {
75
76
  }
76
77
  else if (err) {
77
78
  // Log failure
78
- env.log.error(LOG_ACTION, (_d = err.code) !== null && _d !== void 0 ? _d : 'unexpected', LOG_DETAILS);
79
+ env.log.error(LOG_ACTION, (_c = err.code) !== null && _c !== void 0 ? _c : 'unexpected', LOG_DETAILS);
79
80
  res.statusCode = 422; // Unprocessable Entity
80
81
  return res.send(err);
81
82
  }
@@ -84,8 +85,8 @@ const addRoute = (env) => {
84
85
  const pwd = (0, password_1.createPasswordHash)(details.password);
85
86
  const user = {
86
87
  uid: null,
87
- username: (_e = details.username) !== null && _e !== void 0 ? _e : null,
88
- email: (_f = details.email) !== null && _f !== void 0 ? _f : null,
88
+ username: (_d = details.username) !== null && _d !== void 0 ? _d : null,
89
+ email: (_e = details.email) !== null && _e !== void 0 ? _e : null,
89
90
  email_verified: false,
90
91
  display_name: details.displayName,
91
92
  password: pwd.hash,
@@ -96,8 +97,8 @@ const addRoute = (env) => {
96
97
  access_token_created: new Date(),
97
98
  last_signin: new Date(),
98
99
  last_signin_ip: req.ip,
99
- picture: (_g = details.picture) !== null && _g !== void 0 ? _g : null,
100
- settings: (_h = details.settings) !== null && _h !== void 0 ? _h : {},
100
+ picture: (_f = details.picture) !== null && _f !== void 0 ? _f : null,
101
+ settings: (_g = details.settings) !== null && _g !== void 0 ? _g : {},
101
102
  };
102
103
  const userRef = yield env.authRef.push(user);
103
104
  user.uid = userRef.key;
@@ -122,13 +123,12 @@ const addRoute = (env) => {
122
123
  activationCode: (0, tokens_1.createSignedPublicToken)({ uid: user.uid }, env.tokenSalt),
123
124
  emailVerified: false,
124
125
  };
125
- (_j = env.config.email) === null || _j === void 0 ? void 0 : _j.send(request).catch(err => {
126
+ (_h = env.config.email) === null || _h === void 0 ? void 0 : _h.send(request).catch(err => {
126
127
  env.log.error(LOG_ACTION + '.email', 'unexpected', Object.assign(Object.assign({}, LOG_DETAILS), { request }), err);
127
128
  });
128
129
  // Return the positive news
129
- const isAdmin = req.user && req.user.uid === 'admin';
130
130
  res.send({
131
- access_token: isAdmin ? '' : (0, tokens_1.createPublicAccessToken)(user.uid, req.ip, user.access_token, env.tokenSalt),
131
+ access_token: (0, admin_1.isAdmin)(req.user) ? '' : (0, tokens_1.createPublicAccessToken)(user.uid, req.ip, user.access_token, env.tokenSalt),
132
132
  user: (0, user_1.getPublicAccountDetails)(user),
133
133
  });
134
134
  }
@@ -13,6 +13,7 @@ exports.addRoute = exports.UpdateError = void 0;
13
13
  const user_1 = require("../schema/user");
14
14
  const validate_1 = require("../shared/validate");
15
15
  const error_1 = require("../shared/error");
16
+ const admin_1 = require("../shared/admin");
16
17
  class UpdateError extends Error {
17
18
  constructor(code, message) {
18
19
  super(message);
@@ -31,7 +32,7 @@ const addRoute = (env) => {
31
32
  return (0, error_1.sendNotAuthenticatedError)(res, 'unauthenticated_update', 'Sign in to change details');
32
33
  }
33
34
  const uid = details.uid || req.user.uid;
34
- if (req.user.uid !== 'admin' && (uid !== req.user.uid || typeof details.is_disabled === 'boolean')) {
35
+ if (!(0, admin_1.isAdmin)(req.user) && (uid !== req.user.uid || typeof details.is_disabled === 'boolean' || details.roles)) {
35
36
  env.log.error(LOG_ACTION, 'unauthorized_update', LOG_DETAILS);
36
37
  return (0, error_1.sendUnauthorizedError)(res, 'unauthorized_update', 'You are not authorized to perform this update. This attempt has been logged.');
37
38
  }
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.addAuthenticionRoutes = void 0;
4
- const user_1 = require("../middleware/user");
5
4
  const auth_state_1 = require("./auth-state");
6
5
  const auth_signin_1 = require("./auth-signin");
7
6
  const auth_signout_1 = require("./auth-signout");
@@ -19,8 +18,6 @@ const addAuthenticionRoutes = (env) => {
19
18
  if (!env.config.auth.enabled) {
20
19
  throw new Error('Authentication not enabled in the server settings');
21
20
  }
22
- // Bearer authentication middleware
23
- (0, user_1.addMiddleware)(env);
24
21
  // Auth state endpoint
25
22
  (0, auth_state_1.addRoute)(env);
26
23
  // signin endpoint
@@ -12,9 +12,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.addRoute = void 0;
13
13
  const acebase_core_1 = require("acebase-core");
14
14
  const error_1 = require("../shared/error");
15
+ const admin_1 = require("../shared/admin");
15
16
  const addRoute = (env) => {
16
17
  env.router.get(`/reflect/${env.db.name}/*`, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
17
- var _a;
18
18
  // Reflection API
19
19
  const path = req.path.slice(env.db.name.length + 10);
20
20
  const access = yield env.rules.isOperationAllowed(req.user, path, 'reflect', { context: req.context, type: req.query.type });
@@ -22,7 +22,7 @@ const addRoute = (env) => {
22
22
  return (0, error_1.sendUnauthorizedError)(res, access.code, access.message);
23
23
  }
24
24
  const impersonatedAccess = {
25
- uid: ((_a = req.user) === null || _a === void 0 ? void 0 : _a.uid) !== 'admin' ? null : req.query.impersonate,
25
+ uid: !(0, admin_1.isAdmin)(req.user) ? null : req.query.impersonate,
26
26
  /**
27
27
  * NEW, check all possible operations
28
28
  */
@@ -14,6 +14,7 @@ const acebase_1 = require("acebase");
14
14
  const acebase_core_1 = require("acebase-core");
15
15
  const rules_1 = require("../rules");
16
16
  const error_1 = require("../shared/error");
17
+ const admin_1 = require("../shared/admin");
17
18
  class SetDataError extends Error {
18
19
  constructor(code, message) {
19
20
  super(message);
@@ -23,7 +24,7 @@ class SetDataError extends Error {
23
24
  exports.SetDataError = SetDataError;
24
25
  const addRoute = (env) => {
25
26
  env.router.put(`/data/${env.db.name}/*`, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
26
- var _a, _b, _c, _d, _e, _f;
27
+ var _a, _b, _c, _d, _e;
27
28
  const path = req.path.slice(env.db.name.length + 7);
28
29
  const LOG_ACTION = 'data.set';
29
30
  const LOG_DETAILS = { ip: req.ip, uid: (_b = (_a = req.user) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null, path };
@@ -38,7 +39,7 @@ const addRoute = (env) => {
38
39
  throw new SetDataError('invalid_serialized_value', 'The sent value is not properly serialized');
39
40
  }
40
41
  const val = acebase_core_1.Transport.deserialize(data);
41
- if (path === '' && ((_c = req.user) === null || _c === void 0 ? void 0 : _c.uid) !== 'admin' && val !== null && typeof val === 'object') {
42
+ if (path === '' && !(0, admin_1.isAdmin)(req.user) && val !== null && typeof val === 'object') {
42
43
  // Non-admin user: remove any private properties from the update object
43
44
  Object.keys(val).filter(key => key.startsWith('__')).forEach(key => delete val[key]);
44
45
  }
@@ -62,7 +63,7 @@ const addRoute = (env) => {
62
63
  catch (err) {
63
64
  if (err instanceof rules_1.AccessRuleValidationError) {
64
65
  const access = err.result;
65
- env.log.error(LOG_ACTION, 'unauthorized', Object.assign(Object.assign({}, LOG_DETAILS), { rule_code: access.code, rule_path: (_d = access.rulePath) !== null && _d !== void 0 ? _d : null, rule_error: (_f = (_e = access.details) === null || _e === void 0 ? void 0 : _e.message) !== null && _f !== void 0 ? _f : null }));
66
+ env.log.error(LOG_ACTION, 'unauthorized', Object.assign(Object.assign({}, LOG_DETAILS), { rule_code: access.code, rule_path: (_c = access.rulePath) !== null && _c !== void 0 ? _c : null, rule_error: (_e = (_d = access.details) === null || _d === void 0 ? void 0 : _d.message) !== null && _e !== void 0 ? _e : null }));
66
67
  return (0, error_1.sendUnauthorizedError)(res, access.code, access.message);
67
68
  }
68
69
  else if (err instanceof acebase_1.SchemaValidationError) {
@@ -14,6 +14,7 @@ const acebase_1 = require("acebase");
14
14
  const acebase_core_1 = require("acebase-core");
15
15
  const rules_1 = require("../rules");
16
16
  const error_1 = require("../shared/error");
17
+ const admin_1 = require("../shared/admin");
17
18
  exports.TRANSACTION_TIMEOUT_MS = 10000; // 10s to finish a started transaction
18
19
  class DataTransactionError extends Error {
19
20
  constructor(code, message) {
@@ -83,7 +84,7 @@ const addRoutes = (env) => {
83
84
  }));
84
85
  // Finish transaction endpoint:
85
86
  env.router.post(`/transaction/${env.db.name}/finish`, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
86
- var _f, _g, _h, _j, _k, _l, _m;
87
+ var _f, _g, _h, _j, _k, _l;
87
88
  const data = req.body;
88
89
  const LOG_ACTION = 'data.transaction.finish';
89
90
  const LOG_DETAILS = { ip: req.ip, uid: (_g = (_f = req.user) === null || _f === void 0 ? void 0 : _f.uid) !== null && _g !== void 0 ? _g : null, path: data.path };
@@ -114,7 +115,7 @@ const addRoutes = (env) => {
114
115
  throw new DataTransactionError('invalid_serialized_value', 'The sent value is not properly serialized');
115
116
  }
116
117
  const newValue = cancel ? undefined : acebase_core_1.Transport.deserialize(data.value);
117
- if (tx.path === '' && ((_l = req.user) === null || _l === void 0 ? void 0 : _l.uid) !== 'admin' && newValue !== null && typeof newValue === 'object') {
118
+ if (tx.path === '' && !(0, admin_1.isAdmin)(req.user) && newValue !== null && typeof newValue === 'object') {
118
119
  // Non-admin user: remove any private properties from the update object
119
120
  Object.keys(newValue).filter(key => key.startsWith('__')).forEach(key => delete newValue[key]);
120
121
  }
@@ -136,7 +137,7 @@ const addRoutes = (env) => {
136
137
  tx.finish(); // Finish without value cancels the transaction
137
138
  if (err instanceof rules_1.AccessRuleValidationError) {
138
139
  const access = err.result;
139
- env.log.error(LOG_ACTION, 'unauthorized', Object.assign(Object.assign({}, LOG_DETAILS), { rule_code: access.code, rule_path: (_m = access.rulePath) !== null && _m !== void 0 ? _m : null }), access.details);
140
+ env.log.error(LOG_ACTION, 'unauthorized', Object.assign(Object.assign({}, LOG_DETAILS), { rule_code: access.code, rule_path: (_l = access.rulePath) !== null && _l !== void 0 ? _l : null }), access.details);
140
141
  return (0, error_1.sendUnauthorizedError)(res, access.code, access.message);
141
142
  }
142
143
  else if (err instanceof acebase_1.SchemaValidationError) {
@@ -14,6 +14,7 @@ const acebase_1 = require("acebase");
14
14
  const acebase_core_1 = require("acebase-core");
15
15
  const rules_1 = require("../rules");
16
16
  const error_1 = require("../shared/error");
17
+ const admin_1 = require("../shared/admin");
17
18
  class UpdateDataError extends Error {
18
19
  constructor(code, message) {
19
20
  super(message);
@@ -23,7 +24,7 @@ class UpdateDataError extends Error {
23
24
  exports.UpdateDataError = UpdateDataError;
24
25
  const addRoute = (env) => {
25
26
  env.router.post(`/data/${env.db.name}/*`, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
26
- var _a, _b, _c, _d, _e, _f;
27
+ var _a, _b, _c, _d, _e;
27
28
  const path = req.path.slice(env.db.name.length + 7);
28
29
  const LOG_ACTION = 'data.update';
29
30
  const LOG_DETAILS = { ip: req.ip, uid: (_b = (_a = req.user) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null, path };
@@ -38,7 +39,7 @@ const addRoute = (env) => {
38
39
  throw new UpdateDataError('invalid_serialized_value', 'The sent value is not properly serialized');
39
40
  }
40
41
  const val = acebase_core_1.Transport.deserialize(data);
41
- if (path === '' && ((_c = req.user) === null || _c === void 0 ? void 0 : _c.uid) !== 'admin' && val !== null && typeof val === 'object') {
42
+ if (path === '' && !(0, admin_1.isAdmin)(req.user) && val !== null && typeof val === 'object') {
42
43
  // Non-admin user: remove any private properties from the update object
43
44
  Object.keys(val).filter(key => key.startsWith('__')).forEach(key => delete val[key]);
44
45
  }
@@ -63,7 +64,7 @@ const addRoute = (env) => {
63
64
  catch (err) {
64
65
  if (err instanceof rules_1.AccessRuleValidationError) {
65
66
  const access = err.result;
66
- env.log.error(LOG_ACTION, 'unauthorized', Object.assign(Object.assign({}, LOG_DETAILS), { rule_code: access.code, rule_path: (_d = access.rulePath) !== null && _d !== void 0 ? _d : null, rule_error: (_f = (_e = access.details) === null || _e === void 0 ? void 0 : _e.message) !== null && _f !== void 0 ? _f : null }));
67
+ env.log.error(LOG_ACTION, 'unauthorized', Object.assign(Object.assign({}, LOG_DETAILS), { rule_code: access.code, rule_path: (_c = access.rulePath) !== null && _c !== void 0 ? _c : null, rule_error: (_e = (_d = access.details) === null || _d === void 0 ? void 0 : _d.message) !== null && _e !== void 0 ? _e : null }));
67
68
  return (0, error_1.sendUnauthorizedError)(res, access.code, access.message);
68
69
  }
69
70
  if (err instanceof acebase_1.SchemaValidationError) {
@@ -19,7 +19,7 @@ const addRoute = (env) => {
19
19
  info: {
20
20
  title: 'AceBase Server',
21
21
  description: 'AceBase Server API endpoint documentation and test environment. This documentation is available on the server because it is running in development mode. To disable this, set your NODE_ENV environment variable to production. Many endpoints require you to authenticate using Bearer authentication. Use the _/auth/{dbname}/signin_ endpoint to obtain an access token, then click the _Authorize_ button and paste your token into the input field. For more information about AceBase, see GitHub',
22
- version: '1.18.1',
22
+ version: '1.19.0',
23
23
  contact: {
24
24
  name: 'AceBase API Support',
25
25
  email: 'me@appy.one',
@@ -1,8 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.addRoute = void 0;
4
+ const admin_1 = require("../shared/admin");
4
5
  const os = require("os");
5
- const SERVER_VERSION = '1.18.1'; // Loaded from package.json by npm scripts
6
+ const SERVER_VERSION = '1.19.0'; // Loaded from package.json by npm scripts
6
7
  const addRoute = (env) => {
7
8
  // Add info endpoint
8
9
  env.router.get(`/info/${env.db.name}`, (req, res) => {
@@ -11,7 +12,7 @@ const addRoute = (env) => {
11
12
  time: Date.now(),
12
13
  process: process.pid,
13
14
  };
14
- if (req.user && req.user.uid === 'admin') {
15
+ if ((0, admin_1.isAdmin)(req.user)) {
15
16
  const numberToByteSize = number => {
16
17
  return Math.round((number / 1024 / 1024) * 100) / 100 + 'MB';
17
18
  };
package/dist/cjs/rules.js CHANGED
@@ -14,6 +14,7 @@ const acebase_core_1 = require("acebase-core");
14
14
  const fs = require("fs");
15
15
  const sandbox_1 = require("./sandbox");
16
16
  const settings_1 = require("./settings");
17
+ const admin_1 = require("./shared/admin");
17
18
  class AccessRuleValidationError extends Error {
18
19
  constructor(result) {
19
20
  super(result.message);
@@ -141,7 +142,7 @@ class PathBasedRules {
141
142
  // Authentication is disabled, anyone can do anything. Not really a smart thing to do!
142
143
  return allow;
143
144
  }
144
- else if ((user === null || user === void 0 ? void 0 : user.uid) === 'admin') {
145
+ else if ((0, admin_1.isAdmin)(user)) {
145
146
  // Always allow admin access
146
147
  // TODO: implement user.is_admin, so the default admin account can be disabled
147
148
  return allow;
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getPublicAccountDetails = void 0;
4
4
  const getPublicAccountDetails = (account) => {
5
- var _a, _b, _c, _d, _e;
5
+ var _a, _b, _c, _d, _e, _f;
6
6
  return {
7
7
  uid: account.uid,
8
8
  username: account.username,
@@ -19,6 +19,7 @@ const getPublicAccountDetails = (account) => {
19
19
  changePasswordRequested: (_d = account.change_password_requested) === null || _d === void 0 ? void 0 : _d.toISOString(),
20
20
  changePasswordBefore: (_e = account.change_password_before) === null || _e === void 0 ? void 0 : _e.toISOString(),
21
21
  settings: account.settings,
22
+ roles: (_f = account.roles) !== null && _f !== void 0 ? _f : [],
22
23
  };
23
24
  };
24
25
  exports.getPublicAccountDetails = getPublicAccountDetails;
@@ -21,6 +21,7 @@ const oauth_providers_1 = require("./oauth-providers");
21
21
  const rules_1 = require("./rules");
22
22
  const connection_1 = require("./middleware/connection");
23
23
  const cors_1 = require("./middleware/cors");
24
+ const user_1 = require("./middleware/user");
24
25
  const auth_1 = require("./routes/auth");
25
26
  const auth_2 = require("./auth");
26
27
  const data_1 = require("./routes/data");
@@ -103,7 +104,7 @@ class AceBaseServer extends acebase_core_1.SimpleEventEmitter {
103
104
  this.init({ authDb });
104
105
  }
105
106
  init(env) {
106
- var _a, _b, _c;
107
+ var _a, _b, _c, _d, _e, _f, _g;
107
108
  return __awaiter(this, void 0, void 0, function* () {
108
109
  const config = this.config;
109
110
  const db = this.db;
@@ -146,12 +147,20 @@ class AceBaseServer extends acebase_core_1.SimpleEventEmitter {
146
147
  rules,
147
148
  instance: this,
148
149
  };
149
- // Add connection middleware
150
+ // Add connection middleware (http server middleware, not express)
150
151
  const killConnections = (0, connection_1.default)(routeEnv);
152
+ // Run preMiddleware callback to allow user code to add own express middleware to the server
153
+ yield ((_c = (_b = this.config).preMiddleware) === null || _c === void 0 ? void 0 : _c.call(_b, this));
151
154
  // Add CORS middleware
152
155
  (0, cors_1.default)(routeEnv);
153
156
  // Add cache middleware
154
157
  (0, cache_1.default)(routeEnv);
158
+ if (config.auth.enabled) {
159
+ // Setup auth middleware
160
+ (0, user_1.default)(routeEnv);
161
+ }
162
+ // Run postMiddleware callback to allow user code to add own express middleware to the server
163
+ yield ((_e = (_d = this.config).postMiddleware) === null || _e === void 0 ? void 0 : _e.call(_d, this));
155
164
  if (config.auth.enabled) {
156
165
  // Setup auth database
157
166
  yield (0, auth_2.default)(routeEnv);
@@ -181,7 +190,7 @@ class AceBaseServer extends acebase_core_1.SimpleEventEmitter {
181
190
  // Create websocket server
182
191
  (0, websocket_1.addWebsocketServer)(routeEnv);
183
192
  // Run init callback to allow user code to call `server.extend`, `server.router.[method]`, `server.setRule` etc before the server starts listening
184
- yield ((_c = (_b = this.config).init) === null || _c === void 0 ? void 0 : _c.call(_b, this));
193
+ yield ((_g = (_f = this.config).init) === null || _g === void 0 ? void 0 : _g.call(_f, this));
185
194
  // If we own the server, add 404 handler
186
195
  if (!this.config.server) {
187
196
  (0, _404_1.default)(routeEnv);
@@ -167,6 +167,12 @@ class AceBaseServerConfig {
167
167
  if (typeof settings.logColors === 'boolean') {
168
168
  this.logColors = settings.logColors;
169
169
  }
170
+ if (typeof settings.preMiddleware === 'function') {
171
+ this.preMiddleware = settings.preMiddleware;
172
+ }
173
+ if (typeof settings.postMiddleware === 'function') {
174
+ this.postMiddleware = settings.postMiddleware;
175
+ }
170
176
  if (typeof settings.init === 'function') {
171
177
  this.init = settings.init;
172
178
  }
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isAdmin = void 0;
4
+ function isAdmin(user) {
5
+ return (user === null || user === void 0 ? void 0 : user.uid) === 'admin' || ((user === null || user === void 0 ? void 0 : user.roles) || []).includes('admin');
6
+ }
7
+ exports.isAdmin = isAdmin;
8
+ //# sourceMappingURL=admin.js.map
@@ -256,8 +256,9 @@ const addWebsocketServer = (env) => {
256
256
  context: data.context,
257
257
  finish: undefined,
258
258
  timeout: setTimeout(() => {
259
+ var _a;
259
260
  delete client.transactions[tx.id];
260
- tx.finish(); // Finish without value cancels the transaction
261
+ (_a = tx.finish) === null || _a === void 0 ? void 0 : _a.call(tx); // Finish without value cancels the transaction
261
262
  env.log.error(LOG_ACTION, 'timeout', LOG_DETAILS);
262
263
  serverManager.send(event.socket, 'tx_error', { id: tx.id, reason: 'timeout' });
263
264
  }, TRANSACTION_TIMEOUT_MS),
@@ -1,4 +1,5 @@
1
1
  import { sendUnauthorizedError } from '../shared/error.js';
2
+ import { isAdmin } from '../shared/admin.js';
2
3
  /**
3
4
  * Middleware function that checks if the current user is `admin`. An 403 Forbidden error will be sent in the response if
4
5
  * authentication is enabled on the server and the user is not signed in as admin.
@@ -15,7 +16,7 @@ import { sendUnauthorizedError } from '../shared/error.js';
15
16
  */
16
17
  export const adminOnly = (env, errorMessage = 'only admin can perform this operation') => {
17
18
  return (req, res, next) => {
18
- if (env.config.auth.enabled && (!req.user || req.user.uid !== 'admin')) {
19
+ if (env.config.auth.enabled && !isAdmin(req.user)) {
19
20
  return sendUnauthorizedError(res, 'admin_only', errorMessage);
20
21
  }
21
22
  next();
@@ -42,4 +42,5 @@ export const addMiddleware = (env) => {
42
42
  next();
43
43
  });
44
44
  };
45
+ export default addMiddleware;
45
46
  //# sourceMappingURL=user.js.map
@@ -24,7 +24,7 @@ export class DropboxAuthProvider extends OAuth2Provider {
24
24
  async init(info) {
25
25
  // Return url to get authorization code with
26
26
  const options = info.options || {};
27
- const authUrl = `https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${this.settings.client_id}&scope=${encodeURIComponent(this.settings.scopes.join(' '))}&redirect_uri=${encodeURIComponent(info.redirect_url)}&locale=${options.locale || ''}&require_role=${options.require_role || ''}&force_reauthentication=${options.force_reauthentication === true}&force_reapprove=${options.force_reapprove === true}&disable_signup=${options.disable_signup === true}&state=${encodeURIComponent(info.state)}`;
27
+ const authUrl = `https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${this.settings.client_id}&scope=${encodeURIComponent(this.settings.scopes.join(' '))}&redirect_uri=${encodeURIComponent(info.redirect_url)}${options.locale ? `&locale=${options.locale}` : ''}${options.require_role ? `&require_role=${options.require_role}` : ''}&force_reauthentication=${options.force_reauthentication === true}&force_reapprove=${options.force_reapprove === true}&disable_signup=${options.disable_signup === true}&state=${encodeURIComponent(info.state)}`;
28
28
  return authUrl;
29
29
  }
30
30
  async getAccessToken(params) {
@@ -1,3 +1,4 @@
1
+ import { isAdmin } from '../shared/admin.js';
1
2
  import { sendNotAuthenticatedError, sendUnauthorizedError, sendUnexpectedError } from '../shared/error.js';
2
3
  export class DeleteError extends Error {
3
4
  constructor(code, message) {
@@ -14,14 +15,14 @@ export const addRoute = (env) => {
14
15
  env.log.error(LOG_ACTION, 'unauthenticated_delete', LOG_DETAILS);
15
16
  return sendNotAuthenticatedError(res, 'unauthenticated_delete', 'You are not authorized to perform this operation, your attempt has been logged');
16
17
  }
17
- if (req.user.uid !== 'admin' && details.uid !== req.user.uid) {
18
+ if (!isAdmin(req.user) && details.uid !== req.user.uid) {
18
19
  env.log.error(LOG_ACTION, 'unauthorized_delete', LOG_DETAILS);
19
20
  return sendUnauthorizedError(res, 'unauthorized_delete', 'You are not authorized to perform this operation, your attempt has been logged');
20
21
  }
21
22
  const uid = details.uid ?? req.user.uid;
22
23
  if (uid === 'admin') {
23
24
  env.log.error(LOG_ACTION, 'unauthorized_delete', LOG_DETAILS);
24
- return sendUnauthorizedError(res, 'unauthorized_delete', 'The admin account cannot be deleted, your attempt has been logged');
25
+ return sendUnauthorizedError(res, 'unauthorized_delete', 'The default admin account cannot be deleted, your attempt has been logged');
25
26
  }
26
27
  try {
27
28
  await env.authRef.child(uid).remove();
@@ -4,6 +4,7 @@ import { createPasswordHash } from '../shared/password.js';
4
4
  import { ID } from 'acebase-core';
5
5
  import { createPublicAccessToken, createSignedPublicToken } from '../shared/tokens.js';
6
6
  import { sendUnauthorizedError, sendUnexpectedError } from '../shared/error.js';
7
+ import { isAdmin } from '../shared/admin.js';
7
8
  export class SignupError extends Error {
8
9
  constructor(code, message) {
9
10
  super(message);
@@ -14,9 +15,9 @@ export const addRoute = (env) => {
14
15
  env.router.post(`/auth/${env.db.name}/signup`, async (req, res) => {
15
16
  const LOG_ACTION = 'auth.signup';
16
17
  const LOG_DETAILS = { ip: req.ip, uid: req.user?.uid ?? null };
17
- if (!env.config.auth.allowUserSignup && req.user?.uid !== 'admin') {
18
+ if (!env.config.auth.allowUserSignup && !isAdmin(req.user)) {
18
19
  env.log.error(LOG_ACTION, 'user_signup_disabled', LOG_DETAILS);
19
- return sendUnauthorizedError(res, 'admin_only', 'Only admin is allowed to create users');
20
+ return sendUnauthorizedError(res, 'admin_only', 'Only admins are allowed to create users');
20
21
  }
21
22
  // Create user if it doesn't exist yet.
22
23
  // TODO: Rate-limit nr of signups per IP to prevent abuse
@@ -112,9 +113,8 @@ export const addRoute = (env) => {
112
113
  env.log.error(LOG_ACTION + '.email', 'unexpected', { ...LOG_DETAILS, request }, err);
113
114
  });
114
115
  // Return the positive news
115
- const isAdmin = req.user && req.user.uid === 'admin';
116
116
  res.send({
117
- access_token: isAdmin ? '' : createPublicAccessToken(user.uid, req.ip, user.access_token, env.tokenSalt),
117
+ access_token: isAdmin(req.user) ? '' : createPublicAccessToken(user.uid, req.ip, user.access_token, env.tokenSalt),
118
118
  user: getPublicAccountDetails(user),
119
119
  });
120
120
  }
@@ -1,6 +1,7 @@
1
1
  import { getPublicAccountDetails } from '../schema/user.js';
2
2
  import { emailExistsError, invalidDisplayNameError, invalidEmailError, invalidPictureError, invalidSettingsError, invalidUsernameError, isValidDisplayName, isValidEmail, isValidNewEmailAddress, isValidNewUsername, isValidPicture, isValidSettings, isValidUsername, usernameExistsError } from '../shared/validate.js';
3
3
  import { sendNotAuthenticatedError, sendUnauthorizedError, sendUnexpectedError } from '../shared/error.js';
4
+ import { isAdmin } from '../shared/admin.js';
4
5
  export class UpdateError extends Error {
5
6
  constructor(code, message) {
6
7
  super(message);
@@ -17,7 +18,7 @@ export const addRoute = (env) => {
17
18
  return sendNotAuthenticatedError(res, 'unauthenticated_update', 'Sign in to change details');
18
19
  }
19
20
  const uid = details.uid || req.user.uid;
20
- if (req.user.uid !== 'admin' && (uid !== req.user.uid || typeof details.is_disabled === 'boolean')) {
21
+ if (!isAdmin(req.user) && (uid !== req.user.uid || typeof details.is_disabled === 'boolean' || details.roles)) {
21
22
  env.log.error(LOG_ACTION, 'unauthorized_update', LOG_DETAILS);
22
23
  return sendUnauthorizedError(res, 'unauthorized_update', 'You are not authorized to perform this update. This attempt has been logged.');
23
24
  }
@@ -1,4 +1,3 @@
1
- import { addMiddleware as addBearerAuthMiddleware } from '../middleware/user.js';
2
1
  import { addRoute as addStateRoute } from './auth-state.js';
3
2
  import { addRoute as addSignInRoute } from './auth-signin.js';
4
3
  import { addRoute as addSignOutRoute } from './auth-signout.js';
@@ -16,8 +15,6 @@ export const addAuthenticionRoutes = (env) => {
16
15
  if (!env.config.auth.enabled) {
17
16
  throw new Error('Authentication not enabled in the server settings');
18
17
  }
19
- // Bearer authentication middleware
20
- addBearerAuthMiddleware(env);
21
18
  // Auth state endpoint
22
19
  addStateRoute(env);
23
20
  // signin endpoint
@@ -1,5 +1,6 @@
1
1
  import { PathInfo } from 'acebase-core';
2
2
  import { sendUnauthorizedError } from '../shared/error.js';
3
+ import { isAdmin } from '../shared/admin.js';
3
4
  export const addRoute = (env) => {
4
5
  env.router.get(`/reflect/${env.db.name}/*`, async (req, res) => {
5
6
  // Reflection API
@@ -9,7 +10,7 @@ export const addRoute = (env) => {
9
10
  return sendUnauthorizedError(res, access.code, access.message);
10
11
  }
11
12
  const impersonatedAccess = {
12
- uid: req.user?.uid !== 'admin' ? null : req.query.impersonate,
13
+ uid: !isAdmin(req.user) ? null : req.query.impersonate,
13
14
  /**
14
15
  * NEW, check all possible operations
15
16
  */
@@ -2,6 +2,7 @@ import { SchemaValidationError } from 'acebase';
2
2
  import { Transport } from 'acebase-core';
3
3
  import { AccessRuleValidationError } from '../rules.js';
4
4
  import { sendBadRequestError, sendError, sendUnauthorizedError } from '../shared/error.js';
5
+ import { isAdmin } from '../shared/admin.js';
5
6
  export class SetDataError extends Error {
6
7
  constructor(code, message) {
7
8
  super(message);
@@ -24,7 +25,7 @@ export const addRoute = (env) => {
24
25
  throw new SetDataError('invalid_serialized_value', 'The sent value is not properly serialized');
25
26
  }
26
27
  const val = Transport.deserialize(data);
27
- if (path === '' && req.user?.uid !== 'admin' && val !== null && typeof val === 'object') {
28
+ if (path === '' && !isAdmin(req.user) && val !== null && typeof val === 'object') {
28
29
  // Non-admin user: remove any private properties from the update object
29
30
  Object.keys(val).filter(key => key.startsWith('__')).forEach(key => delete val[key]);
30
31
  }
@@ -2,6 +2,7 @@ import { SchemaValidationError } from 'acebase';
2
2
  import { ID, Transport } from 'acebase-core';
3
3
  import { AccessRuleValidationError } from '../rules.js';
4
4
  import { sendBadRequestError, sendError, sendUnauthorizedError, sendUnexpectedError } from '../shared/error.js';
5
+ import { isAdmin } from '../shared/admin.js';
5
6
  export const TRANSACTION_TIMEOUT_MS = 10000; // 10s to finish a started transaction
6
7
  export class DataTransactionError extends Error {
7
8
  constructor(code, message) {
@@ -98,7 +99,7 @@ export const addRoutes = (env) => {
98
99
  throw new DataTransactionError('invalid_serialized_value', 'The sent value is not properly serialized');
99
100
  }
100
101
  const newValue = cancel ? undefined : Transport.deserialize(data.value);
101
- if (tx.path === '' && req.user?.uid !== 'admin' && newValue !== null && typeof newValue === 'object') {
102
+ if (tx.path === '' && !isAdmin(req.user) && newValue !== null && typeof newValue === 'object') {
102
103
  // Non-admin user: remove any private properties from the update object
103
104
  Object.keys(newValue).filter(key => key.startsWith('__')).forEach(key => delete newValue[key]);
104
105
  }
@@ -2,6 +2,7 @@ import { SchemaValidationError } from 'acebase';
2
2
  import { Transport } from 'acebase-core';
3
3
  import { AccessRuleValidationError } from '../rules.js';
4
4
  import { sendBadRequestError, sendError, sendUnauthorizedError } from '../shared/error.js';
5
+ import { isAdmin } from '../shared/admin.js';
5
6
  export class UpdateDataError extends Error {
6
7
  constructor(code, message) {
7
8
  super(message);
@@ -24,7 +25,7 @@ export const addRoute = (env) => {
24
25
  throw new UpdateDataError('invalid_serialized_value', 'The sent value is not properly serialized');
25
26
  }
26
27
  const val = Transport.deserialize(data);
27
- if (path === '' && req.user?.uid !== 'admin' && val !== null && typeof val === 'object') {
28
+ if (path === '' && !isAdmin(req.user) && val !== null && typeof val === 'object') {
28
29
  // Non-admin user: remove any private properties from the update object
29
30
  Object.keys(val).filter(key => key.startsWith('__')).forEach(key => delete val[key]);
30
31
  }
@@ -14,7 +14,7 @@ export const addRoute = (env) => {
14
14
  info: {
15
15
  title: 'AceBase Server',
16
16
  description: 'AceBase Server API endpoint documentation and test environment. This documentation is available on the server because it is running in development mode. To disable this, set your NODE_ENV environment variable to production. Many endpoints require you to authenticate using Bearer authentication. Use the _/auth/{dbname}/signin_ endpoint to obtain an access token, then click the _Authorize_ button and paste your token into the input field. For more information about AceBase, see GitHub',
17
- version: '1.18.1',
17
+ version: '1.19.0',
18
18
  contact: {
19
19
  name: 'AceBase API Support',
20
20
  email: 'me@appy.one',
@@ -1,5 +1,6 @@
1
+ import { isAdmin } from '../shared/admin.js';
1
2
  import * as os from 'os';
2
- const SERVER_VERSION = '1.18.1'; // Loaded from package.json by npm scripts
3
+ const SERVER_VERSION = '1.19.0'; // Loaded from package.json by npm scripts
3
4
  export const addRoute = (env) => {
4
5
  // Add info endpoint
5
6
  env.router.get(`/info/${env.db.name}`, (req, res) => {
@@ -8,7 +9,7 @@ export const addRoute = (env) => {
8
9
  time: Date.now(),
9
10
  process: process.pid,
10
11
  };
11
- if (req.user && req.user.uid === 'admin') {
12
+ if (isAdmin(req.user)) {
12
13
  const numberToByteSize = number => {
13
14
  return Math.round((number / 1024 / 1024) * 100) / 100 + 'MB';
14
15
  };
package/dist/esm/rules.js CHANGED
@@ -2,6 +2,7 @@ import { PathInfo } from 'acebase-core';
2
2
  import * as fs from 'fs';
3
3
  import { executeSandboxed } from './sandbox.js';
4
4
  import { AUTH_ACCESS_DEFAULT } from './settings/index.js';
5
+ import { isAdmin } from './shared/admin.js';
5
6
  export class AccessRuleValidationError extends Error {
6
7
  constructor(result) {
7
8
  super(result.message);
@@ -127,7 +128,7 @@ export class PathBasedRules {
127
128
  // Authentication is disabled, anyone can do anything. Not really a smart thing to do!
128
129
  return allow;
129
130
  }
130
- else if (user?.uid === 'admin') {
131
+ else if (isAdmin(user)) {
131
132
  // Always allow admin access
132
133
  // TODO: implement user.is_admin, so the default admin account can be disabled
133
134
  return allow;
@@ -15,6 +15,7 @@ export const getPublicAccountDetails = (account) => {
15
15
  changePasswordRequested: account.change_password_requested?.toISOString(),
16
16
  changePasswordBefore: account.change_password_before?.toISOString(),
17
17
  settings: account.settings,
18
+ roles: account.roles ?? [],
18
19
  };
19
20
  };
20
21
  //# sourceMappingURL=user.js.map
@@ -9,7 +9,8 @@ import oAuth2Providers from './oauth-providers/index.js';
9
9
  import { PathBasedRules } from './rules.js';
10
10
  import addConnectionMiddleware from './middleware/connection.js';
11
11
  import addCorsMiddleware from './middleware/cors.js';
12
- import addAuthenticionRoutes from './routes/auth.js';
12
+ import addBearerAuthMiddleware from './middleware/user.js';
13
+ import addAuthenticationRoutes from './routes/auth.js';
13
14
  import setupAuthentication from './auth.js';
14
15
  import addDataRoutes from './routes/data.js';
15
16
  import addWebManagerRoutes from './routes/webmanager.js';
@@ -133,17 +134,25 @@ export class AceBaseServer extends SimpleEventEmitter {
133
134
  rules,
134
135
  instance: this,
135
136
  };
136
- // Add connection middleware
137
+ // Add connection middleware (http server middleware, not express)
137
138
  const killConnections = addConnectionMiddleware(routeEnv);
139
+ // Run preMiddleware callback to allow user code to add own express middleware to the server
140
+ await this.config.preMiddleware?.(this);
138
141
  // Add CORS middleware
139
142
  addCorsMiddleware(routeEnv);
140
143
  // Add cache middleware
141
144
  addCacheMiddleware(routeEnv);
145
+ if (config.auth.enabled) {
146
+ // Setup auth middleware
147
+ addBearerAuthMiddleware(routeEnv);
148
+ }
149
+ // Run postMiddleware callback to allow user code to add own express middleware to the server
150
+ await this.config.postMiddleware?.(this);
142
151
  if (config.auth.enabled) {
143
152
  // Setup auth database
144
153
  await setupAuthentication(routeEnv);
145
154
  // Add auth endpoints
146
- const { resetPassword, verifyEmailAddress } = addAuthenticionRoutes(routeEnv);
155
+ const { resetPassword, verifyEmailAddress } = addAuthenticationRoutes(routeEnv);
147
156
  this.resetPassword = resetPassword;
148
157
  this.verifyEmailAddress = verifyEmailAddress;
149
158
  }
@@ -161,6 +161,12 @@ export class AceBaseServerConfig {
161
161
  if (typeof settings.logColors === 'boolean') {
162
162
  this.logColors = settings.logColors;
163
163
  }
164
+ if (typeof settings.preMiddleware === 'function') {
165
+ this.preMiddleware = settings.preMiddleware;
166
+ }
167
+ if (typeof settings.postMiddleware === 'function') {
168
+ this.postMiddleware = settings.postMiddleware;
169
+ }
164
170
  if (typeof settings.init === 'function') {
165
171
  this.init = settings.init;
166
172
  }
@@ -0,0 +1,4 @@
1
+ export function isAdmin(user) {
2
+ return user?.uid === 'admin' || (user?.roles || []).includes('admin');
3
+ }
4
+ //# sourceMappingURL=admin.js.map
@@ -242,7 +242,7 @@ export const addWebsocketServer = (env) => {
242
242
  finish: undefined,
243
243
  timeout: setTimeout(() => {
244
244
  delete client.transactions[tx.id];
245
- tx.finish(); // Finish without value cancels the transaction
245
+ tx.finish?.(); // Finish without value cancels the transaction
246
246
  env.log.error(LOG_ACTION, 'timeout', LOG_DETAILS);
247
247
  serverManager.send(event.socket, 'tx_error', { id: tx.id, reason: 'timeout' });
248
248
  }, TRANSACTION_TIMEOUT_MS),
@@ -1,3 +1,4 @@
1
1
  import { RouteInitEnvironment } from '../shared/env';
2
2
  export declare const addMiddleware: (env: RouteInitEnvironment) => void;
3
+ export default addMiddleware;
3
4
  //# sourceMappingURL=user.d.ts.map
@@ -18,6 +18,8 @@ export type RequestBody = {
18
18
  settings?: {
19
19
  [name: string]: string | number | boolean;
20
20
  };
21
+ /** Admin only: what roles the user has */
22
+ roles?: string[];
21
23
  } & ({
22
24
  displayName: string;
23
25
  } | {
@@ -67,7 +67,7 @@ export declare class PathBasedRules {
67
67
  db: AceBase;
68
68
  authEnabled: boolean;
69
69
  });
70
- isOperationAllowed(user: Pick<DbUserAccountDetails, 'uid'>, path: string, operation: AccessCheckOperation, data?: Record<string, any>): Promise<HasAccessResult>;
70
+ isOperationAllowed(user: Pick<DbUserAccountDetails, 'uid' | 'roles'>, path: string, operation: AccessCheckOperation, data?: Record<string, any>): Promise<HasAccessResult>;
71
71
  add(rulePaths: string | string[], ruleTypes: PathRuleType | PathRuleType[], callback: PathRuleFunction): void;
72
72
  }
73
73
  export {};
@@ -29,6 +29,8 @@ export type AceBaseUser = ({
29
29
  /** ISO date string */
30
30
  changePasswordBefore: string;
31
31
  settings: UserSettings;
32
+ /** Roles the user has */
33
+ roles: string[];
32
34
  };
33
35
  export type DbUserAccountDetails = ({
34
36
  username: string;
@@ -81,6 +83,8 @@ export type DbUserAccountDetails = ({
81
83
  access_token_created?: Date;
82
84
  /** additional settings for this user */
83
85
  settings: UserSettings;
86
+ /** roles this user has */
87
+ roles?: string[];
84
88
  };
85
89
  export declare const getPublicAccountDetails: (account: DbUserAccountDetails) => AceBaseUser;
86
90
  //# sourceMappingURL=user.d.ts.map
@@ -167,7 +167,17 @@ export type AceBaseServerSettings = Partial<{
167
167
  */
168
168
  logColors: boolean;
169
169
  /**
170
- * Init callback that runs before the server adds 404 middleware and starts listening to incoming calls.
170
+ * Callback that runs before the server adds middleware and routes.
171
+ * Use this callback to add custom middleware for logging purposes, header processing etc before the server's own.
172
+ */
173
+ preMiddleware?: (server: AceBaseServer) => Promise<void>;
174
+ /**
175
+ * Callback that runs after the server has added its middleware, before any routes are added.
176
+ * Use this callback to add custom middleware for logging purposes, header processing etc before the server's own.
177
+ */
178
+ postMiddleware?: (server: AceBaseServer) => Promise<void>;
179
+ /**
180
+ * Init callback that runs after all middleware (except 404 handler) has been added, before the server starts listening to incoming calls.
171
181
  * Use this callback to extend the server with custom routes, add data validation rules, wait for external events, etc.
172
182
  * @param server Instance of the `AceBaseServer`
173
183
  */
@@ -190,7 +200,9 @@ export declare class AceBaseServerConfig {
190
200
  readonly storage?: AceBaseStorageSettings;
191
201
  readonly sponsor: boolean;
192
202
  readonly logColors: boolean;
193
- readonly init?: (server: AceBaseServer) => Promise<void>;
203
+ readonly preMiddleware?: AceBaseServerSettings['preMiddleware'];
204
+ readonly postMiddleware?: AceBaseServerSettings['postMiddleware'];
205
+ readonly init?: AceBaseServerSettings['init'];
194
206
  constructor(settings: AceBaseServerSettings);
195
207
  }
196
208
  //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,3 @@
1
+ import { DbUserAccountDetails } from '../schema/user.js';
2
+ export declare function isAdmin(user?: Pick<DbUserAccountDetails, 'uid' | 'roles'>): boolean;
3
+ //# sourceMappingURL=admin.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acebase-server",
3
- "version": "1.18.1",
3
+ "version": "1.19.0",
4
4
  "description": "AceBase realtime database server (webserver endpoint to allow remote connections)",
5
5
  "main": "./dist/cjs/index.js",
6
6
  "module": "./dist/esm/index.js",