feat: 支持小程序上传配置加密存储

This commit is contained in:
que01 committed 2026-10-13 17:28:40 +08:00
1 parent 526a9db789
commit 3d0252d187
10 files changed
+257 -12

No files matched your search

@@ -0,0 +1 @@
ALTER TABLE "BrandProfile" ADD COLUMN "miniAppSettings" JSONB;
+1
View File
@@ -47,6 +47,7 @@ model BrandProfile {
deliveryNote String?
contactPhone String?
contactWechat String?
miniAppSettings Json?
config Json?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -11,9 +11,12 @@ import {
import type { FastifyRequest } from "fastify";
import { existsSync } from "node:fs";
import { resolve } from "node:path";
import { Prisma } from "@prisma/client";
import { AdminAccessService } from "../../admin-access.service.js";
import { PrismaService } from "../../prisma.service.js";
import { AdminMiniAppReleaseService } from "./admin-miniapp-release.service.js";
import { UpdateMiniAppSettingsDto } from "./admin-miniapp-settings.dto.js";
import { decryptMiniAppCredential, encryptMiniAppCredential } from "./miniapp-credential-crypto.js";
import {
CreateMiniAppReleaseDto,
UpdateMiniAppReleaseStatusDto,
@@ -44,6 +47,65 @@ export class AdminMiniAppReleaseController {
private readonly prisma: PrismaService,
) {}
@Get("settings")
async settings(@Req() request: FastifyRequest): Promise<unknown> {
const identity = await this.identity(request);
const brand = await this.prisma.brandProfile.findUnique({
where: { id: identity.brandId },
select: { miniAppSettings: true },
});
const settings = this.jsonObject(brand?.miniAppSettings);
return {
appId: "",
artifactPath: "",
build: {},
...settings,
privateKey: undefined,
credential: settings.credential ? { algorithm: "aes-256-gcm" } : null,
hasStoredCredentials: Boolean(settings.credential),
};
}
@Patch("settings")
async updateSettings(
@Req() request: FastifyRequest,
@Body() body: UpdateMiniAppSettingsDto & { privateKey?: string },
): Promise<unknown> {
const identity = await this.identity(request);
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
if (body.privateKey !== undefined && !body.privateKey.startsWith("-----BEGIN"))
throw new BadRequestException("上传私钥格式无效");
const brand = await this.prisma.brandProfile.findUniqueOrThrow({
where: { id: identity.brandId },
select: { miniAppSettings: true },
});
const current = this.jsonObject(brand.miniAppSettings);
const credential =
body.privateKey === undefined
? current.credential
: encryptMiniAppCredential(body.privateKey);
const settings = {
...current,
appId: body.appId ?? current.appId ?? "",
artifactPath: body.artifactPath ?? current.artifactPath ?? "",
build: {
...this.jsonObject(current.build),
...this.jsonObject(body.build),
} as Prisma.InputJsonObject,
...(credential ? { credential } : {}),
} satisfies Prisma.InputJsonObject;
await this.prisma.brandProfile.update({
where: { id: identity.brandId },
data: { miniAppSettings: settings },
});
return {
appId: settings.appId,
artifactPath: settings.artifactPath,
build: settings.build,
hasStoredCredentials: Boolean(settings.credential),
};
}
@Get()
list(@Req() request: FastifyRequest): Promise<unknown[]> {
return this.identity(request).then(({ brandId }) => this.releases.list(brandId));
@@ -68,10 +130,22 @@ export class AdminMiniAppReleaseController {
});
if (!task) throw new BadRequestException("小程序发布任务不存在");
if (task.status !== "built") throw new BadRequestException("当前小程序发布任务不能重复上传");
const appid = this.requiredEnv("WECHAT_APP_ID");
const privateKey = this.requiredEnv("WECHAT_UPLOAD_PRIVATE_KEY");
const artifactPath = process.env.WEAPP_ARTIFACT_PATH;
if (!artifactPath) throw new BadRequestException("WEAPP_ARTIFACT_PATH 未配置");
const brand = await this.prisma.brandProfile.findUniqueOrThrow({
where: { id: identity.brandId },
select: { miniAppSettings: true },
});
const settings = this.jsonObject(brand.miniAppSettings);
const appid =
typeof settings.appId === "string" && settings.appId
? settings.appId
: this.requiredEnv("WECHAT_APP_ID");
const privateKey = settings.credential
? decryptMiniAppCredential(settings.credential)
: this.requiredEnv("WECHAT_UPLOAD_PRIVATE_KEY");
const artifactPath =
typeof settings.artifactPath === "string" && settings.artifactPath
? settings.artifactPath
: this.requiredEnv("WEAPP_ARTIFACT_PATH");
const projectPath = resolve(artifactPath);
if (!existsSync(projectPath) || !existsSync(resolve(projectPath, "app.json")))
throw new BadRequestException("小程序构建产物不存在");
@@ -126,4 +200,10 @@ export class AdminMiniAppReleaseController {
if (!value) throw new BadRequestException(`${name} 未配置`);
return value;
}
private jsonObject(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
}
@@ -0,0 +1,20 @@
import { IsObject, IsOptional, IsString, MaxLength } from "class-validator";
export class UpdateMiniAppSettingsDto {
@IsOptional()
@IsString()
@MaxLength(100)
appId?: string;
@IsOptional()
@IsString()
artifactPath?: string;
@IsOptional()
@IsObject()
build?: Record<string, unknown>;
@IsOptional()
@IsString()
privateKey?: string;
}
@@ -0,0 +1,48 @@
import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
import { UnauthorizedException } from "@nestjs/common";
const ALGORITHM = "aes-256-gcm";
export function encryptionKey(): Buffer {
const value = process.env.MINIAPP_CREDENTIAL_ENCRYPTION_KEY ?? process.env.SESSION_SECRET;
if (!value || value.length < 32) throw new UnauthorizedException("小程序凭据加密密钥未正确配置");
return createHash("sha256").update(value).digest();
}
export function encryptMiniAppCredential(plaintext: string): {
ciphertext: string;
iv: string;
authTag: string;
algorithm: string;
} {
const iv = randomBytes(12);
const cipher = createCipheriv(ALGORITHM, encryptionKey(), iv);
const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
return {
algorithm: ALGORITHM,
ciphertext: ciphertext.toString("base64"),
iv: iv.toString("base64"),
authTag: cipher.getAuthTag().toString("base64"),
};
}
export function decryptMiniAppCredential(value: unknown): string {
const payload =
value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
if (
!payload ||
payload.algorithm !== ALGORITHM ||
typeof payload.ciphertext !== "string" ||
typeof payload.iv !== "string" ||
typeof payload.authTag !== "string"
)
throw new UnauthorizedException("小程序上传凭据不可用");
const decipher = createDecipheriv(ALGORITHM, encryptionKey(), Buffer.from(payload.iv, "base64"));
decipher.setAuthTag(Buffer.from(payload.authTag, "base64"));
return Buffer.concat([
decipher.update(Buffer.from(payload.ciphertext, "base64")),
decipher.final(),
]).toString("utf8");
}