feat: 支持按品牌配置微信登录凭据
This commit is contained in:
1 parent
e75c524343
commit
d0a0eeea8c
23 files changed
+460
-62
No files matched your search
+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([
|
||||
@@ -18,4 +18,9 @@ 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,10 +18,17 @@ 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: body.appId ?? current.appId ?? "",
|
||||
appId: nextAppId,
|
||||
apiBaseUrl:
|
||||
body.apiBaseUrl === undefined ? (current.apiBaseUrl ?? "") : this.apiBaseUrl(body),
|
||||
build: {
|
||||
@@ -31,6 +38,9 @@ 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);
|
||||
@@ -47,6 +57,14 @@ 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("小程序请求地址不能为空");
|
||||
@@ -58,16 +76,21 @@ 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: {},
|
||||
...settings,
|
||||
apiBaseUrl: this.effectiveApiBaseUrl(settings.apiBaseUrl),
|
||||
...rest,
|
||||
apiBaseUrl: this.effectiveApiBaseUrl(rest.apiBaseUrl),
|
||||
privateKey: undefined,
|
||||
credential: settings.credential ? { algorithm: "aes-256-gcm" } : null,
|
||||
hasStoredCredentials: Boolean(settings.credential),
|
||||
...this.buildConfigSummary(settings.apiBaseUrl, settings.appId),
|
||||
credential: credential ? { algorithm: "aes-256-gcm" } : null,
|
||||
hasStoredCredentials: Boolean(credential),
|
||||
hasStoredAppSecret: Boolean(appSecretCredential),
|
||||
loginConfigured: Boolean(appId && appSecretCredential),
|
||||
...this.buildConfigSummary(rest.apiBaseUrl, rest.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,7 +1,11 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { signIdentity } from "../../auth.js";
|
||||
import type { WechatSession } from "../../wechat-auth.js";
|
||||
import {
|
||||
WechatAuthService,
|
||||
resolveWechatLoginCredentials,
|
||||
type WechatSession,
|
||||
} from "../../wechat-auth.js";
|
||||
import { PublicBrandContextService } from "../public/public-brand-context.service.js";
|
||||
|
||||
@Injectable()
|
||||
@@ -9,15 +13,18 @@ export class CustomerSessionService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly brandContext: PublicBrandContextService,
|
||||
private readonly wechatAuth: WechatAuthService,
|
||||
) {}
|
||||
|
||||
async loginWithWechat(session: WechatSession, brandSlug?: string): Promise<{ token: string }> {
|
||||
async loginWithWechat(code: string, 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 },
|
||||
select: { id: true, miniAppSettings: 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,6 +1,5 @@
|
||||
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";
|
||||
@@ -11,18 +10,14 @@ import { ChangeAdminPasswordDto } from "../../admin.dto.js";
|
||||
|
||||
@Controller("customer/session")
|
||||
export class CustomerSessionController {
|
||||
constructor(
|
||||
private readonly wechatAuth: WechatAuthService,
|
||||
private readonly sessions: CustomerSessionService,
|
||||
) {}
|
||||
constructor(private readonly sessions: CustomerSessionService) {}
|
||||
|
||||
@Post("wechat")
|
||||
async wechatLogin(
|
||||
@Body() body: WechatLoginDto,
|
||||
@Query("brandSlug") brandSlug?: string,
|
||||
): Promise<{ token: string }> {
|
||||
const session = await this.wechatAuth.exchangeCode(body.code);
|
||||
return this.sessions.loginWithWechat(session, brandSlug);
|
||||
return this.sessions.loginWithWechat(body.code, brandSlug);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Injectable, ServiceUnavailableException, UnauthorizedException } from "@nestjs/common";
|
||||
import { decryptMiniAppCredential } from "./miniapp-credential-crypto.js";
|
||||
|
||||
interface WechatSessionResponse {
|
||||
openid?: string;
|
||||
@@ -14,17 +15,45 @@ 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): Promise<WechatSession> {
|
||||
async exchangeCode(code: string, credentials: WechatLoginCredentials): Promise<WechatSession> {
|
||||
if (!code.trim()) throw new UnauthorizedException("微信登录 code 不能为空");
|
||||
const appId = process.env.WECHAT_APP_ID;
|
||||
const appSecret = process.env.WECHAT_APP_SECRET;
|
||||
if (!appId || !appSecret) throw new ServiceUnavailableException("微信登录尚未配置");
|
||||
if (!credentials.appId || !credentials.appSecret)
|
||||
throw new ServiceUnavailableException("微信登录尚未配置");
|
||||
|
||||
const query = new URLSearchParams({
|
||||
appid: appId,
|
||||
secret: appSecret,
|
||||
appid: credentials.appId,
|
||||
secret: credentials.appSecret,
|
||||
js_code: code,
|
||||
grant_type: "authorization_code",
|
||||
});
|
||||
|
||||
@@ -4,7 +4,10 @@ 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 } from "../src/modules/admin/miniapp-credential-crypto.js";
|
||||
import {
|
||||
decryptMiniAppCredential,
|
||||
encryptMiniAppCredential,
|
||||
} from "../src/miniapp-credential-crypto.js";
|
||||
|
||||
process.env.SESSION_SECRET = "settings-service-test-secret-1234567890";
|
||||
|
||||
@@ -25,12 +28,19 @@ function createService(settings: Record<string, unknown> = {}) {
|
||||
return { service: new AdminMiniAppSettingsService(releases), saved };
|
||||
}
|
||||
|
||||
test("settings presentation never exposes plaintext credentials", async () => {
|
||||
test("settings presentation never exposes encrypted credential payloads", 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>;
|
||||
@@ -38,8 +48,12 @@ test("settings presentation never exposes plaintext credentials", 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 () => {
|
||||
@@ -67,6 +81,7 @@ 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);
|
||||
@@ -82,3 +97,54 @@ 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/modules/admin/miniapp-credential-crypto.js";
|
||||
import { encryptMiniAppCredential } from "../src/miniapp-credential-crypto.js";
|
||||
|
||||
process.env.SESSION_SECRET = "upload-service-test-secret-1234567890";
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ 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 {
|
||||
@@ -866,7 +867,7 @@ test("API restart recovers an expired persisted miniapp build attempt", async ()
|
||||
}
|
||||
});
|
||||
|
||||
test("miniapp release settings never expose or persist plaintext private keys", async () => {
|
||||
test("miniapp release settings never expose or persist plaintext credentials", async () => {
|
||||
const login = await request("/admin/session/login", {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
@@ -897,6 +898,13 @@ test("miniapp release settings never expose or persist plaintext private keys",
|
||||
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,
|
||||
@@ -904,6 +912,7 @@ test("miniapp release settings never expose or persist plaintext private keys",
|
||||
appId: "wxtestsettings",
|
||||
apiBaseUrl: "https://wechat.example.com/api/",
|
||||
privateKey,
|
||||
appSecret,
|
||||
},
|
||||
});
|
||||
assert.equal(saved.statusCode, 200);
|
||||
@@ -912,17 +921,24 @@ test("miniapp release settings never expose or persist plaintext private keys",
|
||||
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", {
|
||||
@@ -5597,13 +5613,30 @@ test("wechat login validates the request DTO before exchanging the code", async
|
||||
assert.equal(response.statusCode, 400);
|
||||
});
|
||||
|
||||
test("wechat login creates a customer session for the requested brand", async () => {
|
||||
test("wechat login creates a customer session using the requested brand credentials", 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 () => ({ openid: sessionOpenid });
|
||||
wechatAuth.exchangeCode = async (code, credentials) => {
|
||||
assert.equal(code, "test-code");
|
||||
assert.deepEqual(credentials, { appId, appSecret });
|
||||
return { openid: sessionOpenid };
|
||||
};
|
||||
try {
|
||||
const response = await request("/customer/session/wechat?brandSlug=linjing-doors", {
|
||||
method: "POST",
|
||||
@@ -5621,6 +5654,49 @@ test("wechat login creates a customer session for the requested brand", async ()
|
||||
} 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 private keys",
|
||||
successTest: "miniapp release settings never expose or persist plaintext private keys",
|
||||
authorizationTest: "miniapp release settings never expose or persist plaintext credentials",
|
||||
successTest: "miniapp release settings never expose or persist plaintext credentials",
|
||||
},
|
||||
{
|
||||
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 private keys",
|
||||
successTest: "miniapp release settings never expose or persist plaintext private keys",
|
||||
authorizationTest: "miniapp release settings never expose or persist plaintext credentials",
|
||||
successTest: "miniapp release settings never expose or persist plaintext credentials",
|
||||
},
|
||||
{
|
||||
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 for the requested brand",
|
||||
successTest: "wechat login creates a customer session using the requested brand credentials",
|
||||
},
|
||||
{
|
||||
method: "POST",
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
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,
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user