dsh-go-workbuddy 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +67 -2
- package/bridge/bridge.mjs +323 -0
- package/bridge/oauth.mjs +169 -0
- package/bridge/tools/farm.mjs +62 -0
- package/bridge/vendor/dsh-connect-workbuddy/LICENSE +21 -0
- package/bridge/vendor/dsh-connect-workbuddy/THIRD_PARTY_NOTICES.md +69 -0
- package/bridge/vendor/dsh-connect-workbuddy/lib/host-heartbeat-BxjdI1KZ.js +12761 -0
- package/bridge/vendor/dsh-connect-workbuddy/lib/index.js +18578 -0
- package/bridge/vendor/dsh-connect-workbuddy/package.json +7 -0
- package/cordis.patch.yml +8 -0
- package/lib/index.js +497 -0
- package/package.json +72 -4
- package/package.json.bak-pub +72 -0
package/README.md
CHANGED
|
@@ -1,3 +1,68 @@
|
|
|
1
|
-
#
|
|
1
|
+
# local-workbuddy
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
dsh-go 手机原生界面里的 WorkBuddy 入口:输入框上方一条积分胶囊、一个签到胶囊,
|
|
4
|
+
加上「积分」和「模型」两个原生面板。数据全部来自本机已登录的 WorkBuddy 账号。
|
|
5
|
+
|
|
6
|
+
## 为什么要有它
|
|
7
|
+
|
|
8
|
+
`dsh-connect-workbuddy` 本体是给 Harness 网页版用的:设置卡片是 web 组件,Flutter
|
|
9
|
+
界面里看不到;它自带的 `/v1` 网关只绑在插件进程内的随机端口,外部拿不到。
|
|
10
|
+
所以这里做了两件事:
|
|
11
|
+
|
|
12
|
+
1. `bridge/` 里放了一个本地桥,直连插件导出的 `WorkBuddyCredentialStore` /
|
|
13
|
+
`WorkBuddyUpstreamClient`(复用登录态与自动续期,不碰任何账号状态)。
|
|
14
|
+
2. `lib/index.js` 把桥的数据画成原生胶囊和面板;首次用到时自动起桥。
|
|
15
|
+
|
|
16
|
+
结构照抄 `local-codearts` 那套:`package.json` 的 `dshGo.contributes` 声明界面,
|
|
17
|
+
`lib/index.js` 在 `ctx.inject(['dshGo'], …)` 里写处理逻辑。
|
|
18
|
+
|
|
19
|
+
## 界面
|
|
20
|
+
|
|
21
|
+
| 位置 | 内容 |
|
|
22
|
+
| --- | --- |
|
|
23
|
+
| 输入框上方胶囊 | `WB 登录`(检查登录态,没登录就复制网页版地址) |
|
|
24
|
+
| 输入框上方胶囊 | `WB 签到`(一键领今日积分,会真写账号) |
|
|
25
|
+
| 输入框上方状态条 | `WB 余 N 积分`,5 分钟刷新一次 |
|
|
26
|
+
| 面板「WorkBuddy 积分」 | 剩余积分、区域、账号、今日签到、连续天数、积分包列表、刷新 / 签到 / 切区 |
|
|
27
|
+
| 面板「WorkBuddy 模型」 | 当前区可用模型,点一行复制模型 id |
|
|
28
|
+
| 加号面板 `WB 模型` | 直接打开模型面板 |
|
|
29
|
+
|
|
30
|
+
面板出现在对话详情页「插件」页签和「全部功能」。
|
|
31
|
+
|
|
32
|
+
## 依赖
|
|
33
|
+
|
|
34
|
+
- 本机装 `dsh-connect-workbuddy`(web profile),且至少登录过一个区。
|
|
35
|
+
- 桥的 `node_modules` 是符号链接农场:`bridge/tools/farm.mjs` 会把 `/opt/dsh/node_modules`
|
|
36
|
+
和各 profile 的 `node_modules` 链过来。首次用桥时插件会自动跑一次,也可以手动:
|
|
37
|
+
|
|
38
|
+
```sh
|
|
39
|
+
cd ~/.dsh/dsh-go/plugins/local-workbuddy/bridge
|
|
40
|
+
node tools/farm.mjs
|
|
41
|
+
node --preserve-symlinks --preserve-symlinks-main bridge.mjs
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## 登录
|
|
45
|
+
|
|
46
|
+
插件不发起登录,只读登录态:
|
|
47
|
+
|
|
48
|
+
- 国内版 `/root/.dsh/.workbuddy-auth.cn.json`
|
|
49
|
+
- 国际版 `/root/.dsh/.workbuddy-auth.global.json`
|
|
50
|
+
|
|
51
|
+
登录入口:手机浏览器打开 `http://127.0.0.1:3080` → 设置 → WorkBuddy → 扫码。
|
|
52
|
+
点「WB 登录」胶囊会把地址复制到剪贴板。
|
|
53
|
+
|
|
54
|
+
## 对外还能单独用
|
|
55
|
+
|
|
56
|
+
`bridge/bridge.mjs` 本身就是个 OpenAI 兼容服务(`/v1/models`、`/v1/chat/completions`,
|
|
57
|
+
外加 `/api/accounts`、`/api/credits`、`/api/checkin`),任何软件都能把 base_url 指过来:
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
node bridge.mjs # 127.0.0.1:8791,Bearer 在 ~/.workbuddy-bridge-token
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## 卸载
|
|
64
|
+
|
|
65
|
+
```sh
|
|
66
|
+
dsh plugin --profile web remove local-workbuddy
|
|
67
|
+
```
|
|
68
|
+
再删本目录。
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// WorkBuddy 本地桥:把 dsh-connect-workbuddy 的登录态 + 上游客户端包成
|
|
3
|
+
// 一个 OpenAI 兼容的 HTTP 服务,任何软件都能直接调用 WorkBuddy 的模型与积分。
|
|
4
|
+
//
|
|
5
|
+
// 用法:
|
|
6
|
+
// node tools/farm.mjs # 一次性:建依赖链接
|
|
7
|
+
// node bridge.mjs # 启动,默认 127.0.0.1:8791
|
|
8
|
+
//
|
|
9
|
+
// 接口:
|
|
10
|
+
// GET /health
|
|
11
|
+
// GET /api/accounts?region=cn|global
|
|
12
|
+
// GET /api/credits?region=cn&account=ID
|
|
13
|
+
// GET /api/checkin?region=cn POST /api/checkin?region=cn
|
|
14
|
+
// GET /v1/models?region=cn
|
|
15
|
+
// POST /v1/chat/completions (OpenAI 兼容,支持 stream:true)
|
|
16
|
+
import { createServer } from 'node:http'
|
|
17
|
+
import { spawnSync } from 'node:child_process'
|
|
18
|
+
import { readFileSync, writeFileSync, existsSync } from 'node:fs'
|
|
19
|
+
import { randomBytes } from 'node:crypto'
|
|
20
|
+
import { join, dirname } from 'node:path'
|
|
21
|
+
import { fileURLToPath } from 'node:url'
|
|
22
|
+
import { homedir } from 'node:os'
|
|
23
|
+
import * as oauth from './oauth.mjs'
|
|
24
|
+
|
|
25
|
+
const here = dirname(fileURLToPath(import.meta.url))
|
|
26
|
+
|
|
27
|
+
let wb
|
|
28
|
+
try {
|
|
29
|
+
wb = await import('dsh-connect-workbuddy')
|
|
30
|
+
} catch (error) {
|
|
31
|
+
if (process.platform !== 'win32' && !process.execArgv.includes('--preserve-symlinks')) {
|
|
32
|
+
// ESM 解析会回到真实路径,只有带这两个开关才能从农场里找到 peer 依赖
|
|
33
|
+
const r = spawnSync(
|
|
34
|
+
process.execPath,
|
|
35
|
+
['--preserve-symlinks', '--preserve-symlinks-main', fileURLToPath(import.meta.url), ...process.argv.slice(2)],
|
|
36
|
+
{ stdio: 'inherit', env: process.env }
|
|
37
|
+
)
|
|
38
|
+
process.exit(r.status ?? 1)
|
|
39
|
+
}
|
|
40
|
+
console.error('[bridge] 载入 dsh-connect-workbuddy 失败:', error.message)
|
|
41
|
+
console.error('[bridge] 先跑 `node tools/farm.mjs`,并确认插件已装进某个 profile。')
|
|
42
|
+
process.exit(1)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const {
|
|
46
|
+
WorkBuddyCredentialStore,
|
|
47
|
+
WorkBuddyUpstreamClient,
|
|
48
|
+
workbuddyOwnAuthPath,
|
|
49
|
+
WORKBUDDY_CONNECT_VERSION,
|
|
50
|
+
} = wb
|
|
51
|
+
|
|
52
|
+
const PORT = Number(process.env.WB_BRIDGE_PORT || 8792)
|
|
53
|
+
const HOST = process.env.WB_BRIDGE_HOST || '127.0.0.1'
|
|
54
|
+
|
|
55
|
+
// ——— 桥自己的 Bearer ——
|
|
56
|
+
function loadToken() {
|
|
57
|
+
if (process.env.WB_BRIDGE_TOKEN) return process.env.WB_BRIDGE_TOKEN
|
|
58
|
+
const file = join(homedir(), '.workbuddy-bridge-token')
|
|
59
|
+
if (existsSync(file)) return readFileSync(file, 'utf8').trim()
|
|
60
|
+
const token = 'wb-' + randomBytes(24).toString('hex')
|
|
61
|
+
writeFileSync(file, token + '\n', { mode: 0o600 })
|
|
62
|
+
return token
|
|
63
|
+
}
|
|
64
|
+
const TOKEN = loadToken()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
const client = new WorkBuddyUpstreamClient()
|
|
68
|
+
const creditCache = new Map()
|
|
69
|
+
const checkinCache = new Map()
|
|
70
|
+
|
|
71
|
+
// 一个区一个 store;refresh 直接借上游客户端的刷新接口
|
|
72
|
+
const stores = new Map()
|
|
73
|
+
function storeOf(region) {
|
|
74
|
+
if (region !== 'cn' && region !== 'global') throw new Error(`unknown region: ${region}`)
|
|
75
|
+
let s = stores.get(region)
|
|
76
|
+
if (s === undefined) {
|
|
77
|
+
s = new WorkBuddyCredentialStore({
|
|
78
|
+
region,
|
|
79
|
+
refresh: (credential) => client.refreshToken(credential),
|
|
80
|
+
})
|
|
81
|
+
stores.set(region, s)
|
|
82
|
+
}
|
|
83
|
+
return s
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function credentialOf(region, accountId) {
|
|
87
|
+
const store = storeOf(region)
|
|
88
|
+
if (accountId) {
|
|
89
|
+
const c = await store.credentialFor(accountId)
|
|
90
|
+
if (c === undefined) throw Object.assign(new Error('account not found'), { status: 404 })
|
|
91
|
+
return c
|
|
92
|
+
}
|
|
93
|
+
return await store.resolve()
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function send(res, status, body, headers = {}) {
|
|
97
|
+
const text = typeof body === 'string' ? body : JSON.stringify(body)
|
|
98
|
+
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', ...headers })
|
|
99
|
+
res.end(text)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function fail(res, status, code, message) {
|
|
103
|
+
send(res, status, { error: { code, message, type: 'workbuddy_bridge' } })
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function authorized(req) {
|
|
107
|
+
const raw = req.headers.authorization || ''
|
|
108
|
+
return raw.startsWith('Bearer ') && raw.slice(7).trim() === TOKEN
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// 区的三种指定方式:?region= / X-WB-Region 头 / 模型名前缀 global:xxx
|
|
112
|
+
function regionOf(req, url, modelId) {
|
|
113
|
+
const direct = url.searchParams.get('region') || req.headers['x-wb-region']
|
|
114
|
+
if (direct === 'cn' || direct === 'global') return direct
|
|
115
|
+
if (typeof modelId === 'string' && modelId.startsWith('global:')) return 'global'
|
|
116
|
+
return 'cn'
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function modelIdOf(modelId) {
|
|
120
|
+
if (typeof modelId === 'string' && modelId.includes(':')) return modelId.slice(modelId.indexOf(':') + 1)
|
|
121
|
+
return modelId
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function readBody(req, limit = 8 << 20) {
|
|
125
|
+
const chunks = []
|
|
126
|
+
let size = 0
|
|
127
|
+
for await (const chunk of req) {
|
|
128
|
+
size += chunk.length
|
|
129
|
+
if (size > limit) throw Object.assign(new Error('body too large'), { status: 413 })
|
|
130
|
+
chunks.push(chunk)
|
|
131
|
+
}
|
|
132
|
+
return Buffer.concat(chunks).toString('utf8')
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const server = createServer(async (req, res) => {
|
|
136
|
+
const url = new URL(req.url || '/', `http://${HOST}:${PORT}`)
|
|
137
|
+
const path = url.pathname
|
|
138
|
+
try {
|
|
139
|
+
if (path === '/health') {
|
|
140
|
+
const out = { ok: true, plugin: WORKBUDDY_CONNECT_VERSION, features: ['accounts', 'credits', 'checkin', 'models', 'chat', 'login'], regions: {} }
|
|
141
|
+
for (const region of ['cn', 'global']) {
|
|
142
|
+
try {
|
|
143
|
+
const accounts = await storeOf(region).accounts()
|
|
144
|
+
out.regions[region] = { accounts: accounts.length, authPath: workbuddyOwnAuthPath(region) }
|
|
145
|
+
} catch (error) {
|
|
146
|
+
out.regions[region] = { error: String(error && error.message) }
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return send(res, 200, out)
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (!authorized(req)) return fail(res, 401, 'unauthorized', 'Bearer token required')
|
|
153
|
+
|
|
154
|
+
if (path === '/api/login/start' && (req.method === 'POST' || req.method === 'GET')) {
|
|
155
|
+
const region = regionOf(req, url)
|
|
156
|
+
const answer = await oauth.start(region)
|
|
157
|
+
return send(res, 200, { region, ...answer })
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (path === '/api/login/poll' && req.method === 'POST') {
|
|
161
|
+
const region = regionOf(req, url)
|
|
162
|
+
const raw = await readBody(req)
|
|
163
|
+
const payload = JSON.parse(raw || '{}')
|
|
164
|
+
if (typeof payload.loginId !== 'string' || payload.loginId === '') return fail(res, 400, 'bad_login_id', 'loginId required')
|
|
165
|
+
const answer = await oauth.poll(region, payload.loginId, storeOf(region))
|
|
166
|
+
return send(res, 200, { region, ...answer })
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (path === '/api/account/remove' && req.method === 'POST') {
|
|
170
|
+
const region = regionOf(req, url)
|
|
171
|
+
const target = url.searchParams.get('account')
|
|
172
|
+
if (target === null || target === '') return fail(res, 400, 'bad_account', 'account required')
|
|
173
|
+
await storeOf(region).removeAccount(target)
|
|
174
|
+
creditCache.clear()
|
|
175
|
+
checkinCache.clear()
|
|
176
|
+
return send(res, 200, { ok: true, account: target })
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
if (path === '/api/cache/clear') {
|
|
180
|
+
creditCache.clear()
|
|
181
|
+
checkinCache.clear()
|
|
182
|
+
return send(res, 200, { ok: true })
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (path === '/api/accounts') {
|
|
186
|
+
const accounts = await storeOf(regionOf(req, url)).accounts()
|
|
187
|
+
return send(res, 200, { accounts })
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (path === '/api/credits') {
|
|
191
|
+
const region = regionOf(req, url)
|
|
192
|
+
const acct = url.searchParams.get('account')
|
|
193
|
+
const key = `${region}:${acct ?? ''}`
|
|
194
|
+
const nowT = Date.now()
|
|
195
|
+
const hit = creditCache.get(key)
|
|
196
|
+
const force = url.searchParams.get('force') === '1'
|
|
197
|
+
if (hit !== undefined && !force && nowT - hit.at < 300_000) {
|
|
198
|
+
return send(res, 200, hit.value)
|
|
199
|
+
}
|
|
200
|
+
const credential = await credentialOf(region, acct)
|
|
201
|
+
const credits = await client.fetchCredits(credential)
|
|
202
|
+
creditCache.set(key, { at: nowT, value: credits })
|
|
203
|
+
return send(res, 200, credits)
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (path === '/api/checkin') {
|
|
207
|
+
const region = regionOf(req, url)
|
|
208
|
+
const acct = url.searchParams.get('account')
|
|
209
|
+
const key = `${region}:${acct ?? ''}`
|
|
210
|
+
const credential = await credentialOf(region, acct)
|
|
211
|
+
if (req.method === 'POST') {
|
|
212
|
+
const claim = await client.claimDailyCheckin(credential)
|
|
213
|
+
checkinCache.delete(key)
|
|
214
|
+
creditCache.delete(key)
|
|
215
|
+
return send(res, 200, { claim })
|
|
216
|
+
}
|
|
217
|
+
const nowT = Date.now()
|
|
218
|
+
const force = url.searchParams.get('force') === '1'
|
|
219
|
+
const hit = checkinCache.get(key)
|
|
220
|
+
if (hit !== undefined && !force && nowT - hit.at < 300_000) return send(res, 200, hit.value)
|
|
221
|
+
const status = await client.fetchCheckinStatus(credential)
|
|
222
|
+
checkinCache.set(key, { at: nowT, value: status })
|
|
223
|
+
return send(res, 200, status)
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
if (path === '/v1/models') {
|
|
227
|
+
const region = regionOf(req, url)
|
|
228
|
+
const credential = await credentialOf(region, url.searchParams.get('account'))
|
|
229
|
+
const read = await client.fetchModels(credential)
|
|
230
|
+
const prefix = region === 'global' ? 'global:' : ''
|
|
231
|
+
return send(res, 200, {
|
|
232
|
+
object: 'list',
|
|
233
|
+
region,
|
|
234
|
+
data: read.models.map((m) => ({
|
|
235
|
+
id: prefix + m.id,
|
|
236
|
+
object: 'model',
|
|
237
|
+
created: 0,
|
|
238
|
+
owned_by: 'workbuddy',
|
|
239
|
+
raw: m,
|
|
240
|
+
})),
|
|
241
|
+
})
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
if (path === '/v1/chat/completions' && req.method === 'POST') {
|
|
245
|
+
const raw = await readBody(req)
|
|
246
|
+
const body = JSON.parse(raw)
|
|
247
|
+
const region = regionOf(req, url, body.model)
|
|
248
|
+
const credential = await credentialOf(region, url.searchParams.get('account'))
|
|
249
|
+
body.model = modelIdOf(body.model)
|
|
250
|
+
// 上游只支持流式:无论客户端要 stream 与否,都按流式请求。
|
|
251
|
+
const wantStream = body.stream !== false
|
|
252
|
+
body.stream = true
|
|
253
|
+
const result = await client.chatStream(credential, JSON.stringify(body))
|
|
254
|
+
if (!result.ok) {
|
|
255
|
+
return send(res, result.status || 502, {
|
|
256
|
+
error: { code: result.kind, message: result.message, detail: result.detail },
|
|
257
|
+
})
|
|
258
|
+
}
|
|
259
|
+
if (wantStream) {
|
|
260
|
+
res.writeHead(200, {
|
|
261
|
+
'Content-Type': result.response.headers.get('content-type') || 'text/event-stream; charset=utf-8',
|
|
262
|
+
'Cache-Control': 'no-cache', Connection: 'keep-alive', 'X-Accel-Buffering': 'no',
|
|
263
|
+
})
|
|
264
|
+
// 上游回的 model 是真实 id(如 hy4-flash),和请求的别名(hy4flash)不同。
|
|
265
|
+
// 有些客户端校验两者一致,这里把每个 chunk 的 model 改回请求值。
|
|
266
|
+
const reader = result.response.body.getReader()
|
|
267
|
+
const requestedModel = body.model
|
|
268
|
+
let carry = ''
|
|
269
|
+
for (;;) {
|
|
270
|
+
const { done, value } = await reader.read()
|
|
271
|
+
if (done) break
|
|
272
|
+
let text = carry + Buffer.from(value).toString('utf8')
|
|
273
|
+
const lines = text.split('\n')
|
|
274
|
+
carry = lines.pop() ?? ''
|
|
275
|
+
const fixed = lines.map((line) => {
|
|
276
|
+
if (!line.startsWith('data:') || line.includes('[DONE]')) return line
|
|
277
|
+
try {
|
|
278
|
+
const j = JSON.parse(line.slice(5).trim())
|
|
279
|
+
if (j.model !== undefined) j.model = requestedModel
|
|
280
|
+
return 'data: ' + JSON.stringify(j)
|
|
281
|
+
} catch { return line }
|
|
282
|
+
})
|
|
283
|
+
if (fixed.length) res.write(fixed.join('\n') + '\n')
|
|
284
|
+
}
|
|
285
|
+
if (carry.trim()) res.write(carry + '\n')
|
|
286
|
+
res.end()
|
|
287
|
+
return
|
|
288
|
+
}
|
|
289
|
+
// 非流式:把 SSE 聚合成一条标准 OpenAI 响应
|
|
290
|
+
const text = await result.response.text()
|
|
291
|
+
const out = { id: 'chatcmpl-' + randomBytes(8).toString('hex'), object: 'chat.completion', created: Math.floor(Date.now()/1000), model: body.model, choices: [{ index: 0, message: { role: 'assistant', content: '' }, finish_reason: 'stop' }], usage: undefined }
|
|
292
|
+
let content = ''
|
|
293
|
+
for (const line of text.split(/\r?\n/)) {
|
|
294
|
+
if (!line.startsWith('data:')) continue
|
|
295
|
+
const data = line.slice(5).trim()
|
|
296
|
+
if (data === '[DONE]') continue
|
|
297
|
+
try {
|
|
298
|
+
const j = JSON.parse(data)
|
|
299
|
+
const delta = j.choices?.[0]?.delta?.content
|
|
300
|
+
if (typeof delta === 'string') content += delta
|
|
301
|
+
if (j.usage) out.usage = j.usage
|
|
302
|
+
} catch {}
|
|
303
|
+
}
|
|
304
|
+
out.choices[0].message.content = content
|
|
305
|
+
return send(res, 200, out)
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
return fail(res, 404, 'not_found', `no such route: ${req.method} ${path}`)
|
|
309
|
+
} catch (error) {
|
|
310
|
+
const message = String((error && error.message) || error)
|
|
311
|
+
if (/no signed-in WorkBuddy account/i.test(message)) {
|
|
312
|
+
return fail(res, 409, 'not_logged_in', message)
|
|
313
|
+
}
|
|
314
|
+
if (/encrypted/i.test(message)) return fail(res, 409, 'credential_encrypted', message)
|
|
315
|
+
const status = error && error.status ? error.status : 500
|
|
316
|
+
return fail(res, status, 'bridge_error', message)
|
|
317
|
+
}
|
|
318
|
+
})
|
|
319
|
+
|
|
320
|
+
server.listen(PORT, HOST, () => {
|
|
321
|
+
console.log(`[bridge] workbuddy ${WORKBUDDY_CONNECT_VERSION} 监听 http://${HOST}:${PORT}`)
|
|
322
|
+
console.log(`[bridge] token: ${TOKEN}`)
|
|
323
|
+
})
|
package/bridge/oauth.mjs
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// 自包含的 WorkBuddy 扫码登录:直接跟上游 /v2/plugin/auth/* 对话,拿到的凭据
|
|
2
|
+
// 交给 vendor 的 WorkBuddyCredentialStore 落库。不依赖宿主插件、不依赖 dsh web 的
|
|
3
|
+
// cookie/token —— 把本目录整个拷走也能登录。
|
|
4
|
+
import { randomUUID } from 'node:crypto'
|
|
5
|
+
|
|
6
|
+
const API_PREFIX = '/v2/plugin'
|
|
7
|
+
const BASE = { cn: 'https://www.codebuddy.cn', global: 'https://www.workbuddy.ai' }
|
|
8
|
+
|
|
9
|
+
const sessions = new Map()
|
|
10
|
+
|
|
11
|
+
function firstString(source, keys) {
|
|
12
|
+
for (const key of keys) {
|
|
13
|
+
const value = source[key]
|
|
14
|
+
if (typeof value === 'string' && value.trim() !== '') return value.trim()
|
|
15
|
+
if (typeof value === 'number' && Number.isFinite(value)) return String(value)
|
|
16
|
+
}
|
|
17
|
+
return ''
|
|
18
|
+
}
|
|
19
|
+
function optionalString(source, keys) {
|
|
20
|
+
const value = firstString(source, keys)
|
|
21
|
+
return value === '' ? undefined : value
|
|
22
|
+
}
|
|
23
|
+
function envelopeData(doc) {
|
|
24
|
+
const data = doc?.data
|
|
25
|
+
return typeof data === 'object' && data !== null && !Array.isArray(data) ? data : {}
|
|
26
|
+
}
|
|
27
|
+
async function readJson(response) {
|
|
28
|
+
try {
|
|
29
|
+
const parsed = JSON.parse(await response.text())
|
|
30
|
+
return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? parsed : undefined
|
|
31
|
+
} catch {
|
|
32
|
+
return undefined
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function expiryMs(source, absoluteKeys, ttlKeys) {
|
|
36
|
+
for (const key of absoluteKeys) {
|
|
37
|
+
const value = source[key]
|
|
38
|
+
if (typeof value === 'number' && value > 0) return value > 0xe8d4a51000 ? value : value * 1000
|
|
39
|
+
if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) {
|
|
40
|
+
const n = Number(value)
|
|
41
|
+
return n > 0xe8d4a51000 ? n : n * 1000
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
for (const key of ttlKeys) {
|
|
45
|
+
const value = source[key]
|
|
46
|
+
if (typeof value === 'number' && value > 0) return Date.now() + value * 1000
|
|
47
|
+
}
|
|
48
|
+
return undefined
|
|
49
|
+
}
|
|
50
|
+
function jwtIdentityOf(token) {
|
|
51
|
+
const empty = { sub: '', nickname: '', uin: '', preferredUsername: '' }
|
|
52
|
+
if (typeof token !== 'string') return empty
|
|
53
|
+
const parts = token.split('.')
|
|
54
|
+
if (parts.length < 2) return empty
|
|
55
|
+
try {
|
|
56
|
+
const payload = JSON.parse(Buffer.from(parts[1] ?? '', 'base64url').toString('utf8'))
|
|
57
|
+
if (typeof payload !== 'object' || payload === null) return empty
|
|
58
|
+
return {
|
|
59
|
+
sub: firstString(payload, ['sub', 'Sub']),
|
|
60
|
+
nickname: firstString(payload, ['nickname', 'NickName']),
|
|
61
|
+
uin: firstString(payload, ['uin', 'Uin']),
|
|
62
|
+
preferredUsername: firstString(payload, ['preferred_username', 'preferredUsername', 'PreferredUsername']),
|
|
63
|
+
}
|
|
64
|
+
} catch {
|
|
65
|
+
return empty
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function hasIdentity(profile) {
|
|
69
|
+
return firstString(profile, ['uid', 'Uid', 'userId', 'UserID']) !== ''
|
|
70
|
+
}
|
|
71
|
+
async function collectAccount(base, accessToken, tokenData) {
|
|
72
|
+
const headers = { Authorization: `Bearer ${accessToken}`, Accept: 'application/json' }
|
|
73
|
+
const domain = firstString(tokenData, ['domain', 'Domain'])
|
|
74
|
+
if (domain !== '') headers['X-Domain'] = domain
|
|
75
|
+
let profile = {}
|
|
76
|
+
for (const path of [`${API_PREFIX}/account`, `${API_PREFIX}/login/account`]) {
|
|
77
|
+
try {
|
|
78
|
+
const doc = await readJson(await fetch(`${base}${path}`, { method: 'GET', headers, signal: AbortSignal.timeout(30_000) }))
|
|
79
|
+
if (doc === undefined) continue
|
|
80
|
+
const candidate = envelopeData(doc)
|
|
81
|
+
if (!hasIdentity(candidate)) continue
|
|
82
|
+
profile = candidate
|
|
83
|
+
break
|
|
84
|
+
} catch {}
|
|
85
|
+
}
|
|
86
|
+
const jwt = jwtIdentityOf(accessToken)
|
|
87
|
+
const uid = firstString(profile, ['uid', 'Uid', 'userId', 'UserID']) || jwt.sub
|
|
88
|
+
if (uid === '') throw new Error('无法识别这个账号:上游没有返回账号资料,登录令牌里也没有可用的身份信息。')
|
|
89
|
+
const nickname = optionalString(profile, ['nickname', 'NickName', 'ScreenName']) ?? optionalString(jwt, ['nickname']) ?? optionalString(jwt, ['preferredUsername'])
|
|
90
|
+
const uin = optionalString(profile, ['uin', 'Uin']) ?? optionalString(jwt, ['uin'])
|
|
91
|
+
const enterpriseId = optionalString(profile, ['enterpriseId', 'EnterpriseId'])
|
|
92
|
+
const refreshExpiresAtMs = expiryMs(tokenData, ['refreshExpiresAt', 'refresh_expires_at'], ['refreshExpiresIn', 'refresh_expires_in'])
|
|
93
|
+
return {
|
|
94
|
+
accessToken,
|
|
95
|
+
refreshToken: firstString(tokenData, ['refreshToken', 'refresh_token', 'RefreshToken']),
|
|
96
|
+
expiresAtMs: expiryMs(tokenData, ['expiresAt', 'expires_at'], ['expiresIn', 'expires_in']) ?? 0,
|
|
97
|
+
...(refreshExpiresAtMs === undefined ? {} : { refreshExpiresAtMs }),
|
|
98
|
+
domain: domain !== '' ? domain : firstString(profile, ['domain', 'Domain']),
|
|
99
|
+
uid,
|
|
100
|
+
...(nickname === undefined ? {} : { nickname }),
|
|
101
|
+
...(uin === undefined ? {} : { uin }),
|
|
102
|
+
...(enterpriseId === undefined ? {} : { enterpriseId }),
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 第一步:向要登录的区要一个 state,返回要打开的扫码地址。 */
|
|
107
|
+
export async function start(region) {
|
|
108
|
+
const base = BASE[region] ?? BASE.cn
|
|
109
|
+
let response
|
|
110
|
+
try {
|
|
111
|
+
response = await fetch(`${base}${API_PREFIX}/auth/state?platform=workbuddy`, {
|
|
112
|
+
method: 'POST',
|
|
113
|
+
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
114
|
+
body: '{}',
|
|
115
|
+
signal: AbortSignal.timeout(30_000),
|
|
116
|
+
})
|
|
117
|
+
} catch (error) {
|
|
118
|
+
return { error: `连不上 ${base}:${String(error?.message ?? error)}` }
|
|
119
|
+
}
|
|
120
|
+
const doc = await readJson(response)
|
|
121
|
+
if (doc === undefined) return { error: `登录服务返回的不是 JSON(http ${response.status})` }
|
|
122
|
+
const data = envelopeData(doc)
|
|
123
|
+
const state = firstString(data, ['state', 'State'])
|
|
124
|
+
if (state === '') return { error: `登录服务没给 state(http ${response.status})` }
|
|
125
|
+
const authUrl = firstString(data, ['authUrl', 'auth_url', 'url', 'Url']) || `${base}/login?state=${encodeURIComponent(state)}`
|
|
126
|
+
const loginId = `wbo_${randomUUID().replaceAll('-', '')}`
|
|
127
|
+
sessions.set(loginId, { region, base, state, expiresAtMs: Date.now() + 600_000, done: false })
|
|
128
|
+
return { loginId, verificationUri: authUrl, expiresIn: 600 }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** 第二步:用户扫完码后轮询;成功后用 store.addOAuthAccount 落库。 */
|
|
132
|
+
export async function poll(region, loginId, store) {
|
|
133
|
+
const session = sessions.get(loginId)
|
|
134
|
+
if (session === undefined) return { done: true, error: '登录会话不存在,请重新发起' }
|
|
135
|
+
if (session.region !== region) return { done: true, error: '登录会话属于另一个区' }
|
|
136
|
+
if (session.done) return { done: true, accountId: session.result }
|
|
137
|
+
if (Date.now() > session.expiresAtMs) {
|
|
138
|
+
sessions.delete(loginId)
|
|
139
|
+
return { done: true, error: '登录超时,请重新发起' }
|
|
140
|
+
}
|
|
141
|
+
let response
|
|
142
|
+
try {
|
|
143
|
+
response = await fetch(`${session.base}${API_PREFIX}/auth/token?state=${encodeURIComponent(session.state)}`, {
|
|
144
|
+
method: 'GET',
|
|
145
|
+
headers: { Accept: 'application/json' },
|
|
146
|
+
signal: AbortSignal.timeout(30_000),
|
|
147
|
+
})
|
|
148
|
+
} catch {
|
|
149
|
+
return { done: false }
|
|
150
|
+
}
|
|
151
|
+
const doc = await readJson(response)
|
|
152
|
+
if (doc === undefined) return { done: false }
|
|
153
|
+
const code = typeof doc.code === 'number' ? doc.code : -1
|
|
154
|
+
if (code !== 0 && code !== 200) return { done: false }
|
|
155
|
+
const data = envelopeData(doc)
|
|
156
|
+
const accessToken = firstString(data, ['accessToken', 'access_token', 'AccessToken'])
|
|
157
|
+
if (accessToken === '') return { done: false }
|
|
158
|
+
session.done = true
|
|
159
|
+
try {
|
|
160
|
+
const account = await collectAccount(session.base, accessToken, data)
|
|
161
|
+
const accountId = await store.addOAuthAccount(account)
|
|
162
|
+
sessions.delete(loginId)
|
|
163
|
+
session.result = accountId
|
|
164
|
+
return { done: true, accountId }
|
|
165
|
+
} catch (error) {
|
|
166
|
+
sessions.delete(loginId)
|
|
167
|
+
return { done: true, error: String(error?.message ?? error) }
|
|
168
|
+
}
|
|
169
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// 建一个 node_modules 符号链接农场,让 dsh-connect-workbuddy 的 peer 依赖能以
|
|
2
|
+
// 裸包名解析到(ESM 从包的“真实路径”往上找,所以必须配合 --preserve-symlinks)。
|
|
3
|
+
import { readdir, mkdir, rm, symlink, stat } from 'node:fs/promises'
|
|
4
|
+
import { existsSync } from 'node:fs'
|
|
5
|
+
import { join, dirname, basename } from 'node:path'
|
|
6
|
+
import { fileURLToPath } from 'node:url'
|
|
7
|
+
import { homedir } from 'node:os'
|
|
8
|
+
|
|
9
|
+
const here = dirname(fileURLToPath(import.meta.url))
|
|
10
|
+
const root = dirname(here)
|
|
11
|
+
const nm = join(root, 'node_modules')
|
|
12
|
+
|
|
13
|
+
const DSH_HOME = process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
14
|
+
const HOST_NM = process.env.DSH_HOST_MODULES || '/opt/dsh/node_modules'
|
|
15
|
+
const PROFILES = join(DSH_HOME, 'profiles')
|
|
16
|
+
|
|
17
|
+
async function linkAll(fromDir, intoDir) {
|
|
18
|
+
let names = []
|
|
19
|
+
try {
|
|
20
|
+
names = await readdir(fromDir)
|
|
21
|
+
} catch {
|
|
22
|
+
return
|
|
23
|
+
}
|
|
24
|
+
for (const name of names) {
|
|
25
|
+
const target = join(fromDir, name)
|
|
26
|
+
const dest = join(intoDir, name)
|
|
27
|
+
try {
|
|
28
|
+
const st = await stat(target)
|
|
29
|
+
if (!st.isDirectory()) continue
|
|
30
|
+
} catch {
|
|
31
|
+
continue
|
|
32
|
+
}
|
|
33
|
+
if (name.startsWith('@')) {
|
|
34
|
+
await mkdir(dest, { recursive: true })
|
|
35
|
+
await linkAll(target, dest)
|
|
36
|
+
continue
|
|
37
|
+
}
|
|
38
|
+
if (existsSync(dest)) continue
|
|
39
|
+
await symlink(target, dest, 'dir')
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
await rm(nm, { recursive: true, force: true })
|
|
44
|
+
await mkdir(nm, { recursive: true })
|
|
45
|
+
|
|
46
|
+
// 0) vendor 自带的核心代码:优先用它,彻底不依赖 profile 里装的 dsh-connect-workbuddy
|
|
47
|
+
const vendor = join(root, 'vendor', 'dsh-connect-workbuddy')
|
|
48
|
+
if (existsSync(vendor)) await symlink(vendor, join(nm, 'dsh-connect-workbuddy'), 'dir')
|
|
49
|
+
|
|
50
|
+
// 1) 宿主自带依赖(@earendil-works/pi-ai、@deepseek-ai/* 等)
|
|
51
|
+
await linkAll(HOST_NM, nm)
|
|
52
|
+
|
|
53
|
+
// 2) 各 profile 装的插件与 dsh-* 包
|
|
54
|
+
let profiles = []
|
|
55
|
+
try {
|
|
56
|
+
profiles = await readdir(PROFILES)
|
|
57
|
+
} catch {}
|
|
58
|
+
for (const p of profiles) await linkAll(join(PROFILES, p, 'node_modules'), nm)
|
|
59
|
+
|
|
60
|
+
const found = existsSync(join(nm, 'dsh-connect-workbuddy'))
|
|
61
|
+
console.log(existsSync(vendor) ? 'farm ok(自带 vendor): ' + nm : (found ? 'farm ok(profile 副本): ' + nm : 'farm 缺 dsh-connect-workbuddy'))
|
|
62
|
+
process.exitCode = found ? 0 : 1
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 LaoDing
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|