acebase-server 1.16.2 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (252) hide show
  1. package/README.md +180 -10
  2. package/bin/acebase-server.js +8 -0
  3. package/build-vars.js +2 -1
  4. package/dist/cjs/auth.js +88 -88
  5. package/dist/cjs/cluster.js +6 -56
  6. package/dist/cjs/index.d.ts +1 -1
  7. package/dist/cjs/index.js +24 -24
  8. package/dist/cjs/logger.js +73 -73
  9. package/dist/cjs/middleware/404.js +14 -14
  10. package/dist/cjs/middleware/admin-only.js +28 -28
  11. package/dist/cjs/middleware/cache.js +14 -14
  12. package/dist/cjs/middleware/connection.js +49 -49
  13. package/dist/cjs/middleware/context.js +20 -20
  14. package/dist/cjs/middleware/cors.js +50 -50
  15. package/dist/cjs/middleware/swagger.js +17 -17
  16. package/dist/cjs/middleware/user.js +57 -57
  17. package/dist/cjs/oauth-providers/dropbox.js +109 -109
  18. package/dist/cjs/oauth-providers/facebook.js +85 -85
  19. package/dist/cjs/oauth-providers/google.js +119 -119
  20. package/dist/cjs/oauth-providers/index.js +26 -26
  21. package/dist/cjs/oauth-providers/instagram.js +80 -80
  22. package/dist/cjs/oauth-providers/oauth-provider.js +20 -20
  23. package/dist/cjs/oauth-providers/spotify.js +113 -113
  24. package/dist/cjs/routes/auth-change-password.js +87 -87
  25. package/dist/cjs/routes/auth-delete.js +52 -52
  26. package/dist/cjs/routes/auth-forgot-password.js +77 -77
  27. package/dist/cjs/routes/auth-reset-password.js +97 -97
  28. package/dist/cjs/routes/auth-signin.js +46 -46
  29. package/dist/cjs/routes/auth-signout.js +61 -61
  30. package/dist/cjs/routes/auth-signup.js +142 -142
  31. package/dist/cjs/routes/auth-state.js +25 -25
  32. package/dist/cjs/routes/auth-update.js +131 -131
  33. package/dist/cjs/routes/auth-verify-email.js +71 -71
  34. package/dist/cjs/routes/auth.js +57 -54
  35. package/dist/cjs/routes/data-exists.js +33 -33
  36. package/dist/cjs/routes/data-export.js +48 -48
  37. package/dist/cjs/routes/data-get.js +70 -66
  38. package/dist/cjs/routes/data-import.js +54 -54
  39. package/dist/cjs/routes/data-index-create.js +42 -42
  40. package/dist/cjs/routes/data-index-delete.js +33 -33
  41. package/dist/cjs/routes/data-index-list.js +31 -31
  42. package/dist/cjs/routes/data-query.js +80 -70
  43. package/dist/cjs/routes/data-reflect.js +97 -86
  44. package/dist/cjs/routes/data-schema-get.js +36 -36
  45. package/dist/cjs/routes/data-schema-set.js +30 -30
  46. package/dist/cjs/routes/data-schema-test.js +43 -43
  47. package/dist/cjs/routes/data-schemas-list.js +32 -32
  48. package/dist/cjs/routes/data-set.js +85 -75
  49. package/dist/cjs/routes/data-sync-changes.js +81 -67
  50. package/dist/cjs/routes/data-sync-mutations.js +81 -67
  51. package/dist/cjs/routes/data-transaction.js +159 -139
  52. package/dist/cjs/routes/data-update.js +86 -75
  53. package/dist/cjs/routes/data.js +62 -62
  54. package/dist/cjs/routes/docs.js +258 -251
  55. package/dist/cjs/routes/meta-info.js +63 -63
  56. package/dist/cjs/routes/meta-logs.js +49 -49
  57. package/dist/cjs/routes/meta-ping.js +11 -11
  58. package/dist/cjs/routes/meta-stats.js +27 -27
  59. package/dist/cjs/routes/meta.js +19 -19
  60. package/dist/cjs/routes/oauth2-init.js +54 -54
  61. package/dist/cjs/routes/oauth2-refresh.js +42 -42
  62. package/dist/cjs/routes/oauth2-signin.js +265 -265
  63. package/dist/cjs/routes/webmanager.js +26 -26
  64. package/dist/cjs/rules.js +380 -167
  65. package/dist/cjs/sandbox.js +28 -0
  66. package/dist/cjs/schema/user.js +24 -24
  67. package/dist/cjs/server.js +410 -407
  68. package/dist/cjs/settings/email.js +2 -2
  69. package/dist/cjs/settings/index.js +175 -172
  70. package/dist/cjs/shared/clients.js +26 -26
  71. package/dist/cjs/shared/email.js +2 -2
  72. package/dist/cjs/shared/env.js +2 -2
  73. package/dist/cjs/shared/error.js +33 -33
  74. package/dist/cjs/shared/http.js +28 -28
  75. package/dist/cjs/shared/password.js +45 -45
  76. package/dist/cjs/shared/rootpath.js +16 -16
  77. package/dist/cjs/shared/signin.js +143 -143
  78. package/dist/cjs/shared/simple-fetch.js +76 -76
  79. package/dist/cjs/shared/tokens.js +79 -79
  80. package/dist/cjs/shared/validate.js +61 -61
  81. package/dist/cjs/start.js +119 -53
  82. package/dist/cjs/test.js +10 -10
  83. package/dist/cjs/websocket/index.js +331 -319
  84. package/dist/cjs/websocket/manager.js +15 -15
  85. package/dist/cjs/websocket/socket.io.js +76 -76
  86. package/dist/esm/auth.js +75 -75
  87. package/dist/esm/cluster.js +6 -54
  88. package/dist/esm/index.d.ts +1 -1
  89. package/dist/esm/index.js +4 -4
  90. package/dist/esm/logger.js +51 -51
  91. package/dist/esm/middleware/404.js +10 -10
  92. package/dist/esm/middleware/admin-only.js +24 -24
  93. package/dist/esm/middleware/cache.js +10 -10
  94. package/dist/esm/middleware/connection.js +45 -45
  95. package/dist/esm/middleware/context.js +16 -16
  96. package/dist/esm/middleware/cors.js +44 -44
  97. package/dist/esm/middleware/swagger.js +13 -13
  98. package/dist/esm/middleware/user.js +44 -44
  99. package/dist/esm/oauth-providers/dropbox.js +90 -90
  100. package/dist/esm/oauth-providers/facebook.js +66 -66
  101. package/dist/esm/oauth-providers/google.js +96 -96
  102. package/dist/esm/oauth-providers/index.js +18 -18
  103. package/dist/esm/oauth-providers/instagram.js +61 -61
  104. package/dist/esm/oauth-providers/oauth-provider.js +16 -16
  105. package/dist/esm/oauth-providers/spotify.js +92 -92
  106. package/dist/esm/routes/auth-change-password.js +72 -72
  107. package/dist/esm/routes/auth-delete.js +37 -37
  108. package/dist/esm/routes/auth-forgot-password.js +62 -62
  109. package/dist/esm/routes/auth-reset-password.js +81 -81
  110. package/dist/esm/routes/auth-signin.js +33 -33
  111. package/dist/esm/routes/auth-signout.js +47 -47
  112. package/dist/esm/routes/auth-signup.js +127 -127
  113. package/dist/esm/routes/auth-state.js +12 -12
  114. package/dist/esm/routes/auth-update.js +116 -116
  115. package/dist/esm/routes/auth-verify-email.js +57 -57
  116. package/dist/esm/routes/auth.js +53 -50
  117. package/dist/esm/routes/data-exists.js +20 -20
  118. package/dist/esm/routes/data-export.js +35 -35
  119. package/dist/esm/routes/data-get.js +56 -52
  120. package/dist/esm/routes/data-import.js +41 -41
  121. package/dist/esm/routes/data-index-create.js +28 -28
  122. package/dist/esm/routes/data-index-delete.js +20 -20
  123. package/dist/esm/routes/data-index-list.js +18 -18
  124. package/dist/esm/routes/data-query.js +66 -56
  125. package/dist/esm/routes/data-reflect.js +83 -72
  126. package/dist/esm/routes/data-schema-get.js +23 -23
  127. package/dist/esm/routes/data-schema-set.js +17 -17
  128. package/dist/esm/routes/data-schema-test.js +29 -29
  129. package/dist/esm/routes/data-schemas-list.js +19 -19
  130. package/dist/esm/routes/data-set.js +70 -60
  131. package/dist/esm/routes/data-sync-changes.js +67 -53
  132. package/dist/esm/routes/data-sync-mutations.js +67 -53
  133. package/dist/esm/routes/data-transaction.js +142 -123
  134. package/dist/esm/routes/data-update.js +71 -60
  135. package/dist/esm/routes/data.js +58 -58
  136. package/dist/esm/routes/docs.js +252 -245
  137. package/dist/esm/routes/meta-info.js +59 -59
  138. package/dist/esm/routes/meta-logs.js +35 -35
  139. package/dist/esm/routes/meta-ping.js +7 -7
  140. package/dist/esm/routes/meta-stats.js +14 -14
  141. package/dist/esm/routes/meta.js +15 -15
  142. package/dist/esm/routes/oauth2-init.js +41 -41
  143. package/dist/esm/routes/oauth2-refresh.js +29 -29
  144. package/dist/esm/routes/oauth2-signin.js +251 -251
  145. package/dist/esm/routes/webmanager.js +22 -22
  146. package/dist/esm/rules.js +374 -163
  147. package/dist/esm/sandbox.js +12 -0
  148. package/dist/esm/schema/user.js +19 -19
  149. package/dist/esm/server.js +395 -387
  150. package/dist/esm/settings/email.js +1 -1
  151. package/dist/esm/settings/index.js +168 -165
  152. package/dist/esm/shared/clients.js +22 -22
  153. package/dist/esm/shared/email.js +1 -1
  154. package/dist/esm/shared/env.js +1 -1
  155. package/dist/esm/shared/error.js +25 -25
  156. package/dist/esm/shared/http.js +22 -22
  157. package/dist/esm/shared/password.js +38 -38
  158. package/dist/esm/shared/rootpath.js +13 -13
  159. package/dist/esm/shared/signin.js +128 -128
  160. package/dist/esm/shared/simple-fetch.js +59 -59
  161. package/dist/esm/shared/tokens.js +72 -72
  162. package/dist/esm/shared/validate.js +41 -41
  163. package/dist/esm/start.js +116 -50
  164. package/dist/esm/test.js +8 -8
  165. package/dist/esm/websocket/index.js +313 -302
  166. package/dist/esm/websocket/manager.js +11 -11
  167. package/dist/esm/websocket/socket.io.js +71 -71
  168. package/dist/types/auth.d.ts +3 -3
  169. package/dist/types/cluster.d.ts +6 -1
  170. package/dist/types/index.d.ts +4 -4
  171. package/dist/types/logger.d.ts +35 -35
  172. package/dist/types/middleware/404.d.ts +7 -7
  173. package/dist/types/middleware/admin-only.d.ts +19 -19
  174. package/dist/types/middleware/cache.d.ts +3 -3
  175. package/dist/types/middleware/connection.d.ts +7 -7
  176. package/dist/types/middleware/context.d.ts +3 -3
  177. package/dist/types/middleware/cors.d.ts +25 -25
  178. package/dist/types/middleware/swagger.d.ts +3 -3
  179. package/dist/types/middleware/user.d.ts +2 -2
  180. package/dist/types/oauth-providers/dropbox.d.ts +52 -52
  181. package/dist/types/oauth-providers/facebook.d.ts +41 -41
  182. package/dist/types/oauth-providers/google.d.ts +43 -43
  183. package/dist/types/oauth-providers/index.d.ts +10 -10
  184. package/dist/types/oauth-providers/instagram.d.ts +50 -50
  185. package/dist/types/oauth-providers/oauth-provider.d.ts +74 -74
  186. package/dist/types/oauth-providers/spotify.d.ts +53 -53
  187. package/dist/types/routes/auth-change-password.d.ts +20 -20
  188. package/dist/types/routes/auth-delete.d.ts +16 -16
  189. package/dist/types/routes/auth-forgot-password.d.ts +16 -16
  190. package/dist/types/routes/auth-reset-password.d.ts +23 -23
  191. package/dist/types/routes/auth-signin.d.ts +24 -24
  192. package/dist/types/routes/auth-signout.d.ts +14 -14
  193. package/dist/types/routes/auth-signup.d.ts +32 -32
  194. package/dist/types/routes/auth-state.d.ts +13 -13
  195. package/dist/types/routes/auth-update.d.ts +33 -33
  196. package/dist/types/routes/auth-verify-email.d.ts +21 -21
  197. package/dist/types/routes/auth.d.ts +6 -6
  198. package/dist/types/routes/data-exists.d.ts +9 -9
  199. package/dist/types/routes/data-export.d.ts +10 -10
  200. package/dist/types/routes/data-get.d.ts +14 -14
  201. package/dist/types/routes/data-import.d.ts +13 -13
  202. package/dist/types/routes/data-index-create.d.ts +51 -51
  203. package/dist/types/routes/data-index-delete.d.ts +17 -17
  204. package/dist/types/routes/data-index-list.d.ts +21 -21
  205. package/dist/types/routes/data-query.d.ts +49 -49
  206. package/dist/types/routes/data-reflect.d.ts +29 -29
  207. package/dist/types/routes/data-schema-get.d.ts +11 -11
  208. package/dist/types/routes/data-schema-set.d.ts +20 -19
  209. package/dist/types/routes/data-schema-test.d.ts +19 -19
  210. package/dist/types/routes/data-schemas-list.d.ts +11 -11
  211. package/dist/types/routes/data-set.d.ts +27 -27
  212. package/dist/types/routes/data-sync-changes.d.ts +25 -28
  213. package/dist/types/routes/data-sync-mutations.d.ts +25 -28
  214. package/dist/types/routes/data-transaction.d.ts +34 -34
  215. package/dist/types/routes/data-update.d.ts +27 -27
  216. package/dist/types/routes/data.d.ts +3 -3
  217. package/dist/types/routes/docs.d.ts +3 -3
  218. package/dist/types/routes/meta-info.d.ts +11 -11
  219. package/dist/types/routes/meta-logs.d.ts +20 -20
  220. package/dist/types/routes/meta-ping.d.ts +7 -7
  221. package/dist/types/routes/meta-stats.d.ts +13 -13
  222. package/dist/types/routes/meta.d.ts +3 -3
  223. package/dist/types/routes/oauth2-init.d.ts +13 -13
  224. package/dist/types/routes/oauth2-refresh.d.ts +17 -17
  225. package/dist/types/routes/oauth2-signin.d.ts +15 -15
  226. package/dist/types/routes/webmanager.d.ts +3 -3
  227. package/dist/types/rules.d.ts +73 -34
  228. package/dist/types/sandbox.d.ts +3 -0
  229. package/dist/types/schema/user.d.ts +85 -85
  230. package/dist/types/server.d.ts +117 -111
  231. package/dist/types/settings/email.d.ts +14 -14
  232. package/dist/types/settings/index.d.ts +195 -187
  233. package/dist/types/shared/clients.d.ts +46 -46
  234. package/dist/types/shared/email.d.ts +34 -34
  235. package/dist/types/shared/env.d.ts +47 -44
  236. package/dist/types/shared/error.d.ts +15 -15
  237. package/dist/types/shared/http.d.ts +22 -21
  238. package/dist/types/shared/password.d.ts +19 -19
  239. package/dist/types/shared/rootpath.d.ts +2 -2
  240. package/dist/types/shared/signin.d.ts +31 -31
  241. package/dist/types/shared/simple-fetch.d.ts +21 -21
  242. package/dist/types/shared/tokens.d.ts +24 -24
  243. package/dist/types/shared/validate.d.ts +22 -22
  244. package/dist/types/start.d.ts +1 -1
  245. package/dist/types/test.d.ts +1 -1
  246. package/dist/types/websocket/index.d.ts +6 -6
  247. package/dist/types/websocket/manager.d.ts +99 -99
  248. package/dist/types/websocket/socket.io.d.ts +10 -10
  249. package/package.json +7 -4
  250. package/src/routes/data-schema-set.yaml +4 -0
  251. package/src/routes/data-set.yaml +5 -5
  252. package/src/routes/data-update.yaml +4 -4
@@ -1,129 +1,129 @@
1
- import { ID } from 'acebase-core';
2
- import { createPasswordHash, getOldPasswordHash, getPasswordHash } from './password.js';
3
- import { decodePublicAccessToken } from './tokens.js';
4
- export class SignInError extends Error {
5
- constructor(code, message, details = {}) {
6
- super(message);
7
- this.code = code;
8
- this.details = details;
9
- }
10
- }
11
- /**
12
- * 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.
13
- * Throws a `SignInError` if sign in fails for a known reason.
14
- * @param credentials credentials to sign in the user with
15
- * @param env environment state
16
- * @param req current http request
17
- * @returns
18
- */
19
- export const signIn = async (credentials, env, req) => {
20
- const LOG_ACTION = 'auth.signin';
21
- const LOG_DETAILS = { ip: req.ip, method: credentials.method };
22
- try {
23
- const query = env.authRef.query();
24
- let tokenDetails;
25
- switch (credentials.method) {
26
- case 'token': {
27
- if (typeof credentials.access_token !== 'string') {
28
- throw new SignInError('invalid_details', 'sign in request has invalid arguments');
29
- }
30
- try {
31
- tokenDetails = decodePublicAccessToken(credentials.access_token, env.tokenSalt);
32
- query.filter('access_token', '==', tokenDetails.access_token);
33
- }
34
- catch (err) {
35
- throw new SignInError('invalid_token', err.message);
36
- }
37
- break;
38
- }
39
- case 'internal': {
40
- // Method used internally: uses the access token extracted from a public access token (see tokenDetails.access_token in above 'token' case)
41
- if (typeof credentials.access_token !== 'string') {
42
- throw new SignInError('invalid_details', 'sign in request has invalid arguments');
43
- }
44
- query.filter('access_token', '==', credentials.access_token);
45
- break;
46
- }
47
- case 'email': {
48
- if (typeof credentials.email !== 'string' || typeof credentials.password !== 'string') {
49
- throw new SignInError('invalid_details', 'sign in request has invalid arguments');
50
- }
51
- query.filter('email', '==', credentials.email);
52
- break;
53
- }
54
- case 'account': {
55
- if (typeof credentials.username !== 'string' || typeof credentials.password !== 'string') {
56
- throw new SignInError('invalid_details', 'sign in request has invalid arguments');
57
- }
58
- query.filter('username', '==', credentials.username);
59
- break;
60
- }
61
- default: {
62
- throw new SignInError('invalid_method', `Unsupported sign in method ${credentials.method}`);
63
- }
64
- }
65
- const snaps = await query.get();
66
- if (snaps.length === 0) {
67
- throw new SignInError('not_found', `account not found`);
68
- }
69
- else if (snaps.length > 1) {
70
- throw new SignInError('duplicate', `${snaps.length} users found with the same ${credentials.method}. Contact your database administrator`, { count: snaps.length });
71
- }
72
- const snap = snaps[0];
73
- const user = snap.val();
74
- user.uid = snap.key;
75
- if (user.is_disabled === true) {
76
- throw new SignInError('account_disabled', 'Your account has been disabled. Contact your database administrator');
77
- }
78
- if (credentials.method === 'token' && tokenDetails.uid !== user.uid) {
79
- throw new SignInError('token_mismatch', 'Sign in again');
80
- }
81
- if (credentials.method === 'account' || credentials.method === 'email') {
82
- // Check password
83
- const hash = user.password_salt ? getPasswordHash(credentials.password, user.password_salt) : getOldPasswordHash(credentials.password);
84
- if (user.password !== hash) {
85
- throw new SignInError('wrong_password', 'Incorrect password');
86
- }
87
- }
88
- // Keep track of properties to update, both in db and in our object
89
- const updates = {
90
- // Update prev / last sign in stats
91
- prev_signin: user.last_signin,
92
- prev_signin_ip: user.last_signin_ip,
93
- last_signin: new Date(),
94
- last_signin_ip: req.ip,
95
- };
96
- if ('password' in credentials) {
97
- if (!user.password_salt) {
98
- // OLD md5 password hash, convert to new salted hash
99
- const pwd = createPasswordHash(credentials.password);
100
- updates.password = pwd.hash;
101
- updates.password_salt = pwd.salt;
102
- }
103
- if (!user.access_token) {
104
- // Generate access token
105
- updates.access_token = ID.generate();
106
- updates.access_token_created = new Date();
107
- }
108
- }
109
- // Update user object
110
- Object.assign(user, updates);
111
- // Update db
112
- await snap.ref.update(updates);
113
- // Log history item
114
- if (credentials.method !== 'internal') {
115
- env.log.event(LOG_ACTION, LOG_DETAILS);
116
- }
117
- // Add to cache
118
- env.authCache.set(user.uid, user);
119
- // Bind user to current request
120
- req.user = user;
121
- return user;
122
- }
123
- catch (err) {
124
- // Log error
125
- env.log.error(LOG_ACTION, err.code ?? 'unexpected', LOG_DETAILS, typeof err.code === 'undefined' ? err : null);
126
- throw err;
127
- }
128
- };
1
+ import { ID } from 'acebase-core';
2
+ import { createPasswordHash, getOldPasswordHash, getPasswordHash } from './password.js';
3
+ import { decodePublicAccessToken } from './tokens.js';
4
+ export class SignInError extends Error {
5
+ constructor(code, message, details = {}) {
6
+ super(message);
7
+ this.code = code;
8
+ this.details = details;
9
+ }
10
+ }
11
+ /**
12
+ * 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.
13
+ * Throws a `SignInError` if sign in fails for a known reason.
14
+ * @param credentials credentials to sign in the user with
15
+ * @param env environment state
16
+ * @param req current http request
17
+ * @returns
18
+ */
19
+ export const signIn = async (credentials, env, req) => {
20
+ const LOG_ACTION = 'auth.signin';
21
+ const LOG_DETAILS = { ip: req.ip, method: credentials.method };
22
+ try {
23
+ const query = env.authRef.query();
24
+ let tokenDetails;
25
+ switch (credentials.method) {
26
+ case 'token': {
27
+ if (typeof credentials.access_token !== 'string') {
28
+ throw new SignInError('invalid_details', 'sign in request has invalid arguments');
29
+ }
30
+ try {
31
+ tokenDetails = decodePublicAccessToken(credentials.access_token, env.tokenSalt);
32
+ query.filter('access_token', '==', tokenDetails.access_token);
33
+ }
34
+ catch (err) {
35
+ throw new SignInError('invalid_token', err.message);
36
+ }
37
+ break;
38
+ }
39
+ case 'internal': {
40
+ // Method used internally: uses the access token extracted from a public access token (see tokenDetails.access_token in above 'token' case)
41
+ if (typeof credentials.access_token !== 'string') {
42
+ throw new SignInError('invalid_details', 'sign in request has invalid arguments');
43
+ }
44
+ query.filter('access_token', '==', credentials.access_token);
45
+ break;
46
+ }
47
+ case 'email': {
48
+ if (typeof credentials.email !== 'string' || typeof credentials.password !== 'string') {
49
+ throw new SignInError('invalid_details', 'sign in request has invalid arguments');
50
+ }
51
+ query.filter('email', '==', credentials.email);
52
+ break;
53
+ }
54
+ case 'account': {
55
+ if (typeof credentials.username !== 'string' || typeof credentials.password !== 'string') {
56
+ throw new SignInError('invalid_details', 'sign in request has invalid arguments');
57
+ }
58
+ query.filter('username', '==', credentials.username);
59
+ break;
60
+ }
61
+ default: {
62
+ throw new SignInError('invalid_method', `Unsupported sign in method ${credentials.method}`);
63
+ }
64
+ }
65
+ const snaps = await query.get();
66
+ if (snaps.length === 0) {
67
+ throw new SignInError('not_found', `account not found`);
68
+ }
69
+ else if (snaps.length > 1) {
70
+ throw new SignInError('duplicate', `${snaps.length} users found with the same ${credentials.method}. Contact your database administrator`, { count: snaps.length });
71
+ }
72
+ const snap = snaps[0];
73
+ const user = snap.val();
74
+ user.uid = snap.key;
75
+ if (user.is_disabled === true) {
76
+ throw new SignInError('account_disabled', 'Your account has been disabled. Contact your database administrator');
77
+ }
78
+ if (credentials.method === 'token' && tokenDetails.uid !== user.uid) {
79
+ throw new SignInError('token_mismatch', 'Sign in again');
80
+ }
81
+ if (credentials.method === 'account' || credentials.method === 'email') {
82
+ // Check password
83
+ const hash = user.password_salt ? getPasswordHash(credentials.password, user.password_salt) : getOldPasswordHash(credentials.password);
84
+ if (user.password !== hash) {
85
+ throw new SignInError('wrong_password', 'Incorrect password');
86
+ }
87
+ }
88
+ // Keep track of properties to update, both in db and in our object
89
+ const updates = {
90
+ // Update prev / last sign in stats
91
+ prev_signin: user.last_signin,
92
+ prev_signin_ip: user.last_signin_ip,
93
+ last_signin: new Date(),
94
+ last_signin_ip: req.ip,
95
+ };
96
+ if ('password' in credentials) {
97
+ if (!user.password_salt) {
98
+ // OLD md5 password hash, convert to new salted hash
99
+ const pwd = createPasswordHash(credentials.password);
100
+ updates.password = pwd.hash;
101
+ updates.password_salt = pwd.salt;
102
+ }
103
+ if (!user.access_token) {
104
+ // Generate access token
105
+ updates.access_token = ID.generate();
106
+ updates.access_token_created = new Date();
107
+ }
108
+ }
109
+ // Update user object
110
+ Object.assign(user, updates);
111
+ // Update db
112
+ await snap.ref.update(updates);
113
+ // Log history item
114
+ if (credentials.method !== 'internal') {
115
+ env.log.event(LOG_ACTION, LOG_DETAILS);
116
+ }
117
+ // Add to cache
118
+ env.authCache.set(user.uid, user);
119
+ // Bind user to current request
120
+ req.user = user;
121
+ return user;
122
+ }
123
+ catch (err) {
124
+ // Log error
125
+ env.log.error(LOG_ACTION, err.code ?? 'unexpected', LOG_DETAILS, typeof err.code === 'undefined' ? err : null);
126
+ throw err;
127
+ }
128
+ };
129
129
  //# sourceMappingURL=signin.js.map
@@ -1,60 +1,60 @@
1
- import { request } from 'https';
2
- /**
3
- * Very lightweight custom fetch implementation to avoid additional dependencies
4
- * @param url
5
- * @param options
6
- */
7
- export function fetch(url, options) {
8
- return new Promise((resolve, reject) => {
9
- const method = options?.method || 'GET';
10
- const headers = options?.headers;
11
- const req = request(url, { method, headers }, res => {
12
- // res.setEncoding('binary'); // will result in strings!!!!
13
- const ready = new Promise((resolve, reject) => {
14
- const chunks = [];
15
- res.on('data', data => {
16
- chunks.push(data);
17
- });
18
- res.on('end', () => {
19
- const buffer = Buffer.concat(chunks);
20
- resolve(buffer);
21
- });
22
- res.on('error', (err) => {
23
- reject(err);
24
- });
25
- });
26
- const response = {
27
- get status() { return res.statusCode; },
28
- get headers() {
29
- return {
30
- get(name) {
31
- const val = res.headers[name.toLowerCase()];
32
- if (val instanceof Array) {
33
- return val.join(', ');
34
- }
35
- return val;
36
- },
37
- };
38
- },
39
- async text() {
40
- const buffer = await ready;
41
- return buffer.toString('utf8');
42
- },
43
- json() {
44
- // return Promise.resolve(JSON.parse(body));
45
- return this.text().then(json => JSON.parse(json));
46
- },
47
- async arrayBuffer() {
48
- const data = await ready;
49
- const arrayBuffer = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
50
- return arrayBuffer;
51
- },
52
- };
53
- resolve(response);
54
- });
55
- req.on('error', reject);
56
- options?.body && req.write(options.body, 'utf8');
57
- req.end();
58
- });
59
- }
1
+ import { request } from 'https';
2
+ /**
3
+ * Very lightweight custom fetch implementation to avoid additional dependencies
4
+ * @param url
5
+ * @param options
6
+ */
7
+ export function fetch(url, options) {
8
+ return new Promise((resolve, reject) => {
9
+ const method = options?.method || 'GET';
10
+ const headers = options?.headers;
11
+ const req = request(url, { method, headers }, res => {
12
+ // res.setEncoding('binary'); // will result in strings!!!!
13
+ const ready = new Promise((resolve, reject) => {
14
+ const chunks = [];
15
+ res.on('data', data => {
16
+ chunks.push(data);
17
+ });
18
+ res.on('end', () => {
19
+ const buffer = Buffer.concat(chunks);
20
+ resolve(buffer);
21
+ });
22
+ res.on('error', (err) => {
23
+ reject(err);
24
+ });
25
+ });
26
+ const response = {
27
+ get status() { return res.statusCode; },
28
+ get headers() {
29
+ return {
30
+ get(name) {
31
+ const val = res.headers[name.toLowerCase()];
32
+ if (val instanceof Array) {
33
+ return val.join(', ');
34
+ }
35
+ return val;
36
+ },
37
+ };
38
+ },
39
+ async text() {
40
+ const buffer = await ready;
41
+ return buffer.toString('utf8');
42
+ },
43
+ json() {
44
+ // return Promise.resolve(JSON.parse(body));
45
+ return this.text().then(json => JSON.parse(json));
46
+ },
47
+ async arrayBuffer() {
48
+ const data = await ready;
49
+ const arrayBuffer = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
50
+ return arrayBuffer;
51
+ },
52
+ };
53
+ resolve(response);
54
+ });
55
+ req.on('error', reject);
56
+ options?.body && req.write(options.body, 'utf8');
57
+ req.end();
58
+ });
59
+ }
60
60
  //# sourceMappingURL=simple-fetch.js.map
@@ -1,73 +1,73 @@
1
- import * as crypto from 'crypto';
2
- export const createPublicAccessToken = (uid, ip, dbToken, password) => {
3
- const obj = {
4
- t: dbToken,
5
- c: Date.now(),
6
- u: uid,
7
- i: ip,
8
- };
9
- // let str = JSON.stringify(obj);
10
- // str = Buffer.from(str).toString('base64');
11
- // return 'a' + str; // version a
12
- return 'b' + createSignedPublicToken(obj, password);
13
- };
14
- export const decodePublicAccessToken = (accessToken, password) => {
15
- let details;
16
- if (accessToken[0] === 'b') {
17
- // New signed version
18
- const obj = parseSignedPublicToken(accessToken.slice(1), password);
19
- details = {
20
- access_token: obj.t,
21
- uid: obj.u,
22
- created: obj.c,
23
- ip: obj.i,
24
- };
25
- }
26
- else if (accessToken[0] === 'a') {
27
- // Old insecure version, previously allowed until August 1, 2020.
28
- throw new Error('Old token version not allowed');
29
- }
30
- if (!details || !details.access_token || !details.uid || !details.created || !details.ip) {
31
- throw new Error('Invalid token');
32
- }
33
- return details;
34
- };
35
- const getSignature = (content, salt) => {
36
- // Use fast md5 with salt to sign with. Large salt recommended!!
37
- return crypto.createHash('md5').update(salt + content).digest('hex');
38
- };
39
- /**
40
- * Sign objects with an md5 hash. An attacker might base4 decode it and see the content and generated checksum hash,
41
- * but will need to guess the password used to generate the hash to manipulate it. This is not impossible but will take
42
- * a very long time when using a large password
43
- * @param obj data object to sign
44
- * @param password password to use as salt for the generated md5 hash
45
- * @returns base64 encoded signed token
46
- */
47
- export const createSignedPublicToken = (obj, password) => {
48
- const str = JSON.stringify(obj);
49
- const checksum = getSignature(str, password);
50
- return Buffer.from(JSON.stringify({ v: 1, cs: checksum, d: str })).toString('base64');
51
- };
52
- /**
53
- * Parses and validates a signed token that was previouslt generated by `createSignedPublicToken`
54
- * @param str token previously generated by `createSignedPublicToken`
55
- * @param password the same password used to create the token with
56
- * @returns the original data object
57
- */
58
- export const parseSignedPublicToken = (str, password) => {
59
- const json = Buffer.from(str, 'base64').toString('utf8');
60
- const obj = JSON.parse(json);
61
- if (obj.v !== 1) {
62
- throw new Error(`Unsupported version`);
63
- }
64
- if (typeof obj.cs !== 'string' || typeof obj.d !== 'string') {
65
- throw new Error('Invalid token');
66
- }
67
- const checksum = obj.cs;
68
- if (checksum !== getSignature(obj.d, password)) {
69
- throw new Error(`compromised object`);
70
- }
71
- return JSON.parse(obj.d);
72
- };
1
+ import * as crypto from 'crypto';
2
+ export const createPublicAccessToken = (uid, ip, dbToken, password) => {
3
+ const obj = {
4
+ t: dbToken,
5
+ c: Date.now(),
6
+ u: uid,
7
+ i: ip,
8
+ };
9
+ // let str = JSON.stringify(obj);
10
+ // str = Buffer.from(str).toString('base64');
11
+ // return 'a' + str; // version a
12
+ return 'b' + createSignedPublicToken(obj, password);
13
+ };
14
+ export const decodePublicAccessToken = (accessToken, password) => {
15
+ let details;
16
+ if (accessToken[0] === 'b') {
17
+ // New signed version
18
+ const obj = parseSignedPublicToken(accessToken.slice(1), password);
19
+ details = {
20
+ access_token: obj.t,
21
+ uid: obj.u,
22
+ created: obj.c,
23
+ ip: obj.i,
24
+ };
25
+ }
26
+ else if (accessToken[0] === 'a') {
27
+ // Old insecure version, previously allowed until August 1, 2020.
28
+ throw new Error('Old token version not allowed');
29
+ }
30
+ if (!details || !details.access_token || !details.uid || !details.created || !details.ip) {
31
+ throw new Error('Invalid token');
32
+ }
33
+ return details;
34
+ };
35
+ const getSignature = (content, salt) => {
36
+ // Use fast md5 with salt to sign with. Large salt recommended!!
37
+ return crypto.createHash('md5').update(salt + content).digest('hex');
38
+ };
39
+ /**
40
+ * Sign objects with an md5 hash. An attacker might base4 decode it and see the content and generated checksum hash,
41
+ * but will need to guess the password used to generate the hash to manipulate it. This is not impossible but will take
42
+ * a very long time when using a large password
43
+ * @param obj data object to sign
44
+ * @param password password to use as salt for the generated md5 hash
45
+ * @returns base64 encoded signed token
46
+ */
47
+ export const createSignedPublicToken = (obj, password) => {
48
+ const str = JSON.stringify(obj);
49
+ const checksum = getSignature(str, password);
50
+ return Buffer.from(JSON.stringify({ v: 1, cs: checksum, d: str })).toString('base64');
51
+ };
52
+ /**
53
+ * Parses and validates a signed token that was previouslt generated by `createSignedPublicToken`
54
+ * @param str token previously generated by `createSignedPublicToken`
55
+ * @param password the same password used to create the token with
56
+ * @returns the original data object
57
+ */
58
+ export const parseSignedPublicToken = (str, password) => {
59
+ const json = Buffer.from(str, 'base64').toString('utf8');
60
+ const obj = JSON.parse(json);
61
+ if (obj.v !== 1) {
62
+ throw new Error(`Unsupported version`);
63
+ }
64
+ if (typeof obj.cs !== 'string' || typeof obj.d !== 'string') {
65
+ throw new Error('Invalid token');
66
+ }
67
+ const checksum = obj.cs;
68
+ if (checksum !== getSignature(obj.d, password)) {
69
+ throw new Error(`compromised object`);
70
+ }
71
+ return JSON.parse(obj.d);
72
+ };
73
73
  //# sourceMappingURL=tokens.js.map
@@ -1,42 +1,42 @@
1
- export const isValidEmail = (email) => {
2
- return /[a-z0-9_.+]+@([a-z0-9\-]+\.)+[a-z]{2,}/i.test(email);
3
- };
4
- export const isValidNewEmailAddress = async (authRef, email) => {
5
- const exists = await authRef.query().filter('email', '==', email).exists();
6
- return !exists;
7
- };
8
- export const isValidNewUsername = async (authRef, username) => {
9
- const exists = await authRef.query().filter('username', '==', username).exists();
10
- return !exists;
11
- };
12
- export const isValidUsername = (username) => {
13
- return username !== 'admin' && typeof username === 'string' && username.length >= 5 && /^[a-z0-9]+$/.test(username);
14
- };
15
- export const isValidDisplayName = (displayName) => {
16
- return typeof displayName === 'string' && displayName.length >= 5;
17
- };
18
- export const isValidPassword = (password) => {
19
- // return typeof password === 'string' && password.length >= 8 && password.indexOf(' ') < 0 && /[0-9]/.test(password) && /[a-z]/.test(password) && /[A-Z]/.test(password);
20
- return typeof password === 'string' && password.length >= 8 && password.indexOf(' ') < 0; // Let client application set their own password rules. Keep minimum length of 8 and no spaces requirement.
21
- };
22
- export const isValidPicture = (picture) => {
23
- return picture === null || (typeof picture === 'object' && typeof picture.url === 'string' && typeof picture.width === 'number' && typeof picture.height === 'number');
24
- };
25
- export const isValidSettings = (settings) => {
26
- return typeof settings === 'undefined'
27
- || (typeof settings === 'object'
28
- && Object.keys(settings).length <= 100 // max 100 settings
29
- && Object.keys(settings).map(key => typeof settings[key]).every(t => ['string', 'number', 'boolean'].indexOf(t) >= 0) // only string, number, boolean values
30
- && Object.keys(settings).filter(key => typeof settings[key] === 'string').every(key => settings[key].length <= 250) // strings values <= 250 chars
31
- );
32
- };
33
- export const invalidEmailError = { code: 'invalid_email', message: 'Invalid email address' };
34
- export const invalidUsernameError = { code: 'invalid_username', message: 'Invalid username, must be at least 5 characters and can only contain lowercase characters a-z and 0-9' };
35
- export const emailExistsError = { code: 'email_conflict', message: 'Account with email address exists already' };
36
- export const usernameExistsError = { code: 'username_conflict', message: 'Account with username exists already' };
37
- export const emailOrUsernameExistsError = { code: 'conflict', message: `Account with username and/or email already exists` };
38
- export const invalidDisplayNameError = { code: 'invalid_display_name', message: 'Invalid display_name, must be at least 5 characters' };
39
- export const invalidPasswordError = { code: 'invalid_password', message: 'Invalid password, must be at least 8 characters and cannot contain spaces' };
40
- export const invalidPictureError = { code: 'invalid_picture', message: 'Invalid picture, must be an object with url, width and height properties' };
41
- export const invalidSettingsError = { code: 'invalid_settings', message: 'Invalid settings, must be an object and contain only string, number and/or boolean values. Additionaly, string values can have a maximum length of 250, and a maximum of 100 settings can be added' };
1
+ export const isValidEmail = (email) => {
2
+ return /[a-z0-9_.+]+@([a-z0-9\-]+\.)+[a-z]{2,}/i.test(email);
3
+ };
4
+ export const isValidNewEmailAddress = async (authRef, email) => {
5
+ const exists = await authRef.query().filter('email', '==', email).exists();
6
+ return !exists;
7
+ };
8
+ export const isValidNewUsername = async (authRef, username) => {
9
+ const exists = await authRef.query().filter('username', '==', username).exists();
10
+ return !exists;
11
+ };
12
+ export const isValidUsername = (username) => {
13
+ return username !== 'admin' && typeof username === 'string' && username.length >= 5 && /^[a-z0-9]+$/.test(username);
14
+ };
15
+ export const isValidDisplayName = (displayName) => {
16
+ return typeof displayName === 'string' && displayName.length >= 5;
17
+ };
18
+ export const isValidPassword = (password) => {
19
+ // return typeof password === 'string' && password.length >= 8 && password.indexOf(' ') < 0 && /[0-9]/.test(password) && /[a-z]/.test(password) && /[A-Z]/.test(password);
20
+ return typeof password === 'string' && password.length >= 8 && password.indexOf(' ') < 0; // Let client application set their own password rules. Keep minimum length of 8 and no spaces requirement.
21
+ };
22
+ export const isValidPicture = (picture) => {
23
+ return picture === null || (typeof picture === 'object' && typeof picture.url === 'string' && typeof picture.width === 'number' && typeof picture.height === 'number');
24
+ };
25
+ export const isValidSettings = (settings) => {
26
+ return typeof settings === 'undefined'
27
+ || (typeof settings === 'object'
28
+ && Object.keys(settings).length <= 100 // max 100 settings
29
+ && Object.keys(settings).map(key => typeof settings[key]).every(t => ['string', 'number', 'boolean'].indexOf(t) >= 0) // only string, number, boolean values
30
+ && Object.keys(settings).filter(key => typeof settings[key] === 'string').every(key => settings[key].length <= 250) // strings values <= 250 chars
31
+ );
32
+ };
33
+ export const invalidEmailError = { code: 'invalid_email', message: 'Invalid email address' };
34
+ export const invalidUsernameError = { code: 'invalid_username', message: 'Invalid username, must be at least 5 characters and can only contain lowercase characters a-z and 0-9' };
35
+ export const emailExistsError = { code: 'email_conflict', message: 'Account with email address exists already' };
36
+ export const usernameExistsError = { code: 'username_conflict', message: 'Account with username exists already' };
37
+ export const emailOrUsernameExistsError = { code: 'conflict', message: `Account with username and/or email already exists` };
38
+ export const invalidDisplayNameError = { code: 'invalid_display_name', message: 'Invalid display_name, must be at least 5 characters' };
39
+ export const invalidPasswordError = { code: 'invalid_password', message: 'Invalid password, must be at least 8 characters and cannot contain spaces' };
40
+ export const invalidPictureError = { code: 'invalid_picture', message: 'Invalid picture, must be an object with url, width and height properties' };
41
+ export const invalidSettingsError = { code: 'invalid_settings', message: 'Invalid settings, must be an object and contain only string, number and/or boolean values. Additionaly, string values can have a maximum length of 250, and a maximum of 100 settings can be added' };
42
42
  //# sourceMappingURL=validate.js.map