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:
1 parent
f52577ff9e
commit
44fe7a0142
27 files changed
+986
-62
No files matched your search
@@ -0,0 +1,81 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { ConflictException, NotFoundException } from "@nestjs/common";
|
||||
import { AdminMiniAppReleaseService } from "../src/modules/admin/admin-miniapp-release.service.js";
|
||||
import type { PrismaService } from "../src/prisma.service.js";
|
||||
|
||||
const brandId = "brand-1";
|
||||
const actorId = "admin-1";
|
||||
|
||||
function createService(task: Record<string, unknown> | null): AdminMiniAppReleaseService {
|
||||
const prisma = {
|
||||
$transaction: async (callback: (tx: unknown) => unknown) =>
|
||||
callback({
|
||||
miniAppReleaseTask: {
|
||||
findFirst: async () => task,
|
||||
update: async ({ data }: { data: Record<string, unknown> }) => ({ ...task, ...data }),
|
||||
},
|
||||
}),
|
||||
} as unknown as PrismaService;
|
||||
return new AdminMiniAppReleaseService(prisma);
|
||||
}
|
||||
|
||||
function builtTask(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: "task-1",
|
||||
brandId,
|
||||
version: 3,
|
||||
status: "built",
|
||||
buildStatus: "idle",
|
||||
error: null,
|
||||
buildLogs: [],
|
||||
audit: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
test("构建进度更新不触发发布状态机的顺序校验", async () => {
|
||||
const release = await createService(builtTask()).updateBuild(brandId, actorId, "task-1", {
|
||||
buildLogs: [{ message: "开始构建", stream: "stdout" }],
|
||||
buildStatus: "building",
|
||||
});
|
||||
assert.equal((release as { status: string }).status, "built");
|
||||
assert.equal((release as { buildStatus: string }).buildStatus, "building");
|
||||
});
|
||||
|
||||
test("构建进度更新按品牌隔离,任务不存在时抛出 404", async () => {
|
||||
await assert.rejects(
|
||||
() => createService(null).updateBuild(brandId, actorId, "task-1", { buildStatus: "building" }),
|
||||
NotFoundException,
|
||||
);
|
||||
});
|
||||
|
||||
test("重新构建时可以清除上一次遗留的错误信息", async () => {
|
||||
const release = await createService(
|
||||
builtTask({ buildStatus: "failed", error: "小程序构建产物缺少 app.json" }),
|
||||
).updateBuild(brandId, actorId, "task-1", { buildStatus: "building", error: null });
|
||||
assert.equal((release as { error: string | null }).error, null);
|
||||
assert.equal((release as { buildStatus: string }).buildStatus, "building");
|
||||
});
|
||||
|
||||
test("发布状态机仍拒绝越级变更并允许合法上传流转", async () => {
|
||||
await assert.rejects(
|
||||
() =>
|
||||
createService(builtTask()).updateStatus(brandId, actorId, "task-1", { status: "published" }),
|
||||
ConflictException,
|
||||
);
|
||||
const uploaded = await createService(builtTask()).updateStatus(brandId, actorId, "task-1", {
|
||||
status: "uploaded",
|
||||
weappUploadId: "test-upload",
|
||||
});
|
||||
assert.equal((uploaded as { status: string }).status, "uploaded");
|
||||
assert.equal((uploaded as { weappUploadId: string }).weappUploadId, "test-upload");
|
||||
});
|
||||
|
||||
test("失败任务重试时可回到 built 并清除错误", async () => {
|
||||
const release = await createService(
|
||||
builtTask({ status: "failed", buildStatus: "failed", error: "上传失败" }),
|
||||
).updateStatus(brandId, actorId, "task-1", { status: "built", buildStatus: "building" });
|
||||
assert.equal((release as { status: string }).status, "built");
|
||||
assert.equal((release as { error: string | null }).error, null);
|
||||
});
|
||||
@@ -94,6 +94,23 @@ test("miniapp release tasks are authorized, idempotent, and state checked", asyn
|
||||
payload: { status: "published" },
|
||||
});
|
||||
assert.equal(JSON.parse(published.body).status, "published");
|
||||
|
||||
const buildingTask = await prisma.miniAppReleaseTask.create({
|
||||
data: {
|
||||
brandId,
|
||||
version: 900001,
|
||||
actorId: "integration-test",
|
||||
status: "built",
|
||||
buildStatus: "building",
|
||||
},
|
||||
});
|
||||
const busy = await request(`/admin/miniapp-releases/${buildingTask.id}/upload`, {
|
||||
method: "POST",
|
||||
headers,
|
||||
payload: {},
|
||||
});
|
||||
assert.equal(busy.statusCode, 409);
|
||||
await prisma.miniAppReleaseTask.delete({ where: { id: buildingTask.id } });
|
||||
});
|
||||
|
||||
test("miniapp release settings never expose or persist plaintext private keys", async () => {
|
||||
@@ -102,18 +119,47 @@ test("miniapp release settings never expose or persist plaintext private keys",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const headers = { authorization: `Bearer ${JSON.parse(login.body).token}` };
|
||||
const privateKey = `-----BEGIN TEST KEY-----\n${Date.now()}\n-----END TEST KEY-----`;
|
||||
const { generateKeyPairSync } = await import("node:crypto");
|
||||
const privateKey = generateKeyPairSync("rsa", {
|
||||
modulusLength: 2048,
|
||||
privateKeyEncoding: { type: "pkcs8", format: "pem" },
|
||||
publicKeyEncoding: { type: "spki", format: "pem" },
|
||||
}).privateKey;
|
||||
const invalid = await request("/admin/miniapp-releases/settings", {
|
||||
method: "PATCH",
|
||||
headers,
|
||||
payload: {
|
||||
appId: "wxtestsettings",
|
||||
privateKey: "-----BEGIN PRIVATE KEY-----\nMIIB\n-----END PRIVATE KEY-----",
|
||||
},
|
||||
});
|
||||
assert.equal(invalid.statusCode, 400);
|
||||
const rejected = await request("/admin/miniapp-releases/settings", {
|
||||
method: "PATCH",
|
||||
headers,
|
||||
payload: { appId: "wxtestsettings", apiBaseUrl: "http://wechat.example.com/api" },
|
||||
});
|
||||
assert.equal(rejected.statusCode, 400);
|
||||
const saved = await request("/admin/miniapp-releases/settings", {
|
||||
method: "PATCH",
|
||||
headers,
|
||||
payload: { appId: "wxtestsettings", privateKey },
|
||||
payload: {
|
||||
appId: "wxtestsettings",
|
||||
apiBaseUrl: "https://wechat.example.com/api/",
|
||||
privateKey,
|
||||
},
|
||||
});
|
||||
assert.equal(saved.statusCode, 200);
|
||||
const body = JSON.parse(saved.body);
|
||||
assert.equal(body.appId, "wxtestsettings");
|
||||
assert.equal(body.apiBaseUrl, "https://wechat.example.com/api");
|
||||
assert.equal(body.requestDomain, "wechat.example.com");
|
||||
assert.equal(body.hasStoredCredentials, true);
|
||||
assert.equal(body.privateKey, undefined);
|
||||
assert.equal(body.credential?.algorithm, "aes-256-gcm");
|
||||
assert.ok(body.requestDomain === null || typeof body.requestDomain === "string");
|
||||
assert.ok(body.buildError === null || typeof body.buildError === "string");
|
||||
if (typeof body.requestDomain === "string") assert.ok(!body.requestDomain.includes("localhost"));
|
||||
const brand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } });
|
||||
const credential = brand.miniAppSettings?.credential;
|
||||
assert.ok(credential);
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { existsSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { test } from "node:test";
|
||||
import {
|
||||
miniappArtifactRoot,
|
||||
miniappProjectPath,
|
||||
REPOSITORY_ROOT,
|
||||
} from "../src/modules/admin/miniapp-artifact.js";
|
||||
|
||||
test("小程序产物根目录锚定仓库根目录,不随 API 进程工作目录变化", () => {
|
||||
const configured = process.env.MINIAPP_ARTIFACT_ROOT;
|
||||
delete process.env.MINIAPP_ARTIFACT_ROOT;
|
||||
try {
|
||||
assert.ok(existsSync(resolve(REPOSITORY_ROOT, "pnpm-workspace.yaml")));
|
||||
assert.equal(miniappArtifactRoot(), resolve(REPOSITORY_ROOT, "apps/taro/dist"));
|
||||
assert.ok(!miniappArtifactRoot().includes(resolve(REPOSITORY_ROOT, "apps/api")));
|
||||
} finally {
|
||||
if (configured !== undefined) process.env.MINIAPP_ARTIFACT_ROOT = configured;
|
||||
}
|
||||
});
|
||||
|
||||
test("按模板包 key 生成唯一的微信小程序产物目录", () => {
|
||||
const configured = process.env.MINIAPP_ARTIFACT_ROOT;
|
||||
delete process.env.MINIAPP_ARTIFACT_ROOT;
|
||||
try {
|
||||
assert.equal(
|
||||
miniappProjectPath("linjing-editorial"),
|
||||
resolve(REPOSITORY_ROOT, "apps/taro/dist/linjing-editorial/weapp"),
|
||||
);
|
||||
} finally {
|
||||
if (configured !== undefined) process.env.MINIAPP_ARTIFACT_ROOT = configured;
|
||||
}
|
||||
});
|
||||
|
||||
test("显式配置的产物根目录按仓库根目录解析相对路径", () => {
|
||||
assert.equal(
|
||||
miniappArtifactRoot("custom/artifacts"),
|
||||
resolve(REPOSITORY_ROOT, "custom/artifacts"),
|
||||
);
|
||||
assert.equal(miniappArtifactRoot("/srv/miniapp"), resolve("/srv/miniapp"));
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import {
|
||||
miniappApiBaseUrl,
|
||||
validateApiBaseUrl,
|
||||
weappAppId,
|
||||
} from "../src/modules/admin/miniapp-build-config.js";
|
||||
|
||||
test("后台配置的请求地址优先于环境变量,改域名不需要动服务端配置", () => {
|
||||
const env = { MINIAPP_API_BASE_URL: "https://env.example.com/api" };
|
||||
assert.equal(
|
||||
miniappApiBaseUrl("https://stored.example.com/api/", env),
|
||||
"https://stored.example.com/api",
|
||||
);
|
||||
assert.equal(miniappApiBaseUrl("", env), "https://env.example.com/api");
|
||||
assert.equal(miniappApiBaseUrl(undefined, env), "https://env.example.com/api");
|
||||
});
|
||||
|
||||
test("后台地址允许带路径前缀,保存前会去掉结尾斜杠", () => {
|
||||
assert.equal(
|
||||
validateApiBaseUrl("https://wechat.app.que01.top/api/"),
|
||||
"https://wechat.app.que01.top/api",
|
||||
);
|
||||
assert.throws(() => validateApiBaseUrl("http://wechat.app.que01.top/api"), /https/);
|
||||
});
|
||||
|
||||
test("优先使用 MINIAPP_API_BASE_URL,去掉结尾斜杠", () => {
|
||||
assert.equal(
|
||||
miniappApiBaseUrl(undefined, { MINIAPP_API_BASE_URL: "https://wechat.app.que01.top/api/" }),
|
||||
"https://wechat.app.que01.top/api",
|
||||
);
|
||||
});
|
||||
|
||||
test("没有显式配置时由 PUBLIC_BASE_URL 加默认 /api 推导", () => {
|
||||
assert.equal(
|
||||
miniappApiBaseUrl(undefined, { PUBLIC_BASE_URL: "https://wechat.app.que01.top" }),
|
||||
"https://wechat.app.que01.top/api",
|
||||
);
|
||||
assert.equal(
|
||||
miniappApiBaseUrl(undefined, {
|
||||
PUBLIC_BASE_URL: "https://wechat.app.que01.top/",
|
||||
MINIAPP_API_PATH: "/v2",
|
||||
}),
|
||||
"https://wechat.app.que01.top/v2",
|
||||
);
|
||||
});
|
||||
|
||||
test("非 https 的公网地址必须被拒绝,避免再次打出 localhost 包", () => {
|
||||
assert.throws(
|
||||
() => miniappApiBaseUrl(undefined, { MINIAPP_API_BASE_URL: "http://wechat.app.que01.top/api" }),
|
||||
/https/,
|
||||
);
|
||||
assert.throws(() => miniappApiBaseUrl(undefined, { MINIAPP_API_BASE_URL: "https://" }), /URL/);
|
||||
assert.throws(() => miniappApiBaseUrl(undefined, {}), /小程序请求地址/);
|
||||
});
|
||||
|
||||
test("本地调试地址允许 http,方便开发环境构建", () => {
|
||||
assert.equal(
|
||||
miniappApiBaseUrl(undefined, { MINIAPP_API_BASE_URL: "http://localhost:3001" }),
|
||||
"http://localhost:3001",
|
||||
);
|
||||
assert.equal(
|
||||
miniappApiBaseUrl(undefined, { MINIAPP_API_BASE_URL: "http://127.0.0.1:3001" }),
|
||||
"http://127.0.0.1:3001",
|
||||
);
|
||||
});
|
||||
|
||||
test("AppID 取品牌配置优先,回落 WEAPP_APP_ID,并拒绝占位值", () => {
|
||||
assert.equal(weappAppId("wxd75d946d6978d183", {}), "wxd75d946d6978d183");
|
||||
assert.equal(weappAppId(null, { WEAPP_APP_ID: "wxfallback" }), "wxfallback");
|
||||
assert.throws(() => weappAppId("undefined", {}), /AppID/);
|
||||
assert.throws(() => weappAppId("touristappid", {}), /AppID/);
|
||||
assert.throws(() => weappAppId("", {}), /AppID/);
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { buildingStaleMs, isStaleBuilding } from "../src/modules/admin/miniapp-build-status.js";
|
||||
|
||||
const now = Date.UTC(2026, 9, 13, 12, 0, 0);
|
||||
|
||||
function task(buildStatus: string, minutesAgo: number) {
|
||||
return { buildStatus, updatedAt: new Date(now - minutesAgo * 60_000) };
|
||||
}
|
||||
|
||||
test("构建中的任务在超过阈值未更新时视为已中断", () => {
|
||||
assert.equal(isStaleBuilding(task("building", 1), now), false);
|
||||
assert.equal(isStaleBuilding(task("building", 16), now), true);
|
||||
assert.equal(isStaleBuilding(task("building", 24 * 60), now), true);
|
||||
});
|
||||
|
||||
test("非 building 状态永远不算中断,避免误伤正常流程", () => {
|
||||
for (const status of ["idle", "success", "failed"]) {
|
||||
assert.equal(isStaleBuilding(task(status, 24 * 60), now), false);
|
||||
}
|
||||
});
|
||||
|
||||
test("时间戳异常时按未中断处理,宁可挡住重试也不允许并发构建", () => {
|
||||
assert.equal(isStaleBuilding({ buildStatus: "building", updatedAt: "not-a-date" }, now), false);
|
||||
});
|
||||
|
||||
test("阈值可通过环境变量覆盖,非法值回退到默认 15 分钟", () => {
|
||||
assert.equal(buildingStaleMs("60000"), 60_000);
|
||||
for (const invalid of [undefined, "0", "-1", "abc"]) {
|
||||
assert.equal(buildingStaleMs(invalid), 15 * 60 * 1000);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { resolveMiniprogramCi } from "../src/modules/admin/miniapp-ci.js";
|
||||
|
||||
function fakeCi() {
|
||||
return {
|
||||
Project: class {},
|
||||
upload: async () => ({ strUint64Version: "1" }),
|
||||
};
|
||||
}
|
||||
|
||||
test("CommonJS 形态的 miniprogram-ci 从 default 上取 Project 与 upload", () => {
|
||||
const ci = fakeCi();
|
||||
const resolved = resolveMiniprogramCi({ default: ci, __esModule: true });
|
||||
assert.equal(resolved.Project, ci.Project);
|
||||
assert.equal(resolved.upload, ci.upload);
|
||||
});
|
||||
|
||||
test("已是命名导出的模块可以直接使用", () => {
|
||||
const ci = fakeCi();
|
||||
const resolved = resolveMiniprogramCi(ci);
|
||||
assert.equal(resolved.Project, ci.Project);
|
||||
assert.equal(resolved.upload, ci.upload);
|
||||
});
|
||||
|
||||
test("缺少 Project 或 upload 时抛出明确错误,而不是 undefined is not a constructor", () => {
|
||||
assert.throws(
|
||||
() => resolveMiniprogramCi({ default: { upload: async () => ({}) } }),
|
||||
/miniprogram-ci/,
|
||||
);
|
||||
assert.throws(() => resolveMiniprogramCi({ Project: class {} }), /miniprogram-ci/);
|
||||
assert.throws(() => resolveMiniprogramCi(null), /miniprogram-ci/);
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { generateKeyPairSync } from "node:crypto";
|
||||
import { test } from "node:test";
|
||||
import {
|
||||
inspectPrivateKey,
|
||||
normalizePrivateKey,
|
||||
} from "../src/modules/admin/miniapp-private-key.js";
|
||||
|
||||
function pemWithNewlines(): string {
|
||||
const { privateKey } = generateKeyPairSync("rsa", {
|
||||
modulusLength: 2048,
|
||||
privateKeyEncoding: { type: "pkcs8", format: "pem" },
|
||||
publicKeyEncoding: { type: "spki", format: "pem" },
|
||||
});
|
||||
return privateKey;
|
||||
}
|
||||
|
||||
test("单行私钥(换行被输入框吞掉)可以还原为合法 PEM 并恢复签名能力", () => {
|
||||
const pem = pemWithNewlines();
|
||||
const flattened = pem.replace(/\n/g, " ").replace(/\s+/g, " ").trim();
|
||||
assert.equal(inspectPrivateKey(flattened).valid, true);
|
||||
assert.ok(normalizePrivateKey(flattened).split("\n").length > 10);
|
||||
});
|
||||
|
||||
test("字面量 \\n 转义的私钥同样可以还原", () => {
|
||||
const pem = pemWithNewlines();
|
||||
assert.equal(inspectPrivateKey(pem.replace(/\n/g, "\\n")).valid, true);
|
||||
});
|
||||
|
||||
test("规范化是幂等的,不会反复改写已正确的 PEM", () => {
|
||||
const normalized = normalizePrivateKey(pemWithNewlines());
|
||||
assert.equal(normalizePrivateKey(normalized), normalized);
|
||||
assert.equal(inspectPrivateKey(normalized).valid, true);
|
||||
assert.equal(inspectPrivateKey(normalized).kind, "rsa");
|
||||
});
|
||||
|
||||
test("损坏或非 PEM 内容会被判定为无效,而不是静默保存", () => {
|
||||
assert.equal(inspectPrivateKey("not-a-pem").valid, false);
|
||||
assert.equal(
|
||||
inspectPrivateKey("-----BEGIN PRIVATE KEY-----\nMIIB\n-----END PRIVATE KEY-----").valid,
|
||||
false,
|
||||
);
|
||||
const truncated = pemWithNewlines().slice(0, 120);
|
||||
assert.equal(inspectPrivateKey(truncated).valid, false);
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { runMiniAppUpload } from "../src/modules/admin/miniapp-upload.js";
|
||||
|
||||
const invalidRequest = {
|
||||
projectPath: "/tmp/not-a-project",
|
||||
appid: "wxtest",
|
||||
privateKey: "not-a-pem",
|
||||
version: "1",
|
||||
desc: "test",
|
||||
robot: 1,
|
||||
};
|
||||
|
||||
test("上传在独立进程执行,失败时返回可读错误且不抛出未捕获异常", async () => {
|
||||
await assert.rejects(
|
||||
() => runMiniAppUpload(invalidRequest, 60_000),
|
||||
(error: Error) => {
|
||||
assert.match(error.message, /微信代码上传失败|上传进程/);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("上传超时会终止子进程并返回明确错误", async () => {
|
||||
await assert.rejects(
|
||||
() => runMiniAppUpload(invalidRequest, 1),
|
||||
(error: Error) => {
|
||||
assert.ok(error.message.includes("超时") || error.message.includes("上传"));
|
||||
return true;
|
||||
},
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user