Speed up terminal auth snapshot loading

This commit is contained in:
2569718930@qq.com
2026-05-30 21:08:19 +08:00
parent d9eea721ef
commit 52f92d8650
2 changed files with 39 additions and 2 deletions
+33 -2
View File
@@ -21,7 +21,10 @@ import {
buildSubscriptionRequiredAuthProfile,
isSubscriptionRequiredBackendResponse,
} from "@/lib/auth-profile-proxy";
import { hasSupabaseServerEnv } from "@/lib/supabase/server";
import {
hasSupabaseServerEnv,
hasSupabaseSessionCookieValues,
} from "@/lib/supabase/server";
const API_BASE = process.env.POLYWEATHER_API_BASE_URL;
@@ -171,6 +174,15 @@ function applyEntitlementSnapshotFromAuthPayload(
return response;
}
function hasRequestSupabaseSessionCookie(req: NextRequest) {
return hasSupabaseSessionCookieValues(
req.cookies.getAll().map((item) => ({
name: item.name,
value: item.value,
})),
);
}
export async function GET(req: NextRequest) {
const requestHost =
req.headers.get("x-forwarded-host") || req.headers.get("host") || req.nextUrl.host;
@@ -190,9 +202,28 @@ export async function GET(req: NextRequest) {
);
}
const preferSnapshot = req.nextUrl.searchParams.get("prefer_snapshot") === "1";
if (
preferSnapshot &&
!req.headers.get("authorization") &&
hasRequestSupabaseSessionCookie(req)
) {
const snapshotPayload = entitlementSnapshotToAuthPayload(
readEntitlementSnapshot(req),
);
if (snapshotPayload) {
return NextResponse.json(
{
...snapshotPayload,
entitlement_snapshot_reason: "prefer_snapshot_fast_path",
},
{ headers: { "Cache-Control": "no-store" } },
);
}
}
let auth: Awaited<ReturnType<typeof buildBackendRequestHeaders>> | null = null;
let bearerIdentity: VerifiedBearerIdentity | null | undefined;
const preferSnapshot = req.nextUrl.searchParams.get("prefer_snapshot") === "1";
const getBearerIdentityOnce = async () => {
if (bearerIdentity !== undefined) return bearerIdentity;
bearerIdentity = await getVerifiedBearerIdentity(req);
@@ -302,6 +302,12 @@ export function runTests() {
authMeRouteSource.indexOf("await fetch(`${API_BASE}/api/auth/me`"),
"auth profile proxy must return unauthenticated locally for no-session Supabase requests instead of forwarding the backend entitlement token",
);
assert(
authMeRouteSource.includes('reason: "prefer_snapshot_fast_path"') &&
authMeRouteSource.indexOf('reason: "prefer_snapshot_fast_path"') <
authMeRouteSource.indexOf("buildBackendRequestHeaders(req)"),
"auth profile proxy must return a valid entitlement snapshot before reading Supabase session cookies on terminal cold start",
);
assert(
backendAuthSource.includes("if (incomingAuth) {") &&
backendAuthSource.indexOf("if (incomingAuth) {") <