feat(docker): bundle Convex backend with oTunes
- Run the web app and Convex backend in one container with generated per-install keys - Derive Convex URLs from the server address and update self-hosting docs
This commit is contained in:
17 files changed
+378
-143
No files matched your search
+47
-20
@@ -7,12 +7,11 @@
|
||||
# To ensure security and compatibility, regularly update the NODE_VERSION ARG to the latest LTS version.
|
||||
ARG NODE_VERSION=24.13.0-slim
|
||||
|
||||
FROM node:${NODE_VERSION} AS runner-base
|
||||
|
||||
RUN apt-get update && \
|
||||
apt-get install -y ffmpeg && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
# The Convex backend runs inside the oTunes image. Pin to a commit tag from
|
||||
# https://github.com/get-convex/convex-backend/pkgs/container/convex-backend
|
||||
ARG CONVEX_BACKEND_IMAGE=ghcr.io/get-convex/convex-backend:5c7cb5bc7db457290f1769f95f1d1340912f7fd7
|
||||
|
||||
FROM node:${NODE_VERSION} AS node
|
||||
|
||||
FROM node:${NODE_VERSION} AS dependencies
|
||||
|
||||
@@ -57,35 +56,63 @@ COPY --from=dependencies /app/packages/convex/node_modules ./packages/convex/nod
|
||||
|
||||
ENV NODE_ENV=production
|
||||
|
||||
ARG NEXT_PUBLIC_CONVEX_URL
|
||||
|
||||
WORKDIR /app/apps/web
|
||||
|
||||
RUN --mount=type=cache,target=/app/apps/web/.next/cache \
|
||||
corepack enable pnpm && pnpm build
|
||||
|
||||
# ============================================
|
||||
# Stage 3: Run Next.js application
|
||||
# Stage 3: Convex functions, deployed to the bundled backend on boot
|
||||
# ============================================
|
||||
|
||||
FROM runner-base AS runner
|
||||
FROM node:${NODE_VERSION} AS convex-functions
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=3000
|
||||
ENV HOSTNAME="0.0.0.0"
|
||||
COPY package.json pnpm-lock.yaml .npmrc ./
|
||||
COPY packages/convex/package.json ./packages/convex/
|
||||
|
||||
RUN mkdir /data
|
||||
RUN printf '%s\n' \
|
||||
'packages:' \
|
||||
' - "packages/convex"' \
|
||||
> pnpm-workspace.yaml
|
||||
|
||||
COPY --from=builder --chown=node:node /app/apps/web/public ./apps/web/public
|
||||
COPY --from=builder --chown=node:node /app/apps/web/.next/standalone ./
|
||||
COPY --from=builder --chown=node:node /app/apps/web/.next/static ./apps/web/.next/static
|
||||
RUN --mount=type=cache,target=/root/.local/share/pnpm/store \
|
||||
corepack enable pnpm && \
|
||||
pnpm install --frozen-lockfile --prod --filter @otunes/convex...
|
||||
|
||||
RUN mkdir -p apps/web/.next && chown -R node:node apps/web/.next
|
||||
COPY packages/convex ./packages/convex
|
||||
|
||||
USER node
|
||||
# ============================================
|
||||
# Stage 4: Run Convex and Next.js together
|
||||
# ============================================
|
||||
|
||||
EXPOSE 3000
|
||||
FROM ${CONVEX_BACKEND_IMAGE} AS runner
|
||||
|
||||
CMD ["node", "apps/web/server.js"]
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends ffmpeg tini && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN useradd --system --user-group --home-dir /app --shell /usr/sbin/nologin otunes
|
||||
|
||||
COPY --from=node /usr/local/bin/node /opt/node/bin/node
|
||||
|
||||
COPY --from=convex-functions /app /opt/otunes/convex
|
||||
COPY docker/generate-auth-keys.mjs /opt/otunes/generate-auth-keys.mjs
|
||||
COPY --chmod=755 docker/entrypoint.sh /usr/local/bin/otunes-entrypoint
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=builder --chown=otunes:otunes /app/apps/web/public ./apps/web/public
|
||||
COPY --from=builder --chown=otunes:otunes /app/apps/web/.next/standalone ./
|
||||
COPY --from=builder --chown=otunes:otunes /app/apps/web/.next/static ./apps/web/.next/static
|
||||
|
||||
RUN mkdir -p apps/web/.next /data && chown -R otunes:otunes apps/web/.next
|
||||
|
||||
EXPOSE 3000 3210
|
||||
|
||||
HEALTHCHECK --interval=10s --timeout=5s --start-period=60s \
|
||||
CMD curl -fsS http://127.0.0.1:3210/version && curl -fsS -o /dev/null http://127.0.0.1:3000/signin
|
||||
|
||||
ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/otunes-entrypoint"]
|
||||
CMD []
|
||||
@@ -40,6 +40,12 @@ Run the Convex backend (from the shared package):
|
||||
pnpm dev:convex
|
||||
```
|
||||
|
||||
Point the dev deployment at your music folder (it defaults to `/data`):
|
||||
|
||||
```bash
|
||||
cd packages/convex && npx convex env set DATA "/path/to/Music"
|
||||
```
|
||||
|
||||
Other commands:
|
||||
|
||||
```bash
|
||||
@@ -51,61 +57,39 @@ pnpm format # format with Prettier
|
||||
|
||||
## Hosting with Docker
|
||||
|
||||
Here's an example `docker-compose.yml` file to get you started:
|
||||
The image runs both the web app and its Convex backend, so there is nothing to configure. Here's an example `docker-compose.yml`:
|
||||
|
||||
```yaml
|
||||
name: music
|
||||
services:
|
||||
otunes:
|
||||
image: git.abunchofknowitalls.com/joshuafhiggins/otunes:latest
|
||||
ports:
|
||||
- "3000:3000"
|
||||
- "3000:3000" # web app
|
||||
- "3210:3210" # Convex
|
||||
volumes:
|
||||
- ./otunes-data:/convex/data
|
||||
- /SomeAttachedStorage/Music:/data
|
||||
environment:
|
||||
- NEXT_PUBLIC_CONVEX_URL=http://127.0.0.1:3210
|
||||
- CONVEX_SELF_HOSTED_URL=http://127.0.0.1:3210
|
||||
- CONVEX_SELF_HOSTED_ADMIN_KEY=REPLACE_ME
|
||||
restart: unless-stopped
|
||||
image: otunes
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
- NEXT_PUBLIC_CONVEX_URL=http://127.0.0.1:3210
|
||||
backend:
|
||||
stop_grace_period: 10s
|
||||
stop_signal: SIGINT
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "3210:3210"
|
||||
- "3211:3211"
|
||||
volumes:
|
||||
- ./database:/convex/data
|
||||
environment:
|
||||
- CONVEX_CLOUD_ORIGIN=http://127.0.0.1:3210
|
||||
- CONVEX_SITE_ORIGIN=http://127.0.0.1:3211
|
||||
- APPLICATION_MAX_CONCURRENT_MUTATIONS=16
|
||||
- APPLICATION_MAX_CONCURRENT_NODE_ACTIONS=16
|
||||
- APPLICATION_MAX_CONCURRENT_QUERIES=16
|
||||
- APPLICATION_MAX_CONCURRENT_V8_ACTIONS=16
|
||||
- DISABLE_BEACON=true
|
||||
- DISABLE_METRICS_ENDPOINT=true
|
||||
- DOCUMENT_RETENTION_DELAY=172800
|
||||
- DO_NOT_REQUIRE_SSL=true
|
||||
- REDACT_LOGS_TO_CLIENT=true
|
||||
- RUST_LOG=info
|
||||
image: ghcr.io/get-convex/convex-backend:latest
|
||||
healthcheck:
|
||||
test: curl -f http://localhost:3210/version
|
||||
interval: 5s
|
||||
start_period: 10s
|
||||
```
|
||||
|
||||
First run `docker compose up -d backend` and `docker compose exec backend ./generate_admin_key.sh` to generate the admin key needed for the frontend. Take this key and put it in the `CONVEX_SELF_HOSTED_ADMIN_KEY` environment variable for the `otunes` service.
|
||||
Change `/SomeAttachedStorage/Music` to the folder containing your `lossless`, `normal`, and `atmos` libraries, then run `docker compose up -d`. The first account you create becomes the admin.
|
||||
|
||||
`CONVEX_SELF_HOSTED_URL`, `CONVEX_CLOUD_ORIGIN`, and `NEXT_PUBLIC_CONVEX_URL` should be changed to the same reversed proxied, SSL protected, domain and `CONVEX_SITE_ORIGIN` on a different domain.
|
||||
On first boot the container generates its own Convex instance secret and sign-in keys and stores them in `./otunes-data`, so no two installs share secrets. Back up that folder: it holds your database and keys.
|
||||
|
||||
Then change `/SomeAttachedStorage/Music` to the path where your music is stored and run `docker compose down && docker compose up -d` to start the whole app together.
|
||||
### Reverse proxy
|
||||
|
||||
The web app finds Convex from the address you open it at:
|
||||
|
||||
| You open | Convex is expected at |
|
||||
| --- | --- |
|
||||
| `https://music.example.com` | `https://convex.music.example.com` |
|
||||
| `http://192.168.1.5:3000` or `http://localhost:3000` | port `3210` on the same host |
|
||||
|
||||
So for a domain, point `music.example.com` at port `3000` and `convex.music.example.com` at port `3210` (WebSockets must be allowed). The mobile app uses the same convention.
|
||||
|
||||
If Convex has to live somewhere else, set `PUBLIC_CONVEX_URL` on the container to its public URL.
|
||||
|
||||
## Downloads
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { buildConvexUrl, isLocalHost } from "@otunes/convex/server-url"
|
||||
|
||||
export type ServerConfig = {
|
||||
/** Raw hostname the user entered, e.g. `music.example.com` or `192.168.86.25:3000` */
|
||||
hostname: string
|
||||
@@ -9,30 +11,6 @@ export type ServerConfig = {
|
||||
|
||||
const SERVER_CONFIG_KEY = "otunes.server-config"
|
||||
const LEGACY_SERVER_CONFIG_KEY = "otunes:server-config"
|
||||
const LOCAL_CONVEX_PORT = "3210"
|
||||
|
||||
function parseHostPort(hostname: string): { host: string; port?: string } {
|
||||
const colonIndex = hostname.lastIndexOf(":")
|
||||
if (colonIndex === -1) {
|
||||
return { host: hostname }
|
||||
}
|
||||
const host = hostname.slice(0, colonIndex)
|
||||
const port = hostname.slice(colonIndex + 1)
|
||||
if (!/^\d+$/.test(port)) {
|
||||
return { host: hostname }
|
||||
}
|
||||
return { host, port }
|
||||
}
|
||||
|
||||
function isLocalHost(hostname: string): boolean {
|
||||
const host = parseHostPort(hostname).host.toLowerCase()
|
||||
return (
|
||||
host === "localhost" ||
|
||||
host === "127.0.0.1" ||
|
||||
host.endsWith(".local") ||
|
||||
/^\d{1,3}(\.\d{1,3}){3}$/.test(host)
|
||||
)
|
||||
}
|
||||
|
||||
function normalizeHostnameInput(input: string): string {
|
||||
return input.trim().replace(/^https?:\/\//i, "").replace(/\/+$/, "")
|
||||
@@ -43,16 +21,6 @@ function buildServerUrl(hostname: string): string {
|
||||
return `${protocol}://${hostname}`
|
||||
}
|
||||
|
||||
function buildConvexUrl(hostname: string): string {
|
||||
const { host, port } = parseHostPort(hostname)
|
||||
const protocol = isLocalHost(hostname) ? "http" : "https"
|
||||
if (isLocalHost(hostname)) {
|
||||
return `${protocol}://${host}:${LOCAL_CONVEX_PORT}`
|
||||
}
|
||||
const convexHost = `convex.${host}`
|
||||
return port ? `${protocol}://${convexHost}:${port}` : `${protocol}://${convexHost}`
|
||||
}
|
||||
|
||||
export function parseServerHostname(input: string): ServerConfig | null {
|
||||
const hostname = normalizeHostnameInput(input)
|
||||
if (!hostname) return null
|
||||
|
||||
@@ -2,6 +2,7 @@ import { AlbumView } from "@/components/album-view"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { fetchQuery } from "convex/nextjs"
|
||||
import { convexServerOptions } from "@/lib/convex-server"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { Metadata } from "next"
|
||||
import { cache } from "react"
|
||||
@@ -12,7 +13,7 @@ interface PageProps {
|
||||
}
|
||||
|
||||
const fetchAlbumDetail = cache((id: Id<"albums">) =>
|
||||
fetchQuery(api.library.browseAlbumDetail, { id })
|
||||
fetchQuery(api.library.browseAlbumDetail, { id }, convexServerOptions())
|
||||
)
|
||||
|
||||
export async function generateMetadata({
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { fetchQuery } from "convex/nextjs"
|
||||
import { convexServerOptions } from "@/lib/convex-server"
|
||||
import { ArtistView } from "@/components/artist-view"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
@@ -11,7 +12,7 @@ interface PageProps {
|
||||
}
|
||||
|
||||
const fetchArtistDetail = cache((id: Id<"artists">) =>
|
||||
fetchQuery(api.library.browseArtistDetail, { id })
|
||||
fetchQuery(api.library.browseArtistDetail, { id }, convexServerOptions())
|
||||
)
|
||||
|
||||
export async function generateMetadata({
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { fetchQuery } from "convex/nextjs"
|
||||
import { convexServerOptions } from "@/lib/convex-server"
|
||||
import { ArtistsView } from "@/components/artists-view"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { Metadata } from "next"
|
||||
@@ -8,7 +9,9 @@ interface PageProps {
|
||||
params: Promise<{ id: string }>
|
||||
}
|
||||
|
||||
const fetchArtists = cache(() => fetchQuery(api.library.browseArtists))
|
||||
const fetchArtists = cache(() =>
|
||||
fetchQuery(api.library.browseArtists, {}, convexServerOptions())
|
||||
)
|
||||
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
@@ -37,7 +40,7 @@ export default async function Page({ params }: PageProps) {
|
||||
const { id } = await params
|
||||
const [artists, albums] = await Promise.all([
|
||||
fetchArtists(),
|
||||
fetchQuery(api.library.browseAlbums),
|
||||
fetchQuery(api.library.browseAlbums, {}, convexServerOptions()),
|
||||
])
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { fetchQuery } from "convex/nextjs"
|
||||
import { convexServerOptions } from "@/lib/convex-server"
|
||||
import { ArtistsView } from "@/components/artists-view"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
export default async function Page() {
|
||||
const [artists, albums] = await Promise.all([
|
||||
fetchQuery(api.library.browseArtists),
|
||||
fetchQuery(api.library.browseAlbums),
|
||||
fetchQuery(api.library.browseArtists, {}, convexServerOptions()),
|
||||
fetchQuery(api.library.browseAlbums, {}, convexServerOptions()),
|
||||
])
|
||||
|
||||
return (
|
||||
|
||||
@@ -3,6 +3,7 @@ import { PlaylistView } from "@/components/playlist-view"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server"
|
||||
import { fetchQuery } from "convex/nextjs"
|
||||
import { convexServerOptions } from "@/lib/convex-server"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { Metadata } from "next"
|
||||
import { cache } from "react"
|
||||
@@ -16,7 +17,7 @@ const fetchPlaylistDetail = cache(async (id: Id<"playlists">) => {
|
||||
return fetchQuery(
|
||||
api.playlists.browsePlaylistDetail,
|
||||
{ id },
|
||||
{ token }
|
||||
convexServerOptions(token)
|
||||
)
|
||||
})
|
||||
|
||||
|
||||
+48
-22
@@ -7,6 +7,7 @@ import { ThemeProvider } from "@/components/theme-provider"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Toaster } from "@/components/ui/sonner"
|
||||
import type { Metadata } from "next"
|
||||
import { headers } from "next/headers"
|
||||
|
||||
const inter = Inter({ subsets: ["latin"], variable: "--font-sans" })
|
||||
|
||||
@@ -15,28 +16,53 @@ const fontMono = Geist_Mono({
|
||||
variable: "--font-mono",
|
||||
})
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "oTunes",
|
||||
description: "Our Music",
|
||||
appleWebApp: {
|
||||
capable: true,
|
||||
title: "oTunes",
|
||||
startupImage: "/logo-dark.png",
|
||||
statusBarStyle: "default",
|
||||
},
|
||||
openGraph: {
|
||||
type: "website",
|
||||
url: process.env.HOSTED_URL || "http://localhost:3000",
|
||||
async function hostedUrl() {
|
||||
if (process.env.HOSTED_URL) {
|
||||
return new URL(process.env.HOSTED_URL)
|
||||
}
|
||||
|
||||
const requestHeaders = await headers()
|
||||
const host = (
|
||||
requestHeaders.get("x-forwarded-host") ?? requestHeaders.get("host")
|
||||
)
|
||||
?.split(",")[0]
|
||||
.trim()
|
||||
const protocol =
|
||||
requestHeaders.get("x-forwarded-proto")?.split(",")[0].trim() ?? "http"
|
||||
|
||||
try {
|
||||
return new URL(`${protocol}://${host}`)
|
||||
} catch {
|
||||
return new URL("http://localhost:3000")
|
||||
}
|
||||
}
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const url = await hostedUrl()
|
||||
|
||||
return {
|
||||
title: "oTunes",
|
||||
description: "Our Music",
|
||||
siteName: "oTunes",
|
||||
images: [
|
||||
{
|
||||
url: "/logo-dark.png",
|
||||
},
|
||||
],
|
||||
},
|
||||
metadataBase: new URL(process.env.HOSTED_URL || "http://localhost:3000"),
|
||||
appleWebApp: {
|
||||
capable: true,
|
||||
title: "oTunes",
|
||||
startupImage: "/logo-dark.png",
|
||||
statusBarStyle: "default",
|
||||
},
|
||||
openGraph: {
|
||||
type: "website",
|
||||
url,
|
||||
title: "oTunes",
|
||||
description: "Our Music",
|
||||
siteName: "oTunes",
|
||||
images: [
|
||||
{
|
||||
url: "/logo-dark.png",
|
||||
},
|
||||
],
|
||||
},
|
||||
metadataBase: url,
|
||||
}
|
||||
}
|
||||
|
||||
export default function RootLayout({
|
||||
@@ -56,8 +82,8 @@ export default function RootLayout({
|
||||
)}
|
||||
>
|
||||
<body className={"overflow-x-hidden"}>
|
||||
<ConvexAuthNextjsServerProvider>
|
||||
<ConvexClientProvider>
|
||||
<ConvexAuthNextjsServerProvider storageNamespace="otunes">
|
||||
<ConvexClientProvider convexUrl={process.env.PUBLIC_CONVEX_URL}>
|
||||
<ThemeProvider>
|
||||
{children}
|
||||
<Toaster />
|
||||
|
||||
@@ -1,14 +1,42 @@
|
||||
"use client"
|
||||
|
||||
import { ConvexAuthNextjsProvider } from "@convex-dev/auth/nextjs"
|
||||
import { buildConvexUrl } from "@otunes/convex/server-url"
|
||||
import { ConvexReactClient } from "convex/react"
|
||||
import { ReactNode } from "react"
|
||||
|
||||
const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!)
|
||||
// Server rendering never runs Convex queries, so this URL is never contacted.
|
||||
const SSR_CONVEX_URL = "http://127.0.0.1:3210"
|
||||
|
||||
export function ConvexClientProvider({ children }: { children: ReactNode }) {
|
||||
let client: ConvexReactClient | undefined
|
||||
|
||||
function browserConvexUrl() {
|
||||
const { host, protocol } = window.location
|
||||
return buildConvexUrl(host, protocol === "https:" ? "https" : "http")
|
||||
}
|
||||
|
||||
function getConvexClient(convexUrl: string | undefined) {
|
||||
if (!client) {
|
||||
client = new ConvexReactClient(
|
||||
typeof window === "undefined"
|
||||
? SSR_CONVEX_URL
|
||||
: (convexUrl ??
|
||||
process.env.NEXT_PUBLIC_CONVEX_URL ??
|
||||
browserConvexUrl())
|
||||
)
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
export function ConvexClientProvider({
|
||||
convexUrl,
|
||||
children,
|
||||
}: {
|
||||
convexUrl?: string
|
||||
children: ReactNode
|
||||
}) {
|
||||
return (
|
||||
<ConvexAuthNextjsProvider client={convex}>
|
||||
<ConvexAuthNextjsProvider client={getConvexClient(convexUrl)}>
|
||||
{children}
|
||||
</ConvexAuthNextjsProvider>
|
||||
)
|
||||
|
||||
@@ -2,9 +2,25 @@ import { ConvexHttpClient } from "convex/browser"
|
||||
|
||||
let client: ConvexHttpClient | null = null
|
||||
|
||||
/**
|
||||
* URL the Next.js server uses to reach Convex. Never derive this from request
|
||||
* headers: auth tokens are sent to it, so a forged Host would leak them.
|
||||
*/
|
||||
export function getConvexServerUrl() {
|
||||
return (
|
||||
process.env.CONVEX_INTERNAL_URL ??
|
||||
process.env.NEXT_PUBLIC_CONVEX_URL ??
|
||||
"http://127.0.0.1:3210"
|
||||
)
|
||||
}
|
||||
|
||||
export function convexServerOptions(token?: string) {
|
||||
return { url: getConvexServerUrl(), token }
|
||||
}
|
||||
|
||||
export function getConvexClient() {
|
||||
if (!client) {
|
||||
client = new ConvexHttpClient(process.env.NEXT_PUBLIC_CONVEX_URL!)
|
||||
client = new ConvexHttpClient(getConvexServerUrl())
|
||||
}
|
||||
return client
|
||||
}
|
||||
+16
-12
@@ -3,6 +3,7 @@ import {
|
||||
createRouteMatcher,
|
||||
nextjsMiddlewareRedirect,
|
||||
} from "@convex-dev/auth/nextjs/server"
|
||||
import { getConvexServerUrl } from "@/lib/convex-server"
|
||||
|
||||
const isAuthPage = createRouteMatcher(["/signin", "/signup"])
|
||||
const isPublic = createRouteMatcher([
|
||||
@@ -15,21 +16,24 @@ const isPublic = createRouteMatcher([
|
||||
"/playlist/:id",
|
||||
])
|
||||
|
||||
export default convexAuthNextjsMiddleware(async (request, { convexAuth }) => {
|
||||
if (isPublic(request)) {
|
||||
return
|
||||
}
|
||||
export default convexAuthNextjsMiddleware(
|
||||
async (request, { convexAuth }) => {
|
||||
if (isPublic(request)) {
|
||||
return
|
||||
}
|
||||
|
||||
const authenticated = await convexAuth.isAuthenticated()
|
||||
const authenticated = await convexAuth.isAuthenticated()
|
||||
|
||||
if (isAuthPage(request) && authenticated) {
|
||||
return nextjsMiddlewareRedirect(request, "/")
|
||||
}
|
||||
if (isAuthPage(request) && authenticated) {
|
||||
return nextjsMiddlewareRedirect(request, "/")
|
||||
}
|
||||
|
||||
if (!isAuthPage(request) && !authenticated) {
|
||||
return nextjsMiddlewareRedirect(request, "/signin")
|
||||
}
|
||||
})
|
||||
if (!isAuthPage(request) && !authenticated) {
|
||||
return nextjsMiddlewareRedirect(request, "/signin")
|
||||
}
|
||||
},
|
||||
{ convexUrl: getConvexServerUrl() }
|
||||
)
|
||||
|
||||
export const config = {
|
||||
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env bash
|
||||
# Runs the Convex backend and the oTunes web server in one container.
|
||||
#
|
||||
# Every secret is generated on first boot and kept in /convex/data:
|
||||
# - the Convex instance secret (by the upstream read_credentials.sh)
|
||||
# - the Convex Auth signing keys (stored as Convex environment variables)
|
||||
# The admin key is derived from the instance secret on each boot, used to deploy
|
||||
# the bundled functions, and never exported to the web server.
|
||||
set -euo pipefail
|
||||
|
||||
NODE=/opt/node/bin/node
|
||||
CONVEX_DATA_DIR=/convex/data
|
||||
FUNCTIONS_DIR=/opt/otunes/convex/packages/convex
|
||||
BACKEND_URL=http://127.0.0.1:3210
|
||||
|
||||
: "${CONVEX_CLOUD_ORIGIN:=http://127.0.0.1:3210}"
|
||||
: "${CONVEX_SITE_ORIGIN:=http://127.0.0.1:3211}"
|
||||
: "${APPLICATION_MAX_CONCURRENT_MUTATIONS:=16}"
|
||||
: "${APPLICATION_MAX_CONCURRENT_NODE_ACTIONS:=16}"
|
||||
: "${APPLICATION_MAX_CONCURRENT_QUERIES:=16}"
|
||||
: "${APPLICATION_MAX_CONCURRENT_V8_ACTIONS:=16}"
|
||||
: "${DISABLE_BEACON:=true}"
|
||||
: "${DISABLE_METRICS_ENDPOINT:=true}"
|
||||
: "${DOCUMENT_RETENTION_DELAY:=172800}"
|
||||
: "${DO_NOT_REQUIRE_SSL:=true}"
|
||||
: "${REDACT_LOGS_TO_CLIENT:=true}"
|
||||
: "${RUST_LOG:=info}"
|
||||
export CONVEX_CLOUD_ORIGIN CONVEX_SITE_ORIGIN \
|
||||
APPLICATION_MAX_CONCURRENT_MUTATIONS APPLICATION_MAX_CONCURRENT_NODE_ACTIONS \
|
||||
APPLICATION_MAX_CONCURRENT_QUERIES APPLICATION_MAX_CONCURRENT_V8_ACTIONS \
|
||||
DISABLE_BEACON DISABLE_METRICS_ENDPOINT DOCUMENT_RETENTION_DELAY \
|
||||
DO_NOT_REQUIRE_SSL REDACT_LOGS_TO_CLIENT RUST_LOG
|
||||
|
||||
backend_pid=""
|
||||
web_pid=""
|
||||
|
||||
log() {
|
||||
echo "[otunes] $*"
|
||||
}
|
||||
|
||||
stop() {
|
||||
trap - TERM INT
|
||||
if [ -n "$web_pid" ]; then kill -TERM "$web_pid" 2>/dev/null || true; fi
|
||||
if [ -n "$backend_pid" ]; then kill -INT "$backend_pid" 2>/dev/null || true; fi
|
||||
wait || true
|
||||
}
|
||||
trap 'stop; exit 0' TERM INT
|
||||
|
||||
convex_cli() {
|
||||
(
|
||||
cd "$FUNCTIONS_DIR"
|
||||
unset CONVEX_DEPLOYMENT CONVEX_DEPLOY_KEY
|
||||
CONVEX_SELF_HOSTED_URL="$BACKEND_URL" \
|
||||
CONVEX_SELF_HOSTED_ADMIN_KEY="$admin_key" \
|
||||
"$NODE" node_modules/convex/bin/main.js "$@"
|
||||
)
|
||||
}
|
||||
|
||||
# Only root (the backend) may read the database and instance secret.
|
||||
mkdir -p "$CONVEX_DATA_DIR"
|
||||
chmod 700 "$CONVEX_DATA_DIR"
|
||||
|
||||
log "Starting Convex backend"
|
||||
(cd /convex && umask 077 && exec ./run_backend.sh) &
|
||||
backend_pid=$!
|
||||
|
||||
for _ in $(seq 1 120); do
|
||||
if curl -fsS "$BACKEND_URL/version" >/dev/null 2>&1; then
|
||||
break
|
||||
fi
|
||||
if ! kill -0 "$backend_pid" 2>/dev/null; then
|
||||
log "Convex backend exited during startup"
|
||||
exit 1
|
||||
fi
|
||||
sleep 0.5
|
||||
done
|
||||
if ! curl -fsS "$BACKEND_URL/version" >/dev/null 2>&1; then
|
||||
log "Convex backend did not become ready"
|
||||
stop
|
||||
exit 1
|
||||
fi
|
||||
|
||||
admin_key=$(cd /convex && ./generate_admin_key.sh)
|
||||
|
||||
log "Deploying Convex functions"
|
||||
convex_cli deploy --typecheck disable --codegen disable
|
||||
|
||||
if [ -z "$(convex_cli env get JWKS 2>/dev/null || true)" ]; then
|
||||
log "Generating Convex Auth signing keys"
|
||||
"$NODE" /opt/otunes/generate-auth-keys.mjs | convex_cli env set --force
|
||||
fi
|
||||
|
||||
unset admin_key
|
||||
|
||||
log "Starting web server"
|
||||
(
|
||||
cd /app
|
||||
export HOME=/app NODE_ENV=production PORT=3000 HOSTNAME=0.0.0.0
|
||||
export CONVEX_INTERNAL_URL="$BACKEND_URL"
|
||||
exec setpriv --reuid=otunes --regid=otunes --init-groups \
|
||||
"$NODE" apps/web/server.js
|
||||
) &
|
||||
web_pid=$!
|
||||
|
||||
set +e
|
||||
wait -n "$backend_pid" "$web_pid"
|
||||
status=$?
|
||||
set -e
|
||||
|
||||
log "A process exited with status $status, shutting down"
|
||||
stop
|
||||
exit "$status"
|
||||
@@ -0,0 +1,14 @@
|
||||
// Prints a fresh Convex Auth signing key pair in .env format for `convex env set`.
|
||||
import { generateKeyPairSync } from "node:crypto"
|
||||
|
||||
const { privateKey, publicKey } = generateKeyPairSync("rsa", {
|
||||
modulusLength: 2048,
|
||||
})
|
||||
const pkcs8 = privateKey.export({ type: "pkcs8", format: "pem" })
|
||||
const jwk = publicKey.export({ format: "jwk" })
|
||||
const jwks = JSON.stringify({ keys: [{ use: "sig", ...jwk }] })
|
||||
|
||||
process.stdout.write(
|
||||
`JWT_PRIVATE_KEY="${pkcs8.trimEnd().replace(/\n/g, " ")}"\n`
|
||||
)
|
||||
process.stdout.write(`JWKS=${jwks}\n`)
|
||||
@@ -11,9 +11,7 @@ import { ConvexError } from "convex/values"
|
||||
import type { Id } from "./_generated/dataModel"
|
||||
import { action, internalAction, type ActionCtx } from "./_generated/server"
|
||||
|
||||
const DATA_DIR = process.env.CONVEX_SITE_URL?.includes("127.0.0.1")
|
||||
? "/Volumes/FastStorage/Apple Music"
|
||||
: process.env.DATA || "/data"
|
||||
const DATA_DIR = process.env.DATA || "/data"
|
||||
const HLS_CACHE_DIR = "/tmp/otunes"
|
||||
const HLS_MAX_IDLE_MS = 30 * 60 * 1000
|
||||
|
||||
|
||||
@@ -18,6 +18,10 @@
|
||||
"./playback-stream": {
|
||||
"types": "./playback-stream.ts",
|
||||
"default": "./playback-stream.ts"
|
||||
},
|
||||
"./server-url": {
|
||||
"types": "./server-url.ts",
|
||||
"default": "./server-url.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
/** Port the self-hosted Convex backend listens on when there is no `convex.` subdomain. */
|
||||
export const LOCAL_CONVEX_PORT = "3210"
|
||||
|
||||
export function parseHostPort(hostname: string): {
|
||||
host: string
|
||||
port?: string
|
||||
} {
|
||||
const colonIndex = hostname.lastIndexOf(":")
|
||||
if (colonIndex === -1) {
|
||||
return { host: hostname }
|
||||
}
|
||||
const host = hostname.slice(0, colonIndex)
|
||||
const port = hostname.slice(colonIndex + 1)
|
||||
if (!/^\d+$/.test(port)) {
|
||||
return { host: hostname }
|
||||
}
|
||||
return { host, port }
|
||||
}
|
||||
|
||||
export function isLocalHost(hostname: string): boolean {
|
||||
const host = parseHostPort(hostname).host.toLowerCase()
|
||||
return (
|
||||
host === "localhost" ||
|
||||
host === "127.0.0.1" ||
|
||||
host.endsWith(".local") ||
|
||||
/^\d{1,3}(\.\d{1,3}){3}$/.test(host)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Convex URL for an oTunes server reached at `hostname` (host with optional port).
|
||||
* Local hosts use the Convex port directly, everything else uses the
|
||||
* `convex.` subdomain, e.g. `music.example.com` -> `https://convex.music.example.com`.
|
||||
*/
|
||||
export function buildConvexUrl(
|
||||
hostname: string,
|
||||
protocol: "http" | "https" = isLocalHost(hostname) ? "http" : "https"
|
||||
): string {
|
||||
const { host, port } = parseHostPort(hostname)
|
||||
if (isLocalHost(hostname)) {
|
||||
return `${protocol}://${host}:${LOCAL_CONVEX_PORT}`
|
||||
}
|
||||
const convexHost = `convex.${host}`
|
||||
return port
|
||||
? `${protocol}://${convexHost}:${port}`
|
||||
: `${protocol}://${convexHost}`
|
||||
}
|
||||
Reference in new issue
Block a user