fix: harden portal routing, API transport and admin builds on test14
This commit is contained in:
parent
21f44059e4
commit
83d00822dc
@ -1,5 +1,7 @@
|
|||||||
# Nomadro
|
# Nomadro
|
||||||
|
|
||||||
|
2026-11-09:`test13` 收尾后切换 `test14`,仅优化门户/后端/后台功能与构建,不调整前端视觉、不部署生产。修复首页重写循环、迁移 Next.js 16 `proxy`、统一本地 `.com` API/配置默认值、修复 Strict Mode 埋点监听及后台请求异常处理、为共享 PocketBase 凭证增加并发保护与一次 401 恢复,并修复 `.cn` 后台构建类型冲突。范围与验证见 [test14 开发记录](docs/test14-development.md)。
|
||||||
|
|
||||||
2026-11-08:远程工作门禁 + Work UX + 语言水合修复并部署 `.com` — `/social/work` 未加入社区不可用(登录/注册/补资料,与约会同门禁);Pads/Boards 增强(收藏复制删除、专注预览快捷键、看板筛选模板);`LocaleProvider`/`LanguageSwitcher` 首帧固定 zh 消除 hydration mismatch;反馈页英文短语补全。本地构建上传门户 `.next` + `admin.nomadro.com` + API/social;`.cn` 未同步。
|
2026-11-08:远程工作门禁 + Work UX + 语言水合修复并部署 `.com` — `/social/work` 未加入社区不可用(登录/注册/补资料,与约会同门禁);Pads/Boards 增强(收藏复制删除、专注预览快捷键、看板筛选模板);`LocaleProvider`/`LanguageSwitcher` 首帧固定 zh 消除 hydration mismatch;反馈页英文短语补全。本地构建上传门户 `.next` + `admin.nomadro.com` + API/social;`.cn` 未同步。
|
||||||
|
|
||||||
2026-11-07:Work Pads 深度定制(Etherpad 域模型 → Next 原生)— `/social/work/pads`:作者色条、行号、在场名单、侧栏聊天、时间轴浏览/还原、冲突提示、导入导出、Ctrl/⌘+S、删除;API `presence`/`chat`/`DELETE` + Welcome pad;work 服务补 PocketBase 鉴权。无 iframe。
|
2026-11-07:Work Pads 深度定制(Etherpad 域模型 → Next 原生)— `/social/work/pads`:作者色条、行号、在场名单、侧栏聊天、时间轴浏览/还原、冲突提示、导入导出、Ctrl/⌘+S、删除;API `presence`/`chat`/`DELETE` + Welcome pad;work 服务补 PocketBase 鉴权。无 iframe。
|
||||||
|
|||||||
@ -125,6 +125,7 @@ export default function NavAdmin() {
|
|||||||
const group = cat?.groups?.[groupIdx]
|
const group = cat?.groups?.[groupIdx]
|
||||||
|
|
||||||
function moveCat(from: number, to: number) {
|
function moveCat(from: number, to: number) {
|
||||||
|
if (!nav) return
|
||||||
if (to < 0 || to >= nav.categories.length) return
|
if (to < 0 || to >= nav.categories.length) return
|
||||||
const cats = [...nav.categories]
|
const cats = [...nav.categories]
|
||||||
const [item] = cats.splice(from, 1)
|
const [item] = cats.splice(from, 1)
|
||||||
@ -134,6 +135,7 @@ export default function NavAdmin() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function moveGroup(from: number, to: number) {
|
function moveGroup(from: number, to: number) {
|
||||||
|
if (!nav) return
|
||||||
if (!cat || to < 0 || to >= cat.groups.length) return
|
if (!cat || to < 0 || to >= cat.groups.length) return
|
||||||
const groups = [...cat.groups]
|
const groups = [...cat.groups]
|
||||||
const [item] = groups.splice(from, 1)
|
const [item] = groups.splice(from, 1)
|
||||||
@ -144,6 +146,7 @@ export default function NavAdmin() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function moveLink(from: number, to: number) {
|
function moveLink(from: number, to: number) {
|
||||||
|
if (!nav) return
|
||||||
if (!cat || !group || to < 0 || to >= group.links.length) return
|
if (!cat || !group || to < 0 || to >= group.links.length) return
|
||||||
const links = [...group.links]
|
const links = [...group.links]
|
||||||
const [item] = links.splice(from, 1)
|
const [item] = links.splice(from, 1)
|
||||||
@ -558,7 +561,7 @@ export default function NavAdmin() {
|
|||||||
<select
|
<select
|
||||||
value={link.action || 'open'}
|
value={link.action || 'open'}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const action = e.target.value === 'copy' ? 'copy' : 'open'
|
const action: 'copy' | 'open' = e.target.value === 'copy' ? 'copy' : 'open'
|
||||||
const links = group.links.map((l, j) =>
|
const links = group.links.map((l, j) =>
|
||||||
j === li ? { ...l, action } : l,
|
j === li ? { ...l, action } : l,
|
||||||
)
|
)
|
||||||
|
|||||||
@ -11,7 +11,10 @@
|
|||||||
"isolatedModules": true,
|
"isolatedModules": true,
|
||||||
"noEmit": true,
|
"noEmit": true,
|
||||||
"jsx": "react-jsx",
|
"jsx": "react-jsx",
|
||||||
"strict": true
|
"strict": true,
|
||||||
|
"paths": {
|
||||||
|
"react": ["./node_modules/@types/react/index.d.ts"]
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"include": ["src"]
|
"include": ["src"]
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,6 +2,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
import threading
|
||||||
import time
|
import time
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@ -34,11 +35,14 @@ class PocketBaseClient:
|
|||||||
self._admin_token: str | None = None
|
self._admin_token: str | None = None
|
||||||
self._token_at = 0.0
|
self._token_at = 0.0
|
||||||
self._client: httpx.Client | None = None
|
self._client: httpx.Client | None = None
|
||||||
|
self._http_lock = threading.Lock()
|
||||||
|
self._auth_lock = threading.Lock()
|
||||||
|
|
||||||
def _http(self) -> httpx.Client:
|
def _http(self) -> httpx.Client:
|
||||||
if self._client is None:
|
with self._http_lock:
|
||||||
self._client = httpx.Client(timeout=25.0, trust_env=False)
|
if self._client is None:
|
||||||
return self._client
|
self._client = httpx.Client(timeout=25.0, trust_env=False)
|
||||||
|
return self._client
|
||||||
|
|
||||||
def request(
|
def request(
|
||||||
self,
|
self,
|
||||||
@ -54,6 +58,15 @@ class PocketBaseClient:
|
|||||||
headers["Authorization"] = self.admin_token()
|
headers["Authorization"] = self.admin_token()
|
||||||
url = f"{self.base_url}{path}"
|
url = f"{self.base_url}{path}"
|
||||||
res = self._http().request(method, url, headers=headers, json=json, params=params)
|
res = self._http().request(method, url, headers=headers, json=json, params=params)
|
||||||
|
# A rejected credential did not authorize the operation. Refresh once;
|
||||||
|
# never replay timeouts, 5xx responses or transport failures for writes.
|
||||||
|
if admin and res.status_code == 401:
|
||||||
|
with self._auth_lock:
|
||||||
|
if self._admin_token == headers["Authorization"]:
|
||||||
|
self._admin_token = None
|
||||||
|
self._token_at = 0.0
|
||||||
|
headers["Authorization"] = self.admin_token()
|
||||||
|
res = self._http().request(method, url, headers=headers, json=json, params=params)
|
||||||
if res.status_code >= 400:
|
if res.status_code >= 400:
|
||||||
try:
|
try:
|
||||||
detail = res.json()
|
detail = res.json()
|
||||||
@ -65,7 +78,11 @@ class PocketBaseClient:
|
|||||||
return res.json()
|
return res.json()
|
||||||
|
|
||||||
def admin_token(self) -> str:
|
def admin_token(self) -> str:
|
||||||
if self._admin_token and (time.time() - self._token_at) < 280:
|
with self._auth_lock:
|
||||||
|
return self._refresh_admin_token()
|
||||||
|
|
||||||
|
def _refresh_admin_token(self) -> str:
|
||||||
|
if self._admin_token and (time.monotonic() - self._token_at) < 280:
|
||||||
return self._admin_token
|
return self._admin_token
|
||||||
body = {"identity": self.email, "password": self.password}
|
body = {"identity": self.email, "password": self.password}
|
||||||
last: Exception | None = None
|
last: Exception | None = None
|
||||||
@ -78,7 +95,7 @@ class PocketBaseClient:
|
|||||||
token = (data or {}).get("token")
|
token = (data or {}).get("token")
|
||||||
if token:
|
if token:
|
||||||
self._admin_token = str(token)
|
self._admin_token = str(token)
|
||||||
self._token_at = time.time()
|
self._token_at = time.monotonic()
|
||||||
return self._admin_token
|
return self._admin_token
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
last = exc
|
last = exc
|
||||||
|
|||||||
91
apps/api/tests/test_pb_client.py
Normal file
91
apps/api/tests/test_pb_client.py
Normal file
@ -0,0 +1,91 @@
|
|||||||
|
"""Credential recovery and concurrency tests; no live PocketBase calls."""
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'services'))
|
||||||
|
from nomadro_pb.client import PocketBaseClient, PocketBaseError
|
||||||
|
|
||||||
|
|
||||||
|
class PocketBaseClientTests(unittest.TestCase):
|
||||||
|
def client(self, handler):
|
||||||
|
client = PocketBaseClient(base_url='https://pb.invalid', email='test', password='test')
|
||||||
|
client._client = httpx.Client(transport=httpx.MockTransport(handler))
|
||||||
|
self.addCleanup(client._client.close)
|
||||||
|
return client
|
||||||
|
|
||||||
|
def test_concurrent_calls_share_one_authentication(self):
|
||||||
|
auth_calls = []
|
||||||
|
barrier = threading.Barrier(8)
|
||||||
|
|
||||||
|
def handler(request):
|
||||||
|
auth_calls.append(request.url.path)
|
||||||
|
return httpx.Response(200, json={'token': 'shared'})
|
||||||
|
|
||||||
|
client = self.client(handler)
|
||||||
|
|
||||||
|
def token(_):
|
||||||
|
barrier.wait(timeout=5)
|
||||||
|
return client.admin_token()
|
||||||
|
|
||||||
|
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||||
|
self.assertEqual(list(pool.map(token, range(8))), ['shared'] * 8)
|
||||||
|
self.assertEqual(len(auth_calls), 1)
|
||||||
|
|
||||||
|
def test_expired_credential_refreshes_once_and_preserves_write(self):
|
||||||
|
writes = []
|
||||||
|
auth_calls = []
|
||||||
|
|
||||||
|
def handler(request):
|
||||||
|
if request.url.path.endswith('auth-with-password'):
|
||||||
|
auth_calls.append(request)
|
||||||
|
return httpx.Response(200, json={'token': f'token-{len(auth_calls)}'})
|
||||||
|
writes.append((request.headers['Authorization'], request.content))
|
||||||
|
return httpx.Response(401 if len(writes) == 1 else 200, json={'id': 'saved'})
|
||||||
|
|
||||||
|
client = self.client(handler)
|
||||||
|
self.assertEqual(client.create('records', {'title': 'hello'}), {'id': 'saved'})
|
||||||
|
self.assertEqual([token for token, _ in writes], ['token-1', 'token-2'])
|
||||||
|
self.assertEqual(writes[0][1], writes[1][1])
|
||||||
|
|
||||||
|
def test_repeated_unauthorized_response_stops_after_one_retry(self):
|
||||||
|
writes = []
|
||||||
|
|
||||||
|
def handler(request):
|
||||||
|
if request.url.path.endswith('auth-with-password'):
|
||||||
|
return httpx.Response(200, json={'token': 'rejected'})
|
||||||
|
writes.append(request)
|
||||||
|
return httpx.Response(401, json={'message': 'rejected'})
|
||||||
|
|
||||||
|
with self.assertRaises(PocketBaseError):
|
||||||
|
self.client(handler).create('records', {'title': 'hello'})
|
||||||
|
self.assertEqual(len(writes), 2)
|
||||||
|
|
||||||
|
def test_server_errors_and_timeouts_do_not_replay_writes(self):
|
||||||
|
for failure in [403, 500, 'timeout']:
|
||||||
|
with self.subTest(failure=failure):
|
||||||
|
writes = []
|
||||||
|
|
||||||
|
def handler(request):
|
||||||
|
if request.url.path.endswith('auth-with-password'):
|
||||||
|
return httpx.Response(200, json={'token': 'valid'})
|
||||||
|
writes.append(request)
|
||||||
|
if failure == 'timeout':
|
||||||
|
raise httpx.ReadTimeout('timeout', request=request)
|
||||||
|
return httpx.Response(failure, json={'message': 'failed'})
|
||||||
|
|
||||||
|
with self.assertRaises((PocketBaseError, httpx.ReadTimeout)):
|
||||||
|
self.client(handler).create('records', {'title': 'hello'})
|
||||||
|
self.assertEqual(len(writes), 1)
|
||||||
|
|
||||||
|
def test_legacy_admin_endpoint_remains_supported(self):
|
||||||
|
def handler(request):
|
||||||
|
if '/_superusers/' in request.url.path:
|
||||||
|
return httpx.Response(404, json={})
|
||||||
|
return httpx.Response(200, json={'token': 'legacy'})
|
||||||
|
|
||||||
|
self.assertEqual(self.client(handler).admin_token(), 'legacy')
|
||||||
@ -25,9 +25,9 @@ export async function api<T = unknown>(path: string, init: RequestInit = {}): Pr
|
|||||||
|
|
||||||
const timeout = new AbortController()
|
const timeout = new AbortController()
|
||||||
const timer = window.setTimeout(() => timeout.abort(), 20000)
|
const timer = window.setTimeout(() => timeout.abort(), 20000)
|
||||||
const abort = () => timeout.abort()
|
const abort = () => timeout.abort(init.signal?.reason)
|
||||||
init.signal?.addEventListener('abort', abort, { once: true })
|
init.signal?.addEventListener('abort', abort, { once: true })
|
||||||
if (init.signal?.aborted) timeout.abort()
|
if (init.signal?.aborted) abort()
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${API_BASE}${path}`, { ...init, headers, signal: timeout.signal, cache: 'no-store' })
|
const res = await fetch(`${API_BASE}${path}`, { ...init, headers, signal: timeout.signal, cache: 'no-store' })
|
||||||
if (res.status === 401 && getToken() === token) {
|
if (res.status === 401 && getToken() === token) {
|
||||||
@ -37,22 +37,26 @@ export async function api<T = unknown>(path: string, init: RequestInit = {}): Pr
|
|||||||
window.location.replace('/login')
|
window.location.replace('/login')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (res.status === 204) return {} as T
|
if (res.status === 204 || res.status === 205) return {} as T
|
||||||
const isJson = /(?:application\/json|\+json)(?:;|$)/i.test(res.headers.get('content-type') || '')
|
const isJson = /(?:application\/json|\+json)(?:;|$)/i.test(res.headers.get('content-type') || '')
|
||||||
let data: unknown
|
let data: unknown
|
||||||
try { data = await res.json() }
|
try { data = await res.json() }
|
||||||
catch { throw new Error(`服务返回异常(${res.status}),请稍后重试;保存操作请先确认结果`) }
|
catch {
|
||||||
|
if (timeout.signal.aborted) throw timeout.signal.reason
|
||||||
|
throw new Error(`服务返回异常(${res.status}),请稍后重试;保存操作请先确认结果`)
|
||||||
|
}
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const err = data as { detail?: unknown; message?: string }
|
const err = (data && typeof data === 'object' ? data : {}) as { detail?: unknown; message?: unknown }
|
||||||
const detail = typeof err.detail === 'string' ? err.detail : Array.isArray(err.detail)
|
const detail = typeof err.detail === 'string' ? err.detail : Array.isArray(err.detail)
|
||||||
? err.detail.map((item: { msg?: string }) => item.msg || '参数错误').join(';') : ''
|
? err.detail.map((item: unknown) => item && typeof item === 'object' && 'msg' in item && typeof item.msg === 'string' ? item.msg : '参数错误').join(';') : ''
|
||||||
throw new Error(detail || err.message || `请求失败(${res.status})`)
|
throw new Error(detail || (typeof err.message === 'string' ? err.message : '') || `请求失败(${res.status})`)
|
||||||
}
|
}
|
||||||
if (!isJson || data == null) {
|
if (!isJson || data == null) {
|
||||||
throw new Error('服务返回异常,请稍后重试')
|
throw new Error('服务返回异常,请稍后重试')
|
||||||
}
|
}
|
||||||
return data as T
|
return data as T
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (init.signal?.aborted) throw init.signal.reason ?? error
|
||||||
if (timeout.signal.aborted && !init.signal?.aborted) throw new Error('请求超时,请刷新重试;保存操作请先确认结果')
|
if (timeout.signal.aborted && !init.signal?.aborted) throw new Error('请求超时,请刷新重试;保存操作请先确认结果')
|
||||||
if (error instanceof TypeError) throw new Error('网络连接失败,请检查网络后重试;保存操作请先确认结果')
|
if (error instanceof TypeError) throw new Error('网络连接失败,请检查网络后重试;保存操作请先确认结果')
|
||||||
throw error
|
throw error
|
||||||
|
|||||||
@ -3,10 +3,10 @@ import react from '@vitejs/plugin-react'
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* admin.nomadro.com — Web only; isolated from apps/admin (.cn)
|
* admin.nomadro.com — Web only; isolated from apps/admin (.cn)
|
||||||
* 本地默认打本机 API(与门户共用 data/remote-config.json),改价即时生效。
|
* 本地默认连接 .com 线上后端,与门户保持一致。
|
||||||
* 连美国机:VITE_DEV_API=https://api.nomadro.com
|
* 仅显式联调时通过 VITE_DEV_API 覆盖。
|
||||||
*/
|
*/
|
||||||
const DEV_API = process.env.VITE_DEV_API || 'http://127.0.0.1:8080'
|
const DEV_API = process.env.VITE_DEV_API?.trim() || 'https://nomadro.com'
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [react()],
|
plugins: [react()],
|
||||||
|
|||||||
38
docs/test14-development.md
Normal file
38
docs/test14-development.md
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
# test14 功能与构建优化
|
||||||
|
|
||||||
|
2026-11-09。基于 `test13` 收尾提交 `21f4405` 创建;仅涉及 Next.js 门户、FastAPI 后端及管理后台。未改样式、视觉组件、小程序或冻结游戏模块,未执行生产部署。
|
||||||
|
|
||||||
|
## 修改
|
||||||
|
|
||||||
|
- Next.js 16:`src/middleware.ts` 迁移至 `src/proxy.ts`,消除旧文件约定弃用提示。
|
||||||
|
- 首页:本地生产冒烟发现 `/` 重写到 `/social` 后返回指向 `/` 的 308。根页面改为直接组合原有社区布局与首页组件,避免循环;继续保留旧 `/social` 地址到 `/` 的跳转。
|
||||||
|
- 本地后端:Next 通用 API、`.com` 管理后台默认指向 `https://nomadro.com`;浏览器开发模式远程配置默认指向线上 `.com`,生产仍同源。显式环境变量继续优先,服务地址规范化尾部斜杠。
|
||||||
|
- 埋点:React Strict Mode 的 effect 清理后重新挂载时恢复点击/异常监听;会话起始事件仍只发送一次。
|
||||||
|
- 请求:门户和 `.com` 后台兼容 205 无内容响应;后台保留调用方取消原因,处理 null/异常校验错误数据,避免误报网络错误。已有新会话不被旧请求的 401 清除。
|
||||||
|
- 后端:共享 PocketBase HTTP 客户端初始化与凭证刷新加锁,缓存使用单调时钟;管理请求 401 时刷新凭证并至多重试一次。超时、403 和 5xx 不重放写请求,保留旧版 PocketBase 登录兼容。
|
||||||
|
- `.cn` 后台:将 React 类型解析固定到自身 React 18 类型包,修复导航排序回调的空值检查及 action 联合类型推导。不更改 React 版本,不修改页面外观。
|
||||||
|
|
||||||
|
## 验证命令
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pnpm build
|
||||||
|
pnpm build:admin-com
|
||||||
|
pnpm build:admin
|
||||||
|
node --test tests/runtime-transport.test.mjs
|
||||||
|
python -m unittest discover -s apps/api/tests -p test_pb_client.py -v
|
||||||
|
python -m unittest discover -s apps/api/tests -p test_scoped_schema.py -v
|
||||||
|
python -m unittest discover -s apps/api/tests -p test_coffee_notify_api.py -v
|
||||||
|
```
|
||||||
|
|
||||||
|
本地生产路由冒烟:先运行 `pnpm exec next start --hostname 127.0.0.1 --port 3114`,再执行 `node tests/portal-smoke.mjs`;仅读取本地页面,验证首页、旧地址重定向、VIP/导航页面与响应头。测试不连接或写入生产 PocketBase。
|
||||||
|
|
||||||
|
修改的 Next/TS 文件执行定向 ESLint;构建包含 TypeScript 检查。前端传输测试 12 项;后端凭证、schema、预约和通知测试合计 14 项。
|
||||||
|
|
||||||
|
最终结果:门户生产构建成功(233 个静态页面生成),两套后台构建通过,26 项回归测试及 6 条本地生产页面/跳转冒烟全部通过。首页最终返回 200,`/social?smoke=1` 正确跳转至 `/?smoke=1`,不再循环。
|
||||||
|
|
||||||
|
## 边界
|
||||||
|
|
||||||
|
- 本地运行数据库、临时脚本、截图及构建产物不提交;已有本地数据保留。
|
||||||
|
- 构建仍使用原有 `next/font/google` Noto Sans SC,依赖 Google 字体下载;曾出现一次下载失败,未替换字体以避免视觉变化。
|
||||||
|
- 未宣称已达到性能极限;本批验证的是上述功能、构建和本地路由,没有生产负载测试或全量业务端到端验收。
|
||||||
|
- `.com` 为默认开发目标,`.cn` 不自动同步;没有上传 `.next`、后台 dist 或小程序包。
|
||||||
@ -1,10 +1,8 @@
|
|||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import type { NextConfig } from "next";
|
import type { NextConfig } from "next";
|
||||||
|
import { serviceUpstream } from "./src/lib/online-upstream";
|
||||||
|
|
||||||
const API_URL = (process.env.API_URL || "http://127.0.0.1:8080").replace(
|
const API_URL = serviceUpstream(process.env.API_URL);
|
||||||
/\/$/,
|
|
||||||
"",
|
|
||||||
);
|
|
||||||
/** Social IM is isolated (nomadro-social / portal nginx /rt). Never assume api.* hosts it. */
|
/** Social IM is isolated (nomadro-social / portal nginx /rt). Never assume api.* hosts it. */
|
||||||
const SOCIAL_API_URL = (
|
const SOCIAL_API_URL = (
|
||||||
process.env.SOCIAL_API_URL ||
|
process.env.SOCIAL_API_URL ||
|
||||||
|
|||||||
@ -1,7 +1,13 @@
|
|||||||
/**
|
import SocialLayout from "./social/layout";
|
||||||
* Canonical home URL is `/`. Middleware rewrites it to `/social`
|
import SocialHomePage from "./social/page";
|
||||||
* (layout + HomeClient). This stub exists so the App Router keeps `/`.
|
|
||||||
*/
|
export { metadata } from "./social/layout";
|
||||||
|
|
||||||
|
/** Render the existing social home at its canonical URL without a rewrite. */
|
||||||
export default function HomePage() {
|
export default function HomePage() {
|
||||||
return null;
|
return (
|
||||||
|
<SocialLayout>
|
||||||
|
<SocialHomePage />
|
||||||
|
</SocialLayout>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -68,18 +68,19 @@ export function PortalAnalytics() {
|
|||||||
}, [posthogOn, fingerprintOn, posthogKey, posthogHost]);
|
}, [posthogOn, fingerprintOn, posthogKey, posthogHost]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (started.current) return;
|
if (!started.current) {
|
||||||
started.current = true;
|
started.current = true;
|
||||||
const sid = sessionId();
|
const sid = sessionId();
|
||||||
track("session_start", {
|
track("session_start", {
|
||||||
label: "portal",
|
label: "portal",
|
||||||
props: {
|
props: {
|
||||||
sid,
|
sid,
|
||||||
referrer: typeof document !== "undefined" ? document.referrer.slice(0, 120) : "",
|
referrer: typeof document !== "undefined" ? document.referrer.slice(0, 120) : "",
|
||||||
lang: typeof navigator !== "undefined" ? navigator.language : "",
|
lang: typeof navigator !== "undefined" ? navigator.language : "",
|
||||||
},
|
},
|
||||||
immediate: true,
|
immediate: true,
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const onClick = (ev: MouseEvent) => {
|
const onClick = (ev: MouseEvent) => {
|
||||||
const el = (ev.target as Element | null)?.closest?.(
|
const el = (ev.target as Element | null)?.closest?.(
|
||||||
|
|||||||
@ -15,7 +15,7 @@ export async function requestJson<T>(url: string, init: RequestInit = {}): Promi
|
|||||||
if (init.body && !(init.body instanceof FormData) && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json')
|
if (init.body && !(init.body instanceof FormData) && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json')
|
||||||
try {
|
try {
|
||||||
const response = await fetch(url, { ...init, headers, signal: controller.signal, cache: 'no-store' })
|
const response = await fetch(url, { ...init, headers, signal: controller.signal, cache: 'no-store' })
|
||||||
if (response.status === 204) return undefined as T
|
if (response.status === 204 || response.status === 205) return undefined as T
|
||||||
let data: Record<string, unknown>
|
let data: Record<string, unknown>
|
||||||
try {
|
try {
|
||||||
data = await response.json()
|
data = await response.json()
|
||||||
|
|||||||
@ -5,6 +5,6 @@
|
|||||||
export const ONLINE_COM_ORIGIN = "https://nomadro.com";
|
export const ONLINE_COM_ORIGIN = "https://nomadro.com";
|
||||||
|
|
||||||
export function serviceUpstream(envValue: string | undefined): string {
|
export function serviceUpstream(envValue: string | undefined): string {
|
||||||
const raw = (envValue || ONLINE_COM_ORIGIN).trim().replace(/\/$/, "");
|
const raw = (envValue || ONLINE_COM_ORIGIN).trim().replace(/\/+$/, "");
|
||||||
return raw || ONLINE_COM_ORIGIN;
|
return raw || ONLINE_COM_ORIGIN;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,11 +1,12 @@
|
|||||||
/**
|
/**
|
||||||
* 浏览器端配置入口:
|
* 浏览器端配置入口:
|
||||||
* - 设了 NEXT_PUBLIC_REMOTE_CONFIG_URL → 直连线上(本地调试同线上后台)
|
* - 设了 NEXT_PUBLIC_REMOTE_CONFIG_URL → 直连线上(本地调试同线上后台)
|
||||||
* - 否则同源 /api/config
|
* - 本地开发默认线上 .com;生产环境同源 /api/config
|
||||||
*/
|
*/
|
||||||
export function remoteConfigUrl(): string {
|
export function remoteConfigUrl(): string {
|
||||||
const explicit = (process.env.NEXT_PUBLIC_REMOTE_CONFIG_URL || "").trim();
|
const explicit = (process.env.NEXT_PUBLIC_REMOTE_CONFIG_URL || "").trim();
|
||||||
if (explicit) return explicit.replace(/\/$/, "");
|
if (explicit) return explicit.replace(/\/$/, "");
|
||||||
|
if (process.env.NODE_ENV === "development") return "https://nomadro.com/api/config";
|
||||||
return "/api/config";
|
return "/api/config";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -48,7 +48,7 @@ const COMMUNITY_ROOTS = new Set([
|
|||||||
/** Standalone nomadvip paths → /vip/* (do not steal /book) */
|
/** Standalone nomadvip paths → /vip/* (do not steal /book) */
|
||||||
const VIP_ROOTS = new Set(["topic", "paid", "cloudphone"]);
|
const VIP_ROOTS = new Set(["topic", "paid", "cloudphone"]);
|
||||||
|
|
||||||
export function middleware(request: NextRequest) {
|
export function proxy(request: NextRequest) {
|
||||||
const { pathname, search } = request.nextUrl;
|
const { pathname, search } = request.nextUrl;
|
||||||
|
|
||||||
if (pathname === '/notifications' || pathname.startsWith('/notifications/')) {
|
if (pathname === '/notifications' || pathname.startsWith('/notifications/')) {
|
||||||
@ -57,12 +57,7 @@ export function middleware(request: NextRequest) {
|
|||||||
return NextResponse.redirect(url, 308);
|
return NextResponse.redirect(url, 308);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Site home is 游民社区: serve /social at `/`, canonicalize bare /social → /
|
// The root page renders the social home directly; only legacy URLs redirect.
|
||||||
if (pathname === "/" || pathname === "") {
|
|
||||||
const url = request.nextUrl.clone();
|
|
||||||
url.pathname = "/social";
|
|
||||||
return NextResponse.rewrite(url);
|
|
||||||
}
|
|
||||||
if (pathname === "/social" || pathname === "/social/") {
|
if (pathname === "/social" || pathname === "/social/") {
|
||||||
const url = request.nextUrl.clone();
|
const url = request.nextUrl.clone();
|
||||||
url.pathname = "/";
|
url.pathname = "/";
|
||||||
26
tests/portal-smoke.mjs
Normal file
26
tests/portal-smoke.mjs
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
|
||||||
|
// Run against a local `next start`; no production API calls or mutations.
|
||||||
|
const origin = process.env.PORTAL_SMOKE_ORIGIN || 'http://127.0.0.1:3114';
|
||||||
|
assert.ok(['127.0.0.1', 'localhost'].includes(new URL(origin).hostname));
|
||||||
|
for (const [path, status, location] of [
|
||||||
|
['/', 200],
|
||||||
|
['/social?smoke=1', 308, '/?smoke=1'],
|
||||||
|
['/ebook', 308, '/book'],
|
||||||
|
['/notifications/settings', 308, '/social/notifications/settings'],
|
||||||
|
['/vip', 200],
|
||||||
|
['/nav', 200],
|
||||||
|
]) {
|
||||||
|
const response = await fetch(new URL(path, origin), {
|
||||||
|
redirect: 'manual', signal: AbortSignal.timeout(20000),
|
||||||
|
});
|
||||||
|
assert.equal(response.status, status, path);
|
||||||
|
if (location) {
|
||||||
|
const target = new URL(response.headers.get('location'), origin);
|
||||||
|
assert.equal(target.pathname + target.search, location, path);
|
||||||
|
}
|
||||||
|
assert.equal(response.headers.get('x-content-type-options'), 'nosniff', path);
|
||||||
|
const body = await response.text();
|
||||||
|
if (path === '/') assert.ok(body.includes('community-root social-skin'), 'Social home layout must render at /');
|
||||||
|
console.log(`${path}: ${status} OK`);
|
||||||
|
}
|
||||||
103
tests/runtime-transport.test.mjs
Normal file
103
tests/runtime-transport.test.mjs
Normal file
@ -0,0 +1,103 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { readFile } from 'node:fs/promises';
|
||||||
|
import test from 'node:test';
|
||||||
|
import ts from 'typescript';
|
||||||
|
|
||||||
|
// Exercise the real TS transports without a browser, bundler or live service.
|
||||||
|
async function loadTs(path) {
|
||||||
|
const source = (await readFile(new URL(path, import.meta.url), 'utf8'))
|
||||||
|
.replaceAll('import.meta.env.VITE_API_BASE', "''");
|
||||||
|
const { outputText } = ts.transpileModule(source, {
|
||||||
|
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext },
|
||||||
|
});
|
||||||
|
return import(`data:text/javascript;base64,${Buffer.from(outputText).toString('base64')}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const portal = await loadTs('../src/lib/client-request.ts');
|
||||||
|
const admin = await loadTs('../apps/com/admin/src/api/client.ts');
|
||||||
|
const { serviceUpstream } = await loadTs('../src/lib/online-upstream.ts');
|
||||||
|
const remoteConfig = await loadTs('../src/lib/remote-config-client.ts');
|
||||||
|
|
||||||
|
test('development config and live endpoints use the online backend', () => {
|
||||||
|
const previousMode = process.env.NODE_ENV;
|
||||||
|
const previousUrl = process.env.NEXT_PUBLIC_REMOTE_CONFIG_URL;
|
||||||
|
try {
|
||||||
|
delete process.env.NEXT_PUBLIC_REMOTE_CONFIG_URL;
|
||||||
|
process.env.NODE_ENV = 'development';
|
||||||
|
assert.equal(remoteConfig.remoteConfigUrl(), 'https://nomadro.com/api/config');
|
||||||
|
assert.equal(remoteConfig.remoteConfigStreamUrl(), 'https://nomadro.com/api/config/stream');
|
||||||
|
assert.equal(remoteConfig.remoteConfigMetaUrl(), 'https://nomadro.com/api/config/meta');
|
||||||
|
process.env.NODE_ENV = 'production';
|
||||||
|
assert.equal(remoteConfig.remoteConfigUrl(), '/api/config');
|
||||||
|
process.env.NEXT_PUBLIC_REMOTE_CONFIG_URL = 'https://example.invalid/api/config';
|
||||||
|
assert.equal(remoteConfig.remoteConfigMetaUrl(), 'https://example.invalid/api/config/meta');
|
||||||
|
} finally {
|
||||||
|
if (previousMode === undefined) delete process.env.NODE_ENV;
|
||||||
|
else process.env.NODE_ENV = previousMode;
|
||||||
|
if (previousUrl === undefined) delete process.env.NEXT_PUBLIC_REMOTE_CONFIG_URL;
|
||||||
|
else process.env.NEXT_PUBLIC_REMOTE_CONFIG_URL = previousUrl;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('upstream defaults and explicit overrides', () => {
|
||||||
|
for (const value of [undefined, '', ' ']) assert.equal(serviceUpstream(value), 'https://nomadro.com');
|
||||||
|
assert.equal(serviceUpstream(' https://nomadro.com/// '), 'https://nomadro.com');
|
||||||
|
assert.equal(serviceUpstream('http://127.0.0.1:8021/'), 'http://127.0.0.1:8021');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('portal and admin request contracts', async (t) => {
|
||||||
|
const originalFetch = globalThis.fetch;
|
||||||
|
const values = new Map();
|
||||||
|
globalThis.localStorage = {
|
||||||
|
getItem: key => values.get(key) ?? null,
|
||||||
|
setItem: (key, value) => values.set(key, value),
|
||||||
|
removeItem: key => values.delete(key),
|
||||||
|
};
|
||||||
|
globalThis.window = { setTimeout, clearTimeout };
|
||||||
|
t.after(() => {
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
delete globalThis.localStorage;
|
||||||
|
delete globalThis.window;
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const [name, request] of [['portal', portal.requestJson], ['admin', admin.api]]) {
|
||||||
|
await t.test(`${name}: no-content responses`, async () => {
|
||||||
|
for (const status of [204, 205]) {
|
||||||
|
globalThis.fetch = async () => new Response(null, { status });
|
||||||
|
await request('/test');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await t.test(`${name}: FormData keeps browser multipart boundary`, async () => {
|
||||||
|
globalThis.fetch = async (_url, init) => {
|
||||||
|
assert.equal(init.headers.has('Content-Type'), false);
|
||||||
|
return Response.json({ ok: true });
|
||||||
|
};
|
||||||
|
await request('/test', { method: 'POST', body: new FormData() });
|
||||||
|
});
|
||||||
|
await t.test(`${name}: malformed and null errors stay understandable`, async () => {
|
||||||
|
for (const body of ['null', '{"detail":[null, {"msg":"bad field"}]}', '<html>bad gateway</html>']) {
|
||||||
|
globalThis.fetch = async () => new Response(body, { status: 502, headers: { 'Content-Type': 'application/json' } });
|
||||||
|
await assert.rejects(request('/test'), error => error instanceof Error && !(error instanceof TypeError));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await t.test(`${name}: cancellation stays cancellation`, async () => {
|
||||||
|
const controller = new AbortController();
|
||||||
|
const reason = new DOMException('Navigation cancelled', 'AbortError');
|
||||||
|
globalThis.fetch = async (_url, init) => {
|
||||||
|
controller.abort(reason);
|
||||||
|
throw init.signal.reason;
|
||||||
|
};
|
||||||
|
await assert.rejects(request('/test', { signal: controller.signal }), error => error === reason);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await t.test('stale 401 cannot log out a newer admin session', async () => {
|
||||||
|
admin.setToken('old');
|
||||||
|
globalThis.fetch = async () => {
|
||||||
|
admin.setToken('new');
|
||||||
|
return Response.json({ detail: 'expired' }, { status: 401 });
|
||||||
|
};
|
||||||
|
await assert.rejects(admin.api('/test'), /expired/);
|
||||||
|
assert.equal(admin.getToken(), 'new');
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Reference in New Issue
Block a user