From 2def692109372c011d08b505dd47a51d23ba285b Mon Sep 17 00:00:00 2001 From: Devanarayanan Date: Sat, 14 Nov 2026 22:12:56 +0000 Subject: [PATCH 1/2] feat: enhance security checks for mobile clients and CSRF token validation --- .example.env | 4 +- mobile/lib/config/app_config.dart | 2 +- mobile/pubspec.yaml | 2 +- package-lock.json | 4 +- package.json | 2 +- public/openapi/openapi.yaml | 2 +- src/app/api/auth/save-token/route.ts | 6 ++- src/app/api/backend/[...path]/route.ts | 3 +- src/lib/security/app-check.ts | 60 ++++++++++++++++++-------- 9 files changed, 57 insertions(+), 28 deletions(-) diff --git a/.example.env b/.example.env index 55045c71..5ff66ff0 100644 --- a/.example.env +++ b/.example.env @@ -44,7 +44,7 @@ NEXT_PUBLIC_APP_NAME=GhostClass # âš ī¸ App version displayed in footer and health checks # 🔨 Build-time (Infisical `/build-time` folder) -NEXT_PUBLIC_APP_VERSION=4.7.1 +NEXT_PUBLIC_APP_VERSION=4.7.2 # âš ī¸ Your production domain WITHOUT https:// # All URL-based variables are derived from this. @@ -379,7 +379,7 @@ REQUEST_SIGNATURE_MAX_AGE=600 # âš ī¸ Minimum supported app version required to bypass forced update # 🚀 Runtime (Infisical `/runtime` folder → Server Env Var) -MIN_APP_VERSION=4.7.1 +MIN_APP_VERSION=4.7.2 # â„šī¸ Enforce Firebase App Check for all mobile clients in production # Valid: "true", "false" (default: false in dev, true recommended in prod) diff --git a/mobile/lib/config/app_config.dart b/mobile/lib/config/app_config.dart index df964827..8409eae2 100644 --- a/mobile/lib/config/app_config.dart +++ b/mobile/lib/config/app_config.dart @@ -89,7 +89,7 @@ class AppConfig { /// Current application version static String get appVersion => - const String.fromEnvironment('APP_VERSION', defaultValue: '4.7.1'); + const String.fromEnvironment('APP_VERSION', defaultValue: '4.7.2'); /// Commit SHA injected by CI for release builds. static String get appCommitSha => diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml index b3b0d6a0..072b928b 100644 --- a/mobile/pubspec.yaml +++ b/mobile/pubspec.yaml @@ -16,7 +16,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. -version: 4.7.1+1 +version: 4.7.2+1 environment: sdk: ^3.11.4 diff --git a/package-lock.json b/package-lock.json index d85e7c92..82152706 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ghostclass", - "version": "4.7.1", + "version": "4.7.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ghostclass", - "version": "4.7.1", + "version": "4.7.2", "dependencies": { "@hookform/resolvers": "^7.0.6", "@radix-ui/react-alert-dialog": "^1.1.23", diff --git a/package.json b/package.json index 9f34989e..e1b2535f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ghostclass", - "version": "4.7.1", + "version": "4.7.2", "private": true, "engines": { "node": ">=22.12.0", diff --git a/public/openapi/openapi.yaml b/public/openapi/openapi.yaml index aaa1f428..932bfb30 100644 --- a/public/openapi/openapi.yaml +++ b/public/openapi/openapi.yaml @@ -6,7 +6,7 @@ openapi: 3.1.0 info: title: GhostClass API - version: 4.7.1 + version: 4.7.2 description: | **GhostClass API** provides endpoints for authentication, profile synchronization, attendance integrations with EzyGo, telemetry, and build provenance. diff --git a/src/app/api/auth/save-token/route.ts b/src/app/api/auth/save-token/route.ts index fda8570f..f409a3f9 100644 --- a/src/app/api/auth/save-token/route.ts +++ b/src/app/api/auth/save-token/route.ts @@ -387,7 +387,8 @@ const handler = async ( ) => { const headerList = await headers(); const cookieStore = await cookies(); - const isAppCheck = authType === "app-check"; + const isAppCheck = + authType === "app-check" || !headerList.has("sec-fetch-site"); const headerErr = await validateRequestHeaders(headerList, isAppCheck); if (headerErr) return headerErr; @@ -492,7 +493,8 @@ const handler = async ( current_year: syncRes?.academic?.current_year ?? info.current_year, }; - if (authType !== "app-check") { + const isMobileClient = isAppCheck || !!fcm_token; + if (!isMobileClient) { await setAuthCookie(token); return NextResponse.json(response); diff --git a/src/app/api/backend/[...path]/route.ts b/src/app/api/backend/[...path]/route.ts index d8b430fe..568502f8 100644 --- a/src/app/api/backend/[...path]/route.ts +++ b/src/app/api/backend/[...path]/route.ts @@ -234,7 +234,8 @@ async function validateProxyAuthAndOrigin( authType?: "app-check" | "csrf" | "none", ): Promise<{ token?: string; errorResponse?: NextResponse }> { const isPublic = PUBLIC_PATHS.has(fullPath); - const isMobileApp = authType === "app-check"; + const isMobileApp = + authType === "app-check" || !req.headers.has("sec-fetch-site"); const originError = await validateOrigin( req, diff --git a/src/lib/security/app-check.ts b/src/lib/security/app-check.ts index 0dc5e207..9486d284 100644 --- a/src/lib/security/app-check.ts +++ b/src/lib/security/app-check.ts @@ -354,30 +354,56 @@ async function verifyAuthentication( return await verifyCsrfAuth(headerList); } - // State-changing web requests MUST have a CSRF token. + // State-changing requests: web clients must have a CSRF token. + // Mobile clients (no sec-fetch-site header) fall through to the + // ENFORCE_APP_CHECK gate so fail-open works correctly when attestation fails. const method = req.method.toUpperCase(); const isStateChanging = ["POST", "PUT", "DELETE", "PATCH"].includes(method); - if (isStateChanging && !hasAppCheckToken) { - const isVitestBypass = - process.env.NODE_ENV !== "production" && process.env.VITEST === "true"; - if (!isVitestBypass) { - return { - isValid: false, - error: "Missing CSRF token", - reason: "Security check failed.", - action: "Please refresh the page or restart the app.", - authType: "csrf", - isWebRequest: true, - }; - } + const isWebClient = headerList.has("sec-fetch-site"); + if (isStateChanging && isWebClient) { + // Browser without CSRF token — always reject regardless of enforcement flag. + // Web CSRF protection is never fail-open. + return { + isValid: false, + error: "Missing CSRF token", + reason: "Security check failed.", + action: "Please refresh the page or restart the app.", + authType: "csrf", + isWebRequest: true, + }; } - // Neither header is present. If App Check is not enforced, we allow the request. + // No App Check token and no CSRF token. + // Respect the ENFORCE_APP_CHECK environment variable: + // - "true" → strict: reject (fail-closed) + // - absent/other → permissive: allow through (fail-open) + // For mobile clients (not a web browser), identify as "app-check" authType with + // isAttested: false, so downstream handlers (like save-token and backend proxy) + // skip browser origin checks and return mobile session payloads. if (process.env.ENFORCE_APP_CHECK !== "true") { - return { isValid: true, authType: "none" }; + return { + isValid: true, + authType: isWebClient ? "none" : "app-check", + isMobileRequest: !isWebClient, + isWebRequest: isWebClient, + isAttested: false, + }; } - return { isValid: false, error: "Unauthenticated", authType: "none" }; + return { + isValid: false, + error: isWebClient + ? "Unauthenticated" + : "Missing mandatory App Check token", + reason: isWebClient + ? "Authentication required." + : SECURITY_ERRORS.MISSING_TOKEN.reason, + action: isWebClient + ? "Please log in again." + : SECURITY_ERRORS.MISSING_TOKEN.action, + authType: isWebClient ? "none" : "app-check", + criticalRisk: !isWebClient, + }; } async function handleRateLimit( From d90599ddda05a91f3039c59bd1240adbc7f1d9b1 Mon Sep 17 00:00:00 2001 From: Devanarayanan Date: Sat, 14 Nov 2026 22:24:24 +0000 Subject: [PATCH 2/2] fix: app check and CSRF validation logic for mobile clients --- mobile/lib/services/dio_service.dart | 2 + src/app/api/auth/save-token/route.ts | 3 +- src/app/api/backend/[...path]/route.ts | 3 +- src/lib/security/app-check.ts | 60 ++++++++------------------ 4 files changed, 21 insertions(+), 47 deletions(-) diff --git a/mobile/lib/services/dio_service.dart b/mobile/lib/services/dio_service.dart index 31b031ae..d88b56f8 100644 --- a/mobile/lib/services/dio_service.dart +++ b/mobile/lib/services/dio_service.dart @@ -224,6 +224,7 @@ class DioService { const errorMsg = 'App Check token is empty - verify Firebase activation'; options.extra['appCheckError'] = errorMsg; + options.headers['X-Firebase-AppCheck'] = 'unverified'; AppLogger.w('DioService: $errorMsg (continuing in fail-open mode)'); } } on Object catch (e) { @@ -236,6 +237,7 @@ class DioService { ); options.extra['appCheckError'] = e.toString(); options.extra['appCheckTransient'] = _isTransientAppCheckFailure(e); + options.headers['X-Firebase-AppCheck'] = 'unverified'; } } diff --git a/src/app/api/auth/save-token/route.ts b/src/app/api/auth/save-token/route.ts index f409a3f9..b1c9f8a2 100644 --- a/src/app/api/auth/save-token/route.ts +++ b/src/app/api/auth/save-token/route.ts @@ -387,8 +387,7 @@ const handler = async ( ) => { const headerList = await headers(); const cookieStore = await cookies(); - const isAppCheck = - authType === "app-check" || !headerList.has("sec-fetch-site"); + const isAppCheck = authType === "app-check"; const headerErr = await validateRequestHeaders(headerList, isAppCheck); if (headerErr) return headerErr; diff --git a/src/app/api/backend/[...path]/route.ts b/src/app/api/backend/[...path]/route.ts index 568502f8..d8b430fe 100644 --- a/src/app/api/backend/[...path]/route.ts +++ b/src/app/api/backend/[...path]/route.ts @@ -234,8 +234,7 @@ async function validateProxyAuthAndOrigin( authType?: "app-check" | "csrf" | "none", ): Promise<{ token?: string; errorResponse?: NextResponse }> { const isPublic = PUBLIC_PATHS.has(fullPath); - const isMobileApp = - authType === "app-check" || !req.headers.has("sec-fetch-site"); + const isMobileApp = authType === "app-check"; const originError = await validateOrigin( req, diff --git a/src/lib/security/app-check.ts b/src/lib/security/app-check.ts index 9486d284..0dc5e207 100644 --- a/src/lib/security/app-check.ts +++ b/src/lib/security/app-check.ts @@ -354,56 +354,30 @@ async function verifyAuthentication( return await verifyCsrfAuth(headerList); } - // State-changing requests: web clients must have a CSRF token. - // Mobile clients (no sec-fetch-site header) fall through to the - // ENFORCE_APP_CHECK gate so fail-open works correctly when attestation fails. + // State-changing web requests MUST have a CSRF token. const method = req.method.toUpperCase(); const isStateChanging = ["POST", "PUT", "DELETE", "PATCH"].includes(method); - const isWebClient = headerList.has("sec-fetch-site"); - if (isStateChanging && isWebClient) { - // Browser without CSRF token — always reject regardless of enforcement flag. - // Web CSRF protection is never fail-open. - return { - isValid: false, - error: "Missing CSRF token", - reason: "Security check failed.", - action: "Please refresh the page or restart the app.", - authType: "csrf", - isWebRequest: true, - }; + if (isStateChanging && !hasAppCheckToken) { + const isVitestBypass = + process.env.NODE_ENV !== "production" && process.env.VITEST === "true"; + if (!isVitestBypass) { + return { + isValid: false, + error: "Missing CSRF token", + reason: "Security check failed.", + action: "Please refresh the page or restart the app.", + authType: "csrf", + isWebRequest: true, + }; + } } - // No App Check token and no CSRF token. - // Respect the ENFORCE_APP_CHECK environment variable: - // - "true" → strict: reject (fail-closed) - // - absent/other → permissive: allow through (fail-open) - // For mobile clients (not a web browser), identify as "app-check" authType with - // isAttested: false, so downstream handlers (like save-token and backend proxy) - // skip browser origin checks and return mobile session payloads. + // Neither header is present. If App Check is not enforced, we allow the request. if (process.env.ENFORCE_APP_CHECK !== "true") { - return { - isValid: true, - authType: isWebClient ? "none" : "app-check", - isMobileRequest: !isWebClient, - isWebRequest: isWebClient, - isAttested: false, - }; + return { isValid: true, authType: "none" }; } - return { - isValid: false, - error: isWebClient - ? "Unauthenticated" - : "Missing mandatory App Check token", - reason: isWebClient - ? "Authentication required." - : SECURITY_ERRORS.MISSING_TOKEN.reason, - action: isWebClient - ? "Please log in again." - : SECURITY_ERRORS.MISSING_TOKEN.action, - authType: isWebClient ? "none" : "app-check", - criticalRisk: !isWebClient, - }; + return { isValid: false, error: "Unauthenticated", authType: "none" }; } async function handleRateLimit(