diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 418a005..bf7e4f6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -95,24 +95,30 @@ jobs: ); NODE - - name: Checkout pinned Thally runtime + # Begin with protected source. Prove the manifest's exact commit is on + # that history before checking out or executing any of its files. + - name: Checkout protected Thally runtime if: needs.plan.outputs.full == 'true' uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: repository: thallylabs/thally - ref: ${{ steps.runtime.outputs.sha }} + ref: main path: runtime-source fetch-depth: 0 persist-credentials: false - name: Prove runtime revision is on protected main if: needs.plan.outputs.full == 'true' + shell: bash env: RUNTIME_SHA: ${{ steps.runtime.outputs.sha }} run: | + [[ "$RUNTIME_SHA" =~ ^[0-9a-f]{40}$ ]] git -C runtime-source fetch --no-tags origin main - test "$(git -C runtime-source rev-parse HEAD)" = "$RUNTIME_SHA" + git -C runtime-source cat-file -e "$RUNTIME_SHA^{commit}" git -C runtime-source merge-base --is-ancestor "$RUNTIME_SHA" origin/main + git -C runtime-source checkout --detach "$RUNTIME_SHA" + test "$(git -C runtime-source rev-parse HEAD)" = "$RUNTIME_SHA" - name: Verify generated runtime snapshot if: needs.plan.outputs.full == 'true' @@ -134,7 +140,9 @@ jobs: with: # Wrangler 4.111+ requires Node 22 for the exact dry-run package gate. node-version: 22 - cache: npm + # Repository scripts are untrusted, including on manual runs. Never + # persist their npm cache into a shared default-branch cache. + package-manager-cache: false - name: Install pinned content tooling run: npm ci --ignore-scripts --prefix .github/thally-tooling @@ -155,10 +163,21 @@ jobs: if: needs.plan.outputs.full == 'true' run: npm ci --ignore-scripts + # Lifecycle scripts are intentionally skipped during install. Type checking + # still needs the generated modules normally created by postinstall. + - name: Generate runtime sources + if: needs.plan.outputs.full == 'true' + run: npm run runtime-sources:build + - name: Test if: needs.plan.outputs.full == 'true' run: npm test + # Cloudflare is an explicit CI profile, not a portable site dependency. + - name: Install optional Cloudflare tooling + if: needs.plan.outputs.full == 'true' + run: npm run setup:cloudflare + - name: Build managed runtime and content assets if: needs.plan.outputs.full == 'true' run: npm run build:cloudflare diff --git a/src/app/(docs)/changelog/page.tsx b/src/app/(docs)/changelog/page.tsx index 25cba89..36fbdd2 100644 --- a/src/app/(docs)/changelog/page.tsx +++ b/src/app/(docs)/changelog/page.tsx @@ -1,5 +1,10 @@ +/** Changelog content and its complete, canonical social metadata. */ +import type { Metadata } from 'next' import { DocLayout } from '@/components/docs/doc-layout' -import { getBreadcrumbs, getSeoConfig } from '@/data/docs' +import { getBreadcrumbs, getSeoConfig, canReaderViewPage } from '@/data/docs' +import { getEffectiveI18nConfig } from '@/lib/i18n/request' +import { getContentI18nConfig } from '@/lib/i18n/content' +import { buildLocaleAlternates } from '@/lib/i18n/metadata' import { getReaderContext } from '@/lib/reader-auth/context' import { canReaderViewResolvedDoc, denyDocumentAccess } from '@/lib/reader-auth/page-gate' import { getDocFromParams } from '@/data/get-doc' @@ -9,10 +14,17 @@ import { resolveBuildSiteConfig } from '@/lib/site-config' import { getSiteUrl } from '@/lib/site-url' import { buildOgImageUrl, formatOgBreadcrumb, formatOgDisplayUrl } from '@/lib/og' -export async function generateMetadata() { +/** Project the same published locale cluster as ordinary documentation pages. */ +export async function generateMetadata(): Promise { const doc = await getDocFromParams(['changelog']) if (!doc) return {} - if (!(await canReaderViewResolvedDoc(doc, await getReaderContext()))) return {} + const reader = await getReaderContext() + if (!(await canReaderViewResolvedDoc(doc, reader))) return {} + const i18n = await getEffectiveI18nConfig() + const contentI18n = await getContentI18nConfig(['changelog'], i18n) + const allowed = await Promise.all(contentI18n.locales.map(locale => + canReaderViewPage(doc.id, reader, locale.code === i18n.defaultLocale ? undefined : locale.code))) + const availableI18n = { ...contentI18n, locales: contentI18n.locales.filter((_, index) => allowed[index]) } const siteUrl = getSiteUrl() const description = plainInlineText(doc.description) const ogImageUrl = buildOgImageUrl({ @@ -32,8 +44,17 @@ export async function generateMetadata() { return { title: fullTitle ? { absolute: fullTitle } : doc.title, description, - alternates: { canonical: `${siteUrl}${doc.href}` }, + ...(doc.noindex || doc.hidden ? { robots: { index: false, follow: false } } : {}), + alternates: { + canonical: `${siteUrl}${doc.href}`, + ...(!doc.noindex && !doc.hidden + ? { languages: buildLocaleAlternates(siteUrl, doc.href, availableI18n) } + : {}), + }, openGraph: { + type: 'article', + url: `${siteUrl}${doc.href}`, + siteName: resolveBuildSiteConfig().name, title: doc.title, description, images: [{ url: ogImageUrl, width: 1200, height: 630 }], diff --git a/src/app/api/site-config/route.ts b/src/app/api/site-config/route.ts index 06a627d..27e5ff0 100644 --- a/src/app/api/site-config/route.ts +++ b/src/app/api/site-config/route.ts @@ -1,19 +1,32 @@ +/** Public identity and optional artwork availability, never private settings. */ import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' import { getEffectiveSiteConfig } from '@/lib/admin/site-config' import { getAdminSettings } from '@/lib/admin/settings' +import { resolveBrandAsset } from '@/lib/brand-assets' export const runtime = 'nodejs' /** Public: the effective site name/description/repo (build config + admin overrides). * Lets client components (the header) reflect dashboard edits without a rebuild. */ export async function GET(request: NextRequest) { - const [identity, settings] = await Promise.all([ + const [identity, settings, lightLogo, darkLogo] = await Promise.all([ getEffectiveSiteConfig(request.nextUrl.origin), getAdminSettings(), + resolveBrandAsset('logo', 'light', request.nextUrl.origin), + resolveBrandAsset('logo', 'dark', request.nextUrl.origin), ]) - // Only this public capability flag crosses the boundary; never serialize settings. - return NextResponse.json({ ...identity, mcpEnabled: settings.mcpEnabled !== false }, { + // Project only public capabilities; never serialize the settings record. + return NextResponse.json({ + ...identity, + mcpEnabled: settings.mcpEnabled !== false, + // Presence is enough to select the existing byte route. Upload data and + // private configuration never cross this public identity projection. + logos: { + light: Boolean(lightLogo?.path || lightLogo?.dataUri), + dark: Boolean(darkLogo?.path || darkLogo?.dataUri), + }, + }, { headers: { 'cache-control': 'public, max-age=30' }, }) } diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 1091b97..f05b0ec 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -35,7 +35,7 @@ import { SiteBanner } from '@/components/layout/site-banner' import { WebMcpTools } from '@/components/agent/web-mcp-tools' import { CloudHandshake } from '@/components/cloud/cloud-handshake' import { localeDirection } from '@/lib/i18n/config' -import { getEffectiveI18nConfig } from '@/lib/i18n/request' +import { getEffectiveI18nConfig, getDocumentLocale } from '@/lib/i18n/request' import { resolveBuildSiteConfig } from '@/lib/site-config' import { validMetatags } from '@/lib/metatags' import { getBuildSiteAppearance } from '@/lib/cloud-link/appearance' @@ -277,6 +277,7 @@ export default async function RootLayout({ children }: Readonly<{ children: Reac const effectiveSite = resolveBuildSiteConfig() const siteUrl = getSiteUrl() const defaultLang = i18n.defaultLocale + const documentLang = await getDocumentLocale(i18n) const siteJsonLd = buildSiteJsonLd({ siteUrl, siteName: effectiveSite.name, @@ -290,8 +291,8 @@ export default async function RootLayout({ children }: Readonly<{ children: Reac // globals.css --font-heading default and docs.json font overrides — can // reference and override them. { }, ] - return [...docPages, ...apiPages, ...staticPages] + // Special routes can also be navigable documents. Keep their first entry, + // which contains document locale alternates and authored modification dates. + return [...docPages, ...apiPages, ...staticPages].filter((entry, index, pages) => + pages.findIndex(candidate => candidate.url === entry.url) === index) } diff --git a/src/components/layout/logo.tsx b/src/components/layout/logo.tsx index 358b445..3dede0c 100644 --- a/src/components/layout/logo.tsx +++ b/src/components/layout/logo.tsx @@ -5,7 +5,7 @@ import { useEffect, useRef, useState, useSyncExternalStore } from 'react' import { useReaderTheme } from '@/components/theme/reader-theme' import { cn } from '@/lib/utils' -import { displaySiteName, useSiteName } from './use-site-name' +import { displaySiteName, useSiteName, useSiteLogo } from './use-site-name' // Stable no-op subscribe for the hydration gate below. const emptySubscribe = () => () => {} @@ -19,7 +19,7 @@ interface LogoProps { export function Logo({ className, showText = true }: LogoProps) { const siteName = useSiteName() // Show an admin-uploaded logo when one exists; otherwise the default mark + - // site name. The probes /api/brand/logo and swaps in on load. + // site name. Only emit the image after the public identity confirms artwork. const [customOk, setCustomOk] = useState(false) const imgRef = useRef(null) @@ -31,10 +31,11 @@ export function Logo({ className, showText = true }: LogoProps) { const mounted = useSyncExternalStore(emptySubscribe, () => true, () => false) const { resolvedTheme } = useReaderTheme() const isDark = mounted && resolvedTheme === 'dark' + const hasCustomLogo = useSiteLogo(isDark ? 'dark' : 'light') const src = isDark ? '/api/brand/logo?mode=dark' : '/api/brand/logo' - // The is server-rendered, so it can finish loading BEFORE React attaches - // onLoad (the event never fires). Check completeness on mount to catch that. + // Artwork may already be cached when a live identity update adds it. Check + // completeness as well as onLoad so the fallback does not remain visible. // The default mark can be missing too (a site that pruned public/brand): // drop it rather than show a broken-image icon; the site name stays. const defaultRef = useRef(null) @@ -45,23 +46,25 @@ export function Logo({ className, showText = true }: LogoProps) { if (img?.complete) setCustomOk(img.naturalWidth > 0) const fallback = defaultRef.current if (fallback?.complete && fallback.naturalWidth === 0) setDefaultOk(false) - }, []) + }, [hasCustomLogo, src]) return (
- {/* eslint-disable-next-line @next/next/no-img-element */} - {siteName} setCustomOk(true)} - onError={() => setCustomOk(false)} - // A fixed height gives icons and wordmarks equal visual weight. The - // width cap contains unusually wide assets; object-fit avoids distortion. - style={{ height: 28, width: 'auto', maxWidth: 'min(160px, 100%)', objectFit: 'contain', objectPosition: 'left', display: customOk ? 'block' : 'none' }} - /> - {!customOk ? ( + {hasCustomLogo ? ( + /* eslint-disable-next-line @next/next/no-img-element */ + {siteName} setCustomOk(true)} + onError={() => setCustomOk(false)} + // A fixed height gives icons and wordmarks equal visual weight. The + // width cap contains unusually wide assets; object-fit avoids distortion. + style={{ height: 28, width: 'auto', maxWidth: 'min(160px, 100%)', objectFit: 'contain', objectPosition: 'left', display: customOk ? 'block' : 'none' }} + /> + ) : null} + {!hasCustomLogo || !customOk ? ( <> {/* The default Thally leaf keeps its exact olive in both modes. A site owner's uploaded logo still replaces it above. */} diff --git a/src/components/layout/use-site-name.ts b/src/components/layout/use-site-name.ts index 3245fbe..1cd1527 100644 --- a/src/components/layout/use-site-name.ts +++ b/src/components/layout/use-site-name.ts @@ -1,5 +1,7 @@ 'use client' +/** Shared public identity refresh; absent artwork never creates an image probe. */ + import { createContext, createElement, @@ -12,6 +14,13 @@ import { siteConfig } from '@/data/site' const SiteNameContext = createContext(null) +interface SiteLogos { + light: boolean + dark: boolean +} + +const SiteLogoContext = createContext({ light: false, dark: false }) + interface SiteNameProviderProps { children: ReactNode initialName: string @@ -25,15 +34,23 @@ interface SiteNameProviderProps { */ export function SiteNameProvider({ children, initialName }: SiteNameProviderProps) { const [name, setName] = useState(initialName) + const [logos, setLogos] = useState({ light: false, dark: false }) useEffect(() => { fetch('/api/site-config') .then((r) => (r.ok ? r.json() : null)) .then((c) => { if (c?.name && typeof c.name === 'string') setName(c.name) + if (c?.logos) setLogos({ light: c.logos.light === true, dark: c.logos.dark === true }) }) .catch(() => {}) }, []) - return createElement(SiteNameContext.Provider, { value: name }, children) + return createElement(SiteNameContext.Provider, { value: name }, + createElement(SiteLogoContext.Provider, { value: logos }, children)) +} + +/** Whether the current public identity has actual artwork for the requested mode. */ +export function useSiteLogo(mode: 'light' | 'dark'): boolean { + return useContext(SiteLogoContext)[mode] } /** The effective site name — request snapshot, refreshed live by the dashboard. */ diff --git a/src/lib/i18n/document-locale.ts b/src/lib/i18n/document-locale.ts new file mode 100644 index 0000000..8c11ed5 --- /dev/null +++ b/src/lib/i18n/document-locale.ts @@ -0,0 +1,11 @@ +/** Middleware-owned path context for server-rendered managed document language. */ + +import type { I18nConfig } from './config' + +export const DOCUMENT_PATH_HEADER = 'x-thally-document-path' + +/** Resolve only enabled, exact route prefixes; arbitrary headers cannot invent a locale. */ +export function documentLocaleFromPath(pathname: string | null, i18n: I18nConfig): string { + const prefix = pathname?.startsWith('/') ? pathname.split('/')[1] : null + return i18n.locales.find(locale => locale.code === prefix)?.code ?? i18n.defaultLocale +} diff --git a/src/lib/i18n/request.ts b/src/lib/i18n/request.ts index 6b89a95..2693367 100644 --- a/src/lib/i18n/request.ts +++ b/src/lib/i18n/request.ts @@ -7,6 +7,9 @@ import 'server-only' import { cache } from 'react' +import { headers } from 'next/headers' +import { isRemoteContentSource } from '@/lib/content-source' +import { DOCUMENT_PATH_HEADER, documentLocaleFromPath } from './document-locale' import { getI18nConfig } from '@/data/docs' import { getAdminSettings } from '@/lib/admin/settings' import { getRequestCloudSiteConfig } from '@/lib/cloud-link/request' @@ -59,3 +62,9 @@ export const getEffectiveI18nConfig = cache(async (): Promise => { const admin = await getAdminSettings() return resolveI18nSelection(admin.localization, repository) }) + +/** Read request context only for managed content, preserving unlinked static builds. */ +export async function getDocumentLocale(i18n: I18nConfig): Promise { + if (!isRemoteContentSource()) return i18n.defaultLocale + return documentLocaleFromPath((await headers()).get(DOCUMENT_PATH_HEADER), i18n) +} diff --git a/src/middleware.ts b/src/middleware.ts index 22ab533..3bdc8b7 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -23,6 +23,7 @@ import { getCloudAccessConfigEdge, getManagedSiteIdEdge } from '@/lib/cloud-link import { isMarkdownPagesEnabled } from '@/lib/markdown-pages' import { createDailyVisitorKey, externalReferrerDomain } from '@/lib/analytics/identity' import { problemResponse } from '@/lib/http/problem' +import { DOCUMENT_PATH_HEADER } from '@/lib/i18n/document-locale' import { isReaderAuthActive } from '@/lib/reader-auth/config' // Static API paths are known without importing the Node-only content graph. @@ -501,7 +502,12 @@ export async function middleware(request: NextRequest, event: NextFetchEvent) { // custom header agents read directly, so it carries an absolute URL. Only // potential content pages get the headers, including API-reference pages; // known service APIs, admin routes, and Next internals do not. - const response = NextResponse.next() + // Root layouts cannot receive a nested catch-all locale. Replace any caller + // supplied context with the real path so managed HTML can declare its language + // before JavaScript runs, without rewriting docs or negotiating RSC payloads. + const requestHeaders = new Headers(request.headers) + requestHeaders.set(DOCUMENT_PATH_HEADER, pathname) + const response = NextResponse.next({ request: { headers: requestHeaders } }) if (isPotentialDocsPagePath(pathname)) { response.headers.append('Link', '; rel="llms-txt"') // Standard relation types agents actually dereference (RFC 8288): the diff --git a/starter-release.json b/starter-release.json index 700ced0..057f716 100644 --- a/starter-release.json +++ b/starter-release.json @@ -5,8 +5,8 @@ "defaultBranch": "main", "runtime": { "repository": "thallylabs/thally", - "commitSha": "d8345dda03189ba1d75810b5310117c5cd9c3f6d", - "treeSha": "0a0831d9802d3614e4f4d11704e637ed04284ca3" + "commitSha": "79ab77f08b832fc8ee37c6103c64a9c52d48de39", + "treeSha": "b0c574508bace2fad15b8f327aedfb2e1a169520" }, "packages": { "@thallylabs/core": "^0.2.18"