@jskit-ai/users-core 0.2.14 → 0.2.16

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 (46) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/package.json +24 -17
  3. package/patterns/user-administration-server/PATTERN.md +59 -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/userProfilesRepository.js +246 -145
  24. package/src/server/common/repositories/userSettingsRepository.js +20 -49
  25. package/src/server/common/services/authProfileSyncService.js +3 -5
  26. package/src/server/types.js +9 -1
  27. package/src/server/usersIdentity.js +11 -11
  28. package/src/server/usersRuntime.js +13 -11
  29. package/src/shared/resources/userProfileResource.js +43 -13
  30. package/src/shared/resources/userSettingsResource.js +34 -29
  31. package/test/accountSecurityService.test.js +2 -2
  32. package/test/authProfileSyncService.test.js +13 -9
  33. package/test/exportsContract.test.js +2 -0
  34. package/test/featureRuntime.test.js +63 -20
  35. package/test/i18nCodes.test.js +6 -10
  36. package/test/repositories.mysql.test.js +384 -0
  37. package/test/resourcesCanonical.test.js +58 -22
  38. package/test/support/mysqlUsers.js +74 -0
  39. package/test/userSettingsInternalResource.test.js +3 -3
  40. package/test/userSettingsResource.test.js +3 -3
  41. package/test/usersPackageScaffoldContract.test.js +70 -12
  42. package/test/usersRouteRequestInputValidator.test.js +2 -2
  43. package/test/usersRouteResources.test.js +73 -29
  44. package/patterns/user-administration-server/example/packages/users/src/shared/userResource.js +0 -69
  45. package/patterns/user-administration-server/example/packages/users-workspace/src/shared/userResource.js +0 -56
  46. 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/mysqlUsers.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,74 @@
1
+ import knexLib from "knex";
2
+ import { after } from "node:test";
3
+ import { requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
4
+ import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
5
+ import { createTestResourceRuntime } from "@jskit-ai/resource-runtime/test";
6
+ import usersInitial from "../../migrations/users_core_generic_initial.cjs";
7
+ import usersUsername from "../../migrations/users_core_profile_username.cjs";
8
+ import usersUpdatedAt from "../../migrations/users_core_profile_updated_at.cjs";
9
+ import { createUsersExtensions } from "../../src/server/usersExtensions.js";
10
+ import { createUsersIdentity } from "../../src/server/usersIdentity.js";
11
+ import { userProfileTableResource } from "../../src/shared/resources/userProfileResource.js";
12
+ import { userSettingsTableResource } from "../../src/shared/resources/userSettingsResource.js";
13
+
14
+ // The migrated users tables in a MariaDB/MySQL database of the test file's own, named after TEST_DB_NAME with the
15
+ // file's suffix, made on first use and dropped when the file ends. Each test keeps to its own users.
16
+ const MIGRATIONS = [usersInitial, usersUsername, usersUpdatedAt];
17
+
18
+ async function openDatabase(suffix, cleanups) {
19
+ const name = `${requireTestDatabase(process.env)}_${suffix}`;
20
+ if (name.length > 64) throw new Error(`Test database name ${name} is longer than MySQL's 64 characters.`);
21
+ const server = {
22
+ host: process.env.DB_HOST,
23
+ port: Number(process.env.DB_PORT) || 3306,
24
+ user: process.env.DB_USER,
25
+ password: process.env.DB_PASSWORD,
26
+ // The mysql2 options database-runtime's connection gives an application, so records read as apps see them.
27
+ supportBigNumbers: true,
28
+ bigNumberStrings: true,
29
+ dateStrings: ["DATE"],
30
+ timezone: "Z"
31
+ };
32
+ const admin = knexLib({ client: "mysql2", connection: server, pool: { min: 0, max: 1 } });
33
+ const knex = knexLib({ client: "mysql2", connection: { ...server, database: name }, pool: { min: 0, max: 6 } });
34
+ cleanups.push(async () => {
35
+ try {
36
+ await knex.destroy();
37
+ await admin.raw("DROP DATABASE IF EXISTS ??", [name]);
38
+ } finally {
39
+ await admin.destroy();
40
+ }
41
+ });
42
+ await admin.raw("DROP DATABASE IF EXISTS ??", [name]);
43
+ await admin.raw("CREATE DATABASE ??", [name]);
44
+ for (const migration of MIGRATIONS) await migration.up(knex);
45
+ // The users tables, owned as UsersIdentityProvider owns them.
46
+ const runtime = await createTestResourceRuntime({ knex, logger: silentLogger });
47
+ const resources = await runtime.own("users.identity", [userProfileTableResource, userSettingsTableResource]);
48
+ const identity = createUsersIdentity({ resources, extensions: createUsersExtensions() });
49
+ // Background work's context, as a feature declaring a systemScope receives it.
50
+ const systemContext = runtime.declareSystemScope("users.identity", "import users")("users test import");
51
+ return Object.freeze({ knex, resources, systemContext, ...identity });
52
+ }
53
+
54
+ /**
55
+ * The file's database: call it at the file's top level, then `await open()` in each test after
56
+ * requireTestDatabase(). The database is made by the first test that opens it and dropped after the file's tests.
57
+ * @param {string} suffix A short name unique to the test file, such as "users_repos".
58
+ */
59
+ function usersDatabase(suffix) {
60
+ const cleanups = [];
61
+ let opening = null;
62
+ after(async () => {
63
+ if (opening) await opening.catch(() => {});
64
+ for (const cleanup of cleanups) await cleanup();
65
+ });
66
+ return Object.freeze({
67
+ open() {
68
+ opening ??= openDatabase(suffix, cleanups);
69
+ return opening;
70
+ }
71
+ });
72
+ }
73
+
74
+ export { usersDatabase };
@@ -1,8 +1,8 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
- import { userSettingsResource } from "../src/shared/resources/userSettingsResource.js";
3
+ import { userSettingsTableResource } from "../src/shared/resources/userSettingsResource.js";
4
4
 
5
5
  test("shared user settings resource declares user_id as the resource id column", () => {
6
- assert.equal(userSettingsResource.idProperty, "user_id");
7
- assert.equal(userSettingsResource.schema.id?.storage?.column, "user_id");
6
+ assert.equal(userSettingsTableResource.idProperty, "user_id");
7
+ assert.equal(userSettingsTableResource.schema.id?.storage?.column, "user_id");
8
8
  });
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
3
3
  import { validateOperationSection } from "@jskit-ai/http-runtime/shared/validators/operationValidation";
4
4
  import {
5
5
  USER_SETTINGS_ALL_KEYS,
6
- userSettingsResource
6
+ userSettingsContract
7
7
  } from "../src/shared/resources/userSettingsResource.js";
8
8
 
9
9
  function parseBody(operation, payload = {}) {
@@ -15,7 +15,7 @@ function parseBody(operation, payload = {}) {
15
15
  }
16
16
 
17
17
  test("user settings preferences update keeps required string validation", async () => {
18
- const parsed = await parseBody(userSettingsResource.operations.preferencesUpdate, {
18
+ const parsed = await parseBody(userSettingsContract.operations.preferencesUpdate, {
19
19
  theme: " "
20
20
  });
21
21
 
@@ -24,7 +24,7 @@ test("user settings preferences update keeps required string validation", async
24
24
  });
25
25
 
26
26
  test("user settings notifications update rejects non-boolean values", async () => {
27
- const parsed = await parseBody(userSettingsResource.operations.notificationsUpdate, {
27
+ const parsed = await parseBody(userSettingsContract.operations.notificationsUpdate, {
28
28
  productUpdates: "yes"
29
29
  });
30
30