Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions docs/APP_API.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,15 @@ server functions call — nothing is duplicated.

## Auth

Every route needs `Authorization: Bearer <Appwrite JWT>`. 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 <jwt>` is accepted too,
but only works without a proxy in front: on Appwrite Cloud the edge executor
overwrites `Authorization` with its own `Basic opr:<secret>` 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

Expand Down
29 changes: 29 additions & 0 deletions src/lib/app-api.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { describe, expect, it } from 'vitest'
import {
APP_JWT_HEADER,
MAX_VOTE_LOOKUP,
appToken,
bearerToken,
commentInput,
statusForFailure,
Expand Down Expand Up @@ -28,6 +30,33 @@ describe('bearerToken', () => {
})
})

describe('appToken', () => {
const headers = (init: Record<string, string>) => 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:<secret>` 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({
Expand Down
31 changes: 24 additions & 7 deletions src/lib/app-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down Expand Up @@ -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:<secret>` 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 <jwt>` 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. */
Expand Down
4 changes: 2 additions & 2 deletions src/server/app-api.server.ts
Original file line number Diff line number Diff line change
@@ -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'

Expand Down Expand Up @@ -60,7 +60,7 @@ export async function handleAppRequest<S extends z.ZodType, T>(
schema: S,
action: (input: z.infer<S>, appUser: AppUser) => Promise<ActionResult<T>>,
): Promise<Response> {
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()
Expand Down
Loading