Harden platform upgrade: ops admin, live config, shared service proxy, and smoke deploys.

Ship Operations console polish, PocketBase social fixtures, and portal join-leads without local DBs or probe scripts.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Eric 2026-11-05 01:20:55 +08:00
parent 9b7ffb24dc
commit 308974bf5e
67 changed files with 1833 additions and 363 deletions

View File

@ -1,6 +1,8 @@
# Nomadro
中文数字游民操作系统([nomadro.cn](https://nomadro.cn))。
数字游民操作系统(主开发与默认发版:[nomadro.com](https://nomadro.com);中国独立站:[nomadro.cn](https://nomadro.cn))。
2026-11 平台升级已部署至 `.com` 门户、API 与 [Web 管理后台](https://admin.nomadro.com)。升级内容、验收范围、构建编号与回滚位置见 [升级记录](docs/platform-upgrade-2026-11.md)。`.cn` 未同步本次发版。
## 架构

View File

@ -1,5 +1,7 @@
# Nomadro 统一 API
2026-11 `.com` 升级已部署:服务资源监控、配置校验与版本冲突保护、原子配置写入、WebSocket 断线任务清理、PocketBase 消息幂等与最近历史读取。生产保留 `/opt/nomadmini/backend/app` 兼容布局,部署时转换导入前缀;不要用本地统一入口覆盖生产 `main.py`。详见 [平台升级记录](../../docs/platform-upgrade-2026-11.md)。
## 2026-11-02:社区消息与报名兼容修复(未部署)
仅修改 `social_svc/store.py` 与 `social_svc/routers/api.py`:聊天改为读取最近一批、按时间正序返回,同秒消息以 rowid 保持稳定顺序;消息可带 `clientId`、报名可带 `requestId`,由设备身份和频道/岗位限定作用域,重复请求复用同一记录与时间,不同载荷返回 409。旧客户端不传标识继续兼容。纯 SQLite 接口移入线程池,消息发布失败不影响已提交记录。

View File

@ -17,7 +17,7 @@ from pathlib import Path
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
SERVICES = Path(__file__).resolve().parent / "services"
SERVICES = Path(__file__).resolve().parents[1] / "services"
if str(SERVICES) not in sys.path:
sys.path.insert(0, str(SERVICES))
@ -25,6 +25,8 @@ from ebook_svc.jobs import reconcile_pending_orders # noqa: E402
from ebook_svc.config import settings as ebook_settings # noqa: E402
from ebook_svc.routers import ( # noqa: E402
admin,
ops_admin,
audience_admin,
auth,
books,
douyin_admin,
@ -138,6 +140,8 @@ for _prefix in ("/api", "/api/ebook"):
app.include_router(shop.router, prefix=_prefix)
app.include_router(memo.router, prefix=_prefix)
app.include_router(admin.router)
app.include_router(ops_admin.router)
app.include_router(audience_admin.router)
app.include_router(douyin_admin.router)
app.include_router(join_group_admin.router)
app.include_router(vip_admin.router)

View File

@ -1,7 +1,16 @@
"""运营:ntfy 状态 / 试推 — admin.nomadro.com 与 .cn 共用。"""
from __future__ import annotations
import asyncio
import os
import shutil
import time
from datetime import datetime, timezone
from pathlib import Path
import httpx
from fastapi import APIRouter, Depends
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from ebook_svc.config import settings
@ -11,6 +20,63 @@ from ebook_svc.services import ntfy as ntfy_svc
router = APIRouter(prefix="/api/admin/ops", tags=["ops-admin"])
async def _probe(client: httpx.AsyncClient, name: str, url: str) -> dict:
started = time.monotonic()
try:
response = await client.get(url)
ok = 200 <= response.status_code < 300
if ok:
try:
payload = response.json()
ok = isinstance(payload, dict) and payload.get('ok') is True
except ValueError:
ok = False
status = response.status_code
except httpx.HTTPError:
ok, status = False, None
return {"name": name, "ok": ok, "status": status,
"latencyMs": round((time.monotonic() - started) * 1000)}
def _resources() -> dict:
disk = shutil.disk_usage(Path.cwd())
memory = None
try:
values = {}
for line in Path('/proc/meminfo').read_text().splitlines():
key, value = line.split(':', 1)
values[key] = int(value.split()[0]) * 1024
total = values['MemTotal']
available = values['MemAvailable']
memory = {"totalBytes": total, "usedBytes": total - available,
"usedPercent": round((total - available) * 100 / total, 1)}
except (OSError, ValueError, KeyError):
pass
try:
load = list(os.getloadavg())
except (AttributeError, OSError):
load = None
return {"disk": {"totalBytes": disk.total, "usedBytes": disk.used,
"usedPercent": round(disk.used * 100 / disk.total, 1)},
"memory": memory, "loadAverage": load, "cpuCount": os.cpu_count()}
@router.get('/health')
async def ops_health(_: str = Depends(require_admin)):
# Fixed loopback targets; callers cannot probe arbitrary hosts or paths.
async with httpx.AsyncClient(timeout=3.0, trust_env=False) as client:
checks = await asyncio.gather(
_probe(client, 'Next.js 门户', 'http://127.0.0.1:4003/api/health'),
_probe(client, '业务 API', 'http://127.0.0.1:8010/health'),
_probe(client, '社区服务', 'http://127.0.0.1:8020/health'),
)
resources = await asyncio.to_thread(_resources)
return JSONResponse({"ok": all(c['ok'] for c in checks), "checks": checks,
"resources": resources,
"checkedAt": datetime.now(timezone.utc).isoformat()},
headers={"Cache-Control": "no-store"})
class NtfyTestBody(BaseModel):
title: str = Field(default="[WebAdmin] 试推", max_length=80)
message: str = Field(default="admin.nomadro.com 通知通路正常", max_length=500)
@ -27,7 +93,7 @@ async def ntfy_status(_: str = Depends(require_admin)) -> dict:
"baseUrl": base,
"topic": topic,
"hasToken": bool((settings.ntfy_token or "").strip()),
"publicHint": "https://ntfy.nomadro.cn/" + topic if topic else "",
"publicHint": base + "/" + topic if base.startswith("https://") and topic else "",
}

View File

@ -131,7 +131,15 @@ async def public_remote_config_ws(ws: WebSocket) -> None:
json.dumps({"type": "config", **cur, "source": "pull"}, ensure_ascii=False)
)
await asyncio.gather(pump_out(), pump_in())
tasks = [asyncio.create_task(pump_out()), asyncio.create_task(pump_in())]
try:
done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
for task in done:
task.result()
finally:
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
except WebSocketDisconnect:
pass
except Exception:

View File

@ -3,7 +3,7 @@ from __future__ import annotations
from typing import Any, Literal
from fastapi import APIRouter, Depends
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from ebook_svc.core.security import require_admin
@ -15,9 +15,9 @@ router = APIRouter(prefix="/api/admin/weapp/switches", tags=["weapp-switches"])
class ModuleIn(BaseModel):
enabled: bool | None = None
title: str | None = None
tabLabel: str | None = None
note: str | None = None
title: str | None = Field(default=None, max_length=120)
tabLabel: str | None = Field(default=None, max_length=60)
note: str | None = Field(default=None, max_length=1000)
class FlagsIn(BaseModel):
@ -29,6 +29,11 @@ class FlagsIn(BaseModel):
joinGroupWechat: bool | None = None
socialTrialEnabled: bool | None = None
socialAvatarFaceCheck: bool | None = None
adsenseEnabled: bool | None = None
adsenseClientId: str | None = Field(default=None, max_length=64, pattern=r"^(ca-pub-[0-9]+)?$")
adsensePublisherId: str | None = Field(default=None, max_length=64, pattern=r"^(pub-[0-9]+)?$")
adsenseSlotBlogMid: str | None = Field(default=None, max_length=32, pattern=r"^[0-9]*$")
adsenseSlotBlogEnd: str | None = Field(default=None, max_length=32, pattern=r"^[0-9]*$")
class SocialTrialIn(BaseModel):
@ -44,7 +49,7 @@ class CopyIn(BaseModel):
homeTagline: str | None = None
homeLead: str | None = None
vipCta: str | None = None
vipPriceFen: int | None = Field(default=None, ge=0)
vipPriceFen: int | None = Field(default=None, ge=0, le=100000000)
vipProductId: str | None = None
wechatOaName: str | None = None
memoUnlockCta: str | None = None
@ -65,6 +70,7 @@ class VipHeroIn(BaseModel):
class SwitchesBody(BaseModel):
expectedVersion: int | None = Field(default=None, ge=0)
modules: dict[str, ModuleIn] | None = None
flags: FlagsIn | None = None
copy: CopyIn | None = Field(default=None, alias="copy")
@ -97,6 +103,10 @@ async def get_switches(_: str = Depends(require_admin)) -> dict[str, Any]:
@router.put("")
async def put_switches(body: SwitchesBody, _: str = Depends(require_admin)) -> dict[str, Any]:
if body.expectedVersion is not None:
current = read_weapp_switches()
if current.get('version') != body.expectedVersion:
raise HTTPException(409, '配置已更新,请加载最新配置后重试;当前修改尚未保存')
patch: dict[str, Any] = {}
if body.modules is not None:
patch["modules"] = {

View File

@ -5,6 +5,8 @@
from __future__ import annotations
import json
import os
import tempfile
from copy import deepcopy
from datetime import datetime, timezone
from typing import Any
@ -125,7 +127,23 @@ def _write_raw(out: dict[str, Any]) -> None:
bak.write_text(path.read_text(encoding="utf-8"), encoding="utf-8")
except Exception:
pass
path.write_text(json.dumps(out, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
temporary = None
try:
with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=path.parent,
prefix=path.name + '.', suffix='.tmp', delete=False) as handle:
temporary = handle.name
handle.write(json.dumps(out, ensure_ascii=False, indent=2) + '\n')
handle.flush()
os.fsync(handle.fileno())
if path.exists():
os.chmod(temporary, path.stat().st_mode & 0o777)
if hasattr(os, 'chown'):
info = path.stat()
os.chown(temporary, info.st_uid, info.st_gid)
os.replace(temporary, path)
finally:
if temporary and os.path.exists(temporary):
os.unlink(temporary)
try:
from ebook_svc.services.config_live import notify_config_written

View File

@ -3,6 +3,8 @@ from __future__ import annotations
import time
import uuid
import hashlib
import json
from typing import Any
from nomadro_pb import ensure_once, get_pb, pb_quote
@ -601,8 +603,10 @@ def list_messages(
lim = max(1, min(int(limit or 100), 500))
rows = get_pb().list_all(
C_MESSAGES,
filter=f"channel_id={pb_quote(channel_id)}",
sort="seq",
filter=(f"channel_id={pb_quote(channel_id)}"
+ (f" && seq>{int(since)}" if since is not None and since > 0 else '')
+ (f" && seq<{int(before)}" if before is not None and before > 0 else '')),
sort="-seq,-created_at,-id",
hard_limit=2000,
)
needle = (q or "").strip().lower()
@ -637,10 +641,7 @@ def list_messages(
"editedAt": r.get("edited_at") or "",
}
)
if before is not None and before > 0:
out = out[-lim:]
else:
out = out[-lim:]
out = list(reversed(out[:lim]))
avatars = _avatars_for_guests([str(m.get("guestId") or "") for m in out])
return [
_public_message(m, avatar=avatars.get(str(m.get("guestId") or ""), ""))
@ -654,6 +655,7 @@ def add_message(
text: str,
guest_id: str,
*,
client_id: str | None = None,
kind: str = "text",
meta: dict[str, Any] | None = None,
attachments: list[Any] | None = None,
@ -661,6 +663,25 @@ def add_message(
) -> dict[str, Any]:
init_pb()
pb = get_pb()
stable_id = None
request_meta = dict(meta or {})
fingerprint = hashlib.sha256(json.dumps(
[author, text, kind, meta or {}, attachments or [], reply_to],
sort_keys=True, ensure_ascii=False, separators=(',', ':'),
).encode()).hexdigest()
if client_id:
stable_id = hashlib.sha256(json.dumps([channel_id, guest_id, client_id]).encode()).hexdigest()[:15]
request_meta.update({'clientId': client_id, 'requestFingerprint': fingerprint})
existing = pb.first(C_MESSAGES, filter=f'id={pb_quote(stable_id)}')
if existing:
if (existing.get('meta') or {}).get('requestFingerprint') != fingerprint:
raise ValueError('同一请求标识不能用于不同消息')
return get_message(stable_id) or {}
# Replays must not consume quota or fail after the original exhausted it.
from social_svc.trial_gate import assert_chat_trial_ok
from social_svc.im import check_rate
assert_chat_trial_ok(guest_id)
check_rate(guest_id)
seq = channel_seq(channel_id) + 1
now = _now()
body = {
@ -670,7 +691,7 @@ def add_message(
"nick": (author or "游民")[:48],
"text": (text or "")[:4000],
"kind": kind or "text",
"meta": meta or {},
"meta": request_meta,
"attachments": attachments or [],
"reply_to": reply_to,
"reactions": {},
@ -679,7 +700,19 @@ def add_message(
"created_at": now,
"edited_at": "",
}
rec = pb.create(C_MESSAGES, body)
if stable_id:
body['id'] = stable_id
try:
rec = pb.create(C_MESSAGES, body)
except Exception:
if not stable_id:
raise
existing = pb.first(C_MESSAGES, filter=f'id={pb_quote(stable_id)}')
if not existing:
raise
if (existing.get('meta') or {}).get('requestFingerprint') != fingerprint:
raise ValueError('同一请求标识不能用于不同消息')
return get_message(stable_id) or {}
meta_rec = _ch_meta(channel_id)
if meta_rec:
pb.update(C_CHMETA, meta_rec["id"], {"seq": seq, "updated_at": now})
@ -694,6 +727,9 @@ def add_message(
"updated_at": now,
},
)
saved = get_message(str(rec.get('id') or ''))
if saved:
return saved
avatars = _avatars_for_guests([guest_id])
return _public_message(
{

View File

@ -209,10 +209,7 @@ async def post_message(
raise HTTPException(status_code=400, detail="empty message")
def persist():
from social_svc.trial_gate import assert_chat_trial_ok
store.init_db()
assert_chat_trial_ok(peer)
return store.add_message(
channel_id,
body.author,

View File

@ -437,9 +437,6 @@ def add_message(
attachments: list[Any] | None = None,
mentions: list[Any] | None = None,
) -> dict[str, Any]:
from social_svc.im import check_rate
check_rate(guest_id)
body = (text or "").strip()[:2000]
atts = _normalize_attachments(attachments)
if not body and not atts:
@ -465,6 +462,7 @@ def add_message(
author,
body,
guest_id,
client_id=client_id,
kind="text",
meta=meta,
attachments=atts,

View File

@ -0,0 +1,82 @@
"""Isolated PocketBase adapter fixture; never connects to an external service."""
import copy
import json
import re
import uuid
from unittest.mock import patch
class MemoryPocketBase:
base_url = 'http://isolated.invalid'
def __init__(self):
self.rows = {}
def _matches(self, row, expression):
if not expression:
return True
if ' || ' in expression:
return any(self._matches(row, part) for part in expression.split(' || '))
if ' && ' in expression:
return all(self._matches(row, part) for part in expression.split(' && '))
match = re.fullmatch(r'([\w.]+)\s*(=|>|<)\s*(.+)', expression)
if not match:
raise AssertionError(f'Unsupported test filter: {expression}')
key, operator, raw = match.groups()
expected = json.loads(raw)
actual = row
for segment in key.split('.'):
actual = actual.get(segment) if isinstance(actual, dict) else None
if operator == '=':
return actual == expected
return actual is not None and (actual > expected if operator == '>' else actual < expected)
def list_all(self, collection, *, filter=None, sort=None, hard_limit=5000):
rows = [copy.deepcopy(row) for row in self.rows.get(collection, {}).values() if self._matches(row, filter)]
if sort:
for key in reversed(sort.split(',')):
rows.sort(key=lambda row: row.get(key.lstrip('-')) or 0, reverse=key.startswith('-'))
return rows[:hard_limit]
def first(self, collection, *, filter):
rows = self.list_all(collection, filter=filter, hard_limit=1)
return rows[0] if rows else None
def create(self, collection, payload):
row = copy.deepcopy(payload)
row.setdefault('id', uuid.uuid4().hex[:15])
table = self.rows.setdefault(collection, {})
if row['id'] in table:
raise ValueError('duplicate id')
table[row['id']] = row
return copy.deepcopy(row)
def update(self, collection, record_id, payload):
row = self.rows[collection][record_id]
row.update(copy.deepcopy(payload))
return copy.deepcopy(row)
def upsert(self, collection, *, filter, payload):
current = self.first(collection, filter=filter)
return self.update(collection, current['id'], payload) if current else self.create(collection, payload)
def request(self, method, path, **kwargs):
assert method == 'GET', method
parts = path.split('/')
return copy.deepcopy(self.rows[parts[3]][parts[5]])
def isolate_social(test):
from social_svc import pb_data, im
adapter = MemoryPocketBase()
for target, value in [
('social_svc.pb_data.get_pb', lambda: adapter),
('social_svc.pb_data.ensure_once', lambda: None),
('nomadro_pb.ensure_once', lambda: None),
('social_svc.im.check_rate', lambda guest_id: None),
('social_svc.trial_gate.assert_chat_trial_ok', lambda guest_id: None),
]:
override = patch(target, value)
override.start()
test.addCleanup(override.stop)
return adapter

View File

@ -0,0 +1,70 @@
"""Admin health/schema regression checks without app startup or production data."""
import asyncio
import importlib.util
import json
import sys
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
import httpx
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import ValidationError
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'services'))
from ebook_svc.routers import ops_admin
class OpsUpgradeTests(unittest.TestCase):
def test_health_requires_admin(self):
app = FastAPI()
app.include_router(ops_admin.router)
with TestClient(app) as client:
self.assertEqual(client.get('/api/admin/ops/health').status_code, 401)
def test_health_checks_payload_and_handles_downstream_failure(self):
def respond(request):
if request.url.port == 4003:
return httpx.Response(200, json={'ok': True})
if request.url.port == 8010:
return httpx.Response(200, json={'ok': False})
raise httpx.ConnectError('unavailable')
async def run():
async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as client:
return await asyncio.gather(*[ops_admin._probe(client, str(port), f'http://127.0.0.1:{port}/health') for port in (4003, 8010, 8020)])
checks = asyncio.run(run())
self.assertEqual([row['ok'] for row in checks], [True, False, False])
self.assertIsNone(checks[-1]['status'])
def load_switches(self):
target = Path(__file__).resolve().parents[1] / 'services/ebook_svc/routers/weapp_switches_admin.py'
spec = importlib.util.spec_from_file_location('isolated_switches', target)
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
with patch.dict(sys.modules, {
'ebook_svc.services.store': SimpleNamespace(store=SimpleNamespace()),
'ebook_svc.services.weapp_switches': SimpleNamespace(read_weapp_switches=lambda: {'version': 10}, write_weapp_switches=lambda patch: patch),
}):
spec.loader.exec_module(module)
return module
def test_adsense_fields_are_preserved_and_validated(self):
module = self.load_switches()
body = module.SwitchesBody.model_validate({'flags': {'adsenseEnabled': False, 'adsenseClientId': 'ca-pub-123', 'adsenseSlotBlogMid': '456'}})
self.assertEqual(body.flags.adsenseClientId, 'ca-pub-123')
self.assertEqual(body.flags.adsenseSlotBlogMid, '456')
for value in ['javascript:alert(1)', 'ca-pub-no-digits']:
with self.assertRaises(ValidationError):
module.SwitchesBody.model_validate({'flags': {'adsenseClientId': value}})
def test_stale_config_write_is_rejected(self):
module = self.load_switches()
app = FastAPI()
app.include_router(module.router)
app.dependency_overrides[module.require_admin] = lambda: 'isolated-admin'
with TestClient(app) as client:
response = client.put('/api/admin/weapp/switches', json={'expectedVersion': 9, 'flags': {'payEnabled': False}})
self.assertEqual(response.status_code, 409)
self.assertEqual(client.put('/api/admin/weapp/switches', json={'expectedVersion': 10, 'flags': {'payEnabled': False}}).status_code, 200)

View File

@ -7,6 +7,7 @@ import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from unittest.mock import AsyncMock, Mock
from types import SimpleNamespace
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "services"))
@ -15,6 +16,19 @@ from ebook_svc.services.public_config_snapshot import PublicConfigSnapshot
class PublicConfigSnapshotTests(unittest.TestCase):
def test_websocket_disconnect_cancels_output_task(self):
router = self.load_router()
from fastapi import WebSocketDisconnect
async def run():
queue = asyncio.Queue()
fanout = SimpleNamespace(register=lambda: queue, unregister=Mock())
ws = SimpleNamespace(accept=AsyncMock(), send_text=AsyncMock(), receive_text=AsyncMock(side_effect=WebSocketDisconnect()), close=AsyncMock())
with patch.object(router, 'fanout', fanout), patch.object(router, 'read_config_meta', return_value={'version': 1}), patch.object(router, 'notify_config_changed', side_effect=lambda meta, **kwargs: meta):
await asyncio.wait_for(router.public_remote_config_ws(ws), timeout=1)
fanout.unregister.assert_called_once_with(queue)
self.assertFalse(any('pump_out' in task.get_coro().__qualname__ for task in asyncio.all_tasks()))
asyncio.run(run())
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
@ -85,6 +99,8 @@ class PublicConfigSnapshotTests(unittest.TestCase):
self.assertEqual(response.headers["access-control-allow-origin"], "*")
self.assertEqual({route.path for route in router.router.routes}, {
"/api/config", "/api/ebook/config", "/api/config/meta", "/api/ebook/config/meta",
"/api/config/pull", "/api/ebook/config/pull", "/api/config/stream", "/api/ebook/config/stream",
"/api/config/ws", "/api/ebook/config/ws",
})
def test_meta_handles_malformed_version_without_server_error(self):

View File

@ -10,15 +10,12 @@ from fastapi import FastAPI
from fastapi.testclient import TestClient
from social_svc import store
from social_svc.routers.api import router
from pb_fixture import isolate_social
class SocialApiTests(unittest.TestCase):
def setUp(self):
directory = tempfile.TemporaryDirectory()
self.addCleanup(directory.cleanup)
override = patch.object(store, 'SOCIAL_DB_PATH', Path(directory.name) / 'social.db')
override.start()
self.addCleanup(override.stop)
self.pb = isolate_social(self)
publish = patch('social_svc.routers.api.publish_chat_message', new_callable=AsyncMock)
publish.start()
self.addCleanup(publish.stop)
@ -43,6 +40,17 @@ class SocialApiTests(unittest.TestCase):
self.assertEqual(self.client.post(url, json={'text': ' '}, headers=self.headers).status_code, 400)
self.assertEqual(self.client.post(url, json={'text': 'Hello'}).status_code, 400)
def test_message_replay_survives_exhausted_trial(self):
url = '/api/social/v1/channels/general/messages'
body = {'author': 'Name', 'text': 'Hello', 'clientId': 'retry-after-quota'}
first = self.client.post(url, json=body, headers=self.headers)
self.assertEqual(first.status_code, 200)
with patch('social_svc.trial_gate.assert_chat_trial_ok', side_effect=ValueError('trial exhausted')):
replay = self.client.post(url, json=body, headers=self.headers)
self.assertEqual(replay.status_code, 200)
self.assertEqual(replay.json(), first.json())
self.assertEqual(self.client.post(url, json={**body, 'clientId': 'new'}, headers=self.headers).status_code, 402)
def test_application_retry_and_whitespace_validation(self):
url = '/api/social/v1/gigs/project/apply'
body = {'name': 'Name', 'contact': 'Contact', 'requestId': 'same'}

View File

@ -1,4 +1,4 @@
"""Social regressions use a temporary SQLite database; no production app startup."""
"""Social regressions exercise the current PocketBase adapter in isolation."""
import sys
import tempfile
import unittest
@ -7,26 +7,23 @@ from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'services'))
from social_svc import store
from pb_fixture import isolate_social
class SocialStoreTests(unittest.TestCase):
def setUp(self):
directory = tempfile.TemporaryDirectory()
self.addCleanup(directory.cleanup)
override = patch.object(store, 'SOCIAL_DB_PATH', Path(directory.name) / 'social.db')
override.start()
self.addCleanup(override.stop)
self.pb = isolate_social(self)
store.init_db()
def test_recent_history_is_chronological_even_with_equal_timestamps(self):
with patch.object(store, '_now', return_value='2026-11-02T00:00:00.000Z'):
with patch('social_svc.pb_data._now', return_value='2026-11-02T00:00:00.000Z'):
for i in range(125):
store.add_message('lobby', 'Guest', str(i), 'guest')
self.assertEqual([m['text'] for m in store.list_messages('lobby')], [str(i) for i in range(25, 125)])
self.assertEqual(store.list_messages('other'), [])
def test_message_replay_is_idempotent_and_preserves_time(self):
with patch.object(store, '_now', return_value='first'):
with patch('social_svc.pb_data._now', return_value='first'):
first = store.add_message('lobby', 'Guest', 'hello', 'guest', 'request1')
self.assertEqual(store.add_message('lobby', 'Guest', 'hello', 'guest', 'request1'), first)
self.assertEqual(len(store.list_messages('lobby')), 1)
@ -52,13 +49,13 @@ class SocialStoreTests(unittest.TestCase):
store.add_gig_app('gig', 'Name', 'Changed', 'Note', 'guest', 'key')
second = store.add_gig_app('other', 'Name', 'Contact', 'Note', 'guest', 'key')
self.assertNotEqual(first['id'], second['id'])
with store.db() as conn:
self.assertEqual(conn.execute('SELECT COUNT(*) FROM gig_apps').fetchone()[0], 2)
self.assertEqual(len(self.pb.list_all('social_gig_apps')), 2)
def test_roster_round_trip_isolated_by_guest(self):
profile = dict(name='Name', title='Designer', city='Dali', phone='private',
linktree='https://example.invalid', skills='Design', bio='Hello')
saved = store.upsert_roster('one', profile)
saved.pop('isFirstProfile', None)
self.assertEqual(store.get_roster('one'), saved)
self.assertIsNone(store.get_roster('two'))
store.init_db()
@ -67,13 +64,10 @@ class SocialStoreTests(unittest.TestCase):
def test_existing_tables_and_rows_survive_reinitialization(self):
message = store.add_message('lobby', 'Guest', 'existing', 'guest')
review = store.add_review('cafe', 'Guest', 4, 'Good', '', 'guest')
with store.db() as conn:
before = list(conn.execute("SELECT name, sql FROM sqlite_master WHERE type='table' ORDER BY name"))
before = self.pb.list_all('social_cafe_reviews')
store.init_db()
store.add_message('lobby', 'Guest', 'new', 'guest', 'key')
with store.db() as conn:
after = list(conn.execute("SELECT name, sql FROM sqlite_master WHERE type='table' ORDER BY name"))
self.assertEqual([tuple(row) for row in before], [tuple(row) for row in after])
self.assertEqual(before, self.pb.list_all('social_cafe_reviews'))
self.assertEqual(store.list_messages('lobby')[0]['id'], message['id'])
self.assertEqual(store.list_reviews('cafe')[0]['id'], review['id'])

View File

@ -6,6 +6,8 @@
## 能力
2026-11 升级:响应式深浅主题、可搜索导航、移动菜单键盘操作、路由错误恢复;新增 `/:lane/operations` 服务资源监控。配置页显示实时版本并阻止过期版本覆盖;订单分页、状态识别与安全 CSV 导出已加强。线上验收与回滚见 [平台升级记录](../../../docs/platform-upgrade-2026-11.md)。
流程:登录 → **全屏选模块** → 进入该模块壳。
| 页 | 路径 | 说明 |

View File

@ -4,10 +4,13 @@
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, viewport-fit=cover, maximum-scale=1"
content="width=device-width, initial-scale=1.0, viewport-fit=cover"
/>
<meta name="theme-color" content="#0c0c0f" />
<meta name="color-scheme" content="dark" />
<meta name="color-scheme" content="dark light" />
<script>
try { const theme = localStorage.getItem('nomadro_admin_theme') === 'light' ? 'light' : 'dark'; document.documentElement.dataset.theme = theme; document.documentElement.style.colorScheme = theme } catch {}
</script>
<meta name="description" content="Nomadro 游民社区运营后台 · admin.nomadro.com" />
<title>Nomadro · 社区运营台</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />

View File

@ -1,18 +1,20 @@
import { lazy, Suspense } from 'react'
import { Navigate, Route, Routes, useParams } from 'react-router-dom'
import { getToken } from './api/client'
import { readLane } from './lib/lane'
import Login from './pages/Login'
import ModuleSelect from './pages/ModuleSelect'
import WebLayout from './components/WebLayout'
import Docs from './pages/Docs'
import Switches from './pages/Switches'
import Events from './pages/Events'
import Orders from './pages/Orders'
import Users from './pages/Users'
import Ntfy from './pages/Ntfy'
import Social from './pages/Social'
import SocialDetail from './pages/SocialDetail'
import Blog from './pages/Blog'
const Docs = lazy(() => import('./pages/Docs'))
const Switches = lazy(() => import('./pages/Switches'))
const Events = lazy(() => import('./pages/Events'))
const Orders = lazy(() => import('./pages/Orders'))
const Users = lazy(() => import('./pages/Users'))
const Ntfy = lazy(() => import('./pages/Ntfy'))
const Social = lazy(() => import('./pages/Social'))
const SocialDetail = lazy(() => import('./pages/SocialDetail'))
const Blog = lazy(() => import('./pages/Blog'))
const Operations = lazy(() => import('./pages/Operations'))
import LaneHub, { type LaneKey } from './pages/LaneHub'
/**
@ -42,7 +44,7 @@ function HomeRedirect() {
export default function App() {
return (
<Routes>
<Suspense fallback={<div className="com-empty" role="status">正在加载工作区…</div>}><Routes>
<Route path="/login" element={<Login />} />
<Route
@ -75,6 +77,7 @@ export default function App() {
>
<Route index element={<Navigate to="social/overview" replace />} />
<Route path="audience" element={<LaneHome />} />
<Route path="operations" element={<Operations />} />
<Route path="switches" element={<Switches />} />
<Route path="social" element={<Navigate to="overview" replace />} />
<Route path="social/overview" element={<Social />} />
@ -128,6 +131,6 @@ export default function App() {
<Route path="/docs" element={<Navigate to="/" replace />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</Routes></Suspense>
)
}

View File

@ -16,22 +16,43 @@ export function clearToken() {
}
export async function api<T = unknown>(path: string, init: RequestInit = {}): Promise<T> {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
...(init.headers as Record<string, string> | undefined),
const headers = new Headers(init.headers)
if (init.body && !(init.body instanceof FormData) && !headers.has('Content-Type')) {
headers.set('Content-Type', 'application/json')
}
const token = getToken()
if (token) headers.Authorization = `Bearer ${token}`
if (token) headers.set('Authorization', `Bearer ${token}`)
const res = await fetch(`${API_BASE}${path}`, { ...init, headers })
const timeout = new AbortController()
const timer = window.setTimeout(() => timeout.abort(), 20000)
const abort = () => timeout.abort()
init.signal?.addEventListener('abort', abort, { once: true })
if (init.signal?.aborted) timeout.abort()
try {
const res = await fetch(`${API_BASE}${path}`, { ...init, headers, signal: timeout.signal, cache: 'no-store' })
if (res.status === 401) {
clearToken()
if (!path.includes('/login')) window.location.href = '/login'
if (!path.includes('/login')) {
sessionStorage.setItem('nomadro_admin_return', window.location.pathname + window.location.search)
window.location.replace('/login')
}
}
const data = await res.json().catch(() => ({}))
if (!res.ok) {
const err = data as { detail?: string; message?: string }
throw new Error(err.detail || err.message || '请求失败')
const err = data as { detail?: unknown; message?: string }
const detail = typeof err.detail === 'string' ? err.detail : Array.isArray(err.detail)
? err.detail.map((item: { msg?: string }) => item.msg || '参数错误').join(';') : ''
throw new Error(detail || err.message || `请求失败(${res.status})`)
}
if (res.status !== 204 && !res.headers.get('content-type')?.includes('application/json')) {
throw new Error('服务返回异常,请稍后重试')
}
return data as T
} catch (error) {
if (timeout.signal.aborted && !init.signal?.aborted) throw new Error('请求超时,请刷新重试;保存操作请先确认结果')
throw error
} finally {
window.clearTimeout(timer)
init.signal?.removeEventListener('abort', abort)
}
}

View File

@ -0,0 +1,11 @@
import { Component, type ErrorInfo, type ReactNode } from 'react'
export default class ErrorBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
state = { failed: false }
static getDerivedStateFromError() { return { failed: true } }
componentDidCatch(error: Error, info: ErrorInfo) { console.error('Admin render failed', error, info.componentStack) }
render() {
if (this.state.failed) return <div className="com-empty" role="alert"><h1>页面暂时无法显示</h1><p>请重新加载页面,再继续操作。</p><button className="com-btn" onClick={() => window.location.reload()}>重新加载</button></div>
return this.props.children
}
}

View File

@ -1,4 +1,4 @@
import { useEffect, useMemo, useState } from 'react'
import { useEffect, useMemo, useRef, useState } from 'react'
import { NavLink, Outlet, useLocation, useNavigate, useParams } from 'react-router-dom'
import { clearToken } from '../api/client'
import { writeLane } from '../lib/lane'
@ -20,6 +20,7 @@ function buildNav(lane: LaneKey): NavGroup[] {
id: 'today',
label: '今日',
items: [
{ to: `${p}/operations`, label: '服务与资源', hint: '实时' },
{ to: `${s}/overview`, end: true, label: '指挥台', hint: '总览' },
{ to: `${s}/joins`, label: '加入线索' },
{ to: `${s}/liveness`, label: '自拍确认' },
@ -101,8 +102,44 @@ export default function WebLayout() {
const meta = LANE_META[lane]
const groups = useMemo(() => buildNav(lane), [lane])
const [open, setOpen] = useState(false)
const [query, setQuery] = useState('')
const searchRef = useRef<HTMLInputElement>(null)
const [online, setOnline] = useState(navigator.onLine)
const [theme, setTheme] = useState(() => document.documentElement.dataset.theme || 'dark')
const visibleGroups = groups.map(group => ({ ...group, items: group.items.filter(item =>
`${group.label} ${item.label}`.toLowerCase().includes(query.trim().toLowerCase())) })).filter(group => group.items.length)
const pageTitle = titleFromPath(lane, pathname)
useEffect(() => {
document.title = `${pageTitle} · Nomadro 运营台`
}, [pageTitle])
useEffect(() => {
const update = () => setOnline(navigator.onLine)
const keydown = (event: KeyboardEvent) => {
if (event.key === 'Escape') setOpen(false)
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'k') {
event.preventDefault(); setOpen(window.matchMedia('(max-width: 860px)').matches); searchRef.current?.focus()
}
}
window.addEventListener('online', update)
window.addEventListener('offline', update)
window.addEventListener('keydown', keydown)
return () => {
window.removeEventListener('online', update)
window.removeEventListener('offline', update)
window.removeEventListener('keydown', keydown)
}
}, [])
function toggleTheme() {
const next = theme === 'dark' ? 'light' : 'dark'
document.documentElement.dataset.theme = next
document.documentElement.style.colorScheme = next
localStorage.setItem('nomadro_admin_theme', next)
setTheme(next)
}
useEffect(() => {
writeLane(lane)
}, [lane])
@ -113,8 +150,21 @@ export default function WebLayout() {
useEffect(() => {
document.body.style.overflow = open ? 'hidden' : ''
const main = document.getElementById('main-content')
if (open) main?.setAttribute('inert', '')
else main?.removeAttribute('inert')
const trap = (event: KeyboardEvent) => {
if (event.key !== 'Tab' || !open) return
const elements = Array.from(document.querySelectorAll<HTMLElement>('.com-topbar-menu, .com-side button, .com-side a, .com-side input')).filter(el => !el.hasAttribute('disabled') && el.offsetParent !== null)
const first = elements[0], last = elements[elements.length - 1]
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus() }
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus() }
}
document.addEventListener('keydown', trap)
return () => {
document.body.style.overflow = ''
main?.removeAttribute('inert')
document.removeEventListener('keydown', trap)
}
}, [open])
@ -126,12 +176,14 @@ export default function WebLayout() {
function switchLane(next: LaneKey) {
if (next === lane) return
writeLane(next)
const rest = pathname.replace(/^\/(cn|intl)/, '') || '/social/overview'
// Detail IDs are tied to their audience; enter the list when switching lanes.
const rest = pathname.replace(/^\/(cn|intl)/, '').replace(/(\/social\/[^/]+)\/[^/]+$/, '$1') || '/social/overview'
nav(`/${next}${rest.startsWith('/') ? rest : `/${rest}`}`)
}
return (
<div className={`com-shell com-shell--${lane}${open ? ' com-shell--nav-open' : ''}`}>
<a className="com-skip" href="#main-content">跳至主要内容</a>
<header className="com-topbar">
<button
type="button"
@ -180,7 +232,7 @@ export default function WebLayout() {
/>
)}
<aside className="com-side" aria-hidden={!open}>
<aside className="com-side">
<div className="com-logo">
<span className="com-mark">N</span>
<div>
@ -208,9 +260,11 @@ export default function WebLayout() {
</button>
</div>
<p className="com-lane-hint">{meta.sub}</p>
<div className="com-nav-search"><input ref={searchRef} type="search" aria-label="搜索后台功能" placeholder="搜索功能… Ctrl K" value={query} onChange={e => setQuery(e.target.value)} /></div>
<nav className="com-nav" aria-label="后台导航">
{groups.map((group) => (
{visibleGroups.length === 0 && <p className="com-muted">没有匹配的功能</p>}
{visibleGroups.map((group) => (
<div key={group.id} className="com-nav-group">
<div className="com-nav-group-label">{group.label}</div>
{group.items.map((item) => (
@ -229,6 +283,7 @@ export default function WebLayout() {
</nav>
<div className="com-side-foot">
<button className="com-logout" type="button" onClick={toggleTheme} aria-label={theme === 'dark' ? '切换浅色主题' : '切换深色主题'}>{theme === 'dark' ? '☀ 浅色模式' : '◐ 深色模式'}</button>
<a
className="com-side-link"
href="https://nomadro.com/social"
@ -243,8 +298,10 @@ export default function WebLayout() {
</div>
</aside>
<main className="com-main">
<Outlet />
<main className="com-main" id="main-content" tabIndex={-1}>
<div className="com-workspace-bar"><div><span className="com-workspace-label">NOMADRO / WORKSPACE</span><p>{meta.title}受众 <span>/</span> {pageTitle}</p></div><span className={`com-connection${online ? '' : ' is-offline'}`} role="status"><i />{online ? '网络已连接' : '网络已断开'}</span></div>
{!online && <div className="com-toast com-toast-err" role="alert">网络已断开,请恢复连接后继续保存操作。</div>}
<Outlet key={lane} />
</main>
</div>
)

View File

@ -0,0 +1,13 @@
/** Spreadsheet formulas must not execute when exported user input is opened. */
export function downloadCsv(name: string, rows: unknown[][]) {
const escape = (value: unknown) => {
let text = String(value ?? '')
if (/^[\s]*[=+@\-]/.test(text)) text = `'${text}`
return `"${text.replace(/"/g, '""')}"`
}
const content = '\ufeff' + rows.map(row => row.map(escape).join(',')).join('\r\n')
const url = URL.createObjectURL(new Blob([content], { type: 'text/csv;charset=utf-8' }))
const link = document.createElement('a')
link.href = url; link.download = name; link.click()
window.setTimeout(() => URL.revokeObjectURL(url), 1000)
}

View File

@ -0,0 +1,11 @@
const PAID = new Set(['paid', 'success', 'succeeded', 'completed', 'trade_success', 'trade_finished'])
const PENDING = new Set(['pending', 'created', 'waiting', 'wait_buyer_pay', 'unpaid', 'notpay'])
export function orderState(status: string): 'paid' | 'pending' | 'refunded' | 'cancelled' | 'failed' | 'unknown' {
const value = (status || '').trim().toLowerCase()
if (PAID.has(value)) return 'paid'
if (PENDING.has(value)) return 'pending'
if (['refund', 'refunded', 'refund_success'].includes(value)) return 'refunded'
if (['cancel', 'cancelled', 'canceled', 'closed', 'trade_closed'].includes(value)) return 'cancelled'
if (['fail', 'failed', 'error', 'payerror'].includes(value)) return 'failed'
return 'unknown'
}

View File

@ -0,0 +1,44 @@
import { useEffect, useState } from 'react'
import { API_BASE, api } from '../api/client'
export type ConfigMeta = { version: number; updatedAt: string }
/** One subscription per mounted consumer; polling also covers proxy/SSE failures. */
export function useConfigLive() {
const [meta, setMeta] = useState<ConfigMeta | null>(null)
const [connected, setConnected] = useState(false)
useEffect(() => {
const controller = new AbortController()
let stream: EventSource | null = null
let pending = false
const accept = (data: ConfigMeta) => {
if (!controller.signal.aborted && Number.isFinite(data.version)) setMeta(data)
}
const poll = async () => {
if (pending || document.hidden) return
pending = true
try { accept(await api<ConfigMeta>('/api/config/meta', { signal: controller.signal })) }
catch { /* Keep last confirmed metadata during outages. */ }
finally { pending = false }
}
if (typeof EventSource !== 'undefined') {
stream = new EventSource(`${API_BASE}/api/config/stream`)
stream.onopen = () => setConnected(true)
stream.onerror = () => setConnected(false)
stream.addEventListener('config', event => {
try { accept(JSON.parse((event as MessageEvent).data)) } catch { /* poll retries */ }
})
}
void poll()
const interval = window.setInterval(() => void poll(), 15000)
const refresh = () => void poll()
window.addEventListener('online', refresh)
document.addEventListener('visibilitychange', refresh)
return () => {
controller.abort(); stream?.close(); window.clearInterval(interval)
window.removeEventListener('online', refresh)
document.removeEventListener('visibilitychange', refresh)
}
}, [])
return { meta, connected }
}

View File

@ -2,12 +2,14 @@ import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import App from './App'
import ErrorBoundary from './components/ErrorBoundary'
import './styles.css'
import './upgrade.css'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<BrowserRouter>
<App />
<ErrorBoundary><App /></ErrorBoundary>
</BrowserRouter>
</React.StrictMode>,
)

View File

@ -180,14 +180,14 @@ export default function Events() {
) : null}
<div className="com-toolbar">
<select value={filter} onChange={(e) => setFilter(e.target.value)}>
<select aria-label="事件类型" value={filter} onChange={(e) => setFilter(e.target.value)}>
{FILTERS.map((f) => (
<option key={f || 'all'} value={f}>
{f || '全部事件类型'}
</option>
))}
</select>
<select value={clientFilter} onChange={(e) => setClientFilter(e.target.value)}>
<select aria-label="事件来源" value={clientFilter} onChange={(e) => setClientFilter(e.target.value)}>
{CLIENTS.map((c) => (
<option key={c || 'all'} value={c}>
{clientLabel(c)}

View File

@ -253,6 +253,7 @@ export default function LaneHub({ lane }: { lane: LaneKey }) {
<p>本轨默认渠道</p>
</div>
<select
aria-label="关注渠道"
className="com-select"
disabled={busy}
value={L.followChannel}

View File

@ -20,7 +20,9 @@ export default function Login() {
body: JSON.stringify({ username, password }),
})
setToken(data.token)
nav(`/${readLane()}/social/overview`)
const saved = sessionStorage.getItem('nomadro_admin_return') || ''
sessionStorage.removeItem('nomadro_admin_return')
nav(/^\/(cn|intl)(\/|$)/.test(saved) ? saved : `/${readLane()}/social/overview`, { replace: true })
} catch (ex: unknown) {
setErr(ex instanceof Error ? ex.message : '登录失败')
} finally {
@ -46,6 +48,8 @@ export default function Login() {
value={username}
onChange={(e) => setUsername(e.target.value)}
autoComplete="username"
required
maxLength={100}
/>
</label>
<label>
@ -55,10 +59,11 @@ export default function Login() {
value={password}
onChange={(e) => setPassword(e.target.value)}
autoComplete="current-password"
required
enterKeyHint="go"
/>
</label>
{err && <div className="error">{err}</div>}
{err && <div className="error" role="alert">{err}</div>}
<button type="submit" disabled={loading}>
{loading ? '进入中…' : '进入指挥台'}
</button>

View File

@ -55,8 +55,7 @@ export default function Ntfy() {
<div>
<h1>ntfy 通知</h1>
<p>
关键埋点 / 支付会自动推送。此处查看通路状态并可手动试推。订阅:{' '}
<code>ntfy.nomadro.cn</code>
查看通知通路状态;关键埋点和支付事件由服务端推送。
</p>
</div>
<button type="button" className="com-btn com-btn-ghost" onClick={load} disabled={loading}>

View File

@ -0,0 +1,47 @@
import { useCallback, useEffect, useState } from 'react'
import { api } from '../api/client'
type Usage = { totalBytes: number; usedBytes: number; usedPercent: number }
type Health = {
ok: boolean
checkedAt: string
checks: { name: string; ok: boolean; status: number | null; latencyMs: number }[]
resources: { disk: Usage; memory: Usage | null; loadAverage: number[] | null; cpuCount: number | null }
}
const gb = (bytes: number) => `${(bytes / 1024 ** 3).toFixed(1)} GB`
export default function Operations() {
const [data, setData] = useState<Health | null>(null)
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const load = useCallback(async (signal?: AbortSignal) => {
setLoading(true)
try {
const result = await api<Health>('/api/admin/ops/health', { signal })
if (!signal?.aborted) { setData(result); setError('') }
} catch (e) {
if (!signal?.aborted) setError(e instanceof Error ? e.message : '检查失败')
} finally { if (!signal?.aborted) setLoading(false) }
}, [])
useEffect(() => {
const controller = new AbortController()
void load(controller.signal)
const timer = window.setInterval(() => { if (!document.hidden) void load(controller.signal) }, 30000)
return () => { controller.abort(); window.clearInterval(timer) }
}, [load])
return <div className="com-page">
<header className="com-page-head com-page-head-row"><div><p className="com-kicker">SYSTEM / LIVE</p><h1>服务与资源</h1><p>美国生产环境 · 每 30 秒检查 · 隐藏页面时暂停刷新</p></div>
<button className="com-btn" disabled={loading} onClick={() => void load()}>{loading ? '检查中…' : '立即检查'}</button>
</header>
{error && <div className="com-toast com-toast-err" role="alert">{error} {data ? '下方保留上次检查结果。' : ''}</div>}
{data ? <>
<section className={`com-health-banner ${data.ok && !error ? 'is-healthy' : 'is-degraded'}`} role="status"><span className="com-status-dot" /><div><strong>{error ? '状态更新失败' : data.ok ? '核心服务运行正常' : '部分服务需要检查'}</strong><p>上次检查:{new Date(data.checkedAt).toLocaleString('zh-CN', { hour12: false })}</p></div></section>
<div className="com-health-grid">{data.checks.map(check => <article className="com-panel" key={check.name}><span className={`com-badge tone-${check.ok ? 'ok' : 'bad'}`}>{check.ok ? '可用' : '异常'}</span><h2>{check.name}</h2><strong className="com-health-value">{check.latencyMs}<small> ms</small></strong><p className="com-muted">{check.status ? `HTTP ${check.status}` : '连接失败或检查超时'}</p></article>)}</div>
<div className="com-health-grid">{(['memory', 'disk'] as const).map(key => {
const usage = data.resources[key]
return <article className="com-panel" key={key}><h2>{key === 'memory' ? '内存使用' : '磁盘使用'}</h2>{usage ? <><strong className="com-health-value">{usage.usedPercent}<small>%</small></strong><progress aria-label={key === 'memory' ? '内存使用率' : '磁盘使用率'} max={100} value={usage.usedPercent} /><p className="com-muted">{gb(usage.usedBytes)} / {gb(usage.totalBytes)}</p></> : <p className="com-muted">此环境暂不提供内存指标</p>}</article>
})}<article className="com-panel"><h2>系统负载</h2><strong className="com-health-value">{data.resources.loadAverage?.[0].toFixed(2) ?? '—'}</strong><p className="com-muted">1 / 5 / 15 分钟:{data.resources.loadAverage?.map(v => v.toFixed(2)).join(' / ') ?? '暂无指标'}</p><span className="com-badge">{data.resources.cpuCount ?? '—'} 个 CPU 核心</span></article></div>
<p className="com-muted">检查反映服务在机内的可达性;外部域名和 TLS 由上线验收单独验证。</p>
</> : <div className="com-empty" role="status">{loading ? '正在检查生产服务…' : '检查未完成,请重试。'}</div>}
</div>
}

View File

@ -1,5 +1,7 @@
import { useCallback, useEffect, useMemo, useState } from 'react'
import { api } from '../api/client'
import { orderState } from '../lib/orders'
import { downloadCsv } from '../lib/csv'
type Order = {
out_trade_no: string
@ -30,31 +32,29 @@ function shortId(id: string, n = 10) {
}
function statusLabel(status: string) {
const s = (status || '').toLowerCase()
if (s.includes('paid') || s.includes('success')) return '已支付'
if (s.includes('pend') || s.includes('creat') || s.includes('wait')) return '待支付'
if (s.includes('cancel')) return '已取消'
if (s.includes('fail')) return '失败'
if (s.includes('refund')) return '退款'
const s = orderState(status)
if (s === 'paid') return '已支付'
if (s === 'pending') return '待支付'
if (s === 'cancelled') return '已取消'
if (s === 'failed') return '失败'
if (s === 'refunded') return '退款'
return status || '未知'
}
function statusTone(status: string) {
const s = (status || '').toLowerCase()
if (s.includes('paid') || s.includes('success')) return 'ok'
if (s.includes('pend') || s.includes('creat') || s.includes('wait')) return 'warn'
if (s.includes('fail') || s.includes('cancel') || s.includes('refund')) return 'bad'
const s = orderState(status)
if (s === 'paid') return 'ok'
if (s === 'pending') return 'warn'
if (['failed', 'cancelled', 'refunded'].includes(s)) return 'bad'
return 'muted'
}
function isPaid(status: string) {
const s = (status || '').toLowerCase()
return s.includes('paid') || s.includes('success')
return orderState(status) === 'paid'
}
function isPending(status: string) {
const s = (status || '').toLowerCase()
return s.includes('pend') || s.includes('creat') || s.includes('wait')
return orderState(status) === 'pending'
}
export default function Orders() {
@ -63,6 +63,9 @@ export default function Orders() {
const [err, setErr] = useState('')
const [q, setQ] = useState('')
const [tab, setTab] = useState<StatusTab>('all')
const [page, setPage] = useState(1)
const pageSize = 50
useEffect(() => setPage(1), [q, tab, orders])
const load = useCallback(() => {
setLoading(true)
@ -160,8 +163,13 @@ export default function Orders() {
type="search"
value={q}
placeholder="搜索单号 / openid / book_id"
aria-label="搜索订单"
onChange={(e) => setQ(e.target.value)}
/>
<button type="button" className="com-btn" disabled={loading || !filtered.length} onClick={() => downloadCsv(`nomadro-orders-${new Date().toISOString().slice(0, 10)}.csv`, [
['时间', '单号', '用户', '商品', '金额(元)', '状态', '发货'],
...filtered.map(order => [fmtTime(order.created_at), order.out_trade_no, order.openid, order.book_id, (order.amount_fen / 100).toFixed(2), statusLabel(order.status), order.delivered ? '已发' : '未发']),
])}>导出筛选结果</button>
</div>
<div className="com-table-wrap">
@ -179,13 +187,13 @@ export default function Orders() {
</tr>
</thead>
<tbody>
{filtered.map((o) => (
{filtered.slice((page - 1) * pageSize, page * pageSize).map((o) => (
<tr key={o.out_trade_no}>
<td>{fmtTime(o.created_at)}</td>
<td>
<code>{shortId(o.out_trade_no, 14)}</code>
<code title={o.out_trade_no}>{shortId(o.out_trade_no, 14)}</code>
</td>
<td>{shortId(o.openid)}</td>
<td title={o.openid}>{shortId(o.openid)}</td>
<td>{o.book_id === '__vip__' ? 'VIP' : o.book_id || '—'}</td>
<td>{fmtYuan(o.amount_fen || 0)}</td>
<td>
@ -202,6 +210,7 @@ export default function Orders() {
<div className="com-empty">{loading ? '加载中…' : '暂无订单'}</div>
)}
</div>
<div className="com-pagination"><span>匹配 {filtered.length} 条 · 第 {page} / {Math.max(1, Math.ceil(filtered.length / pageSize))} 页</span><button className="com-btn" disabled={page <= 1} onClick={() => setPage(p => p - 1)}>上一页</button><button className="com-btn" disabled={page * pageSize >= filtered.length} onClick={() => setPage(p => p + 1)}>下一页</button></div>
</div>
)
}

View File

@ -127,7 +127,7 @@ function Donut({
/>
)
})}
<text x="60" y="58" textAnchor="middle" fill="#f8fafc" fontSize="16" fontWeight="700">
<text x="60" y="58" textAnchor="middle" fill="var(--text)" fontSize="16" fontWeight="700">
{total}
</text>
<text x="60" y="74" textAnchor="middle" fill="#94a3b8" fontSize="9">
@ -511,6 +511,7 @@ export default function Social() {
</button>
</div>
<textarea
aria-label="社区目录 JSON 配置"
className="com-pre"
style={{ width: '100%', minHeight: 420, resize: 'vertical', fontFamily: 'ui-monospace, monospace' }}
value={catalogJson}

View File

@ -4,6 +4,7 @@
*/
import { useCallback, useEffect, useMemo, useState } from 'react'
import { api } from '../api/client'
import { useConfigLive } from '../lib/useConfigLive'
type Mod = { enabled: boolean; title: string; tabLabel?: string; note?: string }
@ -112,6 +113,7 @@ function Switch({
}
export default function Switches() {
const live = useConfigLive()
const [cfg, setCfg] = useState<SwitchesCfg | null>(null)
const [busy, setBusy] = useState(false)
const [msg, setMsg] = useState('')
@ -169,7 +171,7 @@ export default function Switches() {
try {
const data = await api<SwitchesCfg>('/api/admin/weapp/switches', {
method: 'PUT',
body: JSON.stringify(body),
body: JSON.stringify({ ...body, expectedVersion: cfg?.version }),
})
setCfg(data)
setDraftCopy({
@ -196,7 +198,6 @@ export default function Switches() {
setMsg(okHint)
} catch (e: unknown) {
setErr(e instanceof Error ? e.message : '保存失败')
await load().catch(() => undefined)
} finally {
setBusy(false)
}
@ -224,7 +225,7 @@ export default function Switches() {
<header className="com-page-head">
<h1>动态开关</h1>
<p>
页面显隐、功能 flag、VIP 入口与文案。写入 remote-config,Web 端热更新。
.com 全站共享配置:页面显隐、功能、VIP 入口与文案。保存后前台实时更新;受众专属文案请到「受众设置」。
</p>
<div className="com-chip-row">
<span className="com-chip">版本 v{cfg.version ?? '—'}</span>
@ -238,6 +239,9 @@ export default function Switches() {
{msg ? <div className="com-toast com-toast-ok">{msg}</div> : null}
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
<div className="com-config-live" role="status"><span className={`com-status-dot${live.connected ? '' : ' is-polling'}`} />{live.connected ? '实时配置通道已连接' : '配置轮询兜底中'}<span>服务端 v{live.meta?.version ?? '—'} · 当前编辑 v{cfg.version ?? '—'}</span></div>
{live.meta && cfg.version != null && live.meta.version !== cfg.version && <div className="com-toast">配置已在其他页面更新。请刷新后再保存,避免覆盖新配置。<button className="com-btn" disabled={busy} onClick={() => { if (window.confirm('刷新将放弃当前未保存的修改,是否继续?')) void load().catch(e => setErr(String(e))) }}>加载最新配置</button></div>}
<nav className="com-tabs" aria-label="开关分类">
{TABS.map((t) => (
<button
@ -336,6 +340,7 @@ export default function Switches() {
<p>popup=弹窗 · vip=跳会员页</p>
</div>
<select
aria-label="加群行为"
className="com-select"
disabled={busy}
value={cfg.flags.joinGroupAction || 'vip'}
@ -441,8 +446,8 @@ export default function Switches() {
disabled={busy}
onClick={() => {
const yuan = Number(priceYuan)
if (!Number.isFinite(yuan) || yuan < 0) {
setErr('价格无效')
if (!/^\d+(\.\d{1,2})?$/.test(priceYuan.trim()) || !Number.isFinite(yuan) || yuan < 0 || yuan > 1000000) {
setErr('请填写 0–1,000,000 元之间的价格,最多两位小数;免费请明确填写 0')
return
}
const fen = Math.round(yuan * 100)

View File

@ -0,0 +1,146 @@
/* Shared operations workspace; portal styles are deliberately separate. */
:root {
--bg: #0b1018;
--panel: #121a26;
--panel-2: #192435;
--line: #273347;
--text: #eaf0f8;
--muted: #9daec5;
--accent: #f6b44b;
--accent-2: #64c9ed;
--side-w: 252px;
--radius: 14px;
--shadow: 0 8px 28px #00000020;
}
:root[data-theme='light'] {
--bg: #f3f6fa;
--panel: #fff;
--panel-2: #eaf0f7;
--line: #d5dfea;
--text: #16253a;
--muted: #536880;
--accent: #995b09;
--accent-2: #08688f;
--danger: #b42d3d;
--ok: #087759;
--shadow: 0 8px 28px #233c5910;
}
body { background: var(--bg); }
button, input, select, textarea { font: inherit; }
button, a, input, select, textarea { -webkit-tap-highlight-color: transparent; }
button { transition: background .15s, border-color .15s, box-shadow .15s; }
button:disabled { cursor: not-allowed; opacity: .55; }
:focus-visible { outline: 2px solid var(--accent-2); outline-offset: 3px; }
.com-skip { position: fixed; top: -80px; left: 16px; z-index: 100; padding: 14px; background: var(--panel); border: 2px solid var(--accent-2); border-radius: 8px; }
.com-skip:focus { top: 12px; }
.com-side { background: var(--panel); border-color: var(--line); padding: 24px 14px 16px; gap: 12px; backdrop-filter: none; }
.com-logo { padding-bottom: 10px; }
.com-mark, .com-topbar-mark, .login-mark { box-shadow: none; border-radius: 12px; }
.com-sub { font-size: 11px; letter-spacing: .04em; }
.com-lane-switch { background: var(--bg); border-color: var(--line); border-radius: 10px; }
.com-lane-switch button { color: var(--muted); min-height: 36px; border-radius: 7px; }
.com-lane-switch button.is-on { background: var(--panel-2); color: var(--text); box-shadow: 0 1px 4px #00000020; }
.com-lane-hint { margin: 0 6px; font-size: 11px; }
.com-nav-search input { width: 100%; border: 1px solid var(--line); border-radius: 9px; background: var(--bg); padding: 11px 12px; color: var(--text); font-size: 12px; min-height: 42px; }
.com-nav { scrollbar-width: thin; scrollbar-color: var(--line) transparent; padding-right: 3px; }
.com-nav-group { margin-bottom: 12px; }
.com-nav-group-label { color: var(--muted); font-size: 10px; letter-spacing: .12em; margin: 10px 10px 4px; }
.com-nav a { border-radius: 8px; min-height: 38px; padding: 9px 12px; font-size: 13px; border: 1px solid transparent; color: var(--muted); }
.com-nav a:hover { background: var(--panel-2); color: var(--text); }
.com-nav a.active { background: var(--panel-2); border-color: var(--line); color: var(--text); box-shadow: inset 3px 0 var(--accent); }
.com-nav-hint { color: var(--accent); font-size: 10px; }
.com-side-foot { border-color: var(--line); display: grid; grid-template-columns: 1fr 1fr; gap: 7px; }
.com-side-foot > :first-child { grid-column: 1 / -1; }
.com-side-link, .com-logout { min-height: 38px; font-size: 12px; border-radius: 8px; border-color: var(--line); }
.com-main { padding: 0 32px 60px; }
.com-workspace-bar { min-height: 90px; display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 26px; border-bottom: 1px solid var(--line); }
.com-workspace-label { color: var(--muted); font-size: 10px; font-weight: 600; letter-spacing: .14em; }
.com-workspace-bar p { margin: 7px 0 0; font-size: 12px; }
.com-workspace-bar p span { color: var(--muted); margin: 0 8px; }
.com-connection { display: flex; align-items: center; gap: 7px; font-size: 11px; color: var(--muted); white-space: nowrap; }
.com-connection i, .com-status-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--ok); flex-shrink: 0; }
.com-connection.is-offline i { background: var(--danger); }
.com-page { max-width: 1500px; margin: 0 auto; }
.com-page-head { margin-bottom: 24px; }
.com-page-head h1 { font-size: clamp(24px, 3vw, 32px); letter-spacing: -.035em; line-height: 1.25; }
.com-page-head p { color: var(--muted); line-height: 1.65; }
.com-kicker { font-size: 10px; letter-spacing: .15em; color: var(--accent) !important; margin: 0 0 6px; }
.com-panel, .com-stat, .com-table-wrap, .com-cmd-hero { background: var(--panel); border-color: var(--line); box-shadow: var(--shadow); border-radius: var(--radius); }
.com-panel { padding: 22px; }
.com-panel h2 { font-size: 15px; }
.com-stat { padding: 20px; position: relative; overflow: hidden; }
.com-stat::before { content: ''; position: absolute; height: 3px; left: 20px; right: 20px; top: 0; background: var(--line); }
.com-stat strong { color: var(--text); font-variant-numeric: tabular-nums; }
.com-stat-label { color: var(--muted); }
.com-cmd-hero { background: var(--panel); border-top: 3px solid var(--accent); padding: 26px; }
.com-cmd-card { background: var(--bg); border-color: var(--line); }
.com-cmd-card:hover { background: var(--panel-2); border-color: var(--accent); }
.com-cmd-card strong { color: var(--text); }
.com-table-wrap { overflow-x: auto; }
.com-table { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; }
.com-table th { background: var(--panel-2); color: var(--muted); font-size: 11px; letter-spacing: .025em; padding: 14px; white-space: nowrap; }
.com-table td { border-color: var(--line); padding: 14px; font-size: 12px; }
.com-table tbody tr:hover { background: var(--panel-2); }
.com-table code { color: var(--text); }
.com-btn, .com-toolbar input, .com-toolbar select, .com-field input, .com-field select, .com-field textarea { border-radius: 9px; border-color: var(--line); min-height: 42px; }
.com-toolbar input, .com-toolbar select, .com-field input, .com-field select, .com-field textarea { background: var(--bg); color: var(--text); }
.com-btn { background: var(--panel-2); color: var(--text); }
.com-btn:hover { border-color: var(--accent-2); }
.com-tabs { gap: 6px; padding: 4px; width: fit-content; max-width: 100%; border-radius: 10px; background: var(--panel-2); overflow-x: auto; }
.com-tab { border: none; color: var(--muted); border-radius: 7px; min-height: 38px; white-space: nowrap; }
.com-tab.is-on { background: var(--panel); color: var(--text); box-shadow: 0 2px 6px #00000010; }
.com-empty { padding: 60px 20px; text-align: center; color: var(--muted); }
.com-muted, .com-panel-desc { color: var(--muted); }
.com-health-banner { display: flex; align-items: center; gap: 16px; padding: 22px; background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); margin-bottom: 22px; }
.com-health-banner .com-status-dot { width: 12px; height: 12px; box-shadow: 0 0 0 5px color-mix(in srgb, var(--ok) 12%, transparent); }
.com-health-banner p { font-size: 12px; color: var(--muted); margin: 6px 0 0; }
.is-degraded .com-status-dot { background: var(--danger); box-shadow: none; }
.com-health-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; margin-bottom: 16px; }
.com-health-value { display: block; margin: 18px 0; font-size: 36px; font-weight: 600; letter-spacing: -.04em; font-variant-numeric: tabular-nums; }
.com-health-value small { font-size: 15px; font-weight: 400; color: var(--muted); }
.com-health-grid progress { width: 100%; height: 7px; accent-color: var(--accent-2); }
.com-pagination { display: flex; align-items: center; justify-content: flex-end; gap: 12px; margin-top: 18px; font-size: 12px; color: var(--muted); }
.com-config-live { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; padding: 12px 15px; margin-bottom: 18px; border: 1px solid var(--line); border-radius: 9px; background: var(--panel); font-size: 12px; }
.com-config-live > span:last-child { margin-left: auto; color: var(--muted); }
.com-status-dot.is-polling { background: var(--accent); }
.login-card { background: var(--panel); border-color: var(--line); padding: 36px; box-shadow: 0 24px 80px #00000030; width: min(460px, 100%); }
.login-card input { background: var(--bg); border-color: var(--line); }
.login-orbit { border-color: var(--line); }
.com-toast { border-radius: 10px; line-height: 1.6; }
:root[data-theme='light'] .com-topbar { background: var(--panel); border-color: var(--line); }
:root[data-theme='light'] .com-media, :root[data-theme='light'] .com-audit-card, :root[data-theme='light'] .com-timeline li, :root[data-theme='light'] .com-pre-sm { background: var(--bg); border-color: var(--line); }
:root[data-theme='light'] .com-badge.tone-ok { color: #087759; background: #e2f4ed; }
:root[data-theme='light'] .com-badge.tone-info { color: #075985; background: #e0f2fe; }
:root[data-theme='light'] .com-status.on { color: #087759; }
:root[data-theme='light'] .com-status.off,
:root[data-theme='light'] .com-switch-card.is-off p { color: var(--muted); }
:root[data-theme='light'] .com-blog-card { background: var(--panel); border-color: var(--line); }
:root[data-theme='light'] .com-switch-card.is-off,
:root[data-theme='light'] .com-blog-card.is-hidden { opacity: 1; }
:root[data-theme='light'] .com-badge.tone-warn { color: #935a0a; background: #fff0d3; }
:root[data-theme='light'] .com-badge.tone-bad { color: #b42d3d; background: #ffeaed; }
:root[data-theme='light'] .com-toast-err { color: #b42d3d; background: #ffeaed; }
:root[data-theme='light'] .com-chip { background: var(--panel); color: var(--muted); border-color: var(--line); }
:root[data-theme='light'] .com-chip-ok { background: #e2f4ed; color: #087759; }
:root[data-theme='light'] .com-select, :root[data-theme='light'] .com-textarea { background: var(--bg); color: var(--text); }
:root[data-theme='light'] .com-switch-card, :root[data-theme='light'] .com-hub-card, :root[data-theme='light'] .modsel-card { background: var(--panel); border-color: var(--line); }
:root[data-theme='light'] .com-flag-row { border-color: var(--line); }
.com-switch input:focus-visible + .com-switch-track { outline: 2px solid var(--accent-2); outline-offset: 4px; }
@media (max-width: 1100px) { .com-main { padding-inline: 22px; } .com-health-grid { gap: 12px; } }
@media (max-width: 860px) {
.com-main { padding: 0 16px 40px; }
.com-topbar { background: var(--panel); border-color: var(--line); }
.com-workspace-bar { min-height: 74px; margin-bottom: 20px; }
.com-connection { font-size: 10px; }
.com-nav a { min-height: 44px; }
.com-side { visibility: hidden; }
.com-shell--nav-open .com-side { visibility: visible; }
.com-health-grid { grid-template-columns: 1fr; }
.com-health-grid .com-panel { padding: 20px; }
.com-page-head-row { align-items: flex-start; gap: 14px; }
.com-cmd-hero { padding: 20px; }
.com-table td { padding: 12px; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation: none !important; transition: none !important; scroll-behavior: auto !important; }
}

View File

@ -0,0 +1,9 @@
# /etc/systemd/system/nomadro.service.d/20-runtime.conf
# Keep Next's default hostname: loopback binding breaks same-origin HTTPS rewrites.
[Service]
ExecStart=
ExecStart=/usr/bin/node /var/www/nomadro.cn/node_modules/next/dist/bin/next start --port 4003
TimeoutStopSec=20
KillMode=control-group
Restart=on-failure
RestartSec=3

View File

@ -0,0 +1,43 @@
# .com 平台升级与验收记录
本次已发布到 `https://nomadro.com`、`https://admin.nomadro.com`、`https://api.nomadro.com`,只操作美国服务器。`.cn`、小程序和冻结游戏未发布。门户保留现有视觉设计,修改集中在正确性、安全、故障恢复与业务联通;管理后台更新整体交互与主题。
## 已完成
- 门户:修复 TypeScript 错误并恢复构建类型校验;工作、通知、咖啡预约代理统一超时、取消与错误响应,正确处理 204;修正通知设置旧路径。
- 身份与支付:登录同步向 PocketBase 验证 token 及身份;未配置管理员时拒绝伪造会话;加入线索接口补管理员鉴权;支付确认检查订单归属、严格识别支付成功并检查持久化可用性。
- 聊天:PocketBase 消息使用按频道、访客、clientId 生成的稳定记录 ID;相同请求可重试,不同载荷返回 409;重试不重复消耗试用额度;历史读取最新一批后按时间正序展示。
- 实时配置:Next 与 Python 原子替换配置文件,保留权限;目录监听兼容文件原子替换;SSE/WS 断开清理订阅和任务;客户端超时、联网恢复与轮询兜底。后台支持实时版本显示和过期版本冲突提示。
- 管理后台:深浅主题持久化、响应式布局、导航搜索及 Ctrl-K、移动菜单焦点约束和 Escape 关闭、跳到内容链接、错误恢复、中文/国际轨切换状态清理。
- 经营表单:价格禁止空值误写成免费,校验小数位与范围;AdSense 配置字段服务端接受并验证;订单状态精确映射、分页与 CSV 公式注入防护;补齐筛选器和配置输入标签。
- 运维:新增 `/:lane/operations`,显示受保护的固定服务健康探测、延迟、内存和磁盘;API 客户端统一超时与登录恢复;路由分包;HTML 强制重新验证、内容哈希资源长期缓存。
## 验证与边界
源码清单覆盖 208 个页面文件、81 个 Next 接口文件、15 个管理页文件、311 个输入控件、2483 处 JSX 文案与 485 处 Python 路由声明,见 `artifacts/platform-upgrade/source-inventory.json`。这是静态清单,不能等同于每一项业务已端到端验收。
已完成的实际验证:
- `pnpm typecheck`、Next 生产构建和管理后台生产构建通过,关闭忽略类型错误选项。
- 24 个隔离后端测试通过,覆盖聊天幂等、试用额度重试、配置校验/冲突、健康探测与 WebSocket 任务释放,不写线上数据库。
- 线上门户 164 个可具体访问页面扫描:无 404、无 5xx;8 项未登录访问/支付负向检查均返回预期状态。
- 线上后台中文/国际轨共 52 个导航页面:无浏览器 JavaScript 异常、无 API 错误;主题持久化、搜索、移动布局、菜单开关检查通过。
- 线上 48 个只读管理 API:匿名均 401、登录后均成功。另 8 个需要实体参数或可能触发动作的 GET 未自动执行。
- 线上实时链路:保留原 offlineBadge 值提交一次配置,版本 79 → 80,门户、后台、API 三路 SSE 均收到 80,三路元信息一致;重复旧版本写入返回 409。未改变业务开关实际值。
- axe 检查 10 个代表页面的深浅主题共 20 个组合;结果见 `admin-accessibility.json`。发现的标签和浅色主题对比度问题均修复并复测。
真实扣款、外部通知发送、删除/封禁等破坏性动作未在线执行;依赖实际用户数据和第三方服务的完整旅程仍需持续验证。本记录不宣称所有功能已达到“完美”。
## 部署、故障处理与回滚
先在本机完成构建,再上传校验压缩包,保留回滚副本,验证公网 HTTPS 后记录成功。首次发布时公网根路径出现 500,已恢复旧构建并定位:Next 显式绑定 loopback 时,同源 HTTPS 重写被错误代理到内部 HTTP 端口。改为直接 Node 启动并使用默认 hostname 后,重新发布通过。
当前门户构建:`9RLnvAJBeFIveggBpiHzV`;最终发布 `20261104T163457Z`;对应回滚目录 `/var/backups/nomadro-upgrade/20261104T163457Z`(前一正常门户备份在 `20261104T162734Z`)。后端、社交和后台初始升级备份 `/var/backups/nomadro-upgrade/20261104T161951Z`。管理后台最终静态发布为 `20261104T163233Z`,HTML 备份 `/var/backups/nomadro-upgrade/admin-20261104T163233Z`;旧哈希资源保留,避免旧标签页加载失败。
美国机器门户目录名仍为 `/var/www/nomadro.cn`,不代表此次操作中国站。服务:`nomadro`(4003)、`nomadmini-api`(8010)、`nomadro-social`(8020)。生产 API 使用 `/opt/nomadmini/backend/app` 的兼容导入布局,不能直接覆盖为本地统一入口。
发布脚本:`scripts/deploy_platform_upgrade_com.py`、`scripts/deploy_portal_upgrade_com.py`、`scripts/deploy_admin_dist_com.py`。运行时 drop-in 源文件为 `apps/com/deploy/nomadro-runtime.conf`,不要添加 `--hostname 127.0.0.1`。公网首页、聊天、通知设置已纳入发布健康门槛。
门户回滚:停止 `nomadro`,保留故障 `.next`,从对应备份恢复 `next` 为运行目录 `.next`,恢复 `sources.tgz` 后启动并验证公网首页。后端可从初始备份 `backend.tgz` 恢复原路径后重启 API 与社交服务。后台可恢复备份 HTML(旧哈希资源仍在);初始完整后台副本也保留。Nginx 修改前已创建同目录时间戳备份,并经 `nginx -t` 验证后 reload。
所有测试报告位于 `artifacts/platform-upgrade/`。现有工作区的数据库改动与非本次临时文件未清理或覆盖。

View File

@ -45,10 +45,6 @@ const aliases = {
const nextConfig: NextConfig = {
poweredByHeader: false,
compress: true,
typescript: {
// 生产机内存紧;social/centrifugo 发版勿被无关 admin TS 卡死
ignoreBuildErrors: true,
},
experimental: {
externalDir: true,
optimizePackageImports: [

View File

@ -0,0 +1,48 @@
/** Source inventory, not a substitute for functional acceptance. */
import fs from 'node:fs';
import path from 'node:path';
import ts from 'typescript';
const root = process.cwd();
const output = path.join(root, 'artifacts/platform-upgrade');
fs.mkdirSync(output, { recursive: true });
function files(directory) {
return fs.readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
const name = path.join(directory, entry.name);
if (['node_modules', 'vendor', 'dist', '.next', '__pycache__'].includes(entry.name)) return [];
return entry.isDirectory() ? files(name) : [name];
});
}
const inventory = { generatedAt: new Date().toISOString(), pages: [], nextInterfaces: [], adminPages: [], fields: [], copy: [], pythonInterfaces: [] };
for (const dir of ['src', 'apps/com/admin/src']) for (const file of files(path.join(root, dir))) {
const relative = path.relative(root, file).replaceAll('\\', '/');
if (!/\.(ts|tsx)$/.test(file)) continue;
const text = fs.readFileSync(file, 'utf8');
const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, file.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
const line = node => source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;
if (/\/page\.tsx$/.test(relative)) inventory.pages.push({ file: relative, route: relative.replace('src/app', '').replace(/\/page\.tsx$/, '') || '/' });
if (/\/route\.ts$/.test(relative)) inventory.nextInterfaces.push({ file: relative, methods: [...new Set([...text.matchAll(/\b(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b/g)].map(match => match[1]))] });
if (relative.startsWith('apps/com/admin/src/pages/')) inventory.adminPages.push(relative);
function visit(node) {
if (ts.isJsxSelfClosingElement(node) || ts.isJsxOpeningElement(node)) {
const tag = node.tagName.getText(source);
if (['input', 'select', 'textarea'].includes(tag)) {
const attributes = Object.fromEntries(node.attributes.properties.filter(ts.isJsxAttribute).map(attr => [attr.name.getText(source), attr.initializer?.getText(source) ?? true]));
inventory.fields.push({ file: relative, line: line(node), tag, attributes });
}
}
if (ts.isJsxText(node) && node.text.trim()) inventory.copy.push({ file: relative, line: line(node), text: node.text.trim() });
ts.forEachChild(node, visit);
}
visit(source);
}
for (const file of files(path.join(root, 'apps/api')).filter(file => file.endsWith('.py'))) {
const text = fs.readFileSync(file, 'utf8');
for (const match of text.matchAll(/@(\w+)\.(get|post|put|patch|delete|websocket)\(\s*["']([^"']+)/g)) {
inventory.pythonInterfaces.push({ file: path.relative(root, file).replaceAll('\\', '/'), line: text.slice(0, match.index).split('\n').length, method: match[2].toUpperCase(), path: match[3] });
}
}
fs.writeFileSync(path.join(output, 'source-inventory.json'), JSON.stringify(inventory, null, 2));
const summary = Object.fromEntries(Object.entries(inventory).filter(([,value]) => Array.isArray(value)).map(([key, value]) => [key, value.length]));
fs.writeFileSync(path.join(output, 'inventory-summary.json'), JSON.stringify(summary, null, 2));
console.log(JSON.stringify(summary));

View File

@ -0,0 +1,30 @@
"""Publish locally built admin assets before atomically replacing HTML."""
import json
import runpy
from datetime import datetime, timezone
from pathlib import Path
root = Path(__file__).resolve().parents[1]
client = runpy.run_path(str(root / 'apps/admin/deploy/_upload_next_us.py'))['connect']()
remote = '/www/wwwroot/admin.nomadro.com'
release = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
try:
_, output, error = client.exec_command(f'mkdir -p /var/backups/nomadro-upgrade/admin-{release} && cp {remote}/index.html /var/backups/nomadro-upgrade/admin-{release}/index.html')
if output.channel.recv_exit_status(): raise RuntimeError(error.read().decode())
with client.open_sftp() as sftp:
for path in (root / 'apps/com/admin/dist').rglob('*'):
if not path.is_file() or path.name == 'index.html': continue
target = remote + '/' + path.relative_to(root / 'apps/com/admin/dist').as_posix()
try: sftp.mkdir(str(Path(target).parent).replace('\\', '/'))
except OSError: pass
sftp.put(str(path), target)
sftp.put(str(root / 'apps/com/admin/dist/index.html'), remote + '/index.html.next')
_, output, error = client.exec_command(f'mv {remote}/index.html.next {remote}/index.html && curl -fsS --max-time 15 https://admin.nomadro.com/ >/dev/null')
if output.channel.recv_exit_status(): raise RuntimeError(error.read().decode())
path = root / 'artifacts/platform-upgrade/deployment.json'
report = json.loads(path.read_text())
report['adminFollowup'] = {'release': release, 'backup': f'/var/backups/nomadro-upgrade/admin-{release}', 'deployed': True}
path.write_text(json.dumps(report, indent=2), encoding='utf-8')
print('Admin deployed', release)
finally:
client.close()

View File

@ -0,0 +1,153 @@
"""Deploy locally validated artifacts to .com only, with retained rollback copies."""
from __future__ import annotations
import hashlib
import io
import json
import runpy
import sys
import tarfile
import tempfile
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.stdout.reconfigure(encoding='utf-8', errors='replace', line_buffering=True)
RELEASE = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
BACKUP = f'/var/backups/nomadro-upgrade/{RELEASE}'
STAGE = f'/var/www/nomadro.cn/.upgrade-{RELEASE}'
PORTAL = '/var/www/nomadro.cn'
ADMIN = '/www/wwwroot/admin.nomadro.com'
API_FILES = [
'routers/ops_admin.py', 'routers/public_config.py', 'routers/weapp_switches_admin.py',
'services/weapp_switches.py',
]
SOCIAL_FILES = ['pb_data.py', 'store.py', 'routers/api.py']
SOURCE_FILES = [
'next.config.ts', 'src/middleware.ts', 'src/lib/service-proxy.ts', 'src/lib/admin-auth.ts',
'src/lib/remote-config-live.ts', 'src/lib/remote-config-store.ts', 'src/lib/use-remote-config.ts',
'src/app/api/config/stream/route.ts', 'src/app/api/pay/confirm/route.ts',
'src/app/api/auth/sync-session/route.ts',
'src/app/api/portal/join-leads/route.ts', 'src/app/api/admin/social/ugc/join-leads/route.ts',
'src/app/api/work/v1/[[...path]]/route.ts', 'src/app/api/notify/v1/[[...path]]/route.ts',
'src/app/api/coffee/v1/[[...path]]/route.ts', 'src/modules/social/components/PeopleClient.tsx',
'src/modules/social/components/PlaceMapPreview.tsx', 'src/modules/social/components/SocialMapCanvas.tsx',
'src/modules/social/lib/phrases.ts', 'src/modules/work/lib/store.ts',
'src/modules/work/micro/custom-elements.d.ts',
]
def run(client, command, timeout=180):
_, stdout, stderr = client.exec_command(command, timeout=timeout)
output = stdout.read().decode('utf-8', 'replace')
error = stderr.read().decode('utf-8', 'replace')
code = stdout.channel.recv_exit_status()
if output.strip(): print(output.strip())
if error.strip(): print(error.strip(), file=sys.stderr)
if code: raise RuntimeError(f'remote step failed ({code})')
def main():
assert (ROOT / '.next/BUILD_ID').is_file(), 'build Next locally first'
assert (ROOT / 'apps/com/admin/dist/index.html').is_file(), 'build admin locally first'
build_id = (ROOT / '.next/BUILD_ID').read_text().strip()
client = runpy.run_path(str(ROOT / 'apps/admin/deploy/_upload_next_us.py'))['connect']()
mutations_started = False
with tempfile.TemporaryDirectory() as temporary:
package = Path(temporary) / 'upgrade.tgz'
with tarfile.open(package, 'w:gz') as archive:
def include(info):
if any(info.name == f'portal/.next/{part}' or info.name.startswith(f'portal/.next/{part}/') for part in ['cache', 'dev']): return None
if info.name.endswith('/lock'): return None
return info
archive.add(ROOT / '.next', arcname='portal/.next', filter=include)
for relative in SOURCE_FILES: archive.add(ROOT / relative, arcname='portal/' + relative)
archive.add(ROOT / 'apps/com/admin/dist', arcname='admin')
for relative in API_FILES:
text = (ROOT / 'apps/api/services/ebook_svc' / relative).read_text(encoding='utf-8').replace('ebook_svc.', 'app.')
blob = text.encode('utf-8')
entry = tarfile.TarInfo('api/' + relative); entry.size = len(blob); entry.mode = 0o644
archive.addfile(entry, io.BytesIO(blob))
for relative in SOCIAL_FILES:
archive.add(ROOT / 'apps/api/services/social_svc' / relative, arcname='social/' + relative)
digest = hashlib.sha256(package.read_bytes()).hexdigest()
print('release', RELEASE, 'build', build_id, 'packageMB', round(package.stat().st_size / 1024**2, 1))
sftp = client.open_sftp()
try:
sftp.put(str(package), f'/tmp/nomadro-upgrade-{RELEASE}.tgz')
finally: sftp.close()
targets = [f'/opt/nomadmini/backend/app/{name}' for name in API_FILES] + [f'{PORTAL}/apps/api/services/social_svc/{name}' for name in SOCIAL_FILES]
target_args = ' '.join(targets)
try:
run(client, f'''set -eu
echo '{digest} /tmp/nomadro-upgrade-{RELEASE}.tgz' | sha256sum -c -
mkdir -p {STAGE} {BACKUP}
tar -xzf /tmp/nomadro-upgrade-{RELEASE}.tgz -C {STAGE}
tar -czf {BACKUP}/backend.tgz {target_args}
cp -a {ADMIN} {BACKUP}/admin
cp /etc/nginx/sites-available/admin.nomadro.com.conf {BACKUP}/admin-nginx.conf
cp {PORTAL}/data/remote-config.json {BACKUP}/remote-config.json
python3 -m compileall -q {STAGE}/api {STAGE}/social
test -f {STAGE}/portal/.next/BUILD_ID
''')
mutations_started = True
for relative in API_FILES:
run(client, f'cp {STAGE}/api/{relative} /opt/nomadmini/backend/app/{relative}')
for relative in SOCIAL_FILES:
run(client, f'cp {STAGE}/social/{relative} {PORTAL}/apps/api/services/social_svc/{relative}')
# Source parity for the legacy API tree and repository service tree.
for relative in API_FILES:
source = ROOT / 'apps/api/services/ebook_svc' / relative
destination = f'{PORTAL}/apps/api/services/ebook_svc/{relative}'
sftp = client.open_sftp()
try: sftp.put(str(source), destination)
finally: sftp.close()
run(client, '''set -eu
cd /opt/nomadmini/backend
.venv/bin/python -c 'from app.routers import ops_admin,public_config,weapp_switches_admin; print("API imports OK")'
systemctl restart nomadmini-api nomadro-social
''')
run(client, f'''set -eu
cd {PORTAL}
systemctl stop nomadro
mv .next {BACKUP}/next
mv {STAGE}/portal/.next .next
cp -a {STAGE}/portal/. {PORTAL}/
if [ -f src/proxy.ts ]; then mv src/proxy.ts {BACKUP}/proxy.ts; fi
systemctl start nomadro
for attempt in $(seq 1 30); do
if curl --fail --silent --max-time 3 http://127.0.0.1:4003/api/health >/dev/null; then break; fi
sleep 1
done
curl --fail --silent --max-time 10 http://127.0.0.1:4003/api/health >/dev/null
curl --fail --silent --max-time 15 https://nomadro.com/ >/dev/null
curl --fail --silent --max-time 15 https://nomadro.com/social/chat >/dev/null
curl --fail --silent --max-time 15 https://nomadro.com/notifications/settings >/dev/null
curl --fail --silent --max-time 10 http://127.0.0.1:8010/health >/dev/null
curl --fail --silent --max-time 10 http://127.0.0.1:8020/health >/dev/null
cp -a {STAGE}/admin/assets/. {ADMIN}/assets/
cp {STAGE}/admin/index.html {ADMIN}/index.html.next
mv {ADMIN}/index.html.next {ADMIN}/index.html
systemctl is-active nomadro nomadmini-api nomadro-social nginx
''')
report = {'release': RELEASE, 'buildId': build_id, 'backup': BACKUP, 'stage': STAGE, 'sha256': digest, 'deployed': True}
(ROOT / 'artifacts/platform-upgrade/deployment.json').write_text(json.dumps(report, indent=2), encoding='utf-8')
print('DEPLOYED', json.dumps(report))
except Exception:
if mutations_started:
print('Rolling back runtime artifacts')
run(client, f'''set -eu
tar -xzf {BACKUP}/backend.tgz -C /
if [ -d {BACKUP}/next ]; then
systemctl stop nomadro
if [ -d {PORTAL}/.next ]; then mv {PORTAL}/.next {STAGE}/failed-next; fi
mv {BACKUP}/next {PORTAL}/.next
fi
cp -a {BACKUP}/admin/. {ADMIN}/
systemctl restart nomadmini-api nomadro-social nomadro
''')
raise
finally:
client.close()
if __name__ == '__main__': main()

View File

@ -0,0 +1,74 @@
"""Deploy the locally built portal only; retain a rollback and verify public HTTPS."""
import hashlib
import json
import runpy
import tarfile
import tempfile
from pathlib import Path
deployment = runpy.run_path(str(Path(__file__).with_name('deploy_platform_upgrade_com.py')))
ROOT, PORTAL, RELEASE = (deployment[key] for key in ['ROOT', 'PORTAL', 'RELEASE'])
run = deployment['run']
backup = deployment['BACKUP']
stage = deployment['STAGE']
client = runpy.run_path(str(ROOT / 'apps/admin/deploy/_upload_next_us.py'))['connect']()
try:
with tempfile.TemporaryDirectory() as temporary:
package = Path(temporary) / 'portal.tgz'
with tarfile.open(package, 'w:gz') as archive:
def include(info):
if any(info.name == f'.next/{part}' or info.name.startswith(f'.next/{part}/') for part in ['cache', 'dev']):
return None
return None if info.name.endswith('/lock') else info
archive.add(ROOT / '.next', arcname='.next', filter=include)
for source in deployment['SOURCE_FILES']:
archive.add(ROOT / source, arcname=source)
digest = hashlib.sha256(package.read_bytes()).hexdigest()
print('Uploading portal', RELEASE, round(package.stat().st_size / 1024**2, 1), 'MB', flush=True)
with client.open_sftp() as sftp:
sftp.put(str(package), f'/tmp/nomadro-portal-{RELEASE}.tgz')
run(client, f'''set -eu
echo '{digest} /tmp/nomadro-portal-{RELEASE}.tgz' | sha256sum -c -
mkdir -p {stage} {backup}
tar -xzf /tmp/nomadro-portal-{RELEASE}.tgz -C {stage}
cd {PORTAL}
tar -czf {backup}/sources.tgz {' '.join(deployment['SOURCE_FILES'])} 2>/dev/null || test -s {backup}/sources.tgz
cp -a /etc/systemd/system/nomadro.service.d {backup}/runtime
''')
try:
run(client, f'''set -eu
cd {PORTAL}
systemctl stop nomadro
mv .next {backup}/next
mv {stage}/.next .next
cp -a {stage}/. .
if [ -f src/proxy.ts ]; then mv src/proxy.ts {backup}/proxy.ts; fi
systemctl start nomadro
for attempt in $(seq 1 30); do
if curl -fsS --max-time 3 http://127.0.0.1:4003/api/health >/dev/null; then break; fi
sleep 1
done
curl -fsS --max-time 15 https://nomadro.com/ >/dev/null
curl -fsS --max-time 15 https://nomadro.com/social/chat >/dev/null
curl -fsS --max-time 15 https://nomadro.com/notifications/settings >/dev/null
systemctl is-active nomadro
cat .next/BUILD_ID
''')
except Exception:
run(client, f'''set -eu
systemctl stop nomadro
if [ -d {backup}/next ]; then
mv {PORTAL}/.next {stage}/failed-next
mv {backup}/next {PORTAL}/.next
fi
tar -xzf {backup}/sources.tgz -C {PORTAL}
systemctl start nomadro
''')
raise
path = ROOT / 'artifacts/platform-upgrade/deployment.json'
report = json.loads(path.read_text(encoding='utf-8'))
report['portal'] = {'release': RELEASE, 'buildId': (ROOT / '.next/BUILD_ID').read_text().strip(), 'backup': backup, 'sha256': digest, 'httpsHealthPassed': True}
path.write_text(json.dumps(report, indent=2), encoding='utf-8')
print('PORTAL DEPLOYED', json.dumps(report['portal']), flush=True)
finally:
client.close()

View File

@ -0,0 +1,31 @@
"""Keep admin HTML fresh and content-hashed assets cacheable on .com."""
import runpy
import shlex
from datetime import datetime, timezone
client = runpy.run_path('apps/admin/deploy/_upload_next_us.py')['connect']()
path = '/etc/nginx/sites-available/admin.nomadro.com.conf'
try:
with client.open_sftp() as sftp:
with sftp.open(path) as handle:
original = handle.read().decode()
updated = original.replace(
'location /assets/ { try_files $uri =404; expires 30d; }',
'location /assets/ { try_files $uri =404; add_header Cache-Control "public, max-age=31536000, immutable" always; add_header X-Content-Type-Options "nosniff" always; }')
updated = updated.replace(
'location / { try_files $uri $uri/ /index.html; }',
'location / { try_files $uri $uri/ /index.html; add_header Cache-Control "no-cache, must-revalidate" always; add_header X-Content-Type-Options "nosniff" always; add_header Referrer-Policy "strict-origin-when-cross-origin" always; }')
if updated == original:
print('Cache policy already installed')
else:
backup = path + '.backup-' + datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
with sftp.open(backup, 'w') as handle: handle.write(original)
with sftp.open(path, 'w') as handle: handle.write(updated)
_, output, error = client.exec_command('nginx -t && systemctl reload nginx')
code = output.channel.recv_exit_status()
if code:
with sftp.open(path, 'w') as handle: handle.write(original)
raise RuntimeError(error.read().decode())
print('Admin cache policy deployed; backup', backup)
finally:
client.close()

View File

@ -0,0 +1,31 @@
"""Read-only accessibility checks against representative production admin pages."""
import json
import re
from pathlib import Path
from playwright.sync_api import sync_playwright
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / 'artifacts/platform-upgrade'
credentials = re.search(r'`([^`]+)` / `([^`]+)`', (ROOT / 'apps/com/admin/README.md').read_text(encoding='utf-8'))
report = []
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page(viewport={'width': 1440, 'height': 1000})
page.goto('https://admin.nomadro.com/login')
page.locator('input[autocomplete=username]').fill(credentials[1])
page.locator('input[autocomplete=current-password]').fill(credentials[2])
page.locator('button[type=submit]').click()
page.wait_for_url(re.compile(r'.*/(cn|intl)/social/overview'))
for route in ['social/overview', 'switches', 'orders', 'users', 'events', 'ntfy', 'audience', 'social/catalog', 'operations', 'blog']:
for theme in ['dark', 'light']:
page.goto('https://admin.nomadro.com/intl/' + route, wait_until='domcontentloaded')
page.locator('.com-page').wait_for()
page.wait_for_timeout(900)
page.evaluate('(theme) => document.documentElement.setAttribute("data-theme", theme)', theme)
page.wait_for_timeout(250)
page.add_script_tag(path=str(OUT / 'axe.min.js'))
violations = page.evaluate('''async () => (await axe.run(document, {runOnly:{type:'tag',values:['wcag2a','wcag2aa','wcag21aa']}})).violations.map(v => ({id:v.id,impact:v.impact,description:v.description,nodes:v.nodes.map(n => ({target:n.target,summary:n.failureSummary}))}))''')
report.append({'route': route, 'theme': theme, 'violations': violations})
browser.close()
(OUT / 'admin-accessibility.json').write_text(json.dumps(report, indent=2), encoding='utf-8')
print(json.dumps({'pagesAndThemes': len(report), 'violations': [{'route': row['route'], 'theme': row['theme'], 'ids': [v['id'] for v in row['violations']]} for row in report if row['violations']]}))

View File

@ -0,0 +1,67 @@
"""Read-only browser acceptance for admin.com; credentials never enter reports."""
import json
import os
import re
import sys
from pathlib import Path
from playwright.sync_api import sync_playwright
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / 'artifacts/platform-upgrade'
OUT.mkdir(parents=True, exist_ok=True)
BASE = sys.argv[1] if len(sys.argv) > 1 else 'http://localhost:5174'
credentials = re.search(r'登录:`([^`]+)` / `([^`]+)`', (ROOT / 'apps/com/admin/README.md').read_text(encoding='utf-8'))
username = os.getenv('NOMADRO_ADMIN_USERNAME') or credentials.group(1)
password = os.getenv('NOMADRO_ADMIN_PASSWORD') or credentials.group(2)
report = {'base': BASE, 'pages': [], 'errors': [], 'responses': [], 'checks': []}
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context(viewport={'width': 1440, 'height': 1000}, device_scale_factor=1)
page = context.new_page()
page.on('pageerror', lambda error: report['errors'].append(str(error)))
page.on('response', lambda response: report['responses'].append({'url': response.url.split('?')[0], 'status': response.status}) if response.status >= 400 and '/api/' in response.url else None)
page.goto(BASE + '/login', wait_until='networkidle')
page.locator('input[autocomplete=username]').fill(username)
page.locator('input[autocomplete=current-password]').fill(password)
page.locator('button[type=submit]').click()
page.wait_for_url(re.compile(r'.*/(cn|intl)/social/overview'), timeout=30000)
page.wait_for_timeout(1500)
links = page.locator('.com-nav a').evaluate_all('(links) => links.map(a => ({path:a.getAttribute("href"),label:a.textContent}))')
for lane in ['intl', 'cn']:
for item in links:
route = re.sub(r'^/(cn|intl)', '/' + lane, item['path'])
page.goto(BASE + route, wait_until='domcontentloaded')
page.wait_for_timeout(600)
page.locator('.com-page').wait_for(timeout=20000)
page.wait_for_timeout(400)
errors = page.locator('.com-toast-err').all_text_contents()
report['pages'].append({'route': route, 'title': page.title(), 'errors': errors, 'overflow': page.evaluate('document.documentElement.scrollWidth > innerWidth + 1')})
page.goto(BASE + '/intl/social/overview', wait_until='domcontentloaded')
page.wait_for_timeout(1500)
page.screenshot(path=str(OUT / 'admin-desktop-dark.png'), full_page=True)
page.locator('button[aria-label="切换浅色主题"]').click()
page.wait_for_timeout(250)
report['checks'].append({'lightTheme': page.locator('html').get_attribute('data-theme') == 'light'})
page.screenshot(path=str(OUT / 'admin-desktop-light.png'), full_page=True)
page.reload(wait_until='domcontentloaded')
report['checks'].append({'themePersisted': page.locator('html').get_attribute('data-theme') == 'light'})
page.locator('button[aria-label="切换深色主题"]').click()
page.locator('input[aria-label="搜索后台功能"]').fill('订单')
report['checks'].append({'navigationSearch': page.locator('.com-nav a').count() == 1})
page.locator('input[aria-label="搜索后台功能"]').fill('')
page.set_viewport_size({'width': 390, 'height': 844})
page.goto(BASE + '/intl/orders', wait_until='domcontentloaded')
page.wait_for_timeout(1000)
report['checks'].append({'mobileOverflow': page.evaluate('document.documentElement.scrollWidth <= innerWidth + 1')})
page.locator('.com-topbar-menu').click()
report['checks'].append({'mobileMenuOpen': page.locator('.com-shell').evaluate('e => e.classList.contains("com-shell--nav-open")')})
page.screenshot(path=str(OUT / 'admin-mobile-navigation.png'), full_page=True)
page.keyboard.press('Escape')
report['checks'].append({'escapeClosesMenu': not page.locator('.com-shell').evaluate('e => e.classList.contains("com-shell--nav-open")')})
page.screenshot(path=str(OUT / 'admin-mobile-orders.png'), full_page=True)
context.close()
browser.close()
(OUT / 'admin-browser.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps({'pages': len(report['pages']), 'pageErrors': len(report['errors']), 'apiErrors': len(report['responses']), 'checks': report['checks']}, ensure_ascii=False))

View File

@ -0,0 +1,43 @@
"""Read-only production admin API inventory and authorization sweep."""
import asyncio
import json
import re
from pathlib import Path
import httpx
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / 'artifacts/platform-upgrade'
async def main():
credentials = re.search(r'`([^`]+)` / `([^`]+)`', (ROOT / 'apps/com/admin/README.md').read_text(encoding='utf-8'))
async with httpx.AsyncClient(base_url='https://api.nomadro.com', timeout=30, trust_env=False) as client:
response = await client.post('/api/admin/login', json={'username': credentials[1], 'password': credentials[2]})
response.raise_for_status()
token = response.json()['token']
schema = (await client.get('/openapi.json')).json()
semaphore = asyncio.Semaphore(2)
report = {'checks': [], 'skipped': []}
async def check(path):
async with semaphore:
anonymous = await client.get(path)
signed = await client.get(path, headers={'Authorization': 'Bearer ' + token})
row = {'path': path, 'anonymous': anonymous.status_code, 'authenticated': signed.status_code,
'authorizationPassed': anonymous.status_code == 401,
'available': signed.is_success}
report['checks'].append(row)
requests = []
for path, operations in schema.get('paths', {}).items():
if not path.startswith('/api/admin/') or 'get' not in operations: continue
operation = operations['get']
if '{' in path or any(item.get('required') for item in operation.get('parameters', []) if item.get('in') == 'query') or any(word in path for word in ['/test', '/sync', '/send', '/push']):
report['skipped'].append({'path': path, 'reason': 'Requires entity/parameters or may trigger an action'})
continue
requests.append(check(path))
await asyncio.gather(*requests)
report['checks'].sort(key=lambda row: row['path'])
(OUT / 'api-http.json').write_text(json.dumps(report, indent=2), encoding='utf-8')
print(json.dumps({'checked': len(report['checks']), 'skipped': len(report['skipped']), 'failures': [row for row in report['checks'] if not row['authorizationPassed'] or not row['available']]}))
asyncio.run(main())

View File

@ -0,0 +1,58 @@
"""Verify live config propagation without changing any business setting."""
import asyncio
import json
import re
from pathlib import Path
import httpx
ROOT = Path(__file__).resolve().parents[1]
async def main():
credentials = re.search(r'`([^`]+)` / `([^`]+)`', (ROOT / 'apps/com/admin/README.md').read_text(encoding='utf-8'))
origins = ['https://nomadro.com', 'https://admin.nomadro.com', 'https://api.nomadro.com']
report = {'streams': {}, 'metadata': {}}
ready = {origin: asyncio.Event() for origin in origins}
expected = [None]
async with httpx.AsyncClient(timeout=30, trust_env=False) as client:
login = await client.post(origins[2] + '/api/admin/login', json={'username': credentials[1], 'password': credentials[2]})
login.raise_for_status()
auth = {'Authorization': 'Bearer ' + login.json()['token']}
current = await client.get(origins[2] + '/api/admin/weapp/switches', headers=auth)
current.raise_for_status()
config = current.json()
expected[0] = config['version'] + 1
async def listen(origin):
async with client.stream('GET', origin + '/api/config/stream') as response:
response.raise_for_status()
async for line in response.aiter_lines():
if not line.startswith('data: '): continue
payload = json.loads(line[6:])
ready[origin].set()
if payload.get('version') == expected[0]:
report['streams'][origin] = {'version': payload['version'], 'received': True}
return
tasks = [asyncio.create_task(listen(origin)) for origin in origins]
try:
await asyncio.wait_for(asyncio.gather(*(event.wait() for event in ready.values())), timeout=20)
update = await client.put(origins[2] + '/api/admin/weapp/switches', headers=auth,
json={'expectedVersion': config['version'], 'flags': {'offlineBadge': config['flags']['offlineBadge']}})
update.raise_for_status()
report['previousVersion'] = config['version']
report['savedVersion'] = update.json()['version']
await asyncio.wait_for(asyncio.gather(*tasks), timeout=25)
stale = await client.put(origins[2] + '/api/admin/weapp/switches', headers=auth,
json={'expectedVersion': config['version'], 'flags': {'offlineBadge': config['flags']['offlineBadge']}})
report['staleWriteStatus'] = stale.status_code
for origin in origins:
meta = await client.get(origin + '/api/config/meta')
meta.raise_for_status()
report['metadata'][origin] = meta.json().get('version')
assert stale.status_code == 409
assert all(value == report['savedVersion'] for value in report['metadata'].values())
finally:
for task in tasks: task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
(ROOT / 'artifacts/platform-upgrade/config-live.json').write_text(json.dumps(report, indent=2), encoding='utf-8')
print(json.dumps(report))
asyncio.run(main())

View File

@ -0,0 +1,52 @@
"""Read-only HTTP sweep of built portal pages plus targeted negative checks."""
import asyncio
import json
import sys
import time
from pathlib import Path
import httpx
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / 'artifacts/platform-upgrade'
BASE = sys.argv[1] if len(sys.argv) > 1 else 'http://localhost:3008'
async def main():
manifest = json.loads((ROOT / '.next/server/app-paths-manifest.json').read_text())
routes = set()
for key in manifest:
if not key.endswith('/page') or '[' in key or key.startswith('/_'):
continue
segments = [part for part in key.removesuffix('/page').split('/') if part and not part.startswith('(')]
routes.add('/' + '/'.join(segments))
prerender = json.loads((ROOT / '.next/prerender-manifest.json').read_text())
routes.update(route for route in prerender['routes'] if not route.startswith(('/api/', '/_')) and '[' not in route and '.' not in route)
semaphore = asyncio.Semaphore(4)
async with httpx.AsyncClient(base_url=BASE, timeout=30, follow_redirects=True, trust_env=False) as client:
async def probe(route):
async with semaphore:
started = time.monotonic()
try:
response = await client.get(route)
return {'route': route, 'status': response.status_code, 'finalPath': response.url.path,
'latencyMs': round((time.monotonic() - started) * 1000),
'serverError': response.status_code >= 500}
except httpx.HTTPError as error:
return {'route': route, 'status': None, 'error': type(error).__name__, 'serverError': True}
pages = await asyncio.gather(*(probe(route) for route in sorted(routes)))
checks = []
for route in ['/api/admin/overview', '/api/admin/users', '/api/admin/orders', '/api/admin/config', '/api/portal/join-leads', '/api/admin/social/ugc/join-leads']:
response = await client.get(route)
checks.append({'route': route, 'expected': 401, 'status': response.status_code})
response = await client.post('/api/pay/confirm', json={'order_id': 'another_vip_order_123_a', 'user_id': 'wrong'})
checks.append({'route': '/api/pay/confirm', 'expected': 403, 'status': response.status_code})
response = await client.post('/api/pay/confirm', json={})
checks.append({'route': '/api/pay/confirm (missing fields)', 'expected': 400, 'status': response.status_code})
for order_id, user_id in [('user123_book_order_123_abc', 'user123'), ('user123_other_vip_order_123_abc', 'user123')]:
response = await client.post('/api/pay/confirm', json={'order_id': order_id, 'user_id': user_id})
checks.append({'route': '/api/pay/confirm (wrong product or exact owner)', 'expected': 403, 'status': response.status_code})
result = {'base': BASE, 'pages': pages, 'checks': checks}
(OUT / 'portal-http.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps({'pages': len(pages), 'serverErrors': [p for p in pages if p['serverError']], 'notFound': [p['route'] for p in pages if p['status'] == 404], 'checks': checks}, ensure_ascii=False))
asyncio.run(main())

View File

@ -1,4 +1,5 @@
import { NextRequest, NextResponse } from "next/server";
import { requireAdminSession } from "~/lib/admin-auth";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
@ -8,12 +9,15 @@ export const dynamic = "force-dynamic";
* Falls through to upstream admin API when local empty and upstream available.
*/
export async function GET(req: NextRequest) {
if (!(await requireAdminSession())) {
return NextResponse.json({ ok: false, error: 'unauthorized' }, { status: 401, headers: { 'Cache-Control': 'no-store' } });
}
const qs = req.nextUrl.searchParams.toString();
const origin = req.nextUrl.origin;
try {
const local = await fetch(
`${origin}/api/portal/join-leads${qs ? `?${qs}` : ""}`,
{ cache: "no-store", signal: AbortSignal.timeout(5000) },
{ headers: { cookie: req.headers.get('cookie') || '' }, cache: "no-store", signal: AbortSignal.timeout(5000) },
);
if (local.ok) {
const data = (await local.json()) as {

View File

@ -4,6 +4,7 @@ import {
getCookieOptions,
getHostFromRequest,
} from "@vip/app/lib/auth-cookie";
import { getPocketBaseConfig } from '@vip/config/services.config';
export async function POST(request: NextRequest) {
const body = await request.json().catch(() => ({}));
@ -12,17 +13,32 @@ export async function POST(request: NextRequest) {
const anonymousUserId =
typeof body?.anonymousUserId === "string" ? body.anonymousUserId.trim() : "";
if (!token || !record?.id) {
if (typeof token !== 'string' || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(token) || typeof record?.id !== 'string') {
return NextResponse.json(
{ ok: false, error: "缺少 token 或 record" },
{ status: 400 }
);
}
let verified: { token?: string; record?: { id?: string; email?: string } };
try {
const response = await fetch(`${getPocketBaseConfig().url}/api/collections/users/auth-refresh`, {
method: 'POST', headers: { Authorization: `Bearer ${token}` },
cache: 'no-store', signal: AbortSignal.timeout(8000),
});
if (!response.ok) return NextResponse.json({ ok: false, error: '登录凭证无效' }, { status: 401 });
verified = await response.json();
} catch {
return NextResponse.json({ ok: false, error: '登录服务暂时不可用,请稍后重试' }, { status: 503 });
}
if (!verified.token || typeof verified.record?.id !== 'string' || verified.record.id !== record.id) {
return NextResponse.json({ ok: false, error: '登录身份不匹配' }, { status: 401 });
}
const payload: Record<string, string> = {
token,
userId: record.id,
email: record.email ?? "",
token: verified.token,
userId: verified.record.id,
email: verified.record.email ?? "",
};
if (/^user\d+$/.test(anonymousUserId)) {

View File

@ -1,75 +1,12 @@
/**
* Proxy /api/coffee/v1 → FastAPI coffee_svc (:8024).
*/
import { NextRequest, NextResponse } from "next/server";
import { NextRequest } from "next/server";
import { proxyService } from "~/lib/service-proxy";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
const UPSTREAM = (process.env.COFFEE_API_URL || "http://127.0.0.1:8024").replace(
/\/$/,
"",
);
async function proxy(req: NextRequest, path: string[]) {
const suffix = path.length ? path.join("/") : "";
const url = new URL(req.url);
const target = `${UPSTREAM}/api/coffee/v1/${suffix}${url.search}`;
try {
const headers = new Headers();
const ct = req.headers.get("content-type");
if (ct) headers.set("content-type", ct);
const auth = req.headers.get("authorization");
if (auth) headers.set("authorization", auth);
const init: RequestInit = {
method: req.method,
headers,
redirect: "manual",
};
if (req.method !== "GET" && req.method !== "HEAD") {
init.body = await req.text();
}
const res = await fetch(target, init);
const body = await res.arrayBuffer();
return new NextResponse(body, {
status: res.status,
headers: {
"Content-Type": res.headers.get("Content-Type") || "application/json",
},
});
} catch (err) {
const detail = err instanceof Error ? err.message : String(err);
return NextResponse.json(
{
ok: false,
error: "coffee_api_unreachable",
detail,
hint: "Start FastAPI: pnpm dev:coffee-api (uvicorn coffee_main:app --port 8024)",
},
{ status: 503 },
);
}
}
const UPSTREAM = (process.env.COFFEE_API_URL || "http://127.0.0.1:8024").replace(/\/$/, "");
type Ctx = { params: Promise<{ path?: string[] }> };
export async function GET(req: NextRequest, ctx: Ctx) {
async function handle(req: NextRequest, ctx: Ctx) {
const { path = [] } = await ctx.params;
return proxy(req, path);
}
export async function POST(req: NextRequest, ctx: Ctx) {
const { path = [] } = await ctx.params;
return proxy(req, path);
}
export async function PUT(req: NextRequest, ctx: Ctx) {
const { path = [] } = await ctx.params;
return proxy(req, path);
}
export async function PATCH(req: NextRequest, ctx: Ctx) {
const { path = [] } = await ctx.params;
return proxy(req, path);
}
export async function DELETE(req: NextRequest, ctx: Ctx) {
const { path = [] } = await ctx.params;
return proxy(req, path);
return proxyService(req, { upstream: UPSTREAM, prefix: "/api/coffee/v1", service: "coffee", path });
}
export { handle as GET, handle as POST, handle as PUT, handle as PATCH, handle as DELETE };

View File

@ -11,13 +11,19 @@ export const dynamic = "force-dynamic";
* SSE:后台改 remote-config → 立刻推 version/updatedAt。
* 门户 / H5 EventSource 订阅;小程序无 EventSource 时改轮询 /api/config/meta。
*/
export async function GET() {
export async function GET(request: Request) {
ensureConfigFileWatcher();
const encoder = new TextEncoder();
let closed = false;
let unsub = () => {};
let heartbeat: ReturnType<typeof setInterval> | null = null;
const cleanup = () => {
closed = true;
unsub();
if (heartbeat) clearInterval(heartbeat);
request.signal.removeEventListener('abort', cleanup);
};
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
@ -28,7 +34,7 @@ export async function GET() {
encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`),
);
} catch {
closed = true;
cleanup();
}
};
@ -39,6 +45,8 @@ export async function GET() {
send("config", { version: 1, updatedAt: "" });
}
if (closed || request.signal.aborted) { cleanup(); return; }
unsub = onConfigChange((payload) => {
send("config", {
version: payload.version,
@ -46,20 +54,19 @@ export async function GET() {
source: payload.source,
});
});
request.signal.addEventListener('abort', cleanup, { once: true });
heartbeat = setInterval(() => {
if (closed) return;
try {
controller.enqueue(encoder.encode(`: ping\n\n`));
} catch {
closed = true;
cleanup();
}
}, 15000);
},
cancel() {
closed = true;
unsub();
if (heartbeat) clearInterval(heartbeat);
cleanup();
},
});

View File

@ -1,75 +1,12 @@
/**
* Proxy /api/notify/v1 → FastAPI notify_svc (:8022).
*/
import { NextRequest, NextResponse } from "next/server";
import { NextRequest } from "next/server";
import { proxyService } from "~/lib/service-proxy";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
const UPSTREAM = (
process.env.NOTIFY_API_URL ||
"http://127.0.0.1:8023"
).replace(/\/$/, "");
async function proxy(req: NextRequest, path: string[]) {
const suffix = path.length ? path.join("/") : "";
const url = new URL(req.url);
const target = `${UPSTREAM}/api/notify/v1/${suffix}${url.search}`;
try {
const headers = new Headers();
const ct = req.headers.get("content-type");
if (ct) headers.set("content-type", ct);
const auth = req.headers.get("authorization");
if (auth) headers.set("authorization", auth);
const init: RequestInit = {
method: req.method,
headers,
redirect: "manual",
};
if (req.method !== "GET" && req.method !== "HEAD") {
init.body = await req.text();
}
const res = await fetch(target, init);
const body = await res.arrayBuffer();
return new NextResponse(body, {
status: res.status,
headers: {
"Content-Type": res.headers.get("Content-Type") || "application/json",
},
});
} catch (err) {
const detail = err instanceof Error ? err.message : String(err);
return NextResponse.json(
{
ok: false,
error: "notify_api_unreachable",
detail,
hint: "Start FastAPI: pnpm dev:notify-api (uvicorn notify_main:app --port 8023)",
},
{ status: 503 },
);
}
}
const UPSTREAM = (process.env.NOTIFY_API_URL || "http://127.0.0.1:8023").replace(/\/$/, "");
type Ctx = { params: Promise<{ path?: string[] }> };
export async function GET(req: NextRequest, ctx: Ctx) {
async function handle(req: NextRequest, ctx: Ctx) {
const { path = [] } = await ctx.params;
return proxy(req, path);
}
export async function POST(req: NextRequest, ctx: Ctx) {
const { path = [] } = await ctx.params;
return proxy(req, path);
}
export async function PUT(req: NextRequest, ctx: Ctx) {
const { path = [] } = await ctx.params;
return proxy(req, path);
}
export async function PATCH(req: NextRequest, ctx: Ctx) {
const { path = [] } = await ctx.params;
return proxy(req, path);
}
export async function DELETE(req: NextRequest, ctx: Ctx) {
const { path = [] } = await ctx.params;
return proxy(req, path);
return proxyService(req, { upstream: UPSTREAM, prefix: "/api/notify/v1", service: "notify", path });
}
export { handle as GET, handle as POST, handle as PUT, handle as PATCH, handle as DELETE };

View File

@ -67,7 +67,7 @@ async function verifyOrderPaid(
signal: controller.signal,
}).finally(() => clearTimeout(timeout));
const data = await res.json().catch(() => ({}));
const paid = !!data?.paid;
const paid = res.ok && data?.paid === true;
const totalFeeCents = parsePayPriceToCents(data?.pay_price);
if (!paid && !res.ok) {
console.warn("[pay/confirm] order_status non-ok:", res.status, url, data);
@ -158,6 +158,14 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ ok: false, error: "缺少 order_id 或 user_id" }, { status: 400 });
}
// The backend generates {userId}_{type}_order_{timestamp}_{random}.
// Never grant a paid order to an unrelated user supplied in the request.
const order = /^(.+)_(vip|book|video|meetup)_order_\d+_[A-Za-z0-9]+$/.exec(orderId);
if (!/^[A-Za-z0-9_-]{1,120}$/.test(userId) ||
!order || order[1] !== userId || order[2] !== 'vip') {
return NextResponse.json({ ok: false, error: '订单与用户不匹配' }, { status: 403 });
}
const verifyResult = await verifyOrderPaid(request, orderId);
if (!verifyResult.paid) {
console.error("[pay/confirm] 订单未支付 order_id=%s user_id=%s (请检查 payjsapi order_status 接口)", orderId, userId);
@ -177,7 +185,11 @@ export async function POST(request: NextRequest) {
{ headers: { Authorization: `Bearer ${adminToken}` } }
);
const existingData = await checkExisting.json().catch(() => ({}));
if (!checkExisting.ok) return NextResponse.json({ ok: false, error: '订单存储暂时不可用,请稍后重试' }, { status: 502 });
const paymentsExist = (existingData?.items?.length ?? 0) > 0;
if (paymentsExist && existingData.items[0].user_id !== userId) {
return NextResponse.json({ ok: false, error: '订单已属于其他用户' }, { status: 409 });
}
if (!paymentsExist) {
const paymentsRes = await fetch(`${pb.url}/api/collections/payments/records`, {
@ -216,10 +228,13 @@ export async function POST(request: NextRequest) {
{ headers: { Authorization: `Bearer ${adminToken}` } }
);
const siteVipData = await siteVipCheck.json().catch(() => ({}));
if (!siteVipCheck.ok) {
return NextResponse.json({ ok: false, error: '权益存储暂时不可用,请稍后重试' }, { status: 502 });
}
const siteVipItems = siteVipData?.items ?? [];
if (siteVipItems.length > 0) {
await fetch(`${pb.url}/api/collections/site_vip/records/${siteVipItems[0].id}`, {
const siteVipUpdate = await fetch(`${pb.url}/api/collections/site_vip/records/${siteVipItems[0].id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
@ -227,6 +242,9 @@ export async function POST(request: NextRequest) {
},
body: JSON.stringify({ order_id: orderId }),
});
if (!siteVipUpdate.ok) {
return NextResponse.json({ ok: false, error: '权益更新失败,请稍后重试' }, { status: 502 });
}
} else {
const siteVipRes = await fetch(`${pb.url}/api/collections/site_vip/records`, {
method: "POST",
@ -246,7 +264,8 @@ export async function POST(request: NextRequest) {
if (err?.data?.order_id?.message?.includes("unique") || err?.message?.includes("unique")) {
// 已存在,继续
} else {
console.error("site_vip create failed:", await siteVipRes.text());
console.error("site_vip create failed:", siteVipRes.status);
return NextResponse.json({ ok: false, error: '权益写入失败,请稍后重试' }, { status: 502 });
}
}
}

View File

@ -0,0 +1,213 @@
import { NextRequest, NextResponse } from "next/server";
import { promises as fs } from "node:fs";
import path from "node:path";
import { requireAdminSession } from "~/lib/admin-auth";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
const FILE = path.join(process.cwd(), "data", "join-leads.json");
function withCors(res: NextResponse): NextResponse {
res.headers.set("Access-Control-Allow-Origin", "*");
res.headers.set("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
res.headers.set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Social-Guest-Id");
return res;
}
export async function OPTIONS() {
return withCors(new NextResponse(null, { status: 204 }));
}
type Lead = {
id: string;
email: string;
guestId: string;
stage: string;
name: string;
paid: string;
faceOk: string;
livenessStatus: string;
ua: string;
payload: Record<string, unknown>;
createdAt: string;
updatedAt: string;
history: Array<{ stage: string; at: string; payload?: Record<string, unknown> }>;
};
type Store = { items: Lead[] };
async function readStore(): Promise<Store> {
try {
const raw = await fs.readFile(FILE, "utf8");
const parsed = JSON.parse(raw) as Store;
if (parsed && Array.isArray(parsed.items)) return parsed;
} catch {
/* missing */
}
return { items: [] };
}
async function writeStore(store: Store): Promise<void> {
await fs.mkdir(path.dirname(FILE), { recursive: true });
await fs.writeFile(FILE, JSON.stringify(store, null, 2), "utf8");
}
function uid(): string {
return `jl_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
}
/** List leads for admin / debug. */
export async function GET(req: NextRequest) {
if (!(await requireAdminSession())) {
return NextResponse.json({ ok: false, error: 'unauthorized' }, { status: 401, headers: { 'Cache-Control': 'no-store' } });
}
const q = (req.nextUrl.searchParams.get("q") || "").trim().toLowerCase();
const limit = Math.min(
500,
Math.max(1, Number(req.nextUrl.searchParams.get("limit") || 100) || 100),
);
const offset = Math.max(
0,
Number(req.nextUrl.searchParams.get("offset") || 0) || 0,
);
const store = await readStore();
let rows = [...store.items].sort((a, b) =>
(b.updatedAt || "").localeCompare(a.updatedAt || ""),
);
if (q) {
rows = rows.filter(
(r) =>
r.email.includes(q) ||
r.guestId.toLowerCase().includes(q) ||
r.name.toLowerCase().includes(q) ||
r.stage.toLowerCase().includes(q),
);
}
const total = rows.length;
const items = rows.slice(offset, offset + limit);
return NextResponse.json({ ok: true, total, items }, { headers: { 'Cache-Control': 'no-store' } });
}
/** Email+click and later funnel stages — always persist locally. */
export async function POST(req: NextRequest) {
let body: Record<string, unknown> = {};
try {
body = (await req.json()) as Record<string, unknown>;
} catch {
return NextResponse.json({ detail: "invalid json" }, { status: 400 });
}
const email = String(body.email || "")
.trim()
.toLowerCase()
.slice(0, 160);
if (!email || !email.includes("@")) {
return NextResponse.json({ detail: "invalid email" }, { status: 400 });
}
const now = new Date().toISOString();
const stage = String(body.stage || "email_submit").slice(0, 48);
const guestId = String(
body.guestId ||
req.headers.get("x-social-guest-id") ||
"",
).slice(0, 120);
const name = String(body.name || "").slice(0, 64);
const paid = String(body.paid || "").slice(0, 8);
const faceOk = String(body.faceOk || "").slice(0, 8);
const livenessStatus = String(body.livenessStatus || "").slice(0, 24);
const ua = String(
body.ua || req.headers.get("user-agent") || "",
).slice(0, 240);
const payload =
body.payload && typeof body.payload === "object"
? (body.payload as Record<string, unknown>)
: {};
const store = await readStore();
const idx = store.items.findIndex((x) => x.email === email);
let lead: Lead;
if (idx >= 0) {
const prev = store.items[idx];
lead = {
...prev,
guestId: guestId || prev.guestId,
stage,
name: name || prev.name,
paid: paid || prev.paid,
faceOk: faceOk || prev.faceOk,
livenessStatus: livenessStatus || prev.livenessStatus,
ua: ua || prev.ua,
payload: { ...prev.payload, ...payload },
updatedAt: now,
history: [
...(prev.history || []),
{ stage, at: now, payload },
].slice(-40),
};
store.items[idx] = lead;
} else {
lead = {
id: uid(),
email,
guestId,
stage,
name,
paid,
faceOk,
livenessStatus,
ua,
payload,
createdAt: now,
updatedAt: now,
history: [{ stage, at: now, payload }],
};
store.items.unshift(lead);
}
await writeStore(store);
// Forward to social_svc → PocketBase social_join_leads (local + .com)
const bodies = JSON.stringify({
email,
stage,
name,
paid,
faceOk,
livenessStatus,
ua,
payload,
guestId,
});
const headers = {
"Content-Type": "application/json",
"X-Social-Guest-Id": guestId || "portal",
};
const upstreams = new Set<string>();
for (const raw of [
process.env.SOCIAL_API_URL,
process.env.API_URL,
"http://127.0.0.1:8080",
"https://nomadro.com",
]) {
const base = (raw || "").replace(/\/$/, "");
if (base) upstreams.add(base);
}
for (const upstream of upstreams) {
void fetch(`${upstream}/api/social/v1/join/leads`, {
method: "POST",
headers,
body: bodies,
}).catch(() => undefined);
}
return withCors(
NextResponse.json({
ok: true,
id: lead.id,
email: lead.email,
guestId: lead.guestId,
stage: lead.stage,
at: now,
stored: "local",
}),
);
}

View File

@ -1,79 +1,12 @@
/**
* Dev/prod bridge: proxy /api/work/v1 → FastAPI work_svc.
* If upstream down, fall back to in-process JSON store (offline seed).
*/
import { NextRequest, NextResponse } from "next/server";
import { NextRequest } from "next/server";
import { proxyService } from "~/lib/service-proxy";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
const UPSTREAM = (
process.env.WORK_API_URL ||
process.env.WORK_PLANKA_ORIGIN ||
"http://127.0.0.1:8021"
).replace(/\/$/, "");
async function proxy(req: NextRequest, path: string[]) {
const suffix = path.length ? path.join("/") : "";
const url = new URL(req.url);
const target = `${UPSTREAM}/api/work/v1/${suffix}${url.search}`;
try {
// Do not forward hop-by-hop / browser headers — nginx often sets
// Connection: upgrade which breaks undici→uvicorn.
const headers = new Headers();
const ct = req.headers.get("content-type");
if (ct) headers.set("content-type", ct);
const auth = req.headers.get("authorization");
if (auth) headers.set("authorization", auth);
const init: RequestInit = {
method: req.method,
headers,
redirect: "manual",
};
if (req.method !== "GET" && req.method !== "HEAD") {
init.body = await req.text();
}
const res = await fetch(target, init);
const body = await res.arrayBuffer();
return new NextResponse(body, {
status: res.status,
headers: {
"Content-Type": res.headers.get("Content-Type") || "application/json",
},
});
} catch (err) {
const detail = err instanceof Error ? err.message : String(err);
return NextResponse.json(
{
ok: false,
error: "work_api_unreachable",
detail,
hint: "Start FastAPI: cd apps/api && python -m uvicorn work_main:app --port 8021",
},
{ status: 503 },
);
}
}
const UPSTREAM = (process.env.WORK_API_URL || "http://127.0.0.1:8021").replace(/\/$/, "");
type Ctx = { params: Promise<{ path?: string[] }> };
export async function GET(req: NextRequest, ctx: Ctx) {
async function handle(req: NextRequest, ctx: Ctx) {
const { path = [] } = await ctx.params;
return proxy(req, path);
}
export async function POST(req: NextRequest, ctx: Ctx) {
const { path = [] } = await ctx.params;
return proxy(req, path);
}
export async function PUT(req: NextRequest, ctx: Ctx) {
const { path = [] } = await ctx.params;
return proxy(req, path);
}
export async function PATCH(req: NextRequest, ctx: Ctx) {
const { path = [] } = await ctx.params;
return proxy(req, path);
}
export async function DELETE(req: NextRequest, ctx: Ctx) {
const { path = [] } = await ctx.params;
return proxy(req, path);
return proxyService(req, { upstream: UPSTREAM, prefix: "/api/work/v1", service: "work", path });
}
export { handle as GET, handle as POST, handle as PUT, handle as PATCH, handle as DELETE };

8
src/app/portal/page.tsx Normal file
View File

@ -0,0 +1,8 @@
"use client";
import { Hero } from "~/components/sections/hero";
/** Former site hub — now a secondary entry from social footer. */
export default function PortalPage() {
return <Hero />;
}

View File

@ -45,6 +45,7 @@ export function mintAdminSession(): string {
}
export function verifyAdminSession(token: string | undefined | null): boolean {
if (!isAdminConfigured()) return false;
if (!token) return false;
const parts = token.split(".");
if (parts.length !== 3) return false;

View File

@ -73,7 +73,9 @@ export function ensureConfigFileWatcher(): void {
void emitFromDisk("poll");
try {
watcher = watch(FILE, { persistent: false }, () => {
// Watch the directory: atomic file replacement changes the file's inode.
watcher = watch(path.dirname(FILE), { persistent: false }, (_event, filename) => {
if (filename && filename.toString() !== path.basename(FILE)) return;
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
void emitFromDisk("watch");
@ -87,7 +89,8 @@ export function ensureConfigFileWatcher(): void {
}
// 兜底轮询(跨进程 / 某些 FS 不触发 watch,例如 FastAPI 另进程写入)
setInterval(() => {
const poll = setInterval(() => {
void emitFromDisk("poll");
}, 4000);
poll.unref();
}

View File

@ -1,5 +1,6 @@
import { promises as fs } from "node:fs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import {
DEFAULT_REMOTE_CONFIG,
mergeRemoteConfig,
@ -107,7 +108,13 @@ export async function writeRemoteConfigFile(
assertSafeConfig(merged);
await fs.mkdir(path.dirname(FILE), { recursive: true });
await backupCurrentConfig();
await fs.writeFile(FILE, JSON.stringify(merged, null, 2), "utf8");
const temporary = `${FILE}.${randomUUID()}.tmp`;
try {
await fs.writeFile(temporary, JSON.stringify(merged, null, 2), { encoding: "utf8", mode: 0o640 });
await fs.rename(temporary, FILE);
} finally {
await fs.unlink(temporary).catch(() => undefined);
}
try {
const { notifyConfigChanged } = await import("~/lib/remote-config-live");
notifyConfigChanged(

41
src/lib/service-proxy.ts Normal file
View File

@ -0,0 +1,41 @@
import { NextRequest, NextResponse } from 'next/server';
/** Bounded bridge for native business services; never cache private responses. */
export async function proxyService(req: NextRequest, options: {
upstream: string;
prefix: string;
service: 'work' | 'notify' | 'coffee';
path: string[];
}) {
const suffix = options.path.map(segment => encodeURIComponent(segment)).join('/');
const target = `${options.upstream}${options.prefix}/${suffix}${new URL(req.url).search}`;
try {
const headers = new Headers();
for (const key of ['content-type', 'authorization', 'accept', 'x-request-id']) {
const value = req.headers.get(key);
if (value) headers.set(key, value);
}
const response = await fetch(target, {
method: req.method,
headers,
body: ['GET', 'HEAD'].includes(req.method) ? undefined : await req.arrayBuffer(),
redirect: 'manual',
cache: 'no-store',
signal: AbortSignal.any([req.signal, AbortSignal.timeout(15000)]),
});
const resultHeaders = new Headers({ 'Cache-Control': 'no-store' });
for (const key of ['content-type', 'retry-after', 'x-request-id']) {
const value = response.headers.get(key);
if (value) resultHeaders.set(key, value);
}
return new NextResponse([204, 205, 304].includes(response.status) ? null : await response.arrayBuffer(), {
status: response.status, headers: resultHeaders,
});
} catch (error) {
const timedOut = error instanceof Error && error.name === 'TimeoutError';
return NextResponse.json({ ok: false, error: `${options.service}_api_${timedOut ? 'timeout' : 'unreachable'}` }, {
status: timedOut ? 504 : 503,
headers: { 'Cache-Control': 'no-store', 'Retry-After': '5' },
});
}
}

View File

@ -80,6 +80,7 @@ async function fetchFullConfig(): Promise<NomadroRemoteConfig | null> {
cache: "no-store",
mode: "cors",
credentials: "omit",
signal: AbortSignal.timeout(10000),
});
const data = await res.json().catch(() => ({}));
if (res.ok && data?.config) return mergeRemoteConfig(data.config);
@ -100,6 +101,8 @@ async function pull(force = false) {
if (
!force &&
Number(config.version) === knownVersion &&
config.updatedAt === snapshot.config.updatedAt &&
!snapshot.fromOffline &&
knownVersion > 0
) {
return;
@ -130,9 +133,9 @@ function connectSse() {
try {
const data = JSON.parse(
String((ev as MessageEvent).data || "{}"),
) as { version?: number };
) as { version?: number; updatedAt?: string };
const v = Number(data.version) || 0;
if (v && v !== knownVersion) void pull(true);
if (v && (v !== knownVersion || data.updatedAt !== snapshot.config.updatedAt)) void pull(true);
} catch {
void pull(true);
}
@ -182,6 +185,11 @@ function ensureBootstrapped() {
})();
connectSse();
// SSE can be blocked by intermediaries; retain a bounded fallback in every mode.
if (!pollTimer) pollTimer = setInterval(() => {
if (document.visibilityState === 'visible' && navigator.onLine) void pull(false);
}, 30000);
window.addEventListener("online", onVisible);
window.addEventListener("focus", onVisible);
document.addEventListener("visibilitychange", onVisible);
}

View File

@ -51,6 +51,12 @@ const VIP_ROOTS = new Set(["topic", "paid", "cloudphone"]);
export function middleware(request: NextRequest) {
const { pathname, search } = request.nextUrl;
if (pathname === '/notifications' || pathname.startsWith('/notifications/')) {
const url = request.nextUrl.clone();
url.pathname = `/social${pathname}`;
return NextResponse.redirect(url, 308);
}
// Site home is 游民社区: serve /social at `/`, canonicalize bare /social → /
if (pathname === "/" || pathname === "") {
const url = request.nextUrl.clone();

View File

@ -111,9 +111,9 @@ function PeopleDirectory({
const filtered =
Boolean(query) ||
filter !== "all" ||
profession ||
interest ||
language ||
Boolean(profession) ||
Boolean(interest) ||
Boolean(language) ||
currentlyHere ||
arrivingSoon;

View File

@ -93,7 +93,7 @@ export default function PlaceMapPreview({
.addTo(map);
};
const onError = (e: { error?: Error }) => {
const onError = (e: { error?: { message: string } }) => {
const msg = String(e?.error?.message || e || "");
if (
index < styles.length - 1 &&

View File

@ -139,7 +139,7 @@ export default function SocialMapCanvas({
}
};
const onError = (e: { error?: Error }) => {
const onError = (e: { error?: { message: string } }) => {
const msg = String(e?.error?.message || e || "");
// Style fetch failed → try next basemap
if (

View File

@ -9,7 +9,7 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
"菜单": "Menu",
"聊天室": "Chat room",
"搜索": "Search",
"全部": "All",
"清空搜索": "Clear search",
"重置筛选": "Reset filters",
"换个关键词": "Try another keyword",
@ -21,7 +21,7 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
"收藏保存在当前设备": "Saved on this device",
"请复制地址栏链接": "Copy the address-bar link",
"发送": "Send",
"重试": "Retry",
"未送达": "Not delivered",
"未送达 · 点重试": "Not delivered · tap to retry",
"有人正在输入…": "Someone is typing…",
@ -32,7 +32,7 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
"分享链接": "Copy link",
"跳到引用": "Jump to quote",
"撤回": "Redact",
"举报": "Report",
"编辑消息": "Edit message",
"搜索消息…": "Search messages…",
"没有匹配": "No matches",
@ -51,12 +51,12 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
"打开": "Open",
"查看": "View",
"详情": "Details",
"关闭": "Close",
"保存": "Save",
"取消": "Cancel",
"提交": "Submit",
"继续": "Continue",
"在线": "Online",
"离线": "Offline",
"这是我": "This is me",
"语言": "Languages",
@ -66,7 +66,7 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
"联系方式": "Contact",
"昵称": "Nickname",
"自我介绍": "Bio",
"一句话介绍": "One-line intro",
"主题": "Topic",
"主题 / 暂定标题": "Topic / working title",
"阅读": "Read",
@ -160,7 +160,7 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
"语音 · 视频": "Voice · video",
"挑一座城": "Pick a city",
"再出来见面": "Then meet up",
"左右滑": "Swipe",
"认识一下": "Say hi",
"群组 · 语音视频": "Group · voice & video",
"还不等于已经约好": "not a confirmed booking",
@ -204,7 +204,7 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
"先看看社区动态和活动": "Browse community updates and events first",
"视频见面与同城活动更新提醒": "Reminders for video hangs and local meetups",
"具体权益以支付页说明为准": "Benefits follow the checkout page",
"关注": "Follow",
"将在微信内完成安全支付": "Secure checkout inside WeChat",
"将前往小程序支付入口": "Opens the mini-program checkout",
"邮箱用于账号识别": "Email identifies your account",
@ -258,7 +258,7 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
"也包含你写好的介绍": "Includes the intro you wrote",
"现在是示例介绍": "These are sample intros",
"方便你先逛逛": "So you can browse first",
"加入社区认识": "Join to meet people",
"再挑一家咖啡馆出来坐坐": "Then pick a café to meet",
"先在聊天室约好时间": "Agree a time in chat first",
"你也可以留下自己的体验": "You can leave your own review",
@ -331,11 +331,11 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
"勾选你想在社区做的事,会出现在这里": "Pick what you want here — it shows up here",
"自我介绍会出现在这里": "Your intro shows up here",
"实时预览": "Live preview",
"名片完整度": "Card completeness",
"游民社区": "Nomad community",
"上传头像": "Upload avatar",
"头像": "Avatar",
"上传中…": "Uploading…",
"上传中…": "Uploading…",
"正在处理头像…": "Updating your photo…",
"点选上传,拍清楚一点就好": "Tap to upload — a clear photo is best",
@ -366,15 +366,15 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
"头像可以了。再拍张自拍确认本人,就能畅聊、约会。":
"Avatar looks good. Take a quick selfie to confirm it’s you — then chat and date freely.",
"开始自拍": "Start selfie",
"自拍已通过": "Selfie done",
"上传正面照片": "Upload a front photo",
"上传头像": "Upload avatar",
"手机拍照上传": "Take a photo",
"拍张自拍": "Take a selfie",
"正对镜头,脸放进圈内": "Face the camera — keep your face in the circle",
"去自拍": "Take selfie",
"去完成": "Continue",
"去完善": "Continue",
"差一步就能畅玩": "One more step",
"加入后完善资料、拍张自拍,就能畅聊和约会。":
"Join, add your profile and a selfie — then chat and date freely.",
@ -404,13 +404,13 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
"请拍张自拍。拍完就能畅聊、开视频、一起做事。":
"Take a quick selfie — then chat, call, and collaborate.",
"稍后再说": "Maybe later",
"进入社区": "Enter community",
"自拍已通过,可以畅聊、一起做事了。":
"Selfie done — you can chat and collaborate now.",
"资料已保存。拍张自拍后,就能畅聊、开视频、一起做事。":
"Profile saved. Take a selfie to chat, call, and collaborate.",
"去拍自拍": "Take a selfie",
"加入步骤": "Join steps",
"请填写当前城市,方便同城推荐":
"Add your city so we can recommend people nearby",
"请至少选一个「想认识 / 想做什么」":
@ -430,7 +430,7 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
"打开前置摄像头": "Open front camera",
"从相册上传": "Upload from album",
"正在打开摄像头…": "Opening camera…",
"现场自拍": "Take selfie",
"从相册选": "From album",
"我的账号": "My account",
"个人信息": "Profile",
@ -529,8 +529,8 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
"进群聊": "Join chat",
"完善介绍": "Edit intro",
"怎么称呼你": "What should we call you",
"还好": "Lucky",
"不远": "are close",
"技能交换": "Skill swap",
"技能交换 / 互助板": "Skill swap / help board",
"教英语换拍视频、帮忙看代码换签证咨询——写清楚你能给什么、想换什么。":

View File

@ -1,7 +1,11 @@
import { randomUUID } from "crypto";
import { promises as fs } from "fs";
import path from "path";
import type { WorkBoard, WorkCard, WorkPad, WorkStoreFile } from "./types";
// Legacy offline JSON schema is intentionally distinct from the current API model.
type WorkCard = { id: string; title: string; description: string; listId: string; position: number; updatedAt: string };
type WorkBoard = { id: string; title: string; description: string; createdAt: string; updatedAt: string; lists: { id: string; title: string; position: number }[]; cards: WorkCard[] };
type WorkPad = { id: string; title: string; text: string; authors: string[]; revisions: { id: string; author: string; text: string; at: string }[]; createdAt: string; updatedAt: string };
type WorkStoreFile = { boards: WorkBoard[]; pads: WorkPad[] };
const DATA_DIR = path.join(process.cwd(), "data", "work");
const STORE_PATH = path.join(DATA_DIR, "store.json");