@jskit-ai/users-core 0.2.12 → 0.2.14

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 CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - The profile projector's `syncIdentityProfile` takes `onlyWhenChanged`: an existing profile that already matches the identity (email, display name, provider identity) is answered after one read, without opening a transaction, ensuring user settings or running the lifecycle contributors (workspaces' personal workspace provisioning); a missing or changed profile is synchronized in full. JSKIT's auth providers pass it on ordinary requests and synchronize in full at sign-in and session refresh. Visible difference: a personal workspace, owner membership or user settings row deleted while its person is signed in is re-created at their next sign-in or session refresh instead of their next request; a name or email changed at the provider still shows at the next request.
6
+ - A new profile's username (the email's local part, or the requested name, then `name-2` to `name-1000`) is chosen with one read of every taken candidate through the profile resource's new `usernames` filter (`in`), instead of one read per taken candidate, so a common name costs the same statements after 10 namesakes as after 200. The chosen name, the trimming of long names, the profile's own name counting as free and the error when all 1,000 are taken are unchanged.
5
7
  - The account security routes' declared rate limits apply, now that the kernel enforces route limits.
6
8
  - The settings, security and avatar field messages are sent in the coded form `{ code, message, params }`, so their field errors translate. The English is unchanged.
7
9
  - The resources' validation feedback names the catalog key `jskit.users.feedback.validationFailed` instead of plain English; JSKIT's forms render it with `text()`, so the English shown is unchanged.
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@jskit-ai/users-core",
3
- "version": "0.2.12",
3
+ "version": "0.2.14",
4
4
  "type": "module",
5
5
  "scripts": {
6
- "test": "node --test --test-concurrency=1"
6
+ "test": "jskit test"
7
7
  },
8
8
  "exports": {
9
9
  "./server/UsersFeature": "./src/server/UsersFeature.js",
@@ -17,12 +17,12 @@
17
17
  "./locales/en.json": "./locales/en.json"
18
18
  },
19
19
  "dependencies": {
20
- "@jskit-ai/database-runtime": "0.1.259",
21
- "@jskit-ai/json-rest-api-core": "0.2.11",
22
- "@jskit-ai/resource-core": "0.1.201",
23
- "@jskit-ai/resource-crud-core": "0.1.201",
24
- "@jskit-ai/storage-runtime": "0.1.256",
25
- "@jskit-ai/uploads-runtime": "0.2.10",
20
+ "@jskit-ai/database-runtime": "0.1.261",
21
+ "@jskit-ai/json-rest-api-core": "0.2.13",
22
+ "@jskit-ai/resource-core": "0.1.203",
23
+ "@jskit-ai/resource-crud-core": "0.1.203",
24
+ "@jskit-ai/storage-runtime": "0.1.258",
25
+ "@jskit-ai/uploads-runtime": "0.2.12",
26
26
  "json-rest-schema": "^1.0.17"
27
27
  },
28
28
  "description": "Users/account runtime plus HTTP routes for account features.",
@@ -191,8 +191,8 @@
191
191
  }
192
192
  },
193
193
  "peerDependencies": {
194
- "@jskit-ai/auth-core": "0.2.10",
195
- "@jskit-ai/http-runtime": "0.2.10",
196
- "@jskit-ai/kernel": "0.2.10"
194
+ "@jskit-ai/auth-core": "0.2.12",
195
+ "@jskit-ai/http-runtime": "0.2.12",
196
+ "@jskit-ai/kernel": "0.2.12"
197
197
  }
198
198
  }
@@ -10,8 +10,8 @@
10
10
  "./shared": "./src/shared/index.js"
11
11
  },
12
12
  "dependencies": {
13
- "@jskit-ai/crud-core": "0.2.11",
14
- "@jskit-ai/resource-crud-core": "0.1.201"
13
+ "@jskit-ai/crud-core": "0.2.13",
14
+ "@jskit-ai/resource-crud-core": "0.1.203"
15
15
  },
16
16
  "jskit": {
17
17
  "kind": "runtime",
@@ -10,9 +10,9 @@
10
10
  "./shared": "./src/shared/index.js"
11
11
  },
12
12
  "dependencies": {
13
- "@jskit-ai/crud-core": "0.2.11",
14
- "@jskit-ai/resource-crud-core": "0.1.201",
15
- "@jskit-ai/workspaces-core": "0.2.12"
13
+ "@jskit-ai/crud-core": "0.2.13",
14
+ "@jskit-ai/resource-crud-core": "0.1.203",
15
+ "@jskit-ai/workspaces-core": "0.2.14"
16
16
  },
17
17
  "jskit": {
18
18
  "kind": "runtime",
@@ -10,7 +10,8 @@ import {
10
10
  import { normalizeLowerText, normalizeRecordId, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
11
11
  import {
12
12
  createJsonRestContext,
13
- extractJsonRestCollectionRows
13
+ extractJsonRestCollectionRows,
14
+ queryAllJsonRestCollectionRows
14
15
  } from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
15
16
  import { normalizeIdentity } from "../support/identity.js";
16
17
  import { USERNAME_MAX_LENGTH, normalizeNullableString, normalizeNullableVersion, normalizeUsername } from "../../../shared/resources/userProfileValues.js";
@@ -74,6 +75,9 @@ function usernameBaseFromEmail(email) {
74
75
  return username || "user";
75
76
  }
76
77
 
78
+ // The base, then base-2 to base-1000.
79
+ const USERNAME_CANDIDATE_LIMIT = 1000;
80
+
77
81
  function buildUsernameCandidate(baseUsername, suffix) {
78
82
  const normalizedBase = normalizeUsername(baseUsername) || "user";
79
83
  if (suffix < 1) {
@@ -120,25 +124,33 @@ function buildDuplicateEmailConflictError(cause) {
120
124
  */
121
125
  async function resolveUniqueUsername(api, baseUsername, { excludeUserId = null, transaction = null } = {}) {
122
126
  const normalizedExcludeUserId = normalizeDbRecordId(excludeUserId, { fallback: null });
123
-
124
- for (let suffix = 0; suffix < 1000; suffix += 1) {
125
- const candidate = buildUsernameCandidate(baseUsername, suffix);
126
- const existingRows = extractJsonRestCollectionRows(
127
- await api.resources.userProfiles.query({
128
- queryParams: {
129
- filters: {
130
- username: candidate
131
- }
132
- },
133
- transaction,
134
- format: "plain"
135
- })
136
- );
137
- const existing = existingRows[0] || null;
138
- const existingId = normalizeDbRecordId(existing?.id, { fallback: null });
139
- if (!existing || existingId === normalizedExcludeUserId) {
140
- return candidate;
127
+ const candidates = Array.from(
128
+ { length: USERNAME_CANDIDATE_LIMIT },
129
+ (_, suffix) => buildUsernameCandidate(baseUsername, suffix)
130
+ );
131
+
132
+ // One read of every profile holding a candidate, however many namesakes came before.
133
+ const existingRows = await queryAllJsonRestCollectionRows(
134
+ api.resources.userProfiles,
135
+ {
136
+ queryParams: {
137
+ filters: {
138
+ usernames: candidates
139
+ }
140
+ },
141
+ transaction,
142
+ format: "plain"
141
143
  }
144
+ );
145
+ const holderIdByUsername = new Map(
146
+ existingRows.map((row) => [normalizeLowerText(row.username), normalizeDbRecordId(row.id, { fallback: null })])
147
+ );
148
+
149
+ const candidate = candidates.find((username) => (
150
+ !holderIdByUsername.has(username) || holderIdByUsername.get(username) === normalizedExcludeUserId
151
+ ));
152
+ if (candidate) {
153
+ return candidate;
142
154
  }
143
155
 
144
156
  throw new Error("Unable to generate unique username.");
@@ -88,8 +88,19 @@ function createService({ userProfilesRepository, resolveLifecycleContributors, u
88
88
  );
89
89
  }
90
90
 
91
- async function syncIdentityProfile(profileLike, options = {}) {
91
+ /**
92
+ * Creates or updates the users row of a signed-in identity, ensures its settings and runs the lifecycle
93
+ * contributors (personal workspace provisioning). With `onlyWhenChanged`, an existing row that already
94
+ * matches the identity is answered after one read, without that work: an ordinary request's check.
95
+ * @param {object} profileLike
96
+ * @param {{ onlyWhenChanged?: boolean, trx?: object }} [options]
97
+ */
98
+ async function syncIdentityProfile(profileLike, { onlyWhenChanged = false, ...options } = {}) {
92
99
  const normalized = buildNormalizedIdentityProfile(profileLike);
100
+ if (onlyWhenChanged) {
101
+ const existing = await findByIdentity(normalized, options);
102
+ if (!profileNeedsUpdate(existing, normalized)) return requireSynchronizedProfile(existing);
103
+ }
93
104
  const lifecycleContributors = resolveLifecycleContributors();
94
105
 
95
106
  const runSync = async (trx) => {
@@ -65,7 +65,8 @@ const userProfileResource = defineCrudResource({
65
65
  namespace: "userProfile",
66
66
  tableName: "users",
67
67
  searchSchema: {
68
- id: { type: "id", actualField: "id" }
68
+ id: { type: "id", actualField: "id" },
69
+ usernames: { type: "array", actualField: "username", filterOperator: "in", items: { type: "string" } }
69
70
  },
70
71
  schema: {
71
72
  authProvider: {
@@ -175,3 +175,55 @@ test("auth profile sync joins the supplied managed transaction and propagates co
175
175
  await assert.rejects(service.syncIdentityProfile(profile, { trx }), error => error === failure);
176
176
  assert.deepEqual(calls, [trx, trx, trx, trx]);
177
177
  });
178
+
179
+ test("an ordinary request's profile check (onlyWhenChanged) reads a matching profile once and synchronizes only a changed or missing one", async () => {
180
+ const stored = { id: "7", authProvider: "local", authProviderUserSid: "u-7", email: "ada@example.com", displayName: "Ada" };
181
+ let row = stored;
182
+ const calls = [];
183
+ const service = createService({
184
+ userProfilesRepository: {
185
+ async findByIdentity(_identity, options = {}) {
186
+ calls.push(options.trx ? "find in transaction" : "find");
187
+ return row;
188
+ },
189
+ async upsert(payload) {
190
+ calls.push("upsert");
191
+ row = { id: row?.id || "8", ...payload };
192
+ return row;
193
+ },
194
+ async withTransaction(work) {
195
+ calls.push("transaction");
196
+ return work({ trxId: "tx" });
197
+ }
198
+ },
199
+ userSettingsRepository: {
200
+ async ensureForUserId(userId) {
201
+ calls.push("ensure settings");
202
+ return { userId };
203
+ }
204
+ },
205
+ resolveLifecycleContributors: () => [{
206
+ contributorId: "test.lifecycle",
207
+ async afterIdentityProfileSynced() {
208
+ calls.push("lifecycle");
209
+ }
210
+ }]
211
+ });
212
+ const identity = (displayName) => ({ authProvider: "local", authProviderUserSid: "u-7", email: "ada@example.com", displayName });
213
+
214
+ assert.equal(await service.syncIdentityProfile(identity("Ada"), { onlyWhenChanged: true }), stored);
215
+ assert.deepEqual(calls.splice(0), ["find"]);
216
+
217
+ const renamed = await service.syncIdentityProfile(identity("Ada Lovelace"), { onlyWhenChanged: true });
218
+ assert.equal(renamed.displayName, "Ada Lovelace");
219
+ assert.deepEqual(calls.splice(0), ["find", "transaction", "find in transaction", "upsert", "ensure settings", "lifecycle"]);
220
+
221
+ row = null;
222
+ const created = await service.syncIdentityProfile(identity("Ada Lovelace"), { onlyWhenChanged: true });
223
+ assert.equal(created.id, "8");
224
+ assert.deepEqual(calls.splice(0), ["find", "transaction", "find in transaction", "upsert", "ensure settings", "lifecycle"]);
225
+
226
+ // A sign-in or token refresh (no option) still synchronizes a matching profile in full.
227
+ await service.syncIdentityProfile(identity("Ada Lovelace"));
228
+ assert.deepEqual(calls.splice(0), ["transaction", "find in transaction", "ensure settings", "lifecycle"]);
229
+ });
@@ -117,13 +117,14 @@ test("userProfilesRepository.upsert sends plain data with transaction outside th
117
117
  api: {
118
118
  resources: {
119
119
  userProfiles: {
120
+ vars: {},
120
121
  async query({ queryParams, format }) {
121
122
  assert.equal(format, "plain");
122
123
  const filters = queryParams?.filters || {};
123
124
  if (Object.hasOwn(filters, "authProvider") || Object.hasOwn(filters, "authProviderUserSid")) {
124
125
  return asCollectionDocument([]);
125
126
  }
126
- if (Object.hasOwn(filters, "username")) {
127
+ if (Object.hasOwn(filters, "usernames")) {
127
128
  return asCollectionDocument([]);
128
129
  }
129
130
  return asCollectionDocument([]);
@@ -425,6 +426,7 @@ test("profile upsert performs duplicate recovery after its API transaction has f
425
426
  },
426
427
  resources: {
427
428
  userProfiles: {
429
+ vars: {},
428
430
  async query({ transaction, queryParams, format }) {
429
431
  assert.equal(format, "plain");
430
432
  if (active) {
@@ -460,6 +462,7 @@ test("profile upsert never recovers inside a caller-owned failed transaction", a
460
462
  async transaction() { throw new Error("Must join the caller's owner"); },
461
463
  resources: {
462
464
  userProfiles: {
465
+ vars: {},
463
466
  async query({ transaction }) {
464
467
  assert.equal(transaction, trx);
465
468
  reads += 1;
@@ -488,6 +491,7 @@ for (const outcome of ["pending", "committed", "unknown"]) {
488
491
  const api = {
489
492
  resources: {
490
493
  userProfiles: {
494
+ vars: {},
491
495
  async query() { reads += 1; return asCollectionDocument([]); },
492
496
  async post() { throw failure; }
493
497
  }
@@ -510,3 +514,83 @@ for (const outcome of ["pending", "committed", "unknown"]) {
510
514
  assert.equal(reads, 2);
511
515
  });
512
516
  }
517
+
518
+ // The username upsert chooses for `email` while `holders` (username to profile id) are taken,
519
+ // and the username reads it made. `existing` is the identity's profile, when it has one.
520
+ async function chooseUsername(email, holders, { existing = null } = {}) {
521
+ const trx = { trxId: "caller-managed" };
522
+ const usernameReads = [];
523
+ let written = null;
524
+ const repository = createUserProfilesRepository({
525
+ api: {
526
+ resources: {
527
+ userProfiles: {
528
+ vars: {},
529
+ async query({ queryParams, transaction }) {
530
+ assert.equal(transaction, trx);
531
+ const filters = queryParams?.filters || {};
532
+ if (Object.hasOwn(filters, "usernames")) {
533
+ usernameReads.push(filters.usernames);
534
+ return asCollectionDocument(filters.usernames
535
+ .filter((username) => holders.has(username))
536
+ .map((username) => ({ id: holders.get(username), username })));
537
+ }
538
+ return asCollectionDocument(existing ? [existing] : []);
539
+ },
540
+ async post({ data }) {
541
+ written = data.username;
542
+ return { id: "11", ...data };
543
+ },
544
+ async patch({ id, data }) {
545
+ written = data.username;
546
+ return { ...existing, id, ...data };
547
+ }
548
+ }
549
+ }
550
+ }
551
+ });
552
+ await repository.upsert({
553
+ authProvider: "local", authProviderUserSid: "local-7", email, displayName: "Ada"
554
+ }, { trx });
555
+ return { username: written, usernameReads };
556
+ }
557
+
558
+ const takenBy = (usernames, id = "8") => new Map(usernames.map((username) => [username, id]));
559
+
560
+ test("profile upsert chooses the first free username of base, base-2 to base-1000 in one read", async () => {
561
+ const fresh = await chooseUsername("ada@example.com", new Map());
562
+ assert.equal(fresh.username, "ada");
563
+ assert.equal(fresh.usernameReads.length, 1);
564
+ assert.equal(fresh.usernameReads[0].length, 1000);
565
+ assert.deepEqual(fresh.usernameReads[0].slice(0, 3), ["ada", "ada-2", "ada-3"]);
566
+ assert.equal(fresh.usernameReads[0][999], "ada-1000");
567
+
568
+ assert.equal((await chooseUsername("ada@example.com", takenBy(["ada"]))).username, "ada-2");
569
+ const gap = await chooseUsername("ada@example.com", takenBy(["ada", "ada-2", "ada-4", "ada-5"]));
570
+ assert.equal(gap.username, "ada-3");
571
+ assert.equal(gap.usernameReads.length, 1);
572
+ });
573
+
574
+ test("profile upsert trims a long username base so the suffixed name fits", async () => {
575
+ const longBase = "a".repeat(120);
576
+ const longEmail = `${"a".repeat(130)}@example.com`;
577
+ assert.equal((await chooseUsername(longEmail, new Map())).username, longBase);
578
+ assert.equal((await chooseUsername(longEmail, takenBy([longBase]))).username, `${"a".repeat(118)}-2`);
579
+ const taken = [longBase, ...Array.from({ length: 8 }, (_, index) => `${"a".repeat(118)}-${index + 2}`)];
580
+ assert.equal((await chooseUsername(longEmail, takenBy(taken))).username, `${"a".repeat(117)}-10`);
581
+ });
582
+
583
+ test("profile upsert keeps a username the profile itself holds", async () => {
584
+ const existing = {
585
+ id: "7", authProvider: "local", authProviderUserSid: "local-7",
586
+ email: "ada@example.com", username: "", displayName: "Ada"
587
+ };
588
+ assert.equal((await chooseUsername("ada@example.com", takenBy(["ada"], "7"), { existing })).username, "ada");
589
+ assert.equal((await chooseUsername("ada@example.com", takenBy(["ada"], "8"), { existing })).username, "ada-2");
590
+ });
591
+
592
+ test("profile upsert fails the same way when base to base-1000 are all taken", async () => {
593
+ const taken = ["ada", ...Array.from({ length: 999 }, (_, index) => `ada-${index + 2}`)];
594
+ await assert.rejects(chooseUsername("ada@example.com", takenBy(taken)), /Unable to generate unique username\./);
595
+ assert.equal((await chooseUsername("ada@example.com", takenBy(taken.slice(0, -1)))).username, "ada-1000");
596
+ });