From 01b7582030e7049fafc05bb3c98bf6b334de1940 Mon Sep 17 00:00:00 2001 From: Damodar Lohani Date: Sun, 8 Nov 2026 10:07:42 +0545 Subject: [PATCH 1/2] Add a JSON API for the mobile and desktop apps The apps used the old Next.js REST routes (/api/posts, /api/vote, ...), which went away with the TanStack Start rewrite, so the shipped app can no longer load or write anything. The apps now read public data straight from Appwrite. For writes and the signed-in person's votes they call /api/app/* with an Appwrite JWT: each route verifies it the way establishSession does, then runs the same castVote, createComment, removeComment, createPost and syncProfile the website uses, so rate limits, counters and notifications stay in one place. Co-Authored-By: Claude Opus 5.5 --- docs/APP_API.md | 40 +++++++++ src/lib/app-api.test.ts | 81 +++++++++++++++++ src/lib/app-api.ts | 87 ++++++++++++++++++ src/routeTree.gen.ts | 136 +++++++++++++++++++++++++++++ src/routes/api/app.comments.$id.ts | 21 +++++ src/routes/api/app.comments.ts | 17 ++++ src/routes/api/app.session.ts | 27 ++++++ src/routes/api/app.submit.ts | 17 ++++ src/routes/api/app.vote.ts | 19 ++++ src/routes/api/app.votes.ts | 26 ++++++ src/server/app-api.server.ts | 86 ++++++++++++++++++ 11 files changed, 557 insertions(+) create mode 100644 docs/APP_API.md create mode 100644 src/lib/app-api.test.ts create mode 100644 src/lib/app-api.ts create mode 100644 src/routes/api/app.comments.$id.ts create mode 100644 src/routes/api/app.comments.ts create mode 100644 src/routes/api/app.session.ts create mode 100644 src/routes/api/app.submit.ts create mode 100644 src/routes/api/app.vote.ts create mode 100644 src/routes/api/app.votes.ts create mode 100644 src/server/app-api.server.ts diff --git a/docs/APP_API.md b/docs/APP_API.md new file mode 100644 index 0000000..0acb29b --- /dev/null +++ b/docs/APP_API.md @@ -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 `. 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": "", "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`. diff --git a/src/lib/app-api.test.ts b/src/lib/app-api.test.ts new file mode 100644 index 0000000..56b0c07 --- /dev/null +++ b/src/lib/app-api.test.ts @@ -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) + }) +}) diff --git a/src/lib/app-api.ts b/src/lib/app-api.ts new file mode 100644 index 0000000..930ea33 --- /dev/null +++ b/src/lib/app-api.ts @@ -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 ` 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 { + status: number + body: { data: T } | { error: string; code?: string; existingId?: string } +} + +/** Map an ActionResult onto the app API's response shape. */ +export function toAppResponse(result: ActionResult): AppApiBody { + 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.' +} diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.ts index d2e646a..caeef1c 100644 --- a/src/routeTree.gen.ts +++ b/src/routeTree.gen.ts @@ -48,11 +48,17 @@ import { Route as AppThreadsThreadIdRouteImport } from './routes/_app/threads.$t import { Route as AppTopicsIndexRouteImport } from './routes/_app/topics.index' import { Route as AppTopicsTopicKeyRouteImport } from './routes/_app/topics.$topicKey' import { Route as AppUsersUserIdRouteImport } from './routes/_app/users.$userId' +import { Route as ApiAppCommentsRouteImport } from './routes/api/app.comments' +import { Route as ApiAppSessionRouteImport } from './routes/api/app.session' +import { Route as ApiAppSubmitRouteImport } from './routes/api/app.submit' +import { Route as ApiAppVoteRouteImport } from './routes/api/app.vote' +import { Route as ApiAppVotesRouteImport } from './routes/api/app.votes' import { Route as ApiDigestPreviewRouteImport } from './routes/api/digest.preview' import { Route as AppUsersUserIdIndexRouteImport } from './routes/_app/users.$userId.index' import { Route as AppUsersUserIdCommentsRouteImport } from './routes/_app/users.$userId.comments' import { Route as AppUsersUserIdFollowersRouteImport } from './routes/_app/users.$userId.followers' import { Route as AppUsersUserIdFollowingRouteImport } from './routes/_app/users.$userId.following' +import { Route as ApiAppCommentsIdRouteImport } from './routes/api/app.comments.$id' import { Route as ApiOgThreadIdRouteImport } from './routes/api/og/thread.$id' const AppRoute = AppRouteImport.update({ @@ -249,6 +255,31 @@ const AppUsersUserIdRoute = AppUsersUserIdRouteImport.update({ path: '/users/$userId', getParentRoute: () => AppRoute, } as any) +const ApiAppCommentsRoute = ApiAppCommentsRouteImport.update({ + id: '/api/app/comments', + path: '/api/app/comments', + getParentRoute: () => rootRouteImport, +} as any) +const ApiAppSessionRoute = ApiAppSessionRouteImport.update({ + id: '/api/app/session', + path: '/api/app/session', + getParentRoute: () => rootRouteImport, +} as any) +const ApiAppSubmitRoute = ApiAppSubmitRouteImport.update({ + id: '/api/app/submit', + path: '/api/app/submit', + getParentRoute: () => rootRouteImport, +} as any) +const ApiAppVoteRoute = ApiAppVoteRouteImport.update({ + id: '/api/app/vote', + path: '/api/app/vote', + getParentRoute: () => rootRouteImport, +} as any) +const ApiAppVotesRoute = ApiAppVotesRouteImport.update({ + id: '/api/app/votes', + path: '/api/app/votes', + getParentRoute: () => rootRouteImport, +} as any) const ApiDigestPreviewRoute = ApiDigestPreviewRouteImport.update({ id: '/preview', path: '/preview', @@ -274,6 +305,11 @@ const AppUsersUserIdFollowingRoute = AppUsersUserIdFollowingRouteImport.update({ path: '/following', getParentRoute: () => AppUsersUserIdRoute, } as any) +const ApiAppCommentsIdRoute = ApiAppCommentsIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => ApiAppCommentsRoute, +} as any) const ApiOgThreadIdRoute = ApiOgThreadIdRouteImport.update({ id: '/api/og/thread/$id', path: '/api/og/thread/$id', @@ -314,6 +350,11 @@ export interface FileRoutesByFullPath { '/threads/$threadId': typeof AppThreadsThreadIdRoute '/topics/$topicKey': typeof AppTopicsTopicKeyRoute '/users/$userId': typeof AppUsersUserIdRouteWithChildren + '/api/app/comments': typeof ApiAppCommentsRouteWithChildren + '/api/app/session': typeof ApiAppSessionRoute + '/api/app/submit': typeof ApiAppSubmitRoute + '/api/app/vote': typeof ApiAppVoteRoute + '/api/app/votes': typeof ApiAppVotesRoute '/api/digest/preview': typeof ApiDigestPreviewRoute '/channels/': typeof AppChannelsIndexRoute '/messages/': typeof AppMessagesIndexRoute @@ -322,6 +363,7 @@ export interface FileRoutesByFullPath { '/users/$userId/comments': typeof AppUsersUserIdCommentsRoute '/users/$userId/followers': typeof AppUsersUserIdFollowersRoute '/users/$userId/following': typeof AppUsersUserIdFollowingRoute + '/api/app/comments/$id': typeof ApiAppCommentsIdRoute '/api/og/thread/$id': typeof ApiOgThreadIdRoute '/users/$userId/': typeof AppUsersUserIdIndexRoute } @@ -357,6 +399,11 @@ export interface FileRoutesByTo { '/past/$day': typeof AppPastDayRoute '/threads/$threadId': typeof AppThreadsThreadIdRoute '/topics/$topicKey': typeof AppTopicsTopicKeyRoute + '/api/app/comments': typeof ApiAppCommentsRouteWithChildren + '/api/app/session': typeof ApiAppSessionRoute + '/api/app/submit': typeof ApiAppSubmitRoute + '/api/app/vote': typeof ApiAppVoteRoute + '/api/app/votes': typeof ApiAppVotesRoute '/api/digest/preview': typeof ApiDigestPreviewRoute '/channels': typeof AppChannelsIndexRoute '/messages': typeof AppMessagesIndexRoute @@ -365,6 +412,7 @@ export interface FileRoutesByTo { '/users/$userId/comments': typeof AppUsersUserIdCommentsRoute '/users/$userId/followers': typeof AppUsersUserIdFollowersRoute '/users/$userId/following': typeof AppUsersUserIdFollowingRoute + '/api/app/comments/$id': typeof ApiAppCommentsIdRoute '/api/og/thread/$id': typeof ApiOgThreadIdRoute '/users/$userId': typeof AppUsersUserIdIndexRoute } @@ -405,6 +453,11 @@ export interface FileRoutesById { '/_app/threads/$threadId': typeof AppThreadsThreadIdRoute '/_app/topics/$topicKey': typeof AppTopicsTopicKeyRoute '/_app/users/$userId': typeof AppUsersUserIdRouteWithChildren + '/api/app/comments': typeof ApiAppCommentsRouteWithChildren + '/api/app/session': typeof ApiAppSessionRoute + '/api/app/submit': typeof ApiAppSubmitRoute + '/api/app/vote': typeof ApiAppVoteRoute + '/api/app/votes': typeof ApiAppVotesRoute '/api/digest/preview': typeof ApiDigestPreviewRoute '/_app/channels/': typeof AppChannelsIndexRoute '/_app/messages/': typeof AppMessagesIndexRoute @@ -413,6 +466,7 @@ export interface FileRoutesById { '/_app/users/$userId/comments': typeof AppUsersUserIdCommentsRoute '/_app/users/$userId/followers': typeof AppUsersUserIdFollowersRoute '/_app/users/$userId/following': typeof AppUsersUserIdFollowingRoute + '/api/app/comments/$id': typeof ApiAppCommentsIdRoute '/api/og/thread/$id': typeof ApiOgThreadIdRoute '/_app/users/$userId/': typeof AppUsersUserIdIndexRoute } @@ -452,6 +506,11 @@ export interface FileRouteTypes { | '/threads/$threadId' | '/topics/$topicKey' | '/users/$userId' + | '/api/app/comments' + | '/api/app/session' + | '/api/app/submit' + | '/api/app/vote' + | '/api/app/votes' | '/api/digest/preview' | '/channels/' | '/messages/' @@ -460,6 +519,7 @@ export interface FileRouteTypes { | '/users/$userId/comments' | '/users/$userId/followers' | '/users/$userId/following' + | '/api/app/comments/$id' | '/api/og/thread/$id' | '/users/$userId/' fileRoutesByTo: FileRoutesByTo @@ -495,6 +555,11 @@ export interface FileRouteTypes { | '/past/$day' | '/threads/$threadId' | '/topics/$topicKey' + | '/api/app/comments' + | '/api/app/session' + | '/api/app/submit' + | '/api/app/vote' + | '/api/app/votes' | '/api/digest/preview' | '/channels' | '/messages' @@ -503,6 +568,7 @@ export interface FileRouteTypes { | '/users/$userId/comments' | '/users/$userId/followers' | '/users/$userId/following' + | '/api/app/comments/$id' | '/api/og/thread/$id' | '/users/$userId' id: @@ -542,6 +608,11 @@ export interface FileRouteTypes { | '/_app/threads/$threadId' | '/_app/topics/$topicKey' | '/_app/users/$userId' + | '/api/app/comments' + | '/api/app/session' + | '/api/app/submit' + | '/api/app/vote' + | '/api/app/votes' | '/api/digest/preview' | '/_app/channels/' | '/_app/messages/' @@ -550,6 +621,7 @@ export interface FileRouteTypes { | '/_app/users/$userId/comments' | '/_app/users/$userId/followers' | '/_app/users/$userId/following' + | '/api/app/comments/$id' | '/api/og/thread/$id' | '/_app/users/$userId/' fileRoutesById: FileRoutesById @@ -566,6 +638,11 @@ export interface RootRouteChildren { FeedsSplatRoute: typeof FeedsSplatRoute SitemapsFileRoute: typeof SitemapsFileRoute USplatRoute: typeof USplatRoute + ApiAppCommentsRoute: typeof ApiAppCommentsRouteWithChildren + ApiAppSessionRoute: typeof ApiAppSessionRoute + ApiAppSubmitRoute: typeof ApiAppSubmitRoute + ApiAppVoteRoute: typeof ApiAppVoteRoute + ApiAppVotesRoute: typeof ApiAppVotesRoute ApiOgThreadIdRoute: typeof ApiOgThreadIdRoute } @@ -844,6 +921,41 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AppUsersUserIdRouteImport parentRoute: typeof AppRoute } + '/api/app/comments': { + id: '/api/app/comments' + path: '/api/app/comments' + fullPath: '/api/app/comments' + preLoaderRoute: typeof ApiAppCommentsRouteImport + parentRoute: typeof rootRouteImport + } + '/api/app/session': { + id: '/api/app/session' + path: '/api/app/session' + fullPath: '/api/app/session' + preLoaderRoute: typeof ApiAppSessionRouteImport + parentRoute: typeof rootRouteImport + } + '/api/app/submit': { + id: '/api/app/submit' + path: '/api/app/submit' + fullPath: '/api/app/submit' + preLoaderRoute: typeof ApiAppSubmitRouteImport + parentRoute: typeof rootRouteImport + } + '/api/app/vote': { + id: '/api/app/vote' + path: '/api/app/vote' + fullPath: '/api/app/vote' + preLoaderRoute: typeof ApiAppVoteRouteImport + parentRoute: typeof rootRouteImport + } + '/api/app/votes': { + id: '/api/app/votes' + path: '/api/app/votes' + fullPath: '/api/app/votes' + preLoaderRoute: typeof ApiAppVotesRouteImport + parentRoute: typeof rootRouteImport + } '/api/digest/preview': { id: '/api/digest/preview' path: '/preview' @@ -879,6 +991,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AppUsersUserIdFollowingRouteImport parentRoute: typeof AppUsersUserIdRoute } + '/api/app/comments/$id': { + id: '/api/app/comments/$id' + path: '/$id' + fullPath: '/api/app/comments/$id' + preLoaderRoute: typeof ApiAppCommentsIdRouteImport + parentRoute: typeof ApiAppCommentsRoute + } '/api/og/thread/$id': { id: '/api/og/thread/$id' path: '/api/og/thread/$id' @@ -1001,6 +1120,18 @@ const ApiDigestRouteWithChildren = ApiDigestRoute._addFileChildren( ApiDigestRouteChildren, ) +interface ApiAppCommentsRouteChildren { + ApiAppCommentsIdRoute: typeof ApiAppCommentsIdRoute +} + +const ApiAppCommentsRouteChildren: ApiAppCommentsRouteChildren = { + ApiAppCommentsIdRoute: ApiAppCommentsIdRoute, +} + +const ApiAppCommentsRouteWithChildren = ApiAppCommentsRoute._addFileChildren( + ApiAppCommentsRouteChildren, +) + const rootRouteChildren: RootRouteChildren = { AppRoute: AppRouteWithChildren, AuthRoute: AuthRouteWithChildren, @@ -1013,6 +1144,11 @@ const rootRouteChildren: RootRouteChildren = { FeedsSplatRoute: FeedsSplatRoute, SitemapsFileRoute: SitemapsFileRoute, USplatRoute: USplatRoute, + ApiAppCommentsRoute: ApiAppCommentsRouteWithChildren, + ApiAppSessionRoute: ApiAppSessionRoute, + ApiAppSubmitRoute: ApiAppSubmitRoute, + ApiAppVoteRoute: ApiAppVoteRoute, + ApiAppVotesRoute: ApiAppVotesRoute, ApiOgThreadIdRoute: ApiOgThreadIdRoute, } export const routeTree = rootRouteImport diff --git a/src/routes/api/app.comments.$id.ts b/src/routes/api/app.comments.$id.ts new file mode 100644 index 0000000..ebd72a1 --- /dev/null +++ b/src/routes/api/app.comments.$id.ts @@ -0,0 +1,21 @@ +import { createFileRoute } from '@tanstack/react-router' +import { z } from 'zod' + +/** Delete one of your own comments. */ +export const Route = createFileRoute('/api/app/comments/$id')({ + server: { + handlers: { + DELETE: async ({ request, params }) => { + const [{ handleAppRequest }, { isValidId }, { removeComment }] = await Promise.all([ + import('@/server/app-api.server'), + import('@/lib/url'), + import('@/server/comments.server'), + ]) + return handleAppRequest(request, z.object({}), async (_input, { user }) => { + if (!isValidId(params.id)) return { ok: false, error: 'This comment no longer exists.' } + return removeComment(user, params.id) + }) + }, + }, + }, +}) diff --git a/src/routes/api/app.comments.ts b/src/routes/api/app.comments.ts new file mode 100644 index 0000000..ca3a8f6 --- /dev/null +++ b/src/routes/api/app.comments.ts @@ -0,0 +1,17 @@ +import { createFileRoute } from '@tanstack/react-router' + +/** Add a comment or a reply; answers the new comment. */ +export const Route = createFileRoute('/api/app/comments')({ + server: { + handlers: { + POST: async ({ request }) => { + const [{ handleAppRequest }, { commentInput }, { createComment }] = await Promise.all([ + import('@/server/app-api.server'), + import('@/lib/app-api'), + import('@/server/comments.server'), + ]) + return handleAppRequest(request, commentInput, (input, { user }) => createComment(user, input)) + }, + }, + }, +}) diff --git a/src/routes/api/app.session.ts b/src/routes/api/app.session.ts new file mode 100644 index 0000000..fb5ac5a --- /dev/null +++ b/src/routes/api/app.session.ts @@ -0,0 +1,27 @@ +import { createFileRoute } from '@tanstack/react-router' +import { z } from 'zod' + +/** + * The app calls this right after signing in: it creates or renames the + * person's profile, as `establishSession` does for the website. + */ +export const Route = createFileRoute('/api/app/session')({ + server: { + handlers: { + POST: async ({ request }) => { + const [{ handleAppRequest }, { syncProfile }] = await Promise.all([ + import('@/server/app-api.server'), + import('@/server/profiles.server'), + ]) + return handleAppRequest( + request, + z.object({}).passthrough(), + async (_input, { user, registration }) => { + await syncProfile(user, registration) + return { ok: true, data: { user } } + }, + ) + }, + }, + }, +}) diff --git a/src/routes/api/app.submit.ts b/src/routes/api/app.submit.ts new file mode 100644 index 0000000..0a8af9c --- /dev/null +++ b/src/routes/api/app.submit.ts @@ -0,0 +1,17 @@ +import { createFileRoute } from '@tanstack/react-router' + +/** Submit a story; answers its id (409 with `existingId` when it was already shared). */ +export const Route = createFileRoute('/api/app/submit')({ + server: { + handlers: { + POST: async ({ request }) => { + const [{ handleAppRequest }, { submitInput }, { createPost }] = await Promise.all([ + import('@/server/app-api.server'), + import('@/lib/app-api'), + import('@/server/posts.server'), + ]) + return handleAppRequest(request, submitInput, (input, { user }) => createPost(user, input)) + }, + }, + }, +}) diff --git a/src/routes/api/app.vote.ts b/src/routes/api/app.vote.ts new file mode 100644 index 0000000..5057554 --- /dev/null +++ b/src/routes/api/app.vote.ts @@ -0,0 +1,19 @@ +import { createFileRoute } from '@tanstack/react-router' + +/** Cast, flip or remove a vote; answers the new vote and score. */ +export const Route = createFileRoute('/api/app/vote')({ + server: { + handlers: { + POST: async ({ request }) => { + const [{ handleAppRequest }, { voteInput }, { castVote }] = await Promise.all([ + import('@/server/app-api.server'), + import('@/lib/app-api'), + import('@/server/votes.server'), + ]) + return handleAppRequest(request, voteInput, (input, { user }) => + castVote(user, input.resourceType, input.resourceId, input.direction), + ) + }, + }, + }, +}) diff --git a/src/routes/api/app.votes.ts b/src/routes/api/app.votes.ts new file mode 100644 index 0000000..865a40f --- /dev/null +++ b/src/routes/api/app.votes.ts @@ -0,0 +1,26 @@ +import { createFileRoute } from '@tanstack/react-router' + +/** The signed-in person's votes on the given posts and comments (votes are private). */ +export const Route = createFileRoute('/api/app/votes')({ + server: { + handlers: { + POST: async ({ request }) => { + const [{ handleAppRequest }, { voteLookupInput }, { getUserVotes }] = await Promise.all([ + import('@/server/app-api.server'), + import('@/lib/app-api'), + import('@/server/db.server'), + ]) + return handleAppRequest(request, voteLookupInput, async (input, { user }) => { + const [posts, comments] = await Promise.all([ + getUserVotes(user.id, 'post', input.posts), + getUserVotes(user.id, 'comment', input.comments), + ]) + return { + ok: true, + data: { posts: Object.fromEntries(posts), comments: Object.fromEntries(comments) }, + } + }) + }, + }, + }, +}) diff --git a/src/server/app-api.server.ts b/src/server/app-api.server.ts new file mode 100644 index 0000000..9a7c1c9 --- /dev/null +++ b/src/server/app-api.server.ts @@ -0,0 +1,86 @@ +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 { getModeratorIds, getPublicConfig } from './env.server' +import { MODERATOR_LABELS } from './session.server' + +/* + * Server half of the app API (see src/lib/app-api.ts). Each request carries an + * Appwrite JWT; it is verified with Appwrite (`account.get` as that user), the + * same check `establishSession` does for the website before it issues a cookie. + */ + +export interface AppUser { + user: SessionUser + /** Account registration time, for the profile sync on sign-in. */ + registration: string +} + +/** JWT → verified user, briefly, so a burst of taps doesn't re-verify each time. */ +const VERIFY_TTL_MS = 60_000 +const verified = new Map() + +async function verify(jwt: string): Promise { + const now = Date.now() + const hit = verified.get(jwt) + if (hit && now - hit.at < VERIFY_TTL_MS) return hit.value + + const { appwriteEndpoint, appwriteProjectId } = getPublicConfig() + let account + try { + const client = new Client().setEndpoint(appwriteEndpoint).setProject(appwriteProjectId).setJWT(jwt) + account = await new Account(client).get() + } catch { + verified.delete(jwt) + return null + } + const user: SessionUser = { id: account.$id, name: account.name, email: account.email } + if (account.labels.some((label) => MODERATOR_LABELS.includes(label)) || getModeratorIds().has(user.id)) { + user.moderator = true + } + const value = { user, registration: account.registration } + if (verified.size > 1000) verified.clear() + verified.set(jwt, { at: now, value }) + return value +} + +function json(status: number, body: unknown) { + return Response.json(body, { status, headers: { 'cache-control': 'no-store' } }) +} + +const UNAUTHORIZED = json(401, { error: 'Please sign in to continue.', code: 'unauthorized' }) + +/** + * Authenticate, validate the JSON body against `schema`, run `action`, and + * answer `{ data }` or `{ error, code? }` with a matching status. + */ +export async function handleAppRequest( + request: Request, + schema: S, + action: (input: z.infer, appUser: AppUser) => Promise>, +): Promise { + const token = bearerToken(request.headers.get('authorization')) + if (!token) return UNAUTHORIZED.clone() + const appUser = await verify(token) + if (!appUser) return UNAUTHORIZED.clone() + + let raw: unknown = {} + if (request.method !== 'GET' && request.method !== 'DELETE') { + try { + raw = await request.json() + } catch { + return json(400, { error: 'Send a JSON body.' }) + } + } + const parsed = schema.safeParse(raw) + if (!parsed.success) return json(400, { error: validationMessage(parsed.error) }) + + try { + const { status, body } = toAppResponse(await action(parsed.data, appUser)) + return json(status, body) + } catch (error) { + console.error('[app-api]', new URL(request.url).pathname, error) + return json(500, { error: 'Something went wrong. Please try again.' }) + } +} From ab21cbb5878c2c346661c126644da9ef0cf32479 Mon Sep 17 00:00:00 2001 From: Damodar Lohani Date: Sun, 8 Nov 2026 10:54:18 +0545 Subject: [PATCH 2/2] Format two files prettier flags on main CI's format:check fails on main because of these two files; this is prettier --write on them and nothing else. Co-Authored-By: Claude Opus 5.5 --- src/api/moderation.ts | 9 +++++++-- src/components/layout/navigation.tsx | 5 +---- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/api/moderation.ts b/src/api/moderation.ts index 7a0b606..37757ba 100644 --- a/src/api/moderation.ts +++ b/src/api/moderation.ts @@ -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') @@ -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 => { const user = await getSessionUser({ fresh: true }) diff --git a/src/components/layout/navigation.tsx b/src/components/layout/navigation.tsx index f552fe9..2625f1e 100644 --- a/src/components/layout/navigation.tsx +++ b/src/components/layout/navigation.tsx @@ -67,10 +67,7 @@ function SidebarChannels({ pathname }: { pathname: string }) { {/* Negative margin + padding leaves room for focus rings inside the scroll clip. */} -