An industrial-grade, high-performance JWT gateway and cryptography library for MoonBit, featuring constant-time verification, streaming AEAD protection (ChaCha20-Poly1305), and production-ready flow control middleware for API security and edge computing.
Acknowledgements
This project is a derivative work based on moonbit-crypto/mb-crypto (Apache-2.0). The nine cryptographic modules listed below (Sections 1–9) are adapted from that upstream project with modifications for the gateway integration context. See each module’s README for detailed change scope.
License
Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
This project contains code adapted from moonbit-crypto/mb-crypto (commit range main), which is also licensed under Apache-2.0.
The following table lists each cryptographic module, its upstream source, the license (Apache-2.0), and the scope of modifications made in this repository:
Note: The upstream repository moonbit-crypto/mb-crypto is itself licensed under Apache-2.0. Modifications in this repository are limited to adding convenience wrappers and integration shims; no cryptographic algorithms were changed.
Project Vision
mb-secure-stream is a production-ready security infrastructure for high-performance stream processing. It provides:
Zero-trust security: Every request is authenticated and authorized at the edge
High performance: Sub-millisecond latency with index-based token splitting (no intermediate string allocations)
Edge-native: Designed for Cloudflare Workers, Fastly Compute, and WASM runtimes
Composable: Modular design allows picking only what you need
Why MoonBit?
MoonBit is chosen for this project because of its unique advantages for security-critical, high-performance applications:
Minimal (no intermediate strings in token splitting)
Design characteristic
Test coverage
150/150 tests passing
moon test
Note: All performance metrics are measured using moon bench --target wasm-gc on the local development machine. Actual performance may vary depending on the target deployment environment (Cloudflare Workers, Fastly Compute, etc.). See crypto/mb-jwt/src/jwt_bench.mbt and gateway/src/gateway_bench.mbt for the full benchmark suite.
Rate limiting: Token bucket algorithm for request rate control
Bandwidth shaping: Byte-level token bucket for bandwidth management
Circuit breaker: Failure isolation with automatic recovery
Connection pooling: Upstream connection limits
Design Principles
Stateless: No external dependencies, suitable for edge deployment
Input validation: Comprehensive bounds checking and type validation
Fail-safe: Always verify before using decrypted data
Constant-time: No data-dependent branches in critical paths
Use Cases
1. API Security Gateway
Microservices architecture unified entry point for identity and access management.
let ctx = new_stream_context(jwt_token)
execute_security_filter(ctx, jwt_key, current_time)
if ctx.is_allowed {
// Forward to upstream with user context
// ctx.user_sub is populated from the JWT "sub" claim
// ctx.user_role is populated from the JWT "role" claim (or "guest" if absent)
forward_request(ctx.user_sub, ctx.user_role)
}
2. WebSocket/Streaming Proxy
Real-time data streams with JWT authentication and flow control.
let fq = new_fair_queue()
let rl = new_rate_limiter(1000L, 100L)
// Authenticate once, then rate-limit each message
if ctx.is_allowed && rl.try_consume(current_time) {
fq.enqueue(ctx.user_sub, Priority::Normal, byte_size, timestamp)
}
3. Edge Computing / Zero-Trust Network
Resource-constrained edge nodes with high security requirements.
// Stateless, no external dependencies
let cb = new_circuit_breaker(5L, 30_000L)
let rp = new_replay_protector(300L)
if cb.allow_request(current_time) && rp.check_nonce(nonce, current_time) {
// Process request
}
Modules
Module
Description
crypto/mb-jwt
JWT sign/verify (HS256, ES256) with constant-time verification
// Create context with JWT token
let ctx = new_stream_context("eyJhbGciOiJIUzI1NiJ9...")
// Execute security filter
let jwt_key = JwtKey::HS256("my-secret")
let current_time = 1700000000
execute_security_filter(ctx, jwt_key, current_time)
// Check result
if ctx.is_allowed {
// Success: access granted
println("Access allowed, sub: \{ctx.user_sub}, role: \{ctx.user_role}")
// Forward request with user context
forward_request(ctx.user_sub, ctx.user_role)
} else {
// Failure: access denied
println("Access denied: \{ctx.error_message}")
// Return 401/403 error
}
Error Messages
Error Type
error_message
HTTP Status
Invalid signature
“Crypto Blocked: Invalid signature”
401
Malformed token
“Crypto Blocked: Malformed token format”
401
Algorithm mismatch
“Crypto Blocked: Algorithm mismatch”
401
Token expired
“Gateway Blocked: Token has expired”
401
Not yet valid
“Gateway Blocked: Token is not yet valid (nbf)”
401
Invalid issuer
“Gateway Blocked: Invalid issuer”
403
Invalid audience
“Gateway Blocked: Invalid audience”
403
Quick Start
# Install MoonBit
curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash
# Workspace check and full test suite
moon check -d
moon fmt --check crypto/mb-aead crypto/mb-chacha \
crypto/mb-getrandom crypto/mb-hash crypto/mb-hkdf \
crypto/mb-hmac crypto/mb-jwt crypto/mb-p256 \
crypto/mb-poly1305 gateway
moon info
moon test
# Module-level smoke tests
cd crypto/mb-jwt && moon test
cd ../../gateway && moon test
Examples
Cloudflare Worker Example
A production-ready JWT gateway (reverse proxy) deployed on Cloudflare Worker. This example demonstrates how to use the MoonBit cryptography library for JWT verification in a real-world edge computing scenario.
What it does:
JWT Authentication: Verifies Authorization: Bearer <token> using HMAC-SHA256
CORS Handling: Manages cross-origin requests with configurable allowed origins
Request Forwarding: Proxies authenticated requests to upstream server (ORIGIN_URL)
User Context Injection: Adds X-User-ID and X-User-Role headers to upstream requests
Security Headers: Adds HSTS and CORS headers to responses
Implementation: Currently in TypeScript using Web Crypto API. The MoonBit library in this repo can be compiled to WASM (moon build --target wasm-gc) for similar edge deployments.
See examples/cloudflare-worker/README.md for deployment instructions.
mb-secure-stream
An industrial-grade, high-performance JWT gateway and cryptography library for MoonBit, featuring constant-time verification, streaming AEAD protection (ChaCha20-Poly1305), and production-ready flow control middleware for API security and edge computing.
Acknowledgements
This project is a derivative work based on moonbit-crypto/mb-crypto (Apache-2.0). The nine cryptographic modules listed below (Sections 1–9) are adapted from that upstream project with modifications for the gateway integration context. See each module’s README for detailed change scope.
License
Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
This project contains code adapted from moonbit-crypto/mb-crypto (commit range
main), which is also licensed under Apache-2.0.========================================================================
Modules Adapted from moonbit-crypto/mb-crypto
The following table lists each cryptographic module, its upstream source, the license (Apache-2.0), and the scope of modifications made in this repository:
crypto/mb-hashSha256::digest_stringandSha512::digest_stringconvenience methodscrypto/mb-hmaccrypto/mb-chachaencrypt_bytes/decrypt_bytesconvenience wrapperscrypto/mb-poly1305poly1305_mac_bytes/poly1305_verify_bytesBytes APIcrypto/mb-aeadaead_encrypt_bytes/aead_decrypt_bytesBytes API convenience wrapperscrypto/mb-p256ecdsa_sign_message/ecdsa_verify_messagewrappers for JWT integrationcrypto/mb-hkdf_bytesconvenience wrapperscrypto/mb-getrandomcrypto/mb-jwtmb-hash,mb-hmac,mb-p256,mb-base64urlfrom moonbit-crypto/mb-cryptoalg:nonerejection, claims validationgatewayProject Vision
mb-secure-stream is a production-ready security infrastructure for high-performance stream processing. It provides:
Why MoonBit?
MoonBit is chosen for this project because of its unique advantages for security-critical, high-performance applications:
1. WASM-First Design
moon build --target wasmormoon build --target wasm-gcmoon test --target wasm-gc2. Zero GC Pressure
3. Type Safety
4. Block-Style Organization
5. Built-in Testing
Performance
Absolute Performance
moon bench --target wasm-gcmoon bench --target wasm-gcmoon bench --target wasm-gcmoon bench --target wasm-gcmoon bench --target wasm-gcmoon bench --target wasm-gcmoon bench --target wasm-gcmoon bench --target wasm-gcmoon bench --target wasm-gcmoon bench --target wasm-gcmoon bench --target wasm-gcmoon bench --target wasm-gcmoon bench --target wasm-gcmoon bench --target wasm-gcmoon bench --target wasm-gcmoon bench --target wasm-gcmoon testPerformance Comparison (HS256 Verify)
Key Insights:
60μs) and Rust (40μs)Security Features
Cryptographic Security
alg:noneto prevent signature bypass (CVE-2016-5431)to_array()allocations)Gateway Security
Design Principles
Use Cases
1. API Security Gateway
Microservices architecture unified entry point for identity and access management.
2. WebSocket/Streaming Proxy
Real-time data streams with JWT authentication and flow control.
3. Edge Computing / Zero-Trust Network
Resource-constrained edge nodes with high security requirements.
Modules
crypto/mb-jwtcrypto/mb-hmaccrypto/mb-hashcrypto/mb-chachacrypto/mb-aeadcrypto/mb-poly1305crypto/mb-p256crypto/mb-hkdfcrypto/mb-getrandomgatewayAPI Reference
JWT API
Core Functions
sign(payload, key)payload: String(JSON),key: JwtKeyResult[String, JWTError]verify(token, key)token: String,key: JwtKeyResult[String, JWTError]decode(token)token: StringResult[String, JWTError]decode_header(token)token: StringResult[String, JWTError]validate_claims(payload, current_time, expected_iss, expected_aud)payload: JWTPayload,current_time: Int64,expected_iss: String?,expected_aud: String?Result[Unit, JWTError]Key Types
Data Structures
Usage Example
Gateway API
Core Functions
new_stream_context(token)token: StringStreamContextexecute_security_filter(ctx, key, time)ctx: StreamContext,key: JwtKey,time: Int64UnitData Structures
Usage Example
Error Messages
Quick Start
Examples
Cloudflare Worker Example
A production-ready JWT gateway (reverse proxy) deployed on Cloudflare Worker. This example demonstrates how to use the MoonBit cryptography library for JWT verification in a real-world edge computing scenario.
What it does:
Authorization: Bearer <token>using HMAC-SHA256ORIGIN_URL)X-User-IDandX-User-Roleheaders to upstream requestsImplementation: Currently in TypeScript using Web Crypto API. The MoonBit library in this repo can be compiled to WASM (
moon build --target wasm-gc) for similar edge deployments.See
examples/cloudflare-worker/README.mdfor deployment instructions.Architecture
Test Coverage
Official Test Sources
This project’s test suite is based on the following official standards and test vectors:
Cryptographic Standards
RFC 8439 — ChaCha20 and Poly1305 for IETF Protocols
RFC 7539 — ChaCha20 and Poly1305 for TLS (superseded by RFC 8439)
RFC 4231 — Identifiers and Test Vectors for HMAC-SHA-224/256/384/512
RFC 5869 — HMAC-based Extract-and-Expand Key Derivation Function (HKDF)
RFC 7518 — JSON Web Algorithms (JWA)
RFC 7519 — JSON Web Token (JWT)
RFC 4648 §5 — Base64url encoding (no padding, URL-safe alphabet)
RFC 2104 — HMAC: Keyed-Hashing for Message Authentication
JWT Test Vectors
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9{"sub":"1234567890","name":"John Doe","iat":1516239022}Security Vulnerability Test Suites
OWASP WSTG-CRYP-04 — JWT Vulnerability Matrix
jwt_tool — Known CVE and attack test cases
P-256 (ECDSA) Tests
License
Apache 2.0