@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
@@ -0,0 +1,384 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
4
+ import { findDuplicateEntryError } from "@jskit-ai/database-runtime/shared";
5
+ import { createRepository as createUserProfilesRepository } from "../src/server/common/repositories/userProfilesRepository.js";
6
+ import { createRepository as createUserSettingsRepository } from "../src/server/common/repositories/userSettingsRepository.js";
7
+ import { DEFAULT_USER_SETTINGS } from "../src/shared/settings.js";
8
+ import { usersDatabase } from "./support/usersDatabases.js";
9
+
10
+ // users.profiles and users.settings on MariaDB/MySQL, on the users and user_settings table handles: the records
11
+ // they answer, the username a new profile gets, transactions, and a standalone insert that loses a race.
12
+ const database = usersDatabase("users_repos");
13
+ const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u;
14
+
15
+ const identityOf = (tag, extra = {}) => ({
16
+ authProvider: "local",
17
+ authProviderUserSid: `identity-${tag}`,
18
+ email: `${tag}@example.test`,
19
+ displayName: tag,
20
+ ...extra
21
+ });
22
+
23
+ // A profile row written past the repository, as another request would have.
24
+ async function insertProfile(db, tag, extra = {}) {
25
+ const [id] = await db.knex("users").insert({
26
+ auth_provider: "local",
27
+ auth_provider_user_sid: `identity-${tag}`,
28
+ email: `${tag}@example.test`,
29
+ username: tag,
30
+ display_name: tag,
31
+ ...extra
32
+ });
33
+ return String(id);
34
+ }
35
+
36
+ // The statements a call sends.
37
+ async function statementsOf(db, work) {
38
+ let count = 0;
39
+ const listener = () => { count += 1; };
40
+ db.knex.on("query", listener);
41
+ try {
42
+ return { result: await work(), count };
43
+ } finally {
44
+ db.knex.off("query", listener);
45
+ }
46
+ }
47
+
48
+ test("withTransaction answers its work's value, commits with it and rolls back with it", async () => {
49
+ requireTestDatabase(process.env);
50
+ const db = await database.open();
51
+ for (const repository of [db.profiles, db.settings]) {
52
+ assert.deepEqual(await repository.withTransaction({}, async () => ({ answered: true })), { answered: true });
53
+ const failure = new Error("Participant failed");
54
+ // The managed transaction rolls back, and the participant's own failure reaches the caller.
55
+ await assert.rejects(repository.withTransaction({}, async () => { throw failure; }), (error) => error === failure);
56
+ }
57
+ const failure = new Error("Abort");
58
+ await assert.rejects(db.profiles.withTransaction({}, async (txOptions) => {
59
+ await db.profiles.createWithSettings({ profile: identityOf("rolled") }, txOptions);
60
+ throw failure;
61
+ }), (error) => error === failure);
62
+ assert.equal(await db.profiles.findByIdentity({ provider: "local", providerUserId: "identity-rolled" }), null);
63
+ const kept = await db.profiles.withTransaction({}, (txOptions) => db.profiles.createWithSettings({
64
+ profile: identityOf("kept"),
65
+ settings: { theme: "dark" }
66
+ }, txOptions));
67
+ assert.equal(kept.settings.theme, "dark");
68
+ assert.equal((await db.settings.findByUserId(kept.profile.id)).theme, "dark");
69
+ });
70
+
71
+ test("a profile reads back normalized, by id, email or identity; an unknown one is null", async () => {
72
+ requireTestDatabase(process.env);
73
+ const db = await database.open();
74
+ const created = await db.profiles.upsert(identityOf("reads", { email: " Reads@Example.TEST ", authProvider: " LOCAL " }));
75
+ assert.deepEqual(Object.keys(created), [
76
+ "id", "authProvider", "authProviderUserSid", "email", "username", "displayName",
77
+ "avatarStorageKey", "avatarVersion", "avatarUpdatedAt", "createdAt", "updatedAt"
78
+ ]);
79
+ assert.match(created.id, /^\d+$/u);
80
+ assert.equal(created.email, "reads@example.test");
81
+ assert.equal(created.authProvider, "local");
82
+ assert.equal(created.username, "reads", "the username comes from the email's local part");
83
+ assert.match(created.createdAt, ISO);
84
+ assert.equal(created.avatarStorageKey, null);
85
+
86
+ assert.deepEqual(await db.profiles.findById(created.id), created);
87
+ assert.deepEqual(await db.profiles.findByEmail(" READS@example.test "), created);
88
+ assert.deepEqual(await db.profiles.findByIdentity({ provider: " Local ", providerUserId: "identity-reads" }), created);
89
+ assert.equal(await db.profiles.findByEmail("nobody@example.test"), null);
90
+ assert.equal(await db.profiles.findById("999999999"), null);
91
+ assert.equal(await db.profiles.findById("not-an-id"), null);
92
+ assert.equal(await db.profiles.findByIdentity({ provider: "local", providerUserId: "nobody" }), null);
93
+ });
94
+
95
+ test("an upsert of a known identity patches its email and name and keeps its username", async () => {
96
+ requireTestDatabase(process.env);
97
+ const db = await database.open();
98
+ const created = await db.profiles.upsert(identityOf("renamed"));
99
+ const updated = await db.profiles.upsert(identityOf("renamed", {
100
+ email: " RENAMED.NEW@EXAMPLE.TEST ",
101
+ displayName: "Renamed Again",
102
+ username: "ignored"
103
+ }));
104
+ assert.equal(updated.id, created.id);
105
+ assert.equal(updated.email, "renamed.new@example.test");
106
+ assert.equal(updated.displayName, "Renamed Again");
107
+ assert.equal(updated.username, "renamed");
108
+ assert.match(updated.updatedAt, ISO);
109
+ await assert.rejects(db.profiles.upsert({ authProvider: "local", email: "x@example.test", displayName: "x" }),
110
+ /upsert requires provider\/authProvider and providerUserId\/authProviderUserSid\./u);
111
+ await assert.rejects(db.profiles.upsert({ authProvider: "local", authProviderUserSid: "x", displayName: "x" }),
112
+ /upsert requires email and displayName\./u);
113
+ });
114
+
115
+ test("the display name and avatar updates answer the changed profile", async () => {
116
+ requireTestDatabase(process.env);
117
+ const db = await database.open();
118
+ const created = await db.profiles.upsert(identityOf("avatar"));
119
+ assert.equal((await db.profiles.updateDisplayNameById(created.id, "Avatar Person")).displayName, "Avatar Person");
120
+ const avatarUpdatedAt = new Date("2026-04-21T12:00:00.000Z");
121
+ const withAvatar = await db.profiles.updateAvatarById(created.id, {
122
+ avatarStorageKey: "avatars/1.png",
123
+ avatarVersion: "v1",
124
+ avatarUpdatedAt
125
+ });
126
+ assert.equal(withAvatar.avatarStorageKey, "avatars/1.png");
127
+ assert.equal(withAvatar.avatarVersion, "v1");
128
+ assert.equal(withAvatar.avatarUpdatedAt, avatarUpdatedAt.toISOString());
129
+ assert.match(withAvatar.updatedAt, ISO);
130
+ const cleared = await db.profiles.clearAvatarById(created.id);
131
+ assert.deepEqual([cleared.avatarStorageKey, cleared.avatarVersion, cleared.avatarUpdatedAt], [null, null, null]);
132
+ assert.equal(await db.profiles.updateDisplayNameById("", "Nobody"), null);
133
+ });
134
+
135
+ test("a new profile gets the first free username of base, base-2 to base-1000, in the same statements however many are taken", async () => {
136
+ requireTestDatabase(process.env);
137
+ const db = await database.open();
138
+ const first = await statementsOf(db, () => db.profiles.upsert(identityOf("ada-one", { email: "ada@one.example.test" })));
139
+ assert.equal(first.result.username, "ada");
140
+ await insertProfile(db, "ada-3", { email: "ada-3@example.test" });
141
+ await insertProfile(db, "ada-2", { email: "ada-2@example.test" });
142
+ const third = await statementsOf(db, () => db.profiles.upsert(identityOf("ada-two", { email: "ada@two.example.test" })));
143
+ assert.equal(third.result.username, "ada-4");
144
+ assert.equal(third.count, first.count, `${first.count} and ${third.count} statements`);
145
+ assert.equal((await db.profiles.upsert(identityOf("ada-three", { email: "x@three.example.test", username: "Ada" }))).username,
146
+ "ada-5", "a requested username is the base");
147
+
148
+ const longLocal = "b".repeat(130);
149
+ assert.equal((await db.profiles.upsert(identityOf("long-one", { email: `${longLocal}@one.example.test` }))).username,
150
+ "b".repeat(120));
151
+ assert.equal((await db.profiles.upsert(identityOf("long-two", { email: `${longLocal}@two.example.test` }))).username,
152
+ `${"b".repeat(118)}-2`, "a long base is trimmed so the suffixed name fits");
153
+ });
154
+
155
+ test("a new profile is refused when base to base-1000 are all taken", async () => {
156
+ requireTestDatabase(process.env);
157
+ const db = await database.open();
158
+ const taken = ["cy", ...Array.from({ length: 998 }, (_, index) => `cy-${index + 2}`)];
159
+ await db.knex.batchInsert("users", taken.map((username) => ({
160
+ auth_provider: "local",
161
+ auth_provider_user_sid: `identity-${username}`,
162
+ email: `${username}@taken.example.test`,
163
+ username,
164
+ display_name: username
165
+ })), 500);
166
+ assert.equal((await db.profiles.upsert(identityOf("cy-last", { email: "cy@last.example.test" }))).username, "cy-1000");
167
+ await assert.rejects(db.profiles.upsert(identityOf("cy-none", { email: "cy@none.example.test" })),
168
+ /Unable to generate unique username\./u);
169
+ });
170
+
171
+ test("an email another identity holds is USER_PROFILE_EMAIL_CONFLICT, failing a caller's transaction", async () => {
172
+ requireTestDatabase(process.env);
173
+ const db = await database.open();
174
+ await db.profiles.upsert(identityOf("held"));
175
+ await assert.rejects(db.profiles.upsert(identityOf("thief", { email: "held@example.test" })), (error) => {
176
+ assert.equal(error.code, "USER_PROFILE_EMAIL_CONFLICT");
177
+ assert.equal(error.transactionOutcome, "rolledBack");
178
+ assert.ok(findDuplicateEntryError(error.cause));
179
+ return true;
180
+ });
181
+ let participant = null;
182
+ await assert.rejects(db.profiles.withTransaction({}, async (txOptions) => {
183
+ try {
184
+ await db.profiles.upsert(identityOf("thief", { email: "held@example.test" }), txOptions);
185
+ } catch (error) {
186
+ participant = error;
187
+ throw error;
188
+ }
189
+ }), (error) => error.transactionOutcome === "rolledBack");
190
+ assert.equal(participant.code, "USER_PROFILE_EMAIL_CONFLICT");
191
+ assert.equal(participant.transactionOutcome, "pending");
192
+ assert.equal(await db.profiles.findByIdentity({ provider: "local", providerUserId: "identity-thief" }), null);
193
+ });
194
+
195
+ test("a standalone profile insert that loses its identity to another answers the winner; in a caller's transaction it fails", async () => {
196
+ requireTestDatabase(process.env);
197
+ const db = await database.open();
198
+ let raceNext = true;
199
+ let competitor = null;
200
+ // Another request creates the same identity between this upsert's read and its insert.
201
+ const racing = createUserProfilesRepository({
202
+ userProfiles: {
203
+ ...db.resources.userProfiles,
204
+ async create(attributes, options) {
205
+ if (raceNext) {
206
+ raceNext = false;
207
+ competitor = await insertProfile(db, "race", { email: "race.winner@example.test", username: "race-winner" });
208
+ }
209
+ return db.resources.userProfiles.create(attributes, options);
210
+ }
211
+ },
212
+ userSettings: db.settings
213
+ });
214
+ const answered = await racing.upsert(identityOf("race"));
215
+ assert.equal(answered.id, competitor);
216
+ assert.equal(answered.email, "race.winner@example.test", "the winner's record, read after the insert rolled back");
217
+
218
+ await db.knex("users").where({ id: competitor }).delete();
219
+ raceNext = true;
220
+ let participant = null;
221
+ await assert.rejects(racing.withTransaction({}, async (txOptions) => {
222
+ try {
223
+ return await racing.upsert(identityOf("race"), txOptions);
224
+ } catch (error) {
225
+ participant = error;
226
+ throw error;
227
+ }
228
+ }), (error) => error.transactionOutcome === "rolledBack");
229
+ assert.equal(participant.transactionOutcome, "pending", "the caller's transaction is failed, not recovered");
230
+ assert.ok(findDuplicateEntryError(participant));
231
+ });
232
+
233
+ test("user settings start from the defaults once, join a caller's transaction, and a lost standalone insert reads the winner", async () => {
234
+ requireTestDatabase(process.env);
235
+ const db = await database.open();
236
+ const userId = await insertProfile(db, "settings");
237
+ assert.equal(await db.settings.findByUserId(userId), null);
238
+ const ensured = await db.settings.ensureForUserId(userId);
239
+ assert.equal(ensured.id, userId);
240
+ for (const [key, value] of Object.entries(DEFAULT_USER_SETTINGS)) assert.deepEqual(ensured[key], value, key);
241
+ assert.deepEqual(await db.settings.ensureForUserId(userId), ensured, "a second call reads the same record");
242
+ assert.equal((await db.settings.updatePreferences(userId, { theme: "dark", unknown: "dropped" })).theme, "dark");
243
+ const passwordOff = await db.settings.updatePasswordSignInEnabled(userId, false, { passwordSetupRequired: true });
244
+ assert.deepEqual([passwordOff.passwordSignInEnabled, passwordOff.passwordSetupRequired], [false, true]);
245
+ await assert.rejects(db.settings.ensureForUserId("not-an-id"), /requires a valid user id/u);
246
+
247
+ const rolledBack = await insertProfile(db, "settings-rolled");
248
+ await assert.rejects(db.settings.withTransaction({}, async (txOptions) => {
249
+ await db.settings.ensureForUserId(rolledBack, txOptions);
250
+ throw new Error("Abort");
251
+ }), /Abort/u);
252
+ assert.equal(await db.settings.findByUserId(rolledBack), null, "it rolls back with the caller's transaction");
253
+
254
+ const raced = await insertProfile(db, "settings-race");
255
+ const racing = createUserSettingsRepository({
256
+ userSettings: {
257
+ ...db.resources.userSettings,
258
+ async create(attributes, options) {
259
+ await db.knex("user_settings").insert({ user_id: raced, theme: "light" });
260
+ return db.resources.userSettings.create(attributes, options);
261
+ }
262
+ }
263
+ });
264
+ assert.equal((await racing.ensureForUserId(raced)).theme, "light", "the winner's settings");
265
+ await db.knex("user_settings").where({ user_id: raced }).delete();
266
+ await assert.rejects(racing.withTransaction({}, (txOptions) => racing.ensureForUserId(raced, txOptions)),
267
+ (error) => error.transactionOutcome === "rolledBack" && Boolean(findDuplicateEntryError(error)));
268
+ });
269
+
270
+ test("countUsers counts every user, or those created since a time, leaving out the excluded", async () => {
271
+ requireTestDatabase(process.env);
272
+ const db = await database.open();
273
+ const before = await db.profiles.countUsers();
274
+ const one = await db.profiles.upsert(identityOf("count-one"));
275
+ await db.profiles.upsert(identityOf("count-two"));
276
+ assert.equal(await db.profiles.countUsers(), before + 2);
277
+ assert.equal(await db.profiles.countUsers({ excludeIds: [one.id, one.id, "999999999"] }), before + 1);
278
+ assert.equal(await db.profiles.countUsers({ createdSince: new Date(Date.now() + 86400000) }), 0);
279
+ });
280
+
281
+ test("users.profiles serves a CRUD feature's reads, with JSON:API documents passed through", async () => {
282
+ requireTestDatabase(process.env);
283
+ const db = await database.open();
284
+ const created = await db.profiles.upsert(identityOf("crud"));
285
+ const page = await db.profiles.query({ filters: { email: "crud@example.test" }, page: { size: 5 } }, {});
286
+ assert.deepEqual(page.records.map(({ id }) => id), [created.id]);
287
+ const document = await db.profiles.get(created.id, {}, { format: "jsonapi" });
288
+ assert.equal(document.data.id, created.id);
289
+ assert.equal(document.data.attributes.email, "crud@example.test");
290
+ assert.equal(typeof db.profiles.pageLimits().request, "number");
291
+ });
292
+
293
+ test("countUsers counts only the users of one sign-in provider when asked", async () => {
294
+ requireTestDatabase(process.env);
295
+ const db = await database.open();
296
+ const before = await db.profiles.countUsers({ authProvider: "oidc-count" });
297
+ await db.profiles.upsert(identityOf("provider-a", { authProvider: "oidc-count" }));
298
+ await db.profiles.upsert(identityOf("provider-b"));
299
+ assert.equal(await db.profiles.countUsers({ authProvider: " OIDC-Count " }), before + 1);
300
+ });
301
+
302
+ test("createWithId creates a profile with the id it is given; a taken id fails", async () => {
303
+ requireTestDatabase(process.env);
304
+ const db = await database.open();
305
+ await insertProfile(db, "legacy-name");
306
+ const created = await db.profiles.createWithId(identityOf("legacy", { id: "880001", username: "legacy-name" }));
307
+ assert.equal(created.id, "880001");
308
+ // The username is made unique, as a new profile's always is.
309
+ assert.equal(created.username, "legacy-name-2");
310
+ assert.match(created.createdAt, ISO);
311
+ assert.equal((await db.profiles.findById("880001")).email, "legacy@example.test");
312
+ await assert.rejects(db.profiles.createWithId(identityOf("legacy-again", { id: "880001" })),
313
+ (error) => Boolean(findDuplicateEntryError(error)));
314
+ await assert.rejects(db.profiles.createWithId(identityOf("no-id")), /createWithId requires id/u);
315
+ await assert.rejects(db.profiles.createWithId({ id: "880002", email: "x@example.test" }),
316
+ /createWithId requires authProvider, authProviderUserSid, displayName/u);
317
+ });
318
+
319
+ test("listByEmails answers the profiles of a set of emails in one read", async () => {
320
+ requireTestDatabase(process.env);
321
+ const db = await database.open();
322
+ const one = await db.profiles.upsert(identityOf("emails-one"));
323
+ const two = await db.profiles.upsert(identityOf("emails-two"));
324
+ const { result, count } = await statementsOf(db, () => db.profiles.listByEmails([
325
+ " Emails-One@Example.TEST ", "emails-two@example.test", "emails-one@example.test", "nobody@example.test"
326
+ ]));
327
+ assert.deepEqual(result.map(({ id }) => id).sort(), [one.id, two.id].sort());
328
+ assert.equal(count, 1);
329
+ assert.deepEqual(await db.profiles.listByEmails([]), []);
330
+ await assert.rejects(db.profiles.listByEmails("one@example.test"), /takes an array of emails/u);
331
+ });
332
+
333
+ test("createManyIgnoringExisting creates the new identities, keeps the existing ones and runs only as background work", async () => {
334
+ requireTestDatabase(process.env);
335
+ const db = await database.open();
336
+ const existing = await db.profiles.upsert(identityOf("bulk-existing"));
337
+ const rows = [
338
+ identityOf("bulk-existing", { email: "bulk-changed@example.test", displayName: "Changed", username: "bulk-changed" }),
339
+ identityOf("bulk-new-one", { username: "bulk-new-one" }),
340
+ identityOf("bulk-new-two", { username: "bulk-new-two" })
341
+ ];
342
+ await assert.rejects(db.profiles.createManyIgnoringExisting(rows, {}), /runs only in a system context/u);
343
+ await assert.rejects(
344
+ db.profiles.createManyIgnoringExisting([identityOf("bulk-no-username")], { context: db.systemContext }),
345
+ /row 0 requires username/u
346
+ );
347
+
348
+ const ids = await db.profiles.createManyIgnoringExisting(rows, { context: db.systemContext });
349
+ const created = await db.profiles.listByEmails(["bulk-new-one@example.test", "bulk-new-two@example.test"]);
350
+ assert.deepEqual(created.map(({ id }) => id).sort(), [...ids].sort());
351
+ assert.equal(ids.length, 2);
352
+ // The existing identity's profile is untouched.
353
+ assert.deepEqual(await db.profiles.findById(existing.id), existing);
354
+
355
+ // Running it again creates nothing.
356
+ assert.deepEqual(await db.profiles.createManyIgnoringExisting(rows, { context: db.systemContext }), []);
357
+ });
358
+
359
+ test("changeUsername gives a profile a free username and refuses one another profile holds", async () => {
360
+ requireTestDatabase(process.env);
361
+ const db = await database.open();
362
+ const mine = await db.profiles.upsert(identityOf("rename-mine"));
363
+ const other = await db.profiles.upsert(identityOf("rename-other"));
364
+ const renamed = await db.profiles.changeUsername(mine.id, " Rename-Fresh ");
365
+ assert.equal(renamed.username, "rename-fresh");
366
+ assert.equal((await db.profiles.changeUsername(mine.id, "rename-fresh")).username, "rename-fresh");
367
+ // Refused before any write, so the caller's transaction goes on.
368
+ const kept = await db.profiles.withTransaction({}, async (txOptions) => {
369
+ await assert.rejects(db.profiles.changeUsername(mine.id, other.username, txOptions), { code: "USER_PROFILE_USERNAME_CONFLICT" });
370
+ return db.profiles.updateDisplayNameById(mine.id, "Still Mine", txOptions);
371
+ });
372
+ assert.equal(kept.displayName, "Still Mine");
373
+ assert.equal(await db.profiles.changeUsername("999999999", "rename-ghost"), null);
374
+ });
375
+
376
+ test("a users list reads by display name, then email", async () => {
377
+ requireTestDatabase(process.env);
378
+ const db = await database.open();
379
+ for (const [tag, displayName] of [["sort-c", "Sort Bravo"], ["sort-a", "Sort Alpha"], ["sort-b", "Sort Bravo"]]) {
380
+ await db.profiles.upsert(identityOf(tag, { displayName }));
381
+ }
382
+ const page = await db.profiles.query({ filters: { q: "sort-" }, page: { size: 10 } }, {});
383
+ assert.deepEqual(page.records.map(({ email }) => email), ["sort-a@example.test", "sort-b@example.test", "sort-c@example.test"]);
384
+ });
@@ -4,8 +4,8 @@ import path from "node:path";
4
4
  import { existsSync } from "node:fs";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { resolveSchemaTransportSchemaDefinition } from "@jskit-ai/kernel/shared/validators";
7
- import { userProfileResource } from "../src/shared/resources/userProfileResource.js";
8
- import { userSettingsResource } from "../src/shared/resources/userSettingsResource.js";
7
+ import { userProfileContract, userProfileCrud, userProfileTableResource } from "../src/shared/resources/userProfileResource.js";
8
+ import { userSettingsContract, userSettingsCrud, userSettingsTableResource } from "../src/shared/resources/userSettingsResource.js";
9
9
 
10
10
  function assertResourceOperationMessages(resource, operationName, label) {
11
11
  const operation = resource?.operations?.[operationName];
@@ -25,37 +25,73 @@ function assertResourceOperationMessages(resource, operationName, label) {
25
25
  );
26
26
  }
27
27
 
28
- test("users-core resources expose messages for all operations", () => {
29
- const resources = {
30
- userProfile: userProfileResource,
31
- userSettings: userSettingsResource
28
+ test("users-core API contracts expose messages for all operations", () => {
29
+ const contracts = {
30
+ userProfile: userProfileContract,
31
+ userSettings: userSettingsContract
32
32
  };
33
33
 
34
- for (const [label, resource] of Object.entries(resources)) {
35
- for (const operationName of ["view", "list", "create", "replace", "patch"]) {
36
- assertResourceOperationMessages(resource, operationName, label);
34
+ for (const [label, contract] of Object.entries(contracts)) {
35
+ for (const operationName of Object.keys(contract.operations)) {
36
+ assertResourceOperationMessages(contract, operationName, label);
37
37
  }
38
38
  }
39
39
  });
40
40
 
41
+ test("users-core CRUD contracts expose messages for view, list, create, replace and patch", () => {
42
+ const contracts = {
43
+ userProfile: userProfileCrud,
44
+ userSettings: userSettingsCrud
45
+ };
46
+
47
+ for (const [label, contract] of Object.entries(contracts)) {
48
+ assert.equal(contract.namespace, label);
49
+ assert.deepEqual(Object.keys(contract.operations), ["view", "list", "create", "replace", "patch"]);
50
+ for (const operationName of Object.keys(contract.operations)) {
51
+ assertResourceOperationMessages(contract, operationName, label);
52
+ }
53
+ }
54
+ });
55
+
56
+ test("the users and user_settings tables are table resources, apart from their CRUD and API contracts", () => {
57
+ assert.equal(userProfileTableResource.name, "userProfiles");
58
+ assert.equal(userProfileTableResource.tableName, "users");
59
+ assert.equal(userSettingsTableResource.name, "userSettings");
60
+ assert.equal(userSettingsTableResource.tableName, "user_settings");
61
+ assert.equal(Object.hasOwn(userProfileTableResource, "operations"), false);
62
+ assert.equal(Object.hasOwn(userSettingsTableResource, "operations"), false);
63
+ assert.equal(userProfileCrud.resource, userProfileTableResource);
64
+ assert.equal(userSettingsCrud.resource, userSettingsTableResource);
65
+ });
66
+
67
+ test("the users table resource searches display name, email and username with q", () => {
68
+ assert.deepEqual(userProfileTableResource.searchSchema.q, {
69
+ type: "string",
70
+ oneOf: ["displayName", "email", "username"],
71
+ filterOperator: "like",
72
+ splitBy: " ",
73
+ matchAll: true
74
+ });
75
+ });
76
+
41
77
  test("user profile resource exposes managed timestamps used by JSON REST writes", () => {
42
- assert.equal(userProfileResource.schema.createdAt?.type, "dateTime");
43
- assert.equal(userProfileResource.schema.createdAt?.storage?.column, "created_at");
44
- assert.equal(userProfileResource.schema.createdAt?.storage?.writeSerializer, "datetime-utc");
45
- assert.equal(userProfileResource.schema.updatedAt?.type, "dateTime");
46
- assert.equal(userProfileResource.schema.updatedAt?.storage?.column, "updated_at");
47
- assert.equal(userProfileResource.schema.updatedAt?.storage?.writeSerializer, "datetime-utc");
78
+ assert.equal(userProfileTableResource.schema.createdAt?.type, "dateTime");
79
+ assert.equal(userProfileTableResource.schema.createdAt?.storage?.column, "created_at");
80
+ assert.equal(userProfileTableResource.schema.createdAt?.storage?.writeSerializer, "datetime-utc");
81
+ assert.equal(userProfileTableResource.schema.updatedAt?.type, "dateTime");
82
+ assert.equal(userProfileTableResource.schema.updatedAt?.storage?.column, "updated_at");
83
+ assert.equal(userProfileTableResource.schema.updatedAt?.storage?.writeSerializer, "datetime-utc");
48
84
  });
49
85
 
50
86
  test("users-core specialized resource operations expose messages and validators", () => {
51
87
  const operationSpecs = [
52
- { label: "userProfile.avatarUpload", operation: userProfileResource.operations.avatarUpload },
53
- { label: "userProfile.avatarDelete", operation: userProfileResource.operations.avatarDelete },
54
- { label: "userSettings.passwordChange", operation: userSettingsResource.operations.passwordChange },
55
- { label: "userSettings.passwordMethodToggle", operation: userSettingsResource.operations.passwordMethodToggle },
56
- { label: "userSettings.oauthLinkStart", operation: userSettingsResource.operations.oauthLinkStart },
57
- { label: "userSettings.oauthUnlink", operation: userSettingsResource.operations.oauthUnlink },
58
- { label: "userSettings.logoutOtherSessions", operation: userSettingsResource.operations.logoutOtherSessions }
88
+ { label: "userProfile.avatarUpload", operation: userProfileContract.operations.avatarUpload },
89
+ { label: "userProfile.avatarDelete", operation: userProfileContract.operations.avatarDelete },
90
+ { label: "userSettings.passwordChange", operation: userSettingsContract.operations.passwordChange },
91
+ { label: "userSettings.passwordMethodToggle", operation: userSettingsContract.operations.passwordMethodToggle },
92
+ { label: "userSettings.oauthLinkStart", operation: userSettingsContract.operations.oauthLinkStart },
93
+ { label: "userSettings.oauthUnlink", operation: userSettingsContract.operations.oauthUnlink },
94
+ { label: "userSettings.logoutOtherSessions", operation: userSettingsContract.operations.logoutOtherSessions }
59
95
  ];
60
96
 
61
97
  for (const { label, operation } of operationSpecs) {
@@ -0,0 +1,115 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { countQueries, requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
4
+
5
+ // users.profiles.listByIds and users.settings.listByUserIds on a database of the test file's own (usersDatabases.js),
6
+ // run on MariaDB/MySQL and on PostgreSQL alike: more ids than one page of query in one call, an id named twice, and
7
+ // ids the caller cannot see.
8
+
9
+ const identityOf = (tag, extra = {}) => ({
10
+ authProvider: "local",
11
+ authProviderUserSid: `identity-${tag}`,
12
+ email: `${tag}@example.test`,
13
+ displayName: tag,
14
+ username: tag,
15
+ ...extra
16
+ });
17
+
18
+ // Ids in numeric order, as the users table sorts them.
19
+ const numerically = (left, right) => (BigInt(left) < BigInt(right) ? -1 : BigInt(left) > BigInt(right) ? 1 : 0);
20
+
21
+ /**
22
+ * Registers the listByIds and listByUserIds tests on `database`.
23
+ * @param {{ open: () => Promise<any> }} database
24
+ * @param {{ skip?: string | false }} [options]
25
+ */
26
+ function listByIdsCases(database, { skip = false } = {}) {
27
+ test("listByIds answers every profile of 1,205 ids in one call, sorted by id, in one statement per 1,000 ids", { skip }, async () => {
28
+ requireTestDatabase(process.env);
29
+ const db = await database.open();
30
+ const ids = await db.profiles.createManyIgnoringExisting(
31
+ Array.from({ length: 1205 }, (_, index) => identityOf(`many-${index}`)),
32
+ { context: db.systemContext }
33
+ );
34
+ assert.equal(ids.length, 1205);
35
+
36
+ const { result, count } = await countQueries(db.knex, () => db.profiles.listByIds([...ids].reverse()));
37
+ assert.deepEqual(result.map(({ id }) => id), [...ids].sort(numerically));
38
+ assert.equal(count, 2, "1,205 ids are read in two statements, never one per page of 100 or per id");
39
+ assert.deepEqual(result[0], await db.profiles.findById(result[0].id), "each profile reads as findById answers it");
40
+ });
41
+
42
+ test("listByIds answers a profile named twice once, and leaves out ids naming no profile and values that are no id", { skip }, async () => {
43
+ requireTestDatabase(process.env);
44
+ const db = await database.open();
45
+ const one = await db.profiles.upsert(identityOf("ids-one"));
46
+ const two = await db.profiles.upsert(identityOf("ids-two"));
47
+ const { result, count } = await countQueries(db.knex, () => db.profiles.listByIds([
48
+ two.id, ` ${one.id} `, Number(two.id), one.id, "999999999", "not-an-id", `0${one.id}`, 0, -1, null, undefined
49
+ ]));
50
+ assert.deepEqual(result.map(({ id }) => id), [one.id, two.id]);
51
+ assert.deepEqual(result, [await db.profiles.findById(one.id), await db.profiles.findById(two.id)]);
52
+ assert.equal(count, 1);
53
+
54
+ assert.deepEqual(await countQueries(db.knex, () => db.profiles.listByIds([])), { result: [], count: 0, queries: [] });
55
+ assert.deepEqual(await db.profiles.listByIds(["999999999", "not-an-id"]), []);
56
+ await assert.rejects(db.profiles.listByIds(one.id), /listByIds takes an array of user ids/u);
57
+ });
58
+
59
+ test("listByIds sees what query sees for the caller, and joins the caller's transaction", { skip }, async () => {
60
+ requireTestDatabase(process.env);
61
+ const db = await database.open();
62
+ const shown = await db.profiles.upsert(identityOf("ids-shown"));
63
+ const hidden = await db.profiles.upsert(identityOf("ids-hidden"));
64
+ const ids = [hidden.id, shown.id];
65
+ // The users table owned again, with a row policy that hides one profile from every caller but background work.
66
+ const narrowed = await db.ownedWith({
67
+ rowPolicy: ({ query, column, caller }) => {
68
+ if (caller.kind !== "system") query.whereNot(column("username"), hidden.username);
69
+ return true;
70
+ }
71
+ });
72
+
73
+ const { records } = await narrowed.profiles.query({ filters: { id: ids }, page: { size: 10 } }, {});
74
+ assert.deepEqual(records.map(({ id }) => id), [shown.id]);
75
+ assert.deepEqual((await narrowed.profiles.listByIds(ids)).map(({ id }) => id), [shown.id]);
76
+ assert.deepEqual(
77
+ (await narrowed.profiles.listByIds(ids, { context: narrowed.systemContext })).map(({ id }) => id),
78
+ [shown.id, hidden.id].sort(numerically)
79
+ );
80
+
81
+ // A profile created in the caller's transaction is listed inside it, and is gone once the transaction rolls back.
82
+ const abort = new Error("Abort");
83
+ let created = null;
84
+ await assert.rejects(db.profiles.withTransaction({}, async (txOptions) => {
85
+ created = await db.profiles.upsert(identityOf("ids-uncommitted"), txOptions);
86
+ assert.deepEqual((await db.profiles.listByIds([created.id, shown.id], txOptions)).map(({ id }) => id), [shown.id, created.id]);
87
+ throw abort;
88
+ }), (error) => error === abort);
89
+ assert.deepEqual((await db.profiles.listByIds([created.id, shown.id])).map(({ id }) => id), [shown.id]);
90
+ });
91
+
92
+ test("settings.listByUserIds answers each listed user's settings once, sorted by user id, as findByUserId reads them", { skip }, async () => {
93
+ requireTestDatabase(process.env);
94
+ const db = await database.open();
95
+ const one = await db.profiles.upsert(identityOf("settings-one"));
96
+ const two = await db.profiles.upsert(identityOf("settings-two"));
97
+ const unset = await db.profiles.upsert(identityOf("settings-unset"));
98
+ await db.settings.ensureForUserId(one.id);
99
+ await db.settings.ensureForUserId(two.id);
100
+ // A row saved before locales were canonical.
101
+ await db.knex("user_settings").where({ user_id: two.id }).update({ locale: "en-us" });
102
+
103
+ const { result, count } = await countQueries(db.knex, () => db.settings.listByUserIds([
104
+ two.id, unset.id, ` ${one.id} `, two.id, "not-an-id", null
105
+ ]));
106
+ assert.deepEqual(result, [await db.settings.findByUserId(one.id), await db.settings.findByUserId(two.id)]);
107
+ assert.equal(result[1].locale, "en-US");
108
+ assert.equal(count, 1, "one statement, never one per user");
109
+
110
+ assert.deepEqual(await countQueries(db.knex, () => db.settings.listByUserIds([])), { result: [], count: 0, queries: [] });
111
+ await assert.rejects(db.settings.listByUserIds(one.id), /listByUserIds takes an array of user ids/u);
112
+ });
113
+ }
114
+
115
+ export { listByIdsCases };