@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.
- package/LICENSE +202 -0
- package/NOTICE +4 -0
- package/package.json +62 -1
- package/src/account-provisioning.ts +24 -0
- package/src/admin-forms.tsx +70 -0
- package/src/admin-security.ts +63 -0
- package/src/admin-ui.tsx +438 -0
- package/src/app.ts +115 -0
- package/src/audit-event.ts +23 -0
- package/src/audit.ts +35 -0
- package/src/authorization-api.ts +3 -0
- package/src/authorization.ts +135 -0
- package/src/authorized-execution.ts +15 -0
- package/src/bootstrap.ts +23 -0
- package/src/browser-dispatch.ts +19 -0
- package/src/calendar-display.ts +26 -0
- package/src/capabilities.ts +41 -0
- package/src/commands.ts +46 -0
- package/src/config-proposal-contract.ts +16 -0
- package/src/config-proposals.ts +95 -0
- package/src/config-shorthand.ts +200 -0
- package/src/config.ts +286 -0
- package/src/console-contract.ts +105 -0
- package/src/console-contribution.ts +7 -0
- package/src/console.ts +84 -0
- package/src/crud.ts +146 -0
- package/src/crypto.ts +33 -0
- package/src/detail-display.ts +59 -0
- package/src/detail-layout.ts +17 -0
- package/src/errors.ts +3 -0
- package/src/event-delivery.ts +76 -0
- package/src/events.ts +11 -0
- package/src/execution/atomic.ts +70 -0
- package/src/execution/compiler.ts +55 -0
- package/src/execution/context.ts +100 -0
- package/src/execution/d1.ts +46 -0
- package/src/execution/errors.ts +21 -0
- package/src/execution/index.ts +6 -0
- package/src/execution/outbox.ts +8 -0
- package/src/execution/permissions.ts +9 -0
- package/src/execution/policies.ts +156 -0
- package/src/execution/policy-receipts.ts +51 -0
- package/src/execution/types.ts +74 -0
- package/src/execution/workflow.ts +35 -0
- package/src/form-display.ts +36 -0
- package/src/idempotency.ts +10 -0
- package/src/identity-providers.ts +2 -0
- package/src/identity-settings.ts +42 -0
- package/src/identity-writes.ts +14 -0
- package/src/identity.ts +2 -0
- package/src/index.ts +32 -0
- package/src/json-csrf.ts +22 -0
- package/src/kernel/adapters/tenancy.ts +8 -0
- package/src/kernel/audit-port.ts +12 -0
- package/src/kernel/builtin-source.ts +34 -0
- package/src/kernel/composition.ts +77 -0
- package/src/kernel/identity-port.ts +36 -0
- package/src/kernel/mail-outbox-port.ts +23 -0
- package/src/kernel/migrations.ts +76 -0
- package/src/kernel/operation-name.ts +8 -0
- package/src/kernel/plugin.ts +92 -0
- package/src/kernel/predicate.ts +69 -0
- package/src/kernel/registry.ts +198 -0
- package/src/kernel/schema-check.ts +13 -0
- package/src/logging.ts +21 -0
- package/src/migrations/better-auth-schema.ts +2 -0
- package/src/migrations/email-delivery-schema.ts +6 -0
- package/src/migrations/planner.ts +77 -0
- package/src/migrations/schema.ts +85 -0
- package/src/migrations/version-contract.ts +28 -0
- package/src/migrations/versions.ts +90 -0
- package/src/ops-schema.ts +13 -0
- package/src/ops.ts +34 -0
- package/src/organization-permissions.ts +13 -0
- package/src/organization-rules.ts +25 -0
- package/src/organizations.ts +43 -0
- package/src/plugins.ts +3 -0
- package/src/policies.ts +186 -0
- package/src/public-schema.ts +65 -0
- package/src/query/compiler.ts +395 -0
- package/src/query/cursor.ts +43 -0
- package/src/query/enum-labels.json +16 -0
- package/src/query/enum-values.ts +7 -0
- package/src/query/errors.ts +10 -0
- package/src/query/executor.ts +118 -0
- package/src/query/facade.ts +34 -0
- package/src/query/labels.ts +105 -0
- package/src/query/limits.ts +8 -0
- package/src/query/observability.ts +49 -0
- package/src/query/routes.ts +60 -0
- package/src/query/schema.ts +216 -0
- package/src/query/search.ts +15 -0
- package/src/relay.ts +65 -0
- package/src/request-timing.ts +71 -0
- package/src/schema-compatibility.ts +43 -0
- package/src/scope-operations.ts +3 -0
- package/src/session-contract.ts +1 -0
- package/src/types.ts +30 -0
- package/src/worker-fetch.ts +14 -0
- package/src/workflow-routes.ts +156 -0
- package/src/workflow-runtime.ts +327 -0
- package/src/workflow-schema.ts +29 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { InstanceConfig, OrganizationAction } from './config'
|
|
2
|
+
import { isOrganizationAdministrator, organizationRoleRank } from './execution/permissions'
|
|
3
|
+
import type { Scope } from './identity'
|
|
4
|
+
import type { AtomicRule, SqlStatement } from './execution/types'
|
|
5
|
+
|
|
6
|
+
export function issuerGuard(config: InstanceConfig, scope: Scope, action: OrganizationAction, grantRole?: string) {
|
|
7
|
+
const roles = Object.entries(config.organizationPermissions).filter(([, grants]) => grants.includes(action)).map(([role]) => role)
|
|
8
|
+
.filter(role => action.startsWith('invitations.') || isOrganizationAdministrator(config, role))
|
|
9
|
+
.filter(role => grantRole === undefined || organizationRoleRank(config, role) >= organizationRoleRank(config, grantRole))
|
|
10
|
+
return { sql: `EXISTS (SELECT 1 FROM memberships issuer WHERE issuer.organization_id=? AND issuer.user_id=? AND issuer.role IN (${roles.map(() => '?').join(',') || 'NULL'}))`, values: [scope.organizationId, scope.actor.id, ...roles] }
|
|
11
|
+
}
|
|
12
|
+
/** Each gate raises an SQL assertion before any later membership, email or audit write. */
|
|
13
|
+
export function organizationRule(name: string, ...statements: SqlStatement[]): AtomicRule {
|
|
14
|
+
return { name, statements: statements.map(statement => ({ ...statement, expectRows: 1 })) }
|
|
15
|
+
}
|
|
16
|
+
export function memberMutationRule(config: InstanceConfig, scope: Scope, userId: string, role: string | null, remove: boolean, leave: boolean): AtomicRule {
|
|
17
|
+
const guard = leave ? { sql: '1', values: [] } : issuerGuard(config, scope, remove ? 'members.remove' : 'members.update')
|
|
18
|
+
const predicate = `organization_id=? AND user_id=? AND (role<>? OR ?=? OR (SELECT count(*) FROM memberships owners WHERE owners.organization_id=? AND owners.role=?)>1) AND ${guard.sql}`
|
|
19
|
+
const values = [scope.organizationId, userId, config.organizationOwnerRole, role, config.organizationOwnerRole, scope.organizationId, config.organizationOwnerRole, ...guard.values]
|
|
20
|
+
return { name: 'last_owner', statements: [{
|
|
21
|
+
sql: remove ? `DELETE FROM memberships WHERE ${predicate}` : `UPDATE memberships SET role=? WHERE ${predicate}`,
|
|
22
|
+
bindings: remove ? values : [role, ...values], expectRows: 1,
|
|
23
|
+
diagnose: { sql: `SELECT EXISTS (SELECT 1 FROM memberships WHERE ${predicate}) AS ok`, bindings: values },
|
|
24
|
+
}] }
|
|
25
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { authorizeOperation } from './authorization'
|
|
2
|
+
import { isOrganizationAdministrator } from './execution/permissions'
|
|
3
|
+
import { ApiError } from './errors'
|
|
4
|
+
import { z } from 'zod'
|
|
5
|
+
import { coreExecutionContext } from './execution/context'
|
|
6
|
+
import { D1AtomicStore, D1AtomicReader } from './execution/d1'
|
|
7
|
+
import { executeAtomic, defineAtomicOperation } from './execution/atomic'
|
|
8
|
+
import type { InstanceConfig } from './config'
|
|
9
|
+
import type { RuntimeEnv, Scope } from './types'
|
|
10
|
+
import type { AtomicOperation, AtomicPlan, ExecutionContext } from './execution/types'
|
|
11
|
+
import type { ResolvedActor } from './authorization'
|
|
12
|
+
// Only the trusted plugin route executors below can mint these values. Nothing on a
|
|
13
|
+
// public context, callback prototype or operation permission grants membership.
|
|
14
|
+
const memberCapabilities = new WeakSet<object>()
|
|
15
|
+
const memberSlots = new WeakMap<ExecutionContext, Readonly<{ operation: AtomicOperation; mode: 'update' | 'create' }>>()
|
|
16
|
+
/** Read-only execution seam; never returns the capability itself. */
|
|
17
|
+
export function memberManagementMode(context: ExecutionContext, operation: AtomicOperation): 'update' | 'create' | undefined {
|
|
18
|
+
const capability = memberSlots.get(context)
|
|
19
|
+
return capability && memberCapabilities.has(capability) && capability.operation === operation ? capability.mode : undefined
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function meDocument(resolved: ResolvedActor, config: InstanceConfig) {
|
|
23
|
+
const provider = config.plugins?.find(plugin => plugin.provides?.organizations)
|
|
24
|
+
const organizationCreationAllowed = !!provider && (config.pluginConfig?.[provider.name] as { allowCreate?: boolean } | undefined)?.allowCreate !== false
|
|
25
|
+
return { organizationsEnabled: !!provider, organizationCreationAllowed, user: resolved.user, actor: resolved.actor, memberships: resolved.organizations.map(org => ({ organization_id: org.id, name: org.name, role: org.role })) }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function membershipExecutor(config: InstanceConfig, env: RuntimeEnv) {
|
|
29
|
+
// Only core-resolved scopes reach this seam. The HTTP schemas have already
|
|
30
|
+
// validated input; the plan is a synchronous, fully bound SQL description.
|
|
31
|
+
return async function execute(scope: Scope, name: string, system: Extract<AtomicOperation['permission'], { system: string }>['system'], plan: AtomicPlan) {
|
|
32
|
+
authorizeOperation(scope, name)
|
|
33
|
+
const context = coreExecutionContext(config, scope, new D1AtomicStore(env.DB, { env, config }), new D1AtomicReader(env.DB))
|
|
34
|
+
const operation = defineAtomicOperation({ name, permission: { system }, input: z.strictObject({}), plan: () => plan })
|
|
35
|
+
if (['members.update', 'organizations.create', 'invitations.accept'].includes(system)) {
|
|
36
|
+
if (context.scope.actor.type !== 'user' || (system === 'members.update' && !isOrganizationAdministrator(config, context.scope.role))) throw new ApiError(403, 'field_forbidden')
|
|
37
|
+
const capability = Object.freeze({ operation, mode: system === 'members.update' ? 'update' as const : 'create' as const })
|
|
38
|
+
memberCapabilities.add(capability)
|
|
39
|
+
memberSlots.set(context, capability)
|
|
40
|
+
}
|
|
41
|
+
return executeAtomic(operation, {}, context)
|
|
42
|
+
}
|
|
43
|
+
}
|
package/src/plugins.ts
ADDED
package/src/policies.ts
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { constantQuantifier } from './config-shorthand'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
import { baseFields, type Field, type InstanceConfig } from './config'
|
|
4
|
+
import { fieldsFor, fieldType, filterSchema, type Filter } from './query/schema'
|
|
5
|
+
import type { Predicate, PredicateOperators, TableFilter } from './kernel/plugin'
|
|
6
|
+
import type { Scope } from './types'
|
|
7
|
+
import { ApiError } from './errors'
|
|
8
|
+
import { quote } from './migrations/schema'
|
|
9
|
+
import { kernelFor } from './kernel/registry'
|
|
10
|
+
|
|
11
|
+
type ActorRow = Record<string, string | number | boolean | null>
|
|
12
|
+
export interface ActorMembership { user_id: string; organization_id: string; role: string }
|
|
13
|
+
const projections = new WeakMap<Scope, Readonly<ActorRow>>()
|
|
14
|
+
const protectedByConfig = new WeakMap<InstanceConfig, ReadonlySet<string>>()
|
|
15
|
+
export function actorFields(config: InstanceConfig): Record<string, Field['type']> {
|
|
16
|
+
return { ...Object.fromEntries(config.account ? fieldsFor(config, config.account.entity).map(name => [name, fieldType(config, config.account!.entity, name)]) : []), id: 'string', role: 'string', organization_id: 'string' }
|
|
17
|
+
}
|
|
18
|
+
export function validatePolicies(config: InstanceConfig) {
|
|
19
|
+
const fields = actorFields(config); const protectedFields = new Set<string>(config.account?.assignments ?? [])
|
|
20
|
+
const actorValue = (type: Field['type']) => z.string().refine(value => {
|
|
21
|
+
if (!value.startsWith('$actor.')) return false
|
|
22
|
+
const field = value.slice(7)
|
|
23
|
+
return Object.hasOwn(fields, field) && (fields[field] === type || (['string', 'ref', 'enum', 'text', 'datetime'].includes(type) && ['string', 'ref', 'enum', 'text', 'datetime'].includes(fields[field])))
|
|
24
|
+
}, 'Unknown or incompatible $actor field')
|
|
25
|
+
function visit(value: unknown, depth = 0) {
|
|
26
|
+
if (depth > 32) throw new Error('Policy depth exceeds budget')
|
|
27
|
+
if (typeof value === 'string' && value.startsWith('$actor.')) {
|
|
28
|
+
const name = value.slice(7)
|
|
29
|
+
if (!Object.hasOwn(fields, name)) throw new Error(`Unknown $actor field: ${name}`)
|
|
30
|
+
protectedFields.add(name)
|
|
31
|
+
} else if (value && typeof value === 'object') Object.values(value).forEach(child => visit(child, depth + 1))
|
|
32
|
+
}
|
|
33
|
+
for (const [entity, roles] of Object.entries(config.policies)) {
|
|
34
|
+
if (!Object.hasOwn(config.entities, entity)) throw new Error(`Unknown policy entity: ${entity}`)
|
|
35
|
+
for (const [role, policy] of Object.entries(roles)) {
|
|
36
|
+
if (!config.roles.includes(role)) throw new Error(`Unknown policy role: ${role}`)
|
|
37
|
+
if (typeof policy === 'string') continue
|
|
38
|
+
visit(policy.where)
|
|
39
|
+
// Validate references separately: a string operand must not accept an unknown actor name as a literal.
|
|
40
|
+
filterSchema(config, false, 4, actorValue)(entity, 0).parse(policy.where)
|
|
41
|
+
if (policy.fields?.some(field => !fieldsFor(config, entity).includes(field))) throw new Error(`Unknown policy field: ${entity}`)
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
protectedByConfig.set(config, protectedFields)
|
|
45
|
+
}
|
|
46
|
+
export function protectedActorFields(config: InstanceConfig): ReadonlySet<string> {
|
|
47
|
+
if (!protectedByConfig.has(config)) validatePolicies(config)
|
|
48
|
+
return protectedByConfig.get(config)!
|
|
49
|
+
}
|
|
50
|
+
/** Only server adapters call this. Scope resolution may pass its freshly verified
|
|
51
|
+
* membership; executions without that projection always reload live authority. */
|
|
52
|
+
export async function loadActorProjection(config: InstanceConfig, scope: Scope, first: <T>(sql: string, bindings: (string | number | null)[]) => Promise<T | null>, membership?: Readonly<ActorMembership>) {
|
|
53
|
+
projections.delete(scope)
|
|
54
|
+
if (scope.actor.type === 'service') return
|
|
55
|
+
let accountId = scope.actor.id
|
|
56
|
+
if (scope.actor.type === 'agent') {
|
|
57
|
+
const token = await first<{ issuer_id: string }>('SELECT issuer_id FROM access_tokens WHERE id=? AND organization_id=? AND revoked_at IS NULL AND expires_at>?', [scope.actor.tokenId ?? scope.actor.id, scope.organizationId, new Date().toISOString()])
|
|
58
|
+
if (!token) return
|
|
59
|
+
accountId = token.issuer_id
|
|
60
|
+
}
|
|
61
|
+
const member = scope.actor.type === 'user' && membership?.user_id === accountId && membership.organization_id === scope.organizationId
|
|
62
|
+
? membership : await first<ActorMembership>('SELECT * FROM memberships WHERE user_id=? AND organization_id=?', [accountId, scope.organizationId])
|
|
63
|
+
if (!member) return
|
|
64
|
+
const extension = config.account ? await first<ActorRow>(`SELECT ${fieldsFor(config, config.account.entity).map(quote).join(',')} FROM ${quote(config.account.entity)} WHERE id=? AND organization_id=?`, [accountId, scope.organizationId]) : {}
|
|
65
|
+
if (!extension) return // Unmapped accounts are deny-all, even for a named membership role.
|
|
66
|
+
const row: ActorRow = { ...extension, id: accountId, role: member.role, organization_id: scope.organizationId }
|
|
67
|
+
for (const [field, definition] of Object.entries(config.account ? config.entities[config.account.entity].fields : {})) if (definition.type === 'bool' && row[field] !== null) row[field] = Boolean(row[field])
|
|
68
|
+
// Extension role is application data; memberships remain the authority for the active role.
|
|
69
|
+
projections.set(scope, Object.freeze(row))
|
|
70
|
+
}
|
|
71
|
+
export function actorAccountId(scope: Scope): string { return String(projections.get(scope)?.id ?? scope.actor.id) }
|
|
72
|
+
export function copyActorProjection(source: Scope, target: Scope) { const row = projections.get(source); if (row) projections.set(target, row) }
|
|
73
|
+
function rolePolicyFilter(config: InstanceConfig, entity: string, scope: Scope, role: string): TableFilter {
|
|
74
|
+
if (scope.actor.type === 'service' && scope.role === 'SYSTEM') return { kind: 'all' }
|
|
75
|
+
const actor = projections.get(scope)
|
|
76
|
+
if ((config.account || scope.actor.type === 'agent') && !actor) return { kind: 'none' }
|
|
77
|
+
const policy = config.policies[entity]?.[role] ?? 'none'
|
|
78
|
+
if (policy === 'all') return { kind: 'all' }
|
|
79
|
+
if (policy === 'none') return { kind: 'none' }
|
|
80
|
+
if (!Object.keys(policy.where).length && policy.deny !== 'forbidden') return { kind: 'all' }
|
|
81
|
+
if (!actor && JSON.stringify(policy.where).includes('$actor.')) return { kind: 'none' }
|
|
82
|
+
function missingOperand(value: unknown): boolean {
|
|
83
|
+
if (typeof value === 'string' && value.startsWith('$actor.')) return actor?.[value.slice(7)] == null
|
|
84
|
+
return !!value && typeof value === 'object' && Object.values(value).some(missingOperand)
|
|
85
|
+
}
|
|
86
|
+
// Deny the complete policy before Boolean composition: replacing one comparison
|
|
87
|
+
// by FALSE would become TRUE under NOT / none and could widen an OR branch.
|
|
88
|
+
// Keep a predicate so writes assert the same FALSE pre/post-image in the batch.
|
|
89
|
+
if (missingOperand(policy.where)) return { kind: 'where', predicate: { any: [] }, ...(policy.deny === 'forbidden' ? { deny: 'forbidden' as const } : {}) }
|
|
90
|
+
function substitute(value: unknown): any {
|
|
91
|
+
if (typeof value === 'string' && value.startsWith('$actor.')) return actor![value.slice(7)] ?? null
|
|
92
|
+
return Array.isArray(value) ? value.map(substitute) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).map(([key, child]) => [key, substitute(child)])) : value
|
|
93
|
+
}
|
|
94
|
+
const predicate = compilePolicyPredicate(config, entity, policy.where, substitute)
|
|
95
|
+
if (constantPredicate(predicate) === false) return { kind: 'none', ...(policy.deny === 'forbidden' ? { deny: 'forbidden' as const } : {}) }
|
|
96
|
+
return { kind: 'where', predicate, ...(policy.deny === 'forbidden' ? { deny: 'forbidden' as const } : {}) }
|
|
97
|
+
}
|
|
98
|
+
function compilePolicyPredicate(config: InstanceConfig, name: string, filter: Filter, substitute: (value: unknown) => unknown): Predicate {
|
|
99
|
+
return { all: Object.entries(filter).map(([key, value]): Predicate => {
|
|
100
|
+
if (key === 'and' || key === 'or') return { [key === 'and' ? 'all' : 'any']: (value as Filter[]).map(child => compilePolicyPredicate(config, name, child, substitute)) } as Predicate
|
|
101
|
+
if (key === 'not') return { not: compilePolicyPredicate(config, name, value as Filter, substitute) }
|
|
102
|
+
const relation = config.entities[name].relations[key]
|
|
103
|
+
if (relation) {
|
|
104
|
+
const none = relation.many && Object.hasOwn(value as object, 'none')
|
|
105
|
+
return { [none ? 'notExists' : 'exists']: { entity: relation.entity, field: relation.many ? relation.field : 'id', parentField: relation.many ? 'id' : relation.field,
|
|
106
|
+
predicate: compilePolicyPredicate(config, relation.entity, (relation.many ? (value as Record<string, Filter>)[none ? 'none' : 'some'] : value) as Filter, substitute) } } as Predicate
|
|
107
|
+
}
|
|
108
|
+
const operators = substitute(value) as PredicateOperators
|
|
109
|
+
return { [key]: operators }
|
|
110
|
+
}) }
|
|
111
|
+
}
|
|
112
|
+
/** Fold only Boolean constants; no database state is inferred by capability metadata. */
|
|
113
|
+
function constantPredicate(node: Predicate): boolean | undefined {
|
|
114
|
+
const entries = Object.entries(node)
|
|
115
|
+
if (entries.length === 1 && ['all', 'any'].includes(entries[0][0]) && Array.isArray(entries[0][1])) {
|
|
116
|
+
const [key, children] = entries[0] as ['all' | 'any', Predicate[]]
|
|
117
|
+
const values = children.map(constantPredicate)
|
|
118
|
+
if (key === 'all') return values.includes(false) ? false : values.every(value => value === true) ? true : undefined
|
|
119
|
+
return values.includes(true) ? true : values.every(value => value === false) ? false : undefined
|
|
120
|
+
}
|
|
121
|
+
if (entries.length === 1 && entries[0][0] === 'not') {
|
|
122
|
+
const value = constantPredicate(entries[0][1] as Predicate)
|
|
123
|
+
return value === undefined ? undefined : !value
|
|
124
|
+
}
|
|
125
|
+
if (entries.length === 1 && (entries[0][0] === 'exists' || entries[0][0] === 'notExists')) {
|
|
126
|
+
return constantQuantifier(entries[0][0] === 'notExists', constantPredicate(entries[0][1].predicate))
|
|
127
|
+
}
|
|
128
|
+
if (entries.some(([, operators]) => operators && Array.isArray(operators.in) && !operators.in.length)) return false
|
|
129
|
+
return undefined
|
|
130
|
+
}
|
|
131
|
+
/** A token's live role caps its issuer's live membership; it cannot outlive a role loss. */
|
|
132
|
+
export function rbacRoles(scope: Scope): string[] {
|
|
133
|
+
const principal = projections.get(scope)?.role
|
|
134
|
+
return principal && principal !== scope.role ? [scope.role, String(principal)] : [scope.role]
|
|
135
|
+
}
|
|
136
|
+
/** System audit access requires an owner credential and a live owner issuer. */
|
|
137
|
+
export function hasOwnerRole(scope: Scope): boolean {
|
|
138
|
+
return (scope.actor.type !== 'agent' || projections.has(scope)) && rbacRoles(scope).every(role => role === 'owner')
|
|
139
|
+
}
|
|
140
|
+
export function policyFilter(config: InstanceConfig, entity: string, scope: Scope): TableFilter {
|
|
141
|
+
const filters = rbacRoles(scope).map(role => rolePolicyFilter(config, entity, scope, role))
|
|
142
|
+
if (filters.some(filter => filter.kind === 'none')) return { kind: 'none', ...(filters.some(filter => 'deny' in filter && filter.deny === 'forbidden') ? { deny: 'forbidden' as const } : {}) }
|
|
143
|
+
const where = filters.filter((filter): filter is Extract<TableFilter, { kind: 'where' }> => filter.kind === 'where')
|
|
144
|
+
return where.length ? { kind: 'where', predicate: { all: where.map(filter => filter.predicate) }, ...(where.some(filter => filter.deny === 'forbidden') ? { deny: 'forbidden' as const } : {}) } : { kind: 'all' }
|
|
145
|
+
}
|
|
146
|
+
export function readableFields(config: InstanceConfig, entity: string, scope: Scope): string[] {
|
|
147
|
+
return [...baseFields, ...Object.keys(config.entities[entity].fields)].filter(field => rbacRoles(scope).every(role => {
|
|
148
|
+
const policy = config.policies[entity]?.[role]
|
|
149
|
+
const allow = typeof policy === 'object' ? policy.fields : undefined
|
|
150
|
+
// Stable cursors and relation assembly require id whenever a role grants fields.
|
|
151
|
+
return (!allow || allow.includes(field) || (field === 'id' && allow.length > 0)) && (!config.entities[entity].fields[field]?.sensitive || role === 'owner' || role === 'administrator' || !!allow?.includes(field))
|
|
152
|
+
}))
|
|
153
|
+
}
|
|
154
|
+
/** Declared account assignments only; this never grants membership-management authority. */
|
|
155
|
+
export function canManageAccountAssignments(config: InstanceConfig, scope: Scope, fields: string[]): boolean {
|
|
156
|
+
const actor = projections.get(scope)
|
|
157
|
+
return kernelFor(config).permissionsActive && scope.actor.type === 'user'
|
|
158
|
+
&& actor?.id === scope.actor.id && actor.organization_id === scope.organizationId && actor.role === scope.role
|
|
159
|
+
&& !!config.account?.managedBy?.includes(scope.role)
|
|
160
|
+
&& fields.every(field => config.account?.assignments?.includes(field))
|
|
161
|
+
}
|
|
162
|
+
export function assertActorFields(config: InstanceConfig, scope: Scope, entity: string, fields: string[], targetId?: string) {
|
|
163
|
+
if (scope.actor.type === 'service' || entity !== config.account?.entity) return
|
|
164
|
+
const assigned = fields.filter(field => protectedActorFields(config).has(field))
|
|
165
|
+
if (!assigned.length) return
|
|
166
|
+
// Account assignments only; authoritative membership changes retain the private owner path.
|
|
167
|
+
if (canManageAccountAssignments(config, scope, assigned) && targetId !== undefined && targetId !== actorAccountId(scope)) return
|
|
168
|
+
throw new ApiError(403, 'field_forbidden')
|
|
169
|
+
}
|
|
170
|
+
/** Private receipt identity; callers hash it, never serialize it into a surface. */
|
|
171
|
+
export function actorPolicyIdentity(config: InstanceConfig, scope: Scope) {
|
|
172
|
+
const actor = projections.get(scope)
|
|
173
|
+
return { principal: actorAccountId(scope), credential: scope.actor, role: scope.role, organization: scope.organizationId,
|
|
174
|
+
attributes: Object.fromEntries([...protectedActorFields(config)].map(field => [field, actor?.[field] ?? null])) }
|
|
175
|
+
}
|
|
176
|
+
/** Conservative entity-level write metadata; row ownership still gates each mutation. */
|
|
177
|
+
export function writableFields(config: InstanceConfig, entity: string, scope: Scope): string[] {
|
|
178
|
+
return Object.entries(config.entities[entity].fields).filter(([field, definition]) => !definition.readOnly &&
|
|
179
|
+
!(entity === config.account?.entity && protectedActorFields(config).has(field))).map(([field]) => field)
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Internal differential-test seam: uses the production compiler without actor substitution. */
|
|
183
|
+
export const policyFoldTest = {
|
|
184
|
+
compile: (config: InstanceConfig, entity: string, filter: Filter): Predicate => compilePolicyPredicate(config, entity, filter, value => value),
|
|
185
|
+
constantPredicate,
|
|
186
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
import { labelDependencies } from './query/labels'
|
|
3
|
+
import { fieldsFor, fieldType, operatorsFor } from './query/schema'
|
|
4
|
+
import { QUERY_LIMITS } from './query/limits'
|
|
5
|
+
import type { InstanceConfig } from './config'
|
|
6
|
+
import type { RuntimeOptions } from './types'
|
|
7
|
+
|
|
8
|
+
// These objects map user-defined names to schemas; their keys are not keywords.
|
|
9
|
+
const schemaMaps = new Set(['properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas'])
|
|
10
|
+
function sanitizeSchema(value: unknown, sensitive = false): unknown {
|
|
11
|
+
if (Array.isArray(value)) return value.map(item => sanitizeSchema(item, sensitive))
|
|
12
|
+
if (value === null || typeof value !== 'object') return value
|
|
13
|
+
const node = value as Record<string, unknown>
|
|
14
|
+
sensitive ||= node.sensitive === true
|
|
15
|
+
return Object.fromEntries(Object.entries(node).flatMap(([key, item]) => {
|
|
16
|
+
if (['default', 'examples', 'const'].includes(key) || (sensitive && key === 'description')) return []
|
|
17
|
+
return [[key, schemaMaps.has(key) && item && typeof item === 'object'
|
|
18
|
+
? Object.fromEntries(Object.entries(item).map(([name, schema]) => [name, sanitizeSchema(schema, sensitive)]))
|
|
19
|
+
: sanitizeSchema(item, sensitive)]]
|
|
20
|
+
}))
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Anonymous build metadata: explicit entity projection, sanitized input schemas. */
|
|
24
|
+
export function publicSchema(config: InstanceConfig, options: RuntimeOptions) {
|
|
25
|
+
return {
|
|
26
|
+
instance: config.id, revision: config.revision,
|
|
27
|
+
...(config.displayName ? { displayName: config.displayName } : {}),
|
|
28
|
+
...(config.ui ? { ui: config.ui } : {}),
|
|
29
|
+
entities: Object.fromEntries(Object.entries(config.entities).map(([name, entity]) => [name, {
|
|
30
|
+
...(entity.label ? { displayField: entity.displayField, labelDependencies: labelDependencies(config, name) } : {}),
|
|
31
|
+
fields: Object.fromEntries(Object.entries(entity.fields).map(([fieldName, field]) => [fieldName, {
|
|
32
|
+
type: field.type, required: field.required,
|
|
33
|
+
...(field.values === undefined ? {} : { values: field.values }),
|
|
34
|
+
...(field.entity === undefined ? {} : { entity: field.entity }),
|
|
35
|
+
...(field.readOnly === undefined ? {} : { readOnly: field.readOnly }),
|
|
36
|
+
...(field.sensitive === undefined ? {} : { sensitive: field.sensitive }),
|
|
37
|
+
...(field.ui === undefined ? {} : { ui: field.ui }),
|
|
38
|
+
}])),
|
|
39
|
+
}])),
|
|
40
|
+
query: {
|
|
41
|
+
format: 'filter-object', required: ['entity', 'limit'], combinators: ['and', 'or', 'not'],
|
|
42
|
+
limits: QUERY_LIMITS,
|
|
43
|
+
entities: Object.fromEntries(Object.entries(config.entities).map(([name, entity]) => [name, {
|
|
44
|
+
fields: Object.fromEntries(fieldsFor(config, name).map(field => [field, { type: fieldType(config, name, field), operators: operatorsFor(fieldType(config, name, field)) }])),
|
|
45
|
+
relations: Object.fromEntries(Object.entries(entity.relations).map(([key, relation]) => [key, {
|
|
46
|
+
entity: relation.entity, field: relation.field, cardinality: relation.many ? '1:n' : 'n:1',
|
|
47
|
+
...(relation.through ? { through: relation.through } : {}),
|
|
48
|
+
...(relation.many ? { quantifiers: ['some', 'none'] } : {}),
|
|
49
|
+
}])),
|
|
50
|
+
}])),
|
|
51
|
+
},
|
|
52
|
+
policies: Object.fromEntries(Object.entries(config.policies).map(([entity, roles]) => [entity, Object.fromEntries(Object.keys(roles).map(role => [role, true]))])),
|
|
53
|
+
capabilities: { path: '/o/:org/capabilities', authentication: 'required' },
|
|
54
|
+
roles: config.roles, permissions: config.permissions,
|
|
55
|
+
commands: config.commands.flatMap(name => {
|
|
56
|
+
const command = options.commands?.get(name)
|
|
57
|
+
return command && !('system' in command.permission) ? [{ name, permission: command.permission, ...(command.ui ? { ui: command.ui } : {}),
|
|
58
|
+
additionalPermissions: command.additionalPermissions ?? [], inputSchema: sanitizeSchema(z.toJSONSchema(command.input)) }] : []
|
|
59
|
+
}),
|
|
60
|
+
workflows: [...(options.workflows?.values() ?? [])].map(workflow => ({ name: workflow.name, version: workflow.version,
|
|
61
|
+
inputSchema: sanitizeSchema(z.toJSONSchema(workflow.input)),
|
|
62
|
+
permissions: workflow.steps?.map(step => ({ name: step.operation.name, permission: step.operation.permission })),
|
|
63
|
+
})),
|
|
64
|
+
}
|
|
65
|
+
}
|