MoonBit cryptography and JWT gateway with experimental libsodium-compatible secretstream authenticated encryption and independent interoperability tests.
| # | Module | Upstream Source | License | Reference / Modification Scope |
|---|---|---|---|---|
| 1 | crypto/mb-hash | moonbit-crypto/mb-crypto/mb-hash | Apache-2.0 | SHA-256 and SHA-512 implementation adapted verbatim; added Sha256::digest_string and Sha512::digest_string convenience methods |
| 2 | crypto/mb-hmac | moonbit-crypto/mb-crypto/mb-hmac | Apache-2.0 | HMAC-SHA256 and HMAC-SHA512 adapted verbatim; no semantic changes |
| 3 | crypto/mb-chacha | moonbit-crypto/mb-crypto/mb-chacha | Apache-2.0 | ChaCha20/XChaCha20 stream ciphers adapted verbatim; added encrypt_bytes/decrypt_bytes convenience wrappers |
| 4 | crypto/mb-poly1305 | moonbit-crypto/mb-crypto/mb-poly1305 | Apache-2.0 | Poly1305 one-time MAC adapted verbatim; added poly1305_mac_bytes / poly1305_verify_bytes Bytes API |
| 5 | crypto/mb-aead | moonbit-crypto/mb-crypto/mb-aead | Apache-2.0 | ChaCha20-Poly1305 AEAD adapted verbatim; added aead_encrypt_bytes / aead_decrypt_bytes Bytes API convenience wrappers |
| 6 | crypto/mb-p256 | moonbit-crypto/mb-crypto/mb-p256 | Apache-2.0 | ECDSA P-256 adapted verbatim; added ecdsa_sign_message/ecdsa_verify_message wrappers for JWT integration |
| 7 | crypto/mb-hkdf | moonbit-crypto/mb-crypto/mb-hkdf | Apache-2.0 | HKDF adapted verbatim; added _bytes convenience wrappers |
| 8 | crypto/mb-getrandom | moonbit-crypto/mb-crypto/mb-getrandom | Apache-2.0 | OS CSPRNG adapted verbatim; no semantic changes |
| 9 | crypto/mb-jwt | Built on top of mb-hash, mb-hmac, mb-p256, mb-base64url from moonbit-crypto/mb-crypto | Apache-2.0 | JWT sign/verify (HS256, ES256) — original implementation in this repository using upstream crypto primitives; adds signature comparison, alg:none rejection, claims validation |
| 10 | gateway | This repository (original) | Apache-2.0 | JWT security filter middleware, flow control (rate limiter, circuit breaker, fair queue, bandwidth shaper, connection pool, backoff, replay protection), stream metrics |
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.
| Metric | Value | Source |
|---|---|---|
| JWT verify (HS256) | 24.09 μs ± 0.87 μs | moon bench --target wasm-gc |
| JWT sign (HS256) | 19.74 μs ± 1.51 μs | moon bench --target wasm-gc |
| JWT decode (no verify) | 14.90 μs ± 0.87 μs | moon bench --target wasm-gc |
| JWT sign (ES256) | 10.61 ms ± 0.38 ms | moon bench --target wasm-gc |
| JWT verify (ES256) | 20.65 ms ± 0.47 ms | moon bench --target wasm-gc |
| Base64url encode (11 bytes) | 1.04 μs ± 0.04 μs | moon bench --target wasm-gc |
| Base64url decode (8 bytes) | 590 ns ± 14 ns | moon bench --target wasm-gc |
| Security filter execute | 25.03 μs ± 0.56 μs | moon bench --target wasm-gc |
| Rate limiter (try_consume) | 13.37 ns ± 2.06 ns | moon bench --target wasm-gc |
| Replay protector (check_nonce) | 56.66 ns ± 10.03 ns | moon bench --target wasm-gc |
| Fair queue (dequeue) | 14.76 ns ± 1.53 ns | moon bench --target wasm-gc |
| Circuit breaker (allow_request) | 24.01 ns ± 5.97 ns | moon bench --target wasm-gc |
| Bandwidth shaper (try_consume) | 15.64 ns ± 2.44 ns | moon bench --target wasm-gc |
| Connection pool (acquire) | 17.77 ns ± 2.97 ns | moon bench --target wasm-gc |
| Stream metrics (record_request) | 9.71 μs ± 3.88 μs | moon bench --target wasm-gc |
| Backoff (next_delay) | 17.79 ns ± 2.07 ns | moon bench --target wasm-gc |
| Memory allocation | Minimal (no intermediate strings in token splitting) | Design characteristic |
| Current test result | 155/155 tests passing | moon test --deny-warn |
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.
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)
}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)
}// 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
}| Module | Description |
|---|---|
| crypto/mb-jwt | JWT sign/verify (HS256, ES256) with signature and claims validation |
| crypto/mb-hmac | HMAC-SHA256 and HMAC-SHA512 |
| crypto/mb-hash | SHA-2 family (SHA-256, SHA-512) |
| crypto/mb-chacha | ChaCha20 and XChaCha20 stream ciphers (RFC 8439) |
| crypto/mb-aead | ChaCha20-Poly1305 AEAD (RFC 8439) |
| crypto/mb-poly1305 | Poly1305 one-time authenticator (RFC 7539) |
| crypto/mb-p256 | ECDSA P-256 (secp256r1) signatures |
| crypto/mb-hkdf | HKDF key derivation (RFC 5869) |
| crypto/mb-getrandom | Secure random bytes (OS CSPRNG) |
| gateway | JWT security filter middleware |
| Function | Input | Output | Description |
|---|---|---|---|
| sign(payload, key) | payload: String (JSON), key: JwtKey | Result[String, JWTError] | Create signed JWT token |
| verify(token, key) | token: String, key: JwtKey | Result[String, JWTError] | Verify JWT and return payload JSON |
| decode(token) | token: String | Result[String, JWTError] | Decode without verification |
| decode_header(token) | token: String | Result[String, JWTError] | Decode header without verification |
| validate_claims(payload, current_time, expected_iss, expected_aud) | payload: JWTPayload, current_time: Int64, expected_iss: String?, expected_aud: String? | Result[Unit, JWTError] | Validate exp, nbf, iss, aud |
enum JwtKey {
HS256(String) // HMAC-SHA256 secret key
ES256(Array[UInt]) // ECDSA P-256 private key (32 bytes)
}struct JWTPayload {
iss: Option[String] // Issuer
sub: Option[String] // Subject (user ID)
aud: Option[String] // Audience
exp: Option[Int64] // Expiration time (Unix timestamp)
nbf: Option[Int64] // Not before (Unix timestamp)
iat: Option[Int64] // Issued at (Unix timestamp)
jti: Option[String] // JWT ID
}// Sign
let key = JwtKey::HS256("my-secret")
let payload = "{\"sub\":\"user123\",\"exp\":2000000000,\"role\":\"admin\"}"
let token = sign(payload, key)? // Returns: "header.payload.signature"
// Verify
match verify(token, key) {
Ok(payload_json) => {
// Success: payload_json is the decoded JSON string
println("Valid token: \{payload_json}")
}
Err(InvalidSignature) => println("Invalid signature")
Err(TokenExpired(_, _)) => println("Token expired")
Err(e) => println("Error: \{e}")
}| Function | Input | Output | Description |
|---|---|---|---|
| new_stream_context(token) | token: String | StreamContext | Create security context |
| execute_security_filter(ctx, key, time) | ctx: StreamContext, key: JwtKey, time: Int64 | Unit | Validate JWT and populate context |
struct StreamContext {
token: String // Input: JWT token
mut is_allowed: Bool // Output: true if valid
mut error_message: String // Output: error reason if invalid
mut user_sub: String // Output: JWT "sub" claim (user ID)
mut user_role: String // Output: JWT "role" claim ("admin", "guest", etc.)
}// 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 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 |
# 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┌─────────────────────────────────────────────────────────────┐
│ Client Request │
│ (JWT Token in Header) │
└───────────────────────────┬─────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Security Filter │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │
│ │ verify() │→ │ parse_claims│→ │ validate_claims() │ │
│ │ (HMAC/ECDSA)│ │ (JSON) │ │ (exp/nbf/iss/aud) │ │
│ └─────────────┘ └─────────────┘ └─────────────────────┘ │
└───────────────────────────┬─────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Stream Context │
│ ┌──────────┐ ┌──────────┐ ┌──────────────────────────┐ │
│ │is_allowed│ │user_role │ │ user_sub │ │
│ └──────────┘ └──────────┘ └──────────────────────────┘ │
└───────────────────────────┬─────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Flow Control │
│ ┌────────────┐ ┌────────────┐ ┌──────────────────────┐ │
│ │RateLimiter │ │FairQueue │ │ BandwidthShaper │ │
│ └────────────┘ └────────────┘ └──────────────────────┘ │
│ ┌────────────┐ ┌────────────┐ ┌──────────────────────┐ │
│ │CircuitBrkr │ │Backoff │ │ ConnectionPool │ │
│ └────────────┘ └────────────┘ └──────────────────────┘ │
└───────────────────────────┬─────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Upstream Service │
│ (with user context) │
└─────────────────────────────────────────────────────────────┘# Run all tests
moon test
# Coverage: 150/150 tests passing
# - JWT sign/verify (HS256, ES256)
# - Security attacks (alg:none, algorithm confusion, signature tampering)
# - Claims validation (exp, nbf, iss, aud)
# - Flow control (rate limiting, fair queue, circuit breaker)
# - Bandwidth shaping and connection pooling
# - Metrics and observabilityInstall
Download zipMoonBit cryptography and JWT gateway with experimental libsodium-compatible secretstream authenticated encryption and independent interoperability tests.