JWT
Official sources are open to Staxis GitLab group members: how to join and view the code.
Repository:
JWT development
Versions:
tags
and releases
Description
JWT means JSON Web Token: a compact, URL-safe format for carrying JSON claims between parties. Standard JWTs can use signatures or message authentication codes through JWS, or encryption through JWE. A signature or MAC alone does not hide the payload. See RFC 7519 for the standard format and terminology.
The Staxis pack named jwt provides its own authenticated AES-GCM encrypted JSON envelope. Its output is an object or a Base64URL encoding of that object, not a standard JWT compact string or JWE compact token. Create and read these envelopes through this layer's encrypt and decrypt methods; do not pass them to a generic JWT verifier expecting an interoperable JWT format.
Its manifest.label and manifest.typology are both jwt. It exposes a synchronous internal API and can optionally register HTTP endpoints through serverApp. The application decides what the encrypted data means, who may receive a token, and which actions that data authorizes.
Read before flight
-
We suggest verifying that KEY:JWT is configured with private, high-entropy key material before startup, and keeping it stable for each environment. Changing it invalidates existing envelopes and requires matching pack integrity records to be regenerated.
-
We suggest leaving HTTP endpoints disabled until authentication, authorization, rate limits, and HTTPS are configured. A generic encryption endpoint must not let an untrusted caller mint arbitrary identities or permissions for your application.
-
We suggest keeping payloads small and expiration short enough for your workflow. The cryptographic operations are synchronous. Protect token transport and storage, avoid logging tokens, and prefer request bodies over URLs for confidential values.
Requirements and Installation
The manifest declares serverApp and the httpRestParser library. No external npm package is required: the layer uses Node.js cryptography. Install through the Manager:
manager -> install -> jwt
Keep httpRestParser before its consumers and serverApp before jwt when enabling HTTP endpoints. Place internal consumers after jwt. Prepare KEY:JWT and the project's Vault and integrity files as described in First setup. KEY:JWT is the jwt typology's integrity key and the stable secret used by this pack for encryption. It is separate from the short-lived Vault access token used by another layer to obtain the API.
Files Map
| File | Purpose |
|---|---|
| manifest.json | Declares the jwt label and runtime slot, required packs, and permitted callers |
| configs.js | Supplies the Node dependency allowance, encryption settings, size limit, and disabled HTTP endpoint defaults |
| main.js | Implements Vault-backed encryption/decryption, envelope validation, lifecycle gating, and optional HTTP handling |
| README.md | Original pack reference, token formats, and internal/HTTP usage |
Configuration
In the project's config.js, settings belong to config.serveropt.jwt. The Node built-in allowance belongs to config.engineopt.guard.allowNodeDeps and is global to the assembled application. Merge these branches into the exported config object, preserving the other Guardian rules. The example matches the pack defaults.
// config.js -> config (merge into the exported object)
engineopt: {
guard: {
allowNodeDeps: true
}
},
serveropt: {
jwt: {
enabled: true,
level: 2,
format: 'json',
expire: 900,
maxPayloadBytes: 65536,
endpoints: {
enabled: false,
encrypt: '/jwt/encrypt',
decrypt: '/jwt/decrypt'
}
}
}
| Option under config.serveropt.jwt | Behaviour |
|---|---|
| enabled | false publishes an inactive layer instead of the encryption API |
| level | Integer 1, 2, or 3; selects the profile for newly encrypted tokens |
| format | json returns an envelope object; base64url returns its encoded JSON representation |
| expire | Positive integer lifetime in seconds; 900 is 15 minutes; false creates non-expiring tokens |
| maxPayloadBytes | Positive integer limit for the UTF-8 serialized plaintext; supplied as 65536 bytes |
| endpoints.enabled | Enables HTTP handling when true; supplied as false |
| endpoints.encrypt, endpoints.decrypt | Distinct route aliases, matched exactly after removing the query string |
Decryption reads the level and expiration from the authenticated envelope. Changing level or format affects new output; it does not make decryption require that same configured level or representation. Apply configuration and key changes through a controlled restart, since the Vault retains its loaded key material. Token size checks complement the raw-body limits configured in httpRestParser or its upstream reader.
Authorize a Calling Layer
The supplied jwt manifest permits jwt itself. To allow your own consumer, add its manifest.label to system-lrpcks/jwt/manifest.json, preserving the existing entries. This fragment shows the permits field to merge into that manifest:
{
"permits": ["jwt", "someOtherLayer"]
}
The consumer can declare "require": ["jwt"] and must come after jwt in the stack. Run the following inside that consumer's factory or method, with its engine and layers equipment:
const tokenAccess = engine.vault.requireAccess(
'someOtherLayer', // Requesting pack's manifest.label
'jwt' // Provider pack's manifest.label
)
if (typeof tokenAccess !== 'string' || tokenAccess.startsWith('error:')) {
throw new Error('JWT layer access was denied')
}
const instance = layers.require(
'jwt', // Provider's manifest.typology: its runtime slot
tokenAccess,
false
)
const jwt = instance?.assets
if (!jwt?.active || typeof jwt.encrypt !== 'function' || typeof jwt.decrypt !== 'function') {
throw new Error('JWT layer is unavailable')
}
tokenAccess authorizes access to the Staxis layer. It is not the encrypted application token. The official pack happens to use jwt for both its label and runtime slot; those arguments still have different roles.
Encrypt and Decrypt an Object
const encryptedToken = jwt.encrypt({
userId: 42,
role: 'editor'
})
if (encryptedToken === false) {
throw new Error('Token encryption failed')
}
const restoredData = jwt.decrypt(encryptedToken)
if (restoredData === false) {
throw new Error('Token is invalid, expired, or unavailable')
}
// restoredData is { userId: 42, role: 'editor' }
Both calls are synchronous. Supply a JSON object as the plaintext, not an array, string, or null. Use JSON-serializable values: circular references and BigInt cause encryption to fail; JSON serialization omits object properties whose values are undefined or functions. The public facade returns false on failure, including rejected input, expiration, failed authentication, or an inactive layer. Check that result before using the recovered data.
A successful decrypt restores the JSON data; it does not authenticate an HTTP user, establish a session, check a role, or authorize a request by itself. Those decisions belong to the application that issues and consumes the token.
Encryption Profiles and Envelope Format
| Level | Cipher |
|---|---|
| 1 | AES-128-GCM |
| 2 | AES-192-GCM; supplied default |
| 3 | AES-256-GCM |
Each encryption uses a random 16-byte salt and 12-byte IV. A level-specific key is derived from KEY:JWT through HKDF-SHA512. AES-GCM authenticates the ciphertext and the covered metadata with a 16-byte tag. Expired tokens and altered authenticated data are rejected during decryption.
| Envelope Field | Meaning |
|---|---|
| v | Envelope version, currently 1 |
| level | Profile used to encrypt this token |
| exp | Unix expiration time in seconds, or false |
| salt, iv | Base64URL-encoded salt and IV |
| tag | Base64URL-encoded authentication tag |
| data | Base64URL-encoded ciphertext, not the original JSON object |
format='base64url' encodes the entire JSON envelope for transport. It does not add another layer of encryption or create a standard compact JWT. decrypt accepts the envelope object, its JSON string, or its Base64URL-encoded JSON representation. Trust application fields returned by decrypt rather than arbitrary extra fields attached to the outer envelope.
The envelope does not implement standard issuer, audience, not-before, or token-ID checks. The layer has no token revocation list or automatic refresh flow. If your workflow needs those policies, implement them in the application. The current pack uses one KEY:JWT rather than a multi-key rotation scheme.
Enable HTTP Endpoints Only When Needed
Internal API use does not require HTTP endpoints. To enable them, first add the requesting pack label jwt to serverApp's manifest permits array, retaining its other callers. The currently supplied serverApp manifest does not include jwt. This permission lets jwt register its middleware; it does not authenticate clients calling the endpoints.
Register application authentication and authorization before the JWT middleware and configure request-size and rate limits. Keep httpRestParser loaded before jwt. Then merge this branch into config.js:
// config.js -> config (merge into the exported object)
serveropt: {
jwt: {
endpoints: {
enabled: true,
encrypt: '/jwt/encrypt',
decrypt: '/jwt/decrypt'
}
}
}
The aliases match the exact pathname and currently accept any HTTP method. The examples use POST; enforce a method policy upstream if needed. Unknown paths continue through the normal middleware chain. The input is parsed by httpRestParser, which combines body and query values. Query values take precedence on a duplicate top-level key.
| Endpoint | Accepted Input |
|---|---|
| /jwt/encrypt | The plaintext object directly, or an object with a data property containing it |
| /jwt/decrypt | The envelope directly, or an object with a token property containing the envelope or encoded token |
When using the data wrapper, the plaintext is the value of data; sibling fields are not automatically merged into that nested object. Prefer the token wrapper for decryption so the same request shape works with both JSON envelopes and Base64URL output.
HTTP Round Trip
After the upstream access policy and endpoints are configured, this example performs a round trip from another local Node.js script. Adjust the address to your listener. Add the credentials required by your application's authentication policy; this sample demonstrates only the payload shapes.
const base = 'http://127.0.0.1:3000'
const encryptedResponse = await fetch(base + '/jwt/encrypt', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
data: { userId: 42, role: 'editor' }
})
})
const encryptedResult = await encryptedResponse.json()
if (!encryptedResponse.ok || encryptedResult.errors) {
throw new Error(encryptedResult.message || 'Encryption request failed')
}
const decryptedResponse = await fetch(base + '/jwt/decrypt', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: encryptedResult.payload })
})
const decryptedResult = await decryptedResponse.json()
if (!decryptedResponse.ok || decryptedResult.errors) {
throw new Error(decryptedResult.message || 'Decryption request failed')
}
// decryptedResult.payload is { userId: 42, role: 'editor' }
Successful responses contain errors=false, a token encrypted or token decrypted message, and the result in payload. Failed token operations contain errors=true and payload=null. Inspect the errors field even when the response has HTTP status 200: the current httpRestParser buffer emitter does not apply the extra status argument supplied by this pack. Parser-level failures can instead complete the response directly, for example with 400 or 413.
Lifecycle and Key Changes
enabled=false or an unsuccessful attach publishes active=false without the encryption methods. An active facade publishes active, level, format, encrypt, and decrypt. Its metadata describes the facade created at attach; the methods still check the layer's current active state.
Detach disables encryption and decryption, including calls through retained facade references. Mounted endpoint middleware remains registered but passes requests onwards while inactive. To change keys, provision the new private key, regenerate the corresponding integrity records, and restart. Previously encrypted tokens cannot be decrypted with the replacement key.
For the original configuration and API reference, see the pack README.
Documentation
This page is the HTML adaptation of the pack's README.md, with practical clarifications checked against the implementation. Complete Staxis onboarding to request GitLab access to the official sources.