@jskit-ai/workspaces-core 0.2.45 → 0.2.47

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,12 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - `workspaces.core` gains `roleContext({ workspaceId, userId, role, reason }, { context: systemContext(reason), trx? })`, the context of installer and seed work done in one workspace as a user in a role of the role catalog that they are not given there: required records a workspace gets for the platform's owner, who is normally no member of a self-created workspace, or a seed's starter data. It has exactly a member context's shape (`actor`, `workspace`, `membership`, `permissions`, the `workspace_user` visibility context and `requestMeta.resolvedWorkspaceContext`) with the membership `{ workspaceId, userId, roleSid, status: "active" }`, which is never saved and replaces any membership the user has there, and the role's permissions, so a permission check and a row policy decide as for a member in that role; it also records `reason`, which a row policy reads as `caller.reason` and which grants nothing. It is no system context and no job: request row limits apply and other owners' hidden fields stay hidden. Only a system context makes one, with a non-empty reason; any other context, a missing reason, ids that are no record ids and a role the catalog lacks are a TypeError before any statement, a missing or deleted workspace is 404 `workspaces.workspace.notFound`, a user id naming no one 404 `users.profile.notFound`, and an application without workspaces 403 `workspaces.workspace.contextDisabled`. It reads the user, the workspace and its settings, and writes nothing (no settings, no owner membership). The directory service's new `resolveRoleWorkspaceContextById(user, workspaceId, roleSid, options)` builds it. `memberContext` is unchanged and still means real membership only.
6
+ - An action run in a context that already carries the resolved context of the action's workspace (`requestMeta.resolvedWorkspaceContext` with that workspace's slug, as a member context and a role context carry it) keeps it: the workspace action context contributor no longer reads the workspace, the membership and the settings again, so a role context's unsaved membership survives into the action, and a member context's action no longer repeats its reads.
7
+
8
+ - A new PostgreSQL or SQLite database migrates again with workspaces-core. In 0.2.80 its first `db:migrate` failed with `migration file "workspaces_core_indexes_by_user.cjs" failed` (`relation "workspace_memberships" does not exist` on PostgreSQL, `no such table` on SQLite): Knex runs a package's migrations in file name order, which put the new index migration before `workspaces_core_initial`, the one that makes the tables. `workspaces_core_indexes_by_user` now does nothing when the tables do not exist yet, and the new `workspaces_core_person_indexes`, which runs after `workspaces_core_initial`, adds `ix_workspace_memberships_user` and `ix_workspaces_owner` when they are missing. A database that already ran `workspaces_core_indexes_by_user` keeps its two indexes, and the new migration adds no second copy. MariaDB and MySQL were not affected and nothing changes there. Run `db:migrate`.
9
+ - Making a workspace (`workspace.workspaces.create`) and changing its name or avatar (`workspace.workspaces.update`) publish an entity change of the workspace itself on `runtime.events`: `type` "entity.changed", `source` "workspace", `entity` "workspace", `operation` "created" or "updated", `entityId` the workspace's id from the action's answer. Before, neither action published anything, so an application keeping its own copy of workspace facts (a directory, an index of names) heard of a member or a settings change but never of a new or renamed workspace. The events carry no realtime delivery; no browser is told.
10
+
5
11
  - A person's workspaces are read through an index on PostgreSQL: the new migration `workspaces_core_indexes_by_user` adds `ix_workspace_memberships_user` (`workspace_memberships.user_id`), which `workspaces.listForUserId` and `workspaces.memberships.listActiveWorkspaceIdsByUserId` read by, and `ix_workspaces_owner` (`workspaces.owner_user_id`), which `workspaces.findPersonalByOwnerUserId` reads by. PostgreSQL indexes no foreign key's columns by itself, so each of those reads scanned every membership or workspace; the memberships' unique `(workspace_id, user_id)` key serves a workspace's members, not a person's workspaces. MariaDB and MySQL already index both columns through their foreign keys' own indexes, so there the migration changes nothing. Run `db:migrate`.
6
12
 
7
13
  - `workspaces.core` gains `memberContext({ workspaceId, userId }, { context: systemContext(reason), trx? })`, the context of one member of one workspace for background work done as that member: a record started for the person it is assigned to, a notification for one recipient, a member's template setup, a submission synced for the person who made it. It is resolved as the member's own request on a `workspace_user` route is, by the same reads (the workspace, the active membership with the owner's ensured, the role's permissions and the settings), now shared with that request's resolution through the directory service's new `resolveMemberWorkspaceContextById(user, workspaceId, options)`, and refused as it is: 404 `workspaces.workspace.notFound` for a missing or deleted workspace, 403 `workspaces.workspace.accessDenied` for a user who is no active member (removed, inactive, never one, or no user), 403 `workspaces.workspace.contextDisabled` without workspaces. The context signs the member in (`actor`, so `resolveActorId` answers them and an action checks their `permissions`), carries `workspace`, `membership`, `permissions`, the `workspace_user` visibility context and `requestMeta.resolvedWorkspaceContext`, and is no system context or job: request row limits apply, other owners' hidden fields stay hidden and a row policy is told `caller.kind` "user". Only a system context makes one; any other context, a `forWorkspace` job's too, and ids that are no record ids are a TypeError before any statement. An action runs in it with `actions.execute({ actionId, input, context: { ...member, surface: "app" } })` and sees what the member's request on that route sees. JSKIT keeps no disabled flag on users, so it reads no sign-in state: an account its auth provider refuses at sign-in is still resolved.
@@ -7,6 +7,11 @@
7
7
  // and MariaDB) made an index for each foreign key when the tables were created, named after the key
8
8
  // (workspace_memberships_user_id_foreign, workspaces_owner_user_id_foreign), which already serves these reads, so
9
9
  // there it adds nothing.
10
+ //
11
+ // Knex runs a directory's migrations in file name order, which puts this one before workspaces_core_initial: on a new
12
+ // database the tables do not exist yet when it runs, so it does nothing, and workspaces_core_person_indexes, which runs
13
+ // after workspaces_core_initial, adds the indexes. On a database that already had the tables it adds them, as it always
14
+ // did; every database it ran on is one of those, since on any other it failed.
10
15
  const INDEXES = Object.freeze([
11
16
  Object.freeze({ table: "workspace_memberships", name: "ix_workspace_memberships_user", column: "user_id" }),
12
17
  Object.freeze({ table: "workspaces", name: "ix_workspaces_owner", column: "owner_user_id" })
@@ -18,6 +23,9 @@ function foreignKeysAreIndexed(knex) {
18
23
 
19
24
  exports.up = async function up(knex) {
20
25
  if (foreignKeysAreIndexed(knex)) return;
26
+ for (const { table } of INDEXES) {
27
+ if (!(await knex.schema.hasTable(table))) return;
28
+ }
21
29
  for (const { table, name, column } of INDEXES) {
22
30
  await knex.raw("create index if not exists ?? on ?? (??)", [name, table, column]);
23
31
  }
@@ -0,0 +1,30 @@
1
+ // The indexes a person's workspaces are read through, as workspaces_core_indexes_by_user describes them:
2
+ // ix_workspace_memberships_user (workspace_memberships.user_id) and ix_workspaces_owner (workspaces.owner_user_id), on
3
+ // PostgreSQL and SQLite. MySQL and MariaDB index both columns through their foreign keys, so there it adds nothing.
4
+ //
5
+ // workspaces_core_indexes_by_user runs before workspaces_core_initial (Knex runs a directory's migrations in file name
6
+ // order), so on a new database it finds no tables and adds nothing; this one runs after workspaces_core_initial and
7
+ // adds them. On a database that had the tables when workspaces_core_indexes_by_user ran, the indexes exist already and
8
+ // this one leaves them as they are.
9
+ const INDEXES = Object.freeze([
10
+ Object.freeze({ table: "workspace_memberships", name: "ix_workspace_memberships_user", column: "user_id" }),
11
+ Object.freeze({ table: "workspaces", name: "ix_workspaces_owner", column: "owner_user_id" })
12
+ ]);
13
+
14
+ function foreignKeysAreIndexed(knex) {
15
+ return /mysql|maria/iu.test(String(knex.client.config.client));
16
+ }
17
+
18
+ exports.up = async function up(knex) {
19
+ if (foreignKeysAreIndexed(knex)) return;
20
+ for (const { table, name, column } of INDEXES) {
21
+ await knex.raw("create index if not exists ?? on ?? (??)", [name, table, column]);
22
+ }
23
+ };
24
+
25
+ exports.down = async function down(knex) {
26
+ if (foreignKeysAreIndexed(knex)) return;
27
+ for (const { name } of INDEXES) {
28
+ await knex.raw("drop index if exists ??", [name]);
29
+ }
30
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/workspaces-core",
3
- "version": "0.2.45",
3
+ "version": "0.2.47",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -25,7 +25,7 @@
25
25
  "dependencies": {
26
26
  "@jskit-ai/resource-core": "0.1.217",
27
27
  "@jskit-ai/resource-crud-core": "0.1.219",
28
- "@jskit-ai/users-core": "0.2.45",
28
+ "@jskit-ai/users-core": "0.2.47",
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.",
@@ -215,6 +215,6 @@
215
215
  "@jskit-ai/database-runtime": "0.1.275",
216
216
  "@jskit-ai/http-runtime": "0.2.26",
217
217
  "@jskit-ai/kernel": "0.2.26",
218
- "@jskit-ai/resource-runtime": "0.2.34"
218
+ "@jskit-ai/resource-runtime": "0.2.35"
219
219
  }
220
220
  }
@@ -1,5 +1,5 @@
1
1
  import { resolveRequest } from "@jskit-ai/kernel/server/actions/actionContributorHelpers";
2
- import { normalizeObject } from "@jskit-ai/kernel/shared/support/normalize";
2
+ import { normalizeLowerText, normalizeObject } from "@jskit-ai/kernel/shared/support/normalize";
3
3
  import { normalizeSurfaceId } from "@jskit-ai/kernel/shared/surface/registry";
4
4
  import {
5
5
  checkRouteVisibility,
@@ -54,11 +54,19 @@ function createWorkspaceActionContextContributor({
54
54
  resolveOptions.requireMembership = false;
55
55
  }
56
56
 
57
- const resolvedWorkspaceContext = await workspaceService.resolveWorkspaceContextForUserBySlug(
58
- resolveActionUser(context, payload),
59
- payload.workspaceSlug,
60
- resolveOptions
61
- );
57
+ // A context that already carries this workspace's resolved context, as a member context and a role context do
58
+ // (workspaces.memberContext, workspaces.roleContext), keeps it: a role context's membership is never saved, so no
59
+ // read finds it.
60
+ const carried = context?.requestMeta?.resolvedWorkspaceContext;
61
+ const carriesWorkspace = Boolean(carried?.workspace?.slug) &&
62
+ normalizeLowerText(carried.workspace.slug) === normalizeLowerText(payload.workspaceSlug);
63
+ const resolvedWorkspaceContext = carriesWorkspace
64
+ ? carried
65
+ : await workspaceService.resolveWorkspaceContextForUserBySlug(
66
+ resolveActionUser(context, payload),
67
+ payload.workspaceSlug,
68
+ resolveOptions
69
+ );
62
70
 
63
71
  const contribution = {
64
72
  requestMeta: {
@@ -312,6 +312,31 @@ function createService({
312
312
  return requireMember(await readWorkspaceContextForUser(user, workspace?.deletedAt ? null : workspace, options));
313
313
  }
314
314
 
315
+ /**
316
+ * The workspace context of a user acting in the workspace with this id in a role of the role catalog, for installer
317
+ * and seed work (the `roleContext` of `workspaces.core`): the workspace, an active membership of the user in that
318
+ * role, which is never saved and replaces any membership the user has there, the role's permissions and the
319
+ * workspace's settings as stored. It writes nothing. A deleted or missing workspace is 404
320
+ * `workspaces.workspace.notFound`, as for resolveMemberWorkspaceContextById.
321
+ * @param {{ id: string }} user
322
+ * @param {unknown} workspaceId
323
+ * @param {string} roleSid The id of a role of the role catalog.
324
+ * @param {object} [options]
325
+ */
326
+ async function resolveRoleWorkspaceContextById(user, workspaceId, roleSid, options = {}) {
327
+ requireWorkspaceContext();
328
+ const workspace = await workspacesRepository.findById(workspaceId, options);
329
+ if (!workspace || workspace.deletedAt) {
330
+ throw new AppError(404, "Workspace not found.", { code: "workspaces.workspace.notFound" });
331
+ }
332
+ return {
333
+ workspace,
334
+ membership: Object.freeze({ workspaceId: workspace.id, userId: user.id, roleSid, status: "active" }),
335
+ permissions: listCatalogRolePermissions(roleCatalog, roleSid),
336
+ workspaceSettings: await workspaceSettingsRepository.findByWorkspaceId(workspace.id, options)
337
+ };
338
+ }
339
+
315
340
  function requireWorkspaceContext() {
316
341
  if (resolvedTenancyMode === TENANCY_MODE_NONE) {
317
342
  throw new AppError(403, "Workspace context is disabled.", { code: "workspaces.workspace.contextDisabled" });
@@ -370,7 +395,8 @@ function createService({
370
395
  listWorkspacesForUser,
371
396
  listWorkspacesForAuthenticatedUser,
372
397
  resolveWorkspaceContextForUserBySlug,
373
- resolveMemberWorkspaceContextById
398
+ resolveMemberWorkspaceContextById,
399
+ resolveRoleWorkspaceContextById
374
400
  });
375
401
  }
376
402
 
@@ -1,5 +1,6 @@
1
1
  import { normalizeAuthActor } from "@jskit-ai/auth-core/server/authActor";
2
- import { normalizeRecordId } from "@jskit-ai/kernel/shared/support/normalize";
2
+ import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
3
+ import { normalizeLowerText, normalizeRecordId } from "@jskit-ai/kernel/shared/support/normalize";
3
4
  import { normalizeVisibilityContext, ROUTE_VISIBILITY_WORKSPACE_USER } from "@jskit-ai/kernel/shared/support/visibility";
4
5
  import { isSystemContext } from "@jskit-ai/resource-runtime/server";
5
6
  import { buildVisibilityContribution } from "../contributors/workspaceRouteVisibilityResolver.js";
@@ -21,12 +22,39 @@ function memberActorOf(profile) {
21
22
  }
22
23
 
23
24
  /**
24
- * The `memberContext` of `workspaces.core`.
25
+ * The context of the user this profile is in a resolved workspace context, as their request on a `workspace_user`
26
+ * route carries it.
27
+ * @param {{ id: string, authProvider: string, authProviderUserSid: string, email: string, displayName: string }} profile
28
+ * @param {{ workspace: { id: string }, membership: object, permissions: string[] }} resolvedWorkspaceContext
29
+ */
30
+ function workspaceUserContextOf(profile, resolvedWorkspaceContext) {
31
+ return {
32
+ actor: memberActorOf(profile),
33
+ workspace: resolvedWorkspaceContext.workspace,
34
+ membership: resolvedWorkspaceContext.membership,
35
+ permissions: resolvedWorkspaceContext.permissions,
36
+ // An action it runs resolves its visibility as that route's request does, to this visibility context.
37
+ routeVisibility: ROUTE_VISIBILITY_WORKSPACE_USER,
38
+ visibilityContext: normalizeVisibilityContext({
39
+ visibility: ROUTE_VISIBILITY_WORKSPACE_USER,
40
+ ...buildVisibilityContribution({
41
+ visibility: ROUTE_VISIBILITY_WORKSPACE_USER,
42
+ scopeOwnerId: resolvedWorkspaceContext.workspace.id,
43
+ userId: profile.id
44
+ })
45
+ }),
46
+ requestMeta: Object.freeze({ resolvedWorkspaceContext })
47
+ };
48
+ }
49
+
50
+ /**
51
+ * The `memberContext` and `roleContext` of `workspaces.core`.
25
52
  * @param {object} dependencies
26
53
  * @param {import("../../types.js").WorkspaceDirectoryService} dependencies.workspaceService
27
54
  * @param {import("@jskit-ai/users-core/server/types").UsersProfiles} dependencies.userProfiles
55
+ * @param {import("../../types.js").WorkspaceRoleCatalog} dependencies.roleCatalog
28
56
  */
29
- function createWorkspaceMemberContexts({ workspaceService, userProfiles }) {
57
+ function createWorkspaceMemberContexts({ workspaceService, userProfiles, roleCatalog }) {
30
58
  /**
31
59
  * The context of one member of one workspace, for background work done as that member (a record started for the
32
60
  * person it is assigned to, a notification for one recipient, a submission synced for the person who made it): the
@@ -63,27 +91,65 @@ function createWorkspaceMemberContexts({ workspaceService, userProfiles }) {
63
91
  // A user id that names no one is no member, which the membership check refuses.
64
92
  const profile = await userProfiles.findById(normalizedUserId, options);
65
93
  const resolvedWorkspaceContext = await workspaceService.resolveMemberWorkspaceContextById(profile, normalizedWorkspaceId, options);
94
+ return Object.freeze(workspaceUserContextOf(profile, resolvedWorkspaceContext));
95
+ }
96
+
97
+ /**
98
+ * The context of a user acting in one workspace in a role of the role catalog that they are not given there, for
99
+ * installer and seed work the platform does for a person who is no member, or a member in another role: required
100
+ * modules installed for the platform's owner in each workspace, say. It has exactly a member context's shape: the
101
+ * user is its `actor`, `membership` is an active membership of theirs in that role
102
+ * (`{ workspaceId, userId, roleSid, status: "active" }`), which is never saved and replaces any membership they
103
+ * have there, and `permissions` are the role's, so a permission check or a row policy that reads them decides as for
104
+ * a member in that role. It is no system context and no job: request row limits apply, other owners' hidden fields
105
+ * stay hidden, and a row policy is told `caller.kind` "user", with the `reason` the context records as
106
+ * `caller.reason`, which grants nothing. Work done as a real member takes `memberContext`, which refuses anyone who
107
+ * is not one.
108
+ *
109
+ * Only a system context makes one (`{ context: systemContext(reason) }`, with `trx` to read in the caller's
110
+ * transaction), and only with the reason this work acts in a role: any other context, a missing or blank reason,
111
+ * ids that are no record ids and a role the catalog does not have are a TypeError, before any statement. A missing
112
+ * or deleted workspace is 404 `workspaces.workspace.notFound`, a user id that names no one 404
113
+ * `users.profile.notFound`, and an application without workspaces 403 `workspaces.workspace.contextDisabled`. It
114
+ * reads the user, the workspace and its settings, and writes nothing.
115
+ * @param {{ workspaceId: unknown, userId: unknown, role: unknown, reason: unknown }} acting
116
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} options
117
+ */
118
+ async function roleContext({ workspaceId, userId, role, reason } = {}, options = {}) {
119
+ if (!isSystemContext(options.context)) {
120
+ throw new TypeError("workspaces.roleContext() runs only in a system context: pass { context: systemContext(reason) }.");
121
+ }
122
+ const normalizedReason = typeof reason === "string" ? reason.trim() : "";
123
+ if (!normalizedReason) {
124
+ throw new TypeError("workspaces.roleContext() needs { reason }: why this work acts in a role the user is not given in the workspace.");
125
+ }
126
+ const normalizedWorkspaceId = normalizeRecordId(workspaceId, { fallback: null });
127
+ const normalizedUserId = normalizeRecordId(userId, { fallback: null });
128
+ if (!normalizedWorkspaceId || !normalizedUserId) {
129
+ throw new TypeError(
130
+ "workspaces.roleContext() takes { workspaceId, userId }, the ids of a workspace and of the user who acts in it. " +
131
+ `Received: ${String(workspaceId)}, ${String(userId)}`
132
+ );
133
+ }
134
+ const roleSid = normalizeLowerText(role);
135
+ const roleIds = roleCatalog.roles.map((entry) => entry.id);
136
+ if (!roleIds.includes(roleSid)) {
137
+ throw new TypeError(`workspaces.roleContext() takes a role of the role catalog (${roleIds.join(", ")}). Received: ${String(role)}`);
138
+ }
139
+ const profile = await userProfiles.findById(normalizedUserId, options);
140
+ if (!profile) {
141
+ throw new AppError(404, "User profile was not found.", { code: "users.profile.notFound" });
142
+ }
143
+ const resolvedWorkspaceContext = await workspaceService.resolveRoleWorkspaceContextById(profile, normalizedWorkspaceId, roleSid, options);
66
144
  return Object.freeze({
67
- actor: memberActorOf(profile),
68
- workspace: resolvedWorkspaceContext.workspace,
69
- membership: resolvedWorkspaceContext.membership,
70
- permissions: resolvedWorkspaceContext.permissions,
71
- // An action it runs resolves its visibility as that route's request does, to this visibility context.
72
- routeVisibility: ROUTE_VISIBILITY_WORKSPACE_USER,
73
- visibilityContext: normalizeVisibilityContext({
74
- visibility: ROUTE_VISIBILITY_WORKSPACE_USER,
75
- ...buildVisibilityContribution({
76
- visibility: ROUTE_VISIBILITY_WORKSPACE_USER,
77
- scopeOwnerId: resolvedWorkspaceContext.workspace.id,
78
- userId: profile.id
79
- })
80
- }),
81
- requestMeta: Object.freeze({ resolvedWorkspaceContext })
145
+ ...workspaceUserContextOf(profile, resolvedWorkspaceContext),
146
+ reason: normalizedReason
82
147
  });
83
148
  }
84
149
 
85
150
  return Object.freeze({
86
- memberContext
151
+ memberContext,
152
+ roleContext
87
153
  });
88
154
  }
89
155
 
@@ -1,3 +1,5 @@
1
+ import { jsonApiResultValue } from "@jskit-ai/http-runtime/shared";
2
+ import { createEntityChangedActionEvent } from "@jskit-ai/kernel/server/actions";
1
3
  import { emptyInputValidator } from "@jskit-ai/kernel/server/actions/actionContributorHelpers";
2
4
  import { composeSchemaDefinitions } from "@jskit-ai/kernel/shared/validators";
3
5
  import { workspaceCrud } from "../../shared/resources/workspaceResource.js";
@@ -8,6 +10,15 @@ function workspaceAssistantSummary({ id, slug, name, ownerUserId, avatarUrl }) {
8
10
  return { id, slug, name, ownerUserId, avatarUrl };
9
11
  }
10
12
 
13
+ // A workspace made or changed (its name, its avatar) is an entity change of the workspace itself, for the application's
14
+ // listeners on runtime.events; the workspace's id is the action's answer's.
15
+ const workspaceChanged = (operation) => Object.freeze([createEntityChangedActionEvent({
16
+ source: "workspace",
17
+ entity: "workspace",
18
+ operation,
19
+ entityId: ({ result }) => jsonApiResultValue(result)?.id
20
+ })]);
21
+
11
22
  const workspaceUpdateInputValidator = composeSchemaDefinitions([
12
23
  workspaceSlugParamsValidator,
13
24
  workspaceCrud.operations.patch.body
@@ -37,6 +48,7 @@ function createWorkspaceDirectoryActions({ workspaceService }) {
37
48
  transformResult: (result) => workspaceAssistantSummary(result.value)
38
49
  }
39
50
  },
51
+ events: workspaceChanged("created"),
40
52
  execute: (input, context) => workspaceService.createWorkspaceForAuthenticatedUser(
41
53
  resolveActionUser(context, input),
42
54
  input,
@@ -114,6 +126,7 @@ function createWorkspaceDirectoryActions({ workspaceService }) {
114
126
  transformResult: (result) => workspaceAssistantSummary(result.value)
115
127
  }
116
128
  },
129
+ events: workspaceChanged("updated"),
117
130
  execute: (input, context) => workspaceService.updateWorkspaceForAuthenticatedUser(
118
131
  resolveActionUser(context, input),
119
132
  input.workspaceSlug,
@@ -72,7 +72,7 @@ function createWorkspaceRecords(resources) {
72
72
 
73
73
  /**
74
74
  * The `workspaces.core` capability: the workspace services, the invite and
75
- * settings repositories and `memberContext`, built from the runtime config.
75
+ * settings repositories, `memberContext` and `roleContext`, built from the runtime config.
76
76
  * @param {object} dependencies
77
77
  * @param {import("@jskit-ai/kernel/server/types").RuntimeAppRoot} dependencies.appRoot
78
78
  * @param {import("@jskit-ai/kernel/server/types").RuntimeConfig} dependencies.config
@@ -159,7 +159,7 @@ function createWorkspacesRuntime({
159
159
  workspaceInvitationsEnabled: invitationsEnabled,
160
160
  roleCatalog
161
161
  });
162
- const memberContexts = createWorkspaceMemberContexts({ workspaceService, userProfiles });
162
+ const memberContexts = createWorkspaceMemberContexts({ workspaceService, userProfiles, roleCatalog });
163
163
 
164
164
  return Object.freeze({
165
165
  enabled: tenancyProfile.workspace.enabled === true,
@@ -167,6 +167,8 @@ function createWorkspacesRuntime({
167
167
  selfCreateEnabled: tenancyProfile.workspace.allowSelfCreate === true,
168
168
  // The context of one member of one workspace, for background work done as that member.
169
169
  memberContext: memberContexts.memberContext,
170
+ // The context of a user acting in one workspace in a role they are not given there, for installer and seed work.
171
+ roleContext: memberContexts.roleContext,
170
172
  // The workspace route support the assistant runtime reads.
171
173
  scope: Object.freeze({
172
174
  params: workspaceSlugParamsValidator,
@@ -1,4 +1,6 @@
1
- import { indexesByUserCases, openMysql } from "./support/indexesByUserCases.js";
1
+ import { indexesByUserCases, migrationOrderCases, openMysql } from "./support/indexesByUserCases.js";
2
2
 
3
- // workspaces_core_indexes_by_user on MariaDB/MySQL, whose foreign keys' own indexes serve these reads.
3
+ // workspaces_core_indexes_by_user and workspaces_core_person_indexes on MariaDB/MySQL, whose foreign keys' own indexes
4
+ // serve these reads.
4
5
  indexesByUserCases(openMysql("ws_by_user"), { dialect: "mysql" });
6
+ migrationOrderCases(openMysql("ws_order"), { dialect: "mysql" });
@@ -1,4 +1,5 @@
1
- import { POSTGRES_ELSEWHERE, indexesByUserCases, openPostgres } from "./support/indexesByUserCases.js";
1
+ import { POSTGRES_ELSEWHERE, indexesByUserCases, migrationOrderCases, openPostgres } from "./support/indexesByUserCases.js";
2
2
 
3
- // workspaces_core_indexes_by_user on PostgreSQL.
3
+ // workspaces_core_indexes_by_user and workspaces_core_person_indexes on PostgreSQL.
4
4
  indexesByUserCases(openPostgres("ws_by_user"), { dialect: "postgres", skip: POSTGRES_ELSEWHERE });
5
+ migrationOrderCases(openPostgres("ws_order"), { dialect: "postgres", skip: POSTGRES_ELSEWHERE });
@@ -1,4 +1,5 @@
1
- import { indexesByUserCases, openSqlite } from "./support/indexesByUserCases.js";
1
+ import { indexesByUserCases, migrationOrderCases, openSqlite } from "./support/indexesByUserCases.js";
2
2
 
3
- // workspaces_core_indexes_by_user on SQLite.
3
+ // workspaces_core_indexes_by_user and workspaces_core_person_indexes on SQLite.
4
4
  indexesByUserCases(openSqlite, { dialect: "sqlite", database: false });
5
+ migrationOrderCases(openSqlite, { dialect: "sqlite", database: false });
@@ -435,24 +435,25 @@ describe(`users and workspaces repositories on migrated ${databaseLabel}`, () =>
435
435
  // The directory service as workspacesRuntime builds it, with roles that grant different permissions, and its member
436
436
  // contexts.
437
437
  function memberDirectory(tenancyMode = "workspaces") {
438
+ const roleCatalog = createWorkspaceRoleCatalog({
439
+ roleCatalog: {
440
+ roles: {
441
+ owner: { permissions: ["*"] },
442
+ admin: { assignable: true, permissions: ["workspace.members.view", "crud.notes.patch"] },
443
+ member: { assignable: true, permissions: ["crud.notes.list"] }
444
+ }
445
+ }
446
+ });
438
447
  const directory = createDirectoryService({
439
448
  tenancyProfile: resolveTenancyProfile({ tenancyMode }),
440
- roleCatalog: createWorkspaceRoleCatalog({
441
- roleCatalog: {
442
- roles: {
443
- owner: { permissions: ["*"] },
444
- admin: { assignable: true, permissions: ["workspace.members.view", "crud.notes.patch"] },
445
- member: { assignable: true, permissions: ["crud.notes.list"] }
446
- }
447
- }
448
- }),
449
+ roleCatalog,
449
450
  personalWorkspaceName: buildWorkspaceName,
450
451
  createdParticipant: noWorkspaceCreatedParticipant,
451
452
  workspacesRepository: workspaces,
452
453
  workspaceMembershipsRepository: memberships,
453
454
  workspaceSettingsRepository: settings
454
455
  });
455
- return { directory, ...createWorkspaceMemberContexts({ workspaceService: directory, userProfiles: profiles }) };
456
+ return { directory, ...createWorkspaceMemberContexts({ workspaceService: directory, userProfiles: profiles, roleCatalog }) };
456
457
  }
457
458
 
458
459
  // A signed-in request's actor for a profile, as the local sign-in provider builds it.
@@ -641,6 +642,118 @@ describe(`users and workspaces repositories on migrated ${databaseLabel}`, () =>
641
642
  assert.ok(many.sql.every((sql) => /^select\b/iu.test(sql.trim())), "A member's resolution after the first writes nothing");
642
643
  });
643
644
 
645
+ test("roleContext gives a user a role of the catalog in a workspace, a member context's shape with an unsaved membership and the reason, and writes nothing", async () => {
646
+ const { directory, memberContext, roleContext } = memberDirectory();
647
+ const owner = await createProfile("Ada");
648
+ const member = await createProfile("Grace");
649
+ const outsider = await createProfile("Linus");
650
+ const workspace = await workspaces.insert({ slug: "team", name: "Team", ownerUserId: owner.id });
651
+ await memberships.ensureOwnerMembership(workspace.id, owner.id);
652
+ await memberships.addMember({ workspaceId: workspace.id, userId: member.id });
653
+ // The workspace's first request writes its settings; a workspace no request has opened has none yet.
654
+ await directory.resolveWorkspaceContextForUserBySlug(owner, workspace.slug);
655
+ const unopened = await workspaces.insert({ slug: "new", name: "New", ownerUserId: owner.id });
656
+ const system = { context: memberJobContext() };
657
+ const reason = "install the required modules for the platform's owner";
658
+
659
+ for (const [person, role] of [[outsider, "admin"], [member, "admin"], [owner, "member"]]) {
660
+ const { result: context, sql } = await statementsOf(() => roleContext({ workspaceId: workspace.id, userId: person.id, role, reason }, system));
661
+ assert.ok(sql.every((statement) => /^select\b/iu.test(statement.trim())), `${role} for ${person.displayName} writes nothing: ${sql.join(" | ")}`);
662
+ assert.deepEqual(context.membership, { workspaceId: workspace.id, userId: person.id, roleSid: role, status: "active" });
663
+ assert.deepEqual(context.permissions, role === "admin" ? ["workspace.members.view", "crud.notes.patch"] : ["crud.notes.list"]);
664
+ assert.deepEqual(context.actor, requestActorOf(person), "signed in as the user it names");
665
+ assert.equal(resolveActorId(context), person.id);
666
+ assert.equal(context.reason, reason);
667
+ assert.equal(isSystemContext(context), false, "A role context is no system context");
668
+ assert.equal(Object.isFrozen(context), true);
669
+ // A member context's shape, with the reason: the same workspace, visibility and settings as the member's request.
670
+ const request = await directory.resolveWorkspaceContextForUserBySlug(owner, workspace.slug);
671
+ assert.deepEqual(Object.keys(context).sort(), [...Object.keys(await memberContext({ workspaceId: workspace.id, userId: owner.id }, system)), "reason"].sort());
672
+ assert.deepEqual(context.workspace, request.workspace);
673
+ assert.equal(context.routeVisibility, "workspace_user");
674
+ assert.deepEqual(context.visibilityContext, {
675
+ visibility: "workspace_user",
676
+ scopeKind: "workspace_user",
677
+ requiresActorScope: true,
678
+ scopeOwnerId: workspace.id,
679
+ userId: person.id
680
+ });
681
+ assert.deepEqual(context.requestMeta.resolvedWorkspaceContext, {
682
+ workspace: request.workspace,
683
+ membership: context.membership,
684
+ permissions: context.permissions,
685
+ workspaceSettings: request.workspaceSettings
686
+ });
687
+ }
688
+ // The users' real memberships are as they were: none for the outsider, and the member's own role.
689
+ assert.equal(await memberships.findByWorkspaceIdAndUserId(workspace.id, outsider.id), null);
690
+ assert.equal((await memberships.findByWorkspaceIdAndUserId(workspace.id, member.id)).roleSid, "member");
691
+ assert.equal((await memberContext({ workspaceId: workspace.id, userId: member.id }, system)).membership.roleSid, "member");
692
+ await assert.rejects(memberContext({ workspaceId: workspace.id, userId: outsider.id }, system), (error) => error.status === 403);
693
+
694
+ // A workspace no request has opened has no settings yet, and the role context writes none, nor the owner's
695
+ // membership a member context ensures.
696
+ const { result: fresh, sql } = await statementsOf(() => roleContext({ workspaceId: unopened.id, userId: owner.id, role: "OWNER", reason }, system));
697
+ assert.ok(sql.every((statement) => /^select\b/iu.test(statement.trim())), sql.join(" | "));
698
+ assert.equal(fresh.requestMeta.resolvedWorkspaceContext.workspaceSettings, null);
699
+ assert.equal(fresh.membership.roleSid, "owner");
700
+ assert.equal(await knex("workspace_settings").where({ workspace_id: unopened.id }).first(), undefined);
701
+ assert.equal(await memberships.findByWorkspaceIdAndUserId(unopened.id, owner.id), null);
702
+
703
+ // In the caller's transaction it reads what the transaction wrote.
704
+ await memberships.withTransaction(system, async (txOptions) => {
705
+ const joiner = await createProfile("Barbara", txOptions);
706
+ const context = await roleContext({ workspaceId: workspace.id, userId: joiner.id, role: "member", reason }, txOptions);
707
+ assert.equal(context.actor.id, joiner.id);
708
+ });
709
+ });
710
+
711
+ test("roleContext refuses no system context, a missing reason, ids that are no record ids and a role the catalog lacks before any statement, and a missing workspace or user with 404", async () => {
712
+ const { roleContext } = memberDirectory();
713
+ const owner = await createProfile("Ada");
714
+ const workspace = await workspaces.insert({ slug: "team", name: "Team", ownerUserId: owner.id });
715
+ await memberships.ensureOwnerMembership(workspace.id, owner.id);
716
+ const deleted = await workspaces.insert({ slug: "gone", name: "Gone", ownerUserId: owner.id });
717
+ await workspaces.updateById(deleted.id, { deletedAt: new Date().toISOString() });
718
+ const systemContext = memberJobContext();
719
+ const asked = { workspaceId: workspace.id, userId: owner.id, role: "admin", reason: "seed the workspace's starter records" };
720
+ assert.equal((await roleContext(asked, { context: systemContext })).membership.roleSid, "admin");
721
+ const notSystem = /roleContext\(\) runs only in a system context/u;
722
+ const noReason = /roleContext\(\) needs \{ reason \}/u;
723
+ const badIds = /roleContext\(\) takes \{ workspaceId, userId \}/u;
724
+ const badRole = /roleContext\(\) takes a role of the role catalog \(owner, admin, member\)/u;
725
+ const refusals = [
726
+ ["no options", asked, undefined, notSystem],
727
+ ["a signed-in request's context", asked, { context: { actor: { id: owner.id } } }, notSystem],
728
+ ["a workspace job's context", asked, { context: systemContext.forWorkspace(workspace.id) }, notSystem],
729
+ ["a role context", asked, { context: await roleContext(asked, { context: systemContext }) }, notSystem],
730
+ ...[undefined, "", " ", 7, {}].map((reason) => [`reason ${JSON.stringify(reason)}`, { ...asked, reason }, { context: systemContext }, noReason]),
731
+ ["no workspaceId", { ...asked, workspaceId: undefined }, { context: systemContext }, badIds],
732
+ ["userId \"abc\"", { ...asked, userId: "abc" }, { context: systemContext }, badIds],
733
+ ...[undefined, "", "superuser", "admins"].map((role) => [`role ${JSON.stringify(role)}`, { ...asked, role }, { context: systemContext }, badRole])
734
+ ];
735
+ for (const [label, acting, options, message] of refusals) {
736
+ const { statements, sql } = await statementsOf(() => assert.rejects(roleContext(acting, options), (error) => {
737
+ assert.ok(error instanceof TypeError, `${label}: ${error}`);
738
+ assert.match(error.message, message, label);
739
+ return true;
740
+ }));
741
+ assert.equal(statements, 0, `${label} is refused before any statement: ${sql.join(" | ")}`);
742
+ }
743
+
744
+ const refuses = ([status, code], label) => (error) => {
745
+ assert.ok(error instanceof AppError, `${label}: ${error}`);
746
+ assert.deepEqual([error.status, error.code], [status, code], label);
747
+ return true;
748
+ };
749
+ const system = { context: systemContext };
750
+ await assert.rejects(roleContext({ ...asked, workspaceId: "999999" }, system), refuses([404, "workspaces.workspace.notFound"], "a workspace id naming no workspace"));
751
+ await assert.rejects(roleContext({ ...asked, workspaceId: deleted.id }, system), refuses([404, "workspaces.workspace.notFound"], "a deleted workspace"));
752
+ await assert.rejects(roleContext({ ...asked, userId: "999999" }, system), refuses([404, "users.profile.notFound"], "a user id naming no one"));
753
+ const { roleContext: noTenancyRoleContext } = memberDirectory("none");
754
+ await assert.rejects(noTenancyRoleContext(asked, system), refuses([403, "workspaces.workspace.contextDisabled"], "an application without workspaces"));
755
+ });
756
+
644
757
  test("workspaces.lock and memberships.lockByWorkspaceIdAndUserId take lockMode share, and refuse another mode before any statement", async () => {
645
758
  const owner = await createProfile("Ada");
646
759
  const workspace = await workspaces.insert({ slug: "shared", name: "Shared", ownerUserId: owner.id });
@@ -1,5 +1,9 @@
1
1
  import assert from "node:assert/strict";
2
+ import { readdirSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import path from "node:path";
2
5
  import test from "node:test";
6
+ import { fileURLToPath } from "node:url";
3
7
  import knexLib from "knex";
4
8
  import { requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
5
9
  import { startTestFeatures } from "@jskit-ai/resource-runtime/test";
@@ -26,6 +30,14 @@ const READS = Object.freeze({
26
30
  memberships: { table: "workspace_memberships", column: "user_id", sqlite: "ix_workspace_memberships_user", postgres: "ix_workspace_memberships_user", mysql: "workspace_memberships_user_id_foreign" },
27
31
  owned: { table: "workspaces", column: "owner_user_id", sqlite: "ix_workspaces_owner", postgres: "ix_workspaces_owner", mysql: "workspaces_owner_user_id_foreign" }
28
32
  });
33
+ // The migration directories of users-core and workspaces-core, in the order an application migrates them, each in
34
+ // file name order, as createKnexMigrationConfig has Knex run them.
35
+ const MIGRATION_DIRECTORIES = ["../../../users-core/migrations", "../../migrations"]
36
+ .map((directory) => fileURLToPath(new URL(directory, import.meta.url)));
37
+ const DIRECTORY_MIGRATIONS = Object.freeze({ directory: MIGRATION_DIRECTORIES, extension: "cjs", sortDirsSeparately: true });
38
+ const INDEXES_BY_USER = "workspaces_core_indexes_by_user.cjs";
39
+ const PERSON_INDEXES = "workspaces_core_person_indexes.cjs";
40
+ const require = createRequire(import.meta.url);
29
41
 
30
42
  // Each index of `table` with its columns in order.
31
43
  async function indexColumns(knex, dialect, table) {
@@ -53,6 +65,28 @@ async function indexColumns(knex, dialect, table) {
53
65
  return columns;
54
66
  }
55
67
 
68
+ // The indexes of `table` on `column` alone.
69
+ async function indexesOn(knex, dialect, table, column) {
70
+ const indexes = [...(await indexColumns(knex, dialect, table))];
71
+ return indexes.filter(([, columns]) => columns.length === 1 && columns[0] === column).map(([name]) => name);
72
+ }
73
+
74
+ // The migrations of a database made before workspaces_core_indexes_by_user existed and then upgraded to the release
75
+ // that added it: every other migration of both directories in Knex's order, then that one. The migrations are named
76
+ // by their files, as Knex names a directory's, so a later run on the directories finds them run.
77
+ function upgradedDatabaseMigrations() {
78
+ const files = MIGRATION_DIRECTORIES.flatMap((directory) =>
79
+ readdirSync(directory).filter((file) => file.endsWith(".cjs")).sort().map((file) => ({ directory, file })));
80
+ return {
81
+ getMigrations: async () => [
82
+ ...files.filter(({ file }) => file !== INDEXES_BY_USER && file !== PERSON_INDEXES),
83
+ files.find(({ file }) => file === INDEXES_BY_USER)
84
+ ],
85
+ getMigrationName: ({ file }) => file,
86
+ getMigration: async ({ directory, file }) => require(path.join(directory, file))
87
+ };
88
+ }
89
+
56
90
  // The indexes the planner reads for one captured statement. PostgreSQL's planner is told to avoid whole-table scans,
57
91
  // which it prefers for tables this small, so its plan shows whether an index can serve the statement.
58
92
  async function indexesUsed(knex, dialect, { sql, bindings }) {
@@ -148,6 +182,43 @@ function indexesByUserCases(open, { dialect, database = true, skip = false }) {
148
182
  });
149
183
  }
150
184
 
185
+ /**
186
+ * Registers the tests of the migrations as Knex runs them, on the empty database `open(t)` answers: a new database
187
+ * migrated from nothing, and one that ran workspaces_core_indexes_by_user after workspaces_core_initial. Each ends with
188
+ * `ix_workspace_memberships_user` and `ix_workspaces_owner` (InnoDB's foreign key indexes on MariaDB/MySQL), each the
189
+ * one index on its column.
190
+ * @param {(t: import("node:test").TestContext) => Promise<import("knex").Knex>} open
191
+ * @param {{ dialect: "sqlite" | "postgres" | "mysql", database?: boolean, skip?: string | false }} options
192
+ */
193
+ function migrationOrderCases(open, { dialect, database = true, skip = false }) {
194
+ async function indexedOnce(knex) {
195
+ for (const { table, column, [dialect]: index } of Object.values(READS)) {
196
+ assert.deepEqual(await indexesOn(knex, dialect, table, column), [index], `${table}.${column} has one index, ${index}`);
197
+ }
198
+ }
199
+
200
+ test(`a new database migrated in Knex's order has a person's indexes (${dialect})`, { skip }, async (t) => {
201
+ if (database) requireTestDatabase(process.env);
202
+ const knex = await open(t);
203
+ await knex.migrate.latest(DIRECTORY_MIGRATIONS);
204
+ await indexedOnce(knex);
205
+ // Rolled back in the reverse order, workspaces_core_person_indexes takes the indexes back before the tables go and
206
+ // workspaces_core_indexes_by_user, last, finds nothing to drop.
207
+ await knex.migrate.rollback(DIRECTORY_MIGRATIONS, true);
208
+ assert.equal(await knex.schema.hasTable("workspace_memberships"), false);
209
+ });
210
+
211
+ test(`a database that ran ${INDEXES_BY_USER} after the tables keeps its indexes, once (${dialect})`, { skip }, async (t) => {
212
+ if (database) requireTestDatabase(process.env);
213
+ const knex = await open(t);
214
+ await knex.migrate.latest({ migrationSource: upgradedDatabaseMigrations() });
215
+ await indexedOnce(knex);
216
+ const [, ran] = await knex.migrate.latest(DIRECTORY_MIGRATIONS);
217
+ assert.deepEqual(ran, [PERSON_INDEXES]);
218
+ await indexedOnce(knex);
219
+ });
220
+ }
221
+
151
222
  /** An in-memory SQLite database. */
152
223
  async function openSqlite(t) {
153
224
  const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
@@ -207,4 +278,4 @@ const POSTGRES_ELSEWHERE = process.env.DB_CLIENT && process.env.DB_CLIENT !== "p
207
278
  ? `a PostgreSQL test, on a ${process.env.DB_CLIENT} run`
208
279
  : false;
209
280
 
210
- export { POSTGRES_ELSEWHERE, indexesByUserCases, openMysql, openPostgres, openSqlite };
281
+ export { POSTGRES_ELSEWHERE, indexesByUserCases, migrationOrderCases, openMysql, openPostgres, openSqlite };
@@ -383,3 +383,40 @@ test("workspace action context contributor permits missing membership only for a
383
383
  assert.equal(contribution.membership, null);
384
384
  assert.deepEqual(contribution.permissions, []);
385
385
  });
386
+
387
+ test("workspace action context contributor keeps the resolved context a member or role context carries for the action's workspace", async () => {
388
+ const calls = [];
389
+ const contributor = createWorkspaceActionContextContributor({
390
+ workspaceService: {
391
+ async resolveWorkspaceContextForUserBySlug(user, workspaceSlug) {
392
+ calls.push(workspaceSlug);
393
+ return { workspace: { id: 11, slug: workspaceSlug }, membership: null, permissions: [] };
394
+ }
395
+ },
396
+ workspaceSurfaceIds: ["app"]
397
+ });
398
+ // A role context's membership, which no read finds.
399
+ const carried = {
400
+ workspace: { id: 10, slug: "acme" },
401
+ membership: { workspaceId: "10", userId: "42", roleSid: "owner", status: "active" },
402
+ permissions: ["*"]
403
+ };
404
+ const context = {
405
+ actor: { id: 42 },
406
+ workspace: carried.workspace,
407
+ membership: carried.membership,
408
+ permissions: carried.permissions,
409
+ requestMeta: { resolvedWorkspaceContext: carried }
410
+ };
411
+ const contribute = (workspaceSlug) => contributor.contribute({
412
+ definition: { id: "templates.install", surfaces: ["app"] },
413
+ input: { workspaceSlug },
414
+ context
415
+ });
416
+
417
+ assert.deepEqual(await contribute("ACME"), { requestMeta: { resolvedWorkspaceContext: carried } });
418
+ assert.deepEqual(calls, [], "the carried context of the same workspace is not resolved again");
419
+ // Another workspace's slug is resolved as before.
420
+ assert.deepEqual((await contribute("other")).requestMeta.resolvedWorkspaceContext.workspace, { id: 11, slug: "other" });
421
+ assert.deepEqual(calls, ["other"]);
422
+ });
@@ -251,7 +251,15 @@ async function issuesApp(t) {
251
251
  );
252
252
  return countQueries(knex, () => actions.execute({ actionId, input: { workspaceSlug: workspace.slug }, context: { ...member, surface: "app" } }));
253
253
  }
254
- return { list, notice, context, runAsMember, owner, member, guest, outsider, workspace };
254
+ // The same job running one action as a user in a role of the catalog, for installer work.
255
+ async function runInRole(user, role, actionId) {
256
+ const acting = await workspaces.roleContext(
257
+ { workspaceId: workspace.id, userId: user.id, role, reason: "install the workspace's required records" },
258
+ { context: systemContext("install each workspace's required records") }
259
+ );
260
+ return countQueries(knex, () => actions.execute({ actionId, input: { workspaceSlug: workspace.slug }, context: { ...acting, surface: "app" } }));
261
+ }
262
+ return { list, notice, context, runAsMember, runInRole, owner, member, guest, outsider, workspace };
255
263
  }
256
264
 
257
265
  // The statements of one read of the workspace context, whatever the database quotes its names with: the workspace by
@@ -357,3 +365,32 @@ test("a member context lists the member's workspace's rows as the member's reque
357
365
  assert.equal(response.body.includes("ACTION_PERMISSION_DENIED"), true, response.body);
358
366
  await assert.rejects(runAsMember(guest, "crud.issues.list"), (error) => error.status === 403 && error.code === "ACTION_PERMISSION_DENIED");
359
367
  });
368
+
369
+ test("a role context runs an action as a member in that role would, for a user who is no member or a member in another role, and writes nothing", async (t) => {
370
+ const { context, list, runInRole, member, guest, outsider } = await issuesApp(t);
371
+
372
+ // The action sees what a member in that role sees at their own request, with an unsaved membership.
373
+ const request = (await context(member)).response.json();
374
+ for (const user of [outsider, guest]) {
375
+ const { result, queries } = await runInRole(user, "member", ACTION_READ_CONTEXT);
376
+ const seen = JSON.parse(JSON.stringify(result));
377
+ assert.deepEqual(seen.membership, { workspaceId: request.workspace.id, userId: user.id, roleSid: "member", status: "active" });
378
+ assert.equal(seen.actorId, user.id);
379
+ assert.deepEqual(seen.permissions, request.permissions, "the role's permissions");
380
+ assert.deepEqual(seen.workspace, request.workspace);
381
+ assert.deepEqual(seen.visibilityContext, { ...request.visibilityContext, userId: user.id });
382
+ assert.ok(queries.every((sql) => /^select\b/iu.test(sql.trim())), `nothing is written: ${queries.join("\n")}`);
383
+ }
384
+
385
+ // The permission check passes as the role: the member role lists the workspace's issues, which the outsider's and
386
+ // the guest's own requests may not, and the guest role is refused as a guest's request is.
387
+ assert.equal((await list(outsider)).response.statusCode, 403);
388
+ assert.equal((await list(guest)).response.statusCode, 403);
389
+ const memberTitles = (await list(member)).response.json().data.map((record) => record.attributes.title).sort();
390
+ for (const user of [outsider, guest]) {
391
+ const { result, queries } = await runInRole(user, "member", "crud.issues.list");
392
+ assert.deepEqual(jsonApiResultValue(result).data.map((record) => record.attributes.title).sort(), memberTitles);
393
+ assert.ok(queries.every((sql) => /^select\b/iu.test(sql.trim())), `nothing is written: ${queries.join("\n")}`);
394
+ }
395
+ await assert.rejects(runInRole(member, "guest", "crud.issues.list"), (error) => error.status === 403 && error.code === "ACTION_PERMISSION_DENIED");
396
+ });
@@ -84,6 +84,26 @@ test("workspace mutation actions declare their domain and bootstrap changes expl
84
84
  assert.deepEqual(events[0].realtime.payload, { workspaceSlug: "acme" });
85
85
  });
86
86
 
87
+ test("making and changing a workspace are entity changes of the workspace, named by the id the action answers", async () => {
88
+ const context = { actor: { id: 7 }, requestMeta: {} };
89
+ const [create, update] = ["workspace.workspaces.create", "workspace.workspaces.update"]
90
+ .map((id) => workspaceDirectoryActionSpecifications.find((action) => action.id === id));
91
+ assert.deepEqual([create.events.length, update.events.length], [1, 1]);
92
+ const [created] = await Promise.all(create.events.map((builder) => builder({
93
+ input: { name: "Acme" },
94
+ result: returnJsonApiData({ id: "11", slug: "acme", name: "Acme", ownerUserId: "7" }),
95
+ context
96
+ })));
97
+ assert.deepEqual([created.type, created.source, created.entity, created.operation, created.entityId], ["entity.changed", "workspace", "workspace", "created", "11"]);
98
+ assert.equal(created.realtime, undefined);
99
+ const [updated] = await Promise.all(update.events.map((builder) => builder({
100
+ input: { workspaceSlug: "acme", name: "Acme Ltd" },
101
+ result: returnJsonApiData({ id: "11", slug: "acme", name: "Acme Ltd", ownerUserId: "7" }),
102
+ context
103
+ })));
104
+ assert.deepEqual([updated.entity, updated.operation, updated.entityId], ["workspace", "updated", "11"]);
105
+ });
106
+
87
107
  test("workspace invite actions reach the invite's recipient through the members service, once per event", async () => {
88
108
  const lookups = [];
89
109
  const [create, revoke] = ["workspace.invite.create", "workspace.invite.revoke"].map((id) => createWorkspaceMembersActions({