Skip to content

breaking(auth): replace auth from lucia to self-managed session/credentials#3864

Open
KATO-Hiro wants to merge 11 commits into
stagingfrom
#3855
Open

breaking(auth): replace auth from lucia to self-managed session/credentials#3864
KATO-Hiro wants to merge 11 commits into
stagingfrom
#3855

Conversation

@KATO-Hiro

@KATO-Hiro KATO-Hiro commented Jul 15, 2026

Copy link
Copy Markdown
Collaborator

close #3855

Summary by CodeRabbit

  • 新機能
    • 自前のセッション認証に対応し、ログイン・新規登録・ログアウトの処理を改善しました。
    • セッションの有効期限管理、無効化、Cookie更新に対応しました。
    • パスワードの安全なハッシュ化と検証を追加しました。
  • 改善
    • 既存の認証情報との互換性を維持しながら、認証処理を安定化しました。
    • ユーザー名の重複時に適切なエラーを表示します。
  • ドキュメント
    • 認証方式や開発ルールの説明を更新しました。

KATO-Hiro and others added 11 commits July 15, 2026 07:10
Ports lucia v2's scrypt-based hash/verify and random string generation
so existing password hashes stay valid without a data migration, ahead
of removing the lucia dependency itself.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Reimplements lucia v2's session create/validate/invalidate semantics
(24h active + 14d idle window, idle-triggered renewal without id
rotation, idempotent delete) directly against Prisma, continuing the
lucia dependency removal alongside the password hashing utilities.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Adds createAuthRequest as a lucia-free replacement for
auth.handleRequest(event), backed by the new session service
(validateSession) and session cookie constants. Wires it into
hooks.server.ts and retypes app.d.ts's Locals.auth accordingly.
The lucia import in auth.ts is still present pending full removal.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
…sion/credentials

Replaces lucia's createUser/createSession/useKey/invalidateSession
calls in the login, signup, and logout routes with the new
credentials service (registerUser/authenticateUser) and session
service (createSession/invalidateSession) added in prior commits.
Drops @lucia-auth/adapter-prisma and lucia from package.json/lockfile,
removes the lucia auth() export, and cleans up now-stale lucia
references in schema.prisma, database.ts, app.d.ts, and auth.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Updates stale "Lucia" wording in e2e comments, drops the removed
@lucia-auth/adapter-prisma package from vite's test.deps.exclude, and
aligns seed.ts's key id casing with credentials.ts's buildKeyId
(toLowerCase, not toLocaleLowerCase). Adds the lucia removal plan doc.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
validateSession's renewal update could race with a concurrent logout
deleting the same row between findUnique and update, surfacing an
unhandled P2025 as a 500. Treat that case as an expired/gone session
instead.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
…nd remaining tasks

Checks off all Phase 1-5 tasks and appends the mandatory refactor-cycle
notes: novel lessons (lucia v2 idle renewal doesn't reissue the cookie,
vendored-source verification via npm pack, brace-expansion pitfall in
grep --include, rules doc duplication) and remaining low-priority tasks
(cookie sliding expiry, timing-safe username enumeration, a doc typo).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Promotes a novel lesson from the remove-lucia-v2 refactor cycle
(docs/dev-notes/2026-07-05/remove-lucia-v2/plan.md): grep --include
with brace expansion silently matches nothing, and repo-wide sweeps
must cover root files, e2e/, and config, not just src/prisma/.claude.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Migration is complete and its novel lessons already folded into
.claude/rules/coding-style.md (08bbc3f).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Lucia依存を削除し、セッション管理、パスワードハッシュ、資格情報認証を自前実装へ移行しました。認証ルート、サーバーフック、型定義、シード処理、関連ドキュメントと設定も更新されています。

Changes

自前認証基盤

Layer / File(s) Summary
セッションと認証リクエスト
src/lib/server/session.ts, src/lib/server/auth.ts, src/app.d.ts, src/lib/server/*test.ts
24時間のアクティブ期限と14日のアイドル期限を持つセッション発行・検証・無効化、auth_session Cookie、検証結果のリクエスト内キャッシュを追加しました。
資格情報と暗号処理
src/lib/server/password.ts, src/lib/server/random.ts, src/features/auth/services/*, prisma/seed.ts
scryptによるs2形式のパスワード処理、ランダムID生成、登録・認証サービスを追加し、成功・失敗・互換性をテストしました。
認証ルートへの統合
src/hooks.server.ts, src/routes/(auth)/*
ログイン、サインアップ、ログアウト、サーバーフックを新しい認証APIへ切り替えました。
依存関係と認証参照の整理
.claude/rules/*, CONTRIBUTING.md, package.json, prisma/schema.prisma, vite.config.ts, e2e/problems_cache.spec.ts
Lucia依存と関連設定・参照を削除し、自前セッション認証と残存参照検索の方針を記載しました。

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant LoginRoute
  participant Credentials
  participant Session
  participant AuthRequest
  LoginRoute->>Credentials: authenticateUser(username, password)
  Credentials-->>LoginRoute: userId または null
  LoginRoute->>Session: createSession(userId)
  Session-->>LoginRoute: SessionCookieData
  LoginRoute->>AuthRequest: setSession(session)
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Lucia と Prisma アダプタの削除、自前セッション/パスワード実装、関連ルート・型・文書の更新が要件に沿っています。
Out of Scope Changes check ✅ Passed 認証置き換えに伴うテスト・型・設定・文書の更新で、明確な無関係変更は見当たりません。
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Lucia から自前のセッション/認証実装への置き換えを正確に要約しており、変更内容と一致しています。
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch #3855

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@KATO-Hiro KATO-Hiro changed the title breaking(auth): replace lucia from to auth on self-managed session/credentials breaking(auth): replace auth from lucia to self-managed session/credentials Jul 15, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/routes/(auth)/signup/+page.server.ts (1)

40-56: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

ユーザー登録と初期セッション発行を一貫した結果にしてください。

registerUser成功後にcreateSessionが失敗すると、ユーザーと資格情報だけが永続化されます。画面上は登録失敗になりますが、再試行は「使用済みユーザー名」となります。

同一トランザクションで登録とセッションを作成するか、登録成功後のセッション障害を「登録成功・ログイン失敗」として扱ってください。

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/routes/`(auth)/signup/+page.server.ts around lines 40 - 56, Update the
signup flow around registerUser and createSession so a successful user
registration cannot be reported as a generic registration failure when session
creation fails. Use a single transaction for registration and session creation,
or explicitly handle post-registration session failures as registration success
with login failure, preserving the duplicate-username handling for registerUser
returning null.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@prisma/seed.ts`:
- Around line 132-137: Rename the local variable hashed_password to
hashedPassword in the seed flow, including its declaration and references in
keyFactory.create. Preserve the database field name hashed_password unchanged.

In `@src/features/auth/services/credentials.ts`:
- Around line 43-51: Update the credential verification flow in
src/features/auth/services/credentials.ts lines 43-51 so missing keys or null
hashed_password values still call verifyPassword with a fixed dummy hash before
returning null. Update the corresponding expectations in
src/features/auth/services/credentials.test.ts lines 128-144 to assert that the
dummy hash is verified instead of expecting no verification.

In `@src/lib/server/auth.test.ts`:
- Around line 74-99: Add a test in the validate session tests covering an
idle-extension response from validateSession(). Configure the mock to return the
existing session ID with a later idlePeriodExpiresAt, call auth.validate(), and
verify event.cookies.set updates the same SESSION_COOKIE_NAME and session ID
with the refreshed expires value and existing cookie attributes.

In `@src/lib/server/session.test.ts`:
- Around line 127-150: Update the idle-session tests around validateSession to
assert that the returned authentication result includes the refreshed
idlePeriodExpiresAt after extending the session. Verify the expected expiration
value alongside the existing database update assertions, while preserving the
current same-ID and boundary-case behavior.

In `@src/lib/server/session.ts`:
- Around line 54-64:
アイドル延長時の新しい有効期限をセッション検証結果からCookie設定まで渡してください。src/lib/server/session.ts:54-64 の
validateSession() は更新後の idle_expires を返し、src/lib/server/auth.ts:51-55 の
validate() は成功時にその期限を使って cookies.set
を再実行してください。src/lib/server/session.test.ts:127-150
では延長期限の返却を、src/lib/server/auth.test.ts:74-99 では延長後 expires での cookies.set
を検証してください。
- Around line 49-52: Update validateSession in src/lib/server/session.ts to
delete the expired session record when now exceeds session.idle_expires before
returning null, using the existing session storage mechanism. Update
src/lib/server/session.test.ts lines 171-180 to assert that expired-session
validation removes the session instead of preserving it.

---

Outside diff comments:
In `@src/routes/`(auth)/signup/+page.server.ts:
- Around line 40-56: Update the signup flow around registerUser and
createSession so a successful user registration cannot be reported as a generic
registration failure when session creation fails. Use a single transaction for
registration and session creation, or explicitly handle post-registration
session failures as registration success with login failure, preserving the
duplicate-username handling for registerUser returning null.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: b07aade6-2b09-445d-841f-b1baa44c6180

📥 Commits

Reviewing files that changed from the base of the PR and between dd6d2e2 and fffdea1.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml, !pnpm-lock.yaml
📒 Files selected for processing (28)
  • .claude/rules/auth.md
  • .claude/rules/coding-style.md
  • CONTRIBUTING.md
  • e2e/problems_cache.spec.ts
  • package.json
  • prisma/schema.prisma
  • prisma/seed.ts
  • src/app.d.ts
  • src/features/account/services/atcoder_verification.test.ts
  • src/features/auth/services/credentials.test.ts
  • src/features/auth/services/credentials.ts
  • src/hooks.server.ts
  • src/lib/server/auth.test.ts
  • src/lib/server/auth.ts
  • src/lib/server/database.ts
  • src/lib/server/password.test.ts
  • src/lib/server/password.ts
  • src/lib/server/random.test.ts
  • src/lib/server/random.ts
  • src/lib/server/session.test.ts
  • src/lib/server/session.ts
  • src/routes/(auth)/login/+page.server.ts
  • src/routes/(auth)/logout/+page.server.ts
  • src/routes/(auth)/signup/+page.server.ts
  • src/routes/+layout.server.ts
  • src/routes/+page.server.ts
  • src/routes/+page.svelte
  • vite.config.ts
💤 Files with no reviewable changes (5)
  • src/routes/+page.svelte
  • package.json
  • src/routes/+layout.server.ts
  • src/routes/+page.server.ts
  • src/lib/server/database.ts

Comment thread prisma/seed.ts
Comment thread src/features/auth/services/credentials.ts
Comment thread src/lib/server/auth.test.ts
Comment thread src/lib/server/session.test.ts
Comment thread src/lib/server/session.ts
Comment thread src/lib/server/session.ts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[deps] EOL となった認証ライブラリを削除 + 自前実装に変更しましょう

1 participant