698b3ffc90
- 登录/发码两处 catch 的"分流 + 提示 + 上报"逻辑抽成 presentAuthFailure(error, fallback, action) - 错误池指纹的 action 由调用点传入,避免新增认证动作时各自拼一套导致指纹漂移
645 lines
21 KiB
TypeScript
645 lines
21 KiB
TypeScript
import {
|
|
Component,
|
|
type ErrorInfo,
|
|
type FormEvent,
|
|
type ReactNode,
|
|
useEffect,
|
|
useRef,
|
|
useState,
|
|
} from 'react';
|
|
|
|
import type { AuthUser } from '../../../../packages/shared/src/contracts/auth';
|
|
import brandIcon from '../../../../packages/shared/src/icons/taonier-product-ip.png';
|
|
import { ErrorReportNotice } from '../components/error-report/ErrorReportNotice';
|
|
import { ClientActionError } from '../services/clientActionError';
|
|
import {
|
|
getClientAuthErrorMessage,
|
|
loginClientWithPassword,
|
|
loginClientWithPhoneCode,
|
|
logoutClientAuthSession,
|
|
normalizeAuthPhoneInput,
|
|
readClientAuthState,
|
|
resolveClientAuthFailure,
|
|
sendClientPhoneLoginCode,
|
|
subscribeClientAuthState,
|
|
} from '../services/clientAuth';
|
|
import {
|
|
type ClientServerPreset,
|
|
type ClientServerSelection,
|
|
clientServerSelectionEnabled,
|
|
getClientServerBaseUrl,
|
|
getClientServerSelection,
|
|
hydrateClientServerSelection,
|
|
normalizeClientServerBaseUrl,
|
|
setClientServerSelection,
|
|
} from '../services/clientHttp';
|
|
import {
|
|
captureClientError,
|
|
installWebviewLogBridge,
|
|
} from '../services/errorReporting';
|
|
import {
|
|
beginPlatformSessionClearTransition,
|
|
beginPlatformSessionTransition,
|
|
commitAuthenticatedPlatformSession,
|
|
currentPlatformSessionGeneration,
|
|
} from '../services/platformSession';
|
|
|
|
type ClientRuntimeErrorBoundaryProps = {
|
|
children: ReactNode;
|
|
onLogout: () => void;
|
|
};
|
|
|
|
type ClientRuntimeErrorBoundaryState = {
|
|
errorMessage: string;
|
|
};
|
|
|
|
type AuthCheckStage = 'token' | 'refresh' | 'me' | 'runner';
|
|
|
|
const AUTH_CHECK_STAGE_LABELS: Record<AuthCheckStage, string> = {
|
|
token: '读取本地登录凭据',
|
|
refresh: '刷新登录状态',
|
|
me: '确认当前用户',
|
|
runner: '连接本地运行时',
|
|
};
|
|
|
|
const AUTH_CHECK_REQUEST_TIMEOUT_MS = 15_000;
|
|
// Existing endpoint probes can consume the 10s IPC budget before Runner's
|
|
// 30s startup deadline. Keep the UI fence slightly above that worst case.
|
|
const AUTH_CHECK_RUNNER_TIMEOUT_MS = 45_000;
|
|
|
|
function withAuthCheckTimeout<T>(
|
|
promise: Promise<T>,
|
|
timeoutMs: number,
|
|
message: string,
|
|
) {
|
|
void promise.catch(() => undefined);
|
|
let timeoutId: number | undefined;
|
|
const timeout = new Promise<T>((_, reject) => {
|
|
timeoutId = window.setTimeout(() => reject(new Error(message)), timeoutMs);
|
|
});
|
|
return Promise.race([promise, timeout]).finally(() => {
|
|
if (timeoutId !== undefined) {
|
|
window.clearTimeout(timeoutId);
|
|
}
|
|
});
|
|
}
|
|
|
|
export class ClientRuntimeErrorBoundary extends Component<
|
|
ClientRuntimeErrorBoundaryProps,
|
|
ClientRuntimeErrorBoundaryState
|
|
> {
|
|
state: ClientRuntimeErrorBoundaryState = { errorMessage: '' };
|
|
|
|
static getDerivedStateFromError(error: unknown) {
|
|
return {
|
|
errorMessage:
|
|
error instanceof Error && error.message.trim()
|
|
? error.message
|
|
: '登录后页面发生未知错误',
|
|
};
|
|
}
|
|
|
|
componentDidCatch(error: unknown, errorInfo: ErrorInfo) {
|
|
console.error('AGC authenticated client render failed', error, errorInfo);
|
|
void captureClientError(error, { source: 'react-render' });
|
|
}
|
|
|
|
render() {
|
|
if (!this.state.errorMessage) {
|
|
return this.props.children;
|
|
}
|
|
return (
|
|
<main
|
|
className="client-auth-shell platform-theme platform-theme--light"
|
|
aria-label="客户端页面加载失败"
|
|
>
|
|
<section className="client-auth-panel">
|
|
<img className="client-auth-logo" src={brandIcon} alt="陶泥儿" />
|
|
<div>
|
|
<h1>客户端页面加载失败</h1>
|
|
<p className="client-auth-status">{this.state.errorMessage}</p>
|
|
</div>
|
|
<button type="button" onClick={this.props.onLogout}>
|
|
返回登录
|
|
</button>
|
|
</section>
|
|
</main>
|
|
);
|
|
}
|
|
}
|
|
|
|
export function AuthenticatedClient({
|
|
children,
|
|
}: {
|
|
children: (session: { user: AuthUser; logout: () => void }) => ReactNode;
|
|
}) {
|
|
const [authStatus, setAuthStatus] = useState<
|
|
'checking' | 'authenticated' | 'unauthenticated'
|
|
>('checking');
|
|
const [authUser, setAuthUser] = useState<AuthUser | null>(null);
|
|
const [authCheckStage, setAuthCheckStage] = useState<AuthCheckStage>('token');
|
|
const [authCheckElapsedSeconds, setAuthCheckElapsedSeconds] = useState(0);
|
|
const [authCheckError, setAuthCheckError] = useState('');
|
|
const [authCheckRetryKey, setAuthCheckRetryKey] = useState(0);
|
|
const authCheckRunRef = useRef(0);
|
|
/**
|
|
* 登录尝试代次。UI 的 45s 围栏只约束"等待":底层 native 提交仍在队列里跑,所以围栏超时后
|
|
* 仍要有人接手这次提交的结果。代次确保只有最近一次登录尝试的迟到结果能改变界面。
|
|
*/
|
|
const loginAttemptRef = useRef(0);
|
|
const [loginMode, setLoginMode] = useState<'code' | 'password'>('code');
|
|
const [phone, setPhone] = useState('');
|
|
const [code, setCode] = useState('');
|
|
const [password, setPassword] = useState('');
|
|
const [loginStatus, setLoginStatus] = useState('请登录后继续');
|
|
const [loginBusy, setLoginBusy] = useState(false);
|
|
const [codeBusy, setCodeBusy] = useState(false);
|
|
const [codeCooldownSeconds, setCodeCooldownSeconds] = useState(0);
|
|
const initialServerSelection = getClientServerSelection();
|
|
const [serverSelection, setServerSelection] = useState<ClientServerSelection>(
|
|
initialServerSelection,
|
|
);
|
|
const [customServerUrl, setCustomServerUrl] = useState(
|
|
initialServerSelection.customBaseUrl,
|
|
);
|
|
|
|
function persistServerSelection() {
|
|
try {
|
|
const next = setClientServerSelection({
|
|
preset: serverSelection.preset,
|
|
customBaseUrl: customServerUrl,
|
|
});
|
|
setServerSelection(next);
|
|
return true;
|
|
} catch (error) {
|
|
setLoginStatus(error instanceof Error ? error.message : String(error));
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function handleServerPresetChange(preset: ClientServerPreset) {
|
|
if (preset === 'custom') {
|
|
setServerSelection((current) => ({ ...current, preset }));
|
|
return;
|
|
}
|
|
const next = setClientServerSelection({
|
|
preset,
|
|
customBaseUrl: customServerUrl,
|
|
});
|
|
setServerSelection(next);
|
|
setLoginStatus(`已选择 ${preset} 服务器`);
|
|
}
|
|
// 服务器选择是 Rust 客户端偏好:本地 debug 启动时读一次,打包产物始终用渠道默认值。
|
|
useEffect(() => {
|
|
if (!clientServerSelectionEnabled) return;
|
|
let disposed = false;
|
|
void hydrateClientServerSelection().then((selection) => {
|
|
if (disposed) return;
|
|
setServerSelection(selection);
|
|
setCustomServerUrl(selection.customBaseUrl);
|
|
});
|
|
return () => {
|
|
disposed = true;
|
|
};
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
const uninstallWebviewLogBridge = installWebviewLogBridge();
|
|
const handleError = (event: ErrorEvent) => {
|
|
void captureClientError(event.error ?? event.message, {
|
|
source: 'window.onerror',
|
|
});
|
|
};
|
|
const handleRejection = (event: PromiseRejectionEvent) => {
|
|
void captureClientError(event.reason, { source: 'unhandledrejection' });
|
|
};
|
|
window.addEventListener('error', handleError);
|
|
window.addEventListener('unhandledrejection', handleRejection);
|
|
return () => {
|
|
uninstallWebviewLogBridge();
|
|
window.removeEventListener('error', handleError);
|
|
window.removeEventListener('unhandledrejection', handleRejection);
|
|
};
|
|
}, []);
|
|
|
|
/** 恢复登录态:凭据续期、用户复核与原生会话安装都在 Rust 内完成。 */
|
|
useEffect(() => {
|
|
let disposed = false;
|
|
async function hydrateAuth() {
|
|
const runId = ++authCheckRunRef.current;
|
|
const isActiveRun = () => !disposed && authCheckRunRef.current === runId;
|
|
setAuthCheckError('');
|
|
setAuthCheckStage('refresh');
|
|
try {
|
|
const state = await withAuthCheckTimeout(
|
|
readClientAuthState(getClientServerBaseUrl()),
|
|
AUTH_CHECK_REQUEST_TIMEOUT_MS,
|
|
'检查登录状态超时,请检查服务器地址和网络后重试',
|
|
);
|
|
if (!isActiveRun()) return;
|
|
if (state.status === 'unavailable') {
|
|
setAuthCheckError(state.message);
|
|
setLoginStatus(state.message);
|
|
setAuthStatus('unauthenticated');
|
|
return;
|
|
}
|
|
if (state.status !== 'authenticated') {
|
|
setAuthStatus('unauthenticated');
|
|
return;
|
|
}
|
|
setAuthCheckStage('runner');
|
|
const committedGeneration = await withAuthCheckTimeout(
|
|
commitAuthenticatedPlatformSession(
|
|
state.user,
|
|
currentPlatformSessionGeneration(),
|
|
state.apiBaseUrl,
|
|
),
|
|
AUTH_CHECK_RUNNER_TIMEOUT_MS,
|
|
'连接本地运行时超时,请重试或重启客户端',
|
|
);
|
|
if (committedGeneration === null || !isActiveRun()) return;
|
|
setAuthUser(state.user);
|
|
setAuthCheckError('');
|
|
setAuthStatus('authenticated');
|
|
} catch (error) {
|
|
if (!isActiveRun()) return;
|
|
const message = getClientAuthErrorMessage(
|
|
error,
|
|
'登录服务暂时不可用,请稍后重试',
|
|
);
|
|
setAuthCheckError(message);
|
|
setLoginStatus(message);
|
|
setAuthStatus('unauthenticated');
|
|
}
|
|
}
|
|
void hydrateAuth();
|
|
return () => {
|
|
disposed = true;
|
|
};
|
|
}, [authCheckRetryKey]);
|
|
useEffect(() => {
|
|
if (authStatus !== 'checking') {
|
|
return;
|
|
}
|
|
setAuthCheckElapsedSeconds(0);
|
|
const timer = window.setInterval(() => {
|
|
setAuthCheckElapsedSeconds((current) => current + 1);
|
|
}, 1000);
|
|
return () => window.clearInterval(timer);
|
|
}, [authStatus, authCheckRetryKey]);
|
|
|
|
// Rust 是认证态事实源:另一个窗口登录/登出、或 Rust 内部判定登录失效时同步界面。
|
|
useEffect(() => {
|
|
let disposed = false;
|
|
let unsubscribe: (() => void) | null = null;
|
|
void subscribeClientAuthState((state) => {
|
|
if (disposed) return;
|
|
if (state.status === 'authenticated') {
|
|
setAuthUser((current) =>
|
|
current?.id === state.user.id ? state.user : state.user,
|
|
);
|
|
setAuthCheckError('');
|
|
setAuthStatus('authenticated');
|
|
return;
|
|
}
|
|
setAuthUser(null);
|
|
setAuthStatus('unauthenticated');
|
|
setLoginStatus('登录已失效,请重新登录');
|
|
})
|
|
.then((release) => {
|
|
if (disposed) release();
|
|
else unsubscribe = release;
|
|
})
|
|
.catch(() => undefined);
|
|
return () => {
|
|
disposed = true;
|
|
unsubscribe?.();
|
|
};
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (codeCooldownSeconds <= 0) {
|
|
return;
|
|
}
|
|
const timer = window.setInterval(() => {
|
|
setCodeCooldownSeconds((current) => Math.max(0, current - 1));
|
|
}, 1000);
|
|
return () => window.clearInterval(timer);
|
|
}, [codeCooldownSeconds]);
|
|
|
|
/**
|
|
* 认证动作失败的统一收口:可识别的业务 / 会话拒绝只给用户提示;真故障与未识别变体带上文交给
|
|
* 错误池。`action` 决定错误池指纹,新增认证动作必须走这里、不要在各自的 catch 里另拼一套。
|
|
*/
|
|
function presentAuthFailure(
|
|
error: unknown,
|
|
fallback: string,
|
|
action: string,
|
|
) {
|
|
const failure = resolveClientAuthFailure(error, fallback);
|
|
setLoginStatus(failure.message);
|
|
if (failure.kind === 'report') {
|
|
void captureClientError(
|
|
new ClientActionError(
|
|
failure.message,
|
|
{ source: 'auth', action },
|
|
error,
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
async function handleSendCode() {
|
|
if (codeBusy || codeCooldownSeconds > 0) {
|
|
return;
|
|
}
|
|
if (!persistServerSelection()) return;
|
|
const apiBaseUrl = getClientServerBaseUrl();
|
|
const normalizedPhone = normalizeAuthPhoneInput(phone);
|
|
if (!normalizedPhone) {
|
|
setLoginStatus('请输入手机号');
|
|
return;
|
|
}
|
|
setCodeBusy(true);
|
|
setLoginStatus('正在发送验证码');
|
|
try {
|
|
const response = await sendClientPhoneLoginCode(
|
|
normalizedPhone,
|
|
apiBaseUrl,
|
|
);
|
|
setCodeCooldownSeconds(Math.max(0, Math.floor(response.cooldownSeconds)));
|
|
setLoginStatus(`验证码已发送,${response.expiresInSeconds} 秒内有效`);
|
|
} catch (error) {
|
|
presentAuthFailure(error, '发送验证码失败', 'send-login-code');
|
|
} finally {
|
|
setCodeBusy(false);
|
|
}
|
|
}
|
|
|
|
async function handleLoginSubmit(event: FormEvent<HTMLFormElement>) {
|
|
event.preventDefault();
|
|
if (loginBusy) {
|
|
return;
|
|
}
|
|
const normalizedPhone = normalizeAuthPhoneInput(phone);
|
|
if (!normalizedPhone) {
|
|
setLoginStatus('请输入手机号');
|
|
return;
|
|
}
|
|
if (loginMode === 'code' && !code.trim()) {
|
|
setLoginStatus('请输入验证码');
|
|
return;
|
|
}
|
|
if (loginMode === 'password' && !password.trim()) {
|
|
setLoginStatus('请输入密码');
|
|
return;
|
|
}
|
|
if (!persistServerSelection()) return;
|
|
const loginApiBaseUrl = getClientServerBaseUrl();
|
|
const loginAttempt = (loginAttemptRef.current += 1);
|
|
setLoginBusy(true);
|
|
setLoginStatus('正在登录');
|
|
const loginGeneration = beginPlatformSessionTransition();
|
|
try {
|
|
// Rust 登录命令内部完成:凭据持久化 → 本机运行时会话安装 → Runner 传播 → 事件。
|
|
const user =
|
|
loginMode === 'code'
|
|
? await loginClientWithPhoneCode(
|
|
normalizedPhone,
|
|
code,
|
|
loginApiBaseUrl,
|
|
)
|
|
: await loginClientWithPassword(
|
|
normalizedPhone,
|
|
password,
|
|
loginApiBaseUrl,
|
|
);
|
|
const committedGeneration = await withAuthCheckTimeout(
|
|
commitAuthenticatedPlatformSession(
|
|
user,
|
|
loginGeneration,
|
|
loginApiBaseUrl,
|
|
),
|
|
AUTH_CHECK_RUNNER_TIMEOUT_MS,
|
|
'连接本地运行时超时,请重试或重启客户端',
|
|
);
|
|
if (committedGeneration === null) {
|
|
return;
|
|
}
|
|
if (loginAttemptRef.current !== loginAttempt) {
|
|
return;
|
|
}
|
|
setAuthUser(user);
|
|
setAuthCheckError('');
|
|
setAuthStatus('authenticated');
|
|
setCode('');
|
|
setPassword('');
|
|
} catch (error) {
|
|
presentAuthFailure(error, '登录失败', 'login');
|
|
} finally {
|
|
setLoginBusy(false);
|
|
}
|
|
}
|
|
async function logout() {
|
|
beginPlatformSessionClearTransition();
|
|
let nativeClearError: unknown = null;
|
|
try {
|
|
await withAuthCheckTimeout(
|
|
logoutClientAuthSession(),
|
|
AUTH_CHECK_RUNNER_TIMEOUT_MS,
|
|
'清理本地运行时超时,请重启客户端后再登录',
|
|
);
|
|
} catch (error) {
|
|
nativeClearError = error;
|
|
}
|
|
setAuthUser(null);
|
|
setAuthCheckError('');
|
|
setAuthStatus('unauthenticated');
|
|
setLoginStatus(
|
|
nativeClearError
|
|
? '已退出登录;本地运行时登录态同步失败,请重启客户端后再登录'
|
|
: '已退出登录',
|
|
);
|
|
}
|
|
|
|
if (authStatus === 'checking') {
|
|
const stageLabel = AUTH_CHECK_STAGE_LABELS[authCheckStage];
|
|
return (
|
|
<main
|
|
className="client-auth-shell platform-theme platform-theme--light"
|
|
aria-label="登录状态检查"
|
|
>
|
|
<section className="client-auth-panel">
|
|
<img className="client-auth-logo" src={brandIcon} alt="陶泥儿" />
|
|
<h1>正在检查登录状态</h1>
|
|
<p className="client-auth-status" aria-live="polite">
|
|
{stageLabel} · 已等待 {authCheckElapsedSeconds} 秒
|
|
</p>
|
|
<p className="client-auth-status" aria-live="polite">
|
|
{authCheckElapsedSeconds >= 8
|
|
? '检查时间较长,请确认服务器可访问;若持续无响应可稍后重试'
|
|
: '正在恢复会话,请稍候'}
|
|
</p>
|
|
</section>
|
|
</main>
|
|
);
|
|
}
|
|
|
|
if (!authUser) {
|
|
return (
|
|
<main
|
|
className="client-auth-shell platform-theme platform-theme--light"
|
|
aria-label="登录"
|
|
>
|
|
<form className="client-auth-panel" onSubmit={handleLoginSubmit}>
|
|
<img className="client-auth-logo" src={brandIcon} alt="陶泥儿" />
|
|
<div>
|
|
<h1>登录陶泥儿 GameAgent</h1>
|
|
<p>登录后进入首页和本地项目工作区</p>
|
|
</div>
|
|
{clientServerSelectionEnabled ? (
|
|
<>
|
|
<label>
|
|
服务器
|
|
<select
|
|
aria-label="服务器"
|
|
disabled={loginBusy || codeBusy}
|
|
value={serverSelection.preset}
|
|
onChange={(event) =>
|
|
handleServerPresetChange(
|
|
event.currentTarget.value as ClientServerPreset,
|
|
)
|
|
}
|
|
>
|
|
<option value="release">release</option>
|
|
<option value="dev">dev</option>
|
|
<option value="custom">custom</option>
|
|
</select>
|
|
</label>
|
|
{serverSelection.preset === 'custom' ? (
|
|
<label>
|
|
自定义服务器地址
|
|
<input
|
|
aria-label="自定义服务器地址"
|
|
disabled={loginBusy || codeBusy}
|
|
inputMode="url"
|
|
placeholder="https://example.com"
|
|
value={customServerUrl}
|
|
onChange={(event) =>
|
|
setCustomServerUrl(event.currentTarget.value)
|
|
}
|
|
onBlur={() => {
|
|
if (!customServerUrl.trim()) return;
|
|
try {
|
|
normalizeClientServerBaseUrl(customServerUrl);
|
|
persistServerSelection();
|
|
} catch (error) {
|
|
setLoginStatus(
|
|
error instanceof Error
|
|
? error.message
|
|
: String(error),
|
|
);
|
|
}
|
|
}}
|
|
/>
|
|
</label>
|
|
) : null}
|
|
</>
|
|
) : null}
|
|
{authCheckError ? (
|
|
<div role="alert" className="client-auth-status">
|
|
<p>{authCheckError}</p>
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
beginPlatformSessionTransition();
|
|
setAuthCheckError('');
|
|
setAuthStatus('checking');
|
|
setAuthCheckRetryKey((current) => current + 1);
|
|
}}
|
|
disabled={loginBusy || codeBusy}
|
|
>
|
|
重试登录状态检查
|
|
</button>
|
|
</div>
|
|
) : null}
|
|
<div className="client-auth-tabs" role="group" aria-label="登录方式">
|
|
<button
|
|
type="button"
|
|
className={loginMode === 'code' ? 'is-active' : ''}
|
|
onClick={() => setLoginMode('code')}
|
|
>
|
|
验证码登录
|
|
</button>
|
|
<button
|
|
type="button"
|
|
className={loginMode === 'password' ? 'is-active' : ''}
|
|
onClick={() => setLoginMode('password')}
|
|
>
|
|
密码登录
|
|
</button>
|
|
</div>
|
|
<label>
|
|
手机号
|
|
<input
|
|
autoComplete="tel"
|
|
inputMode="tel"
|
|
value={phone}
|
|
onChange={(event) => setPhone(event.currentTarget.value)}
|
|
/>
|
|
</label>
|
|
{loginMode === 'code' ? (
|
|
<div className="client-auth-code-row">
|
|
<label>
|
|
验证码
|
|
<input
|
|
autoComplete="one-time-code"
|
|
inputMode="numeric"
|
|
value={code}
|
|
onChange={(event) => setCode(event.currentTarget.value)}
|
|
/>
|
|
</label>
|
|
<button
|
|
type="button"
|
|
onClick={handleSendCode}
|
|
disabled={codeBusy || codeCooldownSeconds > 0}
|
|
>
|
|
{codeBusy
|
|
? '发送中'
|
|
: codeCooldownSeconds > 0
|
|
? `${codeCooldownSeconds}s`
|
|
: '获取验证码'}
|
|
</button>
|
|
</div>
|
|
) : (
|
|
<label>
|
|
密码
|
|
<input
|
|
autoComplete="current-password"
|
|
type="password"
|
|
value={password}
|
|
onChange={(event) => setPassword(event.currentTarget.value)}
|
|
/>
|
|
</label>
|
|
)}
|
|
<button type="submit" disabled={loginBusy}>
|
|
{loginBusy ? '登录中' : '登录'}
|
|
</button>
|
|
{!authCheckError ? (
|
|
<p className="client-auth-status">{loginStatus}</p>
|
|
) : null}
|
|
</form>
|
|
</main>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<ClientRuntimeErrorBoundary onLogout={logout}>
|
|
{children({ user: authUser, logout })}
|
|
</ClientRuntimeErrorBoundary>
|
|
<ErrorReportNotice />
|
|
</>
|
|
);
|
|
}
|