Gingee is a comprehensive application server designed to accelerate development by providing a rich set of secure, powerful, and easy-to-use features out of the box. This document provides an overview of the key platform features and the standard library of App Modules.
These are the core architectural features that define the Gingee development experience.
Secure Sandbox Execution
Every server script runs in a secure, isolated environment. This prevents common vulnerabilities like path traversal and protects the main server process from errors or crashes in application code. When app.json → cache.server.enabled is true, Gingee reuses sandboxed module instances (box scripts and box.local_modules) across requests—still invoking the exported handler each time—while preserving the same permission and path jail rules. Disable server cache or use no_cache_regex for live-edit paths; reloadApp drops the instance cache for that app. Bare $g in box code is request-local (ALS); keep gingee(async ($g) => …) on entries. Use $g.locals for writable per-request scratch (not assignments onto $g itself).
Errors: the HTTP request path catches failures of the handler promise (await script() / await gingee(...)) and returns 500 when headers are not yet sent. Detached async work that is not awaited is not part of that promise: an unhandled rejection is logged ([unhandledRejection]) and the process keeps running. Sync uncaughtException is logged ([uncaughtException], optional ALS app name), the engine attempts graceful shutdown, then process.exit(1) — do not assume the process is healthy after a sync fatal. Prefer await, .catch, or the queue module for background side effects. See Threat Model → How not to take down the node.
Response compression
With gingee.json → content_encoding.enabled, static files may be served from a pre-gzipped server-cache entry, and $g.response.send gzip when the raw body is at least content_encoding.size_threshold bytes (default 1024) and the client sends Accept-Encoding: gzip. When cache.client is enabled, static responses include ETag / Last-Modified and support 304 revalidation (alongside long max-age); no_cache_regex still forces no-store.
Whitelist-Based Permissions System
A secure-by-default model where applications must be explicitly granted privileges by an administrator to access sensitive modules like the filesystem (fs), database (db), outbound HTTP client (httpclient), transactional email (email), or generative AI (ai). Isolation is cooperative multi-app (shared process)—see the Threat Model.
Flexible Routing Engine
Gingee features a powerful routing engine with two modes. For regular apps, use the zero-config File-Based Routing. For building RESTful APIs, create a routes.json manifest to enable Manifest-Based Routing with dynamic path parameters (e.g., /users/:id).
Multi-Database Abstraction Layer Write your database logic once and deploy against multiple database systems. Gingee supports PostgreSQL, MySQL/MariaDB, SQLite, MS SQL Server, and Oracle, automatically transpiling queries for the target database.
Modern JavaScript Support (ESM)
Use modern ES Module syntax (import/from) directly in your backend scripts. Gingee uses on-the-fly transpilation to handle this automatically, with no build steps or complex package.json configuration required.
SPA Hosting & Development Workflow
Gingee provides first-class support for modern Single Page Applications (React, Vue, Angular). In development (type: "SPA", mode: "development"), it proxies non-API requests to your frontend's native hot-reloading server for a unified, CORS-free environment. In production, it serves compiled assets from spa.build_path and falls back to spa.fallback_path (e.g. index.html) for client-side routers. Backend APIs continue to run from the secure box/ folder. See the SPA Developer's Guide.
Application Lifecycle Management
A privileged platform module allows for full lifecycle management, enabling the creation, packaging (.gin), installation, upgrading, backup, and rollback of applications, a powerful module accessible to designated privileged apps as configured in gingee.json. The default Gingee Glade Admin Tool is one such privileged app.
App Store with Interactive Installation
The gingee-cli provides commands to browse and install applications from any decentralized "GStore" - the Gingee app store (a static server hosting a gstore.json manifest). The installation process is fully interactive, reading a permissions manifest (pmft.json) and database requirements directly from the app package to guide the administrator through a secure, one-command setup.
Hierarchical & Context-Aware Logging
Each app writes to its own structured JSON log file within its private box directory, while logs are also forwarded to a central, timestamped server log for a complete system overview.
Resilient Distributed Caching The server provides a centralized, pluggable caching service. Use a dependency-free in-memory cache for local development, or switch to a Redis backend for horizontally scaled production deployments by changing a single line of config.
Transactional Email (email Module)
Send mail through a provider adapter (SendGrid in v1, plus a console logger for local dev). Config is a single object in app.json (optional defaults in gingee.json). Apps call email.send(message) or email.sendWithConfig(runtimeConfig, message) for a one-transaction override. Requires the email permission.
Outbound Messaging (messaging Module)
Send SMS/MMS/WhatsApp through a provider adapter (Twilio in v1, plus mock and console loggers for local dev). Set channel: 'whatsapp' for WhatsApp (optional whatsapp_from in config); use contentSid / contentVariables for Twilio Content Templates. Config is a single object in app.json (optional defaults in gingee.json). Apps call messaging.send(message) or messaging.sendWithConfig(runtimeConfig, message) for a one-transaction override. Requires the messaging permission. Sample app: ginbon (/ginbon/ — contacts, templates, compose with SMS/MMS/WhatsApp, history).
Engine cache invalidate (cache.invalidateSysCache)
Non-privileged apps with the cache permission can drop static / transpile / instance caches for path prefixes under their own web/box (after unzip/codegen) without platform.reloadApp. From an isolation worker the call is forwarded to the master (static cache + fan-out to all workers). Does not reinit messaging/email/ai. Schedule-only refresh: require('scheduler').rebind(names?) with the scheduler permission.
Generative AI (ai Module)
Chat, streaming completions (chatStream), multimodal image/file parts, document parsing/OCR, and content moderation behind a provider adapter (mock, gemini; xai planned). Single hybrid config (gingee.json / app.json) with optional per-call { config } override. Streaming apps use $g.response.startStream / writeSSE / endStream. Requires the ai permission.
Streamed HTTP Responses
Server scripts can stream progressive output (for example Server-Sent Events for AI tokens) via $g.response.startStream(), write() / writeSSE(), and endStream(), without exposing Node’s raw response object to the sandbox.
CRON Scheduler
Apps declare recurring jobs in app.json → schedules (script, URL, or queue handoff). The in-process scheduler is off by default (gingee.json → scheduler.enabled). Multi-server: enable on one node, or set scheduler.coordination.driver: "redis" with sibling scheduler.redis (same connection shape as queue/cache) so every node can enable the scheduler with single-fire locks (or global leader). Glade → Schedules lists jobs on this node and supports Run now. Requires the scheduler permission (httpclient for URL; queue for queue targets). Overlap policy is skip; jobs are skipped while the app is in maintenance.
Request & Outbound Limits
Process-wide and per-app concurrency caps, request wall-clock timeouts, stream idle/hard timeouts, and default httpclient outbound timeouts (gingee.json → limits). Overload returns 503; request budget expiry returns 504. Apps may only tighten limits in app.json.
Egress / SSRF policy
Default egress.mode: protected blocks outbound calls to loopback, private, link-local, and cloud metadata targets for httpclient and scheduler URL jobs; DNS is checked and redirects are re-validated. Deny → 403 EGRESS_DENIED. Use allow_cidrs / allow_hosts for intentional internal access, or mode: "off" for local dev only.
Config secret references
Use env:VAR_NAME or file:… (under secrets.file_roots) in app.json / gingee.json for JWT, DB passwords, API keys, etc. The engine resolves them at load; sandbox scripts still cannot access host process.env.
Prometheus Metrics:
Engine-scoped /metrics (default) in Prometheus text format for scrapes. Default localhost-only (metrics.allow_from); optional bearer token. Series cover HTTP scripts, concurrency rejects, egress denials, scheduler runs, WebSocket upgrades/connections/fan-out, queue/DLQ counters, and process gauges—not cross-app data APIs for untrusted code.
Audit Trail:
Append-only JSONL log (audit.path, default logs/audit.jsonl) for permission grants, app lifecycle (install, upgrade, reload, delete, rollback), scheduler Run now, queue DLQ retry/discard, and log list/read metadata. Complements application request logs.
Optional feature packages:
Heavy or specialized npm packages ship as optionalDependencies: sharp (image), non-SQLite SQL drivers (pg, mysql2, mssql, oracledb), chart/canvas, pdfmake, SendGrid, Twilio, and Gemini SDK. A normal npm install still tries to install them, but a failed native build does not fail the whole install. For a slimmer tree use npm install --omit=optional, then add only what you need (npm install sharp pg pdfmake twilio, etc.). Missing packages surface as FEATURE_NOT_INSTALLED when an app actually uses that feature. SQLite, console email, mock messaging, and mock AI remain available without optionals.
Process isolation (opt-in):
With isolation.mode: "process", selected apps run server scripts in a child process (IPC). Public HTTP ports stay on the master. Privileged apps (e.g. Glade) stay in-process. Supports buffered and SSE responses (including AI streams), solo workers (isolation.apps / app.json) or isolation groups (shared worker—group membership alone is enough; no duplicate apps list required), auto-restart with backoff after unexpected crash, request-timeout cancel (IPC + AbortSignal; optional worker kill), and worker-side re-init of ai / email / messaging from app.json. See Server Config → isolation.
WebSockets (opt-in per app):
Bidirectional real-time connections on the same public HTTP(S) port (ws library). Declare app.json → websockets (handler + optional auth), grant the websockets permission, then use require('websockets') for rooms/broadcast. Multi-tenant apps should use tenantRoom(tenantId, name). Connections terminate on the master (not isolation workers). Multi-node: set websockets.fanout.driver: "redis" and sibling websockets.redis so toRoom / toApp reach sockets on every master. Prefer SSE for one-shot AI token streams. Sample app: ginchat (/ginchat/). See Server Config → websockets.
Background job queue (queue module):
Enqueue deferred work with require('queue').add(name, payload) (permission queue). Handlers under box/jobs/{name}.js receive $g.queue (id, payload, attempt). Drivers: memory (default, single-node) or redis (multi-node, durable). Retries with backoff; exhausted jobs go to a dead-letter queue (DLQ). Glade Queue / DLQ: live jobs (running/waiting/pending/delayed, auto-refresh) and DLQ (retry/discard). CRON may use target.type: "queue". See Server Config → queue.
Module override (permission module_override):
Trusted apps may call $g.overrideModule(specifier, boxRelativePath) so that for the rest of the request matching require(...) (protected/other bare names, relative or box-root paths) loads an in-box wrapper. Restricted/forbidden names cannot be overridden. Wrappers use normal jailing; override map is off for the wrapper tree (no recursion). Sample: web/appsandboxtest/ (full matrix + deny cases). See Permissions Guide → Module overrides.
Project local modules (box.local_modules):
Server-wide sandboxed require roots for project-owned libraries when Gingee is installed under node_modules. Default is [] (opt-in). Configure e.g. ["./local_modules"]; .js only; platform modules/ always wins over local roots; not part of .gin app packages. Included in the per-app sandboxed instance cache when cache.server is on. Samples: web/appsandboxtest/ (sandbox_kit), web/perftest/ (mylib/store). See Server Config → box.local_modules.
startup_scripts in their app.json to run one-time initialization logic, such as database schema migrations or cache warming, when the server starts or after an app is installed/upgraded. A failed startup script prevents that app from being registered (server and other apps continue).
Gingee comes "batteries-included" with a rich standard library of modules. These can be required by name (e.g., require('crypto')) from any sandboxed server script.
gingee
The core middleware and context provider. Entry scripts use await gingee(async ($g) => { … }). Inside that handler, bare $g / globalThis.$g is also available to required box modules (live, request-local Proxy). $g.locals is a fresh writable object every request for app scratch state. Sandbox console.* maps to the app Winston logger (box/logs); prefer $g.log. Handles automatic request body parsing.
cache
A secure, multi-tenant facade module for application data caching. It provides a simple API (get, set, del, clear) and automatically namespaces all keys to ensure data isolation between apps.
db
The unified database interface. Provides a consistent API (query, execute, transaction) for interacting with any configured database.
email
Transactional email via provider adapters (sendgrid, console). Config from gingee.json / app.json, plus sendWithConfig for per-transaction overrides. Permission-protected.
messaging
Outbound SMS/MMS/WhatsApp via provider adapters (mock, console, twilio). Same single-config + send / sendWithConfig pattern as email; WhatsApp via channel + optional Content Templates. Permission-protected. Sample: web/ginbon/.
ai
Generative AI (chat, streaming chatStream, multimodal parts, document parse/OCR, content moderation). Providers: mock, gemini (v1); xai (Grok) planned P1. Permission-protected; per-call config override supported.
fs
A secure, virtualized filesystem wrapper. Jails all file and folder operations to an app's private box or public web scope, preventing path traversal attacks. Includes read/write helpers, readJSON / writeJSON (sync and async), directory listing (readdir, listFiles, listDirs), recursive walk (includeDirs / maxDepth; results relative to the walked folder), and stat. Relative paths (no leading /) resolve to the executing gbox script directory; leading / is scope-root.
httpclient
A powerful wrapper for making external HTTP(S) requests: get, post, put, patch, and delete. Body-bearing methods share postType content types (JSON, form, text, XML, multipart). It handles redirects, HTTPS, egress/SSRF policy, outbound timeouts, and intelligently processes response bodies into strings or buffers.
formdata
A simple factory module for creating multipart/form-data bodies for file uploads via the httpclient.
zip
A utility for creating and extracting zip archives. It can operate on buffers or files and has secure defaults for cross-scope operations.
image
A high-performance module for server-side image manipulation. Wraps the optional sharp package to provide a secure, chainable API for resizing, filtering, and format conversion. Install sharp (or install without --omit=optional) when using this module.
html
A server-side web scraping and parsing module. Wraps cheerio to load and query HTML from strings, files, or remote URLs.
qrcode
A generator for both 2D QR Codes (via qrcode()) and traditional 1D barcodes (via barcode()). It can output generated codes as a PNG Buffer or a DataURL.
chart
A server-side chart rendering engine. Wraps Chart.js to create beautiful, modern charts as PNG images from a standard JSON configuration.
dashboard
A powerful composition engine for creating multi-chart dashboards. It uses a JSON grid layout to render multiple charts into a single, unified image.
pdf
A high-level PDF generation module. Wraps pdfmake to create complex, multi-page documents with flowing layouts, tables, and images from a declarative JSON definition.
auth
JWT toolkit (auth.jwt.create / verify): HS256, exp/iat, optional iss, secret from app jwt_secret or server gingee.json → jwt.secret (supports env: / file: refs). Per-call { secret, iss } overrides allowed.
crypto
A comprehensive cryptographic library. Provides tools for hashing, HMAC, secure password management (argon2), symmetric encryption (AES-2GCM), and random string generation.
uuid
A dependency-free utility for generating and validating RFC 4122 v4 UUIDs.
utils
A large "standard library" of general-purpose helpers, organized into namespaces: rnd (random data), string (manipulation), validate (data validation), and misc.
encode
A unified module for all common encoding and decoding needs, including base64, hex, uri components, and html entities.
platform (Privileged)
The privileged, admin-level module for the Glade Admin Tool. It provides the APIs to manage the full lifecycle of all applications on the server.