28 lines
1.1 KiB
TypeScript
28 lines
1.1 KiB
TypeScript
import { createHmac } from 'node:crypto'
|
|
import { DesktopClientError } from './contract.mjs'
|
|
|
|
export function issueKnowledgeSession(ownerId: string, desktopExpiresAt: Date) {
|
|
const secret = process.env.XIAOYI_KNOWLEDGE_SESSION_SECRET
|
|
if (!secret || Buffer.byteLength(secret, 'utf8') < 32) {
|
|
throw new DesktopClientError('小壹知识库自动授权暂不可用', 503, 'knowledge_session_unavailable')
|
|
}
|
|
|
|
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,
|
|
})).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(),
|
|
}
|
|
}
|