@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/atrest.js ADDED
@@ -0,0 +1,382 @@
1
+ /**
2
+ * Reading the WorkBuddy desktop app's own session, when it is installed.
3
+ *
4
+ * Since WorkBuddy 5.6.0 the desktop app stores its credential *encrypted at
5
+ * rest*: the access token, the refresh token and the nickname are each written
6
+ * as `{"$wbEncrypted":1,"envelope":"<base64>"}`, where the envelope is
7
+ * `{suite, keyId, nonce, authTag, ciphertext}` — AES-256-GCM with a 12-byte
8
+ * nonce and a 16-byte tag, over a length-prefixed transcript that binds the
9
+ * ciphertext to the exact field it was written for.
10
+ *
11
+ * The key is not a user secret: it is a build-time constant compiled into the
12
+ * app's own Electron native module, and the app hands it out through
13
+ * `loggerGet()`. This module therefore asks the very build that wrote the file
14
+ * — running its binary as plain Node (`ELECTRON_RUN_AS_NODE=1`) and calling the
15
+ * binding — rather than carrying a copy of a build-specific constant. The
16
+ * derived key lives in memory for the process lifetime and is never written to
17
+ * disk or logged.
18
+ *
19
+ * This is an **optional convenience**, not a dependency: the plugin's own
20
+ * device-authorization login (see `auth.js`) is the primary path and works
21
+ * whether or not the desktop app is installed. When the app *is* installed,
22
+ * importing its session saves a browser round trip.
23
+ *
24
+ * @module dsh-workbuddy-connect/atrest
25
+ */
26
+ import { createDecipheriv, createHash } from 'node:crypto'
27
+ import { execFile } from 'node:child_process'
28
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
29
+ import { homedir } from 'node:os'
30
+ import { join } from 'node:path'
31
+
32
+ /** How long the app is given to answer with its key payload. */
33
+ const KEY_FETCH_TIMEOUT_MS = 15_000
34
+
35
+ /** Envelope framing names, mapped to the single-byte AAD framing code. */
36
+ const FRAMING_CODE = { file: 1, field: 2, record: 3, stream: 4 }
37
+
38
+ /** Standard (symmetric) format identifiers, transcripted into the AAD. */
39
+ const STANDARD_FORMAT_ID = { file: 'WBEF1', field: 'WBEV1', record: 'WBER1', stream: 'WBES1' }
40
+
41
+ /** Domain separator the AAD transcript starts with. */
42
+ const AAD_DOMAIN = Buffer.from('WB-AAD\0', 'ascii')
43
+
44
+ /** Scheme name of the symmetric envelope this module opens. */
45
+ const SYMMETRIC_SCHEME = 'sym-v1'
46
+
47
+ /** Environment override pointing at the WorkBuddy desktop executable. */
48
+ export const WORKBUDDY_APP_EXECUTABLE_ENV = 'WORKBUDDY_APP_EXECUTABLE'
49
+
50
+ function encodeUint32(value) {
51
+ const bytes = Buffer.allocUnsafe(4)
52
+ bytes.writeUInt32BE(value)
53
+ return bytes
54
+ }
55
+
56
+ /** Length-prefixed UTF-8 string: uint32 big-endian length followed by the bytes. */
57
+ function encodeLengthPrefixed(value) {
58
+ const bytes = Buffer.from(value, 'utf8')
59
+ return Buffer.concat([encodeUint32(bytes.length), bytes])
60
+ }
61
+
62
+ /**
63
+ * The authenticated additional data for one `sym-v1` FIELD-framed envelope.
64
+ *
65
+ * Only the field framing is implemented: it is the shape the desktop app uses
66
+ * for credential fields, and it is also the shape that cannot be confused with
67
+ * a whole-file envelope, so an unexpected framing is a parse error rather than
68
+ * a silently wrong transcript.
69
+ */
70
+ function fieldAad(keyId, suite) {
71
+ if (!/^[0-9a-f]{16}$/u.test(keyId)) throw new Error('workbuddy: envelope keyId is malformed')
72
+ return Buffer.concat([
73
+ AAD_DOMAIN,
74
+ Buffer.from([1]),
75
+ encodeLengthPrefixed(STANDARD_FORMAT_ID.field),
76
+ encodeLengthPrefixed(SYMMETRIC_SCHEME),
77
+ encodeUint32(suite),
78
+ encodeLengthPrefixed(keyId),
79
+ Buffer.from([FRAMING_CODE.field]),
80
+ // Field framing carries no sequence, and the envelope is not final.
81
+ Buffer.from([0]),
82
+ Buffer.from([0]),
83
+ ])
84
+ }
85
+
86
+ /** Whether a value is the app's encrypted-field wrapper. */
87
+ export function isEncryptedFieldWrapper(value) {
88
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
89
+ const keys = Object.keys(value).sort()
90
+ return keys.length === 2
91
+ && keys[0] === '$wbEncrypted'
92
+ && keys[1] === 'envelope'
93
+ && value['$wbEncrypted'] === 1
94
+ && typeof value['envelope'] === 'string'
95
+ }
96
+
97
+ /**
98
+ * The at-rest key id for a derived 32-byte key: the first 16 hex characters
99
+ * of its SHA-256. The envelope's `keyId` is checked against this, so a
100
+ * mismatched key fails loudly instead of returning garbage.
101
+ */
102
+ export function deriveAtRestKeyId(key) {
103
+ return createHash('sha256').update(key).digest('hex').slice(0, 16)
104
+ }
105
+
106
+ /**
107
+ * Derive the 32-byte field key from the app's key payload.
108
+ *
109
+ * The app hashes the payload's base64 STRING — not its decoded bytes — so the
110
+ * same spelling is required here; hashing the decoded secret would produce a
111
+ * different key and every field would fail to open.
112
+ */
113
+ export function deriveAtRestKey(payloadJson) {
114
+ let payload
115
+ try {
116
+ payload = JSON.parse(payloadJson)
117
+ } catch {
118
+ throw new Error('workbuddy: the at-rest key payload is not valid JSON')
119
+ }
120
+ if (typeof payload !== 'object' || payload === null) {
121
+ throw new Error('workbuddy: the at-rest key payload is not an object')
122
+ }
123
+ const secret = payload['atRestSecretKey']
124
+ if (typeof secret !== 'string' || secret === '') {
125
+ throw new Error('workbuddy: the at-rest key payload carries no atRestSecretKey')
126
+ }
127
+ return createHash('sha256').update(secret, 'utf8').digest()
128
+ }
129
+
130
+ /**
131
+ * Open one encrypted field with a derived key and return its plaintext.
132
+ *
133
+ * Throws when the envelope is malformed, belongs to another key, or fails
134
+ * authentication — a GCM tag mismatch is the signal that the transcript or the
135
+ * key is wrong, and it must never degrade into a truncated token.
136
+ */
137
+ export function openEncryptedField(field, key) {
138
+ if (!isEncryptedFieldWrapper(field)) throw new Error('workbuddy: not an encrypted-field wrapper')
139
+ let record
140
+ try {
141
+ record = JSON.parse(Buffer.from(field.envelope, 'base64').toString('utf8'))
142
+ } catch {
143
+ throw new Error('workbuddy: the encrypted-field envelope is not valid base64 JSON')
144
+ }
145
+ const suite = record['suite']
146
+ const keyId = record['keyId']
147
+ const nonce = record['nonce']
148
+ const authTag = record['authTag']
149
+ const ciphertext = record['ciphertext']
150
+ if (typeof suite !== 'number' || typeof keyId !== 'string') {
151
+ throw new Error('workbuddy: the encrypted-field envelope is missing suite or keyId')
152
+ }
153
+ if (typeof nonce !== 'string' || typeof authTag !== 'string' || typeof ciphertext !== 'string') {
154
+ throw new Error('workbuddy: the encrypted-field envelope is missing nonce, authTag or ciphertext')
155
+ }
156
+ const expectedKeyId = deriveAtRestKeyId(key)
157
+ if (keyId !== expectedKeyId) {
158
+ throw new Error(`workbuddy: the encrypted field belongs to key ${keyId}, not the available key ${expectedKeyId}`)
159
+ }
160
+ const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(nonce, 'base64'), { authTagLength: 16 })
161
+ decipher.setAAD(fieldAad(keyId, suite))
162
+ decipher.setAuthTag(Buffer.from(authTag, 'base64'))
163
+ return Buffer.concat([decipher.update(Buffer.from(ciphertext, 'base64')), decipher.final()]).toString('utf8')
164
+ }
165
+
166
+ /** macOS App-bundle roots: system-wide first, then the user's own install. */
167
+ function macAppRoots() {
168
+ return ['/Applications', join(homedir(), 'Applications')]
169
+ }
170
+
171
+ /**
172
+ * The `CFBundleExecutable` out of an `Info.plist`.
173
+ *
174
+ * The binary is named `Electron` for BOTH WorkBuddy bundles — the app is an
175
+ * Electron app, and every Electron app's executable is called `Electron` — so
176
+ * the bundle identifier has to be confirmed before the binary is run. Running
177
+ * some other Electron app's binary would ask the wrong program for a key.
178
+ */
179
+ function bundleExecutable(bundle) {
180
+ const plist = join(bundle, 'Contents', 'Info.plist')
181
+ if (!existsSync(plist)) return undefined
182
+ let text
183
+ try {
184
+ text = readFileSync(plist, 'utf8')
185
+ } catch {
186
+ return undefined
187
+ }
188
+ const executable = /<key>\s*CFBundleExecutable\s*<\/key>\s*<string>([^<]*)<\/string>/u.exec(text)?.[1]?.trim()
189
+ if (executable === undefined || executable === '') return undefined
190
+ const identifier = /<key>\s*CFBundleIdentifier\s*<\/key>\s*<string>([^<]*)<\/string>/u.exec(text)?.[1]?.trim()
191
+ if (identifier === undefined || !/workbuddy/i.test(identifier)) return undefined
192
+ const path = join(bundle, 'Contents', 'MacOS', executable)
193
+ return existsSync(path) ? path : undefined
194
+ }
195
+
196
+ /**
197
+ * The installed WorkBuddy desktop executable, or undefined.
198
+ *
199
+ * The international bundle is `WorkBuddy AI.app` and the CN one is
200
+ * `WorkBuddy.app`; both are looked for, and the first that carries a
201
+ * WorkBuddy bundle identifier wins.
202
+ */
203
+ export function findDesktopExecutable() {
204
+ const override = process.env[WORKBUDDY_APP_EXECUTABLE_ENV]
205
+ if (override !== undefined && override.trim() !== '') return override.trim()
206
+ if (process.platform !== 'darwin') return undefined
207
+ for (const root of macAppRoots()) {
208
+ for (const name of ['WorkBuddy AI.app', 'WorkBuddy.app']) {
209
+ const found = bundleExecutable(join(root, name))
210
+ if (found !== undefined) return found
211
+ }
212
+ }
213
+ return undefined
214
+ }
215
+
216
+ /**
217
+ * Ask the installed desktop app for its key payload by running its own binary
218
+ * as plain Node and calling the native binding.
219
+ *
220
+ * The binding is the app's own public surface for this value, so the plugin
221
+ * never carries a copy of a build-specific constant. The child is given no
222
+ * stdin and a hard timeout, and its stdout is the only thing read.
223
+ */
224
+ export function fetchAtRestKeyPayload(executable) {
225
+ return new Promise((resolve, reject) => {
226
+ const source = "try{process.stdout.write(process._linkedBinding('electron_browser_workbuddy_storage').loggerGet())}"
227
+ + "catch(e){process.exitCode=3;process.stderr.write(String(e&&e.message||e))}"
228
+ execFile(
229
+ executable,
230
+ ['-e', source],
231
+ {
232
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
233
+ timeout: KEY_FETCH_TIMEOUT_MS,
234
+ windowsHide: true,
235
+ maxBuffer: 1024 * 1024,
236
+ },
237
+ (error, stdout, stderr) => {
238
+ if (error !== null) {
239
+ reject(new Error(`workbuddy: the desktop app did not provide its at-rest key (${stderr.trim() || error.message})`))
240
+ return
241
+ }
242
+ const payload = stdout.trim()
243
+ if (payload === '') {
244
+ reject(new Error('workbuddy: the desktop app returned an empty at-rest key payload'))
245
+ return
246
+ }
247
+ resolve(payload)
248
+ },
249
+ )
250
+ })
251
+ }
252
+
253
+ /** Process-lifetime cache of the derived key; never persisted. */
254
+ let cachedKey
255
+ let inflightKey
256
+
257
+ /**
258
+ * The derived at-rest key, or undefined when the desktop app cannot be asked.
259
+ *
260
+ * A failure is remembered briefly so a machine without the app does not spawn
261
+ * a child process for every probe.
262
+ */
263
+ export async function resolveAtRestKey() {
264
+ if (cachedKey !== undefined) return cachedKey
265
+ inflightKey ??= (async () => {
266
+ const executable = findDesktopExecutable()
267
+ if (executable === undefined) return undefined
268
+ try {
269
+ const payload = await fetchAtRestKeyPayload(executable)
270
+ return deriveAtRestKey(payload)
271
+ } catch {
272
+ // The app is installed but did not answer: treat it as "no key" rather
273
+ // than as a hard failure, so the plugin's own login path still works.
274
+ return undefined
275
+ }
276
+ })().finally(() => {
277
+ inflightKey = undefined
278
+ })
279
+ cachedKey = await inflightKey
280
+ return cachedKey
281
+ }
282
+
283
+ /**
284
+ * The directory the desktop app keeps its credential files in.
285
+ *
286
+ * `WORKBUDDY_AUTH_FILE` overrides it, which is how a test or a relocated app
287
+ * points the plugin at a specific document.
288
+ */
289
+ export function desktopAuthDir() {
290
+ const override = process.env['WORKBUDDY_AUTH_FILE']
291
+ if (override !== undefined && override.trim() !== '') return override
292
+ return join(homedir(), 'Library', 'Application Support', 'CodeBuddyExtension', 'Data', 'Public', 'auth')
293
+ }
294
+
295
+ /**
296
+ * The newest credential document the desktop app wrote, or undefined.
297
+ *
298
+ * The app rotates its file (the `workbuddy-desktop*.info` family carries a
299
+ * timestamp in its name), so the newest one by modification time is the
300
+ * current session.
301
+ */
302
+ export function findDesktopCredentialFile(dir = desktopAuthDir()) {
303
+ const override = process.env['WORKBUDDY_AUTH_FILE']
304
+ if (override !== undefined && override.trim() !== '') {
305
+ return existsSync(override) ? override : undefined
306
+ }
307
+ let entries
308
+ try {
309
+ entries = readdirSync(dir)
310
+ } catch {
311
+ return undefined
312
+ }
313
+ let best
314
+ let bestAt = 0
315
+ for (const entry of entries) {
316
+ if (!entry.startsWith('workbuddy-desktop') || !entry.endsWith('.info')) continue
317
+ const path = join(dir, entry)
318
+ let at
319
+ try {
320
+ at = statSync(path).mtimeMs
321
+ } catch {
322
+ continue
323
+ }
324
+ if (at > bestAt) {
325
+ bestAt = at
326
+ best = path
327
+ }
328
+ }
329
+ return best
330
+ }
331
+
332
+ /**
333
+ * The desktop app's current session, decrypted.
334
+ *
335
+ * Returns undefined when the app is not installed, has never signed in, or
336
+ * cannot be asked for its key. Every failure inside is a reason to fall back
337
+ * to the plugin's own login, never an error the user has to act on.
338
+ */
339
+ export async function readDesktopCredential(dir = desktopAuthDir()) {
340
+ const file = findDesktopCredentialFile(dir)
341
+ if (file === undefined) return undefined
342
+ let document
343
+ try {
344
+ document = JSON.parse(readFileSync(file, 'utf8'))
345
+ } catch {
346
+ return undefined
347
+ }
348
+ if (typeof document !== 'object' || document === null) return undefined
349
+ const auth = document['auth']
350
+ const account = document['account']
351
+ if (typeof auth !== 'object' || auth === null) return undefined
352
+
353
+ const key = await resolveAtRestKey()
354
+ if (key === undefined) return undefined
355
+
356
+ const open = (value) => {
357
+ if (isEncryptedFieldWrapper(value)) return openEncryptedField(value, key)
358
+ return typeof value === 'string' ? value : undefined
359
+ }
360
+ const accessToken = open(auth['accessToken'])
361
+ if (accessToken === undefined || accessToken === '') return undefined
362
+ const refreshToken = open(auth['refreshToken']) ?? ''
363
+ const nickname = typeof account === 'object' && account !== null ? open(account['nickname']) : undefined
364
+ const domain = typeof auth['domain'] === 'string' ? auth['domain'] : ''
365
+ const expiresAt = typeof auth['expiresAt'] === 'number' ? auth['expiresAt'] : 0
366
+ const refreshExpiresAt = typeof auth['refreshExpiresAt'] === 'number' ? auth['refreshExpiresAt'] : undefined
367
+ const uid = typeof account === 'object' && account !== null && typeof account['uid'] === 'string' ? account['uid'] : ''
368
+ const enterpriseId = typeof account === 'object' && account !== null && typeof account['enterpriseId'] === 'string'
369
+ ? account['enterpriseId']
370
+ : undefined
371
+ return {
372
+ accessToken,
373
+ refreshToken,
374
+ domain,
375
+ expiresAtMs: expiresAt,
376
+ ...refreshExpiresAt === undefined ? {} : { refreshExpiresAtMs: refreshExpiresAt },
377
+ uid,
378
+ ...nickname === undefined ? {} : { nickname },
379
+ ...enterpriseId === undefined ? {} : { enterpriseId },
380
+ source: 'desktop-app',
381
+ }
382
+ }