@workbasehq/core 0.2.15 → 0.3.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.
- package/package.json +18 -3
- package/src/access-evaluator.ts +72 -0
- package/src/access-guards.ts +35 -0
- package/src/access-inputs.ts +62 -0
- package/src/access-lock/cli.ts +34 -0
- package/src/access-lock.ts +183 -0
- package/src/access.ts +209 -0
- package/src/account-action-conditions.ts +27 -0
- package/src/account-command.ts +8 -0
- package/src/admin-ui.tsx +3 -2
- package/src/app.ts +3 -3
- package/src/canonical.ts +6 -0
- package/src/capabilities.ts +5 -3
- package/src/commands.ts +14 -8
- package/src/config.ts +105 -69
- package/src/console-build.ts +37 -0
- package/src/console-contract.ts +4 -0
- package/src/console-model.ts +2 -0
- package/src/console.ts +3 -3
- package/src/crud.ts +13 -7
- package/src/dev-mailbox.ts +35 -0
- package/src/display-identity.ts +12 -0
- package/src/execution/atomic.ts +17 -3
- package/src/execution/policies.ts +14 -6
- package/src/execution/policy-receipts.ts +6 -5
- package/src/execution/post-commit.ts +11 -0
- package/src/execution/types.ts +1 -1
- package/src/index.ts +2 -0
- package/src/infra/README.md +39 -3
- package/src/infra/d1-migrations.ts +4 -3
- package/src/infra/instance-migrations.ts +26 -5
- package/src/infra/provision-config-main.mjs +3 -3
- package/src/infra/provision-diagnostics.ts +4 -0
- package/src/infra/provision-plan.ts +34 -5
- package/src/infra/provision.ts +26 -4
- package/src/infra/schema.ts +1 -1
- package/src/kernel/invitation-mail-port.ts +26 -0
- package/src/kernel/mail-outbox-port.ts +4 -2
- package/src/kernel/migrations.ts +38 -15
- package/src/kernel/plugin.ts +2 -0
- package/src/kernel/predicate.ts +15 -3
- package/src/kernel/registry.ts +69 -12
- package/src/member-bootstrap.ts +65 -0
- package/src/member-identities.ts +42 -0
- package/src/migrations/diagnostics.ts +6 -1
- package/src/migrations/model-b.ts +2 -1
- package/src/migrations/operational-evidence.ts +51 -0
- package/src/migrations/planner.ts +12 -1
- package/src/migrations/rebuild.ts +17 -12
- package/src/migrations/reset-era.ts +29 -0
- package/src/migrations/schema-bundle.ts +43 -0
- package/src/migrations/schema-cli.ts +74 -0
- package/src/migrations/schema-git.ts +36 -0
- package/src/migrations/schema-lock.ts +159 -0
- package/src/migrations/schema-plan.ts +94 -0
- package/src/migrations/schema.ts +73 -48
- package/src/migrations/sdk-baseline.ts +35 -0
- package/src/migrations/system-schema.ts +39 -0
- package/src/model-inputs.ts +25 -0
- package/src/openapi/cli.ts +72 -0
- package/src/openapi/generate.ts +166 -0
- package/src/openapi/input-projection.ts +131 -0
- package/src/openapi/public-paths.ts +80 -0
- package/src/openapi/routes.ts +29 -0
- package/src/ops.ts +4 -2
- package/src/organization-name.ts +35 -0
- package/src/organization-permissions.ts +10 -0
- package/src/organizations.ts +72 -3
- package/src/policies.ts +22 -6
- package/src/public-projection.ts +108 -0
- package/src/public-schema.ts +5 -43
- package/src/query/input-schema.ts +89 -0
- package/src/query/limits.ts +1 -1
- package/src/query/schema.ts +11 -89
- package/src/record-action-routes.ts +87 -0
- package/src/record-actions-data.ts +17 -0
- package/src/record-actions.ts +61 -0
- package/src/record-read.ts +20 -0
- package/src/row-access.ts +11 -0
- package/src/row-invitations.ts +29 -0
- package/src/schema/README.md +323 -0
- package/src/schema/declaration.ts +5 -0
- package/src/schema/load.ts +423 -0
- package/src/schema/lock-format.ts +117 -0
- package/src/schema/physical-names.ts +30 -0
- package/src/schema/revision.ts +16 -0
- package/src/schema/source-location.ts +3 -0
- package/src/schema-compatibility.ts +2 -2
- package/src/schema.ts +171 -0
- package/src/types.ts +1 -1
- package/src/user-link-eligibility.ts +36 -0
- package/src/user-links.ts +27 -16
- package/src/worker-access-actions.ts +89 -0
- package/src/worker-access.ts +61 -0
- package/src/workflow-runtime.ts +109 -22
- package/src/bootstrap.ts +0 -23
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { readRecord } from './record-read'
|
|
2
|
+
import { isAccountAccessCommand } from './account-command'
|
|
3
|
+
import { z } from 'zod'
|
|
4
|
+
import { ApiError } from './errors'
|
|
5
|
+
import type { InstanceConfig } from './config'
|
|
6
|
+
import type { App, RuntimeEnv } from './types'
|
|
7
|
+
import { kernelFor } from './kernel/registry'
|
|
8
|
+
import { actionGuardSql } from './record-actions'
|
|
9
|
+
import { quote } from './migrations/schema'
|
|
10
|
+
import { executeAtomic } from './execution/atomic'
|
|
11
|
+
import { coreExecutionContext } from './execution/context'
|
|
12
|
+
import { D1AtomicReader, D1AtomicStore } from './execution/d1'
|
|
13
|
+
import { RuleFailed } from './execution/errors'
|
|
14
|
+
import type { AtomicStore, SqlStatement } from './execution/types'
|
|
15
|
+
|
|
16
|
+
function actionInputKeys(schema: any): string[] {
|
|
17
|
+
// Inspect input-side wrappers structurally, without executing transforms or
|
|
18
|
+
// relying on Zod constructor identity across module realms.
|
|
19
|
+
for (let depth = 0; schema && depth < 16; depth++) {
|
|
20
|
+
if (schema.shape) return Object.keys(schema.shape)
|
|
21
|
+
if (schema.in) schema = schema.in
|
|
22
|
+
else if (typeof schema.unwrap === 'function') schema = schema.unwrap()
|
|
23
|
+
else break
|
|
24
|
+
}
|
|
25
|
+
return []
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function recordActionRoutes(app: App, config: InstanceConfig, env: RuntimeEnv) {
|
|
29
|
+
if (config.baseline !== 'workbase-sdk') return
|
|
30
|
+
const kernel = kernelFor(config)
|
|
31
|
+
app.post('/api/:entity/:id/actions/:name', async c => {
|
|
32
|
+
const entity = c.req.param('entity'), id = c.req.param('id'), name = c.req.param('name')
|
|
33
|
+
const scope = c.get('scope'), policy = config.effectiveAccess!
|
|
34
|
+
// Establish GET's complete read authority before any ID-dependent callback.
|
|
35
|
+
await readRecord(config, scope, env, entity, id)
|
|
36
|
+
const action = policy.actions.find(action => action.entity === entity && action.name === name)
|
|
37
|
+
const operation = action && kernel.commands.get(action.command)
|
|
38
|
+
if (!action || !operation) throw new ApiError(404, 'not_found')
|
|
39
|
+
const guard = actionGuardSql(policy, scope, entity, name, 'throw')
|
|
40
|
+
if (!guard) throw new ApiError(404, 'not_found')
|
|
41
|
+
// Preserve every JSON key for strict validation, including __proto__.
|
|
42
|
+
const raw = await c.req.json()
|
|
43
|
+
const accountAction = isAccountAccessCommand(config, action.command)
|
|
44
|
+
// Invitation credentials are never selectors for a record action. Their
|
|
45
|
+
// rejection is independent of whether a foreign credential exists.
|
|
46
|
+
if (accountAction && raw && typeof raw === 'object' && ['token', 'invitation_id'].some(key => Object.hasOwn(raw, key))) throw new ApiError(404, 'not_found')
|
|
47
|
+
// Validate the body keys here; executeAtomic validates values and applies
|
|
48
|
+
// defaults/transforms exactly once through the command's input schema.
|
|
49
|
+
// Shape access is structural so schemas from another Zod realm work too.
|
|
50
|
+
const keys = actionInputKeys(operation.input).filter(key => !['id', 'rowId', 'role'].includes(key))
|
|
51
|
+
const body = z.strictObject(Object.fromEntries(keys.map(key => [key, z.unknown().optional()]))).parse(raw)
|
|
52
|
+
const input = { ...body, id }
|
|
53
|
+
const diagnose: SqlStatement = {
|
|
54
|
+
sql: `SELECT COALESCE((${guard.allowed.sql}),0) AS ok, ${guard.state.sql} AS reason FROM ${quote(entity)} WHERE id=? AND (${guard.read.sql})`,
|
|
55
|
+
bindings: [...(guard.allowed.bindings ?? []), ...(guard.state.bindings ?? []), id, ...(guard.read.bindings ?? [])],
|
|
56
|
+
}
|
|
57
|
+
const store = new D1AtomicStore(env.DB, { env, config }), reader = new D1AtomicReader(env.DB)
|
|
58
|
+
const guarded: AtomicStore = { run: plan => store.run({ ...plan, rules: [{ name: 'record_action', statements: [{
|
|
59
|
+
// A no-op DML supplies changes() for the existing expectRows assertion.
|
|
60
|
+
// It precedes every command write and rolls back with the whole batch.
|
|
61
|
+
sql: `UPDATE ${quote(entity)} SET id=id WHERE id=? AND (${guard.allowed.sql})`,
|
|
62
|
+
bindings: [id, ...(guard.allowed.bindings ?? [])], expectRows: 1, diagnose,
|
|
63
|
+
}] }, ...plan.rules] }) }
|
|
64
|
+
try {
|
|
65
|
+
const result = await executeAtomic(operation, input, coreExecutionContext(config, scope, guarded, reader))
|
|
66
|
+
if (accountAction && name === 'invite') c.header('Cache-Control', 'no-store')
|
|
67
|
+
return c.json(result.body, result.status as any)
|
|
68
|
+
} catch (error) {
|
|
69
|
+
// Prepare/planning errors must not outlive the record's visibility.
|
|
70
|
+
// Confirmed GET denials (403/404) conceal the command error; an inconclusive
|
|
71
|
+
// recheck (e.g. D1 outage surfacing as query_invalid) is an opaque 5xx.
|
|
72
|
+
try { await readRecord(config, scope, env, entity, id) }
|
|
73
|
+
catch (recheck) {
|
|
74
|
+
if (recheck instanceof ApiError && (recheck.status === 403 || recheck.status === 404)) throw recheck
|
|
75
|
+
throw new Error('record action visibility recheck failed', { cause: { recheck, error } })
|
|
76
|
+
}
|
|
77
|
+
if (!(error instanceof RuleFailed) && !(isAccountAccessCommand(config, action.command) && /UNIQUE constraint failed/i.test(String(error)))) throw error
|
|
78
|
+
// Diagnosis is read-only and runs only after atomic rollback. It cannot
|
|
79
|
+
// authorize a commit; hidden rows have precisely GET's error body.
|
|
80
|
+
const state = await reader.first<{ ok: number; reason: string | null }>(diagnose)
|
|
81
|
+
if (!state) throw new ApiError(404, 'not_found')
|
|
82
|
+
if (!state.ok) return c.json({ error: 'action_unavailable', reason: state.reason ?? 'sdk.action_unavailable' }, 409)
|
|
83
|
+
if (!(error instanceof RuleFailed)) throw new ApiError(409, 'invitation_pending')
|
|
84
|
+
throw error
|
|
85
|
+
}
|
|
86
|
+
})
|
|
87
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
import type { InstanceConfig } from './config'
|
|
3
|
+
|
|
4
|
+
export const recordActionsSchema = z.record(z.string().regex(/^[a-z][a-z0-9_]*$/), z.strictObject({
|
|
5
|
+
command: z.string().min(1),
|
|
6
|
+
available: z.array(z.strictObject({ when: z.record(z.string(), z.unknown()), reason: z.string().regex(/^[\w-]+(?:\.[\w-]+)+$/) })).optional(),
|
|
7
|
+
}))
|
|
8
|
+
type Operators = { eq?: unknown; ne?: unknown; in?: readonly unknown[]; lt?: unknown; lte?: unknown; gt?: unknown; gte?: unknown; contains?: string; isNull?: boolean }
|
|
9
|
+
export type ActionWhen<E extends { fields: object; relations?: object }> = {
|
|
10
|
+
[K in keyof E['fields'] | 'id' | 'organization_id' | 'created_at' | 'updated_at' | 'version']?: Operators
|
|
11
|
+
} & { [K in keyof NonNullable<E['relations']>]?: Record<string, unknown> } & {
|
|
12
|
+
use?: string; actorLinkedIn?: string; and?: ActionWhen<E>[]; or?: ActionWhen<E>[]; not?: ActionWhen<E>
|
|
13
|
+
}
|
|
14
|
+
/** Finite, untranslated keys for dictionary validation; no console dependency. */
|
|
15
|
+
export function actionReasonKeys(config: InstanceConfig): string[] {
|
|
16
|
+
return [...new Set(config.effectiveAccess?.actions.flatMap(action => action.conditions.map(condition => condition.reason)) ?? [])].sort()
|
|
17
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { commandPreflight } from './commands'
|
|
2
|
+
import { accountConditionSql } from './account-action-conditions'
|
|
3
|
+
import type { EffectiveAccessPolicy } from './access'
|
|
4
|
+
import { ApiError } from './errors'
|
|
5
|
+
import { kernelFor } from './kernel/registry'
|
|
6
|
+
import { rolePolicyFilter } from './policies'
|
|
7
|
+
import { writeFilter } from './execution/policies'
|
|
8
|
+
import type { SqlStatement } from './execution/types'
|
|
9
|
+
import type { InstanceConfig } from './config'
|
|
10
|
+
import type { Scope } from './types'
|
|
11
|
+
import { quote } from './migrations/schema'
|
|
12
|
+
|
|
13
|
+
const bindings = new WeakMap<EffectiveAccessPolicy, InstanceConfig>()
|
|
14
|
+
export function bindActionPolicy(policy: EffectiveAccessPolicy, config: InstanceConfig) { bindings.set(policy, config) }
|
|
15
|
+
|
|
16
|
+
export type ActionState = { enabled: true } | { enabled: false; reason: string }
|
|
17
|
+
/** One SQL definition shared by detail availability and the atomic dispatcher.
|
|
18
|
+
* False/NULL conditions both disable; CASE preserves authored reason order.
|
|
19
|
+
*/
|
|
20
|
+
export function actionGuardSql(policy: EffectiveAccessPolicy, scope: Scope, entity: string, name: string, denial: 'omit' | 'throw' = 'omit') {
|
|
21
|
+
const config = bindings.get(policy)!
|
|
22
|
+
const kernel = kernelFor(config)
|
|
23
|
+
const action = policy.actions.find(action => action.entity === entity && action.name === name)
|
|
24
|
+
if (!action) return undefined
|
|
25
|
+
const operation = kernel.commands.get(action.command)
|
|
26
|
+
if (!operation) return undefined
|
|
27
|
+
try {
|
|
28
|
+
commandPreflight(config, scope, operation)
|
|
29
|
+
kernel.atomicPermission(scope, operation)
|
|
30
|
+
}
|
|
31
|
+
catch (error) { if (denial === 'omit' && error instanceof ApiError && [403, 405].includes(error.status)) return undefined; throw error }
|
|
32
|
+
if (action.dependencies.some(path => {
|
|
33
|
+
const [target, field] = path.split('.')
|
|
34
|
+
return !kernel.fieldMask(target, scope).includes(field)
|
|
35
|
+
})) return undefined
|
|
36
|
+
if ('system' in operation.permission) return undefined
|
|
37
|
+
const read = writeFilter(kernel, scope, entity)
|
|
38
|
+
const write = writeFilter(kernel, scope, entity, entity, operation.permission.operation)
|
|
39
|
+
const conditions = action.conditions.map(condition => ({ ...condition,
|
|
40
|
+
...('opaque' in condition ? accountConditionSql(config, entity, condition) : writeFilter(kernel, scope, entity, entity, 'read', rolePolicyFilter(config, entity, scope, scope.role, { where: condition.when }))),
|
|
41
|
+
}))
|
|
42
|
+
const allowed: SqlStatement = { sql: [read, write, ...conditions].map(part => `(${part.sql})`).join(' AND '), bindings: [read, write, ...conditions].flatMap(part => [...(part.bindings ?? [])]) }
|
|
43
|
+
const reason: SqlStatement = { sql: `CASE ${conditions.map(part => `WHEN NOT COALESCE((${part.sql}),0) THEN ?`).join(' ')} ELSE NULL END`,
|
|
44
|
+
bindings: conditions.flatMap(part => [...(part.bindings ?? []), part.reason]) }
|
|
45
|
+
// A command write filter can narrow rows even without an authored condition.
|
|
46
|
+
// Its denial is unavailable, with a stable SDK key rather than a predicate leak.
|
|
47
|
+
const state: SqlStatement = { sql: conditions.length ? reason.sql : 'NULL', bindings: conditions.length ? reason.bindings : [] }
|
|
48
|
+
return { action, operation, read, allowed, state }
|
|
49
|
+
}
|
|
50
|
+
export async function recordActions(config: InstanceConfig, scope: Scope, db: D1Database, entity: string, id: string): Promise<Record<string, ActionState>> {
|
|
51
|
+
const policy = config.effectiveAccess!
|
|
52
|
+
const entries: [string, ActionState][] = []
|
|
53
|
+
for (const action of policy.actions.filter(action => action.entity === entity)) {
|
|
54
|
+
const guard = actionGuardSql(policy, scope, entity, action.name)
|
|
55
|
+
if (!guard) continue
|
|
56
|
+
const row = await db.prepare(`SELECT COALESCE((${guard.allowed.sql}),0) AS enabled, ${guard.state.sql} AS reason FROM ${quote(entity)} WHERE id=? AND (${guard.read.sql})`)
|
|
57
|
+
.bind(...(guard.allowed.bindings ?? []), ...(guard.state.bindings ?? []), id, ...(guard.read.bindings ?? [])).first<{ enabled: number; reason: string | null }>()
|
|
58
|
+
if (row) entries.push([action.name, row.enabled ? { enabled: true } : { enabled: false, reason: row.reason ?? 'sdk.action_unavailable' }])
|
|
59
|
+
}
|
|
60
|
+
return Object.fromEntries(entries)
|
|
61
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { InstanceConfig } from './config'
|
|
2
|
+
import type { RuntimeEnv, Scope } from './types'
|
|
3
|
+
import { ApiError } from './errors'
|
|
4
|
+
import { kernelFor } from './kernel/registry'
|
|
5
|
+
import { executeQuery, type QueryLog } from './query/executor'
|
|
6
|
+
import { restQuery } from './query/facade'
|
|
7
|
+
import { cursorSecret } from './query/routes'
|
|
8
|
+
|
|
9
|
+
/** Detail GET authority, including credentials, hooks, ID mask and SQL read filters.
|
|
10
|
+
* Action dispatch uses this before callbacks and again when normalizing errors.
|
|
11
|
+
*/
|
|
12
|
+
export async function readRecord(config: InstanceConfig, scope: Scope, env: RuntimeEnv, entity: string, id: string,
|
|
13
|
+
params: Record<string, string> = {}, writeLog?: (log: QueryLog) => void) {
|
|
14
|
+
if (!Object.hasOwn(config.entities, entity)) throw new ApiError(404, 'entity_not_found')
|
|
15
|
+
const kernel = kernelFor(config)
|
|
16
|
+
kernel.readPermission(scope, entity)
|
|
17
|
+
const result = await executeQuery(kernel, scope, env.DB, await cursorSecret(env), restQuery(config, entity, params, id), { legacyErrors: true, writeLog })
|
|
18
|
+
if (!result.data.length) throw new ApiError(404, 'not_found')
|
|
19
|
+
return result.data[0]
|
|
20
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Members status discloses account identity through workspace members.read and the source link field grant.
|
|
2
|
+
* Storage currently holds one scalar link. The inconsistency result is reserved for
|
|
3
|
+
* adapters/legacy sources; invitation history is never treated as linked accounts. */
|
|
4
|
+
export interface RowAccessStatus {
|
|
5
|
+
state: 'invited' | 'expired' | 'signed_in' | 'no_account'
|
|
6
|
+
inconsistency: 'multiple_linked_accounts' | null
|
|
7
|
+
linked_accounts?: { id: string; label?: string }[]
|
|
8
|
+
can_invite: boolean
|
|
9
|
+
can_cancel: boolean
|
|
10
|
+
invitation?: { id: string; email: string; expires_at: string }
|
|
11
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { invitationRole } from './worker-access'
|
|
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 { userLinks } from './user-links'
|
|
8
|
+
import { writeFilter } from './execution/policies'
|
|
9
|
+
import { issuerGuard } from './organization-rules'
|
|
10
|
+
import { kernelFor } from './kernel/registry'
|
|
11
|
+
|
|
12
|
+
export const rowTargetSchema = z.strictObject({ entity: z.string().regex(/^[a-z][a-z0-9_]*$/), row: z.string().min(1).max(200) })
|
|
13
|
+
export type RowTarget = z.infer<typeof rowTargetSchema>
|
|
14
|
+
export function rowLink(config: InstanceConfig, target: RowTarget) {
|
|
15
|
+
const link = userLinks(config).find(link => link.entity === target.entity)
|
|
16
|
+
if (!link) throw new ApiError(400, 'user_link_required')
|
|
17
|
+
return link
|
|
18
|
+
}
|
|
19
|
+
/** Pin one prepared issuer role and compile its policy once. SQL rechecks the
|
|
20
|
+
* live role and the target pre-image in the same batch as the invitation claim. */
|
|
21
|
+
export function rowInvitationGuard(config: InstanceConfig, scope: Scope, target: RowTarget, available = true) {
|
|
22
|
+
const link = rowLink(config, target)
|
|
23
|
+
const policy = writeFilter(kernelFor(config), scope, target.entity, target.entity, 'create')
|
|
24
|
+
const issuer = issuerGuard(config, scope, 'invitations.create', invitationRole(config, target.entity), role => (scope.actor.type === 'agent' || role === scope.role) && !!config.permissions[role]?.[target.entity]?.includes('create'))
|
|
25
|
+
return {
|
|
26
|
+
sql: `${issuer.sql} AND EXISTS (SELECT 1 FROM ${quote(target.entity)} WHERE organization_id=? AND id=? ${available ? `AND ${quote(link.field)} IS NULL` : ''} AND ${policy.sql})`,
|
|
27
|
+
values: [...issuer.values, scope.organizationId, target.row, ...(policy.bindings ?? [])],
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
# Canonical entity declarations
|
|
2
|
+
|
|
3
|
+
`@workbasehq/core/schema` supplies runtime declarations and core schema types.
|
|
4
|
+
`@workbasehq/core/schema/load` is a separate build-time entry: it reads source with
|
|
5
|
+
TypeScript's compiler API, interprets the accepted literal declarations without
|
|
6
|
+
importing or executing consumer modules, and returns `{ config, sources }`. Keeping the loader separate prevents Node file
|
|
7
|
+
APIs and the TypeScript compiler from entering the runtime declaration graph.
|
|
8
|
+
|
|
9
|
+
Use a TypeScript-capable host such as Bun or tsx for loading, as with the existing
|
|
10
|
+
infrastructure config imports. TypeScript is a declared core dependency for the
|
|
11
|
+
loader; a consumer does not need an undeclared workspace dependency.
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
// schema/worker.ts
|
|
15
|
+
import { accountLink, defineEntity } from '@workbasehq/core/schema'
|
|
16
|
+
|
|
17
|
+
export default defineEntity({
|
|
18
|
+
fields: {
|
|
19
|
+
name: { type: 'text', required: true },
|
|
20
|
+
user: accountLink(),
|
|
21
|
+
},
|
|
22
|
+
displayField: 'name',
|
|
23
|
+
})
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
// config.ts
|
|
28
|
+
import { defineConfig } from '@workbasehq/core/schema'
|
|
29
|
+
import worker from './schema/worker.ts'
|
|
30
|
+
|
|
31
|
+
export default defineConfig({
|
|
32
|
+
id: 'sample',
|
|
33
|
+
roles: ['admin', 'staff'],
|
|
34
|
+
organizationOwnerRole: 'admin',
|
|
35
|
+
languages: ['cs', 'en'],
|
|
36
|
+
entities: { worker },
|
|
37
|
+
})
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
// A build/check entry, run with Bun or tsx.
|
|
42
|
+
import { loadConfig } from '@workbasehq/core/schema/load'
|
|
43
|
+
|
|
44
|
+
const { config, sources } = await loadConfig('./config.ts')
|
|
45
|
+
console.log(config.entities.worker.fields.name.type) // text
|
|
46
|
+
console.log(sources['entities.worker.fields.name']) // { file, line, column }
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
The new entry requires an explicit, nonempty list of unique roles and an owner
|
|
50
|
+
role from that list. SDK permission-provider configuration must agree with those
|
|
51
|
+
values. It adds no implicit `owner` or `member`, and supplies no implicit
|
|
52
|
+
organization grants. Existing permissions/policies may be supplied in their core
|
|
53
|
+
form for schema-only tooling. Executing a canonical configuration requires
|
|
54
|
+
the explicit access declaration described below.
|
|
55
|
+
|
|
56
|
+
`languages` is a nonempty ordered list of unique language tags; its first item is
|
|
57
|
+
the Instance default. The loader validates and retains that order. This entry
|
|
58
|
+
adds no translation runtime. Entity, field and enum labels belong in
|
|
59
|
+
`locales/<language>/domain.json` dictionaries; inline labels are rejected.
|
|
60
|
+
|
|
61
|
+
Each entity map entry must explicitly import a default or named `defineEntity`
|
|
62
|
+
export from its matching `./schema/<entity>.ts` file. The config default export
|
|
63
|
+
is a direct `defineConfig({...})` call. Named SDK imports may use local aliases.
|
|
64
|
+
The loader reads exactly `schema/<entity>.ts` and rejects competing candidates
|
|
65
|
+
(other extensions, extensionless files, directories, case variants). Use explicit
|
|
66
|
+
`.ts` specifiers. Only direct SDK/entity imports and the declaration export are
|
|
67
|
+
accepted; side-effect imports, helper wrappers, extra exports and top-level code
|
|
68
|
+
are rejected. Files with syntax errors are rejected. Config options are literal
|
|
69
|
+
data, except for imported entity identifiers. The returned config is the branded
|
|
70
|
+
`defineConfig` result of that literal data, equal to the module's default export.
|
|
71
|
+
|
|
72
|
+
Scope: the loader validates the declaration *shape* that agents and authors write.
|
|
73
|
+
It is not a sandbox against the consumer repository's own toolchain configuration.
|
|
74
|
+
Module redirection configured by the repository itself (tsconfig `paths`, package
|
|
75
|
+
`imports`/self-reference aliases, symlinked SDK copies, `verbatimModuleSyntax`
|
|
76
|
+
keeping type-only imports) is trusted, as is everything else in that repository.
|
|
77
|
+
The entity argument is an object literal with object/array/scalar literals inside
|
|
78
|
+
it. Spreads, identifier values, shorthand properties, methods, accessors, computed
|
|
79
|
+
keys, duplicate properties and arbitrary calls are rejected, including inside
|
|
80
|
+
nested arrays or objects. Type assertions and `satisfies` around literals are
|
|
81
|
+
allowed. The one permitted call is imported SDK `accountLink()` at `fields.user`,
|
|
82
|
+
without arguments. Expressions use the core serialized expression format as
|
|
83
|
+
literal data, rather than executable query-builder calls inside the declaration.
|
|
84
|
+
|
|
85
|
+
`accountLink()` normalizes to the existing optional protected `user` ref to
|
|
86
|
+
`users`, with `userLink: true`, `readOnly: true` and the to-one `user_account`
|
|
87
|
+
relation. Generic create/update validators cannot write or clear it. The SDK adds
|
|
88
|
+
the minimal `users` account projection (`name`, `role`) and `account.entity` to
|
|
89
|
+
the normalized config. An Instance cannot declare `users` or replace account
|
|
90
|
+
ownership. This declaration change does not move or apply any table DDL.
|
|
91
|
+
|
|
92
|
+
The returned config is the existing kernel schema. Core `string`, `text`, `int`,
|
|
93
|
+
`float`, `bool`, `datetime`, `enum` and `ref` types, computed fields, display
|
|
94
|
+
expressions and public metadata all use that schema. `number` and `boolean` are
|
|
95
|
+
not schema field type aliases. Domain declarations have no plugin migrations or
|
|
96
|
+
`checkSchema`; SDK plugin contract checks and migrations remain available.
|
|
97
|
+
|
|
98
|
+
Source map keys use config paths, for example `entities.worker.fields.user`.
|
|
99
|
+
Locations use absolute filenames and one-based lines/columns. Invalid literals
|
|
100
|
+
and declaration values throw `SourceError` formatted as `file:line:column`.
|
|
101
|
+
Runtime declarations validate values on their own; source syntax checking requires
|
|
102
|
+
`loadConfig`, which should run before a build executes the config normally.
|
|
103
|
+
|
|
104
|
+
The existing `defineInstance` entry retains inline/shorthand declarations and its
|
|
105
|
+
legacy role/default-grant normalization. Import those modules through the legacy
|
|
106
|
+
entry; `loadConfig` accepts only canonical `defineConfig` modules. Schema and access locks are checked by their SDK CLIs.
|
|
107
|
+
|
|
108
|
+
## Authored access (option C)
|
|
109
|
+
|
|
110
|
+
Declare domain access inside `defineEntity`, next to its fields and relations.
|
|
111
|
+
This keeps schema and policy edits together and reuses the same literal validator
|
|
112
|
+
and source map. Import a direct `defineAccess({...})` export from `./access.ts`
|
|
113
|
+
as the config's `access` property. This shared declaration has three required maps:
|
|
114
|
+
|
|
115
|
+
- `roles`: every configured role, each with `system`, an explicit action-to-decision
|
|
116
|
+
map. `accessSystemActions` exported from `@workbasehq/core/schema` lists its keys.
|
|
117
|
+
- `entities`: every SDK/system entity in the exported `accessEntities` list,
|
|
118
|
+
including `users`. Each value is a complete role matrix, as for domain access.
|
|
119
|
+
- `predicates`: named literal query filters, referenced using `{ use: 'name' }`.
|
|
120
|
+
|
|
121
|
+
The exports enumerate required keys for authoring/check tools. Source declarations
|
|
122
|
+
must spell out their entries: generated maps, spreads and helper calls are outside
|
|
123
|
+
the literal boundary. `access.ts` uses the same unambiguous direct-file resolution
|
|
124
|
+
as entity modules, including rejecting competing extensions and extra code.
|
|
125
|
+
|
|
126
|
+
An entity's access entry for each role is either `deny`, `none`, or an object
|
|
127
|
+
with all four operations: `read`, `create`, `update`, `delete`. List uses `read`.
|
|
128
|
+
Every operation is `allow`, `none`, `deny`, or `{ where: <filter> }`. Read also
|
|
129
|
+
accepts `fields`, an explicit projection mask (id is retained for nonempty masks).
|
|
130
|
+
An omitted mask grants nonsensitive schema fields; sensitive fields require an
|
|
131
|
+
explicit mask. No role name grants sensitive fields automatically. SDK entities
|
|
132
|
+
without a schema projection accept decisions only, enforced at resource ports;
|
|
133
|
+
row predicates and masks require a schema projection such as `users`.
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
// Inside schema/worker.ts's defineEntity literal:
|
|
137
|
+
access: {
|
|
138
|
+
admin: { read: 'allow', create: 'allow', update: 'allow', delete: 'allow' },
|
|
139
|
+
staff: {
|
|
140
|
+
read: { where: { use: 'linked_worker' }, fields: ['id', 'name'] },
|
|
141
|
+
create: 'deny', update: 'deny', delete: 'deny',
|
|
142
|
+
},
|
|
143
|
+
}
|
|
144
|
+
// Inside access.ts's predicates map:
|
|
145
|
+
linked_worker: { user: { eq: '$actor.id' } }
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
These synthetic roles illustrate the mechanism; they do not select a product
|
|
149
|
+
policy. Missing role/entity/operation/action entries are errors. `none` contributes
|
|
150
|
+
no grant; held roles contribute a union of grants and field masks, with any
|
|
151
|
+
explicit `deny` winning for that operation. Unknown roles fail closed. Credential
|
|
152
|
+
operation allowlists are independently enforced. Writes never grant read access,
|
|
153
|
+
and create/update/delete predicates are checked independently of the read filter.
|
|
154
|
+
Existing organization scoping and protected account-link writes still apply.
|
|
155
|
+
|
|
156
|
+
System actions require both an authored action grant and the corresponding entity
|
|
157
|
+
operation grant: for example `members.read` also requires `memberships.read`, and
|
|
158
|
+
`invitations.revoke` requires `invitations.delete`. `tokens` maps to `access_tokens`,
|
|
159
|
+
`audit` to `audit_events`, and `workflows` to `workflow_runs`. Default privileges
|
|
160
|
+
and built-in role names cannot bypass either denial. Compatibility permission
|
|
161
|
+
maps and SQL issuer guards are derived from these same decisions. Authored access
|
|
162
|
+
cannot be mixed with legacy `permissions`, `policies` or `organizationPermissions`.
|
|
163
|
+
|
|
164
|
+
Named predicates expand at build time with a maximum depth of 16 and 512 visited
|
|
165
|
+
values per expansion. Unused predicates are also checked. Named cycles and
|
|
166
|
+
operation-specific relation-policy cycles fail with their cycle path. Invalid
|
|
167
|
+
filters, references, masks and expansion budgets map back to file:line diagnostics.
|
|
168
|
+
|
|
169
|
+
`config.effectiveAccess` is the exported `EffectiveAccessPolicy`, available from
|
|
170
|
+
`@workbasehq/core/schema`. It contains canonically ordered entity/role/operation
|
|
171
|
+
rules with expanded filters, masks, named references, relation dependencies,
|
|
172
|
+
explicit decisions and system actions with their required entity/operation targets.
|
|
173
|
+
Masks are null for mutations and SDK resources without a schema projection. Its `source` fields are stable source-map
|
|
174
|
+
keys; the loader's `sources` supplies exact locations without making policy equality
|
|
175
|
+
depend on declaration order or machine paths. Execution consumes this representation;
|
|
176
|
+
slice 2b will serialize it to access locks. There is no second audit policy compiler.
|
|
177
|
+
The same type includes registered command permissions/additional permissions, opaque
|
|
178
|
+
command markers, and opaque plugin-hook names. The kernel resolves code-registered
|
|
179
|
+
commands during composition; serialize `kernel.config.effectiveAccess` for the
|
|
180
|
+
complete registry. Unresolved command names have null permissions and cannot run.
|
|
181
|
+
Executable prepare/plan and custom plugin checks remain enforced and marked opaque.
|
|
182
|
+
|
|
183
|
+
`loadConfig` also returns `configHash`, a SHA-256 of the config, imported entity
|
|
184
|
+
and shared access source paths/bytes. Policy-only edits change this hash without
|
|
185
|
+
altering `config.revision` or physical schema SQL. The loader binds `config.revision` from `schema.lock.json` (r1 before initialization);
|
|
186
|
+
`defineConfig` rejects an authored revision. Slice-1 declarations without access remain readable
|
|
187
|
+
by schema tools; the kernel refuses to execute them with legacy defaults.
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
## Physical schema lock and migration bundles
|
|
191
|
+
|
|
192
|
+
Run `bun run migrate:plan --init` with no lock or domain SQL to initialize r1.
|
|
193
|
+
With `--base <ref> --init`, the ref must also have no lock or domain migrations.
|
|
194
|
+
Subsequent plans require `--base <ref>` and compare against that ref's tip.
|
|
195
|
+
The adapter only reads local Git objects; fetch the desired ref before planning.
|
|
196
|
+
SDK/plugin DDL stays in SDK ledgers.
|
|
197
|
+
|
|
198
|
+
A schema change writes one `NNNN_rN.sql` bundle and a lock whose parent is the
|
|
199
|
+
SHA-256 of the exact base lock bytes. Repeated plans preserve the same bytes.
|
|
200
|
+
Base migration files must remain unchanged. `check:schema --base <ref>` validates
|
|
201
|
+
that linkage, the generated SQL, the config against the lock, and manual evidence.
|
|
202
|
+
Without a base, `check:schema` checks config and bundle evidence only.
|
|
203
|
+
The root invariant check supplies `origin/main` (or `origin/$GITHUB_BASE_REF`);
|
|
204
|
+
pass `--base <ref>` to override it for a stacked branch.
|
|
205
|
+
|
|
206
|
+
Bundles contain exactly one header followed by pre-data, generated, and post-data
|
|
207
|
+
regions in that order. Regeneration preserves manual region bytes, including line
|
|
208
|
+
endings. Changed generated SQL or a moved parent requires renewed manual review:
|
|
209
|
+
run `migrate:plan --base <ref> --confirm-manual` to record evidence in the header.
|
|
210
|
+
Evidence hashes decimal UTF-8 byte-length-prefixed bodies (`length:body`) in
|
|
211
|
+
pre/generated/post order. Editing a confirmed manual region invalidates evidence.
|
|
212
|
+
The migration ledger still hashes the entire file.
|
|
213
|
+
|
|
214
|
+
Regenerating against a moved base renumbers the pending bundle and rewrites its
|
|
215
|
+
parent. If its filename collides with a newly merged migration, the base file is
|
|
216
|
+
restored and the pending bundle moves to the next revision. An empty schema diff
|
|
217
|
+
removes a pending bundle only when both manual regions are empty.
|
|
218
|
+
|
|
219
|
+
Both commands accept `--config`, `--root`, `--directory` and `--migrations`.
|
|
220
|
+
Installed consumers invoke `@workbasehq/core/migrations/schema-cli` with `plan` or
|
|
221
|
+
`check`; repository scripts only supply paths and the CI base.
|
|
222
|
+
Runtime builds bind the lock with `bindSchemaLock`; direct `defineConfig`
|
|
223
|
+
declarations remain unbound until a lock is supplied.
|
|
224
|
+
|
|
225
|
+
New locks use `lockVersion: 2`. The lock retains SQL-only `tables` and adds
|
|
226
|
+
`entities[]` with immutable `ent_…` IDs, `logicalName`, `physicalName`, and
|
|
227
|
+
`fields[]` with immutable `fld_…` IDs and the same name pair. These are storage
|
|
228
|
+
identities: SDK-owned accounts and computed fields have no domain storage entry;
|
|
229
|
+
implicit domain columns do. IDs are deterministically seeded from the initial
|
|
230
|
+
physical path, then preserved across explicit rename intents.
|
|
231
|
+
|
|
232
|
+
`parseLock` and `bindSchemaLock` validate v2 and bootstrap repository v1 locks
|
|
233
|
+
deterministically. A plan with no schema diff can write exactly that v2 bootstrap
|
|
234
|
+
without a migration or revision change. Its original parent, physical names and
|
|
235
|
+
all existing migration bytes remain unchanged. Old SDKs reject v2: upgrade the
|
|
236
|
+
SDK before consuming a v2 lock.
|
|
237
|
+
|
|
238
|
+
Both rename inputs use `renameFrom`: a field option, or a top-level entity option
|
|
239
|
+
such as `defineEntity({ renameFrom: 'worker', fields: { … } })` in
|
|
240
|
+
`schema/staff.ts`. Sources must exist in the base lock and disappear from the
|
|
241
|
+
authored schema; names/IDs cannot collide or be claimed twice. Similar shapes
|
|
242
|
+
never imply a rename. A rename must preserve the SQL definition and be isolated
|
|
243
|
+
from other schema edits. Computed/implicit/account renames and backfill intents
|
|
244
|
+
remain unsupported.
|
|
245
|
+
|
|
246
|
+
Each rename appends to `transitions[]`: `id`, `entityId`, optional `fieldIds`
|
|
247
|
+
(one field in this slice), `from`/`to` (`logical`, `physical`), `bridge`
|
|
248
|
+
(`field` = dual column, `entity` = view), and `phase`
|
|
249
|
+
(`expanded | switched | contracted`). History is retained. At most one
|
|
250
|
+
non-contracted transition may exist per entity, including field transitions.
|
|
251
|
+
An expanded candidate retains the source mapping and records the target as
|
|
252
|
+
intent; logical switching belongs to a later release. This slice only builds
|
|
253
|
+
pure candidate records: SQL planning rejects open transitions by ID before any
|
|
254
|
+
lock/bundle writes. It cannot apply expansion, advance phases or contract.
|
|
255
|
+
|
|
256
|
+
`createPhysicalNameResolver(lock)` is exported from `@workbasehq/core/schema`
|
|
257
|
+
and `@workbasehq/core/schema/physical-names`. It validates and snapshots the lock;
|
|
258
|
+
`entityId(logicalName)` and `fieldId(entityId, logicalName)` locate identities,
|
|
259
|
+
while `table(entityId)` and `column(entityId, fieldId)` return pinned physical
|
|
260
|
+
names. Unknown IDs/names and fields belonging to another entity fail. Runtime
|
|
261
|
+
CRUD, query and policy compilers will adopt the resolver in the next slice.
|
|
262
|
+
|
|
263
|
+
Record actions are strict entity data pointing at registered commands:
|
|
264
|
+
|
|
265
|
+
```ts
|
|
266
|
+
actions: {
|
|
267
|
+
close: {
|
|
268
|
+
command: 'record/close',
|
|
269
|
+
available: [{ when: { state: { eq: 'open' } }, reason: 'record.closed' }],
|
|
270
|
+
},
|
|
271
|
+
}
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
`when` uses access predicates, including `{ use: 'name' }`. Compilation rejects
|
|
275
|
+
unregistered, unallowlisted and system-permission commands. Expanded conditions,
|
|
276
|
+
field dependencies and declaration sources live in `effectiveAccess.actions` and
|
|
277
|
+
both access locks; command bodies remain opaque guards. `actionReasonKeys(config)`
|
|
278
|
+
from `@workbasehq/core/schema` exposes the finite authored reason keys.
|
|
279
|
+
|
|
280
|
+
SDK-era detail GETs include an `actions` map, independent of projection. Forbidden
|
|
281
|
+
or masked-dependency actions are omitted. SQL evaluates availability and selects
|
|
282
|
+
the first failing reason. List, query and generic mutation responses omit the map.
|
|
283
|
+
The SDK era marker is `baseline: 'workbase-sdk'`; domain fields and relations named
|
|
284
|
+
`actions` and `access` are reserved in that era, including declarations without compiled access.
|
|
285
|
+
Legacy configurations retain their existing response and naming contracts.
|
|
286
|
+
|
|
287
|
+
`POST /api/:entity/:id/actions/:name` accepts `{}` for input-less commands.
|
|
288
|
+
Object-shaped command schemas declare other accepted body keys; body `id`,
|
|
289
|
+
`rowId` and `role` are rejected. Values/defaults/transforms run once through the
|
|
290
|
+
command schema, with the path supplying `id`. Role permission runs before record access; the first rule of
|
|
291
|
+
one atomic batch rechecks read/write predicates and conditions with `expectRows: 1`.
|
|
292
|
+
A hidden/unknown/masked action returns GET's `404 not_found` body. A readable,
|
|
293
|
+
unavailable action returns `409 {error: 'action_unavailable', reason}`. Diagnosis
|
|
294
|
+
is read-only after rollback. `client.act(entity, id, name, signal)` caches a returned
|
|
295
|
+
detail row or refetches detail; failures expose `ApiFailure.reason`.
|
|
296
|
+
|
|
297
|
+
Account links opt in with `defineAccess({ accountLinks: { worker: {
|
|
298
|
+
invitationRole: 'staff' } }, ... })`. The role must exist, differ from the owner,
|
|
299
|
+
and have read access to the linked entity. Legacy instances retain `member`.
|
|
300
|
+
The mapping registers `invite`, `cancel_invite`, `link_account` and
|
|
301
|
+
`unlink_account`; their core SQL conditions are recorded as `opaque: true` in
|
|
302
|
+
lock version 1. These adapter commands are reachable through the record
|
|
303
|
+
dispatcher. The existing legacy `link_account`/`remove_access` commands keep their
|
|
304
|
+
original `rowId`/`userId` inputs and behavior.
|
|
305
|
+
|
|
306
|
+
For mapped links, detail includes `access` only with `invitations.read`:
|
|
307
|
+
`{state, account, invitation}`, with states `no_account`, `invited`, `expired`,
|
|
308
|
+
`linked`. Account is `{id, display_name, email}`; invitation is
|
|
309
|
+
`{id, email, expires_at}`. Linked state has no invitation. Staff read scope and
|
|
310
|
+
mutation grants remain authored instance policy; the fixture grants self-read.
|
|
311
|
+
|
|
312
|
+
The invite body is strictly `{email}`, link is `{user_id}`, cancel and unlink
|
|
313
|
+
are `{}`. Body selectors and roles are rejected; the route owns the record id. Invitation
|
|
314
|
+
credentials/selectors in a card body receive the same `404 not_found` regardless
|
|
315
|
+
of their existence; they can never select another invitation.
|
|
316
|
+
Invite returns `{invitation_id, expires_at, accept_url}` with `Cache-Control:
|
|
317
|
+
no-store`; the credential is absent from detail, audit and locks. It queues one
|
|
318
|
+
outbox intent in the same D1 batch. Expired history is superseded by migration
|
|
319
|
+
004's trigger before its partial unique index is checked. Delivery is separate.
|
|
320
|
+
Unlink clears links and pending account invitations, retaining membership and
|
|
321
|
+
independently granted access. `client.actWith(entity, id, name, body, signal)`
|
|
322
|
+
returns `{record, result}` after the same cache refresh as `act()`; credentials
|
|
323
|
+
stay in the result and are never cached as record data.
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export type DeclarationPath = (string | number)[]
|
|
2
|
+
/** Paths are mapped to source positions by the build-time loader. */
|
|
3
|
+
export class DeclarationError extends Error {
|
|
4
|
+
constructor(readonly path: DeclarationPath, message: string) { super(message); this.name = 'DeclarationError' }
|
|
5
|
+
}
|