feat(m3): auth & user management with session, tests, and e2e

- Custom error classes (lib/errors.ts) and signed-cookie session
  (lib/auth/session.ts, HMAC-SHA256, httpOnly+sameSite=lax)
- UserRepository + AuthService (bcrypt hashing, role/status checks,
  register/login/logout/getCurrentUser/updateProfile)
- Auth helpers (getCurrentUser), user validator, API error handler
- API routes: register (auto-login), login, logout, me, PATCH users/me,
  GET admin/migrations (admin-only guard)
- middleware.ts redirects unauthenticated page access to /login
- Screens: login (login/register toggle), profile, dashboard skeleton,
  home redirect
- vitest: exclude e2e specs, setupFiles for SESSION_SECRET
- playwright: run migrate before dev server, set SESSION_SECRET
- Unit tests (UserRepository, AuthService, session), integration
  auth-flow, e2e auth.spec (register/login/logout/protected/401)
This commit is contained in:
Ken Yasue
2026-06-25 00:36:42 +02:00
parent 40ff4fb909
commit 21b9f03e9d
27 changed files with 1578 additions and 10 deletions

81
tests/e2e/auth.spec.ts Normal file
View File

@ -0,0 +1,81 @@
import { test, expect } from '@playwright/test';
function uniqueEmail(): string {
return `e2e-${Date.now()}-${Math.floor(Math.random() * 1_000_000)}@example.com`;
}
test.describe('authentication', () => {
test('register lands on the dashboard, then profile and logout', async ({
page,
}) => {
const email = uniqueEmail();
await page.goto('/login');
await page.getByRole('button', { name: '新規登録はこちら' }).click();
await page.getByLabel('表示名').fill('E2E User');
await page.getByLabel('メールアドレス').fill(email);
await page.getByLabel('パスワード').fill('password123');
await page.getByRole('button', { name: '登録する' }).click();
// 登録と同時にログイン → ダッシュボードへ
await expect(page).toHaveURL(/\/dashboard/);
await expect(
page.getByRole('heading', { name: 'ダッシュボード' })
).toBeVisible();
// プロフィールへ移動しログアウト
await page.getByRole('link', { name: /さん/ }).click();
await expect(page).toHaveURL(/\/profile/);
await page.getByRole('button', { name: 'ログアウト' }).click();
await expect(page).toHaveURL(/\/login/);
});
test('login with a pre-registered account', async ({ page, request }) => {
const email = uniqueEmail();
await request.post('/api/auth/register', {
data: { name: 'Pre User', email, password: 'password123' },
});
await page.goto('/login');
await page.getByLabel('メールアドレス').fill(email);
await page.getByLabel('パスワード').fill('password123');
await page.getByRole('button', { name: 'ログイン' }).click();
await expect(page).toHaveURL(/\/dashboard/);
});
test('wrong password shows an error and stays on login', async ({
page,
request,
}) => {
const email = uniqueEmail();
await request.post('/api/auth/register', {
data: { name: 'Pre User', email, password: 'password123' },
});
await page.goto('/login');
await page.getByLabel('メールアドレス').fill(email);
await page.getByLabel('パスワード').fill('wrong-password');
await page.getByRole('button', { name: 'ログイン' }).click();
await expect(page.getByRole('alert')).toBeVisible();
await expect(page).toHaveURL(/\/login/);
});
test('unauthenticated access to a protected page redirects to login', async ({
browser,
}) => {
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('/dashboard');
await expect(page).toHaveURL(/\/login/);
await context.close();
});
test('unauthenticated API request returns 401', async ({ request }) => {
const res = await request.get('/api/auth/me');
expect(res.status()).toBe(401);
});
});

View File

@ -0,0 +1,89 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createMigratedTestDb } from '@/tests/helpers/db';
import type { SqliteDatabase } from '@/lib/db/sqlite';
import { UserRepository } from '@/repositories/UserRepository';
import { AuthService } from '@/services/AuthService';
import { verifySessionToken } from '@/lib/auth/session';
import { UnauthorizedError } from '@/lib/errors';
describe('authentication flow (integration)', () => {
let db: SqliteDatabase;
let repo: UserRepository;
let authService: AuthService;
beforeEach(() => {
db = createMigratedTestDb();
repo = new UserRepository(db);
authService = new AuthService(repo);
});
afterEach(() => {
db.close();
});
it('registers, logs in, resolves the session, and reads the user', () => {
// 1. 登録
const registered = authService.register({
name: 'Flow User',
email: 'flow@example.com',
password: 'password123',
});
expect(registered.id).toBeGreaterThan(0);
// 2. ログイン → トークン発行
const { user, token } = authService.login(
'flow@example.com',
'password123'
);
expect(user.id).toBe(registered.id);
// 3. トークンからユーザーIDを解決(セッション復元)
const resolvedUserId = verifySessionToken(token);
expect(resolvedUserId).toBe(user.id);
// 4. ユーザーIDから現在ユーザーを取得(getCurrentUser相当)
const current = repo.findById(resolvedUserId!);
expect(current?.email).toBe('flow@example.com');
});
it('rejects login after the account is deactivated', () => {
authService.register({
name: 'Flow User',
email: 'flow@example.com',
password: 'password123',
});
// 一度ログイン成功を確認
expect(() =>
authService.login('flow@example.com', 'password123')
).not.toThrow();
// 無効化
const user = repo.findByEmail('flow@example.com')!;
repo.update(user.id, { status: 'inactive' });
// 無効アカウントではログイン不可
expect(() => authService.login('flow@example.com', 'password123')).toThrow(
UnauthorizedError
);
});
it('prevents a session token from resolving after profile email changes', () => {
const created = authService.register({
name: 'Flow User',
email: 'flow@example.com',
password: 'password123',
});
const { token } = authService.login('flow@example.com', 'password123');
expect(verifySessionToken(token)).toBe(created.id);
// プロフィール更新(メール変更)後もトークンはuidベースで有効
authService.updateProfile(created.id, {
email: 'changed@example.com',
name: 'New Name',
});
const resolved = repo.findById(verifySessionToken(token)!);
expect(resolved?.email).toBe('changed@example.com');
});
});

2
tests/setup.ts Normal file
View File

@ -0,0 +1,2 @@
// テスト実行時に必要な環境変数のデフォルトを設定する
process.env.SESSION_SECRET = process.env.SESSION_SECRET ?? 'test-secret';

View File

@ -0,0 +1,44 @@
import { describe, it, expect } from 'vitest';
import { createSessionToken, verifySessionToken } from '@/lib/auth/session';
describe('session token', () => {
it('round-trips a user id through create and verify', () => {
const token = createSessionToken(42);
expect(verifySessionToken(token)).toBe(42);
});
it('returns null for a tampered signature', () => {
const token = createSessionToken(42);
const [encoded] = token.split('.');
const tampered = `${encoded}.aW52YWxpZHNpZ25hdHVyZQ`;
expect(verifySessionToken(tampered)).toBeNull();
});
it('returns null for a tampered payload', () => {
const token = createSessionToken(42);
const [, signature] = token.split('.');
// payload を別ユーザーIDに書き換えたトークン署名は元のまま
const forgedPayload = Buffer.from(
JSON.stringify({ uid: 99, iat: Date.now() })
).toString('base64url');
const forged = `${forgedPayload}.${signature}`;
expect(verifySessionToken(forged)).toBeNull();
});
it('returns null for a malformed token', () => {
expect(verifySessionToken('not-a-valid-token')).toBeNull();
expect(verifySessionToken('only.one.too.many')).toBeNull();
expect(verifySessionToken('')).toBeNull();
});
it('returns null when the payload uid is not a number', () => {
const encoded = Buffer.from(
JSON.stringify({ uid: 'not-a-number', iat: Date.now() })
).toString('base64url');
// 署名は無意味でも構造は整える
expect(verifySessionToken(`${encoded}.${encoded}`)).toBeNull();
});
});

View File

@ -0,0 +1,127 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createMigratedTestDb } from '@/tests/helpers/db';
import type { SqliteDatabase } from '@/lib/db/sqlite';
import { UserRepository } from '@/repositories/UserRepository';
describe('UserRepository', () => {
let db: SqliteDatabase;
let repo: UserRepository;
beforeEach(() => {
db = createMigratedTestDb();
repo = new UserRepository(db);
});
afterEach(() => {
db.close();
});
describe('create', () => {
it('creates a user and returns it with an id and active status', () => {
const user = repo.create({
name: 'Alice',
email: 'alice@example.com',
passwordHash: 'hashed',
});
expect(user.id).toBeGreaterThan(0);
expect(user.name).toBe('Alice');
expect(user.email).toBe('alice@example.com');
expect(user.passwordHash).toBe('hashed');
expect(user.role).toBe('member');
expect(user.status).toBe('active');
expect(user.createdAt).toBeTruthy();
});
it('rejects a duplicate email (UNIQUE constraint)', () => {
repo.create({
name: 'Alice',
email: 'dup@example.com',
passwordHash: 'h',
});
expect(() =>
repo.create({
name: 'Bob',
email: 'dup@example.com',
passwordHash: 'h',
})
).toThrow();
});
});
describe('findById', () => {
it('returns the user when found', () => {
const created = repo.create({
name: 'Alice',
email: 'a@example.com',
passwordHash: 'h',
});
const found = repo.findById(created.id);
expect(found?.id).toBe(created.id);
expect(found?.name).toBe('Alice');
});
it('returns null when no user exists for the id', () => {
expect(repo.findById(99999)).toBeNull();
});
});
describe('findByEmail', () => {
it('returns the user matching the email', () => {
repo.create({ name: 'Alice', email: 'a@example.com', passwordHash: 'h' });
const found = repo.findByEmail('a@example.com');
expect(found?.name).toBe('Alice');
});
it('returns null when no user matches the email', () => {
expect(repo.findByEmail('nobody@example.com')).toBeNull();
});
});
describe('update', () => {
it('updates name, email, avatarUrl, role and status', () => {
const created = repo.create({
name: 'Alice',
email: 'a@example.com',
passwordHash: 'h',
});
const updated = repo.update(created.id, {
name: 'Alice2',
email: 'a2@example.com',
avatarUrl: 'https://example.com/avatar.png',
role: 'system_admin',
status: 'inactive',
});
expect(updated?.name).toBe('Alice2');
expect(updated?.email).toBe('a2@example.com');
expect(updated?.avatarUrl).toBe('https://example.com/avatar.png');
expect(updated?.role).toBe('system_admin');
expect(updated?.status).toBe('inactive');
});
it('only updates provided fields', () => {
const created = repo.create({
name: 'Alice',
email: 'a@example.com',
passwordHash: 'h',
});
const updated = repo.update(created.id, { name: 'NewName' });
expect(updated?.name).toBe('NewName');
expect(updated?.email).toBe('a@example.com');
});
it('returns null when updating a non-existent user', () => {
const result = repo.update(99999, { name: 'X' });
// UPDATE affects 0 rows; findById returns null
expect(result).toBeNull();
});
});
});

View File

@ -0,0 +1,177 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createMigratedTestDb } from '@/tests/helpers/db';
import type { SqliteDatabase } from '@/lib/db/sqlite';
import { UserRepository } from '@/repositories/UserRepository';
import { AuthService } from '@/services/AuthService';
import { ConflictError, UnauthorizedError, NotFoundError } from '@/lib/errors';
import { verifySessionToken } from '@/lib/auth/session';
import bcrypt from 'bcrypt';
describe('AuthService', () => {
let db: SqliteDatabase;
let repo: UserRepository;
let authService: AuthService;
beforeEach(() => {
db = createMigratedTestDb();
repo = new UserRepository(db);
authService = new AuthService(repo);
});
afterEach(() => {
db.close();
});
describe('register', () => {
it('creates a user with a bcrypt-hashed password', () => {
const user = authService.register({
name: 'Alice',
email: 'alice@example.com',
password: 'password123',
});
expect(user.id).toBeGreaterThan(0);
expect(user.passwordHash).not.toBe('password123');
expect(bcrypt.compareSync('password123', user.passwordHash!)).toBe(true);
expect(user.role).toBe('member');
expect(user.status).toBe('active');
});
it('throws ConflictError when the email is already registered', () => {
authService.register({
name: 'Alice',
email: 'dup@example.com',
password: 'password123',
});
expect(() =>
authService.register({
name: 'Bob',
email: 'dup@example.com',
password: 'password123',
})
).toThrow(ConflictError);
});
it('throws ValidationError for a weak password', () => {
expect(() =>
authService.register({
name: 'Alice',
email: 'a@example.com',
password: 'short',
})
).toThrow();
});
});
describe('login', () => {
beforeEach(() => {
authService.register({
name: 'Alice',
email: 'alice@example.com',
password: 'password123',
});
});
it('returns the user and a verifiable session token on success', () => {
const { user, token } = authService.login(
'alice@example.com',
'password123'
);
expect(user.email).toBe('alice@example.com');
expect(verifySessionToken(token)).toBe(user.id);
});
it('throws UnauthorizedError when the password is wrong', () => {
expect(() =>
authService.login('alice@example.com', 'wrong-password')
).toThrow(UnauthorizedError);
});
it('throws UnauthorizedError when the email does not exist', () => {
expect(() =>
authService.login('nobody@example.com', 'password123')
).toThrow(UnauthorizedError);
});
it('throws UnauthorizedError when the account is inactive', () => {
const user = repo.findByEmail('alice@example.com')!;
repo.update(user.id, { status: 'inactive' });
expect(() =>
authService.login('alice@example.com', 'password123')
).toThrow(UnauthorizedError);
});
});
describe('getCurrentUser', () => {
it('returns the user for a valid id', () => {
const created = authService.register({
name: 'Alice',
email: 'alice@example.com',
password: 'password123',
});
expect(authService.getCurrentUser(created.id)?.email).toBe(
'alice@example.com'
);
});
it('returns null for an unknown id', () => {
expect(authService.getCurrentUser(99999)).toBeNull();
});
});
describe('updateProfile', () => {
it('updates name and email', () => {
const created = authService.register({
name: 'Alice',
email: 'alice@example.com',
password: 'password123',
});
const updated = authService.updateProfile(created.id, {
name: 'Alice New',
email: 'alice2@example.com',
});
expect(updated.name).toBe('Alice New');
expect(updated.email).toBe('alice2@example.com');
});
it('throws ConflictError when changing email to one already in use', () => {
authService.register({
name: 'Alice',
email: 'alice@example.com',
password: 'password123',
});
const bob = authService.register({
name: 'Bob',
email: 'bob@example.com',
password: 'password123',
});
expect(() =>
authService.updateProfile(bob.id, { email: 'alice@example.com' })
).toThrow(ConflictError);
});
it('throws NotFoundError when the user does not exist', () => {
expect(() => authService.updateProfile(99999, { name: 'X' })).toThrow(
NotFoundError
);
});
});
describe('createWithRole', () => {
it('creates a user with the specified role', () => {
const admin = authService.createWithRole(
{ name: 'Admin', email: 'admin@example.com', password: 'password123' },
'system_admin'
);
expect(admin.role).toBe('system_admin');
});
});
});