acebase-server 1.19.2 → 1.20.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 (63) hide show
  1. package/README.md +19 -33
  2. package/api-clients/thunder-client/README.md +32 -0
  3. package/api-clients/thunder-client/collection.json +1069 -0
  4. package/api-clients/thunder-client/environment.json +25 -0
  5. package/dist/cjs/auth.js +10 -7
  6. package/dist/cjs/logger.js +3 -3
  7. package/dist/cjs/middleware/user.js +6 -13
  8. package/dist/cjs/oauth-providers/facebook.js +1 -1
  9. package/dist/cjs/oauth-providers/instagram.js +1 -1
  10. package/dist/cjs/routes/auth-change-password.js +12 -9
  11. package/dist/cjs/routes/auth-reset-password.js +6 -5
  12. package/dist/cjs/routes/auth-signin.js +15 -2
  13. package/dist/cjs/routes/data-reflect.js +1 -1
  14. package/dist/cjs/routes/data-transaction.js +7 -7
  15. package/dist/cjs/routes/docs.js +1 -1
  16. package/dist/cjs/routes/meta-info.js +2 -2
  17. package/dist/cjs/routes/oauth2-signin.js +2 -2
  18. package/dist/cjs/rules.js +4 -2
  19. package/dist/cjs/sandbox.js +2 -3
  20. package/dist/cjs/server.js +5 -2
  21. package/dist/cjs/shared/admin.js +1 -2
  22. package/dist/cjs/shared/error.js +2 -1
  23. package/dist/cjs/shared/http.js +17 -0
  24. package/dist/cjs/shared/signin.js +72 -76
  25. package/dist/cjs/shared/simple-fetch.js +1 -2
  26. package/dist/cjs/shared/tokens.js +1 -1
  27. package/dist/cjs/start.js +1 -1
  28. package/dist/cjs/websocket/index.js +10 -10
  29. package/dist/cjs/websocket/socket.io.js +2 -2
  30. package/dist/esm/auth.js +10 -7
  31. package/dist/esm/middleware/user.js +6 -13
  32. package/dist/esm/oauth-providers/facebook.js +1 -1
  33. package/dist/esm/oauth-providers/instagram.js +1 -1
  34. package/dist/esm/routes/auth-change-password.js +11 -8
  35. package/dist/esm/routes/auth-reset-password.js +3 -3
  36. package/dist/esm/routes/auth-signin.js +17 -4
  37. package/dist/esm/routes/data-reflect.js +1 -1
  38. package/dist/esm/routes/docs.js +1 -1
  39. package/dist/esm/routes/meta-info.js +2 -2
  40. package/dist/esm/routes/oauth2-signin.js +2 -2
  41. package/dist/esm/rules.js +4 -2
  42. package/dist/esm/server.js +4 -1
  43. package/dist/esm/shared/error.js +1 -1
  44. package/dist/esm/shared/http.js +17 -0
  45. package/dist/esm/shared/signin.js +87 -75
  46. package/dist/esm/shared/tokens.js +1 -1
  47. package/dist/esm/start.js +1 -1
  48. package/dist/esm/websocket/socket.io.js +2 -2
  49. package/dist/types/routes/auth-change-password.d.ts +1 -0
  50. package/dist/types/rules.d.ts +1 -1
  51. package/dist/types/schema/user.d.ts +4 -0
  52. package/dist/types/settings/index.d.ts +0 -2
  53. package/dist/types/shared/clients.d.ts +0 -1
  54. package/dist/types/shared/env.d.ts +12 -11
  55. package/dist/types/shared/http.d.ts +2 -2
  56. package/dist/types/shared/password.d.ts +1 -1
  57. package/dist/types/shared/signin.d.ts +4 -6
  58. package/dist/types/shared/simple-fetch.d.ts +2 -2
  59. package/dist/types/shared/tokens.d.ts +1 -1
  60. package/package.json +10 -11
  61. package/release_notes.md +21 -2
  62. package/src/routes/auth-change-password.yaml +9 -0
  63. package/src/routes/auth-signin.yaml +2 -1
@@ -12,7 +12,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.signIn = exports.SignInError = void 0;
13
13
  const acebase_core_1 = require("acebase-core");
14
14
  const password_1 = require("./password");
15
- const tokens_1 = require("./tokens");
16
15
  class SignInError extends Error {
17
16
  constructor(code, message, details = {}) {
18
17
  super(message);
@@ -21,43 +20,22 @@ class SignInError extends Error {
21
20
  }
22
21
  }
23
22
  exports.SignInError = SignInError;
24
- /**
25
- * Signs in a user and logs the request. If successful, adds the user to authCache, binds the user to the http request and returns the user details.
26
- * Throws a `SignInError` if sign in fails for a known reason.
27
- * @param credentials credentials to sign in the user with
28
- * @param env environment state
29
- * @param req current http request
30
- * @returns
31
- */
32
- const signIn = (credentials, env, req) => __awaiter(void 0, void 0, void 0, function* () {
33
- var _a;
34
- const LOG_ACTION = 'auth.signin';
35
- const LOG_DETAILS = { ip: req.ip, method: credentials.method };
36
- try {
23
+ const queryUser = (credentials, env) => __awaiter(void 0, void 0, void 0, function* () {
24
+ let user;
25
+ if (credentials.method === 'token') {
26
+ // Uses the uid and access token extracted from a public access token
27
+ if (typeof credentials.access_token !== 'string') {
28
+ throw new SignInError('invalid_details', 'sign in request has invalid arguments');
29
+ }
30
+ const snap = yield env.authRef.child(credentials.uid).get();
31
+ if (snap.exists()) {
32
+ user = snap.val();
33
+ user.uid = snap.key;
34
+ }
35
+ }
36
+ else {
37
37
  const query = env.authRef.query();
38
- let tokenDetails;
39
38
  switch (credentials.method) {
40
- case 'token': {
41
- if (typeof credentials.access_token !== 'string') {
42
- throw new SignInError('invalid_details', 'sign in request has invalid arguments');
43
- }
44
- try {
45
- tokenDetails = (0, tokens_1.decodePublicAccessToken)(credentials.access_token, env.tokenSalt);
46
- query.filter('access_token', '==', tokenDetails.access_token);
47
- }
48
- catch (err) {
49
- throw new SignInError('invalid_token', err.message);
50
- }
51
- break;
52
- }
53
- case 'internal': {
54
- // Method used internally: uses the access token extracted from a public access token (see tokenDetails.access_token in above 'token' case)
55
- if (typeof credentials.access_token !== 'string') {
56
- throw new SignInError('invalid_details', 'sign in request has invalid arguments');
57
- }
58
- query.filter('access_token', '==', credentials.access_token);
59
- break;
60
- }
61
39
  case 'email': {
62
40
  if (typeof credentials.email !== 'string' || typeof credentials.password !== 'string') {
63
41
  throw new SignInError('invalid_details', 'sign in request has invalid arguments');
@@ -77,21 +55,43 @@ const signIn = (credentials, env, req) => __awaiter(void 0, void 0, void 0, func
77
55
  }
78
56
  }
79
57
  const snaps = yield query.get();
80
- if (snaps.length === 0) {
81
- throw new SignInError('not_found', `account not found`);
82
- }
83
- else if (snaps.length > 1) {
58
+ if (snaps.length > 1) {
84
59
  throw new SignInError('duplicate', `${snaps.length} users found with the same ${credentials.method}. Contact your database administrator`, { count: snaps.length });
85
60
  }
86
- const snap = snaps[0];
87
- const user = snap.val();
88
- user.uid = snap.key;
61
+ else if (snaps.length === 1) {
62
+ const snap = snaps[0];
63
+ user = snap.val();
64
+ user.uid = snap.key;
65
+ }
66
+ }
67
+ if (!user) {
68
+ throw new SignInError('not_found', `account not found`);
69
+ }
70
+ return user;
71
+ });
72
+ /**
73
+ * Signs in a user and logs the request. Uses cache for token sign-in method. If successful, adds the user to cache and returns the user details.
74
+ * Throws a `SignInError` if sign in fails for a known reason.
75
+ * @param credentials credentials to sign in the user with
76
+ * @param env environment state
77
+ * @param req current http request
78
+ * @returns
79
+ */
80
+ const signIn = (credentials, env, ip, isNewSession) => __awaiter(void 0, void 0, void 0, function* () {
81
+ var _a, _b, _c;
82
+ const LOG_ACTION = 'auth.signin';
83
+ const LOG_DETAILS = Object.assign(Object.assign(Object.assign({ ip, method: credentials.method }, ('uid' in credentials && { uid: credentials.uid })), ('username' in credentials && { username: credentials.username })), ('email' in credentials && { email: credentials.email }));
84
+ try {
85
+ const isCached = credentials.method === 'token' && env.authCache.has(credentials.uid);
86
+ const user = isCached
87
+ ? env.authCache.get(credentials.uid)
88
+ : yield queryUser(credentials, env);
89
+ if (credentials.method === 'token' && credentials.access_token !== user.access_token) {
90
+ throw new SignInError('expired_token', `Access token has expired. Sign in again`);
91
+ }
89
92
  if (user.is_disabled === true) {
90
93
  throw new SignInError('account_disabled', 'Your account has been disabled. Contact your database administrator');
91
94
  }
92
- if (credentials.method === 'token' && tokenDetails.uid !== user.uid) {
93
- throw new SignInError('token_mismatch', 'Sign in again');
94
- }
95
95
  if (credentials.method === 'account' || credentials.method === 'email') {
96
96
  // Check password
97
97
  const hash = user.password_salt ? (0, password_1.getPasswordHash)(credentials.password, user.password_salt) : (0, password_1.getOldPasswordHash)(credentials.password);
@@ -99,44 +99,40 @@ const signIn = (credentials, env, req) => __awaiter(void 0, void 0, void 0, func
99
99
  throw new SignInError('wrong_password', 'Incorrect password');
100
100
  }
101
101
  }
102
- // Keep track of properties to update, both in db and in our object
103
- const updates = {
104
- // Update prev / last sign in stats
105
- prev_signin: user.last_signin,
106
- prev_signin_ip: user.last_signin_ip,
107
- last_signin: new Date(),
108
- last_signin_ip: req.ip,
109
- };
110
- if ('password' in credentials) {
111
- if (!user.password_salt) {
112
- // OLD md5 password hash, convert to new salted hash
113
- const pwd = (0, password_1.createPasswordHash)(credentials.password);
114
- updates.password = pwd.hash;
115
- updates.password_salt = pwd.salt;
102
+ if (isNewSession) {
103
+ // Keep track of properties to update, both in db and cached details
104
+ const updates = Object.assign({ last_session_start: new Date(), last_session_ip: ip }, (credentials.method !== 'token' && Object.assign(Object.assign(Object.assign({}, (user.last_signin && { prev_signin: user.last_signin })), (user.last_signin_ip && { prev_signin_ip: user.last_signin_ip })), { last_signin: new Date(), last_signin_ip: ip })));
105
+ if ('password' in credentials) {
106
+ if (!user.password_salt) {
107
+ // OLD md5 password hash, convert to new salted hash
108
+ const pwd = (0, password_1.createPasswordHash)(credentials.password);
109
+ updates.password = pwd.hash;
110
+ updates.password_salt = pwd.salt;
111
+ }
112
+ if (!user.access_token) {
113
+ // Generate access token
114
+ updates.access_token = acebase_core_1.ID.generate();
115
+ updates.access_token_created = new Date();
116
+ }
116
117
  }
117
- if (!user.access_token) {
118
- // Generate access token
119
- updates.access_token = acebase_core_1.ID.generate();
120
- updates.access_token_created = new Date();
118
+ // Update user object
119
+ Object.assign(user, updates);
120
+ // Update db
121
+ yield env.authRef.child(user.uid).update(updates);
122
+ // Log history item
123
+ if (!LOG_DETAILS.uid) {
124
+ LOG_DETAILS.uid = user.uid;
121
125
  }
126
+ env.log.event(LOG_ACTION, LOG_DETAILS).catch((err) => env.debug.fatal(`Failed to log successful sign in to db`, err));
122
127
  }
123
- // Update user object
124
- Object.assign(user, updates);
125
- // Update db
126
- yield snap.ref.update(updates);
127
- // Log history item
128
- if (credentials.method !== 'internal') {
129
- env.log.event(LOG_ACTION, LOG_DETAILS);
130
- }
131
- // Add to cache
128
+ // Update cache
132
129
  env.authCache.set(user.uid, user);
133
- // Bind user to current request
134
- req.user = user;
135
130
  return user;
136
131
  }
137
132
  catch (err) {
138
133
  // Log error
139
- env.log.error(LOG_ACTION, (_a = err.code) !== null && _a !== void 0 ? _a : 'unexpected', LOG_DETAILS, typeof err.code === 'undefined' ? err : null);
134
+ env.log.error(LOG_ACTION, (_a = err === null || err === void 0 ? void 0 : err.code) !== null && _a !== void 0 ? _a : 'unexpected', LOG_DETAILS, (_c = (_b = err === null || err === void 0 ? void 0 : err.code) !== null && _b !== void 0 ? _b : err) !== null && _c !== void 0 ? _c : null)
135
+ .catch((err) => env.debug.fatal(`Failed to log failed sign in to db`, err));
140
136
  throw err;
141
137
  }
142
138
  });
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.fetch = void 0;
12
+ exports.fetch = fetch;
13
13
  const https_1 = require("https");
14
14
  /**
15
15
  * Very lightweight custom fetch implementation to avoid additional dependencies
@@ -73,5 +73,4 @@ function fetch(url, options) {
73
73
  req.end();
74
74
  });
75
75
  }
76
- exports.fetch = fetch;
77
76
  //# sourceMappingURL=simple-fetch.js.map
@@ -43,7 +43,7 @@ const getSignature = (content, salt) => {
43
43
  };
44
44
  /**
45
45
  * Sign objects with an md5 hash. An attacker might base4 decode it and see the content and generated checksum hash,
46
- * but will need to guess the password used to generate the hash to manipulate it. This is not impossible but will take
46
+ * but will need to guess the password used to generate the hash to manipulate it. This is not impossible but will take
47
47
  * a very long time when using a large password
48
48
  * @param obj data object to sign
49
49
  * @param password password to use as salt for the generated md5 hash
package/dist/cjs/start.js CHANGED
@@ -102,7 +102,7 @@ if (getVariable('AUTH', 'true') === 'true' || +getVariable('AUTH', 1) === 1) {
102
102
  allowUserSignup: +getVariable('AUTH_USER_SIGNUP', 1) === 1,
103
103
  defaultAccessRule: getVariable('AUTH_DEFAULT_ACCESS_RULE'),
104
104
  defaultAdminPassword: getVariable('AUTH_DEFAULT_ADMIN_PASSWORD'),
105
- newUserRateLimit: +getVariable('AUTH_NEW_USER_RATE_LIMIT', 0),
105
+ newUserRateLimit: +getVariable('AUTH_NEW_USER_RATE_LIMIT', 0), // No implemented yet
106
106
  separateDb: getVariable('AUTH_SEPARATE_DB', false),
107
107
  tokensExpire: +getVariable('AUTH_TOKENS_EXPIRE', 0), // No implemented yet
108
108
  };
@@ -233,20 +233,20 @@ const addWebsocketServer = (env) => {
233
233
  });
234
234
  const TRANSACTION_TIMEOUT_MS = 10000; // 10s to finish a started transaction
235
235
  serverManager.on('transaction-start', (event) => __awaiter(void 0, void 0, void 0, function* () {
236
- var _c, _d, _e;
236
+ var _a, _b, _c;
237
237
  // Start transaction
238
238
  const client = getClientBySocketId(event.socket_id, 'transaction-start');
239
239
  if (!client || !event.data) {
240
240
  return;
241
241
  }
242
242
  const LOG_ACTION = 'socket.transaction.start';
243
- const LOG_DETAILS = { ip: event.socket.conn.remoteAddress, uid: (_d = (_c = client.user) === null || _c === void 0 ? void 0 : _c.uid) !== null && _d !== void 0 ? _d : null, path: event.data.path };
243
+ const LOG_DETAILS = { ip: event.socket.conn.remoteAddress, uid: (_b = (_a = client.user) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null, path: event.data.path };
244
244
  env.debug.verbose(`Client ${event.socket_id} is sending transaction start request on path "${event.data.path}"`);
245
245
  const data = event.data;
246
246
  // Pre-check if reading AND writing is allowed (special transact operation)
247
247
  const access = yield env.rules.isOperationAllowed(client.user, data.path, 'transact');
248
248
  if (!access.allow) {
249
- env.log.error(LOG_ACTION, 'unauthorized', Object.assign(Object.assign({}, LOG_DETAILS), { rule_code: access.code, rule_path: (_e = access.rulePath) !== null && _e !== void 0 ? _e : null }), access.details);
249
+ 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 }), access.details);
250
250
  return serverManager.send(event.socket, 'tx_error', { id: data.id, reason: 'access_denied' });
251
251
  }
252
252
  const tx = {
@@ -268,11 +268,11 @@ const addWebsocketServer = (env) => {
268
268
  // Start transaction
269
269
  env.debug.verbose(`Transaction ${tx.id} starting...`);
270
270
  const donePromise = env.db.api.transaction(tx.path, (val) => __awaiter(void 0, void 0, void 0, function* () {
271
- var _f;
271
+ var _a;
272
272
  env.debug.verbose(`Transaction ${tx.id} started with value: `, val);
273
273
  const access = yield env.rules.isOperationAllowed(client.user, data.path, 'get', { value: val, context: tx.context });
274
274
  if (!access.allow) {
275
- env.log.error(LOG_ACTION, 'unauthorized', Object.assign(Object.assign({}, LOG_DETAILS), { rule_code: access.code, rule_path: (_f = access.rulePath) !== null && _f !== void 0 ? _f : null }), access.details);
275
+ env.log.error(LOG_ACTION, 'unauthorized', Object.assign(Object.assign({}, LOG_DETAILS), { rule_code: access.code, rule_path: (_a = access.rulePath) !== null && _a !== void 0 ? _a : null }), access.details);
276
276
  serverManager.send(event.socket, 'tx_error', { id: tx.id, reason: 'access_denied' });
277
277
  return; // Return undefined to cancel transaction
278
278
  }
@@ -289,19 +289,19 @@ const addWebsocketServer = (env) => {
289
289
  }), { context: tx.context });
290
290
  }));
291
291
  serverManager.on('transaction-finish', (event) => __awaiter(void 0, void 0, void 0, function* () {
292
- var _g, _h, _j, _k, _l;
292
+ var _a, _b, _c, _d, _e;
293
293
  // Finish transaction
294
294
  const client = getClientBySocketId(event.socket_id, 'transaction-finish');
295
295
  if (!client || !event.data) {
296
296
  return;
297
297
  }
298
298
  const LOG_ACTION = 'socket.transaction.finish';
299
- const LOG_DETAILS = { ip: event.socket.conn.remoteAddress, uid: (_h = (_g = client.user) === null || _g === void 0 ? void 0 : _g.uid) !== null && _h !== void 0 ? _h : null, path: event.data.path };
299
+ const LOG_DETAILS = { ip: event.socket.conn.remoteAddress, uid: (_b = (_a = client.user) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null, path: event.data.path };
300
300
  const data = event.data;
301
301
  const tx = client.transactions[data.id];
302
302
  try {
303
303
  if (!tx || data.path !== tx.path) {
304
- env.log.error(LOG_ACTION, tx ? 'wrong_path' : 'not_found', Object.assign(Object.assign({}, LOG_DETAILS), { id: data.id, tx_path: (_j = tx === null || tx === void 0 ? void 0 : tx.path) !== null && _j !== void 0 ? _j : null }));
304
+ env.log.error(LOG_ACTION, tx ? 'wrong_path' : 'not_found', Object.assign(Object.assign({}, LOG_DETAILS), { id: data.id, tx_path: (_c = tx === null || tx === void 0 ? void 0 : tx.path) !== null && _c !== void 0 ? _c : null }));
305
305
  throw new SocketRequestError('transaction_not_found', 'Transaction not found');
306
306
  }
307
307
  clearTimeout(tx.timeout);
@@ -310,7 +310,7 @@ const addWebsocketServer = (env) => {
310
310
  if (typeof newValue !== 'undefined') {
311
311
  const access = yield env.rules.isOperationAllowed(client.user, data.path, 'set', { value: newValue, context: tx.context });
312
312
  if (!access.allow) {
313
- env.log.error(LOG_ACTION, 'unauthorized', Object.assign(Object.assign({}, LOG_DETAILS), { rule_code: access.code, rule_path: (_k = access.rulePath) !== null && _k !== void 0 ? _k : null }), access.details);
313
+ 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 }), access.details);
314
314
  throw new SocketRequestError('access_denied', 'Access denied');
315
315
  }
316
316
  }
@@ -323,7 +323,7 @@ const addWebsocketServer = (env) => {
323
323
  // Other errors have been logged already
324
324
  env.log.error(LOG_ACTION, 'unexpected', LOG_DETAILS, err);
325
325
  }
326
- serverManager.send(event.socket, 'tx_error', { id: tx.id, reason: (_l = err.code) !== null && _l !== void 0 ? _l : err.message, data });
326
+ serverManager.send(event.socket, 'tx_error', { id: tx.id, reason: (_e = err.code) !== null && _e !== void 0 ? _e : err.message, data });
327
327
  tx.finish(); // Finish with undefined, canceling the transaction
328
328
  }
329
329
  }));
@@ -34,8 +34,8 @@ const createServer = (env) => {
34
34
  const maxPayloadBytes = 10e7; // Socket is closed if sent message exceeds this. Socket.io 2.x default is 10e7 (100MB)
35
35
  const server = createSocketIOServer(env.server, {
36
36
  // See https://socket.io/docs/v2/server-initialization/ and https://socket.io/docs/v3/server-initialization/
37
- pingInterval: 5000,
38
- pingTimeout: 5000,
37
+ pingInterval: 5000, // socket.io 2.x default is 25000
38
+ pingTimeout: 5000, // socket.io 2.x default is 5000, 3.x default = 20000
39
39
  maxHttpBufferSize: maxPayloadBytes,
40
40
  path: `/${env.rootPath ? `${env.rootPath}/` : ''}socket.io`,
41
41
  // Allow socket.io 2.x clients (using engine.io 3.x):
package/dist/esm/auth.js CHANGED
@@ -5,16 +5,19 @@ export const setupAuthentication = async (env) => {
5
5
  // Setup auth cache
6
6
  env.authCache = new SimpleCache({ expirySeconds: 300, cloneValues: false, maxEntries: 1000 });
7
7
  // Get or generate a salt to hash public tokens with
8
- await env.securityRef.child('token_salt').transaction(snap => {
9
- env.tokenSalt = snap.val();
10
- if (!env.tokenSalt) {
8
+ await env.securityRef.child('token_salt').transaction((snap) => {
9
+ if (snap.exists()) {
10
+ env.tokenSalt = snap.val();
11
+ }
12
+ else {
13
+ // Generate new salt and store it
11
14
  const length = 256;
12
15
  env.tokenSalt = randomBytes(Math.ceil(length / 2)).toString('hex').slice(0, length);
13
16
  return env.tokenSalt;
14
17
  }
15
18
  });
16
19
  // Setup admin account
17
- await env.authRef.child('admin').transaction(snap => {
20
+ await env.authRef.child('admin').transaction((snap) => {
18
21
  let adminAccount = snap.val();
19
22
  if (adminAccount === null) {
20
23
  // Use provided default password, or generate one:
@@ -23,13 +26,13 @@ export const setupAuthentication = async (env) => {
23
26
  adminAccount = {
24
27
  uid: null,
25
28
  username: 'admin',
26
- email: null,
29
+ email: null, // no email address for admin
27
30
  display_name: `${env.db.name} AceBase admin`,
28
31
  password: pwd.hash,
29
32
  password_salt: pwd.salt,
30
- change_password: true,
33
+ change_password: true, // flags that password must be changed. Not implemented yet
31
34
  created: new Date(),
32
- access_token: null,
35
+ access_token: null, // Will be set upon login, so bearer authentication strategy can find user with this token
33
36
  settings: {},
34
37
  };
35
38
  env.debug.warn(`__________________________________________________________________`.colorize(ColorStyle.red));
@@ -22,21 +22,14 @@ export const addMiddleware = (env) => {
22
22
  tokenDetails = decodePublicAccessToken(token, env.tokenSalt);
23
23
  }
24
24
  catch (err) {
25
- return sendNotAuthenticatedError(res, 'invalid_token', 'The passed token is invalid. Sign in again');
25
+ return sendNotAuthenticatedError(res, 'invalid_token', 'Access token is invalid. Sign in again');
26
26
  }
27
- // Is this token cached?
28
- req.user = env.authCache.get(tokenDetails.uid);
29
- if (!req.user) {
30
- // Query database to get user for this token
31
- try {
32
- req.user = await signIn({ method: 'internal', access_token: tokenDetails.access_token }, env, req);
33
- }
34
- catch (err) {
35
- return sendNotAuthenticatedError(res, err.code, err.message);
36
- }
27
+ try {
28
+ // Query database to get user for this token, assign to request
29
+ req.user = await signIn({ method: 'token', uid: tokenDetails.uid, access_token: tokenDetails.access_token }, env, req.ip, false);
37
30
  }
38
- if (req.user.is_disabled === true) {
39
- return sendNotAuthenticatedError(res, 'account_disabled', 'Your account has been disabled. Contact your database administrator');
31
+ catch (err) {
32
+ return sendNotAuthenticatedError(res, err.code, err.message);
40
33
  }
41
34
  }
42
35
  next();
@@ -56,7 +56,7 @@ export class FacebookAuthProvider extends OAuth2Provider {
56
56
  display_name: user.short_name,
57
57
  picture: user.picture.data.is_silhouette ? null : [{ width: user.picture.data.width, height: user.picture.data.height, url: user.picture.data.url }],
58
58
  email: user.email,
59
- email_verified: typeof user.email === 'string',
59
+ email_verified: typeof user.email === 'string', // If we get the email address, it's always verified
60
60
  other: {
61
61
  // We haven't requested more, so we didn't get more
62
62
  },
@@ -50,7 +50,7 @@ export class InstagramAuthProvider extends OAuth2Provider {
50
50
  name: user.full_name,
51
51
  display_name: user.username,
52
52
  picture: [{ url: user.profile_picture }],
53
- email: null,
53
+ email: null, //NO E-MAIL! user.email,
54
54
  email_verified: false,
55
55
  other: Object.keys(user)
56
56
  .filter(key => !['id', 'username', 'full_name', 'profile_picture'].includes(key))
@@ -10,7 +10,7 @@ export class ChangePasswordError extends Error {
10
10
  }
11
11
  export const addRoute = (env) => {
12
12
  env.router.post(`/auth/${env.db.name}/change_password`, async (req, res) => {
13
- const access_token = req.user?.access_token;
13
+ let accessToken = req.user?.access_token;
14
14
  const details = req.body;
15
15
  const LOG_ACTION = 'auth.change_password';
16
16
  const LOG_DETAILS = { ip: req.ip, uid: details.uid ?? null };
@@ -26,7 +26,7 @@ export const addRoute = (env) => {
26
26
  return;
27
27
  }
28
28
  try {
29
- let publicAccessToken;
29
+ const signOutOtherClients = details.sign_out === true;
30
30
  await env.authRef.child(details.uid).transaction(snap => {
31
31
  if (!snap.exists()) {
32
32
  throw new ChangePasswordError('unknown_uid', `Unknown uid`);
@@ -37,29 +37,32 @@ export const addRoute = (env) => {
37
37
  if (user.password !== hash) {
38
38
  throw new ChangePasswordError('wrong_password', `Wrong password`);
39
39
  }
40
- if (access_token && access_token !== user.access_token) {
40
+ if (accessToken && accessToken !== user.access_token) {
41
41
  throw new ChangePasswordError('wrong_access_token', `Cannot change password while signed in as other user, or with an old token`);
42
42
  }
43
43
  const pwd = createPasswordHash(details.new_password);
44
44
  const updates = {
45
- access_token: ID.generate(),
46
- access_token_created: new Date(),
47
45
  password: pwd.hash,
48
46
  password_salt: pwd.salt,
49
47
  };
48
+ if (signOutOtherClients || !accessToken) {
49
+ accessToken = ID.generate();
50
+ updates.access_token = accessToken;
51
+ updates.access_token_created = new Date();
52
+ }
50
53
  // Update user object
51
54
  Object.assign(user, updates);
52
55
  // Set or update cache
53
56
  env.authCache.set(user.uid, user);
54
- // Create new public access token
55
- publicAccessToken = createPublicAccessToken(user.uid, req.ip, user.access_token, env.tokenSalt);
56
57
  return user; // Update db
57
58
  });
59
+ // Create new public access token
60
+ const publicAccessToken = createPublicAccessToken(details.uid, req.ip, accessToken, env.tokenSalt);
58
61
  env.log.event(LOG_ACTION, LOG_DETAILS);
59
62
  res.send({ access_token: publicAccessToken }); // Client must use this new access token from now on
60
63
  }
61
64
  catch (err) {
62
- env.log.error(LOG_ACTION, err.code, LOG_DETAILS);
65
+ env.log.error(LOG_ACTION, err?.code ?? 'unknown', LOG_DETAILS);
63
66
  if (err.code) {
64
67
  sendBadRequestError(res, err);
65
68
  }
@@ -19,7 +19,7 @@ export const addRoute = (env) => {
19
19
  return parseSignedPublicToken(code, env.tokenSalt);
20
20
  }
21
21
  catch (err) {
22
- throw new ResetPasswordError('invalid_code', err.message);
22
+ throw new ResetPasswordError('invalid_code', err?.message ?? '');
23
23
  }
24
24
  })();
25
25
  const snap = await env.authRef.child(verification.uid).get();
@@ -67,8 +67,8 @@ export const addRoute = (env) => {
67
67
  res.send('OK');
68
68
  }
69
69
  catch (err) {
70
- env.log.error(LOG_ACTION, err.code ?? 'unexpected', { ...LOG_DETAILS, message: (err instanceof Error && err.message) ?? err.toString() });
71
- if (err.code) {
70
+ env.log.error(LOG_ACTION, err?.code ?? 'unexpected', { ...LOG_DETAILS, message: err?.message ?? err?.toString() ?? 'Unexpected error' });
71
+ if (err?.code) {
72
72
  sendBadRequestError(res, err);
73
73
  }
74
74
  else {
@@ -1,7 +1,7 @@
1
1
  import { getPublicAccountDetails } from '../schema/user.js';
2
2
  import { sendNotAuthenticatedError, sendUnexpectedError } from '../shared/error.js';
3
- import { createPublicAccessToken } from '../shared/tokens.js';
4
- import { signIn } from '../shared/signin.js';
3
+ import { createPublicAccessToken, decodePublicAccessToken } from '../shared/tokens.js';
4
+ import { signIn, SignInError } from '../shared/signin.js';
5
5
  export const addRoute = (env) => {
6
6
  if (!env.config.auth.enabled) {
7
7
  throw new Error('Authentication not enabled in the server settings');
@@ -10,7 +10,20 @@ export const addRoute = (env) => {
10
10
  const details = req.body;
11
11
  const clientId = details.client_id || null; // NEW in AceBaseClient v0.9.4
12
12
  try {
13
- const user = await signIn(details, env, req);
13
+ const credentials = (() => {
14
+ if (details.method === 'token') {
15
+ // This is a public access token, convert to a private token that contains the user's uid and actual access token
16
+ try {
17
+ const tokenDetails = decodePublicAccessToken(details.access_token, env.tokenSalt);
18
+ return { method: 'token', uid: tokenDetails.uid, access_token: tokenDetails.access_token };
19
+ }
20
+ catch (err) {
21
+ throw new SignInError('invalid_token', `Access token is invalid. Sign in again`);
22
+ }
23
+ }
24
+ return details;
25
+ })();
26
+ const user = await signIn(credentials, env, req.ip, true);
14
27
  if (typeof clientId === 'string' && env.clients.has(clientId)) {
15
28
  const client = env.clients.get(clientId);
16
29
  client.user = user; // Bind user to client socket
@@ -21,7 +34,7 @@ export const addRoute = (env) => {
21
34
  });
22
35
  }
23
36
  catch (err) {
24
- if (typeof err.code === 'string') {
37
+ if (typeof err?.code === 'string') {
25
38
  // Authentication error
26
39
  return sendNotAuthenticatedError(res, err.code, err.message);
27
40
  }
@@ -68,7 +68,7 @@ export const addRoute = (env) => {
68
68
  }
69
69
  for (const childInfo of list ?? []) {
70
70
  childInfo.access = {
71
- read: (await env.rules.isOperationAllowed(impersonatedUser, PathInfo.getChildPath(path, childInfo.key), 'get')).allow,
71
+ read: (await env.rules.isOperationAllowed(impersonatedUser, PathInfo.getChildPath(path, childInfo.key), 'get')).allow, // Use pre-flight 'get' check to mimic legacy 'read' check
72
72
  write: (await env.rules.isOperationAllowed(impersonatedUser, PathInfo.getChildPath(path, childInfo.key), 'update')).allow, // Use pre-flight 'update' check to mimic legacy 'write' check
73
73
  };
74
74
  }
@@ -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.19.2',
17
+ version: '1.20.0', // Loaded from package.json by npm scripts
18
18
  contact: {
19
19
  name: 'AceBase API Support',
20
20
  email: 'me@appy.one',
@@ -1,6 +1,6 @@
1
1
  import { isAdmin } from '../shared/admin.js';
2
2
  import * as os from 'os';
3
- const SERVER_VERSION = '1.19.2'; // Loaded from package.json by npm scripts
3
+ const SERVER_VERSION = '1.20.0'; // Loaded from package.json by npm scripts
4
4
  export const addRoute = (env) => {
5
5
  // Add info endpoint
6
6
  env.router.get(`/info/${env.db.name}`, (req, res) => {
@@ -39,7 +39,7 @@ export const addRoute = (env) => {
39
39
  total: numberToByteSize(os.totalmem()),
40
40
  free: numberToByteSize(os.freemem()),
41
41
  process: {
42
- arrayBuffers: numberToByteSize(mem.arrayBuffers),
42
+ arrayBuffers: numberToByteSize(mem.arrayBuffers), // arrayBuffers was added in Node v13.9.0, v12.17.0
43
43
  external: numberToByteSize(mem.external),
44
44
  heapTotal: numberToByteSize(mem.heapTotal),
45
45
  heapUsed: numberToByteSize(mem.heapUsed),
@@ -166,9 +166,9 @@ export const addRoute = (env) => {
166
166
  const pwd = createPasswordHash(generatePassword());
167
167
  user = {
168
168
  uid: null,
169
- username: typeof user_details.email === 'undefined' ? providerUsername : null,
169
+ username: typeof user_details.email === 'undefined' ? providerUsername : null, // provider-accountid usernames for external accounts without email address
170
170
  email: user_details.email || null,
171
- email_verified: user_details.email_verified,
171
+ email_verified: user_details.email_verified, // trust provider's verification
172
172
  display_name: user_details.display_name,
173
173
  password: pwd.hash,
174
174
  password_salt: pwd.salt,
package/dist/esm/rules.js CHANGED
@@ -112,10 +112,12 @@ export class PathBasedRules {
112
112
  }
113
113
  };
114
114
  fs.watchFile(rulesFilePath, watchFileListener);
115
- this.stop = () => {
115
+ const stop = () => {
116
116
  fs.unwatchFile(rulesFilePath, watchFileListener);
117
+ process.off('SIGINT', stop);
117
118
  };
118
- process.on('SIGINT', this.stop);
119
+ this.stop = stop;
120
+ process.on('SIGINT', stop);
119
121
  this.authEnabled = env.authEnabled;
120
122
  this.accessRules = accessRules;
121
123
  }
@@ -213,7 +213,10 @@ export class AceBaseServer extends SimpleEventEmitter {
213
213
  });
214
214
  };
215
215
  // Handle SIGINT and shutdown requests
216
+ const sigintHandler = () => shutdown({ sigint: true });
216
217
  const shutdown = async (request) => {
218
+ // Don't keep listening for SIGINT once the server has been shut down
219
+ process.off('SIGINT', sigintHandler);
217
220
  this.debug.warn('shutting down server');
218
221
  routeEnv.rules.stop();
219
222
  const getConnectionsCount = () => {
@@ -314,7 +317,7 @@ export class AceBaseServer extends SimpleEventEmitter {
314
317
  this._ready = true;
315
318
  this.emitOnce(`ready`);
316
319
  });
317
- process.on('SIGINT', () => shutdown({ sigint: true }));
320
+ process.on('SIGINT', sigintHandler);
318
321
  }
319
322
  }
320
323
  /**
@@ -21,6 +21,6 @@ export const sendBadRequestError = (res, err) => {
21
21
  res.status(400).contentType('application/json').send({ code: err.code, message: err.message }); // Bad Request
22
22
  };
23
23
  export const sendUnexpectedError = (res, err) => {
24
- res.status(500).contentType('application/json').send({ code: 'unexpected', message: 'server error', details: err.message }); // Internal server error
24
+ res.status(500).contentType('application/json').send({ code: 'unexpected', message: 'server error', details: err?.message ?? 'Unknown error' }); // Internal server error
25
25
  };
26
26
  //# sourceMappingURL=error.js.map