@workbasehq/core 0.2.15 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +18 -3
- package/src/access-evaluator.ts +72 -0
- package/src/access-guards.ts +35 -0
- package/src/access-inputs.ts +62 -0
- package/src/access-lock/cli.ts +34 -0
- package/src/access-lock.ts +183 -0
- package/src/access.ts +209 -0
- package/src/account-action-conditions.ts +27 -0
- package/src/account-command.ts +8 -0
- package/src/admin-ui.tsx +3 -2
- package/src/app.ts +3 -3
- package/src/canonical.ts +6 -0
- package/src/capabilities.ts +5 -3
- package/src/commands.ts +14 -8
- package/src/config.ts +105 -69
- package/src/console-build.ts +37 -0
- package/src/console-contract.ts +4 -0
- package/src/console-model.ts +2 -0
- package/src/console.ts +3 -3
- package/src/crud.ts +13 -7
- package/src/dev-mailbox.ts +35 -0
- package/src/display-identity.ts +12 -0
- package/src/execution/atomic.ts +17 -3
- package/src/execution/policies.ts +14 -6
- package/src/execution/policy-receipts.ts +6 -5
- package/src/execution/post-commit.ts +11 -0
- package/src/execution/types.ts +1 -1
- package/src/index.ts +2 -0
- package/src/infra/README.md +39 -3
- package/src/infra/d1-migrations.ts +4 -3
- package/src/infra/instance-migrations.ts +26 -5
- package/src/infra/provision-config-main.mjs +3 -3
- package/src/infra/provision-diagnostics.ts +4 -0
- package/src/infra/provision-plan.ts +34 -5
- package/src/infra/provision.ts +26 -4
- package/src/infra/schema.ts +1 -1
- package/src/kernel/invitation-mail-port.ts +26 -0
- package/src/kernel/mail-outbox-port.ts +4 -2
- package/src/kernel/migrations.ts +38 -15
- package/src/kernel/plugin.ts +2 -0
- package/src/kernel/predicate.ts +15 -3
- package/src/kernel/registry.ts +69 -12
- package/src/member-bootstrap.ts +65 -0
- package/src/member-identities.ts +42 -0
- package/src/migrations/diagnostics.ts +6 -1
- package/src/migrations/model-b.ts +2 -1
- package/src/migrations/operational-evidence.ts +51 -0
- package/src/migrations/planner.ts +12 -1
- package/src/migrations/rebuild.ts +17 -12
- package/src/migrations/reset-era.ts +29 -0
- package/src/migrations/schema-bundle.ts +43 -0
- package/src/migrations/schema-cli.ts +74 -0
- package/src/migrations/schema-git.ts +36 -0
- package/src/migrations/schema-lock.ts +159 -0
- package/src/migrations/schema-plan.ts +94 -0
- package/src/migrations/schema.ts +73 -48
- package/src/migrations/sdk-baseline.ts +35 -0
- package/src/migrations/system-schema.ts +39 -0
- package/src/model-inputs.ts +25 -0
- package/src/openapi/cli.ts +72 -0
- package/src/openapi/generate.ts +166 -0
- package/src/openapi/input-projection.ts +131 -0
- package/src/openapi/public-paths.ts +80 -0
- package/src/openapi/routes.ts +29 -0
- package/src/ops.ts +4 -2
- package/src/organization-name.ts +35 -0
- package/src/organization-permissions.ts +10 -0
- package/src/organizations.ts +72 -3
- package/src/policies.ts +22 -6
- package/src/public-projection.ts +108 -0
- package/src/public-schema.ts +5 -43
- package/src/query/input-schema.ts +89 -0
- package/src/query/limits.ts +1 -1
- package/src/query/schema.ts +11 -89
- package/src/record-action-routes.ts +87 -0
- package/src/record-actions-data.ts +17 -0
- package/src/record-actions.ts +61 -0
- package/src/record-read.ts +20 -0
- package/src/row-access.ts +11 -0
- package/src/row-invitations.ts +29 -0
- package/src/schema/README.md +323 -0
- package/src/schema/declaration.ts +5 -0
- package/src/schema/load.ts +423 -0
- package/src/schema/lock-format.ts +117 -0
- package/src/schema/physical-names.ts +30 -0
- package/src/schema/revision.ts +16 -0
- package/src/schema/source-location.ts +3 -0
- package/src/schema-compatibility.ts +2 -2
- package/src/schema.ts +171 -0
- package/src/types.ts +1 -1
- package/src/user-link-eligibility.ts +36 -0
- package/src/user-links.ts +27 -16
- package/src/worker-access-actions.ts +89 -0
- package/src/worker-access.ts +61 -0
- package/src/workflow-runtime.ts +109 -22
- package/src/bootstrap.ts +0 -23
package/src/access.ts
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { accountActions, type AccountCondition } from './account-action-conditions'
|
|
2
|
+
import { workerAccessCommands } from './worker-access-actions'
|
|
3
|
+
import { accessGuards } from './access-guards'
|
|
4
|
+
import { userLinks } from './user-link-fields'
|
|
5
|
+
import { userLinkCommands } from './user-links'
|
|
6
|
+
import type { AtomicOperation } from './execution/types'
|
|
7
|
+
import { systemAccessTarget } from './access-evaluator'
|
|
8
|
+
import { z } from 'zod'
|
|
9
|
+
import { baseFields, organizationActions, reservedEntities, type InstanceConfig, type Operation } from './config'
|
|
10
|
+
import { DeclarationError } from './schema/declaration'
|
|
11
|
+
import { validatePolicies } from './policies'
|
|
12
|
+
import type { Filter } from './query/schema'
|
|
13
|
+
|
|
14
|
+
export const accessOperations = ['read', 'create', 'update', 'delete'] as const
|
|
15
|
+
export const accessEntities = [...reservedEntities, 'atomic_assert', 'workflow_runs', 'workflow_steps', 'workflow_holds', '_ops_relay_run', '_migrations', 'identity_profiles', 'organization_scopes'].sort()
|
|
16
|
+
export const accessSystemActions = [...organizationActions, 'audit.read', 'workflows.read', 'workflows.resume', 'workflows.cancel',
|
|
17
|
+
'organizations.create', 'members.leave', 'invitations.accept'].sort()
|
|
18
|
+
const decision = z.enum(['allow', 'none', 'deny'])
|
|
19
|
+
const grant = z.union([decision, z.strictObject({ where: z.record(z.string(), z.unknown()), fields: z.array(z.string()).optional() })])
|
|
20
|
+
export const entityAccessSchema = z.record(z.string(), z.union([z.literal('deny'), z.literal('none'), z.strictObject({
|
|
21
|
+
read: grant, create: grant, update: grant, delete: grant,
|
|
22
|
+
})]))
|
|
23
|
+
const sharedSchema = z.strictObject({
|
|
24
|
+
roles: z.record(z.string(), z.strictObject({ system: z.record(z.string(), decision) })),
|
|
25
|
+
entities: z.record(z.string(), entityAccessSchema),
|
|
26
|
+
predicates: z.record(z.string(), z.record(z.string(), z.unknown())),
|
|
27
|
+
accountLinks: z.record(z.string(), z.strictObject({ invitationRole: z.string() })).optional(),
|
|
28
|
+
})
|
|
29
|
+
export type EntityAccess = z.input<typeof entityAccessSchema>
|
|
30
|
+
export type AccessInput = z.input<typeof sharedSchema>
|
|
31
|
+
export function defineAccess(input: AccessInput): AccessInput {
|
|
32
|
+
const result = sharedSchema.safeParse(input)
|
|
33
|
+
if (!result.success) {
|
|
34
|
+
const issue = result.error.issues[0]
|
|
35
|
+
throw new DeclarationError(issue.path.map(String), issue.message)
|
|
36
|
+
}
|
|
37
|
+
return result.data
|
|
38
|
+
}
|
|
39
|
+
export interface EffectiveEntityPolicy {
|
|
40
|
+
entity: string
|
|
41
|
+
role: string
|
|
42
|
+
operation: Operation
|
|
43
|
+
decision: 'allow' | 'none' | 'deny'
|
|
44
|
+
where: Filter
|
|
45
|
+
/** Read projection; null for mutations and SDK resources without a schema. */
|
|
46
|
+
fields: string[] | null
|
|
47
|
+
predicates: string[]
|
|
48
|
+
dependencies: string[]
|
|
49
|
+
/** Stable source-map key; loadConfig returns its file:line location separately. */
|
|
50
|
+
source: string
|
|
51
|
+
}
|
|
52
|
+
/** Normalized grants shared by execution and audit; other runtime/config inputs
|
|
53
|
+
* are audited separately as enforcementInputs. Execution consumes these exact rules.
|
|
54
|
+
* Arrays and object keys are canonical; no functions, implicit grants or host paths.
|
|
55
|
+
*/
|
|
56
|
+
export interface EffectiveRecordAction {
|
|
57
|
+
entity: string; name: string; command: string
|
|
58
|
+
conditions: ({ when: Filter; reason: string } | AccountCondition)[]
|
|
59
|
+
dependencies: string[]
|
|
60
|
+
source: string
|
|
61
|
+
}
|
|
62
|
+
export interface EffectiveAccessPolicy {
|
|
63
|
+
version: 1
|
|
64
|
+
roles: string[]
|
|
65
|
+
accountLinks?: Record<string, { invitationRole: string }>
|
|
66
|
+
actions: EffectiveRecordAction[]
|
|
67
|
+
entities: EffectiveEntityPolicy[]
|
|
68
|
+
guards: { name: string; permission: AtomicOperation['permission'] | null; additionalPermissions: AtomicOperation['permission'][]; opaque: true }[]
|
|
69
|
+
opaqueHooks: string[]
|
|
70
|
+
system: { role: string; action: string; decision: 'allow' | 'none' | 'deny'; target: { entity: string; operation: Operation }; source: string }[]
|
|
71
|
+
}
|
|
72
|
+
const sorted = (values: Iterable<string>) => [...new Set(values)].sort()
|
|
73
|
+
function canonical(value: unknown): any {
|
|
74
|
+
return Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object'
|
|
75
|
+
? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, child]) => [key, canonical(child)])) : value
|
|
76
|
+
}
|
|
77
|
+
export const ACCESS_EXPANSION_LIMITS = { depth: 16, size: 512 } as const
|
|
78
|
+
export function compileAccess(config: InstanceConfig, declarations: Record<string, EntityAccess | undefined>, input: AccessInput): EffectiveAccessPolicy {
|
|
79
|
+
const roles = sorted(config.roles)
|
|
80
|
+
const error = (source: string, message: string): never => { throw new DeclarationError(source.split('.'), message) }
|
|
81
|
+
const known = sorted([...accessEntities, ...Object.keys(config.entities)])
|
|
82
|
+
for (const role of Object.keys(input.roles)) if (!roles.includes(role)) error(`access.roles.${role}`, `Unknown access role: ${role}`)
|
|
83
|
+
for (const entity of Object.keys(input.entities)) if (!accessEntities.includes(entity)) error(`access.entities.${entity}`, `Entity ${entity} must declare access in schema/${entity}.ts`)
|
|
84
|
+
const result: EffectiveAccessPolicy = { version: 1, roles, actions: [], entities: [], system: [], guards: [], opaqueHooks: [] }
|
|
85
|
+
function expand(value: unknown, source: string, names: Set<string>, stack: string[] = [], depth = 0, budget = { size: 0 }): any {
|
|
86
|
+
if (depth > ACCESS_EXPANSION_LIMITS.depth || ++budget.size > ACCESS_EXPANSION_LIMITS.size) error(source, 'Predicate expansion exceeds depth/size budget')
|
|
87
|
+
if (value && typeof value === 'object' && !Array.isArray(value) && Object.hasOwn(value, 'use')) {
|
|
88
|
+
const name = (value as { use: unknown }).use
|
|
89
|
+
if (typeof name !== 'string' || !Object.hasOwn(input.predicates, name)) error(source, `Unknown predicate: ${String(name)}`)
|
|
90
|
+
if (Object.keys(value).length !== 1) error(source, 'A predicate use must be its own literal object')
|
|
91
|
+
if (stack.includes(name as string)) error(`access.predicates.${name}`, `Predicate cycle: ${[...stack, name].join(' -> ')}`)
|
|
92
|
+
names.add(name as string)
|
|
93
|
+
return expand(input.predicates[name as string], `access.predicates.${name}`, names, [...stack, name as string], depth + 1, budget)
|
|
94
|
+
}
|
|
95
|
+
if (Array.isArray(value)) return value.map(child => expand(child, source, names, stack, depth + 1, budget))
|
|
96
|
+
return value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).map(([key, child]) => [key, expand(child, source, names, stack, depth + 1, budget)])) : value
|
|
97
|
+
}
|
|
98
|
+
// Unused named predicates are still authored data, so unknown names/cycles/size fail.
|
|
99
|
+
for (const name of sorted(Object.keys(input.predicates))) expand({ use: name }, `access.predicates.${name}`, new Set())
|
|
100
|
+
for (const entity of known) {
|
|
101
|
+
const system = accessEntities.includes(entity)
|
|
102
|
+
const source = system ? `access.entities.${entity}` : `entities.${entity}.access`
|
|
103
|
+
const matrix = system ? input.entities[entity] : declarations[entity]
|
|
104
|
+
for (const role of Object.keys(matrix ?? {})) if (!roles.includes(role)) error(`${source}.${role}`, `Unknown access role: ${role}`)
|
|
105
|
+
for (const role of roles) {
|
|
106
|
+
if (!matrix || !Object.hasOwn(matrix, role)) error(source, `Missing access entry for role ${role}, entity ${entity}`)
|
|
107
|
+
for (const operation of accessOperations) {
|
|
108
|
+
const entry = matrix![role]
|
|
109
|
+
const authored = typeof entry === 'string' ? entry : entry[operation]
|
|
110
|
+
if (operation !== 'read' && typeof authored === 'object' && authored.fields) error(`${source}.${role}.${operation}`, 'Field masks must be declared on read')
|
|
111
|
+
const names = new Set<string>()
|
|
112
|
+
const path = `${source}.${role}${typeof entry === 'string' ? '' : `.${operation}`}`
|
|
113
|
+
const where = typeof authored === 'object' ? expand(authored.where, path, names) : {}
|
|
114
|
+
const fields = config.entities[entity] ? [...baseFields, ...Object.keys(config.entities[entity].fields).filter(field => !config.entities[entity].fields[field].sensitive)] : [...baseFields]
|
|
115
|
+
const mask = sorted(typeof authored === 'object' && authored.fields ? authored.fields : fields)
|
|
116
|
+
if (mask.length && !mask.includes('id')) mask.push('id')
|
|
117
|
+
const rule: EffectiveEntityPolicy = { entity, role, operation, decision: typeof authored === 'string' ? authored : 'allow',
|
|
118
|
+
where: canonical(where), fields: operation !== 'read' || !config.entities[entity] ? null : typeof authored === 'string' && authored !== 'allow' ? [] : sorted(mask), predicates: sorted(names), dependencies: [], source: path }
|
|
119
|
+
if (config.entities[entity] && rule.decision === 'allow') {
|
|
120
|
+
try { validatePolicies({ ...config, effectiveAccess: undefined, policies: { [entity]: { [role]: { where, fields: rule.fields ?? undefined } } } }) }
|
|
121
|
+
catch (cause) { error(path, cause instanceof Error ? cause.message : String(cause)) }
|
|
122
|
+
} else if (Object.keys(where).length || typeof authored === 'object' && authored.fields) error(path, `Row predicates and masks require a schema entity: ${entity}`)
|
|
123
|
+
function dependencies(name: string, filter: Filter) {
|
|
124
|
+
for (const [key, value] of Object.entries(filter)) {
|
|
125
|
+
if (key === 'actorLinkedIn') rule.dependencies.push(value as string)
|
|
126
|
+
else if (key === 'and' || key === 'or') (value as Filter[]).forEach(child => dependencies(name, child))
|
|
127
|
+
else if (key === 'not') dependencies(name, value as Filter)
|
|
128
|
+
else {
|
|
129
|
+
const relation = config.entities[name]?.relations[key]
|
|
130
|
+
if (relation) { rule.dependencies.push(relation.entity); dependencies(relation.entity, (relation.many ? Object.values(value as object)[0] : value) as Filter) }
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
dependencies(entity, where)
|
|
135
|
+
rule.dependencies = sorted(rule.dependencies)
|
|
136
|
+
result.entities.push(rule)
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
// Dependencies of a relation include its target's effective policy for the same operation.
|
|
141
|
+
for (const operation of accessOperations) {
|
|
142
|
+
const graph = new Map(known.map(entity => [entity, sorted(result.entities.filter(rule => rule.entity === entity && rule.operation === operation).flatMap(rule => rule.dependencies))]))
|
|
143
|
+
const done = new Set<string>()
|
|
144
|
+
function visit(entity: string, stack: string[], owner?: EffectiveEntityPolicy) {
|
|
145
|
+
if (stack.includes(entity)) error(owner!.source, `Relation policy cycle: ${[...stack, entity].join(' -> ')}`)
|
|
146
|
+
if (done.has(entity)) return
|
|
147
|
+
for (const target of graph.get(entity) ?? []) visit(target, [...stack, entity], owner ?? result.entities.find(rule => rule.entity === entity && rule.operation === operation && rule.dependencies.includes(target)))
|
|
148
|
+
done.add(entity)
|
|
149
|
+
}
|
|
150
|
+
for (const entity of known) visit(entity, [])
|
|
151
|
+
}
|
|
152
|
+
for (const role of roles) {
|
|
153
|
+
const system = input.roles[role]?.system
|
|
154
|
+
if (!system) error(`access.roles`, `Missing system grants for role ${role}`)
|
|
155
|
+
for (const action of Object.keys(system!)) if (!accessSystemActions.includes(action)) error(`access.roles.${role}.system.${action}`, `Unknown system action: ${action}`)
|
|
156
|
+
for (const action of accessSystemActions) {
|
|
157
|
+
const source = `access.roles.${role}.system.${action}`
|
|
158
|
+
if (!Object.hasOwn(system!, action)) error(`access.roles.${role}.system`, `Missing explicit system action ${action} for role ${role}`)
|
|
159
|
+
result.system.push({ role, action, decision: system![action], target: systemAccessTarget(action), source })
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
for (const entity of Object.keys(config.entities).sort()) for (const name of Object.keys(config.entities[entity].actions ?? {}).sort()) {
|
|
163
|
+
const action = config.entities[entity].actions![name]
|
|
164
|
+
const source = `entities.${entity}.actions.${name}`
|
|
165
|
+
const dependencies = new Set<string>()
|
|
166
|
+
function fields(target: string, filter: Filter) {
|
|
167
|
+
for (const [key, value] of Object.entries(filter)) {
|
|
168
|
+
if (key === 'and' || key === 'or') (value as Filter[]).forEach(child => fields(target, child))
|
|
169
|
+
else if (key === 'not') fields(target, value as Filter)
|
|
170
|
+
else if (key === 'actorLinkedIn') dependencies.add(`${value}.user`)
|
|
171
|
+
else {
|
|
172
|
+
const relation = config.entities[target].relations[key]
|
|
173
|
+
if (relation) {
|
|
174
|
+
dependencies.add(`${target}.${relation.many ? 'id' : relation.field}`)
|
|
175
|
+
dependencies.add(`${relation.entity}.${relation.many ? relation.field : 'id'}`)
|
|
176
|
+
fields(relation.entity, (relation.many ? Object.values(value as object)[0] : value) as Filter)
|
|
177
|
+
} else dependencies.add(`${target}.${key}`)
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
const conditions = (action.available ?? []).map((condition, i) => {
|
|
182
|
+
const path = `${source}.available.${i}.when`
|
|
183
|
+
const when = canonical(expand(condition.when, path, new Set()))
|
|
184
|
+
try { validatePolicies({ ...config, effectiveAccess: undefined, policies: { [entity]: { [roles[0]]: { where: when } } } }) }
|
|
185
|
+
catch (cause) { error(path, cause instanceof Error ? cause.message : String(cause)) }
|
|
186
|
+
fields(entity, when)
|
|
187
|
+
return { when, reason: condition.reason }
|
|
188
|
+
})
|
|
189
|
+
result.actions.push({ entity, name, command: action.command, conditions, dependencies: sorted(dependencies), source })
|
|
190
|
+
}
|
|
191
|
+
for (const [entity, mapping] of Object.entries(input.accountLinks ?? {}).sort(([a], [b]) => a.localeCompare(b))) {
|
|
192
|
+
const source = `access.accountLinks.${entity}.invitationRole`
|
|
193
|
+
if (!userLinks(config).some(link => link.entity === entity)) error(source, `Account link required: ${entity}`)
|
|
194
|
+
if (!roles.includes(mapping.invitationRole)) error(source, `Unknown invitation role: ${mapping.invitationRole}`)
|
|
195
|
+
if (mapping.invitationRole === config.organizationOwnerRole) error(source, 'Invitation role cannot be organizationOwnerRole')
|
|
196
|
+
if (!result.entities.some(rule => rule.entity === entity && rule.role === mapping.invitationRole && rule.operation === 'read' && rule.decision === 'allow')) error(source, `Invitation role requires read on ${entity}`)
|
|
197
|
+
;(result.accountLinks ??= {})[entity] = { ...mapping }
|
|
198
|
+
}
|
|
199
|
+
const reservedCommands = Object.keys(result.accountLinks ?? {}).flatMap(entity => accountActions(entity).map(action => action.command))
|
|
200
|
+
for (const action of result.actions) if (reservedCommands.includes(action.command)) error(action.source, 'Account commands require their core registered action')
|
|
201
|
+
for (const entity of Object.keys(result.accountLinks ?? {})) {
|
|
202
|
+
for (const action of accountActions(entity)) {
|
|
203
|
+
if (result.actions.some(existing => existing.entity === entity && existing.name === action.name)) error(action.source, `Reserved account action: ${action.name}`)
|
|
204
|
+
result.actions.push(action)
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
const builtins = workerAccessCommands({ ...config, effectiveAccess: result })
|
|
208
|
+
return accessGuards(result, [...config.commands, ...builtins.map(command => command.name)], [...(config.plugins ?? []).flatMap(plugin => [...(plugin.commands ?? [])]), ...userLinkCommands(config), ...builtins], config.plugins ?? [])
|
|
209
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { EffectiveRecordAction } from './access'
|
|
2
|
+
import type { InstanceConfig } from './config'
|
|
3
|
+
import { quote } from './migrations/schema'
|
|
4
|
+
import { userLinks } from './user-link-fields'
|
|
5
|
+
|
|
6
|
+
export type AccountCondition = { opaque: true; kind: 'unlinked' | 'linked' | 'pending' | 'clear'; reason: string }
|
|
7
|
+
export { accountActionNames, accountCommand } from './account-command'
|
|
8
|
+
import { accountActionNames, accountCommand } from './account-command'
|
|
9
|
+
/** Compiler-only macros; authored conditions remain strict {when, reason} data. */
|
|
10
|
+
export function accountActions(entity: string): EffectiveRecordAction[] {
|
|
11
|
+
const unlinked: AccountCondition = { opaque: true, kind: 'unlinked', reason: 'access.already_linked' }
|
|
12
|
+
return accountActionNames.map(name => ({ entity, name, command: accountCommand(entity, name),
|
|
13
|
+
conditions: name === 'invite' ? [unlinked, { opaque: true, kind: 'clear', reason: 'access.invitation_pending' }]
|
|
14
|
+
: name === 'cancel_invite' ? [{ opaque: true, kind: 'pending', reason: 'access.no_invitation' }]
|
|
15
|
+
: name === 'link_account' ? [unlinked] : [{ opaque: true, kind: 'linked', reason: 'access.not_linked' }],
|
|
16
|
+
dependencies: [`${entity}.user`], source: `access.accountLinks.${entity}`,
|
|
17
|
+
}))
|
|
18
|
+
}
|
|
19
|
+
export function accountConditionSql(config: InstanceConfig, entity: string, condition: AccountCondition) {
|
|
20
|
+
const link = userLinks(config).find(link => link.entity === entity)
|
|
21
|
+
if (!link || !config.effectiveAccess?.accountLinks?.[entity]) throw new Error('Unregistered account condition')
|
|
22
|
+
const field = `${quote(entity)}.${quote(link.field)}`
|
|
23
|
+
if (condition.kind === 'unlinked') return { sql: `${field} IS NULL`, bindings: [] }
|
|
24
|
+
if (condition.kind === 'linked') return { sql: `${field} IS NOT NULL`, bindings: [] }
|
|
25
|
+
const pending = `EXISTS (SELECT 1 FROM invitations card_invitation WHERE card_invitation.organization_id=${quote(entity)}.organization_id AND card_invitation.target_entity=? AND card_invitation.target_row=${quote(entity)}.id AND card_invitation.accepted_at IS NULL AND card_invitation.revoked_at IS NULL AND card_invitation.declined_at IS NULL AND card_invitation.expired_at IS NULL AND card_invitation.expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now'))`
|
|
26
|
+
return { sql: condition.kind === 'clear' ? `NOT ${pending}` : `(${field} IS NULL AND ${pending})`, bindings: [entity] }
|
|
27
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { InstanceConfig } from './config'
|
|
2
|
+
|
|
3
|
+
// Data-only names shared by build-time projection and runtime command adapters.
|
|
4
|
+
export const accountActionNames = ['invite', 'cancel_invite', 'link_account', 'unlink_account'] as const
|
|
5
|
+
export const accountCommand = (entity: string, action: string) => `${entity}/access_${action}`
|
|
6
|
+
export function isAccountAccessCommand(config: InstanceConfig, name: string) {
|
|
7
|
+
return Object.keys(config.effectiveAccess?.accountLinks ?? {}).some(entity => accountActionNames.some(action => name === accountCommand(entity, action)))
|
|
8
|
+
}
|
package/src/admin-ui.tsx
CHANGED
|
@@ -11,6 +11,7 @@ import { type InstanceConfig, type OrganizationAction } from './config'
|
|
|
11
11
|
import type { App, AppContext, RuntimeEnv, Scope } from './types'
|
|
12
12
|
import type { CommandRegistry, CommandDefinition } from './commands'
|
|
13
13
|
import { ApiError } from './errors'
|
|
14
|
+
import { organizationNameApiSchema } from './organization-name'
|
|
14
15
|
import { assertIdentityTransport } from './identity-settings'
|
|
15
16
|
import { adminForm, browserRequest, csrfToken, isLoopbackDev, submissionKey, verifySubmissionKey } from './admin-security'
|
|
16
17
|
import { CommandInput, FieldInput, Form, Hidden, commandBody, commandFields, entityBody } from './admin-forms'
|
|
@@ -150,10 +151,10 @@ export function adminRoutes(app: App, config: InstanceConfig, env: RuntimeEnv, c
|
|
|
150
151
|
const csrf = await csrfToken(c, secret)
|
|
151
152
|
if (c.req.path === '/admin' || c.req.path === '/admin/') {
|
|
152
153
|
const organizationsForm = async (error?: ApiError) => page(c, 'Organizations', <><ul>{actor.organizations.map(org => <li><a href={`/admin/o/${enc(org.id)}`}>{org.name}</a> ({org.role})</li>)}</ul>
|
|
153
|
-
<h2>Create organization</h2>{error ? errorMessage(error) : null}<Form action="/admin" csrf={csrf} label="Create organization"><label>Name<input name="name" required
|
|
154
|
+
<h2>Create organization</h2>{error && error.code !== 'invalid_organization_name' ? errorMessage(error) : null}<Form action="/admin" csrf={csrf} label="Create organization"><label>Name<input name="name" required value={form?.get('name') ?? ''} aria-invalid={error?.code === 'invalid_organization_name' ? 'true' : undefined} aria-describedby={error?.code === 'invalid_organization_name' ? 'name-error' : undefined} /></label>{error?.code === 'invalid_organization_name' ? <p id="name-error" class="error" role="alert">Invalid organization name: {String(error.detail?.reason)}.</p> : null}</Form></>, csrf, undefined, error?.status)
|
|
154
155
|
onError(organizationsForm)
|
|
155
156
|
if (form) {
|
|
156
|
-
const org = await api(c, '/orgs', undefined, 'POST', { name: form.get('name') })
|
|
157
|
+
const org = await api(c, '/orgs', undefined, 'POST', { name: organizationNameApiSchema.parse(form.get('name') ?? undefined) })
|
|
157
158
|
return c.redirect(`/admin/o/${enc(org.id)}`, 303)
|
|
158
159
|
}
|
|
159
160
|
return organizationsForm()
|
package/src/app.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { eventDeliveryContext } from './event-delivery'
|
|
2
|
-
import { bootstrapRoutes } from './bootstrap'
|
|
3
2
|
import { capabilityRoutes } from './capabilities'
|
|
4
3
|
import { consoleModelRoutes } from './console-model'
|
|
5
4
|
import { queryRoutes } from './query/routes'
|
|
6
5
|
import { QueryError } from './query/errors'
|
|
7
6
|
import { validatedBrowserDispatch } from './browser-dispatch'
|
|
8
7
|
import { consoleRoutes } from './console'
|
|
8
|
+
import { openApiRoutes } from './openapi/routes'
|
|
9
9
|
import { jsonCookieCSRF } from './json-csrf'
|
|
10
10
|
import { KernelRegistry } from './kernel/registry'
|
|
11
11
|
import { workflowRoutes } from './workflow-routes'
|
|
@@ -81,7 +81,7 @@ function buildApp(input: InstanceInput, env: RuntimeEnv, options: RuntimeOptions
|
|
|
81
81
|
}])
|
|
82
82
|
else await securityLog(env.DB, { ...c.get('scope'), correlationId: c.get('correlationId') }, `${c.req.method} ${routePath(c, -1)}`, status)
|
|
83
83
|
}
|
|
84
|
-
return c.json({ error: known ? error.code : status === 400 ? 'validation_error' : constraint ? 'constraint_conflict' : 'internal_error', ...(error instanceof QueryError ? { path: error.path, ...(error.cost ? { cost: error.cost } : {}) } : {}), ...(known && error.hint ? { hint: error.hint } : {}), ...(known && error.detail ? { detail: error.detail } : {}), ...(error instanceof RuleFailed && error.code === 'rule_failed' ? { rule: error.rule, diagnosis: error.diagnosis } : {}) }, status as any)
|
|
84
|
+
return c.json({ error: known ? error.code : status === 400 ? 'validation_error' : constraint ? 'constraint_conflict' : 'internal_error', ...(error instanceof ZodError && c.req.path.startsWith('/api/') ? { issues: error.issues.map(({ path, code }) => ({ path, code })) } : {}), ...(error instanceof QueryError ? { path: error.path, ...(error.cost ? { cost: error.cost } : {}) } : {}), ...(known && error.hint ? { hint: error.hint } : {}), ...(known && error.detail ? { detail: error.detail } : {}), ...(error instanceof RuleFailed && error.code === 'rule_failed' ? { rule: error.rule, diagnosis: error.diagnosis } : {}) }, status as any)
|
|
85
85
|
})
|
|
86
86
|
app.get('/health', async c => {
|
|
87
87
|
const schema = await schemaStatus(env, config)
|
|
@@ -90,6 +90,7 @@ function buildApp(input: InstanceInput, env: RuntimeEnv, options: RuntimeOptions
|
|
|
90
90
|
// Public build metadata only: never include runtime bindings, credentials or records.
|
|
91
91
|
app.get('/console-info', c => c.json({ instance: config.id, displayName: config.displayName, roles: config.roles, locale: config.locale, ui: { defaultLanguage: config.ui?.defaultLanguage } }))
|
|
92
92
|
app.get('/schema', c => c.json(publicSchema(config, options)))
|
|
93
|
+
openApiRoutes(app, config)
|
|
93
94
|
consoleRoutes(app, config, env)
|
|
94
95
|
for (const path of ['/api/*', '/commands/*', '/workflows/*', '/query', '/orgs', '/orgs/*', '/organizations/*', '/me/profile', '/invitations/*']) app.use(path, jsonCookieCSRF(env))
|
|
95
96
|
adminRoutes(validatedBrowserDispatch(app, env), config, env, options.commands, options.workflows)
|
|
@@ -107,7 +108,6 @@ function buildApp(input: InstanceInput, env: RuntimeEnv, options: RuntimeOptions
|
|
|
107
108
|
workflowRoutes(app, config, env, options.workflows ?? new Map())
|
|
108
109
|
kernel.mount(app, env)
|
|
109
110
|
options.extend?.(app, config, env)
|
|
110
|
-
bootstrapRoutes(app, kernel, env, options)
|
|
111
111
|
capabilityRoutes(app, kernel, env)
|
|
112
112
|
consoleModelRoutes(app, kernel, env)
|
|
113
113
|
queryRoutes(app, kernel, env)
|
package/src/canonical.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export function canonical(value: unknown): unknown {
|
|
2
|
+
if (Array.isArray(value)) return value.map(canonical)
|
|
3
|
+
if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value)
|
|
4
|
+
.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, child]) => [key, canonical(child)]))
|
|
5
|
+
return value
|
|
6
|
+
}
|
package/src/capabilities.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { ApiError } from './errors'
|
|
|
5
5
|
import { writableFields } from './policies'
|
|
6
6
|
import { hasOwnerRole } from './policies'
|
|
7
7
|
import { organizationPermission } from './execution/permissions'
|
|
8
|
+
import { isOrganizationAdministrator } from './organization-permissions'
|
|
8
9
|
|
|
9
10
|
/** Projection of the live authorization ports; never serialize their predicates. */
|
|
10
11
|
export function capabilities(kernel: KernelRegistry, scope: Scope) {
|
|
@@ -13,7 +14,7 @@ export function capabilities(kernel: KernelRegistry, scope: Scope) {
|
|
|
13
14
|
}
|
|
14
15
|
const entities = Object.fromEntries(Object.entries(kernel.config.entities).map(([name, entity]) => [name, {
|
|
15
16
|
readable: kernel.fieldMask(name, scope), writable: writableFields(kernel.config, name, scope),
|
|
16
|
-
operations: (['read', 'create', 'update', 'delete'] as const).filter(operation => (operation === 'read' || !entity.commandsOnly) && kernel.tableFilter(name, scope).kind !== 'none' && kernel.can(scope, name, operation)),
|
|
17
|
+
operations: (['read', 'create', 'update', 'delete'] as const).filter(operation => (operation === 'read' || !entity.commandsOnly) && kernel.tableFilter(name, scope, operation).kind !== 'none' && kernel.can(scope, name, operation)),
|
|
17
18
|
...(entity.displayField && kernel.fieldMask(name, scope).includes(entity.displayField) ? { displayField: entity.displayField } : {}),
|
|
18
19
|
}]))
|
|
19
20
|
const commands = [...kernel.commands.values()].filter(command => kernel.config.commands.includes(command.name) && !('system' in command.permission) && permits(() => kernel.atomicPermission(scope, command))).map(command => command.name)
|
|
@@ -24,6 +25,7 @@ export function capabilities(kernel: KernelRegistry, scope: Scope) {
|
|
|
24
25
|
// Match the read routes' complete gates, including their identity/owner checks.
|
|
25
26
|
// Navigation needs grants, not whole member/token/workflow/audit collections.
|
|
26
27
|
const resources = {
|
|
28
|
+
'members.search_link_account': isOrganizationAdministrator(kernel.config, scope.role) && permits(() => { kernel.resourcePermission(scope, 'members.read'); organizationPermission(kernel.config, scope, 'members.read') }),
|
|
27
29
|
'organizations.update': kernel.providers.has('organizations') && kernel.permissionsActive && permits(() => kernel.resourcePermission(scope, 'organizations.update')),
|
|
28
30
|
...Object.fromEntries((['members.read', 'members.update', 'members.remove', 'invitations.read', 'invitations.create', 'invitations.revoke', 'tokens.read'] as const).map(action => [action,
|
|
29
31
|
permits(() => { kernel.resourcePermission(scope, action); organizationPermission(kernel.config, scope, action) }),
|
|
@@ -32,10 +34,10 @@ export function capabilities(kernel: KernelRegistry, scope: Scope) {
|
|
|
32
34
|
permits(() => { kernel.resourcePermission(scope, action); organizationPermission(kernel.config, scope, action) }),
|
|
33
35
|
])),
|
|
34
36
|
'workflows.read': permits(() => kernel.resourcePermission(scope, 'workflows.read')),
|
|
35
|
-
'audit.read': !!kernel.audit && hasOwnerRole(scope) && permits(() => kernel.resourcePermission(scope, 'audit.read')),
|
|
37
|
+
'audit.read': !!kernel.audit && hasOwnerRole(scope, kernel.config) && permits(() => kernel.resourcePermission(scope, 'audit.read')),
|
|
36
38
|
}
|
|
37
39
|
return { revision: kernel.config.revision, entities, commands, workflows, resources, organization: { role: scope.role } }
|
|
38
40
|
}
|
|
39
41
|
export function capabilityRoutes(app: App, kernel: KernelRegistry, env: RuntimeEnv) {
|
|
40
|
-
app.get('/o/:org/capabilities', scopeMiddleware(env, kernel.config, kernel), c => c.json(capabilities(kernel, c.get('scope'))))
|
|
42
|
+
app.get('/o/:org/capabilities', scopeMiddleware(env, kernel.config, kernel), c => { c.header('Cache-Control', 'no-store'); return c.json(capabilities(kernel, c.get('scope'))) })
|
|
41
43
|
}
|
package/src/commands.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isAccountAccessCommand } from './account-command'
|
|
1
2
|
import { z } from 'zod'
|
|
2
3
|
import type { InstanceConfig } from './config'
|
|
3
4
|
import type { App, RuntimeEnv, Scope } from './types'
|
|
@@ -23,17 +24,22 @@ export function createCommandRegistry(definitions: readonly CommandDefinition<an
|
|
|
23
24
|
}
|
|
24
25
|
return registry
|
|
25
26
|
}
|
|
27
|
+
/** Shared entity-grant preflight. Atomic authorization follows with the actual input. */
|
|
28
|
+
export function commandPreflight(config: InstanceConfig, scope: Scope, operation: CommandDefinition) {
|
|
29
|
+
if (!config.commands.includes(operation.name) || 'system' in operation.permission) throw new ApiError(405, 'unsupported_command')
|
|
30
|
+
const kernel = kernelFor(config)
|
|
31
|
+
for (const grant of [operation.permission, ...(operation.additionalPermissions ?? [])]) {
|
|
32
|
+
kernel.commandGuard({ name: operationName(operation), kind: 'entity', permission: grant }, scope, undefined)
|
|
33
|
+
}
|
|
34
|
+
userLinkActionPermission(config, scope, operation)
|
|
35
|
+
}
|
|
26
36
|
/** Internal/trusted adapter compatibility. Never accept this context from request JSON. */
|
|
27
37
|
export async function executeCommand(ctx: CommandContext, name: string, input: unknown): Promise<AtomicResult> {
|
|
38
|
+
// Card adapters require the record dispatcher's bound atomic guard.
|
|
39
|
+
if (isAccountAccessCommand(ctx.config, name)) throw new ApiError(405, 'unsupported_command')
|
|
28
40
|
const operation = ctx.commands.get(name)
|
|
29
|
-
if (!
|
|
30
|
-
|
|
31
|
-
// Entity grants preflight the named command; the token must allow that actual command,
|
|
32
|
-
// independently of any operation previously checked by requireScope.
|
|
33
|
-
for (const grant of [operation.permission, ...(operation.additionalPermissions ?? [])]) {
|
|
34
|
-
kernelFor(ctx.config).commandGuard({ name: operationName(operation), kind: 'entity', permission: grant }, ctx.scope, undefined)
|
|
35
|
-
}
|
|
36
|
-
userLinkActionPermission(ctx.config, ctx.scope, operation)
|
|
41
|
+
if (!operation) throw new ApiError(405, 'unsupported_command')
|
|
42
|
+
commandPreflight(ctx.config, ctx.scope, operation)
|
|
37
43
|
const raw = z.record(z.string(), z.unknown()).parse(typeof input === 'function' ? await input() : input)
|
|
38
44
|
const { idempotencyKey, ...payload } = raw
|
|
39
45
|
const key = z.string().min(1).max(128).optional().parse(idempotencyKey)
|