@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
@@ -0,0 +1,438 @@
1
+ /** @jsxImportSource hono/jsx */
2
+ import { Q } from '@jakub.knejzlik/ts-query'
3
+ import { renderStatement } from './query/compiler'
4
+ import { kernelFor } from './kernel/registry'
5
+ import type { Child } from 'hono/jsx'
6
+ import { getCookie } from 'hono/cookie'
7
+ import { ZodError } from 'zod'
8
+ import { SESSION_COOKIE } from './session-contract'
9
+ import { requireScope } from './authorization'
10
+ import { type InstanceConfig, type OrganizationAction } from './config'
11
+ import type { App, AppContext, RuntimeEnv, Scope } from './types'
12
+ import type { CommandRegistry, CommandDefinition } from './commands'
13
+ import { ApiError } from './errors'
14
+ import { assertIdentityTransport } from './identity-settings'
15
+ import { adminForm, browserRequest, csrfToken, isLoopbackDev, submissionKey, verifySubmissionKey } from './admin-security'
16
+ import { CommandInput, FieldInput, Form, Hidden, commandBody, commandFields, entityBody } from './admin-forms'
17
+ import { organizationPermission } from './execution/permissions'
18
+ import { permission } from './crud'
19
+ import { createLogger } from './logging'
20
+ import { securityLog } from './events'
21
+ import { workflowReader } from './workflow-routes'
22
+ import type { WorkflowRegistry } from './workflow-runtime'
23
+
24
+ const workflowStatuses = ['needs_attention', 'pending', 'running', 'waiting_external', 'completed', 'failed', 'compensating', 'compensated', 'cancelled']
25
+ const workflowTime = (value: number | null) => value ? new Date(value).toISOString() : '—'
26
+
27
+ const CSP = "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'"
28
+ const css = `:root{font:16px system-ui,sans-serif;color:#172b3a;background:#f4f6f8}body{max-width:1100px;margin:auto;padding:1.5rem}a{color:#075a97}header,nav{display:flex;gap:1rem;flex-wrap:wrap;align-items:center}header{justify-content:space-between;border-bottom:1px solid #ccd4dc;padding-bottom:1rem}main{background:white;padding:1.5rem;margin-top:1rem;border:1px solid #d8dfe5;border-radius:.5rem}nav{margin-top:1rem}form{margin:1rem 0;padding:1rem;border:1px solid #d8dfe5;border-radius:.3rem}label{display:block;margin:.7rem 0}input,select,textarea,button{font:inherit;max-width:100%;box-sizing:border-box}input:not([type=hidden]),select,textarea{display:block;padding:.4rem;width:32rem}input[type=checkbox]{width:auto;display:inline}button{padding:.4rem .8rem;cursor:pointer}table{border-collapse:collapse;width:100%;display:block;overflow:auto}td,th{text-align:left;border-bottom:1px solid #d8dfe5;padding:.6rem;vertical-align:top}td form{margin:.2rem;padding:.4rem}td input,td select{width:auto}pre{white-space:pre-wrap;overflow-wrap:anywhere}code{overflow-wrap:anywhere}.error{color:#9b1c1c}small{color:#526272}`
29
+ const enc = encodeURIComponent
30
+ const roles = ['owner', 'dispatcher', 'viewer']
31
+ const roleInput = (current = 'viewer', ceiling = 'owner') => <label>Role<select name="role">{roles.filter(role => roles.indexOf(role) >= roles.indexOf(ceiling)).map(role => <option value={role} selected={role === current}>{role}</option>)}</select></label>
32
+ const human: Record<string, string> = {
33
+ csrf_failed: 'This form could not be verified. Reload the page and try again.',
34
+ permission_denied: 'Your role does not allow this action.', organization_forbidden: 'You do not have access to this organization.',
35
+ last_owner: 'An organization must keep at least one owner.', version_conflict: 'This record changed. Reload it before saving again.',
36
+ validation_error: 'Check the required fields and their formats.', internal_error: 'The request could not be completed.',
37
+ workflow_not_paused: 'Only a workflow run that needs attention can be resumed.', workflow_terminal: 'This workflow run has already finished.',
38
+ 'workflow.definition_mismatch': 'The saved workflow definition differs from this instance. Restore compatible code before continuing.',
39
+ owner_required: 'Only an organization owner can use this page.', commands_only: 'Use a command to change this entity.',
40
+ }
41
+ function errorInfo(error: unknown) {
42
+ if (error instanceof ApiError) return error
43
+ const message = error instanceof Error ? error.message : ''
44
+ const constraint = /SQLITE_CONSTRAINT|constraint failed/i.test(message)
45
+ return new ApiError(error instanceof ZodError || error instanceof SyntaxError || error instanceof URIError ? 400 : constraint ? 409 : 500,
46
+ error instanceof ZodError || error instanceof SyntaxError || error instanceof URIError ? 'validation_error' : constraint ? 'constraint_conflict' : 'internal_error')
47
+ }
48
+ function errorMessage(error: ApiError) {
49
+ return <p class="error" role="alert">{human[error.code] ?? `${error.code.replaceAll('_', ' ')}.`} <code>{error.code}</code></p>
50
+ }
51
+ function canOrganization(config: InstanceConfig, scope: Scope, action: OrganizationAction) {
52
+ try { kernelFor(config).resourcePermission(scope, action); organizationPermission(config, scope, action); return true } catch (error) { if (error instanceof ApiError) return false; throw error }
53
+ }
54
+ function canCommand(config: InstanceConfig, scope: Scope, command: CommandDefinition) {
55
+ if ('system' in command.permission) return false
56
+ return [command.permission, ...(command.additionalPermissions ?? [])].every(grant => kernelFor(config).can(scope, grant.entity, grant.operation))
57
+ }
58
+ // The legacy admin is English-only and has no translation catalog for labelKey.
59
+ function adminCommandLabel(name: string, command?: CommandDefinition) {
60
+ const label = command?.ui?.label
61
+ if (label) return typeof label === 'string' ? label : label.en
62
+ const words = name.split('/').at(-1)!.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ')
63
+ return words.charAt(0).toUpperCase() + words.slice(1)
64
+ }
65
+
66
+ /** Browser adapter only. Richer presentation can replace these views while retaining the JSON/public execution interfaces. */
67
+ export function adminRoutes(app: App, config: InstanceConfig, env: RuntimeEnv, commands: CommandRegistry = new Map(), workflows: WorkflowRegistry = new Map()) {
68
+ const secret = env.IDENTITY?.secret ?? ''
69
+ function page(c: AppContext, title: string, children: Child, csrf = '', scope?: Scope, status = 200) {
70
+ const root = scope ? `/admin/o/${enc(scope.organizationId)}` : ''
71
+ const html = <html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>{title} · Workbase</title><style>{css}</style></head>
72
+ <body><header><a href="/admin">Workbase · {config.id}</a>{csrf && getCookie(c, SESSION_COOKIE) ? <Form action="/auth/logout" csrf={csrf} label="Log out" /> : null}</header>
73
+ {scope ? <nav aria-label="Organization"><a href={root}>Overview</a>
74
+ {canOrganization(config, scope, 'members.read') ? <a href={`${root}/members`}>Members</a> : null}
75
+ {canOrganization(config, scope, 'invitations.read') ? <a href={`${root}/invitations`}>Invitations</a> : null}
76
+ {canOrganization(config, scope, 'tokens.read') ? <a href={`${root}/tokens`}>Agent tokens</a> : null}
77
+ {Object.keys(config.entities).filter(name => kernelFor(config).can(scope, name, 'read')).map(name => <a href={`${root}/entities/${name}`}>{name}</a>)}
78
+ <a href={`${root}/commands`}>Commands</a><a href={`${root}/workflows`}>Workflows</a>{kernelFor(config).audit && scope.role === 'owner' ? <a href={`${root}/audit`}>Audit</a> : null}
79
+ </nav> : null}<main><h1>{title}</h1>{children}</main></body></html>
80
+ return c.html(`<!doctype html>${html.toString()}`, status as any)
81
+ }
82
+ async function api(c: AppContext, path: string, org?: string, method = 'GET', body?: unknown, validatedAuthForm = false) {
83
+ const headers = new Headers({ Accept: 'application/json', 'X-Correlation-Id': c.get('correlationId') })
84
+ for (const name of ['Cookie', 'Origin', 'Sec-Fetch-Site', 'CF-Connecting-IP']) {
85
+ const value = c.req.header(name); if (value) headers.set(name, value)
86
+ }
87
+ // Only auth adapters set this flag, after adminForm validates provenance and CSRF.
88
+ if (validatedAuthForm) headers.set('Origin', new URL(c.req.url).origin)
89
+ if (org) headers.set('X-Organization-Id', org)
90
+ if (body !== undefined) headers.set('Content-Type', 'application/json')
91
+ // Local Hono dispatch, never fetch(): no network, duplicate writes or alternate authorization implementation.
92
+ const response = await app.fetch(new Request(new URL(path, c.req.url), { method, headers, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }))
93
+ for (const cookie of response.headers.getSetCookie()) c.header('Set-Cookie', cookie, { append: true })
94
+ if (!response.ok) {
95
+ const result = await response.json().catch(() => ({})) as any
96
+ throw new ApiError(response.status, typeof result.error === 'string' ? result.error : 'request_failed', typeof result.hint === 'string' ? result.hint : undefined)
97
+ }
98
+ return response.status === 204 ? {} : await response.json() as any
99
+ }
100
+ async function wrapped(c: AppContext, run: (onError: (renderer: (error: ApiError) => Promise<Response>) => void) => Promise<Response>, route: string) {
101
+ c.header('Content-Security-Policy', CSP)
102
+ c.header('Cache-Control', 'no-store')
103
+ c.header('Referrer-Policy', 'no-referrer')
104
+ c.header('X-Content-Type-Options', 'nosniff')
105
+ let response: Response
106
+ let errorRenderer: ((error: ApiError) => Promise<Response>) | undefined
107
+ try { response = await run(renderer => { errorRenderer = renderer }) } catch (cause) {
108
+ const error = errorInfo(cause)
109
+ if ([403, 409].includes(error.status)) await securityLog(env.DB, { ...c.get('scope'), correlationId: c.get('correlationId') }, `${c.req.method} ${route}`, error.status)
110
+ const reload = c.req.path.replace(/\/(members|invitations|tokens)\/[^/]+\/(role|remove|revoke)$/, '/$1')
111
+ response = errorRenderer && [400, 409, 422].includes(error.status) ? await errorRenderer(error) : page(c, 'Request failed', <><p class="error" role="alert">{human[error.code] ?? `${error.code.replaceAll('_', ' ')}.`} <code>{error.code}</code></p><p><a href={reload.startsWith('/admin/') ? reload : '/admin'}>Reload page</a> · <a href="/admin">Organizations</a></p></>, '', undefined, error.status)
112
+ }
113
+ createLogger({ stage: env.STAGE ?? 'local', correlationId: c.get('correlationId'), route })('info', 'admin.page', { status: response.status })
114
+ return response
115
+ }
116
+ async function login(c: AppContext, email = '', error?: ApiError) {
117
+ assertIdentityTransport(c.req.raw, 403)
118
+ return page(c, 'Sign in', <><p>Enter your email address to receive a sign-in link.</p>{error ? errorMessage(error) : null}
119
+ <Form action="/auth/sign-in/magic-link" csrf={await csrfToken(c, secret)} label="Send magic link"><Hidden name="callbackURL" value="/admin" /><label>Email<input type="email" name="email" required autocomplete="email" value={email} /></label></Form></>, '', undefined, error?.status)
120
+ }
121
+ // These two form adapters are installed before authRoutes; JSON REST clients keep their existing behavior.
122
+ for (const path of ['/auth/sign-in/magic-link', '/auth/logout']) app.use(path, async (c, next) => {
123
+ if (c.req.method !== 'POST' || !/^(?:application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)(?:;|$)/i.test(c.req.header('Content-Type') ?? '')) return next()
124
+ return wrapped(c, async onError => {
125
+ const form = await adminForm(c, secret)
126
+ if (path === '/auth/sign-in/magic-link') {
127
+ onError(error => login(c, form.get('email') ?? '', error))
128
+ await api(c, path, undefined, 'POST', { email: form.get('email'), callbackURL: '/admin' }, true)
129
+ return page(c, 'Check your mailbox', <p>Check your mailbox for a sign-in link.</p>)
130
+ }
131
+ if (!getCookie(c, SESSION_COOKIE)) throw new ApiError(401, 'unauthenticated')
132
+ await kernelFor(config).requireActor(browserRequest(c), env)
133
+ await api(c, path, undefined, 'POST', {}, true)
134
+ return c.redirect('/admin/login', 303)
135
+ }, path)
136
+ })
137
+ const handle = (c: AppContext) => wrapped(c, async onError => {
138
+ if (c.req.path === '/admin/login' && c.req.method === 'GET') return login(c)
139
+ // Validate POST provenance even when the session has expired. All admin mutations use POST.
140
+ const form = c.req.method === 'POST' ? await adminForm(c, secret) : undefined
141
+ if (!['GET', 'POST'].includes(c.req.method)) throw new ApiError(405, 'method_not_allowed')
142
+ assertIdentityTransport(c.req.raw, 403)
143
+ if (!getCookie(c, SESSION_COOKIE)) return c.redirect('/admin/login', 302)
144
+ let actor
145
+ try { actor = await kernelFor(config).requireActor(browserRequest(c), env) } catch (error) {
146
+ if (error instanceof ApiError && error.status === 401) return c.redirect('/admin/login', 302)
147
+ throw error
148
+ }
149
+ if (!actor.user) throw new ApiError(403, 'user_required')
150
+ const csrf = await csrfToken(c, secret)
151
+ if (c.req.path === '/admin' || c.req.path === '/admin/') {
152
+ const organizationsForm = async (error?: ApiError) => page(c, 'Organizations', <><ul>{actor.organizations.map(org => <li><a href={`/admin/o/${enc(org.id)}`}>{org.name}</a> ({org.role})</li>)}</ul>
153
+ <h2>Create organization</h2>{error ? errorMessage(error) : null}<Form action="/admin" csrf={csrf} label="Create organization"><label>Name<input name="name" required maxlength={200} value={form?.get('name') ?? ''} /></label></Form></>, csrf, undefined, error?.status)
154
+ onError(organizationsForm)
155
+ if (form) {
156
+ const org = await api(c, '/orgs', undefined, 'POST', { name: form.get('name') })
157
+ return c.redirect(`/admin/o/${enc(org.id)}`, 303)
158
+ }
159
+ return organizationsForm()
160
+ }
161
+ const match = /^\/admin\/o\/([^/]+)(?:\/(.*))?$/.exec(c.req.path)
162
+ if (!match) throw new ApiError(404, 'not_found')
163
+ const org = decodeURIComponent(match[1]); const tail = match[2] ?? ''
164
+ const organization = await env.DB.prepare('SELECT id,name FROM organizations WHERE id=?').bind(org).first<{ id: string; name: string }>()
165
+ if (!organization) throw new ApiError(404, 'organization_not_found')
166
+ const scope = await requireScope(actor, org, config, c.get('correlationId'))
167
+ c.set('scope', scope)
168
+ const root = `/admin/o/${enc(org)}`
169
+ const workflowRead = workflowReader(config, env, workflows, actor, org, c.get('correlationId'))
170
+ const orgApi = `/orgs/${enc(org)}`
171
+ const render = (title: string, body: Child, status = 200) => page(c, title, body, csrf, scope, status)
172
+ if (!tail) {
173
+ if (form) throw new ApiError(405, 'method_not_allowed')
174
+ const counts = []
175
+ for (const name of Object.keys(config.entities)) {
176
+ if (!kernelFor(config).can(scope, name, 'read')) continue
177
+ permission(config, scope, name, 'read')
178
+ const filter = renderStatement(kernelFor(config), scope, Q.select().from(name, 'count_row').field(Q.raw('COUNT(*)'), 'n'))
179
+ const n = await env.DB.prepare(filter.sql).bind(...filter.bindings).first<number>('n')
180
+ counts.push(<li><a href={`${root}/entities/${name}`}>{name}</a>: {n}</li>)
181
+ }
182
+ const workflowCounts = await workflowRead.counts()
183
+ return render(organization.name, <><p>Role: {scope.role}</p><ul>{counts}</ul><h2>Workflow runs</h2><ul>{workflowStatuses.map(status => <li><a href={`${root}/workflows?status=${status}`}>{status === 'needs_attention' ? <strong>{status}: {workflowCounts[status] ?? 0}</strong> : `${status}: ${workflowCounts[status] ?? 0}`}</a></li>)}</ul></>)
184
+ }
185
+ if (tail === 'workflows' || tail.startsWith('workflows/')) {
186
+ const workflowRoot = `${root}/workflows`
187
+ if (tail === 'workflows') {
188
+ if (form) throw new ApiError(405, 'method_not_allowed')
189
+ const status = c.req.query('status') ?? 'needs_attention'
190
+ if (status !== 'all' && !workflowStatuses.includes(status)) throw new ApiError(400, 'invalid_status')
191
+ const runs = await workflowRead.list(status === 'all' ? undefined : status, true)
192
+ const catalog = await workflowRead.catalog()
193
+ return render('Workflows', <><nav aria-label="Workflow status">{['needs_attention', 'all', ...workflowStatuses.slice(1)].map(value => <a href={`${workflowRoot}?status=${value}`} aria-current={value === status ? 'page' : undefined}>{value === 'all' ? 'All' : value}</a>)}</nav>
194
+ {catalog.length ? <p><a href={`${workflowRoot}/new`}>Start workflow</a></p> : null}<p>Newest 100 runs for this filter.</p>
195
+ {!runs.length ? <p>{status === 'needs_attention' ? 'No workflow runs need attention.' : 'No workflow runs match this filter.'}</p> : <table><thead><tr><th>Run</th><th>Definition / version</th><th>Status</th><th>Last error code</th><th>Started / updated</th><th>Initiating actor type</th></tr></thead><tbody>{runs.map(run => <tr><td><a href={`${workflowRoot}/${enc(run.id)}`}>{run.id.slice(0, 6)}…{run.id.slice(-6)}</a></td><td>{run.definition_name} / {run.definition_version}</td><td>{run.status}</td><td>{run.last_error_code ?? '—'}</td><td>{run.created_at}<br />{run.updated_at}</td><td>{run.actor_type}</td></tr>)}</tbody></table>}</>)
196
+ }
197
+ if (tail === 'workflows/new') {
198
+ const catalog = await workflowRead.catalog()
199
+ const selected = form?.get('definition') ?? c.req.query('definition') ?? catalog[0]?.name
200
+ const definition = workflows.get(selected ?? '')
201
+ if (definition) await workflowRead.startScope(definition)
202
+ else if (selected) throw new ApiError(404, 'workflow_not_found')
203
+ const startForm = async (error?: ApiError) => {
204
+ const fields = []
205
+ for (const field of definition ? commandFields(definition.input) : []) {
206
+ const reference = field.definition.referenceEntity
207
+ const entity = typeof reference === 'string' && Object.hasOwn(config.entities, reference) ? reference : undefined
208
+ fields.push(entity ? <FieldInput name={field.name} field={{ type: 'ref', entity, required: field.required }} value={form?.get(field.name) ?? undefined} choices={(await api(c, `/api/${enc(entity)}?limit=90`, org)).data} />
209
+ : <CommandInput {...field} value={form?.get(field.name) ?? undefined} />)
210
+ }
211
+ return render('Start workflow', <>{error ? errorMessage(error) : null}{catalog.length ? <><form method="get" action={`${workflowRoot}/new`}><label>Definition<select name="definition">{catalog.map(item => <option value={item.name} selected={item.name === selected}>{item.name} / {item.version}</option>)}</select></label><button type="submit">Choose definition</button></form>
212
+ <h2>{definition?.name} / {definition?.version}</h2><Form action={`${workflowRoot}/new`} csrf={csrf} label="Start workflow"><Hidden name="definition" value={selected} /><Hidden name="idempotencyKey" value={form?.get('idempotencyKey') ?? await submissionKey(csrf)} />{fields}</Form></> : <p>No workflow definitions are available for your role on this instance.</p>}</>, error?.status)
213
+ }
214
+ if (form) {
215
+ if (!definition) throw new ApiError(403, 'workflow_forbidden')
216
+ await verifySubmissionKey(csrf, form.get('idempotencyKey') ?? '')
217
+ onError(startForm)
218
+ const result = await api(c, `/workflows/${definition.name}`, org, 'POST', commandBody(form, definition.input))
219
+ return c.redirect(`${workflowRoot}/${enc(result.id)}`, 303)
220
+ }
221
+ return startForm()
222
+ }
223
+ const runMatch = /^workflows\/([^/]+)(?:\/(resume|cancel))?$/.exec(tail)
224
+ if (!runMatch) throw new ApiError(404, 'not_found')
225
+ const id = decodeURIComponent(runMatch[1]); const action = runMatch[2]
226
+ const detailPath = `${workflowRoot}/${enc(id)}`
227
+ const detail = async (error?: ApiError) => {
228
+ const run = await workflowRead.detail(id, true)
229
+ // Audit has its own owner-only read authority; do not bypass it for run readers.
230
+ const query = new URLSearchParams({ entity: 'workflows', entity_id: id, limit: '25' })
231
+ if (c.req.query('audit_cursor')) query.set('cursor', c.req.query('audit_cursor')!)
232
+ const events = kernelFor(config).audit && scope.role === 'owner' ? await api(c, `/audit/events?${query}`, org) : undefined
233
+ return render('Workflow run', <>{error ? errorMessage(error) : null}<p><code>{id}</code></p><p>{run.definition_name} / {run.definition_version}</p><p>Status: <strong>{run.status}</strong></p><p>Last error code: <code>{run.last_error_code ?? '—'}</code></p><p>Started: {run.created_at} · Updated: {run.updated_at}</p>
234
+ <h2>Steps</h2><table><thead><tr><th>Step</th><th>Disposition</th><th>Attempts / undo attempts</th><th>Deadline / undo deadline (UTC)</th><th>Next attempt (UTC)</th><th>Error code</th></tr></thead><tbody>{run.steps.map((step: any) => <tr><td>{step.step_id}</td><td>{step.status}</td><td>{step.attempts} / {step.compensation_attempts}</td><td>{workflowTime(step.deadline_at)}<br />{workflowTime(step.compensation_deadline_at)}</td><td>{workflowTime(step.next_attempt_at)}</td><td>{step.last_error_code ?? '—'}</td></tr>)}</tbody></table>
235
+ <h2>Result</h2><pre>{JSON.stringify(run.result, null, 2)}</pre>
236
+ {scope.role === 'owner' ? <>{run.status === 'needs_attention' ? <Form action={`${detailPath}/resume`} csrf={csrf} label="Resume"><Hidden name="idempotencyKey" value={await submissionKey(csrf)} /></Form> : null}
237
+ {!['completed', 'compensated', 'cancelled'].includes(run.status) ? <Form action={`${detailPath}/cancel`} csrf={csrf} label="Cancel"><Hidden name="idempotencyKey" value={await submissionKey(csrf)} /></Form> : null}</> : null}
238
+ {kernelFor(config).audit ? <><h2>Audit events</h2>{events ? <><p>Delivered events only, 25 per page. Delivery may be delayed.</p>{events.data.length ? events.data.map((event: any) => <article><h3>{event.operation}</h3><p>{event.occurred_at} · {event.actor.type}</p>{event.details?.step_id ? <p>Step: {event.details.step_id}</p> : null}{event.details?.code ? <p>Error code: <code>{event.details.code}</code></p> : null}</article>) : <p>No delivered audit events for this run.</p>}{events.next_cursor ? <a rel="next" href={`${detailPath}?audit_cursor=${enc(events.next_cursor)}`}>Next audit page</a> : null}</> : <p>Audit events are available to organization owners.</p>}</> : null}
239
+ </>, error?.status)
240
+ }
241
+ if (form) {
242
+ if (!action) throw new ApiError(405, 'method_not_allowed')
243
+ if (scope.role !== 'owner') throw new ApiError(403, 'owner_required')
244
+ await verifySubmissionKey(csrf, form.get('idempotencyKey') ?? '')
245
+ onError(detail)
246
+ await api(c, `/workflows/${enc(id)}/${action}`, org, 'POST', {})
247
+ return c.redirect(detailPath, 303)
248
+ }
249
+ if (action) throw new ApiError(404, 'not_found')
250
+ return detail()
251
+ }
252
+ if (tail === 'members' || tail.startsWith('members/')) {
253
+ if (form) {
254
+ const member = /^members\/([^/]+)\/(role|remove)$/.exec(tail)
255
+ if (!member) throw new ApiError(404, 'not_found')
256
+ if (member[2] === 'role') {
257
+ organizationPermission(config, scope, 'members.update')
258
+ onError(async error => render('Members', <>{errorMessage(error)}<Form action={`${root}/${tail}`} csrf={csrf} label="Change role">{roleInput(form.get('role') ?? 'viewer')}</Form></>, error.status))
259
+ }
260
+ await api(c, `${orgApi}/members/${member[1]}`, org, member[2] === 'remove' ? 'DELETE' : 'PATCH', member[2] === 'role' ? { role: form.get('role') } : undefined)
261
+ return c.redirect(`${root}/members`, 303)
262
+ }
263
+ if (tail !== 'members') throw new ApiError(404, 'not_found')
264
+ const result = await api(c, `${orgApi}/members`, org)
265
+ return render('Members', <table><thead><tr><th>Email</th><th>Role</th><th>Actions</th></tr></thead><tbody>{result.data.map((member: any) => <tr><td>{member.email}</td><td>{member.role}</td><td>
266
+ {canOrganization(config, scope, 'members.update') ? <Form action={`${root}/members/${enc(member.user_id)}/role`} csrf={csrf} label="Change role">{roleInput(member.role)}</Form> : null}
267
+ {canOrganization(config, scope, 'members.remove') ? <Form action={`${root}/members/${enc(member.user_id)}/remove`} csrf={csrf} label="Remove member" /> : null}
268
+ </td></tr>)}</tbody></table>)
269
+ }
270
+ if (tail === 'invitations' || tail.startsWith('invitations/')) {
271
+ if (form) {
272
+ if (tail === 'invitations') {
273
+ organizationPermission(config, scope, 'invitations.create')
274
+ onError(async error => render('Invitations', <>{errorMessage(error)}<Form action={`${root}/invitations`} csrf={csrf} label="Send invitation"><label>Email<input type="email" name="email" required value={form.get('email') ?? ''} /></label>{roleInput(form.get('role') ?? 'viewer', scope.role)}</Form></>, error.status))
275
+ const created = await api(c, `${orgApi}/invitations`, org, 'POST', { email: form.get('email'), role: form.get('role') })
276
+ let link: string | null = null
277
+ if (isLoopbackDev(c.req.raw, env.STAGE)) {
278
+ // Only the authorized create result may supply this local development link.
279
+ organizationPermission(config, scope, 'invitations.create')
280
+ link = created.accept_url ?? null
281
+ }
282
+ return render('Invitation created', <><p>Sent to {created.email}.</p>{link ? <p>Local development invitation: <a href={link}>{link}</a></p> : null}<a href={`${root}/invitations`}>Invitations</a></>, 201)
283
+ }
284
+ const revoke = /^invitations\/([^/]+)\/revoke$/.exec(tail)
285
+ if (!revoke) throw new ApiError(404, 'not_found')
286
+ await api(c, `${orgApi}/invitations/${revoke[1]}`, org, 'DELETE')
287
+ return c.redirect(`${root}/invitations`, 303)
288
+ }
289
+ if (tail !== 'invitations') throw new ApiError(404, 'not_found')
290
+ const result = await api(c, `${orgApi}/invitations`, org)
291
+ return render('Invitations', <><table><thead><tr><th>Email</th><th>Role</th><th>Status / expiry</th><th>Actions</th></tr></thead><tbody>{result.data.map((invitation: any) => <tr><td>{invitation.email}</td><td>{invitation.role}</td><td>{invitation.revoked_at ? 'Revoked' : invitation.accepted_at ? 'Accepted' : invitation.expires_at}</td><td>
292
+ {!invitation.revoked_at && !invitation.accepted_at && canOrganization(config, scope, 'invitations.revoke') ? <Form action={`${root}/invitations/${enc(invitation.id)}/revoke`} csrf={csrf} label="Revoke invitation" /> : null}
293
+ </td></tr>)}</tbody></table>{canOrganization(config, scope, 'invitations.create') ? <><h2>Invite a member</h2><Form action={`${root}/invitations`} csrf={csrf} label="Send invitation"><label>Email<input type="email" name="email" required /></label>{roleInput('viewer', scope.role)}</Form></> : null}</>)
294
+ }
295
+ if (tail === 'tokens' || tail.startsWith('tokens/')) {
296
+ if (form) {
297
+ if (tail === 'tokens') {
298
+ organizationPermission(config, scope, 'tokens.create')
299
+ onError(async error => render('Agent tokens', <>{errorMessage(error)}<Form action={`${root}/tokens`} csrf={csrf} label="Create token"><label>Name<input name="name" required maxlength={200} value={form.get('name') ?? ''} /></label>{roleInput(form.get('role') ?? 'viewer')}<label>Allowed operations (comma-separated; blank = role permissions)<input name="operations" value={form.get('operations') ?? ''} /></label></Form></>, error.status))
300
+ const result = await api(c, `${orgApi}/tokens`, org, 'POST', { name: form.get('name'), role: form.get('role'), ...(form.get('operations') ? { operations: form.get('operations')!.split(',').map(op => op.trim()).filter(Boolean) } : {}) })
301
+ return render('Agent token created', <><p>Copy this token now. It is shown only once.</p><pre>{result.token}</pre><a href={`${root}/tokens`}>Agent tokens</a></>, 201)
302
+ }
303
+ const revoke = /^tokens\/([^/]+)\/revoke$/.exec(tail)
304
+ if (!revoke) throw new ApiError(404, 'not_found')
305
+ await api(c, `${orgApi}/tokens/${revoke[1]}`, org, 'DELETE')
306
+ return c.redirect(`${root}/tokens`, 303)
307
+ }
308
+ if (tail !== 'tokens') throw new ApiError(404, 'not_found')
309
+ const result = await api(c, `${orgApi}/tokens`, org)
310
+ return render('Agent tokens', <><table><thead><tr><th>Name / prefix</th><th>Role / operations</th><th>Expiry</th><th>Actions</th></tr></thead><tbody>{result.data.map((token: any) => <tr><td>{token.name} / {token.prefix}</td><td>{token.role} / {(token.operations ?? ['all permitted operations']).join(', ')}</td><td>{token.expires_at}</td><td>{!token.revoked_at && canOrganization(config, scope, 'tokens.revoke') ? <Form action={`${root}/tokens/${enc(token.id)}/revoke`} csrf={csrf} label="Revoke token" /> : token.revoked_at ? 'Revoked' : null}</td></tr>)}</tbody></table>
311
+ {canOrganization(config, scope, 'tokens.create') ? <><h2>Create agent token</h2><Form action={`${root}/tokens`} csrf={csrf} label="Create token"><label>Name<input name="name" required maxlength={200} /></label>{roleInput()}<label>Allowed operations (comma-separated; blank = role permissions)<input name="operations" /></label></Form></> : null}</>)
312
+ }
313
+ if (tail === 'commands' || tail.startsWith('commands/')) {
314
+ const selected = tail === 'commands' ? undefined : decodeURIComponent(tail.slice('commands/'.length))
315
+ if (selected && !config.commands.includes(selected)) throw new ApiError(404, 'command_not_found')
316
+ const command = selected ? commands.get(selected) : undefined
317
+ const authorizeCommand = () => {
318
+ if (!command) throw new ApiError(405, 'unsupported_command')
319
+ if ('system' in command.permission) throw new ApiError(405, 'unsupported_command')
320
+ for (const grant of [command.permission, ...(command.additionalPermissions ?? [])]) permission(config, scope, grant.entity, grant.operation)
321
+ }
322
+ const forms = async (error?: ApiError) => render('Commands', <>{error && !commandFields(command!.input).some(field => field.name === error.hint) ? errorMessage(error) : null}{await Promise.all(config.commands.filter(name => !selected || name === selected).map(async name => {
323
+ const definition = commands.get(name)
324
+ const label = adminCommandLabel(name, definition)
325
+ return <section><h2>{label}</h2>{definition && canCommand(config, scope, definition) ? <Form action={`${root}/commands/${name}`} csrf={csrf} label={label}>
326
+ <Hidden name="idempotencyKey" value={form?.get('idempotencyKey') ?? await submissionKey(csrf)} />
327
+ {commandFields(definition.input).map(field => <CommandInput {...field} value={form?.get(field.name) ?? undefined} error={error?.hint === field.name ? errorMessage(error) : undefined} />)}
328
+ </Form> : <p>{definition ? 'Your role cannot run this command.' : 'This command is not registered.'}</p>}</section>
329
+ }))}</>, error?.status)
330
+ if (form) {
331
+ authorizeCommand()
332
+ const key = await verifySubmissionKey(csrf, form.get('idempotencyKey') ?? '')
333
+ onError(forms)
334
+ await api(c, `/commands/${selected}`, org, 'POST', commandBody(form, command!.input))
335
+ return c.redirect(`${root}/commands/${selected}?receipt=${enc(key)}`, 303)
336
+ }
337
+ if (c.req.query('receipt') !== undefined) {
338
+ authorizeCommand()
339
+ const key = await verifySubmissionKey(csrf, c.req.query('receipt')!)
340
+ const receipt = await env.DB.prepare('SELECT response_json FROM idempotency_keys WHERE organization_id=? AND key=? AND command=?').bind(org, key, selected).first<string>('response_json')
341
+ if (!receipt) throw new ApiError(404, 'receipt_not_found')
342
+ return render('Command completed', <><pre>{JSON.stringify(JSON.parse(receipt).body, null, 2)}</pre><a href={`${root}/commands`}>Commands</a></>)
343
+ }
344
+ return forms()
345
+ }
346
+ if (tail === 'audit') {
347
+ if (!kernelFor(config).audit) throw new ApiError(404, 'not_found')
348
+ if (form) throw new ApiError(405, 'method_not_allowed')
349
+ const query = new URLSearchParams()
350
+ for (const key of ['entity', 'entity_id', 'from', 'to']) if (c.req.query(key)) query.set(key, c.req.query(key)!)
351
+ query.set('limit', '25')
352
+ if (c.req.query('cursor') !== undefined) query.set('cursor', c.req.query('cursor')!)
353
+ const result = await api(c, `/audit/events?${query}`, org)
354
+ const next = new URLSearchParams(query); if (result.next_cursor) next.set('cursor', result.next_cursor)
355
+ return render('Audit', <><form method="get" action={`${root}/audit`}>{['entity', 'entity_id', 'from', 'to'].map(key => <label>{key}<input name={key} value={query.get(key) ?? ''} /></label>)}<button type="submit">Filter audit</button></form>
356
+ <p>Delivered events only, 25 per page. Delivery may be delayed.</p>
357
+ {result.data.map((event: any) => <article><h2>{event.operation}</h2><pre>{JSON.stringify(event, null, 2)}</pre></article>)}
358
+ {result.next_cursor ? <a rel="next" href={`${root}/audit?${next}`}>Next page</a> : null}</>)
359
+ }
360
+ const entityMatch = /^entities\/([^/]+)(?:\/([^/]+))?(?:\/(edit|delete))?$/.exec(tail)
361
+ if (!entityMatch) throw new ApiError(404, 'not_found')
362
+ const name = decodeURIComponent(entityMatch[1]); const id = entityMatch[2] ? decodeURIComponent(entityMatch[2]) : undefined; const action = entityMatch[3]
363
+ if (!Object.hasOwn(config.entities, name)) throw new ApiError(404, 'entity_not_found')
364
+ const definition = config.entities[name]
365
+ const entityRoot = `${root}/entities/${name}`
366
+ const apiRoot = `/api/${name}`
367
+ if (form) {
368
+ permission(config, scope, name, action === 'delete' ? 'delete' : id ? 'update' : 'create')
369
+ if (definition.commandsOnly) throw new ApiError(405, 'commands_only')
370
+ if (action === 'delete') {
371
+ if (form.get('confirm') !== 'yes') throw new ApiError(400, 'confirmation_required')
372
+ await api(c, `${apiRoot}/${enc(id!)}`, org, 'DELETE')
373
+ return c.redirect(entityRoot, 303)
374
+ }
375
+ if (id && action !== 'edit') throw new ApiError(405, 'method_not_allowed')
376
+ onError(error => entityForm(error))
377
+ const body = entityBody(form, definition.fields)
378
+ if (id) body.version = Number(form.get('version'))
379
+ const result = await api(c, id ? `${apiRoot}/${enc(id)}` : apiRoot, org, id ? 'PATCH' : 'POST', body)
380
+ return c.redirect(`${entityRoot}/${enc(result.id)}`, 303)
381
+ }
382
+ async function fields(row: Record<string, any> = {}, error?: ApiError) {
383
+ const elements = []
384
+ for (const [key, field] of Object.entries(definition.fields)) {
385
+ if (field.readOnly) continue
386
+ let choices: Record<string, any>[] = []
387
+ if (field.type === 'ref' && kernelFor(config).can(scope, field.entity!, 'read')) choices = (await api(c, `/api/${field.entity}?limit=90`, org)).data
388
+ elements.push(<FieldInput name={key} field={field} value={row[key]} choices={choices} error={error?.hint === key ? errorMessage(error) : undefined} />)
389
+ }
390
+ return elements
391
+ }
392
+ async function entityForm(error: ApiError) {
393
+ const row = Object.fromEntries(form!)
394
+ return render(`${id ? 'Edit' : 'Create'} ${name}`, <>
395
+ {error.hint && Object.hasOwn(definition.fields, error.hint) && !definition.fields[error.hint].readOnly ? null : errorMessage(error)}
396
+ <Form action={id ? `${entityRoot}/${enc(id)}/edit` : entityRoot} csrf={csrf} label={id ? 'Save' : 'Create'}>
397
+ {id ? <Hidden name="version" value={form!.get('version')} /> : null}{await fields(row, error)}
398
+ </Form></>, error.status)
399
+ }
400
+ const commandLinks = <><p>This entity is changed through commands.</p>{config.commands.map(commandName => {
401
+ const command = commands.get(commandName)
402
+ return command && 'entity' in command.permission && command.permission.entity === name && canCommand(config, scope, command)
403
+ ? <form method="get" action={`${root}/commands/${commandName}`}><button type="submit">{adminCommandLabel(commandName, command)}</button></form> : null
404
+ })}<a href={`${root}/commands`}>Open commands</a></>
405
+ if (id === 'new') {
406
+ if (action) throw new ApiError(404, 'not_found')
407
+ permission(config, scope, name, 'create')
408
+ return render(`Create ${name}`, definition.commandsOnly ? commandLinks : <><p>Dates and times use UTC. Relation choices show at most 90 rows.</p><Form action={entityRoot} csrf={csrf} label="Create">{await fields()}</Form></>)
409
+ }
410
+ if (id) {
411
+ const row = await api(c, `${apiRoot}/${enc(id)}`, org)
412
+ if (action === 'edit') {
413
+ permission(config, scope, name, 'update')
414
+ return render(`Edit ${name}`, definition.commandsOnly ? commandLinks : <><p>Dates and times use UTC. Relation choices show at most 90 rows.</p><Form action={`${entityRoot}/${enc(id)}/edit`} csrf={csrf}><Hidden name="version" value={row.version} />{await fields(row)}</Form></>)
415
+ }
416
+ if (action === 'delete') {
417
+ permission(config, scope, name, 'delete')
418
+ return render(`Delete ${name}`, definition.commandsOnly ? commandLinks : <><p>Delete this record permanently?</p><pre>{JSON.stringify(row, null, 2)}</pre><Form action={`${entityRoot}/${enc(id)}/delete`} csrf={csrf} label="Confirm delete"><label><input type="checkbox" name="confirm" value="yes" required /> I confirm deletion</label></Form></>)
419
+ }
420
+ return render(`${name} detail`, <><pre>{JSON.stringify(row, null, 2)}</pre>{definition.commandsOnly ? commandLinks : <p>
421
+ {kernelFor(config).can(scope, name, 'update') ? <a href={`${entityRoot}/${enc(id)}/edit`}>Edit</a> : null}{' '}
422
+ {kernelFor(config).can(scope, name, 'delete') ? <a href={`${entityRoot}/${enc(id)}/delete`}>Delete</a> : null}</p>}</>)
423
+ }
424
+ const query = new URLSearchParams()
425
+ for (const key of ['limit', 'cursor']) if (c.req.query(key)) query.set(key, c.req.query(key)!)
426
+ // Reference fields have generated organization-scoped indexes. Avoid arbitrary full-scan filters.
427
+ const filterFields = Object.entries(definition.fields).filter(([, field]) => field.type === 'ref')
428
+ for (const [key] of filterFields) if (c.req.query(key)) query.set(key, c.req.query(key)!)
429
+ const result = await api(c, `${apiRoot}?${query}`, org)
430
+ const next = new URLSearchParams(query); if (result.next_cursor) next.set('cursor', result.next_cursor)
431
+ return render(name, <>{definition.commandsOnly ? commandLinks : kernelFor(config).can(scope, name, 'create') ? <p><a href={`${entityRoot}/new`}>Create {name}</a></p> : null}
432
+ <form method="get" action={entityRoot}><label>Rows per page<input name="limit" type="number" min={1} max={90} value={query.get('limit') ?? '25'} /></label>{filterFields.map(([key]) => <label>{key}<input name={key} value={query.get(key) ?? ''} /></label>)}<button type="submit">Filter</button></form>
433
+ <table><thead><tr><th>Record</th>{Object.keys(definition.fields).map(key => <th>{key}</th>)}</tr></thead><tbody>{result.data.map((row: any) => <tr><td><a href={`${entityRoot}/${enc(row.id)}`}>{row.id}</a></td>{Object.keys(definition.fields).map(key => <td>{String(row[key] ?? '')}</td>)}</tr>)}</tbody></table>
434
+ {result.next_cursor ? <a rel="next" href={`${entityRoot}?${next}`}>Next page</a> : null}</>)
435
+ }, c.req.path === '/admin/login' ? '/admin/login' : c.req.path === '/admin' || c.req.path === '/admin/' ? '/admin' : '/admin/o/:orgId/*')
436
+ app.all('/admin', handle)
437
+ app.all('/admin/*', handle)
438
+ }
package/src/app.ts ADDED
@@ -0,0 +1,115 @@
1
+ import { eventDeliveryContext } from './event-delivery'
2
+ import { bootstrapRoutes } from './bootstrap'
3
+ import { capabilityRoutes } from './capabilities'
4
+ import { queryRoutes } from './query/routes'
5
+ import { QueryError } from './query/errors'
6
+ import { validatedBrowserDispatch } from './browser-dispatch'
7
+ import { consoleRoutes } from './console'
8
+ import { jsonCookieCSRF } from './json-csrf'
9
+ import { KernelRegistry } from './kernel/registry'
10
+ import { workflowRoutes } from './workflow-routes'
11
+ import { Hono } from 'hono'
12
+ import { adminRoutes } from './admin-ui'
13
+ import { routePath } from 'hono/route'
14
+ import { ZodError } from 'zod'
15
+ import { publicSchema } from './public-schema'
16
+ import type { InstanceInput } from './config'
17
+ import type { AppEnv, RuntimeEnv, RuntimeOptions } from './types'
18
+ import { scopeMiddleware } from './authorization'
19
+ import { crudRoutes } from './crud'
20
+ import { ApiError } from './errors'
21
+ import { identityEnvironment } from './identity-settings'
22
+ import { identityWrite } from './identity-writes'
23
+ import { securityLog } from './events'
24
+ import { ulid } from './crypto'
25
+ import { commandRoutes, createCommandRegistry } from './commands'
26
+ import { outboxStats, requireInternal } from './audit'
27
+ import { relay } from './relay'
28
+ import { schemaStatus } from './schema-compatibility'
29
+ import { opsStatus } from './ops'
30
+ import { RuleFailed } from './execution/errors'
31
+ import { timeRequest, timedSync, timedDatabase } from './request-timing'
32
+ export function createApp(input: InstanceInput, env: RuntimeEnv, options: RuntimeOptions = {}) {
33
+ return timedSync('bootstrap', () => buildApp(input, env, options))
34
+ }
35
+ function buildApp(input: InstanceInput, env: RuntimeEnv, options: RuntimeOptions) {
36
+ env = { ...env, DB: timedDatabase(env.DB) }
37
+ if (options.authorization === 'trust' && (env.SCHEMA_EXPECTED || (env.STAGE && env.STAGE !== 'local'))) throw new Error('authorization_trust_requires_development')
38
+ const kernel = new KernelRegistry(input, options, env)
39
+ const config = kernel.config
40
+ options = { ...options, commands: kernel.commands, workflows: kernel.workflows }
41
+ env = identityEnvironment(env)
42
+ const app = new Hono<AppEnv>()
43
+ const fetch = app.fetch.bind(app)
44
+ app.fetch = (request, bindings, context) => timeRequest(async () => await fetch(request, bindings, context))
45
+ app.use('*', async (c, next) => {
46
+ let context: Pick<ExecutionContext, 'waitUntil'> | undefined
47
+ try { context = c.executionCtx } catch { /* app.request() has no Worker context. */ }
48
+ return context ? eventDeliveryContext.run({ waitUntil: promise => context!.waitUntil(promise) }, next) : next()
49
+ })
50
+ app.use('*', async (c, next) => {
51
+ const url = new URL(c.req.url)
52
+ // Keep the native endpoint registered, with one canonical browser/cookie origin.
53
+ if (env.STAGE === 'staging' && url.hostname.endsWith('.workers.dev') && env.AUTH_BASE_URL) {
54
+ const target = new URL(env.AUTH_BASE_URL)
55
+ target.pathname = url.pathname; target.search = url.search
56
+ return c.redirect(target.href, 308)
57
+ }
58
+ await next()
59
+ })
60
+ app.use('*', async (c, next) => {
61
+ const correlation = c.req.header('X-Correlation-Id')
62
+ c.set('correlationId', correlation && /^[a-zA-Z0-9_-]{1,100}$/.test(correlation) ? correlation : ulid())
63
+ await next()
64
+ c.header('X-Correlation-Id', c.get('correlationId'))
65
+ })
66
+ app.onError(async (error, c) => {
67
+ const known = error instanceof ApiError
68
+ const constraint = /SQLITE_CONSTRAINT|constraint failed/i.test(error.message)
69
+ const status = known ? error.status : error instanceof ZodError || error instanceof SyntaxError ? 400 : constraint ? 409 : 500
70
+ if (known && error.code === 'insecure_identity_transport') {
71
+ // Fixed code only: callbacks and magic-link URLs contain credentials.
72
+ await identityWrite(env, config, 'security_denied', [{
73
+ sql: 'INSERT INTO security_log (id,operation,status,correlation_id,occurred_at) VALUES (?,?,?,?,?)',
74
+ bindings: [ulid(), error.code, status, c.get('correlationId'), new Date().toISOString()], expectRows: 1,
75
+ }])
76
+ } else if (status === 403 || status === 409) {
77
+ if (c.req.path.startsWith('/auth/')) await identityWrite(env, config, 'security_denied', [{
78
+ sql: 'INSERT INTO security_log (id,operation,status,correlation_id,occurred_at) VALUES (?,?,?,?,?)',
79
+ bindings: [ulid(), `${c.req.method} ${routePath(c, -1)}`, status, c.get('correlationId'), new Date().toISOString()], expectRows: 1,
80
+ }])
81
+ else await securityLog(env.DB, { ...c.get('scope'), correlationId: c.get('correlationId') }, `${c.req.method} ${routePath(c, -1)}`, status)
82
+ }
83
+ return c.json({ error: known ? error.code : status === 400 ? 'validation_error' : constraint ? 'constraint_conflict' : 'internal_error', ...(error instanceof QueryError ? { path: error.path, ...(error.cost ? { cost: error.cost } : {}) } : {}), ...(known && error.hint ? { hint: error.hint } : {}), ...(known && error.detail ? { detail: error.detail } : {}), ...(error instanceof RuleFailed && error.code === 'rule_failed' ? { rule: error.rule, diagnosis: error.diagnosis } : {}) }, status as any)
84
+ })
85
+ app.get('/health', async c => {
86
+ const schema = await schemaStatus(env, config)
87
+ return c.json({ instance: config.id, revision: config.revision, core_version: '0.1.0', schema }, schema.compatible ? 200 : 503)
88
+ })
89
+ // Public build metadata only: never include runtime bindings, credentials or records.
90
+ app.get('/schema', c => c.json(publicSchema(config, options)))
91
+ consoleRoutes(app, config, env)
92
+ for (const path of ['/api/*', '/commands/*', '/workflows/*', '/query', '/orgs', '/orgs/*', '/organizations/*', '/me/profile', '/invitations/*']) app.use(path, jsonCookieCSRF(env))
93
+ adminRoutes(validatedBrowserDispatch(app, env), config, env, options.commands, options.workflows)
94
+ // Native admin forms have already passed adminForm; JSON identity mutations use the same provenance gate.
95
+ app.use('/auth/*', jsonCookieCSRF(env))
96
+ app.use('/internal/*', async (c, next) => { requireInternal(env, c.req.header('X-Internal-Token')); await next() })
97
+ app.post('/internal/relay', async c => c.json(await relay(env, config)))
98
+ app.get('/internal/ops', async c => c.json(await opsStatus(env, config)))
99
+ app.get('/internal/outbox-stats', async c => c.json(await outboxStats(env.DB)))
100
+ app.get('/internal/webhook-failures', async c => {
101
+ const result = await env.DB.prepare("SELECT event_id,organization_id,attempts,next_attempt_at,last_error FROM webhook_deliveries WHERE state='failed' ORDER BY next_attempt_at LIMIT 100").all()
102
+ return c.json({ data: result.results })
103
+ })
104
+ for (const path of ['/api/*', '/commands/*', '/query']) app.use(path, scopeMiddleware(env, config, kernel))
105
+ workflowRoutes(app, config, env, options.workflows ?? new Map())
106
+ kernel.mount(app, env)
107
+ options.extend?.(app, config, env)
108
+ bootstrapRoutes(app, kernel, env, options)
109
+ capabilityRoutes(app, kernel, env)
110
+ queryRoutes(app, kernel, env)
111
+ crudRoutes(app, config, env)
112
+ commandRoutes(app, config, env, options.commands ?? createCommandRegistry([]))
113
+ app.all('/commands/*', () => { throw new ApiError(405, 'unsupported_command') })
114
+ return app
115
+ }
@@ -0,0 +1,23 @@
1
+ import type { InstanceConfig } from './config'
2
+ import { ulid } from './crypto'
3
+ import type { Actor, Scope } from './identity'
4
+ export interface AuditEvent {
5
+ event_id: string; instance_id: string; organization_id: string; actor: Actor;
6
+ operation: string; entity: string; entity_id: string; occurred_at: string;
7
+ correlation_id: string; schema_version: number; changes: Record<string, unknown>;
8
+ details?: Record<string, unknown>
9
+ }
10
+ function redact(value: unknown): unknown {
11
+ if (typeof value === 'string' && /[A-Z0-9._%+-]+@[A-Z0-9.-]+/i.test(value)) return '[redacted]'
12
+ if (Array.isArray(value)) return value.map(redact)
13
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).filter(([k]) => !/password|token|salt|email|secret/i.test(k)).map(([k, v]) => [k, redact(v)]))
14
+ return value
15
+ }
16
+ export function makeEvent(config: InstanceConfig, scope: Scope, operation: string, entity: string, id: string, before: Record<string, unknown> = {}, after: Record<string, unknown> = {}, details?: Record<string, unknown>): AuditEvent {
17
+ const changes: Record<string, unknown> = {}
18
+ for (const [key, field] of Object.entries(config.entities[entity]?.fields ?? {})) {
19
+ if (field.sensitive || /password|token|salt|email|secret/i.test(key)) continue
20
+ if (JSON.stringify(before[key] ?? null) !== JSON.stringify(after[key] ?? null)) changes[key] = { before: redact(before[key] ?? null), after: redact(after[key] ?? null) }
21
+ }
22
+ return { event_id: ulid(), instance_id: config.id, organization_id: scope.organizationId, actor: scope.actor, operation, entity, entity_id: id, occurred_at: new Date().toISOString(), correlation_id: scope.correlationId, schema_version: config.revision, changes, ...(details ? { details: redact(details) as Record<string, unknown> } : {}) }
23
+ }