Skip to content

Commit

Permalink
feat: 调整auth授权机制
Browse files Browse the repository at this point in the history
  • Loading branch information
weaigc committed Aug 3, 2023
1 parent dabc286 commit 7282d72
Show file tree
Hide file tree
Showing 12 changed files with 66 additions and 17 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ https://bing.github1s.tk
### 部署其它平台
<details>
<summary>
由于其他平台目前遭到 new bing 封杀,会遇到更多问题,不再做推荐,有需要的可以自行查看
由于其他平台目前遭到 New Bing 封杀,会遇到很多问题,不再做推荐,有需要的可以自行查看
</summary>

#### 部署到 Netlify
Expand Down
2 changes: 1 addition & 1 deletion cloudflare/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const TRAGET_HOST='hf4all-bingo.hf.space' // 请将此域名改成你自己的
export default {
async fetch(request) {
const uri = new URL(request.url);
uri.hostname = TRAGET_HOST
uri.host = TRAGET_HOST
return fetch(new Request(uri.toString(), request));
},
};
2 changes: 2 additions & 0 deletions next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ const nextConfig = {
config.resolve = {
...config.resolve,
fallback: {
'bufferutil': false,
'utf-8-validate': false,
http: false,
https: false,
stream: false,
Expand Down
2 changes: 1 addition & 1 deletion src/components/settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export function Settings() {
const maxAge = 86400 * 30
encodeHeadersToCookie(curlValue).forEach(cookie => document.cookie = `${cookie}; Max-Age=${maxAge}; Path=/`)
} else {
ChunkKeys.forEach(key => document.cookie = `${key}=; Path=/`)
[...ChunkKeys, 'BING_COOKIE', 'BING_UA', 'BING_IP'].forEach(key => document.cookie = `${key}=; Path=/`)
}

toast.success('保存成功')
Expand Down
4 changes: 2 additions & 2 deletions src/components/user-menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useEffect, useState } from 'react'
import Image from 'next/image'
import { toast } from 'react-hot-toast'
import { Button } from '@/components/ui/button'
import { version } from '../../package.json'
import pkg from '../../package.json'
import {
DropdownMenu,
DropdownMenuContent,
Expand Down Expand Up @@ -97,7 +97,7 @@ export function UserMenu() {
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem className="flex-col items-start">
<div className="font-medium">版本信息 {version}</div>
<div className="font-medium">版本信息 {pkg.version}</div>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem className="flex-col items-start">
Expand Down
4 changes: 2 additions & 2 deletions src/lib/hooks/use-bing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export function useBing(botId: BotId = 'bing') {
speaker.reset()
await chatState.bot.sendMessage({
prompt: input,
imageUrl,
imageUrl: /\?bcid=([^&]+)/.test(imageUrl ?? '') ? `https://www.bing.com/images/blob?bcid=${RegExp.$1}` : imageUrl,
options: {
...options,
useProxy,
Expand Down Expand Up @@ -94,7 +94,7 @@ export function useBing(botId: BotId = 'bing') {
setAttachmentList([{ url: imgUrl, status: 'loading' }])
const response = await chatState.bot.uploadImage(imgUrl, bingConversationStyle)
if (response?.blobId) {
setAttachmentList([{ url: `https://www.bing.com/images/blob?bcid=${response.blobId}`, status: 'loaded' }])
setAttachmentList([{ url: `/api/blob?bcid=${response.blobId}`, status: 'loaded' }])
} else {
setAttachmentList([{ url: imgUrl, status: 'error' }])
}
Expand Down
4 changes: 2 additions & 2 deletions src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ export function parseUA(ua?: string, default_ua = DEFAULT_UA) {
return / EDGE?/i.test(decodeURIComponent(ua || '')) ? decodeURIComponent(ua!.trim()) : default_ua
}

export function createHeaders(cookies: Partial<{ [key: string]: string }>) {
export function createHeaders(cookies: Partial<{ [key: string]: string }>, defaultHeaders?: Partial<{ [key: string]: string }>) {
let {
BING_COOKIE = process.env.BING_COOKIE,
BING_UA = process.env.BING_UA,
Expand All @@ -109,7 +109,7 @@ export function createHeaders(cookies: Partial<{ [key: string]: string }>) {
const ua = parseUA(BING_UA)

if (!BING_COOKIE) {
BING_COOKIE = 'xxx' // hf 暂时不用 Cookie 也可以正常使用
BING_COOKIE = defaultHeaders?.IMAGE_BING_COOKIE || 'xxx' // hf 暂时不用 Cookie 也可以正常使用
}

const parsedCookie = parseCookie(BING_COOKIE, '_U')
Expand Down
40 changes: 40 additions & 0 deletions src/pages/api/blob.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
'use server'

import { NextApiRequest, NextApiResponse } from 'next'
import { Readable } from 'node:stream'
import { fetch } from '@/lib/isomorphic'

const API_DOMAIN = 'https://www.bing.com'

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const { bcid } = req.query

const { headers, body } = await fetch(`${API_DOMAIN}/images/blob?bcid=${bcid}`,
{
method: 'GET',
headers: {
"sec-ch-ua": "\"Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"115\", \"Chromium\";v=\"115\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Windows\"",
"Referrer-Policy": "origin-when-cross-origin",
},
},
)

res.writeHead(200, {
'Content-Length': headers.get('content-length')!,
'Content-Type': headers.get('content-type')!,
})
// @ts-ignore
return Readable.fromWeb(body!).pipe(res)
} catch (e) {
console.log('Error', e)
return res.json({
result: {
value: 'UploadFailed',
message: `${e}`
}
})
}
}
6 changes: 3 additions & 3 deletions src/pages/api/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ import { NextApiRequest, NextApiResponse } from 'next'
import { fetch, debug } from '@/lib/isomorphic'
import { createHeaders } from '@/lib/utils'

const API_ENDPOINT = 'https://www.bing.com/turing/conversation/create'
// const API_ENDPOINT = 'https://edgeservices.bing.com/edgesvc/turing/conversation/create';
// const API_ENDPOINT = 'https://www.bing.com/turing/conversation/create'
const API_ENDPOINT = 'https://edgeservices.bing.com/edgesvc/turing/conversation/create';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const headers = createHeaders(req.cookies)

debug('headers', headers)
const response = await fetch(API_ENDPOINT, { method: 'GET', headers, redirect: 'error', mode: 'cors', credentials: 'include' })
const response = await fetch(API_ENDPOINT, { method: 'GET', headers })
.then((res) => res.text())
res.writeHead(200, {
'Content-Type': 'application/json',
Expand Down
9 changes: 7 additions & 2 deletions src/pages/api/image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,15 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
})
}
try {
const headers = createHeaders(req.cookies)
const headers = createHeaders(req.cookies, {
IMAGE_BING_COOKIE: process.env.IMAGE_BING_COOKIE
})

debug('headers', headers)
const response = await createImage(String(prompt), String(id), headers)
const response = await createImage(String(prompt), String(id), {
...headers,
'x-ms-useragent': 'azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.0 OS/Win32',
})
res.writeHead(200, {
'Content-Type': 'text/plain; charset=UTF-8',
})
Expand Down
7 changes: 4 additions & 3 deletions src/pages/api/kblob.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
'use server'

import { NextApiRequest, NextApiResponse } from 'next'
import FormData from 'form-data'
import { fetch } from '@/lib/isomorphic'
import { KBlobRequest } from '@/lib/bots/bing/types'
import FormData from 'form-data'

const API_DOMAIN = 'https://www.bing.com'
// const API_DOMAIN = 'https://bing.vcanbb.top'
const API_DOMAIN = 'https://bing.vcanbb.top'

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const { knowledgeRequest, imageBase64 } = req.body as KBlobRequest

const formData = new FormData()
formData.append('knowledgeRequest', JSON.stringify(knowledgeRequest))
if (imageBase64) {
Expand All @@ -27,6 +27,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
"sec-ch-ua-platform": "\"Windows\"",
"Referer": `${API_DOMAIN}/web/index.html`,
"Referrer-Policy": "origin-when-cross-origin",
'x-ms-useragent': 'azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.0 OS/Win32',
...formData.getHeaders()
}
}
Expand Down
1 change: 1 addition & 0 deletions src/pages/api/sydney.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
...headers,
'accept-language': 'zh-CN,zh;q=0.9',
'cache-control': 'no-cache',
'x-ms-useragent': 'azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.0 OS/Win32',
pragma: 'no-cache',
}
})
Expand Down

0 comments on commit 7282d72

Please sign in to comment.