@sixzjd/dsh-workbuddy-connect 0.0.0-stage → 0.3.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/lib/auth.js ADDED
@@ -0,0 +1,540 @@
1
+ /**
2
+ * WorkBuddy credential storage and device-authorization login.
3
+ *
4
+ * Every credential the plugin holds comes from the device-authorization flow
5
+ * below, which is what makes this store's write paths the whole story: a login
6
+ * writes one, and a refresh replaces one. Nothing here reads a file the
7
+ * WorkBuddy desktop app wrote, so the plugin works whether or not that app is
8
+ * installed and wherever it happens to keep its state.
9
+ *
10
+ * Two details of the login are load-bearing:
11
+ *
12
+ * - **One cookie jar per attempt.** The CN gateway tags the `auth/state`
13
+ * response with a routing cookie and correlates the browser's completion with
14
+ * the state it issued, so the state request and every later poll must present
15
+ * the same jar. A shared jar would let two concurrent logins (the CN and
16
+ * international cards) answer for each other.
17
+ * - **A pending login is not an error.** `auth/token` answers HTTP 200 with
18
+ * business code 11217 while the human has not finished, so the envelope's
19
+ * code — not the HTTP status — decides pending from complete.
20
+ *
21
+ * @module dsh-workbuddy-connect/auth
22
+ */
23
+ import { readFileSync, mkdirSync, renameSync, writeFileSync } from 'node:fs'
24
+ import { dirname, join } from 'node:path'
25
+ import { realmOf, regionOf } from './upstream.js'
26
+ import { workbuddyPluginDataDir } from './paths.js'
27
+
28
+ /** The one provenance a stored credential can have: this plugin's own login. */
29
+ export const WORKBUDDY_CREDENTIAL_SOURCE = 'login'
30
+
31
+ /** Basename of the plugin-owned credential file inside the plugin's data directory. */
32
+ export const WORKBUDDY_AUTH_FILENAME = '.workbuddy-auth.json'
33
+
34
+ /** Basename of the international variant's credential file. */
35
+ export const WORKBUDDY_AI_AUTH_FILENAME = '.workbuddy-ai-auth.json'
36
+
37
+ /** The on-disk document version this writer produces. */
38
+ const OWN_FORMAT_VERSION = 1
39
+
40
+ /** Upstream host per realm; both serve the identical plugin login paths. */
41
+ const LOGIN_BASE = {
42
+ cn: 'https://copilot.tencent.com',
43
+ global: 'https://www.workbuddy.ai',
44
+ }
45
+
46
+ /**
47
+ * Origin and Referer per realm. They are not the same host as the API: the CN
48
+ * deployment serves `copilot.tencent.com` for the `codebuddy.cn` site, and the
49
+ * gateway rejects a request whose Origin does not match the realm it targets.
50
+ */
51
+ const LOGIN_ORIGIN = {
52
+ cn: 'https://www.codebuddy.cn',
53
+ global: 'https://www.workbuddy.ai',
54
+ }
55
+
56
+ /** CLI identity the login endpoints expect; unrelated to the chat User-Agent. */
57
+ const LOGIN_USER_AGENT = 'CLI/2.63.2 CodeBuddy/2.63.2'
58
+
59
+ /** Login round trips are interactive; a slow one is dead, not merely slow. */
60
+ const LOGIN_TIMEOUT_MS = 30_000
61
+
62
+ /** Business code `auth/token` returns while the browser half is unfinished. */
63
+ export const LOGIN_PENDING_CODE = 11217
64
+
65
+ /** Path of the state issuer, relative to the realm's base URL. */
66
+ const AUTH_STATE_PATH = '/v2/plugin/auth/state?platform=CLI'
67
+
68
+ function authTokenPath(state) {
69
+ return `/v2/plugin/auth/token?state=${encodeURIComponent(state)}`
70
+ }
71
+
72
+ function loginAccountPath(state) {
73
+ return `/v2/plugin/login/account?state=${encodeURIComponent(state)}`
74
+ }
75
+
76
+ /** Normalized WorkBuddy credential, timestamps in epoch milliseconds. */
77
+ export function isDocument(value) {
78
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
79
+ }
80
+
81
+ function optionalString(value) {
82
+ return typeof value === 'string' && value !== '' ? value : undefined
83
+ }
84
+
85
+ /** Normalize an expiry that may arrive in seconds or milliseconds. */
86
+ function expiryToMs(value) {
87
+ if (!Number.isFinite(value) || value <= 0) return 0
88
+ return value > 1e12 ? value : value * 1000
89
+ }
90
+
91
+ /**
92
+ * Parse a WorkBuddy credential document in either on-disk layout: the nested
93
+ * form `{"auth":{...},"account":{...}}` this plugin writes and the flat form
94
+ * hand-written files use. Returns undefined when the document carries no access
95
+ * token.
96
+ */
97
+ export function parseWorkBuddyAuth(text) {
98
+ let parsed
99
+ try {
100
+ parsed = JSON.parse(text)
101
+ } catch {
102
+ return undefined
103
+ }
104
+ if (!isDocument(parsed)) return undefined
105
+ let auth
106
+ let identity
107
+ if (isDocument(parsed['auth'])) {
108
+ auth = parsed['auth']
109
+ identity = isDocument(parsed['account']) ? parsed['account'] : {}
110
+ } else {
111
+ auth = parsed
112
+ identity = parsed
113
+ }
114
+ const accessToken = typeof auth['accessToken'] === 'string' ? auth['accessToken'] : ''
115
+ if (accessToken === '') return undefined
116
+ const refreshExpiresAtMs = typeof auth['refreshExpiresAt'] === 'number' ? expiryToMs(auth['refreshExpiresAt']) : undefined
117
+ const enterpriseId = optionalString(identity['enterpriseId'])
118
+ const nickname = optionalString(identity['nickname'])
119
+ const realm = optionalString(parsed['region']) ?? optionalString(auth['realm'])
120
+ return {
121
+ accessToken,
122
+ refreshToken: typeof auth['refreshToken'] === 'string' ? auth['refreshToken'] : '',
123
+ expiresAtMs: typeof auth['expiresAt'] === 'number' ? expiryToMs(auth['expiresAt']) : 0,
124
+ ...refreshExpiresAtMs === undefined ? {} : { refreshExpiresAtMs },
125
+ domain: optionalString(auth['domain']) ?? '',
126
+ ...realm === undefined ? {} : { region: realm.trim().toLowerCase() === 'global' ? 'global' : 'cn' },
127
+ uid: optionalString(identity['uid']) ?? '',
128
+ ...enterpriseId === undefined ? {} : { enterpriseId },
129
+ ...nickname === undefined ? {} : { nickname },
130
+ source: WORKBUDDY_CREDENTIAL_SOURCE,
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Serialize the plugin-owned document in the nested cross-tool layout.
136
+ *
137
+ * `expiresAt` is written in **seconds**, matching the published format this
138
+ * one comes from: the two write the same file, so a value in the wrong unit
139
+ * would be read as an expiry decades away rather than rejected. Readers here
140
+ * accept either unit, which is what makes that safe.
141
+ */
142
+ function ownDocument(credential) {
143
+ const region = realmOf(credential)
144
+ return {
145
+ version: OWN_FORMAT_VERSION,
146
+ region,
147
+ auth: {
148
+ accessToken: credential.accessToken,
149
+ refreshToken: credential.refreshToken,
150
+ expiresAt: Math.floor(credential.expiresAtMs / 1000),
151
+ ...credential.refreshExpiresAtMs === undefined ? {} : { refreshExpiresAt: Math.floor(credential.refreshExpiresAtMs / 1000) },
152
+ domain: credential.domain,
153
+ realm: region,
154
+ },
155
+ account: {
156
+ uid: credential.uid,
157
+ ...credential.enterpriseId === undefined ? {} : { enterpriseId: credential.enterpriseId },
158
+ ...credential.nickname === undefined ? {} : { nickname: credential.nickname },
159
+ },
160
+ }
161
+ }
162
+
163
+ /** Write a JSON document atomically: a temporary file renamed over the target. */
164
+ export function writeJsonAtomic(path, value) {
165
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
166
+ const tmp = `${path}.tmp`
167
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 })
168
+ renameSync(tmp, path)
169
+ }
170
+
171
+ /** Read a JSON document, or undefined when it is absent or unreadable. */
172
+ export function readJsonFile(path) {
173
+ try {
174
+ const parsed = JSON.parse(readFileSync(path, 'utf8'))
175
+ if (isDocument(parsed)) return parsed
176
+ } catch {
177
+ // An absent or malformed file is simply "no document".
178
+ }
179
+ return undefined
180
+ }
181
+
182
+ /**
183
+ * Credential store with demand-driven refresh.
184
+ *
185
+ * Refresh policy: refresh only when the access token is inside the margin (or
186
+ * already expired), and keep the refreshed credential in the plugin-owned file.
187
+ * A failed refresh still returns a not-yet-expired token, so an unreachable
188
+ * refresh endpoint does not take down a working session.
189
+ */
190
+ export class WorkBuddyCredentialStore {
191
+ /**
192
+ * @param {object} options
193
+ * @param {object} [options.variant] The variant this store belongs to.
194
+ * @param {string} [options.ownPath] Explicit credential path.
195
+ * @param {(credential: object) => Promise<object>} options.refresh Upstream refresh.
196
+ * @param {number} [options.refreshMarginMs] Refresh this long before expiry.
197
+ */
198
+ constructor(options) {
199
+ this.variant = options.variant
200
+ this.refresh = options.refresh
201
+ this.refreshMarginMs = options.refreshMarginMs ?? 5 * 60 * 1000
202
+ this.ownPath = options.ownPath ?? join(
203
+ workbuddyPluginDataDir(),
204
+ options.variant ? options.variant.authFilename : WORKBUDDY_AUTH_FILENAME,
205
+ )
206
+ this.inflight = undefined
207
+ }
208
+
209
+ /** The plugin-owned credential path, for diagnostics. */
210
+ ownAuthPath() {
211
+ return this.ownPath
212
+ }
213
+
214
+ /**
215
+ * Read the stored credential without refreshing anything.
216
+ *
217
+ * A credential belonging to the other realm is refused rather than used: one
218
+ * plugin serves both products, and sending one realm's token to the other's
219
+ * endpoint would leak it across products.
220
+ */
221
+ async current() {
222
+ const credential = await this.readOwn()
223
+ if (credential === undefined || this.variant === undefined) return credential
224
+ const region = realmOf(credential)
225
+ if (region !== this.variant.region) {
226
+ throw new Error(
227
+ `${this.variant.displayName} holds a ${region === 'cn' ? 'WorkBuddy (CN)' : 'WorkBuddy AI'} credential`
228
+ + ` (domain ${JSON.stringify(credential.domain)}) in ${this.ownPath};`
229
+ + ` sign in again for ${this.variant.appName}, or remove that file`,
230
+ )
231
+ }
232
+ return credential
233
+ }
234
+
235
+ /**
236
+ * Persist a credential a login just obtained. This is the store's only write
237
+ * path besides refresh; the login route is its only caller.
238
+ */
239
+ async save(credential) {
240
+ if (this.variant !== undefined) {
241
+ const region = realmOf(credential)
242
+ if (region !== this.variant.region) {
243
+ throw new Error(
244
+ `refusing to store a ${region === 'cn' ? 'WorkBuddy (CN)' : 'WorkBuddy AI'} credential`
245
+ + ` for ${this.variant.displayName}`,
246
+ )
247
+ }
248
+ }
249
+ await this.saveOwn(credential)
250
+ }
251
+
252
+ /**
253
+ * The credential to send upstream: {@link current}, refreshed on demand.
254
+ * Single-flight, so parallel requests share one refresh.
255
+ */
256
+ async resolve() {
257
+ const credential = await this.current()
258
+ if (credential === undefined) {
259
+ const app = this.variant?.appName ?? 'WorkBuddy'
260
+ throw new Error(
261
+ `workbuddy: not signed in to ${app}; sign in from the plugin's settings card`
262
+ + ` (the credential is stored at ${this.ownPath})`,
263
+ )
264
+ }
265
+ if (!this.needsRefresh(credential)) return credential
266
+ this.inflight ??= this.refreshNow(credential).finally(() => {
267
+ this.inflight = undefined
268
+ })
269
+ return this.inflight
270
+ }
271
+
272
+ /** Read-only sign-in summary; never refreshes and never throws. */
273
+ async status() {
274
+ try {
275
+ const credential = await this.current()
276
+ if (credential === undefined) return { state: 'signed-out' }
277
+ return {
278
+ state: 'signed-in',
279
+ expiresAtMs: credential.expiresAtMs,
280
+ ...credential.refreshExpiresAtMs === undefined ? {} : { refreshExpiresAtMs: credential.refreshExpiresAtMs },
281
+ ...credential.nickname === undefined ? {} : { nickname: credential.nickname },
282
+ ...credential.domain === '' ? {} : { domain: credential.domain },
283
+ region: realmOf(credential),
284
+ }
285
+ } catch (error) {
286
+ // A realm mismatch (or an unreadable file) is a *diagnosable* signed-out
287
+ // state, not a silent one: the user needs the path to the file that is
288
+ // wrong, and which product it actually belongs to.
289
+ return { state: 'signed-out', reason: error instanceof Error ? error.message : String(error) }
290
+ }
291
+ }
292
+
293
+ /** Remove the stored credential. */
294
+ async logout() {
295
+ try {
296
+ const { rm } = await import('node:fs/promises')
297
+ await rm(this.ownPath, { force: true })
298
+ } catch {
299
+ // Nothing to remove: logging out is idempotent.
300
+ }
301
+ }
302
+
303
+ needsRefresh(credential) {
304
+ if (credential.expiresAtMs <= 0) return true
305
+ return Date.now() + this.refreshMarginMs >= credential.expiresAtMs
306
+ }
307
+
308
+ async refreshNow(credential) {
309
+ if (credential.refreshToken === '') {
310
+ if (credential.expiresAtMs > Date.now() + 30_000) return credential
311
+ throw new Error('workbuddy: access token expired and no refresh token is stored; sign in again from the settings card')
312
+ }
313
+ try {
314
+ const outcome = await this.refresh(credential)
315
+ const refreshed = {
316
+ ...credential,
317
+ accessToken: outcome.accessToken,
318
+ ...outcome.refreshToken === undefined ? {} : { refreshToken: outcome.refreshToken },
319
+ expiresAtMs: outcome.expiresInSec !== undefined
320
+ ? Date.now() + outcome.expiresInSec * 1000
321
+ : credential.expiresAtMs,
322
+ ...outcome.domain === undefined || outcome.domain === '' ? {} : { domain: outcome.domain },
323
+ source: WORKBUDDY_CREDENTIAL_SOURCE,
324
+ }
325
+ await this.saveOwn(refreshed)
326
+ return refreshed
327
+ } catch (error) {
328
+ if (credential.expiresAtMs > Date.now() + 30_000) return credential
329
+ throw new Error(
330
+ `workbuddy: token refresh failed and the access token is expired (${String(error)});`
331
+ + " sign in again from the plugin's settings card",
332
+ )
333
+ }
334
+ }
335
+
336
+ async saveOwn(credential) {
337
+ // The plugin's data directory is created here rather than assumed: the first
338
+ // write of a fresh install is what brings it into being.
339
+ writeJsonAtomic(this.ownPath, ownDocument(credential))
340
+ }
341
+
342
+ async readOwn() {
343
+ try {
344
+ return parseWorkBuddyAuth(await import('node:fs/promises').then(fs => fs.readFile(this.ownPath, 'utf8')))
345
+ } catch {
346
+ // An absent file means "not signed in". Any other read failure is treated
347
+ // the same way: the only recovery either way is to sign in again, and a
348
+ // status read must never be the thing that breaks the card.
349
+ return undefined
350
+ }
351
+ }
352
+ }
353
+
354
+ /** A minimal cookie jar, scoped to one login attempt. */
355
+ class LoginCookieJar {
356
+ constructor() {
357
+ this.cookies = new Map()
358
+ }
359
+
360
+ /** Record every cookie the response set, last write winning per name. */
361
+ absorb(response) {
362
+ for (const raw of response.headers.getSetCookie()) {
363
+ const pair = raw.split(';', 1)[0] ?? ''
364
+ const separator = pair.indexOf('=')
365
+ if (separator <= 0) continue
366
+ const name = pair.slice(0, separator).trim()
367
+ const value = pair.slice(separator + 1).trim()
368
+ if (name !== '') this.cookies.set(name, value)
369
+ }
370
+ }
371
+
372
+ /** The Cookie header for this attempt, or undefined when it holds nothing. */
373
+ header() {
374
+ if (this.cookies.size === 0) return undefined
375
+ return [...this.cookies].map(([name, value]) => `${name}=${value}`).join('; ')
376
+ }
377
+ }
378
+
379
+ /** One upstream `{code,msg,data}` reply, decoded tolerantly. */
380
+ async function readEnvelope(response) {
381
+ const text = await response.text()
382
+ let parsed
383
+ try {
384
+ parsed = JSON.parse(text)
385
+ } catch {
386
+ throw new Error(`workbuddy login: upstream returned non-JSON (http ${response.status}): ${text.slice(0, 160)}`)
387
+ }
388
+ if (!isDocument(parsed)) {
389
+ throw new Error(`workbuddy login: upstream returned an unexpected document (http ${response.status})`)
390
+ }
391
+ return {
392
+ code: typeof parsed['code'] === 'number' ? parsed['code'] : 0,
393
+ msg: typeof parsed['msg'] === 'string' ? parsed['msg'] : '',
394
+ data: 'data' in parsed ? parsed['data'] : undefined,
395
+ }
396
+ }
397
+
398
+ /**
399
+ * Normalize a realm spelling, folding anything unrecognised onto CN so a
400
+ * missing or mistyped value behaves like the deployment the plugin shipped for.
401
+ */
402
+ export function normalizeLoginRegion(region) {
403
+ return String(region ?? '').trim().toLowerCase() === 'global' ? 'global' : 'cn'
404
+ }
405
+
406
+ /**
407
+ * The login client. One instance serves both cards; each attempt owns its own
408
+ * cookie jar, keyed by the state it issued.
409
+ */
410
+ export class WorkBuddyLoginClient {
411
+ constructor(fetchImpl = globalThis.fetch) {
412
+ this.fetchImpl = fetchImpl
413
+ this.jars = new Map()
414
+ }
415
+
416
+ /** Request headers for one realm, carrying the attempt's cookies when it has any. */
417
+ headers(region, jar) {
418
+ const origin = LOGIN_ORIGIN[region]
419
+ const cookie = jar?.header()
420
+ return {
421
+ 'Content-Type': 'application/json',
422
+ 'Accept': 'application/json, text/plain, */*',
423
+ 'X-Requested-With': 'XMLHttpRequest',
424
+ 'Origin': origin,
425
+ 'Referer': `${origin}/`,
426
+ 'User-Agent': LOGIN_USER_AGENT,
427
+ ...cookie === undefined ? {} : { 'Cookie': cookie },
428
+ }
429
+ }
430
+
431
+ /**
432
+ * Issue one attempt: obtain the state and the URL the human must open.
433
+ *
434
+ * The response's cookies are retained under the returned state, because the
435
+ * poll that finishes this attempt has to present them.
436
+ */
437
+ async begin(region) {
438
+ const jar = new LoginCookieJar()
439
+ const response = await this.fetchImpl(`${LOGIN_BASE[region]}${AUTH_STATE_PATH}`, {
440
+ method: 'POST',
441
+ headers: this.headers(region),
442
+ body: '{}',
443
+ signal: AbortSignal.timeout(LOGIN_TIMEOUT_MS),
444
+ })
445
+ jar.absorb(response)
446
+ const envelope = await readEnvelope(response)
447
+ if (!response.ok || envelope.code !== 0) {
448
+ throw new Error(`workbuddy login: auth state failed (http ${response.status}, code ${envelope.code}): ${envelope.msg.slice(0, 160)}`)
449
+ }
450
+ const data = isDocument(envelope.data) ? envelope.data : {}
451
+ const state = optionalString(data['state'])
452
+ const authUrl = optionalString(data['authUrl'])
453
+ if (state === undefined || authUrl === undefined) {
454
+ throw new Error('workbuddy login: auth state reply carried no state or authUrl')
455
+ }
456
+ this.jars.set(state, jar)
457
+ return { state, authUrl, region }
458
+ }
459
+
460
+ /** Drop a finished or abandoned attempt's jar. */
461
+ forget(state) {
462
+ this.jars.delete(state)
463
+ }
464
+
465
+ /** How many attempts currently hold a jar; diagnostics and tests. */
466
+ pendingCount() {
467
+ return this.jars.size
468
+ }
469
+
470
+ /**
471
+ * Poll one attempt once. The caller drives the cadence.
472
+ *
473
+ * `pending` covers both "the human has not finished" (business code 11217)
474
+ * and "the gateway refused this poll yet" (a 4xx while the browser half is
475
+ * still open). A transport failure, or a 5xx, is a real error and is thrown:
476
+ * retrying those as pending would hide an outage behind a spinner that never
477
+ * resolves.
478
+ */
479
+ async poll(attempt) {
480
+ const jar = this.jars.get(attempt.state)
481
+ const response = await this.fetchImpl(
482
+ `${LOGIN_BASE[attempt.region]}${authTokenPath(attempt.state)}`,
483
+ { method: 'GET', headers: this.headers(attempt.region, jar), signal: AbortSignal.timeout(LOGIN_TIMEOUT_MS) },
484
+ )
485
+ jar?.absorb(response)
486
+ if (response.status >= 500) {
487
+ throw new Error(`workbuddy login: token endpoint failed (http ${response.status})`)
488
+ }
489
+ if (response.status >= 400) return { status: 'pending' }
490
+ const envelope = await readEnvelope(response)
491
+ if (envelope.code === LOGIN_PENDING_CODE) return { status: 'pending' }
492
+ if (envelope.code !== 0) return { status: 'pending' }
493
+ const data = isDocument(envelope.data) ? envelope.data : {}
494
+ const accessToken = optionalString(data['accessToken'])
495
+ if (accessToken === undefined) return { status: 'pending' }
496
+ const tokens = {
497
+ accessToken,
498
+ refreshToken: optionalString(data['refreshToken']) ?? '',
499
+ expiresInSec: typeof data['expiresIn'] === 'number' && data['expiresIn'] > 0 ? data['expiresIn'] : 0,
500
+ domain: optionalString(data['domain']) ?? '',
501
+ }
502
+ return { status: 'complete', tokens, account: await this.fetchAccount(attempt, tokens.accessToken, jar) }
503
+ }
504
+
505
+ /**
506
+ * Read the account identity for a finished attempt.
507
+ *
508
+ * Best effort by design: the token bundle is what makes the credential
509
+ * usable, and the identity only improves the display name and the
510
+ * `X-User-Id` header. A failure here must not discard a working login.
511
+ */
512
+ async fetchAccount(attempt, accessToken, jar) {
513
+ try {
514
+ const response = await this.fetchImpl(
515
+ `${LOGIN_BASE[attempt.region]}${loginAccountPath(attempt.state)}`,
516
+ {
517
+ method: 'GET',
518
+ headers: { ...this.headers(attempt.region, jar), 'Authorization': `Bearer ${accessToken}` },
519
+ signal: AbortSignal.timeout(LOGIN_TIMEOUT_MS),
520
+ },
521
+ )
522
+ jar?.absorb(response)
523
+ if (!response.ok) return { uid: '' }
524
+ const envelope = await readEnvelope(response)
525
+ const data = isDocument(envelope.data) ? envelope.data : {}
526
+ const enterpriseId = optionalString(data['enterpriseId'])
527
+ const nickname = optionalString(data['nickname'])
528
+ return {
529
+ uid: optionalString(data['uid']) ?? '',
530
+ ...enterpriseId === undefined ? {} : { enterpriseId },
531
+ ...nickname === undefined ? {} : { nickname },
532
+ }
533
+ } catch {
534
+ // Best effort: the credential is already usable.
535
+ return { uid: '' }
536
+ }
537
+ }
538
+ }
539
+
540
+ export { regionOf, realmOf }