feat(api): 开发平台、门店相关代码
This commit is contained in:
@@ -2,20 +2,24 @@ import { Controller, Get, Inject, Module } from '@nestjs/common';
|
||||
import type { Database } from '@atlas/database';
|
||||
import { AuthModule } from './auth/auth.module.js';
|
||||
import { ApiError } from './common/api-error.js';
|
||||
import { Public } from './common/public.decorator.js';
|
||||
import { AppConfigModule } from './config/app-config.module.js';
|
||||
import { DATABASE, DatabaseModule } from './database/database.module.js';
|
||||
import { SecurityModule } from './security/security.module.js';
|
||||
import { StoresModule } from './stores/stores.module.js';
|
||||
|
||||
@Controller()
|
||||
class HealthController {
|
||||
public constructor(@Inject(DATABASE) private readonly database: Database) {}
|
||||
|
||||
@Get('health')
|
||||
@Public()
|
||||
check() {
|
||||
return { status: 'ok', service: 'api' };
|
||||
}
|
||||
|
||||
@Get('ready')
|
||||
@Public()
|
||||
async ready() {
|
||||
try {
|
||||
await this.database.query('SELECT 1');
|
||||
@@ -31,7 +35,13 @@ class HealthController {
|
||||
}
|
||||
|
||||
@Module({
|
||||
imports: [AppConfigModule, DatabaseModule, SecurityModule, AuthModule],
|
||||
imports: [
|
||||
AppConfigModule,
|
||||
DatabaseModule,
|
||||
SecurityModule,
|
||||
AuthModule,
|
||||
StoresModule,
|
||||
],
|
||||
controllers: [HealthController],
|
||||
})
|
||||
export class AppModule {}
|
||||
|
||||
@@ -3,10 +3,10 @@ import {
|
||||
Controller,
|
||||
Get,
|
||||
HttpCode,
|
||||
Inject,
|
||||
Post,
|
||||
Req,
|
||||
Res,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
ApiBearerAuth,
|
||||
@@ -18,12 +18,19 @@ import {
|
||||
ApiUnauthorizedResponse,
|
||||
} from '@nestjs/swagger';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { loginRequestSchema, registerRequestSchema } from '@atlas/contracts';
|
||||
import {
|
||||
loginRequestSchema,
|
||||
registerRequestSchema,
|
||||
type Workspace,
|
||||
} from '@atlas/contracts';
|
||||
import { ApiError } from '../common/api-error.js';
|
||||
import { AccessTokenGuard, type AuthenticatedRequest } from './auth.guard.js';
|
||||
import { Public } from '../common/public.decorator.js';
|
||||
import type { AuthenticatedRequest } from './auth.guard.js';
|
||||
import { AuthService, type RequestMetadata } from './auth.service.js';
|
||||
import { CurrentWorkspace } from '../workspace/current-workspace.decorator.js';
|
||||
|
||||
const refreshCookie = 'atlas_refresh';
|
||||
// 控制器只负责 HTTP 边界;账户、会话与工作空间的一致性由 AuthService 的事务保证。
|
||||
type HttpRequest = {
|
||||
header: (name: string) => string | undefined;
|
||||
ip?: string;
|
||||
@@ -40,9 +47,12 @@ type HttpResponse = {
|
||||
@ApiTags('Authentication')
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
public constructor(private readonly authService: AuthService) {}
|
||||
public constructor(
|
||||
@Inject(AuthService) private readonly authService: AuthService,
|
||||
) {}
|
||||
|
||||
@Post('register')
|
||||
@Public()
|
||||
@ApiOperation({ summary: '注册账户并创建个人工作空间' })
|
||||
@ApiBody({
|
||||
schema: {
|
||||
@@ -68,6 +78,8 @@ export class AuthController {
|
||||
}
|
||||
|
||||
@Post('login')
|
||||
@Public()
|
||||
@HttpCode(200)
|
||||
@ApiOperation({ summary: '使用邮箱和密码登录' })
|
||||
@ApiBody({
|
||||
schema: {
|
||||
@@ -91,12 +103,15 @@ export class AuthController {
|
||||
}
|
||||
|
||||
@Post('refresh')
|
||||
@Public()
|
||||
@HttpCode(200)
|
||||
@ApiOperation({ summary: '轮换 refresh cookie 并获取新的 access token' })
|
||||
public async refresh(
|
||||
@Req() request: HttpRequest,
|
||||
@Res({ passthrough: true }) response: HttpResponse,
|
||||
) {
|
||||
try {
|
||||
// refresh token 不进入 JSON body,仅从浏览器自动发送的 HttpOnly cookie 读取。
|
||||
const result = await this.authService.refresh(
|
||||
readCookie(request.header('cookie'), refreshCookie),
|
||||
metadata(request),
|
||||
@@ -117,7 +132,6 @@ export class AuthController {
|
||||
|
||||
@Post('logout')
|
||||
@HttpCode(204)
|
||||
@UseGuards(AccessTokenGuard)
|
||||
@ApiBearerAuth('access-token')
|
||||
@ApiOperation({ summary: '撤销当前登录会话' })
|
||||
@ApiNoContentResponse({ description: '会话已撤销' })
|
||||
@@ -131,13 +145,17 @@ export class AuthController {
|
||||
}
|
||||
|
||||
@Get('me')
|
||||
@UseGuards(AccessTokenGuard)
|
||||
@ApiBearerAuth('access-token')
|
||||
@ApiOperation({ summary: '获取当前用户、工作空间和页头初始上下文' })
|
||||
@ApiOkResponse({ description: '当前身份和工作空间' })
|
||||
@ApiUnauthorizedResponse({ description: 'access token 无效或已过期' })
|
||||
public async me(@Req() request: AuthenticatedRequest) {
|
||||
return { data: await this.authService.me(request.auth.userId) };
|
||||
public async me(
|
||||
@Req() request: AuthenticatedRequest,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return {
|
||||
data: await this.authService.me(request.auth.userId, workspace),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,6 +196,7 @@ function metadata(request: HttpRequest): RequestMetadata {
|
||||
};
|
||||
}
|
||||
function cookieOptions() {
|
||||
// cookie 路径限制在认证接口,避免无关请求携带长期会话凭证。
|
||||
return {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
@@ -198,6 +217,7 @@ function clearRefreshCookie(response: HttpResponse) {
|
||||
});
|
||||
}
|
||||
function readCookie(header: string | undefined, name: string) {
|
||||
// 只解析本服务需要的单个 cookie,避免引入与认证无关的 cookie 状态。
|
||||
return header
|
||||
?.split(';')
|
||||
.map((part) => part.trim())
|
||||
|
||||
@@ -13,10 +13,11 @@ const scrypt = promisify(scryptCallback) as (
|
||||
keyLength: number,
|
||||
options: { N: number; r: number; p: number; maxmem: number },
|
||||
) => Promise<Buffer>;
|
||||
// 使用较高成本的 scrypt 参数,控制离线破解密码哈希时的时间与内存成本。
|
||||
const scryptOptions = { N: 16_384, r: 8, p: 1, maxmem: 32 * 1024 * 1024 };
|
||||
|
||||
export async function hashPassword(password: string): Promise<string> {
|
||||
// The random salt and expensive KDF keep a database leak from exposing passwords directly.
|
||||
// 每个密码使用独立随机盐,数据库泄露时不能直接复用预计算结果。
|
||||
const salt = randomBytes(16).toString('base64url');
|
||||
const derived = (await scrypt(password, salt, 64, scryptOptions)) as Buffer;
|
||||
return `scrypt$${salt}$${derived.toString('base64url')}`;
|
||||
@@ -40,6 +41,7 @@ export function createOpaqueToken(): string {
|
||||
return randomBytes(48).toString('base64url');
|
||||
}
|
||||
export function tokenHash(token: string): string {
|
||||
// refresh token 只以摘要形式存库;服务端无需保存可直接用于登录的原文。
|
||||
return createHash('sha256').update(token).digest('base64url');
|
||||
}
|
||||
|
||||
@@ -53,7 +55,7 @@ export function signAccessToken(
|
||||
claims: AccessTokenClaims,
|
||||
secret: string,
|
||||
): string {
|
||||
// Access tokens are short-lived; refresh sessions remain revocable in PostgreSQL.
|
||||
// access token 是短期自包含凭证;真正可撤销的会话状态仍以 PostgreSQL 为准。
|
||||
const header = Buffer.from(
|
||||
JSON.stringify({ alg: 'HS256', typ: 'JWT' }),
|
||||
).toString('base64url');
|
||||
@@ -73,6 +75,7 @@ export function verifyAccessToken(
|
||||
.update(`${header}.${payload}`)
|
||||
.digest();
|
||||
const actual = Buffer.from(signature, 'base64url');
|
||||
// 恒定时间比较可避免根据签名比对耗时推测正确前缀。
|
||||
if (actual.length !== expected.length || !timingSafeEqual(actual, expected))
|
||||
return null;
|
||||
try {
|
||||
|
||||
@@ -1,18 +1,43 @@
|
||||
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Inject,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import type { Workspace } from '@atlas/contracts';
|
||||
import { IS_PUBLIC_ENDPOINT } from '../common/public.decorator.js';
|
||||
import { AuthService } from './auth.service.js';
|
||||
|
||||
export type AuthenticatedRequest = {
|
||||
header: (name: string) => string | undefined;
|
||||
auth: { userId: string; sessionId: string };
|
||||
auth: {
|
||||
userId: string;
|
||||
sessionId: string;
|
||||
workspace?: Workspace;
|
||||
};
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class AccessTokenGuard implements CanActivate {
|
||||
public constructor(private readonly authService: AuthService) {}
|
||||
public constructor(
|
||||
@Inject(Reflector) private readonly reflector: Reflector,
|
||||
@Inject(AuthService) private readonly authService: AuthService,
|
||||
) {}
|
||||
public async canActivate(context: ExecutionContext) {
|
||||
// 公开端点必须显式声明,避免新路由因忘记添加守卫而意外暴露。
|
||||
if (
|
||||
this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_ENDPOINT, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
])
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
const request = context
|
||||
.switchToHttp()
|
||||
.getRequest<AuthenticatedRequest>();
|
||||
// 只在此处解析 Authorization,后续守卫和控制器共享已验证的会话身份。
|
||||
request.auth = await this.authService.authenticate(
|
||||
request.header('authorization'),
|
||||
);
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import { AuthController } from './auth.controller.js';
|
||||
import { AccessTokenGuard } from './auth.guard.js';
|
||||
import { AuthService } from './auth.service.js';
|
||||
import { WorkspaceContextGuard } from '../workspace/workspace-context.guard.js';
|
||||
|
||||
@Module({
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, AccessTokenGuard],
|
||||
providers: [
|
||||
AuthService,
|
||||
AccessTokenGuard,
|
||||
WorkspaceContextGuard,
|
||||
{ provide: APP_GUARD, useExisting: AccessTokenGuard },
|
||||
{ provide: APP_GUARD, useExisting: WorkspaceContextGuard },
|
||||
],
|
||||
})
|
||||
export class AuthModule {}
|
||||
|
||||
@@ -33,12 +33,14 @@ type WorkspaceRow = { id: string; name: string; role: Workspace['role'] };
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
// access token 短期存在于浏览器内存;refresh session 的有效期更长且可服务端撤销。
|
||||
private readonly accessTtlSeconds = 900;
|
||||
private readonly refreshTtlDays = 30;
|
||||
|
||||
public constructor(
|
||||
@Inject(DATABASE) private readonly database: Database,
|
||||
@Inject(APP_CONFIG) private readonly config: AppConfig,
|
||||
@Inject(AuthRateLimiter)
|
||||
private readonly rateLimiter: AuthRateLimiter,
|
||||
) {}
|
||||
|
||||
@@ -56,12 +58,12 @@ export class AuthService {
|
||||
`密码至少需要 ${this.config.AUTH_PASSWORD_MIN_LENGTH} 个字符`,
|
||||
);
|
||||
const email = input.email.trim().toLowerCase();
|
||||
// Apply the shared limiter before spending CPU on password hashing or querying account existence.
|
||||
// 限流必须早于密码哈希和用户查询,避免攻击者消耗 CPU 或探测账户状态。
|
||||
await this.rateLimiter.consume('register', { ip: metadata.ip, email });
|
||||
const passwordHash = await hashPassword(input.password);
|
||||
try {
|
||||
return await this.database.transaction(async (transaction) => {
|
||||
// A user must never exist without its initial tenant and owner membership.
|
||||
// 用户、个人工作空间和 owner membership 必须原子创建,不能留下半成品租户。
|
||||
const user = await insertUser(
|
||||
transaction,
|
||||
email,
|
||||
@@ -100,7 +102,7 @@ export class AuthService {
|
||||
|
||||
public async login(input: LoginRequest, metadata: RequestMetadata) {
|
||||
const email = input.email.trim().toLowerCase();
|
||||
// Use the same normalized value for the limiter and citext account lookup.
|
||||
// 限流与 citext 查询使用同一规范化邮箱,避免大小写绕过限流桶。
|
||||
await this.rateLimiter.consume('login', { ip: metadata.ip, email });
|
||||
const result = await this.database.query<UserRow>(
|
||||
'SELECT id, email, display_name, email_verified_at, created_at, status, password_hash FROM atlas.users WHERE email = $1',
|
||||
@@ -133,7 +135,7 @@ export class AuthService {
|
||||
refreshToken: string | undefined,
|
||||
metadata: RequestMetadata,
|
||||
) {
|
||||
// Refresh has no trusted email until its opaque token is validated, so it is IP-scoped only.
|
||||
// refresh token 验证前没有可信邮箱,只能按 IP 维度限流。
|
||||
await this.rateLimiter.consume('refresh', { ip: metadata.ip });
|
||||
if (!refreshToken)
|
||||
throw new ApiError(401, 'SESSION_EXPIRED', '登录会话已过期');
|
||||
@@ -149,7 +151,7 @@ export class AuthService {
|
||||
const user = sessions.rows[0];
|
||||
if (!user || user.status !== 'active')
|
||||
throw new ApiError(401, 'SESSION_EXPIRED', '登录会话已过期');
|
||||
// Row locking makes a refresh token single-use even when two browser requests arrive together.
|
||||
// 行锁保证并发 refresh 时旧 token 只能成功使用一次。
|
||||
await transaction.query(
|
||||
'UPDATE atlas.user_sessions SET revoked_at = now() WHERE id = $1',
|
||||
[user.session_id],
|
||||
@@ -180,6 +182,7 @@ export class AuthService {
|
||||
? verifyAccessToken(token, this.config.AUTH_JWT_SECRET)
|
||||
: null;
|
||||
if (!claims) throw new UnauthorizedException();
|
||||
// JWT 签名有效仍不足够;必须确认对应 session 未撤销且未过期。
|
||||
const active = await this.database.query(
|
||||
'SELECT 1 FROM atlas.user_sessions WHERE id = $1 AND user_id = $2 AND revoked_at IS NULL AND expires_at > now()',
|
||||
[claims.sid, claims.sub],
|
||||
@@ -188,8 +191,8 @@ export class AuthService {
|
||||
return { userId: claims.sub, sessionId: claims.sid };
|
||||
}
|
||||
|
||||
public async me(userId: string) {
|
||||
const workspace = await this.findWorkspace(userId);
|
||||
public async me(userId: string, workspace: Workspace) {
|
||||
// workspace 由全局守卫解析,避免控制器或服务各自选择租户造成边界不一致。
|
||||
const users = await this.database.query<UserRow>(
|
||||
'SELECT id, email, display_name, email_verified_at, created_at, status, password_hash FROM atlas.users WHERE id = $1',
|
||||
[userId],
|
||||
@@ -233,6 +236,7 @@ export class AuthService {
|
||||
workspace: WorkspaceRow,
|
||||
metadata: RequestMetadata,
|
||||
) {
|
||||
// refresh token 仅通过 HttpOnly cookie 交给浏览器,响应体只暴露短期 access token。
|
||||
const refreshToken = createOpaqueToken();
|
||||
const session = await transaction.query<{ id: string }>(
|
||||
`INSERT INTO atlas.user_sessions (user_id, refresh_token_hash, expires_at, ip_hash, user_agent)
|
||||
@@ -284,6 +288,7 @@ function isUniqueViolation(error: unknown): error is { code: string } {
|
||||
);
|
||||
}
|
||||
function publicUser(user: UserRow): AuthUser {
|
||||
// 白名单映射防止 password_hash 等内部字段随查询结果泄露给客户端。
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
@@ -298,6 +303,7 @@ async function insertUser(
|
||||
passwordHash: string,
|
||||
displayName: string | null,
|
||||
) {
|
||||
// slug 使用用户 UUID,显示名称变化不会影响个人工作空间的稳定标识。
|
||||
const result = await transaction.query<UserRow>(
|
||||
'INSERT INTO atlas.users (email, password_hash, display_name) VALUES ($1, $2, $3) RETURNING id, email, display_name, email_verified_at, created_at, status, password_hash',
|
||||
[email, passwordHash, displayName],
|
||||
|
||||
@@ -25,6 +25,7 @@ export class ApiErrorFilter implements ExceptionFilter {
|
||||
}>();
|
||||
const requestId = request.requestId ?? `req_${randomUUID()}`;
|
||||
if (exception instanceof ApiError) {
|
||||
// 已知业务错误保留其稳定 code 与 details,方便前端精确处理。
|
||||
const body = exception.getResponse() as {
|
||||
error: Record<string, unknown>;
|
||||
};
|
||||
@@ -33,6 +34,7 @@ export class ApiErrorFilter implements ExceptionFilter {
|
||||
.json({ error: { ...body.error, request_id: requestId } });
|
||||
}
|
||||
if (exception instanceof HttpException) {
|
||||
// Nest 内部异常不泄露原始 message,避免暴露认证或解析实现细节。
|
||||
return response.status(exception.getStatus()).json({
|
||||
error: {
|
||||
code: 'HTTP_ERROR',
|
||||
@@ -50,6 +52,7 @@ export class ApiErrorFilter implements ExceptionFilter {
|
||||
path: request.originalUrl,
|
||||
},
|
||||
);
|
||||
// 未预期异常只返回通用信息,request_id 用于从结构化日志定位根因。
|
||||
return response.status(500).json({
|
||||
error: {
|
||||
code: 'INTERNAL_ERROR',
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { HttpException, HttpStatus } from '@nestjs/common';
|
||||
|
||||
export class ApiError extends HttpException {
|
||||
// 业务代码只能通过此类型抛出可预期错误,最终由全局过滤器统一封装为 error 信封。
|
||||
public constructor(
|
||||
status: HttpStatus,
|
||||
code: string,
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import { createHmac } from 'node:crypto';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import type { Database, DatabaseTransaction } from '@atlas/database';
|
||||
import { APP_CONFIG, type AppConfig } from '../config/app-config.module.js';
|
||||
import { DATABASE } from '../database/database.module.js';
|
||||
import { ApiError } from './api-error.js';
|
||||
|
||||
type IdempotentResponse = { status: number; body: unknown };
|
||||
type IdempotencyInput = {
|
||||
workspaceId: string;
|
||||
userId: string;
|
||||
method: 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
||||
path: string;
|
||||
key: string;
|
||||
request: unknown;
|
||||
};
|
||||
type IdempotencyRow = {
|
||||
request_fingerprint: string;
|
||||
status: 'in_progress' | 'completed';
|
||||
response_status: number | null;
|
||||
response_body: unknown;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class IdempotencyService {
|
||||
public constructor(
|
||||
@Inject(DATABASE) private readonly database: Database,
|
||||
@Inject(APP_CONFIG) private readonly config: AppConfig,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 幂等记录与业务写入共用同一个工作空间事务。只有两者都提交,重试才会得到可靠的历史响应。
|
||||
*/
|
||||
public async run(
|
||||
input: IdempotencyInput,
|
||||
work: (transaction: DatabaseTransaction) => Promise<IdempotentResponse>,
|
||||
): Promise<IdempotentResponse> {
|
||||
const fingerprint = createHmac(
|
||||
'sha256',
|
||||
this.config.IDEMPOTENCY_KEY_SECRET,
|
||||
)
|
||||
.update(canonicalize(input.request))
|
||||
.digest('base64url');
|
||||
|
||||
return this.database.workspaceTransaction(
|
||||
input.workspaceId,
|
||||
async (transaction) => {
|
||||
const inserted = await transaction.query<IdempotencyRow>(
|
||||
`INSERT INTO atlas.idempotency_requests
|
||||
(workspace_id, user_id, http_method, request_path, idempotency_key, request_fingerprint)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
ON CONFLICT (workspace_id, user_id, http_method, request_path, idempotency_key) DO NOTHING
|
||||
RETURNING request_fingerprint, status, response_status, response_body`,
|
||||
[
|
||||
input.workspaceId,
|
||||
input.userId,
|
||||
input.method,
|
||||
input.path,
|
||||
input.key,
|
||||
fingerprint,
|
||||
],
|
||||
);
|
||||
if (!inserted.rows[0]) {
|
||||
// 冲突插入会等待首个事务结束;随后行锁确保只能读取完整的持久化结果。
|
||||
const existing = await transaction.query<IdempotencyRow>(
|
||||
`SELECT request_fingerprint, status, response_status, response_body
|
||||
FROM atlas.idempotency_requests
|
||||
WHERE workspace_id = $1 AND user_id = $2 AND http_method = $3
|
||||
AND request_path = $4 AND idempotency_key = $5
|
||||
FOR UPDATE`,
|
||||
[
|
||||
input.workspaceId,
|
||||
input.userId,
|
||||
input.method,
|
||||
input.path,
|
||||
input.key,
|
||||
],
|
||||
);
|
||||
const row = existing.rows[0];
|
||||
if (!row || row.request_fingerprint !== fingerprint) {
|
||||
throw new ApiError(
|
||||
409,
|
||||
'IDEMPOTENCY_KEY_REUSED',
|
||||
'幂等键已用于不同请求',
|
||||
);
|
||||
}
|
||||
if (row.status !== 'completed' || !row.response_status) {
|
||||
throw new ApiError(
|
||||
409,
|
||||
'IDEMPOTENCY_REQUEST_IN_PROGRESS',
|
||||
'相同请求仍在处理中',
|
||||
);
|
||||
}
|
||||
return {
|
||||
status: row.response_status,
|
||||
body: row.response_body,
|
||||
};
|
||||
}
|
||||
|
||||
const response = await work(transaction);
|
||||
await transaction.query(
|
||||
`UPDATE atlas.idempotency_requests
|
||||
SET status = 'completed', response_status = $1, response_body = $2,
|
||||
completed_at = now()
|
||||
WHERE workspace_id = $3 AND user_id = $4 AND http_method = $5
|
||||
AND request_path = $6 AND idempotency_key = $7`,
|
||||
[
|
||||
response.status,
|
||||
response.body,
|
||||
input.workspaceId,
|
||||
input.userId,
|
||||
input.method,
|
||||
input.path,
|
||||
input.key,
|
||||
],
|
||||
);
|
||||
return response;
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** 规范化排序后再签名,使 JSON 字段顺序不会改变同一请求的身份。 */
|
||||
function canonicalize(value: unknown): string {
|
||||
if (value === null || typeof value !== 'object')
|
||||
return JSON.stringify(value);
|
||||
if (Array.isArray(value)) return `[${value.map(canonicalize).join(',')}]`;
|
||||
const record = value as Record<string, unknown>;
|
||||
return `{${Object.keys(record)
|
||||
.sort()
|
||||
.map((key) => `${JSON.stringify(key)}:${canonicalize(record[key])}`)
|
||||
.join(',')}}`;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const IS_PUBLIC_ENDPOINT = 'atlas:is-public-endpoint';
|
||||
|
||||
// 全局认证守卫只跳过显式标记的端点,避免新接口因遗漏守卫而意外公开。
|
||||
export const Public = () => SetMetadata(IS_PUBLIC_ENDPOINT, true);
|
||||
@@ -19,8 +19,7 @@ function findEnvironmentFile(): string {
|
||||
return environmentFile ?? resolve(process.cwd(), '.env');
|
||||
}
|
||||
|
||||
// This schema is the only supported source for API runtime settings. Defaults are
|
||||
// intentionally limited to non-secret local-development values.
|
||||
// 此 schema 是 API 运行配置的唯一来源;默认值只允许用于不含秘密的本地开发场景。
|
||||
const environmentSchema = z.object({
|
||||
NODE_ENV: z
|
||||
.enum(['development', 'test', 'production'])
|
||||
@@ -31,6 +30,13 @@ const environmentSchema = z.object({
|
||||
REDIS_URL: z.url(),
|
||||
AUTH_JWT_SECRET: z.string().min(32),
|
||||
AUTH_RATE_LIMIT_KEY_SECRET: z.string().min(32),
|
||||
STORE_SECRET_ENCRYPTION_KEY: z.string().min(32),
|
||||
STORE_SECRET_ENCRYPTION_KEY_VERSION: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(64)
|
||||
.default('v1'),
|
||||
IDEMPOTENCY_KEY_SECRET: z.string().min(32),
|
||||
AUTH_PASSWORD_MIN_LENGTH: z.coerce
|
||||
.number()
|
||||
.int()
|
||||
@@ -83,7 +89,7 @@ function validateEnvironment(
|
||||
): Environment {
|
||||
const result = environmentSchema.safeParse(environment);
|
||||
if (result.success) return result.data;
|
||||
// Fail before Nest opens a listener; a half-configured API is unsafe to run.
|
||||
// 在 Nest 开始监听前失败,避免半配置 API 对外提供不安全服务。
|
||||
throw new Error(
|
||||
`Invalid environment configuration: ${result.error.issues.map((issue) => issue.path.join('.')).join(', ')}`,
|
||||
);
|
||||
@@ -92,7 +98,7 @@ function validateEnvironment(
|
||||
function createAppConfig(environment: Environment): AppConfig {
|
||||
return {
|
||||
...environment,
|
||||
// Express only trusts forwarding headers when this explicit allowlist is non-empty.
|
||||
// 只有显式给出代理网段时才信任转发头,避免客户端伪造来源 IP。
|
||||
trustedProxyCidrs: environment.TRUSTED_PROXY_CIDRS.split(',')
|
||||
.map((value) => value.trim())
|
||||
.filter(Boolean),
|
||||
@@ -106,15 +112,14 @@ function createAppConfig(environment: Environment): AppConfig {
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
cache: true,
|
||||
// Turbo runs this workspace's scripts from apps/api, while the
|
||||
// shared development environment lives at the repository root.
|
||||
// Turbo 从 apps/api 运行脚本,但共享开发环境文件位于仓库根目录。
|
||||
envFilePath: findEnvironmentFile(),
|
||||
}),
|
||||
],
|
||||
providers: [
|
||||
{
|
||||
provide: APP_CONFIG,
|
||||
// Export a normalized immutable config object so services never read process.env directly.
|
||||
// 导出规范化配置,业务服务不得散落读取 process.env。
|
||||
useFactory: (): AppConfig =>
|
||||
createAppConfig(validateEnvironment(process.env)),
|
||||
},
|
||||
|
||||
@@ -10,6 +10,7 @@ export const DATABASE = Symbol('DATABASE');
|
||||
{
|
||||
provide: DATABASE,
|
||||
inject: [APP_CONFIG],
|
||||
// 业务代码只能拿到受限应用连接,迁移连接串绝不注入 API 容器。
|
||||
useFactory: (config: AppConfig): Database =>
|
||||
createApplicationDatabase(config.DATABASE_URL),
|
||||
},
|
||||
@@ -19,6 +20,7 @@ export const DATABASE = Symbol('DATABASE');
|
||||
export class DatabaseModule implements OnModuleDestroy {
|
||||
public constructor(@Inject(DATABASE) private readonly database: Database) {}
|
||||
public async onModuleDestroy() {
|
||||
// Nest 关闭时主动释放连接池,避免测试和热重启遗留连接。
|
||||
await this.database.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ const severity: Record<LogLevel, number> = {
|
||||
log: 2,
|
||||
debug: 3,
|
||||
};
|
||||
// 按字段名递归脱敏,日志中不得出现会话、密码、密钥或授权头原文。
|
||||
const sensitiveKeys = /authorization|cookie|password|secret|token|api[_-]?key/i;
|
||||
|
||||
export class AppLogger implements LoggerService {
|
||||
@@ -40,6 +41,7 @@ export class AppLogger implements LoggerService {
|
||||
message: typeof message === 'string' ? message : sanitize(message),
|
||||
context: sanitize(context),
|
||||
};
|
||||
// 每行独立 JSON,方便日志采集系统按字段索引 request_id、状态码等上下文。
|
||||
const output = JSON.stringify(entry);
|
||||
if (level === 'error') console.error(output);
|
||||
else console.log(output);
|
||||
|
||||
+38
-45
@@ -1,6 +1,7 @@
|
||||
import 'reflect-metadata';
|
||||
import { execFile } from 'node:child_process';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { NestExpressApplication } from '@nestjs/platform-express';
|
||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
@@ -16,31 +17,10 @@ type RequestWithId = Request & {
|
||||
requestId?: string;
|
||||
};
|
||||
|
||||
function openSwaggerInDevelopment(config: AppConfig, logger: AppLogger): void {
|
||||
if (
|
||||
config.NODE_ENV !== 'development' ||
|
||||
!config.swaggerEnabled ||
|
||||
process.platform !== 'darwin'
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const swaggerUrl = `http://localhost:${config.API_PORT}/api-docs`;
|
||||
// 只在本机开发时打开浏览器,生产环境和非 macOS 主机不执行外部进程。
|
||||
execFile('open', [swaggerUrl], (error) => {
|
||||
if (error) {
|
||||
logger.warn('swagger_auto_open_failed', {
|
||||
error: error.message,
|
||||
url: swaggerUrl,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function bootstrap() {
|
||||
export async function createApplication() {
|
||||
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
|
||||
bodyParser: false,
|
||||
// Keep Nest's bootstrap errors visible until AppLogger is installed below.
|
||||
// 自定义日志器安装前保留 Nest 启动日志,避免配置错误没有可见诊断。
|
||||
logger: ['error', 'warn', 'log'],
|
||||
});
|
||||
const config = app.get<AppConfig>(APP_CONFIG);
|
||||
@@ -48,7 +28,7 @@ async function bootstrap() {
|
||||
app.useLogger(logger);
|
||||
|
||||
if (config.trustedProxyCidrs.length > 0) {
|
||||
// Never trust forwarded headers unless the deployment names its proxy networks explicitly.
|
||||
// 仅在部署明确声明代理网段时信任转发头,避免伪造客户端 IP。
|
||||
app.getHttpAdapter()
|
||||
.getInstance()
|
||||
.set('trust proxy', config.trustedProxyCidrs);
|
||||
@@ -68,6 +48,7 @@ async function bootstrap() {
|
||||
],
|
||||
exposedHeaders: ['X-Request-Id'],
|
||||
});
|
||||
// Helmet、body 限制、请求 ID 与全局错误过滤器必须在业务路由前注册。
|
||||
app.use(helmet({ contentSecurityPolicy: false }));
|
||||
app.useBodyParser('json', { limit: config.API_BODY_LIMIT_BYTES });
|
||||
app.useBodyParser('urlencoded', {
|
||||
@@ -79,6 +60,7 @@ async function bootstrap() {
|
||||
const typedRequest = request;
|
||||
const typedResponse = response;
|
||||
const suppliedId = typedRequest.headers['x-request-id'];
|
||||
// 合法调用方提供的 request ID 可贯穿上游链路;其他情况由服务端生成。
|
||||
const requestId =
|
||||
typeof suppliedId === 'string' &&
|
||||
/^[A-Za-z0-9_-]{8,128}$/.test(suppliedId)
|
||||
@@ -104,6 +86,7 @@ async function bootstrap() {
|
||||
app.enableShutdownHooks();
|
||||
|
||||
if (config.swaggerEnabled) {
|
||||
// Swagger 仅描述运行时已注册路由;冻结接口契约仍以 docs/api 为准。
|
||||
const swaggerConfig = new DocumentBuilder()
|
||||
.setTitle('Atlas Seller Kit API')
|
||||
.setDescription('Atlas 卖家工作台 HTTP API 文档')
|
||||
@@ -122,30 +105,40 @@ async function bootstrap() {
|
||||
});
|
||||
}
|
||||
|
||||
return { app, config, logger };
|
||||
}
|
||||
|
||||
export async function bootstrap() {
|
||||
const { app, config, logger } = await createApplication();
|
||||
await app.listen(config.API_PORT);
|
||||
logger.log('api_started', {
|
||||
port: config.API_PORT,
|
||||
swagger_enabled: config.swaggerEnabled,
|
||||
});
|
||||
openSwaggerInDevelopment(config, logger);
|
||||
}
|
||||
|
||||
void bootstrap().catch((error: unknown) => {
|
||||
const details =
|
||||
error instanceof Error
|
||||
? {
|
||||
name: error.name,
|
||||
message: error.message,
|
||||
stack: error.stack,
|
||||
}
|
||||
: error;
|
||||
console.error(
|
||||
JSON.stringify({
|
||||
timestamp: new Date().toISOString(),
|
||||
level: 'error',
|
||||
message: 'api_startup_failed',
|
||||
error: details,
|
||||
}),
|
||||
);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
// 测试复用应用工厂时不自动监听固定端口,只有直接运行入口才启动服务。
|
||||
if (
|
||||
process.argv[1] &&
|
||||
resolve(process.argv[1]) === fileURLToPath(import.meta.url)
|
||||
) {
|
||||
void bootstrap().catch((error: unknown) => {
|
||||
const details =
|
||||
error instanceof Error
|
||||
? {
|
||||
name: error.name,
|
||||
message: error.message,
|
||||
stack: error.stack,
|
||||
}
|
||||
: error;
|
||||
console.error(
|
||||
JSON.stringify({
|
||||
timestamp: new Date().toISOString(),
|
||||
level: 'error',
|
||||
message: 'api_startup_failed',
|
||||
error: details,
|
||||
}),
|
||||
);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { Inject, Injectable, OnModuleDestroy } from '@nestjs/common';
|
||||
import {
|
||||
Inject,
|
||||
Injectable,
|
||||
OnModuleDestroy,
|
||||
OnModuleInit,
|
||||
} from '@nestjs/common';
|
||||
import { createHmac } from 'node:crypto';
|
||||
import { Redis } from 'ioredis';
|
||||
import { ApiError } from '../common/api-error.js';
|
||||
@@ -8,17 +13,23 @@ type AuthAction = 'login' | 'register' | 'refresh';
|
||||
type Limit = { ip: number; email?: number };
|
||||
|
||||
@Injectable()
|
||||
export class AuthRateLimiter implements OnModuleDestroy {
|
||||
export class AuthRateLimiter implements OnModuleInit, OnModuleDestroy {
|
||||
private readonly redis: Redis;
|
||||
|
||||
public constructor(@Inject(APP_CONFIG) private readonly config: AppConfig) {
|
||||
// Redis makes counters shared across API processes instead of resetting per instance.
|
||||
// Redis 让限流计数在多个 API 实例间共享,不会随单个实例重启清零。
|
||||
this.redis = new Redis(config.REDIS_URL, {
|
||||
enableOfflineQueue: false,
|
||||
lazyConnect: true,
|
||||
maxRetriesPerRequest: 1,
|
||||
});
|
||||
}
|
||||
|
||||
public async onModuleInit(): Promise<void> {
|
||||
// 在开始接收认证请求前完成连接,避免首个请求命中 Redis 连接竞态而被误判为 503。
|
||||
await this.redis.connect();
|
||||
}
|
||||
|
||||
public async consume(
|
||||
action: AuthAction,
|
||||
identifiers: { ip: string | null; email?: string },
|
||||
@@ -41,6 +52,10 @@ export class AuthRateLimiter implements OnModuleDestroy {
|
||||
}
|
||||
|
||||
public async onModuleDestroy(): Promise<void> {
|
||||
if (this.redis.status !== 'ready') {
|
||||
this.redis.disconnect();
|
||||
return;
|
||||
}
|
||||
await this.redis.quit();
|
||||
}
|
||||
|
||||
@@ -56,10 +71,10 @@ export class AuthRateLimiter implements OnModuleDestroy {
|
||||
)
|
||||
.update(identifier)
|
||||
.digest('base64url');
|
||||
// The raw IP/email never becomes part of a Redis key or a loggable identifier.
|
||||
// Redis key 只保存 IP/邮箱的 HMAC,不暴露可被日志或运维工具读取的原文。
|
||||
const key = `atlas:auth-rate-limit:${action}:${dimension}:${digest}`;
|
||||
try {
|
||||
// INCR + first-write EXPIRE must be atomic or concurrent requests could leave a key unexpired.
|
||||
// INCR 与首次 EXPIRE 必须原子执行,避免并发下产生永不过期的限流 key。
|
||||
const count = await this.redis.eval(
|
||||
"local value = redis.call('INCR', KEYS[1]); if value == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]); end; return value;",
|
||||
1,
|
||||
@@ -75,7 +90,7 @@ export class AuthRateLimiter implements OnModuleDestroy {
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError) throw error;
|
||||
// Authentication fails closed: silently bypassing a broken shared limiter enables brute-force attacks.
|
||||
// 认证限流故障时必须拒绝请求;静默跳过会扩大暴力破解风险。
|
||||
throw new ApiError(
|
||||
503,
|
||||
'AUTH_RATE_LIMIT_UNAVAILABLE',
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import type { Database, DatabaseTransaction } from '@atlas/database';
|
||||
import { ApiError } from '../common/api-error.js';
|
||||
import { DATABASE } from '../database/database.module.js';
|
||||
|
||||
type PlatformRow = {
|
||||
id: string;
|
||||
code: string;
|
||||
name: string;
|
||||
capabilities: Record<string, unknown>;
|
||||
supported_currencies: string[];
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class PlatformsService {
|
||||
public constructor(@Inject(DATABASE) private readonly database: Database) {}
|
||||
|
||||
public async list() {
|
||||
const rows = await this.database.query<PlatformRow>(
|
||||
`SELECT p.id, p.code, p.name, p.capabilities,
|
||||
coalesce(array_agg(pcs.currency_code ORDER BY pcs.currency_code)
|
||||
FILTER (WHERE pcs.is_enabled AND c.is_enabled), ARRAY[]::char(3)[]) AS supported_currencies
|
||||
FROM atlas.platforms p
|
||||
LEFT JOIN atlas.platform_currency_support pcs ON pcs.platform_id = p.id
|
||||
LEFT JOIN atlas.currencies c ON c.code = pcs.currency_code
|
||||
WHERE p.status = 'active'
|
||||
GROUP BY p.id
|
||||
ORDER BY CASE WHEN p.code = 'OZON' THEN 0 ELSE 1 END, p.name`,
|
||||
);
|
||||
return rows.rows.map((platform) => ({
|
||||
id: platform.id,
|
||||
code: platform.code,
|
||||
name: platform.name,
|
||||
supported_currencies: platform.supported_currencies,
|
||||
// 能力未配置时使用 null,而不是把 Ozon 的市场或语言假设扩散到通用模型。
|
||||
default_market_code: stringCapability(
|
||||
platform.capabilities,
|
||||
'default_market_code',
|
||||
),
|
||||
default_locale: stringCapability(
|
||||
platform.capabilities,
|
||||
'default_locale',
|
||||
),
|
||||
}));
|
||||
}
|
||||
|
||||
public async context(workspaceId: string, platformId: string) {
|
||||
return this.database.workspaceTransaction(
|
||||
workspaceId,
|
||||
async (transaction) => {
|
||||
const platform = await this.requireActivePlatform(
|
||||
transaction,
|
||||
platformId,
|
||||
);
|
||||
const stores = await transaction.query<{
|
||||
id: string;
|
||||
name: string;
|
||||
status: string;
|
||||
credential_status: string;
|
||||
count: string;
|
||||
}>(
|
||||
`SELECT s.id, s.name, s.status, s.credential_status,
|
||||
count(*) OVER ()::text AS count
|
||||
FROM atlas.stores s
|
||||
WHERE s.platform_id = $1 AND s.deleted_at IS NULL AND s.is_default
|
||||
LIMIT 1`,
|
||||
[platformId],
|
||||
);
|
||||
// 默认门店不存在时仍要正确返回总数,不能用默认行的窗口函数猜测。
|
||||
const count = await transaction.query<{ count: string }>(
|
||||
`SELECT count(*)::text AS count FROM atlas.stores
|
||||
WHERE platform_id = $1 AND deleted_at IS NULL`,
|
||||
[platformId],
|
||||
);
|
||||
const defaultStore = stores.rows[0];
|
||||
return {
|
||||
platform: {
|
||||
id: platform.id,
|
||||
code: platform.code,
|
||||
name: platform.name,
|
||||
},
|
||||
default_store: defaultStore
|
||||
? {
|
||||
id: defaultStore.id,
|
||||
name: defaultStore.name,
|
||||
status: defaultStore.status,
|
||||
credential_status: defaultStore.credential_status,
|
||||
}
|
||||
: null,
|
||||
store_count: Number(count.rows[0]?.count ?? 0),
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private async requireActivePlatform(
|
||||
transaction: DatabaseTransaction,
|
||||
platformId: string,
|
||||
) {
|
||||
const rows = await transaction.query<{
|
||||
id: string;
|
||||
code: string;
|
||||
name: string;
|
||||
}>(
|
||||
`SELECT id, code, name FROM atlas.platforms WHERE id = $1 AND status = 'active'`,
|
||||
[platformId],
|
||||
);
|
||||
if (!rows.rows[0]) {
|
||||
throw new ApiError(
|
||||
422,
|
||||
'PLATFORM_UNAVAILABLE',
|
||||
'平台不存在或已停用',
|
||||
);
|
||||
}
|
||||
return rows.rows[0];
|
||||
}
|
||||
}
|
||||
|
||||
function stringCapability(
|
||||
capabilities: Record<string, unknown>,
|
||||
key: string,
|
||||
): string | null {
|
||||
const value = capabilities[key];
|
||||
return typeof value === 'string' ? value : null;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import {
|
||||
createCipheriv,
|
||||
createHash,
|
||||
createHmac,
|
||||
randomBytes,
|
||||
} from 'node:crypto';
|
||||
|
||||
export type EncryptedStoreSecret = {
|
||||
ciphertext: Buffer;
|
||||
nonce: Buffer;
|
||||
fingerprint: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* 密钥只在此边界短暂以明文存在。数据库保存 AES-GCM 密文和随机 nonce,
|
||||
* fingerprint 是不可逆 HMAC,仅用于安全地识别同一份密钥。
|
||||
*/
|
||||
export function encryptStoreSecret(
|
||||
plaintext: string,
|
||||
keyMaterial: string,
|
||||
): EncryptedStoreSecret {
|
||||
const key = createHash('sha256').update(keyMaterial).digest();
|
||||
const nonce = randomBytes(12);
|
||||
const cipher = createCipheriv('aes-256-gcm', key, nonce);
|
||||
const ciphertext = Buffer.concat([
|
||||
cipher.update(plaintext, 'utf8'),
|
||||
cipher.final(),
|
||||
cipher.getAuthTag(),
|
||||
]);
|
||||
return {
|
||||
ciphertext,
|
||||
nonce,
|
||||
fingerprint: createHmac('sha256', key)
|
||||
.update(plaintext)
|
||||
.digest('base64url'),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Headers,
|
||||
HttpCode,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
Res,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
ApiAcceptedResponse,
|
||||
ApiBearerAuth,
|
||||
ApiNoContentResponse,
|
||||
ApiOkResponse,
|
||||
ApiOperation,
|
||||
ApiTags,
|
||||
} from '@nestjs/swagger';
|
||||
import {
|
||||
createStoreRequestSchema,
|
||||
listStoresQuerySchema,
|
||||
updateStoreRequestSchema,
|
||||
} from '@atlas/contracts';
|
||||
import { z } from 'zod';
|
||||
import { ApiError } from '../common/api-error.js';
|
||||
import type { AuthenticatedRequest } from '../auth/auth.guard.js';
|
||||
import { CurrentWorkspace } from '../workspace/current-workspace.decorator.js';
|
||||
import type { Workspace } from '@atlas/contracts';
|
||||
import { PlatformsService } from './platforms.service.js';
|
||||
import { StoresService } from './stores.service.js';
|
||||
|
||||
type HttpResponse = { status: (status: number) => HttpResponse };
|
||||
|
||||
@ApiTags('Platforms')
|
||||
@ApiBearerAuth('access-token')
|
||||
@Controller()
|
||||
export class PlatformsController {
|
||||
public constructor(private readonly platformsService: PlatformsService) {}
|
||||
|
||||
@Get('platforms')
|
||||
@ApiOperation({ summary: '获取已启用的平台及非敏感能力目录' })
|
||||
@ApiOkResponse({ description: '平台目录' })
|
||||
public async list() {
|
||||
return { data: await this.platformsService.list() };
|
||||
}
|
||||
|
||||
@Get('platform-context')
|
||||
@ApiOperation({ summary: '获取页头所选平台的默认门店上下文' })
|
||||
@ApiOkResponse({ description: '平台、默认门店和门店总数' })
|
||||
public async context(
|
||||
@Headers('x-atlas-platform-id') platformId: string | undefined,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
) {
|
||||
if (!platformId) {
|
||||
throw new ApiError(
|
||||
400,
|
||||
'PLATFORM_CONTEXT_REQUIRED',
|
||||
'请求缺少 X-Atlas-Platform-Id',
|
||||
);
|
||||
}
|
||||
return {
|
||||
data: await this.platformsService.context(
|
||||
workspace.id,
|
||||
requireUuid('X-Atlas-Platform-Id', platformId),
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@ApiTags('Stores')
|
||||
@ApiBearerAuth('access-token')
|
||||
@Controller('stores')
|
||||
export class StoresController {
|
||||
public constructor(private readonly storesService: StoresService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: '按平台分页列出当前工作空间的门店' })
|
||||
@ApiOkResponse({ description: '门店列表与不透明游标' })
|
||||
public async list(
|
||||
@Query() query: unknown,
|
||||
@Headers('x-atlas-platform-id') platformHeader: string | undefined,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
) {
|
||||
if (platformHeader) {
|
||||
throw new ApiError(
|
||||
400,
|
||||
'PLATFORM_CONTEXT_CONFLICT',
|
||||
'门店管理列表不能同时使用平台 header 和 platform_id 查询参数',
|
||||
);
|
||||
}
|
||||
return this.storesService.list(
|
||||
workspace.id,
|
||||
parse(listStoresQuerySchema, query),
|
||||
);
|
||||
}
|
||||
|
||||
@Get(':storeId')
|
||||
@ApiOperation({ summary: '读取单个门店' })
|
||||
public async get(
|
||||
@Param('storeId') storeId: string,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return {
|
||||
data: await this.storesService.get(
|
||||
workspace.id,
|
||||
requireUuid('store_id', storeId),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: '创建门店连接,并请求异步凭据验证' })
|
||||
@ApiAcceptedResponse({ description: '已加密保存凭据,并创建验证操作' })
|
||||
public async create(
|
||||
@Body() body: unknown,
|
||||
@Headers('idempotency-key') idempotencyKey: string | undefined,
|
||||
@Req() request: AuthenticatedRequest,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@Res({ passthrough: true }) response: HttpResponse,
|
||||
) {
|
||||
return withStatus(
|
||||
response,
|
||||
await this.storesService.create(
|
||||
workspace.id,
|
||||
request.auth.userId,
|
||||
requireIdempotencyKey(idempotencyKey),
|
||||
parse(createStoreRequestSchema, body),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@Patch(':storeId')
|
||||
@ApiOperation({ summary: '按版本编辑门店;更新密钥会重新请求验证' })
|
||||
@ApiOkResponse({ description: '普通字段已更新' })
|
||||
@ApiAcceptedResponse({ description: '新密钥已保存,并创建验证操作' })
|
||||
public async update(
|
||||
@Param('storeId') storeId: string,
|
||||
@Body() body: unknown,
|
||||
@Headers('idempotency-key') idempotencyKey: string | undefined,
|
||||
@Headers('if-match') ifMatch: string | undefined,
|
||||
@Req() request: AuthenticatedRequest,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@Res({ passthrough: true }) response: HttpResponse,
|
||||
) {
|
||||
return withStatus(
|
||||
response,
|
||||
await this.storesService.update(
|
||||
workspace.id,
|
||||
request.auth.userId,
|
||||
requireUuid('store_id', storeId),
|
||||
requireIdempotencyKey(idempotencyKey),
|
||||
parseRevision(ifMatch),
|
||||
parse(updateStoreRequestSchema, body),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@Post(':storeId/set-default')
|
||||
@ApiOperation({ summary: '设为当前平台默认门店' })
|
||||
public async setDefault(
|
||||
@Param('storeId') storeId: string,
|
||||
@Headers('idempotency-key') idempotencyKey: string | undefined,
|
||||
@Req() request: AuthenticatedRequest,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@Res({ passthrough: true }) response: HttpResponse,
|
||||
) {
|
||||
return withStatus(
|
||||
response,
|
||||
await this.storesService.setDefault(
|
||||
workspace.id,
|
||||
request.auth.userId,
|
||||
requireUuid('store_id', storeId),
|
||||
requireIdempotencyKey(idempotencyKey),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@Post(':storeId/credential-verifications')
|
||||
@ApiOperation({ summary: '手动请求重新验证门店凭据' })
|
||||
@ApiAcceptedResponse({ description: '凭据验证操作已入队' })
|
||||
public async credentialVerification(
|
||||
@Param('storeId') storeId: string,
|
||||
@Headers('idempotency-key') idempotencyKey: string | undefined,
|
||||
@Req() request: AuthenticatedRequest,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@Res({ passthrough: true }) response: HttpResponse,
|
||||
) {
|
||||
return withStatus(
|
||||
response,
|
||||
await this.storesService.requestCredentialVerification(
|
||||
workspace.id,
|
||||
request.auth.userId,
|
||||
requireUuid('store_id', storeId),
|
||||
requireIdempotencyKey(idempotencyKey),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@Post(':storeId/warehouse-syncs')
|
||||
@ApiOperation({ summary: '请求异步同步门店仓库' })
|
||||
@ApiAcceptedResponse({ description: '仓库同步操作已入队' })
|
||||
public async warehouseSync(
|
||||
@Param('storeId') storeId: string,
|
||||
@Headers('idempotency-key') idempotencyKey: string | undefined,
|
||||
@Req() request: AuthenticatedRequest,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@Res({ passthrough: true }) response: HttpResponse,
|
||||
) {
|
||||
return withStatus(
|
||||
response,
|
||||
await this.storesService.requestWarehouseSync(
|
||||
workspace.id,
|
||||
request.auth.userId,
|
||||
requireUuid('store_id', storeId),
|
||||
requireIdempotencyKey(idempotencyKey),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@Get(':storeId/warehouses')
|
||||
@ApiOperation({ summary: '读取最近成功同步的仓库摘要' })
|
||||
public async warehouses(
|
||||
@Param('storeId') storeId: string,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.storesService.warehouses(
|
||||
workspace.id,
|
||||
requireUuid('store_id', storeId),
|
||||
);
|
||||
}
|
||||
|
||||
@Delete(':storeId')
|
||||
@HttpCode(204)
|
||||
@ApiOperation({ summary: '软删除门店连接并撤销当前密钥' })
|
||||
@ApiNoContentResponse({ description: '门店已删除' })
|
||||
public async remove(
|
||||
@Param('storeId') storeId: string,
|
||||
@Headers('idempotency-key') idempotencyKey: string | undefined,
|
||||
@Req() request: AuthenticatedRequest,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@Res({ passthrough: true }) response: HttpResponse,
|
||||
) {
|
||||
return withStatus(
|
||||
response,
|
||||
await this.storesService.remove(
|
||||
workspace.id,
|
||||
request.auth.userId,
|
||||
requireUuid('store_id', storeId),
|
||||
requireIdempotencyKey(idempotencyKey),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiTags('Operations')
|
||||
@ApiBearerAuth('access-token')
|
||||
@Controller('operations')
|
||||
export class OperationsController {
|
||||
public constructor(private readonly storesService: StoresService) {}
|
||||
|
||||
@Get(':operationId')
|
||||
@ApiOperation({ summary: '读取当前工作空间的异步操作状态' })
|
||||
public async get(
|
||||
@Param('operationId') operationId: string,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return {
|
||||
data: await this.storesService.operation(
|
||||
workspace.id,
|
||||
requireUuid('operation_id', operationId),
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function withStatus(
|
||||
response: HttpResponse,
|
||||
result: { status: number; body: unknown },
|
||||
) {
|
||||
response.status(result.status);
|
||||
return result.body;
|
||||
}
|
||||
|
||||
function requireIdempotencyKey(value: string | undefined): string {
|
||||
if (!value) {
|
||||
throw new ApiError(
|
||||
400,
|
||||
'IDEMPOTENCY_KEY_REQUIRED',
|
||||
'请求缺少 Idempotency-Key',
|
||||
);
|
||||
}
|
||||
return requireUuid('Idempotency-Key', value);
|
||||
}
|
||||
|
||||
function requireUuid(field: string, value: string): string {
|
||||
if (z.uuid().safeParse(value).success) return value;
|
||||
throw new ApiError(422, 'VALIDATION_FAILED', '请求参数不符合要求', [
|
||||
{ field, code: 'INVALID_FIELD', message: `${field} 必须是 UUID` },
|
||||
]);
|
||||
}
|
||||
|
||||
function parseRevision(value: string | undefined): number {
|
||||
const match = value?.match(/^"([1-9]\d*)"$/);
|
||||
if (!match) {
|
||||
throw new ApiError(
|
||||
400,
|
||||
'IF_MATCH_REQUIRED',
|
||||
'请求必须携带形如 "1" 的 If-Match',
|
||||
);
|
||||
}
|
||||
return Number(match[1]);
|
||||
}
|
||||
|
||||
function parse<T>(schema: z.ZodType<T>, value: unknown): T {
|
||||
const result = schema.safeParse(value);
|
||||
if (result.success) return result.data;
|
||||
throw new ApiError(
|
||||
422,
|
||||
'VALIDATION_FAILED',
|
||||
'请求参数不符合要求',
|
||||
result.error.issues.map((issue) => ({
|
||||
field: issue.path.join('.'),
|
||||
code: 'INVALID_FIELD',
|
||||
message: issue.message,
|
||||
})),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { IdempotencyService } from '../common/idempotency.service.js';
|
||||
import {
|
||||
OperationsController,
|
||||
PlatformsController,
|
||||
StoresController,
|
||||
} from './stores.controller.js';
|
||||
import { PlatformsService } from './platforms.service.js';
|
||||
import { StoresService } from './stores.service.js';
|
||||
|
||||
@Module({
|
||||
controllers: [PlatformsController, StoresController, OperationsController],
|
||||
providers: [IdempotencyService, PlatformsService, StoresService],
|
||||
})
|
||||
export class StoresModule {}
|
||||
@@ -0,0 +1,729 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import type {
|
||||
CreateStoreRequest,
|
||||
ListStoresQuery,
|
||||
Operation,
|
||||
Store,
|
||||
UpdateStoreRequest,
|
||||
} from '@atlas/contracts';
|
||||
import type { Database, DatabaseTransaction } from '@atlas/database';
|
||||
import { ApiError } from '../common/api-error.js';
|
||||
import { IdempotencyService } from '../common/idempotency.service.js';
|
||||
import { APP_CONFIG, type AppConfig } from '../config/app-config.module.js';
|
||||
import { DATABASE } from '../database/database.module.js';
|
||||
import { encryptStoreSecret } from './store-secret.crypto.js';
|
||||
|
||||
type StoreRow = Omit<Store, keyof { created_at: never; updated_at: never }> & {
|
||||
credential_checked_at: Date | string | null;
|
||||
api_key_expires_at: Date | string | null;
|
||||
product_limit_checked_at: Date | string | null;
|
||||
warehouses_synced_at: Date | string | null;
|
||||
created_at: Date | string;
|
||||
updated_at: Date | string;
|
||||
};
|
||||
type StoreLockRow = {
|
||||
id: string;
|
||||
platform_id: string;
|
||||
revision: number;
|
||||
is_default: boolean;
|
||||
status: string;
|
||||
};
|
||||
type OperationRow = {
|
||||
id: string;
|
||||
kind: string;
|
||||
status: string;
|
||||
created_at: Date | string;
|
||||
completed_at: Date | string | null;
|
||||
error_code: string | null;
|
||||
error_message: string | null;
|
||||
};
|
||||
type WarehouseRow = {
|
||||
id: string;
|
||||
platform_warehouse_id: string;
|
||||
name: string;
|
||||
fulfillment: string;
|
||||
is_rfbs: boolean | null;
|
||||
status: string;
|
||||
synced_at: Date | string;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class StoresService {
|
||||
public constructor(
|
||||
private readonly idempotency: IdempotencyService,
|
||||
@Inject(DATABASE) private readonly database: Database,
|
||||
@Inject(APP_CONFIG) private readonly config: AppConfig,
|
||||
) {}
|
||||
|
||||
public async list(workspaceId: string, query: ListStoresQuery) {
|
||||
const cursor = query.cursor ? decodeCursor(query.cursor) : null;
|
||||
return this.database.workspaceTransaction(
|
||||
workspaceId,
|
||||
async (transaction: DatabaseTransaction) => {
|
||||
const rows = await transaction.query<StoreRow>(
|
||||
`${storeSelect}
|
||||
WHERE s.platform_id = $1 AND s.deleted_at IS NULL
|
||||
AND ($2::timestamptz IS NULL OR (s.created_at, s.id) < ($2::timestamptz, $3::uuid))
|
||||
GROUP BY s.id, binding.value
|
||||
ORDER BY s.created_at DESC, s.id DESC
|
||||
LIMIT $4`,
|
||||
[
|
||||
query.platform_id,
|
||||
cursor?.createdAt ?? null,
|
||||
cursor?.id ?? null,
|
||||
query.limit + 1,
|
||||
],
|
||||
);
|
||||
const hasMore = rows.rows.length > query.limit;
|
||||
const items = rows.rows.slice(0, query.limit).map(toStore);
|
||||
const last = items.at(-1);
|
||||
return {
|
||||
data: items,
|
||||
meta: {
|
||||
next_cursor:
|
||||
hasMore && last
|
||||
? encodeCursor(last.created_at, last.id)
|
||||
: null,
|
||||
has_more: hasMore,
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
public async get(workspaceId: string, storeId: string): Promise<Store> {
|
||||
return this.database.workspaceTransaction(
|
||||
workspaceId,
|
||||
async (transaction: DatabaseTransaction) =>
|
||||
this.requireStore(transaction, storeId),
|
||||
);
|
||||
}
|
||||
|
||||
public async create(
|
||||
workspaceId: string,
|
||||
userId: string,
|
||||
idempotencyKey: string,
|
||||
input: CreateStoreRequest,
|
||||
) {
|
||||
return this.idempotency.run(
|
||||
{
|
||||
workspaceId,
|
||||
userId,
|
||||
method: 'POST',
|
||||
path: '/api/stores',
|
||||
key: idempotencyKey,
|
||||
request: input,
|
||||
},
|
||||
async (transaction) => {
|
||||
await this.assertPlatformCurrency(
|
||||
transaction,
|
||||
input.platform_id,
|
||||
input.currency_code,
|
||||
);
|
||||
// 同一平台的默认店铺修改串行化,避免两个并发创建都错误地判断自己是首店。
|
||||
await lockPlatform(transaction, workspaceId, input.platform_id);
|
||||
const existing = await transaction.query<{ id: string }>(
|
||||
`SELECT id FROM atlas.stores
|
||||
WHERE platform_id = $1 AND platform_client_id = $2
|
||||
LIMIT 1`,
|
||||
[input.platform_id, input.client_id],
|
||||
);
|
||||
if (existing.rows[0]) {
|
||||
throw new ApiError(
|
||||
409,
|
||||
'STORE_CONNECTION_ALREADY_EXISTS',
|
||||
'该平台账户已绑定为门店',
|
||||
);
|
||||
}
|
||||
const currentStores = await transaction.query<{
|
||||
count: string;
|
||||
}>(
|
||||
`SELECT count(*)::text AS count FROM atlas.stores
|
||||
WHERE platform_id = $1 AND deleted_at IS NULL`,
|
||||
[input.platform_id],
|
||||
);
|
||||
const becomesDefault =
|
||||
Number(currentStores.rows[0]?.count ?? 0) === 0 ||
|
||||
input.is_default;
|
||||
if (becomesDefault) {
|
||||
await transaction.query(
|
||||
`UPDATE atlas.stores SET is_default = false, revision = revision + 1, updated_at = now()
|
||||
WHERE platform_id = $1 AND is_default AND deleted_at IS NULL`,
|
||||
[input.platform_id],
|
||||
);
|
||||
}
|
||||
const created = await transaction.query<{ id: string }>(
|
||||
`INSERT INTO atlas.stores
|
||||
(workspace_id, platform_id, name, platform_client_id, currency_code, is_default, note)
|
||||
VALUES (current_setting('app.workspace_id')::uuid, $1, $2, $3, $4, $5, $6)
|
||||
RETURNING id`,
|
||||
[
|
||||
input.platform_id,
|
||||
input.name,
|
||||
input.client_id,
|
||||
input.currency_code,
|
||||
becomesDefault,
|
||||
input.note ?? null,
|
||||
],
|
||||
);
|
||||
const storeId = created.rows[0].id;
|
||||
await this.replaceApiKey(transaction, storeId, input.api_key);
|
||||
const operation = await this.createOperation(
|
||||
transaction,
|
||||
userId,
|
||||
storeId,
|
||||
'store_credential_verification',
|
||||
);
|
||||
return {
|
||||
status: 202,
|
||||
body: {
|
||||
data: {
|
||||
store: await this.requireStore(
|
||||
transaction,
|
||||
storeId,
|
||||
),
|
||||
operation,
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
public async update(
|
||||
workspaceId: string,
|
||||
userId: string,
|
||||
storeId: string,
|
||||
idempotencyKey: string,
|
||||
revision: number,
|
||||
input: UpdateStoreRequest,
|
||||
) {
|
||||
return this.idempotency.run(
|
||||
{
|
||||
workspaceId,
|
||||
userId,
|
||||
method: 'PATCH',
|
||||
path: `/api/stores/${storeId}`,
|
||||
key: idempotencyKey,
|
||||
request: { if_match: revision, ...input },
|
||||
},
|
||||
async (transaction) => {
|
||||
const current = await this.lockStore(transaction, storeId);
|
||||
this.assertRevision(current, revision);
|
||||
if (input.currency_code) {
|
||||
await this.assertPlatformCurrency(
|
||||
transaction,
|
||||
current.platform_id,
|
||||
input.currency_code,
|
||||
);
|
||||
}
|
||||
const replacingKey = input.api_key !== undefined;
|
||||
await transaction.query(
|
||||
`UPDATE atlas.stores
|
||||
SET name = COALESCE($1, name), currency_code = COALESCE($2, currency_code),
|
||||
note = CASE WHEN $3 THEN $4 ELSE note END,
|
||||
status = CASE WHEN $5 THEN 'verifying'::atlas.store_status ELSE status END,
|
||||
credential_status = CASE WHEN $5 THEN 'unknown'::atlas.credential_status ELSE credential_status END,
|
||||
last_error_code = CASE WHEN $5 THEN NULL ELSE last_error_code END,
|
||||
last_error_message = CASE WHEN $5 THEN NULL ELSE last_error_message END,
|
||||
last_error_at = CASE WHEN $5 THEN NULL ELSE last_error_at END,
|
||||
revision = revision + 1, updated_at = now()
|
||||
WHERE id = $6`,
|
||||
[
|
||||
input.name ?? null,
|
||||
input.currency_code ?? null,
|
||||
Object.hasOwn(input, 'note'),
|
||||
input.note ?? null,
|
||||
replacingKey,
|
||||
storeId,
|
||||
],
|
||||
);
|
||||
if (input.api_key !== undefined) {
|
||||
await this.replaceApiKey(
|
||||
transaction,
|
||||
storeId,
|
||||
input.api_key,
|
||||
);
|
||||
const operation = await this.createOperation(
|
||||
transaction,
|
||||
userId,
|
||||
storeId,
|
||||
'store_credential_verification',
|
||||
);
|
||||
return {
|
||||
status: 202,
|
||||
body: {
|
||||
data: {
|
||||
store: await this.requireStore(
|
||||
transaction,
|
||||
storeId,
|
||||
),
|
||||
operation,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
status: 200,
|
||||
body: {
|
||||
data: await this.requireStore(transaction, storeId),
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
public async setDefault(
|
||||
workspaceId: string,
|
||||
userId: string,
|
||||
storeId: string,
|
||||
idempotencyKey: string,
|
||||
) {
|
||||
return this.idempotency.run(
|
||||
{
|
||||
workspaceId,
|
||||
userId,
|
||||
method: 'POST',
|
||||
path: `/api/stores/${storeId}/set-default`,
|
||||
key: idempotencyKey,
|
||||
request: {},
|
||||
},
|
||||
async (transaction) => {
|
||||
const current = await this.lockStore(transaction, storeId);
|
||||
await lockPlatform(
|
||||
transaction,
|
||||
workspaceId,
|
||||
current.platform_id,
|
||||
);
|
||||
await transaction.query(
|
||||
`UPDATE atlas.stores SET is_default = false, revision = revision + 1, updated_at = now()
|
||||
WHERE platform_id = $1 AND is_default AND deleted_at IS NULL AND id <> $2`,
|
||||
[current.platform_id, storeId],
|
||||
);
|
||||
if (!current.is_default) {
|
||||
await transaction.query(
|
||||
`UPDATE atlas.stores SET is_default = true, revision = revision + 1, updated_at = now()
|
||||
WHERE id = $1`,
|
||||
[storeId],
|
||||
);
|
||||
}
|
||||
return {
|
||||
status: 200,
|
||||
body: {
|
||||
data: await this.requireStore(transaction, storeId),
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
public async requestCredentialVerification(
|
||||
workspaceId: string,
|
||||
userId: string,
|
||||
storeId: string,
|
||||
idempotencyKey: string,
|
||||
) {
|
||||
return this.requestOperation(
|
||||
workspaceId,
|
||||
userId,
|
||||
storeId,
|
||||
idempotencyKey,
|
||||
'credential-verifications',
|
||||
'store_credential_verification',
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
public async requestWarehouseSync(
|
||||
workspaceId: string,
|
||||
userId: string,
|
||||
storeId: string,
|
||||
idempotencyKey: string,
|
||||
) {
|
||||
return this.requestOperation(
|
||||
workspaceId,
|
||||
userId,
|
||||
storeId,
|
||||
idempotencyKey,
|
||||
'warehouse-syncs',
|
||||
'store_warehouse_sync',
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
public async remove(
|
||||
workspaceId: string,
|
||||
userId: string,
|
||||
storeId: string,
|
||||
idempotencyKey: string,
|
||||
) {
|
||||
return this.idempotency.run(
|
||||
{
|
||||
workspaceId,
|
||||
userId,
|
||||
method: 'DELETE',
|
||||
path: `/api/stores/${storeId}`,
|
||||
key: idempotencyKey,
|
||||
request: {},
|
||||
},
|
||||
async (transaction) => {
|
||||
const current = await this.lockStore(transaction, storeId);
|
||||
if (current.is_default) {
|
||||
const replacement = await transaction.query<{ id: string }>(
|
||||
`SELECT id FROM atlas.stores
|
||||
WHERE platform_id = $1 AND id <> $2 AND deleted_at IS NULL LIMIT 1`,
|
||||
[current.platform_id, storeId],
|
||||
);
|
||||
if (replacement.rows[0]) {
|
||||
throw new ApiError(
|
||||
422,
|
||||
'DEFAULT_STORE_REPLACEMENT_REQUIRED',
|
||||
'删除默认门店前必须先选择同平台的其他默认门店',
|
||||
);
|
||||
}
|
||||
}
|
||||
await transaction.query(
|
||||
`UPDATE atlas.stores
|
||||
SET deleted_at = now(), status = 'deleted', is_default = false,
|
||||
revision = revision + 1, updated_at = now()
|
||||
WHERE id = $1`,
|
||||
[storeId],
|
||||
);
|
||||
// 删除连接后立刻撤销可用密钥,避免后台任务或未来恢复流程继续使用它。
|
||||
await transaction.query(
|
||||
`UPDATE atlas.store_secrets SET revoked_at = now(), updated_at = now()
|
||||
WHERE store_id = $1 AND revoked_at IS NULL`,
|
||||
[storeId],
|
||||
);
|
||||
return { status: 204, body: null };
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
public async warehouses(workspaceId: string, storeId: string) {
|
||||
return this.database.workspaceTransaction(
|
||||
workspaceId,
|
||||
async (transaction: DatabaseTransaction) => {
|
||||
const store = await this.requireStore(transaction, storeId);
|
||||
const rows = await transaction.query<WarehouseRow>(
|
||||
`SELECT id, platform_warehouse_id, name, fulfillment, is_rfbs, status, synced_at
|
||||
FROM atlas.store_warehouses WHERE store_id = $1 ORDER BY name, id`,
|
||||
[storeId],
|
||||
);
|
||||
return {
|
||||
data: rows.rows.map((row) => ({
|
||||
...row,
|
||||
synced_at: toIso(row.synced_at),
|
||||
})),
|
||||
meta: { warehouses_synced_at: store.warehouses_synced_at },
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
public async operation(workspaceId: string, operationId: string) {
|
||||
return this.database.workspaceTransaction(
|
||||
workspaceId,
|
||||
async (transaction: DatabaseTransaction) => {
|
||||
const rows = await transaction.query<OperationRow>(
|
||||
`SELECT id, kind, status, created_at, completed_at, error_code, error_message
|
||||
FROM atlas.operations WHERE id = $1`,
|
||||
[operationId],
|
||||
);
|
||||
if (!rows.rows[0]) throw notFound('操作');
|
||||
return toOperation(rows.rows[0]);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private async requestOperation(
|
||||
workspaceId: string,
|
||||
userId: string,
|
||||
storeId: string,
|
||||
idempotencyKey: string,
|
||||
pathSuffix: string,
|
||||
kind: string,
|
||||
requiresValidCredential: boolean,
|
||||
) {
|
||||
return this.idempotency.run(
|
||||
{
|
||||
workspaceId,
|
||||
userId,
|
||||
method: 'POST',
|
||||
path: `/api/stores/${storeId}/${pathSuffix}`,
|
||||
key: idempotencyKey,
|
||||
request: {},
|
||||
},
|
||||
async (transaction) => {
|
||||
const store = await this.requireStore(transaction, storeId);
|
||||
if (store.status === 'disabled') {
|
||||
throw new ApiError(422, 'STORE_DISABLED', '门店已停用');
|
||||
}
|
||||
if (
|
||||
requiresValidCredential &&
|
||||
store.credential_status !== 'valid'
|
||||
) {
|
||||
throw new ApiError(
|
||||
422,
|
||||
'STORE_CREDENTIAL_UNAVAILABLE',
|
||||
'门店凭据尚未验证通过,无法同步仓库',
|
||||
);
|
||||
}
|
||||
const operation = await this.createOperation(
|
||||
transaction,
|
||||
userId,
|
||||
storeId,
|
||||
kind,
|
||||
);
|
||||
return { status: 202, body: { data: { operation } } };
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private async assertPlatformCurrency(
|
||||
transaction: DatabaseTransaction,
|
||||
platformId: string,
|
||||
currencyCode: string,
|
||||
) {
|
||||
const platform = await transaction.query<{ id: string }>(
|
||||
`SELECT id FROM atlas.platforms WHERE id = $1 AND status = 'active'`,
|
||||
[platformId],
|
||||
);
|
||||
if (!platform.rows[0]) {
|
||||
throw new ApiError(
|
||||
422,
|
||||
'PLATFORM_UNAVAILABLE',
|
||||
'平台不存在或已停用',
|
||||
);
|
||||
}
|
||||
const supported = await transaction.query<{ currency_code: string }>(
|
||||
`SELECT pcs.currency_code FROM atlas.platform_currency_support pcs
|
||||
JOIN atlas.currencies c ON c.code = pcs.currency_code
|
||||
WHERE pcs.platform_id = $1 AND pcs.currency_code = $2
|
||||
AND pcs.is_enabled AND c.is_enabled`,
|
||||
[platformId, currencyCode],
|
||||
);
|
||||
if (!supported.rows[0]) {
|
||||
throw new ApiError(
|
||||
422,
|
||||
'PLATFORM_CURRENCY_UNSUPPORTED',
|
||||
'该平台不支持此默认计价币种',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async lockStore(transaction: DatabaseTransaction, storeId: string) {
|
||||
const rows = await transaction.query<StoreLockRow>(
|
||||
`SELECT id, platform_id, revision, is_default, status
|
||||
FROM atlas.stores WHERE id = $1 AND deleted_at IS NULL FOR UPDATE`,
|
||||
[storeId],
|
||||
);
|
||||
if (!rows.rows[0]) throw notFound('门店');
|
||||
return rows.rows[0];
|
||||
}
|
||||
|
||||
private assertRevision(current: StoreLockRow, expected: number) {
|
||||
if (current.revision !== expected) {
|
||||
throw new ApiError(
|
||||
409,
|
||||
'VERSION_CONFLICT',
|
||||
'门店已被其他操作更新',
|
||||
[
|
||||
{
|
||||
field: 'If-Match',
|
||||
code: 'VERSION_CONFLICT',
|
||||
message: `当前版本为 ${current.revision}`,
|
||||
current_revision: current.revision,
|
||||
},
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async replaceApiKey(
|
||||
transaction: DatabaseTransaction,
|
||||
storeId: string,
|
||||
apiKey: string,
|
||||
) {
|
||||
const secret = encryptStoreSecret(
|
||||
apiKey,
|
||||
this.config.STORE_SECRET_ENCRYPTION_KEY,
|
||||
);
|
||||
const existing = await transaction.query<{ id: string }>(
|
||||
`SELECT id FROM atlas.store_secrets
|
||||
WHERE store_id = $1 AND kind = 'seller_api_key' AND fingerprint = $2
|
||||
FOR UPDATE`,
|
||||
[storeId, secret.fingerprint],
|
||||
);
|
||||
await transaction.query(
|
||||
`UPDATE atlas.store_secrets SET revoked_at = now(), updated_at = now()
|
||||
WHERE store_id = $1 AND kind = 'seller_api_key' AND revoked_at IS NULL`,
|
||||
[storeId],
|
||||
);
|
||||
if (existing.rows[0]) {
|
||||
// 同一密钥可被重新提交用于验证;恢复历史行避免违反防重指纹唯一约束。
|
||||
await transaction.query(
|
||||
`UPDATE atlas.store_secrets
|
||||
SET secret_ciphertext = $1, secret_nonce = $2, encryption_key_version = $3,
|
||||
status = 'unknown', revoked_at = NULL, updated_at = now()
|
||||
WHERE id = $4`,
|
||||
[
|
||||
secret.ciphertext,
|
||||
secret.nonce,
|
||||
this.config.STORE_SECRET_ENCRYPTION_KEY_VERSION,
|
||||
existing.rows[0].id,
|
||||
],
|
||||
);
|
||||
return;
|
||||
}
|
||||
await transaction.query(
|
||||
`INSERT INTO atlas.store_secrets
|
||||
(workspace_id, store_id, kind, secret_ciphertext, secret_nonce, encryption_key_version, fingerprint)
|
||||
VALUES (current_setting('app.workspace_id')::uuid, $1, 'seller_api_key', $2, $3, $4, $5)`,
|
||||
[
|
||||
storeId,
|
||||
secret.ciphertext,
|
||||
secret.nonce,
|
||||
this.config.STORE_SECRET_ENCRYPTION_KEY_VERSION,
|
||||
secret.fingerprint,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
private async createOperation(
|
||||
transaction: DatabaseTransaction,
|
||||
userId: string,
|
||||
storeId: string,
|
||||
kind: string,
|
||||
): Promise<Operation> {
|
||||
const created = await transaction.query<OperationRow>(
|
||||
`INSERT INTO atlas.operations
|
||||
(workspace_id, kind, resource_type, resource_id, created_by_user_id)
|
||||
VALUES (current_setting('app.workspace_id')::uuid, $1, 'store', $2, $3)
|
||||
RETURNING id, kind, status, created_at, completed_at, error_code, error_message`,
|
||||
[kind, storeId, userId],
|
||||
);
|
||||
const operation = toOperation(created.rows[0]);
|
||||
await transaction.query(
|
||||
`INSERT INTO atlas.outbox_events
|
||||
(workspace_id, aggregate_type, aggregate_id, event_type, event_payload, deduplication_key)
|
||||
VALUES (current_setting('app.workspace_id')::uuid, 'store', $1, $2, $3, $4)`,
|
||||
[
|
||||
storeId,
|
||||
`${kind}.requested`,
|
||||
{ store_id: storeId, operation_id: operation.id },
|
||||
operation.id,
|
||||
],
|
||||
);
|
||||
return operation;
|
||||
}
|
||||
|
||||
private async requireStore(
|
||||
transaction: DatabaseTransaction,
|
||||
storeId: string,
|
||||
): Promise<Store> {
|
||||
const rows = await transaction.query<StoreRow>(
|
||||
`${storeSelect}
|
||||
WHERE s.id = $1 AND s.deleted_at IS NULL
|
||||
GROUP BY s.id, binding.value`,
|
||||
[storeId],
|
||||
);
|
||||
if (!rows.rows[0]) throw notFound('门店');
|
||||
return toStore(rows.rows[0]);
|
||||
}
|
||||
}
|
||||
|
||||
const storeSelect = `
|
||||
SELECT s.id, s.platform_id, s.name, s.platform_client_id, s.currency_code,
|
||||
s.is_default, s.note, s.status, s.credential_status, s.credential_checked_at,
|
||||
CASE WHEN s.last_error_code IS NULL THEN NULL
|
||||
ELSE jsonb_build_object('code', s.last_error_code, 'message', s.last_error_message, 'at', s.last_error_at)
|
||||
END AS last_error,
|
||||
s.api_key_expires_at, s.product_limit, s.product_limit_checked_at,
|
||||
count(sw.id)::integer AS warehouse_count, max(sw.synced_at) AS warehouses_synced_at,
|
||||
binding.value AS watermark_template, s.created_at, s.updated_at, s.revision
|
||||
FROM atlas.stores s
|
||||
LEFT JOIN atlas.store_warehouses sw ON sw.store_id = s.id
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT jsonb_build_object('id', wt.id, 'name', wt.name) AS value
|
||||
FROM atlas.store_watermark_bindings wb
|
||||
JOIN atlas.watermark_templates wt ON wt.id = wb.template_id
|
||||
WHERE wb.store_id = s.id AND wb.unbound_at IS NULL
|
||||
LIMIT 1
|
||||
) binding ON true`;
|
||||
|
||||
function toStore(row: StoreRow): Store {
|
||||
return {
|
||||
...row,
|
||||
credential_checked_at: toIso(row.credential_checked_at),
|
||||
api_key_expires_at: toIso(row.api_key_expires_at),
|
||||
product_limit_checked_at: toIso(row.product_limit_checked_at),
|
||||
warehouses_synced_at: toIso(row.warehouses_synced_at),
|
||||
created_at: toRequiredIso(row.created_at),
|
||||
updated_at: toRequiredIso(row.updated_at),
|
||||
cookie_status: null,
|
||||
};
|
||||
}
|
||||
|
||||
function toOperation(row: OperationRow): Operation {
|
||||
return {
|
||||
id: row.id,
|
||||
kind: row.kind,
|
||||
status: row.status,
|
||||
created_at: toRequiredIso(row.created_at),
|
||||
completed_at: toIso(row.completed_at),
|
||||
error:
|
||||
row.error_code && row.error_message
|
||||
? { code: row.error_code, message: row.error_message }
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
function toIso(value: Date | string | null): string | null {
|
||||
if (value === null) return null;
|
||||
return value instanceof Date ? value.toISOString() : value;
|
||||
}
|
||||
|
||||
function toRequiredIso(value: Date | string): string {
|
||||
return value instanceof Date ? value.toISOString() : value;
|
||||
}
|
||||
|
||||
function notFound(resource: string) {
|
||||
return new ApiError(404, 'RESOURCE_NOT_FOUND', `${resource}不存在`);
|
||||
}
|
||||
|
||||
async function lockPlatform(
|
||||
transaction: DatabaseTransaction,
|
||||
workspaceId: string,
|
||||
platformId: string,
|
||||
) {
|
||||
await transaction.query(
|
||||
`SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`,
|
||||
[`${workspaceId}:${platformId}`],
|
||||
);
|
||||
}
|
||||
|
||||
function encodeCursor(createdAt: string, id: string): string {
|
||||
return Buffer.from(JSON.stringify({ createdAt, id })).toString('base64url');
|
||||
}
|
||||
|
||||
function decodeCursor(cursor: string): { createdAt: string; id: string } {
|
||||
try {
|
||||
const value = JSON.parse(
|
||||
Buffer.from(cursor, 'base64url').toString('utf8'),
|
||||
) as { createdAt?: unknown; id?: unknown };
|
||||
if (
|
||||
typeof value.createdAt !== 'string' ||
|
||||
Number.isNaN(Date.parse(value.createdAt)) ||
|
||||
typeof value.id !== 'string' ||
|
||||
!/^[0-9a-f]{8}-[0-9a-f-]{27}$/i.test(value.id)
|
||||
) {
|
||||
throw new Error('invalid cursor');
|
||||
}
|
||||
return { createdAt: value.createdAt, id: value.id };
|
||||
} catch {
|
||||
throw new ApiError(422, 'VALIDATION_FAILED', '分页游标无效', [
|
||||
{ field: 'cursor', code: 'INVALID_FIELD', message: '分页游标无效' },
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { createParamDecorator, type ExecutionContext } from '@nestjs/common';
|
||||
import type { Workspace } from '@atlas/contracts';
|
||||
import type { WorkspaceAuthenticatedRequest } from './workspace-context.guard.js';
|
||||
|
||||
// 受保护接口经全局工作空间守卫验证后,只能从这里读取当前工作空间。
|
||||
export const CurrentWorkspace = createParamDecorator(
|
||||
(_data: unknown, context: ExecutionContext): Workspace => {
|
||||
const request = context
|
||||
.switchToHttp()
|
||||
.getRequest<WorkspaceAuthenticatedRequest>();
|
||||
return request.auth.workspace;
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,63 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Inject,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import type { Workspace } from '@atlas/contracts';
|
||||
import type { Database } from '@atlas/database';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { ApiError } from '../common/api-error.js';
|
||||
import { IS_PUBLIC_ENDPOINT } from '../common/public.decorator.js';
|
||||
import { DATABASE } from '../database/database.module.js';
|
||||
import type { AuthenticatedRequest } from '../auth/auth.guard.js';
|
||||
|
||||
export type WorkspaceAuthenticatedRequest = AuthenticatedRequest & {
|
||||
auth: AuthenticatedRequest['auth'] & { workspace: Workspace };
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class WorkspaceContextGuard implements CanActivate {
|
||||
public constructor(
|
||||
@Inject(Reflector) private readonly reflector: Reflector,
|
||||
@Inject(DATABASE) private readonly database: Database,
|
||||
) {}
|
||||
|
||||
public async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
if (
|
||||
this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_ENDPOINT, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
])
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const request = context
|
||||
.switchToHttp()
|
||||
.getRequest<AuthenticatedRequest>();
|
||||
// 当前一期每位用户只有一个个人工作空间;后续多人协作时此处将按显式选择的工作空间校验 membership。
|
||||
const workspace = await this.findCurrentWorkspace(request.auth.userId);
|
||||
if (!workspace) {
|
||||
throw new ApiError(
|
||||
403,
|
||||
'WORKSPACE_MEMBERSHIP_REQUIRED',
|
||||
'当前账户没有可用工作空间',
|
||||
);
|
||||
}
|
||||
// 后续控制器和服务只使用此处验证过的上下文,绝不相信客户端传入 workspace_id。
|
||||
request.auth.workspace = workspace;
|
||||
return true;
|
||||
}
|
||||
|
||||
private async findCurrentWorkspace(
|
||||
userId: string,
|
||||
): Promise<Workspace | null> {
|
||||
// 排序规则是首期“唯一有效工作空间”的临时选择策略,不是未来的工作空间切换协议。
|
||||
const result = await this.database.query<Workspace>(
|
||||
`SELECT w.id, w.name, m.role FROM atlas.workspace_memberships m JOIN atlas.workspaces w ON w.id = m.workspace_id WHERE m.user_id = $1 AND w.status = 'active' ORDER BY m.joined_at LIMIT 1`,
|
||||
[userId],
|
||||
);
|
||||
return result.rows[0] ?? null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user