fix: harden secrets and session checks

This commit is contained in:
JetSprow
2026-04-29 17:18:36 +10:00
parent 69be1d6fcc
commit 58fa4fefa4
44 changed files with 454 additions and 154 deletions

View File

@@ -6,16 +6,23 @@ import { requireAdmin } from "@/lib/require-auth";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { actorFromSession, recordAuditLog } from "@/services/audit";
import { encrypt } from "@/lib/crypto";
import { encrypt, isEncryptedValue } from "@/lib/crypto";
import { testAndSyncNodeInbounds } from "@/services/node-panel/sync-inbounds";
const nodeSchema = z.object({
const nodeBaseSchema = z.object({
name: z.string().trim().optional(),
panelUrl: z.string().trim().min(1, "3x-ui 面板地址必填"),
panelUsername: z.string().trim().min(1, "3x-ui 用户名必填"),
});
const createNodeSchema = nodeBaseSchema.extend({
panelPassword: z.string().trim().min(1, "3x-ui 密码必填"),
});
const updateNodeSchema = nodeBaseSchema.extend({
panelPassword: z.string().trim().optional(),
});
function normalizePanelUrl(raw: string): string {
try {
let value = raw.trim();
@@ -34,24 +41,26 @@ function normalizePanelUrl(raw: string): string {
}
}
function parseNodeData(formData: FormData) {
const raw = nodeSchema.parse(Object.fromEntries(formData));
function parseNodeData(formData: FormData, mode: "create" | "update") {
const raw = (mode === "create" ? createNodeSchema : updateNodeSchema)
.parse(Object.fromEntries(formData));
const panelUrl = normalizePanelUrl(raw.panelUrl);
const panel = new URL(panelUrl);
const panelPassword = raw.panelPassword?.trim();
const name = (raw.name || "").trim() || `节点-${panel.hostname}`;
return {
name,
panelUrl,
panelUsername: raw.panelUsername,
panelPassword: raw.panelPassword,
...(panelPassword ? { panelPassword: encrypt(panelPassword) } : {}),
panelType: "3x-ui",
};
}
export async function createNode(formData: FormData) {
const session = await requireAdmin();
const data = parseNodeData(formData);
const data = parseNodeData(formData, "create");
const node = await prisma.nodeServer.create({ data });
const result = await testAndSyncNodeInbounds(node);
@@ -72,7 +81,18 @@ export async function createNode(formData: FormData) {
export async function updateNode(id: string, formData: FormData) {
const session = await requireAdmin();
const data = parseNodeData(formData);
const data = parseNodeData(formData, "update");
if (!data.panelPassword) {
const existing = await prisma.nodeServer.findUnique({
where: { id },
select: { panelPassword: true },
});
if (existing?.panelPassword && !isEncryptedValue(existing.panelPassword)) {
data.panelPassword = encrypt(existing.panelPassword);
}
}
const node = await prisma.nodeServer.update({ where: { id }, data });
const result = await testAndSyncNodeInbounds(node);

View File

@@ -4,8 +4,10 @@ import { prisma } from "@/lib/prisma";
import { requireAdmin } from "@/lib/require-auth";
import { revalidatePath } from "next/cache";
import {
decryptPaymentConfigForUse,
normalizePaymentConfig,
parsePaymentConfig,
preparePaymentConfigForStorage,
} from "@/services/payment/catalog";
import { actorFromSession, recordAuditLog } from "@/services/audit";
import { z } from "zod";
@@ -18,11 +20,19 @@ export async function savePaymentConfig(
const session = await requireAdmin();
const normalizedConfig = normalizePaymentConfig(config);
let finalConfig = normalizedConfig as Record<string, string | number>;
const current = await prisma.paymentConfig.findUnique({
where: { provider },
select: { config: true },
});
const storageConfig = preparePaymentConfigForStorage(
provider,
normalizedConfig,
current?.config as Record<string, unknown> | undefined,
);
if (enabled) {
try {
finalConfig = parsePaymentConfig(provider, normalizedConfig) as Record<string, string | number>;
parsePaymentConfig(provider, decryptPaymentConfigForUse(provider, storageConfig));
} catch (error) {
if (error instanceof z.ZodError) {
const messages = error.issues.map((e) => e.message).join("");
@@ -32,7 +42,7 @@ export async function savePaymentConfig(
}
}
const jsonConfig = JSON.parse(JSON.stringify(finalConfig));
const jsonConfig = JSON.parse(JSON.stringify(storageConfig));
await prisma.paymentConfig.upsert({
where: { provider },

View File

@@ -8,7 +8,7 @@ import { requireAdmin } from "@/lib/require-auth";
import { actorFromSession, recordAuditLog } from "@/services/audit";
import { getAppConfig } from "@/services/app-config";
import { normalizeSiteUrl } from "@/services/site-url";
import { encrypt } from "@/lib/crypto";
import { encrypt, isEncryptedValue } from "@/lib/crypto";
import { getErrorMessage } from "@/lib/errors";
import { sendSmtpTestEmail } from "@/services/email";
@@ -100,6 +100,17 @@ function buildSettingsUpdate(parsed: z.infer<typeof settingsSchema>, current: Aw
const smtpPassword = parsed.smtpPassword?.trim()
? encrypt(parsed.smtpPassword.trim())
: current.smtpPassword;
const turnstileSiteKey = parsed.turnstileSiteKey || null;
const currentTurnstileSecret = current.turnstileSecretKey
? isEncryptedValue(current.turnstileSecretKey)
? current.turnstileSecretKey
: encrypt(current.turnstileSecretKey)
: null;
const turnstileSecretKey = parsed.turnstileSecretKey?.trim()
? encrypt(parsed.turnstileSecretKey.trim())
: turnstileSiteKey
? currentTurnstileSecret
: null;
const next = {
siteName: parsed.siteName,
@@ -150,8 +161,8 @@ function buildSettingsUpdate(parsed: z.infer<typeof settingsSchema>, current: Aw
inviteRewardEnabled: optionalBoolean(parsed.inviteRewardEnabled, current.inviteRewardEnabled),
inviteRewardRate: parsed.inviteRewardRate ?? Number(current.inviteRewardRate),
inviteRewardCouponId: parsed.inviteRewardCouponId || null,
turnstileSiteKey: parsed.turnstileSiteKey || null,
turnstileSecretKey: parsed.turnstileSecretKey || null,
turnstileSiteKey,
turnstileSecretKey,
smtpEnabled,
smtpHost: parsed.smtpHost || null,
smtpPort: parsed.smtpPort ?? current.smtpPort,

View File

@@ -1,8 +1,13 @@
import type { Prisma } from "@prisma/client";
import { prisma } from "@/lib/prisma";
import { notFound } from "next/navigation";
import { sanitizeInboundSettings, sanitizeStreamSettings } from "@/services/node-inbound-sanitize";
const nodeDetailInclude = {
const nodeDetailSelect = {
id: true,
name: true,
panelUrl: true,
status: true,
inbounds: {
where: { isActive: true },
orderBy: { updatedAt: "desc" },
@@ -12,17 +17,25 @@ const nodeDetailInclude = {
},
},
},
} satisfies Prisma.NodeServerInclude;
} satisfies Prisma.NodeServerSelect;
export type NodeDetail = Prisma.NodeServerGetPayload<{
include: typeof nodeDetailInclude;
select: typeof nodeDetailSelect;
}>;
export async function getNodeDetail(id: string): Promise<NodeDetail> {
const node = await prisma.nodeServer.findUnique({
where: { id },
include: nodeDetailInclude,
select: nodeDetailSelect,
});
if (!node) notFound();
return node;
return {
...node,
inbounds: node.inbounds.map((inbound) => ({
...inbound,
settings: sanitizeInboundSettings(inbound.settings),
streamSettings: sanitizeStreamSettings(inbound.streamSettings),
})),
};
}

View File

@@ -60,7 +60,6 @@ function NodeCard({ node, siteUrl }: { node: NodeServerRow; siteUrl: string | nu
name: node.name,
panelUrl: node.panelUrl,
panelUsername: node.panelUsername,
panelPassword: node.panelPassword,
}}
triggerLabel="编辑"
triggerVariant="outline"

View File

@@ -22,7 +22,6 @@ interface NodeFormValue {
name: string;
panelUrl: string | null;
panelUsername: string | null;
panelPassword: string | null;
}
export function NodeForm({
@@ -92,7 +91,13 @@ export function NodeForm({
</div>
<div>
<Label></Label>
<Input name="panelPassword" type="password" defaultValue={node?.panelPassword ?? ""} required />
<Input
name="panelPassword"
type="password"
placeholder={isEdit ? "留空则沿用当前密码" : "请输入面板密码"}
required={!isEdit}
autoComplete="new-password"
/>
</div>
</div>

View File

@@ -2,8 +2,15 @@ import type { Prisma } from "@prisma/client";
import { prisma } from "@/lib/prisma";
import { parsePage } from "@/lib/utils";
import { getConfiguredSiteUrl } from "@/services/site-url";
import { sanitizeInboundSettings } from "@/services/node-inbound-sanitize";
const nodeInclude = {
const nodeSelect = {
id: true,
name: true,
panelUrl: true,
panelUsername: true,
status: true,
agentToken: true,
_count: { select: { inbounds: true } },
inbounds: {
where: { isActive: true },
@@ -16,10 +23,10 @@ const nodeInclude = {
},
orderBy: { updatedAt: "desc" },
},
} satisfies Prisma.NodeServerInclude;
} satisfies Prisma.NodeServerSelect;
export type NodeServerRow = Prisma.NodeServerGetPayload<{
include: typeof nodeInclude;
select: typeof nodeSelect;
}>;
export async function getNodeServers(
@@ -44,7 +51,7 @@ export async function getNodeServers(
const [nodes, total, siteUrl] = await Promise.all([
prisma.nodeServer.findMany({
where,
include: nodeInclude,
select: nodeSelect,
orderBy: { createdAt: "desc" },
skip,
take: pageSize,
@@ -53,5 +60,14 @@ export async function getNodeServers(
getConfiguredSiteUrl(),
]);
return { nodes, total, page, pageSize, filters: { q, status }, siteUrl };
const safeNodes = nodes.map((node) => ({
...node,
agentToken: node.agentToken ? "configured" : null,
inbounds: node.inbounds.map((inbound) => ({
...inbound,
settings: sanitizeInboundSettings(inbound.settings),
})),
}));
return { nodes: safeNodes, total, page, pageSize, filters: { q, status }, siteUrl };
}

View File

@@ -22,10 +22,17 @@ interface Props {
provider: string;
fields: Field[];
currentConfig?: Record<string, string>;
secretConfigured?: Record<string, boolean>;
enabled: boolean;
}
export function PaymentConfigForm({ provider, fields, currentConfig, enabled: initialEnabled }: Props) {
export function PaymentConfigForm({
provider,
fields,
currentConfig,
secretConfigured = {},
enabled: initialEnabled,
}: Props) {
const [enabled, setEnabled] = useState(initialEnabled);
const [saving, setSaving] = useState(false);
@@ -65,6 +72,13 @@ export function PaymentConfigForm({ provider, fields, currentConfig, enabled: in
try {
await savePaymentConfig(provider, config, enabled);
for (const field of fields) {
if (!field.secret) continue;
const input = e.currentTarget.elements.namedItem(field.key);
if (input instanceof HTMLInputElement) {
input.value = "";
}
}
toast.success("保存成功");
} catch (error) {
toast.error(getErrorMessage(error, "保存失败"));
@@ -99,8 +113,8 @@ export function PaymentConfigForm({ provider, fields, currentConfig, enabled: in
<Input
name={field.key}
type={field.secret ? "password" : "text"}
placeholder={field.placeholder}
defaultValue={currentConfig?.[field.key] || ""}
placeholder={field.secret && secretConfigured[field.key] ? "留空保持不变" : field.placeholder}
defaultValue={field.secret ? "" : currentConfig?.[field.key] || ""}
/>
</div>
),

View File

@@ -20,7 +20,7 @@ export default async function PaymentsPage() {
title="支付配置"
/>
<div className="grid gap-5">
{providerConfigs.map(({ provider, config }) => (
{providerConfigs.map(({ provider, config, secretConfigured }) => (
<section key={provider.id} className="surface-card overflow-hidden rounded-xl p-4">
<div className="mb-4 flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
<div className="flex items-start gap-3">
@@ -37,7 +37,8 @@ export default async function PaymentsPage() {
<PaymentConfigForm
provider={provider.id}
fields={provider.fields}
currentConfig={config?.config as Record<string, string> | undefined}
currentConfig={config?.config}
secretConfigured={secretConfigured}
enabled={config?.enabled ?? false}
/>
</section>

View File

@@ -1,12 +1,29 @@
import { prisma } from "@/lib/prisma";
import { PAYMENT_PROVIDER_DEFINITIONS } from "@/services/payment/catalog";
import {
getPaymentSecretConfiguredState,
PAYMENT_PROVIDER_DEFINITIONS,
redactPaymentConfigForClient,
} from "@/services/payment/catalog";
export async function getPaymentProviderConfigs() {
const configs = await prisma.paymentConfig.findMany();
const configMap = new Map(configs.map((config) => [config.provider, config]));
return PAYMENT_PROVIDER_DEFINITIONS.map((provider) => ({
provider,
config: configMap.get(provider.id),
}));
return PAYMENT_PROVIDER_DEFINITIONS.map((provider) => {
const config = configMap.get(provider.id);
const configValue = config?.config as Record<string, unknown> | undefined;
return {
provider,
config: config
? {
enabled: config.enabled,
config: redactPaymentConfigForClient(provider.id, configValue ?? {}),
}
: null,
secretConfigured: configValue
? getPaymentSecretConfiguredState(provider.id, configValue)
: {},
};
});
}

View File

@@ -52,7 +52,7 @@ export default async function AdminSettingsPage() {
inviteRewardRate: Number(config.inviteRewardRate),
inviteRewardCouponId: config.inviteRewardCouponId,
turnstileSiteKey: config.turnstileSiteKey,
turnstileSecretKey: config.turnstileSecretKey,
turnstileSecretConfigured: Boolean(config.turnstileSecretKey),
smtpEnabled: config.smtpEnabled,
smtpHost: config.smtpHost,
smtpPort: config.smtpPort,

View File

@@ -41,7 +41,7 @@ interface AppConfig {
inviteRewardRate: number;
inviteRewardCouponId: string | null;
turnstileSiteKey: string | null;
turnstileSecretKey: string | null;
turnstileSecretConfigured: boolean;
smtpEnabled: boolean;
smtpHost: string | null;
smtpPort: number;
@@ -123,6 +123,11 @@ export function SettingsForm({ config, coupons }: { config: AppConfig; coupons:
if (password instanceof HTMLInputElement) {
password.value = "";
}
const turnstileSecret = form.elements.namedItem("turnstileSecretKey");
if (turnstileSecret instanceof HTMLInputElement) {
turnstileSecret.value = "";
}
}
return (
@@ -553,7 +558,16 @@ export function SettingsForm({ config, coupons }: { config: AppConfig; coupons:
</div>
<div className="space-y-2">
<Label htmlFor="turnstileSecretKey">Secret Key</Label>
<Input id="turnstileSecretKey" name="turnstileSecretKey" type="password" defaultValue={config.turnstileSecretKey ?? ""} placeholder="0x4AAAAAAA..." />
<Input
id="turnstileSecretKey"
name="turnstileSecretKey"
type="password"
placeholder={config.turnstileSecretConfigured ? "留空保持不变" : "0x4AAAAAAA..."}
autoComplete="new-password"
/>
{config.turnstileSecretConfigured && (
<p className="text-xs leading-5 text-muted-foreground">Secret Key Site Key Turnstile</p>
)}
</div>
</div>
</section>

View File

@@ -1,5 +1,6 @@
import Link from "next/link";
import type { SubscriptionRiskEvent } from "@prisma/client";
import { ChevronDown } from "lucide-react";
import {
SubscriptionStatusBadge,
SubscriptionTypeBadge,
@@ -155,60 +156,97 @@ function ReviewState({ event }: { event: SubscriptionRiskEventRow }) {
);
}
function RiskEventCard({ event }: { event: SubscriptionRiskEventRow }) {
function RiskStat({ label, value }: { label: string; value: string | number }) {
return (
<article className="surface-card overflow-hidden rounded-xl">
<div className="grid xl:grid-cols-[minmax(0,0.9fr)_minmax(25rem,1.2fr)_minmax(18rem,0.65fr)]">
<section className="space-y-5 p-5">
<span className="min-w-0 rounded-lg border border-border/70 bg-muted/20 px-2.5 py-1.5">
<span className="block text-[0.68rem] leading-none text-muted-foreground">{label}</span>
<span className="mt-1 block truncate font-mono text-sm font-semibold leading-none">{value}</span>
</span>
);
}
function RiskEventCard({ event }: { event: SubscriptionRiskEventRow }) {
const summary = event.geoSummary;
const userLabel = event.user?.email ?? "未知用户";
const scopeLabel = event.subscription?.plan.name ?? "总订阅";
return (
<details className="surface-card group overflow-hidden rounded-xl">
<summary className="flex cursor-pointer list-none items-start gap-4 p-4 text-left [&::-webkit-details-marker]:hidden sm:p-5">
<div className="min-w-0 flex-1 space-y-3">
<div className="flex flex-wrap items-center gap-2">
<StatusBadge tone={event.level === "SUSPENDED" ? "danger" : "warning"}>
{reasonLabel(event.reason)}
</StatusBadge>
<StatusBadge tone="neutral">{kindLabel(event.kind)}</StatusBadge>
<StatusBadge tone={reviewStatusTone(event.reviewStatus)}>{reviewStatusLabel(event.reviewStatus)}</StatusBadge>
{event.userRestrictionActive && <StatusBadge tone="danger"></StatusBadge>}
{event.reportSentAt && <StatusBadge tone="info"></StatusBadge>}
<span className="text-xs text-muted-foreground">{formatDate(event.createdAt)}</span>
</div>
<div className="space-y-2">
<p className="text-sm font-semibold leading-6">{event.message}</p>
<p className="break-all font-mono text-xs text-muted-foreground"> IP{event.ip || "未知 IP"}</p>
</div>
<div className="grid gap-4 border-t border-border/60 pt-4 md:grid-cols-2 xl:grid-cols-1 2xl:grid-cols-2">
<div className="space-y-1">
<p className="text-xs font-medium text-muted-foreground"></p>
<UserBlock event={event} />
<div className="grid gap-3 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-end">
<div className="min-w-0 space-y-1.5">
<p className="line-clamp-2 text-sm font-semibold leading-6">{event.message}</p>
<p className="truncate text-xs text-muted-foreground">
{userLabel} · {scopeLabel} · IP{event.ip || "未知 IP"}
</p>
</div>
<div className="space-y-1">
<p className="text-xs font-medium text-muted-foreground"></p>
<EventScope event={event} />
<div className="grid grid-cols-4 gap-2 text-right sm:flex sm:justify-end">
<RiskStat label="国家" value={summary.uniqueCountryCount} />
<RiskStat label="省区" value={summary.uniqueRegionCount} />
<RiskStat label="城市" value={summary.uniqueCityCount} />
<RiskStat label="IP" value={summary.uniqueIpCount} />
</div>
</div>
</section>
</div>
<section className="border-y border-border/70 bg-muted/10 p-5 xl:border-x xl:border-y-0">
<SubscriptionRiskGeoDetails summary={event.geoSummary} />
</section>
<span className="mt-1 flex shrink-0 items-center gap-1.5 rounded-md border border-border bg-muted/30 px-2.5 py-1.5 text-xs font-medium text-muted-foreground transition-colors group-hover:text-foreground">
<span className="hidden sm:inline"></span>
<ChevronDown className="size-4 transition-transform group-open:rotate-180" />
</span>
</summary>
<aside className="space-y-5 p-5">
<div className="space-y-2">
<p className="text-xs font-medium text-muted-foreground"></p>
<ReviewState event={event} />
</div>
<div className="border-t border-border/60 pt-4">
<SubscriptionRiskReviewActions
eventId={event.id}
reviewStatus={event.reviewStatus}
canRestoreSubscription={event.canRestoreSubscription}
restorableSubscriptionCount={event.restorableSubscriptionCount}
riskReport={event.riskReport}
reportSentAt={event.reportSentAt}
userRestrictionActive={event.userRestrictionActive}
finalAction={event.finalAction}
/>
</div>
</aside>
<div className="border-t border-border/70">
<div className="grid xl:grid-cols-[minmax(0,0.85fr)_minmax(24rem,1.15fr)_minmax(18rem,0.7fr)]">
<section className="space-y-5 p-5">
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-1 2xl:grid-cols-2">
<div className="space-y-1">
<p className="text-xs font-medium text-muted-foreground"></p>
<UserBlock event={event} />
</div>
<div className="space-y-1">
<p className="text-xs font-medium text-muted-foreground"></p>
<EventScope event={event} />
</div>
</div>
</section>
<section className="border-y border-border/70 bg-muted/10 p-5 xl:border-x xl:border-y-0">
<SubscriptionRiskGeoDetails summary={summary} />
</section>
<aside className="space-y-5 p-5">
<div className="space-y-2">
<p className="text-xs font-medium text-muted-foreground"></p>
<ReviewState event={event} />
</div>
<div className="border-t border-border/60 pt-4">
<SubscriptionRiskReviewActions
eventId={event.id}
reviewStatus={event.reviewStatus}
canRestoreSubscription={event.canRestoreSubscription}
restorableSubscriptionCount={event.restorableSubscriptionCount}
riskReport={event.riskReport}
reportSentAt={event.reportSentAt}
userRestrictionActive={event.userRestrictionActive}
finalAction={event.finalAction}
/>
</div>
</aside>
</div>
</div>
</article>
</details>
);
}

View File

@@ -1,8 +1,7 @@
import type { Metadata } from "next";
import { Suspense } from "react";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { redirect } from "next/navigation";
import { getActiveSession } from "@/lib/require-auth";
import { AdminSidebar } from "@/components/admin/sidebar";
import { AdminMobileNav } from "@/components/admin/mobile-nav";
import { AnnouncementLoader } from "@/components/announcements/announcement-loader";
@@ -21,7 +20,7 @@ export default async function AdminLayout({
}: {
children: React.ReactNode;
}) {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
if (!session) {
redirect("/login");
}

View File

@@ -1,8 +1,7 @@
import type { Metadata } from "next";
import { Suspense } from "react";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { redirect } from "next/navigation";
import { getActiveSession } from "@/lib/require-auth";
import { AnnouncementLoader } from "@/components/announcements/announcement-loader";
import { PageTransition } from "@/components/shared/page-transition";
@@ -19,7 +18,7 @@ export default async function AuthLayout({
}: {
children: React.ReactNode;
}) {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
if (session) {
redirect(session.user.role === "ADMIN" ? "/admin/dashboard" : "/dashboard");
}

View File

@@ -1,7 +1,6 @@
import type { Metadata } from "next";
import { getServerSession } from "next-auth";
import { redirect } from "next/navigation";
import { authOptions } from "@/lib/auth";
import { getActiveSession } from "@/lib/require-auth";
import { getActiveSubscriptionRiskRestriction } from "@/services/subscription-risk-review";
export const metadata: Metadata = {
@@ -17,7 +16,7 @@ export default async function PaymentLayout({
}: {
children: React.ReactNode;
}) {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
if (!session) {
redirect("/login");

View File

@@ -1,6 +1,5 @@
import type { Metadata } from "next";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { getActiveSession } from "@/lib/require-auth";
import { PageHeader, PageShell } from "@/components/shared/page-shell";
import { AccountPanel } from "./account-panel";
import { getAccountPageData } from "./account-data";
@@ -12,7 +11,7 @@ export const metadata: Metadata = {
};
export default async function AccountPage() {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
const { user, siteNotice } = await getAccountPageData(session!.user.id);
return (

View File

@@ -1,8 +1,7 @@
import type { Metadata } from "next";
import { getActiveSession } from "@/lib/require-auth";
import Link from "next/link";
import { getServerSession } from "next-auth";
import { ShoppingBag, ShoppingCart } from "lucide-react";
import { authOptions } from "@/lib/auth";
import { EmptyState, PageHeader, PageShell } from "@/components/shared/page-shell";
import { buttonVariants } from "@/components/ui/button";
import { CartClient } from "./cart-client";
@@ -14,7 +13,7 @@ export const metadata: Metadata = {
};
export default async function CartPage() {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
const data = await getCartPageData(session!.user.id);
return (

View File

@@ -1,6 +1,5 @@
import type { Metadata } from "next";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { getActiveSession } from "@/lib/require-auth";
import { PageHeader, PageShell } from "@/components/shared/page-shell";
import { getDashboardData, getDashboardTrafficTrend } from "./dashboard-data";
import {
@@ -24,7 +23,7 @@ export const metadata: Metadata = {
};
export default async function UserDashboard() {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
const userId = session!.user.id;
const { activeSubs, pendingOrderCount, paidOrderCount, config } =

View File

@@ -1,8 +1,7 @@
import type { Metadata } from "next";
import { Suspense } from "react";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { redirect } from "next/navigation";
import { getActiveSession } from "@/lib/require-auth";
import { UserSidebar } from "@/components/user/sidebar";
import { UserMobileNav } from "@/components/user/mobile-nav";
import { AnnouncementLoader } from "@/components/announcements/announcement-loader";
@@ -24,7 +23,7 @@ export default async function UserLayout({
}: {
children: React.ReactNode;
}) {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
if (!session) {
redirect("/login");
}

View File

@@ -1,6 +1,5 @@
import type { Metadata } from "next";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { getActiveSession } from "@/lib/require-auth";
import { PageHeader, PageShell } from "@/components/shared/page-shell";
import { NotificationBulkAction } from "./notification-actions";
import { NotificationList } from "./_components/notification-list";
@@ -12,7 +11,7 @@ export const metadata: Metadata = {
};
export default async function NotificationsPage() {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
const { notifications, unreadCount, readCount } = await getUserNotifications(session!.user.id);
return (

View File

@@ -1,6 +1,5 @@
import type { Metadata } from "next";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { getActiveSession } from "@/lib/require-auth";
import { Pagination } from "@/components/shared/pagination";
import { PageHeader, PageShell } from "@/components/shared/page-shell";
import { UserOrdersTable } from "./_components/user-orders-table";
@@ -16,7 +15,7 @@ export default async function UserOrdersPage({
}: {
searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
const { orders, total, page, pageSize } = await getUserOrders({
userId: session!.user.id,
searchParams: await searchParams,

View File

@@ -1,9 +1,8 @@
import type { Metadata } from "next";
import { getActiveSession } from "@/lib/require-auth";
import Link from "next/link";
import { getServerSession } from "next-auth";
import { Film, LifeBuoy, Radio } from "lucide-react";
import { authOptions } from "@/lib/auth";
import { EmptyState, PageShell } from "@/components/shared/page-shell";
import { buttonVariants } from "@/components/ui/button";
import { PendingOrderBanner } from "./pending-order-banner";
@@ -30,7 +29,7 @@ export const metadata: Metadata = {
};
export default async function StorePage() {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
const { plans, availabilityMap, pendingOrder, latencyRecommendations } = await getStorePageData(session?.user.id);
const proxyPlans = getProxyPlans(plans);
const streamingPlans = getStreamingPlans(plans);

View File

@@ -1,8 +1,7 @@
import type { Metadata } from "next";
import { getActiveSession } from "@/lib/require-auth";
import { headers } from "next/headers";
import { notFound } from "next/navigation";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { PageHeader, PageShell, SectionHeader } from "@/components/shared/page-shell";
import { SubscriptionDetailCards } from "@/components/subscriptions/subscription-detail-cards";
import { SubscriptionTimelineSection } from "@/components/subscriptions/subscription-timeline-section";
@@ -22,7 +21,7 @@ export default async function UserSubscriptionDetailPage({
}: {
params: Promise<{ id: string }>;
}) {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
const { id } = await params;
const requestHeaders = await headers();
const [data, baseUrl] = await Promise.all([

View File

@@ -1,6 +1,5 @@
import type { Metadata } from "next";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { getActiveSession } from "@/lib/require-auth";
import { PageHeader, PageShell } from "@/components/shared/page-shell";
import {
getActiveSubscriptions,
@@ -22,7 +21,7 @@ export const metadata: Metadata = {
};
export default async function SubscriptionsPage() {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
const [subs, baseUrl] = await Promise.all([
getUserSubscriptions(session!.user.id),
getSubscriptionBaseUrl(),

View File

@@ -1,7 +1,6 @@
import type { Metadata } from "next";
import { getActiveSession } from "@/lib/require-auth";
import { notFound } from "next/navigation";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { PageHeader, PageShell } from "@/components/shared/page-shell";
import {
SupportTicketPriorityBadge,
@@ -23,7 +22,7 @@ export default async function SupportTicketDetailPage({
}: {
params: Promise<{ id: string }>;
}) {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
const { id } = await params;
const ticket = await getUserSupportTicketDetail({
ticketId: id,

View File

@@ -1,6 +1,5 @@
import type { Metadata } from "next";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { getActiveSession } from "@/lib/require-auth";
import { PageHeader, PageShell } from "@/components/shared/page-shell";
import { prisma } from "@/lib/prisma";
import { getAppConfig } from "@/services/app-config";
@@ -19,7 +18,7 @@ export default async function SupportPage({
}: {
searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
const resolvedSearchParams = await searchParams;
const riskEventId = typeof resolvedSearchParams.riskEventId === "string" ? resolvedSearchParams.riskEventId : "";
const [tickets, openTicketCount, config, riskEvent] = await Promise.all([

View File

@@ -7,6 +7,7 @@ import { verifyTurnstile } from "@/lib/turnstile";
import { rateLimit } from "@/lib/rate-limit";
import { getClientIp } from "@/lib/request-context";
import { isSmtpConfigured, normalizeEmailAddress, sendRegistrationVerificationEmail } from "@/services/email";
import { decryptIfEncrypted } from "@/lib/crypto";
const schema = z.object({
email: z.string().email("邮箱格式不正确"),
@@ -58,8 +59,11 @@ export async function POST(req: Request) {
);
}
if (config.turnstileSecretKey) {
if (!turnstileToken || !(await verifyTurnstile(turnstileToken, config.turnstileSecretKey))) {
const turnstileSecretKey = config.turnstileSecretKey
? decryptIfEncrypted(config.turnstileSecretKey)
: "";
if (turnstileSecretKey) {
if (!turnstileToken || !(await verifyTurnstile(turnstileToken, turnstileSecretKey))) {
return NextResponse.json({ error: "人机验证失败Turnstile token 缺失、已过期或校验未通过" }, { status: 403 });
}
}

View File

@@ -1,10 +1,9 @@
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { getActiveSession } from "@/lib/require-auth";
import { jsonError, jsonOk } from "@/lib/api-response";
import { getUserNotifications } from "@/app/(user)/notifications/notifications-data";
export async function GET() {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
if (!session) return jsonError("未登录", { status: 401 });
const data = await getUserNotifications(session.user.id);

View File

@@ -1,7 +1,6 @@
import { getServerSession } from "next-auth";
import { z } from "zod";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { getActiveSession } from "@/lib/require-auth";
import { jsonError, jsonOk } from "@/lib/api-response";
import { getPaymentAdapter } from "@/services/payment/factory";
import { rateLimit } from "@/lib/rate-limit";
@@ -28,7 +27,7 @@ function isSafePaymentUrl(value: string | undefined) {
export async function POST(req: Request) {
try {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
if (!session) {
return jsonError("未登录", { status: 401 });
}

View File

@@ -1,13 +1,12 @@
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { getActiveSession } from "@/lib/require-auth";
import { jsonError, jsonOk } from "@/lib/api-response";
export async function GET(
_req: Request,
{ params }: { params: Promise<{ orderId: string }> },
) {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
if (!session) {
return jsonError("未登录", { status: 401 });
}

View File

@@ -1,6 +1,5 @@
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { getActiveSession } from "@/lib/require-auth";
import { jsonError, jsonOk } from "@/lib/api-response";
import { getPaymentAdapter } from "@/services/payment/factory";
import { handleVerifiedPaymentSuccess } from "@/services/payment/process";
@@ -9,7 +8,7 @@ export async function GET(
_req: Request,
{ params }: { params: Promise<{ tradeNo: string }> }
) {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
if (!session) {
return jsonError("未登录", { status: 401 });
}

View File

@@ -1,12 +1,11 @@
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { getActiveSession } from "@/lib/require-auth";
import { prisma } from "@/lib/prisma";
export async function GET(
req: Request,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
if (!session) {
return new Response("附件访问失败:你尚未登录,请登录后重新打开附件", { status: 401 });
}

View File

@@ -1,7 +1,6 @@
import type { Metadata } from "next";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { redirect } from "next/navigation";
import { getActiveSession } from "@/lib/require-auth";
export const metadata: Metadata = {
title: "首页",
@@ -9,7 +8,7 @@ export const metadata: Metadata = {
};
export default async function Home() {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
if (!session) redirect("/login");
if (session.user.role === "ADMIN") redirect("/admin/dashboard");
redirect("/dashboard");

View File

@@ -1,9 +1,8 @@
import { getServerSession } from "next-auth";
import { authOptions } from "./auth";
import { jsonError } from "./api-response";
import { getActiveSession } from "./require-auth";
export async function requireAdminApiSession() {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
if (!session || session.user.role !== "ADMIN") {
return {
session: null,

View File

@@ -3,6 +3,7 @@ import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";
import { prisma } from "./prisma";
import { verifyTurnstile } from "./turnstile";
import { decryptIfEncrypted } from "./crypto";
export const authOptions: NextAuthOptions = {
providers: [
@@ -17,9 +18,12 @@ export const authOptions: NextAuthOptions = {
if (!credentials?.email || !credentials?.password) return null;
const config = await prisma.appConfig.findUnique({ where: { id: "default" } });
if (config?.turnstileSecretKey) {
const turnstileSecretKey = config?.turnstileSecretKey
? decryptIfEncrypted(config.turnstileSecretKey)
: "";
if (turnstileSecretKey) {
const token = credentials.turnstileToken;
if (!token || !(await verifyTurnstile(token, config.turnstileSecretKey))) {
if (!token || !(await verifyTurnstile(token, turnstileSecretKey))) {
return null;
}
}

View File

@@ -18,6 +18,22 @@ export function encrypt(text: string): string {
return `${iv.toString("hex")}:${authTag.toString("hex")}:${encrypted.toString("hex")}`;
}
function isHexBytes(value: string) {
return value.length > 0 && value.length % 2 === 0 && /^[0-9a-f]+$/i.test(value);
}
export function isEncryptedValue(data: string): boolean {
const parts = data.split(":");
if (parts.length !== 3) return false;
const [ivHex, authTagHex, encryptedHex] = parts;
return ivHex.length === 32
&& authTagHex.length === 32
&& isHexBytes(ivHex)
&& isHexBytes(authTagHex)
&& isHexBytes(encryptedHex);
}
export function decrypt(data: string): string {
const parts = data.split(":");
if (parts.length !== 3) {
@@ -28,3 +44,7 @@ export function decrypt(data: string): string {
decipher.setAuthTag(Buffer.from(authTagHex, "hex"));
return decipher.update(Buffer.from(encryptedHex, "hex")) + decipher.final("utf8");
}
export function decryptIfEncrypted(data: string): string {
return isEncryptedValue(data) ? decrypt(data) : data;
}

View File

@@ -1,9 +1,29 @@
import { getServerSession } from "next-auth";
import { authOptions } from "./auth";
import { prisma } from "./prisma";
import { getActiveSubscriptionRiskRestriction } from "@/services/subscription-risk-review";
export async function requireAdmin() {
export async function getActiveSession() {
const session = await getServerSession(authOptions);
if (!session?.user?.id) return null;
const user = await prisma.user.findUnique({
where: { id: session.user.id },
select: { id: true, email: true, name: true, role: true, status: true },
});
if (!user || user.status !== "ACTIVE") return null;
session.user.id = user.id;
session.user.email = user.email;
session.user.name = user.name;
session.user.role = user.role;
return session;
}
export async function requireAdmin() {
const session = await getActiveSession();
if (!session || session.user.role !== "ADMIN") {
throw new Error("无权限");
}
@@ -11,7 +31,7 @@ export async function requireAdmin() {
}
export async function requireAuth(options: { allowDuringRiskRestriction?: boolean } = {}) {
const session = await getServerSession(authOptions);
const session = await getActiveSession();
if (!session) {
throw new Error("未登录");
}

View File

@@ -242,13 +242,19 @@ export async function verifyEmailToken(token: string) {
if (record.purpose === "REGISTRATION_VERIFY") {
if (!record.userId) return { ok: false as const, message: "验证链接缺少账户信息" };
await prisma.user.update({
where: { id: record.userId },
const result = await prisma.user.updateMany({
where: {
id: record.userId,
status: { in: ["PENDING_EMAIL", "ACTIVE"] },
},
data: {
emailVerifiedAt: new Date(),
status: "ACTIVE",
},
});
if (result.count !== 1) {
return { ok: false as const, message: "账户当前状态不允许完成验证,请联系管理员" };
}
return { ok: true as const, message: "邮箱验证完成,现在可以登录账户。" };
}

View File

@@ -0,0 +1,28 @@
function asRecord(value: unknown): Record<string, unknown> | null {
return value && typeof value === "object" && !Array.isArray(value)
? value as Record<string, unknown>
: null;
}
function stringValue(value: unknown) {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
export function sanitizeInboundSettings(settings: unknown) {
const record = asRecord(settings);
const displayName = stringValue(record?.displayName);
return displayName ? { displayName } : {};
}
export function sanitizeStreamSettings(streamSettings: unknown) {
const record = asRecord(streamSettings);
if (!record) return null;
const network = stringValue(record.network);
const security = stringValue(record.security);
const sanitized: Record<string, string> = {};
if (network) sanitized.network = network;
if (security) sanitized.security = security;
return Object.keys(sanitized).length > 0 ? sanitized : null;
}

View File

@@ -1,8 +1,11 @@
import type { NodeServer } from "@prisma/client";
import { decryptIfEncrypted } from "@/lib/crypto";
import type { NodePanelAdapter } from "./adapter";
import { ThreeXUIAdapter } from "./three-x-ui";
export function createPanelAdapter(server: NodeServer): NodePanelAdapter {
type PanelServerConfig = Pick<NodeServer, "name" | "panelType" | "panelUrl" | "panelUsername" | "panelPassword">;
export function createPanelAdapter(server: PanelServerConfig): NodePanelAdapter {
const panelType = server.panelType ?? "3x-ui";
if (panelType !== "3x-ui") {
throw new Error(`节点 ${server.name} 面板类型不支持:${panelType},当前仅支持 3x-ui`);
@@ -10,5 +13,9 @@ export function createPanelAdapter(server: NodeServer): NodePanelAdapter {
if (!server.panelUrl || !server.panelUsername || !server.panelPassword) {
throw new Error(`节点 ${server.name} 未配置 3x-ui 面板信息`);
}
return new ThreeXUIAdapter(server.panelUrl, server.panelUsername, server.panelPassword);
return new ThreeXUIAdapter(
server.panelUrl,
server.panelUsername,
decryptIfEncrypted(server.panelPassword),
);
}

View File

@@ -1,4 +1,5 @@
import { z } from "zod";
import { decryptIfEncrypted, encrypt, isEncryptedValue } from "@/lib/crypto";
export interface PaymentConfigField {
key: string;
@@ -107,6 +108,78 @@ function normalizeConfig(config: Record<string, unknown>): Record<string, string
);
}
function getSecretFieldKeys(provider: string) {
return new Set(
(getPaymentProviderDefinition(provider)?.fields ?? [])
.filter((field) => field.secret)
.map((field) => field.key),
);
}
export function decryptPaymentConfigForUse(
provider: string,
config: Record<string, unknown>,
): Record<string, string> {
const normalized = normalizeConfig(config);
const secretKeys = getSecretFieldKeys(provider);
for (const key of secretKeys) {
if (normalized[key]) {
normalized[key] = decryptIfEncrypted(normalized[key]);
}
}
return normalized;
}
export function preparePaymentConfigForStorage(
provider: string,
incomingConfig: Record<string, unknown>,
currentConfig?: Record<string, unknown> | null,
): Record<string, string> {
const normalized = normalizeConfig(incomingConfig);
const current = currentConfig ? normalizeConfig(currentConfig) : {};
const secretKeys = getSecretFieldKeys(provider);
for (const key of secretKeys) {
const nextSecret = normalized[key]?.trim();
const currentSecret = current[key]?.trim();
if (nextSecret) {
normalized[key] = encrypt(nextSecret);
} else if (currentSecret) {
normalized[key] = isEncryptedValue(currentSecret) ? currentSecret : encrypt(currentSecret);
} else {
normalized[key] = "";
}
}
return normalized;
}
export function redactPaymentConfigForClient(
provider: string,
config: Record<string, unknown>,
): Record<string, string> {
const normalized = normalizeConfig(config);
for (const key of getSecretFieldKeys(provider)) {
normalized[key] = "";
}
return normalized;
}
export function getPaymentSecretConfiguredState(
provider: string,
config: Record<string, unknown>,
): Record<string, boolean> {
const normalized = normalizeConfig(config);
const result: Record<string, boolean> = {};
for (const key of getSecretFieldKeys(provider)) {
result[key] = Boolean(normalized[key]);
}
return result;
}
export function getPaymentProviderDefinition(provider: string) {
return PAYMENT_PROVIDER_DEFINITIONS.find((item) => item.id === provider) ?? null;
}

View File

@@ -4,6 +4,7 @@ import { EasyPayAdapter, type EasyPayConfig } from "./epay";
import { AlipayF2FAdapter, type AlipayF2FConfig } from "./alipay-f2f";
import { UsdtTrc20Adapter, type UsdtTrc20Config } from "./usdt-trc20";
import {
decryptPaymentConfigForUse,
getPaymentProviderName,
parsePaymentConfig,
} from "./catalog";
@@ -22,7 +23,7 @@ export async function getPaymentAdapter(provider: string): Promise<PaymentAdapte
const cfg = parsePaymentConfig(
realProvider,
config.config as Record<string, string>,
decryptPaymentConfigForUse(realProvider, config.config as Record<string, unknown>),
);
switch (realProvider) {

View File

@@ -98,9 +98,9 @@ export function buildSubscriptionUserInfo(stats: SubscriptionTrafficStats | null
}
function getAggregateSubscriptionSecret() {
const secret = process.env.NEXTAUTH_SECRET ?? process.env.AUTH_SECRET ?? process.env.DATABASE_URL;
const secret = process.env.NEXTAUTH_SECRET ?? process.env.AUTH_SECRET;
if (!secret) {
throw new Error("缺少订阅链接签名密钥,请配置 NEXTAUTH_SECRET");
throw new Error("缺少订阅链接签名密钥,请配置 NEXTAUTH_SECRET 或 AUTH_SECRET");
}
return secret;
}