diff --git a/packages/webui/src/App.tsx b/packages/webui/src/App.tsx index d6781eca..7e3ade0b 100644 --- a/packages/webui/src/App.tsx +++ b/packages/webui/src/App.tsx @@ -5,7 +5,9 @@ import { ThemeProvider } from '@/contexts/ThemeContext'; import { SessionProvider } from '@/contexts/SessionContext'; import { LoginPage } from '@/components/pages/login-page'; import { ChangePasswordPage } from '@/components/pages/change-password-page'; +import { ConsentPage } from '@/components/pages/consent-page'; import { ApiProvider, createApiClient, useApi, type ApiClient } from '@/lib/api'; +import type { AgreementsPayload } from '@/lib/api/types'; import { appRouter } from '@/router'; export default function App() { @@ -21,6 +23,10 @@ function AuthBoundary() { const [authed, setAuthed] = useState(false); const [mustChange, setMustChange] = useState(false); const [status, setStatus] = useState('未连接'); + // Agreement consent gate, shown after login but BEFORE the forced password + // change. `agreements === null` while the post-auth fetch is in flight. + const [agreements, setAgreements] = useState(null); + const [needsConsent, setNeedsConsent] = useState(false); // The password from *this* session's login, carried into the forced // change-password gate so it doesn't have to render an old-password field // (which browsers autofill, misleading users on upgrade). Stays undefined @@ -38,6 +44,18 @@ function AuthBoundary() { [], ); + const refreshAgreements = useCallback(async () => { + try { + const payload = await client.agreements.get(); + setAgreements(payload); + setNeedsConsent(payload.consentRequired); + } catch { + // Fail open on a fetch error so a transient hiccup can't wedge the gate. + setAgreements({ version: '', consentRequired: false, documents: [] }); + setNeedsConsent(false); + } + }, [client]); + useEffect(() => { (async () => { const ok = await client.status(); @@ -45,54 +63,88 @@ function AuthBoundary() { setAuthed(true); setStatus('已连接'); setMustChange(await client.mustChangePassword()); + await refreshAgreements(); } setAuthChecked(true); })(); - }, [client]); + }, [client, refreshAgreements]); - const handleLogoutComplete = useCallback(() => { + const handleLoggedOut = useCallback(() => { // Reset the URL so the next login lands on the overview page, matching - // the pre-router behaviour. + // the pre-router behaviour, and clear every post-auth gate. window.history.replaceState({}, '', '/'); setAuthed(false); setStatus('未连接'); setMustChange(false); + setAgreements(null); + setNeedsConsent(false); + setLoginPassword(undefined); }, []); + const handleDecline = useCallback(async () => { + await client.logout(); + handleLoggedOut(); + }, [client, handleLoggedOut]); + + let view: React.ReactNode; + if (!authChecked) { + view = 初始化中…; + } else if (!authed) { + view = ( + { + setAuthed(true); + setStatus('已连接'); + setMustChange(needsChange); + setLoginPassword(password); + void refreshAgreements(); + }} + /> + ); + } else if (agreements === null) { + view = 加载中…; + } else if (needsConsent) { + view = ( + setNeedsConsent(false)} + onStale={refreshAgreements} + onDecline={handleDecline} + /> + ); + } else if (mustChange) { + view = ( + { + setMustChange(false); + setLoginPassword(undefined); + }} + /> + ); + } else { + view = ( + + + + ); + } + return ( - - {!authChecked ? ( -
- 初始化中… -
- ) : !authed ? ( - { - setAuthed(true); - setStatus('已连接'); - setMustChange(needsChange); - setLoginPassword(password); - }} - /> - ) : mustChange ? ( - { - setMustChange(false); - setLoginPassword(undefined); - }} - /> - ) : ( - - - - )} -
+ {view}
); } +function Splash({ children }: { children: React.ReactNode }) { + return ( +
+ {children} +
+ ); +} + function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean, password: string) => void }) { const api = useApi(); const handleLogin = useCallback( @@ -107,6 +159,40 @@ function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean, password: str return ; } +function ConsentGate({ + payload, + onAccepted, + onStale, + onDecline, +}: { + payload: AgreementsPayload; + onAccepted: () => void; + onStale: () => void; + onDecline: () => void; +}) { + const api = useApi(); + return ( + { + const result = await api.agreements.recordConsent(payload.version); + if (result.success) { + onAccepted(); + return { success: true }; + } + // 409: the agreement text changed under us — re-fetch and re-prompt. + if (result.currentVersion && result.currentVersion !== payload.version) { + onStale(); + return { success: false, message: '协议已更新,已为你载入最新版本,请重新阅读后确认。' }; + } + return { success: false, message: result.message ?? '提交失败,请重试' }; + }} + /> + ); +} + function ForcedChangePasswordGate({ knownOldPassword, onSuccess, diff --git a/packages/webui/src/components/pages/consent-page.tsx b/packages/webui/src/components/pages/consent-page.tsx new file mode 100644 index 00000000..7f528298 --- /dev/null +++ b/packages/webui/src/components/pages/consent-page.tsx @@ -0,0 +1,169 @@ +import { useState } from 'react'; +import { motion } from 'motion/react'; +import { Check, ScrollText, ShieldCheck } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Card, CardContent } from '@/components/ui/card'; +import { ThemeToggle } from '@/components/theme-toggle'; +import { Markdown } from '@/lib/markdown'; +import { cn } from '@/lib/utils'; +import type { AgreementDoc } from '@/lib/api/types'; + +interface ConsentPageProps { + documents: AgreementDoc[]; + version: string; + /** Persist acceptance. Resolves {success:false,message} to show inline. */ + onAccept: () => Promise<{ success: boolean; message?: string }>; + /** Operator refuses — caller logs them out. */ + onDecline: () => void; +} + +const TAB_FALLBACK_TITLE: Record = { + eula: '用户协议 / EULA', + privacy: '隐私政策 / Privacy', +}; + +/** + * Full-screen consent gate shown once at first login, before the forced + * password change. The operator must accept the EULA + Privacy Notice before + * the panel unlocks; acceptance is keyed to the agreement content version, so + * it persists across app upgrades and re-prompts only when the text changes. + */ +export function ConsentPage({ documents, version, onAccept, onDecline }: ConsentPageProps) { + const tabs = documents.length > 0 ? documents : []; + const [activeId, setActiveId] = useState(tabs[0]?.id ?? 'eula'); + const [agreed, setAgreed] = useState(false); + const [submitting, setSubmitting] = useState(false); + const [error, setError] = useState(null); + + const active = tabs.find((d) => d.id === activeId) ?? tabs[0]; + + const handleAccept = async () => { + if (!agreed || submitting) return; + setSubmitting(true); + setError(null); + try { + const result = await onAccept(); + if (!result.success) { + setError(result.message ?? '提交失败,请重试'); + setSubmitting(false); + } + // on success the parent unmounts this gate; no local state change needed. + } catch { + // Defense in depth: onAccept should never reject (client resolves errors), + // but never leave the button stuck on "提交中…" if it somehow does. + setError('网络错误,请重试'); + setSubmitting(false); + } + }; + + return ( +
+
+
+ +
+ + + + +
+
+ +
+
+

请阅读并同意以下协议

+

+ 首次使用前,请阅读并同意《用户协议》与《隐私政策》。同意一次后无需重复确认;仅当协议内容更新时才会再次请求确认。 +
+ Please read and accept the agreements below before first use. You only consent once — you'll be asked again only if the text changes. +

+
+
+ + {/* tab switcher */} +
+ {tabs.map((doc) => ( + + ))} +
+ + {active && (active.declaredVersion || active.effectiveDate) && ( +

+ {active.declaredVersion && `版本 / Version ${active.declaredVersion}`} + {active.declaredVersion && active.effectiveDate && ' · '} + {active.effectiveDate && `生效 / Effective ${active.effectiveDate}`} +

+ )} + + {/* document body */} +
+ {active ? ( + + ) : ( +

未能加载协议文本,请刷新页面重试。

+ )} +
+ + {/* agree checkbox */} + + + {error &&

{error}

} + +
+ + +
+
+
+

agreements {version.slice(0, 8)}

+
+
+ ); +} diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts index e3c7afaf..8c7c5965 100644 --- a/packages/webui/src/lib/api/client.ts +++ b/packages/webui/src/lib/api/client.ts @@ -2,6 +2,7 @@ import type { AccountConnections, BackupBundle, BackupImportResult, DebugActionD import type { PasswordRule } from '@/components/pages/change-password-page'; import { normalizeOneBotConfig } from '@/lib/onebot-config'; import { + type AgreementsPayload, ApiError, type ApiClient, type ChangePasswordResult, @@ -47,6 +48,7 @@ class HttpApiClient implements ApiClient { readonly notifications: ApiClient['notifications']; readonly systemSettings: ApiClient['systemSettings']; readonly debug: ApiClient['debug']; + readonly agreements: ApiClient['agreements']; constructor(opts: CreateApiClientOptions = {}) { this.tokenStore = opts.tokenStore ?? localStorageTokenStore(DEFAULT_TOKEN_KEY); @@ -185,6 +187,26 @@ class HttpApiClient implements ApiClient { channelId, }), }; + + this.agreements = { + get: () => this.getJson('/api/agreements'), + recordConsent: async (version) => { + // Read the body even on non-2xx so a 409 can surface currentVersion to + // the caller (instead of fetchJson throwing it away as an ApiError). + // A network failure (fetch reject) must resolve to {success:false}, not + // throw, or the consent button hangs on "提交中…" with no error shown. + try { + const res = await this.request('/api/agreements/record-consent', { + method: 'POST', + body: JSON.stringify({ version }), + }); + const data = await readJson<{ success?: boolean; message?: string; currentVersion?: string }>(res); + return { success: res.ok && !!data.success, message: data.message, currentVersion: data.currentVersion }; + } catch (e) { + return { success: false, message: e instanceof Error ? e.message : '网络错误,请重试' }; + } + }, + }; } // ---------- HTTP helpers ---------- diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts index 45e6369c..aa7d22fb 100644 --- a/packages/webui/src/lib/api/types.ts +++ b/packages/webui/src/lib/api/types.ts @@ -39,6 +39,29 @@ export type LoginResult = export type ChangePasswordResult = { success: boolean; message?: string }; +export interface AgreementDoc { + id: 'eula' | 'privacy'; + title: string; + declaredVersion: string; + effectiveDate: string; + text: string; +} + +export interface AgreementsPayload { + /** Content-hash version of the current agreement set. */ + version: string; + /** Whether the operator must (re-)accept before using the panel. */ + consentRequired: boolean; + documents: AgreementDoc[]; +} + +export type RecordConsentResult = { + success: boolean; + message?: string; + /** On a 409 version-mismatch, the server's current version to re-fetch. */ + currentVersion?: string; +}; + export type ProcessActionResult = { process?: HookProcessInfo & { error?: string }; }; @@ -61,6 +84,14 @@ export interface ApiClient { checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }>; changePassword(oldPassword: string, newPassword: string): Promise; + // ---- EULA / PRIVACY consent (shown after login, before set-password) ---- + agreements: { + /** Fetch agreement texts + current version + whether consent is required. */ + get(): Promise; + /** Record acceptance of `version`. success:false (409) carries currentVersion. */ + recordConsent(version: string): Promise; + }; + // ---- system ---- qqList(): Promise; system(): Promise; diff --git a/packages/webui/src/lib/markdown.tsx b/packages/webui/src/lib/markdown.tsx new file mode 100644 index 00000000..b72d4a77 --- /dev/null +++ b/packages/webui/src/lib/markdown.tsx @@ -0,0 +1,244 @@ +import { Fragment, type ReactNode } from 'react'; + +/** + * Tiny dependency-free markdown renderer, scoped to what the EULA / PRIVACY + * documents actually use: headings (#..####), horizontal rules, blockquotes, + * ordered / unordered lists, fenced code blocks, paragraphs, and the inline + * spans bold / italic / code / links. + * + * It renders to React elements (never dangerouslySetInnerHTML), so all text is + * auto-escaped by React and the renderer cannot introduce XSS even though the + * source text comes over the wire. Links are additionally restricted to + * http/https/mailto; anything else renders as plain text. + */ +export function Markdown({ content }: { content: string }): ReactNode { + const blocks = parseBlocks(content.replace(/\r\n?/g, '\n')); + return ( +
+ {blocks.map((block, i) => ( + {renderBlock(block)} + ))} +
+ ); +} + +type Block = + | { type: 'heading'; level: number; text: string } + | { type: 'hr' } + | { type: 'quote'; lines: string[] } + | { type: 'ul'; items: string[] } + | { type: 'ol'; items: string[] } + | { type: 'code'; text: string } + | { type: 'p'; text: string }; + +function parseBlocks(src: string): Block[] { + const lines = src.split('\n'); + const blocks: Block[] = []; + let i = 0; + + while (i < lines.length) { + const line = lines[i]; + + // blank line — skip + if (line.trim() === '') { + i++; + continue; + } + + // fenced code block ``` ... ``` + if (/^\s*```/.test(line)) { + const body: string[] = []; + i++; + while (i < lines.length && !/^\s*```/.test(lines[i])) { + body.push(lines[i]); + i++; + } + i++; // consume closing fence (or EOF) + blocks.push({ type: 'code', text: body.join('\n') }); + continue; + } + + // horizontal rule + if (/^\s*([-*_])\s*(\1\s*){2,}$/.test(line)) { + blocks.push({ type: 'hr' }); + i++; + continue; + } + + // heading + const heading = line.match(/^(#{1,6})\s+(.*)$/); + if (heading) { + blocks.push({ type: 'heading', level: heading[1].length, text: heading[2].trim() }); + i++; + continue; + } + + // blockquote (consecutive `>` lines) + if (/^\s*>/.test(line)) { + const quote: string[] = []; + while (i < lines.length && /^\s*>/.test(lines[i])) { + quote.push(lines[i].replace(/^\s*>\s?/, '')); + i++; + } + blocks.push({ type: 'quote', lines: quote }); + continue; + } + + // unordered list + if (/^\s*[-*+]\s+/.test(line)) { + const items: string[] = []; + while (i < lines.length && /^\s*[-*+]\s+/.test(lines[i])) { + items.push(lines[i].replace(/^\s*[-*+]\s+/, '')); + i++; + } + blocks.push({ type: 'ul', items }); + continue; + } + + // ordered list + if (/^\s*\d+[.)]\s+/.test(line)) { + const items: string[] = []; + while (i < lines.length && /^\s*\d+[.)]\s+/.test(lines[i])) { + items.push(lines[i].replace(/^\s*\d+[.)]\s+/, '')); + i++; + } + blocks.push({ type: 'ol', items }); + continue; + } + + // paragraph — gather until a blank line or a line that starts a new block + const para: string[] = []; + while (i < lines.length && lines[i].trim() !== '' && !startsNewBlock(lines[i])) { + para.push(lines[i].trim()); + i++; + } + blocks.push({ type: 'p', text: para.join(' ') }); + } + + return blocks; +} + +function startsNewBlock(line: string): boolean { + return ( + /^\s*```/.test(line) || + /^(#{1,6})\s+/.test(line) || + /^\s*>/.test(line) || + /^\s*[-*+]\s+/.test(line) || + /^\s*\d+[.)]\s+/.test(line) || + /^\s*([-*_])\s*(\1\s*){2,}$/.test(line) + ); +} + +function renderBlock(block: Block): ReactNode { + switch (block.type) { + case 'heading': { + const cls = [ + 'text-xl font-semibold tracking-tight', + 'text-lg font-semibold tracking-tight', + 'text-base font-semibold', + 'text-sm font-semibold', + 'text-sm font-semibold text-muted-foreground', + 'text-xs font-semibold text-muted-foreground', + ][block.level - 1]; + const inner = renderInline(block.text); + switch (block.level) { + case 1: + return

{inner}

; + case 2: + return

{inner}

; + case 3: + return

{inner}

; + case 4: + return

{inner}

; + case 5: + return
{inner}
; + default: + return
{inner}
; + } + } + case 'hr': + return
; + case 'quote': + return ( +
+ {block.lines.map((l, i) => ( +

{renderInline(l)}

+ ))} +
+ ); + case 'ul': + return ( +
    + {block.items.map((it, i) => ( +
  • {renderInline(it)}
  • + ))} +
+ ); + case 'ol': + return ( +
    + {block.items.map((it, i) => ( +
  1. {renderInline(it)}
  2. + ))} +
+ ); + case 'code': + return ( +
+          {block.text}
+        
+ ); + case 'p': + return

{renderInline(block.text)}

; + } +} + +// Inline spans: `code`, **bold**, *italic* / _italic_, [text](url). +// +// Scanned in ONE pass with a global regex (lastIndex advances), and every +// span uses a *bounded* negated class (`{1,N}`). Both matter: a greedy +// UNbounded negated class (`[^\]]+`) on bracket-/asterisk-dense text causes +// O(n²) catastrophic backtracking and can hang the render thread on a large +// doc. The caps are far larger than any real inline span; anything longer +// renders literally rather than risking a hang. +const INLINE_RE = + /`[^`\n]{1,2048}`|\*\*[^*\n]{1,2048}\*\*|\*[^*\n]{1,2048}\*|_[^_\n]{1,2048}_|\[[^\]\n]{1,512}\]\([^)\s]{1,2048}\)/g; + +function renderInline(text: string): ReactNode[] { + const out: ReactNode[] = []; + const re = new RegExp(INLINE_RE.source, 'g'); // fresh instance: own lastIndex + let last = 0; + let key = 0; + let m: RegExpExecArray | null; + + while ((m = re.exec(text)) !== null) { + if (m.index > last) out.push(text.slice(last, m.index)); + const tok = m[0]; + if (tok.startsWith('`')) { + out.push({tok.slice(1, -1)}); + } else if (tok.startsWith('**')) { + out.push({renderInline(tok.slice(2, -2))}); + } else if (tok.startsWith('*') || tok.startsWith('_')) { + out.push({renderInline(tok.slice(1, -1))}); + } else { + // [label](href) — tok already matched the bounded link shape. + const link = tok.match(/^\[([^\]]*)\]\(([^)\s]+)\)$/); + if (link) out.push(safeLink(link[2], link[1], key++)); + else out.push(tok); + } + last = m.index + tok.length; + } + if (last < text.length) out.push(text.slice(last)); + + return out; +} + +function safeLink(href: string, label: string, key: number): ReactNode { + const ok = /^(https?:|mailto:)/i.test(href); + if (!ok) return {label}; + return ( + + {label} + + ); +}