Untitled

Anonymous
TypeScript
11/17/2026 8:08 AM
8.0 KB
19
Indexable
Never
import { NextRequest, NextResponse } from "next/server";
import createMiddleware from "next-intl/middleware";
import { isPrivatePaymentPath, PRIVATE_LINK_HEADERS } from "./lib/payment-link-privacy.mjs";
import { routing, type Locale } from "./i18n/routing";
import { serverReceipt, TRACE_HEADER } from "./components/navigation/navigation-diagnostics.mjs";
import {
  matchNotificationOpenPath,
  notificationOpenPath,
} from "./lib/appNotificationLinks";

import { safeAuthReturnPath, safeOAuthReturnPath } from "./lib/authReturnPath";

const publicPages = [
  "/auth/sign-up",
  "/auth/sign-in",
  "/auth/forgot-password",
  "/auth/reset-password",
  "/signin",
  // Staff arrive here from a one-time link and have no session yet, so this
  // must stay reachable while unauthenticated.
  "/auth/staff-set-password/.*",
  "/i/.*",
  "/gym/.*",
  "/setup/.*",
  "/onboarding",
  "/pay/[^/]+",
  "/legal/.*",
];

// Function to check if the path should skip internationalization
function shouldSkipInternationalization(path: string): boolean {
  const pwaFiles = [
    "/sw.js",
    "/manifest.json",
    "/swe-worker-development.js",
    "/workbox-",
    "/precache-manifest",
    "/newlogo/",
    "/fonts/",
    "/icons/",
    "/icon.png",
    "/favicon-",
    "icons/icon-192.png",
    "icons/icon-512.png",
    "icons/icon-384.png",
  ];

  return pwaFiles.some((file) => path.includes(file));
}

/**
 * Bare /auth/* (no locale): redirect cleanly to default locale
 */
const BARE_AUTH_PATH =
  /^\/auth\/(sign-in|sign-up|forgot-password|reset-password)\/?$/i;

const intlMiddleware = createMiddleware({
  ...routing,
});

const authEntryPages = [
  "/auth/sign-in",
  "/auth/sign-up",
  "/auth/sign-up-dance",
  "/auth/sign-up-library",
  "/auth/forgot-password",
  "/auth/reset-password",
  "/signin",
];

const authEntryPathnameRegex = RegExp(
  `^(/(${[...routing.locales].join("|")}))?(${authEntryPages
    .flatMap((p) => (p === "/" ? ["", "/"] : p))
    .join("|")})/?$`,
  "i",
);

export default function middleware(req: NextRequest) {
  const url = req.nextUrl;
  const path = url.pathname;
  const token = req.cookies.get("refreshToken")?.value;
  // Normal RSC traffic still skips middleware. Only an explicitly traced RSC
  // matches the extra entry. Next strips the RSC header before invoking us.
  // Require the existing session gate as well: a forged diagnostic header on
  // a document must never bypass sign-in or bare-path locale handling.
  if (req.headers.has(TRACE_HEADER)) {
    try {
      const receipt = serverReceipt(req.url, url.origin, req.method, req.headers, !!token);
      if (receipt) {
        const response = NextResponse.next();
        response.headers.set(TRACE_HEADER, receipt.id);
        // Production removes log/info calls. Keep this opt-in structured
        // receipt on the retained sink; it is not an application error.
        try { console.warn(JSON.stringify(receipt)); } catch { /* Best-effort log sink. */ }
        return response;
      }
    } catch { /* Diagnostics must not fail a page request. */ }
  }

  // Public QR documents are served directly, without an owner session, locale
  // redirect or the authenticated app shell/analytics.
  if (/^\/qr\/(?:card|(?:check-in|staff)\/[^/]+)\/?$/.test(path)) {
    return NextResponse.next();
  }

  // Skip for chrome-specific paths
  if (path.indexOf("chrome") > -1) {
    return NextResponse.next();
  }

  // Skip internationalization for PWA files
  if (shouldSkipInternationalization(path)) {
    return NextResponse.next();
  }

  // If user is already authenticated and visits an auth entry page (sign-in, sign-up, etc.), redirect to dashboard
  if (token && authEntryPathnameRegex.test(path) &&
      !(path.endsWith("/auth/sign-in") && url.searchParams.get("session_expired") === "1")) {
    const pathLocale = path.split("/")[1];
    const isValidLocale = (locale: string): locale is Locale =>
      routing.locales.includes(locale as Locale);

    const locale = isValidLocale(pathLocale)
      ? pathLocale
      : routing.defaultLocale;

    // Signed in meanwhile (another tab): go on to the notification sign-in
    // was asked to return to, or the explicitly allowlisted OAuth consent page.
    const returnPath = safeAuthReturnPath(url.searchParams.get("next"));
    return NextResponse.redirect(
      new URL(returnPath || `/${locale}/dashboard`, req.url),
    );
  }

  // --- Bare auth paths: redirect to default locale ---
  const bareAuth = path.match(BARE_AUTH_PATH);
  if (bareAuth) {
    const authSegment = bareAuth[1].toLowerCase();
    const destination = new URL(`/${routing.defaultLocale}/auth/${authSegment}`, req.url);
    destination.search = url.search;
    return NextResponse.redirect(destination);
  }

  // Create regex for public pages with locale prefix
  const publicPathnameRegex = RegExp(
    `^(/(${[...routing.locales].join("|")}))?(${publicPages
      .flatMap((p) => (p === "/" ? ["", "/"] : p))
      .join("|")})/?$`,
    "i",
  );

  const isPublicPage = publicPathnameRegex.test(path);

  // Handle root path
  if (path === "/" || path === "") {
    const lang = routing.defaultLocale;
    const redirectUrl = new URL(
      token ? `/${lang}/dashboard` : `/${lang}/auth/sign-in`,
      req.url,
    );
    return NextResponse.redirect(redirectUrl);
  }

  // For public pages, just apply the intl middleware
  if (isPublicPage) {
    const response = intlMiddleware(req);
    if (isPrivatePaymentPath(path)) {
      for (const { key, value } of PRIVATE_LINK_HEADERS) response.headers.set(key, value);
    }
    return response;
  }

  // For protected routes, check authentication
  if (!token) {
    const pathLocale = path.split("/")[1];
    const isValidLocale = (locale: string): locale is Locale =>
      routing.locales.includes(locale as Locale);

    const locale = isValidLocale(pathLocale)
      ? pathLocale
      : routing.defaultLocale;

    // Always locale-prefixed — single hop to sign-in.
    const signIn = new URL(`/${locale}/auth/sign-in`, req.url);
    // A tapped app notification (the phone app may open it cold, without a
    // language) comes back to that notification after sign-in. The return
    // path is rebuilt from the checked id, never copied from the request.
    const notification = matchNotificationOpenPath(path);
    if (notification) {
      signIn.searchParams.set(
        "next",
        notificationOpenPath(notification.id, notification.locale || locale),
      );
    }
    const consentPath = safeOAuthReturnPath(`/${locale}/oauth/authorize${url.search}`);
    if (/^\/(?:[a-z]{2}\/)?oauth\/authorize\/?$/.test(path) && consentPath) {
      signIn.searchParams.set("next", consentPath);
    }
    return NextResponse.redirect(signIn);
  }

  // Apply intl middleware for authenticated routes
  const response = intlMiddleware(req);
  if (isPrivatePaymentPath(path)) {
    for (const { key, value } of PRIVATE_LINK_HEADERS) response.headers.set(key, value);
  }
  return response;
}

export const config = {
  matcher: [
    {
      // Explicit opt-in only; no middleware cost for ordinary RSC requests.
      source: "/:locale(en|de|es|ar|zh)/:path*",
      has: [
        { type: "header", key: "rsc", value: "1" },
        { type: "header", key: "x-gf-navigation-trace", value: "[0-9a-fA-F-]{36}" },
      ],
    },
    {
      // Keep invocations off static/PWA/meta assets as much as possible.
      source:
        "/((?!api|_next/static|_next/image|assets|newlogo|fonts|icons|icon\\.png|favicon\\.ico|favicon-|apple-touch|sw\\.js|workbox|manifest\\.json|robots\\.txt|sitemap|posthog-snippet\\.js|.*\\.(?:svg|png|jpg|jpeg|gif|webp|ico|txt|xml|json|js|map|woff2?)$).*)",
      // In-app page switches and prefetches (requests made by Next's router)
      // skip the middleware: each run is billed as a function invocation, and
      // for these it had nothing to decide. The language is already in the
      // path (NavigationProvider adds it) and page shells carry no data, so a
      // signed-out tab is caught by the API's 401 instead. Full page loads
      // still run it.
      missing: [{ type: "header", key: "rsc" }],
    },
  ],
};
Editor is loading...
Leave a Comment