@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,2 @@
1
+ export interface Actor { type: 'user' | 'agent' | 'service'; id: string; tokenId?: string }
2
+ export interface Scope { organizationId: string; actor: Actor; role: string; correlationId: string }
package/src/index.ts ADDED
@@ -0,0 +1,32 @@
1
+ export * from './config'
2
+ export * from './migrations/schema'
3
+ export * from './app'
4
+ export * from './types'
5
+ export * from './events'
6
+ export * from './crypto'
7
+ export * from './crud'
8
+ export * from './errors'
9
+ export * from './audit'
10
+ export * from './relay'
11
+ export * from './migrations/planner'
12
+ export { defineCommand, createCommandRegistry } from './commands'
13
+ export type { CommandDefinition, CommandRegistry } from './commands'
14
+
15
+ export * from './authorization-api'
16
+ export * from './identity'
17
+
18
+ export * from "./authorized-execution"
19
+ export * from './execution'
20
+ export * from './identity-providers'
21
+
22
+ export * from './workflow-runtime'
23
+
24
+ export * from './kernel/plugin'
25
+ export * from './kernel/registry'
26
+ export { tenancy } from './kernel/adapters/tenancy'
27
+
28
+ export type { ShorthandInput, ShorthandEntity, FieldShorthand, RelationShorthand, OperationShorthand, PermissionDeclaration, PermissionShorthand, PolicyScope, PolicyShorthand } from './config-shorthand'
29
+ export { expand } from './config-shorthand'
30
+
31
+ export { consumeEvents } from './event-delivery'
32
+ export type { AuditOutboxRow } from './kernel/audit-port'
@@ -0,0 +1,22 @@
1
+ import { getCookie } from 'hono/cookie'
2
+ import type { MiddlewareHandler } from 'hono'
3
+ import { SESSION_COOKIE } from './session-contract'
4
+ import type { AppEnv, RuntimeEnv } from './types'
5
+ import { assertIdentityTransport } from './identity-settings'
6
+ import { ApiError } from './errors'
7
+
8
+ /** Bearer takes precedence in Better Auth. Invalid Bearers must not fall back to cookies. */
9
+ export function jsonCookieCSRF(env: RuntimeEnv): MiddlewareHandler<AppEnv> {
10
+ return async (c, next) => {
11
+ if (!['GET', 'HEAD', 'OPTIONS'].includes(c.req.method) && getCookie(c, SESSION_COOKIE)) {
12
+ if (!['localhost', '127.0.0.1', '[::1]'].includes(new URL(c.req.url).hostname)) assertIdentityTransport(c.req.raw, c.req.path.startsWith('/auth/') ? 403 : 401)
13
+ const authorization = c.req.header('Authorization')
14
+ if (!authorization?.startsWith('Bearer ') || !authorization.slice(7).trim()) {
15
+ const allowed = env.IDENTITY?.baseURL ?? env.AUTH_BASE_URL ?? new URL(c.req.url).origin
16
+ if (c.req.header('Origin') !== allowed || c.req.header('Sec-Fetch-Site') !== 'same-origin' ||
17
+ c.req.header('Content-Type')?.split(';')[0].trim().toLowerCase() !== 'application/json') throw new ApiError(403, 'csrf_failed')
18
+ }
19
+ }
20
+ await next()
21
+ }
22
+ }
@@ -0,0 +1,8 @@
1
+ import { builtinPlugin } from '../builtin-source'
2
+ import type { WorkbasePlugin } from '../plugin'
3
+ /** Scope must already have passed requireScope; a client org is only a selector. */
4
+ export const tenancy: WorkbasePlugin = builtinPlugin({
5
+ name: 'tenancy', version: '0.1.0', provides: { organizations: '1.x' }, requires: { identity: '^1' },
6
+ policyInConfig: true,
7
+ tableFilter: (_entity, scope) => ({ kind: 'where', predicate: { organization_id: { eq: scope.organizationId } } }),
8
+ })
@@ -0,0 +1,12 @@
1
+ import type { AuditEvent } from '../audit-event'
2
+ import type { RuntimeEnv } from '../types'
3
+
4
+ export interface AuditOutboxRow { event_id: string; organization_id: string; payload: string }
5
+ export interface AuditSink { insert(event: AuditEvent): Promise<number | void> }
6
+ export interface AuditRelayOptions {
7
+ sweep?: boolean; sink?: AuditSink; now?: number; failBeforeSinkInsert?: boolean; failAfterSinkInsert?: boolean
8
+ }
9
+ export interface AuditPort {
10
+ deliver(env: RuntimeEnv, row: AuditOutboxRow, options?: AuditRelayOptions): Promise<void>
11
+ relay(env: RuntimeEnv, options?: AuditRelayOptions): Promise<{ delivered: number; errors: number }>
12
+ }
@@ -0,0 +1,34 @@
1
+ import type { WorkbasePlugin } from './plugin'
2
+
3
+ // tsImport loads isolated module copies in one realm. Keep provenance across
4
+ // those copies without accepting names, structural lookalikes or copied hooks.
5
+ const key = Symbol.for('workbase.builtin-plugin-sources')
6
+ const shared = globalThis as unknown as Record<symbol, WeakSet<object>>
7
+ const sources = shared[key] ??= new WeakSet<object>()
8
+ export function builtinPlugin(plugin: WorkbasePlugin): WorkbasePlugin {
9
+ // Canonical source cannot describe contributions that callers can replace in
10
+ // place. Freeze plain descriptor data, leaving Zod instances/lazy caches alone.
11
+ const seen = new WeakSet<object>()
12
+ const freezeData = (value: unknown): void => {
13
+ if (!value || typeof value !== 'object' || seen.has(value)) return
14
+ const prototype = Object.getPrototypeOf(value)
15
+ if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) return
16
+ seen.add(value)
17
+ for (const child of Object.values(value)) freezeData(child)
18
+ Object.freeze(value)
19
+ }
20
+ freezeData(plugin.contributes)
21
+ freezeData(plugin.model)
22
+ freezeData(plugin.commands)
23
+ freezeData(plugin.workflows)
24
+ // Zod populates lazy method caches; only descriptor data is frozen.
25
+ for (const key of ['provides', 'requires', 'optionalRequires', 'migrations'] as const) {
26
+ const value = plugin[key]
27
+ if (key === 'migrations') for (const migration of plugin.migrations ?? []) Object.freeze(migration)
28
+ if (value) Object.freeze(value)
29
+ }
30
+ Object.freeze(plugin)
31
+ sources.add(plugin)
32
+ return plugin
33
+ }
34
+ export function isBuiltinPlugin(plugin: WorkbasePlugin): boolean { return sources.has(plugin) }
@@ -0,0 +1,77 @@
1
+ import type { WorkbasePlugin } from './plugin'
2
+
3
+ /** Contract majors are deliberately narrower than package semver. Only login is multi-provider. */
4
+ export function resolvePlugins(input: readonly WorkbasePlugin[], interactive = false) {
5
+ const ownContracts = (plugin: WorkbasePlugin, key: 'provides' | 'requires' | 'optionalRequires') => Object.hasOwn(plugin, key) ? Object.fromEntries(Object.entries(plugin[key] ?? {})) : {}
6
+ const contracts = new Map(input.map(plugin => [plugin, ownContracts(plugin, 'provides')]))
7
+ const names = new Set<string>()
8
+ const providers = new Map<string, WorkbasePlugin[]>()
9
+ const identifier = /^[a-z][a-z0-9_-]*$/
10
+ for (const plugin of input) {
11
+ if (!identifier.test(plugin.name) || !plugin.version || names.has(plugin.name)) throw new Error(`Invalid or duplicate plugin: ${plugin.name}`)
12
+ names.add(plugin.name)
13
+ const migrations = new Set<string>()
14
+ for (const migration of plugin.migrations ?? []) {
15
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(migration.name)) throw new Error(`Invalid plugin migration: ${plugin.name}/${migration.name}`)
16
+ if (migrations.has(migration.name)) throw new Error(`Duplicate plugin migration: ${plugin.name}/${migration.name}`)
17
+ migrations.add(migration.name)
18
+ }
19
+ for (const [contract, version] of Object.entries(contracts.get(plugin)!)) {
20
+ if (!identifier.test(contract) || !/^(0|[1-9]\d*)\.x$/.test(version)) throw new Error(`Invalid contract provided by ${plugin.name}: ${contract}@${version}; expected <major>.x`)
21
+ const existing = providers.get(contract) ?? []
22
+ if (existing.length && contract !== 'login') throw new Error(`Duplicate provider for ${contract}: ${existing[0].name}, ${plugin.name}`)
23
+ if (existing.some(p => contracts.get(p)![contract] !== version)) throw new Error(`Incompatible providers for ${contract}: ${version}`)
24
+ providers.set(contract, [...existing, plugin])
25
+ }
26
+ if (plugin.contributes?.console && contracts.get(plugin)!.console !== '1.x' && ownContracts(plugin, 'requires').console !== '^1' && ownContracts(plugin, 'optionalRequires').console !== '^1') throw new Error(`Plugin ${plugin.name}: console contributions require console@^1`)
27
+ const provides = contracts.get(plugin)!
28
+ if (plugin.configure && !provides.permissions) throw new Error(`Plugin ${plugin.name}: role configuration requires the permissions contract`)
29
+ if (plugin.authorization && !provides.permissions) throw new Error(`Plugin ${plugin.name}: authorization requires the permissions contract`)
30
+ if (plugin.authenticateCredential && !provides['machine-credentials']) throw new Error(`Plugin ${plugin.name}: authenticateCredential requires the machine-credentials contract`)
31
+ if (plugin.authenticate && !provides.login) throw new Error(`Plugin ${plugin.name}: authenticate requires the login contract`)
32
+ if (plugin.mailOutbox && !provides['mail-outbox']) throw new Error(`Plugin ${plugin.name}: mailOutbox requires the mail-outbox contract`)
33
+ if (plugin.audit && !provides.audit) throw new Error(`Plugin ${plugin.name}: audit port requires the audit contract`)
34
+ if (provides.login && !ownContracts(plugin, 'requires').identity) throw new Error(`Plugin ${plugin.name}: login requires identity`)
35
+
36
+ }
37
+ for (const contract of ['mail-outbox', 'audit'] as const) for (const plugin of providers.get(contract) ?? []) {
38
+ if (contracts.get(plugin)![contract] !== '1.x' || !(contract === 'audit' ? plugin.audit : plugin.mailOutbox)) throw new Error(`Plugin ${plugin.name}: ${contract} requires a 1.x port`)
39
+ }
40
+ for (const plugin of providers.get('permissions') ?? []) {
41
+ const provides = contracts.get(plugin)!
42
+ if (provides.permissions && (provides.permissions !== '1.x' || plugin.authorization !== true || typeof plugin.tableFilter !== 'function' || typeof plugin.commandGuard !== 'function')) {
43
+ throw new Error(`Plugin ${plugin.name}: permissions requires 1.x, authorization:true, tableFilter and commandGuard`)
44
+ }
45
+ }
46
+ for (const plugin of providers.get('console') ?? []) if (contracts.get(plugin)!.console !== '1.x' || !plugin.validateConsole || !plugin.consoleRegistry) throw new Error(`Plugin ${plugin.name}: console requires a complete 1.x registry provider`)
47
+ if (interactive && !providers.has('login')) throw new Error('Interactive instance requires a login provider')
48
+ const dependencies = new Map<WorkbasePlugin, WorkbasePlugin[]>()
49
+ for (const plugin of input) {
50
+ const deps: WorkbasePlugin[] = []
51
+ for (const [required, requirements] of [[true, ownContracts(plugin, 'requires')], [false, ownContracts(plugin, 'optionalRequires')]] as const) {
52
+ for (const [contract, range] of Object.entries(requirements)) {
53
+ if (!identifier.test(contract) || !/^\^(0|[1-9]\d*)$/.test(range)) throw new Error(`Plugin ${plugin.name}: invalid requirement ${contract}@${range}; expected ^<major>`)
54
+ const matches = providers.get(contract) ?? []
55
+ if (!matches.length && required) throw new Error(`Plugin ${plugin.name}: missing required contract ${contract}@${range}`)
56
+ for (const provider of matches) {
57
+ const version = contracts.get(provider)![contract]
58
+ if (version !== `${range.slice(1)}.x`) throw new Error(`Plugin ${plugin.name}: ${contract}@${range} incompatible with ${provider.name} providing ${version}`)
59
+ deps.push(provider)
60
+ }
61
+ }
62
+ }
63
+ dependencies.set(plugin, deps)
64
+ }
65
+ const ordered: WorkbasePlugin[] = []
66
+ const visiting: WorkbasePlugin[] = []
67
+ const visited = new Set<WorkbasePlugin>()
68
+ function visit(plugin: WorkbasePlugin) {
69
+ if (visited.has(plugin)) return
70
+ if (visiting.includes(plugin)) throw new Error(`Plugin dependency cycle: ${[...visiting.slice(visiting.indexOf(plugin)), plugin].map(p => p.name).join(' -> ')}`)
71
+ visiting.push(plugin)
72
+ for (const dependency of dependencies.get(plugin)!) visit(dependency)
73
+ visiting.pop(); visited.add(plugin); ordered.push(plugin)
74
+ }
75
+ for (const plugin of input) visit(plugin)
76
+ return { plugins: Object.freeze(ordered), providers: providers as ReadonlyMap<string, readonly WorkbasePlugin[]> }
77
+ }
@@ -0,0 +1,36 @@
1
+ import type { InstanceConfig } from '../config'
2
+ import type { ResolvedActor, RuntimeEnv } from '../types'
3
+
4
+ export interface LocalUser { id: string; email: string; name?: string }
5
+ export interface ExternalIdentity { provider: string; issuer: string; subject: string }
6
+ export interface ExternalIdentityAssertion extends ExternalIdentity { email: string; emailVerified: boolean; firstName?: string; lastName?: string }
7
+ export interface ProfileSynchronization { method: string; maxLatencySeconds: number }
8
+ export interface ProfileNames { firstName: string; lastName: string }
9
+ export interface SelfProfile {
10
+ id: string
11
+ email: string
12
+ firstName: string | null
13
+ lastName: string | null
14
+ displayName: string | null
15
+ authority: { kind: 'local' | 'idp'; provider: string | null; synchronization: ProfileSynchronization | null }
16
+ capabilities: { canEditNames: boolean; canEditEmail: false }
17
+ completeness: { complete: boolean; missingFields: ('firstName' | 'lastName')[] }
18
+ syncedAt: string | null
19
+ }
20
+ export interface IdentityLink {
21
+ userId: string
22
+ external: ExternalIdentityAssertion
23
+ /** An explicit server-side confirmation; a JSON copy has no session provenance. */
24
+ confirmation?: ResolvedActor
25
+ }
26
+ export interface IdentityPort {
27
+ resolveUser(db: D1Database, userId: string): Promise<LocalUser>
28
+ resolveExternalIdentity(db: D1Database, external: ExternalIdentity): Promise<LocalUser>
29
+ linkExternalIdentity(env: RuntimeEnv, config: InstanceConfig, link: IdentityLink): Promise<void>
30
+ readProfile(db: D1Database, config: InstanceConfig, userId: string): Promise<SelfProfile>
31
+ /** Invitation hint: fills only an absent local profile, never a partial/existing or IdP profile. */
32
+ prefillProfile(env: RuntimeEnv, config: InstanceConfig, userId: string, names: ProfileNames): Promise<void>
33
+ updateProfile(env: RuntimeEnv, config: InstanceConfig, userId: string, names: ProfileNames): Promise<SelfProfile>
34
+ /** Trusted login adapter only, after credential verification and external mapping resolution. */
35
+ syncProfile(env: RuntimeEnv, config: InstanceConfig, external: ExternalIdentity, names: ProfileNames): Promise<void>
36
+ }
@@ -0,0 +1,23 @@
1
+ import type { GuardedStatement } from '../execution/types'
2
+ import type { InstanceConfig } from '../config'
3
+ import type { RuntimeEnv } from '../types'
4
+
5
+ /** Templates and credential eligibility belong to the calling plugin. */
6
+ export interface MailIntent {
7
+ id: string; organizationId: string | null; recipient: string; subject: string
8
+ body: string; text: string; html: string; expiresAt: string
9
+ /** Caller-owned display name; the shared configured mailbox remains the sender. */
10
+ senderName?: string
11
+ }
12
+ export interface MailStatus {
13
+ id: string; delivery_status: 'pending' | 'sending' | 'sent' | 'failed'
14
+ attempts: number; sent_at: string | null; last_error: string | null
15
+ }
16
+ export interface MailOutboxPort {
17
+ /** Include this statement in the caller's transaction; guard preserves mutation chaining. */
18
+ intent(message: MailIntent, guard?: string): GuardedStatement
19
+ status(db: D1Database, id: string): Promise<MailStatus | null>
20
+ /** Caller must revalidate the live credential, scope and operation before every attempt. */
21
+ deliver(env: RuntimeEnv, config: InstanceConfig, id: string, eligible: () => Promise<boolean>): Promise<void>
22
+ retry(env: RuntimeEnv, config: InstanceConfig, id: string, eligible: () => Promise<boolean>): Promise<void>
23
+ }
@@ -0,0 +1,76 @@
1
+ import { sha256 } from '../crypto'
2
+ import type { WorkbasePlugin } from './plugin'
3
+ import type { InstanceConfig } from '../config'
4
+
5
+ /** Per-plugin append-only ledgers. Absent namespaces are retained on uninstall. */
6
+ export async function applyPluginMigrations(db: D1Database, plugins: readonly WorkbasePlugin[]) {
7
+ await db.prepare('CREATE TABLE IF NOT EXISTS _plugin_migrations (namespace TEXT NOT NULL, name TEXT NOT NULL, position INTEGER NOT NULL, checksum TEXT NOT NULL, PRIMARY KEY(namespace,name), UNIQUE(namespace,position))').run()
8
+ for (const plugin of plugins) {
9
+ const migrations = plugin.migrations ?? []
10
+ const { results: applied } = await db.prepare('SELECT name,position,checksum FROM _plugin_migrations WHERE namespace=? ORDER BY position').bind(plugin.name).all<{ name: string; position: number; checksum: string }>()
11
+ const checksums = await Promise.all(migrations.map(m => sha256(m.sql)))
12
+ for (const [position, row] of applied.entries()) {
13
+ if (row.position !== position || migrations[position]?.name !== row.name) throw new Error(`Plugin migrations must be append-only: ${plugin.name}/${row.name}`)
14
+ if (checksums[position] !== row.checksum) throw new Error(`Plugin migration changed: ${plugin.name}/${row.name}`)
15
+ }
16
+ for (let position = applied.length; position < migrations.length; position++) {
17
+ const migration = migrations[position]
18
+ // D1 batch is transactional. SQL is supplied as statements by trusted plugins.
19
+ // exec supports multi-statement SQL but is not transactional with the ledger;
20
+ // prepare/batch keeps DDL, data changes and their ledger entry atomic.
21
+ const statements = splitStatements(migration.sql).map(sql => db.prepare(sql))
22
+ await db.batch([...statements, db.prepare('INSERT INTO _plugin_migrations (namespace,name,position,checksum) VALUES (?,?,?,?)').bind(plugin.name, migration.name, position, checksums[position])])
23
+ }
24
+ }
25
+ }
26
+
27
+ /** Split SQL without treating semicolons in quoted strings/comments as boundaries. */
28
+ function splitStatements(sql: string): string[] {
29
+ const statements: string[] = []
30
+ let trigger = false; let bodyStatementStart = false; let words: string[] = []
31
+ let start = 0; let depth = 0; let hasCode = false; let quote = ''; let lineComment = false; let blockComment = false
32
+ for (let i = 0; i < sql.length; i++) {
33
+ const c = sql[i], next = sql[i + 1]
34
+ if (lineComment) { if (c === '\n') lineComment = false; continue }
35
+ if (blockComment) { if (c === '*' && next === '/') { blockComment = false; i++ }; continue }
36
+ if (quote) { if (c === quote) { if (next === quote) i++; else quote = '' }; continue }
37
+ if (c === '-' && next === '-') { lineComment = true; i++; continue }
38
+ if (c === '/' && next === '*') { blockComment = true; i++; continue }
39
+ if (!/\s|;/.test(c)) hasCode = true
40
+ if (c === "'" || c === '"' || c === '`' || c === '[') { quote = c === '[' ? ']' : c; continue }
41
+ if (/[a-z_]/i.test(c)) {
42
+ const word = /^[a-z_][a-z_0-9]*/i.exec(sql.slice(i))![0]
43
+ words.push(word.toUpperCase())
44
+ if (/^CREATE (?:TEMP(?:ORARY)? )?TRIGGER$/.test(words.join(' '))) trigger = true
45
+ if (words.length === 1 && /^(BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)$/i.test(word)) throw new Error('Plugin migration transaction control is forbidden')
46
+ // A trigger closes only at the beginning of a body statement. END in
47
+ // new.end, SELECT end or ORDER BY end is an identifier, even before ';'.
48
+ if (/^CASE$/i.test(word)) depth++
49
+ else if (trigger && depth === 0 && /^BEGIN$/i.test(word)) { depth++; bodyStatementStart = true; i += word.length - 1; continue }
50
+ else if (/^END$/i.test(word) && (depth > (trigger ? 1 : 0) || (trigger && bodyStatementStart))) depth = Math.max(0, depth - 1)
51
+ bodyStatementStart = false
52
+ i += word.length - 1; continue
53
+ }
54
+ if (c === ';' && trigger && depth === 1) bodyStatementStart = true
55
+ if (c === ';' && depth === 0) { const statement = sql.slice(start, i).trim(); if (statement && hasCode) statements.push(statement); start = i + 1; hasCode = false; trigger = false; words = [] }
56
+ }
57
+ if (depth !== 0) throw new Error('Unterminated plugin migration block')
58
+ const last = sql.slice(start).trim(); if (last && hasCode) statements.push(last)
59
+ return statements
60
+ }
61
+
62
+ export interface PluginMigrationRow { namespace: string; name: string; position: number; checksum: string }
63
+ export async function expectedPluginMigrations(plugins: readonly WorkbasePlugin[]): Promise<PluginMigrationRow[]> {
64
+ const rows = await Promise.all(plugins.flatMap(plugin => (plugin.migrations ?? []).map(async (migration, position) => ({ namespace: plugin.name, name: migration.name, position, checksum: await sha256(migration.sql) }))))
65
+ return rows.sort((a, b) => a.namespace < b.namespace ? -1 : a.namespace > b.namespace ? 1 : a.position - b.position)
66
+ }
67
+ export async function pluginMigrationStatus(db: D1Database, plugins: readonly WorkbasePlugin[], config: Pick<InstanceConfig, 'entities'>) {
68
+ for (const plugin of plugins) await plugin.checkSchema?.(db, config)
69
+ const expected = await expectedPluginMigrations(plugins)
70
+ const names = new Set(plugins.map(plugin => plugin.name))
71
+ const { results } = await db.prepare('SELECT namespace,name,position,checksum FROM _plugin_migrations ORDER BY namespace,position').all<PluginMigrationRow>()
72
+ // Uninstalled namespaces remain on disk but cannot satisfy installed contracts.
73
+ const applied = results.filter(row => names.has(row.namespace))
74
+ const hash = (rows: PluginMigrationRow[]) => sha256(JSON.stringify(rows.map(({ namespace, name, position, checksum }) => ({ namespace, name, position, checksum }))))
75
+ return { expected: await hash(expected), applied: await hash(applied) }
76
+ }
@@ -0,0 +1,8 @@
1
+ import type { Operation } from '../config'
2
+
3
+ /** Keep the existing exact allowlist vocabulary for CRUD, registered commands and resources. */
4
+ export function operationName(target: { entity: string; operation: Operation } | { name: string } | { system: string }): string {
5
+ if ('name' in target) return target.name
6
+ if ('system' in target) return target.system
7
+ return `${target.entity}.${target.operation}`
8
+ }
@@ -0,0 +1,92 @@
1
+ import type { ConsoleContribution, ConsoleRegistry } from '../console-contract'
2
+ import type { IdentityPort, ProfileSynchronization } from './identity-port'
3
+ import type { MailOutboxPort } from './mail-outbox-port'
4
+ import type { AuditPort } from './audit-port'
5
+ import type { ZodType } from 'zod'
6
+ import type { InstanceConfig, InstanceInput, OrganizationAction } from '../config'
7
+ import type { CommandDefinition } from '../commands'
8
+ import type { WorkflowDefinition } from '../execution/workflow'
9
+ import type { AtomicOperation } from '../execution/types'
10
+ import type { AuditEvent } from '../audit-event'
11
+ import type { App, ResolvedActor, RuntimeEnv, Scope } from '../types'
12
+
13
+ /** Server-resolved constants only. Task 3 compiles policies/$actor into this contract. */
14
+ export type PredicateValue = string | number | boolean | null
15
+ export interface PredicateOperators {
16
+ eq?: PredicateValue; ne?: PredicateValue; in?: readonly PredicateValue[]
17
+ lt?: Exclude<PredicateValue, null>; lte?: Exclude<PredicateValue, null>
18
+ gt?: Exclude<PredicateValue, null>; gte?: Exclude<PredicateValue, null>
19
+ contains?: string; isNull?: boolean
20
+ }
21
+ /** Child field correlates to parentField on the current table; identifiers are server-owned. */
22
+ export interface PredicateRelation { entity: string; field: string; parentField: string; predicate: Predicate }
23
+ export type Predicate = { all: readonly Predicate[] } | { any: readonly Predicate[] }
24
+ | { not: Predicate } | { exists: PredicateRelation } | { notExists: PredicateRelation }
25
+ | { [field: string]: PredicateOperators }
26
+ export type TableFilter = { kind: 'all' } | { kind: 'none'; deny?: 'empty' | 'forbidden' } | { kind: 'where'; predicate: Predicate; deny?: 'empty' | 'forbidden' }
27
+ export type GuardResult = { allow: true } | { allow: false; code: string }
28
+ export type ResourceAction = OrganizationAction | 'audit.read' | 'workflows.read' | 'workflows.resume' | 'workflows.cancel'
29
+ /** Metadata only; no planning function, store or execution capability is exposed. */
30
+ export interface KernelCommand {
31
+ name: string
32
+ kind: 'entity' | 'command' | 'resource'
33
+ permission: AtomicOperation['permission'] | { system: ResourceAction }
34
+ additionalPermissions?: AtomicOperation['additionalPermissions']
35
+ }
36
+ export interface PluginMigration { name: string; sql: string }
37
+ export interface PluginMcpTool { name: string; description: string; inputSchema: ZodType }
38
+ export interface PluginContext { readonly config: InstanceConfig }
39
+ export interface WorkbasePlugin {
40
+ name: string
41
+ version: string
42
+ /** Public contract majors, independent of the package version. */
43
+ provides?: Readonly<Record<string, `${number}.x`>>
44
+ requires?: Readonly<Record<string, `^${number}`>>
45
+ optionalRequires?: Readonly<Record<string, `^${number}`>>
46
+ /** Only the single permissions contract provider can enable authorization. */
47
+ authorization?: boolean
48
+ /** Stable local profile/mapping port, supplied by Identity only. */
49
+ identity?: IdentityPort
50
+ /** Profile synchronization policy declared by an external login adapter. */
51
+ profileAuthority?: { provider: string; synchronization: ProfileSynchronization }
52
+ mailOutbox?: MailOutboxPort
53
+ audit?: AuditPort
54
+ contributes?: { console?: ConsoleContribution }
55
+ /** Console provider owns registry validation and actor projection. */
56
+ validateConsole?(config: InstanceConfig): void
57
+ consoleRegistry?(config: InstanceConfig, scope: Scope): ConsoleRegistry
58
+ authenticate?(this: PluginContext, req: Request, env: RuntimeEnv): Promise<ResolvedActor | null> | ResolvedActor | null
59
+ /** Runs only for the sole, Identity-validated login claimant. */
60
+ synchronizeProfile?(this: PluginContext, req: Request, env: RuntimeEnv, actor: ResolvedActor): Promise<void>
61
+ /** Optional Organizations port. A selector is never a membership grant. */
62
+ resolveScopeId?(db: D1Database, selected?: string): Promise<string | null>
63
+ /** Login owns provisional session issuance and revocation, never Members. */
64
+ signInInvitation?(this: PluginContext, email: string, request: Request, env: RuntimeEnv): Promise<{ actor: ResolvedActor; response: Response; revoke: () => Promise<void> }>
65
+ /** Canonical filters fully described by model policy/scope need no additional custom receipt. */
66
+ policyInConfig?: true
67
+ tableFilter?(this: PluginContext, entity: string, scope: Scope): TableFilter
68
+ fieldMask?(this: PluginContext, entity: string, scope: Scope): readonly string[]
69
+ commandGuard?(this: PluginContext, command: KernelCommand, scope: Scope, input: unknown): GuardResult
70
+ /** Project plugin-owned configuration into the validated model's compatibility fields. */
71
+ configuration?: unknown
72
+ configure?(configuration: unknown): Partial<Pick<InstanceInput, 'roles' | 'organizationOwnerRole' | 'organizationPermissions'>>
73
+ /** Credential authentication is independent of interactive login providers. */
74
+ authenticateCredential?(this: PluginContext, req: Request, env: RuntimeEnv): Promise<ResolvedActor | null> | ResolvedActor | null
75
+ /** Validates config.pluginConfig[name], including schema defaults/transforms. */
76
+ configSchema?: ZodType
77
+ /** Domain defaults materialized by defineInstance; explicit schema edits take precedence. */
78
+ model?: Partial<Pick<InstanceInput, 'entities' | 'permissions' | 'policies' | 'ui' | 'account' | 'commands' | 'organizationPermissions'>>
79
+ /** Bind workflow effects to this Worker environment without selecting a distribution. */
80
+ workflowDefinitions?(env: RuntimeEnv): ReadonlyMap<string, WorkflowDefinition<any>>
81
+ entities?: InstanceInput['entities']
82
+ commands?: readonly CommandDefinition<any>[]
83
+ workflows?: readonly WorkflowDefinition<any>[]
84
+ migrations?: readonly PluginMigration[]
85
+ /** Read-only structural verification against the effective instance model and applied ledger. */
86
+ checkSchema?(db: D1Database, config: Pick<InstanceConfig, 'entities'>): Promise<void>
87
+ /** Read-only verification of additional bindings at the deployed compatibility gate. */
88
+ checkEnvironment?(env: { DB: D1Database; AUDIT_KV?: KVNamespace }): Promise<void>
89
+ routes?(this: PluginContext, app: App, config: InstanceConfig, env: RuntimeEnv): void
90
+ mcpTools?(this: PluginContext): readonly PluginMcpTool[]
91
+ onEvent?(this: PluginContext, event: AuditEvent): void | Promise<void>
92
+ }
@@ -0,0 +1,69 @@
1
+ import { quote } from '../migrations/schema'
2
+ import type { Predicate, PredicateRelation, PredicateValue } from './plugin'
3
+
4
+ /** Structured predicates only. The query compiler supplies the active library value/EXISTS renderers. */
5
+ export function renderPredicate(predicate: Predicate, tableAlias: string,
6
+ bindValue?: (value: Exclude<PredicateValue, null>) => string,
7
+ renderRelation?: (relation: PredicateRelation, parentAlias: string, negated: boolean) => string,
8
+ ): { sql: string; bindings: unknown[] } {
9
+ const alias = quote(tableAlias); const bindings: unknown[] = []
10
+ function bind(value: unknown): string {
11
+ if (!['string', 'number', 'boolean'].includes(typeof value) || (typeof value === 'number' && !Number.isFinite(value))) throw new Error('Invalid predicate value')
12
+ if (bindValue) return bindValue(value as Exclude<PredicateValue, null>)
13
+ bindings.push(typeof value === 'boolean' ? Number(value) : value); return '?'
14
+ }
15
+ function render(node: Predicate): string {
16
+ if (!node || typeof node !== 'object' || Array.isArray(node)) throw new Error('Invalid predicate')
17
+ const entries = Object.entries(node)
18
+ if (!entries.length) throw new Error('Empty predicate')
19
+ const logical = entries.find(([key, value]) => (key === 'all' || key === 'any') && Array.isArray(value))
20
+ if (logical) {
21
+ if (entries.length !== 1) throw new Error('Invalid predicate combinator')
22
+ const [key, children] = logical as ['all' | 'any', Predicate[]]
23
+ return `(${children.length ? children.map(render).join(key === 'all' ? ' AND ' : ' OR ') : key === 'all' ? '1=1' : '0=1'})`
24
+ }
25
+ if (Object.hasOwn(node, 'not')) {
26
+ if (entries.length !== 1) throw new Error('Invalid predicate combinator')
27
+ return `(NOT ${render((node as { not: Predicate }).not)})`
28
+ }
29
+ const relationKey = Object.hasOwn(node, 'exists') ? 'exists' : Object.hasOwn(node, 'notExists') ? 'notExists' : undefined
30
+ if (relationKey) {
31
+ if (entries.length !== 1 || !renderRelation) throw new Error('Relation predicate requires scoped compiler')
32
+ const relation = (node as Record<string, PredicateRelation>)[relationKey]
33
+ if (!relation || Object.keys(relation).length !== 4 || !['entity', 'field', 'parentField', 'predicate'].every(key => Object.hasOwn(relation, key))
34
+ || ![relation.entity, relation.field, relation.parentField].every(value => typeof value === 'string')) throw new Error('Invalid predicate relation')
35
+ quote(relation.entity); quote(relation.field); quote(relation.parentField)
36
+ return `(${renderRelation(relation, tableAlias, relationKey === 'notExists')})`
37
+ }
38
+ return `(${entries.flatMap(([field, operators]) => {
39
+ const column = `${alias}.${quote(field)}`
40
+ if (!operators || typeof operators !== 'object' || Array.isArray(operators) || !Object.keys(operators).length) throw new Error('Invalid predicate operator')
41
+ return Object.entries(operators).map(([op, value]) => {
42
+ if (op === 'isNull') {
43
+ if (typeof value !== 'boolean') throw new Error('Invalid predicate value')
44
+ return `${column} IS ${value ? '' : 'NOT '}NULL`
45
+ }
46
+ if ((op === 'eq' || op === 'ne') && value === null) return `${column} IS ${op === 'eq' ? '' : 'NOT '}NULL`
47
+ if (op === 'in') {
48
+ if (!Array.isArray(value)) throw new Error('Invalid predicate value')
49
+ if (!value.length) return '0=1'
50
+ const values = value.filter(v => v !== null).map(v => {
51
+ if (!['string', 'number', 'boolean'].includes(typeof v) || typeof v === 'number' && !Number.isFinite(v)) throw new Error('Invalid predicate value')
52
+ return typeof v === 'boolean' ? Number(v) : v
53
+ })
54
+ // D1 binds JS numbers as REAL. CASE removes RHS affinity; only JSON numbers are cast.
55
+ const parts = [...(values.length ? [`${column} IN (SELECT CASE WHEN type IN ('integer', 'real') THEN CAST(value AS REAL) ELSE value END FROM json_each(${bind(JSON.stringify(values))}))`] : []), ...(value.includes(null) ? [`${column} IS NULL`] : [])]
56
+ return `(${parts.join(' OR ')})`
57
+ }
58
+ if (op === 'contains') {
59
+ if (typeof value !== 'string') throw new Error('Invalid predicate value')
60
+ return `instr(${column},${bind(value)})>0`
61
+ }
62
+ const sqlOp = ({ eq: '=', ne: '!=', lt: '<', lte: '<=', gt: '>', gte: '>=' } as Record<string, string>)[op]
63
+ if (!sqlOp || !Object.hasOwn({ eq: 1, ne: 1, lt: 1, lte: 1, gt: 1, gte: 1 }, op)) throw new Error('Invalid predicate operator')
64
+ return `${column}${sqlOp}${bind(value)}`
65
+ })
66
+ }).join(' AND ')})`
67
+ }
68
+ return { sql: render(predicate), bindings }
69
+ }