diff --git a/.env.example b/.env.example index cfb08de..116c486 100644 --- a/.env.example +++ b/.env.example @@ -18,4 +18,5 @@ OBJECT_STORAGE_SECRET_KEY=minioadmin WECHAT_APP_ID= WECHAT_APP_SECRET= WECHAT_UPLOAD_PRIVATE_KEY= +MINIAPP_CREDENTIAL_ENCRYPTION_KEY=replace-with-32-byte-random-secret WEAPP_ARTIFACT_PATH=apps/taro/dist/food/weapp diff --git a/apps/admin/src/features/publication/PublicationPage.tsx b/apps/admin/src/features/publication/PublicationPage.tsx index ddd24ef..71945dd 100644 --- a/apps/admin/src/features/publication/PublicationPage.tsx +++ b/apps/admin/src/features/publication/PublicationPage.tsx @@ -1,4 +1,4 @@ -import { useState } from "react"; +import { useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { @@ -40,6 +40,10 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool const [confirmAction, setConfirmAction] = useState<"publish" | "revoke" | null>(null); const [rollbackVersion, setRollbackVersion] = useState(null); const [note, setNote] = useState(""); + const [settingsOpen, setSettingsOpen] = useState(false); + const [settingsAppId, setSettingsAppId] = useState(""); + const [settingsArtifactPath, setSettingsArtifactPath] = useState(""); + const [settingsPrivateKey, setSettingsPrivateKey] = useState(""); const brand = useQuery({ queryKey: ["publication-brand"], queryFn: () => client.getAdminBrand(), @@ -69,6 +73,10 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool queryKey: ["publication-miniapp-releases"], queryFn: () => client.listAdminMiniAppReleases(), }); + const miniAppSettings = useQuery({ + queryKey: ["publication-miniapp-settings"], + queryFn: () => client.getAdminMiniAppSettings(), + }); const refresh = () => { for (const key of [ "publication-brand", @@ -145,6 +153,15 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool void miniAppReleases.refetch(); }, }); + const saveMiniAppSettings = useMutation({ + mutationFn: (values: { appId?: string; artifactPath?: string; privateKey?: string }) => + client.updateAdminMiniAppSettings(values), + onSuccess: () => { + setSettingsOpen(false); + message.success("小程序上传配置已保存"); + void miniAppSettings.refetch(); + }, + }); const uploadMiniAppRelease = useMutation({ mutationFn: (id: string) => client.uploadAdminMiniAppRelease(id), onSuccess: () => { @@ -178,6 +195,7 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool void readiness.refetch(); void releases.refetch(); void miniAppReleases.refetch(); + void miniAppSettings.refetch(); }; const industryKey = workspace.data?.installations[0]?.templateKey ?? @@ -194,6 +212,12 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool ? brand.data.config.visualTemplateKey : (visuals[0]?.key ?? null); const currentRelease = releases.data?.find((item) => item.status === "published"); + useEffect(() => { + if (!miniAppSettings.data) return; + setSettingsAppId(miniAppSettings.data.appId); + setSettingsArtifactPath(miniAppSettings.data.artifactPath); + setSettingsPrivateKey(""); + }, [miniAppSettings.data]); const publishedHistory = (releases.data ?? []).filter( (item) => item.status === "published" || item.status === "superseded", ); @@ -384,13 +408,21 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool 使用微信官方 miniprogram-ci 上传代码;审核与发布状态需按微信平台结果人工确认。 - + + + + {miniAppSettings.data?.hasStoredCredentials ? ( + 已配置上传凭据 + ) : ( + 未配置上传凭据 + )} + {miniAppReleases.data?.length ? ( @@ -527,6 +559,44 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool > 模板会更新当前品牌的草稿结构,不会立即改变已发布的小程序。请安装后核对业务内容与视觉模板。 + setSettingsOpen(false)} + confirmLoading={saveMiniAppSettings.isPending} + onOk={() => + saveMiniAppSettings.mutate({ + appId: settingsAppId, + artifactPath: settingsArtifactPath, + ...(settingsPrivateKey ? { privateKey: settingsPrivateKey } : {}), + }) + } + > + + setSettingsAppId(event.target.value)} + placeholder="微信 AppID" + /> + setSettingsArtifactPath(event.target.value)} + placeholder="服务端可访问的构建产物路径" + /> + setSettingsPrivateKey(event.target.value)} + placeholder={ + miniAppSettings.data?.hasStoredCredentials + ? "已加密保存,输入新值可替换" + : "微信上传私钥" + } + /> + + 私钥使用 AES-256-GCM 加密后保存;加密密钥只保留在服务端环境变量中。 + + + ); } diff --git a/apps/api/prisma/migrations/20261013010000_add_miniapp_release_settings/migration.sql b/apps/api/prisma/migrations/20261013010000_add_miniapp_release_settings/migration.sql new file mode 100644 index 0000000..cff378b --- /dev/null +++ b/apps/api/prisma/migrations/20261013010000_add_miniapp_release_settings/migration.sql @@ -0,0 +1 @@ +ALTER TABLE "BrandProfile" ADD COLUMN "miniAppSettings" JSONB; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 8766f3f..2a8bc85 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -47,6 +47,7 @@ model BrandProfile { deliveryNote String? contactPhone String? contactWechat String? + miniAppSettings Json? config Json? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt diff --git a/apps/api/src/modules/admin/admin-miniapp-release.controller.ts b/apps/api/src/modules/admin/admin-miniapp-release.controller.ts index a8707b6..21bd3df 100644 --- a/apps/api/src/modules/admin/admin-miniapp-release.controller.ts +++ b/apps/api/src/modules/admin/admin-miniapp-release.controller.ts @@ -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 { + 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 { + 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 { 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 { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : {}; + } } diff --git a/apps/api/src/modules/admin/admin-miniapp-settings.dto.ts b/apps/api/src/modules/admin/admin-miniapp-settings.dto.ts new file mode 100644 index 0000000..fab8354 --- /dev/null +++ b/apps/api/src/modules/admin/admin-miniapp-settings.dto.ts @@ -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; + + @IsOptional() + @IsString() + privateKey?: string; +} diff --git a/apps/api/src/modules/admin/miniapp-credential-crypto.ts b/apps/api/src/modules/admin/miniapp-credential-crypto.ts new file mode 100644 index 0000000..87f5971 --- /dev/null +++ b/apps/api/src/modules/admin/miniapp-credential-crypto.ts @@ -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) + : 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"); +} diff --git a/packages/api-client/src/index.ts b/packages/api-client/src/index.ts index fd805aa..4b9e53f 100644 --- a/packages/api-client/src/index.ts +++ b/packages/api-client/src/index.ts @@ -16,6 +16,7 @@ export type { BrandReleaseSummary, BrandUpdate, } from "./types/brand.js"; +export type { MiniAppReleaseSettings, MiniAppReleaseTask } from "./types/brand.js"; export type { CapabilityInstallation } from "./types/capability.js"; export type { CapabilityMetadata } from "./types/capability.js"; export type { ApiErrorBody } from "./types/common.js"; @@ -220,6 +221,11 @@ export class ApiClient updateAdminMiniAppReleaseStatus = ( ...arguments_: Parameters ) => this.resources.brand.updateAdminMiniAppReleaseStatus(...arguments_); + getAdminMiniAppSettings = (...arguments_: Parameters) => + this.resources.brand.getAdminMiniAppSettings(...arguments_); + updateAdminMiniAppSettings = ( + ...arguments_: Parameters + ) => this.resources.brand.updateAdminMiniAppSettings(...arguments_); getPublicTemplate = (...arguments_: Parameters) => this.resources.template.getPublicTemplate(...arguments_); listPublicTemplates = (...arguments_: Parameters) => diff --git a/packages/api-client/src/resources/brand.ts b/packages/api-client/src/resources/brand.ts index 10a2597..36fc7c6 100644 --- a/packages/api-client/src/resources/brand.ts +++ b/packages/api-client/src/resources/brand.ts @@ -6,6 +6,7 @@ import type { BrandProfile, BrandReleaseSummary, MiniAppReleaseTask, + MiniAppReleaseSettings, BrandUpdate, } from "../types/brand.js"; @@ -74,6 +75,12 @@ export interface BrandMethods { weappUploadId?: string; }, ): Promise; + getAdminMiniAppSettings(): Promise; + updateAdminMiniAppSettings(body: { + appId?: string; + artifactPath?: string; + privateKey?: string; + }): Promise; } export function brandMethods({ request }: { request: RequestFn }): BrandMethods { @@ -125,5 +132,8 @@ export function brandMethods({ request }: { request: RequestFn }): BrandMethods method: "PATCH", body, }), + getAdminMiniAppSettings: () => request("/admin/miniapp-releases/settings"), + updateAdminMiniAppSettings: (body) => + request("/admin/miniapp-releases/settings", { method: "PATCH", body }), }; } diff --git a/packages/api-client/src/types/brand.ts b/packages/api-client/src/types/brand.ts index ddacd14..cb2163d 100644 --- a/packages/api-client/src/types/brand.ts +++ b/packages/api-client/src/types/brand.ts @@ -59,6 +59,14 @@ export interface MiniAppReleaseTask { updatedAt: string; } +export interface MiniAppReleaseSettings { + appId: string; + artifactPath: string; + build: Record; + credential: { algorithm: string } | null; + hasStoredCredentials: boolean; +} + export type BrandPresentationUpdate = Partial< Record< "identity" | "home" | "offerings" | "detail" | "profile" | "inquiry" | "success" | "records",