Custom Collections & Safe AST Formulas
The dynamic schema subsystem in @latticedx/plugin-dxos-studio lets platform administrators and App Builder provision tenant-isolated domain tables through dxosBuilder without hand-written SQL DDL. Every custom collection receives an indexed organizationId column, FORCE ROW LEVEL SECURITY in PostgreSQL 16, linear-time Thompson NFA input validation, and sandboxed derived fields evaluated on a pure recursive-descent AST interpreter.
dxosBuilder API and Naming Contract
All dxosBuilder actions are guarded by requireBuilderAdmin. Schema creation and mutation require rootOnly privilege alongside PAT scope write.
/api/dxosBuilder:listDomains/api/dxosBuilder:createDomain/api/dxosBuilder:listBusinessPacks/api/dxosBuilder:installBusinessPack| Parameter | Type | Default | Description |
|---|---|---|---|
CUSTOM_COLLECTION_RE | RegExp | /^latticeCustom[A-Z][A-Za-z0-9]{1,40}$/ | All user-defined or App Builder collections must match this naming pattern. |
FIELD_NAME_RE | RegExp | /^[a-z][a-zA-Z0-9_]{0,62}$/ | Field identifiers start with a lowercase letter and are capped at 63 characters. |
BLOCKED_FIELD_NAMES | Set<string> | 6 keys | Blocks __proto__, constructor, prototype, id, createdAt, and updatedAt. |
SYSTEM_PROTECTED_COLLECTIONS | Set<string> | 32 tables | Prevents overwriting or targeting system tables such as users, roles, apiKeys, workflows, latticeAiAuditLogs, and latticeUiSnapshots. |
ALLOWLISTED_BUSINESS_COLLECTIONS | Set<string> | 9 tables | Core tables permitted as relation targets: latticeRequests, latticeOrders, latticeOrderLines, latticeServiceTickets, latticeParaDocuments, latticeIncidentCases, latticeLocations, latticeAssets, latticeAgentProposals. |
Automatic PostgreSQL RLS and belongsToMany Join Safety
Whenever createOrUpdateDomainCollection provisions or extends a latticeCustom* collection, domain-schema-rls.js executes a deterministic safety sequence:
- Prepends a non-null indexed
organizationId(string,allowNull: false,index: true) column and creates indexidx_<collection>_org. If the index identifier exceeds PostgreSQL's 63-byte cap,buildSafePgIndexNametruncates it and appends an 8-character SHA-256 hash suffix. - For every
belongsToManyfield,ensureBelongsToManyJoinCollectionprovisions and RLS-protects the join tablelatticeCustom<Src><Tgt>Join(with organization, foreign-key, and composite unique(organizationId, foreignKey, otherKey)indexes) before syncing the parent table. This prevents Sequelize from auto-creating an unprotected join table. attachAndVerifyPgRlsrunsENABLE ROW LEVEL SECURITYplusFORCE ROW LEVEL SECURITYand installs policylattice_tenant_isolationreferencingapp.current_organdapp.rls_bypass. It then queriespg_class(relrowsecurity,relforcerowsecurity), throwingPG_RLS_VERIFICATION_FAILEDif verification fails.- During
ALTER TABLEschema migrations on existing tables,syncCollectionWithSafeRlskeeps RLS enabled (fail-closed) while temporarily dropping and re-attachinglattice_tenant_isolationinside atry/finallyblock. - Finally,
grantDomainRbacgrantsDEFAULT_ROLE_ACTIONStoldx_admin,ldx_manager,ldx_operator, andldx_employee, and binds a portal page viaupsertPortalPageForDomainwhenportalSlugis supplied.
All 12 Supported Field Types (ALLOWED_FIELD_TYPES)
rich-schema.js supports 12 canonical field types (ALLOWED_FIELD_TYPES) mapped to NocoBase interfaces and UI components:
| # | Field type | NocoBase interface | uiSchema['x-component'] | Storage and Special Configuration |
|---|---|---|---|---|
| 1 | string | input (or select) | Input (or Select) | Short text; switches to Select when enumValues or validation.enum is set. |
| 2 | text | textarea | Input.TextArea | Multi-line text supporting validation.min, max, and pattern. |
| 3 | integer | integer | InputNumber | Integer column supporting required, unique, min, max, and enum. |
| 4 | float | number | InputNumber | Floating-point number supporting required, unique, min, and max. |
| 5 | boolean | checkbox | Checkbox | Boolean flag; min and max validation are disallowed. |
| 6 | date | date | DatePicker | Calendar date without time-of-day component. |
| 7 | datetime | datetime | DatePicker (showTime: true) | Full ISO-8601 timestamp with time picker. |
| 8 | json | json | Input.JSON | Stored as PostgreSQL jsonb; unique, min, and max are disallowed. |
| 9 | belongsTo | obo | AssociationField | Uses foreignKey (default <name>Id), targeting latticeCustom* or the 9 allowlisted business collections. |
| 10 | hasOne | oho | AssociationField | One-to-one relation referencing target via foreignKey and sourceKey (id). |
| 11 | belongsToMany | m2m | AssociationField | Many-to-many relation backed by an automatically RLS-protected through join table. |
| 12 | formula | formula | InputNumber / Input / Checkbox | Read-only derived field (x-read-pretty: true) evaluated by the Safe AST Engine according to formulaReturnType. |
Validation Rules and Linear-Time Thompson NFA Engine
Field validation rules are stored under uiSchema['x-validation'] and enforced synchronously at runtime via beforeValidate and beforeSave hooks (registerRichSchemaHooks). Supported keys are required, unique (tenant-scoped uniqueness check returning HTTP 409), min, max, enum (1..100 string or finite number items), and pattern (string and text fields only).
Instead of executing V8's backtracking RegExp.test (which is vulnerable to ReDoS), validateSafeRegexPattern compiles each pattern into a Thompson NFA and runs an O(n * m) lock-step simulation. Backreferences, lookbehinds, and nested or ambiguous quantifiers are rejected before compilation.
| Parameter | Type | Default | Description |
|---|---|---|---|
MAX_REGEX_PATTERN_LENGTH | number | 256 | Maximum length of the validation regex pattern string. |
MAX_REGEX_INPUT_LENGTH | number | 4096 | Maximum field value string length accepted by the runtime matcher. |
MAX_REGEX_QUANTIFIER_BOUND | number | 100 | Maximum repetition bound {m,n} and total quantifier count per pattern. |
MAX_REGEX_AST_DEPTH | number | 64 | Maximum AST group nesting depth allowed during regex parsing. |
MAX_NFA_STATES | number | 512 | Maximum total NFA state count for start-anchored (^) patterns. |
MAX_UNANCHORED_ROOT_NFA_STATES | number | 320 | Stricter root state cap enforced on unanchored regex patterns. |
MAX_TOTAL_LOOKAHEAD_STATES | number | 120 | Maximum combined NFA states allocated to positive or negative lookaheads. |
Safe AST Formula Engine (rich-schema.js)
Formula fields are tokenized, parsed by recursive descent, and interpreted directly on the AST without eval or new Function. Declared formulaReturnType must be one of float, integer, string, or boolean.
| Parameter | Type | Default | Description |
|---|---|---|---|
MAX_FORMULA_LENGTH | number | 1000 | Maximum character length of a formula expression string. |
MAX_FORMULA_TOKENS | number | 256 | Maximum lexical token count emitted by tokenizeFormula. |
MAX_FORMULA_DEPTH | number | 24 | Maximum AST nesting depth allowed during expression parsing. |
Supported Operators | operators | 17 operators | Arithmetic (+, -, *, /, %), logical (!, &&, ||), ternary (?:), and comparison (==, ===, !=, !==, <, <=, >, >=). |
BLOCKED_FORMULA_IDENTIFIERS | Set<string> | 15 keywords | Blocks __proto__, constructor, prototype, global, globalThis, process, require, module, exports, Function, eval, Proxy, Reflect, window, and self. |
Complete Catalog of 22 Formula Functions (FORMULA_FUNCTIONS)
Math Functions (8)
| Signature | Parameter Types | Return Type | Edge & Null Handling |
|---|---|---|---|
ROUND(n, digits = 0) | number, integer? | number | null | Clamps digits to [0..10]; returns null when n is non-finite. |
ABS(n) | number | number | null | Returns Math.abs(n) or null if n cannot coerce to a finite number. |
CEIL(n) | number | integer | null | Rounds upward via Math.ceil(n) or returns null. |
FLOOR(n) | number | integer | null | Rounds downward via Math.floor(n) or returns null. |
MIN(...args) | ...number | number | null | Filters out null/non-numeric arguments; returns null if none remain. |
MAX(...args) | ...number | number | null | Filters out null/non-numeric arguments; returns maximum or null. |
POW(base, exp) | number, number | number | null | Computes base ** exp; returns null when output is NaN or Infinity. |
SQRT(n) | number | number | null | Returns Math.sqrt(n); returns null if n < 0 or invalid. |
Conditional and Null Functions (3)
| Signature | Parameter Types | Return Type | Edge & Null Handling |
|---|---|---|---|
COALESCE(...args) | ...any | any | null | Returns the first argument that is neither null nor undefined; else null. |
IF(cond, thenVal, elseVal) | any, any, any | any | Evaluates truthiness of cond and returns thenVal or elseVal. |
ISNULL(v) | any | boolean | Returns true strictly for v === null || v === undefined ("" and 0 return false). |
String Functions (6)
| Signature | Parameter Types | Return Type | Edge & Null Handling |
|---|---|---|---|
CONCAT(...args) | ...any | string | Concatenates arguments as strings; null and undefined coerce to "". |
UPPER(s) | any | string | Uppercases string representation; returns "" for null/undefined. |
LOWER(s) | any | string | Lowercases string representation; returns "" for null/undefined. |
TRIM(s) | any | string | Trims leading and trailing whitespace; returns "" for null/undefined. |
LEN(s) | any | integer | Returns 0 for null/undefined; .length for string/array or coerced string length. |
SUBSTR(s, start = 0, len) | any, integer?, integer? | string | Slices from start >= 0 for len >= 0 characters; slices to end when len is omitted. |
Date and Time Functions (5)
| Signature | Parameter Types | Return Type | Edge & Null Handling |
|---|---|---|---|
NOW() | (none) | string | Returns current UTC timestamp in ISO-8601 format (new Date().toISOString()). |
YEAR(d) | Date | string | number | integer | null | Extracts UTC year (getUTCFullYear()); returns null for invalid dates. |
MONTH(d) | Date | string | number | integer | null | Extracts 1-based UTC month (1..12); returns null for invalid dates. |
DAY(d) | Date | string | number | integer | null | Extracts UTC day of month (1..31); returns null for invalid dates. |
DATEDIFF_DAYS(d1, d2) | Date | string, Date | string | integer | null | Truncates (d1.getTime() - d2.getTime()) / 86400000 toward zero. |
Domain Creation API Example
{
"collectionName": "latticeCustomColdLotLogs",
"title": "Cold Lot Logs",
"portalSlug": "cold-lot-logs",
"fields": [
{ "name": "lotCode", "type": "string", "required": true, "validation": { "unique": true, "pattern": "^LOT-[0-9]{4}-[A-Z0-9]{2,8}$" } },
{ "name": "order", "type": "belongsTo", "target": "latticeOrders", "foreignKey": "orderId" },
{ "name": "tempC", "type": "float", "validation": { "min": -80, "max": 50 } },
{ "name": "isExcursion", "type": "formula", "formulaReturnType": "boolean", "formulaExpression": "IF(ISNULL(tempC), false, tempC > -15)" }
]
}Operational Notes
- Uniqueness checks (
unique: true) are scoped strictly toorganizationIdand return HTTP409on duplicate values within the same tenant while allowing identical values across distinct tenants. - Formula expressions reject self-references matching the defining field's
nameand reject any function outside the 22 registeredFORMULA_FUNCTIONS. - Patterns anchored at the start of input (
^) permit up to512NFA states, whereas unanchored patterns are capped at320root states to keep validation predictable.
