feat: add user token secret management for channels
- Implemented user token secret generation and retrieval in channel service. - Added ResetUserTokenSecret method to reset the user token secret for channels. - Updated channel configuration parsing to include user token secret. - Enhanced WebSocket service to utilize user token secret for external info retrieval. - Modified dashboard channel edit component to support user token secret display and reset functionality. - Introduced API endpoint for resetting user token secret. - Updated IM and SDK configurations to include user token. - Added tests for user token verification logic.
This commit is contained in:
@@ -26,6 +26,7 @@ import {
|
||||
fetchAIAgentsAll,
|
||||
fetchChannel,
|
||||
fetchWxWorkKFAccounts,
|
||||
resetChannelUserTokenSecret,
|
||||
} from "@/lib/api/admin"
|
||||
|
||||
type ChannelFormDialogProps = {
|
||||
@@ -53,12 +54,14 @@ type WebChannelConfig = {
|
||||
themeColor?: string
|
||||
position?: "left" | "right"
|
||||
width?: string
|
||||
userTokenSecret?: string
|
||||
}
|
||||
|
||||
type WechatMPChannelConfig = {
|
||||
title?: string
|
||||
subtitle?: string
|
||||
themeColor?: string
|
||||
userTokenSecret?: string
|
||||
}
|
||||
|
||||
const defaultWebChannelConfig: Required<WebChannelConfig> = {
|
||||
@@ -67,6 +70,7 @@ const defaultWebChannelConfig: Required<WebChannelConfig> = {
|
||||
themeColor: "#2563eb",
|
||||
position: "right",
|
||||
width: "380px",
|
||||
userTokenSecret: "",
|
||||
}
|
||||
|
||||
const schema = z
|
||||
@@ -80,6 +84,7 @@ const schema = z
|
||||
widgetThemeColor: z.string().trim(),
|
||||
widgetPosition: z.enum(["left", "right"]),
|
||||
widgetWidth: z.string().trim(),
|
||||
userTokenSecret: z.string().trim(),
|
||||
remark: z.string().trim(),
|
||||
})
|
||||
.superRefine((values, ctx) => {
|
||||
@@ -110,6 +115,7 @@ const emptyForm: EditForm = {
|
||||
widgetThemeColor: defaultWebChannelConfig.themeColor,
|
||||
widgetPosition: defaultWebChannelConfig.position,
|
||||
widgetWidth: defaultWebChannelConfig.width,
|
||||
userTokenSecret: "",
|
||||
remark: "",
|
||||
}
|
||||
|
||||
@@ -139,6 +145,7 @@ function parseWebChannelConfig(configJson: string): Required<WebChannelConfig> {
|
||||
parsed.themeColor?.trim() || defaultWebChannelConfig.themeColor,
|
||||
position,
|
||||
width: parsed.width?.trim() || defaultWebChannelConfig.width,
|
||||
userTokenSecret: parsed.userTokenSecret?.trim() || "",
|
||||
}
|
||||
} catch {
|
||||
return defaultWebChannelConfig
|
||||
@@ -150,6 +157,7 @@ function parseWechatMPChannelConfig(configJson: string): Required<WechatMPChanne
|
||||
title: "公众号客服",
|
||||
subtitle: defaultWebChannelConfig.subtitle,
|
||||
themeColor: defaultWebChannelConfig.themeColor,
|
||||
userTokenSecret: "",
|
||||
}
|
||||
if (!configJson.trim()) {
|
||||
return fallback
|
||||
@@ -161,6 +169,7 @@ function parseWechatMPChannelConfig(configJson: string): Required<WechatMPChanne
|
||||
subtitle: parsed.subtitle?.trim() ?? fallback.subtitle,
|
||||
themeColor:
|
||||
parsed.themeColor?.trim() || defaultWebChannelConfig.themeColor,
|
||||
userTokenSecret: parsed.userTokenSecret?.trim() || "",
|
||||
}
|
||||
} catch {
|
||||
return fallback
|
||||
@@ -191,6 +200,7 @@ function buildForm(item: AdminChannel | null): EditForm {
|
||||
widgetThemeColor: wechatConfig?.themeColor ?? webConfig.themeColor,
|
||||
widgetPosition: webConfig.position,
|
||||
widgetWidth: webConfig.width,
|
||||
userTokenSecret: wechatConfig?.userTokenSecret ?? webConfig.userTokenSecret,
|
||||
remark: item.remark || "",
|
||||
}
|
||||
}
|
||||
@@ -204,6 +214,7 @@ function buildPayload(form: EditForm, status: number): CreateAdminChannelPayload
|
||||
subtitle: form.widgetSubtitle.trim(),
|
||||
themeColor:
|
||||
form.widgetThemeColor.trim() || defaultWebChannelConfig.themeColor,
|
||||
userTokenSecret: form.userTokenSecret.trim(),
|
||||
}
|
||||
const configJson =
|
||||
channelType === "wxwork_kf"
|
||||
@@ -214,6 +225,7 @@ function buildPayload(form: EditForm, status: number): CreateAdminChannelPayload
|
||||
...webLikeConfig,
|
||||
position: form.widgetPosition || defaultWebChannelConfig.position,
|
||||
width: form.widgetWidth.trim() || defaultWebChannelConfig.width,
|
||||
userTokenSecret: form.userTokenSecret.trim(),
|
||||
})
|
||||
return {
|
||||
channelType,
|
||||
@@ -276,10 +288,12 @@ function ChannelFormBody({
|
||||
handleSubmit,
|
||||
register,
|
||||
reset,
|
||||
setValue,
|
||||
formState: { errors },
|
||||
} = form
|
||||
const channelType = useWatch({ control, name: "channelType" })
|
||||
const openKfId = useWatch({ control, name: "openKfId" })
|
||||
const userTokenSecret = useWatch({ control, name: "userTokenSecret" })
|
||||
|
||||
useEffect(() => {
|
||||
async function loadAIAgents() {
|
||||
@@ -371,6 +385,44 @@ function ChannelFormBody({
|
||||
await onSubmit(buildPayload(values, currentStatus))
|
||||
}
|
||||
|
||||
async function handleResetUserTokenSecret() {
|
||||
if (!itemId) {
|
||||
return
|
||||
}
|
||||
if (!window.confirm("重置后旧 userToken 将在过期后失效,确认重置?")) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
const result = await resetChannelUserTokenSecret(itemId)
|
||||
setValue("userTokenSecret", result.userTokenSecret, {
|
||||
shouldDirty: true,
|
||||
})
|
||||
if (channelDetail) {
|
||||
const parsed = JSON.parse(channelDetail.configJson || "{}") as Record<string, unknown>
|
||||
parsed.userTokenSecret = result.userTokenSecret
|
||||
setChannelDetail({
|
||||
...channelDetail,
|
||||
configJson: JSON.stringify(parsed),
|
||||
})
|
||||
}
|
||||
toast.success("已重置用户 JWT Secret")
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "重置用户 JWT Secret 失败")
|
||||
}
|
||||
}
|
||||
|
||||
async function copyUserTokenSecret() {
|
||||
if (!userTokenSecret) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await navigator.clipboard.writeText(userTokenSecret)
|
||||
toast.success("已复制用户 JWT Secret")
|
||||
} catch {
|
||||
toast.error("复制失败")
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<ProjectDialog
|
||||
open={true}
|
||||
@@ -558,6 +610,52 @@ function ChannelFormBody({
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="space-y-3 rounded-md border p-3">
|
||||
<div>
|
||||
<div className="text-sm font-medium">用户 JWT Secret</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
业务系统使用该 secret 签发 userToken。重置后请同步更新业务系统配置。
|
||||
</div>
|
||||
</div>
|
||||
{!itemId ? (
|
||||
<div className="rounded-md bg-muted px-3 py-2 text-sm text-muted-foreground">
|
||||
保存渠道后可生成用户 JWT Secret。
|
||||
</div>
|
||||
) : (
|
||||
<Field data-invalid={!!errors.userTokenSecret}>
|
||||
<FieldLabel htmlFor="channel-user-token-secret">Secret</FieldLabel>
|
||||
<FieldContent>
|
||||
<div className="flex flex-col gap-2 sm:flex-row">
|
||||
<Input
|
||||
id="channel-user-token-secret"
|
||||
readOnly
|
||||
className="font-mono text-xs"
|
||||
{...register("userTokenSecret")}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={copyUserTokenSecret}
|
||||
disabled={!userTokenSecret}
|
||||
>
|
||||
<CopyIcon className="size-4" />
|
||||
复制
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => void handleResetUserTokenSecret()}
|
||||
>
|
||||
重置
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<FieldError errors={[errors.userTokenSecret]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
)}
|
||||
</div>
|
||||
{channelType === "wechat_mp" ? (
|
||||
<WechatMPAccessGuide channelId={channelDetail?.channelId || ""} />
|
||||
) : (
|
||||
|
||||
@@ -205,6 +205,10 @@ export type UpdateAdminChannelPayload = CreateAdminChannelPayload & {
|
||||
id: number
|
||||
}
|
||||
|
||||
export type ResetChannelUserTokenSecretResult = {
|
||||
userTokenSecret: string
|
||||
}
|
||||
|
||||
export type AIAgent = {
|
||||
id: number
|
||||
name: string
|
||||
@@ -589,6 +593,16 @@ export function updateChannelStatus(id: number, status: number) {
|
||||
})
|
||||
}
|
||||
|
||||
export function resetChannelUserTokenSecret(id: number) {
|
||||
return request<ResetChannelUserTokenSecretResult>(
|
||||
"/api/dashboard/channel/reset_user_token_secret",
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ id }),
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
export function deleteChannel(id: number) {
|
||||
return request<void>("/api/dashboard/channel/delete", {
|
||||
method: "POST",
|
||||
|
||||
+11
-5
@@ -105,6 +105,7 @@ export type ImWidgetConfig = {
|
||||
channelId?: string
|
||||
channelType?: string
|
||||
externalSource?: string
|
||||
userToken?: string
|
||||
title?: string
|
||||
subtitle?: string
|
||||
themeColor?: string
|
||||
@@ -149,18 +150,23 @@ function getRuntimeImConfig() {
|
||||
(widgetConfig.externalSource || OPEN_IM_EXTERNAL_SOURCE).trim() || "web_chat",
|
||||
externalId: (widgetConfig.externalId || "").trim(),
|
||||
externalName: (widgetConfig.externalName || "").trim(),
|
||||
userToken: (widgetConfig.userToken || "").trim(),
|
||||
}
|
||||
}
|
||||
|
||||
function createImHeaders() {
|
||||
const config = getRuntimeImConfig()
|
||||
const headers: Record<string, string> = {
|
||||
"X-External-Source": config.externalSource,
|
||||
"X-External-Id": config.externalId || getGuestId(),
|
||||
"X-Channel-Id": config.channelId,
|
||||
}
|
||||
if (config.externalName) {
|
||||
headers["X-External-Name"] = encodeURIComponent(config.externalName)
|
||||
if (config.userToken) {
|
||||
headers.Authorization = `Bearer ${config.userToken}`
|
||||
} else {
|
||||
headers["X-External-Source"] = config.externalSource
|
||||
headers["X-External-Id"] = config.externalId || getGuestId()
|
||||
if (config.externalName) {
|
||||
headers["X-External-Name"] = encodeURIComponent(config.externalName)
|
||||
}
|
||||
}
|
||||
return {
|
||||
...headers,
|
||||
@@ -212,7 +218,7 @@ export function fetchImMessages(
|
||||
)
|
||||
}
|
||||
|
||||
/** 外部身份仅通过 createImHeaders()(X-External-*)传递,无 JSON body */
|
||||
/** 外部身份仅通过 createImHeaders()(Authorization 或 X-External-*)传递,无 JSON body */
|
||||
export function createOrMatchImConversation() {
|
||||
return request<ImConversation>("/api/conversation/create_or_match", {
|
||||
...createRequestOptions({ method: "POST" }),
|
||||
|
||||
@@ -26,6 +26,12 @@ export function createImRealtimeConnection() {
|
||||
(config.externalSource ?? "web_chat").trim() || "web_chat"
|
||||
)
|
||||
const channelId = encodeURIComponent(config.channelId || "")
|
||||
const userToken = (config.userToken ?? "").trim()
|
||||
if (userToken) {
|
||||
return new WebSocket(
|
||||
`${baseUrl}/api/ws/open?channelId=${channelId}&userToken=${encodeURIComponent(userToken)}`
|
||||
)
|
||||
}
|
||||
const externalName = (config.externalName ?? "").trim()
|
||||
const nameQuery =
|
||||
externalName !== ""
|
||||
|
||||
@@ -8,6 +8,8 @@ export type KefuWidgetHostConfig = {
|
||||
externalId?: string
|
||||
/** 访客展示名,随请求以 X-External-Name / WS query externalName 传给后端 */
|
||||
externalName?: string
|
||||
/** 业务系统签发的前台用户 JWT */
|
||||
userToken?: string
|
||||
title?: string
|
||||
subtitle?: string
|
||||
position?: "left" | "right"
|
||||
@@ -52,6 +54,7 @@ export function readKefuWidgetConfig(): KefuWidgetHostConfig {
|
||||
undefined,
|
||||
externalId: query.get("externalId") ?? undefined,
|
||||
externalName: query.get("externalName") ?? undefined,
|
||||
userToken: query.get("userToken") ?? undefined,
|
||||
title: query.get("title") ?? undefined,
|
||||
subtitle: query.get("subtitle") ?? undefined,
|
||||
position: (query.get("position") as "left" | "right" | null) ?? undefined,
|
||||
|
||||
@@ -48,6 +48,9 @@
|
||||
}
|
||||
merged.channelId = String(merged.channelId || "");
|
||||
merged.externalSource = String(merged.externalSource || "web_chat");
|
||||
if (merged.userToken) {
|
||||
merged.userToken = String(merged.userToken);
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
@@ -67,6 +70,7 @@
|
||||
if (config.apiBaseUrl) frameUrl.searchParams.set("apiBaseUrl", config.apiBaseUrl);
|
||||
if (config.externalSource) frameUrl.searchParams.set("externalSource", config.externalSource);
|
||||
if (config.externalName) frameUrl.searchParams.set("externalName", config.externalName);
|
||||
if (config.userToken) frameUrl.searchParams.set("userToken", config.userToken);
|
||||
return frameUrl;
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +43,9 @@
|
||||
merged.apiBaseUrl = String(merged.apiBaseUrl || merged.baseUrl).replace(/\/$/, "");
|
||||
merged.channelId = String(merged.channelId || "");
|
||||
merged.externalSource = String(merged.externalSource || "web_chat");
|
||||
if (merged.userToken) {
|
||||
merged.userToken = String(merged.userToken);
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
@@ -67,6 +70,7 @@
|
||||
if (config.themeColor) frameUrl.searchParams.set("themeColor", config.themeColor);
|
||||
if (config.width) frameUrl.searchParams.set("width", config.width);
|
||||
if (config.externalName) frameUrl.searchParams.set("externalName", config.externalName);
|
||||
if (config.userToken) frameUrl.searchParams.set("userToken", config.userToken);
|
||||
return frameUrl;
|
||||
}
|
||||
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user