395 lines
14 KiB
TypeScript
395 lines
14 KiB
TypeScript
import {
|
||
BadRequestException,
|
||
BadGatewayException,
|
||
Body,
|
||
ConflictException,
|
||
Controller,
|
||
Get,
|
||
Param,
|
||
Patch,
|
||
Post,
|
||
Req,
|
||
} from "@nestjs/common";
|
||
import type { FastifyRequest } from "fastify";
|
||
import { existsSync } from "node:fs";
|
||
import { spawn } from "node:child_process";
|
||
import { resolve } from "node:path";
|
||
import { Prisma } from "@prisma/client";
|
||
import { getTemplatePackageManifest, templatePackageRegistry } from "@personal-brand/config";
|
||
import { AdminAccessService } from "../../admin-access.service.js";
|
||
import { AdminMiniAppReleaseService } from "./admin-miniapp-release.service.js";
|
||
import { UpdateMiniAppSettingsDto } from "./admin-miniapp-settings.dto.js";
|
||
import { miniappArtifactRoot, miniappProjectPath, REPOSITORY_ROOT } from "./miniapp-artifact.js";
|
||
import { miniappApiBaseUrl, validateApiBaseUrl, weappAppId } from "./miniapp-build-config.js";
|
||
import { buildingStaleMs, isStaleBuilding } from "./miniapp-build-status.js";
|
||
import { decryptMiniAppCredential, encryptMiniAppCredential } from "./miniapp-credential-crypto.js";
|
||
import { inspectPrivateKey, normalizePrivateKey } from "./miniapp-private-key.js";
|
||
import { runMiniAppUpload } from "./miniapp-upload.js";
|
||
import {
|
||
CreateMiniAppReleaseDto,
|
||
UpdateMiniAppReleaseStatusDto,
|
||
UploadMiniAppReleaseDto,
|
||
} from "./admin-miniapp-release.dto.js";
|
||
|
||
function miniAppTemplateKey(industryTemplateKey: string): string | null {
|
||
return (
|
||
getTemplatePackageManifest(industryTemplateKey)?.packageKey ??
|
||
templatePackageRegistry.find((item) =>
|
||
item.supportedIndustryTemplates.includes(industryTemplateKey),
|
||
)?.packageKey ??
|
||
null
|
||
);
|
||
}
|
||
|
||
interface BuildLog {
|
||
at: string;
|
||
message: string;
|
||
stream: "stdout" | "stderr";
|
||
}
|
||
|
||
interface BuildProcess {
|
||
stdout: NodeJS.ReadableStream;
|
||
stderr: NodeJS.ReadableStream;
|
||
on: (event: "close" | "error", listener: (code: number | null) => void) => void;
|
||
}
|
||
|
||
@Controller("admin/miniapp-releases")
|
||
export class AdminMiniAppReleaseController {
|
||
constructor(
|
||
private readonly access: AdminAccessService,
|
||
private readonly releases: AdminMiniAppReleaseService,
|
||
) {}
|
||
|
||
@Get("latest")
|
||
async latest(@Req() request: FastifyRequest): Promise<unknown> {
|
||
const identity = await this.identity(request);
|
||
const task = await this.releases.latest(identity.brandId);
|
||
return task ?? null;
|
||
}
|
||
|
||
@Get("settings")
|
||
async settings(@Req() request: FastifyRequest): Promise<unknown> {
|
||
const identity = await this.identity(request);
|
||
const settings = this.jsonObject(await this.releases.settings(identity.brandId));
|
||
const buildConfig = this.buildConfigSummary(settings.apiBaseUrl, settings.appId);
|
||
return {
|
||
appId: "",
|
||
artifactPath: miniappArtifactRoot(),
|
||
build: {},
|
||
...settings,
|
||
apiBaseUrl: this.effectiveApiBaseUrl(settings.apiBaseUrl),
|
||
privateKey: undefined,
|
||
credential: settings.credential ? { algorithm: "aes-256-gcm" } : null,
|
||
hasStoredCredentials: Boolean(settings.credential),
|
||
...buildConfig,
|
||
};
|
||
}
|
||
|
||
private buildConfigSummary(
|
||
storedApiBaseUrl: unknown,
|
||
storedAppId: unknown,
|
||
): {
|
||
requestDomain: string | null;
|
||
buildError: string | null;
|
||
} {
|
||
try {
|
||
const base = miniappApiBaseUrl(storedApiBaseUrl);
|
||
weappAppId(storedAppId);
|
||
return { requestDomain: new URL(base).host, buildError: null };
|
||
} catch (error) {
|
||
return {
|
||
requestDomain: null,
|
||
buildError: error instanceof Error ? error.message : "小程序构建参数未配置",
|
||
};
|
||
}
|
||
}
|
||
|
||
/** 表单回显:品牌未显式配置时展示环境推导出的默认地址,便于管理员在其基础上修改。 */
|
||
private effectiveApiBaseUrl(storedApiBaseUrl: unknown): string {
|
||
try {
|
||
return miniappApiBaseUrl(storedApiBaseUrl);
|
||
} catch {
|
||
return typeof storedApiBaseUrl === "string" ? storedApiBaseUrl : "";
|
||
}
|
||
}
|
||
|
||
@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) {
|
||
if (!body.privateKey.trim().startsWith("-----BEGIN"))
|
||
throw new BadRequestException("上传私钥格式无效:应为 -----BEGIN 开头的 PEM 内容");
|
||
const inspection = inspectPrivateKey(body.privateKey);
|
||
if (!inspection.valid)
|
||
throw new BadRequestException(
|
||
`上传私钥无法解析(${inspection.reason ?? "PEM 格式错误"})。请粘贴微信开发者工具生成的完整私钥,注意保留换行。`,
|
||
);
|
||
}
|
||
const current = this.jsonObject(await this.releases.settings(identity.brandId));
|
||
let apiBaseUrl: string | undefined;
|
||
if (body.apiBaseUrl !== undefined) {
|
||
const trimmed = body.apiBaseUrl.trim();
|
||
if (!trimmed) throw new BadRequestException("小程序请求地址不能为空");
|
||
try {
|
||
apiBaseUrl = validateApiBaseUrl(trimmed);
|
||
} catch (error) {
|
||
throw new BadRequestException(
|
||
error instanceof Error ? error.message : "小程序请求地址无效",
|
||
);
|
||
}
|
||
}
|
||
const credential =
|
||
body.privateKey === undefined
|
||
? current.credential
|
||
: encryptMiniAppCredential(normalizePrivateKey(body.privateKey));
|
||
const settings = {
|
||
...current,
|
||
appId: body.appId ?? current.appId ?? "",
|
||
apiBaseUrl: apiBaseUrl ?? current.apiBaseUrl ?? "",
|
||
build: {
|
||
...this.jsonObject(current.build),
|
||
...this.jsonObject(body.build),
|
||
} as Prisma.InputJsonObject,
|
||
...(credential ? { credential } : {}),
|
||
templateKey: current.templateKey ?? null,
|
||
} satisfies Prisma.InputJsonObject;
|
||
await this.releases.saveSettings(identity.brandId, settings);
|
||
return {
|
||
appId: settings.appId,
|
||
apiBaseUrl: this.effectiveApiBaseUrl(settings.apiBaseUrl),
|
||
artifactPath: miniappArtifactRoot(),
|
||
build: settings.build,
|
||
credential: settings.credential ? { algorithm: "aes-256-gcm" } : null,
|
||
hasStoredCredentials: Boolean(settings.credential),
|
||
...this.buildConfigSummary(settings.apiBaseUrl, settings.appId),
|
||
};
|
||
}
|
||
|
||
@Get()
|
||
list(@Req() request: FastifyRequest): Promise<unknown[]> {
|
||
return this.identity(request).then(({ brandId }) => this.releases.list(brandId));
|
||
}
|
||
|
||
@Post()
|
||
create(@Req() request: FastifyRequest, @Body() body: CreateMiniAppReleaseDto): Promise<unknown> {
|
||
return this.identity(request).then(({ brandId, subject }) =>
|
||
this.releases.create(brandId, subject, body),
|
||
);
|
||
}
|
||
|
||
@Post(":id/upload")
|
||
async upload(
|
||
@Req() request: FastifyRequest,
|
||
@Param("id") taskId: string,
|
||
@Body() body: UploadMiniAppReleaseDto,
|
||
): Promise<unknown> {
|
||
const identity = await this.identity(request);
|
||
const { task, brand } = await this.releases.uploadContext(identity.brandId, taskId);
|
||
if (task.status !== "built" && task.status !== "failed")
|
||
throw new BadRequestException("当前小程序发布任务不能重复上传");
|
||
const staleBuilding = isStaleBuilding(task);
|
||
if (task.buildStatus === "building" && !staleBuilding)
|
||
throw new ConflictException("小程序构建正在进行中,请稍后");
|
||
const settings = this.jsonObject(brand.miniAppSettings);
|
||
const appid = (() => {
|
||
try {
|
||
return weappAppId(settings.appId);
|
||
} catch (error) {
|
||
throw new BadRequestException(error instanceof Error ? error.message : "未配置微信 AppID");
|
||
}
|
||
})();
|
||
const privateKey = settings.credential
|
||
? decryptMiniAppCredential(settings.credential)
|
||
: this.requiredEnv("WECHAT_UPLOAD_PRIVATE_KEY");
|
||
const normalizedPrivateKey = normalizePrivateKey(privateKey);
|
||
const keyInspection = inspectPrivateKey(normalizedPrivateKey);
|
||
if (!keyInspection.valid)
|
||
throw new BadRequestException(
|
||
`上传私钥无法解析(${keyInspection.reason ?? "PEM 格式错误"})。请在“小程序上传配置”里重新粘贴完整私钥。`,
|
||
);
|
||
const templateKey = miniAppTemplateKey(brand.templateKey);
|
||
if (!templateKey) throw new BadRequestException("当前品牌模板没有可上传的小程序包");
|
||
let buildConfig: { apiBaseUrl: string; appId: string };
|
||
try {
|
||
buildConfig = {
|
||
apiBaseUrl: miniappApiBaseUrl(settings.apiBaseUrl),
|
||
appId: weappAppId(settings.appId),
|
||
};
|
||
} catch (error) {
|
||
throw new BadRequestException(
|
||
error instanceof Error ? error.message : "小程序构建参数未配置",
|
||
);
|
||
}
|
||
const projectPath = miniappProjectPath(templateKey);
|
||
const buildLogs: BuildLog[] = [
|
||
{
|
||
at: new Date().toISOString(),
|
||
message: `开始构建 ${templateKey} 微信小程序`,
|
||
stream: "stdout",
|
||
},
|
||
{
|
||
at: new Date().toISOString(),
|
||
message: `请求地址 ${buildConfig.apiBaseUrl},AppID ${buildConfig.appId}`,
|
||
stream: "stdout",
|
||
},
|
||
];
|
||
if (staleBuilding)
|
||
buildLogs.push({
|
||
at: new Date().toISOString(),
|
||
message: `上一次构建已超过 ${Math.round(buildingStaleMs() / 60000)} 分钟没有进展,按中断处理并重新构建`,
|
||
stream: "stderr",
|
||
});
|
||
if (task.status === "failed") {
|
||
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
|
||
status: "built",
|
||
buildLogs,
|
||
buildStatus: "building",
|
||
});
|
||
} else {
|
||
await this.releases.updateBuild(identity.brandId, identity.subject, taskId, {
|
||
buildLogs,
|
||
buildStatus: "building",
|
||
error: null,
|
||
});
|
||
}
|
||
const result = await this.buildWeApp(templateKey, buildConfig, (message, stream) => {
|
||
buildLogs.push({ at: new Date().toISOString(), message, stream });
|
||
void this.releases
|
||
.updateBuild(identity.brandId, identity.subject, taskId, {
|
||
buildLogs,
|
||
buildStatus: "building",
|
||
})
|
||
.catch(() => undefined);
|
||
});
|
||
if (result.exitCode !== 0) {
|
||
buildLogs.push({
|
||
at: new Date().toISOString(),
|
||
message: `构建失败,退出码 ${result.exitCode}`,
|
||
stream: "stderr",
|
||
});
|
||
await this.releases.updateBuild(identity.brandId, identity.subject, taskId, {
|
||
error: `小程序构建失败,请查看构建日志`,
|
||
buildLogs,
|
||
buildStatus: "failed",
|
||
});
|
||
throw new BadRequestException("小程序构建失败,请查看构建日志");
|
||
}
|
||
if (!existsSync(projectPath) || !existsSync(resolve(projectPath, "app.json"))) {
|
||
buildLogs.push({
|
||
at: new Date().toISOString(),
|
||
message: `构建完成但缺少产物:${projectPath}/app.json`,
|
||
stream: "stderr",
|
||
});
|
||
await this.releases.updateBuild(identity.brandId, identity.subject, taskId, {
|
||
error: "小程序构建产物缺少 app.json",
|
||
buildLogs,
|
||
buildStatus: "failed",
|
||
});
|
||
throw new BadRequestException(`小程序构建产物缺少 app.json:${projectPath}`);
|
||
}
|
||
buildLogs.push({
|
||
at: new Date().toISOString(),
|
||
message: "构建完成,开始上传微信",
|
||
stream: "stdout",
|
||
});
|
||
await this.releases.updateBuild(identity.brandId, identity.subject, taskId, {
|
||
buildLogs,
|
||
buildStatus: "success",
|
||
});
|
||
try {
|
||
const uploadResult = await runMiniAppUpload({
|
||
projectPath,
|
||
appid,
|
||
privateKey: normalizedPrivateKey,
|
||
version: body.version ?? String(task.version),
|
||
desc: body.desc ?? `brand content v${task.version}`,
|
||
robot: body.robot ?? 1,
|
||
});
|
||
return this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
|
||
status: "uploaded",
|
||
buildLogs,
|
||
buildStatus: "success",
|
||
weappUploadId:
|
||
typeof uploadResult.strUint64Version === "string"
|
||
? uploadResult.strUint64Version
|
||
: String(task.version),
|
||
});
|
||
} catch (error) {
|
||
const message = error instanceof Error ? error.message : "微信代码上传失败";
|
||
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
|
||
status: "failed",
|
||
buildLogs,
|
||
buildStatus: "failed",
|
||
error: message,
|
||
});
|
||
throw new BadGatewayException(message);
|
||
}
|
||
}
|
||
|
||
@Patch(":id/status")
|
||
async updateStatus(
|
||
@Req() request: FastifyRequest,
|
||
@Param("id") taskId: string,
|
||
@Body() body: UpdateMiniAppReleaseStatusDto,
|
||
): Promise<unknown> {
|
||
const identity = await this.identity(request);
|
||
return this.releases.updateStatus(identity.brandId, identity.subject, taskId, body);
|
||
}
|
||
|
||
private async identity(request: FastifyRequest): Promise<{ subject: string; brandId: string }> {
|
||
const { subject, brandId } = await this.access.requireBrand(request);
|
||
return { subject, brandId };
|
||
}
|
||
|
||
private requiredEnv(name: string): string {
|
||
const value = process.env[name];
|
||
if (!value) throw new BadRequestException(`${name} 未配置`);
|
||
return value;
|
||
}
|
||
|
||
private buildWeApp(
|
||
templateKey: string,
|
||
buildConfig: { apiBaseUrl: string; appId: string },
|
||
onLog: (message: string, stream: "stdout" | "stderr") => void,
|
||
): Promise<{ exitCode: number }> {
|
||
return new Promise((resolvePromise, rejectPromise) => {
|
||
const child = spawn("pnpm", ["--filter", "@personal-brand/taro", "build:weapp"], {
|
||
cwd: REPOSITORY_ROOT,
|
||
env: {
|
||
...process.env,
|
||
TEMPLATE_KEY: templateKey,
|
||
TARO_ENV: "weapp",
|
||
API_BASE_URL: buildConfig.apiBaseUrl,
|
||
WEAPP_APP_ID: buildConfig.appId,
|
||
},
|
||
shell: process.platform === "win32",
|
||
}) as BuildProcess;
|
||
const readStream = (stream: NodeJS.ReadableStream, name: "stdout" | "stderr") => {
|
||
let buffer = "";
|
||
stream.on("data", (chunk: Buffer | string) => {
|
||
buffer += chunk.toString();
|
||
for (const message of buffer.split("\n").slice(0, -1)) onLog(message, name);
|
||
buffer = buffer.slice(buffer.lastIndexOf("\n") + 1);
|
||
});
|
||
stream.on("end", () => {
|
||
if (buffer) onLog(buffer, name);
|
||
});
|
||
};
|
||
readStream(child.stdout, "stdout");
|
||
readStream(child.stderr, "stderr");
|
||
child.on("close", (code) => resolvePromise({ exitCode: code ?? 1 }));
|
||
child.on("error", () => rejectPromise(new Error("小程序构建进程启动失败")));
|
||
});
|
||
}
|
||
|
||
private jsonObject(value: unknown): Record<string, unknown> {
|
||
return value && typeof value === "object" && !Array.isArray(value)
|
||
? (value as Record<string, unknown>)
|
||
: {};
|
||
}
|
||
}
|