Skip to content

An AI-powered search engine with a generative UI

feat(version): add sidebar version footer with update indicator (#1078)

Nathan Pride731cda98c267
diff --git a/Dockerfile b/Dockerfile
index 02100bcd..484b7c4f 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -20,6 +20,9 @@ RUN npm run build
FROM node:22-slim AS runner
WORKDIR /app
+# Install method shown in the sidebar version footer
+ENV MORPHIC_INSTALL_METHOD=docker
+
# Install bun for dependency management (used for migrations)
RUN npm install -g bun
diff --git a/app/layout.tsx b/app/layout.tsx
index 8c10272b..8dda84ea 100644
--- a/app/layout.tsx
+++ b/app/layout.tsx
@@ -129,7 +129,7 @@ export default async function RootLayout({
initialUsage={initialUsage}
enabled={usageBudgetEnabled}
>
- {userId && <AppSidebar />}
+ {userId && <AppSidebar user={user} />}
<KeyboardShortcutHandler />
<div className="flex flex-col flex-1 min-w-0">
<Header user={user} />
diff --git a/components/__tests__/app-sidebar.test.tsx b/components/__tests__/app-sidebar.test.tsx
index b6c21e24..0b05226a 100644
--- a/components/__tests__/app-sidebar.test.tsx
+++ b/components/__tests__/app-sidebar.test.tsx
@@ -21,6 +21,10 @@ vi.mock('../sidebar/library-menu-item', () => ({
LibraryMenuItem: () => <div>Library</div>
}))
+vi.mock('../sidebar/version-footer', () => ({
+ VersionFooter: () => <div />
+}))
+
vi.mock('@/hooks/use-mobile', () => ({
useIsMobile: () => false
}))
diff --git a/components/app-sidebar.tsx b/components/app-sidebar.tsx
index de1d08e8..aefb4938 100644
--- a/components/app-sidebar.tsx
+++ b/components/app-sidebar.tsx
@@ -2,11 +2,13 @@ import { Suspense } from 'react'
import Link from 'next/link'
import { isAnonymousMode } from '@/lib/auth/provider'
+import type { AppUser } from '@/lib/auth/types'
import { cn } from '@/lib/utils'
import {
Sidebar,
SidebarContent,
+ SidebarFooter,
SidebarHeader,
SidebarMenu,
SidebarRail,
@@ -17,9 +19,11 @@ import { ChatHistorySection } from './sidebar/chat-history-section'
import { ChatHistorySkeleton } from './sidebar/chat-history-skeleton'
import { LibraryMenuItem } from './sidebar/library-menu-item'
import { NewChatMenuItem } from './sidebar/new-chat-menu-item'
+import { VersionFooter } from './sidebar/version-footer'
+import { VersionFooterSkeleton } from './sidebar/version-footer-skeleton'
import { IconLogo } from './ui/icons'
-export default function AppSidebar() {
+export default function AppSidebar({ user }: { user?: AppUser | null }) {
// Anonymous mode has no per-user library, and the server actions reject it,
// so the entry point follows the same switch the pages use.
const libraryAvailable = !isAnonymousMode()
@@ -44,6 +48,11 @@ export default function AppSidebar() {
</Suspense>
</div>
</SidebarContent>
+ <SidebarFooter>
+ <Suspense fallback={<VersionFooterSkeleton />}>
+ <VersionFooter user={user} />
+ </Suspense>
+ </SidebarFooter>
<SidebarRail />
</Sidebar>
)
diff --git a/components/sidebar/__tests__/version-footer.test.tsx b/components/sidebar/__tests__/version-footer.test.tsx
new file mode 100644
index 00000000..d34d886b
--- /dev/null
+++ b/components/sidebar/__tests__/version-footer.test.tsx
@@ -0,0 +1,157 @@
+import { render, screen } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
+
+import { isAnonymousMode } from '@/lib/auth/provider'
+import type { AppUser } from '@/lib/auth/types'
+import { checkForUpdate } from '@/lib/version/update-check'
+
+import packageJson from '../../../package.json'
+import { VersionFooter } from '../version-footer'
+
+vi.mock('@/lib/auth/provider', () => ({
+ isAnonymousMode: vi.fn()
+}))
+
+vi.mock('@/lib/version/update-check', () => ({
+ checkForUpdate: vi.fn()
+}))
+
+const mockedIsAnonymousMode = vi.mocked(isAnonymousMode)
+const mockedCheckForUpdate = vi.mocked(checkForUpdate)
+
+const UPDATE_RESULT = {
+ hasUpdate: true,
+ latestVersion: 'v1.9.0',
+ releaseUrl: 'https://github.com/miurla/morphic/releases/tag/v1.9.0'
+}
+
+function appUser(role?: string): AppUser {
+ return {
+ id: 'user-1',
+ email: '[email protected]',
+ role
+ }
+}
+
+async function renderFooter(user?: AppUser | null) {
+ render(await VersionFooter({ user }))
+}
+
+describe('VersionFooter', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.stubEnv('MORPHIC_INSTALL_METHOD', 'docker')
+ mockedIsAnonymousMode.mockReturnValue(false)
+ mockedCheckForUpdate.mockResolvedValue({ hasUpdate: false })
+ })
+
+ afterEach(() => {
+ vi.unstubAllEnvs()
+ })
+
+ test('shows the version link and install label when up to date', async () => {
+ await renderFooter()
+
+ const versionLink = screen.getByRole('link', {
+ name: `v${packageJson.version}`
+ })
+ expect(versionLink).toHaveAttribute(
+ 'href',
+ 'https://github.com/miurla/morphic/releases'
+ )
+ expect(versionLink).toHaveAttribute('target', '_blank')
+ expect(versionLink).toHaveAttribute('rel', 'noopener')
+ expect(screen.getByText('docker')).toBeInTheDocument()
+ expect(screen.queryByText(/Update:/)).not.toBeInTheDocument()
+ })
+
+ test('shows the update link to an admin', async () => {
+ mockedCheckForUpdate.mockResolvedValue(UPDATE_RESULT)
+
+ await renderFooter(appUser('admin'))
+
+ const updateLink = screen.getByRole('link', { name: 'Update: v1.9.0' })
+ expect(updateLink).toHaveAttribute(
+ 'href',
+ 'https://github.com/miurla/morphic/releases/tag/v1.9.0'
+ )
+ expect(updateLink).toHaveAttribute('target', '_blank')
+ expect(updateLink).toHaveAttribute('rel', 'noopener')
+ expect(screen.queryByText('docker')).not.toBeInTheDocument()
+ })
+
+ test('hides the update link from non-admin users', async () => {
+ mockedCheckForUpdate.mockResolvedValue(UPDATE_RESULT)
+
+ await renderFooter(appUser('user'))
+
+ expect(screen.queryByText(/Update:/)).not.toBeInTheDocument()
+ expect(screen.getByText('docker')).toBeInTheDocument()
+ })
+
+ test('hides the update link when the provider exposes no role', async () => {
+ mockedCheckForUpdate.mockResolvedValue(UPDATE_RESULT)
+
+ await renderFooter(appUser())
+
+ expect(screen.queryByText(/Update:/)).not.toBeInTheDocument()
+ expect(screen.getByText('docker')).toBeInTheDocument()
+ })
+
+ test('shows the update link to an allowlisted email without a role', async () => {
+ vi.stubEnv('MORPHIC_ADMIN_EMAILS', '[email protected]')
+ mockedCheckForUpdate.mockResolvedValue(UPDATE_RESULT)
+
+ await renderFooter(appUser())
+
+ expect(
+ screen.getByRole('link', { name: 'Update: v1.9.0' })
+ ).toBeInTheDocument()
+ })
+
+ test('matches allowlisted emails case-insensitively', async () => {
+ vi.stubEnv('MORPHIC_ADMIN_EMAILS', '[email protected], [email protected]')
+ mockedCheckForUpdate.mockResolvedValue(UPDATE_RESULT)
+
+ await renderFooter(appUser())
+
+ expect(
+ screen.getByRole('link', { name: 'Update: v1.9.0' })
+ ).toBeInTheDocument()
+ })
+
+ test('hides the update link for an email outside the allowlist', async () => {
+ vi.stubEnv('MORPHIC_ADMIN_EMAILS', '[email protected]')
+ mockedCheckForUpdate.mockResolvedValue(UPDATE_RESULT)
+
+ await renderFooter(appUser())
+
+ expect(screen.queryByText(/Update:/)).not.toBeInTheDocument()
+ })
+
+ test('shows the update link in anonymous mode without a resolved user', async () => {
+ mockedIsAnonymousMode.mockReturnValue(true)
+ mockedCheckForUpdate.mockResolvedValue(UPDATE_RESULT)
+
+ await renderFooter(null)
+
+ expect(
+ screen.getByRole('link', { name: 'Update: v1.9.0' })
+ ).toBeInTheDocument()
+ })
+
+ test('degrades to version and label when the check throws', async () => {
+ mockedCheckForUpdate.mockRejectedValue(new Error('boom'))
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ await renderFooter()
+
+ expect(
+ screen.getByRole('link', { name: `v${packageJson.version}` })
+ ).toBeInTheDocument()
+ expect(screen.getByText('docker')).toBeInTheDocument()
+ expect(screen.queryByText(/Update:/)).not.toBeInTheDocument()
+
+ warnSpy.mockRestore()
+ })
+})
diff --git a/components/sidebar/version-footer-skeleton.tsx b/components/sidebar/version-footer-skeleton.tsx
new file mode 100644
index 00000000..f5137839
--- /dev/null
+++ b/components/sidebar/version-footer-skeleton.tsx
@@ -0,0 +1,19 @@
+import { Skeleton } from '@/components/ui/skeleton'
+
+/**
+ * Placeholder matching the version footer's two-line height so the sidebar
+ * footer area does not shift when the footer streams in after a cold update
+ * check.
+ */
+export function VersionFooterSkeleton() {
+ return (
+ <div className="text-xs text-center space-y-0.5">
+ <div className="flex justify-center">
+ <Skeleton className="h-4 w-14" />
+ </div>
+ <div className="flex justify-center">
+ <Skeleton className="h-4 w-10" />
+ </div>
+ </div>
+ )
+}
diff --git a/components/sidebar/version-footer.tsx b/components/sidebar/version-footer.tsx
new file mode 100644
index 00000000..edc39a16
--- /dev/null
+++ b/components/sidebar/version-footer.tsx
@@ -0,0 +1,84 @@
+import { isAnonymousMode } from '@/lib/auth/provider'
+import type { AppUser } from '@/lib/auth/types'
+import { parseAdminEmails } from '@/lib/version/admins'
+import { getVersionCheckConfig } from '@/lib/version/config'
+import { resolveInstallMethod } from '@/lib/version/install-method'
+import {
+ checkForUpdate,
+ type UpdateCheckResult
+} from '@/lib/version/update-check'
+
+import packageJson from '../../package.json'
+
+/**
+ * The viewer counts as an admin when the resolved auth provider is the
+ * anonymous one (single-operator mode, which sets no role), when the provider
+ * resolved an `admin` role onto the user (e.g. Better Auth), or when the
+ * user's email is on the `MORPHIC_ADMIN_EMAILS` allowlist (for providers
+ * without a role concept, e.g. Supabase). The user is the one the root layout
+ * already resolved, so the footer performs no auth lookup of its own.
+ */
+function isAdminViewer(user: AppUser | null | undefined): boolean {
+ if (isAnonymousMode()) {
+ return true
+ }
+ if (!user) {
+ return false
+ }
+ if (user.role === 'admin') {
+ return true
+ }
+ return (
+ !!user.email && parseAdminEmails(process.env).has(user.email.toLowerCase())
+ )
+}
+
+/**
+ * Sidebar footer showing the running version and install method, plus an
+ * update link for admins when a newer upstream release exists. Any failure
+ * in the update check degrades to version + install label.
+ */
+export async function VersionFooter({ user }: { user?: AppUser | null }) {
+ const version = packageJson.version
+ const installMethod = resolveInstallMethod(process.env)
+ const { repo } = getVersionCheckConfig()
+
+ let update: UpdateCheckResult | null = null
+ try {
+ const result = await checkForUpdate(version)
+ if (result.hasUpdate && isAdminViewer(user)) {
+ update = result
+ }
+ } catch (error) {
+ console.warn('[version] update indicator degraded to label only:', error)
+ }
+
+ return (
+ <div className="text-xs text-muted-foreground text-center space-y-0.5">
+ <div>
+ <a
+ href={`https://github.com/${repo}/releases`}
+ target="_blank"
+ rel="noopener"
+ className="font-mono underline"
+ >
+ v{version}
+ </a>
+ </div>
+ <div>
+ {update ? (
+ <a
+ href={update.releaseUrl}
+ target="_blank"
+ rel="noopener"
+ className="text-destructive underline"
+ >
+ Update: {update.latestVersion}
+ </a>
+ ) : (
+ <span className="italic">{installMethod}</span>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/docker-compose.yaml b/docker-compose.yaml
index c9854de8..0613121b 100644
--- a/docker-compose.yaml
+++ b/docker-compose.yaml
@@ -32,6 +32,12 @@ services:
LOCAL_REDIS_URL: ${LOCAL_REDIS_URL:-redis://redis:6379}
SEARCH_API: ${SEARCH_API:-searxng}
SEARXNG_API_URL: ${SEARXNG_API_URL:-http://searxng:8080}
+ # Version footer / update check (all optional, see docs/CONFIGURATION.md)
+ # MORPHIC_INSTALL_METHOD: docker # Footer label; the image already sets this
+ # MORPHIC_UPDATE_CHECK_REPO: miurla/morphic # Upstream repo to check (default: miurla/morphic)
+ # MORPHIC_UPDATE_CHECK_TTL_SECONDS: '86400' # Check cache window in seconds (default: 86400, floor 300)
+ # MORPHIC_UPDATE_CHECK_DISABLED: 'false' # Set to 'true' to skip upstream requests entirely
+ # MORPHIC_ADMIN_EMAILS: '[email protected]' # Extra admin emails for the update link (providers without roles)
ports:
- '3000:3000' # Maps port 3000 on the host to port 3000 in the container.
depends_on:
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 5dafccf5..cc918702 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -501,3 +501,34 @@ CRAWL4AI_BASE_URL=http://localhost:11235
# Optional: only needed when the instance requires an API key
# CRAWL4AI_API_KEY=[YOUR_CRAWL4AI_API_KEY]
```
+
+### Version and Update Check
+
+The sidebar footer shows the running version (linking to the upstream releases page) and the install method. The server checks the upstream GitHub releases feed once per cache window; when a newer stable release exists, admins see an `Update: vX.Y.Z` link in place of the install label. The check is not user-specific: it runs once per cache window whenever any viewer triggers a render, and the cached result is shared. The check is silent on any failure and never blocks rendering.
+
+```bash
+# Optional: install-method label shown in the footer. Used verbatim, so any
+# value works (the Docker image sets `docker`). Defaults to `vercel` on
+# Vercel, `source` elsewhere.
+MORPHIC_INSTALL_METHOD=docker
+
+# Optional: upstream owner/repo whose latest release is checked
+# (default: miurla/morphic)
+MORPHIC_UPDATE_CHECK_REPO=miurla/morphic
+
+# Optional: cache window for the release check, in seconds
+# (default: 86400; values below 300 are clamped to 300; unset, empty, or
+# non-numeric values fall back to the default)
+MORPHIC_UPDATE_CHECK_TTL_SECONDS=86400
+
+# Optional: set to true to perform no upstream requests at all (default: false)
+MORPHIC_UPDATE_CHECK_DISABLED=false
+
+# Optional: comma-separated email addresses treated as admins for the update
+# link (case-insensitive). Useful when the auth provider has no role concept,
+# e.g. Supabase, where no user carries an `admin` role. No effect in anonymous
+# mode, where every viewer counts as an admin.
+```
+
+The update link is shown to administrators only: users with the `admin` role, users whose email is listed in `MORPHIC_ADMIN_EMAILS`, or any user when `ENABLE_AUTH=false` (single-operator anonymous mode). The email allowlist only controls visibility of the update link; it grants no privileges elsewhere in the app. The version identifier and install label stay visible to everyone.
diff --git a/docs/PRIVACY.md b/docs/PRIVACY.md
index a9c4624d..2903f6d6 100644
--- a/docs/PRIVACY.md
+++ b/docs/PRIVACY.md
@@ -2,28 +2,29 @@
This document lists everything a self-hosted Morphic instance can send outside your own server, what each destination receives, and how to turn it off.
-**Morphic never reports anything to the Morphic project or its maintainers.** There is no phone-home endpoint in the codebase. Beyond that, a self-hosted instance contacts the services you configure credentials for, the sites the agent reads, and the browser-side destinations listed below. One case contacts a service you have not configured: see [Reading pages](#reading-pages).
+**Morphic never reports anything to the Morphic project or its maintainers.** There is no phone-home endpoint in the codebase. Beyond that, a self-hosted instance contacts the services you configure credentials for, the sites the agent reads, and the browser-side destinations listed below. Two cases contact a service you have not configured: the pages the agent reads (see [Reading pages](#reading-pages)) and the sidebar update check, which queries the GitHub releases API once per cache window (disable with `MORPHIC_UPDATE_CHECK_DISABLED=true`).
## Summary
Requests made by your server:
-| Destination | What it receives | Default when self-hosting |
-| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- |
-| AI provider (OpenAI, Anthropic, Google, ...) | Full prompt: system prompt, conversation history, search results, attachments | **On.** Required to answer |
-| Search provider (Tavily, SearXNG, Exa, Brave, Firecrawl) | The search query the agent generates | **On.** Required to search |
-| Web pages the agent reads | Your server's IP and user agent, to whichever site the agent chose | On |
-| Jina Reader or Tavily Extract | The URL being read | Only when the agent asks for API extraction |
-| PostgreSQL | Chats, messages, attachment metadata, feedback; with `AUTH_PROVIDER=better-auth`, also the auth tables: accounts, sessions, linked identities, verification tokens, invitations | On. Local container under Docker |
-| Redis | Cached search results, rate limit counters, usage counters | Local container under Docker |
-| Supabase | Email, password, OAuth identity, sessions | Off unless configured |
-| SMTP server | Invitation, password reset, and bootstrap emails: recipient address and a one-time link | Off unless configured |
-| R2 / S3 | Uploaded file bytes, under a key holding the user id, chat id, and filename | Off unless configured |
-| Favicon provider (Google by default) | The hostname of each cited source | On. Configurable, and can be turned off |
-| Slack | Feedback text and the submitter's email | Off unless `SLACK_WEBHOOK_URL` is set |
-| PostHog | Product analytics events. Not the user's query text | **Off** |
-| Langfuse | Full prompts and completions as traces | **Off** |
-| Vercel Analytics | Page views | **Off** |
+| Destination | What it receives | Default when self-hosting |
+| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
+| AI provider (OpenAI, Anthropic, Google, ...) | Full prompt: system prompt, conversation history, search results, attachments | **On.** Required to answer |
+| Search provider (Tavily, SearXNG, Exa, Brave, Firecrawl) | The search query the agent generates | **On.** Required to search |
+| Web pages the agent reads | Your server's IP and user agent, to whichever site the agent chose | On |
+| Jina Reader or Tavily Extract | The URL being read | Only when the agent asks for API extraction |
+| PostgreSQL | Chats, messages, attachment metadata, feedback; with `AUTH_PROVIDER=better-auth`, also the auth tables: accounts, sessions, linked identities, verification tokens, invitations | On. Local container under Docker |
+| Redis | Cached search results, rate limit counters, usage counters | Local container under Docker |
+| Supabase | Email, password, OAuth identity, sessions | Off unless configured |
+| SMTP server | Invitation, password reset, and bootstrap emails: recipient address and a one-time link | Off unless configured |
+| R2 / S3 | Uploaded file bytes, under a key holding the user id, chat id, and filename | Off unless configured |
+| Favicon provider (Google by default) | The hostname of each cited source | On. Configurable, and can be turned off |
+| GitHub releases API | An anonymous request for the latest release of one repo: your server's IP and the repo name. No credentials, no user data | **On.** Once per 24 h; off with `MORPHIC_UPDATE_CHECK_DISABLED=true` |
+| Slack | Feedback text and the submitter's email | Off unless `SLACK_WEBHOOK_URL` is set |
+| PostHog | Product analytics events. Not the user's query text | **Off** |
+| Langfuse | Full prompts and completions as traces | **Off** |
+| Vercel Analytics | Page views | **Off** |
Requests made by the user's browser, which env vars do not control:
@@ -135,5 +136,6 @@ To run Morphic with as little as possible leaving your network:
- The Docker Compose PostgreSQL and Redis containers
- No PostHog, Langfuse, Supabase, R2, or Slack credentials
- `NEXT_TELEMETRY_DISABLED=1`
+- `MORPHIC_UPDATE_CHECK_DISABLED=true`
Pages the agent reads are still fetched from their origin sites, which is the point of a search engine, and the browser-side requests above still happen.
diff --git a/lib/version/__tests__/admins.test.ts b/lib/version/__tests__/admins.test.ts
new file mode 100644
index 00000000..f4dfb753
--- /dev/null
+++ b/lib/version/__tests__/admins.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, test } from 'vitest'
+
+import { parseAdminEmails } from '../admins'
+
+describe('parseAdminEmails', () => {
+ test.each([
+ { name: 'unset yields an empty allowlist', env: {}, expected: [] },
+ {
+ name: 'empty string yields an empty allowlist',
+ env: { MORPHIC_ADMIN_EMAILS: '' },
+ expected: []
+ },
+ {
+ name: 'single email',
+ env: { MORPHIC_ADMIN_EMAILS: '[email protected]' },
+ expected: ['[email protected]']
+ },
+ {
+ name: 'entries are trimmed and lowercased',
+ env: { MORPHIC_ADMIN_EMAILS: ' [email protected] ' },
+ expected: ['[email protected]']
+ },
+ {
+ name: 'multiple emails with empty segments ignored',
+ env: { MORPHIC_ADMIN_EMAILS: '[email protected],, [email protected] ,' },
+ },
+ {
+ name: 'duplicates collapse',
+ env: { MORPHIC_ADMIN_EMAILS: '[email protected],[email protected]' },
+ expected: ['[email protected]']
+ }
+ ])('$name', ({ env, expected }) => {
+ expect([...parseAdminEmails(env)]).toEqual(expected)
+ })
+})
diff --git a/lib/version/__tests__/config.test.ts b/lib/version/__tests__/config.test.ts
new file mode 100644
index 00000000..8af8e82d
--- /dev/null
+++ b/lib/version/__tests__/config.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, test, vi } from 'vitest'
+
+import { parseVersionCheckConfig } from '../config'
+
+describe('parseVersionCheckConfig', () => {
+ test.each([
+ {
+ name: 'defaults when nothing is set',
+ env: {},
+ expected: {
+ repo: 'miurla/morphic',
+ ttlSeconds: 86400,
+ disabled: false
+ }
+ },
+ {
+ name: 'repo override',
+ env: { MORPHIC_UPDATE_CHECK_REPO: 'acme/morphic' },
+ expected: {
+ repo: 'acme/morphic',
+ ttlSeconds: 86400,
+ disabled: false
+ }
+ },
+ {
+ name: 'ttl override',
+ env: { MORPHIC_UPDATE_CHECK_TTL_SECONDS: '3600' },
+ expected: {
+ repo: 'miurla/morphic',
+ ttlSeconds: 3600,
+ disabled: false
+ }
+ },
+ {
+ name: 'ttl below floor clamps to 300',
+ env: { MORPHIC_UPDATE_CHECK_TTL_SECONDS: '10' },
+ expected: {
+ repo: 'miurla/morphic',
+ ttlSeconds: 300,
+ disabled: false
+ }
+ },
+ {
+ name: 'ttl at the floor stays at 300',
+ env: { MORPHIC_UPDATE_CHECK_TTL_SECONDS: '300' },
+ expected: {
+ repo: 'miurla/morphic',
+ ttlSeconds: 300,
+ disabled: false
+ }
+ },
+ {
+ name: 'non-numeric ttl falls back to the default',
+ env: { MORPHIC_UPDATE_CHECK_TTL_SECONDS: 'banana' },
+ expected: {
+ repo: 'miurla/morphic',
+ ttlSeconds: 86400,
+ disabled: false
+ }
+ },
+ {
+ name: 'empty ttl falls back to the default',
+ env: { MORPHIC_UPDATE_CHECK_TTL_SECONDS: '' },
+ expected: {
+ repo: 'miurla/morphic',
+ ttlSeconds: 86400,
+ disabled: false
+ }
+ },
+ {
+ name: 'fractional ttl is truncated',
+ env: { MORPHIC_UPDATE_CHECK_TTL_SECONDS: '3600.9' },
+ expected: {
+ repo: 'miurla/morphic',
+ ttlSeconds: 3600,
+ disabled: false
+ }
+ },
+ {
+ name: 'disabled flag',
+ env: { MORPHIC_UPDATE_CHECK_DISABLED: 'true' },
+ expected: {
+ repo: 'miurla/morphic',
+ ttlSeconds: 86400,
+ disabled: true
+ }
+ },
+ {
+ name: 'disabled only matches the literal true',
+ env: { MORPHIC_UPDATE_CHECK_DISABLED: 'yes' },
+ expected: {
+ repo: 'miurla/morphic',
+ ttlSeconds: 86400,
+ disabled: false
+ }
+ }
+ ])('$name', ({ env, expected }) => {
+ expect(parseVersionCheckConfig(env)).toEqual(expected)
+ })
+
+ test('valid repo variants pass through', () => {
+ expect(
+ parseVersionCheckConfig({
+ MORPHIC_UPDATE_CHECK_REPO: 'acme-foundation/morphic.rs'
+ }).repo
+ ).toBe('acme-foundation/morphic.rs')
+ })
+
+ test('invalid repo values fall back to the default with a warning', () => {
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const invalid = [
+ 'https://github.com/acme/morphic',
+ 'acme/morphic/',
+ 'acme/morphic/extra',
+ 'not a repo',
+ 'acme'
+ ]
+ for (const repo of invalid) {
+ expect(
+ parseVersionCheckConfig({ MORPHIC_UPDATE_CHECK_REPO: repo }).repo
+ ).toBe('miurla/morphic')
+ }
+ expect(warnSpy).toHaveBeenCalledTimes(invalid.length)
+
+ warnSpy.mockRestore()
+ })
+})
diff --git a/lib/version/__tests__/install-method.test.ts b/lib/version/__tests__/install-method.test.ts
new file mode 100644
index 00000000..9d13c2f2
--- /dev/null
+++ b/lib/version/__tests__/install-method.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, test } from 'vitest'
+
+import { resolveInstallMethod } from '../install-method'
+
+describe('resolveInstallMethod', () => {
+ test.each([
+ {
+ name: 'explicit override is used verbatim',
+ env: { MORPHIC_INSTALL_METHOD: 'unraid' },
+ expected: 'unraid'
+ },
+ {
+ name: 'explicit override wins over Vercel detection',
+ env: { MORPHIC_INSTALL_METHOD: 'docker', VERCEL: '1' },
+ expected: 'docker'
+ },
+ {
+ name: 'Vercel detection when no override is set',
+ env: { VERCEL: '1' },
+ expected: 'vercel'
+ },
+ {
+ name: 'empty override falls through to Vercel detection',
+ env: { MORPHIC_INSTALL_METHOD: '', VERCEL: '1' },
+ expected: 'vercel'
+ },
+ {
+ name: 'defaults to source',
+ env: {},
+ expected: 'source'
+ }
+ ])('$name', ({ env, expected }) => {
+ expect(resolveInstallMethod(env)).toBe(expected)
+ })
+})
diff --git a/lib/version/__tests__/semver.test.ts b/lib/version/__tests__/semver.test.ts
new file mode 100644
index 00000000..b476e73f
--- /dev/null
+++ b/lib/version/__tests__/semver.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, test } from 'vitest'
+
+import { isUpdateAvailable, parseReleaseTag } from '../semver'
+
+describe('parseReleaseTag', () => {
+ test.each([
+ { tag: 'v1.8.0', expected: { major: 1, minor: 8, patch: 0 } },
+ { tag: '1.8.0', expected: { major: 1, minor: 8, patch: 0 } },
+ { tag: 'v0.0.1', expected: { major: 0, minor: 0, patch: 1 } },
+ { tag: 'v1.8.0-rc1', expected: null },
+ { tag: 'v1.8', expected: null },
+ { tag: 'v1', expected: null },
+ { tag: 'release-1.8.0', expected: null },
+ { tag: '', expected: null }
+ ])('parses $tag', ({ tag, expected }) => {
+ expect(parseReleaseTag(tag)).toEqual(expected)
+ })
+})
+
+describe('isUpdateAvailable', () => {
+ test.each([
+ { current: '1.7.0', tag: 'v1.8.0', expected: true },
+ { current: '1.7.0', tag: 'v2.0.0', expected: true },
+ { current: '1.7.0', tag: 'v1.7.1', expected: true },
+ { current: '1.7.0', tag: '1.8.0', expected: true },
+ { current: '1.7.0', tag: 'v1.7.0', expected: false },
+ { current: '1.7.0', tag: 'v1.6.9', expected: false },
+ { current: '2.0.0', tag: 'v1.9.9', expected: false },
+ { current: '1.7.0', tag: 'v1.8.0-rc1', expected: false },
+ { current: '1.7.0', tag: 'not-a-version', expected: false },
+ { current: 'not-a-version', tag: 'v1.8.0', expected: false }
+ ])('current $current vs $tag', ({ current, tag, expected }) => {
+ expect(isUpdateAvailable(current, tag)).toBe(expected)
+ })
+})
diff --git a/lib/version/__tests__/update-check.test.ts b/lib/version/__tests__/update-check.test.ts
new file mode 100644
index 00000000..bd70eb93
--- /dev/null
+++ b/lib/version/__tests__/update-check.test.ts
@@ -0,0 +1,299 @@
+import { beforeEach, describe, expect, test, vi } from 'vitest'
+
+import { getVersionCheckConfig } from '../config'
+import { checkForUpdate, resetFailureBackoff } from '../update-check'
+
+vi.mock('../config', () => ({
+ getVersionCheckConfig: vi.fn()
+}))
+
+const mockedGetConfig = vi.mocked(getVersionCheckConfig)
+
+function mockFetchSuccess(body: unknown) {
+ return vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: async () => body
+ })
+}
+
+describe('checkForUpdate', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ resetFailureBackoff()
+ mockedGetConfig.mockReturnValue({
+ repo: 'miurla/morphic',
+ ttlSeconds: 86400,
+ disabled: false
+ })
+ })
+
+ test('reports an update for a newer upstream release', async () => {
+ // html_url is deliberately hostile: the release link must be built from
+ // the configured repo and the parsed tag, never from the response body.
+ const fetchMock = mockFetchSuccess({
+ tag_name: 'v1.8.0',
+ html_url: 'https://redirect.example.com/not-trusted'
+ })
+ vi.stubGlobal('fetch', fetchMock)
+
+ const result = await checkForUpdate('1.7.0')
+
+ expect(result).toEqual({
+ hasUpdate: true,
+ latestVersion: 'v1.8.0',
+ releaseUrl: 'https://github.com/miurla/morphic/releases/tag/v1.8.0'
+ })
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://api.github.com/repos/miurla/morphic/releases/latest',
+ expect.objectContaining({
+ next: { revalidate: 86400 },
+ headers: { accept: 'application/vnd.github+json' },
+ signal: expect.any(AbortSignal)
+ })
+ )
+
+ vi.unstubAllGlobals()
+ })
+
+ test('reports no update when upstream is at or behind the running version', async () => {
+ vi.stubGlobal('fetch', mockFetchSuccess({ tag_name: 'v1.7.0' }))
+
+ expect(await checkForUpdate('1.7.0')).toEqual({ hasUpdate: false })
+
+ vi.unstubAllGlobals()
+ })
+
+ test('degrades to no-update on timeout', async () => {
+ const timeoutError = new Error('The operation was aborted due to timeout')
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(timeoutError))
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ expect(await checkForUpdate('1.7.0')).toEqual({ hasUpdate: false })
+ expect(warnSpy).toHaveBeenCalled()
+
+ warnSpy.mockRestore()
+ vi.unstubAllGlobals()
+ })
+
+ test('degrades to no-update on a 403 rate-limit response', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue({ ok: false, status: 403 })
+ )
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ expect(await checkForUpdate('1.7.0')).toEqual({ hasUpdate: false })
+ expect(warnSpy).toHaveBeenCalled()
+
+ warnSpy.mockRestore()
+ vi.unstubAllGlobals()
+ })
+
+ test.each([
+ {
+ name: 'json body is not valid JSON',
+ response: {
+ ok: true,
+ status: 200,
+ json: async () => {
+ throw new SyntaxError('Unexpected token < in JSON')
+ }
+ }
+ },
+ {
+ name: 'payload lacks a tag',
+ response: { ok: true, status: 200, json: async () => ({}) }
+ },
+ {
+ name: 'payload has an unparseable prerelease tag',
+ response: {
+ ok: true,
+ status: 200,
+ json: async () => ({ tag_name: 'v1.8.0-rc1' })
+ }
+ }
+ ])(
+ 'degrades to no-update on a malformed payload: $name',
+ async ({ response }) => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response))
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ expect(await checkForUpdate('1.7.0')).toEqual({ hasUpdate: false })
+
+ warnSpy.mockRestore()
+ vi.unstubAllGlobals()
+ }
+ )
+
+ test('makes no upstream request when the check is disabled', async () => {
+ mockedGetConfig.mockReturnValue({
+ repo: 'miurla/morphic',
+ ttlSeconds: 86400,
+ disabled: true
+ })
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+
+ expect(await checkForUpdate('1.7.0')).toEqual({ hasUpdate: false })
+ expect(fetchMock).not.toHaveBeenCalled()
+
+ vi.unstubAllGlobals()
+ })
+
+ test('concurrent calls share a single upstream request', async () => {
+ let settleFetch!: (response: unknown) => void
+ const fetchMock = vi.fn().mockImplementation(
+ () =>
+ new Promise(resolve => {
+ settleFetch = resolve
+ })
+ )
+ vi.stubGlobal('fetch', fetchMock)
+
+ const first = checkForUpdate('1.7.0')
+ const second = checkForUpdate('1.7.0')
+ settleFetch({
+ ok: true,
+ status: 200,
+ json: async () => ({ tag_name: 'v1.8.0' })
+ })
+
+ const [r1, r2] = await Promise.all([first, second])
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(r1).toEqual({
+ hasUpdate: true,
+ latestVersion: 'v1.8.0',
+ releaseUrl: 'https://github.com/miurla/morphic/releases/tag/v1.8.0'
+ })
+ expect(r2).toEqual(r1)
+
+ vi.unstubAllGlobals()
+ })
+
+ test('concurrent calls share a single request when the upstream fails', async () => {
+ let failFetch!: (error: unknown) => void
+ const fetchMock = vi.fn().mockImplementation(
+ () =>
+ new Promise((_resolve, reject) => {
+ failFetch = reject
+ })
+ )
+ vi.stubGlobal('fetch', fetchMock)
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ const first = checkForUpdate('1.7.0')
+ const second = checkForUpdate('1.7.0')
+ failFetch(new TypeError('fetch failed'))
+
+ expect(await Promise.all([first, second])).toEqual([
+ { hasUpdate: false },
+ { hasUpdate: false }
+ ])
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(warnSpy).toHaveBeenCalledTimes(1)
+
+ warnSpy.mockRestore()
+ vi.unstubAllGlobals()
+ })
+
+ test('concurrent calls with different versions compare against the shared tag', async () => {
+ let settleFetch!: (response: unknown) => void
+ const fetchMock = vi.fn().mockImplementation(
+ () =>
+ new Promise(resolve => {
+ settleFetch = resolve
+ })
+ )
+ vi.stubGlobal('fetch', fetchMock)
+
+ // Both join one request; each compares the shared tag against its own
+ // version: 1.9.0 is ahead of v1.8.0 (no update), 1.7.0 is behind (update).
+ const ahead = checkForUpdate('1.9.0')
+ const behind = checkForUpdate('1.7.0')
+ settleFetch({
+ ok: true,
+ status: 200,
+ json: async () => ({ tag_name: 'v1.8.0' })
+ })
+
+ expect(await ahead).toEqual({ hasUpdate: false })
+ expect(await behind).toEqual({
+ hasUpdate: true,
+ latestVersion: 'v1.8.0',
+ releaseUrl: 'https://github.com/miurla/morphic/releases/tag/v1.8.0'
+ })
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+
+ vi.unstubAllGlobals()
+ })
+
+ test('negative cache suppresses retries after a network failure', async () => {
+ const fetchMock = vi.fn().mockRejectedValue(new TypeError('fetch failed'))
+ vi.stubGlobal('fetch', fetchMock)
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ expect(await checkForUpdate('1.7.0')).toEqual({ hasUpdate: false })
+ expect(await checkForUpdate('1.7.0')).toEqual({ hasUpdate: false })
+ expect(await checkForUpdate('1.7.0')).toEqual({ hasUpdate: false })
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(warnSpy).toHaveBeenCalledTimes(1)
+
+ warnSpy.mockRestore()
+ vi.unstubAllGlobals()
+ })
+
+ test('negative cache suppresses retries after a non-2xx response', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({ ok: false, status: 403 })
+ vi.stubGlobal('fetch', fetchMock)
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ expect(await checkForUpdate('1.7.0')).toEqual({ hasUpdate: false })
+ expect(await checkForUpdate('1.7.0')).toEqual({ hasUpdate: false })
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+
+ warnSpy.mockRestore()
+ vi.unstubAllGlobals()
+ })
+
+ test('negative cache suppresses retries after an unusable release tag', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: async () => ({ tag_name: 'nightly-2026-10-01' })
+ })
+ vi.stubGlobal('fetch', fetchMock)
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ expect(await checkForUpdate('1.7.0')).toEqual({ hasUpdate: false })
+ expect(await checkForUpdate('1.7.0')).toEqual({ hasUpdate: false })
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(warnSpy).toHaveBeenCalledTimes(1)
+
+ warnSpy.mockRestore()
+ vi.unstubAllGlobals()
+ })
+
+ test('a successful check clears the negative cache', async () => {
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('down')))
+ await checkForUpdate('1.7.0')
+ vi.unstubAllGlobals()
+
+ // Simulate the TTL window passing, then a successful check.
+ resetFailureBackoff()
+ vi.stubGlobal('fetch', mockFetchSuccess({ tag_name: 'v1.7.0' }))
+ expect(await checkForUpdate('1.7.0')).toEqual({ hasUpdate: false })
+ vi.unstubAllGlobals()
+
+ // The success cleared the backoff, so the next failure is attempted.
+ const failMock = vi.fn().mockRejectedValue(new Error('down'))
+ vi.stubGlobal('fetch', failMock)
+ await checkForUpdate('1.7.0')
+ expect(failMock).toHaveBeenCalledTimes(1)
+
+ warnSpy.mockRestore()
+ vi.unstubAllGlobals()
+ })
+})
diff --git a/lib/version/admins.ts b/lib/version/admins.ts
new file mode 100644
index 00000000..6e31b48e
--- /dev/null
+++ b/lib/version/admins.ts
@@ -0,0 +1,18 @@
+/**
+ * Parses `MORPHIC_ADMIN_EMAILS`: a comma-separated allowlist of email
+ * addresses that count as admins for the version footer's update link.
+ * Intended for auth providers without a role concept (e.g. Supabase), where
+ * no user ever carries an `admin` role. Matching is case-insensitive;
+ * entries are trimmed and empty segments are ignored.
+ */
+export function parseAdminEmails(
+ env: Record<string, string | undefined>
+): Set<string> {
+ const raw = env.MORPHIC_ADMIN_EMAILS ?? ''
+ return new Set(
+ raw
+ .split(',')
+ .map(email => email.trim().toLowerCase())
+ .filter(email => email.length > 0)
+ )
+}
diff --git a/lib/version/config.ts b/lib/version/config.ts
new file mode 100644
index 00000000..51ffafce
--- /dev/null
+++ b/lib/version/config.ts
@@ -0,0 +1,52 @@
+export interface VersionCheckConfig {
+ /** Upstream `owner/repo` whose latest release is checked. */
+ repo: string
+ /** Cache window for the upstream release check, in seconds. */
+ ttlSeconds: number
+ /** When true, no upstream requests are made at all. */
+ disabled: boolean
+}
+
+const DEFAULT_REPO = 'miurla/morphic'
+const DEFAULT_TTL_SECONDS = 86400
+const MIN_TTL_SECONDS = 300
+const REPO_PATTERN = /^[\w.-]+\/[\w.-]+$/
+
+/**
+ * Pure env parsing so the rules (default, override, floor clamp, invalid
+ * fallback, disabled flag) can be covered table-driven without touching
+ * `process.env` per case.
+ */
+export function parseVersionCheckConfig(
+ env: Record<string, string | undefined>
+): VersionCheckConfig {
+ let repo = env.MORPHIC_UPDATE_CHECK_REPO?.trim() || DEFAULT_REPO
+ if (!REPO_PATTERN.test(repo)) {
+ console.warn(
+ `[version] ignoring invalid MORPHIC_UPDATE_CHECK_REPO "${repo}" ` +
+ `(expected "owner/repo"); using ${DEFAULT_REPO}`
+ )
+ repo = DEFAULT_REPO
+ }
+
+ let ttlSeconds = DEFAULT_TTL_SECONDS
+ const rawTtl = env.MORPHIC_UPDATE_CHECK_TTL_SECONDS?.trim()
+ if (rawTtl !== undefined && rawTtl !== '') {
+ const parsed = Number(rawTtl)
+ if (Number.isFinite(parsed)) {
+ ttlSeconds = Math.max(MIN_TTL_SECONDS, Math.trunc(parsed))
+ }
+ }
+
+ const disabled = env.MORPHIC_UPDATE_CHECK_DISABLED === 'true'
+
+ return { repo, ttlSeconds, disabled }
+}
+
+let cachedConfig: VersionCheckConfig | undefined
+
+/** Reads `process.env` once and caches the result for the process lifetime. */
+export function getVersionCheckConfig(): VersionCheckConfig {
+ cachedConfig ??= parseVersionCheckConfig(process.env)
+ return cachedConfig
+}
diff --git a/lib/version/install-method.ts b/lib/version/install-method.ts
new file mode 100644
index 00000000..90b96fd7
--- /dev/null
+++ b/lib/version/install-method.ts
@@ -0,0 +1,18 @@
+/**
+ * Resolves the install-method label shown in the sidebar footer.
+ * Precedence: explicit `MORPHIC_INSTALL_METHOD` (used verbatim, so operators
+ * can set any value such as `docker` or `unraid`), then Vercel detection via
+ * the platform-provided `VERCEL` env var, then `source`.
+ */
+export function resolveInstallMethod(
+ env: Record<string, string | undefined>
+): string {
+ const explicit = env.MORPHIC_INSTALL_METHOD
+ if (explicit !== undefined && explicit.trim() !== '') {
+ return explicit
+ }
+ if (env.VERCEL) {
+ return 'vercel'
+ }
+ return 'source'
+}
diff --git a/lib/version/semver.ts b/lib/version/semver.ts
new file mode 100644
index 00000000..aed22c9d
--- /dev/null
+++ b/lib/version/semver.ts
@@ -0,0 +1,43 @@
+export interface ReleaseVersion {
+ major: number
+ minor: number
+ patch: number
+}
+
+/**
+ * Parses a release tag such as `v1.8.0` (or `1.8.0`) into its numeric parts.
+ * Returns null for anything that is not a plain `X.Y.Z` version, so prerelease
+ * tags like `v1.8.0-rc1` fall through as "no update".
+ */
+export function parseReleaseTag(tag: string): ReleaseVersion | null {
+ const normalized = tag.startsWith('v') ? tag.slice(1) : tag
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(normalized)
+ if (!match) {
+ return null
+ }
+ return {
+ major: Number(match[1]),
+ minor: Number(match[2]),
+ patch: Number(match[3])
+ }
+}
+
+/**
+ * True only when `tag` parses and is numerically greater than `current`,
+ * compared by major, then minor, then patch. Equal, lower, or unparseable
+ * inputs are treated as no update available.
+ */
+export function isUpdateAvailable(current: string, tag: string): boolean {
+ const currentVersion = parseReleaseTag(current)
+ const latestVersion = parseReleaseTag(tag)
+ if (!currentVersion || !latestVersion) {
+ return false
+ }
+ if (latestVersion.major !== currentVersion.major) {
+ return latestVersion.major > currentVersion.major
+ }
+ if (latestVersion.minor !== currentVersion.minor) {
+ return latestVersion.minor > currentVersion.minor
+ }
+ return latestVersion.patch > currentVersion.patch
+}
diff --git a/lib/version/update-check.ts b/lib/version/update-check.ts
new file mode 100644
index 00000000..692b74dd
--- /dev/null
+++ b/lib/version/update-check.ts
@@ -0,0 +1,111 @@
+import { getVersionCheckConfig } from './config'
+import { isUpdateAvailable, parseReleaseTag } from './semver'
+
+export type UpdateCheckResult =
+ | { hasUpdate: false }
+ | { hasUpdate: true; latestVersion: string; releaseUrl: string }
+
+const NO_UPDATE: UpdateCheckResult = { hasUpdate: false }
+
+const REQUEST_TIMEOUT_MS = 2000
+
+let lastFailureAt = 0
+let inFlight: Promise<string | null> | null = null
+
+/** Clears the failure backoff and the in-flight slot. Exported for tests only. */
+export function resetFailureBackoff(): void {
+ lastFailureAt = 0
+ inFlight = null
+}
+
+/**
+ * Fetches the latest release tag from the configured repo. Returns the tag on
+ * success, or null for every failure mode (throw, timeout, non-2xx, malformed
+ * JSON, missing tag) after logging a warning and arming the failure backoff.
+ */
+async function fetchLatestTag(
+ repo: string,
+ ttlSeconds: number
+): Promise<string | null> {
+ try {
+ const response = await fetch(
+ `https://api.github.com/repos/${repo}/releases/latest`,
+ {
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ next: { revalidate: ttlSeconds },
+ headers: { accept: 'application/vnd.github+json' }
+ }
+ )
+
+ if (!response.ok) {
+ lastFailureAt = Date.now()
+ console.warn(
+ `[version] update check failed with status ${response.status}`
+ )
+ return null
+ }
+
+ const release = (await response.json()) as { tag_name?: unknown }
+ const tag =
+ typeof release.tag_name === 'string' ? release.tag_name : undefined
+
+ if (!tag || !parseReleaseTag(tag)) {
+ lastFailureAt = Date.now()
+ console.warn('[version] update check returned an unusable release tag')
+ return null
+ }
+
+ lastFailureAt = 0
+ return tag
+ } catch (error) {
+ lastFailureAt = Date.now()
+ console.warn('[version] update check failed:', error)
+ return null
+ }
+}
+
+/**
+ * Checks the upstream GitHub releases feed for a newer stable release.
+ * Every failure mode (throw, timeout, non-2xx, malformed JSON, missing tag)
+ * degrades to the no-update result with a warn-level log; callers never see
+ * an exception and no user-facing error is produced.
+ *
+ * Next's fetch cache only stores successful responses, so network errors,
+ * non-2xx responses, and unusable release tags get a module-level negative
+ * cache: without it, an unreachable upstream or a repo whose latest release is
+ * not tagged `X.Y.Z` would retry (and warn) on every page render instead of
+ * once per cache window. Concurrent calls share a single in-flight upstream
+ * request; each caller compares the shared release tag against its own
+ * version, so the shared fetch never changes a caller's verdict.
+ */
+export async function checkForUpdate(
+ currentVersion: string
+): Promise<UpdateCheckResult> {
+ const { repo, ttlSeconds, disabled } = getVersionCheckConfig()
+ if (disabled) {
+ return NO_UPDATE
+ }
+
+ if (Date.now() - lastFailureAt < ttlSeconds * 1000) {
+ return NO_UPDATE
+ }
+
+ const pending =
+ inFlight ??
+ (inFlight = fetchLatestTag(repo, ttlSeconds).finally(() => {
+ inFlight = null
+ }))
+ const tag = await pending
+
+ if (!tag || !isUpdateAvailable(currentVersion, tag)) {
+ return NO_UPDATE
+ }
+
+ // The URL is constructed from the configured repo and the parsed tag
+ // rather than taken from the response body, so nothing in the payload
+ // can steer the admin-facing link.
+ const releaseUrl = `https://github.com/${repo}/releases/tag/${tag}`
+ const latestVersion = tag.startsWith('v') ? tag : `v${tag}`
+
+ return { hasUpdate: true, latestVersion, releaseUrl }
+}