@workbasehq/core 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/package.json +62 -1
  4. package/src/account-provisioning.ts +24 -0
  5. package/src/admin-forms.tsx +70 -0
  6. package/src/admin-security.ts +63 -0
  7. package/src/admin-ui.tsx +438 -0
  8. package/src/app.ts +115 -0
  9. package/src/audit-event.ts +23 -0
  10. package/src/audit.ts +35 -0
  11. package/src/authorization-api.ts +3 -0
  12. package/src/authorization.ts +135 -0
  13. package/src/authorized-execution.ts +15 -0
  14. package/src/bootstrap.ts +23 -0
  15. package/src/browser-dispatch.ts +19 -0
  16. package/src/calendar-display.ts +26 -0
  17. package/src/capabilities.ts +41 -0
  18. package/src/commands.ts +46 -0
  19. package/src/config-proposal-contract.ts +16 -0
  20. package/src/config-proposals.ts +95 -0
  21. package/src/config-shorthand.ts +200 -0
  22. package/src/config.ts +286 -0
  23. package/src/console-contract.ts +105 -0
  24. package/src/console-contribution.ts +7 -0
  25. package/src/console.ts +84 -0
  26. package/src/crud.ts +146 -0
  27. package/src/crypto.ts +33 -0
  28. package/src/detail-display.ts +59 -0
  29. package/src/detail-layout.ts +17 -0
  30. package/src/errors.ts +3 -0
  31. package/src/event-delivery.ts +76 -0
  32. package/src/events.ts +11 -0
  33. package/src/execution/atomic.ts +70 -0
  34. package/src/execution/compiler.ts +55 -0
  35. package/src/execution/context.ts +100 -0
  36. package/src/execution/d1.ts +46 -0
  37. package/src/execution/errors.ts +21 -0
  38. package/src/execution/index.ts +6 -0
  39. package/src/execution/outbox.ts +8 -0
  40. package/src/execution/permissions.ts +9 -0
  41. package/src/execution/policies.ts +156 -0
  42. package/src/execution/policy-receipts.ts +51 -0
  43. package/src/execution/types.ts +74 -0
  44. package/src/execution/workflow.ts +35 -0
  45. package/src/form-display.ts +36 -0
  46. package/src/idempotency.ts +10 -0
  47. package/src/identity-providers.ts +2 -0
  48. package/src/identity-settings.ts +42 -0
  49. package/src/identity-writes.ts +14 -0
  50. package/src/identity.ts +2 -0
  51. package/src/index.ts +32 -0
  52. package/src/json-csrf.ts +22 -0
  53. package/src/kernel/adapters/tenancy.ts +8 -0
  54. package/src/kernel/audit-port.ts +12 -0
  55. package/src/kernel/builtin-source.ts +34 -0
  56. package/src/kernel/composition.ts +77 -0
  57. package/src/kernel/identity-port.ts +36 -0
  58. package/src/kernel/mail-outbox-port.ts +23 -0
  59. package/src/kernel/migrations.ts +76 -0
  60. package/src/kernel/operation-name.ts +8 -0
  61. package/src/kernel/plugin.ts +92 -0
  62. package/src/kernel/predicate.ts +69 -0
  63. package/src/kernel/registry.ts +198 -0
  64. package/src/kernel/schema-check.ts +13 -0
  65. package/src/logging.ts +21 -0
  66. package/src/migrations/better-auth-schema.ts +2 -0
  67. package/src/migrations/email-delivery-schema.ts +6 -0
  68. package/src/migrations/planner.ts +77 -0
  69. package/src/migrations/schema.ts +85 -0
  70. package/src/migrations/version-contract.ts +28 -0
  71. package/src/migrations/versions.ts +90 -0
  72. package/src/ops-schema.ts +13 -0
  73. package/src/ops.ts +34 -0
  74. package/src/organization-permissions.ts +13 -0
  75. package/src/organization-rules.ts +25 -0
  76. package/src/organizations.ts +43 -0
  77. package/src/plugins.ts +3 -0
  78. package/src/policies.ts +186 -0
  79. package/src/public-schema.ts +65 -0
  80. package/src/query/compiler.ts +395 -0
  81. package/src/query/cursor.ts +43 -0
  82. package/src/query/enum-labels.json +16 -0
  83. package/src/query/enum-values.ts +7 -0
  84. package/src/query/errors.ts +10 -0
  85. package/src/query/executor.ts +118 -0
  86. package/src/query/facade.ts +34 -0
  87. package/src/query/labels.ts +105 -0
  88. package/src/query/limits.ts +8 -0
  89. package/src/query/observability.ts +49 -0
  90. package/src/query/routes.ts +60 -0
  91. package/src/query/schema.ts +216 -0
  92. package/src/query/search.ts +15 -0
  93. package/src/relay.ts +65 -0
  94. package/src/request-timing.ts +71 -0
  95. package/src/schema-compatibility.ts +43 -0
  96. package/src/scope-operations.ts +3 -0
  97. package/src/session-contract.ts +1 -0
  98. package/src/types.ts +30 -0
  99. package/src/worker-fetch.ts +14 -0
  100. package/src/workflow-routes.ts +156 -0
  101. package/src/workflow-runtime.ts +327 -0
  102. package/src/workflow-schema.ts +29 -0
package/src/console.ts ADDED
@@ -0,0 +1,84 @@
1
+ import type { App, AppContext, RuntimeEnv } from './types'
2
+ import type { InstanceConfig } from './config'
3
+
4
+ export const CONSOLE_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'self'; frame-ancestors 'none'"
5
+ export async function buildInfo(config: Pick<InstanceConfig, 'revision'>, env: RuntimeEnv, url: string) {
6
+ let sha = env.BUILD_SHA; let builtAt = env.BUILD_AT
7
+ // Raw local `wrangler dev --local` has the build manifest even without SST's bindings.
8
+ if ((!sha || !builtAt) && env.ASSETS) {
9
+ const response = await env.ASSETS.fetch(new Request(new URL('/build-meta.json', url)))
10
+ if (response.ok) {
11
+ const build = await response.json() as { sha?: unknown; builtAt?: unknown }
12
+ if (typeof build.sha === 'string' && /^[a-f0-9]{40}$/.test(build.sha) && typeof build.builtAt === 'string' && Number.isFinite(Date.parse(build.builtAt))) {
13
+ sha = build.sha; builtAt = build.builtAt
14
+ }
15
+ }
16
+ }
17
+ return { sha: sha ?? 'unbuilt', builtAt: builtAt ?? 'unbuilt', revision: config.revision }
18
+ }
19
+ function isConsolePath(path: string) {
20
+ return !(/^\/(api|auth|mcp|internal|ops|admin|commands|workflows|query|orgs|invitations|audit|me|health|schema|bootstrap|build\.json)(\/|$)/.test(path)
21
+ || /^\/o\/[^/]+\/(bootstrap|capabilities|console-registry|console-pages|config-versions)(\/|$)/.test(path))
22
+ }
23
+
24
+ async function serveConsole(request: Request, env: RuntimeEnv) {
25
+ if (!env.ASSETS) return Response.json({ error: 'console_not_built' }, { status: 503, headers: { 'Content-Security-Policy': CONSOLE_CSP } })
26
+ const url = new URL(request.url)
27
+ let response = await env.ASSETS.fetch(request)
28
+ if (response.status === 404 && !url.pathname.split('/').at(-1)?.includes('.')) {
29
+ url.pathname = '/index.html'
30
+ response = await env.ASSETS.fetch(new Request(url, request))
31
+ }
32
+ const headers = new Headers(response.headers)
33
+ headers.set('Content-Security-Policy', CONSOLE_CSP)
34
+ headers.set('X-Content-Type-Options', 'nosniff')
35
+ headers.set('Referrer-Policy', 'no-referrer')
36
+ if (headers.get('Content-Type')?.includes('text/html')) headers.set('Cache-Control', 'no-cache')
37
+ return new Response(response.body, { status: response.status, headers })
38
+ }
39
+
40
+ /** Safe before loading the application: public assets/build contain no actor projections. */
41
+ export async function publicConsoleResponse(request: Request, env: RuntimeEnv): Promise<Response | undefined> {
42
+ const url = new URL(request.url)
43
+ if (env.STAGE === 'staging' && url.hostname.endsWith('.workers.dev') && env.AUTH_BASE_URL) {
44
+ const target = new URL(env.AUTH_BASE_URL)
45
+ target.pathname = url.pathname; target.search = url.search
46
+ return Response.redirect(target.href, 308)
47
+ }
48
+ if (!['GET', 'HEAD'].includes(request.method)) return
49
+ const path = url.pathname
50
+ if (path === '/build.json' && env.SCHEMA_EXPECTED) {
51
+ let revision: unknown
52
+ try { revision = JSON.parse(env.SCHEMA_EXPECTED).revision } catch { return }
53
+ if (typeof revision !== 'number' || !Number.isInteger(revision) || revision < 1) return
54
+ const response = Response.json(await buildInfo({ revision }, env, request.url), { headers: { 'Cache-Control': 'no-store' } })
55
+ return request.method === 'HEAD' ? new Response(null, response) : response
56
+ }
57
+ if (path === '/console' || path.startsWith('/console/')) {
58
+ const target = (path.slice('/console'.length) || '/') + url.search
59
+ return new Response(null, { status: 301, headers: { Location: target.startsWith('//') ? url.origin + target : target } })
60
+ }
61
+ if (path === '/auth/complete' || isConsolePath(path)) return serveConsole(request, env)
62
+ }
63
+ /** Same-origin assets are always reached through the Worker, including navigations. */
64
+ export function consoleRoutes(app: App, config: InstanceConfig, env: RuntimeEnv) {
65
+ for (const path of ['/console', '/console/*']) app.all(path, c => {
66
+ const url = new URL(c.req.url)
67
+ const target = (url.pathname.slice('/console'.length) || '/') + url.search
68
+ // A doubled slash in an old path must never become a cross-origin redirect.
69
+ return c.redirect(target.startsWith('//') ? url.origin + target : target, 301)
70
+ })
71
+ app.get('/build.json', async c => {
72
+ return c.json(await buildInfo(config, env, c.req.url), 200, { 'Cache-Control': 'no-store' })
73
+ })
74
+ const serve = (c: AppContext) => serveConsole(c.req.raw, env)
75
+ // This exact browser callback precedes /auth/* and never reaches Better Auth.
76
+ app.get('/auth/complete', serve)
77
+ app.notFound(c => {
78
+ const path = c.req.path
79
+ // Reserve service namespaces, including unknown endpoints, before the SPA.
80
+ if (!['GET', 'HEAD'].includes(c.req.method)
81
+ || !isConsolePath(path)) return c.text('404 Not Found', 404)
82
+ return serve(c)
83
+ })
84
+ }
package/src/crud.ts ADDED
@@ -0,0 +1,146 @@
1
+ import { assertActorFields } from './policies'
2
+ import { enforcePlan, writeFilter } from './execution/policies'
3
+ import { compile } from './execution/compiler'
4
+ import type { GuardedStatement } from './execution/types'
5
+ import { z } from 'zod'
6
+ import { fieldsFor } from './query/schema'
7
+ import { restQuery } from './query/facade'
8
+ import { executeQuery } from './query/executor'
9
+ import { observeQuery } from './query/observability'
10
+ import { cursorSecret } from './query/routes'
11
+ import { requestHash } from './idempotency'
12
+ import { kernelFor } from './kernel/registry'
13
+ import { bodyValidator, type InstanceConfig, type Operation } from './config'
14
+ import type { App, AppContext, RuntimeEnv, Scope } from './types'
15
+ import { ApiError } from './errors'
16
+ import { makeEvent, type AuditEvent } from './events'
17
+ import { publishCommittedEvents } from './event-delivery'
18
+ import { quote } from './migrations/schema'
19
+ type Row = Record<string, any>
20
+ export function permission(config: InstanceConfig, scope: Scope, entity: string, op: Operation) {
21
+ kernelFor(config).permission(scope, entity, op)
22
+ }
23
+ export function serialize(config: InstanceConfig, name: string, row: Row) {
24
+ const out: Row = Object.fromEntries(fieldsFor(config, name).filter(key => Object.hasOwn(row, key)).map(key => [key, row[key]]))
25
+ for (const [key, f] of Object.entries(config.entities[name].fields)) if (f.type === 'bool' && Object.hasOwn(out, key) && out[key] !== null) out[key] = Boolean(out[key])
26
+ return out
27
+ }
28
+ export function crudRoutes(app: App, config: InstanceConfig, env: RuntimeEnv) {
29
+ const kernel = kernelFor(config)
30
+ const storedFields = (name: string) => fieldsFor(config, name).filter(field => !config.entities[name].label || field !== config.entities[name].displayField)
31
+ const responseRow = async (name: string, scope: Scope, row: Row) => {
32
+ const readable = new Set(kernel.fieldMask(name, scope))
33
+ const result = Object.fromEntries(Object.entries(serialize(config, name, row)).filter(([field]) => readable.has(field)))
34
+ // Stored mutation/replay bodies retain their original values, but references
35
+ // must pass the same current target visibility check as query projections.
36
+ for (const [field, definition] of Object.entries(config.entities[name].fields)) {
37
+ if (definition.type !== 'ref' || result[field] == null) continue
38
+ const target = definition.entity!
39
+ if (!kernel.can(scope, target, 'read') || !kernel.fieldMask(target, scope).includes('id')) { result[field] = null; continue }
40
+ const policy = writeFilter(kernel, scope, target)
41
+ const visible = await env.DB.prepare(`SELECT id FROM ${quote(target)} WHERE id=? AND (${policy.sql})`).bind(result[field], ...(policy.bindings ?? [])).first()
42
+ if (!visible) result[field] = null
43
+ }
44
+ return result
45
+ }
46
+ async function mutate(name: string, scope: Scope, statement: GuardedStatement, event: AuditEvent, tail: D1PreparedStatement[] = []) {
47
+ const plan = enforcePlan(kernel, scope, { rules: [{ name: 'crud_write', statements: [{ ...statement, expectRows: 1 }] }], event: { entity: name, entityId: '', operation: 'crud' }, result: { status: 200, body: {} } })
48
+ const sql = compile({ runId: crypto.randomUUID(), rules: plan.rules })
49
+ const cleanup = sql.pop()!
50
+ try { await env.DB.batch([...sql.map(s => env.DB.prepare(s.sql).bind(...(s.bindings ?? []))), env.DB.prepare('INSERT INTO audit_outbox (event_id,organization_id,payload,created_at) VALUES (?,?,?,?)').bind(event.event_id, event.organization_id, JSON.stringify(event), event.occurred_at), ...tail, env.DB.prepare(cleanup.sql).bind(...(cleanup.bindings ?? []))]) }
51
+ catch (error) {
52
+ if (/CHECK constraint failed: policy_ok\s*=\s*1/i.test(String(error))) throw new ApiError(403, 'policy_violation')
53
+ if (/CHECK constraint failed: actor_ok\s*=\s*1/i.test(String(error))) throw new ApiError(403, 'field_forbidden')
54
+ if (/CHECK constraint failed: (?:atomic_assert|ok\s*=\s*1)/i.test(String(error))) throw new ApiError(409, 'version_conflict')
55
+ throw error
56
+ }
57
+ await publishCommittedEvents(env, config, [event])
58
+ }
59
+ function hidden(name: string, scope: Scope): never {
60
+ const filter = kernel.tableFilter(name, scope)
61
+ throw new ApiError('deny' in filter && filter.deny === 'forbidden' ? 403 : 404, 'deny' in filter && filter.deny === 'forbidden' ? 'policy_violation' : 'not_found')
62
+ }
63
+ function entity(c: AppContext, op: Operation) {
64
+ const name = c.req.param('entity')!; const definition = config.entities[name]
65
+ if (!Object.hasOwn(config.entities, name)) throw new ApiError(404, 'entity_not_found')
66
+ const scope = c.get('scope')
67
+ if (op === 'read') kernel.readPermission(scope, name)
68
+ else kernel.permission(scope, name, op)
69
+ if (op !== 'read' && definition.commandsOnly) throw new ApiError(405, 'commands_only', 'Use a registered /commands/:name command')
70
+ return { name, definition, scope, table: quote(name) }
71
+ }
72
+ app.get('/api/:entity', c => observeQuery(env.DB, c.get('scope'), async (writeLog, rejectedInput) => {
73
+ await rejectedInput({ entity: c.req.param('entity'), id: c.req.param('id'), params: c.req.query() })
74
+ const { name, scope } = entity(c, 'read')
75
+ const query = restQuery(config, name, c.req.query())
76
+ const result = await executeQuery(kernel, scope, env.DB, await cursorSecret(env), query, { legacyErrors: true, writeLog })
77
+ return c.json({ data: result.data, next_cursor: result.next_cursor ? result.data.at(-1)!.id : null })
78
+ }))
79
+ app.get('/api/:entity/:id', c => observeQuery(env.DB, c.get('scope'), async (writeLog, rejectedInput) => {
80
+ await rejectedInput({ entity: c.req.param('entity'), id: c.req.param('id'), params: c.req.query() })
81
+ const { name, scope } = entity(c, 'read')
82
+ const result = await executeQuery(kernel, scope, env.DB, await cursorSecret(env), restQuery(config, name, c.req.query(), c.req.param('id')), { legacyErrors: true, writeLog })
83
+ if (!result.data.length) throw new ApiError(404, 'not_found')
84
+ return c.json(result.data[0])
85
+ }))
86
+ app.post('/api/:entity', async c => {
87
+ const { name, definition, scope, table } = entity(c, 'create')
88
+ const body = bodyValidator(definition).parse(await c.req.json()) as Row
89
+ const key = z.string().min(1).max(128).optional().parse(c.req.header('Idempotency-Key'))
90
+ const operation = `${name}.create`
91
+ const hash = key ? await requestHash(operation, body) : undefined
92
+ const replay = async () => {
93
+ if (!key) return null
94
+ const stored = await env.DB.prepare('SELECT command,request_hash,response_json FROM idempotency_keys WHERE organization_id=? AND key=?').bind(scope.organizationId, key).first<{ command: string; request_hash: string; response_json: string }>()
95
+ if (!stored) return null
96
+ if (stored.command !== operation || stored.request_hash !== hash) throw new ApiError(422, 'idempotency_payload_mismatch')
97
+ const row = JSON.parse(stored.response_json).body as Row
98
+ const policy = writeFilter(kernel, scope, name)
99
+ const visible = await env.DB.prepare(`SELECT id FROM ${table} WHERE id=? AND (${policy.sql})`).bind(row.id, ...(policy.bindings ?? [])).first()
100
+ if (!visible) hidden(name, scope)
101
+ return row
102
+ }
103
+ const prior = await replay()
104
+ if (prior) return c.json(await responseRow(name, scope, prior), 201)
105
+ const now = new Date().toISOString()
106
+ const row: Row = { id: crypto.randomUUID(), organization_id: scope.organizationId, created_at: now, updated_at: now, version: 1 }
107
+ for (const [key, f] of Object.entries(definition.fields)) if (!definition.label || key !== definition.displayField) row[key] = Object.hasOwn(body, key) ? body[key] : f.default ?? null
108
+ const keys = Object.keys(row)
109
+ assertActorFields(config, scope, name, Object.keys(body))
110
+ try { await mutate(name, scope, { sql: `INSERT INTO ${table} (${keys.map(quote).join(',')}) VALUES (${keys.map(() => '?').join(',')})`, bindings: keys.map(k => typeof row[k] === 'boolean' ? Number(row[k]) : row[k]) }, makeEvent(config, scope, `${name}.created`, name, row.id, {}, row), [
111
+ ...(key ? [env.DB.prepare('INSERT INTO idempotency_keys (organization_id,key,command,response_json,request_hash) VALUES (?,?,?,?,?)').bind(scope.organizationId, key, operation, JSON.stringify({ status: 201, body: serialize(config, name, row) }), hash!)] : []),
112
+ ]) } catch (error) {
113
+ const winner = await replay()
114
+ if (winner) return c.json(await responseRow(name, scope, winner), 201)
115
+ throw error
116
+ }
117
+ return c.json(await responseRow(name, scope, row), 201)
118
+ })
119
+ app.patch('/api/:entity/:id', async c => {
120
+ const { name, definition, scope, table } = entity(c, 'update')
121
+ const raw = await c.req.json<Row>()
122
+ const expected = Number(c.req.header('If-Match')?.replaceAll('"', '') ?? raw.version)
123
+ if (!Number.isSafeInteger(expected) || expected < 1) throw new ApiError(400, 'version_required')
124
+ delete raw.version
125
+ assertActorFields(config, scope, name, Object.keys(raw), c.req.param('id'))
126
+ const body = bodyValidator(definition, true).parse(raw) as Row
127
+ if (!Object.keys(body).length) throw new ApiError(400, 'empty_update')
128
+ const policy = writeFilter(kernel, scope, name)
129
+ const before = await env.DB.prepare(`SELECT ${storedFields(name).map(quote).join(',')} FROM ${table} WHERE organization_id=? AND id=? AND (${policy.sql})`).bind(scope.organizationId, c.req.param('id'), ...(policy.bindings ?? [])).first<Row>()
130
+ if (!before) hidden(name, scope)
131
+ if (before.version !== expected) throw new ApiError(409, 'version_conflict')
132
+ assertActorFields(config, scope, name, Object.keys(body), c.req.param('id'))
133
+ const after: Row = { ...serialize(config, name, before), ...body, updated_at: new Date().toISOString(), version: expected + 1 }
134
+ const keys = [...Object.keys(body), 'updated_at', 'version']
135
+ await mutate(name, scope, { sql: `UPDATE ${table} SET ${keys.map(k => `${quote(k)}=?`).join(',')} WHERE organization_id=? AND id=? AND version=?`, bindings: [...keys.map(k => typeof after[k] === 'boolean' ? Number(after[k]) : after[k]), scope.organizationId, c.req.param('id'), expected] }, makeEvent(config, scope, `${name}.updated`, name, before.id, serialize(config, name, before), after))
136
+ return c.json(await responseRow(name, scope, after))
137
+ })
138
+ app.delete('/api/:entity/:id', async c => {
139
+ const { name, scope, table } = entity(c, 'delete')
140
+ const policy = writeFilter(kernel, scope, name)
141
+ const before = await env.DB.prepare(`SELECT ${storedFields(name).map(quote).join(',')} FROM ${table} WHERE organization_id=? AND id=? AND (${policy.sql})`).bind(scope.organizationId, c.req.param('id'), ...(policy.bindings ?? [])).first<Row>()
142
+ if (!before) hidden(name, scope)
143
+ await mutate(name, scope, { sql: `DELETE FROM ${table} WHERE organization_id=? AND id=? AND version=?`, bindings: [scope.organizationId, c.req.param('id'), before.version] }, makeEvent(config, scope, `${name}.deleted`, name, before.id, serialize(config, name, before)))
144
+ return c.body(null, 204)
145
+ })
146
+ }
package/src/crypto.ts ADDED
@@ -0,0 +1,33 @@
1
+ const hex = (bytes: Uint8Array) => [...bytes].map(b => b.toString(16).padStart(2, '0')).join('')
2
+ const bytes = (value: string) => Uint8Array.from(value.match(/.{2}/g) ?? [], n => parseInt(n, 16))
3
+ export const randomToken = () => hex(crypto.getRandomValues(new Uint8Array(32)))
4
+ export const randomSalt = () => hex(crypto.getRandomValues(new Uint8Array(16)))
5
+ export const sha256 = async (value: string) => hex(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value))))
6
+ export async function passwordHash(password: string, salt: string) {
7
+ const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(password), 'PBKDF2', false, ['deriveBits'])
8
+ return hex(new Uint8Array(await crypto.subtle.deriveBits({ name: 'PBKDF2', salt: bytes(salt), iterations: 100000, hash: 'SHA-256' }, key, 256)))
9
+ }
10
+ export function equalHash(a: string, b: string) {
11
+ if (a.length !== b.length) return false
12
+ let diff = 0
13
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)
14
+ return diff === 0
15
+ }
16
+ const alphabet = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'
17
+ export function ulid(now = Date.now()) {
18
+ let time = now; let id = ''
19
+ for (let i = 0; i < 10; i++) { id = alphabet[time % 32] + id; time = Math.floor(time / 32) }
20
+ for (const b of crypto.getRandomValues(new Uint8Array(16))) id += alphabet[b & 31]
21
+ return id
22
+ }
23
+
24
+ export async function signWebhook(secret: string, payload: string) {
25
+ const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
26
+ return hex(new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(payload))))
27
+ }
28
+
29
+ /** Same SHA-256/base64url hash used for Better Auth magic-link verification rows. */
30
+ export async function magicLinkTokenHash(token: string) {
31
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(token)))
32
+ return btoa(String.fromCharCode(...digest)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '')
33
+ }
@@ -0,0 +1,59 @@
1
+ import { z } from 'zod'
2
+ import type { InstanceConfig } from './config'
3
+ import { detailSectionsSchema, validateDetailLayout } from './detail-layout'
4
+
5
+ const identifier = z.string().regex(/^[a-z][a-z0-9_]*$/)
6
+ const item = z.union([identifier, z.strictObject({
7
+ field: identifier, label: z.string().min(1).optional(), help: z.string().min(1).optional(),
8
+ when: z.strictObject({ field: identifier, eq: z.union([z.string(), z.number().finite(), z.boolean(), z.null()]) }).optional(),
9
+ })])
10
+ /** Labels/composite values use the entity's SR-61 ts-query expression, never a browser composer. */
11
+ export const detailDisplaySchema = z.strictObject({
12
+ inlineEdit: z.boolean().optional(),
13
+ lists: z.record(identifier, z.strictObject({ entity: identifier, label: z.string().min(1),
14
+ bind: z.strictObject({ field: identifier, record: z.literal('id') }), columns: z.array(identifier).min(1).optional(), create: z.boolean().optional(),
15
+ })).optional(),
16
+ summary: z.array(item).optional(),
17
+ groups: z.array(z.strictObject({ id: identifier, label: z.string().min(1), help: z.string().min(1).optional(), fields: z.array(item).min(1) })).optional(),
18
+ sections: detailSectionsSchema.optional(),
19
+ fields: z.array(identifier).optional(),
20
+ metrics: z.array(z.strictObject({ field: identifier, unitField: identifier.optional(), tone: z.enum(['positive', 'negative']).optional() })).optional(),
21
+ relations: z.record(identifier, z.strictObject({ columns: z.array(identifier), defaultSort: z.strictObject({ key: identifier, direction: z.enum(['asc', 'desc']) }).optional() })).optional(),
22
+ }).superRefine((detail, ctx) => {
23
+ if (detail.summary !== undefined && detail.groups === undefined || detail.groups !== undefined && detail.fields !== undefined) ctx.addIssue({ code: 'custom', message: 'Summary requires groups; groups replace detail.fields' })
24
+ })
25
+ export function validateDetailDisplay(config: Pick<InstanceConfig, 'entities'>, name: string, input: unknown) {
26
+ const detail = detailDisplaySchema.parse(input)
27
+ const entity = config.entities[name]
28
+ const known = (field: string) => ['id', 'organization_id', 'created_at', 'updated_at', 'version'].includes(field) || Object.hasOwn(entity.fields, field)
29
+ const check = (field: string) => { if (!known(field)) throw new Error(`Unknown UI detail field: ${name}.${field}`) }
30
+ const ids = new Set<string>(); const fields = new Set<string>()
31
+ for (const group of detail.groups ?? []) {
32
+ if (ids.has(group.id)) throw new Error(`Duplicate UI detail group: ${name}.${group.id}`)
33
+ ids.add(group.id)
34
+ }
35
+ for (const item of [...detail.summary ?? [], ...(detail.groups ?? []).flatMap(group => group.fields)]) {
36
+ const value = typeof item === 'string' ? { field: item } : item
37
+ check(value.field)
38
+ if (['id', 'organization_id'].includes(value.field)) throw new Error(`Technical UI detail field: ${name}.${value.field}`)
39
+ if (fields.has(value.field)) throw new Error(`Duplicate UI detail field: ${name}.${value.field}`)
40
+ fields.add(value.field)
41
+ if (value.when) {
42
+ check(value.when.field)
43
+ const type = entity.fields[value.when.field]?.type ?? (value.when.field === 'version' ? 'int' : 'string')
44
+ const operand = value.when.eq
45
+ if (operand !== null && (type === 'bool' ? typeof operand !== 'boolean' : ['int', 'float'].includes(type) ? typeof operand !== 'number' || type === 'int' && !Number.isSafeInteger(operand) : typeof operand !== 'string') || type === 'enum' && operand !== null && !entity.fields[value.when.field].values?.includes(String(operand))) throw new Error(`Invalid UI detail condition: ${name}.${value.when.field}`)
46
+ }
47
+ }
48
+ for (const field of [...detail.fields ?? [], ...(detail.metrics ?? []).flatMap(metric => [metric.field, ...metric.unitField ? [metric.unitField] : []])]) check(field)
49
+ for (const [key, list] of Object.entries(detail.lists ?? {})) {
50
+ const target = config.entities[list.entity]; const field = target?.fields[list.bind.field]
51
+ if (key === 'info' || !field || field.type !== 'ref' || field.entity !== name || entity.relations[key] && (entity.relations[key].entity !== list.entity || entity.relations[key].field !== list.bind.field || !entity.relations[key].many)) throw new Error(`Invalid UI context list: ${name}.${key}`)
52
+ if (list.columns && (new Set(list.columns).size !== list.columns.length || list.columns.some(column => !['id', 'created_at', 'updated_at', 'version'].includes(column) && !Object.hasOwn(target.fields, column)))) throw new Error(`Invalid UI context list columns: ${name}.${key}`)
53
+ }
54
+ validateDetailLayout(name, { ...entity.relations, ...Object.fromEntries(Object.keys(detail.lists ?? {}).map(key => [key, { many: true }])) }, detail.sections)
55
+ for (const [relation, hint] of Object.entries(detail.relations ?? {})) {
56
+ const target = config.entities[entity.relations[relation]?.entity]
57
+ if (!target || [...hint.columns, ...hint.defaultSort ? [hint.defaultSort.key] : []].some(field => !['id', 'organization_id', 'created_at', 'updated_at', 'version'].includes(field) && !Object.hasOwn(target.fields, field))) throw new Error(`Invalid UI detail relation: ${name}.${relation}`)
58
+ }
59
+ }
@@ -0,0 +1,17 @@
1
+ import { z } from 'zod'
2
+ import type { ConsoleDetailSection } from './console-contract'
3
+
4
+ export const detailSectionsSchema = z.array(z.union([
5
+ z.strictObject({ fields: z.literal('info') }),
6
+ z.strictObject({ row: z.array(z.string().min(1)).min(1).max(3) }),
7
+ ]))
8
+
9
+ /** Shared by canonical model UI and explicit Console display contributions. */
10
+ export function validateDetailLayout(entity: string, relations: Record<string, { many?: boolean }>, sections?: ConsoleDetailSection[]) {
11
+ const seen = new Set<string>()
12
+ for (const section of sections ?? []) for (const key of section.row ?? ['info']) {
13
+ if (key !== 'info' && !relations[key]?.many) throw new Error(`Unknown UI detail layout card: ${entity}.${key}`)
14
+ if (seen.has(key)) throw new Error(`Duplicate UI detail layout card: ${entity}.${key}`)
15
+ seen.add(key)
16
+ }
17
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,3 @@
1
+ export class ApiError extends Error {
2
+ constructor(public status: number, public code: string, public hint?: string, public detail?: Readonly<Record<string, unknown>>) { super(code) }
3
+ }
@@ -0,0 +1,76 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks'
2
+ import type { InstanceConfig } from './config'
3
+ import type { RuntimeEnv } from './types'
4
+ import type { AuditEvent } from './audit-event'
5
+ import type { AuditOutboxRow } from './kernel/audit-port'
6
+ import { boundKernel, KernelRegistry } from './kernel/registry'
7
+
8
+ // Request-local: cached apps and simultaneous requests must never share a context.
9
+ export const eventDeliveryContext = new AsyncLocalStorage<Pick<ExecutionContext, 'waitUntil'>>()
10
+ const auditPort = (config: InstanceConfig) => (boundKernel(config) ?? new KernelRegistry(config)).audit
11
+
12
+ export async function sendOutboxRows(queue: Queue<AuditOutboxRow>, rows: readonly AuditOutboxRow[], deliverOversized: (row: AuditOutboxRow) => Promise<void>) {
13
+ // Leave headroom for Queue's per-message metadata within the 256 KB batch limit.
14
+ let delivered = 0; let errors = 0
15
+ let batch: MessageSendRequest<AuditOutboxRow>[] = []; let bytes = 0
16
+ const flush = async () => {
17
+ if (batch.length) {
18
+ try { await queue.sendBatch(batch) } catch { errors += batch.length }
19
+ }
20
+ batch = []; bytes = 0
21
+ }
22
+ for (const row of rows) {
23
+ const size = new TextEncoder().encode(JSON.stringify(row)).byteLength + 100
24
+ if (size > 128 * 1024) {
25
+ try { await deliverOversized(row); delivered++ } catch { errors++ }
26
+ continue
27
+ }
28
+ if (batch.length === 100 || bytes + size > 250000) await flush()
29
+ batch.push({ body: row, contentType: 'json' }); bytes += size
30
+ }
31
+ await flush()
32
+ return { delivered, errors }
33
+ }
34
+
35
+ /** Called only after the domain batch has resolved successfully. Never rejects a committed write. */
36
+ export async function publishCommittedEvents(env: RuntimeEnv, config: InstanceConfig, events: readonly AuditEvent[]) {
37
+ if (!events.length) return
38
+ const rows = events.map(event => ({ event_id: event.event_id, organization_id: event.organization_id, payload: JSON.stringify(event) }))
39
+ const deliver = async () => {
40
+ try {
41
+ if (env.EVENTS_QUEUE) {
42
+ const result = await sendOutboxRows(env.EVENTS_QUEUE, rows, async row => {
43
+ const audit = auditPort(config)
44
+ if (!audit) throw new Error('audit_port_required')
45
+ await audit.deliver(env, row)
46
+ })
47
+ if (result.errors) console.error('audit_publish_failed')
48
+ }
49
+ else {
50
+ const audit = auditPort(config)
51
+ if (audit) for (const row of rows) await audit.deliver(env, row)
52
+ }
53
+ } catch {
54
+ // D1 remains the retry source; never expose payloads or transport exceptions.
55
+ console.error('audit_publish_failed')
56
+ }
57
+ }
58
+ const context = eventDeliveryContext.getStore()
59
+ if (env.EVENTS_QUEUE && context) context.waitUntil(deliver())
60
+ else await deliver()
61
+ }
62
+
63
+ export async function consumeEvents(batch: MessageBatch<AuditOutboxRow>, env: RuntimeEnv, config: InstanceConfig) {
64
+ let audit: ReturnType<typeof auditPort>
65
+ try { audit = auditPort(config) } catch {
66
+ for (const message of batch.messages) message.retry()
67
+ return
68
+ }
69
+ for (const message of batch.messages) {
70
+ try {
71
+ if (!audit) throw new Error('audit_port_required')
72
+ await audit.deliver(env, message.body)
73
+ message.ack()
74
+ } catch { message.retry() }
75
+ }
76
+ }
package/src/events.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { sha256, ulid } from './crypto'
2
+ import type { Scope } from './identity'
3
+ import type { AuditEvent } from './audit-event'
4
+ export { makeEvent, type AuditEvent } from './audit-event'
5
+ export const outboxStatement = (db: D1Database, event: AuditEvent, guard = 'changes() = 1') => db.prepare(`INSERT INTO audit_outbox (event_id,organization_id,payload,created_at) SELECT ?,?,?,? WHERE ${guard}`).bind(event.event_id, event.organization_id, JSON.stringify(event), event.occurred_at)
6
+ export async function securityLog(db: D1Database, scope: Partial<Scope>, operation: string, status: number) {
7
+ const requested = scope.organizationId
8
+ const organization = requested ? await db.prepare('SELECT id FROM organizations WHERE id=?').bind(requested).first<string>('id') : null
9
+ const requestedHash = requested && !organization ? await sha256(requested) : null
10
+ await db.prepare('INSERT INTO security_log (id,organization_id,requested_scope_hash,actor_id,operation,status,correlation_id,occurred_at) VALUES (?,?,?,?,?,?,?,?)').bind(ulid(), organization, requestedHash, scope.actor?.id ?? null, operation, status, scope.correlationId ?? ulid(), new Date().toISOString()).run()
11
+ }
@@ -0,0 +1,70 @@
1
+ import { needsPolicyReceipt, receiptIdentity, receiptExpression, authorizeReplay } from './policy-receipts'
2
+ import { kernelFor } from '../kernel/registry'
3
+ import { loadActorProjection } from '../policies'
4
+ import { enforcePlan } from './policies'
5
+ import { z } from 'zod'
6
+ import { ApiError } from '../errors'
7
+ import { makeEvent } from '../audit-event'
8
+ import { outboxInsert } from './outbox'
9
+ import { requestHash } from '../idempotency'
10
+ import { infrastructure, authorizeAtomic } from './context'
11
+ import { memberManagementMode } from '../organizations'
12
+ import { validatePlan, compile } from './compiler'
13
+ import { RuleFailed } from './errors'
14
+ import type { AtomicOperation, AtomicResult, ExecutionContext, StorePlan } from './types'
15
+
16
+ export function defineAtomicOperation<S extends z.ZodType, P = undefined>(operation: AtomicOperation<S, P>): AtomicOperation<S, P> {
17
+ if (!/^[a-z][a-z0-9_]*(\/[a-z][a-z0-9_]*)+$/.test(operation.name)) throw new Error('Invalid command name')
18
+ return operation
19
+ }
20
+ export async function executeAtomic<S extends z.ZodType>(operation: AtomicOperation<S>, input: unknown, context: ExecutionContext): Promise<AtomicResult> {
21
+ // Bind route authority and permission to this request before any await or
22
+ // command callback. Later mutations of the caller's operation cannot upgrade it.
23
+ const identity = operation
24
+ const memberMode = memberManagementMode(context, identity)
25
+ operation = Object.freeze({ ...operation, permission: Object.freeze({ ...operation.permission }),
26
+ additionalPermissions: operation.additionalPermissions && Object.freeze(operation.additionalPermissions.map(grant => Object.freeze({ ...grant }))) })
27
+ const { store, reader, policyReceipt } = infrastructure(context)
28
+ const { config, scope, idempotencyKey: key } = context
29
+ await loadActorProjection(config, scope, (sql, bindings) => reader.first({ sql, bindings }))
30
+ authorizeAtomic(context, operation, input, identity)
31
+ const kernel = kernelFor(config)
32
+ const policyIdentity = policyReceipt || needsPolicyReceipt(kernel) ? await receiptIdentity(config, scope) : undefined
33
+ const keySchema = operation.idempotency === 'required' ? z.string().min(1).max(128) : z.string().min(1).max(128).optional()
34
+ keySchema.parse(key)
35
+ const body = operation.input.parse(input)
36
+ const hash = key ? await requestHash(operation.name, body) : undefined
37
+ async function replay(): Promise<AtomicResult | null> {
38
+ if (!key) return null
39
+ const row = await reader.first<{ command: string; request_hash: string | null; response_json: string }>({ sql: 'SELECT command,request_hash,response_json FROM idempotency_keys WHERE organization_id=? AND key=?', bindings: [scope.organizationId, key] })
40
+ if (!row) return null
41
+ if (row.command !== operation.name || row.request_hash !== hash) throw new ApiError(422, 'idempotency_payload_mismatch')
42
+ return authorizeReplay(kernel, scope, reader, row.response_json, policyIdentity)
43
+ }
44
+ const prior = await replay()
45
+ if (prior) return prior
46
+ let conflict: string | undefined
47
+ try {
48
+ const prepared = await operation.prepare?.(Object.freeze({ __proto__: null, ...context, reader: Object.freeze({ __proto__: null, first: <T>(query: Parameters<typeof reader.first>[0]) => reader.first<T>(query) }) }), body)
49
+ const rawPlan = operation.plan(Object.freeze({ __proto__: null, ...context, prepared, now: new Date().toISOString(), newId: crypto.randomUUID() }), body)
50
+ validatePlan(rawPlan)
51
+ const plan = enforcePlan(kernelFor(config), scope, rawPlan, memberMode)
52
+ conflict = plan.conflict
53
+ const event = makeEvent(config, scope, plan.event.operation, plan.event.entity, plan.event.entityId, plan.event.before, plan.event.after, plan.event.details)
54
+ const runId = crypto.randomUUID()
55
+ const response = policyIdentity ? receiptExpression(config, plan.rules, runId, plan.result, policyIdentity) : { sql: '?', bindings: [JSON.stringify(plan.result)] }
56
+ const submission: StorePlan = { runId, rules: [...plan.rules,
57
+ { name: 'audit_outbox', statements: [outboxInsert(event, { sql: 'NOT EXISTS (SELECT 1 FROM atomic_assert WHERE run_id=? AND ok<>1)', bindings: [runId] })] },
58
+ ...(key ? [{ name: 'idempotency_key', statements: [{ sql: `INSERT INTO idempotency_keys (organization_id,key,command,response_json,request_hash) SELECT ?,?,?,${response.sql},? WHERE changes()=1`, bindings: [scope.organizationId, key, operation.name, ...(response.bindings ?? []), hash!], expectRows: 1 as const }] }] : []),
59
+ ] }
60
+ // Validate for every adapter, including capability markers and SQL shape.
61
+ compile(submission)
62
+ await store.run(submission)
63
+ return plan.result
64
+ } catch (error) {
65
+ const winner = await replay()
66
+ if (winner) return winner
67
+ if (error instanceof RuleFailed && conflict) throw new RuleFailed(error.rule, conflict)
68
+ throw error
69
+ }
70
+ }
@@ -0,0 +1,55 @@
1
+ import { writeGuard, policyCapture, policyAssertion, policyMutation } from './policies'
2
+ import type { AtomicPlan, StorePlan, SqlStatement } from './types'
3
+ import { UnsupportedAtomicOperation } from './errors'
4
+
5
+ function description(value: unknown): void {
6
+ if (typeof value === 'function' || (value && typeof value === 'object' && 'then' in value)) throw new UnsupportedAtomicOperation('Plans must be synchronous descriptions')
7
+ if (Array.isArray(value)) value.forEach(description)
8
+ else if (value && typeof value === 'object') Object.values(value).forEach(description)
9
+ }
10
+ export function validatePlan(plan: AtomicPlan): void {
11
+ description(plan)
12
+ if (plan.remoteCall || plan.dependsOnPriorWrite) throw new UnsupportedAtomicOperation('Remote calls and JavaScript dependencies on writes require a workflow')
13
+ if (plan.databases?.some(db => db !== 'primary') || (plan.databases?.length ?? 0) > 1) throw new UnsupportedAtomicOperation('An atomic plan targets exactly one database')
14
+ if (!plan.rules?.length || !plan.rules.some(rule => rule.statements.length)) throw new UnsupportedAtomicOperation('An atomic plan needs SQL rules')
15
+ if (plan.rules.some(rule => rule.statements.some(statement => 'policyGuard' in statement))) throw new UnsupportedAtomicOperation('Policy guard metadata is execution-owned')
16
+ }
17
+ export function readOnly(query: SqlStatement): void {
18
+ // Deliberately narrow. WITH/PRAGMA and multi-statement SQL are not reader capabilities.
19
+ if (!/^\s*SELECT\b/i.test(query.sql) || /;|--|\/\*/.test(query.sql)) throw new UnsupportedAtomicOperation('Preparation and diagnosis accept one SELECT only')
20
+ }
21
+ /** Assertions immediately follow their writes: changes() therefore refers to that write. */
22
+ export function compile(plan: StorePlan): SqlStatement[] {
23
+ description(plan)
24
+ const sql: SqlStatement[] = []
25
+ const postImages: SqlStatement[] = []
26
+ let step = 0
27
+ let policyIndex = 0
28
+ if (!plan.rules?.length || !plan.rules.some(rule => rule.statements.length)) throw new UnsupportedAtomicOperation('An atomic plan needs SQL rules')
29
+ for (const rule of plan.rules) {
30
+ if (!/^[a-z][a-z0-9_]*$/.test(rule.name)) throw new UnsupportedAtomicOperation('Invalid rule name')
31
+ for (const statement of rule.statements) {
32
+ if (statement.bindings?.some(value => value !== null && typeof value !== 'string' && (typeof value !== 'number' || !Number.isFinite(value)))) throw new UnsupportedAtomicOperation('SQL bindings must be values known before execution')
33
+ if (statement.database && statement.database !== 'primary') throw new UnsupportedAtomicOperation('Cross-database statement')
34
+ if (!/^\s*(INSERT|UPDATE|DELETE)\b/i.test(statement.sql) || /;|--|\/\*/.test(statement.sql) || /^\s*(?:INSERT\s+(?:OR\s+\w+\s+)?INTO|UPDATE(?:\s+OR\s+\w+)?|DELETE\s+FROM)\s+["`\[]?atomic_assert\b/i.test(statement.sql)) throw new UnsupportedAtomicOperation('Rules accept one domain DML statement only')
35
+ if (statement.expectRows !== undefined && statement.expectRows !== 1 && statement.expectRows !== '>=1') throw new UnsupportedAtomicOperation('Unsupported row expectation')
36
+ if (statement.diagnose) readOnly(statement.diagnose)
37
+ const guard = writeGuard(statement)
38
+ // Adapter-owned unguarded statements must not shift receipt capture identities.
39
+ const index = guard ? policyIndex++ : -1
40
+ if (guard) sql.push(...policyCapture(guard, plan.runId, index))
41
+ sql.push(guard ? policyMutation(statement, guard, plan.runId, index) : { sql: statement.sql, bindings: statement.bindings })
42
+ if (statement.expectRows !== undefined) sql.push({
43
+ sql: `INSERT INTO atomic_assert (run_id,rule,step,${guard && !statement.diagnose ? 'ok,policy_ok' : 'ok'}) VALUES (?,?,?,${guard && !statement.diagnose ? '1,' : ''}(SELECT changes()) ${statement.expectRows === 1 ? '=' : '>='} 1)`,
44
+ bindings: [plan.runId, rule.name, step++],
45
+ })
46
+ if (guard) {
47
+ const assertion = policyAssertion(guard, plan.runId, index)
48
+ postImages.push({ sql: `INSERT INTO atomic_assert (run_id,rule,step,ok,policy_ok) VALUES (?,?,?,1,(${assertion.sql}))`, bindings: [plan.runId, 'policy_violation', step++, ...(assertion.bindings ?? [])] })
49
+ }
50
+ }
51
+ }
52
+ sql.push(...postImages)
53
+ sql.push({ sql: 'DELETE FROM atomic_assert WHERE run_id=?', bindings: [plan.runId] })
54
+ return sql
55
+ }