MongoDB
Official sources are open to Staxis GitLab group members:
how to join and view the code.
Repository:
MongoDB development
Versions:
tags
and releases
Description
The mongodb layer manages a local MongoDB process belonging to the current Staxis project and the clients used to access it. It starts or reconnects to that process, authenticates the project's permanent Super Admin, and manages scoped access tokens and temporary user sessions. Its manifest.label and manifest.typology are both mongodb.
Built-in hooks provide database, collection, document, and nested data operations. The optional HTTP API connects requests to those hooks through the authorized session's client. Staxis does not include an interactive MongoDB shell or CLI management panel; configuration and the supplied APIs are the layer's integration paths. External MongoDB administration tools remain separate. MongoDB Atlas and other remote database services are outside this local process lifecycle.
Read before flight
-
We strongly suggest preparing a private project secret before the first real startup and backing it up securely with the database recovery material. Keep it stable: it determines the Super Admin identity and the cipher used for application tokens.
-
We suggest reviewing the Guardian permissions supplied by this pack. allowBareDeps and allowOpaqueExecution enable its driver and trusted mongod executable; these switches apply to the assembled application. Keep dependency and filesystem rules aligned with your deployment. Shell command strings remain denied.
-
We suggest keeping role-provisioning keys in trusted backend or local administration flows, protecting the HTTP API with your application's access policy and HTTPS, and avoiding token logging. The browser API tester is a development aid, not a public provisioning panel for permanent Vault keys.
-
We suggest sizing client pools together with the expected number of active sessions. maxPoolSize limits each client pool, not the total connections across all session clients. Keep database storage outside public static directories and application source scanning, and plan backups for the stored data.
Requirements and Installation
The manifest declares serverApp, httpListener, httpStatics, and the httpRestParser library. The layer also needs the mongodb npm driver and the mongod database server installed on the host. Install the pack through the Manager:
manager -> install -> mongodb
Make httpRestParser available before mongodb and register serverApp before the layer mounts its routes. Place httpListener after the route providers so the HTTP application is assembled before it starts listening. See the HTTP Series for that flow. serverApp's manifest permits must include the requesting pack label mongodb; the supplied manifest already includes it.
mongod must be available through PATH or a trusted executable path. The selection order is config.database.mongodb.dbbinary, then MONGOD_BINARY when dbbinary is unset, then mongod. The supplied dbbinary value is mongod. You do not need mongosh to provision the Super Admin through the automatic bootstrap described below.
Files Map
| File | Purpose |
|---|---|
| manifest.json | Declares the mongodb label and runtime slot, and required packs |
| configs.js | Provides database, client, API, token, and Guardian defaults |
| main.js | Coordinates the lifecycle and holds the permanent Super Admin project secret |
| mongodb.mainConnection.js | Starts or reconnects to the project process and authenticates the main client |
| mongodb.sessionManager.js | Manages access tokens, revocation, temporary MongoDB users, and session clients |
| mongodb.mountRoutes.js | Registers the configured HTTP routes through serverApp |
| mongodb.mountRoutes.router.js | Parses requests and maps authorized sessions to hooks |
| hooks-sessions/ | Token creation, inspection, revocation, and session management |
| hooks-database/ | Database lifecycle and maintenance operations |
| hooks-collections/ | Collection operations |
| hooks-documents/ | Document operations |
| hooks-data/ | Reads and changes nested document data |
| hooks-methods/ | Internal support methods, including retained legacy helpers |
| README.md, readme.api.md, readme.extend.md | Original setup, API, and extension guides |
| .fomap | Lists the resources managed by pack installation and export |
Configuration
In the project's config.js, database settings belong to config.database.mongodb. Merge this baseline into the exported config object, preserving the other settings supplied by the pack. The example uses its default process, token, and pool values.
// config.js -> config (merge into the exported object)
database: {
mongodb: {
dbapis: 'api-database',
dblogs: false,
tokenTTL: 24 * 60 * 60 * 1000,
blacklist: 'statical',
blackListTTL: 24 * 60 * 60 * 1000 + 5 * 60 * 1000,
dbpath: 'mongodb-phsfl',
dbhost: '127.0.0.1',
dbport: false,
dbbinary: 'mongod',
dbbootstrap: true,
dbweb: true,
dbClientOpt: {
directConnection: true,
minPoolSize: 0,
maxPoolSize: 10
}
}
}
| Option under config.database.mongodb | Behaviour |
|---|---|
| dbpath, dbhost | Project storage directory and the interface used by the local process; supplied as mongodb-phsfl and 127.0.0.1 |
| dbport | false selects and persists a free local port; a numeric value requires that port |
| dbbinary | Trusted executable name or path for mongod |
| dbbootstrap | true starts the project process when needed and requests verified shutdown on detach; false requires an externally started process |
| dbweb, dbapis | Enable the HTTP API and choose its route root; defaults produce /api-database/ |
| tokenTTL | Default application-token lifetime in milliseconds; false or -1 disables expiration unless explicitly set for the token |
| blacklist, blackListTTL | runtime keeps revoked-token hashes in memory; statical persists them. Retention uses milliseconds and does not release a revocation before token expiration |
| dbClientOpt | MongoDB driver options used for the main and session clients, including the limits of each client pool |
| dblogs | Controls the pack's operation-result logging |
Guardian settings belong to config.engineopt.guard. The pack supplies dependency rules, filesystem access for mongodb-phsfl and system-temp, and scanning exclusions for MongoDB storage. If you change the storage path, update those rules too. The API path exclusion for httpKindness belongs to config.serveropt.notKindness; update it if you change dbapis.
The older flat config.database layout is accepted for migration; use config.database.mongodb for new configuration. Legacy dbauth and dbband fields are not active authentication or bandwidth controls. Authentication follows the project identity and session flow described here.
Project Process and Ownership
mongod is the database server process; MongoClient is the Node.js client used to connect to it. The layer manages the project process and its main client, then creates separate clients for authorized user sessions. A running process is checked against the expected storage path, port, and bound interface. Its PID alone is not accepted as ownership proof.
mongodb-phsfl means MongoDB Process Hosted Files. It contains the database server's stored data and log, not application source. The selected automatic port is tracked separately in system-lrpcks/mongodb/.cache. With persistent revocation enabled, token hashes and expiration values are stored in mongodb-phsfl/.staxis-mongodb-blacklist.csv.
Permanent Super Admin Identity
Before the first real startup, replace #SUPER_ADMIN_CIPHER_HASH in system-lrpcks/mongodb/main.js with a private 32-byte hexadecimal project value. If you need, the following command generates a new value; run it in a trusted local environment and keep its output private:
node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))"
The value is a permanent secret seed, not two credentials joined together. The layer uses two separate HMAC-SHA256 contexts to derive a deterministic username and password. It reconstructs the same identity in memory at each start without prompting for or printing those credentials. No Super Admin Vault entry is required. Follow the project integrity setup after customizing the pack source.
Keep the seed stable and private for the lifetime of the database; do not reuse it in another project. It also determines the secret used to encrypt application access tokens. Changing it derives a different MongoDB identity and makes existing tokens unreadable; restoring the original seed restores that derivation. Changing it is not an automatic account or token migration.
First Startup with Automatic Bootstrap
With config.database.mongodb.dbbootstrap=true, the first startup of a new project database follows this sequence:
Prepare the permanent project seed and the database configuration.
Start Staxis. The layer starts mongod with authentication enabled if the project process is inactive.
The layer derives its Super Admin identity and creates that MongoDB user with the root role on admin.
It reconnects with that identity, verifies process ownership, and initializes sessions and configured routes.
Initial user creation uses the MongoDB localhost exception, which applies only while the database instance has no users or roles. The layer restricts automatic provisioning to a process it started. It does not take over an existing database with unrelated accounts. This creates the infrastructure Super Admin, not an application administrator token.
Starting the Process Outside Staxis
Use this path after the project database has been bootstrapped with the same permanent seed. Set config.database.mongodb.dbbootstrap=false and configure a fixed host, port, and storage path:
// config.js -> config (merge into the exported object)
database: {
mongodb: {
dbbootstrap: false,
dbhost: '127.0.0.1',
dbport: 27017,
dbpath: 'mongodb-phsfl'
}
}
Start mongod externally with the matching settings. For example, replace the absolute project path below with your own; on Windows use quoted Windows paths and mongod.exe when needed:
mongod --dbpath "/absolute/project/path/mongodb-phsfl" --bind_ip 127.0.0.1 --port 27017 --auth --logpath "/absolute/project/path/mongodb-phsfl/mongod.log" --logappend
Staxis still authenticates its derived identity and checks the process configuration. In this mode the host owns process startup and shutdown; detaching the layer closes its clients and leaves the external database process running.
Vault Role Keys and Application Tokens
The MongoDB Super Admin, a role-provisioning key, and an application access token serve different purposes. The Super Admin owns the layer's infrastructure connection. Independent Vault child keys authorize token creation for one of the four application roles:
KEY:MONGODB:ADMIN <private-random-value>
KEY:MONGODB:MANAGER <private-random-value>
KEY:MONGODB:EDITOR <private-random-value>
KEY:MONGODB:READER <private-random-value>
Generate independent private values and add them through the trusted Vault-management flow. The layer does not generate or write these entries into .keys. A missing role key disables that role's direct provisioning path; it does not disable ordinary delegation from an authorized session. In a trusted provisioning request, levelVaultKey carries the matching role key. Never send that permanent key to a public browser.
Normal delegation uses approvalToken from an active higher-level session. It can create only lower roles, and its database and collection grants must cover the requested scope:
admin -> manager, editor, reader
manager -> editor, reader
editor -> reader
reader -> none
The first application administrator is provisioned separately using KEY:MONGODB:ADMIN. The resulting accessToken identifies an application user with a role, data grants, and expiration; opening a session creates the corresponding MongoDB user client. Closing a session and revoking a token are separate operations.
First Staxis Administrator
After the MongoDB project Super Admin has been verified and KEY:MONGODB:ADMIN exists, create the first application administrator token from a trusted backend or local administration script. The Super Admin created during bootstrap does not automatically create this application token.
This example uses the default API root and a local HTTP listener. Adjust base to your listener. MONGODB_ADMIN_PROVISIONING_KEY represents a private, server-side way to retrieve the value of KEY:MONGODB:ADMIN; the layer does not automatically populate that environment variable. Add any credentials required by your application's upstream access policy.
// Run in a trusted Node.js administration script, not in a public browser.
const base = 'http://127.0.0.1:3000'
const levelVaultKey = process.env.MONGODB_ADMIN_PROVISIONING_KEY
if (!levelVaultKey) {
throw new Error('The private MongoDB admin provisioning key is missing')
}
const createResponse = await fetch(base + '/api-database/create-token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: 'project-admin',
role: 'admin',
grants: [{ database: '*', collections: ['*'] }],
expiresAt: false,
levelVaultKey
})
})
const created = await createResponse.json()
if (!createResponse.ok || created.errors || typeof created.payload !== 'string' || !created.payload) {
throw new Error(created.message || 'MongoDB admin token creation failed')
}
const accessToken = created.payload
Here grants covers all databases and collections, and expiresAt=false deliberately creates a non-expiring administrator token, as in the original provisioning example. Choose narrower grants or a future Unix timestamp in milliseconds when required by your policy. Store the resulting accessToken privately; do not log it or distribute the permanent levelVaultKey to clients.
Open the runtime session with the returned accessToken. Continue in the same script:
const openResponse = await fetch(base + '/api-database/open-my-session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ accessToken })
})
const opened = await openResponse.json()
if (!openResponse.ok || opened.errors) {
throw new Error(opened.message || 'MongoDB admin session opening failed')
}
// Supply accessToken in the payload of subsequent protected database requests.
Protected database operations require that opened session and the same accessToken in their request payload. Once the administrator session is active, its token can be used as approvalToken to delegate lower roles within its grants. Closing a session does not revoke its token; revoke-token is the separate revocation action.
The browser API tester is for development. Keep permanent Vault role keys out of publicly exposed browser forms and frontend JavaScript; initial provisioning belongs to a trusted flow.
Public Layer Bundle
The attached layer publishes only the following status and routing information:
| Asset | Meaning |
|---|---|
| routing | The mounted route base and router reference, or false when unavailable |
| webready | Whether the HTTP route surface is ready |
The main client, session clients, Vault secrets, hooks, and access tokens are not exposed in this public bundle. Database operations use the layer's supplied API and authorized session flow.
Documentation
The advanced guides and source repositories require membership of the Staxis GitLab group. Complete Staxis onboarding: connect your GitLab account, request group access, and wait for approval. Then open the resources while signed in with that same account. See Repository Access for the full procedure.
The following overview helps you choose the relevant guide. Request fields, complete examples, result details, and implementation notes remain in the original Markdown files.
-
README.md: Setup and Project Identity
This page is the HTML adaptation of the pack's README.md. Its installation, configuration, project identity, first administrator, and lifecycle sections have been brought into this manual above. Use the original Markdown to consult the source guide.
-
readme.api.md: Current API Usage
readme.api.md explains how to call the current public API: the route base, the errors/message/payload response format, token authorization, and the active-session requirement. It includes the first administrator flow, operation families, and examples for reading and moving nested data. Start here when implementing requests in your application.
Its data-path overview covers nested object keys, ID-based selection, and array positions with INDEX=N. It also describes operation-specific restrictions, such as move-data rejecting wildcard array positions. Use this guide to understand the pack's path syntax before composing nested operations.
-
readme.api.table.md: Session Routes and Hook Details
readme.api.table.md combines a current session-route summary with the older Historical hook details reference. Use it to look up individual operations and their detailed notes. The index below gives only names and short descriptions, using current route names. Document and data routes absent from the historical table are covered by the current API guide.
Historical host and auth fields and the get-database-list name predate the current session flow. Follow readme.api.md and the current hook implementation for request fields and authorization. All protected database, collection, document, data, and test operations need an accessToken whose session is already active. The test endpoint checks the protected API flow.
Token and Session Management
Endpoint or Hook Summary create-token Create an encrypted access token for a role and data grants, using a matching Vault role key or an authorized higher session revoke-token Revoke a token and close its active session, with self-revocation or authorized higher-role approval inspect-token Inspect a restricted token identity and expiration state; available to authorized admin and manager roles open-my-session Open or refresh the token owner's runtime MongoDB session close-my-session Close the owner's session without revoking the access token kill-session Let an authorized admin or manager close a covered lower-level user session list-sessions List the active-session summaries visible to the requesting admin or manager Database Main Hooks
Endpoint or Hook Summary create-database Initialize a database with its first collection destroy-database Drop a database and its contents open-database Run the retained database-open operation; application access still requires an active token session close-database Run the retained database-close operation; use close-my-session for the token owner's session database-list List databases; named get-database-list in the historical table export-database Export a database as a ZIP containing BSON dump files import-database Import a database from a ZIP containing BSON files extract-database Extract database content as a ZIP containing BIN/JSON files rewrite-database Rewrite database content from BIN/JSON files Manipulate Collections
Endpoint or Hook Summary get-collections-list List collection names and document counts get-collection Get summary information about one collection create-collection Create an empty collection destroy-collection Remove a collection and its contents empty-collection Remove the documents while keeping the collection rename-collection Rename a collection Manipulate Documents
Endpoint or Hook Summary init-document Insert documents into a collection drop-document Remove a document selected by its identifier or index Read and Manipulate Nested Data
Endpoint or Hook Summary get-all-data Read the documents in a collection get-data Read or collect nested values selected by a data path get-filtered-data Find data using the hook's filter parameters add-data Add or extend data within existing documents update-data Update values at the requested document path remove-data Remove a selected nested data item move-data Move data between selected paths, subject to the hook's type and identifier rules rename-data Rename a selected data key Historical and Transitional Account Hooks
The historical table also contains an unfinished users-account entry. The current API guide separately lists database-users-changepass, database-users-updatename, and database-users-dropaccount as transitional native MongoDB account hooks. These are separate from Staxis token creation and session delegation; consult their current implementation before using them.
-
readme.extend.md: Add Your Own Operations
readme.extend.md explains the internal responsibilities and the steps for adding a custom operation. Read it after the setup and API guides when you need functionality beyond the built-in hooks. It walks through these steps:
-
Create the hook file: choose the matching hooks-* family and follow the existing callback contract, returning errors, message, and payload.
-
Import it in mongodb.mountRoutes.router.js: register the operation alongside the other hook imports.
-
Map the route in mongodb.mountRoutes.router.js: parse the request, resolve its active accessToken session, pass the session client to the hook, emit the result, and add the handler to the routes array.
-
Let the route mounter register it: mongodb.mountRoutes.js mounts the router set under config.database.mongodb.dbapis; no second manual registration is needed.
The guide also maps the internal flow: main.js coordinates the lifecycle, mongodb.mainConnection.js owns the process and main client, mongodb.sessionManager.js owns tokens and sessions, and the routing modules connect requests to hooks. Keep operation logic in the matching hook family when extending the pack.
-
Official MongoDB References
-
Localhost exception: the MongoDB rule used to create the first project user during bootstrap.
-
Create users on self-managed deployments: MongoDB's user administration and role-assignment procedures.
-
createUser database command: the native command used to provision MongoDB accounts.
-
mongod configuration and command-line mapping: the relationship between server configuration and process startup options.