@jskit-ai/users-core 0.2.15 → 0.2.17

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 (50) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/package.json +24 -17
  3. package/patterns/user-administration-server/PATTERN.md +63 -10
  4. package/patterns/user-administration-server/example/packages/users/package.json +5 -4
  5. package/patterns/user-administration-server/example/packages/users/src/server/UsersFeature.js +7 -5
  6. package/patterns/user-administration-server/example/packages/users/src/shared/index.js +1 -1
  7. package/patterns/user-administration-server/example/packages/users/src/shared/userCrud.js +21 -0
  8. package/patterns/user-administration-server/example/packages/users-workspace/package.json +11 -5
  9. package/patterns/user-administration-server/example/packages/users-workspace/src/server/UsersWorkspaceFeature.js +14 -5
  10. package/patterns/user-administration-server/example/packages/users-workspace/src/server/workspaceMembersOnly.js +52 -0
  11. package/patterns/user-administration-server/example/packages/users-workspace/src/shared/index.js +1 -1
  12. package/patterns/user-administration-server/example/packages/users-workspace/src/shared/userCrud.js +21 -0
  13. package/src/server/UsersFeature.js +10 -6
  14. package/src/server/UsersIdentityProvider.js +13 -29
  15. package/src/server/accountNotifications/accountNotificationsActions.js +3 -3
  16. package/src/server/accountNotifications/accountNotificationsRoutes.js +3 -3
  17. package/src/server/accountPreferences/accountPreferencesActions.js +3 -3
  18. package/src/server/accountPreferences/accountPreferencesRoutes.js +3 -3
  19. package/src/server/accountProfile/accountProfileActions.js +9 -9
  20. package/src/server/accountProfile/accountProfileRoutes.js +5 -5
  21. package/src/server/accountSecurity/accountSecurityActions.js +10 -10
  22. package/src/server/accountSecurity/accountSecurityRoutes.js +9 -9
  23. package/src/server/common/repositories/recordsByIds.js +38 -0
  24. package/src/server/common/repositories/userProfilesRepository.js +261 -146
  25. package/src/server/common/repositories/userSettingsRepository.js +37 -49
  26. package/src/server/common/services/authProfileSyncService.js +3 -5
  27. package/src/server/types.js +9 -1
  28. package/src/server/usersIdentity.js +11 -11
  29. package/src/server/usersRuntime.js +13 -11
  30. package/src/shared/resources/userProfileResource.js +43 -13
  31. package/src/shared/resources/userSettingsResource.js +35 -29
  32. package/test/accountSecurityService.test.js +2 -2
  33. package/test/authProfileSyncService.test.js +13 -9
  34. package/test/exportsContract.test.js +2 -0
  35. package/test/featureRuntime.test.js +63 -20
  36. package/test/i18nCodes.test.js +6 -10
  37. package/test/listByIds.mysql.test.js +5 -0
  38. package/test/listByIds.postgres.test.js +6 -0
  39. package/test/repositories.mysql.test.js +384 -0
  40. package/test/resourcesCanonical.test.js +58 -22
  41. package/test/support/listByIdsCases.js +115 -0
  42. package/test/support/usersDatabases.js +135 -0
  43. package/test/userSettingsInternalResource.test.js +3 -3
  44. package/test/userSettingsResource.test.js +3 -3
  45. package/test/usersPackageScaffoldContract.test.js +70 -12
  46. package/test/usersRouteRequestInputValidator.test.js +2 -2
  47. package/test/usersRouteResources.test.js +73 -29
  48. package/patterns/user-administration-server/example/packages/users/src/shared/userResource.js +0 -69
  49. package/patterns/user-administration-server/example/packages/users-workspace/src/shared/userResource.js +0 -56
  50. package/test/repositoryContracts.test.js +0 -596
package/CHANGELOG.md CHANGED
@@ -2,12 +2,38 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - `users.profiles.listByIds(ids, options)` answers every profile of a list of ids in one call, however many, sorted by id. An id named twice answers its profile once, and an id naming no profile the caller can see, or that is no id, is left out. It reads 1,000 distinct ids per statement, each joining the caller's transaction and seeing what `query` sees for the caller's context. Code that names people by id read them in `query` pages of at most 100, walked by hand, once a group passed 100 people. Its tests run on MariaDB/MySQL (`listByIds.mysql.test.js`) and PostgreSQL (`listByIds.postgres.test.js`, in CI's PostgreSQL job).
6
+ - `users.settings.listByUserIds(userIds, options)` answers the settings of a list of users in one call, the same way: sorted by user id, each user once, users without settings left out, and each locale canonical as `findByUserId` reads it. Code that showed many people's settings read them with one `findByUserId` per person.
7
+
8
+ - user_settings declares its foreign key, user_id to users (`foreignKeys`), so json-rest-api 3.1.0 can skip the visibility query a system-context read makes for a record such a key guarantees exists. `jskit test --databases` checks each against an app's test database. workspaces-core's `repositories.integration.test.js` proves it matches the migrations, with the users table, which has none.
9
+ - The `users/user-administration-server` pattern's `workspaceMembersOnly` reads the workspace's members with only the list's context and transaction (`passedOn(options)`): the list's own settings, such as `format: "jsonapi"`, no longer reach `workspaces.memberships`.
10
+ - The user settings table's fields with a default (theme, locale, time zone, date and number formats, currency, avatar size, and the password and notification flags) are no longer `required`, which `defineTableResource` now refuses beside `defaultTo`: a create that leaves one out gets its default where it failed REQUIRED. The CRUD and API contracts keep their own body and output schemas, so requests are unchanged.
11
+ - `@jskit-ai/database-runtime` and `@jskit-ai/resource-runtime` are peer dependencies, required and at the same versions, where they were dependencies: its user settings are a table resource and its profiles live in the database, and the app holds one copy of the table runtime that every package shares, as it does the kernel. npm installs a required peer as it installed the dependency, so an app installs the same packages and versions; a release whose versions disagree now fails the install with ERESOLVE instead of nesting a second copy.
12
+ - **Security.** The `users/user-administration-server` pattern's workspace variant narrows its repository to the reads it narrows: `workspaceMembersOnly` answers only `query`, `get` and `pageLimits`, where it passed users.profiles' other methods (`findByEmail`, `countUsers`, the writes) through un-narrowed to anything that required the feature's capability.
13
+ - `@jskit-ai/users-core/server/UsersExtensionsProvider` exports `UsersExtensionsProvider`, which provides `users.extensions`, so a test can start `UsersIdentityProvider` (`users.profiles`, `users.settings`) beside its own features with `startTestFeatures`.
14
+ - **Breaking.** The users table resource drops its scalar `id` search entry, which made `filters: { id: ids }` fail, and its `ids` entry: `filters: { id }` takes one id or a list. The settings table drops `search: true` on its `id` field. `countUsers` and the `users/user-administration-server` pattern's workspace narrowing filter by `id`. **Upgrading:** `filters: { ids }` on `users.profiles` becomes `filters: { id: ids }`.
15
+ - The `users/user-administration-server` pattern's packages require `crud.contracts`, which every package with a CRUD feature now lists.
16
+ - The `users/user-administration-server` pattern's users list and view answer only the display name, email, username and timestamps its CRUD contract names: before, the CRUD service also answered the sign-in identity and the avatar's storage, which the contract kept out of its output with `{}` entries. Applications that copied the pattern get the same by upgrading crud-core, and drop the `{}` entries.
17
+ - The `users/user-administration-server` pattern's workspace variant lists only the workspace's active members: its `decorateRepository` (`src/server/workspaceMembersOnly.js`) narrows users-core's repository with `workspaces.memberships`' `activeMemberIds`, and anyone else is a missing record. Before, the `users` table being public, a workspace admin's list showed every user with an account. An application that copied the variant copies the narrowing.
18
+ - `users.profiles` gains what an application moving its own users table onto users-core needs, each joining the caller's transaction: `createWithId(profile, options)` creates a profile with the id it is given (an application that keeps the ids of its earlier users table; on PostgreSQL, advance the id sequence after such an import); `listByEmails(emails, options)` answers the profiles of a set of emails in one read, through the users table resource's new `emails` filter (`in`); `createManyIgnoringExisting(profiles, options)` creates, in one INSERT per chunk, the profiles whose identity has none and leaves the others as they are, answering the new ids, and runs only in a system context; `changeUsername(userId, username, options)` refuses a username another profile holds with `USER_PROFILE_USERNAME_CONFLICT` before writing, so the caller's transaction goes on; and `countUsers` takes `authProvider`, counting the users of one sign-in provider.
19
+ - The users table resource reads in display-name order, then email (`defaultSort: ["displayName", "email"]`), so a users list keeps the order it had before it moved onto users-core's resource.
20
+ - **Breaking (data-access redesign).** `UsersIdentityProvider` owns the `users` and `user_settings` tables through `defineFeature({ owns })` and reads and writes them through their resource handles, instead of registering them on `runtime.json-rest-api`; it requires `runtime.resources` and `runtime.actions`. `users.profiles`, `users.settings` and `auth.profile.projector` keep their methods and answers. Their `withTransaction(options, work)` runs `work(txOptions)` in the caller's transaction or in one it opens, and every call inside passes `txOptions` on. `users.profiles` also exposes the reads `query`, `get` and `pageLimits`, for a CRUD feature that names it as its `ownerRepository`, and no handle writes. Behaviour difference: a display name or avatar update of a missing profile answers `null` outside a transaction, instead of failing with json-rest-api's 404.
21
+ - **Breaking (data-access redesign).** Each users table is one table resource: `userProfileTableResource` (name `userProfiles`, table `users`) and `userSettingsTableResource` (name `userSettings`, table `user_settings`), registered under their names, from the same module paths (`./shared/resources/userProfileResource` and `./shared/resources/userSettingsResource`); a name ending in `TableResource` is a table resource, one ending in `Contract` or `Crud` a contract on it. The HTTP operations are API contracts: `userProfileContract` (patch, avatarUpload, avatarDelete) and `userSettingsContract` (view, preferencesUpdate, notificationsUpdate, passwordChange, passwordMethodToggle, oauthLinkStart, oauthUnlink, logoutOtherSessions). The account CRUD operations are CRUD contracts on those table resources, with the operations, bodies, outputs and messages they had: `userProfileCrud` and `userSettingsCrud` (view, list, create, replace and patch, under the namespaces `userProfile` and `userSettings`; no JSKIT route serves them). The users table resource gains the `q` filter: every word in the display name, email or username. The user-administration pattern's examples build their CRUD contract, `userCrud`, on `userProfileTableResource` instead of a second table resource on `users`.
5
22
  - The profile projector's `syncIdentityProfile` takes `onlyWhenChanged`: an existing profile that already matches the identity (email, display name, provider identity) is answered after one read, without opening a transaction, ensuring user settings or running the lifecycle contributors (workspaces' personal workspace provisioning); a missing or changed profile is synchronized in full. JSKIT's auth providers pass it on ordinary requests and synchronize in full at sign-in and session refresh. Visible difference: a personal workspace, owner membership or user settings row deleted while its person is signed in is re-created at their next sign-in or session refresh instead of their next request; a name or email changed at the provider still shows at the next request.
6
23
  - A new profile's username (the email's local part, or the requested name, then `name-2` to `name-1000`) is chosen with one read of every taken candidate through the profile resource's new `usernames` filter (`in`), instead of one read per taken candidate, so a common name costs the same statements after 10 namesakes as after 200. The chosen name, the trimming of long names, the profile's own name counting as free and the error when all 1,000 are taken are unchanged.
7
24
  - The account security routes' declared rate limits apply, now that the kernel enforces route limits.
8
25
  - The settings, security and avatar field messages are sent in the coded form `{ code, message, params }`, so their field errors translate. The English is unchanged.
9
26
  - The resources' validation feedback names the catalog key `jskit.users.feedback.validationFailed` instead of plain English; JSKIT's forms render it with `text()`, so the English shown is unchanged.
10
27
  - `USER_PROFILE_EMAIL_CONFLICT` has its English in the catalog, so it translates.
28
+ - **Breaking (data-access redesign).** The users' records are their owners' capabilities: `users.profiles` (the `users` table: `findById`, `findByEmail`, `findByIdentity`, `upsert`, the display name and avatar updates, `createWithSettings` and `countUsers`) and `users.settings` (the `user_settings` table: `findByUserId`, `ensureForUserId` and the settings updates). `UsersIdentityProvider` provides them, with `auth.profile.projector`, instead of `users.identity`, and `users.core` no longer has `repositories`; its types are `UsersProfiles` and `UsersSettings`.
29
+ - New `createWithSettings({ profile, settings }, options)` on `users.profiles` creates a profile (or, for an identity that has one, updates it, as `upsert` does) and gives it its settings in one transaction, the caller's `options.trx` or its own: the settings start from the defaults and the given fields replace them, and the call answers `{ profile, settings }`.
30
+ - New `countUsers({ excludeIds, createdSince }, options)` on `users.profiles` counts the users with one aggregate read, or two when `excludeIds` is given (json-rest-api 2.4 has no "not in" filter, so the excluded users who match are counted and subtracted). The profile resource gains the filters it uses: `ids` (`id in [...]`) and `createdSince` (`created_at >=`).
31
+
32
+ ### Upgrading
33
+
34
+ - A feature that required `identity: "users.identity"` requires `users.profiles`, `users.settings` and, for the projector, `auth.profile.projector`: `identity.repositories.userProfiles` becomes the `users.profiles` capability and `identity.repositories.userSettings` becomes `users.settings`. Code that read `repositories.userProfiles` or `repositories.userSettings` of `users.core` requires them the same way. The `UsersIdentity` type is gone; use `UsersProfiles` and `UsersSettings`.
35
+ - Tests that run `UsersIdentityProvider.setup()` read `{ profiles, settings, profileProjector }` from its result, and pass `{ extensions, actionCatalogue, resourceRuntime }` (for example `createTestResourceRuntime({ knex })` of `@jskit-ai/resource-runtime/test`) instead of `jsonRestApi`.
36
+ - `profiles.withTransaction(async (trx) => …)` with `{ trx }` passed inside becomes `profiles.withTransaction(options, async (txOptions) => …)` with `txOptions` passed inside, and the same for `settings.withTransaction`. A raw Knex transaction is refused by the handles' writes; join the caller's managed one by passing its options.
11
37
 
12
38
  ### New codes (17)
13
39
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/users-core",
3
- "version": "0.2.15",
3
+ "version": "0.2.17",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -14,15 +14,14 @@
14
14
  "./shared/resources/userProfileResource": "./src/shared/resources/userProfileResource.js",
15
15
  "./shared/resources/userSettingsResource": "./src/shared/resources/userSettingsResource.js",
16
16
  "./shared/settings": "./src/shared/settings.js",
17
+ "./server/UsersExtensionsProvider": "./src/server/UsersExtensionsProvider.js",
17
18
  "./locales/en.json": "./locales/en.json"
18
19
  },
19
20
  "dependencies": {
20
- "@jskit-ai/database-runtime": "0.1.262",
21
- "@jskit-ai/json-rest-api-core": "0.2.14",
22
- "@jskit-ai/resource-core": "0.1.204",
23
- "@jskit-ai/resource-crud-core": "0.1.204",
24
- "@jskit-ai/storage-runtime": "0.1.259",
25
- "@jskit-ai/uploads-runtime": "0.2.13",
21
+ "@jskit-ai/resource-core": "0.1.206",
22
+ "@jskit-ai/resource-crud-core": "0.1.206",
23
+ "@jskit-ai/storage-runtime": "0.1.261",
24
+ "@jskit-ai/uploads-runtime": "0.2.15",
26
25
  "json-rest-schema": "^1.0.17"
27
26
  },
28
27
  "description": "Users/account runtime plus HTTP routes for account features.",
@@ -31,7 +30,8 @@
31
30
  "capabilities": {
32
31
  "provides": [
33
32
  "users.core",
34
- "users.identity",
33
+ "users.profiles",
34
+ "users.settings",
35
35
  "users.extensions",
36
36
  "auth.profile.projector"
37
37
  ],
@@ -41,7 +41,7 @@
41
41
  "runtime.bootstrap",
42
42
  "runtime.database",
43
43
  "runtime.http",
44
- "runtime.json-rest-api",
44
+ "runtime.resources",
45
45
  "runtime.storage",
46
46
  "runtime.uploads"
47
47
  ]
@@ -85,7 +85,7 @@
85
85
  },
86
86
  {
87
87
  "subpath": "./server/UsersIdentityProvider",
88
- "summary": "Exports UsersIdentityProvider, which provides users.identity (the user profile and settings repositories) and auth.profile.projector."
88
+ "summary": "Exports UsersIdentityProvider, which provides users.profiles (the users table's records, with createWithSettings and countUsers), users.settings (the users' settings records) and auth.profile.projector."
89
89
  },
90
90
  {
91
91
  "subpath": "./server/usersExtensions",
@@ -97,11 +97,11 @@
97
97
  },
98
98
  {
99
99
  "subpath": "./shared/resources/userProfileResource",
100
- "summary": "Exports the shared user profile resource."
100
+ "summary": "Exports the users table resource (userProfileTableResource), the account profile's CRUD contract (userProfileCrud) and the profile API contract (userProfileContract)."
101
101
  },
102
102
  {
103
103
  "subpath": "./shared/resources/userSettingsResource",
104
- "summary": "Exports the shared user settings resource."
104
+ "summary": "Exports the user_settings table resource (userSettingsTableResource), the account settings' CRUD contract (userSettingsCrud), the settings API contract (userSettingsContract) and the settings keys and output schemas."
105
105
  },
106
106
  {
107
107
  "subpath": "./shared/settings",
@@ -109,12 +109,17 @@
109
109
  },
110
110
  {
111
111
  "subpath": "./server/types",
112
- "summary": "Types of the users.core, users.identity and users.extensions capabilities, for features that require them."
112
+ "summary": "Types of the users.core, users.profiles, users.settings and users.extensions capabilities, for features that require them."
113
+ },
114
+ {
115
+ "subpath": "./server/UsersExtensionsProvider",
116
+ "summary": "Exports UsersExtensionsProvider, which provides users.extensions, for a test that starts UsersIdentityProvider."
113
117
  }
114
118
  ],
115
119
  "capabilities": [
116
120
  "users.core",
117
- "users.identity",
121
+ "users.profiles",
122
+ "users.settings",
118
123
  "users.extensions",
119
124
  "auth.profile.projector"
120
125
  ]
@@ -191,8 +196,10 @@
191
196
  }
192
197
  },
193
198
  "peerDependencies": {
194
- "@jskit-ai/auth-core": "0.2.13",
195
- "@jskit-ai/http-runtime": "0.2.13",
196
- "@jskit-ai/kernel": "0.2.13"
199
+ "@jskit-ai/auth-core": "0.2.15",
200
+ "@jskit-ai/database-runtime": "0.1.264",
201
+ "@jskit-ai/http-runtime": "0.2.15",
202
+ "@jskit-ai/kernel": "0.2.15",
203
+ "@jskit-ai/resource-runtime": "0.2.13"
197
204
  }
198
205
  }
@@ -22,21 +22,70 @@ credentials, or an application that needs no administrative user listing.
22
22
 
23
23
  Choose global versus workspace scope, visible and editable fields, permission
24
24
  policy, route surface, filters, and whether account deletion is part of the
25
- product. Do not expose password/session data through the resource.
25
+ product. Do not expose password, session or sign-in identity data through the
26
+ CRUD contract.
26
27
 
27
28
  ## Framework APIs
28
29
 
29
30
  Use `@jskit-ai/users-core` for profile persistence and policies,
30
- `defineCrudJsonApiFeature()` from `@jskit-ai/crud-core` for standard mechanics,
31
- and the resource contracts from `@jskit-ai/resource-crud-core`.
31
+ `defineCrudFeature()` from `@jskit-ai/crud-core` for standard mechanics,
32
+ and `defineCrudContract()` from `@jskit-ai/resource-crud-core`.
33
+
34
+ users-core is the `users` table's one owner, so an administration feature does
35
+ not own it: `defineCrudFeature({ crud: userCrud, ownerRepository: "users.profiles", ... })`
36
+ serves the CRUD contract through users-core's repository. The workspace
37
+ variant also names `visibility: "workspace"`: its routes are a workspace's,
38
+ so they resolve the caller's workspace and check its `crud.users.*`
39
+ permissions. The `users` table is public, every user's, so the variant also
40
+ narrows the repository to the workspace's members with `decorateRepository`
41
+ (`src/server/workspaceMembersOnly.js`): a list reads only the active members
42
+ from `workspaces.memberships`' `activeMemberIds`, and anyone else is a missing
43
+ record, so a workspace admin never learns who else has an account. The narrowed
44
+ repository answers only `query`, `get` and `pageLimits`: users.profiles' other
45
+ methods (`findByEmail`, `countUsers`, the writes) read or write every user, so
46
+ they never pass through it.
47
+
48
+ The `users` table has one table resource, users-core's `userProfileTableResource`
49
+ (`@jskit-ai/users-core/shared/resources/userProfileResource`). An
50
+ administration package never defines a second one; `jskit check` fails a table
51
+ with two. It builds its CRUD contract on that resource,
52
+ `defineCrudContract(userProfileTableResource, { namespace, operations, fields })`,
53
+ which chooses the operations, their namespace and the fields each returns; a
54
+ field it does not name, such as the sign-in identity, is never shown. The
55
+ list searches with the resource's `q` filter: every word in the display name,
56
+ email or username.
57
+
58
+ Other code that reads or writes the users' records (a decorated service, a
59
+ hook, a job) requires their owners' capabilities, never the `users` or
60
+ `user_settings` tables:
61
+
62
+ - `users.profiles`: `findById`, `findByEmail`, `findByIdentity`,
63
+ `listByEmails(emails, options)` (one read),
64
+ `listByIds(ids, options)` (every profile of the ids, sorted by id, one read
65
+ per 1,000 ids), `upsert`,
66
+ `createWithSettings({ profile, settings }, options)` (the profile and its
67
+ settings in one transaction; settings start from the defaults),
68
+ `createWithId(profile, options)` (a profile keeping an earlier table's id),
69
+ `createManyIgnoringExisting(profiles, options)` (a re-runnable bulk import,
70
+ system context only), `changeUsername(userId, username, options)` and
71
+ `countUsers({ excludeIds, createdSince, authProvider }, options)`.
72
+ - `users.settings`: `findByUserId`, `listByUserIds(userIds, options)` (the
73
+ settings of every listed user who has them, sorted by user id, one read per
74
+ 1,000 ids), `ensureForUserId` and the settings updates.
75
+
76
+ Their types are `UsersProfiles` and `UsersSettings` in
77
+ `@jskit-ai/users-core/server/types`. Every method takes `options` last and
78
+ joins the caller's transaction: inside `withTransaction(options, async
79
+ (txOptions) => …)`, pass `txOptions` to every call.
32
80
 
33
81
  ## Invariants
34
82
 
35
83
  - The public user id is the resource identity.
36
84
  - Workspace operations are scoped before repository access.
37
85
  - Permission checks happen before records or record existence are disclosed.
38
- - Shared profile persistence remains owned by `@jskit-ai/users-core`.
39
- - The resource is the field contract; the feature projects its repository,
86
+ - Shared profile persistence remains owned by `@jskit-ai/users-core`, and so
87
+ does the `users` table's one table resource.
88
+ - The CRUD contract is the field contract; the feature projects its repository,
40
89
  service, actions, and routes without app-local ceremony.
41
90
  - Each package exports the type of the capability it provides:
42
91
  `src/server/types.js` declares `AppUsers` (for `app.users`) or
@@ -54,9 +103,12 @@ and the resource contracts from `@jskit-ai/resource-crud-core`.
54
103
 
55
104
  `example/packages/users/` is a global administration package.
56
105
  `example/packages/users-workspace/` demonstrates the workspace route/action
57
- boundary, with workspaces-core's `WORKSPACE_CRUD_SCOPE`, while reusing the same
58
- service contract. Each package's
59
- `src/server/types.js` declares the type of the capability it provides. Copy only the composition
106
+ boundary, with workspaces-core's `WORKSPACE_CRUD_SCOPE`, and lists only the
107
+ workspace's members through the same service contract. Each package's `src/shared/userCrud.js` builds its CRUD
108
+ contract on users-core's `userProfileTableResource`, its `package.json` requires
109
+ `users.profiles` (users-core, which owns the table, must be installed), and its
110
+ `src/server/types.js` declares the type of the capability it provides; the
111
+ workspace variant also requires `workspaces.memberships`. Copy only the composition
60
112
  that matches the product and adapt it as ordinary application source.
61
113
 
62
114
  ## Variation points
@@ -71,9 +123,10 @@ isolation, missing records, null/cleared fields, filtering, and pagination.
71
123
 
72
124
  ## Avoid
73
125
 
74
- - copying authentication credential tables into the user resource
126
+ - a second table resource on `users` or `user_settings`
127
+ - copying authentication credential tables into the CRUD contract
75
128
  - trusting route scope without repository scope
76
- - adding app-local mechanics already provided by `defineCrudJsonApiFeature()`
129
+ - adding app-local mechanics already provided by `defineCrudFeature()`
77
130
  - generator metadata or field questionnaires
78
131
  - probing a collaborator, defaulting one to `null`, `{}` or a no-op, setters
79
132
  that fill a slot after construction, and module-level registries
@@ -10,8 +10,9 @@
10
10
  "./shared": "./src/shared/index.js"
11
11
  },
12
12
  "dependencies": {
13
- "@jskit-ai/crud-core": "0.2.14",
14
- "@jskit-ai/resource-crud-core": "0.1.204"
13
+ "@jskit-ai/crud-core": "0.2.16",
14
+ "@jskit-ai/resource-crud-core": "0.1.206",
15
+ "@jskit-ai/users-core": "0.2.17"
15
16
  },
16
17
  "jskit": {
17
18
  "kind": "runtime",
@@ -20,10 +21,10 @@
20
21
  "app.users"
21
22
  ],
22
23
  "requires": [
24
+ "crud.contracts",
23
25
  "runtime.http",
24
- "runtime.json-rest-api",
25
26
  "runtime.actions",
26
- "runtime.database"
27
+ "users.profiles"
27
28
  ]
28
29
  },
29
30
  "runtime": {
@@ -1,12 +1,14 @@
1
- import { defineCrudJsonApiFeature } from "@jskit-ai/crud-core/server/defineCrudJsonApiFeature";
2
- import { resource } from "../shared/userResource.js";
1
+ import { defineCrudFeature } from "@jskit-ai/crud-core/server/defineCrudFeature";
2
+ import { userCrud } from "../shared/userCrud.js";
3
3
 
4
- const UsersFeature = defineCrudJsonApiFeature({
5
- resource,
4
+ // users-core owns the users table; this feature serves the administration
5
+ // CRUD contract through its owner's repository.
6
+ const UsersFeature = defineCrudFeature({
7
+ crud: userCrud,
8
+ ownerRepository: "users.profiles",
6
9
  id: "app.users",
7
10
  capability: "app.users",
8
11
  surface: "home",
9
- ownershipFilter: "public",
10
12
  relativePath: "/users"
11
13
  });
12
14
 
@@ -1 +1 @@
1
- export { resource } from "./userResource.js";
1
+ export { userCrud } from "./userCrud.js";
@@ -0,0 +1,21 @@
1
+ import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
2
+ import { userProfileTableResource } from "@jskit-ai/users-core/shared/resources/userProfileResource";
3
+
4
+ // The users list and view. The users table has one table resource, users-core's
5
+ // userProfileTableResource; this contract chooses the operations and the fields they
6
+ // return, and the list searches with the resource's q (display name, email and
7
+ // username). It shows only the fields it names, so the sign-in identity and the
8
+ // avatar's storage stay out of administration.
9
+ const userCrud = defineCrudContract(userProfileTableResource, {
10
+ namespace: "users",
11
+ operations: ["list", "view"],
12
+ fields: {
13
+ displayName: { output: "optional" },
14
+ email: { output: "optional" },
15
+ username: { output: "optional" },
16
+ createdAt: { output: "required" },
17
+ updatedAt: { output: "required" }
18
+ }
19
+ });
20
+
21
+ export { userCrud };
@@ -10,9 +10,14 @@
10
10
  "./shared": "./src/shared/index.js"
11
11
  },
12
12
  "dependencies": {
13
- "@jskit-ai/crud-core": "0.2.14",
14
- "@jskit-ai/resource-crud-core": "0.1.204",
15
- "@jskit-ai/workspaces-core": "0.2.15"
13
+ "@jskit-ai/crud-core": "0.2.16",
14
+ "@jskit-ai/resource-crud-core": "0.1.206",
15
+ "@jskit-ai/users-core": "0.2.17",
16
+ "@jskit-ai/workspaces-core": "0.2.17"
17
+ },
18
+ "peerDependencies": {
19
+ "@jskit-ai/kernel": "0.2.15",
20
+ "@jskit-ai/resource-runtime": "0.2.13"
16
21
  },
17
22
  "jskit": {
18
23
  "kind": "runtime",
@@ -21,10 +26,11 @@
21
26
  "app.users-workspace"
22
27
  ],
23
28
  "requires": [
29
+ "crud.contracts",
24
30
  "runtime.http",
25
- "runtime.json-rest-api",
26
31
  "runtime.actions",
27
- "runtime.database"
32
+ "users.profiles",
33
+ "workspaces.memberships"
28
34
  ]
29
35
  },
30
36
  "runtime": {
@@ -1,13 +1,22 @@
1
- import { defineCrudJsonApiFeature } from "@jskit-ai/crud-core/server/defineCrudJsonApiFeature";
1
+ import { defineCrudFeature } from "@jskit-ai/crud-core/server/defineCrudFeature";
2
2
  import { WORKSPACE_CRUD_SCOPE } from "@jskit-ai/workspaces-core/server/support/workspaceCrud";
3
- import { resource } from "../shared/userResource.js";
3
+ import { userCrud } from "../shared/userCrud.js";
4
+ import { workspaceMembersOnly } from "./workspaceMembersOnly.js";
4
5
 
5
- const UsersWorkspaceFeature = defineCrudJsonApiFeature({
6
- resource,
6
+ // users-core owns the users table; this feature serves the administration
7
+ // CRUD contract on a workspace's admin surface through its owner's
8
+ // repository. The routes are a workspace's, so they resolve the caller's
9
+ // workspace and check its crud.users.* permissions, and the repository is
10
+ // narrowed to that workspace's members: the users table is every user's.
11
+ const UsersWorkspaceFeature = defineCrudFeature({
12
+ crud: userCrud,
13
+ ownerRepository: "users.profiles",
14
+ requires: { memberships: "workspaces.memberships" },
15
+ decorateRepository: ({ repository, memberships }) => workspaceMembersOnly(repository, memberships),
16
+ visibility: "workspace",
7
17
  id: "app.users-workspace",
8
18
  capability: "app.users-workspace",
9
19
  surface: "admin",
10
- ownershipFilter: "workspace",
11
20
  relativePath: "/users",
12
21
  scope: WORKSPACE_CRUD_SCOPE
13
22
  });
@@ -0,0 +1,52 @@
1
+ import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
+ import { passedOn, resolveWorkspaceScopeValue } from "@jskit-ai/resource-runtime/server";
3
+
4
+ /**
5
+ * users-core's users repository narrowed to the caller's workspace: a list reads only the workspace's active members,
6
+ * and anyone else is a missing record, so a workspace admin never learns who else has an account. The users table is
7
+ * public, so its handle alone would list every user; the narrowing reads the workspace's memberships first. It answers
8
+ * only the reads it narrows (query and get, with pageLimits): the rest of users.profiles, such as findByEmail or
9
+ * countUsers, never passes through this feature's repository, so nothing reaches users past the narrowing through it.
10
+ * @param {import("@jskit-ai/crud-core/server/types").CrudRepository} repository
11
+ * @param {import("@jskit-ai/workspaces-core/server/types").WorkspaceMembershipsRepository} memberships
12
+ */
13
+ function workspaceMembersOnly(repository, memberships) {
14
+ // The caller's workspace's active members; none when the context names no workspace. The memberships get only the
15
+ // context and transaction: the list's own settings (its format, missing) are for the users read.
16
+ function memberIds(options) {
17
+ return memberships.activeMemberIds(resolveWorkspaceScopeValue(options.context), passedOn(options));
18
+ }
19
+
20
+ /**
21
+ * One page of the workspace's members the params select.
22
+ * @param {Record<string, any>} params
23
+ * @param {{ context?: object }} options
24
+ */
25
+ async function query(params, options) {
26
+ const members = await memberIds(options);
27
+ const requested = params.filters?.id;
28
+ // An empty list matches no row: a workspace with no members lists nobody.
29
+ const id = requested === undefined ? members : [requested].flat().map(String).filter((memberId) => members.includes(memberId));
30
+ return repository.query({ ...params, filters: { ...params.filters, id } }, options);
31
+ }
32
+
33
+ /**
34
+ * A member of the workspace, or a missing record for anyone else.
35
+ * @param {unknown} id
36
+ * @param {Record<string, any>} params
37
+ * @param {{ context?: object, missing?: "skip" }} options
38
+ */
39
+ async function get(id, params, options) {
40
+ if ((await memberIds(options)).includes(String(id))) {
41
+ return repository.get(id, params, options);
42
+ }
43
+ if (options.missing === "skip") {
44
+ return null;
45
+ }
46
+ throw new AppError(404, "Document not found.", { code: "crud.document.notFound" });
47
+ }
48
+
49
+ return Object.freeze({ query, get, pageLimits: repository.pageLimits });
50
+ }
51
+
52
+ export { workspaceMembersOnly };
@@ -1 +1 @@
1
- export { resource } from "./userResource.js";
1
+ export { userCrud } from "./userCrud.js";
@@ -0,0 +1,21 @@
1
+ import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
2
+ import { userProfileTableResource } from "@jskit-ai/users-core/shared/resources/userProfileResource";
3
+
4
+ // The users list and view. The users table has one table resource, users-core's
5
+ // userProfileTableResource; this contract chooses the operations and the fields they
6
+ // return, and the list searches with the resource's q (display name, email and
7
+ // username). It shows only the fields it names, so the sign-in identity and the
8
+ // avatar's storage stay out of administration.
9
+ const userCrud = defineCrudContract(userProfileTableResource, {
10
+ namespace: "users",
11
+ operations: ["list", "view"],
12
+ fields: {
13
+ displayName: { output: "optional" },
14
+ email: { output: "optional" },
15
+ username: { output: "optional" },
16
+ createdAt: { output: "required" },
17
+ updatedAt: { output: "required" }
18
+ }
19
+ });
20
+
21
+ export { userCrud };
@@ -17,7 +17,9 @@ const UsersFeature = defineFeature({
17
17
  authService: "auth.service",
18
18
  bootstrap: "runtime.bootstrap",
19
19
  http: "runtime.http",
20
- identity: "users.identity",
20
+ profileProjector: "auth.profile.projector",
21
+ profiles: "users.profiles",
22
+ settings: "users.settings",
21
23
  storage: "runtime.storage",
22
24
  uploads: "runtime.uploads"
23
25
  },
@@ -29,12 +31,14 @@ const UsersFeature = defineFeature({
29
31
  * @param {import("@jskit-ai/auth-core/server/types").AuthService} capabilities.authService
30
32
  * @param {import("@jskit-ai/kernel/server/types").RuntimeBootstrap} capabilities.bootstrap
31
33
  * @param {import("@jskit-ai/kernel/server/types").RuntimeHttp} capabilities.http
32
- * @param {import("./types.js").UsersIdentity} capabilities.identity
34
+ * @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} capabilities.profileProjector
35
+ * @param {import("./types.js").UsersProfiles} capabilities.profiles
36
+ * @param {import("./types.js").UsersSettings} capabilities.settings
33
37
  * @param {import("@jskit-ai/storage-runtime/server/types").RuntimeStorage} capabilities.storage
34
38
  * @param {import("@jskit-ai/uploads-runtime/server/types").RuntimeUploads} capabilities.uploads
35
39
  */
36
- setup({ authService, bootstrap, http, identity, storage, uploads }) {
37
- const users = createUsersRuntime({ authService, identity, storage });
40
+ setup({ authService, bootstrap, http, profileProjector, profiles, settings, storage, uploads }) {
41
+ const users = createUsersRuntime({ authService, profileProjector, profiles, settings, storage });
38
42
  registerAccountProfileRoutes(http.router, {
39
43
  accountProfileService: users.services.accountProfile,
40
44
  authService,
@@ -48,8 +52,8 @@ const UsersFeature = defineFeature({
48
52
  order: 100,
49
53
  contribute: createUsersBootstrapContributor({
50
54
  authService,
51
- userProfilesRepository: users.repositories.userProfiles,
52
- userSettingsRepository: users.repositories.userSettings
55
+ userProfilesRepository: profiles,
56
+ userSettingsRepository: settings
53
57
  }).contribute
54
58
  });
55
59
  return { users };
@@ -1,44 +1,28 @@
1
- import { toDatabaseDateTimeUtc } from "@jskit-ai/database-runtime/shared";
2
- import {
3
- addResourceIfMissing,
4
- createJsonRestResourceScopeOptions
5
- } from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
6
- import { defineProvider } from "@jskit-ai/kernel/shared/capabilities";
7
- import { userProfileResource } from "../shared/resources/userProfileResource.js";
8
- import { userSettingsResource } from "../shared/resources/userSettingsResource.js";
1
+ import { defineFeature } from "@jskit-ai/kernel/server/features";
2
+ import { userProfileTableResource } from "../shared/resources/userProfileResource.js";
3
+ import { userSettingsTableResource } from "../shared/resources/userSettingsResource.js";
9
4
  import { createUsersIdentity } from "./usersIdentity.js";
10
5
 
11
- const UsersIdentityProvider = defineProvider({
6
+ // The users and user_settings tables' one owner. Other features reach them
7
+ // through the repositories it provides, never through the tables.
8
+ const UsersIdentityProvider = defineFeature({
12
9
  id: "users.identity",
10
+ owns: [userProfileTableResource, userSettingsTableResource],
13
11
  requires: {
14
- extensions: "users.extensions",
15
- jsonRestApi: "runtime.json-rest-api"
12
+ extensions: "users.extensions"
16
13
  },
17
14
  provides: {
18
- identity: "users.identity",
15
+ profiles: "users.profiles",
16
+ settings: "users.settings",
19
17
  profileProjector: "auth.profile.projector"
20
18
  },
21
19
  /**
22
20
  * @param {object} capabilities
23
21
  * @param {import("./types.js").UsersExtensions} capabilities.extensions
24
- * @param {import("@jskit-ai/json-rest-api-core/server/types").RuntimeJsonRestApi} capabilities.jsonRestApi
22
+ * @param {import("./types.js").UsersResources} capabilities.resources
25
23
  */
26
- async setup({ extensions, jsonRestApi }) {
27
- const scopeOptions = {
28
- writeSerializers: { "datetime-utc": toDatabaseDateTimeUtc }
29
- };
30
- await addResourceIfMissing(
31
- jsonRestApi,
32
- "userProfiles",
33
- createJsonRestResourceScopeOptions(userProfileResource, scopeOptions)
34
- );
35
- await addResourceIfMissing(
36
- jsonRestApi,
37
- "userSettings",
38
- createJsonRestResourceScopeOptions(userSettingsResource, scopeOptions)
39
- );
40
- const identity = createUsersIdentity({ jsonRestApi, extensions });
41
- return { identity, profileProjector: identity.profileProjector };
24
+ setup({ extensions, resources }) {
25
+ return createUsersIdentity({ resources, extensions });
42
26
  }
43
27
  });
44
28
 
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  resolveRequest
3
3
  } from "@jskit-ai/kernel/server/actions/actionContributorHelpers";
4
- import { userSettingsResource } from "../../shared/resources/userSettingsResource.js";
4
+ import { userSettingsContract } from "../../shared/resources/userSettingsResource.js";
5
5
  import { resolveActionUser } from "../common/support/resolveActionUser.js";
6
6
  import { ACCOUNT_SETTINGS_AND_BOOTSTRAP_EVENTS } from "../common/support/realtimeServiceEvents.js";
7
7
 
@@ -17,12 +17,12 @@ function createAccountNotificationsActions({ accountNotificationsService }) {
17
17
  permission: {
18
18
  require: "authenticated"
19
19
  },
20
- input: userSettingsResource.operations.notificationsUpdate.body,
20
+ input: userSettingsContract.operations.notificationsUpdate.body,
21
21
  output: null,
22
22
  extensions: {
23
23
  assistant: {
24
24
  description: "Update the signed-in user’s notification preferences.",
25
- output: userSettingsResource.operations.notificationsUpdate.output,
25
+ output: userSettingsContract.operations.notificationsUpdate.output,
26
26
  transformResult: (result) => result.value
27
27
  }
28
28
  },
@@ -1,5 +1,5 @@
1
1
  import { createJsonApiResourceRouteContract } from "@jskit-ai/http-runtime/shared/validators/jsonApiRouteTransport";
2
- import { userSettingsResource } from "../../shared/resources/userSettingsResource.js";
2
+ import { userSettingsContract } from "../../shared/resources/userSettingsResource.js";
3
3
  import { resolveAccountSettingsResourceId } from "../common/support/accountSettingsJsonApiTransport.js";
4
4
 
5
5
  /** @param {import("@jskit-ai/kernel/server/types").RuntimeRouter} router */
@@ -16,8 +16,8 @@ function registerAccountNotificationsRoutes(router) {
16
16
  ...createJsonApiResourceRouteContract({
17
17
  requestType: "user-notification-settings",
18
18
  responseType: "user-settings",
19
- body: userSettingsResource.operations.notificationsUpdate.body,
20
- output: userSettingsResource.operations.view.output,
19
+ body: userSettingsContract.operations.notificationsUpdate.body,
20
+ output: userSettingsContract.operations.view.output,
21
21
  outputKind: "record",
22
22
  getRecordId: resolveAccountSettingsResourceId,
23
23
  includeValidation400: true