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
40 changes: 40 additions & 0 deletions docs/APP_API.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# App API (`/api/app/*`)

The JSON API the Refetch mobile and desktop apps
([refetch_flutter](https://github.com/refetch-io/refetch_flutter)) call for
everything that writes or needs the signed-in person's private data.

The apps **read public data straight from Appwrite** (posts, comments, channels
and topics are readable by anyone). Writes can't go there directly: a vote also
moves the story's score counters, and comments and submissions run rate limits,
duplicate checks, mentions and notifications. Those rules live in
`src/server/*.server.ts`, so these routes call the same functions the website's
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" }`.

## Responses

- Success: `200 { "data": … }`
- Failure: `{ "error": "<message for people>", "code"?, "existingId"? }` with
`400` (validation or a rule), `401` (`unauthorized`), `409` (`duplicate`) or
`429` (`rate_limited`); `500` for an unexpected error.

## Routes

| Method | Path | Body | `data` |
| --- | --- | --- | --- |
| POST | `/api/app/session` | `{}` | `{ user }`. Call after signing in; creates or renames the profile. |
| POST | `/api/app/vote` | `{ resourceType: 'post' \| 'comment', resourceId, direction: 'up' \| 'down' }` | `{ vote: 'up' \| 'down' \| null, count }`. Same direction again removes the vote. |
| POST | `/api/app/votes` | `{ posts?: string[], comments?: string[] }` (≤ 200 each) | `{ posts: { [id]: 'up' \| 'down' }, comments: { … } }` |
| POST | `/api/app/comments` | `{ postId, content, replyId? }` | the new comment |
| DELETE | `/api/app/comments/:id` | — | — (your own comments only) |
| POST | `/api/app/submit` | `{ title, url, comment? }` | `{ id }`; `409` with `existingId` when the link was already shared |

Validation lives in `src/lib/app-api.ts` (unit tested); the request handling in
`src/server/app-api.server.ts`.
9 changes: 7 additions & 2 deletions src/api/moderation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ import { z } from 'zod'
import type { ActionResult } from '@/lib/types'
import { REPORT_NOTE_MAX, REPORT_REASON_VALUES, type ModerationItem } from '@/lib/reports'
import { isValidId } from '@/lib/url'
import { countModerationQueue, createReport, listModerationQueue, resolveReports } from '@/server/reports.server'
import {
countModerationQueue,
createReport,
listModerationQueue,
resolveReports,
} from '@/server/reports.server'
import { getSessionUser } from '@/server/session.server'

const id = z.string().refine(isValidId, 'Invalid id')
Expand Down Expand Up @@ -41,7 +46,7 @@ export const fetchModerationCount = createServerFn({ method: 'GET' }).handler(as
return user?.moderator ? countModerationQueue() : 0
})

export const resolveReport =createServerFn({ method: 'POST' })
export const resolveReport = createServerFn({ method: 'POST' })
.validator(z.object({ resourceType, resourceId: id, action: z.enum(['dismiss', 'remove']) }))
.handler(async ({ data }): Promise<ActionResult> => {
const user = await getSessionUser({ fresh: true })
Expand Down
5 changes: 1 addition & 4 deletions src/components/layout/navigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,7 @@ function SidebarChannels({ pathname }: { pathname: string }) {
</h2>
</div>
{/* Negative margin + padding leaves room for focus rings inside the scroll clip. */}
<nav
aria-label="Channels"
className="-mx-2 -my-1 min-h-0 space-y-0.5 overflow-y-auto px-2 py-1"
>
<nav aria-label="Channels" className="-mx-2 -my-1 min-h-0 space-y-0.5 overflow-y-auto px-2 py-1">
{list.map((channel) => {
const active = pathname === `/channels/${channel.id}`
return (
Expand Down
81 changes: 81 additions & 0 deletions src/lib/app-api.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { describe, expect, it } from 'vitest'
import {
MAX_VOTE_LOOKUP,
bearerToken,
commentInput,
statusForFailure,
submitInput,
toAppResponse,
voteInput,
voteLookupInput,
} from './app-api'

const JWT = 'eyJhbGciOiJIUzI1NiJ9.payload.signature'

describe('bearerToken', () => {
it('reads a bearer token', () => {
expect(bearerToken(`Bearer ${JWT}`)).toBe(JWT)
expect(bearerToken(`bearer ${JWT}`)).toBe(JWT)
})

it('rejects missing, malformed and implausible tokens', () => {
expect(bearerToken(null)).toBeNull()
expect(bearerToken('')).toBeNull()
expect(bearerToken(JWT)).toBeNull()
expect(bearerToken('Basic abc')).toBeNull()
expect(bearerToken('Bearer short')).toBeNull()
expect(bearerToken(`Bearer ${'x'.repeat(5000)}`)).toBeNull()
})
})

describe('toAppResponse', () => {
it('wraps success in data', () => {
expect(toAppResponse({ ok: true, data: { vote: 'up', count: 3 } })).toEqual({
status: 200,
body: { data: { vote: 'up', count: 3 } },
})
})

it('maps failure codes onto statuses and keeps existingId', () => {
expect(
toAppResponse({ ok: false, code: 'duplicate', error: 'Already shared.', existingId: 'abc' }),
).toEqual({ status: 409, body: { error: 'Already shared.', code: 'duplicate', existingId: 'abc' } })
expect(toAppResponse({ ok: false, error: 'Nope.' })).toEqual({ status: 400, body: { error: 'Nope.' } })
})

it('uses 401 and 429 for auth and rate limits', () => {
expect(statusForFailure('unauthorized')).toBe(401)
expect(statusForFailure('rate_limited')).toBe(429)
})
})

describe('inputs', () => {
it('validates votes', () => {
expect(voteInput.safeParse({ resourceType: 'post', resourceId: 'abc', direction: 'up' }).success).toBe(
true,
)
expect(voteInput.safeParse({ resourceType: 'user', resourceId: 'abc', direction: 'up' }).success).toBe(
false,
)
expect(voteInput.safeParse({ resourceType: 'post', resourceId: '../x', direction: 'up' }).success).toBe(
false,
)
})

it('defaults and caps vote lookups', () => {
expect(voteLookupInput.parse({})).toEqual({ posts: [], comments: [] })
const tooMany = Array.from({ length: MAX_VOTE_LOOKUP + 1 }, (_, i) => `p${i}`)
expect(voteLookupInput.safeParse({ posts: tooMany }).success).toBe(false)
})

it('trims comments and rejects empty ones', () => {
expect(commentInput.parse({ postId: 'abc', content: ' hi ' }).content).toBe('hi')
expect(commentInput.safeParse({ postId: 'abc', content: ' ' }).success).toBe(false)
})

it('requires an http(s) url to submit', () => {
expect(submitInput.safeParse({ title: 'T', url: 'https://example.com' }).success).toBe(true)
expect(submitInput.safeParse({ title: 'T', url: 'javascript:alert(1)' }).success).toBe(false)
expect(submitInput.safeParse({ title: ' ', url: 'https://example.com' }).success).toBe(false)
})
})
87 changes: 87 additions & 0 deletions src/lib/app-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { z } from 'zod'
import type { ActionResult } from '@/lib/types'
import { LIMITS } from '@/lib/constants'
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.
*
* This file holds the framework-free parts so they can be unit tested.
*/

const id = z.string().refine(isValidId, 'Invalid id')

/** At most this many ids per type in one `/api/app/votes` lookup. */
export const MAX_VOTE_LOOKUP = 200

export const voteInput = z.object({
resourceType: z.enum(['post', 'comment']),
resourceId: id,
direction: z.enum(['up', 'down']),
})

export const voteLookupInput = z.object({
posts: z.array(id).max(MAX_VOTE_LOOKUP).default([]),
comments: z.array(id).max(MAX_VOTE_LOOKUP).default([]),
})

export const commentInput = z.object({
postId: id,
content: z.string().trim().min(1, 'Write something first.').max(LIMITS.commentMax),
replyId: id.optional(),
})

export const submitInput = z.object({
title: z.string().trim().min(1, 'Add a title.').max(LIMITS.titleMax),
url: z.string().trim().max(LIMITS.urlMax).refine(isHttpUrl, 'Enter a valid http(s) URL.'),
comment: z.string().trim().max(LIMITS.submissionNoteMax).optional(),
})

/** 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
}

/** HTTP status for a failed action, from its error code. */
export function statusForFailure(code: string | undefined): number {
switch (code) {
case 'unauthorized':
return 401
case 'rate_limited':
return 429
case 'duplicate':
return 409
default:
return 400
}
}

export interface AppApiBody<T> {
status: number
body: { data: T } | { error: string; code?: string; existingId?: string }
}

/** Map an ActionResult onto the app API's response shape. */
export function toAppResponse<T>(result: ActionResult<T>): AppApiBody<T> {
if (result.ok) return { status: 200, body: { data: result.data } }
return {
status: statusForFailure(result.code),
body: {
error: result.error,
...(result.code ? { code: result.code } : {}),
...(result.existingId ? { existingId: result.existingId } : {}),
},
}
}

/** The first validation message, worded for people. */
export function validationMessage(error: z.ZodError): string {
return error.issues[0]?.message ?? 'Invalid request.'
}
Loading
Loading