@workbasehq/core 0.2.14 → 0.2.15
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 +1 -1
- package/src/config.ts +1 -1
- package/src/console-presentation.ts +1 -1
- package/src/query/compiler.ts +13 -0
- package/src/query/schema.ts +13 -3
- package/src/user-link-fields.ts +7 -0
- package/src/user-links.ts +3 -4
package/package.json
CHANGED
package/src/config.ts
CHANGED
|
@@ -18,7 +18,7 @@ export { Q, Cond }
|
|
|
18
18
|
/** SQLite date formatting with column operands; values use the library wire encoding. */
|
|
19
19
|
export const Fn = { ...LibraryFn, strftime: (format: string, date: string) => Q.expr(`FN(${JSON.stringify(['STRFTIME', Q.value(format).serialize(), Q.expr(date).serialize()])})`) }
|
|
20
20
|
|
|
21
|
-
export const CORE_VERSION = '0.2.
|
|
21
|
+
export const CORE_VERSION = '0.2.15'
|
|
22
22
|
const navigationIconSchema = z.enum(['LayoutDashboard', 'Users', 'MapPin', 'Coins', 'Wallet', 'ArrowLeftRight', 'Settings', 'Building2', 'Activity', 'Workflow', 'Database', 'Folder'])
|
|
23
23
|
const identifier = z.string().regex(/^[a-z][a-z0-9_]*$/)
|
|
24
24
|
export const serializedExpressionSchema = z.union([z.string().min(1).max(32000), z.record(z.string(), z.unknown()).transform(value => JSON.stringify(value))])
|
|
@@ -125,7 +125,7 @@ export function consolePresentation(kernel: KernelRegistry, scope: Scope, author
|
|
|
125
125
|
})
|
|
126
126
|
return {
|
|
127
127
|
entities, pages,
|
|
128
|
-
navigation: source.navigation.filter(item => !!item.page !== !!item.entity && permits(item.grant) && (!item.roles || item.roles.includes(scope.role)) && (!item.page || pages.some(page => page.id === item.page))
|
|
128
|
+
navigation: source.navigation.filter(item => (scope.role !== 'member' || item.placement === 'sidebar' && !!item.entity) && !!item.page !== !!item.entity && permits(item.grant) && (!item.roles || item.roles.includes(scope.role)) && (!item.page || pages.some(page => page.id === item.page))
|
|
129
129
|
&& (!item.entity || canRead(item.entity) && (!item.view || entities[item.entity]?.list?.views?.some(view => view.id === item.view)))).map(item => ({ ...pick(item, ['id', 'placement', 'label', 'icon', 'order', 'roles', 'page', 'entity', 'view']),
|
|
130
130
|
...(item.grant ? { grant: safeGrant(item.grant) } : {}),
|
|
131
131
|
...(item.group ? { group: pick(item.group, ['id', 'label', 'order', 'icon']) } : {}) })),
|
package/src/query/compiler.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { userLinks } from '../user-link-fields'
|
|
1
2
|
import { DisplayPartsExpression, needsDisplayParts, partsAlias } from './display-parts'
|
|
2
3
|
import { expressionInfo, readableComputed, rebindExpression, type ExpressionInfo } from './expressions'
|
|
3
4
|
import { ApiError } from '../errors'
|
|
@@ -27,6 +28,17 @@ class ScopedCondition extends Condition {
|
|
|
27
28
|
: this.filter.kind === 'all' ? '1=1' : '0=1'
|
|
28
29
|
}
|
|
29
30
|
}
|
|
31
|
+
/** Access state is derived only for authorized root rows; credentials never enter projections. */
|
|
32
|
+
class RowAccessCondition extends Condition {
|
|
33
|
+
constructor(private kernel: KernelRegistry, private scope: Scope, private query: QueryInput) { super() }
|
|
34
|
+
toSQL(flavor: ISQLFlavor) {
|
|
35
|
+
const link = userLinks(this.kernel.config).find(link => link.entity === this.query.entity)!
|
|
36
|
+
const bind = (v: unknown) => value(v).toSQL(flavor)
|
|
37
|
+
const root = `SELECT 1 FROM ${quote(link.entity)} access_row WHERE access_row.organization_id=${bind(this.scope.organizationId)} AND access_row.id="row"."id" AND access_row.${quote(link.field)} IS NOT NULL`
|
|
38
|
+
const invitation = `(SELECT CASE WHEN accepted_at IS NOT NULL OR revoked_at IS NOT NULL OR declined_at IS NOT NULL THEN 'no_account' WHEN expired_at IS NOT NULL OR expires_at<=strftime('%Y-%m-%dT%H:%M:%fZ','now') THEN 'expired' ELSE 'invited' END FROM invitations WHERE organization_id=${bind(this.scope.organizationId)} AND target_entity=${bind(this.query.entity)} AND target_row="row"."id" ORDER BY created_at DESC,id DESC LIMIT 1)`
|
|
39
|
+
return `(CASE WHEN EXISTS (${root}) THEN 'signed_in' ELSE coalesce(${invitation},'no_account') END)=${bind(this.query.rowAccess)}`
|
|
40
|
+
}
|
|
41
|
+
}
|
|
30
42
|
class ContainsCondition extends Condition {
|
|
31
43
|
constructor(private column: string, private text: string, private insensitive = false) { super() }
|
|
32
44
|
toSQL(flavor: ISQLFlavor) {
|
|
@@ -483,6 +495,7 @@ export function compileRoot(kernel: KernelRegistry, scope: Scope, query: QueryIn
|
|
|
483
495
|
labeled = labeled.field(display ? Q.raw(`json_extract(${quote('labels')}."${labelAlias(key)}", '$.row.${display}')`) : Q.raw('NULL'), sortAlias(key))
|
|
484
496
|
}
|
|
485
497
|
let ast = labelKeys.length ? Q.select().from(labeled, 'row').field('row.*') : source
|
|
498
|
+
if (query.rowAccess) ast = ast.where(new RowAccessCondition(kernel, scope, query))
|
|
486
499
|
const order = queryOrder(query).map(o => ({ ...o, field: orderField(o) }))
|
|
487
500
|
function searchCondition(key: string, text: string, locale: 'en' | 'cs' = 'en'): Condition {
|
|
488
501
|
const path = labelPath(kernel.config, query.entity, key)
|
package/src/query/schema.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { organizationPermission } from '../organization-permissions'
|
|
2
|
+
import { userLinks } from '../user-link-fields'
|
|
1
3
|
import { z } from 'zod'
|
|
2
4
|
import { baseFields, type Field, type InstanceConfig } from '../config'
|
|
3
5
|
import type { KernelRegistry } from '../kernel/registry'
|
|
@@ -12,7 +14,8 @@ export type Scalar = string | number | boolean | null
|
|
|
12
14
|
export interface Filter { [key: string]: unknown }
|
|
13
15
|
export interface Order { field: string; dir: 'asc' | 'desc'; label?: boolean }
|
|
14
16
|
export interface Selection { labels?: string[]; select?: string[]; where?: Filter; orderBy?: Order[]; limit?: number; include?: Record<string, Selection> }
|
|
15
|
-
export
|
|
17
|
+
export type RowAccessState = 'no_account' | 'invited' | 'expired' | 'signed_in'
|
|
18
|
+
export interface QueryInput extends Selection { rowAccess?: RowAccessState; contextList?: { entity: string; list: string; id: string }; search?: { text: string; fields: string[]; locale?: 'en' | 'cs' }; labelWhere?: Record<string, { contains: string; locale?: 'en' | 'cs' }>; entity: string; limit: number; cursor?: string }
|
|
16
19
|
export const fieldsFor = (config: InstanceConfig, entity: string) => [...baseFields, ...Object.keys(config.entities[entity].fields)]
|
|
17
20
|
export function fieldType(config: InstanceConfig, entity: string, field: string): Field['type'] {
|
|
18
21
|
return config.entities[entity].fields[field]?.type ?? (field === 'version' ? 'int' : ['created_at', 'updated_at'].includes(field) ? 'datetime' : 'string')
|
|
@@ -83,6 +86,7 @@ export function querySchema(config: InstanceConfig, entity: string, rest = false
|
|
|
83
86
|
}
|
|
84
87
|
shape.search = z.strictObject({ text: z.string().min(1).max(2000), fields: z.array(z.enum([...new Set([...names, ...labelNames])] as [string, ...string[]])).min(1).max(names.length + labelNames.length).refine(v => new Set(v).size === v.length), locale: z.enum(['en', 'cs']).optional() }).optional()
|
|
85
88
|
shape.contextList = z.strictObject({ entity: z.string().regex(/^[a-z][a-z0-9_]*$/).max(100), list: z.string().regex(/^[a-z][a-z0-9_]*$/).max(100), id: z.string().min(1).max(2000) }).optional()
|
|
89
|
+
shape.rowAccess = z.enum(['no_account', 'invited', 'expired', 'signed_in']).optional()
|
|
86
90
|
shape.entity = z.literal(name); shape.cursor = z.string().min(1).max(L.cursorBytes).optional()
|
|
87
91
|
}
|
|
88
92
|
return z.strictObject(shape)
|
|
@@ -129,12 +133,18 @@ export function validateQuery(kernel: KernelRegistry, scope: Scope, input: unkno
|
|
|
129
133
|
if (!parsed.success) {
|
|
130
134
|
const issue = parsed.error.issues[0]
|
|
131
135
|
// Unknown client keys/values never become error text or paths.
|
|
132
|
-
const known = new Set(['entity', 'select', 'where', 'search', 'text', 'fields', 'locale', 'labelWhere', 'labels', 'label', 'orderBy', 'field', 'dir', 'limit', 'cursor', 'include', 'and', 'or', 'not', 'some', 'none',
|
|
136
|
+
const known = new Set(['entity', 'rowAccess', 'select', 'where', 'search', 'text', 'fields', 'locale', 'labelWhere', 'labels', 'label', 'orderBy', 'field', 'dir', 'limit', 'cursor', 'include', 'and', 'or', 'not', 'some', 'none',
|
|
133
137
|
...Object.values(kernel.config.entities).flatMap(e => [...Object.keys(e.fields), ...Object.keys(e.relations)]), ...baseFields,
|
|
134
138
|
...operatorsFor('string')])
|
|
135
139
|
invalid(issue.path.map(p => typeof p === 'number' ? p : known.has(String(p)) ? String(p) : '?'))
|
|
136
140
|
}
|
|
137
141
|
const query = parsed.data as QueryInput
|
|
142
|
+
if (query.rowAccess) {
|
|
143
|
+
if (!kernel.providers.has('members') || !userLinks(kernel.config).some(link => link.entity === entity)) invalid(['rowAccess'])
|
|
144
|
+
kernel.resourcePermission(scope, 'invitations.read')
|
|
145
|
+
organizationPermission(kernel.config, scope, 'invitations.read')
|
|
146
|
+
kernel.readPermission(scope, entity)
|
|
147
|
+
}
|
|
138
148
|
if (query.contextList) {
|
|
139
149
|
const context = query.contextList
|
|
140
150
|
// Resolve from trusted configuration using the same plugin-over-model precedence as the registry.
|
|
@@ -149,7 +159,7 @@ export function validateQuery(kernel: KernelRegistry, scope: Scope, input: unkno
|
|
|
149
159
|
// This predicate goes through normal field masks, policy-scoped sources and cursor hashing.
|
|
150
160
|
delete query.contextList
|
|
151
161
|
}
|
|
152
|
-
const cost: QueryCost = { depth: 0, relations: 0, fieldRows: 0, exists: 0, nodes: 0 }
|
|
162
|
+
const cost: QueryCost = { depth: 0, relations: 0, fieldRows: 0, exists: query.rowAccess ? 2 : 0, nodes: 0 }
|
|
153
163
|
// Every compiled client table source masks each readable FK once. Visibility
|
|
154
164
|
// probes only test the target's scoped predicate, so do not recursively mask it.
|
|
155
165
|
function foreignKeyCost(name: string) {
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { InstanceConfig } from './config'
|
|
2
|
+
|
|
3
|
+
/** Read-only link metadata, independent of the privileged account-link writers. */
|
|
4
|
+
export function userLinks(config: InstanceConfig) {
|
|
5
|
+
return Object.entries(config.entities).flatMap(([entity, definition]) => Object.entries(definition.fields)
|
|
6
|
+
.filter(([, field]) => field.userLink).map(([field]) => ({ entity, field })))
|
|
7
|
+
}
|
package/src/user-links.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { userLinks } from './user-link-fields'
|
|
2
|
+
export { userLinks } from './user-link-fields'
|
|
1
3
|
// Core-only account-link writers. No raw SQL or capability is exposed to clients.
|
|
2
4
|
import { z } from 'zod'
|
|
3
5
|
import type { InstanceConfig } from './config'
|
|
@@ -24,10 +26,7 @@ function writer(statement: GuardedStatement, mode: 'link' | 'cleanup'): GuardedS
|
|
|
24
26
|
export const userLinkWriter = (statement: GuardedStatement) => writers.get(statement)
|
|
25
27
|
// Only these core-minted statements can substitute a prepared-role policy filter.
|
|
26
28
|
export const userLinkPolicyFilter = (statement: GuardedStatement) => livePolicies.get(statement)
|
|
27
|
-
|
|
28
|
-
return Object.entries(config.entities).flatMap(([entity, definition]) => Object.entries(definition.fields)
|
|
29
|
-
.filter(([, field]) => field.userLink).map(([field]) => ({ entity, field })))
|
|
30
|
-
}
|
|
29
|
+
|
|
31
30
|
export function assertUnprotectedFields(definition: Pick<InstanceConfig['entities'][string], 'fields'>, fields: string[]) {
|
|
32
31
|
if (fields.some(field => definition.fields[field]?.userLink)) throw new ApiError(400, 'protected_field')
|
|
33
32
|
}
|