π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(auth): split the auth surface into a prerendered micro app (#18542)
Innei12fa88e49a99
diff --git a/.agents/skills/split-micro-app/SKILL.md b/.agents/skills/split-micro-app/SKILL.mdindex 7dd991b4671..dc057386e05 100644--- a/.agents/skills/split-micro-app/SKILL.md+++ b/.agents/skills/split-micro-app/SKILL.md@@ -12,6 +12,9 @@ the decisions and landmines, not copies of the code:- **`apps/workbench`** (`/verify`, `/acceptance`) β all code in this repo, builds and deploys from OSS CI.- **`apps/share`** (`/share/t/:id`, `/share/page/:id`) β renders Cloud-only surfaces, so itbuilds and deploys from **lobehub-cloud** CI. See Β§1b before touching it.+- **`apps/auth`** (`/signin`, `/signup`, β¦) β the SSG variant: `ssr: false` + `prerender`, so+ the worker carries no React at all (7KB). 18 locales x 4 routes of prerendered documents.+ Also renders Cloud-only surfaces (Β§1b). See Β§3b.## Hosting@@ -124,6 +127,11 @@ own last successful run's `share-build-inputs` (first run always builds).through tsconfig `paths` (`@/business/*` β `./src/business/*` then `./lobehub/src/business/*`;`@/*` β `./src/*` then `./lobehub/src/*`). Split by **ownership**, not by which repo is handy:+`apps/auth` is the cheap case: because `ssr: false` ships no render graph, the Cloud overlay+(BusinessAuthProvider β Turnstile + referral) added **one chunk and 0 extra SSR stubs** β+measured at 585.7KB gz eager vs 587.3KB for the open-source build, with byte-identical markup.+Do not assume that; `apps/share` needed 8.2MB of stubbing. Measure per app.+| Code | Where it goes || ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- || Routes, shell, SSR pipeline, worker, CDN deploy, SSR stubs of OSS modules | OSS `apps/<name>` β Docker serves the same app |@@ -233,6 +241,86 @@ gateway routes API to `app` instead), and redirect `/` + unknown paths to `WORKB- **Prefilling a virtualized list**: `virtua` caches measured sizes by index, so a _truncated_prefill that later grows misaligns every row. Prefill the whole list or none of it.+## 3b. Prerendering instead of SSR (`ssr: false`)++When every page is config-free at render time, `ssr: false` + `prerender` drops the whole SSR+bundle-weight battle: no stubs, no client gates, and the worker is a static picker.+`apps/auth`'s is \~7KB β it resolves the locale, fetches one document out of the assets binding,+and swaps a `window.__SERVER_CONFIG__` placeholder for the deployment's config.++- **Runtime config cannot be baked.** The build has no deployment's env, so the document is+ prerendered config-free and the worker injects it. Anything that reads it must be hydration-+ gated (`useIsHydrated`), or the first client render diverges from the document.+- **Audit what actually needs to travel that way β most of it does not.** The hydration gate+ applies to the _whole_ injected object, so every value routed through it is a value missing+ from the prerendered HTML. In `apps/auth` the config carried 11 fields; the pages read 6, and+ the most visible one was in the wrong layer entirely: `enableBusinessFeatures` is a+ **build-time constant** (`@lobechat/business-const`, `false` open-source / `true` in Cloud via+ a pnpm override) that was being round-tripped through the server, and with it the SSO provider+ list β itself a hardcoded array in the Cloud overlay. Reading the constant directly instead+ put Google/GitHub/Apple into the static document. `featureFlags`, `enableMarketTrustedClient`,+ `telemetry` and `aiProvider` had zero consumers and were dropped from the endpoint, which is+ public and unauthenticated. Do this audit before accepting "config-dependent UI pops in after+ hydration" as the cost of prerendering.+- **Prerendering turns every `localStorage` read during render into a hydration bug.** A+ returning user's stored state (`useState(readStored)`) makes the first client render disagree+ with a document that was built without it β `apps/auth` hit this twice, on the terms checkbox+ and on the "last used" provider badge, both of which also reorder the buttons. Move them to+ `useState(empty)` + `useEffect`. A fresh browser will not reproduce it; seed the keys and+ reload.+- **The config needs an endpoint.** A worker has no access to the app's env; `apps/auth` reads+ `GET /webapi/auth/spa-config` (public, `s-maxage`) through the API base and tolerates failure+ by leaving the placeholder in place.+- **Landmine β one document per locale must live at the canonical path.** Prerendering+ `/:locale/signin` and serving it at `/signin` looks like it works and silently breaks+ hydration: React Router matches the plain route, finds no context for the prefixed route id,+ and React re-renders the whole document β leaving **two copies of the page in the DOM**, with+ no console warning. Only the second one is visible, so a screenshot looks fine; count+ `document.querySelectorAll('form')` to catch it. The fix is one build pass per locale+ (`AUTH_PRERENDER_LOCALE` β `environments.ssr.define`), each prerendering the same canonical+ paths, with the non-default passes' documents folded into `build/client/__i18n/<locale>/`.+ Keep the locale out of the **client** define so every pass emits byte-identical assets β+ `scripts/build.mjs` asserts that by resolving each copied document's asset refs against the+ default build.+- **The matrix costs build time, not bytes β and it parallelizes.** `apps/auth` runs all 18+ locales for 73 documents and 17.8MB in `build/client`, with **no change to first load**+ (640.8KB gz over the same 34 eager files: the per-locale dictionary chunks are lazy and each+ document carries only its own). The non-default passes share nothing and write to their own+ `build-<locale>`, so they fan out: **3m05s sequential β 44s at 6 concurrent** on 16 cores.+ Each pass costs about two cores; past \~6 it stops paying (9 concurrent measured 42s, with+ per-pass time rising 12s β 16s). `AUTH_BUILD_CONCURRENCY` overrides the+ `min(6, availableParallelism() - 2)` default, which lands on 2 for a 4-vCPU CI runner β+ budget \~2min there, and mind that `NODE_OPTIONS=--max-old-space-size` applies per child.+ If that is still too slow, the remaining move is one build plus N renders against+ `build/server/index.js` with the locale threaded through `entry.server.tsx` β that trades the+ build-time define for request state, so it needs `AsyncLocalStorage` or strict sequencing.+ Verify RTL locales (`ar`, `fa-IR`) in a browser β they exercise the antd direction path that+ no LTR document touches.+- **The prerender list is loaded by plain Node** (`react-router.config.ts`), so it cannot import+ anything alias-resolved and has to be a literal array. Guard it against the dictionaries on+ disk in the build script, or a newly translated locale silently prerenders as English.+- **i18n must be synchronous for the served locale.** A resources-to-backend fetch renders+ English first and swaps a tick later, which is a hydration mismatch against a prerendered+ zh-CN document. Bundling every locale into the client instead costs a lot (auth: 63KB gz of+ dictionaries, eagerly modulepreloaded on every route), so `apps/auth` inlines **only the+ served locale** into the document as `<script type="application/json">` and keeps the others+ behind an on-demand backend for the language switcher. Weigh it: that moved 44KB gz off the+ JS path but put 22KB gz onto the document, which is the one thing first paint waits for, and+ the dictionary is now re-sent per document instead of cached once. A per-locale hashed JS+ file loaded by a blocking script would beat both; nobody has built it yet.+- **The client build must stay locale-agnostic** for the one-pass-per-locale scheme to share+ assets, so anything that reads the dictionaries needs a server/client twin: the prerender+ module holds every bundle, the `.client` twin reads the document's inlined JSON, and+ `vite.config.shared.mts` swaps them per environment. `meta()` runs on both sides β it goes+ through the same twin, not a second copy of the strings.+- **`resolve.noExternal: true` on the ssr env, build only.** The prerender pass runs the built+ server bundle through plain Node, which rejects the extensionless directory imports some+ published `es/` bundles ship (`@lobehub/fluent-emoji`). Setting it for `serve` too breaks the+ dev module runner on inlined CJS (`module is not defined`, then `require is not defined`) β+ and leaving it off leaves `react-router dev` 500ing on that same directory import. **Known+ gap:** `apps/auth`'s dev server does not run; the working local loop is+ `bun run build && wrangler dev`.+RR v8 gotchas (docs/templates still say v7):| v8 change | Symptom |diff --git a/apps/auth/.gitignore b/apps/auth/.gitignorenew file mode 100644index 00000000000..efe22b2b813--- /dev/null+++ b/apps/auth/.gitignore@@ -0,0 +1,6 @@+.react-router/+!app/lib/+.wrangler/+build/+build-*/+build-inputs.txtdiff --git a/apps/auth/app/entry.client.tsx b/apps/auth/app/entry.client.tsxnew file mode 100644index 00000000000..1665c387ec2--- /dev/null+++ b/apps/auth/app/entry.client.tsx@@ -0,0 +1,28 @@+import { startTransition, StrictMode } from 'react';+import { hydrateRoot } from 'react-dom/client';+import { HydratedRouter } from 'react-router/dom';++// In production the worker inlines this before the document is served. The dev+// server has no such stage, so fetch it through vite's API proxy instead β+// after hydration, which is when `AuthAppShell` first reads it either way.+const loadDevServerConfig = async () => {+ if (!import.meta.env.DEV) return;++ try {+ const response = await fetch('/webapi/auth/spa-config');+ if (response.ok) window.__SERVER_CONFIG__ = await response.json();+ } catch {+ // Rendering config-less is the same state a failed lookup gives in production.+ }+};++void loadDevServerConfig();++startTransition(() => {+ hydrateRoot(+ document,+ <StrictMode>+ <HydratedRouter />+ </StrictMode>,+ );+});diff --git a/apps/auth/app/entry.server.tsx b/apps/auth/app/entry.server.tsxnew file mode 100644index 00000000000..26094123866--- /dev/null+++ b/apps/auth/app/entry.server.tsx@@ -0,0 +1,45 @@+import { createCache } from '@ant-design/cssinjs';+import { buildInlineAntdStyle } from '@lobehub/ui/static-css/runtime';+import { extractStaticStyle, StyleProvider } from 'antd-style';+import { renderToReadableStream } from 'react-dom/server';+import type { EntryContext } from 'react-router';+import { ServerRouter } from 'react-router';+import { styleKeys } from 'virtual:lobehub/antd-static-css';++export default async function handleRequest(+ request: Request,+ responseStatusCode: number,+ responseHeaders: Headers,+ routerContext: EntryContext,+) {+ let status = responseStatusCode;+ const antdCache = createCache();++ const stream = await renderToReadableStream(+ <StyleProvider cache={antdCache} speedy={false}>+ <ServerRouter context={routerContext} url={request.url} />+ </StyleProvider>,+ {+ onError(error) {+ status = 500;+ console.error(error);+ },+ },+ );++ // Style extraction reads the finished markup, so the render must not stream.+ await stream.allReady;+ const html = await new Response(stream).text();++ const inlineAntd = buildInlineAntdStyle(antdCache, { styleKeys });+ const emotionTags = extractStaticStyle(html, { includeAntd: false })+ .map((item) => item.tag)+ .join('');++ responseHeaders.set('Content-Type', 'text/html; charset=utf-8');++ return new Response(html.replace('</head>', `${inlineAntd.html}${emotionTags}</head>`), {+ headers: responseHeaders,+ status,+ });+}diff --git a/apps/auth/app/env.d.ts b/apps/auth/app/env.d.tsnew file mode 100644index 00000000000..ff90c34b425--- /dev/null+++ b/apps/auth/app/env.d.ts@@ -0,0 +1 @@+declare const __AUTH_PRERENDER_LOCALE__: string;diff --git a/apps/auth/app/lib/locale.ts b/apps/auth/app/lib/locale.tsnew file mode 100644index 00000000000..0548cdc57a2--- /dev/null+++ b/apps/auth/app/lib/locale.ts@@ -0,0 +1,9 @@+import { DEFAULT_PRERENDER_LOCALE } from './prerender';++export const resolveAuthLocale = (): string => {+ if (typeof document !== 'undefined') {+ return document.documentElement.lang || DEFAULT_PRERENDER_LOCALE;+ }++ return __AUTH_PRERENDER_LOCALE__;+};diff --git a/apps/auth/app/lib/prerender.test.ts b/apps/auth/app/lib/prerender.test.tsnew file mode 100644index 00000000000..2b814c1943d--- /dev/null+++ b/apps/auth/app/lib/prerender.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from 'vitest';++import {+ DEFAULT_PRERENDER_LOCALE,+ documentPathFor,+ PRERENDER_LOCALES,+ PRERENDER_ROUTES,+ resolveDocumentLocale,+ SPA_FALLBACK_DOCUMENT,+} from './prerender';++describe('documentPathFor', () => {+ it('serves the default-locale document at the canonical path', () => {+ expect(documentPathFor('/signin', DEFAULT_PRERENDER_LOCALE)).toBe('/signin/index.html');+ });++ it('serves other locales from the folded i18n tree', () => {+ expect(documentPathFor('/signup', 'zh-CN')).toBe('/__i18n/zh-CN/signup/index.html');+ });++ it('falls back to the SPA shell for param routes', () => {+ expect(documentPathFor('/oauth/consent/abc', 'ja-JP')).toBe(SPA_FALLBACK_DOCUMENT);+ });+});++describe('resolveDocumentLocale', () => {+ it('keeps a prerendered locale', () => {+ expect(resolveDocumentLocale('ja-JP')).toBe('ja-JP');+ });++ it('falls back to the default locale when the request is unknown', () => {+ expect(resolveDocumentLocale('klingon')).toBe(DEFAULT_PRERENDER_LOCALE);+ });+});++describe('prerender matrix', () => {+ it('prerenders the four static auth routes', () => {+ expect([...PRERENDER_ROUTES]).toEqual([+ '/signin',+ '/signup',+ '/verify-email',+ '/reset-password',+ ]);+ });++ it('covers every locale that ships auth dictionaries', () => {+ expect(PRERENDER_LOCALES).toHaveLength(18);+ expect(PRERENDER_LOCALES).toContain(DEFAULT_PRERENDER_LOCALE);+ });+});diff --git a/apps/auth/app/lib/prerender.ts b/apps/auth/app/lib/prerender.tsnew file mode 100644index 00000000000..c326cbae90d--- /dev/null+++ b/apps/auth/app/lib/prerender.ts@@ -0,0 +1,51 @@+export const DEFAULT_PRERENDER_LOCALE = 'en-US';++export const SPA_FALLBACK_DOCUMENT = '/index.html';++export const PRERENDER_ROUTES = [+ '/signin',+ '/signup',+ '/verify-email',+ '/reset-password',+] as const;++// Hand-written: `react-router.config.ts` is loaded by plain Node and cannot+// resolve the repo's path aliases, so this list cannot be imported from+// `@/locales/resources`. `scripts/build.mjs` checks it against locales on disk.+export const PRERENDER_LOCALES = [+ 'ar',+ 'bg-BG',+ 'de-DE',+ 'en-US',+ 'es-ES',+ 'fa-IR',+ 'fr-FR',+ 'it-IT',+ 'ja-JP',+ 'ko-KR',+ 'nl-NL',+ 'pl-PL',+ 'pt-BR',+ 'ru-RU',+ 'tr-TR',+ 'vi-VN',+ 'zh-CN',+ 'zh-TW',+] as const;++export const prerenderOutputDir = (route: string) => route.replace(/^\//, '');++export const resolveDocumentLocale = (locale: string) =>+ (PRERENDER_LOCALES as readonly string[]).includes(locale) ? locale : DEFAULT_PRERENDER_LOCALE;++export const documentPathFor = (pathname: string, locale: string) => {+ const route = pathname.length > 1 && pathname.endsWith('/') ? pathname.slice(0, -1) : pathname;+ const prerendered = (PRERENDER_ROUTES as readonly string[]).includes(route);++ if (!prerendered) return SPA_FALLBACK_DOCUMENT;++ const document = `${route}/index.html`;+ if (locale === DEFAULT_PRERENDER_LOCALE) return document;++ return `/__i18n/${locale}${document}`;+};diff --git a/apps/auth/app/lib/seo.ts b/apps/auth/app/lib/seo.tsnew file mode 100644index 00000000000..e4fe7adf940--- /dev/null+++ b/apps/auth/app/lib/seo.ts@@ -0,0 +1,79 @@+import { APPLE_APP_STORE_ID, BRANDING_NAME, ORG_NAME } from '@lobechat/business-const';+import type { MetaDescriptor } from 'react-router';+import urlJoin from 'url-join';++import { OFFICIAL_SITE } from '@/const/url';+import { isCustomORG } from '@/const/version';++import { readAuthResources } from '../shell/authResources';++const OG_IMAGE_URL = 'https://lobehub.com/assets/cao-og.webp';+const TWITTER_SITE = '@lobehub';+const INDEXABLE_PATHS = new Set(['/signin', '/signup']);++const interpolate = (text: string) => text.replaceAll('{{appName}}', BRANDING_NAME);++const lookup = (resources: Record<string, string>, key: string, fallback: string) =>+ interpolate(resources[key] || fallback);++export const buildAuthMeta = (locale: string, pathname: string): MetaDescriptor[] => {+ const normalized =+ pathname.length > 1 && pathname.endsWith('/') ? pathname.slice(0, -1) : pathname;+ const auth = readAuthResources(locale).auth;+ const indexable = INDEXABLE_PATHS.has(normalized);+ const descriptionFallback = lookup(auth, 'signin.subtitle', '');++ let title = BRANDING_NAME;+ let description = descriptionFallback;+ let canonical: string | undefined;++ switch (normalized) {+ case '/signin': {+ title = lookup(auth, 'betterAuth.signin.emailStep.title', 'Sign In');+ description = lookup(auth, 'signin.subtitle', descriptionFallback);+ canonical = urlJoin(OFFICIAL_SITE, '/signin');+ break;+ }+ case '/signup': {+ title = lookup(auth, 'betterAuth.signup.title', 'Create Account');+ description = lookup(auth, 'betterAuth.signup.subtitle', descriptionFallback);+ canonical = urlJoin(OFFICIAL_SITE, '/signup');+ break;+ }+ default: {+ break;+ }+ }++ const ogLocale = locale.replace('-', '_');+ const meta: MetaDescriptor[] = [+ { title },+ { content: description, name: 'description' },+ { content: indexable ? 'index, follow' : 'noindex, nofollow', name: 'robots' },+ { content: title, property: 'og:title' },+ { content: description, property: 'og:description' },+ { content: 'website', property: 'og:type' },+ { content: BRANDING_NAME, property: 'og:site_name' },+ { content: ogLocale, property: 'og:locale' },+ { content: OG_IMAGE_URL, property: 'og:image' },+ { content: title, property: 'og:image:alt' },+ { content: 'summary_large_image', name: 'twitter:card' },+ { content: isCustomORG ? `@${ORG_NAME}` : TWITTER_SITE, name: 'twitter:site' },+ { content: title, name: 'twitter:title' },+ { content: description, name: 'twitter:description' },+ { content: OG_IMAGE_URL, name: 'twitter:image' },+ ];++ if (canonical) {+ meta.push(+ { href: canonical, rel: 'canonical', tagName: 'link' },+ { content: canonical, property: 'og:url' },+ );+ }++ if (APPLE_APP_STORE_ID) {+ meta.push({ content: `app-id=${APPLE_APP_STORE_ID}`, name: 'apple-itunes-app' });+ }++ return meta;+};diff --git a/apps/auth/app/lib/serverConfig.ts b/apps/auth/app/lib/serverConfig.tsnew file mode 100644index 00000000000..25314e03115--- /dev/null+++ b/apps/auth/app/lib/serverConfig.ts@@ -0,0 +1 @@+export const SERVER_CONFIG_PLACEHOLDER = 'window.__SERVER_CONFIG__ = undefined; /* SERVER_CONFIG */';diff --git a/apps/auth/app/root.tsx b/apps/auth/app/root.tsxnew file mode 100644index 00000000000..0b8576673b9--- /dev/null+++ b/apps/auth/app/root.tsx@@ -0,0 +1,115 @@+import type { CSSProperties, PropsWithChildren } from 'react';+import { Links, Meta, Outlet, Scripts, ScrollRestoration, useRouteError } from 'react-router';+import { isRtlLang } from 'rtl-detect';+import { href as antdStaticCssHref } from 'virtual:lobehub/antd-static-css';+import { href as themeVarsCssHref } from 'virtual:lobehub/theme-vars-css';++import NextThemeProvider from '@/layout/GlobalProvider/NextThemeProvider';+import { isChunkLoadError, notifyChunkError } from '@/utils/chunkError';++import { resolveAuthLocale } from './lib/locale';+import { buildAuthMeta } from './lib/seo';+import { SERVER_CONFIG_PLACEHOLDER } from './lib/serverConfig';+import AuthAppShell from './shell/AuthAppShell';+import { serializeAuthResources } from './shell/authResources';+import { AUTH_I18N_SCRIPT_ID } from './shell/i18nScript';++const bodyBackground = `+html body { background: #f8f8f8; }+html[data-theme='dark'] body { background-color: #000; }+`;++// Only reaches the document on the SPA fallback shell, which matches no route:+// every page route replaces the whole set with its own.+export const meta = () => buildAuthMeta(resolveAuthLocale(), '/');++export const Layout = ({ children }: PropsWithChildren) => {+ const locale = resolveAuthLocale();++ return (+ <html suppressHydrationWarning dir={isRtlLang(locale) ? 'rtl' : 'ltr'} lang={locale}>+ <head>+ <meta charSet="utf-8" />+ <meta content="width=device-width, initial-scale=1" name="viewport" />+ <link href="/favicon.ico" rel="icon" />+ <Meta />+ <Links />+ <style dangerouslySetInnerHTML={{ __html: bodyBackground }} />+ <link href={themeVarsCssHref} rel="stylesheet" />+ <link href={antdStaticCssHref} rel="stylesheet" />+ <script dangerouslySetInnerHTML={{ __html: SERVER_CONFIG_PLACEHOLDER }} />+ <script+ dangerouslySetInnerHTML={{ __html: serializeAuthResources(locale) }}+ id={AUTH_I18N_SCRIPT_ID}+ type={'application/json'}+ />+ </head>+ <body>+ {children}+ <ScrollRestoration />+ <Scripts />+ </body>+ </html>+ );+};++export default function Root() {+ const locale = resolveAuthLocale();++ return (+ <NextThemeProvider>+ <AuthAppShell locale={locale}>+ <Outlet />+ </AuthAppShell>+ </NextThemeProvider>+ );+}++const buttonStyle: CSSProperties = {+ background: 'transparent',+ border: '1px solid currentcolor',+ borderRadius: 6,+ color: 'inherit',+ cursor: 'pointer',+ font: 'inherit',+ padding: '6px 16px',+};++// Replaces Root, so it renders without the i18n provider: plain markup and+// English copy only, matching the auth SPA's own boundary.+export const ErrorBoundary = () => {+ const error = useRouteError();++ if (typeof window !== 'undefined' && isChunkLoadError(error)) notifyChunkError();++ return (+ <div+ style={{+ alignItems: 'center',+ display: 'flex',+ flexDirection: 'column',+ fontFamily: 'sans-serif',+ gap: 16,+ justifyContent: 'center',+ minHeight: '100dvh',+ padding: 16,+ }}+ >+ <h2 style={{ margin: 0 }}>Something went wrong</h2>+ <div style={{ display: 'flex', gap: 12 }}>+ <button style={buttonStyle} type={'button'} onClick={() => window.location.reload()}>+ Retry+ </button>+ <button+ style={buttonStyle}+ type={'button'}+ onClick={() => {+ window.location.href = '/signin';+ }}+ >+ Back to sign in+ </button>+ </div>+ </div>+ );+};diff --git a/apps/auth/app/routes.ts b/apps/auth/app/routes.tsnew file mode 100644index 00000000000..22ab9f77ba9--- /dev/null+++ b/apps/auth/app/routes.ts@@ -0,0 +1,19 @@+import { index, route, type RouteConfig } from '@react-router/dev/routes';++export default [+ index('routes/homeRedirect.tsx'),+ route('signin', 'routes/signin.tsx'),+ route('signup', 'routes/signup.tsx'),+ route('verify-email', 'routes/verifyEmail.tsx'),+ route('reset-password', 'routes/resetPassword.tsx'),+ route('auth-error', 'routes/authError.tsx'),+ route('market-auth-callback', 'routes/marketAuthCallback.tsx'),+ route('oauth/consent/:uid', 'routes/oauthConsent.tsx'),+ route('oauth/device', 'routes/oauthDevice.tsx'),+ route('oauth/device/confirm', 'routes/oauthDeviceConfirm.tsx'),+ route('oauth/device/success', 'routes/oauthDeviceSuccess.tsx'),+ route('oauth/callback/success', 'routes/oauthCallbackSuccess.tsx'),+ route('oauth/callback/social', 'routes/oauthCallbackSocial.tsx'),+ route('oauth/callback/error', 'routes/oauthCallbackError.tsx'),+ route('*', 'routes/catchall.tsx'),+] satisfies RouteConfig;diff --git a/apps/auth/app/routes/authError.tsx b/apps/auth/app/routes/authError.tsxnew file mode 100644index 00000000000..c149a6f8f95--- /dev/null+++ b/apps/auth/app/routes/authError.tsx@@ -0,0 +1,6 @@+import { resolveAuthLocale } from '../lib/locale';+import { buildAuthMeta } from '../lib/seo';++export const meta = () => buildAuthMeta(resolveAuthLocale(), '/auth-error');++export { default } from '@/features/Auth/AuthError';diff --git a/apps/auth/app/routes/catchall.tsx b/apps/auth/app/routes/catchall.tsxnew file mode 100644index 00000000000..2db056f2c6b--- /dev/null+++ b/apps/auth/app/routes/catchall.tsx@@ -0,0 +1,13 @@+import { useEffect } from 'react';++import Loading from '@/components/Loading/BrandTextLoading';++// The worker answers `/` and unmatched paths before React Router sees them; this+// only runs for a client-side navigation that fell through the route table.+export default function AuthCatchAll() {+ useEffect(() => {+ window.location.replace('/signin');+ }, []);++ return <Loading debugId={'AuthCatchAll'} />;+}diff --git a/apps/auth/app/routes/homeRedirect.tsx b/apps/auth/app/routes/homeRedirect.tsxnew file mode 100644index 00000000000..1ffdb3cdf3b--- /dev/null+++ b/apps/auth/app/routes/homeRedirect.tsx@@ -0,0 +1 @@+export { default } from './catchall';diff --git a/apps/auth/app/routes/marketAuthCallback.tsx b/apps/auth/app/routes/marketAuthCallback.tsxnew file mode 100644index 00000000000..a236b57ba70--- /dev/null+++ b/apps/auth/app/routes/marketAuthCallback.tsx@@ -0,0 +1,6 @@+import { resolveAuthLocale } from '../lib/locale';+import { buildAuthMeta } from '../lib/seo';++export const meta = () => buildAuthMeta(resolveAuthLocale(), '/market-auth-callback');++export { default } from '@/features/Auth/MarketAuthCallback';diff --git a/apps/auth/app/routes/oauthCallbackError.tsx b/apps/auth/app/routes/oauthCallbackError.tsxnew file mode 100644index 00000000000..5d043c84126--- /dev/null+++ b/apps/auth/app/routes/oauthCallbackError.tsx@@ -0,0 +1,6 @@+import { resolveAuthLocale } from '../lib/locale';+import { buildAuthMeta } from '../lib/seo';++export const meta = () => buildAuthMeta(resolveAuthLocale(), '/oauth/callback/error');++export { default } from '@/features/Auth/OAuthCallback/Error';diff --git a/apps/auth/app/routes/oauthCallbackSocial.tsx b/apps/auth/app/routes/oauthCallbackSocial.tsxnew file mode 100644index 00000000000..42f426ba0ca--- /dev/null+++ b/apps/auth/app/routes/oauthCallbackSocial.tsx@@ -0,0 +1,6 @@+import { resolveAuthLocale } from '../lib/locale';+import { buildAuthMeta } from '../lib/seo';++export const meta = () => buildAuthMeta(resolveAuthLocale(), '/oauth/callback/social');++export { default } from '@/features/Auth/OAuthCallback/Social';diff --git a/apps/auth/app/routes/oauthCallbackSuccess.tsx b/apps/auth/app/routes/oauthCallbackSuccess.tsxnew file mode 100644index 00000000000..a6dc539a2d3--- /dev/null+++ b/apps/auth/app/routes/oauthCallbackSuccess.tsx@@ -0,0 +1,6 @@+import { resolveAuthLocale } from '../lib/locale';+import { buildAuthMeta } from '../lib/seo';++export const meta = () => buildAuthMeta(resolveAuthLocale(), '/oauth/callback/success');++export { default } from '@/features/Auth/OAuthCallback/Success';diff --git a/apps/auth/app/routes/oauthConsent.tsx b/apps/auth/app/routes/oauthConsent.tsxnew file mode 100644index 00000000000..47ba10ea496--- /dev/null+++ b/apps/auth/app/routes/oauthConsent.tsx@@ -0,0 +1,6 @@+import { resolveAuthLocale } from '../lib/locale';+import { buildAuthMeta } from '../lib/seo';++export const meta = () => buildAuthMeta(resolveAuthLocale(), '/oauth/consent');++export { default } from '@/features/Auth/OAuthConsent';diff --git a/apps/auth/app/routes/oauthDevice.tsx b/apps/auth/app/routes/oauthDevice.tsxnew file mode 100644index 00000000000..28036962826--- /dev/null+++ b/apps/auth/app/routes/oauthDevice.tsx@@ -0,0 +1,6 @@+import { resolveAuthLocale } from '../lib/locale';+import { buildAuthMeta } from '../lib/seo';++export const meta = () => buildAuthMeta(resolveAuthLocale(), '/oauth/device');++export { default } from '@/features/Auth/OAuthDevice/DeviceInputPage';diff --git a/apps/auth/app/routes/oauthDeviceConfirm.tsx b/apps/auth/app/routes/oauthDeviceConfirm.tsxnew file mode 100644index 00000000000..3bad0510a68--- /dev/null+++ b/apps/auth/app/routes/oauthDeviceConfirm.tsx@@ -0,0 +1,6 @@+import { resolveAuthLocale } from '../lib/locale';+import { buildAuthMeta } from '../lib/seo';++export const meta = () => buildAuthMeta(resolveAuthLocale(), '/oauth/device/confirm');++export { default } from '@/features/Auth/OAuthDevice/DeviceConfirmPage';diff --git a/apps/auth/app/routes/oauthDeviceSuccess.tsx b/apps/auth/app/routes/oauthDeviceSuccess.tsxnew file mode 100644index 00000000000..03da6777f41--- /dev/null+++ b/apps/auth/app/routes/oauthDeviceSuccess.tsx@@ -0,0 +1,6 @@+import { resolveAuthLocale } from '../lib/locale';+import { buildAuthMeta } from '../lib/seo';++export const meta = () => buildAuthMeta(resolveAuthLocale(), '/oauth/device/success');++export { default } from '@/features/Auth/OAuthDevice/DeviceSuccessPage';diff --git a/apps/auth/app/routes/resetPassword.tsx b/apps/auth/app/routes/resetPassword.tsxnew file mode 100644index 00000000000..a64a7711dd3--- /dev/null+++ b/apps/auth/app/routes/resetPassword.tsx@@ -0,0 +1,6 @@+import { resolveAuthLocale } from '../lib/locale';+import { buildAuthMeta } from '../lib/seo';++export const meta = () => buildAuthMeta(resolveAuthLocale(), '/reset-password');++export { default } from '@/features/Auth/ResetPassword';diff --git a/apps/auth/app/routes/signin.tsx b/apps/auth/app/routes/signin.tsxnew file mode 100644index 00000000000..371962b7b8d--- /dev/null+++ b/apps/auth/app/routes/signin.tsx@@ -0,0 +1,6 @@+import { resolveAuthLocale } from '../lib/locale';+import { buildAuthMeta } from '../lib/seo';++export const meta = () => buildAuthMeta(resolveAuthLocale(), '/signin');++export { default } from '@/features/Auth/SignIn';diff --git a/apps/auth/app/routes/signup.tsx b/apps/auth/app/routes/signup.tsxnew file mode 100644index 00000000000..d5a99b098e7--- /dev/null+++ b/apps/auth/app/routes/signup.tsx@@ -0,0 +1,6 @@+import { resolveAuthLocale } from '../lib/locale';+import { buildAuthMeta } from '../lib/seo';++export const meta = () => buildAuthMeta(resolveAuthLocale(), '/signup');++export { default } from '@/features/Auth/SignUp';diff --git a/apps/auth/app/routes/verifyEmail.tsx b/apps/auth/app/routes/verifyEmail.tsxnew file mode 100644index 00000000000..2f9089c2688--- /dev/null+++ b/apps/auth/app/routes/verifyEmail.tsx@@ -0,0 +1,6 @@+import { resolveAuthLocale } from '../lib/locale';+import { buildAuthMeta } from '../lib/seo';++export const meta = () => buildAuthMeta(resolveAuthLocale(), '/verify-email');++export { default } from '@/features/Auth/VerifyEmail';diff --git a/apps/auth/app/shell/AuthAppShell.tsx b/apps/auth/app/shell/AuthAppShell.tsxnew file mode 100644index 00000000000..bac37d03769--- /dev/null+++ b/apps/auth/app/shell/AuthAppShell.tsx@@ -0,0 +1,80 @@+import { ModalHost } from '@lobehub/ui/base-ui';+import { memo, type PropsWithChildren } from 'react';++import BusinessAuthProvider from '@/business/client/BusinessAuthProvider';+import { LobeAnalyticsProviderWrapper } from '@/components/Analytics/LobeAnalyticsProviderWrapper';+import type { IFeatureFlags } from '@/config/featureFlags';+import { mapFeatureFlagsEnvToState } from '@/config/featureFlags';+import AuthContainer from '@/features/AuthShell/AuthContainer';+import { AuthServerConfigProvider } from '@/features/AuthShell/AuthServerConfigProvider';+import AuthThemeLite from '@/features/AuthShell/AuthThemeLite';+import { useIsHydrated } from '@/hooks/useIsHydrated';+import type { GlobalServerConfig } from '@/types/serverConfig';+import type { AnalyticsConfig } from '@/types/spaServerConfig';++import AuthLocaleProvider from './AuthLocaleProvider';++const EMPTY_ANALYTICS = {};++/** What `/webapi/auth/spa-config` serves β narrower than the Next.js shell's. */+interface AuthWorkerConfig {+ analyticsConfig: AnalyticsConfig;+ config: Pick<+ GlobalServerConfig,+ 'disableEmailPassword' | 'enableEmailVerification' | 'enableMagicLink' | 'oAuthSSOProviders'+ >;+ enableOIDC: boolean;+ featureFlags?: Partial<IFeatureFlags>;+ globalCDN?: boolean;+}++// Everything here is deployment state the build cannot know, so the worker+// injects it. Reading it only after hydration keeps the first client render+// byte-identical to the prerendered document β which is why+// `enableBusinessFeatures` must not travel this way: prerendering the SSO+// buttons depends on knowing it during the render.+const useInjectedServerConfig = (): AuthWorkerConfig | undefined => {+ const isHydrated = useIsHydrated();++ if (!isHydrated) return undefined;++ return window.__SERVER_CONFIG__ as unknown as AuthWorkerConfig | undefined;+};++interface AuthAppShellProps extends PropsWithChildren {+ locale: string;+}++const AuthAppShell = memo<AuthAppShellProps>(({ children, locale }) => {+ const serverConfig = useInjectedServerConfig();++ return (+ <AuthLocaleProvider locale={locale}>+ <AuthThemeLite globalCDN={serverConfig?.globalCDN}>+ <AuthServerConfigProvider+ enableOIDC={serverConfig?.enableOIDC}+ isMobile={false}+ serverConfig={serverConfig?.config}+ featureFlags={+ serverConfig?.featureFlags+ ? mapFeatureFlagsEnvToState(serverConfig.featureFlags)+ : undefined+ }+ >+ <LobeAnalyticsProviderWrapper+ analytics={serverConfig?.analyticsConfig ?? EMPTY_ANALYTICS}+ >+ <BusinessAuthProvider>+ <AuthContainer>{children}</AuthContainer>+ </BusinessAuthProvider>+ </LobeAnalyticsProviderWrapper>+ </AuthServerConfigProvider>+ <ModalHost />+ </AuthThemeLite>+ </AuthLocaleProvider>+ );+});++AuthAppShell.displayName = 'AuthAppShell';++export default AuthAppShell;diff --git a/apps/auth/app/shell/AuthLocaleProvider.tsx b/apps/auth/app/shell/AuthLocaleProvider.tsxnew file mode 100644index 00000000000..4c629571e51--- /dev/null+++ b/apps/auth/app/shell/AuthLocaleProvider.tsx@@ -0,0 +1,49 @@+import { ConfigProvider } from 'antd';+import { memo, type PropsWithChildren, useEffect, useState } from 'react';+import { isRtlLang } from 'rtl-detect';++import { readAuthResources } from './authResources';+import { createAuthI18n } from './createAuthI18n';++interface AuthLocaleProviderProps extends PropsWithChildren {+ locale: string;+}++const AuthLocaleProvider = memo<AuthLocaleProviderProps>(({ children, locale }) => {+ const [i18n] = useState(() => createAuthI18n({ locale, resources: readAuthResources(locale) }));+ const [lang, setLang] = useState(locale);++ if (!i18n.instance.isInitialized) {+ i18n.init();+ }++ useEffect(() => {+ const handleLang = (lng: string) => {+ setLang((prev) => (prev === lng ? prev : lng));+ };++ i18n.instance.on('languageChanged', handleLang);+ return () => {+ i18n.instance.off('languageChanged', handleLang);+ };+ }, [i18n]);++ return (+ <ConfigProvider+ direction={isRtlLang(lang) ? 'rtl' : 'ltr'}+ theme={{+ components: {+ Button: {+ contentFontSizeSM: 12,+ },+ },+ }}+ >+ {children}+ </ConfigProvider>+ );+});++AuthLocaleProvider.displayName = 'AuthLocaleProvider';++export default AuthLocaleProvider;diff --git a/apps/auth/app/shell/authResources.client.ts b/apps/auth/app/shell/authResources.client.tsnew file mode 100644index 00000000000..5368008c6fe--- /dev/null+++ b/apps/auth/app/shell/authResources.client.ts@@ -0,0 +1,15 @@+import { AUTH_I18N_SCRIPT_ID, type AuthResourceBundle } from './i18nScript';++const script = () => document.getElementById(AUTH_I18N_SCRIPT_ID);++let parsed: AuthResourceBundle | undefined;++export const readAuthResources = (_locale?: string): AuthResourceBundle => {+ parsed ??= JSON.parse(script()?.textContent || '{}');++ return parsed!;+};++// Returned verbatim so re-rendering the tag produces the exact bytes the+// document was prerendered with.+export const serializeAuthResources = (_locale?: string): string => script()?.textContent ?? '';diff --git a/apps/auth/app/shell/authResources.ts b/apps/auth/app/shell/authResources.tsnew file mode 100644index 00000000000..a56046c5303--- /dev/null+++ b/apps/auth/app/shell/authResources.ts@@ -0,0 +1,45 @@+import defaultAuth from '@/locales/default/auth';+import defaultAuthError from '@/locales/default/authError';+import defaultCommon from '@/locales/default/common';+import defaultError from '@/locales/default/error';+import defaultMarketAuth from '@/locales/default/marketAuth';+import defaultOauth from '@/locales/default/oauth';++import { DEFAULT_PRERENDER_LOCALE, resolveDocumentLocale } from '../lib/prerender';+import type { AuthNamespace, AuthResourceBundle } from './i18nScript';++// Prerender-only: `vite.config.shared.mts` swaps this module for the `.client`+// twin, so no dictionary enters the browser bundle β each document carries just+// its own locale, inlined by `root.tsx`.+const translated = import.meta.glob<{ default: Record<string, string> }>(+ '../../../../locales/*/{auth,authError,common,error,marketAuth,oauth}.json',+ { eager: true },+);++const BUNDLES: Record<string, Partial<AuthResourceBundle>> = {};++for (const [file, module] of Object.entries(translated)) {+ const match = /\/locales\/([^/]+)\/([^/]+)\.json$/.exec(file);+ if (!match) continue;++ const [, locale, namespace] = match;+ (BUNDLES[locale!] ??= {})[namespace as AuthNamespace] = module.default;+}++// English comes from the typed source the other locales are generated from, so+// a key added there is never missing here while the mirror catches up.+BUNDLES[DEFAULT_PRERENDER_LOCALE] = {+ auth: defaultAuth,+ authError: defaultAuthError,+ common: defaultCommon,+ error: defaultError,+ marketAuth: defaultMarketAuth,+ oauth: defaultOauth,+};++export const readAuthResources = (locale: string): AuthResourceBundle =>+ BUNDLES[resolveDocumentLocale(locale)] as AuthResourceBundle;++export const serializeAuthResources = (locale: string): string =>+ // `<` must not appear raw inside a script element; `\u003c` is still valid JSON.+ JSON.stringify(readAuthResources(locale)).replaceAll('<', String.raw`\u003c`);diff --git a/apps/auth/app/shell/createAuthI18n.ts b/apps/auth/app/shell/createAuthI18n.tsnew file mode 100644index 00000000000..6ead0e723c3--- /dev/null+++ b/apps/auth/app/shell/createAuthI18n.ts@@ -0,0 +1,54 @@+import i18next from 'i18next';+import resourcesToBackend from 'i18next-resources-to-backend';+import { initReactI18next } from 'react-i18next';++import { DEFAULT_LANG } from '@/const/locale';+import { normalizeLocale } from '@/locales/resources';++import type { AuthResourceBundle } from './i18nScript';+import { AUTH_NAMESPACES } from './i18nScript';+import { loadAuthNamespace } from './loadAuthNamespace';++interface CreateAuthI18nOptions {+ locale: string;+ resources: AuthResourceBundle;+}++// The served locale is bundled into the document and initialised synchronously,+// so prerender and hydration render identical markup; anything the language+// switcher reaches afterwards arrives through the on-demand backend.+export const createAuthI18n = ({ locale, resources }: CreateAuthI18nOptions) => {+ const lng = normalizeLocale(locale);+ const instance = i18next+ .createInstance()+ .use(initReactI18next)+ .use(resourcesToBackend(loadAuthNamespace));++ // With `ns: []` and the served language bundled, i18next treats every+ // namespace as loaded and never asks the backend β switching has to fetch.+ instance.on('languageChanged', (next) => {+ if (normalizeLocale(next) === lng) return;+ void instance.reloadResources([normalizeLocale(next)], [...AUTH_NAMESPACES]);+ });++ return {+ init: () =>+ instance.init({+ defaultNS: ['auth', 'common', 'error'],+ fallbackLng: DEFAULT_LANG,+ initAsync: false,+ interpolation: { escapeValue: false },+ keySeparator: false,+ lng,+ ns: [],+ partialBundledLanguages: true,+ react: {+ bindI18nStore: 'added',+ useSuspense: false,+ },+ resources: { [lng]: resources },+ showSupportNotice: false,+ }),+ instance,+ };+};diff --git a/apps/auth/app/shell/i18nScript.ts b/apps/auth/app/shell/i18nScript.tsnew file mode 100644index 00000000000..78f83e6b1fe--- /dev/null+++ b/apps/auth/app/shell/i18nScript.ts@@ -0,0 +1,14 @@+export const AUTH_I18N_SCRIPT_ID = 'auth-i18n';++export const AUTH_NAMESPACES = [+ 'auth',+ 'authError',+ 'common',+ 'error',+ 'marketAuth',+ 'oauth',+] as const;++export type AuthNamespace = (typeof AUTH_NAMESPACES)[number];++export type AuthResourceBundle = Record<AuthNamespace, Record<string, string>>;diff --git a/apps/auth/app/shell/loadAuthNamespace.ts b/apps/auth/app/shell/loadAuthNamespace.tsnew file mode 100644index 00000000000..752ef4c69ee--- /dev/null+++ b/apps/auth/app/shell/loadAuthNamespace.ts@@ -0,0 +1,27 @@+import { normalizeLocale } from '@/locales/resources';++import { DEFAULT_PRERENDER_LOCALE } from '../lib/prerender';++// Only the served locale ships inside the document; the language switcher offers+// all of them, so every other dictionary is fetched on demand. Lazy on purpose β+// these become their own chunks and never touch the first-load path.+const translated = import.meta.glob<{ default: Record<string, string> }>(+ '../../../../locales/*/{auth,authError,common,error,marketAuth,oauth}.json',+);++const defaults = import.meta.glob<{ default: Record<string, string> }>(+ '../../../../packages/locales/src/default/{auth,authError,common,error,marketAuth,oauth}.ts',+);++const entry = <T>(map: Record<string, () => Promise<T>>, suffix: string) =>+ Object.entries(map).find(([file]) => file.endsWith(suffix))?.[1];++export const loadAuthNamespace = async (lng: string, namespace: string) => {+ const locale = normalizeLocale(lng);+ const load =+ locale === DEFAULT_PRERENDER_LOCALE+ ? entry(defaults, `/default/${namespace}.ts`)+ : entry(translated, `/${locale}/${namespace}.json`);++ return (await load?.())?.default;+};diff --git a/apps/auth/app/stubs/loadAuthNamespace.ts b/apps/auth/app/stubs/loadAuthNamespace.tsnew file mode 100644index 00000000000..344aca822e5--- /dev/null+++ b/apps/auth/app/stubs/loadAuthNamespace.ts@@ -0,0 +1,3 @@+// The prerender pass renders one locale, already bundled β it never switches+// language, so the on-demand loader's glob has no business in that graph.+export const loadAuthNamespace = async () => undefined;diff --git a/apps/auth/app/virtual-modules.d.ts b/apps/auth/app/virtual-modules.d.tsnew file mode 100644index 00000000000..8083314a0f1--- /dev/null+++ b/apps/auth/app/virtual-modules.d.ts@@ -0,0 +1,10 @@+declare module 'virtual:lobehub/antd-static-css' {+ export const css: string;+ export const href: string;+ export const styleKeys: string[];+}++declare module 'virtual:lobehub/theme-vars-css' {+ export const css: string;+ export const href: string;+}diff --git a/apps/auth/package.json b/apps/auth/package.jsonnew file mode 100644index 00000000000..ca44d786632--- /dev/null+++ b/apps/auth/package.json@@ -0,0 +1,20 @@+{+ "name": "@lobehub/auth",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "scripts": {+ "build": "node scripts/build.mjs",+ "deploy": "bun scripts/deploy.ts",+ "dev": "react-router dev -c vite.config.rr.mts",+ "preview": "wrangler dev",+ "type-check": "tsc --noEmit"+ },+ "devDependencies": {+ "@ant-design/cssinjs": "^2.1.2",+ "@react-router/dev": "^8.3.0",+ "isbot": "^5.1.32",+ "vite-tsconfig-paths": "^6.1.1",+ "wrangler": "^4.123.0"+ }+}diff --git a/apps/auth/react-router.config.ts b/apps/auth/react-router.config.tsnew file mode 100644index 00000000000..332b44361c7--- /dev/null+++ b/apps/auth/react-router.config.ts@@ -0,0 +1,16 @@+import type { Config } from '@react-router/dev/config';++import { PRERENDER_ROUTES } from './app/lib/prerender';++export default {+ appDirectory: 'app',+ // One pass per locale writes into its own directory; scripts/build.mjs folds+ // the non-default passes' documents back into the default build.+ buildDirectory: process.env.AUTH_BUILD_DIR || 'build',+ prerender: [...PRERENDER_ROUTES],+ // Lazy discovery hits /__manifest, which the gateway routes to the default+ // target (app) on the shared lobehub.com origin β the HTML reply breaks+ // client navigations. The route table is tiny; ship it with the document.+ routeDiscovery: { mode: 'initial' },+ ssr: false,+} satisfies Config;diff --git a/apps/auth/scripts/build.mjs b/apps/auth/scripts/build.mjsnew file mode 100644index 00000000000..b6c00ef186a--- /dev/null+++ b/apps/auth/scripts/build.mjs@@ -0,0 +1,184 @@+import { execFile, execFileSync } from 'node:child_process';+import { cp, mkdir, readdir, readFile, rm, stat } from 'node:fs/promises';+import { availableParallelism } from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);++const appRoot = fileURLToPath(new URL('..', import.meta.url));+const { DEFAULT_PRERENDER_LOCALE, PRERENDER_LOCALES, PRERENDER_ROUTES, prerenderOutputDir } =+ await import(new URL('../app/lib/prerender.ts', import.meta.url).href);++const AUTH_NAMESPACES = ['auth', 'authError', 'common', 'error', 'marketAuth', 'oauth'];++// The matrix is a hand-written list because `react-router.config.ts` is loaded+// by plain Node, which cannot resolve the repo's aliases. Check it against the+// dictionaries on disk so a new translation is never silently left un-rendered.+const assertLocaleMatrix = async () => {+ const localesDir = path.resolve(appRoot, '../../locales');+ const onDisk = (await readdir(localesDir, { withFileTypes: true }))+ .filter((entry) => entry.isDirectory())+ .map((entry) => entry.name);++ const complete = [];+ for (const locale of onDisk) {+ const files = new Set(await readdir(path.join(localesDir, locale)));+ if (AUTH_NAMESPACES.every((ns) => files.has(`${ns}.json`))) complete.push(locale);+ }++ const missing = complete.filter((locale) => !PRERENDER_LOCALES.includes(locale));+ const extra = PRERENDER_LOCALES.filter((locale) => !complete.includes(locale));++ if (missing.length > 0 || extra.length > 0)+ throw new Error(+ `PRERENDER_LOCALES is out of sync with locales/: ` ++ `${missing.length > 0 ? `missing ${missing.join(', ')}; ` : ''}` ++ `${extra.length > 0 ? `no dictionaries for ${extra.join(', ')}` : ''}`,+ );++ console.log(+ `Locale matrix: ${PRERENDER_LOCALES.length} locales x ${PRERENDER_ROUTES.length} routes`,+ );+};++const run = (command, args, env) =>+ execFileSync(command, args, { cwd: appRoot, env: { ...process.env, ...env }, stdio: 'inherit' });++const buildPass = (locale, buildDir) => {+ console.log(`\n=== Prerender pass: ${locale} -> ${buildDir} ===`);+ run('node_modules/.bin/react-router', ['build', '-c', 'vite.config.rr.mts'], {+ AUTH_BUILD_DIR: buildDir,+ AUTH_PRERENDER_LOCALE: locale,+ });+};++// A pass costs about two cores, and the passes after the first one only exist+// to produce their four documents β their client output is identical and gets+// thrown away, so they are pure fan-out.+const CONCURRENCY =+ Number(process.env.AUTH_BUILD_CONCURRENCY) ||+ Math.max(1, Math.min(6, availableParallelism() - 2));++const buildPassAsync = async (locale, buildDir) => {+ const started = Date.now();+ // Output is captured rather than inherited: eighteen interleaved vite logs+ // are unreadable, and a failure still surfaces through the rejection.+ await execFileAsync('node_modules/.bin/react-router', ['build', '-c', 'vite.config.rr.mts'], {+ cwd: appRoot,+ env: { ...process.env, AUTH_BUILD_DIR: buildDir, AUTH_PRERENDER_LOCALE: locale },+ maxBuffer: 64 * 1024 * 1024,+ }).catch((error) => {+ throw new Error(+ `prerender pass ${locale} failed:\n${error.stderr || error.stdout || error.message}`,+ );+ });++ return Date.now() - started;+};++const pool = async (items, worker) => {+ const queue = [...items];++ await Promise.all(+ Array.from({ length: Math.min(CONCURRENCY, queue.length) }, async () => {+ for (let item = queue.shift(); item !== undefined; item = queue.shift()) await worker(item);+ }),+ );+};++const { SERVER_CONFIG_PLACEHOLDER } = await import(+ new URL('../app/lib/serverConfig.ts', import.meta.url).href+);++const assertDocument = async (html, clientDir, label) => {+ if (!html.includes(SERVER_CONFIG_PLACEHOLDER))+ throw new Error(`${label} lost the server-config placeholder the worker replaces`);++ const title = html.match(/<title>([^<]*)<\/title>/)?.[1];+ if (!title) throw new Error(`${label} rendered without a title`);++ if (!/<meta[^>]+name="robots"/.test(html))+ throw new Error(`${label} rendered without a robots directive`);++ await assertAssetsResolve(html, clientDir, label);+};++const assertAssetsResolve = async (html, clientDir, label) => {+ const referenced = [...html.matchAll(/(?:src|href)="(\/assets\/[^"]+)"/g)].map((m) => m[1]);+ for (const asset of new Set(referenced)) {+ await stat(path.join(clientDir, asset)).catch(() => {+ throw new Error(`${label} references a missing asset: ${asset}`);+ });+ }+};++const main = async () => {+ const defaultClient = path.join(appRoot, 'build/client');++ await assertLocaleMatrix();++ buildPass(DEFAULT_PRERENDER_LOCALE, 'build');++ // Emitted before the locale passes so their documents can be checked against+ // the complete asset set they reference.+ console.log('\n=== Static CSS ===');+ run('node', ['scripts/emit-static-css.mjs']);++ for (const route of [...PRERENDER_ROUTES, '']) {+ const document = path.join(defaultClient, prerenderOutputDir(route), 'index.html');+ await assertDocument(+ await readFile(document, 'utf8'),+ defaultClient,+ `${DEFAULT_PRERENDER_LOCALE}${route || '/ (spa fallback)'}`,+ );+ }++ const remaining = PRERENDER_LOCALES.filter((locale) => locale !== DEFAULT_PRERENDER_LOCALE);+ console.log(`\n=== ${remaining.length} locale passes, ${CONCURRENCY} at a time ===`);++ let done = 0;++ await pool(remaining, async (locale) => {+ const buildDir = `build-${locale}`;+ const elapsed = await buildPassAsync(locale, buildDir);++ for (const route of PRERENDER_ROUTES) {+ const source = path.join(+ appRoot,+ buildDir,+ 'client',+ prerenderOutputDir(route),+ 'index.html',+ );+ const target = path.join(+ defaultClient,+ '__i18n',+ locale,+ prerenderOutputDir(route),+ 'index.html',+ );++ // Only the SSR environment carries the locale, so every pass emits the+ // same client assets β a stale hash here means that stopped being true.+ await assertDocument(await readFile(source, 'utf8'), defaultClient, `${locale}${route}`);++ await mkdir(path.dirname(target), { recursive: true });+ await cp(source, target);+ }++ await rm(path.join(appRoot, buildDir), { force: true, recursive: true });+ done += 1;+ console.log(+ ` [${String(done).padStart(2)}/${remaining.length}] ${locale.padEnd(6)} ${PRERENDER_ROUTES.length} documents in ${(elapsed / 1000).toFixed(1)}s`,+ );+ });++ console.log('\n=== Worker ===');+ run('node_modules/.bin/vite', ['build', '-c', 'vite.config.worker.mts']);++ console.log(`\nBuilt ${(await readdir(defaultClient)).length} top-level client entries.`);+};++await main();diff --git a/apps/auth/scripts/deploy.ts b/apps/auth/scripts/deploy.tsnew file mode 100644index 00000000000..644d982108f--- /dev/null+++ b/apps/auth/scripts/deploy.ts@@ -0,0 +1,78 @@+import { execSync } from 'node:child_process';+import { existsSync } from 'node:fs';+import { resolve } from 'node:path';++import dotenv from 'dotenv';++import { uploadAssets } from '../../../scripts/mobileSpaWorkflow/upload';++const authRoot = resolve(__dirname, '..');+const repoRoot = resolve(authRoot, '../..');+const assetsDir = resolve(authRoot, 'build/client/assets');++// A host repo that builds this app from a submodule keeps its own .env; it+// points AUTH_ENV_FILE at it so local deploys pick up the same credentials.+dotenv.config({ path: process.env.AUTH_ENV_FILE || resolve(repoRoot, '.env') });++const firstEnv = (...names: string[]) => {+ for (const name of names) {+ const value = process.env[name];+ if (value) return value;+ }+ return undefined;+};++const requireEnv = (...names: string[]): string => {+ const value = firstEnv(...names);+ if (!value) throw new Error(`Missing env: ${names.join(' / ')}`);+ return value;+};++async function main() {+ const publicDomain = new URL(requireEnv('ASSET_S3_PUBLIC_DOMAIN', 'MOBILE_S3_PUBLIC_DOMAIN'))+ .origin;+ // Same convention as cloud's resolveViteBase: a stable entry suffix, no version+ // stamp β content-hashed filenames make uploads incremental and cache-immutable.+ // Deliberately not the generic ASSET_S3_KEY_PREFIX: workbench reads that one+ // too, and a shared value would put both apps on the same prefix.+ const keyPrefix = (firstEnv('AUTH_S3_KEY_PREFIX') || 'auth').replaceAll(/^\/+|\/+$/g, '');+ const cdnBase = `${publicDomain}/${keyPrefix}/`;++ console.log(`=== Step 1: Build auth (VITE_CDN_BASE=${cdnBase}) ===`);+ execSync('bun run build', {+ cwd: authRoot,+ env: {+ ...process.env,+ NODE_ENV: 'production',+ NODE_OPTIONS: '--max-old-space-size=8192',+ VITE_CDN_BASE: cdnBase,+ },+ stdio: 'inherit',+ });++ if (!existsSync(assetsDir)) throw new Error(`Build output not found at ${assetsDir}`);++ console.log('\n=== Step 2: Upload assets to S3 ===');+ await uploadAssets(assetsDir, {+ accessKeyId: requireEnv('ASSET_S3_ACCESS_KEY_ID', 'MOBILE_S3_ACCESS_KEY_ID'),+ bucket: requireEnv('ASSET_S3_BUCKET', 'MOBILE_S3_BUCKET'),+ endpoint: requireEnv('ASSET_S3_ENDPOINT', 'MOBILE_S3_ENDPOINT'),+ keyPrefix,+ publicDomain,+ region: firstEnv('ASSET_S3_REGION', 'MOBILE_S3_REGION') || 'auto',+ secretAccessKey: requireEnv('ASSET_S3_SECRET_ACCESS_KEY', 'MOBILE_S3_SECRET_ACCESS_KEY'),+ });++ console.log('\n=== Step 3: Deploy worker ===');+ execSync('node_modules/.bin/wrangler deploy', {+ cwd: authRoot,+ stdio: 'inherit',+ });++ console.log('\n=== Deploy complete ===');+}++main().catch((error) => {+ console.error('Deploy failed:', error);+ process.exit(1);+});diff --git a/apps/auth/scripts/emit-static-css.mjs b/apps/auth/scripts/emit-static-css.mjsnew file mode 100644index 00000000000..7b6531beb86--- /dev/null+++ b/apps/auth/scripts/emit-static-css.mjs@@ -0,0 +1,27 @@+import { mkdir, writeFile } from 'node:fs/promises';+import { fileURLToPath } from 'node:url';++import { antdStaticCssOptions, themeVarsCssOptions } from '../staticCssOptions.mjs';++process.env.NODE_ENV = 'production';++const { buildAntdStaticCss, buildThemeVarsCss } = await import('@lobehub/ui/static-css');++const clientAssetsDir = new URL('../build/client/assets/', import.meta.url);+await mkdir(clientAssetsDir, { recursive: true });++const antd = buildAntdStaticCss(antdStaticCssOptions);+const themeVars = buildThemeVarsCss(themeVarsCssOptions);++for (const payload of [antd, themeVars]) {+ // href may be CDN-absolute; the local mirror always lives at assets/<basename>.+ const fileName = new URL(payload.href, 'https://placeholder.invalid').pathname.split('/').at(-1);+ const target = new URL(fileName, clientAssetsDir);+ await writeFile(target, payload.css, 'utf8');+ console.log(fileURLToPath(target));+}++if (antd.failedProbes.length > 0) {+ console.error('static-css failed probes:', antd.failedProbes);+ process.exit(1);+}diff --git a/apps/auth/scripts/should-build.mjs b/apps/auth/scripts/should-build.mjsnew file mode 100644index 00000000000..60958c094a4--- /dev/null+++ b/apps/auth/scripts/should-build.mjs@@ -0,0 +1,82 @@+import { execFileSync } from 'node:child_process';+import { appendFileSync, readFileSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');+const manifestPath =+ process.env.AUTH_MANIFEST || path.resolve(repoRoot, 'apps/auth/build-inputs.txt');++// Inputs the bundle graph cannot see: build config and its imports, dependency+// versions, and the locale files a future pass may start bundling.+//+// Matched anywhere in the path, not anchored: a host repo that builds this app+// from a submodule reports the same files under its own prefix+// (`lobehub/apps/auth/...`), and both spellings must trigger.+const META_TRIGGER_SEGMENTS = [+ 'apps/auth/',+ 'plugins/vite/',+ 'packages/locales/src/default/',+ 'pnpm-lock.yaml',+ 'tsconfig.json',+];+const BUNDLED_LOCALE = /locales\/[^/]+\/(?:auth|authError|common|error|marketAuth|oauth)\.json$/;++const META_TRIGGERS = [+ (file) => META_TRIGGER_SEGMENTS.some((segment) => file.includes(segment)),+ (file) => BUNDLED_LOCALE.test(file),+];++const emit = (shouldBuild, reason, hits = []) => {+ console.log(reason);+ for (const hit of hits) console.log(` ${hit}`);+ console.log(`should_build=${shouldBuild}`);+ if (process.env.GITHUB_OUTPUT) {+ appendFileSync(process.env.GITHUB_OUTPUT, `should_build=${shouldBuild}\n`);+ }+};++const args = process.argv.slice(2);+let changed;++if (args[0] === '--files') {+ changed = args.slice(1);+} else {+ const [base, head = 'HEAD'] = args;+ if (!base) {+ emit(true, 'no base commit provided β building');+ process.exit(0);+ }+ try {+ changed = execFileSync('git', ['diff', '--name-only', `${base}...${head}`], {+ cwd: repoRoot,+ encoding: 'utf8',+ })+ .split('\n')+ .filter(Boolean);+ } catch {+ emit(true, `base commit ${base} not resolvable β building`);+ process.exit(0);+ }+}++let manifestText;+try {+ manifestText = readFileSync(manifestPath, 'utf8');+} catch {+ emit(true, `manifest ${manifestPath} not available β building`);+ process.exit(0);+}++const manifest = new Set(manifestText.split('\n').filter(Boolean));+const hits = changed.filter(+ (file) => manifest.has(file) || META_TRIGGERS.some((matches) => matches(file)),+);++emit(+ hits.length > 0,+ hits.length > 0+ ? `${hits.length} auth build input(s) changed:`+ : `no auth build inputs among ${changed.length} changed file(s)`,+ hits.slice(0, 20),+);diff --git a/apps/auth/staticCssOptions.mjs b/apps/auth/staticCssOptions.mjsnew file mode 100644index 00000000000..987e0985f9c--- /dev/null+++ b/apps/auth/staticCssOptions.mjs@@ -0,0 +1,9 @@+const cdnBase = (process.env.VITE_CDN_BASE || '').replace(/\/+$/, '');++export const antdStaticCssOptions = {+ hrefTemplate: (hash) => `${cdnBase}/assets/antd-${hash}.css`,+};++export const themeVarsCssOptions = {+ hrefTemplate: (hash) => `${cdnBase}/assets/theme-vars-${hash}.css`,+};diff --git a/apps/auth/tsconfig.json b/apps/auth/tsconfig.jsonnew file mode 100644index 00000000000..b7b947e7c8f--- /dev/null+++ b/apps/auth/tsconfig.json@@ -0,0 +1,17 @@+{+ "compilerOptions": {+ "plugins": [],+ "types": ["vite/client"]+ },+ "exclude": ["node_modules"],+ "extends": "../../tsconfig.json",+ "include": [+ "app/**/*.ts",+ "app/**/*.tsx",+ "workers/**/*.ts",+ "vite.config.rr.mts",+ "vite.config.worker.mts",+ "react-router.config.ts",+ "../../src/types/global.d.ts"+ ]+}diff --git a/apps/auth/vite.config.rr.mts b/apps/auth/vite.config.rr.mtsnew file mode 100644index 00000000000..6a74038d50e--- /dev/null+++ b/apps/auth/vite.config.rr.mts@@ -0,0 +1,34 @@+import { existsSync } from 'node:fs';+import path from 'node:path';++import dotenv from 'dotenv';+import tsconfigPaths from 'vite-tsconfig-paths';++import { antdStaticCssOptions, themeVarsCssOptions } from './staticCssOptions.mjs';+import { createAuthRrConfig } from './vite.config.shared.mts';++const appRoot = path.resolve(import.meta.dirname);++const envFile = process.env.AUTH_ENV_FILE || path.resolve(appRoot, '../../.env');+if (existsSync(envFile)) dotenv.config({ path: envFile });++// A host repo that overlays this app (lobehub-cloud maps `@/business/*` and+// friends onto its own implementations) points this at its root tsconfig.+// Vite 8's native tsconfigPaths resolves against the tsconfig nearest each+// importer, which for submodule files is this repo's β losing the overlay.+const overlayTsconfig = process.env.AUTH_TSCONFIG_PROJECT;++export default createAuthRrConfig({+ appRoot,+ repoRoot: overlayTsconfig ? path.dirname(overlayTsconfig) : path.resolve(appRoot, '../..'),+ resolvePlugins: overlayTsconfig+ ? [+ tsconfigPaths({+ ignoreConfigErrors: true,+ projects: [overlayTsconfig],+ root: path.dirname(overlayTsconfig),+ }),+ ]+ : undefined,+ staticCss: { antd: antdStaticCssOptions, themeVars: themeVarsCssOptions },+});diff --git a/apps/auth/vite.config.shared.mts b/apps/auth/vite.config.shared.mtsnew file mode 100644index 00000000000..39a1f442520--- /dev/null+++ b/apps/auth/vite.config.shared.mts@@ -0,0 +1,234 @@+import { writeFileSync } from 'node:fs';+import path from 'node:path';++import { lobeStaticCssPlugin } from '@lobehub/ui/static-css/vite';+import { reactRouter } from '@react-router/dev/vite';+import { defineConfig, type Plugin, type PluginOption } from 'vite';++import { lobeIconImports } from '../../plugins/vite/lobeIconImports';+import { viteMarkdownImport } from '../../plugins/vite/markdownImport';+import { viteNodeModuleStub } from '../../plugins/vite/nodeModuleStub';+import { vitePlatformResolve } from '../../plugins/vite/platformResolve';+import {+ sharedRendererDedupe,+ sharedRendererDefine,+} from '../../plugins/vite/sharedRendererConfig';+import { DEFAULT_PRERENDER_LOCALE } from './app/lib/prerender';++interface StaticCssOptions {+ hrefTemplate: (hash: string) => string;+}++export interface AuthRrConfigOptions {+ /** Directory holding `app/` β the submodule copy when a host repo overlays this app. */+ appRoot: string;+ /** Repo whose files count as build inputs and are allowed by the dev server. */+ repoRoot: string;+ /**+ * Resolution for `@/*`. Vite 8 native tsconfigPaths walks to the tsconfig+ * nearest each importer, which loses a host repo's overlay paths β those+ * hosts pass their own resolver plugin here instead.+ */+ resolvePlugins?: PluginOption[];+ staticCss: { antd: StaticCssOptions; themeVars: StaticCssOptions };+}++export const createAuthRrConfig = ({+ appRoot,+ repoRoot,+ resolvePlugins,+ staticCss,+}: AuthRrConfigOptions) => {+ const prerenderLocale = JSON.stringify(+ process.env.AUTH_PRERENDER_LOCALE || DEFAULT_PRERENDER_LOCALE,+ );+ const define = {+ ...sharedRendererDefine({ isElectron: false, isMobile: false }),+ // Client-side the value is never read β the browser takes the locale off+ // `<html lang>` β but the identifier has to resolve in both environments.+ __AUTH_PRERENDER_LOCALE__: JSON.stringify(DEFAULT_PRERENDER_LOCALE),+ };+ const { 'process.env': _processEnvFallback, ...ssrDefine } = define;+ const prerenderDefine = { ...ssrDefine, __AUTH_PRERENDER_LOCALE__: prerenderLocale };++ const moduleTrace = (needle: string): Plugin => ({+ applyToEnvironment: (environment) => environment.name === (process.env.AUTH_TRACE_ENV || 'ssr'),+ buildEnd() {+ const targets = [...this.getModuleIds()].filter((id) => id.includes(needle));+ for (const target of targets.slice(0, 2)) {+ const parent = new Map<string, string | null>([[target, null]]);+ const queue = [target];+ let found: string | null = null;+ while (queue.length > 0 && !found) {+ const current = queue.shift()!;+ const info = this.getModuleInfo(current);+ for (const importer of [...(info?.importers ?? []), ...(info?.dynamicImporters ?? [])]) {+ if (parent.has(importer)) continue;+ parent.set(importer, current);+ queue.push(importer);+ if (importer.startsWith(appRoot) || importer.includes('virtual:react-router')) {+ found = importer;+ break;+ }+ }+ }+ const chain: string[] = [];+ let cursor: string | null = found;+ while (cursor) {+ chain.push(cursor);+ cursor = parent.get(cursor) ?? null;+ }+ console.info(`\n=== module trace: ${target}`);+ console.info(chain.join('\n -> ') || '(no importer path found)');+ }+ },+ name: 'auth-module-trace',+ });++ // The locale dictionaries are ~210KB of the eager client graph. The browser+ // gets its one locale inlined in the document instead, so the module that+ // holds every bundle is swapped for a DOM reader on the client build.+ const clientStubs: Record<string, string> = {+ [path.resolve(appRoot, 'app/shell/authResources.ts')]: path.resolve(+ appRoot,+ 'app/shell/authResources.client.ts',+ ),+ };++ const ssrStubs: Record<string, string> = {+ [path.resolve(appRoot, 'app/shell/loadAuthNamespace.ts')]: path.resolve(+ appRoot,+ 'app/stubs/loadAuthNamespace.ts',+ ),+ };++ const authSsrStubs = (): Plugin => ({+ applyToEnvironment: (environment) => environment.name === 'ssr',+ enforce: 'pre',+ name: 'auth-ssr-stubs',+ async resolveId(source, importer, options) {+ if (!source.includes('loadAuthNamespace')) return null;++ const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });++ return resolved ? (ssrStubs[resolved.id] ?? null) : null;+ },+ });++ const authClientStubs = (): Plugin => ({+ applyToEnvironment: (environment) => environment.name === 'client',+ enforce: 'pre',+ name: 'auth-client-stubs',+ async resolveId(source, importer, options) {+ if (!source.includes('authResources')) return null;++ const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });++ return resolved ? (clientStubs[resolved.id] ?? null) : null;+ },+ });++ const buildInputIds = new Set<string>();++ const buildInputsManifest = (): Plugin => ({+ apply: 'build',+ buildEnd() {+ for (const id of this.getModuleIds()) {+ if (!id.startsWith(repoRoot)) continue;+ if (id.includes('/node_modules/') || id.includes('\0')) continue;+ buildInputIds.add(path.relative(repoRoot, id.split('?')[0]!));+ }+ },+ name: 'auth-build-inputs-manifest',+ writeBundle(options) {+ if (!options.dir?.includes('build/client')) return;+ const manifest = [...buildInputIds].sort().join('\n');+ writeFileSync(path.resolve(appRoot, 'build-inputs.txt'), `${manifest}\n`);+ },+ });++ const staticCssDevServe = (): Plugin => {+ const cache = new Map<string, string>();+ const serve = async (kind: 'antd' | 'themeVars') => {+ if (!cache.has(kind)) {+ const { buildAntdStaticCss, buildThemeVarsCss } = await import('@lobehub/ui/static-css');+ cache.set(+ kind,+ kind === 'antd'+ ? buildAntdStaticCss(staticCss.antd).css+ : buildThemeVarsCss(staticCss.themeVars).css,+ );+ }+ return cache.get(kind)!;+ };++ return {+ apply: 'serve',+ configureServer(server) {+ server.middlewares.use(async (req, res, next) => {+ const url = req.url ?? '';+ const kind = /^\/assets\/antd-[a-f0-9]+\.css/.test(url)+ ? ('antd' as const)+ : /^\/assets\/theme-vars-[a-f0-9]+\.css/.test(url)+ ? ('themeVars' as const)+ : undefined;+ if (!kind) return next();+ res.setHeader('Content-Type', 'text/css; charset=utf-8');+ res.setHeader('Cache-Control', 'no-cache');+ res.end(await serve(kind));+ });+ },+ name: 'auth-static-css-dev-serve',+ };+ };++ const proxyTarget = process.env.AUTH_API_PROXY || 'https://app.lobehub.com';+ const backendProxy = Object.fromEntries(+ ['/api', '/oidc', '/trpc', '/webapi'].map((prefix) => [+ prefix,+ { changeOrigin: true, target: proxyTarget },+ ]),+ );++ return defineConfig(({ command }) => ({+ base: command === 'serve' ? '/' : process.env.VITE_CDN_BASE || '/',+ environments: {+ client: { define },+ ssr: {+ define: prerenderDefine,+ // The prerender pass runs the built server bundle through plain Node,+ // which rejects the extensionless directory imports some published `es/`+ // bundles still ship β bundle every dependency instead of externalizing.+ resolve: { noExternal: command === 'build' ? true : [] },+ },+ },+ plugins: [+ process.env.AUTH_TRACE_MODULE ? moduleTrace(process.env.AUTH_TRACE_MODULE) : undefined,+ authClientStubs(),+ authSsrStubs(),+ buildInputsManifest(),+ viteMarkdownImport(),+ viteNodeModuleStub(),+ vitePlatformResolve('web'),+ lobeStaticCssPlugin({ antd: staticCss.antd, themeVars: staticCss.themeVars }),+ staticCssDevServe(),+ reactRouter(),+ ...lobeIconImports(),+ ...(resolvePlugins ?? []),+ ],+ resolve: {+ // The builtin-tool packages declare `@lobehub/ui: ^5` and resolve to an+ // older copy than the app's; without deduping, their render surfaces fail+ // to import components that only exist in the app's version.+ dedupe: [...sharedRendererDedupe, '@lobehub/ui'],+ tsconfigPaths: !resolvePlugins,+ },+ server: {+ fs: {+ allow: [repoRoot],+ },+ port: Number(process.env.AUTH_SPA_PORT_RR) || 3018,+ proxy: backendProxy,+ },+ }));+};diff --git a/apps/auth/vite.config.worker.mts b/apps/auth/vite.config.worker.mtsnew file mode 100644index 00000000000..29315eec222--- /dev/null+++ b/apps/auth/vite.config.worker.mts@@ -0,0 +1,22 @@+import path from 'node:path';++import { defineConfig } from 'vite';++const appRoot = path.resolve(import.meta.dirname);++// wrangler's own bundler cannot resolve the repo's `@/*` tsconfig paths, so the+// worker is bundled here and `wrangler.jsonc` points at the output.+export default defineConfig({+ build: {+ emptyOutDir: true,+ outDir: 'build/worker',+ rollupOptions: {+ input: path.resolve(appRoot, 'workers/app.ts'),+ output: { entryFileNames: 'index.js', format: 'esm' },+ },+ ssr: true,+ target: 'esnext',+ },+ resolve: { tsconfigPaths: true },+ ssr: { noExternal: true, target: 'webworker' },+});diff --git a/apps/auth/workers/app.ts b/apps/auth/workers/app.tsnew file mode 100644index 00000000000..52e522e3f28--- /dev/null+++ b/apps/auth/workers/app.ts@@ -0,0 +1,104 @@+import { resolveRequestLocale } from '@/locales/requestLocale';++import {+ documentPathFor,+ resolveDocumentLocale,+ SPA_FALLBACK_DOCUMENT,+} from '../app/lib/prerender';+import { injectServerConfig, withDocumentLocale } from './document';++interface Env {+ ASSETS: { fetch: (request: Request) => Promise<Response> };+ AUTH_API_BASE?: string;+ AUTH_APP_HOME?: string;+}++const API_PREFIXES = ['/api', '/oidc', '/trpc', '/webapi'];++const AUTH_PATH_PREFIXES = [+ '/signin',+ '/signup',+ '/verify-email',+ '/reset-password',+ '/auth-error',+ '/market-auth-callback',+ '/oauth',+];++const CONFIG_ENDPOINT = '/webapi/auth/spa-config';++const matchesPrefix = (pathname: string, prefixes: string[]) =>+ prefixes.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));++const isAssetPath = (pathname: string) =>+ pathname.startsWith('/assets/') || pathname.slice(pathname.lastIndexOf('/')).includes('.');++const stripTrailingSlash = (pathname: string) =>+ pathname.length > 1 && pathname.endsWith('/') ? pathname.slice(0, -1) : pathname;++const loadServerConfig = async (env: Env, request: Request): Promise<unknown | undefined> => {+ if (!env.AUTH_API_BASE) return undefined;++ const target = new URL(CONFIG_ENDPOINT, env.AUTH_API_BASE);++ try {+ // The endpoint answers with `s-maxage`, so the edge cache handles the TTL.+ const response = await fetch(target, {+ headers: { accept: 'application/json', cookie: request.headers.get('cookie') ?? '' },+ });+ if (!response.ok) return undefined;++ return await response.json();+ } catch {+ // A config lookup failure must not take the sign-in page down: the document+ // still renders, and the browser falls back to the config-less state.+ return undefined;+ }+};++const serveDocument = async (request: Request, env: Env, pathname: string) => {+ const locale = resolveDocumentLocale(resolveRequestLocale(request));+ const url = new URL(request.url);++ const documentPath = documentPathFor(pathname, locale);++ const [document, serverConfig] = await Promise.all([+ env.ASSETS.fetch(new Request(new URL(documentPath, url.origin), { headers: request.headers })),+ loadServerConfig(env, request),+ ]);++ if (!document.ok) return document;++ let html = injectServerConfig(await document.text(), serverConfig);++ if (documentPath === SPA_FALLBACK_DOCUMENT) html = withDocumentLocale(html, locale);++ return new Response(html, {+ headers: {+ 'Cache-Control': 'no-cache',+ 'Content-Type': 'text/html; charset=utf-8',+ },+ });+};++export default {+ fetch(request: Request, env: Env) {+ const url = new URL(request.url);+ const pathname = stripTrailingSlash(url.pathname);++ // Standalone deployments have no reverse proxy in front: forward the app's+ // same-origin API calls to the backend, mirroring vite's dev proxy.+ if (env.AUTH_API_BASE && matchesPrefix(pathname, API_PREFIXES)) {+ const target = new URL(url.pathname + url.search, env.AUTH_API_BASE);++ return fetch(new Request(target, request));+ }++ if (isAssetPath(pathname)) return env.ASSETS.fetch(request);++ if (!matchesPrefix(pathname, AUTH_PATH_PREFIXES))+ return Response.redirect(env.AUTH_APP_HOME || 'https://lobehub.com', 302);++ return serveDocument(request, env, pathname);+ },+};diff --git a/apps/auth/workers/document.test.ts b/apps/auth/workers/document.test.tsnew file mode 100644index 00000000000..c930aed21a9--- /dev/null+++ b/apps/auth/workers/document.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest';++import { SERVER_CONFIG_PLACEHOLDER } from '../app/lib/serverConfig';+import { injectServerConfig, withDocumentLocale } from './document';++const documentWith = (head: string) => `<html lang="en-US"><head>${head}</head></html>`;++describe('injectServerConfig', () => {+ it('replaces the placeholder the renderer emits', () => {+ const html = injectServerConfig(documentWith(SERVER_CONFIG_PLACEHOLDER), { enableOIDC: true });++ expect(html).toContain('window.__SERVER_CONFIG__ = {"enableOIDC":true};');+ expect(html).not.toContain(SERVER_CONFIG_PLACEHOLDER);+ });++ it('escapes sequences that would break out of the script', () => {+ const html = injectServerConfig(documentWith(SERVER_CONFIG_PLACEHOLDER), {+ html: '</script><script>alert(1)</script>',+ });++ expect(html).not.toContain('</script><script>');+ });++ it('leaves the document untouched when no config was resolved', () => {+ const original = documentWith(SERVER_CONFIG_PLACEHOLDER);++ expect(injectServerConfig(original, undefined)).toBe(original);+ });+});++describe('withDocumentLocale', () => {+ it('rewrites the lang the SPA fallback was prerendered with', () => {+ expect(+ withDocumentLocale('<html suppressHydrationWarning dir="ltr" lang="en-US">', 'zh-CN'),+ ).toBe('<html suppressHydrationWarning dir="ltr" lang="zh-CN">');+ });+});diff --git a/apps/auth/workers/document.ts b/apps/auth/workers/document.tsnew file mode 100644index 00000000000..7dc8d0e1e81--- /dev/null+++ b/apps/auth/workers/document.ts@@ -0,0 +1,18 @@+import { serializeForHtml } from '@/server/utils/serializeForHtml';++import { SERVER_CONFIG_PLACEHOLDER } from '../app/lib/serverConfig';++export const injectServerConfig = (html: string, serverConfig: unknown) =>+ serverConfig === undefined+ ? html+ : html.replace(+ SERVER_CONFIG_PLACEHOLDER,+ `window.__SERVER_CONFIG__ = ${serializeForHtml(serverConfig)};`,+ );++/**+ * The SPA fallback is prerendered once, in the default locale; the browser reads+ * `<html lang>` to pick its dictionary, so it has to carry the real one.+ */+export const withDocumentLocale = (html: string, locale: string) =>+ html.replace(/<html([^>]*?)\slang="[^"]*"/, `<html$1 lang="${locale}"`);diff --git a/apps/auth/wrangler.jsonc b/apps/auth/wrangler.jsoncnew file mode 100644index 00000000000..9e3c7dd8fe1--- /dev/null+++ b/apps/auth/wrangler.jsonc@@ -0,0 +1,24 @@+{+ "$schema": "../../node_modules/wrangler/config-schema.json",+ "name": "lobehub-auth",+ "account_id": "d35842305b91be4b48e06ff9a9ad83f5",+ "main": "./build/worker/index.js",+ "compatibility_date": "2026-08-01",+ "compatibility_flags": ["nodejs_compat"],+ "assets": {+ "binding": "ASSETS",+ "directory": "./build/client",+ "html_handling": "none",+ "not_found_handling": "none",+ "run_worker_first": true+ },+ "observability": {+ "enabled": true,+ "head_sampling_rate": 1,+ "logs": { "invocation_logs": false }+ },+ "vars": {+ "AUTH_API_BASE": "https://app.lobehub.com",+ "AUTH_APP_HOME": "https://lobehub.com"+ }+}diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex f9191e2e68d..78c168fe5c4 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -4,6 +4,7 @@ packages:- .- e2e- apps/desktop/src/main+ - apps/auth- apps/server- apps/share- apps/workbenchdiff --git a/src/app/(backend)/webapi/auth/spa-config/route.test.ts b/src/app/(backend)/webapi/auth/spa-config/route.test.tsnew file mode 100644index 00000000000..f62de05cfe4--- /dev/null+++ b/src/app/(backend)/webapi/auth/spa-config/route.test.ts@@ -0,0 +1,49 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { GET } from './route';++const mocks = vi.hoisted(() => ({+ appEnv: { CDN_USE_GLOBAL: true },+ authEnv: { ENABLE_OIDC: true },+ buildAnalyticsConfig: vi.fn(() => ({+ posthog: { debug: false, host: 'https://ph', key: 'phc' },+ })),+ getServerAuthConfig: vi.fn(() => ({+ disableEmailPassword: false,+ enableEmailVerification: true,+ enableMagicLink: false,+ oAuthSSOProviders: ['github'],+ })),+ getServerFeatureFlagsValue: vi.fn(() => ({ auth_captcha: true })),+}));++vi.mock('@/config/featureFlags', () => ({+ getServerFeatureFlagsValue: mocks.getServerFeatureFlagsValue,+}));++vi.mock('@/envs/app', () => ({ appEnv: mocks.appEnv }));++vi.mock('@/envs/auth', () => ({ authEnv: mocks.authEnv }));++vi.mock('@/libs/spaHtml', () => ({+ buildAnalyticsConfig: mocks.buildAnalyticsConfig,+}));++vi.mock('@/server/globalConfig/getServerAuthConfig', () => ({+ getServerAuthConfig: mocks.getServerAuthConfig,+}));++describe('GET /webapi/auth/spa-config', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('includes the env-level feature flags the auth shell maps onto state', async () => {+ const response = await GET();+ const body = await response.json();++ expect(mocks.getServerFeatureFlagsValue).toHaveBeenCalled();+ expect(body.featureFlags).toEqual({ auth_captcha: true });+ });+});diff --git a/src/app/(backend)/webapi/auth/spa-config/route.ts b/src/app/(backend)/webapi/auth/spa-config/route.tsnew file mode 100644index 00000000000..074f3262780--- /dev/null+++ b/src/app/(backend)/webapi/auth/spa-config/route.ts@@ -0,0 +1,36 @@+import { getServerFeatureFlagsValue } from '@/config/featureFlags';+import { appEnv } from '@/envs/app';+import { authEnv } from '@/envs/auth';+import { buildAnalyticsConfig } from '@/libs/spaHtml';+import { getServerAuthConfig } from '@/server/globalConfig/getServerAuthConfig';++// The prerendered auth micro app ships without any deployment's config baked in;+// its worker reads this to fill `window.__SERVER_CONFIG__` before serving a page.+//+// Deliberately narrower than `AuthSPAServerConfig`: this endpoint is public and+// unauthenticated, so it carries only the fields the auth pages actually read.+// `enableBusinessFeatures` is not among them β it is a build-time constant.+export const GET = () => {+ const { disableEmailPassword, enableEmailVerification, enableMagicLink, oAuthSSOProviders } =+ getServerAuthConfig();++ return Response.json(+ {+ analyticsConfig: buildAnalyticsConfig(),+ config: {+ disableEmailPassword,+ enableEmailVerification,+ enableMagicLink,+ oAuthSSOProviders,+ },+ enableOIDC: authEnv.ENABLE_OIDC,+ featureFlags: getServerFeatureFlagsValue(),+ globalCDN: appEnv.CDN_USE_GLOBAL,+ },+ {+ headers: {+ 'Cache-Control': 'public, max-age=0, s-maxage=60, stale-while-revalidate=600',+ },+ },+ );+};diff --git a/vitest.config.mts b/vitest.config.mtsindex 53496c0503d..d0c621ec509 100644--- a/vitest.config.mts+++ b/vitest.config.mts@@ -32,6 +32,9 @@ const alias = {'@/utils/errorResponse': resolve(__dirname, './src/utils/errorResponse'),'@/utils/unzipFile': resolve(__dirname, './src/utils/unzipFile'),'@/utils/server': resolve(__dirname, './src/utils/server'),+ // apps/auth sits outside the root tsconfig's include, so its files get no path+ // mapping from tsconfigPaths β pin the one server util its worker shares.+ '@/server/utils/serializeForHtml': resolve(__dirname, './apps/server/src/utils/serializeForHtml'),'@/utils/identifier': resolve(__dirname, './src/utils/identifier'),'@/utils/electron': resolve(__dirname, './src/utils/electron'),'@/utils/markdownToTxt': resolve(__dirname, './src/utils/markdownToTxt'),