接入成品上架工作台单点登录
This commit is contained in:
parent
cb0296a44e
commit
95bb9db4ce
89
app/api/desktop/[...path]/finished-web.test.ts
Normal file
89
app/api/desktop/[...path]/finished-web.test.ts
Normal file
@ -0,0 +1,89 @@
|
||||
/** @jest-environment node */
|
||||
import { DesktopClientError } from '@/lib/desktop-client/contract.mjs'
|
||||
import { getDesktopDelivery } from '@/lib/desktop-client/deliveries'
|
||||
import { requireDesktop } from '@/lib/desktop-client/service'
|
||||
import { FinishedWebSsoError, issueFinishedWebLink } from '@/lib/finished-web-sso'
|
||||
import { GET, POST } from './route'
|
||||
|
||||
jest.mock('next-auth', () => ({}))
|
||||
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
|
||||
jest.mock('@/lib/desktop-client/service', () => ({ requireDesktop: jest.fn() }))
|
||||
jest.mock('@/lib/desktop-client/deliveries', () => ({ getDesktopDelivery: jest.fn() }))
|
||||
jest.mock('@/lib/employee-directory', () => ({}))
|
||||
jest.mock('@/lib/finished-web-sso', () => ({
|
||||
...jest.requireActual('@/lib/finished-web-sso'),
|
||||
issueFinishedWebLink: jest.fn(),
|
||||
}))
|
||||
|
||||
const path = ['deliveries', 'owned-project', 'detail', 'owned-material', 'finished-web']
|
||||
const receipt = {
|
||||
requestId: 'owned-request', materialId: 'owned-material', materialType: '自动上架-详情',
|
||||
state: 'completed' as const, listingStatus: null,
|
||||
}
|
||||
const link = {
|
||||
url: 'https://pddg.jiansuntuzhi.cn/finished-web/#token=simulated-link',
|
||||
expiresAt: '2027-01-02T07:04:20.518Z',
|
||||
user: { id: 123, username: 'operator', name: '测试账号', role: 'operator' },
|
||||
}
|
||||
|
||||
function request(method: 'POST' | 'GET' = 'POST', segments = path) {
|
||||
const input = new Request('http://localhost:3000/api/desktop/' + segments.join('/'), {
|
||||
method, headers: { Authorization: 'Bearer desktop-session-placeholder' },
|
||||
})
|
||||
return (method === 'POST' ? POST : GET)(input, { params: { path: segments } })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks()
|
||||
jest.mocked(requireDesktop).mockResolvedValue({
|
||||
id: 'session', account: { id: 'owner', name: '实名' }, expiresAt: new Date(), isSuperAdmin: false,
|
||||
})
|
||||
jest.mocked(getDesktopDelivery).mockResolvedValue(receipt)
|
||||
jest.mocked(issueFinishedWebLink).mockResolvedValue(link)
|
||||
})
|
||||
|
||||
test('桌面会话只能为当前账户的指定详情交付换链', async () => {
|
||||
const response = await request()
|
||||
expect(jest.mocked(requireDesktop).mock.calls[0][0].headers.get('authorization')).toBe('Bearer desktop-session-placeholder')
|
||||
expect(getDesktopDelivery).toHaveBeenCalledWith('owner', 'owned-project', 'detail')
|
||||
expect(issueFinishedWebLink).toHaveBeenCalledWith('owner')
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.headers.get('cache-control')).toBe('private, no-store')
|
||||
expect(await response.json()).toEqual(link)
|
||||
})
|
||||
|
||||
test('无效或已撤销的 Bearer 会话无法进入交付查询', async () => {
|
||||
jest.mocked(requireDesktop).mockRejectedValue(new DesktopClientError('请重新登录', 401, 'session_expired'))
|
||||
expect((await request()).status).toBe(401)
|
||||
expect(getDesktopDelivery).not.toHaveBeenCalled()
|
||||
expect(issueFinishedWebLink).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('无权访问项目时不签发', async () => {
|
||||
jest.mocked(getDesktopDelivery).mockRejectedValue(new DesktopClientError('项目不存在或无权访问', 404, 'not_found'))
|
||||
expect((await request()).status).toBe(404)
|
||||
expect(issueFinishedWebLink).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test.each([
|
||||
['无交付', null],
|
||||
['已删除', { ...receipt, state: 'removed' as const }],
|
||||
['成品编号不一致', { ...receipt, materialId: 'other-material' }],
|
||||
])('%s时不签发', async (_label, value) => {
|
||||
jest.mocked(getDesktopDelivery).mockResolvedValue(value)
|
||||
expect((await request()).status).toBe(404)
|
||||
expect(issueFinishedWebLink).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('GET 和非详情类型均不能触发签发', async () => {
|
||||
expect((await request('GET')).status).toBe(404)
|
||||
expect((await request('POST', [path[0], path[1], 'video', path[3], path[4]])).status).toBe(404)
|
||||
expect(issueFinishedWebLink).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('上游 401 与客户端会话失效有不同错误码', async () => {
|
||||
jest.mocked(issueFinishedWebLink).mockRejectedValue(new FinishedWebSsoError('工作台拒绝了服务授权', 401, 'finished_web_upstream'))
|
||||
const response = await request()
|
||||
expect(response.status).toBe(401)
|
||||
expect(await response.json()).toEqual({ error: '工作台拒绝了服务授权', code: 'finished_web_upstream' })
|
||||
})
|
||||
@ -92,6 +92,12 @@ async function route(request:Request,{params}:{params:{path:string[]}}){
|
||||
value=await delivery.createDesktopDelivery(ownerId,JSON.parse((await body(request)).toString()),reauthorize)
|
||||
}
|
||||
else if(method==='GET'&&parts.length===3)value=await delivery.getDesktopDelivery(ownerId,parts[1],parts[2]) || {delivery:null}
|
||||
else if(method==='POST'&&parts.length===5&&parts[2]==='detail'&&parts[4]==='finished-web'){
|
||||
const receipt = await delivery.getDesktopDelivery(ownerId, parts[1], 'detail')
|
||||
desktopAssert(receipt?.state === 'completed' && receipt.materialId === parts[3], '该详情成品不存在或无权访问', 404, 'not_found')
|
||||
const { issueFinishedWebLink } = await import('@/lib/finished-web-sso')
|
||||
value = await issueFinishedWebLink(ownerId)
|
||||
}
|
||||
else throw new DesktopClientError('接口不存在',404)
|
||||
}
|
||||
else if(parts[0]==='projects'){
|
||||
|
||||
101
app/api/materials/[id]/finished-web/route.test.ts
Normal file
101
app/api/materials/[id]/finished-web/route.test.ts
Normal file
@ -0,0 +1,101 @@
|
||||
/** @jest-environment node */
|
||||
import { NextRequest } from 'next/server'
|
||||
import { getServerSession } from 'next-auth'
|
||||
import { canUserViewMaterial } from '@/lib/department-permission'
|
||||
import { FinishedWebSsoError, issueFinishedWebLink } from '@/lib/finished-web-sso'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { canAccessMaterialPrivacy } from '@/lib/task-detail-privacy'
|
||||
import { POST } from './route'
|
||||
|
||||
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
|
||||
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
|
||||
jest.mock('@/lib/prisma', () => ({ prisma: { material: { findFirst: jest.fn() } } }))
|
||||
jest.mock('@/lib/department-permission', () => ({ canUserViewMaterial: jest.fn() }))
|
||||
jest.mock('@/lib/task-detail-privacy', () => ({ canAccessMaterialPrivacy: jest.fn(), TASK_DETAIL_PRIVACY_SELECT: {} }))
|
||||
jest.mock('@/lib/employee-directory', () => ({}))
|
||||
jest.mock('@/lib/finished-web-sso', () => ({
|
||||
...jest.requireActual('@/lib/finished-web-sso'),
|
||||
issueFinishedWebLink: jest.fn(),
|
||||
}))
|
||||
|
||||
const params = { id: 'detail-material' }
|
||||
const user = { id: 'viewer', role: 'USER', department: '运营部', managedDepartment: null }
|
||||
const material = { userId: 'owner', materialType: '自动上架-详情', accessScope: 'general' }
|
||||
const link = {
|
||||
url: 'https://pddg.jiansuntuzhi.cn/finished-web/#token=simulated-link',
|
||||
expiresAt: '2027-01-02T07:04:20.518Z',
|
||||
user: { id: 123, username: 'operator', name: '测试账号', role: 'operator' },
|
||||
}
|
||||
|
||||
function request(headers: Record<string, string> = { Origin: 'http://localhost:3000' }) {
|
||||
return POST(new NextRequest('http://localhost:3000/api/materials/detail-material/finished-web', {
|
||||
method: 'POST', headers, body: JSON.stringify({ nickname: '不应使用的花名', userId: 'other-user' }),
|
||||
}), { params })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks()
|
||||
;(getServerSession as jest.Mock).mockResolvedValue({ user })
|
||||
jest.mocked(prisma.material.findFirst).mockResolvedValue(material as never)
|
||||
jest.mocked(canUserViewMaterial).mockResolvedValue(true)
|
||||
jest.mocked(canAccessMaterialPrivacy).mockResolvedValue(true)
|
||||
jest.mocked(issueFinishedWebLink).mockResolvedValue(link)
|
||||
})
|
||||
|
||||
test('登录用户可按素材权限换链,签发身份只取自会话', async () => {
|
||||
const response = await request()
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.headers.get('cache-control')).toBe('private, no-store')
|
||||
expect(await response.json()).toEqual(link)
|
||||
expect(prisma.material.findFirst).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: { id: params.id, deletedAt: null, materialType: '自动上架-详情' },
|
||||
}))
|
||||
expect(canAccessMaterialPrivacy).toHaveBeenCalledWith(material, user.id)
|
||||
expect(canUserViewMaterial).toHaveBeenCalledWith(user.department, user.role, null, material.materialType, user.id)
|
||||
expect(issueFinishedWebLink).toHaveBeenCalledWith(user.id)
|
||||
})
|
||||
|
||||
test('成品所有者沿用分享页的查看权限', async () => {
|
||||
jest.mocked(prisma.material.findFirst).mockResolvedValue({ ...material, userId: user.id } as never)
|
||||
jest.mocked(canUserViewMaterial).mockResolvedValue(false)
|
||||
expect((await request()).status).toBe(200)
|
||||
expect(canAccessMaterialPrivacy).toHaveBeenCalled()
|
||||
expect(canUserViewMaterial).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('未登录时拒绝换链', async () => {
|
||||
;(getServerSession as jest.Mock).mockResolvedValue(null)
|
||||
expect((await request()).status).toBe(401)
|
||||
expect(prisma.material.findFirst).not.toHaveBeenCalled()
|
||||
expect(issueFinishedWebLink).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test.each([
|
||||
{},
|
||||
{ Origin: 'https://untrusted.example', 'Sec-Fetch-Site': 'cross-site' },
|
||||
])('拒绝非本站请求 %j', async headers => {
|
||||
expect((await request(headers as Record<string, string>)).status).toBe(403)
|
||||
expect(prisma.material.findFirst).not.toHaveBeenCalled()
|
||||
expect(issueFinishedWebLink).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('成品不存在、已删除或不是详情类型时不签发', async () => {
|
||||
jest.mocked(prisma.material.findFirst).mockResolvedValue(null)
|
||||
expect((await request()).status).toBe(404)
|
||||
expect(issueFinishedWebLink).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test.each(['privacy', 'type'])('越权拒绝(%s)', async scope => {
|
||||
jest.mocked(canAccessMaterialPrivacy).mockResolvedValue(scope !== 'privacy')
|
||||
jest.mocked(canUserViewMaterial).mockResolvedValue(scope !== 'type')
|
||||
expect((await request()).status).toBe(403)
|
||||
expect(issueFinishedWebLink).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('传递签发模块提供的中文消息和 HTTP 状态', async () => {
|
||||
jest.mocked(issueFinishedWebLink).mockRejectedValue(new FinishedWebSsoError('请稍后再试', 429, 'finished_web_upstream'))
|
||||
const response = await request()
|
||||
expect(response.status).toBe(429)
|
||||
expect(await response.json()).toEqual({ error: '请稍后再试' })
|
||||
expect(response.headers.get('cache-control')).toBe('private, no-store')
|
||||
})
|
||||
41
app/api/materials/[id]/finished-web/route.ts
Normal file
41
app/api/materials/[id]/finished-web/route.ts
Normal file
@ -0,0 +1,41 @@
|
||||
import { NextResponse, type NextRequest } from 'next/server'
|
||||
import { getServerSession } from 'next-auth'
|
||||
import { authOptions } from '@/lib/auth'
|
||||
import { isAllowedCorsOrigin } from '@/lib/cors-origin'
|
||||
import { canUserViewMaterial } from '@/lib/department-permission'
|
||||
import { FinishedWebSsoError, issueFinishedWebLink } from '@/lib/finished-web-sso'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { canAccessMaterialPrivacy, TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy'
|
||||
import { XIAOYI_DELIVERY_MATERIAL_TYPES } from '@/lib/xiaoyi-delivery-material'
|
||||
|
||||
export const runtime = 'nodejs'
|
||||
const headers = { 'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff' }
|
||||
|
||||
export async function POST(request: NextRequest, { params }: { params: { id: string } }) {
|
||||
const fail = (error: string, status: number) => NextResponse.json({ error }, { status, headers })
|
||||
try {
|
||||
const session = await getServerSession(authOptions)
|
||||
const user = session?.user as { id?: string; role: string; department?: string; managedDepartment?: string | null } | undefined
|
||||
if (!user?.id) return fail('请先登录素材库', 401)
|
||||
|
||||
const origin = request.headers.get('origin')
|
||||
if (!origin || request.headers.get('sec-fetch-site') === 'cross-site' || !isAllowedCorsOrigin(request, origin)) {
|
||||
return fail('请从素材库详情页打开成品上架工作台', 403)
|
||||
}
|
||||
const material = await prisma.material.findFirst({
|
||||
where: { id: params.id, deletedAt: null, materialType: XIAOYI_DELIVERY_MATERIAL_TYPES.detail },
|
||||
select: { userId: true, materialType: true, ...TASK_DETAIL_PRIVACY_SELECT },
|
||||
})
|
||||
if (!material) return fail('该详情成品不存在', 404)
|
||||
if (!(await canAccessMaterialPrivacy(material, user.id)) || (
|
||||
material.userId !== user.id &&
|
||||
!(await canUserViewMaterial(user.department, user.role, user.managedDepartment, material.materialType, user.id))
|
||||
)) {
|
||||
return fail('无权限查看该详情成品', 403)
|
||||
}
|
||||
return NextResponse.json(await issueFinishedWebLink(user.id), { headers })
|
||||
} catch (error) {
|
||||
if (error instanceof FinishedWebSsoError) return fail(error.message, error.status)
|
||||
return fail('成品上架工作台暂不可用,请稍后再试', 503)
|
||||
}
|
||||
}
|
||||
@ -17,10 +17,11 @@ import { useToast } from '@/hooks/useToast'
|
||||
import AudioVisualizer from '@/components/AudioVisualizer'
|
||||
import ProductPackageDetail from '@/components/detail/ProductPackageDetail'
|
||||
import XiaoyiDeliveryDetail from '@/components/detail/XiaoyiDeliveryDetail'
|
||||
import { isXiaoyiDeliveryMaterial } from '@/lib/xiaoyi-delivery-material'
|
||||
import { isXiaoyiDeliveryMaterial, XIAOYI_DELIVERY_MATERIAL_TYPES } from '@/lib/xiaoyi-delivery-material'
|
||||
import TaskPageDetail from '@/components/detail/TaskPageDetail'
|
||||
import ThreeDOriginalDetail from '@/components/detail/ThreeDOriginalDetail'
|
||||
import MaterialDetailHeader, {
|
||||
type MaterialDetailAction,
|
||||
type MaterialDetailCapabilities,
|
||||
} from '@/components/detail/MaterialDetailHeader'
|
||||
import { useConfirmActionDialog } from '@/components/ConfirmActionDialog'
|
||||
@ -540,7 +541,7 @@ export default function SharePage() {
|
||||
const [selectedSkuIds, setSelectedSkuIds] = useState<Set<string>>(new Set())
|
||||
const [downloadingBatchType, setDownloadingBatchType] = useState<'model' | 'white-background' | null>(null)
|
||||
const [skuListRefreshKey, setSkuListRefreshKey] = useState(0)
|
||||
const [detailActionBusy, setDetailActionBusy] = useState<'favorite' | 'share' | 'delete' | null>(null)
|
||||
const [detailActionBusy, setDetailActionBusy] = useState<MaterialDetailAction>(null)
|
||||
const { confirmAction, confirmActionDialog } = useConfirmActionDialog()
|
||||
const pageRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
@ -1107,6 +1108,45 @@ export default function SharePage() {
|
||||
void runDownload()
|
||||
}
|
||||
|
||||
const handleOpenFinishedWeb = async () => {
|
||||
if (!material || detailActionBusy) return
|
||||
// Claim the tab during the click so popup blockers do not drop the async navigation.
|
||||
const tab = window.open('about:blank', '_blank')
|
||||
const reportFailure = (message: string) => showToast(message, { variant: 'error', duration: 5000 })
|
||||
if (!tab) {
|
||||
reportFailure('浏览器拦截了新标签页,请允许本站打开新标签页后重试')
|
||||
return
|
||||
}
|
||||
tab.opener = null
|
||||
tab.document.title = '正在打开成品上架工作台'
|
||||
tab.document.body.textContent = '正在打开成品上架工作台…'
|
||||
setDetailActionBusy('finished-web')
|
||||
try {
|
||||
const response = await fetch(`/api/materials/${encodeURIComponent(material.id)}/finished-web`, {
|
||||
method: 'POST',
|
||||
cache: 'no-store',
|
||||
})
|
||||
const result = await response.json()
|
||||
if (!response.ok) {
|
||||
tab.close()
|
||||
reportFailure(result.error || '成品上架工作台暂不可用,请稍后再试')
|
||||
return
|
||||
}
|
||||
if (!tab.closed) {
|
||||
const link = tab.document.createElement('a')
|
||||
link.href = result.url
|
||||
link.rel = 'noopener noreferrer'
|
||||
tab.document.body.appendChild(link)
|
||||
link.click()
|
||||
}
|
||||
} catch {
|
||||
tab.close()
|
||||
reportFailure('暂时无法打开成品上架工作台,请稍后再试')
|
||||
} finally {
|
||||
setDetailActionBusy(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleShareMaterial = async () => {
|
||||
const shareUrl = buildPublicMaterialShareUrl(materialId)
|
||||
setDetailActionBusy('share')
|
||||
@ -1726,6 +1766,9 @@ export default function SharePage() {
|
||||
}}
|
||||
onFavorite={() => void handleFavoriteMaterial()}
|
||||
onShare={() => void handleShareMaterial()}
|
||||
onOpenFinishedWeb={session?.user && mappedMaterialType === XIAOYI_DELIVERY_MATERIAL_TYPES.detail
|
||||
? () => void handleOpenFinishedWeb()
|
||||
: undefined}
|
||||
onEdit={() => router.push(`/edit/${material.id}`)}
|
||||
onDelete={() => void handleDeleteMaterial()}
|
||||
/>
|
||||
|
||||
@ -2099,6 +2099,7 @@ impl Backend {
|
||||
Ok(result)
|
||||
}
|
||||
"delivery-status" => self.delivery_status(input),
|
||||
"finished-web-open" => self.open_finished_web(input),
|
||||
"project-state" => self.project_state(input),
|
||||
"configure-xiaoyi-knowledge" => Ok(knowledge_http::configure_for_account(input)),
|
||||
"select-model" => {
|
||||
@ -2791,7 +2792,8 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if matches!(method.as_str(), "materials" | "creation-catalog" | "creation-thumbnail" | "preview" | "delivery-status") {
|
||||
let material_read = matches!(method.as_str(), "materials" | "preview" | "delivery-status" | "finished-web-open");
|
||||
if material_read || matches!(method.as_str(), "creation-catalog" | "creation-thumbnail") {
|
||||
if method.starts_with("creation-")
|
||||
&& let Some(doc) = input["doc"].as_u64()
|
||||
{
|
||||
@ -2813,7 +2815,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
reader.action(&task_method, &input, &task_events, &task_ctx)
|
||||
};
|
||||
if task_method != "preview" || result.is_err() {
|
||||
let result = if matches!(task_method.as_str(), "materials" | "preview" | "delivery-status") {
|
||||
let result = if material_read {
|
||||
Ok(bound_material_read(result, &task_reference))
|
||||
} else {
|
||||
Ok(bound_creation_read(result, &task_reference))
|
||||
@ -2822,7 +2824,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
}
|
||||
task_ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}) {
|
||||
let result = if matches!(method.as_str(), "materials" | "preview" | "delivery-status") {
|
||||
let result = if material_read {
|
||||
Ok(bound_material_read(Err(error.into()), &reference))
|
||||
} else {
|
||||
let mut value = bound_creation_read(Err(error.into()), &reference);
|
||||
|
||||
@ -573,6 +573,9 @@ impl Backend {
|
||||
write_json(&state_file, &state)?;
|
||||
return Ok(json!({"materialId":material_id,"requestId":request_id,"kind":"detail"}));
|
||||
}
|
||||
if metadata["brandName"].as_str().is_none_or(|brand| brand.trim().is_empty()) {
|
||||
return Err("请在产品资料中填写商品品牌后再完结提交".into());
|
||||
}
|
||||
if !same_delivery {
|
||||
state = json!({"identity":identity,"requestId":Uuid::new_v4().to_string(),"uploads":{}});
|
||||
write_json(&state_file, &state)?;
|
||||
|
||||
@ -6,6 +6,16 @@ use base64::engine::general_purpose::STANDARD;
|
||||
use photocraft_doc::LayerContent;
|
||||
use photocraft_geom::Rect;
|
||||
|
||||
const FINISHED_WEB_URL_PREFIX: &str = "https://pddg.jiansuntuzhi.cn/finished-web/#token=";
|
||||
|
||||
fn finished_web_url(value: &Value) -> R<&str> {
|
||||
value["url"].as_str().filter(|url| {
|
||||
url.strip_prefix(FINISHED_WEB_URL_PREFIX).is_some_and(|token| {
|
||||
!token.is_empty() && token.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'_' | b'-'))
|
||||
})
|
||||
}).ok_or_else(|| "成品上架工作台返回的登录链接无效,请联系管理员".into())
|
||||
}
|
||||
|
||||
const FILE_LIMIT: u64 = 512 * 1024 * 1024;
|
||||
const BACKUP_LIMIT: u64 = 256 * 1024 * 1024;
|
||||
const SESSION_FILES_LIMIT: u64 = 1024 * 1024 * 1024;
|
||||
@ -737,6 +747,41 @@ impl Backend {
|
||||
Ok(if value["materialId"].is_string() { json!({"delivery":value}) } else { value })
|
||||
}
|
||||
|
||||
pub(super) fn open_finished_web(&self, input: &Value) -> R<Value> {
|
||||
let doc = input["doc"].as_u64().ok_or("请先打开项目")?;
|
||||
self.ensure_owner(doc)?;
|
||||
self.check_dispatch()?;
|
||||
let context = {
|
||||
let _guard = context_guard();
|
||||
read_json(&self.project_dir(doc)?.join("context.json"))?
|
||||
};
|
||||
if context["project"]["source"] != "desktop" {
|
||||
return Err("请先将详情成品提交到素材库".into());
|
||||
}
|
||||
let project = context["project"]["id"].as_str().and_then(|id| Uuid::parse_str(id).ok())
|
||||
.ok_or("云项目身份无效")?;
|
||||
let material = input["materialId"].as_str().filter(|id| {
|
||||
!id.is_empty() && id.len() <= 80
|
||||
&& id.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-'))
|
||||
}).ok_or("详情成品身份无效")?;
|
||||
let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?;
|
||||
let request = self.http.post(format!("{}/api/desktop/deliveries/{project}/detail/{material}/finished-web", self.origin))
|
||||
.bearer_auth(token).timeout(Duration::from_secs(20));
|
||||
let response = request.send().map_err(|error| network_message(&error))?;
|
||||
let (status, receipt) = body(response, 16 * 1024)?;
|
||||
if status != 200 {
|
||||
if status == 401 && receipt["code"] != "finished_web_upstream" {
|
||||
self.check_cloud_authority(status)?;
|
||||
}
|
||||
return Err(receipt["error"].as_str().unwrap_or("暂时无法打开成品上架工作台,请稍后再试").into());
|
||||
}
|
||||
|
||||
self.check_dispatch()?;
|
||||
crate::services::open_external_url(finished_web_url(&receipt)?)
|
||||
.map_err(|_| "未能打开系统浏览器,请检查默认浏览器设置后重试")?;
|
||||
Ok(json!({}))
|
||||
}
|
||||
|
||||
fn delivery_project_id(&self, dir: &Path, revision: u64, artifacts: &[super::material_delivery::Artifact]) -> R<String> {
|
||||
let context = { let _guard = context_guard(); read_json(&dir.join("context.json"))? };
|
||||
if context["revision"].as_u64() != Some(revision) { return Err("本机版本已变化,请保存后重新完结".into()); }
|
||||
@ -1266,6 +1311,23 @@ impl Backend {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn finished_web_url_accepts_only_the_workbench_token_fragment() {
|
||||
let valid = format!("{FINISHED_WEB_URL_PREFIX}simulated-link");
|
||||
let receipt = json!({"url":valid});
|
||||
assert!(finished_web_url(&receipt).is_ok());
|
||||
for invalid in [
|
||||
"https://pddg.jiansuntuzhi.cn.example/finished-web/#token=simulated-link",
|
||||
"https://pddg.jiansuntuzhi.cn/finished-web/?token=simulated-link",
|
||||
"https://pddg.jiansuntuzhi.cn:8443/finished-web/#token=simulated-link",
|
||||
"https://pddg.jiansuntuzhi.cn/finished-web/#token=",
|
||||
"https://pddg.jiansuntuzhi.cn/finished-web/#token=simulated-link&extra=1",
|
||||
] {
|
||||
assert!(finished_web_url(&json!({"url":invalid})).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_completed_pi_journal_can_be_packaged_and_rechecked_but_unknown_still_blocks_update() {
|
||||
let account = std::env::temp_dir().join(format!("sync-large-pi-journal-{}", Uuid::new_v4()));
|
||||
|
||||
@ -1174,6 +1174,9 @@ pub struct Workspace {
|
||||
sync_confirm: bool,
|
||||
listing_read_at: Option<(u64, Instant)>,
|
||||
listing_read_error: Option<String>,
|
||||
delivery_completion: bool,
|
||||
finished_web_pending: bool,
|
||||
finished_web_error: Option<String>,
|
||||
sync_dirty: bool,
|
||||
sync_request_meta: String,
|
||||
}
|
||||
@ -1803,6 +1806,9 @@ impl Workspace {
|
||||
sync_confirm: false,
|
||||
listing_read_at: None,
|
||||
listing_read_error: None,
|
||||
delivery_completion: false,
|
||||
finished_web_pending: false,
|
||||
finished_web_error: None,
|
||||
sync_dirty: true,
|
||||
sync_request_meta: String::new(),
|
||||
};
|
||||
@ -3448,6 +3454,12 @@ impl Workspace {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if method == "finished-web-open" {
|
||||
if let Ok(value) = result {
|
||||
creation::finished_web_received(self, app, &value);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if method == "project-list" {
|
||||
if let Ok(value) = result {
|
||||
self.receive_project_list(app, &value);
|
||||
@ -3983,6 +3995,10 @@ impl Workspace {
|
||||
self.creation_pending = None;
|
||||
self.creation_run = None;
|
||||
self.creation_progress.clear();
|
||||
self.sync_confirm = false;
|
||||
self.delivery_completion = false;
|
||||
self.finished_web_pending = false;
|
||||
self.finished_web_error = None;
|
||||
self.agent_rule = Value::Null;
|
||||
self.agent_rule_state = Value::Null;
|
||||
self.agent_categories.clear();
|
||||
|
||||
@ -2045,6 +2045,11 @@ pub(super) fn sync_received(w: &mut Workspace, app: &PhotocraftApp, value: &Valu
|
||||
if let Some(id) = value["materialDelivery"]["materialId"].as_str() {
|
||||
w.project_context["materialDelivery"] = value["materialDelivery"].clone();
|
||||
w.note(format!("成品已提交素材库,素材 ID:{id}"));
|
||||
w.delivery_completion = true;
|
||||
w.sync_confirm = true;
|
||||
w.listing_read_at = None;
|
||||
w.listing_read_error = None;
|
||||
w.finished_web_error = None;
|
||||
}
|
||||
w.project_refresh_requested = true;
|
||||
w.creation_progress = if value["materialDelivery"]["materialId"].is_string() {
|
||||
@ -2073,6 +2078,13 @@ pub(super) fn listing_status_received(w: &mut Workspace, app: &PhotocraftApp, va
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn finished_web_received(w: &mut Workspace, app: &PhotocraftApp, value: &Value) {
|
||||
if bound(w, app, value) {
|
||||
w.finished_web_pending = false;
|
||||
w.finished_web_error = value["error"].as_str().map(str::to_owned);
|
||||
}
|
||||
}
|
||||
|
||||
fn listing_status_text(receipt: &Value) -> (&'static str, stitch_ui::StatusTone) {
|
||||
use stitch_ui::StatusTone::{Error, Neutral};
|
||||
if receipt["state"] == "removed" {
|
||||
@ -2278,6 +2290,7 @@ impl Workspace {
|
||||
let finish = button.clicked();
|
||||
if finish {
|
||||
self.sync_confirm = true;
|
||||
self.delivery_completion = false;
|
||||
self.listing_read_at = None;
|
||||
self.listing_read_error = None;
|
||||
}
|
||||
@ -2293,10 +2306,19 @@ impl Workspace {
|
||||
}
|
||||
ui.ctx().request_repaint_after(Duration::from_secs(15));
|
||||
}
|
||||
let title = if delivered { "上架状态" } else { "完结项目" };
|
||||
let receipt = &self.project_context["materialDelivery"];
|
||||
let completion_receipt = self.delivery_completion && receipt["materialId"].is_string();
|
||||
let confirming = !delivered && !completion_receipt;
|
||||
let title = if completion_receipt {
|
||||
"成品已提交素材库"
|
||||
} else if delivered {
|
||||
"上架状态"
|
||||
} else {
|
||||
"完结项目"
|
||||
};
|
||||
let closed = stitch_ui::dialog(ui, egui::Id::unique("xiaoyi-finish-project"), title,
|
||||
self.sync_confirm, self.reduce_motion, 360.0, |ui| {
|
||||
if !delivered {
|
||||
if confirming {
|
||||
ui.label("将已完成的详情、主图和 SKU 成品提交到素材库?");
|
||||
}
|
||||
let receipt = &self.project_context["materialDelivery"];
|
||||
@ -2321,12 +2343,30 @@ impl Workspace {
|
||||
stitch_ui::status_label(ui, "上架状态刷新失败", stitch_ui::StatusTone::Warning)
|
||||
.on_hover_text(error);
|
||||
}
|
||||
if let Some(error) = &self.finished_web_error
|
||||
&& !confirming
|
||||
{
|
||||
stitch_ui::status_label(ui, error, stitch_ui::StatusTone::Error);
|
||||
}
|
||||
let target = receipt["materialId"].as_str().filter(|_| !confirming && receipt["state"] != "removed")
|
||||
.zip(app.session.active().map(|state| state.doc.id.0))
|
||||
.map(|(material, doc)| json!({"materialId":material, "doc":doc}));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let dismiss = if delivered { "关闭" } else { "取消" };
|
||||
if let Some(target) = target {
|
||||
let label = if self.finished_web_pending { "正在打开…" } else { "打开成品上架工作台" };
|
||||
if stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Primary, !self.finished_web_pending).clicked() {
|
||||
self.finished_web_error = None;
|
||||
match self.tx.send(Request::Action("finished-web-open".into(), target)) {
|
||||
Ok(()) => self.finished_web_pending = true,
|
||||
Err(_) => self.finished_web_error = Some("本机服务已停止,请重启后重试".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
let dismiss = if confirming { "取消" } else { "关闭" };
|
||||
if stitch_ui::action_button(ui, dismiss, stitch_ui::ButtonRole::Secondary, true).clicked() {
|
||||
self.sync_confirm = false;
|
||||
}
|
||||
if !delivered && stitch_ui::action_button(ui, "完结并提交", stitch_ui::ButtonRole::Primary, idle).clicked() {
|
||||
if confirming && stitch_ui::action_button(ui, "完结并提交", stitch_ui::ButtonRole::Primary, idle).clicked() {
|
||||
self.sync_confirm = false;
|
||||
self.sync_action(app, "project-sync", json!({"status":"completed"}));
|
||||
}
|
||||
@ -8276,6 +8316,29 @@ mod tests {
|
||||
assert!(!w.sync_dirty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finished_web_feedback_is_bound_to_the_delivery_project() {
|
||||
let (mut w, app) = setup();
|
||||
let mut receipt = reference(&w);
|
||||
receipt["materialDelivery"] = json!({"materialId":"delivered-detail", "kind":"detail"});
|
||||
receipt["status"] = json!("completed");
|
||||
sync_received(&mut w, &app, &receipt);
|
||||
assert!(w.sync_confirm && w.delivery_completion);
|
||||
assert!(!w.finished_web_pending, "the completion receipt does not open the workbench on its own");
|
||||
|
||||
w.finished_web_pending = true;
|
||||
let mut other_project = receipt.clone();
|
||||
other_project["doc"] = json!(receipt["doc"].as_u64().unwrap().wrapping_add(1));
|
||||
other_project["error"] = json!("其他项目的错误");
|
||||
finished_web_received(&mut w, &app, &other_project);
|
||||
assert!(w.finished_web_pending && w.finished_web_error.is_none());
|
||||
|
||||
receipt["error"] = json!("成品上架工作台暂时无法连接,请稍后再试");
|
||||
finished_web_received(&mut w, &app, &receipt);
|
||||
assert!(!w.finished_web_pending);
|
||||
assert_eq!(w.finished_web_error.as_deref(), receipt["error"].as_str());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_candidate_or_text_requires_sync_even_when_canvas_revision_is_identical() {
|
||||
let (mut w, app) = setup();
|
||||
|
||||
@ -171,8 +171,12 @@ project_run_slot! {
|
||||
template_ui: template_slots::UiState = template_slots::UiState::default(),
|
||||
pending_slot_apply: Option<Value> = None,
|
||||
template_save_deadline: Option<Instant> = None,
|
||||
sync_confirm: bool = false,
|
||||
listing_read_at: Option<(u64, Instant)> = None,
|
||||
listing_read_error: Option<String> = None,
|
||||
delivery_completion: bool = false,
|
||||
finished_web_pending: bool = false,
|
||||
finished_web_error: Option<String> = None,
|
||||
sync_dirty: bool = true,
|
||||
sync_request_meta: String = String::new(),
|
||||
}
|
||||
@ -288,7 +292,7 @@ impl Workspace {
|
||||
| "save" | "metadata-save" | "draft" | "production-deliver-bundle"
|
||||
| "image" | "image-progress" | "image-recover" | "template-progress"
|
||||
| "creation-facts" | "creation-points" | "creation-plan" | "creation-generate"
|
||||
| "creation-recover" | "creation-stream") || method.starts_with("slot-") => value,
|
||||
| "creation-recover" | "creation-stream" | "finished-web-open") || method.starts_with("slot-") => value,
|
||||
_ => return None,
|
||||
};
|
||||
let by_doc = data["documentId"].as_u64().or_else(|| data["doc"].as_u64())
|
||||
|
||||
@ -1,8 +1,11 @@
|
||||
'use client'
|
||||
|
||||
type MaterialDetailAction =
|
||||
import { ExternalLink } from 'lucide-react'
|
||||
|
||||
export type MaterialDetailAction =
|
||||
| 'favorite'
|
||||
| 'share'
|
||||
| 'finished-web'
|
||||
| 'edit'
|
||||
| 'delete'
|
||||
| null
|
||||
@ -24,6 +27,7 @@ type MaterialDetailHeaderProps = {
|
||||
onBack: () => void
|
||||
onFavorite: () => void
|
||||
onShare: () => void
|
||||
onOpenFinishedWeb?: () => void
|
||||
onEdit: () => void
|
||||
onDelete: () => void
|
||||
}
|
||||
@ -79,6 +83,7 @@ export default function MaterialDetailHeader({
|
||||
onBack,
|
||||
onFavorite,
|
||||
onShare,
|
||||
onOpenFinishedWeb,
|
||||
onEdit,
|
||||
onDelete,
|
||||
}: MaterialDetailHeaderProps) {
|
||||
@ -115,6 +120,18 @@ export default function MaterialDetailHeader({
|
||||
</div>
|
||||
|
||||
<div className="grid flex-none grid-cols-2 gap-2 sm:flex sm:flex-wrap sm:justify-end">
|
||||
{onOpenFinishedWeb && (
|
||||
<div className="col-span-2 [&>button]:w-full">
|
||||
<ActionButton
|
||||
label={busyAction === 'finished-web' ? '正在打开…' : '打开成品上架工作台'}
|
||||
disabled={controlsDisabled}
|
||||
onClick={onOpenFinishedWeb}
|
||||
>
|
||||
<ExternalLink size={18} aria-hidden="true" />
|
||||
</ActionButton>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{capabilities.canFavorite && (
|
||||
<ActionButton
|
||||
label={isFavorited ? '已收藏' : '收藏'}
|
||||
|
||||
@ -38,7 +38,7 @@ const file = (uploadId: string, fileName: string) => ({ uploadId, fileName, file
|
||||
const account = { id: 'owner', name: '登录账号' }
|
||||
const authorize = async () => account
|
||||
const input = {
|
||||
projectId: 'project-1', requestId: 'request-1', kind: 'detail' as const, productModel: 'SPU-1',
|
||||
projectId: 'project-1', requestId: 'request-1', kind: 'detail' as const, productModel: 'SPU-1', brandName: '示例品牌',
|
||||
assets: {
|
||||
main: [file('upload-main', 'main.jpg')],
|
||||
detail: [file('upload-detail', 'detail.jpg')],
|
||||
@ -122,7 +122,14 @@ test('同一花色的多张 SKU 图可共享原值数组', async () => {
|
||||
await expect(createDesktopDelivery(account.id, request, authorize)).rejects.toThrow('不能同时绑定')
|
||||
})
|
||||
|
||||
test('兼容此前以 productModel 和单条码签名的交付重试', async () => {
|
||||
test.each([undefined, '', ' '])('新交付缺少商品品牌时在上传前拒绝', async brandName => {
|
||||
await expect(createDesktopDelivery(account.id, { ...input, brandName }, authorize))
|
||||
.rejects.toMatchObject({ status: 400, code: 'brand_required', message: '请填写商品品牌后再完结提交' })
|
||||
expect(mkdir).not.toHaveBeenCalled()
|
||||
expect(findDetailMaterialMatches).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('兼容此前以空品牌、productModel 和单条码签名的交付重试', async () => {
|
||||
const fingerprint = createHash('sha256').update(JSON.stringify({
|
||||
projectId: input.projectId, requestId: input.requestId, kind: input.kind, productModel: input.productModel,
|
||||
categoryName: '', productCategoryName: '', brandName: '', productName: '', identifierType: '',
|
||||
@ -134,7 +141,7 @@ test('兼容此前以 productModel 和单条码签名的交付重试', async ()
|
||||
jest.mocked(prisma.$queryRawUnsafe).mockResolvedValueOnce([{ id: 'project-1' }]).mockResolvedValueOnce([
|
||||
{ requestId: input.requestId, fingerprint, materialId: 'old-material', materialType: '自动上架-详情', state: 'completed' },
|
||||
])
|
||||
await expect(createDesktopDelivery(account.id, input, authorize)).resolves.toMatchObject({ materialId: 'old-material' })
|
||||
await expect(createDesktopDelivery(account.id, { ...input, brandName: '' }, authorize)).resolves.toMatchObject({ materialId: 'old-material' })
|
||||
expect(mkdir).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@ -159,8 +166,8 @@ test('三种成品共用项目和 SPU,作者取自再次校验的会话,详
|
||||
...input, identifier: fixture.identifier, detailBarcode: fixture.detailBarcode, authorName: '伪造作者', userId: 'other-user',
|
||||
assets: { ...input.assets, sku: fixture.sku.map(sku => ({ ...file('upload-' + sku.variantId, sku.fileName), ...sku })) },
|
||||
},
|
||||
{ ...input, requestId: 'video-request', kind: 'video' as const, identifier: 'spu-9', assets: { files: [file('video', '成品.mp4')] } },
|
||||
{ ...input, requestId: 'show-request', kind: 'buyer_show' as const, identifier: 'SPU-9', assets: { files: [file('show', '买家秀.jpg')] } },
|
||||
{ ...input, requestId: 'video-request', kind: 'video' as const, identifier: 'spu-9', brandName: '', assets: { files: [file('video', '成品.mp4')] } },
|
||||
{ ...input, requestId: 'show-request', kind: 'buyer_show' as const, identifier: 'SPU-9', brandName: '', assets: { files: [file('show', '买家秀.jpg')] } },
|
||||
]
|
||||
for (const shipment of shipments) {
|
||||
const files = Object.values(shipment.assets).flat()
|
||||
|
||||
154
lib/__tests__/finished-web-sso.test.ts
Normal file
154
lib/__tests__/finished-web-sso.test.ts
Normal file
@ -0,0 +1,154 @@
|
||||
/** @jest-environment node */
|
||||
import { getEmployeeByUserId, type EmployeeDirectoryEntry } from '@/lib/employee-directory'
|
||||
import { issueFinishedWebLink } from '@/lib/finished-web-sso'
|
||||
|
||||
jest.mock('@/lib/employee-directory', () => ({ getEmployeeByUserId: jest.fn() }))
|
||||
|
||||
const endpoint = 'https://pddg.jiansuntuzhi.cn/api/sso/finished-web/token'
|
||||
const base = 'https://pddg.jiansuntuzhi.cn/finished-web/'
|
||||
const secret = 'test-configuration'
|
||||
const valid = {
|
||||
success: true,
|
||||
url: base + '#token=simulated-link',
|
||||
expiresAt: '2027-01-02T07:04:20.518Z',
|
||||
user: { id: 123, username: 'operator', name: '在职花名', role: 'operator' },
|
||||
}
|
||||
|
||||
function employee(employmentState = 'ACTIVE', flowerName: string | null = ' 在职花名 ') {
|
||||
return { employmentState, flowerName, displayName: '其他名字', realName: '实名' } as EmployeeDirectoryEntry
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.replaceProperty(process, 'env', { ...process.env, FINISHED_WEB_ACCESS_KEY: secret })
|
||||
jest.mocked(getEmployeeByUserId).mockResolvedValue(employee())
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks()
|
||||
jest.resetAllMocks()
|
||||
})
|
||||
|
||||
test('仅以正式在职花名签发,响应仅包含工作台链接、过期时间和账号信息', async () => {
|
||||
const fetch = jest.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json({
|
||||
...valid,
|
||||
token: 'discarded-test-field',
|
||||
user: { ...valid.user, secret },
|
||||
}))
|
||||
const timeout = jest.spyOn(AbortSignal, 'timeout')
|
||||
|
||||
await expect(issueFinishedWebLink('library-user')).resolves.toEqual({
|
||||
url: valid.url, expiresAt: valid.expiresAt, user: valid.user,
|
||||
})
|
||||
expect(getEmployeeByUserId).toHaveBeenCalledWith('library-user', { allowDingtalkFallback: false })
|
||||
expect(timeout).toHaveBeenCalledWith(15_000)
|
||||
expect(fetch).toHaveBeenCalledTimes(1)
|
||||
expect(fetch).toHaveBeenCalledWith(endpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ secret, nickname: '在职花名' }),
|
||||
redirect: 'error',
|
||||
cache: 'no-store',
|
||||
signal: expect.any(AbortSignal),
|
||||
})
|
||||
})
|
||||
|
||||
test.each([undefined, '', ' '])('未配置服务密钥时返回 503', async value => {
|
||||
if (value === undefined) delete process.env.FINISHED_WEB_ACCESS_KEY
|
||||
else process.env.FINISHED_WEB_ACCESS_KEY = value
|
||||
const fetch = jest.spyOn(globalThis, 'fetch').mockRejectedValue(new Error())
|
||||
await expect(issueFinishedWebLink('library-user')).rejects.toMatchObject({
|
||||
status: 503, message: expect.stringContaining('登录密钥尚未配置'),
|
||||
})
|
||||
expect(getEmployeeByUserId).not.toHaveBeenCalled()
|
||||
expect(fetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test.each([
|
||||
['未绑定', null],
|
||||
['离职', employee('RESIGNED')],
|
||||
['状态未知', employee('UNKNOWN')],
|
||||
['缺少花名', employee('ACTIVE', null)],
|
||||
['花名全为空格', employee('ACTIVE', ' ')],
|
||||
])('%s时拒绝签发', async (_label, entry) => {
|
||||
const fetch = jest.spyOn(globalThis, 'fetch').mockRejectedValue(new Error())
|
||||
jest.mocked(getEmployeeByUserId).mockResolvedValue(entry)
|
||||
await expect(issueFinishedWebLink('library-user')).rejects.toMatchObject({
|
||||
status: 404, message: expect.stringContaining('没有绑定在职花名'),
|
||||
})
|
||||
expect(fetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test.each([
|
||||
['HTTP', 'http://pddg.jiansuntuzhi.cn/finished-web/#token=simulated-link'],
|
||||
['其他域名', 'https://pddg.jiansuntuzhi.cn.example/finished-web/#token=simulated-link'],
|
||||
['非默认端口', 'https://pddg.jiansuntuzhi.cn:8443/finished-web/#token=simulated-link'],
|
||||
['用户名', 'https://operator@pddg.jiansuntuzhi.cn/finished-web/#token=simulated-link'],
|
||||
['其他路径', 'https://pddg.jiansuntuzhi.cn/finished-web/other/#token=simulated-link'],
|
||||
['查询参数', base + '?token=simulated-link'],
|
||||
['包含查询参数的片段链接', base + '?source=x#token=simulated-link'],
|
||||
['缺少片段', base],
|
||||
['空令牌', base + '#token='],
|
||||
['多余片段字段', base + '#token=simulated-link&extra=1'],
|
||||
['末尾控制字符', base + '#token=simulated-link\n'],
|
||||
])('拒绝工作台地址中的%s', async (_label, url) => {
|
||||
jest.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json({ ...valid, url }))
|
||||
await expect(issueFinishedWebLink('library-user')).rejects.toMatchObject({
|
||||
status: 503, code: 'finished_web_invalid_receipt',
|
||||
})
|
||||
})
|
||||
|
||||
test.each([
|
||||
{ success: false },
|
||||
{ expiresAt: 'invalid-date' },
|
||||
{ user: null },
|
||||
])('拒绝错误的成功响应字段 %j', async fields => {
|
||||
jest.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json({ ...valid, ...fields }))
|
||||
await expect(issueFinishedWebLink('library-user')).rejects.toMatchObject({
|
||||
status: 503, code: 'finished_web_invalid_receipt',
|
||||
})
|
||||
})
|
||||
|
||||
test.each([
|
||||
[400, '无法识别当前花名'],
|
||||
[401, '拒绝了服务授权'],
|
||||
[404, '没有在职账号'],
|
||||
[429, '过于频繁'],
|
||||
[503, '登录服务暂不可用'],
|
||||
[500, '登录服务暂不可用'],
|
||||
])('将上游 HTTP %i 转为中文错误', async (status, message) => {
|
||||
jest.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json({ error: 'untrusted-upstream-error' }, { status }))
|
||||
await expect(issueFinishedWebLink('library-user')).rejects.toMatchObject({
|
||||
status: status === 500 ? 503 : status,
|
||||
code: 'finished_web_upstream',
|
||||
message: expect.stringContaining(message),
|
||||
})
|
||||
})
|
||||
|
||||
test.each([false, true])('签发请求超时后返回 503(是否在读取响应体时超时:%s)', async duringRead => {
|
||||
const controller = new AbortController()
|
||||
jest.spyOn(AbortSignal, 'timeout').mockReturnValue(controller.signal)
|
||||
const abort = () => {
|
||||
controller.abort()
|
||||
return Promise.reject(new DOMException('request aborted', 'TimeoutError'))
|
||||
}
|
||||
jest.spyOn(globalThis, 'fetch').mockImplementation(() => duringRead
|
||||
? Promise.resolve({ ok: true, json: abort } as unknown as Response)
|
||||
: abort())
|
||||
await expect(issueFinishedWebLink('library-user')).rejects.toMatchObject({
|
||||
status: 503, message: expect.stringContaining('连接成品上架工作台超时'),
|
||||
})
|
||||
})
|
||||
|
||||
test('签发连线错误不会透出请求细节', async () => {
|
||||
jest.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('untrusted-network-error'))
|
||||
await expect(issueFinishedWebLink('library-user')).rejects.toMatchObject({
|
||||
status: 503, message: expect.stringContaining('暂时无法连接'),
|
||||
})
|
||||
})
|
||||
|
||||
test('HTTP 200 时拒绝无效 JSON', async () => {
|
||||
jest.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('not JSON'))
|
||||
await expect(issueFinishedWebLink('library-user')).rejects.toMatchObject({
|
||||
status: 503, code: 'finished_web_invalid_receipt',
|
||||
})
|
||||
})
|
||||
@ -177,6 +177,7 @@ export async function createDesktopDelivery(ownerId: string, input: Input, reaut
|
||||
desktopAssert(previous[0].requestId === request.requestId && [request.fingerprint, request.legacyFingerprint].includes(previous[0].fingerprint), '已有不同的交付记录,请保留原素材并联系管理员', 409, 'delivery_conflict')
|
||||
return {requestId:previous[0].requestId,materialId:previous[0].materialId,materialType:previous[0].materialType,state:previous[0].state}
|
||||
}
|
||||
desktopAssert(request.kind !== 'detail' || request.brandName, '请填写商品品牌后再完结提交', 400, 'brand_required')
|
||||
await projectDeliveryIdentifier(prisma, ownerId, request.projectId, request.identifier)
|
||||
|
||||
const barcodeFiles = request.files.filter(file => file.barcodes.length)
|
||||
|
||||
83
lib/finished-web-sso.ts
Normal file
83
lib/finished-web-sso.ts
Normal file
@ -0,0 +1,83 @@
|
||||
import { z } from 'zod'
|
||||
import { getEmployeeByUserId } from '@/lib/employee-directory'
|
||||
|
||||
const workbenchUrlPrefix = 'https://pddg.jiansuntuzhi.cn/finished-web/#token='
|
||||
const tokenEndpoint = 'https://pddg.jiansuntuzhi.cn/api/sso/finished-web/token'
|
||||
|
||||
const upstreamMessages: Record<number, string> = {
|
||||
400: '成品上架工作台无法识别当前花名,请联系管理员核对',
|
||||
401: '成品上架工作台拒绝了服务授权,请联系管理员',
|
||||
404: '当前花名在成品上架工作台没有在职账号,请联系管理员开通',
|
||||
429: '打开成品上架工作台的请求过于频繁,请稍后再试',
|
||||
503: '成品上架工作台的登录服务暂不可用,请稍后再试',
|
||||
}
|
||||
|
||||
const upstreamReceipt = z.object({
|
||||
success: z.literal(true),
|
||||
url: z.string().refine(value => {
|
||||
if (!value.startsWith(workbenchUrlPrefix)) return false
|
||||
const token = value.slice(workbenchUrlPrefix.length)
|
||||
return token.length > 0 && !/[^A-Za-z0-9._-]/.test(token)
|
||||
}),
|
||||
expiresAt: z.string().datetime({ offset: true }),
|
||||
user: z.object({
|
||||
id: z.union([z.number(), z.string()]),
|
||||
username: z.string(),
|
||||
name: z.string(),
|
||||
role: z.string(),
|
||||
}),
|
||||
})
|
||||
|
||||
export class FinishedWebSsoError extends Error {
|
||||
constructor(message: string, public readonly status: number, public readonly code: string) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
export async function issueFinishedWebLink(userId: string) {
|
||||
const secret = process.env.FINISHED_WEB_ACCESS_KEY
|
||||
if (!secret?.trim()) {
|
||||
throw new FinishedWebSsoError('成品上架工作台的登录密钥尚未配置,请联系管理员', 503, 'finished_web_unconfigured')
|
||||
}
|
||||
|
||||
const employee = await getEmployeeByUserId(userId, { allowDingtalkFallback: false })
|
||||
const nickname = employee?.employmentState === 'ACTIVE' ? employee.flowerName?.trim() : undefined
|
||||
if (!nickname) {
|
||||
throw new FinishedWebSsoError('当前账号没有绑定在职花名,请联系管理员核对人员档案', 404, 'finished_web_nickname_missing')
|
||||
}
|
||||
|
||||
const signal = AbortSignal.timeout(15_000)
|
||||
const unavailable = () => new FinishedWebSsoError(
|
||||
signal.aborted ? '连接成品上架工作台超时,请稍后再试' : '成品上架工作台暂时无法连接,请稍后再试',
|
||||
503, 'finished_web_unavailable',
|
||||
)
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(tokenEndpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ secret, nickname }),
|
||||
redirect: 'error',
|
||||
cache: 'no-store',
|
||||
signal,
|
||||
})
|
||||
} catch {
|
||||
throw unavailable()
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const status = Object.hasOwn(upstreamMessages, response.status) ? response.status : 503
|
||||
throw new FinishedWebSsoError(upstreamMessages[status], status, 'finished_web_upstream')
|
||||
}
|
||||
|
||||
const invalidReceipt = () => new FinishedWebSsoError(
|
||||
'成品上架工作台返回的登录信息无效,请联系管理员', 503, 'finished_web_invalid_receipt',
|
||||
)
|
||||
const data: unknown = await response.json().catch(() => {
|
||||
throw signal.aborted ? unavailable() : invalidReceipt()
|
||||
})
|
||||
const receipt = upstreamReceipt.safeParse(data)
|
||||
if (!receipt.success) throw invalidReceipt()
|
||||
const { url, expiresAt, user } = receipt.data
|
||||
return { url, expiresAt, user }
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user