auth-server-primitives
БесплатноБез исполняемых скриптовНе проверенServer-side authentication primitives for TanStack Start: session cookies (HttpOnly, Secure, SameSite, __Host- prefix), session read/issue/destroy via…
от TanStack★ 15 408 звёзд на GitHubОб этом скилле
Auth Server Primitives
This skill covers the server half of authentication: session storage, cookie issuance, OAuth flow, password-reset hardening, CSRF, rate limiting. For the routing half (_authenticated layout, beforeLoad redirects, RBAC checks), see @tanstack/router-core#router-core/auth-and-guards.
CRITICAL: Protect the data/API boundary first. Server functions, server routes, and other API endpoints that touch private data must enforce auth inside the handler or middleware. Route guards are route UX, not the data security boundary. CRITICAL: Validating the shape of a client-supplied identifier (
z.string().uuid().parse(...)) is not authorization. A parsed UUID is still some tenant — re-check membership against the session principal before using it. CRITICAL: Read session/cookies inside.handler()or middleware.server(), not at module scope. Module-level reads run before requests exist (and are also undefined on Cloudflare Workers).
Production Checklist
- Enforce auth in every server function, server route, or API endpoint that reads or writes private user, tenant, or account data. Use route
beforeLoadfor page UX, not as the data boundary. - Use
.validator()on every server function that accepts input. - Store sessions in
HttpOnly,Secure,SameSitecookies. Do not store session tokens inlocalStorageorsessionStorage. - Hash passwords with bcrypt, scrypt, or Argon2. For missing users, verify against a dummy hash and return the same login/reset message.
- Rate limit login, registration, and password-reset endpoints.
- Use CSRF or same-origin protections for non-GET server functions and server routes.
- Log authentication events and monitor failures.
- Test direct unauthenticated calls to protected server functions; they should reject before returning data.
- Follow the anonymous redirect and inspect its HTML and serialized state. Login and unauthorized pages must not name the protected user, tenant, or record.
Session Cookies
The recommended session storage is an HTTP-only cookie holding either an opaque session ID (with server-side lookup) or a signed/encrypted token. The cookie flags matter — set them all.
// src/server/session.ts
import {
deleteCookie,
getCookie,
setCookie,
} from '@tanstack/react-start/server'
const SESSION_COOKIE = '__Host-session' // __Host- prefix binds to the exact origin + path '/'
const ONE_DAY = 60 * 60 * 24
const sessionCookieOptions = {
httpOnly: true, // not readable from JS — defeats XSS exfiltration
secure: true, // HTTPS only (required for __Host- prefix)
sameSite: 'lax', // sent on top-level navigations, blocks most CSRF
path: '/', // required for __Host- prefix
} as const
export function setSessionCookie(token: string) {
setCookie(SESSION_COOKIE, token, {
...sessionCookieOptions,
maxAge: ONE_DAY,
})
}
export function clearSessionCookie() {
deleteCookie(SESSION_COOKIE, sessionCookieOptions)
}
export function readSessionToken(): string | null {
return getCookie(SESSION_COOKIE) ?? null
}
Write cookies with setCookie (or appendResponseHeader('set-cookie', serialized) for a cookie that a library already serialized). Do not use setResponseHeader('Set-Cookie', ...) for this: it replaces every cookie on the outgoing response, including cookies set by other middleware or returned by a handler.
Flag rationale:
HttpOnly— JavaScript can't read the cookie, so an XSS bug can't steal the session.Secure— HTTPS only. Required when using__Host-prefix.SameSite=Lax— blocks CSRF on most cross-origin POST/PUT/DELETE. UseStrictfor highest-security flows where loss of cross-site GET navigation is acceptable.__Host-prefix — binds the cookie to the exact origin (no Domain attribute, Path must be/, Secure must be set). Prevents subdomain takeover from forging a session cookie.Path=/— required by__Host-.Max-Age— finite lifetime so a stolen cookie isn't useful forever. Pair with server-side session rotation.
Session Lookup as Middleware
Use middleware to centralize session loading so every protected handler sees a typed session:
// src/server/auth-middleware.ts
import { createMiddleware } from '@tanstack/react-start'
import { readSessionToken } from './session'
export const authMiddleware = createMiddleware({ type: 'function' }).server(
async ({ next }) => {
const token = readSessionToken()
const session = token ? await db.sessions.findValid(token) : null
if (!session) throw new Error('Unauthorized')
return next({ context: { session } })
},
)
Attach it to every server function that needs a logged-in user:
import { createServerFn } from '@tanstack/react-start'
import { authMiddleware } from '~/server/auth-middleware'
export const getMyOrders = createServerFn({ method: 'GET' })
.middleware([authMiddleware])
.handler(async ({ context }) => {
return db.orders.findMany
Установить auth-server-primitives в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл auth-server-primitives?
Server-side authentication primitives for TanStack Start: session cookies (HttpOnly, Secure, SameSite, __Host- prefix), session read/issue/destroy via createServerFn and middleware, OAuth authorization-code flow with state and PKCE, password-reset enumeration defense, CSRF for non-GET RPCs, rate limiting auth endpoints, session rotation on privilege change. Pairs with router-core/auth-and-guards for the routing side.
Как установить скилл auth-server-primitives?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл auth-server-primitives запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic