@jskit-ai/workspaces-core 0.2.32 → 0.2.33

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
+ - `GET .../members` and `GET .../invites` (`workspace.members.list` and `workspace.invites.list`) answer a request that leaves out `page[cursor]` or `page[limit]` again, such as every first page the members screen reads (`page[limit]=20`). Since 0.2.25 those answered 400 `ACTION_VALIDATION_FAILED`, "Value could not be cast to the required type." at `/data/attributes/cursor` (and at `/data/attributes/limit` when no limit was named), so the members screen showed no members and no invitations in any workspace. The routes handed their action `cursor` and `limit` by name, undefined when the query left one out, and an action's input refuses a field that is present but undefined; they now hand on only the fields the query sends. A route test reads both lists, first and next pages, through Fastify, the auth policy, the list actions and the JSON:API transport and serializer.
6
+
5
7
  - 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
8
  - 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.
7
9
  - 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`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/workspaces-core",
3
- "version": "0.2.32",
3
+ "version": "0.2.33",
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.212",
27
27
  "@jskit-ai/resource-crud-core": "0.1.214",
28
- "@jskit-ai/users-core": "0.2.32",
28
+ "@jskit-ai/users-core": "0.2.33",
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.",
@@ -15,6 +15,20 @@ import {
15
15
  } from "../common/validators/routeParamsValidator.js";
16
16
  import { resolveDefaultWorkspaceRouteSurfaceIdFromAppConfig } from "../support/workspaceActionSurfaces.js";
17
17
 
18
+ /**
19
+ * A members or invites list request's action input: its workspace, and the cursor and limit its query sends, each only
20
+ * when sent. An action's input refuses a field that is present but undefined, so naming an absent one refused every
21
+ * first page with 400.
22
+ * @param {{ params: { workspaceSlug: string }, query: { cursor?: string, limit?: number } }} input The request's input.
23
+ */
24
+ function listPageActionInput({ params, query }) {
25
+ return {
26
+ workspaceSlug: params.workspaceSlug,
27
+ ...(Object.hasOwn(query, "cursor") ? { cursor: query.cursor } : {}),
28
+ ...(Object.hasOwn(query, "limit") ? { limit: query.limit } : {})
29
+ };
30
+ }
31
+
18
32
  /**
19
33
  * @param {import("@jskit-ai/kernel/server/types").RuntimeRouter} router
20
34
  * @param {{ config: import("@jskit-ai/kernel/server/types").RuntimeConfig, workspaceInvitationsEnabled: boolean }} options
@@ -77,11 +91,7 @@ function registerWorkspaceMembersRoutes(router, { config, workspaceInvitationsEn
77
91
  async function (request, reply) {
78
92
  const response = await request.executeAction({
79
93
  actionId: "workspace.members.list",
80
- input: {
81
- workspaceSlug: request.input.params.workspaceSlug,
82
- cursor: request.input.query.cursor,
83
- limit: request.input.query.limit
84
- }
94
+ input: listPageActionInput(request.input)
85
95
  });
86
96
  reply.code(200).send(response);
87
97
  }
@@ -179,11 +189,7 @@ function registerWorkspaceMembersRoutes(router, { config, workspaceInvitationsEn
179
189
  async function (request, reply) {
180
190
  const response = await request.executeAction({
181
191
  actionId: "workspace.invites.list",
182
- input: {
183
- workspaceSlug: request.input.params.workspaceSlug,
184
- cursor: request.input.query.cursor,
185
- limit: request.input.query.limit
186
- }
192
+ input: listPageActionInput(request.input)
187
193
  });
188
194
  reply.code(200).send(response);
189
195
  }
@@ -0,0 +1,191 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import Fastify from "fastify";
4
+ import { AuthExtensionsProvider } from "@jskit-ai/auth-core/server/providers/AuthExtensionsProvider";
5
+ import { AuthPolicyProvider } from "@jskit-ai/auth-core/server/providers/AuthPolicyProvider";
6
+ import { HttpProvider } from "@jskit-ai/kernel/server/http";
7
+ import { createBootstrapRuntime } from "@jskit-ai/kernel/server/runtime";
8
+ import { createPackageTestKnex, startTestFeatures } from "@jskit-ai/resource-runtime/test";
9
+ import { UsersExtensionsProvider } from "@jskit-ai/users-core/server/UsersExtensionsProvider";
10
+ import { UsersIdentityProvider } from "@jskit-ai/users-core/server/UsersIdentityProvider";
11
+ import { WorkspacesFeature } from "../src/server/WorkspacesFeature.js";
12
+ import { WorkspacesIntegrationsProvider } from "../src/server/WorkspacesIntegrationsProvider.js";
13
+
14
+ // The members and invites lists as the members screen reads them: GET .../members and GET .../invites through
15
+ // Fastify, the auth policy, the routes' query validation, the list actions and the JSON:API serializer. The service
16
+ // tests call the service directly, so a route that handed its action a bad input went unseen: every first page,
17
+ // which names no cursor, answered 400 "Value could not be cast" pointing at /data/attributes/cursor.
18
+
19
+ const config = Object.freeze({
20
+ appPublicUrl: "http://localhost:5173",
21
+ tenancyMode: "workspaces",
22
+ tenancyPolicy: { workspace: { allowSelfCreate: true } },
23
+ workspaceInvitations: { enabled: true },
24
+ workspaceMembers: { defaults: { inviteExpiresInMs: 86400000 } },
25
+ workspaceSettings: { defaults: { invitesEnabled: true } },
26
+ surfaceDefaultId: "app",
27
+ surfaceDefinitions: { app: { id: "app", requiresWorkspace: true, accessPolicyId: "workspace_member" } },
28
+ surfaceAccessPolicies: { workspace_member: { requireWorkspaceMembership: true } },
29
+ roleCatalog: {
30
+ workspace: { defaultInviteRole: "member" },
31
+ roles: {
32
+ owner: { permissions: ["*"] },
33
+ member: { assignable: true, permissions: ["workspace.members.view"] },
34
+ guest: { assignable: true, permissions: [] }
35
+ }
36
+ }
37
+ });
38
+
39
+ // The signed-in user is the profile the test names in a header, as a session would name it.
40
+ const headerAuthService = Object.freeze({
41
+ async authenticateRequest(request) {
42
+ const id = String(request.headers["x-test-user"] || "");
43
+ return id
44
+ ? { authenticated: true, actor: { id, email: `${id}@example.com`, displayName: id }, transientFailure: false }
45
+ : { authenticated: false, actor: null, transientFailure: false };
46
+ }
47
+ });
48
+
49
+ async function membersApp(t) {
50
+ const knex = await createPackageTestKnex(t, { environment: process.env });
51
+ const app = Fastify();
52
+ t.after(() => app.close());
53
+ const started = await startTestFeatures({
54
+ knex,
55
+ createTables: true,
56
+ features: [
57
+ HttpProvider,
58
+ AuthExtensionsProvider,
59
+ AuthPolicyProvider,
60
+ UsersExtensionsProvider,
61
+ UsersIdentityProvider,
62
+ WorkspacesFeature,
63
+ WorkspacesIntegrationsProvider
64
+ ],
65
+ requires: { profiles: "users.profiles", workspaces: "workspaces.core", memberships: "workspaces.memberships" },
66
+ inputs: {
67
+ "auth.service": headerAuthService,
68
+ "runtime.app-root": process.cwd(),
69
+ "runtime.bootstrap": createBootstrapRuntime(),
70
+ "runtime.config": config,
71
+ "runtime.env": {},
72
+ "runtime.fastify": app
73
+ }
74
+ });
75
+ t.after(started.stop);
76
+ const { profiles, workspaces, memberships } = started.capabilities;
77
+ const person = (name) => profiles.upsert({
78
+ authProvider: "local",
79
+ authProviderUserSid: `identity-${name}`,
80
+ email: `${name}@example.com`,
81
+ displayName: name
82
+ });
83
+ const owner = await person("owner");
84
+ const member = await person("member");
85
+ const guest = await person("guest");
86
+ const outsider = await person("outsider");
87
+ const workspace = await workspaces.services.directory.ensurePersonalWorkspaceForUser(owner);
88
+ await workspaces.services.directory.ensurePersonalWorkspaceForUser(outsider);
89
+ await memberships.addMember({ workspaceId: workspace.id, userId: member.id });
90
+ await memberships.addMember({ workspaceId: workspace.id, userId: guest.id, roleSid: "guest" });
91
+ for (const email of ["ivy@example.com", "jon@example.com", "kim@example.com"]) {
92
+ await workspaces.services.members.createInvite(workspace, owner, { email, roleSid: "member" });
93
+ }
94
+
95
+ const get = (user, path, { query = {}, slug = workspace.slug } = {}) => app.inject({
96
+ method: "GET",
97
+ url: `/api/w/${slug}/${path}`,
98
+ query,
99
+ headers: user ? { "x-test-user": user.id } : {}
100
+ });
101
+ return { get, owner, member, guest, outsider, workspace };
102
+ }
103
+
104
+ // A page's query as the JSON:API transport sends it: http-web's useList names its limit (20 unless the screen says
105
+ // otherwise) and, from the second page on, the previous page's nextCursor.
106
+ const page = (limit, cursor) => ({
107
+ query: {
108
+ ...(limit === undefined ? {} : { "page[limit]": String(limit) }),
109
+ ...(cursor === undefined ? {} : { "page[cursor]": cursor })
110
+ }
111
+ });
112
+
113
+ // A list response's attributes, after checking it answered 200 as a workspace record of its JSON:API type.
114
+ function listAttributes(response, type, workspace) {
115
+ assert.equal(response.statusCode, 200, response.body);
116
+ const { data } = response.json();
117
+ assert.equal(data.type, type, response.body);
118
+ assert.equal(data.id, String(workspace.id), response.body);
119
+ return data.attributes;
120
+ }
121
+
122
+ const displayNames = (attributes) => attributes.members.map(({ displayName }) => displayName);
123
+ const inviteEmails = (attributes) => attributes.invites.map(({ email }) => email).sort();
124
+
125
+ test("the members list answers its first page and each next page through its route", async (t) => {
126
+ const { get, owner, member, workspace } = await membersApp(t);
127
+
128
+ // The members screen's first page, and a caller that names no page at all.
129
+ for (const user of [owner, member]) {
130
+ for (const request of [page(20), page()]) {
131
+ const all = listAttributes(await get(user, "members", request), "workspace-members", workspace);
132
+ assert.deepEqual(displayNames(all), ["guest", "member", "owner"]);
133
+ assert.equal(all.nextCursor, null);
134
+ assert.equal(all.workspace.slug, workspace.slug);
135
+ assert.ok(all.roleCatalog.roles.length > 0);
136
+ }
137
+ }
138
+
139
+ const first = listAttributes(await get(owner, "members", page(2)), "workspace-members", workspace);
140
+ assert.deepEqual(displayNames(first), ["guest", "member"]);
141
+ assert.equal(typeof first.nextCursor, "string");
142
+ const last = listAttributes(await get(owner, "members", page(2, first.nextCursor)), "workspace-members", workspace);
143
+ assert.deepEqual(displayNames(last), ["owner"]);
144
+ assert.equal(last.nextCursor, null);
145
+ });
146
+
147
+ test("the invites list answers its first page and each next page through its route", async (t) => {
148
+ const { get, owner, member, workspace } = await membersApp(t);
149
+
150
+ // The members screen's first page, and a caller that names no page at all.
151
+ for (const user of [owner, member]) {
152
+ for (const request of [page(20), page()]) {
153
+ const all = listAttributes(await get(user, "invites", request), "workspace-invites", workspace);
154
+ assert.deepEqual(inviteEmails(all), ["ivy@example.com", "jon@example.com", "kim@example.com"]);
155
+ assert.equal(all.nextCursor, null);
156
+ assert.equal(all.workspace.slug, workspace.slug);
157
+ }
158
+ }
159
+
160
+ const first = listAttributes(await get(owner, "invites", page(2)), "workspace-invites", workspace);
161
+ assert.equal(first.invites.length, 2);
162
+ assert.equal(typeof first.nextCursor, "string");
163
+ const last = listAttributes(await get(owner, "invites", page(2, first.nextCursor)), "workspace-invites", workspace);
164
+ assert.equal(last.invites.length, 1);
165
+ assert.equal(last.nextCursor, null);
166
+ assert.deepEqual([...first.invites, ...last.invites].map(({ email }) => email).sort(),
167
+ ["ivy@example.com", "jon@example.com", "kim@example.com"]);
168
+ });
169
+
170
+ test("the members and invites list routes refuse as strictly as before", async (t) => {
171
+ const { get, owner, guest, outsider } = await membersApp(t);
172
+
173
+ for (const path of ["members", "invites"]) {
174
+ const refusals = [
175
+ ["signed out", await get(null, path, page(20)), 401, "auth.session.required"],
176
+ ["not a member", await get(outsider, path, page(20)), 403, "workspaces.workspace.accessDenied"],
177
+ ["a member without workspace.members.view", await get(guest, path, page(20)), 403, "ACTION_PERMISSION_DENIED"],
178
+ ["an unknown workspace", await get(owner, path, { ...page(20), slug: "no-such-workspace" }), 404,
179
+ "workspaces.workspace.notFound"],
180
+ ["a limit over 100", await get(owner, path, page(101)), 400, "limit"]
181
+ ];
182
+ for (const [label, response, statusCode, text] of refusals) {
183
+ assert.equal(response.statusCode, statusCode, `${path}, ${label}: ${response.body}`);
184
+ assert.equal(response.body.includes(text), true, `${path}, ${label}: ${response.body}`);
185
+ }
186
+ }
187
+ // A cursor the members list never answered, with no limit named.
188
+ const unknownCursor = await get(owner, "members", page(undefined, "not-a-cursor"));
189
+ assert.equal(unknownCursor.statusCode, 400, unknownCursor.body);
190
+ assert.equal(unknownCursor.body.includes("workspaces.member.cursorInvalid"), true, unknownCursor.body);
191
+ });