@jskit-ai/workspaces-core 0.2.58 → 0.2.59

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
package/CHANGELOG.md CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - `config.workspaceInvitations.anyAccount` (default `false`, which keeps today's rule): with it on, any signed-in account holding an invitation's link may accept it. The invited address, in any letter case, accepts as before. Another address must confirm: the redeem request's new `acceptAs` attribute names the signed-in account's email; without it, or with another value, redeeming answers 409 `workspaces.invite.differentEmailUnconfirmed` ("This invitation was sent to {maskedEmail}. Confirm that you want to join as {email}.", `params.email` the account's address, `params.maskedEmail` the invited one) and changes nothing. A workspace whose new `invitesRequireSameEmail` setting is on still refuses another address with 403 `workspaces.invite.emailMismatchUser`, and refusing stays the invited address's alone. `GET /api/workspace/invitations/resolve` answers `requiresSameEmail`, and the invitation context resolver gives a registration or a provider sign-in from the link the invitation whatever the account's address unless its workspace requires the invited one, carrying the invitation's own email.
6
+ - The workspace setting `invitesRequireSameEmail` (the new migration `workspaces_core_settings_invites_require_same_email`, a `workspace_settings.invites_require_same_email` boolean, NOT NULL, default false; run `npm run db:migrate`), new workspaces' default from `config.workspaceSettings.defaults.invitesRequireSameEmail` (false when unset), written through `PATCH /api/w/:workspaceSlug/settings` under `workspace.settings.update` and optional in every settings write. Reads answer the effective value, true whenever `anyAccount` is off, and `invitesAnyAccountAvailable`.
7
+ - Members show the address they were invited at: every member summary (`listActiveByWorkspaceId`, `findActiveByWorkspaceIdAndUserId`, `listMembers`, `listMembersPage`, `getMember`, `GET .../members`) answers `invitedEmail`, the address of the invitation the member last joined through when it is not their account's email, else `""`. The membership keeps a reference to that invitation (the new migration `workspaces_core_memberships_accepted_invite`, a nullable `workspace_memberships.accepted_invite_id` foreign key to `workspace_invites`, set null when the invitation is deleted; run `npm run db:migrate`), written at each acceptance, so a later acceptance with the account's own address clears it. The members page reads it in its one statement; a summary through the memberships handle reads the invitations in one more batched read.
8
+ - `tenancyPolicy.workspace.autoProvision` takes `"unless-member"`: sign-in provisioning makes a personal workspace only for someone who is an active member of no workspace and whose sign-in carries no invitation naming a workspace (a registration's, or a provider sign-in started from one); an invitation the resolver refused counts as none. Any other value than `true`, `false` and `"unless-member"` stops startup. Profile sync's `afterIdentityProfileSynced` contributor receives the sign-in's `invitation` and passes it on as `ensureProvisionedWorkspaceForAuthenticatedUser(user, options, { invitation })`. `workspaces.memberships` gains `hasActiveMembership(userId, options)`, which reads at most one membership.
9
+ - The acceptance participant (`workspaces.invite-acceptance-participant`) receives `{ invite, user, workspace }`, `workspace` being `{ id, slug, name, ownerUserId }` read inside the acceptance's transaction, each shallow frozen; it still runs after the membership is written and its failure rolls the acceptance back. After an acceptance by another address commits, the invite mailer's optional `sendInviteAcceptedByOtherAddress({ inviteId, invite, inviter, member, workspace, locale, message }, options)` tells the inviter (`jskit.workspaces.inviteAcceptedEmail.*`, in the inviter's saved locale; the application environment's delivery rules apply). A mailer without it sends nothing, and a failure is logged and never undoes the acceptance.
10
+ - **Behaviour change:** an expired invitation stays `expired`. Redeeming one marks it `expired` (it was marked `revoked`) and commits that before answering 409 `workspaces.invite.expired`; from then on it resolves as `expired` and every later accept or refuse answers the same 409 (they answered 404), as does an invitation a newer one to the same address replaced. `revoked` means only that the workspace withdrew it.
11
+ - `workspaces.core`'s `services.directory.deleteWorkspace(workspaceId, options)` deletes a workspace in the caller's transaction when given one: the database's cascades take its memberships, settings and invitations, and an application table whose `workspace_id` has no cascade refuses the delete. It answers `false` for a missing workspace and `true` otherwise, and publishes no event, calls no participant and checks no permission, as `transferOwnership` does.
5
12
  - **Behaviour change:** a workspace the signed-in person is no active member of (never one, removed, inactive, or no user at all) is answered as one that doesn't exist: 404 `workspaces.workspace.notFound` ("Workspace not found."), where it was 403 `workspaces.workspace.accessDenied` ("You do not have access to this workspace."), on every route whose surface requires membership, in the bootstrap's `requestedWorkspace` (`status: "not_found"`, where it was `"forbidden"`) and from `memberContext`. Someone outside a workspace could tell an existing workspace's slug from a typo by the answer; now the two answers are identical. `workspaces.workspace.accessDenied` is gone from the catalog. A surface with `requireWorkspaceMembership: false` still resolves the workspace for a non-member, and a member without a route's permission is still 403.
6
13
  - `workspaces_core_initial-collation`, a migration Knex runs just before `workspaces_core_initial` (run `npm run db:migrate`): on MySQL and MariaDB it creates the workspace tables, where they do not exist yet, in the collation of the existing tables (`workspaces`, then `users`, then `auth_local_users`) rather than the database's default, and converts one recorded in another collation when no character can be lost. It changes nothing where they match.
7
14
  - `workspaces.transferOwnership({ workspaceId, toUserId, previousOwnerRoleSid = "admin" }, options)` hands a workspace to another of its active members, in the caller's transaction when `options` carries one and in one of its own otherwise. It locks the workspace's row and reads the workspace through that lock, then locks the new and the previous owner's memberships in one locking read, so two transfers of one workspace take turns and the second moves it on from the owner the first left. `owner_user_id` becomes `toUserId` and `updatedAt` moves; the new owner's membership takes the `owner` role; the previous owner's takes `previousOwnerRoleSid` and stays active, or is created active with it when they had none. A personal workspace stops being personal (`is_personal` false): the new owner's own personal workspace stays theirs, and where personal workspaces are provisioned the previous owner is given a new one at their next provisioning. A `toUserId` who already owns it writes nothing and answers `changed: false`. A missing or deleted workspace is 404 `workspaces.workspace.notFound` and a `toUserId` with no active membership 409 `workspaces.member.newOwnerNotActive` (new, "The new owner must be an active member of the workspace."), with nothing written; ids that are no record ids and a `previousOwnerRoleSid` that is not the text of a role other than `owner` are a TypeError before any statement. It answers the workspace as `findById` answers it, plus `previousOwnerUserId` and `changed`, sends the same statements however many members the workspace has, and publishes no event: an application keeping its own copy of workspace facts updates it from the answer.
package/locales/en.json CHANGED
@@ -41,7 +41,9 @@
41
41
  "simulated": "Outside production the invitation email was logged, not sent. Copy the invite link to share it.",
42
42
  "sendFailed": "Unable to send workspace invite email.",
43
43
  "decisionRequired": "Decision is required.",
44
- "decisionInvalid": "Decision must be accept or refuse."
44
+ "decisionInvalid": "Decision must be accept or refuse.",
45
+ "acceptAsInvalid": "acceptAs must be the signed-in account's email address.",
46
+ "differentEmailUnconfirmed": "This invitation was sent to {maskedEmail}. Confirm that you want to join as {email}."
45
47
  },
46
48
  "inviteEmail": {
47
49
  "subject": "You're invited to {workspace}",
@@ -52,6 +54,11 @@
52
54
  "accept": "Accept invitation",
53
55
  "workspaceFallback": "the workspace"
54
56
  },
57
+ "inviteAcceptedEmail": {
58
+ "subject": "{member} joined {workspace}",
59
+ "body": "{member} accepted your invitation to {workspace}, which you sent to {invitedEmail}. They joined with their account {memberEmail}.",
60
+ "review": "If you did not expect this, remove them from the workspace's members."
61
+ },
55
62
  "feedback": {
56
63
  "validationFailed": "Validation failed.",
57
64
  "workspaceInvalid": "Fix invalid workspace values and try again.",
@@ -97,6 +104,9 @@
97
104
  "invitesEnabled": {
98
105
  "required": "invitesEnabled is required.",
99
106
  "invalid": "invitesEnabled must be a boolean."
107
+ },
108
+ "invitesRequireSameEmail": {
109
+ "invalid": "invitesRequireSameEmail must be a boolean."
100
110
  }
101
111
  }
102
112
  }
@@ -0,0 +1,22 @@
1
+ // The invitation a membership was last accepted through, whose address the members list shows when it is not the
2
+ // member's account's. Null for an owner's membership, one an application added, and every membership made before it.
3
+ // The invitation's row goes with its workspace, and the reference is cleared then.
4
+ const MEMBERSHIPS_TABLE = "workspace_memberships";
5
+ const COLUMN_NAME = "accepted_invite_id";
6
+
7
+ exports.up = async function up(knex) {
8
+ if (!(await knex.schema.hasColumn(MEMBERSHIPS_TABLE, COLUMN_NAME))) {
9
+ await knex.schema.alterTable(MEMBERSHIPS_TABLE, (table) => {
10
+ table.bigInteger(COLUMN_NAME).unsigned().nullable().references("id").inTable("workspace_invites").onDelete("SET NULL");
11
+ });
12
+ }
13
+ };
14
+
15
+ exports.down = async function down(knex) {
16
+ if (await knex.schema.hasColumn(MEMBERSHIPS_TABLE, COLUMN_NAME)) {
17
+ await knex.schema.alterTable(MEMBERSHIPS_TABLE, (table) => {
18
+ table.dropForeign([COLUMN_NAME]);
19
+ table.dropColumn(COLUMN_NAME);
20
+ });
21
+ }
22
+ };
@@ -0,0 +1,20 @@
1
+ // Whether only an invitation's own address may accept the workspace's invitations, where the application lets any
2
+ // account accept them (config.workspaceInvitations.anyAccount). Every existing workspace starts without the rule.
3
+ const WORKSPACE_SETTINGS_TABLE = "workspace_settings";
4
+ const COLUMN_NAME = "invites_require_same_email";
5
+
6
+ exports.up = async function up(knex) {
7
+ if (!(await knex.schema.hasColumn(WORKSPACE_SETTINGS_TABLE, COLUMN_NAME))) {
8
+ await knex.schema.alterTable(WORKSPACE_SETTINGS_TABLE, (table) => {
9
+ table.boolean(COLUMN_NAME).notNullable().defaultTo(false);
10
+ });
11
+ }
12
+ };
13
+
14
+ exports.down = async function down(knex) {
15
+ if (await knex.schema.hasColumn(WORKSPACE_SETTINGS_TABLE, COLUMN_NAME)) {
16
+ await knex.schema.alterTable(WORKSPACE_SETTINGS_TABLE, (table) => {
17
+ table.dropColumn(COLUMN_NAME);
18
+ });
19
+ }
20
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/workspaces-core",
3
- "version": "0.2.58",
3
+ "version": "0.2.59",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -24,9 +24,9 @@
24
24
  "./locales/en.json": "./locales/en.json"
25
25
  },
26
26
  "dependencies": {
27
- "@jskit-ai/resource-core": "0.1.221",
28
- "@jskit-ai/resource-crud-core": "0.1.223",
29
- "@jskit-ai/users-core": "0.2.58",
27
+ "@jskit-ai/resource-core": "0.1.222",
28
+ "@jskit-ai/resource-crud-core": "0.1.224",
29
+ "@jskit-ai/users-core": "0.2.59",
30
30
  "json-rest-schema": "^1.0.20"
31
31
  },
32
32
  "description": "Workspace tenancy runtime plus HTTP routes, role catalog, and workspace config scaffolding.",
@@ -216,10 +216,10 @@
216
216
  }
217
217
  },
218
218
  "peerDependencies": {
219
- "@jskit-ai/auth-core": "0.2.34",
220
- "@jskit-ai/database-runtime": "0.1.280",
221
- "@jskit-ai/http-runtime": "0.2.30",
222
- "@jskit-ai/kernel": "0.2.30",
223
- "@jskit-ai/resource-runtime": "0.2.44"
219
+ "@jskit-ai/auth-core": "0.2.35",
220
+ "@jskit-ai/database-runtime": "0.1.281",
221
+ "@jskit-ai/http-runtime": "0.2.31",
222
+ "@jskit-ai/kernel": "0.2.31",
223
+ "@jskit-ai/resource-runtime": "0.2.45"
224
224
  }
225
225
  }
@@ -24,11 +24,21 @@ Choose workspace creation policy, roles, invitation policy, expiry, email copy,
24
24
  member permissions, personal-workspace behavior, and surface access rules.
25
25
 
26
26
  In `workspaces` mode, `tenancyPolicy.workspace.autoProvision: true` gives every
27
- user a personal workspace in addition to shared ones; the optional
27
+ user a personal workspace in addition to shared ones, and `"unless-member"` only
28
+ to someone in no workspace who signs in without an invitation; the optional
28
29
  `workspaces.personal-workspace-name` capability, a function of the user, names it. `workspaceSettings.defaults` sets
29
- `invitesEnabled` and the colours (`lightPrimaryColor`, `darkPrimaryColor` and
30
+ `invitesEnabled`, `invitesRequireSameEmail` and the colours (`lightPrimaryColor`, `darkPrimaryColor` and
30
31
  the other palette fields) that new workspaces start with.
31
32
 
33
+ Decide who may accept an invitation: by default only the invited address.
34
+ `workspaceInvitations.anyAccount: true` lets any signed-in account holding the
35
+ link join after confirming (`acceptAs`, else 409
36
+ `workspaces.invite.differentEmailUnconfirmed`), except in a workspace whose
37
+ `invitesRequireSameEmail` setting is on (403 `workspaces.invite.emailMismatchUser`).
38
+ Members then show `invitedEmail`, the address they were invited at, and the
39
+ mailer's optional `sendInviteAcceptedByOtherAddress` tells the inviter after
40
+ commit.
41
+
32
42
  ## Framework APIs
33
43
 
34
44
  Use workspace routes, resources, scope helpers, tenancy profiles, and settings
@@ -84,7 +94,7 @@ catalogue entries. Updating labels requires no database migration.
84
94
  Provide one function as the optional `workspaces.invite-acceptance-participant`
85
95
  capability, from a small application feature that requires only what its writes
86
96
  need (it cannot require `workspaces.core`, which receives it). The built-in
87
- `workspace.invite.redeem` action invokes `fn({ invite, user }, txOptions)`
97
+ `workspace.invite.redeem` action invokes `fn({ invite, user, workspace }, txOptions)`
88
98
  after validating the recipient, state and expiry and activating membership in the
89
99
  uncommitted transaction. Pass `txOptions` to every application owner's calls and
90
100
  propagate failures. JSKIT marks accepted and commits after the function succeeds. Keep
@@ -124,7 +134,8 @@ transactional creation; put related acceptance writes in the participant. Revoca
124
134
  a managed transaction. Raw Knex/savepoint transactions cannot own resource
125
135
  writes. Invitation mutations lock workspace then invitation rows, revalidate
126
136
  current state and reject changes to accepted/revoked invitations. Expiry rejection
127
- for the matching recipient commits revocation before returning 409. Preserve transaction
137
+ commits the invitation as `expired` before returning 409, and it stays `expired`
138
+ (`revoked` is only a workspace's withdrawal). Preserve transaction
128
139
  outcomes and causes; a completion-hook error after commit cannot undo writes.
129
140
 
130
141
  See the human guide's **Workspace tenancy → Transactional invitation
@@ -169,7 +180,14 @@ setup({ env }) {
169
180
 
170
181
  Without a renderer, workspaces-core uses its built-in email; without a mailer,
171
182
  invitations are created and their delivery reports `mailer_unconfigured`. The
172
- feature must not require `workspaces.core`, which receives both.
183
+ feature must not require `workspaces.core`, which receives both. A mailer may
184
+ also have `sendInviteAcceptedByOtherAddress(notice, options)`, which tells the
185
+ inviter, after the acceptance commits, that another address accepted their
186
+ invitation; a failure is logged and never undoes the acceptance.
187
+
188
+ `services.directory.deleteWorkspace(workspaceId, options)` deletes a workspace in
189
+ the caller's transaction (cascading its memberships, settings and invitations),
190
+ answers `false` for a missing one, publishes no event and checks no permission.
173
191
 
174
192
  ## Variation points
175
193
 
@@ -179,7 +197,9 @@ ids, and product-specific workspace settings.
179
197
  ## Verification
180
198
 
181
199
  Test create/list/select, member and non-member access, each role boundary,
182
- invitation expiry/redemption, cross-workspace isolation, and email output.
200
+ invitation expiry/redemption, acceptance by another address where `anyAccount`
201
+ is on (confirmed, unconfirmed and in a workspace requiring the invited address),
202
+ cross-workspace isolation, and email output.
183
203
 
184
204
  ## Avoid
185
205
 
@@ -86,6 +86,7 @@ const WorkspacesFeature = defineFeature({
86
86
  inviteMailer: inviteMailer
87
87
  ? createAppEnvironmentInviteMailer({ env, logger, mailer: inviteMailer })
88
88
  : unconfiguredWorkspaceInviteMailer,
89
+ logger,
89
90
  personalWorkspaceName: personalWorkspaceName ?? buildWorkspaceName,
90
91
  resources,
91
92
  userProfiles,
@@ -99,8 +99,8 @@ const WorkspacesIntegrationsProvider = defineProvider({
99
99
  usersExtensions.registerProfileSyncLifecycleContributor({
100
100
  contributorId: "workspaces.provisioning",
101
101
  order: 100,
102
- async afterIdentityProfileSynced({ profile, options }) {
103
- await workspaceService.ensureProvisionedWorkspaceForAuthenticatedUser(profile, options);
102
+ async afterIdentityProfileSynced({ profile, invitation, options }) {
103
+ await workspaceService.ensureProvisionedWorkspaceForAuthenticatedUser(profile, options, { invitation });
104
104
  }
105
105
  });
106
106
 
@@ -106,6 +106,17 @@ function createRepository({ workspaceInvites, workspaces }) {
106
106
  return invite?.tokenHash === normalizeText(tokenHash) ? invite : null;
107
107
  }
108
108
 
109
+ // The invite a token names in any status, or null; never a locking read, inside a transaction too.
110
+ async function findByTokenHash(tokenHash, options = {}) {
111
+ const normalizedTokenHash = normalizeText(tokenHash);
112
+ if (!normalizedTokenHash) {
113
+ return null;
114
+ }
115
+
116
+ const rows = await queryInvites({ tokenHash: normalizedTokenHash }, { ...options, lock: false });
117
+ return normalizeInviteRecord(rows[0] || null);
118
+ }
119
+
109
120
  async function findByTokenHashWithWorkspace(tokenHash, options = {}) {
110
121
  const normalizedTokenHash = normalizeText(tokenHash);
111
122
  if (!normalizedTokenHash) {
@@ -289,15 +300,9 @@ function createRepository({ workspaceInvites, workspaces }) {
289
300
  });
290
301
  }
291
302
  const updatedAt = new Date().toISOString();
292
- await patchInvite(
293
- id,
294
- {
295
- status,
296
- [status === "accepted" ? "acceptedAt" : "revokedAt"]: updatedAt,
297
- updatedAt
298
- },
299
- txOptions
300
- );
303
+ // An accepted invite records when it was accepted and a revoked one when; an expired one only its status.
304
+ const stamp = { accepted: { acceptedAt: updatedAt }, revoked: { revokedAt: updatedAt } }[status] ?? {};
305
+ await patchInvite(id, { status, ...stamp, updatedAt }, txOptions);
301
306
  });
302
307
  }
303
308
 
@@ -309,6 +314,11 @@ function createRepository({ workspaceInvites, workspaces }) {
309
314
  return transitionPendingById(inviteId, "revoked", options);
310
315
  }
311
316
 
317
+ // A pending invite whose time ran out: it reads "expired" from then on, as one the workspace withdrew reads "revoked".
318
+ async function markExpiredById(inviteId, options = {}) {
319
+ return transitionPendingById(inviteId, "expired", options);
320
+ }
321
+
312
322
  async function findPendingByIdForWorkspace(inviteId, workspaceId, options = {}) {
313
323
  const normalizedInviteId = normalizeRecordId(inviteId, { fallback: null });
314
324
  const normalizedWorkspaceId = normalizeRecordId(workspaceId, { fallback: null });
@@ -339,6 +349,7 @@ function createRepository({ workspaceInvites, workspaces }) {
339
349
  lockWorkspaceForInvitations,
340
350
  findById,
341
351
  findPendingByTokenHash,
352
+ findByTokenHash,
342
353
  findByTokenHashWithWorkspace,
343
354
  listPendingByEmail,
344
355
  listPendingByWorkspaceIdWithWorkspace,
@@ -347,6 +358,7 @@ function createRepository({ workspaceInvites, workspaces }) {
347
358
  expirePendingByWorkspaceIdAndEmail,
348
359
  markAcceptedById,
349
360
  revokeById,
361
+ markExpiredById,
350
362
  findPendingByIdForWorkspace
351
363
  });
352
364
  }
@@ -21,14 +21,16 @@ function decodeCursor(cursor) {
21
21
 
22
22
  /**
23
23
  * A workspace's members a page at a time, with their users' names and emails: the members list of
24
- * `workspaces.core`. A page is one statement on the memberships joined to users.profiles' join source, so it reads
25
- * a page of rows however many members the workspace has.
24
+ * `workspaces.core`. A page is one statement on the memberships joined to users.profiles' join source and to the
25
+ * invitations they were accepted through, so it reads a page of rows however many members the workspace has.
26
26
  * @param {object} dependencies
27
27
  * @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} dependencies.workspaceMemberships
28
28
  * The workspace_memberships table's handle.
29
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} dependencies.workspaceInvites
30
+ * The workspace_invites table's handle.
29
31
  * @param {Pick<import("@jskit-ai/users-core/server/types").UsersProfiles, "joinSource">} dependencies.userProfiles
30
32
  */
31
- function createRepository({ workspaceMemberships, userProfiles }) {
33
+ function createRepository({ workspaceMemberships, workspaceInvites, userProfiles }) {
32
34
  /**
33
35
  * One page of the workspace's active members by display name (then user id), each as listActiveByWorkspaceId
34
36
  * summarizes it: `{ members, next }`, where `next` is the cursor of the page after, or null on the last page.
@@ -36,7 +38,8 @@ function createRepository({ workspaceMemberships, userProfiles }) {
36
38
  * @param {{ size: number, after?: string }} page At most the memberships handle's pageLimits().request members.
37
39
  * @param {object} [options]
38
40
  */
39
- // Knex: report - one page of a workspace's active members with their users' names and emails, by display name
41
+ // Knex: report - one page of a workspace's active members with their users' names and emails and the address they
42
+ // were invited at, by display name
40
43
  async function listActivePage(workspaceId, { size, after }, options = {}) {
41
44
  const normalizedWorkspaceId = normalizeRecordId(workspaceId, { fallback: null });
42
45
  if (!normalizedWorkspaceId) {
@@ -48,6 +51,8 @@ function createRepository({ workspaceMemberships, userProfiles }) {
48
51
  const profiles = user.query
49
52
  .select({ userId: user.column("id"), shown: user.column("displayName"), mail: user.column("email") })
50
53
  .as("p");
54
+ const invite = await workspaceInvites.joinSource({ alias: "i", filters: { workspace: normalizedWorkspaceId } }, options);
55
+ const invites = invite.query.select({ inviteId: invite.column("id"), invitedAt: invite.column("email") }).as("a");
51
56
  const { query } = await workspaceMemberships.scopedQuery(
52
57
  { alias: "m", filters: { workspace: normalizedWorkspaceId, status: "active" } },
53
58
  options
@@ -55,12 +60,14 @@ function createRepository({ workspaceMemberships, userProfiles }) {
55
60
  const memberUserId = workspaceMemberships.column("userId", "m");
56
61
  query
57
62
  .join(profiles, "p.userId", memberUserId)
63
+ .leftJoin(invites, "a.inviteId", workspaceMemberships.column("acceptedInviteId", "m"))
58
64
  .select({
59
65
  user_id: memberUserId,
60
66
  role_sid: workspaceMemberships.column("roleSid", "m"),
61
67
  status: workspaceMemberships.column("status", "m"),
62
68
  display_name: "p.shown",
63
- email: "p.mail"
69
+ email: "p.mail",
70
+ invited_email: "a.invitedAt"
64
71
  })
65
72
  .orderBy(["p.shown", memberUserId])
66
73
  .limit(limit + 1);
@@ -4,6 +4,8 @@ import { OWNER_ROLE_ID } from "../../../shared/roles.js";
4
4
 
5
5
  // A bulk read's users per query, so its "in" list stays well inside every database's limits.
6
6
  const USER_IDS_PER_QUERY = 1000;
7
+ // A member summary's reads: the membership with its user and the invitation it was accepted through.
8
+ const MEMBER_SUMMARY_INCLUDES = Object.freeze(["user", "acceptedInvite"]);
7
9
 
8
10
  function normalizeMembershipRecord(payload) {
9
11
  if (!payload) {
@@ -16,6 +18,7 @@ function normalizeMembershipRecord(payload) {
16
18
  userId: normalizeDbRecordId(payload?.user?.id || payload?.userId, { fallback: null }),
17
19
  roleSid: normalizeLowerText(payload.roleSid || "member") || "member",
18
20
  status: normalizeLowerText(payload.status || "active") || "active",
21
+ acceptedInviteId: normalizeDbRecordId(payload?.acceptedInvite?.id || payload?.acceptedInviteId, { fallback: null }),
19
22
  createdAt: payload.createdAt ? toIsoString(payload.createdAt) : null,
20
23
  updatedAt: payload.updatedAt ? toIsoString(payload.updatedAt) : null
21
24
  };
@@ -26,16 +29,20 @@ function normalizeMemberSummaryRow(row) {
26
29
  return null;
27
30
  }
28
31
 
32
+ const email = normalizeLowerText(row.email);
33
+ const invitedEmail = normalizeLowerText(row.invited_email);
29
34
  return {
30
35
  userId: normalizeDbRecordId(row.user_id, { fallback: "" }),
31
36
  roleSid: normalizeLowerText(row.role_sid || "member") || "member",
32
37
  status: normalizeLowerText(row.status || "active") || "active",
33
38
  displayName: normalizeText(row.display_name),
34
- email: normalizeLowerText(row.email)
39
+ email,
40
+ // The address of the invitation the member last joined through, when it is not their account's email.
41
+ invitedEmail: invitedEmail === email ? "" : invitedEmail
35
42
  };
36
43
  }
37
44
 
38
- // A membership read with its user included, as a member summary.
45
+ // A membership read with its user and the invitation it was accepted through included, as a member summary.
39
46
  function memberSummaryFromMembership(row) {
40
47
  if (!row) {
41
48
  return null;
@@ -46,7 +53,8 @@ function memberSummaryFromMembership(row) {
46
53
  role_sid: row.roleSid,
47
54
  status: row.status,
48
55
  display_name: row.user?.displayName,
49
- email: row.user?.email
56
+ email: row.user?.email,
57
+ invited_email: row.acceptedInvite?.email
50
58
  });
51
59
  }
52
60
 
@@ -140,13 +148,20 @@ function createRepository({ workspaceMemberships }) {
140
148
  const existing = await findByWorkspaceIdAndUserId(normalizedWorkspaceId, normalizedUserId, options);
141
149
  const roleSid = normalizeLowerText(patch?.roleSid ?? existing?.roleSid) || "member";
142
150
  const status = normalizeLowerText(patch?.status ?? existing?.status) || "active";
151
+ // The invitation an acceptance makes the membership through, which replaces the one it was accepted through before.
152
+ const acceptedInvite = patch?.acceptedInviteId === undefined
153
+ ? {}
154
+ : { acceptedInviteId: normalizeRecordId(patch.acceptedInviteId, { fallback: null }) };
143
155
 
144
156
  if (!existing) {
145
- await createMembership({ roleSid, status, workspaceId: normalizedWorkspaceId, userId: normalizedUserId }, options);
157
+ await createMembership(
158
+ { roleSid, status, ...acceptedInvite, workspaceId: normalizedWorkspaceId, userId: normalizedUserId },
159
+ options
160
+ );
146
161
  return findByWorkspaceIdAndUserId(normalizedWorkspaceId, normalizedUserId, options);
147
162
  }
148
163
 
149
- await patchMembership(existing.id, { roleSid, status }, options);
164
+ await patchMembership(existing.id, { roleSid, status, ...acceptedInvite }, options);
150
165
  return findByWorkspaceIdAndUserId(normalizedWorkspaceId, normalizedUserId, options);
151
166
  }
152
167
 
@@ -186,7 +201,7 @@ function createRepository({ workspaceMemberships }) {
186
201
  return [];
187
202
  }
188
203
 
189
- const rows = await queryMemberships({ workspace: normalizedWorkspaceId, ...filters }, options, { include: ["user"] });
204
+ const rows = await queryMemberships({ workspace: normalizedWorkspaceId, ...filters }, options, { include: MEMBER_SUMMARY_INCLUDES });
190
205
  const members = rows.map(memberSummaryFromMembership).filter(Boolean);
191
206
 
192
207
  members.sort((left, right) => String(left.displayName || "").localeCompare(String(right.displayName || "")));
@@ -224,7 +239,7 @@ function createRepository({ workspaceMemberships }) {
224
239
  status: "active"
225
240
  },
226
241
  options,
227
- { include: ["user"] }
242
+ { include: MEMBER_SUMMARY_INCLUDES }
228
243
  );
229
244
 
230
245
  return memberSummaryFromMembership(rows[0] || null);
@@ -242,6 +257,20 @@ function createRepository({ workspaceMemberships }) {
242
257
  .filter(Boolean);
243
258
  }
244
259
 
260
+ // Whether the user is an active member of any workspace, in one read of at most one membership.
261
+ async function hasActiveMembership(userId, options = {}) {
262
+ const normalizedUserId = normalizeRecordId(userId, { fallback: null });
263
+ if (!normalizedUserId) {
264
+ return false;
265
+ }
266
+
267
+ const { records } = await workspaceMemberships.query(
268
+ { filters: { user: normalizedUserId, status: "active" }, fields: ["status"], page: { size: 1 } },
269
+ options
270
+ );
271
+ return records.length > 0;
272
+ }
273
+
245
274
  /**
246
275
  * Each user's active workspace ids, as listActiveWorkspaceIdsByUserId lists them, in one
247
276
  * query per 1,000 users: its cost does not grow with the users asked about.
@@ -318,7 +347,8 @@ function createRepository({ workspaceMemberships }) {
318
347
  findActiveByWorkspaceIdAndUserId,
319
348
  listActiveWorkspaceIdsByUserId,
320
349
  listActiveWorkspaceIdsByUserIds,
321
- listActiveWorkspaceIdsByUserIdsAmong
350
+ listActiveWorkspaceIdsByUserIdsAmong,
351
+ hasActiveMembership
322
352
  });
323
353
  }
324
354
 
@@ -268,6 +268,23 @@ function createRepository({ workspaces, workspaceMemberships }) {
268
268
  return row ? { id: normalizeRecordId(row.id, { fallback: null }) } : null;
269
269
  }
270
270
 
271
+ /**
272
+ * Deletes the workspace's row, in the caller's transaction when `options` carries one. The database's cascades take
273
+ * its memberships, settings and invites with it; a table of the application's own that references the workspace
274
+ * without a cascade refuses the delete. Answers false when there was no such workspace, true otherwise. It
275
+ * publishes no event: an application keeping its own copy of workspace facts updates it from the answer.
276
+ * @param {unknown} workspaceId
277
+ * @param {object} [options]
278
+ * @returns {Promise<boolean>}
279
+ */
280
+ async function deleteById(workspaceId, options = {}) {
281
+ const id = normalizeRecordId(workspaceId, { fallback: null });
282
+ if (!id) {
283
+ throw new TypeError(`workspaces.deleteById() requires a workspace id. Received: ${String(workspaceId)}`);
284
+ }
285
+ return (await workspaces.delete(id, { ...options, missing: "skip" })) !== null;
286
+ }
287
+
271
288
  /**
272
289
  * Hands a workspace to another of its active members, in the caller's transaction when `options` carries one (the
273
290
  * txOptions of withTransaction), otherwise in one of its own. It locks the workspace's row first and reads the
@@ -370,6 +387,7 @@ function createRepository({ workspaces, workspaceMemberships }) {
370
387
  updateById,
371
388
  listForUserId,
372
389
  lock,
390
+ deleteById,
373
391
  transferOwnership
374
392
  });
375
393
  }
@@ -5,7 +5,7 @@ import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
5
5
  import { normalizeLowerText, normalizeRecordId, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
6
6
  import { WORKSPACE_PATCH_FIELD_KEYS } from "../../../shared/resources/workspaceResource.js";
7
7
  import { listCatalogRolePermissions } from "../../../shared/roles.js";
8
- import { TENANCY_MODE_NONE } from "../../../shared/tenancyProfile.js";
8
+ import { TENANCY_MODE_NONE, WORKSPACE_AUTO_PROVISION_UNLESS_MEMBER } from "../../../shared/tenancyProfile.js";
9
9
  import { mapWorkspaceSummary } from "../formatters/workspaceFormatter.js";
10
10
 
11
11
  const WORKSPACE_SLUG_CANDIDATE_LIMIT = 1000;
@@ -193,13 +193,30 @@ function createService({
193
193
  return returnJsonApiData({ items: await listWorkspacesForUser(user, options), nextCursor: null });
194
194
  }
195
195
 
196
- async function ensureProvisionedWorkspaceForAuthenticatedUser(user, options = {}) {
196
+ /**
197
+ * The signed-in user's personal workspace, made when missing, as `tenancyPolicy.workspace.autoProvision` says:
198
+ * always with `true`, never with `false` (null). With "unless-member" only for a user who is no active member of
199
+ * any workspace and whose sign-in carries no invitation naming a workspace (`signIn.invitation`, as the auth
200
+ * invitation context resolver resolved it): a person joining a workspace by an invitation gets no workspace of
201
+ * their own (null).
202
+ * @param {{ id?: unknown } | null} user
203
+ * @param {object} [options]
204
+ * @param {{ invitation?: { workspaceId?: string } | null }} [signIn]
205
+ */
206
+ async function ensureProvisionedWorkspaceForAuthenticatedUser(user, options = {}, { invitation = null } = {}) {
197
207
  const normalizedUserId = normalizeRecordId(user?.id, { fallback: null });
198
208
  if (!normalizedUserId) {
199
209
  throw new AppError(400, "Invalid authenticated user payload.", { code: "workspaces.user.invalidPayload" });
200
210
  }
201
211
 
202
- if (workspacePolicy.autoProvision !== true) {
212
+ if (workspacePolicy.autoProvision === WORKSPACE_AUTO_PROVISION_UNLESS_MEMBER) {
213
+ if (normalizeRecordId(invitation?.workspaceId, { fallback: null })) {
214
+ return null;
215
+ }
216
+ if (await workspaceMembershipsRepository.hasActiveMembership(normalizedUserId, options)) {
217
+ return null;
218
+ }
219
+ } else if (workspacePolicy.autoProvision !== true) {
203
220
  return null;
204
221
  }
205
222
 
@@ -209,6 +226,18 @@ function createService({
209
226
  }, options);
210
227
  }
211
228
 
229
+ /**
230
+ * Deletes a workspace, in the caller's transaction when `options` carries one: its row, and through the database's
231
+ * cascades its memberships, settings and invites. False when there was no such workspace, true otherwise. Like
232
+ * transferOwnership it publishes no event, and it runs no participant: the caller decides when a workspace may go.
233
+ * @param {unknown} workspaceId
234
+ * @param {object} [options]
235
+ * @returns {Promise<boolean>}
236
+ */
237
+ async function deleteWorkspace(workspaceId, options = {}) {
238
+ return workspacesRepository.deleteById(workspaceId, options);
239
+ }
240
+
212
241
  /**
213
242
  * Creates a workspace the user owns. The action's input schema has already
214
243
  * trimmed the name and slug and lowercased the slug.
@@ -396,6 +425,7 @@ function createService({
396
425
  return Object.freeze({
397
426
  ensurePersonalWorkspaceForUser,
398
427
  ensureProvisionedWorkspaceForAuthenticatedUser,
428
+ deleteWorkspace,
399
429
  createWorkspaceForAuthenticatedUser,
400
430
  getWorkspaceForAuthenticatedUser,
401
431
  updateWorkspaceForAuthenticatedUser,
@@ -7,7 +7,8 @@ function normalizeWorkspaceInvitationsConfig(appConfig) {
7
7
 
8
8
  return Object.freeze({
9
9
  enabled: source.enabled !== false,
10
- allowInPersonalMode: source.allowInPersonalMode !== false
10
+ allowInPersonalMode: source.allowInPersonalMode !== false,
11
+ anyAccount: source.anyAccount === true
11
12
  });
12
13
  }
13
14
 
@@ -27,6 +28,9 @@ function resolveWorkspaceInvitationsPolicy({ appConfig, tenancyProfile }) {
27
28
  enabled,
28
29
  workspaceEnabled,
29
30
  allowInPersonalMode: config.allowInPersonalMode,
31
+ // Any signed-in account holding an invitation's link may accept it, unless its workspace requires the invited
32
+ // address (invitesRequireSameEmail); off, only the account whose email is the invited one may.
33
+ anyAccount: enabled && config.anyAccount,
30
34
  tenancyMode
31
35
  });
32
36
  }
@@ -37,8 +37,16 @@
37
37
  * `held` (an email the mailer keeps until the application's email is set up,
38
38
  * and sends then) and `failed`; for any other status it shows the result's
39
39
  * `message` (translated by `messageCode` when given), else a neutral notice.
40
+ *
41
+ * Its optional `sendInviteAcceptedByOtherAddress` tells an inviter that an
42
+ * account whose email is not the invited address accepted their invitation
43
+ * (where `config.workspaceInvitations.anyAccount` lets one). It is called once
44
+ * the acceptance committed, never inside its transaction; its failure is logged
45
+ * and the acceptance stands. A mailer without it sends no such notice.
46
+ * `message` is the notice's `{ subject, text, html }` in the inviter's language.
40
47
  * @typedef {object} WorkspaceInviteMailer
41
48
  * @property {(message: { inviteId: string, email: string, inviteUrl: string, workspace: { id: string, slug: string, name: string, ownerUserId: string, avatarUrl: string }, inviter: object | null, roleSid: string, expiresAt: string, locale: string, message: object }, options?: object) => Promise<{ status?: string, message?: string, messageCode?: string, messageParams?: object, providerMessageId?: string } | void>} sendWorkspaceInvite
49
+ * @property {(notice: { inviteId: string, invite: { id: string, email: string, roleSid: string }, inviter: { id: string, email: string, displayName: string }, member: { id: string, email: string, displayName: string }, workspace: { id: string, slug: string, name: string }, locale: string, message: { subject: string, text: string, html: string } }, options?: object) => Promise<unknown>} [sendInviteAcceptedByOtherAddress]
42
50
  */
43
51
 
44
52
  /**
@@ -47,12 +55,26 @@
47
55
  * @typedef {(input: { email: string, inviteUrl: string, workspace: object, inviter: object | null, roleSid: string, roleLabel?: string, expiresAt: string, locale: string, timeZone: string, t: (key: string, params?: object) => string }) => object | Promise<object>} WorkspaceInviteEmailTemplate
48
56
  */
49
57
 
58
+ /**
59
+ * An accepted invitation: the invitation as read before it was marked accepted
60
+ * (with at least these fields), the user who accepted it (the signed-in actor,
61
+ * with at least these) and the workspace they joined. `invite.email` is the
62
+ * invited address and `user.email` the account's, which differ when another
63
+ * account accepted it.
64
+ * @typedef {{
65
+ * invite: { id: string, email: string, workspaceId: string, invitedByUserId: string | null, roleSid: string, [field: string]: unknown },
66
+ * user: { id: string, email: string, displayName: string, [field: string]: unknown },
67
+ * workspace: { id: string, slug: string, name: string, ownerUserId: string }
68
+ * }} WorkspaceInviteAcceptance
69
+ */
70
+
50
71
  /**
51
72
  * The `workspaces.invite-acceptance-participant` capability: the application's
52
73
  * writes for an accepted invitation. It runs after the membership is activated,
53
74
  * inside the uncommitted acceptance transaction, and a failure rolls the
54
- * acceptance back. Its options join that transaction: pass them to every call.
55
- * @typedef {(acceptance: { invite: object, user: object }, options: { trx: unknown, context?: object }) => Promise<void>} WorkspaceInviteAcceptanceParticipant
75
+ * acceptance back. Its options join that transaction: pass them to every call,
76
+ * such as `workspaces.core`'s `services.directory.deleteWorkspace`.
77
+ * @typedef {(acceptance: WorkspaceInviteAcceptance, options: { trx: unknown, context?: object }) => Promise<void>} WorkspaceInviteAcceptanceParticipant
56
78
  */
57
79
 
58
80
  /**