Sessions + OAuth (GitHub, Google) avec Drizzle, pour Hono et Next.js
Installer
genpm add @core/authCe que vous obtenez
- Source dans src/lib/auth/, 9 fichiers. (26 ko)
- Règles IA dans src/lib/auth/AGENTS.md, plus les fichiers de règles de l’IDE.
- Variables d’environnement ajoutées à .env.example : AUTH_SECRET, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET.
- Résout @core/db pour vous.
README
@core/auth
Sessions + OAuth (GitHub, Google) with Drizzle, for Hono and Next.js
A GenPM module: source code + AI rules + MCP config, injected into your project instead of hidden in node_modules. The code lands in src/lib/auth, pinned to a verified commit, and you own it.
Install
genpm add @core/authNo genpm yet? curl -fsSL https://genpm.net/install.sh | sh (macOS/Linux), irm https://genpm.net/install.ps1 | iex (Windows), or one-off with npx @genpm-net/cli add @core/auth.
Or let your AI agent do it: run genpm mcp setup once, then ask "add @core/auth with genpm" in Claude Code, Cursor, VS Code, Windsurf, Codex or Gemini CLI. It shows you a dry-run plan before writing anything.
What it does
Cookie sessions (random token, only its SHA-256 stored, 30-day sliding expiry, rotation) and OAuth login with GitHub
and Google via arctic. Tables: users, auth_sessions, oauth_accounts. No roles or permissions (out of scope:
build them in your app on top of users.id). No passwords.
Setup
After genpm add, follow these steps (your AI agent finds the same steps in src/lib/auth/AGENTS.md and can do them for you):
- Env:
AUTH_SECRET(≥ 32 random chars, e.g.openssl rand -base64 32),GITHUB_CLIENT_ID,GITHUB_CLIENT_SECRET. Optional Google:GOOGLE_CLIENT_ID,GOOGLE_CLIENT_SECRET. Providers without both vars are disabled. - OAuth app callback URL:
<origin>/auth/callback/github(and/auth/callback/google). - Generate and apply migrations (see
src/lib/db/AGENTS.md). - Hono:
Next.js (App Router): createimport { authRoutes, requireUser, sessionMiddleware } from './lib/auth/adapters/hono.ts'; app.use(sessionMiddleware); app.route('/auth', authRoutes()); app.get('/api/me', requireUser, (c) => c.json(c.get('user')));app/auth/login/[provider]/route.tswithexport { loginRoute as GET } from '@/lib/auth/adapters/next', the same forcallback/[provider](callbackRoute) andapp/auth/logout/route.ts(logoutRoute as POST). In Server Components:const user = await getUser(await cookies()). Delete the adapter of the framework you don't use (adapters/hono.tsimportshono; in a Next project delete everysrc/lib/*/adapters/hono.ts, ortscfails). To react to logins (welcome email, onboarding):authRoutes({ onLogin: ({ user, isNewUser }) => … })in Hono,export const GET = callbackRouteWith({ onLogin })in Next.js.isNewUseris true only the first time. - Login link:
<a href="/auth/login/github?returnTo=/dashboard">. Logout:POST /auth/logout(a plain HTML form is redirected to/;fetchgets 204). - Verify: open
/auth/login/github, finish the flow, thenGET /api/mereturns the user.
What's inside
Paths are relative to src/lib/auth.
index.ts— public API:getUserFromCookieHeader,signOut,startOAuth,finishOAuth, session functions,User.adapters/hono.ts—sessionMiddleware,requireUser,authRoutes().adapters/next.ts—loginRoute,callbackRoute,logoutRoute,getUser(cookies).schema.ts— Drizzle tables. Depends on../db(@core/db).
At a glance
- GenPM dependencies (installed with it): @core/db
- npm dependencies (proposed, never installed without asking):
arctic,@oslojs/crypto,@oslojs/encoding - Environment variables (added to
.env.example):AUTH_SECRET,GITHUB_CLIENT_ID,GITHUB_CLIENT_SECRET - AI rules:
AGENTS.md, loaded by your agent only when it works insrc/lib/auth
Security
GenPM installs a 40-character commit SHA (never a branch), verifies an Ed25519-signed manifest, never runs install scripts and scans AI rules for prompt injection. Details: genpm.net/docs/security.
License
Voici exactement ce que lit votre IA quand elle travaille dans src/lib/auth. Rien d’autre n’est ajouté à son contexte.
@core/auth — rules for AI agents
Purpose
Cookie sessions (random token, only its SHA-256 stored, 30-day sliding expiry, rotation) and OAuth login with GitHub
and Google via arctic. Tables: users, auth_sessions, oauth_accounts. No roles or permissions (out of scope:
build them in your app on top of users.id). No passwords.
Map
index.ts— public API:getUserFromCookieHeader,signOut,startOAuth,finishOAuth, session functions,User.adapters/hono.ts—sessionMiddleware,requireUser,authRoutes().adapters/next.ts—loginRoute,callbackRoute,logoutRoute,getUser(cookies).schema.ts— Drizzle tables. Depends on../db(@core/db).
Integration
- Env:
AUTH_SECRET(≥ 32 random chars, e.g.openssl rand -base64 32),GITHUB_CLIENT_ID,GITHUB_CLIENT_SECRET. Optional Google:GOOGLE_CLIENT_ID,GOOGLE_CLIENT_SECRET. Providers without both vars are disabled. - OAuth app callback URL:
<origin>/auth/callback/github(and/auth/callback/google). - Generate and apply migrations (see
src/lib/db/AGENTS.md). - Hono:
Next.js (App Router): createimport { authRoutes, requireUser, sessionMiddleware } from './lib/auth/adapters/hono.ts'; app.use(sessionMiddleware); app.route('/auth', authRoutes()); app.get('/api/me', requireUser, (c) => c.json(c.get('user')));app/auth/login/[provider]/route.tswithexport { loginRoute as GET } from '@/lib/auth/adapters/next', the same forcallback/[provider](callbackRoute) andapp/auth/logout/route.ts(logoutRoute as POST). In Server Components:const user = await getUser(await cookies()). Delete the adapter of the framework you don't use (adapters/hono.tsimportshono; in a Next project delete everysrc/lib/*/adapters/hono.ts, ortscfails). To react to logins (welcome email, onboarding):authRoutes({ onLogin: ({ user, isNewUser }) => … })in Hono,export const GET = callbackRouteWith({ onLogin })in Next.js.isNewUseris true only the first time. - Login link:
<a href="/auth/login/github?returnTo=/dashboard">. Logout:POST /auth/logout(a plain HTML form is redirected to/;fetchgets 204). - Verify: open
/auth/login/github, finish the flow, thenGET /api/mereturns the user.
Conventions
- Read the current user only through
sessionMiddleware/getUser; never parse the cookie yourself. - Other modules reference
users.id(text,usr_…) withonDelete: 'cascade'orset null. - Call
rotateSessionafter a privilege change andinvalidateUserSessionswhen an account is compromised. - If you installed
@core/dbwith--dest, fix the../db/index.jsimports here.
Don't
- Don't store or log session tokens, OAuth codes or
AUTH_SECRET. - Don't link accounts by unverified email;
upsertOAuthUseralready enforces it. - Don't accept absolute
returnToURLs (open redirect); usesafeReturnTo. - Don't make GET requests log users out, and don't disable
HttpOnly/SameSiteon the cookie.
# @core/auth — rules for AI agents
## Purpose
Cookie sessions (random token, only its SHA-256 stored, 30-day sliding expiry, rotation) and OAuth login with GitHub
and Google via `arctic`. Tables: `users`, `auth_sessions`, `oauth_accounts`. No roles or permissions (out of scope:
build them in your app on top of `users.id`). No passwords.
## Map
- `index.ts` — public API: `getUserFromCookieHeader`, `signOut`, `startOAuth`, `finishOAuth`, session functions, `User`.
- `adapters/hono.ts` — `sessionMiddleware`, `requireUser`, `authRoutes()`.
- `adapters/next.ts` — `loginRoute`, `callbackRoute`, `logoutRoute`, `getUser(cookies)`.
- `schema.ts` — Drizzle tables. Depends on `../db` (@core/db).
## Integration
1. Env: `AUTH_SECRET` (≥ 32 random chars, e.g. `openssl rand -base64 32`), `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`.
Optional Google: `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`. Providers without both vars are disabled.
2. OAuth app callback URL: `<origin>/auth/callback/github` (and `/auth/callback/google`).
3. Generate and apply migrations (see `src/lib/db/AGENTS.md`).
4. Hono:
```ts
import { authRoutes, requireUser, sessionMiddleware } from './lib/auth/adapters/hono.ts';
app.use(sessionMiddleware);
app.route('/auth', authRoutes());
app.get('/api/me', requireUser, (c) => c.json(c.get('user')));
```
Next.js (App Router): create `app/auth/login/[provider]/route.ts` with `export { loginRoute as GET } from '@/lib/auth/adapters/next'`,
the same for `callback/[provider]` (`callbackRoute`) and `app/auth/logout/route.ts` (`logoutRoute as POST`).
In Server Components: `const user = await getUser(await cookies())`.
Delete the adapter of the framework you don't use (`adapters/hono.ts` imports `hono`; in a Next project delete every
`src/lib/*/adapters/hono.ts`, or `tsc` fails).
To react to logins (welcome email, onboarding): `authRoutes({ onLogin: ({ user, isNewUser }) => … })` in Hono,
`export const GET = callbackRouteWith({ onLogin })` in Next.js. `isNewUser` is true only the first time.
5. Login link: `<a href="/auth/login/github?returnTo=/dashboard">`. Logout: `POST /auth/logout` (a plain HTML form is redirected to `/`; `fetch` gets 204).
6. Verify: open `/auth/login/github`, finish the flow, then `GET /api/me` returns the user.
## Conventions
- Read the current user only through `sessionMiddleware`/`getUser`; never parse the cookie yourself.
- Other modules reference `users.id` (text, `usr_…`) with `onDelete: 'cascade'` or `set null`.
- Call `rotateSession` after a privilege change and `invalidateUserSessions` when an account is compromised.
- If you installed `@core/db` with `--dest`, fix the `../db/index.js` imports here.
## Don't
- Don't store or log session tokens, OAuth codes or `AUTH_SECRET`.
- Don't link accounts by unverified email; `upsertOAuthUser` already enforces it.
- Don't accept absolute `returnTo` URLs (open redirect); use `safeReturnTo`.
- Don't make GET requests log users out, and don't disable `HttpOnly`/`SameSite` on the cookie.
L’arborescence exacte qui sera injectée, après .genpmignore. Épinglée à
// Adaptador Next.js (App Router). Sin importar `next`: usa Request/Response estándar.
// app/auth/login/[provider]/route.ts → export const GET = loginRoute;
// app/auth/callback/[provider]/route.ts → export const GET = callbackRoute; (o callbackRouteWith({ onLogin }))
// app/auth/logout/route.ts → export const POST = logoutRoute;
// Server Components: `const user = await getUser(await cookies())` (cookies de 'next/headers').
import { AuthError, enabledProviders, finishOAuth, getUserFromCookieHeader, type LoginHook, type Provider, runLoginHook, SESSION_COOKIE, signOut, startOAuth, type User } from '../index.ts';
type Ctx = { params: Promise<{ provider: string }> };
type CookieStore = { get(name: string): { value: string } | undefined };
const isProvider = (p: string): p is Provider => (enabledProviders() as string[]).includes(p);
const json = (body: unknown, status: number) => Response.json(body, { status });
export async function loginRoute(req: Request, ctx: Ctx): Promise<Response> {
const { provider } = await ctx.params;
if (!isProvider(provider)) return json({ error: 'unknown_provider' }, 404);
const url = new URL(req.url);
const { url: to, setCookie } = startOAuth(provider, { origin: url.origin, returnTo: url.searchParams.get('returnTo') });
return new Response(null, { status: 302, headers: { location: to.toString(), 'set-cookie': setCookie } });
}
/** Callback con `onLogin` (se llama tras cada login correcto con `isNewUser`). */
export function callbackRouteWith(opts: { onLogin?: LoginHook } = {}) {
return (req: Request, ctx: Ctx) => callback(req, ctx, opts.onLogin);
}
export function callbackRoute(req: Request, ctx: Ctx): Promise<Response> {
return callback(req, ctx);
}
async function callback(req: Request, ctx: Ctx, onLogin?: LoginHook): Promise<Response> {
const { provider } = await ctx.params;
if (!isProvider(provider)) return json({ error: 'unknown_provider' }, 404);
try {
const r = await finishOAuth(provider, { url: req.url, cookieHeader: req.headers.get('cookie') });
await runLoginHook(onLogin, { user: r.user, isNewUser: r.isNewUser, provider });
const headers = new Headers({ location: r.returnTo });
for (const c of r.setCookies) headers.append('set-cookie', c);
return new Response(null, { status: 302, headers });
} catch (e) {
if (e instanceof AuthError) return json({ error: e.code }, e.code === 'invalid_state' ? 400 : 502);
throw e;
}
}
export async function logoutRoute(req: Request): Promise<Response> {
const headers = new Headers({ 'set-cookie': await signOut(req.headers.get('cookie')) });
// Un formulario HTML (`<form method="post" action="/auth/logout">`) vuelve a la portada; fetch() recibe 204.
if (!req.headers.get('accept')?.includes('text/html')) return new Response(null, { status: 204, headers });
headers.set('location', '/');
return new Response(null, { status: 303, headers });
}
/** Usuario actual en Server Components / Route Handlers: `getUser(await cookies())`. */
export async function getUser(cookies: CookieStore): Promise<User | null> {
const token = cookies.get(SESSION_COOKIE)?.value;
return token ? getUserFromCookieHeader(`${SESSION_COOKIE}=${encodeURIComponent(token)}`) : null;
}
Ce paquet ne déclare aucun serveur MCP.
- genpm
- @core/db ^1.0.0
- proposé
- GenPM propose la commande npm et ne l’exécute que si vous acceptez.
- analyse
- analyse réussie · 0 problème
- commit
- v1.2.1 → 986973cd937c39696cc0bcb61a6c8b7027dcad31 · vérifié après téléchargement
- scripts
- Aucun. GenPM n’exécute jamais le code des paquets.
- licence
- MIT
- Qualité
- 100/100
- Licence reconnuevalidé
- AGENTS.md explique son objectifvalidé
- AGENTS.md donne les étapes d’intégrationvalidé
- AGENTS.md liste conventions ou interditsvalidé
- Contient des testsvalidé
- Analyse de sécurité réussievalidé
- Publié au cours des 6 derniers moisvalidé
- Éditeur vérifiévalidé
- Résumé et mots-clésvalidé
- signalement
- Vous avez repéré un problème ?