feat: 支持小程序上传配置加密存储
This commit is contained in:
1 parent
526a9db789
commit
3d0252d187
10 files changed
+257
-12
No files matched your search
@@ -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
|
||||
@@ -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<number | null>(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
|
||||
<Typography.Paragraph type="secondary">
|
||||
使用微信官方 miniprogram-ci 上传代码;审核与发布状态需按微信平台结果人工确认。
|
||||
</Typography.Paragraph>
|
||||
<Button
|
||||
disabled={!currentRelease}
|
||||
loading={createMiniAppRelease.isPending}
|
||||
onClick={() => createMiniAppRelease.mutate()}
|
||||
>
|
||||
基于当前品牌版本创建任务
|
||||
</Button>
|
||||
<Space wrap style={{ marginBottom: 12 }}>
|
||||
<Button
|
||||
disabled={!currentRelease}
|
||||
loading={createMiniAppRelease.isPending}
|
||||
onClick={() => createMiniAppRelease.mutate()}
|
||||
>
|
||||
基于当前品牌版本创建任务
|
||||
</Button>
|
||||
<Button onClick={() => setSettingsOpen(true)}>上传配置</Button>
|
||||
{miniAppSettings.data?.hasStoredCredentials ? (
|
||||
<Tag color="green">已配置上传凭据</Tag>
|
||||
) : (
|
||||
<Tag color="warning">未配置上传凭据</Tag>
|
||||
)}
|
||||
</Space>
|
||||
<Divider />
|
||||
{miniAppReleases.data?.length ? (
|
||||
<Space direction="vertical" style={{ width: "100%" }}>
|
||||
@@ -527,6 +559,44 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
|
||||
>
|
||||
模板会更新当前品牌的草稿结构,不会立即改变已发布的小程序。请安装后核对业务内容与视觉模板。
|
||||
</Modal>
|
||||
<Modal
|
||||
title="小程序上传配置"
|
||||
open={settingsOpen}
|
||||
onCancel={() => setSettingsOpen(false)}
|
||||
confirmLoading={saveMiniAppSettings.isPending}
|
||||
onOk={() =>
|
||||
saveMiniAppSettings.mutate({
|
||||
appId: settingsAppId,
|
||||
artifactPath: settingsArtifactPath,
|
||||
...(settingsPrivateKey ? { privateKey: settingsPrivateKey } : {}),
|
||||
})
|
||||
}
|
||||
>
|
||||
<Space direction="vertical" style={{ width: "100%" }}>
|
||||
<Input
|
||||
value={settingsAppId}
|
||||
onChange={(event) => setSettingsAppId(event.target.value)}
|
||||
placeholder="微信 AppID"
|
||||
/>
|
||||
<Input
|
||||
value={settingsArtifactPath}
|
||||
onChange={(event) => setSettingsArtifactPath(event.target.value)}
|
||||
placeholder="服务端可访问的构建产物路径"
|
||||
/>
|
||||
<Input.Password
|
||||
value={settingsPrivateKey}
|
||||
onChange={(event) => setSettingsPrivateKey(event.target.value)}
|
||||
placeholder={
|
||||
miniAppSettings.data?.hasStoredCredentials
|
||||
? "已加密保存,输入新值可替换"
|
||||
: "微信上传私钥"
|
||||
}
|
||||
/>
|
||||
<Typography.Text type="secondary">
|
||||
私钥使用 AES-256-GCM 加密后保存;加密密钥只保留在服务端环境变量中。
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
</Modal>
|
||||
</QueryState>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "BrandProfile" ADD COLUMN "miniAppSettings" JSONB;
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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<BrandMethods["updateAdminMiniAppReleaseStatus"]>
|
||||
) => this.resources.brand.updateAdminMiniAppReleaseStatus(...arguments_);
|
||||
getAdminMiniAppSettings = (...arguments_: Parameters<BrandMethods["getAdminMiniAppSettings"]>) =>
|
||||
this.resources.brand.getAdminMiniAppSettings(...arguments_);
|
||||
updateAdminMiniAppSettings = (
|
||||
...arguments_: Parameters<BrandMethods["updateAdminMiniAppSettings"]>
|
||||
) => this.resources.brand.updateAdminMiniAppSettings(...arguments_);
|
||||
getPublicTemplate = (...arguments_: Parameters<TemplateMethods["getPublicTemplate"]>) =>
|
||||
this.resources.template.getPublicTemplate(...arguments_);
|
||||
listPublicTemplates = (...arguments_: Parameters<TemplateMethods["listPublicTemplates"]>) =>
|
||||
|
||||
@@ -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<MiniAppReleaseTask>;
|
||||
getAdminMiniAppSettings(): Promise<MiniAppReleaseSettings>;
|
||||
updateAdminMiniAppSettings(body: {
|
||||
appId?: string;
|
||||
artifactPath?: string;
|
||||
privateKey?: string;
|
||||
}): Promise<MiniAppReleaseSettings>;
|
||||
}
|
||||
|
||||
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 }),
|
||||
};
|
||||
}
|
||||
@@ -59,6 +59,14 @@ export interface MiniAppReleaseTask {
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface MiniAppReleaseSettings {
|
||||
appId: string;
|
||||
artifactPath: string;
|
||||
build: Record<string, unknown>;
|
||||
credential: { algorithm: string } | null;
|
||||
hasStoredCredentials: boolean;
|
||||
}
|
||||
|
||||
export type BrandPresentationUpdate = Partial<
|
||||
Record<
|
||||
"identity" | "home" | "offerings" | "detail" | "profile" | "inquiry" | "success" | "records",
|
||||
|
||||
Reference in new issue
Block a user