@jskit-ai/workspaces-core 0.2.31 → 0.2.32

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 workspace route whose auth policy and action context differ in requiring membership (`contextPolicy: "optional"` on a route with `visibility: "workspace"`) reads its workspace context once per request instead of twice. The per-request cache keyed its reads by the membership requirement as well as the user and slug, so the two callers read the workspace, the membership and the settings each. Reads are now cached per user and slug, and each caller checks membership against the shared result: 401 `workspaces.auth.required` signed out, 403 `workspaces.workspace.accessDenied` for a non-member where membership is required, as before.
6
+ - The workspace invite mailer's `sendWorkspaceInvite` receives the invitation's id as `inviteId`, beside `email`, `inviteUrl`, `workspace` (with its `id`), `inviter`, `roleSid`, `expiresAt`, `locale` and `message`, so a mailer can record which invitation each email delivers.
5
7
  - A test copy (`SIDE_EFFECTS` is not `live`) sends no invitation email: a provided invite mailer is replaced by one that logs the invitation and answers the new delivery status `simulated`, with "Test copy: the invitation email was not sent. Copy the invite link to share it." (`workspaces.invite.simulated`). The feature now requires `runtime.logger`.
6
8
  - A workspace route that names no permission of its own, such as every CRUD route, reads its workspace context once per request instead of twice. The route visibility resolver read the workspace, the membership and the settings without the request, so the workspace action context contributor read them all again: a CRUD list sent six statements more than it needed (on SQLite, 13 statements where 7 do). The visibility resolver now passes the request, and both share the request's one resolution, as the auth policy and the action context already did. The same user, workspace, membership and permissions decide, with the same refusals: 401 signed out, 403 `workspaces.workspace.accessDenied` for a non-member, 404 `workspaces.workspace.notFound` for an unknown slug and 403 `ACTION_PERMISSION_DENIED` for a member without the permission.
7
9
  - The unknown-grant refusal now says, right after the grants it reports, to search the application's own code for a permission before removing or renaming its grant (`hasPermission()`, `can()`, permission string checks, including names built in code such as `` `crud.${resource}.list` ``), since the check cannot see those; a permission the application checks goes in `roleCatalog.customPermissions`, and a grant is removed only when nothing uses it. Before, a reported grant that an application service still checked with `hasPermission()` read as dead, and removing it took that access from every role but the owner. The did-you-mean suggestions are unchanged, and the workspace-server pattern says the same.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/workspaces-core",
3
- "version": "0.2.31",
3
+ "version": "0.2.32",
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.211",
27
- "@jskit-ai/resource-crud-core": "0.1.213",
28
- "@jskit-ai/users-core": "0.2.31",
26
+ "@jskit-ai/resource-core": "0.1.212",
27
+ "@jskit-ai/resource-crud-core": "0.1.214",
28
+ "@jskit-ai/users-core": "0.2.32",
29
29
  "json-rest-schema": "^1.0.20"
30
30
  },
31
31
  "description": "Workspace tenancy runtime plus HTTP routes, role catalog, and workspace config scaffolding.",
@@ -211,10 +211,10 @@
211
211
  }
212
212
  },
213
213
  "peerDependencies": {
214
- "@jskit-ai/auth-core": "0.2.20",
215
- "@jskit-ai/database-runtime": "0.1.269",
216
- "@jskit-ai/http-runtime": "0.2.20",
217
- "@jskit-ai/kernel": "0.2.20",
218
- "@jskit-ai/resource-runtime": "0.2.25"
214
+ "@jskit-ai/auth-core": "0.2.21",
215
+ "@jskit-ai/database-runtime": "0.1.270",
216
+ "@jskit-ai/http-runtime": "0.2.21",
217
+ "@jskit-ai/kernel": "0.2.21",
218
+ "@jskit-ai/resource-runtime": "0.2.26"
219
219
  }
220
220
  }
@@ -248,48 +248,52 @@ function createService({
248
248
  return returnJsonApiData(await workspacesRepository.updateById(workspaceContext.workspace.id, patch, options));
249
249
  }
250
250
 
251
- // The checks that run before a request's handler (its auth policy, its route visibility and its
252
- // action context) each need the request's workspace context. They pass the request and share one
253
- // resolution for the same user, slug and membership requirement, instead of reading the workspace, the
254
- // membership and the settings again for each check. A call without a request resolves on
255
- // its own.
251
+ // The checks that run before a request's handler (its auth policy, its route visibility and its action context) each
252
+ // need the request's workspace context, some requiring membership and some not (a route with contextPolicy
253
+ // "optional" and no permission). They pass the request and share one read of the workspace, the user's membership
254
+ // and the settings for the same user and slug; each call then applies its own membership requirement. A call
255
+ // without a request reads on its own.
256
256
  const requestWorkspaceContexts = new WeakMap();
257
257
 
258
258
  /**
259
+ * A surface that requires membership refuses an anonymous visitor (401) and a non-member (403); one that does not (a
260
+ * public payment link) resolves the workspace for them with no membership and no permissions.
259
261
  * @param {{ id?: unknown } | null} user
260
262
  * @param {string} workspaceSlug
261
263
  * @param {{ request?: object, requireMembership?: boolean }} [options]
262
264
  */
263
- function resolveWorkspaceContextForUserBySlug(user, workspaceSlug, options = {}) {
265
+ async function resolveWorkspaceContextForUserBySlug(user, workspaceSlug, options = {}) {
266
+ const requireMembership = options.requireMembership !== false;
267
+ if (requireMembership && !normalizeRecordId(user?.id, { fallback: null })) {
268
+ throw new AppError(401, "Authentication required.", { code: "workspaces.auth.required" });
269
+ }
270
+ const workspaceContext = await readRequestWorkspaceContext(user, workspaceSlug, options);
271
+ if (requireMembership && !workspaceContext.membership) {
272
+ throw new AppError(403, "You do not have access to this workspace.", { code: "workspaces.workspace.accessDenied" });
273
+ }
274
+ return workspaceContext;
275
+ }
276
+
277
+ function readRequestWorkspaceContext(user, workspaceSlug, options) {
264
278
  const request = options.request;
265
279
  if (!request || typeof request !== "object") {
266
280
  return readWorkspaceContextForUserBySlug(user, workspaceSlug, options);
267
281
  }
268
- const key = [
269
- normalizeRecordId(user?.id, { fallback: "" }),
270
- normalizeLowerText(workspaceSlug),
271
- options.requireMembership !== false
272
- ].join("\0");
273
- let resolutions = requestWorkspaceContexts.get(request);
274
- if (!resolutions) {
275
- resolutions = new Map();
276
- requestWorkspaceContexts.set(request, resolutions);
282
+ const key = `${normalizeRecordId(user?.id, { fallback: "" })}\0${normalizeLowerText(workspaceSlug)}`;
283
+ let reads = requestWorkspaceContexts.get(request);
284
+ if (!reads) {
285
+ reads = new Map();
286
+ requestWorkspaceContexts.set(request, reads);
277
287
  }
278
- if (!resolutions.has(key)) {
279
- resolutions.set(key, readWorkspaceContextForUserBySlug(user, workspaceSlug, options));
288
+ if (!reads.has(key)) {
289
+ reads.set(key, readWorkspaceContextForUserBySlug(user, workspaceSlug, options));
280
290
  }
281
- return resolutions.get(key);
291
+ return reads.get(key);
282
292
  }
283
293
 
284
- // A surface that requires membership refuses an anonymous visitor (401); one that does not (a public payment link)
285
- // resolves the workspace for them with no membership and no permissions, as it does for a signed-in non-member.
294
+ // The workspace, the user's active membership (null for an anonymous visitor or a non-member) and the settings.
286
295
  async function readWorkspaceContextForUserBySlug(user, workspaceSlug, options = {}) {
287
- const requireMembership = options.requireMembership !== false;
288
296
  const normalizedUserId = normalizeRecordId(user?.id, { fallback: null });
289
- if (!normalizedUserId && requireMembership) {
290
- throw new AppError(401, "Authentication required.", { code: "workspaces.auth.required" });
291
- }
292
-
293
297
  if (resolvedTenancyMode === TENANCY_MODE_NONE) {
294
298
  throw new AppError(403, "Workspace context is disabled.", { code: "workspaces.workspace.contextDisabled" });
295
299
  }
@@ -316,10 +320,6 @@ function createService({
316
320
  membership = await workspaceMembershipsRepository.ensureOwnerMembership(workspace.id, normalizedUserId, options);
317
321
  }
318
322
 
319
- if ((!membership || normalizeLowerText(membership.status) !== "active") && requireMembership) {
320
- throw new AppError(403, "You do not have access to this workspace.", { code: "workspaces.workspace.accessDenied" });
321
- }
322
-
323
323
  if (!membership || normalizeLowerText(membership.status) !== "active") {
324
324
  membership = null;
325
325
  }
@@ -30,10 +30,11 @@
30
30
 
31
31
  /**
32
32
  * The `workspaces.invite-mailer` capability: a feature that provides it sends
33
- * workspace invitation email. Its result is the delivery outcome; the status
34
- * defaults to "sent".
33
+ * workspace invitation email. It is told which saved invitation it sends
34
+ * (`inviteId`, its `workspace_invites` row, in `workspace.id`'s workspace).
35
+ * Its result is the delivery outcome; the status defaults to "sent".
35
36
  * @typedef {object} WorkspaceInviteMailer
36
- * @property {(message: { email: string, inviteUrl: string, workspace: object, inviter: object | null, roleSid: string, expiresAt: string, locale: string, message: object }, options?: object) => Promise<{ status?: string, message?: string, messageCode?: string, messageParams?: object, providerMessageId?: string } | void>} sendWorkspaceInvite
37
+ * @property {(message: { inviteId: string, email: string, inviteUrl: string, workspace: { id: string, slug: string, name: string, ownerUserId: string, avatarUrl: string }, inviter: object | null, roleSid: string, expiresAt: string, locale: string, message: object }, options?: object) => Promise<{ status?: string, message?: string, messageCode?: string, messageParams?: object, providerMessageId?: string } | void>} sendWorkspaceInvite
37
38
  */
38
39
 
39
40
  /**
@@ -175,6 +175,7 @@ function createService({
175
175
  t: (key, params) => i18n.t(locale, key, params)
176
176
  });
177
177
  const result = await workspaceInviteMailer.sendWorkspaceInvite({
178
+ inviteId: normalizeRecordId(invite.id, { fallback: "" }),
178
179
  email: invite.email,
179
180
  inviteUrl,
180
181
  workspace: mapMembersWorkspace(workspace),
@@ -312,6 +312,37 @@ describe(`users and workspaces repositories on migrated ${databaseLabel}`, () =>
312
312
  );
313
313
  });
314
314
 
315
+ test("workspaces.lock and memberships.lockByWorkspaceIdAndUserId take lockMode share, and refuse another mode before any statement", async () => {
316
+ const owner = await createProfile("Ada");
317
+ const workspace = await workspaces.insert({ slug: "shared", name: "Shared", ownerUserId: owner.id });
318
+ await memberships.ensureOwnerMembership(workspace.id, owner.id);
319
+ // A read check that needs the workspace and the membership unchanged until it commits holds them shared.
320
+ const { result, sql } = await statementsOf(() => workspaces.withTransaction({}, async (txOptions) => {
321
+ const shared = { ...txOptions, lockMode: "share" };
322
+ return [
323
+ await workspaces.lock(workspace.id, shared),
324
+ (await memberships.lockByWorkspaceIdAndUserId(workspace.id, owner.id, shared))?.userId
325
+ ];
326
+ }));
327
+ assert.deepEqual(result, [{ id: workspace.id }, owner.id]);
328
+ const locking = sql.filter((statement) => /\bfor (?:update|share|no key update)\b|\block in share mode\b/iu.test(statement));
329
+ const clause = { pg: /\bfor share\b/iu, mysql2: /\block in share mode\b/iu }[configuration.client];
330
+ if (clause) {
331
+ // PostgreSQL's lockWhere reads its rows again after the lock, so the membership's lock may be two statements.
332
+ assert.ok(locking.some((statement) => /\bfrom [`"]?workspaces[`"]? /u.test(statement)), sql.join(" | "));
333
+ assert.ok(locking.some((statement) => /\bfrom [`"]?workspace_memberships[`"]? /u.test(statement)), sql.join(" | "));
334
+ assert.ok(locking.every((statement) => clause.test(statement)), locking.join(" | "));
335
+ } else {
336
+ assert.deepEqual(locking, [], "SQLite takes its write lock, not a row lock");
337
+ }
338
+ const refused = await statementsOf(() => workspaces.withTransaction({}, async (txOptions) => {
339
+ const exclusive = { ...txOptions, lockMode: "exclusive" };
340
+ await assert.rejects(workspaces.lock(workspace.id, exclusive), { name: "TypeError", message: /lockMode is "update" \(the default\), "noKeyUpdate" or "share"/u });
341
+ await assert.rejects(memberships.lockByWorkspaceIdAndUserId(workspace.id, owner.id, exclusive), { name: "TypeError", message: /lockMode is "update" \(the default\), "noKeyUpdate" or "share"/u });
342
+ }));
343
+ assert.equal(refused.sql.filter((statement) => /^\s*select\b/iu.test(statement)).length, 0, refused.sql.join(" | "));
344
+ });
345
+
315
346
  test("another owner's report joins the workspaces' and memberships' join sources in one statement, each keeping its filters and the report its scope", async (t) => {
316
347
  // Another feature's workspace-owned table, whose report reads each row's workspace slug and active membership.
317
348
  await knex.schema.createTable("test_reminders", (table) => {
@@ -218,10 +218,11 @@ test("the workspace context answers a member's workspace, membership, permission
218
218
  errorWith(403, "workspaces.workspace.contextDisabled", "Workspace context is disabled."));
219
219
 
220
220
  const request = {};
221
- const shared = directory.resolveWorkspaceContextForUserBySlug(owner, "context-team", { request });
222
- assert.equal(directory.resolveWorkspaceContextForUserBySlug(owner, "Context-Team", { request }), shared,
223
- "one request reads one context for the same user and slug");
224
- await shared;
221
+ const [shared, again] = await Promise.all([
222
+ directory.resolveWorkspaceContextForUserBySlug(owner, "context-team", { request }),
223
+ directory.resolveWorkspaceContextForUserBySlug(owner, "Context-Team", { request })
224
+ ]);
225
+ assert.equal(again, shared, "one request reads one context for the same user and slug");
225
226
  });
226
227
 
227
228
  test("get and update read the context first and save only the patchable fields", async () => {
@@ -351,6 +351,9 @@ test("workspaceMembersService.createInvite sends generated invite URLs through t
351
351
  assert.equal(templateCalls[0].inviteUrl, response.inviteUrl);
352
352
  assert.equal(templateCalls[0].locale, "en");
353
353
  assert.equal(mailerCalls.length, 1);
354
+ // The mailer is told which saved invitation it sends, and in which workspace.
355
+ assert.equal(mailerCalls[0].payload.inviteId, "88");
356
+ assert.equal(mailerCalls[0].payload.workspace.id, "7");
354
357
  assert.equal(mailerCalls[0].payload.locale, "en");
355
358
  assert.equal(mailerCalls[0].payload.email, "invitee@example.com");
356
359
  assert.equal(mailerCalls[0].payload.inviteUrl, response.inviteUrl);
@@ -6,6 +6,7 @@ import { AuthPolicyProvider } from "@jskit-ai/auth-core/server/providers/AuthPol
6
6
  import { CrudContractsProvider } from "@jskit-ai/crud-core/server/crudContracts";
7
7
  import { defineCrudFeature } from "@jskit-ai/crud-core/server/defineCrudFeature";
8
8
  import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
9
+ import { defineFeature } from "@jskit-ai/kernel/server/features";
9
10
  import { HttpProvider } from "@jskit-ai/kernel/server/http";
10
11
  import { createBootstrapRuntime } from "@jskit-ai/kernel/server/runtime";
11
12
  import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
@@ -16,6 +17,7 @@ import { UsersIdentityProvider } from "@jskit-ai/users-core/server/UsersIdentity
16
17
  import { WorkspacesFeature } from "../src/server/WorkspacesFeature.js";
17
18
  import { WorkspacesIntegrationsProvider } from "../src/server/WorkspacesIntegrationsProvider.js";
18
19
  import { WORKSPACE_CRUD_SCOPE } from "../src/server/support/workspaceCrud.js";
20
+ import { workspaceSlugParamsValidator } from "../src/server/common/validators/routeParamsValidator.js";
19
21
 
20
22
  // A workspace CRUD list served as an application serves it: Fastify, the auth policy plugin, the HTTP runtime's
21
23
  // visibility resolvers, the action context contributors and a CRUD feature on a workspace surface, over the users and
@@ -43,6 +45,44 @@ const IssuesFeature = defineCrudFeature({
43
45
  scope: WORKSPACE_CRUD_SCOPE
44
46
  });
45
47
 
48
+ // A hand-written route with contextPolicy "optional" and no permission: the auth policy resolves the workspace context
49
+ // without requiring membership, and the action's context contributor resolves it again requiring it.
50
+ const ACTION_READ_NOTICE = "test.workspace-notice.read";
51
+ const NoticeFeature = defineFeature({
52
+ id: "test.workspace-notice",
53
+ requires: { http: "runtime.http" },
54
+ setup({ http }) {
55
+ http.router.register(
56
+ "GET",
57
+ "/api/w/:workspaceSlug/notice",
58
+ {
59
+ auth: "required",
60
+ surface: "app",
61
+ visibility: "workspace",
62
+ contextPolicy: "optional",
63
+ meta: { summary: "Reads the workspace's notice." },
64
+ params: workspaceSlugParamsValidator
65
+ },
66
+ async function readNotice(request, reply) {
67
+ reply.code(200).send(await request.executeAction({ actionId: ACTION_READ_NOTICE, input: request.input.params }));
68
+ }
69
+ );
70
+ return {};
71
+ },
72
+ actions: [
73
+ Object.freeze({
74
+ id: ACTION_READ_NOTICE,
75
+ version: 1,
76
+ kind: "query",
77
+ channels: ["api"],
78
+ surfaces: ["app"],
79
+ input: workspaceSlugParamsValidator,
80
+ output: null,
81
+ execute: (_input, context) => ({ workspaceId: context.workspace.id, roleSid: context.membership.roleSid })
82
+ })
83
+ ]
84
+ });
85
+
46
86
  const config = Object.freeze({
47
87
  appPublicUrl: "http://localhost:5173",
48
88
  tenancyMode: "workspaces",
@@ -89,7 +129,8 @@ async function issuesApp(t) {
89
129
  WorkspacesFeature,
90
130
  WorkspacesIntegrationsProvider,
91
131
  CrudContractsProvider,
92
- IssuesFeature
132
+ IssuesFeature,
133
+ NoticeFeature
93
134
  ],
94
135
  requires: { profiles: "users.profiles", workspaces: "workspaces.core", memberships: "workspaces.memberships" },
95
136
  inputs: {
@@ -123,15 +164,17 @@ async function issuesApp(t) {
123
164
  { workspace_id: other.id, title: "Another workspace's issue" }
124
165
  ]);
125
166
 
126
- async function list(user, slug = workspace.slug) {
167
+ async function get(user, slug, suffix) {
127
168
  const { result: response, queries } = await countQueries(knex, () => app.inject({
128
169
  method: "GET",
129
- url: `/api/w/${slug}/issues`,
170
+ url: `/api/w/${slug}/${suffix}`,
130
171
  headers: user ? { "x-test-user": user.id } : {}
131
172
  }));
132
173
  return { response, queries };
133
174
  }
134
- return { list, owner, member, guest, outsider, workspace };
175
+ const list = (user, slug = workspace.slug) => get(user, slug, "issues");
176
+ const notice = (user, slug = workspace.slug) => get(user, slug, "notice");
177
+ return { list, notice, owner, member, guest, outsider, workspace };
135
178
  }
136
179
 
137
180
  // The statements of one read of the workspace context, whatever the database quotes its names with: the workspace by
@@ -180,3 +223,25 @@ test("a workspace CRUD list request refuses as strictly as before", async (t) =>
180
223
  assert.ok(reading(queries, "workspace").length <= 1, `${label} reads the workspace at most once: ${queries.join("\n")}`);
181
224
  }
182
225
  });
226
+
227
+ test("a route whose auth policy and action context differ in requiring membership reads the context once", async (t) => {
228
+ const { notice, owner, member, outsider, workspace } = await issuesApp(t);
229
+
230
+ for (const [user, roleSid] of [[owner, "owner"], [member, "member"]]) {
231
+ const { response, queries } = await notice(user);
232
+ assert.equal(response.statusCode, 200, response.body);
233
+ assert.deepEqual(response.json(), { workspaceId: workspace.id, roleSid });
234
+ const statements = queries.join("\n");
235
+ t.diagnostic(`a contextPolicy "optional" request for the ${roleSid} sends ${queries.length} statements`);
236
+ // Before, the auth policy's read (membership optional) and the action context's (membership required) were two.
237
+ assert.equal(reading(queries, "workspace").length, 1, statements);
238
+ assert.equal(reading(queries, "membership").length, 1, statements);
239
+ assert.equal(reading(queries, "settings").length, 1, statements);
240
+ }
241
+
242
+ // The shared read still refuses a non-member where membership is required.
243
+ const { response, queries } = await notice(outsider);
244
+ assert.equal(response.statusCode, 403, response.body);
245
+ assert.equal(response.body.includes("workspaces.workspace.accessDenied"), true, response.body);
246
+ assert.equal(reading(queries, "workspace").length, 1, queries.join("\n"));
247
+ });
@@ -802,11 +802,12 @@ test("one request's auth policy and action context share one workspace context r
802
802
  await service.resolveWorkspaceContextForUserBySlug(user, "team-alpha");
803
803
  assert.equal(calls.findBySlug, 4, "A call without a request resolves each time");
804
804
  const request = {};
805
- await service.resolveWorkspaceContextForUserBySlug(user, "team-alpha", { request });
806
- await service.resolveWorkspaceContextForUserBySlug(user, "team-alpha", { request, requireMembership: false });
805
+ const required = await service.resolveWorkspaceContextForUserBySlug(user, "team-alpha", { request });
806
+ const optional = await service.resolveWorkspaceContextForUserBySlug(user, "team-alpha", { request, requireMembership: false });
807
+ assert.equal(optional, required, "Another membership requirement shares the read");
807
808
  await service.resolveWorkspaceContextForUserBySlug({ ...user, id: "8" }, "team-alpha", { request });
808
809
  await service.resolveWorkspaceContextForUserBySlug(user, "team-alpha", { request });
809
- assert.equal(calls.findBySlug, 7, "Another membership requirement or user resolves on its own");
810
+ assert.equal(calls.findBySlug, 6, "Another user resolves on its own");
810
811
  });
811
812
 
812
813
  test("workspaceService.getWorkspaceForAuthenticatedUser resolves workspace from slug context", async () => {