@workbasehq/core 0.0.0 → 0.1.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 (102) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/package.json +62 -1
  4. package/src/account-provisioning.ts +24 -0
  5. package/src/admin-forms.tsx +70 -0
  6. package/src/admin-security.ts +63 -0
  7. package/src/admin-ui.tsx +438 -0
  8. package/src/app.ts +115 -0
  9. package/src/audit-event.ts +23 -0
  10. package/src/audit.ts +35 -0
  11. package/src/authorization-api.ts +3 -0
  12. package/src/authorization.ts +135 -0
  13. package/src/authorized-execution.ts +15 -0
  14. package/src/bootstrap.ts +23 -0
  15. package/src/browser-dispatch.ts +19 -0
  16. package/src/calendar-display.ts +26 -0
  17. package/src/capabilities.ts +41 -0
  18. package/src/commands.ts +46 -0
  19. package/src/config-proposal-contract.ts +16 -0
  20. package/src/config-proposals.ts +95 -0
  21. package/src/config-shorthand.ts +200 -0
  22. package/src/config.ts +286 -0
  23. package/src/console-contract.ts +105 -0
  24. package/src/console-contribution.ts +7 -0
  25. package/src/console.ts +84 -0
  26. package/src/crud.ts +146 -0
  27. package/src/crypto.ts +33 -0
  28. package/src/detail-display.ts +59 -0
  29. package/src/detail-layout.ts +17 -0
  30. package/src/errors.ts +3 -0
  31. package/src/event-delivery.ts +76 -0
  32. package/src/events.ts +11 -0
  33. package/src/execution/atomic.ts +70 -0
  34. package/src/execution/compiler.ts +55 -0
  35. package/src/execution/context.ts +100 -0
  36. package/src/execution/d1.ts +46 -0
  37. package/src/execution/errors.ts +21 -0
  38. package/src/execution/index.ts +6 -0
  39. package/src/execution/outbox.ts +8 -0
  40. package/src/execution/permissions.ts +9 -0
  41. package/src/execution/policies.ts +156 -0
  42. package/src/execution/policy-receipts.ts +51 -0
  43. package/src/execution/types.ts +74 -0
  44. package/src/execution/workflow.ts +35 -0
  45. package/src/form-display.ts +36 -0
  46. package/src/idempotency.ts +10 -0
  47. package/src/identity-providers.ts +2 -0
  48. package/src/identity-settings.ts +42 -0
  49. package/src/identity-writes.ts +14 -0
  50. package/src/identity.ts +2 -0
  51. package/src/index.ts +32 -0
  52. package/src/json-csrf.ts +22 -0
  53. package/src/kernel/adapters/tenancy.ts +8 -0
  54. package/src/kernel/audit-port.ts +12 -0
  55. package/src/kernel/builtin-source.ts +34 -0
  56. package/src/kernel/composition.ts +77 -0
  57. package/src/kernel/identity-port.ts +36 -0
  58. package/src/kernel/mail-outbox-port.ts +23 -0
  59. package/src/kernel/migrations.ts +76 -0
  60. package/src/kernel/operation-name.ts +8 -0
  61. package/src/kernel/plugin.ts +92 -0
  62. package/src/kernel/predicate.ts +69 -0
  63. package/src/kernel/registry.ts +198 -0
  64. package/src/kernel/schema-check.ts +13 -0
  65. package/src/logging.ts +21 -0
  66. package/src/migrations/better-auth-schema.ts +2 -0
  67. package/src/migrations/email-delivery-schema.ts +6 -0
  68. package/src/migrations/planner.ts +77 -0
  69. package/src/migrations/schema.ts +85 -0
  70. package/src/migrations/version-contract.ts +28 -0
  71. package/src/migrations/versions.ts +90 -0
  72. package/src/ops-schema.ts +13 -0
  73. package/src/ops.ts +34 -0
  74. package/src/organization-permissions.ts +13 -0
  75. package/src/organization-rules.ts +25 -0
  76. package/src/organizations.ts +43 -0
  77. package/src/plugins.ts +3 -0
  78. package/src/policies.ts +186 -0
  79. package/src/public-schema.ts +65 -0
  80. package/src/query/compiler.ts +395 -0
  81. package/src/query/cursor.ts +43 -0
  82. package/src/query/enum-labels.json +16 -0
  83. package/src/query/enum-values.ts +7 -0
  84. package/src/query/errors.ts +10 -0
  85. package/src/query/executor.ts +118 -0
  86. package/src/query/facade.ts +34 -0
  87. package/src/query/labels.ts +105 -0
  88. package/src/query/limits.ts +8 -0
  89. package/src/query/observability.ts +49 -0
  90. package/src/query/routes.ts +60 -0
  91. package/src/query/schema.ts +216 -0
  92. package/src/query/search.ts +15 -0
  93. package/src/relay.ts +65 -0
  94. package/src/request-timing.ts +71 -0
  95. package/src/schema-compatibility.ts +43 -0
  96. package/src/scope-operations.ts +3 -0
  97. package/src/session-contract.ts +1 -0
  98. package/src/types.ts +30 -0
  99. package/src/worker-fetch.ts +14 -0
  100. package/src/workflow-routes.ts +156 -0
  101. package/src/workflow-runtime.ts +327 -0
  102. package/src/workflow-schema.ts +29 -0
package/src/audit.ts ADDED
@@ -0,0 +1,35 @@
1
+ import type { RuntimeEnv } from './types'
2
+ import { ApiError } from './errors'
3
+ import { equalHash } from './crypto'
4
+ import type { AuditEvent } from './audit-event'
5
+
6
+ /** Resolve page actors once, within the audit reader's organization. Never use email. */
7
+ export async function auditActorLabels(db: D1Database, organizationId: string, events: AuditEvent[]) {
8
+ const ids = [...new Set(events.filter(event => event.actor?.type === 'user').map(event => event.actor.id))]
9
+ if (!ids.length) return events
10
+ const rows = await db.prepare(`SELECT m.user_id,u.name,p.first_name,p.last_name
11
+ FROM memberships m JOIN "user" u ON u.id=m.user_id
12
+ LEFT JOIN identity_profiles p ON p.user_id=u.id AND (
13
+ NOT EXISTS (SELECT 1 FROM identities i WHERE i.user_id=u.id AND i.provider<>'local')
14
+ OR (p.synced_at IS NOT NULL
15
+ AND (SELECT count(*) FROM identities i WHERE i.user_id=u.id AND i.provider<>'local')=1
16
+ AND EXISTS (SELECT 1 FROM identities i WHERE i.user_id=u.id AND i.provider=p.source_provider AND i.issuer=p.source_issuer AND i.subject=p.source_subject)))
17
+ WHERE m.organization_id=? AND m.user_id IN (SELECT value FROM json_each(?))`)
18
+ .bind(organizationId, JSON.stringify(ids)).all<{ user_id: string; name: string | null; first_name: string | null; last_name: string | null }>()
19
+ const safeName = (name: string) => name && !/[A-Z0-9._%+-]+@[A-Z0-9.-]+/i.test(name)
20
+ const labels = new Map(rows.results.map(row => {
21
+ const fullName = [row.first_name?.trim(), row.last_name?.trim()].filter(Boolean).join(' ')
22
+ const displayName = row.name?.trim() ?? ''
23
+ return [row.user_id, safeName(fullName) ? fullName : safeName(displayName) ? displayName : row.user_id]
24
+ }))
25
+ return events.map(event => event.actor?.type === 'user'
26
+ ? { ...event, actor: { ...event.actor, label: labels.get(event.actor.id) ?? event.actor.id } } : event)
27
+ }
28
+ export function requireInternal(env: RuntimeEnv, token: string | undefined) {
29
+ if (!env.INTERNAL_TOKEN) throw new ApiError(503, 'internal_token_not_configured')
30
+ if (!token || !equalHash(env.INTERNAL_TOKEN, token)) throw new ApiError(403, 'internal_token_required')
31
+ }
32
+ export async function outboxStats(db: D1Database, now = Date.now()) {
33
+ const row = await db.prepare('SELECT count(*) AS backlog,min(created_at) AS oldest FROM audit_outbox WHERE delivered_at IS NULL').first<{ backlog: number; oldest: string | null }>()
34
+ return { backlog: row!.backlog, oldest_undelivered_age_seconds: row!.oldest ? Math.max(0, Math.floor((now - Date.parse(row!.oldest)) / 1000)) : null }
35
+ }
@@ -0,0 +1,3 @@
1
+ // Public authorization surface. Account-scope construction stays inside core.
2
+ export { resolveActor, requireScope, authorizeOperation, scopeMiddleware } from './authorization'
3
+ export type { AvailableOrganization, ResolvedActor } from './authorization'
@@ -0,0 +1,135 @@
1
+ import { loadActorProjection, type ActorMembership } from './policies'
2
+ import { scopeOperations } from './scope-operations'
3
+ import { kernelFor, type KernelRegistry } from './kernel/registry'
4
+ import type { MiddlewareHandler } from 'hono'
5
+ import type { InstanceConfig } from './config'
6
+ import { ulid } from './crypto'
7
+ import { ApiError } from './errors'
8
+ import type { Actor, AppEnv, RuntimeEnv, Scope } from './types'
9
+ import { timed, databaseIdentity } from './request-timing'
10
+
11
+ /** Compatibility helper bound to the installed login providers. */
12
+ export async function resolveActor(request: Request, env: RuntimeEnv, config?: InstanceConfig): Promise<ResolvedActor> {
13
+ if (!config) throw new Error('A bound instance config is required to resolve an actor')
14
+ return kernelFor(config).requireActor(request, env)
15
+ }
16
+
17
+ export interface AvailableOrganization { id: string; name: string; role: string }
18
+ export interface ResolvedActor {
19
+ actor: Actor
20
+ user: { id: string; email: string; name?: string } | null
21
+ organizations: AvailableOrganization[]
22
+ }
23
+ /** Internal login proof: only a trusted adapter can construct one. The optional
24
+ * SQL predicate correlates the session to memberships alias m in the same read. */
25
+ export interface LoginSessionProof {
26
+ valid(): Promise<boolean>
27
+ verified(): Promise<boolean>
28
+ recipientVerification: 'local-profile' | 'provider'
29
+ membershipCondition?(now: string): { sql: string; bindings: unknown[] }
30
+ }
31
+ interface Verification { env: RuntimeEnv; hash: string; session?: LoginSessionProof }
32
+ /** Internal provider seam. Proof is retained privately and rechecked on every scoped use. */
33
+ export function sealActor(result: ResolvedActor, verification: Verification): ResolvedActor {
34
+ Object.freeze(result.actor)
35
+ if (result.user) Object.freeze(result.user)
36
+ result.organizations.forEach(Object.freeze)
37
+ Object.freeze(result.organizations)
38
+ Object.freeze(result)
39
+ verified.set(result, verification)
40
+ return result
41
+ }
42
+ // Runtime provenance prevents a JSON object or client-supplied identity from becoming an authority.
43
+ const verified = new WeakMap<ResolvedActor, Verification>()
44
+ interface TokenRow { id: string; organization_id: string; role: string; operations: string | null; name: string }
45
+ const tokenQuery = `SELECT t.id,t.organization_id,t.role,t.operations,o.name FROM access_tokens t JOIN organizations o ON o.id=t.organization_id WHERE t.token_hash=? AND t.revoked_at IS NULL AND t.expires_at>?`
46
+ /** Client-supplied identity/org is a selector, never an authority. Call for each execution; do not cache scopes. */
47
+ export async function requireScope(actor: ResolvedActor, organizationId: string, config?: InstanceConfig, correlationId = ulid(), operation?: string): Promise<Scope> {
48
+ const verification = verified.get(actor)
49
+ if (!verification) throw new ApiError(401, 'unverified_actor')
50
+ const { env, hash } = verification
51
+ const now = new Date().toISOString()
52
+ if (config) organizationId = await kernelFor(config).resolveScopeId(env.DB, organizationId)
53
+ if (!organizationId) throw new ApiError(403, 'organization_required')
54
+ let role: string; let operations: string[] | null = null
55
+ let membership: ActorMembership | undefined
56
+ if (actor.actor.type === 'agent') {
57
+ const token = await env.DB.prepare(tokenQuery).bind(hash, now).first<TokenRow>()
58
+ if (!token) throw new ApiError(401, 'unauthenticated')
59
+ if (token.organization_id !== organizationId) throw new ApiError(403, 'organization_forbidden')
60
+ role = token.role; operations = token.operations === null ? null : JSON.parse(token.operations)
61
+ const used = await env.DB.batch([env.DB.prepare('UPDATE access_tokens SET last_used_at=? WHERE id=? AND revoked_at IS NULL AND expires_at>?').bind(now, token.id, now)])
62
+ if (used[0].meta.changes !== 1) throw new ApiError(401, 'unauthenticated')
63
+ } else {
64
+ const proof = verification.session
65
+ if (!proof) throw new ApiError(401, 'unauthenticated')
66
+ if (!proof.membershipCondition && !await proof.valid()) throw new ApiError(401, 'unauthenticated')
67
+ const condition = proof.membershipCondition?.(now) ?? { sql: '1=1', bindings: [] }
68
+ const member = await env.DB.prepare(`SELECT m.user_id,m.organization_id,m.role FROM memberships m
69
+ WHERE m.user_id=? AND m.organization_id=? AND (${condition.sql})`).bind(actor.actor.id, organizationId, ...condition.bindings).first<ActorMembership>()
70
+ if (!member) throw new ApiError(403, 'organization_forbidden')
71
+ role = member.role
72
+ membership = member
73
+ }
74
+ const scope: Scope = { organizationId, actor: { ...actor.actor }, role, correlationId }
75
+ if (config) await loadActorProjection(config, scope, (sql, bindings) => env.DB.prepare(sql).bind(...bindings).first(), membership)
76
+ Object.freeze(scope.actor)
77
+ Object.freeze(scope)
78
+ scopeOperations.set(scope, { operations })
79
+ if (operation) authorizeOperation(scope, operation)
80
+ return scope
81
+ }
82
+ /** Check the actual operation on every path. A requireScope bound operation is only
83
+ * an additional preflight; it must never substitute for the operation being executed. */
84
+ export function authorizeOperation(scope: Scope, operation: string) {
85
+ const restriction = scopeOperations.get(scope)
86
+ if (!restriction) throw new ApiError(403, 'unverified_scope')
87
+ if (restriction.operations && !restriction.operations.includes(operation)) throw new ApiError(403, 'operation_forbidden')
88
+ }
89
+ export function scopeMiddleware(env: RuntimeEnv, config?: InstanceConfig, kernel?: KernelRegistry): MiddlewareHandler<AppEnv> {
90
+ kernel ??= config ? kernelFor(config) : undefined
91
+ if (!kernel) throw new Error('A bound kernel is required for scope middleware')
92
+ const selected = kernel
93
+ config = selected.config
94
+ return async (c, next) => {
95
+ const actor = await selected.requireActor(c.req.raw, env)
96
+ if (actor.user) c.set('userId', actor.user.id)
97
+ const org = c.req.param('org') ?? c.req.header('X-Organization-Id') ?? ''
98
+ // A command allowlist contains exact registered names. CRUD uses entity.read/create/update/delete.
99
+ const operation = c.req.path.startsWith('/commands/') ? c.req.path.slice('/commands/'.length) : undefined
100
+ c.set('scope', { organizationId: org, actor: actor.actor, role: '', correlationId: c.get('correlationId') })
101
+ const scope = await timed('scope', () => requireScope(actor, org, config, c.get('correlationId'), operation))
102
+ c.set('resolvedActor', actor)
103
+ c.set('scope', scope)
104
+ if (scope.actor.type === 'agent' && c.req.path.startsWith('/audit/')) authorizeOperation(scope, 'audit.read')
105
+ await timed('handler', next)
106
+ }
107
+ }
108
+
109
+ /** Core-only account scope: creation/acceptance precede membership. Never accept a
110
+ * client role here; callers supply the new owner role or the stored invitation role.
111
+ */
112
+ export async function accountScope(actor: ResolvedActor, organizationId: string, role: string, correlationId: string): Promise<Scope> {
113
+ const verification = verified.get(actor)
114
+ if (!verification) throw new ApiError(401, 'unverified_actor')
115
+ if (!actor.user) throw new ApiError(403, 'user_required')
116
+ if (!await verification.session?.valid()) throw new ApiError(401, 'unauthenticated')
117
+ const scope: Scope = Object.freeze({ organizationId, actor: actor.actor, role, correlationId })
118
+ scopeOperations.set(scope, { operations: null })
119
+ return scope
120
+ }
121
+
122
+ export async function requireVerifiedSession(actor: ResolvedActor, db?: D1Database) {
123
+ const verification = verified.get(actor)
124
+ if (!verification || !actor.user || (db && databaseIdentity(verification.env.DB) !== databaseIdentity(db))) throw new ApiError(403, 'verified_session_required')
125
+ const proof = verification.session
126
+ if (!proof || !await proof.verified()) throw new ApiError(403, 'verified_session_required')
127
+ return proof.recipientVerification === 'provider'
128
+ }
129
+
130
+ /** Informational copy only; never an authorization context or capability. */
131
+ export function allowedOperations(scope: Scope): string[] | null {
132
+ const restriction = scopeOperations.get(scope)
133
+ if (!restriction) throw new ApiError(403, 'unverified_scope')
134
+ return restriction.operations ? [...restriction.operations] : null
135
+ }
@@ -0,0 +1,15 @@
1
+ import { kernelFor } from './kernel/registry'
2
+ import type { InstanceConfig } from './config'
3
+ import type { RuntimeEnv } from './types'
4
+ import { requireScope } from './authorization'
5
+ import { executeCommand, type CommandRegistry } from './commands'
6
+ /** Entry point for MCP/internal adapters. Identity/org inputs are selectors, never authority.
7
+ * Resolve on EVERY execution, including replay; never retain a previous scope or client role.
8
+ * executeCommand is the lower-level trusted pipeline; adapters must use this boundary.
9
+ */
10
+ export async function executeAuthorized(request: Request, env: RuntimeEnv, config: InstanceConfig, commands: CommandRegistry, organizationId: string, name: string, input: unknown) {
11
+ const actor = await kernelFor(config).requireActor(request, env)
12
+ const correlation = request.headers.get('X-Correlation-Id')
13
+ const scope = await requireScope(actor, organizationId, config, correlation && /^[a-zA-Z0-9_-]{1,100}$/.test(correlation) ? correlation : undefined, name)
14
+ return executeCommand({ env, config, commands, scope }, name, input)
15
+ }
@@ -0,0 +1,23 @@
1
+ import type { App, RuntimeEnv, RuntimeOptions } from './types'
2
+ import type { KernelRegistry } from './kernel/registry'
3
+ import { capabilities } from './capabilities'
4
+ import { publicSchema } from './public-schema'
5
+ import { meDocument } from './organizations'
6
+ import { scopeMiddleware } from './authorization'
7
+ import { buildInfo } from './console'
8
+
9
+ /** Session-local QueryClient caching only: never share actor/org projections in HTTP caches. */
10
+ export function bootstrapRoutes(app: App, kernel: KernelRegistry, env: RuntimeEnv, options: RuntimeOptions) {
11
+ app.get('/o/:org/bootstrap', scopeMiddleware(env, kernel.config, kernel), async c => c.json({
12
+ schema: publicSchema(kernel.config, options),
13
+ capabilities: capabilities(kernel, c.get('scope')),
14
+ console: kernel.providers.get('console')?.[0]?.consoleRegistry?.(kernel.config, c.get('scope')),
15
+ me: meDocument(c.get('resolvedActor'), kernel.config),
16
+ build: await buildInfo(kernel.config, env, c.req.url),
17
+ }, 200, { 'Cache-Control': 'private, no-store', Vary: 'Cookie, Authorization, X-Organization-Id' }))
18
+ app.get('/bootstrap', async c => c.json({
19
+ schema: publicSchema(kernel.config, options),
20
+ me: meDocument(await kernel.requireActor(c.req.raw, env), kernel.config),
21
+ build: await buildInfo(kernel.config, env, c.req.url),
22
+ }, 200, { 'Cache-Control': 'private, no-store', Vary: 'Cookie, Authorization' }))
23
+ }
@@ -0,0 +1,19 @@
1
+ import type { App, RuntimeEnv } from './types'
2
+ /** A private adapter object, never a network header or alternate public entry point.
3
+ * The frozen admin's internal JSON calls occur after adminForm validates its HMAC/provenance.
4
+ * Keep native form compatibility while requiring full provenance at the JSON boundary.
5
+ */
6
+ export function validatedBrowserDispatch(app: App, env: RuntimeEnv): App {
7
+ const adapter = Object.create(app) as App
8
+ adapter.fetch = (request, ...args) => {
9
+ if (!['GET', 'HEAD', 'OPTIONS'].includes(request.method)) {
10
+ const headers = new Headers(request.headers)
11
+ headers.set('Origin', env.IDENTITY?.baseURL ?? env.AUTH_BASE_URL ?? new URL(request.url).origin)
12
+ headers.set('Sec-Fetch-Site', 'same-origin')
13
+ headers.set('Content-Type', 'application/json')
14
+ request = new Request(request, { headers })
15
+ }
16
+ return app.fetch(request, ...args)
17
+ }
18
+ return adapter
19
+ }
@@ -0,0 +1,26 @@
1
+ import { z } from 'zod'
2
+ import type { InstanceConfig } from './config'
3
+
4
+ const identifier = z.string().regex(/^[a-z][a-z0-9_]*$/)
5
+ /** Alternative entity list presentations; filter presets remain list.views. */
6
+ export const calendarViewsSchema = z.array(z.strictObject({
7
+ kind: z.literal('calendar'), startField: identifier,
8
+ endField: identifier.optional(), titleField: identifier.optional(),
9
+ titleFields: z.array(identifier).min(1).max(4).refine(fields => new Set(fields).size === fields.length).optional(),
10
+ secondaryField: identifier.optional(),
11
+ })).max(1)
12
+ export type CalendarView = z.infer<typeof calendarViewsSchema>[number]
13
+ export function validateCalendarViews(config: InstanceConfig, entity: string, input: unknown) {
14
+ if (input === undefined) return
15
+ for (const view of calendarViewsSchema.parse(input)) {
16
+ const definition = config.entities[entity]
17
+ for (const field of [view.startField, view.endField].filter((field): field is string => !!field)) {
18
+ if (definition.fields[field]?.type !== 'datetime' && !['created_at', 'updated_at'].includes(field)) throw new Error(`Invalid calendar date field: ${entity}.${field}`)
19
+ }
20
+ if (view.titleField && (!definition.fields[view.titleField] || definition.fields[view.titleField].type === 'ref')) throw new Error(`Invalid calendar title field: ${entity}.${view.titleField}`)
21
+ if (view.titleField && view.titleFields) throw new Error(`Conflicting calendar title declarations: ${entity}`)
22
+ for (const field of view.titleFields ?? []) if (!definition.fields[field]) throw new Error(`Invalid calendar title field: ${entity}.${field}`)
23
+ if (view.secondaryField && (!definition.fields[view.secondaryField] || ['ref', 'json'].includes(definition.fields[view.secondaryField].type))) throw new Error(`Invalid calendar secondary field: ${entity}.${view.secondaryField}`)
24
+ if (view.endField === view.startField) throw new Error(`Duplicate calendar date field: ${entity}.${view.startField}`)
25
+ }
26
+ }
@@ -0,0 +1,41 @@
1
+ import type { KernelRegistry } from './kernel/registry'
2
+ import type { App, RuntimeEnv, Scope } from './types'
3
+ import { scopeMiddleware } from './authorization'
4
+ import { ApiError } from './errors'
5
+ import { writableFields } from './policies'
6
+ import { hasOwnerRole } from './policies'
7
+ import { organizationPermission } from './execution/permissions'
8
+
9
+ /** Projection of the live authorization ports; never serialize their predicates. */
10
+ export function capabilities(kernel: KernelRegistry, scope: Scope) {
11
+ function permits(check: () => void) {
12
+ try { check(); return true } catch (error) { if (error instanceof ApiError && [403, 405].includes(error.status)) return false; throw error }
13
+ }
14
+ const entities = Object.fromEntries(Object.entries(kernel.config.entities).map(([name, entity]) => [name, {
15
+ readable: kernel.fieldMask(name, scope), writable: writableFields(kernel.config, name, scope),
16
+ operations: (['read', 'create', 'update', 'delete'] as const).filter(operation => (operation === 'read' || !entity.commandsOnly) && kernel.tableFilter(name, scope).kind !== 'none' && kernel.can(scope, name, operation)),
17
+ ...(entity.displayField && kernel.fieldMask(name, scope).includes(entity.displayField) ? { displayField: entity.displayField } : {}),
18
+ }]))
19
+ const commands = [...kernel.commands.values()].filter(command => kernel.config.commands.includes(command.name) && !('system' in command.permission) && permits(() => kernel.atomicPermission(scope, command))).map(command => command.name)
20
+ const workflows = Object.fromEntries([...kernel.workflows.values()].map(workflow => [workflow.name, [
21
+ ...(permits(() => { for (const step of workflow.steps ?? []) kernel.atomicPermission(scope, step.operation) }) ? ['start' as const] : []),
22
+ ...(['cancel', 'resume'] as const).filter(action => permits(() => kernel.resourcePermission(scope, `workflows.${action}`))),
23
+ ]]))
24
+ // Match the read routes' complete gates, including their identity/owner checks.
25
+ // Navigation needs grants, not whole member/token/workflow/audit collections.
26
+ const resources = {
27
+ 'organizations.update': kernel.providers.has('organizations') && kernel.permissionsActive && permits(() => kernel.resourcePermission(scope, 'organizations.update')),
28
+ ...Object.fromEntries((['members.read', 'members.update', 'members.remove', 'invitations.read', 'invitations.create', 'invitations.revoke', 'tokens.read'] as const).map(action => [action,
29
+ permits(() => { kernel.resourcePermission(scope, action); organizationPermission(kernel.config, scope, action) }),
30
+ ])),
31
+ ...Object.fromEntries((['tokens.create', 'tokens.revoke'] as const).map(action => [action,
32
+ permits(() => { kernel.resourcePermission(scope, action); organizationPermission(kernel.config, scope, action) }),
33
+ ])),
34
+ 'workflows.read': permits(() => kernel.resourcePermission(scope, 'workflows.read')),
35
+ 'audit.read': !!kernel.audit && hasOwnerRole(scope) && permits(() => kernel.resourcePermission(scope, 'audit.read')),
36
+ }
37
+ return { revision: kernel.config.revision, entities, commands, workflows, resources, organization: { role: scope.role } }
38
+ }
39
+ export function capabilityRoutes(app: App, kernel: KernelRegistry, env: RuntimeEnv) {
40
+ app.get('/o/:org/capabilities', scopeMiddleware(env, kernel.config, kernel), c => c.json(capabilities(kernel, c.get('scope'))))
41
+ }
@@ -0,0 +1,46 @@
1
+ import { z } from 'zod'
2
+ import type { InstanceConfig } from './config'
3
+ import type { App, RuntimeEnv, Scope } from './types'
4
+ import { ApiError } from './errors'
5
+ import { kernelFor } from './kernel/registry'
6
+ import { operationName } from './kernel/operation-name'
7
+ import { executeAtomic, defineAtomicOperation } from './execution/atomic'
8
+ import { coreExecutionContext } from './execution/context'
9
+ import { D1AtomicStore, D1AtomicReader } from './execution/d1'
10
+ import type { AtomicOperation, AtomicResult } from './execution/types'
11
+
12
+ /** Compatibility names for the existing registry and trusted direct dispatcher. */
13
+ export type CommandDefinition<S extends z.ZodType = z.ZodType> = AtomicOperation<S>
14
+ export type CommandRegistry = ReadonlyMap<string, CommandDefinition<any>>
15
+ export interface CommandContext { env: RuntimeEnv; config: InstanceConfig; scope: Scope; commands: CommandRegistry }
16
+ export const defineCommand = defineAtomicOperation
17
+ export function createCommandRegistry(definitions: readonly CommandDefinition<any>[]): CommandRegistry {
18
+ const registry = new Map<string, CommandDefinition<any>>()
19
+ for (const definition of definitions) {
20
+ if (registry.has(definition.name)) throw new Error(`Duplicate command: ${definition.name}`)
21
+ registry.set(definition.name, definition)
22
+ }
23
+ return registry
24
+ }
25
+ /** Internal/trusted adapter compatibility. Never accept this context from request JSON. */
26
+ export async function executeCommand(ctx: CommandContext, name: string, input: unknown): Promise<AtomicResult> {
27
+ const operation = ctx.commands.get(name)
28
+ if (!ctx.config.commands.includes(name) || !operation) throw new ApiError(405, 'unsupported_command')
29
+ if ('system' in operation.permission) throw new ApiError(405, 'unsupported_command')
30
+ // Entity grants preflight the named command; the token must allow that actual command,
31
+ // independently of any operation previously checked by requireScope.
32
+ for (const grant of [operation.permission, ...(operation.additionalPermissions ?? [])]) {
33
+ kernelFor(ctx.config).commandGuard({ name: operationName(operation), kind: 'entity', permission: grant }, ctx.scope, undefined)
34
+ }
35
+ const raw = z.record(z.string(), z.unknown()).parse(typeof input === 'function' ? await input() : input)
36
+ const { idempotencyKey, ...payload } = raw
37
+ const key = z.string().min(1).max(128).optional().parse(idempotencyKey)
38
+ const context = coreExecutionContext(ctx.config, ctx.scope, new D1AtomicStore(ctx.env.DB, { env: ctx.env, config: ctx.config }), new D1AtomicReader(ctx.env.DB), key)
39
+ return executeAtomic(operation, payload, context)
40
+ }
41
+ export function commandRoutes(app: App, config: InstanceConfig, env: RuntimeEnv, commands: CommandRegistry) {
42
+ app.post('/commands/*', async c => {
43
+ const response = await executeCommand({ config, env, commands, scope: c.get('scope') }, c.req.path.slice('/commands/'.length), () => c.req.json())
44
+ return c.json(response.body, response.status as any)
45
+ })
46
+ }
@@ -0,0 +1,16 @@
1
+ import type { ConfigChange } from './migrations/version-contract'
2
+ /** Browser-safe draft projection. No runtime config or provider credentials. */
3
+ export type ConfigPatch = (
4
+ | { kind: 'add_enum_filter'; entity: string; field: string; values: string[] }
5
+ | { kind: 'enable_calendar'; entity: string; startField: string }
6
+ | { kind: 'add_list_column'; entity: string; field: string }
7
+ )[]
8
+ export interface ConfigProposal {
9
+ proposalId: string
10
+ baseRevision: number
11
+ revision: number
12
+ patch: ConfigPatch
13
+ changes: ConfigChange[]
14
+ plan: { sql: string; destructive: string[]; blocked: string[]; warnings: string[] }
15
+ appliesToDatabase: false
16
+ }
@@ -0,0 +1,95 @@
1
+ import { z } from 'zod'
2
+ import { baseFields, cloneInstanceConfig, defineInstance, type InstanceConfig } from './config'
3
+ import { plan } from './migrations/planner'
4
+ import { diffVersions, versionData } from './migrations/versions'
5
+ import type { ConfigPatch } from './config-proposal-contract'
6
+ export type { ConfigPatch, ConfigProposal } from './config-proposal-contract'
7
+
8
+ const identifier = z.string().max(63).regex(/^[a-z][a-z0-9_]*$/).refine(value => !['__proto__', 'prototype', 'constructor'].includes(value))
9
+ /** Bounded additive operations; neither a model nor a browser supplies executable config. */
10
+ export const configPatchSchema = z.array(z.discriminatedUnion('kind', [
11
+ z.strictObject({ kind: z.literal('add_enum_filter'), entity: identifier, field: identifier, values: z.array(z.string().min(1).max(100)).min(1).max(30).refine(values => new Set(values).size === values.length) }),
12
+ z.strictObject({ kind: z.literal('enable_calendar'), entity: identifier, startField: identifier }),
13
+ z.strictObject({ kind: z.literal('add_list_column'), entity: identifier, field: identifier }),
14
+ ])).min(1).max(10)
15
+ export interface ConfigProposer { propose(prompt: string, config: InstanceConfig): Promise<ConfigPatch> }
16
+ export const promptSchema = z.string().trim().min(1).max(2000)
17
+ const refuse = (message: string): never => { throw new Error(message) }
18
+
19
+ export class RuleConfigProposer implements ConfigProposer {
20
+ async propose(raw: string, config: InstanceConfig): Promise<ConfigPatch> {
21
+ const prompt = promptSchema.parse(raw).toLowerCase()
22
+ if (/\b(delete|remove|drop|rename|replace|permission|role|sql|deploy)\b|sma[zž]|odstra[nň]/.test(prompt)) refuse('Only additive field, filter, calendar and list column changes are supported.')
23
+ const tokens: string[] = prompt.match(/[a-z][a-z0-9_]*/g) ?? []
24
+ const entities = Object.keys(config.entities)
25
+ const matches = entities.filter(entity => tokens.includes(entity) || tokens.includes(entity.replace(/s$/, '')))
26
+ const entity = matches.length === 1 ? matches[0] : entities.length === 1 && !matches.length ? entities[0] : refuse(`Name one entity: ${entities.join(', ')}`)
27
+ const fields = config.entities[entity].fields
28
+ if (/\bcalendar\b|kalend[aá][řr]/.test(prompt)) {
29
+ const dates = Object.keys(fields).filter(field => fields[field].type === 'datetime')
30
+ const explicitDate = prompt.match(/(?:using|field|pole)\s+([a-z][a-z0-9_]*)/)?.[1]
31
+ if (explicitDate && !dates.includes(explicitDate)) refuse(`Unknown datetime field: ${explicitDate}`)
32
+ const named = dates.filter(field => tokens.includes(field))
33
+ const startField = named.length === 1 ? named[0] : dates.length === 1 ? dates[0] : refuse(`Name one datetime field on ${entity}: ${dates.join(', ') || 'none'}`)
34
+ return [{ kind: 'enable_calendar', entity, startField }]
35
+ }
36
+ if (/\bcolumn\b|sloupec/.test(prompt)) {
37
+ const named = Object.keys(fields).filter(field => tokens.includes(field))
38
+ if (named.length !== 1) refuse('Name one existing field for the list column.')
39
+ return [{ kind: 'add_list_column', entity, field: named[0] }]
40
+ }
41
+ if (/\bfilter\b|filtr/.test(prompt) && /\b(field|enum|status)\b|pole/.test(prompt)) {
42
+ const field = prompt.match(/(?:add|přidej|pridej)\s+(?:an?\s+)?(?:enum\s+)?([a-z][a-z0-9_]*)\s+(?:enum\s+)?(?:field|pole)/)?.[1] ?? (/\bstatus\b/.test(prompt) ? 'status' : refuse('Name the enum field, for example: add status field with filter.'))
43
+ const valuesText = prompt.match(/(?:values|hodnoty)\s*[:=]?\s*([a-z0-9_, -]+)$/)?.[1]
44
+ const values = valuesText ? valuesText.split(',').map(value => value.trim()) : ['new', 'in_progress', 'done']
45
+ return configPatchSchema.parse([{ kind: 'add_enum_filter', entity, field, values }])
46
+ }
47
+ return refuse('Supported requests: add status field with filter to <entity>; enable calendar on <entity> using <date_field>; add <field> column to <entity>.')
48
+ }
49
+ }
50
+
51
+ /** Provider adapters receive a schema description and return JSON, never config source or SQL. */
52
+ export interface ConfigProposalProvider {
53
+ complete(input: { prompt: string; config: Record<string, unknown>; patchSchema: unknown }): Promise<unknown>
54
+ }
55
+ export class LlmConfigProposer implements ConfigProposer {
56
+ constructor(private provider: ConfigProposalProvider) {}
57
+ async propose(prompt: string, config: InstanceConfig): Promise<ConfigPatch> {
58
+ return configPatchSchema.parse(await this.provider.complete({ prompt: promptSchema.parse(prompt), config: versionData(config), patchSchema: z.toJSONSchema(configPatchSchema) }))
59
+ }
60
+ }
61
+
62
+ export function prepareConfigProposal(config: InstanceConfig, rawPatch: unknown) {
63
+ const patch = configPatchSchema.parse(rawPatch)
64
+ const next = cloneInstanceConfig(config)
65
+ for (const entity of Object.values(next.entities)) for (const field of Object.values(entity.fields)) delete field.renameFrom
66
+ for (const operation of patch) {
67
+ const entity = next.entities[operation.entity] ?? refuse(`Unknown entity: ${operation.entity}`)
68
+ next.ui ??= { entities: {} }
69
+ const display = next.ui.entities[operation.entity] ??= {}
70
+ const list = display.list ??= {}
71
+ if (operation.kind === 'add_enum_filter') {
72
+ if (Object.hasOwn(entity.fields, operation.field) || baseFields.includes(operation.field)) refuse(`Field already exists or is reserved: ${operation.field}`)
73
+ entity.fields[operation.field] = { type: 'enum', required: false, values: operation.values }
74
+ list.filter = { ...list.filter, [operation.field]: 'enum' }
75
+ // Header filters are available only for visible list columns.
76
+ if (list.columns) list.columns = [...list.columns, operation.field]
77
+ for (const form of Object.values(display.form ?? {})) form.fields = [...form.fields, operation.field]
78
+ } else if (operation.kind === 'enable_calendar') {
79
+ if (entity.fields[operation.startField]?.type !== 'datetime') refuse('Calendar requires an existing datetime field.')
80
+ if (display.views?.length) refuse('A calendar is already configured.')
81
+ display.views = [{ kind: 'calendar', startField: operation.startField }]
82
+ } else {
83
+ if (!Object.hasOwn(entity.fields, operation.field)) refuse(`Unknown field: ${operation.field}`)
84
+ // Without configured columns the list already includes visible schema fields.
85
+ const columns = list.columns ?? Object.keys(entity.fields).filter(field => !entity.fields[field].ui?.hidden)
86
+ if (columns.includes(operation.field)) refuse('The list already includes this column.')
87
+ list.columns = [...columns, operation.field]
88
+ }
89
+ }
90
+ next.revision++
91
+ const target = defineInstance(next)
92
+ const migration = plan(config, target)
93
+ if (migration.blocked.length || migration.destructive.length) refuse(`Plan refused: ${migration.blocked.join('; ')}`)
94
+ return { target, patch, plan: migration, changes: diffVersions(versionData(config), versionData(target)) }
95
+ }