Skip to content

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.

GET/api/dxosBuilder:listDomains
Bearer JWT | ldx_pat_*read
Lists all ^latticeCustom* collections with field definitions, RLS status, and bound portal routes.
POST/api/dxosBuilder:createDomain
Bearer JWT | ldx_pat_*write (rootOnly)
Creates or updates a ^latticeCustom* collection, attaching organizationId, B-tree index, FORCE RLS, ldx_* role permissions, and an optional portal page.
GET/api/dxosBuilder:listBusinessPacks
Bearer JWT | ldx_pat_*read
Returns the built-in BUSINESS_PACK_CATALOG entries and their domain schema templates.
POST/api/dxosBuilder:installBusinessPack
Bearer JWT | ldx_pat_*write
Installs a Business Pack into the target organization, syncing collections, DMN tables, and portal views.
Naming Constraints and Protection Boundaries
ParameterTypeDefaultDescription
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 keysBlocks __proto__, constructor, prototype, id, createdAt, and updatedAt.
SYSTEM_PROTECTED_COLLECTIONS
Set<string>32 tablesPrevents overwriting or targeting system tables such as users, roles, apiKeys, workflows, latticeAiAuditLogs, and latticeUiSnapshots.
ALLOWLISTED_BUSINESS_COLLECTIONS
Set<string>9 tablesCore 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:

  1. Prepends a non-null indexed organizationId (string, allowNull: false, index: true) column and creates index idx_<collection>_org. If the index identifier exceeds PostgreSQL's 63-byte cap, buildSafePgIndexName truncates it and appends an 8-character SHA-256 hash suffix.
  2. For every belongsToMany field, ensureBelongsToManyJoinCollection provisions and RLS-protects the join table latticeCustom<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.
  3. attachAndVerifyPgRls runs ENABLE ROW LEVEL SECURITY plus FORCE ROW LEVEL SECURITY and installs policy lattice_tenant_isolation referencing app.current_org and app.rls_bypass. It then queries pg_class (relrowsecurity, relforcerowsecurity), throwing PG_RLS_VERIFICATION_FAILED if verification fails.
  4. During ALTER TABLE schema migrations on existing tables, syncCollectionWithSafeRls keeps RLS enabled (fail-closed) while temporarily dropping and re-attaching lattice_tenant_isolation inside a try/finally block.
  5. Finally, grantDomainRbac grants DEFAULT_ROLE_ACTIONS to ldx_admin, ldx_manager, ldx_operator, and ldx_employee, and binds a portal page via upsertPortalPageForDomain when portalSlug is 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 typeNocoBase interfaceuiSchema['x-component']Storage and Special Configuration
1stringinput (or select)Input (or Select)Short text; switches to Select when enumValues or validation.enum is set.
2texttextareaInput.TextAreaMulti-line text supporting validation.min, max, and pattern.
3integerintegerInputNumberInteger column supporting required, unique, min, max, and enum.
4floatnumberInputNumberFloating-point number supporting required, unique, min, and max.
5booleancheckboxCheckboxBoolean flag; min and max validation are disallowed.
6datedateDatePickerCalendar date without time-of-day component.
7datetimedatetimeDatePicker (showTime: true)Full ISO-8601 timestamp with time picker.
8jsonjsonInput.JSONStored as PostgreSQL jsonb; unique, min, and max are disallowed.
9belongsTooboAssociationFieldUses foreignKey (default <name>Id), targeting latticeCustom* or the 9 allowlisted business collections.
10hasOneohoAssociationFieldOne-to-one relation referencing target via foreignKey and sourceKey (id).
11belongsToManym2mAssociationFieldMany-to-many relation backed by an automatically RLS-protected through join table.
12formulaformulaInputNumber / Input / CheckboxRead-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.

Thompson NFA Safety Limits
ParameterTypeDefaultDescription
MAX_REGEX_PATTERN_LENGTH
number256Maximum length of the validation regex pattern string.
MAX_REGEX_INPUT_LENGTH
number4096Maximum field value string length accepted by the runtime matcher.
MAX_REGEX_QUANTIFIER_BOUND
number100Maximum repetition bound {m,n} and total quantifier count per pattern.
MAX_REGEX_AST_DEPTH
number64Maximum AST group nesting depth allowed during regex parsing.
MAX_NFA_STATES
number512Maximum total NFA state count for start-anchored (^) patterns.
MAX_UNANCHORED_ROOT_NFA_STATES
number320Stricter root state cap enforced on unanchored regex patterns.
MAX_TOTAL_LOOKAHEAD_STATES
number120Maximum 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.

Sandbox Guardrails and Blocked Identifiers
ParameterTypeDefaultDescription
MAX_FORMULA_LENGTH
number1000Maximum character length of a formula expression string.
MAX_FORMULA_TOKENS
number256Maximum lexical token count emitted by tokenizeFormula.
MAX_FORMULA_DEPTH
number24Maximum AST nesting depth allowed during expression parsing.
Supported Operators
operators17 operatorsArithmetic (+, -, *, /, %), logical (!, &&, ||), ternary (?:), and comparison (==, ===, !=, !==, <, <=, >, >=).
BLOCKED_FORMULA_IDENTIFIERS
Set<string>15 keywordsBlocks __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) ​

SignatureParameter TypesReturn TypeEdge & Null Handling
ROUND(n, digits = 0)number, integer?number | nullClamps digits to [0..10]; returns null when n is non-finite.
ABS(n)numbernumber | nullReturns Math.abs(n) or null if n cannot coerce to a finite number.
CEIL(n)numberinteger | nullRounds upward via Math.ceil(n) or returns null.
FLOOR(n)numberinteger | nullRounds downward via Math.floor(n) or returns null.
MIN(...args)...numbernumber | nullFilters out null/non-numeric arguments; returns null if none remain.
MAX(...args)...numbernumber | nullFilters out null/non-numeric arguments; returns maximum or null.
POW(base, exp)number, numbernumber | nullComputes base ** exp; returns null when output is NaN or Infinity.
SQRT(n)numbernumber | nullReturns Math.sqrt(n); returns null if n < 0 or invalid.

Conditional and Null Functions (3) ​

SignatureParameter TypesReturn TypeEdge & Null Handling
COALESCE(...args)...anyany | nullReturns the first argument that is neither null nor undefined; else null.
IF(cond, thenVal, elseVal)any, any, anyanyEvaluates truthiness of cond and returns thenVal or elseVal.
ISNULL(v)anybooleanReturns true strictly for v === null || v === undefined ("" and 0 return false).

String Functions (6) ​

SignatureParameter TypesReturn TypeEdge & Null Handling
CONCAT(...args)...anystringConcatenates arguments as strings; null and undefined coerce to "".
UPPER(s)anystringUppercases string representation; returns "" for null/undefined.
LOWER(s)anystringLowercases string representation; returns "" for null/undefined.
TRIM(s)anystringTrims leading and trailing whitespace; returns "" for null/undefined.
LEN(s)anyintegerReturns 0 for null/undefined; .length for string/array or coerced string length.
SUBSTR(s, start = 0, len)any, integer?, integer?stringSlices from start >= 0 for len >= 0 characters; slices to end when len is omitted.

Date and Time Functions (5) ​

SignatureParameter TypesReturn TypeEdge & Null Handling
NOW()(none)stringReturns current UTC timestamp in ISO-8601 format (new Date().toISOString()).
YEAR(d)Date | string | numberinteger | nullExtracts UTC year (getUTCFullYear()); returns null for invalid dates.
MONTH(d)Date | string | numberinteger | nullExtracts 1-based UTC month (1..12); returns null for invalid dates.
DAY(d)Date | string | numberinteger | nullExtracts UTC day of month (1..31); returns null for invalid dates.
DATEDIFF_DAYS(d1, d2)Date | string, Date | stringinteger | nullTruncates (d1.getTime() - d2.getTime()) / 86400000 toward zero.

Domain Creation API Example ​

json
{
  "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 to organizationId and return HTTP 409 on duplicate values within the same tenant while allowing identical values across distinct tenants.
  • Formula expressions reject self-references matching the defining field's name and reject any function outside the 22 registered FORMULA_FUNCTIONS.
  • Patterns anchored at the start of input (^) permit up to 512 NFA states, whereas unanchored patterns are capped at 320 root states to keep validation predictable.

Apache-2.0 · LatticeDX v0.4.2 · Powered by NocoBase · v2.2.50 · Apache-2.0 (Clause 5.2)