fix: harden api authentication and validation
This commit is contained in:
@@ -3,6 +3,7 @@ DATABASE_URL=postgresql://postgres:postgres@localhost:5432/personal_brand
|
|||||||
API_PORT=3001
|
API_PORT=3001
|
||||||
ADMIN_PORT=3000
|
ADMIN_PORT=3000
|
||||||
SESSION_SECRET=replace-with-a-long-random-value
|
SESSION_SECRET=replace-with-a-long-random-value
|
||||||
|
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
|
||||||
OBJECT_STORAGE_ENDPOINT=
|
OBJECT_STORAGE_ENDPOINT=
|
||||||
OBJECT_STORAGE_BUCKET=
|
OBJECT_STORAGE_BUCKET=
|
||||||
OBJECT_STORAGE_ACCESS_KEY=
|
OBJECT_STORAGE_ACCESS_KEY=
|
||||||
|
|||||||
10
apps/api/src/admin.dto.ts
Normal file
10
apps/api/src/admin.dto.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { IsIn, IsOptional, IsString } from "class-validator";
|
||||||
|
|
||||||
|
export class UpdateBookingStatusDto {
|
||||||
|
@IsIn(["received", "contacting", "confirmed", "completed", "cancelled"])
|
||||||
|
status!: "received" | "contacting" | "confirmed" | "completed" | "cancelled";
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
adminNote?: string;
|
||||||
|
}
|
||||||
34
apps/api/src/auth.ts
Normal file
34
apps/api/src/auth.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import { UnauthorizedException } from "@nestjs/common";
|
||||||
|
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||||
|
|
||||||
|
type Identity = { subject: string; brandId: string; role: "customer" | "admin"; exp: number };
|
||||||
|
|
||||||
|
function secret(): string {
|
||||||
|
const value = process.env.SESSION_SECRET;
|
||||||
|
if (!value || value.length < 32) throw new UnauthorizedException("服务端会话密钥未正确配置");
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function signIdentity(
|
||||||
|
identity: Omit<Identity, "exp">,
|
||||||
|
ttlSeconds = 60 * 60 * 24 * 7,
|
||||||
|
): string {
|
||||||
|
const payload = Buffer.from(
|
||||||
|
JSON.stringify({ ...identity, exp: Math.floor(Date.now() / 1000) + ttlSeconds }),
|
||||||
|
).toString("base64url");
|
||||||
|
const signature = createHmac("sha256", secret()).update(payload).digest("base64url");
|
||||||
|
return `${payload}.${signature}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readIdentity(token: string): Identity {
|
||||||
|
const [payload, signature] = token.split(".");
|
||||||
|
if (!payload || !signature) throw new UnauthorizedException("登录态无效");
|
||||||
|
const expected = createHmac("sha256", secret()).update(payload).digest();
|
||||||
|
const actual = Buffer.from(signature, "base64url");
|
||||||
|
if (actual.length !== expected.length || !timingSafeEqual(actual, expected))
|
||||||
|
throw new UnauthorizedException("登录态无效");
|
||||||
|
const identity = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as Identity;
|
||||||
|
if (!identity.exp || identity.exp < Math.floor(Date.now() / 1000))
|
||||||
|
throw new UnauthorizedException("登录态已过期");
|
||||||
|
return identity;
|
||||||
|
}
|
||||||
@@ -33,6 +33,16 @@ export class BookingService {
|
|||||||
throw new BadRequestException("普通套餐至少选择一份有效套餐");
|
throw new BadRequestException("普通套餐至少选择一份有效套餐");
|
||||||
}
|
}
|
||||||
const extraData = input.extraData as { people?: unknown; location?: unknown } | undefined;
|
const extraData = input.extraData as { people?: unknown; location?: unknown } | undefined;
|
||||||
|
const allowedExtraKeys = new Set([
|
||||||
|
"people",
|
||||||
|
"location",
|
||||||
|
"budgetRange",
|
||||||
|
"tastePreferences",
|
||||||
|
"allergyNotes",
|
||||||
|
"dishPreferences",
|
||||||
|
]);
|
||||||
|
if (input.extraData && Object.keys(input.extraData).some((key) => !allowedExtraKeys.has(key)))
|
||||||
|
throw new BadRequestException("存在不支持的行业字段");
|
||||||
if (
|
if (
|
||||||
input.requestType === "private_chef" &&
|
input.requestType === "private_chef" &&
|
||||||
(!input.requestedDate || !extraData?.people || !extraData.location)
|
(!input.requestedDate || !extraData?.people || !extraData.location)
|
||||||
|
|||||||
@@ -18,28 +18,9 @@ import { PrismaService } from "./prisma.service.js";
|
|||||||
import { WechatAuthService } from "./wechat-auth.js";
|
import { WechatAuthService } from "./wechat-auth.js";
|
||||||
import { BookingService } from "./booking.service.js";
|
import { BookingService } from "./booking.service.js";
|
||||||
import { CreateBookingDto } from "./booking.dto.js";
|
import { CreateBookingDto } from "./booking.dto.js";
|
||||||
|
import { UpdateBookingStatusDto } from "./admin.dto.js";
|
||||||
import type { FastifyRequest } from "fastify";
|
import type { FastifyRequest } from "fastify";
|
||||||
import { createHmac } from "node:crypto";
|
import { readIdentity, signIdentity } from "./auth.js";
|
||||||
|
|
||||||
function signIdentity(identity: { brandId: string; openid: string }): string {
|
|
||||||
const payload = Buffer.from(JSON.stringify(identity)).toString("base64url");
|
|
||||||
const signature = createHmac("sha256", process.env.SESSION_SECRET ?? "development-only-secret")
|
|
||||||
.update(payload)
|
|
||||||
.digest("base64url");
|
|
||||||
return `${payload}.${signature}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function readIdentity(token: string): { brandId: string; openid: string } {
|
|
||||||
const [payload, signature] = token.split(".");
|
|
||||||
const expected = createHmac("sha256", process.env.SESSION_SECRET ?? "development-only-secret")
|
|
||||||
.update(payload ?? "")
|
|
||||||
.digest("base64url");
|
|
||||||
if (!payload || signature !== expected) throw new BadRequestException("客户登录态无效");
|
|
||||||
return JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as {
|
|
||||||
brandId: string;
|
|
||||||
openid: string;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
@Controller("health")
|
@Controller("health")
|
||||||
export class HealthController {
|
export class HealthController {
|
||||||
@@ -105,7 +86,9 @@ export class CustomerSessionController {
|
|||||||
update: { lastLoginAt: new Date() },
|
update: { lastLoginAt: new Date() },
|
||||||
create: { brandId: brand.id, openid: session.openid },
|
create: { brandId: brand.id, openid: session.openid },
|
||||||
});
|
});
|
||||||
return { token: signIdentity({ brandId: brand.id, openid: session.openid }) };
|
return {
|
||||||
|
token: signIdentity({ subject: session.openid, brandId: brand.id, role: "customer" }),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -153,7 +136,9 @@ export class CustomerBookingController {
|
|||||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||||
if (!token) throw new BadRequestException("缺少客户登录态");
|
if (!token) throw new BadRequestException("缺少客户登录态");
|
||||||
try {
|
try {
|
||||||
return readIdentity(token);
|
const identity = readIdentity(token);
|
||||||
|
if (identity.role !== "customer") throw new BadRequestException("客户登录态无效");
|
||||||
|
return { brandId: identity.brandId, openid: identity.subject };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof BadRequestException) throw error;
|
if (error instanceof BadRequestException) throw error;
|
||||||
throw new BadRequestException("客户登录态无效");
|
throw new BadRequestException("客户登录态无效");
|
||||||
@@ -165,20 +150,20 @@ export class CustomerBookingController {
|
|||||||
export class AdminBookingController {
|
export class AdminBookingController {
|
||||||
constructor(private readonly bookings: BookingService) {}
|
constructor(private readonly bookings: BookingService) {}
|
||||||
@Get()
|
@Get()
|
||||||
list(): Promise<unknown> {
|
list(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
|
this.requireAdmin(request);
|
||||||
return this.bookings.listForAdmin(
|
return this.bookings.listForAdmin(
|
||||||
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
|
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@Post(":id/status")
|
@Post(":id/status")
|
||||||
update(
|
update(
|
||||||
|
@Req() request: FastifyRequest,
|
||||||
@Param("id") id: string,
|
@Param("id") id: string,
|
||||||
@Body()
|
@Body()
|
||||||
body: {
|
body: UpdateBookingStatusDto,
|
||||||
status: "received" | "contacting" | "confirmed" | "completed" | "cancelled";
|
|
||||||
adminNote?: string;
|
|
||||||
},
|
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
|
this.requireAdmin(request);
|
||||||
return this.bookings.updateStatus(
|
return this.bookings.updateStatus(
|
||||||
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
|
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
|
||||||
id,
|
id,
|
||||||
@@ -186,6 +171,13 @@ export class AdminBookingController {
|
|||||||
body.adminNote,
|
body.adminNote,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private requireAdmin(request: FastifyRequest): void {
|
||||||
|
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||||
|
if (!token) throw new BadRequestException("缺少管理员登录态");
|
||||||
|
const identity = readIdentity(token);
|
||||||
|
if (identity.role !== "admin") throw new BadRequestException("无管理员权限");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
|
|||||||
Reference in New Issue
Block a user