Phase 1: Backend scaffold with Fastify, Prisma, Docker

This commit is contained in:
2026-02-23 15:26:50 +01:00
commit 8ea3279c3b
17 changed files with 3345 additions and 0 deletions

26
src/app.ts Normal file
View File

@@ -0,0 +1,26 @@
import Fastify from 'fastify';
import cors from '@fastify/cors';
import prismaPlugin from './plugins/prisma.js';
import errorHandlerPlugin from './plugins/error-handler.js';
import authPlugin from './plugins/auth.js';
import healthRoutes from './routes/health.js';
import { config } from './config.js';
export async function buildApp() {
const app = Fastify({
logger: {
level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
},
});
// Plugins
await app.register(cors, { origin: config.corsOrigin });
await app.register(errorHandlerPlugin);
await app.register(prismaPlugin);
await app.register(authPlugin);
// Routes
await app.register(healthRoutes);
return app;
}

44
src/config.ts Normal file
View File

@@ -0,0 +1,44 @@
function required(key: string): string {
const value = process.env[key];
if (!value) throw new Error(`Missing required env var: ${key}`);
return value;
}
function optional(key: string, fallback: string): string {
return process.env[key] || fallback;
}
export const config = {
port: parseInt(optional('PORT', '3000'), 10),
host: optional('HOST', '0.0.0.0'),
jwt: {
secret: required('JWT_SECRET'),
issuer: optional('JWT_ISSUER', 'lck-control'),
accessTtl: 15 * 60, // 15 minutes
refreshTtl: 30 * 24 * 3600, // 30 days
},
tokenEncryptionKey: required('TOKEN_ENCRYPTION_KEY'),
meta: {
appId: required('META_APP_ID'),
appSecret: required('META_APP_SECRET'),
redirectUri: required('META_REDIRECT_URI'),
},
youtube: {
clientId: required('YOUTUBE_CLIENT_ID'),
clientSecret: required('YOUTUBE_CLIENT_SECRET'),
redirectUri: required('YOUTUBE_REDIRECT_URI'),
},
twitch: {
clientId: required('TWITCH_CLIENT_ID'),
clientSecret: required('TWITCH_CLIENT_SECRET'),
redirectUri: required('TWITCH_REDIRECT_URI'),
},
appScheme: optional('APP_SCHEME', 'com.omixlab.lckcontrol'),
corsOrigin: optional('CORS_ORIGIN', '*'),
} as const;

16
src/index.ts Normal file
View File

@@ -0,0 +1,16 @@
import { buildApp } from './app.js';
import { config } from './config.js';
async function main() {
const app = await buildApp();
try {
await app.listen({ port: config.port, host: config.host });
app.log.info(`Server listening on ${config.host}:${config.port}`);
} catch (err) {
app.log.error(err);
process.exit(1);
}
}
main();

View File

@@ -0,0 +1,16 @@
import { FastifyRequest, FastifyReply } from 'fastify';
import { verifyAccessToken } from '../plugins/auth.js';
export async function requireAuth(request: FastifyRequest, reply: FastifyReply) {
const header = request.headers.authorization;
if (!header?.startsWith('Bearer ')) {
reply.status(401).send({ error: 'Missing or invalid authorization header' });
return;
}
try {
request.userId = await verifyAccessToken(header.slice(7));
} catch {
reply.status(401).send({ error: 'Invalid or expired token' });
}
}

35
src/plugins/auth.ts Normal file
View File

@@ -0,0 +1,35 @@
import { FastifyPluginAsync, FastifyRequest } from 'fastify';
import fp from 'fastify-plugin';
import * as jose from 'jose';
import { config } from '../config.js';
declare module 'fastify' {
interface FastifyRequest {
userId: string;
}
}
const secret = new TextEncoder().encode(config.jwt.secret);
export async function signAccessToken(userId: string): Promise<string> {
return new jose.SignJWT({ sub: userId })
.setProtectedHeader({ alg: 'HS256' })
.setIssuer(config.jwt.issuer)
.setIssuedAt()
.setExpirationTime(`${config.jwt.accessTtl}s`)
.sign(secret);
}
export async function verifyAccessToken(token: string): Promise<string> {
const { payload } = await jose.jwtVerify(token, secret, {
issuer: config.jwt.issuer,
});
if (!payload.sub) throw new Error('Invalid token: missing sub');
return payload.sub;
}
const authPlugin: FastifyPluginAsync = async (fastify) => {
fastify.decorateRequest('userId', '');
};
export default fp(authPlugin, { name: 'auth' });

View File

@@ -0,0 +1,41 @@
import { FastifyPluginAsync, FastifyError } from 'fastify';
import fp from 'fastify-plugin';
export class AppError extends Error {
constructor(
public statusCode: number,
message: string,
) {
super(message);
this.name = 'AppError';
}
}
const errorHandlerPlugin: FastifyPluginAsync = async (fastify) => {
fastify.setErrorHandler((error: FastifyError | AppError, _request, reply) => {
if (error instanceof AppError) {
reply.status(error.statusCode).send({
error: error.message,
});
return;
}
// Fastify validation errors
if (error.validation) {
reply.status(400).send({
error: 'Validation failed',
details: error.validation,
});
return;
}
fastify.log.error(error);
reply.status(error.statusCode ?? 500).send({
error: error.statusCode && error.statusCode < 500
? error.message
: 'Internal server error',
});
});
};
export default fp(errorHandlerPlugin, { name: 'error-handler' });

21
src/plugins/prisma.ts Normal file
View File

@@ -0,0 +1,21 @@
import { FastifyPluginAsync } from 'fastify';
import fp from 'fastify-plugin';
import { PrismaClient } from '@prisma/client';
declare module 'fastify' {
interface FastifyInstance {
prisma: PrismaClient;
}
}
const prismaPlugin: FastifyPluginAsync = async (fastify) => {
const prisma = new PrismaClient();
await prisma.$connect();
fastify.decorate('prisma', prisma);
fastify.addHook('onClose', async () => {
await prisma.$disconnect();
});
};
export default fp(prismaPlugin, { name: 'prisma' });

9
src/routes/health.ts Normal file
View File

@@ -0,0 +1,9 @@
import { FastifyPluginAsync } from 'fastify';
const healthRoutes: FastifyPluginAsync = async (fastify) => {
fastify.get('/health', async () => {
return { status: 'ok', timestamp: new Date().toISOString() };
});
};
export default healthRoutes;

91
src/types/api.ts Normal file
View File

@@ -0,0 +1,91 @@
// ── Auth ──────────────────────────────────────────────────
export interface MetaCallbackBody {
code: string;
deviceInfo?: string;
}
export interface RefreshBody {
refreshToken: string;
}
export interface AuthTokensResponse {
accessToken: string;
refreshToken: string;
expiresIn: number;
}
export interface UserProfileResponse {
id: string;
displayName: string;
email: string | null;
avatarUrl: string | null;
}
// ── Providers ────────────────────────────────────────────
export interface AuthUrlResponse {
url: string;
state: string;
}
export interface ProviderCallbackBody {
code: string;
state: string;
}
export interface LinkedAccountResponse {
id: string;
serviceId: string;
displayName: string;
accountId: string;
avatarUrl: string | null;
}
// ── Streams ──────────────────────────────────────────────
export interface CreateStreamPlanBody {
name: string;
destinations: CreateDestinationBody[];
}
export interface CreateDestinationBody {
serviceId: string;
title: string;
description?: string;
privacyStatus?: string;
gameId?: string;
tags?: string;
}
export interface StreamPlanResponse {
id: string;
name: string;
status: string;
createdAt: string;
updatedAt: string;
destinations: StreamDestinationResponse[];
}
export interface StreamDestinationResponse {
id: string;
serviceId: string;
title: string;
description: string;
privacyStatus: string;
gameId: string;
tags: string;
rtmpUrl: string;
streamKey: string;
broadcastId: string;
status: string;
}
export interface PrepareResponse {
planId: string;
destinations: PreparedDestination[];
}
export interface PreparedDestination {
serviceId: string;
rtmpUrl: string;
streamKey: string;
broadcastId: string;
}