セッション + OAuth(GitHub、Google)、Drizzle 使用、Hono と Next.js 対応
コード9 ファイルコンテキスト約 670 トークンスキャン合格
インストール
$
genpm add @core/auth含まれるもの
- src/lib/auth/ にソースコード(9 ファイル)。 (23.2 KB)
- src/lib/auth/AGENTS.md に AI ルール、加えて IDE 用のルールファイル。
- .env.example に追加される環境変数: AUTH_SECRET, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET。
- @core/db を自動で解決します。
README
このパッケージには README がありません。
約 670 トークン→ src/lib/auth/AGENTS.md→ .cursor/rules/genpm-core-auth.mdc
これは 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.js'; 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). - Login link:
<a href="/auth/login/github?returnTo=/dashboard">. Logout:POST /auth/logout. - 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.js';
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`).
5. Login link: `<a href="/auth/login/github?returnTo=/dashboard">`. Logout: `POST /auth/logout`.
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 適用後に組み込まれる正確なツリーです。固定先:
// Tablas de @core/auth. Las recoge drizzle-kit vía src/lib/db/drizzle.config.ts.
import { index, pgTable, primaryKey, text, timestamp } from 'drizzle-orm/pg-core';
import { primaryId, timestamps } from '../db/index.js';
export const users = pgTable('users', {
id: primaryId('usr'),
email: text('email').unique(),
name: text('name'),
avatarUrl: text('avatar_url'),
...timestamps,
});
/** El id de la sesión es el SHA-256 del token: un volcado de la BD no permite suplantar a nadie. */
export const authSessions = pgTable(
'auth_sessions',
{
id: text('id').primaryKey(),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
expiresAt: timestamp('expires_at', { withTimezone: true, mode: 'date' }).notNull(),
...timestamps,
},
(t) => [index('auth_sessions_user_idx').on(t.userId)],
);
export const oauthAccounts = pgTable(
'oauth_accounts',
{
provider: text('provider', { enum: ['github', 'google'] }).notNull(),
providerUserId: text('provider_user_id').notNull(),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
...timestamps,
},
(t) => [primaryKey({ columns: [t.provider, t.providerUserId] }), index('oauth_accounts_user_idx').on(t.userId)],
);
export type User = typeof users.$inferSelect;
export type Session = typeof authSessions.$inferSelect;
このパッケージは MCP サーバーを宣言していません。
| バージョン | コミット | 公開日 | スキャン |
|---|---|---|---|
| 1.0.0 | 12c4918 | 4 時間前 | ✔ スキャン合格 |
- genpm
- @core/db ^1.0.0
- 提案
- GenPM は npm コマンドを提案し、あなたが承認した場合にのみ実行します。
- スキャン
- スキャン合格 · 指摘 0 件
- コミット
- v1.0.0 → 12c4918f68aa7cb6062a976347bf6a7d691cc218 · 取得後に検証済み
- スクリプト
- なし。GenPM はパッケージのコードを実行しません。
- ライセンス
- MIT
- 報告
- 問題を見つけましたか?