Config
What the deployment is. The class is the schema of the file: an unknown key is an error, and secrets live in separate files.
this.secret( "mail.passwordFile" )A TypeScript backend for people who build applications. Secure by default, small by design: routes, sessions, access rights, models, Postgres or SQLite, workers and logs in one package, written together.
npm install @r-libre/z4jsMost Node backends start as a blank Express app and grow by accretion.
The main concepts are deliberately few. Use TypeScript and Node when they already solve the problem, and add an abstraction only where it earns its place.
What the deployment is. The class is the schema of the file: an unknown key is an error, and secrets live in separate files.
this.secret( "mail.passwordFile" )What the database holds. A model manages a table and the queries on it: SQL is written there, nowhere else.
notesModel.get( id )What a resource answers. An object that only notes its routes: created anywhere, tested alone, mounted in several groups.
this.get( "/item/:id", … )Who may reach it. A prefix and a decision, guarded or unprotected, written in the main.
RouteGroup.guarded( … )What a user may do. Four actions per resource, nothing else, checked in every handler.
notes/createWho the user is. Opaque tokens, no cookies, refresh tokens rotated on every use.
sessions.guardWhat runs beside the requests. Classes registered by name, messages both ways, named mutexes.
stats.call( "count", … )What happened. One line per event: a stable name, then the data in JSON.
req.log.info( "note.created" )A group is either guarded or unprotected, and you have to say which one. An open route stands out in review instead of hiding behind a forgotten middleware.
const api = RouteGroup.guarded( "/api", sessions.guard )
.add( "/notes", new NotesEP( deps ) )
.add( "/live", live );
const auth = RouteGroup.unprotected( "/auth" )
.add( "/", sessions.endPoints );
await serve( {
config, logger,
groups: [api, auth],
statics: [{ path: "/", folder: config.www }]
} );Security is not a chapter at the end of the documentation. It is what happens when you write nothing special.
Anything not explicitly allowed is refused. The client gets a status and a short message, never an internal detail. Every value from a client is checked before you use it.
Opaque tokens, only their SHA-256 hash stored. 15 minute access tokens, refresh tokens rotated on every use: a reused one ends the session. A sensitive route adds a step-up filter.
this.del( "/item/:id", this.on_delete,
{ filter: sessions.stepUp } );
// without a recent confirmation of identity:
// 403 step-up required
An import creates, so it needs notes/create: no right is ever invented for a feature. In debug mode, a handler that forgets to check access is reported.
One central handler: the cause goes to the log, never to the response. Security events come from a closed list, never filtered, in their own file.
throw new HttpError( 404, "unknown note" );auth.login.failed · auth.unauthorized · auth.stepup.failedOne package provides them, written together, with the same rules everywhere.
A handler is a method. paramValue, bodyValue and queryValue read one named value, convert it, check it, and return the right TypeScript type; a structured object goes through a Shape. A missing, malformed, too long or out of range value is a 400 that names the parameter and never echoes its value.
async on_update( req: Request, res: Response ) {
await this.need( req, "notes/update" );
const id = this.paramValue( req, "id", "uuid" );
const changes = noteShape.parse( this.bodyValue( req, "note", "object" ) );
await notesModel.update( id, changes );
res.json( {} );
}Describe an object once, validate it everywhere: a shape has no Node or browser dependency, so the server and the client share the same one. Only the declared fields are kept, and a forgotten field fails to compile. A refused value is a 400 that names the field, never its value. Never mandatory.
import { Shape } from "@r-libre/z4js/shape";
interface NoteText {
title: string;
text: string;
}
// what a client may change in a note
export const noteShape = Shape.object<NoteText>( {
title: Shape.string( ).trim( ).maxLen( 100 ),
text: Shape.string( ).maxLen( 10_000 ),
} );
const note = noteShape.parse( data ); // NoteText, or ShapeError: "title": too long (max 100)
const changes = noteShape.parse( data, true ); // Partial<NoteText>: only the fields received
const notes = noteShape.parseArray( data ); // NoteText[]A model is the abstraction of the database: SQL is written in models, nowhere else. It manages one table, or a few, and the queries on it are its methods: a handler calls notesModel.get( id ) and gets a typed object back. The model also creates its table and migrates it at startup.
// the notes table
export class NotesModel extends Model {
constructor( ) {
super( "notes", 40 );
}
async get( id: UUID ): Promise<Note> {
const [note] = await sql<Note[]>`select * from notes where id = ${id}`;
return note;
}
async get_from_author( author: string ): Promise<Note[]> {
return sql<Note[]>`select * from notes where author = ${author}`;
}
async update( id: UUID, changes: NoteText ): Promise<void> {
await sql`update notes set ${sql( changes, "title", "text" )} where id = ${id}`;
}
}
export const notesModel = new NotesModel( );Refused unless declared. The file arrives with the request of the action, so access is checked before a single byte is read. Each file field has its size limit, files are streamed to disk under a random name, and whatever is not kept is deleted when the answer is sent.
async on_import( req: Request, res: Response ) {
await this.need( req, "notes/create" ); // before reading a single byte
const { data } = await this.filesOf( req, {
data: { maxBytes: 1_000_000, types: ["text/csv"] },
} );
const comment = this.bodyValue( req, "comment", "string", { required: false } );
// otherwise deleted at the end of the request
await data.keep( join( config.data, "imports", data.id ) );
res.status( 201 ).json( { id: data.id } );
}A worker is a class and a name, running in a thread of its own. Starting one gives the object you talk to: post, call, broadcast, on. A class can be started several times, each worker with its name and its own data: one device, one worker. A worker receives its messages one at a time in onMessage, or reads them itself in its loop to stay reachable in the middle of heavy work. A crashed worker is logged, its calls fail and its mutexes are released.
// one worker per device: scans it without end, and stays reachable between two scans
class Device extends Worker {
private link: Link;
private values: number[] = [];
onStart( ) {
const { ip } = this.data as { ip: string };
this.link = openLink( ip );
}
onRun( ) {
let msg: WorkerMessage;
while( !this.signal.aborted ) {
if( msg = this.peekMessage( ) ) { // never waits, sees the stop too
const { address, value } = msg.data as { address: number, value?: number };
if( msg.type === "read" ) {
msg.reply( this.values[address] ); // answers the call
}
else if( msg.type === "write" ) {
this.link.write( address, value );
}
}
this.values = this.link.scan( ); // heavy, synchronous
}
}
onStop( ) {
this.link.close( );
}
}
Worker.register( "device", Device );
// main.ts: one device, one worker
const press = await workers.start( "device", { name: "press", data: { ip: "10.0.0.5" } } );
const oven = await workers.start( "device", { name: "oven", data: { ip: "10.0.0.6" } } );
press.post( "write", { address: 12, value: 1 } );
const value = await oven.call( "read", { address: 3 } );A channel notes its WebSocket endpoints and is mounted in a group, like end points. In a guarded group, the client asks for a ticket with a POST, then opens the socket within one second: the ticket is one-time, bound to the endpoint and the user. Messages of one socket are processed one at a time, in order, so per-socket state needs no lock. To push events, the channel keeps its open sockets and gives the end points a method to call.
// live notifications of the notes
export class LiveChannel extends Channel {
private readonly sockets = new Set<WSocket>( );
constructor( ) {
super( );
this.route( "/notes", {
onOpen: socket => { this.sockets.add( socket ); },
onMessage: ( ) => { }, // the clients only listen
onClose: socket => { this.sockets.delete( socket ); },
} );
}
// called by the end points
notify( event: object ) {
for( const socket of this.sockets ) {
socket.send( event );
}
}
}
// POST /api/live/notes → { ticket }
// wss://host/api/live/notes?ticket=… → socketPostgres through postgres.js for sites, SQLite through node:sqlite for small projects and desktop apps. Both are written the same way, in the models, with tagged templates, and values are always bound. No ORM, no query builder.
const [note] = await sql`select * from notes where id = ${id}`;await sql`insert into notes ${sql( note )}`;await sql`update notes set ${sql( changes, "title", "text" )} where id = ${id}`;Five packages, that is all. No ORM, no validation library, no logger, no session store, no JWT library, no upload middleware. Sources are published as TypeScript, as is: what you debug is what was written.
z4js keeps the daily work short: readable logs, an API description read from your sources, and threads you can actually debug.
$ git clone https://github.com/rlibre/z4js
$ cd z4js/demo/frontend
$ npm install && npm run build
$ cd ../backend
$ npm install && npm run build
$ npm run start:log
# a notes application: z4js backend, x4js frontendz4js ships an AI guide (the rules) and an AI context (the API). Agents can also inspect the TypeScript sources shipped in node_modules/@r-libre/z4js.
x4js is the UI counterpart of z4js: the same philosophy on both sides. Plain TypeScript classes, very few dependencies, and code that runs when you call it. More than 50 components for dense, professional interfaces.