acebase-server 1.16.2 → 1.17.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 (250) hide show
  1. package/README.md +180 -10
  2. package/build-vars.js +2 -1
  3. package/dist/cjs/auth.js +88 -88
  4. package/dist/cjs/cluster.js +56 -56
  5. package/dist/cjs/index.d.ts +1 -1
  6. package/dist/cjs/index.js +24 -24
  7. package/dist/cjs/logger.js +73 -73
  8. package/dist/cjs/middleware/404.js +14 -14
  9. package/dist/cjs/middleware/admin-only.js +28 -28
  10. package/dist/cjs/middleware/cache.js +14 -14
  11. package/dist/cjs/middleware/connection.js +49 -49
  12. package/dist/cjs/middleware/context.js +20 -20
  13. package/dist/cjs/middleware/cors.js +50 -50
  14. package/dist/cjs/middleware/swagger.js +17 -17
  15. package/dist/cjs/middleware/user.js +57 -57
  16. package/dist/cjs/oauth-providers/dropbox.js +109 -109
  17. package/dist/cjs/oauth-providers/facebook.js +85 -85
  18. package/dist/cjs/oauth-providers/google.js +119 -119
  19. package/dist/cjs/oauth-providers/index.js +26 -26
  20. package/dist/cjs/oauth-providers/instagram.js +80 -80
  21. package/dist/cjs/oauth-providers/oauth-provider.js +20 -20
  22. package/dist/cjs/oauth-providers/spotify.js +113 -113
  23. package/dist/cjs/routes/auth-change-password.js +87 -87
  24. package/dist/cjs/routes/auth-delete.js +52 -52
  25. package/dist/cjs/routes/auth-forgot-password.js +77 -77
  26. package/dist/cjs/routes/auth-reset-password.js +97 -97
  27. package/dist/cjs/routes/auth-signin.js +46 -46
  28. package/dist/cjs/routes/auth-signout.js +61 -61
  29. package/dist/cjs/routes/auth-signup.js +142 -142
  30. package/dist/cjs/routes/auth-state.js +25 -25
  31. package/dist/cjs/routes/auth-update.js +131 -131
  32. package/dist/cjs/routes/auth-verify-email.js +71 -71
  33. package/dist/cjs/routes/auth.js +57 -54
  34. package/dist/cjs/routes/data-exists.js +33 -33
  35. package/dist/cjs/routes/data-export.js +48 -48
  36. package/dist/cjs/routes/data-get.js +70 -66
  37. package/dist/cjs/routes/data-import.js +54 -54
  38. package/dist/cjs/routes/data-index-create.js +42 -42
  39. package/dist/cjs/routes/data-index-delete.js +33 -33
  40. package/dist/cjs/routes/data-index-list.js +31 -31
  41. package/dist/cjs/routes/data-query.js +80 -70
  42. package/dist/cjs/routes/data-reflect.js +97 -86
  43. package/dist/cjs/routes/data-schema-get.js +36 -36
  44. package/dist/cjs/routes/data-schema-set.js +30 -30
  45. package/dist/cjs/routes/data-schema-test.js +43 -43
  46. package/dist/cjs/routes/data-schemas-list.js +32 -32
  47. package/dist/cjs/routes/data-set.js +85 -75
  48. package/dist/cjs/routes/data-sync-changes.js +81 -67
  49. package/dist/cjs/routes/data-sync-mutations.js +81 -67
  50. package/dist/cjs/routes/data-transaction.js +159 -139
  51. package/dist/cjs/routes/data-update.js +86 -75
  52. package/dist/cjs/routes/data.js +62 -62
  53. package/dist/cjs/routes/docs.js +258 -251
  54. package/dist/cjs/routes/meta-info.js +63 -63
  55. package/dist/cjs/routes/meta-logs.js +49 -49
  56. package/dist/cjs/routes/meta-ping.js +11 -11
  57. package/dist/cjs/routes/meta-stats.js +27 -27
  58. package/dist/cjs/routes/meta.js +19 -19
  59. package/dist/cjs/routes/oauth2-init.js +54 -54
  60. package/dist/cjs/routes/oauth2-refresh.js +42 -42
  61. package/dist/cjs/routes/oauth2-signin.js +265 -265
  62. package/dist/cjs/routes/webmanager.js +26 -26
  63. package/dist/cjs/rules.js +380 -167
  64. package/dist/cjs/sandbox.js +28 -0
  65. package/dist/cjs/schema/user.js +24 -24
  66. package/dist/cjs/server.js +415 -407
  67. package/dist/cjs/settings/email.js +2 -2
  68. package/dist/cjs/settings/index.js +175 -172
  69. package/dist/cjs/shared/clients.js +26 -26
  70. package/dist/cjs/shared/email.js +2 -2
  71. package/dist/cjs/shared/env.js +2 -2
  72. package/dist/cjs/shared/error.js +33 -33
  73. package/dist/cjs/shared/http.js +28 -28
  74. package/dist/cjs/shared/password.js +45 -45
  75. package/dist/cjs/shared/rootpath.js +16 -16
  76. package/dist/cjs/shared/signin.js +143 -143
  77. package/dist/cjs/shared/simple-fetch.js +76 -76
  78. package/dist/cjs/shared/tokens.js +79 -79
  79. package/dist/cjs/shared/validate.js +61 -61
  80. package/dist/cjs/start.js +53 -53
  81. package/dist/cjs/test.js +10 -10
  82. package/dist/cjs/websocket/index.js +331 -319
  83. package/dist/cjs/websocket/manager.js +15 -15
  84. package/dist/cjs/websocket/socket.io.js +76 -76
  85. package/dist/esm/auth.js +75 -75
  86. package/dist/esm/cluster.js +54 -54
  87. package/dist/esm/index.d.ts +1 -1
  88. package/dist/esm/index.js +4 -4
  89. package/dist/esm/logger.js +51 -51
  90. package/dist/esm/middleware/404.js +10 -10
  91. package/dist/esm/middleware/admin-only.js +24 -24
  92. package/dist/esm/middleware/cache.js +10 -10
  93. package/dist/esm/middleware/connection.js +45 -45
  94. package/dist/esm/middleware/context.js +16 -16
  95. package/dist/esm/middleware/cors.js +44 -44
  96. package/dist/esm/middleware/swagger.js +13 -13
  97. package/dist/esm/middleware/user.js +44 -44
  98. package/dist/esm/oauth-providers/dropbox.js +90 -90
  99. package/dist/esm/oauth-providers/facebook.js +66 -66
  100. package/dist/esm/oauth-providers/google.js +96 -96
  101. package/dist/esm/oauth-providers/index.js +18 -18
  102. package/dist/esm/oauth-providers/instagram.js +61 -61
  103. package/dist/esm/oauth-providers/oauth-provider.js +16 -16
  104. package/dist/esm/oauth-providers/spotify.js +92 -92
  105. package/dist/esm/routes/auth-change-password.js +72 -72
  106. package/dist/esm/routes/auth-delete.js +37 -37
  107. package/dist/esm/routes/auth-forgot-password.js +62 -62
  108. package/dist/esm/routes/auth-reset-password.js +81 -81
  109. package/dist/esm/routes/auth-signin.js +33 -33
  110. package/dist/esm/routes/auth-signout.js +47 -47
  111. package/dist/esm/routes/auth-signup.js +127 -127
  112. package/dist/esm/routes/auth-state.js +12 -12
  113. package/dist/esm/routes/auth-update.js +116 -116
  114. package/dist/esm/routes/auth-verify-email.js +57 -57
  115. package/dist/esm/routes/auth.js +53 -50
  116. package/dist/esm/routes/data-exists.js +20 -20
  117. package/dist/esm/routes/data-export.js +35 -35
  118. package/dist/esm/routes/data-get.js +56 -52
  119. package/dist/esm/routes/data-import.js +41 -41
  120. package/dist/esm/routes/data-index-create.js +28 -28
  121. package/dist/esm/routes/data-index-delete.js +20 -20
  122. package/dist/esm/routes/data-index-list.js +18 -18
  123. package/dist/esm/routes/data-query.js +66 -56
  124. package/dist/esm/routes/data-reflect.js +83 -72
  125. package/dist/esm/routes/data-schema-get.js +23 -23
  126. package/dist/esm/routes/data-schema-set.js +17 -17
  127. package/dist/esm/routes/data-schema-test.js +29 -29
  128. package/dist/esm/routes/data-schemas-list.js +19 -19
  129. package/dist/esm/routes/data-set.js +70 -60
  130. package/dist/esm/routes/data-sync-changes.js +67 -53
  131. package/dist/esm/routes/data-sync-mutations.js +67 -53
  132. package/dist/esm/routes/data-transaction.js +142 -123
  133. package/dist/esm/routes/data-update.js +71 -60
  134. package/dist/esm/routes/data.js +58 -58
  135. package/dist/esm/routes/docs.js +252 -245
  136. package/dist/esm/routes/meta-info.js +59 -59
  137. package/dist/esm/routes/meta-logs.js +35 -35
  138. package/dist/esm/routes/meta-ping.js +7 -7
  139. package/dist/esm/routes/meta-stats.js +14 -14
  140. package/dist/esm/routes/meta.js +15 -15
  141. package/dist/esm/routes/oauth2-init.js +41 -41
  142. package/dist/esm/routes/oauth2-refresh.js +29 -29
  143. package/dist/esm/routes/oauth2-signin.js +251 -251
  144. package/dist/esm/routes/webmanager.js +22 -22
  145. package/dist/esm/rules.js +374 -163
  146. package/dist/esm/sandbox.js +12 -0
  147. package/dist/esm/schema/user.js +19 -19
  148. package/dist/esm/server.js +395 -387
  149. package/dist/esm/settings/email.js +1 -1
  150. package/dist/esm/settings/index.js +168 -165
  151. package/dist/esm/shared/clients.js +22 -22
  152. package/dist/esm/shared/email.js +1 -1
  153. package/dist/esm/shared/env.js +1 -1
  154. package/dist/esm/shared/error.js +25 -25
  155. package/dist/esm/shared/http.js +22 -22
  156. package/dist/esm/shared/password.js +38 -38
  157. package/dist/esm/shared/rootpath.js +13 -13
  158. package/dist/esm/shared/signin.js +128 -128
  159. package/dist/esm/shared/simple-fetch.js +59 -59
  160. package/dist/esm/shared/tokens.js +72 -72
  161. package/dist/esm/shared/validate.js +41 -41
  162. package/dist/esm/start.js +50 -50
  163. package/dist/esm/test.js +8 -8
  164. package/dist/esm/websocket/index.js +313 -302
  165. package/dist/esm/websocket/manager.js +11 -11
  166. package/dist/esm/websocket/socket.io.js +71 -71
  167. package/dist/types/auth.d.ts +3 -3
  168. package/dist/types/cluster.d.ts +1 -1
  169. package/dist/types/index.d.ts +4 -4
  170. package/dist/types/logger.d.ts +35 -35
  171. package/dist/types/middleware/404.d.ts +7 -7
  172. package/dist/types/middleware/admin-only.d.ts +19 -19
  173. package/dist/types/middleware/cache.d.ts +3 -3
  174. package/dist/types/middleware/connection.d.ts +7 -7
  175. package/dist/types/middleware/context.d.ts +3 -3
  176. package/dist/types/middleware/cors.d.ts +25 -25
  177. package/dist/types/middleware/swagger.d.ts +3 -3
  178. package/dist/types/middleware/user.d.ts +2 -2
  179. package/dist/types/oauth-providers/dropbox.d.ts +52 -52
  180. package/dist/types/oauth-providers/facebook.d.ts +41 -41
  181. package/dist/types/oauth-providers/google.d.ts +43 -43
  182. package/dist/types/oauth-providers/index.d.ts +10 -10
  183. package/dist/types/oauth-providers/instagram.d.ts +50 -50
  184. package/dist/types/oauth-providers/oauth-provider.d.ts +74 -74
  185. package/dist/types/oauth-providers/spotify.d.ts +53 -53
  186. package/dist/types/routes/auth-change-password.d.ts +20 -20
  187. package/dist/types/routes/auth-delete.d.ts +16 -16
  188. package/dist/types/routes/auth-forgot-password.d.ts +16 -16
  189. package/dist/types/routes/auth-reset-password.d.ts +23 -23
  190. package/dist/types/routes/auth-signin.d.ts +24 -24
  191. package/dist/types/routes/auth-signout.d.ts +14 -14
  192. package/dist/types/routes/auth-signup.d.ts +32 -32
  193. package/dist/types/routes/auth-state.d.ts +13 -13
  194. package/dist/types/routes/auth-update.d.ts +33 -33
  195. package/dist/types/routes/auth-verify-email.d.ts +21 -21
  196. package/dist/types/routes/auth.d.ts +6 -6
  197. package/dist/types/routes/data-exists.d.ts +9 -9
  198. package/dist/types/routes/data-export.d.ts +10 -10
  199. package/dist/types/routes/data-get.d.ts +14 -14
  200. package/dist/types/routes/data-import.d.ts +13 -13
  201. package/dist/types/routes/data-index-create.d.ts +51 -51
  202. package/dist/types/routes/data-index-delete.d.ts +17 -17
  203. package/dist/types/routes/data-index-list.d.ts +21 -21
  204. package/dist/types/routes/data-query.d.ts +49 -49
  205. package/dist/types/routes/data-reflect.d.ts +29 -29
  206. package/dist/types/routes/data-schema-get.d.ts +11 -11
  207. package/dist/types/routes/data-schema-set.d.ts +19 -19
  208. package/dist/types/routes/data-schema-test.d.ts +19 -19
  209. package/dist/types/routes/data-schemas-list.d.ts +11 -11
  210. package/dist/types/routes/data-set.d.ts +27 -27
  211. package/dist/types/routes/data-sync-changes.d.ts +25 -28
  212. package/dist/types/routes/data-sync-mutations.d.ts +25 -28
  213. package/dist/types/routes/data-transaction.d.ts +34 -34
  214. package/dist/types/routes/data-update.d.ts +27 -27
  215. package/dist/types/routes/data.d.ts +3 -3
  216. package/dist/types/routes/docs.d.ts +3 -3
  217. package/dist/types/routes/meta-info.d.ts +11 -11
  218. package/dist/types/routes/meta-logs.d.ts +20 -20
  219. package/dist/types/routes/meta-ping.d.ts +7 -7
  220. package/dist/types/routes/meta-stats.d.ts +13 -13
  221. package/dist/types/routes/meta.d.ts +3 -3
  222. package/dist/types/routes/oauth2-init.d.ts +13 -13
  223. package/dist/types/routes/oauth2-refresh.d.ts +17 -17
  224. package/dist/types/routes/oauth2-signin.d.ts +15 -15
  225. package/dist/types/routes/webmanager.d.ts +3 -3
  226. package/dist/types/rules.d.ts +73 -34
  227. package/dist/types/sandbox.d.ts +3 -0
  228. package/dist/types/schema/user.d.ts +85 -85
  229. package/dist/types/server.d.ts +117 -111
  230. package/dist/types/settings/email.d.ts +14 -14
  231. package/dist/types/settings/index.d.ts +195 -187
  232. package/dist/types/shared/clients.d.ts +46 -46
  233. package/dist/types/shared/email.d.ts +34 -34
  234. package/dist/types/shared/env.d.ts +47 -44
  235. package/dist/types/shared/error.d.ts +15 -15
  236. package/dist/types/shared/http.d.ts +22 -21
  237. package/dist/types/shared/password.d.ts +19 -19
  238. package/dist/types/shared/rootpath.d.ts +2 -2
  239. package/dist/types/shared/signin.d.ts +31 -31
  240. package/dist/types/shared/simple-fetch.d.ts +21 -21
  241. package/dist/types/shared/tokens.d.ts +24 -24
  242. package/dist/types/shared/validate.d.ts +22 -22
  243. package/dist/types/start.d.ts +1 -1
  244. package/dist/types/test.d.ts +1 -1
  245. package/dist/types/websocket/index.d.ts +6 -6
  246. package/dist/types/websocket/manager.d.ts +99 -99
  247. package/dist/types/websocket/socket.io.d.ts +10 -10
  248. package/package.json +4 -4
  249. package/src/routes/data-set.yaml +5 -5
  250. package/src/routes/data-update.yaml +4 -4
@@ -1,17 +1,17 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.packageRootPath = void 0;
4
- const path_1 = require("path");
5
- // This file is in ./src/shared/rootpath.ts
6
- // When this code runs it is at ./dist/cjs/shared/rootpath.js or ./dist/esm/shared/rootpath.js
7
- // So, the package root is at ../../..
8
- let currentDir = __dirname;
9
- if (process.platform === 'win32' && currentDir.startsWith('/')) {
10
- // tsc-esm-fix does not handle win32 file urls correctly, the drive letter in import.meta.url is prefixed with a slash: file:///C:/dir/file.js
11
- currentDir = currentDir.slice(1);
12
- }
13
- // tsc-esm-fix also does not use decodeURI to remove encoded characters (such as %20 for spaces)
14
- currentDir = decodeURI(currentDir);
15
- exports.packageRootPath = (0, path_1.resolve)(currentDir, '../../..');
16
- exports.default = exports.packageRootPath;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.packageRootPath = void 0;
4
+ const path_1 = require("path");
5
+ // This file is in ./src/shared/rootpath.ts
6
+ // When this code runs it is at ./dist/cjs/shared/rootpath.js or ./dist/esm/shared/rootpath.js
7
+ // So, the package root is at ../../..
8
+ let currentDir = __dirname;
9
+ if (process.platform === 'win32' && currentDir.startsWith('/')) {
10
+ // tsc-esm-fix does not handle win32 file urls correctly, the drive letter in import.meta.url is prefixed with a slash: file:///C:/dir/file.js
11
+ currentDir = currentDir.slice(1);
12
+ }
13
+ // tsc-esm-fix also does not use decodeURI to remove encoded characters (such as %20 for spaces)
14
+ currentDir = decodeURI(currentDir);
15
+ exports.packageRootPath = (0, path_1.resolve)(currentDir, '../../..');
16
+ exports.default = exports.packageRootPath;
17
17
  //# sourceMappingURL=rootpath.js.map
@@ -1,144 +1,144 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.signIn = exports.SignInError = void 0;
13
- const acebase_core_1 = require("acebase-core");
14
- const password_1 = require("./password");
15
- const tokens_1 = require("./tokens");
16
- class SignInError extends Error {
17
- constructor(code, message, details = {}) {
18
- super(message);
19
- this.code = code;
20
- this.details = details;
21
- }
22
- }
23
- 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 {
37
- const query = env.authRef.query();
38
- let tokenDetails;
39
- 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
- case 'email': {
62
- if (typeof credentials.email !== 'string' || typeof credentials.password !== 'string') {
63
- throw new SignInError('invalid_details', 'sign in request has invalid arguments');
64
- }
65
- query.filter('email', '==', credentials.email);
66
- break;
67
- }
68
- case 'account': {
69
- if (typeof credentials.username !== 'string' || typeof credentials.password !== 'string') {
70
- throw new SignInError('invalid_details', 'sign in request has invalid arguments');
71
- }
72
- query.filter('username', '==', credentials.username);
73
- break;
74
- }
75
- default: {
76
- throw new SignInError('invalid_method', `Unsupported sign in method ${credentials.method}`);
77
- }
78
- }
79
- 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) {
84
- throw new SignInError('duplicate', `${snaps.length} users found with the same ${credentials.method}. Contact your database administrator`, { count: snaps.length });
85
- }
86
- const snap = snaps[0];
87
- const user = snap.val();
88
- user.uid = snap.key;
89
- if (user.is_disabled === true) {
90
- throw new SignInError('account_disabled', 'Your account has been disabled. Contact your database administrator');
91
- }
92
- if (credentials.method === 'token' && tokenDetails.uid !== user.uid) {
93
- throw new SignInError('token_mismatch', 'Sign in again');
94
- }
95
- if (credentials.method === 'account' || credentials.method === 'email') {
96
- // Check password
97
- const hash = user.password_salt ? (0, password_1.getPasswordHash)(credentials.password, user.password_salt) : (0, password_1.getOldPasswordHash)(credentials.password);
98
- if (user.password !== hash) {
99
- throw new SignInError('wrong_password', 'Incorrect password');
100
- }
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;
116
- }
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();
121
- }
122
- }
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
132
- env.authCache.set(user.uid, user);
133
- // Bind user to current request
134
- req.user = user;
135
- return user;
136
- }
137
- catch (err) {
138
- // 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);
140
- throw err;
141
- }
142
- });
143
- exports.signIn = signIn;
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.signIn = exports.SignInError = void 0;
13
+ const acebase_core_1 = require("acebase-core");
14
+ const password_1 = require("./password");
15
+ const tokens_1 = require("./tokens");
16
+ class SignInError extends Error {
17
+ constructor(code, message, details = {}) {
18
+ super(message);
19
+ this.code = code;
20
+ this.details = details;
21
+ }
22
+ }
23
+ 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 {
37
+ const query = env.authRef.query();
38
+ let tokenDetails;
39
+ 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
+ case 'email': {
62
+ if (typeof credentials.email !== 'string' || typeof credentials.password !== 'string') {
63
+ throw new SignInError('invalid_details', 'sign in request has invalid arguments');
64
+ }
65
+ query.filter('email', '==', credentials.email);
66
+ break;
67
+ }
68
+ case 'account': {
69
+ if (typeof credentials.username !== 'string' || typeof credentials.password !== 'string') {
70
+ throw new SignInError('invalid_details', 'sign in request has invalid arguments');
71
+ }
72
+ query.filter('username', '==', credentials.username);
73
+ break;
74
+ }
75
+ default: {
76
+ throw new SignInError('invalid_method', `Unsupported sign in method ${credentials.method}`);
77
+ }
78
+ }
79
+ 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) {
84
+ throw new SignInError('duplicate', `${snaps.length} users found with the same ${credentials.method}. Contact your database administrator`, { count: snaps.length });
85
+ }
86
+ const snap = snaps[0];
87
+ const user = snap.val();
88
+ user.uid = snap.key;
89
+ if (user.is_disabled === true) {
90
+ throw new SignInError('account_disabled', 'Your account has been disabled. Contact your database administrator');
91
+ }
92
+ if (credentials.method === 'token' && tokenDetails.uid !== user.uid) {
93
+ throw new SignInError('token_mismatch', 'Sign in again');
94
+ }
95
+ if (credentials.method === 'account' || credentials.method === 'email') {
96
+ // Check password
97
+ const hash = user.password_salt ? (0, password_1.getPasswordHash)(credentials.password, user.password_salt) : (0, password_1.getOldPasswordHash)(credentials.password);
98
+ if (user.password !== hash) {
99
+ throw new SignInError('wrong_password', 'Incorrect password');
100
+ }
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;
116
+ }
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();
121
+ }
122
+ }
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
132
+ env.authCache.set(user.uid, user);
133
+ // Bind user to current request
134
+ req.user = user;
135
+ return user;
136
+ }
137
+ catch (err) {
138
+ // 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);
140
+ throw err;
141
+ }
142
+ });
143
+ exports.signIn = signIn;
144
144
  //# sourceMappingURL=signin.js.map
@@ -1,77 +1,77 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.fetch = void 0;
13
- const https_1 = require("https");
14
- /**
15
- * Very lightweight custom fetch implementation to avoid additional dependencies
16
- * @param url
17
- * @param options
18
- */
19
- function fetch(url, options) {
20
- return new Promise((resolve, reject) => {
21
- const method = (options === null || options === void 0 ? void 0 : options.method) || 'GET';
22
- const headers = options === null || options === void 0 ? void 0 : options.headers;
23
- const req = (0, https_1.request)(url, { method, headers }, res => {
24
- // res.setEncoding('binary'); // will result in strings!!!!
25
- const ready = new Promise((resolve, reject) => {
26
- const chunks = [];
27
- res.on('data', data => {
28
- chunks.push(data);
29
- });
30
- res.on('end', () => {
31
- const buffer = Buffer.concat(chunks);
32
- resolve(buffer);
33
- });
34
- res.on('error', (err) => {
35
- reject(err);
36
- });
37
- });
38
- const response = {
39
- get status() { return res.statusCode; },
40
- get headers() {
41
- return {
42
- get(name) {
43
- const val = res.headers[name.toLowerCase()];
44
- if (val instanceof Array) {
45
- return val.join(', ');
46
- }
47
- return val;
48
- },
49
- };
50
- },
51
- text() {
52
- return __awaiter(this, void 0, void 0, function* () {
53
- const buffer = yield ready;
54
- return buffer.toString('utf8');
55
- });
56
- },
57
- json() {
58
- // return Promise.resolve(JSON.parse(body));
59
- return this.text().then(json => JSON.parse(json));
60
- },
61
- arrayBuffer() {
62
- return __awaiter(this, void 0, void 0, function* () {
63
- const data = yield ready;
64
- const arrayBuffer = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
65
- return arrayBuffer;
66
- });
67
- },
68
- };
69
- resolve(response);
70
- });
71
- req.on('error', reject);
72
- (options === null || options === void 0 ? void 0 : options.body) && req.write(options.body, 'utf8');
73
- req.end();
74
- });
75
- }
76
- exports.fetch = fetch;
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.fetch = void 0;
13
+ const https_1 = require("https");
14
+ /**
15
+ * Very lightweight custom fetch implementation to avoid additional dependencies
16
+ * @param url
17
+ * @param options
18
+ */
19
+ function fetch(url, options) {
20
+ return new Promise((resolve, reject) => {
21
+ const method = (options === null || options === void 0 ? void 0 : options.method) || 'GET';
22
+ const headers = options === null || options === void 0 ? void 0 : options.headers;
23
+ const req = (0, https_1.request)(url, { method, headers }, res => {
24
+ // res.setEncoding('binary'); // will result in strings!!!!
25
+ const ready = new Promise((resolve, reject) => {
26
+ const chunks = [];
27
+ res.on('data', data => {
28
+ chunks.push(data);
29
+ });
30
+ res.on('end', () => {
31
+ const buffer = Buffer.concat(chunks);
32
+ resolve(buffer);
33
+ });
34
+ res.on('error', (err) => {
35
+ reject(err);
36
+ });
37
+ });
38
+ const response = {
39
+ get status() { return res.statusCode; },
40
+ get headers() {
41
+ return {
42
+ get(name) {
43
+ const val = res.headers[name.toLowerCase()];
44
+ if (val instanceof Array) {
45
+ return val.join(', ');
46
+ }
47
+ return val;
48
+ },
49
+ };
50
+ },
51
+ text() {
52
+ return __awaiter(this, void 0, void 0, function* () {
53
+ const buffer = yield ready;
54
+ return buffer.toString('utf8');
55
+ });
56
+ },
57
+ json() {
58
+ // return Promise.resolve(JSON.parse(body));
59
+ return this.text().then(json => JSON.parse(json));
60
+ },
61
+ arrayBuffer() {
62
+ return __awaiter(this, void 0, void 0, function* () {
63
+ const data = yield ready;
64
+ const arrayBuffer = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
65
+ return arrayBuffer;
66
+ });
67
+ },
68
+ };
69
+ resolve(response);
70
+ });
71
+ req.on('error', reject);
72
+ (options === null || options === void 0 ? void 0 : options.body) && req.write(options.body, 'utf8');
73
+ req.end();
74
+ });
75
+ }
76
+ exports.fetch = fetch;
77
77
  //# sourceMappingURL=simple-fetch.js.map
@@ -1,80 +1,80 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseSignedPublicToken = exports.createSignedPublicToken = exports.decodePublicAccessToken = exports.createPublicAccessToken = void 0;
4
- const crypto = require("crypto");
5
- const createPublicAccessToken = (uid, ip, dbToken, password) => {
6
- const obj = {
7
- t: dbToken,
8
- c: Date.now(),
9
- u: uid,
10
- i: ip,
11
- };
12
- // let str = JSON.stringify(obj);
13
- // str = Buffer.from(str).toString('base64');
14
- // return 'a' + str; // version a
15
- return 'b' + (0, exports.createSignedPublicToken)(obj, password);
16
- };
17
- exports.createPublicAccessToken = createPublicAccessToken;
18
- const decodePublicAccessToken = (accessToken, password) => {
19
- let details;
20
- if (accessToken[0] === 'b') {
21
- // New signed version
22
- const obj = (0, exports.parseSignedPublicToken)(accessToken.slice(1), password);
23
- details = {
24
- access_token: obj.t,
25
- uid: obj.u,
26
- created: obj.c,
27
- ip: obj.i,
28
- };
29
- }
30
- else if (accessToken[0] === 'a') {
31
- // Old insecure version, previously allowed until August 1, 2020.
32
- throw new Error('Old token version not allowed');
33
- }
34
- if (!details || !details.access_token || !details.uid || !details.created || !details.ip) {
35
- throw new Error('Invalid token');
36
- }
37
- return details;
38
- };
39
- exports.decodePublicAccessToken = decodePublicAccessToken;
40
- const getSignature = (content, salt) => {
41
- // Use fast md5 with salt to sign with. Large salt recommended!!
42
- return crypto.createHash('md5').update(salt + content).digest('hex');
43
- };
44
- /**
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
47
- * a very long time when using a large password
48
- * @param obj data object to sign
49
- * @param password password to use as salt for the generated md5 hash
50
- * @returns base64 encoded signed token
51
- */
52
- const createSignedPublicToken = (obj, password) => {
53
- const str = JSON.stringify(obj);
54
- const checksum = getSignature(str, password);
55
- return Buffer.from(JSON.stringify({ v: 1, cs: checksum, d: str })).toString('base64');
56
- };
57
- exports.createSignedPublicToken = createSignedPublicToken;
58
- /**
59
- * Parses and validates a signed token that was previouslt generated by `createSignedPublicToken`
60
- * @param str token previously generated by `createSignedPublicToken`
61
- * @param password the same password used to create the token with
62
- * @returns the original data object
63
- */
64
- const parseSignedPublicToken = (str, password) => {
65
- const json = Buffer.from(str, 'base64').toString('utf8');
66
- const obj = JSON.parse(json);
67
- if (obj.v !== 1) {
68
- throw new Error(`Unsupported version`);
69
- }
70
- if (typeof obj.cs !== 'string' || typeof obj.d !== 'string') {
71
- throw new Error('Invalid token');
72
- }
73
- const checksum = obj.cs;
74
- if (checksum !== getSignature(obj.d, password)) {
75
- throw new Error(`compromised object`);
76
- }
77
- return JSON.parse(obj.d);
78
- };
79
- exports.parseSignedPublicToken = parseSignedPublicToken;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseSignedPublicToken = exports.createSignedPublicToken = exports.decodePublicAccessToken = exports.createPublicAccessToken = void 0;
4
+ const crypto = require("crypto");
5
+ const createPublicAccessToken = (uid, ip, dbToken, password) => {
6
+ const obj = {
7
+ t: dbToken,
8
+ c: Date.now(),
9
+ u: uid,
10
+ i: ip,
11
+ };
12
+ // let str = JSON.stringify(obj);
13
+ // str = Buffer.from(str).toString('base64');
14
+ // return 'a' + str; // version a
15
+ return 'b' + (0, exports.createSignedPublicToken)(obj, password);
16
+ };
17
+ exports.createPublicAccessToken = createPublicAccessToken;
18
+ const decodePublicAccessToken = (accessToken, password) => {
19
+ let details;
20
+ if (accessToken[0] === 'b') {
21
+ // New signed version
22
+ const obj = (0, exports.parseSignedPublicToken)(accessToken.slice(1), password);
23
+ details = {
24
+ access_token: obj.t,
25
+ uid: obj.u,
26
+ created: obj.c,
27
+ ip: obj.i,
28
+ };
29
+ }
30
+ else if (accessToken[0] === 'a') {
31
+ // Old insecure version, previously allowed until August 1, 2020.
32
+ throw new Error('Old token version not allowed');
33
+ }
34
+ if (!details || !details.access_token || !details.uid || !details.created || !details.ip) {
35
+ throw new Error('Invalid token');
36
+ }
37
+ return details;
38
+ };
39
+ exports.decodePublicAccessToken = decodePublicAccessToken;
40
+ const getSignature = (content, salt) => {
41
+ // Use fast md5 with salt to sign with. Large salt recommended!!
42
+ return crypto.createHash('md5').update(salt + content).digest('hex');
43
+ };
44
+ /**
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
47
+ * a very long time when using a large password
48
+ * @param obj data object to sign
49
+ * @param password password to use as salt for the generated md5 hash
50
+ * @returns base64 encoded signed token
51
+ */
52
+ const createSignedPublicToken = (obj, password) => {
53
+ const str = JSON.stringify(obj);
54
+ const checksum = getSignature(str, password);
55
+ return Buffer.from(JSON.stringify({ v: 1, cs: checksum, d: str })).toString('base64');
56
+ };
57
+ exports.createSignedPublicToken = createSignedPublicToken;
58
+ /**
59
+ * Parses and validates a signed token that was previouslt generated by `createSignedPublicToken`
60
+ * @param str token previously generated by `createSignedPublicToken`
61
+ * @param password the same password used to create the token with
62
+ * @returns the original data object
63
+ */
64
+ const parseSignedPublicToken = (str, password) => {
65
+ const json = Buffer.from(str, 'base64').toString('utf8');
66
+ const obj = JSON.parse(json);
67
+ if (obj.v !== 1) {
68
+ throw new Error(`Unsupported version`);
69
+ }
70
+ if (typeof obj.cs !== 'string' || typeof obj.d !== 'string') {
71
+ throw new Error('Invalid token');
72
+ }
73
+ const checksum = obj.cs;
74
+ if (checksum !== getSignature(obj.d, password)) {
75
+ throw new Error(`compromised object`);
76
+ }
77
+ return JSON.parse(obj.d);
78
+ };
79
+ exports.parseSignedPublicToken = parseSignedPublicToken;
80
80
  //# sourceMappingURL=tokens.js.map