@jskit-ai/workspaces-core 0.2.48 → 0.2.49

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,7 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - **Breaking:** a provided `workspaces.invite-mailer` sends as `APP_ENV` says (`createAppEnvironmentInviteMailer`, replacing the simulated mailer): production sends each invitation; staging sends it only to `STAGING_EMAIL_TO`, its message marked with the address it was for; development, test and staging without `STAGING_EMAIL_TO` log it and answer `status: "simulated"` (`workspaces.invite.simulated`, "Outside production the invitation email was logged, not sent. Copy the invite link to share it."). A role grant no action requires refuses to start in development and test and is logged in staging and production, by `APP_ENV`, not `NODE_ENV`.
5
6
  - `workspaces.core` gains `roleContext({ workspaceId, userId, role, reason }, { context: systemContext(reason), trx? })`, the context of installer and seed work done in one workspace as a user in a role of the role catalog that they are not given there: required records a workspace gets for the platform's owner, who is normally no member of a self-created workspace, or a seed's starter data. It has exactly a member context's shape (`actor`, `workspace`, `membership`, `permissions`, the `workspace_user` visibility context and `requestMeta.resolvedWorkspaceContext`) with the membership `{ workspaceId, userId, roleSid, status: "active" }`, which is never saved and replaces any membership the user has there, and the role's permissions, so a permission check and a row policy decide as for a member in that role; it also records `reason`, which a row policy reads as `caller.reason` and which grants nothing. It is no system context and no job: request row limits apply and other owners' hidden fields stay hidden. Only a system context makes one, with a non-empty reason; any other context, a missing reason, ids that are no record ids and a role the catalog lacks are a TypeError before any statement, a missing or deleted workspace is 404 `workspaces.workspace.notFound`, a user id naming no one 404 `users.profile.notFound`, and an application without workspaces 403 `workspaces.workspace.contextDisabled`. It reads the user, the workspace and its settings, and writes nothing (no settings, no owner membership). The directory service's new `resolveRoleWorkspaceContextById(user, workspaceId, roleSid, options)` builds it. `memberContext` is unchanged and still means real membership only.
6
7
  - An action run in a context that already carries the resolved context of the action's workspace (`requestMeta.resolvedWorkspaceContext` with that workspace's slug, as a member context and a role context carry it) keeps it: the workspace action context contributor no longer reads the workspace, the membership and the settings again, so a role context's unsaved membership survives into the action, and a member context's action no longer repeats its reads.
7
8
 
package/locales/en.json CHANGED
@@ -38,7 +38,7 @@
38
38
  "emailMismatchAccount": "Invitation email does not match account email.",
39
39
  "notAvailable": "Invitation is not available.",
40
40
  "mailerUnconfigured": "No workspace invite mailer is configured.",
41
- "simulated": "Test copy: the invitation email was not sent. Copy the invite link to share it.",
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
44
  "decisionInvalid": "Decision must be accept or refuse."
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/workspaces-core",
3
- "version": "0.2.48",
3
+ "version": "0.2.49",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -23,9 +23,9 @@
23
23
  "./locales/en.json": "./locales/en.json"
24
24
  },
25
25
  "dependencies": {
26
- "@jskit-ai/resource-core": "0.1.217",
27
- "@jskit-ai/resource-crud-core": "0.1.219",
28
- "@jskit-ai/users-core": "0.2.48",
26
+ "@jskit-ai/resource-core": "0.1.218",
27
+ "@jskit-ai/resource-crud-core": "0.1.220",
28
+ "@jskit-ai/users-core": "0.2.49",
29
29
  "json-rest-schema": "^1.0.20"
30
30
  },
31
31
  "description": "Workspace tenancy runtime plus HTTP routes, role catalog, and workspace config scaffolding.",
@@ -211,10 +211,10 @@
211
211
  }
212
212
  },
213
213
  "peerDependencies": {
214
- "@jskit-ai/auth-core": "0.2.29",
215
- "@jskit-ai/database-runtime": "0.1.275",
216
- "@jskit-ai/http-runtime": "0.2.26",
217
- "@jskit-ai/kernel": "0.2.26",
218
- "@jskit-ai/resource-runtime": "0.2.36"
214
+ "@jskit-ai/auth-core": "0.2.30",
215
+ "@jskit-ai/database-runtime": "0.1.276",
216
+ "@jskit-ai/http-runtime": "0.2.27",
217
+ "@jskit-ai/kernel": "0.2.27",
218
+ "@jskit-ai/resource-runtime": "0.2.37"
219
219
  }
220
220
  }
@@ -1,4 +1,4 @@
1
- import { isProductionEnv } from "@jskit-ai/kernel/server/runtime/runtimeMode";
1
+ import { isDeployed } from "@jskit-ai/kernel/shared/support/appEnvironment";
2
2
  import { defineProvider } from "@jskit-ai/kernel/shared/capabilities";
3
3
  import {
4
4
  collectRequiredPermissions,
@@ -10,9 +10,9 @@ import {
10
10
  * Checks, once every feature has registered its actions and routes, that each grant of the workspace role catalogue
11
11
  * covers a permission the application requires: an action's, a route's, a surface access policy's, or one the role
12
12
  * catalogue's `customPermissions` declares. A grant such as `crud.labels.patch`, which no action requires, would
13
- * otherwise leave a role silently refused (`ACTION_PERMISSION_DENIED`) where it was meant to be allowed. Outside
14
- * production the server refuses to start; in production, where the grant gives nothing and costs nothing, it starts
15
- * and logs a warning.
13
+ * otherwise leave a role silently refused (`ACTION_PERMISSION_DENIED`) where it was meant to be allowed. In
14
+ * development and test (APP_ENV) the server refuses to start; in staging and production, where the grant gives
15
+ * nothing and costs nothing, it starts and logs a warning.
16
16
  */
17
17
  const WorkspaceRoleGrantsProvider = defineProvider({
18
18
  id: "workspaces.role-grants",
@@ -47,7 +47,7 @@ const WorkspaceRoleGrantsProvider = defineProvider({
47
47
  return;
48
48
  }
49
49
  const message = describeUnknownRoleGrants(findings);
50
- if (isProductionEnv(env)) {
50
+ if (isDeployed(env)) {
51
51
  logger.warn({ unknownRoleGrants: findings.map(({ roleId, grant }) => ({ roleId, grant })) }, message);
52
52
  return;
53
53
  }
@@ -1,5 +1,4 @@
1
1
  import { defineFeature } from "@jskit-ai/kernel/server/features";
2
- import { sideEffectsAreLive } from "@jskit-ai/kernel/shared/support/sideEffects";
3
2
  import { createWorkspaceBootstrapContributor } from "./workspaceBootstrapContributor.js";
4
3
  import { registerWorkspaceDirectoryRoutes } from "./workspaceDirectory/workspaceDirectoryRoutes.js";
5
4
  import { createWorkspaceDirectoryActions } from "./workspaceDirectory/workspaceDirectoryActions.js";
@@ -9,7 +8,7 @@ import { registerWorkspacePendingInvitationsRoutes } from "./workspacePendingInv
9
8
  import { createWorkspacePendingInvitationsActions } from "./workspacePendingInvitations/workspacePendingInvitationsActions.js";
10
9
  import { registerWorkspaceSettingsRoutes } from "./workspaceSettings/workspaceSettingsRoutes.js";
11
10
  import { unconfiguredWorkspaceInviteMailer } from "./workspaceMembers/unconfiguredWorkspaceInviteMailer.js";
12
- import { createSimulatedWorkspaceInviteMailer } from "./workspaceMembers/simulatedWorkspaceInviteMailer.js";
11
+ import { createAppEnvironmentInviteMailer } from "./workspaceMembers/appEnvironmentInviteMailer.js";
13
12
  import { renderDefaultWorkspaceInviteEmail } from "./workspaceMembers/defaultWorkspaceInviteEmail.js";
14
13
  import { noInviteAcceptanceParticipant } from "./workspacePendingInvitations/noInviteAcceptanceParticipant.js";
15
14
  import { noWorkspaceCreatedParticipant } from "./workspaceDirectory/noWorkspaceCreatedParticipant.js";
@@ -83,9 +82,9 @@ const WorkspacesFeature = defineFeature({
83
82
  env,
84
83
  inviteAcceptanceParticipant: inviteAcceptanceParticipant ?? noInviteAcceptanceParticipant,
85
84
  inviteEmailTemplate: inviteEmailTemplate ?? renderDefaultWorkspaceInviteEmail,
86
- // A test copy (SIDE_EFFECTS is not live) logs the invitations a provided mailer would send, and sends none.
85
+ // A provided mailer sends as APP_ENV says: only production sends each invitation to its address.
87
86
  inviteMailer: inviteMailer
88
- ? (sideEffectsAreLive(env) ? inviteMailer : createSimulatedWorkspaceInviteMailer(logger))
87
+ ? createAppEnvironmentInviteMailer({ env, logger, mailer: inviteMailer })
89
88
  : unconfiguredWorkspaceInviteMailer,
90
89
  personalWorkspaceName: personalWorkspaceName ?? buildWorkspaceName,
91
90
  resources,
@@ -33,7 +33,7 @@
33
33
  * workspace invitation email. It is told which saved invitation it sends
34
34
  * (`inviteId`, its `workspace_invites` row, in `workspace.id`'s workspace).
35
35
  * Its result is the delivery outcome; the status defaults to "sent". The
36
- * members panel words its own notice for `sent`, `simulated` (a test copy),
36
+ * members panel words its own notice for `sent`, `simulated` (logged outside production),
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.
@@ -0,0 +1,44 @@
1
+ import { deliverMessage, markStagingEmail } from "@jskit-ai/kernel/server/runtime/appEnvironment";
2
+
3
+ /**
4
+ * The provided `workspaces.invite-mailer`, sending as APP_ENV says (`deliverMessage`). Production sends each
5
+ * invitation to its address. Staging sends it only to STAGING_EMAIL_TO, its message showing the address it was for
6
+ * (`markStagingEmail`). Otherwise, in development, test and staging without STAGING_EMAIL_TO, it logs the
7
+ * invitation's recipient, subject and link and reports the delivery `simulated`, so the inviter copies the link to
8
+ * share it.
9
+ * @param {object} dependencies
10
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} dependencies.env
11
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
12
+ * @param {import("../types.js").WorkspaceInviteMailer} dependencies.mailer The provided mailer.
13
+ * @returns {import("../types.js").WorkspaceInviteMailer}
14
+ */
15
+ function createAppEnvironmentInviteMailer({ env, logger, mailer }) {
16
+ async function sendWorkspaceInvite(invite, options) {
17
+ const delivery = await deliverMessage({
18
+ env,
19
+ logger,
20
+ channel: "email",
21
+ to: invite.email,
22
+ summary: `the workspace invitation email to ${invite.email}`,
23
+ details: { subject: String(invite.message?.subject || ""), inviteUrl: invite.inviteUrl },
24
+ send: (to, { originalTo }) => mailer.sendWorkspaceInvite(
25
+ { ...invite, email: to, message: markStagingEmail(invite.message, originalTo) },
26
+ options
27
+ )
28
+ });
29
+ if (delivery.sent) {
30
+ return delivery.result;
31
+ }
32
+ return {
33
+ status: "simulated",
34
+ message: "Outside production the invitation email was logged, not sent. Copy the invite link to share it.",
35
+ messageCode: "workspaces.invite.simulated",
36
+ messageParams: {},
37
+ providerMessageId: ""
38
+ };
39
+ }
40
+
41
+ return Object.freeze({ sendWorkspaceInvite });
42
+ }
43
+
44
+ export { createAppEnvironmentInviteMailer };
@@ -0,0 +1,77 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { createAppEnvironmentInviteMailer } from "../src/server/workspaceMembers/appEnvironmentInviteMailer.js";
4
+
5
+ const INVITE = Object.freeze({
6
+ inviteId: "7",
7
+ email: "guest@example.com",
8
+ inviteUrl: "https://app.example.test/invite?token=abc",
9
+ message: Object.freeze({ subject: "You're invited to Books", text: "Join us", html: "<p>Join us</p>" })
10
+ });
11
+ const DEPLOYED = Object.freeze({ NODE_ENV: "production" });
12
+
13
+ function mailerIn(env) {
14
+ const logs = [];
15
+ const sent = [];
16
+ const mailer = createAppEnvironmentInviteMailer({
17
+ env,
18
+ logger: { info: (details, message) => logs.push({ details, message }), warn() {}, error() {}, debug() {} },
19
+ mailer: {
20
+ async sendWorkspaceInvite(invite, options) {
21
+ sent.push({ invite, options });
22
+ return { status: "sent", providerMessageId: "m-1" };
23
+ }
24
+ }
25
+ });
26
+ return { logs, sent, mailer };
27
+ }
28
+
29
+ test("development and test log each invitation, send none and report it simulated", async () => {
30
+ for (const APP_ENV of ["development", "test"]) {
31
+ const { logs, sent, mailer } = mailerIn({ APP_ENV });
32
+ const delivery = await mailer.sendWorkspaceInvite(INVITE, {});
33
+ assert.equal(delivery.status, "simulated", APP_ENV);
34
+ assert.equal(delivery.messageCode, "workspaces.invite.simulated");
35
+ assert.equal(sent.length, 0);
36
+ assert.deepEqual(logs, [{
37
+ details: {
38
+ appEnv: APP_ENV,
39
+ kind: "email",
40
+ to: "guest@example.com",
41
+ subject: "You're invited to Books",
42
+ inviteUrl: "https://app.example.test/invite?token=abc"
43
+ },
44
+ message: `${APP_ENV === "test" ? "Test" : "Development"}: the workspace invitation email to guest@example.com was logged, not sent.`
45
+ }]);
46
+ }
47
+ });
48
+
49
+ test("staging sends an invitation for someone else only to STAGING_EMAIL_TO, saying whom it was for", async () => {
50
+ const { logs, sent, mailer } = mailerIn({ ...DEPLOYED, APP_ENV: "staging", STAGING_EMAIL_TO: "qa@example.test" });
51
+ const options = { trx: null };
52
+ assert.deepEqual(await mailer.sendWorkspaceInvite(INVITE, options), { status: "sent", providerMessageId: "m-1" });
53
+ assert.equal(sent.length, 1);
54
+ const [{ invite, options: passed }] = sent;
55
+ assert.equal(passed, options);
56
+ assert.equal(invite.email, "qa@example.test", "never to the guest");
57
+ assert.equal(invite.inviteUrl, INVITE.inviteUrl);
58
+ assert.deepEqual(invite.message, {
59
+ subject: "You're invited to Books",
60
+ text: "Staging: this email was for guest@example.com.\n\nJoin us",
61
+ html: "<p>Staging: this email was for guest@example.com.</p><p>Join us</p>",
62
+ headers: { "X-Staging-Original-To": "guest@example.com" }
63
+ });
64
+ assert.equal(logs.at(-1).message,
65
+ "Staging: the workspace invitation email to guest@example.com was sent to qa@example.test (STAGING_EMAIL_TO) instead.");
66
+ });
67
+
68
+ test("staging without STAGING_EMAIL_TO logs each invitation, and production sends it to its address unmarked", async () => {
69
+ const staging = mailerIn({ ...DEPLOYED, APP_ENV: "staging" });
70
+ assert.equal((await staging.mailer.sendWorkspaceInvite(INVITE, {})).status, "simulated");
71
+ assert.equal(staging.sent.length, 0);
72
+ assert.match(staging.logs[0].message, /was logged, not sent: STAGING_EMAIL_TO is not set\.$/u);
73
+
74
+ const production = mailerIn({ ...DEPLOYED, APP_ENV: "production", STAGING_EMAIL_TO: "qa@example.test" });
75
+ assert.equal((await production.mailer.sendWorkspaceInvite(INVITE, {})).status, "sent");
76
+ assert.deepEqual(production.sent[0].invite, INVITE);
77
+ });
@@ -73,7 +73,7 @@ test("WorkspacesFeature assembles workspace behavior and explicit integrations",
73
73
  "runtime.app-root": process.cwd(),
74
74
  "runtime.bootstrap": bootstrap,
75
75
  "runtime.config": runtimeConfig(),
76
- "runtime.env": {},
76
+ "runtime.env": { APP_ENV: "test" },
77
77
  "runtime.http": {
78
78
  router: {
79
79
  register(method, path) {
@@ -68,7 +68,7 @@ async function membersApp(t) {
68
68
  "runtime.app-root": process.cwd(),
69
69
  "runtime.bootstrap": createBootstrapRuntime(),
70
70
  "runtime.config": config,
71
- "runtime.env": {},
71
+ "runtime.env": { APP_ENV: "test" },
72
72
  "runtime.fastify": app
73
73
  }
74
74
  });
@@ -201,7 +201,7 @@ async function issuesApp(t) {
201
201
  "runtime.app-root": process.cwd(),
202
202
  "runtime.bootstrap": createBootstrapRuntime(),
203
203
  "runtime.config": config,
204
- "runtime.env": {},
204
+ "runtime.env": { APP_ENV: "test" },
205
205
  "runtime.fastify": app
206
206
  }
207
207
  });
@@ -40,7 +40,7 @@ function captureLogger() {
40
40
  return { warnings, logger: { debug: ignore, info: ignore, error: ignore, warn: (...args) => warnings.push(args) } };
41
41
  }
42
42
 
43
- function startRuntime({ config, env = {}, logger = captureLogger().logger, workspacesEnabled = true, routes = [] }) {
43
+ function startRuntime({ config, env = { APP_ENV: "test" }, logger = captureLogger().logger, workspacesEnabled = true, routes = [] }) {
44
44
  const workspaces = defineProvider({
45
45
  id: "test.workspaces",
46
46
  provides: { workspaces: "workspaces.core" },
@@ -58,9 +58,9 @@ function startRuntime({ config, env = {}, logger = captureLogger().logger, works
58
58
  return runtime.start();
59
59
  }
60
60
 
61
- test("outside production the server refuses to start while a role grants a permission no action requires", async () => {
61
+ test("in development and test the server refuses to start while a role grants a permission no action requires", async () => {
62
62
  await assert.rejects(
63
- startRuntime({ config: memberGrants(["crud.labels.list", "crud.labels.patch"]), env: { NODE_ENV: "test" } }),
63
+ startRuntime({ config: memberGrants(["crud.labels.list", "crud.labels.patch"]), env: { APP_ENV: "test" } }),
64
64
  (error) => {
65
65
  assert.match(error.message, /Role "member" grants "crud\.labels\.patch", which no action requires; did you mean "crud\.labels\.update"\?/u);
66
66
  assert.match(
@@ -72,18 +72,20 @@ test("outside production the server refuses to start while a role grants a permi
72
72
  }
73
73
  );
74
74
  await assert.rejects(
75
- startRuntime({ config: memberGrants(["crud.labels.patch"]) }),
75
+ startRuntime({ config: memberGrants(["crud.labels.patch"]), env: { APP_ENV: "development", NODE_ENV: "production" } }),
76
76
  /crud\.labels\.patch/u,
77
- "an unset NODE_ENV is development"
77
+ "NODE_ENV decides nothing"
78
78
  );
79
79
  });
80
80
 
81
- test("in production the server starts and logs the grant as a warning", async () => {
82
- const { warnings, logger } = captureLogger();
83
- await startRuntime({ config: memberGrants(["crud.labels.patch"]), env: { NODE_ENV: "production" }, logger });
81
+ test("in staging and production the server starts and logs the grant as a warning", async () => {
82
+ for (const APP_ENV of ["staging", "production"]) {
83
+ const { warnings, logger } = captureLogger();
84
+ await startRuntime({ config: memberGrants(["crud.labels.patch"]), env: { APP_ENV, NODE_ENV: "production" }, logger });
84
85
 
85
- assert.equal(warnings.length, 1);
86
- assert.match(String(warnings[0].at(-1)), /Role "member" grants "crud\.labels\.patch", which no action requires; did you mean "crud\.labels\.update"\?/u);
86
+ assert.equal(warnings.length, 1, APP_ENV);
87
+ assert.match(String(warnings[0].at(-1)), /Role "member" grants "crud\.labels\.patch", which no action requires; did you mean "crud\.labels\.update"\?/u);
88
+ }
87
89
  });
88
90
 
89
91
  test("a role catalogue whose grants each cover a required permission starts quietly", async () => {
@@ -1,29 +0,0 @@
1
- import { logSimulatedSideEffect } from "@jskit-ai/kernel/server/runtime/sideEffects";
2
-
3
- /**
4
- * The invite mailer of a test copy (SIDE_EFFECTS is not `live`) in place of the provided
5
- * `workspaces.invite-mailer`: it emails nothing, logs the invitation's recipient, subject and link, and reports the
6
- * delivery as simulated, so the inviter copies the link to share it.
7
- * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} logger
8
- * @returns {import("../types.js").WorkspaceInviteMailer}
9
- */
10
- function createSimulatedWorkspaceInviteMailer(logger) {
11
- async function sendWorkspaceInvite({ email, inviteUrl, message }) {
12
- logSimulatedSideEffect(logger, {
13
- kind: "email",
14
- summary: `the workspace invitation email to ${email}`,
15
- details: { email, subject: String(message?.subject || ""), inviteUrl }
16
- });
17
- return {
18
- status: "simulated",
19
- message: "Test copy: the invitation email was not sent. Copy the invite link to share it.",
20
- messageCode: "workspaces.invite.simulated",
21
- messageParams: {},
22
- providerMessageId: ""
23
- };
24
- }
25
-
26
- return Object.freeze({ sendWorkspaceInvite });
27
- }
28
-
29
- export { createSimulatedWorkspaceInviteMailer };
@@ -1,29 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import test from "node:test";
3
- import { createSimulatedWorkspaceInviteMailer } from "../src/server/workspaceMembers/simulatedWorkspaceInviteMailer.js";
4
-
5
- test("a test copy's invite mailer sends nothing, logs the invitation and reports it simulated", async () => {
6
- const logs = [];
7
- const mailer = createSimulatedWorkspaceInviteMailer({
8
- info: (details, message) => logs.push({ details, message }),
9
- warn() {},
10
- error() {},
11
- debug() {}
12
- });
13
- const delivery = await mailer.sendWorkspaceInvite({
14
- email: "guest@example.com",
15
- inviteUrl: "https://app.example.test/invite?token=abc",
16
- message: { subject: "You're invited to Books", text: "Join us", html: "<p>Join us</p>" }
17
- });
18
- assert.equal(delivery.status, "simulated");
19
- assert.equal(delivery.messageCode, "workspaces.invite.simulated");
20
- assert.equal(logs.length, 1);
21
- assert.deepEqual(logs[0].details, {
22
- sideEffects: "simulate",
23
- kind: "email",
24
- email: "guest@example.com",
25
- subject: "You're invited to Books",
26
- inviteUrl: "https://app.example.test/invite?token=abc"
27
- });
28
- assert.match(logs[0].message, /^Test copy: the workspace invitation email to guest@example\.com was simulated, not sent/u);
29
- });