@workbasehq/core 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/package.json +62 -1
  4. package/src/account-provisioning.ts +24 -0
  5. package/src/admin-forms.tsx +70 -0
  6. package/src/admin-security.ts +63 -0
  7. package/src/admin-ui.tsx +438 -0
  8. package/src/app.ts +115 -0
  9. package/src/audit-event.ts +23 -0
  10. package/src/audit.ts +35 -0
  11. package/src/authorization-api.ts +3 -0
  12. package/src/authorization.ts +135 -0
  13. package/src/authorized-execution.ts +15 -0
  14. package/src/bootstrap.ts +23 -0
  15. package/src/browser-dispatch.ts +19 -0
  16. package/src/calendar-display.ts +26 -0
  17. package/src/capabilities.ts +41 -0
  18. package/src/commands.ts +46 -0
  19. package/src/config-proposal-contract.ts +16 -0
  20. package/src/config-proposals.ts +95 -0
  21. package/src/config-shorthand.ts +200 -0
  22. package/src/config.ts +286 -0
  23. package/src/console-contract.ts +105 -0
  24. package/src/console-contribution.ts +7 -0
  25. package/src/console.ts +84 -0
  26. package/src/crud.ts +146 -0
  27. package/src/crypto.ts +33 -0
  28. package/src/detail-display.ts +59 -0
  29. package/src/detail-layout.ts +17 -0
  30. package/src/errors.ts +3 -0
  31. package/src/event-delivery.ts +76 -0
  32. package/src/events.ts +11 -0
  33. package/src/execution/atomic.ts +70 -0
  34. package/src/execution/compiler.ts +55 -0
  35. package/src/execution/context.ts +100 -0
  36. package/src/execution/d1.ts +46 -0
  37. package/src/execution/errors.ts +21 -0
  38. package/src/execution/index.ts +6 -0
  39. package/src/execution/outbox.ts +8 -0
  40. package/src/execution/permissions.ts +9 -0
  41. package/src/execution/policies.ts +156 -0
  42. package/src/execution/policy-receipts.ts +51 -0
  43. package/src/execution/types.ts +74 -0
  44. package/src/execution/workflow.ts +35 -0
  45. package/src/form-display.ts +36 -0
  46. package/src/idempotency.ts +10 -0
  47. package/src/identity-providers.ts +2 -0
  48. package/src/identity-settings.ts +42 -0
  49. package/src/identity-writes.ts +14 -0
  50. package/src/identity.ts +2 -0
  51. package/src/index.ts +32 -0
  52. package/src/json-csrf.ts +22 -0
  53. package/src/kernel/adapters/tenancy.ts +8 -0
  54. package/src/kernel/audit-port.ts +12 -0
  55. package/src/kernel/builtin-source.ts +34 -0
  56. package/src/kernel/composition.ts +77 -0
  57. package/src/kernel/identity-port.ts +36 -0
  58. package/src/kernel/mail-outbox-port.ts +23 -0
  59. package/src/kernel/migrations.ts +76 -0
  60. package/src/kernel/operation-name.ts +8 -0
  61. package/src/kernel/plugin.ts +92 -0
  62. package/src/kernel/predicate.ts +69 -0
  63. package/src/kernel/registry.ts +198 -0
  64. package/src/kernel/schema-check.ts +13 -0
  65. package/src/logging.ts +21 -0
  66. package/src/migrations/better-auth-schema.ts +2 -0
  67. package/src/migrations/email-delivery-schema.ts +6 -0
  68. package/src/migrations/planner.ts +77 -0
  69. package/src/migrations/schema.ts +85 -0
  70. package/src/migrations/version-contract.ts +28 -0
  71. package/src/migrations/versions.ts +90 -0
  72. package/src/ops-schema.ts +13 -0
  73. package/src/ops.ts +34 -0
  74. package/src/organization-permissions.ts +13 -0
  75. package/src/organization-rules.ts +25 -0
  76. package/src/organizations.ts +43 -0
  77. package/src/plugins.ts +3 -0
  78. package/src/policies.ts +186 -0
  79. package/src/public-schema.ts +65 -0
  80. package/src/query/compiler.ts +395 -0
  81. package/src/query/cursor.ts +43 -0
  82. package/src/query/enum-labels.json +16 -0
  83. package/src/query/enum-values.ts +7 -0
  84. package/src/query/errors.ts +10 -0
  85. package/src/query/executor.ts +118 -0
  86. package/src/query/facade.ts +34 -0
  87. package/src/query/labels.ts +105 -0
  88. package/src/query/limits.ts +8 -0
  89. package/src/query/observability.ts +49 -0
  90. package/src/query/routes.ts +60 -0
  91. package/src/query/schema.ts +216 -0
  92. package/src/query/search.ts +15 -0
  93. package/src/relay.ts +65 -0
  94. package/src/request-timing.ts +71 -0
  95. package/src/schema-compatibility.ts +43 -0
  96. package/src/scope-operations.ts +3 -0
  97. package/src/session-contract.ts +1 -0
  98. package/src/types.ts +30 -0
  99. package/src/worker-fetch.ts +14 -0
  100. package/src/workflow-routes.ts +156 -0
  101. package/src/workflow-runtime.ts +327 -0
  102. package/src/workflow-schema.ts +29 -0
@@ -0,0 +1,100 @@
1
+ import { copyActorProjection, loadActorProjection } from '../policies'
2
+ import { scopeOperations } from '../scope-operations'
3
+ import { operationName } from '../kernel/operation-name'
4
+ import { bindKernel } from '../kernel/registry'
5
+ import type { WorkflowRuntime } from './workflow'
6
+ // Internal adapter seam: deliberately not exported from the package entry point.
7
+ import type { InstanceConfig } from '../config'
8
+ import type { Scope } from '../identity'
9
+ import type { AtomicReader, AtomicStore, ExecutionContext } from './types'
10
+ import { PermissionRevoked } from './errors'
11
+ import { atomicPermission } from './permissions'
12
+ import type { AtomicOperation } from './types'
13
+ import { ApiError } from '../errors'
14
+ // Adapter-private capability, bound to one verified context and one declared undo.
15
+ const holdReleases = new WeakMap<ExecutionContext, AtomicOperation>()
16
+ export function holdReleaseContext(context: ExecutionContext, operation: AtomicOperation) {
17
+ infrastructure(context)
18
+ if (context.scope.actor.type !== 'service' || context.scope.actor.id !== 'system' || context.scope.role !== 'SYSTEM') throw new ApiError(403, 'permission_denied')
19
+ holdReleases.set(context, operation)
20
+ return context
21
+ }
22
+ export function authorizeAtomic(context: ExecutionContext, operation: AtomicOperation, input?: unknown, identity = operation) {
23
+ const release = holdReleases.get(context)
24
+ if (release) {
25
+ if (release !== identity) throw new PermissionRevoked()
26
+ return
27
+ }
28
+ atomicPermission(context.config, context.scope, operation, input)
29
+ }
30
+ const contexts = new WeakMap<ExecutionContext, { store: AtomicStore; reader: AtomicReader; workflowRuntime?: WorkflowRuntime; policyReceipt?: boolean }>()
31
+ function freeze<T>(value: T): T {
32
+ if (value && typeof value === 'object') {
33
+ Object.values(value).forEach(freeze)
34
+ Object.freeze(value)
35
+ }
36
+ return value
37
+ }
38
+ export function coreExecutionContext(config: InstanceConfig, scope: Scope, store: AtomicStore, reader: AtomicReader, idempotencyKey?: string, workflowRuntime?: WorkflowRuntime, options: { policyReceipt?: boolean } = {}): ExecutionContext {
39
+ // Plugin hooks are trusted code, not cloneable execution data. The bound registry
40
+ // retains them; execution snapshots contain only the immutable schema/config data.
41
+ const { plugins: _plugins, ...data } = config
42
+ const context = Object.freeze({ __proto__: null, config: freeze(structuredClone(data)), scope: Object.freeze({ ...scope, actor: Object.freeze({ ...scope.actor }) }), idempotencyKey,
43
+ audit: Object.freeze({ instance_id: config.id, schema_version: config.revision, correlation_id: scope.correlationId }) }) as unknown as ExecutionContext
44
+ const restriction = scopeOperations.get(scope)
45
+ if (restriction) scopeOperations.set(context.scope, restriction)
46
+ copyActorProjection(scope, context.scope)
47
+ bindKernel(config, context.config)
48
+ contexts.set(context, { store, reader, workflowRuntime, policyReceipt: options.policyReceipt })
49
+ return context
50
+ }
51
+ export function infrastructure(context: ExecutionContext) {
52
+ const value = contexts.get(context)
53
+ if (!value) throw new ApiError(403, 'unverified_execution_context')
54
+ return value
55
+ }
56
+
57
+ /** Every workflow step/retry must call this with its actual operation before effects.
58
+ * Durable workflows use their persisted actor, independent of the browser session.
59
+ * Membership removal, role loss, agent expiry/revocation -> non-retryable needs_attention.
60
+ * No operation argument means preserving ALL grants of the saved role (conservative).
61
+ */
62
+ export async function assertLivePermission(context: ExecutionContext, operation?: AtomicOperation): Promise<Scope> {
63
+ const { reader } = infrastructure(context)
64
+ const original = context.scope
65
+ if (holdReleases.has(context)) {
66
+ if (operation !== holdReleases.get(context)) throw new PermissionRevoked()
67
+ return original
68
+ }
69
+ let role: string
70
+ let operations: string[] | null = null
71
+ if (original.actor.type === 'user') {
72
+ const member = await reader.first<{ role: string }>({ sql: 'SELECT role FROM memberships WHERE user_id=? AND organization_id=?', bindings: [original.actor.id, original.organizationId] })
73
+ if (!member) throw new PermissionRevoked()
74
+ role = member.role
75
+ } else if (original.actor.type === 'agent') {
76
+ const token = await reader.first<{ role: string; operations: string | null }>({ sql: 'SELECT role,operations FROM access_tokens WHERE id=? AND organization_id=? AND revoked_at IS NULL AND expires_at>?', bindings: [original.actor.tokenId ?? original.actor.id, original.organizationId, new Date().toISOString()] })
77
+ if (!token) throw new PermissionRevoked()
78
+ role = token.role; operations = token.operations === null ? null : JSON.parse(token.operations)
79
+ } else throw new PermissionRevoked()
80
+ const scope = freeze({ ...original, actor: { ...original.actor }, role })
81
+ scopeOperations.set(scope, { operations })
82
+ await loadActorProjection(context.config, scope, (sql, bindings) => reader.first({ sql, bindings }))
83
+ try {
84
+ if (operation) {
85
+ if (operations && !operations.includes(operationName(operation))) throw new PermissionRevoked()
86
+ atomicPermission(context.config, scope, operation)
87
+ } else {
88
+ const previous = context.config.permissions[original.role] ?? {}
89
+ const current = context.config.permissions[role] ?? {}
90
+ for (const [entity, grants] of Object.entries(previous)) if (grants.some(grant => !current[entity]?.includes(grant))) throw new PermissionRevoked()
91
+ for (const grant of context.config.organizationPermissions[original.role] ?? []) if (!context.config.organizationPermissions[role]?.includes(grant)) throw new PermissionRevoked()
92
+ // Without an operation, a constrained agent cannot prove the step's allowlist membership.
93
+ if (operations) throw new PermissionRevoked()
94
+ }
95
+ return scope
96
+ } catch (error) {
97
+ if (error instanceof ApiError && (error.status === 401 || error.status === 403)) throw new PermissionRevoked()
98
+ throw error
99
+ }
100
+ }
@@ -0,0 +1,46 @@
1
+ import { publishCommittedEvents } from '../event-delivery'
2
+ import type { RuntimeEnv } from '../types'
3
+ import type { InstanceConfig } from '../config'
4
+ import { ApiError } from '../errors'
5
+ import type { AtomicReader, AtomicStore, RawOutcome, SqlStatement, StorePlan } from './types'
6
+ import { compile, readOnly } from './compiler'
7
+ import { RuleFailed } from './errors'
8
+
9
+ export class D1AtomicReader implements AtomicReader {
10
+ constructor(private readonly db: D1Database) {}
11
+ first<T>(query: SqlStatement): Promise<T | null> {
12
+ readOnly(query)
13
+ return this.db.prepare(query.sql).bind(...(query.bindings ?? [])).first<T>()
14
+ }
15
+ }
16
+ export class D1AtomicStore implements AtomicStore {
17
+ constructor(private readonly db: D1Database, private readonly delivery?: { env: RuntimeEnv; config: InstanceConfig }) {}
18
+ async run(plan: StorePlan): Promise<RawOutcome> {
19
+ const statements = compile(plan)
20
+ let results: D1Result[]
21
+ try {
22
+ results = await this.db.batch(statements.map(s => this.db.prepare(s.sql).bind(...(s.bindings ?? []))))
23
+ } catch (error) {
24
+ if (/CHECK constraint failed: policy_ok\s*=\s*1/i.test(String(error))) throw new ApiError(403, 'policy_violation')
25
+ if (/CHECK constraint failed: actor_ok\s*=\s*1/i.test(String(error))) throw new ApiError(403, 'field_forbidden')
26
+ // The CHECK, not diagnosis, guarantees rollback. Another request may already
27
+ // have changed the rolled-back state when these optional SELECTs run.
28
+ if (!/CHECK constraint failed: (?:atomic_assert|ok\s*=\s*1)/i.test(String(error))) throw error
29
+ const reader = new D1AtomicReader(this.db)
30
+ for (const rule of plan.rules) for (const statement of rule.statements) {
31
+ if (!statement.diagnose) continue
32
+ try {
33
+ const diagnosis = await reader.first<{ ok: number }>(statement.diagnose)
34
+ if (!diagnosis?.ok) throw new RuleFailed(rule.name)
35
+ } catch (diagnosisError) {
36
+ if (diagnosisError instanceof RuleFailed) throw diagnosisError
37
+ // Diagnostic failure cannot change the guaranteed atomic rejection.
38
+ }
39
+ }
40
+ throw new RuleFailed('unknown')
41
+ }
42
+ if (this.delivery) await publishCommittedEvents(this.delivery.env, this.delivery.config,
43
+ plan.rules.flatMap(rule => rule.statements.flatMap(statement => statement.outboxEvent ? [statement.outboxEvent] : [])))
44
+ return { changes: results.map(r => r.meta.changes) }
45
+ }
46
+ }
@@ -0,0 +1,21 @@
1
+ import { ApiError } from '../errors'
2
+ export class UnsupportedAtomicOperation extends ApiError {
3
+ constructor(reason: string) { super(422, 'unsupported_atomic_operation', reason); this.name = 'UnsupportedAtomicOperation' }
4
+ }
5
+ export class RuleFailed extends ApiError {
6
+ readonly diagnosis = 'best_effort' as const
7
+ constructor(public rule: string, compatibilityCode?: string) {
8
+ super(409, compatibilityCode ?? 'rule_failed')
9
+ this.name = 'RuleFailed'
10
+ }
11
+ }
12
+ export class WorkflowRuntimeNotConfigured extends ApiError {
13
+ constructor() { super(503, 'workflow_runtime_not_configured'); this.name = 'WorkflowRuntimeNotConfigured' }
14
+ }
15
+
16
+ /** Durable engines must stop ordinary retries and persist this disposition. */
17
+ export class PermissionRevoked extends ApiError {
18
+ readonly workflowStatus = 'needs_attention' as const
19
+ readonly retryable = false
20
+ constructor() { super(403, 'permission_revoked'); this.name = 'PermissionRevoked' }
21
+ }
@@ -0,0 +1,6 @@
1
+ export * from './types'
2
+ export * from './errors'
3
+ export * from './atomic'
4
+ export * from './workflow'
5
+
6
+ export { assertLivePermission } from './context'
@@ -0,0 +1,8 @@
1
+ import type { AuditEvent } from '../audit-event'
2
+ import type { GuardedStatement } from './types'
3
+
4
+ export function outboxInsert(event: AuditEvent, guard?: { sql: string; bindings?: readonly (string | number | null)[] }): GuardedStatement {
5
+ return { sql: `INSERT INTO audit_outbox (event_id,organization_id,payload,created_at) SELECT ?,?,?,?${guard ? ` WHERE ${guard.sql}` : ''}`,
6
+ bindings: [event.event_id, event.organization_id, JSON.stringify(event), event.occurred_at, ...(guard?.bindings ?? [])], outboxEvent: event, expectRows: 1 }
7
+ }
8
+
@@ -0,0 +1,9 @@
1
+ import { kernelFor } from '../kernel/registry'
2
+ import type { InstanceConfig } from '../config'
3
+ import type { Scope } from '../identity'
4
+ import type { AtomicOperation } from './types'
5
+
6
+ export { isOrganizationAdministrator, organizationRoleRank, organizationPermission } from '../organization-permissions'
7
+ export function atomicPermission(config: InstanceConfig, scope: Scope, operation: AtomicOperation, input?: unknown) {
8
+ kernelFor(config).atomicPermission(scope, operation, input)
9
+ }
@@ -0,0 +1,156 @@
1
+ import { ApiError } from '../errors'
2
+ import { renderPredicate, type KernelRegistry } from '../kernel/registry'
3
+ import type { Predicate, PredicateRelation, TableFilter } from '../kernel/plugin'
4
+ import { actorAccountId, canManageAccountAssignments, protectedActorFields } from '../policies'
5
+ import { quote } from '../migrations/schema'
6
+ import type { Scope } from '../types'
7
+ import type { AtomicPlan, GuardedStatement, PolicyWriteGuard, SqlStatement, SqlValue } from './types'
8
+ import { UnsupportedAtomicOperation } from './errors'
9
+
10
+ export type WriteGuard = PolicyWriteGuard
11
+ export const writeGuard = (statement: GuardedStatement) => Object.hasOwn(statement, 'policyGuard') ? statement.policyGuard : undefined
12
+ /** Same structured predicate semantics as query table sources, including scoped EXISTS. */
13
+ export function writeFilter(kernel: KernelRegistry, scope: Scope, entity: string, alias = entity): SqlStatement {
14
+ const bindings: SqlValue[] = []; let references = 0
15
+ const bind = (value: string | number | boolean) => { bindings.push(typeof value === 'boolean' ? Number(value) : value); return '?' }
16
+ function render(filter: TableFilter, table: string): string {
17
+ if (++references > 128) throw new ApiError(403, 'policy_violation')
18
+ return filter.kind === 'where' ? renderPredicate(filter.predicate, table, bind, relation).sql : filter.kind === 'all' ? '1=1' : '0=1'
19
+ }
20
+ function relation(node: PredicateRelation, parent: string, negated: boolean): string {
21
+ const child = `write_policy_${references}`
22
+ const scoped = render(kernel.tableFilter(node.entity, scope), child)
23
+ const explicit = render({ kind: 'where', predicate: node.predicate }, child)
24
+ // Put policy expressions inside the derived source, as the read compiler does.
25
+ // SQLite's expression-depth cap then does not accumulate the complete target
26
+ // policy tree at every correlation along a four-relation path.
27
+ const visible = `${child}_visible`
28
+ return `${negated ? 'NOT ' : ''}EXISTS(SELECT 1 FROM (SELECT ${quote(child)}.${quote(node.field)} AS ${quote('policy_key')} FROM ${quote(node.entity)} AS ${quote(child)} WHERE ${scoped} AND ${explicit}) AS ${quote(visible)} WHERE ${quote(visible)}.${quote('policy_key')}=${quote(parent)}.${quote(node.parentField)})`
29
+ }
30
+ const sql = render(kernel.tableFilter(entity, scope), alias)
31
+ if (bindings.length > 100) throw new ApiError(403, 'policy_violation')
32
+ return { sql, bindings }
33
+ }
34
+
35
+ interface Token { text: string; start: number; end: number; depth: number; binding: number }
36
+ /** A bounded SQL lexer for trusted single-table DML, never a client SQL interface.
37
+ * Unsupported write shapes fail closed when a policy needs enforcement. */
38
+ function tokens(sql: string): Token[] {
39
+ const result: Token[] = []; let depth = 0; let binding = 0
40
+ const pattern = /\s+|'(?:''|[^'])*'|"(?:""|[^"])*"|`[^`]*`|\[[^\]]*\]|[a-zA-Z_][a-zA-Z_0-9]*|\?|[0-9]+|./g
41
+ for (const match of sql.matchAll(pattern)) {
42
+ const text = match[0]; if (/^\s+$/.test(text)) continue
43
+ if (text === ')') depth--
44
+ result.push({ text, start: match.index!, end: match.index! + text.length, depth, binding })
45
+ if (text === '?') binding++
46
+ if (text === '(') depth++
47
+ }
48
+ return result
49
+ }
50
+ const identifier = (token: Token) => token.text.replace(/^["`\[]|["`\]]$/g, '').toLowerCase()
51
+ function operand(token: Token, bindings: readonly SqlValue[]): SqlValue {
52
+ if (token.text === '?') return bindings[token.binding]
53
+ if (/^'/.test(token.text)) return token.text.slice(1, -1).replaceAll("''", "'")
54
+ throw new UnsupportedAtomicOperation('Policy INSERT requires a constant or bound id')
55
+ }
56
+ export function enforcePlan(kernel: KernelRegistry, scope: Scope, plan: AtomicPlan, memberManagement?: 'update' | 'create'): AtomicPlan {
57
+ if (scope.actor.type === 'service' && scope.role === 'SYSTEM') return plan
58
+ const protectedFields = protectedActorFields(kernel.config)
59
+ return { ...plan, rules: plan.rules.map(rule => ({ ...rule, statements: rule.statements.map(original => {
60
+ const ts = tokens(original.sql); const top = ts.filter(t => t.depth === 0)
61
+ const operation = ts[0]?.text.toUpperCase()
62
+ const target = operation === 'UPDATE' ? ts[1] : operation === 'DELETE' ? ts[2] : operation === 'INSERT' && ts[1]?.text.toUpperCase() === 'INTO' ? ts[2] : undefined
63
+ if (!target) throw new UnsupportedAtomicOperation('Unsupported policy DML shape')
64
+ const entity = identifier(target).toLowerCase()
65
+ if (target.text.startsWith("'") || ts[ts.indexOf(target) + 1]?.text === '.' || (operation === 'UPDATE' && ts[1]?.text.toUpperCase() === 'OR')) throw new UnsupportedAtomicOperation('Policy DML requires an unqualified identifier')
66
+ const domain = Object.hasOwn(kernel.config.entities, entity)
67
+ const account = entity === kernel.config.account?.entity
68
+ const member = entity === 'memberships'
69
+ if (account && ['INSERT', 'UPDATE'].includes(operation!) && memberManagement === 'create') return original
70
+ // Existing system writers retain their narrowly authorized paths.
71
+ 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')
74
+ const protect = account || member
75
+ if (!domain && !protect) return original
76
+ 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
+ const bindings = original.bindings ?? []
78
+ 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] } }
80
+ if (operation === 'UPDATE' || operation === 'DELETE') {
81
+ const where = top.find(t => t.text.toUpperCase() === 'WHERE')
82
+ const set = top.find(t => t.text.toUpperCase() === 'SET')
83
+ if (top.some(t => ['RETURNING', 'LIMIT', 'ORDER', 'FROM', 'WITH'].includes(t.text.toUpperCase()) && t !== ts[1]) && operation === 'UPDATE') throw new UnsupportedAtomicOperation('Policy mutation requires single-table DML')
84
+ if (operation === 'UPDATE' && (!set || ts[ts.indexOf(target) + 1] !== set)) throw new UnsupportedAtomicOperation('Policy UPDATE aliases are unsupported')
85
+ guard.where = { sql: where ? original.sql.slice(where.end) : '1=1', bindings: where ? bindings.slice(where.binding) : [] }
86
+ if (operation === 'DELETE' && ts[ts.indexOf(target) + 1] && ts[ts.indexOf(target) + 1] !== where) throw new UnsupportedAtomicOperation('Policy DELETE aliases are unsupported')
87
+ if (protect && operation === 'UPDATE') {
88
+ const assignments = top.filter(t => t.start >= set!.end && t.start < (where?.start ?? Infinity))
89
+ const starts = [0, ...assignments.flatMap((t, i) => t.text === ',' ? [i + 1] : [])]
90
+ if (starts.some(i => !/^[a-z][a-z0-9_]*$/.test(identifier(assignments[i])) || assignments[i + 1]?.text !== '=')) throw new UnsupportedAtomicOperation('Protected fields require simple assignments')
91
+ const assigned = starts.map(i => identifier(assignments[i]))
92
+ const dependency = (field: string) => protectedFields.has(member && field === 'user_id' ? 'id' : field)
93
+ if (assigned.some(field => dependency(field) || (member && ['user_id', 'role'].includes(field)))) {
94
+ if (account) {
95
+ // Additive account-assignment allowance, never a membership capability.
96
+ // Capture checks every target, including bulk statements and unchanged values.
97
+ if (!canManageAccountAssignments(kernel.config, scope, assigned.filter(dependency))) throw new ApiError(403, 'field_forbidden')
98
+ guard.protected = { sql: `${quote(entity)}.${quote('id')}<>?`, bindings: [actorAccountId(scope)] }
99
+ } else {
100
+ if (memberManagement !== 'update') throw new ApiError(403, 'field_forbidden')
101
+ if (assigned.some(dependency)) guard.protected = { sql: `${quote(entity)}.${quote('user_id')}<>?`, bindings: [actorAccountId(scope)] }
102
+ }
103
+ }
104
+ }
105
+ // Evaluate the original target predicate exactly once. The compiler mutates
106
+ // these captured IDs, so volatile predicates and changes() cannot choose an
107
+ // uncaptured post-image when evaluated a second time.
108
+ guard.mutation = { sql: where ? original.sql.slice(0, where.start) : original.sql, bindings: where ? bindings.slice(0, where.binding) : bindings }
109
+ } else if (operation === 'INSERT') {
110
+ if (top.some(t => ['UNION', 'ON', 'RETURNING'].includes(t.text.toUpperCase()))) throw new UnsupportedAtomicOperation('Policy INSERT does not support unions or upserts')
111
+ const open = ts[ts.indexOf(target) + 1]
112
+ const closeIndex = ts.findIndex(t => t.text === ')' && t.depth === 0)
113
+ const columns = ts.slice(ts.indexOf(open) + 1, closeIndex).filter(t => t.text !== ',').map(identifier)
114
+ const source = ts[closeIndex + 1]
115
+ if (source?.text.toUpperCase() === 'VALUES' && top.some(t => t.start > source.end && t.text === ',')) throw new UnsupportedAtomicOperation('Policy INSERT accepts one row')
116
+ const values = ts.slice(closeIndex + 2).filter(t => t.depth === (source?.text.toUpperCase() === 'VALUES' ? 1 : 0))
117
+ const operands: Token[][] = [[]]
118
+ for (const token of values) { if (token.text.toUpperCase() === 'WHERE') break; if (token.text === ',') operands.push([]); else operands.at(-1)!.push(token) }
119
+ const id = operands[columns.indexOf(member ? 'user_id' : 'id')]
120
+ if (!open || open.text !== '(' || !id || id.length !== 1) throw new UnsupportedAtomicOperation('Policy INSERT requires explicit columns and id')
121
+ guard.id = operand(id[0], bindings)
122
+ if (!domain) {
123
+ if (memberManagement !== 'create' && columns.some(field => field === 'role' || protectedFields.has(field))) throw new ApiError(403, 'field_forbidden')
124
+ if (memberManagement !== 'create' && guard.id === actorAccountId(scope) && columns.some(field => protectedFields.has(field))) throw new ApiError(403, 'field_forbidden')
125
+ return original
126
+ }
127
+ if (protect && columns.some(field => protectedFields.has(field))) throw new ApiError(403, 'field_forbidden')
128
+ } else throw new UnsupportedAtomicOperation('Unsupported policy mutation')
129
+ return { ...statement, policyGuard: guard }
130
+ }) })) }
131
+ }
132
+ function rowKey(guard: WriteGuard): string {
133
+ const table = quote(guard.entity)
134
+ return guard.entity === 'memberships' ? `json_array(${table}.user_id,${table}.organization_id)` : `${table}.id`
135
+ }
136
+ /** Internal compiler-generated assertions. IDs are captured before each UPDATE/DELETE,
137
+ * so arbitrary bulk predicates and post-image moves cannot evade the check. */
138
+ export function policyCapture(guard: WriteGuard, runId: string, index: number): SqlStatement[] {
139
+ if (!guard.where) return []
140
+ const prefix = `policy_${index}:`
141
+ return [{ sql: `INSERT INTO atomic_assert (run_id,rule,step,ok,policy_ok,actor_ok) SELECT ?,? || ${rowKey(guard)},-(${(index + 1) * 1000000}+ROW_NUMBER() OVER ()),1,CASE WHEN (${guard.filter.sql}) THEN 1 ELSE 0 END,${guard.protected ? `CASE WHEN (${guard.protected.sql}) THEN 1 ELSE 0 END` : '1'} FROM ${quote(guard.entity)} WHERE ${guard.where.sql}`,
142
+ bindings: [runId, prefix, ...(guard.filter.bindings ?? []), ...(guard.protected?.bindings ?? []), ...(guard.where.bindings ?? [])] }]
143
+ }
144
+ export function policyMutation(statement: GuardedStatement, guard: WriteGuard, runId: string, index: number): SqlStatement {
145
+ if (!guard.mutation) return statement
146
+ const prefix = `policy_${index}:`
147
+ return { sql: `${guard.mutation.sql} WHERE EXISTS(SELECT 1 FROM atomic_assert AS captured WHERE captured.run_id=? AND substr(captured.rule,1,?)=? AND ${rowKey(guard)}=substr(captured.rule,?)) AND (${guard.filter.sql})`,
148
+ bindings: [...(guard.mutation.bindings ?? []), runId, prefix.length, prefix, prefix.length + 1, ...(guard.filter.bindings ?? [])] }
149
+ }
150
+ export function policyAssertion(guard: WriteGuard, runId: string, index: number): SqlStatement {
151
+ const table = quote(guard.entity); const prefix = `policy_${index}:`
152
+ if (guard.operation === 'INSERT') return { sql: `SELECT EXISTS(SELECT 1 FROM ${table} WHERE id=? AND ${guard.filter.sql})`, bindings: [guard.id!, ...(guard.filter.bindings ?? [])] }
153
+ const exists = `EXISTS(SELECT 1 FROM ${table} WHERE ${rowKey(guard)}=substr(captured.rule,?)${guard.operation === 'DELETE' ? '' : ` AND ${guard.filter.sql}`})`
154
+ return { sql: `SELECT ${guard.requireRow ? 'EXISTS(SELECT 1 FROM atomic_assert WHERE run_id=? AND substr(rule,1,?)=?) AND ' : ''}NOT EXISTS(SELECT 1 FROM atomic_assert AS captured WHERE run_id=? AND substr(rule,1,?)=? AND ${guard.operation === 'DELETE' ? '' : 'NOT '}${exists})`,
155
+ bindings: [...(guard.requireRow ? [runId, prefix.length, prefix] : []), runId, prefix.length, prefix, prefix.length + 1, ...(guard.operation === 'DELETE' ? [] : guard.filter.bindings ?? [])] }
156
+ }
@@ -0,0 +1,51 @@
1
+ import { isBuiltinPlugin } from '../kernel/builtin-source'
2
+ import { ApiError } from '../errors'
3
+ import { requestHash } from '../idempotency'
4
+ import type { InstanceConfig } from '../config'
5
+ import type { Scope } from '../types'
6
+ import type { KernelRegistry } from '../kernel/registry'
7
+ import { actorPolicyIdentity } from '../policies'
8
+ import { quote } from '../migrations/schema'
9
+ import { writeFilter, writeGuard } from './policies'
10
+ import type { AtomicReader, AtomicResult, AtomicRule, SqlStatement, SqlValue } from './types'
11
+
12
+ export function needsPolicyReceipt(kernel: KernelRegistry) {
13
+ return !!kernel.config.account || Object.values(kernel.config.policies).some(roles => Object.values(roles).some(policy => typeof policy === 'object' && Object.keys(policy.where).length)) || kernel.plugins.some(plugin => plugin.tableFilter && !(isBuiltinPlugin(plugin) && plugin.policyInConfig === true))
14
+ }
15
+ export const receiptIdentity = (config: InstanceConfig, scope: Scope) => requestHash('policy-receipt', actorPolicyIdentity(config, scope))
16
+ /** Capture affected IDs while assertion rows still exist, before final post-image checks.
17
+ * Receipt metadata is adapter-private and is stripped before returning an AtomicResult. */
18
+ export function receiptExpression(config: InstanceConfig, rules: readonly AtomicRule[], runId: string, result: AtomicResult, identity: string): SqlStatement {
19
+ const parts: string[] = []; const bindings: SqlValue[] = [JSON.stringify(result), identity]; let index = 0
20
+ for (const rule of rules) for (const statement of rule.statements) {
21
+ const guard = writeGuard(statement); const prefix = `policy_${guard ? index++ : -1}:`
22
+ if (!guard || !config.entities[guard.entity] || guard.operation === 'DELETE') continue
23
+ if (guard.where) {
24
+ parts.push('SELECT ? AS entity,substr(rule,?) AS id FROM atomic_assert WHERE run_id=? AND substr(rule,1,?)=?')
25
+ bindings.push(guard.entity, prefix.length + 1, runId, prefix.length, prefix)
26
+ } else {
27
+ parts.push('SELECT ? AS entity,? AS id'); bindings.push(guard.entity, guard.id!)
28
+ }
29
+ }
30
+ const rows = parts.length ? `(SELECT json_group_array(json_object('entity',entity,'id',id)) FROM (${parts.join(' UNION ALL ')}))` : "'[]'"
31
+ return { sql: `json_set(?, '$.__workbase_policy', json_object('actor',?, 'rows',json(${rows})))`, bindings }
32
+ }
33
+ export async function authorizeReplay(kernel: KernelRegistry, scope: Scope, reader: AtomicReader, serialized: string, identity?: string): Promise<AtomicResult> {
34
+ const { __workbase_policy: receipt, ...result } = JSON.parse(serialized)
35
+ if (identity) {
36
+ if (!receipt || receipt.actor !== identity) throw new ApiError(403, 'policy_violation')
37
+ await authorizeReceiptRows(kernel, scope, reader, receipt.rows)
38
+ }
39
+ return result as AtomicResult
40
+ }
41
+ /** Workflow readers use their own live row policy, independently of the effect's initiating actor. */
42
+ export async function authorizeReceiptRows(kernel: KernelRegistry, scope: Scope, reader: AtomicReader, rows: unknown, read = false) {
43
+ if (!Array.isArray(rows)) throw new ApiError(403, 'policy_violation')
44
+ for (const row of rows) {
45
+ if (!row || !Object.hasOwn(kernel.config.entities, row.entity) || typeof row.id !== 'string') throw new ApiError(403, 'policy_violation')
46
+ if (read && !kernel.can(scope, row.entity, 'read')) throw new ApiError(403, 'policy_violation')
47
+ const filter = writeFilter(kernel, scope, row.entity)
48
+ const visible = await reader.first<{ ok: number }>({ sql: `SELECT EXISTS(SELECT 1 FROM ${quote(row.entity)} WHERE id=? AND (${filter.sql})) AS ok`, bindings: [row.id, ...(filter.bindings ?? [])] })
49
+ if (!visible?.ok) throw new ApiError(403, 'policy_violation')
50
+ }
51
+ }
@@ -0,0 +1,74 @@
1
+ import type { z } from 'zod'
2
+ import type { InstanceConfig, Operation, OrganizationAction } from '../config'
3
+ import type { Scope } from '../identity'
4
+ import type { AuditEvent } from '../audit-event'
5
+
6
+ export type SqlValue = string | number | null
7
+ export interface SqlStatement { sql: string; bindings?: readonly SqlValue[] }
8
+ /** Generated only by the execution policy pass; retained by serializing adapters. */
9
+ export interface PolicyWriteGuard {
10
+ entity: string; where?: SqlStatement; filter: SqlStatement; operation: string
11
+ protected?: SqlStatement; id?: SqlValue; requireRow?: boolean; mutation?: SqlStatement
12
+ }
13
+ export interface GuardedStatement extends SqlStatement {
14
+ /** Outbox event committed by this statement; used only after batch success. */
15
+ outboxEvent?: AuditEvent
16
+ readonly policyGuard?: PolicyWriteGuard
17
+ expectRows?: 1 | '>=1'
18
+ /** Optional read-only diagnosis after rollback; never decides whether to commit. */
19
+ diagnose?: SqlStatement
20
+ database?: string
21
+ }
22
+ export interface AtomicRule { name: string; statements: readonly GuardedStatement[] }
23
+ export interface AtomicResult { status: number; body: Record<string, any> }
24
+ export interface EventDescription {
25
+ operation: string; entity: string; entityId: string
26
+ before?: Record<string, unknown>; after?: Record<string, unknown>
27
+ /** Redacted effect receipt for operations spanning several rows. */
28
+ details?: Record<string, unknown>
29
+ }
30
+ export interface AtomicPlan {
31
+ rules: readonly AtomicRule[]
32
+ result: AtomicResult
33
+ event: EventDescription
34
+ /** Only the adapter's primary database is supported. */
35
+ databases?: readonly string[]
36
+ remoteCall?: boolean
37
+ dependsOnPriorWrite?: boolean
38
+ /** Compatibility for existing HTTP rejection bodies. New operations use rule_failed. */
39
+ conflict?: string
40
+ }
41
+ export interface StorePlan { runId: string; rules: readonly AtomicRule[] }
42
+ export interface RawOutcome { changes: readonly number[] }
43
+ /** One indivisible submission. No transaction handle or between-statement callbacks. */
44
+ export interface AtomicStore { run(plan: StorePlan): Promise<RawOutcome> }
45
+ export interface AtomicReader { first<T>(query: SqlStatement): Promise<T | null> }
46
+ declare const verifiedContext: unique symbol
47
+ /** Core adapters alone construct this after authentication and live membership resolution. */
48
+ export interface ExecutionContext {
49
+ readonly [verifiedContext]: true
50
+ readonly scope: Readonly<Scope>
51
+ readonly config: InstanceConfig
52
+ readonly idempotencyKey?: string
53
+ readonly audit: Readonly<Pick<AuditEvent, 'instance_id' | 'schema_version' | 'correlation_id'>>
54
+ }
55
+ export interface PreparationContext extends ExecutionContext { readonly reader: AtomicReader }
56
+ export interface PlanningContext<Prepared = undefined> extends ExecutionContext {
57
+ readonly prepared: Prepared
58
+ readonly now: string
59
+ readonly newId: string
60
+ }
61
+ /** Reusable rule functions have no store, promises or commit capability. */
62
+ export type Rule<Input, Prepared = undefined> = (ctx: PlanningContext<Prepared>, input: Input) => AtomicRule
63
+ export interface AtomicOperation<Schema extends z.ZodType = z.ZodType, Prepared = any> {
64
+ name: string
65
+ /** Public presentation only; never grants authority or changes execution. */
66
+ ui?: { labelKey?: string; label?: string | { en: string; cs: string }; replacesCrud?: 'create' | 'update' | 'delete' }
67
+ permission: { entity: string; operation: Operation } | { system: OrganizationAction | 'organizations.create' | 'members.leave' | 'invitations.accept' | 'identity.write' }
68
+ additionalPermissions?: readonly { entity: string; operation: Operation }[]
69
+ input: Schema
70
+ idempotency?: 'required' | 'optional'
71
+ /** Reads only, before planning. Every correctness dependency must be rechecked in SQL. */
72
+ prepare?(ctx: PreparationContext, input: z.output<Schema>): Promise<Prepared>
73
+ plan(ctx: PlanningContext<Prepared>, input: z.output<Schema>): AtomicPlan
74
+ }
@@ -0,0 +1,35 @@
1
+ import type { z } from 'zod'
2
+ import type { AtomicOperation, ExecutionContext } from './types'
3
+ import { infrastructure } from './context'
4
+ import { WorkflowRuntimeNotConfigured } from './errors'
5
+ export type WorkflowStatus = 'pending' | 'running' | 'waiting_external' | 'completed' | 'failed' | 'compensating' | 'compensated' | 'needs_attention' | 'cancelled'
6
+ export interface WorkflowStepContext {
7
+ context: ExecutionContext; runId: string; input: any; checkpoints: Record<string, unknown>; signal: AbortSignal
8
+ }
9
+ export interface WorkflowStep {
10
+ id: string
11
+ /** Actual permission checked on every attempt, including compensation. */
12
+ operation: AtomicOperation<any>
13
+ kind?: 'atomic' | 'external'
14
+ policy: { maxAttempts: number; backoffMs: number; timeoutMs: number; deadlineMs: number }
15
+ /** Effects must deduplicate using context.idempotencyKey (atomic) or runId (external). */
16
+ run(context: WorkflowStepContext): Promise<unknown>
17
+ /** Read-only receipt lookup; never issues another business effect. null means uncertain. */
18
+ recover?(context: WorkflowStepContext): Promise<unknown | null>
19
+ /** This step owns the workflow_holds reservation; its undo only releases that hold. */
20
+ holdsCapacity?: boolean
21
+ sideEffect: boolean
22
+ compensate?: { operation: AtomicOperation<any>; run(context: WorkflowStepContext): Promise<unknown> }
23
+ }
24
+ export interface WorkflowDefinition<S extends z.ZodType = z.ZodType> {
25
+ name: string; version: string; input: S; steps?: readonly WorkflowStep[]
26
+ }
27
+ export interface WorkflowHandle { id: string }
28
+ export interface WorkflowRuntime {
29
+ start<S extends z.ZodType>(workflow: WorkflowDefinition<S>, input: z.output<S>, context: ExecutionContext): Promise<WorkflowHandle>
30
+ }
31
+ export async function startWorkflow<S extends z.ZodType>(workflow: WorkflowDefinition<S>, input: unknown, context: ExecutionContext): Promise<WorkflowHandle> {
32
+ const { workflowRuntime } = infrastructure(context)
33
+ if (!workflowRuntime) throw new WorkflowRuntimeNotConfigured()
34
+ return workflowRuntime.start(workflow, workflow.input.parse(input), context)
35
+ }
@@ -0,0 +1,36 @@
1
+ import { z } from 'zod'
2
+ import type { InstanceConfig } from './config'
3
+ import type { ConsoleEntityDisplay } from './console-contract'
4
+
5
+ const identifier = z.string().regex(/^[a-z][a-z0-9_]*$/)
6
+ const view = z.strictObject({ fields: z.array(identifier) })
7
+ /** Canonical serializable form contract, shared with explicit Console contributions. */
8
+ export const formDisplaySchema = z.strictObject({ create: view.optional(), edit: view.optional() })
9
+ export const formSectionsSchema = z.array(z.strictObject({ id: identifier, label: z.string().min(1), fields: z.array(identifier) }))
10
+
11
+ export function validateFormDisplay(name: string, entity: InstanceConfig['entities'][string], display: Pick<ConsoleEntityDisplay, 'form' | 'sections'>) {
12
+ const known = (field: string) => Object.hasOwn(entity.fields, field) || !!entity.relations[field]?.through
13
+ const check = (fields: string[]) => {
14
+ const seen = new Set<string>()
15
+ for (const field of fields) {
16
+ if (!known(field)) throw new Error(`Unknown UI form field: ${name}.${field}`)
17
+ if (seen.has(field)) throw new Error(`Duplicate UI form field: ${name}.${field}`)
18
+ seen.add(field)
19
+ }
20
+ }
21
+ const form = display.form === undefined ? undefined : formDisplaySchema.parse(display.form)
22
+ for (const view of Object.values(form ?? {})) check(view.fields)
23
+ if (form?.create) for (const [field, spec] of Object.entries(entity.fields)) {
24
+ // Server defaults and server-owned fields need no create control.
25
+ if (spec.required && !spec.readOnly && spec.default === undefined && (!form.create.fields.includes(field) || spec.ui?.hidden)) {
26
+ throw new Error(`Required UI create field omitted: ${name}.${field}`)
27
+ }
28
+ }
29
+ const sections = display.sections === undefined ? [] : formSectionsSchema.parse(display.sections)
30
+ const ids = new Set<string>()
31
+ check(sections.flatMap(section => section.fields))
32
+ for (const section of sections) {
33
+ if (ids.has(section.id)) throw new Error(`Duplicate UI form section: ${name}.${section.id}`)
34
+ ids.add(section.id)
35
+ }
36
+ }
@@ -0,0 +1,10 @@
1
+ import { sha256 } from './crypto'
2
+ // Canonical JSON makes property ordering irrelevant, including nested operation inputs.
3
+ function canonical(value: any): any {
4
+ if (Array.isArray(value)) return value.map(canonical)
5
+ if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])]))
6
+ return value
7
+ }
8
+ export async function requestHash(command: string, input: unknown) {
9
+ return sha256(JSON.stringify(canonical({ command, input })))
10
+ }
@@ -0,0 +1,2 @@
1
+ import { z } from 'zod'
2
+ export const emailSchema = z.email().transform(value => value.toLowerCase())
@@ -0,0 +1,42 @@
1
+ import type { RuntimeEnv } from './types'
2
+ import { ApiError } from './errors'
3
+ const loopbackHosts = new Set(['localhost', '127.0.0.1', '[::1]'])
4
+ /** Dev credentials require the real request boundary, never just a copied baseURL.
5
+ * Forwarded headers are deliberately not trusted. Browser requests must also be same-origin. */
6
+ export function devLocalIdentityEnabled(env: RuntimeEnv, request?: Request): boolean {
7
+ return !!env.IDENTITY?.localPassword && !!request && loopbackIdentityRequest(request)
8
+ }
9
+ function loopbackIdentityRequest(request: Request): boolean {
10
+ const url = new URL(request.url)
11
+ if (!['http:', 'https:'].includes(url.protocol) || !loopbackHosts.has(url.hostname)) return false
12
+ const host = request.headers.get('host')
13
+ const origin = request.headers.get('origin')
14
+ return (!host || host.toLowerCase() === url.host) && (!origin || origin === url.origin)
15
+ }
16
+ /** Inspect the actual URL before reading credentials. Never trust Forwarded headers. */
17
+ export function assertIdentityTransport(request: Request, status: 401 | 403 = 401): void {
18
+ if (new URL(request.url).protocol === 'https:' || loopbackIdentityRequest(request)) return
19
+ throw new ApiError(status, 'insecure_identity_transport')
20
+ }
21
+ /** SST injects flat bindings. The object form is for in-process adapters/tests. */
22
+ export function identityEnvironment(env: RuntimeEnv): RuntimeEnv {
23
+ if (env.IDENTITY) {
24
+ const settings = env.IDENTITY
25
+ const origin = new URL(settings.baseURL)
26
+ const loopback = loopbackHosts.has(origin.hostname)
27
+ // HTTP is permitted only for loopback development; cookies remain Secure even there.
28
+ if (origin.origin !== settings.baseURL || (origin.protocol !== 'https:' && !(origin.protocol === 'http:' && loopback))) throw new ApiError(503, 'invalid_identity_origin')
29
+ if (settings.localPassword && !loopback) throw new ApiError(503, 'dev_identity_requires_loopback')
30
+ if (settings.oidc) {
31
+ const issuer = new URL(settings.oidc.issuer)
32
+ if (issuer.username || issuer.password || issuer.search || issuer.hash || (issuer.protocol !== 'https:' && !(issuer.protocol === 'http:' && loopbackHosts.has(issuer.hostname)))) throw new ApiError(503, 'invalid_oidc_issuer')
33
+ }
34
+ return env
35
+ }
36
+ if (!env.AUTH_BASE_URL && !env.BETTER_AUTH_SECRET) return env
37
+ if (!env.AUTH_BASE_URL || !env.BETTER_AUTH_SECRET) throw new ApiError(503, 'identity_not_configured')
38
+ const oidcValues = [env.OIDC_ISSUER, env.OIDC_CLIENT_ID, env.OIDC_CLIENT_SECRET]
39
+ if (oidcValues.some(Boolean) && !oidcValues.every(Boolean)) throw new ApiError(503, 'oidc_not_configured')
40
+ return identityEnvironment({ ...env, IDENTITY: { baseURL: env.AUTH_BASE_URL, secret: env.BETTER_AUTH_SECRET, localPassword: env.DEV_LOCAL_IDENTITY === 'true',
41
+ ...(env.OIDC_ISSUER ? { oidc: { issuer: env.OIDC_ISSUER, clientId: env.OIDC_CLIENT_ID!, clientSecret: env.OIDC_CLIENT_SECRET! } } : {}) } })
42
+ }
@@ -0,0 +1,14 @@
1
+ // Trusted identity adapter only; never exported from the package entry point.
2
+ import { z } from 'zod'
3
+ import type { InstanceConfig } from './config'
4
+ import type { RuntimeEnv } from './types'
5
+ import type { GuardedStatement } from './execution/types'
6
+ import { coreExecutionContext } from './execution/context'
7
+ import { D1AtomicReader, D1AtomicStore } from './execution/d1'
8
+ import { executeAtomic } from './execution/atomic'
9
+ export async function identityWrite(env: RuntimeEnv, config: InstanceConfig, name: string, statements: GuardedStatement[], userId = 'identity-adapter') {
10
+ const context = coreExecutionContext(config, { actor: { type: 'service', id: userId }, organizationId: '__identity__', role: '', correlationId: crypto.randomUUID() }, new D1AtomicStore(env.DB, { env, config }), new D1AtomicReader(env.DB))
11
+ return executeAtomic({ name: `identity/${name}`, permission: { system: 'identity.write' }, input: z.strictObject({}), plan: () => ({
12
+ rules: [{ name: `identity_${name}`, statements }], event: { operation: `identity.${name}`, entity: 'identities', entityId: userId }, result: { status: 200, body: {} },
13
+ }) }, {}, context)
14
+ }