@cube0/middleware
Shared middleware for Cube0 MCP servers (built with Hono) to handle authentication, context injection, and secure secret retrieval.
Installation
npm install @cube0/middleware
Features
- Automatic Authentication: Validates
Authorization: Bearer <API_KEY> headers against the Cube0 platform.
- Context Management: Initializes
AsyncLocalStorage with the request context for safe global access within the request scope.
- Secret Management: Provides a
getSecret() helper to securely fetch user-specific credentials (e.g., Twitter access tokens) from the Cube0 platform at runtime.
Usage
1. Register the Middleware
Apply the cube0 middleware to your Hono application. This ensures all requests are authenticated and the context is initialized.
import { Hono } from "hono";
import { cube0 } from "@cube0/middleware";
const app = new Hono<{ Bindings: { CUBE0_URL: string } }>();
app.use("*", cube0());
app.post("/mcp", async (c) => {
return c.json({ message: "Authenticated request" });
});
export default app;
2. Fetching Secrets
Use the getSecret helper to retrieve credentials for connected providers. This function uses the authenticated user's context to fetch the correct secrets from the Cube0 platform.
import { getSecret } from "@cube0/middleware";
async function postTweet(content: string) {
const secrets = await getSecret("twitter");
const accessToken = secrets.accessToken;
}
Configuration
The middleware requires the CUBE0_URL environment variable to be set in your Cloudflare Worker configuration (wrangler.json or wrangler.jsonc).
// wrangler.jsonc
{
"vars": {
"CUBE0_URL": "https://cube0.ai"
}
}
API Reference
cube0()
Hono middleware factory. Returns a middleware function that:
- Checks for
Authorization header.
- Validates the API key with Cube0.
- Initializes the request context.
getSecret(provider: string): Promise<any>
Fetches secrets for the specified provider (e.g., "twitter", "github").
- provider: The provider identifier.
- Returns: A promise resolving to the JSON object containing secrets.
- Throws: Error if context is not initialized or if the user is not connected to the provider.