chore(api): p1a final-review hygiene items

- contracts: add NOT_FOUND error code (framework-level 404 for unknown
  routes); Error enum + regen committed
- api: 404 default mapping in AllExceptionsFilter now NOT_FOUND (was
  ALBUM_NOT_FOUND); business 404s unchanged via explicit ApiException codes
- api: extract configureApp (prefix/CORS/x-powered-by) shared by main-cn
  bootstrap and e2e; disable x-powered-by, asserted in e2e
- api: move parseCursor/parseLimit (+page-size bounds) from
  albums.controller to shared/pagination; members/uploads/public re-pointed
- infra: bind compose published ports to 127.0.0.1 (mysql/redis/minio);
  .env.example endpoints follow suit
- e2e: unknown-route 404 NOT_FOUND + x-powered-by absent cases added
  (api e2e 120 -> 122)

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
浅念
2026-09-18 08:18:30 +08:00
parent 62382eca3c
commit 47fb81ad31
16 changed files with 137 additions and 83 deletions
+3 -3
View File
@@ -1,6 +1,6 @@
DATABASE_URL_CN=mysql://root:root@localhost:3306/photo_cn?connection_limit=10
REDIS_URL_CN=redis://localhost:6379
S3_ENDPOINT=http://localhost:9000
DATABASE_URL_CN=mysql://root:root@127.0.0.1:3306/photo_cn?connection_limit=10
REDIS_URL_CN=redis://127.0.0.1:6379
S3_ENDPOINT=http://127.0.0.1:9000
S3_REGION=us-east-1
S3_ACCESS_KEY=photo-dev
S3_SECRET_KEY=photo-dev-secret
+3 -3
View File
@@ -7,7 +7,7 @@ services:
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: photo_cn
ports: ["3306:3306"]
ports: ["127.0.0.1:3306:3306"]
volumes: [mysql-cn-data:/var/lib/mysql]
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-uroot", "-proot"]
@@ -15,7 +15,7 @@ services:
retries: 12
redis-cn:
image: redis:7-alpine
ports: ["6379:6379"]
ports: ["127.0.0.1:6379:6379"]
healthcheck: { test: ["CMD", "redis-cli", "ping"], interval: 5s, retries: 12 }
minio:
image: quay.io/minio/minio:latest
@@ -23,7 +23,7 @@ services:
environment:
MINIO_ROOT_USER: photo-dev
MINIO_ROOT_PASSWORD: photo-dev-secret
ports: ["9000:9000", "9001:9001"]
ports: ["127.0.0.1:9000:9000", "127.0.0.1:9001:9001"]
volumes: [minio-data:/data]
minio-init:
image: quay.io/minio/mc:latest
+1
View File
@@ -977,6 +977,7 @@ components:
- AUTH_TOKEN_EXPIRED
- AUTH_RATE_LIMITED
- AUTH_FORBIDDEN
- NOT_FOUND
- ALBUM_NOT_FOUND
- ALBUM_NOT_PUBLIC
- ALBUM_UPLOAD_DISABLED
+5
View File
@@ -7,6 +7,11 @@ export const ErrorCodes = {
// 复用 VALIDATION_FAILED 则语义错位。与 openapi.yaml Error enum 同步增补。
AUTH_RATE_LIMITED: 'AUTH_RATE_LIMITED',
AUTH_FORBIDDEN: 'AUTH_FORBIDDEN',
// P1a 终审修缮①(P1b Task 1 补登):框架级 404(未注册路由等)此前兜底映射
// ALBUM_NOT_FOUND,语义错位。业务 404 一律经 ApiException 显式携带域码;
// NOT_FOUND 仅代表"框架/路由层面的资源不存在"。与 openapi.yaml Error enum
// 同步增补。
NOT_FOUND: 'NOT_FOUND',
ALBUM_NOT_FOUND: 'ALBUM_NOT_FOUND',
ALBUM_NOT_PUBLIC: 'ALBUM_NOT_PUBLIC',
ALBUM_UPLOAD_DISABLED: 'ALBUM_UPLOAD_DISABLED',
+1 -1
View File
@@ -404,7 +404,7 @@ export interface components {
* @description 稳定错误码,与 src/errors.ts 的 ErrorCodes 一一对应。
* @enum {string}
*/
readonly code: "AUTH_INVALID_CREDENTIALS" | "AUTH_TOKEN_EXPIRED" | "AUTH_RATE_LIMITED" | "AUTH_FORBIDDEN" | "ALBUM_NOT_FOUND" | "ALBUM_NOT_PUBLIC" | "ALBUM_UPLOAD_DISABLED" | "MEMBER_CONFLICT" | "UPLOAD_SESSION_CONFLICT" | "UPLOAD_VERIFY_FAILED" | "PHOTO_NOT_FOUND" | "PHOTO_NOT_PUBLIC" | "VALIDATION_FAILED" | "INTERNAL_ERROR";
readonly code: "AUTH_INVALID_CREDENTIALS" | "AUTH_TOKEN_EXPIRED" | "AUTH_RATE_LIMITED" | "AUTH_FORBIDDEN" | "NOT_FOUND" | "ALBUM_NOT_FOUND" | "ALBUM_NOT_PUBLIC" | "ALBUM_UPLOAD_DISABLED" | "MEMBER_CONFLICT" | "UPLOAD_SESSION_CONFLICT" | "UPLOAD_VERIFY_FAILED" | "PHOTO_NOT_FOUND" | "PHOTO_NOT_PUBLIC" | "VALIDATION_FAILED" | "INTERNAL_ERROR";
/** @description 服务器生成的可读消息(诊断用,不作为客户端展示文案依据)。 */
readonly message: string;
/** @description 请求追踪 ID。 */
+4 -46
View File
@@ -3,8 +3,8 @@
// listAlbums/getAlbum/updateAlbum)。控制器级 SessionGuard:四端点全需认证
// (契约均有 bearerAuth、无 security: [] 例外)。职责仅剩:
// · 透传认证用户(req.user,守卫挂载);
// · 查询参数规整(limit 1..100 整数、cursor 长度),非法 → 400
// VALIDATION_FAILED,与 body 校验同一出口;
// · 查询参数规整(limit 1..100 整数、cursor 长度)经 shared/pagination
// (P1a 终审修缮③迁出本控制器),非法 → 400 VALIDATION_FAILED;
// · 权限/可见性→HTTP 映射交由服务层抛 ApiException(404 ALBUM_NOT_FOUND)。
import {
Body,
@@ -22,19 +22,17 @@ import { ErrorCodes } from '@photo/contracts';
import { ApiException } from '../api-exception';
import type { AuthUser } from '../auth/session.guard';
import { AuthenticatedRequest, SessionGuard } from '../auth/session.guard';
import { parseCursor, parseLimit } from '../shared/pagination';
import {
DEFAULT_ALBUM_PAGE_SIZE,
MAX_ALBUM_PAGE_SIZE,
type AlbumListResponse,
type AlbumResponse,
AlbumsService,
} from './albums.service';
import { AlbumCreateRequestDto, AlbumUpdateRequestDto } from './dto';
import { MAX_CURSOR_LENGTH } from '../shared/cursor';
/**
* 守卫放行后提取 req.user;防御性兜底(守卫未挂载属装配错误,按未认证拒绝)。
* members/categories 控制器(Task 17)复用同一判定,导出。
* members/categories/photos/uploads 控制器复用同一判定,导出。
*/
export function userOf(req: AuthenticatedRequest): AuthUser {
if (req.user === undefined) {
@@ -47,46 +45,6 @@ export function userOf(req: AuthenticatedRequest): AuthUser {
return req.user;
}
/** limit 查询参数:缺省 20,须为 1..100 的十进制整数(契约 bounds)。导出供
* members 列表(Task 17,同契约 bounds)复用。 */
export function parseLimit(raw: string | undefined): number {
if (raw === undefined || raw === '') {
return DEFAULT_ALBUM_PAGE_SIZE;
}
if (!/^\d+$/.test(raw)) {
throw new ApiException(
ErrorCodes.VALIDATION_FAILED,
'limit 必须是 1-100 的整数',
HttpStatus.BAD_REQUEST,
);
}
const limit = Number.parseInt(raw, 10);
if (limit < 1 || limit > MAX_ALBUM_PAGE_SIZE) {
throw new ApiException(
ErrorCodes.VALIDATION_FAILED,
'limit 必须是 1-100 的整数',
HttpStatus.BAD_REQUEST,
);
}
return limit;
}
/** cursor 查询参数:仅做长度规整(语义校验在服务层解码时);导出供 members
* 列表(Task 17)复用。 */
export function parseCursor(raw: string | undefined): string | undefined {
if (raw === undefined || raw === '') {
return undefined;
}
if (raw.length > MAX_CURSOR_LENGTH) {
throw new ApiException(
ErrorCodes.VALIDATION_FAILED,
'cursor 不合法',
HttpStatus.BAD_REQUEST,
);
}
return raw;
}
@Controller('albums')
@UseGuards(SessionGuard)
export class AlbumsController {
@@ -42,10 +42,6 @@ export type AlbumSummaryResponse = components['schemas']['AlbumSummary'];
export type AlbumResponse = components['schemas']['Album'];
export type AlbumListResponse = components['schemas']['AlbumList'];
/** 契约 listAlbums:limit 缺省 20,上下界 1..100。 */
export const DEFAULT_ALBUM_PAGE_SIZE = 20;
export const MAX_ALBUM_PAGE_SIZE = 100;
const PUBLIC_TOKEN_LENGTH = 24;
const PUBLIC_TOKEN_ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
@@ -1,7 +1,7 @@
// services/api/src/albums/members.controller.ts —— /albums/{albumId}/members
// 端点(Task 17)。方法名与契约 operationId 一一对应(addAlbumMember/
// listAlbumMembers/removeAlbumMember)。控制器级 SessionGuard:三端点全需
// 认证。控制器只做认证用户透传 + 查询参数规整(复用 albums.controller 的
// 认证。控制器只做认证用户透传 + 查询参数规整(shared/pagination 的
// parseLimit/parseCursor,同一契约 bounds/游标语义);权限与 HTTP 映射由
// MembersService 抛 ApiException(404 ALBUM_NOT_FOUND / 403 AUTH_FORBIDDEN /
// 409 MEMBER_CONFLICT)。
@@ -19,7 +19,8 @@ import {
UseGuards,
} from '@nestjs/common';
import { AuthenticatedRequest, SessionGuard } from '../auth/session.guard';
import { parseCursor, parseLimit, userOf } from './albums.controller';
import { userOf } from './albums.controller';
import { parseCursor, parseLimit } from '../shared/pagination';
import { MemberAddRequestDto } from './dto';
import {
type MemberListResponse,
@@ -51,7 +51,7 @@ describe('AllExceptionsFilter', () => {
[new BadRequestException('title is required'), HttpStatus.BAD_REQUEST, ErrorCodes.VALIDATION_FAILED],
[new UnauthorizedException(), HttpStatus.UNAUTHORIZED, ErrorCodes.AUTH_TOKEN_EXPIRED],
[new ForbiddenException(), HttpStatus.FORBIDDEN, ErrorCodes.AUTH_FORBIDDEN],
[new NotFoundException('album'), HttpStatus.NOT_FOUND, ErrorCodes.ALBUM_NOT_FOUND],
[new NotFoundException('route'), HttpStatus.NOT_FOUND, ErrorCodes.NOT_FOUND],
])('maps HttpException %p to status %i / code %s', (exception, status, code) => {
const captured = runFilter(exception, 'req-1');
expect(captured.status).toBe(status);
+4 -1
View File
@@ -28,7 +28,10 @@ const STATUS_TO_ERROR_CODE: Readonly<Record<number, ErrorCode>> = {
[HttpStatus.BAD_REQUEST]: ErrorCodes.VALIDATION_FAILED,
[HttpStatus.UNAUTHORIZED]: ErrorCodes.AUTH_TOKEN_EXPIRED,
[HttpStatus.FORBIDDEN]: ErrorCodes.AUTH_FORBIDDEN,
[HttpStatus.NOT_FOUND]: ErrorCodes.ALBUM_NOT_FOUND,
// 框架级 404(未注册路由):NOT_FOUND。业务 404(相册/照片不存在等)全部经
// ApiException 显式携带域码(ALBUM_NOT_FOUND 等),不走本兜底行——P1a 终审
// 修缮①:此前默认 ALBUM_NOT_FOUND 让未知路由冒充业务错误。
[HttpStatus.NOT_FOUND]: ErrorCodes.NOT_FOUND,
};
const GENERIC_INTERNAL_MESSAGE = 'Internal server error';
+4 -9
View File
@@ -2,23 +2,18 @@
// cn-app 部署入口(P1a 仅此一个 API 入口)。构建产物 dist/main-cn.js 由根 dev:api /
// 生产启动命令运行;env 一律来自进程环境(根 dotenv-cli 注入),此处不读文件。
import 'reflect-metadata';
import { type INestApplication } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { type NestExpressApplication } from '@nestjs/platform-express';
import { Logger } from 'nestjs-pino';
import { AppCnModule } from './app-cn.module';
import { API_PREFIX } from './shared/constants';
import { configureApp } from './shared/configure-app';
async function bootstrap(): Promise<void> {
const app = await NestFactory.create<INestApplication>(AppCnModule, {
const app = await NestFactory.create<NestExpressApplication>(AppCnModule, {
bufferLogs: true,
});
app.useLogger(app.get(Logger));
app.setGlobalPrefix(API_PREFIX);
const corsOrigins = (process.env.CORS_ORIGINS ?? 'http://localhost:5173')
.split(',')
.map((origin) => origin.trim())
.filter((origin) => origin !== '');
app.enableCors({ origin: corsOrigins });
configureApp(app);
const port = Number.parseInt(process.env.PORT ?? '', 10) || 8080;
await app.listen(port);
app.get(Logger).log(`api-cn listening on port ${port}`);
+1 -1
View File
@@ -16,7 +16,7 @@ import {
} from '@nestjs/common';
import { ErrorCodes } from '@photo/contracts';
import { ApiException } from '../api-exception';
import { parseCursor } from '../albums/albums.controller';
import { parseCursor } from '../shared/pagination';
import {
DEFAULT_PUBLIC_PHOTO_PAGE_SIZE,
MAX_PUBLIC_PHOTO_PAGE_SIZE,
+18
View File
@@ -0,0 +1,18 @@
// services/api/src/shared/configure-app.ts —— 应用级配置(全局前缀 / CORS /
// 响应头),main-cn.ts 生产引导与 e2e 测试装配共用同一函数:此前 e2e 各 spec
// 手工镜像 setGlobalPrefix,两处漂移无从守护;收敛为单一来源后,e2e 对
// x-powered-by 头的断言才真正落在生产引导路径上(P1a 终审修缮②)。
// 参数类型取 NestExpressApplication:disable() 是 Express 适配器特有方法。
import type { NestExpressApplication } from '@nestjs/platform-express';
import { API_PREFIX } from './constants';
export function configureApp(app: NestExpressApplication): void {
app.setGlobalPrefix(API_PREFIX);
// 隐藏 Express x-powered-by 指纹响应头(终审修缮②,e2e 断言之)。
app.disable('x-powered-by');
const corsOrigins = (process.env.CORS_ORIGINS ?? 'http://localhost:5173')
.split(',')
.map((origin) => origin.trim())
.filter((origin) => origin !== '');
app.enableCors({ origin: corsOrigins });
}
+57
View File
@@ -0,0 +1,57 @@
// services/api/src/shared/pagination.ts —— 列表查询参数规整(limit/cursor)。
// P1a 终审修缮③:自 albums.controller 迁入 shared——members/uploads/public 与
// albums 共用同一契约 bounds,工具函数不再寄居相册控制器导出。语义零变化:
// · limit:缺省 20,须为 1..100 的十进制整数,非法 → 400 VALIDATION_FAILED
// (与 body 校验同一出口);
// · cursor:仅长度上限规整(≤512,契约 CursorQuery.maxLength),语义校验在
// 服务层解码处(shared/cursor.ts)。
// 公开照片列表 bounds 不同(1..60 缺省 30),其 parsePublicPhotoLimit 仍在
// public.controller 本地维护,勿混用。
import { HttpStatus } from '@nestjs/common';
import { ErrorCodes } from '@photo/contracts';
import { ApiException } from '../api-exception';
import { MAX_CURSOR_LENGTH } from './cursor';
/** 列表 limit 缺省值(albums/members/uploads 各列表契约共用 bounds)。 */
export const DEFAULT_PAGE_SIZE = 20;
/** 列表 limit 上界(1..100,同上)。 */
export const MAX_PAGE_SIZE = 100;
/** limit 查询参数:缺省 20,须为 1..100 的十进制整数(契约 bounds)。 */
export function parseLimit(raw: string | undefined): number {
if (raw === undefined || raw === '') {
return DEFAULT_PAGE_SIZE;
}
if (!/^\d+$/.test(raw)) {
throw new ApiException(
ErrorCodes.VALIDATION_FAILED,
'limit 必须是 1-100 的整数',
HttpStatus.BAD_REQUEST,
);
}
const limit = Number.parseInt(raw, 10);
if (limit < 1 || limit > MAX_PAGE_SIZE) {
throw new ApiException(
ErrorCodes.VALIDATION_FAILED,
'limit 必须是 1-100 的整数',
HttpStatus.BAD_REQUEST,
);
}
return limit;
}
/** cursor 查询参数:仅做长度规整(语义校验在服务层解码时)。 */
export function parseCursor(raw: string | undefined): string | undefined {
if (raw === undefined || raw === '') {
return undefined;
}
if (raw.length > MAX_CURSOR_LENGTH) {
throw new ApiException(
ErrorCodes.VALIDATION_FAILED,
'cursor 不合法',
HttpStatus.BAD_REQUEST,
);
}
return raw;
}
@@ -1,7 +1,7 @@
// services/api/src/uploads/uploads.controller.ts —— /uploads 端点(Task 18 起;
// Task 19 增补 listUploads/renewUploadCredential/completeUpload)。方法名与契约
// operationId 一一对应。控制器级 SessionGuard:端点全需认证。职责:透传认证
// 用户 + 查询参数规整(parseLimit/parseCursor 复用相册控制器导出,同契约 bounds)。
// 用户 + 查询参数规整(parseLimit/parseCursor 用 shared/pagination,同契约 bounds)。
// 注意 DTO 必须值导入(非 import type):@Body 参数类型经 emitDecoratorMetadata
// 进入设计期元数据,import type 会令参数在管线中被置为 undefined(Task 18 实测)。
import {
@@ -16,11 +16,8 @@ import {
Req,
UseGuards,
} from '@nestjs/common';
import {
parseCursor,
parseLimit,
userOf,
} from '../albums/albums.controller';
import { userOf } from '../albums/albums.controller';
import { parseCursor, parseLimit } from '../shared/pagination';
import { AuthenticatedRequest, SessionGuard } from '../auth/session.guard';
import { UploadsService } from './uploads.service';
import type {
+29 -6
View File
@@ -1,24 +1,30 @@
// services/api/test/health.e2e-spec.ts
// e2e 冒烟:验证 e2e 工装(Nest testing module + supertest + 根 .env 加载)可用。
// 不监听端口:app.init() 后直接对 app.getHttpServer() 发请求。
// 全局前缀与 main-cn.ts 共用 src/shared/constants 的 API_PREFIX(Task 7 遗留项⑥)。
import { type INestApplication } from '@nestjs/common';
// 应用级配置与 main-cn.ts 共用 src/shared/configure-app(P1a 终审修缮后收敛为
// 单一来源),故本 spec 对响应头/未知路由的断言即生产引导路径的行为:
// · /health 基本形状 + x-request-id 回显/生成/超长替换;
// · 未注册路由 → 404 信封 code=NOT_FOUND(终审修缮①:框架级 404 不再冒充
// ALBUM_NOT_FOUND;业务 404 一律经 ApiException 显式携带域码);
// · 响应不暴露 x-powered-by 指纹头(终审修缮②)。
import { Test } from '@nestjs/testing';
import { type NestExpressApplication } from '@nestjs/platform-express';
import request from 'supertest';
import { AppCnModule } from '../src/app-cn.module';
import { API_PREFIX } from '../src/shared/constants';
import { configureApp } from '../src/shared/configure-app';
import { resetDb } from './reset';
describe(`GET /${API_PREFIX}/health (e2e)`, () => {
let app: INestApplication;
describe(`e2e smoke: /${API_PREFIX}/health & framework defaults`, () => {
let app: NestExpressApplication;
beforeAll(async () => {
await resetDb();
const moduleRef = await Test.createTestingModule({
imports: [AppCnModule],
}).compile();
app = moduleRef.createNestApplication();
app.setGlobalPrefix(API_PREFIX);
app = moduleRef.createNestApplication<NestExpressApplication>();
configureApp(app);
await app.init();
});
@@ -56,4 +62,21 @@ describe(`GET /${API_PREFIX}/health (e2e)`, () => {
expect(requestId).not.toBe(overlong);
expect((requestId as string).length).toBeLessThanOrEqual(128);
});
it('responds 404 error envelope with code NOT_FOUND for unknown routes', async () => {
const res = await request(app.getHttpServer()).get(
`/${API_PREFIX}/nonexistent-route`,
);
expect(res.status).toBe(404);
expect(res.body).toMatchObject({
code: 'NOT_FOUND',
requestId: expect.any(String) as string,
});
expect(typeof res.body.message).toBe('string');
});
it('omits the x-powered-by response header', async () => {
const res = await request(app.getHttpServer()).get(`/${API_PREFIX}/health`);
expect(res.headers['x-powered-by']).toBeUndefined();
});
});