Skip to content

Commit 42fa85e

Browse files
committed
DEV-1264: Optimization and more flexible configuration of Better-Auth
1 parent 07f32c7 commit 42fa85e

17 files changed

+1746
-643
lines changed

CLAUDE.md

Lines changed: 219 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,114 @@
22

33
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
44

5+
## Self-Improvement Instructions
6+
7+
**Claude Code must actively maintain and improve this file.**
8+
9+
After significant development sessions where new fundamental insights were gained together with the developer, Claude Code should:
10+
11+
1. **Update this file** with new learnings that are valuable for future development sessions (patterns, pitfalls, best practices discovered during implementation)
12+
13+
2. **Validate against best practices** - Check if this CLAUDE.md still follows Claude Code best practices and can be optimally utilized for development
14+
15+
3. **Optimize automatically** - Restructure, clarify, or extend sections as needed to maximize effectiveness
16+
17+
**Goal:** This CLAUDE.md should always be current and optimally structured so that Claude Code is perfectly briefed to extend and improve this project in the best possible way.
18+
19+
**When to update:**
20+
- New architectural patterns established
21+
- Important edge cases or pitfalls discovered
22+
- New integrations added that require specific handling
23+
- Development workflows improved
24+
- Common mistakes identified that should be avoided
25+
26+
## Project Overview
27+
28+
### What is this?
29+
This is **@lenne.tech/nest-server** - an extension/layer on top of [NestJS](https://docs.nestjs.com/) that provides additional functionality for building server applications with GraphQL and MongoDB.
30+
31+
- **NPM Package**: https://www.npmjs.com/package/@lenne.tech/nest-server
32+
- **GitHub Repository**: https://github.com/lenneTech/nest-server
33+
- **NestJS Framework**: https://github.com/nestjs/nest
34+
35+
### Ecosystem
36+
37+
This package is part of the lenne.Tech ecosystem:
38+
39+
1. **@lenne.tech/nest-server** (this repository)
40+
- Core extension package providing reusable components
41+
- Extended through `src/core/common` (decorators, helpers, services)
42+
- Extended through `src/core/modules` (auth, file, user modules)
43+
44+
2. **nest-server-starter** (https://github.com/lenneTech/nest-server-starter)
45+
- Template project for new applications
46+
- Has @lenne.tech/nest-server as dependency
47+
- **Reference project**: Each new version is integrated and tested here
48+
- **Migration documentation**: Commits document required changes for each version upgrade
49+
50+
3. **lt CLI** (https://github.com/lenneTech/cli)
51+
- Command-line tool for project initialization and extension
52+
- Server commands: https://github.com/lenneTech/cli/tree/main/src/commands/server
53+
- Use `lt server module <ModuleName>` to generate new modules
54+
55+
## Important Development Guidelines
56+
57+
### Design Principles
58+
59+
**Dynamic Integration & Flexible Configuration**
60+
61+
All new components (third-party package integrations, elements in `src/core/common`, and modules in `src/core/modules`) must be designed with maximum flexibility:
62+
63+
1. **Dynamic Integrability**: Components should be opt-in and configurable at runtime or during module initialization. Avoid hardcoded dependencies that force all consumers to use specific features.
64+
65+
2. **Flexible Configuration**: Provide comprehensive configuration options so consuming projects can customize behavior without modifying this package. Use:
66+
- Configuration interfaces with sensible defaults
67+
- Factory methods for custom implementations
68+
- Conditional feature activation via config flags
69+
- Dependency injection for swappable implementations
70+
71+
3. **No Package Modification Required**: The goal is that projects using @lenne.tech/nest-server can fully leverage all features, customized to their specific needs, without ever needing to fork or modify this package.
72+
73+
**Example Pattern:**
74+
```typescript
75+
// Good: Configurable module with options
76+
CoreModule.forRoot({
77+
graphQl: { playground: true, introspection: true },
78+
email: { provider: 'smtp', config: { ... } },
79+
customFeature: { enabled: false } // Opt-in
80+
})
81+
82+
// Bad: Hardcoded behavior that can't be customized
83+
```
84+
85+
### When Modifying This Package
86+
87+
1. **Backward Compatibility**: Changes affect all projects using this package. Consider breaking changes carefully.
88+
89+
2. **Version Documentation**: After significant changes, the corresponding update must be applied and documented in the [nest-server-starter](https://github.com/lenneTech/nest-server-starter) repository.
90+
91+
3. **Test Coverage**: All changes must pass E2E tests (`npm test`). Production-ready code requires all tests to pass without errors.
92+
93+
4. **Export Management**: New public components must be exported via `src/index.ts` to be available to consuming projects.
94+
95+
### Code Organization
96+
97+
- `src/core/` - **Reusable framework components** (exported to consumers)
98+
- `src/core/common/` - Decorators, helpers, interceptors, pipes, scalars, services
99+
- `src/core/modules/` - Auth, File, User, HealthCheck modules
100+
- `src/server/` - **Internal test/demo implementation** (not exported)
101+
- `src/index.ts` - **Public API exports**
102+
103+
### Adding New Features
104+
105+
When adding new functionality:
106+
107+
1. **Determine location**: Core components go in `src/core/`, test implementations in `src/server/`
108+
2. **Follow existing patterns**: Check similar existing implementations for consistency
109+
3. **Update exports**: Add public APIs to `src/index.ts`
110+
4. **Add tests**: Create or extend E2E tests in `tests/`
111+
5. **Document changes**: Update relevant documentation if needed
112+
5113
## Common Development Commands
6114

7115
### Building and Running
@@ -27,8 +135,9 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
27135
- `npm run docs` - Generate and serve API documentation (SpectaQL + Compodoc)
28136
- `npm run docs:ci` - Generate documentation for CI
29137

30-
### Development Utilities
31-
- `npm run build:dev` - Build and push to yalc for local package development
138+
### Package Development
139+
- `npm run build:dev` - Build and push to yalc for local package testing
140+
- `npm run build:pack` - Create tarball for integration testing
32141
- `npm run reinit` - Clean reinstall with tests and build
33142
- `npm run watch` - Watch for changes using npm-watch
34143

@@ -38,7 +147,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
38147
This is a **NestJS-based server** with **GraphQL API** and **MongoDB** integration using Mongoose. The codebase is organized into two main layers:
39148

40149
1. **Core Layer** (`src/core/`) - Reusable framework components
41-
2. **Server Layer** (`src/server/`) - Project-specific implementations
150+
2. **Server Layer** (`src/server/`) - Project-specific implementations (for testing)
42151

43152
### Key Architectural Components
44153

@@ -96,17 +205,16 @@ lt server module <ModuleName>
96205

97206
#### Security Implementation
98207
- `@Restricted()` decorator for field-level access control
99-
- `@Roles()` decorator for method-level authorization
208+
- `@Roles()` decorator for method-level authorization
100209
- Response interceptor automatically filters restricted fields
101210
- Security interceptor processes `securityCheck()` methods
102211

103212
## Testing Configuration
104213

105214
### E2E Tests
106-
- Primary testing approach using Jest
107-
- Configuration in `jest-e2e.json`
215+
- Primary testing approach using Vitest (migrated from Jest)
216+
- Configuration in `vitest.config.ts`
108217
- Test files in `tests/` directory with `.e2e-spec.ts` suffix
109-
- 20-second timeout for database operations
110218
- Run with `NODE_ENV=local` environment
111219

112220
### Test Environment Setup
@@ -120,10 +228,35 @@ This package serves dual purposes:
120228
1. **NPM Package**: Distributed as `@lenne.tech/nest-server` for integration
121229
2. **Direct Usage**: Can be cloned and extended as a project template
122230

123-
### Package Development
124-
- `npm run build:dev` - Build and publish to yalc for local testing
125-
- `npm run build:pack` - Create tarball for integration testing
126-
- Main entry: `dist/index.js`, Types: `dist/index.d.ts`
231+
### Versioning Strategy
232+
233+
The version number follows a specific schema: `MAJOR.MINOR.PATCH`
234+
235+
| Part | Meaning |
236+
|---------|--------------------------------------------------------------------|
237+
| `MAJOR` | Mirrors the NestJS major version (e.g., `11.x.x` = NestJS 11) |
238+
| `MINOR` | Breaking changes or significant restructuring |
239+
| `PATCH` | Improvements (bugfixes) or additions (new features) - non-breaking |
240+
241+
**Examples:**
242+
- `11.0.0` → Initial release for NestJS 11
243+
- `11.1.0` → Breaking change or major restructuring within NestJS 11
244+
- `11.1.5` → Bugfix or new feature (backward compatible)
245+
246+
**Important:** When incrementing the minor version, always document the breaking changes clearly in the commit message and ensure the nest-server-starter is updated with migration instructions.
247+
248+
### Release Process
249+
1. Make changes and ensure all tests pass
250+
2. Update version in `package.json`
251+
3. Build the package (`npm run build`)
252+
4. Publish to npm
253+
5. Update and test in nest-server-starter
254+
6. Commit changes to starter with migration notes
255+
256+
### Package Exports
257+
- Main entry: `dist/index.js`
258+
- Types: `dist/index.d.ts`
259+
- All public APIs exported from `src/index.ts`
127260

128261
## Environment Configuration
129262

@@ -142,4 +275,78 @@ This package serves dual purposes:
142275
### Email Configuration
143276
- Supports both SMTP and Mailjet providers
144277
- Template rendering with EJS
145-
- Development uses Ethereal Email / MailHog for testing
278+
- Development uses Ethereal Email / MailHog for testing
279+
280+
## Debugging & Troubleshooting
281+
282+
### Common Issues
283+
284+
**E2E Tests Timeout or Fail**
285+
- Ensure MongoDB is running on `localhost:27017`
286+
- Verify `NODE_ENV=local` is set
287+
- Use `npm run test:e2e-doh` for open handle detection
288+
- Check test timeout settings in `vitest.config.ts`
289+
290+
**GraphQL Introspection Not Working**
291+
- Verify introspection is enabled in `config.env.ts` for non-production
292+
- Check Apollo Server configuration in CoreModule
293+
294+
**Database Connection Failures**
295+
- Verify MongoDB connection string in environment config
296+
- Check `mongoose.set('strictQuery', false)` setting
297+
- Ensure MongoDB service is running
298+
299+
**Module/Service Not Found After Adding**
300+
- Verify export in `src/index.ts`
301+
- Check module is properly imported in CoreModule or target module
302+
- Run `npm run build` to regenerate dist files
303+
304+
**Validation Errors Not Showing**
305+
- Ensure `MapAndValidatePipe` is applied
306+
- Check class-validator decorators on input classes
307+
- Verify DTO extends correct base class
308+
309+
## Role System (RoleEnum)
310+
311+
The role system distinguishes between **real roles** and **system roles**:
312+
313+
### Real Roles
314+
Actual roles stored in `user.roles` array in the database:
315+
- `RoleEnum.ADMIN` - Administrator role
316+
317+
### System Roles (S_ Prefix)
318+
System roles are used for **runtime checks only** and must **NEVER** be stored in `user.roles`:
319+
320+
| Role | Purpose | Check Logic |
321+
|------|---------|-------------|
322+
| `S_USER` | User is logged in | `currentUser` exists |
323+
| `S_VERIFIED` | User is verified | `user.verified \|\| user.verifiedAt \|\| user.emailVerified` |
324+
| `S_CREATOR` | User created the object | `object.createdBy === user.id` |
325+
| `S_SELF` | User is accessing own data | `object.id === user.id` |
326+
| `S_EVERYONE` | Public access | Always true |
327+
| `S_NO_ONE` | Locked access | Always false |
328+
329+
### Critical Rule
330+
```typescript
331+
// CORRECT: Using S_ roles in decorators (runtime checks)
332+
@Roles(RoleEnum.S_USER)
333+
@Restricted(RoleEnum.S_VERIFIED)
334+
335+
// WRONG: Storing S_ roles in user.roles array
336+
roles: [RoleEnum.S_USER] // ❌ NEVER do this!
337+
338+
// CORRECT: Empty roles or real roles only
339+
roles: [] // ✓ Empty array
340+
roles: [RoleEnum.ADMIN] // ✓ Real role
341+
```
342+
343+
The `S_` prefix indicates a **system check**, not an actual role. These are evaluated dynamically at runtime based on context (current user, request, object being accessed).
344+
345+
## Best Practices for This Repository
346+
347+
1. **All code, comments, and documentation must be in English**
348+
2. **Run tests before considering any change complete** - `npm test`
349+
3. **Follow existing code patterns** for consistency across the codebase
350+
4. **Consider downstream impact** - this package is used by multiple projects
351+
5. **Document breaking changes** clearly for version updates
352+
6. **Never store S_ roles in user.roles** - they are system checks, not actual roles

0 commit comments

Comments
 (0)