refactor(P0): JWT 认证、并发安全、错误日志三项安全加固

- 新增 JWT httpOnly cookie 认证链路 (jose),登录/注册签发 token,
  所有用户和盲盒 API 改为从 cookie 提取 userId,不再信任客户端传值
- 新增 /api/auth/logout 端点清除认证 cookie
- GET /api/user 区分 owner/非 owner,非 owner 不暴露 email
- atomicUpdateRoom 新增 per-room 应用层互斥锁,防止 SQLite 下并发 lost update
- 修复 getRoomData 中 fire-and-forget delete 改为 await
- 37 个静默 catch 块跨 17 个文件添加 console.error 日志
- 新增 REFACTOR_PLAN.md 全景分析文档
This commit is contained in:
2026-03-02 17:24:26 +08:00
parent 99120a7042
commit ce76980fe5
41 changed files with 528 additions and 144 deletions
+12 -6
View File
@@ -132,7 +132,8 @@ export async function tagIdea(content: string): Promise<IdeaTags | null> {
searchQuery: parsed.searchQuery,
searchType: parsed.searchType,
};
} catch {
} catch (e) {
console.error("tagIdea failed:", e);
return null;
}
}
@@ -170,7 +171,8 @@ export async function suggestIdeas(existingIdeas: string[]): Promise<string[]> {
return parsed.suggestions
.filter((s: unknown) => typeof s === "string" && s.length > 0)
.slice(0, 4);
} catch {
} catch (e) {
console.error("suggestIdeas failed:", e);
return [];
}
}
@@ -236,7 +238,8 @@ ${Object.entries(ctx.candidates)
})),
summary: String(parsed.summary ?? ""),
};
} catch {
} catch (e) {
console.error("generateSchedule failed:", e);
return null;
}
}
@@ -284,7 +287,8 @@ export async function refinePlan(
})) return null;
return result as import("@/types").WeekendPlanData[];
} catch {
} catch (e) {
console.error("refinePlan failed:", e);
return null;
}
}
@@ -337,7 +341,8 @@ export async function suggestAlternativeItems(
typeof (a as Record<string, unknown>).searchQuery === "string",
)
.slice(0, 3) as Array<{ activity: string; searchQuery: string; reason: string }>;
} catch {
} catch (e) {
console.error("suggestAlternativeItems failed:", e);
return null;
}
}
@@ -437,7 +442,8 @@ export async function runAgentLoop(
let args: Record<string, unknown>;
try {
args = JSON.parse(toolCall.function.arguments);
} catch {
} catch (e) {
console.error("runAgentLoop: failed to parse tool arguments:", e);
args = {};
}
+5 -1
View File
@@ -12,7 +12,11 @@ export class ApiError extends Error {
}
}
/** Validates that value is a non-empty string; throws 401 otherwise. */
/**
* Validates that value is a non-empty string; throws 401 otherwise.
* Used for room routes where anonymous users pass userId in body.
* For registered-user routes, prefer getAuthUserId() from lib/auth.
*/
export function requireUserId(value: unknown): string {
if (!value || typeof value !== "string") {
throw new ApiError("请先登录", 401);
+80
View File
@@ -0,0 +1,80 @@
import { SignJWT, jwtVerify } from "jose";
import { NextRequest, NextResponse } from "next/server";
import { ApiError } from "@/lib/api";
const COOKIE_NAME = "nw_token";
const TOKEN_MAX_AGE = 7 * 24 * 60 * 60; // 7 days in seconds
function getSecret() {
const secret = process.env.JWT_SECRET;
if (!secret) {
throw new Error("JWT_SECRET environment variable is not set");
}
return new TextEncoder().encode(secret);
}
export async function signToken(userId: string): Promise<string> {
return new SignJWT({ sub: userId })
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime(`${TOKEN_MAX_AGE}s`)
.sign(getSecret());
}
export async function verifyToken(token: string): Promise<string> {
const { payload } = await jwtVerify(token, getSecret());
if (!payload.sub) throw new Error("Invalid token payload");
return payload.sub;
}
export function setAuthCookie(res: NextResponse, token: string): NextResponse {
res.cookies.set(COOKIE_NAME, token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: TOKEN_MAX_AGE,
});
return res;
}
export function clearAuthCookie(res: NextResponse): NextResponse {
res.cookies.set(COOKIE_NAME, "", {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: 0,
});
return res;
}
/**
* Extracts authenticated userId from JWT cookie.
* Throws 401 if no valid token is present.
*/
export async function getAuthUserId(req: NextRequest): Promise<string> {
const token = req.cookies.get(COOKIE_NAME)?.value;
if (!token) {
throw new ApiError("请先登录", 401);
}
try {
return await verifyToken(token);
} catch {
throw new ApiError("登录已过期,请重新登录", 401);
}
}
/**
* Optionally extracts userId from JWT cookie.
* Returns null if no valid token (does not throw).
*/
export async function getOptionalAuthUserId(req: NextRequest): Promise<string | null> {
const token = req.cookies.get(COOKIE_NAME)?.value;
if (!token) return null;
try {
return await verifyToken(token);
} catch {
return null;
}
}
+12 -6
View File
@@ -319,7 +319,8 @@ function buildAgentTools(
try {
const pois = await searchPois(query, searchType, lat, lng);
return JSON.stringify(pois);
} catch {
} catch (e) {
console.error("searchPoiTool failed:", e);
return JSON.stringify([]);
}
},
@@ -369,7 +370,8 @@ function buildAgentTools(
const distanceKm = Math.round(Number(data.route.distance) / 100) / 10;
const { description, mode } = parseTransitSegments(transit.segments ?? []);
return JSON.stringify({ durationMin, distanceKm, description, mode });
} catch {
} catch (e) {
console.error("getTravelTimeTool failed:", e);
return JSON.stringify({ error: "路线查询失败" });
}
},
@@ -535,7 +537,8 @@ async function runLegacyPlanGeneration(
try {
const pois = await searchPois(idea.searchQuery, idea.searchType, room.lat, room.lng);
return { query: idea.searchQuery, pois };
} catch {
} catch (e) {
console.error(`searchPois failed for "${idea.searchQuery}":`, e);
return { query: idea.searchQuery, pois: [] };
}
}),
@@ -560,7 +563,8 @@ async function runLegacyPlanGeneration(
try {
const pois = await searchPois(idea.searchQuery, idea.searchType, anchorLat, anchorLng);
return { query: idea.searchQuery, pois };
} catch {
} catch (e) {
console.error(`searchPois (category) failed for "${idea.searchQuery}":`, e);
return { query: idea.searchQuery, pois: [] };
}
}),
@@ -643,7 +647,8 @@ async function queryTransit(
const transit = data.route.transits[0];
const { description } = parseTransitSegments(transit.segments ?? []);
return { durationMin: Math.ceil(Number(transit.duration) / 60), description };
} catch {
} catch (e) {
console.error("queryTransit failed:", e);
return null;
}
}
@@ -770,7 +775,8 @@ export async function runPlanGeneration(
onProgress,
);
days = agentResult.days;
} catch {
} catch (e) {
console.error("runAgentPlanGeneration failed, falling back to legacy:", e);
onProgress?.("使用备用方案规划...");
const legacyResult = await runLegacyPlanGeneration(
{ lat: room.lat, lng: room.lng },
+2 -1
View File
@@ -15,7 +15,8 @@ export async function loadImageAsDataUrl(src: string): Promise<string | null> {
const ctx = canvas.getContext("2d")!;
ctx.drawImage(img, 0, 0);
return canvas.toDataURL("image/jpeg", 0.85);
} catch {
} catch (e) {
console.error("proxyToDataUrl failed:", e);
return null;
}
}
+39 -14
View File
@@ -102,32 +102,57 @@ export async function getRoomData(
const room = await prisma.room.findUnique({ where: { id: roomId } });
if (!room) return null;
if (room.expiresAt < new Date()) {
prisma.room.delete({ where: { id: roomId } }).catch(() => {});
await prisma.room.delete({ where: { id: roomId } }).catch((e) => {
console.error(`Failed to delete expired room ${roomId}:`, e);
});
return null;
}
return normalize(JSON.parse(room.data));
}
/**
* Atomic read-modify-write within a Prisma transaction.
* Prevents race conditions when multiple users swipe concurrently.
* Per-room mutex to serialize concurrent read-modify-write operations.
* SQLite doesn't support row-level locks (SELECT ... FOR UPDATE),
* so we use an application-level lock to prevent lost updates.
*/
const roomLocks = new Map<string, Promise<unknown>>();
function withRoomLock<T>(roomId: string, fn: () => Promise<T>): Promise<T> {
const prev = roomLocks.get(roomId) ?? Promise.resolve();
const next = prev.then(fn, fn);
roomLocks.set(roomId, next);
// Cleanup the lock entry when the chain settles
next.finally(() => {
if (roomLocks.get(roomId) === next) {
roomLocks.delete(roomId);
}
});
return next;
}
/**
* Atomic read-modify-write with per-room serialization.
* Uses an application-level mutex to prevent concurrent lost updates,
* since SQLite lacks row-level locking.
*/
export async function atomicUpdateRoom(
roomId: string,
updater: (data: RoomData) => RoomData,
): Promise<RoomData | null> {
return prisma.$transaction(async (tx) => {
const room = await tx.room.findUnique({ where: { id: roomId } });
if (!room) return null;
return withRoomLock(roomId, () =>
prisma.$transaction(async (tx) => {
const room = await tx.room.findUnique({ where: { id: roomId } });
if (!room) return null;
const data = normalize(JSON.parse(room.data));
const updated = updater(data);
const data = normalize(JSON.parse(room.data));
const updated = updater(data);
await tx.room.update({
where: { id: roomId },
data: { data: JSON.stringify(updated) },
});
await tx.room.update({
where: { id: roomId },
data: { data: JSON.stringify(updated) },
});
return updated;
});
return updated;
}),
);
}
+7 -1
View File
@@ -55,8 +55,14 @@ export function setCachedPreferences(prefs: UserPreferences): void {
localStorage.setItem("nowhatever_preferences", JSON.stringify(prefs));
}
export function logout(): void {
export async function logout(): Promise<void> {
if (typeof window === "undefined") return;
// Clear server-side auth cookie
try {
await fetch("/api/auth/logout", { method: "POST" });
} catch {
// Best-effort: cookie will expire anyway
}
localStorage.removeItem(PROFILE_KEY);
localStorage.removeItem("nowhatever_preferences");
const newId = crypto.randomUUID();