Phase 1: Backend scaffold with Fastify, Prisma, Docker
This commit is contained in:
32
.env.example
Normal file
32
.env.example
Normal file
@@ -0,0 +1,32 @@
|
||||
# Server
|
||||
PORT=3000
|
||||
HOST=0.0.0.0
|
||||
DATABASE_URL="file:../data/lck.db"
|
||||
|
||||
# JWT
|
||||
JWT_SECRET=change-me-to-a-random-64-char-string
|
||||
JWT_ISSUER=lck-control
|
||||
|
||||
# Token Encryption
|
||||
TOKEN_ENCRYPTION_KEY=change-me-to-a-64-hex-char-string-representing-32-bytes
|
||||
|
||||
# Meta OAuth
|
||||
META_APP_ID=your-meta-app-id
|
||||
META_APP_SECRET=your-meta-app-secret
|
||||
META_REDIRECT_URI=https://lck.yourdomain.com/auth/meta/callback-redirect
|
||||
|
||||
# YouTube OAuth
|
||||
YOUTUBE_CLIENT_ID=your-google-client-id
|
||||
YOUTUBE_CLIENT_SECRET=your-google-client-secret
|
||||
YOUTUBE_REDIRECT_URI=https://lck.yourdomain.com/providers/youtube/callback-redirect
|
||||
|
||||
# Twitch OAuth
|
||||
TWITCH_CLIENT_ID=your-twitch-client-id
|
||||
TWITCH_CLIENT_SECRET=your-twitch-client-secret
|
||||
TWITCH_REDIRECT_URI=https://lck.yourdomain.com/providers/twitch/callback-redirect
|
||||
|
||||
# App deep link scheme
|
||||
APP_SCHEME=com.omixlab.lckcontrol
|
||||
|
||||
# CORS
|
||||
CORS_ORIGIN=*
|
||||
11
.gitignore
vendored
Normal file
11
.gitignore
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
node_modules/
|
||||
dist/
|
||||
data/
|
||||
*.db
|
||||
*.db-journal
|
||||
.env
|
||||
.env.local
|
||||
.env.production
|
||||
*.log
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
29
Dockerfile
Normal file
29
Dockerfile
Normal file
@@ -0,0 +1,29 @@
|
||||
FROM node:20-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json* ./
|
||||
RUN npm ci
|
||||
COPY prisma ./prisma
|
||||
RUN npx prisma generate
|
||||
COPY tsconfig.json ./
|
||||
COPY src ./src
|
||||
RUN npm run build
|
||||
|
||||
FROM node:20-alpine AS production
|
||||
|
||||
RUN apk add --no-cache tini
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json package-lock.json* ./
|
||||
RUN npm ci --omit=dev
|
||||
COPY prisma ./prisma
|
||||
RUN npx prisma generate
|
||||
COPY --from=builder /app/dist ./dist
|
||||
|
||||
RUN mkdir -p /app/data
|
||||
|
||||
ENV NODE_ENV=production
|
||||
EXPOSE 3000
|
||||
|
||||
ENTRYPOINT ["/sbin/tini", "--"]
|
||||
CMD ["node", "dist/index.js"]
|
||||
19
docker-compose.yml
Normal file
19
docker-compose.yml
Normal file
@@ -0,0 +1,19 @@
|
||||
services:
|
||||
backend:
|
||||
build: .
|
||||
container_name: lck-control-backend
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "3100:3000"
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
- DATABASE_URL=file:/app/data/lck.db
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://localhost:3000/health"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
2815
package-lock.json
generated
Normal file
2815
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
35
package.json
Normal file
35
package.json
Normal file
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"name": "lck-control-backend",
|
||||
"version": "1.0.0",
|
||||
"description": "LCK Control backend — Meta auth, YouTube/Twitch OAuth, stream management",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js",
|
||||
"db:generate": "prisma generate",
|
||||
"db:push": "prisma db push",
|
||||
"db:migrate": "prisma migrate dev",
|
||||
"db:studio": "prisma studio",
|
||||
"lint": "eslint src/",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cookie": "^11.0.1",
|
||||
"@fastify/cors": "^10.0.1",
|
||||
"@fastify/rate-limit": "^10.2.1",
|
||||
"@prisma/client": "^6.4.1",
|
||||
"fastify": "^5.2.1",
|
||||
"fastify-plugin": "^5.0.1",
|
||||
"jose": "^6.0.8",
|
||||
"undici": "^7.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.13.4",
|
||||
"prisma": "^6.4.1",
|
||||
"tsx": "^4.19.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^3.0.5"
|
||||
}
|
||||
}
|
||||
85
prisma/schema.prisma
Normal file
85
prisma/schema.prisma
Normal file
@@ -0,0 +1,85 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "sqlite"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(uuid())
|
||||
metaId String @unique
|
||||
displayName String
|
||||
email String?
|
||||
avatarUrl String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
linkedAccounts LinkedAccount[]
|
||||
streamPlans StreamPlan[]
|
||||
sessions Session[]
|
||||
}
|
||||
|
||||
model Session {
|
||||
id String @id @default(uuid())
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
refreshToken String @unique
|
||||
expiresAt DateTime
|
||||
deviceInfo String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([userId])
|
||||
}
|
||||
|
||||
model LinkedAccount {
|
||||
id String @id @default(uuid())
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
serviceId String
|
||||
displayName String
|
||||
accountId String
|
||||
avatarUrl String?
|
||||
accessTokenEnc String
|
||||
refreshTokenEnc String
|
||||
tokenExpiresAt DateTime
|
||||
accessTokenIv String
|
||||
refreshTokenIv String
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([userId, serviceId])
|
||||
@@index([userId])
|
||||
}
|
||||
|
||||
model StreamPlan {
|
||||
id String @id @default(uuid())
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
name String
|
||||
status String @default("DRAFT")
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
destinations StreamDestination[]
|
||||
|
||||
@@index([userId])
|
||||
}
|
||||
|
||||
model StreamDestination {
|
||||
id String @id @default(uuid())
|
||||
planId String
|
||||
plan StreamPlan @relation(fields: [planId], references: [id], onDelete: Cascade)
|
||||
serviceId String
|
||||
title String
|
||||
description String @default("")
|
||||
privacyStatus String @default("public")
|
||||
gameId String @default("")
|
||||
tags String @default("")
|
||||
rtmpUrl String @default("")
|
||||
streamKey String @default("")
|
||||
broadcastId String @default("")
|
||||
status String @default("PENDING")
|
||||
|
||||
@@index([planId])
|
||||
}
|
||||
26
src/app.ts
Normal file
26
src/app.ts
Normal 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
44
src/config.ts
Normal 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
16
src/index.ts
Normal 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();
|
||||
16
src/middleware/require-auth.ts
Normal file
16
src/middleware/require-auth.ts
Normal 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
35
src/plugins/auth.ts
Normal 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' });
|
||||
41
src/plugins/error-handler.ts
Normal file
41
src/plugins/error-handler.ts
Normal 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
21
src/plugins/prisma.ts
Normal 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
9
src/routes/health.ts
Normal 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
91
src/types/api.ts
Normal 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;
|
||||
}
|
||||
20
tsconfig.json
Normal file
20
tsconfig.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "Node16",
|
||||
"moduleResolution": "Node16",
|
||||
"lib": ["ES2022"],
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
Reference in New Issue
Block a user