Files
musicshare/apps/api/src/app.ts
T
chrisandClaude Opus 5.5 5cbde5e7f9 The Android app updates itself from our Gitea releases; feed cards fade in instead of bouncing
- API: GET /app/android/latest reads the latest Gitea release (ANDROID_RELEASES_URL, optional token for a
  private repo) with the APK's SHA-256 from SHA256SUMS; GET /app/android/apk/:name streams that APK.
- App (modules/updater): downloads in the background, checks the SHA-256, and installs through
  PackageInstaller: quietly once when leaving the app (Android 12+), otherwise from the feed banner or
  Settings > App version. F-Droid builds leave it out and drop the install permissions.
- CI: the release notes come from the fastlane changelog; the app shows the part above ---.
- Settings: Create-account and Link Spotify buttons for Last.fm and ListenBrainz.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 12:34:04 -04:00

91 lines
3.5 KiB
TypeScript

import cookie from '@fastify/cookie';
import cors from '@fastify/cors';
import rateLimit from '@fastify/rate-limit';
import multipart from '@fastify/multipart';
import websocket from '@fastify/websocket';
import Fastify from 'fastify';
import { ZodError } from 'zod';
import { sql } from './db';
import { env } from './env';
import { loadUser } from './lib/auth';
import { HttpError } from './lib/http';
import { redis } from './lib/redis';
import { adminRoutes } from './routes/admin';
import { appUpdateRoutes } from './routes/appUpdates';
import { accountRoutes } from './routes/account';
import { authRoutes } from './routes/auth';
import { avatarRoutes } from './routes/avatars';
import { connectionRoutes } from './routes/connections';
import { deviceRoutes } from './routes/devices';
import { meRoutes } from './routes/me';
import { reactionRoutes } from './routes/reactions';
import { notificationRoutes } from './routes/notifications';
import { realtimeRoutes } from './routes/realtime';
import { safetyRoutes } from './routes/safety';
import { trackRoutes } from './routes/tracks';
import { userRoutes } from './routes/users';
import { webhookRoutes } from './routes/webhooks';
/** Builds the API without listening, so tests can drive it with app.inject(). */
export async function buildApp({ logger = true, rateLimits = true }: { logger?: boolean; rateLimits?: boolean } = {}) {
const app = Fastify({
logger,
trustProxy: true,
// Serve /api/... as well as /..., so a reverse proxy can forward /api/ with or without stripping it.
rewriteUrl: (req) => {
const url = req.url ?? '/';
return url === '/api' || url.startsWith('/api/') || url.startsWith('/api?') ? url.slice(4) || '/' : url;
},
});
await app.register(cors, {
origin: [env.WEB_URL],
credentials: true,
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
});
await app.register(cookie);
// Rate limits are per-route (see `config.rateLimit`); the Redis store makes them global across instances.
if (rateLimits) await app.register(rateLimit, { global: false, redis });
await app.register(websocket);
await app.register(multipart);
app.decorateRequest('user', null);
app.decorateRequest('sessionId', null);
app.addHook('onRequest', loadUser);
app.setErrorHandler((err, req, reply) => {
if (err instanceof ZodError) {
return reply.status(400).send({ error: err.issues[0]?.message ?? 'Invalid input', issues: err.issues });
}
if (err instanceof HttpError) return reply.status(err.status).send({ error: err.message });
const status = (err as { statusCode?: number }).statusCode;
if (status && status < 500) return reply.status(status).send({ error: (err as Error).message });
req.log.error(err);
return reply.status(500).send({ error: 'Internal server error' });
});
app.get('/health', async () => {
await Promise.all([sql`select 1`, redis.ping()]);
return { ok: true };
});
await app.register(authRoutes);
await app.register(accountRoutes);
await app.register(meRoutes);
await app.register(avatarRoutes);
await app.register(userRoutes);
await app.register(safetyRoutes);
await app.register(adminRoutes);
await app.register(trackRoutes);
await app.register(reactionRoutes);
await app.register(notificationRoutes);
await app.register(connectionRoutes);
await app.register(deviceRoutes);
await app.register(realtimeRoutes);
await app.register(appUpdateRoutes);
// registered as its own plugin so its permissive body parsers stay scoped to webhook routes
await app.register(webhookRoutes);
return app;
}