fix: 打通小程序代码上传链路

小程序上传此前连续失败,根因分散在状态机、产物路径、模块导入、私钥解析和进程隔离上,逐项修复:

- 构建进度改用 updateBuild 只写 buildStatus/buildLogs,不再用 updateStatus 记录进度,避免状态机拒绝自我迁移而返回 409
- 产物目录锚定仓库根目录,不再随 API 进程工作目录变成 apps/api/apps/taro/dist
- miniprogram-ci 为 CommonJS 包,动态导入后从 default 归一化取 Project/upload,替换原有的类型断言
- 上传私钥统一还原成合法 PEM;输入框曾把换行吞成单行,导致 OpenSSL 解码失败,现保存时校验、上传时自动修复存量数据
- 上传改在独立子进程执行,miniprogram-ci 崩溃或超时不再终止 API 进程,失败返回 502 并保留微信原始错误
- 构建超过 MINIAPP_BUILD_STALE_MS 无进度即视为中断,允许重新上传,避免任务永久卡在 building
- 构建前校验请求地址与 AppID,请求地址支持在品牌配置中维护,环境变量仅作回落,避免再打出指向 localhost 的包
- 小程序 /media/ 按请求地址的 origin 解析,不再依赖网关剥离 /api 前缀

新增对应单测与集成断言,并更新部署说明。
This commit is contained in:
que01 committed 2026-10-13 21:58:48 +08:00
1 parent f52577ff9e
commit 44fe7a0142
27 files changed
+986 -62

No files matched your search

@@ -1,5 +1,6 @@
import {
BadRequestException,
BadGatewayException,
Body,
ConflictException,
Controller,
@@ -19,15 +20,18 @@ 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 { 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";
const MINIAPP_ARTIFACT_ROOT = process.env.MINIAPP_ARTIFACT_ROOT ?? "apps/taro/dist";
function miniAppTemplateKey(industryTemplateKey: string): string | null {
return (
getTemplatePackageManifest(industryTemplateKey)?.packageKey ??
@@ -38,22 +42,6 @@ function miniAppTemplateKey(industryTemplateKey: string): string | null {
);
}
interface MiniprogramCi {
Project: new (options: {
projectPath: string;
type: "miniProgram";
appid: string;
privateKey: string;
}) => unknown;
upload: (options: {
project: unknown;
version: string;
desc: string;
robot: number;
setting: { es6: boolean; minified: boolean };
}) => Promise<Record<string, unknown>>;
}
interface BuildLog {
at: string;
message: string;
@@ -92,17 +80,48 @@ export class AdminMiniAppReleaseController {
select: { miniAppSettings: true },
});
const settings = this.jsonObject(brand?.miniAppSettings);
const buildConfig = this.buildConfigSummary(settings.apiBaseUrl, settings.appId);
return {
appId: "",
artifactPath: MINIAPP_ARTIFACT_ROOT,
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,
@@ -110,20 +129,40 @@ export class AdminMiniAppReleaseController {
): 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("上传私钥格式无效");
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 brand = await this.prisma.brandProfile.findUniqueOrThrow({
where: { id: identity.brandId },
select: { miniAppSettings: true },
});
const current = this.jsonObject(brand.miniAppSettings);
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(body.privateKey);
: 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),
@@ -137,10 +176,12 @@ export class AdminMiniAppReleaseController {
});
return {
appId: settings.appId,
artifactPath: MINIAPP_ARTIFACT_ROOT,
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),
};
}
@@ -169,40 +210,79 @@ export class AdminMiniAppReleaseController {
if (!task) throw new BadRequestException("小程序发布任务不存在");
if (task.status !== "built" && task.status !== "failed")
throw new BadRequestException("当前小程序发布任务不能重复上传");
if (task.buildStatus === "building")
const staleBuilding = isStaleBuilding(task);
if (task.buildStatus === "building" && !staleBuilding)
throw new ConflictException("小程序构建正在进行中,请稍后");
const brand = await this.prisma.brandProfile.findUniqueOrThrow({
where: { id: identity.brandId },
select: { miniAppSettings: true, templateKey: true },
});
const settings = this.jsonObject(brand.miniAppSettings);
const appid =
typeof settings.appId === "string" && settings.appId
? settings.appId
: this.requiredEnv("WECHAT_APP_ID");
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("当前品牌模板没有可上传的小程序包");
const projectPath = resolve(MINIAPP_ARTIFACT_ROOT, templateKey, "weapp");
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",
},
];
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
status: task.status,
buildLogs,
buildStatus: "building",
});
const result = await this.buildWeApp(templateKey, (message, stream) => {
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
.updateStatus(identity.brandId, identity.subject, taskId, {
status: task.status,
.updateBuild(identity.brandId, identity.subject, taskId, {
buildLogs,
buildStatus: "building",
})
@@ -214,8 +294,7 @@ export class AdminMiniAppReleaseController {
message: `构建失败,退出码 ${result.exitCode}`,
stream: "stderr",
});
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
status: task.status,
await this.releases.updateBuild(identity.brandId, identity.subject, taskId, {
error: `小程序构建失败,请查看构建日志`,
buildLogs,
buildStatus: "failed",
@@ -228,38 +307,30 @@ export class AdminMiniAppReleaseController {
message: `构建完成但缺少产物:${projectPath}/app.json`,
stream: "stderr",
});
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
status: task.status,
await this.releases.updateBuild(identity.brandId, identity.subject, taskId, {
error: "小程序构建产物缺少 app.json",
buildLogs,
buildStatus: "failed",
});
throw new BadRequestException("小程序构建产物缺少 app.json");
throw new BadRequestException(`小程序构建产物缺少 app.json:${projectPath}`);
}
buildLogs.push({
at: new Date().toISOString(),
message: "构建完成,开始上传微信",
stream: "stdout",
});
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
status: task.status,
await this.releases.updateBuild(identity.brandId, identity.subject, taskId, {
buildLogs,
buildStatus: "success",
});
const ci = (await import("miniprogram-ci")) as unknown as MiniprogramCi;
const project = new ci.Project({
projectPath,
type: "miniProgram",
appid,
privateKey,
});
try {
const uploadResult = await ci.upload({
project,
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,
setting: { es6: false, minified: true },
});
return this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
status: "uploaded",
@@ -271,13 +342,14 @@ export class AdminMiniAppReleaseController {
: 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: error instanceof Error ? error.message : "微信代码上传失败",
error: message,
});
throw error;
throw new BadGatewayException(message);
}
}
@@ -304,12 +376,19 @@ export class AdminMiniAppReleaseController {
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: resolve(process.cwd(), "../.."),
env: { ...process.env, TEMPLATE_KEY: templateKey, TARO_ENV: "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") => {