@jskit-ai/workspaces-core 0.2.58 → 0.2.60

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.
Files changed (49) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/locales/en.json +11 -1
  3. package/migrations/workspaces_core_memberships_accepted_invite.cjs +22 -0
  4. package/migrations/workspaces_core_settings_invites_require_same_email.cjs +20 -0
  5. package/package.json +9 -9
  6. package/patterns/workspace-server/PATTERN.md +26 -6
  7. package/src/server/WorkspacesFeature.js +1 -0
  8. package/src/server/WorkspacesIntegrationsProvider.js +2 -2
  9. package/src/server/common/repositories/workspaceInvitesRepository.js +21 -9
  10. package/src/server/common/repositories/workspaceMemberPagesRepository.js +12 -5
  11. package/src/server/common/repositories/workspaceMembershipsRepository.js +38 -8
  12. package/src/server/common/repositories/workspacesRepository.js +18 -0
  13. package/src/server/common/services/workspaceDirectoryService.js +33 -3
  14. package/src/server/support/workspaceInvitationsPolicy.js +5 -1
  15. package/src/server/types.js +24 -2
  16. package/src/server/workspaceMembers/appEnvironmentInviteMailer.js +26 -2
  17. package/src/server/workspaceMembers/defaultWorkspaceInviteEmail.js +1 -1
  18. package/src/server/workspaceMembers/workspaceMembersService.js +1 -0
  19. package/src/server/workspacePendingInvitations/inviterNotice.js +75 -0
  20. package/src/server/workspacePendingInvitations/workspacePendingInvitationsService.js +130 -26
  21. package/src/server/workspaceSettings/workspaceSettingsRepository.js +16 -4
  22. package/src/server/workspaceSettings/workspaceSettingsService.js +6 -1
  23. package/src/server/workspacesRuntime.js +16 -2
  24. package/src/shared/resources/workspaceMembersResource.js +13 -1
  25. package/src/shared/resources/workspaceMembershipsResource.js +11 -1
  26. package/src/shared/resources/workspacePendingInvitationsResource.js +2 -0
  27. package/src/shared/resources/workspaceSettingsResource.js +24 -2
  28. package/src/shared/tenancyProfile.js +15 -2
  29. package/test/appEnvironmentInviteMailer.test.js +33 -0
  30. package/test/featureRuntime.test.js +9 -1
  31. package/test/inviterNotice.test.js +66 -0
  32. package/test/repositories.integration.test.js +10 -12
  33. package/test/repositoryContracts.test.js +1 -0
  34. package/test/roleLabels.test.js +7 -2
  35. package/test/support/indexesByUserCases.js +2 -8
  36. package/test/support/invitationTransactions.js +14 -4
  37. package/test/support/mysqlWorkspaces.js +8 -9
  38. package/test/support/transferOwnershipCases.js +3 -9
  39. package/test/support/workspacesMigrations.js +23 -0
  40. package/test/tenancyProfile.test.js +16 -0
  41. package/test/workspaceDirectoryService.mysql.test.js +74 -0
  42. package/test/workspaceInvitationsPolicy.test.js +11 -0
  43. package/test/workspaceMemberListRoutes.test.js +9 -2
  44. package/test/workspaceMembersService.mysql.test.js +3 -3
  45. package/test/workspacePendingInvitationsService.mysql.test.js +94 -8
  46. package/test/workspacePendingInvitationsService.test.js +231 -5
  47. package/test/workspaceRecords.test.js +1 -0
  48. package/test/workspaceRecordsFeature.test.js +2 -7
  49. package/test/workspaceSettingsService.test.js +30 -5
@@ -5,7 +5,8 @@ import { deliverMessage, markStagingEmail } from "@jskit-ai/kernel/server/runtim
5
5
  * invitation to its address. Staging sends it only to STAGING_EMAIL_TO, its message showing the address it was for
6
6
  * (`markStagingEmail`). Otherwise, in development, test and staging without STAGING_EMAIL_TO, it logs the
7
7
  * invitation's recipient, subject and link and reports the delivery `simulated`, so the inviter copies the link to
8
- * share it.
8
+ * share it. A mailer that also sends `sendInviteAcceptedByOtherAddress` has that notice sent the same way, to the
9
+ * inviter.
9
10
  * @param {object} dependencies
10
11
  * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} dependencies.env
11
12
  * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
@@ -38,7 +39,30 @@ function createAppEnvironmentInviteMailer({ env, logger, mailer }) {
38
39
  };
39
40
  }
40
41
 
41
- return Object.freeze({ sendWorkspaceInvite });
42
+ // The notice that another address accepted an invitation goes to its inviter the same way, when the provided mailer
43
+ // sends it at all.
44
+ async function sendInviteAcceptedByOtherAddress(notice, options) {
45
+ const delivery = await deliverMessage({
46
+ env,
47
+ logger,
48
+ channel: "email",
49
+ to: notice.inviter.email,
50
+ summary: `the notice to ${notice.inviter.email} that ${notice.member.email} accepted an invitation sent to ${notice.invite.email}`,
51
+ details: { subject: String(notice.message?.subject || "") },
52
+ send: (to, { originalTo }) => mailer.sendInviteAcceptedByOtherAddress(
53
+ { ...notice, inviter: { ...notice.inviter, email: to }, message: markStagingEmail(notice.message, originalTo) },
54
+ options
55
+ )
56
+ });
57
+ return delivery.sent ? delivery.result : { status: "simulated" };
58
+ }
59
+
60
+ // readable-check: allow method-probe - optional operation: sendInviteAcceptedByOtherAddress is an optional workspaces.invite-mailer operation
61
+ const sendsAcceptedNotice = typeof mailer.sendInviteAcceptedByOtherAddress === "function";
62
+ return Object.freeze({
63
+ sendWorkspaceInvite,
64
+ ...(sendsAcceptedNotice ? { sendInviteAcceptedByOtherAddress } : {})
65
+ });
42
66
  }
43
67
 
44
68
  export { createAppEnvironmentInviteMailer };
@@ -80,4 +80,4 @@ function renderDefaultWorkspaceInviteEmail({
80
80
  };
81
81
  }
82
82
 
83
- export { formatInviteExpiry, renderDefaultWorkspaceInviteEmail };
83
+ export { escapeHtml, formatInviteExpiry, renderDefaultWorkspaceInviteEmail };
@@ -105,6 +105,7 @@ function createService({
105
105
  status: normalizeLowerText(member.status || "active") || "active",
106
106
  displayName: normalizeText(member.displayName),
107
107
  email: normalizeLowerText(member.email),
108
+ invitedEmail: normalizeLowerText(member.invitedEmail),
108
109
  isOwner: userId === normalizeRecordId(workspace.ownerUserId, { fallback: "" }) || roleSid === OWNER_ROLE_ID
109
110
  };
110
111
  }
@@ -0,0 +1,75 @@
1
+ import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
2
+ import { escapeHtml } from "../workspaceMembers/defaultWorkspaceInviteEmail.js";
3
+
4
+ const DEFAULT_LOCALE = "en";
5
+
6
+ /**
7
+ * The email telling an inviter that an account with another address accepted their invitation, in their language.
8
+ * @param {{ acceptance: import("../types.js").WorkspaceInviteAcceptance, t: (key: string, params?: object) => string }} input
9
+ */
10
+ function renderInviteAcceptedByOtherAddressEmail({ acceptance, t }) {
11
+ const { invite, user, workspace } = acceptance;
12
+ const params = {
13
+ member: user.displayName || user.email,
14
+ memberEmail: user.email,
15
+ invitedEmail: invite.email,
16
+ workspace: workspace.name || workspace.slug
17
+ };
18
+ const paragraphs = [
19
+ t("jskit.workspaces.inviteAcceptedEmail.body", params),
20
+ t("jskit.workspaces.inviteAcceptedEmail.review", params)
21
+ ];
22
+ return {
23
+ subject: t("jskit.workspaces.inviteAcceptedEmail.subject", params),
24
+ text: paragraphs.join("\n\n"),
25
+ html: paragraphs.map((paragraph) => `<p>${escapeHtml(paragraph)}</p>`).join("\n")
26
+ };
27
+ }
28
+
29
+ /**
30
+ * Tells an invitation's inviter that an account whose email is not the invited address accepted it, through the
31
+ * invite mailer's optional `sendInviteAcceptedByOtherAddress`, once the acceptance committed. Without that method,
32
+ * or without an inviter (one whose account is gone), nothing is sent. The acceptance stands whatever happens here: a
33
+ * failure is logged.
34
+ * @param {object} dependencies
35
+ * @param {import("../types.js").WorkspaceInviteMailer} dependencies.inviteMailer
36
+ * @param {import("@jskit-ai/users-core/server/types").UsersProfiles} dependencies.userProfiles
37
+ * @param {import("@jskit-ai/users-core/server/types").UsersSettings} dependencies.userSettings
38
+ * @param {import("../types.js").WorkspacesServerI18n} dependencies.i18n
39
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
40
+ * @returns {(acceptance: import("../types.js").WorkspaceInviteAcceptance, options?: object) => Promise<void>}
41
+ */
42
+ function createInviterNotice({ inviteMailer, userProfiles, userSettings, i18n, logger }) {
43
+ // readable-check: allow method-probe - optional operation: sendInviteAcceptedByOtherAddress is an optional workspaces.invite-mailer operation
44
+ if (typeof inviteMailer.sendInviteAcceptedByOtherAddress !== "function") {
45
+ return async function notifyNoInviter() {};
46
+ }
47
+
48
+ return async function notifyInviter(acceptance, options = {}) {
49
+ const { invite, user, workspace } = acceptance;
50
+ try {
51
+ const inviter = invite.invitedByUserId ? await userProfiles.findById(invite.invitedByUserId, options) : null;
52
+ if (!inviter?.email) {
53
+ return;
54
+ }
55
+ const settings = await userSettings.findByUserId(inviter.id, options);
56
+ const locale = normalizeText(settings?.locale) || DEFAULT_LOCALE;
57
+ await inviteMailer.sendInviteAcceptedByOtherAddress({
58
+ inviteId: invite.id,
59
+ invite: { id: invite.id, email: invite.email, roleSid: invite.roleSid },
60
+ inviter: { id: inviter.id, email: inviter.email, displayName: normalizeText(inviter.displayName) },
61
+ member: { id: user.id, email: user.email, displayName: user.displayName },
62
+ workspace: { id: workspace.id, slug: workspace.slug, name: workspace.name },
63
+ locale,
64
+ message: renderInviteAcceptedByOtherAddressEmail({ acceptance, t: (key, params) => i18n.t(locale, key, params) })
65
+ }, options);
66
+ } catch (error) {
67
+ logger.warn(
68
+ { error, inviteId: invite.id, workspaceId: workspace.id },
69
+ "The inviter was not told that another address accepted their invitation."
70
+ );
71
+ }
72
+ };
73
+ }
74
+
75
+ export { createInviterNotice, renderInviteAcceptedByOtherAddressEmail };
@@ -8,10 +8,25 @@ import { normalizeLowerText, normalizeRecordId, normalizeText } from "@jskit-ai/
8
8
  * @param {object} dependencies
9
9
  * @param {import("../types.js").WorkspaceInvitesRepository} dependencies.workspaceInvitesRepository
10
10
  * @param {import("../types.js").WorkspaceMembershipsRepository} dependencies.workspaceMembershipsRepository
11
+ * @param {import("../types.js").WorkspacesRepository} dependencies.workspacesRepository
12
+ * @param {import("../types.js").WorkspaceSettingsRepository} dependencies.workspaceSettingsRepository
11
13
  * @param {import("../types.js").WorkspaceRoleCatalog} dependencies.roleCatalog
12
14
  * @param {import("../types.js").WorkspaceInviteAcceptanceParticipant} dependencies.acceptanceParticipant
15
+ * @param {boolean} dependencies.invitationsAnyAccount Whether any signed-in account may accept an invitation
16
+ * (config.workspaceInvitations.anyAccount), unless its workspace requires the invited address.
17
+ * @param {(acceptance: import("../types.js").WorkspaceInviteAcceptance, options: object) => Promise<void>} dependencies.notifyInviter
18
+ * Tells the inviter that another address accepted their invitation, after the acceptance committed.
13
19
  */
14
- function createService({ workspaceInvitesRepository, workspaceMembershipsRepository, roleCatalog, acceptanceParticipant }) {
20
+ function createService({
21
+ workspaceInvitesRepository,
22
+ workspaceMembershipsRepository,
23
+ workspacesRepository,
24
+ workspaceSettingsRepository,
25
+ roleCatalog,
26
+ acceptanceParticipant,
27
+ invitationsAnyAccount,
28
+ notifyInviter
29
+ }) {
15
30
  function roleLabelMetadata(roleSid) {
16
31
  const role = roleCatalog.roles.find((entry) => entry.id === (normalizeLowerText(roleSid || "member") || "member"));
17
32
  const label = typeof role?.label === "string" ? role.label.trim() : "";
@@ -19,10 +34,10 @@ function createService({ workspaceInvitesRepository, workspaceMembershipsReposit
19
34
  }
20
35
 
21
36
  // Acceptance and refusal own their transaction (outermost): related writes belong in the acceptance participant.
22
- async function withInviteTransaction(user, token, options, work) {
37
+ async function withInviteTransaction(user, token, decision, options, work) {
23
38
  // Locate outside the transaction to avoid a stale MySQL repeatable-read
24
39
  // snapshot. The callback validates again under the workspace/invite locks.
25
- const initial = await requirePendingInviteForUserByToken(user, token, options);
40
+ const initial = await requirePendingInviteForUserByToken(user, token, decision, options);
26
41
  // work receives the locking options its repository reads take, and the transaction's own options.
27
42
  const result = await workspaceInvitesRepository.withTransaction({ ...options, outermost: true }, (txOptions) => work({
28
43
  ...txOptions,
@@ -30,13 +45,26 @@ function createService({ workspaceInvitesRepository, workspaceMembershipsReposit
30
45
  workspaceId: initial.invite.workspaceId,
31
46
  inviteId: initial.invite.id
32
47
  }, txOptions));
33
- // Commit expiry revocation before reporting the rejection.
48
+ // Commit the invitation's expiry before reporting the rejection.
34
49
  if (result.expired) {
35
- throw Object.assign(new AppError(409, "Invitation has expired.", { code: "workspaces.invite.expired" }), { transactionOutcome: "committed" });
50
+ throw Object.assign(invitationExpiredError(), { transactionOutcome: "committed" });
36
51
  }
37
52
  return result;
38
53
  }
39
54
 
55
+ function invitationExpiredError() {
56
+ return new AppError(409, "Invitation has expired.", { code: "workspaces.invite.expired" });
57
+ }
58
+
59
+ function sameEmail(left, right) {
60
+ return normalizeLowerText(left) === normalizeLowerText(right);
61
+ }
62
+
63
+ // Whether only the invitation's own address may accept it: always without anyAccount, else as its workspace says.
64
+ async function requiresSameEmail(workspaceId, options) {
65
+ return !invitationsAnyAccount || workspaceSettingsRepository.findInvitesRequireSameEmail(workspaceId, options);
66
+ }
67
+
40
68
  function requireAuthenticatedInviteUser(user) {
41
69
  if (!normalizeRecordId(user?.id, { fallback: null })) {
42
70
  throw new AppError(401, "Authentication required.", { code: "workspaces.auth.required" });
@@ -94,6 +122,7 @@ function createService({ workspaceInvitesRepository, workspaceMembershipsReposit
94
122
  maskedEmail: "",
95
123
  roleSid: "",
96
124
  expiresAt: null,
125
+ requiresSameEmail: true,
97
126
  workspace: {
98
127
  id: "",
99
128
  slug: "",
@@ -112,6 +141,7 @@ function createService({ workspaceInvitesRepository, workspaceMembershipsReposit
112
141
  roleSid: normalizeLowerText(invite.roleSid || "member") || "member",
113
142
  ...roleLabelMetadata(invite.roleSid),
114
143
  expiresAt: invite.expiresAt || null,
144
+ requiresSameEmail: invite.requiresSameEmail,
115
145
  workspace: {
116
146
  id: normalizeRecordId(invite.workspaceId, { fallback: "" }),
117
147
  slug: normalizeText(invite.workspaceSlug),
@@ -144,21 +174,43 @@ function createService({ workspaceInvitesRepository, workspaceMembershipsReposit
144
174
  };
145
175
  }
146
176
 
147
- async function requirePendingInviteForUserByToken(user, token, options = {}) {
177
+ /**
178
+ * The pending invitation the token names and the signed-in user who decides it. None is 404, or 409 expired for an
179
+ * invitation that expired. The invited address decides it; another account only accepts it, only with anyAccount
180
+ * and only where its workspace does not require the invited address (403 otherwise), and only once it confirmed it
181
+ * joins as itself: `acceptAs` is its own email (409 workspaces.invite.differentEmailUnconfirmed otherwise).
182
+ * @param {object} user
183
+ * @param {string} token
184
+ * @param {{ decision: "accept" | "refuse", acceptAs?: string }} decision
185
+ * @param {object} [options]
186
+ */
187
+ async function requirePendingInviteForUserByToken(user, token, { decision, acceptAs }, options = {}) {
148
188
  const actor = requireAuthenticatedInviteUser(user);
149
189
  const tokenHash = requireInviteTokenHash(token);
150
190
 
151
191
  const invite = await workspaceInvitesRepository.findPendingByTokenHash(tokenHash, options);
152
192
  if (!invite) {
193
+ if ((await workspaceInvitesRepository.findByTokenHash(tokenHash, options))?.status === "expired") {
194
+ throw invitationExpiredError();
195
+ }
153
196
  throw new AppError(404, "Invitation not found or already handled.", {
154
197
  code: "workspaces.invite.invitationNotFoundOrHandled"
155
198
  });
156
199
  }
157
200
 
158
- if (normalizeLowerText(invite.email) !== normalizeLowerText(actor.email)) {
159
- throw new AppError(403, "Invitation email does not match authenticated user.", {
160
- code: "workspaces.invite.emailMismatchUser"
161
- });
201
+ if (!sameEmail(invite.email, actor.email)) {
202
+ if (decision !== "accept" || await requiresSameEmail(invite.workspaceId, options)) {
203
+ throw new AppError(403, "Invitation email does not match authenticated user.", {
204
+ code: "workspaces.invite.emailMismatchUser"
205
+ });
206
+ }
207
+ if (!sameEmail(acceptAs, actor.email)) {
208
+ const params = { email: normalizeLowerText(actor.email), maskedEmail: maskInviteEmail(invite.email) };
209
+ throw new AppError(409, `This invitation was sent to ${params.maskedEmail}. Confirm that you want to join as ${params.email}.`, {
210
+ code: "workspaces.invite.differentEmailUnconfirmed",
211
+ params
212
+ });
213
+ }
162
214
  }
163
215
 
164
216
  return {
@@ -188,19 +240,29 @@ function createService({ workspaceInvitesRepository, workspaceMembershipsReposit
188
240
  const tokenHash = requireInviteTokenHash(token);
189
241
  const invite = await workspaceInvitesRepository.findByTokenHashWithWorkspace(tokenHash, options);
190
242
 
191
- return mapResolvedInvite(invite, token);
243
+ return mapResolvedInvite(
244
+ invite && { ...invite, requiresSameEmail: await requiresSameEmail(invite.workspaceId, options) },
245
+ token
246
+ );
192
247
  }
193
248
 
194
249
  async function resolveInviteByToken(token, options = {}) {
195
250
  return returnJsonApiData(await findInviteByToken(token, options));
196
251
  }
197
252
 
253
+ /**
254
+ * The invitation a registration or a sign-in carries, for the auth provider: refused when it is not pending, and
255
+ * when it was sent to another address unless any account may accept it there. Its `email` is always the
256
+ * invitation's own, so an account registering with another address still confirms it.
257
+ * @param {{ token: string, email: string }} invitation
258
+ * @param {object} [options]
259
+ */
198
260
  async function resolveInviteContextForAuth({ token, email }, options = {}) {
199
261
  const resolved = await findInviteByToken(token, options);
200
262
  if (resolved.status !== "pending") {
201
263
  throw new AppError(409, "Invitation is not available.", { code: "workspaces.invite.notAvailable" });
202
264
  }
203
- if (normalizeLowerText(resolved.email) !== normalizeLowerText(email)) {
265
+ if (!sameEmail(resolved.email, email) && resolved.requiresSameEmail) {
204
266
  throw new AppError(403, "Invitation email does not match account email.", {
205
267
  code: "workspaces.invite.emailMismatchAccount"
206
268
  });
@@ -225,10 +287,10 @@ function createService({ workspaceInvitesRepository, workspaceMembershipsReposit
225
287
  return workspaceId;
226
288
  }
227
289
 
228
- async function resolveInviteActionInput(user, token, options, methodName) {
229
- const resolvedInvite = await requirePendingInviteForUserByToken(user, token, options);
290
+ async function resolveInviteActionInput(user, token, decision, options, methodName) {
291
+ const resolvedInvite = await requirePendingInviteForUserByToken(user, token, decision, options);
230
292
  if (resolvedInvite.invite.expiresAt && new Date(resolvedInvite.invite.expiresAt).getTime() < Date.now()) {
231
- await workspaceInvitesRepository.revokeById(resolvedInvite.invite.id, options);
293
+ await workspaceInvitesRepository.markExpiredById(resolvedInvite.invite.id, options);
232
294
  return { expired: true };
233
295
  }
234
296
 
@@ -238,11 +300,47 @@ function createService({ workspaceInvitesRepository, workspaceMembershipsReposit
238
300
  };
239
301
  }
240
302
 
241
- async function acceptInviteByToken({ user, token }, options = {}) {
242
- return withInviteTransaction(user, token, options, async (transactionOptions, txOptions) => {
303
+ // What an acceptance tells its participant and, when another address accepted, the inviter: the invitation and the
304
+ // user as read (the fields named here always), and the workspace they join.
305
+ function describeAcceptance(invite, user, workspace) {
306
+ return Object.freeze({
307
+ invite: Object.freeze({
308
+ ...invite,
309
+ id: normalizeRecordId(invite.id, { fallback: "" }),
310
+ email: normalizeLowerText(invite.email),
311
+ workspaceId: normalizeRecordId(invite.workspaceId, { fallback: "" }),
312
+ invitedByUserId: normalizeRecordId(invite.invitedByUserId, { fallback: null }),
313
+ roleSid: normalizeLowerText(invite.roleSid || "member") || "member"
314
+ }),
315
+ user: Object.freeze({
316
+ ...user,
317
+ id: normalizeRecordId(user.id, { fallback: "" }),
318
+ email: normalizeLowerText(user.email),
319
+ displayName: normalizeText(user.displayName)
320
+ }),
321
+ workspace: Object.freeze({
322
+ id: normalizeRecordId(workspace.id, { fallback: "" }),
323
+ slug: normalizeText(workspace.slug),
324
+ name: normalizeText(workspace.name || workspace.slug),
325
+ ownerUserId: normalizeRecordId(workspace.ownerUserId, { fallback: "" })
326
+ })
327
+ });
328
+ }
329
+
330
+ /**
331
+ * Accepts the invitation the token names for the signed-in user, in one transaction of its own: the membership,
332
+ * the acceptance participant's writes and the invitation's state commit or roll back together. When the user's
333
+ * email is not the invited one (see requirePendingInviteForUserByToken), the inviter is told once it committed.
334
+ * @param {{ user: object, token: string, acceptAs?: string }} input
335
+ * @param {object} [options]
336
+ */
337
+ async function acceptInviteByToken({ user, token, acceptAs }, options = {}) {
338
+ const decision = { decision: "accept", acceptAs };
339
+ const accepted = await withInviteTransaction(user, token, decision, options, async (transactionOptions, txOptions) => {
243
340
  const resolved = await resolveInviteActionInput(
244
341
  user,
245
342
  token,
343
+ decision,
246
344
  transactionOptions,
247
345
  "workspacePendingInvitationsService.acceptInviteByToken"
248
346
  );
@@ -253,24 +351,30 @@ function createService({ workspaceInvitesRepository, workspaceMembershipsReposit
253
351
  await workspaceMembershipsRepository.upsertMembership(
254
352
  workspaceId,
255
353
  resolvedInvite.user.id,
256
- { roleSid: resolvedInvite.invite.roleSid, status: "active" },
354
+ { roleSid: resolvedInvite.invite.roleSid, status: "active", acceptedInviteId: resolvedInvite.invite.id },
257
355
  transactionOptions
258
356
  );
357
+ const workspace = await workspacesRepository.findById(workspaceId, txOptions);
358
+ const acceptance = describeAcceptance(resolvedInvite.invite, resolvedInvite.user, workspace);
259
359
  // Repository locking options stay internal to this service: the participant gets the transaction's own options.
260
- await acceptanceParticipant({
261
- invite: Object.freeze({ ...resolvedInvite.invite }),
262
- user: Object.freeze({ ...resolvedInvite.user })
263
- }, txOptions);
360
+ await acceptanceParticipant(acceptance, txOptions);
264
361
  await workspaceInvitesRepository.markAcceptedById(resolvedInvite.invite.id, transactionOptions);
265
- return { decision: "accepted", workspaceId };
362
+ return { decision: "accepted", workspaceId, acceptance };
266
363
  });
364
+ const { acceptance, ...answer } = accepted;
365
+ if (acceptance.invite.email !== acceptance.user.email) {
366
+ await notifyInviter(acceptance, options);
367
+ }
368
+ return answer;
267
369
  }
268
370
 
269
371
  async function refuseInviteByToken({ user, token }, options = {}) {
270
- return withInviteTransaction(user, token, options, async (transactionOptions) => {
372
+ const decision = { decision: "refuse" };
373
+ return withInviteTransaction(user, token, decision, options, async (transactionOptions) => {
271
374
  const resolved = await resolveInviteActionInput(
272
375
  user,
273
376
  token,
377
+ decision,
274
378
  transactionOptions,
275
379
  "workspacePendingInvitationsService.refuseInviteByToken"
276
380
  );
@@ -284,9 +388,9 @@ function createService({ workspaceInvitesRepository, workspaceMembershipsReposit
284
388
  }
285
389
 
286
390
  // Accepts the invitation a token names when the user decided "accept", and refuses it otherwise.
287
- async function redeemInviteByToken(user, { token, decision }, options = {}) {
391
+ async function redeemInviteByToken(user, { token, decision, acceptAs }, options = {}) {
288
392
  return returnJsonApiData(decision === "accept"
289
- ? await acceptInviteByToken({ user, token }, options)
393
+ ? await acceptInviteByToken({ user, token, acceptAs }, options)
290
394
  : await refuseInviteByToken({ user, token }, options));
291
395
  }
292
396
 
@@ -4,7 +4,7 @@ import { normalizeRecordId } from "@jskit-ai/kernel/shared/support/normalize";
4
4
  import { WORKSPACE_SETTINGS_FIELD_KEYS } from "../../shared/resources/workspaceSettingsResource.js";
5
5
  import { resolveWorkspaceThemePalettes } from "../../shared/settings.js";
6
6
 
7
- function buildDefaultWorkspaceSettingsCreatePayload(workspaceId, defaultInvitesEnabled, defaultColorSettings) {
7
+ function buildDefaultWorkspaceSettingsCreatePayload(workspaceId, { defaultInvitesEnabled, defaultInvitesRequireSameEmail, defaultColorSettings }) {
8
8
  const palettes = resolveWorkspaceThemePalettes(defaultColorSettings);
9
9
 
10
10
  return {
@@ -17,7 +17,8 @@ function buildDefaultWorkspaceSettingsCreatePayload(workspaceId, defaultInvitesE
17
17
  darkSecondaryColor: palettes.dark.secondaryColor,
18
18
  darkSurfaceColor: palettes.dark.surfaceColor,
19
19
  darkSurfaceVariantColor: palettes.dark.surfaceVariantColor,
20
- invitesEnabled: defaultInvitesEnabled
20
+ invitesEnabled: defaultInvitesEnabled,
21
+ invitesRequireSameEmail: defaultInvitesRequireSameEmail
21
22
  };
22
23
  }
23
24
 
@@ -29,9 +30,12 @@ function buildDefaultWorkspaceSettingsCreatePayload(workspaceId, defaultInvitesE
29
30
  * @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} dependencies.workspaceSettings
30
31
  * The workspace_settings table's handle.
31
32
  * @param {boolean} dependencies.defaultInvitesEnabled
33
+ * @param {boolean} dependencies.defaultInvitesRequireSameEmail
32
34
  * @param {object} dependencies.defaultColorSettings The configured colors that replace the theme's.
33
35
  */
34
- function createRepository({ workspaceSettings, defaultInvitesEnabled, defaultColorSettings }) {
36
+ function createRepository({ workspaceSettings, defaultInvitesEnabled, defaultInvitesRequireSameEmail, defaultColorSettings }) {
37
+ const defaults = { defaultInvitesEnabled, defaultInvitesRequireSameEmail, defaultColorSettings };
38
+
35
39
  async function findByWorkspaceId(workspaceId, options = {}) {
36
40
  const normalizedWorkspaceId = normalizeRecordId(workspaceId, { fallback: null });
37
41
  if (!normalizedWorkspaceId) {
@@ -55,7 +59,7 @@ function createRepository({ workspaceSettings, defaultInvitesEnabled, defaultCol
55
59
 
56
60
  try {
57
61
  await workspaceSettings.create(
58
- buildDefaultWorkspaceSettingsCreatePayload(normalizedWorkspaceId, defaultInvitesEnabled, defaultColorSettings),
62
+ buildDefaultWorkspaceSettingsCreatePayload(normalizedWorkspaceId, defaults),
59
63
  { ...options, returning: "none" }
60
64
  );
61
65
  } catch (error) {
@@ -68,6 +72,13 @@ function createRepository({ workspaceSettings, defaultInvitesEnabled, defaultCol
68
72
  return findByWorkspaceId(normalizedWorkspaceId, options);
69
73
  }
70
74
 
75
+ // Whether only an invitation's own address may accept the workspace's invitations: its setting, or the app's default
76
+ // while it has no settings yet. It reads them without making them.
77
+ async function findInvitesRequireSameEmail(workspaceId, options = {}) {
78
+ const settings = await findByWorkspaceId(workspaceId, options);
79
+ return settings ? settings.invitesRequireSameEmail === true : defaultInvitesRequireSameEmail;
80
+ }
81
+
71
82
  async function updateSettingsByWorkspaceId(workspaceId, patch, options = {}) {
72
83
  const normalizedWorkspaceId = normalizeRecordId(workspaceId, { fallback: null });
73
84
  if (!normalizedWorkspaceId) {
@@ -98,6 +109,7 @@ function createRepository({ workspaceSettings, defaultInvitesEnabled, defaultCol
98
109
  withTransaction: workspaceSettings.withTransaction,
99
110
  findByWorkspaceId,
100
111
  ensureForWorkspaceId,
112
+ findInvitesRequireSameEmail,
101
113
  updateSettingsByWorkspaceId
102
114
  });
103
115
  }
@@ -8,9 +8,11 @@ import { cloneWorkspaceRoleCatalog } from "../../shared/roles.js";
8
8
  * @param {object} dependencies
9
9
  * @param {import("../types.js").WorkspaceSettingsRepository} dependencies.workspaceSettingsRepository
10
10
  * @param {boolean} dependencies.workspaceInvitationsEnabled
11
+ * @param {boolean} dependencies.workspaceInvitationsAnyAccount Whether a workspace may let any account accept its
12
+ * invitations (config.workspaceInvitations.anyAccount).
11
13
  * @param {import("../types.js").WorkspaceRoleCatalog} dependencies.roleCatalog
12
14
  */
13
- function createService({ workspaceSettingsRepository, workspaceInvitationsEnabled, roleCatalog }) {
15
+ function createService({ workspaceSettingsRepository, workspaceInvitationsEnabled, workspaceInvitationsAnyAccount, roleCatalog }) {
14
16
  async function readWorkspaceSettings(workspace, options = {}) {
15
17
  const settingsRecord = await workspaceSettingsRepository.ensureForWorkspaceId(workspace.id, {
16
18
  ...options,
@@ -24,6 +26,9 @@ function createService({ workspaceSettingsRepository, workspaceInvitationsEnable
24
26
  settings.invitesEnabled = invitesEnabled;
25
27
  settings.invitesAvailable = workspaceInvitationsEnabled;
26
28
  settings.invitesEffective = invitesEnabled;
29
+ // Without anyAccount only the invited address accepts, whatever the workspace saved.
30
+ settings.invitesRequireSameEmail = !workspaceInvitationsAnyAccount || settings.invitesRequireSameEmail === true;
31
+ settings.invitesAnyAccountAvailable = workspaceInvitationsAnyAccount;
27
32
 
28
33
  return {
29
34
  workspace: {
@@ -14,6 +14,7 @@ import { createWorkspaceMemberContexts } from "./common/services/workspaceMember
14
14
  import { createWorkspacesServerI18n } from "./i18n.js";
15
15
  import { createWorkspaceInviteUrlBuilder } from "./workspaceMembers/workspaceInviteUrls.js";
16
16
  import { createService as createWorkspaceMembersService } from "./workspaceMembers/workspaceMembersService.js";
17
+ import { createInviterNotice } from "./workspacePendingInvitations/inviterNotice.js";
17
18
  import { createService as createWorkspacePendingInvitationsService } from "./workspacePendingInvitations/workspacePendingInvitationsService.js";
18
19
  import { createRepository as createWorkspaceSettingsRepository } from "./workspaceSettings/workspaceSettingsRepository.js";
19
20
  import { createService as createWorkspaceSettingsService } from "./workspaceSettings/workspaceSettingsService.js";
@@ -101,6 +102,10 @@ function createWorkspaceDirectory({
101
102
  config?.workspaceSettings?.defaults?.invitesEnabled,
102
103
  "runtime.config.workspaceSettings.defaults.invitesEnabled"
103
104
  ),
105
+ defaultInvitesRequireSameEmail: requireBoolean(
106
+ config?.workspaceSettings?.defaults?.invitesRequireSameEmail ?? false,
107
+ "runtime.config.workspaceSettings.defaults.invitesRequireSameEmail"
108
+ ),
104
109
  defaultColorSettings: requireWorkspaceColorDefaults(config?.workspaceSettings?.defaults)
105
110
  });
106
111
  const workspaceService = createWorkspaceService({
@@ -133,6 +138,7 @@ function createWorkspaceDirectory({
133
138
  * @param {import("./types.js").WorkspaceInviteMailer} dependencies.inviteMailer
134
139
  * @param {import("./types.js").WorkspaceInviteEmailTemplate} dependencies.inviteEmailTemplate
135
140
  * @param {import("./types.js").WorkspaceInviteAcceptanceParticipant} dependencies.inviteAcceptanceParticipant
141
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
136
142
  * @param {import("./types.js").PersonalWorkspaceName} dependencies.personalWorkspaceName
137
143
  * @param {import("./types.js").WorkspacesResources} dependencies.resources The handles of the tables `workspaces.core` owns.
138
144
  * @param {import("@jskit-ai/users-core/server/types").UsersProfiles} dependencies.userProfiles
@@ -148,6 +154,7 @@ function createWorkspacesRuntime({
148
154
  inviteMailer,
149
155
  inviteEmailTemplate,
150
156
  inviteAcceptanceParticipant,
157
+ logger,
151
158
  personalWorkspaceName,
152
159
  resources,
153
160
  userProfiles,
@@ -168,6 +175,7 @@ function createWorkspacesRuntime({
168
175
  const { tenancyProfile, roleCatalog, workspaceSettingsRepository, workspaceService } = directory;
169
176
  const invitationsPolicy = resolveWorkspaceInvitationsPolicy({ appConfig: config, tenancyProfile });
170
177
  const invitationsEnabled = invitationsPolicy.enabled === true;
178
+ const i18n = createWorkspacesServerI18n({ appRoot });
171
179
  const workspaceInvitesRepository = createWorkspaceInvitesRepository({
172
180
  workspaceInvites: resources.workspaceInvites,
173
181
  workspaces: workspacesRepository
@@ -175,13 +183,18 @@ function createWorkspacesRuntime({
175
183
  const workspacePendingInvitationsService = createWorkspacePendingInvitationsService({
176
184
  workspaceInvitesRepository,
177
185
  workspaceMembershipsRepository,
186
+ workspacesRepository,
187
+ workspaceSettingsRepository,
178
188
  roleCatalog,
179
- acceptanceParticipant: inviteAcceptanceParticipant
189
+ acceptanceParticipant: inviteAcceptanceParticipant,
190
+ invitationsAnyAccount: invitationsPolicy.anyAccount,
191
+ notifyInviter: createInviterNotice({ inviteMailer, userProfiles, userSettings, i18n, logger })
180
192
  });
181
193
  const workspaceMembersService = createWorkspaceMembersService({
182
194
  workspaceMembershipsRepository,
183
195
  workspaceMemberPagesRepository: createWorkspaceMemberPagesRepository({
184
196
  workspaceMemberships: resources.workspaceMemberships,
197
+ workspaceInvites: resources.workspaceInvites,
185
198
  userProfiles
186
199
  }),
187
200
  workspaceInvitesRepository,
@@ -194,13 +207,14 @@ function createWorkspacesRuntime({
194
207
  inviteUrlBuilder: createWorkspaceInviteUrlBuilder({ appConfig: config, env }),
195
208
  workspaceInviteMailer: inviteMailer,
196
209
  workspaceInviteEmailTemplate: inviteEmailTemplate,
197
- i18n: createWorkspacesServerI18n({ appRoot }),
210
+ i18n,
198
211
  userProfilesRepository: userProfiles,
199
212
  userSettingsRepository: userSettings
200
213
  });
201
214
  const workspaceSettingsService = createWorkspaceSettingsService({
202
215
  workspaceSettingsRepository,
203
216
  workspaceInvitationsEnabled: invitationsEnabled,
217
+ workspaceInvitationsAnyAccount: invitationsPolicy.anyAccount,
204
218
  roleCatalog
205
219
  });
206
220
 
@@ -10,7 +10,8 @@ const WORKSPACE_MEMBERS_FIELD_MESSAGES = deepFreeze({
10
10
  inviteTokenRequired: { code: "workspaces.invite.tokenRequired", message: "Invite token is required." },
11
11
  inviteTokenInvalid: { code: "workspaces.invite.tokenInvalid", message: "Invite token is invalid." },
12
12
  decisionRequired: { code: "workspaces.invite.decisionRequired", message: "Decision is required." },
13
- decisionInvalid: { code: "workspaces.invite.decisionInvalid", message: "Decision must be accept or refuse." }
13
+ decisionInvalid: { code: "workspaces.invite.decisionInvalid", message: "Decision must be accept or refuse." },
14
+ acceptAsInvalid: { code: "workspaces.invite.acceptAsInvalid", message: "acceptAs must be the signed-in account's email address." }
14
15
  });
15
16
 
16
17
  const workspaceSummaryOutputSchema = createSchema({
@@ -27,6 +28,8 @@ const memberSummaryOutputSchema = createSchema({
27
28
  status: { type: "string", required: true, minLength: 1, maxLength: 64 },
28
29
  displayName: { type: "string", required: true },
29
30
  email: { type: "string", required: true, minLength: 1, maxLength: 255 },
31
+ // The address of the invitation the member joined through, when it is not their account's email; else "".
32
+ invitedEmail: { type: "string", required: true, maxLength: 255 },
30
33
  isOwner: { type: "boolean", required: true }
31
34
  });
32
35
 
@@ -217,6 +220,15 @@ const redeemInviteBodySchema = createSchema({
217
220
  required: WORKSPACE_MEMBERS_FIELD_MESSAGES.decisionRequired,
218
221
  default: WORKSPACE_MEMBERS_FIELD_MESSAGES.decisionInvalid
219
222
  }
223
+ },
224
+ // The email of the account the person agreed to join as, when the invitation was sent to another address.
225
+ acceptAs: {
226
+ type: "string",
227
+ required: false,
228
+ maxLength: 255,
229
+ messages: {
230
+ default: WORKSPACE_MEMBERS_FIELD_MESSAGES.acceptAsInvalid
231
+ }
220
232
  }
221
233
  });
222
234
 
@@ -9,7 +9,8 @@ const workspaceMembershipsResource = defineTableResource({
9
9
  ownership: "public",
10
10
  foreignKeys: [
11
11
  { columns: ["workspaceId"], referencedTableName: "workspaces" },
12
- { columns: ["userId"], referencedTableName: "users" }
12
+ { columns: ["userId"], referencedTableName: "users" },
13
+ { columns: ["acceptedInviteId"], referencedTableName: "workspace_invites" }
13
14
  ],
14
15
  searchSchema: {
15
16
  workspace: { type: "id", actualField: "workspace_id", filterOperator: "=" },
@@ -52,6 +53,15 @@ const workspaceMembershipsResource = defineTableResource({
52
53
  search: true,
53
54
  setter: (value) => normalizeLowerText(value)
54
55
  },
56
+ // The invitation the member last joined through: its address is the member's invitedEmail when it is not their
57
+ // account's. Null for an owner's membership, one an application added, and one older than the column.
58
+ acceptedInviteId: {
59
+ type: "id",
60
+ nullable: true,
61
+ belongsTo: "workspaceInvites",
62
+ as: "acceptedInvite",
63
+ storage: { column: "accepted_invite_id" }
64
+ },
55
65
  createdAt: {
56
66
  type: "dateTime",
57
67
  storage: {
@@ -43,6 +43,8 @@ const invitationResolveOutputSchema = createSchema({
43
43
  roleSid: { type: "string", required: true },
44
44
  roleLabel: { type: "string", required: false },
45
45
  expiresAt: { type: "string", required: false, nullable: true, minLength: 1 },
46
+ // False when any signed-in account may accept the invitation, confirming first when its email is another.
47
+ requiresSameEmail: { type: "boolean", required: true },
46
48
  workspace: {
47
49
  type: "object",
48
50
  required: true,