fix: 修复系统一致性与安全问题

This commit is contained in:
que01 committed 2026-10-14 17:36:46 +08:00
1 parent aaeec14733
commit f158f906d5
19 files changed
+194 -34

No files matched your search

+1 -1
View File
@@ -8,7 +8,7 @@ DATABASE_URL=postgresql://personal_brand:replace-with-a-long-database-password@1
SESSION_SECRET=replace-with-at-least-32-random-characters
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
SEED_ADMIN_PASSWORD=replace-with-a-one-time-initial-password
SEED_MODE=seed
SEED_MODE=skip
API_PORT=3001
API_PREFIX=
+7 -3
View File
@@ -1,7 +1,7 @@
import { CloudUploadOutlined, DeleteOutlined, PictureOutlined } from "@ant-design/icons";
import { Alert, Button, Image, Popconfirm, Spin, Upload, message } from "antd";
import { useEffect, useMemo, useState } from "react";
import { createApiClient } from "../lib/api.js";
import { apiBaseUrl, createApiClient } from "../lib/api.js";
interface ImageUrlFieldProps {
id?: string;
@@ -50,11 +50,15 @@ export function ImageUrlField({ id, value, onChange, placeholder, scope }: Image
contentType: file.type,
...(scope ? { scope } : {}),
});
const response = await fetch(presign.uploadUrl, {
const isLocalUpload = presign.mode === "local";
const uploadUrl = isLocalUpload
? `${apiBaseUrl.replace(/\/$/, "")}${presign.uploadUrl}`
: presign.uploadUrl;
const response = await fetch(uploadUrl, {
method: "PUT",
headers: {
"content-type": file.type,
...(presign.uploadUrl.startsWith("/api/")
...(isLocalUpload
? { authorization: `Bearer ${localStorage.getItem("adminToken") ?? ""}` }
: {}),
},
@@ -47,7 +47,6 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
const [miniAppSettingsForm] = Form.useForm<{
appId: string;
apiBaseUrl: string;
artifactPath: string;
privateKey?: string;
}>();
const brand = useQuery({
@@ -92,7 +91,6 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
miniAppSettingsForm.setFieldsValue({
appId: miniAppSettings.data.appId,
apiBaseUrl: miniAppSettings.data.apiBaseUrl,
artifactPath: miniAppSettings.data.artifactPath,
privateKey: "",
});
}, [miniAppSettings.data, miniAppSettingsForm]);
@@ -202,10 +200,10 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
},
});
const saveMiniAppSettings = useMutation({
mutationFn: (values: { appId: string; artifactPath: string; privateKey?: string }) =>
mutationFn: (values: { appId: string; apiBaseUrl: string; privateKey?: string }) =>
client.updateAdminMiniAppSettings({
appId: values.appId,
artifactPath: values.artifactPath,
apiBaseUrl: values.apiBaseUrl,
...(values.privateKey ? { privateKey: values.privateKey } : {}),
}),
onSuccess: () => {
+6
View File
@@ -19,6 +19,12 @@ export class AdminAccessService {
throw new UnauthorizedException("管理员登录态无效或已过期");
}
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
const user = await this.prisma.adminUser.findUnique({
where: { id: identity.subject },
select: { mustChangePassword: true },
});
if (!user || user.mustChangePassword)
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
const membership = await this.prisma.brandMembership.findUnique({
where: { adminUserId_brandId: { adminUserId: identity.subject, brandId: identity.brandId } },
});
+1
View File
@@ -10,6 +10,7 @@ export class AdminMembershipGuard implements CanActivate {
canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<FastifyRequest>();
if (request.url.startsWith("/admin/session/login")) return Promise.resolve(true);
if (request.url.startsWith("/admin/session/change-password")) return Promise.resolve(true);
if (!request.url.startsWith("/admin/")) return Promise.resolve(true);
if (
/^\/admin\/workspace\/(install|capabilities(?:\/|$)|template(?:\/|$)|fields(?:\/|$))/.test(
+1 -1
View File
@@ -164,7 +164,7 @@ class AdminWorkspaceController {
where: { brandId, source: "sample" },
});
const existingOffering = await this.prisma.offering.count({
where: { brandId, name: "序章·入户门" },
where: { brandId, name: { in: sample.offerings.map((item) => item.name) } },
});
if (existing || existingOffering) throw new BadRequestException("示例内容已经导入");
const result = await this.prisma.$transaction(async (tx) => {
@@ -11,7 +11,6 @@ export class UpdateMiniAppSettingsDto {
@MaxLength(200)
apiBaseUrl?: string;
@IsOptional()
@IsOptional()
@IsObject()
build?: Record<string, unknown>;
@@ -136,7 +136,7 @@ export class AdminUploadController {
const target = path.join(this.localMediaRoot, key);
await mkdir(path.dirname(target), { recursive: true });
return {
uploadUrl: `/api/admin/uploads/local?key=${encodeURIComponent(key)}`,
uploadUrl: `/admin/uploads/local?key=${encodeURIComponent(key)}`,
key,
publicUrl: `${this.localMediaBaseUrl}/${key}`,
mode: "local",
@@ -132,7 +132,8 @@ export class CustomerInquirySubmissionController {
if (field.type === "number" && !Number.isFinite(Number(value)))
throw new BadRequestException(`${label}必须是数字`);
}
const allowedKeys = new Set(fields.map((field) => String(field.key)));
const visibleFields = fields.filter((field) => this.isVisibleField(field, body.values));
const allowedKeys = new Set(visibleFields.map((field) => String(field.key)));
const values = Object.fromEntries(
Object.entries(body.values).filter(([key]) => allowedKeys.has(key)),
);
@@ -150,4 +151,29 @@ export class CustomerInquirySubmissionController {
});
return this.present(submission);
}
private visibilityRuleMatches(rule: unknown, values: Record<string, unknown>): boolean {
if (!rule || typeof rule !== "object") return true;
const item = rule as Record<string, unknown>;
if (typeof item.field !== "string") return true;
const value = values[item.field];
switch (item.operator) {
case "exists":
return Array.isArray(value) ? value.length > 0 : Boolean(value);
case "equals":
return value === item.value;
case "not-equals":
return value !== item.value;
case "in":
return Array.isArray(item.value) && typeof value === "string" && item.value.includes(value);
default:
return true;
}
}
private isVisibleField(field: Record<string, unknown>, values: Record<string, unknown>): boolean {
return (Array.isArray(field.visibleWhen) ? field.visibleWhen : []).every((rule) =>
this.visibilityRuleMatches(rule, values),
);
}
}
@@ -1,4 +1,11 @@
import { BadRequestException, Controller, Get, Param, Query } from "@nestjs/common";
import {
BadRequestException,
Controller,
Get,
NotFoundException,
Param,
Query,
} from "@nestjs/common";
import { PublicBrandContextService } from "./public-brand-context.service.js";
import { BrandReleaseService } from "../../brand-release.service.js";
@@ -34,7 +41,7 @@ export class PublicOfferingController {
const item = (snapshot?.offerings ?? [])
.map((raw) => this.object(raw))
.find((offering) => offering.id === id && offering.isEnabled === true);
if (!item) throw new BadRequestException("业务提供项不存在");
if (!item) throw new NotFoundException("业务提供项不存在");
const forms = (snapshot?.forms ?? []).filter((raw) => {
const form = this.object(raw);
return form.offeringId === id && form.isEnabled === true;
@@ -149,6 +149,35 @@ export function toRuntimeInquiryFields(snapshot: Prisma.JsonValue): RuntimeInqui
? [{ label: item.label, value: item.value }]
: [];
});
const visibleWhen = asArray(value.visibleWhen).flatMap((rule) => {
if (!rule || typeof rule !== "object") return [];
const item = rule as Record<string, unknown>;
if (typeof item.field !== "string") return [];
const operator: "equals" | "not-equals" | "exists" | "in" = item.operator as
"equals" | "not-equals" | "exists" | "in";
if (
operator !== "equals" &&
operator !== "not-equals" &&
operator !== "exists" &&
operator !== "in"
)
return [];
const ruleValue = item.value;
const normalizedValue =
typeof ruleValue === "string" ||
typeof ruleValue === "number" ||
typeof ruleValue === "boolean" ||
(Array.isArray(ruleValue) && ruleValue.every((entry) => typeof entry === "string"))
? ruleValue
: undefined;
return [
{
field: item.field,
operator,
...(normalizedValue === undefined ? {} : { value: normalizedValue }),
},
];
});
return [
{
key: value.key,
@@ -156,6 +185,7 @@ export function toRuntimeInquiryFields(snapshot: Prisma.JsonValue): RuntimeInqui
type,
required: value.required === true,
...(options.length ? { options } : {}),
...(visibleWhen.length ? { visibleWhen } : {}),
},
];
});
+36 -5
View File
@@ -164,6 +164,7 @@ test("miniapp release settings never expose or persist plaintext private keys",
const brand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } });
const credential = brand.miniAppSettings?.credential;
assert.ok(credential);
assert.equal(brand.miniAppSettings.apiBaseUrl, "https://wechat.example.com/api");
assert.equal(typeof credential.ciphertext, "string");
assert.ok(!JSON.stringify(brand.miniAppSettings).includes(privateKey));
const missing = await request("/admin/miniapp-releases/settings");
@@ -1552,6 +1553,11 @@ test("manually created member must change the initial password before normal use
});
assert.equal(login.statusCode, 201);
assert.equal(JSON.parse(login.body).mustChangePassword, true);
const blocked = await request("/admin/brands/members", {
headers: { authorization: `Bearer ${JSON.parse(login.body).token}` },
});
assert.equal(blocked.statusCode, 403);
assert.match(errorMessage(blocked.body), /初始密码/);
const changed = await request("/admin/session/change-password", {
method: "POST",
headers: { authorization: `Bearer ${JSON.parse(login.body).token}` },
@@ -2388,6 +2394,12 @@ test("admin can create and version an inquiry form", async () => {
{ label: "设计", value: "design" },
],
},
{
key: "wechat",
type: "text",
label: "微信号",
visibleWhen: [{ field: "contact_method", operator: "equals", value: "wechat" }],
},
],
},
});
@@ -2443,6 +2455,10 @@ test("admin can create and version an inquiry form", async () => {
const publicOffering = await request(`/public/offerings/${offering.id}`);
assert.equal(publicOffering.statusCode, 200);
assert.equal(JSON.parse(publicOffering.body).inquiryForms[0].id, id);
assert.equal(
(await request("/public/offerings/00000000-0000-0000-0000-000000000000")).statusCode,
404,
);
const publicWorkspace = await request("/public/workspace");
assert.equal(publicWorkspace.statusCode, 200);
const runtimeForm = JSON.parse(publicWorkspace.body).inquiryForms.find(
@@ -2456,6 +2472,9 @@ test("admin can create and version an inquiry form", async () => {
),
);
assert.deepEqual(runtimeForm.fields[1].options, [{ label: "微信", value: "wechat" }]);
assert.deepEqual(runtimeForm.fields[3].visibleWhen, [
{ field: "contact_method", operator: "equals", value: "wechat" },
]);
await prisma.inquiryForm.update({
where: { id },
data: {
@@ -2466,13 +2485,25 @@ test("admin can create and version an inquiry form", async () => {
const submission = await request("/customer/inquiry-submissions", {
method: "POST",
headers: { authorization: `Bearer ${customerToken}` },
payload: { formId: id, values: { budget: 1000, ignored: "not persisted" } },
payload: {
formId: id,
values: {
budget: 1000,
contact_method: "wechat",
ignored: "not persisted",
wechat: "brand-wechat",
},
},
});
assert.equal(submission.statusCode, 201);
assert.equal(JSON.parse(submission.body).formVersion, 2);
assert.equal(JSON.parse(submission.body).fieldsSnapshot[0].key, "budget");
assert.equal(JSON.parse(submission.body).offeringId, offering.id);
assert.deepEqual(JSON.parse(submission.body).values, { budget: 1000 });
assert.deepEqual(JSON.parse(submission.body).values, {
budget: 1000,
contact_method: "wechat",
wechat: "brand-wechat",
});
assert.equal((await request("/customer/inquiry-submissions")).statusCode, 401);
const adminCannotListCustomerSubmissions = await request("/customer/inquiry-submissions", {
headers: { authorization: `Bearer ${token}` },
@@ -2760,7 +2791,7 @@ test("admin can manage offerings and public endpoint hides disabled offerings",
assert.equal(previewOffering?.presentation?.categoryKey, "set-meal");
assert.equal(previewOffering?.presentation?.categoryLabel, "套餐");
const publicItem = await request(`/public/offerings/${id}`);
assert.equal(publicItem.statusCode, 400);
assert.equal(publicItem.statusCode, 404);
const publicList = await request("/public/offerings");
assert.equal(publicList.statusCode, 200);
assert.ok(!JSON.parse(publicList.body).some((item) => item.id === id));
@@ -2771,14 +2802,14 @@ test("admin can manage offerings and public endpoint hides disabled offerings",
});
assert.equal(updated.statusCode, 200);
const hidden = await request(`/public/offerings/${id}`);
assert.equal(hidden.statusCode, 400);
assert.equal(hidden.statusCode, 404);
const reenabled = await request(`/admin/workspace/offerings/${id}`, {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
payload: { isEnabled: true },
});
assert.equal(reenabled.statusCode, 200);
assert.equal((await request(`/public/offerings/${id}`)).statusCode, 400);
assert.equal((await request(`/public/offerings/${id}`)).statusCode, 404);
} finally {
const deleted = await request(`/admin/workspace/offerings/${id}`, {
method: "DELETE",
+1 -1
View File
@@ -39,7 +39,7 @@ test("local upload presign targets the API route and requires brand access", asy
{},
{ fileName: "portrait.jpg", contentType: "image/jpeg" },
);
assert.match(result.uploadUrl, /^\/api\/admin\/uploads\/local\?key=\d{4}%2F[a-f0-9]{16}\.jpg$/);
assert.match(result.uploadUrl, /^\/admin\/uploads\/local\?key=\d{4}%2F[a-f0-9]{16}\.jpg$/);
assert.equal(result.mode, "local");
} finally {
for (const [name, value] of [
+4
View File
@@ -46,6 +46,10 @@ async function main() {
initialReleases,
"Repeated seed must preserve release history and snapshots",
);
await fixtureDatabase.adminUser.updateMany({
where: { username: "admin" },
data: { mustChangePassword: false },
});
console.log("Seed idempotency verified: content, forms and release history preserved");
status = run(process.execPath, ["--test", "test/http.integration.test.js"]);
return status;
+1 -1
View File
@@ -1,7 +1,7 @@
#!/bin/sh
set -eu
case "${SEED_MODE:-seed}" in
case "${SEED_MODE:-skip}" in
seed)
node_modules/.bin/tsx prisma/seed.ts
;;
+1 -1
View File
@@ -79,7 +79,7 @@ export interface BrandMethods {
getAdminMiniAppSettings(): Promise<MiniAppReleaseSettings>;
updateAdminMiniAppSettings(body: {
appId?: string;
artifactPath?: string;
apiBaseUrl?: string;
privateKey?: string;
}): Promise<MiniAppReleaseSettings>;
}
+1
View File
@@ -8,4 +8,5 @@ export interface PresignedUpload {
uploadUrl: string;
key: string;
publicUrl: string;
mode?: "local";
}
+26
View File
@@ -69,3 +69,29 @@ test("发布检查与发布操作使用当前品牌的管理接口", async () =>
},
]);
});
test("小程序上传配置会提交请求地址", async () => {
const calls: Array<{ url: string; method?: string; body?: string }> = [];
const client = new ApiClient({
baseUrl: "http://api.test",
token: "brand-token",
fetcher: async (url, init) => {
calls.push({ url, method: init?.method, body: init?.body });
return response({ appId: "wx123", apiBaseUrl: "https://wechat.example.com/api" });
},
});
await client.updateAdminMiniAppSettings({
appId: "wx123",
apiBaseUrl: "https://wechat.example.com/api",
});
assert.deepEqual(calls, [
{
url: "http://api.test/admin/miniapp-releases/settings",
method: "PATCH",
body: JSON.stringify({
appId: "wx123",
apiBaseUrl: "https://wechat.example.com/api",
}),
},
]);
});
+39 -12
View File
@@ -21,6 +21,12 @@ const inquiryFieldOptionSchema = z.object({
value: z.string().min(1),
});
const visibilityRuleSchema = z.object({
field: z.string().regex(/^[a-z][a-zA-Z0-9_]*$/),
operator: z.enum(["equals", "not-equals", "exists", "in"]),
value: z.union([z.string(), z.number(), z.boolean(), z.array(z.string())]).optional(),
});
export const inquiryFieldSchema = z
.object({
// 字段 key 允许 snake_case 和 camelCase,模板字段通常使用 camelCase。
@@ -29,6 +35,7 @@ export const inquiryFieldSchema = z
label: z.string().min(1),
required: z.boolean().optional(),
options: z.array(inquiryFieldOptionSchema).optional(),
visibleWhen: z.array(visibilityRuleSchema).optional(),
})
.passthrough()
.superRefine((field, context) => {
@@ -41,19 +48,39 @@ export const inquiryFieldSchema = z
}
});
export const fieldSnapshotSchema = z.array(inquiryFieldSchema).superRefine((fields, context) => {
const seen = new Set<string>();
fields.forEach((field, index) => {
if (seen.has(field.key)) {
context.addIssue({
code: z.ZodIssueCode.custom,
path: [index, "key"],
message: "字段 key 不能重复",
});
}
seen.add(field.key);
const fieldVisibilityRulesRefinement = (
fields: Array<z.infer<typeof inquiryFieldSchema>>,
context: z.RefinementCtx,
) => {
fields.forEach((field, fieldIndex) => {
(field.visibleWhen ?? []).forEach((rule, ruleIndex) => {
if (!fields.some((target) => target.key === rule.field)) {
context.addIssue({
code: z.ZodIssueCode.custom,
path: [fieldIndex, "visibleWhen", ruleIndex, "field"],
message: "可见性规则引用的字段不存在",
});
}
});
});
});
};
export const fieldSnapshotSchema = z
.array(inquiryFieldSchema)
.superRefine((fields, context) => {
const seen = new Set<string>();
fields.forEach((field, index) => {
if (seen.has(field.key)) {
context.addIssue({
code: z.ZodIssueCode.custom,
path: [index, "key"],
message: "字段 key 不能重复",
});
}
seen.add(field.key);
});
})
.superRefine(fieldVisibilityRulesRefinement);
export const offeringConfigSchema = z
.object({