fix: 收口依赖兼容与会话撤销

为 miniprogram-ci 和 Jimp 依赖增加兼容 patch 与 smoke test;修复平台模板管理员路由漏配;收紧模板契约校验;为 admin/customer 增加 token 撤销和集中会话存储;同步品牌切换角色、doctor source hash、多屏宽截图证据和 CI 构建门禁。
This commit is contained in:
que01 committed 2026-10-18 23:43:25 +08:00
1 parent 4f0b50c7f1
commit 3017e3eb49
65 files changed
+1623 -975

No files matched your search

@@ -0,0 +1,2 @@
-- 客户 token 版本用于登出后撤销既有登录态。
ALTER TABLE "CustomerUser" ADD COLUMN "tokenVersion" INTEGER NOT NULL DEFAULT 0;
+1
View File
@@ -365,6 +365,7 @@ model CustomerUser {
brandId String
brand BrandProfile @relation(fields: [brandId], references: [id])
openid String
tokenVersion Int @default(0)
lastLoginAt DateTime @default(now())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
+9
View File
@@ -44,6 +44,15 @@ export class AdminAuthService {
};
}
async logout(userId: string): Promise<void> {
const user = await this.prisma.adminUser.findUnique({ where: { id: userId } });
if (!user?.isEnabled) throw new UnauthorizedException("管理员登录态无效或已过期");
await this.prisma.adminUser.update({
where: { id: userId },
data: { tokenVersion: { increment: 1 } },
});
}
async changePassword(
userId: string,
currentPassword: string,
+6 -1
View File
@@ -22,7 +22,12 @@ export class AdminMembershipGuard implements CanActivate {
if (routePath === "admin/session/login") return Promise.resolve(true);
if (routePath === "admin/session/change-password") return Promise.resolve(true);
if (!routePath.startsWith("admin/")) return Promise.resolve(true);
if (routePath === "admin/templates" || routePath.startsWith("admin/templates/")) {
if (
routePath === "admin/templates" ||
routePath.startsWith("admin/templates/") ||
routePath === "admin/template-operations" ||
routePath.startsWith("admin/template-operations/")
) {
return this.access.requireTemplateAdmin(request).then(() => true);
}
if (
-11
View File
@@ -22,8 +22,6 @@ export interface CreateBookingInput {
items?: Array<{ offeringId: string; quantity: number }>;
}
export type CustomerIdentity = { brandId: string; openid: string };
@Injectable()
export class BookingService {
constructor(
@@ -31,15 +29,6 @@ export class BookingService {
private readonly releases: BrandReleaseService,
) {}
async requireCustomer(identity: CustomerIdentity): Promise<string> {
const customer = await this.prisma.customerUser.findUnique({
where: { brandId_openid: identity },
select: { id: true },
});
if (!customer) throw new BadRequestException("请先完成微信登录");
return customer.id;
}
async create(brandId: string, customerUserId: string, input: CreateBookingInput) {
const snapshot = await this.releases.getPublishedSnapshot(brandId);
if (!snapshot) throw new BadRequestException("品牌尚未发布");
@@ -0,0 +1,46 @@
import { ForbiddenException, Injectable, UnauthorizedException } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { PrismaService } from "../../prisma.service.js";
import { readIdentity } from "../../auth.js";
export type CustomerIdentity = {
brandId: string;
openid: string;
customerUserId: string;
};
@Injectable()
export class CustomerAccessService {
constructor(private readonly prisma: PrismaService) {}
async require(request: FastifyRequest): Promise<CustomerIdentity> {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少客户登录态");
let identity;
try {
identity = readIdentity(token);
} catch {
throw new UnauthorizedException("客户登录态无效或已过期");
}
if (identity.role !== "customer") throw new ForbiddenException("客户登录态无效或已过期");
const customer = await this.prisma.customerUser.findUnique({
where: { brandId_openid: { brandId: identity.brandId, openid: identity.subject } },
select: { id: true, tokenVersion: true },
});
if (!customer || identity.tokenVersion !== customer.tokenVersion)
throw new UnauthorizedException("客户登录态无效或已过期");
return {
brandId: identity.brandId,
openid: identity.subject,
customerUserId: customer.id,
};
}
async logout(request: FastifyRequest): Promise<void> {
const identity = await this.require(request);
await this.prisma.customerUser.update({
where: { id: identity.customerUserId },
data: { tokenVersion: { increment: 1 } },
});
}
}
@@ -1,18 +1,21 @@
import { BadRequestException, Body, Controller, Get, Param, Post, Req } from "@nestjs/common";
import { Body, Controller, Get, Param, Post, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { Prisma } from "@prisma/client";
import { BookingService } from "../../booking.service.js";
import { CreateBookingDto } from "../../booking.dto.js";
import { readIdentity } from "../../auth.js";
import { CustomerAccessService } from "./customer-access.service.js";
@Controller("customer/bookings")
export class CustomerBookingController {
constructor(private readonly bookings: BookingService) {}
constructor(
private readonly bookings: BookingService,
private readonly access: CustomerAccessService,
) {}
@Post()
async create(@Req() request: FastifyRequest, @Body() body: CreateBookingDto): Promise<unknown> {
const identity = this.identity(request);
const customerId = await this.bookings.requireCustomer(identity);
const identity = await this.identity(request);
const customerId = identity.customerUserId;
return this.bookings.create(identity.brandId, customerId, {
...body,
extraData: body.extraData as Prisma.InputJsonObject,
@@ -21,28 +24,19 @@ export class CustomerBookingController {
@Get()
async list(@Req() request: FastifyRequest): Promise<unknown> {
const identity = this.identity(request);
const customerId = await this.bookings.requireCustomer(identity);
const identity = await this.identity(request);
const customerId = identity.customerUserId;
return this.bookings.listForCustomer(identity.brandId, customerId);
}
@Post(":id/cancel")
async cancel(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
const identity = this.identity(request);
const customerId = await this.bookings.requireCustomer(identity);
const identity = await this.identity(request);
const customerId = identity.customerUserId;
return this.bookings.cancelForCustomer(identity.brandId, customerId, id);
}
private identity(request: FastifyRequest): { brandId: string; openid: string } {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new BadRequestException("缺少客户登录态");
try {
const identity = readIdentity(token);
if (identity.role !== "customer") throw new BadRequestException("客户登录态无效");
return { brandId: identity.brandId, openid: identity.subject };
} catch (error) {
if (error instanceof BadRequestException) throw error;
throw new BadRequestException("客户登录态无效");
}
private identity(request: FastifyRequest) {
return this.access.require(request);
}
}
@@ -1,21 +1,15 @@
import {
Body,
Controller,
ForbiddenException,
Get,
Param,
Post,
Req,
UnauthorizedException,
} from "@nestjs/common";
import { Body, Controller, Get, Param, Post, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { readIdentity } from "../../auth.js";
import { CustomerAccessService } from "./customer-access.service.js";
import { CreateInquirySubmissionDto } from "../../booking.dto.js";
import { CustomerInquirySubmissionService } from "./customer-inquiry-submission.service.js";
@Controller("customer/inquiry-submissions")
export class CustomerInquirySubmissionController {
constructor(private readonly submissions: CustomerInquirySubmissionService) {}
constructor(
private readonly submissions: CustomerInquirySubmissionService,
private readonly access: CustomerAccessService,
) {}
private present<T extends { customerSubject: string; adminNote?: string | null }>(submission: T) {
const {
customerSubject: _customerSubject,
@@ -26,34 +20,21 @@ export class CustomerInquirySubmissionController {
void _adminNote;
return publicSubmission;
}
private identity(request: FastifyRequest): ReturnType<typeof readIdentity> {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少客户登录态");
try {
const identity = readIdentity(token);
if (identity.role !== "customer") throw new ForbiddenException("无客户权限");
return identity;
} catch (error) {
if (error instanceof ForbiddenException) throw error;
throw new UnauthorizedException("客户登录态无效或已过期");
}
private identity(request: FastifyRequest) {
return this.access.require(request);
}
@Get()
async list(@Req() request: FastifyRequest): Promise<unknown> {
const identity = this.identity(request);
const submissions = await this.submissions.listForCustomer(identity.brandId, identity.subject);
const identity = await this.identity(request);
const submissions = await this.submissions.listForCustomer(identity.brandId, identity.openid);
return submissions.map((submission) => this.present(submission));
}
@Get(":id")
async get(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
const identity = this.identity(request);
const submission = await this.submissions.getForCustomer(
identity.brandId,
identity.subject,
id,
);
const identity = await this.identity(request);
const submission = await this.submissions.getForCustomer(identity.brandId, identity.openid, id);
return this.present(submission);
}
@@ -62,8 +43,8 @@ export class CustomerInquirySubmissionController {
@Req() request: FastifyRequest,
@Body() body: CreateInquirySubmissionDto,
): Promise<unknown> {
const identity = this.identity(request);
const submission = await this.submissions.create(identity.brandId, identity.subject, body);
const identity = await this.identity(request);
const submission = await this.submissions.create(identity.brandId, identity.openid, body);
return this.present(submission);
}
}
@@ -0,0 +1,14 @@
import { Controller, Post, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { CustomerAccessService } from "./customer-access.service.js";
@Controller("customer/session")
export class CustomerSessionController {
constructor(private readonly access: CustomerAccessService) {}
@Post("logout")
async logout(@Req() request: FastifyRequest): Promise<{ loggedOut: true }> {
await this.access.logout(request);
return { loggedOut: true };
}
}
@@ -5,10 +5,16 @@ import { PublicModule } from "../public/public.module.js";
import { CustomerBookingController } from "./customer-booking.controller.js";
import { CustomerInquirySubmissionController } from "./customer-inquiry-submission.controller.js";
import { CustomerInquirySubmissionService } from "./customer-inquiry-submission.service.js";
import { CustomerAccessService } from "./customer-access.service.js";
import { CustomerSessionController } from "./customer-session.controller.js";
@Module({
imports: [InfrastructureModule, PublicModule, BookingModule],
controllers: [CustomerInquirySubmissionController, CustomerBookingController],
providers: [CustomerInquirySubmissionService],
controllers: [
CustomerInquirySubmissionController,
CustomerBookingController,
CustomerSessionController,
],
providers: [CustomerInquirySubmissionService, CustomerAccessService],
})
export class CustomerModule {}
@@ -18,13 +18,18 @@ export class CustomerSessionService {
select: { id: true },
});
if (!brand) throw new BadRequestException("品牌尚未初始化");
await this.prisma.customerUser.upsert({
const customer = await this.prisma.customerUser.upsert({
where: { brandId_openid: { brandId: brand.id, openid: session.openid } },
update: { lastLoginAt: new Date() },
create: { brandId: brand.id, openid: session.openid },
});
return {
token: signIdentity({ subject: session.openid, brandId: brand.id, role: "customer" }),
token: signIdentity({
subject: session.openid,
brandId: brand.id,
role: "customer",
tokenVersion: customer.tokenVersion,
}),
};
}
}
@@ -39,6 +39,16 @@ export class AdminSessionController {
return this.auth.login(body.username, body.password);
}
@Post("logout")
async logout(@Req() request: FastifyRequest): Promise<{ loggedOut: true }> {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少管理员登录态");
const identity = readIdentity(token);
if (identity.role !== "admin") throw new UnauthorizedException("管理员登录态无效");
await this.auth.logout(identity.subject);
return { loggedOut: true };
}
@Post("change-password")
async changePassword(
@Req() request: FastifyRequest,
@@ -60,7 +60,7 @@ export class TenantController {
async switchBrand(
@Req() request: FastifyRequest,
@Param("brandId") brandId: string,
): Promise<{ token: string; brand: unknown }> {
): Promise<{ token: string; role: string; brand: unknown }> {
const identity = this.adminIdentity(request);
return this.tenants.switchBrand(identity, brandId);
}
@@ -113,6 +113,7 @@ export class TenantService {
role: "admin",
tokenVersion: identity.tokenVersion ?? 0,
}),
role: membership.role,
brand: membership.brand,
};
}
+81 -2
View File
@@ -247,6 +247,30 @@ test("模板失败指标仅平台模板管理员可查,按窗口聚合且不
await prisma.adminUser.delete({ where: { id: ordinaryUser.id } });
}
const templateAdminWithoutMembership = await prisma.adminUser.create({
data: {
username: `metrics-platform-${randomUUID()}`,
passwordHash: "unused",
displayName: "平台模板管理员",
platformTemplateRole: "template_admin",
mustChangePassword: false,
},
});
try {
const response = await request("/admin/template-operations/failures", {
headers: {
authorization: `Bearer ${signIdentity({
subject: templateAdminWithoutMembership.id,
brandId: "00000000-0000-0000-0000-000000000000",
role: "admin",
})}`,
},
});
assert.equal(response.statusCode, 200, response.body);
} finally {
await prisma.adminUser.delete({ where: { id: templateAdminWithoutMembership.id } });
}
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
@@ -516,7 +540,10 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
/所属行业|must match its key/,
],
[{ ...stored.manifestSnapshot, requiredCapabilities: ["unknown"] }, /未注册的 capability/],
[{ ...stored.manifestSnapshot, visualTemplateKey: "unknown" }, /元数据/],
[
{ ...stored.manifestSnapshot, visualTemplateKey: "unknown" },
/visualTemplateKey must match packageKey|元数据/,
],
[{ ...stored.manifestSnapshot, runtimeContract: "9.0" }, /契约/],
[{ ...stored.manifestSnapshot, dataSlots: [null] }, /契约/],
[{ ...stored.manifestSnapshot, navigation: [null] }, /契约/],
@@ -3868,6 +3895,54 @@ test("admin login validates credentials", async () => {
assert.equal(response.statusCode, 401);
});
test("admin logout revokes the current token", async () => {
const username = `logout-admin-${randomUUID()}`;
const password = "logout-password-123";
const user = await prisma.adminUser.create({
data: {
username,
passwordHash: await bcrypt.hash(password, 12),
displayName: "登出测试管理员",
mustChangePassword: false,
},
});
await prisma.brandMembership.create({
data: { brandId, adminUserId: user.id, role: "owner", isEnabled: true },
});
try {
const login = await request("/admin/session/login", {
method: "POST",
payload: { username, password },
});
assert.equal(login.statusCode, 201, login.body);
const token = JSON.parse(login.body).token;
const headers = { authorization: `Bearer ${token}` };
const before = await request("/admin/bookings/unread-count", { headers });
assert.equal(before.statusCode, 200);
const logout = await request("/admin/session/logout", { method: "POST", headers });
assert.equal(logout.statusCode, 201);
const after = await request("/admin/bookings/unread-count", { headers });
assert.equal(after.statusCode, 401);
} finally {
await prisma.adminUser.delete({ where: { id: user.id } });
}
});
test("customer logout revokes the current token", async () => {
const openid = `logout-${randomUUID()}`;
await prisma.customerUser.create({ data: { brandId, openid } });
const token = signIdentity({ subject: openid, brandId, role: "customer" });
const headers = { authorization: `Bearer ${token}` };
const before = await request("/customer/inquiry-submissions", { headers });
assert.equal(before.statusCode, 200);
const logout = await request("/customer/session/logout", { method: "POST", headers });
assert.equal(logout.statusCode, 201);
const after = await request("/customer/inquiry-submissions", { headers });
assert.equal(after.statusCode, 401);
});
test("admin login does not auto-grant ownership to users without memberships", async () => {
const username = `no-membership-${Date.now()}`;
const user = await prisma.adminUser.create({
@@ -4287,7 +4362,7 @@ test("admin can manage trust content", async () => {
test("customer booking endpoints require a valid customer session", async () => {
const missing = await request("/customer/bookings");
assert.equal(missing.statusCode, 400);
assert.equal(missing.statusCode, 401);
const list = await request("/customer/bookings", {
headers: { authorization: `Bearer ${customerToken}` },
@@ -4774,6 +4849,9 @@ test("atelier template imports selected package and preserves draft publication
(await json("/public/workspace?brandSlug=" + slug)).brand.visualPresentation.home.title,
"仅草稿可见的新标题",
);
const atelierCustomer = await prisma.customerUser.create({
data: { brandId: brand.id, openid: "atelier-test-customer" },
});
const customerHeaders = {
authorization: `Bearer ${signIdentity({ subject: "atelier-test-customer", brandId: brand.id, role: "customer" })}`,
};
@@ -4819,6 +4897,7 @@ test("atelier template imports selected package and preserves draft publication
);
}
} finally {
await prisma.customerUser.deleteMany({ where: { brandId: brand.id } });
await prisma.brandProfile.delete({ where: { id: brand.id } });
}
});
@@ -0,0 +1,31 @@
import assert from "node:assert/strict";
import { createRequire } from "node:module";
import test from "node:test";
const require = createRequire(import.meta.url);
const png = Buffer.from(
"89504e470d0a1a0a0000000d4948445200000001000000010802000000907753de0000000c49444154789c63f8cfc0000003010100c9fe92ef0000000049454e44ae426082",
"hex",
);
test("miniprogram-ci compatibility patches keep overridden runtime APIs usable", async () => {
const buildCloud = require(
require.resolve("miniprogram-ci/dist/modules/nativecompiler/ios/buildCloud.js"),
);
assert.equal(typeof buildCloud.default, "object");
const uuid = require("uuid") as { v4: () => string };
assert.match(uuid.v4(), /^[0-9a-f-]{36}$/);
const imageSize = require("image-size") as {
imageSize: (input: Buffer) => { width: number; height: number; type: string };
};
assert.deepEqual(imageSize.imageSize(png), { width: 1, height: 1, type: "png" });
const Jimp = require("jimp") as {
read: (input: Buffer) => Promise<{ bitmap: { width: number; height: number } }>;
};
const image = await Jimp.read(png);
assert.equal(image.bitmap.width, 1);
assert.equal(image.bitmap.height, 1);
});
@@ -45,7 +45,7 @@ async function main() {
.filter((entry) => entry.isDirectory() && entry.name !== targetMigration)
.map((entry) => entry.name)
.sort();
assert.equal(migrationDirs.at(-1), "20261018170000_add_admin_token_version");
assert.equal(migrationDirs.at(-1), "20261018180000_add_customer_token_version");
await admin.$executeRawUnsafe(`CREATE SCHEMA "${schema}"`);
createdSchema = true;