@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
package/src/config.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import { baseFields } from './model-inputs'
2
+ export { baseFields, bodyValidator } from './model-inputs'
3
+ import { recordActionsSchema } from './record-actions-data'
1
4
  import { coreEnums, type CoreRole } from './query/enum-values'
2
5
  import { z } from 'zod'
3
6
  import { calendarViewsSchema, validateCalendarViews } from './calendar-display'
@@ -18,7 +21,7 @@ export { Q, Cond }
18
21
  /** SQLite date formatting with column operands; values use the library wire encoding. */
19
22
  export const Fn = { ...LibraryFn, strftime: (format: string, date: string) => Q.expr(`FN(${JSON.stringify(['STRFTIME', Q.value(format).serialize(), Q.expr(date).serialize()])})`) }
20
23
 
21
- export const CORE_VERSION = '0.2.15'
24
+ export const CORE_VERSION = '0.3.1'
22
25
  const navigationIconSchema = z.enum(['LayoutDashboard', 'Users', 'MapPin', 'Coins', 'Wallet', 'ArrowLeftRight', 'Settings', 'Building2', 'Activity', 'Workflow', 'Database', 'Folder'])
23
26
  const identifier = z.string().regex(/^[a-z][a-z0-9_]*$/)
24
27
  export const serializedExpressionSchema = z.union([z.string().min(1).max(32000), z.record(z.string(), z.unknown()).transform(value => JSON.stringify(value))])
@@ -88,6 +91,8 @@ const schema = z.object({
88
91
  }).optional(),
89
92
  }).optional(),
90
93
  pluginConfig: z.record(z.string(), z.unknown()).optional(),
94
+ languages: z.array(z.string()).optional(),
95
+ baseline: z.literal('workbase-sdk').optional(),
91
96
  locale: z.enum(['en', 'cs']).default('en'),
92
97
  timeZone: z.string().default('UTC'),
93
98
  enumLabels: z.record(z.string(), z.record(z.string(), z.string())).optional(),
@@ -96,8 +101,10 @@ const schema = z.object({
96
101
  displayName: z.string().trim().min(1).optional(),
97
102
  id: identifier, revision: z.number().int().positive(),
98
103
  entities: z.record(identifier, z.object({
104
+ renameFrom: identifier.optional(),
99
105
  fields: z.record(identifier, fieldSchema),
100
106
  relations: z.record(identifier, z.object({ field: identifier, entity: identifier, many: z.boolean().optional(), through: z.strictObject({ entity: identifier, field: identifier, createCommand: z.string().min(1), deleteCommand: z.string().min(1) }).optional() })).default({}),
107
+ actions: recordActionsSchema.optional(),
101
108
  commandsOnly: z.boolean().optional(),
102
109
  displayField: serializedExpressionSchema.optional(),
103
110
  displayExpression: z.string().optional(),
@@ -117,13 +124,22 @@ const schema = z.object({
117
124
  }).superRefine((config, ctx) => {
118
125
  if (config.plugins?.length && typeof config.interactive !== 'boolean') ctx.addIssue({ code: 'custom', path: ['interactive'], message: 'interactive must be an explicit boolean when plugins are installed' })
119
126
  })
127
+ /** Shared schema for source-derived audits and property checks. */
128
+ export const instanceConfigSchema = schema
120
129
  export type Field = z.infer<typeof fieldSchema>
121
- export type InstanceConfig = z.infer<typeof schema>
130
+ export type InstanceConfig = z.infer<typeof schema> & { effectiveAccess?: import('./access').EffectiveAccessPolicy; openapi?: Record<string, unknown> }
122
131
  export type InstanceInput = z.input<typeof schema>
123
132
  export type Operation = 'read' | 'create' | 'update' | 'delete'
124
- export const baseFields = ['id', 'organization_id', 'created_at', 'updated_at', 'version']
125
- const reserved = new Set(['users', 'organizations', 'memberships', 'sessions', 'invitations', 'email_outbox', 'audit_outbox', 'security_log', 'idempotency_keys', 'instance_meta', 'webhook_deliveries', 'audit_events', 'd1_migrations', 'identities', 'access_tokens', 'user', 'session', 'account', 'verification', 'rateLimit', 'identity_link_grants', '_plugin_migrations'])
126
- export function defineInstance(input: Omit<ShorthandInput, 'roles' | 'entities' | 'permissions'> & { roles?: string[]; entities?: ShorthandInput['entities']; permissions?: ShorthandInput['permissions'] }): InstanceConfig {
133
+ export const reservedEntities = new Set(['users', 'organizations', 'memberships', 'sessions', 'invitations', 'email_outbox', 'audit_outbox', 'security_log', 'idempotency_keys', 'instance_meta', 'webhook_deliveries', 'audit_events', 'd1_migrations', 'identities', 'access_tokens', 'user', 'session', 'account', 'verification', 'rateLimit', 'identity_link_grants', '_plugin_migrations'])
134
+ type InstanceDefinitionInput = Omit<ShorthandInput, 'roles' | 'entities' | 'permissions' | 'baseline'> & { roles?: string[]; entities?: ShorthandInput['entities']; permissions?: ShorthandInput['permissions'] }
135
+ export function defineInstance(input: InstanceDefinitionInput): InstanceConfig {
136
+ const config = input as InstanceConfig
137
+ // Replaying or planning a compiled V3 schema must retain its authored roles,
138
+ // just as the runtime kernel does. Inline instances keep legacy expansion.
139
+ return normalizeInstance(input, config.baseline === 'workbase-sdk' && !!config.effectiveAccess)
140
+ }
141
+ /** @internal Shared kernel normalization; schema declarations opt into exact authored roles. */
142
+ export function normalizeInstance(input: InstanceDefinitionInput, exactRoles = false, entityError?: (error: unknown, path: (string | number)[]) => never): InstanceConfig {
127
143
  const resolved = resolvePlugins(input.plugins ?? [], input.interactive)
128
144
  const pluginConfig = { ...input.pluginConfig }
129
145
  let contribution: Partial<InstanceInput> = {}
@@ -146,14 +162,31 @@ export function defineInstance(input: Omit<ShorthandInput, 'roles' | 'entities'
146
162
  // existing entries byte-for-byte. Newly materialized roles receive no grants.
147
163
  const authoredRoles = expanded.roles
148
164
  const roles = [...authoredRoles]
149
- for (const role of [expanded.organizationOwnerRole ?? 'owner', 'member']) if (!roles.includes(role)) roles.push(role)
150
- const config = schema.parse({ ...expanded, roles })
165
+ if (exactRoles) {
166
+ if (JSON.stringify(roles) !== JSON.stringify(input.roles) || expanded.organizationOwnerRole !== input.organizationOwnerRole) throw new Error('Plugin role configuration must match declared roles and organizationOwnerRole')
167
+ } else for (const role of [expanded.organizationOwnerRole ?? 'owner', 'member']) if (!roles.includes(role)) roles.push(role)
168
+ // Era belongs to the authored input, never a plugin configure() contribution.
169
+ // Strip the contributed key so absent legacy inputs retain no own baseline key.
170
+ const { baseline: _baseline, ...data } = expanded
171
+ // Declarations may be unbound during schema planning; defineConfig installs the throwing accessor.
172
+ const validator = exactRoles && input.revision === undefined ? schema.safeExtend({ revision: z.number().int().positive().optional() as never }) : schema
173
+ const config = validator.parse({ ...data, roles,
174
+ ...(Object.hasOwn(input, 'baseline') ? { baseline: (input as InstanceInput).baseline } : {}),
175
+ }) as InstanceConfig
176
+ // Generated spec data survives normalization, copies and serialized configs.
177
+ // Only SDK-era configs carry a bound spec (bindOpenApi requires the baseline); legacy inputs cannot author one.
178
+ if ('openapi' in input) {
179
+ if (config.baseline !== 'workbase-sdk') throw new Error('openapi is generated into openapi.json and bound with bindOpenApi; legacy configs cannot carry it')
180
+ config.openapi = (input as InstanceConfig).openapi
181
+ }
182
+ // Re-normalizing an executable config retains its already-compiled access policy.
183
+ if ('effectiveAccess' in input) config.effectiveAccess = (input as InstanceConfig).effectiveAccess
151
184
  for (const name of Object.keys(config.pluginConfig ?? {})) {
152
185
  if (!config.plugins?.some(plugin => plugin.name === name)) throw new Error(`Unknown plugin config: ${name}`)
153
186
  }
154
187
  // Custom roles have no default grants. Preserve sparse explicit/model tables;
155
188
  // implicit tables retain their existing empty entries for custom roles.
156
- const defaultRoles = input.organizationPermissions === undefined && model.organizationPermissions === undefined
189
+ const defaultRoles = exactRoles ? [] : input.organizationPermissions === undefined && model.organizationPermissions === undefined
157
190
  ? authoredRoles.filter(role => role !== 'member') : authoredRoles.filter(role => Object.hasOwn(defaultOrganizationPermissions, role))
158
191
  // Only absent entries receive legacy defaults; a persisted [] stays empty on reload.
159
192
  config.organizationPermissions = { ...Object.fromEntries(defaultRoles.filter(role => !Object.hasOwn(config.organizationPermissions, role))
@@ -161,50 +194,69 @@ export function defineInstance(input: Omit<ShorthandInput, 'roles' | 'entities'
161
194
  if (!authoredRoles.includes(config.organizationOwnerRole) && !Object.hasOwn(config.organizationPermissions, config.organizationOwnerRole)) config.organizationPermissions[config.organizationOwnerRole] = []
162
195
  if (config.organizationOwnerRole !== 'owner' && !config.roles.includes(config.organizationOwnerRole)) throw new Error('Unknown organization owner role')
163
196
  for (const [name, entity] of Object.entries(config.entities)) {
164
- if ((reserved.has(name) && !(name === 'users' && config.account?.entity === name)) || name === 'atomic_assert' || name.startsWith('sqlite_') || name.startsWith('d1_')) throw new Error(`Reserved entity: ${name}`)
165
- if (Object.keys(entity.fields).length > 90) throw new Error('Entity exceeds the supported field/parameter budget')
166
- for (const [key, field] of Object.entries(entity.fields)) {
167
- if (field.userLink) {
168
- if (name === 'users' || config.account?.entity !== 'users' || key !== 'user' || field.type !== 'ref' || field.entity !== 'users'
169
- || field.required || field.computed || field.default != null || field.backfillFrom || field.renameFrom
170
- || !Object.values(entity.relations).some(relation => !relation.many && relation.field === key && relation.entity === 'users')) throw new Error(`Invalid user link: ${name}.${key}`)
171
- field.readOnly = true
197
+ let path: (string | number)[] = ['entities', name]
198
+ try {
199
+ if ((reservedEntities.has(name) && !(name === 'users' && config.account?.entity === name)) || name === 'atomic_assert' || name.startsWith('sqlite_') || name.startsWith('d1_')) throw new Error(`Reserved entity: ${name}`)
200
+ path = ['entities', name, 'fields']
201
+ if (Object.keys(entity.fields).length > 90) throw new Error('Entity exceeds the supported field/parameter budget')
202
+ for (const [key, field] of Object.entries(entity.fields)) {
203
+ path = ['entities', name, 'fields', key]
204
+ if (field.userLink) {
205
+ if (name === 'users' || config.account?.entity !== 'users' || key !== 'user' || field.type !== 'ref' || field.entity !== 'users'
206
+ || field.required || field.computed || field.default != null || field.backfillFrom || field.renameFrom
207
+ || !Object.values(entity.relations).some(relation => !relation.many && relation.field === key && relation.entity === 'users')) throw new Error(`Invalid user link: ${name}.${key}`)
208
+ field.readOnly = true
209
+ }
210
+ if (name === 'users' && ['email', 'password_hash', 'salt'].includes(key)) throw new Error(`Account identity field is private: ${key}`)
211
+ if (field.computed) field.readOnly = true
212
+ if (baseFields.includes(key) || config.baseline === 'workbase-sdk' && ['actions', 'access'].includes(key)) throw new Error(`Reserved field: ${key}`)
213
+ path = ['entities', name, 'fields', key, 'min']
214
+ if (field.min !== undefined && !['int', 'float'].includes(field.type)) throw new Error('min requires a numeric field')
215
+ path = ['entities', name, 'fields', key, 'default']
216
+ if (field.default !== undefined && field.default !== null) {
217
+ const value = field.default
218
+ const valid = field.type === 'bool' ? typeof value === 'boolean'
219
+ : field.type === 'int' ? Number.isSafeInteger(value) && (value as number) >= (field.min ?? Number.MIN_SAFE_INTEGER)
220
+ : field.type === 'float' ? typeof value === 'number' && Number.isFinite(value) && value >= (field.min ?? -Number.MAX_VALUE)
221
+ : field.type === 'enum' ? field.values!.includes(String(value)) && typeof value === 'string'
222
+ : field.type === 'datetime' ? typeof value === 'string' && z.iso.datetime().safeParse(value).success
223
+ : typeof value === 'string'
224
+ if (!valid) throw new Error(`Invalid default: ${name}.${key}`)
225
+ }
226
+ if (field.required && field.default === null) throw new Error(`Required default cannot be null: ${name}.${key}`)
227
+ path = ['entities', name, 'fields', key, 'entity']
228
+ if (field.type === 'ref' && !Object.hasOwn(config.entities, field.entity!)) throw new Error(`Unknown reference: ${field.entity}`)
229
+ path = ['entities', name, 'fields', key, 'backfillFrom']
230
+ if (field.backfillFrom) {
231
+ const ref = entity.fields[field.backfillFrom.refField]
232
+ if (!ref?.entity || ref.computed || !config.entities[ref.entity]?.fields[field.backfillFrom.valueField] || config.entities[ref.entity].fields[field.backfillFrom.valueField].computed) throw new Error('Invalid backfill reference')
233
+ }
172
234
  }
173
- if (name === 'users' && ['email', 'password_hash', 'salt'].includes(key)) throw new Error(`Account identity field is private: ${key}`)
174
- if (field.computed) field.readOnly = true
175
- if (baseFields.includes(key)) throw new Error(`Reserved field: ${key}`)
176
- if (field.min !== undefined && !['int', 'float'].includes(field.type)) throw new Error('min requires a numeric field')
177
- if (field.default !== undefined && field.default !== null) {
178
- const value = field.default
179
- const valid = field.type === 'bool' ? typeof value === 'boolean'
180
- : field.type === 'int' ? Number.isSafeInteger(value) && (value as number) >= (field.min ?? Number.MIN_SAFE_INTEGER)
181
- : field.type === 'float' ? typeof value === 'number' && Number.isFinite(value) && value >= (field.min ?? -Number.MAX_VALUE)
182
- : field.type === 'enum' ? field.values!.includes(String(value)) && typeof value === 'string'
183
- : field.type === 'datetime' ? typeof value === 'string' && z.iso.datetime().safeParse(value).success
184
- : typeof value === 'string'
185
- if (!valid) throw new Error(`Invalid default: ${name}.${key}`)
235
+ for (const [relationName, r] of Object.entries(entity.relations)) {
236
+ path = ['entities', name, 'relations', relationName]
237
+ if (config.baseline === 'workbase-sdk' && ['actions', 'access'].includes(relationName)) throw new Error(`Reserved relation: ${relationName}`)
238
+ path.push('field')
239
+ const target = r.many ? config.entities[r.entity]?.fields[r.field] : entity.fields[r.field]
240
+ if (!target || target.type !== 'ref' || target.entity !== (r.many ? name : r.entity)) throw new Error(`Invalid relation on ${name}`)
241
+ path = ['entities', name, 'relations', relationName, 'through']
242
+ if (r.through) {
243
+ const join = config.entities[r.entity]
244
+ const other = join?.fields[r.through.field]
245
+ if (Object.hasOwn(entity.fields, relationName) || !r.many || r.field === r.through.field || other?.type !== 'ref' || other.entity !== r.through.entity
246
+ || Object.entries(join.fields).some(([field, spec]) => ![r.field, r.through!.field].includes(field) && !(spec.readOnly && spec.ui?.hidden))
247
+ || ![r.through.createCommand, r.through.deleteCommand].every(command => config.commands.includes(command))) throw new Error(`Invalid pure join relation on ${name}`)
248
+ const inverse = Object.values(config.entities[r.through.entity]?.relations ?? {}).some(inverse => inverse.entity === r.entity && inverse.field === r.through!.field && inverse.through?.entity === name && inverse.through.field === r.field)
249
+ if (!inverse) throw new Error(`Missing inverse pure join relation on ${name}`)
250
+ }
186
251
  }
187
- if (field.required && field.default === null) throw new Error(`Required default cannot be null: ${name}.${key}`)
188
- if (field.type === 'ref' && !Object.hasOwn(config.entities, field.entity!)) throw new Error(`Unknown reference: ${field.entity}`)
189
- if (field.backfillFrom) {
190
- const ref = entity.fields[field.backfillFrom.refField]
191
- if (!ref?.entity || ref.computed || !config.entities[ref.entity]?.fields[field.backfillFrom.valueField] || config.entities[ref.entity].fields[field.backfillFrom.valueField].computed) throw new Error('Invalid backfill reference')
192
- }
193
- }
194
- for (const [relationName, r] of Object.entries(entity.relations)) {
195
- const target = r.many ? config.entities[r.entity]?.fields[r.field] : entity.fields[r.field]
196
- if (!target || target.type !== 'ref' || target.entity !== (r.many ? name : r.entity)) throw new Error(`Invalid relation on ${name}`)
197
- if (r.through) {
198
- const join = config.entities[r.entity]
199
- const other = join?.fields[r.through.field]
200
- if (Object.hasOwn(entity.fields, relationName) || !r.many || r.field === r.through.field || other?.type !== 'ref' || other.entity !== r.through.entity
201
- || Object.entries(join.fields).some(([field, spec]) => ![r.field, r.through!.field].includes(field) && !(spec.readOnly && spec.ui?.hidden))
202
- || ![r.through.createCommand, r.through.deleteCommand].every(command => config.commands.includes(command))) throw new Error(`Invalid pure join relation on ${name}`)
203
- const inverse = Object.values(config.entities[r.through.entity]?.relations ?? {}).some(inverse => inverse.entity === r.entity && inverse.field === r.through!.field && inverse.through?.entity === name && inverse.through.field === r.field)
204
- if (!inverse) throw new Error(`Missing inverse pure join relation on ${name}`)
252
+ for (const [i, c] of entity.checks.entries()) {
253
+ path = ['entities', name, 'checks', i, !entity.fields[c.left] || entity.fields[c.left].computed ? 'left' : 'right']
254
+ if (!entity.fields[c.left] || !entity.fields[c.right] || entity.fields[c.left].computed || entity.fields[c.right].computed) throw new Error('Unknown check field')
205
255
  }
256
+ } catch (error) {
257
+ if (entityError) entityError(error, path)
258
+ throw error
206
259
  }
207
- for (const c of entity.checks) if (!entity.fields[c.left] || !entity.fields[c.right] || entity.fields[c.left].computed || entity.fields[c.right].computed) throw new Error('Unknown check field')
208
260
  }
209
261
  for (const [role, grants] of Object.entries(config.permissions)) {
210
262
  if (!config.roles.includes(role as any)) throw new Error(`Unknown role ${role}`)
@@ -252,7 +304,11 @@ export function defineInstance(input: Omit<ShorthandInput, 'roles' | 'entities'
252
304
  const known = (field: string) => baseFields.includes(field) || Object.hasOwn(entity.fields, field)
253
305
  validateFormDisplay(name, entity, hints)
254
306
  if (hints.detail) validateDetailDisplay(config, name, hints.detail)
255
- for (const [field, spec] of Object.entries(entity.fields)) if (spec.ui?.signedBy && (!known(spec.ui.signedBy.field) || !['int', 'float'].includes(spec.type))) throw new Error(`Invalid signed UI field: ${name}.${field}`)
307
+ for (const [field, spec] of Object.entries(entity.fields)) if (spec.ui?.signedBy && (!known(spec.ui.signedBy.field) || !['int', 'float'].includes(spec.type))) {
308
+ const error = new Error(`Invalid signed UI field: ${name}.${field}`)
309
+ if (entityError) entityError(error, ['entities', name, 'fields', field, 'ui', 'signedBy', 'field'])
310
+ throw error
311
+ }
256
312
  validateCalendarViews(config, name, hints.views)
257
313
  const list = hints.list
258
314
  if (!list) continue
@@ -295,26 +351,6 @@ export function inspectInstance(input: Parameters<typeof defineInstance>[0]) {
295
351
  throw error
296
352
  }
297
353
  }
298
- export function bodyValidator(entity: InstanceConfig['entities'][string], partial = false) {
299
- const shape: Record<string, z.ZodType> = {}
300
- for (const [name, f] of Object.entries(entity.fields)) {
301
- if (f.readOnly || f.computed) continue
302
- let v: z.ZodType
303
- switch (f.type) {
304
- case 'int': v = z.number().int().min(f.min ?? Number.MIN_SAFE_INTEGER); break
305
- case 'float': v = z.number().min(f.min ?? -Number.MAX_VALUE); break
306
- case 'bool': v = z.boolean(); break
307
- case 'datetime': v = z.iso.datetime(); break
308
- case 'enum': v = z.enum(f.values as [string, ...string[]]); break
309
- default: v = z.string().min(1).max(f.type === 'text' ? 100000 : 2000)
310
- }
311
- if (!f.required) v = v.nullable()
312
- if (!partial && f.default !== undefined) v = v.default(f.default)
313
- else if (partial || !f.required) v = v.optional()
314
- shape[name] = v
315
- }
316
- return z.strictObject(shape)
317
- }
318
354
  export const allowed = (c: InstanceConfig, role: string, entity: string, op: Operation) => Object.hasOwn(c.permissions, role) && Object.hasOwn(c.permissions[role], entity) && c.permissions[role][entity].includes(op)
319
355
 
320
356
  /** Clone mutable schema/config data while retaining the trusted plugin code references. */
@@ -0,0 +1,37 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { readFile, readdir } from 'node:fs/promises'
3
+ import { join } from 'node:path'
4
+
5
+ export const CONSOLE_SHA_MARKER = 'WORKBASE_BUNDLE_SHA_' + 'X'.repeat(21)
6
+ const stamp = /(<meta name="workbase-build-sha" content=")([^"]+)(">)/g
7
+
8
+ /** Snapshot the complete upload directory, including Vite's copied public assets. */
9
+ export async function readConsoleArtifacts(directory: string): Promise<Map<string, Buffer>> {
10
+ const files = new Map<string, Buffer>()
11
+ async function visit(path: string, prefix: string) {
12
+ for (const entry of await readdir(path, { withFileTypes: true })) {
13
+ const name = prefix + entry.name, file = join(path, entry.name)
14
+ if (entry.isDirectory()) await visit(file, name + '/')
15
+ else if (entry.isFile()) files.set(name, await readFile(file))
16
+ else throw new Error('Console output must contain only files and directories')
17
+ }
18
+ }
19
+ await visit(directory, '')
20
+ return files
21
+ }
22
+
23
+ /** Exclude only self-referential identity/time metadata; preserve all other bytes. */
24
+ export function consoleArtifactsSHA(files: Map<string, Buffer>): string {
25
+ const hash = createHash('sha1')
26
+ for (const name of [...files.keys()].filter(name => name !== 'build-meta.json').sort()) {
27
+ const raw = files.get(name)!
28
+ const bytes = name.endsWith('.html')
29
+ ? Buffer.from(raw.toString('latin1').replace(stamp, `$1${CONSOLE_SHA_MARKER}$3`), 'latin1') : raw
30
+ hash.update(JSON.stringify([name, bytes.length]) + '\0').update(bytes)
31
+ }
32
+ return hash.digest('hex')
33
+ }
34
+
35
+ export function consoleHTMLStamps(html: string): string[] {
36
+ return [...html.matchAll(stamp)].map(match => match[2])
37
+ }
@@ -127,6 +127,10 @@ export interface ConsoleModelRelation {
127
127
  through?: { entity: string; field: string; createCommand: string; deleteCommand: string }
128
128
  }
129
129
  export interface ConsoleModelEntity extends Omit<ConsoleEntityDisplay, 'fields'> {
130
+ /** Structural identity of the protected link, independent of read/manage grants. */
131
+ accountLink?: { field: string; entity: string }
132
+ /** Members status endpoint is available under the current read grants. */
133
+ rowAccess?: boolean
130
134
  rowInvitations?: boolean
131
135
  fields: Record<string, ConsoleModelField>
132
136
  columns: string[]
@@ -36,6 +36,7 @@ export function consoleModel(kernel: KernelRegistry, scope: Scope): ConsoleModel
36
36
  if (Array.isArray(schema.required)) schema.required = schema.required.filter(field => Object.hasOwn(schema.properties as object, field))
37
37
  return consoleInputSchema(schema, node => authority.schema(node) && literalGrants.get(node) !== false)
38
38
  }
39
+ const link = Object.entries(entity.fields).find(([, field]) => field.userLink)
39
40
  let rowInvitations = false
40
41
  if (kernel.providers.has('members') && authority.read(name, 'id') && Object.values(entity.fields).some(field => field.userLink)) {
41
42
  try { kernel.permission(scope, name, 'create'); kernel.resourcePermission(scope, 'invitations.create'); organizationPermission(config, scope, 'invitations.create'); rowInvitations = canGrantRole(config, scope.role, 'member') } catch {}
@@ -44,6 +45,7 @@ export function consoleModel(kernel: KernelRegistry, scope: Scope): ConsoleModel
44
45
  const displayField = entity.displayField && authority.read(name, entity.displayField) ? entity.displayField : undefined
45
46
  return [name, {
46
47
  ...display,
48
+ ...(link ? { accountLink: { field: link[0], entity: link[1].entity! }, rowAccess: kernel.providers.has('members') && authority.read(name, 'id') && authority.grant('invitations.read') } : {}),
47
49
  ...(rowInvitations ? { rowInvitations: true } : {}),
48
50
  fields: Object.fromEntries(fieldsFor(config, name).filter(field => authority.read(name, field)).map(field => {
49
51
  const definition = entity.fields[field]
package/src/console.ts CHANGED
@@ -14,11 +14,11 @@ export async function buildInfo(config: Pick<InstanceConfig, 'revision'>, env: R
14
14
  }
15
15
  }
16
16
  }
17
- return { sha: sha ?? 'unbuilt', builtAt: builtAt ?? 'unbuilt', revision: config.revision }
17
+ return { sha: sha ?? 'unbuilt', builtAt: builtAt ?? 'unbuilt', revision: config.revision, openapi: env.OPENAPI_SHA256 ?? 'unbuilt' }
18
18
  }
19
19
  function isConsolePath(path: string) {
20
- return !(/^\/(api|auth|mcp|internal|ops|admin|commands|workflows|query|orgs|invitations|audit|me|health|schema|console-info|bootstrap|build\.json)(\/|$)/.test(path)
21
- || /^\/o\/[^/]+\/(bootstrap|capabilities|console-model|console-registry|console-pages|config-versions)(\/|$)/.test(path))
20
+ return !(/^\/(api|auth|mcp|internal|ops|admin|commands|workflows|query|orgs|invitations|audit|me|health|schema|console-info|build\.json|openapi\.json)(\/|$)/.test(path)
21
+ || /^\/o\/[^/]+\/(capabilities|console-model|console-pages|config-versions)(\/|$)/.test(path))
22
22
  }
23
23
 
24
24
  async function serveConsole(request: Request, env: RuntimeEnv) {
package/src/crud.ts CHANGED
@@ -1,3 +1,7 @@
1
+ import { readRecord } from './record-read'
2
+ import { accountAccessState, canReadAccountAccess } from './worker-access'
3
+ import { recordActionRoutes } from './record-action-routes'
4
+ import { recordActions } from './record-actions'
1
5
  import { assertActorFields } from './policies'
2
6
  import { enforcePlan, writeFilter } from './execution/policies'
3
7
  import { compile } from './execution/compiler'
@@ -27,6 +31,7 @@ export function serialize(config: InstanceConfig, name: string, row: Row) {
27
31
  return out
28
32
  }
29
33
  export function crudRoutes(app: App, config: InstanceConfig, env: RuntimeEnv) {
34
+ recordActionRoutes(app, config, env)
30
35
  const kernel = kernelFor(config)
31
36
  const storedFields = (name: string) => fieldsFor(config, name).filter(field => !config.entities[name].fields[field]?.computed).filter(field => !config.entities[name].label || field !== config.entities[name].displayField)
32
37
  const responseRow = async (name: string, scope: Scope, row: Row) => {
@@ -79,10 +84,11 @@ export function crudRoutes(app: App, config: InstanceConfig, env: RuntimeEnv) {
79
84
  }))
80
85
  app.get('/api/:entity/:id', c => observeQuery(env.DB, c.get('scope'), async (writeLog, rejectedInput) => {
81
86
  await rejectedInput({ entity: c.req.param('entity'), id: c.req.param('id'), params: c.req.query() })
82
- const { name, scope } = entity(c, 'read')
83
- const result = await executeQuery(kernel, scope, env.DB, await cursorSecret(env), restQuery(config, name, c.req.query(), c.req.param('id')), { legacyErrors: true, writeLog })
84
- if (!result.data.length) throw new ApiError(404, 'not_found')
85
- return c.json(result.data[0])
87
+ const name = c.req.param('entity')!, scope = c.get('scope')
88
+ const row = await readRecord(config, scope, env, name, c.req.param('id')!, c.req.query(), writeLog)
89
+ if (config.baseline === 'workbase-sdk') row.actions = await recordActions(config, scope, env.DB, name, c.req.param('id')!)
90
+ if (config.baseline === 'workbase-sdk' && canReadAccountAccess(config, scope, name)) row.access = await accountAccessState(config, scope, env.DB, name, c.req.param('id')!)
91
+ return c.json(row)
86
92
  }))
87
93
  app.post('/api/:entity', async c => {
88
94
  const { name, definition, scope, table } = entity(c, 'create')
@@ -98,7 +104,7 @@ export function crudRoutes(app: App, config: InstanceConfig, env: RuntimeEnv) {
98
104
  if (!stored) return null
99
105
  if (stored.command !== operation || stored.request_hash !== hash) throw new ApiError(422, 'idempotency_payload_mismatch')
100
106
  const row = JSON.parse(stored.response_json).body as Row
101
- const policy = writeFilter(kernel, scope, name)
107
+ const policy = writeFilter(kernel, scope, name, name, 'create')
102
108
  const visible = await env.DB.prepare(`SELECT id FROM ${table} WHERE id=? AND (${policy.sql})`).bind(row.id, ...(policy.bindings ?? [])).first()
103
109
  if (!visible) hidden(name, scope)
104
110
  return row
@@ -129,7 +135,7 @@ export function crudRoutes(app: App, config: InstanceConfig, env: RuntimeEnv) {
129
135
  assertActorFields(config, scope, name, Object.keys(raw), c.req.param('id'))
130
136
  const body = bodyValidator(definition, true).parse(raw) as Row
131
137
  if (!Object.keys(body).length) throw new ApiError(400, 'empty_update')
132
- const policy = writeFilter(kernel, scope, name)
138
+ const policy = writeFilter(kernel, scope, name, name, 'update')
133
139
  const before = await env.DB.prepare(`SELECT ${storedFields(name).map(quote).join(',')} FROM ${table} WHERE organization_id=? AND id=? AND (${policy.sql})`).bind(scope.organizationId, c.req.param('id'), ...(policy.bindings ?? [])).first<Row>()
134
140
  if (!before) hidden(name, scope)
135
141
  if (before.version !== expected) throw new ApiError(409, 'version_conflict')
@@ -141,7 +147,7 @@ export function crudRoutes(app: App, config: InstanceConfig, env: RuntimeEnv) {
141
147
  })
142
148
  app.delete('/api/:entity/:id', async c => {
143
149
  const { name, scope, table } = entity(c, 'delete')
144
- const policy = writeFilter(kernel, scope, name)
150
+ const policy = writeFilter(kernel, scope, name, name, 'delete')
145
151
  const before = await env.DB.prepare(`SELECT ${storedFields(name).map(quote).join(',')} FROM ${table} WHERE organization_id=? AND id=? AND (${policy.sql})`).bind(scope.organizationId, c.req.param('id'), ...(policy.bindings ?? [])).first<Row>()
146
152
  if (!before) hidden(name, scope)
147
153
  await mutate(name, scope, { sql: `DELETE FROM ${table} WHERE organization_id=? AND id=? AND version=?`, bindings: [scope.organizationId, c.req.param('id'), before.version] }, makeEvent(config, scope, `${name}.deleted`, name, before.id, serialize(config, name, before)))
@@ -0,0 +1,35 @@
1
+ import { equalHash, sha256 } from './crypto'
2
+
3
+ interface DevMailboxEnv {
4
+ DB: D1Database
5
+ STAGE?: string
6
+ DEV_MAILBOX_TOKEN?: string
7
+ }
8
+
9
+ export default {
10
+ /** Separate operator-only Worker entry. Never import this from the application Worker. */
11
+ async fetch(request: Request, env: DevMailboxEnv): Promise<Response> {
12
+ const respond = (body: unknown, status = 200) => Response.json(body, { status, headers: {
13
+ 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff',
14
+ } })
15
+ // Defense in depth for hand-deployed sidecars; the provisioner also gates construction.
16
+ if (env.STAGE !== 'dev' && env.STAGE !== 'test') return respond({ error: 'not_found' }, 404)
17
+ if (!env.DEV_MAILBOX_TOKEN || !/^[\x21-\x7e]{32,256}$/.test(env.DEV_MAILBOX_TOKEN)) return respond({ error: 'dev_mailbox_not_configured' }, 503)
18
+ const authorization = request.headers.get('Authorization') ?? ''
19
+ if (request.headers.has('Origin') || !authorization.startsWith('Bearer ') || authorization.length > 263
20
+ || !equalHash(await sha256(authorization.slice(7)), await sha256(env.DEV_MAILBOX_TOKEN))) return respond({ error: 'forbidden' }, 403)
21
+ const url = new URL(request.url)
22
+ if (url.pathname !== '/messages') return respond({ error: 'not_found' }, 404)
23
+ if (request.method !== 'GET') return respond({ error: 'method_not_allowed' }, 405)
24
+ const recipient = url.searchParams.get('recipient') ?? ''
25
+ const limit = url.searchParams.get('limit') ?? '20'
26
+ if (url.searchParams.getAll('recipient').length !== 1 || recipient.length > 254 || !/^[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+$/.test(recipient)
27
+ || url.searchParams.getAll('limit').length > 1 || !/^[1-9]\d?$/.test(limit) || Number(limit) > 50
28
+ || [...url.searchParams.keys()].some(key => key !== 'recipient' && key !== 'limit')) return respond({ error: 'invalid_query' }, 400)
29
+ try {
30
+ const { results } = await env.DB.prepare(`SELECT id,recipient,subject,body,created_at,expires_at FROM email_outbox
31
+ WHERE recipient=? ORDER BY created_at DESC,rowid DESC LIMIT ?`).bind(recipient, Number(limit)).all()
32
+ return respond({ messages: results })
33
+ } catch { return respond({ error: 'dev_mailbox_unavailable' }, 503) }
34
+ },
35
+ }
@@ -0,0 +1,12 @@
1
+ /** Supply only rows already authorized by the caller's member/inviter/issuer
2
+ * boundary. This pure projection cannot load another user's profile or leak
3
+ * credential, external subject, membership or synchronization metadata. */
4
+ export function displayIdentity(row: { firstName?: string | null; lastName?: string | null; name?: string | null; email?: string | null } | null) {
5
+ const names = [row?.firstName?.trim(), row?.lastName?.trim()].filter(Boolean).join(' ')
6
+ const legacy = row?.name?.trim()
7
+ const email = row?.email?.trim()
8
+ if (names) return { displayName: names, source: 'profile' as const }
9
+ if (legacy) return { displayName: legacy, source: 'legacy_name' as const }
10
+ if (email) return { displayName: email, source: 'email' as const }
11
+ return { displayName: null, source: 'unavailable' as const }
12
+ }
@@ -1,3 +1,4 @@
1
+ import { postCommitFor } from './post-commit'
1
2
  import { needsPolicyReceipt, receiptIdentity, receiptExpression, authorizeReplay } from './policy-receipts'
2
3
  import { kernelFor } from '../kernel/registry'
3
4
  import { loadActorProjection } from '../policies'
@@ -44,14 +45,17 @@ export async function executeAtomic<S extends z.ZodType>(operation: AtomicOperat
44
45
  const prior = await replay()
45
46
  if (prior) return prior
46
47
  let conflict: string | undefined
48
+ let prepared: unknown
49
+ let committed: AtomicResult
50
+ const postCommit = postCommitFor(identity)
51
+ const runId = crypto.randomUUID()
47
52
  try {
48
- const prepared = await operation.prepare?.(Object.freeze({ __proto__: null, ...context, reader: Object.freeze({ __proto__: null, first: <T>(query: Parameters<typeof reader.first>[0]) => reader.first<T>(query) }) }), body)
53
+ prepared = await operation.prepare?.(Object.freeze({ __proto__: null, ...context, reader: Object.freeze({ __proto__: null, first: <T>(query: Parameters<typeof reader.first>[0]) => reader.first<T>(query) }) }), body)
49
54
  const rawPlan = operation.plan(Object.freeze({ __proto__: null, ...context, prepared, now: new Date().toISOString(), newId: crypto.randomUUID() }), body)
50
55
  validatePlan(rawPlan)
51
56
  const plan = enforcePlan(kernelFor(config), scope, rawPlan, memberMode)
52
57
  conflict = plan.conflict
53
58
  const event = makeEvent(config, scope, plan.event.operation, plan.event.entity, plan.event.entityId, plan.event.before, plan.event.after, plan.event.details)
54
- const runId = crypto.randomUUID()
55
59
  const response = policyIdentity ? receiptExpression(config, plan.rules, runId, plan.result, policyIdentity) : { sql: '?', bindings: [JSON.stringify(plan.result)] }
56
60
  const submission: StorePlan = { runId, rules: [...plan.rules,
57
61
  { name: 'audit_outbox', statements: [outboxInsert(event, { sql: 'NOT EXISTS (SELECT 1 FROM atomic_assert WHERE run_id=? AND ok<>1)', bindings: [runId] })] },
@@ -60,11 +64,21 @@ export async function executeAtomic<S extends z.ZodType>(operation: AtomicOperat
60
64
  // Validate for every adapter, including capability markers and SQL shape.
61
65
  compile(submission)
62
66
  await store.run(submission)
63
- return plan.result
67
+ committed = plan.result
64
68
  } catch (error) {
65
69
  const winner = await replay()
66
70
  if (winner) return winner
67
71
  if (error instanceof RuleFailed && conflict) throw new RuleFailed(error.rule, conflict)
68
72
  throw error
69
73
  }
74
+ // The commit is final: post-commit failures must never enter rollback/replay
75
+ // handling, and idempotent replays must never repeat external effects.
76
+ if (postCommit) {
77
+ try { return await postCommit(prepared, committed) }
78
+ catch {
79
+ // Exceptions may contain credentials or provider payloads.
80
+ console.error(JSON.stringify({ event: 'post_commit_failed', operationId: runId }))
81
+ }
82
+ }
83
+ return committed
70
84
  }
@@ -12,7 +12,7 @@ import { assertUnprotectedFields, userLinkWriter, userLinkPolicyFilter } from '.
12
12
  export type WriteGuard = PolicyWriteGuard
13
13
  export const writeGuard = (statement: GuardedStatement) => Object.hasOwn(statement, 'policyGuard') ? statement.policyGuard : undefined
14
14
  /** Same structured predicate semantics as query table sources, including scoped EXISTS. */
15
- export function writeFilter(kernel: KernelRegistry, scope: Scope, entity: string, alias = entity): SqlStatement {
15
+ export function writeFilter(kernel: KernelRegistry, scope: Scope, entity: string, alias = entity, operation: import('../config').Operation = 'read', rootFilter?: TableFilter): SqlStatement {
16
16
  const bindings: SqlValue[] = []; let references = 0
17
17
  const bind = (value: string | number | boolean) => { bindings.push(typeof value === 'boolean' ? Number(value) : value); return '?' }
18
18
  function render(filter: TableFilter, table: string): string {
@@ -21,7 +21,8 @@ export function writeFilter(kernel: KernelRegistry, scope: Scope, entity: string
21
21
  }
22
22
  function relation(node: PredicateRelation, parent: string, negated: boolean): string {
23
23
  const child = `write_policy_${references}`
24
- const explicit = render({ kind: 'where', predicate: node.predicate }, child)
24
+ let explicit = render({ kind: 'where', predicate: node.predicate }, child)
25
+ if (kernel.config.effectiveAccess) { explicit = `${explicit} AND ${quote(child)}.organization_id=?`; bindings.push(scope.organizationId) }
25
26
  // Put policy expressions inside the derived source, as the read compiler does.
26
27
  // SQLite's expression-depth cap then does not accumulate the complete target
27
28
  // policy tree at every correlation along a four-relation path.
@@ -29,9 +30,15 @@ export function writeFilter(kernel: KernelRegistry, scope: Scope, entity: string
29
30
  return `${negated ? 'NOT ' : ''}EXISTS(SELECT 1 FROM (SELECT ${quote(child)}.${quote(node.field)} AS ${quote('policy_key')} FROM ${quote(node.entity)} AS ${quote(child)} WHERE ${explicit}) AS ${quote(visible)} WHERE ${quote(visible)}.${quote('policy_key')}=${quote(parent)}.${quote(node.parentField)})`
30
31
  }
31
32
  let filter: TableFilter
32
- try { filter = expandPolicyFilter(entity, child => kernel.tableFilter(child, scope), 128) }
33
+ let root = true
34
+ try { filter = expandPolicyFilter(entity, child => {
35
+ const selected = root && rootFilter ? rootFilter : kernel.tableFilter(child, scope, operation)
36
+ root = false
37
+ return selected
38
+ }, 128) }
33
39
  catch { throw new ApiError(403, 'policy_violation') }
34
- const sql = render(filter, alias)
40
+ let sql = render(filter, alias)
41
+ if (kernel.config.effectiveAccess) { sql = `(${sql}) AND ${quote(alias)}.organization_id=?`; bindings.push(scope.organizationId) }
35
42
  if (bindings.length > 100 || sql.length > 64_000) throw new ApiError(403, 'policy_violation')
36
43
  return { sql, bindings }
37
44
  }
@@ -116,13 +123,14 @@ export function enforcePlan(kernel: KernelRegistry, scope: Scope, plan: AtomicPl
116
123
  // Existing system writers retain their narrowly authorized paths.
117
124
  if (!domain && !member) return original
118
125
  const liveFilter = userLinkPolicyFilter(original)
119
- if (!liveFilter && domain && kernel.tableFilter(entity, scope).kind === 'none') throw new ApiError(403, 'policy_violation')
126
+ const authoredOperation = operation!.toLowerCase() === 'insert' ? 'create' : operation!.toLowerCase() as 'update' | 'delete'
127
+ if (!liveFilter && domain && kernel.tableFilter(entity, scope, authoredOperation).kind === 'none') throw new ApiError(403, 'policy_violation')
120
128
  const protect = account || member
121
129
  if (!domain && !protect) return original
122
130
  if (ts.some((token, i) => token.text === '?' && ts[i + 1]?.start === token.end && /^\d/.test(ts[i + 1].text)) || ts.some(token => [':', '@', '$'].includes(token.text))) throw new UnsupportedAtomicOperation('Policy SQL uses plain positional bindings')
123
131
  const bindings = original.bindings ?? []
124
132
  const statement = { ...original }
125
- const guard: WriteGuard = { entity, operation: operation!, requireRow: original.expectRows !== undefined, filter: liveFilter ?? (domain ? writeFilter(kernel, scope, entity) : { sql: `${quote(entity)}.${quote('organization_id')}=?`, bindings: [scope.organizationId] }) }
133
+ const guard: WriteGuard = { entity, operation: operation!, requireRow: original.expectRows !== undefined, filter: liveFilter ?? (domain ? writeFilter(kernel, scope, entity, entity, authoredOperation) : { sql: `${quote(entity)}.${quote('organization_id')}=?`, bindings: [scope.organizationId] }) }
126
134
  if (operation === 'UPDATE' || operation === 'DELETE') {
127
135
  const where = top.find(t => t.text.toUpperCase() === 'WHERE')
128
136
  const set = top.find(t => t.text.toUpperCase() === 'SET')
@@ -21,13 +21,13 @@ export function receiptExpression(config: InstanceConfig, rules: readonly Atomic
21
21
  const guard = writeGuard(statement); const prefix = `policy_${guard ? index++ : -1}:`
22
22
  if (!guard || !config.entities[guard.entity] || guard.operation === 'DELETE') continue
23
23
  if (guard.where) {
24
- parts.push('SELECT ? AS entity,substr(rule,?) AS id FROM atomic_assert WHERE run_id=? AND substr(rule,1,?)=?')
25
- bindings.push(guard.entity, prefix.length + 1, runId, prefix.length, prefix)
24
+ parts.push(`SELECT ? AS entity,${config.effectiveAccess ? '? AS operation,' : ''}substr(rule,?) AS id FROM atomic_assert WHERE run_id=? AND substr(rule,1,?)=?`)
25
+ bindings.push(guard.entity, ...(config.effectiveAccess ? [guard.operation === 'INSERT' ? 'create' : 'update'] : []), prefix.length + 1, runId, prefix.length, prefix)
26
26
  } else {
27
- parts.push('SELECT ? AS entity,? AS id'); bindings.push(guard.entity, guard.id!)
27
+ parts.push(`SELECT ? AS entity,${config.effectiveAccess ? '? AS operation,' : ''}? AS id`); bindings.push(guard.entity, ...(config.effectiveAccess ? ['create'] : []), guard.id!)
28
28
  }
29
29
  }
30
- const rows = parts.length ? `(SELECT json_group_array(json_object('entity',entity,'id',id)) FROM (${parts.join(' UNION ALL ')}))` : "'[]'"
30
+ const rows = parts.length ? `(SELECT json_group_array(json_object('entity',entity,'id',id${config.effectiveAccess ? " ,'operation',operation" : ''})) FROM (${parts.join(' UNION ALL ')}))` : "'[]'"
31
31
  return { sql: `json_set(?, '$.__workbase_policy', json_object('actor',?, 'rows',json(${rows})))`, bindings }
32
32
  }
33
33
  export async function authorizeReplay(kernel: KernelRegistry, scope: Scope, reader: AtomicReader, serialized: string, identity?: string): Promise<AtomicResult> {
@@ -44,7 +44,8 @@ export async function authorizeReceiptRows(kernel: KernelRegistry, scope: Scope,
44
44
  for (const row of rows) {
45
45
  if (!row || !Object.hasOwn(kernel.config.entities, row.entity) || typeof row.id !== 'string') throw new ApiError(403, 'policy_violation')
46
46
  if (read && !kernel.can(scope, row.entity, 'read')) throw new ApiError(403, 'policy_violation')
47
- const filter = writeFilter(kernel, scope, row.entity)
47
+ if (kernel.config.effectiveAccess && !read && !['create', 'update'].includes(row.operation)) throw new ApiError(403, 'policy_violation')
48
+ const filter = writeFilter(kernel, scope, row.entity, row.entity, read ? 'read' : row.operation ?? 'read')
48
49
  const visible = await reader.first<{ ok: number }>({ sql: `SELECT EXISTS(SELECT 1 FROM ${quote(row.entity)} WHERE id=? AND (${filter.sql})) AS ok`, bindings: [row.id, ...(filter.bindings ?? [])] })
49
50
  if (!visible?.ok) throw new ApiError(403, 'policy_violation')
50
51
  }
@@ -0,0 +1,11 @@
1
+ import type { AtomicOperation, AtomicResult } from './types'
2
+
3
+ // Internal lifecycle seam: callbacks are registered by core, outside declarative
4
+ // plans. Prepared credentials never enter config, receipts or serialized plans.
5
+ type PostCommit = (prepared: any, result: AtomicResult) => Promise<AtomicResult>
6
+ const callbacks = new WeakMap<AtomicOperation, PostCommit>()
7
+ export function registerPostCommit<T extends AtomicOperation<any>>(operation: T, callback: (prepared: Awaited<ReturnType<NonNullable<T['prepare']>>>, result: AtomicResult) => Promise<AtomicResult>): T {
8
+ callbacks.set(operation, callback)
9
+ return operation
10
+ }
11
+ export const postCommitFor = (operation: AtomicOperation) => callbacks.get(operation)
@@ -66,7 +66,7 @@ export interface AtomicOperation<Schema extends z.ZodType = z.ZodType, Prepared
66
66
  name: string
67
67
  /** Public presentation only; never grants authority or changes execution. */
68
68
  ui?: { placement?: { entity: string; action: 'create' }; labelKey?: string; label?: string | { en: string; cs: string }; replacesCrud?: 'create' | 'update' | 'delete' }
69
- permission: { entity: string; operation: Operation } | { system: OrganizationAction | 'organizations.create' | 'members.leave' | 'invitations.accept' | 'identity.write' }
69
+ permission: { entity: string; operation: Operation } | { system: OrganizationAction | 'organizations.create' | 'organizations.provision' | 'members.bootstrap' | 'members.leave' | 'invitations.accept' | 'identity.write' }
70
70
  additionalPermissions?: readonly { entity: string; operation: Operation }[]
71
71
  input: Schema
72
72
  idempotency?: 'required' | 'optional'