@terreno/admin-backend 57.3.0 → 57.6.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 (51) hide show
  1. package/README.md +3 -3
  2. package/bunfig.toml +9 -1
  3. package/dist/adminApp.d.ts +20 -2
  4. package/dist/adminApp.js +1261 -1873
  5. package/dist/adminConfigIdentity.d.ts +1 -0
  6. package/dist/adminConfigIdentity.js +27 -50
  7. package/dist/adminMigrations.d.ts +10 -0
  8. package/dist/adminMigrations.js +120 -0
  9. package/dist/adminScriptJob.d.ts +32 -0
  10. package/dist/adminScriptJob.js +202 -0
  11. package/dist/adminTextSearch.d.ts +1 -0
  12. package/dist/adminTextSearch.js +22 -78
  13. package/dist/adminUiV2.d.ts +2 -0
  14. package/dist/adminUiV2.js +49 -146
  15. package/dist/aggregateAdmin.js +104 -227
  16. package/dist/documentStorageApp.js +184 -325
  17. package/dist/enrichAdminListFilters.d.ts +7 -0
  18. package/dist/enrichAdminListFilters.js +26 -0
  19. package/dist/filterParser.js +230 -183
  20. package/dist/index.d.ts +2 -0
  21. package/dist/index.js +4 -1
  22. package/dist/legacy.js +21 -23
  23. package/dist/resolvedAdminModel.js +23 -78
  24. package/dist/routePath.js +3 -3
  25. package/dist/scriptCli.js +161 -307
  26. package/dist/tests/bunSetup.js +1 -1
  27. package/package.json +10 -10
  28. package/src/adminApp.migrations.test.ts +232 -0
  29. package/src/adminApp.models.test.ts +731 -1
  30. package/src/adminApp.syncMeta.test.ts +237 -0
  31. package/src/adminApp.test.ts +92 -0
  32. package/src/adminApp.ts +373 -130
  33. package/src/adminConfigIdentity.ts +1 -0
  34. package/src/adminHttpGoldens.test.ts +337 -0
  35. package/src/adminMigrations.ts +157 -0
  36. package/src/adminScriptJob.test.ts +297 -0
  37. package/src/adminScriptJob.ts +271 -0
  38. package/src/adminSyncMutationAuthMismatch.test.ts +650 -0
  39. package/src/adminTextSearch.test.ts +28 -0
  40. package/src/adminTextSearch.ts +1 -0
  41. package/src/adminUiV2.ts +2 -0
  42. package/src/aggregateAdmin.test.ts +125 -0
  43. package/src/aggregateAdmin.ts +2 -0
  44. package/src/enrichAdminListFilters.test.ts +44 -0
  45. package/src/enrichAdminListFilters.ts +29 -0
  46. package/src/filterParser.test.ts +95 -0
  47. package/src/filterParser.ts +156 -10
  48. package/src/index.ts +2 -0
  49. package/src/legacy.ts +5 -1
  50. package/src/resolvedAdminModel.ts +2 -1
  51. package/tsconfig.json +6 -21
@@ -0,0 +1,650 @@
1
+ /**
2
+ * Admin windowed sync write authorization: REST and `POST /sync/mutate` with
3
+ * `mutationMode: "adminWindow"` must enforce the same AdminApp semantics.
4
+ */
5
+ import {afterEach, beforeEach, describe, expect, it} from "bun:test";
6
+ import {
7
+ ADMIN_MODEL_ACCESS,
8
+ addAuthRoutes,
9
+ apiErrorMiddleware,
10
+ apiUnauthorizedMiddleware,
11
+ clearSyncRegistry,
12
+ createAccess,
13
+ createdUpdatedPlugin,
14
+ findOneOrNoneFor,
15
+ isDeletedPlugin,
16
+ Membership,
17
+ Organization,
18
+ orgScopedPlugin,
19
+ Permissions,
20
+ registerSync,
21
+ SyncApp,
22
+ setupAuth,
23
+ syncPlugin,
24
+ terrenoStatements,
25
+ type User,
26
+ type UserModel as UserModelType,
27
+ } from "@terreno/api";
28
+ import {authAsUser, getBaseServer, setupDb, UserModel} from "@terreno/api/testing";
29
+ import {assert} from "chai";
30
+ import type express from "express";
31
+ import mongoose from "mongoose";
32
+ import type TestAgent from "supertest/lib/agent";
33
+
34
+ import type {AdminAuditEvent, AdminModelConfig} from "./adminApp";
35
+ import {AdminApp, adminOwnedBy} from "./adminApp";
36
+
37
+ interface WindowTodo {
38
+ _id: string;
39
+ ownerId: string;
40
+ title: string;
41
+ protectedLabel?: string;
42
+ _syncSeq?: number;
43
+ }
44
+
45
+ const windowTodoSchema = new mongoose.Schema<WindowTodo>({
46
+ _id: {
47
+ default: (): string => new mongoose.Types.ObjectId().toHexString(),
48
+ description: "Client-minted string id",
49
+ type: String,
50
+ },
51
+ ownerId: {description: "Owner user id", required: true, type: String},
52
+ protectedLabel: {description: "Admin readonly label", type: String},
53
+ title: {description: "Todo title", required: true, type: String},
54
+ });
55
+ windowTodoSchema.plugin(isDeletedPlugin);
56
+ windowTodoSchema.plugin(createdUpdatedPlugin);
57
+ windowTodoSchema.plugin(syncPlugin);
58
+
59
+ const WindowTodoModel =
60
+ mongoose.models.WindowTodo ?? mongoose.model<WindowTodo>("WindowTodo", windowTodoSchema);
61
+
62
+ const windowTodoAdminConfig: AdminModelConfig = {
63
+ adminAccess: {isOwned: adminOwnedBy("ownerId")},
64
+ displayName: "Window todos",
65
+ listFields: ["title", "ownerId", "protectedLabel"],
66
+ model: WindowTodoModel,
67
+ permissions: {delete: false, update: true},
68
+ readonlyFields: ["protectedLabel"],
69
+ routePath: "/window-todos",
70
+ };
71
+
72
+ const productSyncOptions = {
73
+ permissions: {
74
+ create: [Permissions.IsAuthenticated],
75
+ delete: [Permissions.IsAuthenticated],
76
+ list: [Permissions.IsAuthenticated],
77
+ read: [Permissions.IsAuthenticated],
78
+ update: [Permissions.IsOwner],
79
+ },
80
+ preCreate: (body: Record<string, unknown>, req: express.Request): Record<string, unknown> => ({
81
+ ...body,
82
+ ownerId: String((req.user as {id?: string} | undefined)?.id ?? body.ownerId),
83
+ }),
84
+ sync: {adminBroadcast: true, scope: {type: "owner" as const}},
85
+ };
86
+
87
+ const buildHarness = ({
88
+ grants,
89
+ onAdminAudit,
90
+ productHookTracker,
91
+ resolvePermissions,
92
+ }: {
93
+ grants: Record<string, string[]>;
94
+ onAdminAudit?: (event: AdminAuditEvent) => void | Promise<void>;
95
+ productHookTracker?: {postUpdateCalls: number; preCreateCalls: number; preUpdateCalls: number};
96
+ resolvePermissions?: (args: {user: User}) => Promise<Record<string, string[]>>;
97
+ }): express.Application => {
98
+ clearSyncRegistry();
99
+ registerSync({
100
+ config: {adminBroadcast: true, scope: {type: "owner"}},
101
+ model: WindowTodoModel,
102
+ options: {
103
+ ...productSyncOptions,
104
+ postUpdate: async (doc, cleanedBody, request, prevDoc) => {
105
+ if (productHookTracker) {
106
+ productHookTracker.postUpdateCalls++;
107
+ }
108
+ void doc;
109
+ void cleanedBody;
110
+ void request;
111
+ void prevDoc;
112
+ },
113
+ preCreate: (body, req) => {
114
+ if (productHookTracker) {
115
+ productHookTracker.preCreateCalls++;
116
+ }
117
+ return productSyncOptions.preCreate(body, req);
118
+ },
119
+ preUpdate: (body, _req) => {
120
+ if (productHookTracker) {
121
+ productHookTracker.preUpdateCalls++;
122
+ }
123
+ return body as Record<string, unknown>;
124
+ },
125
+ },
126
+ routePath: "/window-todos",
127
+ });
128
+
129
+ const accessControl = createAccess({
130
+ connection: mongoose.connection,
131
+ resolvePermissions:
132
+ resolvePermissions ??
133
+ (async ({user}) => {
134
+ if (user?.admin) {
135
+ return grants;
136
+ }
137
+ return {};
138
+ }),
139
+ statements: {...terrenoStatements, adminWindowTodo: ADMIN_MODEL_ACCESS},
140
+ });
141
+
142
+ const app = getBaseServer();
143
+ setupAuth(app, UserModel as unknown as UserModelType);
144
+ addAuthRoutes(app, UserModel as unknown as UserModelType);
145
+ new AdminApp({
146
+ accessControl,
147
+ basePath: "/admin",
148
+ models: [
149
+ {
150
+ ...windowTodoAdminConfig,
151
+ adminAccess: {
152
+ isOwned: adminOwnedBy("ownerId"),
153
+ resource: "adminWindowTodo",
154
+ },
155
+ },
156
+ ],
157
+ onAdminAudit,
158
+ }).register(app);
159
+ new SyncApp({accessControl}).register(app);
160
+ app.use(apiUnauthorizedMiddleware);
161
+ app.use(apiErrorMiddleware);
162
+ return app;
163
+ };
164
+
165
+ const adminWindowMutate = (body: Record<string, unknown>): Record<string, unknown> => ({
166
+ ...body,
167
+ mutationMode: "adminWindow",
168
+ });
169
+
170
+ describe("admin window sync mutation authorization", () => {
171
+ let agent: TestAgent;
172
+ let actorId: string;
173
+ let otherOwnerId: string;
174
+
175
+ beforeEach(async () => {
176
+ await setupDb();
177
+ otherOwnerId = new mongoose.Types.ObjectId().toHexString();
178
+ const app = buildHarness({
179
+ grants: {admin: ["access"], adminWindowTodo: ["read", "writeOwned"]},
180
+ });
181
+ agent = await authAsUser(app, "admin");
182
+ const actor = await findOneOrNoneFor(UserModel, {email: "admin@example.com"});
183
+ assert.exists(actor);
184
+ actorId = String(actor?._id);
185
+ });
186
+
187
+ afterEach(async () => {
188
+ clearSyncRegistry();
189
+ await WindowTodoModel.deleteMany({});
190
+ });
191
+
192
+ it("REST PATCH and admin-window sync both deny writeOwned update on another owner's row", async () => {
193
+ const owned = await WindowTodoModel.create({
194
+ ownerId: actorId,
195
+ protectedLabel: "mine",
196
+ title: "Owned",
197
+ });
198
+ const other = await WindowTodoModel.create({
199
+ ownerId: otherOwnerId,
200
+ protectedLabel: "theirs",
201
+ title: "Other",
202
+ });
203
+
204
+ await agent.patch(`/admin/window-todos/${other._id}`).send({title: "REST blocked"}).expect(403);
205
+
206
+ const syncRes = await agent
207
+ .post("/sync/mutate")
208
+ .send(
209
+ adminWindowMutate({
210
+ baseVersion: other._syncSeq ?? 1,
211
+ collection: "window-todos",
212
+ data: {title: "Sync blocked"},
213
+ id: other._id,
214
+ mutationId: "admin-writeowned-deny",
215
+ operation: "update",
216
+ })
217
+ )
218
+ .expect(403);
219
+
220
+ expect(syncRes.body.nack.code).toBe("unauthorized");
221
+ const reloaded = await WindowTodoModel.findById(other._id).lean();
222
+ expect(reloaded?.title).toBe("Other");
223
+
224
+ await agent.patch(`/admin/window-todos/${owned._id}`).send({title: "REST ok"}).expect(200);
225
+ });
226
+
227
+ it("REST PATCH and admin-window sync both strip readonlyFields", async () => {
228
+ const row = await WindowTodoModel.create({
229
+ ownerId: actorId,
230
+ protectedLabel: "keep-me",
231
+ title: "Before",
232
+ });
233
+
234
+ await agent
235
+ .patch(`/admin/window-todos/${row._id}`)
236
+ .send({protectedLabel: "REST stripped", title: "After REST"})
237
+ .expect(200);
238
+
239
+ const afterRest = await WindowTodoModel.findById(row._id).lean();
240
+ expect(afterRest?.protectedLabel).toBe("keep-me");
241
+ expect(afterRest?.title).toBe("After REST");
242
+
243
+ const syncRes = await agent
244
+ .post("/sync/mutate")
245
+ .send(
246
+ adminWindowMutate({
247
+ baseVersion: afterRest?._syncSeq ?? 2,
248
+ collection: "window-todos",
249
+ data: {protectedLabel: "Sync stripped", title: "After sync"},
250
+ id: row._id,
251
+ mutationId: "admin-readonly-strip",
252
+ operation: "update",
253
+ })
254
+ )
255
+ .expect(200);
256
+
257
+ expect(syncRes.body.ack.mutationId).toBe("admin-readonly-strip");
258
+ const afterSync = await WindowTodoModel.findById(row._id).lean();
259
+ expect(afterSync?.protectedLabel).toBe("keep-me");
260
+ expect(afterSync?.title).toBe("After sync");
261
+ });
262
+
263
+ it("REST DELETE disabled and admin-window sync delete both return unauthorized", async () => {
264
+ const row = await WindowTodoModel.create({
265
+ ownerId: actorId,
266
+ title: "To delete",
267
+ });
268
+
269
+ const restDelete = await agent.delete(`/admin/window-todos/${row._id}`);
270
+ expect([403, 405]).toContain(restDelete.status);
271
+
272
+ const syncRes = await agent
273
+ .post("/sync/mutate")
274
+ .send(
275
+ adminWindowMutate({
276
+ collection: "window-todos",
277
+ id: row._id,
278
+ mutationId: "admin-delete-disabled",
279
+ operation: "delete",
280
+ })
281
+ )
282
+ .expect(403);
283
+
284
+ expect(syncRes.body.nack.code).toBe("unauthorized");
285
+ const stillThere = await WindowTodoModel.findById(row._id).lean();
286
+ expect(stillThere?.deleted).not.toBe(true);
287
+ });
288
+
289
+ it("onAdminAudit fires for REST PATCH and admin-window sync update", async () => {
290
+ const auditEvents: AdminAuditEvent[] = [];
291
+ const app = buildHarness({
292
+ grants: {admin: ["access"], adminWindowTodo: ["read", "write"]},
293
+ onAdminAudit: async (event) => {
294
+ auditEvents.push(event);
295
+ },
296
+ });
297
+ const writer = await authAsUser(app, "admin");
298
+ const row = await WindowTodoModel.create({
299
+ ownerId: actorId,
300
+ title: "Audited",
301
+ });
302
+
303
+ await writer.patch(`/admin/window-todos/${row._id}`).send({title: "REST audit"}).expect(200);
304
+ expect(auditEvents.filter((event) => event.verb === "updated")).toHaveLength(1);
305
+
306
+ const current = await WindowTodoModel.findById(row._id).lean();
307
+ await writer
308
+ .post("/sync/mutate")
309
+ .send(
310
+ adminWindowMutate({
311
+ baseVersion: current?._syncSeq ?? 2,
312
+ collection: "window-todos",
313
+ data: {title: "Sync audit"},
314
+ id: row._id,
315
+ mutationId: "admin-sync-audit",
316
+ operation: "update",
317
+ })
318
+ )
319
+ .expect(200);
320
+
321
+ expect(auditEvents.filter((event) => event.verb === "updated")).toHaveLength(2);
322
+ });
323
+
324
+ it("rejects admin-window marker spoofing from a non-admin product user", async () => {
325
+ const app = buildHarness({
326
+ grants: {admin: ["access"], adminWindowTodo: ["read", "write"]},
327
+ });
328
+ const stranger = await authAsUser(app, "notAdmin");
329
+ const row = await WindowTodoModel.create({
330
+ ownerId: otherOwnerId,
331
+ title: "Protected",
332
+ });
333
+
334
+ const syncRes = await stranger
335
+ .post("/sync/mutate")
336
+ .send(
337
+ adminWindowMutate({
338
+ baseVersion: row._syncSeq ?? 1,
339
+ collection: "window-todos",
340
+ data: {title: "Spoofed"},
341
+ id: row._id,
342
+ mutationId: "spoof-admin-window",
343
+ operation: "update",
344
+ })
345
+ )
346
+ .expect(403);
347
+
348
+ expect(syncRes.body.nack.code).toBe("unauthorized");
349
+ const reloaded = await WindowTodoModel.findById(row._id).lean();
350
+ expect(reloaded?.title).toBe("Protected");
351
+ });
352
+
353
+ it("product sync path without admin-window marker keeps IsOwner semantics", async () => {
354
+ const app = buildHarness({
355
+ grants: {admin: ["access"], adminWindowTodo: ["read", "write"]},
356
+ });
357
+ const productUser = await authAsUser(app, "notAdmin");
358
+ const row = await WindowTodoModel.create({
359
+ ownerId: otherOwnerId,
360
+ title: "Product path",
361
+ });
362
+
363
+ const syncRes = await productUser
364
+ .post("/sync/mutate")
365
+ .send({
366
+ baseVersion: row._syncSeq ?? 1,
367
+ collection: "window-todos",
368
+ data: {title: "Product denied"},
369
+ id: row._id,
370
+ mutationId: "product-isowner-deny",
371
+ operation: "update",
372
+ })
373
+ .expect(403);
374
+
375
+ expect(syncRes.body.nack.code).toBe("unauthorized");
376
+ const reloaded = await WindowTodoModel.findById(row._id).lean();
377
+ expect(reloaded?.title).toBe("Product path");
378
+ });
379
+
380
+ it("admin-window sync does not run product pre/post hooks", async () => {
381
+ const tracker = {postUpdateCalls: 0, preCreateCalls: 0, preUpdateCalls: 0};
382
+ const app = buildHarness({
383
+ grants: {admin: ["access"], adminWindowTodo: ["read", "write"]},
384
+ productHookTracker: tracker,
385
+ });
386
+ const writer = await authAsUser(app, "admin");
387
+ const row = await WindowTodoModel.create({
388
+ ownerId: actorId,
389
+ title: "Hook isolation",
390
+ });
391
+
392
+ await writer
393
+ .post("/sync/mutate")
394
+ .send(
395
+ adminWindowMutate({
396
+ baseVersion: row._syncSeq ?? 1,
397
+ collection: "window-todos",
398
+ data: {title: "Admin hooks only"},
399
+ id: row._id,
400
+ mutationId: "admin-hook-isolation",
401
+ operation: "update",
402
+ })
403
+ )
404
+ .expect(200);
405
+
406
+ expect(tracker.preCreateCalls).toBe(0);
407
+ expect(tracker.preUpdateCalls).toBe(0);
408
+ expect(tracker.postUpdateCalls).toBe(0);
409
+ });
410
+
411
+ it("product sync without admin-window marker still runs product preUpdate", async () => {
412
+ const tracker = {postUpdateCalls: 0, preCreateCalls: 0, preUpdateCalls: 0};
413
+ const app = buildHarness({
414
+ grants: {admin: ["access"], adminWindowTodo: ["read", "write"]},
415
+ productHookTracker: tracker,
416
+ });
417
+ const owner = await authAsUser(app, "notAdmin");
418
+ const ownerDoc = await findOneOrNoneFor(UserModel, {email: "notAdmin@example.com"});
419
+ assert.exists(ownerDoc);
420
+ const ownerUserId = String(ownerDoc?._id);
421
+ const row = await WindowTodoModel.create({
422
+ ownerId: ownerUserId,
423
+ title: "Owned",
424
+ });
425
+
426
+ await owner
427
+ .post("/sync/mutate")
428
+ .send({
429
+ baseVersion: row._syncSeq ?? 1,
430
+ collection: "window-todos",
431
+ data: {title: "Product hook ok"},
432
+ id: row._id,
433
+ mutationId: "product-preupdate-runs",
434
+ operation: "update",
435
+ })
436
+ .expect(200);
437
+
438
+ expect(tracker.preUpdateCalls).toBe(1);
439
+ expect(tracker.postUpdateCalls).toBe(1);
440
+ expect(tracker.preCreateCalls).toBe(0);
441
+ });
442
+
443
+ it("admin-window sync update invokes AdminApp post hooks for audit", async () => {
444
+ const auditEvents: AdminAuditEvent[] = [];
445
+ const app = buildHarness({
446
+ grants: {admin: ["access"], adminWindowTodo: ["read", "write"]},
447
+ onAdminAudit: async (event) => {
448
+ auditEvents.push(event);
449
+ },
450
+ });
451
+ const writer = await authAsUser(app, "admin");
452
+ const row = await WindowTodoModel.create({
453
+ ownerId: actorId,
454
+ title: "Post hook audit",
455
+ });
456
+
457
+ await writer
458
+ .post("/sync/mutate")
459
+ .send(
460
+ adminWindowMutate({
461
+ baseVersion: row._syncSeq ?? 1,
462
+ collection: "window-todos",
463
+ data: {title: "Audited via post hook"},
464
+ id: row._id,
465
+ mutationId: "admin-post-hook-audit",
466
+ operation: "update",
467
+ })
468
+ )
469
+ .expect(200);
470
+
471
+ expect(auditEvents).toHaveLength(1);
472
+ expect(auditEvents[0]?.verb).toBe("updated");
473
+ expect(auditEvents[0]?.actorId).toBe(actorId);
474
+ });
475
+ });
476
+
477
+ interface WindowOrgTodo {
478
+ _id: string;
479
+ organizationId: mongoose.Types.ObjectId;
480
+ title: string;
481
+ _syncSeq?: number;
482
+ }
483
+
484
+ const windowOrgTodoSchema = new mongoose.Schema<WindowOrgTodo>({
485
+ _id: {
486
+ default: (): string => new mongoose.Types.ObjectId().toHexString(),
487
+ description: "Client-minted string id",
488
+ type: String,
489
+ },
490
+ title: {description: "Todo title", required: true, type: String},
491
+ });
492
+ windowOrgTodoSchema.plugin(orgScopedPlugin);
493
+ windowOrgTodoSchema.plugin(isDeletedPlugin);
494
+ windowOrgTodoSchema.plugin(createdUpdatedPlugin);
495
+ windowOrgTodoSchema.plugin(syncPlugin);
496
+
497
+ const WindowOrgTodoModel =
498
+ mongoose.models.WindowOrgTodo ??
499
+ mongoose.model<WindowOrgTodo>("WindowOrgTodo", windowOrgTodoSchema);
500
+
501
+ const buildOrgWindowHarness = (): express.Application => {
502
+ clearSyncRegistry();
503
+ registerSync({
504
+ config: {adminBroadcast: true, scope: {field: "organizationId", type: "tenant"}},
505
+ model: WindowOrgTodoModel,
506
+ options: {
507
+ permissions: {
508
+ create: [Permissions.IsAuthenticated],
509
+ delete: [Permissions.IsAuthenticated],
510
+ list: [Permissions.IsAuthenticated],
511
+ read: [Permissions.IsAuthenticated],
512
+ update: [Permissions.IsAuthenticated],
513
+ },
514
+ sync: {adminBroadcast: true, scope: {field: "organizationId", type: "tenant" as const}},
515
+ },
516
+ routePath: "/window-org-todos",
517
+ });
518
+
519
+ const accessControl = createAccess({
520
+ connection: mongoose.connection,
521
+ organizations: true,
522
+ resolvePermissions: async ({user}) => {
523
+ if (user?.admin) {
524
+ return {admin: ["access"], adminWindowOrgTodo: ["read", "write"]};
525
+ }
526
+ return {};
527
+ },
528
+ statements: {...terrenoStatements, adminWindowOrgTodo: ADMIN_MODEL_ACCESS},
529
+ userModel: UserModel as unknown as UserModelType,
530
+ });
531
+
532
+ const app = getBaseServer();
533
+ setupAuth(app, UserModel as unknown as UserModelType);
534
+ addAuthRoutes(app, UserModel as unknown as UserModelType);
535
+ new AdminApp({
536
+ accessControl,
537
+ basePath: "/admin",
538
+ models: [
539
+ {
540
+ adminAccess: {resource: "adminWindowOrgTodo"},
541
+ displayName: "Window org todos",
542
+ listFields: ["title", "organizationId"],
543
+ model: WindowOrgTodoModel,
544
+ routePath: "/window-org-todos",
545
+ },
546
+ ],
547
+ organizations: true,
548
+ }).register(app);
549
+ new SyncApp({accessControl}).register(app);
550
+ app.use(apiUnauthorizedMiddleware);
551
+ app.use(apiErrorMiddleware);
552
+ return app;
553
+ };
554
+
555
+ describe("admin window org-scoped mutation membership", () => {
556
+ let agent: TestAgent;
557
+ let firstOrgId: string;
558
+ let secondOrgId: string;
559
+
560
+ beforeEach(async () => {
561
+ const [admin] = await setupDb();
562
+ admin.roles = ["operator"];
563
+ await admin.save();
564
+ await Promise.all([
565
+ Membership.deleteMany({}),
566
+ Organization.deleteMany({}),
567
+ WindowOrgTodoModel.deleteMany({}),
568
+ ]);
569
+ const app = buildOrgWindowHarness();
570
+ agent = await authAsUser(app, "admin");
571
+ const [firstOrg, secondOrg] = await Organization.create([
572
+ {name: "First Org", ownerId: admin._id},
573
+ {name: "Second Org", ownerId: admin._id},
574
+ ]);
575
+ firstOrgId = String(firstOrg._id);
576
+ secondOrgId = String(secondOrg._id);
577
+ });
578
+
579
+ afterEach(async () => {
580
+ clearSyncRegistry();
581
+ await WindowOrgTodoModel.deleteMany({});
582
+ });
583
+
584
+ it("REST PATCH denies another org's row; admin-window sync is disabled for org-scoped models", async () => {
585
+ const other = await WindowOrgTodoModel.create({
586
+ organizationId: secondOrgId,
587
+ title: "Other org",
588
+ });
589
+
590
+ await agent
591
+ .patch(`/admin/window-org-todos/${other._id}`)
592
+ .set("X-Organization-Id", firstOrgId)
593
+ .send({title: "REST blocked"})
594
+ .expect(403);
595
+
596
+ const syncRes = await agent
597
+ .post("/sync/mutate")
598
+ .set("X-Organization-Id", firstOrgId)
599
+ .send(
600
+ adminWindowMutate({
601
+ baseVersion: other._syncSeq ?? 1,
602
+ collection: "window-org-todos",
603
+ data: {title: "Sync blocked"},
604
+ id: other._id,
605
+ mutationId: "admin-org-membership-deny",
606
+ operation: "update",
607
+ })
608
+ )
609
+ .expect(403);
610
+
611
+ expect(JSON.stringify(syncRes.body)).toContain("adminBroadcast");
612
+ const reloaded = await WindowOrgTodoModel.findById(other._id).lean();
613
+ expect(reloaded?.title).toBe("Other org");
614
+ });
615
+
616
+ it("REST PATCH allows update of the current org's row; admin-window sync stays disabled", async () => {
617
+ const owned = await WindowOrgTodoModel.create({
618
+ organizationId: firstOrgId,
619
+ title: "Same org",
620
+ });
621
+
622
+ await agent
623
+ .patch(`/admin/window-org-todos/${owned._id}`)
624
+ .set("X-Organization-Id", firstOrgId)
625
+ .send({title: "REST ok"})
626
+ .expect(200);
627
+
628
+ const afterRest = await WindowOrgTodoModel.findById(owned._id).lean();
629
+ expect(afterRest?.title).toBe("REST ok");
630
+
631
+ const syncRes = await agent
632
+ .post("/sync/mutate")
633
+ .set("X-Organization-Id", firstOrgId)
634
+ .send(
635
+ adminWindowMutate({
636
+ baseVersion: afterRest?._syncSeq ?? 2,
637
+ collection: "window-org-todos",
638
+ data: {title: "Sync ok"},
639
+ id: owned._id,
640
+ mutationId: "admin-org-membership-allow",
641
+ operation: "update",
642
+ })
643
+ )
644
+ .expect(403);
645
+
646
+ expect(JSON.stringify(syncRes.body)).toContain("adminBroadcast");
647
+ const afterSyncAttempt = await WindowOrgTodoModel.findById(owned._id).lean();
648
+ expect(afterSyncAttempt?.title).toBe("REST ok");
649
+ });
650
+ });
@@ -52,6 +52,30 @@ describe("buildAdminPartialSearchFilter", () => {
52
52
  $or: [{name: {$regex: new RegExp(id, "i")}}, {ownerId: new mongoose.Types.ObjectId(id)}],
53
53
  });
54
54
  });
55
+
56
+ it("returns undefined for blank search text", () => {
57
+ const filter = buildAdminPartialSearchFilter({
58
+ model: {schema: foodSchema},
59
+ q: " ",
60
+ searchFields: ["name"],
61
+ });
62
+ assert.isUndefined(filter);
63
+ });
64
+
65
+ it("discovers ObjectId schema paths when extraObjectIdFields is omitted", () => {
66
+ const id = new mongoose.Types.ObjectId().toString();
67
+ const filter = buildAdminPartialSearchFilter({
68
+ model: {schema: foodSchema},
69
+ q: id,
70
+ searchFields: ["name"],
71
+ });
72
+ // Mongoose reports ObjectId instance as "ObjectId"; this helper only
73
+ // auto-discovers paths whose instance is "ObjectID", so ownerId is omitted
74
+ // unless extraObjectIdFields is set.
75
+ assert.deepEqual(filter, {
76
+ $or: [{name: {$regex: new RegExp(id, "i")}}],
77
+ });
78
+ });
55
79
  });
56
80
 
57
81
  describe("andMongoFilters", () => {
@@ -59,6 +83,10 @@ describe("andMongoFilters", () => {
59
83
  expect(andMongoFilters({}, {name: "x"})).toEqual({name: "x"});
60
84
  });
61
85
 
86
+ it("returns the base when extra is omitted", () => {
87
+ assert.deepEqual(andMongoFilters({completed: true}, undefined), {completed: true});
88
+ });
89
+
62
90
  it("wraps both sides in $and", () => {
63
91
  expect(andMongoFilters({completed: true}, {$or: [{name: /a/i}]})).toEqual({
64
92
  $and: [{completed: true}, {$or: [{name: /a/i}]}],
@@ -3,6 +3,7 @@ import mongoose from "mongoose";
3
3
  /** List-query param for the admin table search box. */
4
4
  export const ADMIN_LIST_SEARCH_PARAM = "q";
5
5
 
6
+ /** @internal */
6
7
  export const escapeRegexLiteral = (value: string): string => {
7
8
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8
9
  };
package/src/adminUiV2.ts CHANGED
@@ -78,6 +78,8 @@ export interface AdminListFilterBoolean {
78
78
 
79
79
  export interface AdminListFilterChoice {
80
80
  choices: {label: string; value: string}[];
81
+ /** When true, filter UI offers Empty and parser accepts `__empty__` sentinel. */
82
+ allowEmpty?: boolean;
81
83
  field: string;
82
84
  kind: "choice";
83
85
  label?: string;