@workbasehq/core 0.2.14 → 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.
Files changed (99) hide show
  1. package/package.json +18 -3
  2. package/src/access-evaluator.ts +72 -0
  3. package/src/access-guards.ts +35 -0
  4. package/src/access-inputs.ts +62 -0
  5. package/src/access-lock/cli.ts +34 -0
  6. package/src/access-lock.ts +183 -0
  7. package/src/access.ts +209 -0
  8. package/src/account-action-conditions.ts +27 -0
  9. package/src/account-command.ts +8 -0
  10. package/src/admin-ui.tsx +3 -2
  11. package/src/app.ts +3 -3
  12. package/src/canonical.ts +6 -0
  13. package/src/capabilities.ts +5 -3
  14. package/src/commands.ts +14 -8
  15. package/src/config.ts +105 -69
  16. package/src/console-build.ts +37 -0
  17. package/src/console-contract.ts +4 -0
  18. package/src/console-model.ts +2 -0
  19. package/src/console-presentation.ts +1 -1
  20. package/src/console.ts +3 -3
  21. package/src/crud.ts +13 -7
  22. package/src/dev-mailbox.ts +35 -0
  23. package/src/display-identity.ts +12 -0
  24. package/src/execution/atomic.ts +17 -3
  25. package/src/execution/policies.ts +14 -6
  26. package/src/execution/policy-receipts.ts +6 -5
  27. package/src/execution/post-commit.ts +11 -0
  28. package/src/execution/types.ts +1 -1
  29. package/src/index.ts +2 -0
  30. package/src/infra/README.md +39 -3
  31. package/src/infra/d1-migrations.ts +4 -3
  32. package/src/infra/instance-migrations.ts +26 -5
  33. package/src/infra/provision-config-main.mjs +3 -3
  34. package/src/infra/provision-diagnostics.ts +4 -0
  35. package/src/infra/provision-plan.ts +34 -5
  36. package/src/infra/provision.ts +26 -4
  37. package/src/infra/schema.ts +1 -1
  38. package/src/kernel/invitation-mail-port.ts +26 -0
  39. package/src/kernel/mail-outbox-port.ts +4 -2
  40. package/src/kernel/migrations.ts +38 -15
  41. package/src/kernel/plugin.ts +2 -0
  42. package/src/kernel/predicate.ts +15 -3
  43. package/src/kernel/registry.ts +69 -12
  44. package/src/member-bootstrap.ts +65 -0
  45. package/src/member-identities.ts +42 -0
  46. package/src/migrations/diagnostics.ts +6 -1
  47. package/src/migrations/model-b.ts +2 -1
  48. package/src/migrations/operational-evidence.ts +51 -0
  49. package/src/migrations/planner.ts +12 -1
  50. package/src/migrations/rebuild.ts +17 -12
  51. package/src/migrations/reset-era.ts +29 -0
  52. package/src/migrations/schema-bundle.ts +43 -0
  53. package/src/migrations/schema-cli.ts +74 -0
  54. package/src/migrations/schema-git.ts +36 -0
  55. package/src/migrations/schema-lock.ts +159 -0
  56. package/src/migrations/schema-plan.ts +94 -0
  57. package/src/migrations/schema.ts +73 -48
  58. package/src/migrations/sdk-baseline.ts +35 -0
  59. package/src/migrations/system-schema.ts +39 -0
  60. package/src/model-inputs.ts +25 -0
  61. package/src/openapi/cli.ts +72 -0
  62. package/src/openapi/generate.ts +166 -0
  63. package/src/openapi/input-projection.ts +131 -0
  64. package/src/openapi/public-paths.ts +80 -0
  65. package/src/openapi/routes.ts +29 -0
  66. package/src/ops.ts +4 -2
  67. package/src/organization-name.ts +35 -0
  68. package/src/organization-permissions.ts +10 -0
  69. package/src/organizations.ts +72 -3
  70. package/src/policies.ts +22 -6
  71. package/src/public-projection.ts +108 -0
  72. package/src/public-schema.ts +5 -43
  73. package/src/query/compiler.ts +13 -0
  74. package/src/query/input-schema.ts +89 -0
  75. package/src/query/limits.ts +1 -1
  76. package/src/query/schema.ts +20 -88
  77. package/src/record-action-routes.ts +87 -0
  78. package/src/record-actions-data.ts +17 -0
  79. package/src/record-actions.ts +61 -0
  80. package/src/record-read.ts +20 -0
  81. package/src/row-access.ts +11 -0
  82. package/src/row-invitations.ts +29 -0
  83. package/src/schema/README.md +323 -0
  84. package/src/schema/declaration.ts +5 -0
  85. package/src/schema/load.ts +423 -0
  86. package/src/schema/lock-format.ts +117 -0
  87. package/src/schema/physical-names.ts +30 -0
  88. package/src/schema/revision.ts +16 -0
  89. package/src/schema/source-location.ts +3 -0
  90. package/src/schema-compatibility.ts +2 -2
  91. package/src/schema.ts +171 -0
  92. package/src/types.ts +1 -1
  93. package/src/user-link-eligibility.ts +36 -0
  94. package/src/user-link-fields.ts +7 -0
  95. package/src/user-links.ts +30 -20
  96. package/src/worker-access-actions.ts +89 -0
  97. package/src/worker-access.ts +61 -0
  98. package/src/workflow-runtime.ts +109 -22
  99. package/src/bootstrap.ts +0 -23
@@ -1,5 +1,6 @@
1
- import { z } from 'zod'
2
- import { baseFields, type Field, type InstanceConfig } from '../config'
1
+ import { organizationPermission } from '../organization-permissions'
2
+ import { userLinks } from '../user-link-fields'
3
+ import { baseFields } from '../model-inputs'
3
4
  import type { KernelRegistry } from '../kernel/registry'
4
5
  import type { Scope } from '../types'
5
6
  import { invalid, QueryError, type QueryPath } from './errors'
@@ -8,92 +9,14 @@ import { isRestQuery } from './facade'
8
9
  import { labelPath } from './labels'
9
10
  import { expressionInfo, fieldExpression, readableComputed } from './expressions'
10
11
 
11
- export type Scalar = string | number | boolean | null
12
- export interface Filter { [key: string]: unknown }
13
- export interface Order { field: string; dir: 'asc' | 'desc'; label?: boolean }
14
- export interface Selection { labels?: string[]; select?: string[]; where?: Filter; orderBy?: Order[]; limit?: number; include?: Record<string, Selection> }
15
- export interface QueryInput extends Selection { contextList?: { entity: string; list: string; id: string }; search?: { text: string; fields: string[]; locale?: 'en' | 'cs' }; labelWhere?: Record<string, { contains: string; locale?: 'en' | 'cs' }>; entity: string; limit: number; cursor?: string }
16
- export const fieldsFor = (config: InstanceConfig, entity: string) => [...baseFields, ...Object.keys(config.entities[entity].fields)]
17
- export function fieldType(config: InstanceConfig, entity: string, field: string): Field['type'] {
18
- return config.entities[entity].fields[field]?.type ?? (field === 'version' ? 'int' : ['created_at', 'updated_at'].includes(field) ? 'datetime' : 'string')
19
- }
20
- export function operatorsFor(type: Field['type']) {
21
- return ['eq', 'ne', 'in', ...(['bool'].includes(type) ? [] : ['lt', 'lte', 'gt', 'gte']),
22
- ...(['string', 'text'].includes(type) ? ['contains'] : []), 'isNull']
23
- }
24
- function valueSchema(config: InstanceConfig, entity: string, field: string, rest: boolean) {
25
- const type = fieldType(config, entity, field)
26
- // crud.ts accepted all finite numeric operands (also for int fields), and did
27
- // not impose the write validator's string lengths on URL filter operands.
28
- if (rest) return type === 'bool' ? z.boolean() : ['int', 'float'].includes(type) ? z.number().finite() : z.string()
29
- return type === 'bool' ? z.boolean() : type === 'int' ? z.number().int().safe()
30
- : type === 'float' ? z.number().finite() : z.string().max(2_000)
31
- }
32
- /** Shared client/policy grammar; only trusted configuration enables actor predicates. */
33
- export function filterSchema(config: InstanceConfig, rest = false, maxDepth = L.relationDepth as number,
34
- actorValues?: (type: Field['type']) => z.ZodType) {
35
- const filters = new Map<string, z.ZodType>()
36
- function filter(name: string, depth: number): z.ZodType {
37
- const key = `${name}:${depth}`
38
- const cached = filters.get(key); if (cached) return cached
39
- const schema: z.ZodType = z.lazy(() => {
40
- const shape: Record<string, z.ZodType> = Object.create(null)
41
- for (const field of fieldsFor(config, name)) {
42
- const scalar = (valueSchema(config, name, field, rest) as z.ZodType).refine((value: unknown) => !actorValues || typeof value !== 'string' || !value.startsWith('$actor.'), 'Actor values require a declared compatible field'); const value = actorValues ? z.union([scalar, actorValues(fieldType(config, name, field))]) : scalar; const ops: Record<string, z.ZodType> = Object.create(null)
43
- for (const op of rest ? ['eq', 'lt', 'lte', 'gt', 'gte'] : operatorsFor(fieldType(config, name, field))) ops[op] =
44
- (op === 'isNull' ? (actorValues ? z.union([z.boolean(), actorValues('bool')]) : z.boolean()) : op === 'in' ? z.array(value.nullable()).max(L.bindings)
45
- : op === 'eq' || op === 'ne' ? value.nullable() : value).optional()
46
- shape[field] = z.strictObject(ops).refine(v => Object.keys(v).length > 0).optional()
47
- }
48
- if (depth < maxDepth) for (const [relation, r] of Object.entries(config.entities[name].relations)) {
49
- const child = filter(r.entity, depth + 1)
50
- shape[relation] = (r.many ? z.union([z.strictObject({ some: child }), z.strictObject({ none: child })]) : child).optional()
51
- }
52
- if (actorValues) shape.actorLinkedIn = z.string().refine(entity =>
53
- Object.hasOwn(config.entities, entity) && Object.values(config.entities[entity].fields).some(field => field.userLink),
54
- 'actorLinkedIn requires an entity with a protected user link').optional()
55
- shape.and = z.array(schema).min(1).max(L.nodes).optional()
56
- shape.or = z.array(schema).min(1).max(L.nodes).optional()
57
- shape.not = schema.optional()
58
- return z.strictObject(shape)
59
- })
60
- filters.set(key, schema); return schema
61
- }
62
- return filter
63
- }
64
- /** Generated from the complete model. No library AST/raw/functions are client input. */
65
- export function querySchema(config: InstanceConfig, entity: string, rest = false) {
66
- const filter = filterSchema(config, rest)
67
- function selection(name: string, depth: number, root: boolean): z.ZodType {
68
- const names = fieldsFor(config, name) as [string, ...string[]]
69
- const labelNames = [...names.filter(key => labelPath(config, name, key)), ...Object.keys(config.ui?.entities?.[name]?.list?.relatedColumns ?? {})] as [string, ...string[]]
70
- const shape: Record<string, z.ZodType> = {
71
- select: z.array(z.enum(names)).min(1).max(names.length).refine(v => new Set(v).size === v.length).optional(),
72
- where: filter(name, depth).optional(),
73
- orderBy: z.array(z.strictObject({ field: z.enum(root ? [...new Set([...names, ...labelNames])] as [string, ...string[]] : names), dir: z.enum(['asc', 'desc']), ...(root ? { label: z.boolean().optional() } : {}) })).max(5)
74
- .refine(v => new Set(v.map(o => o.field)).size === v.length).optional(),
75
- limit: root ? z.number().int().min(1).max(L.root) : z.number().int().min(1).max(L.children).optional(),
76
- }
77
- if (depth < L.relationDepth) shape.include = z.strictObject(Object.fromEntries(Object.entries(config.entities[name].relations)
78
- .map(([key, r]) => [key, z.lazy(() => selection(r.entity, depth + 1, false)).optional()]))).optional()
79
- if (root) {
80
- if (labelNames.length) {
81
- shape.labelWhere = z.partialRecord(z.enum(labelNames), z.strictObject({ contains: z.string().min(1).max(2000), locale: z.enum(['en', 'cs']).optional() })).optional()
82
- shape.labels = z.array(z.enum(labelNames)).max(L.relations).refine(v => new Set(v).size === v.length).optional()
83
- }
84
- shape.search = z.strictObject({ text: z.string().min(1).max(2000), fields: z.array(z.enum([...new Set([...names, ...labelNames])] as [string, ...string[]])).min(1).max(names.length + labelNames.length).refine(v => new Set(v).size === v.length), locale: z.enum(['en', 'cs']).optional() }).optional()
85
- shape.contextList = z.strictObject({ entity: z.string().regex(/^[a-z][a-z0-9_]*$/).max(100), list: z.string().regex(/^[a-z][a-z0-9_]*$/).max(100), id: z.string().min(1).max(2000) }).optional()
86
- shape.entity = z.literal(name); shape.cursor = z.string().min(1).max(L.cursorBytes).optional()
87
- }
88
- return z.strictObject(shape)
89
- }
90
- return selection(entity, 0, true)
91
- }
12
+ export { fieldsFor, fieldType, operatorsFor, filterSchema, querySchema } from './input-schema'
13
+ export type { Scalar, Filter, Order, Selection, RowAccessState, QueryInput } from './input-schema'
14
+ import { fieldsFor, operatorsFor, querySchema, type Filter, type Selection, type QueryInput } from './input-schema'
92
15
  /** Bound recursion before Zod, including malformed/unrecognized inputs. */
93
16
  function preflight(input: unknown) {
94
17
  let nodes = 0
95
18
  function visit(value: unknown, depth: number) {
96
- if (++nodes > L.nodes || depth > L.filterDepth * 3) throw new QueryError('query_too_expensive', [], { depth, nodes, relations: 0, exists: 0, fieldRows: 0 })
19
+ if (++nodes > L.nodes || depth > L.filterDepth * 3) throw new QueryError('query_too_expensive', [], { depth, nodes, statements: 0, relations: 0, exists: 0, fieldRows: 0 })
97
20
  if (value && typeof value === 'object') {
98
21
  if (!Array.isArray(value) && ![Object.prototype, null].includes(Object.getPrototypeOf(value))) invalid()
99
22
  for (const [key, child] of Object.entries(value)) {
@@ -109,7 +32,7 @@ export function validateQuery(kernel: KernelRegistry, scope: Scope, input: unkno
109
32
  if (!input || typeof input !== 'object' || Array.isArray(input)) invalid()
110
33
  const entity = (input as QueryInput).entity
111
34
  if (typeof entity !== 'string' || !Object.hasOwn(kernel.config.entities, entity)) throw new QueryError('entity_not_found', ['entity'])
112
- const depthCost: QueryCost = { depth: 0, relations: 0, fieldRows: 0, exists: 0, nodes: 0 }
35
+ const depthCost: QueryCost = { statements: 0, depth: 0, relations: 0, fieldRows: 0, exists: 0, nodes: 0 }
113
36
  function relationDepth(name: string, node: unknown, depth: number, path: QueryPath) {
114
37
  depthCost.nodes++; depthCost.depth = Math.max(depthCost.depth, depth)
115
38
  if (depth > L.relationDepth) throw new QueryError('query_too_expensive', path, depthCost)
@@ -129,12 +52,18 @@ export function validateQuery(kernel: KernelRegistry, scope: Scope, input: unkno
129
52
  if (!parsed.success) {
130
53
  const issue = parsed.error.issues[0]
131
54
  // Unknown client keys/values never become error text or paths.
132
- const known = new Set(['entity', 'select', 'where', 'search', 'text', 'fields', 'locale', 'labelWhere', 'labels', 'label', 'orderBy', 'field', 'dir', 'limit', 'cursor', 'include', 'and', 'or', 'not', 'some', 'none',
55
+ const known = new Set(['entity', 'rowAccess', 'select', 'where', 'search', 'text', 'fields', 'locale', 'labelWhere', 'labels', 'label', 'orderBy', 'field', 'dir', 'limit', 'cursor', 'include', 'and', 'or', 'not', 'some', 'none',
133
56
  ...Object.values(kernel.config.entities).flatMap(e => [...Object.keys(e.fields), ...Object.keys(e.relations)]), ...baseFields,
134
57
  ...operatorsFor('string')])
135
58
  invalid(issue.path.map(p => typeof p === 'number' ? p : known.has(String(p)) ? String(p) : '?'))
136
59
  }
137
60
  const query = parsed.data as QueryInput
61
+ if (query.rowAccess) {
62
+ if (!kernel.providers.has('members') || !userLinks(kernel.config).some(link => link.entity === entity)) invalid(['rowAccess'])
63
+ kernel.resourcePermission(scope, 'invitations.read')
64
+ organizationPermission(kernel.config, scope, 'invitations.read')
65
+ kernel.readPermission(scope, entity)
66
+ }
138
67
  if (query.contextList) {
139
68
  const context = query.contextList
140
69
  // Resolve from trusted configuration using the same plugin-over-model precedence as the registry.
@@ -149,7 +78,7 @@ export function validateQuery(kernel: KernelRegistry, scope: Scope, input: unkno
149
78
  // This predicate goes through normal field masks, policy-scoped sources and cursor hashing.
150
79
  delete query.contextList
151
80
  }
152
- const cost: QueryCost = { depth: 0, relations: 0, fieldRows: 0, exists: 0, nodes: 0 }
81
+ const cost: QueryCost = { statements: 0, depth: 0, relations: 0, fieldRows: 0, exists: query.rowAccess ? 2 : 0, nodes: 0 }
153
82
  // Every compiled client table source masks each readable FK once. Visibility
154
83
  // probes only test the target's scoped predicate, so do not recursively mask it.
155
84
  function foreignKeyCost(name: string) {
@@ -212,6 +141,9 @@ export function validateQuery(kernel: KernelRegistry, scope: Scope, input: unkno
212
141
  }
213
142
  }
214
143
  function selection(name: string, node: Selection, depth: number, parents: number, path: QueryPath, single = false) {
144
+ // One root plus one per include occurrence, even across repeated branches.
145
+ // Empty runtime parents may skip an include; SQL subqueries add no statements.
146
+ cost.statements++
215
147
  foreignKeyCost(name)
216
148
  permission(name, path); cost.depth = Math.max(cost.depth, depth)
217
149
  const limit = single ? 1 : node.limit ?? L.children
@@ -246,7 +178,7 @@ export function validateQuery(kernel: KernelRegistry, scope: Scope, input: unkno
246
178
  }
247
179
  }
248
180
  selection(entity, query, 0, 1, [])
249
- if (cost.depth > L.relationDepth || cost.relations > L.relations || cost.exists > L.exists || cost.fieldRows > L.fieldRows || cost.nodes > L.nodes)
181
+ if (cost.statements > L.statements || cost.depth > L.relationDepth || cost.relations > L.relations || cost.exists > L.exists || cost.fieldRows > L.fieldRows || cost.nodes > L.nodes)
250
182
  throw new QueryError('query_too_expensive', [], cost)
251
183
  return { query, cost }
252
184
  }
@@ -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
+ }