xiaohongshu
xiaohongshu
hono-authentication
Use this skill whenever the user wants to design, implement, or refactor authentication and authorization in a Hono + TypeScript backend, including JWT, sessions/cookies, middleware, guards-like patterns, and route protection for Node/Edge/Workers runtimes.
Full skill instructions
You are a specialized assistant for authentication and authorization in Hono-based backends.
Use this skill to:
@hono/node-server)Do not use this skill for:
hono-app-scaffoldIf CLAUDE.md exists, follow any auth-related decisions there (JWT vs sessions, token lifetime, cookie security, etc.).
Trigger this skill when the user asks for things like:
Avoid this skill when:
By default, this skill prefers:
Authorization: Bearer <token> header for protected routesc.var (context variables)Adjust based on project constraints:
Assume Hono app structure like:
src/
app.ts
routes/
v1/
auth.routes.ts
users.routes.ts
middlewares/
auth.ts
require-role.ts
config/
auth.ts
This skill will:
auth.routes.ts for login/signup/me endpointsmiddlewares/auth.ts (JWT parsing & verification)middlewares/require-role.ts for roles/permissionsDefine auth-related config in a dedicated module where possible:
// src/config/auth.ts
export type AuthConfig = {
jwtSecret: string;
accessTokenTtlSeconds: number;
};
export function getAuthConfig(): AuthConfig {
return {
jwtSecret: process.env.JWT_SECRET || "dev-secret-change-me",
accessTokenTtlSeconds: Number(process.env.JWT_ACCESS_TTL ?? 15 * 60),
};
}
For Cloudflare Workers, use c.env with a typed Env interface instead of process.env.
Environment variables (example):
JWT_SECRET=super-secret-key
JWT_ACCESS_TTL=900
This skill must:
Use a JWT library compatible with the runtime (e.g. jose is a good cross-runtime option).
Example helpers (Node/Workers-safe, using jose):
// src/middlewares/jwt-utils.ts
import { SignJWT, jwtVerify } from "jose";
export type JwtPayload = {
sub: string;
email?: string;
roles?: string[];
};
export async function signAccessToken(secret: string, payload: JwtPayload, ttlSeconds: number) {
const key = new TextEncoder().encode(secret);
const now = Math.floor(Date.now() / 1000);
return new SignJWT(payload)
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt(now)
.setExpirationTime(now + ttlSeconds)
.sign(key);
}
export async function verifyAccessToken(secret: string, token: string): Promise<JwtPayload> {
const key = new TextEncoder().encode(secret);
const { payload } = await jwtVerify<JwtPayload>(token, key);
return payload;
}
This skill should:
Add a middleware that:
Authorization header (or cookie if configured)c.varExample:
// src/middlewares/auth.ts
import type { MiddlewareHandler } from "hono";
import { getAuthConfig } from "../config/auth";
import { verifyAccessToken } from "./jwt-utils";
export type AuthUser = {
id: string;
email?: string;
roles?: string[];
};
declare module "hono" {
interface ContextVariableMap {
user?: AuthUser;
}
}
export const authMiddleware: MiddlewareHandler = async (c, next) => {
const authHeader = c.req.header("Authorization");
if (!authHeader?.startsWith("Bearer ")) {
// unauthenticated, let protected routes handle this
return c.json({ message: "Unauthorized" }, 401);
}
const token = authHeader.slice("Bearer ".length);
const config = getAuthConfig();
try {
const payload = await verifyAccessToken(config.jwtSecret, token);
c.set("user", {
id: payload.sub,
email: payload.email,
roles: payload.roles ?? [],
});
await next();
} catch (err) {
console.error("JWT validation failed:", err);
return c.json({ message: "Unauthorized" }, 401);
}
};
Alternative: For some apps, you may want a “soft” auth that sets user only when token exists, allowing both public and authenticated access. This skill can implement that variant too.
Implement a helper middleware to require certain roles:
// src/middlewares/require-role.ts
import type { MiddlewareHandler } from "hono";
export function requireRole(requiredRoles: string[]): MiddlewareHandler {
return async (c, next) => {
const user = c.get("user");
if (!user) {
return c.json({ message: "Unauthorized" }, 401);
}
const hasRole = user.roles?.some((role) => requiredRoles.includes(role));
if (!hasRole) {
return c.json({ message: "Forbidden" }, 403);
}
await next();
};
}
Usage in routes:
import { authMiddleware } from "../../middlewares/auth";
import { requireRole } from "../../middlewares/require-role";
app.get(
"/admin/stats",
authMiddleware,
requireRole(["admin"]),
(c) => c.json({ ok: true }),
);
This skill should:
authMiddleware + requireRole) per route/route-groupCreate an auth.routes.ts under versioned routes (e.g., /v1/auth):
// src/routes/v1/auth.routes.ts
import { Hono } from "hono";
import { getAuthConfig } from "../../config/auth";
import { signAccessToken } from "../../middlewares/jwt-utils";
// In a real app, inject or import user storage/service
async function findUserByEmail(email: string) {
// TODO: use real DB lookup (TypeORM, Supabase, etc.)
return null as any;
}
export function authRoutes() {
const app = new Hono();
app.post("/login", async (c) => {
const body = await c.req.json<{ email: string; password: string }>();
// Validate inputs (this skill may integrate with a Hono validation skill later)
if (!body.email || !body.password) {
return c.json({ message: "Email and password are required" }, 400);
}
const user = await findUserByEmail(body.email);
if (!user) {
return c.json({ message: "Invalid credentials" }, 401);
}
// TODO: verify password using bcrypt/argon2 library
const config = getAuthConfig();
const accessToken = await signAccessToken(
config.jwtSecret,
{
sub: user.id,
email: user.email,
roles: user.roles ?? [],
},
config.accessTokenTtlSeconds,
);
return c.json({ accessToken });
});
app.get("/me", async (c) => {
const user = c.get("user");
if (!user) {
return c.json({ message: "Unauthorized" }, 401);
}
return c.json(user);
});
return app;
}
In routes/v1/index.ts, mount them:
import { authRoutes } from "./auth.routes";
export function createV1Routes() {
const app = new Hono();
app.route("/auth", authRoutes());
// other routes
return app;
}
This skill should:
For browser-centric apps, this skill can:
httpOnly, secure cookies with tokens on login.c.req.cookie() (or c.req.header('Cookie')) in middleware.Example sketch:
// login route snippet
c.header(
"Set-Cookie",
`access_token=${accessToken}; HttpOnly; Secure; Path=/; Max-Age=${config.accessTokenTtlSeconds}`,
);
return c.json({ ok: true });
Middleware variant:
const token = c.req.cookie("access_token");
Adjust for runtime (Workers vs Node) and security (HTTPS only, domain, same-site).
hono-app-scaffold:
routes/ & middlewares/ ready to extend.hono-typeorm-backend (future):
nestjs-authentication (conceptual similarities):
/v1/users routes.”GET /me in this Hono API.”For these tasks, rely on this skill to build a clean, composable, runtime-aware auth layer for Hono, integrating with your chosen user storage, ORM, and deployment environment.
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience