refactor(auth): factory-style use cases + controllers + real Payload impls

- Use cases (sign-in, sign-up, sign-out) → factory functions with I*UseCase aliases
- Controllers → factory functions with I*Controller aliases
- DI symbols + module updated with .toDynamicValue() bindings for factories
- New: real UsersRepository (Payload-backed, SanitizedConfig, contract-tested)
- New: real AuthenticationService (node:crypto hashing/UUIDs; createSession/
  validateSession/invalidateSession deferred — see refactor log §7)
- bindProductionAuth swaps both mocks for real impls (was a no-op before)
- Tests refactored to construct mocks and inject directly (no container rebinding)
- Feature test constructs full chain via direct factory injection

Refactor log: §2, §4.1, §4.2, §5.1, §5.2, §6.1, §7
Spec: §6.1, §7

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-06 00:01:11 +02:00
parent aa325f91cc
commit 780d5cb83b
24 changed files with 694 additions and 349 deletions

View File

@@ -87,6 +87,13 @@ Entity model moves (git mv — history preserved):
## 2. Files added (with purpose)
### Task 4: Real implementations + tests
- `packages/auth/src/infrastructure/repositories/users.repository.ts` — real Payload-backed `UsersRepository` (implements `IUsersRepository` via `getPayload`)
- `packages/auth/src/infrastructure/repositories/users.repository.test.ts` — contract suite backed by an in-memory Payload stub (mirrors `articles.repository.test.ts` pattern)
- `packages/auth/src/infrastructure/services/authentication.service.ts` — real `AuthenticationService` using `node:crypto` for hashing/UUIDs; session methods deferred (see §7)
- `packages/auth/src/infrastructure/services/authentication.service.test.ts` — tests for `generateUserId`, `hashPassword`/`verifyPassword` round-trip, and deferred-method error assertions
### Task 2: Entities split — new error files
- `packages/auth/src/entities/errors/auth.ts` — AuthenticationError, UnauthenticatedError, UnauthorizedError (split from errors.ts)
@@ -110,10 +117,22 @@ Entity model moves (git mv — history preserved):
## 4. Pattern changes (code-level)
### 4.1 Use cases — factory function pattern
(populated when a use case is migrated)
Applied to all 3 auth use cases (`sign-in`, `sign-up`, `sign-out`):
- Use cases are now factory functions: `(deps) => async (input) => result`
- Each file exports `export type I*UseCase = ReturnType<typeof *UseCase>` for DI typing
- Use cases NO LONGER call `authContainer.get()` inside their bodies — all dependencies are passed as factory arguments
- Tests construct mocks directly: `const useCase = signInUseCase(mockUsers, mockAuth); await useCase(input);`
### 4.2 Controllers — one per use case
(populated when controllers are split)
Applied to all 3 auth controllers (`sign-in`, `sign-up`, `sign-out`):
- Controllers were already split (one file per use case) — Task 4 refactors them to factory functions
- Factory pattern: `(useCase: I*UseCase) => async (input) => result`
- Each exports `export type I*Controller = ReturnType<typeof *Controller>`
- Validation (Zod `safeParse`) stays inside the controller factory; throws `InputParseError` on failure
### 4.3 Entities split — models/ + errors/ subdirs
@@ -129,19 +148,56 @@ Pattern now in place across auth, blog, marketing-pages, navigation (media skipp
## 5. DI changes
### 5.1 Inversify `.toDynamicValue` bindings
(populated when DI modules are updated)
Applied to `packages/auth/src/di/module.ts`:
- `AUTH_SYMBOLS` expanded with 6 new keys: `ISignInUseCase`, `ISignUpUseCase`, `ISignOutUseCase`, `ISignInController`, `ISignUpController`, `ISignOutController`
- Use cases bound with `.toDynamicValue((ctx) => factoryFn(ctx.container.get(...)))` — dependencies resolved from the container at call time
- Controllers bound identically, taking the corresponding use case symbol from the container
- Repository and service bindings remain `.to(Mock*)` as the default
### 5.2 Mock siblings registered as default bindings
(populated when modules are updated)
- `MockUsersRepository` and `MockAuthenticationService` remain the default bindings in `AuthModule`
- `bindProductionAuth(config: SanitizedConfig)` now swaps both to `UsersRepository` and `AuthenticationService` (real Payload-backed implementations)
- Previously `bindProductionAuth` was a no-op; it now rebinds both symbols using `.toConstantValue(new RealImpl(config))`
## 6. Test refactor patterns
### 6.1 Direct injection (no container rebinding)
(populated when tests are migrated)
Applied to all auth use-case tests, controller tests, the router test, and the feature integration test:
- **Before:** `beforeEach` unbinds and rebinds symbols on `authContainer`
- **After:** each test (or `it`) constructs its own `MockUsersRepository` + `MockAuthenticationService`, then calls the factory directly:
```typescript
const users = new MockUsersRepository([]);
const auth = new MockAuthenticationService(users);
const useCase = signInUseCase(users, auth);
const result = await useCase({ username: "alice", password: "testpassword" });
```
- No `authContainer.unbind()` / `authContainer.bind()` calls remain in test files
- The `authRouter` test and `container.test.ts` still reference `authContainer` (unavoidable — the router resolves controllers via the container, and the container test verifies the DI wiring), but they use the default bindings without rebinding
- The feature test (`tests/sign-in-flow.feature.test.ts`) fully constructs the chain via direct injection rather than calling `authRouter.createCaller({})`
## 7. Open issues / deferred decisions
(populated as encountered)
### Task 4: AuthenticationService — deferred session methods
Three methods on `AuthenticationService` (in `packages/auth/src/infrastructure/services/authentication.service.ts`) are deferred because Payload's auth API does not map cleanly to the generic `IAuthenticationService` session interface:
| Method | Why deferred |
|---|---|
| `createSession(user)` | Payload creates sessions via its REST `/api/users/login` endpoint and returns a JWT token. Mapping this to a generic `{ session: Session; cookie: Cookie }` shape requires knowing Payload's JWT payload structure, the session expiry, and the exact cookie name/attributes Payload uses — which vary by collection config. |
| `validateSession(sessionId)` | Payload validates sessions by verifying a JWT. This requires calling `payload.auth()` or `payload.find()` with the token, and is tightly coupled to Payload's internal token format. |
| `invalidateSession(sessionId)` | Payload's default auth strategy is stateless JWT — there is no server-side session store to clear. Invalidation is done client-side by expiring the cookie. A proper implementation would require either a token blocklist or switching to Payload's API keys feature. |
All three throw `new NotImplementedError("methodName")` with a clear message (`"NotImplemented: AuthenticationService.<method> — see refactor log §7"`). The mock (`MockAuthenticationService`) handles all test paths.
**TODO:** Revisit once the session cookie strategy is finalized. Consider:
- Using Payload's local API `payload.auth()` for `validateSession`
- Implementing a Redis-backed token blocklist for `invalidateSession`
- Or replacing the `IAuthenticationService` interface with Payload-specific abstractions
---