Let's use AI to Earn!
TypeScript auto-publishdouyindouyin-apielectron-appelectron-reactkuaishoukwaipublishedshipinhaotoolxiaohongshu
feat: auto-login via init service and remove Docker build-arg env vars
Sakurab3af2eff5ef6
diff --git a/docker-compose.yml b/docker-compose.ymlindex 436f10bb..16351294 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -62,6 +62,26 @@ services:retries: 5start_period: 30s+ aitoearn-init:+ image: node:lts-alpine+ container_name: aitoearn-init+ depends_on:+ mongodb:+ condition: service_healthy+ volumes:+ - ./scripts/init.mjs:/app/init.mjs:ro+ - ./scripts/init-package.json:/app/package.json:ro+ - init-data:/data/init+ working_dir: /app+ environment:+ MONGO_URI: mongodb://admin:password@mongodb:27017+ JWT_SECRET: change-this-jwt-secret+ DB_NAME: aitoearn+ AUTO_LOGIN_TOKEN_PATH: /data/init/token.txt+ entrypoint: /bin/sh -c "npm install --omit=dev 2>/dev/null && node init.mjs"+ networks:+ - aitoearn-network+rustfs-init:image: minio/mc:latestcontainer_name: aitoearn-rustfs-init@@ -238,12 +258,14 @@ services:depends_on:aitoearn-server:condition: service_healthy+ volumes:+ - init-data:/data/init:ronetworks:- aitoearn-networkenvironment:NODE_ENV: productionNEXT_TELEMETRY_DISABLED: 1- NEXT_PUBLIC_API_URL: http://localhost:8080/api+ AUTO_LOGIN_TOKEN_PATH: /data/init/token.txtnginx:image: nginx:alpine@@ -283,3 +305,5 @@ volumes:driver: localrustfs-data:driver: local+ init-data:+ driver: localdiff --git a/nginx/nginx.conf b/nginx/nginx.confindex b165612f..40719b3a 100644--- a/nginx/nginx.conf+++ b/nginx/nginx.conf@@ -92,6 +92,10 @@ http {proxy_pass http://aitoearn-server:3002;}+ location /oss/ {+ proxy_pass http://aitoearn-rustfs:9000/aitoearn/;+ }+location / {proxy_pass http://aitoearn-web:3000;}diff --git a/project/aitoearn-web/.env b/project/aitoearn-web/.envindex dabadc3f..025b23e9 100644--- a/project/aitoearn-web/.env+++ b/project/aitoearn-web/.env@@ -1,5 +1,8 @@-# OSS URL-NEXT_PUBLIC_OSS_URL="https://assets.aitoearn.ai/"+# API URL+NEXT_PUBLIC_API_URL="/api"++# OSS URL(自部署通过 nginx 代理到本地 rustfs)+NEXT_PUBLIC_OSS_URL="/oss/"# OSS URL 代理NEXT_PUBLIC_OSS_URL_PROXY="/ossProxy/"diff --git a/project/aitoearn-web/.env.production b/project/aitoearn-web/.env.productionindex ef5273c0..41486de4 100644--- a/project/aitoearn-web/.env.production+++ b/project/aitoearn-web/.env.production@@ -1,4 +1 @@NEXT_PUBLIC_EVN=prod--# NEXT_PUBLIC_API_URL / NEXT_PUBLIC_HOST_URL / NEXT_PUBLIC_OSS_URL-# 由 Dockerfile 构建参数注入,不在此处硬编码,避免覆盖 Docker ENVdiff --git a/project/aitoearn-web/.github/workflows/deploy.yml b/project/aitoearn-web/.github/workflows/deploy.ymlindex 9dae6360..8259c69d 100644--- a/project/aitoearn-web/.github/workflows/deploy.yml+++ b/project/aitoearn-web/.github/workflows/deploy.yml@@ -15,14 +15,6 @@ on:required: falsetype: stringdefault: linux/amd64- environment:- description: 部署环境- required: false- type: choice- options:- - dev- - prod- default: prodpermissions:contents: read@@ -71,20 +63,6 @@ jobs:fiecho "version=$VERSION" >> $GITHUB_OUTPUT- - name: Set environment URLs- id: env-urls- run: |- ENV="${{ github.event.inputs.environment || 'prod' }}"- if [ "$ENV" = "dev" ]; then- echo "host_url=https://dev.aitoearn.ai" >> $GITHUB_OUTPUT- echo "oss_url=https://assets.dev.aitoearn.ai/" >> $GITHUB_OUTPUT- echo "base_api=https://dev.aitoearn.ai/api" >> $GITHUB_OUTPUT- else- echo "host_url=https://aitoearn.ai" >> $GITHUB_OUTPUT- echo "oss_url=https://assets.aitoearn.ai/" >> $GITHUB_OUTPUT- echo "base_api=https://aitoearn.ai/api" >> $GITHUB_OUTPUT- fi-- name: Build and push to Fly.io registryuses: docker/build-push-action@v5with:@@ -93,12 +71,8 @@ jobs:platforms: ${{ github.event.inputs.architectures }}push: truetags: ${{ env.FLY_REGISTRY }}/${{ env.APP_NAME }}:${{ steps.version.outputs.version }}- build-args: |- NEXT_PUBLIC_HOST_URL=${{ steps.env-urls.outputs.host_url }}- NEXT_PUBLIC_OSS_URL=${{ steps.env-urls.outputs.oss_url }}- NEXT_PUBLIC_API_URL=${{ steps.env-urls.outputs.base_api }}- cache-from: type=gha,scope=fly-${{ github.event.inputs.environment || 'prod' }}- cache-to: type=gha,mode=max,scope=fly-${{ github.event.inputs.environment || 'prod' }}+ cache-from: type=gha,scope=fly-prod+ cache-to: type=gha,mode=max,scope=fly-prod- name: Build and push to private registryuses: docker/build-push-action@v5@@ -108,12 +82,8 @@ jobs:platforms: ${{ github.event.inputs.architectures }}push: truetags: ${{ env.DOCKER_REGISTRY }}/${{ env.APP_NAME }}:${{ steps.version.outputs.version }}- build-args: |- NEXT_PUBLIC_HOST_URL=${{ steps.env-urls.outputs.host_url }}- NEXT_PUBLIC_OSS_URL=${{ steps.env-urls.outputs.oss_url }}- NEXT_PUBLIC_API_URL=${{ steps.env-urls.outputs.base_api }}- cache-from: type=gha,scope=private-${{ github.event.inputs.environment || 'prod' }}- cache-to: type=gha,mode=max,scope=private-${{ github.event.inputs.environment || 'prod' }}+ cache-from: type=gha,scope=private-prod+ cache-to: type=gha,mode=max,scope=private-prod- name: Build summaryrun: |echo "### ✅ 构建成功: ${{ env.APP_NAME }}" >> $GITHUB_STEP_SUMMARY@@ -157,7 +127,7 @@ jobs:const repo = '${{ env.INFRASTRUCTURE_REPO }}';const apps = ${{ steps.build-apps-json.outputs.apps_json }};const branch = '${{ github.ref_name }}';- const environment = '${{ github.event.inputs.environment }}' || 'prod';+ const environment = 'prod';await github.rest.repos.createDispatchEvent({owner: owner,@@ -188,7 +158,7 @@ jobs:echo "## 🚀 已触发部署" >> $GITHUB_STEP_SUMMARYecho "" >> $GITHUB_STEP_SUMMARYecho "- **分支**: ${{ github.ref_name }}" >> $GITHUB_STEP_SUMMARY- echo "- **环境**: ${{ github.event.inputs.environment || 'prod' }}" >> $GITHUB_STEP_SUMMARY+ echo "- **环境**: prod" >> $GITHUB_STEP_SUMMARYecho "- **提交**: [\`${{ github.sha }}\`](${{ github.server_url }}/${{ github.repository }}/commit/${{ github.sha }})" >> $GITHUB_STEP_SUMMARYecho "- **部署目标**: ${{ env.INFRASTRUCTURE_REPO }}" >> $GITHUB_STEP_SUMMARYecho "- **应用**: ${{ env.APP_NAME }}" >> $GITHUB_STEP_SUMMARYdiff --git a/project/aitoearn-web/Dockerfile b/project/aitoearn-web/Dockerfileindex 669e2139..e5517b08 100644--- a/project/aitoearn-web/Dockerfile+++ b/project/aitoearn-web/Dockerfile@@ -17,13 +17,6 @@ RUN pnpm install --frozen-lockfile --prod=falseFROM base AS builderWORKDIR /app-ARG NEXT_PUBLIC_HOST_URL-ARG NEXT_PUBLIC_OSS_URL-ARG NEXT_PUBLIC_API_URL-ENV NEXT_PUBLIC_HOST_URL=$NEXT_PUBLIC_HOST_URL-ENV NEXT_PUBLIC_OSS_URL=$NEXT_PUBLIC_OSS_URL-ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL-COPY --from=deps /app/node_modules ./node_modulesCOPY . .diff --git a/project/aitoearn-web/next-sitemap.config.js b/project/aitoearn-web/next-sitemap.config.jsindex f84bfd78..4954b6f1 100644--- a/project/aitoearn-web/next-sitemap.config.js+++ b/project/aitoearn-web/next-sitemap.config.js@@ -6,7 +6,7 @@ const { HREFLANG_MAP, languages } = require('./src/lib/i18n/hreflangMap.cjs')const BLOCKLIST_REGEX = /material\/album\/\[id\]/const HAS_DYNAMIC_SEGMENT = /\[[^/]+?\]/-const siteUrl = process.env.NEXT_PUBLIC_HOST_URL || 'https://aitoearn.ai'+const siteUrl = 'https://aitoearn.ai'// 生成多语言alternateRefs(每个语言的根 URL)const alternateRefs = languages.map(lang => ({diff --git a/project/aitoearn-web/src/app/[lng]/(welcome)/welcome/page.tsx b/project/aitoearn-web/src/app/[lng]/(welcome)/welcome/page.tsxindex 16607f37..57b2c363 100644--- a/project/aitoearn-web/src/app/[lng]/(welcome)/welcome/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/(welcome)/welcome/page.tsx@@ -6,7 +6,7 @@import type { Metadata } from 'next'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/general'+import { getMetadata } from '@/utils/server-general'import WelcomePageContent from './WelcomePageContent'// SEO 元数据diff --git a/project/aitoearn-web/src/app/[lng]/accounts/page.tsx b/project/aitoearn-web/src/app/[lng]/accounts/page.tsxindex c44f1a54..a14a3ac9 100644--- a/project/aitoearn-web/src/app/[lng]/accounts/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/accounts/page.tsx@@ -1,7 +1,7 @@import type { PageParams } from '@/app/globals'import AccountPageCore from '@/app/[lng]/accounts/accountCore'import { useTranslation } from '@/app/i18n'-import { getMetadata } from '@/utils/general'+import { getMetadata } from '@/utils/server-general'export async function generateMetadata({ params }: PageParams) {const { lng } = await paramsdiff --git a/project/aitoearn-web/src/app/[lng]/ai-social/page.tsx b/project/aitoearn-web/src/app/[lng]/ai-social/page.tsxindex d1acd27f..1519f76f 100644--- a/project/aitoearn-web/src/app/[lng]/ai-social/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/ai-social/page.tsx@@ -5,7 +5,7 @@import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/general'+import { getMetadata } from '@/utils/server-general'import { AiSocialPageContent } from './AiSocialPageContent'// SEO 元数据diff --git a/project/aitoearn-web/src/app/[lng]/auth/login/page.tsx b/project/aitoearn-web/src/app/[lng]/auth/login/page.tsxindex b4d936ec..dcef6746 100644--- a/project/aitoearn-web/src/app/[lng]/auth/login/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/auth/login/page.tsx@@ -6,7 +6,7 @@import type { Metadata } from 'next'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/general'+import { getMetadata } from '@/utils/server-general'import LoginContent from './components/LoginContent'// SEO 元数据diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/page.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/page.tsxindex d74bcb33..da8b5b69 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/draft-box/page.tsx@@ -6,7 +6,7 @@import dynamic from 'next/dynamic'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/lib/i18n/languageConfig'-import { getMetadata } from '@/utils/general'+import { getMetadata } from '@/utils/server-general'interface PageParams {params: Promise<{ lng: string }>diff --git a/project/aitoearn-web/src/app/[lng]/layout.tsx b/project/aitoearn-web/src/app/[lng]/layout.tsxindex 641813ce..4107b533 100644--- a/project/aitoearn-web/src/app/[lng]/layout.tsx+++ b/project/aitoearn-web/src/app/[lng]/layout.tsx@@ -9,6 +9,7 @@ import MobileNav from '@/app/layout/MobileNav'import { ChannelManager } from '@/components/ChannelManager'import { StructuredData } from '@/components/SEO/StructuredData'import { getHreflang } from '@/lib/i18n/languageConfig'+import { getBaseUrl } from '@/utils/server-general'import { Providers } from '../layout/Providers'import '@/app/var.css'import '../globals.css'@@ -19,7 +20,7 @@ export async function generateMetadata({ params }: { params: Promise<{ lng: strilng = fallbackLngconst { t } = await useTranslation(lng)- const baseUrl = process.env.NEXT_PUBLIC_HOST_URL || 'https://aitoearn.ai'+ const baseUrl = await getBaseUrl()// 生成hreflang链接const alternateRefs = languages.map(lang => ({@@ -51,7 +52,7 @@ export default async function RootLayout({params: Promise<{ lng: string }>}>) {const { lng } = await params- const baseUrl = process.env.NEXT_PUBLIC_HOST_URL || 'https://aitoearn.ai'+ const baseUrl = await getBaseUrl()return (<html lang={lng} dir={dir(lng)} suppressHydrationWarning>diff --git a/project/aitoearn-web/src/app/[lng]/material/agent-assets/page.tsx b/project/aitoearn-web/src/app/[lng]/material/agent-assets/page.tsxindex 0718a427..046145f9 100644--- a/project/aitoearn-web/src/app/[lng]/material/agent-assets/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/material/agent-assets/page.tsx@@ -6,7 +6,7 @@import type { Metadata } from 'next'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/general'+import { getMetadata } from '@/utils/server-general'import { AgentAssetsPageCore } from './agentAssetsPageCore'export async function generateMetadata({diff --git a/project/aitoearn-web/src/app/[lng]/material/page.tsx b/project/aitoearn-web/src/app/[lng]/material/page.tsxindex cc7510c9..1faca2cf 100644--- a/project/aitoearn-web/src/app/[lng]/material/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/material/page.tsx@@ -2,7 +2,7 @@ import type { PageParams } from '@/app/globals'import * as React from 'react'import { MaterialPageCore } from '@/app/[lng]/material/materialPageCore'import { useTranslation } from '@/app/i18n'-import { getMetadata } from '@/utils/general'+import { getMetadata } from '@/utils/server-general'export async function generateMetadata({ params }: PageParams) {const { lng } = await paramsdiff --git a/project/aitoearn-web/src/app/[lng]/promo/[code]/page.tsx b/project/aitoearn-web/src/app/[lng]/promo/[code]/page.tsxindex 6d0b8604..e71b135a 100644--- a/project/aitoearn-web/src/app/[lng]/promo/[code]/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/promo/[code]/page.tsx@@ -6,7 +6,7 @@import type { Metadata } from 'next'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/general'+import { getMetadata } from '@/utils/server-general'import PromoPageCore from './promoPageCore'// 生成 SEO 元数据diff --git a/project/aitoearn-web/src/app/[lng]/promo/page.tsx b/project/aitoearn-web/src/app/[lng]/promo/page.tsxindex 5a650013..453439bd 100644--- a/project/aitoearn-web/src/app/[lng]/promo/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/promo/page.tsx@@ -6,7 +6,7 @@import type { Metadata } from 'next'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/general'+import { getMetadata } from '@/utils/server-general'import PromoCallbackCore from './promoCallbackCore'// 生成 SEO 元数据diff --git a/project/aitoearn-web/src/app/[lng]/websit/data-deletion/page.tsx b/project/aitoearn-web/src/app/[lng]/websit/data-deletion/page.tsxindex 18cbc479..9eb0a5c8 100644--- a/project/aitoearn-web/src/app/[lng]/websit/data-deletion/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/websit/data-deletion/page.tsx@@ -5,7 +5,7 @@import type { Metadata } from 'next'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/general'+import { getMetadata } from '@/utils/server-general'import styles from '../websit.module.scss'export async function generateMetadata({diff --git a/project/aitoearn-web/src/app/[lng]/websit/data-protection-agreement/page.tsx b/project/aitoearn-web/src/app/[lng]/websit/data-protection-agreement/page.tsxindex ddd34248..7e05e1f8 100644--- a/project/aitoearn-web/src/app/[lng]/websit/data-protection-agreement/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/websit/data-protection-agreement/page.tsx@@ -5,7 +5,7 @@import type { Metadata } from 'next'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/general'+import { getMetadata } from '@/utils/server-general'import DataProtectionContent from './DataProtectionContent'export async function generateMetadata({diff --git a/project/aitoearn-web/src/app/[lng]/websit/extension-privacy-policy/page.tsx b/project/aitoearn-web/src/app/[lng]/websit/extension-privacy-policy/page.tsxindex cfa238f6..a6c4483b 100644--- a/project/aitoearn-web/src/app/[lng]/websit/extension-privacy-policy/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/websit/extension-privacy-policy/page.tsx@@ -5,7 +5,7 @@import type { Metadata } from 'next'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/general'+import { getMetadata } from '@/utils/server-general'import styles from '../websit.module.scss'export async function generateMetadata({diff --git a/project/aitoearn-web/src/app/[lng]/websit/plugin-guide/page.tsx b/project/aitoearn-web/src/app/[lng]/websit/plugin-guide/page.tsxindex 2d09e532..e3518458 100644--- a/project/aitoearn-web/src/app/[lng]/websit/plugin-guide/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/websit/plugin-guide/page.tsx@@ -5,7 +5,7 @@import type { Metadata } from 'next'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/general'+import { getMetadata } from '@/utils/server-general'import PluginGuideContent from './PluginGuideContent'export async function generateMetadata({diff --git a/project/aitoearn-web/src/app/[lng]/websit/privacy-policy/page.tsx b/project/aitoearn-web/src/app/[lng]/websit/privacy-policy/page.tsxindex 27e365bc..0bc20c5d 100644--- a/project/aitoearn-web/src/app/[lng]/websit/privacy-policy/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/websit/privacy-policy/page.tsx@@ -5,7 +5,7 @@import type { Metadata } from 'next'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/general'+import { getMetadata } from '@/utils/server-general'import styles from '../websit.module.scss'export async function generateMetadata({diff --git a/project/aitoearn-web/src/app/[lng]/websit/terms-of-service/page.tsx b/project/aitoearn-web/src/app/[lng]/websit/terms-of-service/page.tsxindex 42b70432..5db67bb6 100644--- a/project/aitoearn-web/src/app/[lng]/websit/terms-of-service/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/websit/terms-of-service/page.tsx@@ -5,7 +5,7 @@import type { Metadata } from 'next'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/general'+import { getMetadata } from '@/utils/server-general'import styles from '../websit.module.scss'export async function generateMetadata({diff --git a/project/aitoearn-web/src/app/api/auto-login/route.ts b/project/aitoearn-web/src/app/api/auto-login/route.tsnew file mode 100644index 00000000..445daea0--- /dev/null+++ b/project/aitoearn-web/src/app/api/auto-login/route.ts@@ -0,0 +1,17 @@+/**+ * auto-login API Route - 读取 init 服务生成的自动登录 token+ */++import { readFileSync } from 'fs'+import { NextResponse } from 'next/server'++export function GET() {+ const tokenPath = process.env.AUTO_LOGIN_TOKEN_PATH+ if (!tokenPath) return NextResponse.json({ token: null })+ try {+ const token = readFileSync(tokenPath, 'utf-8').trim()+ return NextResponse.json({ token })+ } catch {+ return NextResponse.json({ token: null })+ }+}diff --git a/project/aitoearn-web/src/lib/server-fetch.ts b/project/aitoearn-web/src/lib/server-fetch.tsindex e01de2cb..367ba8e1 100644--- a/project/aitoearn-web/src/lib/server-fetch.ts+++ b/project/aitoearn-web/src/lib/server-fetch.ts@@ -4,6 +4,8 @@* 无客户端依赖(不使用 useUserStore、directTrans)*/+import { headers } from 'next/headers'+interface ServerFetchOptions {revalidate?: number | falsetags?: string[]@@ -15,14 +17,16 @@ interface ApiResponse<T> {message: string}-function getBaseUrl() {- // 生产环境 NEXT_PUBLIC_API_URL 是 /api(相对路径),SSR 需要完整 URL+async function getApiBaseUrl() {const apiUrl = process.env.NEXT_PUBLIC_API_URL || '/api'if (apiUrl.startsWith('http')) {return apiUrl}- const hostUrl = process.env.NEXT_PUBLIC_HOST_URL || 'https://aitoearn.ai'- return `${hostUrl}${apiUrl}`+ // 相对路径时,从请求 headers 中获取 host 拼接完整 URL+ const h = await headers()+ const host = h.get('host') || 'localhost:3000'+ const proto = h.get('x-forwarded-proto') || 'http'+ return `${proto}://${host}${apiUrl}`}/**@@ -35,7 +39,7 @@ export async function serverFetch<T>(options: ServerFetchOptions = {},): Promise<ApiResponse<T> | null> {try {- const baseUrl = getBaseUrl()+ const baseUrl = await getApiBaseUrl()const url = new URL(`${baseUrl}/${path}`)if (params) {diff --git a/project/aitoearn-web/src/store/user.ts b/project/aitoearn-web/src/store/user.tsindex 4eb6756f..55338c48 100644--- a/project/aitoearn-web/src/store/user.ts+++ b/project/aitoearn-web/src/store/user.ts@@ -78,7 +78,15 @@ export const useUserStore = createPersistStore(set({ userInfo })},- appInit() {+ async appInit() {+ // 自动登录:从 init 服务生成的 token 文件中获取+ if (!_get().token) {+ try {+ const res = await fetch('/api/auto-login')+ const data = await res.json()+ if (data.token) methods.setToken(data.token)+ } catch {}+ }methods.getUserInfo()useAccountStore.getState().accountInit()},diff --git a/project/aitoearn-web/src/utils/general.ts b/project/aitoearn-web/src/utils/general.tsindex 4887a6cc..24e3ae6b 100644--- a/project/aitoearn-web/src/utils/general.ts+++ b/project/aitoearn-web/src/utils/general.ts@@ -1,92 +1,7 @@-import type { Metadata } from 'next'-import { getHreflang, languages } from '@/lib/i18n/languageConfig'-export async function getPageTitle(name: string, lng: string) {return `${name} —— AiToEarn`}-/**- * 生成页面 Metadata(符合 SEO 最佳实践)- * @param props - 基础 Metadata 配置- * @param lng - 当前语言- * @param path - 页面路径(不含语言前缀),如 '/accounts'- */-export async function getMetadata(props: Metadata, lng: string, path?: string): Promise<Metadata> {- path = path || '/'-- const baseUrl = process.env.NEXT_PUBLIC_HOST_URL || 'https://aitoearn.ai'-- const title = await getPageTitle(typeof props.title === 'string' ? props.title : '', lng)-- const description = typeof props.description === 'string' ? props.description : ''-- // 生成所有语言的 alternate links(用于 hreflang)- const languageAlternates = languages.reduce(- (acc, lang) => {- // 使用 x-default 作为默认语言的 hreflang- const hreflang = lang === 'en' ? 'x-default' : getHreflang(lang)- acc[hreflang] = `${baseUrl}/${lang}${path}`- return acc- },- {} as Record<string, string>,- )-- // 默认的 OG 图片- const defaultOgImage = `${baseUrl}/og-image.png`-- return {- ...props,- title,- description,- keywords: props.keywords,- referrer: 'no-referrer',- // Canonical URL 和 alternate links- alternates: {- canonical: `${baseUrl}/${lng}${path}`,- languages: languageAlternates,- ...props.alternates,- },- // OpenGraph 元数据(社交媒体分享)- openGraph: {- title,- description,- url: `${baseUrl}/${lng}${path}`,- siteName: 'AiToEarn',- locale: lng,- type: 'website',- images: [- {- url: defaultOgImage,- width: 1200,- height: 630,- alt: title,- },- ],- ...props.openGraph,- },- // Twitter Card 元数据- twitter: {- card: 'summary_large_image',- title,- description,- images: [defaultOgImage],- ...props.twitter,- },- // 搜索引擎爬虫指令- robots: props.robots || {- index: true,- follow: true,- googleBot: {- 'index': true,- 'follow': true,- 'max-video-preview': -1,- 'max-image-preview': 'large',- 'max-snippet': -1,- },- },- }-}-export function sleep(ms: number) {return new Promise(resolve => setTimeout(resolve, ms))}diff --git a/project/aitoearn-web/src/utils/server-general.ts b/project/aitoearn-web/src/utils/server-general.tsnew file mode 100644index 00000000..8bac88cd--- /dev/null+++ b/project/aitoearn-web/src/utils/server-general.ts@@ -0,0 +1,98 @@+/**+ * server-general - 服务端专用工具函数+ * 仅在 Server Component / generateMetadata 中使用,不可被客户端组件引用+ */++import type { Metadata } from 'next'+import { headers } from 'next/headers'+import { getHreflang, languages } from '@/lib/i18n/languageConfig'+import { getPageTitle } from '@/utils/general'++export async function getBaseUrl() {+ const h = await headers()+ const host = h.get('host') || 'localhost:3000'+ const proto = h.get('x-forwarded-proto') || 'http'+ return `${proto}://${host}`+}++/**+ * 生成页面 Metadata(符合 SEO 最佳实践)+ * @param props - 基础 Metadata 配置+ * @param lng - 当前语言+ * @param path - 页面路径(不含语言前缀),如 '/accounts'+ */+export async function getMetadata(props: Metadata, lng: string, path?: string): Promise<Metadata> {+ path = path || '/'++ const baseUrl = await getBaseUrl()++ const title = await getPageTitle(typeof props.title === 'string' ? props.title : '', lng)++ const description = typeof props.description === 'string' ? props.description : ''++ // 生成所有语言的 alternate links(用于 hreflang)+ const languageAlternates = languages.reduce(+ (acc, lang) => {+ // 使用 x-default 作为默认语言的 hreflang+ const hreflang = lang === 'en' ? 'x-default' : getHreflang(lang)+ acc[hreflang] = `${baseUrl}/${lang}${path}`+ return acc+ },+ {} as Record<string, string>,+ )++ // 默认的 OG 图片+ const defaultOgImage = `${baseUrl}/og-image.png`++ return {+ ...props,+ title,+ description,+ keywords: props.keywords,+ referrer: 'no-referrer',+ // Canonical URL 和 alternate links+ alternates: {+ canonical: `${baseUrl}/${lng}${path}`,+ languages: languageAlternates,+ ...props.alternates,+ },+ // OpenGraph 元数据(社交媒体分享)+ openGraph: {+ title,+ description,+ url: `${baseUrl}/${lng}${path}`,+ siteName: 'AiToEarn',+ locale: lng,+ type: 'website',+ images: [+ {+ url: defaultOgImage,+ width: 1200,+ height: 630,+ alt: title,+ },+ ],+ ...props.openGraph,+ },+ // Twitter Card 元数据+ twitter: {+ card: 'summary_large_image',+ title,+ description,+ images: [defaultOgImage],+ ...props.twitter,+ },+ // 搜索引擎爬虫指令+ robots: props.robots || {+ index: true,+ follow: true,+ googleBot: {+ 'index': true,+ 'follow': true,+ 'max-video-preview': -1,+ 'max-image-preview': 'large',+ 'max-snippet': -1,+ },+ },+ }+}diff --git a/scripts/build.sh b/scripts/build.shindex 14f73a90..1627168e 100755--- a/scripts/build.sh+++ b/scripts/build.sh@@ -27,7 +27,6 @@ echo "=== Building frontend image ==="cd "$PROJECT_ROOT/project/aitoearn-web"docker build \- --build-arg NEXT_PUBLIC_API_URL=http://localhost:8080/api \-t aitoearn/aitoearn-web:latest .echo "=== All images built successfully ==="diff --git a/scripts/init-package.json b/scripts/init-package.jsonnew file mode 100644index 00000000..ed360671--- /dev/null+++ b/scripts/init-package.json@@ -0,0 +1,7 @@+{+ "type": "module",+ "dependencies": {+ "mongodb": "~6.20.0",+ "jsonwebtoken": "^9.0.3"+ }+}diff --git a/scripts/init.mjs b/scripts/init.mjsnew file mode 100644index 00000000..834b2e39--- /dev/null+++ b/scripts/init.mjs@@ -0,0 +1,87 @@+/**+ * 初始化脚本 - 创建默认用户并生成自动登录 token+ * 通过 docker-compose aitoearn-init 服务运行+ */++import { MongoClient } from 'mongodb'+import jwt from 'jsonwebtoken'+import { writeFileSync, mkdirSync } from 'fs'+import { dirname } from 'path'+import crypto from 'crypto'++const MONGO_URI = process.env.MONGO_URI || 'mongodb://admin:password@mongodb:27017'+const JWT_SECRET = process.env.JWT_SECRET || 'change-this-jwt-secret'+const DB_NAME = process.env.DB_NAME || 'aitoearn'+const TOKEN_PATH = process.env.AUTO_LOGIN_TOKEN_PATH || '/data/init/token.txt'+const DEFAULT_EMAIL = '[email protected]'++async function main() {+ const client = new MongoClient(MONGO_URI)+ await client.connect()+ console.log('Connected to MongoDB')++ const db = client.db(DB_NAME)+ const users = db.collection('users')++ let user = await users.findOne({ mail: DEFAULT_EMAIL, isDelete: { $ne: true } })++ if (!user) {+ const now = new Date()+ const result = await users.insertOne({+ name: 'Admin',+ mail: DEFAULT_EMAIL,+ status: 1,+ userType: 'CREATOR',+ isDelete: false,+ score: 0,+ usedStorage: 0,+ storage: { total: 524288000 },+ locale: 'en-US',+ createdAt: now,+ updatedAt: now,+ })+ user = { _id: result.insertedId, mail: DEFAULT_EMAIL, name: 'Admin' }++ // 生成 popularizeCode(复用后端算法)+ const identifier = DEFAULT_EMAIL+ const phoneHash = crypto+ .createHash('sha256')+ .update(identifier)+ .digest('hex')+ .substring(0, 16)+ const combinedSalt = `aitoearn${phoneHash}`+ const hash = crypto+ .createHash('sha256')+ .update(user._id.toString())+ .update(combinedSalt)+ .digest('hex')+ const numericValue = parseInt(hash.substring(0, 6), 16)+ const code = numericValue+ .toString(36)+ .slice(-5)+ .toUpperCase()+ .padStart(5, '0')++ await users.updateOne({ _id: user._id }, { $set: { popularizeCode: code } })+ console.log(`Created default user: ${DEFAULT_EMAIL}`)+ } else {+ console.log(`Found existing user: ${DEFAULT_EMAIL}`)+ }++ const token = jwt.sign(+ { id: user._id.toString(), mail: user.mail, name: user.name },+ JWT_SECRET,+ { expiresIn: '100y' },+ )++ mkdirSync(dirname(TOKEN_PATH), { recursive: true })+ writeFileSync(TOKEN_PATH, token)+ console.log(`Token written to ${TOKEN_PATH}`)++ await client.close()+}++main().catch((e) => {+ console.error(e)+ process.exit(1)+})