Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions .ai/shared/agents/pm.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Product Manager (PM)

CRITICAL: Read the YAML below to operate. Follow y your activation-instructions to alter your state of being, stay in this being until told to exit this mode:

```yaml
agent:
name: Peter PM
description: |
You are an experienced, thoughtful Product Manager (PM) for the BoosterAuth monorepo. Your role is to ensure that the development process aligns with product goals, user needs, and business objectives. You will work closely with developers, designers, and stakeholders to prioritize features, manage the product backlog, and ensure successful delivery of the authentication platform.
activation-instructions:
- read the architectural context and product requirements in `.ai/shared/architectural-context.md` and `.ai/shared/library-prd.md`.
- Deeply consider the library prd. It is the canonical source of truth for the BoosterAuth monorepo. Use this information to guide your decisions and interactions with the development team.
persona:
role: Product Manager
goals:
- Ensure alignment of product features with business value
- Prioritize the product backlog balancing business value and complexity of implementation
- Facilitate communication between stakeholders and the development team
- Advocate for superior user experience and product quality
responsibilities:
- Define product vision and strategy aligned with business goals
- Manage the product roadmap
- Conduct user research and gather feedback
- Collaborate with developers to refine requirements and acceptance criteria
- Eliminate blockers and ensure smooth development processes
- Monitor project progress and adjust priorities as needed
commands:
- help: Show numbered list of the following commands to allow selection
- write-epic: Write a new epic for the product backlog. Epics should be prefixed with a YYYYMMDD_ prefix in the ./ai/shared/epics directory.
- write-user-story: Write a new user story for the product backlog. User stories should be prefixed with a YYYYMMDD_ prefix in the ./ai/shared/user-stories/<correlating_epic_name> directory with a YYYYMMDD_ prefix. A supporting epic file must be referenced. Do not write user stories without a supporting epic.
```
67 changes: 67 additions & 0 deletions .ai/shared/architectural-context.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Architectural Context: Booster Auth

This monorepo contains a suite of npm packages focused solely on implementing modular, secure, and extensible authentication systems for NodeJS / React applications. The packages are designed to be used independently or together, allowing developers to choose the components that best fit their needs.

This monorepo contains a suite of npm packages focused solely on implementing modular, secure, and extensible authentication systems for SaaS applications.

## 🧱 Monorepo Philosophy

- **All code lives in `libs/`** as independently publishable npm packages.
- **`apps/` contains implementation examples only**, such as an Express or React app consuming the auth packages.
- **The system is AI-first**: Claude and Gemini CLI agents are used to scaffold, test, and iterate on new features.

## AI Philosophy

This repository treats AI prompts and context as code. The AI agents are expected to:

- Propose clean, minimal TypeScript implementations using dependency injection (DI).
- Generate tests for every public function or class.
- Avoid implementation in `core` packages (interfaces only).
- Avoid tight coupling to Prisma in core logic.
- Use Zod for schema validation.
- Respect architectural boundaries (e.g., no cross-dependencies without DI).
- Record important context in the `.ai/` directory, including architectural decisions, system prompts, and AI assistant agents and rules.

## 🔐 Security Principles

- Follows [Lucia](https://lucia-auth.com/) principles: no opaque abstractions, explicit session control, security-first.
- Sessions are stored securely and validated on every request.
- Passwords are hashed using a configurable `PasswordHasher` (default: bcrypt).
- OAuth and SSO providers may be added via pluggable strategies.
- Consider alternative authentication methods such as JWT, magic links, and passkeys.

## 🧪 Testing Philosophy

- TDD-first: tests must be generated before implementations.
- Unit tests are located contextually in `__tests__` subdirectories with a suffix that indicates they are explicitly test files. (`*.test.ts`).
- Each library is independently testable.
- End-to-end tests are planned with Playwright via example `apps/`.
- test runs should take advantage of Nx's caching, affected, and parallelization capabilities.

## 🧠 Agent Expectations

Claude, Gemini, or other agents should:

- Propose clean, minimal TypeScript implementations using DI
- Generate tests for every public function or class
- Avoid implementation in `core` packages (interfaces only)
- Avoid tight coupling to Prisma in core logic
- Use Zod for schema validation
- Respect architectural boundaries (e.g., no cross-dependencies without DI)

## ⚙️ Tooling & Platform Defaults

With the exception of typescript, all tooling suggested below is the **default** for the monorepo. You may override these defaults, but do so consistently with the architectural context.

- Language: TypeScript (`strict` mode)
- Package Manager: pnpm
- Monorepo: Nx
- Linting: ESLint (flat config via internal libraries)
- Backend: Express + tRPC
- ORM: Prisma (PostgreSQL preferred)
- Validation: Zod
- Default deployment targets: AWS ECS Fargate (server), CloudFront (client)

## 🔌 DI & Extensibility

- Core services (`SessionService`, `IdentityService`) receive dependencies via constructor injection.
207 changes: 207 additions & 0 deletions .ai/shared/epics/20250709_traditional-web-authentication.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
# Epic: Traditional Web-Based Authentication

## Overview

Implement a complete traditional web-based authentication system that enables users to securely sign up, sign in, and manage their accounts within the BoosterAuth monorepo ecosystem.

## Business Value

- **Developer Experience**: Provides a foundational authentication system that developers can easily integrate into their SaaS applications
- **Security First**: Implements industry-standard security practices following Lucia principles
- **Modularity**: Allows developers to pick and choose authentication components as needed
- **Time to Market**: Reduces development time for teams needing secure authentication
- **Compliance**: Meets security standards required for enterprise SaaS applications

## Success Criteria

- [ ] Users can successfully sign up with email and password
- [ ] Users can sign in with valid credentials
- [ ] Users can securely sign out and invalidate sessions
- [ ] Users can reset forgotten passwords via email
- [ ] All authentication flows are secure and follow best practices
- [ ] System prevents enumeration attacks
- [ ] Password policies are configurable
- [ ] All packages are independently publishable and testable

## Architectural Considerations

### Package Structure

Following the monorepo philosophy, authentication functionality will be distributed across multiple packages in `libs/`:

- **Core Interfaces** (`@booster-auth/core`): Abstract interfaces and types only
- **Session Management** (`@booster-auth/session`): Session creation, validation, and lifecycle
- **Identity Management** (`@booster-auth/identity`): User identity and credential management
- **Password Management** (`@booster-auth/password-authentication`): Password hashing, validation, and reset
- **Email Services** (`@booster-auth/email`): Email provider abstraction and templates

### Security Principles

- **No Opaque Abstractions**: Clear, explicit session control
- **Secure Defaults**: bcrypt password hashing, secure session storage
- **Configurable Security**: Customizable password policies and session timeouts
- **Protection Against Attacks**: Enumeration attack prevention, token expiration

### Dependency Injection

- Core services (`SessionService`, `IdentityService`, `PasswordService`) receive dependencies via constructor injection
- No tight coupling to Prisma in core logic
- Pluggable strategies for different authentication methods

### Testing Strategy

- TDD-first approach: tests generated before implementations
- Unit tests in `__tests__` subdirectories with `*.test.ts` suffix
- Each library independently testable
- Comprehensive coverage of security scenarios

## Technical Requirements

### Data Layer

- **User Accounts**: User accounts with email, hashed passwords, metadata
- **Session Storage**: Secure session tokens with expiration
- **Password Reset Tokens**: Temporary, single-use tokens with TTL
- **Audit Logging**: Authentication events for security monitoring

### API Contracts

- **Zod Schema Validation**: All inputs validated with Zod schemas
- **TypeScript Strict Mode**: Full type safety across all packages
- **Error Handling**: Consistent error responses that don't leak information
- **Rate Limiting**: Protection against brute force attacks

### Integration Points

- **Email Provider Abstraction**: Support for SMTP, SendGrid, Postmark
- **Database Abstraction**: Prisma integration without tight coupling - consider how drizzle can similarly be used
- **Middleware Integration**: Express middleware for session validation

## User Flows Covered

### 1. User Sign Up

- Email and password validation
- Password hashing and secure storage
- Account creation with proper error handling
- Welcome email (optional)

### 2. User Sign In

- Credential validation without enumeration
- Session creation and token generation
- Secure session storage
- Failed attempt handling

### 3. User Sign Out

- Session invalidation
- Token cleanup
- Secure logout confirmation

### 4. Password Reset Flow

- Reset request with email validation
- Secure token generation and email delivery
- Password reset with token validation
- Token invalidation after use
- Confirmation email after reset

## Non-Functional Requirements

### Performance

- Session validation in < 100ms
- Password hashing optimized for security vs. performance
- Efficient token lookup and validation

### Security

- Passwords hashed with bcrypt (configurable rounds)
- Session tokens cryptographically secure
- Protection against timing attacks
- Secure token expiration and cleanup

### Scalability

- Stateless session validation
- Horizontal scaling support
- Database connection pooling
- Rate limiting and abuse protection

## Dependencies and Constraints

### Technology Stack

- **Language**: TypeScript (strict mode)
- **Validation**: Zod schemas
- **Hashing**: bcrypt (configurable)
- **Database**: Prisma (PostgreSQL preferred)
- **Testing**: Jest with comprehensive coverage

### External Dependencies

- Email service providers (SMTP, SendGrid, Postmark)
- Database for persistent storage
- Redis for session storage (optional)
- Rate limiting service (optional)

## Risks and Mitigation

### Security Risks

- **Risk**: Password brute force attacks
- **Mitigation**: Rate limiting, account lockout, secure password policies

- **Risk**: Session hijacking
- **Mitigation**: Secure token generation, HTTPS only, proper expiration

- **Risk**: Enumeration attacks
- **Mitigation**: Consistent response times, generic error messages

### Technical Risks

- **Risk**: Package dependency complexity
- **Mitigation**: Clear interfaces, dependency injection, independent testing

- **Risk**: Performance bottlenecks
- **Mitigation**: Efficient algorithms, caching, performance monitoring

## Acceptance Criteria

### Functional

- All user flows work end-to-end
- Security measures prevent common attacks
- Error handling provides appropriate feedback
- Email delivery is reliable and configurable

### Technical

- All packages pass independent tests
- Code coverage > 90%
- Performance benchmarks met
- Security audit passes
- Documentation complete

### Architectural

- Dependency injection properly implemented
- No cross-package dependencies without DI
- Interfaces clearly defined in core packages
- Modular design allows independent usage

## Definition of Done

- [ ] All user stories completed and tested
- [ ] Security review passed
- [ ] Performance benchmarks met
- [ ] Documentation updated
- [ ] Examples in `apps/` directory functional
- [ ] All packages independently publishable
- [ ] CI/CD pipeline passing
- [ ] Ready for beta testing with real applications

---

*This epic will be decomposed into specific user stories covering each authentication flow, package implementation, and integration requirement.*
75 changes: 75 additions & 0 deletions .ai/shared/library-prd.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# Booster Auth Library

This monorepo contains a suite of npm packages focused solely on implementing modular, secure, and extensible authentication systems for SaaS applications.

## Key Features

- **Modular Design**: Each package is independently publishable and can be used in isolation or together.
- **Security First**: Follows best practices for secure authentication, including session management and password hashing.
- **Extensible**: Easily add new authentication methods or providers through pluggable strategies.
- **Embrace Open Standards**: Supports OAuth, OIDC, SAML, and other common authentication protocols.
- **AI-First Development**: Utilizes AI agents for code generation, testing, PR review, and refactoring.
- **TDD Approach**: Tests are generated before implementations, ensuring high code quality and reliability.
- **TypeScript**: Built with TypeScript for type safety and developer experience.

## Development Philosophy

- **Convention over Configuration**: Provides sensible defaults while allowing customization.
- **Semantic Versioning**: Follows semantic versioning for all packages to ensure compatibility and stability.
- **Test-Driven Development**: All features are developed with tests first, ensuring reliability and maintainability.
- **AI-Assisted Development**: Leverages AI tools for code generation, testing, and refactoring to enhance productivity and code quality.
- **Security as a Priority**: Implements security best practices from the ground up, ensuring that authentication systems are robust and secure.
- **Extensible Architecture**: Designed to be easily extended with new authentication methods, providers, and features.
- **Modular Packages**: Each package serves a specific purpose, allowing developers to pick and choose components as needed.
- **Documentation-Driven**: Comprehensive documentation is provided for each package, including usage examples and API references.

## Architectural Decision Records

Each architectural decision is documented in the `apps/docs/adr` directory. These records provide context and rationale for design choices, helping maintain clarity and consistency as the project evolves.

## Glossary

Login, logout, and registration are not acceptable terms in this project. Instead, we use the following terminology:

- **Sign In**: The process of authenticating a user with their credentials.
- **Sign Out**: The process of terminating a user's session, effectively logging them out.
- **Sign Up**: The process of creating a new user account, typically involving registration with an email and password.
- **Session**: A temporary state that maintains user authentication status, allowing access to protected resources.
- **Session Timeout**: The duration after which a session expires, requiring the user to sign in again.
- **Identity** - A representation of a user within the authentication system, including their credentials and associated metadata. An identity correlates an individual user with their authentication credentials, such as email and password, or OAuth tokens. A user can have multiple identities (e.g., one for email/password and another for OAuth).

## Ongoing Documentation

Documentation is continuously updated to reflect the latest architectural decisions, package features, and development practices. Key documentation files will be maintained in a docsify library in `apps/docs`. Docsify maintains a set of markdown files that are rendered as a static site, allowing for easy navigation and searchability.

## Initial Functionality

### Web-Based Authentication

#### Traditional Registration

An unauthenticated user can register by providing a valid, unique email address, password, and password. The system will validate the input, hash the password, and store the user in the database.

Passwords should not be stored in plaintext. Instead, they should be hashed using a secure hashing algorithm (e.g., bcrypt) before being stored in the database.

Passwords requirements should be configurable, allowing for flexibility in password policies (e.g., minimum length, complexity requirements).

### Traditional Sign In

An unauthenticated user can sign in by providing a valid email address and password. The system will validate the credentials, check the password against the stored hash, and create a session if successful. The system should not reveal whether the email address exists in the system to prevent enumeration attacks. It should simply indicate whether the sign-in was successful or not.

### Forgot Password

An authenticated user can request a password reset by providing their email address. The system will generate a secure, perishable token, send it to the user's email, and allow them to reset their password using that token. The token should have an expiration time to prevent misuse.

Tokens cannot be reused. Once a password is reset using a token, the token should be invalidated to prevent further use. There should also be a configurable TTL (time-to-live) for the token, after which it will expire and no longer be valid.

Different email providers should be considered. Basic SMTP support is required, but more advanced providers (e.g., SendGrid, Mailgun) may be added later.

### Password Reset Email Confirmation

Upon resetting their password, the user should receive a confirmation email indicating that their password has been successfully changed. This email should not contain the new password but simply confirm the change and offer an opportunity to take action if the user did not initiate the change.

### Sign Out

An authenticated user can sign out by terminating their session. The system should invalidate the user's session token, preventing further access to protected resources until the user signs in again. Systemically, the user should be forgotten until they sign in again, at which point a new session is created.
Loading