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.
- package/README.md +180 -10
- package/build-vars.js +2 -1
- package/dist/cjs/auth.js +88 -88
- package/dist/cjs/cluster.js +56 -56
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +24 -24
- package/dist/cjs/logger.js +73 -73
- package/dist/cjs/middleware/404.js +14 -14
- package/dist/cjs/middleware/admin-only.js +28 -28
- package/dist/cjs/middleware/cache.js +14 -14
- package/dist/cjs/middleware/connection.js +49 -49
- package/dist/cjs/middleware/context.js +20 -20
- package/dist/cjs/middleware/cors.js +50 -50
- package/dist/cjs/middleware/swagger.js +17 -17
- package/dist/cjs/middleware/user.js +57 -57
- package/dist/cjs/oauth-providers/dropbox.js +109 -109
- package/dist/cjs/oauth-providers/facebook.js +85 -85
- package/dist/cjs/oauth-providers/google.js +119 -119
- package/dist/cjs/oauth-providers/index.js +26 -26
- package/dist/cjs/oauth-providers/instagram.js +80 -80
- package/dist/cjs/oauth-providers/oauth-provider.js +20 -20
- package/dist/cjs/oauth-providers/spotify.js +113 -113
- package/dist/cjs/routes/auth-change-password.js +87 -87
- package/dist/cjs/routes/auth-delete.js +52 -52
- package/dist/cjs/routes/auth-forgot-password.js +77 -77
- package/dist/cjs/routes/auth-reset-password.js +97 -97
- package/dist/cjs/routes/auth-signin.js +46 -46
- package/dist/cjs/routes/auth-signout.js +61 -61
- package/dist/cjs/routes/auth-signup.js +142 -142
- package/dist/cjs/routes/auth-state.js +25 -25
- package/dist/cjs/routes/auth-update.js +131 -131
- package/dist/cjs/routes/auth-verify-email.js +71 -71
- package/dist/cjs/routes/auth.js +57 -54
- package/dist/cjs/routes/data-exists.js +33 -33
- package/dist/cjs/routes/data-export.js +48 -48
- package/dist/cjs/routes/data-get.js +70 -66
- package/dist/cjs/routes/data-import.js +54 -54
- package/dist/cjs/routes/data-index-create.js +42 -42
- package/dist/cjs/routes/data-index-delete.js +33 -33
- package/dist/cjs/routes/data-index-list.js +31 -31
- package/dist/cjs/routes/data-query.js +80 -70
- package/dist/cjs/routes/data-reflect.js +97 -86
- package/dist/cjs/routes/data-schema-get.js +36 -36
- package/dist/cjs/routes/data-schema-set.js +30 -30
- package/dist/cjs/routes/data-schema-test.js +43 -43
- package/dist/cjs/routes/data-schemas-list.js +32 -32
- package/dist/cjs/routes/data-set.js +85 -75
- package/dist/cjs/routes/data-sync-changes.js +81 -67
- package/dist/cjs/routes/data-sync-mutations.js +81 -67
- package/dist/cjs/routes/data-transaction.js +159 -139
- package/dist/cjs/routes/data-update.js +86 -75
- package/dist/cjs/routes/data.js +62 -62
- package/dist/cjs/routes/docs.js +258 -251
- package/dist/cjs/routes/meta-info.js +63 -63
- package/dist/cjs/routes/meta-logs.js +49 -49
- package/dist/cjs/routes/meta-ping.js +11 -11
- package/dist/cjs/routes/meta-stats.js +27 -27
- package/dist/cjs/routes/meta.js +19 -19
- package/dist/cjs/routes/oauth2-init.js +54 -54
- package/dist/cjs/routes/oauth2-refresh.js +42 -42
- package/dist/cjs/routes/oauth2-signin.js +265 -265
- package/dist/cjs/routes/webmanager.js +26 -26
- package/dist/cjs/rules.js +380 -167
- package/dist/cjs/sandbox.js +28 -0
- package/dist/cjs/schema/user.js +24 -24
- package/dist/cjs/server.js +415 -407
- package/dist/cjs/settings/email.js +2 -2
- package/dist/cjs/settings/index.js +175 -172
- package/dist/cjs/shared/clients.js +26 -26
- package/dist/cjs/shared/email.js +2 -2
- package/dist/cjs/shared/env.js +2 -2
- package/dist/cjs/shared/error.js +33 -33
- package/dist/cjs/shared/http.js +28 -28
- package/dist/cjs/shared/password.js +45 -45
- package/dist/cjs/shared/rootpath.js +16 -16
- package/dist/cjs/shared/signin.js +143 -143
- package/dist/cjs/shared/simple-fetch.js +76 -76
- package/dist/cjs/shared/tokens.js +79 -79
- package/dist/cjs/shared/validate.js +61 -61
- package/dist/cjs/start.js +53 -53
- package/dist/cjs/test.js +10 -10
- package/dist/cjs/websocket/index.js +331 -319
- package/dist/cjs/websocket/manager.js +15 -15
- package/dist/cjs/websocket/socket.io.js +76 -76
- package/dist/esm/auth.js +75 -75
- package/dist/esm/cluster.js +54 -54
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +4 -4
- package/dist/esm/logger.js +51 -51
- package/dist/esm/middleware/404.js +10 -10
- package/dist/esm/middleware/admin-only.js +24 -24
- package/dist/esm/middleware/cache.js +10 -10
- package/dist/esm/middleware/connection.js +45 -45
- package/dist/esm/middleware/context.js +16 -16
- package/dist/esm/middleware/cors.js +44 -44
- package/dist/esm/middleware/swagger.js +13 -13
- package/dist/esm/middleware/user.js +44 -44
- package/dist/esm/oauth-providers/dropbox.js +90 -90
- package/dist/esm/oauth-providers/facebook.js +66 -66
- package/dist/esm/oauth-providers/google.js +96 -96
- package/dist/esm/oauth-providers/index.js +18 -18
- package/dist/esm/oauth-providers/instagram.js +61 -61
- package/dist/esm/oauth-providers/oauth-provider.js +16 -16
- package/dist/esm/oauth-providers/spotify.js +92 -92
- package/dist/esm/routes/auth-change-password.js +72 -72
- package/dist/esm/routes/auth-delete.js +37 -37
- package/dist/esm/routes/auth-forgot-password.js +62 -62
- package/dist/esm/routes/auth-reset-password.js +81 -81
- package/dist/esm/routes/auth-signin.js +33 -33
- package/dist/esm/routes/auth-signout.js +47 -47
- package/dist/esm/routes/auth-signup.js +127 -127
- package/dist/esm/routes/auth-state.js +12 -12
- package/dist/esm/routes/auth-update.js +116 -116
- package/dist/esm/routes/auth-verify-email.js +57 -57
- package/dist/esm/routes/auth.js +53 -50
- package/dist/esm/routes/data-exists.js +20 -20
- package/dist/esm/routes/data-export.js +35 -35
- package/dist/esm/routes/data-get.js +56 -52
- package/dist/esm/routes/data-import.js +41 -41
- package/dist/esm/routes/data-index-create.js +28 -28
- package/dist/esm/routes/data-index-delete.js +20 -20
- package/dist/esm/routes/data-index-list.js +18 -18
- package/dist/esm/routes/data-query.js +66 -56
- package/dist/esm/routes/data-reflect.js +83 -72
- package/dist/esm/routes/data-schema-get.js +23 -23
- package/dist/esm/routes/data-schema-set.js +17 -17
- package/dist/esm/routes/data-schema-test.js +29 -29
- package/dist/esm/routes/data-schemas-list.js +19 -19
- package/dist/esm/routes/data-set.js +70 -60
- package/dist/esm/routes/data-sync-changes.js +67 -53
- package/dist/esm/routes/data-sync-mutations.js +67 -53
- package/dist/esm/routes/data-transaction.js +142 -123
- package/dist/esm/routes/data-update.js +71 -60
- package/dist/esm/routes/data.js +58 -58
- package/dist/esm/routes/docs.js +252 -245
- package/dist/esm/routes/meta-info.js +59 -59
- package/dist/esm/routes/meta-logs.js +35 -35
- package/dist/esm/routes/meta-ping.js +7 -7
- package/dist/esm/routes/meta-stats.js +14 -14
- package/dist/esm/routes/meta.js +15 -15
- package/dist/esm/routes/oauth2-init.js +41 -41
- package/dist/esm/routes/oauth2-refresh.js +29 -29
- package/dist/esm/routes/oauth2-signin.js +251 -251
- package/dist/esm/routes/webmanager.js +22 -22
- package/dist/esm/rules.js +374 -163
- package/dist/esm/sandbox.js +12 -0
- package/dist/esm/schema/user.js +19 -19
- package/dist/esm/server.js +395 -387
- package/dist/esm/settings/email.js +1 -1
- package/dist/esm/settings/index.js +168 -165
- package/dist/esm/shared/clients.js +22 -22
- package/dist/esm/shared/email.js +1 -1
- package/dist/esm/shared/env.js +1 -1
- package/dist/esm/shared/error.js +25 -25
- package/dist/esm/shared/http.js +22 -22
- package/dist/esm/shared/password.js +38 -38
- package/dist/esm/shared/rootpath.js +13 -13
- package/dist/esm/shared/signin.js +128 -128
- package/dist/esm/shared/simple-fetch.js +59 -59
- package/dist/esm/shared/tokens.js +72 -72
- package/dist/esm/shared/validate.js +41 -41
- package/dist/esm/start.js +50 -50
- package/dist/esm/test.js +8 -8
- package/dist/esm/websocket/index.js +313 -302
- package/dist/esm/websocket/manager.js +11 -11
- package/dist/esm/websocket/socket.io.js +71 -71
- package/dist/types/auth.d.ts +3 -3
- package/dist/types/cluster.d.ts +1 -1
- package/dist/types/index.d.ts +4 -4
- package/dist/types/logger.d.ts +35 -35
- package/dist/types/middleware/404.d.ts +7 -7
- package/dist/types/middleware/admin-only.d.ts +19 -19
- package/dist/types/middleware/cache.d.ts +3 -3
- package/dist/types/middleware/connection.d.ts +7 -7
- package/dist/types/middleware/context.d.ts +3 -3
- package/dist/types/middleware/cors.d.ts +25 -25
- package/dist/types/middleware/swagger.d.ts +3 -3
- package/dist/types/middleware/user.d.ts +2 -2
- package/dist/types/oauth-providers/dropbox.d.ts +52 -52
- package/dist/types/oauth-providers/facebook.d.ts +41 -41
- package/dist/types/oauth-providers/google.d.ts +43 -43
- package/dist/types/oauth-providers/index.d.ts +10 -10
- package/dist/types/oauth-providers/instagram.d.ts +50 -50
- package/dist/types/oauth-providers/oauth-provider.d.ts +74 -74
- package/dist/types/oauth-providers/spotify.d.ts +53 -53
- package/dist/types/routes/auth-change-password.d.ts +20 -20
- package/dist/types/routes/auth-delete.d.ts +16 -16
- package/dist/types/routes/auth-forgot-password.d.ts +16 -16
- package/dist/types/routes/auth-reset-password.d.ts +23 -23
- package/dist/types/routes/auth-signin.d.ts +24 -24
- package/dist/types/routes/auth-signout.d.ts +14 -14
- package/dist/types/routes/auth-signup.d.ts +32 -32
- package/dist/types/routes/auth-state.d.ts +13 -13
- package/dist/types/routes/auth-update.d.ts +33 -33
- package/dist/types/routes/auth-verify-email.d.ts +21 -21
- package/dist/types/routes/auth.d.ts +6 -6
- package/dist/types/routes/data-exists.d.ts +9 -9
- package/dist/types/routes/data-export.d.ts +10 -10
- package/dist/types/routes/data-get.d.ts +14 -14
- package/dist/types/routes/data-import.d.ts +13 -13
- package/dist/types/routes/data-index-create.d.ts +51 -51
- package/dist/types/routes/data-index-delete.d.ts +17 -17
- package/dist/types/routes/data-index-list.d.ts +21 -21
- package/dist/types/routes/data-query.d.ts +49 -49
- package/dist/types/routes/data-reflect.d.ts +29 -29
- package/dist/types/routes/data-schema-get.d.ts +11 -11
- package/dist/types/routes/data-schema-set.d.ts +19 -19
- package/dist/types/routes/data-schema-test.d.ts +19 -19
- package/dist/types/routes/data-schemas-list.d.ts +11 -11
- package/dist/types/routes/data-set.d.ts +27 -27
- package/dist/types/routes/data-sync-changes.d.ts +25 -28
- package/dist/types/routes/data-sync-mutations.d.ts +25 -28
- package/dist/types/routes/data-transaction.d.ts +34 -34
- package/dist/types/routes/data-update.d.ts +27 -27
- package/dist/types/routes/data.d.ts +3 -3
- package/dist/types/routes/docs.d.ts +3 -3
- package/dist/types/routes/meta-info.d.ts +11 -11
- package/dist/types/routes/meta-logs.d.ts +20 -20
- package/dist/types/routes/meta-ping.d.ts +7 -7
- package/dist/types/routes/meta-stats.d.ts +13 -13
- package/dist/types/routes/meta.d.ts +3 -3
- package/dist/types/routes/oauth2-init.d.ts +13 -13
- package/dist/types/routes/oauth2-refresh.d.ts +17 -17
- package/dist/types/routes/oauth2-signin.d.ts +15 -15
- package/dist/types/routes/webmanager.d.ts +3 -3
- package/dist/types/rules.d.ts +73 -34
- package/dist/types/sandbox.d.ts +3 -0
- package/dist/types/schema/user.d.ts +85 -85
- package/dist/types/server.d.ts +117 -111
- package/dist/types/settings/email.d.ts +14 -14
- package/dist/types/settings/index.d.ts +195 -187
- package/dist/types/shared/clients.d.ts +46 -46
- package/dist/types/shared/email.d.ts +34 -34
- package/dist/types/shared/env.d.ts +47 -44
- package/dist/types/shared/error.d.ts +15 -15
- package/dist/types/shared/http.d.ts +22 -21
- package/dist/types/shared/password.d.ts +19 -19
- package/dist/types/shared/rootpath.d.ts +2 -2
- package/dist/types/shared/signin.d.ts +31 -31
- package/dist/types/shared/simple-fetch.d.ts +21 -21
- package/dist/types/shared/tokens.d.ts +24 -24
- package/dist/types/shared/validate.d.ts +22 -22
- package/dist/types/start.d.ts +1 -1
- package/dist/types/test.d.ts +1 -1
- package/dist/types/websocket/index.d.ts +6 -6
- package/dist/types/websocket/manager.d.ts +99 -99
- package/dist/types/websocket/socket.io.d.ts +10 -10
- package/package.json +4 -4
- package/src/routes/data-set.yaml +5 -5
- package/src/routes/data-update.yaml +4 -4
package/README.md
CHANGED
|
@@ -93,7 +93,7 @@ The following `authentication` settings are available:
|
|
|
93
93
|
|
|
94
94
|
### Setup authorization rules
|
|
95
95
|
|
|
96
|
-
If you enabled authentication, you can also define access rules for your data. Using rules, you can allow or deny specific (or anonymous) users
|
|
96
|
+
If you enabled authentication, you can also define access rules for your data. Using rules, you can allow or deny specific (or anonymous) users _read_ and/or _write_ access to your data. These rules are identical to those used by [Firebase](https://firebase.google.com/docs/database/security/), but reading current data in the db works a little differently. In addition, ".schema" rules allow for an easy and clean way to validate data being written, while ".validate" rules allow you to check existing data and use more advanced business logic. The rules are saved in a file called _rules.json_ in your database directory, but can be overridden and extended programmatically (see [Coding your rules](#coding-your-rules)). The default rules written to the file are determined by the `defaultAccessRule` authentication setting at the first server launch with `authentication` enabled.
|
|
97
97
|
|
|
98
98
|
The default _rules.json_ file content is based on the value of the `defaultAccessRule` setting, possible values are:
|
|
99
99
|
* `"auth"`: Only allow authenticated users read/write access to the database
|
|
@@ -112,7 +112,7 @@ When `defaultAccessRule: "auth"` is used, it will generate the following _rules.
|
|
|
112
112
|
|
|
113
113
|
When `"allow"` or `"deny"` is used, the `".read"` and `".write"` properties will be set to `true` or `false` respectively.
|
|
114
114
|
|
|
115
|
-
If you want to further restrict what data users can
|
|
115
|
+
If you want to further restrict what data users can _read_ and/or _write_ to (RECOMMENDED!), you could edit the file as such, granting users _read_/_write_ access to their own user node:
|
|
116
116
|
```json
|
|
117
117
|
{
|
|
118
118
|
"rules": {
|
|
@@ -126,7 +126,9 @@ If you want to further restrict what data users can access and/or write to (RECO
|
|
|
126
126
|
}
|
|
127
127
|
```
|
|
128
128
|
|
|
129
|
-
NOTE: Just like Firebase, access is denied by default
|
|
129
|
+
NOTE: Just like Firebase, access is denied by default if no rule is found for a target path. If an access rule is found at any location in the path, it will be used for any child path UNLESS your rule returns "cascade" (v1.17.0+). This means that, unlike Firebase, _read_ and/or _write_ access for child/descending paths CAN be overridden if you need to. "cascade" simply instructs the rule parser to postpone the decision making if the request is made on a child path, which is essentially as if there was no rule set for the current path. If the request is made on the rule path itself though, "cascade" will deny access because it is the last rule to execute and no access was granted.
|
|
130
|
+
|
|
131
|
+
For example, if you want to allow users _read_ access to a path, and _write_ access only for specific child path(s), use the following rules:
|
|
130
132
|
|
|
131
133
|
```json
|
|
132
134
|
{
|
|
@@ -143,13 +145,110 @@ NOTE: Just like Firebase, access is denied by default when no rule is found for
|
|
|
143
145
|
}
|
|
144
146
|
```
|
|
145
147
|
Above rules enforces:
|
|
146
|
-
* No
|
|
147
|
-
*
|
|
148
|
-
*
|
|
148
|
+
* No _read_ or _write_ access to the root node or any child for anyone. (No rule has been set for those nodes, access will be denied)
|
|
149
|
+
* _Read_ access to all reviews for specific shops ('shop_reviews/shop1', 'shop_reviews/shop2') for anyone, including unauthenticated clients (`".read"` rule is set to `true`)
|
|
150
|
+
* _Write_ access to an authenticated user's own review for any shop. (`".write"` rule is set to `"auth.uid === $uid"`)
|
|
151
|
+
|
|
152
|
+
If you want to allow a specific user _read_/_write_ access to a path, and only _read_ access to a specific child path for all other users:
|
|
153
|
+
```json
|
|
154
|
+
{
|
|
155
|
+
"rules": {
|
|
156
|
+
"users": {
|
|
157
|
+
"$uid": {
|
|
158
|
+
".read": "auth?.uid === $uid ? 'allow' : 'cascade'",
|
|
159
|
+
".write": "auth.uid === $uid",
|
|
160
|
+
"public": {
|
|
161
|
+
".read": true
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
```
|
|
168
|
+
Above rules enforces:
|
|
169
|
+
* No _read_ or _write_ access to the root node or any child for anyone. (No rule has been set for those nodes, access will be denied)
|
|
170
|
+
* _Read_ access for an authenticated user's own data in "users/$uid", including all child data
|
|
171
|
+
* No _read_ access for unauthenticated users and/or other users to "users/$uid", undecided _read_ access (`'cascade'`) for child paths. NOTE `auth?.uid` needs the `?.` to allow unauthenticated users to cascade - if rule execution fails it ALWAYS denies access.
|
|
172
|
+
* _Read_ access for everyone to "users/$uid/public" (if `users/$uid/.read` cascaded, `users/$uid/public/.read` is `true`)
|
|
173
|
+
* _Write_ access to an authenticated user's own data in "users/$uid" and all child data (`".write"` rule is set to `"auth.uid === $uid"`)
|
|
174
|
+
|
|
175
|
+
NOTE that `"allow"` can be returned from a rule function instead of `true`, and `"deny"` instead of `false`, `undefined` or other _falsy_ values.
|
|
176
|
+
|
|
177
|
+
### Rule environment variables and functions
|
|
178
|
+
_(NEW v1.17.0+)_
|
|
179
|
+
|
|
180
|
+
Besides the `auth` variable used in above examples, there are other variables and functions you can use in your rule definitions. You can use these to determine if the data to be read or written conforms to your business logic. The following variables and functions are available in your `.read` and `.write` rules:
|
|
181
|
+
* `auth`: The currently signed in user (or `null` for anonymous access)
|
|
182
|
+
* `now`: a `number` with the current time in ms (you can also use `Date.now()`)
|
|
183
|
+
* `path`: a `string` containing the current path being read/written
|
|
184
|
+
* `operation`: one of the following values:
|
|
185
|
+
* _read_ operations `'get'`, `'reflect'`, `'exists'`, `'query'`, `'export'`
|
|
186
|
+
* _write_ operations `'update'`, `'set'`, `'delete'`, `'transact'`, `'import'`
|
|
187
|
+
* `data`: data being written to the target, only available in `.validate` rules for `'update'` and `'set'` _write_ operations. Read more about `'.validate'` rules [here](#validate-data-being-written)
|
|
188
|
+
* `context`: contextual data that was passed along with _write_ operations in client code.
|
|
189
|
+
* `value`: an asynchronous function that gets a value from the database at a relative (`./property`, `../other/property`) or absolute (`/collection/item`) path. You can use this to check any existing data in the database to determine if the operation is allowed. For example, use `await value('./locked') !== true` to check if the `locked` property of the current target path is not set to `true`. It's possible to selectively load data from the given path by passing an additional `include` argument: `const contributors = await value('invoices', ['*/paid']); const allow = Object.keys(invoices).every(id => invoices[id].paid === true); return allow;`: this only allows access if all of the linked `invoices` have been paid.
|
|
190
|
+
* `exists`: an asynchronous function that checks if the value of a relative (`./property`) or absolute (`/collection/item`) path currently exists in the database. For example, you can use `await exists('./authors/' + auth.uid)` to check if current user is one of the authors of an item being written to.
|
|
191
|
+
* `$variable`: the value of a variable in your rules path. If the rule is set on path `posts/$postId` and the path being updated is `posts/lcoq4mnp000008mkaqk9hx9d`, then `$postId` will be `lcoq4mnp000008mkaqk9hx9d`
|
|
192
|
+
|
|
193
|
+
Note that instead of using the `operation` variable, you can also specify specific rules for each operation: the rules `".write": "true", ".set": "auth.uid !== null"` allow all users to write data to nested paths, but restrict `set` operation to signed in users only. The same can be done with a single `write` rule: `".write": "operation !== 'set' || auth.uid !== null"` or more verbose: `".write": "if (operation !== 'set') { return true; } else { return auth.uid !== null }"`
|
|
194
|
+
|
|
195
|
+
Remember that above rules cascade to child paths, and are therefore enforced for all data being read from or written to child/descendant paths - once a rule allows or denies access, this cannot be overridden by rules defined on nested child paths. The only exception to this are `.validate` rules that are evaluated on the target paths being read from or written to. If a parent `.write` rule allows access, a `.validate` rule on the target path is still able to deny access.
|
|
196
|
+
|
|
197
|
+
### Validate data being written
|
|
198
|
+
_(NEW v1.17.0+)_
|
|
199
|
+
|
|
200
|
+
In addition to the read/write rules explained above, AceBase now supports defining `.validate` rules. In contrast to `.read` and `.write` rules, `.validate` rules do not cascade and are enforced on the target path only. This allows you to validate the data being written to specific paths. `.validate` rules are executed after verifying that a `.write` rule grants access. They fully support JavaScript, so you can use the same checks you'd use in client side code to validate your data with. As a general rule, use `.validate` rules only if you have to perform checks that `.schema` rules can't handle, such as using current data in the database, or advanced type checks such as string length.
|
|
201
|
+
|
|
202
|
+
The following additional variables are available to `'.validate'` rules:
|
|
203
|
+
* `data`: data being written to the target for `'update'` and `'set'` _write_ operations. `'transact'` operations are executed in 2 steps: a `'get'` _read_ operation, followed by a `'set'` _write_ operation. Note that `'import'` operations use streaming updates and their data cannot be validated with `'.validate'` rules before they are stored to the database; use `'.schema'` rules to validate data being imported, or deny imports altogether using `if (operation === 'import') { return 'deny' }` in your `.write` rule, or by simply setting `{ ".import": false }`.
|
|
204
|
+
|
|
205
|
+
NOTE: keep in mind that the `value` for `'update'` operations are partial objects to update the existing stored value with. If your `.validate` rule checks for property existence or their values, make sure you allow missing properties if the operation is `'update'` (or use a `.schema` rule instead)
|
|
206
|
+
|
|
207
|
+
Example: validate writes to _/widget_
|
|
208
|
+
```json
|
|
209
|
+
{
|
|
210
|
+
"rules": {
|
|
211
|
+
"widget": {
|
|
212
|
+
".write": true,
|
|
213
|
+
// a valid widget must have attributes "color" and "size", but ignore update operations (partial objects!)
|
|
214
|
+
".validate": "operation === 'update' || ('color' in data && 'size' in data)",
|
|
215
|
+
"size": {
|
|
216
|
+
// the value of "size" must be a number between 0 and 99
|
|
217
|
+
".validate": "typeof data === 'number' && data >= 0 && data <= 99"
|
|
218
|
+
},
|
|
219
|
+
"color": {
|
|
220
|
+
// the value of "color" must exist as a key in /valid_colors (eg /valid_colors/black)
|
|
221
|
+
".validate": "typeof data === 'string' && await exists(`/valid_colors/${data}`)"
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
The above example could be combined with `.schema` rules to make these checks easier. See [Schema validation](#schema-validation) below for more info.
|
|
229
|
+
```json
|
|
230
|
+
{
|
|
231
|
+
"rules": {
|
|
232
|
+
"widget": {
|
|
233
|
+
".write": true,
|
|
234
|
+
// add required "color" and "size" types to schema definition
|
|
235
|
+
".schema": "{ color: string; size: number }",
|
|
236
|
+
"size": {
|
|
237
|
+
// the value of "size" must be a number between 0 and 99
|
|
238
|
+
".validate": "data >= 0 && data <= 99"
|
|
239
|
+
},
|
|
240
|
+
"color": {
|
|
241
|
+
// the value of "color" must exist as a key in /valid_colors (eg /valid_colors/black)
|
|
242
|
+
".validate": "await exists(`/valid_colors/${data}`)"
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
```
|
|
149
248
|
|
|
150
249
|
### Schema validation
|
|
151
250
|
|
|
152
|
-
AceBase server
|
|
251
|
+
AceBase server supports TypeScript-like schema definitions and validation. Once you've defined a schema for a path, all data being written must adhere to the set schema. Data to be stored/updated will be validated against the schema and denied or allowed accordingly.
|
|
153
252
|
|
|
154
253
|
There are 2 ways to can add schemas:
|
|
155
254
|
- In your `rules.json` file, see below.
|
|
@@ -231,6 +330,49 @@ And, if you prefer, schema definitions can be defined as strings instead:
|
|
|
231
330
|
}
|
|
232
331
|
```
|
|
233
332
|
|
|
333
|
+
## Coding your rules
|
|
334
|
+
_(NEW v1.17.0+)_
|
|
335
|
+
|
|
336
|
+
Instead of writing your rules into the `rules.json` file on your server, it is also possible to configure them in your code. Any rule you set with code will override or augment existing rules found in the `rules.json` file, so can use both. Coding your rules has a number of advantages:
|
|
337
|
+
* You can use the same rule definitions and functions on multiple paths without copy/pasting
|
|
338
|
+
* You can code them in your favorite editor
|
|
339
|
+
* You can use running server values and cached data in your rules, such as `process.env` and vars like `maintanceMode`
|
|
340
|
+
* Rules become debuggable!
|
|
341
|
+
|
|
342
|
+
To add a rule in your code, use the following syntax:
|
|
343
|
+
```js
|
|
344
|
+
server.setRule(path, ruleTypes, async (env) => { /* your rule code */ });
|
|
345
|
+
```
|
|
346
|
+
where:
|
|
347
|
+
* `path` is the exact database path to set the rule, such as `'users/$uid'`, or an array of paths.
|
|
348
|
+
* `ruleTypes` is either 1 rule type like `read`, or multiple in an array like `['read', 'write']`
|
|
349
|
+
|
|
350
|
+
The callback function is an `async` function that receives all available environment variables in the `env` argument: `env.auth` will contain the `auth` object, `env.vars` the `vars` object etc. If you use the ES6 destructuring syntax, you can use the same rule syntax from your `rules.json` file: `async ({ auth }) => auth !== null`
|
|
351
|
+
|
|
352
|
+
It is best to setup your rules while AceBase Server is starting up, before it is accepting connections. To do this, you can pass an `init` callback function to the server settings that is executed right before the http server is started:
|
|
353
|
+
|
|
354
|
+
```js
|
|
355
|
+
const server = new AceBaseServer('mydb', {
|
|
356
|
+
host: 'localhost',
|
|
357
|
+
port: 4000,
|
|
358
|
+
// ...
|
|
359
|
+
async init(server) {
|
|
360
|
+
// Allow read and write access to users' own data
|
|
361
|
+
server.setRule('users/$uid', ['read', 'write'], ({ auth, vars }) => auth.uid === vars.$uid);
|
|
362
|
+
|
|
363
|
+
// Limit user status to either 'online' or 'offline'
|
|
364
|
+
server.setRule('users/$uid/status', 'validate', ({ data }) => ['online', 'offline'].includes(data));
|
|
365
|
+
|
|
366
|
+
// Only allow following existing users
|
|
367
|
+
server.setRule('users/$uid/following/$otherUid', 'validate', async ({ vars, exists }) => await exists(`/users/${vars.$otherUid}`));
|
|
368
|
+
}
|
|
369
|
+
});
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
NOTE that you can use the `env.vars` object to get access to the values of named wildcards in your database paths. The values are also exposed as `env.$name`, but you can't use them this way in TypeScript because they can't be predefined in the `env` type.
|
|
373
|
+
|
|
374
|
+
NOTE now this `init` method is available, is is advisable to also move any `server.extend`, `server.db.schema.set`, `server.configAuthProvider` and `server.router.get` etc calls you'd have here!
|
|
375
|
+
|
|
234
376
|
## Sending user e-mails [NEW]
|
|
235
377
|
|
|
236
378
|
If your app allows users to sign up, you'll need a way to verify their e-mail addresses, send welcome and password reset e-mails etc. AceBase Server does not send the e-mails itself (yet), but provides a way to handle this yourself:
|
|
@@ -435,6 +577,34 @@ db.ref('uploads/images').on('child_added', async snap => {
|
|
|
435
577
|
|
|
436
578
|
## Extending the server API
|
|
437
579
|
|
|
580
|
+
To extend the server's endpoints, there are 2 options:
|
|
581
|
+
* Use `server.router.get` and `server.router.post` etc to add custom Express endpoints to the server.
|
|
582
|
+
* Use `server.extend` to create an endpoint that can be called by an AceBaseClient using `client.callExtension`
|
|
583
|
+
|
|
584
|
+
### Using Express router
|
|
585
|
+
|
|
586
|
+
Simply add your routes with `server.router.get`, `.put`, `.post` etc. You can use `req.user` to check if it is an authenticated request - your client code must add the `Authorization: Bearer [token]` header to requests in order for this to work.
|
|
587
|
+
```js
|
|
588
|
+
server.router.get('/membersonly', (req, res) => {
|
|
589
|
+
if (!req.user) {
|
|
590
|
+
return res.status(403).send('Members only');
|
|
591
|
+
}
|
|
592
|
+
res.send(`Welcome ${req.user.display_name}`);
|
|
593
|
+
});
|
|
594
|
+
```
|
|
595
|
+
|
|
596
|
+
If you want to create your own router to bind custom routes to:
|
|
597
|
+
```js
|
|
598
|
+
const myRouter = server.app.createRouter();
|
|
599
|
+
// Bind the new router to /myroutes
|
|
600
|
+
server.router.use('/myroutes', myRouter);
|
|
601
|
+
// Add routes to own router
|
|
602
|
+
myRouter.get('custom1', handleMethod1); // /myroutes/custom1
|
|
603
|
+
myRouter.get('custom2', handleMethod1); // /myroutes/custom2
|
|
604
|
+
```
|
|
605
|
+
|
|
606
|
+
### Using `server.extend`
|
|
607
|
+
|
|
438
608
|
You can add your own custom API functions to the server with the `server.extend(method, path, handler)` method:
|
|
439
609
|
|
|
440
610
|
```javascript
|
|
@@ -443,15 +613,15 @@ await server.ready();
|
|
|
443
613
|
|
|
444
614
|
const _quotes = [...];
|
|
445
615
|
server.extend('get', 'quotes/random', (req, res) => {
|
|
446
|
-
|
|
616
|
+
const index = Math.round(Math.random() * _quotes.length);
|
|
447
617
|
res.send(quotes[index]);
|
|
448
618
|
});
|
|
449
619
|
server.extend('get', 'quotes/specific', (req, res) => {
|
|
450
|
-
|
|
620
|
+
const index = req.query.index;
|
|
451
621
|
res.send(quotes[index]);
|
|
452
622
|
});
|
|
453
623
|
server.extend('post', 'quotes/add', (req, res) => {
|
|
454
|
-
|
|
624
|
+
const quote = {
|
|
455
625
|
text: req.body.text,
|
|
456
626
|
author: req.body.author
|
|
457
627
|
};
|
package/build-vars.js
CHANGED
|
@@ -3,7 +3,8 @@ const { readFileSync, writeFileSync } = require('fs');
|
|
|
3
3
|
const { execSync } = require('child_process');
|
|
4
4
|
const packageInfo = require('./package.json');
|
|
5
5
|
|
|
6
|
-
const
|
|
6
|
+
const sources = ['routes/meta-info', 'routes/docs'];
|
|
7
|
+
const files = sources.reduce((all ,file) => (all.push(`./dist/cjs/${file}.js`, `./dist/esm/${file}.js`), all), []);
|
|
7
8
|
files.forEach(file => {
|
|
8
9
|
const originalContent = readFileSync(file, 'utf8');
|
|
9
10
|
content = originalContent.replace(/%SERVER_VERSION%/g, packageInfo.version);
|
package/dist/cjs/auth.js
CHANGED
|
@@ -1,89 +1,89 @@
|
|
|
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.setupAuthentication = void 0;
|
|
13
|
-
const acebase_core_1 = require("acebase-core");
|
|
14
|
-
const crypto_1 = require("crypto");
|
|
15
|
-
const password_1 = require("./shared/password");
|
|
16
|
-
const setupAuthentication = (env) => __awaiter(void 0, void 0, void 0, function* () {
|
|
17
|
-
// Setup auth cache
|
|
18
|
-
env.authCache = new acebase_core_1.SimpleCache({ expirySeconds: 300, cloneValues: false, maxEntries: 1000 });
|
|
19
|
-
// Get or generate a salt to hash public tokens with
|
|
20
|
-
yield env.securityRef.child('token_salt').transaction(snap => {
|
|
21
|
-
env.tokenSalt = snap.val();
|
|
22
|
-
if (!env.tokenSalt) {
|
|
23
|
-
const length = 256;
|
|
24
|
-
env.tokenSalt = (0, crypto_1.randomBytes)(Math.ceil(length / 2)).toString('hex').slice(0, length);
|
|
25
|
-
return env.tokenSalt;
|
|
26
|
-
}
|
|
27
|
-
});
|
|
28
|
-
// Setup admin account
|
|
29
|
-
yield env.authRef.child('admin').transaction(snap => {
|
|
30
|
-
let adminAccount = snap.val();
|
|
31
|
-
if (adminAccount === null) {
|
|
32
|
-
// Use provided default password, or generate one:
|
|
33
|
-
const adminPassword = env.config.auth.defaultAdminPassword || (0, password_1.generatePassword)();
|
|
34
|
-
const pwd = (0, password_1.createPasswordHash)(adminPassword);
|
|
35
|
-
adminAccount = {
|
|
36
|
-
uid: null,
|
|
37
|
-
username: 'admin',
|
|
38
|
-
email: null,
|
|
39
|
-
display_name: `${env.db.name} AceBase admin`,
|
|
40
|
-
password: pwd.hash,
|
|
41
|
-
password_salt: pwd.salt,
|
|
42
|
-
change_password: true,
|
|
43
|
-
created: new Date(),
|
|
44
|
-
access_token: null,
|
|
45
|
-
settings: {},
|
|
46
|
-
};
|
|
47
|
-
env.debug.warn(`__________________________________________________________________`.colorize(acebase_core_1.ColorStyle.red));
|
|
48
|
-
env.debug.warn(``.colorize(acebase_core_1.ColorStyle.red));
|
|
49
|
-
env.debug.warn(`IMPORTANT: Admin account created`.colorize(acebase_core_1.ColorStyle.red));
|
|
50
|
-
env.debug.warn(`You need the admin account to remotely administer the database`.colorize(acebase_core_1.ColorStyle.red));
|
|
51
|
-
env.debug.warn(`Use the following credentials to authenticate an AceBaseClient:`.colorize(acebase_core_1.ColorStyle.red));
|
|
52
|
-
env.debug.warn(``);
|
|
53
|
-
env.debug.warn(` username: admin`.colorize(acebase_core_1.ColorStyle.red));
|
|
54
|
-
env.debug.warn(` password: ${adminPassword}`.colorize(acebase_core_1.ColorStyle.red));
|
|
55
|
-
env.debug.warn(``);
|
|
56
|
-
env.debug.warn(`THIS IS ONLY SHOWN ONCE!`.colorize(acebase_core_1.ColorStyle.red));
|
|
57
|
-
env.debug.warn(`__________________________________________________________________`.colorize(acebase_core_1.ColorStyle.red));
|
|
58
|
-
return adminAccount; // Save it
|
|
59
|
-
}
|
|
60
|
-
else if (env.config.auth.defaultAdminPassword) {
|
|
61
|
-
// Check if the default password was changed
|
|
62
|
-
let passwordHash;
|
|
63
|
-
if (!adminAccount.password_salt) {
|
|
64
|
-
// Old md5 password hash?
|
|
65
|
-
passwordHash = (0, password_1.getOldPasswordHash)(env.config.auth.defaultAdminPassword);
|
|
66
|
-
}
|
|
67
|
-
else {
|
|
68
|
-
passwordHash = (0, password_1.getPasswordHash)(env.config.auth.defaultAdminPassword, adminAccount.password_salt);
|
|
69
|
-
}
|
|
70
|
-
if (adminAccount.password === passwordHash) {
|
|
71
|
-
env.debug.warn(`WARNING: default password for admin user was not changed!`.colorize(acebase_core_1.ColorStyle.red));
|
|
72
|
-
if (!adminAccount.password_salt) {
|
|
73
|
-
// Create new password hash
|
|
74
|
-
const pwd = (0, password_1.createPasswordHash)(env.config.auth.defaultAdminPassword);
|
|
75
|
-
adminAccount.password = pwd.hash;
|
|
76
|
-
adminAccount.password_salt = pwd.salt;
|
|
77
|
-
return adminAccount; // Save it
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
});
|
|
82
|
-
// Make sure indexes are present for quick user lookups
|
|
83
|
-
env.authDb.indexes.create(env.authRef.path, 'username');
|
|
84
|
-
env.authDb.indexes.create(env.authRef.path, 'email');
|
|
85
|
-
env.authDb.indexes.create(env.authRef.path, 'access_token');
|
|
86
|
-
});
|
|
87
|
-
exports.setupAuthentication = setupAuthentication;
|
|
88
|
-
exports.default = exports.setupAuthentication;
|
|
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.setupAuthentication = void 0;
|
|
13
|
+
const acebase_core_1 = require("acebase-core");
|
|
14
|
+
const crypto_1 = require("crypto");
|
|
15
|
+
const password_1 = require("./shared/password");
|
|
16
|
+
const setupAuthentication = (env) => __awaiter(void 0, void 0, void 0, function* () {
|
|
17
|
+
// Setup auth cache
|
|
18
|
+
env.authCache = new acebase_core_1.SimpleCache({ expirySeconds: 300, cloneValues: false, maxEntries: 1000 });
|
|
19
|
+
// Get or generate a salt to hash public tokens with
|
|
20
|
+
yield env.securityRef.child('token_salt').transaction(snap => {
|
|
21
|
+
env.tokenSalt = snap.val();
|
|
22
|
+
if (!env.tokenSalt) {
|
|
23
|
+
const length = 256;
|
|
24
|
+
env.tokenSalt = (0, crypto_1.randomBytes)(Math.ceil(length / 2)).toString('hex').slice(0, length);
|
|
25
|
+
return env.tokenSalt;
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
// Setup admin account
|
|
29
|
+
yield env.authRef.child('admin').transaction(snap => {
|
|
30
|
+
let adminAccount = snap.val();
|
|
31
|
+
if (adminAccount === null) {
|
|
32
|
+
// Use provided default password, or generate one:
|
|
33
|
+
const adminPassword = env.config.auth.defaultAdminPassword || (0, password_1.generatePassword)();
|
|
34
|
+
const pwd = (0, password_1.createPasswordHash)(adminPassword);
|
|
35
|
+
adminAccount = {
|
|
36
|
+
uid: null,
|
|
37
|
+
username: 'admin',
|
|
38
|
+
email: null,
|
|
39
|
+
display_name: `${env.db.name} AceBase admin`,
|
|
40
|
+
password: pwd.hash,
|
|
41
|
+
password_salt: pwd.salt,
|
|
42
|
+
change_password: true,
|
|
43
|
+
created: new Date(),
|
|
44
|
+
access_token: null,
|
|
45
|
+
settings: {},
|
|
46
|
+
};
|
|
47
|
+
env.debug.warn(`__________________________________________________________________`.colorize(acebase_core_1.ColorStyle.red));
|
|
48
|
+
env.debug.warn(``.colorize(acebase_core_1.ColorStyle.red));
|
|
49
|
+
env.debug.warn(`IMPORTANT: Admin account created`.colorize(acebase_core_1.ColorStyle.red));
|
|
50
|
+
env.debug.warn(`You need the admin account to remotely administer the database`.colorize(acebase_core_1.ColorStyle.red));
|
|
51
|
+
env.debug.warn(`Use the following credentials to authenticate an AceBaseClient:`.colorize(acebase_core_1.ColorStyle.red));
|
|
52
|
+
env.debug.warn(``);
|
|
53
|
+
env.debug.warn(` username: admin`.colorize(acebase_core_1.ColorStyle.red));
|
|
54
|
+
env.debug.warn(` password: ${adminPassword}`.colorize(acebase_core_1.ColorStyle.red));
|
|
55
|
+
env.debug.warn(``);
|
|
56
|
+
env.debug.warn(`THIS IS ONLY SHOWN ONCE!`.colorize(acebase_core_1.ColorStyle.red));
|
|
57
|
+
env.debug.warn(`__________________________________________________________________`.colorize(acebase_core_1.ColorStyle.red));
|
|
58
|
+
return adminAccount; // Save it
|
|
59
|
+
}
|
|
60
|
+
else if (env.config.auth.defaultAdminPassword) {
|
|
61
|
+
// Check if the default password was changed
|
|
62
|
+
let passwordHash;
|
|
63
|
+
if (!adminAccount.password_salt) {
|
|
64
|
+
// Old md5 password hash?
|
|
65
|
+
passwordHash = (0, password_1.getOldPasswordHash)(env.config.auth.defaultAdminPassword);
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
passwordHash = (0, password_1.getPasswordHash)(env.config.auth.defaultAdminPassword, adminAccount.password_salt);
|
|
69
|
+
}
|
|
70
|
+
if (adminAccount.password === passwordHash) {
|
|
71
|
+
env.debug.warn(`WARNING: default password for admin user was not changed!`.colorize(acebase_core_1.ColorStyle.red));
|
|
72
|
+
if (!adminAccount.password_salt) {
|
|
73
|
+
// Create new password hash
|
|
74
|
+
const pwd = (0, password_1.createPasswordHash)(env.config.auth.defaultAdminPassword);
|
|
75
|
+
adminAccount.password = pwd.hash;
|
|
76
|
+
adminAccount.password_salt = pwd.salt;
|
|
77
|
+
return adminAccount; // Save it
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
// Make sure indexes are present for quick user lookups
|
|
83
|
+
env.authDb.indexes.create(env.authRef.path, 'username');
|
|
84
|
+
env.authDb.indexes.create(env.authRef.path, 'email');
|
|
85
|
+
env.authDb.indexes.create(env.authRef.path, 'access_token');
|
|
86
|
+
});
|
|
87
|
+
exports.setupAuthentication = setupAuthentication;
|
|
88
|
+
exports.default = exports.setupAuthentication;
|
|
89
89
|
//# sourceMappingURL=auth.js.map
|
package/dist/cjs/cluster.js
CHANGED
|
@@ -1,57 +1,57 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
const acebase_1 = require("acebase");
|
|
4
|
-
const server_1 = require("./server");
|
|
5
|
-
const cluster = require("cluster");
|
|
6
|
-
const numCPUs = 2; //os.cpus().length;
|
|
7
|
-
/**
|
|
8
|
-
* Node.js cluster example. You can use this as a reference how to create an AceBaseServer cluster using Node.js'
|
|
9
|
-
* built-in cluster functionality.
|
|
10
|
-
*
|
|
11
|
-
* If you want to run a pm2 or cloud-based cluster instead, do NOT use this code.
|
|
12
|
-
* To do that, see https://github.com/appy-one/acebase-ipc-server
|
|
13
|
-
*
|
|
14
|
-
*/
|
|
15
|
-
const dbname = 'default';
|
|
16
|
-
const options = { /* default options */}; // Load from cluster.config.js!
|
|
17
|
-
options.authentication = { enabled: false };
|
|
18
|
-
options.https = { enabled: false };
|
|
19
|
-
if (cluster.isMaster) {
|
|
20
|
-
// Startup master
|
|
21
|
-
console.log(`Starting database server cluster with ${numCPUs} workers`);
|
|
22
|
-
const master = new acebase_1.AceBase(dbname, options);
|
|
23
|
-
master.once('ready', () => {
|
|
24
|
-
console.log(`Master database server started on process ${process.pid}`);
|
|
25
|
-
});
|
|
26
|
-
for (let i = 0; i < numCPUs; i++) {
|
|
27
|
-
const worker = cluster.fork();
|
|
28
|
-
worker.on('disconnect', () => {
|
|
29
|
-
console.error(`worker ${worker.process.pid} disconnected`);
|
|
30
|
-
});
|
|
31
|
-
worker.on('message', (msg) => {
|
|
32
|
-
if (msg === 'acebase-server-shutdown') {
|
|
33
|
-
// We could handle shutdown message here to kill the worker safely, but we'll do it in the worker threads instead: see below
|
|
34
|
-
// worker.kill();
|
|
35
|
-
}
|
|
36
|
-
});
|
|
37
|
-
}
|
|
38
|
-
cluster.on('exit', (worker, code, signal) => {
|
|
39
|
-
console.error(`worker ${worker.process.pid} died`);
|
|
40
|
-
});
|
|
41
|
-
}
|
|
42
|
-
else {
|
|
43
|
-
console.log(`Worker ${process.pid} is running`);
|
|
44
|
-
const server = new server_1.AceBaseServer(dbname, options);
|
|
45
|
-
server.ready(() => {
|
|
46
|
-
console.log(`Worker database server started on process ${process.pid}`);
|
|
47
|
-
});
|
|
48
|
-
// Handle shutdown event to exit the worker process safely
|
|
49
|
-
server.on('shutdown', () => {
|
|
50
|
-
process.exit();
|
|
51
|
-
});
|
|
52
|
-
// Other option:
|
|
53
|
-
// process.on('acebase-server-shutdown', () => {
|
|
54
|
-
// process.exit();
|
|
55
|
-
// });
|
|
56
|
-
}
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const acebase_1 = require("acebase");
|
|
4
|
+
const server_1 = require("./server");
|
|
5
|
+
const cluster = require("cluster");
|
|
6
|
+
const numCPUs = 2; //os.cpus().length;
|
|
7
|
+
/**
|
|
8
|
+
* Node.js cluster example. You can use this as a reference how to create an AceBaseServer cluster using Node.js'
|
|
9
|
+
* built-in cluster functionality.
|
|
10
|
+
*
|
|
11
|
+
* If you want to run a pm2 or cloud-based cluster instead, do NOT use this code.
|
|
12
|
+
* To do that, see https://github.com/appy-one/acebase-ipc-server
|
|
13
|
+
*
|
|
14
|
+
*/
|
|
15
|
+
const dbname = 'default';
|
|
16
|
+
const options = { /* default options */}; // Load from cluster.config.js!
|
|
17
|
+
options.authentication = { enabled: false };
|
|
18
|
+
options.https = { enabled: false };
|
|
19
|
+
if (cluster.isMaster) {
|
|
20
|
+
// Startup master
|
|
21
|
+
console.log(`Starting database server cluster with ${numCPUs} workers`);
|
|
22
|
+
const master = new acebase_1.AceBase(dbname, options);
|
|
23
|
+
master.once('ready', () => {
|
|
24
|
+
console.log(`Master database server started on process ${process.pid}`);
|
|
25
|
+
});
|
|
26
|
+
for (let i = 0; i < numCPUs; i++) {
|
|
27
|
+
const worker = cluster.fork();
|
|
28
|
+
worker.on('disconnect', () => {
|
|
29
|
+
console.error(`worker ${worker.process.pid} disconnected`);
|
|
30
|
+
});
|
|
31
|
+
worker.on('message', (msg) => {
|
|
32
|
+
if (msg === 'acebase-server-shutdown') {
|
|
33
|
+
// We could handle shutdown message here to kill the worker safely, but we'll do it in the worker threads instead: see below
|
|
34
|
+
// worker.kill();
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
cluster.on('exit', (worker, code, signal) => {
|
|
39
|
+
console.error(`worker ${worker.process.pid} died`);
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
console.log(`Worker ${process.pid} is running`);
|
|
44
|
+
const server = new server_1.AceBaseServer(dbname, options);
|
|
45
|
+
server.ready(() => {
|
|
46
|
+
console.log(`Worker database server started on process ${process.pid}`);
|
|
47
|
+
});
|
|
48
|
+
// Handle shutdown event to exit the worker process safely
|
|
49
|
+
server.on('shutdown', () => {
|
|
50
|
+
process.exit();
|
|
51
|
+
});
|
|
52
|
+
// Other option:
|
|
53
|
+
// process.on('acebase-server-shutdown', () => {
|
|
54
|
+
// process.exit();
|
|
55
|
+
// });
|
|
56
|
+
}
|
|
57
57
|
//# sourceMappingURL=cluster.js.map
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export * from '../types';
|
|
1
|
+
export * from '../types/index.js';
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
-
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
-
};
|
|
16
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.AceBaseServerAuthenticationSettings = exports.AceBaseServerTransactionSettings = exports.AceBaseServer = void 0;
|
|
18
|
-
var server_1 = require("./server");
|
|
19
|
-
Object.defineProperty(exports, "AceBaseServer", { enumerable: true, get: function () { return server_1.AceBaseServer; } });
|
|
20
|
-
var settings_1 = require("./settings");
|
|
21
|
-
Object.defineProperty(exports, "AceBaseServerTransactionSettings", { enumerable: true, get: function () { return settings_1.AceBaseServerTransactionSettings; } });
|
|
22
|
-
Object.defineProperty(exports, "AceBaseServerAuthenticationSettings", { enumerable: true, get: function () { return settings_1.AceBaseServerAuthenticationSettings; } });
|
|
23
|
-
__exportStar(require("./shared/email"), exports);
|
|
24
|
-
__exportStar(require("./oauth-providers"), exports);
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.AceBaseServerAuthenticationSettings = exports.AceBaseServerTransactionSettings = exports.AceBaseServer = void 0;
|
|
18
|
+
var server_1 = require("./server");
|
|
19
|
+
Object.defineProperty(exports, "AceBaseServer", { enumerable: true, get: function () { return server_1.AceBaseServer; } });
|
|
20
|
+
var settings_1 = require("./settings");
|
|
21
|
+
Object.defineProperty(exports, "AceBaseServerTransactionSettings", { enumerable: true, get: function () { return settings_1.AceBaseServerTransactionSettings; } });
|
|
22
|
+
Object.defineProperty(exports, "AceBaseServerAuthenticationSettings", { enumerable: true, get: function () { return settings_1.AceBaseServerAuthenticationSettings; } });
|
|
23
|
+
__exportStar(require("./shared/email"), exports);
|
|
24
|
+
__exportStar(require("./oauth-providers"), exports);
|
|
25
25
|
//# sourceMappingURL=index.js.map
|