@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,198 @@
1
+ import { isBuiltinPlugin } from './builtin-source'
2
+ import { baseFields, defineInstance, type InstanceConfig, type InstanceInput, type Operation } from '../config'
3
+ import { createCommandRegistry, type CommandRegistry } from '../commands'
4
+ import { createWorkflowRegistry, type WorkflowRegistry } from '../workflow-runtime'
5
+ import { authorizeOperation } from '../authorization'
6
+ import { operationName } from './operation-name'
7
+ import { ApiError } from '../errors'
8
+ import type { App, ResolvedActor, RuntimeEnv, RuntimeOptions, Scope } from '../types'
9
+ import type { AuditEvent } from '../audit-event'
10
+ import type { AtomicOperation } from '../execution/types'
11
+ import type { KernelCommand, ResourceAction, PluginMigration, TableFilter, WorkbasePlugin } from './plugin'
12
+ import { renderPredicate } from './predicate'
13
+ export { renderPredicate } from './predicate'
14
+ import { resolvePlugins } from './composition'
15
+ import { applyPluginMigrations } from './migrations'
16
+ import { timed } from '../request-timing'
17
+
18
+ const registries = new WeakMap<InstanceConfig, KernelRegistry>()
19
+ export const lifecyclePhases = ['contribute', 'validate', 'migrations', 'ports', 'mount'] as const
20
+ export class KernelRegistry {
21
+ readonly plugins: readonly WorkbasePlugin[]
22
+ readonly providers: ReadonlyMap<string, readonly WorkbasePlugin[]>
23
+ readonly config: InstanceConfig
24
+ readonly commands: CommandRegistry
25
+ readonly workflows: WorkflowRegistry
26
+ readonly migrations: readonly PluginMigration[]
27
+ /** True only for a complete permissions provider outside development trust. */
28
+ readonly permissionsActive: boolean
29
+ private readonly trust: boolean
30
+ private readonly hasAuthorization: boolean
31
+ constructor(config: InstanceInput, options: RuntimeOptions = {}, env?: RuntimeEnv) {
32
+ const resolved = resolvePlugins(options.plugins ?? config.plugins ?? [], config.interactive)
33
+ this.plugins = resolved.plugins
34
+ this.providers = resolved.providers
35
+ const names = new Set(this.plugins.map(plugin => plugin.name))
36
+ // contribute: reject collisions rather than allowing load order to silently overwrite code.
37
+ const entities = { ...config.entities }
38
+ const commands = [...(options.commands?.values() ?? [])]
39
+ const workflows = [...(options.workflows?.values() ?? [])]
40
+ const commandNames = [...(config.commands ?? [])]
41
+ for (const plugin of this.plugins) {
42
+ for (const [name, entity] of Object.entries(plugin.entities ?? {})) {
43
+ if (Object.hasOwn(entities, name)) throw new Error(`Duplicate entity: ${name}`)
44
+ entities[name] = entity
45
+ }
46
+ for (const command of plugin.commands ?? []) {
47
+ if (!isBuiltinPlugin(plugin) || !options.commands?.has(command.name)) commands.push(command)
48
+ if (!commandNames.includes(command.name)) commandNames.push(command.name)
49
+ }
50
+ for (const workflow of [...(plugin.workflows ?? []), ...(env ? plugin.workflowDefinitions?.(env)?.values() ?? [] : [])]) {
51
+ if (!isBuiltinPlugin(plugin) || !options.workflows?.has(workflow.name)) workflows.push(workflow)
52
+ }
53
+ }
54
+ // validate: whole model, registries, and each plugin-owned section.
55
+ const pluginConfig = { ...config.pluginConfig }
56
+ for (const plugin of this.plugins) if (plugin.configSchema) pluginConfig[plugin.name] = plugin.configSchema.parse(pluginConfig[plugin.name])
57
+ for (const name of Object.keys(pluginConfig)) if (!names.has(name)) throw new Error(`Unknown plugin config: ${name}`)
58
+ this.config = defineInstance({ ...config, plugins: this.plugins, entities, commands: commandNames,
59
+ ...(config.pluginConfig || Object.keys(pluginConfig).length ? { pluginConfig } : {}) })
60
+ this.providers.get('console')?.[0]?.validateConsole?.(this.config)
61
+ this.commands = createCommandRegistry(commands)
62
+ this.workflows = createWorkflowRegistry(workflows)
63
+ // migrations: append hooks to the supplied chain. Applying D1 migrations remains an operator action.
64
+ this.migrations = Object.freeze([...(options.migrations ?? []), ...this.plugins.flatMap(plugin => (plugin.migrations ?? []).map(migration => ({ ...migration, name: `${plugin.name}/${migration.name}` })))])
65
+ if (new Set(this.migrations.map(migration => migration.name)).size !== this.migrations.length) throw new Error('Duplicate plugin migration')
66
+ // ports: only complete validated configuration becomes visible to request helpers.
67
+ this.trust = options.authorization === 'trust'
68
+ this.hasAuthorization = this.providers.has('permissions')
69
+ this.permissionsActive = !this.trust && this.hasAuthorization
70
+ if (this.trust) console.warn('Workbase kernel: authorization=trust enabled (development only)')
71
+ registries.set(this.config, this)
72
+ }
73
+ get identity() {
74
+ const port = this.providers.get('identity')?.[0]?.identity
75
+ if (!port) throw new ApiError(401, 'identity_port_required')
76
+ return port
77
+ }
78
+ get mailOutbox() {
79
+ const port = this.providers.get('mail-outbox')?.[0]?.mailOutbox
80
+ if (!port) throw new ApiError(503, 'mail_outbox_required')
81
+ return port
82
+ }
83
+ get audit() { return this.providers.get('audit')?.[0]?.audit }
84
+ /** Explicit operator action; never run migrations in a request or on uninstall. */
85
+ applyMigrations(db: D1Database) { return applyPluginMigrations(db, this.plugins) }
86
+ async resolveScopeId(db: D1Database, selected?: string): Promise<string> {
87
+ const provider = this.providers.get('organizations')?.[0]
88
+ if (!provider) {
89
+ if (!this.providers.has('members')) {
90
+ if (!selected) throw new ApiError(403, 'organization_required')
91
+ return selected
92
+ }
93
+ if (selected && selected !== 'instance') throw new ApiError(403, 'organization_forbidden')
94
+ return 'instance'
95
+ }
96
+ // Compatibility tenancy supplies no new scope port during extraction.
97
+ const scope = provider.resolveScopeId ? await provider.resolveScopeId(db, selected) : selected
98
+ if (!scope) throw new ApiError(403, 'organization_required')
99
+ return scope
100
+ }
101
+ async signInInvitation(email: string, request: Request, env: RuntimeEnv) {
102
+ const providers = (this.providers.get('login') ?? []).filter(plugin => plugin.signInInvitation)
103
+ if (providers.length !== 1) throw new ApiError(401, 'invitation_login_required')
104
+ return providers[0].signInInvitation!.call(this, email, request, env)
105
+ }
106
+ mount(app: App, env: RuntimeEnv) {
107
+ for (const plugin of this.plugins) plugin.routes?.call(this, app, this.config, env)
108
+ }
109
+ mcpTools() { return this.plugins.flatMap(plugin => plugin.mcpTools?.call(this) ?? []) }
110
+ async onEvent(event: AuditEvent) {
111
+ for (const plugin of this.plugins) await plugin.onEvent?.call(this, event)
112
+ }
113
+ async authenticate(request: Request, env: RuntimeEnv): Promise<ResolvedActor | null> {
114
+ let claimed: ResolvedActor | null = null
115
+ let login: WorkbasePlugin | undefined
116
+ for (const plugin of this.plugins) {
117
+ for (const authenticate of [plugin.authenticate, plugin.authenticateCredential]) {
118
+ const actor = await authenticate?.call(this, request, env)
119
+ if (!actor) continue
120
+ if (claimed) throw new ApiError(401, 'ambiguous_login')
121
+ claimed = actor
122
+ login = authenticate === plugin.authenticate ? plugin : undefined
123
+ }
124
+ }
125
+ if (claimed?.actor.type === 'user' && !claimed.user) throw new ApiError(401, 'invalid_local_identity')
126
+ if (claimed?.user) {
127
+ if (claimed.actor.type !== 'user' || claimed.actor.id !== claimed.user.id) throw new ApiError(401, 'invalid_local_identity')
128
+ const local = await this.identity.resolveUser(env.DB, claimed.user.id)
129
+ if (local.email.toLowerCase() !== claimed.user.email.toLowerCase()) throw new ApiError(401, 'invalid_local_identity')
130
+ await login?.synchronizeProfile?.call(this, request, env, claimed)
131
+ }
132
+ return claimed // anonymous; scoped surfaces require a verified actor.
133
+ }
134
+ async requireActor(request: Request, env: RuntimeEnv): Promise<ResolvedActor> {
135
+ return timed('auth', async () => {
136
+ const actor = await this.authenticate(request, env)
137
+ if (!actor) throw new ApiError(401, 'unauthenticated')
138
+ return actor
139
+ })
140
+ }
141
+ tableFilter(entity: string, scope: Scope): TableFilter {
142
+ if (!this.trust && !this.hasAuthorization) return { kind: 'none' }
143
+ const filters = this.plugins.flatMap(plugin => plugin.tableFilter ? [plugin.tableFilter.call(this, entity, scope)] : [])
144
+ if (!filters.length) return { kind: this.trust ? 'all' : 'none' }
145
+ if (filters.some(filter => filter.kind === 'none')) return { kind: 'none', ...(filters.some(filter => 'deny' in filter && filter.deny === 'forbidden') ? { deny: 'forbidden' as const } : {}) }
146
+ const where = filters.filter((filter): filter is Extract<TableFilter, { kind: 'where' }> => filter.kind === 'where')
147
+ return where.length ? { kind: 'where', predicate: { all: where.map(filter => filter.predicate) }, ...(where.some(filter => filter.deny === 'forbidden') ? { deny: 'forbidden' as const } : {}) } : { kind: 'all' }
148
+ }
149
+ fieldMask(entity: string, scope: Scope): string[] {
150
+ let fields = [...baseFields, ...Object.keys(this.config.entities[entity].fields)]
151
+ for (const plugin of this.plugins) if (plugin.fieldMask) {
152
+ const mask = new Set(plugin.fieldMask.call(this, entity, scope))
153
+ fields = fields.filter(field => mask.has(field))
154
+ }
155
+ return fields
156
+ }
157
+ commandGuard(command: KernelCommand, scope: Scope, input: unknown) {
158
+ // Only the existing trusted identity writer can use this service permission.
159
+ const internal = scope.actor.type === 'service' && 'system' in command.permission && command.permission.system === 'identity.write'
160
+ if (!internal && !this.trust && !this.hasAuthorization) throw new ApiError(403, 'permission_denied')
161
+ // Credential restrictions and entity-scope provenance survive provider removal and trust.
162
+ if (scope.actor.type === 'agent' || command.kind === 'entity') authorizeOperation(scope, operationName(command))
163
+ for (const plugin of this.plugins) {
164
+ const result = plugin.commandGuard?.call(this, command, scope, input)
165
+ if (result && !result.allow) throw new ApiError(403, result.code)
166
+ }
167
+ }
168
+ resourcePermission(scope: Scope, action: ResourceAction) {
169
+ this.commandGuard({ name: operationName({ system: action }), kind: 'resource', permission: { system: action } }, scope, undefined)
170
+ }
171
+ permission(scope: Scope, entity: string, operation: Operation) {
172
+ this.commandGuard({ name: operationName({ entity, operation }), kind: 'entity', permission: { entity, operation } }, scope, undefined)
173
+ }
174
+ /** Only use when the caller compiles tableFilter into every table reference. */
175
+ readPermission(scope: Scope, entity: string) {
176
+ if (!this.trust && !this.hasAuthorization) return
177
+ this.permission(scope, entity, 'read')
178
+ }
179
+ can(scope: Scope, entity: string, operation: Operation) {
180
+ if (operation === 'read' && (this.tableFilter(entity, scope).kind === 'none' || !this.fieldMask(entity, scope).includes('id'))) return false
181
+ try { this.permission(scope, entity, operation); return true } catch (error) { if (error instanceof ApiError && error.status === 403) return false; throw error }
182
+ }
183
+ atomicPermission(scope: Scope, operation: AtomicOperation, input?: unknown) {
184
+ this.commandGuard({ name: operationName(operation), kind: 'command', permission: operation.permission, additionalPermissions: operation.additionalPermissions }, scope, input)
185
+ }
186
+ }
187
+ /** Request and execution helpers only accept a validated, explicitly bound composition. */
188
+ export function boundKernel(config: InstanceConfig): KernelRegistry | undefined { return registries.get(config) }
189
+ export function kernelFor(config: InstanceConfig): KernelRegistry {
190
+ const registry = boundKernel(config)
191
+ if (!registry) throw new Error('Unbound instance config: construct KernelRegistry and use kernel.config')
192
+ return registry
193
+ }
194
+ /** Preserve the selected ports across immutable execution-context config snapshots. */
195
+ export function bindKernel(source: InstanceConfig, target: InstanceConfig) { registries.set(target, kernelFor(source)) }
196
+ export function filterSql(filter: TableFilter, tableAlias: string): { sql: string; bindings: unknown[] } {
197
+ return filter.kind === 'where' ? renderPredicate(filter.predicate, tableAlias) : { sql: filter.kind === 'all' ? '1=1' : '0=1', bindings: [] }
198
+ }
@@ -0,0 +1,13 @@
1
+ import { baseFields, type InstanceConfig } from '../config'
2
+ import { quote } from '../migrations/schema'
3
+
4
+ /** Check the effective model plus columns referenced by fixed plugin SQL/routes. */
5
+ export async function checkInstanceSchema(db: D1Database, config: Pick<InstanceConfig, 'entities'>, dependencies: Record<string, readonly string[]>) {
6
+ const tables = new Set([...Object.keys(config.entities), ...Object.keys(dependencies)])
7
+ for (const table of tables) {
8
+ const fields = new Set([...baseFields, ...Object.keys(config.entities[table]?.fields ?? {}), ...(dependencies[table] ?? [])])
9
+ // Qualify identifiers so SQLite cannot treat an absent quoted column as a string.
10
+ const columns = [...fields].map(field => `${quote(table)}.${quote(field)}`).join(',')
11
+ await db.prepare(`SELECT ${columns} FROM ${quote(table)} LIMIT 0`).all()
12
+ }
13
+ }
package/src/logging.ts ADDED
@@ -0,0 +1,21 @@
1
+ // Log IDs and numeric measurements, never request/event payloads or arbitrary free text.
2
+ const messages = { 'ops.relay.run': 'Relay completed', 'ops.relay.failed': 'Relay failed', 'admin.page': 'Admin page served' } as const
3
+ export type LogEvent = keyof typeof messages
4
+ export interface LogIds { stage: string; correlationId?: string; organizationId?: string; route?: string }
5
+ export type Measurements = Record<string, number | boolean | null>
6
+ const pageRoutes = new Set(['/admin', '/admin/login', '/admin/o/:orgId/*', '/auth/sign-in/magic-link', '/auth/logout'])
7
+ const safeId = (value: unknown) => typeof value === 'string' && /^[a-zA-Z0-9_-]{1,100}$/.test(value) ? value : undefined
8
+ export function createLogger(ids: LogIds, write: (line: string) => void = console.log) {
9
+ return (level: 'info' | 'error', event: LogEvent, data?: Measurements) => {
10
+ if (!Object.hasOwn(messages, event)) return
11
+ const measurements = Object.fromEntries(Object.entries(data ?? {}).filter(([key, value]) =>
12
+ !/token|password|email|payload|secret|authorization/i.test(key) && /^[a-zA-Z][a-zA-Z0-9_]*$/.test(key)
13
+ && (value === null || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value)))))
14
+ write(JSON.stringify({ level, event, stage: safeId(ids.stage) ?? 'unknown', message: messages[event], ts: new Date().toISOString(),
15
+ ...(safeId(ids.correlationId) ? { correlationId: ids.correlationId } : {}),
16
+ ...(safeId(ids.organizationId) ? { organizationId: ids.organizationId } : {}),
17
+ ...(ids.route && pageRoutes.has(ids.route) ? { route: ids.route } : {}),
18
+ ...(Object.keys(measurements).length ? { data: measurements } : {}),
19
+ }))
20
+ }
21
+ }
@@ -0,0 +1,2 @@
1
+ // Generated by packages/core/generate-auth-migration.mjs.
2
+ export const betterAuthSchema = "create table \"user\" (\"id\" text not null primary key, \"name\" text not null, \"email\" text not null unique, \"emailVerified\" integer not null, \"image\" text, \"createdAt\" date not null, \"updatedAt\" date not null);\n\ncreate table \"session\" (\"id\" text not null primary key, \"expiresAt\" date not null, \"token\" text not null unique, \"createdAt\" date not null, \"updatedAt\" date not null, \"ipAddress\" text, \"userAgent\" text, \"userId\" text not null references \"user\" (\"id\") on delete cascade);\n\ncreate table \"account\" (\"id\" text not null primary key, \"issuer\" text not null, \"accountId\" text not null, \"providerId\" text not null, \"userId\" text not null references \"user\" (\"id\") on delete cascade, \"accessToken\" text, \"refreshToken\" text, \"idToken\" text, \"accessTokenExpiresAt\" date, \"refreshTokenExpiresAt\" date, \"scope\" text, \"password\" text, \"createdAt\" date not null, \"updatedAt\" date not null);\n\ncreate table \"verification\" (\"id\" text not null primary key, \"identifier\" text not null, \"value\" text not null, \"expiresAt\" date not null, \"createdAt\" date not null, \"updatedAt\" date not null);\n\ncreate table \"rateLimit\" (\"id\" text not null primary key, \"key\" text not null unique, \"count\" integer not null, \"lastRequest\" bigint not null);\n\ncreate index \"session_userId_idx\" on \"session\" (\"userId\");\n\ncreate index \"account_userId_idx\" on \"account\" (\"userId\");\n\ncreate index \"verification_identifier_idx\" on \"verification\" (\"identifier\");\n\ncreate unique index \"account_issuer_accountId_uidx\" on \"account\" (\"issuer\", \"accountId\");\n\n\n\n\nCREATE TABLE email_outbox_new (id TEXT PRIMARY KEY, organization_id TEXT REFERENCES organizations(id), recipient TEXT NOT NULL, subject TEXT NOT NULL, body TEXT NOT NULL, created_at TEXT NOT NULL);\nINSERT INTO email_outbox_new SELECT * FROM email_outbox;\nDROP TABLE email_outbox;\nALTER TABLE email_outbox_new RENAME TO email_outbox;\nCREATE TABLE identity_link_grants (state_hash TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id), session_id TEXT NOT NULL, expires_at TEXT NOT NULL);\nCREATE UNIQUE INDEX identities_issuer_subject_idx ON identities(issuer,subject);\n"
@@ -0,0 +1,6 @@
1
+ /** Append-only migration, shared by fresh schema generation and deployed instance chains. */
2
+ export const emailDeliverySchema = `ALTER TABLE email_outbox ADD COLUMN delivery_status TEXT NOT NULL DEFAULT 'pending' CHECK (delivery_status IN ('pending','sending','sent','failed'));
3
+ ALTER TABLE email_outbox ADD COLUMN attempts INTEGER NOT NULL DEFAULT 0;
4
+ ALTER TABLE email_outbox ADD COLUMN sent_at TEXT;
5
+ ALTER TABLE email_outbox ADD COLUMN last_error TEXT;
6
+ `
@@ -0,0 +1,77 @@
1
+ import { defineInstance, type InstanceConfig } from '../config'
2
+ import { column, createEntity, initialSchema, literal, quote, revisionSQL } from './schema'
3
+ export interface MigrationPlan { sql: string; destructive: string[]; blocked: string[]; warnings: string[] }
4
+ export function plan(fromConfig: InstanceConfig | null, toConfig: InstanceConfig, options: { allowDestructive?: boolean } = {}): MigrationPlan {
5
+ const to = defineInstance(toConfig)
6
+ if (!fromConfig) return { sql: initialSchema(to), destructive: [], blocked: [], warnings: [] }
7
+ const from = defineInstance(fromConfig)
8
+ if (from.id !== to.id) throw new Error('Cannot migrate between different instance IDs')
9
+ if (to.revision <= from.revision) throw new Error('Target revision must increase')
10
+ const sql: string[] = []; const destructive: string[] = []; const blocked: string[] = []; const warnings: string[] = []
11
+ // Visit removed parents first, then reverse: every child is dropped before its refs.
12
+ const removed = new Set(Object.keys(from.entities).filter(name => !to.entities[name]))
13
+ const visited = new Set<string>(); const visiting = new Set<string>(); const parentsFirst: string[] = []
14
+ function visit(name: string) {
15
+ if (visited.has(name)) return
16
+ if (visiting.has(name)) { blocked.push(`Cyclic table removals require a manually reviewed foreign_keys migration: ${name}`); return }
17
+ visiting.add(name)
18
+ for (const field of Object.values(from.entities[name].fields)) if (field.type === 'ref' && removed.has(field.entity!)) visit(field.entity!)
19
+ visiting.delete(name); visited.add(name); parentsFirst.push(name)
20
+ }
21
+ for (const name of removed) visit(name)
22
+ if (options.allowDestructive) for (const name of parentsFirst.reverse()) sql.push(`DROP TABLE ${quote(name)};`)
23
+ for (const [name, previous] of Object.entries(from.entities)) {
24
+ if (!to.entities[name]) {
25
+ destructive.push(`DROP TABLE ${name}`)
26
+ if (Object.values(to.entities).some(e => Object.values(e.fields).some(f => f.entity === name))) blocked.push(`Referenced table cannot be removed: ${name}`)
27
+ continue
28
+ }
29
+ const next = to.entities[name]
30
+ const renamed = new Set<string>()
31
+ for (const [key, field] of Object.entries(next.fields)) {
32
+ if (field.renameFrom && field.renameFrom !== key && previous.fields[key] && previous.fields[field.renameFrom]) { blocked.push(`Rename target already exists: ${name}.${key}`); continue }
33
+ const oldKey = field.renameFrom && !previous.fields[key] ? field.renameFrom : key
34
+ const old = previous.fields[oldKey]
35
+ if (oldKey !== key) {
36
+ if (!old || next.fields[oldKey] || renamed.has(oldKey)) { blocked.push(`Ambiguous rename: ${name}.${oldKey} -> ${key}`); continue }
37
+ renamed.add(oldKey)
38
+ sql.push(`ALTER TABLE ${quote(name)} RENAME COLUMN ${quote(oldKey)} TO ${quote(key)};`)
39
+ if (old.type === 'ref') {
40
+ sql.push(`DROP INDEX ${quote(`${name}_${oldKey}_idx`)};`)
41
+ sql.push(`CREATE INDEX ${quote(`${name}_${key}_idx`)} ON ${quote(name)}(organization_id, ${quote(key)});`)
42
+ }
43
+ }
44
+ if (old) {
45
+ const physical = (f: typeof field) => ({ type: f.type, required: f.required, values: f.values, entity: f.entity, default: f.default, min: f.min })
46
+ if (JSON.stringify(physical(old)) !== JSON.stringify(physical(field))) {
47
+ destructive.push(`ALTER definition ${name}.${key}`)
48
+ blocked.push(`Changing an existing column's type/default/constraints requires a manually reviewed migration: ${name}.${key}`)
49
+ }
50
+ } else {
51
+ if (field.type === 'ref') { blocked.push(`Adding a composite reference requires a manually reviewed migration: ${name}.${key}`); continue }
52
+ if (field.required && (field.default === undefined || field.default === null)) { blocked.push(`Required added field needs a non-null backfill default: ${name}.${key}`); continue }
53
+ sql.push(`ALTER TABLE ${quote(name)} ADD COLUMN ${column(key, field)};`)
54
+ if (field.backfillFrom) {
55
+ const ref = next.fields[field.backfillFrom.refField]
56
+ const source = `(SELECT source.${quote(field.backfillFrom.valueField)} FROM ${quote(ref.entity!)} source WHERE source.organization_id = ${quote(name)}.organization_id AND source.id = ${quote(name)}.${quote(field.backfillFrom.refField)})`
57
+ const value = field.required && field.default !== undefined ? `COALESCE(${source}, ${literal(field.default)})` : source
58
+ sql.push(`UPDATE ${quote(name)} SET ${quote(key)} = ${value};`)
59
+ }
60
+ }
61
+ }
62
+ for (const [key, field] of Object.entries(previous.fields)) {
63
+ if (next.fields[key] || renamed.has(key)) continue
64
+ destructive.push(`DROP COLUMN ${name}.${key}`)
65
+ if (field.type === 'ref' || previous.checks.some(c => c.left === key || c.right === key)) blocked.push(`Constraint-bearing column removal requires a manually reviewed migration: ${name}.${key}`)
66
+ else if (options.allowDestructive) sql.push(`ALTER TABLE ${quote(name)} DROP COLUMN ${quote(key)};`)
67
+ }
68
+ const normalizedChecks = previous.checks.map(c => ({ ...c, left: Object.entries(next.fields).find(([, f]) => f.renameFrom === c.left)?.[0] ?? c.left, right: Object.entries(next.fields).find(([, f]) => f.renameFrom === c.right)?.[0] ?? c.right }))
69
+ if (JSON.stringify(normalizedChecks) !== JSON.stringify(next.checks)) blocked.push(`Changing table checks requires a manually reviewed migration: ${name}`)
70
+ }
71
+ for (const [name, entity] of Object.entries(to.entities)) if (!from.entities[name]) sql.push(createEntity(name, entity))
72
+ if (destructive.length && !options.allowDestructive) blocked.push('Destructive operations require --allow-destructive')
73
+ if (destructive.length) warnings.push('Review destructive operations and take a backup before applying; this planner never applies SQL.')
74
+ if (blocked.length) return { sql: `-- BLOCKED: ${blocked.join('\n-- ')}\n`, destructive, blocked, warnings }
75
+ sql.push(revisionSQL(to.revision))
76
+ return { sql: `-- ${from.id}: revision ${from.revision} -> ${to.revision}\n${sql.join('\n')}\n`, destructive, blocked, warnings }
77
+ }
@@ -0,0 +1,85 @@
1
+ import { workflowSchema } from '../workflow-schema'
2
+ import { opsSchema } from '../ops-schema'
3
+ import { betterAuthSchema } from './better-auth-schema'
4
+ import { emailDeliverySchema } from './email-delivery-schema'
5
+ import { CORE_VERSION, type Field, type InstanceConfig } from '../config'
6
+ export function quote(name: string) {
7
+ if (!/^[a-z][a-z0-9_]*$/.test(name)) throw new Error(`Invalid SQL identifier: ${name}`)
8
+ return `"${name}"`
9
+ }
10
+ export function literal(value: unknown): string {
11
+ if (value === null) return 'NULL'
12
+ if (typeof value === 'boolean') return value ? '1' : '0'
13
+ if (typeof value === 'number' && Number.isFinite(value)) return String(value)
14
+ if (typeof value === 'string') return `'${value.replaceAll("'", "''")}'`
15
+ throw new Error('Unsupported SQL literal')
16
+ }
17
+ export function column(name: string, f: Field) {
18
+ const q = quote(name)
19
+ const type = ['int', 'bool'].includes(f.type) ? 'INTEGER' : f.type === 'float' ? 'REAL' : 'TEXT'
20
+ return `${q} ${type}${f.required ? ' NOT NULL' : ''}${f.default !== undefined ? ` DEFAULT ${literal(f.default)}` : ''}${f.type === 'enum' ? ` CHECK (${q} IN (${f.values!.map(literal).join(', ')}))` : ''}${f.type === 'bool' ? ` CHECK (${q} IN (0,1))` : ''}${f.min !== undefined ? ` CHECK (${q} >= ${literal(f.min)})` : ''}`
21
+ }
22
+ export function createEntity(name: string, entity: InstanceConfig['entities'][string]) {
23
+ const columns = [
24
+ 'id TEXT PRIMARY KEY', 'organization_id TEXT NOT NULL REFERENCES organizations(id)',
25
+ 'created_at TEXT NOT NULL', 'updated_at TEXT NOT NULL', 'version INTEGER NOT NULL DEFAULT 1',
26
+ ...Object.entries(entity.fields).map(([k, f]) => column(k, f)), 'UNIQUE (organization_id, id)',
27
+ ...Object.entries(entity.fields).filter(([, f]) => f.type === 'ref').map(([k, f]) => `FOREIGN KEY (organization_id, ${quote(k)}) REFERENCES ${quote(f.entity!)}(organization_id, id)`),
28
+ ...entity.checks.map(c => `CHECK (${quote(c.left)} ${c.op} ${quote(c.right)})`),
29
+ ]
30
+ return `CREATE TABLE ${quote(name)} (\n ${columns.join(',\n ')}\n);\nCREATE INDEX ${quote(`${name}_org_idx`)} ON ${quote(name)}(organization_id, id);\n` + Object.entries(entity.fields).filter(([, f]) => f.type === 'ref').map(([k]) => `CREATE INDEX ${quote(`${name}_${k}_idx`)} ON ${quote(name)}(organization_id, ${quote(k)});`).join('\n')
31
+ }
32
+ export const systemSchema = `
33
+ CREATE TABLE atomic_assert (run_id TEXT NOT NULL, rule TEXT NOT NULL, step INTEGER NOT NULL DEFAULT 0, ok INTEGER NOT NULL CHECK (ok = 1), policy_ok INTEGER NOT NULL DEFAULT 1 CHECK (policy_ok = 1), actor_ok INTEGER NOT NULL DEFAULT 1 CHECK (actor_ok = 1), PRIMARY KEY (run_id, step)) WITHOUT ROWID;
34
+ CREATE TABLE organizations (id TEXT PRIMARY KEY, name TEXT NOT NULL);
35
+ CREATE TABLE users (id TEXT PRIMARY KEY, email TEXT NOT NULL UNIQUE, password_hash TEXT NOT NULL, salt TEXT NOT NULL, created_at TEXT NOT NULL);
36
+ CREATE TABLE memberships (user_id TEXT NOT NULL REFERENCES users(id), organization_id TEXT NOT NULL REFERENCES organizations(id), role TEXT NOT NULL CHECK (role IN ('owner','dispatcher','viewer')), PRIMARY KEY (user_id, organization_id));
37
+ CREATE TABLE sessions (token_hash TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id), expires_at TEXT NOT NULL);
38
+ CREATE INDEX sessions_user_idx ON sessions(user_id);
39
+ CREATE TABLE invitations (id TEXT PRIMARY KEY, organization_id TEXT NOT NULL REFERENCES organizations(id), email TEXT NOT NULL, role TEXT NOT NULL CHECK (role IN ('owner','dispatcher','viewer')), token_hash TEXT NOT NULL UNIQUE, expires_at TEXT NOT NULL, accepted_at TEXT, accepted_user_id TEXT REFERENCES users(id), inviter_id TEXT NOT NULL REFERENCES users(id));
40
+ CREATE INDEX invitations_org_idx ON invitations(organization_id);
41
+ CREATE TABLE email_outbox (id TEXT PRIMARY KEY, organization_id TEXT NOT NULL REFERENCES organizations(id), recipient TEXT NOT NULL, subject TEXT NOT NULL, body TEXT NOT NULL, created_at TEXT NOT NULL);
42
+ CREATE TABLE audit_outbox (event_id TEXT PRIMARY KEY, organization_id TEXT NOT NULL, payload TEXT NOT NULL CHECK(json_valid(payload)), created_at TEXT NOT NULL, delivered_at TEXT, attempts INTEGER NOT NULL DEFAULT 0, last_error TEXT);
43
+ CREATE INDEX audit_outbox_pending_idx ON audit_outbox(delivered_at, created_at);
44
+ CREATE TABLE security_log (id TEXT PRIMARY KEY, organization_id TEXT, actor_id TEXT, operation TEXT NOT NULL, status INTEGER NOT NULL, correlation_id TEXT NOT NULL, occurred_at TEXT NOT NULL, requested_scope_hash TEXT);
45
+ CREATE INDEX security_log_org_idx ON security_log(organization_id, occurred_at);
46
+ CREATE TABLE idempotency_keys (organization_id TEXT NOT NULL, key TEXT NOT NULL, command TEXT NOT NULL, response_json TEXT NOT NULL, request_hash TEXT, PRIMARY KEY (organization_id, key));
47
+ CREATE TABLE webhook_deliveries (event_id TEXT PRIMARY KEY, organization_id TEXT NOT NULL, payload TEXT NOT NULL, state TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0, next_attempt_at TEXT NOT NULL, last_error TEXT, lease_until TEXT);
48
+ CREATE INDEX webhook_pending_idx ON webhook_deliveries(state, next_attempt_at);
49
+
50
+ ALTER TABLE invitations ADD COLUMN revoked_at TEXT;
51
+ ALTER TABLE invitations ADD COLUMN created_at TEXT;
52
+ CREATE TABLE identities (
53
+ user_id TEXT NOT NULL REFERENCES users(id), provider TEXT NOT NULL, issuer TEXT NOT NULL,
54
+ subject TEXT NOT NULL, created_at TEXT NOT NULL, UNIQUE(provider, issuer, subject)
55
+ );
56
+ CREATE INDEX identities_user_idx ON identities(user_id);
57
+ INSERT INTO identities (user_id,provider,issuer,subject,created_at) SELECT id,'local','local',id,created_at FROM users;
58
+ CREATE TABLE access_tokens (
59
+ id TEXT PRIMARY KEY, organization_id TEXT NOT NULL REFERENCES organizations(id),
60
+ issuer_id TEXT NOT NULL REFERENCES users(id), name TEXT NOT NULL,
61
+ token_hash TEXT NOT NULL UNIQUE, prefix TEXT NOT NULL,
62
+ role TEXT NOT NULL CHECK(role IN ('owner','dispatcher','viewer')),
63
+ operations TEXT CHECK(operations IS NULL OR (json_valid(operations) AND json_type(operations)='array')),
64
+ expires_at TEXT NOT NULL, revoked_at TEXT, last_used_at TEXT, created_at TEXT NOT NULL
65
+ );
66
+ CREATE INDEX access_tokens_org_idx ON access_tokens(organization_id);
67
+ CREATE INDEX memberships_org_role_idx ON memberships(organization_id,role);
68
+ CREATE TABLE instance_meta (revision INTEGER PRIMARY KEY, core_version TEXT NOT NULL, applied_at TEXT NOT NULL);
69
+ `
70
+ export const revisionSQL = (revision: number) => `INSERT INTO instance_meta VALUES (${revision}, '${CORE_VERSION}', strftime('%Y-%m-%dT%H:%M:%fZ','now'));`
71
+ export const initialSchema = (config: InstanceConfig) => configuredSystemSchema(config) + opsSchema + (config.account?.entity === 'users' ? betterAuthSchema.replace('user_id TEXT NOT NULL REFERENCES users(id)', 'user_id TEXT NOT NULL REFERENCES "user"(id)') : betterAuthSchema) + emailDeliverySchema + workflowSchema + Object.entries(config.entities).filter(([n]) => !(n === 'users' && config.account?.entity === n)).map(([n, e]) => createEntity(n, e)).join('\n') + '\n' + revisionSQL(config.revision) + '\n'
72
+
73
+ /** Fresh schemas support configured application roles and the explicit users/account extension.
74
+ * Existing installations keep their append-only migration chain. */
75
+ function configuredSystemSchema(config: InstanceConfig) {
76
+ let sql = systemSchema.replaceAll("'owner','dispatcher','viewer'", [...new Set(['owner', 'dispatcher', 'viewer', ...config.roles])].map(literal).join(','))
77
+ if (config.account?.entity === 'users') {
78
+ const domain = createEntity('users', config.entities.users)
79
+ .replace('id TEXT PRIMARY KEY,', "id TEXT PRIMARY KEY, email TEXT UNIQUE, password_hash TEXT NOT NULL DEFAULT '', salt TEXT NOT NULL DEFAULT '',")
80
+ sql = sql.replace(/CREATE TABLE users \([^;]+;/, domain)
81
+ .replace("INSERT INTO identities (user_id,provider,issuer,subject,created_at) SELECT id,'local','local',id,created_at FROM users;", '')
82
+ .replace('CREATE TABLE identities (\n user_id TEXT NOT NULL REFERENCES users(id)', 'CREATE TABLE identities (\n user_id TEXT NOT NULL REFERENCES "user"(id)')
83
+ }
84
+ return sql
85
+ }
@@ -0,0 +1,28 @@
1
+ /** Browser-safe projections: no executable config, credentials or database bindings. */
2
+ export interface ConfigVersion {
3
+ revision: number
4
+ date?: string
5
+ commit?: string
6
+ rollbackTo?: number
7
+ config: Record<string, unknown>
8
+ }
9
+ export interface ConfigChange {
10
+ kind: 'entity' | 'field' | 'view' | 'config'
11
+ path: string
12
+ change: 'added' | 'removed' | 'changed'
13
+ before?: unknown
14
+ after?: unknown
15
+ }
16
+ export interface VersionHistory {
17
+ instance: string
18
+ currentRevision: number
19
+ versions: {
20
+ revision: number
21
+ date?: string
22
+ commit?: string
23
+ rollbackTo?: number
24
+ predecessor?: number
25
+ changes: ConfigChange[]
26
+ rollback: { sql: string; destructive: string[]; blocked: string[]; warnings: string[]; unchanged: boolean; newRevision: number }
27
+ }[]
28
+ }
@@ -0,0 +1,90 @@
1
+ import { cloneInstanceConfig, defineInstance, serializableInstanceConfig, type InstanceConfig } from '../config'
2
+ import { plan, type MigrationPlan } from './planner'
3
+
4
+ import type { ConfigVersion, ConfigChange, VersionHistory } from './version-contract'
5
+ export type { ConfigVersion, ConfigChange, VersionHistory } from './version-contract'
6
+
7
+ export const versionData = (config: InstanceConfig): Record<string, unknown> => {
8
+ const { plugins: _plugins, revision: _revision, ...data } = serializableInstanceConfig(config)
9
+ return JSON.parse(JSON.stringify({ ...data, ...(config.plugins ? { plugins: config.plugins.map(({ name, version, provides, requires, optionalRequires, configuration }) => ({ name, version, provides, requires, optionalRequires, configuration })) } : {}) }))
10
+ }
11
+ const stable = (value: unknown): string => JSON.stringify(value && typeof value === 'object'
12
+ ? Array.isArray(value) ? value.map(item => JSON.parse(stable(item))) : Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a.localeCompare(b)).map(([key, v]) => [key, JSON.parse(stable(v))])) : value ?? null)
13
+ export const equalVersionData = (a: Record<string, unknown>, b: Record<string, unknown>) => stable(a) === stable(b)
14
+ export const sameVersionData = (a: InstanceConfig, b: InstanceConfig) => stable(versionData(a)) === stable(versionData(b))
15
+
16
+ /** Stable structured values, rather than a text diff of source formatting. */
17
+ export function diffVersions(before: Record<string, any> | null, after: Record<string, any>): ConfigChange[] {
18
+ const changes: ConfigChange[] = []
19
+ const compare = (kind: ConfigChange['kind'], prefix: string, a: Record<string, unknown> = {}, b: Record<string, unknown> = {}) => {
20
+ for (const key of [...new Set([...Object.keys(a), ...Object.keys(b)])].sort()) {
21
+ if (stable(a[key]) === stable(b[key]) && Object.hasOwn(a, key) === Object.hasOwn(b, key)) continue
22
+ changes.push({ kind, path: `${prefix}${key}`, change: !Object.hasOwn(a, key) ? 'added' : !Object.hasOwn(b, key) ? 'removed' : 'changed',
23
+ ...(Object.hasOwn(a, key) ? { before: a[key] } : {}), ...(Object.hasOwn(b, key) ? { after: b[key] } : {}) })
24
+ }
25
+ }
26
+ const a = before ?? {}; compare('entity', 'entities.', a.entities, after.entities)
27
+ for (const entity of Object.keys(after.entities ?? {})) {
28
+ if (a.entities?.[entity]) {
29
+ const { fields: oldFields, ...oldMeta } = a.entities[entity]
30
+ const { fields: newFields, ...newMeta } = after.entities[entity]
31
+ const index = changes.findIndex(c => c.path === `entities.${entity}`)
32
+ if (index !== -1 && stable(oldMeta) === stable(newMeta)) changes.splice(index, 1)
33
+ else if (index !== -1) changes[index] = { kind: 'entity', path: `entities.${entity}`, change: 'changed', before: oldMeta, after: newMeta }
34
+ compare('field', `entities.${entity}.fields.`, oldFields, newFields)
35
+ } else compare('field', `entities.${entity}.fields.`, {}, after.entities[entity].fields)
36
+ }
37
+ for (const entity of Object.keys(a.entities ?? {})) if (!after.entities?.[entity]) compare('field', `entities.${entity}.fields.`, a.entities[entity].fields, {})
38
+ for (const entity of [...new Set([...Object.keys(a.ui?.entities ?? {}), ...Object.keys(after.ui?.entities ?? {})])].sort()) {
39
+ const views = (data: any) => Object.fromEntries((data?.ui?.entities?.[entity]?.views ?? []).map((v: any) => [v.id ?? v.kind, v]))
40
+ const presets = (data: any) => Object.fromEntries((data?.ui?.entities?.[entity]?.list?.views ?? []).map((v: any) => [v.id ?? v.kind, v]))
41
+ compare('view', `ui.entities.${entity}.views.`, views(a), views(after))
42
+ compare('view', `ui.entities.${entity}.list.views.`, presets(a), presets(after))
43
+ }
44
+ const { entities: _a, ui: _au, ...restA } = a; const { entities: _b, ui: _bu, ...restB } = after
45
+ compare('config', '', restA, restB)
46
+ const remainingUi = (data: any) => {
47
+ if (!data.ui) return {}
48
+ const { entities, ...restUi } = data.ui
49
+ const hints = Object.fromEntries(Object.entries(entities ?? {}).flatMap(([key, value]: [string, any]) => {
50
+ const { views: _views, list, ...rest } = value
51
+ const { views: _presets, ...remainingList } = list ?? {}
52
+ const remaining = { ...rest, ...(Object.keys(remainingList).length ? { list: remainingList } : {}) }
53
+ return Object.keys(remaining).length ? [[key, remaining]] : []
54
+ }))
55
+ return { ...restUi, ...(Object.keys(hints).length ? { entities: hints } : {}) }
56
+ }
57
+ compare('config', 'ui.', remainingUi(a), remainingUi(after))
58
+ return changes
59
+ }
60
+
61
+ export const unchangedRollbackPlan = (revision: number): MigrationPlan => ({ sql: `-- Configuration already matches v${revision}; no version or migration will be created.\n`, blocked: [], destructive: [], warnings: [] })
62
+
63
+ export function planRollback(current: InstanceConfig, historical: InstanceConfig, options: { allowDestructive?: boolean } = {}): { target: InstanceConfig; plan: MigrationPlan; unchanged: boolean } {
64
+ if (current.id !== historical.id) throw new Error('Cannot roll back between different instance IDs')
65
+ if (historical.revision > current.revision) throw new Error('Rollback target must be an existing revision')
66
+ const target = cloneInstanceConfig(historical)
67
+ target.revision = current.revision + 1
68
+ const unchanged = sameVersionData(current, historical)
69
+ const migration = plan(current, target, options)
70
+ if (migration.destructive.length) migration.warnings.unshift('Rollback may delete populated tables or columns. No live data was inspected; all drops require explicit --allow-destructive and prior contract review.')
71
+ return { target, plan: migration, unchanged }
72
+ }
73
+
74
+ export function versionHistory(current: InstanceConfig, history: readonly ConfigVersion[]): VersionHistory {
75
+ const versions = [...history].sort((a, b) => a.revision - b.revision)
76
+ if (new Set(versions.map(v => v.revision)).size !== versions.length) throw new Error('Duplicate config version')
77
+ if (versions.some(v => !Number.isSafeInteger(v.revision) || v.revision < 1 || v.config.id !== current.id || v.revision > current.revision)) throw new Error('Invalid config history')
78
+ const live: ConfigVersion = { revision: current.revision, config: versionData(current) }
79
+ const index = versions.findIndex(v => v.revision === current.revision)
80
+ if (index === -1) versions.push(live)
81
+ else versions[index] = { ...versions[index], config: live.config }
82
+ return { instance: current.id, currentRevision: current.revision, versions: versions.map((version, i) => {
83
+ const historical = defineInstance({ ...version.config, revision: version.revision, plugins: undefined, pluginConfig: undefined, interactive: false } as unknown as InstanceConfig)
84
+ const rollback = planRollback({ ...current, plugins: undefined, pluginConfig: undefined, interactive: false }, historical)
85
+ const unchanged = equalVersionData(version.config, versionData(current))
86
+ return { revision: version.revision, date: version.date, commit: version.commit, rollbackTo: version.rollbackTo,
87
+ predecessor: versions[i - 1]?.revision, changes: diffVersions(versions[i - 1]?.config ?? null, version.config),
88
+ rollback: { ...(unchanged ? unchangedRollbackPlan(current.revision) : rollback.plan), unchanged, newRevision: unchanged ? current.revision : rollback.target.revision } }
89
+ }) }
90
+ }
@@ -0,0 +1,13 @@
1
+ // Framework operational relay metadata.
2
+ export const opsSchema = `
3
+ CREATE TABLE _ops_relay_run (
4
+ id INTEGER PRIMARY KEY CHECK (id = 1),
5
+ ts TEXT NOT NULL,
6
+ backlog INTEGER NOT NULL,
7
+ oldest_age_seconds INTEGER,
8
+ failed INTEGER NOT NULL,
9
+ delivered INTEGER NOT NULL,
10
+ webhook_delivered INTEGER NOT NULL,
11
+ errors INTEGER NOT NULL
12
+ );
13
+ `
package/src/ops.ts ADDED
@@ -0,0 +1,34 @@
1
+ import { queryMetrics } from './query/observability'
2
+ import type { RuntimeEnv } from './types'
3
+ import { outboxStats } from './audit'
4
+ import { schemaStatus } from './schema-compatibility'
5
+ import type { InstanceConfig } from './config'
6
+ export async function relayMetrics(env: RuntimeEnv, now = Date.now()) {
7
+ const stats = await outboxStats(env.DB, now)
8
+ const failures = await env.DB.prepare("SELECT count(*) AS failed FROM webhook_deliveries WHERE state='failed'").first<{ failed: number }>()
9
+ const errors = await env.DB.prepare('SELECT count(*) AS failed FROM audit_outbox WHERE delivered_at IS NULL AND last_error IS NOT NULL').first<{ failed: number }>()
10
+ return { backlog: stats.backlog, oldestAgeSeconds: stats.oldest_undelivered_age_seconds, failed: (failures?.failed ?? 0) + (errors?.failed ?? 0) }
11
+ }
12
+ export async function recordRelayRun(env: RuntimeEnv, metrics: Awaited<ReturnType<typeof relayMetrics>> & { delivered: number; webhookDelivered: number; errors: number }) {
13
+ await env.DB.prepare('INSERT INTO _ops_relay_run (id,ts,backlog,oldest_age_seconds,failed,delivered,webhook_delivered,errors) VALUES (1,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET ts=excluded.ts,backlog=excluded.backlog,oldest_age_seconds=excluded.oldest_age_seconds,failed=excluded.failed,delivered=excluded.delivered,webhook_delivered=excluded.webhook_delivered,errors=excluded.errors')
14
+ .bind(new Date().toISOString(), metrics.backlog, metrics.oldestAgeSeconds, metrics.failed, metrics.delivered, metrics.webhookDelivered, metrics.errors).run()
15
+ }
16
+ async function lastRelayRun(env: RuntimeEnv) {
17
+ try {
18
+ const row = await env.DB.prepare('SELECT ts,backlog,oldest_age_seconds AS oldestAgeSeconds,failed,delivered,webhook_delivered AS webhookDelivered,errors FROM _ops_relay_run WHERE id=1').first()
19
+ return row
20
+ } catch { return null } // Local-only schema fixtures may omit the optional cron snapshot.
21
+ }
22
+ const tables = async (db: D1Database) => (await db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all<{ name: string }>()).results.map(row => row.name)
23
+ export async function opsStatus(env: RuntimeEnv, config: InstanceConfig) {
24
+ let webhookServiceHealthy = false
25
+ try {
26
+ const response = await env.WEBHOOK_SERVICE?.fetch('https://webhook.internal/health', { signal: AbortSignal.timeout(3000) })
27
+ webhookServiceHealthy = response?.ok === true
28
+ await response?.body?.cancel()
29
+ } catch { /* Presence alone cannot prove the binding target is healthy. */ }
30
+ return { queries: queryMetrics(env.DB), ...(await relayMetrics(env)), lastRun: await lastRelayRun(env), webhookServiceHealthy, schema: await schemaStatus(env, config),
31
+ tables: { DB: await tables(env.DB) },
32
+ bindings: { EVENTS_QUEUE: typeof env.EVENTS_QUEUE?.sendBatch === 'function', DB: !!env.DB, AUDIT_KV: !!env.AUDIT_KV, WEBHOOK_SERVICE: typeof env.WEBHOOK_SERVICE?.fetch === 'function', INTERNAL_TOKEN: !!env.INTERNAL_TOKEN, WEBHOOK_URL: !!env.WEBHOOK_URL, WEBHOOK_ALLOWED_HOSTS: !!env.WEBHOOK_ALLOWED_HOSTS, BETTER_AUTH_SECRET: !!env.BETTER_AUTH_SECRET, AUTH_BASE_URL: !!env.AUTH_BASE_URL },
33
+ }
34
+ }
@@ -0,0 +1,13 @@
1
+ import type { InstanceConfig, OrganizationAction } from './config'
2
+ import type { Scope } from './types'
3
+ import { ApiError } from './errors'
4
+
5
+ export const isOrganizationAdministrator = (config: InstanceConfig, role: string) => role === 'owner' || role === config.organizationOwnerRole
6
+ /** Preserve the existing role ranks, with the configured owner above ordinary roles. */
7
+ export const organizationRoleRank = (config: InstanceConfig, role: string) => isOrganizationAdministrator(config, role) ? 2 : role === 'dispatcher' ? 1 : 0
8
+ export function organizationPermission(config: InstanceConfig, scope: Scope, action: OrganizationAction) {
9
+ if (scope.actor.type !== 'user') throw new ApiError(403, 'user_required')
10
+ if ((action === 'members.read' || action === 'invitations.read') && config.roles.includes(scope.role)) return
11
+ if (!Object.hasOwn(config.organizationPermissions, scope.role) || !config.organizationPermissions[scope.role].includes(action)) throw new ApiError(403, 'permission_denied')
12
+ if (action !== 'members.read' && !action.startsWith('invitations.') && !isOrganizationAdministrator(config, scope.role)) throw new ApiError(403, 'owner_required')
13
+ }