dsh-plugin-doubao 0.0.0-stage → 0.2.0
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/LICENSE +21 -0
- package/README.md +457 -2
- package/bin/login.bat +27 -0
- package/bin/login.js +112 -0
- package/cordis.patch.yml +13 -0
- package/lib/adapter.js +851 -0
- package/lib/bridge.js +608 -0
- package/lib/client.js +171 -0
- package/lib/credits.js +143 -0
- package/lib/doubao.js +746 -0
- package/lib/identity.js +291 -0
- package/lib/index.js +290 -0
- package/lib/login.js +357 -0
- package/lib/rates.js +117 -0
- package/lib/risk-memory.js +84 -0
- package/package.json +54 -4
package/lib/identity.js
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Recover the machine's Doubao device identity from the installed client.
|
|
3
|
+
*
|
|
4
|
+
* Why this has to exist: the chat endpoint keys its risk engine on a device
|
|
5
|
+
* fingerprint. A request with no identity gets `710012001 login invalid`; a
|
|
6
|
+
* freshly minted device_id with a perfectly valid session gets `710022004`,
|
|
7
|
+
* because the account has never seen that device before. Only the device id the
|
|
8
|
+
* client itself registered is accepted, and there is no API that hands it out —
|
|
9
|
+
* the client keeps it in Local Storage.
|
|
10
|
+
*
|
|
11
|
+
* Chromium stores Local Storage in a leveldb. Its Cookies SQLite is exclusively
|
|
12
|
+
* locked while the client runs (EBUSY, even for a read-only handle, and SQLite's
|
|
13
|
+
* `immutable=1` cannot open it either), but the leveldb `.log`/`.ldb` files are
|
|
14
|
+
* ordinary append-only files that stay readable on a live client. So this module
|
|
15
|
+
* can work while the user has Doubao open — it never starts or stops it.
|
|
16
|
+
*
|
|
17
|
+
* Two sources are consulted, in this order:
|
|
18
|
+
*
|
|
19
|
+
* 1. `Local State` — a plain JSON file next to the profiles, carrying
|
|
20
|
+
* `aha.device.device_id`. Always present and never locked.
|
|
21
|
+
* 2. the leveldb files, for `client_device_info`.
|
|
22
|
+
*
|
|
23
|
+
* The order matters. leveldb blocks are written with prefix compression, so once
|
|
24
|
+
* the client compacts (its `.log` folds into an `.ldb`) the key
|
|
25
|
+
* `client_device_info` is no longer a contiguous byte run and a scan finds
|
|
26
|
+
* nothing — which is exactly what happened here after a restart. `Local State`
|
|
27
|
+
* survived it, so it is the primary source and leveldb is the fallback for the
|
|
28
|
+
* extra fields.
|
|
29
|
+
*/
|
|
30
|
+
import { readdirSync, readFileSync, statSync } from 'node:fs'
|
|
31
|
+
import { join, posix } from 'node:path'
|
|
32
|
+
import { homedir } from 'node:os'
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Where the client keeps its data. The Electron shell is installed in a few
|
|
36
|
+
* different places depending on how it was installed, so several profiles are
|
|
37
|
+
* probed in order.
|
|
38
|
+
*/
|
|
39
|
+
export function candidateUserDataDirs(env = process.env, platform = process.platform) {
|
|
40
|
+
const home = homedir()
|
|
41
|
+
if (platform === 'darwin') {
|
|
42
|
+
// Electron/Chromium apps on macOS put their user data under Application
|
|
43
|
+
// Support. Doubao uses the bundle name; older builds used lowercase.
|
|
44
|
+
const support = posix.join(home, 'Library', 'Application Support')
|
|
45
|
+
return [
|
|
46
|
+
posix.join(support, 'Doubao', 'User Data'),
|
|
47
|
+
posix.join(support, 'doubao', 'User Data'),
|
|
48
|
+
posix.join(support, 'Doubao'),
|
|
49
|
+
posix.join(support, 'doubao'),
|
|
50
|
+
]
|
|
51
|
+
}
|
|
52
|
+
if (platform === 'linux') {
|
|
53
|
+
// XDG_CONFIG_HOME is the standard override; ~/.config is the default.
|
|
54
|
+
const config = env.XDG_CONFIG_HOME ?? posix.join(home, '.config')
|
|
55
|
+
return [
|
|
56
|
+
posix.join(config, 'doubao'),
|
|
57
|
+
posix.join(config, 'Doubao'),
|
|
58
|
+
posix.join(home, '.doubao'),
|
|
59
|
+
posix.join(home, '.config', 'doubao', 'User Data'),
|
|
60
|
+
]
|
|
61
|
+
}
|
|
62
|
+
const local = env.LOCALAPPDATA ?? join(home, 'AppData', 'Local')
|
|
63
|
+
const roaming = env.APPDATA ?? join(home, 'AppData', 'Roaming')
|
|
64
|
+
return [
|
|
65
|
+
join(local, 'Doubao', 'User Data'),
|
|
66
|
+
join(roaming, 'Doubao', 'User Data'),
|
|
67
|
+
join(local, 'Doubao'),
|
|
68
|
+
join(roaming, 'Doubao'),
|
|
69
|
+
]
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function localStorageDirs(env = process.env, profiles = ['Default'], platform = process.platform) {
|
|
73
|
+
const out = []
|
|
74
|
+
for (const root of candidateUserDataDirs(env, platform)) {
|
|
75
|
+
for (const profile of profiles) out.push(join(root, profile, 'Local Storage', 'leveldb'))
|
|
76
|
+
}
|
|
77
|
+
return out
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The identity the client wrote to `Local State`.
|
|
82
|
+
*
|
|
83
|
+
* `aha.device` holds the device id in plain JSON, alongside the install id and
|
|
84
|
+
* the machine's own identifiers. Chromium rewrites this file in place rather
|
|
85
|
+
* than through a compaction log, so the value stays readable across restarts and
|
|
86
|
+
* while the client runs.
|
|
87
|
+
*/
|
|
88
|
+
export function readLocalStateIdentity(userDataDir) {
|
|
89
|
+
const path = join(userDataDir, 'Local State')
|
|
90
|
+
let raw
|
|
91
|
+
try {
|
|
92
|
+
raw = readFileSync(path, 'utf8')
|
|
93
|
+
} catch {
|
|
94
|
+
return undefined
|
|
95
|
+
}
|
|
96
|
+
let parsed
|
|
97
|
+
try {
|
|
98
|
+
parsed = JSON.parse(raw.replace(/^\uFEFF/, ''))
|
|
99
|
+
} catch {
|
|
100
|
+
return undefined
|
|
101
|
+
}
|
|
102
|
+
const device = parsed?.aha?.device
|
|
103
|
+
const deviceId = device?.device_id
|
|
104
|
+
if (typeof deviceId !== 'string' || deviceId.length === 0) return undefined
|
|
105
|
+
return {
|
|
106
|
+
deviceId,
|
|
107
|
+
deviceModel: undefined,
|
|
108
|
+
source: path,
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Read the first JSON object starting at `at`, respecting nesting and strings.
|
|
114
|
+
*
|
|
115
|
+
* A fixed-size slice does not work: leveldb appends records back to back, so the
|
|
116
|
+
* bytes after the object we want belong to unrelated keys, and the object itself
|
|
117
|
+
* may contain braces inside string values.
|
|
118
|
+
*/
|
|
119
|
+
function jsonAt(buf, at) {
|
|
120
|
+
const open = buf.indexOf(0x7b, at) // '{'
|
|
121
|
+
if (open < 0) return undefined
|
|
122
|
+
let depth = 0
|
|
123
|
+
let inString = false
|
|
124
|
+
let escaped = false
|
|
125
|
+
const limit = Math.min(buf.length, open + 200_000)
|
|
126
|
+
for (let i = open; i < limit; i += 1) {
|
|
127
|
+
const c = buf[i]
|
|
128
|
+
if (inString) {
|
|
129
|
+
if (escaped) escaped = false
|
|
130
|
+
else if (c === 0x5c) escaped = true
|
|
131
|
+
else if (c === 0x22) inString = false
|
|
132
|
+
continue
|
|
133
|
+
}
|
|
134
|
+
if (c === 0x22) inString = true
|
|
135
|
+
else if (c === 0x7b) depth += 1
|
|
136
|
+
else if (c === 0x7d) {
|
|
137
|
+
depth -= 1
|
|
138
|
+
if (depth === 0) {
|
|
139
|
+
try {
|
|
140
|
+
return JSON.parse(buf.toString('utf8', open, i + 1))
|
|
141
|
+
} catch {
|
|
142
|
+
return undefined
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return undefined
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function valueAfter(buf, key) {
|
|
151
|
+
const at = buf.indexOf(key, 0, 'latin1')
|
|
152
|
+
if (at < 0) return undefined
|
|
153
|
+
const from = at + key.length
|
|
154
|
+
// leveldb prefixes the payload with a type byte and a length varint, so the
|
|
155
|
+
// quote or brace we want is a few bytes along, not immediately after the key.
|
|
156
|
+
const window = Math.min(buf.length, from + 16)
|
|
157
|
+
for (let i = from; i < window; i += 1) {
|
|
158
|
+
if (buf[i] === 0x7b) return jsonAt(buf, i) // '{'
|
|
159
|
+
if (buf[i] === 0x22) {
|
|
160
|
+
const end = buf.indexOf(0x22, i + 1)
|
|
161
|
+
if (end < 0) return undefined
|
|
162
|
+
return buf.toString('utf8', i + 1, end)
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
// Some values (s_v_web_id) are stored as a bare string with no quotes at all.
|
|
166
|
+
let i = from
|
|
167
|
+
while (i < buf.length && (buf[i] < 0x20 || buf[i] === 0x7f)) i += 1
|
|
168
|
+
let end = i
|
|
169
|
+
while (end < buf.length && buf[end] >= 0x20 && end - i < 128) end += 1
|
|
170
|
+
if (end <= i) return undefined
|
|
171
|
+
const bare = buf.toString('utf8', i, end)
|
|
172
|
+
// Anything starting with a closing brace is the tail of a neighbouring record,
|
|
173
|
+
// not a value for this key — reporting it would make the caller trust junk.
|
|
174
|
+
if (/^[}\]),;]/.test(bare)) return undefined
|
|
175
|
+
return bare
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Newest first, and prefer live `.log` files over compacted `.ldb` ones. */
|
|
179
|
+
function leveldbFiles(dir) {
|
|
180
|
+
let names
|
|
181
|
+
try {
|
|
182
|
+
names = readdirSync(dir).filter((f) => /\.(ldb|log)$/i.test(f))
|
|
183
|
+
} catch {
|
|
184
|
+
return []
|
|
185
|
+
}
|
|
186
|
+
const withStat = []
|
|
187
|
+
for (const name of names) {
|
|
188
|
+
try {
|
|
189
|
+
withStat.push({ name, stat: statSync(join(dir, name)) })
|
|
190
|
+
} catch {
|
|
191
|
+
// a file can vanish between readdir and stat while leveldb compacts
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
withStat.sort((a, b) => {
|
|
195
|
+
const aLog = a.name.endsWith('.log')
|
|
196
|
+
const bLog = b.name.endsWith('.log')
|
|
197
|
+
if (aLog !== bLog) return aLog ? -1 : 1
|
|
198
|
+
return b.stat.mtimeMs - a.stat.mtimeMs
|
|
199
|
+
})
|
|
200
|
+
return withStat
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Scan one profile's leveldb for the identity keys.
|
|
205
|
+
*
|
|
206
|
+
* `client_device_info` carries `deviceId` and the browser build the client
|
|
207
|
+
* reports; `__tea_cache_tokens_582478` carries the `web_id` the web client would
|
|
208
|
+
* use. We do not need the cookies from here — those come from a login.
|
|
209
|
+
*/
|
|
210
|
+
export function scanLocalStorage(dir) {
|
|
211
|
+
const info = {}
|
|
212
|
+
for (const { name } of leveldbFiles(dir)) {
|
|
213
|
+
let buf
|
|
214
|
+
try {
|
|
215
|
+
buf = readFileSync(join(dir, name))
|
|
216
|
+
} catch {
|
|
217
|
+
continue // locked or permission-denied; try the next file
|
|
218
|
+
}
|
|
219
|
+
if (!info.deviceId) {
|
|
220
|
+
const dev = valueAfter(buf, 'client_device_info')
|
|
221
|
+
if (dev && typeof dev === 'object' && dev.deviceId) {
|
|
222
|
+
info.deviceId = String(dev.deviceId)
|
|
223
|
+
if (dev.deviceIdCustom) info.deviceIdCustom = String(dev.deviceIdCustom)
|
|
224
|
+
if (dev.chromiumVersion) info.chromiumVersion = String(dev.chromiumVersion)
|
|
225
|
+
if (dev.clientVersion) info.clientVersion = String(dev.clientVersion)
|
|
226
|
+
if (dev.deviceModel) info.deviceModel = String(dev.deviceModel)
|
|
227
|
+
info.source = join(dir, name)
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
if (!info.webId) {
|
|
231
|
+
const tea = valueAfter(buf, '__tea_cache_tokens_582478')
|
|
232
|
+
if (tea && typeof tea === 'object') {
|
|
233
|
+
const web = tea.web_id ?? tea.webId
|
|
234
|
+
if (web) info.webId = String(web)
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
if (!info.legacyFp) {
|
|
238
|
+
const fp = valueAfter(buf, 's_v_web_id')
|
|
239
|
+
if (typeof fp === 'string' && fp) info.legacyFp = fp
|
|
240
|
+
}
|
|
241
|
+
if (info.deviceId && info.webId) break
|
|
242
|
+
}
|
|
243
|
+
return info
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Probe every known profile directory and return the first hit. */
|
|
247
|
+
export function findClientIdentity(env = process.env, platform = process.platform) {
|
|
248
|
+
const tried = []
|
|
249
|
+
for (const root of candidateUserDataDirs(env, platform)) {
|
|
250
|
+
const fromState = readLocalStateIdentity(root)
|
|
251
|
+
if (fromState) {
|
|
252
|
+
// Local State only carries the id; the leveldb still has the browser build
|
|
253
|
+
// the client reports, which the request has to echo back.
|
|
254
|
+
const extra = scanLocalStorage(join(root, 'Default', 'Local Storage', 'leveldb'))
|
|
255
|
+
const info = { ...extra, ...fromState }
|
|
256
|
+
if (!info.chromiumVersion) info.chromiumVersion = extra.chromiumVersion
|
|
257
|
+
if (!info.clientVersion) info.clientVersion = extra.clientVersion
|
|
258
|
+
return { found: true, info, dir: root, tried }
|
|
259
|
+
}
|
|
260
|
+
tried.push(join(root, 'Local State'))
|
|
261
|
+
}
|
|
262
|
+
for (const dir of localStorageDirs(env, ['Default'], platform)) {
|
|
263
|
+
const info = scanLocalStorage(dir)
|
|
264
|
+
if (info.deviceId) return { found: true, info, dir, tried }
|
|
265
|
+
tried.push(dir)
|
|
266
|
+
}
|
|
267
|
+
return { found: false, info: {}, tried }
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* The three query parameters the risk engine actually checks. `fp` is not the
|
|
272
|
+
* `s_v_web_id` cookie value — it is literally `verify_` + the device id, which is
|
|
273
|
+
* what the desktop client sends.
|
|
274
|
+
*/
|
|
275
|
+
export function toIdentity(info) {
|
|
276
|
+
const deviceId = info?.deviceId ?? info?.deviceIdCustom
|
|
277
|
+
if (!deviceId) return undefined
|
|
278
|
+
return {
|
|
279
|
+
deviceId,
|
|
280
|
+
fp: `verify_${deviceId}`,
|
|
281
|
+
webId: info?.webId ?? deviceId,
|
|
282
|
+
chromiumVersion: info?.chromiumVersion ?? '147.0.7727.149',
|
|
283
|
+
clientVersion: info?.clientVersion ?? '2.35.12',
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** Where to cache minted credentials so they survive a restart. */
|
|
288
|
+
export function credentialPath(env = process.env) {
|
|
289
|
+
const base = env.DSH_HOME ?? join(homedir(), '.dsh')
|
|
290
|
+
return join(base, 'doubao-local', 'credentials.json')
|
|
291
|
+
}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Doubao provider for DSH.
|
|
3
|
+
*
|
|
4
|
+
* The plugin talks to doubao.com with the account's own session and registers
|
|
5
|
+
* itself as an LLM provider.
|
|
6
|
+
*
|
|
7
|
+
* Two credentials are required, and they come from different places:
|
|
8
|
+
* - the session cookie, from a QR scan with the Douyin app (see lib/login.js)
|
|
9
|
+
* - the device id, from the installed client's leveldb (see lib/identity.js)
|
|
10
|
+
* A freshly minted device id is rejected with 710022004, which is why the second
|
|
11
|
+
* half cannot be fabricated.
|
|
12
|
+
*
|
|
13
|
+
* There is also a third thing, discovered the hard way: the service wants an
|
|
14
|
+
* `a_bogus`/`msToken` pair that only the client can mint. While the account is
|
|
15
|
+
* in good standing an unsigned request goes through anyway, so every turn starts
|
|
16
|
+
* with a plain request and the client is left alone. Once the semantic risk model
|
|
17
|
+
* flags the account, unsigned requests are refused with 710022004; only then does
|
|
18
|
+
* the plugin remember the flag (lib/risk-memory.js, surviving restarts) and route
|
|
19
|
+
* turns through the client's signed page over the debugger bridge (lib/bridge.js),
|
|
20
|
+
* starting the client if needed. The flag expires, so a recovered account drifts
|
|
21
|
+
* back to direct requests without launching anything again. `allowBridge: false`
|
|
22
|
+
* keeps a turn direct-only for good.
|
|
23
|
+
*/
|
|
24
|
+
import { join } from 'node:path'
|
|
25
|
+
import { homedir } from 'node:os'
|
|
26
|
+
import { createAdapter, DEFAULT_PROVIDER } from './adapter.js'
|
|
27
|
+
import { readCredentials, runLoginServer, credentialsPath } from './login.js'
|
|
28
|
+
import { findClientIdentity, toIdentity } from './identity.js'
|
|
29
|
+
import { Pacer } from './doubao.js'
|
|
30
|
+
import { bridgeAvailable } from './bridge.js'
|
|
31
|
+
import { createRiskMemory } from './risk-memory.js'
|
|
32
|
+
import { fetchCredits } from './credits.js'
|
|
33
|
+
|
|
34
|
+
export const name = 'doubao'
|
|
35
|
+
export const inject = ['llm']
|
|
36
|
+
|
|
37
|
+
/** Where the composer's readout asks for the balance. */
|
|
38
|
+
export const CREDITS_PATH = '/plugins/dsh-plugin-doubao/credits'
|
|
39
|
+
|
|
40
|
+
const DEFAULTS = {
|
|
41
|
+
providerId: DEFAULT_PROVIDER,
|
|
42
|
+
displayName: 'Doubao',
|
|
43
|
+
// The pacer exists to keep bursts off the account, and it holds its lock for
|
|
44
|
+
// the whole turn (request *and* stream), so this number is also the floor
|
|
45
|
+
// between two consecutive questions. Measured on the live account: at 6000 a
|
|
46
|
+
// follow-up turn started 2.6s later than at 0 with no risk-control difference,
|
|
47
|
+
// because a turn already takes ~3.5s to first token on its own. 1500 keeps a
|
|
48
|
+
// gap without making every message wait for the previous one to age out; the
|
|
49
|
+
// 710022004 cooldown below is the real protection and stays intact.
|
|
50
|
+
minIntervalMs: 1500,
|
|
51
|
+
credentialsPath: join(process.env.DSH_HOME ?? join(homedir(), '.dsh'), 'doubao-local', 'credentials.json'),
|
|
52
|
+
loginPort: 8899,
|
|
53
|
+
// The client's DevTools port. Only used when the account is under risk control
|
|
54
|
+
// and needs the signed bridge (see lib/bridge.js).
|
|
55
|
+
bridgePort: 9222,
|
|
56
|
+
// Direct-first by default: a clean account never needs the client. Set false
|
|
57
|
+
// to forbid launching/probing the client entirely (direct requests only).
|
|
58
|
+
allowBridge: true,
|
|
59
|
+
// How long a 710022004 flag keeps routing through the bridge, in ms.
|
|
60
|
+
riskTtlMs: 30 * 60 * 1000,
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function resolveConfig(config = {}) {
|
|
64
|
+
return {
|
|
65
|
+
providerId: config.providerId ?? DEFAULTS.providerId,
|
|
66
|
+
displayName: config.displayName ?? DEFAULTS.displayName,
|
|
67
|
+
minIntervalMs: config.minIntervalMs ?? DEFAULTS.minIntervalMs,
|
|
68
|
+
credentialsPath: config.credentialsPath ?? process.env.DOUBAO_CREDENTIALS ?? DEFAULTS.credentialsPath,
|
|
69
|
+
loginPort: config.loginPort ?? DEFAULTS.loginPort,
|
|
70
|
+
bridgePort: config.bridgePort ?? DEFAULTS.bridgePort,
|
|
71
|
+
allowBridge: config.allowBridge ?? DEFAULTS.allowBridge,
|
|
72
|
+
riskTtlMs: config.riskTtlMs ?? DEFAULTS.riskTtlMs,
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Load what a chat call needs, preferring what login stored.
|
|
78
|
+
*
|
|
79
|
+
* The device id is re-read from the client on every call rather than trusted from
|
|
80
|
+
* the saved file: a client reinstall changes it, and a stale id fails as
|
|
81
|
+
* 710022004 — indistinguishable from a rate limit, and much harder to diagnose.
|
|
82
|
+
*/
|
|
83
|
+
export function createCredentialLoader(settings, logger) {
|
|
84
|
+
return async function loadCredentials() {
|
|
85
|
+
const store = { DSH_HOME: process.env.DSH_HOME }
|
|
86
|
+
const saved = readCredentials(store)
|
|
87
|
+
if (!saved) return undefined
|
|
88
|
+
const found = findClientIdentity(store)
|
|
89
|
+
const identity = found.found ? toIdentity(found.info) : saved.identity
|
|
90
|
+
if (found.found && saved.identity?.deviceId && saved.identity.deviceId !== identity.deviceId) {
|
|
91
|
+
logger?.warn?.(
|
|
92
|
+
`doubao: the client's device id (${identity.deviceId}) differs from the stored one ` +
|
|
93
|
+
`(${saved.identity.deviceId}); using the client's, which is the one the account trusts`,
|
|
94
|
+
)
|
|
95
|
+
}
|
|
96
|
+
return { cookies: saved.cookies, identity, account: saved.account }
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Whether a request may read the balance.
|
|
102
|
+
*
|
|
103
|
+
* The route answers with the account's remaining credit, so it is loopback-only
|
|
104
|
+
* in both directions: the `Host` must name this listener (a page that resolves
|
|
105
|
+
* `localhost` to a foreign address cannot ride the browser's trust of it) and a
|
|
106
|
+
* present `Origin` must be local too. An ABSENT `Origin` passes — that is what
|
|
107
|
+
* the plugin's own fetch and a test client look like.
|
|
108
|
+
*/
|
|
109
|
+
function hostIsLocal(host, localAddress) {
|
|
110
|
+
if (typeof host !== 'string' || host.trim() === '') return false
|
|
111
|
+
const bracket = host.startsWith('[') ? host.indexOf(']') : -1
|
|
112
|
+
const bare = (bracket !== -1 ? host.slice(1, bracket) : host.split(':')[0]).trim().toLowerCase()
|
|
113
|
+
if (bare === 'localhost' || bare === '::1' || bare === '127.0.0.1') return true
|
|
114
|
+
if (bare === '0.0.0.0' || bare === '::') return false
|
|
115
|
+
return typeof localAddress === 'string' && bare === localAddress.trim().toLowerCase()
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function originIsLocal(origin, localAddress) {
|
|
119
|
+
if (typeof origin !== 'string' || origin.trim() === '') return true
|
|
120
|
+
try {
|
|
121
|
+
return hostIsLocal(new URL(origin).host, localAddress)
|
|
122
|
+
} catch {
|
|
123
|
+
return false
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function sendJson(res, status, body, extraHeaders = {}) {
|
|
128
|
+
const payload = JSON.stringify(body)
|
|
129
|
+
res.writeHead(status, {
|
|
130
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
131
|
+
'Content-Length': Buffer.byteLength(payload),
|
|
132
|
+
...extraHeaders,
|
|
133
|
+
})
|
|
134
|
+
res.end(payload)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Mount `GET /plugins/dsh-plugin-doubao/credits`.
|
|
139
|
+
*
|
|
140
|
+
* Registered through `ctx.effect` so the route is removed with the fiber — a
|
|
141
|
+
* disposed plugin must not leave a URL answering with a credential it no longer
|
|
142
|
+
* owns.
|
|
143
|
+
*/
|
|
144
|
+
export function registerCreditsRoute(webCtx, read, logger) {
|
|
145
|
+
webCtx.effect(() => {
|
|
146
|
+
const dispose = webCtx.webServer.register({
|
|
147
|
+
kind: 'exact',
|
|
148
|
+
path: CREDITS_PATH,
|
|
149
|
+
handler: async (req, res) => {
|
|
150
|
+
if (req.method !== 'GET') {
|
|
151
|
+
sendJson(res, 405, { error: 'method not allowed' })
|
|
152
|
+
return
|
|
153
|
+
}
|
|
154
|
+
const localAddress = req.socket?.localAddress
|
|
155
|
+
if (!hostIsLocal(req.headers.host, localAddress)) {
|
|
156
|
+
sendJson(res, 403, { error: 'host-not-trusted' })
|
|
157
|
+
return
|
|
158
|
+
}
|
|
159
|
+
if (!originIsLocal(req.headers.origin, localAddress)) {
|
|
160
|
+
sendJson(res, 403, { error: 'origin-not-trusted' })
|
|
161
|
+
return
|
|
162
|
+
}
|
|
163
|
+
try {
|
|
164
|
+
const credits = await read()
|
|
165
|
+
// `credits: null` means "could not read it right now"; the readout
|
|
166
|
+
// draws an em dash. A missing key would read as zero instead.
|
|
167
|
+
sendJson(res, 200, { credits: credits ?? null }, { 'Cache-Control': 'no-store' })
|
|
168
|
+
} catch (error) {
|
|
169
|
+
logger?.warn?.(`doubao: credit readout failed (${error?.message ?? error})`)
|
|
170
|
+
sendJson(res, 200, { credits: null, error: 'read-failed' }, { 'Cache-Control': 'no-store' })
|
|
171
|
+
}
|
|
172
|
+
},
|
|
173
|
+
})
|
|
174
|
+
return () => dispose()
|
|
175
|
+
})
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export async function apply(ctx, config = {}) {
|
|
179
|
+
const settings = resolveConfig(config)
|
|
180
|
+
const logger = ctx.logger ?? console
|
|
181
|
+
|
|
182
|
+
const loadCredentials = createCredentialLoader(settings, logger)
|
|
183
|
+
const pacer = new Pacer({ minIntervalMs: settings.minIntervalMs })
|
|
184
|
+
// Persist risk flags alongside the credentials so a 710022004 stays remembered
|
|
185
|
+
// across DSH restarts: a recovered account's first request after a restart is
|
|
186
|
+
// otherwise a fresh doomed direct probe (and another chance to deepen the flag).
|
|
187
|
+
const riskMemory = createRiskMemory({
|
|
188
|
+
file: join(process.env.DSH_HOME ?? join(homedir(), '.dsh'), 'doubao-local', 'risk-flags.json'),
|
|
189
|
+
ttlMs: settings.riskTtlMs,
|
|
190
|
+
logger,
|
|
191
|
+
})
|
|
192
|
+
const adapter = createAdapter({
|
|
193
|
+
loadCredentials,
|
|
194
|
+
logger,
|
|
195
|
+
pacer,
|
|
196
|
+
providerId: settings.providerId,
|
|
197
|
+
bridgePort: settings.bridgePort,
|
|
198
|
+
riskMemory,
|
|
199
|
+
allowBridge: settings.allowBridge,
|
|
200
|
+
})
|
|
201
|
+
|
|
202
|
+
const existing = ctx.llm?.listProviders?.() ?? []
|
|
203
|
+
if (existing.some((p) => p.id === settings.providerId)) {
|
|
204
|
+
logger.warn?.(
|
|
205
|
+
`doubao: provider "${settings.providerId}" is already registered by another plugin; ` +
|
|
206
|
+
`set providerId in this plugin's config to something else (the adapter would be rejected as DUPLICATE_ADAPTER)`,
|
|
207
|
+
)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// registerAdapter wires its own ctx.effect, so the route disappears with the
|
|
211
|
+
// plugin fiber — no manual disposer, and no chance of leaking a stale provider.
|
|
212
|
+
ctx.llm.registerAdapter([settings.providerId], adapter)
|
|
213
|
+
|
|
214
|
+
// The remaining-credit readout the composer shows. One upstream read per
|
|
215
|
+
// request: the number changes with every turn, so caching it inside the host
|
|
216
|
+
// would only serve a stale balance to the very panel that exists to be current.
|
|
217
|
+
const credits = async () => {
|
|
218
|
+
const credential = await loadCredentials()
|
|
219
|
+
if (!credential) return undefined
|
|
220
|
+
return fetchCredits({ identity: credential.identity, cookies: credential.cookies, logger })
|
|
221
|
+
}
|
|
222
|
+
ctx.provide?.('doubaoCredits', { read: credits })
|
|
223
|
+
|
|
224
|
+
// The composer's readout is a browser component, so the balance has to cross
|
|
225
|
+
// the host's HTTP surface. `ctx.inject` (not a direct `ctx.webServer` touch)
|
|
226
|
+
// keeps the route alive regardless of whether webServer was up at plugin start.
|
|
227
|
+
ctx.inject?.(['webServer'], (webCtx) => registerCreditsRoute(webCtx, credits, logger))
|
|
228
|
+
|
|
229
|
+
const saved = readCredentials({ DSH_HOME: process.env.DSH_HOME })
|
|
230
|
+
if (!saved) {
|
|
231
|
+
logger.log?.(
|
|
232
|
+
`doubao: not signed in yet — run \`node bin/login.js\` from the plugin directory and scan the QR with the Douyin app (see README). ` +
|
|
233
|
+
`Credentials will be written to ${settings.credentialsPath}`,
|
|
234
|
+
)
|
|
235
|
+
} else {
|
|
236
|
+
const found = findClientIdentity({ DSH_HOME: process.env.DSH_HOME })
|
|
237
|
+
logger.log?.(
|
|
238
|
+
found.found
|
|
239
|
+
? `doubao: provider "${settings.providerId}" ready (device ${toIdentity(found.info).deviceId})`
|
|
240
|
+
: `doubao: signed in, but no Doubao desktop client identity was found — calls will be refused until ` +
|
|
241
|
+
`the client is installed and has signed in once`,
|
|
242
|
+
)
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// A tool so the URL is reachable from inside a session, where the user may be
|
|
246
|
+
// running DSH without a terminal in front of them.
|
|
247
|
+
let login
|
|
248
|
+
|
|
249
|
+
async function ensureLoginUrl() {
|
|
250
|
+
if (login) return login.url
|
|
251
|
+
login = await runLoginServer({
|
|
252
|
+
port: settings.loginPort,
|
|
253
|
+
logger,
|
|
254
|
+
onCredentials() {
|
|
255
|
+
logger.log?.('doubao: sign-in complete; the provider is ready to use')
|
|
256
|
+
},
|
|
257
|
+
})
|
|
258
|
+
return login.url
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
ctx.provide?.('doubao', {
|
|
262
|
+
async status() {
|
|
263
|
+
const store = { DSH_HOME: process.env.DSH_HOME }
|
|
264
|
+
const credential = readCredentials(store)
|
|
265
|
+
const found = findClientIdentity(store)
|
|
266
|
+
return {
|
|
267
|
+
providerId: settings.providerId,
|
|
268
|
+
signedIn: Boolean(credential?.cookies),
|
|
269
|
+
credentialsPath: credentialsPath(store),
|
|
270
|
+
account: credential?.account,
|
|
271
|
+
deviceId: found.found ? toIdentity(found.info).deviceId : credential?.identity?.deviceId,
|
|
272
|
+
deviceSource: found.found ? 'client' : credential ? 'stored' : 'none',
|
|
273
|
+
cooldownMs: pacer.coolingDownMs,
|
|
274
|
+
// Whether the client's signer is reachable right now. Worth surfacing:
|
|
275
|
+
// an account held by the signature check fails without it and works with
|
|
276
|
+
// it, and the two states are otherwise indistinguishable from the call
|
|
277
|
+
// site.
|
|
278
|
+
bridge: await bridgeAvailable(settings.bridgePort).catch(() => false),
|
|
279
|
+
bridgePort: settings.bridgePort,
|
|
280
|
+
loginUrl: login?.url,
|
|
281
|
+
}
|
|
282
|
+
},
|
|
283
|
+
async login() {
|
|
284
|
+
return ensureLoginUrl()
|
|
285
|
+
},
|
|
286
|
+
})
|
|
287
|
+
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export { createAdapter, readCredentials }
|