refactor: 拆分媒体上传职责并锁定API路由
This commit is contained in:
1 parent
6f18c67315
commit
2ad009f5c0
8 files changed
+375
-171
No files matched your search
@@ -1,23 +1,14 @@
|
||||
import { BadRequestException, Controller, Put, Query, Req } from "@nestjs/common";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { Controller, Put, Query, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
|
||||
const allowedExtensions = new Map([
|
||||
["image/jpeg", ".jpg"],
|
||||
["image/png", ".png"],
|
||||
["image/webp", ".webp"],
|
||||
["image/avif", ".avif"],
|
||||
]);
|
||||
import { AdminUploadService } from "./admin-upload.service.js";
|
||||
|
||||
@Controller("admin/uploads")
|
||||
export class AdminLocalUploadController {
|
||||
constructor(private readonly access: AdminAccessService) {}
|
||||
|
||||
private get mediaRoot(): string {
|
||||
return path.resolve(process.env.LOCAL_MEDIA_ROOT || path.join(process.cwd(), "media"));
|
||||
}
|
||||
constructor(
|
||||
private readonly access: AdminAccessService,
|
||||
private readonly uploads: AdminUploadService,
|
||||
) {}
|
||||
|
||||
@Put("local")
|
||||
async upload(
|
||||
@@ -26,30 +17,11 @@ export class AdminLocalUploadController {
|
||||
): Promise<{ saved: true }> {
|
||||
await this.access.requireBrand(request);
|
||||
const rawKey = key ?? (request.query as { key?: string }).key;
|
||||
const decodedKey = (rawKey ?? "").includes("%")
|
||||
? decodeURIComponent(rawKey as string)
|
||||
: (rawKey ?? "");
|
||||
if (
|
||||
!decodedKey ||
|
||||
decodedKey.includes("..") ||
|
||||
decodedKey.startsWith("/") ||
|
||||
!/^\d{4}\//.test(decodedKey)
|
||||
) {
|
||||
throw new BadRequestException("上传 key 无效");
|
||||
}
|
||||
if (!allowedExtensions.has(request.headers["content-type"] ?? "")) {
|
||||
throw new BadRequestException("仅支持图片上传");
|
||||
}
|
||||
const contentType = allowedExtensions.get(request.headers["content-type"] ?? "");
|
||||
if (!contentType || !decodedKey.endsWith(contentType)) {
|
||||
throw new BadRequestException("上传文件类型与 key 不一致");
|
||||
}
|
||||
const target = path.join(this.mediaRoot, decodedKey);
|
||||
if (!target.startsWith(path.resolve(this.mediaRoot))) {
|
||||
throw new BadRequestException("上传 key 无效");
|
||||
}
|
||||
await mkdir(path.dirname(target), { recursive: true });
|
||||
await writeFile(target, request.body as Buffer);
|
||||
await this.uploads.saveLocal(
|
||||
rawKey ?? "",
|
||||
request.headers["content-type"] ?? "",
|
||||
request.body as Buffer,
|
||||
);
|
||||
return { saved: true };
|
||||
}
|
||||
}
|
||||
@@ -1,145 +1,24 @@
|
||||
import { BadRequestException, Body, Controller, Get, Post, Req } from "@nestjs/common";
|
||||
import { HeadBucketCommand, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
|
||||
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { Body, Controller, Get, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { IsIn, IsOptional, IsString, MaxLength } from "class-validator";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
|
||||
export class PresignUploadDto {
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
fileName!: string;
|
||||
|
||||
@IsString()
|
||||
@IsIn(["image/jpeg", "image/png", "image/webp", "image/avif"])
|
||||
contentType!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(64)
|
||||
scope?: "brand" | "offering" | "trust";
|
||||
}
|
||||
|
||||
class ObjectStorage {
|
||||
private readonly client = new S3Client({
|
||||
region: process.env.OBJECT_STORAGE_REGION || "us-east-1",
|
||||
...(process.env.OBJECT_STORAGE_ENDPOINT
|
||||
? { endpoint: process.env.OBJECT_STORAGE_ENDPOINT }
|
||||
: {}),
|
||||
forcePathStyle: Boolean(process.env.OBJECT_STORAGE_ENDPOINT),
|
||||
credentials: {
|
||||
accessKeyId: process.env.OBJECT_STORAGE_ACCESS_KEY || "",
|
||||
secretAccessKey: process.env.OBJECT_STORAGE_SECRET_KEY || "",
|
||||
},
|
||||
});
|
||||
|
||||
private get bucket(): string {
|
||||
const bucket = process.env.OBJECT_STORAGE_BUCKET;
|
||||
if (!bucket) throw new BadRequestException("媒体上传尚未配置");
|
||||
return bucket;
|
||||
}
|
||||
|
||||
publicUrl(key: string): string {
|
||||
const endpoint = process.env.OBJECT_STORAGE_PUBLIC_URL?.replace(/\/$/, "");
|
||||
return endpoint ? `${endpoint}/${key}` : `/${key}`;
|
||||
}
|
||||
|
||||
get bucketName(): string {
|
||||
return this.bucket;
|
||||
}
|
||||
|
||||
async presignPut(key: string, contentType: string): Promise<string> {
|
||||
return getSignedUrl(
|
||||
this.client,
|
||||
new PutObjectCommand({ Bucket: this.bucket, Key: key, ContentType: contentType }),
|
||||
{ expiresIn: 600 },
|
||||
);
|
||||
}
|
||||
|
||||
async checkBucket(): Promise<"ok" | "unavailable"> {
|
||||
try {
|
||||
await this.client.send(new HeadBucketCommand({ Bucket: this.bucket }));
|
||||
return "ok";
|
||||
} catch {
|
||||
return "unavailable";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const allowedExtensions = new Map([
|
||||
["image/jpeg", ".jpg"],
|
||||
["image/png", ".png"],
|
||||
["image/webp", ".webp"],
|
||||
["image/avif", ".avif"],
|
||||
]);
|
||||
import { PresignUploadDto } from "./admin-upload.dto.js";
|
||||
import { AdminUploadService } from "./admin-upload.service.js";
|
||||
|
||||
@Controller("admin/uploads")
|
||||
export class AdminUploadController {
|
||||
private readonly storage = new ObjectStorage();
|
||||
|
||||
constructor(private readonly access: AdminAccessService) {}
|
||||
|
||||
private get localMediaRoot(): string {
|
||||
return path.resolve(process.env.LOCAL_MEDIA_ROOT || path.join(process.cwd(), "media"));
|
||||
}
|
||||
|
||||
private get localMediaBaseUrl(): string {
|
||||
return process.env.LOCAL_MEDIA_BASE_URL || "/media";
|
||||
}
|
||||
constructor(
|
||||
private readonly access: AdminAccessService,
|
||||
private readonly uploads: AdminUploadService,
|
||||
) {}
|
||||
|
||||
@Get("config")
|
||||
async config() {
|
||||
const objectStorageConfigured = Boolean(
|
||||
process.env.OBJECT_STORAGE_BUCKET &&
|
||||
process.env.OBJECT_STORAGE_ACCESS_KEY &&
|
||||
process.env.OBJECT_STORAGE_SECRET_KEY,
|
||||
);
|
||||
const localMediaConfigured = Boolean(process.env.LOCAL_MEDIA_ROOT);
|
||||
if (localMediaConfigured) {
|
||||
return { configured: true, status: "ok", mode: "local" };
|
||||
}
|
||||
const configured = Boolean(objectStorageConfigured);
|
||||
return {
|
||||
configured,
|
||||
status: configured ? await this.storage.checkBucket() : "unconfigured",
|
||||
...(configured ? { bucket: this.storage.bucketName } : {}),
|
||||
...(configured ? { mode: "object-storage" } : {}),
|
||||
};
|
||||
return this.uploads.getConfiguration();
|
||||
}
|
||||
|
||||
@Post("presign")
|
||||
async presign(@Req() request: FastifyRequest, @Body() body: PresignUploadDto) {
|
||||
await this.access.requireBrand(request);
|
||||
const extension = allowedExtensions.get(body.contentType);
|
||||
if (!extension) throw new BadRequestException("仅支持 JPG、PNG、WebP 或 AVIF 图片");
|
||||
const cleanName = body.fileName
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9._-]+/g, "-")
|
||||
.slice(-64);
|
||||
const digest = createHash("sha256")
|
||||
.update(`${body.scope ?? "brand"}:${cleanName}:${randomUUID()}`)
|
||||
.digest("hex")
|
||||
.slice(0, 16);
|
||||
const key = `${new Date().getFullYear()}/${digest}${extension}`;
|
||||
const objectStorageEnabled = Boolean(
|
||||
process.env.OBJECT_STORAGE_BUCKET &&
|
||||
process.env.OBJECT_STORAGE_ACCESS_KEY &&
|
||||
process.env.OBJECT_STORAGE_SECRET_KEY,
|
||||
);
|
||||
if (objectStorageEnabled) {
|
||||
const uploadUrl = await this.storage.presignPut(key, body.contentType);
|
||||
return { uploadUrl, key, publicUrl: this.storage.publicUrl(key) };
|
||||
}
|
||||
const target = path.join(this.localMediaRoot, key);
|
||||
await mkdir(path.dirname(target), { recursive: true });
|
||||
return {
|
||||
uploadUrl: `/admin/uploads/local?key=${encodeURIComponent(key)}`,
|
||||
key,
|
||||
publicUrl: `${this.localMediaBaseUrl}/${key}`,
|
||||
mode: "local",
|
||||
};
|
||||
return this.uploads.presign(body);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { IsIn, IsOptional, IsString, MaxLength } from "class-validator";
|
||||
|
||||
export class PresignUploadDto {
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
fileName!: string;
|
||||
|
||||
@IsString()
|
||||
@IsIn(["image/jpeg", "image/png", "image/webp", "image/avif"])
|
||||
contentType!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(64)
|
||||
scope?: "brand" | "offering" | "trust";
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import { HeadBucketCommand, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
|
||||
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { PresignUploadDto } from "./admin-upload.dto.js";
|
||||
|
||||
const allowedExtensions = new Map([
|
||||
["image/jpeg", ".jpg"],
|
||||
["image/png", ".png"],
|
||||
["image/webp", ".webp"],
|
||||
["image/avif", ".avif"],
|
||||
]);
|
||||
|
||||
export interface UploadConfiguration {
|
||||
configured: boolean;
|
||||
status: "ok" | "unavailable" | "unconfigured";
|
||||
bucket?: string;
|
||||
mode: "local" | "object-storage";
|
||||
}
|
||||
|
||||
export interface PresignedUpload {
|
||||
uploadUrl: string;
|
||||
key: string;
|
||||
publicUrl: string;
|
||||
mode?: "local";
|
||||
}
|
||||
|
||||
class ObjectStorage {
|
||||
private readonly client = new S3Client({
|
||||
region: process.env.OBJECT_STORAGE_REGION || "us-east-1",
|
||||
...(process.env.OBJECT_STORAGE_ENDPOINT
|
||||
? { endpoint: process.env.OBJECT_STORAGE_ENDPOINT }
|
||||
: {}),
|
||||
forcePathStyle: Boolean(process.env.OBJECT_STORAGE_ENDPOINT),
|
||||
credentials: {
|
||||
accessKeyId: process.env.OBJECT_STORAGE_ACCESS_KEY || "",
|
||||
secretAccessKey: process.env.OBJECT_STORAGE_SECRET_KEY || "",
|
||||
},
|
||||
});
|
||||
|
||||
private get bucket(): string {
|
||||
const bucket = process.env.OBJECT_STORAGE_BUCKET;
|
||||
if (!bucket) throw new BadRequestException("媒体上传尚未配置");
|
||||
return bucket;
|
||||
}
|
||||
|
||||
publicUrl(key: string): string {
|
||||
const endpoint = process.env.OBJECT_STORAGE_PUBLIC_URL?.replace(/\/$/, "");
|
||||
return endpoint ? `${endpoint}/${key}` : `/${key}`;
|
||||
}
|
||||
|
||||
get bucketName(): string {
|
||||
return this.bucket;
|
||||
}
|
||||
|
||||
async presignPut(key: string, contentType: string): Promise<string> {
|
||||
return getSignedUrl(
|
||||
this.client,
|
||||
new PutObjectCommand({ Bucket: this.bucket, Key: key, ContentType: contentType }),
|
||||
{ expiresIn: 600 },
|
||||
);
|
||||
}
|
||||
|
||||
async checkBucket(): Promise<"ok" | "unavailable"> {
|
||||
try {
|
||||
await this.client.send(new HeadBucketCommand({ Bucket: this.bucket }));
|
||||
return "ok";
|
||||
} catch {
|
||||
return "unavailable";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AdminUploadService {
|
||||
private readonly storage = new ObjectStorage();
|
||||
|
||||
async getConfiguration(): Promise<UploadConfiguration> {
|
||||
if (this.localMediaConfigured) {
|
||||
return { configured: true, status: "ok", mode: "local" };
|
||||
}
|
||||
const configured = this.objectStorageConfigured;
|
||||
return {
|
||||
configured,
|
||||
status: configured ? await this.storage.checkBucket() : "unconfigured",
|
||||
...(configured ? { bucket: this.storage.bucketName } : {}),
|
||||
mode: "object-storage",
|
||||
};
|
||||
}
|
||||
|
||||
async presign(body: PresignUploadDto): Promise<PresignedUpload> {
|
||||
const extension = this.extensionFor(body.contentType);
|
||||
const cleanName = body.fileName
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9._-]+/g, "-")
|
||||
.slice(-64);
|
||||
const digest = createHash("sha256")
|
||||
.update(`${body.scope ?? "brand"}:${cleanName}:${randomUUID()}`)
|
||||
.digest("hex")
|
||||
.slice(0, 16);
|
||||
const key = `${new Date().getFullYear()}/${digest}${extension}`;
|
||||
if (this.objectStorageConfigured) {
|
||||
const uploadUrl = await this.storage.presignPut(key, body.contentType);
|
||||
return { uploadUrl, key, publicUrl: this.storage.publicUrl(key) };
|
||||
}
|
||||
const target = path.join(this.localMediaRoot, key);
|
||||
await mkdir(path.dirname(target), { recursive: true });
|
||||
return {
|
||||
uploadUrl: `/admin/uploads/local?key=${encodeURIComponent(key)}`,
|
||||
key,
|
||||
publicUrl: `${this.localMediaBaseUrl}/${key}`,
|
||||
mode: "local",
|
||||
};
|
||||
}
|
||||
|
||||
async saveLocal(key: string, contentType: string, body: Buffer): Promise<void> {
|
||||
const decodedKey = key.includes("%") ? decodeURIComponent(key) : key;
|
||||
if (
|
||||
!decodedKey ||
|
||||
decodedKey.includes("..") ||
|
||||
decodedKey.startsWith("/") ||
|
||||
!/^\d{4}\//.test(decodedKey)
|
||||
) {
|
||||
throw new BadRequestException("上传 key 无效");
|
||||
}
|
||||
const extension = this.extensionFor(contentType);
|
||||
if (!decodedKey.endsWith(extension)) {
|
||||
throw new BadRequestException("上传文件类型与 key 不一致");
|
||||
}
|
||||
const mediaRoot = this.localMediaRoot;
|
||||
const target = path.join(mediaRoot, decodedKey);
|
||||
if (!target.startsWith(mediaRoot)) throw new BadRequestException("上传 key 无效");
|
||||
await mkdir(path.dirname(target), { recursive: true });
|
||||
await writeFile(target, body);
|
||||
}
|
||||
|
||||
private extensionFor(contentType: string): string {
|
||||
const extension = allowedExtensions.get(contentType);
|
||||
if (!extension) throw new BadRequestException("仅支持 JPG、PNG、WebP 或 AVIF 图片");
|
||||
return extension;
|
||||
}
|
||||
|
||||
private get objectStorageConfigured(): boolean {
|
||||
return Boolean(
|
||||
process.env.OBJECT_STORAGE_BUCKET &&
|
||||
process.env.OBJECT_STORAGE_ACCESS_KEY &&
|
||||
process.env.OBJECT_STORAGE_SECRET_KEY,
|
||||
);
|
||||
}
|
||||
|
||||
private get localMediaConfigured(): boolean {
|
||||
return Boolean(process.env.LOCAL_MEDIA_ROOT);
|
||||
}
|
||||
|
||||
private get localMediaRoot(): string {
|
||||
return path.resolve(process.env.LOCAL_MEDIA_ROOT || path.join(process.cwd(), "media"));
|
||||
}
|
||||
|
||||
private get localMediaBaseUrl(): string {
|
||||
return process.env.LOCAL_MEDIA_BASE_URL || "/media";
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import { AdminMiniAppReleaseService } from "./admin-miniapp-release.service.js";
|
||||
import { AdminMiniAppSettingsService } from "./admin-miniapp-settings.service.js";
|
||||
import { AdminMiniAppUploadService } from "./admin-miniapp-upload.service.js";
|
||||
import { AdminReleaseController } from "./admin-release.controller.js";
|
||||
import { AdminUploadService } from "./admin-upload.service.js";
|
||||
import { AdminUploadController } from "./admin-upload.controller.js";
|
||||
|
||||
@Module({
|
||||
@@ -29,6 +30,7 @@ import { AdminUploadController } from "./admin-upload.controller.js";
|
||||
AdminMiniAppBuildService,
|
||||
AdminMiniAppSettingsService,
|
||||
AdminMiniAppUploadService,
|
||||
AdminUploadService,
|
||||
],
|
||||
})
|
||||
export class AdminModule {}
|
||||
Reference in new issue
Block a user