@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,4 +1,4 @@
1
1
 
2
- > @opensaas/stack-core@0.39.2 build /home/runner/work/stack/stack/packages/core
2
+ > @opensaas/stack-core@0.41.0 build /home/runner/work/stack/stack/packages/core
3
3
  > tsc
4
4
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,194 @@
1
1
  # @opensaas/stack-core
2
2
 
3
+ ## 0.41.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#1179](https://github.com/OpenSaasAU/stack/pull/1179) [`67dce2e`](https://github.com/OpenSaasAU/stack/commit/67dce2e9d96afdc5c69f0a2f1c8b395346d4e942) Thanks [@borisno2](https://github.com/borisno2)! - A list/field `resolveInput` / `validate` / `beforeOperation` / `afterOperation` hook's `context` is now a full secured context — `sudo()`, `withSession()`, `transaction()` and `serverAction` — bound to the write's OWN transaction client, exactly like the `txContext` a `context.transaction()` callback receives.
8
+
9
+ ```typescript
10
+ Order: list({
11
+ hooks: {
12
+ beforeOperation: async ({ context }) => {
13
+ // Elevated AND atomic with this write — rolls back together if it throws.
14
+ await context.sudo().db.auditLog.create({ data: { action: 'order-write' } })
15
+ },
16
+ },
17
+ })
18
+ ```
19
+
20
+ Previously this `context` had no `sudo()`/`withSession()`/`transaction()` at all, forcing a workaround (`getContext(session).sudo()`) that opened a SEPARATE connection from the write's transaction — its writes could survive a rollback, and it could deadlock on a single-connection adapter. `context.transaction()` called from inside one of these hooks now joins the write's transaction rather than opening a nested one. `beforeTransaction`/`afterTransaction` are unaffected — they keep the plain access-checked context bound to the base client, always. A field's `resolveOutput` keeps the same context type as before; which client it's bound to already depended on how the read arose (a plain read: the base client; a create/update's own Field Visibility pass: that write's transaction client), unchanged by this release.
21
+
22
+ ### Patch Changes
23
+
24
+ - [#1108](https://github.com/OpenSaasAU/stack/pull/1108) [`2260539`](https://github.com/OpenSaasAU/stack/commit/2260539c5488dae0ee6e7f86ccd913e5c898ccdb) Thanks [@borisno2](https://github.com/borisno2)! - Fix: a relation quantifier (`some`/`every`/`none`/`is`/`isNot`) nested inside an `include` entry's own `where` is now scoped by the deeper related list's `query` access and field-read access too, reusing `buildAccessScopedWhere` ([#916](https://github.com/OpenSaasAU/stack/issues/916)) — closing a residual probing-oracle gap in [#1092](https://github.com/OpenSaasAU/stack/issues/1092)'s fix.
25
+
26
+ - [#1102](https://github.com/OpenSaasAU/stack/pull/1102) [`aa34cca`](https://github.com/OpenSaasAU/stack/commit/aa34cca65877759b9625da1538c65c53ed54385a) Thanks [@borisno2](https://github.com/borisno2)! - Fix: a `where`/`orderBy` nested inside a caller's `include` entry now validates against the related list's config, closing a probing oracle over undeclared or read-denied fields one hop into a relation ([#1092](https://github.com/OpenSaasAU/stack/issues/1092)).
27
+
28
+ - [#1041](https://github.com/OpenSaasAU/stack/pull/1041) [`182153c`](https://github.com/OpenSaasAU/stack/commit/182153cb976b14ef67673d0eeef7925d950bfa10) Thanks [@borisno2](https://github.com/borisno2)! - Upgrade Prisma packages to `^7.9.1`, keeping the CLI, client, and driver adapters on the same release. Scaffolded PostgreSQL projects now pin `@prisma/adapter-pg` to `^7.9.1`.
29
+
30
+ - [#1101](https://github.com/OpenSaasAU/stack/pull/1101) [`682795f`](https://github.com/OpenSaasAU/stack/commit/682795f7c7f0d0194ffd08e993d452c368bcd847) Thanks [@borisno2](https://github.com/borisno2)! - Fix a query fragment read (`{ query: fragment }`) skipping the Access Filter's scoping walk, so a related list's `query` access, row filters, and the read-include depth cap were never enforced. Fragment reads may now return fewer related rows — those rows were never authorised.
31
+
32
+ - [#1110](https://github.com/OpenSaasAU/stack/pull/1110) [`73d1b6a`](https://github.com/OpenSaasAU/stack/commit/73d1b6aba9a9b789a8111105d56257a1de66a883) Thanks [@borisno2](https://github.com/borisno2)! - A caller-supplied `_count` in `include` is now scoped by each named relation's own `query` access (a row filter is folded into the count, a fully denied relation counts `0`), closing a cardinality leak where counts previously reached the caller unscoped.
33
+
34
+ - [#1091](https://github.com/OpenSaasAU/stack/pull/1091) [`f1e8792`](https://github.com/OpenSaasAU/stack/commit/f1e8792ce580d92a5874599dfb8a8ccde4d6c8b3) Thanks [@borisno2](https://github.com/borisno2)! - Fix a read naming a list-only ref's synthetic back-relation (`from_<List>_<field>`) in `include`: it now resolves to the declared relationship it stands for and is scoped by that list's `query` access, its field-level `read` gates, and its virtual fields — instead of being returned unscoped. An `include` key that resolves to neither a declared relationship, a synthetic back-relation, nor `_count` is now rejected rather than silently passed through. Responses will shrink for callers relying on either gap — the extra rows and fields they received were never authorised.
35
+
36
+ - [#1120](https://github.com/OpenSaasAU/stack/pull/1120) [`9eb7c77`](https://github.com/OpenSaasAU/stack/commit/9eb7c7766d212e92b02d53a1ba3aaead4faf1496) Thanks [@borisno2](https://github.com/borisno2)! - Fix `_count` ignoring a relationship's field-level `read` access, letting the true count of a hidden relationship leak through both the admin list view and a caller-supplied `_count`.
37
+
38
+ - [#1090](https://github.com/OpenSaasAU/stack/pull/1090) [`5b478de`](https://github.com/OpenSaasAU/stack/commit/5b478de64f3564d837d2f9f912972e49008be884) Thanks [@borisno2](https://github.com/borisno2)! - Fix nested update/delete (e.g. `post.update({ data: { author: { update: {...} } } })`) silently treating a Prisma filter returned by the target list's `update`/`delete` access as an unconditional allow. It is now re-checked against the target row in the database, matching top-level write behavior.
39
+
40
+ - [#1115](https://github.com/OpenSaasAU/stack/pull/1115) [`d335122`](https://github.com/OpenSaasAU/stack/commit/d335122323b3402c0838aa50873fab0c085fbb01) Thanks [@borisno2](https://github.com/borisno2)! - Fix a denied to-many relation coming back `undefined` instead of `[]` on both the caller-`include:` and fragment `query` read paths.
41
+
42
+ ## 0.40.0
43
+
44
+ ### Minor Changes
45
+
46
+ - [#1020](https://github.com/OpenSaasAU/stack/pull/1020) [`8e6707a`](https://github.com/OpenSaasAU/stack/commit/8e6707adcca9d7e062bc1747ec79a29082c09ef9) Thanks [@borisno2](https://github.com/borisno2)! - Add `ui.listView.defaultColumn` to field config — a declared, presentation-only flag (default `true`) controlling whether a field belongs in a list/related-list table's default column set. Naming a field explicitly in `ui.listView.initialColumns` or a relationship's `ui.itemView.columns` always shows it regardless of this flag.
47
+
48
+ ```typescript
49
+ fields: {
50
+ internalScore: integer({ ui: { listView: { defaultColumn: false } } }),
51
+ }
52
+ ```
53
+
54
+ `password()` now sets this flag to `false` by default instead of the admin UI matching on field type — a password field can opt back into default columns with `ui: { listView: { defaultColumn: true } } }`.
55
+
56
+ - [#1011](https://github.com/OpenSaasAU/stack/pull/1011) [`afd1a60`](https://github.com/OpenSaasAU/stack/commit/afd1a60a6ddaa558bf14887e45fa1c007e6669b0) Thanks [@borisno2](https://github.com/borisno2)! - `OperationAccess.create` now throws `InvalidCreateAccessResultError` when the rule returns anything other than `true`/`false` — most notably a Prisma filter, which previously fell through the `create` access check unrecognised and was silently treated as a full allow (both the top-level write pipeline and nested-create paths were affected).
57
+
58
+ Create has no existing row to scope a filter against, so a filter can no longer be honoured here:
59
+
60
+ ```typescript
61
+ // Before: type-checked, read as row-scoped, actually allowed everyone
62
+ create: ({ session }) => ({ ownerId: { equals: session.userId } })
63
+
64
+ // Now throws InvalidCreateAccessResultError. Scope ownership in a hook instead:
65
+ hooks: {
66
+ resolveInput: async ({ resolvedData, context, operation }) => {
67
+ if (operation === 'create') {
68
+ return { ...resolvedData, ownerId: context.session?.userId }
69
+ }
70
+ return resolvedData
71
+ },
72
+ },
73
+ access: {
74
+ operation: {
75
+ create: ({ session }) => !!session, // boolean only
76
+ },
77
+ },
78
+ ```
79
+
80
+ `create: () => false` still denies via Silent failure as before; only a non-boolean result now throws.
81
+
82
+ - [#984](https://github.com/OpenSaasAU/stack/pull/984) [`51ae299`](https://github.com/OpenSaasAU/stack/commit/51ae299b7624f97e890f85b3075c62d8e114cec2) Thanks [@borisno2](https://github.com/borisno2)! - Extend `isIndexed` to `integer`, `timestamp`, and `select`, matching `text`, `decimal`, `bigInt`, `calendarDay`, and `relationship`.
83
+
84
+ ```typescript
85
+ fields: {
86
+ rank: integer({ isIndexed: true }),
87
+ publishedAt: timestamp({ isIndexed: true }),
88
+ status: select({
89
+ options: [{ label: 'Draft', value: 'draft' }],
90
+ isIndexed: 'unique',
91
+ }),
92
+ }
93
+ ```
94
+
95
+ `isIndexed: true` generates a block-level `@@index([field])`; `isIndexed: 'unique'` generates an inline `@unique`. `select` supports both under the default string column and a native-enum column (`db: { type: 'enum' }`). No field type's default indexing behavior changes — an existing config generates the same schema as before.
96
+
97
+ - [#1007](https://github.com/OpenSaasAU/stack/pull/1007) [`4ce64b4`](https://github.com/OpenSaasAU/stack/commit/4ce64b4f9868eca0f34cc0676e46440b3d8f16ce) Thanks [@borisno2](https://github.com/borisno2)! - The derived MCP `query` tool now accepts an optional `fields` projection — the wire form of the runtime's existing fragment field selection — so an assistant can select scalars and nested relation fields (with `where`/`orderBy`/`take`/`skip`, and a to-many's row count) in a single call instead of following a foreign key with a second one. Omitting `fields` is unchanged, a bare read exactly as before.
98
+
99
+ ```json
100
+ {
101
+ "name": "list_post_query",
102
+ "arguments": {
103
+ "fields": {
104
+ "title": true,
105
+ "author": { "fields": { "name": true } },
106
+ "comments": {
107
+ "fields": { "text": true },
108
+ "where": { "approved": { "equals": true } },
109
+ "take": 5,
110
+ "count": true
111
+ }
112
+ }
113
+ }
114
+ }
115
+ ```
116
+
117
+ The generated tool schema enumerates two levels of each list's own fields and relations, per session, and refuses (as an `isError` tool result, never a protocol error) anything it doesn't advertise — an unknown field, or a relation named a third level deep. See the ADR (`docs/adr/0033-mcp-tools-advertise-a-bounded-projection.md`) for the full design.
118
+
119
+ **Behaviour change:** `tools/list` is now evaluated per session. A list whose operation-level `query` access denies the session outright no longer appears in the tool listing at all — none of its four CRUD tools, and no relation entry elsewhere pointing at it. Previously every list's tools were listed regardless of session.
120
+
121
+ - [#1002](https://github.com/OpenSaasAU/stack/pull/1002) [`48d2762`](https://github.com/OpenSaasAU/stack/commit/48d27626dfb636c481301116e46c826ef3156124) Thanks [@borisno2](https://github.com/borisno2)! - Fix admin UI URL round-trip for a list keyed with anything other than strict PascalCase (issue [#991](https://github.com/OpenSaasAU/stack/issues/991)). `getListKeyFromUrl` reconstructs a list key by string transformation, which is lossy for a non-PascalCase key — a real example is a better-auth plugin's derived list (e.g. `oauthApplication`, from the `mcp` plugin's OAuth tables). Such a list appeared in navigation but its own link resolved to a key that did not exist in `config.lists`, rendering "List not found".
122
+
123
+ `@opensaas/stack-core` adds `resolveListKeyFromUrl(urlSegment, listKeys)` alongside the existing `getListKeyFromUrl`, which is unchanged and still exported. The new resolver matches a URL segment against the config's actual list keys via `getUrlKey` — the same helper that builds the URL — instead of reconstructing one, so route lookup and URL generation cannot drift apart. It returns `undefined` for a segment matching no list (so callers keep rendering their existing "not found" state), and throws if two distinct list keys would produce the same URL segment.
124
+
125
+ ```typescript
126
+ import { resolveListKeyFromUrl } from '@opensaas/stack-core'
127
+
128
+ resolveListKeyFromUrl('oauth-application', Object.keys(config.lists)) // 'oauthApplication'
129
+ resolveListKeyFromUrl('does-not-exist', Object.keys(config.lists)) // undefined
130
+ ```
131
+
132
+ `@opensaas/stack-ui`'s `AdminUI` now uses `resolveListKeyFromUrl` for its route resolution, fixing the broken link for any such list.
133
+
134
+ `@opensaas/stack-auth`'s `convertBetterAuthSchema` now PascalCases a better-auth plugin's camelCase `modelName` when deriving a list key (`oauthApplication` → `OauthApplication`, `rateLimit` → `RateLimit`), matching the repo's PascalCase list-key convention and fixing the same round-trip bug at the source for these lists.
135
+
136
+ **Schema-affecting for `@opensaas/stack-auth` users with a better-auth plugin that declares extra tables** (e.g. `mcp`'s OAuth tables, or `rateLimit.storage: 'database'` with no `modelName` remap configured): the generated Prisma **model name** changes to match the new PascalCase list key. The physical **table name** does not change — the previous camelCase name is preserved via `db.map` (`@@map`) — so `prisma db push` / `prisma migrate dev` sees a model rename, not a table rename, and `context.db.oauthApplication` (the camelCase db accessor) keeps working unchanged. Regenerate (`pnpm generate`) and re-run your migration/push step after upgrading.
137
+
138
+ - [#1003](https://github.com/OpenSaasAU/stack/pull/1003) [`9de43c8`](https://github.com/OpenSaasAU/stack/commit/9de43c80c8ef996dc6f08f68f7c1d8451aa0f10e) Thanks [@borisno2](https://github.com/borisno2)! - Add `context.withSession(session)` — a sibling to `sudo()` for the other axis. It derives a `StackContext` that reuses the receiver's already-resolved config, client (including a transaction client — a call inside `context.transaction()` stays in that transaction), and storage, but carries a substituted session, so access control and hooks run against the new session as normal.
139
+
140
+ This closes a gap for callers that are legitimately authorised but arrive without the session a list `validate` hook expects — an unattended dispatcher, a service principal, or a job runner:
141
+
142
+ ```typescript
143
+ // Runs with the job owner's session so hooks see the right identity, while
144
+ // still going through the normal access control checks for that session.
145
+ const asOwner = context.withSession(job.ownerSession)
146
+ await asOwner.db.task.update({ where: { id: job.taskId }, data: { status: 'done' } })
147
+
148
+ // Drop to anonymous
149
+ const anonymous = context.withSession(null)
150
+ ```
151
+
152
+ `withSession` grants no authority of its own — the derived context can do exactly what any context built with that session directly could do. It's orthogonal to `sudo()`: `context.withSession(s).sudo()` and `context.sudo().withSession(s)` are equivalent, since `withSession` preserves the receiver's sudo state instead of resetting it.
153
+
154
+ The generated `Context<TSession>` type (`.opensaas/types.ts`) now includes `withSession: (session: TSession | null) => Context<TSession>` alongside `sudo`, so the method is typed in application code — run `opensaas generate` (or `pnpm generate`) to pick it up.
155
+
156
+ ### Patch Changes
157
+
158
+ - [#1017](https://github.com/OpenSaasAU/stack/pull/1017) [`b30fa61`](https://github.com/OpenSaasAU/stack/commit/b30fa6135a6acca8c9be99fbdf5ffa7faab1959f) Thanks [@{](https://github.com/{)! - Let an application declare model-level indexes (`db.indexes`) on the derived auth lists (`User`/`Session`/`Account`/`Verification`/`RateLimit`).
159
+
160
+ Each per-model block in `authPlugin()` now accepts `indexes`, in the same shape as a list's own `db.indexes`:
161
+
162
+ ```typescript
163
+ authPlugin({
164
+ // Adopt a live constraint's real name instead of Prisma's derived one.
165
+ indexes: [{ fields: ['email'], unique: true, name: 'user_email_key' }] },
166
+ session: { indexes: [{ fields: ['token'], unique: true, name: 'session_token_key' }] },
167
+ // Extend a derived column into a composite index.
168
+ verification: {
169
+ indexes: [{ fields: ['identifier', { field: 'createdAt', sort: 'desc' }] }],
170
+ },
171
+ })
172
+ ```
173
+
174
+ An entry covering a column the stack already derives an index for (e.g. `User.email`) suppresses that derived index for that column and emits only the app's entry, rather than erroring — the application's declaration wins (ADR-0035). Suppression is per-column: every other derived index on the model is unaffected.
175
+
176
+ This also fixes a related generator gap: a list's `db.indexes` can now reference `createdAt`/`updatedAt` even when the list has no explicit field for them and relies on `db.timestamps` for the auto-injected columns (previously only a list with an explicitly declared `createdAt`/`updatedAt` field could be indexed on it).
177
+
178
+ - [#983](https://github.com/OpenSaasAU/stack/pull/983) [`16da817`](https://github.com/OpenSaasAU/stack/commit/16da8176114826d18d6747d27abedf75de6c3262) Thanks [@borisno2](https://github.com/borisno2)! - Fix `HashedPassword.toJSON()` returning the raw bcrypt hash, so `JSON.stringify` of a row (e.g. a server→client prop, `Response.json()`, an MCP tool response) no longer leaks the stored hash for a `password()` field.
179
+
180
+ `toJSON()` now returns `{ isSet: boolean }`, matching the redaction the admin UI already applies via `valueForClientSerialization`. `toString()`, `valueOf()`, `[Symbol.toPrimitive]`, and `==` comparison against the hash are unchanged. If you parse `JSON.stringify`'d rows and read the password field as a string, update that code to read `.isSet` instead — this is a visible output/type change on `HashedPassword.toJSON()`, though the field's read access remains the application's to configure (unchanged).
181
+
182
+ - [#999](https://github.com/OpenSaasAU/stack/pull/999) [`f85c7d1`](https://github.com/OpenSaasAU/stack/commit/f85c7d1b92e76d5e8ae090f93c0ff94e0d6c36c1) Thanks [@borisno2](https://github.com/borisno2)! - MCP derived CRUD tool and custom tool failures (access denial, thrown engine/database errors, input schema validation) now return a successful JSON-RPC response with `result.isError: true` instead of a JSON-RPC `error` object, so the calling model can see and recover from them. Genuine protocol failures (unknown method, malformed request, unknown tool name) are unchanged. Note: the wire shape of tool failures changes — a consumer asserting on the old `error` shape will need to update.
183
+
184
+ - [#1006](https://github.com/OpenSaasAU/stack/pull/1006) [`0f2e12a`](https://github.com/OpenSaasAU/stack/commit/0f2e12a69710e759d8749b8536fd5b31836226e9) Thanks [@borisno2](https://github.com/borisno2)! - `relationship({ ref: 'ListName' })` list-only refs now accept `db.foreignKey: { map: '...' }` to rename the foreign key column. The boolean form (`true`/`false`) is still rejected there since ownership is implicit on a list-only ref.
185
+
186
+ - [#1004](https://github.com/OpenSaasAU/stack/pull/1004) [`05c747a`](https://github.com/OpenSaasAU/stack/commit/05c747a18284ac769860f751a660b72591570571) Thanks [@borisno2](https://github.com/borisno2)! - Fix a nested create/update/delete through a list-only ref's synthetic reverse relation (`from_<List>_<field>`) silently bypassing the target list's hooks and validation. It now runs the same pipeline a declared relationship field's nested write gets. Under `sudo()`, an undeclared key that isn't a synthetic reverse relation is now refused rather than passed through unchecked.
187
+
188
+ - [#1000](https://github.com/OpenSaasAU/stack/pull/1000) [`0b5b51e`](https://github.com/OpenSaasAU/stack/commit/0b5b51e52787ea9e945206a109a7a56dc38e78e5) Thanks [@borisno2](https://github.com/borisno2)! - Fix `P2002` unique-constraint errors losing per-field detail under Prisma 7 driver adapters (`@prisma/adapter-pg`, PGlite), where `meta.target` is left empty. The error handler now recovers the violated columns and constraint name from the adapter's error shape, and a new `uniqueConstraintOf(error)` helper exposes this to callers of `context.db.*` directly. Unique-violation messages under driver adapters change from the generic fallback back to field-specific text.
189
+
190
+ - [#1001](https://github.com/OpenSaasAU/stack/pull/1001) [`52dfdd2`](https://github.com/OpenSaasAU/stack/commit/52dfdd2c051aa2f4b4cbd96a459213c34c3bf85c) Thanks [@borisno2](https://github.com/borisno2)! - Fix `include` on a to-one relationship throwing `PrismaClientValidationError` when the related list's `query` access resolves to a filter (Prisma only accepts a nested `where` on a to-many include). The relation is now fetched and access-scoped via a batched existence check instead, returning `null` for an excluded related row rather than throwing — a caller relying on the previous exception, or whose types assumed a non-null relation, should re-check nullability.
191
+
3
192
  ## 0.39.2
4
193
 
5
194
  ### Patch Changes
package/CLAUDE.md CHANGED
@@ -192,6 +192,97 @@ Key points:
192
192
  optimistically at write time, unchanged. See ADR-0028 and the hooks concept
193
193
  doc.
194
194
 
195
+ #### Hook context is the same secured context as a transaction's (#1176)
196
+
197
+ A list/field `resolveInput` / `validate` / `beforeOperation` / `afterOperation`
198
+ hook's `context` argument is a full `StackContext` — `sudo()`, `withSession()`,
199
+ `transaction()` and `serverAction` are all present, exactly like the `txContext`
200
+ a `context.transaction()` callback receives — bound to the WRITE'S OWN
201
+ transaction client, not the base one. This amends ADR-0012: the Write
202
+ Pipeline's transaction rebind (`bindContextToTransaction`) goes through the
203
+ same `getContext` factory `context.transaction()` already rebuilds through,
204
+ instead of hand-assembling a bare `AccessContext` object literal.
205
+
206
+ ```typescript
207
+ Order: list({
208
+ hooks: {
209
+ beforeOperation: async ({ context }) => {
210
+ // Elevated AND atomic with this write: rolls back together if the
211
+ // write (or a later hook in it) throws — unlike `getContext(session)
212
+ // .sudo()`, which would bind to a SEPARATE connection.
213
+ await context.sudo().db.auditLog.create({ data: { action: 'order-write' } })
214
+ },
215
+ },
216
+ })
217
+ ```
218
+
219
+ - `context.sudo()` / `context.withSession(s)` from one of these hooks stays
220
+ bound to the SAME transaction client the hook itself was given — carrying
221
+ the write's transaction owner (ADR-0028, so a write through them defers its
222
+ `afterTransaction` to that owner) and the hook's own resolve chain
223
+ (ADR-0023, so a write issued from inside a `resolveOutput` hook keeps that
224
+ hook's cycle-guard chain into its own Field Visibility pass).
225
+ - `context.transaction(fn)` called from inside one of these hooks **joins**
226
+ the write's transaction (the existing "no interactive client → run
227
+ directly" fallback) — it never opens a nested one.
228
+ - Plugin runtimes are **not** re-executed on this rebind (same rule as the
229
+ nested-write rebind ADR-0010 already established).
230
+ - **Unaffected:** `beforeTransaction` / `afterTransaction` (list and field) keep
231
+ the plain `AccessContext`, bound to the BASE client, always — see ADR-0028
232
+ for why boundary hooks must not run through a client that may already be
233
+ closed by flush time.
234
+ - **A field's `resolveOutput` keeps the plain `AccessContext` type**, but which
235
+ client it's bound to already depended — before this record and after it
236
+ alike — on how the read that triggered it arose: a plain top-level read
237
+ resolves against the base client; a `resolveOutput` that runs as part of a
238
+ create/update's OWN result (the write's Field Visibility pass, Phase 11)
239
+ resolves against THAT write's transaction client (ADR-0010) — so a
240
+ `context.db` read/write from inside such a hook is already atomic with the
241
+ write, same as `beforeOperation`/`afterOperation`. Not a consequence of this
242
+ record; stated here only so it isn't mistaken for one.
243
+
244
+ See ADR-0066 and the hooks concept doc's "In-transaction vs
245
+ transaction-boundary hooks" section.
246
+
247
+ #### Substituting a session (`context.withSession`, #980)
248
+
249
+ `context.withSession(session)` sits beside `sudo()` on the other axis:
250
+ `sudo()` keeps the session and drops access control; `withSession()` keeps
251
+ access control (and hooks) and swaps the session. It reuses the receiver's
252
+ already-resolved config, client (including a transaction client — a call
253
+ inside `context.transaction()` stays in that transaction), and storage.
254
+
255
+ Like `sudo()` (and unlike `transaction()`), plugin runtime services are
256
+ **rebuilt, not reused** — `plugin.runtime(context, sudo)` factories are
257
+ re-run so any plugin service that closes over the session (e.g. an auth
258
+ plugin's "who is this session" lookup) binds to the _new_ one rather than
259
+ staying stale. A hot loop calling `withSession()` per iteration re-runs
260
+ every plugin's `runtime()` each time; batch via a shared derived context
261
+ where the loop body doesn't need a different session per iteration.
262
+
263
+ ```typescript
264
+ // An unattended dispatcher running a committed intent, or any job runner
265
+ // that is legitimately authorised but arrives without the session a list's
266
+ // validate hook wants to see in `args.context.session`.
267
+ async function dispatchJob(context: StackContext, job: { ownerSession: Session }) {
268
+ const asOwner = context.withSession(job.ownerSession)
269
+ await asOwner.db.task.update({ where: { id: job.taskId }, data: { status: 'done' } })
270
+ }
271
+ ```
272
+
273
+ **`withSession` grants no authority of its own.** It is not an
274
+ authorisation — the derived context can do exactly what any context built
275
+ with that session directly could do; access rules still evaluate against
276
+ the new session. The application decides who may call it.
277
+
278
+ **Orthogonal to `sudo()`.** `context.withSession(s).sudo()` and
279
+ `context.sudo().withSession(s)` are equivalent — both elevated and both
280
+ carrying `s`. `withSession` preserves the receiver's sudo state rather than
281
+ resetting it: called on an already-sudo context it stays sudo, called on a
282
+ plain context it does not grant sudo.
283
+
284
+ `withSession(null)` is a legitimate way to drop to an anonymous context.
285
+
195
286
  ### Generators (`src/generator/`)
196
287
 
197
288
  - `prisma.ts` - Generates `prisma/schema.prisma` from config
@@ -320,6 +411,18 @@ const context = createContext<typeof prisma>(config, prisma, session)
320
411
  - Uses context for all operations (access control enforced); writes are validated by the normal `context.db` pipeline (field Zod schemas, hooks, access control)
321
412
  - Custom tools may declare a Zod `inputSchema` — validated on `tools/call`, converted to JSON Schema for `tools/list` — or a plain JSON Schema object
322
413
  - Auth adapters (like `@opensaas/stack-auth/mcp`) provide session integration; custom session fields pass through to access control
414
+ - The derived `query` tool accepts an optional `fields` projection (`packages/core/src/mcp/projection.ts`) — the wire form of a fragment field selection, translated into a `context.db` `include` so the ordinary read pipeline (access scoping, `needs` folding, the depth cap) applies with no parallel read path. The generated schema enumerates two fixed levels of each list's vocabulary, per session; `tools/list` itself is per-session as a result (ADR-0033)
415
+
416
+ ### The MCP `query` Tool's `fields` Projection (ADR-0033)
417
+
418
+ An optional `fields` argument on the derived `query` tool narrows (or widens, up to two levels) what a read returns, in the wire form of a fragment field selection: `{ scalarField: true, relation: { fields: {...} } }`. A to-many relation additionally accepts `where`/`orderBy`/`take`/`skip` and a `count`. Omitting `fields` is unchanged — a bare read, per ADR-0024.
419
+
420
+ `projection.ts` does the work in two passes, both walking the same per-session vocabulary (`relatedListIfVisible`):
421
+
422
+ - `generateFieldsProjectionSchema` builds the JSON Schema advertised on `tools/list` — a relation whose target list denies this session's operation-level `query` access, or has `mcp.enabled: false`, is omitted from the vocabulary entirely, not merely left unusable.
423
+ - `resolveFieldsProjection` validates a caller's `fields` against that same vocabulary and translates it into a plain `context.db` `include` (deliberately NOT the fragment `query:` argument — going through the ordinary caller-`include` path is what gets `buildAccessScopedInclude`'s nested-`where` AND-fold, the to-one existence check, and the depth cap for free; the trade-off is that every computed field at a traversed level still computes server-side, same as any other `include`-based read, even one the projection didn't select — only the wire response is narrowed). Throws `McpProjectionRefusedError` (caught in the handler and turned into an `isError` tool result, never a JSON-RPC error) naming what was asked for and what's available on any mismatch.
424
+
425
+ A to-many's `count` is resolved separately via Prisma's `_count.select`, access-scoped by ANDing the related list's `query` access with any caller `where` on that same relation (mirroring, but not reusing, `relationship-count.ts`'s `_count` scoping — that module's own helper isn't exported and was built for a different feature, issue #732's admin list view).
323
426
 
324
427
  ### With Third-Party Field Packages
325
428
 
@@ -1,24 +1,103 @@
1
- import type { Session, AccessContext } from './types.js';
1
+ import type { Session, AccessContext, PrismaFilter } from './types.js';
2
2
  import type { OpenSaasConfig, FieldConfig, ListConfig } from '../config/types.js';
3
+ import { type ResolveSyntheticRelation } from './query-validation.js';
4
+ /**
5
+ * One relation's recorded access filter, or an outright denial — see the
6
+ * module doc's "To-one relations" section. `kind: 'scoped'` is to-one only
7
+ * (a to-many filter is attached as Prisma `where` instead, never recorded
8
+ * here); `kind: 'denied'` is recorded for BOTH arities (issue #1103) — a
9
+ * to-many relation has no `where`-based way to record "zero rows, and the
10
+ * key itself absent" either, so it shares the same post-query mechanism a
11
+ * denied to-one already used.
12
+ */
13
+ export type ToOneAccessFilterEntry = {
14
+ kind: 'scoped';
15
+ relatedListName: string;
16
+ accessWhere: PrismaFilter;
17
+ } | {
18
+ kind: 'denied';
19
+ };
20
+ /**
21
+ * Which relations, at which nesting level of an `include`, need a post-query
22
+ * fixup rather than a Prisma-side `where` — a to-one relation whose related
23
+ * list's `query` access resolved to a filter (`kind: 'scoped'`) or a denial
24
+ * (`kind: 'denied'`), Prisma cannot express either as a nested `where` on a
25
+ * to-one include; a to-many relation whose related list denies `query`
26
+ * access outright (`kind: 'denied'` only — a to-many filter is attached as
27
+ * `where` and never reaches this tree) is dropped from `include` entirely,
28
+ * so nothing marks its key present in the raw row either (issue #1103).
29
+ * `resolveToOneAccessVisibility` consumes this tree; `filterReadableFields`
30
+ * (`field-visibility.ts`) applies its result — forcing a denied key to `null`
31
+ * for a to-one relation, `[]` for a to-many one.
32
+ */
33
+ export type ToOneAccessFilterTree = {
34
+ /** Relation keys at THIS level needing a post-query fixup. */
35
+ filters: Record<string, ToOneAccessFilterEntry>;
36
+ /** Per-key trees for relations present in the include for other reasons, whose own nested include may contain further filters. */
37
+ nested: Record<string, ToOneAccessFilterTree>;
38
+ };
39
+ export declare function emptyToOneAccessFilterTree(): ToOneAccessFilterTree;
40
+ /**
41
+ * Whether a relationship field is to-one (at most one related row) rather
42
+ * than to-many. Exported so `field-visibility.ts` can pick the same `null`
43
+ * (to-one) vs `[]` (to-many) shape for a denied relation's forced value
44
+ * (issue #1103) that this module used to decide whether to record the
45
+ * denial in the first place — one source of truth for arity, not two.
46
+ */
47
+ export declare function isToOneRelationship(fieldConfig: FieldConfig): boolean;
48
+ /**
49
+ * Which `_count.select` keys, at which nesting level of an `include`, were
50
+ * denied outright by their related list's `query` access — omitted from the
51
+ * `_count.select` sent to Prisma (issue #1087), so the row Prisma returns
52
+ * either lacks the key entirely or lacks a `_count` object at all. Consumed
53
+ * post-query by `filterReadableFields` (`field-visibility.ts`), which injects
54
+ * `0` for each — a count is a session-relative value, and `0` is what "no
55
+ * visible rows" means for it, never an absent key (mirroring the to-one
56
+ * `null` injection this module already does for issue #974, though a denied
57
+ * count needs no existence check: `0` requires no query at all).
58
+ */
59
+ export type CountAccessDenialTree = {
60
+ /** `_count.select` keys denied at THIS level. */
61
+ keys: Set<string>;
62
+ /** Per-relation trees for relations present in the include for other reasons, whose own nested include may contain a further `_count`. */
63
+ nested: Record<string, CountAccessDenialTree>;
64
+ };
65
+ export declare function emptyCountAccessDenialTree(): CountAccessDenialTree;
3
66
  /**
4
67
  * Build the access-scoped `include` for exactly the relations a read
5
68
  * requested, recursing only into branches `requestedInclude` itself names.
6
69
  *
7
70
  * For each key in `requestedInclude`:
8
- * - Not a config-declared relationship access control does not govern it;
9
- * passed through unchanged (e.g. a fragment/caller key that isn't a
10
- * relationship at all).
71
+ * - A declared field that isn't a relationship (scalar, virtual, …) → access
72
+ * control does not govern it; passed through unchanged (a virtual key is
73
+ * stripped later by `stripVirtualFieldsFromInclude`, #628).
74
+ * - Not declared at all → resolved via `resolveSyntheticReverseRelation`
75
+ * (the synthetic-back-relation case above); `_count` is scoped by
76
+ * `buildAccessScopedCountSelect` (issue #1087 — each named relation's own
77
+ * `query` access, exactly like any other relation this walk scopes; a
78
+ * denied one is recorded for `filterReadableFields` to inject `0` for,
79
+ * post-query, since Prisma cannot be asked for a guaranteed `0`); anything
80
+ * else throws `UndeclaredIncludeKeyError` rather than reaching the
81
+ * database unscoped.
11
82
  * - A declared relationship whose related list's `query` access denies it
12
83
  * (`=== false`) → dropped entirely, no matter what the request asked for
13
84
  * nested beneath it (#566): the caller chooses *which* relations, access
14
- * control chooses *whether* and *with what filter*.
15
- * - Otherwise the access `where` is AND-combined with any caller-supplied
16
- * nested `where` (never replaced the other half of #566), a
17
- * caller-supplied `take` rides through unchanged (#752), and the "One
18
- * hop" rule (ADR-0026) — nested relations are scoped ONLY if
19
- * `requestedInclude` itself named a nested `include` here. A bare relation
20
- * (or one with no nested `include`) fetches its own columns and stops: no
21
- * recursive call, no access evaluation on anything beneath it.
85
+ * control chooses *whether* and *with what filter*. This denial is also
86
+ * recorded in `toOneAccessFilters` (`kind: 'denied'`), for either arity, so
87
+ * `filterReadableFields` can still surface an explicit `null` (to-one,
88
+ * issue #974) or `[]` (to-many, issue #1103) for it rather than an absent
89
+ * key.
90
+ * - Otherwise, for a to-**many** relation the access `where` is
91
+ * AND-combined with any caller-supplied nested `where` (never replaced
92
+ * the other half of #566), and a caller-supplied `take` rides through
93
+ * unchanged (#752). For a to-**one** relation → the access filter (if any)
94
+ * is recorded in `toOneAccessFilters` instead of attached as `where`,
95
+ * because Prisma only accepts a nested `where` on a to-many include
96
+ * (issue #974) — the entry itself never carries a `where` for a to-one key.
97
+ * - Either way — the "One hop" rule (ADR-0026) — nested relations are scoped
98
+ * ONLY if `requestedInclude` itself named a nested `include` here. A bare
99
+ * relation (or one with no nested `include`) fetches its own columns and
100
+ * stops: no recursive call, no access evaluation on anything beneath it.
22
101
  *
23
102
  * **Depth is a cost limit, not a cycle guard (ADR-0026).** A `requestedInclude`
24
103
  * is always a finite literal — the caller's own object, or
@@ -32,7 +111,57 @@ import type { OpenSaasConfig, FieldConfig, ListConfig } from '../config/types.js
32
111
  export declare function buildAccessScopedInclude(requestedInclude: Record<string, unknown>, fieldConfigs: Record<string, FieldConfig>, args: {
33
112
  session: Session | null;
34
113
  context: AccessContext;
35
- }, config: OpenSaasConfig, listKey: string, depth?: number): Promise<Record<string, unknown>>;
114
+ }, config: OpenSaasConfig, listKey: string, depth?: number): Promise<{
115
+ include: Record<string, unknown>;
116
+ toOneAccessFilters: ToOneAccessFilterTree;
117
+ countDenials: CountAccessDenialTree;
118
+ }>;
119
+ /**
120
+ * One relation's resolved post-query visibility — see
121
+ * `resolveToOneAccessVisibility`. `kind: 'visible'` (an existence check
122
+ * against a set of ids) only ever arises for a to-one relation, since only a
123
+ * to-one `kind: 'scoped'` filter entry produces one; `kind: 'denied'` passes
124
+ * straight through unresolved for either arity.
125
+ */
126
+ export type ToOneVisibility = {
127
+ kind: 'denied';
128
+ } | {
129
+ kind: 'visible';
130
+ ids: ReadonlySet<string>;
131
+ };
132
+ /** The resolved counterpart to {@link ToOneAccessFilterTree}, produced by `resolveToOneAccessVisibility`. */
133
+ export type ToOneAccessVisibilityTree = {
134
+ filters: Record<string, ToOneVisibility>;
135
+ nested: Record<string, ToOneAccessVisibilityTree>;
136
+ };
137
+ export declare function emptyToOneAccessVisibilityTree(): ToOneAccessVisibilityTree;
138
+ /**
139
+ * Resolve a `ToOneAccessFilterTree` against the RAW rows Prisma already
140
+ * fetched (unscoped for the flagged to-one relations — see
141
+ * `buildAccessScopedInclude`) into the set of related ids the session may
142
+ * actually see, one batched `id IN (...)` existence check per (relation,
143
+ * nesting level) across every row in `items` — never once per row.
144
+ *
145
+ * For each `filters` entry at a level:
146
+ * - `kind: 'denied'` → carried straight through; no query, nothing to check.
147
+ * - `kind: 'scoped'` → every id present at this key across ALL of `items` is
148
+ * collected first (an empty set skips the query entirely — nothing to
149
+ * check), then ONE `findMany` through the RAW `prisma` client (not
150
+ * `context.db`, which would re-evaluate the same access-control function a
151
+ * second time) asks which of those ids also satisfy `accessWhere` — the
152
+ * exact `PrismaFilter` `checkAccess` already produced, handed to Prisma
153
+ * unmodified rather than interpreted by hand.
154
+ *
155
+ * Recurses into `nested` by flattening the related items reached through
156
+ * each key across every row in `items` (a to-many hop contributes every one
157
+ * of its rows; a to-one hop contributes its single row, if any) into the
158
+ * next level's own `items` array, so a to-one relation nested arbitrarily
159
+ * deep is still resolved with one batched query per node, not per parent row.
160
+ */
161
+ export declare function resolveToOneAccessVisibility(items: readonly unknown[], tree: ToOneAccessFilterTree, args: {
162
+ session: Session | null;
163
+ context: AccessContext;
164
+ }): Promise<ToOneAccessVisibilityTree>;
36
165
  /**
37
166
  * Scope every relation filter (`some`/`every`/`none`/`is`/`isNot`) nested in a
38
167
  * caller's `where` by the related list's own `query` access — the `where`
@@ -73,11 +202,25 @@ export declare function buildAccessScopedInclude(requestedInclude: Record<string
73
202
  * caller can observe that an inaccessible related row exists (an `every`
74
203
  * that "should" pass instead fails), but never that row's field values,
75
204
  * which is the property this ticket exists to close.
205
+ *
206
+ * A quantifier's value of literal `null` (`is: null`/`isNot: null`, a to-one
207
+ * relation's existence check) is passed through untouched rather than folded:
208
+ * it names no fields to read-check or scope, and AND-folding an access filter
209
+ * into it would silently invert the caller's own predicate (see the inline
210
+ * comment at that branch).
211
+ *
212
+ * `resolveSyntheticRelation` (#1092/#1108) extends this to a key that
213
+ * resolves to a synthetic back-relation (#1082) rather than a declared
214
+ * field, recursing against its SOURCE list. Only `buildAccessScopedInclude`
215
+ * passes it, for the include-nested `where` position; the top-level `where`
216
+ * this function was originally built for (`context/index.ts`) omits it, so
217
+ * a synthetic key there is unaffected — matching #1092's own scope, which
218
+ * deliberately left the top-level checks unchanged.
76
219
  */
77
220
  export declare function buildAccessScopedWhere(where: unknown, listConfig: ListConfig<any>, listName: string, config: OpenSaasConfig, args: {
78
221
  session: Session | null;
79
222
  context: AccessContext;
80
- }): Promise<unknown>;
223
+ }, resolveSyntheticRelation?: ResolveSyntheticRelation): Promise<unknown>;
81
224
  /**
82
225
  * Remove keys that correspond to `virtual` fields from a Prisma `include`
83
226
  * object, recursing into nested relationship includes using the related
@@ -1 +1 @@
1
- {"version":3,"file":"access-filter.d.ts","sourceRoot":"","sources":["../../src/access/access-filter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,aAAa,EAAgB,MAAM,YAAY,CAAA;AACtE,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAA;AAkFjF;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,wBAAwB,CAC5C,gBAAgB,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACzC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,EACzC,IAAI,EAAE;IACJ,OAAO,EAAE,OAAO,GAAG,IAAI,CAAA;IACvB,OAAO,EAAE,aAAa,CAAA;CACvB,EACD,MAAM,EAAE,cAAc,EACtB,OAAO,EAAE,MAAM,EACf,KAAK,GAAE,MAAU,GAChB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAwDlC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AACH,wBAAsB,sBAAsB,CAC1C,KAAK,EAAE,OAAO,EAEd,UAAU,EAAE,UAAU,CAAC,GAAG,CAAC,EAC3B,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,cAAc,EACtB,IAAI,EAAE;IACJ,OAAO,EA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