Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
@@ -0,0 +1,77 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { Avatar, Radio, RadioGroup, Typography } from '@douyinfe/semi-ui';
import { Building2, User } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { optionKey } from './authorizeParams';
const { Text } = Typography;
/**
* 授权范围选择:「个人」或所属的某个企业。选项由 oauth/context 返回。
*/
const ScopeOptionList = ({ options, value, onChange, disabled }) => {
const { t } = useTranslation();
return (
<RadioGroup
type='pureCard'
direction='vertical'
value={value}
disabled={disabled}
onChange={(e) => onChange(e.target.value)}
aria-label={t('选择使用范围')}
className='w-full'
>
{options.map((option) => {
const isOrg = option.scope === 'organization';
const key = optionKey(option);
return (
<Radio
key={key}
value={key}
className='w-full'
extra={
<Text type='tertiary' size='small'>
{isOrg ? t('企业范围') : t('个人范围')}
</Text>
}
>
<div className='flex items-center gap-2 min-w-0'>
{option.logo ? (
<Avatar src={option.logo} size='extra-small' shape='square' />
) : (
<Avatar size='extra-small' shape='square' color='light-blue'>
{isOrg ? <Building2 size={14} /> : <User size={14} />}
</Avatar>
)}
<Text strong ellipsis={{ showTooltip: true }}>
{isOrg ? option.name : option.name || t('个人')}
</Text>
</div>
</Radio>
);
})}
</RadioGroup>
);
};
export default ScopeOptionList;
+428
View File
@@ -0,0 +1,428 @@
/* 进入 WeyAi 的过渡画面。配色全部由主题 token 派生(品牌色换预设、亮暗切换
都自动跟随),整页背景交给 PageBackground 单层渲染,这里只画徽标、进度与
一个聚焦用的居中光晕。动效在 prefers-reduced-motion 下全部关闭。 */
.weyai-handoff {
--ho-ink: var(--text-primary);
--ho-muted: var(--text-secondary);
--ho-line: var(--border-subtle);
--ho-card: var(--surface-card);
/* 主色只取品牌 token:--semi-color-primary 要等 /api/status 回来由
helpers/theme.js 注入,首次访问(OAuth 从 WeyAi 拉起的新会话正是这种)
在那之前是 Semi 默认蓝,与 --brand-primary-rgb 派生的环/光晕会是两种蓝。
两个变量同批注入、同源,注入前后都一致 */
--ho-accent: rgb(var(--brand-primary-rgb));
--ho-accent-rgb: var(--brand-primary-rgb);
--ho-tint: color-mix(in srgb, var(--ho-accent) 12%, transparent);
--ho-tint-strong: color-mix(in srgb, var(--ho-accent) 28%, transparent);
color: var(--ho-ink);
}
/* ───── 居中光晕 ───── */
.weyai-handoff__halo {
position: absolute;
left: 50%;
top: 50%;
width: min(70vw, 560px);
height: min(70vw, 560px);
transform: translate(-50%, -56%);
border-radius: 50%;
background: radial-gradient(
circle at center,
rgb(var(--ho-accent-rgb) / 0.22) 0%,
rgb(var(--ho-accent-rgb) / 0.08) 38%,
transparent 70%
);
/* 不加 filter: blur —— 径向渐变到 70% 已是透明,模糊看不出差别,却让
低端机每帧多做一次几百像素的 GPU 模糊 */
pointer-events: none;
animation: weyai-handoff-breathe 5s ease-in-out infinite;
}
.dark .weyai-handoff__halo {
background: radial-gradient(
circle at center,
rgb(var(--ho-accent-rgb) / 0.3) 0%,
rgb(var(--ho-accent-rgb) / 0.1) 38%,
transparent 70%
);
}
/* ───── 内容面板 ───── */
.weyai-handoff__panel {
width: 100%;
max-width: 420px;
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
padding: 8px 0 24px;
animation: weyai-handoff-rise 0.3s cubic-bezier(0.22, 1, 0.36, 1) both;
}
/* ───── 徽标:脉动光环 + 旋转弧 + 环绕光点 + 品牌 tile ───── */
.weyai-handoff__emblem {
position: relative;
width: 128px;
height: 128px;
margin-bottom: 28px;
}
.weyai-handoff__pulse {
position: absolute;
inset: -18px;
border-radius: 50%;
background: radial-gradient(
circle,
rgb(var(--ho-accent-rgb) / 0.28) 0%,
rgb(var(--ho-accent-rgb) / 0.06) 55%,
transparent 72%
);
animation: weyai-handoff-pulse 2.4s ease-out infinite;
}
.weyai-handoff__ring {
position: absolute;
inset: 0;
border-radius: 50%;
background: conic-gradient(
from 0deg,
transparent 0deg,
transparent 200deg,
rgb(var(--ho-accent-rgb) / 0.15) 260deg,
rgb(var(--ho-accent-rgb) / 0.95) 360deg
);
/* mask 只取 alpha:把实心圆盘挖成 3px 圆环。颜色值本身不参与显示 */
-webkit-mask: radial-gradient(
farthest-side,
transparent calc(100% - 3.5px),
#000 calc(100% - 2.5px)
);
mask: radial-gradient(
farthest-side,
transparent calc(100% - 3.5px),
#000 calc(100% - 2.5px)
);
animation: weyai-handoff-spin 1.3s linear infinite;
}
.weyai-handoff__orbit {
position: absolute;
inset: 12px;
border-radius: 50%;
border: 1px dashed var(--ho-tint-strong);
animation: weyai-handoff-spin 6s linear infinite reverse;
}
.weyai-handoff__orbit i {
position: absolute;
top: -5px;
left: calc(50% - 5px);
width: 10px;
height: 10px;
border-radius: 50%;
background: var(--ho-accent);
box-shadow: 0 0 0 4px rgb(var(--ho-accent-rgb) / 0.18);
}
.weyai-handoff__tile {
position: absolute;
inset: 30px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 18px;
background: var(--ho-card);
border: 1px solid color-mix(in srgb, var(--ho-accent) 18%, var(--ho-line));
box-shadow:
0 18px 40px -16px rgb(var(--ho-accent-rgb) / 0.45),
0 2px 6px rgb(var(--ho-accent-rgb) / 0.08);
}
.weyai-handoff__logo {
width: 40px;
height: 40px;
border-radius: 10px;
object-fit: cover;
}
/* ───── 文案 ───── */
.weyai-handoff__title {
margin: 0 0 6px;
font-size: 22px;
font-weight: 700;
letter-spacing: -0.01em;
line-height: 1.3;
color: var(--ho-ink);
}
.weyai-handoff__dots {
display: inline-flex;
gap: 3px;
margin-left: 4px;
vertical-align: baseline;
}
.weyai-handoff__dots i {
width: 4px;
height: 4px;
border-radius: 50%;
background: var(--ho-accent);
opacity: 0.25;
animation: weyai-handoff-blink 1.2s ease-in-out infinite;
}
.weyai-handoff__dots i:nth-child(2) {
animation-delay: 0.2s;
}
.weyai-handoff__dots i:nth-child(3) {
animation-delay: 0.4s;
}
.weyai-handoff__subtitle {
margin: 0 0 28px;
font-size: 13px;
line-height: 1.5;
color: var(--ho-muted);
}
/* ───── 三步进度 ───── */
.weyai-handoff__steps {
list-style: none;
margin: 0 0 14px;
padding: 0;
display: flex;
align-items: flex-start;
justify-content: center;
width: 100%;
}
.weyai-handoff__step {
position: relative;
flex: 1 1 0;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
min-width: 0;
}
.weyai-handoff__step-dot {
display: flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
border-radius: 50%;
border: 2px solid var(--ho-line);
background: var(--ho-card);
color: var(--ho-card);
transition:
border-color 0.2s,
background-color 0.2s,
box-shadow 0.2s;
}
/* 标签允许折两行:390px 下每步只有约 110px,英/日/泰/越的"建立安全会话"
单行放不下,nowrap + 省略号会把它切成 "Establish secure se…" */
.weyai-handoff__step-label {
max-width: 100%;
padding: 0 4px;
font-size: 12px;
line-height: 1.3;
color: var(--ho-muted);
overflow-wrap: anywhere;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
transition: color 0.2s;
}
/* 连接线:从本步圆点右缘到下一步圆点左缘 */
.weyai-handoff__step-line {
position: absolute;
top: 10px;
left: calc(50% + 13px);
right: calc(-50% + 13px);
height: 2px;
border-radius: 2px;
background: var(--ho-line);
}
.weyai-handoff__step--done .weyai-handoff__step-dot {
border-color: var(--ho-accent);
background: var(--ho-accent);
color: var(--ho-card);
}
.weyai-handoff__step--done .weyai-handoff__step-line {
background: var(--ho-accent);
}
.weyai-handoff__step--done .weyai-handoff__step-label {
color: var(--ho-ink);
}
.weyai-handoff__step--active .weyai-handoff__step-dot {
border-color: var(--ho-accent);
box-shadow: 0 0 0 5px var(--ho-tint);
animation: weyai-handoff-dot 1.6s ease-in-out infinite;
}
.weyai-handoff__step--active .weyai-handoff__step-label {
color: var(--ho-accent);
font-weight: 600;
}
/* ───── 进度条:宽度跟真实阶段走,高光只是让它"活着" ───── */
.weyai-handoff__bar {
position: relative;
width: min(100%, 280px);
height: 4px;
border-radius: 999px;
background: var(--ho-tint);
overflow: hidden;
}
.weyai-handoff__bar-fill {
position: absolute;
left: 0;
top: 0;
bottom: 0;
border-radius: inherit;
overflow: hidden;
background: linear-gradient(
90deg,
color-mix(in srgb, var(--ho-accent) 70%, var(--ho-card)),
var(--ho-accent)
);
transition: width 0.2s cubic-bezier(0.22, 1, 0.36, 1);
}
/* 镜面高光:白色是"反光"本身而非配色,属固定色例外;只在已填充段内扫动 */
.weyai-handoff__bar-shine {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 40%;
border-radius: inherit;
background: linear-gradient(
90deg,
transparent,
rgb(255 255 255 / 0.55),
transparent
);
animation: weyai-handoff-shine 1.8s ease-in-out infinite;
}
/* ───── 跳转卡住时的手动入口 ───── */
.weyai-handoff__manual {
margin-top: 22px;
padding: 8px 16px;
border-radius: 999px;
font: inherit;
font-size: 13px;
font-weight: 600;
/* 主色直接放在淡色底上约 4.1:1,不到 AA;往墨色压两成,亮色压深、暗色提亮 */
color: color-mix(in srgb, var(--ho-accent) 80%, var(--ho-ink));
background: var(--ho-tint);
border: 1px solid var(--ho-tint-strong);
cursor: pointer;
text-decoration: none;
transition:
background-color 0.2s,
box-shadow 0.2s;
animation: weyai-handoff-rise 0.3s ease-out both;
}
.weyai-handoff__manual:hover {
background: var(--ho-tint-strong);
}
.weyai-handoff__manual:focus-visible {
outline: 2px solid color-mix(in srgb, var(--ho-accent) 55%, transparent);
outline-offset: 2px;
}
/* ───── 动画 ───── */
@keyframes weyai-handoff-spin {
to {
transform: rotate(360deg);
}
}
@keyframes weyai-handoff-pulse {
0% {
transform: scale(0.85);
opacity: 0.9;
}
70% {
transform: scale(1.15);
opacity: 0;
}
100% {
transform: scale(1.15);
opacity: 0;
}
}
@keyframes weyai-handoff-breathe {
0%,
100% {
opacity: 0.75;
transform: translate(-50%, -56%) scale(1);
}
50% {
opacity: 1;
transform: translate(-50%, -56%) scale(1.06);
}
}
@keyframes weyai-handoff-rise {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes weyai-handoff-blink {
0%,
80%,
100% {
opacity: 0.25;
}
40% {
opacity: 1;
}
}
@keyframes weyai-handoff-dot {
0%,
100% {
box-shadow: 0 0 0 4px var(--ho-tint);
}
50% {
box-shadow: 0 0 0 7px var(--ho-tint);
}
}
@keyframes weyai-handoff-shine {
from {
transform: translateX(-100%);
}
to {
transform: translateX(250%);
}
}
@media (prefers-reduced-motion: reduce) {
.weyai-handoff__halo,
.weyai-handoff__panel,
.weyai-handoff__pulse,
.weyai-handoff__ring,
.weyai-handoff__orbit,
.weyai-handoff__dots i,
.weyai-handoff__step--active .weyai-handoff__step-dot,
.weyai-handoff__bar-shine,
.weyai-handoff__manual,
.weyai-handoff .animate-pulse {
animation: none;
}
.weyai-handoff__dots i {
opacity: 0.6;
}
.weyai-handoff__bar-shine {
display: none;
}
}
@media (max-width: 480px) {
.weyai-handoff__emblem {
width: 108px;
height: 108px;
}
.weyai-handoff__tile {
inset: 26px;
}
.weyai-handoff__title {
font-size: 19px;
}
.weyai-handoff__step-label {
font-size: 11px;
}
}
+158
View File
@@ -0,0 +1,158 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// 进入 WeyAi 的过渡画面。授权页在三个瞬态里没有任何可操作内容:拉授权信息、
// 静默签发、授权完成等浏览器跳走。原来这三态套在登录卡片里只放一个 Spin,
// 而登录页背景主题是按需懒加载的 chunk,这个页面通常在 chunk 到达前就跳走了,
// 用户看到的是"空白底 + 小转圈"。这里改为:同步渲染的 token 派生背景
// (PageBackground,随主题预设与亮暗自动变化)+ 品牌环形加载动画 + 三步
// 真实进度(按 phase 推进,不是假进度条)。
//
// 跳转卡住的兜底:授权完成后浏览器应当立刻跳走,若数秒后还停在这里(弹窗
// 拦截、location.replace 被扩展拦下),显示手动入口,用户不至于干等。手动
// 入口是**重新走一遍授权**(整页刷新),不是再打一次回跳地址:回跳地址里的
// code 只能核销一次,若第一次跳转其实已经到达网关只是慢,再打一次会让网关
// 拿着已核销的 code 报错,反而把本来会成功的登录弄坏。刷新会重新拉上下文、
// 静默签发新 code,无论第一次是没发出去还是发出去了都能收敛。
import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Check } from 'lucide-react';
import PageBackground from '../../components/common/PageBackground';
import './WeyAiHandoff.css';
// 授权完成后等多久还没跳走就露出手动入口。网关换 token 正常在 1 秒内,
// 8 秒仍未离开这一页基本可以断定跳转没发出去
const MANUAL_RETRY_DELAY_MS = 8000;
export const HANDOFF_STAGE_LOADING = 0;
export const HANDOFF_STAGE_ISSUING = 1;
export const HANDOFF_STAGE_REDIRECT = 2;
export default function WeyAiHandoff({
logo,
stage,
title,
subtitle,
clientName = 'WeyAi',
}) {
const { t } = useTranslation();
const [showManual, setShowManual] = useState(false);
useEffect(() => {
if (stage !== HANDOFF_STAGE_REDIRECT) {
setShowManual(false);
return undefined;
}
const timer = setTimeout(() => setShowManual(true), MANUAL_RETRY_DELAY_MS);
return () => clearTimeout(timer);
}, [stage]);
const steps = [
t('验证账号'),
t('建立安全会话'),
t('打开 {{name}}', { name: clientName }),
];
return (
<div
className='weyai-handoff relative overflow-hidden flex items-center justify-center px-4 sm:px-6 lg:px-8'
style={{ minHeight: 'calc(100vh - var(--content-top-offset, 0px))' }}
>
<PageBackground variant='rich' grid animate />
{/* 居中光晕:把视线聚到徽标上,颜色随品牌色 */}
<div className='weyai-handoff__halo' aria-hidden='true' />
<div className='weyai-handoff__panel relative z-10'>
<div className='weyai-handoff__emblem' aria-hidden='true'>
<span className='weyai-handoff__pulse' />
<span className='weyai-handoff__ring' />
<span className='weyai-handoff__orbit'>
<i />
</span>
<span className='weyai-handoff__tile'>
<img src={logo} alt='' className='weyai-handoff__logo' />
</span>
</div>
{/* 播报区只包住标题与副标题:整块面板做 live region 会把三个步骤名
和链接一并复读,而步骤推进本身又不改文本、读屏听不到 */}
<div role='status' aria-live='polite'>
<h1 className='weyai-handoff__title'>
{title}
<span className='weyai-handoff__dots' aria-hidden='true'>
<i />
<i />
<i />
</span>
</h1>
<p className='weyai-handoff__subtitle'>{subtitle}</p>
</div>
<ol className='weyai-handoff__steps' aria-label={t('进度')}>
{steps.map((label, index) => {
const state =
index < stage ? 'done' : index === stage ? 'active' : 'todo';
return (
<li
key={label}
className={`weyai-handoff__step weyai-handoff__step--${state}`}
aria-current={state === 'active' ? 'step' : undefined}
>
<span className='weyai-handoff__step-dot'>
{state === 'done' ? (
<Check size={11} strokeWidth={3} />
) : null}
</span>
<span className='weyai-handoff__step-label'>{label}</span>
{index < steps.length - 1 && (
<span
className='weyai-handoff__step-line'
aria-hidden='true'
/>
)}
</li>
);
})}
</ol>
<div className='weyai-handoff__bar' aria-hidden='true'>
{/* 高光放在已填充段内部:放在轨道上会扫过未填充的那截,暗色下像
多了一根乱动的亮条 */}
<span
className='weyai-handoff__bar-fill'
style={{ width: `${((stage + 1) / steps.length) * 100}%` }}
>
<span className='weyai-handoff__bar-shine' />
</span>
</div>
{showManual && (
<button
type='button'
className='weyai-handoff__manual'
onClick={() => window.location.reload()}
>
{t('没有自动跳转?点此重试')}
</button>
)}
</div>
</div>
);
}
@@ -0,0 +1,101 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// 授权页的纯函数(不依赖 React 和请求封装,便于单测)。
export const DESKTOP_CLIENT_ID = 'weyai-desktop';
// 页面从地址栏读取、原样透传给服务端的参数(页面自己不拼 redirect_uri)
export const AUTHORIZE_PARAM_KEYS = [
'client_id',
'redirect_uri',
'state',
'code_challenge',
'code_challenge_method',
'scope_hint',
'device_name',
'prompt',
];
export function readAuthorizeParams(searchParams) {
const params = {};
AUTHORIZE_PARAM_KEYS.forEach((key) => {
params[key] = searchParams.get(key) || '';
});
return params;
}
/**
* 把 axios 错误或 success:false 响应统一成 { status, code, message, data }。
*/
export function parseClientApiError(error) {
const response = error?.response;
const body = response?.data;
const isObject = body && typeof body === 'object';
return {
status: response?.status || 0,
code: (isObject && body.code) || '',
message: (isObject && body.message) || '',
data: (isObject && body.data) || null,
};
}
/**
* 只放行服务端返回的 http(s) 或 weyai: 跳转地址,挡住 javascript:/data: 之类的伪协议。
* 地址本身由服务端按登记的 redirect_uri 生成,页面不做任何拼接。
*/
export function isAllowedRedirect(redirect) {
if (!redirect || typeof redirect !== 'string') return false;
let url;
try {
url = new URL(redirect);
} catch (_e) {
return false;
}
return ['https:', 'http:', 'weyai:'].includes(url.protocol);
}
/**
* 未登录时的登录页地址:按 scope_hint 去个人登录或企业登录,登录后回到当前授权页。
* 没有 scope_hint(网页端网关发起)时与 PrivateRoute 一致,默认去企业登录页,
* 页内可切换到个人登录,回跳地址已由登录页写入本地存储。
*/
export function buildLoginTarget(scopeHint, currentPath) {
const base = scopeHint === 'personal' ? '/login' : '/org/login';
return `${base}?redirect=${encodeURIComponent(currentPath)}`;
}
/**
* GET oauth/context 的查询参数:client_id、redirect_uri 决定合法性,prompt 决定是否
* 静默,scope_hint(personal / organization,桌面端登录入口带)决定默认选中个人还是企业。
* 空值不传,避免服务端把空串当成显式的 hint。
*/
export function buildContextQuery(params) {
const query = {};
['client_id', 'redirect_uri', 'prompt', 'scope_hint'].forEach((key) => {
const value = params?.[key];
if (value) query[key] = value;
});
return query;
}
export function optionKey(option) {
if (!option) return '';
return `${option.scope}:${Number(option.org_id) || 0}`;
}
@@ -0,0 +1,113 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import assert from 'node:assert/strict';
import test from 'node:test';
import {
buildContextQuery,
buildLoginTarget,
isAllowedRedirect,
optionKey,
parseClientApiError,
readAuthorizeParams,
} from './authorizeParams.js';
test('isAllowedRedirect only accepts http(s) and weyai schemes', () => {
assert.equal(isAllowedRedirect('weyai://auth/callback?code=a&state=b'), true);
assert.equal(isAllowedRedirect('https://ai.example.com/sso/callback'), true);
assert.equal(isAllowedRedirect('javascript:alert(1)'), false);
assert.equal(isAllowedRedirect('data:text/html,hi'), false);
assert.equal(isAllowedRedirect('/relative'), false);
assert.equal(isAllowedRedirect(''), false);
assert.equal(isAllowedRedirect(undefined), false);
});
test('buildLoginTarget follows scope_hint and keeps the return path', () => {
const path = '/client/authorize?client_id=weyai-desktop&state=x';
assert.equal(
buildLoginTarget('personal', path),
`/login?redirect=${encodeURIComponent(path)}`,
);
assert.equal(
buildLoginTarget('organization', path),
`/org/login?redirect=${encodeURIComponent(path)}`,
);
assert.equal(
buildLoginTarget('', path),
`/org/login?redirect=${encodeURIComponent(path)}`,
);
});
test('readAuthorizeParams reads every known param with empty defaults', () => {
const params = readAuthorizeParams(
new URLSearchParams('client_id=weyai-web&prompt=select&extra=1'),
);
assert.equal(params.client_id, 'weyai-web');
assert.equal(params.prompt, 'select');
assert.equal(params.redirect_uri, '');
assert.equal('extra' in params, false);
});
test('optionKey distinguishes personal and organization scopes', () => {
assert.equal(optionKey({ scope: 'personal', org_id: 0 }), 'personal:0');
assert.equal(
optionKey({ scope: 'organization', org_id: '12' }),
'organization:12',
);
assert.equal(optionKey(null), '');
});
test('parseClientApiError extracts code, message and data', () => {
const err = parseClientApiError({
response: {
status: 403,
data: {
success: false,
code: 'SCOPE_NOT_ALLOWED',
message: 'no',
data: { reason: 'org_only' },
},
},
});
assert.deepEqual(err, {
status: 403,
code: 'SCOPE_NOT_ALLOWED',
message: 'no',
data: { reason: 'org_only' },
});
assert.equal(parseClientApiError(new Error('network')).status, 0);
});
test('buildContextQuery forwards scope_hint and drops empty values', () => {
assert.deepEqual(
buildContextQuery({
client_id: 'weyai-desktop',
redirect_uri: 'weyai://auth/callback',
state: 'xyz',
scope_hint: 'organization',
prompt: '',
}),
{
client_id: 'weyai-desktop',
redirect_uri: 'weyai://auth/callback',
scope_hint: 'organization',
},
);
assert.deepEqual(buildContextQuery(undefined), {});
});
@@ -0,0 +1,56 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// WeyAi 客户端授权页(/client/authorize)的接口封装。
// 接口约定见 WeyAi 仓库 docs/fork/账号登录接入方案.md 4.2、4.4:
// 成功 { success: true, data };失败 { success: false, code, message, data },
// 客户端只按 code 分支。
import { API } from '../../helpers/api';
import { buildContextQuery } from './authorizeParams';
function unwrap(res) {
const body = res?.data;
if (body && body.success === false) {
const err = new Error(body.message || 'request failed');
err.response = res;
throw err;
}
// 兼容 { success, data } 与直接返回数据两种形态
if (body && typeof body === 'object' && 'data' in body) {
return body.data;
}
return body;
}
export async function fetchOAuthContext(params) {
const res = await API.get('/api/client/v1/oauth/context', {
params: buildContextQuery(params),
skipErrorHandler: true,
disableDuplicate: true,
});
return unwrap(res);
}
export async function submitAuthorize(payload) {
const res = await API.post('/api/client/v1/oauth/authorize', payload, {
skipErrorHandler: true,
});
return unwrap(res);
}
+553
View File
@@ -0,0 +1,553 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// WeyAi 客户端授权页 /client/authorize(方案 4.4)。
// - 自带登录判断,不套 PrivateRoute(PrivateRoute 总是去企业登录页)。
// - client_id / redirect_uri 不合法时只报错、不做任何跳转。
// - 所有跳转地址都用服务端返回的 redirect,页面绝不自己拼 redirect_uri。
// - 页面禁止被嵌入:服务端应下发 X-Frame-Options / frame-ancestors,这里再做前端兜底。
import React, {
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Banner, Button, Typography } from '@douyinfe/semi-ui';
import { Monitor } from 'lucide-react';
import { API } from '../../helpers/api';
import { clearUserData, getLogo } from '../../helpers';
import { UserContext } from '../../context/User';
import GlassCard from '../../components/auth/GlassCard';
import AuthCardHeader from '../../components/auth/AuthCardHeader';
import AuthBackground from '../../components/common/AuthBackground';
import ScopeOptionList from './ScopeOptionList';
import WeyAiHandoff, {
HANDOFF_STAGE_ISSUING,
HANDOFF_STAGE_LOADING,
HANDOFF_STAGE_REDIRECT,
} from './WeyAiHandoff';
import { fetchOAuthContext, submitAuthorize } from './clientAuthorizeApi';
import {
DESKTOP_CLIENT_ID,
buildLoginTarget,
isAllowedRedirect,
optionKey,
parseClientApiError,
readAuthorizeParams,
} from './authorizeParams';
const { Text } = Typography;
// 被 iframe 嵌入时(点击劫持)不渲染任何可操作内容,并尝试跳出框架。
function detectFramed() {
try {
return window.self !== window.top;
} catch (_e) {
return true;
}
}
const ClientAuthorize = () => {
const { t } = useTranslation();
const navigate = useNavigate();
const location = useLocation();
const [searchParams] = useSearchParams();
const [, userDispatch] = useContext(UserContext);
const logo = getLogo();
const params = useMemo(
() => readAuthorizeParams(searchParams),
[searchParams],
);
const isDesktop = params.client_id === DESKTOP_CLIENT_ID;
const currentPath = `${location.pathname}${location.search}`;
const [framed] = useState(detectFramed);
// phase: loading | fatal | ready | submitting | done
const [phase, setPhase] = useState('loading');
const [fatalMessage, setFatalMessage] = useState('');
const [context, setContext] = useState(null);
const [selected, setSelected] = useState('');
const [inlineError, setInlineError] = useState('');
const [doneInfo, setDoneInfo] = useState(null);
const autoSubmittedRef = useRef(false);
const reasonText = useCallback(
(reason) => {
switch (reason) {
case 'org_only_no_org':
case 'org_only':
return t('当前账号仅能使用企业资源,但没有可用的企业');
case 'web_access_denied':
return t('你的账号暂未开通 WeyAi 网页端,请联系管理员');
case 'super_admin':
return t('超级管理员只能使用个人范围');
case 'not_member':
return t('你已不是该企业的成员');
case 'org_unusable':
return t('该企业当前不可用(已冻结、欠费或待审核)');
default:
return t('当前账号没有可用的使用范围');
}
},
[t],
);
const goLogin = useCallback(() => {
// 服务端判定未登录时,本地缓存的登录态已失效:清掉,否则 /login 的
// AuthRedirect 会把「看起来已登录」的用户弹到体验中心,回不到授权页。
clearUserData();
userDispatch({ type: 'logout' });
navigate(buildLoginTarget(params.scope_hint, currentPath), {
replace: true,
});
}, [currentPath, navigate, params.scope_hint, userDispatch]);
const loadContext = useCallback(async () => {
setPhase('loading');
setInlineError('');
if (!params.client_id || !params.redirect_uri) {
setFatalMessage(t('授权请求无效:缺少客户端或回调地址'));
setPhase('fatal');
return;
}
// 与后端 Authorize 的必填项对齐。缺这几个参数时后端一定拒绝,不先拦住
// 就会让用户选完范围、点了"允许"才看到报错,而且无从补救
if (
!params.state ||
!params.code_challenge ||
params.code_challenge_method !== 'S256'
) {
setFatalMessage(t('授权请求无效:缺少必要的安全参数'));
setPhase('fatal');
return;
}
try {
const data = await fetchOAuthContext(params);
const options = Array.isArray(data?.options) ? data.options : [];
setContext({ ...data, options });
const preferred = data?.default_option
? optionKey(data.default_option)
: '';
const hasPreferred = options.some(
(option) => optionKey(option) === preferred,
);
setSelected(
hasPreferred ? preferred : options[0] ? optionKey(options[0]) : '',
);
setPhase('ready');
} catch (error) {
const err = parseClientApiError(error);
if (err.code === 'INVALID_CLIENT') {
setFatalMessage(t('授权请求无效:客户端或回调地址不合法'));
setPhase('fatal');
return;
}
// weyai-remote(公网访问):后台总开关关闭
if (err.code === 'REMOTE_DISABLED') {
setFatalMessage(t('WeyAi 公网访问暂未开放,请联系管理员'));
setPhase('fatal');
return;
}
if (err.code === 'UNAUTHENTICATED' || err.status === 401) {
goLogin();
return;
}
if (err.code === 'INVALID_REQUEST') {
setFatalMessage(t('授权请求参数有误'));
} else if (err.code === 'RATE_LIMITED') {
setFatalMessage(t('请求过于频繁,请稍后再试'));
} else {
setFatalMessage(err.message || t('加载授权信息失败,请稍后重试'));
}
setPhase('fatal');
}
}, [goLogin, params, t]);
// 只在进入页面(或地址参数变化)时加载一次;切换语言等导致的回调重建不重复拉取
const loadedForRef = useRef('');
useEffect(() => {
if (framed) {
try {
window.top.location.replace(window.location.href);
} catch (_e) {
// 跨域父页面不允许改写 location,保持不渲染操作按钮即可
}
return;
}
if (loadedForRef.current === location.search) return;
loadedForRef.current = location.search;
loadContext();
}, [framed, loadContext, location.search]);
const followRedirect = useCallback(
(redirect, denied) => {
if (!isAllowedRedirect(redirect)) {
setFatalMessage(t('服务端返回的跳转地址无效'));
setPhase('fatal');
return;
}
// 拒绝授权与"没有网页端权限"都是 200 + redirect,只有回跳地址里的
// error= 能区分。不看它就会在被拒时显示"授权完成,正在跳转"
let refused = denied;
if (!refused) {
try {
refused = !!new URL(
redirect,
window.location.origin,
).searchParams.get('error');
} catch {
refused = false;
}
}
setDoneInfo({ redirect, denied: refused });
setPhase('done');
window.location.replace(redirect);
},
[t],
);
const submit = useCallback(
async ({ deny = false, optionKeyValue } = {}) => {
const option = context?.options?.find(
(item) => optionKey(item) === (optionKeyValue || selected),
);
if (!deny && !option) {
setInlineError(t('请选择使用范围'));
return;
}
setPhase('submitting');
setInlineError('');
const payload = {
client_id: params.client_id,
redirect_uri: params.redirect_uri,
state: params.state,
code_challenge: params.code_challenge,
code_challenge_method: params.code_challenge_method,
scope: option ? option.scope : 'personal',
org_id: option ? Number(option.org_id) || 0 : 0,
};
if (params.device_name) payload.device_name = params.device_name;
if (deny) payload.deny = true;
try {
const data = await submitAuthorize(payload);
followRedirect(data?.redirect, deny);
} catch (error) {
const err = parseClientApiError(error);
if (err.code === 'UNAUTHENTICATED') {
goLogin();
return;
}
if (err.code === 'INVALID_CLIENT') {
setFatalMessage(t('授权请求无效:客户端或回调地址不合法'));
setPhase('fatal');
return;
}
if (err.code === 'REMOTE_DISABLED') {
setFatalMessage(t('WeyAi 公网访问暂未开放,请联系管理员'));
setPhase('fatal');
return;
}
if (err.code === 'SCOPE_NOT_ALLOWED') {
// 可选范围可能已变化(例如刚被移出企业),重新拉取后再让用户选
await loadContext();
setInlineError(reasonText(err.data?.reason));
return;
}
if (err.code === 'WEB_ACCESS_DENIED') {
setInlineError(reasonText('web_access_denied'));
} else if (err.code === 'RATE_LIMITED') {
setInlineError(t('请求过于频繁,请稍后再试'));
} else if (err.code === 'INVALID_REQUEST') {
setInlineError(t('授权请求参数有误'));
} else {
setInlineError(err.message || t('授权失败,请稍后重试'));
}
setPhase('ready');
}
},
[
context,
followRedirect,
goLogin,
loadContext,
params,
reasonText,
selected,
t,
],
);
// 网页端可以静默签发的条件:服务端要求静默、有默认范围、且默认范围确实在
// 可选范围里。最后一条与自动提交 effect 共用:只在 effect 里判会让"默认项
// 不在可选范围"时自动提交被跳过、而过渡画面仍以为在签发,页面永久停在
// "正在进入"且没有任何可操作项。不满足就回卡片让用户手选。
const silentKey =
!isDesktop && context?.silent && context?.default_option
? optionKey(context.default_option)
: '';
const canAutoSubmit =
!!silentKey &&
(context?.options || []).some((option) => optionKey(option) === silentKey);
// 网页端:默认范围可用且未要求强制选择时直接签发,不显示页面
useEffect(() => {
if (phase !== 'ready' || !canAutoSubmit || autoSubmittedRef.current) {
return;
}
autoSubmittedRef.current = true;
submit({ optionKeyValue: silentKey });
}, [canAutoSubmit, phase, silentKey, submit]);
const switchAccount = useCallback(async () => {
setPhase('submitting');
try {
await API.get('/api/user/logout', { skipErrorHandler: true });
} catch (_e) {
// 退出失败也回登录页,由登录页重新建立会话
}
goLogin();
}, [goLogin]);
const clientName =
context?.client_name || (isDesktop ? t('WeyAi 桌面端') : 'WeyAi');
const busy = phase === 'submitting';
const silentPending =
canAutoSubmit &&
(phase === 'ready' || phase === 'submitting') &&
!inlineError;
// 三个没有任何可操作内容的瞬态走整页过渡画面(WeyAiHandoff),不再套登录
// 卡片:拉授权信息 → 静默签发 → 授权完成等浏览器跳走。桌面端授权完成后
// 要停在页面上给"没有自动打开"的按钮,被拒也要停下来告知,都不算瞬态。
let handoffStage = null;
if (!framed) {
if (phase === 'loading') handoffStage = HANDOFF_STAGE_LOADING;
else if (silentPending) handoffStage = HANDOFF_STAGE_ISSUING;
else if (phase === 'done' && !isDesktop && !doneInfo?.denied) {
handoffStage = HANDOFF_STAGE_REDIRECT;
}
}
const renderBody = () => {
if (framed) {
return (
<Banner
type='danger'
closeIcon={null}
description={t('出于安全原因,授权页不能在其他页面中打开')}
/>
);
}
if (phase === 'fatal') {
return (
<div className='flex flex-col gap-4'>
<Banner type='danger' closeIcon={null} description={fatalMessage} />
<Button block onClick={() => navigate('/', { replace: true })}>
{t('返回首页')}
</Button>
</div>
);
}
if (phase === 'done') {
return (
<div className='flex flex-col gap-4 items-center text-center'>
<Text>
{doneInfo?.denied
? t('已拒绝授权,可以关闭此页面')
: isDesktop
? t('授权完成,请回到 WeyAi 桌面端继续')
: t('授权完成,正在跳转…')}
</Text>
{isDesktop && !doneInfo?.denied && (
<Button
theme='light'
block
onClick={() => window.location.replace(doneInfo.redirect)}
>
{t('没有自动打开?点此打开 WeyAi')}
</Button>
)}
</div>
);
}
const options = context?.options || [];
const displayName = context?.user?.display_name || '';
return (
<div className='flex flex-col gap-4'>
{displayName && (
<div className='flex items-center justify-between gap-2 text-sm'>
<Text type='tertiary'>{t('当前账号')}</Text>
<Text strong ellipsis={{ showTooltip: true }}>
{displayName}
</Text>
</div>
)}
{options.length === 0 ? (
<Banner
type='warning'
closeIcon={null}
description={reasonText(context?.no_option_reason)}
/>
) : (
<div className='flex flex-col gap-2'>
<Text type='tertiary' size='small'>
{t('选择使用范围')}
</Text>
<ScopeOptionList
options={options}
value={selected}
onChange={setSelected}
disabled={busy}
/>
</div>
)}
{isDesktop && params.device_name && (
<div className='flex items-center justify-between gap-2 text-sm'>
<span className='flex items-center gap-1.5'>
<Monitor size={14} className='text-gray-400' />
<Text type='tertiary'>{t('设备')}</Text>
</span>
<Text ellipsis={{ showTooltip: true }}>{params.device_name}</Text>
</div>
)}
{inlineError && (
<Banner type='danger' closeIcon={null} description={inlineError} />
)}
{isDesktop ? (
<div className='flex flex-col gap-2'>
<div className='flex gap-2'>
<Button
block
disabled={busy}
onClick={() => submit({ deny: true })}
>
{t('拒绝')}
</Button>
<Button
block
theme='solid'
type='primary'
loading={busy}
disabled={options.length === 0}
onClick={() => submit()}
>
{t('允许')}
</Button>
</div>
<Button
block
theme='borderless'
disabled={busy}
onClick={switchAccount}
>
{t('切换账号')}
</Button>
<Text type='tertiary' size='small' className='text-center'>
{t('切换账号会退出当前登录,并将同时退出 WeyAi 网页端')}
</Text>
</div>
) : (
<div className='flex gap-2'>
<Button
block
disabled={busy}
onClick={() => submit({ deny: true })}
>
{t('取消')}
</Button>
<Button
block
theme='solid'
type='primary'
loading={busy}
disabled={options.length === 0}
onClick={() => submit()}
>
{t('继续')}
</Button>
</div>
)}
</div>
);
};
if (handoffStage !== null) {
const handoffTitle =
handoffStage === HANDOFF_STAGE_LOADING
? t('正在加载授权信息')
: t('正在进入 {{name}}', { name: clientName });
return (
<WeyAiHandoff
logo={logo}
stage={handoffStage}
title={handoffTitle}
// 加载阶段还不知道是静默进入还是要选范围,副标题只说"在确认";
// 进入签发/跳转阶段才承诺"正在打开工作台"
subtitle={
handoffStage === HANDOFF_STAGE_LOADING
? t('正在确认授权信息,通常只需几秒')
: t('正在为你打开 {{name}} 工作台,通常只需几秒', {
name: clientName,
})
}
clientName={clientName}
/>
);
}
return (
<div
className='relative overflow-hidden flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8'
style={{ minHeight: 'calc(100vh - var(--content-top-offset, 0px))' }}
>
<AuthBackground />
<div className='w-full max-w-md z-10 flex flex-col items-center'>
<GlassCard>
<AuthCardHeader
wrapperClassName='mb-6'
logo={logo}
title={t('登录 {{name}}', { name: clientName })}
subtitle={
isDesktop
? t('确认后将使用此账号登录 WeyAi 桌面端')
: t('选择进入 WeyAi 时使用的范围')
}
/>
{renderBody()}
</GlassCard>
</div>
</div>
);
};
export default ClientAuthorize;