- TypeScript 83.7%
- JavaScript 12.2%
- Handlebars 4.1%
| .githooks | ||
| .github/workflows | ||
| docs | ||
| scripts | ||
| src | ||
| .DS_Store | ||
| .gitignore | ||
| .nvmrc | ||
| AGENTS.md | ||
| C6.config.example.json | ||
| C6.config.example.ts | ||
| C6.config.json | ||
| LICENSE | ||
| package-lock.json | ||
| package.json | ||
| README.md | ||
| rollup.config.mjs | ||
| tsconfig.json | ||
| tslint.json | ||
| vitest.config.ts | ||
CarbonNode
CarbonNode is a typed SQL ORM runtime plus code generator for REST bindings, with MySQL support and PostgreSQL runtime/generator support.
It is built for:
- full-stack teams that want one query shape across frontend and backend
- explicit column references and safer query composition
- JSON-serializable SQL expression payloads with predictable parsing
- generated TypeScript bindings from live MySQL schema
It can run in two modes:
- SQL executor (
mysqlPoolset): executes SQL directly in Node - HTTP executor (no pool, axios set): sends requests to a CarbonNode REST endpoint
Table of Contents
- Install
- Quickstart
- Execution Model
- C6 + CarbonReact State Management
- Canonical SQL Expression Grammar (6.1.0+)
- Clause-by-Clause Usage
- Helper Builders
- Singular vs Complex Requests
- HTTP Query-String Pitfalls
- Generator Output
- SQL Allowlist
- Lifecycle Hooks and Websocket Broadcast
- Testing
- Migration Notes (6.x -> 7.0)
- Migration Notes (6.0 -> 6.1)
- AI Interpretation Contract
- Git Hooks
- Support
Install
npm install @carbonorm/carbonnode
Peer dependencies:
mysql2for SQL executor modeaxiosfor HTTP executor modeexpressonly if hosting the REST route in your app
Quickstart
1) Generate bindings
Generate C6.ts + C6.test.ts + dump artifacts into an output directory:
npx generateRestBindings \
--config ./rest.config.json \
--prefix "" \
--output ./shared/rest
--config is optional if a C6.config.json, C6.config.ts, .C6.json, or .C6.ts exists in the current directory or any parent directory.
If no config exists and the process is interactive (TTY), the CLI offers a guided prompt to create ./C6.config.json.
Prefer C6.config.json for security/reproducibility; TS config files are executed as local code during generation.
TS config may export a plain object, a function returning an object, or an async function/Promise resolving to the config object.
Config shape:
{
"databases": [
{
"alias": "app",
"host": "127.0.0.1",
"port": 3306,
"user": "root",
"passEnv": "APP_DB_PASS",
"dbnames": ["app"]
},
{
"alias": "analytics",
"host": "analytics-db.internal",
"port": 3306,
"user": "analytics_user",
"passEnv": "ANALYTICS_DB_PASS",
"dbnames": ["analytics", "app"]
}
],
"primaryAlias": "app"
}
Each dbnames entry creates a generated scoped namespace. If one entry has multiple schema names, aliases are generated as:
aliasfor the schema matchingaliasalias_<dbname>for additional schema names
Example above yields C6.analytics and C6.analytics_app.
Starter template: ./C6.config.example.json.
TS starter template: ./C6.config.example.ts.
Beginner-friendly TS setup (recommended when you want env/vault secrets):
- Copy the template.
cp ./C6.config.example.ts ./C6.config.ts
- Set password env vars in your shell.
export APP_DB_PASS='replace-me'
export BILLING_DB_PASS='replace-me'
export ANALYTICS_DB_PASS='replace-me'
-
Open
C6.config.tsand updatehost,user,dbnames,primaryAlias, anddialectfor your databases. Usedialect: "postgresql"for PostgreSQL targets; omitted dialects default to MySQL. -
Generate bindings.
npx generateRestBindings --output ./shared/rest
Notes:
- You can pass an explicit path too:
npx generateRestBindings --config ./C6.config.ts --output ./shared/rest. C6.config.tscan load secrets asynchronously (for example from Vault) before returning the config object.- Keep secret-bearing files out of git. Prefer local/private config names like
.C6.tsor.C6.json.
Import from generated bindings:
import { C6, GLOBAL_REST_PARAMETERS, Actor } from "./shared/rest/C6";
2) Configure runtime
SQL executor mode (Node + direct DB)
import mysql from "mysql2/promise";
import { GLOBAL_REST_PARAMETERS } from "./shared/rest/C6";
GLOBAL_REST_PARAMETERS.mysqlPool = mysql.createPool({
host: "127.0.0.1",
user: "root",
password: "password",
database: "sakila",
});
PostgreSQL runtime execution is available by providing a pg pool and selecting the PostgreSQL SQL dialect:
import { Pool } from "pg";
import { GLOBAL_REST_PARAMETERS } from "./shared/rest/C6";
GLOBAL_REST_PARAMETERS.postgresPool = new Pool({
host: "127.0.0.1",
user: "postgres",
password: "password",
database: "app",
});
GLOBAL_REST_PARAMETERS.sqlDialect = "postgresql";
Current PostgreSQL support covers runtime SQL building/execution for the canonical expression grammar, basic CRUD shapes, RETURNING * for inserts, ON CONFLICT upserts when primary-key metadata is available, and inner-join deletes via DELETE ... USING. MySQL-only forms such as REPLACE and MySQL index hints fail explicitly; non-inner or derived-table delete joins should use a WHERE subselect for now. Binding generation supports dialect: "postgresql" in C6.config.*, uses pg_dump/psql when available, and can reuse a prebuilt C6.pg_dump.sql in CI or no-database environments.
SQL executor mode with multiple databases (request-scoped)
Use GLOBAL_REST_PARAMETERS.databases to register connection targets. Then select one per request with [C6.DB].
import mysql from "mysql2/promise";
import { C6, GLOBAL_REST_PARAMETERS, Actor } from "./shared/rest/C6";
const appPool = mysql.createPool({ host: "10.0.0.10", user: "root", password: "password", database: "app" });
const billingPool = mysql.createPool({ host: "10.0.0.20", user: "root", password: "password", database: "billing" });
GLOBAL_REST_PARAMETERS.databases = {
app: appPool,
billing: billingPool,
};
GLOBAL_REST_PARAMETERS.defaultDatabase = "app";
await Actor.Get({
[C6.DB]: "billing",
[C6.PAGINATION]: { [C6.LIMIT]: 10 },
});
C6.DB is request-scoped and safe for parallel async requests.
If a key exists in GLOBAL_REST_PARAMETERS.databases, generated bindings also expose scoped namespaces:
await C6.billing.Actor.Get({
[C6.PAGINATION]: { [C6.LIMIT]: 10 },
});
This is equivalent to calling Actor.Get({ [C6.DB]: "billing", ... }).
HTTP executor mode (frontend or remote client)
import { axiosInstance } from "@carbonorm/carbonnode";
import { GLOBAL_REST_PARAMETERS } from "./shared/rest/C6";
GLOBAL_REST_PARAMETERS.axios = axiosInstance;
GLOBAL_REST_PARAMETERS.restURL = "/api/rest/";
If you are using CarbonReact, wire reactBootstrap as described in C6 + CarbonReact State Management.
3) Host the REST endpoint (optional, Express)
import express from "express";
import mysql from "mysql2/promise";
import { restExpressRequest } from "@carbonorm/carbonnode";
import { C6 } from "./shared/rest/C6";
const app = express();
app.set("query parser", "extended");
app.use(express.json());
const mysqlPool = mysql.createPool({
host: "127.0.0.1",
user: "root",
password: "password",
database: "sakila",
});
restExpressRequest({
router: app,
routePath: "/api/rest/:table{/:primary}",
C6,
mysqlPool,
});
4) Query data
import { C6, Actor } from "./shared/rest/C6";
const result = await Actor.Get({
[C6.SELECT]: [
Actor.ACTOR_ID,
Actor.FIRST_NAME,
Actor.LAST_NAME,
],
[C6.WHERE]: {
[Actor.LAST_NAME]: [C6.LIKE, [C6.LIT, "%PITT%"]],
},
[C6.PAGINATION]: {
[C6.LIMIT]: 10,
[C6.PAGE]: 1,
[C6.ORDER]: [[Actor.ACTOR_ID, C6.DESC]],
},
});
Execution Model
flowchart LR
Client["App Code\nActor.Get(...)"] --> Request["restRequest facade"]
Request -->|"mysqlPool/postgresPool configured"| SQL["SqlExecutor"] --> DB[("SQL Database")]
Request -->|"no SQL pool"| HTTP["HttpExecutor"] --> REST["/api/rest/:table"]
REST --> Express["ExpressHandler"] --> SQL
restRequest chooses SQL executor when mysqlPool or postgresPool is present; otherwise it uses HTTP executor.
C6 + CarbonReact State Management
If your app uses CarbonReact, CarbonNode can keep table state in sync automatically after requests.
Set:
import { GLOBAL_REST_PARAMETERS } from "./shared/rest/C6";
GLOBAL_REST_PARAMETERS.reactBootstrap = yourCarbonReactInstance;
State sync behavior:
- HTTP executor path:
GET: updates table state with response rowsPOST: inserts created row(s) into statePUT: updates matching row(s) by primary keyDELETE: removes matching row(s) by primary key
- SQL executor path:
GET: updates table state whenreactBootstrapis set- write sync is typically handled by your websocket/event layer
How C6 identifies rows:
stateKeyis table name (restModel.TABLE_NAME)uniqueObjectIdis table primary keys (restModel.PRIMARY_SHORT)
Per-request escape hatch:
await SomeTable.Get({
/* query */
skipReactBootstrap: true,
});
This lets you opt out of automatic state writes when a call is read-only for the UI or you are running a background sync pass.
Canonical SQL Expression Grammar (6.1.0+)
6.1.0 unifies expression parsing across SELECT, WHERE, HAVING, ORDER, and expression-capable UPDATE/INSERT values.
| Purpose | Canonical form |
|---|---|
| Known function | [C6.FUNCTION_NAME, ...args] |
| Custom function | [C6.CALL, "FUNCTION_NAME", ...args] |
| Alias | [C6.AS, expression, "alias"] |
| DISTINCT | [C6.DISTINCT, expression] |
| Literal binding | [C6.LIT, value] |
| ORDER term | [expression, "ASC" | "DESC"] |
Normative rules:
- Bare strings are references only (
table.columnor valid aliases in context). - Non-reference strings must be wrapped with
[C6.LIT, value]. ASandDISTINCTare wrappers, not positional tokens.PAGINATION.ORDERmust be an array of order terms.- CarbonNode normalizes a top-level
ORDERintoPAGINATION.ORDERfor compatibility, but new code should preferPAGINATION.ORDER. - Use
C6.CALLfor unknown/custom function names.
Removed legacy syntax (throws):
[fn, ..., C6.AS, alias][column, C6.AS, alias]- object-rooted function expressions like
{ [C6.COUNT]: [...] } - implicit string literals in function arguments
ORDERobject-map syntax (now array terms only)
Clause-by-Clause Usage
SELECT with wrappers
import { C6, Actor } from "./shared/rest/C6";
const response = await Actor.Get({
[C6.SELECT]: [
[C6.AS, [C6.DISTINCT, Actor.FIRST_NAME], "distinct_name"],
[C6.AS, [C6.COUNT, Actor.ACTOR_ID], "cnt"],
[C6.CALL, "COALESCE", [C6.LIT, "Unknown"], Actor.LAST_NAME],
],
});
WHERE with literals, BETWEEN, IN, AND/OR
import { C6, Actor } from "./shared/rest/C6";
const response = await Actor.Get({
[C6.WHERE]: {
[C6.AND]: [
{ [Actor.LAST_NAME]: [C6.LIKE, [C6.LIT, "S%"]] },
{ [Actor.ACTOR_ID]: [C6.BETWEEN, [5, 50]] },
{ [Actor.FIRST_NAME]: [C6.IN, [[C6.LIT, "NICK"], [C6.LIT, "ED"]]] },
],
},
});
JOIN
import { C6, Actor, Film_Actor } from "./shared/rest/C6";
const response = await Actor.Get({
[C6.SELECT]: [Actor.ACTOR_ID, Actor.FIRST_NAME],
[C6.JOIN]: {
[C6.INNER]: {
[Film_Actor.TABLE_NAME]: {
[Film_Actor.ACTOR_ID]: [C6.EQUAL, Actor.ACTOR_ID],
},
},
},
});
ORDER and pagination
import { C6, Actor } from "./shared/rest/C6";
const response = await Actor.Get({
[C6.PAGINATION]: {
[C6.ORDER]: [
[Actor.LAST_NAME, C6.ASC],
[Actor.FIRST_NAME, C6.DESC],
],
[C6.LIMIT]: 25,
[C6.PAGE]: 1,
},
});
PAGE is 1-based:
PAGE = 1-> first pagePAGE = 2-> second pagePAGE = 0is coerced to1
UPDATE expression values
import { C6, Actor } from "./shared/rest/C6";
await Actor.Put({
[Actor.ACTOR_ID]: 42,
[C6.UPDATE]: {
[Actor.FIRST_NAME]: [C6.CONCAT, [C6.LIT, "Mr. "], Actor.LAST_NAME],
},
});
Helper Builders
CarbonNode exports typed builders for canonical expression tuples and common literal-safe WHERE / HAVING predicates:
import { fn, call, alias, distinct, lit, eqLit, inLit, notInLit, betweenLit, asc, desc } from "@carbonorm/carbonnode";
import { C6, Actor } from "./shared/rest/C6";
const response = await Actor.Get({
[C6.SELECT]: [
alias(distinct(Actor.FIRST_NAME), "distinct_name"),
alias(fn(C6.COUNT, Actor.ACTOR_ID), "cnt"),
call("COALESCE", lit("N/A"), Actor.LAST_NAME),
],
[C6.WHERE]: {
[Actor.FIRST_NAME]: eqLit("NICK"),
[Actor.LAST_NAME]: inLit(["WAHLBERG", "CHASE"]),
[Actor.ACTOR_ID]: notInLit([1, 2]),
0: {
[Actor.LAST_UPDATE]: betweenLit("2006-02-15", "2006-02-16"),
},
},
[C6.PAGINATION]: {
[C6.ORDER]: [desc(fn(C6.COUNT, Actor.ACTOR_ID)), asc(Actor.FIRST_NAME)],
[C6.LIMIT]: 5,
},
});
Use eqLit(), inLit(), notInLit(), and betweenLit() when the comparison value is a string or other non-reference literal that should be wrapped with C6.LIT automatically. Use asc() / desc() for the common one-direction ORDER terms.
Singular vs Complex Requests
Singular requests (primary key at root) are normalized into complex query format.
await Actor.Get({ [Actor.ACTOR_ID]: 42 });
await Actor.Put({ [Actor.ACTOR_ID]: 42, [Actor.LAST_NAME]: "Updated" });
await Actor.Delete({ [Actor.ACTOR_ID]: 42 });
Behavior:
GETwith missing PKs remains a collection query.PUT/DELETEsingular forms require full PK coverage.
HTTP Query-String Pitfalls
If you are manually building URLs, nested arrays must preserve tuple shape exactly.
Common failure:
WHERE[job_runs.job_type][0]=LIT&WHERE[job_runs.job_type][1]=avm_print- This is interpreted as operator tuple
[LIT, "avm_print"], and fails with:Invalid or unsupported SQL operator detected: 'LIT'
Correct structure:
WHERE[job_runs.job_type][0]==WHERE[job_runs.job_type][1][0]=LITWHERE[job_runs.job_type][1][1]=avm_print
Also ensure ORDER is under PAGINATION:
- correct:
PAGINATION[ORDER][0][0]=job_runs.created_at - compatible but non-canonical:
ORDER[0][0]=job_runs.created_at
Recommendation: use generated bindings + axios executor, not manual URL construction.
Generator Output
generateRestBindings writes:
C6.ts(stable compatibility facade and public entrypoint)C6.generated/core.ts(shared runtime state such asTABLES,COLUMNS,initialRestfulObjectsState, andGLOBAL_REST_PARAMETERS)C6.generated/tables/*.ts(one generated table module per table, including the interface, primary-key type, base model, and REST binding)C6.generated/views/*.ts(one generated read-only view module per SQL view, withGetonly)C6.generated/scoped.ts(scoped database bindings)C6.test.ts(generated test suite)C6.mysqldump.sqlfor MySQL generation, orC6.pg_dump.sqlfor PostgreSQL generationC6.mysqldump.jsonC6.mysql.cnffor MySQL generationC6.<databaseKey>.mysqldump.sqlorC6.<databaseKey>.pg_dump.sqlfor each resolved non-primary config database alias
C6.ts re-exports the selected public symbols from C6.generated/**, so existing imports such as
import { C6, Actor, type iActor, TABLES } from "./rest/C6" remain the public contract. Auto-barrel
tools should exclude C6.generated/** to avoid publishing noisy internals. Correctness does not depend
on that exclusion: re-exporting both C6.ts and an individual generated table module resolves to the
same table export.
SQL views are emitted as readonly relations with RELATION_TYPE: "VIEW" and READ_ONLY: true.
They are registered in TABLES for query composition and VIEWS for view-only discovery, so a
view can be used anywhere a selectable relation is valid, including JOIN; generated REST bindings
only expose Get, and runtime request resolution rejects write methods against read-only models.
Template sources:
scripts/assets/handlebars/C6.ts.handlebarsscripts/assets/handlebars/C6.core.ts.handlebarsscripts/assets/handlebars/C6.table.ts.handlebarsscripts/assets/handlebars/C6.tablesIndex.ts.handlebarsscripts/assets/handlebars/C6.view.ts.handlebarsscripts/assets/handlebars/C6.viewsIndex.ts.handlebarsscripts/assets/handlebars/C6.scoped.ts.handlebarsscripts/assets/handlebars/C6.test.ts.handlebars
SQL Allowlist
To enforce a SQL allowlist in production:
import { GLOBAL_REST_PARAMETERS } from "./shared/rest/C6";
GLOBAL_REST_PARAMETERS.sqlAllowListPath = "/path/to/C6.sqlAllowList.json";
Optional: add a project-specific normalizer for allowlist matching:
import { GLOBAL_REST_PARAMETERS } from "./shared/rest/C6";
GLOBAL_REST_PARAMETERS.sqlQueryNormalizer = (normalizedSql) =>
normalizedSql.toLowerCase();
sqlQueryNormalizer runs after CarbonNode's built-in normalization. Use it to enforce house-style matching (for example lowercase-only allowlist entries).
Allowlist file format:
[
"SELECT * FROM `actor` LIMIT 1"
]
Normalization behavior (important):
CarbonNode normalizes both:
- each SQL entry in your allowlist file
- each runtime SQL statement before matching
So you should treat allowlist entries as normalized query shapes, not exact byte-for-byte logs.
Normalization includes:
- stripping ANSI color codes
- collapsing whitespace
- removing trailing
; - normalizing common geo function names (
ST_DISTANCE_SPHERE,ST_GEOMFROMTEXT,MBRCONTAINS) - normalizing
LIMIT/OFFSETnumeric literals to placeholders - collapsing bind groups (for example
IN (?, ?, ?)->IN (? ×*)) - collapsing repeated
VALUESbind rows to a wildcard row shape
Example (conceptual):
-- runtime SQL
SELECT * FROM `actor` WHERE actor.actor_id IN (?, ?, ?) LIMIT 100
-- normalized shape used for matching
SELECT * FROM `actor` WHERE actor.actor_id IN (? ×*) LIMIT ?
When enabled:
- missing allowlist file -> error
- SQL not in allowlist -> blocked
Practical workflow:
- Run representative queries in tests/integration.
- Collect normalized SQL statements.
- Save them into your allowlist JSON.
- Set
GLOBAL_REST_PARAMETERS.sqlAllowListPath.
Lifecycle Hooks and Websocket Broadcast
Generated models include lifecycle hook groups per method:
beforeProcessingbeforeExecutionafterExecutionafterCommit
Unlike other CarbonORM language bindings, C6.ts is not semi-persistent. Modifications to the C6 object should be done at runtime, not by editing the generated file.
Websocket payloads for writes are supported via:
GLOBAL_REST_PARAMETERS.websocketBroadcast = async (payload) => {
// broadcast payload to your websocket infrastructure
};
Real-time communication explained (no websocket background required)
HTTP is request/response. A browser asks, server answers, done.
Real-time systems add server push: when data changes, the server proactively notifies connected clients so they can refresh or patch state immediately.
In CarbonNode:
POST,PUT,DELETEcan triggerwebsocketBroadcastGETdoes not broadcast- CarbonNode does not run a websocket server for you
- you provide the
websocketBroadcastfunction and route payloads into your existing websocket layer (ws, Socket.IO, SSE bridge, etc.)
Payload shape (high level):
- table + method metadata
- request body
- request primary key (when detectable)
- response row(s) and response primary key when available
Why this matters:
- keeps multiple tabs/users aligned without polling
- reduces stale UI after writes
- enables event-driven cache invalidation (
table + primary key)
Minimal ws example:
import { WebSocketServer } from "ws";
import { GLOBAL_REST_PARAMETERS } from "./shared/rest/C6";
const wss = new WebSocketServer({ server: httpServer });
GLOBAL_REST_PARAMETERS.websocketBroadcast = async (payload) => {
const message = JSON.stringify({ type: "db.write", payload });
for (const client of wss.clients) {
if (client.readyState === 1) {
client.send(message);
}
}
};
Client handling pattern:
- listen for
db.writeevents - inspect
payload.REST.TABLE_NAMEand primary keys - invalidate/refetch relevant queries or patch local state
Testing
Run full validation:
npm test
This includes:
- build
- binding generation
- test suite
Migration Notes (6.x -> 7.0)
generateRestBindings is now config-first and this is a breaking change.
Before (6.x):
npx generateRestBindings \
--user root \
--pass password \
--host 127.0.0.1 \
--port 3306 \
--dbname sakila \
--output ./shared/rest
After (7.0):
npx generateRestBindings \
--config ./rest.config.json \
--output ./shared/rest
Flag migration:
--user->databases[].user--pass->databases[].pass(orpassEnv, recommended)--host->databases[].host--port->databases[].port--dbname->databases[].dbname/databases[].dbnames[]--databases(legacy alias map) -> explicitdatabases[]entries in config- PostgreSQL targets should also set
databases[].dialectto"postgresql".
Behavior changes:
- Config discovery checks
.C6.ts,.C6.json,C6.config.local.json,C6.config.ts, andC6.config.jsonfrom CWD upward. - Guided setup scaffolds ignored
C6.config.local.jsonwith mode 0600 and apassEnvreference (defaultC6_DB_PASSWORD). Export that environment variable before generation; the wizard never collects a password. - Multi-schema aliases are explicit via
dbnamesand emitted asC6.<alias>/C6.<alias>_<dbname>.
Security recommendation:
- Prefer
passEnvover inlinepass. - Keep secret-bearing config files out of source control (
.gitignore), for example:.C6.json.C6.tsC6.config.local.jsonrest.config.jsonrest.config.local.json
Migration Notes (6.0 -> 6.1)
Before:
[C6.COUNT, Actor.ACTOR_ID, C6.AS, "cnt"]
After:
[C6.AS, [C6.COUNT, Actor.ACTOR_ID], "cnt"]
Before:
[C6.PAGINATION]: {
[C6.ORDER]: { [Actor.LAST_NAME]: C6.ASC }
}
After:
[C6.PAGINATION]: {
[C6.ORDER]: [[Actor.LAST_NAME, C6.ASC]]
}
Before:
[C6.ST_GEOMFROMTEXT, ["POINT(-104.89 39.39)", 4326]]
After:
[C6.ST_GEOMFROMTEXT, [C6.LIT, "POINT(-104.89 39.39)"], 4326]
AI Interpretation Contract
Use this section as a strict contract for automated query generation.
carbonnode:
version: "6.1.0+"
grammar:
known_function: "[C6C.<KNOWN_FN>, ...args]"
custom_function: "[C6C.CALL, 'FUNCTION_NAME', ...args]"
alias: "[C6C.AS, expression, 'alias']"
distinct: "[C6C.DISTINCT, expression]"
literal: "[C6C.LIT, value]"
order_term: "[expression, 'ASC' | 'DESC']"
required_rules:
- "Bare strings are references only."
- "Wrap non-reference strings with C6C.LIT."
- "PAGINATION.ORDER must be an array of order terms."
- "Use C6C.CALL for unknown function names."
forbidden_legacy:
- "[fn, ..., C6C.AS, alias]"
- "[column, C6C.AS, alias]"
- "{ [C6C.COUNT]: [...] }"
- "Implicit string literals in function args"
- "ORDER object-map syntax"
Git Hooks
This project uses Git hooks via postinstall:
pre-commit: builds project and blocks commits on build failurepost-push: publishes to npm when version changesnpm installrunspostinstallto ensure hooks are configured
Support
Report issues at:
Security behavior and migration
Version 7.0.0 includes the new repository-scan remediation. Version 7.0.1 also prevents deeply nested expression tokens from triggering recursive string conversion inside request validation; the iterative budget rejects them first. Version 7.0.2 closes the eight verification-scan findings, including SQL/browser transport budgets, MySQL write cancellation, and trusted generator tooling. This major bump reflects stricter request defaults and rejection of previously accepted unsafe or ambiguous inputs. Regenerate bindings and review these changes:
- HTTP lifecycle phases are awaited. A rejected
beforeExecutionhook prevents dispatch. HTTP primary keys must be scalar, nonempty URL segments. Delimiters, percent escapes, control characters, and dot segments are rejected; remaining characters are encoded. - Composite identities use complete payload keys or WHERE with a table-only URL.
/rest/:table/:primaryis rejected for composite-key models, even with complete body keys. - Every supplied pagination object retains a limit: default 100, maximum 1000,
maximum offset 100000. LIMIT/PAGE must be positive safe integers (decimal query-string
values are accepted). Trusted
maxPageSizeandmaxPageOffsetcan adjust these caps. - Generic REST denies custom CALLs unless trusted
restFunctionAllowlistapproves them. Delay, file, lock, and listed side-effect functions remain denied. Trusted direct ORM CALL grammar remains available. REST setsstatementTimeoutMsto 5000 by default: MySQL read execution usesmax_execution_time; PostgreSQL usesstatement_timeout. Previous session settings are restored; PostgreSQL mutations use transaction-local settings. MySQL writes reserve a separate cancellation connection before execution and terminate the target session on deadline. Custom MySQL drivers must supply trustedmysqlCancellation. - All request trees have shared iterative budgets: depth 32, 10000 nodes, 1000 items
per collection, 1 MiB input, 1000 SQL parameters, and 256 KiB generated SQL.
Trusted
queryLimitscan adjust individual budgets; request JSON cannot raise them.maxResponseBytesdefaults to 8 MiB. SQL results and HTTP payloads are checked; Native mysql2/pg receipt is bounded before row parsing; unsupported REST transports fail closed. Browser Axios fetch streams are bounded before decoding/JSON parsing; Node uses the capped HTTP adapter. Custom SQL drivers must exposesqlResponseStream; compressed MySQL needs a decoded stream. HTTP requests retain a 30-second default timeout. - Response cache storage is bounded to 1000 entries, 16 MiB total, 1 MiB per entry, and a nonrenewable 60-second TTL. LRU eviction, expired entries, oversized/unserializable responses, and rejected promises force a fresh request. Existing trusted scopes remain required.
- Generator relation names must map to safe identifiers and noncolliding filenames.
Reserved names, separators, traversal, and symbolic links fail before generated-source writes.
Generated typecheck failures are fatal unless explicitly skipped for a controlled offline workflow.
The compiler is a pinned local runtime dependency. Database clients come from trusted fixed paths
or absolute
--mysql-client,--mysqldump-client,--psql-client,--pg-dump-clientflags. Failed online schema/metadata acquisition is fatal; existing dumps require explicit--no-db 1reuse. - Warning/error string fields escape terminal controls, line breaks, and Unicode record controls.
The October 2026 finding review distinguishes historical findings, intentional SQL grammar, SQL-allowlist mitigations, and fixes.
- GET response caching now requires a nonempty
cacheScopein trusted runtime configuration. Use a scope unique to the authenticated principal, tenant, and permission version, and rotate it when any of those change. Do not take it from request JSON. Keys also distinguish SQL pools/HTTP clients and REST URLs. SQL requests with lifecycle hooks bypass result caching so authorization hooks always run. Both SQL and HTTP GET requests requirecacheResults: trueto enable caching; a scope alone does not opt in. Database aliases also partition cache entries when they share a transport. - Generic Express REST routes exclude generated views by default, including
JOINs and scalar/derived subqueries. To expose an authorized view, set trusted
restViewAllowlist: ['view_name']in the server configuration. Request JSON cannot opt in. Direct server ORM reads of views remain available. GROUP_BYaccepts the same expression grammar as SELECT. A single tuple (for example[C6C.CALL, 'COALESCE', column, [C6C.LIT, 'unknown']]) and a list of expressions are both supported. Bare strings remain references.- UPDATE and DELETE require a nonempty WHERE predicate. Trusted server code may
set
allowUnfilteredWrites: truefor intentional unfiltered writes. A client JSON field cannot grant this permission. URL primary keys constrain complex requests with AND and are always bound as literal values. - SQL allowlisting remains optional and should be configured on production REST
endpoints. The final SQL is checked again after mutable execution hooks.
An allowlist constrains query shapes; applications must still authorize users
and bind ownership/tenant values. Bare strings remain references in the SQL
expression grammar; wrap literal data in
[C6C.LIT, value]or useeqLit. - Express responses omit SQL metadata and internal exception messages. Logs
retain the server error. Request
debugcannot raise the configured log level; INFO SQL logs contain status indicators, with SQL text available at DEBUG. - Websocket broadcasts contain identity/invalidation metadata by default, with
empty REQUEST and no RESPONSE row data. Set trusted
websocketIncludeRows: trueonly for callbacks that authorize recipients and redact sensitive fields. - Dependency fetching rejects traversals exceeding 8 levels or 100 requests and
skips repeated table/filter requests. Pagination
next()advances the page. - Generator credentials use private temporary files and are removed on exit.
Schema-derived names are escaped as TypeScript string literals, including
table, view, and database-scoped templates.
C6_NO_DB=1or--no-db 1uses existing dumps without invoking database tools; CI alone does not disable database generation. Trigger bodies and definers are omitted by default;--includeTriggerDefinitions 1is an explicit opt-in for server-only generated artifacts. Raw schema dumps still contain schema details and should not be shipped to browsers. - Generator expressions such as
restUrlExpression, custom imports, and override expressions are trusted source code. Do not populate them from untrusted input. SQL views remain generated read-only relations; only approve intended view query shapes in the SQL allowlist and enforce caller authorization separately. - The CommonJS export uses a
.cjsextension. Regenerate bindings to receive generator fixes. Existing installed applications do not change merely because this repository's fixes merge.
Explicit MySQL writer registration
Register mysqlWriterPool alongside mysqlPool when reads use a replica:
GLOBAL_REST_PARAMETERS.mysqlPool = guardedReaderPool;
GLOBAL_REST_PARAMETERS.mysqlWriterPool = writerPool;
GET uses mysqlPool (or the writer when no read pool is registered). POST, PUT, PATCH and DELETE acquire mysqlWriterPool, falling back to mysqlPool for existing single-pool applications. The complete mutation lifecycle, including transaction and session settings, stays on that writer connection. Register these trusted options globally or per database; never accept pools from request input. Replica health, replication fences and read-after-write policy belong to the registered pool provider.