Forward AskAI API cookies when proxying (#520)

This commit is contained in:
shenlan 2025-10-14 19:57:17 +08:00 committed by GitHub
parent 808aed7cef
commit 72e8da1dd4
2 changed files with 56 additions and 12 deletions

View File

@ -1,14 +1,42 @@
import { getInternalServerServiceBaseUrl } from '@lib/serviceConfig'
export async function POST(req: Request) {
const { question, history } = await req.json()
const apiBase = getInternalServerServiceBaseUrl()
const res = await fetch(`${apiBase}/api/askai`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ question, history })
})
const data = await res.json()
return Response.json(data, { status: res.status })
const FORWARDED_HEADERS = ['authorization', 'cookie', 'x-account-session'] as const
function buildForwardHeaders(req: Request) {
const headers = new Headers({ 'Content-Type': 'application/json' })
for (const name of FORWARDED_HEADERS) {
const value = req.headers.get(name)
if (value) {
headers.set(name, value)
}
}
return headers
}
export async function POST(req: Request) {
try {
const { question, history } = await req.json()
const apiBase = getInternalServerServiceBaseUrl()
const response = await fetch(`${apiBase}/api/askai`, {
method: 'POST',
headers: buildForwardHeaders(req),
body: JSON.stringify({ question, history }),
credentials: 'include'
})
const data = await response.json().catch(() => null)
if (data === null) {
return Response.json({ error: 'Invalid response from server' }, {
status: response.status
})
}
return Response.json(data, { status: response.status })
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error'
return Response.json({ error: message }, { status: 500 })
}
}

View File

@ -1,13 +1,29 @@
import { getInternalServerServiceBaseUrl } from '@lib/serviceConfig'
const FORWARDED_HEADERS = ['authorization', 'cookie', 'x-account-session'] as const
function buildForwardHeaders(req: Request) {
const headers = new Headers({ 'Content-Type': 'application/json' })
for (const name of FORWARDED_HEADERS) {
const value = req.headers.get(name)
if (value) {
headers.set(name, value)
}
}
return headers
}
export async function POST(req: Request) {
try {
const { question, history } = await req.json()
const apiBase = getInternalServerServiceBaseUrl()
const response = await fetch(`${apiBase}/api/rag/query`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ question, history })
headers: buildForwardHeaders(req),
body: JSON.stringify({ question, history }),
credentials: 'include'
})
const data = await response.json().catch(() => null)