fix(desktop): 为小壹知识库签发超管标记
This commit is contained in:
parent
a6f567850d
commit
c8cba8ff5e
@ -36,7 +36,7 @@ async function route(request:Request,{params}:{params:{path:string[]}}){
|
||||
if(parts[0]==='session'&&parts.length===1){if(method==='GET')value={account:auth.account,expiresAt:auth.expiresAt};else if(method==='DELETE'){await revokeDesktop(auth.id,ownerId);value={revoked:true}}else throw new DesktopClientError('接口不存在',404)}
|
||||
else if(parts[0]==='knowledge'&&parts[1]==='session'&&parts.length===2&&method==='GET'){
|
||||
const {issueKnowledgeSession}=await import('@/lib/desktop-client/knowledge-session')
|
||||
value=issueKnowledgeSession(ownerId,auth.expiresAt)
|
||||
value=issueKnowledgeSession(ownerId,auth.expiresAt,auth.isSuperAdmin)
|
||||
}
|
||||
else if(parts[0]==='product-platform'&&parts[1]==='spu'&&parts.length===2&&method==='GET'){
|
||||
const {desktopProductPlatformSpu}=await import('@/lib/desktop-client/product-platform')
|
||||
|
||||
@ -8,8 +8,8 @@ export const dynamic = 'force-dynamic'
|
||||
|
||||
async function route(request: Request) {
|
||||
try {
|
||||
const { account, expiresAt } = await requireDesktop(request)
|
||||
return await proxyKnowledge(request, account.id, expiresAt)
|
||||
const { account, expiresAt, isSuperAdmin } = await requireDesktop(request)
|
||||
return await proxyKnowledge(request, account.id, expiresAt, isSuperAdmin)
|
||||
} catch (error) {
|
||||
const known = error instanceof DesktopClientError
|
||||
const status = known ? error.status : 503
|
||||
|
||||
@ -15,7 +15,7 @@ const origin = 'https://knowledge.test:8443'
|
||||
const secret = randomBytes(32).toString('hex')
|
||||
const desktopAuth = 'Bearer dcs_' + randomBytes(48).toString('base64url')
|
||||
const expiresAt = new Date(Date.now() + 120_000)
|
||||
const account = { username: 'owner', status: 'active', isActive: true, archivedAt: null }
|
||||
const account = { username: 'owner', status: 'active', isActive: true, archivedAt: null, isSuperAdmin: false }
|
||||
const querySession = prisma.$queryRawUnsafe as jest.Mock
|
||||
const findUser = prisma.user.findUnique as jest.Mock
|
||||
const originalEnv = process.env
|
||||
@ -102,8 +102,9 @@ test.each([['POST', POST], ['PUT', PUT], ['PATCH', PATCH], ['DELETE', DELETE], [
|
||||
expect(upstream.mock.calls.length).toBe(0)
|
||||
})
|
||||
|
||||
test('forwards the current release query unchanged with a short-lived signed owner session', async () => {
|
||||
const query = '?a=%2f+%20&a=%25&flag'
|
||||
test.each([true, false])('forwards the query unchanged and signs the database isSuperAdmin=%s', async isSuperAdmin => {
|
||||
findUser.mockResolvedValueOnce({ ...account, isSuperAdmin })
|
||||
const query = `?a=%2f+%20&a=%25&flag&isSuperAdmin=${!isSuperAdmin}`
|
||||
const incoming = request(current + query, 'GET', {
|
||||
Accept: 'application/json', 'If-None-Match': '"v1"', 'X-EKB-Client-Version': '1.0',
|
||||
Cookie: 'example=test', 'X-API-Key': 'ignored',
|
||||
@ -125,8 +126,9 @@ test('forwards the current release query unchanged with a short-lived signed own
|
||||
const signed = /^Bearer ekb_xiaoyi_session_([\w-]+)\.([\w-]+)$/.exec(headers.get('authorization') ?? '')
|
||||
expect(Boolean(signed)).toBe(true)
|
||||
const [, payload, signature] = signed!
|
||||
const { sub, aud, iat, exp } = JSON.parse(Buffer.from(payload, 'base64url').toString())
|
||||
expect({ sub, aud }).toEqual({ sub: 'owner-id', aud: 'xiaoyi-knowledge' })
|
||||
const claims = JSON.parse(Buffer.from(payload, 'base64url').toString())
|
||||
expect(claims).toMatchObject({ sub: 'owner-id', aud: 'xiaoyi-knowledge', isSuperAdmin })
|
||||
const { iat, exp } = claims
|
||||
expect(exp).toBe(Math.floor(expiresAt.getTime() / 1000))
|
||||
expect(exp - iat).toBeGreaterThan(0)
|
||||
expect(exp - iat).toBeLessThanOrEqual(300)
|
||||
|
||||
@ -11,13 +11,13 @@ jest.mock('@/lib/auth', () => ({ authOptions: {} }))
|
||||
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
|
||||
|
||||
const context = { params: { path: ['knowledge', 'session'] } }
|
||||
const request = () => new Request('https://platform.test/api/desktop/knowledge/session', {
|
||||
const request = (claimedSuperAdmin = false) => new Request(`https://platform.test/api/desktop/knowledge/session?isSuperAdmin=${claimedSuperAdmin}`, {
|
||||
headers: { authorization: 'Bearer dcs_' + 'a'.repeat(64) },
|
||||
})
|
||||
const originalSecret = process.env.XIAOYI_KNOWLEDGE_SESSION_SECRET
|
||||
const originalEnabled = process.env.DETAIL_GENERATOR_ENABLED
|
||||
const secret = 'knowledge-session-test-secret-123456789'
|
||||
const user = { username: 'account', realName: '当前账号', isActive: true, status: 'active', archivedAt: null }
|
||||
const user = { username: 'account', realName: '当前账号', isActive: true, status: 'active', archivedAt: null, isSuperAdmin: false }
|
||||
const session = { id: 'session-id', ownerId: 'test-account', expiresAt: new Date('2026-12-01T09:00:00Z') }
|
||||
|
||||
describe('desktop knowledge session', () => {
|
||||
@ -57,15 +57,19 @@ describe('desktop knowledge session', () => {
|
||||
expect(prisma.user.findUnique).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
test('signs the account identity with the configured key and limits the lifetime', async () => {
|
||||
const response = await GET(request(), context)
|
||||
test.each([true, false])('signs the database isSuperAdmin=%s and limits the lifetime', async isSuperAdmin => {
|
||||
jest.mocked(prisma.user.findUnique).mockResolvedValue({ ...user, isSuperAdmin } as any)
|
||||
const response = await GET(request(!isSuperAdmin), context)
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.headers.get('cache-control')).toBe('private, no-store')
|
||||
const result = await response.json()
|
||||
const [encoded, signature] = result.token.replace('ekb_xiaoyi_session_', '').split('.')
|
||||
expect(signature).toBe(createHmac('sha256', secret).update(encoded).digest('base64url'))
|
||||
expect(signature === createHmac('sha256', secret).update(encoded).digest('base64url')).toBe(true)
|
||||
expect(prisma.user.findUnique).toHaveBeenCalledWith({
|
||||
where: { id: session.ownerId }, select: expect.objectContaining({ isSuperAdmin: true }),
|
||||
})
|
||||
expect(JSON.parse(Buffer.from(encoded, 'base64url').toString())).toEqual({
|
||||
sub: 'test-account', aud: 'xiaoyi-knowledge', iat: 1796112000, exp: 1796112300,
|
||||
sub: 'test-account', aud: 'xiaoyi-knowledge', iat: 1796112000, exp: 1796112300, isSuperAdmin,
|
||||
})
|
||||
expect(result.expiresAt).toBe('2026-12-01T08:05:00.000Z')
|
||||
|
||||
|
||||
@ -232,6 +232,10 @@ describe('materials route ai generated', () => {
|
||||
expect(prisma.material.findMany).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: expect.objectContaining({ AND: [{ OR: [
|
||||
{ taskDetailPrivate: false, accessScope: 'general', materialType: { in: ['买家秀图片'] } },
|
||||
{
|
||||
taskDetailPrivate: false, accessScope: 'general', userId: 'user-1',
|
||||
materialType: { in: ['自动上架-详情', '自动上架-视频', '自动上架-买家秀'] },
|
||||
},
|
||||
{ materialType: '任务-详情', taskDetailPrivate: true, accessScope: 'general', taskDetailRequesterUserId: 'user-1' },
|
||||
] }] }),
|
||||
}))
|
||||
|
||||
@ -25,7 +25,7 @@ function upstreamOrigin() {
|
||||
throw new DesktopClientError('企业知识库上游地址未正确配置,请联系管理员', 503, 'knowledge_upstream_misconfigured')
|
||||
}
|
||||
|
||||
export async function proxyKnowledge(request: Request, ownerId: string, expiresAt: Date) {
|
||||
export async function proxyKnowledge(request: Request, ownerId: string, expiresAt: Date, isSuperAdmin: boolean) {
|
||||
const { method } = request
|
||||
desktopAssert(method === 'GET' || method === 'HEAD', '企业知识库代理只支持 GET 和 HEAD', 405, 'knowledge_method_not_allowed')
|
||||
|
||||
@ -36,7 +36,7 @@ export async function proxyKnowledge(request: Request, ownerId: string, expiresA
|
||||
'企业知识库请求路径无效', 400, 'invalid_knowledge_path')
|
||||
|
||||
const origin = upstreamOrigin()
|
||||
const { token } = issueKnowledgeSession(ownerId, expiresAt)
|
||||
const { token } = issueKnowledgeSession(ownerId, expiresAt, isSuperAdmin)
|
||||
const requestHeaders = new Headers({ Authorization: `Bearer ${token}`, 'Accept-Encoding': 'identity' })
|
||||
for (const name of requestHeaderNames) {
|
||||
const value = request.headers.get(name)
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import { createHmac } from 'node:crypto'
|
||||
import { DesktopClientError } from './contract.mjs'
|
||||
|
||||
export function issueKnowledgeSession(ownerId: string, desktopExpiresAt: Date) {
|
||||
export function issueKnowledgeSession(ownerId: string, desktopExpiresAt: Date, isSuperAdmin: boolean) {
|
||||
const secret = process.env.XIAOYI_KNOWLEDGE_SESSION_SECRET
|
||||
if (!secret || Buffer.byteLength(secret, 'utf8') < 32) {
|
||||
throw new DesktopClientError('小壹知识库自动授权配置错误,请联系管理员', 503, 'knowledge_session_misconfigured')
|
||||
@ -18,6 +18,7 @@ export function issueKnowledgeSession(ownerId: string, desktopExpiresAt: Date) {
|
||||
aud: 'xiaoyi-knowledge',
|
||||
iat: issuedAt,
|
||||
exp: expiresAt,
|
||||
isSuperAdmin,
|
||||
})).toString('base64url')
|
||||
const signature = createHmac('sha256', Buffer.from(secret, 'utf8')).update(payload).digest('base64url')
|
||||
return {
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { isSuperAdminSync } from '@/lib/department-permission'
|
||||
import { findDetailProject, listDetailAssets, findDetailAsset } from '@/lib/detail-generator/repository'
|
||||
import { readDetailFile, saveDetailFile, deleteDetailFile } from '@/lib/detail-generator/storage'
|
||||
import { desktopAssert, desktopAuthorization, desktopId, desktopProjectBody, DesktopClientError, DESKTOP_CLIENT_ID, DESKTOP_SCOPES } from './contract.mjs'
|
||||
@ -10,18 +11,22 @@ const db = prisma
|
||||
type Row = Record<string, any>
|
||||
export type DesktopAccount = { id: string; name: string }
|
||||
const columns = 'id,owner_id AS "ownerId",source_web_id AS "sourceWebId",document,conversation,composer,status,revision,updated_at AS "updatedAt"'
|
||||
export async function desktopUser(id: string): Promise<DesktopAccount> {
|
||||
async function desktopIdentity(id: string) {
|
||||
desktopAssert(id, '请先登录', 401, 'unauthenticated')
|
||||
desktopAssert(process.env.DETAIL_GENERATOR_ENABLED === 'true', '小壹客户端服务尚未启用', 403, 'feature_disabled')
|
||||
const user = await db.user.findUnique({
|
||||
where: { id },
|
||||
select: { username: true, realName: true, status: true, isActive: true, archivedAt: true },
|
||||
select: { username: true, realName: true, status: true, isActive: true, archivedAt: true, isSuperAdmin: true },
|
||||
})
|
||||
if (!user?.isActive || user.status !== 'active' || user.archivedAt)
|
||||
throw new DesktopClientError('账号当前不可用,无法授权小壹客户端', 403, 'account_inactive')
|
||||
const name = user.realName?.trim() || user.username.trim()
|
||||
desktopAssert(name, '账号缺少可用署名,请联系管理员', 403, 'account_name_missing')
|
||||
return { id, name }
|
||||
return { account: { id, name }, isSuperAdmin: isSuperAdminSync(user.isSuperAdmin) }
|
||||
}
|
||||
export async function desktopUser(id: string): Promise<DesktopAccount> {
|
||||
const { account } = await desktopIdentity(id)
|
||||
return account
|
||||
}
|
||||
export async function approveDesktop(ownerId: string, input: Record<string, unknown>) {
|
||||
await desktopUser(ownerId)
|
||||
@ -52,7 +57,8 @@ export async function requireDesktop(request: Request) {
|
||||
desktopAssert(token, '请在网页上登录并授权客户端', 401, 'unauthenticated')
|
||||
const rows = await db.$queryRawUnsafe<Row[]>('SELECT id,owner_id AS "ownerId",expires_at AS "expiresAt" FROM desktop_client_sessions WHERE token_hash=$1 AND revoked_at IS NULL AND expires_at>NOW()', hash(token!))
|
||||
desktopAssert(rows[0], '客户端授权已过期或被撤销,请重新登录', 401, 'session_expired')
|
||||
return { id:String(rows[0].id),expiresAt:rows[0].expiresAt,account: await desktopUser(rows[0].ownerId) }
|
||||
const identity = await desktopIdentity(rows[0].ownerId)
|
||||
return { id: String(rows[0].id), expiresAt: rows[0].expiresAt, ...identity }
|
||||
}
|
||||
export async function revokeDesktop(id: string, ownerId: string) { await db.$executeRawUnsafe('UPDATE desktop_client_sessions SET revoked_at=NOW() WHERE id=$1 AND owner_id=$2', id, ownerId) }
|
||||
export async function listDesktopDevices(ownerId: string) {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user