@workbasehq/core 0.2.15 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/package.json +18 -3
  2. package/src/access-evaluator.ts +72 -0
  3. package/src/access-guards.ts +35 -0
  4. package/src/access-inputs.ts +62 -0
  5. package/src/access-lock/cli.ts +34 -0
  6. package/src/access-lock.ts +183 -0
  7. package/src/access.ts +209 -0
  8. package/src/account-action-conditions.ts +27 -0
  9. package/src/account-command.ts +8 -0
  10. package/src/admin-ui.tsx +3 -2
  11. package/src/app.ts +3 -3
  12. package/src/canonical.ts +6 -0
  13. package/src/capabilities.ts +5 -3
  14. package/src/commands.ts +14 -8
  15. package/src/config.ts +105 -69
  16. package/src/console-build.ts +37 -0
  17. package/src/console-contract.ts +4 -0
  18. package/src/console-model.ts +2 -0
  19. package/src/console.ts +3 -3
  20. package/src/crud.ts +13 -7
  21. package/src/dev-mailbox.ts +35 -0
  22. package/src/display-identity.ts +12 -0
  23. package/src/execution/atomic.ts +17 -3
  24. package/src/execution/policies.ts +14 -6
  25. package/src/execution/policy-receipts.ts +6 -5
  26. package/src/execution/post-commit.ts +11 -0
  27. package/src/execution/types.ts +1 -1
  28. package/src/index.ts +2 -0
  29. package/src/infra/README.md +39 -3
  30. package/src/infra/d1-migrations.ts +4 -3
  31. package/src/infra/instance-migrations.ts +26 -5
  32. package/src/infra/provision-config-main.mjs +3 -3
  33. package/src/infra/provision-diagnostics.ts +4 -0
  34. package/src/infra/provision-plan.ts +34 -5
  35. package/src/infra/provision.ts +26 -4
  36. package/src/infra/schema.ts +1 -1
  37. package/src/kernel/invitation-mail-port.ts +26 -0
  38. package/src/kernel/mail-outbox-port.ts +4 -2
  39. package/src/kernel/migrations.ts +38 -15
  40. package/src/kernel/plugin.ts +2 -0
  41. package/src/kernel/predicate.ts +15 -3
  42. package/src/kernel/registry.ts +69 -12
  43. package/src/member-bootstrap.ts +65 -0
  44. package/src/member-identities.ts +42 -0
  45. package/src/migrations/diagnostics.ts +6 -1
  46. package/src/migrations/model-b.ts +2 -1
  47. package/src/migrations/operational-evidence.ts +51 -0
  48. package/src/migrations/planner.ts +12 -1
  49. package/src/migrations/rebuild.ts +17 -12
  50. package/src/migrations/reset-era.ts +29 -0
  51. package/src/migrations/schema-bundle.ts +43 -0
  52. package/src/migrations/schema-cli.ts +74 -0
  53. package/src/migrations/schema-git.ts +36 -0
  54. package/src/migrations/schema-lock.ts +159 -0
  55. package/src/migrations/schema-plan.ts +94 -0
  56. package/src/migrations/schema.ts +73 -48
  57. package/src/migrations/sdk-baseline.ts +35 -0
  58. package/src/migrations/system-schema.ts +39 -0
  59. package/src/model-inputs.ts +25 -0
  60. package/src/openapi/cli.ts +72 -0
  61. package/src/openapi/generate.ts +166 -0
  62. package/src/openapi/input-projection.ts +131 -0
  63. package/src/openapi/public-paths.ts +80 -0
  64. package/src/openapi/routes.ts +29 -0
  65. package/src/ops.ts +4 -2
  66. package/src/organization-name.ts +35 -0
  67. package/src/organization-permissions.ts +10 -0
  68. package/src/organizations.ts +72 -3
  69. package/src/policies.ts +22 -6
  70. package/src/public-projection.ts +108 -0
  71. package/src/public-schema.ts +5 -43
  72. package/src/query/input-schema.ts +89 -0
  73. package/src/query/limits.ts +1 -1
  74. package/src/query/schema.ts +11 -89
  75. package/src/record-action-routes.ts +87 -0
  76. package/src/record-actions-data.ts +17 -0
  77. package/src/record-actions.ts +61 -0
  78. package/src/record-read.ts +20 -0
  79. package/src/row-access.ts +11 -0
  80. package/src/row-invitations.ts +29 -0
  81. package/src/schema/README.md +323 -0
  82. package/src/schema/declaration.ts +5 -0
  83. package/src/schema/load.ts +423 -0
  84. package/src/schema/lock-format.ts +117 -0
  85. package/src/schema/physical-names.ts +30 -0
  86. package/src/schema/revision.ts +16 -0
  87. package/src/schema/source-location.ts +3 -0
  88. package/src/schema-compatibility.ts +2 -2
  89. package/src/schema.ts +171 -0
  90. package/src/types.ts +1 -1
  91. package/src/user-link-eligibility.ts +36 -0
  92. package/src/user-links.ts +27 -16
  93. package/src/worker-access-actions.ts +89 -0
  94. package/src/worker-access.ts +61 -0
  95. package/src/workflow-runtime.ts +109 -22
  96. package/src/bootstrap.ts +0 -23
@@ -1,13 +1,21 @@
1
+ import { requireOrganizationName } from './organization-name'
1
2
  import { authorizeOperation } from './authorization'
2
3
  import { organizationPermission } from './execution/permissions'
3
4
  import { ApiError } from './errors'
5
+ import { RuleFailed } from './execution/errors'
6
+ import { sha256 } from './crypto'
7
+ import { accountProvisioning } from './account-provisioning'
8
+ import { validateRole } from './organization-permissions'
9
+ import { organizationRule } from './organization-rules'
10
+ import { kernelFor } from './kernel/registry'
11
+ import { scopeOperations } from './scope-operations'
4
12
  import { z } from 'zod'
5
13
  import { coreExecutionContext } from './execution/context'
6
14
  import { D1AtomicStore, D1AtomicReader } from './execution/d1'
7
15
  import { executeAtomic, defineAtomicOperation } from './execution/atomic'
8
16
  import type { InstanceConfig } from './config'
9
17
  import type { RuntimeEnv, Scope } from './types'
10
- import type { AtomicOperation, AtomicPlan, ExecutionContext } from './execution/types'
18
+ import type { AtomicOperation, AtomicPlan, ExecutionContext, SqlStatement } from './execution/types'
11
19
  import type { ResolvedActor } from './authorization'
12
20
  // Only the trusted plugin route executors below can mint these values. Nothing on a
13
21
  // public context, callback prototype or operation permission grants membership.
@@ -32,8 +40,8 @@ export function membershipExecutor(config: InstanceConfig, env: RuntimeEnv) {
32
40
  authorizeOperation(scope, name)
33
41
  const context = coreExecutionContext(config, scope, new D1AtomicStore(env.DB, { env, config }), new D1AtomicReader(env.DB))
34
42
  const operation = defineAtomicOperation({ name, permission: { system }, input: z.strictObject({}), plan: () => plan })
35
- if (['members.update', 'organizations.create', 'invitations.accept'].includes(system)) {
36
- if (context.scope.actor.type !== 'user') throw new ApiError(403, 'field_forbidden')
43
+ if (['members.update', 'organizations.create', 'organizations.provision', 'members.bootstrap', 'invitations.accept'].includes(system)) {
44
+ if (context.scope.actor.type !== (['organizations.provision', 'members.bootstrap'].includes(system) ? 'service' : 'user')) throw new ApiError(403, 'field_forbidden')
37
45
  if (system === 'members.update') organizationPermission(config, context.scope, system)
38
46
  const capability = Object.freeze({ operation, mode: system === 'members.update' ? 'update' as const : 'create' as const })
39
47
  memberCapabilities.add(capability)
@@ -42,3 +50,64 @@ export function membershipExecutor(config: InstanceConfig, env: RuntimeEnv) {
42
50
  return executeAtomic(operation, {}, context)
43
51
  }
44
52
  }
53
+
54
+ /** Shared creation statements: organization, optional domain account, then owner membership. */
55
+ export async function organizationCreationRule(config: InstanceConfig, env: RuntimeEnv, owner: { id: string; email: string }, id: string, name: string, role: string, ownerGuard?: SqlStatement) {
56
+ name = requireOrganizationName(name)
57
+ if (!kernelFor(config).providers.has('members')) throw new ApiError(403, 'members_required')
58
+ const provision = await accountProvisioning(env, config, owner, id, role, new Date().toISOString())
59
+ return organizationRule('organization_create',
60
+ { sql: `INSERT INTO organizations (id,name) SELECT ?,?${ownerGuard ? ` WHERE ${ownerGuard.sql}` : ''}`, bindings: [id, name, ...(ownerGuard?.bindings ?? [])] },
61
+ ...provision,
62
+ { sql: 'INSERT INTO memberships (user_id,organization_id,role) SELECT ?,?,? WHERE changes()=1', bindings: [owner.id, id, role] })
63
+ }
64
+
65
+ /** Called only by the ops-guarded organization route; no user session or credential is minted. */
66
+ export async function provisionOrganization(config: InstanceConfig, env: RuntimeEnv, name: string, ownerEmail: string, correlationId: string) {
67
+ name = requireOrganizationName(name)
68
+ const signInRequired = { status: 409 as const, body: { error: 'owner_sign_in_required' } }
69
+ const verifiedOwner = () => env.DB.prepare('SELECT id,email FROM "user" WHERE lower(email)=? AND "emailVerified"=1').bind(ownerEmail.toLowerCase()).first<{ id: string; email: string }>()
70
+ const owner = await verifiedOwner()
71
+ // Return this precondition failure directly so the HTTP error logger writes no rows either.
72
+ if (!owner) return signInRequired
73
+ // A stable primary key makes concurrent retries converge without a new table or migration.
74
+ const id = `provision_${await sha256(JSON.stringify([owner.email.toLowerCase(), name]))}`
75
+ const role = validateRole(config, config.organizationOwnerRole)
76
+ const key = 'organizations.provision'
77
+ const requestHash = await sha256(JSON.stringify([owner.id, owner.email.toLowerCase(), name]))
78
+ const replay = async () => {
79
+ const receipt = await env.DB.prepare('SELECT response_json,request_hash FROM idempotency_keys WHERE organization_id=? AND key=? AND command=?')
80
+ .bind(id, key, 'organizations/provision').first<{ response_json: string; request_hash: string }>()
81
+ if (!receipt) return null
82
+ if (receipt.request_hash !== requestHash) throw new ApiError(409, 'organization_conflict')
83
+ const result = JSON.parse(receipt.response_json) as { body: { id: string; name: string; role: string } }
84
+ return { status: 200 as const, body: { id: result.body.id, name: result.body.name, role: result.body.role, replayed: true } }
85
+ }
86
+ const prior = await replay()
87
+ if (prior) return prior
88
+ const scope: Scope = { actor: { type: 'service', id: 'organization-provisioner' }, organizationId: id, role: '', correlationId }
89
+ scopeOperations.set(scope, { operations: ['organizations/provision'] })
90
+ const body = { id, name, role, replayed: false }
91
+ try {
92
+ const rule = await organizationCreationRule(config, env, owner, id, name, role, {
93
+ sql: 'EXISTS (SELECT 1 FROM "user" WHERE id=? AND lower(email)=? AND "emailVerified"=1)', bindings: [owner.id, owner.email.toLowerCase()],
94
+ })
95
+ await membershipExecutor(config, env)(scope, 'organizations/provision', 'organizations.provision', {
96
+ // Persist the receipt in the same batch, independent of later tenant mutations.
97
+ rules: [rule, organizationRule('organization_provision_receipt', {
98
+ sql: 'INSERT INTO idempotency_keys (organization_id,key,command,response_json,request_hash) VALUES (?,?,?,?,?)',
99
+ bindings: [id, key, 'organizations/provision', JSON.stringify({ status: 201, body }), requestHash],
100
+ })], event: { operation: 'organization.provisioned', entity: 'organizations', entityId: id }, result: { status: 201, body },
101
+ })
102
+ } catch (error) {
103
+ const winner = await replay()
104
+ if (winner) return winner
105
+ if (!await verifiedOwner()) return signInRequired
106
+ // A concurrent assignment must preserve the same single-account conflict as the preflight.
107
+ await accountProvisioning(env, config, owner, id, role, new Date().toISOString())
108
+ // Rule diagnostics are internal; the public contract is a fixed conflict.
109
+ if (error instanceof RuleFailed) throw new ApiError(409, 'organization_conflict')
110
+ throw error
111
+ }
112
+ return { status: 201 as const, body }
113
+ }
package/src/policies.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { effectiveAuthority } from './access-evaluator'
1
2
  import { constantQuantifier } from './config-shorthand'
2
3
  import { z } from 'zod'
3
4
  import { baseFields, type Field, type InstanceConfig } from './config'
@@ -44,7 +45,9 @@ export function validatePolicies(config: InstanceConfig) {
44
45
  } else if (config.entities[entity].fields[field]?.computed) throw new Error(`Row policy cannot depend on computed field: ${entity}.${field}. Fix: use stored fields to establish row access before computing values.`)
45
46
  }
46
47
  }
47
- for (const [entity, roles] of Object.entries(config.policies)) {
48
+ const policies: (readonly [string, InstanceConfig['policies'][string]])[] = config.effectiveAccess ? config.effectiveAccess.entities.filter(rule => config.entities[rule.entity] && rule.decision === 'allow').map(rule => [rule.entity, { [rule.role]: { where: rule.where, fields: rule.fields ?? undefined } }] as const) : Object.entries(config.policies)
49
+ if (config.effectiveAccess) policies.push(...config.effectiveAccess.actions.flatMap(action => action.conditions.filter(condition => 'when' in condition).map(condition => [action.entity, { [config.roles[0]]: { where: condition.when, fields: undefined } }] as const)))
50
+ for (const [entity, roles] of policies) {
48
51
  if (!Object.hasOwn(config.entities, entity)) throw new Error(`Unknown policy entity: ${entity}`)
49
52
  for (const [role, policy] of Object.entries(roles)) {
50
53
  if (!config.roles.includes(role)) throw new Error(`Unknown policy role: ${role}`)
@@ -53,7 +56,7 @@ export function validatePolicies(config: InstanceConfig) {
53
56
  storedPolicyFields(entity, policy.where)
54
57
  // Validate references separately: a string operand must not accept an unknown actor name as a literal.
55
58
  filterSchema(config, false, 4, actorValue)(entity, 0).parse(policy.where)
56
- if (policy.fields?.some(field => !fieldsFor(config, entity).includes(field))) throw new Error(`Unknown policy field: ${entity}`)
59
+ if (policy.fields?.some((field: string) => !fieldsFor(config, entity).includes(field))) throw new Error(`Unknown policy field: ${entity}`)
57
60
  }
58
61
  }
59
62
  protectedByConfig.set(config, protectedFields)
@@ -115,11 +118,11 @@ function policyGraphUsesActorLinks(config: InstanceConfig, entity: string, roles
115
118
  }
116
119
  return policy(entity)
117
120
  }
118
- function rolePolicyFilter(config: InstanceConfig, entity: string, scope: Scope, role: string): TableFilter {
121
+ export function rolePolicyFilter(config: InstanceConfig, entity: string, scope: Scope, role: string, authored?: InstanceConfig['policies'][string][string]): TableFilter {
119
122
  if (scope.actor.type === 'service' && scope.role === 'SYSTEM') return { kind: 'all' }
120
123
  const actor = projections.get(scope)
121
124
  if ((config.account || scope.actor.type === 'agent') && !actor) return { kind: 'none' }
122
- const policy = config.policies[entity]?.[role] ?? 'none'
125
+ const policy = authored ?? config.policies[entity]?.[role] ?? 'none'
123
126
  if (policy === 'all') return { kind: 'all' }
124
127
  if (policy === 'none') return { kind: 'none' }
125
128
  if (!Object.keys(policy.where).length && policy.deny !== 'forbidden') return { kind: 'all' }
@@ -182,15 +185,27 @@ function constantPredicate(node: Predicate): boolean | undefined {
182
185
  }
183
186
  /** A token's live role caps its issuer's live membership; it cannot outlive a role loss. */
184
187
  export const hasActorProjection = (scope: Scope) => projections.has(scope)
188
+ export const actorMembershipRole = (scope: Scope): string | undefined => {
189
+ const role = projections.get(scope)?.role
190
+ return role === undefined ? undefined : String(role)
191
+ }
185
192
  export function rbacRoles(scope: Scope): string[] {
186
193
  const principal = projections.get(scope)?.role
187
194
  return principal && principal !== scope.role ? [scope.role, String(principal)] : [scope.role]
188
195
  }
189
196
  /** System audit access requires an owner credential and a live owner issuer. */
190
- export function hasOwnerRole(scope: Scope): boolean {
197
+ export function hasOwnerRole(scope: Scope, config?: InstanceConfig): boolean {
198
+ if (config?.effectiveAccess) return (scope.actor.type !== 'agent' || projections.has(scope)) && effectiveAuthority(config.effectiveAccess, scope).permits({ system: 'audit.read' })
191
199
  return (scope.actor.type !== 'agent' || projections.has(scope)) && rbacRoles(scope).every(role => roleNamePrivileges(role).has('audit.read'))
192
200
  }
193
- export function policyFilter(config: InstanceConfig, entity: string, scope: Scope): TableFilter {
201
+ export function policyFilter(config: InstanceConfig, entity: string, scope: Scope, operation: import('./config').Operation = 'read'): TableFilter {
202
+ if (config.effectiveAccess) {
203
+ if (scope.actor.type === 'service' && scope.role === 'SYSTEM') return { kind: 'all' }
204
+ const filter = effectiveAuthority(config.effectiveAccess, scope).filter(entity, operation,
205
+ rule => rolePolicyFilter(config, entity, scope, rule.role, { where: rule.where }))
206
+ const authority = actorLinkProjection(scope)
207
+ return { ...filter, actorAuthorities: authority ? [authority] : [] }
208
+ }
194
209
  const roles = rbacRoles(scope)
195
210
  const filters = roles.map(role => rolePolicyFilter(config, entity, scope, role))
196
211
  const where = filters.filter((filter): filter is Extract<TableFilter, { kind: 'where' }> => filter.kind === 'where')
@@ -205,6 +220,7 @@ export function policyFilter(config: InstanceConfig, entity: string, scope: Scop
205
220
  return authority && policyGraphUsesActorLinks(config, entity, roles) ? { ...result, actorAuthorities: [authority] } : result
206
221
  }
207
222
  export function readableFields(config: InstanceConfig, entity: string, scope: Scope): string[] {
223
+ if (config.effectiveAccess) return effectiveAuthority(config.effectiveAccess, scope).fields(entity)
208
224
  return [...baseFields, ...Object.keys(config.entities[entity].fields)].filter(field => rbacRoles(scope).every(role => {
209
225
  const policy = config.policies[entity]?.[role]
210
226
  const allow = typeof policy === 'object' ? policy.fields : undefined
@@ -0,0 +1,108 @@
1
+ import { z } from 'zod'
2
+ import type { InstanceConfig } from './config'
3
+ import type { RuntimeOptions } from './types'
4
+ import { fieldsFor, fieldType, operatorsFor } from './query/input-schema'
5
+ import { QUERY_LIMITS } from './query/limits'
6
+ import { publicOutputSchema } from './openapi/input-projection'
7
+
8
+ // These objects map user-defined names to schemas; their keys are not keywords.
9
+ const schemaMaps = new Set(['properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas'])
10
+ export function sanitizeSchema(value: unknown, sensitive = false): unknown {
11
+ if (Array.isArray(value)) return value.map(item => sanitizeSchema(item, sensitive))
12
+ if (value === null || typeof value !== 'object') return value
13
+ const node = value as Record<string, unknown>
14
+ sensitive ||= node.sensitive === true
15
+ return Object.fromEntries(Object.entries(node).flatMap(([key, item]) => {
16
+ if (['default', 'examples', 'const'].includes(key) || (sensitive && key === 'description')) return []
17
+ return [[key, schemaMaps.has(key) && item && typeof item === 'object'
18
+ ? Object.fromEntries(Object.entries(item).map(([name, schema]) => [name, sanitizeSchema(schema, sensitive)]))
19
+ : sanitizeSchema(item, sensitive)]]
20
+ }))
21
+ }
22
+
23
+ export function publicQuery(config: InstanceConfig) {
24
+ return {
25
+ format: 'filter-object', required: ['entity', 'limit'], combinators: ['and', 'or', 'not'],
26
+ limits: QUERY_LIMITS,
27
+ entities: Object.fromEntries(Object.entries(config.entities).map(([name, entity]) => [name, {
28
+ fields: Object.fromEntries(fieldsFor(config, name).map(field => [field, { type: fieldType(config, name, field), operators: operatorsFor(fieldType(config, name, field)) }])),
29
+ relations: Object.fromEntries(Object.entries(entity.relations).map(([key, relation]) => [key, {
30
+ entity: relation.entity, field: relation.field, cardinality: relation.many ? '1:n' : 'n:1',
31
+ ...(relation.through ? { through: relation.through } : {}),
32
+ ...(relation.many ? { quantifiers: ['some', 'none'] } : {}),
33
+ }])),
34
+ }])),
35
+ }
36
+ }
37
+
38
+ /** Shared anonymous allowlists; preserve /schema insertion order and values. */
39
+ export function publicFields(entity: InstanceConfig['entities'][string]) {
40
+ return Object.fromEntries(Object.entries(entity.fields).map(([fieldName, field]) => [fieldName, {
41
+ type: field.type, required: field.required,
42
+ ...(field.values === undefined ? {} : { values: field.values }),
43
+ ...(field.entity === undefined ? {} : { entity: field.entity }),
44
+ ...(field.readOnly === undefined ? {} : { readOnly: field.readOnly }),
45
+ ...(field.sensitive === undefined ? {} : { sensitive: field.sensitive }),
46
+ ...(field.ui === undefined ? {} : { ui: field.ui }),
47
+ }]))
48
+ }
49
+ export function publicPolicies(config: InstanceConfig) {
50
+ return Object.fromEntries(Object.entries(config.policies).map(([entity, roles]) => [entity, Object.fromEntries(Object.keys(roles).map(role => [role, true]))]))
51
+ }
52
+ export function publicCommandDefinitions(config: InstanceConfig, options: RuntimeOptions) {
53
+ return config.commands.flatMap(name => {
54
+ const command = options.commands?.get(name)
55
+ return command && !('system' in command.permission) ? [{ name, command }] : []
56
+ })
57
+ }
58
+ export function publicCommands(config: InstanceConfig, options: RuntimeOptions, transformInputs = false) {
59
+ return publicCommandDefinitions(config, options).map(({ name, command }) => ({ name, permission: command.permission, ...(command.ui ? { ui: command.ui } : {}),
60
+ additionalPermissions: command.additionalPermissions ?? [], inputSchema: sanitizeSchema(transformInputs ? transformTolerantSchema(command.input) : z.toJSONSchema(command.input)) }))
61
+ }
62
+ /** Legacy output conversion stays the only path for every transform-free command,
63
+ * so its /schema bytes are unchanged by construction. Only a command whose graph
64
+ * contains a transform uses the disclosure-filtered projection. The check is
65
+ * structural: converting first would evaluate default factories before throwing. */
66
+ function transformTolerantSchema(input: z.ZodType) {
67
+ return containsTransform(input) ? publicOutputSchema(input) : z.toJSONSchema(input)
68
+ }
69
+ /** Follow only known type-def children: enum/literal data and checks are leaves.
70
+ * Data descriptors skip executable accessors. Shape and lazy resolution use Zod's
71
+ * caches; a failed resolution leaves legacy conversion to decide the outcome. */
72
+ function containsTransform(schema: z.core.$ZodType, seen = new Set<z.core.$ZodType>()): boolean {
73
+ if (seen.has(schema)) return false
74
+ seen.add(schema)
75
+ const def = schema._zod.def
76
+ const read = (key: string) => Object.getOwnPropertyDescriptor(def, key)?.value
77
+ const children: z.core.$ZodType[] = []
78
+ const add = (value: unknown) => {
79
+ if ((value as z.core.$ZodType | null)?._zod?.def) children.push(value as z.core.$ZodType)
80
+ }
81
+ // Entries too are read as data descriptors: an accessor-backed array index must never run.
82
+ const addList = (value: unknown) => {
83
+ if (!Array.isArray(value)) return
84
+ const length = Object.getOwnPropertyDescriptor(value, 'length')?.value as number
85
+ for (let index = 0; index < length; index++) add(Object.getOwnPropertyDescriptor(value, index)?.value)
86
+ }
87
+ switch (read('type')) {
88
+ case 'transform': return true
89
+ case 'optional': case 'nullable': case 'default': case 'prefault':
90
+ case 'nonoptional': case 'success': case 'catch': case 'readonly': case 'promise':
91
+ add(read('innerType')); break
92
+ case 'array': add(read('element')); break
93
+ case 'object':
94
+ try { Object.values((schema as z.core.$ZodObject)._zod.def.shape).forEach(add) } catch { /* Unresolvable shape. */ }
95
+ add(read('catchall')); break
96
+ case 'union': addList(read('options')); break
97
+ case 'intersection': add(read('left')); add(read('right')); break
98
+ case 'tuple': addList(read('items')); add(read('rest')); break
99
+ case 'record': case 'map': add(read('keyType')); add(read('valueType')); break
100
+ case 'set': add(read('valueType')); break
101
+ case 'pipe': add(read('in')); add(read('out')); break
102
+ case 'function': add(read('input')); add(read('output')); break
103
+ case 'lazy':
104
+ try { add((schema as z.core.$ZodLazy)._zod.innerType) } catch { /* Unresolvable lazy. */ }
105
+ break
106
+ }
107
+ return children.some(child => containsTransform(child, seen))
108
+ }
@@ -1,25 +1,9 @@
1
1
  import { z } from 'zod'
2
2
  import { labelDependencies } from './query/labels'
3
- import { fieldsFor, fieldType, operatorsFor } from './query/schema'
4
- import { QUERY_LIMITS } from './query/limits'
3
+ import { publicQuery, publicCommands, publicFields, publicPolicies, sanitizeSchema } from './public-projection'
5
4
  import type { InstanceConfig } from './config'
6
5
  import type { RuntimeOptions } from './types'
7
6
 
8
- // These objects map user-defined names to schemas; their keys are not keywords.
9
- const schemaMaps = new Set(['properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas'])
10
- function sanitizeSchema(value: unknown, sensitive = false): unknown {
11
- if (Array.isArray(value)) return value.map(item => sanitizeSchema(item, sensitive))
12
- if (value === null || typeof value !== 'object') return value
13
- const node = value as Record<string, unknown>
14
- sensitive ||= node.sensitive === true
15
- return Object.fromEntries(Object.entries(node).flatMap(([key, item]) => {
16
- if (['default', 'examples', 'const'].includes(key) || (sensitive && key === 'description')) return []
17
- return [[key, schemaMaps.has(key) && item && typeof item === 'object'
18
- ? Object.fromEntries(Object.entries(item).map(([name, schema]) => [name, sanitizeSchema(schema, sensitive)]))
19
- : sanitizeSchema(item, sensitive)]]
20
- }))
21
- }
22
-
23
7
  /** Anonymous build metadata: explicit entity projection, sanitized input schemas. */
24
8
  export function publicSchema(config: InstanceConfig, options: RuntimeOptions) {
25
9
  return {
@@ -29,35 +13,13 @@ export function publicSchema(config: InstanceConfig, options: RuntimeOptions) {
29
13
  entities: Object.fromEntries(Object.entries(config.entities).map(([name, entity]) => [name, {
30
14
  ...(entity.displayField ? { displayField: entity.displayField } : {}),
31
15
  ...(entity.label ? { labelDependencies: labelDependencies(config, name) } : {}),
32
- fields: Object.fromEntries(Object.entries(entity.fields).map(([fieldName, field]) => [fieldName, {
33
- type: field.type, required: field.required,
34
- ...(field.values === undefined ? {} : { values: field.values }),
35
- ...(field.entity === undefined ? {} : { entity: field.entity }),
36
- ...(field.readOnly === undefined ? {} : { readOnly: field.readOnly }),
37
- ...(field.sensitive === undefined ? {} : { sensitive: field.sensitive }),
38
- ...(field.ui === undefined ? {} : { ui: field.ui }),
39
- }])),
16
+ fields: publicFields(entity),
40
17
  }])),
41
- query: {
42
- format: 'filter-object', required: ['entity', 'limit'], combinators: ['and', 'or', 'not'],
43
- limits: QUERY_LIMITS,
44
- entities: Object.fromEntries(Object.entries(config.entities).map(([name, entity]) => [name, {
45
- fields: Object.fromEntries(fieldsFor(config, name).map(field => [field, { type: fieldType(config, name, field), operators: operatorsFor(fieldType(config, name, field)) }])),
46
- relations: Object.fromEntries(Object.entries(entity.relations).map(([key, relation]) => [key, {
47
- entity: relation.entity, field: relation.field, cardinality: relation.many ? '1:n' : 'n:1',
48
- ...(relation.through ? { through: relation.through } : {}),
49
- ...(relation.many ? { quantifiers: ['some', 'none'] } : {}),
50
- }])),
51
- }])),
52
- },
53
- policies: Object.fromEntries(Object.entries(config.policies).map(([entity, roles]) => [entity, Object.fromEntries(Object.keys(roles).map(role => [role, true]))])),
18
+ query: publicQuery(config),
19
+ policies: publicPolicies(config),
54
20
  capabilities: { path: '/o/:org/capabilities', authentication: 'required' },
55
21
  roles: config.roles, permissions: config.permissions,
56
- commands: config.commands.flatMap(name => {
57
- const command = options.commands?.get(name)
58
- return command && !('system' in command.permission) ? [{ name, permission: command.permission, ...(command.ui ? { ui: command.ui } : {}),
59
- additionalPermissions: command.additionalPermissions ?? [], inputSchema: sanitizeSchema(z.toJSONSchema(command.input)) }] : []
60
- }),
22
+ commands: publicCommands(config, options, true),
61
23
  workflows: [...(options.workflows?.values() ?? [])].map(workflow => ({ name: workflow.name, version: workflow.version,
62
24
  inputSchema: sanitizeSchema(z.toJSONSchema(workflow.input)),
63
25
  permissions: workflow.steps?.map(step => ({ name: step.operation.name, permission: step.operation.permission })),
@@ -0,0 +1,89 @@
1
+ import { z } from 'zod'
2
+ import { baseFields } from '../model-inputs'
3
+ import type { Field, InstanceConfig } from '../config'
4
+ import { QUERY_LIMITS as L } from './limits'
5
+ import { labelPath } from './labels'
6
+
7
+ export type Scalar = string | number | boolean | null
8
+ export interface Filter { [key: string]: unknown }
9
+ export interface Order { field: string; dir: 'asc' | 'desc'; label?: boolean }
10
+ export interface Selection { labels?: string[]; select?: string[]; where?: Filter; orderBy?: Order[]; limit?: number; include?: Record<string, Selection> }
11
+ export type RowAccessState = 'no_account' | 'invited' | 'expired' | 'signed_in'
12
+ export interface QueryInput extends Selection { rowAccess?: RowAccessState; contextList?: { entity: string; list: string; id: string }; search?: { text: string; fields: string[]; locale?: 'en' | 'cs' }; labelWhere?: Record<string, { contains: string; locale?: 'en' | 'cs' }>; entity: string; limit: number; cursor?: string }
13
+ export const fieldsFor = (config: InstanceConfig, entity: string) => [...baseFields, ...Object.keys(config.entities[entity].fields)]
14
+ export function fieldType(config: InstanceConfig, entity: string, field: string): Field['type'] {
15
+ return config.entities[entity].fields[field]?.type ?? (field === 'version' ? 'int' : ['created_at', 'updated_at'].includes(field) ? 'datetime' : 'string')
16
+ }
17
+ export function operatorsFor(type: Field['type']) {
18
+ return ['eq', 'ne', 'in', ...(['bool'].includes(type) ? [] : ['lt', 'lte', 'gt', 'gte']),
19
+ ...(['string', 'text'].includes(type) ? ['contains'] : []), 'isNull']
20
+ }
21
+ function valueSchema(config: InstanceConfig, entity: string, field: string, rest: boolean) {
22
+ const type = fieldType(config, entity, field)
23
+ // crud.ts accepted all finite numeric operands (also for int fields), and did
24
+ // not impose the write validator's string lengths on URL filter operands.
25
+ if (rest) return type === 'bool' ? z.boolean() : ['int', 'float'].includes(type) ? z.number().finite() : z.string()
26
+ return type === 'bool' ? z.boolean() : type === 'int' ? z.number().int().safe()
27
+ : type === 'float' ? z.number().finite() : z.string().max(2_000)
28
+ }
29
+ /** Shared client/policy grammar; only trusted configuration enables actor predicates. */
30
+ export function filterSchema(config: InstanceConfig, rest = false, maxDepth = L.relationDepth as number,
31
+ actorValues?: (type: Field['type']) => z.ZodType) {
32
+ const filters = new Map<string, z.ZodType>()
33
+ function filter(name: string, depth: number): z.ZodType {
34
+ const key = `${name}:${depth}`
35
+ const cached = filters.get(key); if (cached) return cached
36
+ const schema: z.ZodType = z.lazy(() => {
37
+ const shape: Record<string, z.ZodType> = Object.create(null)
38
+ for (const field of fieldsFor(config, name)) {
39
+ const scalar = (valueSchema(config, name, field, rest) as z.ZodType).refine((value: unknown) => !actorValues || typeof value !== 'string' || !value.startsWith('$actor.'), 'Actor values require a declared compatible field'); const value = actorValues ? z.union([scalar, actorValues(fieldType(config, name, field))]) : scalar; const ops: Record<string, z.ZodType> = Object.create(null)
40
+ for (const op of rest ? ['eq', 'lt', 'lte', 'gt', 'gte'] : operatorsFor(fieldType(config, name, field))) ops[op] =
41
+ (op === 'isNull' ? (actorValues ? z.union([z.boolean(), actorValues('bool')]) : z.boolean()) : op === 'in' ? z.array(value.nullable()).max(L.bindings)
42
+ : op === 'eq' || op === 'ne' ? value.nullable() : value).optional()
43
+ shape[field] = z.strictObject(ops).refine(v => Object.keys(v).length > 0).optional()
44
+ }
45
+ if (depth < maxDepth) for (const [relation, r] of Object.entries(config.entities[name].relations)) {
46
+ const child = filter(r.entity, depth + 1)
47
+ shape[relation] = (r.many ? z.union([z.strictObject({ some: child }), z.strictObject({ none: child })]) : child).optional()
48
+ }
49
+ if (actorValues) shape.actorLinkedIn = z.string().refine(entity =>
50
+ Object.hasOwn(config.entities, entity) && Object.values(config.entities[entity].fields).some(field => field.userLink),
51
+ 'actorLinkedIn requires an entity with a protected user link').optional()
52
+ shape.and = z.array(schema).min(1).max(L.nodes).optional()
53
+ shape.or = z.array(schema).min(1).max(L.nodes).optional()
54
+ shape.not = schema.optional()
55
+ return z.strictObject(shape)
56
+ })
57
+ filters.set(key, schema); return schema
58
+ }
59
+ return filter
60
+ }
61
+ /** Generated from the complete model. No library AST/raw/functions are client input. */
62
+ export function querySchema(config: InstanceConfig, entity: string, rest = false) {
63
+ const filter = filterSchema(config, rest)
64
+ function selection(name: string, depth: number, root: boolean): z.ZodType {
65
+ const names = fieldsFor(config, name) as [string, ...string[]]
66
+ const labelNames = [...names.filter(key => labelPath(config, name, key)), ...Object.keys(config.ui?.entities?.[name]?.list?.relatedColumns ?? {})] as [string, ...string[]]
67
+ const shape: Record<string, z.ZodType> = {
68
+ select: z.array(z.enum(names)).min(1).max(names.length).refine(v => new Set(v).size === v.length).optional(),
69
+ where: filter(name, depth).optional(),
70
+ orderBy: z.array(z.strictObject({ field: z.enum(root ? [...new Set([...names, ...labelNames])] as [string, ...string[]] : names), dir: z.enum(['asc', 'desc']), ...(root ? { label: z.boolean().optional() } : {}) })).max(5)
71
+ .refine(v => new Set(v.map(o => o.field)).size === v.length).optional(),
72
+ limit: root ? z.number().int().min(1).max(L.root) : z.number().int().min(1).max(L.children).optional(),
73
+ }
74
+ if (depth < L.relationDepth) shape.include = z.strictObject(Object.fromEntries(Object.entries(config.entities[name].relations)
75
+ .map(([key, r]) => [key, z.lazy(() => selection(r.entity, depth + 1, false)).optional()]))).optional()
76
+ if (root) {
77
+ if (labelNames.length) {
78
+ shape.labelWhere = z.partialRecord(z.enum(labelNames), z.strictObject({ contains: z.string().min(1).max(2000), locale: z.enum(['en', 'cs']).optional() })).optional()
79
+ shape.labels = z.array(z.enum(labelNames)).max(L.relations).refine(v => new Set(v).size === v.length).optional()
80
+ }
81
+ shape.search = z.strictObject({ text: z.string().min(1).max(2000), fields: z.array(z.enum([...new Set([...names, ...labelNames])] as [string, ...string[]])).min(1).max(names.length + labelNames.length).refine(v => new Set(v).size === v.length), locale: z.enum(['en', 'cs']).optional() }).optional()
82
+ shape.contextList = z.strictObject({ entity: z.string().regex(/^[a-z][a-z0-9_]*$/).max(100), list: z.string().regex(/^[a-z][a-z0-9_]*$/).max(100), id: z.string().min(1).max(2000) }).optional()
83
+ shape.rowAccess = z.enum(['no_account', 'invited', 'expired', 'signed_in']).optional()
84
+ shape.entity = z.literal(name); shape.cursor = z.string().min(1).max(L.cursorBytes).optional()
85
+ }
86
+ return z.strictObject(shape)
87
+ }
88
+ return selection(entity, 0, true)
89
+ }
@@ -5,4 +5,4 @@ export const QUERY_LIMITS = Object.freeze({
5
5
  levelRows: 2_000, rows: 5_000, statements: 16, bindings: 100,
6
6
  tableReferences: 64, sqlLength: 64_000, inputBytes: 64_000, cursorBytes: 8_000,
7
7
  })
8
- export interface QueryCost { expressionSources?: number; depth: number; relations: number; fieldRows: number; exists: number; nodes: number }
8
+ export interface QueryCost { expressionSources?: number; statements: number; depth: number; relations: number; fieldRows: number; exists: number; nodes: number }
@@ -1,7 +1,6 @@
1
1
  import { organizationPermission } from '../organization-permissions'
2
2
  import { userLinks } from '../user-link-fields'
3
- import { z } from 'zod'
4
- import { baseFields, type Field, type InstanceConfig } from '../config'
3
+ import { baseFields } from '../model-inputs'
5
4
  import type { KernelRegistry } from '../kernel/registry'
6
5
  import type { Scope } from '../types'
7
6
  import { invalid, QueryError, type QueryPath } from './errors'
@@ -10,94 +9,14 @@ import { isRestQuery } from './facade'
10
9
  import { labelPath } from './labels'
11
10
  import { expressionInfo, fieldExpression, readableComputed } from './expressions'
12
11
 
13
- export type Scalar = string | number | boolean | null
14
- export interface Filter { [key: string]: unknown }
15
- export interface Order { field: string; dir: 'asc' | 'desc'; label?: boolean }
16
- export interface Selection { labels?: string[]; select?: string[]; where?: Filter; orderBy?: Order[]; limit?: number; include?: Record<string, Selection> }
17
- export type RowAccessState = 'no_account' | 'invited' | 'expired' | 'signed_in'
18
- export interface QueryInput extends Selection { rowAccess?: RowAccessState; contextList?: { entity: string; list: string; id: string }; search?: { text: string; fields: string[]; locale?: 'en' | 'cs' }; labelWhere?: Record<string, { contains: string; locale?: 'en' | 'cs' }>; entity: string; limit: number; cursor?: string }
19
- export const fieldsFor = (config: InstanceConfig, entity: string) => [...baseFields, ...Object.keys(config.entities[entity].fields)]
20
- export function fieldType(config: InstanceConfig, entity: string, field: string): Field['type'] {
21
- return config.entities[entity].fields[field]?.type ?? (field === 'version' ? 'int' : ['created_at', 'updated_at'].includes(field) ? 'datetime' : 'string')
22
- }
23
- export function operatorsFor(type: Field['type']) {
24
- return ['eq', 'ne', 'in', ...(['bool'].includes(type) ? [] : ['lt', 'lte', 'gt', 'gte']),
25
- ...(['string', 'text'].includes(type) ? ['contains'] : []), 'isNull']
26
- }
27
- function valueSchema(config: InstanceConfig, entity: string, field: string, rest: boolean) {
28
- const type = fieldType(config, entity, field)
29
- // crud.ts accepted all finite numeric operands (also for int fields), and did
30
- // not impose the write validator's string lengths on URL filter operands.
31
- if (rest) return type === 'bool' ? z.boolean() : ['int', 'float'].includes(type) ? z.number().finite() : z.string()
32
- return type === 'bool' ? z.boolean() : type === 'int' ? z.number().int().safe()
33
- : type === 'float' ? z.number().finite() : z.string().max(2_000)
34
- }
35
- /** Shared client/policy grammar; only trusted configuration enables actor predicates. */
36
- export function filterSchema(config: InstanceConfig, rest = false, maxDepth = L.relationDepth as number,
37
- actorValues?: (type: Field['type']) => z.ZodType) {
38
- const filters = new Map<string, z.ZodType>()
39
- function filter(name: string, depth: number): z.ZodType {
40
- const key = `${name}:${depth}`
41
- const cached = filters.get(key); if (cached) return cached
42
- const schema: z.ZodType = z.lazy(() => {
43
- const shape: Record<string, z.ZodType> = Object.create(null)
44
- for (const field of fieldsFor(config, name)) {
45
- const scalar = (valueSchema(config, name, field, rest) as z.ZodType).refine((value: unknown) => !actorValues || typeof value !== 'string' || !value.startsWith('$actor.'), 'Actor values require a declared compatible field'); const value = actorValues ? z.union([scalar, actorValues(fieldType(config, name, field))]) : scalar; const ops: Record<string, z.ZodType> = Object.create(null)
46
- for (const op of rest ? ['eq', 'lt', 'lte', 'gt', 'gte'] : operatorsFor(fieldType(config, name, field))) ops[op] =
47
- (op === 'isNull' ? (actorValues ? z.union([z.boolean(), actorValues('bool')]) : z.boolean()) : op === 'in' ? z.array(value.nullable()).max(L.bindings)
48
- : op === 'eq' || op === 'ne' ? value.nullable() : value).optional()
49
- shape[field] = z.strictObject(ops).refine(v => Object.keys(v).length > 0).optional()
50
- }
51
- if (depth < maxDepth) for (const [relation, r] of Object.entries(config.entities[name].relations)) {
52
- const child = filter(r.entity, depth + 1)
53
- shape[relation] = (r.many ? z.union([z.strictObject({ some: child }), z.strictObject({ none: child })]) : child).optional()
54
- }
55
- if (actorValues) shape.actorLinkedIn = z.string().refine(entity =>
56
- Object.hasOwn(config.entities, entity) && Object.values(config.entities[entity].fields).some(field => field.userLink),
57
- 'actorLinkedIn requires an entity with a protected user link').optional()
58
- shape.and = z.array(schema).min(1).max(L.nodes).optional()
59
- shape.or = z.array(schema).min(1).max(L.nodes).optional()
60
- shape.not = schema.optional()
61
- return z.strictObject(shape)
62
- })
63
- filters.set(key, schema); return schema
64
- }
65
- return filter
66
- }
67
- /** Generated from the complete model. No library AST/raw/functions are client input. */
68
- export function querySchema(config: InstanceConfig, entity: string, rest = false) {
69
- const filter = filterSchema(config, rest)
70
- function selection(name: string, depth: number, root: boolean): z.ZodType {
71
- const names = fieldsFor(config, name) as [string, ...string[]]
72
- const labelNames = [...names.filter(key => labelPath(config, name, key)), ...Object.keys(config.ui?.entities?.[name]?.list?.relatedColumns ?? {})] as [string, ...string[]]
73
- const shape: Record<string, z.ZodType> = {
74
- select: z.array(z.enum(names)).min(1).max(names.length).refine(v => new Set(v).size === v.length).optional(),
75
- where: filter(name, depth).optional(),
76
- orderBy: z.array(z.strictObject({ field: z.enum(root ? [...new Set([...names, ...labelNames])] as [string, ...string[]] : names), dir: z.enum(['asc', 'desc']), ...(root ? { label: z.boolean().optional() } : {}) })).max(5)
77
- .refine(v => new Set(v.map(o => o.field)).size === v.length).optional(),
78
- limit: root ? z.number().int().min(1).max(L.root) : z.number().int().min(1).max(L.children).optional(),
79
- }
80
- if (depth < L.relationDepth) shape.include = z.strictObject(Object.fromEntries(Object.entries(config.entities[name].relations)
81
- .map(([key, r]) => [key, z.lazy(() => selection(r.entity, depth + 1, false)).optional()]))).optional()
82
- if (root) {
83
- if (labelNames.length) {
84
- shape.labelWhere = z.partialRecord(z.enum(labelNames), z.strictObject({ contains: z.string().min(1).max(2000), locale: z.enum(['en', 'cs']).optional() })).optional()
85
- shape.labels = z.array(z.enum(labelNames)).max(L.relations).refine(v => new Set(v).size === v.length).optional()
86
- }
87
- shape.search = z.strictObject({ text: z.string().min(1).max(2000), fields: z.array(z.enum([...new Set([...names, ...labelNames])] as [string, ...string[]])).min(1).max(names.length + labelNames.length).refine(v => new Set(v).size === v.length), locale: z.enum(['en', 'cs']).optional() }).optional()
88
- shape.contextList = z.strictObject({ entity: z.string().regex(/^[a-z][a-z0-9_]*$/).max(100), list: z.string().regex(/^[a-z][a-z0-9_]*$/).max(100), id: z.string().min(1).max(2000) }).optional()
89
- shape.rowAccess = z.enum(['no_account', 'invited', 'expired', 'signed_in']).optional()
90
- shape.entity = z.literal(name); shape.cursor = z.string().min(1).max(L.cursorBytes).optional()
91
- }
92
- return z.strictObject(shape)
93
- }
94
- return selection(entity, 0, true)
95
- }
12
+ export { fieldsFor, fieldType, operatorsFor, filterSchema, querySchema } from './input-schema'
13
+ export type { Scalar, Filter, Order, Selection, RowAccessState, QueryInput } from './input-schema'
14
+ import { fieldsFor, operatorsFor, querySchema, type Filter, type Selection, type QueryInput } from './input-schema'
96
15
  /** Bound recursion before Zod, including malformed/unrecognized inputs. */
97
16
  function preflight(input: unknown) {
98
17
  let nodes = 0
99
18
  function visit(value: unknown, depth: number) {
100
- if (++nodes > L.nodes || depth > L.filterDepth * 3) throw new QueryError('query_too_expensive', [], { depth, nodes, relations: 0, exists: 0, fieldRows: 0 })
19
+ if (++nodes > L.nodes || depth > L.filterDepth * 3) throw new QueryError('query_too_expensive', [], { depth, nodes, statements: 0, relations: 0, exists: 0, fieldRows: 0 })
101
20
  if (value && typeof value === 'object') {
102
21
  if (!Array.isArray(value) && ![Object.prototype, null].includes(Object.getPrototypeOf(value))) invalid()
103
22
  for (const [key, child] of Object.entries(value)) {
@@ -113,7 +32,7 @@ export function validateQuery(kernel: KernelRegistry, scope: Scope, input: unkno
113
32
  if (!input || typeof input !== 'object' || Array.isArray(input)) invalid()
114
33
  const entity = (input as QueryInput).entity
115
34
  if (typeof entity !== 'string' || !Object.hasOwn(kernel.config.entities, entity)) throw new QueryError('entity_not_found', ['entity'])
116
- const depthCost: QueryCost = { depth: 0, relations: 0, fieldRows: 0, exists: 0, nodes: 0 }
35
+ const depthCost: QueryCost = { statements: 0, depth: 0, relations: 0, fieldRows: 0, exists: 0, nodes: 0 }
117
36
  function relationDepth(name: string, node: unknown, depth: number, path: QueryPath) {
118
37
  depthCost.nodes++; depthCost.depth = Math.max(depthCost.depth, depth)
119
38
  if (depth > L.relationDepth) throw new QueryError('query_too_expensive', path, depthCost)
@@ -159,7 +78,7 @@ export function validateQuery(kernel: KernelRegistry, scope: Scope, input: unkno
159
78
  // This predicate goes through normal field masks, policy-scoped sources and cursor hashing.
160
79
  delete query.contextList
161
80
  }
162
- const cost: QueryCost = { depth: 0, relations: 0, fieldRows: 0, exists: query.rowAccess ? 2 : 0, nodes: 0 }
81
+ const cost: QueryCost = { statements: 0, depth: 0, relations: 0, fieldRows: 0, exists: query.rowAccess ? 2 : 0, nodes: 0 }
163
82
  // Every compiled client table source masks each readable FK once. Visibility
164
83
  // probes only test the target's scoped predicate, so do not recursively mask it.
165
84
  function foreignKeyCost(name: string) {
@@ -222,6 +141,9 @@ export function validateQuery(kernel: KernelRegistry, scope: Scope, input: unkno
222
141
  }
223
142
  }
224
143
  function selection(name: string, node: Selection, depth: number, parents: number, path: QueryPath, single = false) {
144
+ // One root plus one per include occurrence, even across repeated branches.
145
+ // Empty runtime parents may skip an include; SQL subqueries add no statements.
146
+ cost.statements++
225
147
  foreignKeyCost(name)
226
148
  permission(name, path); cost.depth = Math.max(cost.depth, depth)
227
149
  const limit = single ? 1 : node.limit ?? L.children
@@ -256,7 +178,7 @@ export function validateQuery(kernel: KernelRegistry, scope: Scope, input: unkno
256
178
  }
257
179
  }
258
180
  selection(entity, query, 0, 1, [])
259
- if (cost.depth > L.relationDepth || cost.relations > L.relations || cost.exists > L.exists || cost.fieldRows > L.fieldRows || cost.nodes > L.nodes)
181
+ if (cost.statements > L.statements || cost.depth > L.relationDepth || cost.relations > L.relations || cost.exists > L.exists || cost.fieldRows > L.fieldRows || cost.nodes > L.nodes)
260
182
  throw new QueryError('query_too_expensive', [], cost)
261
183
  return { query, cost }
262
184
  }