Skip to content

Commit

Permalink
feat: 支持环境变量
Browse files Browse the repository at this point in the history
  • Loading branch information
weaigc committed Sep 15, 2023
1 parent 4e78b05 commit 5ecc9f9
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
13 changes: 12 additions & 1 deletion cloudflare/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,18 @@ const { join } = require('path');
const miniflare = join(require.resolve('miniflare'), '../cli.js')
const script = join(__dirname, './worker.js');

const proc = spawn(`node`, ['--experimental-vm-modules', miniflare, script, '-w', '-d', '-m', '-p', process.env.PORT || 8080])
const proc = spawn(`node`, [
'--experimental-vm-modules',
miniflare,
script,
'-w',
'-d',
'-m',
'-b',
`BING_COOKIE=${process.env.BING_COOKIE || ''}`,
'-p',
process.env.PORT || 8080
])
proc.stdout.on('data', (chunk) => {
process.stdout.write(chunk)
})
Expand Down
28 changes: 24 additions & 4 deletions cloudflare/worker.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,23 @@
const SITE_HOST = '' // 为空则自动推断
const TARGET_HOST='hf4all-bingo.hf.space' // 后台服务,默认不需要修改
const BING_COOKIE = '' // 换成你自己的 BING_COOKIE,操作参见 README.md
const TARGET_HOST = 'hf4all-bingo.hf.space' // 后台服务,默认不需要修改

function parseCookie(cookie, cookieName) {
if (!cookie || !cookieName) return ''
const targetCookie = new RegExp(`(?:[; ]|^)${cookieName}=([^;]*)`).test(cookie) ? RegExp.$1 : cookie
return targetCookie ? decodeURIComponent(targetCookie).trim() : cookie.indexOf('=') === -1 ? cookie.trim() : ''
}

function parseCookies(cookie, cookieNames) {
const cookies = {}
cookieNames.forEach(cookieName => {
cookies[cookieName] = parseCookie(cookie, cookieName)
})
return cookies
}
function formatCookies(cookieObj) {
return Object.keys(cookieObj).map(key => `${key}=${cookieObj[key]}`).join('; ')
}

export default {
async handleOptions(request) {
Expand Down Expand Up @@ -39,7 +56,7 @@ export default {
})
},

async fetch(request) {
async fetch(request, env) {
const uri = new URL(request.url)
console.log('uri', uri.toString())
if (request.method === 'OPTIONS') {
Expand All @@ -64,8 +81,11 @@ export default {
return this.handleWebSocket(headers)
}
if (uri.pathname.startsWith('/turing/')) {
if (BING_COOKIE) {
headers.set('cookie', BING_COOKIE)
if (BING_COOKIE || env.BING_COOKIE) {
headers.set('cookie', formatCookies({
...parseCookies(env.BING_COOKIE || BING_COOKIE, ['MUID']),
_U: 'xxx'
}))
}
uri.host = 'www.bing.com'
} else {
Expand Down

0 comments on commit 5ecc9f9

Please sign in to comment.