@terreno/ai 0.10.0 → 0.11.1

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.
@@ -86,7 +86,9 @@ describe("FileAttachment Model", () => {
86
86
  userId,
87
87
  });
88
88
 
89
- expect((attachment as any).ownerId.toString()).toBe(userId.toString());
89
+ expect((attachment as unknown as {ownerId: mongoose.Types.ObjectId}).ownerId.toString()).toBe(
90
+ userId.toString()
91
+ );
90
92
  });
91
93
  });
92
94
 
@@ -0,0 +1,126 @@
1
+ import {beforeAll, beforeEach, describe, expect, it, mock} from "bun:test";
2
+ import {createdUpdatedPlugin, setupServer} from "@terreno/api";
3
+ import type express from "express";
4
+ import mongoose from "mongoose";
5
+ import passportLocalMongoose from "passport-local-mongoose";
6
+ import supertest from "supertest";
7
+
8
+ import {FileAttachment} from "../models/fileAttachment";
9
+ import type {FileStorageService, UploadFileParams, UploadFileResult} from "../service/fileStorage";
10
+ import {addFileRoutes} from "./files";
11
+
12
+ type PasswordedUser = {setPassword: (password: string) => Promise<void>};
13
+ type MockFileStorageService = Pick<FileStorageService, "upload" | "delete" | "getSignedUrl">;
14
+
15
+ const userSchema = new mongoose.Schema({
16
+ admin: {default: false, type: Boolean},
17
+ email: {index: true, type: String},
18
+ name: String,
19
+ });
20
+ userSchema.plugin(
21
+ passportLocalMongoose as unknown as (
22
+ schema: mongoose.Schema,
23
+ options: {usernameField: string}
24
+ ) => void,
25
+ {usernameField: "email"}
26
+ );
27
+ userSchema.plugin(createdUpdatedPlugin);
28
+ const UserModel = mongoose.models.User || mongoose.model("User", userSchema);
29
+
30
+ const authAsUser = async (appInstance: express.Application, type: "admin" | "notAdmin") => {
31
+ const email = type === "admin" ? "admin@example.com" : "notAdmin@example.com";
32
+ const password = type === "admin" ? "securePassword" : "password";
33
+ const agent = supertest.agent(appInstance);
34
+ const res = await agent.post("/auth/login").send({email, password}).expect(200);
35
+ await agent.set("authorization", `Bearer ${res.body.data.token}`);
36
+ return agent;
37
+ };
38
+
39
+ describe("File Routes", () => {
40
+ let app: express.Application;
41
+ let fileStorageService: MockFileStorageService;
42
+
43
+ beforeAll(async () => {
44
+ await UserModel.deleteMany({});
45
+ const admin = await UserModel.create({admin: true, email: "admin@example.com", name: "Admin"});
46
+ await (admin as unknown as PasswordedUser).setPassword("securePassword");
47
+ await admin.save();
48
+ const user = await UserModel.create({email: "notAdmin@example.com", name: "User"});
49
+ await (user as unknown as PasswordedUser).setPassword("password");
50
+ await user.save();
51
+ });
52
+
53
+ beforeEach(async () => {
54
+ await FileAttachment.deleteMany({});
55
+ fileStorageService = {
56
+ delete: mock(async () => {}),
57
+ getSignedUrl: mock(async () => "https://example.com/signed"),
58
+ upload: mock(
59
+ async (params: UploadFileParams): Promise<UploadFileResult> => ({
60
+ filename: params.filename,
61
+ gcsKey: `uploads/${params.userId.toString()}/${params.filename}`,
62
+ mimeType: params.mimeType,
63
+ size: params.buffer.length,
64
+ url: `https://example.com/${params.filename}`,
65
+ })
66
+ ),
67
+ };
68
+ app = setupServer({
69
+ addRoutes: (router, options) => {
70
+ addFileRoutes(router, {
71
+ fileStorageService: fileStorageService as FileStorageService,
72
+ openApiOptions: options,
73
+ });
74
+ },
75
+ skipListen: true,
76
+ userModel: UserModel,
77
+ });
78
+ });
79
+
80
+ describe("POST /files/upload", () => {
81
+ it("uploads a file", async () => {
82
+ const agent = await authAsUser(app, "notAdmin");
83
+ const res = await agent
84
+ .post("/files/upload")
85
+ .attach("file", Buffer.from("hello"), {contentType: "text/plain", filename: "hi.txt"});
86
+ expect(res.status).toBe(200);
87
+ expect(res.body.data.filename).toBe("hi.txt");
88
+ expect(fileStorageService.upload as ReturnType<typeof mock>).toHaveBeenCalledTimes(1);
89
+ });
90
+
91
+ it("rejects when no file is provided", async () => {
92
+ const agent = await authAsUser(app, "notAdmin");
93
+ const res = await agent.post("/files/upload");
94
+ expect(res.status).toBe(400);
95
+ });
96
+
97
+ it("rejects unsupported mime types", async () => {
98
+ const agent = await authAsUser(app, "notAdmin");
99
+ const res = await agent.post("/files/upload").attach("file", Buffer.from("<html></html>"), {
100
+ contentType: "application/x-sh",
101
+ filename: "danger.sh",
102
+ });
103
+ expect(res.status).toBe(500);
104
+ });
105
+ });
106
+
107
+ describe("GET /files/*gcsKey", () => {
108
+ it("returns 404 when the file is missing", async () => {
109
+ const res = await supertest(app).get("/files/missing/key.txt");
110
+ expect(res.status).toBe(404);
111
+ });
112
+ });
113
+
114
+ describe("DELETE /files/*gcsKey", () => {
115
+ it("returns 404 when the file is missing", async () => {
116
+ const agent = await authAsUser(app, "notAdmin");
117
+ const res = await agent.delete("/files/uploads/missing/key.txt");
118
+ expect(res.status).toBe(404);
119
+ });
120
+
121
+ it("requires authentication", async () => {
122
+ const res = await supertest(app).delete("/files/any/thing.txt");
123
+ expect(res.status).toBe(401);
124
+ });
125
+ });
126
+ });
@@ -0,0 +1,132 @@
1
+ import {beforeAll, beforeEach, describe, expect, it, mock} from "bun:test";
2
+ import {createdUpdatedPlugin, setupServer} from "@terreno/api";
3
+ import type express from "express";
4
+ import mongoose from "mongoose";
5
+ import passportLocalMongoose from "passport-local-mongoose";
6
+ import supertest from "supertest";
7
+
8
+ import type {MCPService} from "../service/mcpService";
9
+ import {addMcpRoutes} from "./mcp";
10
+
11
+ type PasswordedUser = {setPassword: (password: string) => Promise<void>};
12
+ type MockMcpService = Pick<MCPService, "getServerStatus" | "getTools" | "reconnectServer">;
13
+
14
+ const userSchema = new mongoose.Schema({
15
+ admin: {default: false, type: Boolean},
16
+ email: {index: true, type: String},
17
+ name: String,
18
+ });
19
+ userSchema.plugin(
20
+ passportLocalMongoose as unknown as (
21
+ schema: mongoose.Schema,
22
+ options: {usernameField: string}
23
+ ) => void,
24
+ {usernameField: "email"}
25
+ );
26
+ userSchema.plugin(createdUpdatedPlugin);
27
+ const UserModel = mongoose.models.User || mongoose.model("User", userSchema);
28
+
29
+ const authAsUser = async (appInstance: express.Application, type: "admin" | "notAdmin") => {
30
+ const email = type === "admin" ? "admin@example.com" : "notAdmin@example.com";
31
+ const password = type === "admin" ? "securePassword" : "password";
32
+ const agent = supertest.agent(appInstance);
33
+ const res = await agent.post("/auth/login").send({email, password}).expect(200);
34
+ await agent.set("authorization", `Bearer ${res.body.data.token}`);
35
+ return agent;
36
+ };
37
+
38
+ describe("MCP Routes", () => {
39
+ let app: express.Application;
40
+ let mcpService: MockMcpService;
41
+
42
+ beforeAll(async () => {
43
+ await UserModel.deleteMany({});
44
+ const admin = await UserModel.create({admin: true, email: "admin@example.com", name: "Admin"});
45
+ await (admin as unknown as PasswordedUser).setPassword("securePassword");
46
+ await admin.save();
47
+ const user = await UserModel.create({email: "notAdmin@example.com", name: "User"});
48
+ await (user as unknown as PasswordedUser).setPassword("password");
49
+ await user.save();
50
+ });
51
+
52
+ beforeEach(() => {
53
+ mcpService = {
54
+ getServerStatus: mock(() => [{connected: true, name: "test-server"}]),
55
+ getTools: mock(async () => ({
56
+ search: {description: "Search", parameters: {type: "object"}},
57
+ })),
58
+ reconnectServer: mock(async () => true),
59
+ } as unknown as MockMcpService;
60
+ app = setupServer({
61
+ addRoutes: (router, options) => {
62
+ addMcpRoutes(router, {mcpService: mcpService as MCPService, openApiOptions: options});
63
+ },
64
+ skipListen: true,
65
+ userModel: UserModel,
66
+ });
67
+ });
68
+
69
+ describe("GET /mcp/servers", () => {
70
+ it("returns 403 for non-admin users", async () => {
71
+ const agent = await authAsUser(app, "notAdmin");
72
+ const res = await agent.get("/mcp/servers");
73
+ expect(res.status).toBe(403);
74
+ });
75
+
76
+ it("returns server status for admin", async () => {
77
+ const agent = await authAsUser(app, "admin");
78
+ const res = await agent.get("/mcp/servers");
79
+ expect(res.status).toBe(200);
80
+ expect(res.body.data).toEqual([{connected: true, name: "test-server"}]);
81
+ });
82
+ });
83
+
84
+ describe("GET /mcp/tools", () => {
85
+ it("returns list of tools for authenticated user", async () => {
86
+ const agent = await authAsUser(app, "notAdmin");
87
+ const res = await agent.get("/mcp/tools");
88
+ expect(res.status).toBe(200);
89
+ expect(res.body.data).toEqual([
90
+ expect.objectContaining({description: "Search", name: "search"}),
91
+ ]);
92
+ });
93
+
94
+ it("requires authentication", async () => {
95
+ const res = await supertest(app).get("/mcp/tools");
96
+ expect(res.status).toBe(401);
97
+ });
98
+ });
99
+
100
+ describe("POST /mcp/servers/:name/reconnect", () => {
101
+ it("returns 403 for non-admin users", async () => {
102
+ const agent = await authAsUser(app, "notAdmin");
103
+ const res = await agent.post("/mcp/servers/test-server/reconnect");
104
+ expect(res.status).toBe(403);
105
+ });
106
+
107
+ it("reconnects the requested server for admin", async () => {
108
+ const agent = await authAsUser(app, "admin");
109
+ const res = await agent.post("/mcp/servers/test-server/reconnect");
110
+ expect(res.status).toBe(200);
111
+ expect(res.body.data).toEqual({connected: true, name: "test-server"});
112
+ expect(mcpService.reconnectServer as ReturnType<typeof mock>).toHaveBeenCalledWith(
113
+ "test-server"
114
+ );
115
+ });
116
+
117
+ it("returns connected=false when reconnect fails", async () => {
118
+ mcpService.reconnectServer = mock(async () => false);
119
+ const customApp = setupServer({
120
+ addRoutes: (router, options) => {
121
+ addMcpRoutes(router, {mcpService: mcpService as MCPService, openApiOptions: options});
122
+ },
123
+ skipListen: true,
124
+ userModel: UserModel,
125
+ });
126
+ const agent = await authAsUser(customApp, "admin");
127
+ const res = await agent.post("/mcp/servers/unknown/reconnect");
128
+ expect(res.status).toBe(200);
129
+ expect(res.body.data.connected).toBe(false);
130
+ });
131
+ });
132
+ });
@@ -0,0 +1,205 @@
1
+ import {beforeAll, beforeEach, describe, expect, it} from "bun:test";
2
+ import {createdUpdatedPlugin, setupServer} from "@terreno/api";
3
+ import type express from "express";
4
+ import mongoose from "mongoose";
5
+ import passportLocalMongoose from "passport-local-mongoose";
6
+ import supertest from "supertest";
7
+
8
+ import {Project} from "../models/project";
9
+ import {addProjectRoutes} from "./projects";
10
+
11
+ const userSchema = new mongoose.Schema({
12
+ admin: {default: false, type: Boolean},
13
+ email: {index: true, type: String},
14
+ name: String,
15
+ });
16
+ userSchema.plugin(
17
+ passportLocalMongoose as unknown as (
18
+ schema: mongoose.Schema,
19
+ options: {usernameField: string}
20
+ ) => void,
21
+ {usernameField: "email"}
22
+ );
23
+ userSchema.plugin(createdUpdatedPlugin);
24
+ const UserModel = mongoose.models.User || mongoose.model("User", userSchema);
25
+
26
+ type PasswordedUser = {setPassword: (password: string) => Promise<void>};
27
+
28
+ const authAsUser = async (appInstance: express.Application, type: "admin" | "notAdmin") => {
29
+ const email = type === "admin" ? "admin@example.com" : "notAdmin@example.com";
30
+ const password = type === "admin" ? "securePassword" : "password";
31
+ const agent = supertest.agent(appInstance);
32
+ const res = await agent.post("/auth/login").send({email, password}).expect(200);
33
+ await agent.set("authorization", `Bearer ${res.body.data.token}`);
34
+ return agent;
35
+ };
36
+
37
+ describe("Project Routes", () => {
38
+ let app: express.Application;
39
+ let notAdminId: mongoose.Types.ObjectId;
40
+
41
+ beforeAll(async () => {
42
+ await UserModel.deleteMany({});
43
+ const admin = await UserModel.create({admin: true, email: "admin@example.com", name: "Admin"});
44
+ await (admin as unknown as PasswordedUser).setPassword("securePassword");
45
+ await admin.save();
46
+ const user = await UserModel.create({email: "notAdmin@example.com", name: "User"});
47
+ await (user as unknown as PasswordedUser).setPassword("password");
48
+ await user.save();
49
+ notAdminId = user._id as mongoose.Types.ObjectId;
50
+ });
51
+
52
+ beforeEach(async () => {
53
+ await Project.deleteMany({});
54
+ app = setupServer({
55
+ addRoutes: (router, options) => {
56
+ addProjectRoutes(router, {openApiOptions: options});
57
+ },
58
+ skipListen: true,
59
+ userModel: UserModel,
60
+ });
61
+ });
62
+
63
+ describe("project memories (subdoc)", () => {
64
+ it("stores memories and exposes _id for each memory", async () => {
65
+ const project = await Project.create({
66
+ memories: [
67
+ {source: "user" as const, text: "Memory 1"},
68
+ {category: "pref", source: "auto" as const, text: "Memory 2"},
69
+ ],
70
+ name: "With memories",
71
+ userId: notAdminId,
72
+ });
73
+ expect(project.memories.length).toBe(2);
74
+ expect(project.memories[0]._id).toBeDefined();
75
+ expect(project.memories[1].category).toBe("pref");
76
+ expect(project.memories[1].source).toBe("auto");
77
+ });
78
+
79
+ it("defaults source to user when not specified", async () => {
80
+ const project = await Project.create({
81
+ memories: [{text: "No source"} as unknown as {source: "user"; text: string}],
82
+ name: "Defaults",
83
+ userId: notAdminId,
84
+ });
85
+ expect(project.memories[0].source).toBe("user");
86
+ });
87
+ });
88
+
89
+ describe("model router CRUD", () => {
90
+ it("creates a project for the authenticated user", async () => {
91
+ const agent = await authAsUser(app, "notAdmin");
92
+ const res = await agent.post("/gpt/projects").send({name: "Created"});
93
+ expect(res.status).toBe(201);
94
+ expect(res.body.data.name).toBe("Created");
95
+ expect(res.body.data.userId).toBe(notAdminId.toString());
96
+ });
97
+
98
+ it("lists only the caller's projects", async () => {
99
+ const other = new mongoose.Types.ObjectId();
100
+ await Project.create({name: "Mine", userId: notAdminId});
101
+ await Project.create({name: "Theirs", userId: other});
102
+ const agent = await authAsUser(app, "notAdmin");
103
+ const res = await agent.get("/gpt/projects");
104
+ expect(res.status).toBe(200);
105
+ const names = (res.body.data as Array<{name: string}>).map((p) => p.name);
106
+ expect(names).toContain("Mine");
107
+ expect(names).not.toContain("Theirs");
108
+ });
109
+
110
+ it("exposes ownerId virtual aliased to userId", async () => {
111
+ const project = await Project.create({name: "With Owner", userId: notAdminId});
112
+ expect(project.toObject({virtuals: true}).ownerId.toString()).toBe(notAdminId.toString());
113
+ });
114
+ });
115
+
116
+ describe("memory routes", () => {
117
+ it("requires text when adding a memory", async () => {
118
+ const project = await Project.create({name: "Proj", userId: notAdminId});
119
+ const agent = await authAsUser(app, "notAdmin");
120
+ const res = await agent
121
+ .post(`/gpt/projects/${project._id.toString()}/memories`)
122
+ .send({category: "pref"});
123
+ expect(res.status).toBe(400);
124
+ });
125
+
126
+ it("adds a memory to a project owned by the caller", async () => {
127
+ const project = await Project.create({name: "Proj", userId: notAdminId});
128
+ const agent = await authAsUser(app, "notAdmin");
129
+ const res = await agent
130
+ .post(`/gpt/projects/${project._id.toString()}/memories`)
131
+ .send({category: "pref", text: "Likes X"});
132
+ expect(res.status).toBe(200);
133
+ expect(res.body.data.text).toBe("Likes X");
134
+ expect(res.body.data.category).toBe("pref");
135
+ expect(res.body.data.source).toBe("user");
136
+ });
137
+
138
+ it("returns 404 when adding to a missing project", async () => {
139
+ const agent = await authAsUser(app, "notAdmin");
140
+ const res = await agent
141
+ .post(`/gpt/projects/${new mongoose.Types.ObjectId().toString()}/memories`)
142
+ .send({text: "Anything"});
143
+ expect(res.status).toBe(404);
144
+ });
145
+
146
+ it("returns 403 when adding to another user's project", async () => {
147
+ const other = new mongoose.Types.ObjectId();
148
+ const project = await Project.create({name: "Theirs", userId: other});
149
+ const agent = await authAsUser(app, "notAdmin");
150
+ const res = await agent
151
+ .post(`/gpt/projects/${project._id.toString()}/memories`)
152
+ .send({text: "Anything"});
153
+ expect(res.status).toBe(403);
154
+ });
155
+
156
+ it("deletes a memory from a project owned by the caller", async () => {
157
+ const project = await Project.create({
158
+ memories: [{source: "user" as const, text: "Mem"}],
159
+ name: "Proj",
160
+ userId: notAdminId,
161
+ });
162
+ const memoryId = project.memories[0]._id?.toString();
163
+ const agent = await authAsUser(app, "notAdmin");
164
+ const res = await agent.delete(
165
+ `/gpt/projects/${project._id.toString()}/memories/${memoryId}`
166
+ );
167
+ expect(res.status).toBe(200);
168
+ expect(res.body.data.deleted).toBe(true);
169
+ const updated = await Project.findById(project._id);
170
+ expect(updated?.memories.length).toBe(0);
171
+ });
172
+
173
+ it("returns 404 when deleting from a missing project", async () => {
174
+ const agent = await authAsUser(app, "notAdmin");
175
+ const res = await agent.delete(
176
+ `/gpt/projects/${new mongoose.Types.ObjectId().toString()}/memories/${new mongoose.Types.ObjectId().toString()}`
177
+ );
178
+ expect(res.status).toBe(404);
179
+ });
180
+
181
+ it("returns 404 for deleting a missing memory", async () => {
182
+ const project = await Project.create({name: "Proj", userId: notAdminId});
183
+ const agent = await authAsUser(app, "notAdmin");
184
+ const res = await agent.delete(
185
+ `/gpt/projects/${project._id.toString()}/memories/${new mongoose.Types.ObjectId().toString()}`
186
+ );
187
+ expect(res.status).toBe(404);
188
+ });
189
+
190
+ it("returns 403 for deleting from another user's project", async () => {
191
+ const other = new mongoose.Types.ObjectId();
192
+ const project = await Project.create({
193
+ memories: [{source: "user" as const, text: "Mem"}],
194
+ name: "Theirs",
195
+ userId: other,
196
+ });
197
+ const memoryId = project.memories[0]._id?.toString();
198
+ const agent = await authAsUser(app, "notAdmin");
199
+ const res = await agent.delete(
200
+ `/gpt/projects/${project._id.toString()}/memories/${memoryId}`
201
+ );
202
+ expect(res.status).toBe(403);
203
+ });
204
+ });
205
+ });
@@ -16,29 +16,7 @@ export const addProjectRoutes = (
16
16
  router: any,
17
17
  options?: {openApiOptions?: Record<string, unknown>}
18
18
  ): void => {
19
- router.use(
20
- "/gpt/projects",
21
- modelRouter(Project, {
22
- ...options?.openApiOptions,
23
- permissions: {
24
- create: [Permissions.IsAuthenticated],
25
- delete: [Permissions.IsOwner],
26
- list: [Permissions.IsAuthenticated],
27
- read: [Permissions.IsOwner],
28
- update: [Permissions.IsOwner],
29
- },
30
- preCreate: (body, req: express.Request) =>
31
- ({
32
- ...body,
33
- userId: (req as any).user?._id,
34
- }) as unknown as ProjectDocument,
35
- queryFields: ["userId"],
36
- queryFilter: (user: any) => ({userId: user?.id}),
37
- sort: "-updated",
38
- })
39
- );
40
-
41
- // Add memory to a project
19
+ // Add memory to a project (registered before modelRouter so it isn't shadowed)
42
20
  router.post(
43
21
  "/gpt/projects/:id/memories",
44
22
  [
@@ -57,7 +35,7 @@ export const addProjectRoutes = (
57
35
  asyncHandler(async (req: express.Request, res: express.Response) => {
58
36
  const {id} = req.params;
59
37
  const {text, category} = req.body;
60
- const userId = (req as any).user?._id as mongoose.Types.ObjectId | undefined;
38
+ const userId = (req.user as {_id?: mongoose.Types.ObjectId} | undefined)?._id;
61
39
 
62
40
  if (!text || typeof text !== "string") {
63
41
  throw new APIError({status: 400, title: "text is required"});
@@ -93,7 +71,7 @@ export const addProjectRoutes = (
93
71
  ],
94
72
  asyncHandler(async (req: express.Request, res: express.Response) => {
95
73
  const {id, memoryId} = req.params;
96
- const userId = (req as any).user?._id as mongoose.Types.ObjectId | undefined;
74
+ const userId = (req.user as {_id?: mongoose.Types.ObjectId} | undefined)?._id;
97
75
 
98
76
  const project = await Project.findById(id);
99
77
  if (!project) {
@@ -114,4 +92,26 @@ export const addProjectRoutes = (
114
92
  return res.json({data: {deleted: true}});
115
93
  })
116
94
  );
95
+
96
+ router.use(
97
+ "/gpt/projects",
98
+ modelRouter(Project, {
99
+ ...options?.openApiOptions,
100
+ permissions: {
101
+ create: [Permissions.IsAuthenticated],
102
+ delete: [Permissions.IsOwner],
103
+ list: [Permissions.IsAuthenticated],
104
+ read: [Permissions.IsOwner],
105
+ update: [Permissions.IsOwner],
106
+ },
107
+ preCreate: (body, req: express.Request) =>
108
+ ({
109
+ ...body,
110
+ userId: (req.user as {_id?: mongoose.Types.ObjectId} | undefined)?._id,
111
+ }) as unknown as ProjectDocument,
112
+ queryFields: ["userId"],
113
+ queryFilter: (user?: {id?: string}) => ({userId: user?.id}),
114
+ sort: "-updated",
115
+ })
116
+ );
117
117
  };