@jskit-ai/users-core 0.2.23 → 0.2.25
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/CHANGELOG.md +1 -0
- package/package.json +11 -11
- package/patterns/user-administration-server/PATTERN.md +7 -3
- package/patterns/user-administration-server/example/packages/users/package.json +3 -3
- package/patterns/user-administration-server/example/packages/users-workspace/package.json +6 -6
- package/patterns/user-administration-server/example/packages/users-workspace/src/server/workspaceMembersOnly.js +69 -17
- package/src/server/common/repositories/userProfilesRepository.js +3 -2
- package/test/usersPackageScaffoldContract.test.js +18 -16
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- The user-administration-server pattern's workspace example (`users-workspace`'s `workspaceMembersOnly`) narrows users to the workspace's members in SQL. A list page is one report over the `users.profiles` and `workspaces.memberships` join sources: the users the list's filters match who hold an active membership, in the users list's order (display name, email, id), with a keyset cursor. A view reads that one membership with `findByWorkspaceIdAndUserId`. Before this, both read every active member id with `activeMemberIds` first. The page's cursor is the report's, and a cursor the list did not answer is refused with 400 `users.list.cursorInvalid`. workspaces-core's `userAdministrationExample.mysql.test.js` proves it on MariaDB/MySQL.
|
|
5
6
|
- `users.profiles` and `users.settings` answer `joinSource({ alias, filters }, options)`, the handle's join source, as `workspaces` and `workspaces.memberships` do: another owner's report reads people and their settings beside its own rows in one statement, under the users table's row policy, where it needed an app-side raw-SQL exception. Its tests run on MariaDB/MySQL (`joinSource.mysql.test.js`) and PostgreSQL (`joinSource.postgres.test.js`).
|
|
6
7
|
- Two first sign-ins of one identity at once (a double-clicked sign-in, two tabs) make one user, and both answer it: the sync that loses the insert (`auth.profile.projector`'s `syncIdentityProfile`) rolls back in full and runs again, reading the winner's profile as a returning sign-in does, with `created: false` for the lifecycle contributors. It failed with the database's duplicate-entry error (`ER_DUP_ENTRY`). Inside a caller's transaction (`trx`) the loss still fails that transaction, for the caller's own retry.
|
|
7
8
|
- `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).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/users-core",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.25",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "jskit test"
|
|
@@ -18,11 +18,11 @@
|
|
|
18
18
|
"./locales/en.json": "./locales/en.json"
|
|
19
19
|
},
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@jskit-ai/resource-core": "0.1.
|
|
22
|
-
"@jskit-ai/resource-crud-core": "0.1.
|
|
23
|
-
"@jskit-ai/storage-runtime": "0.1.
|
|
24
|
-
"@jskit-ai/uploads-runtime": "0.2.
|
|
25
|
-
"json-rest-schema": "^1.0.
|
|
21
|
+
"@jskit-ai/resource-core": "0.1.209",
|
|
22
|
+
"@jskit-ai/resource-crud-core": "0.1.210",
|
|
23
|
+
"@jskit-ai/storage-runtime": "0.1.264",
|
|
24
|
+
"@jskit-ai/uploads-runtime": "0.2.18",
|
|
25
|
+
"json-rest-schema": "^1.0.20"
|
|
26
26
|
},
|
|
27
27
|
"description": "Users/account runtime plus HTTP routes for account features.",
|
|
28
28
|
"jskit": {
|
|
@@ -196,10 +196,10 @@
|
|
|
196
196
|
}
|
|
197
197
|
},
|
|
198
198
|
"peerDependencies": {
|
|
199
|
-
"@jskit-ai/auth-core": "0.2.
|
|
200
|
-
"@jskit-ai/database-runtime": "0.1.
|
|
201
|
-
"@jskit-ai/http-runtime": "0.2.
|
|
202
|
-
"@jskit-ai/kernel": "0.2.
|
|
203
|
-
"@jskit-ai/resource-runtime": "0.2.
|
|
199
|
+
"@jskit-ai/auth-core": "0.2.18",
|
|
200
|
+
"@jskit-ai/database-runtime": "0.1.267",
|
|
201
|
+
"@jskit-ai/http-runtime": "0.2.18",
|
|
202
|
+
"@jskit-ai/kernel": "0.2.18",
|
|
203
|
+
"@jskit-ai/resource-runtime": "0.2.21"
|
|
204
204
|
}
|
|
205
205
|
}
|
|
@@ -38,9 +38,13 @@ variant also names `visibility: "workspace"`: its routes are a workspace's,
|
|
|
38
38
|
so they resolve the caller's workspace and check its `crud.users.*`
|
|
39
39
|
permissions. The `users` table is public, every user's, so the variant also
|
|
40
40
|
narrows the repository to the workspace's members with `decorateRepository`
|
|
41
|
-
(`src/server/workspaceMembersOnly.js`): a list reads only the active members
|
|
42
|
-
|
|
43
|
-
|
|
41
|
+
(`src/server/workspaceMembersOnly.js`): a list reads only the active members,
|
|
42
|
+
and anyone else is a missing record, so a workspace admin never learns who else
|
|
43
|
+
has an account. Each page is one report over users.profiles' and
|
|
44
|
+
`workspaces.memberships`' join sources: the users the list's filters match that
|
|
45
|
+
hold an active membership, in the users list's order, a page at a time, so it
|
|
46
|
+
never reads the workspace's memberships whole; a view reads the one membership
|
|
47
|
+
with `findByWorkspaceIdAndUserId`. The narrowed
|
|
44
48
|
repository answers only `query`, `get` and `pageLimits`: users.profiles' other
|
|
45
49
|
methods (`findByEmail`, `countUsers`, the writes) read or write every user, so
|
|
46
50
|
they never pass through it.
|
|
@@ -10,9 +10,9 @@
|
|
|
10
10
|
"./shared": "./src/shared/index.js"
|
|
11
11
|
},
|
|
12
12
|
"dependencies": {
|
|
13
|
-
"@jskit-ai/crud-core": "0.2.
|
|
14
|
-
"@jskit-ai/resource-crud-core": "0.1.
|
|
15
|
-
"@jskit-ai/users-core": "0.2.
|
|
13
|
+
"@jskit-ai/crud-core": "0.2.24",
|
|
14
|
+
"@jskit-ai/resource-crud-core": "0.1.210",
|
|
15
|
+
"@jskit-ai/users-core": "0.2.25"
|
|
16
16
|
},
|
|
17
17
|
"jskit": {
|
|
18
18
|
"kind": "runtime",
|
|
@@ -10,14 +10,14 @@
|
|
|
10
10
|
"./shared": "./src/shared/index.js"
|
|
11
11
|
},
|
|
12
12
|
"dependencies": {
|
|
13
|
-
"@jskit-ai/crud-core": "0.2.
|
|
14
|
-
"@jskit-ai/resource-crud-core": "0.1.
|
|
15
|
-
"@jskit-ai/users-core": "0.2.
|
|
16
|
-
"@jskit-ai/workspaces-core": "0.2.
|
|
13
|
+
"@jskit-ai/crud-core": "0.2.24",
|
|
14
|
+
"@jskit-ai/resource-crud-core": "0.1.210",
|
|
15
|
+
"@jskit-ai/users-core": "0.2.25",
|
|
16
|
+
"@jskit-ai/workspaces-core": "0.2.25"
|
|
17
17
|
},
|
|
18
18
|
"peerDependencies": {
|
|
19
|
-
"@jskit-ai/kernel": "0.2.
|
|
20
|
-
"@jskit-ai/resource-runtime": "0.2.
|
|
19
|
+
"@jskit-ai/kernel": "0.2.18",
|
|
20
|
+
"@jskit-ai/resource-runtime": "0.2.21"
|
|
21
21
|
},
|
|
22
22
|
"jskit": {
|
|
23
23
|
"kind": "runtime",
|
|
@@ -1,43 +1,95 @@
|
|
|
1
1
|
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
2
2
|
import { passedOn, resolveWorkspaceScopeValue } from "@jskit-ai/resource-runtime/server";
|
|
3
3
|
|
|
4
|
+
// The page size json-rest-api reads for a list that names none.
|
|
5
|
+
const DEFAULT_PAGE_SIZE = 20;
|
|
6
|
+
|
|
7
|
+
// A page's cursor: the display name, email and id of its last user, the users list's order, as base64url JSON.
|
|
8
|
+
function encodeCursor(row) {
|
|
9
|
+
return Buffer.from(JSON.stringify([row.displayName, row.email, String(row.id)])).toString("base64url");
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function decodeCursor(cursor) {
|
|
13
|
+
try {
|
|
14
|
+
const [displayName, email, id] = JSON.parse(Buffer.from(String(cursor), "base64url").toString("utf8"));
|
|
15
|
+
if ([displayName, email, id].every((value) => typeof value === "string")) {
|
|
16
|
+
return { displayName, email, id };
|
|
17
|
+
}
|
|
18
|
+
} catch {
|
|
19
|
+
// Not a cursor this list answered: refused below.
|
|
20
|
+
}
|
|
21
|
+
throw new AppError(400, "This list's cursor is not one it answered.", { code: "users.list.cursorInvalid" });
|
|
22
|
+
}
|
|
23
|
+
|
|
4
24
|
/**
|
|
5
25
|
* users-core's users repository narrowed to the caller's workspace: a list reads only the workspace's active members,
|
|
6
26
|
* 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
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
27
|
+
* public, so its handle alone would list every user. A page is one report over the users the list's filters match
|
|
28
|
+
* that hold an active membership in the workspace, in the users list's order, so it reads a page of rows however many
|
|
29
|
+
* members the workspace has; the users repository then reads that page's users as the CRUD contract answers them. It
|
|
30
|
+
* answers only the reads it narrows (query and get, with pageLimits): the rest of users.profiles, such as findByEmail
|
|
31
|
+
* or countUsers, never passes through this feature's repository, so nothing reaches users past the narrowing through it.
|
|
32
|
+
* @param {import("@jskit-ai/crud-core/server/types").CrudRepository & Pick<import("@jskit-ai/users-core/server/types").UsersProfiles, "joinSource">} repository
|
|
33
|
+
* @param {import("@jskit-ai/workspaces-core/server/types").WorkspacesMemberships} memberships
|
|
12
34
|
*/
|
|
13
35
|
function workspaceMembersOnly(repository, memberships) {
|
|
14
|
-
//
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
36
|
+
// Knex: report - one page of the users the list's filters match that are active members of the workspace, in the users list's order
|
|
37
|
+
async function memberPage(workspaceId, filters, { size, after }, options) {
|
|
38
|
+
const user = await repository.joinSource({ alias: "u", ...(filters === undefined ? {} : { filters }) }, options);
|
|
39
|
+
const member = await memberships.joinSource({ alias: "m", filters: { workspace: workspaceId, status: "active" } }, options);
|
|
40
|
+
const [shown, mail, key] = [user.column("displayName"), user.column("email"), user.column("id")];
|
|
41
|
+
const query = user.query
|
|
42
|
+
.whereExists(member.query.select(member.column("id")).whereColumn(member.column("userId"), key))
|
|
43
|
+
.select({ id: key, displayName: shown, email: mail })
|
|
44
|
+
.orderBy([shown, mail, key])
|
|
45
|
+
.limit(size + 1);
|
|
46
|
+
if (after !== undefined) {
|
|
47
|
+
const last = decodeCursor(after);
|
|
48
|
+
query.where((later) => later.where(shown, ">", last.displayName)
|
|
49
|
+
.orWhere((tie) => tie.where(shown, last.displayName).where(mail, ">", last.email))
|
|
50
|
+
.orWhere((tie) => tie.where(shown, last.displayName).where(mail, last.email).where(key, ">", last.id)));
|
|
51
|
+
}
|
|
52
|
+
const rows = await query;
|
|
53
|
+
return { ids: rows.slice(0, size).map((row) => String(row.id)), next: rows.length > size ? encodeCursor(rows[size - 1]) : null };
|
|
18
54
|
}
|
|
19
55
|
|
|
20
56
|
/**
|
|
21
|
-
* One page of the workspace's members the params select
|
|
57
|
+
* One page of the workspace's members the params select: the report picks the page's users, the users repository
|
|
58
|
+
* reads them, and the page's cursor is the report's.
|
|
22
59
|
* @param {Record<string, any>} params
|
|
23
60
|
* @param {{ context?: object }} options
|
|
24
61
|
*/
|
|
25
62
|
async function query(params, options) {
|
|
26
|
-
const
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
63
|
+
const workspaceId = resolveWorkspaceScopeValue(options.context);
|
|
64
|
+
const size = Number(params.page?.size ?? DEFAULT_PAGE_SIZE);
|
|
65
|
+
const after = params.page?.after;
|
|
66
|
+
// A context with no workspace has no members: the page is empty.
|
|
67
|
+
const page = workspaceId
|
|
68
|
+
? await memberPage(workspaceId, params.filters, { size: Math.min(size, repository.pageLimits().request), after }, passedOn(options))
|
|
69
|
+
: { ids: [], next: null };
|
|
70
|
+
// An empty list matches no row. A size over the page limit throws here, as the users list's own read does.
|
|
71
|
+
const result = await repository.query({ ...params, filters: { id: page.ids }, page: { size } }, options);
|
|
72
|
+
const hasMore = page.next !== null;
|
|
73
|
+
if (options.format !== "jsonapi") {
|
|
74
|
+
return { records: result.records, page: { size, hasMore, next: page.next } };
|
|
75
|
+
}
|
|
76
|
+
// The users read's own links would name its id list; the page's cursor is the report's.
|
|
77
|
+
const { links: _links, ...document } = result;
|
|
78
|
+
return {
|
|
79
|
+
...document,
|
|
80
|
+
meta: { ...document.meta, pagination: { pageSize: size, hasMore, ...(hasMore ? { cursor: { next: page.next } } : {}) } }
|
|
81
|
+
};
|
|
31
82
|
}
|
|
32
83
|
|
|
33
84
|
/**
|
|
34
|
-
* A member of the workspace, or a missing record for anyone else.
|
|
85
|
+
* A member of the workspace, or a missing record for anyone else. It reads the one membership.
|
|
35
86
|
* @param {unknown} id
|
|
36
87
|
* @param {Record<string, any>} params
|
|
37
88
|
* @param {{ context?: object, missing?: "skip" }} options
|
|
38
89
|
*/
|
|
39
90
|
async function get(id, params, options) {
|
|
40
|
-
|
|
91
|
+
const membership = await memberships.findByWorkspaceIdAndUserId(resolveWorkspaceScopeValue(options.context), id, passedOn(options));
|
|
92
|
+
if (membership?.status === "active") {
|
|
41
93
|
return repository.get(id, params, options);
|
|
42
94
|
}
|
|
43
95
|
if (options.missing === "skip") {
|
|
@@ -456,8 +456,9 @@ function createRepository({ userProfiles, userSettings }) {
|
|
|
456
456
|
const normalizedUserId = normalizeDbRecordId(userId, { fallback: null });
|
|
457
457
|
try {
|
|
458
458
|
return await userProfiles.withTransaction(options, async (txOptions) => {
|
|
459
|
-
|
|
460
|
-
|
|
459
|
+
// Usernames are unique, so one row answers who holds it.
|
|
460
|
+
const [holder] = await userProfiles.queryAll({ filters: { usernames: [normalizedUsername] }, take: 1 }, txOptions);
|
|
461
|
+
if (holder && normalizeDbRecordId(holder.id, { fallback: null }) !== normalizedUserId) {
|
|
461
462
|
throw buildDuplicateUsernameConflictError();
|
|
462
463
|
}
|
|
463
464
|
return patchProfile(userId, { username: normalizedUsername }, txOptions);
|
|
@@ -92,7 +92,9 @@ test("both user administration variants stay read-only on users-core's one users
|
|
|
92
92
|
}
|
|
93
93
|
});
|
|
94
94
|
|
|
95
|
-
|
|
95
|
+
// The list's pages are proved on the database in workspaces-core's userAdministrationExample.mysql.test.js: each page is
|
|
96
|
+
// chosen in SQL, so no statement reads the workspace's memberships whole.
|
|
97
|
+
test("the workspace variant shows only the caller's workspace's active members, reading one membership", async () => {
|
|
96
98
|
const { workspaceMembersOnly } = await import(pathToFileURL(path.join(
|
|
97
99
|
patternRoot, "example", "packages", "users-workspace", "src", "server", "workspaceMembersOnly.js"
|
|
98
100
|
)).href);
|
|
@@ -100,38 +102,38 @@ test("the workspace variant lists and shows only the caller's workspace's active
|
|
|
100
102
|
const repository = {
|
|
101
103
|
query: async (params) => (calls.push(["query", params.filters]), { data: [] }),
|
|
102
104
|
get: async (id) => (calls.push(["get", id]), { data: { id } }),
|
|
103
|
-
pageLimits: () => ({}),
|
|
105
|
+
pageLimits: () => ({ request: 100 }),
|
|
104
106
|
// users.profiles' other methods read and write every user.
|
|
105
107
|
findByEmail: async () => ({ id: "3" }),
|
|
106
108
|
countUsers: async () => 3,
|
|
107
109
|
upsert: async () => ({ id: "3" })
|
|
108
110
|
};
|
|
109
111
|
const memberCalls = [];
|
|
112
|
+
const statuses = new Map([["7:1", "active"], ["7:2", "revoked"]]);
|
|
110
113
|
const memberships = {
|
|
111
|
-
|
|
114
|
+
findByWorkspaceIdAndUserId: async (workspaceId, userId, callOptions) => {
|
|
115
|
+
memberCalls.push([workspaceId, userId, callOptions]);
|
|
116
|
+
const status = statuses.get(`${workspaceId}:${userId}`);
|
|
117
|
+
return status ? { workspaceId, userId, status } : null;
|
|
118
|
+
}
|
|
112
119
|
};
|
|
113
120
|
const users = workspaceMembersOnly(repository, memberships);
|
|
114
121
|
const options = { context: { workspace: { id: "7" } } };
|
|
115
122
|
|
|
116
|
-
await users.query({ filters: { q: "ann" }, page: { size: 20 } }, options);
|
|
117
|
-
await users.query({ filters: { id: ["2", "3"] } }, options);
|
|
118
|
-
await users.query({ filters: { id: "3" } }, options);
|
|
119
|
-
await users.query({}, { context: { workspace: { id: "8" } } });
|
|
120
|
-
assert.deepEqual(calls.splice(0), [
|
|
121
|
-
["query", { q: "ann", id: ["1", "2"] }],
|
|
122
|
-
["query", { id: ["2"] }],
|
|
123
|
-
["query", { id: [] }],
|
|
124
|
-
["query", { id: [] }]
|
|
125
|
-
]);
|
|
126
123
|
assert.deepEqual(await users.get("1", {}, options), { data: { id: "1" } });
|
|
124
|
+
assert.equal(await users.get("2", {}, { ...options, missing: "skip" }), null);
|
|
127
125
|
assert.equal(await users.get("3", {}, { ...options, missing: "skip" }), null);
|
|
128
126
|
await assert.rejects(users.get("3", {}, options), (error) => error.status === 404 && error.code === "crud.document.notFound");
|
|
127
|
+
await assert.rejects(users.get("1", {}, { context: { workspace: { id: "8" } } }), (error) => error.status === 404);
|
|
129
128
|
assert.deepEqual(calls, [["get", "1"]]);
|
|
129
|
+
// A context with no workspace lists nobody, without reading memberships.
|
|
130
|
+
await users.query({ page: { size: 20 } }, { context: {}, format: "jsonapi" });
|
|
131
|
+
assert.deepEqual(calls.at(-1), ["query", { id: [] }]);
|
|
130
132
|
assert.equal(users.pageLimits, repository.pageLimits);
|
|
131
133
|
// Only the narrowed reads pass through: nothing else of users.profiles reaches users past the workspace.
|
|
132
134
|
assert.deepEqual(Object.keys(users).sort(), ["get", "pageLimits", "query"]);
|
|
133
|
-
// The
|
|
135
|
+
// The membership read gets only the context and transaction, never the view's own settings.
|
|
134
136
|
const trx = { id: "trx" };
|
|
135
|
-
await users.
|
|
136
|
-
assert.deepEqual(memberCalls.at(-1), { context: options.context, trx });
|
|
137
|
+
await users.get("1", {}, { ...options, trx, format: "jsonapi", missing: "skip" });
|
|
138
|
+
assert.deepEqual(memberCalls.at(-1), ["7", "1", { context: options.context, trx }]);
|
|
137
139
|
});
|