@terreno/api 58.0.6 → 58.1.0

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 (75) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/actions.d.ts +6 -0
  3. package/dist/api.d.ts +21 -0
  4. package/dist/api.js +57 -32
  5. package/dist/bulk.d.ts +79 -0
  6. package/dist/bulk.js +449 -0
  7. package/dist/bulkOpenApi.d.ts +15 -0
  8. package/dist/bulkOpenApi.js +103 -0
  9. package/dist/bulkTransaction.d.ts +33 -0
  10. package/dist/bulkTransaction.js +126 -0
  11. package/dist/errors.d.ts +2 -0
  12. package/dist/errors.js +8 -6
  13. package/dist/index.d.ts +3 -2
  14. package/dist/index.js +6 -3
  15. package/dist/mcp/actionTools.js +2 -0
  16. package/dist/mcp/grantAccess.d.ts +27 -0
  17. package/dist/mcp/grantAccess.js +29 -0
  18. package/dist/mcp/oauth.js +86 -5
  19. package/dist/mcp/oauthMetadata.d.ts +32 -1
  20. package/dist/mcp/oauthMetadata.js +53 -2
  21. package/dist/mcp/registry.d.ts +8 -1
  22. package/dist/mcp/server.js +6 -1
  23. package/dist/mcp/toolGenerator.d.ts +5 -1
  24. package/dist/mcp/toolGenerator.js +11 -0
  25. package/dist/mcp/types.d.ts +11 -0
  26. package/dist/modelRouterWrites.d.ts +23 -0
  27. package/dist/modelRouterWrites.js +54 -0
  28. package/dist/openApi.d.ts +7 -0
  29. package/dist/openApi.js +6 -6
  30. package/dist/permissions.js +5 -4
  31. package/dist/rbac/access.js +2 -0
  32. package/dist/rbac/routes.js +1 -0
  33. package/dist/rbac/statements.d.ts +12 -1
  34. package/dist/rbac/statements.js +89 -1
  35. package/dist/rbac/types.d.ts +9 -2
  36. package/dist/sync/executors.d.ts +6 -4
  37. package/dist/sync/executors.js +6 -2
  38. package/package.json +6 -6
  39. package/src/actions.ts +6 -0
  40. package/src/api.ts +95 -33
  41. package/src/bulk.test.ts +1256 -0
  42. package/src/bulk.ts +680 -0
  43. package/src/bulkOpenApi.test.ts +172 -0
  44. package/src/bulkOpenApi.ts +126 -0
  45. package/src/bulkTransaction.test.ts +197 -0
  46. package/src/bulkTransaction.ts +149 -0
  47. package/src/errors.ts +2 -2
  48. package/src/index.ts +6 -0
  49. package/src/isolated/bulkAtomic.isolated.ts +630 -0
  50. package/src/isolated/bulkStandalone.isolated.ts +133 -0
  51. package/src/isolated/mongoTopology.isolated.ts +29 -0
  52. package/src/mcp/actionTools.ts +2 -0
  53. package/src/mcp/grantAccess.test.ts +107 -0
  54. package/src/mcp/grantAccess.ts +49 -0
  55. package/src/mcp/oauth.test.ts +327 -0
  56. package/src/mcp/oauth.ts +113 -5
  57. package/src/mcp/oauthMetadata.test.ts +125 -1
  58. package/src/mcp/oauthMetadata.ts +99 -2
  59. package/src/mcp/registry.ts +8 -1
  60. package/src/mcp/server.test.ts +419 -2
  61. package/src/mcp/server.ts +8 -1
  62. package/src/mcp/toolGenerator.ts +17 -0
  63. package/src/mcp/types.ts +12 -0
  64. package/src/modelRouterWrites.ts +72 -0
  65. package/src/openApi.ts +1 -1
  66. package/src/permissions.ts +5 -5
  67. package/src/rbac/access.ts +3 -1
  68. package/src/rbac/routes.test.ts +15 -0
  69. package/src/rbac/routes.ts +1 -0
  70. package/src/rbac/statements.test.ts +23 -0
  71. package/src/rbac/statements.ts +100 -1
  72. package/src/rbac/types.ts +9 -2
  73. package/src/sync/executors.test.ts +27 -0
  74. package/src/sync/executors.ts +12 -4
  75. package/src/tests/mongoTopology.ts +53 -0
@@ -82,6 +82,10 @@ describe("rbacRouter", () => {
82
82
  const access = createAccess({
83
83
  connection: mongoose.connection,
84
84
  resolvePermissions: async ({user}) => (user.admin ? allPermissions : {}),
85
+ statementDescriptions: {
86
+ todo: {read: "View a todo", update: " "},
87
+ user: {manageSecurity: "Custom security label"},
88
+ },
85
89
  statements: appStatements,
86
90
  userModel: routeUserModel as unknown as AuthUserModel,
87
91
  });
@@ -122,6 +126,17 @@ describe("rbacRouter", () => {
122
126
  "manageRoles",
123
127
  "assignRoles",
124
128
  ]);
129
+ expect(statementsResponse.body.data.statementDescriptions.todo.read).toBe("View a todo");
130
+ expect(statementsResponse.body.data.statementDescriptions.todo.update).toBeUndefined();
131
+ expect(statementsResponse.body.data.statementDescriptions.user.manageSecurity).toBe(
132
+ "Custom security label"
133
+ );
134
+ expect(statementsResponse.body.data.statementDescriptions.user.updateIdentity).toContain(
135
+ "email"
136
+ );
137
+ expect(statementsResponse.body.data.statementDescriptions.admin.access).toBe(
138
+ "Open the admin panel"
139
+ );
125
140
 
126
141
  const rolesResponse = await adminAgent.get("/rbac/roles").expect(200);
127
142
  expect(rolesResponse.body.data.map((role: {name: string}) => role.name)).toEqual(
@@ -35,6 +35,7 @@ export const rbacRouter = ({
35
35
  asyncHandler(async (_req, res) => {
36
36
  return res.json({
37
37
  data: {
38
+ statementDescriptions: access.statementDescriptions,
38
39
  statements: access.statements,
39
40
  },
40
41
  });
@@ -9,6 +9,7 @@ import {
9
9
  AI_TRACE_ACTIONS,
10
10
  expandRolePermissions,
11
11
  mergeMissingResourcePermissions,
12
+ mergeStatementDescriptions,
12
13
  mergeStatements,
13
14
  OBSERVABILITY_RBAC_RESOURCES,
14
15
  READ_ACTIONS,
@@ -132,6 +133,28 @@ describe("rbac statements", () => {
132
133
  expect(Object.keys(terrenoStatementDescriptions.aiTrace ?? {})).toEqual(["list", "read"]);
133
134
  });
134
135
 
136
+ it("describes every terreno statement action", () => {
137
+ for (const [resource, actions] of Object.entries(terrenoStatements)) {
138
+ for (const action of actions) {
139
+ const description = terrenoStatementDescriptions[resource]?.[action];
140
+ assert.isString(description, `${resource}.${action}`);
141
+ assert.isAbove((description ?? "").trim().length, 0, `${resource}.${action}`);
142
+ }
143
+ }
144
+ });
145
+
146
+ it("merges app descriptions over framework labels and ignores blanks", () => {
147
+ const merged = mergeStatementDescriptions({
148
+ patient: {read: " View a patient chart "},
149
+ user: {manageSecurity: "Custom security label", updateIdentity: " "},
150
+ });
151
+
152
+ assert.equal(merged.patient?.read, "View a patient chart");
153
+ assert.equal(merged.user?.manageSecurity, "Custom security label");
154
+ assert.include(merged.user?.updateIdentity ?? "", "email");
155
+ assert.equal(merged.admin?.access, "Open the admin panel");
156
+ });
157
+
135
158
  it("mergeMissingResourcePermissions adds actions without removing custom grants", () => {
136
159
  const defaults = {
137
160
  aiPrompt: [...terrenoStatements.aiPrompt],
@@ -83,6 +83,11 @@ export type Statements = Record<string, readonly string[]>;
83
83
 
84
84
  export type PermissionSet = {[resource: string]: readonly string[]};
85
85
 
86
+ /** Optional human labels for permissions, keyed by resource then action. */
87
+ export interface StatementDescriptions {
88
+ [resource: string]: Record<string, string>;
89
+ }
90
+
86
91
  export const READ_ACTIONS = ["read", "list", "view"] as const;
87
92
 
88
93
  export const READ_ONLY_ROLE_PERMISSIONS = {readOnly: true} as const;
@@ -103,7 +108,34 @@ export const mergeStatements = <S extends Statements>(appStatements: S): Stateme
103
108
  };
104
109
  };
105
110
 
106
- export const terrenoStatementDescriptions: Record<string, Record<string, string>> = {
111
+ export const adminModelDescriptions = (noun: string): Record<string, string> => ({
112
+ read: `View ${noun} in the admin panel`,
113
+ write: `Create and update any ${noun} in the admin panel`,
114
+ writeOwned: `Create and update ${noun} you own in the admin panel`,
115
+ });
116
+
117
+ export const modelCrudDescriptions = (noun: string): Record<string, string> => ({
118
+ create: `Create ${noun}`,
119
+ delete: `Delete ${noun}`,
120
+ list: `List ${noun}`,
121
+ read: `View ${noun}`,
122
+ update: `Update ${noun}`,
123
+ });
124
+
125
+ export const terrenoStatementDescriptions: StatementDescriptions = {
126
+ admin: {
127
+ access: "Open the admin panel",
128
+ jobs: "Open the jobs admin screen",
129
+ runScripts: "Run admin scripts",
130
+ viewBackgroundTasks: "View background tasks",
131
+ },
132
+ adminAnnouncement: adminModelDescriptions("announcements"),
133
+ adminAnnouncementAcknowledgement: adminModelDescriptions("announcement acknowledgements"),
134
+ adminAnnouncementClickEvent: adminModelDescriptions("announcement click events"),
135
+ adminAnnouncementImpression: adminModelDescriptions("announcement impressions"),
136
+ adminConsentForm: adminModelDescriptions("consent forms"),
137
+ adminConsentResponse: adminModelDescriptions("consent responses"),
138
+ adminFeatureFlag: adminModelDescriptions("feature flags"),
107
139
  aiDataset: {
108
140
  create: "Create datasets",
109
141
  delete: "Delete datasets",
@@ -142,20 +174,87 @@ export const terrenoStatementDescriptions: Record<string, Record<string, string>
142
174
  list: "List traces and observability status",
143
175
  read: "View trace detail and run trace test helpers",
144
176
  },
177
+ announcement: modelCrudDescriptions("announcements"),
178
+ announcementAcknowledgement: {
179
+ list: "List announcement acknowledgements",
180
+ read: "View announcement acknowledgements",
181
+ },
182
+ announcementImpression: {
183
+ list: "List announcement impressions",
184
+ read: "View announcement impressions",
185
+ },
186
+ configuration: {
187
+ read: "View configuration",
188
+ update: "Update configuration",
189
+ },
190
+ consentForm: modelCrudDescriptions("consent forms"),
145
191
  consentResponse: {
146
192
  list: "List consent responses",
147
193
  read: "View consent responses",
148
194
  signOnBehalf: "Record, view, and void provisional consent signatures for other users",
149
195
  },
196
+ featureFlag: modelCrudDescriptions("feature flags"),
197
+ organization: {
198
+ create: "Create organizations",
199
+ delete: "Delete organizations",
200
+ disable: "Disable an organization",
201
+ list: "List organizations",
202
+ manageMembers: "Add, update, and remove organization members",
203
+ read: "View an organization",
204
+ update: "Update an organization",
205
+ },
206
+ rbac: {
207
+ assignRoles: "Assign roles to users",
208
+ manageRoles: "Create and edit roles",
209
+ read: "View roles and the permission vocabulary",
210
+ },
150
211
  user: {
212
+ ...modelCrudDescriptions("users"),
213
+ impersonate: "Sign in as another user",
151
214
  issueSignInLink:
152
215
  "Create a sign-in account for a legacy user and hand them a set-password link (AccountSecurityApp)",
153
216
  manageSecurity: "View any user's sign-in methods and run account recovery (AccountSecurityApp)",
217
+ setPassword: "Set another user's password",
154
218
  updateIdentity:
155
219
  "Change another user's email, disabled flag, email verification, or linked Better Auth and GitHub ids",
156
220
  },
157
221
  };
158
222
 
223
+ const copyStatementDescriptions = (
224
+ target: StatementDescriptions,
225
+ source: StatementDescriptions | undefined
226
+ ): void => {
227
+ for (const [resource, actions] of Object.entries(source ?? {})) {
228
+ const next: Record<string, string> = {...(target[resource] ?? {})};
229
+ for (const [action, description] of Object.entries(actions ?? {})) {
230
+ if (typeof description !== "string") {
231
+ continue;
232
+ }
233
+ const trimmed = description.trim();
234
+ if (trimmed.length === 0) {
235
+ continue;
236
+ }
237
+ next[action] = trimmed;
238
+ }
239
+ if (Object.keys(next).length > 0) {
240
+ target[resource] = next;
241
+ }
242
+ }
243
+ };
244
+
245
+ /**
246
+ * Framework labels, then the app's. An app label replaces the framework label for that
247
+ * action. A blank string is ignored, so it does not erase a framework label.
248
+ */
249
+ export const mergeStatementDescriptions = (
250
+ appDescriptions?: StatementDescriptions
251
+ ): StatementDescriptions => {
252
+ const merged: StatementDescriptions = {};
253
+ copyStatementDescriptions(merged, terrenoStatementDescriptions);
254
+ copyStatementDescriptions(merged, appDescriptions);
255
+ return merged;
256
+ };
257
+
159
258
  /** Add missing actions for selected resources without removing consumer-defined grants. */
160
259
  export const mergeMissingResourcePermissions = (
161
260
  existing: PermissionSet,
package/src/rbac/types.ts CHANGED
@@ -7,7 +7,7 @@ import type {User, UserModel} from "../auth";
7
7
  import type {PermissionMethod} from "../permissions";
8
8
  import type {RbacAuditWrite} from "./auditModel";
9
9
  import type {RbacRoleDocument, RoleDefinition} from "./roleModel";
10
- import type {PermissionSet, Statements} from "./statements";
10
+ import type {PermissionSet, StatementDescriptions, Statements} from "./statements";
11
11
 
12
12
  /**
13
13
  * Non-generic TerrenoAccess for runtime wiring (modelRouter, rbacRouter, TerrenoApp).
@@ -170,7 +170,12 @@ export interface AccessOptions<S extends Statements> {
170
170
  readActions?: readonly string[];
171
171
  cacheTtlMs?: number;
172
172
  resolvePermissions?: (args: {user: User}) => Promise<PermissionSet | null>;
173
- statementDescriptions?: Record<string, Record<string, string>>;
173
+ /**
174
+ * Optional labels for permissions (resource → action → description). Merged over
175
+ * `terrenoStatementDescriptions`; a blank string does not erase a framework label.
176
+ * Returned by `GET /rbac/statements`.
177
+ */
178
+ statementDescriptions?: StatementDescriptions;
174
179
  /**
175
180
  * Extra destinations for RoleManager audit records (e.g. a consuming-app audit log).
176
181
  * The built-in `RbacAudit` collection is still written unless `persistAudit` is false.
@@ -185,6 +190,8 @@ export interface AccessOptions<S extends Statements> {
185
190
 
186
191
  export interface TerrenoAccess<S extends Statements> {
187
192
  readonly statements: S;
193
+ /** Labels for permissions, including framework defaults and `createAccess` overrides. */
194
+ readonly statementDescriptions: StatementDescriptions;
188
195
  readonly ac: ReturnType<typeof createAccessControl<S>>;
189
196
  can: (args: AccessCheckArgs<S>) => Promise<AccessResult>;
190
197
  /**
@@ -816,6 +816,33 @@ describe("executeDelete", () => {
816
816
  expect(tombstones).toHaveLength(1);
817
817
  });
818
818
 
819
+ it("returns prevDoc with deleted not true when skipPostHooks is true", async () => {
820
+ const doc = await createDoc({name: "before-delete"});
821
+ const result = (await executeDelete<ExecStuff>({
822
+ id: doc._id.toString(),
823
+ model: ExecStuffModel,
824
+ options: baseOptions(),
825
+ skipPostHooks: true,
826
+ user: owner,
827
+ })) as {doc: ExecStuff; prevDoc?: ExecStuff};
828
+ expect(result.doc.deleted).toBe(true);
829
+ expect(result.prevDoc).toBeDefined();
830
+ expect(result.prevDoc?.deleted).not.toBe(true);
831
+ expect(result.prevDoc?.name).toBe("before-delete");
832
+ expect(String(result.prevDoc?._id)).toBe(doc._id.toString());
833
+ });
834
+
835
+ it("does not return prevDoc when skipPostHooks is not set", async () => {
836
+ const doc = await createDoc();
837
+ const result = (await executeDelete<ExecStuff>({
838
+ id: doc._id.toString(),
839
+ model: ExecStuffModel,
840
+ options: baseOptions(),
841
+ user: owner,
842
+ })) as {doc: ExecStuff; prevDoc?: ExecStuff};
843
+ expect(result.prevDoc).toBeUndefined();
844
+ });
845
+
819
846
  it("returns an authorized string-id tombstone for an idempotent delete", async () => {
820
847
  const id = "offline-generated-id";
821
848
  await ExecStringIdStuffModel.create({
@@ -22,6 +22,10 @@ import type {Document, Model} from "mongoose";
22
22
  import {addPopulateToQuery, type ModelRouterOptions} from "../api";
23
23
  import {omitUserRolesFromWriteBody, type User} from "../auth";
24
24
  import {loadDocOr404} from "../docLoader";
25
+
26
+ /** Re-exported so `api.ts` can hand it to the bulk route without importing `docLoader` itself. */
27
+ export {loadDocOr404};
28
+
25
29
  import {
26
30
  APIError,
27
31
  type APIErrorConstructor,
@@ -55,9 +59,9 @@ export interface ExecutorResult<T> {
55
59
  */
56
60
  cleanedBody?: Partial<T>;
57
61
  /**
58
- * C5 (FIX 6): present only when `executeUpdate` was called with
59
- * `skipPostHooks: true` — the pre-update document snapshot, needed to
60
- * run `postUpdate` later via `runPostUpdate`.
62
+ * C5 (FIX 6): present only when `executeUpdate` or `executeDelete` was called with
63
+ * `skipPostHooks: true` — the document snapshot from before the write, needed to run
64
+ * `postUpdate` later via `runPostUpdate` and for audit `before` snapshots.
61
65
  */
62
66
  prevDoc?: T;
63
67
  }
@@ -924,6 +928,10 @@ export const executeDelete = async <T>({
924
928
  }
925
929
  }
926
930
 
931
+ // The caller that defers postDelete (bulk, sync) also needs the doc as it was before the
932
+ // tombstone, e.g. for the audit `before` snapshot.
933
+ const prevDoc = skipPostHooks ? (cloneDeep(doc) as T) : undefined;
934
+
927
935
  // Support .deleted from isDeleted plugin
928
936
  if (
929
937
  Object.keys(model.schema.paths).includes("deleted") &&
@@ -956,7 +964,7 @@ export const executeDelete = async <T>({
956
964
  }
957
965
  }
958
966
 
959
- return {doc};
967
+ return prevDoc ? {doc, prevDoc} : {doc};
960
968
  };
961
969
 
962
970
  /** C5 (FIX 6): run `postDelete` outside the write/ledger-finalize window — see `runPostCreate`. */
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Swaps the default mongoose connection to an in-memory Mongo of a chosen topology for one
3
+ * test file. The api preload connects to whatever `TERRENO_TEST_MONGODB_URI` or the local
4
+ * default points at, which is a standalone server on CI and may be a replica set on a dev
5
+ * machine. Tests that depend on the topology (transactions need a replica set; the
6
+ * "transactions unsupported" path needs a standalone) call this in an `*.isolated.ts` file,
7
+ * which runs in a process of its own, so the swap never leaks into other suites.
8
+ */
9
+ import {afterAll, beforeAll} from "bun:test";
10
+ import {resolveMongoLaunchTimeoutMs} from "@terreno/test";
11
+ import {MongoMemoryReplSet, MongoMemoryServer} from "mongodb-memory-server";
12
+ import mongoose from "mongoose";
13
+
14
+ export type MongoTopology = "replicaSet" | "standalone";
15
+
16
+ interface MemoryMongo {
17
+ getUri: () => string;
18
+ stop: () => Promise<boolean>;
19
+ }
20
+
21
+ const startMemoryMongo = async (topology: MongoTopology): Promise<MemoryMongo> => {
22
+ const launchTimeout = resolveMongoLaunchTimeoutMs();
23
+ if (topology === "standalone") {
24
+ return MongoMemoryServer.create({instance: {launchTimeout}});
25
+ }
26
+ return MongoMemoryReplSet.create({
27
+ instanceOpts: [{launchTimeout}],
28
+ replSet: {count: 1, storageEngine: "wiredTiger"},
29
+ });
30
+ };
31
+
32
+ /**
33
+ * Registers `beforeAll` / `afterAll` hooks that reconnect mongoose to a fresh in-memory Mongo
34
+ * with the given topology, then disconnect and stop it. Call at the top level of an
35
+ * `*.isolated.ts` file, after the imports.
36
+ */
37
+ export const useMongoTopology = ({topology}: {topology: MongoTopology}): void => {
38
+ let memoryMongo: MemoryMongo | undefined;
39
+
40
+ // Replace the preload's connection before any test in this file touches a model.
41
+ beforeAll(async () => {
42
+ memoryMongo = await startMemoryMongo(topology);
43
+ await mongoose.disconnect();
44
+ await mongoose.connect(memoryMongo.getUri(), {dbName: "terrenoTopologyTest"});
45
+ await Promise.all(Object.values(mongoose.models).map((model) => model.init()));
46
+ }, 120_000);
47
+
48
+ // Stop the in-memory server; the preload's afterAll closes whatever connection remains.
49
+ afterAll(async () => {
50
+ await mongoose.disconnect();
51
+ await memoryMongo?.stop();
52
+ }, 60_000);
53
+ };