@terreno/api 56.0.0-beta.0 → 57.0.0-beta.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.
Files changed (64) hide show
  1. package/CHANGELOG.md +2 -122
  2. package/LICENSE +21 -202
  3. package/dist/api.d.ts +3 -2
  4. package/dist/auth.js +21 -25
  5. package/dist/betterAuthSetup.d.ts +15 -1
  6. package/dist/betterAuthSetup.js +4 -6
  7. package/dist/configurationPlugin.js +2 -2
  8. package/dist/expressServer.js +11 -5
  9. package/dist/githubAuth.js +1 -4
  10. package/dist/plugins.d.ts +7 -6
  11. package/dist/plugins.js +24 -8
  12. package/dist/realtime/changeStreamWatcher.d.ts +1 -1
  13. package/dist/realtime/changeStreamWatcher.js +0 -2
  14. package/dist/realtime/realtimeApp.d.ts +1 -1
  15. package/dist/realtime/realtimeApp.js +16 -8
  16. package/dist/realtime/types.d.ts +14 -0
  17. package/dist/sync/executors.js +14 -14
  18. package/dist/sync/models.js +1 -1
  19. package/dist/sync/registry.d.ts +4 -4
  20. package/dist/sync/registry.js +1 -1
  21. package/dist/sync/socketHandlers.d.ts +1 -1
  22. package/dist/sync/syncSeqPlugin.js +25 -29
  23. package/dist/tests/models.d.ts +27 -11
  24. package/dist/tests/models.js +5 -3
  25. package/dist/tests/testHelper.d.ts +9 -3
  26. package/package.json +5 -6
  27. package/src/actions.test.ts +19 -12
  28. package/src/actions.ts +2 -2
  29. package/src/api.coverage.test.ts +7 -9
  30. package/src/api.errorPaths.test.ts +47 -1
  31. package/src/api.errors.test.ts +32 -23
  32. package/src/api.ts +22 -12
  33. package/src/auth.test.ts +251 -1
  34. package/src/auth.ts +25 -23
  35. package/src/betterAuthSetup.ts +7 -7
  36. package/src/configuration.test.ts +59 -38
  37. package/src/configurationPlugin.test.ts +72 -42
  38. package/src/configurationPlugin.ts +2 -2
  39. package/src/consentApp.test.ts +12 -12
  40. package/src/expressServer.ts +11 -5
  41. package/src/githubAuth.ts +1 -3
  42. package/src/middleware.test.ts +16 -0
  43. package/src/models/versionConfig.ts +1 -1
  44. package/src/openApiBuilder.test.ts +24 -9
  45. package/src/openApiValidator.test.ts +41 -0
  46. package/src/permissions.middleware.test.ts +73 -81
  47. package/src/permissions.test.ts +35 -25
  48. package/src/plugins.test.ts +74 -29
  49. package/src/plugins.ts +29 -11
  50. package/src/populate.test.ts +25 -16
  51. package/src/realtime/changeStreamWatcher.ts +1 -4
  52. package/src/realtime/realtime.test.ts +239 -0
  53. package/src/realtime/realtimeApp.ts +15 -8
  54. package/src/realtime/realtimeAppSetup.test.ts +159 -0
  55. package/src/realtime/types.ts +14 -0
  56. package/src/secretProvidersGcpClient.test.ts +66 -0
  57. package/src/sync/executors.ts +16 -14
  58. package/src/sync/models.ts +2 -1
  59. package/src/sync/registry.ts +6 -8
  60. package/src/sync/socketHandlers.ts +1 -3
  61. package/src/sync/syncFrontier.test.ts +2 -2
  62. package/src/sync/syncSeqPlugin.test.ts +446 -0
  63. package/src/sync/syncSeqPlugin.ts +43 -51
  64. 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 = {
@@ -6,6 +6,7 @@ import type express from "express";
6
6
  import {Server, type Socket} from "socket.io";
7
7
 
8
8
  import type {User} from "../auth";
9
+ import {APIError} from "../errors";
9
10
  import {logger} from "../logger";
10
11
  import {checkPermissions} from "../permissions";
11
12
  import {warnOnSyncScopesWithoutUserModel} from "../sync/registry";
@@ -69,7 +70,7 @@ export interface RealtimeSocketLike extends SocketWithDecodedToken {
69
70
  join: (room: string) => Promise<void> | void;
70
71
  leave: (room: string) => Promise<void> | void;
71
72
  emit: (event: string, payload: unknown) => void;
72
- on: (event: string, handler: (...args: any[]) => any) => void;
73
+ on: (event: string, handler: (...args: never[]) => void | Promise<void>) => void;
73
74
  }
74
75
 
75
76
  const canSubscribe = async (
@@ -386,7 +387,10 @@ export class RealtimeApp implements TerrenoPlugin {
386
387
  try {
387
388
  logInfo("[realtime] Setting up Socket.io server...");
388
389
 
389
- this.io = new Server(server, {
390
+ // Prefer an injected Server constructor in tests so callers never need
391
+ // process-wide `mock.module("socket.io")` (which poisons later files).
392
+ const SocketServerCtor = this.config.SocketServer ?? Server;
393
+ this.io = new SocketServerCtor(server, {
390
394
  cors: this.config.cors ?? {
391
395
  methods: ["GET", "POST"],
392
396
  origin: "*",
@@ -396,10 +400,12 @@ export class RealtimeApp implements TerrenoPlugin {
396
400
  // Authentication middleware: legacy JWT first, optionally Better Auth sessions.
397
401
  const tokenSecret = this.config.tokenSecret ?? process.env.TOKEN_SECRET;
398
402
  if (!tokenSecret) {
399
- throw new Error(
400
- "[realtime] TOKEN_SECRET is required for socket authentication. " +
401
- "Set process.env.TOKEN_SECRET or pass tokenSecret in RealtimeAppOptions."
402
- );
403
+ throw new APIError({
404
+ status: 500,
405
+ title:
406
+ "[realtime] TOKEN_SECRET is required for socket authentication. " +
407
+ "Set process.env.TOKEN_SECRET or pass tokenSecret in RealtimeAppOptions.",
408
+ });
403
409
  }
404
410
 
405
411
  // D1: pass the issuer through for parity with the HTTP JWT path
@@ -466,8 +472,9 @@ export class RealtimeApp implements TerrenoPlugin {
466
472
  Sentry.captureException(error);
467
473
  });
468
474
 
469
- // Start the change stream watcher
470
- startChangeStreamWatcher(this.io, this.config.changeStream, debug);
475
+ // Start the change stream watcher (injectable for unit tests — see SocketServer).
476
+ const startWatcher = this.config.startChangeStreamWatcher ?? startChangeStreamWatcher;
477
+ startWatcher(this.io, this.config.changeStream, debug);
471
478
 
472
479
  // D1: periodic session re-validation sweep — disconnects sockets whose JWT has
473
480
  // expired, whose Better Auth session is no longer valid, or whose user has
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Tests for RealtimeApp.onServerCreated — the Socket.io server wiring that a
3
+ * live server would exercise. Socket.IO Server and the change-stream watcher are
4
+ * injected via RealtimeAppOptions so we never `mock.module` (bun's module mocks
5
+ * are process-wide and would break later files that need the real implementations).
6
+ */
7
+ import {afterEach, beforeEach, describe, expect, it} from "bun:test";
8
+
9
+ import type http from "node:http";
10
+
11
+ import {RealtimeApp} from "./realtimeApp";
12
+
13
+ type Handler = (...args: unknown[]) => void;
14
+
15
+ interface FakeIo {
16
+ handlers: Map<string, Handler>;
17
+ middleware: unknown[];
18
+ closed: boolean;
19
+ }
20
+
21
+ let ios: FakeIo[] = [];
22
+ let watcherStarts = 0;
23
+
24
+ class FakeServer {
25
+ handlers = new Map<string, Handler>();
26
+ middleware: unknown[] = [];
27
+ closed = false;
28
+ engine = {clientsCount: 0};
29
+
30
+ constructor(..._args: unknown[]) {
31
+ ios.push(this as unknown as FakeIo);
32
+ }
33
+
34
+ use(mw: unknown): void {
35
+ this.middleware.push(mw);
36
+ }
37
+
38
+ on(event: string, handler: Handler): void {
39
+ this.handlers.set(event, handler);
40
+ }
41
+
42
+ close(cb?: () => void): void {
43
+ this.closed = true;
44
+ cb?.();
45
+ }
46
+ }
47
+
48
+ const lastIo = (): FakeIo => {
49
+ const io = ios[ios.length - 1];
50
+ if (!io) {
51
+ throw new Error("No Socket.io server was created");
52
+ }
53
+ return io;
54
+ };
55
+
56
+ const getHandler = (event: string): Handler => {
57
+ const handler = lastIo().handlers.get(event);
58
+ if (!handler) {
59
+ throw new Error(`No handler registered for ${event}`);
60
+ }
61
+ return handler;
62
+ };
63
+
64
+ const fakeServer = {} as http.Server;
65
+
66
+ const createConnectionSocket = (throwOnOn = false): Record<string, unknown> => {
67
+ const listeners = new Map<string, Handler>();
68
+ return {
69
+ decodedToken: {admin: false, id: "user-42"},
70
+ emit: (): void => {},
71
+ id: "socket-1",
72
+ join: async (): Promise<void> => {},
73
+ leave: async (): Promise<void> => {},
74
+ on: (event: string, handler: Handler): void => {
75
+ if (throwOnOn) {
76
+ throw new Error("boom");
77
+ }
78
+ listeners.set(event, handler);
79
+ },
80
+ };
81
+ };
82
+
83
+ /** Shared RealtimeAppOptions that inject FakeServer + a start-watcher counter. */
84
+ const testRealtimeOptions = (
85
+ overrides: ConstructorParameters<typeof RealtimeApp>[0] = {}
86
+ ): ConstructorParameters<typeof RealtimeApp>[0] => ({
87
+ SocketServer: FakeServer as unknown as NonNullable<
88
+ ConstructorParameters<typeof RealtimeApp>[0]
89
+ >["SocketServer"],
90
+ startChangeStreamWatcher: () => {
91
+ watcherStarts += 1;
92
+ },
93
+ ...overrides,
94
+ });
95
+
96
+ describe("RealtimeApp.onServerCreated", () => {
97
+ beforeEach(() => {
98
+ ios = [];
99
+ watcherStarts = 0;
100
+ });
101
+
102
+ afterEach(() => {
103
+ delete process.env.TOKEN_SECRET;
104
+ });
105
+
106
+ it("wires up auth middleware, connection handlers, and the change-stream watcher", () => {
107
+ const app = new RealtimeApp(testRealtimeOptions({debug: true, tokenSecret: "test-secret"}));
108
+ app.onServerCreated(fakeServer);
109
+
110
+ const io = lastIo();
111
+ expect(io.middleware.length).toBe(1);
112
+ expect(io.handlers.has("connection")).toBe(true);
113
+ expect(io.handlers.has("connect_error")).toBe(true);
114
+ expect(watcherStarts).toBe(1);
115
+ expect(app.getIo()).not.toBeNull();
116
+ });
117
+
118
+ it("installs socket handlers for each new connection", () => {
119
+ const app = new RealtimeApp(testRealtimeOptions({tokenSecret: "test-secret"}));
120
+ app.onServerCreated(fakeServer);
121
+
122
+ const connectionHandler = getHandler("connection");
123
+ const socket = createConnectionSocket();
124
+ // Should run installRealtimeSocketHandlers without throwing.
125
+ expect(() => connectionHandler(socket)).not.toThrow();
126
+ });
127
+
128
+ it("captures errors thrown while handling a connection", () => {
129
+ const app = new RealtimeApp(testRealtimeOptions({tokenSecret: "test-secret"}));
130
+ app.onServerCreated(fakeServer);
131
+
132
+ const connectionHandler = getHandler("connection");
133
+ const brokenSocket = createConnectionSocket(true);
134
+ // The handler swallows the error rather than crashing the server.
135
+ expect(() => connectionHandler(brokenSocket)).not.toThrow();
136
+ });
137
+
138
+ it("logs connect_error events without throwing", () => {
139
+ const app = new RealtimeApp(testRealtimeOptions({tokenSecret: "test-secret"}));
140
+ app.onServerCreated(fakeServer);
141
+
142
+ const errorHandler = getHandler("connect_error");
143
+ expect(() => errorHandler(new Error("handshake failed"))).not.toThrow();
144
+ });
145
+
146
+ it("reads the token secret from the environment when not provided in config", () => {
147
+ process.env.TOKEN_SECRET = "env-secret";
148
+ const app = new RealtimeApp(testRealtimeOptions());
149
+ app.onServerCreated(fakeServer);
150
+
151
+ expect(lastIo().handlers.has("connection")).toBe(true);
152
+ });
153
+
154
+ it("throws when no token secret is available", () => {
155
+ delete process.env.TOKEN_SECRET;
156
+ const app = new RealtimeApp(testRealtimeOptions());
157
+ expect(() => app.onServerCreated(fakeServer)).toThrow(/TOKEN_SECRET is required/);
158
+ });
159
+ });
@@ -1,6 +1,8 @@
1
1
  import type express from "express";
2
+ import type {Server as SocketIoServer} from "socket.io";
2
3
  import type {UserModel} from "../auth";
3
4
  import type {SyncAppOptions} from "../sync/routes";
5
+ import type {startChangeStreamWatcher} from "./changeStreamWatcher";
4
6
  import type {BetterAuthSocketOptions} from "./socketAuth";
5
7
 
6
8
  /**
@@ -122,6 +124,18 @@ export interface RealtimeAppOptions {
122
124
  sessionRevalidationIntervalMs?: number;
123
125
  /** Enable debug logging */
124
126
  debug?: boolean;
127
+ /**
128
+ * Test seam: Socket.IO server constructor. Defaults to `socket.io`'s `Server`.
129
+ * Prefer this over `mock.module("socket.io")` — bun's module mocks are process-wide
130
+ * and break later files that need a real Socket.IO server (sync integration, etc.).
131
+ */
132
+ SocketServer?: typeof SocketIoServer;
133
+ /**
134
+ * Test seam: change-stream watcher starter. Defaults to the real
135
+ * `startChangeStreamWatcher`. Same rationale as {@link SocketServer} — avoid
136
+ * process-wide `mock.module` of `./changeStreamWatcher`.
137
+ */
138
+ startChangeStreamWatcher?: typeof startChangeStreamWatcher;
125
139
  }
126
140
 
127
141
  /**
@@ -0,0 +1,66 @@
1
+ import {beforeEach, describe, expect, it, mock} from "bun:test";
2
+
3
+ import {GcpSecretProvider} from "./secretProviders";
4
+
5
+ // Exercises GcpSecretProvider.getClient(), which dynamically imports the
6
+ // optional @google-cloud/secret-manager peer dependency. `mock.module` is
7
+ // hoisted to the top of the file and the registration lives for the rest of the
8
+ // process, so these tests live in their own file: secretProviders.test.ts
9
+ // asserts the behavior when the real (uninstalled) module fails to import, and
10
+ // runs before this file.
11
+ let clientsConstructed = 0;
12
+ const requestedNames: string[] = [];
13
+ let payload: string | Uint8Array = "from-gcp";
14
+
15
+ class FakeSecretManagerServiceClient {
16
+ constructor() {
17
+ clientsConstructed++;
18
+ }
19
+
20
+ async accessSecretVersion(request: {
21
+ name: string;
22
+ }): Promise<[{payload: {data: string | Uint8Array}}]> {
23
+ requestedNames.push(request.name);
24
+ return [{payload: {data: payload}}];
25
+ }
26
+ }
27
+
28
+ mock.module("@google-cloud/secret-manager", () => ({
29
+ SecretManagerServiceClient: FakeSecretManagerServiceClient,
30
+ }));
31
+
32
+ describe("GcpSecretProvider client construction", () => {
33
+ beforeEach(() => {
34
+ clientsConstructed = 0;
35
+ requestedNames.length = 0;
36
+ payload = "from-gcp";
37
+ });
38
+
39
+ it("constructs the client from the imported module and caches it", async () => {
40
+ const provider = new GcpSecretProvider({projectId: "my-project"});
41
+
42
+ expect(await provider.getSecret("openai-api-key")).toBe("from-gcp");
43
+ expect(await provider.getSecret("openai-api-key", "3")).toBe("from-gcp");
44
+
45
+ expect(clientsConstructed).toBe(1);
46
+ expect(requestedNames).toEqual([
47
+ "projects/my-project/secrets/openai-api-key/versions/latest",
48
+ "projects/my-project/secrets/openai-api-key/versions/3",
49
+ ]);
50
+ });
51
+
52
+ it("decodes binary payloads", async () => {
53
+ payload = new TextEncoder().encode("binary-secret");
54
+ const provider = new GcpSecretProvider({projectId: "my-project"});
55
+
56
+ expect(await provider.getSecret("openai-api-key")).toBe("binary-secret");
57
+ });
58
+
59
+ it("honors a full resource path without appending a version twice", async () => {
60
+ const provider = new GcpSecretProvider({projectId: "my-project"});
61
+
62
+ await provider.getSecret("projects/other/secrets/key/versions/7");
63
+
64
+ expect(requestedNames).toEqual(["projects/other/secrets/key/versions/7"]);
65
+ });
66
+ });
@@ -25,7 +25,9 @@ import {loadDocOr404} from "../docLoader";
25
25
  import {
26
26
  APIError,
27
27
  type APIErrorConstructor,
28
+ BadRequestError,
28
29
  errorMessage,
30
+ ForbiddenError,
29
31
  isAPIError,
30
32
  passthroughOrWrap,
31
33
  passthroughOrWrapWrite,
@@ -227,24 +229,24 @@ export const executeCreate = async <T>({
227
229
  });
228
230
  }
229
231
  if (cleanedBody === undefined) {
230
- throw new APIError({
232
+ throw new ForbiddenError({
233
+ code: "create-not-allowed",
231
234
  detail: "A body must be returned from preCreate",
232
- status: 403,
233
235
  title: "Create not allowed",
234
236
  });
235
237
  }
236
238
  if (cleanedBody === null) {
237
- throw new APIError({
239
+ throw new ForbiddenError({
240
+ code: "create-not-allowed",
238
241
  detail: "preCreate hook returned null",
239
- status: 403,
240
242
  title: "Create not allowed",
241
243
  });
242
244
  }
243
245
  }
244
246
  if (cleanedBody === undefined) {
245
- throw new APIError({
247
+ throw new BadRequestError({
248
+ code: "invalid-request-body",
246
249
  detail: "Body is undefined",
247
- status: 400,
248
250
  title: "Invalid request body",
249
251
  });
250
252
  }
@@ -396,16 +398,16 @@ export const executeUpdate = async <T>({
396
398
  });
397
399
  }
398
400
  if (cleanedBody === undefined) {
399
- throw new APIError({
401
+ throw new ForbiddenError({
402
+ code: "update-not-allowed",
400
403
  detail: "A body must be returned from preUpdate",
401
- status: 403,
402
404
  title: "Update not allowed",
403
405
  });
404
406
  }
405
407
  if (cleanedBody === null) {
406
- throw new APIError({
408
+ throw new ForbiddenError({
409
+ code: "update-not-allowed",
407
410
  detail: `preUpdate hook on ${id} returned null`,
408
- status: 403,
409
411
  title: "Update not allowed",
410
412
  });
411
413
  }
@@ -637,16 +639,16 @@ export const executeDelete = async <T>({
637
639
  });
638
640
  }
639
641
  if (body === undefined) {
640
- throw new APIError({
642
+ throw new ForbiddenError({
643
+ code: "delete-not-allowed",
641
644
  detail: "A body must be returned from preDelete",
642
- status: 403,
643
645
  title: "Delete not allowed",
644
646
  });
645
647
  }
646
648
  if (body === null) {
647
- throw new APIError({
649
+ throw new ForbiddenError({
650
+ code: "delete-not-allowed",
648
651
  detail: `preDelete hook for ${id} returned null`,
649
- status: 403,
650
652
  title: "Delete not allowed",
651
653
  });
652
654
  }
@@ -161,6 +161,7 @@ export const claimSyncSeqs = async ({
161
161
  // its pending claims (which would let `computeStableFrontier` transiently report a
162
162
  // frontier above an about-to-be-pending seq). `$range(oldSeq+1, newSeq+1)` materializes
163
163
  // the claimed range from the just-incremented value; `$map` turns it into pending docs.
164
+ // Mongoose 9 disallows update pipelines unless `updatePipeline: true` is set.
164
165
  const doc = await SyncCounter.findOneAndUpdate(
165
166
  {stream},
166
167
  [
@@ -184,7 +185,7 @@ export const claimSyncSeqs = async ({
184
185
  },
185
186
  {$unset: "_syncOldSeq"},
186
187
  ],
187
- {new: true, upsert: true}
188
+ {returnDocument: "after", updatePipeline: true, upsert: true}
188
189
  );
189
190
  return {lastSeq: doc.seq, registered: true, seqs: materialize(doc.seq)};
190
191
  };