Tutorial: Secure Auth with XEMS

This tutorial details the implementation of advanced authentication systems using the XyPriss Encrypted Memory Store (XEMS). Learn how to leverage native isolation and atomic rotation for enterprise-grade security.

1. Session API Fundamentals

Unlike simple key/value storage, the XEMS session layer manages opaque tokens and their entire lifecycle, including automatic encryption and resolution.

Creating a Session
typescript
const runner = xems.forApp(app);
const token = await runner.createSession(
    "auth-pending",
    { email: "user@example.com", mfa_verified: false },
    { ttl: "15m" }
);
Resolution & Rotation
typescript
const session = await runner.resolveSession(token, {
    sandbox: "auth-pending",
    rotate: true,       // Generate a new token atomically
    gracePeriod: 2000,  // 2s overlap for concurrent requests
});

2. Implementing MFA Workflow

A secure multi-factor authentication flow involves migrating data between sandboxes as verification steps are completed.

Initial Authentication

Verify password and create a temporary session in the otp-pending sandbox.

OTP Verification

When the OTP is valid, migrate the user data to a permanent active session using xLink.
MFA Verification Handler
router.post("/mfa/verify", async (req, res) => {
    const runner = xems.forApp(req.app);
    const tempSession = await runner.from("otp-pending").get(req.body.tempToken);

    if (isOtpValid(req.body.code)) {
        // High-level API handles cookie injection and final session linking
        await res.xLink({ userId: tempSession.userId, role: "admin" });
        
        // Cleanup the temporary sandbox
        await runner.from("otp-pending").del(req.body.tempToken);
    }
});

3. Security Best Practices

Persistence Secret

The secret must be exactly 32 bytes. Use environment variables and rotate them periodically for maximum security.

Frontend Isolation

Let XyPriss manage tokens via HttpOnly cookies. Never expose session tokens to client-side JavaScript.

Concurrency Note
Always set a gracePeriod when using token rotation. This prevents race conditions where one of several concurrent requests invalidates the token before others finish.
Plugins Overview

Extend XyPriss with custom functionality using the modular plugin system.