Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1e1d4d0326 | ||
|
|
92227e1311 |
No files matched your search
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"scope": "模板完成证据登记,保留命令、日志与产物哈希",
|
||||
"generatedAt": "2026-10-24T02:02:12.474Z",
|
||||
"generatedAt": "2026-10-23T11:27:49.824Z",
|
||||
"templates": {
|
||||
"acheng-campus-food": {
|
||||
"real-manifest-interaction": {
|
||||
@@ -256,5 +256,5 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"sourceTreeHash": "9d33ce8dbbddd34b91f045f49dc2316e36738ffec1429a93733d45d1b7b2a356"
|
||||
"sourceTreeHash": "1dbd5f3a24cc1f86925b4bcd05c99b45cc00d6a39dabe2302ad07ba7f763c79c"
|
||||
}
|
||||
+4
-3
@@ -19,18 +19,19 @@ OBJECT_STORAGE_PUBLIC_URL=http://localhost:9000/personal-brand-media
|
||||
OBJECT_STORAGE_BUCKET=personal-brand-media
|
||||
OBJECT_STORAGE_ACCESS_KEY=minioadmin
|
||||
OBJECT_STORAGE_SECRET_KEY=minioadmin
|
||||
# 微信 AppID 与 AppSecret 按品牌在后台「小程序配置」维护,不使用全局环境变量
|
||||
WECHAT_APP_ID=
|
||||
WECHAT_APP_SECRET=
|
||||
WECHAT_UPLOAD_PRIVATE_KEY=
|
||||
MINIAPP_CREDENTIAL_ENCRYPTION_KEY=replace-with-32-byte-random-secret
|
||||
# 小程序代码构建产物根目录,相对路径按仓库根目录解析;默认 apps/taro/dist
|
||||
# MINIAPP_ARTIFACT_ROOT=apps/taro/dist
|
||||
# 构建超过该毫秒数没有进度更新即视为中断,允许重新上传;默认 15 分钟
|
||||
# MINIAPP_BUILD_STALE_MS=900000
|
||||
# 小程序请求地址在后台「小程序配置」维护,这里仅为回落值;
|
||||
# 小程序请求地址在后台「小程序上传配置」维护,这里仅为回落值;
|
||||
# 未设置时由 PUBLIC_BASE_URL + MINIAPP_API_PATH 推导
|
||||
# MINIAPP_API_BASE_URL=https://wechat.app.que01.top/api
|
||||
# MINIAPP_API_PATH=/api
|
||||
# 单个品牌的 AppID 在后台“小程序配置”维护,这里只作为回落值
|
||||
# 单个品牌的 AppID 在后台“小程序上传配置”维护,这里只作为回落值
|
||||
# WEAPP_APP_ID=
|
||||
# 上传子进程工作目录;miniprogram-ci 的编译缓存放这里,默认系统临时目录
|
||||
# MINIAPP_UPLOAD_WORKSPACE=/tmp/personal-brand-miniapp-upload
|
||||
@@ -6,9 +6,6 @@ POSTGRES_PORT=5432
|
||||
|
||||
DATABASE_URL=postgresql://personal_brand:replace-with-a-long-database-password@127.0.0.1:5432/personal_brand?schema=public
|
||||
SESSION_SECRET=replace-with-at-least-32-random-characters
|
||||
# 建议单独配置并长期保持不变;未设置时回退 SESSION_SECRET。
|
||||
# 轮换该密钥后,已保存的上传私钥和 AppSecret 都需要在后台重新填写。
|
||||
# MINIAPP_CREDENTIAL_ENCRYPTION_KEY=replace-with-32-byte-random-secret
|
||||
# 单实例使用 memory;多实例部署改用 postgres 并先执行数据库迁移
|
||||
CLIENT_ERROR_THROTTLE_STORE=memory
|
||||
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
|
||||
@@ -34,9 +31,12 @@ OBJECT_STORAGE_ACCESS_KEY=
|
||||
OBJECT_STORAGE_SECRET_KEY=
|
||||
OBJECT_STORAGE_REGION=us-east-1
|
||||
|
||||
# 微信 AppID 与 AppSecret 按品牌在后台「小程序配置」维护,不使用全局环境变量
|
||||
# 访客微信登录配置,与后台「小程序上传配置」相互独立:
|
||||
# AppID 必须与上传配置一致;AppSecret 只放在服务器环境变量中
|
||||
WECHAT_APP_ID=
|
||||
WECHAT_APP_SECRET=
|
||||
|
||||
# 小程序请求地址正常情况下在后台「小程序配置」维护;
|
||||
# 小程序请求地址正常情况下在后台「小程序上传配置」维护;
|
||||
# 这里仅作为后台未配置时的回落值(否则由 PUBLIC_BASE_URL + /api 推导)
|
||||
# MINIAPP_API_BASE_URL=https://wechat.app.que01.top/api
|
||||
# MINIAPP_BUILD_STALE_MS=900000
|
||||
@@ -20,7 +20,7 @@ export function RecordContentFields({
|
||||
return (
|
||||
<Row gutter={16}>
|
||||
{section.fields.map((field) => (
|
||||
<Col key={field.key} xs={24} md={24} data-presentation-binding={field.binding}>
|
||||
<Col key={field.key} xs={24} md={24}>
|
||||
{field.input === "list" ? (
|
||||
<TemplateListField field={field} name={presentationFieldName(sectionKey, field.key)} />
|
||||
) : (
|
||||
|
||||
@@ -9,7 +9,6 @@ export type MiniAppSettingsValues = {
|
||||
appId: string;
|
||||
apiBaseUrl: string;
|
||||
privateKey?: string;
|
||||
appSecret?: string;
|
||||
};
|
||||
|
||||
interface MiniAppSettingsTabProps {
|
||||
@@ -28,15 +27,14 @@ export function MiniAppSettingsTab({ settings, saving, error, onSave }: MiniAppS
|
||||
appId: settings.appId,
|
||||
apiBaseUrl: settings.apiBaseUrl,
|
||||
privateKey: "",
|
||||
appSecret: "",
|
||||
});
|
||||
}, [form, settings]);
|
||||
|
||||
return (
|
||||
<div className="admin-stack admin-stack-lg">
|
||||
<AdminSection
|
||||
title="小程序配置"
|
||||
description="AppID 同时用于代码上传和小程序登录;AppSecret 只用于 wx.login 换取 OpenID;上传私钥和 AppSecret 均使用 AES-256-GCM 加密保存。"
|
||||
title="小程序上传配置"
|
||||
description="AppID 用于服务端调用微信官方上传工具;上传私钥保存前会使用 AES-256-GCM 加密。"
|
||||
>
|
||||
{settings?.buildError ? (
|
||||
<Alert
|
||||
@@ -61,32 +59,7 @@ export function MiniAppSettingsTab({ settings, saving, error, onSave }: MiniAppS
|
||||
label="微信 AppID"
|
||||
rules={[{ required: true, message: "请输入微信 AppID" }]}
|
||||
>
|
||||
<Input maxLength={100} autoComplete="off" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="appSecret"
|
||||
label="微信登录 AppSecret"
|
||||
help={
|
||||
settings?.hasStoredAppSecret
|
||||
? "已加密保存。留空保持现有 AppSecret;修改 AppID 时必须同时填写新 AppID 对应的 AppSecret。"
|
||||
: "从微信公众平台“开发管理 → 开发设置”复制。保存后立即生效,不需要重新上传小程序代码。"
|
||||
}
|
||||
rules={[
|
||||
{
|
||||
validator: (_rule, value: string) =>
|
||||
!value || /^[A-Za-z0-9]{16,64}$/.test(value.trim())
|
||||
? Promise.resolve()
|
||||
: Promise.reject(new Error("AppSecret 应为 16-64 位字母或数字,请复制完整值")),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Input.Password
|
||||
maxLength={64}
|
||||
autoComplete="new-password"
|
||||
placeholder={
|
||||
settings?.hasStoredAppSecret ? "留空保持现有 AppSecret" : "填写该小程序的 AppSecret"
|
||||
}
|
||||
/>
|
||||
<Input maxLength={100} />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="apiBaseUrl"
|
||||
@@ -125,29 +98,15 @@ export function MiniAppSettingsTab({ settings, saving, error, onSave }: MiniAppS
|
||||
className="admin-code-input"
|
||||
/>
|
||||
</Form.Item>
|
||||
{!settings?.loginConfigured ? (
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
className="admin-offset-bottom"
|
||||
title="微信登录尚不可用"
|
||||
description="该品牌需要同时保存微信 AppID 和 AppSecret,体验版才能通过 wx.login 换取 OpenID。"
|
||||
/>
|
||||
) : null}
|
||||
<Space wrap>
|
||||
<Space>
|
||||
<Button type="primary" loading={saving} htmlType="submit">
|
||||
保存小程序配置
|
||||
保存上传配置
|
||||
</Button>
|
||||
{settings?.hasStoredCredentials ? (
|
||||
<StatusTag tone="success" label="已加密保存上传凭据" />
|
||||
) : (
|
||||
<StatusTag tone="warning" label="未配置上传私钥" />
|
||||
)}
|
||||
{settings?.hasStoredAppSecret ? (
|
||||
<StatusTag tone="success" label="已加密保存登录凭据" />
|
||||
) : (
|
||||
<StatusTag tone="warning" label="未配置登录 AppSecret" />
|
||||
)}
|
||||
</Space>
|
||||
<MutationError error={error} />
|
||||
</Form>
|
||||
|
||||
@@ -56,20 +56,14 @@ export function usePublicationMutations({
|
||||
},
|
||||
});
|
||||
const saveMiniAppSettings = useMutation({
|
||||
mutationFn: (values: {
|
||||
appId: string;
|
||||
apiBaseUrl: string;
|
||||
privateKey?: string;
|
||||
appSecret?: string;
|
||||
}) =>
|
||||
mutationFn: (values: { appId: string; apiBaseUrl: string; privateKey?: string }) =>
|
||||
client.updateAdminMiniAppSettings({
|
||||
appId: values.appId,
|
||||
apiBaseUrl: values.apiBaseUrl,
|
||||
...(values.privateKey ? { privateKey: values.privateKey } : {}),
|
||||
...(values.appSecret ? { appSecret: values.appSecret } : {}),
|
||||
}),
|
||||
onSuccess: () => {
|
||||
message.success("小程序配置已保存");
|
||||
message.success("小程序上传配置已保存");
|
||||
void queryClient.invalidateQueries({ queryKey: ["publication-miniapp-settings"] });
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Alert, Button, Form, Input, Modal, Segmented, Select } from "antd";
|
||||
import { useEffect, useRef } from "react";
|
||||
import type {
|
||||
Offering,
|
||||
RuntimeWorkspace,
|
||||
@@ -9,7 +8,7 @@ import type {
|
||||
import { ImageUrlField } from "../../components/ImageUrlField.js";
|
||||
import { RecordContentFields } from "../../components/RecordContentEditor.js";
|
||||
import { ComponentTemplatePreview } from "../brand/ComponentTemplatePreview.js";
|
||||
import type { PreviewSelection, PreviewTarget } from "../brand/preview-selection.js";
|
||||
import type { PreviewTarget } from "../brand/preview-selection.js";
|
||||
import type { FormInstance } from "antd";
|
||||
import "./ServicesPage.css";
|
||||
|
||||
@@ -21,8 +20,6 @@ type OfferingEditorModalProps = {
|
||||
previewWorkspace: RuntimeWorkspace | undefined;
|
||||
previewTargets: Record<"offerings" | "detail", PreviewTarget[]>;
|
||||
activeTemplateFields: TemplateAdminField[];
|
||||
activePreviewBindings: string[];
|
||||
selectedTarget: PreviewTarget | undefined;
|
||||
templateFieldSection: TemplateAdminSection;
|
||||
hasTemplateDetailCopy: boolean;
|
||||
listTarget: PreviewTarget;
|
||||
@@ -30,7 +27,6 @@ type OfferingEditorModalProps = {
|
||||
saving: boolean;
|
||||
onClose: () => void;
|
||||
onPreviewPageChange: (page: "offerings" | "detail") => void;
|
||||
onPreviewTargetSelected: (selection?: PreviewSelection) => void;
|
||||
onValuesChange: (values: Record<string, unknown>) => void;
|
||||
onFinish: (values: Record<string, unknown>) => void;
|
||||
onEditInBrand: () => void;
|
||||
@@ -44,8 +40,6 @@ export function OfferingEditorModal({
|
||||
previewWorkspace,
|
||||
previewTargets,
|
||||
activeTemplateFields,
|
||||
activePreviewBindings,
|
||||
selectedTarget,
|
||||
templateFieldSection,
|
||||
hasTemplateDetailCopy,
|
||||
listTarget,
|
||||
@@ -53,33 +47,10 @@ export function OfferingEditorModal({
|
||||
saving,
|
||||
onClose,
|
||||
onPreviewPageChange,
|
||||
onPreviewTargetSelected,
|
||||
onValuesChange,
|
||||
onFinish,
|
||||
onEditInBrand,
|
||||
}: OfferingEditorModalProps) {
|
||||
const formScroll = useRef<HTMLDivElement>(null);
|
||||
const defaultPreviewTarget = previewPage === "offerings" ? listTarget : detailTarget;
|
||||
const previewSelectionTarget = selectedTarget ?? defaultPreviewTarget;
|
||||
const previewSelection: PreviewSelection | undefined = previewSelectionTarget
|
||||
? previewSelectionTarget.source === "offering" && editingOffering
|
||||
? { targetKey: previewSelectionTarget.key, recordId: editingOffering.id }
|
||||
: { targetKey: previewSelectionTarget.key }
|
||||
: undefined;
|
||||
|
||||
// 点选区块后,在右侧滚动到并高亮对应的输入项;品牌通用区块没有对应输入项时只保留提示。
|
||||
useEffect(() => {
|
||||
const host = formScroll.current;
|
||||
if (!host || !selectedTarget || activePreviewBindings.length === 0) return;
|
||||
const bindings = new Set(activePreviewBindings);
|
||||
const nodes = Array.from(
|
||||
host.querySelectorAll<HTMLElement>("[data-presentation-binding]"),
|
||||
).filter((node) => bindings.has(node.dataset.presentationBinding ?? ""));
|
||||
nodes.forEach((node) => node.classList.add("is-preview-active"));
|
||||
nodes[0]?.scrollIntoView({ block: "center", behavior: "smooth" });
|
||||
return () => nodes.forEach((node) => node.classList.remove("is-preview-active"));
|
||||
}, [selectedTarget, activePreviewBindings]);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
@@ -116,8 +87,11 @@ export function OfferingEditorModal({
|
||||
page={previewPage}
|
||||
offeringId={editingOffering.id}
|
||||
targets={previewTargets[previewPage]}
|
||||
{...(previewSelection ? { selection: previewSelection } : {})}
|
||||
onTargetSelected={onPreviewTargetSelected}
|
||||
selection={{
|
||||
targetKey: previewPage === "offerings" ? listTarget.key : (detailTarget?.key ?? ""),
|
||||
recordId: editingOffering.id,
|
||||
}}
|
||||
onTargetSelected={() => {}}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
@@ -128,7 +102,7 @@ export function OfferingEditorModal({
|
||||
onValuesChange={(_, allValues) => onValuesChange(allValues)}
|
||||
onFinish={onFinish}
|
||||
>
|
||||
<div ref={formScroll} className="service-offering-editor__form-scroll">
|
||||
<div className="service-offering-editor__form-scroll">
|
||||
<h4 className="admin-subhead">基础信息</h4>
|
||||
<Form.Item name="kind" label="类型" rules={[{ required: true }]}>
|
||||
<Select
|
||||
@@ -140,42 +114,24 @@ export function OfferingEditorModal({
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="name"
|
||||
label="名称"
|
||||
data-presentation-binding="offering.name"
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
<Form.Item name="name" label="名称" rules={[{ required: true }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="summary"
|
||||
label="一句话说明"
|
||||
data-presentation-binding="offering.summary"
|
||||
>
|
||||
<Form.Item name="summary" label="一句话说明">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
{!hasTemplateDetailCopy ? (
|
||||
<Form.Item
|
||||
name="description"
|
||||
label="详细介绍"
|
||||
data-presentation-binding="offering.description"
|
||||
>
|
||||
<Form.Item name="description" label="详细介绍">
|
||||
<Input.TextArea rows={5} />
|
||||
</Form.Item>
|
||||
) : null}
|
||||
<Form.Item
|
||||
name="priceText"
|
||||
label="价格展示"
|
||||
data-presentation-binding="offering.priceText"
|
||||
>
|
||||
<Form.Item name="priceText" label="价格展示">
|
||||
<Input placeholder="例如:按现场评估报价 / ¥ 2,800 起" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="coverUrl"
|
||||
label="封面图片地址"
|
||||
help="点击上传,或粘贴服务/产品封面图片地址。"
|
||||
data-presentation-binding="offering.coverUrl"
|
||||
>
|
||||
<ImageUrlField placeholder="粘贴服务或产品封面图片地址" scope="offering" />
|
||||
</Form.Item>
|
||||
@@ -195,28 +151,13 @@ export function OfferingEditorModal({
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
{selectedTarget && selectedTarget.source !== "offering" ? (
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
className="admin-offset-bottom"
|
||||
title={`「${selectedTarget.label}」属于页面通用内容`}
|
||||
description="这项内容不在业务提供项里维护。可点击下方「在小程序页面编辑」到对应区块修改。"
|
||||
/>
|
||||
) : null}
|
||||
{activeTemplateFields.length ? (
|
||||
<div>
|
||||
<h4 className="admin-subhead">
|
||||
{selectedTarget
|
||||
? `${selectedTarget.label}对应字段`
|
||||
: previewPage === "offerings"
|
||||
? "列表展示字段"
|
||||
: "详情展示字段"}
|
||||
{previewPage === "offerings" ? "列表展示字段" : "详情展示字段"}
|
||||
</h4>
|
||||
<p className="admin-section-description admin-offset-bottom">
|
||||
{selectedTarget
|
||||
? "右侧已定位到该区块使用的字段,修改会实时反映在左侧预览。"
|
||||
: "这里只编辑左侧预览对应的字段;它们与小程序页面编辑的是同一份业务数据。"}
|
||||
这里只编辑左侧预览对应的字段;它们与小程序页面编辑的是同一份业务数据。
|
||||
</p>
|
||||
<RecordContentFields
|
||||
section={{
|
||||
@@ -226,14 +167,6 @@ export function OfferingEditorModal({
|
||||
sectionKey="offering"
|
||||
/>
|
||||
</div>
|
||||
) : selectedTarget?.source === "offering" ? (
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
className="admin-offset-bottom"
|
||||
title={`「${selectedTarget.label}」只包含基础信息`}
|
||||
description="请修改上方基础信息,左侧预览会实时同步。"
|
||||
/>
|
||||
) : null}
|
||||
{editingOffering ? (
|
||||
<Button htmlType="button" onClick={onEditInBrand}>
|
||||
|
||||
@@ -59,19 +59,6 @@
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.service-offering-editor__form-scroll [data-presentation-binding] {
|
||||
scroll-margin-block: 24px;
|
||||
border-radius: 8px;
|
||||
transition:
|
||||
background-color 180ms ease,
|
||||
box-shadow 180ms ease;
|
||||
}
|
||||
|
||||
.service-offering-editor__form-scroll [data-presentation-binding].is-preview-active {
|
||||
background-color: rgba(22, 119, 255, 0.07);
|
||||
box-shadow: 0 0 0 2px rgba(22, 119, 255, 0.24);
|
||||
}
|
||||
|
||||
.service-offering-editor__form-scroll .ant-typography h5.ant-typography {
|
||||
margin: 28px 0 4px;
|
||||
padding-bottom: 8px;
|
||||
|
||||
@@ -7,14 +7,9 @@ import { QueryState } from "../../components/QueryState.js";
|
||||
import { OfferingEditorModal } from "./OfferingEditorModal.js";
|
||||
import { OfferingsTable } from "./OfferingsTable.js";
|
||||
import { detailPageLabel, hasTemplateDetailCopy, offeringPageLabel } from "./offering-model.js";
|
||||
import {
|
||||
buildOfferingPreviewWorkspace,
|
||||
previewFieldsByTarget,
|
||||
previewTargetsByPage,
|
||||
} from "./offering-preview.js";
|
||||
import { buildOfferingPreviewWorkspace, previewTargetsByPage } from "./offering-preview.js";
|
||||
import { useOfferingEditor } from "./use-offering-editor.js";
|
||||
import { useOfferingMutations, useOfferingQueries } from "./use-offering-data.js";
|
||||
import type { PreviewSelection } from "../brand/preview-selection.js";
|
||||
|
||||
type PreviewPage = "offerings" | "detail";
|
||||
|
||||
@@ -33,23 +28,15 @@ export function ServicesPage() {
|
||||
|
||||
const sections = workspace.data?.templateContent?.admin.sections ?? [];
|
||||
const previewTargets = useMemo(() => previewTargetsByPage(sections), [sections]);
|
||||
const fieldsByTarget = useMemo(() => previewFieldsByTarget(sections), [sections]);
|
||||
const listTarget = useMemo(
|
||||
() =>
|
||||
previewTargets.offerings.find((target) =>
|
||||
templateFields.some((field) => field.previewTarget === target.key),
|
||||
) ?? {
|
||||
key: "offering.list.item",
|
||||
label: "业务卡片",
|
||||
page: "offerings",
|
||||
source: "offering" as const,
|
||||
},
|
||||
[previewTargets, templateFields],
|
||||
);
|
||||
const detailTarget = useMemo(
|
||||
() => previewTargets.detail.find((target) => target.source === "offering"),
|
||||
[previewTargets],
|
||||
);
|
||||
const listTarget = previewTargets.offerings.find((target) =>
|
||||
templateFields.some((field) => field.previewTarget === target.key),
|
||||
) ?? {
|
||||
key: "offering.list.item",
|
||||
label: "业务卡片",
|
||||
page: "offerings",
|
||||
source: "offering",
|
||||
};
|
||||
const detailTarget = previewTargets.detail.find((target) => target.source === "offering");
|
||||
const listFields = useMemo(
|
||||
() => templateFields.filter((field) => field.previewTarget === listTarget.key),
|
||||
[templateFields, listTarget.key],
|
||||
@@ -65,37 +52,10 @@ export function ServicesPage() {
|
||||
),
|
||||
[templateFields, listFields, detailFields],
|
||||
);
|
||||
const pageTemplateFields = useMemo<TemplateAdminField[]>(
|
||||
() =>
|
||||
editor.previewPage === "offerings"
|
||||
? [...listFields, ...otherFields.filter((field) => field.page === "offerings")]
|
||||
: [...detailFields, ...otherFields.filter((field) => field.page === "detail")],
|
||||
[editor.previewPage, listFields, detailFields, otherFields],
|
||||
);
|
||||
// 点选预览区块后,右侧只保留该区块对应的字段,与小程序页面点选编辑保持一致。
|
||||
const selectedTarget = useMemo(() => {
|
||||
if (!editor.previewTargetKey) return undefined;
|
||||
return (
|
||||
previewTargets[editor.previewPage].find((target) => target.key === editor.previewTargetKey) ??
|
||||
(editor.previewTargetKey === listTarget.key ? listTarget : undefined) ??
|
||||
(editor.previewTargetKey === detailTarget?.key ? detailTarget : undefined)
|
||||
);
|
||||
}, [editor.previewPage, editor.previewTargetKey, previewTargets, listTarget, detailTarget]);
|
||||
const activeTemplateFields = useMemo<TemplateAdminField[]>(
|
||||
() =>
|
||||
selectedTarget
|
||||
? pageTemplateFields.filter((field) => field.previewTarget === selectedTarget.key)
|
||||
: pageTemplateFields,
|
||||
[pageTemplateFields, selectedTarget],
|
||||
);
|
||||
// 区块字段的 binding 用于在右侧表单中滚动并高亮同一份数据。
|
||||
const activePreviewBindings = useMemo(
|
||||
() =>
|
||||
selectedTarget
|
||||
? (fieldsByTarget[selectedTarget.key] ?? []).map((field) => field.binding)
|
||||
: [],
|
||||
[fieldsByTarget, selectedTarget],
|
||||
);
|
||||
const activeTemplateFields: TemplateAdminField[] =
|
||||
editor.previewPage === "offerings"
|
||||
? [...listFields, ...otherFields.filter((field) => field.page === "offerings")]
|
||||
: [...detailFields, ...otherFields.filter((field) => field.page === "detail")];
|
||||
const previewWorkspaceDraft = useMemo(() => {
|
||||
if (!previewWorkspace.data || !editor.editingOffering) return undefined;
|
||||
return buildOfferingPreviewWorkspace({
|
||||
@@ -117,10 +77,9 @@ export function ServicesPage() {
|
||||
void navigate("/admin/brand", {
|
||||
state: {
|
||||
targetKey:
|
||||
editor.previewTargetKey ??
|
||||
(editor.previewPage === "offerings"
|
||||
editor.previewPage === "offerings"
|
||||
? listTarget.key
|
||||
: (detailTarget?.key ?? listTarget.key)),
|
||||
: (detailTarget?.key ?? listTarget.key),
|
||||
recordId: editor.editingOffering.id,
|
||||
},
|
||||
});
|
||||
@@ -161,18 +120,13 @@ export function ServicesPage() {
|
||||
previewWorkspace={previewWorkspaceDraft}
|
||||
previewTargets={previewTargets}
|
||||
activeTemplateFields={activeTemplateFields}
|
||||
activePreviewBindings={activePreviewBindings}
|
||||
selectedTarget={selectedTarget}
|
||||
templateFieldSection={editor.templateFieldSection}
|
||||
hasTemplateDetailCopy={hasTemplateDetailCopy(templateFields)}
|
||||
listTarget={listTarget}
|
||||
detailTarget={detailTarget}
|
||||
saving={mutations.saveOffering.isPending}
|
||||
onClose={editor.closeOffering}
|
||||
onPreviewPageChange={(page: PreviewPage) => editor.changePreviewPage(page)}
|
||||
onPreviewTargetSelected={(selection?: PreviewSelection) =>
|
||||
editor.selectPreviewTarget(selection?.targetKey)
|
||||
}
|
||||
onPreviewPageChange={(page: PreviewPage) => editor.setPreviewPage(page)}
|
||||
onValuesChange={(values) => editor.handleValuesChange(null, values)}
|
||||
onFinish={(values) => mutations.saveOffering.mutate(values)}
|
||||
onEditInBrand={navigateToBrand}
|
||||
|
||||
@@ -32,19 +32,6 @@ export function previewTargetsByPage(
|
||||
return result;
|
||||
}
|
||||
|
||||
export function previewFieldsByTarget(
|
||||
sections: AdminTemplateContent["admin"]["sections"],
|
||||
): Record<string, TemplateAdminField[]> {
|
||||
const result: Record<string, TemplateAdminField[]> = {};
|
||||
for (const section of sections) {
|
||||
for (const field of section.fields) {
|
||||
if (!field.previewTarget) continue;
|
||||
(result[field.previewTarget] ??= []).push(field);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function buildOfferingPreviewWorkspace(options: {
|
||||
previewWorkspace: RuntimeWorkspace;
|
||||
editingOffering: Offering;
|
||||
|
||||
@@ -15,7 +15,6 @@ export function useOfferingEditor(templateFields: TemplateAdminField[]) {
|
||||
const [editingOffering, setEditingOffering] = useState<Offering | null>(null);
|
||||
const [offeringDraftVersion, setOfferingDraftVersion] = useState(0);
|
||||
const [previewPage, setPreviewPage] = useState<OfferingPreviewPage>("detail");
|
||||
const [previewTargetKey, setPreviewTargetKey] = useState<string>();
|
||||
const [formValues, setFormValues] = useState<Record<string, unknown>>({});
|
||||
|
||||
const templateFieldSection = useMemo<TemplateAdminSection>(
|
||||
@@ -33,7 +32,6 @@ export function useOfferingEditor(templateFields: TemplateAdminField[]) {
|
||||
const beginOffering = (item?: Offering) => {
|
||||
setEditingOffering(item ?? null);
|
||||
setPreviewPage("detail");
|
||||
setPreviewTargetKey(undefined);
|
||||
setOfferingOpen(true);
|
||||
offeringForm.setFieldsValue(
|
||||
item
|
||||
@@ -46,19 +44,9 @@ export function useOfferingEditor(templateFields: TemplateAdminField[]) {
|
||||
const closeOffering = () => {
|
||||
setOfferingOpen(false);
|
||||
setEditingOffering(null);
|
||||
setPreviewTargetKey(undefined);
|
||||
offeringForm.resetFields();
|
||||
};
|
||||
|
||||
// 预览与右侧表单共用同一份选中状态:点选区块即定位到对应字段。
|
||||
const selectPreviewTarget = (targetKey?: string) => setPreviewTargetKey(targetKey);
|
||||
|
||||
// 列表与详情是两张不同的页面,切换时清空区块选中,避免沿用另一页的 key。
|
||||
const changePreviewPage = (page: OfferingPreviewPage) => {
|
||||
setPreviewPage(page);
|
||||
setPreviewTargetKey(undefined);
|
||||
};
|
||||
|
||||
const handleValuesChange = (_: unknown, allValues: Record<string, unknown>) => {
|
||||
setFormValues(allValues);
|
||||
setOfferingDraftVersion((version) => version + 1);
|
||||
@@ -72,9 +60,7 @@ export function useOfferingEditor(templateFields: TemplateAdminField[]) {
|
||||
templateFieldSection,
|
||||
formValues,
|
||||
offeringDraftVersion,
|
||||
previewTargetKey,
|
||||
changePreviewPage,
|
||||
selectPreviewTarget,
|
||||
setPreviewPage,
|
||||
beginOffering,
|
||||
closeOffering,
|
||||
handleValuesChange,
|
||||
|
||||
@@ -18,9 +18,4 @@ export class UpdateMiniAppSettingsDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
privateKey?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(128)
|
||||
appSecret?: string;
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { Prisma } from "@prisma/client";
|
||||
import { AdminMiniAppReleaseService } from "./admin-miniapp-release.service.js";
|
||||
import { miniappArtifactRoot } from "./miniapp-artifact.js";
|
||||
import { miniappApiBaseUrl, validateApiBaseUrl, weappAppId } from "./miniapp-build-config.js";
|
||||
import { encryptMiniAppCredential } from "../../miniapp-credential-crypto.js";
|
||||
import { encryptMiniAppCredential } from "./miniapp-credential-crypto.js";
|
||||
import { inspectPrivateKey, normalizePrivateKey } from "./miniapp-private-key.js";
|
||||
import type { UpdateMiniAppSettingsDto } from "./admin-miniapp-settings.dto.js";
|
||||
|
||||
@@ -18,17 +18,10 @@ export class AdminMiniAppSettingsService {
|
||||
|
||||
async update(brandId: string, body: UpdateMiniAppSettingsDto & { privateKey?: string }) {
|
||||
if (body.privateKey !== undefined) this.validatePrivateKey(body.privateKey);
|
||||
if (body.appSecret !== undefined) this.validateAppSecret(body.appSecret);
|
||||
const current = this.jsonObject(await this.releases.settings(brandId));
|
||||
const currentAppId = typeof current.appId === "string" ? current.appId : "";
|
||||
const nextAppId = body.appId === undefined ? currentAppId : body.appId.trim();
|
||||
if (currentAppId && nextAppId !== currentAppId && body.appSecret === undefined)
|
||||
throw new BadRequestException(
|
||||
"修改微信 AppID 时必须同时填写该 AppID 对应的 AppSecret,避免登录凭据与小程序不匹配",
|
||||
);
|
||||
const settings = {
|
||||
...current,
|
||||
appId: nextAppId,
|
||||
appId: body.appId ?? current.appId ?? "",
|
||||
apiBaseUrl:
|
||||
body.apiBaseUrl === undefined ? (current.apiBaseUrl ?? "") : this.apiBaseUrl(body),
|
||||
build: {
|
||||
@@ -38,9 +31,6 @@ export class AdminMiniAppSettingsService {
|
||||
...(body.privateKey === undefined
|
||||
? {}
|
||||
: { credential: encryptMiniAppCredential(normalizePrivateKey(body.privateKey)) }),
|
||||
...(body.appSecret === undefined
|
||||
? {}
|
||||
: { appSecretCredential: encryptMiniAppCredential(body.appSecret.trim()) }),
|
||||
templateKey: current.templateKey ?? null,
|
||||
} satisfies Prisma.InputJsonObject;
|
||||
await this.releases.saveSettings(brandId, settings);
|
||||
@@ -57,14 +47,6 @@ export class AdminMiniAppSettingsService {
|
||||
);
|
||||
}
|
||||
|
||||
private validateAppSecret(appSecret: string) {
|
||||
const trimmed = appSecret.trim();
|
||||
if (!/^[A-Za-z0-9]{16,64}$/.test(trimmed))
|
||||
throw new BadRequestException(
|
||||
"微信登录 AppSecret 格式无效:应为 16-64 位字母或数字,请从微信公众平台复制完整值",
|
||||
);
|
||||
}
|
||||
|
||||
private apiBaseUrl(body: UpdateMiniAppSettingsDto) {
|
||||
const trimmed = body.apiBaseUrl?.trim();
|
||||
if (!trimmed) throw new BadRequestException("小程序请求地址不能为空");
|
||||
@@ -76,21 +58,16 @@ export class AdminMiniAppSettingsService {
|
||||
}
|
||||
|
||||
private present(settings: Record<string, unknown>) {
|
||||
const { credential, appSecretCredential, ...rest } = settings;
|
||||
delete rest.appSecret;
|
||||
const appId = typeof rest.appId === "string" ? rest.appId : "";
|
||||
return {
|
||||
appId: "",
|
||||
artifactPath: miniappArtifactRoot(),
|
||||
build: {},
|
||||
...rest,
|
||||
apiBaseUrl: this.effectiveApiBaseUrl(rest.apiBaseUrl),
|
||||
...settings,
|
||||
apiBaseUrl: this.effectiveApiBaseUrl(settings.apiBaseUrl),
|
||||
privateKey: undefined,
|
||||
credential: credential ? { algorithm: "aes-256-gcm" } : null,
|
||||
hasStoredCredentials: Boolean(credential),
|
||||
hasStoredAppSecret: Boolean(appSecretCredential),
|
||||
loginConfigured: Boolean(appId && appSecretCredential),
|
||||
...this.buildConfigSummary(rest.apiBaseUrl, rest.appId),
|
||||
credential: settings.credential ? { algorithm: "aes-256-gcm" } : null,
|
||||
hasStoredCredentials: Boolean(settings.credential),
|
||||
...this.buildConfigSummary(settings.apiBaseUrl, settings.appId),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
import { miniappReleaseProjectPath, miniappTaroOutputRoot } from "./miniapp-artifact.js";
|
||||
import { miniappApiBaseUrl, weappAppId } from "./miniapp-build-config.js";
|
||||
import { buildingStaleMs, isStaleBuilding } from "./miniapp-build-status.js";
|
||||
import { decryptMiniAppCredential } from "../../miniapp-credential-crypto.js";
|
||||
import { decryptMiniAppCredential } from "./miniapp-credential-crypto.js";
|
||||
import { inspectPrivateKey, normalizePrivateKey } from "./miniapp-private-key.js";
|
||||
import { runMiniAppUpload } from "./miniapp-upload.js";
|
||||
|
||||
@@ -68,7 +68,7 @@ export class AdminMiniAppUploadService {
|
||||
const keyInspection = inspectPrivateKey(normalizedPrivateKey);
|
||||
if (!keyInspection.valid)
|
||||
throw new BadRequestException(
|
||||
`上传私钥无法解析(${keyInspection.reason ?? "PEM 格式错误"})。请在“小程序配置”里重新粘贴完整私钥。`,
|
||||
`上传私钥无法解析(${keyInspection.reason ?? "PEM 格式错误"})。请在“小程序上传配置”里重新粘贴完整私钥。`,
|
||||
);
|
||||
|
||||
const templateManifest = miniAppTemplateManifest(brand.templateKey);
|
||||
|
||||
@@ -26,7 +26,7 @@ export function miniappApiBaseUrl(
|
||||
normalizeBaseUrl(`${normalizeBaseUrl(publicBase)}${env.MINIAPP_API_PATH ?? "/api"}`),
|
||||
);
|
||||
throw new Error(
|
||||
"未配置小程序请求地址:请在“配置与发布 → 小程序配置”里填写“小程序请求地址”,例如 https://wechat.app.que01.top/api",
|
||||
"未配置小程序请求地址:请在“配置与发布 → 小程序上传配置”里填写“小程序请求地址”,例如 https://wechat.app.que01.top/api",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -53,6 +53,6 @@ export function weappAppId(storedAppId: unknown, env: NodeJS.ProcessEnv = proces
|
||||
? storedAppId.trim()
|
||||
: (env.WEAPP_APP_ID?.trim() ?? "");
|
||||
if (!candidate || candidate === "undefined" || candidate === "touristappid")
|
||||
throw new Error("未配置微信 AppID:请在“小程序配置”里填写或设置 WEAPP_APP_ID");
|
||||
throw new Error("未配置微信 AppID:请在“小程序上传配置”里填写或设置 WEAPP_APP_ID");
|
||||
return candidate;
|
||||
}
|
||||
+1
-1
@@ -38,7 +38,7 @@ export function decryptMiniAppCredential(value: unknown): string {
|
||||
typeof payload.iv !== "string" ||
|
||||
typeof payload.authTag !== "string"
|
||||
)
|
||||
throw new UnauthorizedException("小程序凭据不可用");
|
||||
throw new UnauthorizedException("小程序上传凭据不可用");
|
||||
const decipher = createDecipheriv(ALGORITHM, encryptionKey(), Buffer.from(payload.iv, "base64"));
|
||||
decipher.setAuthTag(Buffer.from(payload.authTag, "base64"));
|
||||
return Buffer.concat([
|
||||
@@ -1,11 +1,7 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { signIdentity } from "../../auth.js";
|
||||
import {
|
||||
WechatAuthService,
|
||||
resolveWechatLoginCredentials,
|
||||
type WechatSession,
|
||||
} from "../../wechat-auth.js";
|
||||
import type { WechatSession } from "../../wechat-auth.js";
|
||||
import { PublicBrandContextService } from "../public/public-brand-context.service.js";
|
||||
|
||||
@Injectable()
|
||||
@@ -13,18 +9,15 @@ export class CustomerSessionService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly brandContext: PublicBrandContextService,
|
||||
private readonly wechatAuth: WechatAuthService,
|
||||
) {}
|
||||
|
||||
async loginWithWechat(code: string, brandSlug?: string): Promise<{ token: string }> {
|
||||
async loginWithWechat(session: WechatSession, brandSlug?: string): Promise<{ token: string }> {
|
||||
const brandId = await this.brandContext.resolveId(brandSlug);
|
||||
const brand = await this.prisma.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
select: { id: true, miniAppSettings: true },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!brand) throw new BadRequestException("品牌尚未初始化");
|
||||
const credentials = resolveWechatLoginCredentials(brand.miniAppSettings);
|
||||
const session: WechatSession = await this.wechatAuth.exchangeCode(code, credentials);
|
||||
const customer = await this.prisma.customerUser.upsert({
|
||||
where: { brandId_openid: { brandId: brand.id, openid: session.openid } },
|
||||
update: { lastLoginAt: new Date() },
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Body, Controller, Get, Post, Query, Req, Res } from "@nestjs/common";
|
||||
import type { FastifyReply, FastifyRequest } from "fastify";
|
||||
import { WechatAuthService } from "../../wechat-auth.js";
|
||||
import { AdminPublic, AdminTokenOnly } from "../../admin-auth.decorators.js";
|
||||
import { clearAdminSessionCookie, setAdminSessionCookie } from "../../admin-session-cookie.js";
|
||||
import { AdminAuthService } from "../../admin-auth.service.js";
|
||||
@@ -10,14 +11,18 @@ import { ChangeAdminPasswordDto } from "../../admin.dto.js";
|
||||
|
||||
@Controller("customer/session")
|
||||
export class CustomerSessionController {
|
||||
constructor(private readonly sessions: CustomerSessionService) {}
|
||||
constructor(
|
||||
private readonly wechatAuth: WechatAuthService,
|
||||
private readonly sessions: CustomerSessionService,
|
||||
) {}
|
||||
|
||||
@Post("wechat")
|
||||
async wechatLogin(
|
||||
@Body() body: WechatLoginDto,
|
||||
@Query("brandSlug") brandSlug?: string,
|
||||
): Promise<{ token: string }> {
|
||||
return this.sessions.loginWithWechat(body.code, brandSlug);
|
||||
const session = await this.wechatAuth.exchangeCode(body.code);
|
||||
return this.sessions.loginWithWechat(session, brandSlug);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Injectable, ServiceUnavailableException, UnauthorizedException } from "@nestjs/common";
|
||||
import { decryptMiniAppCredential } from "./miniapp-credential-crypto.js";
|
||||
|
||||
interface WechatSessionResponse {
|
||||
openid?: string;
|
||||
@@ -15,45 +14,17 @@ export interface WechatSession {
|
||||
unionid?: string;
|
||||
}
|
||||
|
||||
export interface WechatLoginCredentials {
|
||||
appId: string;
|
||||
appSecret: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 每个品牌对应自己的小程序,登录凭据必须来自该品牌的后台上传配置。
|
||||
* 不使用全局环境变量或跨品牌回退,避免把 A 品牌的 OpenID 登录到 B 品牌。
|
||||
*/
|
||||
export function resolveWechatLoginCredentials(settings: unknown): WechatLoginCredentials {
|
||||
const payload =
|
||||
settings && typeof settings === "object" && !Array.isArray(settings)
|
||||
? (settings as Record<string, unknown>)
|
||||
: {};
|
||||
const appId = typeof payload.appId === "string" ? payload.appId.trim() : "";
|
||||
if (!appId) throw new ServiceUnavailableException("该品牌尚未配置微信 AppID");
|
||||
if (!payload.appSecretCredential)
|
||||
throw new ServiceUnavailableException("该品牌尚未配置微信登录 AppSecret");
|
||||
let appSecret: string;
|
||||
try {
|
||||
appSecret = decryptMiniAppCredential(payload.appSecretCredential);
|
||||
} catch {
|
||||
throw new ServiceUnavailableException("该品牌微信登录凭据不可用,请重新保存 AppSecret");
|
||||
}
|
||||
if (!appSecret)
|
||||
throw new ServiceUnavailableException("该品牌微信登录 AppSecret 为空,请重新保存");
|
||||
return { appId, appSecret };
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class WechatAuthService {
|
||||
async exchangeCode(code: string, credentials: WechatLoginCredentials): Promise<WechatSession> {
|
||||
async exchangeCode(code: string): Promise<WechatSession> {
|
||||
if (!code.trim()) throw new UnauthorizedException("微信登录 code 不能为空");
|
||||
if (!credentials.appId || !credentials.appSecret)
|
||||
throw new ServiceUnavailableException("微信登录尚未配置");
|
||||
const appId = process.env.WECHAT_APP_ID;
|
||||
const appSecret = process.env.WECHAT_APP_SECRET;
|
||||
if (!appId || !appSecret) throw new ServiceUnavailableException("微信登录尚未配置");
|
||||
|
||||
const query = new URLSearchParams({
|
||||
appid: credentials.appId,
|
||||
secret: credentials.appSecret,
|
||||
appid: appId,
|
||||
secret: appSecret,
|
||||
js_code: code,
|
||||
grant_type: "authorization_code",
|
||||
});
|
||||
|
||||
@@ -4,10 +4,7 @@ import { BadRequestException } from "@nestjs/common";
|
||||
import { generateKeyPairSync } from "node:crypto";
|
||||
import { AdminMiniAppSettingsService } from "../src/modules/admin/admin-miniapp-settings.service.js";
|
||||
import type { AdminMiniAppReleaseService } from "../src/modules/admin/admin-miniapp-release.service.js";
|
||||
import {
|
||||
decryptMiniAppCredential,
|
||||
encryptMiniAppCredential,
|
||||
} from "../src/miniapp-credential-crypto.js";
|
||||
import { decryptMiniAppCredential } from "../src/modules/admin/miniapp-credential-crypto.js";
|
||||
|
||||
process.env.SESSION_SECRET = "settings-service-test-secret-1234567890";
|
||||
|
||||
@@ -28,19 +25,12 @@ function createService(settings: Record<string, unknown> = {}) {
|
||||
return { service: new AdminMiniAppSettingsService(releases), saved };
|
||||
}
|
||||
|
||||
test("settings presentation never exposes encrypted credential payloads", async () => {
|
||||
test("settings presentation never exposes plaintext credentials", async () => {
|
||||
const credential = { algorithm: "aes-256-gcm" };
|
||||
const appSecretCredential = {
|
||||
algorithm: "aes-256-gcm",
|
||||
ciphertext: "encrypted-secret",
|
||||
iv: "iv",
|
||||
authTag: "tag",
|
||||
};
|
||||
const { service } = createService({
|
||||
appId: "wxtestsettings",
|
||||
apiBaseUrl: "https://wechat.example.com/api",
|
||||
credential,
|
||||
appSecretCredential,
|
||||
build: { keep: true },
|
||||
});
|
||||
const result = (await service.get("brand-1")) as Record<string, unknown>;
|
||||
@@ -48,12 +38,8 @@ test("settings presentation never exposes encrypted credential payloads", async
|
||||
assert.equal(result.apiBaseUrl, "https://wechat.example.com/api");
|
||||
assert.equal(result.requestDomain, "wechat.example.com");
|
||||
assert.equal(result.hasStoredCredentials, true);
|
||||
assert.equal(result.hasStoredAppSecret, true);
|
||||
assert.equal(result.loginConfigured, true);
|
||||
assert.deepEqual(result.credential, { algorithm: "aes-256-gcm" });
|
||||
assert.equal(result.privateKey, undefined);
|
||||
assert.equal("appSecretCredential" in result, false);
|
||||
assert.equal(JSON.stringify(result).includes("encrypted-secret"), false);
|
||||
});
|
||||
|
||||
test("update validates URL and private key before persistence", async () => {
|
||||
@@ -81,7 +67,6 @@ test("update encrypts a valid private key and preserves existing settings", asyn
|
||||
appId: "wxnew",
|
||||
apiBaseUrl: "https://new.example.com/api/",
|
||||
privateKey,
|
||||
appSecret: "0123456789abcdef0123456789abcdef",
|
||||
build: { extra: true },
|
||||
})) as Record<string, unknown>;
|
||||
assert.equal(saved.length, 1);
|
||||
@@ -97,54 +82,3 @@ test("update encrypts a valid private key and preserves existing settings", asyn
|
||||
assert.ok(!JSON.stringify(saved[0]).includes(privateKey));
|
||||
assert.equal(result.hasStoredCredentials, true);
|
||||
});
|
||||
|
||||
test("update encrypts the WeChat login AppSecret without exposing it", async () => {
|
||||
const appSecret = "0123456789abcdef0123456789abcdef";
|
||||
const { service, saved } = createService({
|
||||
appId: "wxtestsettings",
|
||||
apiBaseUrl: "https://wechat.example.com/api",
|
||||
});
|
||||
const result = (await service.update("brand-1", { appSecret })) as Record<string, unknown>;
|
||||
assert.equal(saved.length, 1);
|
||||
const appSecretCredential = saved[0]?.appSecretCredential as Record<string, string>;
|
||||
assert.equal(appSecretCredential.algorithm, "aes-256-gcm");
|
||||
assert.equal(decryptMiniAppCredential(appSecretCredential), appSecret);
|
||||
assert.equal(JSON.stringify(saved[0]).includes(appSecret), false);
|
||||
assert.equal(result.hasStoredAppSecret, true);
|
||||
assert.equal(result.loginConfigured, true);
|
||||
assert.equal("appSecretCredential" in result, false);
|
||||
});
|
||||
|
||||
test("update rejects malformed WeChat login AppSecret", async () => {
|
||||
const { service, saved } = createService();
|
||||
await assert.rejects(
|
||||
() => service.update("brand-1", { appSecret: "not-a-valid-secret!" }),
|
||||
BadRequestException,
|
||||
);
|
||||
assert.equal(saved.length, 0);
|
||||
});
|
||||
|
||||
test("changing AppID requires the matching AppSecret", async () => {
|
||||
const appSecret = "0123456789abcdef0123456789abcdef";
|
||||
const { service, saved } = createService({
|
||||
appId: "wxold",
|
||||
appSecretCredential: encryptMiniAppCredential(appSecret),
|
||||
});
|
||||
await assert.rejects(
|
||||
() => service.update("brand-1", { appId: "wxnew" }),
|
||||
/必须同时填写该 AppID 对应的 AppSecret/,
|
||||
);
|
||||
assert.equal(saved.length, 0);
|
||||
});
|
||||
|
||||
test("leaving AppSecret empty preserves the stored credential", async () => {
|
||||
const appSecret = "0123456789abcdef0123456789abcdef";
|
||||
const storedCredential = encryptMiniAppCredential(appSecret);
|
||||
const { service, saved } = createService({
|
||||
appId: "wxtestsettings",
|
||||
appSecretCredential: storedCredential,
|
||||
});
|
||||
await service.update("brand-1", { appId: "wxtestsettings" });
|
||||
assert.equal(saved.length, 1);
|
||||
assert.deepEqual(saved[0]?.appSecretCredential, storedCredential);
|
||||
});
|
||||
@@ -8,7 +8,7 @@ import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { AdminMiniAppUploadService } from "../src/modules/admin/admin-miniapp-upload.service.js";
|
||||
import type { AdminMiniAppReleaseService } from "../src/modules/admin/admin-miniapp-release.service.js";
|
||||
import { encryptMiniAppCredential } from "../src/miniapp-credential-crypto.js";
|
||||
import { encryptMiniAppCredential } from "../src/modules/admin/miniapp-credential-crypto.js";
|
||||
|
||||
process.env.SESSION_SECRET = "upload-service-test-secret-1234567890";
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ import { getTemplatePackageManifest, getVisualTemplateManifest } from "@personal
|
||||
import { createApp } from "../dist/main.js";
|
||||
import { readIdentity, signIdentity } from "../dist/auth.js";
|
||||
import { WechatAuthService } from "../dist/wechat-auth.js";
|
||||
import { encryptMiniAppCredential } from "../dist/miniapp-credential-crypto.js";
|
||||
import { AdminMiniAppReleaseService } from "../dist/modules/admin/admin-miniapp-release.service.js";
|
||||
import { PostgresClientErrorThrottleStore } from "../dist/modules/admin/client-error-throttle.postgres.store.js";
|
||||
import {
|
||||
@@ -867,7 +866,7 @@ test("API restart recovers an expired persisted miniapp build attempt", async ()
|
||||
}
|
||||
});
|
||||
|
||||
test("miniapp release settings never expose or persist plaintext credentials", async () => {
|
||||
test("miniapp release settings never expose or persist plaintext private keys", async () => {
|
||||
const login = await request("/admin/session/login", {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
@@ -898,13 +897,6 @@ test("miniapp release settings never expose or persist plaintext credentials", a
|
||||
payload: { appId: "wxtestsettings", apiBaseUrl: "http://wechat.example.com/api" },
|
||||
});
|
||||
assert.equal(rejected.statusCode, 400);
|
||||
const invalidSecret = await request("/admin/miniapp-releases/settings", {
|
||||
method: "PATCH",
|
||||
headers,
|
||||
payload: { appSecret: "invalid secret!" },
|
||||
});
|
||||
assert.equal(invalidSecret.statusCode, 400);
|
||||
const appSecret = "0123456789abcdef0123456789abcdef";
|
||||
const saved = await request("/admin/miniapp-releases/settings", {
|
||||
method: "PATCH",
|
||||
headers,
|
||||
@@ -912,7 +904,6 @@ test("miniapp release settings never expose or persist plaintext credentials", a
|
||||
appId: "wxtestsettings",
|
||||
apiBaseUrl: "https://wechat.example.com/api/",
|
||||
privateKey,
|
||||
appSecret,
|
||||
},
|
||||
});
|
||||
assert.equal(saved.statusCode, 200);
|
||||
@@ -921,24 +912,17 @@ test("miniapp release settings never expose or persist plaintext credentials", a
|
||||
assert.equal(body.apiBaseUrl, "https://wechat.example.com/api");
|
||||
assert.equal(body.requestDomain, "wechat.example.com");
|
||||
assert.equal(body.hasStoredCredentials, true);
|
||||
assert.equal(body.hasStoredAppSecret, true);
|
||||
assert.equal(body.loginConfigured, true);
|
||||
assert.equal(body.privateKey, undefined);
|
||||
assert.equal(body.credential?.algorithm, "aes-256-gcm");
|
||||
assert.equal("appSecretCredential" in body, false);
|
||||
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;
|
||||
const appSecretCredential = brand.miniAppSettings?.appSecretCredential;
|
||||
assert.ok(credential);
|
||||
assert.ok(appSecretCredential);
|
||||
assert.equal(brand.miniAppSettings.apiBaseUrl, "https://wechat.example.com/api");
|
||||
assert.equal(typeof credential.ciphertext, "string");
|
||||
assert.equal(typeof appSecretCredential.ciphertext, "string");
|
||||
assert.ok(!JSON.stringify(brand.miniAppSettings).includes(privateKey));
|
||||
assert.ok(!JSON.stringify(brand.miniAppSettings).includes(appSecret));
|
||||
const missing = await request("/admin/miniapp-releases/settings");
|
||||
assert.equal(missing.statusCode, 401);
|
||||
const forbidden = await request("/admin/miniapp-releases/settings", {
|
||||
@@ -5613,30 +5597,13 @@ test("wechat login validates the request DTO before exchanging the code", async
|
||||
assert.equal(response.statusCode, 400);
|
||||
});
|
||||
|
||||
test("wechat login creates a customer session using the requested brand credentials", async () => {
|
||||
test("wechat login creates a customer session for the requested brand", async () => {
|
||||
const doorsBrand = await prisma.brandProfile.findUnique({ where: { slug: "linjing-doors" } });
|
||||
assert.ok(doorsBrand);
|
||||
const sessionOpenid = `doors-login-${Date.now()}`;
|
||||
const appId = "wxintegrationdoors";
|
||||
const appSecret = "0123456789abcdef0123456789abcdef";
|
||||
const originalSettings = doorsBrand.miniAppSettings;
|
||||
await prisma.brandProfile.update({
|
||||
where: { id: doorsBrand.id },
|
||||
data: {
|
||||
miniAppSettings: {
|
||||
...(originalSettings && typeof originalSettings === "object" ? originalSettings : {}),
|
||||
appId,
|
||||
appSecretCredential: encryptMiniAppCredential(appSecret),
|
||||
},
|
||||
},
|
||||
});
|
||||
const wechatAuth = app.get(WechatAuthService);
|
||||
const originalExchangeCode = wechatAuth.exchangeCode;
|
||||
wechatAuth.exchangeCode = async (code, credentials) => {
|
||||
assert.equal(code, "test-code");
|
||||
assert.deepEqual(credentials, { appId, appSecret });
|
||||
return { openid: sessionOpenid };
|
||||
};
|
||||
wechatAuth.exchangeCode = async () => ({ openid: sessionOpenid });
|
||||
try {
|
||||
const response = await request("/customer/session/wechat?brandSlug=linjing-doors", {
|
||||
method: "POST",
|
||||
@@ -5654,49 +5621,6 @@ test("wechat login creates a customer session using the requested brand credenti
|
||||
} finally {
|
||||
wechatAuth.exchangeCode = originalExchangeCode;
|
||||
await prisma.customerUser.deleteMany({ where: { openid: sessionOpenid } });
|
||||
await prisma.brandProfile.update({
|
||||
where: { id: doorsBrand.id },
|
||||
data: { miniAppSettings: originalSettings },
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test("wechat login fails closed when a brand has no login AppSecret", async () => {
|
||||
const brand = await prisma.brandProfile.findUnique({ where: { slug: "default-brand" } });
|
||||
assert.ok(brand);
|
||||
const originalSettings = brand.miniAppSettings;
|
||||
const { appSecretCredential: _ignoredAppSecretCredential, ...settingsWithoutAppSecret } =
|
||||
originalSettings && typeof originalSettings === "object" ? originalSettings : {};
|
||||
await prisma.brandProfile.update({
|
||||
where: { id: brand.id },
|
||||
data: {
|
||||
miniAppSettings: {
|
||||
...settingsWithoutAppSecret,
|
||||
appId: "wxmissingsessionsecret",
|
||||
},
|
||||
},
|
||||
});
|
||||
const wechatAuth = app.get(WechatAuthService);
|
||||
const originalExchangeCode = wechatAuth.exchangeCode;
|
||||
let exchanged = false;
|
||||
wechatAuth.exchangeCode = async () => {
|
||||
exchanged = true;
|
||||
return { openid: `must-not-login-${Date.now()}` };
|
||||
};
|
||||
try {
|
||||
const response = await request("/customer/session/wechat?brandSlug=default-brand", {
|
||||
method: "POST",
|
||||
payload: { code: "test-code" },
|
||||
});
|
||||
assert.equal(response.statusCode, 503);
|
||||
assert.equal(JSON.parse(response.body).error.message, "该品牌尚未配置微信登录 AppSecret");
|
||||
assert.equal(exchanged, false);
|
||||
} finally {
|
||||
wechatAuth.exchangeCode = originalExchangeCode;
|
||||
await prisma.brandProfile.update({
|
||||
where: { id: brand.id },
|
||||
data: { miniAppSettings: originalSettings },
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -117,8 +117,8 @@ export const ROUTE_COVERAGE: RouteCoverage[] = [
|
||||
method: "GET",
|
||||
path: "/admin/miniapp-releases/settings",
|
||||
auth: "brand",
|
||||
authorizationTest: "miniapp release settings never expose or persist plaintext credentials",
|
||||
successTest: "miniapp release settings never expose or persist plaintext credentials",
|
||||
authorizationTest: "miniapp release settings never expose or persist plaintext private keys",
|
||||
successTest: "miniapp release settings never expose or persist plaintext private keys",
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
@@ -378,8 +378,8 @@ export const ROUTE_COVERAGE: RouteCoverage[] = [
|
||||
path: "/admin/miniapp-releases/settings",
|
||||
auth: "roles",
|
||||
roles: ["owner", "admin", "platform-admin"],
|
||||
authorizationTest: "miniapp release settings never expose or persist plaintext credentials",
|
||||
successTest: "miniapp release settings never expose or persist plaintext credentials",
|
||||
authorizationTest: "miniapp release settings never expose or persist plaintext private keys",
|
||||
successTest: "miniapp release settings never expose or persist plaintext private keys",
|
||||
},
|
||||
{
|
||||
method: "PATCH",
|
||||
@@ -655,7 +655,7 @@ export const ROUTE_COVERAGE: RouteCoverage[] = [
|
||||
path: "/customer/session/wechat",
|
||||
auth: "public",
|
||||
authorizationTest: null,
|
||||
successTest: "wechat login creates a customer session using the requested brand credentials",
|
||||
successTest: "wechat login creates a customer session for the requested brand",
|
||||
},
|
||||
{
|
||||
method: "POST",
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { ServiceUnavailableException, UnauthorizedException } from "@nestjs/common";
|
||||
import { encryptMiniAppCredential } from "../src/miniapp-credential-crypto.js";
|
||||
import {
|
||||
WechatAuthService,
|
||||
resolveWechatLoginCredentials,
|
||||
type WechatLoginCredentials,
|
||||
} from "../src/wechat-auth.js";
|
||||
|
||||
process.env.SESSION_SECRET = "wechat-auth-test-secret-1234567890";
|
||||
|
||||
const credentials: WechatLoginCredentials = {
|
||||
appId: "wxbranchappid",
|
||||
appSecret: "0123456789abcdef0123456789abcdef",
|
||||
};
|
||||
|
||||
test("resolveWechatLoginCredentials requires a brand AppID", () => {
|
||||
assert.throws(
|
||||
() => resolveWechatLoginCredentials({}),
|
||||
(error: unknown) =>
|
||||
error instanceof ServiceUnavailableException && error.message.includes("AppID"),
|
||||
);
|
||||
});
|
||||
|
||||
test("resolveWechatLoginCredentials requires a brand AppSecret", () => {
|
||||
assert.throws(
|
||||
() => resolveWechatLoginCredentials({ appId: credentials.appId }),
|
||||
(error: unknown) =>
|
||||
error instanceof ServiceUnavailableException && error.message.includes("AppSecret"),
|
||||
);
|
||||
});
|
||||
|
||||
test("resolveWechatLoginCredentials decrypts the brand AppSecret", () => {
|
||||
const resolved = resolveWechatLoginCredentials({
|
||||
appId: credentials.appId,
|
||||
appSecretCredential: encryptMiniAppCredential(credentials.appSecret),
|
||||
});
|
||||
assert.deepEqual(resolved, credentials);
|
||||
});
|
||||
|
||||
test("resolveWechatLoginCredentials reports unusable encrypted credentials as unavailable", () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
resolveWechatLoginCredentials({
|
||||
appId: credentials.appId,
|
||||
appSecretCredential: { algorithm: "aes-256-gcm", ciphertext: "broken" },
|
||||
}),
|
||||
(error: unknown) =>
|
||||
error instanceof ServiceUnavailableException && error.message.includes("凭据不可用"),
|
||||
);
|
||||
});
|
||||
|
||||
test("exchangeCode uses the credentials supplied for the requested brand", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
let requestedUrl = "";
|
||||
globalThis.fetch = async (input: string | URL | Request) => {
|
||||
requestedUrl =
|
||||
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
openid: "openid-1",
|
||||
session_key: "session-key-1",
|
||||
unionid: "unionid-1",
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } },
|
||||
);
|
||||
};
|
||||
try {
|
||||
const session = await new WechatAuthService().exchangeCode("login-code", credentials);
|
||||
const url = new URL(requestedUrl);
|
||||
assert.equal(url.origin + url.pathname, "https://api.weixin.qq.com/sns/jscode2session");
|
||||
assert.equal(url.searchParams.get("appid"), credentials.appId);
|
||||
assert.equal(url.searchParams.get("secret"), credentials.appSecret);
|
||||
assert.equal(url.searchParams.get("js_code"), "login-code");
|
||||
assert.equal(url.searchParams.get("grant_type"), "authorization_code");
|
||||
assert.deepEqual(session, {
|
||||
openid: "openid-1",
|
||||
sessionKey: "session-key-1",
|
||||
unionid: "unionid-1",
|
||||
});
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test("exchangeCode surfaces WeChat rejection details without treating them as success", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = async () =>
|
||||
new Response(JSON.stringify({ errcode: 40029, errmsg: "invalid code" }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
try {
|
||||
await assert.rejects(
|
||||
() => new WechatAuthService().exchangeCode("bad-code", credentials),
|
||||
(error: unknown) =>
|
||||
error instanceof UnauthorizedException && error.message === "invalid code",
|
||||
);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test("exchangeCode reports network and HTTP failures as service unavailable", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
try {
|
||||
globalThis.fetch = async () => {
|
||||
throw new Error("network down");
|
||||
};
|
||||
await assert.rejects(
|
||||
() => new WechatAuthService().exchangeCode("login-code", credentials),
|
||||
ServiceUnavailableException,
|
||||
);
|
||||
|
||||
globalThis.fetch = async () => new Response("upstream error", { status: 502 });
|
||||
await assert.rejects(
|
||||
() => new WechatAuthService().exchangeCode("login-code", credentials),
|
||||
ServiceUnavailableException,
|
||||
);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test("exchangeCode rejects empty codes and incomplete credentials", async () => {
|
||||
const service = new WechatAuthService();
|
||||
await assert.rejects(() => service.exchangeCode(" ", credentials), UnauthorizedException);
|
||||
await assert.rejects(
|
||||
() => service.exchangeCode("login-code", { appId: "", appSecret: "" }),
|
||||
ServiceUnavailableException,
|
||||
);
|
||||
});
|
||||
@@ -180,8 +180,6 @@ async function mockPublicationApi(page: Page, options: MockOptions = {}) {
|
||||
appId: "wx0000000000000000",
|
||||
apiBaseUrl: "https://wechat.app.que01.top/api",
|
||||
hasStoredCredentials: false,
|
||||
hasStoredAppSecret: false,
|
||||
loginConfigured: false,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -270,7 +268,7 @@ test("恢复历史版本会提交版本号并刷新发布记录", async ({ page
|
||||
await expect(page.getByText("历史版本已重新发布")).toBeVisible();
|
||||
});
|
||||
|
||||
test("小程序配置页回填服务端设置并提交新的登录凭据与私钥", async ({ page }) => {
|
||||
test("小程序配置页回填服务端设置并仅提交新私钥", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
const bodies: Record<string, unknown>[] = [];
|
||||
await mockPublicationApi(page, {});
|
||||
@@ -283,8 +281,6 @@ test("小程序配置页回填服务端设置并提交新的登录凭据与私
|
||||
appId: body.appId,
|
||||
apiBaseUrl: body.apiBaseUrl,
|
||||
hasStoredCredentials: true,
|
||||
hasStoredAppSecret: true,
|
||||
loginConfigured: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -296,12 +292,10 @@ test("小程序配置页回填服务端设置并提交新的登录凭据与私
|
||||
await expect(page.getByLabel("微信 AppID")).toHaveValue("wx0000000000000000");
|
||||
await expect(page.getByLabel("小程序请求地址")).toHaveValue("https://wechat.app.que01.top/api");
|
||||
|
||||
const appSecret = "0123456789abcdef0123456789abcdef";
|
||||
await page.getByLabel("微信登录 AppSecret").fill(appSecret);
|
||||
await page
|
||||
.getByLabel("上传私钥")
|
||||
.fill("-----BEGIN PRIVATE KEY-----\nKEY\n-----END PRIVATE KEY-----");
|
||||
await page.getByRole("button", { name: "保存小程序配置" }).click();
|
||||
await page.getByRole("button", { name: "保存上传配置" }).click();
|
||||
|
||||
await expect
|
||||
.poll(() => bodies)
|
||||
@@ -309,9 +303,8 @@ test("小程序配置页回填服务端设置并提交新的登录凭据与私
|
||||
{
|
||||
appId: "wx0000000000000000",
|
||||
apiBaseUrl: "https://wechat.app.que01.top/api",
|
||||
appSecret,
|
||||
privateKey: "-----BEGIN PRIVATE KEY-----\nKEY\n-----END PRIVATE KEY-----",
|
||||
},
|
||||
]);
|
||||
await expect(page.getByText("小程序配置已保存")).toBeVisible();
|
||||
await expect(page.getByText("小程序上传配置已保存")).toBeVisible();
|
||||
});
|
||||
@@ -189,16 +189,6 @@ test("业务编辑弹窗预览列表与详情详情同一份内容", async ({ pa
|
||||
await expect(editor.locator(".service-offering-editor__view")).toContainText("详情内容");
|
||||
await expect(page.getByText("正在核对详情展示")).toBeVisible();
|
||||
|
||||
await preview.locator(".food-detail .hero-copy").click();
|
||||
await expect(preview).toHaveAttribute(
|
||||
"data-active-target",
|
||||
"acheng-campus-food.detail.dishDetail",
|
||||
);
|
||||
await expect(page.getByText("餐品与服务详情对应字段", { exact: true })).toBeVisible();
|
||||
await expect(
|
||||
editor.locator('[data-presentation-binding="offering.config.details.background"]'),
|
||||
).toHaveClass(/is-preview-active/);
|
||||
|
||||
await page.getByLabel("餐品介绍").fill("弹窗编辑后的餐品介绍");
|
||||
await expect(preview.locator(".food-detail .body")).toContainText("弹窗编辑后的餐品介绍");
|
||||
|
||||
@@ -207,25 +197,6 @@ test("业务编辑弹窗预览列表与详情详情同一份内容", async ({ pa
|
||||
await expect(preview).toHaveAttribute("data-active-target", "acheng-campus-food.offerings.item");
|
||||
await expect(page.getByText("正在核对列表展示")).toBeVisible();
|
||||
|
||||
await preview.locator(".offering-card .dish-name").click();
|
||||
await expect(page.getByText("业务卡片对应字段", { exact: true })).toBeVisible();
|
||||
await expect(editor.locator('[data-presentation-binding="offering.name"]')).toHaveClass(
|
||||
/is-preview-active/,
|
||||
);
|
||||
await expect(
|
||||
editor.locator('[data-presentation-binding="offering.config.details.background"]'),
|
||||
).toHaveCount(0);
|
||||
|
||||
await preview.locator(".menu-head").click();
|
||||
await expect(preview).toHaveAttribute("data-active-target", "acheng-campus-food.offerings.menu");
|
||||
await expect(page.getByText("「菜单页说明」属于页面通用内容", { exact: true })).toBeVisible();
|
||||
await expect(editor.locator('[data-presentation-binding="offering.name"]')).not.toHaveClass(
|
||||
/is-preview-active/,
|
||||
);
|
||||
await expect(editor.getByText("详情主图", { exact: true })).toHaveCount(0);
|
||||
|
||||
await preview.locator(".offering-card .dish-name").click();
|
||||
await expect(page.getByText("业务卡片对应字段", { exact: true })).toBeVisible();
|
||||
await page.getByLabel("名称", { exact: true }).fill("列表实时预览餐品");
|
||||
await expect(preview.locator(".offering-card")).toContainText("列表实时预览餐品");
|
||||
|
||||
|
||||
+20
-5
@@ -41,6 +41,23 @@ pnpm deploy:status
|
||||
|
||||
如需异地副本,在 `shared/.env.production` 配置 `BACKUP_OFFSITE_TARGET`(`rsync` 目标,例如 `backup@example-host:/srv/personal-brand-backups/`),并为 `ubuntu` 用户预先配置 SSH key。未配置时备份只保留在同一台 VPS 上,不等同于灾难恢复副本。至少每季度应在隔离数据库执行一次恢复演练,不得在生产数据库上测试恢复;整机重启演练需在维护窗口执行,确认 Admin、API、PostgreSQL 和公网路由恢复后再结束维护。
|
||||
|
||||
## 微信登录配置
|
||||
|
||||
后台「小程序上传配置」中的 AppID 和上传私钥只用于构建、上传小程序代码,不等于访客登录配置。体验版或正式版调用 `wx.login` 后,API 还需要以下两个环境变量才能通过微信 `jscode2session` 换取 OpenID:
|
||||
|
||||
```bash
|
||||
WECHAT_APP_ID=wxd75d946d6978d183
|
||||
WECHAT_APP_SECRET=<小程序 AppSecret>
|
||||
```
|
||||
|
||||
两项写入 `shared/.env.production`,不要提交到仓库。`WECHAT_APP_ID` 必须与后台上传配置中的 AppID 一致;不一致时微信会返回 `40029` 或 `40163`。修改后重启 API:
|
||||
|
||||
```bash
|
||||
pm2 restart personal-brand-api
|
||||
```
|
||||
|
||||
API 通过 `node --env-file=shared/.env.production` 启动,重启后会读取新值。`pnpm deploy:status` 会检查两项是否非空;缺失时状态检查失败。
|
||||
|
||||
## Nginx 反向代理
|
||||
|
||||
生产环境建议使用同源路径:
|
||||
@@ -211,11 +228,9 @@ curl -fsS "$API_BASE_URL/public/workspace?brandSlug=$BRAND_SLUG" |
|
||||
|
||||
`API_BASE_URL` 与 AppID 是**编译期常量**,构建时写入小程序包,无法在后台热改。上传前按以下顺序解析并校验,任一项不合法就直接拒绝构建,避免把指向 `localhost` 的包上传到微信:
|
||||
|
||||
- 请求地址:后台「配置与发布 → 小程序配置」里的“小程序请求地址”优先;未配置时回落到 `MINIAPP_API_BASE_URL`,再回落到 `PUBLIC_BASE_URL` 加 `MINIAPP_API_PATH`(默认 `/api`)。非 `https` 的公网地址会被拒绝。因此换域名只需在后台改这一项并重新上传代码,不用改服务端环境变量。
|
||||
- AppID:同样以后台“小程序配置”里的 AppID 为准,回落 `WEAPP_APP_ID`;`undefined`、`touristappid` 等占位值会被拒绝。
|
||||
- 请求地址:后台「配置与发布 → 小程序上传配置」里的“小程序请求地址”优先;未配置时回落到 `MINIAPP_API_BASE_URL`,再回落到 `PUBLIC_BASE_URL` 加 `MINIAPP_API_PATH`(默认 `/api`)。非 `https` 的公网地址会被拒绝。因此换域名只需在后台改这一项并重新上传代码,不用改服务端环境变量。
|
||||
- AppID:同样以后台“小程序上传配置”里的 AppID 为准,回落 `WEAPP_APP_ID`;`undefined`、`touristappid` 等占位值会被拒绝。
|
||||
|
||||
微信登录同样使用该品牌的 AppID,但 AppSecret 由后台“小程序配置”单独维护。服务端使用 `MINIAPP_CREDENTIAL_ENCRYPTION_KEY`(未配置时回退 `SESSION_SECRET`)加密保存 AppSecret,登录时按 `brandSlug` 读取对应品牌的凭据,不使用全局 `WECHAT_APP_SECRET`,也不会跨品牌回退。修改 AppSecret 后立即生效,不需要重新上传小程序代码;修改 AppID 时必须同时填写该 AppID 对应的 AppSecret。
|
||||
|
||||
该域名必须与微信后台“开发设置 → 服务器域名 → request 合法域名”完全一致,否则小程序打开即报“加载失败,请重试”。后台“小程序配置”会直接展示当前生效的请求域名,便于上线前比对。
|
||||
该域名必须与微信后台“开发设置 → 服务器域名 → request 合法域名”完全一致,否则小程序打开即报“加载失败,请重试”。后台“小程序上传配置”会直接展示当前生效的请求域名,便于上线前比对。
|
||||
|
||||
小程序包内的 `/media/...` 按请求地址的 origin 解析(例如 `https://host/api` → `https://host/media/...`),与网关的 `/media` 路由保持一致,不依赖 `/api` 前缀的剥离行为。
|
||||
@@ -80,7 +80,6 @@ export interface BrandMethods {
|
||||
appId?: string;
|
||||
apiBaseUrl?: string;
|
||||
privateKey?: string;
|
||||
appSecret?: string;
|
||||
}): Promise<MiniAppReleaseSettings>;
|
||||
}
|
||||
|
||||
|
||||
@@ -115,10 +115,6 @@ export interface MiniAppReleaseSettings {
|
||||
build: Record<string, unknown>;
|
||||
credential: { algorithm: string } | null;
|
||||
hasStoredCredentials: boolean;
|
||||
/** 微信登录 AppSecret 是否已加密保存 */
|
||||
hasStoredAppSecret: boolean;
|
||||
/** AppID 与 AppSecret 均已配置,小程序 wx.login 可换取 OpenID */
|
||||
loginConfigured: boolean;
|
||||
/** 小程序包内编译期写入的请求域名,需与微信后台 request 合法域名一致 */
|
||||
requestDomain?: string | null;
|
||||
/** 构建参数缺失时的原因,非空表示当前无法构建上传 */
|
||||
|
||||
@@ -186,7 +186,7 @@ test("发布检查与发布操作使用当前品牌的管理接口", async () =>
|
||||
]);
|
||||
});
|
||||
|
||||
test("小程序配置会提交请求地址", async () => {
|
||||
test("小程序上传配置会提交请求地址", async () => {
|
||||
const calls: Array<{ url: string; method?: string; body?: string }> = [];
|
||||
const client = new ApiClient({
|
||||
baseUrl: "http://api.test",
|
||||
@@ -199,7 +199,6 @@ test("小程序配置会提交请求地址", async () => {
|
||||
await client.updateAdminMiniAppSettings({
|
||||
appId: "wx123",
|
||||
apiBaseUrl: "https://wechat.example.com/api",
|
||||
appSecret: "0123456789abcdef0123456789abcdef",
|
||||
});
|
||||
assert.deepEqual(calls, [
|
||||
{
|
||||
@@ -208,7 +207,6 @@ test("小程序配置会提交请求地址", async () => {
|
||||
body: JSON.stringify({
|
||||
appId: "wx123",
|
||||
apiBaseUrl: "https://wechat.example.com/api",
|
||||
appSecret: "0123456789abcdef0123456789abcdef",
|
||||
}),
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -43,6 +43,7 @@ export function buildRemoteStatusScript({ deployRoot: rootPath = deployRoot } =
|
||||
'printf "backup-timer="; systemctl --user is-active personal-brand-backup.timer',
|
||||
'printf "backup-age-hours="; newest=$(find "$DEPLOY_ROOT/shared/backups" -maxdepth 1 -type f -name "*.dump" -printf "%T@ %p\\n" | sort -nr | head -1 | cut -d" " -f2-); age=$(( ( $(date +%s) - $(stat -c %Y "$newest") ) / 3600 )); echo "$age"; test "$age" -le "${BACKUP_MAX_AGE_HOURS:-36}"',
|
||||
'printf "backup-temp-files="; find "$DEPLOY_ROOT/shared/backups" -maxdepth 1 -type f -name "*.tmp" | wc -l',
|
||||
'printf "wechat-login="; if grep -q "^WECHAT_APP_ID=." "$DEPLOY_ROOT/shared/.env.production" && grep -q "^WECHAT_APP_SECRET=." "$DEPLOY_ROOT/shared/.env.production"; then echo configured; else echo missing; exit 1; fi',
|
||||
'printf "disk="; df -h / | awk \'NR==2 {print $5 " used, " $4 " free"}\'',
|
||||
'printf "release-count="; find "$DEPLOY_ROOT/releases" -mindepth 1 -maxdepth 1 -type d | wc -l',
|
||||
].join("; ");
|
||||
|
||||
@@ -12,6 +12,8 @@ test("生产状态脚本不再要求 VPS 上运行 CI runner", () => {
|
||||
assert.match(script, /personal-brand-backup\.timer/);
|
||||
assert.match(script, /backup-age-hours/);
|
||||
assert.match(script, /BACKUP_MAX_AGE_HOURS/);
|
||||
assert.match(script, /wechat-login/);
|
||||
assert.match(script, /WECHAT_APP_SECRET/);
|
||||
});
|
||||
|
||||
test("生产状态脚本语法有效", () => {
|
||||
|
||||
Reference in new issue
Block a user