Skip to content

Conversation

@andrewck24
Copy link
Owner

Summary

This release contains two major updates to the VolleyBro codebase:

  1. Authentication System Migration: Complete migration from NextAuth.js v5 to Better Auth with Clean Architecture implementation
  2. Development Framework Migration: Transition from BMad to Spec-kit development framework for improved project organization

Major Changes

1. Authentication Framework Migration (PR #264)

Core Authentication Updates

  • Migrated from NextAuth.js v5 to Better Auth 1.3.3
  • Configured Google OAuth 2.0 provider with server-side (auth.ts) and client-side (auth-client.ts) authentication
  • Implemented automated session validation across all API routes

User-Profile Separation Architecture

  • User: Authentication data managed by Better Auth (email, name, image, emailVerified)
  • Profile: Business data managed by application (teams.joined[], teams.inviting[], and future user info fields)
  • Automatic Profile creation via Better Auth database hooks with fallback mechanism

Clean Architecture Implementation

  • Created Use Cases: GetProfileUseCase, CreateProfileUseCase, UpdateProfileUseCase
  • Created Controllers: getProfileController, createProfileController, updateProfileController
  • Implemented Profile Repository with MongoDB/Mongoose
  • Integrated with InversifyJS DI container

API Refactoring

  • Refactored /api/profiles to use controllers and use cases following layered architecture
  • Migrated /api/teams and /api/members routes from .js to .ts
  • Added fallback mechanism for profile auto-creation
  • Updated all routes to use Better Auth session validation

ESLint Modernization

  • Migrated from legacy .eslintrc.json to flat config (eslint.config.mjs)
  • Fixed TypeScript errors across the codebase
  • Updated dependencies to support flat config

Comprehensive Documentation

2. Development Framework Migration

Spec-kit Framework Adoption

  • Migrated from BMad development framework to Spec-kit
  • Removed all .bmad-core/, .claude/commands/BMad/, and .gemini/bmad-method/ directories
  • Added .specify/ directory with new framework structure:
    • Scripts: check-prerequisites.sh, create-new-feature.sh, setup-plan.sh, update-agent-context.sh
    • Templates: agent-file-template.md, checklist-template.md, plan-template.md, spec-template.md, tasks-template.md
    • Constitution: Project principles and guidelines in memory/constitution.md

Benefits of Spec-kit

  • Streamlined feature development workflow with shell scripts
  • Standardized templates for specifications, plans, and tasks
  • Better integration with Claude Code and agent-based development
  • Simplified project organization and documentation structure

Database Changes

User Collection

  • Removed fields: teams, info, preferences
  • Updated field: emailVerified changed from Date to boolean
  • Retains Better Auth managed fields: email, name, image

Profile Collection (New)

  • Added collection with fields: userId, teams.joined[], teams.inviting[]
  • Prepared for future user information fields
  • Migration completed (see migration docs)

Breaking Changes

Environment Variables

  • Removed: AUTH_SECRET, NEXTAUTH_URL
  • Added: BETTER_AUTH_SECRET, BETTER_AUTH_URL

Session Structure

  • Updated from NextAuth session to Better Auth session format
  • All API routes now use auth.api.getSession() for validation

API Changes

  • Profile data now accessed via separate /api/profiles endpoint
  • Team and member routes migrated to TypeScript with updated session handling

Dependencies

Added

Removed

Test Plan

  • Build succeeds (npm run build)
  • Lint passes (npm run lint)
  • TypeScript compilation successful
  • Manual testing: Google OAuth sign-in flow
  • Manual testing: Profile auto-creation
  • Manual testing: Fallback mechanism
  • Spec-kit scripts executable and functional

Known Issues & Follow-up Tasks

  • Test coverage for Better Auth integration (Low priority)
  • Migration of existing user guides to Spec-kit format (Planned)

Files Changed

  • 187 files changed: 8,032 insertions(+), 26,287 deletions(-)
  • Major cleanup of deprecated framework files
  • Comprehensive documentation updates
  • TypeScript migration of API routes

摘要

此版本包含兩項主要更新:

1. 驗證系統遷移(PR #264

核心驗證更新

  • 從 NextAuth.js v5 遷移至 Better Auth 1.3.3
  • 配置 Google OAuth 2.0,支援伺服器端與客戶端驗證
  • 實作所有 API 路由的自動化 session 驗證

User-Profile 分離架構

  • User:由 Better Auth 管理的驗證資料(email, name, image, emailVerified)
  • Profile:由應用程式管理的業務資料(teams.joined[], teams.inviting[] 及未來使用者資訊欄位)
  • 透過 Better Auth 資料庫 hooks 自動建立 Profile,並提供 fallback 機制

Clean Architecture 實作

  • 新增 Use Cases:GetProfileUseCase, CreateProfileUseCase, UpdateProfileUseCase
  • 新增 Controllers:getProfileController, createProfileController, updateProfileController
  • 實作 Profile Repository(MongoDB/Mongoose)
  • 整合至 InversifyJS DI 容器

API 重構

  • 重構 /api/profiles 使用 controllers 與 use cases,遵循分層架構
  • /api/teams/api/members.js 遷移至 .ts
  • 新增 Profile 自動建立的 fallback 機制
  • 所有路由更新為使用 Better Auth session 驗證

ESLint 現代化

  • 從舊版 .eslintrc.json 遷移至 flat config (eslint.config.mjs)
  • 修復整個程式碼庫的 TypeScript 錯誤
  • 更新相依套件以支援 flat config

完整文件

  • 新增使用者管理概述、建立流程、資料同步等詳細文件
  • 更新技術堆疊與原始碼結構文件

2. 開發框架遷移

採用 Spec-kit 框架

  • 從 BMad 開發框架遷移至 Spec-kit
  • 移除所有 .bmad-core/.claude/commands/BMad/.gemini/bmad-method/ 目錄(-26,287 行)
  • 新增 .specify/ 目錄,包含:
    • 腳本:先決條件檢查、新功能建立、計畫設定、agent 上下文更新
    • 模板:agent 檔案、檢查清單、計畫、規格、任務
    • Constitution:專案原則與指南

Spec-kit 優勢

  • 透過 shell 腳本簡化功能開發工作流程
  • 標準化的規格、計畫、任務模板
  • 更好的 Claude Code 與 agent-based 開發整合
  • 簡化專案組織與文件結構

資料庫變更

User Collection

  • 移除欄位:teams, info, preferences
  • 更新欄位:emailVerified 從 Date 改為 boolean
  • 保留 Better Auth 管理的欄位:email, name, image

Profile Collection(新增)

  • 新增 collection,包含 userId, teams.joined[], teams.inviting[]
  • 預留未來使用者資訊欄位
  • 已完成資料遷移(詳見遷移文件)

重大變更

環境變數

  • 移除:AUTH_SECRET, NEXTAUTH_URL
  • 新增:BETTER_AUTH_SECRET, BETTER_AUTH_URL

Session 結構

  • 從 NextAuth session 更新為 Better Auth session 格式
  • 所有 API 路由改用 auth.api.getSession() 驗證

API 變更

  • Profile 資料現透過獨立的 /api/profiles endpoint 存取
  • Team 與 member 路由遷移至 TypeScript 並更新 session 處理

檔案變更

  • 187 個檔案變更:新增 8,032 行,刪除 26,287 行
  • 大量清理已廢棄的框架檔案
  • 全面更新文件
  • API 路由遷移至 TypeScript

已知問題與後續任務

  • Better Auth 整合測試覆蓋率(低優先度)
  • 現有使用者指南遷移至 Spec-kit 格式(已規劃)

andrewck24 and others added 9 commits December 13, 2025 19:18
BREAKING CHANGE: Authentication system migrated from NextAuth.js v5 to Better Auth

- Implement Better Auth with Google OAuth
  - Add Better Auth server config (src/lib/auth.ts)
  - Add Better Auth client (src/lib/auth-client.ts)
  - Configure MongoDB adapter for Better Auth
  - Add auth API route handler ([...all]/route.ts)

- Separate User and Profile entities
  - User: Authentication data (Better Auth managed)
  - Profile: Business data (teams, preferences)
  - Add Profile repository and schema
  - Auto-create profile on first access

- Update all API routes to use Better Auth session
  - Replace auth() with auth.api.getSession()
  - Standardize session checks (session?.user)
  - Implement email-based team inviting with User lookup

- Update components for Better Auth
  - Use authClient for sign-in flow
  - Add error handling to Home component
  - Remove SessionProvider wrapper

- Documentation and migration
  - Update CLAUDE.md with Better Auth flow
  - Archive migration script with documentation
  - Add migration guide in docs/archive/migrations/

Tests passing. Build has pre-existing TypeScript error in info-form.tsx
(unrelated to this migration, tracked for future fix).
…rors

- Migrate from `.eslintrc.json` to `eslint.config.mjs` (ESLint 9)
  - Configure Next.js core web vitals and TypeScript rules
  - Add Storybook, Testing Library, and Jest DOM plugins
  - Set custom rules for Clean Architecture patterns
  - Add global ignores including archived migrations

- Fix `info-form.tsx` TypeScript compilation error
  - Add explicit Resolver type assertion
  - Enhance decidingSetPoints schema with .int()

- Modernize `next.config.js`
  - Convert from CommonJS to ES modules
  - Simplify phase-based logic
  - Use `process.env.NODE_ENV` for environment detection

- Improve UI component types
  - Add `ChartTooltipContentProps` interface
  - Fix Recharts ResponsiveContainer warning with minHeight

- Optimize database schemas
  - Remove duplicate index definition in profile schema

Build and tests passing. ESLint warnings are pre-existing issues
tracked in `docs/stories/better-auth-follow-up.md`.
Implement automatic Profile creation when User is created via OAuth,
following Clean Architecture principles with Use Cases, Controllers,
and proper DI integration.

Key Changes:
- Add Profile Use Cases (Get, Create, Update) with InversifyJS DI
- Add Profile Controllers for orchestrating Use Cases
- Integrate Better Auth databaseHooks.user.create.after
- Refactor /api/profiles to use Controllers (remove direct Mongoose)
- Add fallback mechanism for reliability

Architecture Improvements:
- Remove direct Mongoose operations from API routes
- Implement Controller → Use Case → Repository pattern
- Maintain business logic in Use Cases (duplicate checks)
- Non-blocking design (profile creation failure doesn't block login)

Documentation:
- Add comprehensive User Management docs (index, flow, sync)
- Document design decisions (User vs Profile separation)
- Update architecture docs (source tree)
- Add future planning (custom name/image fields)

Testing:
- Build: ✅ Passing
- Lint: ✅ No errors in modified files
- Manual testing: Passed
Implement Clean Architecture validation layers for Profile API endpoints:

- Controller Layer: Format and transport validation using Zod schemas
  - Add UpdateProfileRequestSchema for request format validation
  - Add ValidationError class for format validation errors
  - Validate teams, info, preferences data types and structure

- Use Case Layer: Business rules validation
  - Prevent updates to immutable fields (userId, _id)
  - Validate Profile existence before updates
  - Ensure teams arrays are properly formatted
  - Add BusinessRuleError class for business logic errors

- API Route Layer: Error handling and HTTP response formatting
  - Remove direct userId validation (migrated to Use Case)
  - Add proper error handling for ValidationError and BusinessRuleError
  - Return appropriate HTTP status codes (400 for validation/business errors)

Files changed:
- src/interface/controllers/user/profile.controller.ts
- src/applications/usecases/user/profile.usecase.ts
- src/app/api/profiles/route.ts
…okies

- Create User component at src/components/user/index.tsx
- Replace server-side sign-out with authClient.signOut() for proper cookie cleanup
- Use client-side navigation (useRouter) instead of server-side redirect
- Simplify user page to only render User component

Server-side sign-out with redirect failed to clear Better Auth session cookies, causing incomplete logout. Client-side authClient.signOut() properly clears all authentication state and cookies before navigation.
feat(auth): migrate from NextAuth.js to Better Auth
Remove BMad development framework files:
- Remove .bmad-core/ agent teams, agents, checklists, tasks, templates, workflows
- Remove .claude/commands/BMad/ agent definitions and tasks
- Remove .gemini/bmad-method/ configuration

Add Spec-kit framework for feature development:
- Add .specify/memory/constitution.md (v1.0.0) establishing five core principles
- Add .specify/templates/ for spec, plan, tasks, checklist, and agent file templates
- Add .specify/scripts/bash/ helper scripts for prerequisites, feature creation, and setup
- Update .gitignore to exclude AI agent directories
@vercel
Copy link

vercel bot commented Dec 20, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
volleybro Ready Ready Preview, Comment Dec 20, 2025 5:19pm

@claude
Copy link

claude bot commented Dec 20, 2025

Claude finished @andrewck24's task —— View job


PR Review Complete: Better Auth Migration and Spec-kit Framework Adoption

I've conducted a comprehensive review of this major migration PR. Here's my analysis:

Code Quality Assessment: EXCELLENT

This is a well-executed migration that demonstrates strong architectural discipline and attention to detail.

Strengths

1. Clean Architecture Implementation 🏛️

  • Excellent layered architecture: The User-Profile separation follows Clean Architecture principles perfectly
  • Proper dependency injection: InversifyJS integration is clean and well-structured
  • Controller → UseCase → Repository pattern: Correctly implemented with proper error handling
  • Domain separation: Authentication (Better Auth) vs Business logic (Profile) separation is architecturally sound

Example: src/interface/controllers/user/profile.controller.ts:53-60 - Controllers properly delegate to Use Cases without business logic

2. Security Best Practices 🔐

  • Session validation: Consistent auth.api.getSession() usage across all API routes
  • Input validation: Zod schemas with .strict() prevent unknown fields
  • Error handling: Proper error boundaries with different error types (ValidationError vs BusinessRuleError)
  • Environment variables: Proper separation of auth secrets

Security concern addressed: src/lib/auth.ts:22-25 - Credentials properly sourced from environment variables

3. Robust Error Handling

  • Layered error handling: Controller validation → Use Case business rules → Repository data access
  • Fallback mechanisms: Profile auto-creation fallback when hooks fail (src/app/api/profiles/route.ts:31-49)
  • Comprehensive error types: ValidationError, BusinessRuleError with proper HTTP status codes

4. ESLint Modernization 🛠️

  • Excellent flat config migration: eslint.config.mjs properly structured
  • TypeScript integration: Correct handling of unused vars and empty interfaces for Clean Architecture
  • Testing configuration: Proper test file targeting and plugin integration

Technical Improvements

1. Database Architecture 📊

// BEFORE: Coupled authentication and business data
User: { email, teams, info, preferences }

// AFTER: Separated concerns
User: { email, name, image, emailVerified }        // Auth data
Profile: { userId, teams: {joined[], inviting[]} } // Business data

This separation enables:

  • Independent auth system upgrades
  • Better data modeling flexibility
  • Cleaner testing boundaries

2. API Route Quality 🌐

The TypeScript migration of API routes shows significant quality improvements:

  • Type safety: .js.ts with proper typing
  • Session handling: Consistent Better Auth integration
  • Error responses: Standardized error formatting

3. Framework Migration Excellence 📋

The BMad → Spec-kit migration is thorough:

  • Complete cleanup: -26,287 lines of deprecated framework files removed
  • New structure: Well-organized .specify/ directory with clear templates and constitution
  • Documentation: Comprehensive constitution with governance principles

🔍 Potential Issues & Recommendations

Minor Security Considerations

  1. Console logging in production (src/lib/auth.ts:31-44):

    console.log(`[Better Auth Hook] User created: ${user.id}`);

    Recommendation: Consider using a proper logging service in production and avoid logging sensitive data.

  2. Missing rate limiting: Authentication endpoints could benefit from rate limiting for better security.

Performance Considerations

  1. Database queries: Profile creation includes a findByUserId check followed by create - consider using upsert operations for better performance
  2. Session validation: Every API call validates session - consider implementing session caching

Code Quality Improvements

  1. Error messages: Some error messages could be more descriptive:

    // Current
    { error: "Internal server error" }
    
    // Better
    { error: "Failed to retrieve user profile", code: "PROFILE_FETCH_ERROR" }
  2. Type safety: Consider adding runtime validation for environment variables using a schema validator

Test Coverage Gaps

Based on jest.setup.ts, testing infrastructure is solid, but consider:

  • Integration tests for the Better Auth migration flow
  • API route tests for the new TypeScript endpoints
  • Error scenario testing for the fallback mechanisms

📋 Migration Completeness

Completed Successfully

  • NextAuth.js → Better Auth migration
  • User-Profile data separation
  • Clean Architecture implementation
  • API routes TypeScript conversion
  • ESLint flat config migration
  • BMad → Spec-kit framework migration
  • Comprehensive documentation

⚠️ Follow-up Recommendations

  1. Add integration tests for the auth migration
  2. Implement rate limiting on authentication endpoints
  3. Add logging service for production environments
  4. Consider session caching for performance
  5. Add error code standards for better API responses

🎯 Overall Assessment

APPROVED ✅ This is an exemplary migration PR that:

  • Follows Clean Architecture principles rigorously
  • Implements security best practices
  • Maintains high code quality standards
  • Provides comprehensive documentation
  • Successfully modernizes the development framework

The codebase is significantly improved with better separation of concerns, enhanced maintainability, and modern development practices.

Risk Level: LOW - Well-planned migration with proper fallback mechanisms and thorough testing structure.


@andrewck24 andrewck24 merged commit ca5dc72 into main Dec 20, 2025
4 checks passed
@github-actions
Copy link

🎉 This PR is included in version 1.0.0 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

@github-actions
Copy link

🎉 This PR is included in version 1.0.0 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

1 similar comment
@github-actions
Copy link

🎉 This PR is included in version 1.0.0 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants