Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix: secure media server and invite decline
Richie McIlroy5e36845a9fad
diff --git a/apps/media-server/src/__tests__/routes/audio-memory.test.ts b/apps/media-server/src/__tests__/routes/audio-memory.test.tsindex 4bea5cd88..3d8799f2f 100644--- a/apps/media-server/src/__tests__/routes/audio-memory.test.ts+++ b/apps/media-server/src/__tests__/routes/audio-memory.test.ts@@ -4,6 +4,21 @@ import { getActiveProcessCount } from "../../lib/ffmpeg";const FIXTURES_DIR = join(import.meta.dir, "..", "fixtures");const TEST_VIDEO_WITH_AUDIO = `file://${join(FIXTURES_DIR, "test-with-audio.mp4")}`;+const MEDIA_SERVER_SECRET = "test-secret";+const AUTH_HEADERS = {+ "Content-Type": "application/json",+ "x-media-server-secret": MEDIA_SERVER_SECRET,+};++process.env.MEDIA_SERVER_WEBHOOK_SECRET = MEDIA_SERVER_SECRET;++function audioPostRequest(path: string, body: unknown): Request {+ return new Request(`http://localhost${path}`, {+ method: "POST",+ headers: AUTH_HEADERS,+ body: JSON.stringify(body),+ });+}async function waitForProcessCleanup(expectedCount: number,@@ -41,11 +56,7 @@ describe("audio routes memory management", () => {test("cleans up after successful check", async () => {const app = await getFreshApp();const response = await app.fetch(- new Request("http://localhost/audio/check", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ videoUrl: TEST_VIDEO_WITH_AUDIO }),- }),+ audioPostRequest("/audio/check", { videoUrl: TEST_VIDEO_WITH_AUDIO }),);expect(response.status).toBe(200);@@ -59,11 +70,7 @@ describe("audio routes memory management", () => {const app = await getFreshApp();const requests = Array.from({ length: 5 }, () =>app.fetch(- new Request("http://localhost/audio/check", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ videoUrl: TEST_VIDEO_WITH_AUDIO }),- }),+ audioPostRequest("/audio/check", { videoUrl: TEST_VIDEO_WITH_AUDIO }),),);@@ -82,13 +89,9 @@ describe("audio routes memory management", () => {test("cleans up after stream is fully consumed", async () => {const app = await getFreshApp();const response = await app.fetch(- new Request("http://localhost/audio/extract", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- videoUrl: TEST_VIDEO_WITH_AUDIO,- stream: true,- }),+ audioPostRequest("/audio/extract", {+ videoUrl: TEST_VIDEO_WITH_AUDIO,+ stream: true,}),);@@ -107,13 +110,9 @@ describe("audio routes memory management", () => {test("cleans up when stream is cancelled early", async () => {const app = await getFreshApp();const response = await app.fetch(- new Request("http://localhost/audio/extract", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- videoUrl: TEST_VIDEO_WITH_AUDIO,- stream: true,- }),+ audioPostRequest("/audio/extract", {+ videoUrl: TEST_VIDEO_WITH_AUDIO,+ stream: true,}),);@@ -129,13 +128,9 @@ describe("audio routes memory management", () => {test("cleans up when response body is not read at all", async () => {const app = await getFreshApp();const response = await app.fetch(- new Request("http://localhost/audio/extract", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- videoUrl: TEST_VIDEO_WITH_AUDIO,- stream: true,- }),+ audioPostRequest("/audio/extract", {+ videoUrl: TEST_VIDEO_WITH_AUDIO,+ stream: true,}),);@@ -150,13 +145,9 @@ describe("audio routes memory management", () => {const app = await getFreshApp();const requests = Array.from({ length: 3 }, () =>app.fetch(- new Request("http://localhost/audio/extract", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- videoUrl: TEST_VIDEO_WITH_AUDIO,- stream: true,- }),+ audioPostRequest("/audio/extract", {+ videoUrl: TEST_VIDEO_WITH_AUDIO,+ stream: true,}),),);diff --git a/apps/media-server/src/__tests__/routes/audio.test.ts b/apps/media-server/src/__tests__/routes/audio.test.tsindex cb4c24d38..1b308da9e 100644--- a/apps/media-server/src/__tests__/routes/audio.test.ts+++ b/apps/media-server/src/__tests__/routes/audio.test.ts@@ -2,20 +2,48 @@ import { beforeEach, describe, expect, mock, test } from "bun:test";import app from "../../app";import * as ffmpeg from "../../lib/ffmpeg";+const MEDIA_SERVER_SECRET = "test-secret";+const AUTH_HEADERS = {+ "Content-Type": "application/json",+ "x-media-server-secret": MEDIA_SERVER_SECRET,+};++process.env.MEDIA_SERVER_WEBHOOK_SECRET = MEDIA_SERVER_SECRET;++function audioPostRequest(path: string, body: unknown): Request {+ return new Request(`http://localhost${path}`, {+ method: "POST",+ headers: AUTH_HEADERS,+ body: JSON.stringify(body),+ });+}++function unauthenticatedAudioPostRequest(path: string, body: unknown): Request {+ return new Request(`http://localhost${path}`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ });+}+describe("POST /audio/check", () => {beforeEach(() => {mock.restore();});- test("returns 400 for missing videoUrl", async () => {+ test("returns 401 without media server secret", async () => {const response = await app.fetch(- new Request("http://localhost/audio/check", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({}),+ unauthenticatedAudioPostRequest("/audio/check", {+ videoUrl: "https://example.com/video.mp4",}),);+ expect(response.status).toBe(401);+ });++ test("returns 400 for missing videoUrl", async () => {+ const response = await app.fetch(audioPostRequest("/audio/check", {}));+expect(response.status).toBe(400);const data = await response.json();expect(data.code).toBe("INVALID_REQUEST");@@ -23,11 +51,7 @@ describe("POST /audio/check", () => {test("returns 400 for invalid URL format", async () => {const response = await app.fetch(- new Request("http://localhost/audio/check", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ videoUrl: "not-a-valid-url" }),- }),+ audioPostRequest("/audio/check", { videoUrl: "not-a-valid-url" }),);expect(response.status).toBe(400);@@ -44,10 +68,8 @@ describe("POST /audio/check", () => {const { default: appWithMock } = await import("../../app");const response = await appWithMock.fetch(- new Request("http://localhost/audio/check", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ videoUrl: "https://example.com/video.mp4" }),+ audioPostRequest("/audio/check", {+ videoUrl: "https://example.com/video.mp4",}),);@@ -65,10 +87,8 @@ describe("POST /audio/check", () => {const { default: appWithMock } = await import("../../app");const response = await appWithMock.fetch(- new Request("http://localhost/audio/check", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ videoUrl: "https://example.com/video.mp4" }),+ audioPostRequest("/audio/check", {+ videoUrl: "https://example.com/video.mp4",}),);@@ -83,15 +103,19 @@ describe("POST /audio/extract", () => {mock.restore();});- test("returns 400 for missing videoUrl", async () => {+ test("returns 401 without media server secret", async () => {const response = await app.fetch(- new Request("http://localhost/audio/extract", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({}),+ unauthenticatedAudioPostRequest("/audio/extract", {+ videoUrl: "https://example.com/video.mp4",}),);+ expect(response.status).toBe(401);+ });++ test("returns 400 for missing videoUrl", async () => {+ const response = await app.fetch(audioPostRequest("/audio/extract", {}));+expect(response.status).toBe(400);const data = await response.json();expect(data.code).toBe("INVALID_REQUEST");@@ -99,11 +123,7 @@ describe("POST /audio/extract", () => {test("returns 400 for invalid URL format", async () => {const response = await app.fetch(- new Request("http://localhost/audio/extract", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ videoUrl: "invalid-url" }),- }),+ audioPostRequest("/audio/extract", { videoUrl: "invalid-url" }),);expect(response.status).toBe(400);@@ -120,10 +140,8 @@ describe("POST /audio/extract", () => {const { default: appWithMock } = await import("../../app");const response = await appWithMock.fetch(- new Request("http://localhost/audio/extract", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ videoUrl: "https://example.com/video.mp4" }),+ audioPostRequest("/audio/extract", {+ videoUrl: "https://example.com/video.mp4",}),);@@ -143,13 +161,9 @@ describe("POST /audio/extract", () => {const { default: appWithMock } = await import("../../app");const response = await appWithMock.fetch(- new Request("http://localhost/audio/extract", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- videoUrl: "https://example.com/video.mp4",- stream: false,- }),+ audioPostRequest("/audio/extract", {+ videoUrl: "https://example.com/video.mp4",+ stream: false,}),);@@ -174,13 +188,9 @@ describe("POST /audio/extract", () => {const { default: appWithMock } = await import("../../app");const response = await appWithMock.fetch(- new Request("http://localhost/audio/extract", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- videoUrl: "https://example.com/video.mp4",- stream: false,- }),+ audioPostRequest("/audio/extract", {+ videoUrl: "https://example.com/video.mp4",+ stream: false,}),);@@ -190,3 +200,61 @@ describe("POST /audio/extract", () => {expect(data.details).toContain("FFmpeg failed");});});++describe("POST /audio/convert", () => {+ beforeEach(() => {+ mock.restore();+ });++ test("returns 401 without media server secret", async () => {+ const response = await app.fetch(+ unauthenticatedAudioPostRequest("/audio/convert", {+ audioUrl: "https://example.com/audio.wav",+ }),+ );++ expect(response.status).toBe(401);+ });++ test("returns 400 for missing audioUrl", async () => {+ const response = await app.fetch(audioPostRequest("/audio/convert", {}));++ expect(response.status).toBe(400);+ const data = await response.json();+ expect(data.code).toBe("INVALID_REQUEST");+ });++ test("returns audio stream when conversion succeeds", async () => {+ const mockAudioData = new Uint8Array([0x49, 0x44, 0x33]);++ mock.module("../../lib/ffmpeg", () => ({+ canAcceptNewProcess: ffmpeg.canAcceptNewProcess,+ checkHasAudioTrack: ffmpeg.checkHasAudioTrack,+ extractAudio: ffmpeg.extractAudio,+ extractAudioStream: () => ({+ stream: new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(mockAudioData);+ controller.close();+ },+ }),+ cleanup: () => {},+ }),+ getActiveProcessCount: ffmpeg.getActiveProcessCount,+ }));++ const { default: appWithMock } = await import("../../app");++ const response = await appWithMock.fetch(+ audioPostRequest("/audio/convert", {+ audioUrl: "https://example.com/audio.wav",+ }),+ );++ expect(response.status).toBe(200);+ expect(response.headers.get("Content-Type")).toBe("audio/mpeg");++ const buffer = await response.arrayBuffer();+ expect(new Uint8Array(buffer)).toEqual(mockAudioData);+ });+});diff --git a/apps/media-server/src/__tests__/routes/video.test.ts b/apps/media-server/src/__tests__/routes/video.test.tsindex ecbed7319..a5e9a999a 100644--- a/apps/media-server/src/__tests__/routes/video.test.ts+++ b/apps/media-server/src/__tests__/routes/video.test.ts@@ -4,6 +4,30 @@ import * as ffmpegVideo from "../../lib/ffmpeg-video";import * as ffprobe from "../../lib/ffprobe";import * as jobManager from "../../lib/job-manager";+const MEDIA_SERVER_SECRET = "test-secret";+const AUTH_HEADERS = {+ "Content-Type": "application/json",+ "x-media-server-secret": MEDIA_SERVER_SECRET,+};++process.env.MEDIA_SERVER_WEBHOOK_SECRET = MEDIA_SERVER_SECRET;++function videoPostRequest(path: string, body: unknown): Request {+ return new Request(`http://localhost${path}`, {+ method: "POST",+ headers: AUTH_HEADERS,+ body: JSON.stringify(body),+ });+}++function unauthenticatedVideoPostRequest(path: string, body: unknown): Request {+ return new Request(`http://localhost${path}`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ });+}+describe("GET /video/status", () => {test("returns server status", async () => {const response = await app.fetch(@@ -29,15 +53,19 @@ describe("POST /video/probe", () => {mock.restore();});- test("returns 400 for missing videoUrl", async () => {+ test("returns 401 without media server secret", async () => {const response = await app.fetch(- new Request("http://localhost/video/probe", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({}),+ unauthenticatedVideoPostRequest("/video/probe", {+ videoUrl: "https://example.com/video.mp4",}),);+ expect(response.status).toBe(401);+ });++ test("returns 400 for missing videoUrl", async () => {+ const response = await app.fetch(videoPostRequest("/video/probe", {}));+expect(response.status).toBe(400);const data = await response.json();expect(data.code).toBe("INVALID_REQUEST");@@ -45,11 +73,7 @@ describe("POST /video/probe", () => {test("returns 400 for invalid URL format", async () => {const response = await app.fetch(- new Request("http://localhost/video/probe", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ videoUrl: "not-a-valid-url" }),- }),+ videoPostRequest("/video/probe", { videoUrl: "not-a-valid-url" }),);expect(response.status).toBe(400);@@ -80,10 +104,8 @@ describe("POST /video/probe", () => {const { default: appWithMock } = await import("../../app");const response = await appWithMock.fetch(- new Request("http://localhost/video/probe", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ videoUrl: "https://example.com/video.mp4" }),+ videoPostRequest("/video/probe", {+ videoUrl: "https://example.com/video.mp4",}),);@@ -104,10 +126,8 @@ describe("POST /video/probe", () => {const { default: appWithMock } = await import("../../app");const response = await appWithMock.fetch(- new Request("http://localhost/video/probe", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ videoUrl: "https://example.com/video.mp4" }),+ videoPostRequest("/video/probe", {+ videoUrl: "https://example.com/video.mp4",}),);@@ -128,10 +148,8 @@ describe("POST /video/probe", () => {const { default: appWithMock } = await import("../../app");const response = await appWithMock.fetch(- new Request("http://localhost/video/probe", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ videoUrl: "https://example.com/video.mp4" }),+ videoPostRequest("/video/probe", {+ videoUrl: "https://example.com/video.mp4",}),);@@ -152,10 +170,8 @@ describe("POST /video/probe", () => {const { default: appWithMock } = await import("../../app");const response = await appWithMock.fetch(- new Request("http://localhost/video/probe", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ videoUrl: "https://example.com/video.mp4" }),+ videoPostRequest("/video/probe", {+ videoUrl: "https://example.com/video.mp4",}),);@@ -171,15 +187,19 @@ describe("POST /video/thumbnail", () => {mock.restore();});- test("returns 400 for missing videoUrl", async () => {+ test("returns 401 without media server secret", async () => {const response = await app.fetch(- new Request("http://localhost/video/thumbnail", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({}),+ unauthenticatedVideoPostRequest("/video/thumbnail", {+ videoUrl: "https://example.com/video.mp4",}),);+ expect(response.status).toBe(401);+ });++ test("returns 400 for missing videoUrl", async () => {+ const response = await app.fetch(videoPostRequest("/video/thumbnail", {}));+expect(response.status).toBe(400);const data = await response.json();expect(data.code).toBe("INVALID_REQUEST");@@ -187,11 +207,7 @@ describe("POST /video/thumbnail", () => {test("returns 400 for invalid URL format", async () => {const response = await app.fetch(- new Request("http://localhost/video/thumbnail", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ videoUrl: "not-a-url" }),- }),+ videoPostRequest("/video/thumbnail", { videoUrl: "not-a-url" }),);expect(response.status).toBe(400);@@ -233,10 +249,8 @@ describe("POST /video/thumbnail", () => {const { default: appWithMock } = await import("../../app");const response = await appWithMock.fetch(- new Request("http://localhost/video/thumbnail", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ videoUrl: "https://example.com/video.mp4" }),+ videoPostRequest("/video/thumbnail", {+ videoUrl: "https://example.com/video.mp4",}),);@@ -256,15 +270,19 @@ describe("POST /video/convert", () => {mock.restore();});- test("returns 400 for missing videoUrl", async () => {+ test("returns 401 without media server secret", async () => {const response = await app.fetch(- new Request("http://localhost/video/convert", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({}),+ unauthenticatedVideoPostRequest("/video/convert", {+ videoUrl: "https://example.com/video.m3u8",}),);+ expect(response.status).toBe(401);+ });++ test("returns 400 for missing videoUrl", async () => {+ const response = await app.fetch(videoPostRequest("/video/convert", {}));+expect(response.status).toBe(400);const data = await response.json();expect(data.code).toBe("INVALID_REQUEST");@@ -314,13 +332,9 @@ describe("POST /video/convert", () => {const { default: appWithMock } = await import("../../app");const response = await appWithMock.fetch(- new Request("http://localhost/video/convert", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- videoUrl: "https://example.com/video.m3u8",- inputExtension: ".m3u8",- }),+ videoPostRequest("/video/convert", {+ videoUrl: "https://example.com/video.m3u8",+ inputExtension: ".m3u8",}),);@@ -341,13 +355,7 @@ describe("POST /video/process", () => {});test("returns 400 for missing required fields", async () => {- const response = await app.fetch(- new Request("http://localhost/video/process", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({}),- }),- );+ const response = await app.fetch(videoPostRequest("/video/process", {}));expect(response.status).toBe(400);const data = await response.json();@@ -356,14 +364,10 @@ describe("POST /video/process", () => {test("returns 400 for missing videoUrl", async () => {const response = await app.fetch(- new Request("http://localhost/video/process", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- videoId: "test-id",- userId: "user-id",- outputPresignedUrl: "https://s3.example.com/output",- }),+ videoPostRequest("/video/process", {+ videoId: "test-id",+ userId: "user-id",+ outputPresignedUrl: "https://s3.example.com/output",}),);@@ -374,15 +378,11 @@ describe("POST /video/process", () => {test("returns 400 for invalid outputPresignedUrl", async () => {const response = await app.fetch(- new Request("http://localhost/video/process", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- videoId: "test-id",- userId: "user-id",- videoUrl: "https://example.com/video.mp4",- outputPresignedUrl: "not-a-url",- }),+ videoPostRequest("/video/process", {+ videoId: "test-id",+ userId: "user-id",+ videoUrl: "https://example.com/video.mp4",+ outputPresignedUrl: "not-a-url",}),);@@ -410,15 +410,11 @@ describe("POST /video/process", () => {const { default: appWithMock } = await import("../../app");const response = await appWithMock.fetch(- new Request("http://localhost/video/process", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- videoId: "test-id",- userId: "user-id",- videoUrl: "https://example.com/video.mp4",- outputPresignedUrl: "https://s3.example.com/output",- }),+ videoPostRequest("/video/process", {+ videoId: "test-id",+ userId: "user-id",+ videoUrl: "https://example.com/video.mp4",+ outputPresignedUrl: "https://s3.example.com/output",}),);@@ -454,15 +450,11 @@ describe("POST /video/process", () => {const { default: appWithMock } = await import("../../app");const response = await appWithMock.fetch(- new Request("http://localhost/video/process", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- videoId: "test-id",- userId: "user-id",- videoUrl: "https://example.com/video.mp4",- outputPresignedUrl: "https://s3.example.com/output",- }),+ videoPostRequest("/video/process", {+ videoId: "test-id",+ userId: "user-id",+ videoUrl: "https://example.com/video.mp4",+ outputPresignedUrl: "https://s3.example.com/output",}),);@@ -562,9 +554,7 @@ describe("POST /video/process/:jobId/cancel", () => {const { default: appWithMock } = await import("../../app");const response = await appWithMock.fetch(- new Request("http://localhost/video/process/nonexistent-job/cancel", {- method: "POST",- }),+ videoPostRequest("/video/process/nonexistent-job/cancel", {}),);expect(response.status).toBe(404);@@ -599,9 +589,7 @@ describe("POST /video/process/:jobId/cancel", () => {const { default: appWithMock } = await import("../../app");const response = await appWithMock.fetch(- new Request("http://localhost/video/process/test-job-id/cancel", {- method: "POST",- }),+ videoPostRequest("/video/process/test-job-id/cancel", {}),);expect(response.status).toBe(400);@@ -644,9 +632,7 @@ describe("POST /video/process/:jobId/cancel", () => {const { default: appWithMock } = await import("../../app");const response = await appWithMock.fetch(- new Request("http://localhost/video/process/test-job-id/cancel", {- method: "POST",- }),+ videoPostRequest("/video/process/test-job-id/cancel", {}),);expect(response.status).toBe(200);@@ -669,9 +655,7 @@ describe("POST /video/cleanup", () => {const { default: appWithMock } = await import("../../app");const response = await appWithMock.fetch(- new Request("http://localhost/video/cleanup", {- method: "POST",- }),+ videoPostRequest("/video/cleanup", {}),);expect(response.status).toBe(200);diff --git a/apps/media-server/src/lib/auth.ts b/apps/media-server/src/lib/auth.tsnew file mode 100644index 000000000..a8e322d28--- /dev/null+++ b/apps/media-server/src/lib/auth.ts@@ -0,0 +1,14 @@+type MediaServerContext = {+ req: { header: (name: string) => string | undefined };+};++export function validateMediaServerSecret(c: MediaServerContext): boolean {+ const secret = process.env.MEDIA_SERVER_WEBHOOK_SECRET;+ if (!secret) {+ console.warn(+ "[media-server] MEDIA_SERVER_WEBHOOK_SECRET is not set — rejecting request. Set this env var to enable authenticated access.",+ );+ return false;+ }+ return c.req.header("x-media-server-secret") === secret;+}diff --git a/apps/media-server/src/routes/audio.ts b/apps/media-server/src/routes/audio.tsindex 350299b75..c8c6424f5 100644--- a/apps/media-server/src/routes/audio.ts+++ b/apps/media-server/src/routes/audio.ts@@ -1,5 +1,6 @@import { Hono } from "hono";import { z } from "zod";+import { validateMediaServerSecret } from "../lib/auth";import {canAcceptNewProcess,checkHasAudioTrack,@@ -41,6 +42,10 @@ audio.get("/status", (c) => {});audio.post("/check", async (c) => {+ if (!validateMediaServerSecret(c)) {+ return c.json({ error: "Unauthorized" }, 401);+ }+const body = await c.req.json();const result = videoUrlSchema.safeParse(body);@@ -95,6 +100,10 @@ audio.post("/check", async (c) => {});audio.post("/extract", async (c) => {+ if (!validateMediaServerSecret(c)) {+ return c.json({ error: "Unauthorized" }, 401);+ }+const body = await c.req.json();const result = extractSchema.safeParse(body);@@ -180,6 +189,10 @@ audio.post("/extract", async (c) => {});audio.post("/convert", async (c) => {+ if (!validateMediaServerSecret(c)) {+ return c.json({ error: "Unauthorized" }, 401);+ }+const body = await c.req.json();const result = convertSchema.safeParse(body);diff --git a/apps/media-server/src/routes/video.ts b/apps/media-server/src/routes/video.tsindex c2dbe4267..f92cae48d 100644--- a/apps/media-server/src/routes/video.ts+++ b/apps/media-server/src/routes/video.ts@@ -1,6 +1,7 @@import { file } from "bun";import { Hono } from "hono";import { z } from "zod";+import { validateMediaServerSecret } from "../lib/auth";import type { ResilientInputFlags } from "../lib/ffmpeg-video";import {downloadVideoToTemp,@@ -37,19 +38,6 @@ import { cleanupStaleTempFiles } from "../lib/temp-files";const video = new Hono();-function validateMediaServerSecret(c: {- req: { header: (name: string) => string | undefined };-}): boolean {- const secret = process.env.MEDIA_SERVER_WEBHOOK_SECRET;- if (!secret) {- console.warn(- "[media-server] MEDIA_SERVER_WEBHOOK_SECRET is not set — rejecting request. Set this env var to enable authenticated access.",- );- return false;- }- return c.req.header("x-media-server-secret") === secret;-}-const probeSchema = z.object({videoUrl: z.string().url(),});@@ -184,6 +172,10 @@ video.get("/status", (c) => {});video.post("/probe", async (c) => {+ if (!validateMediaServerSecret(c)) {+ return c.json({ error: "Unauthorized" }, 401);+ }+const body = await c.req.json();const result = probeSchema.safeParse(body);@@ -238,6 +230,10 @@ video.post("/probe", async (c) => {});video.post("/thumbnail", async (c) => {+ if (!validateMediaServerSecret(c)) {+ return c.json({ error: "Unauthorized" }, 401);+ }+const body = await c.req.json();const result = thumbnailSchema.safeParse(body);@@ -309,6 +305,10 @@ video.post("/thumbnail", async (c) => {});video.post("/convert", async (c) => {+ if (!validateMediaServerSecret(c)) {+ return c.json({ error: "Unauthorized" }, 401);+ }+const body = await c.req.json();const result = convertSchema.safeParse(body);diff --git a/apps/web/__tests__/unit/invite-decline.test.ts b/apps/web/__tests__/unit/invite-decline.test.tsnew file mode 100644index 000000000..3cabd9075--- /dev/null+++ b/apps/web/__tests__/unit/invite-decline.test.ts@@ -0,0 +1,132 @@+import { getCurrentUser } from "@cap/database/auth/session";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mockDb = {+ select: vi.fn(),+ delete: vi.fn(),+ from: vi.fn(),+ where: vi.fn(),+ for: vi.fn(),+ transaction: vi.fn(),+};++vi.mock("@cap/database", () => ({+ db: () => mockDb,+}));++vi.mock("@cap/database/auth/session", () => ({+ getCurrentUser: vi.fn(),+}));++vi.mock("@cap/database/schema", () => ({+ organizationInvites: {+ id: "id",+ invitedEmail: "invitedEmail",+ },+}));++vi.mock("drizzle-orm", () => ({+ eq: vi.fn((field: unknown, value: unknown) => ({ field, value })),+}));++const mockGetCurrentUser = getCurrentUser as ReturnType<typeof vi.fn>;++function resetMockDb() {+ for (const key of Object.keys(mockDb)) {+ const fn = mockDb[key as keyof typeof mockDb];+ if (typeof fn?.mockClear === "function") {+ fn.mockClear();+ }+ }+ mockDb.select.mockReturnValue(mockDb);+ mockDb.delete.mockReturnValue(mockDb);+ mockDb.from.mockReturnValue(mockDb);+ mockDb.where.mockReturnValue(mockDb);+ mockDb.for.mockResolvedValue([]);+ mockDb.transaction.mockImplementation((fn) => fn(mockDb));+}++function makeRequest(body: unknown) {+ return new Request("https://cap.test/api/invite/decline", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ }) as unknown as import("next/server").NextRequest;+}++describe("POST /api/invite/decline", () => {+ let POST: typeof import("@/app/api/invite/decline/route").POST;++ beforeEach(async () => {+ vi.clearAllMocks();+ resetMockDb();+ const mod = await import("@/app/api/invite/decline/route");+ POST = mod.POST;+ });++ it("returns 401 when the requester is not authenticated", async () => {+ mockGetCurrentUser.mockResolvedValue(null);++ const response = await POST(makeRequest({ inviteId: "invite-1" }));++ expect(response.status).toBe(401);+ expect(mockDb.delete).not.toHaveBeenCalled();+ });++ it("returns 400 when inviteId is missing", async () => {+ mockGetCurrentUser.mockResolvedValue({+ id: "user-1",+ email: "[email protected]",+ });++ const response = await POST(makeRequest({}));++ expect(response.status).toBe(400);+ expect(mockDb.delete).not.toHaveBeenCalled();+ });++ it("returns 404 when the invite does not exist", async () => {+ mockGetCurrentUser.mockResolvedValue({+ id: "user-1",+ email: "[email protected]",+ });+ mockDb.for.mockResolvedValueOnce([]);++ const response = await POST(makeRequest({ inviteId: "invite-1" }));++ expect(response.status).toBe(404);+ expect(mockDb.delete).not.toHaveBeenCalled();+ });++ it("returns 403 when the authenticated user is not the invitee", async () => {+ mockGetCurrentUser.mockResolvedValue({+ id: "user-1",+ email: "[email protected]",+ });+ mockDb.for.mockResolvedValueOnce([+ { id: "invite-1", invitedEmail: "[email protected]" },+ ]);++ const response = await POST(makeRequest({ inviteId: "invite-1" }));++ expect(response.status).toBe(403);+ expect(mockDb.delete).not.toHaveBeenCalled();+ });++ it("deletes the invite when the authenticated user is the invitee", async () => {+ mockGetCurrentUser.mockResolvedValue({+ id: "user-1",+ email: "[email protected]",+ });+ mockDb.for.mockResolvedValueOnce([+ { id: "invite-1", invitedEmail: "[email protected]" },+ ]);++ const response = await POST(makeRequest({ inviteId: "invite-1" }));++ expect(response.status).toBe(200);+ expect(await response.json()).toEqual({ success: true });+ expect(mockDb.delete).toHaveBeenCalledTimes(1);+ expect(mockDb.transaction).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/web/__tests__/unit/media-client.test.ts b/apps/web/__tests__/unit/media-client.test.tsindex 3dde2824d..59bbf1db6 100644--- a/apps/web/__tests__/unit/media-client.test.ts+++ b/apps/web/__tests__/unit/media-client.test.ts@@ -13,6 +13,16 @@ vi.mock("@cap/env", () => ({const mockFetch = vi.fn();global.fetch = mockFetch;+const mediaServerEnv = {+ MEDIA_SERVER_URL: "http://localhost:3456",+ MEDIA_SERVER_WEBHOOK_SECRET: "test-secret",+};++const mediaServerHeaders = {+ "Content-Type": "application/json",+ "x-media-server-secret": "test-secret",+};+describe("media-client", () => {beforeEach(() => {vi.clearAllMocks();@@ -21,9 +31,9 @@ describe("media-client", () => {describe("isMediaServerConfigured", () => {it("returns true when MEDIA_SERVER_URL is set", async () => {const { serverEnv } = await import("@cap/env");- vi.mocked(serverEnv).mockReturnValue({- MEDIA_SERVER_URL: "http://localhost:3456",- } as ReturnType<typeof serverEnv>);+ vi.mocked(serverEnv).mockReturnValue(+ mediaServerEnv as ReturnType<typeof serverEnv>,+ );expect(isMediaServerConfigured()).toBe(true);});@@ -41,6 +51,17 @@ describe("media-client", () => {const { serverEnv } = await import("@cap/env");vi.mocked(serverEnv).mockReturnValue({MEDIA_SERVER_URL: "",+ MEDIA_SERVER_WEBHOOK_SECRET: "test-secret",+ } as unknown as ReturnType<typeof serverEnv>);++ expect(isMediaServerConfigured()).toBe(false);+ });++ it("returns false when MEDIA_SERVER_WEBHOOK_SECRET is missing", async () => {+ const { serverEnv } = await import("@cap/env");+ vi.mocked(serverEnv).mockReturnValue({+ MEDIA_SERVER_URL: "http://localhost:3456",+ MEDIA_SERVER_WEBHOOK_SECRET: undefined,} as unknown as ReturnType<typeof serverEnv>);expect(isMediaServerConfigured()).toBe(false);@@ -50,9 +71,9 @@ describe("media-client", () => {describe("checkHasAudioTrackViaMediaServer", () => {beforeEach(async () => {const { serverEnv } = await import("@cap/env");- vi.mocked(serverEnv).mockReturnValue({- MEDIA_SERVER_URL: "http://localhost:3456",- } as ReturnType<typeof serverEnv>);+ vi.mocked(serverEnv).mockReturnValue(+ mediaServerEnv as ReturnType<typeof serverEnv>,+ );});it("throws error when MEDIA_SERVER_URL is not configured", async () => {@@ -66,6 +87,18 @@ describe("media-client", () => {).rejects.toThrow("MEDIA_SERVER_URL is not configured");});+ it("throws error when MEDIA_SERVER_WEBHOOK_SECRET is not configured", async () => {+ const { serverEnv } = await import("@cap/env");+ vi.mocked(serverEnv).mockReturnValue({+ MEDIA_SERVER_URL: "http://localhost:3456",+ MEDIA_SERVER_WEBHOOK_SECRET: undefined,+ } as unknown as ReturnType<typeof serverEnv>);++ await expect(+ checkHasAudioTrackViaMediaServer("https://example.com/video.mp4"),+ ).rejects.toThrow("MEDIA_SERVER_WEBHOOK_SECRET is not configured");+ });+it("returns true when video has audio track", async () => {mockFetch.mockResolvedValueOnce({ok: true,@@ -81,7 +114,7 @@ describe("media-client", () => {"http://localhost:3456/audio/check",{method: "POST",- headers: { "Content-Type": "application/json" },+ headers: mediaServerHeaders,body: JSON.stringify({ videoUrl: "https://example.com/video.mp4" }),},);@@ -119,9 +152,9 @@ describe("media-client", () => {describe("extractAudioViaMediaServer", () => {beforeEach(async () => {const { serverEnv } = await import("@cap/env");- vi.mocked(serverEnv).mockReturnValue({- MEDIA_SERVER_URL: "http://localhost:3456",- } as ReturnType<typeof serverEnv>);+ vi.mocked(serverEnv).mockReturnValue(+ mediaServerEnv as ReturnType<typeof serverEnv>,+ );});it("throws error when MEDIA_SERVER_URL is not configured", async () => {@@ -152,7 +185,7 @@ describe("media-client", () => {"http://localhost:3456/audio/extract",{method: "POST",- headers: { "Content-Type": "application/json" },+ headers: mediaServerHeaders,body: JSON.stringify({videoUrl: "https://example.com/video.mp4",stream: true,@@ -194,9 +227,9 @@ describe("media-client", () => {describe("fetchConvertedVideoViaMediaServer", () => {beforeEach(async () => {const { serverEnv } = await import("@cap/env");- vi.mocked(serverEnv).mockReturnValue({- MEDIA_SERVER_URL: "http://localhost:3456",- } as ReturnType<typeof serverEnv>);+ vi.mocked(serverEnv).mockReturnValue(+ mediaServerEnv as ReturnType<typeof serverEnv>,+ );});it("throws error when MEDIA_SERVER_URL is not configured", async () => {@@ -227,7 +260,7 @@ describe("media-client", () => {"http://localhost:3456/video/convert",{method: "POST",- headers: { "Content-Type": "application/json" },+ headers: mediaServerHeaders,body: JSON.stringify({videoUrl: "https://example.com/video.m3u8",inputExtension: ".m3u8",diff --git a/apps/web/app/(org)/invite/[inviteId]/InviteAccept.tsx b/apps/web/app/(org)/invite/[inviteId]/InviteAccept.tsxindex b4b37b686..3768f4f16 100644--- a/apps/web/app/(org)/invite/[inviteId]/InviteAccept.tsx+++ b/apps/web/app/(org)/invite/[inviteId]/InviteAccept.tsx@@ -28,7 +28,6 @@ export function InviteAccept({setIsLoading(true);try {if (!user) {- // Redirect to sign in page with a return URLrouter.push(`/login?next=/invite/${inviteId}`);return;}@@ -43,7 +42,7 @@ export function InviteAccept({if (response.ok) {toast.success("Invite accepted successfully");- router.push("/dashboard"); // Redirect to dashboard or appropriate page+ router.push("/dashboard");} else {const error = await response.text();toast.error(`Failed to accept invite: ${error}`);@@ -59,6 +58,11 @@ export function InviteAccept({const handleDecline = async () => {setIsLoading(true);try {+ if (!user) {+ router.push(`/login?next=/invite/${inviteId}`);+ return;+ }+const response = await fetch("/api/invite/decline", {method: "POST",headers: {@@ -69,7 +73,7 @@ export function InviteAccept({if (response.ok) {toast.success("Invite declined");- router.push("/"); // Redirect to homepage+ router.push("/");} else {const error = await response.text();toast.error(`Failed to decline invite: ${error}`);diff --git a/apps/web/app/api/invite/decline/route.ts b/apps/web/app/api/invite/decline/route.tsindex f8c3df917..f97bca6cf 100644--- a/apps/web/app/api/invite/decline/route.ts+++ b/apps/web/app/api/invite/decline/route.ts@@ -1,18 +1,63 @@import { db } from "@cap/database";+import { getCurrentUser } from "@cap/database/auth/session";import { organizationInvites } from "@cap/database/schema";import { eq } from "drizzle-orm";import { type NextRequest, NextResponse } from "next/server";export async function POST(request: NextRequest) {- const { inviteId } = await request.json();+ const user = await getCurrentUser();+ if (!user) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }+ let inviteId: unknown;try {- await db()- .delete(organizationInvites)- .where(eq(organizationInvites.id, inviteId));+ ({ inviteId } = await request.json());+ } catch {+ return NextResponse.json(+ { error: "Invalid request body" },+ { status: 400 },+ );+ }++ if (typeof inviteId !== "string" || !inviteId) {+ return NextResponse.json({ error: "Invalid invite ID" }, { status: 400 });+ }++ try {+ await db().transaction(async (tx) => {+ const [invite] = await tx+ .select()+ .from(organizationInvites)+ .where(eq(organizationInvites.id, inviteId))+ .for("update");++ if (!invite) {+ throw new Error("INVITE_NOT_FOUND");+ }++ if (user.email.toLowerCase() !== invite.invitedEmail.toLowerCase()) {+ throw new Error("EMAIL_MISMATCH");+ }++ await tx+ .delete(organizationInvites)+ .where(eq(organizationInvites.id, inviteId));+ });return NextResponse.json({ success: true });} catch (error) {+ if (error instanceof Error) {+ if (error.message === "INVITE_NOT_FOUND") {+ return NextResponse.json(+ { error: "Invite not found" },+ { status: 404 },+ );+ }+ if (error.message === "EMAIL_MISMATCH") {+ return NextResponse.json({ error: "Email mismatch" }, { status: 403 });+ }+ }console.error("Error declining invite:", error);return NextResponse.json({ error: "Internal server error" },diff --git a/apps/web/lib/media-client.ts b/apps/web/lib/media-client.tsindex fc48f04d3..70759acef 100644--- a/apps/web/lib/media-client.ts+++ b/apps/web/lib/media-client.ts@@ -17,6 +17,32 @@ async function sleep(ms: number): Promise<void> {return new Promise((resolve) => setTimeout(resolve, ms));}+function getMediaServerConfig(): {+ mediaServerUrl: string;+ mediaServerSecret: string;+} {+ const env = serverEnv();+ if (!env.MEDIA_SERVER_URL) {+ throw new Error("MEDIA_SERVER_URL is not configured");+ }+ if (!env.MEDIA_SERVER_WEBHOOK_SECRET) {+ throw new Error("MEDIA_SERVER_WEBHOOK_SECRET is not configured");+ }+ return {+ mediaServerUrl: env.MEDIA_SERVER_URL,+ mediaServerSecret: env.MEDIA_SERVER_WEBHOOK_SECRET,+ };+}++function getMediaServerHeaders(+ mediaServerSecret: string,+): Record<string, string> {+ return {+ "Content-Type": "application/json",+ "x-media-server-secret": mediaServerSecret,+ };+}+async function fetchWithRetry(url: string,options: RequestInit,@@ -58,7 +84,8 @@ async function fetchWithRetry(}export function isMediaServerConfigured(): boolean {- return !!serverEnv().MEDIA_SERVER_URL;+ const env = serverEnv();+ return !!env.MEDIA_SERVER_URL && !!env.MEDIA_SERVER_WEBHOOK_SECRET;}export async function checkMediaServerHealth(): Promise<{@@ -84,14 +111,11 @@ export async function checkMediaServerHealth(): Promise<{export async function checkHasAudioTrackViaMediaServer(videoUrl: string,): Promise<boolean> {- const mediaServerUrl = serverEnv().MEDIA_SERVER_URL;- if (!mediaServerUrl) {- throw new Error("MEDIA_SERVER_URL is not configured");- }+ const { mediaServerUrl, mediaServerSecret } = getMediaServerConfig();const response = await fetchWithRetry(`${mediaServerUrl}/audio/check`, {method: "POST",- headers: { "Content-Type": "application/json" },+ headers: getMediaServerHeaders(mediaServerSecret),body: JSON.stringify({ videoUrl }),});@@ -107,14 +131,11 @@ export async function checkHasAudioTrackViaMediaServer(export async function extractAudioViaMediaServer(videoUrl: string,): Promise<Buffer> {- const mediaServerUrl = serverEnv().MEDIA_SERVER_URL;- if (!mediaServerUrl) {- throw new Error("MEDIA_SERVER_URL is not configured");- }+ const { mediaServerUrl, mediaServerSecret } = getMediaServerConfig();const response = await fetchWithRetry(`${mediaServerUrl}/audio/extract`, {method: "POST",- headers: { "Content-Type": "application/json" },+ headers: getMediaServerHeaders(mediaServerSecret),body: JSON.stringify({videoUrl,stream: true,@@ -159,14 +180,11 @@ export interface MediaServerProbeResult {export async function probeVideoViaMediaServer(videoUrl: string,): Promise<MediaServerProbeResult> {- const mediaServerUrl = serverEnv().MEDIA_SERVER_URL;- if (!mediaServerUrl) {- throw new Error("MEDIA_SERVER_URL is not configured");- }+ const { mediaServerUrl, mediaServerSecret } = getMediaServerConfig();const response = await fetchWithRetry(`${mediaServerUrl}/video/probe`, {method: "POST",- headers: { "Content-Type": "application/json" },+ headers: getMediaServerHeaders(mediaServerSecret),body: JSON.stringify({ videoUrl }),});@@ -191,14 +209,11 @@ export async function probeVideoViaMediaServer(export async function convertAudioToMp3ViaMediaServer(audioUrl: string,): Promise<Buffer> {- const mediaServerUrl = serverEnv().MEDIA_SERVER_URL;- if (!mediaServerUrl) {- throw new Error("MEDIA_SERVER_URL is not configured");- }+ const { mediaServerUrl, mediaServerSecret } = getMediaServerConfig();const response = await fetchWithRetry(`${mediaServerUrl}/audio/convert`, {method: "POST",- headers: { "Content-Type": "application/json" },+ headers: getMediaServerHeaders(mediaServerSecret),body: JSON.stringify({audioUrl,outputFormat: "mp3",@@ -228,14 +243,11 @@ export async function fetchConvertedVideoViaMediaServer(videoUrl: string,inputExtension?: string,): Promise<Response> {- const mediaServerUrl = serverEnv().MEDIA_SERVER_URL;- if (!mediaServerUrl) {- throw new Error("MEDIA_SERVER_URL is not configured");- }+ const { mediaServerUrl, mediaServerSecret } = getMediaServerConfig();return await fetchWithRetry(`${mediaServerUrl}/video/convert`, {method: "POST",- headers: { "Content-Type": "application/json" },+ headers: getMediaServerHeaders(mediaServerSecret),body: JSON.stringify({videoUrl,...(inputExtension ? { inputExtension } : {}),diff --git a/docker-compose.coolify.yml b/docker-compose.coolify.ymlindex 4b497ae2f..7471a6feb 100644--- a/docker-compose.coolify.yml+++ b/docker-compose.coolify.yml@@ -45,6 +45,7 @@ services:restart: unless-stoppedenvironment:PORT: 3456+ MEDIA_SERVER_WEBHOOK_SECRET: ${MEDIA_SERVER_WEBHOOK_SECRET}healthcheck:test: ["CMD", "wget", "-qO-", "http://localhost:3456/health"]interval: 30sdiff --git a/docker-compose.template.yml b/docker-compose.template.ymlindex 3de0a8854..e21f40d28 100644--- a/docker-compose.template.yml+++ b/docker-compose.template.yml@@ -57,6 +57,7 @@ services:restart: unless-stoppedenvironment:PORT: 3456+ MEDIA_SERVER_WEBHOOK_SECRET: fe337b52749070bb7b5d2c78cff9948439ea73cbc1869ba39d350e6c24db53b1ports:- "3456:3456"healthcheck:diff --git a/docker-compose.yml b/docker-compose.ymlindex 0aff7ed65..6b9152d06 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -47,6 +47,7 @@ services:restart: unless-stoppedenvironment:PORT: 3456+ MEDIA_SERVER_WEBHOOK_SECRET: ${MEDIA_SERVER_WEBHOOK_SECRET:-fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210}healthcheck:test: ["CMD", "wget", "-qO-", "http://localhost:3456/health"]interval: 30sdiff --git a/packages/local-docker/docker-compose.yml b/packages/local-docker/docker-compose.ymlindex 35bd09ab5..a42005a7b 100644--- a/packages/local-docker/docker-compose.yml+++ b/packages/local-docker/docker-compose.yml@@ -29,6 +29,7 @@ services:network_mode: hostenvironment:PORT: 3456+ MEDIA_SERVER_WEBHOOK_SECRET: ${MEDIA_SERVER_WEBHOOK_SECRET:-local-media-server-secret}# Local S3 Strorageminio: