acebase-server 1.11.0 → 1.12.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 (157) hide show
  1. package/dist/cjs/logger.js +74 -0
  2. package/dist/cjs/logger.js.map +1 -0
  3. package/dist/cjs/middleware/admin-only.js +29 -0
  4. package/dist/cjs/middleware/admin-only.js.map +1 -0
  5. package/dist/cjs/middleware/user.js +4 -4
  6. package/dist/cjs/middleware/user.js.map +1 -1
  7. package/dist/cjs/routes/auth-change-password.js +7 -4
  8. package/dist/cjs/routes/auth-change-password.js.map +1 -1
  9. package/dist/cjs/routes/auth-delete.js +9 -7
  10. package/dist/cjs/routes/auth-delete.js.map +1 -1
  11. package/dist/cjs/routes/auth-forgot-password.js +9 -6
  12. package/dist/cjs/routes/auth-forgot-password.js.map +1 -1
  13. package/dist/cjs/routes/auth-reset-password.js +5 -3
  14. package/dist/cjs/routes/auth-reset-password.js.map +1 -1
  15. package/dist/cjs/routes/auth-signout.js +6 -4
  16. package/dist/cjs/routes/auth-signout.js.map +1 -1
  17. package/dist/cjs/routes/auth-signup.js +17 -15
  18. package/dist/cjs/routes/auth-signup.js.map +1 -1
  19. package/dist/cjs/routes/auth-update.js +9 -6
  20. package/dist/cjs/routes/auth-update.js.map +1 -1
  21. package/dist/cjs/routes/auth-verify-email.js +6 -3
  22. package/dist/cjs/routes/auth-verify-email.js.map +1 -1
  23. package/dist/cjs/routes/data-index-create.js +3 -5
  24. package/dist/cjs/routes/data-index-create.js.map +1 -1
  25. package/dist/cjs/routes/data-index-delete.js +2 -4
  26. package/dist/cjs/routes/data-index-delete.js.map +1 -1
  27. package/dist/cjs/routes/data-index-list.js +2 -4
  28. package/dist/cjs/routes/data-index-list.js.map +1 -1
  29. package/dist/cjs/routes/data-reflect.js +2 -4
  30. package/dist/cjs/routes/data-reflect.js.map +1 -1
  31. package/dist/cjs/routes/data-schema-get.js +2 -4
  32. package/dist/cjs/routes/data-schema-get.js.map +1 -1
  33. package/dist/cjs/routes/data-schema-set.js +2 -4
  34. package/dist/cjs/routes/data-schema-set.js.map +1 -1
  35. package/dist/cjs/routes/data-schema-test.js +2 -4
  36. package/dist/cjs/routes/data-schema-test.js.map +1 -1
  37. package/dist/cjs/routes/data-schemas-list.js +2 -4
  38. package/dist/cjs/routes/data-schemas-list.js.map +1 -1
  39. package/dist/cjs/routes/data-set.js +8 -7
  40. package/dist/cjs/routes/data-set.js.map +1 -1
  41. package/dist/cjs/routes/data-transaction.js +15 -8
  42. package/dist/cjs/routes/data-transaction.js.map +1 -1
  43. package/dist/cjs/routes/data-update.js +8 -6
  44. package/dist/cjs/routes/data-update.js.map +1 -1
  45. package/dist/cjs/routes/meta-logs.js +50 -0
  46. package/dist/cjs/routes/meta-logs.js.map +1 -0
  47. package/dist/cjs/routes/meta.js +3 -0
  48. package/dist/cjs/routes/meta.js.map +1 -1
  49. package/dist/cjs/routes/oauth2-signin.js +9 -6
  50. package/dist/cjs/routes/oauth2-signin.js.map +1 -1
  51. package/dist/cjs/server.js +3 -1
  52. package/dist/cjs/server.js.map +1 -1
  53. package/dist/cjs/shared/env.js.map +1 -1
  54. package/dist/cjs/shared/signin.js +8 -3
  55. package/dist/cjs/shared/signin.js.map +1 -1
  56. package/dist/cjs/start.js +3 -0
  57. package/dist/cjs/start.js.map +1 -1
  58. package/dist/cjs/websocket/index.js +42 -23
  59. package/dist/cjs/websocket/index.js.map +1 -1
  60. package/dist/esm/logger.js +52 -0
  61. package/dist/esm/logger.js.map +1 -0
  62. package/dist/esm/middleware/admin-only.js +25 -0
  63. package/dist/esm/middleware/admin-only.js.map +1 -0
  64. package/dist/esm/middleware/user.js +4 -4
  65. package/dist/esm/middleware/user.js.map +1 -1
  66. package/dist/esm/routes/auth-change-password.js +6 -3
  67. package/dist/esm/routes/auth-change-password.js.map +1 -1
  68. package/dist/esm/routes/auth-delete.js +7 -5
  69. package/dist/esm/routes/auth-delete.js.map +1 -1
  70. package/dist/esm/routes/auth-forgot-password.js +8 -6
  71. package/dist/esm/routes/auth-forgot-password.js.map +1 -1
  72. package/dist/esm/routes/auth-reset-password.js +4 -2
  73. package/dist/esm/routes/auth-reset-password.js.map +1 -1
  74. package/dist/esm/routes/auth-signout.js +4 -2
  75. package/dist/esm/routes/auth-signout.js.map +1 -1
  76. package/dist/esm/routes/auth-signup.js +12 -10
  77. package/dist/esm/routes/auth-signup.js.map +1 -1
  78. package/dist/esm/routes/auth-update.js +8 -6
  79. package/dist/esm/routes/auth-update.js.map +1 -1
  80. package/dist/esm/routes/auth-verify-email.js +6 -2
  81. package/dist/esm/routes/auth-verify-email.js.map +1 -1
  82. package/dist/esm/routes/data-index-create.js +4 -6
  83. package/dist/esm/routes/data-index-create.js.map +1 -1
  84. package/dist/esm/routes/data-index-delete.js +3 -5
  85. package/dist/esm/routes/data-index-delete.js.map +1 -1
  86. package/dist/esm/routes/data-index-list.js +3 -5
  87. package/dist/esm/routes/data-index-list.js.map +1 -1
  88. package/dist/esm/routes/data-reflect.js +1 -4
  89. package/dist/esm/routes/data-reflect.js.map +1 -1
  90. package/dist/esm/routes/data-schema-get.js +3 -5
  91. package/dist/esm/routes/data-schema-get.js.map +1 -1
  92. package/dist/esm/routes/data-schema-set.js +3 -5
  93. package/dist/esm/routes/data-schema-set.js.map +1 -1
  94. package/dist/esm/routes/data-schema-test.js +3 -5
  95. package/dist/esm/routes/data-schema-test.js.map +1 -1
  96. package/dist/esm/routes/data-schemas-list.js +3 -5
  97. package/dist/esm/routes/data-schemas-list.js.map +1 -1
  98. package/dist/esm/routes/data-set.js +6 -5
  99. package/dist/esm/routes/data-set.js.map +1 -1
  100. package/dist/esm/routes/data-transaction.js +12 -5
  101. package/dist/esm/routes/data-transaction.js.map +1 -1
  102. package/dist/esm/routes/data-update.js +6 -4
  103. package/dist/esm/routes/data-update.js.map +1 -1
  104. package/dist/esm/routes/meta-logs.js +36 -0
  105. package/dist/esm/routes/meta-logs.js.map +1 -0
  106. package/dist/esm/routes/meta.js +3 -0
  107. package/dist/esm/routes/meta.js.map +1 -1
  108. package/dist/esm/routes/oauth2-signin.js +8 -5
  109. package/dist/esm/routes/oauth2-signin.js.map +1 -1
  110. package/dist/esm/server.js +3 -1
  111. package/dist/esm/server.js.map +1 -1
  112. package/dist/esm/shared/env.js.map +1 -1
  113. package/dist/esm/shared/signin.js +7 -3
  114. package/dist/esm/shared/signin.js.map +1 -1
  115. package/dist/esm/start.js +3 -0
  116. package/dist/esm/start.js.map +1 -1
  117. package/dist/esm/websocket/index.js +37 -22
  118. package/dist/esm/websocket/index.js.map +1 -1
  119. package/dist/types/logger.d.ts +35 -0
  120. package/dist/types/middleware/admin-only.d.ts +19 -0
  121. package/dist/types/routes/meta-logs.d.ts +20 -0
  122. package/dist/types/rules.d.ts +2 -2
  123. package/dist/types/shared/env.d.ts +3 -1
  124. package/dist/types/shared/signin.d.ts +1 -1
  125. package/dist/types/websocket/index.d.ts +4 -0
  126. package/package.json +5 -5
  127. package/src/logger.ts +56 -0
  128. package/src/middleware/admin-only.ts +29 -0
  129. package/src/middleware/user.ts +4 -4
  130. package/src/routes/auth-change-password.ts +6 -3
  131. package/src/routes/auth-delete.ts +7 -5
  132. package/src/routes/auth-forgot-password.ts +10 -6
  133. package/src/routes/auth-reset-password.ts +5 -2
  134. package/src/routes/auth-signout.ts +5 -2
  135. package/src/routes/auth-signup.ts +13 -10
  136. package/src/routes/auth-update.ts +8 -6
  137. package/src/routes/auth-verify-email.ts +11 -3
  138. package/src/routes/data-index-create.ts +4 -7
  139. package/src/routes/data-index-delete.ts +3 -6
  140. package/src/routes/data-index-list.ts +3 -6
  141. package/src/routes/data-reflect.ts +1 -4
  142. package/src/routes/data-schema-get.ts +3 -5
  143. package/src/routes/data-schema-set.ts +3 -6
  144. package/src/routes/data-schema-test.ts +3 -6
  145. package/src/routes/data-schemas-list.ts +3 -5
  146. package/src/routes/data-set.ts +10 -6
  147. package/src/routes/data-transaction.ts +14 -5
  148. package/src/routes/data-update.ts +8 -4
  149. package/src/routes/meta-logs.ts +57 -0
  150. package/src/routes/meta.ts +4 -0
  151. package/src/routes/oauth2-signin.ts +11 -7
  152. package/src/rules.ts +1 -1
  153. package/src/server.ts +3 -1
  154. package/src/shared/env.ts +2 -1
  155. package/src/shared/signin.ts +10 -4
  156. package/src/start.ts +3 -0
  157. package/src/websocket/index.ts +40 -23
@@ -23,10 +23,14 @@ export type Request = RouteRequest<any, ResponseBody, RequestBody, RequestQuery>
23
23
  export const addRoute = (env: RouteInitEnvironment) => {
24
24
 
25
25
  env.app.put(`/data/${env.db.name}/*`, async (req: Request, res) => {
26
- // Set data
26
+
27
27
  const path = req.path.slice(env.db.name.length + 7);
28
+ const LOG_ACTION = 'data.set';
29
+ const LOG_DETAILS = { ip: req.ip, uid: req.user?.uid ?? null, path };
30
+
28
31
  const access = env.rules.userHasAccess(req.user, path, true);
29
32
  if (!access.allow) {
33
+ env.log.error(LOG_ACTION, 'unauthorized', { ...LOG_DETAILS, rule_code: access.code, rule_path: access.rulePath ?? null, rule_error: access.details?.message ?? null });
30
34
  return sendUnauthorizedError(res, access.code, access.message);
31
35
  }
32
36
 
@@ -58,21 +62,21 @@ export const addRoute = (env: RouteInitEnvironment) => {
58
62
 
59
63
  res.send({ success: true });
60
64
  }
61
- catch(err) {
65
+ catch (err) {
62
66
  if (err instanceof SchemaValidationError) {
63
- env.logRef?.push({ action: 'set_data', success: false, code: 'schema_validation_failed', path, error: err.reason, ip: req.ip, uid: req.user?.uid ?? null });
67
+ env.log.error(LOG_ACTION, 'schema_validation_failed', { ...LOG_DETAILS, reason: err.reason });
64
68
  res.status(422).send({ code: 'schema_validation_failed', message: err.message });
65
69
  }
66
70
  else if (err instanceof SetDataError) {
67
- env.logRef?.push({ action: 'set_data', success: false, code: err.code, path, ip: req.ip, uid: req.user?.uid ?? null });
71
+ env.log.error(LOG_ACTION, err.code, { ...LOG_DETAILS, message: err.message });
68
72
  sendBadRequestError(res, err);
69
73
  }
70
74
  else {
71
75
  env.debug.error(`failed to set "${path}":`, err);
72
- env.logRef?.push({ action: 'set_data', success: false, code: 'unknown_error', path, error: err.message, ip: req.ip, uid: req.user?.uid ?? null });
76
+ env.log.error(LOG_ACTION, 'unexpected', LOG_DETAILS, err);
73
77
  sendError(res, err);
74
78
  }
75
- };
79
+ }
76
80
  });
77
81
 
78
82
  };
@@ -44,8 +44,13 @@ export const addRoutes = (env: RouteInitEnvironment) => {
44
44
  // Start transaction endpoint:
45
45
  env.app.post(`/transaction/${env.db.name}/start`, (req: StartRequest, res) => {
46
46
  const data = req.body;
47
+
48
+ const LOG_ACTION = 'data.transaction.start';
49
+ const LOG_DETAILS = { ip: req.ip, uid: req.user?.uid ?? null, path: data.path };
50
+
47
51
  const access = env.rules.userHasAccess(req.user, data.path, true);
48
52
  if (!access.allow) {
53
+ env.log.error(LOG_ACTION, 'unauthorized', { ...LOG_DETAILS, rule_code: access.code, rule_path: access.rulePath ?? null }, access.details);
49
54
  return sendUnauthorizedError(res, access.code, access.message);
50
55
  }
51
56
 
@@ -84,7 +89,7 @@ export const addRoutes = (env: RouteInitEnvironment) => {
84
89
  }
85
90
  catch (err) {
86
91
  env.debug.error(`failed to start transaction on "${tx.path}":`, err);
87
- env.logRef?.push({ action: 'tx_start', success: false, code: err.code ?? 'unknown_error', path: tx.path, error: err.message, ip: req.ip, uid: req.user?.uid ?? null });
92
+ env.log.error(LOG_ACTION, err.code ?? 'unexpected', LOG_DETAILS, typeof err.code === 'undefined' ? err : null);
88
93
  sendUnexpectedError(res, err);
89
94
  }
90
95
  });
@@ -92,9 +97,12 @@ export const addRoutes = (env: RouteInitEnvironment) => {
92
97
  // Finish transaction endpoint:
93
98
  env.app.post(`/transaction/${env.db.name}/finish`, async (req: FinishRequest, res) => {
94
99
  const data = req.body;
100
+ const LOG_ACTION = 'data.transaction.finish';
101
+ const LOG_DETAILS = { ip: req.ip, uid: req.user?.uid ?? null, path: data.path };
95
102
 
96
103
  const tx = _transactions.get(data.id);
97
104
  if (!tx || tx.path !== data.path) {
105
+ env.log.error(LOG_ACTION, tx ? 'wrong_path' : 'not_found', { ...LOG_DETAILS, id: data.id, tx_path: tx?.path ?? null });
98
106
  res.statusCode = 410; // Gone
99
107
  res.send(`transaction not found`);
100
108
  return;
@@ -104,6 +112,7 @@ export const addRoutes = (env: RouteInitEnvironment) => {
104
112
 
105
113
  const access = env.rules.userHasAccess(req.user, tx.path, true);
106
114
  if (!access.allow) {
115
+ env.log.error(LOG_ACTION, 'unauthorized', { ...LOG_DETAILS, rule_code: access.code, rule_path: access.rulePath ?? null }, access.details);
107
116
  return sendUnauthorizedError(res, access.code, access.message);
108
117
  }
109
118
 
@@ -139,16 +148,16 @@ export const addRoutes = (env: RouteInitEnvironment) => {
139
148
  catch (err) {
140
149
  tx.finish(); // Finish without value cancels the transaction
141
150
  if (err instanceof SchemaValidationError) {
142
- env.logRef?.push({ action: 'tx_finish', success: false, code: 'schema_validation_failed', path: tx.path, error: err.reason, ip: req.ip, uid: req.user?.uid ?? null });
151
+ env.log.error(LOG_ACTION, 'schema_validation_failed', { ...LOG_DETAILS, reason: err.reason });
143
152
  res.status(422).send({ code: 'schema_validation_failed', message: err.message });
144
153
  }
145
154
  else if (err instanceof DataTransactionError) {
146
- env.logRef?.push({ action: 'tx_finish', success: false, code: err.code, path: tx.path, ip: req.ip, uid: req.user?.uid ?? null });
155
+ env.log.error(LOG_ACTION, err.code, { ...LOG_DETAILS, message: err.message });
147
156
  sendBadRequestError(res, err);
148
157
  }
149
158
  else {
150
- env.debug.error(`failed to finsih transaction on "${tx.path}":`, err);
151
- env.logRef?.push({ action: 'tx_finish', success: false, code: 'unknown_error', path: tx.path, error: err.message, ip: req.ip, uid: req.user?.uid ?? null });
159
+ env.debug.error(`failed to finish transaction on "${tx.path}":`, err);
160
+ env.log.error(LOG_ACTION, 'unexpected', LOG_DETAILS, err);
152
161
  sendError(res, err);
153
162
  }
154
163
  }
@@ -24,10 +24,14 @@ export type Request = RouteRequest<any, ResponseBody, RequestBody, RequestQuery>
24
24
  export const addRoute = (env: RouteInitEnvironment) => {
25
25
 
26
26
  env.app.post(`/data/${env.db.name}/*`, async (req: Request, res) => {
27
- // update data
27
+
28
28
  const path = req.path.slice(env.db.name.length + 7);
29
+ const LOG_ACTION = 'data.update';
30
+ const LOG_DETAILS = { ip: req.ip, uid: req.user?.uid ?? null, path };
31
+
29
32
  const access = env.rules.userHasAccess(req.user, path, true);
30
33
  if (!access.allow) {
34
+ env.log.error(LOG_ACTION, 'unauthorized', { ...LOG_DETAILS, rule_code: access.code, rule_path: access.rulePath ?? null, rule_error: access.details?.message ?? null });
31
35
  return sendUnauthorizedError(res, access.code, access.message);
32
36
  }
33
37
 
@@ -61,16 +65,16 @@ export const addRoute = (env: RouteInitEnvironment) => {
61
65
  }
62
66
  catch(err) {
63
67
  if (err instanceof SchemaValidationError) {
64
- env.logRef?.push({ action: 'update_data', success: false, code: 'schema_validation_failed', path, error: err.reason, ip: req.ip, uid: req.user?.uid ?? null });
68
+ env.log.error(LOG_ACTION, 'schema_validation_failed', { ...LOG_DETAILS, reason: err.reason });
65
69
  res.status(422).send({ code: 'schema_validation_failed', message: err.message });
66
70
  }
67
71
  else if (err instanceof UpdateDataError) {
68
- env.logRef?.push({ action: 'update_data', success: false, code: err.code, path, ip: req.ip, uid: req.user?.uid ?? null });
72
+ env.log.error(LOG_ACTION, err.code, { ...LOG_DETAILS, message: err.message });
69
73
  sendBadRequestError(res, err);
70
74
  }
71
75
  else {
72
76
  env.debug.error(`failed to update "${path}":`, err);
73
- env.logRef?.push({ action: 'update_data', success: false, code: `unknown_error`, path, error: err.message, ip: req.ip, uid: req.user?.uid ?? null });
77
+ env.log.error(LOG_ACTION, 'unexpected', LOG_DETAILS, err);
74
78
  sendError(res, err);
75
79
  }
76
80
  }
@@ -0,0 +1,57 @@
1
+ import { AceBase } from 'acebase';
2
+ import { QueryOperator } from 'acebase-core/types/data-reference';
3
+ import adminOnly from '../middleware/admin-only';
4
+ import { RouteInitEnvironment, RouteRequest } from '../shared/env';
5
+
6
+ type AceBaseLogLine = {
7
+ action: string;
8
+ ip: string;
9
+ date: string;
10
+ };
11
+
12
+ export type RequestQuery = { take?: string; skip?: string; sort?: 'date'; filter_col?: string; filter_op?: QueryOperator; filter_val?: string };
13
+ export type RequestBody = null;
14
+ export type ResponseBody = AceBaseLogLine[];
15
+ export type Request = RouteRequest<any, ResponseBody, RequestBody, RequestQuery>;
16
+
17
+ export const addRoute = (env: RouteInitEnvironment) => {
18
+
19
+ env.app.get(`/logs/${env.db.name}`, adminOnly(env), async (req: Request, res) => {
20
+ // Get database logs
21
+
22
+ // Create indexes if not there yet
23
+ const db = (env.log.ref as any).db as AceBase;
24
+ const createIndexes = [
25
+ db.indexes.create(env.log.ref.path, 'date')
26
+ ];
27
+ if (req.query.filter_col === 'action') {
28
+ createIndexes.push(db.indexes.create(env.log.ref.path, 'action', { include: ['date'] }));
29
+ }
30
+ if (req.query.filter_col === 'code') {
31
+ createIndexes.push(db.indexes.create(env.log.ref.path, 'code', { include: ['date'] }));
32
+ }
33
+ await Promise.all(createIndexes);
34
+
35
+ try {
36
+ const query = env.log.query()
37
+ .take(parseInt(req.query.take ?? '100'))
38
+ .skip(parseInt(req.query.skip ?? '0'))
39
+ .sort(req.query.sort ?? 'date', false);
40
+
41
+ if (req.query.filter_col) {
42
+ query.filter(req.query.filter_col, req.query.filter_op, req.query.filter_val);
43
+ }
44
+
45
+ const snaps = await query.get();
46
+ const logs = snaps.getValues() as AceBaseLogLine[];
47
+ res.send(logs);
48
+ }
49
+ catch (err) {
50
+ res.statusCode = 500;
51
+ res.send(err.message);
52
+ }
53
+ });
54
+
55
+ };
56
+
57
+ export default addRoute;
@@ -2,6 +2,7 @@ import type { RouteInitEnvironment } from '../shared/env';
2
2
  import addInfoRoute from './meta-info';
3
3
  import addPingRoute from './meta-ping';
4
4
  import addStatsRoute from './meta-stats';
5
+ import addLogsRoute from './meta-logs';
5
6
 
6
7
  export const addRoutes = (env: RouteInitEnvironment) => {
7
8
 
@@ -13,6 +14,9 @@ export const addRoutes = (env: RouteInitEnvironment) => {
13
14
 
14
15
  // Add database stats endpoint
15
16
  addStatsRoute(env);
17
+
18
+ // Add logs endpoint (admin only)
19
+ addLogsRoute(env);
16
20
  };
17
21
 
18
22
  export default addRoutes;
@@ -17,10 +17,13 @@ export type Request = RouteRequest<any, ResponseBody, RequestBody, RequestQuery>
17
17
  export const addRoute = (env: RouteInitEnvironment) => {
18
18
 
19
19
  env.app.get(`/oauth2/${env.db.name}/signin`, async (req: Request, res) => {
20
-
21
20
  // This is where the user is redirected to by the provider after signin or error
21
+
22
+ const LOG_ACTION = 'oauth2.signin';
23
+ const LOG_DETAILS = { ip: req.ip, provider: null };
24
+
22
25
  try {
23
- const state = parseSignedPublicToken(req.query.state, env.tokenSalt);
26
+ const state = parseSignedPublicToken(req.query.state, env.tokenSalt) as { provider: string; client_id: string; flow: 'socket'|'http'; callbackUrl: string; uid?: string };
24
27
  if (req.query.error) {
25
28
  if (state.flow === 'socket') {
26
29
  const client = env.clients.get(state.client_id);
@@ -36,6 +39,7 @@ export const addRoute = (env: RouteInitEnvironment) => {
36
39
  // Got authorization code
37
40
  const authCode = req.query.code;
38
41
  const provider = env.authProviders[state.provider];
42
+ LOG_DETAILS.provider = state.provider;
39
43
 
40
44
  // Get access & refresh tokens
41
45
  const tokens = await provider.getAccessToken({ type: 'auth', auth_code: authCode, redirect_url: `${req.protocol}://${req.headers.host}/oauth2/${env.db.name}/signin` });
@@ -149,7 +153,7 @@ export const addRoute = (env: RouteInitEnvironment) => {
149
153
  await env.authRef.child(uid).child('settings').update(getProviderSettings());
150
154
 
151
155
  // Log success
152
- env.logRef.push({ action: 'oauth2_signin', success: true, ip: req.ip, date: new Date(), uid });
156
+ env.log.event(LOG_ACTION, { ...LOG_DETAILS, uid });
153
157
 
154
158
  // Cache the user
155
159
  env.authCache.set(user.uid, user);
@@ -172,14 +176,14 @@ export const addRoute = (env: RouteInitEnvironment) => {
172
176
  };
173
177
 
174
178
  env.config.email?.send(request).catch(err => {
175
- env.logRef.push({ action: 'oauth2_login_email', success: false, code: 'unexpected', ip: req.ip, date: new Date(), error: err.message, request });
179
+ env.log.error(LOG_ACTION + '.email', 'unexpected', { ...LOG_DETAILS, uid, request }, err);
176
180
  });
177
181
  }
178
182
  else if (snaps.length === 0) {
179
183
  // User does not exist, create
180
184
 
181
185
  if (!env.config.auth.allowUserSignup) {
182
- env.logRef.push({ action: 'oauth2_signup', success: false, code: 'user_signup_disabled', provider: state.provider, email: user_details.email, date: new Date() });
186
+ env.log.error(LOG_ACTION, 'user_signup_disabled', { ...LOG_DETAILS, email: user_details.email });
183
187
  res.statusCode = 403; // Forbidden
184
188
  return res.send({ code: 'admin_only', message: 'Only admin is allowed to create users' });
185
189
  }
@@ -209,7 +213,7 @@ export const addRoute = (env: RouteInitEnvironment) => {
209
213
  user.uid = uid;
210
214
 
211
215
  // Log success
212
- env.logRef.push({ action: 'oauth2_signup', success: true, ip: req.ip, date: new Date(), uid });
216
+ env.log.event(LOG_ACTION, { ...LOG_DETAILS, uid });
213
217
 
214
218
  // Cache the user
215
219
  env.authCache.set(user.uid, user);
@@ -232,7 +236,7 @@ export const addRoute = (env: RouteInitEnvironment) => {
232
236
  };
233
237
 
234
238
  env.config.email?.send(request).catch(err => {
235
- env.logRef.push({ action: 'oauth2_signup_email', success: false, code: 'unexpected', ip: req.ip, date: new Date(), error: err.message, request });
239
+ env.log.error(LOG_ACTION + '.email', 'unexpected', { ...LOG_DETAILS, uid, request }, err);
236
240
  });
237
241
  }
238
242
  else {
package/src/rules.ts CHANGED
@@ -16,7 +16,7 @@ type RulesData = {
16
16
  }
17
17
  export type RuleValidationFailCode = 'rule'|'no_rule'|'private'|'exception';
18
18
  // type HasAccessResult = { allow: true } | { allow: false; code: RuleValidationFailCode; message: string; rule?: string|boolean; rulePath?: string; details?: any };
19
- type HasAccessResult = { allow: boolean; code?: RuleValidationFailCode; message?: string; rule?: string|boolean; rulePath?: string; details?: any } & ({ allow: true } | { allow: false; code: RuleValidationFailCode; message: string; rule?: string|boolean; rulePath?: string; details?: any });
19
+ type HasAccessResult = { allow: boolean; code?: RuleValidationFailCode; message?: string; rule?: string|boolean; rulePath?: string; details?: Error } & ({ allow: true } | { allow: false; code: RuleValidationFailCode; message: string; rule?: string|boolean; rulePath?: string; details?: Error });
20
20
 
21
21
  export class PathBasedRules {
22
22
 
package/src/server.ts CHANGED
@@ -23,6 +23,7 @@ import addMetadataRoutes from './routes/meta';
23
23
  import add404Middleware from './middleware/404';
24
24
  import addSwaggerMiddleware from './middleware/swagger';
25
25
  import addCacheMiddleware from './middleware/cache';
26
+ import { DatabaseLog } from './logger';
26
27
 
27
28
  type PrivateStorageSettings = AceBaseStorageSettings & { info?: string; type?: 'data'|'transaction'|'auth'|'log' };
28
29
  // type PrivateLocalSettings = AceBaseLocalSettings & { storage: PrivateStorageSettings };
@@ -155,6 +156,7 @@ export class AceBaseServer extends SimpleEventEmitter {
155
156
  const securityRef = authDb ? authDb === db ? db.ref('__auth__/security') : authDb.ref('security') : null;
156
157
  const authRef = authDb ? authDb === db ? db.ref('__auth__/accounts') : authDb.ref('accounts') : null;
157
158
  const logRef = authDb ? authDb === db ? db.ref('__log__') : authDb.ref('log') : null;
159
+ const logger = new DatabaseLog(logRef);
158
160
 
159
161
  // Setup rules
160
162
  const rulesFilePath = `${this.config.path}/${this.db.name}.acebase/rules.json`;
@@ -169,7 +171,7 @@ export class AceBaseServer extends SimpleEventEmitter {
169
171
  debug: this.debug,
170
172
  securityRef,
171
173
  authRef,
172
- logRef,
174
+ log: logger,
173
175
  tokenSalt: null,
174
176
  clients,
175
177
  authCache: null,
package/src/shared/env.ts CHANGED
@@ -9,6 +9,7 @@ import type { Server as HttpServer } from 'http';
9
9
  import type { Server as SecureHttpServer } from 'https';
10
10
  import type { PathBasedRules } from '../rules';
11
11
  import { Api } from 'acebase-core/src/api';
12
+ import { DatabaseLog } from '../logger';
12
13
 
13
14
  export interface RouteInitEnvironment {
14
15
  server: HttpServer | SecureHttpServer;
@@ -19,7 +20,7 @@ export interface RouteInitEnvironment {
19
20
  debug: DebugLogger;
20
21
  securityRef: DataReference;
21
22
  authRef: DataReference;
22
- logRef: DataReference;
23
+ log: DatabaseLog; // logRef: DataReference;
23
24
  tokenSalt: string;
24
25
  clients: Map<string, ConnectedClient>;
25
26
  authCache: SimpleCache<string, DbUserAccountDetails>;
@@ -6,7 +6,7 @@ import { decodePublicAccessToken } from "./tokens";
6
6
 
7
7
  export type SignInCredentials =
8
8
  { method: 'token'; access_token: string } |
9
- { method: 'private_token'; access_token: string } |
9
+ { method: 'internal'; access_token: string } |
10
10
  { method: 'email'; email: string; password: string } |
11
11
  { method: 'account', username: string, password: string };
12
12
 
@@ -25,6 +25,10 @@ export class SignInError extends Error {
25
25
  * @returns
26
26
  */
27
27
  export const signIn = async (credentials: SignInCredentials, env: RouteInitEnvironment, req: RouteRequest) => {
28
+
29
+ const LOG_ACTION = 'auth.signin';
30
+ const LOG_DETAILS = { ip: req.ip, method: credentials.method };
31
+
28
32
  try {
29
33
  const query = env.authRef.query();
30
34
  let tokenDetails: ReturnType<typeof decodePublicAccessToken>;
@@ -42,7 +46,7 @@ export const signIn = async (credentials: SignInCredentials, env: RouteInitEnvir
42
46
  }
43
47
  break;
44
48
  }
45
- case 'private_token': {
49
+ case 'internal': {
46
50
  // Method used internally: uses the access token extracted from a public access token (see tokenDetails.access_token in above 'token' case)
47
51
  if (typeof credentials.access_token !== 'string') {
48
52
  throw new SignInError('invalid_details', 'sign in request has invalid arguments');
@@ -125,7 +129,9 @@ export const signIn = async (credentials: SignInCredentials, env: RouteInitEnvir
125
129
  await snap.ref.update(updates);
126
130
 
127
131
  // Log history item
128
- env.logRef.push({ action: `signin`, type: credentials.method, [credentials.method]: credentials[credentials.method], ip: req.ip, date: new Date(), success: true });
132
+ if (credentials.method !== 'internal') {
133
+ env.log.event(LOG_ACTION, LOG_DETAILS);
134
+ }
129
135
 
130
136
  // Add to cache
131
137
  env.authCache.set(user.uid, user);
@@ -137,7 +143,7 @@ export const signIn = async (credentials: SignInCredentials, env: RouteInitEnvir
137
143
  }
138
144
  catch (err) {
139
145
  // Log error
140
- env.logRef.push({ action: 'signin', type: credentials.method, [credentials.method]: credentials[credentials.method], success: false, code: err.code || 'unexpected', message: err.code ? null : err.message, ip: req.ip, date: new Date(), ...err.details });
146
+ env.log.error(LOG_ACTION, err.code ?? 'unexpected', LOG_DETAILS, typeof err.code === 'undefined' ? err : null);
141
147
  throw err;
142
148
  }
143
149
  }
package/src/start.ts CHANGED
@@ -38,6 +38,9 @@ if (+getVariable('TXLOG', 0) === 1) {
38
38
  maxAge: +getVariable('TXDAYS', 30)
39
39
  };
40
40
  }
41
+ if (+getVariable('AUTH', 1) === 0) {
42
+ options.authentication = { enabled: false };
43
+ }
41
44
  const server = new AceBaseServer(dbname, options);
42
45
  server.once("ready", () => {
43
46
  server.debug.log(`AceBase server running`);
@@ -5,6 +5,12 @@ import { RouteInitEnvironment } from "../shared/env";
5
5
  import { decodePublicAccessToken } from "../shared/tokens";
6
6
  import { createServer, SocketType } from "./socket.io";
7
7
 
8
+ export class SocketRequestError extends Error {
9
+ constructor(public code: string, message: string) {
10
+ super(message);
11
+ }
12
+ }
13
+
8
14
  export const addWebsocketServer = (env: RouteInitEnvironment) => {
9
15
 
10
16
  // TODO: Allow using uWebSockets.js server instead of Socket.IO
@@ -107,7 +113,7 @@ export const addWebsocketServer = (env: RouteInitEnvironment) => {
107
113
  }
108
114
  });
109
115
 
110
- const acknowlegdeRequest = (socket: SocketType, requestId: string) => {
116
+ const acknowledgeRequest = (socket: SocketType, requestId: string) => {
111
117
  // Send acknowledgement
112
118
  serverManager.send(socket, 'result', {
113
119
  success: true,
@@ -132,14 +138,14 @@ export const addWebsocketServer = (env: RouteInitEnvironment) => {
132
138
  const subscriptionPath = event.data.path;
133
139
  const isSubscribed = () => subscriptionPath in client.subscriptions && client.subscriptions[subscriptionPath].some(s => s.event === event.data.event)
134
140
  if (isSubscribed()) {
135
- return acknowlegdeRequest(event.socket, event.data.req_id);
141
+ return acknowledgeRequest(event.socket, event.data.req_id);
136
142
  }
137
143
 
138
144
  // Get client
139
145
  // const client = clients.get(socket.id);
140
146
 
141
147
  if (!env.rules.userHasAccess(client.user, subscriptionPath, false)) {
142
- env.logRef.push({ action: 'subscribe', success: false, code: 'access_denied', uid: client.user ? client.user.uid : '-', path: subscriptionPath });
148
+ env.log.error('event.subscribe', 'access_denied', { uid: client.user?.uid ?? 'anonymous', path: subscriptionPath });
143
149
  return failRequest(event.socket, event.data.req_id, 'access_denied');
144
150
  }
145
151
 
@@ -183,7 +189,7 @@ export const addWebsocketServer = (env: RouteInitEnvironment) => {
183
189
 
184
190
  env.db.api.subscribe(subscriptionPath, event.data.event, callback);
185
191
 
186
- acknowlegdeRequest(event.socket, event.data.req_id);
192
+ acknowledgeRequest(event.socket, event.data.req_id);
187
193
  });
188
194
 
189
195
  serverManager.on('unsubscribe', event => {
@@ -197,7 +203,7 @@ export const addWebsocketServer = (env: RouteInitEnvironment) => {
197
203
  let pathSubs = client.subscriptions[event.data.path];
198
204
  if (!pathSubs) {
199
205
  // We have no knowledge of any active subscriptions on this path
200
- return acknowlegdeRequest(event.socket, event.data.req_id);
206
+ return acknowledgeRequest(event.socket, event.data.req_id);
201
207
  }
202
208
  let remove = pathSubs;
203
209
  if (event.data.event) {
@@ -214,7 +220,7 @@ export const addWebsocketServer = (env: RouteInitEnvironment) => {
214
220
  // No subscriptions left on this path, remove the path entry
215
221
  delete client.subscriptions[event.data.path];
216
222
  }
217
- return acknowlegdeRequest(event.socket, event.data.req_id);
223
+ return acknowledgeRequest(event.socket, event.data.req_id);
218
224
  });
219
225
 
220
226
  serverManager.on('query-unsubscribe', event => {
@@ -226,7 +232,7 @@ export const addWebsocketServer = (env: RouteInitEnvironment) => {
226
232
  // const client = clients.get(socket.id);
227
233
  delete client.realtimeQueries[event.data.query_id];
228
234
 
229
- acknowlegdeRequest(event.socket, event.data.req_id);
235
+ acknowledgeRequest(event.socket, event.data.req_id);
230
236
  });
231
237
 
232
238
  const TRANSACTION_TIMEOUT_MS = 10000; // 10s to finish a started transaction
@@ -234,7 +240,10 @@ export const addWebsocketServer = (env: RouteInitEnvironment) => {
234
240
  serverManager.on('transaction-start', event => {
235
241
  // Start transaction
236
242
  const client = getClientBySocketId(event.socket_id, 'transaction-start');
237
- if (!client) { return; }
243
+ if (!client || !event.data) { return; }
244
+
245
+ const LOG_ACTION = 'socket.transaction.start';
246
+ const LOG_DETAILS = { ip: event.socket.conn.remoteAddress, uid: client.user?.uid ?? null, path: event.data.path };
238
247
 
239
248
  env.debug.verbose(`Client ${event.socket_id} is sending transaction start request on path "${event.data.path}"`);
240
249
  const data = event.data;
@@ -247,12 +256,15 @@ export const addWebsocketServer = (env: RouteInitEnvironment) => {
247
256
  timeout: setTimeout(() => {
248
257
  delete client.transactions[tx.id];
249
258
  tx.finish(); // Finish without value cancels the transaction
259
+ env.log.error(LOG_ACTION, 'timeout', LOG_DETAILS);
250
260
  serverManager.send(event.socket, 'tx_error', { id: tx.id, reason: 'timeout' });
251
261
  }, TRANSACTION_TIMEOUT_MS)
252
262
  };
253
263
 
254
- if (!env.rules.userHasAccess(client.user, data.path, true)) {
264
+ const access = env.rules.userHasAccess(client.user, data.path, true);
265
+ if (!access.allow) {
255
266
  // throw new AccessDeniedError(`access_denied`);
267
+ env.log.error(LOG_ACTION, 'unauthorized', { ...LOG_DETAILS, rule_code: access.code, rule_path: access.rulePath ?? null }, access.details);
256
268
  return serverManager.send(event.socket, 'tx_error', { id: tx.id, reason: 'access_denied' });
257
269
  }
258
270
 
@@ -282,38 +294,43 @@ export const addWebsocketServer = (env: RouteInitEnvironment) => {
282
294
  serverManager.on('transaction-finish', async event => {
283
295
  // Finish transaction
284
296
  const client = getClientBySocketId(event.socket_id, 'transaction-finish');
285
- if (!client) { return; }
297
+ if (!client || !event.data) { return; }
298
+
299
+ const LOG_ACTION = 'socket.transaction.finish';
300
+ const LOG_DETAILS = { ip: event.socket.conn.remoteAddress, uid: client.user?.uid ?? null, path: event.data.path };
286
301
 
287
302
  const data = event.data;
288
303
  const tx = client.transactions[data.id];
289
304
 
290
305
  try {
291
306
  if (!tx || data.path !== tx.path) {
292
- throw new Error('transaction_not_found');
307
+ env.log.error(LOG_ACTION, tx ? 'wrong_path' : 'not_found', { ...LOG_DETAILS, id: data.id, tx_path: tx?.path ?? null });
308
+ throw new SocketRequestError('transaction_not_found', 'Transaction not found');
293
309
  }
294
310
 
295
311
  clearTimeout(tx.timeout);
296
312
  delete client.transactions[data.id];
297
313
 
298
- if (!env.rules.userHasAccess(client.user, data.path, true)) {
299
- throw new Error('access_denied');
314
+ const access = env.rules.userHasAccess(client.user, data.path, true);
315
+ if (!access.allow) {
316
+ env.log.error(LOG_ACTION, 'unauthorized', { ...LOG_DETAILS, rule_code: access.code, rule_path: access.rulePath ?? null }, access.details);
317
+ throw new SocketRequestError('access_denied', 'Access denied');
300
318
  }
301
319
 
302
320
  const newValue = 'val' in data.value ? Transport.deserialize(data.value) : undefined;
303
- try {
304
- const { cursor } = await tx.finish(newValue);
305
- env.debug.verbose(`Transaction ${tx.id} finished`);
306
- serverManager.send(event.socket, 'tx_completed', { id: tx.id, context: { cursor } });
307
- }
308
- catch (err) {
309
- serverManager.send(event.socket, 'tx_error', { id: tx.id, reason: err.message });
310
- }
321
+ const { cursor } = await tx.finish(newValue);
322
+ env.debug.verbose(`Transaction ${tx.id} finished`);
323
+ serverManager.send(event.socket, 'tx_completed', { id: tx.id, context: { cursor } });
311
324
  }
312
325
  catch (err) {
313
- serverManager.send(event.socket, 'tx_error', { id: tx.id, reason: err.message, data });
326
+ if (!(err instanceof SocketRequestError)) {
327
+ // Other errors have been logged already
328
+ env.log.error(LOG_ACTION, 'unexpected', LOG_DETAILS, err);
329
+ }
330
+ serverManager.send(event.socket, 'tx_error', { id: tx.id, reason: err.code ?? err.message, data });
314
331
  tx.finish(); // Finish with undefined, canceling the transaction
315
332
  }
316
-
333
+
317
334
  });
318
335
 
319
336
  return serverManager;