From 479816dd841c976a33adc557b6469eb970fe219c Mon Sep 17 00:00:00 2001 From: Damodar Lohani Date: Sun, 8 Nov 2026 11:20:30 +0545 Subject: [PATCH] Read the app JWT from X-Refetch-JWT, not Authorization On Appwrite Cloud the edge executor overwrites the request's Authorization header with its own `Basic opr:` (edge src/Edge/K8s/Runner.php) before it reaches the site, so the app's Bearer token never arrived and every /api/app/* call answered 401. Verified from the app: the same JWT returns 200 from Appwrite's /v1/account but 401 from /api/app/session. The routes now read the JWT from X-Refetch-JWT and keep Bearer only as a fallback for local runs without the proxy. Co-Authored-By: Claude Opus 5.5 --- docs/APP_API.md | 13 +++++++++---- src/lib/app-api.test.ts | 29 +++++++++++++++++++++++++++++ src/lib/app-api.ts | 31 ++++++++++++++++++++++++------- src/server/app-api.server.ts | 4 ++-- 4 files changed, 64 insertions(+), 13 deletions(-) diff --git a/docs/APP_API.md b/docs/APP_API.md index 0acb29b..5fdc248 100644 --- a/docs/APP_API.md +++ b/docs/APP_API.md @@ -13,10 +13,15 @@ server functions call — nothing is duplicated. ## Auth -Every route needs `Authorization: Bearer `. The app mints the JWT -with `account.createJWT()`; the route verifies it with Appwrite (`account.get` -as that user), the same check `establishSession` does for the website. A missing, -expired or forged token gets `401 { "error": "Please sign in to continue.", "code": "unauthorized" }`. +Every route needs the app's Appwrite JWT (minted with `account.createJWT()`) in +the **`X-Refetch-JWT`** header. `Authorization: Bearer ` is accepted too, +but only works without a proxy in front: on Appwrite Cloud the edge executor +overwrites `Authorization` with its own `Basic opr:` credential before +the request reaches the site, so the apps must use `X-Refetch-JWT`. + +The route verifies the JWT with Appwrite (`account.get` as that user), the +same check `establishSession` does for the website. A missing, expired or +forged token gets `401 { "error": "Please sign in to continue.", "code": "unauthorized" }`. ## Responses diff --git a/src/lib/app-api.test.ts b/src/lib/app-api.test.ts index 56b0c07..5342182 100644 --- a/src/lib/app-api.test.ts +++ b/src/lib/app-api.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it } from 'vitest' import { + APP_JWT_HEADER, MAX_VOTE_LOOKUP, + appToken, bearerToken, commentInput, statusForFailure, @@ -28,6 +30,33 @@ describe('bearerToken', () => { }) }) +describe('appToken', () => { + const headers = (init: Record) => new Headers(init) + + it('reads the JWT from X-Refetch-JWT', () => { + expect(appToken(headers({ [APP_JWT_HEADER]: JWT }))).toBe(JWT) + }) + + // On Appwrite Cloud the edge executor overwrites Authorization with its own + // `Basic opr:` before the request reaches the site, so a Bearer + // token sent by the app never arrives. The custom header has to win. + it('ignores the executor-supplied Authorization when X-Refetch-JWT is set', () => { + expect(appToken(headers({ authorization: 'Basic b3ByOnNlY3JldA==', [APP_JWT_HEADER]: JWT }))).toBe(JWT) + }) + + it('falls back to a Bearer token (local runs without the proxy)', () => { + expect(appToken(headers({ authorization: `Bearer ${JWT}` }))).toBe(JWT) + }) + + it('rejects an executor Basic credential on its own', () => { + expect(appToken(headers({ authorization: 'Basic b3ByOnNlY3JldA==' }))).toBeNull() + }) + + it('rejects implausible tokens in the custom header', () => { + expect(appToken(headers({ [APP_JWT_HEADER]: 'short' }))).toBeNull() + }) +}) + describe('toAppResponse', () => { it('wraps success in data', () => { expect(toAppResponse({ ok: true, data: { vote: 'up', count: 3 } })).toEqual({ diff --git a/src/lib/app-api.ts b/src/lib/app-api.ts index 930ea33..0025113 100644 --- a/src/lib/app-api.ts +++ b/src/lib/app-api.ts @@ -5,10 +5,10 @@ import { isHttpUrl, isValidId } from '@/lib/url' /* * The JSON API the mobile and desktop apps call (`/api/app/*`). The apps sign - * in with Appwrite themselves and send a short-lived Appwrite JWT as a bearer - * token; the routes verify it and then run the same server code the website's - * server functions run, so the rules (rate limits, duplicates, counters, - * notifications) live in one place. + * in with Appwrite themselves and send a short-lived Appwrite JWT in the + * `X-Refetch-JWT` header; the routes verify it and then run the same server + * code the website's server functions run, so the rules (rate limits, + * duplicates, counters, notifications) live in one place. * * This file holds the framework-free parts so they can be unit tested. */ @@ -41,12 +41,29 @@ export const submitInput = z.object({ comment: z.string().trim().max(LIMITS.submissionNoteMax).optional(), }) +/** + * Header the apps send their Appwrite JWT in. Not `Authorization`: on Appwrite + * Cloud the edge executor overwrites that header with its own + * `Basic opr:` before the request reaches the site, so a Bearer token + * from the app never arrives. + */ +export const APP_JWT_HEADER = 'x-refetch-jwt' + +/** A JWT of plausible length (Appwrite JWTs are well under 4 KB), or null. */ +function plausibleJwt(token: string | null | undefined): string | null { + const value = token?.trim() + return value && value.length >= 16 && value.length <= 4096 && !/\s/.test(value) ? value : null +} + +/** The app's JWT: `X-Refetch-JWT`, else `Authorization: Bearer` (local runs). */ +export function appToken(headers: Headers): string | null { + return plausibleJwt(headers.get(APP_JWT_HEADER)) ?? bearerToken(headers.get('authorization')) +} + /** The token from an `Authorization: Bearer ` header, or null. */ export function bearerToken(header: string | null | undefined): string | null { const match = /^Bearer\s+(\S+)$/i.exec(header?.trim() ?? '') - const token = match?.[1] - // Appwrite JWTs are well under 4 KB; anything else is not one. - return token && token.length >= 16 && token.length <= 4096 ? token : null + return plausibleJwt(match?.[1]) } /** HTTP status for a failed action, from its error code. */ diff --git a/src/server/app-api.server.ts b/src/server/app-api.server.ts index 9a7c1c9..4a05957 100644 --- a/src/server/app-api.server.ts +++ b/src/server/app-api.server.ts @@ -1,7 +1,7 @@ import { Account, Client } from 'node-appwrite' import type { z } from 'zod' import type { ActionResult, SessionUser } from '@/lib/types' -import { bearerToken, toAppResponse, validationMessage } from '@/lib/app-api' +import { appToken, toAppResponse, validationMessage } from '@/lib/app-api' import { getModeratorIds, getPublicConfig } from './env.server' import { MODERATOR_LABELS } from './session.server' @@ -60,7 +60,7 @@ export async function handleAppRequest( schema: S, action: (input: z.infer, appUser: AppUser) => Promise>, ): Promise { - const token = bearerToken(request.headers.get('authorization')) + const token = appToken(request.headers) if (!token) return UNAUTHORIZED.clone() const appUser = await verify(token) if (!appUser) return UNAUTHORIZED.clone()