Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Add updates api route (#2351)
Luke Vellae1e125a20e41
diff --git a/apps/web/Dockerfile b/apps/web/Dockerfileindex 6421d43d4..10c6064c5 100644--- a/apps/web/Dockerfile+++ b/apps/web/Dockerfile@@ -78,6 +78,10 @@ ENV PORT=3000ENV HOSTNAME=0.0.0.0ENV LOG_LEVEL=warn+# Rallly cloud API base URL. Set here so only self-hosted images phone home;+# local dev and cloud builds leave it unset and skip outbound calls entirely.+ENV API_BASE_URL=https://api.rallly.co+ARG SELF_HOSTEDENV NEXT_PUBLIC_SELF_HOSTED=$SELF_HOSTEDdiff --git a/apps/web/next.config.ts b/apps/web/next.config.tsindex df436d267..919d980a0 100644--- a/apps/web/next.config.ts+++ b/apps/web/next.config.ts@@ -48,6 +48,17 @@ const nextConfig: NextConfig = {typescript: {ignoreBuildErrors: true,},+ async rewrites() {+ if (!process.env.API_BASE_URL) return [];+ const host = new URL(process.env.API_BASE_URL).host;+ return [+ {+ source: "/:path*",+ has: [{ type: "host", value: host }],+ destination: "/api/:path*",+ },+ ];+ },async redirects() {return [{diff --git a/apps/web/src/app/api/updates/route.ts b/apps/web/src/app/api/updates/route.tsnew file mode 100644index 000000000..6327626f0--- /dev/null+++ b/apps/web/src/app/api/updates/route.ts@@ -0,0 +1,117 @@+import { prisma } from "@rallly/database";+import type { NextRequest } from "next/server";+import { after, NextResponse } from "next/server";+import * as z from "zod";+import { createCache } from "@/lib/cache";+import { createRatelimit } from "@/lib/rate-limit";+import { isSelfHosted } from "@/utils/constants";++const GITHUB_RELEASES_URL =+ "https://api.github.com/repos/lukevella/rallly/releases/latest";++const upstreamSchema = z.object({+ tag_name: z.string().min(1),+ html_url: z.string().min(1),+ published_at: z.string().min(1),+});++type UpdatesPayload = {+ latest: string;+ url: string;+ publishedAt: string;+};++const latestReleaseCache = createCache<UpdatesPayload>({+ namespace: "updates:latest-release",+ ttl: "1 h",+});++const seenInstanceCache = createCache<string>({+ namespace: "updates:seen-instance",+ ttl: "1 d",+});++const ratelimit = createRatelimit(60, "1 h");++async function fetchLatestRelease(): Promise<UpdatesPayload | null> {+ const res = await fetch(GITHUB_RELEASES_URL, {+ headers: {+ Accept: "application/vnd.github+json",+ "User-Agent": "Rallly",+ },+ });+ if (!res.ok) return null;++ const parsed = upstreamSchema.safeParse(await res.json());+ if (!parsed.success) return null;++ return {+ latest: parsed.data.tag_name,+ url: parsed.data.html_url,+ publishedAt: parsed.data.published_at,+ };+}++async function getLatestRelease(): Promise<UpdatesPayload | null> {+ const cached = await latestReleaseCache.get("latest");+ if (cached) return cached;++ const fresh = await fetchLatestRelease();+ if (fresh) await latestReleaseCache.set("latest", fresh);+ return fresh;+}++export async function GET(request: NextRequest) {+ if (isSelfHosted) {+ return new NextResponse(null, { status: 404 });+ }++ const ip = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim();+ const limitKey = ip || "unknown";+ if (ratelimit) {+ const { success } = await ratelimit.limit(`api:updates:${limitKey}`);+ if (!success) {+ return NextResponse.json({ error: "rate_limited" }, { status: 429 });+ }+ }++ const payload = await getLatestRelease();++ if (!payload) {+ return NextResponse.json(+ { error: "upstream_unavailable" },+ { status: 502 },+ );+ }++ const version = request.nextUrl.searchParams.get("version");+ const instanceId = request.nextUrl.searchParams.get("instanceId");+ const parsedVersion = z+ .string()+ .max(64)+ .regex(/^v?\d+(\.\d+){0,2}([-+][0-9A-Za-z.-]+)?$/)+ .safeParse(version);+ const parsedInstanceId = z.uuid().safeParse(instanceId);++ if (parsedVersion.success && parsedInstanceId.success) {+ const validVersion = parsedVersion.data;+ const validInstanceId = parsedInstanceId.data;+ after(async () => {+ try {+ const cachedVersion = await seenInstanceCache.get(validInstanceId);+ if (cachedVersion === validVersion) return;++ await prisma.registeredInstance.upsert({+ where: { instanceId: validInstanceId },+ create: { instanceId: validInstanceId, version: validVersion },+ update: { version: validVersion, lastSeenAt: new Date() },+ });+ await seenInstanceCache.set(validInstanceId, validVersion);+ } catch (error) {+ console.error("Failed to upsert RegisteredInstance", error);+ }+ });+ }++ return NextResponse.json(payload);+}diff --git a/apps/web/src/env.ts b/apps/web/src/env.tsindex ce1010d82..5427bbcf7 100644--- a/apps/web/src/env.ts+++ b/apps/web/src/env.ts@@ -150,6 +150,13 @@ export const env = createEnv({* If not set, Turnstile verification is disabled.*/TURNSTILE_SECRET_KEY: z.string().optional(),+ /**+ * Base URL of the Rallly cloud API (e.g. https://api.rallly.co).+ * Set by the self-hosted Docker image so the instance can phone home for+ * update checks. Unset elsewhere — the features that depend on it no-op+ * when it's missing.+ */+ API_BASE_URL: z.url().optional(),},/** Environment variables available on the client (and server).@@ -241,6 +248,7 @@ export const env = createEnv({HIDE_ATTRIBUTION: process.env.HIDE_ATTRIBUTION,RATE_LIMIT_ENABLED: process.env.RATE_LIMIT_ENABLED,TURNSTILE_SECRET_KEY: process.env.TURNSTILE_SECRET_KEY,+ API_BASE_URL: process.env.API_BASE_URL,NEXT_PUBLIC_TURNSTILE_SITE_KEY: process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY,NEXT_PUBLIC_CDN_BASE_URL: process.env.NEXT_PUBLIC_CDN_BASE_URL,},diff --git a/apps/web/src/lib/cache/index.ts b/apps/web/src/lib/cache/index.tsnew file mode 100644index 000000000..ee8a94634--- /dev/null+++ b/apps/web/src/lib/cache/index.ts@@ -0,0 +1,78 @@+import "server-only";+import { redis } from "@/lib/kv";++export type Unit = "ms" | "s" | "m" | "h" | "d";+export type Duration = `${number} ${Unit}` | `${number}${Unit}`;++const unitToMs: Record<Unit, number> = {+ ms: 1,+ s: 1000,+ m: 60_000,+ h: 3_600_000,+ d: 86_400_000,+};++function parseDurationMs(duration: Duration): number {+ const match = duration.match(/^(\d+)\s?(ms|s|m|h|d)$/);+ if (!match) {+ throw new Error(`Invalid duration: ${duration}`);+ }+ return Number(match[1]) * unitToMs[match[2] as Unit];+}++interface Cache<T> {+ get(key: string): Promise<T | null>;+ set(key: string, value: T): Promise<void>;+ name: "redis" | "memory";+}++function createMemoryCache<T>(prefix: string, ttlMs: number): Cache<T> {+ const store = new Map<string, { value: T; expiresAt: number }>();++ return {+ async get(key) {+ const entry = store.get(prefix + key);+ if (!entry) return null;+ if (Date.now() >= entry.expiresAt) {+ store.delete(prefix + key);+ return null;+ }+ return entry.value;+ },+ async set(key, value) {+ store.set(prefix + key, { value, expiresAt: Date.now() + ttlMs });+ },+ name: "memory",+ };+}++/**+ * Creates a namespaced cache backed by the configured KV store, falling back+ * to an in-memory Map when no KV is configured (e.g. self-hosted without Redis).+ */+export function createCache<T>({+ namespace,+ ttl,+}: {+ namespace: string;+ ttl: Duration;+}): Cache<T> {+ const ttlMs = parseDurationMs(ttl);+ const prefix = `cache:${namespace}:`;++ if (redis) {+ const client = redis;+ const ttlSeconds = Math.max(1, Math.floor(ttlMs / 1000));+ return {+ async get(key) {+ return (await client.get<T>(prefix + key)) ?? null;+ },+ async set(key, value) {+ await client.set(prefix + key, value, { ex: ttlSeconds });+ },+ name: "redis",+ };+ }++ return createMemoryCache<T>(prefix, ttlMs);+}diff --git a/packages/database/prisma/migrations/20260423172330_add_registered_instance/migration.sql b/packages/database/prisma/migrations/20260423172330_add_registered_instance/migration.sqlnew file mode 100644index 000000000..9517c3e70--- /dev/null+++ b/packages/database/prisma/migrations/20260423172330_add_registered_instance/migration.sql@@ -0,0 +1,13 @@+-- CreateTable+CREATE TABLE "registered_instances" (+ "id" TEXT NOT NULL,+ "instance_id" TEXT NOT NULL,+ "version" TEXT NOT NULL,+ "first_seen_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "last_seen_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "registered_instances_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE UNIQUE INDEX "registered_instances_instance_id_key" ON "registered_instances"("instance_id");diff --git a/packages/database/prisma/models/registered-instance.prisma b/packages/database/prisma/models/registered-instance.prismanew file mode 100644index 000000000..cf065a8c8--- /dev/null+++ b/packages/database/prisma/models/registered-instance.prisma@@ -0,0 +1,9 @@+model RegisteredInstance {+ id String @id @default(cuid())+ instanceId String @unique @map("instance_id")+ version String+ firstSeenAt DateTime @default(now()) @map("first_seen_at")+ lastSeenAt DateTime @default(now()) @updatedAt @map("last_seen_at")++ @@map("registered_instances")+}