Skip to content

Commit 3a029f2

Browse files
committed
Fix qianwen csrf token
1 parent 0ed28e2 commit 3a029f2

2 files changed

Lines changed: 22 additions & 6 deletions

File tree

src/app/bots/qianwen/api.ts

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@ interface CreationResponse {
1010
errorCode: string | null
1111
}
1212

13-
export async function createConversation(firstQuery: string) {
13+
export async function createConversation(firstQuery: string, csrfToken: string) {
1414
const resp = await ofetch<CreationResponse>('https://qianwen.aliyun.com/addSession', {
1515
method: 'POST',
1616
body: { firstQuery },
1717
headers: {
18-
'X-Xsrf-Token': '7a3dae93-1d29-4eb6-9940-34efad5a2b78',
18+
'X-Xsrf-Token': csrfToken,
1919
},
2020
})
2121
if (!resp.success) {
@@ -26,3 +26,17 @@ export async function createConversation(firstQuery: string) {
2626
}
2727
return resp.data.sessionId
2828
}
29+
30+
function extractVariable(variableName: string, html: string) {
31+
const regex = new RegExp(`${variableName}\\s?=\\s?"([^"]+)"`)
32+
const match = regex.exec(html)
33+
if (!match) {
34+
throw new Error('Failed to get csrfToken')
35+
}
36+
return match[1]
37+
}
38+
39+
export async function getCsrfToken() {
40+
const html = await ofetch('https://qianwen.aliyun.com', { parseResponse: (t) => t })
41+
return extractVariable('csrfToken', html)
42+
}

src/app/bots/qianwen/index.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { parseSSEResponse } from '~utils/sse'
22
import { AbstractBot, SendMessageParams } from '../abstract-bot'
33
import { requestHostPermission } from '~app/utils/permissions'
44
import { ChatError, ErrorCode } from '~utils/errors'
5-
import { createConversation } from './api'
5+
import { createConversation, getCsrfToken } from './api'
66
import { uuid } from '~utils'
77

88
function generateMessageId() {
@@ -11,6 +11,7 @@ function generateMessageId() {
1111

1212
interface ConversationContext {
1313
conversationId: string
14+
csrfToken: string
1415
lastMessageId?: string
1516
}
1617

@@ -23,16 +24,17 @@ export class QianwenWebBot extends AbstractBot {
2324
}
2425

2526
if (!this.conversationContext) {
26-
const conversationId = await createConversation(params.prompt)
27-
this.conversationContext = { conversationId }
27+
const csrfToken = await getCsrfToken()
28+
const conversationId = await createConversation(params.prompt, csrfToken)
29+
this.conversationContext = { conversationId, csrfToken }
2830
}
2931

3032
const resp = await fetch('https://qianwen.aliyun.com/conversation', {
3133
method: 'POST',
3234
signal: params.signal,
3335
headers: {
3436
'Content-Type': 'application/json',
35-
'X-Xsrf-Token': '7a3dae93-1d29-4eb6-9940-34efad5a2b78',
37+
'X-Xsrf-Token': this.conversationContext.csrfToken,
3638
},
3739
body: JSON.stringify({
3840
action: 'next',

0 commit comments

Comments
 (0)