@jskit-ai/workspaces-core 0.2.20 → 0.2.22

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
+ - A member's role change and their removal lock the membership before they check it, so two at once run one after the other and the second decides on what the first left: a role change that waited for a removal answers 404 `workspaces.member.notFound` instead of making the removed member active again, and a removal that waited for a role change keeps the new role instead of writing back the one it read. `workspaces.memberships` gains `lockByWorkspaceIdAndUserId(workspaceId, userId, txOptions)`, the membership locked until the caller's transaction ends, or null.
6
+ - Expiring an email's pending invites (`expirePendingByWorkspaceIdAndEmail`, which every new invite runs first) is one `patchWhere` on the invites, where it locked them and then patched them one at a time: its statements no longer grow with the invites the email had.
5
7
  - `workspaces.joinSource` and `workspaces.memberships.joinSource` are the handle's `joinSource` (`@jskit-ai/resource-runtime`): the same `{ query, column }` for the same params, carrying the columns a read answers instead of every column of the table. A report that names its columns with `column(field)` reads as before.
6
8
  - An anonymous visitor on a workspace surface that does not require membership (`requireMembership: false`, such as a public payment link under `/api/w/<slug>/...`) resolves to the workspace with no membership and no permissions, as a signed-in non-member does, where every such request answered 401 `workspaces.auth.required`. A surface that requires membership still answers 401 to an anonymous visitor, before it reads the workspace.
7
9
  - Its table resources declare the foreign keys their migrations create (`foreignKeys`), so json-rest-api 3.1.0 can skip the visibility query a system-context read makes for a record such a key guarantees exists. `jskit test --databases` checks each against an app's test database: workspaces.owner_user_id to users; workspace_memberships.workspace_id to workspaces and user_id to users; workspace_settings.workspace_id to workspaces; workspace_invites.workspace_id to workspaces and invited_by_user_id to users. `repositories.integration.test.js` proves the declarations, and users-core's, match the migrations on its database (SQLite, or MariaDB or PostgreSQL with JSKIT_REPOSITORY_TEST_DATABASE_URL).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/workspaces-core",
3
- "version": "0.2.20",
3
+ "version": "0.2.22",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -23,9 +23,9 @@
23
23
  "./locales/en.json": "./locales/en.json"
24
24
  },
25
25
  "dependencies": {
26
- "@jskit-ai/resource-core": "0.1.206",
27
- "@jskit-ai/resource-crud-core": "0.1.206",
28
- "@jskit-ai/users-core": "0.2.20",
26
+ "@jskit-ai/resource-core": "0.1.208",
27
+ "@jskit-ai/resource-crud-core": "0.1.208",
28
+ "@jskit-ai/users-core": "0.2.22",
29
29
  "json-rest-schema": "^1.0.17"
30
30
  },
31
31
  "description": "Workspace tenancy runtime plus HTTP routes, role catalog, and workspace config scaffolding.",
@@ -206,10 +206,10 @@
206
206
  }
207
207
  },
208
208
  "peerDependencies": {
209
- "@jskit-ai/auth-core": "0.2.15",
210
- "@jskit-ai/database-runtime": "0.1.264",
211
- "@jskit-ai/http-runtime": "0.2.15",
212
- "@jskit-ai/kernel": "0.2.15",
213
- "@jskit-ai/resource-runtime": "0.2.16"
209
+ "@jskit-ai/auth-core": "0.2.17",
210
+ "@jskit-ai/database-runtime": "0.1.266",
211
+ "@jskit-ai/http-runtime": "0.2.17",
212
+ "@jskit-ai/kernel": "0.2.17",
213
+ "@jskit-ai/resource-runtime": "0.2.18"
214
214
  }
215
215
  }
@@ -26,35 +26,6 @@ function normalizeInviteRecord(payload) {
26
26
  };
27
27
  }
28
28
 
29
- function normalizeInvitePatchPayload(payload = {}) {
30
- const source = payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
31
- const normalized = {};
32
-
33
- if (Object.hasOwn(source, "roleSid")) {
34
- normalized.roleSid = normalizeLowerText(source.roleSid);
35
- }
36
- if (Object.hasOwn(source, "status")) {
37
- normalized.status = normalizeLowerText(source.status);
38
- }
39
- if (Object.hasOwn(source, "invitedByUserId")) {
40
- normalized.invitedByUserId =
41
- source.invitedByUserId == null
42
- ? null
43
- : normalizeRecordId(source.invitedByUserId, { fallback: null });
44
- }
45
- if (Object.hasOwn(source, "expiresAt")) {
46
- normalized.expiresAt = source.expiresAt == null ? null : toIsoString(source.expiresAt);
47
- }
48
- if (Object.hasOwn(source, "acceptedAt")) {
49
- normalized.acceptedAt = source.acceptedAt == null ? null : toIsoString(source.acceptedAt);
50
- }
51
- if (Object.hasOwn(source, "revokedAt")) {
52
- normalized.revokedAt = source.revokedAt == null ? null : toIsoString(source.revokedAt);
53
- }
54
-
55
- return normalized;
56
- }
57
-
58
29
  function normalizeInviteWithWorkspace(payload = {}) {
59
30
  const invite = normalizeInviteRecord(payload);
60
31
  if (!invite) {
@@ -257,22 +228,12 @@ function createRepository({ workspaceInvites, workspaces }) {
257
228
 
258
229
  await workspaceInvites.withTransaction(options, async (txOptions) => {
259
230
  await lockWorkspaceForInvitations(normalizedWorkspaceId, txOptions);
260
- const patch = normalizeInvitePatchPayload({ status: "expired" });
261
- const rows = await queryInvites(
262
- {
263
- workspace: normalizedWorkspaceId,
264
- email: normalizeLowerText(email),
265
- status: "pending"
266
- },
267
- { ...txOptions, lock: true }
231
+ // One write for every pending invite of the email, however many there are; the handle stamps updatedAt.
232
+ await workspaceInvites.patchWhere(
233
+ { workspace: normalizedWorkspaceId, email: normalizeLowerText(email), status: "pending" },
234
+ { status: "expired" },
235
+ { ...txOptions, returning: "none" }
268
236
  );
269
-
270
- for (const row of rows) {
271
- if (!row?.id) {
272
- continue;
273
- }
274
- await patchInvite(row.id, { status: patch.status, updatedAt: new Date().toISOString() }, txOptions);
275
- }
276
237
  });
277
238
  }
278
239
 
@@ -88,6 +88,24 @@ function createRepository({ workspaceMemberships }) {
88
88
  return normalizeMembershipRecord(rows[0] || null);
89
89
  }
90
90
 
91
+ /**
92
+ * The membership as findByWorkspaceIdAndUserId reads it, locked until the caller's transaction ends, or null. Another
93
+ * change of the same membership that locks it first waits, and then reads what this one left.
94
+ * @param {unknown} workspaceId
95
+ * @param {unknown} userId
96
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} options The caller's transaction.
97
+ */
98
+ async function lockByWorkspaceIdAndUserId(workspaceId, userId, options) {
99
+ const normalizedWorkspaceId = normalizeRecordId(workspaceId, { fallback: null });
100
+ const normalizedUserId = normalizeRecordId(userId, { fallback: null });
101
+ if (!normalizedWorkspaceId || !normalizedUserId) {
102
+ return null;
103
+ }
104
+
105
+ const [row] = await workspaceMemberships.lockWhere({ workspace: normalizedWorkspaceId, user: normalizedUserId }, options);
106
+ return normalizeMembershipRecord(row || null);
107
+ }
108
+
91
109
  async function ensureOwnerMembership(workspaceId, userId, options = {}) {
92
110
  const normalizedWorkspaceId = normalizeRecordId(workspaceId, { fallback: null });
93
111
  const normalizedUserId = normalizeRecordId(userId, { fallback: null });
@@ -260,6 +278,7 @@ function createRepository({ workspaceMemberships }) {
260
278
  // "active" }`).
261
279
  joinSource: workspaceMemberships.joinSource,
262
280
  findByWorkspaceIdAndUserId,
281
+ lockByWorkspaceIdAndUserId,
263
282
  ensureOwnerMembership,
264
283
  upsertMembership,
265
284
  addMember,
@@ -218,6 +218,24 @@ function createService({
218
218
  return returnJsonApiData(await listMembers(workspace, options));
219
219
  }
220
220
 
221
+ // Changes an active member who is not the owner, and answers the members. The membership is locked before it is
222
+ // checked, so a role change and a removal of one member at once run one after the other, and the second decides on
223
+ // what the first left: a removed member is not made active again by a role change, and keeps the role they had.
224
+ async function changeActiveMember(workspace, memberUserId, { ownerError, changes }, options) {
225
+ await workspaceMembershipsRepository.withTransaction(options, async (txOptions) => {
226
+ const membership = await workspaceMembershipsRepository.lockByWorkspaceIdAndUserId(workspace.id, memberUserId, txOptions);
227
+ if (!membership || membership.status !== "active") {
228
+ throw new AppError(404, "Member not found.", { code: "workspaces.member.notFound" });
229
+ }
230
+ if (memberUserId === normalizeRecordId(workspace.ownerUserId, { fallback: null }) || membership.roleSid === OWNER_ROLE_ID) {
231
+ throw ownerError();
232
+ }
233
+ await workspaceMembershipsRepository.upsertMembership(workspace.id, memberUserId, changes(membership), txOptions);
234
+ });
235
+
236
+ return returnJsonApiData(await listMembers(workspace, options));
237
+ }
238
+
221
239
  async function updateMemberRole(workspace, payload, options = {}) {
222
240
  const memberUserId = normalizeRecordId(payload.memberUserId, { fallback: null });
223
241
  const roleSid = normalizeLowerText(payload.roleSid || "");
@@ -228,25 +246,10 @@ function createService({
228
246
  throw roleNotAssignableError();
229
247
  }
230
248
 
231
- const existingMembership = await workspaceMembershipsRepository.findByWorkspaceIdAndUserId(workspace.id, memberUserId, options);
232
- if (!existingMembership || existingMembership.status !== "active") {
233
- throw new AppError(404, "Member not found.", { code: "workspaces.member.notFound" });
234
- }
235
- if (memberUserId === normalizeRecordId(workspace.ownerUserId, { fallback: null }) || existingMembership.roleSid === OWNER_ROLE_ID) {
236
- throw new AppError(409, "Cannot change workspace owner role.", { code: "workspaces.member.ownerRoleLocked" });
237
- }
238
-
239
- await workspaceMembershipsRepository.upsertMembership(
240
- workspace.id,
241
- memberUserId,
242
- {
243
- roleSid,
244
- status: "active"
245
- },
246
- options
247
- );
248
-
249
- return returnJsonApiData(await listMembers(workspace, options));
249
+ return changeActiveMember(workspace, memberUserId, {
250
+ ownerError: () => new AppError(409, "Cannot change workspace owner role.", { code: "workspaces.member.ownerRoleLocked" }),
251
+ changes: () => ({ roleSid, status: "active" })
252
+ }, options);
250
253
  }
251
254
 
252
255
  async function removeMember(workspace, payload, options = {}) {
@@ -255,25 +258,10 @@ function createService({
255
258
  throw memberUserIdRequiredError();
256
259
  }
257
260
 
258
- const existingMembership = await workspaceMembershipsRepository.findByWorkspaceIdAndUserId(workspace.id, memberUserId, options);
259
- if (!existingMembership || existingMembership.status !== "active") {
260
- throw new AppError(404, "Member not found.", { code: "workspaces.member.notFound" });
261
- }
262
- if (memberUserId === normalizeRecordId(workspace.ownerUserId, { fallback: null }) || existingMembership.roleSid === OWNER_ROLE_ID) {
263
- throw new AppError(409, "Cannot remove workspace owner.", { code: "workspaces.member.ownerNotRemovable" });
264
- }
265
-
266
- await workspaceMembershipsRepository.upsertMembership(
267
- workspace.id,
268
- memberUserId,
269
- {
270
- roleSid: existingMembership.roleSid,
271
- status: "revoked"
272
- },
273
- options
274
- );
275
-
276
- return returnJsonApiData(await listMembers(workspace, options));
261
+ return changeActiveMember(workspace, memberUserId, {
262
+ ownerError: () => new AppError(409, "Cannot remove workspace owner.", { code: "workspaces.member.ownerNotRemovable" }),
263
+ changes: (membership) => ({ roleSid: membership.roleSid, status: "revoked" })
264
+ }, options);
277
265
  }
278
266
 
279
267
  async function listInvitesPayload(workspace, options = {}) {
@@ -74,7 +74,10 @@ test("Members and Invitations response validation preserves labels and saved rol
74
74
  async listActiveByWorkspaceId() {
75
75
  return [{ userId: "11", roleSid: savedRole, status: "active", displayName: "Person", email: "person@example.com" }];
76
76
  },
77
- async findByWorkspaceIdAndUserId() { return { userId: "11", roleSid: savedRole, status: "active" }; },
77
+ async withTransaction(options, work) {
78
+ return work({ ...options, trx: {} });
79
+ },
80
+ async lockByWorkspaceIdAndUserId() { return { userId: "11", roleSid: savedRole, status: "active" }; },
78
81
  async upsertMembership(_workspaceId, _userId, patch) { savedRole = patch.roleSid; }
79
82
  },
80
83
  workspaceInvitesRepository: { async listPendingByWorkspaceIdWithWorkspace() { return []; } },
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
3
  import { requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
4
4
  import { findDuplicateEntryError } from "@jskit-ai/database-runtime/shared";
5
+ import { expectFlatQueries } from "@jskit-ai/resource-runtime/test";
5
6
  import { workspacesDatabase } from "./support/mysqlWorkspaces.js";
6
7
 
7
8
  // Characterization of workspaceInvitesRepository on MariaDB/MySQL, through the functions its services call, before
@@ -201,6 +202,26 @@ test("expiring an email's pending invites touches only that workspace's pending
201
202
  });
202
203
  });
203
204
 
205
+ test("expiring an email's pending invites sends the same statements for 3 invites as for 30", async () => {
206
+ requireTestDatabase(process.env);
207
+ const db = await database.open();
208
+ let team = 0;
209
+ await expectFlatQueries({
210
+ environment: process.env,
211
+ knex: db.knex,
212
+ sizes: [3, 30],
213
+ // Each size invites one email to a workspace of its own as often as the size says.
214
+ seed: async (size) => {
215
+ team += 1;
216
+ const { workspace } = await teamOf(db, `flat-expire-${team}`);
217
+ for (let index = 0; index < size; index += 1) await invite(db, workspace, "una@example.test", `flat-expire-${team}-${index}`);
218
+ return workspace;
219
+ },
220
+ run: (workspace) => db.invites.expirePendingByWorkspaceIdAndEmail(workspace.id, "una@example.test")
221
+ });
222
+ assert.deepEqual(await db.invites.listPendingByEmail("una@example.test"), [], "every one of them expired");
223
+ });
224
+
204
225
  test("accepting or revoking stamps a pending invite once; a handled, unknown or foreign invite is a 404", async () => {
205
226
  requireTestDatabase(process.env);
206
227
  const db = await database.open();
@@ -280,13 +301,14 @@ test("a revoke and an accept of one pending invite race: the first to lock it wi
280
301
  let loser;
281
302
  try {
282
303
  await held.promise;
283
- loser = db.invites[second](created.id);
304
+ // Expected at once: its 404 can come as soon as the winner commits, before the winner's own answer.
305
+ loser = assert.rejects(db.invites[second](created.id), handled, `${second} after ${first}`);
284
306
  await untilLockWait(db);
285
307
  } finally {
286
308
  release.resolve();
287
309
  await winner;
288
310
  }
289
- await assert.rejects(loser, handled, `${second} after ${first}`);
311
+ await loser;
290
312
  const stored = await db.invites.findById(created.id);
291
313
  assert.equal(stored.status, status);
292
314
  assert.equal(stored.acceptedAt === null, status === "revoked");
@@ -206,6 +206,70 @@ test("updateMemberRole and removeMember change an active member of their workspa
206
206
  "both changes roll back with the caller's transaction");
207
207
  });
208
208
 
209
+ // Resolves once a statement on this test's database has waited a second or more, which here is only a wait for a row
210
+ // lock: the race's second request has reached the membership the first holds. The test user sees its own
211
+ // connections in the process list without the PROCESS privilege.
212
+ async function untilBlocked(db) {
213
+ const deadline = Date.now() + 10_000;
214
+ while (Date.now() < deadline) {
215
+ const [rows] = await db.knex.raw(
216
+ "SELECT COUNT(*) AS waiting FROM information_schema.PROCESSLIST WHERE DB = ? AND COMMAND = 'Query' " +
217
+ "AND TIME >= 1 AND INFO NOT LIKE '%PROCESSLIST%'",
218
+ [db.name]
219
+ );
220
+ if (Number(rows[0].waiting) > 0) return;
221
+ await new Promise((resolve) => setTimeout(resolve, 50));
222
+ }
223
+ throw new Error("No statement waited for a lock within 10 s.");
224
+ }
225
+
226
+ // Runs `first` in a transaction that holds what it changed until `second`, started meanwhile, waits for it; answers
227
+ // `second`'s outcome once `first` has committed.
228
+ async function race(db, first, second) {
229
+ const held = Promise.withResolvers();
230
+ const release = Promise.withResolvers();
231
+ const winner = db.memberships.withTransaction({}, async (txOptions) => {
232
+ await first(txOptions);
233
+ held.resolve();
234
+ await release.promise;
235
+ });
236
+ let loser;
237
+ try {
238
+ await held.promise;
239
+ loser = second();
240
+ loser.catch(() => {});
241
+ await untilBlocked(db);
242
+ } finally {
243
+ release.resolve();
244
+ await winner;
245
+ }
246
+ return loser;
247
+ }
248
+
249
+ test("a role change and a removal of one member at once: the second decides on what the first left", async () => {
250
+ requireTestDatabase(process.env);
251
+ const db = await database.open();
252
+ const service = membersService(db);
253
+ const { workspace, members } = await teamOf(db, "race", ["cy", "di"]);
254
+ const stored = async (member) => {
255
+ const { roleSid, status } = await db.memberships.findByWorkspaceIdAndUserId(workspace.id, member.id);
256
+ return { roleSid, status };
257
+ };
258
+
259
+ const changingRemoved = race(db,
260
+ (txOptions) => service.removeMember(workspace, { memberUserId: members.cy.id }, txOptions),
261
+ () => service.updateMemberRole(workspace, { memberUserId: members.cy.id, roleSid: "admin" }));
262
+ await assert.rejects(changingRemoved, (error) => error.status === 404 && error.code === "workspaces.member.notFound",
263
+ "a role change that waited for a removal finds no member");
264
+ assert.deepEqual(await stored(members.cy), { roleSid: "member", status: "revoked" }, "the removed member stays removed");
265
+
266
+ await race(db,
267
+ (txOptions) => service.updateMemberRole(workspace, { memberUserId: members.di.id, roleSid: "admin" }, txOptions),
268
+ () => service.removeMember(workspace, { memberUserId: members.di.id }));
269
+ assert.deepEqual(await stored(members.di), { roleSid: "admin", status: "revoked" },
270
+ "a removal that waited for a role change keeps the role it gave");
271
+ });
272
+
209
273
  test("listMembers and the invites list leave out other workspaces' members and invites", async () => {
210
274
  requireTestDatabase(process.env);
211
275
  const db = await database.open();
@@ -71,9 +71,13 @@ function createFixture() {
71
71
  }
72
72
  ];
73
73
  },
74
- async findByWorkspaceIdAndUserId(workspaceId, userId) {
74
+ async withTransaction(options, work) {
75
+ return work({ ...options, trx: {} });
76
+ },
77
+ async lockByWorkspaceIdAndUserId(workspaceId, userId, options) {
75
78
  assert.equal(Number(workspaceId), 7);
76
79
  assert.equal(Number(userId), 11);
80
+ assert.ok(options.trx, "the membership is locked inside the change's transaction");
77
81
  return {
78
82
  workspaceId: "7",
79
83
  userId: "11",
@@ -81,9 +85,10 @@ function createFixture() {
81
85
  status: "active"
82
86
  };
83
87
  },
84
- async upsertMembership(workspaceId, userId, patch) {
88
+ async upsertMembership(workspaceId, userId, patch, options) {
85
89
  assert.equal(Number(workspaceId), 7);
86
90
  assert.equal(Number(userId), 11);
91
+ assert.ok(options.trx, "and written in it");
87
92
  assert.deepEqual(patch, {
88
93
  roleSid: "admin",
89
94
  status: "active"
@@ -530,7 +535,10 @@ test("workspaceMembersService.removeMember marks membership revoked and returns
530
535
  }
531
536
  ];
532
537
  },
533
- async findByWorkspaceIdAndUserId(workspaceId, userId) {
538
+ async withTransaction(options, work) {
539
+ return work({ ...options, trx: {} });
540
+ },
541
+ async lockByWorkspaceIdAndUserId(workspaceId, userId) {
534
542
  assert.equal(Number(workspaceId), 7);
535
543
  assert.equal(Number(userId), 11);
536
544
  return {
@@ -594,7 +602,10 @@ test("workspaceMembersService.removeMember rejects removing the owner", async ()
594
602
  async listActiveByWorkspaceId() {
595
603
  return [];
596
604
  },
597
- async findByWorkspaceIdAndUserId(workspaceId, userId) {
605
+ async withTransaction(options, work) {
606
+ return work({ ...options, trx: {} });
607
+ },
608
+ async lockByWorkspaceIdAndUserId(workspaceId, userId) {
598
609
  assert.equal(Number(workspaceId), 7);
599
610
  assert.equal(Number(userId), 9);
600
611
  return {