@workbasehq/core 0.2.14 → 0.3.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 (99) 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-presentation.ts +1 -1
  20. package/src/console.ts +3 -3
  21. package/src/crud.ts +13 -7
  22. package/src/dev-mailbox.ts +35 -0
  23. package/src/display-identity.ts +12 -0
  24. package/src/execution/atomic.ts +17 -3
  25. package/src/execution/policies.ts +14 -6
  26. package/src/execution/policy-receipts.ts +6 -5
  27. package/src/execution/post-commit.ts +11 -0
  28. package/src/execution/types.ts +1 -1
  29. package/src/index.ts +2 -0
  30. package/src/infra/README.md +39 -3
  31. package/src/infra/d1-migrations.ts +4 -3
  32. package/src/infra/instance-migrations.ts +26 -5
  33. package/src/infra/provision-config-main.mjs +3 -3
  34. package/src/infra/provision-diagnostics.ts +4 -0
  35. package/src/infra/provision-plan.ts +34 -5
  36. package/src/infra/provision.ts +26 -4
  37. package/src/infra/schema.ts +1 -1
  38. package/src/kernel/invitation-mail-port.ts +26 -0
  39. package/src/kernel/mail-outbox-port.ts +4 -2
  40. package/src/kernel/migrations.ts +38 -15
  41. package/src/kernel/plugin.ts +2 -0
  42. package/src/kernel/predicate.ts +15 -3
  43. package/src/kernel/registry.ts +69 -12
  44. package/src/member-bootstrap.ts +65 -0
  45. package/src/member-identities.ts +42 -0
  46. package/src/migrations/diagnostics.ts +6 -1
  47. package/src/migrations/model-b.ts +2 -1
  48. package/src/migrations/operational-evidence.ts +51 -0
  49. package/src/migrations/planner.ts +12 -1
  50. package/src/migrations/rebuild.ts +17 -12
  51. package/src/migrations/reset-era.ts +29 -0
  52. package/src/migrations/schema-bundle.ts +43 -0
  53. package/src/migrations/schema-cli.ts +74 -0
  54. package/src/migrations/schema-git.ts +36 -0
  55. package/src/migrations/schema-lock.ts +159 -0
  56. package/src/migrations/schema-plan.ts +94 -0
  57. package/src/migrations/schema.ts +73 -48
  58. package/src/migrations/sdk-baseline.ts +35 -0
  59. package/src/migrations/system-schema.ts +39 -0
  60. package/src/model-inputs.ts +25 -0
  61. package/src/openapi/cli.ts +72 -0
  62. package/src/openapi/generate.ts +166 -0
  63. package/src/openapi/input-projection.ts +131 -0
  64. package/src/openapi/public-paths.ts +80 -0
  65. package/src/openapi/routes.ts +29 -0
  66. package/src/ops.ts +4 -2
  67. package/src/organization-name.ts +35 -0
  68. package/src/organization-permissions.ts +10 -0
  69. package/src/organizations.ts +72 -3
  70. package/src/policies.ts +22 -6
  71. package/src/public-projection.ts +108 -0
  72. package/src/public-schema.ts +5 -43
  73. package/src/query/compiler.ts +13 -0
  74. package/src/query/input-schema.ts +89 -0
  75. package/src/query/limits.ts +1 -1
  76. package/src/query/schema.ts +20 -88
  77. package/src/record-action-routes.ts +87 -0
  78. package/src/record-actions-data.ts +17 -0
  79. package/src/record-actions.ts +61 -0
  80. package/src/record-read.ts +20 -0
  81. package/src/row-access.ts +11 -0
  82. package/src/row-invitations.ts +29 -0
  83. package/src/schema/README.md +323 -0
  84. package/src/schema/declaration.ts +5 -0
  85. package/src/schema/load.ts +423 -0
  86. package/src/schema/lock-format.ts +117 -0
  87. package/src/schema/physical-names.ts +30 -0
  88. package/src/schema/revision.ts +16 -0
  89. package/src/schema/source-location.ts +3 -0
  90. package/src/schema-compatibility.ts +2 -2
  91. package/src/schema.ts +171 -0
  92. package/src/types.ts +1 -1
  93. package/src/user-link-eligibility.ts +36 -0
  94. package/src/user-link-fields.ts +7 -0
  95. package/src/user-links.ts +30 -20
  96. package/src/worker-access-actions.ts +89 -0
  97. package/src/worker-access.ts +61 -0
  98. package/src/workflow-runtime.ts +109 -22
  99. 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 })),
@@ -1,3 +1,4 @@
1
+ import { userLinks } from '../user-link-fields'
1
2
  import { DisplayPartsExpression, needsDisplayParts, partsAlias } from './display-parts'
2
3
  import { expressionInfo, readableComputed, rebindExpression, type ExpressionInfo } from './expressions'
3
4
  import { ApiError } from '../errors'
@@ -27,6 +28,17 @@ class ScopedCondition extends Condition {
27
28
  : this.filter.kind === 'all' ? '1=1' : '0=1'
28
29
  }
29
30
  }
31
+ /** Access state is derived only for authorized root rows; credentials never enter projections. */
32
+ class RowAccessCondition extends Condition {
33
+ constructor(private kernel: KernelRegistry, private scope: Scope, private query: QueryInput) { super() }
34
+ toSQL(flavor: ISQLFlavor) {
35
+ const link = userLinks(this.kernel.config).find(link => link.entity === this.query.entity)!
36
+ const bind = (v: unknown) => value(v).toSQL(flavor)
37
+ const root = `SELECT 1 FROM ${quote(link.entity)} access_row WHERE access_row.organization_id=${bind(this.scope.organizationId)} AND access_row.id="row"."id" AND access_row.${quote(link.field)} IS NOT NULL`
38
+ const invitation = `(SELECT CASE WHEN accepted_at IS NOT NULL OR revoked_at IS NOT NULL OR declined_at IS NOT NULL THEN 'no_account' WHEN expired_at IS NOT NULL OR expires_at<=strftime('%Y-%m-%dT%H:%M:%fZ','now') THEN 'expired' ELSE 'invited' END FROM invitations WHERE organization_id=${bind(this.scope.organizationId)} AND target_entity=${bind(this.query.entity)} AND target_row="row"."id" ORDER BY created_at DESC,id DESC LIMIT 1)`
39
+ return `(CASE WHEN EXISTS (${root}) THEN 'signed_in' ELSE coalesce(${invitation},'no_account') END)=${bind(this.query.rowAccess)}`
40
+ }
41
+ }
30
42
  class ContainsCondition extends Condition {
31
43
  constructor(private column: string, private text: string, private insensitive = false) { super() }
32
44
  toSQL(flavor: ISQLFlavor) {
@@ -483,6 +495,7 @@ export function compileRoot(kernel: KernelRegistry, scope: Scope, query: QueryIn
483
495
  labeled = labeled.field(display ? Q.raw(`json_extract(${quote('labels')}."${labelAlias(key)}", '$.row.${display}')`) : Q.raw('NULL'), sortAlias(key))
484
496
  }
485
497
  let ast = labelKeys.length ? Q.select().from(labeled, 'row').field('row.*') : source
498
+ if (query.rowAccess) ast = ast.where(new RowAccessCondition(kernel, scope, query))
486
499
  const order = queryOrder(query).map(o => ({ ...o, field: orderField(o) }))
487
500
  function searchCondition(key: string, text: string, locale: 'en' | 'cs' = 'en'): Condition {
488
501
  const path = labelPath(kernel.config, query.entity, key)
@@ -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 }