import { BadRequestException, Injectable } from "@nestjs/common"; 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 { inspectPrivateKey, normalizePrivateKey } from "./miniapp-private-key.js"; import type { UpdateMiniAppSettingsDto } from "./admin-miniapp-settings.dto.js"; @Injectable() export class AdminMiniAppSettingsService { constructor(private readonly releases: AdminMiniAppReleaseService) {} async get(brandId: string): Promise { const settings = this.jsonObject(await this.releases.settings(brandId)); return this.present(settings); } async update(brandId: string, body: UpdateMiniAppSettingsDto & { privateKey?: string }) { if (body.privateKey !== undefined) this.validatePrivateKey(body.privateKey); const current = this.jsonObject(await this.releases.settings(brandId)); const settings = { ...current, appId: body.appId ?? current.appId ?? "", apiBaseUrl: body.apiBaseUrl === undefined ? (current.apiBaseUrl ?? "") : this.apiBaseUrl(body), build: { ...this.jsonObject(current.build), ...this.jsonObject(body.build), } as Prisma.InputJsonObject, ...(body.privateKey === undefined ? {} : { credential: encryptMiniAppCredential(normalizePrivateKey(body.privateKey)) }), templateKey: current.templateKey ?? null, } satisfies Prisma.InputJsonObject; await this.releases.saveSettings(brandId, settings); return this.present(settings); } private validatePrivateKey(privateKey: string) { if (!privateKey.trim().startsWith("-----BEGIN")) throw new BadRequestException("上传私钥格式无效:应为 -----BEGIN 开头的 PEM 内容"); const inspection = inspectPrivateKey(privateKey); if (!inspection.valid) throw new BadRequestException( `上传私钥无法解析(${inspection.reason ?? "PEM 格式错误"})。请粘贴微信开发者工具生成的完整私钥,注意保留换行。`, ); } private apiBaseUrl(body: UpdateMiniAppSettingsDto) { const trimmed = body.apiBaseUrl?.trim(); if (!trimmed) throw new BadRequestException("小程序请求地址不能为空"); try { return validateApiBaseUrl(trimmed); } catch (error) { throw new BadRequestException(error instanceof Error ? error.message : "小程序请求地址无效"); } } private present(settings: Record) { return { appId: "", artifactPath: miniappArtifactRoot(), build: {}, ...settings, apiBaseUrl: this.effectiveApiBaseUrl(settings.apiBaseUrl), privateKey: undefined, credential: settings.credential ? { algorithm: "aes-256-gcm" } : null, hasStoredCredentials: Boolean(settings.credential), ...this.buildConfigSummary(settings.apiBaseUrl, settings.appId), }; } private buildConfigSummary( storedApiBaseUrl: unknown, storedAppId: unknown, ): { requestDomain: string | null; buildError: string | null; } { try { const base = miniappApiBaseUrl(storedApiBaseUrl); weappAppId(storedAppId); return { requestDomain: new URL(base).host, buildError: null }; } catch (error) { return { requestDomain: null, buildError: error instanceof Error ? error.message : "小程序构建参数未配置", }; } } /** 表单回显:品牌未显式配置时展示环境推导出的默认地址,便于管理员在其基础上修改。 */ private effectiveApiBaseUrl(storedApiBaseUrl: unknown) { try { return miniappApiBaseUrl(storedApiBaseUrl); } catch { return typeof storedApiBaseUrl === "string" ? storedApiBaseUrl : ""; } } private jsonObject(value: unknown): Record { return value && typeof value === "object" && !Array.isArray(value) ? (value as Record) : {}; } }