feat: add local auth billing and usage management

This commit is contained in:
inman committed 2026-08-12 12:13:06 +08:00
1 parent f642b5e71f
commit 196fdde83f
119 files changed
+15695 -2650

No files matched your search

+2 -8
View File
@@ -1,11 +1,5 @@
import { completeAuthorizationCallback, redirectToLoginWithError } from "@/lib/server/auth/oauth";
export const runtime = "nodejs";
import { NextResponse } from "next/server";
export async function GET(request: Request) {
try {
return await completeAuthorizationCallback(request);
} catch {
return redirectToLoginWithError(request, "callback_failed");
}
return NextResponse.redirect(new URL("/auth/login?error=callback_failed", request.url));
}
+3 -21
View File
@@ -1,25 +1,7 @@
import { getAuthRuntimeConfig } from "@/lib/auth/config";
import { jsonError } from "@/lib/server/api";
import { jsonOk } from "@/lib/server/api";
export const runtime = "nodejs";
export async function GET(request: Request) {
try {
const config = getAuthRuntimeConfig();
if (!config.authBaseUrl) throw new Error("认证中心地址未配置。");
const randomStr = new URL(request.url).searchParams.get("randomStr")?.trim();
if (!randomStr) throw new Error("randomStr is required.");
const response = await fetch(`${config.authBaseUrl}/code/image?randomStr=${encodeURIComponent(randomStr)}`, {
cache: "no-store"
});
if (!response.ok) throw new Error(`验证码获取失败:${response.status}`);
return new Response(new Uint8Array(await response.arrayBuffer()), {
headers: {
"Content-Type": response.headers.get("content-type") || "image/png",
"Cache-Control": "no-store"
}
});
} catch (error) {
return jsonError(error, 500);
}
export async function GET() {
return jsonOk({ enabled: false, message: "平台账号登录不使用外部验证码。" });
}
+2 -8
View File
@@ -1,11 +1,5 @@
import { createAuthorizeRedirect, redirectToLoginWithError } from "@/lib/server/auth/oauth";
export const runtime = "nodejs";
import { NextResponse } from "next/server";
export async function GET(request: Request) {
try {
return await createAuthorizeRedirect(request);
} catch {
return redirectToLoginWithError(request, "auth_not_configured");
}
return NextResponse.redirect(new URL("/auth/login", request.url));
}
+10 -3
View File
@@ -1,11 +1,18 @@
import { clearAuthCookies } from "@/lib/server/auth/oauth";
import { NextResponse } from "next/server";
import { clearPlatformSessionCookies } from "@/lib/server/auth/local";
export const runtime = "nodejs";
export async function GET(request: Request) {
return clearAuthCookies(request);
return logoutResponse(request);
}
export async function POST(request: Request) {
return clearAuthCookies(request);
return logoutResponse(request);
}
function logoutResponse(request: Request) {
const response = NextResponse.redirect(new URL("/auth/login?loggedOut=1", request.url));
clearPlatformSessionCookies(response, request.url);
return response;
}
+1
View File
@@ -11,6 +11,7 @@ export async function GET() {
authenticated: Boolean(session),
authRequired: config.required,
authConfigured: config.configured,
authMode: session?.authMode || null,
user: session?.user || null
});
}
+29
View File
@@ -0,0 +1,29 @@
import { jsonError, jsonOk, readJsonBody } from "@/lib/server/api";
import { requireAppSession } from "@/lib/server/auth/current-user";
import { changeOwnPassword } from "@/lib/server/account-store";
import { createPlatformSession, setPlatformSessionCookie } from "@/lib/server/auth/local";
export const runtime = "nodejs";
export async function POST(request: Request) {
try {
const session = await requireAppSession();
const body = await readJsonBody<Record<string, unknown>>(request);
const currentPassword = requiredString(body.currentPassword, "当前密码");
const newPassword = requiredString(body.newPassword, "新密码");
const confirmPassword = requiredString(body.confirmPassword, "确认密码");
if (newPassword !== confirmPassword) throw Object.assign(new Error("两次输入的新密码不一致。"), { status: 400 });
const user = await changeOwnPassword(session.user.id, currentPassword, newPassword);
const nextSession = await createPlatformSession(user);
const response = jsonOk({ ok: true, user: nextSession.user });
await setPlatformSessionCookie(response, request.url, nextSession);
return response;
} catch (error) {
return jsonError(error, 400, { request, source: "api.auth.password.change" });
}
}
function requiredString(value: unknown, label: string): string {
if (typeof value === "string" && value.trim()) return value.trim();
throw Object.assign(new Error(`${label}不能为空。`), { status: 400 });
}
+28 -117
View File
@@ -1,134 +1,45 @@
import { getAuthRuntimeConfig, safeNextPath } from "@/lib/auth/config";
import { createSessionCookieValue } from "@/lib/auth/session";
import { jsonError, jsonOk, readJsonBody } from "@/lib/server/api";
import { createSessionFromClaims, verifyAuthJwt } from "@/lib/server/auth/jwt";
import { prepareAuthPassword } from "@/lib/server/auth/password";
import { setSessionCookieValue } from "@/lib/server/auth/session-cookie";
import { authenticatePlatformUser } from "@/lib/server/account-store";
import {
checkIpLoginRateLimit,
clearIpLoginRateLimit,
clientIpFromRequest,
createPlatformSession,
setPlatformSessionCookie
} from "@/lib/server/auth/local";
export const runtime = "nodejs";
type PasswordTokenResponse = {
access_token?: string;
refresh_token?: string;
expires_in?: string | number;
token_type?: string;
error?: string;
error_description?: string;
msg?: string;
message?: string;
[key: string]: unknown;
};
export const dynamic = "force-dynamic";
export async function POST(request: Request) {
const ip = clientIpFromRequest(request);
try {
const body = await readJsonBody<{
username?: string;
password?: string;
password_encrypted?: boolean;
passwordEncrypted?: boolean;
code?: string;
randomStr?: string;
next?: string;
authMode?: string;
}>(request);
const config = getAuthRuntimeConfig({ clientMode: body.authMode === "admin" ? "admin" : "default" });
if (!config.configured || !config.tokenUrl || !config.clientSecret || !config.sessionSecret) {
throw new PasswordLoginError(`认证配置不完整:${config.missing.join(", ") || "未知配置"}`, 500);
const config = getAuthRuntimeConfig();
if (!config.configured || !config.sessionSecret) {
throw Object.assign(new Error(`账号认证配置不完整:${config.missing.join(", ") || "ZHINIAN_AUTH_SESSION_SECRET"}`), { status: 503 });
}
const username = body.username?.trim();
const password = body.password || "";
const code = body.code?.trim();
const randomStr = body.randomStr?.trim();
if (!username || !password) throw new PasswordLoginError("账号和密码不能为空。");
const token = await exchangePasswordToken({
tokenUrl: config.tokenUrl,
clientId: config.clientId,
clientSecret: config.clientSecret,
scope: config.scope,
tenantId: config.tenantId,
username,
password: prepareAuthPassword(password, {
passwordEncrypted: body.password_encrypted || body.passwordEncrypted,
passwordEncryptionKey: config.passwordEncryptionKey
}),
code,
randomStr
});
if (!token.access_token) throw new PasswordLoginError("认证中心没有返回 access_token。", 502);
const claims = await verifyAuthJwt(token.access_token, config);
const session = createSessionFromClaims(claims, config, parseExpiresIn(token.expires_in), {
accessToken: token.access_token,
tokenType: token.token_type
});
checkIpLoginRateLimit(ip);
const body = await readJsonBody<Record<string, unknown>>(request);
const phone = stringValue(body.phone) || stringValue(body.username);
const password = stringValue(body.password);
if (!phone || !password) throw Object.assign(new Error("手机号和密码不能为空。"), { status: 400 });
const user = await authenticatePlatformUser(phone, password);
clearIpLoginRateLimit(ip);
const session = await createPlatformSession(user);
const response = jsonOk({
ok: true,
redirectTo: safeNextPath(body.next),
user: session.user
redirectTo: safeNextPath(stringValue(body.next)),
user: session.user,
authMode: session.authMode
});
setSessionCookieValue(
response,
request.url,
await createSessionCookieValue(session, config.sessionSecret),
new Date(session.expiresAt * 1000)
);
await setPlatformSessionCookie(response, request.url, session);
return response;
} catch (error) {
return jsonError(error, 401);
return jsonError(error, 401, { request, source: "api.auth.password", logClientErrors: false });
}
}
async function exchangePasswordToken(input: {
tokenUrl: string;
clientId: string;
clientSecret: string;
scope: string;
tenantId?: string;
username: string;
password: string;
code?: string;
randomStr?: string;
}): Promise<PasswordTokenResponse> {
const form = new URLSearchParams();
form.set("grant_type", "password");
form.set("scope", input.scope);
form.set("username", input.username);
form.set("password", input.password);
if (input.tenantId) form.set("tenantId", input.tenantId);
if (input.code) form.set("code", input.code);
if (input.randomStr) form.set("randomStr", input.randomStr);
const headers: Record<string, string> = {
Authorization: `Basic ${Buffer.from(`${input.clientId}:${input.clientSecret}`).toString("base64")}`,
"Content-Type": "application/x-www-form-urlencoded"
};
if (input.tenantId) headers.tenantId = input.tenantId;
const response = await fetch(input.tokenUrl, {
method: "POST",
headers,
body: form
});
const payload = await response.json().catch(() => ({})) as PasswordTokenResponse;
if (!response.ok) {
throw new PasswordLoginError(payload.error_description || payload.msg || payload.message || payload.error || "登录失败。", response.status);
}
return payload;
}
function parseExpiresIn(value: string | number | undefined): number | undefined {
if (typeof value === "number" && Number.isFinite(value)) return value;
if (typeof value === "string" && value.trim()) {
const parsed = Number(value);
if (Number.isFinite(parsed)) return parsed;
}
return undefined;
}
class PasswordLoginError extends Error {
status: number;
constructor(message: string, status = 400) {
super(message);
this.name = "PasswordLoginError";
this.status = status;
}
function stringValue(value: unknown): string | undefined {
return typeof value === "string" && value.trim() ? value.trim() : undefined;
}