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:
浅念
2026-09-17 21:17:16 +08:00
parent 368b1d5b47
commit 39cae26106
12 changed files with 803 additions and 26 deletions
+25 -7
View File
@@ -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 {
+70
View File
@@ -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));
}
}
+15
View File
@@ -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 {}
+209
View File
@@ -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() },
});
}
}
+17
View File
@@ -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;
}
+99
View File
@@ -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;
}
}