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:
@@ -74,6 +74,14 @@ paths:
|
|||||||
application/json:
|
application/json:
|
||||||
schema:
|
schema:
|
||||||
$ref: '#/components/schemas/Error'
|
$ref: '#/components/schemas/Error'
|
||||||
|
'429':
|
||||||
|
description: |
|
||||||
|
登录失败次数过多(AUTH_RATE_LIMITED,Task 13 契约修订)。
|
||||||
|
同账号+来源 IP 在窗口期内连续失败达到阈值后锁定一段时间。
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/Error'
|
||||||
'500':
|
'500':
|
||||||
$ref: '#/components/responses/InternalError'
|
$ref: '#/components/responses/InternalError'
|
||||||
|
|
||||||
@@ -967,6 +975,7 @@ components:
|
|||||||
enum:
|
enum:
|
||||||
- AUTH_INVALID_CREDENTIALS
|
- AUTH_INVALID_CREDENTIALS
|
||||||
- AUTH_TOKEN_EXPIRED
|
- AUTH_TOKEN_EXPIRED
|
||||||
|
- AUTH_RATE_LIMITED
|
||||||
- AUTH_FORBIDDEN
|
- AUTH_FORBIDDEN
|
||||||
- ALBUM_NOT_FOUND
|
- ALBUM_NOT_FOUND
|
||||||
- ALBUM_NOT_PUBLIC
|
- ALBUM_NOT_PUBLIC
|
||||||
|
|||||||
@@ -2,6 +2,10 @@
|
|||||||
export const ErrorCodes = {
|
export const ErrorCodes = {
|
||||||
AUTH_INVALID_CREDENTIALS: 'AUTH_INVALID_CREDENTIALS',
|
AUTH_INVALID_CREDENTIALS: 'AUTH_INVALID_CREDENTIALS',
|
||||||
AUTH_TOKEN_EXPIRED: 'AUTH_TOKEN_EXPIRED',
|
AUTH_TOKEN_EXPIRED: 'AUTH_TOKEN_EXPIRED',
|
||||||
|
// Task 13 契约修订(已登记):登录失败基础限速(总纲 P1)需要一个区别于
|
||||||
|
// 凭据错误的错误码——429 若复用 AUTH_INVALID_CREDENTIALS 会向客户端撒谎,
|
||||||
|
// 复用 VALIDATION_FAILED 则语义错位。与 openapi.yaml Error enum 同步增补。
|
||||||
|
AUTH_RATE_LIMITED: 'AUTH_RATE_LIMITED',
|
||||||
AUTH_FORBIDDEN: 'AUTH_FORBIDDEN',
|
AUTH_FORBIDDEN: 'AUTH_FORBIDDEN',
|
||||||
ALBUM_NOT_FOUND: 'ALBUM_NOT_FOUND',
|
ALBUM_NOT_FOUND: 'ALBUM_NOT_FOUND',
|
||||||
ALBUM_NOT_PUBLIC: 'ALBUM_NOT_PUBLIC',
|
ALBUM_NOT_PUBLIC: 'ALBUM_NOT_PUBLIC',
|
||||||
|
|||||||
+13
-1
@@ -404,7 +404,7 @@ export interface components {
|
|||||||
* @description 稳定错误码,与 src/errors.ts 的 ErrorCodes 一一对应。
|
* @description 稳定错误码,与 src/errors.ts 的 ErrorCodes 一一对应。
|
||||||
* @enum {string}
|
* @enum {string}
|
||||||
*/
|
*/
|
||||||
readonly code: "AUTH_INVALID_CREDENTIALS" | "AUTH_TOKEN_EXPIRED" | "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" | "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 服务器生成的可读消息(诊断用,不作为客户端展示文案依据)。 */
|
/** @description 服务器生成的可读消息(诊断用,不作为客户端展示文案依据)。 */
|
||||||
readonly message: string;
|
readonly message: string;
|
||||||
/** @description 请求追踪 ID。 */
|
/** @description 请求追踪 ID。 */
|
||||||
@@ -957,6 +957,18 @@ export interface operations {
|
|||||||
"application/json": components["schemas"]["Error"];
|
"application/json": components["schemas"]["Error"];
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
/**
|
||||||
|
* @description 登录失败次数过多(AUTH_RATE_LIMITED,Task 13 契约修订)。
|
||||||
|
* 同账号+来源 IP 在窗口期内连续失败达到阈值后锁定一段时间。
|
||||||
|
*/
|
||||||
|
429: {
|
||||||
|
headers: {
|
||||||
|
[name: string]: unknown;
|
||||||
|
};
|
||||||
|
content: {
|
||||||
|
"application/json": components["schemas"]["Error"];
|
||||||
|
};
|
||||||
|
};
|
||||||
500: components["responses"]["InternalError"];
|
500: components["responses"]["InternalError"];
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
Generated
+57
-18
@@ -99,13 +99,13 @@ importers:
|
|||||||
dependencies:
|
dependencies:
|
||||||
'@nestjs/common':
|
'@nestjs/common':
|
||||||
specifier: ^10.4.6
|
specifier: ^10.4.6
|
||||||
version: 10.4.22(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
version: 10.4.22(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
||||||
'@nestjs/core':
|
'@nestjs/core':
|
||||||
specifier: ^10.4.6
|
specifier: ^10.4.6
|
||||||
version: 10.4.22(@nestjs/common@10.4.22(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@10.4.22)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
version: 10.4.22(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@10.4.22)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
||||||
'@nestjs/platform-express':
|
'@nestjs/platform-express':
|
||||||
specifier: ^10.4.6
|
specifier: ^10.4.6
|
||||||
version: 10.4.22(@nestjs/common@10.4.22(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)
|
version: 10.4.22(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)
|
||||||
'@node-rs/argon2':
|
'@node-rs/argon2':
|
||||||
specifier: ^2.2.1
|
specifier: ^2.2.1
|
||||||
version: 2.2.1
|
version: 2.2.1
|
||||||
@@ -115,9 +115,15 @@ importers:
|
|||||||
'@photo/db-cn':
|
'@photo/db-cn':
|
||||||
specifier: workspace:*
|
specifier: workspace:*
|
||||||
version: link:../../packages/db-cn
|
version: link:../../packages/db-cn
|
||||||
|
class-transformer:
|
||||||
|
specifier: ^0.5.1
|
||||||
|
version: 0.5.1
|
||||||
|
class-validator:
|
||||||
|
specifier: ^0.15.1
|
||||||
|
version: 0.15.1
|
||||||
nestjs-pino:
|
nestjs-pino:
|
||||||
specifier: ^4.6.1
|
specifier: ^4.6.1
|
||||||
version: 4.6.1(@nestjs/common@10.4.22(reflect-metadata@0.2.2)(rxjs@7.8.2))(pino-http@11.0.0)(pino@10.3.1)(rxjs@7.8.2)
|
version: 4.6.1(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(pino-http@11.0.0)(pino@10.3.1)(rxjs@7.8.2)
|
||||||
pino:
|
pino:
|
||||||
specifier: ^10.0.0
|
specifier: ^10.0.0
|
||||||
version: 10.3.1
|
version: 10.3.1
|
||||||
@@ -133,7 +139,7 @@ importers:
|
|||||||
devDependencies:
|
devDependencies:
|
||||||
'@nestjs/testing':
|
'@nestjs/testing':
|
||||||
specifier: ^10.4.6
|
specifier: ^10.4.6
|
||||||
version: 10.4.22(@nestjs/common@10.4.22(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)(@nestjs/platform-express@10.4.22)
|
version: 10.4.22(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)(@nestjs/platform-express@10.4.22)
|
||||||
'@types/jest':
|
'@types/jest':
|
||||||
specifier: ^29.5.13
|
specifier: ^29.5.13
|
||||||
version: 29.5.14
|
version: 29.5.14
|
||||||
@@ -1010,6 +1016,9 @@ packages:
|
|||||||
'@types/trusted-types@2.0.7':
|
'@types/trusted-types@2.0.7':
|
||||||
resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}
|
resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}
|
||||||
|
|
||||||
|
'@types/validator@13.15.10':
|
||||||
|
resolution: {integrity: sha512-T8L6i7wCuyoK8A/ZeLYt1+q0ty3Zb9+qbSSvrIVitzT3YjZqkTZ40IbRsPanlB4h1QB3JVL1SYCdR6ngtFYcuA==}
|
||||||
|
|
||||||
'@types/yargs-parser@21.0.3':
|
'@types/yargs-parser@21.0.3':
|
||||||
resolution: {integrity: sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==}
|
resolution: {integrity: sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==}
|
||||||
|
|
||||||
@@ -1299,6 +1308,12 @@ packages:
|
|||||||
cjs-module-lexer@1.4.3:
|
cjs-module-lexer@1.4.3:
|
||||||
resolution: {integrity: sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q==}
|
resolution: {integrity: sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q==}
|
||||||
|
|
||||||
|
class-transformer@0.5.1:
|
||||||
|
resolution: {integrity: sha512-SQa1Ws6hUbfC98vKGxZH3KFY0Y1lm5Zm0SY8XX9zbK7FJCyVEac3ATW0RIpwzW+oOfmHE5PMPufDG9hCfoEOMw==}
|
||||||
|
|
||||||
|
class-validator@0.15.1:
|
||||||
|
resolution: {integrity: sha512-LqoS80HBBSCVhz/3KloUly0ovokxpdOLR++Al3J3+dHXWt9sTKlKd4eYtoxhxyUjoe5+UcIM+5k9MIxyBWnRTw==}
|
||||||
|
|
||||||
classnames@2.5.1:
|
classnames@2.5.1:
|
||||||
resolution: {integrity: sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==}
|
resolution: {integrity: sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==}
|
||||||
|
|
||||||
@@ -2141,6 +2156,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==}
|
resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==}
|
||||||
engines: {node: '>= 0.8.0'}
|
engines: {node: '>= 0.8.0'}
|
||||||
|
|
||||||
|
libphonenumber-js@1.13.13:
|
||||||
|
resolution: {integrity: sha512-hV6SmWnyQ8U1QXhhqbqYBHIStNnscG7A5XbGodgdHhf/8N5PwhYpJA5U/yHDjYwPYTd8uNGXqq416XctuvK2PA==}
|
||||||
|
|
||||||
lines-and-columns@1.2.4:
|
lines-and-columns@1.2.4:
|
||||||
resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}
|
resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}
|
||||||
|
|
||||||
@@ -3051,6 +3069,10 @@ packages:
|
|||||||
resolution: {integrity: sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA==}
|
resolution: {integrity: sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA==}
|
||||||
engines: {node: '>=10.12.0'}
|
engines: {node: '>=10.12.0'}
|
||||||
|
|
||||||
|
validator@13.15.35:
|
||||||
|
resolution: {integrity: sha512-TQ5pAGhd5whStmqWvYF4OjQROlmv9SMFVt37qoCBdqRffuuklWYQlCNnEs2ZaIBD1kZRNnikiZOS1eqgkar0iw==}
|
||||||
|
engines: {node: '>= 0.10'}
|
||||||
|
|
||||||
vary@1.1.2:
|
vary@1.1.2:
|
||||||
resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}
|
resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}
|
||||||
engines: {node: '>= 0.8'}
|
engines: {node: '>= 0.8'}
|
||||||
@@ -3798,7 +3820,7 @@ snapshots:
|
|||||||
|
|
||||||
'@lukeed/csprng@1.1.0': {}
|
'@lukeed/csprng@1.1.0': {}
|
||||||
|
|
||||||
'@nestjs/common@10.4.22(reflect-metadata@0.2.2)(rxjs@7.8.2)':
|
'@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2)':
|
||||||
dependencies:
|
dependencies:
|
||||||
file-type: 20.4.1
|
file-type: 20.4.1
|
||||||
iterare: 1.2.1
|
iterare: 1.2.1
|
||||||
@@ -3806,12 +3828,15 @@ snapshots:
|
|||||||
rxjs: 7.8.2
|
rxjs: 7.8.2
|
||||||
tslib: 2.8.1
|
tslib: 2.8.1
|
||||||
uid: 2.0.2
|
uid: 2.0.2
|
||||||
|
optionalDependencies:
|
||||||
|
class-transformer: 0.5.1
|
||||||
|
class-validator: 0.15.1
|
||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- supports-color
|
- supports-color
|
||||||
|
|
||||||
'@nestjs/core@10.4.22(@nestjs/common@10.4.22(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@10.4.22)(reflect-metadata@0.2.2)(rxjs@7.8.2)':
|
'@nestjs/core@10.4.22(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@10.4.22)(reflect-metadata@0.2.2)(rxjs@7.8.2)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@nestjs/common': 10.4.22(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
'@nestjs/common': 10.4.22(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
||||||
'@nuxtjs/opencollective': 0.3.2
|
'@nuxtjs/opencollective': 0.3.2
|
||||||
fast-safe-stringify: 2.1.1
|
fast-safe-stringify: 2.1.1
|
||||||
iterare: 1.2.1
|
iterare: 1.2.1
|
||||||
@@ -3821,14 +3846,14 @@ snapshots:
|
|||||||
tslib: 2.8.1
|
tslib: 2.8.1
|
||||||
uid: 2.0.2
|
uid: 2.0.2
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@nestjs/platform-express': 10.4.22(@nestjs/common@10.4.22(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)
|
'@nestjs/platform-express': 10.4.22(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)
|
||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- encoding
|
- encoding
|
||||||
|
|
||||||
'@nestjs/platform-express@10.4.22(@nestjs/common@10.4.22(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)':
|
'@nestjs/platform-express@10.4.22(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@nestjs/common': 10.4.22(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
'@nestjs/common': 10.4.22(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
||||||
'@nestjs/core': 10.4.22(@nestjs/common@10.4.22(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@10.4.22)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
'@nestjs/core': 10.4.22(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@10.4.22)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
||||||
body-parser: 1.20.4
|
body-parser: 1.20.4
|
||||||
cors: 2.8.5
|
cors: 2.8.5
|
||||||
express: 4.22.1
|
express: 4.22.1
|
||||||
@@ -3837,13 +3862,13 @@ snapshots:
|
|||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- supports-color
|
- supports-color
|
||||||
|
|
||||||
'@nestjs/testing@10.4.22(@nestjs/common@10.4.22(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)(@nestjs/platform-express@10.4.22)':
|
'@nestjs/testing@10.4.22(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)(@nestjs/platform-express@10.4.22)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@nestjs/common': 10.4.22(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
'@nestjs/common': 10.4.22(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
||||||
'@nestjs/core': 10.4.22(@nestjs/common@10.4.22(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@10.4.22)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
'@nestjs/core': 10.4.22(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@10.4.22)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
||||||
tslib: 2.8.1
|
tslib: 2.8.1
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@nestjs/platform-express': 10.4.22(@nestjs/common@10.4.22(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)
|
'@nestjs/platform-express': 10.4.22(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)
|
||||||
|
|
||||||
'@noble/hashes@1.8.0': {}
|
'@noble/hashes@1.8.0': {}
|
||||||
|
|
||||||
@@ -4261,6 +4286,8 @@ snapshots:
|
|||||||
'@types/trusted-types@2.0.7':
|
'@types/trusted-types@2.0.7':
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
|
'@types/validator@13.15.10': {}
|
||||||
|
|
||||||
'@types/yargs-parser@21.0.3': {}
|
'@types/yargs-parser@21.0.3': {}
|
||||||
|
|
||||||
'@types/yargs@17.0.35':
|
'@types/yargs@17.0.35':
|
||||||
@@ -4606,6 +4633,14 @@ snapshots:
|
|||||||
|
|
||||||
cjs-module-lexer@1.4.3: {}
|
cjs-module-lexer@1.4.3: {}
|
||||||
|
|
||||||
|
class-transformer@0.5.1: {}
|
||||||
|
|
||||||
|
class-validator@0.15.1:
|
||||||
|
dependencies:
|
||||||
|
'@types/validator': 13.15.10
|
||||||
|
libphonenumber-js: 1.13.13
|
||||||
|
validator: 13.15.35
|
||||||
|
|
||||||
classnames@2.5.1: {}
|
classnames@2.5.1: {}
|
||||||
|
|
||||||
cliui@7.0.4:
|
cliui@7.0.4:
|
||||||
@@ -5618,6 +5653,8 @@ snapshots:
|
|||||||
prelude-ls: 1.2.1
|
prelude-ls: 1.2.1
|
||||||
type-check: 0.4.0
|
type-check: 0.4.0
|
||||||
|
|
||||||
|
libphonenumber-js@1.13.13: {}
|
||||||
|
|
||||||
lines-and-columns@1.2.4: {}
|
lines-and-columns@1.2.4: {}
|
||||||
|
|
||||||
locate-path@5.0.0:
|
locate-path@5.0.0:
|
||||||
@@ -5739,9 +5776,9 @@ snapshots:
|
|||||||
|
|
||||||
neo-async@2.6.2: {}
|
neo-async@2.6.2: {}
|
||||||
|
|
||||||
nestjs-pino@4.6.1(@nestjs/common@10.4.22(reflect-metadata@0.2.2)(rxjs@7.8.2))(pino-http@11.0.0)(pino@10.3.1)(rxjs@7.8.2):
|
nestjs-pino@4.6.1(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(pino-http@11.0.0)(pino@10.3.1)(rxjs@7.8.2):
|
||||||
dependencies:
|
dependencies:
|
||||||
'@nestjs/common': 10.4.22(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
'@nestjs/common': 10.4.22(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
||||||
pino: 10.3.1
|
pino: 10.3.1
|
||||||
pino-http: 11.0.0
|
pino-http: 11.0.0
|
||||||
rxjs: 7.8.2
|
rxjs: 7.8.2
|
||||||
@@ -6521,6 +6558,8 @@ snapshots:
|
|||||||
'@types/istanbul-lib-coverage': 2.0.6
|
'@types/istanbul-lib-coverage': 2.0.6
|
||||||
convert-source-map: 2.0.0
|
convert-source-map: 2.0.0
|
||||||
|
|
||||||
|
validator@13.15.35: {}
|
||||||
|
|
||||||
vary@1.1.2: {}
|
vary@1.1.2: {}
|
||||||
|
|
||||||
walker@1.0.8:
|
walker@1.0.8:
|
||||||
|
|||||||
@@ -20,6 +20,8 @@
|
|||||||
"@node-rs/argon2": "^2.2.1",
|
"@node-rs/argon2": "^2.2.1",
|
||||||
"@photo/contracts": "workspace:*",
|
"@photo/contracts": "workspace:*",
|
||||||
"@photo/db-cn": "workspace:*",
|
"@photo/db-cn": "workspace:*",
|
||||||
|
"class-transformer": "^0.5.1",
|
||||||
|
"class-validator": "^0.15.1",
|
||||||
"nestjs-pino": "^4.6.1",
|
"nestjs-pino": "^4.6.1",
|
||||||
"pino": "^10.0.0",
|
"pino": "^10.0.0",
|
||||||
"pino-http": "^11.0.0",
|
"pino-http": "^11.0.0",
|
||||||
|
|||||||
@@ -1,14 +1,22 @@
|
|||||||
// services/api/src/app-cn.module.ts
|
// services/api/src/app-cn.module.ts
|
||||||
// 根模块:Prisma(@Global,封装 @photo/db-cn)、日志(nestjs-pino / pino-http)、
|
// 根模块:Prisma(@Global,封装 @photo/db-cn)、日志(nestjs-pino / pino-http)、
|
||||||
// request-id 中间件、全局异常过滤器、/v1/health。
|
// request-id 中间件、全局异常过滤器、全局校验管道(Task 13 起,DTO 经
|
||||||
// 功能模块(auth/albums/uploads/photos/public)自 Task 12+ 起逐个加入。
|
// class-validator 声明、ValidationPipe 强制,失败由过滤器映射 400 VALIDATION_FAILED)、
|
||||||
// 过滤器经 APP_FILTER、中间件经 NestModule 在模块层注册——e2e 直接 import 本模块
|
// /v1/health、/v1/auth/*(Task 13)。
|
||||||
// 即可获得与生产一致的管线(全局前缀除外,由入口设置)。
|
// 功能模块(albums/uploads/photos/public)自 Task 15+ 起逐个加入。
|
||||||
import { type MiddlewareConsumer, Module, type NestModule } from '@nestjs/common';
|
// 过滤器/管道经 APP_FILTER/APP_PIPE、中间件经 NestModule 在模块层注册——e2e 直接
|
||||||
import { APP_FILTER } from '@nestjs/core';
|
// 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 { LoggerModule } from 'nestjs-pino';
|
||||||
import type { IncomingMessage, ServerResponse } from 'node:http';
|
import type { IncomingMessage, ServerResponse } from 'node:http';
|
||||||
import { AllExceptionsFilter } from './all-exceptions.filter';
|
import { AllExceptionsFilter } from './all-exceptions.filter';
|
||||||
|
import { AuthModule } from './auth/auth.module';
|
||||||
import { HealthController } from './health.controller';
|
import { HealthController } from './health.controller';
|
||||||
import { PrismaModule } from './prisma/prisma.module';
|
import { PrismaModule } from './prisma/prisma.module';
|
||||||
import { RequestIdMiddleware, resolveRequestId } from './request-id.middleware';
|
import { RequestIdMiddleware, resolveRequestId } from './request-id.middleware';
|
||||||
@@ -19,6 +27,7 @@ import type { ServerRequestWithId } from './shared/request-with-id';
|
|||||||
imports: [
|
imports: [
|
||||||
// @Global:功能模块(Task 12+)直接注入 PrismaService,无需 re-import。
|
// @Global:功能模块(Task 12+)直接注入 PrismaService,无需 re-import。
|
||||||
PrismaModule,
|
PrismaModule,
|
||||||
|
AuthModule,
|
||||||
LoggerModule.forRoot({
|
LoggerModule.forRoot({
|
||||||
pinoHttp: {
|
pinoHttp: {
|
||||||
// 与 RequestIdMiddleware 共用同一解析函数:优先透传 x-request-id,
|
// 与 RequestIdMiddleware 共用同一解析函数:优先透传 x-request-id,
|
||||||
@@ -43,7 +52,16 @@ import type { ServerRequestWithId } from './shared/request-with-id';
|
|||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
controllers: [HealthController],
|
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 {
|
export class AppCnModule implements NestModule {
|
||||||
configure(consumer: MiddlewareConsumer): void {
|
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