세션 + OAuth(GitHub, Google), Drizzle 기반, Hono와 Next.js 지원
설치
genpm add @core/auth포함 내용
- src/lib/auth/에 소스 코드, 파일 9개. (26kB)
- src/lib/auth/AGENTS.md에 AI 규칙, 그리고 IDE 규칙 파일.
- .env.example에 추가되는 환경 변수: AUTH_SECRET, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET.
- @core/db을(를) 자동으로 해결합니다.
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
이것이 AI가 src/lib/auth에서 작업할 때 읽는 내용 그대로입니다. 그 외에는 컨텍스트에 아무것도 추가되지 않습니다.
@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.
.genpmignore 적용 후 주입될 정확한 트리입니다. 고정 대상:
// Cookies de sesión y de estado OAuth, sin dependencias de framework (devuelven cabeceras Set-Cookie).
import { SESSION_TTL_MS } from './session.ts';
export const SESSION_COOKIE = 'session';
const secure = () => process.env.NODE_ENV === 'production';
export function serializeCookie(name: string, value: string, maxAgeSeconds: number): string {
const parts = [`${name}=${encodeURIComponent(value)}`, 'Path=/', 'HttpOnly', 'SameSite=Lax', `Max-Age=${maxAgeSeconds}`];
if (secure()) parts.push('Secure');
return parts.join('; ');
}
export function parseCookies(header: string | null | undefined): Record<string, string> {
const out: Record<string, string> = {};
for (const part of (header ?? '').split(';')) {
const i = part.indexOf('=');
if (i < 1) continue;
try {
out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
} catch {
// cookie mal codificada: se ignora
}
}
return out;
}
export const sessionCookie = (token: string) => serializeCookie(SESSION_COOKIE, token, SESSION_TTL_MS / 1000);
export const clearSessionCookie = () => serializeCookie(SESSION_COOKIE, '', 0);
이 패키지는 MCP 서버를 선언하지 않습니다.
- genpm
- @core/db ^1.0.0
- 제안됨
- GenPM은 npm 명령을 제안하고, 동의한 경우에만 실행합니다.
- 검사
- 검사 통과 · 문제 0건
- 커밋
- v1.2.1 → 986973cd937c39696cc0bcb61a6c8b7027dcad31 · 가져온 뒤 검증됨
- 스크립트
- 없음. GenPM은 패키지 코드를 절대 실행하지 않습니다.
- 라이선스
- MIT
- 품질
- 100/100
- 인정된 라이선스충족
- AGENTS.md에 목적 설명충족
- AGENTS.md에 통합 단계충족
- AGENTS.md에 규칙 또는 금지 사항충족
- 테스트 포함충족
- 보안 검사 통과충족
- 최근 6개월 내 게시충족
- 인증된 게시자충족
- 요약과 키워드충족
- 신고
- 문제가 있나요?