From 780d5cb83b007306a09b525ae81605000de66ba4 Mon Sep 17 00:00:00 2001 From: Danijel Martinek Date: Wed, 6 May 2026 00:01:11 +0200 Subject: [PATCH] refactor(auth): factory-style use cases + controllers + real Payload impls MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- .../2026-05-05-lazar-pattern-conformance.md | 68 ++++++++++++-- .../use-cases/sign-in.use-case.test.ts | 57 ++++++------ .../application/use-cases/sign-in.use-case.ts | 48 +++++----- .../use-cases/sign-out.use-case.test.ts | 34 ++----- .../use-cases/sign-out.use-case.ts | 17 ++-- .../use-cases/sign-up.use-case.test.ts | 43 +++------ .../application/use-cases/sign-up.use-case.ts | 64 +++++++------ packages/auth/src/di/bind-production.ts | 37 +++++--- packages/auth/src/di/container.test.ts | 14 ++- packages/auth/src/di/module.ts | 62 +++++++++++++ packages/auth/src/di/symbols.ts | 8 ++ .../repositories/users.repository.test.ts | 62 +++++++++++++ .../repositories/users.repository.ts | 51 ++++++++++ .../services/authentication.service.test.ts | 61 ++++++++++++ .../services/authentication.service.ts | 93 +++++++++++++++++++ .../auth/src/integrations/api/router.test.ts | 29 +----- packages/auth/src/integrations/api/router.ts | 23 +++-- .../controllers/sign-in.controller.test.ts | 56 ++++++----- .../controllers/sign-in.controller.ts | 24 ++--- .../controllers/sign-out.controller.test.ts | 42 +++------ .../controllers/sign-out.controller.ts | 22 +++-- .../controllers/sign-up.controller.test.ts | 57 ++++++------ .../controllers/sign-up.controller.ts | 24 +++-- .../auth/tests/sign-in-flow.feature.test.ts | 47 ++++------ 24 files changed, 694 insertions(+), 349 deletions(-) create mode 100644 packages/auth/src/infrastructure/repositories/users.repository.test.ts create mode 100644 packages/auth/src/infrastructure/repositories/users.repository.ts create mode 100644 packages/auth/src/infrastructure/services/authentication.service.test.ts create mode 100644 packages/auth/src/infrastructure/services/authentication.service.ts diff --git a/docs/superpowers/refactor-logs/2026-05-05-lazar-pattern-conformance.md b/docs/superpowers/refactor-logs/2026-05-05-lazar-pattern-conformance.md index fb031cb..adf8329 100644 --- a/docs/superpowers/refactor-logs/2026-05-05-lazar-pattern-conformance.md +++ b/docs/superpowers/refactor-logs/2026-05-05-lazar-pattern-conformance.md @@ -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` 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` +- 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. — 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 --- diff --git a/packages/auth/src/application/use-cases/sign-in.use-case.test.ts b/packages/auth/src/application/use-cases/sign-in.use-case.test.ts index 1514032..2779c9f 100644 --- a/packages/auth/src/application/use-cases/sign-in.use-case.test.ts +++ b/packages/auth/src/application/use-cases/sign-in.use-case.test.ts @@ -1,52 +1,47 @@ -import { beforeEach, describe, expect, it } from "vitest"; -import { authContainer } from "@/di/container"; -import { AUTH_SYMBOLS } from "@/di/symbols"; +import { describe, it, expect } from "vitest"; +import { signInUseCase } from "@/application/use-cases/sign-in.use-case"; import { MockUsersRepository } from "@/infrastructure/repositories/users.repository.mock"; import { MockAuthenticationService } from "@/infrastructure/services/authentication.service.mock"; -import type { IUsersRepository } from "@/application/repositories/users.repository.interface"; -import type { IAuthenticationService } from "@/application/services/authentication.service.interface"; import { AuthenticationError } from "@/entities/errors/auth"; -import { signInUseCase } from "./sign-in.use-case"; +import { userFactory } from "@/__factories__/user.factory"; describe("signInUseCase", () => { - let usersRepo: MockUsersRepository; - let authService: MockAuthenticationService; - - beforeEach(() => { - if (authContainer.isBound(AUTH_SYMBOLS.IUsersRepository)) { - authContainer.unbind(AUTH_SYMBOLS.IUsersRepository); - } - if (authContainer.isBound(AUTH_SYMBOLS.IAuthenticationService)) { - authContainer.unbind(AUTH_SYMBOLS.IAuthenticationService); - } - usersRepo = new MockUsersRepository(); - authService = new MockAuthenticationService(usersRepo); - authContainer - .bind(AUTH_SYMBOLS.IUsersRepository) - .toConstantValue(usersRepo); - authContainer - .bind(AUTH_SYMBOLS.IAuthenticationService) - .toConstantValue(authService); - }); - it("returns a session + cookie on valid credentials", async () => { - const result = await signInUseCase({ + const users = new MockUsersRepository([]); + const auth = new MockAuthenticationService(users); + const seedUser = userFactory.build({ username: "alice", - password: "password_alice", + passwordHash: "hashed_testpassword", }); - expect(result.session.userId).toBe("1"); + await users.createUser(seedUser); + + const useCase = signInUseCase(users, auth); + const result = await useCase({ username: "alice", password: "testpassword" }); + + expect(result.session.userId).toBe(seedUser.id); expect(result.cookie.name).toBe("session"); }); it("throws AuthenticationError when user does not exist", async () => { + const users = new MockUsersRepository([]); + const auth = new MockAuthenticationService(users); + const useCase = signInUseCase(users, auth); + await expect( - signInUseCase({ username: "ghost", password: "anything" }), + useCase({ username: "ghost", password: "anything" }), ).rejects.toBeInstanceOf(AuthenticationError); }); it("throws AuthenticationError on wrong password", async () => { + const users = new MockUsersRepository([]); + const auth = new MockAuthenticationService(users); + await users.createUser( + userFactory.build({ username: "alice", passwordHash: "hashed_correctpassword" }), + ); + + const useCase = signInUseCase(users, auth); await expect( - signInUseCase({ username: "alice", password: "wrong" }), + useCase({ username: "alice", password: "wrong" }), ).rejects.toBeInstanceOf(AuthenticationError); }); }); diff --git a/packages/auth/src/application/use-cases/sign-in.use-case.ts b/packages/auth/src/application/use-cases/sign-in.use-case.ts index 38f5738..d483085 100644 --- a/packages/auth/src/application/use-cases/sign-in.use-case.ts +++ b/packages/auth/src/application/use-cases/sign-in.use-case.ts @@ -1,34 +1,32 @@ import { AuthenticationError } from "../../entities/errors/auth"; import type { Cookie } from "../../entities/models/cookie"; import type { Session } from "../../entities/models/session"; -import { authContainer } from "../../di/container"; -import { AUTH_SYMBOLS } from "../../di/symbols"; import type { IUsersRepository } from "../repositories/users.repository.interface"; import type { IAuthenticationService } from "../services/authentication.service.interface"; -export async function signInUseCase(input: { - username: string; - password: string; -}): Promise<{ session: Session; cookie: Cookie }> { - const usersRepository = authContainer.get( - AUTH_SYMBOLS.IUsersRepository, - ); - const authService = authContainer.get( - AUTH_SYMBOLS.IAuthenticationService, - ); +export type ISignInUseCase = ReturnType; - const existingUser = await usersRepository.getUserByUsername(input.username); - if (!existingUser) { - throw new AuthenticationError("User does not exist"); - } +export const signInUseCase = + ( + usersRepository: IUsersRepository, + authenticationService: IAuthenticationService, + ) => + async (input: { + username: string; + password: string; + }): Promise<{ session: Session; cookie: Cookie }> => { + const existingUser = await usersRepository.getUserByUsername(input.username); + if (!existingUser) { + throw new AuthenticationError("User does not exist"); + } - const validPassword = await authService.verifyPassword( - existingUser.passwordHash, - input.password, - ); - if (!validPassword) { - throw new AuthenticationError("Incorrect username or password"); - } + const validPassword = await authenticationService.verifyPassword( + existingUser.passwordHash, + input.password, + ); + if (!validPassword) { + throw new AuthenticationError("Incorrect username or password"); + } - return await authService.createSession(existingUser); -} + return await authenticationService.createSession(existingUser); + }; diff --git a/packages/auth/src/application/use-cases/sign-out.use-case.test.ts b/packages/auth/src/application/use-cases/sign-out.use-case.test.ts index c5335e7..97d6737 100644 --- a/packages/auth/src/application/use-cases/sign-out.use-case.test.ts +++ b/packages/auth/src/application/use-cases/sign-out.use-case.test.ts @@ -1,35 +1,15 @@ -import { beforeEach, describe, expect, it } from "vitest"; -import { authContainer } from "@/di/container"; -import { AUTH_SYMBOLS } from "@/di/symbols"; +import { describe, it, expect } from "vitest"; +import { signOutUseCase } from "@/application/use-cases/sign-out.use-case"; import { MockUsersRepository } from "@/infrastructure/repositories/users.repository.mock"; import { MockAuthenticationService } from "@/infrastructure/services/authentication.service.mock"; -import type { IUsersRepository } from "@/application/repositories/users.repository.interface"; -import type { IAuthenticationService } from "@/application/services/authentication.service.interface"; -import { signOutUseCase } from "./sign-out.use-case"; describe("signOutUseCase", () => { - let usersRepo: MockUsersRepository; - let authService: MockAuthenticationService; - - beforeEach(() => { - if (authContainer.isBound(AUTH_SYMBOLS.IUsersRepository)) { - authContainer.unbind(AUTH_SYMBOLS.IUsersRepository); - } - if (authContainer.isBound(AUTH_SYMBOLS.IAuthenticationService)) { - authContainer.unbind(AUTH_SYMBOLS.IAuthenticationService); - } - usersRepo = new MockUsersRepository(); - authService = new MockAuthenticationService(usersRepo); - authContainer - .bind(AUTH_SYMBOLS.IUsersRepository) - .toConstantValue(usersRepo); - authContainer - .bind(AUTH_SYMBOLS.IAuthenticationService) - .toConstantValue(authService); - }); - it("returns a blank cookie", async () => { - const result = await signOutUseCase("session_1"); + const users = new MockUsersRepository([]); + const auth = new MockAuthenticationService(users); + const useCase = signOutUseCase(auth); + + const result = await useCase("session_1"); expect(result.blankCookie.name).toBe("session"); expect(result.blankCookie.value).toBe(""); }); diff --git a/packages/auth/src/application/use-cases/sign-out.use-case.ts b/packages/auth/src/application/use-cases/sign-out.use-case.ts index ae783ac..0a38dc6 100644 --- a/packages/auth/src/application/use-cases/sign-out.use-case.ts +++ b/packages/auth/src/application/use-cases/sign-out.use-case.ts @@ -1,13 +1,10 @@ import type { Cookie } from "../../entities/models/cookie"; -import { authContainer } from "../../di/container"; -import { AUTH_SYMBOLS } from "../../di/symbols"; import type { IAuthenticationService } from "../services/authentication.service.interface"; -export async function signOutUseCase( - sessionId: string, -): Promise<{ blankCookie: Cookie }> { - const authService = authContainer.get( - AUTH_SYMBOLS.IAuthenticationService, - ); - return await authService.invalidateSession(sessionId); -} +export type ISignOutUseCase = ReturnType; + +export const signOutUseCase = + (authenticationService: IAuthenticationService) => + async (sessionId: string): Promise<{ blankCookie: Cookie }> => { + return await authenticationService.invalidateSession(sessionId); + }; diff --git a/packages/auth/src/application/use-cases/sign-up.use-case.test.ts b/packages/auth/src/application/use-cases/sign-up.use-case.test.ts index c47efa2..ce127a9 100644 --- a/packages/auth/src/application/use-cases/sign-up.use-case.test.ts +++ b/packages/auth/src/application/use-cases/sign-up.use-case.test.ts @@ -1,47 +1,34 @@ -import { beforeEach, describe, expect, it } from "vitest"; -import { authContainer } from "@/di/container"; -import { AUTH_SYMBOLS } from "@/di/symbols"; +import { describe, it, expect } from "vitest"; +import { signUpUseCase } from "@/application/use-cases/sign-up.use-case"; import { MockUsersRepository } from "@/infrastructure/repositories/users.repository.mock"; import { MockAuthenticationService } from "@/infrastructure/services/authentication.service.mock"; -import type { IUsersRepository } from "@/application/repositories/users.repository.interface"; -import type { IAuthenticationService } from "@/application/services/authentication.service.interface"; import { AuthenticationError } from "@/entities/errors/auth"; -import { signUpUseCase } from "./sign-up.use-case"; +import { userFactory } from "@/__factories__/user.factory"; describe("signUpUseCase", () => { - let usersRepo: MockUsersRepository; - let authService: MockAuthenticationService; - - beforeEach(() => { - if (authContainer.isBound(AUTH_SYMBOLS.IUsersRepository)) { - authContainer.unbind(AUTH_SYMBOLS.IUsersRepository); - } - if (authContainer.isBound(AUTH_SYMBOLS.IAuthenticationService)) { - authContainer.unbind(AUTH_SYMBOLS.IAuthenticationService); - } - usersRepo = new MockUsersRepository(); - authService = new MockAuthenticationService(usersRepo); - authContainer - .bind(AUTH_SYMBOLS.IUsersRepository) - .toConstantValue(usersRepo); - authContainer - .bind(AUTH_SYMBOLS.IAuthenticationService) - .toConstantValue(authService); - }); - it("creates a new user and returns session + cookie + user", async () => { - const result = await signUpUseCase({ + const users = new MockUsersRepository([]); + const auth = new MockAuthenticationService(users); + const useCase = signUpUseCase(users, auth); + + const result = await useCase({ username: "carol", password: "secret_password", }); + expect(result.user.username).toBe("carol"); expect(result.session.userId).toBe(result.user.id); expect(result.cookie.name).toBe("session"); }); it("throws AuthenticationError when username taken", async () => { + const users = new MockUsersRepository([]); + const auth = new MockAuthenticationService(users); + await users.createUser(userFactory.build({ username: "alice" })); + + const useCase = signUpUseCase(users, auth); await expect( - signUpUseCase({ username: "alice", password: "secret_password" }), + useCase({ username: "alice", password: "secret_password" }), ).rejects.toBeInstanceOf(AuthenticationError); }); }); diff --git a/packages/auth/src/application/use-cases/sign-up.use-case.ts b/packages/auth/src/application/use-cases/sign-up.use-case.ts index 8130f11..a0ad42d 100644 --- a/packages/auth/src/application/use-cases/sign-up.use-case.ts +++ b/packages/auth/src/application/use-cases/sign-up.use-case.ts @@ -2,45 +2,43 @@ import { AuthenticationError } from "../../entities/errors/auth"; import type { Cookie } from "../../entities/models/cookie"; import type { Session } from "../../entities/models/session"; import type { User } from "../../entities/models/user"; -import { authContainer } from "../../di/container"; -import { AUTH_SYMBOLS } from "../../di/symbols"; import type { IUsersRepository } from "../repositories/users.repository.interface"; import type { IAuthenticationService } from "../services/authentication.service.interface"; -export async function signUpUseCase(input: { - username: string; - password: string; -}): Promise<{ - session: Session; - cookie: Cookie; - user: Pick; -}> { - const usersRepository = authContainer.get( - AUTH_SYMBOLS.IUsersRepository, - ); - const authService = authContainer.get( - AUTH_SYMBOLS.IAuthenticationService, - ); +export type ISignUpUseCase = ReturnType; - const existingUser = await usersRepository.getUserByUsername(input.username); - if (existingUser) { - throw new AuthenticationError("Username taken"); - } +export const signUpUseCase = + ( + usersRepository: IUsersRepository, + authenticationService: IAuthenticationService, + ) => + async (input: { + username: string; + password: string; + }): Promise<{ + session: Session; + cookie: Cookie; + user: Pick; + }> => { + const existingUser = await usersRepository.getUserByUsername(input.username); + if (existingUser) { + throw new AuthenticationError("Username taken"); + } - const passwordHash = await authService.hashPassword(input.password); - const userId = authService.generateUserId(); + const passwordHash = await authenticationService.hashPassword(input.password); + const userId = authenticationService.generateUserId(); - const newUser = await usersRepository.createUser({ - id: userId, - username: input.username, - passwordHash, - }); + const newUser = await usersRepository.createUser({ + id: userId, + username: input.username, + passwordHash, + }); - const { cookie, session } = await authService.createSession(newUser); + const { cookie, session } = await authenticationService.createSession(newUser); - return { - cookie, - session, - user: { id: newUser.id, username: newUser.username }, + return { + cookie, + session, + user: { id: newUser.id, username: newUser.username }, + }; }; -} diff --git a/packages/auth/src/di/bind-production.ts b/packages/auth/src/di/bind-production.ts index 7ee8eb1..0c2de46 100644 --- a/packages/auth/src/di/bind-production.ts +++ b/packages/auth/src/di/bind-production.ts @@ -1,13 +1,28 @@ -import type { SanitizedConfig as _SanitizedConfig } from "payload"; +import type { SanitizedConfig } from "payload"; +import { authContainer } from "./container"; +import { AUTH_SYMBOLS } from "./symbols"; +import { UsersRepository } from "../infrastructure/repositories/users.repository"; +import { AuthenticationService } from "../infrastructure/services/authentication.service"; +import type { IUsersRepository } from "../application/repositories/users.repository.interface"; +import type { IAuthenticationService } from "../application/services/authentication.service.interface"; -// Auth currently uses Mock repositories even in production: see Plan 3 -// decisions. This helper exists for API symmetry with other features and -// for forward-compatibility if a Payload-backed users repo is added later. -// -// Until then it's a no-op that intentionally accepts (and ignores) the -// SanitizedConfig argument so app-boot code can call it uniformly. -// eslint-disable-next-line @typescript-eslint/no-unused-vars -export function bindProductionAuth(_config: _SanitizedConfig): void { - // Default mock bindings from `module.ts` already loaded by container.ts; - // nothing to swap. +let bound = false; + +export function bindProductionAuth(config: SanitizedConfig): void { + if (bound) return; + bound = true; + + if (authContainer.isBound(AUTH_SYMBOLS.IUsersRepository)) { + authContainer.unbind(AUTH_SYMBOLS.IUsersRepository); + } + authContainer + .bind(AUTH_SYMBOLS.IUsersRepository) + .toConstantValue(new UsersRepository(config)); + + if (authContainer.isBound(AUTH_SYMBOLS.IAuthenticationService)) { + authContainer.unbind(AUTH_SYMBOLS.IAuthenticationService); + } + authContainer + .bind(AUTH_SYMBOLS.IAuthenticationService) + .toConstantValue(new AuthenticationService(config)); } diff --git a/packages/auth/src/di/container.test.ts b/packages/auth/src/di/container.test.ts index 5798957..2c2ac52 100644 --- a/packages/auth/src/di/container.test.ts +++ b/packages/auth/src/di/container.test.ts @@ -6,6 +6,8 @@ import { MockUsersRepository } from "@/infrastructure/repositories/users.reposit import { MockAuthenticationService } from "@/infrastructure/services/authentication.service.mock"; import type { IUsersRepository } from "@/application/repositories/users.repository.interface"; import type { IAuthenticationService } from "@/application/services/authentication.service.interface"; +import type { ISignInUseCase } from "@/application/use-cases/sign-in.use-case"; +import type { ISignInController } from "@/interface-adapters/controllers/sign-in.controller"; import { userFactory } from "@/__factories__/user.factory"; describe("authContainer", () => { @@ -36,14 +38,22 @@ describe("authContainer", () => { const service = authContainer.get( AUTH_SYMBOLS.IAuthenticationService, ); - // The service should be able to validate against the seeded users const user = userFactory.build({ id: "1", username: "alice", passwordHash: "hashed_password_alice" }); const { session, cookie } = await service.createSession(user); expect(session.userId).toBe("1"); expect(cookie.value).toBe(session.id); - // After session creation, validateSession should resolve user via the repo const validated = await service.validateSession(session.id); expect(validated.user.username).toBe("alice"); }); + + it("resolves ISignInUseCase via toDynamicValue binding", () => { + const useCase = authContainer.get(AUTH_SYMBOLS.ISignInUseCase); + expect(typeof useCase).toBe("function"); + }); + + it("resolves ISignInController via toDynamicValue binding", () => { + const controller = authContainer.get(AUTH_SYMBOLS.ISignInController); + expect(typeof controller).toBe("function"); + }); }); diff --git a/packages/auth/src/di/module.ts b/packages/auth/src/di/module.ts index c975541..6785164 100644 --- a/packages/auth/src/di/module.ts +++ b/packages/auth/src/di/module.ts @@ -4,6 +4,30 @@ import type { IUsersRepository } from "../application/repositories/users.reposit import type { IAuthenticationService } from "../application/services/authentication.service.interface"; import { MockUsersRepository } from "../infrastructure/repositories/users.repository.mock"; import { MockAuthenticationService } from "../infrastructure/services/authentication.service.mock"; +import { + signInUseCase, + type ISignInUseCase, +} from "../application/use-cases/sign-in.use-case"; +import { + signUpUseCase, + type ISignUpUseCase, +} from "../application/use-cases/sign-up.use-case"; +import { + signOutUseCase, + type ISignOutUseCase, +} from "../application/use-cases/sign-out.use-case"; +import { + signInController, + type ISignInController, +} from "../interface-adapters/controllers/sign-in.controller"; +import { + signUpController, + type ISignUpController, +} from "../interface-adapters/controllers/sign-up.controller"; +import { + signOutController, + type ISignOutController, +} from "../interface-adapters/controllers/sign-out.controller"; import { AUTH_SYMBOLS } from "./symbols"; export const AuthModule = new ContainerModule((bind: interfaces.Bind) => { @@ -11,4 +35,42 @@ export const AuthModule = new ContainerModule((bind: interfaces.Bind) => { bind(AUTH_SYMBOLS.IAuthenticationService).to( MockAuthenticationService, ); + + bind(AUTH_SYMBOLS.ISignInUseCase).toDynamicValue((ctx) => + signInUseCase( + ctx.container.get(AUTH_SYMBOLS.IUsersRepository), + ctx.container.get(AUTH_SYMBOLS.IAuthenticationService), + ), + ); + + bind(AUTH_SYMBOLS.ISignUpUseCase).toDynamicValue((ctx) => + signUpUseCase( + ctx.container.get(AUTH_SYMBOLS.IUsersRepository), + ctx.container.get(AUTH_SYMBOLS.IAuthenticationService), + ), + ); + + bind(AUTH_SYMBOLS.ISignOutUseCase).toDynamicValue((ctx) => + signOutUseCase( + ctx.container.get(AUTH_SYMBOLS.IAuthenticationService), + ), + ); + + bind(AUTH_SYMBOLS.ISignInController).toDynamicValue((ctx) => + signInController( + ctx.container.get(AUTH_SYMBOLS.ISignInUseCase), + ), + ); + + bind(AUTH_SYMBOLS.ISignUpController).toDynamicValue((ctx) => + signUpController( + ctx.container.get(AUTH_SYMBOLS.ISignUpUseCase), + ), + ); + + bind(AUTH_SYMBOLS.ISignOutController).toDynamicValue((ctx) => + signOutController( + ctx.container.get(AUTH_SYMBOLS.ISignOutUseCase), + ), + ); }); diff --git a/packages/auth/src/di/symbols.ts b/packages/auth/src/di/symbols.ts index 759f31d..e74ca2d 100644 --- a/packages/auth/src/di/symbols.ts +++ b/packages/auth/src/di/symbols.ts @@ -1,4 +1,12 @@ export const AUTH_SYMBOLS = { IUsersRepository: Symbol.for("auth:IUsersRepository"), IAuthenticationService: Symbol.for("auth:IAuthenticationService"), + // Use cases + ISignInUseCase: Symbol.for("auth:ISignInUseCase"), + ISignUpUseCase: Symbol.for("auth:ISignUpUseCase"), + ISignOutUseCase: Symbol.for("auth:ISignOutUseCase"), + // Controllers + ISignInController: Symbol.for("auth:ISignInController"), + ISignUpController: Symbol.for("auth:ISignUpController"), + ISignOutController: Symbol.for("auth:ISignOutController"), } as const; diff --git a/packages/auth/src/infrastructure/repositories/users.repository.test.ts b/packages/auth/src/infrastructure/repositories/users.repository.test.ts new file mode 100644 index 0000000..eb880f7 --- /dev/null +++ b/packages/auth/src/infrastructure/repositories/users.repository.test.ts @@ -0,0 +1,62 @@ +import { describe, vi, beforeEach } from "vitest"; +import { UsersRepository } from "@/infrastructure/repositories/users.repository"; +import { usersRepositoryContract } from "@/__contracts__/users-repository.contract"; +import { stubPayloadConfig } from "@repo/core-testing/payload/stub-config"; + +vi.mock("payload", () => ({ getPayload: vi.fn() })); + +function buildPayloadStub() { + const store = new Map>(); + + return { + create: vi.fn( + async ({ + data, + }: { + collection: string; + data: Record; + overrideAccess?: boolean; + }) => { + const doc = { ...data }; + store.set(String(doc.id), doc); + return doc; + }, + ), + find: vi.fn( + async ({ + where, + }: { + collection: string; + where?: { username?: { equals: string } }; + limit?: number; + overrideAccess?: boolean; + }) => { + const all = Array.from(store.values()); + if (where?.username?.equals) { + return { docs: all.filter((u) => u.username === where.username?.equals) }; + } + return { docs: all }; + }, + ), + findByID: vi.fn( + async ({ id }: { collection: string; id: string; overrideAccess?: boolean }) => { + return store.get(String(id)) ?? null; + }, + ), + }; +} + +describe("UsersRepository", () => { + describe("contract", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + usersRepositoryContract.run(async () => { + const stub = buildPayloadStub(); + const { getPayload } = await import("payload"); + (getPayload as ReturnType).mockResolvedValue(stub); + return new UsersRepository(stubPayloadConfig); + }); + }); +}); diff --git a/packages/auth/src/infrastructure/repositories/users.repository.ts b/packages/auth/src/infrastructure/repositories/users.repository.ts new file mode 100644 index 0000000..5751b23 --- /dev/null +++ b/packages/auth/src/infrastructure/repositories/users.repository.ts @@ -0,0 +1,51 @@ +import { getPayload } from "payload"; +import type { SanitizedConfig } from "payload"; +import type { IUsersRepository } from "../../application/repositories/users.repository.interface"; +import { type User } from "../../entities/models/user"; + +export class UsersRepository implements IUsersRepository { + constructor(private config: SanitizedConfig) {} + + async getUser(id: string): Promise { + const payload = await getPayload({ config: this.config }); + const result = await payload.findByID({ + collection: "users", + id, + overrideAccess: true, + }); + return result ? this.toDomain(result as Record) : undefined; + } + + async getUserByUsername(username: string): Promise { + const payload = await getPayload({ config: this.config }); + const { docs } = await payload.find({ + collection: "users", + where: { username: { equals: username } }, + limit: 1, + overrideAccess: true, + }); + return docs[0] ? this.toDomain(docs[0] as Record) : undefined; + } + + async createUser(input: User): Promise { + const payload = await getPayload({ config: this.config }); + const created = await payload.create({ + collection: "users", + data: { + id: input.id, + username: input.username, + passwordHash: input.passwordHash, + }, + overrideAccess: true, + }); + return this.toDomain(created as Record); + } + + private toDomain(doc: Record): User { + return { + id: doc.id as string, + username: doc.username as string, + passwordHash: doc.passwordHash as string, + }; + } +} diff --git a/packages/auth/src/infrastructure/services/authentication.service.test.ts b/packages/auth/src/infrastructure/services/authentication.service.test.ts new file mode 100644 index 0000000..bf46569 --- /dev/null +++ b/packages/auth/src/infrastructure/services/authentication.service.test.ts @@ -0,0 +1,61 @@ +import { describe, it, expect } from "vitest"; +import { AuthenticationService } from "@/infrastructure/services/authentication.service"; +import { stubPayloadConfig } from "@repo/core-testing/payload/stub-config"; + +describe("AuthenticationService", () => { + const service = new AuthenticationService(stubPayloadConfig); + + describe("generateUserId", () => { + it("returns a UUID string", () => { + const id = service.generateUserId(); + expect(id).toMatch( + /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, + ); + }); + + it("returns unique values", () => { + const ids = Array.from({ length: 5 }, () => service.generateUserId()); + const unique = new Set(ids); + expect(unique.size).toBe(5); + }); + }); + + describe("hashPassword + verifyPassword", () => { + it("round-trips: hash then verify returns true", async () => { + const hash = await service.hashPassword("my-secret"); + const valid = await service.verifyPassword(hash, "my-secret"); + expect(valid).toBe(true); + }); + + it("returns false for wrong password", async () => { + const hash = await service.hashPassword("my-secret"); + const valid = await service.verifyPassword(hash, "wrong-password"); + expect(valid).toBe(false); + }); + + it("returns false for malformed stored hash", async () => { + const valid = await service.verifyPassword("not-a-valid-hash", "anything"); + expect(valid).toBe(false); + }); + }); + + describe("deferred methods (NotImplementedError)", () => { + const user = { + id: "test-id", + username: "testuser", + passwordHash: "hashed_password", + }; + + it("createSession throws NotImplementedError", async () => { + await expect(service.createSession(user)).rejects.toThrow("NotImplemented"); + }); + + it("validateSession throws NotImplementedError", async () => { + await expect(service.validateSession("some-session")).rejects.toThrow("NotImplemented"); + }); + + it("invalidateSession throws NotImplementedError", async () => { + await expect(service.invalidateSession("some-session")).rejects.toThrow("NotImplemented"); + }); + }); +}); diff --git a/packages/auth/src/infrastructure/services/authentication.service.ts b/packages/auth/src/infrastructure/services/authentication.service.ts new file mode 100644 index 0000000..c821482 --- /dev/null +++ b/packages/auth/src/infrastructure/services/authentication.service.ts @@ -0,0 +1,93 @@ +import crypto from "node:crypto"; +import type { SanitizedConfig } from "payload"; +import type { IAuthenticationService } from "../../application/services/authentication.service.interface"; +import type { Cookie } from "../../entities/models/cookie"; +import type { Session } from "../../entities/models/session"; +import type { User } from "../../entities/models/user"; + +// --------------------------------------------------------------------------- +// Deferred methods +// --------------------------------------------------------------------------- +// `createSession`, `validateSession`, and `invalidateSession` require Payload's +// internal JWT-based auth session machinery, which does not map cleanly to a +// generic session interface without deep integration with Payload's REST/local +// API and cookie infrastructure. +// +// TODO(lazar-conformance §7): Implement these three methods once the session +// cookie strategy is settled. Until then they throw NotImplementedError to +// keep the production-shaped file in place without silently no-oping. +// +// The mock (`authentication.service.mock.ts`) handles all test paths. + +class NotImplementedError extends Error { + constructor(method: string) { + super(`NotImplemented: AuthenticationService.${method} — see refactor log §7`); + this.name = "NotImplementedError"; + } +} + +const SALT_LENGTH = 16; +const KEY_LENGTH = 64; +const ITERATIONS = 100_000; +const DIGEST = "sha512"; +const SEPARATOR = ":"; + +export class AuthenticationService implements IAuthenticationService { + constructor(private _config: SanitizedConfig) {} + + generateUserId(): string { + return crypto.randomUUID(); + } + + async hashPassword(password: string): Promise { + const salt = crypto.randomBytes(SALT_LENGTH).toString("hex"); + const hash = await new Promise((resolve, reject) => { + crypto.pbkdf2(password, salt, ITERATIONS, KEY_LENGTH, DIGEST, (err, derivedKey) => { + if (err) reject(err); + else resolve(derivedKey.toString("hex")); + }); + }); + return `${salt}${SEPARATOR}${hash}`; + } + + async verifyPassword(storedHash: string, password: string): Promise { + const parts = storedHash.split(SEPARATOR); + if (parts.length !== 2) return false; + const salt = parts[0]!; + const expectedHash = parts[1]!; + const actualHash = await new Promise((resolve, reject) => { + crypto.pbkdf2(password, salt, ITERATIONS, KEY_LENGTH, DIGEST, (err, derivedKey) => { + if (err) reject(err); + else resolve(derivedKey.toString("hex")); + }); + }); + return crypto.timingSafeEqual( + Buffer.from(expectedHash, "hex"), + Buffer.from(actualHash, "hex"), + ); + } + + // TODO(lazar-conformance §7): Implement using Payload's local.login / JWT session issuance. + // Payload creates sessions via its REST auth endpoint; mapping that to a + // generic { session: Session; cookie: Cookie } shape requires understanding + // the JWT payload structure and the cookie name/attributes Payload uses. + // eslint-disable-next-line @typescript-eslint/no-unused-vars + async createSession(user: User): Promise<{ session: Session; cookie: Cookie }> { + throw new NotImplementedError("createSession"); + } + + // TODO(lazar-conformance §7): Implement using Payload's JWT verify mechanism. + // Need to call Payload's local API to verify the token and retrieve the user. + // eslint-disable-next-line @typescript-eslint/no-unused-vars + async validateSession(sessionId: string): Promise<{ user: User; session: Session }> { + throw new NotImplementedError("validateSession"); + } + + // TODO(lazar-conformance §7): Implement by clearing the session token. + // Payload does not have a server-side session store by default; invalidation + // is typically done client-side by clearing the cookie. + // eslint-disable-next-line @typescript-eslint/no-unused-vars + async invalidateSession(sessionId: string): Promise<{ blankCookie: Cookie }> { + throw new NotImplementedError("invalidateSession"); + } +} diff --git a/packages/auth/src/integrations/api/router.test.ts b/packages/auth/src/integrations/api/router.test.ts index 99340c0..a3a7a02 100644 --- a/packages/auth/src/integrations/api/router.test.ts +++ b/packages/auth/src/integrations/api/router.test.ts @@ -1,30 +1,7 @@ -import { beforeEach, describe, expect, it } from "vitest"; -import { authContainer } from "@/di/container"; -import { AUTH_SYMBOLS } from "@/di/symbols"; -import { MockUsersRepository } from "@/infrastructure/repositories/users.repository.mock"; -import { MockAuthenticationService } from "@/infrastructure/services/authentication.service.mock"; -import type { IUsersRepository } from "@/application/repositories/users.repository.interface"; -import type { IAuthenticationService } from "@/application/services/authentication.service.interface"; +import { describe, it, expect } from "vitest"; import { authRouter } from "./router"; describe("authRouter", () => { - beforeEach(() => { - if (authContainer.isBound(AUTH_SYMBOLS.IUsersRepository)) { - authContainer.unbind(AUTH_SYMBOLS.IUsersRepository); - } - if (authContainer.isBound(AUTH_SYMBOLS.IAuthenticationService)) { - authContainer.unbind(AUTH_SYMBOLS.IAuthenticationService); - } - const usersRepo = new MockUsersRepository(); - const authService = new MockAuthenticationService(usersRepo); - authContainer - .bind(AUTH_SYMBOLS.IUsersRepository) - .toConstantValue(usersRepo); - authContainer - .bind(AUTH_SYMBOLS.IAuthenticationService) - .toConstantValue(authService); - }); - it("exposes signIn, signUp, signOut procedures", () => { const names = Object.keys(authRouter._def.procedures); expect(names).toContain("signIn"); @@ -32,7 +9,9 @@ describe("authRouter", () => { expect(names).toContain("signOut"); }); - it("signIn returns a cookie", async () => { + it("signIn returns a cookie via container-resolved controller", async () => { + // The router resolves controllers via the authContainer (default mock bindings). + // MockUsersRepository is seeded with alice/password_alice by default. const caller = authRouter.createCaller({}); const result = await caller.signIn({ username: "alice", diff --git a/packages/auth/src/integrations/api/router.ts b/packages/auth/src/integrations/api/router.ts index 1c36a04..e2856d2 100644 --- a/packages/auth/src/integrations/api/router.ts +++ b/packages/auth/src/integrations/api/router.ts @@ -1,8 +1,10 @@ import { z } from "zod"; import { router, publicProcedure } from "@repo/core-shared/trpc/init"; -import { signInController } from "../../interface-adapters/controllers/sign-in.controller"; -import { signUpController } from "../../interface-adapters/controllers/sign-up.controller"; -import { signOutController } from "../../interface-adapters/controllers/sign-out.controller"; +import { authContainer } from "../../di/container"; +import { AUTH_SYMBOLS } from "../../di/symbols"; +import type { ISignInController } from "../../interface-adapters/controllers/sign-in.controller"; +import type { ISignUpController } from "../../interface-adapters/controllers/sign-up.controller"; +import type { ISignOutController } from "../../interface-adapters/controllers/sign-out.controller"; export const authRouter = router({ signIn: publicProcedure @@ -12,7 +14,10 @@ export const authRouter = router({ password: z.string().min(6).max(255), }), ) - .mutation(({ input }) => signInController(input)), + .mutation(({ input }) => { + const ctrl = authContainer.get(AUTH_SYMBOLS.ISignInController); + return ctrl(input); + }), signUp: publicProcedure .input( @@ -22,11 +27,17 @@ export const authRouter = router({ confirmPassword: z.string().min(6).max(255), }), ) - .mutation(({ input }) => signUpController(input)), + .mutation(({ input }) => { + const ctrl = authContainer.get(AUTH_SYMBOLS.ISignUpController); + return ctrl(input); + }), signOut: publicProcedure .input(z.object({ sessionId: z.string() })) - .mutation(({ input }) => signOutController(input.sessionId)), + .mutation(({ input }) => { + const ctrl = authContainer.get(AUTH_SYMBOLS.ISignOutController); + return ctrl(input.sessionId); + }), }); export type AuthRouter = typeof authRouter; diff --git a/packages/auth/src/interface-adapters/controllers/sign-in.controller.test.ts b/packages/auth/src/interface-adapters/controllers/sign-in.controller.test.ts index 7f878be..de69150 100644 --- a/packages/auth/src/interface-adapters/controllers/sign-in.controller.test.ts +++ b/packages/auth/src/interface-adapters/controllers/sign-in.controller.test.ts @@ -1,51 +1,47 @@ -import { beforeEach, describe, expect, it } from "vitest"; -import { authContainer } from "@/di/container"; -import { AUTH_SYMBOLS } from "@/di/symbols"; +import { describe, it, expect } from "vitest"; +import { signInController } from "@/interface-adapters/controllers/sign-in.controller"; import { MockUsersRepository } from "@/infrastructure/repositories/users.repository.mock"; import { MockAuthenticationService } from "@/infrastructure/services/authentication.service.mock"; -import type { IUsersRepository } from "@/application/repositories/users.repository.interface"; -import type { IAuthenticationService } from "@/application/services/authentication.service.interface"; +import { signInUseCase } from "@/application/use-cases/sign-in.use-case"; import { InputParseError } from "@/entities/errors/common"; -import { signInController } from "./sign-in.controller"; +import { userFactory } from "@/__factories__/user.factory"; describe("signInController", () => { - let usersRepo: MockUsersRepository; - let authService: MockAuthenticationService; - - beforeEach(() => { - if (authContainer.isBound(AUTH_SYMBOLS.IUsersRepository)) { - authContainer.unbind(AUTH_SYMBOLS.IUsersRepository); - } - if (authContainer.isBound(AUTH_SYMBOLS.IAuthenticationService)) { - authContainer.unbind(AUTH_SYMBOLS.IAuthenticationService); - } - usersRepo = new MockUsersRepository(); - authService = new MockAuthenticationService(usersRepo); - authContainer - .bind(AUTH_SYMBOLS.IUsersRepository) - .toConstantValue(usersRepo); - authContainer - .bind(AUTH_SYMBOLS.IAuthenticationService) - .toConstantValue(authService); - }); - it("returns a cookie on valid credentials", async () => { - const cookie = await signInController({ + const users = new MockUsersRepository([]); + const auth = new MockAuthenticationService(users); + const seedUser = userFactory.build({ username: "alice", - password: "password_alice", + passwordHash: "hashed_testpassword", }); + await users.createUser(seedUser); + + const useCase = signInUseCase(users, auth); + const controller = signInController(useCase); + + const cookie = await controller({ username: "alice", password: "testpassword" }); expect(cookie.name).toBe("session"); }); it("throws InputParseError on missing username", async () => { + const users = new MockUsersRepository([]); + const auth = new MockAuthenticationService(users); + const useCase = signInUseCase(users, auth); + const controller = signInController(useCase); + await expect( - signInController({ password: "anything" }), + controller({ password: "anything" }), ).rejects.toBeInstanceOf(InputParseError); }); it("throws InputParseError on too-short password", async () => { + const users = new MockUsersRepository([]); + const auth = new MockAuthenticationService(users); + const useCase = signInUseCase(users, auth); + const controller = signInController(useCase); + await expect( - signInController({ username: "alice", password: "abc" }), + controller({ username: "alice", password: "abc" }), ).rejects.toBeInstanceOf(InputParseError); }); }); diff --git a/packages/auth/src/interface-adapters/controllers/sign-in.controller.ts b/packages/auth/src/interface-adapters/controllers/sign-in.controller.ts index 14a9277..d4285ac 100644 --- a/packages/auth/src/interface-adapters/controllers/sign-in.controller.ts +++ b/packages/auth/src/interface-adapters/controllers/sign-in.controller.ts @@ -2,20 +2,22 @@ import { z } from "zod"; import { InputParseError } from "../../entities/errors/common"; import type { Cookie } from "../../entities/models/cookie"; -import { signInUseCase } from "../../application/use-cases/sign-in.use-case"; +import type { ISignInUseCase } from "../../application/use-cases/sign-in.use-case"; const inputSchema = z.object({ username: z.string().min(3).max(31), password: z.string().min(6).max(255), }); -export async function signInController( - input: Partial>, -): Promise { - const parsed = inputSchema.safeParse(input); - if (!parsed.success) { - throw new InputParseError("Invalid sign-in input", { cause: parsed.error }); - } - const { cookie } = await signInUseCase(parsed.data); - return cookie; -} +export type ISignInController = ReturnType; + +export const signInController = + (signInUseCase: ISignInUseCase) => + async (input: Partial>): Promise => { + const parsed = inputSchema.safeParse(input); + if (!parsed.success) { + throw new InputParseError("Invalid sign-in input", { cause: parsed.error }); + } + const { cookie } = await signInUseCase(parsed.data); + return cookie; + }; diff --git a/packages/auth/src/interface-adapters/controllers/sign-out.controller.test.ts b/packages/auth/src/interface-adapters/controllers/sign-out.controller.test.ts index 5f272d8..2d109aa 100644 --- a/packages/auth/src/interface-adapters/controllers/sign-out.controller.test.ts +++ b/packages/auth/src/interface-adapters/controllers/sign-out.controller.test.ts @@ -1,40 +1,28 @@ -import { beforeEach, describe, expect, it } from "vitest"; -import { authContainer } from "@/di/container"; -import { AUTH_SYMBOLS } from "@/di/symbols"; +import { describe, it, expect } from "vitest"; +import { signOutController } from "@/interface-adapters/controllers/sign-out.controller"; import { MockUsersRepository } from "@/infrastructure/repositories/users.repository.mock"; import { MockAuthenticationService } from "@/infrastructure/services/authentication.service.mock"; -import type { IUsersRepository } from "@/application/repositories/users.repository.interface"; -import type { IAuthenticationService } from "@/application/services/authentication.service.interface"; +import { signOutUseCase } from "@/application/use-cases/sign-out.use-case"; import { InputParseError } from "@/entities/errors/common"; -import { signOutController } from "./sign-out.controller"; describe("signOutController", () => { - beforeEach(() => { - if (authContainer.isBound(AUTH_SYMBOLS.IUsersRepository)) { - authContainer.unbind(AUTH_SYMBOLS.IUsersRepository); - } - if (authContainer.isBound(AUTH_SYMBOLS.IAuthenticationService)) { - authContainer.unbind(AUTH_SYMBOLS.IAuthenticationService); - } - const usersRepo = new MockUsersRepository(); - const authService = new MockAuthenticationService(usersRepo); - authContainer - .bind(AUTH_SYMBOLS.IUsersRepository) - .toConstantValue(usersRepo); - authContainer - .bind(AUTH_SYMBOLS.IAuthenticationService) - .toConstantValue(authService); - }); - it("returns a blank cookie", async () => { - const cookie = await signOutController("session_anything"); + const users = new MockUsersRepository([]); + const auth = new MockAuthenticationService(users); + const useCase = signOutUseCase(auth); + const controller = signOutController(useCase); + + const cookie = await controller("session_anything"); expect(cookie.name).toBe("session"); expect(cookie.value).toBe(""); }); it("throws InputParseError when sessionId is missing", async () => { - await expect(signOutController(undefined)).rejects.toBeInstanceOf( - InputParseError, - ); + const users = new MockUsersRepository([]); + const auth = new MockAuthenticationService(users); + const useCase = signOutUseCase(auth); + const controller = signOutController(useCase); + + await expect(controller(undefined)).rejects.toBeInstanceOf(InputParseError); }); }); diff --git a/packages/auth/src/interface-adapters/controllers/sign-out.controller.ts b/packages/auth/src/interface-adapters/controllers/sign-out.controller.ts index 3ec085c..aa4785a 100644 --- a/packages/auth/src/interface-adapters/controllers/sign-out.controller.ts +++ b/packages/auth/src/interface-adapters/controllers/sign-out.controller.ts @@ -1,13 +1,15 @@ import { InputParseError } from "../../entities/errors/common"; import type { Cookie } from "../../entities/models/cookie"; -import { signOutUseCase } from "../../application/use-cases/sign-out.use-case"; +import type { ISignOutUseCase } from "../../application/use-cases/sign-out.use-case"; -export async function signOutController( - sessionId: string | undefined, -): Promise { - if (!sessionId) { - throw new InputParseError("Must provide a session ID"); - } - const { blankCookie } = await signOutUseCase(sessionId); - return blankCookie; -} +export type ISignOutController = ReturnType; + +export const signOutController = + (signOutUseCase: ISignOutUseCase) => + async (sessionId: string | undefined): Promise => { + if (!sessionId) { + throw new InputParseError("Must provide a session ID"); + } + const { blankCookie } = await signOutUseCase(sessionId); + return blankCookie; + }; diff --git a/packages/auth/src/interface-adapters/controllers/sign-up.controller.test.ts b/packages/auth/src/interface-adapters/controllers/sign-up.controller.test.ts index edbe4c7..2629e17 100644 --- a/packages/auth/src/interface-adapters/controllers/sign-up.controller.test.ts +++ b/packages/auth/src/interface-adapters/controllers/sign-up.controller.test.ts @@ -1,36 +1,19 @@ -import { beforeEach, describe, expect, it } from "vitest"; -import { authContainer } from "@/di/container"; -import { AUTH_SYMBOLS } from "@/di/symbols"; +import { describe, it, expect } from "vitest"; +import { signUpController } from "@/interface-adapters/controllers/sign-up.controller"; import { MockUsersRepository } from "@/infrastructure/repositories/users.repository.mock"; import { MockAuthenticationService } from "@/infrastructure/services/authentication.service.mock"; -import type { IUsersRepository } from "@/application/repositories/users.repository.interface"; -import type { IAuthenticationService } from "@/application/services/authentication.service.interface"; +import { signUpUseCase } from "@/application/use-cases/sign-up.use-case"; import { InputParseError } from "@/entities/errors/common"; -import { signUpController } from "./sign-up.controller"; +import { userFactory } from "@/__factories__/user.factory"; describe("signUpController", () => { - let usersRepo: MockUsersRepository; - let authService: MockAuthenticationService; - - beforeEach(() => { - if (authContainer.isBound(AUTH_SYMBOLS.IUsersRepository)) { - authContainer.unbind(AUTH_SYMBOLS.IUsersRepository); - } - if (authContainer.isBound(AUTH_SYMBOLS.IAuthenticationService)) { - authContainer.unbind(AUTH_SYMBOLS.IAuthenticationService); - } - usersRepo = new MockUsersRepository(); - authService = new MockAuthenticationService(usersRepo); - authContainer - .bind(AUTH_SYMBOLS.IUsersRepository) - .toConstantValue(usersRepo); - authContainer - .bind(AUTH_SYMBOLS.IAuthenticationService) - .toConstantValue(authService); - }); - it("creates a new user when passwords match", async () => { - const result = await signUpController({ + const users = new MockUsersRepository([]); + const auth = new MockAuthenticationService(users); + const useCase = signUpUseCase(users, auth); + const controller = signUpController(useCase); + + const result = await controller({ username: "carol", password: "secret_password", confirmPassword: "secret_password", @@ -39,12 +22,30 @@ describe("signUpController", () => { }); it("throws InputParseError when passwords do not match", async () => { + const users = new MockUsersRepository([]); + const auth = new MockAuthenticationService(users); + const useCase = signUpUseCase(users, auth); + const controller = signUpController(useCase); + await expect( - signUpController({ + controller({ username: "dave", password: "secret_password", confirmPassword: "different_password", }), ).rejects.toBeInstanceOf(InputParseError); }); + + it("throws InputParseError when username is too short", async () => { + const users = new MockUsersRepository([]); + const auth = new MockAuthenticationService(users); + // Pre-seed so we don't hit the taken-username error + await users.createUser(userFactory.build({ username: "alice" })); + const useCase = signUpUseCase(users, auth); + const controller = signUpController(useCase); + + await expect( + controller({ username: "ab", password: "secret_password", confirmPassword: "secret_password" }), + ).rejects.toBeInstanceOf(InputParseError); + }); }); diff --git a/packages/auth/src/interface-adapters/controllers/sign-up.controller.ts b/packages/auth/src/interface-adapters/controllers/sign-up.controller.ts index 6484a73..b12d296 100644 --- a/packages/auth/src/interface-adapters/controllers/sign-up.controller.ts +++ b/packages/auth/src/interface-adapters/controllers/sign-up.controller.ts @@ -1,7 +1,7 @@ import { z } from "zod"; import { InputParseError } from "../../entities/errors/common"; -import { signUpUseCase } from "../../application/use-cases/sign-up.use-case"; +import type { ISignUpUseCase } from "../../application/use-cases/sign-up.use-case"; const inputSchema = z .object({ @@ -24,12 +24,16 @@ const inputSchema = z } }); -export async function signUpController( - input: Partial>, -): Promise> { - const parsed = inputSchema.safeParse(input); - if (!parsed.success) { - throw new InputParseError("Invalid sign-up input", { cause: parsed.error }); - } - return await signUpUseCase(parsed.data); -} +export type ISignUpController = ReturnType; + +export const signUpController = + (signUpUseCase: ISignUpUseCase) => + async ( + input: Partial>, + ): Promise>> => { + const parsed = inputSchema.safeParse(input); + if (!parsed.success) { + throw new InputParseError("Invalid sign-up input", { cause: parsed.error }); + } + return await signUpUseCase(parsed.data); + }; diff --git a/packages/auth/tests/sign-in-flow.feature.test.ts b/packages/auth/tests/sign-in-flow.feature.test.ts index 4f927b1..e9bebaa 100644 --- a/packages/auth/tests/sign-in-flow.feature.test.ts +++ b/packages/auth/tests/sign-in-flow.feature.test.ts @@ -1,36 +1,27 @@ // Feature-level test: sign-up, then sign-in with the new credentials, then sign-out. +// Constructs the full chain via direct injection (no container rebinding). -import { beforeEach, describe, expect, it } from "vitest"; -import { authContainer } from "../src/di/container"; -import { AUTH_SYMBOLS } from "../src/di/symbols"; +import { describe, it, expect } from "vitest"; import { MockUsersRepository } from "../src/infrastructure/repositories/users.repository.mock"; import { MockAuthenticationService } from "../src/infrastructure/services/authentication.service.mock"; -import type { IUsersRepository } from "../src/application/repositories/users.repository.interface"; -import type { IAuthenticationService } from "../src/application/services/authentication.service.interface"; -import { authRouter } from "../src/integrations/api/router"; +import { signInUseCase } from "../src/application/use-cases/sign-in.use-case"; +import { signUpUseCase } from "../src/application/use-cases/sign-up.use-case"; +import { signOutUseCase } from "../src/application/use-cases/sign-out.use-case"; +import { signInController } from "../src/interface-adapters/controllers/sign-in.controller"; +import { signUpController } from "../src/interface-adapters/controllers/sign-up.controller"; +import { signOutController } from "../src/interface-adapters/controllers/sign-out.controller"; describe("auth feature: sign-up → sign-in → sign-out", () => { - beforeEach(() => { - if (authContainer.isBound(AUTH_SYMBOLS.IUsersRepository)) { - authContainer.unbind(AUTH_SYMBOLS.IUsersRepository); - } - if (authContainer.isBound(AUTH_SYMBOLS.IAuthenticationService)) { - authContainer.unbind(AUTH_SYMBOLS.IAuthenticationService); - } - const usersRepo = new MockUsersRepository(); - const authService = new MockAuthenticationService(usersRepo); - authContainer - .bind(AUTH_SYMBOLS.IUsersRepository) - .toConstantValue(usersRepo); - authContainer - .bind(AUTH_SYMBOLS.IAuthenticationService) - .toConstantValue(authService); - }); - it("a new user can sign up, then sign in, then sign out", async () => { - const caller = authRouter.createCaller({}); + // Construct the full chain via direct injection + const users = new MockUsersRepository([]); + const auth = new MockAuthenticationService(users); - const signUpResult = await caller.signUp({ + const signIn = signInController(signInUseCase(users, auth)); + const signUp = signUpController(signUpUseCase(users, auth)); + const signOut = signOutController(signOutUseCase(auth)); + + const signUpResult = await signUp({ username: "newperson", password: "verysecret", confirmPassword: "verysecret", @@ -38,15 +29,13 @@ describe("auth feature: sign-up → sign-in → sign-out", () => { expect(signUpResult.user.username).toBe("newperson"); const userId = signUpResult.user.id; - const signInCookie = await caller.signIn({ + const signInCookie = await signIn({ username: "newperson", password: "verysecret", }); expect(signInCookie.value).toBe("session_" + userId); - const signOutResult = await caller.signOut({ - sessionId: signInCookie.value, - }); + const signOutResult = await signOut(signInCookie.value); expect(signOutResult.value).toBe(""); }); });