@terreno/api 0.30.0 → 0.31.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 (49) hide show
  1. package/CHANGELOG.md +2 -122
  2. package/LICENSE +21 -202
  3. package/dist/actions.openApi.test.js +1 -3
  4. package/dist/actions.test.js +0 -2
  5. package/dist/api.coverage.test.js +0 -2
  6. package/dist/api.d.ts +3 -2
  7. package/dist/api.errorPaths.test.js +86 -0
  8. package/dist/betterAuthSetup.d.ts +15 -1
  9. package/dist/betterAuthSetup.js +4 -6
  10. package/dist/configurationPlugin.js +2 -2
  11. package/dist/consentApp.test.js +1 -5
  12. package/dist/expressServer.js +11 -5
  13. package/dist/githubAuth.js +1 -4
  14. package/dist/openApiBuilder.test.js +0 -2
  15. package/dist/openApiValidator.test.js +34 -0
  16. package/dist/plugins.d.ts +3 -2
  17. package/dist/plugins.js +5 -1
  18. package/dist/plugins.test.js +12 -0
  19. package/dist/populate.test.js +9 -12
  20. package/dist/realtime/realtime.test.js +231 -0
  21. package/dist/realtime/realtimeApp.d.ts +1 -1
  22. package/dist/realtime/realtimeApp.js +6 -2
  23. package/dist/realtime/realtimeAppSetup.test.d.ts +1 -0
  24. package/dist/realtime/realtimeAppSetup.test.js +213 -0
  25. package/dist/tests/models.d.ts +27 -11
  26. package/dist/tests/models.js +5 -3
  27. package/dist/tests/testHelper.d.ts +9 -3
  28. package/package.json +4 -5
  29. package/src/actions.openApi.test.ts +7 -10
  30. package/src/actions.test.ts +19 -12
  31. package/src/actions.ts +2 -2
  32. package/src/api.coverage.test.ts +7 -9
  33. package/src/api.errorPaths.test.ts +47 -1
  34. package/src/api.ts +22 -11
  35. package/src/betterAuthSetup.ts +7 -7
  36. package/src/configurationPlugin.ts +2 -2
  37. package/src/consentApp.test.ts +12 -12
  38. package/src/expressServer.ts +11 -5
  39. package/src/githubAuth.ts +1 -3
  40. package/src/models/versionConfig.ts +1 -1
  41. package/src/openApiBuilder.test.ts +24 -9
  42. package/src/openApiValidator.test.ts +41 -0
  43. package/src/plugins.test.ts +14 -0
  44. package/src/plugins.ts +9 -4
  45. package/src/populate.test.ts +25 -16
  46. package/src/realtime/realtime.test.ts +239 -0
  47. package/src/realtime/realtimeApp.ts +8 -5
  48. package/src/realtime/realtimeAppSetup.test.ts +161 -0
  49. package/src/tests/models.ts +8 -6
@@ -46,8 +46,10 @@ import {
46
46
  findRegistryEntryByCollection,
47
47
  findRegistryEntryByRoutePath,
48
48
  getRealtimeRegistry,
49
+ type RealtimeRegistryEntry,
49
50
  registerRealtime,
50
51
  } from "./registry";
52
+ import type {RealtimeEvent} from "./types";
51
53
 
52
54
  // ─────────────────────────────────────────────────────────────────────────────
53
55
  // queryMatcher tests
@@ -1768,6 +1770,123 @@ describe("emitToDocumentAndQueryRooms", () => {
1768
1770
 
1769
1771
  expect(emissions).toEqual([]);
1770
1772
  });
1773
+
1774
+ describe("query room fanout with a registry entry", () => {
1775
+ const modelEntry: RealtimeRegistryEntry = {
1776
+ collectionName: "todos",
1777
+ config: {methods: ["create", "update", "delete"], roomStrategy: "model"},
1778
+ modelName: "Todo",
1779
+ options: {
1780
+ permissions: {
1781
+ create: [() => true],
1782
+ delete: [() => true],
1783
+ list: [() => true],
1784
+ read: [() => true],
1785
+ update: [() => true],
1786
+ },
1787
+ },
1788
+ routePath: "/todos",
1789
+ };
1790
+
1791
+ const makeEvent = (method: RealtimeEvent["method"]): RealtimeEvent => ({
1792
+ collection: "todos",
1793
+ id: "doc-1",
1794
+ method,
1795
+ model: "Todo",
1796
+ timestamp: 1,
1797
+ });
1798
+
1799
+ it("emits creates through the permission-filtered path", async () => {
1800
+ const queryId = computeQueryId("todos", {priority: 1});
1801
+ addQuerySubscription("socket-a", "todos", {priority: 1}, queryId);
1802
+ const {addSocketToRoom, emissions, io} = makeIo();
1803
+ addSocketToRoom(`query:${queryId}`, {id: "user-1"});
1804
+
1805
+ await emitToDocumentAndQueryRooms(
1806
+ io,
1807
+ "todos",
1808
+ makeEvent("create"),
1809
+ {priority: 1},
1810
+ () => {},
1811
+ modelEntry
1812
+ );
1813
+
1814
+ const queryEmissions = emissions.filter((e) => e.room === `query:${queryId}`);
1815
+ expect(queryEmissions).toHaveLength(1);
1816
+ expect(queryEmissions[0].payload).toMatchObject({data: {priority: 1}, method: "create"});
1817
+ });
1818
+
1819
+ it("emits updates through the permission-filtered path when the doc still matches", async () => {
1820
+ const queryId = computeQueryId("todos", {priority: 1});
1821
+ addQuerySubscription("socket-a", "todos", {priority: 1}, queryId);
1822
+ const {addSocketToRoom, emissions, io} = makeIo();
1823
+ addSocketToRoom(`query:${queryId}`, {id: "user-1"});
1824
+
1825
+ await emitToDocumentAndQueryRooms(
1826
+ io,
1827
+ "todos",
1828
+ makeEvent("update"),
1829
+ {priority: 1},
1830
+ () => {},
1831
+ modelEntry
1832
+ );
1833
+
1834
+ const queryEmissions = emissions.filter((e) => e.room === `query:${queryId}`);
1835
+ expect(queryEmissions).toHaveLength(1);
1836
+ expect(queryEmissions[0].payload).toMatchObject({method: "update"});
1837
+ });
1838
+
1839
+ it("converts non-matching updates into deletes through the permission-filtered path", async () => {
1840
+ const queryId = computeQueryId("todos", {priority: 1});
1841
+ addQuerySubscription("socket-a", "todos", {priority: 1}, queryId);
1842
+ const {addSocketToRoom, emissions, io} = makeIo();
1843
+ addSocketToRoom(`query:${queryId}`, {id: "user-1"});
1844
+
1845
+ await emitToDocumentAndQueryRooms(
1846
+ io,
1847
+ "todos",
1848
+ makeEvent("update"),
1849
+ {priority: 9},
1850
+ () => {},
1851
+ modelEntry
1852
+ );
1853
+
1854
+ const queryEmissions = emissions.filter((e) => e.room === `query:${queryId}`);
1855
+ expect(queryEmissions).toHaveLength(1);
1856
+ expect(queryEmissions[0].payload).toMatchObject({method: "delete"});
1857
+ });
1858
+
1859
+ it("skips query rooms whose subscribers cannot read the document", async () => {
1860
+ const queryId = computeQueryId("todos", {priority: 1});
1861
+ addQuerySubscription("socket-a", "todos", {priority: 1}, queryId);
1862
+ const {addSocketToRoom, emissions, io} = makeIo();
1863
+ addSocketToRoom(`query:${queryId}`, {id: "other-user"});
1864
+ const ownerEntry: RealtimeRegistryEntry = {
1865
+ ...modelEntry,
1866
+ options: {
1867
+ permissions: {
1868
+ ...modelEntry.options.permissions,
1869
+ read: [
1870
+ (_method, user?: {admin?: boolean; id?: string}, obj?: unknown) =>
1871
+ user?.admin === true ||
1872
+ user?.id === (obj as {ownerId?: string} | undefined)?.ownerId,
1873
+ ],
1874
+ },
1875
+ },
1876
+ };
1877
+
1878
+ await emitToDocumentAndQueryRooms(
1879
+ io,
1880
+ "todos",
1881
+ makeEvent("create"),
1882
+ {ownerId: "user-1", priority: 1},
1883
+ () => {},
1884
+ ownerEntry
1885
+ );
1886
+
1887
+ expect(emissions.some((e) => e.room === `query:${queryId}`)).toBe(false);
1888
+ });
1889
+ });
1771
1890
  });
1772
1891
 
1773
1892
  // ─────────────────────────────────────────────────────────────────────────────
@@ -2059,6 +2178,126 @@ describe("startChangeStreamWatcher", () => {
2059
2178
  });
2060
2179
  });
2061
2180
 
2181
+ // Records every emission so hard-delete room routing can be asserted.
2182
+ const createRecordingIo = (
2183
+ room: string,
2184
+ decodedToken: {admin?: boolean; id?: string} = {admin: true, id: "admin"}
2185
+ ): {
2186
+ emissions: Array<{event: string; payload: unknown}>;
2187
+ io: import("socket.io").Server;
2188
+ } => {
2189
+ const emissions: Array<{event: string; payload: unknown}> = [];
2190
+ const rooms = new Map<string, Set<string>>([[room, new Set(["socket-1"])]]);
2191
+ const sockets = new Map<string, unknown>([
2192
+ [
2193
+ "socket-1",
2194
+ {
2195
+ decodedToken,
2196
+ emit: (event: string, payload: unknown): void => {
2197
+ emissions.push({event, payload});
2198
+ },
2199
+ id: "socket-1",
2200
+ },
2201
+ ],
2202
+ ]);
2203
+ return {
2204
+ emissions,
2205
+ io: {
2206
+ sockets: {adapter: {rooms}, sockets},
2207
+ to: (_room: string) => ({emit: (_event: string, _data: unknown) => {}}),
2208
+ } as unknown as import("socket.io").Server,
2209
+ };
2210
+ };
2211
+
2212
+ it("routes hard deletes for model-strategy models to the model room", async () => {
2213
+ const mockStream = createMockChangeStream();
2214
+ const mockDb = {
2215
+ watch: mock(() => mockStream),
2216
+ };
2217
+ (mongoose.connection as unknown as {db: unknown}).db = mockDb;
2218
+
2219
+ registerRealtime({
2220
+ collectionName: "todos",
2221
+ config: {
2222
+ methods: ["create", "update", "delete"],
2223
+ roomStrategy: "model",
2224
+ },
2225
+ modelName: "Todo",
2226
+ options: {
2227
+ permissions: {
2228
+ create: [() => true],
2229
+ delete: [() => true],
2230
+ list: [() => true],
2231
+ read: [() => true],
2232
+ update: [() => true],
2233
+ },
2234
+ },
2235
+ routePath: "/todos",
2236
+ });
2237
+
2238
+ const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
2239
+ const {emissions, io} = createRecordingIo("model:todos");
2240
+
2241
+ startChangeStreamWatcher(io, {}, true);
2242
+
2243
+ await invokeRegisteredChangeHandler(mockStream, {
2244
+ documentKey: {_id: "doc-1"},
2245
+ ns: {coll: "todos"},
2246
+ operationType: "delete",
2247
+ });
2248
+
2249
+ expect(emissions).toHaveLength(1);
2250
+ expect(emissions[0].payload).toMatchObject({id: "doc-1", method: "delete", model: "Todo"});
2251
+ });
2252
+
2253
+ it("swallows errors thrown while processing a change event", async () => {
2254
+ const mockStream = createMockChangeStream();
2255
+ const mockDb = {
2256
+ watch: mock(() => mockStream),
2257
+ };
2258
+ (mongoose.connection as unknown as {db: unknown}).db = mockDb;
2259
+
2260
+ registerRealtime({
2261
+ collectionName: "todos",
2262
+ config: {
2263
+ methods: ["create", "update", "delete"],
2264
+ roomStrategy: "model",
2265
+ },
2266
+ modelName: "Todo",
2267
+ options: {
2268
+ permissions: {
2269
+ create: [() => true],
2270
+ delete: [() => true],
2271
+ list: [() => true],
2272
+ read: [() => true],
2273
+ update: [() => true],
2274
+ },
2275
+ },
2276
+ routePath: "/todos",
2277
+ });
2278
+
2279
+ const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
2280
+ const roomLookup = mock(() => {
2281
+ throw new Error("adapter unavailable");
2282
+ });
2283
+ const io = {
2284
+ sockets: {adapter: {rooms: {get: roomLookup}}, sockets: new Map()},
2285
+ to: (_room: string) => ({emit: (_event: string, _data: unknown) => {}}),
2286
+ } as unknown as import("socket.io").Server;
2287
+
2288
+ startChangeStreamWatcher(io, {}, true);
2289
+
2290
+ // The handler must not reject — a failed emission cannot take down the change stream.
2291
+ await invokeRegisteredChangeHandler(mockStream, {
2292
+ documentKey: {_id: "doc-1"},
2293
+ fullDocument: {_id: "doc-1", name: "Test Todo"},
2294
+ ns: {coll: "todos"},
2295
+ operationType: "insert",
2296
+ });
2297
+
2298
+ expect(roomLookup).toHaveBeenCalled();
2299
+ });
2300
+
2062
2301
  it("includes updatedFields in event for update operations", async () => {
2063
2302
  const mockStream = createMockChangeStream();
2064
2303
  const mockDb = {
@@ -7,6 +7,7 @@ import type express from "express";
7
7
  import {Server, type Socket} from "socket.io";
8
8
 
9
9
  import type {User} from "../auth";
10
+ import {APIError} from "../errors";
10
11
  import {logger} from "../logger";
11
12
  import {checkPermissions} from "../permissions";
12
13
  import type {TerrenoPlugin} from "../terrenoPlugin";
@@ -61,7 +62,7 @@ export interface RealtimeSocketLike extends SocketWithDecodedToken {
61
62
  join: (room: string) => Promise<void> | void;
62
63
  leave: (room: string) => Promise<void> | void;
63
64
  emit: (event: string, payload: unknown) => void;
64
- on: (event: string, handler: (...args: any[]) => any) => void;
65
+ on: (event: string, handler: (...args: never[]) => void | Promise<void>) => void;
65
66
  }
66
67
 
67
68
  const canSubscribe = async (
@@ -383,10 +384,12 @@ export class RealtimeApp implements TerrenoPlugin {
383
384
  // JWT authentication middleware
384
385
  const tokenSecret = this.config.tokenSecret ?? process.env.TOKEN_SECRET;
385
386
  if (!tokenSecret) {
386
- throw new Error(
387
- "[realtime] TOKEN_SECRET is required for socket authentication. " +
388
- "Set process.env.TOKEN_SECRET or pass tokenSecret in RealtimeAppOptions."
389
- );
387
+ throw new APIError({
388
+ status: 500,
389
+ title:
390
+ "[realtime] TOKEN_SECRET is required for socket authentication. " +
391
+ "Set process.env.TOKEN_SECRET or pass tokenSecret in RealtimeAppOptions.",
392
+ });
390
393
  }
391
394
 
392
395
  this.io.use(
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Tests for RealtimeApp.onServerCreated — the Socket.io server wiring that a
3
+ * live server would exercise. socket.io, the JWT authorize middleware, and the
4
+ * change-stream watcher are mocked so the connection / connect_error handlers
5
+ * can be captured and invoked without standing up a real server.
6
+ */
7
+ import {afterEach, beforeAll, beforeEach, describe, expect, it, mock} from "bun:test";
8
+
9
+ import type http from "node:http";
10
+
11
+ type Handler = (...args: unknown[]) => void;
12
+
13
+ interface FakeIo {
14
+ handlers: Map<string, Handler>;
15
+ middleware: unknown[];
16
+ closed: boolean;
17
+ }
18
+
19
+ let ios: FakeIo[] = [];
20
+ let watcherStarts = 0;
21
+
22
+ class FakeServer {
23
+ handlers = new Map<string, Handler>();
24
+ middleware: unknown[] = [];
25
+ closed = false;
26
+ engine = {clientsCount: 0};
27
+
28
+ constructor(..._args: unknown[]) {
29
+ ios.push(this as unknown as FakeIo);
30
+ }
31
+
32
+ use(mw: unknown): void {
33
+ this.middleware.push(mw);
34
+ }
35
+
36
+ on(event: string, handler: Handler): void {
37
+ this.handlers.set(event, handler);
38
+ }
39
+
40
+ close(cb?: () => void): void {
41
+ this.closed = true;
42
+ cb?.();
43
+ }
44
+ }
45
+
46
+ mock.module("socket.io", () => ({Server: FakeServer}));
47
+ mock.module("@thream/socketio-jwt", () => ({
48
+ authorize: (_opts: unknown) => (_socket: unknown, next: () => void) => next(),
49
+ }));
50
+ mock.module("./changeStreamWatcher", () => ({
51
+ startChangeStreamWatcher: () => {
52
+ watcherStarts += 1;
53
+ },
54
+ stopChangeStreamWatcher: () => {},
55
+ }));
56
+
57
+ let RealtimeApp: typeof import("./realtimeApp").RealtimeApp;
58
+
59
+ beforeAll(async () => {
60
+ ({RealtimeApp} = await import("./realtimeApp"));
61
+ });
62
+
63
+ const lastIo = (): FakeIo => {
64
+ const io = ios[ios.length - 1];
65
+ if (!io) {
66
+ throw new Error("No Socket.io server was created");
67
+ }
68
+ return io;
69
+ };
70
+
71
+ const getHandler = (event: string): Handler => {
72
+ const handler = lastIo().handlers.get(event);
73
+ if (!handler) {
74
+ throw new Error(`No handler registered for ${event}`);
75
+ }
76
+ return handler;
77
+ };
78
+
79
+ const fakeServer = {} as http.Server;
80
+
81
+ const createConnectionSocket = (throwOnOn = false): Record<string, unknown> => {
82
+ const listeners = new Map<string, Handler>();
83
+ return {
84
+ decodedToken: {admin: false, id: "user-42"},
85
+ emit: (): void => {},
86
+ id: "socket-1",
87
+ join: async (): Promise<void> => {},
88
+ leave: async (): Promise<void> => {},
89
+ on: (event: string, handler: Handler): void => {
90
+ if (throwOnOn) {
91
+ throw new Error("boom");
92
+ }
93
+ listeners.set(event, handler);
94
+ },
95
+ };
96
+ };
97
+
98
+ describe("RealtimeApp.onServerCreated", () => {
99
+ beforeEach(() => {
100
+ ios = [];
101
+ watcherStarts = 0;
102
+ });
103
+
104
+ afterEach(() => {
105
+ delete process.env.TOKEN_SECRET;
106
+ });
107
+
108
+ it("wires up auth middleware, connection handlers, and the change-stream watcher", () => {
109
+ const app = new RealtimeApp({debug: true, tokenSecret: "test-secret"});
110
+ app.onServerCreated(fakeServer);
111
+
112
+ const io = lastIo();
113
+ expect(io.middleware.length).toBe(1);
114
+ expect(io.handlers.has("connection")).toBe(true);
115
+ expect(io.handlers.has("connect_error")).toBe(true);
116
+ expect(watcherStarts).toBe(1);
117
+ expect(app.getIo()).not.toBeNull();
118
+ });
119
+
120
+ it("installs socket handlers for each new connection", () => {
121
+ const app = new RealtimeApp({tokenSecret: "test-secret"});
122
+ app.onServerCreated(fakeServer);
123
+
124
+ const connectionHandler = getHandler("connection");
125
+ const socket = createConnectionSocket();
126
+ // Should run installRealtimeSocketHandlers without throwing.
127
+ expect(() => connectionHandler(socket)).not.toThrow();
128
+ });
129
+
130
+ it("captures errors thrown while handling a connection", () => {
131
+ const app = new RealtimeApp({tokenSecret: "test-secret"});
132
+ app.onServerCreated(fakeServer);
133
+
134
+ const connectionHandler = getHandler("connection");
135
+ const brokenSocket = createConnectionSocket(true);
136
+ // The handler swallows the error rather than crashing the server.
137
+ expect(() => connectionHandler(brokenSocket)).not.toThrow();
138
+ });
139
+
140
+ it("logs connect_error events without throwing", () => {
141
+ const app = new RealtimeApp({tokenSecret: "test-secret"});
142
+ app.onServerCreated(fakeServer);
143
+
144
+ const errorHandler = getHandler("connect_error");
145
+ expect(() => errorHandler(new Error("handshake failed"))).not.toThrow();
146
+ });
147
+
148
+ it("reads the token secret from the environment when not provided in config", () => {
149
+ process.env.TOKEN_SECRET = "env-secret";
150
+ const app = new RealtimeApp();
151
+ app.onServerCreated(fakeServer);
152
+
153
+ expect(lastIo().handlers.has("connection")).toBe(true);
154
+ });
155
+
156
+ it("throws when no token secret is available", () => {
157
+ delete process.env.TOKEN_SECRET;
158
+ const app = new RealtimeApp();
159
+ expect(() => app.onServerCreated(fakeServer)).toThrow(/TOKEN_SECRET is required/);
160
+ });
161
+ });
@@ -1,4 +1,4 @@
1
- import mongoose, {type Model, model, Schema} from "mongoose";
1
+ import mongoose, {type Model, model, Schema, type StringSchemaDefinition} from "mongoose";
2
2
  import passportLocalMongoose from "passport-local-mongoose";
3
3
 
4
4
  import {createdUpdatedPlugin, DateOnly, isDisabledPlugin} from "../plugins";
@@ -41,11 +41,11 @@ export interface Food {
41
41
  dateAdded?: string;
42
42
  };
43
43
  tags: string[];
44
- eatenBy: [Schema.Types.ObjectId | User];
44
+ eatenBy: Array<mongoose.Types.ObjectId | User>;
45
45
  lastEatenWith: {[name: string]: Date};
46
46
  categories: FoodCategory[];
47
47
  expiration: string;
48
- likesIds: {userId: string; likes: boolean}[];
48
+ likesIds: {userId: mongoose.Types.ObjectId | string; likes: boolean}[];
49
49
  }
50
50
 
51
51
  export interface RequiredField {
@@ -126,9 +126,11 @@ const foodSchema = new Schema<Food>(
126
126
  type: Schema.Types.ObjectId,
127
127
  },
128
128
  ],
129
- // noExplicitAny: DateOnly is a custom SchemaType not recognized by Mongoose's built-in type definitions
130
- // biome-ignore lint/suspicious/noExplicitAny: DateOnly is a custom SchemaType not recognized by Mongoose's built-in type definitions
131
- expiration: {description: "Expiration date of the food", type: DateOnly as any},
129
+ expiration: {
130
+ description: "Expiration date of the food",
131
+ // DateOnly is a custom SchemaType registered on Schema.Types; it stores an ISO date string.
132
+ type: DateOnly as unknown as StringSchemaDefinition,
133
+ },
132
134
  hidden: {
133
135
  default: false,
134
136
  description: "Whether this food is hidden from listings",