@workbasehq/core 0.2.9 → 0.2.11

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workbasehq/core",
3
- "version": "0.2.9",
3
+ "version": "0.2.11",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./src/index.ts",
@@ -59,7 +59,7 @@
59
59
  "description": "Configuration, authorization, migrations and runtime primitives for Workbase applications.",
60
60
  "repository": {
61
61
  "type": "git",
62
- "url": "git+https://github.com/jakubknejzlik/workbase.git",
62
+ "url": "git+https://github.com/jakubknejzlik/workbase-sdk.git",
63
63
  "directory": "packages/core"
64
64
  },
65
65
  "bin": {
@@ -4,18 +4,18 @@ import type { SqlStatement } from './execution/types'
4
4
  import { quote } from './migrations/schema'
5
5
  import { ApiError } from './errors'
6
6
  import type { RuntimeEnv } from './types'
7
- export async function accountProvisioning(env: RuntimeEnv, config: InstanceConfig, user: { id: string; email: string }, organizationId: string, role: string, now: string): Promise<SqlStatement[]> {
7
+ export async function accountProvisioning(env: RuntimeEnv, config: InstanceConfig, user: { id: string; email: string }, organizationId: string, role: string, now: string, roleError = 'account_provisioning_required'): Promise<SqlStatement[]> {
8
8
  if (config.account?.entity !== 'users') return []
9
- const storedRole = !config.entities.users.fields.role?.computed
10
- const existing = await env.DB.prepare(`SELECT organization_id${storedRole ? ',role' : ''} FROM users WHERE id=?`).bind(user.id).first<{ organization_id: string; role: string }>()
9
+ const existing = await env.DB.prepare('SELECT organization_id FROM users WHERE id=?').bind(user.id).first<{ organization_id: string }>()
11
10
  if (existing) {
12
11
  // A physical domain account has a single organization. Never move it, or
13
- // silently reuse a role from another workspace.
12
+ // silently reuse an account from another workspace.
14
13
  if (existing.organization_id !== organizationId) throw new ApiError(409, 'account_already_assigned')
15
- if (storedRole && existing.role !== role) return [{ sql: 'UPDATE users SET role=?,updated_at=?,version=version+1 WHERE id=? AND organization_id=? AND NOT EXISTS (SELECT 1 FROM memberships WHERE user_id=? AND organization_id=?)', bindings: [role, now, user.id, organizationId, user.id, organizationId] }]
16
14
  return []
17
15
  }
18
- const values: Record<string, string | number | null> = { id: user.id, email: user.email, organization_id: organizationId, created_at: now, updated_at: now, role, name: user.email }
16
+ const values: Record<string, string | number | null> = { id: user.id, email: user.email, organization_id: organizationId, created_at: now, updated_at: now, name: user.email }
17
+ const compatibility = accountRoleValue(config, role, roleError)
18
+ if (compatibility !== undefined) values.role = compatibility
19
19
  for (const field of Object.keys(values)) if (config.entities.users.fields[field]?.computed) delete values[field]
20
20
  for (const [field, definition] of Object.entries(config.entities.users.fields)) {
21
21
  if (definition.computed || Object.hasOwn(values, field)) continue
@@ -24,3 +24,13 @@ export async function accountProvisioning(env: RuntimeEnv, config: InstanceConfi
24
24
  }
25
25
  return [{ sql: `INSERT INTO users (${Object.keys(values).map(quote).join(',')}) SELECT ${Object.keys(values).map(() => '?').join(',')} WHERE NOT EXISTS (SELECT 1 FROM users WHERE id=?)`, bindings: [...Object.values(values), user.id] }]
26
26
  }
27
+
28
+ /** Legacy domain role is inert compatibility data, never membership authority. */
29
+ export function accountRoleValue(config: InstanceConfig, role: string, code = 'account_provisioning_required'): string | number | null | undefined {
30
+ const field = config.entities.users.fields.role
31
+ if (!field || field.computed) return undefined
32
+ if (field.type !== 'enum' || field.values?.includes(role)) return role
33
+ if (field.default !== undefined) return typeof field.default === 'boolean' ? Number(field.default) : field.default
34
+ if (field.required) throw new ApiError(400, code)
35
+ return null
36
+ }
@@ -3,6 +3,7 @@ import type { Child } from 'hono/jsx'
3
3
  import { z } from 'zod'
4
4
  import type { Field } from './config'
5
5
  import { ApiError } from './errors'
6
+ import { assertUnprotectedFields } from './user-links'
6
7
 
7
8
  export const Hidden = ({ name, value }: { name: string; value: unknown }) => <input type="hidden" name={name} value={String(value ?? '')} />
8
9
  export function Form({ action, csrf, children, label = 'Save' }: { action: string; csrf: string; children?: Child; label?: string }) {
@@ -23,6 +24,7 @@ export function FieldInput({ name, field, value, choices = [], error }: { name:
23
24
  value={field.type === 'datetime' && current ? String(current).replace(/Z$/, '') : String(current)} />}{field.type === 'ref' && choices.length === 90 ? <small>showing first 90 — use the API for more</small> : null}{error}</label>
24
25
  }
25
26
  export function entityBody(form: URLSearchParams, fields: Record<string, Field>) {
27
+ assertUnprotectedFields({ fields }, [...form.keys()])
26
28
  const result: Record<string, unknown> = {}
27
29
  for (const [key, field] of Object.entries(fields)) {
28
30
  if (field.readOnly || !form.has(key)) continue
package/src/commands.ts CHANGED
@@ -8,6 +8,7 @@ import { executeAtomic, defineAtomicOperation } from './execution/atomic'
8
8
  import { coreExecutionContext } from './execution/context'
9
9
  import { D1AtomicStore, D1AtomicReader } from './execution/d1'
10
10
  import type { AtomicOperation, AtomicResult } from './execution/types'
11
+ import { userLinkActionPermission } from './user-links'
11
12
 
12
13
  /** Compatibility names for the existing registry and trusted direct dispatcher. */
13
14
  export type CommandDefinition<S extends z.ZodType = z.ZodType> = AtomicOperation<S>
@@ -32,6 +33,7 @@ export async function executeCommand(ctx: CommandContext, name: string, input: u
32
33
  for (const grant of [operation.permission, ...(operation.additionalPermissions ?? [])]) {
33
34
  kernelFor(ctx.config).commandGuard({ name: operationName(operation), kind: 'entity', permission: grant }, ctx.scope, undefined)
34
35
  }
36
+ userLinkActionPermission(ctx.config, ctx.scope, operation)
35
37
  const raw = z.record(z.string(), z.unknown()).parse(typeof input === 'function' ? await input() : input)
36
38
  const { idempotencyKey, ...payload } = raw
37
39
  const key = z.string().min(1).max(128).optional().parse(idempotencyKey)
package/src/config.ts CHANGED
@@ -18,7 +18,7 @@ export { Q, Cond }
18
18
  /** SQLite date formatting with column operands; values use the library wire encoding. */
19
19
  export const Fn = { ...LibraryFn, strftime: (format: string, date: string) => Q.expr(`FN(${JSON.stringify(['STRFTIME', Q.value(format).serialize(), Q.expr(date).serialize()])})`) }
20
20
 
21
- export const CORE_VERSION = '0.2.9'
21
+ export const CORE_VERSION = '0.2.11'
22
22
  const navigationIconSchema = z.enum(['LayoutDashboard', 'Users', 'MapPin', 'Coins', 'Wallet', 'ArrowLeftRight', 'Settings', 'Building2', 'Activity', 'Workflow', 'Database', 'Folder'])
23
23
  const identifier = z.string().regex(/^[a-z][a-z0-9_]*$/)
24
24
  export const serializedExpressionSchema = z.union([z.string().min(1).max(32000), z.record(z.string(), z.unknown()).transform(value => JSON.stringify(value))])
@@ -28,6 +28,7 @@ export const fieldSchema = z.object({
28
28
  required: z.boolean().default(false), values: z.array(z.string()).optional(), entity: identifier.optional(),
29
29
  default: z.union([z.string(), z.number(), z.boolean(), z.null()]).optional(),
30
30
  min: z.number().optional(), readOnly: z.boolean().optional(), sensitive: z.boolean().optional(),
31
+ userLink: z.boolean().optional(),
31
32
  ui: z.strictObject({
32
33
  hidden: z.boolean().optional(),
33
34
  format: z.enum(['identifier']).optional(),
@@ -163,6 +164,12 @@ export function defineInstance(input: Omit<ShorthandInput, 'roles' | 'entities'
163
164
  if ((reserved.has(name) && !(name === 'users' && config.account?.entity === name)) || name === 'atomic_assert' || name.startsWith('sqlite_') || name.startsWith('d1_')) throw new Error(`Reserved entity: ${name}`)
164
165
  if (Object.keys(entity.fields).length > 90) throw new Error('Entity exceeds the supported field/parameter budget')
165
166
  for (const [key, field] of Object.entries(entity.fields)) {
167
+ if (field.userLink) {
168
+ if (name === 'users' || config.account?.entity !== 'users' || key !== 'user' || field.type !== 'ref' || field.entity !== 'users'
169
+ || field.required || field.computed || field.default != null || field.backfillFrom || field.renameFrom
170
+ || !Object.values(entity.relations).some(relation => !relation.many && relation.field === key && relation.entity === 'users')) throw new Error(`Invalid user link: ${name}.${key}`)
171
+ field.readOnly = true
172
+ }
166
173
  if (name === 'users' && ['email', 'password_hash', 'salt'].includes(key)) throw new Error(`Account identity field is private: ${key}`)
167
174
  if (field.computed) field.readOnly = true
168
175
  if (baseFields.includes(key)) throw new Error(`Reserved field: ${key}`)
package/src/crud.ts CHANGED
@@ -16,6 +16,7 @@ import { ApiError } from './errors'
16
16
  import { makeEvent, type AuditEvent } from './events'
17
17
  import { publishCommittedEvents } from './event-delivery'
18
18
  import { quote } from './migrations/schema'
19
+ import { assertUnprotectedFields } from './user-links'
19
20
  type Row = Record<string, any>
20
21
  export function permission(config: InstanceConfig, scope: Scope, entity: string, op: Operation) {
21
22
  kernelFor(config).permission(scope, entity, op)
@@ -85,7 +86,9 @@ export function crudRoutes(app: App, config: InstanceConfig, env: RuntimeEnv) {
85
86
  }))
86
87
  app.post('/api/:entity', async c => {
87
88
  const { name, definition, scope, table } = entity(c, 'create')
88
- const body = bodyValidator(definition).parse(await c.req.json()) as Row
89
+ const raw = z.record(z.string(), z.unknown()).parse(await c.req.json()) as Row
90
+ assertUnprotectedFields(definition, Object.keys(raw))
91
+ const body = bodyValidator(definition).parse(raw) as Row
89
92
  const key = z.string().min(1).max(128).optional().parse(c.req.header('Idempotency-Key'))
90
93
  const operation = `${name}.create`
91
94
  const hash = key ? await requestHash(operation, body) : undefined
@@ -105,7 +108,7 @@ export function crudRoutes(app: App, config: InstanceConfig, env: RuntimeEnv) {
105
108
  const now = new Date().toISOString()
106
109
  const row: Row = { id: crypto.randomUUID(), organization_id: scope.organizationId, created_at: now, updated_at: now, version: 1 }
107
110
  for (const [key, f] of Object.entries(definition.fields)) if (!f.computed && (!definition.label || key !== definition.displayField)) row[key] = Object.hasOwn(body, key) ? body[key] : f.default ?? null
108
- const keys = Object.keys(row)
111
+ const keys = Object.keys(row).filter(key => !definition.fields[key]?.userLink)
109
112
  assertActorFields(config, scope, name, Object.keys(body))
110
113
  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
114
  ...(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!)] : []),
@@ -118,7 +121,8 @@ export function crudRoutes(app: App, config: InstanceConfig, env: RuntimeEnv) {
118
121
  })
119
122
  app.patch('/api/:entity/:id', async c => {
120
123
  const { name, definition, scope, table } = entity(c, 'update')
121
- const raw = await c.req.json<Row>()
124
+ const raw = z.record(z.string(), z.unknown()).parse(await c.req.json()) as Row
125
+ assertUnprotectedFields(definition, Object.keys(raw))
122
126
  const expected = Number(c.req.header('If-Match')?.replaceAll('"', '') ?? raw.version)
123
127
  if (!Number.isSafeInteger(expected) || expected < 1) throw new ApiError(400, 'version_required')
124
128
  delete raw.version
@@ -31,7 +31,7 @@ export class D1AtomicStore implements AtomicStore {
31
31
  if (!statement.diagnose) continue
32
32
  try {
33
33
  const diagnosis = await reader.first<{ ok: number }>(statement.diagnose)
34
- if (!diagnosis?.ok) throw new RuleFailed(rule.name)
34
+ if (!diagnosis?.ok) throw new RuleFailed(rule.name, statement.failureCode)
35
35
  } catch (diagnosisError) {
36
36
  if (diagnosisError instanceof RuleFailed) throw diagnosisError
37
37
  // Diagnostic failure cannot change the guaranteed atomic rejection.
@@ -6,6 +6,7 @@ import { quote } from '../migrations/schema'
6
6
  import type { Scope } from '../types'
7
7
  import type { AtomicPlan, GuardedStatement, PolicyWriteGuard, SqlStatement, SqlValue } from './types'
8
8
  import { UnsupportedAtomicOperation } from './errors'
9
+ import { assertUnprotectedFields, userLinkWriter, userLinkPolicyFilter } from '../user-links'
9
10
 
10
11
  export type WriteGuard = PolicyWriteGuard
11
12
  export const writeGuard = (statement: GuardedStatement) => Object.hasOwn(statement, 'policyGuard') ? statement.policyGuard : undefined
@@ -54,9 +55,51 @@ function operand(token: Token, bindings: readonly SqlValue[]): SqlValue {
54
55
  throw new UnsupportedAtomicOperation('Policy INSERT requires a constant or bound id')
55
56
  }
56
57
  export function enforcePlan(kernel: KernelRegistry, scope: Scope, plan: AtomicPlan, memberManagement?: 'update' | 'create'): AtomicPlan {
58
+ // This invariant also applies to service workflow compensation, independently
59
+ // of row-policy bypass. Only core-minted, immutable statements may write links.
60
+ for (const rule of plan.rules) for (const statement of rule.statements) {
61
+ if (userLinkWriter(statement)) continue
62
+ const ts = tokens(statement.sql)
63
+ const operation = ts[0]?.text.toUpperCase()
64
+ if (operation !== 'UPDATE' && operation !== 'INSERT') continue
65
+ const linkIdentifier = (token: Token) => identifier(token).replace(/^'|'$/g, '')
66
+ let targetIndex = ts[1]?.text.toUpperCase() === 'OR' ? 3 : 1
67
+ if (operation === 'INSERT') targetIndex++ // INTO
68
+ if (ts[targetIndex + 1]?.text === '.') targetIndex += 2 // main.table
69
+ const target = ts[targetIndex]
70
+ const definition = target && kernel.config.entities[linkIdentifier(target)]
71
+ if (!definition || !Object.values(definition.fields).some(field => field.userLink)) continue
72
+ if (ts[1]?.text.toUpperCase() === 'OR' && ts[2]?.text.toUpperCase() === 'REPLACE') throw new ApiError(400, 'protected_field')
73
+ if (operation === 'INSERT') {
74
+ // Keep the closed INSERT dialect on linked entities, including service
75
+ // writes: later conflict arms must not introduce uninspected assignments.
76
+ if (ts.some((token, index) => token.depth === 0 && token.text.toUpperCase() === 'ON' && ts[index + 1]?.text.toUpperCase() === 'CONFLICT')) throw new ApiError(400, 'protected_field')
77
+ // Positional INSERT could write the link without naming it. Refuse it on
78
+ // linked entities, including service effects that bypass row policies.
79
+ if (ts[targetIndex + 1]?.text !== '(') throw new ApiError(400, 'protected_field')
80
+ const close = ts.findIndex(token => token.text === ')' && token.depth === 0)
81
+ assertUnprotectedFields(definition, ts.slice(targetIndex + 2, close).filter(token => token.text !== ',').map(linkIdentifier))
82
+ }
83
+ // Inspect UPDATE assignments, including tuple left-hand sides.
84
+ const start = ts.findIndex(token => token.depth === 0 && token.text.toUpperCase() === 'SET')
85
+ if (start >= 0) {
86
+ const end = ts.findIndex((token, index) => index > start && token.depth === 0 && token.text.toUpperCase() === 'WHERE')
87
+ const assignments = ts.slice(start + 1, end < 0 ? undefined : end)
88
+ // Include tuple assignment LHSs, even though the policy dialect refuses them.
89
+ const assigned: Token[] = []; let left = true
90
+ for (const token of assignments) {
91
+ if (token.depth === 0 && token.text === '=') left = false
92
+ else if (token.depth === 0 && token.text === ',') left = true
93
+ else if (left) assigned.push(token)
94
+ }
95
+ assertUnprotectedFields(definition, assigned.map(linkIdentifier))
96
+ }
97
+ }
57
98
  if (scope.actor.type === 'service' && scope.role === 'SYSTEM') return plan
58
99
  const protectedFields = protectedActorFields(kernel.config)
59
100
  return { ...plan, rules: plan.rules.map(rule => ({ ...rule, statements: rule.statements.map(original => {
101
+ // Cascading revocation and stored invitation targets carry their own authority.
102
+ if (userLinkWriter(original) === 'cleanup') return original
60
103
  const ts = tokens(original.sql); const top = ts.filter(t => t.depth === 0)
61
104
  const operation = ts[0]?.text.toUpperCase()
62
105
  const target = operation === 'UPDATE' ? ts[1] : operation === 'DELETE' ? ts[2] : operation === 'INSERT' && ts[1]?.text.toUpperCase() === 'INTO' ? ts[2] : undefined
@@ -69,14 +112,14 @@ export function enforcePlan(kernel: KernelRegistry, scope: Scope, plan: AtomicPl
69
112
  if (account && ['INSERT', 'UPDATE'].includes(operation!) && memberManagement === 'create') return original
70
113
  // Existing system writers retain their narrowly authorized paths.
71
114
  if (!domain && !member) return original
72
- const filter = domain ? kernel.tableFilter(entity, scope) : { kind: 'all' as const }
73
- if (filter.kind === 'none') throw new ApiError(403, 'policy_violation')
115
+ const liveFilter = userLinkPolicyFilter(original)
116
+ if (!liveFilter && domain && kernel.tableFilter(entity, scope).kind === 'none') throw new ApiError(403, 'policy_violation')
74
117
  const protect = account || member
75
118
  if (!domain && !protect) return original
76
119
  if (ts.some((token, i) => token.text === '?' && ts[i + 1]?.start === token.end && /^\d/.test(ts[i + 1].text)) || ts.some(token => [':', '@', '$'].includes(token.text))) throw new UnsupportedAtomicOperation('Policy SQL uses plain positional bindings')
77
120
  const bindings = original.bindings ?? []
78
121
  const statement = { ...original }
79
- const guard: WriteGuard = { entity, operation: operation!, requireRow: original.expectRows !== undefined, filter: domain ? writeFilter(kernel, scope, entity) : { sql: `${quote(entity)}.${quote('organization_id')}=?`, bindings: [scope.organizationId] } }
122
+ const guard: WriteGuard = { entity, operation: operation!, requireRow: original.expectRows !== undefined, filter: liveFilter ?? (domain ? writeFilter(kernel, scope, entity) : { sql: `${quote(entity)}.${quote('organization_id')}=?`, bindings: [scope.organizationId] }) }
80
123
  if (operation === 'UPDATE' || operation === 'DELETE') {
81
124
  const where = top.find(t => t.text.toUpperCase() === 'WHERE')
82
125
  const set = top.find(t => t.text.toUpperCase() === 'SET')
@@ -17,6 +17,8 @@ export interface GuardedStatement extends SqlStatement {
17
17
  expectRows?: 1 | '>=1'
18
18
  /** Optional read-only diagnosis after rollback; never decides whether to commit. */
19
19
  diagnose?: SqlStatement
20
+ /** Compatibility error when this statement's read-only diagnosis fails. */
21
+ failureCode?: string
20
22
  database?: string
21
23
  }
22
24
  export interface AtomicRule { name: string; statements: readonly GuardedStatement[] }
@@ -1,47 +1,4 @@
1
- const messages = {
2
- usage: 'usage: workbase-migrate migrate <database-id> <migration-directory> [--config <module-path>]; requires CLOUDFLARE_DEFAULT_ACCOUNT_ID and CLOUDFLARE_API_TOKEN',
3
- invalid_config_default_export: 'invalid_config_default_export',
4
- invalid_cloudflare_ids: 'invalid_cloudflare_ids',
5
- duplicate_migration_filename: 'duplicate_migration_filename',
6
- d1_query_failed: 'd1_query_failed',
7
- d1_api_failed: 'd1_api_failed',
8
- invalid_ledger_statement: 'invalid_ledger_statement',
9
- invalid_ledger_bindings: 'invalid_ledger_bindings',
10
- migration_instance_verification_failed: 'migration_instance_verification_failed',
11
- migration_instance_revision_mismatch: 'migration_instance_revision_mismatch',
12
- migration_plugin_verification_failed: 'migration_plugin_verification_failed',
13
- no_migrations: 'no_migrations',
14
- } as const
15
-
16
- type Diagnostic = { code: keyof typeof messages }
17
- | { code: 'd1_http_status'; status: number }
18
- | { code: 'migration_history_mismatch' | 'migration_out_of_order' | 'invalid_migration_filename' | 'migration_sequence_gap_or_duplicate'; filename: unknown }
19
-
20
- const filenameCodes = new Set(['migration_history_mismatch', 'migration_out_of_order', 'invalid_migration_filename', 'migration_sequence_gap_or_duplicate'])
21
-
22
- // The brand and saved text cannot be forged by setting Error.name/message/prototype.
23
- const diagnostics = new WeakMap<object, string>()
24
- export class MigrationDiagnostic extends Error {
25
- constructor(diagnostic: Diagnostic) {
26
- let message: string
27
- if (diagnostic.code === 'd1_http_status') {
28
- const status = diagnostic.status
29
- message = `d1_http_status${Number.isInteger(status) && status >= 100 && status <= 599 ? `:${status}` : ''}`
30
- } else if ('filename' in diagnostic && filenameCodes.has(diagnostic.code)) {
31
- const filename = diagnostic.filename
32
- // Filesystem paths and arbitrary ledger/API values are not safe diagnostics.
33
- message = diagnostic.code + (typeof filename === 'string' && /^[0-9]{4}_[a-zA-Z0-9_-]{1,200}\.sql$/.test(filename) && !filename.includes('\n') ? `:${filename}` : '')
34
- } else {
35
- message = Object.hasOwn(messages, diagnostic.code) ? messages[diagnostic.code as keyof typeof messages] : 'migration_failed'
36
- }
37
- super(message)
38
- diagnostics.set(this, message)
39
- }
40
- }
41
-
42
- export function internalMigrationMessage(error: unknown): string | undefined {
43
- return typeof error === 'object' && error !== null ? diagnostics.get(error) : undefined
44
- }
1
+ export { MigrationDiagnostic, internalMigrationMessage } from '../migrations/diagnostics'
45
2
 
46
3
  /** Redact literal and JSON-escaped values, including secrets in otherwise safe fields. */
47
4
  export function redactCliOutput(text: string, env: NodeJS.ProcessEnv): string {
@@ -1,11 +1,12 @@
1
+ import { coreMigrations } from '../migrations/model-b'
1
2
  import { sha256 } from '../crypto'
2
3
  import type { WorkbasePlugin } from './plugin'
3
4
  import type { InstanceConfig } from '../config'
4
5
 
5
6
  /** Per-plugin append-only ledgers. Absent namespaces are retained on uninstall. */
6
- export async function applyPluginMigrations(db: D1Database, plugins: readonly WorkbasePlugin[]) {
7
+ export async function applyPluginMigrations(db: D1Database, plugins: readonly WorkbasePlugin[], config?: InstanceConfig) {
7
8
  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
+ for (const plugin of ledgerPlugins(plugins, config)) {
9
10
  const migrations = plugin.migrations ?? []
10
11
  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
12
  const checksums = await Promise.all(migrations.map(m => sha256(m.sql)))
@@ -18,7 +19,8 @@ export async function applyPluginMigrations(db: D1Database, plugins: readonly Wo
18
19
  // D1 batch is transactional. SQL is supplied as statements by trusted plugins.
19
20
  // exec supports multi-statement SQL but is not transactional with the ledger;
20
21
  // prepare/batch keeps DDL, data changes and their ledger entry atomic.
21
- const statements = splitStatements(migration.sql).map(sql => db.prepare(sql))
22
+ const sql = migration.statements ? (await migration.statements(db)).flatMap(splitStatements) : splitStatements(migration.sql)
23
+ const statements = sql.map(statement => db.prepare(statement))
22
24
  await db.batch([...statements, db.prepare('INSERT INTO _plugin_migrations (namespace,name,position,checksum) VALUES (?,?,?,?)').bind(plugin.name, migration.name, position, checksums[position])])
23
25
  }
24
26
  }
@@ -61,16 +63,22 @@ function splitStatements(sql: string): string[] {
61
63
 
62
64
  export interface PluginMigrationRow { namespace: string; name: string; position: number; checksum: string }
63
65
  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) }))))
66
+ const rows = await Promise.all(ledgerPlugins(plugins).flatMap(plugin => (plugin.migrations ?? []).map(async (migration, position) => ({ namespace: plugin.name, name: migration.name, position, checksum: await sha256(migration.sql) }))))
65
67
  return rows.sort((a, b) => a.namespace < b.namespace ? -1 : a.namespace > b.namespace ? 1 : a.position - b.position)
66
68
  }
67
69
  export async function pluginMigrationStatus(db: D1Database, plugins: readonly WorkbasePlugin[], config: Pick<InstanceConfig, 'entities'>) {
68
70
  for (const plugin of plugins) await plugin.checkSchema?.(db, config)
69
71
  const expected = await expectedPluginMigrations(plugins)
70
- const names = new Set(plugins.map(plugin => plugin.name))
72
+ const names = new Set(ledgerPlugins(plugins).map(plugin => plugin.name))
71
73
  const { results } = await db.prepare('SELECT namespace,name,position,checksum FROM _plugin_migrations ORDER BY namespace,position').all<PluginMigrationRow>()
72
74
  // Uninstalled namespaces remain on disk but cannot satisfy installed contracts.
73
75
  const applied = results.filter(row => names.has(row.namespace))
74
76
  const hash = (rows: PluginMigrationRow[]) => sha256(JSON.stringify(rows.map(({ namespace, name, position, checksum }) => ({ namespace, name, position, checksum }))))
75
77
  return { expected: await hash(expected), applied: await hash(applied) }
76
78
  }
79
+
80
+ /** Reserved core namespace shares the same transaction and verification contract. */
81
+ function ledgerPlugins(plugins: readonly WorkbasePlugin[], config?: InstanceConfig): readonly WorkbasePlugin[] {
82
+ if (plugins.some(plugin => plugin.name === 'workbase-core')) throw new Error('Reserved migration namespace: workbase-core')
83
+ return [{ name: 'workbase-core', version: '1.0.0', migrations: coreMigrations(config) }, ...plugins]
84
+ }
@@ -33,7 +33,13 @@ export interface KernelCommand {
33
33
  permission: AtomicOperation['permission'] | { system: ResourceAction }
34
34
  additionalPermissions?: AtomicOperation['additionalPermissions']
35
35
  }
36
- export interface PluginMigration { name: string; sql: string }
36
+ export interface PluginMigration {
37
+ name: string
38
+ /** Immutable SQL or static identity, hashed in the append-only ledger. */
39
+ sql: string
40
+ /** Trusted schema-derived SQL; reads precede the atomic statements + receipt batch. */
41
+ statements?: (db: D1Database) => Promise<readonly string[]>
42
+ }
37
43
  export interface PluginMcpTool { name: string; description: string; inputSchema: ZodType }
38
44
  export interface PluginContext { readonly config: InstanceConfig }
39
45
  export interface WorkbasePlugin {
@@ -14,6 +14,7 @@ export { renderPredicate } from './predicate'
14
14
  import { resolvePlugins } from './composition'
15
15
  import { applyPluginMigrations } from './migrations'
16
16
  import { timed } from '../request-timing'
17
+ import { userLinkCommands, userLinkActionPermission } from '../user-links'
17
18
 
18
19
  const registries = new WeakMap<InstanceConfig, KernelRegistry>()
19
20
  export const lifecyclePhases = ['contribute', 'validate', 'migrations', 'ports', 'mount'] as const
@@ -58,6 +59,10 @@ export class KernelRegistry {
58
59
  this.config = defineInstance({ ...config, plugins: this.plugins, entities, commands: commandNames,
59
60
  ...(config.pluginConfig || Object.keys(pluginConfig).length ? { pluginConfig } : {}) })
60
61
  this.providers.get('console')?.[0]?.validateConsole?.(this.config)
62
+ for (const command of userLinkCommands(this.config)) {
63
+ commands.push(command)
64
+ if (!this.config.commands.includes(command.name)) this.config.commands.push(command.name)
65
+ }
61
66
  this.commands = createCommandRegistry(commands)
62
67
  this.workflows = createWorkflowRegistry(workflows)
63
68
  // migrations: append hooks to the supplied chain. Applying D1 migrations remains an operator action.
@@ -82,7 +87,7 @@ export class KernelRegistry {
82
87
  }
83
88
  get audit() { return this.providers.get('audit')?.[0]?.audit }
84
89
  /** Explicit operator action; never run migrations in a request or on uninstall. */
85
- applyMigrations(db: D1Database) { return applyPluginMigrations(db, this.plugins) }
90
+ applyMigrations(db: D1Database) { return applyPluginMigrations(db, this.plugins, this.config) }
86
91
  async resolveScopeId(db: D1Database, selected?: string): Promise<string> {
87
92
  const provider = this.providers.get('organizations')?.[0]
88
93
  if (!provider) {
@@ -182,6 +187,7 @@ export class KernelRegistry {
182
187
  }
183
188
  atomicPermission(scope: Scope, operation: AtomicOperation, input?: unknown) {
184
189
  this.commandGuard({ name: operationName(operation), kind: 'command', permission: operation.permission, additionalPermissions: operation.additionalPermissions }, scope, input)
190
+ userLinkActionPermission(this.config, scope, operation)
185
191
  }
186
192
  }
187
193
  /** Request and execution helpers only accept a validated, explicitly bound composition. */
@@ -0,0 +1,48 @@
1
+ const messages = {
2
+ usage: 'usage: workbase-migrate migrate <database-id> <migration-directory> [--config <module-path>]; requires CLOUDFLARE_DEFAULT_ACCOUNT_ID and CLOUDFLARE_API_TOKEN',
3
+ invalid_config_default_export: 'invalid_config_default_export',
4
+ invalid_cloudflare_ids: 'invalid_cloudflare_ids',
5
+ duplicate_migration_filename: 'duplicate_migration_filename',
6
+ d1_query_failed: 'd1_query_failed',
7
+ d1_api_failed: 'd1_api_failed',
8
+ invalid_ledger_statement: 'invalid_ledger_statement',
9
+ invalid_ledger_bindings: 'invalid_ledger_bindings',
10
+ migration_instance_verification_failed: 'migration_instance_verification_failed',
11
+ migration_instance_revision_mismatch: 'migration_instance_revision_mismatch',
12
+ migration_plugin_verification_failed: 'migration_plugin_verification_failed',
13
+ no_migrations: 'no_migrations',
14
+ } as const
15
+
16
+ type Diagnostic = { code: keyof typeof messages }
17
+ | { code: 'd1_http_status'; status: number }
18
+ | { code: 'migration_blocked'; reason: 'multiple_organizations' | 'account_organization_mismatch' | 'required_account_field'; userIds: string[]; field?: string }
19
+ | { code: 'migration_blocked'; reason: 'incoming_foreign_key_actions'; table: string; referencingTables: string[] }
20
+ | { code: 'migration_history_mismatch' | 'migration_out_of_order' | 'invalid_migration_filename' | 'migration_sequence_gap_or_duplicate'; filename: unknown }
21
+
22
+ const filenameCodes = new Set(['migration_history_mismatch', 'migration_out_of_order', 'invalid_migration_filename', 'migration_sequence_gap_or_duplicate'])
23
+
24
+ // The brand and saved text cannot be forged by setting Error.name/message/prototype.
25
+ const diagnostics = new WeakMap<object, string>()
26
+ export class MigrationDiagnostic extends Error {
27
+ constructor(diagnostic: Diagnostic) {
28
+ let message: string
29
+ if (diagnostic.code === 'migration_blocked') {
30
+ message = `migration_blocked:${diagnostic.reason}:${JSON.stringify(diagnostic.reason === 'incoming_foreign_key_actions' ? { table: diagnostic.table, referencingTables: diagnostic.referencingTables } : { field: diagnostic.field, userIds: diagnostic.userIds })}`
31
+ } else if (diagnostic.code === 'd1_http_status') {
32
+ const status = diagnostic.status
33
+ message = `d1_http_status${Number.isInteger(status) && status >= 100 && status <= 599 ? `:${status}` : ''}`
34
+ } else if ('filename' in diagnostic && filenameCodes.has(diagnostic.code)) {
35
+ const filename = diagnostic.filename
36
+ // Filesystem paths and arbitrary ledger/API values are not safe diagnostics.
37
+ message = diagnostic.code + (typeof filename === 'string' && /^[0-9]{4}_[a-zA-Z0-9_-]{1,200}\.sql$/.test(filename) && !filename.includes('\n') ? `:${filename}` : '')
38
+ } else {
39
+ message = Object.hasOwn(messages, diagnostic.code) ? messages[diagnostic.code as keyof typeof messages] : 'migration_failed'
40
+ }
41
+ super(message)
42
+ diagnostics.set(this, message)
43
+ }
44
+ }
45
+
46
+ export function internalMigrationMessage(error: unknown): string | undefined {
47
+ return typeof error === 'object' && error !== null ? diagnostics.get(error) : undefined
48
+ }
@@ -0,0 +1,145 @@
1
+ import type { InstanceConfig } from '../config'
2
+ import type { PluginMigration } from '../kernel/plugin'
3
+ import { accountRoleValue } from '../account-provisioning'
4
+ import { MigrationDiagnostic } from './diagnostics'
5
+ import { literal } from './schema'
6
+
7
+ // Identifiers originate in the live SQLite catalog, including plugin-owned names.
8
+ const identifier = (name: string) => `"${name.replaceAll('"', '""')}"`
9
+
10
+ /** Token positions keep quoted strings/comments and unrelated CHECKs byte-for-byte. */
11
+ export function withoutRoleChecks(sql: string): string {
12
+ const lexical = [...sql.matchAll(/--[^\n]*|\/\*[\s\S]*?\*\/|'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\]|[a-z_][a-z_0-9]*|[^\s]/gi)]
13
+ const comments = lexical.filter(token => token[0].startsWith('--') || token[0].startsWith('/*'))
14
+ const tokens = lexical.filter(token => !comments.includes(token))
15
+ const word = (i: number) => tokens[i]?.[0].replace(/^["`\[]|["`\]]$/g, '').toLowerCase()
16
+ const removals: [number, number][] = []
17
+ const precedingSeparators = new Map<number, number>()
18
+ let depth = 0; let segment = 0
19
+ for (let i = 0; i < tokens.length; i++) {
20
+ const token = tokens[i]
21
+ if (token[0] === '(') { depth++; if (depth === 1) segment = i + 1 }
22
+ if (token[0] === ')') depth--
23
+ if (token[0] === ',' && depth === 1) segment = i + 1
24
+ if (word(i) !== 'check' || word(i + 1) !== '(' || word(i + 2) !== 'role' || word(i + 3) !== 'in' || word(i + 4) !== '(') continue
25
+ let end = i + 5
26
+ while (/^'(?:''|[^'])*'$/.test(tokens[end]?.[0] ?? '')) {
27
+ end++
28
+ if (tokens[end]?.[0] !== ',') break
29
+ end++
30
+ }
31
+ if (word(end) !== ')' || word(end + 1) !== ')') continue
32
+ const start = word(i - 2) === 'constraint' ? i - 2 : i
33
+ end++
34
+ // SQLite accepts a conflict clause on table CHECKs. It belongs to the
35
+ // removed constraint; leaving it behind can change a preceding UNIQUE.
36
+ if (start === segment && /^on$/i.test(tokens[end + 1]?.[0] ?? '') && /^conflict$/i.test(tokens[end + 2]?.[0] ?? '') && /^(rollback|abort|fail|ignore|replace)$/i.test(tokens[end + 3]?.[0] ?? '')) end += 3
37
+ // Remove the separator independently: intervening comments/newlines belong
38
+ // to the schema, not to this constraint. Adjacent matches may share it.
39
+ if (start === segment) {
40
+ let separator = start - 1
41
+ if (tokens[end + 1]?.[0] === ',') {
42
+ separator = end + 1
43
+ precedingSeparators.set(separator, start - 1)
44
+ } else {
45
+ // Earlier adjacent CHECKs already own the intervening commas. The
46
+ // final one owns the comma before that entire run.
47
+ while (precedingSeparators.has(separator)) separator = precedingSeparators.get(separator)!
48
+ }
49
+ removals.push([tokens[separator].index!, tokens[separator].index! + 1])
50
+ }
51
+ let from = tokens[start].index!
52
+ while (from > 0 && /[^\S\r\n]/.test(sql[from - 1])) from--
53
+ removals.push([from, tokens[end].index! + tokens[end][0].length])
54
+ i = end
55
+ }
56
+ // Never consume a comment, even when it occurs inside a matched constraint.
57
+ const spans: [number, number][] = []
58
+ for (const [start, end] of removals) {
59
+ let from = start
60
+ for (const comment of comments) {
61
+ const left = comment.index!
62
+ const right = left + comment[0].length + (comment[0].startsWith('--') && sql[left + comment[0].length] === '\n' ? 1 : 0)
63
+ if (right <= from || left >= end) continue
64
+ if (from < left) spans.push([from, left])
65
+ from = right
66
+ }
67
+ if (from < end) spans.push([from, end])
68
+ }
69
+ const merged: [number, number][] = []
70
+ for (const [start, end] of spans.sort((a, b) => a[0] - b[0])) {
71
+ const previous = merged.at(-1)
72
+ if (previous && start <= previous[1]) previous[1] = Math.max(previous[1], end)
73
+ else merged.push([start, end])
74
+ }
75
+ for (const [start, end] of merged.reverse()) sql = sql.slice(0, start) + sql.slice(end)
76
+ return sql
77
+ }
78
+
79
+ async function backfill(db: D1Database, config?: InstanceConfig): Promise<string[]> {
80
+ if (config?.account?.entity !== 'users') return []
81
+ const multiple = await db.prepare('SELECT user_id FROM memberships GROUP BY user_id HAVING count(DISTINCT organization_id)>1 ORDER BY user_id').all<{ user_id: string }>()
82
+ if (multiple.results.length) throw new MigrationDiagnostic({ code: 'migration_blocked', reason: 'multiple_organizations', userIds: multiple.results.map(row => row.user_id) })
83
+ const misplaced = await db.prepare('SELECT DISTINCT m.user_id FROM memberships m JOIN users u ON u.id=m.user_id WHERE u.organization_id<>m.organization_id ORDER BY m.user_id').all<{ user_id: string }>()
84
+ if (misplaced.results.length) throw new MigrationDiagnostic({ code: 'migration_blocked', reason: 'account_organization_mismatch', userIds: misplaced.results.map(row => row.user_id) })
85
+ const { results: columns } = await db.prepare('SELECT name FROM pragma_table_info(\'memberships\')').all<{ name: string }>()
86
+ const hasCreatedAt = columns.some(column => column.name === 'created_at')
87
+ const { results: missing } = await db.prepare(`SELECT m.user_id,m.organization_id,m.role,${hasCreatedAt ? 'm.created_at' : 'NULL'} AS created_at,u.email,u.name FROM memberships m LEFT JOIN "user" u ON u.id=m.user_id WHERE NOT EXISTS (SELECT 1 FROM users a WHERE a.id=m.user_id AND a.organization_id=m.organization_id) ORDER BY m.user_id`).all<{ user_id: string; organization_id: string; role: string; created_at: string | null; email: string | null; name: string | null }>()
88
+ const statements: string[] = []
89
+ const blocked = new Map<string, Set<string>>()
90
+ const block = (field: string, userId: string) => { const ids = blocked.get(field) ?? new Set<string>(); ids.add(userId); blocked.set(field, ids) }
91
+ for (const row of missing) {
92
+ const values: Record<string, string | number | boolean | null> = { id: row.user_id, organization_id: row.organization_id, email: row.email, password_hash: '', salt: '', version: 1, name: row.name ?? row.user_id }
93
+ if (!config.entities.users.fields.name) delete values.name
94
+ try {
95
+ const role = accountRoleValue(config, row.role)
96
+ if (role !== undefined) values.role = role
97
+ } catch { block('role', row.user_id) }
98
+ for (const [field, definition] of Object.entries(config.entities.users.fields)) {
99
+ if (definition.computed) { delete values[field]; continue }
100
+ if (Object.hasOwn(values, field)) continue
101
+ if (definition.default !== undefined) values[field] = definition.default
102
+ else if (definition.required) block(field, row.user_id)
103
+ }
104
+ const now = "strftime('%Y-%m-%dT%H:%M:%fZ','now')"
105
+ const timestamps = { created_at: row.created_at ? literal(row.created_at) : now, updated_at: now }
106
+ statements.push(`INSERT INTO users (${[...Object.keys(values), ...Object.keys(timestamps)].map(identifier).join(',')}) SELECT ${[...Object.values(values).map(literal), ...Object.values(timestamps)].join(',')} WHERE NOT EXISTS (SELECT 1 FROM users WHERE id=${literal(row.user_id)} AND organization_id=${literal(row.organization_id)})`)
107
+ }
108
+ for (const [field, userIds] of blocked) throw new MigrationDiagnostic({ code: 'migration_blocked', reason: 'required_account_field', field, userIds: [...userIds] })
109
+ return statements
110
+ }
111
+
112
+ // Keep rebuild.ts's incoming_actions predicate: deferred checks cannot prevent
113
+ // CASCADE/SET NULL, and RESTRICT still checks immediately.
114
+ const incomingActions = (table: string) => `SELECT DISTINCT s.name FROM sqlite_schema s, pragma_foreign_key_list(s.name) fk WHERE s.type = 'table' AND s.name NOT GLOB '_cf_*' AND s.name NOT GLOB 'sqlite_*' AND lower(fk."table") = lower(${literal(table)}) AND (fk.on_delete <> 'NO ACTION' OR fk.on_update <> 'NO ACTION')`
115
+
116
+ export function coreMigrations(config?: InstanceConfig): readonly PluginMigration[] {
117
+ return [{ name: '001_model_b', sql: '-- Model B v1: preserve live role tables; backfill configured users accounts', async statements(db) {
118
+ const statements = await backfill(db, config)
119
+ const witnesses: string[] = []
120
+ const guard = 'workbase_model_b_guard'
121
+ for (const table of ['memberships', 'invitations', 'access_tokens']) {
122
+ const master = await db.prepare(`SELECT sql FROM sqlite_master WHERE type='table' AND name=${literal(table)}`).first<{ sql: string }>()
123
+ if (!master) continue
124
+ const sql = withoutRoleChecks(master.sql)
125
+ if (sql === master.sql) continue
126
+ const incoming = incomingActions(table)
127
+ const { results: referencing } = await db.prepare(`${incoming} ORDER BY s.name`).all<{ name: string }>()
128
+ if (referencing.length) throw new MigrationDiagnostic({ code: 'migration_blocked', reason: 'incoming_foreign_key_actions', table, referencingTables: referencing.map(row => row.name) })
129
+ witnesses.push(`INSERT INTO ${guard} (ok) SELECT NOT EXISTS (${incoming})`)
130
+ const { results: columns } = await db.prepare(`SELECT name FROM pragma_table_info(${literal(table)})`).all<{ name: string }>()
131
+ const { results: objects } = await db.prepare(`SELECT sql FROM sqlite_master WHERE tbl_name=${literal(table)} AND type IN ('index','trigger') AND sql IS NOT NULL ORDER BY type,name`).all<{ sql: string }>()
132
+ witnesses.push(`INSERT INTO ${guard} (ok) SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type='table' AND name=${literal(table)} AND sql=${literal(master.sql)}) AND (SELECT json_group_array(sql) FROM (SELECT sql FROM sqlite_master WHERE tbl_name=${literal(table)} AND type IN ('index','trigger') AND sql IS NOT NULL ORDER BY type,name))=${literal(JSON.stringify(objects.map(object => object.sql)))}`)
133
+ const fields = columns.map(column => identifier(column.name)).join(',')
134
+ const rows = identifier(`workbase_model_b_${table}_rows`)
135
+ statements.push(`CREATE TABLE ${rows} AS SELECT ${fields} FROM ${identifier(table)}`, `DROP TABLE ${identifier(table)}`, sql,
136
+ `INSERT INTO ${identifier(table)} (${fields}) SELECT ${fields} FROM ${rows}`, ...objects.map(object => object.sql), `DROP TABLE ${rows}`)
137
+ }
138
+ if (!statements.length) return []
139
+ // Like rebuild.ts: defer the graph, guard the final FK check in SQL, clean up
140
+ // before the ledger receipt. Failure rolls back DDL, rows and receipt together.
141
+ const accounts = config?.account?.entity === 'users' ? [`INSERT INTO ${guard} (ok) SELECT NOT EXISTS (SELECT user_id FROM memberships GROUP BY user_id HAVING count(DISTINCT organization_id)>1) AND NOT EXISTS (SELECT 1 FROM memberships m WHERE NOT EXISTS (SELECT 1 FROM users u WHERE u.id=m.user_id AND u.organization_id=m.organization_id))`] : []
142
+ return [`CREATE TABLE ${guard} (ok INTEGER CONSTRAINT rebuild_requires_review CHECK (ok = 1))`, 'PRAGMA defer_foreign_keys = ON', ...witnesses, ...statements, ...accounts,
143
+ `INSERT INTO ${guard} (ok) SELECT NOT EXISTS (SELECT 1 FROM pragma_foreign_key_check)`, `DROP TABLE ${guard}`, 'PRAGMA defer_foreign_keys = OFF']
144
+ } }]
145
+ }
@@ -36,3 +36,9 @@ export function organizationPermission(config: InstanceConfig, scope: Scope, act
36
36
  if ((action === 'members.read' || action === 'invitations.read') && config.roles.includes(scope.role)) return
37
37
  if (!Object.hasOwn(config.organizationPermissions, scope.role) || !config.organizationPermissions[scope.role].includes(action)) throw new ApiError(403, 'permission_denied')
38
38
  }
39
+
40
+ /** Exactly the normalized authored and built-in roles; SQL has no fixed role enum. */
41
+ export function validateRole(config: Pick<InstanceConfig, 'roles'>, role: string, code = 'unknown_role', status: 400 | 403 = 400): string {
42
+ if (!config.roles.includes(role)) throw new ApiError(status, code)
43
+ return role
44
+ }
@@ -2,10 +2,12 @@ import type { InstanceConfig, OrganizationAction } from './config'
2
2
  import { canGrantRole } from './execution/permissions'
3
3
  import type { Scope } from './identity'
4
4
  import type { AtomicRule, SqlStatement } from './execution/types'
5
+ import { clearAccountLinks } from './user-links'
5
6
 
6
- export function issuerGuard(config: InstanceConfig, scope: Scope, action: OrganizationAction | undefined, grantRole?: string) {
7
+ export function issuerGuard(config: InstanceConfig, scope: Scope, action: OrganizationAction | undefined, grantRole?: string, roleFilter: (role: string) => boolean = () => true) {
7
8
  const roles = config.roles.filter(role => action === undefined || config.organizationPermissions[role]?.includes(action))
8
9
  .filter(role => grantRole === undefined || canGrantRole(config, role, grantRole))
10
+ .filter(roleFilter)
9
11
  return { sql: `EXISTS (SELECT 1 FROM memberships issuer WHERE issuer.organization_id=? AND issuer.user_id=? AND issuer.role IN (${roles.map(() => '?').join(',') || 'NULL'}))`, values: [scope.organizationId, scope.actor.id, ...roles] }
10
12
  }
11
13
  /** Each gate raises an SQL assertion before any later membership, email or audit write. */
@@ -20,5 +22,5 @@ export function memberMutationRule(config: InstanceConfig, scope: Scope, userId:
20
22
  sql: remove ? `DELETE FROM memberships WHERE ${predicate}` : `UPDATE memberships SET role=? WHERE ${predicate}`,
21
23
  bindings: remove ? values : [role, ...values], expectRows: 1,
22
24
  diagnose: { sql: `SELECT EXISTS (SELECT 1 FROM memberships WHERE ${predicate}) AS ok`, bindings: values },
23
- }] }
25
+ }, ...(remove ? clearAccountLinks(config, scope, userId) : [])] }
24
26
  }
@@ -0,0 +1,123 @@
1
+ // Core-only account-link writers. No raw SQL or capability is exposed to clients.
2
+ import { z } from 'zod'
3
+ import type { InstanceConfig } from './config'
4
+ import type { Scope } from './types'
5
+ import { ApiError } from './errors'
6
+ import { quote } from './migrations/schema'
7
+ import type { AtomicOperation, AtomicRule, GuardedStatement, PlanningContext, SqlStatement } from './execution/types'
8
+ import { writeFilter } from './execution/policies'
9
+ import { kernelFor } from './kernel/registry'
10
+ import { organizationPermission } from './organization-permissions'
11
+ import { issuerGuard } from './organization-rules'
12
+
13
+ type LinkContext = Pick<PlanningContext, 'config' | 'scope' | 'now'>
14
+ // Frozen statement identity, rather than caller-supplied metadata, grants the exception.
15
+ const writers = new WeakMap<GuardedStatement, 'link' | 'cleanup'>()
16
+ const livePolicies = new WeakMap<GuardedStatement, SqlStatement>()
17
+ function writer(statement: GuardedStatement, mode: 'link' | 'cleanup'): GuardedStatement {
18
+ if (statement.bindings) Object.freeze(statement.bindings)
19
+ if (statement.diagnose) { Object.freeze(statement.diagnose.bindings); Object.freeze(statement.diagnose) }
20
+ Object.freeze(statement)
21
+ writers.set(statement, mode)
22
+ return statement
23
+ }
24
+ export const userLinkWriter = (statement: GuardedStatement) => writers.get(statement)
25
+ // Only these core-minted statements can substitute a prepared-role policy filter.
26
+ export const userLinkPolicyFilter = (statement: GuardedStatement) => livePolicies.get(statement)
27
+ export function userLinks(config: InstanceConfig) {
28
+ return Object.entries(config.entities).flatMap(([entity, definition]) => Object.entries(definition.fields)
29
+ .filter(([, field]) => field.userLink).map(([field]) => ({ entity, field })))
30
+ }
31
+ export function assertUnprotectedFields(definition: Pick<InstanceConfig['entities'][string], 'fields'>, fields: string[]) {
32
+ if (fields.some(field => definition.fields[field]?.userLink)) throw new ApiError(400, 'protected_field')
33
+ }
34
+ function linkField(config: InstanceConfig, entity: string) {
35
+ const found = userLinks(config).find(link => link.entity === entity)
36
+ if (!found) throw new ApiError(400, 'user_link_required')
37
+ return quote(found.field)
38
+ }
39
+ /** One SQL mutation rechecks uniqueness and membership inside the atomic batch.
40
+ * The invitation caller runs this AFTER its membership insert, in the same plan. */
41
+ export function linkAccountRow(ctx: LinkContext, entity: string, rowId: string, userId: string, invitation = false): AtomicRule {
42
+ const field = linkField(ctx.config, entity); const table = quote(entity)
43
+ const unique = `NOT EXISTS (SELECT 1 FROM ${table} other WHERE other.organization_id=? AND other.${field}=? AND other.id<>?)`
44
+ return { name: 'account_link', statements: [writer({
45
+ sql: `UPDATE ${table} SET ${field}=?,updated_at=?,version=version+1 WHERE organization_id=? AND id=? AND ${unique}
46
+ AND EXISTS (SELECT 1 FROM users u JOIN memberships m ON m.user_id=u.id AND m.organization_id=u.organization_id WHERE u.id=? AND u.organization_id=?)`,
47
+ bindings: [userId, ctx.now, ctx.scope.organizationId, rowId, ctx.scope.organizationId, userId, rowId, userId, ctx.scope.organizationId], expectRows: 1,
48
+ diagnose: { sql: `SELECT ${unique} AS ok`, bindings: [ctx.scope.organizationId, userId, rowId] }, failureCode: 'account_already_linked',
49
+ }, invitation ? 'cleanup' : 'link')] }
50
+ }
51
+ /** Config-derived registry, scoped to the removed membership's organization. */
52
+ export function clearAccountLinks(config: InstanceConfig, scope: Scope, userId: string): GuardedStatement[] {
53
+ return userLinks(config).map(({ entity, field }) => writer({
54
+ sql: `UPDATE ${quote(entity)} SET ${quote(field)}=NULL,updated_at=?,version=version+1 WHERE organization_id=? AND ${quote(field)}=?`,
55
+ bindings: [new Date().toISOString(), scope.organizationId, userId],
56
+ }, 'cleanup'))
57
+ }
58
+ /** Remove access clears ALL links of the account selected by this row. The source
59
+ * is cleared last so every statement reads the same selector inside the batch. */
60
+ export function unlinkAccountRow(ctx: LinkContext, entity: string, rowId: string): AtomicRule {
61
+ const field = linkField(ctx.config, entity)
62
+ const links = userLinks(ctx.config).sort((a, b) => Number(a.entity === entity) - Number(b.entity === entity))
63
+ return { name: 'account_unlink', statements: links.map(link => writer({
64
+ sql: `UPDATE ${quote(link.entity)} SET ${quote(link.field)}=NULL,updated_at=?,version=version+1 WHERE organization_id=? AND ${quote(link.field)}=(SELECT ${field} FROM ${quote(entity)} WHERE organization_id=? AND id=?)`,
65
+ bindings: [ctx.now, ctx.scope.organizationId, ctx.scope.organizationId, rowId],
66
+ }, 'cleanup')) }
67
+ }
68
+ /** No invitation columns/payload are introduced here; #176 supplies the target. */
69
+ export function invitationAccountLink(ctx: LinkContext, invitation: { entity?: string | null; row?: string | null }, userId: string): AtomicRule[] {
70
+ return invitation.entity && invitation.row ? [linkAccountRow(ctx, invitation.entity, invitation.row, userId, true)] : []
71
+ }
72
+
73
+ const actions = new WeakSet<object>()
74
+ export function userLinkActionPermission(config: InstanceConfig, scope: Scope, operation: AtomicOperation<any>) {
75
+ if (!actions.has(operation.plan)) return
76
+ kernelFor(config).resourcePermission(scope, 'invitations.create')
77
+ organizationPermission(config, scope, 'invitations.create')
78
+ }
79
+ interface PreparedIssuer { role: string; filter: SqlStatement }
80
+ export function userLinkCommands(config: InstanceConfig): AtomicOperation<any>[] {
81
+ return userLinks(config).flatMap(({ entity }) => (['link_account', 'remove_access'] as const).map(action => {
82
+ const rowId = z.string().min(1).meta({ referenceEntity: entity })
83
+ const inputSchema: z.ZodType<{ rowId: string; userId?: string }> = action === 'link_account'
84
+ ? z.strictObject({ rowId, userId: z.string().min(1).meta({ referenceEntity: 'users' }) }) : z.strictObject({ rowId })
85
+ const operation: AtomicOperation<typeof inputSchema, PreparedIssuer> = {
86
+ name: `${entity}/${action}`, permission: { entity, operation: 'update' },
87
+ ui: { label: action === 'link_account' ? { en: 'Link', cs: 'Propojit účet' } : { en: 'Remove access', cs: 'Odebrat přístup' } },
88
+ input: inputSchema,
89
+ async prepare(ctx, input) {
90
+ const policy = kernelFor(ctx.config).tableFilter(entity, ctx.scope)
91
+ if (policy.kind === 'none') throw new ApiError(404, 'not_found')
92
+ if (!await ctx.reader.first({ sql: `SELECT id FROM ${quote(entity)} WHERE organization_id=? AND id=?`, bindings: [ctx.scope.organizationId, input.rowId] })) throw new ApiError(404, 'not_found')
93
+ if (action === 'link_account' && !await ctx.reader.first({ sql: 'SELECT u.id FROM users u JOIN memberships m ON m.user_id=u.id AND m.organization_id=u.organization_id WHERE u.id=? AND u.organization_id=?', bindings: [input.userId!, ctx.scope.organizationId] })) throw new ApiError(404, 'member_not_found')
94
+ const kernel = kernelFor(ctx.config)
95
+ kernel.atomicPermission(ctx.scope, operation, input)
96
+ return { role: ctx.scope.role, filter: writeFilter(kernel, ctx.scope, entity) }
97
+ },
98
+ plan(ctx, input) {
99
+ // A concurrent role change requires a fresh request under that role.
100
+ const guard = issuerGuard(ctx.config, ctx.scope, 'invitations.create', undefined,
101
+ role => role === ctx.prepared.role)
102
+ const policy = ctx.prepared.filter
103
+ const mutation = action === 'link_account' ? linkAccountRow(ctx, entity, input.rowId, input.userId!) : unlinkAccountRow(ctx, entity, input.rowId)
104
+ if (action === 'link_account') for (const statement of mutation.statements) livePolicies.set(statement, policy)
105
+ const issuer: GuardedStatement = Object.freeze({
106
+ // Revocation requires the source pre-image only; clearing its link must
107
+ // not create a post-image policy requirement. Link checks both images
108
+ // through the normal policy guards on its actual mutation below.
109
+ sql: `UPDATE ${quote(entity)} SET version=version WHERE organization_id=? AND id=? AND ${guard.sql} AND ${policy.sql}`,
110
+ bindings: Object.freeze([ctx.scope.organizationId, input.rowId, ...guard.values, ...(policy.bindings ?? [])]), expectRows: 1,
111
+ })
112
+ // Its WHERE checks the live pre-image. Keep the executor's row capture
113
+ // and 403 denial, without checking the cleared source against the policy.
114
+ livePolicies.set(issuer, Object.freeze({ sql: '1=1' }))
115
+ return { rules: [{ name: 'account_link_issuer', statements: [issuer] }, mutation],
116
+ event: { operation: action === 'link_account' ? 'account.linked' : 'account.access_removed', entity, entityId: input.rowId },
117
+ result: { status: 200, body: { id: input.rowId } } }
118
+ },
119
+ }
120
+ actions.add(operation.plan)
121
+ return operation
122
+ }))
123
+ }