gongxiangp2/lib/desktop-client/knowledge-session.ts

29 lines
1.2 KiB
TypeScript

import { createHmac } from 'node:crypto'
import { DesktopClientError } from './contract.mjs'
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')
}
const issuedAt = Math.floor(Date.now() / 1000)
const expiresAt = Math.min(issuedAt + 300, Math.floor(new Date(desktopExpiresAt).getTime() / 1000))
if (!Number.isFinite(expiresAt) || expiresAt <= issuedAt) {
throw new DesktopClientError('客户端授权已过期,请重新登录', 401, 'session_expired')
}
const payload = Buffer.from(JSON.stringify({
sub: ownerId,
aud: 'xiaoyi-knowledge',
iat: issuedAt,
exp: expiresAt,
isSuperAdmin,
})).toString('base64url')
const signature = createHmac('sha256', Buffer.from(secret, 'utf8')).update(payload).digest('base64url')
return {
token: `ekb_xiaoyi_session_${payload}.${signature}`,
expiresAt: new Date(expiresAt * 1000).toISOString(),
}
}