@workbasehq/core 0.1.0 → 0.2.1
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 +27 -2
- package/src/app.ts +5 -2
- package/src/config.ts +1 -1
- package/src/console-authorization.ts +85 -0
- package/src/console-contract.ts +74 -1
- package/src/console-input-schema.ts +135 -0
- package/src/console-model.ts +122 -0
- package/src/console-presentation.ts +136 -0
- package/src/console.ts +2 -2
- package/src/execution/types.ts +1 -1
- package/src/index.ts +1 -1
- package/src/infra/README.md +206 -0
- package/src/infra/bin.mjs +19 -0
- package/src/infra/cli-main.ts +8 -0
- package/src/infra/cli.ts +43 -0
- package/src/infra/d1-migrations.ts +30 -0
- package/src/infra/diagnostics.ts +52 -0
- package/src/infra/http-d1.ts +17 -0
- package/src/infra/index.ts +6 -0
- package/src/infra/instance-migrations.ts +54 -0
- package/src/infra/migration-files.ts +17 -0
- package/src/infra/package-tools.ts +9 -0
- package/src/infra/provision-config-main.mjs +29 -0
- package/src/infra/provision-config.ts +33 -0
- package/src/infra/provision-diagnostics.ts +45 -0
- package/src/infra/provision-plan.ts +143 -0
- package/src/infra/provision.ts +113 -0
- package/src/infra/schema.ts +21 -0
- package/src/infra/sst-runtime.ts +76 -0
- package/src/migrations/better-auth-schema.ts +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@workbasehq/core",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"exports": {
|
|
6
6
|
".": "./src/index.ts",
|
|
@@ -31,7 +31,9 @@
|
|
|
31
31
|
"./identity-providers": "./src/identity-providers.ts",
|
|
32
32
|
"./console-contract": "./src/console-contract.ts",
|
|
33
33
|
"./organization-permissions": "./src/organization-permissions.ts",
|
|
34
|
-
"./session-contract": "./src/session-contract.ts"
|
|
34
|
+
"./session-contract": "./src/session-contract.ts",
|
|
35
|
+
"./infra": "./src/infra/index.ts",
|
|
36
|
+
"./infra/provision": "./src/infra/provision.ts"
|
|
35
37
|
},
|
|
36
38
|
"dependencies": {
|
|
37
39
|
"hono": "4.13.13",
|
|
@@ -58,5 +60,28 @@
|
|
|
58
60
|
"type": "git",
|
|
59
61
|
"url": "git+https://github.com/jakubknejzlik/workbase.git",
|
|
60
62
|
"directory": "packages/core"
|
|
63
|
+
},
|
|
64
|
+
"bin": {
|
|
65
|
+
"workbase-migrate": "src/infra/bin.mjs"
|
|
66
|
+
},
|
|
67
|
+
"peerDependencies": {
|
|
68
|
+
"tsx": "4.23.15",
|
|
69
|
+
"sst": "4.17.1",
|
|
70
|
+
"@pulumi/command": "1.2.1",
|
|
71
|
+
"@pulumi/pulumi": "^3.215.0"
|
|
72
|
+
},
|
|
73
|
+
"peerDependenciesMeta": {
|
|
74
|
+
"tsx": {
|
|
75
|
+
"optional": true
|
|
76
|
+
},
|
|
77
|
+
"sst": {
|
|
78
|
+
"optional": true
|
|
79
|
+
},
|
|
80
|
+
"@pulumi/command": {
|
|
81
|
+
"optional": true
|
|
82
|
+
},
|
|
83
|
+
"@pulumi/pulumi": {
|
|
84
|
+
"optional": true
|
|
85
|
+
}
|
|
61
86
|
}
|
|
62
87
|
}
|
package/src/app.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { eventDeliveryContext } from './event-delivery'
|
|
2
2
|
import { bootstrapRoutes } from './bootstrap'
|
|
3
3
|
import { capabilityRoutes } from './capabilities'
|
|
4
|
+
import { consoleModelRoutes } from './console-model'
|
|
4
5
|
import { queryRoutes } from './query/routes'
|
|
5
6
|
import { QueryError } from './query/errors'
|
|
6
7
|
import { validatedBrowserDispatch } from './browser-dispatch'
|
|
@@ -13,7 +14,7 @@ import { adminRoutes } from './admin-ui'
|
|
|
13
14
|
import { routePath } from 'hono/route'
|
|
14
15
|
import { ZodError } from 'zod'
|
|
15
16
|
import { publicSchema } from './public-schema'
|
|
16
|
-
import type
|
|
17
|
+
import { CORE_VERSION, type InstanceInput } from './config'
|
|
17
18
|
import type { AppEnv, RuntimeEnv, RuntimeOptions } from './types'
|
|
18
19
|
import { scopeMiddleware } from './authorization'
|
|
19
20
|
import { crudRoutes } from './crud'
|
|
@@ -84,9 +85,10 @@ function buildApp(input: InstanceInput, env: RuntimeEnv, options: RuntimeOptions
|
|
|
84
85
|
})
|
|
85
86
|
app.get('/health', async c => {
|
|
86
87
|
const schema = await schemaStatus(env, config)
|
|
87
|
-
return c.json({ instance: config.id, revision: config.revision, core_version:
|
|
88
|
+
return c.json({ instance: config.id, revision: config.revision, core_version: CORE_VERSION, schema }, schema.compatible ? 200 : 503)
|
|
88
89
|
})
|
|
89
90
|
// Public build metadata only: never include runtime bindings, credentials or records.
|
|
91
|
+
app.get('/console-info', c => c.json({ instance: config.id, displayName: config.displayName, roles: config.roles, ui: { defaultLanguage: config.ui?.defaultLanguage } }))
|
|
90
92
|
app.get('/schema', c => c.json(publicSchema(config, options)))
|
|
91
93
|
consoleRoutes(app, config, env)
|
|
92
94
|
for (const path of ['/api/*', '/commands/*', '/workflows/*', '/query', '/orgs', '/orgs/*', '/organizations/*', '/me/profile', '/invitations/*']) app.use(path, jsonCookieCSRF(env))
|
|
@@ -107,6 +109,7 @@ function buildApp(input: InstanceInput, env: RuntimeEnv, options: RuntimeOptions
|
|
|
107
109
|
options.extend?.(app, config, env)
|
|
108
110
|
bootstrapRoutes(app, kernel, env, options)
|
|
109
111
|
capabilityRoutes(app, kernel, env)
|
|
112
|
+
consoleModelRoutes(app, kernel, env)
|
|
110
113
|
queryRoutes(app, kernel, env)
|
|
111
114
|
crudRoutes(app, config, env)
|
|
112
115
|
commandRoutes(app, config, env, options.commands ?? createCommandRegistry([]))
|
package/src/config.ts
CHANGED
|
@@ -13,7 +13,7 @@ import { detailDisplaySchema, validateDetailDisplay } from './detail-display'
|
|
|
13
13
|
|
|
14
14
|
export { Q, Fn, Cond }
|
|
15
15
|
|
|
16
|
-
export const CORE_VERSION = '0.1
|
|
16
|
+
export const CORE_VERSION = '0.2.1'
|
|
17
17
|
const navigationIconSchema = z.enum(['LayoutDashboard', 'Users', 'MapPin', 'Coins', 'Wallet', 'ArrowLeftRight', 'Settings', 'Building2', 'Activity', 'Workflow', 'Database', 'Folder'])
|
|
18
18
|
const identifier = z.string().regex(/^[a-z][a-z0-9_]*$/)
|
|
19
19
|
export const fieldSchema = z.object({
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { KernelRegistry } from './kernel/registry'
|
|
2
|
+
import type { Scope } from './types'
|
|
3
|
+
import type { ConsoleGrant, ConsoleModelCapabilities } from './console-contract'
|
|
4
|
+
import { labelDependencies, labelPath } from './query/labels'
|
|
5
|
+
import { fieldsFor, validateQuery, type QueryInput, type Selection } from './query/schema'
|
|
6
|
+
import { QueryError } from './query/errors'
|
|
7
|
+
|
|
8
|
+
/** One fail-closed authority for every disclosed field, literal and presentation dependency. */
|
|
9
|
+
export function consoleAuthorization(kernel: KernelRegistry, scope: Scope, caps: ConsoleModelCapabilities) {
|
|
10
|
+
const config = kernel.config
|
|
11
|
+
const readable = new Map(Object.entries(config.entities).map(([entity]) => [entity, new Set(
|
|
12
|
+
fieldsFor(config, entity).filter(field => caps.entities[entity]?.operations.includes('read')
|
|
13
|
+
&& caps.entities[entity].readable.includes('id') && caps.entities[entity].readable.includes(field)),
|
|
14
|
+
)]))
|
|
15
|
+
const operation = (entity: string, operation: string) => readable.has(entity) && caps.entities[entity]?.operations.includes(operation) === true
|
|
16
|
+
const command = (name: string) => caps.commands.includes(name)
|
|
17
|
+
const grant = (grant?: ConsoleGrant) => !grant || (typeof grant === 'string' ? caps.resources[grant] === true : operation(grant.entity, grant.operation ?? 'read'))
|
|
18
|
+
const canRead = (entity: string) => readable.get(entity)?.has('id') === true
|
|
19
|
+
function readableField(entity: string, field: string): boolean {
|
|
20
|
+
if (!readable.get(entity)?.has(field)) return false
|
|
21
|
+
const spec = config.entities[entity].fields[field]
|
|
22
|
+
return spec?.type !== 'ref' || !!spec.entity && canRead(spec.entity)
|
|
23
|
+
}
|
|
24
|
+
function read(entity: string, field: string): boolean {
|
|
25
|
+
if (!readableField(entity, field)) return false
|
|
26
|
+
const spec = config.entities[entity]
|
|
27
|
+
return field !== spec.displayField || !spec.label || labelDependencies(config, entity).every(dependency => readableField(dependency.entity, dependency.field))
|
|
28
|
+
}
|
|
29
|
+
const write = (entity: string, field: string, action: 'create' | 'update') => !!config.entities[entity]?.fields[field]
|
|
30
|
+
&& !config.entities[entity].fields[field].readOnly && operation(entity, action)
|
|
31
|
+
&& caps.entities[entity].writable.includes(field)
|
|
32
|
+
// Read access can include sensitive data; configured literals must never disclose
|
|
33
|
+
// those values, including values derived from sensitive display-label operands.
|
|
34
|
+
function literals(entity: string, field: string): boolean {
|
|
35
|
+
if (!read(entity, field) || config.entities[entity]?.fields[field]?.sensitive) return false
|
|
36
|
+
const spec = config.entities[entity]
|
|
37
|
+
return field !== spec.displayField || !spec.label || labelDependencies(config, entity)
|
|
38
|
+
.every(dependency => !config.entities[dependency.entity].fields[dependency.field]?.sensitive)
|
|
39
|
+
}
|
|
40
|
+
const defaults = (entity: string, field: string) => literals(entity, field) && (write(entity, field, 'create') || write(entity, field, 'update'))
|
|
41
|
+
function relation(entity: string, key: string) {
|
|
42
|
+
const r = config.entities[entity]?.relations[key]
|
|
43
|
+
return r && read(entity, 'id') && read(r.entity, 'id') && read(r.many ? r.entity : entity, r.field)
|
|
44
|
+
&& (!r.through || read(r.entity, r.through.field) && read(r.through.entity, 'id')) ? r : undefined
|
|
45
|
+
}
|
|
46
|
+
function label(entity: string, key: string): boolean {
|
|
47
|
+
const path = labelPath(config, entity, key)
|
|
48
|
+
return !!path && path.hops.every(hop => literals(hop.source, hop.field) && canRead(hop.target))
|
|
49
|
+
&& !!path.display && literals(path.entity, path.display)
|
|
50
|
+
}
|
|
51
|
+
function predicateFields(entity: string, where: Record<string, unknown>): boolean {
|
|
52
|
+
return Object.entries(where).every(([key, value]) => {
|
|
53
|
+
if (key === 'and' || key === 'or') return Array.isArray(value) && value.every(child => predicateFields(entity, child))
|
|
54
|
+
if (key === 'not') return !!value && typeof value === 'object' && predicateFields(entity, value as Record<string, unknown>)
|
|
55
|
+
const r = config.entities[entity]?.relations[key]
|
|
56
|
+
if (!r) return literals(entity, key)
|
|
57
|
+
return !!relation(entity, key) && literals(r.many ? r.entity : entity, r.field)
|
|
58
|
+
&& predicateFields(r.entity, (r.many ? Object.values(value as object)[0] : value) as Record<string, unknown>)
|
|
59
|
+
})
|
|
60
|
+
}
|
|
61
|
+
function selection(entity: string, node: Selection): boolean {
|
|
62
|
+
const root = node as QueryInput
|
|
63
|
+
return canRead(entity) && (node.select ?? caps.entities[entity].readable).every(field => read(entity, field))
|
|
64
|
+
&& (!node.where || predicateFields(entity, node.where))
|
|
65
|
+
&& (node.labels ?? []).every(key => label(entity, key))
|
|
66
|
+
&& Object.keys(root.labelWhere ?? {}).every(key => label(entity, key))
|
|
67
|
+
&& (root.search?.fields ?? []).every(key => labelPath(config, entity, key) ? label(entity, key) : literals(entity, key))
|
|
68
|
+
&& (node.orderBy ?? []).every(order => order.label ? label(entity, order.field) : literals(entity, order.field))
|
|
69
|
+
&& Object.entries(node.include ?? {}).every(([key, child]) => {
|
|
70
|
+
const r = relation(entity, key)
|
|
71
|
+
return !!r && selection(r.entity, child)
|
|
72
|
+
})
|
|
73
|
+
}
|
|
74
|
+
function query(input: unknown): QueryInput | undefined {
|
|
75
|
+
try {
|
|
76
|
+
const { query } = validateQuery(kernel, scope, input)
|
|
77
|
+
return selection(query.entity, query) ? query : undefined
|
|
78
|
+
} catch (error) { if (error instanceof QueryError) return undefined; throw error }
|
|
79
|
+
}
|
|
80
|
+
const predicate = (entity: string, where: Record<string, unknown>) => !!query({ entity, select: ['id'], limit: 1, where })
|
|
81
|
+
const schema = (node: Record<string, unknown>) => node.sensitive !== true
|
|
82
|
+
&& (node.referenceEntity === undefined || typeof node.referenceEntity === 'string' && canRead(node.referenceEntity))
|
|
83
|
+
return { operation, command, grant, canRead, read, write, literals, defaults, relation, label, query, predicate, schema }
|
|
84
|
+
}
|
|
85
|
+
export type ConsoleAuthorization = ReturnType<typeof consoleAuthorization>
|
package/src/console-contract.ts
CHANGED
|
@@ -42,6 +42,8 @@ export interface ConsolePage {
|
|
|
42
42
|
export interface ConsoleQuery {
|
|
43
43
|
entity: string; select: string[]; where?: Record<string, unknown>; limit: number
|
|
44
44
|
labels?: string[]
|
|
45
|
+
search?: { text: string; fields: string[]; locale?: 'en' | 'cs' }
|
|
46
|
+
labelWhere?: Record<string, { contains: string; locale?: 'en' | 'cs' }>
|
|
45
47
|
orderBy?: { field: string; dir: 'asc' | 'desc'; label?: boolean }[]
|
|
46
48
|
}
|
|
47
49
|
export interface ConsoleFieldDisplay {
|
|
@@ -100,6 +102,77 @@ export interface ConsoleRegistry {
|
|
|
100
102
|
navigation: ConsoleNavigation[]
|
|
101
103
|
pages: ConsolePage[]
|
|
102
104
|
entities: Record<string, ConsoleEntityDisplay>
|
|
103
|
-
/**
|
|
105
|
+
/** Model presentation hints; the console-model endpoint projects these through live grants. */
|
|
104
106
|
modelUi?: ConsoleModelUI
|
|
105
107
|
}
|
|
108
|
+
|
|
109
|
+
/** JSON Schema 2020-12, including Workbase presentation extensions. */
|
|
110
|
+
export interface ConsoleInputSchema { [keyword: string]: unknown }
|
|
111
|
+
export interface ConsoleModelField {
|
|
112
|
+
type: 'string' | 'text' | 'int' | 'float' | 'bool' | 'datetime' | 'enum' | 'ref'
|
|
113
|
+
/** Storage requirement; create input presence is defined by writeSchema.required. */
|
|
114
|
+
required: boolean
|
|
115
|
+
nullable: boolean
|
|
116
|
+
operators: string[]
|
|
117
|
+
values?: string[]
|
|
118
|
+
entity?: string
|
|
119
|
+
default?: string | number | boolean | null
|
|
120
|
+
min?: number
|
|
121
|
+
readOnly?: boolean
|
|
122
|
+
sensitive?: boolean
|
|
123
|
+
ui?: ConsoleFieldDisplay & { format?: 'identifier' }
|
|
124
|
+
}
|
|
125
|
+
export interface ConsoleModelRelation {
|
|
126
|
+
entity: string; field: string; cardinality: '1:n' | 'n:1'; quantifiers?: string[]
|
|
127
|
+
through?: { entity: string; field: string; createCommand: string; deleteCommand: string }
|
|
128
|
+
}
|
|
129
|
+
export interface ConsoleModelEntity extends Omit<ConsoleEntityDisplay, 'fields'> {
|
|
130
|
+
fields: Record<string, ConsoleModelField>
|
|
131
|
+
columns: string[]
|
|
132
|
+
listColumns?: string[]
|
|
133
|
+
listLimit: number
|
|
134
|
+
displayField?: string
|
|
135
|
+
labelDependencies?: { entity: string; field: string }[]
|
|
136
|
+
relations: Record<string, ConsoleModelRelation>
|
|
137
|
+
commandsOnly: boolean
|
|
138
|
+
checks: { left: string; op: '<=' | '>='; right: string }[]
|
|
139
|
+
/** Indexes emitted by the core planner, not a live database introspection. */
|
|
140
|
+
indexes: { name: string; fields: string[]; unique: boolean }[]
|
|
141
|
+
/** Canonical inputs projected through writable fields and the corresponding operation grant. */
|
|
142
|
+
writeSchema: ConsoleInputSchema
|
|
143
|
+
updateSchema: ConsoleInputSchema
|
|
144
|
+
routes: { list: string; detail: string }
|
|
145
|
+
}
|
|
146
|
+
export interface ConsoleModelCommand {
|
|
147
|
+
name: string
|
|
148
|
+
permission: { entity: string; operation: 'read' | 'create' | 'update' | 'delete' }
|
|
149
|
+
additionalPermissions: readonly ConsoleModelCommand['permission'][]
|
|
150
|
+
/** Placement is presentation only; command capabilities still authorize execution. */
|
|
151
|
+
ui?: { placement?: { entity: string; action: 'create' }; labelKey?: string; label?: string | { en: string; cs: string }; replacesCrud?: 'create' | 'update' | 'delete' }
|
|
152
|
+
inputSchema: ConsoleInputSchema
|
|
153
|
+
}
|
|
154
|
+
export interface ConsoleRuntimeModel {
|
|
155
|
+
instance: string; revision: number; displayName?: string
|
|
156
|
+
locale: 'en' | 'cs'; timeZone: string; enumLabels?: Record<string, Record<string, string>>
|
|
157
|
+
ui?: ConsoleModelUI
|
|
158
|
+
limits: Record<string, number>
|
|
159
|
+
entities: Record<string, ConsoleModelEntity>
|
|
160
|
+
commands: ConsoleModelCommand[]
|
|
161
|
+
workflows: { name: string; version: string; inputSchema: ConsoleInputSchema }[]
|
|
162
|
+
}
|
|
163
|
+
/** Live operation grants plus field masks. A field mask alone grants no operation. */
|
|
164
|
+
export interface ConsoleModelCapabilities {
|
|
165
|
+
revision: number
|
|
166
|
+
organization: { role: string }
|
|
167
|
+
entities: Record<string, { readable: string[]; writable: string[]; operations: string[]; displayField?: string }>
|
|
168
|
+
commands: string[]
|
|
169
|
+
workflows: Record<string, ('start' | 'cancel' | 'resume')[]>
|
|
170
|
+
resources: Record<string, boolean>
|
|
171
|
+
}
|
|
172
|
+
/** Authenticated, organization-scoped wire contract. Check version before adapting. */
|
|
173
|
+
export interface ConsoleModelContract {
|
|
174
|
+
contractVersion: 1
|
|
175
|
+
model: ConsoleRuntimeModel
|
|
176
|
+
capabilities: ConsoleModelCapabilities
|
|
177
|
+
console: ConsoleRegistry | null
|
|
178
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import type { ConsoleInputSchema } from './console-contract'
|
|
2
|
+
|
|
3
|
+
const maps = new Set(['properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas'])
|
|
4
|
+
const children = new Set(['items', 'prefixItems', 'contains', 'additionalProperties', 'unevaluatedProperties',
|
|
5
|
+
'unevaluatedItems', 'propertyNames', 'allOf', 'anyOf', 'oneOf', 'not', 'if', 'then', 'else', 'contentSchema'])
|
|
6
|
+
const references = new Set(['$ref', '$dynamicRef', '$recursiveRef'])
|
|
7
|
+
const literals = new Set(['default', 'const', 'enum', 'description', 'title', 'pattern'])
|
|
8
|
+
// Unknown annotations/extensions never pass through. Values in literal data are not schema nodes.
|
|
9
|
+
const strings = new Set(['$schema', '$id', '$anchor', '$dynamicAnchor', 'referenceEntity'])
|
|
10
|
+
const numbers = new Set(['minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf', 'minLength', 'maxLength',
|
|
11
|
+
'minItems', 'maxItems', 'minContains', 'maxContains', 'minProperties', 'maxProperties'])
|
|
12
|
+
const booleans = new Set(['$recursiveAnchor', 'uniqueItems', 'readOnly', 'writeOnly', 'deprecated', 'sensitive'])
|
|
13
|
+
const formats = new Set(['date-time', 'time', 'date', 'duration', 'email', 'idn-email', 'hostname', 'idn-hostname',
|
|
14
|
+
'ipv4', 'ipv6', 'uri', 'uri-reference', 'iri', 'iri-reference', 'uuid', 'uri-template', 'json-pointer', 'relative-json-pointer', 'regex'])
|
|
15
|
+
const schemaTypes = new Set(['null', 'boolean', 'object', 'array', 'number', 'string', 'integer'])
|
|
16
|
+
const record = (value: unknown): value is Record<string, unknown> => !!value && typeof value === 'object' && !Array.isArray(value)
|
|
17
|
+
const stringArray = (value: unknown): value is string[] => Array.isArray(value) && value.every(item => typeof item === 'string')
|
|
18
|
+
function annotation(key: string, value: unknown): boolean {
|
|
19
|
+
return key === 'format' && typeof value === 'string' && formats.has(value) || strings.has(key) && typeof value === 'string' || numbers.has(key) && typeof value === 'number' && Number.isFinite(value)
|
|
20
|
+
|| booleans.has(key) && typeof value === 'boolean' || key === 'type' && (typeof value === 'string' ? schemaTypes.has(value) : stringArray(value) && value.every(type => schemaTypes.has(type)))
|
|
21
|
+
|| key === 'required' && stringArray(value) || key === 'dependentRequired' && record(value) && Object.values(value).every(stringArray)
|
|
22
|
+
}
|
|
23
|
+
const uiKeys = new Set(['kind', 'label', 'labelKey', 'placeholder', 'help', 'span', 'section', 'hidden', 'format'])
|
|
24
|
+
const schemaNode = (value: unknown) => typeof value === 'boolean' || record(value)
|
|
25
|
+
const schemaChild = (value: unknown) => schemaNode(value) || Array.isArray(value) && value.every(schemaNode)
|
|
26
|
+
|
|
27
|
+
/** Resolve and analyze the schema graph once. Reverse reachability is O(nodes + edges),
|
|
28
|
+
* including shared aliases and cycles; unresolved references seed redaction too. */
|
|
29
|
+
export function consoleInputSchema(value: unknown, allowed: (node: Record<string, unknown>) => boolean): ConsoleInputSchema {
|
|
30
|
+
const nodes = new Set<Record<string, unknown>>()
|
|
31
|
+
const edges = new Map<Record<string, unknown>, Set<Record<string, unknown>>>()
|
|
32
|
+
const anchors = new Map<string, Set<Record<string, unknown>>>()
|
|
33
|
+
function collect(value: unknown) {
|
|
34
|
+
if (Array.isArray(value)) { value.forEach(collect); return }
|
|
35
|
+
if (!record(value) || nodes.has(value)) return
|
|
36
|
+
nodes.add(value)
|
|
37
|
+
const nested = new Set<Record<string, unknown>>()
|
|
38
|
+
function add(child: unknown) {
|
|
39
|
+
if (Array.isArray(child)) child.forEach(add)
|
|
40
|
+
else if (record(child)) { nested.add(child); collect(child) }
|
|
41
|
+
}
|
|
42
|
+
for (const [key, item] of Object.entries(value)) {
|
|
43
|
+
if (maps.has(key) && record(item)) Object.values(item).forEach(add)
|
|
44
|
+
else if (children.has(key)) add(item)
|
|
45
|
+
}
|
|
46
|
+
edges.set(value, nested)
|
|
47
|
+
for (const key of ['$anchor', '$dynamicAnchor']) if (typeof value[key] === 'string') {
|
|
48
|
+
const anchor = value[key]
|
|
49
|
+
if (!anchors.has(anchor)) anchors.set(anchor, new Set())
|
|
50
|
+
anchors.get(anchor)!.add(value)
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
collect(value)
|
|
54
|
+
function targets(reference: unknown): Record<string, unknown>[] {
|
|
55
|
+
if (typeof reference !== 'string') return []
|
|
56
|
+
let ref = reference
|
|
57
|
+
if (!ref.startsWith('#')) {
|
|
58
|
+
const base = record(value) && typeof value.$id === 'string' ? value.$id.split('#')[0] : undefined
|
|
59
|
+
const hash = ref.indexOf('#')
|
|
60
|
+
if (!base || (hash < 0 ? ref : ref.slice(0, hash)) !== base) return []
|
|
61
|
+
ref = hash < 0 ? '#' : ref.slice(hash)
|
|
62
|
+
}
|
|
63
|
+
let fragment: string
|
|
64
|
+
try { fragment = decodeURIComponent(ref.slice(1)) } catch { return [] }
|
|
65
|
+
let result = value
|
|
66
|
+
if (fragment && !fragment.startsWith('/')) return [...anchors.get(fragment) ?? []]
|
|
67
|
+
if (fragment) for (const part of fragment.slice(1).split('/')) {
|
|
68
|
+
if (/~[^01]|~$/.test(part)) return []
|
|
69
|
+
const key = part.replaceAll('~1', '/').replaceAll('~0', '~')
|
|
70
|
+
if (!record(result) && !Array.isArray(result) || !Object.hasOwn(result as object, key)) return []
|
|
71
|
+
result = (result as Record<string, unknown>)[key]
|
|
72
|
+
}
|
|
73
|
+
return record(result) && nodes.has(result) ? [result] : []
|
|
74
|
+
}
|
|
75
|
+
const privateNodes = new Set<Record<string, unknown>>()
|
|
76
|
+
const unresolved = new Set<Record<string, unknown>>()
|
|
77
|
+
for (const node of nodes) {
|
|
78
|
+
if (!allowed(node)) privateNodes.add(node)
|
|
79
|
+
for (const [key, item] of Object.entries(node)) {
|
|
80
|
+
if (maps.has(key) && (!record(item) || !Object.values(item).every(schemaNode))
|
|
81
|
+
|| children.has(key) && !schemaChild(item)) unresolved.add(node)
|
|
82
|
+
if (!maps.has(key) && !children.has(key) && !references.has(key) && !literals.has(key)
|
|
83
|
+
&& !annotation(key, item) && key !== 'examples' && key !== 'x-ui') unresolved.add(node)
|
|
84
|
+
}
|
|
85
|
+
for (const key of references) if (Object.hasOwn(node, key)) {
|
|
86
|
+
// Keep every possible local target in the graph, even for ambiguous or
|
|
87
|
+
// dynamic references: uncertainty must redact candidate definitions too.
|
|
88
|
+
const candidates = targets(node[key])
|
|
89
|
+
candidates.forEach(target => edges.get(node)!.add(target))
|
|
90
|
+
if (key !== '$ref' || candidates.length !== 1) unresolved.add(node)
|
|
91
|
+
// With no known target, alias/context propagation cannot be proven complete.
|
|
92
|
+
// Redact literals throughout this input document rather than trusting a
|
|
93
|
+
// definition that an unsupported reference spelling might still alias.
|
|
94
|
+
if (!candidates.length && record(value)) unresolved.add(value)
|
|
95
|
+
}
|
|
96
|
+
// A nested $id changes reference scope. Fail closed rather than interpreting
|
|
97
|
+
// its descendants against the document root.
|
|
98
|
+
if (node !== value && node.$id !== undefined) unresolved.add(node)
|
|
99
|
+
}
|
|
100
|
+
function reach(seeds: Set<Record<string, unknown>>, graph: Map<Record<string, unknown>, Set<Record<string, unknown>>>) {
|
|
101
|
+
const reached = new Set(seeds)
|
|
102
|
+
const queue = [...seeds]
|
|
103
|
+
for (let i = 0; i < queue.length; i++) for (const child of graph.get(queue[i]) ?? []) if (!reached.has(child)) {
|
|
104
|
+
reached.add(child); queue.push(child)
|
|
105
|
+
}
|
|
106
|
+
return reached
|
|
107
|
+
}
|
|
108
|
+
// Sensitive context propagates into referenced definitions in every use.
|
|
109
|
+
const tainted = reach(new Set([...privateNodes, ...unresolved]), edges)
|
|
110
|
+
const reverse = new Map<Record<string, unknown>, Set<Record<string, unknown>>>()
|
|
111
|
+
for (const [node, targets] of edges) for (const child of targets) {
|
|
112
|
+
if (!reverse.has(child)) reverse.set(child, new Set())
|
|
113
|
+
reverse.get(child)!.add(node)
|
|
114
|
+
}
|
|
115
|
+
const unsafe = reach(tainted, reverse)
|
|
116
|
+
function visit(value: unknown): unknown {
|
|
117
|
+
if (Array.isArray(value)) return value.map(visit)
|
|
118
|
+
if (!record(value)) return value
|
|
119
|
+
const result: Record<string, unknown> = {}
|
|
120
|
+
for (const [key, item] of Object.entries(value)) {
|
|
121
|
+
if (maps.has(key) && record(item)) result[key] = Object.fromEntries(Object.entries(item).filter(([, schema]) => schemaNode(schema)).map(([name, schema]) => [name, visit(schema)]))
|
|
122
|
+
else if (children.has(key) && schemaChild(item)) result[key] = visit(item)
|
|
123
|
+
else if (references.has(key)) { if (key === '$ref' && targets(item).length === 1) result[key] = item }
|
|
124
|
+
else if (literals.has(key)) {
|
|
125
|
+
if (!unsafe.has(value) && (!['description', 'title', 'pattern'].includes(key) || typeof item === 'string') && (key !== 'enum' || Array.isArray(item))) result[key] = item
|
|
126
|
+
} else if (annotation(key, item) && (key !== 'referenceEntity' || allowed(value))) result[key] = item
|
|
127
|
+
else if (key === 'x-ui' && !unsafe.has(value) && record(item)) {
|
|
128
|
+
result[key] = Object.fromEntries(Object.entries(item).filter(([key, hint]) => uiKeys.has(key) && ['string', 'boolean', 'number'].includes(typeof hint)
|
|
129
|
+
|| key === 'fieldOrder' && stringArray(hint) && hint.every(field => record(value.properties) && Object.hasOwn(value.properties, field))))
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return result
|
|
133
|
+
}
|
|
134
|
+
return visit(value) as ConsoleInputSchema
|
|
135
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
import { bodyValidator } from './config'
|
|
3
|
+
import { capabilities } from './capabilities'
|
|
4
|
+
import { scopeMiddleware } from './authorization'
|
|
5
|
+
import { fieldsFor, fieldType, operatorsFor } from './query/schema'
|
|
6
|
+
import { labelDependencies } from './query/labels'
|
|
7
|
+
import { QUERY_LIMITS } from './query/limits'
|
|
8
|
+
import { consolePresentation } from './console-presentation'
|
|
9
|
+
import { consoleAuthorization } from './console-authorization'
|
|
10
|
+
import { consoleInputSchema } from './console-input-schema'
|
|
11
|
+
import type { KernelRegistry } from './kernel/registry'
|
|
12
|
+
import type { App, RuntimeEnv, Scope } from './types'
|
|
13
|
+
import type { ConsoleInputSchema, ConsoleModelContract, ConsoleRuntimeModel } from './console-contract'
|
|
14
|
+
|
|
15
|
+
/** No instance-source imports or private catalog: project the resolved runtime kernel. */
|
|
16
|
+
export function consoleModel(kernel: KernelRegistry, scope: Scope): ConsoleModelContract {
|
|
17
|
+
const config = kernel.config
|
|
18
|
+
const caps = capabilities(kernel, scope)
|
|
19
|
+
const authority = consoleAuthorization(kernel, scope, caps)
|
|
20
|
+
const presentation = consolePresentation(kernel, scope, authority)
|
|
21
|
+
const entities: ConsoleRuntimeModel['entities'] = Object.fromEntries(Object.entries(config.entities).filter(([name]) => authority.canRead(name)
|
|
22
|
+
|| authority.operation(name, 'create') || authority.operation(name, 'update')).map(([name, entity]) => {
|
|
23
|
+
function entityInputSchema(partial = false) {
|
|
24
|
+
const schema = z.toJSONSchema(bodyValidator(entity, partial), { io: 'input' }) as ConsoleInputSchema
|
|
25
|
+
// Preserve sensitivity and the read decision across conversion. Redact only
|
|
26
|
+
// after conversion so server defaults retain their original input requiredness.
|
|
27
|
+
const literalGrants = new WeakMap<object, boolean>()
|
|
28
|
+
schema.properties = Object.fromEntries(Object.entries(schema.properties as Record<string, ConsoleInputSchema>)
|
|
29
|
+
.filter(([field]) => authority.write(name, field, partial ? 'update' : 'create')).map(([field, property]) => {
|
|
30
|
+
const projected: ConsoleInputSchema = { ...property, ...(entity.fields[field].sensitive ? { sensitive: true } : {}) }
|
|
31
|
+
literalGrants.set(projected, authority.literals(name, field))
|
|
32
|
+
if (!authority.defaults(name, field)) delete projected.default
|
|
33
|
+
return [field, projected]
|
|
34
|
+
}))
|
|
35
|
+
if (Array.isArray(schema.required)) schema.required = schema.required.filter(field => Object.hasOwn(schema.properties as object, field))
|
|
36
|
+
return consoleInputSchema(schema, node => authority.schema(node) && literalGrants.get(node) !== false)
|
|
37
|
+
}
|
|
38
|
+
const display = authority.canRead(name) && config.ui?.entities[name] ? presentation.display(name, config.ui.entities[name]) : undefined
|
|
39
|
+
const displayField = entity.displayField && authority.read(name, entity.displayField) ? entity.displayField : undefined
|
|
40
|
+
return [name, {
|
|
41
|
+
...display,
|
|
42
|
+
fields: Object.fromEntries(fieldsFor(config, name).filter(field => authority.read(name, field)).map(field => {
|
|
43
|
+
const definition = entity.fields[field]
|
|
44
|
+
const type = fieldType(config, name, field)
|
|
45
|
+
return [field, {
|
|
46
|
+
type, required: definition?.required ?? true, nullable: definition ? !definition.required : false,
|
|
47
|
+
operators: operatorsFor(type),
|
|
48
|
+
...(definition ? {
|
|
49
|
+
...(definition.values === undefined || !authority.literals(name, field) ? {} : { values: definition.values }),
|
|
50
|
+
...(definition.entity === undefined || !authority.canRead(definition.entity) ? {} : { entity: definition.entity }),
|
|
51
|
+
...(definition.min === undefined ? {} : { min: definition.min }),
|
|
52
|
+
...(definition.default === undefined || !authority.defaults(name, field) ? {} : { default: definition.default }),
|
|
53
|
+
...(definition.readOnly === undefined ? {} : { readOnly: definition.readOnly }),
|
|
54
|
+
...(definition.sensitive === undefined ? {} : { sensitive: definition.sensitive }),
|
|
55
|
+
...(definition.ui === undefined ? {} : { ui: presentation.fieldUI(name, definition.ui) }),
|
|
56
|
+
} : { readOnly: true }),
|
|
57
|
+
}]
|
|
58
|
+
})),
|
|
59
|
+
columns: Object.keys(entity.fields).filter(field => authority.read(name, field)),
|
|
60
|
+
...(display?.list?.columns ? { listColumns: display.list.columns } : {}),
|
|
61
|
+
listLimit: Math.min(30, QUERY_LIMITS.root),
|
|
62
|
+
...(displayField ? { displayField } : {}),
|
|
63
|
+
...(entity.label && displayField ? { labelDependencies: labelDependencies(config, name).filter(dependency => authority.read(dependency.entity, dependency.field)) } : {}),
|
|
64
|
+
relations: Object.fromEntries(Object.entries(entity.relations).filter(([key]) => authority.relation(name, key)).map(([key, relation]) => [key, {
|
|
65
|
+
entity: relation.entity, field: relation.field, cardinality: relation.many ? '1:n' as const : 'n:1' as const,
|
|
66
|
+
...(relation.through ? { through: relation.through } : {}),
|
|
67
|
+
...(relation.many ? { quantifiers: ['some', 'none'] } : {}),
|
|
68
|
+
}])),
|
|
69
|
+
commandsOnly: entity.commandsOnly ?? false,
|
|
70
|
+
checks: entity.checks.filter(check => authority.read(name, check.left) && authority.read(name, check.right)),
|
|
71
|
+
indexes: [
|
|
72
|
+
{ name: `${name}_org_idx`, fields: ['organization_id', 'id'], unique: false },
|
|
73
|
+
...Object.entries(entity.fields).filter(([, field]) => field.type === 'ref').map(([field]) => ({
|
|
74
|
+
name: `${name}_${field}_idx`, fields: ['organization_id', field], unique: false,
|
|
75
|
+
})),
|
|
76
|
+
].filter(index => index.fields.every(field => authority.read(name, field))),
|
|
77
|
+
writeSchema: entityInputSchema(),
|
|
78
|
+
updateSchema: entityInputSchema(true),
|
|
79
|
+
routes: { list: `/o/$orgId/e/${name}`, detail: `/o/$orgId/e/${name}/$id` },
|
|
80
|
+
}]
|
|
81
|
+
}))
|
|
82
|
+
return {
|
|
83
|
+
contractVersion: 1,
|
|
84
|
+
model: {
|
|
85
|
+
instance: config.id, revision: config.revision,
|
|
86
|
+
...(config.displayName ? { displayName: config.displayName } : {}),
|
|
87
|
+
locale: config.locale, timeZone: config.timeZone,
|
|
88
|
+
...(config.enumLabels ? { enumLabels: Object.fromEntries(Object.entries(config.enumLabels).flatMap(([language, labels]) => {
|
|
89
|
+
// Catalogs use language -> translation key, matching query search and i18next.
|
|
90
|
+
const keys = new Set(Object.entries(config.entities).flatMap(([name, entity]) => Object.entries(entity.fields)
|
|
91
|
+
.filter(([field]) => authority.literals(name, field)).flatMap(([, field]) => {
|
|
92
|
+
const values = field.type === 'enum' ? (field.values ?? []).map(value => `value_${value}`) : field.type === 'bool' ? ['yes', 'no'] : []
|
|
93
|
+
return values.flatMap(key => [key, `${key}_${name}`])
|
|
94
|
+
})))
|
|
95
|
+
const dictionary = Object.fromEntries(Object.entries(labels).filter(([key]) => keys.has(key)))
|
|
96
|
+
return Object.keys(dictionary).length ? [[language, dictionary]] : []
|
|
97
|
+
})) } : {}),
|
|
98
|
+
...(config.ui ? { ui: presentation.modelUI(config.ui) } : {}),
|
|
99
|
+
limits: QUERY_LIMITS, entities,
|
|
100
|
+
commands: [...kernel.commands.values()].flatMap(command => caps.commands.includes(command.name) && !('system' in command.permission) ? [{
|
|
101
|
+
name: command.name, permission: command.permission, additionalPermissions: command.additionalPermissions ?? [],
|
|
102
|
+
...(command.ui ? { ui: { ...command.ui, ...(command.ui.placement && !authority.canRead(command.ui.placement.entity) ? { placement: undefined } : {}) } } : {}), inputSchema: consoleInputSchema(z.toJSONSchema(command.input, { io: 'input' }), authority.schema),
|
|
103
|
+
}] : []),
|
|
104
|
+
workflows: [...kernel.workflows.values()].filter(workflow => caps.workflows[workflow.name]?.includes('start')).map(workflow => ({
|
|
105
|
+
name: workflow.name, version: workflow.version, inputSchema: consoleInputSchema(z.toJSONSchema(workflow.input, { io: 'input' }), authority.schema),
|
|
106
|
+
})),
|
|
107
|
+
},
|
|
108
|
+
capabilities: caps,
|
|
109
|
+
console: (() => {
|
|
110
|
+
const registry = kernel.providers.get('console')?.[0]?.consoleRegistry?.(config, scope)
|
|
111
|
+
return registry ? presentation.registry(registry) : null
|
|
112
|
+
})(),
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function consoleModelRoutes(app: App, kernel: KernelRegistry, env: RuntimeEnv) {
|
|
117
|
+
app.get('/o/:org/console-model', async (c, next) => {
|
|
118
|
+
c.header('Cache-Control', 'private, no-store')
|
|
119
|
+
c.header('Vary', 'Cookie, Authorization, X-Organization-Id')
|
|
120
|
+
await next()
|
|
121
|
+
}, scopeMiddleware(env, kernel.config, kernel), c => c.json(consoleModel(kernel, c.get('scope'))))
|
|
122
|
+
}
|