feat(api): password login, sliding renewal, revocable sessions
- POST /v1/auth/password|refresh|logout per contract operationIds; long-lived single token (32B hex, DB stores sha256 only), sliding renewal without rotation, logout sets sessions.revokedAt. - SessionGuard: Bearer -> session -> user eligibility (disabled/locked/ pending revoke access); all failures map to 401 AUTH_TOKEN_EXPIRED. - Anti-enumeration: unknown account / wrong password / status-blocked share one 401 AUTH_INVALID_CREDENTIALS; unknown-account path runs a dummy argon2 verify to equalize timing. - Login rate limiting (P1): in-memory account+IP sliding window, 5 failures / 15 min -> 429; success clears. Contract amendment (registered): new ErrorCodes.AUTH_RATE_LIMITED added to errors.ts + openapi Error enum + 429 response on /auth/password; generated types regenerated and committed. P1a single-instance limiter; P5 needs a Redis-backed implementation. - Global ValidationPipe (APP_PIPE) enforces class-validator DTOs -> 400 VALIDATION_FAILED via the existing exception filter. Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -20,6 +20,8 @@
|
||||
"@node-rs/argon2": "^2.2.1",
|
||||
"@photo/contracts": "workspace:*",
|
||||
"@photo/db-cn": "workspace:*",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.15.1",
|
||||
"nestjs-pino": "^4.6.1",
|
||||
"pino": "^10.0.0",
|
||||
"pino-http": "^11.0.0",
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
// services/api/src/app-cn.module.ts
|
||||
// 根模块:Prisma(@Global,封装 @photo/db-cn)、日志(nestjs-pino / pino-http)、
|
||||
// request-id 中间件、全局异常过滤器、/v1/health。
|
||||
// 功能模块(auth/albums/uploads/photos/public)自 Task 12+ 起逐个加入。
|
||||
// 过滤器经 APP_FILTER、中间件经 NestModule 在模块层注册——e2e 直接 import 本模块
|
||||
// 即可获得与生产一致的管线(全局前缀除外,由入口设置)。
|
||||
import { type MiddlewareConsumer, Module, type NestModule } from '@nestjs/common';
|
||||
import { APP_FILTER } from '@nestjs/core';
|
||||
// request-id 中间件、全局异常过滤器、全局校验管道(Task 13 起,DTO 经
|
||||
// class-validator 声明、ValidationPipe 强制,失败由过滤器映射 400 VALIDATION_FAILED)、
|
||||
// /v1/health、/v1/auth/*(Task 13)。
|
||||
// 功能模块(albums/uploads/photos/public)自 Task 15+ 起逐个加入。
|
||||
// 过滤器/管道经 APP_FILTER/APP_PIPE、中间件经 NestModule 在模块层注册——e2e 直接
|
||||
// import 本模块即可获得与生产一致的管线(全局前缀除外,由入口设置)。
|
||||
import {
|
||||
type MiddlewareConsumer,
|
||||
Module,
|
||||
type NestModule,
|
||||
ValidationPipe,
|
||||
} from '@nestjs/common';
|
||||
import { APP_FILTER, APP_PIPE } from '@nestjs/core';
|
||||
import { LoggerModule } from 'nestjs-pino';
|
||||
import type { IncomingMessage, ServerResponse } from 'node:http';
|
||||
import { AllExceptionsFilter } from './all-exceptions.filter';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { HealthController } from './health.controller';
|
||||
import { PrismaModule } from './prisma/prisma.module';
|
||||
import { RequestIdMiddleware, resolveRequestId } from './request-id.middleware';
|
||||
@@ -19,6 +27,7 @@ import type { ServerRequestWithId } from './shared/request-with-id';
|
||||
imports: [
|
||||
// @Global:功能模块(Task 12+)直接注入 PrismaService,无需 re-import。
|
||||
PrismaModule,
|
||||
AuthModule,
|
||||
LoggerModule.forRoot({
|
||||
pinoHttp: {
|
||||
// 与 RequestIdMiddleware 共用同一解析函数:优先透传 x-request-id,
|
||||
@@ -43,7 +52,16 @@ import type { ServerRequestWithId } from './shared/request-with-id';
|
||||
}),
|
||||
],
|
||||
controllers: [HealthController],
|
||||
providers: [{ provide: APP_FILTER, useClass: AllExceptionsFilter }],
|
||||
providers: [
|
||||
{ provide: APP_FILTER, useClass: AllExceptionsFilter },
|
||||
// 全局校验管道(Task 13):whitelist 剥离 DTO 未声明的属性(契约未禁未知
|
||||
// 字段,剥离而非拒绝);校验失败抛 BadRequestException → 过滤器映射
|
||||
// 400 VALIDATION_FAILED。经 APP_PIPE 在模块层注册,e2e 复用同一管线。
|
||||
{
|
||||
provide: APP_PIPE,
|
||||
useFactory: () => new ValidationPipe({ whitelist: true }),
|
||||
},
|
||||
],
|
||||
})
|
||||
export class AppCnModule implements NestModule {
|
||||
configure(consumer: MiddlewareConsumer): void {
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
// services/api/src/auth/auth.controller.ts —— /auth/* 端点(Task 13)。
|
||||
// 方法名与契约 operationId 一一对应(loginWithPassword / refreshSession / logout),
|
||||
// 响应形状严格契约:camelCase sessionToken/expiresAt,logout 204 无响应体。
|
||||
// /auth/password 无守卫(security: []);refresh/logout 经 SessionGuard(Bearer)。
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Post,
|
||||
Req,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ErrorCodes } from '@photo/contracts';
|
||||
import { ApiException } from '../api-exception';
|
||||
import { AuthService } from './auth.service';
|
||||
import { LoginRequestDto } from './dto';
|
||||
import { AuthenticatedRequest, SessionGuard } from './session.guard';
|
||||
|
||||
/** 登录请求侧只需客户端来源 IP(限速键的一半)。 */
|
||||
interface ClientRequest {
|
||||
ip?: string;
|
||||
socket?: { remoteAddress?: string | undefined };
|
||||
}
|
||||
|
||||
function clientIpOf(req: ClientRequest): string {
|
||||
return req.ip ?? req.socket?.remoteAddress ?? 'unknown';
|
||||
}
|
||||
|
||||
/** 守卫放行后提取会话 id;防御性兜底(守卫未挂载属装配错误,按未认证拒绝)。 */
|
||||
function sessionOf(req: AuthenticatedRequest): string {
|
||||
if (req.sessionId === undefined || req.user === undefined) {
|
||||
throw new ApiException(
|
||||
ErrorCodes.AUTH_TOKEN_EXPIRED,
|
||||
'Session token is missing, invalid, or expired',
|
||||
HttpStatus.UNAUTHORIZED,
|
||||
);
|
||||
}
|
||||
return req.sessionId;
|
||||
}
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
@Post('password')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
loginWithPassword(
|
||||
@Body() dto: LoginRequestDto,
|
||||
@Req() req: ClientRequest,
|
||||
): Promise<{ sessionToken: string; expiresAt: string }> {
|
||||
return this.authService.login(dto.account, dto.password, clientIpOf(req));
|
||||
}
|
||||
|
||||
@Post('refresh')
|
||||
@UseGuards(SessionGuard)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
refreshSession(
|
||||
@Req() req: AuthenticatedRequest,
|
||||
): Promise<{ expiresAt: string }> {
|
||||
return this.authService.refresh(sessionOf(req));
|
||||
}
|
||||
|
||||
@Post('logout')
|
||||
@UseGuards(SessionGuard)
|
||||
@HttpCode(HttpStatus.NO_CONTENT)
|
||||
async logout(@Req() req: AuthenticatedRequest): Promise<void> {
|
||||
await this.authService.logout(sessionOf(req));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// services/api/src/auth/auth.module.ts —— 认证模块(Task 13)。
|
||||
// SessionGuard 一并提供(@UseGuards(SessionGuard) 按类引用时经所属模块 DI 解析),
|
||||
// 但无需 export:guard 只依赖 @Global 的 PrismaService,任意功能模块引用均可解析。
|
||||
// export AuthService 供后续模块复用(如管理端主动吊销会话)。
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { SessionGuard } from './session.guard';
|
||||
|
||||
@Module({
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, SessionGuard],
|
||||
exports: [AuthService],
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -0,0 +1,209 @@
|
||||
// services/api/src/auth/auth.service.ts —— 登录 / 滑动续期 / 注销核心逻辑(Task 13)。
|
||||
// 会话模型:长效单令牌 + 滑动续期(用户决策 2026-09-17,不做 access/refresh 双层)。
|
||||
// 令牌 = 32B randomBytes hex(仅登录响应出现一次);库内只存 sha256(token)。
|
||||
// 安全要点:
|
||||
// · 防账号枚举——账号不存在 / 密码错误 / 状态不合格(停用、锁定、待激活)三者
|
||||
// 返回同一 401 AUTH_INVALID_CREDENTIALS 且同文案;账号不存在时也跑一次等代价
|
||||
// argon2 verify(dummy hash)拉平时延,杜绝「响应快慢」侧信道。
|
||||
// · 登录失败限速(总纲 P1)——account+IP 维度、15 分钟窗口、5 次失败锁定,
|
||||
// 成功登录清零。进程内存实现:P1a 单实例足够;P5 多实例需换 Redis 后端限速器
|
||||
// (本类私有接口不变,替换实现即可)。
|
||||
// · 审计——登录成功写 audit_logs(action='auth.login', actor=用户);
|
||||
// 注销不写审计(会话行 revokedAt 本身即持久的注销凭据)。
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { HttpStatus, Injectable } from '@nestjs/common';
|
||||
import { ErrorCodes } from '@photo/contracts';
|
||||
import { ApiException } from '../api-exception';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { hashPassword, verifyPassword } from './password';
|
||||
import { hashSessionToken } from './session.guard';
|
||||
|
||||
/** 契约默认 30 天(.env AUTH_SESSION_TTL_SECONDS 同名可调)。 */
|
||||
const DEFAULT_SESSION_TTL_SECONDS = 2_592_000;
|
||||
|
||||
const LOGIN_RATE_LIMIT_MAX_FAILURES = 5;
|
||||
const LOGIN_RATE_LIMIT_WINDOW_MS = 15 * 60 * 1000;
|
||||
|
||||
function invalidCredentials(): ApiException {
|
||||
return new ApiException(
|
||||
ErrorCodes.AUTH_INVALID_CREDENTIALS,
|
||||
'Invalid account or password',
|
||||
HttpStatus.UNAUTHORIZED,
|
||||
);
|
||||
}
|
||||
|
||||
// 惰性生成一次 dummy argon2 哈希并复用:账号不存在路径用它跑等代价 verify。
|
||||
// 选「首用时生成」而非内嵌常量:参数始终跟随 hashPassword 当前默认,不会因
|
||||
// 升级 argon2 参数而漂移成不等价时延。
|
||||
let dummyHashPromise: Promise<string> | undefined;
|
||||
function dummyHash(): Promise<string> {
|
||||
dummyHashPromise ??= hashPassword(randomBytes(32).toString('hex'));
|
||||
return dummyHashPromise;
|
||||
}
|
||||
|
||||
/** 进程内滑动窗口失败计数器(account+IP 维度)。 */
|
||||
class InMemoryLoginRateLimiter {
|
||||
private readonly buckets = new Map<string, { count: number; windowStart: number }>();
|
||||
|
||||
constructor(
|
||||
private readonly maxFailures: number,
|
||||
private readonly windowMs: number,
|
||||
) {}
|
||||
|
||||
/** 窗口期内失败次数达到阈值即锁定;窗口过期顺手淘汰条目,Map 不无界增长。 */
|
||||
isLocked(key: string): boolean {
|
||||
const bucket = this.buckets.get(key);
|
||||
if (bucket === undefined) {
|
||||
return false;
|
||||
}
|
||||
if (Date.now() - bucket.windowStart >= this.windowMs) {
|
||||
this.buckets.delete(key);
|
||||
return false;
|
||||
}
|
||||
return bucket.count >= this.maxFailures;
|
||||
}
|
||||
|
||||
recordFailure(key: string): void {
|
||||
const now = Date.now();
|
||||
const bucket = this.buckets.get(key);
|
||||
if (bucket === undefined || now - bucket.windowStart >= this.windowMs) {
|
||||
this.buckets.set(key, { count: 1, windowStart: now });
|
||||
return;
|
||||
}
|
||||
bucket.count += 1;
|
||||
}
|
||||
|
||||
clear(key: string): void {
|
||||
this.buckets.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
export interface LoginResult {
|
||||
sessionToken: string;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
export interface RenewalResult {
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
private readonly sessionTtlSeconds: number;
|
||||
private readonly rateLimiter = new InMemoryLoginRateLimiter(
|
||||
LOGIN_RATE_LIMIT_MAX_FAILURES,
|
||||
LOGIN_RATE_LIMIT_WINDOW_MS,
|
||||
);
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {
|
||||
const raw = Number.parseInt(
|
||||
process.env.AUTH_SESSION_TTL_SECONDS ?? '',
|
||||
10,
|
||||
);
|
||||
this.sessionTtlSeconds =
|
||||
Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_SESSION_TTL_SECONDS;
|
||||
}
|
||||
|
||||
async login(
|
||||
account: string,
|
||||
plainPassword: string,
|
||||
ip: string,
|
||||
): Promise<LoginResult> {
|
||||
// ① 限速先行:锁定期内不触 DB、不跑 argon2(即便密码正确也 429,
|
||||
// 防止用「锁定与否」探测密码正确性)。
|
||||
const rateKey = `${account}|${ip}`;
|
||||
if (this.rateLimiter.isLocked(rateKey)) {
|
||||
throw new ApiException(
|
||||
ErrorCodes.AUTH_RATE_LIMITED,
|
||||
'Too many failed login attempts; try again later',
|
||||
HttpStatus.TOO_MANY_REQUESTS,
|
||||
);
|
||||
}
|
||||
|
||||
// ② 查用户:不存在 → dummy verify 拉平时延后与密码错误同响应。
|
||||
const user = await this.prisma.users.findUnique({ where: { account } });
|
||||
if (user === null) {
|
||||
await verifyPassword(await dummyHash(), plainPassword);
|
||||
this.rateLimiter.recordFailure(rateKey);
|
||||
throw invalidCredentials();
|
||||
}
|
||||
|
||||
// ③ 先验密码再查状态:状态不合格与密码错误同样不可区分(同 401 同文案;
|
||||
// argon2 在两条路径都真实跑过,时延也一致)。
|
||||
if (!(await verifyPassword(user.passwordHash, plainPassword))) {
|
||||
this.rateLimiter.recordFailure(rateKey);
|
||||
throw invalidCredentials();
|
||||
}
|
||||
if (
|
||||
user.sourceStatus === 'disabled' ||
|
||||
user.localLocked ||
|
||||
user.credentialStatus !== 'active'
|
||||
) {
|
||||
// 密码已证实正确——不属于凭据猜测,不计入限速(限速针对撞库,
|
||||
// 停用/待激活账号本就无法登录,计数无防护收益)。
|
||||
throw invalidCredentials();
|
||||
}
|
||||
|
||||
// ④ 签发会话:明文令牌仅本次返回;库存 sha256,expiresAt=now+TTL。
|
||||
const sessionToken = randomBytes(32).toString('hex');
|
||||
const session = await this.prisma.sessions.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
tokenHash: hashSessionToken(sessionToken),
|
||||
expiresAt: new Date(Date.now() + this.sessionTtlSeconds * 1000),
|
||||
},
|
||||
});
|
||||
this.rateLimiter.clear(rateKey);
|
||||
|
||||
// ⑤ 审计(resourceId=会话 id:登录动作产出的资源即会话)。
|
||||
await this.prisma.audit_logs.create({
|
||||
data: {
|
||||
actorId: user.id,
|
||||
action: 'auth.login',
|
||||
resourceId: session.id,
|
||||
metadata: { ip },
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
sessionToken,
|
||||
expiresAt: session.expiresAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 滑动续期:同一令牌不轮换(会话行只前移 expiresAt)。
|
||||
* 守卫已校验有效性;此处仍防御性复核(守卫与更新之间存在微小窗口,
|
||||
* 且未来其它调用方可能绕过守卫)。
|
||||
*/
|
||||
async refresh(sessionId: string): Promise<RenewalResult> {
|
||||
const session = await this.prisma.sessions.findUnique({
|
||||
where: { id: sessionId },
|
||||
});
|
||||
if (
|
||||
session === null ||
|
||||
session.revokedAt !== null ||
|
||||
session.expiresAt.getTime() <= Date.now()
|
||||
) {
|
||||
throw new ApiException(
|
||||
ErrorCodes.AUTH_TOKEN_EXPIRED,
|
||||
'Session token is missing, invalid, or expired',
|
||||
HttpStatus.UNAUTHORIZED,
|
||||
);
|
||||
}
|
||||
const expiresAt = new Date(Date.now() + this.sessionTtlSeconds * 1000);
|
||||
await this.prisma.sessions.update({
|
||||
where: { id: sessionId },
|
||||
data: { expiresAt },
|
||||
});
|
||||
return { expiresAt: expiresAt.toISOString() };
|
||||
}
|
||||
|
||||
/** 注销:置 revokedAt;幂等(updateMany 只在尚未撤销时落时间戳)。 */
|
||||
async logout(sessionId: string): Promise<void> {
|
||||
await this.prisma.sessions.updateMany({
|
||||
where: { id: sessionId, revokedAt: null },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// services/api/src/auth/dto.ts —— auth 端点入参 DTO(Task 13)。
|
||||
// Nest 约定用 class-validator + class-transformer(非 zod):装饰器元数据供全局
|
||||
// ValidationPipe(app-cn.module 经 APP_PIPE 注册)校验,失败抛 BadRequestException,
|
||||
// 由全局过滤器映射 400 VALIDATION_FAILED(契约各 auth 端点的 '400' 响应)。
|
||||
// 字段约束对齐契约 LoginRequest:account/password 均为非空字符串;契约未定义
|
||||
// 长度上限(users.account 列宽 64 由入库侧保证,超长账号查无此人不构成枚举面)。
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class LoginRequestDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
account!: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
password!: string;
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// services/api/src/auth/session.guard.ts —— Bearer 会话守卫(Task 13,规范化守卫)。
|
||||
// 解析 Authorization: Bearer <token> → sha256 查 sessions(users.level: include)
|
||||
// → 校验未撤销 / 未过期 / 用户仍具资格(credentialStatus=active 且 !localLocked
|
||||
// 且 sourceStatus!=disabled——技术文档「停用账号撤销会话」在守卫层落实:
|
||||
// 账号一旦停用,其既有令牌即刻失效,无需等过期)→ 挂载 req.user / req.sessionId。
|
||||
// 全部失败路径(头缺失/格式错/查无会话/已撤销/已过期/资格不符)抛同一
|
||||
// ApiException(AUTH_TOKEN_EXPIRED):同一状态码 + 同一文案,不向调用方泄露失败原因。
|
||||
// 使用方式:@UseGuards(SessionGuard)(按控制器/路由启用,不注册 APP_GUARD)。
|
||||
// 守卫只依赖 @Global 的 PrismaService,任意模块可直接引用,无需 import AuthModule。
|
||||
import { createHash } from 'node:crypto';
|
||||
import {
|
||||
type CanActivate,
|
||||
type ExecutionContext,
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import type { IncomingMessage } from 'node:http';
|
||||
import { ErrorCodes } from '@photo/contracts';
|
||||
import { ApiException } from '../api-exception';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type { RequestWithId } from '../shared/request-with-id';
|
||||
|
||||
/** 守卫挂载后的请求用户信息(后续业务模块经 req.user 读取的规范形状)。 */
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
account: string;
|
||||
/** staff|admin(公司角色;相册角色由 album_members 承载,不进会话)。 */
|
||||
role: string;
|
||||
locale: string | null;
|
||||
}
|
||||
|
||||
/** 经 SessionGuard 放行后的请求(组合而非继承,同 request-with-id.ts 的约定)。 */
|
||||
export interface AuthenticatedRequest extends RequestWithId {
|
||||
user?: AuthUser;
|
||||
/** 守卫命中的会话行 id:refresh/logout 需要定位会话本体(令牌本身不外传到业务层)。 */
|
||||
sessionId?: string;
|
||||
headers: IncomingMessage['headers'];
|
||||
}
|
||||
|
||||
/** 令牌 → 库内存储哈希。32B hex 令牌的 sha256 hex 恰为 64 字符,合 tokenHash 列宽。 */
|
||||
export function hashSessionToken(token: string): string {
|
||||
return createHash('sha256').update(token).digest('hex');
|
||||
}
|
||||
|
||||
function tokenInvalid(): ApiException {
|
||||
return new ApiException(
|
||||
ErrorCodes.AUTH_TOKEN_EXPIRED,
|
||||
'Session token is missing, invalid, or expired',
|
||||
HttpStatus.UNAUTHORIZED,
|
||||
);
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SessionGuard implements CanActivate {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req =
|
||||
context.switchToHttp().getRequest<AuthenticatedRequest>();
|
||||
|
||||
const header = req.headers.authorization;
|
||||
if (typeof header !== 'string' || !header.startsWith('Bearer ')) {
|
||||
throw tokenInvalid();
|
||||
}
|
||||
const token = header.slice('Bearer '.length).trim();
|
||||
if (token === '') {
|
||||
throw tokenInvalid();
|
||||
}
|
||||
|
||||
const session = await this.prisma.sessions.findUnique({
|
||||
where: { tokenHash: hashSessionToken(token) },
|
||||
include: { user: true },
|
||||
});
|
||||
if (session === null) {
|
||||
throw tokenInvalid();
|
||||
}
|
||||
if (session.revokedAt !== null || session.expiresAt.getTime() <= Date.now()) {
|
||||
throw tokenInvalid();
|
||||
}
|
||||
|
||||
const { user } = session;
|
||||
if (
|
||||
user.credentialStatus !== 'active' ||
|
||||
user.localLocked ||
|
||||
user.sourceStatus === 'disabled'
|
||||
) {
|
||||
throw tokenInvalid();
|
||||
}
|
||||
|
||||
req.user = {
|
||||
id: user.id,
|
||||
account: user.account,
|
||||
role: user.role,
|
||||
locale: user.locale,
|
||||
};
|
||||
req.sessionId = session.id;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
// services/api/test/auth.e2e-spec.ts —— Task 13 登录/刷新/注销 e2e(先写后实现)。
|
||||
// 真实 app + MySQL(reset.ts 隔离,用户经 Prisma 直种)。覆盖:
|
||||
// 成功登录(令牌形状 / TTL / audit_logs / sessions.tokenHash)、
|
||||
// 凭据错误的三种 401 归并(错误密码 / 账号不存在 / 状态不合格——同码防枚举)、
|
||||
// 滑动续期(同令牌不轮换、过期时间前移)、垃圾/缺失令牌 401、
|
||||
// 注销 204 + 令牌即刻失效 + sessions.revokedAt、
|
||||
// 账号被停用后既有会话被守卫撤销、
|
||||
// 登录失败限速(第 6 次 429 AUTH_RATE_LIMITED;成功登录清零计数)、
|
||||
// DTO 校验 400 VALIDATION_FAILED(全局校验管道)。
|
||||
// 限速计数在 app 实例内存中跨用例存留——各限速用例使用独立账号,避免相互污染;
|
||||
// alice 在首个用例失败 1 次后由成功登录清零,后续用例不受影响。
|
||||
import { createHash } from 'node:crypto';
|
||||
import { type INestApplication } from '@nestjs/common';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import request from 'supertest';
|
||||
import { PrismaClient } from '@photo/db-cn';
|
||||
import { ErrorCodes } from '@photo/contracts';
|
||||
import { AppCnModule } from '../src/app-cn.module';
|
||||
import { hashPassword } from '../src/auth/password';
|
||||
import { API_PREFIX } from '../src/shared/constants';
|
||||
import { resetDb } from './reset';
|
||||
|
||||
const TTL_SECONDS = Number.parseInt(
|
||||
process.env.AUTH_SESSION_TTL_SECONDS ?? '2592000',
|
||||
10,
|
||||
);
|
||||
/** 断言容差:登录/续期到响应到达之间的真实耗时(本机 e2e 足够)。 */
|
||||
const TTL_TOLERANCE_MS = 120_000;
|
||||
|
||||
function sha256Hex(value: string): string {
|
||||
return createHash('sha256').update(value).digest('hex');
|
||||
}
|
||||
|
||||
describe('auth (e2e)', () => {
|
||||
let app: INestApplication;
|
||||
let prisma: PrismaClient;
|
||||
let aliceId: string;
|
||||
|
||||
const PASSWORD = 'correct-pass-1';
|
||||
|
||||
beforeAll(async () => {
|
||||
await resetDb();
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [AppCnModule],
|
||||
}).compile();
|
||||
app = moduleRef.createNestApplication();
|
||||
app.setGlobalPrefix(API_PREFIX);
|
||||
await app.init();
|
||||
|
||||
prisma = new PrismaClient();
|
||||
const hash = await hashPassword(PASSWORD);
|
||||
aliceId = (
|
||||
await prisma.users.create({
|
||||
data: { account: 'alice', passwordHash: hash, displayName: 'Alice' },
|
||||
select: { id: true },
|
||||
})
|
||||
).id;
|
||||
// 状态不合格三态:停用 / 本地锁定 / 凭据待激活(A01 未激活无法进入)。
|
||||
await prisma.users.create({
|
||||
data: {
|
||||
account: 'bob',
|
||||
passwordHash: hash,
|
||||
displayName: 'Bob',
|
||||
sourceStatus: 'disabled',
|
||||
},
|
||||
});
|
||||
await prisma.users.create({
|
||||
data: {
|
||||
account: 'carol',
|
||||
passwordHash: hash,
|
||||
displayName: 'Carol',
|
||||
localLocked: true,
|
||||
},
|
||||
});
|
||||
await prisma.users.create({
|
||||
data: {
|
||||
account: 'dave',
|
||||
passwordHash: hash,
|
||||
displayName: 'Dave',
|
||||
credentialStatus: 'pending',
|
||||
},
|
||||
});
|
||||
// 限速专用账号(与其它用例隔离,避免内存计数交叉污染)。
|
||||
await prisma.users.create({
|
||||
data: { account: 'erin', passwordHash: hash, displayName: 'Erin' },
|
||||
});
|
||||
await prisma.users.create({
|
||||
data: { account: 'frank', passwordHash: hash, displayName: 'Frank' },
|
||||
});
|
||||
// 会话撤销语义专用账号(测试内会被置为 disabled,不复用其它账号)。
|
||||
await prisma.users.create({
|
||||
data: { account: 'gina', passwordHash: hash, displayName: 'Gina' },
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
function login(account: string, password: string) {
|
||||
return request(app.getHttpServer())
|
||||
.post(`/${API_PREFIX}/auth/password`)
|
||||
.send({ account, password });
|
||||
}
|
||||
|
||||
it('正确账号密码 → 200 {sessionToken, expiresAt≈now+TTL},tokenHash=sha256(token),且写 audit_logs(auth.login)', async () => {
|
||||
const before = Date.now();
|
||||
const res = await login('alice', PASSWORD);
|
||||
expect(res.status).toBe(200);
|
||||
expect(Object.keys(res.body).sort()).toEqual(['expiresAt', 'sessionToken']);
|
||||
|
||||
const { sessionToken, expiresAt } = res.body as {
|
||||
sessionToken: string;
|
||||
expiresAt: string;
|
||||
};
|
||||
// 32B 随机数的 hex 编码。
|
||||
expect(sessionToken).toMatch(/^[0-9a-f]{64}$/);
|
||||
|
||||
const expiresMs = Date.parse(expiresAt);
|
||||
const lower = before + TTL_SECONDS * 1000 - TTL_TOLERANCE_MS;
|
||||
const upper = before + TTL_SECONDS * 1000 + TTL_TOLERANCE_MS;
|
||||
expect(expiresMs).toBeGreaterThanOrEqual(lower);
|
||||
expect(expiresMs).toBeLessThanOrEqual(upper);
|
||||
|
||||
// 库内只存哈希;明文令牌不落库。
|
||||
const session = await prisma.sessions.findUnique({
|
||||
where: { tokenHash: sha256Hex(sessionToken) },
|
||||
});
|
||||
expect(session).not.toBeNull();
|
||||
expect(session?.userId).toBe(aliceId);
|
||||
expect(session?.revokedAt).toBeNull();
|
||||
|
||||
const audit = await prisma.audit_logs.findFirst({
|
||||
where: { action: 'auth.login', actorId: aliceId },
|
||||
});
|
||||
expect(audit).not.toBeNull();
|
||||
});
|
||||
|
||||
it('错误密码 → 401 AUTH_INVALID_CREDENTIALS', async () => {
|
||||
const res = await login('alice', 'wrong-password');
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.body.code).toBe(ErrorCodes.AUTH_INVALID_CREDENTIALS);
|
||||
expect(typeof res.body.requestId).toBe('string');
|
||||
});
|
||||
|
||||
it('不存在的账号 → 401 同一错误码(防账号枚举)', async () => {
|
||||
const res = await login('ghost-account', 'whatever');
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.body.code).toBe(ErrorCodes.AUTH_INVALID_CREDENTIALS);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['sourceStatus=disabled', 'bob'],
|
||||
['localLocked=true', 'carol'],
|
||||
['credentialStatus=pending(A01 未激活)', 'dave'],
|
||||
])('%s → 401 同一错误码(正确密码也不放行)', async (_label, account) => {
|
||||
const res = await login(account as string, PASSWORD);
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.body.code).toBe(ErrorCodes.AUTH_INVALID_CREDENTIALS);
|
||||
});
|
||||
|
||||
it('请求体缺 password → 400 VALIDATION_FAILED(全局校验管道)', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.post(`/${API_PREFIX}/auth/password`)
|
||||
.send({ account: 'alice' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.code).toBe(ErrorCodes.VALIDATION_FAILED);
|
||||
});
|
||||
|
||||
it('滑动续期:有效令牌 → 200 {expiresAt} 前移,且旧令牌仍可用(不轮换)', async () => {
|
||||
const loginRes = await login('alice', PASSWORD);
|
||||
const token: string = loginRes.body.sessionToken;
|
||||
const originalExpires: number = Date.parse(loginRes.body.expiresAt);
|
||||
|
||||
// 把会话过期时间手工缩短到即将过期,续期后应回到 ~now+TTL(前移可观测)。
|
||||
await prisma.sessions.update({
|
||||
where: { tokenHash: sha256Hex(token) },
|
||||
data: { expiresAt: new Date(Date.now() + 60_000) },
|
||||
});
|
||||
|
||||
const before = Date.now();
|
||||
const res = await request(app.getHttpServer())
|
||||
.post(`/${API_PREFIX}/auth/refresh`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(Object.keys(res.body)).toEqual(['expiresAt']);
|
||||
|
||||
const renewedMs = Date.parse(res.body.expiresAt);
|
||||
expect(renewedMs).toBeGreaterThan(originalExpires);
|
||||
expect(renewedMs).toBeGreaterThanOrEqual(
|
||||
before + TTL_SECONDS * 1000 - TTL_TOLERANCE_MS,
|
||||
);
|
||||
expect(renewedMs).toBeLessThanOrEqual(
|
||||
before + TTL_SECONDS * 1000 + TTL_TOLERANCE_MS,
|
||||
);
|
||||
|
||||
// 不轮换:同一令牌再次续期仍 200(若实现为轮换,旧令牌应已失效)。
|
||||
const again = await request(app.getHttpServer())
|
||||
.post(`/${API_PREFIX}/auth/refresh`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
expect(again.status).toBe(200);
|
||||
});
|
||||
|
||||
it('续期携带垃圾令牌 → 401 AUTH_TOKEN_EXPIRED', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.post(`/${API_PREFIX}/auth/refresh`)
|
||||
.set('Authorization', 'Bearer not-a-real-token');
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.body.code).toBe(ErrorCodes.AUTH_TOKEN_EXPIRED);
|
||||
});
|
||||
|
||||
it('续期缺失 Authorization 头 → 401 AUTH_TOKEN_EXPIRED', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.post(`/${API_PREFIX}/auth/refresh`);
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.body.code).toBe(ErrorCodes.AUTH_TOKEN_EXPIRED);
|
||||
});
|
||||
|
||||
it('注销 → 204 无响应体;同令牌后续受保护请求 401;sessions.revokedAt 落库', async () => {
|
||||
const loginRes = await login('alice', PASSWORD);
|
||||
const token: string = loginRes.body.sessionToken;
|
||||
|
||||
const logout = await request(app.getHttpServer())
|
||||
.post(`/${API_PREFIX}/auth/logout`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
expect(logout.status).toBe(204);
|
||||
expect(logout.body).toEqual({});
|
||||
|
||||
const after = await request(app.getHttpServer())
|
||||
.post(`/${API_PREFIX}/auth/refresh`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
expect(after.status).toBe(401);
|
||||
expect(after.body.code).toBe(ErrorCodes.AUTH_TOKEN_EXPIRED);
|
||||
|
||||
const session = await prisma.sessions.findUnique({
|
||||
where: { tokenHash: sha256Hex(token) },
|
||||
select: { revokedAt: true },
|
||||
});
|
||||
expect(session?.revokedAt).not.toBeNull();
|
||||
});
|
||||
|
||||
it('账号被停用后,既有会话被守卫拒绝(撤销语义)', async () => {
|
||||
const res = await login('gina', PASSWORD);
|
||||
expect(res.status).toBe(200);
|
||||
const token: string = res.body.sessionToken;
|
||||
|
||||
await prisma.users.update({
|
||||
where: { account: 'gina' },
|
||||
data: { sourceStatus: 'disabled' },
|
||||
});
|
||||
|
||||
const refresh = await request(app.getHttpServer())
|
||||
.post(`/${API_PREFIX}/auth/refresh`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
expect(refresh.status).toBe(401);
|
||||
expect(refresh.body.code).toBe(ErrorCodes.AUTH_TOKEN_EXPIRED);
|
||||
});
|
||||
|
||||
it('限速:同账号连续 5 次失败后,第 6 次(即使密码正确)→ 429 AUTH_RATE_LIMITED', async () => {
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const res = await login('erin', 'wrong-password');
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.body.code).toBe(ErrorCodes.AUTH_INVALID_CREDENTIALS);
|
||||
}
|
||||
const locked = await login('erin', PASSWORD);
|
||||
expect(locked.status).toBe(429);
|
||||
expect(locked.body.code).toBe(ErrorCodes.AUTH_RATE_LIMITED);
|
||||
});
|
||||
|
||||
it('限速:成功登录清零失败计数(4 次失败 + 成功 + 再失败仍是 401 而非 429)', async () => {
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const res = await login('frank', 'wrong-password');
|
||||
expect(res.status).toBe(401);
|
||||
}
|
||||
const ok = await login('frank', PASSWORD);
|
||||
expect(ok.status).toBe(200);
|
||||
|
||||
const res = await login('frank', 'wrong-password');
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.body.code).toBe(ErrorCodes.AUTH_INVALID_CREDENTIALS);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user