XEMS Tutorial: High-Security Session Management
Learn how to implement enterprise-grade, hardware-bound authentication and session management using XEMS (XyPriss Entry Management System).
This major architectural revision reflects extensive real-world testing and production feedback. Available starting from XyPriss 9.12.60 (powered by XEMS Core v1.1.22).
1. Native Session Helpers Overview
XyPriss abstracts the underlying Go sidecar and cryptographic vault behind three elegant, built-in response and request helpers:
res.xLink(data, options?)
Initiates an authenticated session, encrypts the payload inside the hardware-bound .xems vault, and issues the HttpOnly cookie and tracking header.
req.session
Automatically resolves, decrypts, and attaches the active session payload for incoming requests carrying valid cookies or headers.
res.xUnlink(options?)
Instantly purges the session from the Go encrypted vault store and expires the client cookie.
2. Server Configuration
Declare your XEMS configuration in your server definition or xypriss.config.ts:
import { createServer, __sys__ } from "xypriss";
export const app = createServer({
server: {
xems: {
enable: true,
path: __sys__.path.resolve("vault.xems"), // Native __sys__.path API recommended
secret: process.env.XEMS_SECRET!, // Min 32-byte master key
ttl: "7d", // Expiration (max 7 days)
autoRotation: "1m", // Sliding window rotation
gracePeriod: 15000, // 15 seconds grace overlap
cookieName: "xems_token",
cookieOptions: {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "Strict",
},
},
},
});3. Real-World Authentication Flow
A. Login: Creating a Session (res.xLink)
When credentials are verified, call await res.xLink(sessionData). XEMS generates an opaque cryptographic token and transparently sends the Set-Cookie header:
import { Router } from "xypriss";
const authRouter = new Router();
authRouter.post("/login", async (req, res) => {
const { email, password } = req.body;
const user = await authenticateUser(email, password);
if (!user) {
return res.status(401).json({ error: "Invalid credentials" });
}
// 🔐 Initiate secure XEMS session
await res.xLink({
userId: user.id,
tenantId: user.tenantId,
role: user.role,
email: user.email,
});
return res.status(200).json({
success: true,
message: "Login successful",
user: { id: user.id, email: user.email, role: user.role },
});
});B. Route Protection & Guards (req.session)
Incoming requests with valid session cookies automatically have their decrypted payload attached to req.session:
// authGuard.ts
export const authGuard = (req: any, res: any) => {
if (!req.session || !req.session.userId) {
return res.status(401).json({ error: "Unauthorized" });
}
return true; // Access granted
};
// Protected router
const apiRouter = new Router();
apiRouter.get("/profile", { guards: [authGuard] }, async (req, res) => {
// req.session is decrypted and ready
return res.json({
userId: req.session.userId,
role: req.session.role,
});
});C. Logout: Destroying the Session (res.xUnlink)
Call await res.xUnlink() to destroy the session. It purges the key from the Go encrypted memory store and expires the client cookie:
authRouter.post("/logout", async (req, res) => {
// 🗑️ Terminate session in Go vault & expire client cookie
await res.xUnlink();
return res.status(200).json({
success: true,
message: "Logged out successfully",
});
});4. Multi-Tenant & Custom Sandboxes
Partition sessions into separate isolated namespaces (sandboxes) at runtime for multi-tenant applications or elevated privilege modes:
// Link to a specific organization or admin sandbox
await res.xLink(adminData, {
sandbox: `org.${user.tenantId}`,
ttl: "12h",
});
// Destroy session in a specific sandbox
await res.xUnlink({ sandbox: `org.${user.tenantId}` });5. Security Best Practices
SPAs & Concurrent Requests
Always configure autoRotation: "1m" and a generous gracePeriod (15s) so parallel API calls do not trigger race conditions.
Key Security
Keep XEMS_SECRET (min 32 bytes) strictly in environment variables. Never hardcode master keys.
Hardware Locking
The generated .xems vault is cryptographically bound to the server HWID and file path, making stolen database files unreadable to attackers.
Review all XEMS configuration options, hardware binding, and transport settings.
