@opensaas/stack-core 0.39.2 → 0.41.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 (165) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +189 -0
  3. package/CLAUDE.md +103 -0
  4. package/dist/access/access-filter.d.ts +157 -14
  5. package/dist/access/access-filter.d.ts.map +1 -1
  6. package/dist/access/access-filter.js +470 -42
  7. package/dist/access/access-filter.js.map +1 -1
  8. package/dist/access/access-filter.test.js +982 -17
  9. package/dist/access/access-filter.test.js.map +1 -1
  10. package/dist/access/denied-relation-visibility.test.d.ts +2 -0
  11. package/dist/access/denied-relation-visibility.test.d.ts.map +1 -0
  12. package/dist/access/denied-relation-visibility.test.js +114 -0
  13. package/dist/access/denied-relation-visibility.test.js.map +1 -0
  14. package/dist/access/engine.d.ts +54 -1
  15. package/dist/access/engine.d.ts.map +1 -1
  16. package/dist/access/engine.js +84 -0
  17. package/dist/access/engine.js.map +1 -1
  18. package/dist/access/engine.test.d.ts +2 -0
  19. package/dist/access/engine.test.d.ts.map +1 -0
  20. package/dist/access/engine.test.js +56 -0
  21. package/dist/access/engine.test.js.map +1 -0
  22. package/dist/access/errors.d.ts +62 -0
  23. package/dist/access/errors.d.ts.map +1 -1
  24. package/dist/access/errors.js +85 -2
  25. package/dist/access/errors.js.map +1 -1
  26. package/dist/access/field-access.d.ts +12 -0
  27. package/dist/access/field-access.d.ts.map +1 -1
  28. package/dist/access/field-access.js +22 -2
  29. package/dist/access/field-access.js.map +1 -1
  30. package/dist/access/field-access.test.js +66 -0
  31. package/dist/access/field-access.test.js.map +1 -1
  32. package/dist/access/field-visibility.d.ts +2 -1
  33. package/dist/access/field-visibility.d.ts.map +1 -1
  34. package/dist/access/field-visibility.js +107 -15
  35. package/dist/access/field-visibility.js.map +1 -1
  36. package/dist/access/index.d.ts +9 -2
  37. package/dist/access/index.d.ts.map +1 -1
  38. package/dist/access/index.js +11 -2
  39. package/dist/access/index.js.map +1 -1
  40. package/dist/access/multi-column-read-write.test.js.map +1 -1
  41. package/dist/access/query-validation.d.ts +31 -0
  42. package/dist/access/query-validation.d.ts.map +1 -1
  43. package/dist/access/query-validation.js +75 -16
  44. package/dist/access/query-validation.js.map +1 -1
  45. package/dist/access/relationship-count.d.ts +41 -3
  46. package/dist/access/relationship-count.d.ts.map +1 -1
  47. package/dist/access/relationship-count.js +44 -7
  48. package/dist/access/relationship-count.js.map +1 -1
  49. package/dist/access/relationship-count.test.js +62 -0
  50. package/dist/access/relationship-count.test.js.map +1 -1
  51. package/dist/access/synthetic-include-read.test.d.ts +2 -0
  52. package/dist/access/synthetic-include-read.test.d.ts.map +1 -0
  53. package/dist/access/synthetic-include-read.test.js +121 -0
  54. package/dist/access/synthetic-include-read.test.js.map +1 -0
  55. package/dist/config/types.d.ts +98 -32
  56. package/dist/config/types.d.ts.map +1 -1
  57. package/dist/context/hook-pipeline.d.ts +2 -2
  58. package/dist/context/hook-pipeline.d.ts.map +1 -1
  59. package/dist/context/hook-pipeline.js.map +1 -1
  60. package/dist/context/index.d.ts +35 -2
  61. package/dist/context/index.d.ts.map +1 -1
  62. package/dist/context/index.js +121 -27
  63. package/dist/context/index.js.map +1 -1
  64. package/dist/context/nested-operations.d.ts +2 -2
  65. package/dist/context/nested-operations.d.ts.map +1 -1
  66. package/dist/context/nested-operations.js +74 -15
  67. package/dist/context/nested-operations.js.map +1 -1
  68. package/dist/context/write-pipeline.d.ts +3 -2
  69. package/dist/context/write-pipeline.d.ts.map +1 -1
  70. package/dist/context/write-pipeline.js +31 -34
  71. package/dist/context/write-pipeline.js.map +1 -1
  72. package/dist/fields/index.d.ts +13 -1
  73. package/dist/fields/index.d.ts.map +1 -1
  74. package/dist/fields/index.js +50 -5
  75. package/dist/fields/index.js.map +1 -1
  76. package/dist/fields/relationship-foreign-key.test.d.ts +2 -0
  77. package/dist/fields/relationship-foreign-key.test.d.ts.map +1 -0
  78. package/dist/fields/relationship-foreign-key.test.js +18 -0
  79. package/dist/fields/relationship-foreign-key.test.js.map +1 -0
  80. package/dist/hooks/index.d.ts +16 -15
  81. package/dist/hooks/index.d.ts.map +1 -1
  82. package/dist/hooks/index.js.map +1 -1
  83. package/dist/index.d.ts +4 -1
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +14 -1
  86. package/dist/index.js.map +1 -1
  87. package/dist/lib/case-utils.d.ts +15 -0
  88. package/dist/lib/case-utils.d.ts.map +1 -1
  89. package/dist/lib/case-utils.js +21 -0
  90. package/dist/lib/case-utils.js.map +1 -1
  91. package/dist/lib/case-utils.test.js +23 -1
  92. package/dist/lib/case-utils.test.js.map +1 -1
  93. package/dist/lib/prisma-errors.d.ts +38 -0
  94. package/dist/lib/prisma-errors.d.ts.map +1 -0
  95. package/dist/lib/prisma-errors.js +53 -0
  96. package/dist/lib/prisma-errors.js.map +1 -0
  97. package/dist/mcp/constants.d.ts +23 -0
  98. package/dist/mcp/constants.d.ts.map +1 -0
  99. package/dist/mcp/constants.js +23 -0
  100. package/dist/mcp/constants.js.map +1 -0
  101. package/dist/mcp/field-schema.d.ts +8 -0
  102. package/dist/mcp/field-schema.d.ts.map +1 -0
  103. package/dist/mcp/field-schema.js +69 -0
  104. package/dist/mcp/field-schema.js.map +1 -0
  105. package/dist/mcp/handler.d.ts.map +1 -1
  106. package/dist/mcp/handler.js +76 -90
  107. package/dist/mcp/handler.js.map +1 -1
  108. package/dist/mcp/projection.d.ts +62 -0
  109. package/dist/mcp/projection.d.ts.map +1 -0
  110. package/dist/mcp/projection.js +390 -0
  111. package/dist/mcp/projection.js.map +1 -0
  112. package/dist/utils/password.d.ts +3 -1
  113. package/dist/utils/password.d.ts.map +1 -1
  114. package/dist/utils/password.js +4 -2
  115. package/dist/utils/password.js.map +1 -1
  116. package/package.json +2 -2
  117. package/src/access/access-filter.test.ts +1528 -18
  118. package/src/access/access-filter.ts +708 -42
  119. package/src/access/denied-relation-visibility.test.ts +173 -0
  120. package/src/access/engine.test.ts +67 -0
  121. package/src/access/engine.ts +109 -1
  122. package/src/access/errors.ts +97 -2
  123. package/src/access/field-access.test.ts +78 -0
  124. package/src/access/field-access.ts +34 -2
  125. package/src/access/field-visibility.ts +171 -25
  126. package/src/access/index.ts +25 -0
  127. package/src/access/multi-column-read-write.test.ts +3 -2
  128. package/src/access/query-validation.ts +136 -9
  129. package/src/access/relationship-count.test.ts +75 -0
  130. package/src/access/relationship-count.ts +53 -10
  131. package/src/access/synthetic-include-read.test.ts +179 -0
  132. package/src/config/types.ts +98 -32
  133. package/src/context/hook-pipeline.ts +4 -2
  134. package/src/context/index.ts +203 -42
  135. package/src/context/nested-operations.ts +96 -27
  136. package/src/context/write-pipeline.ts +60 -36
  137. package/src/fields/index.ts +55 -5
  138. package/src/fields/relationship-foreign-key.test.ts +29 -0
  139. package/src/hooks/index.ts +22 -15
  140. package/src/index.ts +17 -1
  141. package/src/lib/case-utils.test.ts +32 -0
  142. package/src/lib/case-utils.ts +26 -0
  143. package/src/lib/prisma-errors.ts +86 -0
  144. package/src/mcp/constants.ts +24 -0
  145. package/src/mcp/field-schema.ts +84 -0
  146. package/src/mcp/handler.ts +109 -107
  147. package/src/mcp/projection.ts +497 -0
  148. package/src/utils/password.ts +5 -3
  149. package/tests/access-relationships.test.ts +3 -3
  150. package/tests/access.test.ts +83 -0
  151. package/tests/context.test.ts +452 -17
  152. package/tests/field-types.test.ts +113 -0
  153. package/tests/hook-context-secured.test.ts +424 -0
  154. package/tests/mcp-fields-projection-access.test.ts +250 -0
  155. package/tests/mcp-handler.test.ts +695 -4
  156. package/tests/nested-access-and-hooks.test.ts +389 -0
  157. package/tests/nested-write-synthetic-relation.test.ts +437 -0
  158. package/tests/password-types.test.ts +28 -0
  159. package/tests/password.test.ts +16 -2
  160. package/tests/prisma-errors.test.ts +141 -0
  161. package/tests/singleton.test.ts +9 -1
  162. package/tests/to-one-include-access-filter.test.ts +172 -0
  163. package/tests/with-session.test.ts +243 -0
  164. package/tests/write-pipeline.test.ts +29 -0
  165. package/tsconfig.tsbuildinfo +1 -1
@@ -1,7 +1,8 @@
1
1
  import { describe, it, expect, vi } from 'vitest';
2
- import { buildAccessScopedInclude } from './access-filter.js';
3
- import { AccessScopeDepthExceededError } from './errors.js';
2
+ import { buildAccessScopedInclude, resolveToOneAccessVisibility } from './access-filter.js';
3
+ import { AccessScopeDepthExceededError, RelationFilterAccessDeniedError, UndeclaredCountKeyError, UndeclaredIncludeKeyError, } from './errors.js';
4
4
  import { READ_INCLUDE_MAX_DEPTH } from './depth-limits.js';
5
+ import { ValidationError } from '../hooks/index.js';
5
6
  /**
6
7
  * Regression coverage for `buildAccessScopedInclude`, the caller-directed
7
8
  * access-scoping walk introduced by ADR-0026. It replaces the old two-step
@@ -19,6 +20,14 @@ import { READ_INCLUDE_MAX_DEPTH } from './depth-limits.js';
19
20
  * relation the request doesn't name never has its list's `query` access
20
21
  * invoked, and naming a relation fetches its own columns and stops (the "One
21
22
  * hop" rule) at every level, not just the root.
23
+ *
24
+ * The scenarios in this file build every chain relation as to-MANY
25
+ * (`rel(ref, true)`), so `where`-in-`include` keeps meaning what it always
26
+ * has here — the walk-depth/caller-directed logic under test is arity-
27
+ * agnostic. The to-one-specific behavior this function grew for issue #974
28
+ * (a `where` on a to-one include is not something Prisma accepts, so it's
29
+ * recorded in `toOneAccessFilters` instead and resolved post-query by
30
+ * `resolveToOneAccessVisibility`) has its own dedicated describe blocks below.
22
31
  */
23
32
  // A relationship field pointing at another list.
24
33
  function rel(ref, many = false) {
@@ -65,10 +74,10 @@ function chainConfig(count) {
65
74
  const listName = `L${i}`;
66
75
  const fields = { name: { type: 'text' } };
67
76
  if (i < count - 1) {
68
- fields.next = rel(`L${i + 1}.prev`);
77
+ fields.next = rel(`L${i + 1}.prev`, true);
69
78
  }
70
79
  if (i > 0) {
71
- fields.prev = rel(`L${i - 1}.next`);
80
+ fields.prev = rel(`L${i - 1}.next`, true);
72
81
  }
73
82
  const filter = { ownerId: { equals: listName } };
74
83
  const queryFn = vi.fn(i === 0 ? () => true : () => filter);
@@ -131,14 +140,14 @@ describe('buildAccessScopedInclude — caller-directed walk (ADR-0026)', () => {
131
140
  },
132
141
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
133
142
  };
134
- const include = await buildAccessScopedInclude({ b: true }, config.lists.A.fields, { session: null, context: makeContext() }, config, 'A');
143
+ const { include } = await buildAccessScopedInclude({ b: true }, config.lists.A.fields, { session: null, context: makeContext() }, config, 'A');
135
144
  expect(include).toEqual({ b: true });
136
145
  expect(queryB).toHaveBeenCalledTimes(1);
137
146
  expect(queryC).not.toHaveBeenCalled();
138
147
  });
139
148
  it("fetches a named relation's own columns and stops — does not auto-expand its subtree (One hop)", async () => {
140
149
  const { config, queryFns } = chainConfig(4); // L0 → L1 → L2 → L3
141
- const include = await buildAccessScopedInclude({ next: true }, config.lists.L0.fields, { session: null, context: makeContext() }, config, 'L0');
150
+ const { include } = await buildAccessScopedInclude({ next: true }, config.lists.L0.fields, { session: null, context: makeContext() }, config, 'L0');
142
151
  // L1 is fetched and where-scoped; L2/L3 are never reached because the
143
152
  // request named `next` bare, with no nested `include` beneath it.
144
153
  expect(include).toEqual({ next: { where: { ownerId: { equals: 'L1' } } } });
@@ -149,7 +158,7 @@ describe('buildAccessScopedInclude — caller-directed walk (ADR-0026)', () => {
149
158
  });
150
159
  it('scopes a nested path at every level the request names it', async () => {
151
160
  const { config, queryFns } = chainConfig(4); // L0 → L1 → L2 → L3
152
- const include = await buildAccessScopedInclude({ next: { include: { next: { include: { next: true } } } } }, config.lists.L0.fields, { session: null, context: makeContext() }, config, 'L0');
161
+ const { include } = await buildAccessScopedInclude({ next: { include: { next: { include: { next: true } } } } }, config.lists.L0.fields, { session: null, context: makeContext() }, config, 'L0');
153
162
  expect(include).toEqual({
154
163
  next: {
155
164
  where: { ownerId: { equals: 'L1' } },
@@ -180,7 +189,7 @@ describe('buildAccessScopedInclude — caller-directed walk (ADR-0026)', () => {
180
189
  },
181
190
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
182
191
  };
183
- const include = await buildAccessScopedInclude({ b: { include: { c: { include: { a: true } } } } }, config.lists.A.fields, { session: null, context: makeContext() }, config, 'A');
192
+ const { include } = await buildAccessScopedInclude({ b: { include: { c: { include: { a: true } } } } }, config.lists.A.fields, { session: null, context: makeContext() }, config, 'A');
184
193
  expect(include).toEqual({ b: { include: { c: { include: { a: true } } } } });
185
194
  });
186
195
  });
@@ -208,7 +217,7 @@ describe('buildAccessScopedInclude — caller take on a to-many relation (issue
208
217
  }
209
218
  it('preserves the take and AND-combines it with the access where', async () => {
210
219
  const config = scopedConfig();
211
- const include = await buildAccessScopedInclude({ posts: { take: 10 } }, config.lists.User.fields, { session: null, context: makeContext() }, config, 'User');
220
+ const { include } = await buildAccessScopedInclude({ posts: { take: 10 } }, config.lists.User.fields, { session: null, context: makeContext() }, config, 'User');
212
221
  // The bound rides on top of the access filter — neither is dropped. The
213
222
  // Post→author back-relation is NOT auto-nested (One hop, ADR-0026) since
214
223
  // the request didn't name it.
@@ -222,7 +231,7 @@ describe('buildAccessScopedInclude — caller take on a to-many relation (issue
222
231
  it('drops a take for a relation whose query access is denied', async () => {
223
232
  const config = scopedConfig();
224
233
  config.lists.Post.access = { operation: { query: () => false } };
225
- const include = await buildAccessScopedInclude({ posts: { take: 10 } }, config.lists.User.fields, { session: null, context: makeContext() }, config, 'User');
234
+ const { include } = await buildAccessScopedInclude({ posts: { take: 10 } }, config.lists.User.fields, { session: null, context: makeContext() }, config, 'User');
226
235
  // A denied relation is dropped wholesale — the take cannot resurrect it.
227
236
  expect(include).toEqual({});
228
237
  });
@@ -256,7 +265,7 @@ describe('buildAccessScopedInclude — fail-closed at the read-include depth cap
256
265
  const { config } = chainConfig(chainLength);
257
266
  // Outer `next` (hop 1) + nestedInclude(HOPS_AT_CAP - 1) = HOPS_AT_CAP hops total — right at the boundary.
258
267
  const requested = { next: nestedInclude(HOPS_AT_CAP - 1) };
259
- const include = await buildAccessScopedInclude(requested, config.lists.L0.fields, { session: null, context: makeContext() }, config, 'L0');
268
+ const { include } = await buildAccessScopedInclude(requested, config.lists.L0.fields, { session: null, context: makeContext() }, config, 'L0');
260
269
  expect(includeDepth(include)).toBe(HOPS_AT_CAP);
261
270
  expect(whereAtHop(include, HOPS_AT_CAP)).toEqual({ ownerId: { equals: `L${HOPS_AT_CAP}` } });
262
271
  });
@@ -268,10 +277,40 @@ describe('buildAccessScopedInclude — fail-closed at the read-include depth cap
268
277
  it('an empty request never throws, even on a deep schema', async () => {
269
278
  const chainLength = HOPS_AT_CAP + 3;
270
279
  const { config } = chainConfig(chainLength);
271
- const include = await buildAccessScopedInclude({}, config.lists.L0.fields, { session: null, context: makeContext() }, config, 'L0');
280
+ const { include } = await buildAccessScopedInclude({}, config.lists.L0.fields, { session: null, context: makeContext() }, config, 'L0');
272
281
  expect(include).toEqual({});
273
282
  });
274
- it('a list with no relationships passes an unrelated requested key through unchanged', async () => {
283
+ it('a declared non-relationship key on a list with no relationships passes through unchanged', async () => {
284
+ const config = {
285
+ db: { provider: 'sqlite' },
286
+ lists: {
287
+ Leaf: {
288
+ fields: { name: { type: 'text' } },
289
+ access: { operation: { query: () => true } },
290
+ },
291
+ },
292
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
293
+ };
294
+ // A declared field that isn't a relationship — access control does not
295
+ // govern it (e.g. a virtual field named in `include`, stripped later by
296
+ // `stripVirtualFieldsFromInclude`).
297
+ const { include } = await buildAccessScopedInclude({ name: true }, config.lists.Leaf.fields, { session: null, context: makeContext() }, config, 'Leaf');
298
+ expect(include).toEqual({ name: true });
299
+ });
300
+ it('rejects a key that is neither declared nor a synthetic back-relation (#1082)', async () => {
301
+ const config = {
302
+ db: { provider: 'sqlite' },
303
+ lists: {
304
+ Leaf: {
305
+ fields: { name: { type: 'text' } },
306
+ access: { operation: { query: () => true } },
307
+ },
308
+ },
309
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
310
+ };
311
+ await expect(buildAccessScopedInclude({ someUnrelatedKey: true }, config.lists.Leaf.fields, { session: null, context: makeContext() }, config, 'Leaf')).rejects.toThrow(UndeclaredIncludeKeyError);
312
+ });
313
+ it('a bare `_count: true` on a list with no to-many relations yields no `_count` key at all (#1087)', async () => {
275
314
  const config = {
276
315
  db: { provider: 'sqlite' },
277
316
  lists: {
@@ -282,10 +321,936 @@ describe('buildAccessScopedInclude — fail-closed at the read-include depth cap
282
321
  },
283
322
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
284
323
  };
285
- // An arbitrary (non-declared-relationship) key passed through unchanged
286
- // access control does not govern keys it doesn't recognize as relationships.
287
- const include = await buildAccessScopedInclude({ someUnrelatedKey: true }, config.lists.Leaf.fields, { session: null, context: makeContext() }, config, 'Leaf');
288
- expect(include).toEqual({ someUnrelatedKey: true });
324
+ const { include } = await buildAccessScopedInclude({ _count: true }, config.lists.Leaf.fields, { session: null, context: makeContext() }, config, 'Leaf');
325
+ expect(include).toEqual({});
326
+ });
327
+ });
328
+ /**
329
+ * Regression coverage for issue #1087: a caller-supplied `_count` in
330
+ * `include` used to reach Prisma unscoped (#1082's "Out of scope" — the one
331
+ * key `buildAccessScopedInclude`'s own denial rule allowlisted through rather
332
+ * than rejecting or scoping). These tests pin the fix: each named relation's
333
+ * `_count.select` entry is scoped by that relation's own `query` access,
334
+ * exactly like the rest of this module scopes `include`, and a denied
335
+ * relation is recorded in `countDenials` for `filterReadableFields` to inject
336
+ * `0` for post-query (Prisma cannot be asked for a guaranteed `0`).
337
+ */
338
+ describe('buildAccessScopedInclude — `_count` is scoped like any other relation (issue #1087)', () => {
339
+ function countConfig(postQuery) {
340
+ return {
341
+ db: { provider: 'sqlite' },
342
+ lists: {
343
+ User: {
344
+ fields: {
345
+ name: { type: 'text' },
346
+ posts: rel('Post.author', true),
347
+ secrets: rel('Secret.owner', true),
348
+ },
349
+ access: { operation: { query: () => true } },
350
+ },
351
+ Post: {
352
+ fields: { title: { type: 'text' }, author: rel('User.posts') },
353
+ access: { operation: { query: postQuery } },
354
+ },
355
+ Secret: {
356
+ fields: { body: { type: 'text' }, owner: rel('User.secrets') },
357
+ access: { operation: { query: () => false } },
358
+ },
359
+ },
360
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
361
+ };
362
+ }
363
+ it('a fully-readable relation counts unchanged', async () => {
364
+ const config = countConfig(() => true);
365
+ const { include, countDenials } = await buildAccessScopedInclude({ _count: { select: { posts: true } } }, config.lists.User.fields, { session: null, context: makeContext() }, config, 'User');
366
+ expect(include).toEqual({ _count: { select: { posts: true } } });
367
+ expect(countDenials.keys.size).toBe(0);
368
+ });
369
+ it('folds the related list row filter into the count select', async () => {
370
+ const config = countConfig(() => ({ published: { equals: true } }));
371
+ const { include } = await buildAccessScopedInclude({ _count: { select: { posts: true } } }, config.lists.User.fields, { session: null, context: makeContext() }, config, 'User');
372
+ expect(include).toEqual({
373
+ _count: { select: { posts: { where: { published: { equals: true } } } } },
374
+ });
375
+ });
376
+ it('AND-combines a caller-supplied nested `where` with the access filter, never replacing it', async () => {
377
+ const config = countConfig(() => ({ published: { equals: true } }));
378
+ const { include } = await buildAccessScopedInclude({ _count: { select: { posts: { where: { title: { contains: 'foo' } } } } } }, config.lists.User.fields, { session: null, context: makeContext() }, config, 'User');
379
+ expect(include).toEqual({
380
+ _count: {
381
+ select: {
382
+ posts: {
383
+ where: {
384
+ AND: [{ published: { equals: true } }, { title: { contains: 'foo' } }],
385
+ },
386
+ },
387
+ },
388
+ },
389
+ });
390
+ });
391
+ it('omits a fully-denied relation from the select and records it in `countDenials`', async () => {
392
+ const config = countConfig(() => true);
393
+ const { include, countDenials } = await buildAccessScopedInclude({ _count: { select: { posts: true, secrets: true } } }, config.lists.User.fields, { session: null, context: makeContext() }, config, 'User');
394
+ expect(include).toEqual({ _count: { select: { posts: true } } });
395
+ expect(countDenials.keys).toEqual(new Set(['secrets']));
396
+ });
397
+ it('a wholly-denied `_count.select` omits the `_count` key entirely, still recording the denial', async () => {
398
+ const config = countConfig(() => true);
399
+ const { include, countDenials } = await buildAccessScopedInclude({ _count: { select: { secrets: true } } }, config.lists.User.fields, { session: null, context: makeContext() }, config, 'User');
400
+ expect(include).toEqual({});
401
+ expect(countDenials.keys).toEqual(new Set(['secrets']));
402
+ });
403
+ it('a denied relation resolves to 0 without validating its caller `where` — no field-name/read-access oracle', async () => {
404
+ // A caller who cannot read a single `Secret` row supplies a nonsense
405
+ // `where` naming a field that doesn't exist. If denial were checked
406
+ // AFTER `where` validation, this would throw a `ValidationError` naming
407
+ // "Secret"'s fields — letting a caller probe a fully denied list's
408
+ // schema. Denial must win first: the count is 0 regardless of `where`.
409
+ const config = countConfig(() => true);
410
+ const { include, countDenials } = await buildAccessScopedInclude({ _count: { select: { secrets: { where: { bogusField: { equals: 1 } } } } } }, config.lists.User.fields, { session: null, context: makeContext() }, config, 'User');
411
+ expect(include).toEqual({});
412
+ expect(countDenials.keys).toEqual(new Set(['secrets']));
413
+ });
414
+ it('rejects a `_count.select` key that is not a countable to-many (undeclared)', async () => {
415
+ const config = countConfig(() => true);
416
+ await expect(buildAccessScopedInclude({ _count: { select: { nonsense: true } } }, config.lists.User.fields, { session: null, context: makeContext() }, config, 'User')).rejects.toThrow(UndeclaredCountKeyError);
417
+ });
418
+ it('rejects a `_count.select` key naming a scalar field', async () => {
419
+ const config = countConfig(() => true);
420
+ await expect(buildAccessScopedInclude({ _count: { select: { name: true } } }, config.lists.User.fields, { session: null, context: makeContext() }, config, 'User')).rejects.toThrow(UndeclaredCountKeyError);
421
+ });
422
+ it('rejects a `_count.select` key naming a to-one relationship', async () => {
423
+ const config = countConfig(() => true);
424
+ await expect(buildAccessScopedInclude({ _count: { select: { author: true } } }, config.lists.Post.fields, { session: null, context: makeContext() }, config, 'Post')).rejects.toThrow(UndeclaredCountKeyError);
425
+ });
426
+ // Issue #1111: a relationship hidden via field-level `read` access must not
427
+ // leak its true count through `_count`, even though the related list's rows
428
+ // are otherwise fully readable — the same denial an ordinary `include` of
429
+ // that field already gets from `filterReadableFields`'s `checkFieldAccess`
430
+ // call.
431
+ it('omits a relation whose field-level `read` access denies it, even though the related list is fully readable', async () => {
432
+ const config = {
433
+ db: { provider: 'sqlite' },
434
+ lists: {
435
+ User: {
436
+ fields: {
437
+ name: { type: 'text' },
438
+ posts: {
439
+ type: 'relationship',
440
+ ref: 'Post.author',
441
+ many: true,
442
+ access: { read: () => false },
443
+ },
444
+ },
445
+ access: { operation: { query: () => true } },
446
+ },
447
+ Post: {
448
+ fields: { title: { type: 'text' }, author: rel('User.posts') },
449
+ access: { operation: { query: () => true } },
450
+ },
451
+ },
452
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
453
+ };
454
+ const { include, countDenials } = await buildAccessScopedInclude({ _count: { select: { posts: true } } }, config.lists.User.fields, { session: null, context: makeContext() }, config, 'User');
455
+ expect(include).toEqual({});
456
+ expect(countDenials.keys).toEqual(new Set(['posts']));
457
+ });
458
+ it('does not reject a `_count.select` key naming a synthetic back-relation (#1082)', async () => {
459
+ const config = {
460
+ db: { provider: 'sqlite' },
461
+ lists: {
462
+ Category: {
463
+ fields: { name: { type: 'text' } },
464
+ access: { operation: { query: () => true } },
465
+ },
466
+ Post: {
467
+ fields: {
468
+ title: { type: 'text' },
469
+ // A list-only ref: no `Category` field names it back, so schema
470
+ // generation synthesizes `from_Post_category` on Category.
471
+ category: rel('Category'),
472
+ },
473
+ access: { operation: { query: () => true } },
474
+ },
475
+ },
476
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
477
+ };
478
+ const { include } = await buildAccessScopedInclude({ _count: { select: { from_Post_category: true } } }, config.lists.Category.fields, { session: null, context: makeContext() }, config, 'Category');
479
+ expect(include).toEqual({ _count: { select: { from_Post_category: true } } });
480
+ });
481
+ it('`_count: true` also expands to a synthetic back-relation, scoped (#1082/#1087)', async () => {
482
+ const config = {
483
+ db: { provider: 'sqlite' },
484
+ lists: {
485
+ Category: {
486
+ fields: { name: { type: 'text' } },
487
+ access: { operation: { query: () => true } },
488
+ },
489
+ Post: {
490
+ fields: {
491
+ title: { type: 'text' },
492
+ category: rel('Category'),
493
+ },
494
+ // A row filter — proves the synthetic relation's count is scoped
495
+ // exactly like an explicitly-named one, not merely included.
496
+ access: { operation: { query: () => ({ published: { equals: true } }) } },
497
+ },
498
+ },
499
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
500
+ };
501
+ const { include } = await buildAccessScopedInclude({ _count: true }, config.lists.Category.fields, { session: null, context: makeContext() }, config, 'Category');
502
+ expect(include).toEqual({
503
+ _count: { select: { from_Post_category: { where: { published: { equals: true } } } } },
504
+ });
505
+ });
506
+ it('scopes a relation filter nested inside a caller-supplied count `where` (e.g. `_count.select.posts.where.comments.some`)', async () => {
507
+ const config = {
508
+ db: { provider: 'sqlite' },
509
+ lists: {
510
+ User: {
511
+ fields: { name: { type: 'text' }, posts: rel('Post.author', true) },
512
+ access: { operation: { query: () => true } },
513
+ },
514
+ Post: {
515
+ fields: {
516
+ title: { type: 'text' },
517
+ author: rel('User.posts'),
518
+ comments: rel('Comment.post', true),
519
+ },
520
+ access: { operation: { query: () => true } },
521
+ },
522
+ Comment: {
523
+ fields: { body: { type: 'text' }, post: rel('Post.comments') },
524
+ // A row filter one hop past the counted relation — must still be
525
+ // folded in, or the resulting post count would reveal whether
526
+ // inaccessible comments matching the caller's filter exist.
527
+ access: { operation: { query: () => ({ approved: { equals: true } }) } },
528
+ },
529
+ },
530
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
531
+ };
532
+ const { include } = await buildAccessScopedInclude({
533
+ _count: {
534
+ select: {
535
+ posts: { where: { comments: { some: { body: { contains: 'hi' } } } } },
536
+ },
537
+ },
538
+ }, config.lists.User.fields, { session: null, context: makeContext() }, config, 'User');
539
+ expect(include).toEqual({
540
+ _count: {
541
+ select: {
542
+ posts: {
543
+ where: {
544
+ comments: {
545
+ some: {
546
+ AND: [{ approved: { equals: true } }, { body: { contains: 'hi' } }],
547
+ },
548
+ },
549
+ },
550
+ },
551
+ },
552
+ },
553
+ });
554
+ });
555
+ it('resolves a synthetic back-relation named inside a caller-supplied count `where` (#1082/#1092)', async () => {
556
+ const config = {
557
+ db: { provider: 'sqlite' },
558
+ lists: {
559
+ User: {
560
+ fields: { name: { type: 'text' }, posts: rel('Post.author', true) },
561
+ access: { operation: { query: () => true } },
562
+ },
563
+ Post: {
564
+ fields: {
565
+ title: { type: 'text' },
566
+ author: rel('User.posts'),
567
+ // A list-only ref: no `Post` field names it back, so schema
568
+ // generation synthesizes `from_Category_posts` on Post.
569
+ category: rel('Category'),
570
+ },
571
+ access: { operation: { query: () => true } },
572
+ },
573
+ Category: {
574
+ fields: {
575
+ name: { type: 'text' },
576
+ posts: rel('Post', true),
577
+ },
578
+ // A row filter one hop past the counted relation, reached only
579
+ // through the synthetic back-relation — must still be folded in.
580
+ access: { operation: { query: () => ({ published: { equals: true } }) } },
581
+ },
582
+ },
583
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
584
+ };
585
+ const { include } = await buildAccessScopedInclude({
586
+ _count: {
587
+ select: {
588
+ posts: { where: { from_Category_posts: { some: { name: { contains: 'news' } } } } },
589
+ },
590
+ },
591
+ }, config.lists.User.fields, { session: null, context: makeContext() }, config, 'User');
592
+ expect(include).toEqual({
593
+ _count: {
594
+ select: {
595
+ posts: {
596
+ where: {
597
+ from_Category_posts: {
598
+ some: {
599
+ AND: [{ published: { equals: true } }, { name: { contains: 'news' } }],
600
+ },
601
+ },
602
+ },
603
+ },
604
+ },
605
+ },
606
+ });
607
+ });
608
+ it('`_count: true` expands to every declared to-many relation, scoped', async () => {
609
+ const config = countConfig(() => true);
610
+ const { include, countDenials } = await buildAccessScopedInclude({ _count: true }, config.lists.User.fields, { session: null, context: makeContext() }, config, 'User');
611
+ expect(include).toEqual({ _count: { select: { posts: true } } });
612
+ expect(countDenials.keys).toEqual(new Set(['secrets']));
613
+ });
614
+ it('scopes `_count` nested inside an ordinary relation include, at that level', async () => {
615
+ const config = {
616
+ db: { provider: 'sqlite' },
617
+ lists: {
618
+ Org: {
619
+ fields: { name: { type: 'text' }, users: rel('User.org', true) },
620
+ access: { operation: { query: () => true } },
621
+ },
622
+ User: {
623
+ fields: {
624
+ name: { type: 'text' },
625
+ org: rel('Org.users'),
626
+ posts: rel('Post.author', true),
627
+ },
628
+ access: { operation: { query: () => true } },
629
+ },
630
+ Post: {
631
+ fields: { title: { type: 'text' }, author: rel('User.posts') },
632
+ access: { operation: { query: () => ({ published: { equals: true } }) } },
633
+ },
634
+ },
635
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
636
+ };
637
+ const { include } = await buildAccessScopedInclude({ users: { include: { _count: { select: { posts: true } } } } }, config.lists.Org.fields, { session: null, context: makeContext() }, config, 'Org');
638
+ expect(include).toEqual({
639
+ users: {
640
+ include: { _count: { select: { posts: { where: { published: { equals: true } } } } } },
641
+ },
642
+ });
643
+ });
644
+ });
645
+ /**
646
+ * Regression coverage for issue #974: Prisma accepts a nested `where` on an
647
+ * `include` entry only for a to-many relation — the same shape on a to-one
648
+ * relation raises `PrismaClientValidationError`. `buildAccessScopedInclude`
649
+ * must never attach one for a to-one relation, whatever its related list's
650
+ * `query` access resolves to; the scoping information goes into
651
+ * `toOneAccessFilters` instead.
652
+ */
653
+ describe('buildAccessScopedInclude — to-one relations record a post-query filter, not `where` (issue #974)', () => {
654
+ function ownerConfig(queryAccess) {
655
+ return {
656
+ db: { provider: 'sqlite' },
657
+ lists: {
658
+ Child: {
659
+ fields: { name: { type: 'text' }, owner: rel('Owner') },
660
+ access: { operation: { query: () => true } },
661
+ },
662
+ Owner: {
663
+ fields: { name: { type: 'text' } },
664
+ access: { operation: { query: queryAccess } },
665
+ },
666
+ },
667
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
668
+ };
669
+ }
670
+ it('records the access filter instead of attaching `where` when the related list scopes by a filter', async () => {
671
+ const config = ownerConfig(() => ({ id: { equals: 'u1' } }));
672
+ const { include, toOneAccessFilters } = await buildAccessScopedInclude({ owner: true }, config.lists.Child.fields, { session: null, context: makeContext() }, config, 'Child');
673
+ // The Prisma-bound include never carries a `where` on this to-one key —
674
+ // Prisma would reject it.
675
+ expect(include).toEqual({ owner: true });
676
+ expect(toOneAccessFilters).toEqual({
677
+ filters: {
678
+ owner: { kind: 'scoped', relatedListName: 'Owner', accessWhere: { id: { equals: 'u1' } } },
679
+ },
680
+ nested: {},
681
+ });
682
+ });
683
+ it('leaves a to-one relation whose related list is fully open untouched — no filter recorded, no extra query later', async () => {
684
+ const config = ownerConfig(() => true);
685
+ const { include, toOneAccessFilters } = await buildAccessScopedInclude({ owner: true }, config.lists.Child.fields, { session: null, context: makeContext() }, config, 'Child');
686
+ expect(include).toEqual({ owner: true });
687
+ expect(toOneAccessFilters).toEqual({ filters: {}, nested: {} });
688
+ });
689
+ it('drops a to-one relation whose related list denies query access outright, and records the denial', async () => {
690
+ const config = ownerConfig(() => false);
691
+ const { include, toOneAccessFilters } = await buildAccessScopedInclude({ owner: true }, config.lists.Child.fields, { session: null, context: makeContext() }, config, 'Child');
692
+ // Never asked of Prisma at all — same as before this fix.
693
+ expect(include).toEqual({});
694
+ expect(toOneAccessFilters).toEqual({ filters: { owner: { kind: 'denied' } }, nested: {} });
695
+ });
696
+ it('records a to-one filter nested inside another relation the caller explicitly included', async () => {
697
+ const config = {
698
+ db: { provider: 'sqlite' },
699
+ lists: {
700
+ GrandChild: {
701
+ fields: { name: { type: 'text' }, child: rel('Child') },
702
+ access: { operation: { query: () => true } },
703
+ },
704
+ Child: {
705
+ fields: { name: { type: 'text' }, owner: rel('Owner') },
706
+ access: { operation: { query: () => true } },
707
+ },
708
+ Owner: {
709
+ fields: { name: { type: 'text' } },
710
+ access: { operation: { query: () => ({ id: { equals: 'u1' } }) } },
711
+ },
712
+ },
713
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
714
+ };
715
+ const { include, toOneAccessFilters } = await buildAccessScopedInclude({ child: { include: { owner: true } } }, config.lists.GrandChild.fields, { session: null, context: makeContext() }, config, 'GrandChild');
716
+ expect(include).toEqual({ child: { include: { owner: true } } });
717
+ expect(toOneAccessFilters).toEqual({
718
+ filters: {},
719
+ nested: {
720
+ child: {
721
+ filters: {
722
+ owner: {
723
+ kind: 'scoped',
724
+ relatedListName: 'Owner',
725
+ accessWhere: { id: { equals: 'u1' } },
726
+ },
727
+ },
728
+ nested: {},
729
+ },
730
+ },
731
+ });
732
+ });
733
+ });
734
+ /**
735
+ * Regression coverage for issue #1103: a denied to-MANY relation used to be
736
+ * dropped from `include` with nothing recorded, unlike its to-one sibling
737
+ * (issue #974, covered above). `filterReadableFields`'s main loop only ever
738
+ * visits keys present in the raw row, so an unrecorded denial left the key
739
+ * silently absent from the result — `undefined`, not `[]` — breaking the
740
+ * fragment API's typed contract (`ResultOf` types a to-many relation as an
741
+ * array). These tests pin that a to-many denial is now recorded exactly like
742
+ * a to-one one, sharing the same `toOneAccessFilters` tree and `kind:
743
+ * 'denied'` entry.
744
+ */
745
+ describe('buildAccessScopedInclude — to-many relations record a denial too, like to-one (issue #1103)', () => {
746
+ function secretsConfig() {
747
+ return {
748
+ db: { provider: 'sqlite' },
749
+ lists: {
750
+ Author: {
751
+ fields: { name: { type: 'text' }, secrets: rel('Secret.author', true) },
752
+ access: { operation: { query: () => true } },
753
+ },
754
+ Secret: {
755
+ fields: { value: { type: 'text' } },
756
+ access: { operation: { query: () => false } },
757
+ },
758
+ },
759
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
760
+ };
761
+ }
762
+ it('drops a to-many relation whose related list denies query access outright, and records the denial', async () => {
763
+ const config = secretsConfig();
764
+ const { include, toOneAccessFilters } = await buildAccessScopedInclude({ secrets: true }, config.lists.Author.fields, { session: null, context: makeContext() }, config, 'Author');
765
+ // Never asked of Prisma at all — same treatment as a denied to-one.
766
+ expect(include).toEqual({});
767
+ expect(toOneAccessFilters).toEqual({ filters: { secrets: { kind: 'denied' } }, nested: {} });
768
+ });
769
+ it('records the denial even when the caller also asked for a `take`/`where` — a denied relation has no shape to preserve', async () => {
770
+ const config = secretsConfig();
771
+ const { include, toOneAccessFilters } = await buildAccessScopedInclude({ secrets: { take: 5, where: { value: { equals: 'x' } } } }, config.lists.Author.fields, { session: null, context: makeContext() }, config, 'Author');
772
+ expect(include).toEqual({});
773
+ expect(toOneAccessFilters).toEqual({ filters: { secrets: { kind: 'denied' } }, nested: {} });
774
+ });
775
+ // Code-review finding on #1103's own PR: a caller's `Include` type allows a
776
+ // bare `boolean` for a relation, so `{ secrets: false }` (or a conditional
777
+ // `{ secrets: cond ? true : undefined }` that resolved to `undefined`)
778
+ // explicitly opts the relation OUT — no different from the key being
779
+ // absent altogether. Before this guard, the loop evaluated (and, once
780
+ // denied, recorded) the key regardless of its value, so a denied relation
781
+ // the caller explicitly disabled still ended up forced to `[]` downstream
782
+ // by `field-visibility.ts` — surfacing a value for a key nobody asked for.
783
+ it('treats an explicit `false` include value as not requested, even when the related list denies query access', async () => {
784
+ const config = secretsConfig();
785
+ const { include, toOneAccessFilters } = await buildAccessScopedInclude({ secrets: false }, config.lists.Author.fields, { session: null, context: makeContext() }, config, 'Author');
786
+ expect(include).toEqual({});
787
+ expect(toOneAccessFilters).toEqual({ filters: {}, nested: {} });
788
+ });
789
+ it('treats an explicit `undefined` include value as not requested, even when the related list denies query access', async () => {
790
+ const config = secretsConfig();
791
+ const { include, toOneAccessFilters } = await buildAccessScopedInclude({ secrets: undefined }, config.lists.Author.fields, { session: null, context: makeContext() }, config, 'Author');
792
+ expect(include).toEqual({});
793
+ expect(toOneAccessFilters).toEqual({ filters: {}, nested: {} });
794
+ });
795
+ it('treats an explicit `false` include value as not requested even when the related list is fully open — never flips it to `true`', async () => {
796
+ const config = secretsConfig();
797
+ config.lists.Secret.access = { operation: { query: () => true } };
798
+ const { include, toOneAccessFilters } = await buildAccessScopedInclude({ secrets: false }, config.lists.Author.fields, { session: null, context: makeContext() }, config, 'Author');
799
+ expect(include).toEqual({});
800
+ expect(toOneAccessFilters).toEqual({ filters: {}, nested: {} });
801
+ });
802
+ });
803
+ describe('resolveToOneAccessVisibility (issue #974)', () => {
804
+ function makeVisibilityContext(findMany) {
805
+ return {
806
+ session: null,
807
+ _isSudo: false,
808
+ _resolveOutputChain: [],
809
+ prisma: { owner: { findMany } },
810
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal context for unit test
811
+ };
812
+ }
813
+ it('passes a denied filter straight through with no query', async () => {
814
+ const findMany = vi.fn();
815
+ const context = makeVisibilityContext(findMany);
816
+ const resolved = await resolveToOneAccessVisibility([{ id: 'c1' }], { filters: { owner: { kind: 'denied' } }, nested: {} }, { session: null, context });
817
+ expect(resolved).toEqual({ filters: { owner: { kind: 'denied' } }, nested: {} });
818
+ expect(findMany).not.toHaveBeenCalled();
819
+ });
820
+ it('skips the query when no row carries a value at the scoped key', async () => {
821
+ const findMany = vi.fn();
822
+ const context = makeVisibilityContext(findMany);
823
+ const tree = {
824
+ filters: {
825
+ owner: {
826
+ kind: 'scoped',
827
+ relatedListName: 'Owner',
828
+ accessWhere: { id: { equals: 'u1' } },
829
+ },
830
+ },
831
+ nested: {},
832
+ };
833
+ const resolved = await resolveToOneAccessVisibility([{ id: 'c1', owner: null }], tree, {
834
+ session: null,
835
+ context,
836
+ });
837
+ expect(resolved).toEqual({
838
+ filters: { owner: { kind: 'visible', ids: new Set() } },
839
+ nested: {},
840
+ });
841
+ expect(findMany).not.toHaveBeenCalled();
842
+ });
843
+ it('batches every row into ONE existence check, through the raw Prisma client, using the exact access filter', async () => {
844
+ const findMany = vi.fn().mockResolvedValue([{ id: 'u1' }, { id: 'u2' }]);
845
+ const context = makeVisibilityContext(findMany);
846
+ const tree = {
847
+ filters: {
848
+ owner: {
849
+ kind: 'scoped',
850
+ relatedListName: 'Owner',
851
+ accessWhere: { studioId: { equals: 's1' } },
852
+ },
853
+ },
854
+ nested: {},
855
+ };
856
+ const items = [
857
+ { id: 'c1', owner: { id: 'u1' } },
858
+ { id: 'c2', owner: { id: 'u2' } },
859
+ { id: 'c3', owner: { id: 'u3' } }, // excluded by the mocked response below
860
+ { id: 'c4', owner: null }, // contributes no id
861
+ ];
862
+ const resolved = await resolveToOneAccessVisibility(items, tree, { session: null, context });
863
+ // One call, not one per row.
864
+ expect(findMany).toHaveBeenCalledTimes(1);
865
+ expect(findMany).toHaveBeenCalledWith({
866
+ where: { AND: [{ studioId: { equals: 's1' } }, { id: { in: ['u1', 'u2', 'u3'] } }] },
867
+ select: { id: true },
868
+ });
869
+ expect(resolved.filters.owner).toEqual({ kind: 'visible', ids: new Set(['u1', 'u2']) });
870
+ });
871
+ it('recurses into nested trees, flattening rows reached through a to-many hop into one batch', async () => {
872
+ const ownerFindMany = vi.fn().mockResolvedValue([{ id: 'u1' }]);
873
+ const context = {
874
+ session: null,
875
+ _isSudo: false,
876
+ _resolveOutputChain: [],
877
+ prisma: { owner: { findMany: ownerFindMany } },
878
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal context for unit test
879
+ };
880
+ const tree = {
881
+ filters: {},
882
+ nested: {
883
+ children: {
884
+ filters: {
885
+ owner: {
886
+ kind: 'scoped',
887
+ relatedListName: 'Owner',
888
+ accessWhere: { id: { equals: 'u1' } },
889
+ },
890
+ },
891
+ nested: {},
892
+ },
893
+ },
894
+ };
895
+ const items = [
896
+ {
897
+ id: 'p1',
898
+ children: [
899
+ { id: 'c1', owner: { id: 'u1' } },
900
+ { id: 'c2', owner: { id: 'u9' } },
901
+ ],
902
+ },
903
+ { id: 'p2', children: [{ id: 'c3', owner: { id: 'u1' } }] },
904
+ ];
905
+ const resolved = await resolveToOneAccessVisibility(items, tree, { session: null, context });
906
+ // Every child across BOTH parents resolved in one batched call.
907
+ expect(ownerFindMany).toHaveBeenCalledTimes(1);
908
+ expect(ownerFindMany).toHaveBeenCalledWith({
909
+ where: { AND: [{ id: { equals: 'u1' } }, { id: { in: ['u1', 'u9'] } }] },
910
+ select: { id: true },
911
+ });
912
+ expect(resolved.nested.children.filters.owner).toEqual({
913
+ kind: 'visible',
914
+ ids: new Set(['u1']),
915
+ });
916
+ });
917
+ });
918
+ /**
919
+ * Regression coverage for issue #1082: a list-only `ref` (`ref: 'Term'`, no
920
+ * target field) makes schema generation synthesize a back-relation on `Term`
921
+ * (`from_Bill_term`) that no list config declares. Before this fix,
922
+ * `buildAccessScopedInclude` treated any key it couldn't resolve to a
923
+ * DECLARED relationship as "not governed by access control" and passed it
924
+ * through unchanged — so a caller naming `from_Bill_term` in `include`
925
+ * bypassed `Bill`'s own `query` access entirely. These tests pin the fix: a
926
+ * synthetic key is scoped exactly like the declared relationship field it
927
+ * stands for.
928
+ */
929
+ describe('buildAccessScopedInclude — synthetic back-relation (#1082)', () => {
930
+ // Term ← Bill.term (list-only ref) ← Bill.lineItems (declared, to-many).
931
+ // `from_Bill_term` is the back-relation schema generation synthesizes on
932
+ // Term; nothing in `Term.fields` declares it.
933
+ function syntheticConfig(billQuery) {
934
+ const config = {
935
+ db: { provider: 'sqlite' },
936
+ lists: {
937
+ Term: {
938
+ fields: { name: { type: 'text' } },
939
+ access: { operation: { query: () => true } },
940
+ },
941
+ Bill: {
942
+ fields: {
943
+ amount: { type: 'integer' },
944
+ term: rel('Term'), // list-only ref — synthesizes `from_Bill_term` on Term
945
+ lineItems: rel('LineItem.bill', true),
946
+ },
947
+ access: { operation: { query: billQuery } },
948
+ },
949
+ LineItem: {
950
+ fields: { sku: { type: 'text' }, bill: rel('Bill.lineItems') },
951
+ access: { operation: { query: () => true } },
952
+ },
953
+ },
954
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
955
+ };
956
+ return config;
957
+ }
958
+ it('drops the relation entirely when the owning list denies query access', async () => {
959
+ const config = syntheticConfig(() => false);
960
+ const { include } = await buildAccessScopedInclude({ from_Bill_term: true }, config.lists.Term.fields, { session: null, context: makeContext() }, config, 'Term');
961
+ expect(include).toEqual({});
962
+ });
963
+ it('AND-folds the owning list access filter with the caller-supplied where', async () => {
964
+ const config = syntheticConfig(() => ({ paid: { equals: true } }));
965
+ const { include } = await buildAccessScopedInclude({ from_Bill_term: { where: { amount: { gt: 10 } } } }, config.lists.Term.fields, { session: null, context: makeContext() }, config, 'Term');
966
+ expect(include).toEqual({
967
+ from_Bill_term: {
968
+ where: { AND: [{ paid: { equals: true } }, { amount: { gt: 10 } }] },
969
+ },
970
+ });
971
+ });
972
+ it('scopes a nested include against the OWNING list fields and consumes depth', async () => {
973
+ const config = syntheticConfig(() => true);
974
+ const lineItemQuery = vi.fn(() => true);
975
+ config.lists.LineItem.access = { operation: { query: lineItemQuery } };
976
+ const { include } = await buildAccessScopedInclude({ from_Bill_term: { include: { lineItems: true } } }, config.lists.Term.fields, { session: null, context: makeContext() }, config, 'Term');
977
+ // The nested `lineItems` key was resolved against Bill's own fields (not
978
+ // Term's, which has no `lineItems` field at all) — proof the recursion
979
+ // used the owning list, not the synthetic key's declaring list.
980
+ expect(lineItemQuery).toHaveBeenCalledTimes(1);
981
+ expect(include).toEqual({ from_Bill_term: { include: { lineItems: true } } });
982
+ });
983
+ it('a synthetic hop counts toward the read-include depth cap the same as a declared one', async () => {
984
+ // A chain like `chainConfig` builds (L0 ↔ L1 ↔ … via declared `next`/`prev`),
985
+ // except the FIRST hop is synthetic: L1's `prev` is a list-only ref, so L0
986
+ // never declares `next` at all — it only gets `from_L1_prev` synthesized
987
+ // onto it. Every hop past that first one is declared, exactly matching the
988
+ // mixed synthetic-then-declared case the depth cap must bound identically.
989
+ const chainLength = READ_INCLUDE_MAX_DEPTH + 2;
990
+ const { config } = chainConfig(chainLength);
991
+ delete config.lists.L0.fields.next;
992
+ config.lists.L1.fields.prev = rel('L0');
993
+ // Outer `from_L1_prev` (hop 1) + nestedInclude(HOPS_AT_CAP) (HOPS_AT_CAP
994
+ // more, via the declared `next` chain from L1 onward) = HOPS_AT_CAP + 1.
995
+ const requested = { from_L1_prev: nestedInclude(READ_INCLUDE_MAX_DEPTH) };
996
+ await expect(buildAccessScopedInclude(requested, config.lists.L0.fields, { session: null, context: makeContext() }, config, 'L0')).rejects.toThrow(AccessScopeDepthExceededError);
997
+ });
998
+ it('still resolves a synthetic hop one level shallower than the cap', async () => {
999
+ const chainLength = READ_INCLUDE_MAX_DEPTH + 1;
1000
+ const { config } = chainConfig(chainLength);
1001
+ delete config.lists.L0.fields.next;
1002
+ config.lists.L1.fields.prev = rel('L0');
1003
+ const requested = { from_L1_prev: nestedInclude(READ_INCLUDE_MAX_DEPTH - 1) };
1004
+ const { include } = await buildAccessScopedInclude(requested, config.lists.L0.fields, { session: null, context: makeContext() }, config, 'L0');
1005
+ expect(includeDepth(include)).toBe(READ_INCLUDE_MAX_DEPTH);
1006
+ });
1007
+ it('rejects a key that resolves to neither a declared relationship nor a synthetic one', async () => {
1008
+ const config = syntheticConfig(() => true);
1009
+ await expect(buildAccessScopedInclude({ from_Nonexistent_field: true }, config.lists.Term.fields, { session: null, context: makeContext() }, config, 'Term')).rejects.toThrow(UndeclaredIncludeKeyError);
1010
+ });
1011
+ });
1012
+ /**
1013
+ * Regression coverage for issue #1092: a `where`/`orderBy` a caller nests
1014
+ * inside an `include` entry reached Prisma with neither #912's key-existence
1015
+ * check nor #915's field-read check — a probing oracle over exactly the
1016
+ * fields those two tickets close one level up. `secret`/`secretNote` below
1017
+ * deny field-level `read` outright; every other field is a normal declared
1018
+ * field, so a throw in these tests can only come from the new validation.
1019
+ */
1020
+ describe('buildAccessScopedInclude — nested where/orderBy validation (#1092)', () => {
1021
+ function blogConfig() {
1022
+ return {
1023
+ db: { provider: 'sqlite' },
1024
+ lists: {
1025
+ Author: {
1026
+ fields: {
1027
+ name: { type: 'text' },
1028
+ posts: rel('Post.author', true),
1029
+ },
1030
+ access: { operation: { query: () => true } },
1031
+ },
1032
+ Post: {
1033
+ fields: {
1034
+ title: { type: 'text' },
1035
+ secret: { type: 'text', access: { read: () => false } },
1036
+ author: rel('Author.posts'),
1037
+ comments: rel('Comment.post', true),
1038
+ },
1039
+ access: { operation: { query: () => true } },
1040
+ },
1041
+ Comment: {
1042
+ fields: {
1043
+ body: { type: 'text' },
1044
+ secretNote: { type: 'text', access: { read: () => false } },
1045
+ post: rel('Post.comments'),
1046
+ },
1047
+ access: { operation: { query: () => true } },
1048
+ },
1049
+ },
1050
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
1051
+ };
1052
+ }
1053
+ it('throws when a nested `where` names a field the session cannot read', async () => {
1054
+ const config = blogConfig();
1055
+ await expect(buildAccessScopedInclude({ posts: { where: { secret: { equals: 'x' } } } }, config.lists.Author.fields, { session: null, context: makeContext() }, config, 'Author')).rejects.toThrow(ValidationError);
1056
+ await expect(buildAccessScopedInclude({ posts: { where: { secret: { equals: 'x' } } } }, config.lists.Author.fields, { session: null, context: makeContext() }, config, 'Author')).rejects.toThrow(/"secret" is denied by field-level read access/);
1057
+ });
1058
+ it('throws when a nested `where` names a key the related list does not declare, naming the related list and key', async () => {
1059
+ const config = blogConfig();
1060
+ await expect(buildAccessScopedInclude({ posts: { where: { bogusField: { equals: 'x' } } } }, config.lists.Author.fields, { session: null, context: makeContext() }, config, 'Author')).rejects.toThrow(/Cannot query "Post" — "bogusField" is not a field of this list/);
1061
+ });
1062
+ it('applies the same two checks to a nested `orderBy`', async () => {
1063
+ const config = blogConfig();
1064
+ await expect(buildAccessScopedInclude({ posts: { orderBy: { secret: 'asc' } } }, config.lists.Author.fields, { session: null, context: makeContext() }, config, 'Author')).rejects.toThrow(ValidationError);
1065
+ await expect(buildAccessScopedInclude({ posts: { orderBy: { bogusField: 'asc' } } }, config.lists.Author.fields, { session: null, context: makeContext() }, config, 'Author')).rejects.toThrow(/Cannot query "Post"/);
1066
+ });
1067
+ it('resolves against the RELATED list, not the current one — a key valid on the parent but not the related list is rejected', async () => {
1068
+ const config = blogConfig();
1069
+ // `name` is declared on Author, not on Post — validating against the
1070
+ // wrong list would let this through.
1071
+ await expect(buildAccessScopedInclude({ posts: { where: { name: { equals: 'x' } } } }, config.lists.Author.fields, { session: null, context: makeContext() }, config, 'Author')).rejects.toThrow(/Cannot query "Post" — "name"/);
1072
+ });
1073
+ it('recurses through AND/OR/NOT', async () => {
1074
+ const config = blogConfig();
1075
+ await expect(buildAccessScopedInclude({
1076
+ posts: {
1077
+ where: { AND: [{ title: { contains: 'x' } }, { OR: [{ secret: { equals: 'x' } }] }] },
1078
+ },
1079
+ }, config.lists.Author.fields, { session: null, context: makeContext() }, config, 'Author')).rejects.toThrow(ValidationError);
1080
+ });
1081
+ it("the key-existence check recurses through a relation quantifier nested inside the entry's own where", async () => {
1082
+ // #912's existence check (`validateQueryKeys`) is the reused #912/#915
1083
+ // top-level walker, which already recurses through a relation quantifier
1084
+ // regardless of caller position — an undeclared key nested that deep
1085
+ // still rejects, naming the list it actually resolved against (Comment,
1086
+ // not Post).
1087
+ const config = blogConfig();
1088
+ await expect(buildAccessScopedInclude({ posts: { where: { comments: { some: { bogusField: { equals: 'x' } } } } } }, config.lists.Author.fields, { session: null, context: makeContext() }, config, 'Author')).rejects.toThrow(/Cannot query "Comment" — "bogusField"/);
1089
+ });
1090
+ it("scopes a relation quantifier nested inside the entry's own where against the DEEPER related list — a read-denied field one hop further out still throws (#916)", async () => {
1091
+ // Without this, #1092's fix would only move the oracle one hop further
1092
+ // out instead of closing it: `posts: { where: { comments: { some: {...} } } }`
1093
+ // names Comment, a list the entry's own #912/#915 checks never reach —
1094
+ // only `buildAccessScopedWhere` (#916), reused here, does.
1095
+ const config = blogConfig();
1096
+ await expect(buildAccessScopedInclude({ posts: { where: { comments: { some: { secretNote: { equals: 'x' } } } } } }, config.lists.Author.fields, { session: null, context: makeContext() }, config, 'Author')).rejects.toThrow(/Cannot query "Comment" — "secretNote"/);
1097
+ });
1098
+ it("folds the deeper related list's own query access into a relation quantifier nested inside the entry's own where", async () => {
1099
+ const config = blogConfig();
1100
+ config.lists.Comment.access = {
1101
+ operation: { query: () => ({ approved: { equals: true } }) },
1102
+ };
1103
+ const { include } = await buildAccessScopedInclude({ posts: { where: { comments: { some: { body: { contains: 'hi' } } } } } }, config.lists.Author.fields, { session: null, context: makeContext() }, config, 'Author');
1104
+ expect(include).toEqual({
1105
+ posts: {
1106
+ where: {
1107
+ comments: {
1108
+ some: { AND: [{ approved: { equals: true } }, { body: { contains: 'hi' } }] },
1109
+ },
1110
+ },
1111
+ },
1112
+ });
1113
+ });
1114
+ it("throws when the deeper related list denies query access outright, matching #916's loud failure", async () => {
1115
+ const config = blogConfig();
1116
+ config.lists.Comment.access = { operation: { query: () => false } };
1117
+ await expect(buildAccessScopedInclude({ posts: { where: { comments: { some: { body: { contains: 'hi' } } } } } }, config.lists.Author.fields, { session: null, context: makeContext() }, config, 'Author')).rejects.toThrow(RelationFilterAccessDeniedError);
1118
+ });
1119
+ it('recurses through a further nested include, at every level the walk reaches', async () => {
1120
+ const config = blogConfig();
1121
+ await expect(buildAccessScopedInclude({ posts: { include: { comments: { where: { secretNote: { equals: 'x' } } } } } }, config.lists.Author.fields, { session: null, context: makeContext() }, config, 'Author')).rejects.toThrow(/Cannot query "Comment" — "secretNote"/);
1122
+ });
1123
+ it('accepts a foreign-key scalar a to-one relationship implies, matching the top-level resolver', async () => {
1124
+ const config = blogConfig();
1125
+ await expect(buildAccessScopedInclude({ posts: { where: { authorId: { equals: 'a1' } } } }, config.lists.Author.fields, { session: null, context: makeContext() }, config, 'Author')).resolves.not.toThrow();
1126
+ });
1127
+ it('leaves a legitimate nested where over readable, declared fields unchanged, still AND-combined with the access filter', async () => {
1128
+ const config = blogConfig();
1129
+ config.lists.Post.access = { operation: { query: () => ({ published: { equals: true } }) } };
1130
+ const { include } = await buildAccessScopedInclude({ posts: { where: { title: { contains: 'hello' } } } }, config.lists.Author.fields, { session: null, context: makeContext() }, config, 'Author');
1131
+ expect(include).toEqual({
1132
+ posts: {
1133
+ where: { AND: [{ published: { equals: true } }, { title: { contains: 'hello' } }] },
1134
+ },
1135
+ });
1136
+ });
1137
+ it('equivalence: the same read-denied predicate throws whether it names the current list, a relation quantifier, or an include-nested where', async () => {
1138
+ // Mirrors the triage comment's three-position table for #1092 — the
1139
+ // include-nested position (the one gap) now matches the other two.
1140
+ const config = blogConfig();
1141
+ await expect(buildAccessScopedInclude({ posts: { where: { secret: { equals: 'x' } } } }, config.lists.Author.fields, { session: null, context: makeContext() }, config, 'Author')).rejects.toThrow(ValidationError);
1142
+ });
1143
+ describe('synthetic back-relation nested in a where (#1082 interaction)', () => {
1144
+ function syntheticNestedConfig() {
1145
+ const config = {
1146
+ db: { provider: 'sqlite' },
1147
+ lists: {
1148
+ Company: {
1149
+ fields: {
1150
+ name: { type: 'text' },
1151
+ terms: rel('Term', true),
1152
+ },
1153
+ access: { operation: { query: () => true } },
1154
+ },
1155
+ Term: {
1156
+ fields: { name: { type: 'text' } },
1157
+ access: { operation: { query: () => true } },
1158
+ },
1159
+ Bill: {
1160
+ fields: {
1161
+ amount: { type: 'integer' },
1162
+ term: rel('Term'), // list-only ref — synthesizes `from_Bill_term` on Term
1163
+ },
1164
+ access: { operation: { query: () => true } },
1165
+ },
1166
+ },
1167
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
1168
+ };
1169
+ return config;
1170
+ }
1171
+ it('does not throw for a nested predicate naming a synthetic back-relation', async () => {
1172
+ const config = syntheticNestedConfig();
1173
+ await expect(buildAccessScopedInclude({ terms: { where: { from_Bill_term: { some: { amount: { gt: 5 } } } } } }, config.lists.Company.fields, { session: null, context: makeContext() }, config, 'Company')).resolves.not.toThrow();
1174
+ });
1175
+ it("recurses into the synthetic's own SOURCE list — an invalid key nested under it still throws, naming that list", async () => {
1176
+ const config = syntheticNestedConfig();
1177
+ await expect(buildAccessScopedInclude({ terms: { where: { from_Bill_term: { some: { bogusField: { equals: 'x' } } } } } }, config.lists.Company.fields, { session: null, context: makeContext() }, config, 'Company')).rejects.toThrow(/Cannot query "Bill" — "bogusField"/);
1178
+ });
1179
+ it("folds the synthetic's own SOURCE list's query access into the nested quantifier clause", async () => {
1180
+ // Regression coverage for a Codex review finding on #1108: the deeper
1181
+ // #916-style scoping originally only recognised a DECLARED
1182
+ // relationship — a synthetic key's nested quantifier passed through
1183
+ // with neither the source list's `query` access folded in nor its
1184
+ // fields' read access checked, even though the shallow #912/#915
1185
+ // checks (validateQueryKeys/validateQueryFieldReadAccess) already
1186
+ // correctly tolerated and resolved the synthetic key itself.
1187
+ const config = syntheticNestedConfig();
1188
+ config.lists.Bill.access = { operation: { query: () => ({ paid: { equals: true } }) } };
1189
+ const { include } = await buildAccessScopedInclude({ terms: { where: { from_Bill_term: { some: { amount: { gt: 5 } } } } } }, config.lists.Company.fields, { session: null, context: makeContext() }, config, 'Company');
1190
+ expect(include).toEqual({
1191
+ terms: {
1192
+ where: {
1193
+ from_Bill_term: {
1194
+ some: { AND: [{ paid: { equals: true } }, { amount: { gt: 5 } }] },
1195
+ },
1196
+ },
1197
+ },
1198
+ });
1199
+ });
1200
+ it('throws when a field nested under a synthetic quantifier is denied by field-level read access', async () => {
1201
+ const config = syntheticNestedConfig();
1202
+ config.lists.Bill.fields.secretAmount = {
1203
+ type: 'integer',
1204
+ access: { read: () => false },
1205
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal field config for unit test
1206
+ };
1207
+ await expect(buildAccessScopedInclude({ terms: { where: { from_Bill_term: { some: { secretAmount: { gt: 5 } } } } } }, config.lists.Company.fields, { session: null, context: makeContext() }, config, 'Company')).rejects.toThrow(/"secretAmount" is denied by field-level read access/);
1208
+ });
1209
+ it("throws when the synthetic's own SOURCE list denies query access outright, matching #916's loud failure", async () => {
1210
+ const config = syntheticNestedConfig();
1211
+ config.lists.Bill.access = { operation: { query: () => false } };
1212
+ await expect(buildAccessScopedInclude({ terms: { where: { from_Bill_term: { some: { amount: { gt: 5 } } } } } }, config.lists.Company.fields, { session: null, context: makeContext() }, config, 'Company')).rejects.toThrow(RelationFilterAccessDeniedError);
1213
+ });
1214
+ });
1215
+ describe("a to-one relation's `is: null`/`isNot: null` inside a nested quantifier (Codex review finding on #1108)", () => {
1216
+ // Root -> Parent (to-many, unscoped) -> Owner (to-one, query-scoped by a
1217
+ // filter). Parent's own access is `true` (no filter), so the outer
1218
+ // AND-fold is a no-op and cannot mask what this test is isolating: the
1219
+ // fold that happens INSIDE the quantifier's own value.
1220
+ function nullQuantifierConfig() {
1221
+ return {
1222
+ db: { provider: 'sqlite' },
1223
+ lists: {
1224
+ Root: {
1225
+ fields: { name: { type: 'text' }, parent: rel('Parent', true) },
1226
+ access: { operation: { query: () => true } },
1227
+ },
1228
+ Parent: {
1229
+ fields: { name: { type: 'text' }, owner: rel('Owner') },
1230
+ access: { operation: { query: () => true } },
1231
+ },
1232
+ Owner: {
1233
+ fields: { name: { type: 'text' } },
1234
+ access: { operation: { query: () => ({ secret: { equals: true } }) } },
1235
+ },
1236
+ },
1237
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
1238
+ };
1239
+ }
1240
+ it('preserves `is: null` rather than inverting it into an access-filter match', async () => {
1241
+ // Before this fix, folding the access filter into a quantifier's
1242
+ // value unconditionally turned `is: null` ("has no related row") into
1243
+ // `is: <accessWhere>` ("has a related row matching the filter") —
1244
+ // the opposite of the caller's own predicate.
1245
+ const config = nullQuantifierConfig();
1246
+ const { include } = await buildAccessScopedInclude({ parent: { where: { owner: { is: null } } } }, config.lists.Root.fields, { session: null, context: makeContext() }, config, 'Root');
1247
+ expect(include).toEqual({ parent: { where: { owner: { is: null } } } });
1248
+ });
1249
+ it('preserves `isNot: null` the same way', async () => {
1250
+ const config = nullQuantifierConfig();
1251
+ const { include } = await buildAccessScopedInclude({ parent: { where: { owner: { isNot: null } } } }, config.lists.Root.fields, { session: null, context: makeContext() }, config, 'Root');
1252
+ expect(include).toEqual({ parent: { where: { owner: { isNot: null } } } });
1253
+ });
289
1254
  });
290
1255
  });
291
1256
  //# sourceMappingURL=access-filter.test.js.map