dsh-multi-router 0.3.7 → 0.4.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/CHANGELOG.md +79 -0
- package/README.md +69 -9
- package/lib/accounts.js +7 -3
- package/lib/{chunk-IEN3ZQFS.js → chunk-3VGKH7MF.js} +75 -6
- package/lib/chunk-3VGKH7MF.js.map +7 -0
- package/lib/{chunk-WNRHV24A.js → chunk-FTM7RHQV.js} +1 -6
- package/lib/{chunk-WNRHV24A.js.map → chunk-FTM7RHQV.js.map} +2 -2
- package/lib/{chunk-3VVQXFPV.js → chunk-GGRCX2NR.js} +2 -2
- package/lib/{chunk-VESY2B5O.js → chunk-UFS7ZJKY.js} +3 -3
- package/lib/{chunk-BIEDP6NW.js → chunk-UQS7DNOQ.js} +525 -49
- package/lib/chunk-UQS7DNOQ.js.map +7 -0
- package/lib/{chunk-HZVBEBOD.js → chunk-XMXFIV5G.js} +2 -1
- package/lib/{chunk-HZVBEBOD.js.map → chunk-XMXFIV5G.js.map} +2 -2
- package/lib/{chunk-PD2DTHG2.js → chunk-XY2UB22K.js} +3 -3
- package/lib/cli.js +5 -5
- package/lib/client.js +269 -18
- package/lib/client.js.map +3 -3
- package/lib/clients.js +4 -4
- package/lib/host.js +14 -10
- package/lib/index.js +14 -10
- package/lib/index.js.map +2 -2
- package/lib/manager.js +6 -6
- package/lib/router.js +2 -2
- package/lib/shim.js +3 -3
- package/package.json +27 -15
- package/lib/chunk-BIEDP6NW.js.map +0 -7
- package/lib/chunk-IEN3ZQFS.js.map +0 -7
- /package/lib/{chunk-3VVQXFPV.js.map → chunk-GGRCX2NR.js.map} +0 -0
- /package/lib/{chunk-VESY2B5O.js.map → chunk-UFS7ZJKY.js.map} +0 -0
- /package/lib/{chunk-PD2DTHG2.js.map → chunk-XY2UB22K.js.map} +0 -0
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../upstream/workbuddy/src/status-paths.ts", "../upstream/workbuddy/src/variants.ts", "../upstream/workbuddy/src/desktop-credential-protection.ts", "../upstream/workbuddy/src/auth.ts", "../upstream/trae/src/paths.ts", "../upstream/trae/src/auth.ts", "../upstream/trae/src/decrypt.ts", "../upstream/trae/src/identity.ts"],
|
|
4
4
|
"sourcesContent": ["/** Node-free constants and types shared by the Host and browser halves. */\n\n/** Plugin-owned status endpoint consumed by its browser half. */\nexport const WORKBUDDY_STATUS_PATH = '/plugins/dsh-workbuddy-connect/status'\n\n/**\n * Plugin-owned probe control endpoint.\n *\n * Separate from the status route because it accepts writes: the status route's\n * loopback Host/Origin guard protects against a DNS-rebinding *page*, which is\n * not the same as authorizing a state-changing action. This route therefore\n * also requires the in-process key the browser half receives with the status\n * document.\n */\nexport const WORKBUDDY_PROBE_PATH = '/plugins/dsh-workbuddy-connect/probe'\n\n/**\n * The international (WorkBuddy AI) variant's own pair of routes.\n *\n * Kept as separate constants rather than a computed suffix so both halves\n * reference literal strings: the browser bundle and the host bundle are built\n * independently, and a shared expression is one build-config drift away from\n * the desk asking a route the host never mounted.\n */\nexport const WORKBUDDY_AI_STATUS_PATH = '/plugins/dsh-workbuddy-connect/ai/status'\nexport const WORKBUDDY_AI_PROBE_PATH = '/plugins/dsh-workbuddy-connect/ai/probe'\n\n/**\n * Same-origin route backing the browser's update reminder.\n *\n * Read-only like the status route, so the same loopback Host/Origin gate\n * applies; it answers public npm/GitHub metadata only and never token\n * material.\n */\nexport const WORKBUDDY_UPDATE_PATH = '/plugins/dsh-workbuddy-connect/update'\n\n/** One model's recorded probe observation, as the card displays it. */\nexport interface WorkBuddyWebProbeModel {\n id: string\n name: string\n /** `validating` results carry efforts; the other states never do. */\n validation: 'validating' | 'non-validating' | 'unknown'\n efforts: readonly string[]\n probedAt: number\n}\n\n/** Probe section of the status document. */\nexport interface WorkBuddyWebProbeSection {\n /** Whether the user has authorized probing. */\n consent: boolean\n /** Whether a sweep is in flight right now. */\n running: boolean\n /** Models the user could probe by hand (undeclared yet reasoning-capable). */\n candidates: readonly string[]\n /** Recorded observations. */\n results: readonly WorkBuddyWebProbeModel[]\n}\n\n/** Action requested from the probe control route. */\nexport interface WorkBuddyProbeAction {\n /**\n * `probe` spends credit on one model; `clear` drops recorded observations;\n * `refresh` re-reads the credential and re-fetches the model catalog;\n * `set-maximum-context-window` persists the international card preference;\n * `set-model-visibility` hides or shows one model for the signed-in\n * account's picker.\n *\n * All five are writes, which is why they share this route's in-process key\n * and loopback guards rather than the read-only status GET.\n */\n action: 'probe' | 'clear' | 'refresh' | 'set-maximum-context-window' | 'set-model-visibility'\n /** Target model id; required for `probe` and `set-model-visibility`. */\n model?: string\n /** Requested value for `set-maximum-context-window` and `set-model-visibility`. */\n enabled?: boolean\n /** Requested picker visibility for `set-model-visibility`. */\n visible?: boolean\n /**\n * Expected account key for `set-model-visibility`: the `visibility.account`\n * the card rendered its checkboxes from. The host refuses the write when the\n * signed-in account has moved on, so a stale card can never land one\n * account's toggle in another account's bucket.\n */\n account?: string\n}\n\n/**\n * Model-visibility section of the status document (issue #36).\n *\n * Present only when an account with a stable user id is signed in: the\n * preferences are per account, so a credential without a uid has nothing to\n * key them by and the card renders no visibility controls rather than editing\n * a bucket every uid-less account would share. The account key is the same\n * non-secret `uid:enterpriseId` identity the saved catalogs use \u2014 never a\n * token.\n */\nexport interface WorkBuddyWebVisibilitySection {\n /** The `uid:enterpriseId` identity these preferences belong to. */\n account: string\n /** Model ids this account has hidden from the picker (the full list, including ids not in the current catalog). */\n disabled: readonly string[]\n}\n\n/**\n * Where the models a card is currently showing came from.\n *\n * The plan requires the card to distinguish a live catalog from the built-in\n * fallback, and to say when the last attempt failed \u2014 otherwise a stale list is\n * indistinguishable from an offline one, and a user cannot tell whether the\n * models they see still match the upstream.\n */\nexport interface WorkBuddyWebCatalog {\n /**\n * Where the models on screen came from, in degradation order:\n * `live` (fetched now) \u2192 `saved` (this account's last successful fetch,\n * restored after a restart or a failed fetch) \u2192 `fallback` (the roster\n * compiled into the plugin). The card distinguishes them because \"stale\" and\n * \"offline with a saved list\" are different situations for the user.\n */\n source: 'live' | 'saved' | 'fallback'\n /** When the live catalog last succeeded, epoch ms. */\n fetchedAt?: number\n /** App version used as the catalog User-Agent, when the variant needed one. */\n appVersion?: string\n /** Why the most recent fetch failed, when it did, redacted for display. */\n error?: string\n}\n\n/** One billing package and its remaining credit. */\nexport interface WorkBuddyWebCreditAccount {\n packageName: string\n remain: number\n size: number\n unlimited?: true\n /** When the package lapses, in epoch milliseconds; absent when unknown. */\n endTimeMs?: number\n}\n\n/** Credit lapsing inside one horizon, as the card reports it. */\nexport interface WorkBuddyWebExpiringCredits {\n /** Sum of the contributing packages' remaining credit. */\n total: number\n /** How many packages contribute. */\n packages: number\n /** Soonest expiry among them, epoch milliseconds. */\n earliestEndTimeMs?: number\n}\n\n/**\n * Credit at risk, bucketed by horizon.\n *\n * Only present when the upstream actually reported end times \u2014 a card must not\n * read \"no expiry data\" as \"nothing expires soon\".\n *\n * Future horizons only: the billing query behind this covers `valid` + `usedUp`\n * packages from the current time forward, so a lapsed package is never in the\n * set and has no bucket here.\n */\nexport interface WorkBuddyWebCreditExpiry {\n within24h: WorkBuddyWebExpiringCredits\n within3d: WorkBuddyWebExpiringCredits\n within7d: WorkBuddyWebExpiringCredits\n}\n\n/** Aggregated credit answer rendered by the plugin card. */\nexport interface WorkBuddyWebCredits {\n total: number\n accounts: readonly WorkBuddyWebCreditAccount[]\n unlimited?: true\n cycleResetTime?: string\n /** Credit lapsing soon, for the card's warning banner. */\n expiry?: WorkBuddyWebCreditExpiry\n}\n\n/** Billing convenience facts for one model, rendered as card badges. */\nexport interface WorkBuddyWebModelBadge {\n id: string\n name: string\n /** Whether the model is currently free (`x0.00` credits). */\n free?: boolean\n /** Promotional badges, e.g. `\u9650\u65F6\u514D\u8D39`, `\u591C\u95F4\u6298\u6263`. */\n badges?: readonly string[]\n /**\n * Credits multiplier in display form, e.g. `x0.79`. Unlike the model\n * picker's copy, the card renders through the browser locale, so this value\n * may be interpolated into a localized sentence rather than shown bare.\n */\n credits?: string\n /**\n * The rate cannot be stated right now, and the card must say so.\n *\n * Set for a row whose price came from a promotion that has since ended: the\n * upstream bakes the discounted value into the cached row, and the original\n * price is not recoverable from it, so neither the old figure nor `free` may\n * be repeated. The card renders \"refresh to see the price\" instead.\n */\n rateUnknown?: true\n /**\n * Context capacity in tokens, taken verbatim from the upstream\n * `maxAllowedSize`/`maxInputTokens`, or from the international document's\n * `contextWindow.defaultLength` when it declares one.\n *\n * The international card can opt into the largest declared alternative. The\n * selected value is what DSH receives as its actual context budget.\n */\n contextWindow?: number\n /** The upstream default, when the card currently uses a selected maximum. */\n defaultContextWindow?: number\n /**\n * The international document's larger selectable window, when it declares\n * one, and the model's maximum input ceiling.\n *\n * Kept apart from {@link contextWindow} because they answer different\n * questions: `contextWindow` is the budget the plugin actually requests under,\n * while these are facts about what the upstream will accept. Showing the 1M\n * ceiling as though it were the working window would overstate the budget.\n */\n maxContextWindow?: number\n maxInputTokens?: number\n}\n\n/**\n * Why no credential is usable, as a closed enum the browser half switches on.\n *\n * Deliberately separate from `reason`: `reason` is free text meant for a human\n * to read, so matching on it would break the moment the wording changes. This\n * is the machine-readable half, and the card uses it \u2014 never a substring of\n * `reason` \u2014 to decide whether the Agent assist block applies.\n */\nexport type WorkBuddySignedOutReasonCode =\n /** Nobody is signed in; nothing diagnosable beyond that. */\n | 'no-credential'\n /** A credential for the *other* product was found in this variant's file. */\n | 'credential-region-mismatch'\n /** An encrypted credential exists but could not be opened (wrong key, GCM failure, helper crash). */\n | 'encrypted-credential-unreadable'\n /** A product on a supported platform: discovery ran to completion and found no usable candidate. */\n | 'electron-binary-not-found'\n /** A product on a supported platform: discovery found more than one distinct usable app. */\n | 'electron-binary-ambiguous'\n /** No auto-discovery for this product/platform and no explicit path configured. */\n | 'electron-binary-unavailable'\n /** An explicit path (option or env) is set but missing or not executable. */\n | 'electron-path-invalid'\n /** Discovery could not finish: tool missing, timeout, output overflow, unreadable plist. */\n | 'electron-discovery-incomplete'\n\n/** Every reason code, for validation without trusting a wire value. */\nconst SIGNED_OUT_REASON_CODES: readonly WorkBuddySignedOutReasonCode[] = [\n 'no-credential',\n 'credential-region-mismatch',\n 'encrypted-credential-unreadable',\n 'electron-binary-not-found',\n 'electron-binary-ambiguous',\n 'electron-binary-unavailable',\n 'electron-path-invalid',\n 'electron-discovery-incomplete',\n]\n\n/** Whether a value is one of the closed set of signed-out reason codes. */\nexport function isWorkBuddySignedOutReasonCode(value: unknown): value is WorkBuddySignedOutReasonCode {\n return typeof value === 'string' && (SIGNED_OUT_REASON_CODES as readonly string[]).includes(value)\n}\n\n/** The JSON document the plugin card renders. */\nexport type WorkBuddyWebStatus =\n | {\n status: 'signed-out'\n /**\n * Why no credential is usable, when that is diagnosable rather than simply\n * \"nobody signed in\" \u2014 today a credential belonging to the other product.\n * The card renders it in place of the generic sign-in hint.\n */\n reason?: string\n /** Machine-readable companion to `reason`; see {@link WorkBuddySignedOutReasonCode}. */\n reasonCode?: WorkBuddySignedOutReasonCode\n }\n | {\n status: 'signed-in'\n nickname?: string\n domain?: string\n source?: 'desktop' | 'dsh'\n expiresAt?: number\n credits?: WorkBuddyWebCredits\n creditsError?: string\n /** Billing convenience facts for the models the plugin serves. */\n models?: readonly WorkBuddyWebModelBadge[]\n /** Where those models came from, and whether the last fetch failed. */\n catalog?: WorkBuddyWebCatalog\n /** Reasoning-effort probe state, consent, and recorded observations. */\n probe?: WorkBuddyWebProbeSection\n /** International-card preference selecting larger declared context windows. */\n useMaximumContextWindow?: boolean\n /** Per-account hidden-model state for the card's visibility controls. */\n visibility?: WorkBuddyWebVisibilitySection\n /**\n * In-process key authorizing probe control writes. Handed to the card with\n * the status document (the card is same-origin and already had to pass the\n * loopback guard); it is never persisted and rotates per process.\n */\n probeKey?: string\n }\n | { status: 'error'; message: string }\n", "/**\n * The two WorkBuddy desktop apps this one plugin serves.\n *\n * Both products are the same client framework in different regions, and both\n * write their sign-in into the *same* shared `CodeBuddyExtension` auth\n * directory \u2014 they differ by file basename, base URL, catalog endpoint, and\n * display identity. Everything that varies between them is collected here as\n * one descriptor, so no module has to carry its own `if (international)`\n * branch and a third variant would be a data change rather than a refactor.\n *\n * This module is host-side (it names files and env vars). The browser half\n * takes the same ids and routes from the Node-free `status-paths.ts`, which\n * stays the single source shared by both halves.\n *\n * @module dsh-workbuddy-connect/variants\n */\n\nimport { WORKBUDDY_AI_STATUS_PATH, WORKBUDDY_AI_PROBE_PATH, WORKBUDDY_PROBE_PATH, WORKBUDDY_STATUS_PATH } from './status-paths.ts'\nimport type { WorkBuddyRegion } from './upstream.ts'\n\n/** One WorkBuddy product variant. */\nexport interface WorkBuddyVariant {\n /** Provider id registered with DSH, e.g. `workbuddy-ai`. */\n id: string\n /** Model-group heading and card title stem, e.g. `WorkBuddy AI`. */\n displayName: string\n /** Desktop app name as users know it, for diagnostics and error copy. */\n appName: string\n /** Which upstream region this variant's credentials must belong to. */\n region: WorkBuddyRegion\n /** Env var overriding the desktop auth-file location. */\n env: string\n /**\n * How this product's Electron helper is identified and located.\n *\n * Optional for source compatibility: `WorkBuddyVariant` is a public type and\n * existing callers construct their own descriptors without it. Resolution\n * falls back to {@link electronProfileFor}, keyed by variant id \u2014 an\n * unknown id stays on the CN profile, the store's other legacy default.\n */\n electron?: WorkBuddyElectronProduct\n /** Basename of the desktop app's own auth file in the shared auth directory. */\n desktopFilename: string\n /** Basename of the plugin-owned credential copy under `$DSH_HOME`. */\n ownFilename: string\n /** Basename of the plugin-owned probe-record file under `$DSH_HOME`. */\n probeFilename: string\n /**\n * Basename of the plugin-owned saved-catalog file under `$DSH_HOME`.\n *\n * One per variant, like the probe records: the two endpoints disagree about\n * rates, windows, and even which models exist for a shared id, so a catalog\n * saved from one must never be served as the other's.\n */\n catalogFilename: string\n /**\n * Basename of the plugin-owned per-account model-visibility file under\n * `$DSH_HOME`.\n *\n * One per variant, for the same reason as the catalogs and probe records:\n * the two endpoints share model ids, so one variant's hidden list must never\n * answer for the other's picker.\n */\n visibilityFilename: string\n /** Same-origin status route consumed by this variant's card. */\n statusPath: string\n /** Same-origin probe-control route consumed by this variant's card. */\n probePath: string\n}\n\n/**\n * How one product's Electron key helper is identified on each platform, and\n * which env var names an explicit binary for it (issues #59/#60).\n *\n * The profile is the *only* place product identity enters helper resolution \u2014\n * never the discovery setting, which only says whether a platform may be\n * searched at all: two products on the same platform differ by bundle id /\n * registry name / exe basename, so a discovery that matches one can never\n * legitimately execute the other's binary.\n */\nexport interface WorkBuddyElectronProduct {\n /** Product name for helper diagnostics and error copy, e.g. `WorkBuddy AI`. */\n productName: string\n /** Env var naming an explicit Electron binary for this product alone. */\n envVar: string\n /** macOS identity and default install layout, verified per product. */\n macOS: {\n bundleId: string\n defaultPath: string\n }\n /**\n * Windows identity from the uninstall registry and the exe it names.\n * `defaultPathSegments` exists only where the default install location has\n * been measured (CN); the international app has only been seen in\n * user-chosen locations, so it stays registry-only \u2014 an unverified default\n * is a guess, and guessing is how the wrong app gets executed.\n */\n windows: {\n displayNamePattern: RegExp\n exeBasename: string\n defaultPathSegments?: readonly string[]\n }\n}\n\n/** CN WorkBuddy first: the existing provider keeps its id, paths, and copy. */\nexport const WORKBUDDY_VARIANTS: readonly WorkBuddyVariant[] = [\n {\n id: 'workbuddy',\n displayName: 'WorkBuddy',\n appName: 'WorkBuddy',\n region: 'cn',\n env: 'WORKBUDDY_AUTH_FILE',\n electron: {\n productName: 'WorkBuddy',\n envVar: 'WORKBUDDY_ELECTRON_BIN',\n macOS: {\n bundleId: 'com.tencent.workbuddy.mac',\n defaultPath: '/Applications/WorkBuddy.app/Contents/MacOS/Electron',\n },\n windows: {\n displayNamePattern: /^WorkBuddy(?:\\s+\\d+(?:\\.\\d+)+(?:[-+][0-9A-Za-z.-]+)?)?$/u,\n exeBasename: 'workbuddy.exe',\n defaultPathSegments: ['Programs', 'WorkBuddy', 'WorkBuddy.exe'],\n },\n },\n desktopFilename: 'workbuddy-desktop.info',\n ownFilename: '.workbuddy-auth.json',\n probeFilename: '.workbuddy-probe.json',\n catalogFilename: '.workbuddy-catalog.json',\n visibilityFilename: '.workbuddy-model-visibility.json',\n statusPath: WORKBUDDY_STATUS_PATH,\n probePath: WORKBUDDY_PROBE_PATH,\n },\n {\n id: 'workbuddy-ai',\n displayName: 'WorkBuddy AI',\n appName: 'WorkBuddy AI',\n region: 'global',\n env: 'WORKBUDDY_AI_AUTH_FILE',\n electron: {\n productName: 'WorkBuddy AI',\n envVar: 'WORKBUDDY_AI_ELECTRON_BIN',\n macOS: {\n bundleId: 'com.workbuddy.workbuddy-ai',\n defaultPath: '/Applications/WorkBuddy AI.app/Contents/MacOS/Electron',\n },\n windows: {\n // Measured in #60: `WorkBuddy AI 5.6.2`. The CN pattern cannot match\n // this value (\"AI\" is not a version) and this pattern cannot match\n // `WorkBuddy 5.6.2` (missing the literal \" AI\"), so the two records\n // never feed each other's discovery.\n displayNamePattern: /^WorkBuddy AI(?:\\s+\\d+(?:\\.\\d+)+(?:[-+][0-9A-Za-z.-]+)?)?$/u,\n exeBasename: 'workbuddyai.exe',\n },\n },\n desktopFilename: 'workbuddy-desktop-ai.info',\n ownFilename: '.workbuddy-ai-auth.json',\n probeFilename: '.workbuddy-ai-probe.json',\n catalogFilename: '.workbuddy-ai-catalog.json',\n visibilityFilename: '.workbuddy-ai-model-visibility.json',\n statusPath: WORKBUDDY_AI_STATUS_PATH,\n probePath: WORKBUDDY_AI_PROBE_PATH,\n },\n]\n\n/** The CN variant; the plugin's long-standing default and compatibility anchor. */\nexport const CN_VARIANT = WORKBUDDY_VARIANTS[0]! satisfies WorkBuddyVariant\n\n/** The international variant. */\nexport const AI_VARIANT = WORKBUDDY_VARIANTS[1]! satisfies WorkBuddyVariant\n\n/** Look up a variant by provider id. */\nexport function variantFor(id: string): WorkBuddyVariant | undefined {\n return WORKBUDDY_VARIANTS.find(variant => variant.id === id)\n}\n\n/**\n * The Electron profile a variant resolves with.\n *\n * Callers inside the plugin pass their known-complete variants; descriptors\n * assembled outside (the type is public and predates the profile) fall back\n * by variant id, so an id-less or unknown custom variant stays on the CN\n * product \u2014 the same default the store's other legacy fields assume.\n */\nexport function electronProfileFor(variant: Pick<WorkBuddyVariant, 'id' | 'electron'> | undefined): WorkBuddyElectronProduct {\n // Both shipped variants always carry their profile; the optional marker\n // exists only for externally assembled descriptors, hence the assertion.\n return variant?.electron ?? (variant?.id === AI_VARIANT.id ? AI_VARIANT : CN_VARIANT).electron!\n}\n", "/**\n * WorkBuddy 5.6.x at-rest credential protection: classification, key\n * resolution, and field decryption for the desktop apps' encrypted auth files.\n *\n * Since WorkBuddy 5.6 both desktop apps (CN and international, which followed\n * in 5.6.2) encrypt `auth.accessToken` and `auth.refreshToken` at rest\n * (`buildPolicy: \"fields\"`, on by default), so the plugin reads\n * `{$wbEncrypted:1, envelope}` wrappers instead of token strings (issues\n * #39/#40, #59/#60). Everything needed to open them lives on the same machine:\n *\n * - the sealed payload (`{version:1, atRestSecretKey}`) comes from the\n * WorkBuddy-modified Electron's private `workbuddyStorage` binding, reached\n * by running *its own* binary once with `ELECTRON_RUN_AS_NODE=1`;\n * - `protectorKey = sha256(atRestSecretKey, utf8)` opens the envelopes with\n * AES-256-GCM; the AAD builder below is transcribed from the app's own\n * `buildAuthenticatedContextAad` (verified live against 5.6.2, see\n * `docs/r3-final.js` in the working copy \u2014 not committed).\n *\n * The plugin process itself can never call `_linkedBinding` (it runs in DSH's\n * Node, not the forked Electron), so the helper is spawned. The key is cached\n * in memory only, single-flight, and re-resolved when an envelope names a\n * different key id. Neither the payload, the key, nor any token is ever\n * logged; error messages carry sizes, ids, and exit codes only.\n *\n * @module dsh-workbuddy-connect/desktop-credential-protection\n */\n\nimport { execFile } from 'node:child_process'\nimport { accessSync, constants, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs'\nimport { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto'\nimport { basename, dirname, join } from 'node:path'\nimport type { WorkBuddySignedOutReasonCode } from './status-paths.ts'\nimport { electronProfileFor } from './variants.ts'\nimport type { WorkBuddyElectronProduct, WorkBuddyVariant } from './variants.ts'\n\n/** The four states a desktop auth document can be read as. */\nexport type DesktopAuthFormat = 'absent' | 'plaintext' | 'encrypted' | 'unrecognized'\n\n/**\n * Env variable naming an explicit Electron binary for the CN product. The\n * international product has its own ({@link WorkBuddyElectronProduct.envVar}\n * on each variant); a shared variable is a single point of failure across two\n * independently installed apps (issue #60).\n */\nexport const WORKBUDDY_ELECTRON_BIN_ENV = 'WORKBUDDY_ELECTRON_BIN'\n\n/**\n * The platform-default Electron binary for one product, or `undefined` where\n * none is verified. macOS defaults come from each product's measured layout;\n * the Windows default needs `LOCALAPPDATA`, and the international app has no\n * verified default location at all \u2014 registry discovery only, never a guess.\n */\nexport function defaultWorkBuddyElectronPath(\n product: WorkBuddyElectronProduct,\n platform: NodeJS.Platform = process.platform,\n): string | undefined {\n if (platform === 'darwin') return product.macOS.defaultPath\n if (platform !== 'win32' || product.windows.defaultPathSegments === undefined) return undefined\n const localAppData = process.env.LOCALAPPDATA?.trim()\n return localAppData === undefined || localAppData === ''\n ? undefined\n : join(localAppData, ...product.windows.defaultPathSegments)\n}\n\n/** One decrypted-openable envelope's decoded parts. */\nexport interface WorkBuddyEnvelope {\n suite: number\n keyId: string\n nonce: Buffer\n authTag: Buffer\n ciphertext: Buffer\n}\n\n/** One auth field found in its encrypted wrapper, with its envelope decoded. */\nexport interface WrappedAuthField {\n field: 'accessToken' | 'refreshToken'\n envelope: WorkBuddyEnvelope\n}\n\n/**\n * A read desktop auth document, as a discriminated union on `format`. The\n * `encrypted` variant carries the parsed document plus the fields still in\n * wrappers; the caller decrypts those fields and hands the rebuilt text to\n * the regular parser, so identity and expiry fields need no second code path.\n */\nexport type DesktopAuthClassification =\n | { format: 'absent' }\n | { format: 'plaintext' }\n | { format: 'encrypted', wrapped: { document: Record<string, unknown>, fields: readonly WrappedAuthField[] } }\n | { format: 'unrecognized' }\n\n/** Distinct key ids across the wrapped fields, in field order. */\nexport function keyIdsOf(fields: readonly WrappedAuthField[]): string[] {\n return [...new Set(fields.map(wrapped => wrapped.envelope.keyId))]\n}\n\n/**\n * Whether a raw value is the 5.6 field wrapper, with its inner envelope\n * decodable. The wrapper is `{$wbEncrypted:1, envelope:<base64 of a JSON\n * {suite,keyId,nonce,authTag,ciphertext>}}`; anything claiming the flag whose\n * envelope cannot be decoded makes the whole document unrecognized rather\n * than encrypted, because no key could ever open it.\n */\nfunction parseWrappedField(field: 'accessToken' | 'refreshToken', value: unknown): WrappedAuthField | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined\n const wrapped = value as Record<string, unknown>\n if (wrapped['$wbEncrypted'] !== 1 || typeof wrapped['envelope'] !== 'string') return undefined\n let inner: unknown\n try {\n inner = JSON.parse(Buffer.from(wrapped['envelope'], 'base64').toString('utf8'))\n } catch {\n return undefined\n }\n if (typeof inner !== 'object' || inner === null || Array.isArray(inner)) return undefined\n const parts = inner as Record<string, unknown>\n const nonce = parseBase64(parts['nonce'], 12)\n const authTag = parseBase64(parts['authTag'], 16)\n const ciphertext = parseBase64(parts['ciphertext'])\n if (nonce === undefined || authTag === undefined || ciphertext === undefined) return undefined\n if (typeof parts['suite'] !== 'number' || !Number.isInteger(parts['suite'])) return undefined\n // Suite 1 is the only scheme WorkBuddy 5.6.x defines for credential fields.\n // Anything else is a format this plugin has not seen, so the wrapper is not\n // claimed as encrypted \u2014 the document then reads as unrecognized and the\n // store reports a diagnosis instead of attempting a blind open.\n if (parts['suite'] !== 1) return undefined\n if (typeof parts['keyId'] !== 'string' || !/^[0-9a-f]{16}$/u.test(parts['keyId'])) return undefined\n return {\n field,\n envelope: {\n suite: parts['suite'],\n keyId: parts['keyId'],\n nonce,\n authTag,\n ciphertext,\n },\n }\n}\n\n/** Decode a base64 value and check its exact byte length when given. */\nfunction parseBase64(value: unknown, length?: number): Buffer | undefined {\n if (typeof value !== 'string' || value === '') return undefined\n let decoded: Buffer\n try {\n decoded = Buffer.from(value, 'base64')\n } catch {\n return undefined\n }\n // Buffer.from is lenient about stray characters; require the round-trip so a\n // tampered envelope is rejected before any key material is involved.\n if (decoded.length === 0 || decoded.toString('base64').replace(/=+$/u, '') !== value.replace(/=+$/u, '')) return undefined\n return length === undefined || decoded.length === length ? decoded : undefined\n}\n\nconst AUTH_FIELDS = ['accessToken', 'refreshToken'] as const\n\n/**\n * Read a desktop auth document's format. `absent` is an empty file; `plaintext`\n * is any document the regular parser could read (even one without a token);\n * `encrypted` has at least one field in a decodable wrapper; everything else \u2014\n * unparsable JSON, non-objects, wrappers whose envelope will not decode \u2014 is\n * `unrecognized`.\n */\nexport function classifyDesktopAuthDocument(text: string): DesktopAuthClassification {\n if (text.trim() === '') return { format: 'absent' }\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n return { format: 'unrecognized' }\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return { format: 'unrecognized' }\n const document = parsed as Record<string, unknown>\n const auth = typeof document['auth'] === 'object' && document['auth'] !== null\n ? document['auth'] as Record<string, unknown>\n : document\n const fields: WrappedAuthField[] = []\n for (const field of AUTH_FIELDS) {\n const value = auth[field]\n if (typeof value === 'string') continue\n const wrapped = parseWrappedField(field, value)\n // A field in *some* object that is not a decodable wrapper: not plaintext,\n // not usable. Treated as unrecognized below unless another field wrapped.\n if (wrapped === undefined && value !== undefined) return { format: 'unrecognized' }\n if (wrapped !== undefined) fields.push(wrapped)\n }\n if (fields.length === 0) return { format: 'plaintext' }\n return { format: 'encrypted', wrapped: { document, fields } }\n}\n\n/**\n * Decrypt a wrapped document into the plaintext text the regular parser reads.\n * Throws a diagnosable error naming the field and key ids \u2014 never envelope or\n * token content \u2014 when any wrapped field cannot be opened.\n */\nexport function unwrapDesktopAuthDocument(\n classification: Extract<DesktopAuthClassification, { format: 'encrypted' }>,\n openField: (wrapped: WrappedAuthField) => string,\n): string {\n const wrapped = classification.wrapped\n const rebuilt = structuredClone(wrapped.document) as Record<string, unknown>\n const auth = typeof rebuilt['auth'] === 'object' && rebuilt['auth'] !== null\n ? rebuilt['auth'] as Record<string, unknown>\n : rebuilt\n for (const field of wrapped.fields) {\n auth[field.field] = openField(field)\n }\n return JSON.stringify(rebuilt)\n}\n\n/**\n * The authenticated-context AAD for one field envelope, transcribed from the\n * app bundle's `buildAuthenticatedContextAad` and verified live against 5.6.2\n * (`docs/r3-final.js` in the working copy holds the original reference).\n * Credential fields are always suite 1 under the `field` framing (WBEV1);\n * the framing family's other members (WBEF1/WBER1/WBES1) belong to other\n * document kinds and are deliberately not implemented \u2014 opening a field is\n * not a place to guess at future formats.\n */\nexport function buildAuthenticatedContextAad(keyId: string, suite: number): Buffer {\n const prefix = Buffer.from('WB-AAD\\0', 'ascii')\n const lengthPrefixed = (value: string): Buffer => {\n const bytes = Buffer.from(value, 'utf8')\n const header = Buffer.allocUnsafe(4)\n header.writeUInt32BE(bytes.length)\n return Buffer.concat([header, bytes])\n }\n const suiteBytes = Buffer.allocUnsafe(4)\n suiteBytes.writeUInt32BE(suite)\n // No sequence numbers on credential fields; the final byte 0 mirrors the\n // reference script's default context.\n return Buffer.concat([\n prefix, Buffer.from([1]),\n lengthPrefixed('WBEV1'),\n lengthPrefixed('sym-v1'),\n suiteBytes,\n lengthPrefixed(keyId),\n Buffer.from([2]),\n Buffer.from([0]),\n Buffer.from([0]),\n ])\n}\n\n/**\n * Open one envelope with a protector key; `undefined` when it will not open.\n * The accepted format is exactly what WorkBuddy 5.6.2 writes \u2014 suite 1 under\n * the `field` framing \u2014 so a failure means \"not this format / wrong key\",\n * and is reported as such rather than retried against other framings.\n */\nexport function openAuthField(key: Buffer, envelope: WorkBuddyEnvelope): string | undefined {\n try {\n const decipher = createDecipheriv('aes-256-gcm', key, envelope.nonce, { authTagLength: 16 })\n decipher.setAAD(buildAuthenticatedContextAad(envelope.keyId, envelope.suite))\n decipher.setAuthTag(envelope.authTag)\n return Buffer.concat([decipher.update(envelope.ciphertext), decipher.final()]).toString('utf8')\n } catch {\n return undefined\n }\n}\n\n/** Seal one field with the exact format `openAuthField` reads. Test helper. */\nexport function sealAuthFieldForTest(key: Buffer, plaintext: string, suite = 1): { '$wbEncrypted': 1, envelope: string } {\n const keyId = createHash('sha256').update(key).digest('hex').slice(0, 16)\n const nonce = randomBytes(12)\n const cipher = createCipheriv('aes-256-gcm', key, nonce, { authTagLength: 16 })\n cipher.setAAD(buildAuthenticatedContextAad(keyId, suite))\n const ciphertext = Buffer.concat([cipher.update(Buffer.from(plaintext, 'utf8')), cipher.final()])\n const inner = {\n suite,\n keyId,\n nonce: nonce.toString('base64'),\n authTag: cipher.getAuthTag().toString('base64'),\n ciphertext: ciphertext.toString('base64'),\n }\n return { '$wbEncrypted': 1, envelope: Buffer.from(JSON.stringify(inner), 'utf8').toString('base64') }\n}\n\n/** The validated `loggerGet()` payload: the sealed at-rest secret. */\nexport interface WorkBuddyAtRestPayload {\n atRestSecretKey: string\n}\n\n/**\n * Validate the helper's payload against the app's own rules: `version:1` and\n * a canonical-base64 32-byte, non-all-zero secret. `undefined` otherwise.\n */\nexport function parseAtRestPayload(text: string): WorkBuddyAtRestPayload | undefined {\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n return undefined\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return undefined\n const payload = parsed as Record<string, unknown>\n if (payload['version'] !== 1) return undefined\n const secret = payload['atRestSecretKey']\n if (typeof secret !== 'string' || secret === '') return undefined\n let decoded: Buffer\n try {\n decoded = Buffer.from(secret, 'base64')\n } catch {\n return undefined\n }\n if (decoded.length !== 32) return undefined\n if (decoded.toString('base64') !== secret) return undefined\n if (decoded.every(byte => byte === 0)) return undefined\n return { atRestSecretKey: secret }\n}\n\n/** Derive the protector key from the payload's secret (sha256 over its UTF-8 string). */\nexport function deriveProtectorKey(secret: string): Buffer {\n return createHash('sha256').update(secret, 'utf8').digest()\n}\n\n/** A resolved protector key and the id envelopes name for it. */\ninterface ResolvedKey {\n key: Buffer\n keyId: string\n}\n\n/** The spawned helper. Separated from the provider so tests can stand it in. */\nexport type WorkBuddyKeyPayloadSource = () => Promise<string>\n\n/**\n * Which automatic discovery, if any, this provider may run when no explicit\n * binary is configured.\n *\n * The value says which *platform* may be searched, never which product: two\n * products on the same platform are told apart by the product profile\n * ({@link WorkBuddyElectronProduct} \u2014 bundle id, registry name, exe basename),\n * so a search for one can never execute the other's binary. `none` remains the\n * safe default for platforms without a verified layout (Linux today).\n */\nexport type WorkBuddyElectronDiscovery = 'none' | 'macos-workbuddy' | 'windows-workbuddy'\n\n/**\n * Select discovery by platform. Both products have verified layouts on macOS\n * and Windows (the international app is registry-only there), so discovery no\n * longer gates on region; Linux and others stay `none`.\n */\nexport function electronDiscoveryFor(\n platform: NodeJS.Platform = process.platform,\n): WorkBuddyElectronDiscovery {\n if (platform === 'darwin') return 'macos-workbuddy'\n if (platform === 'win32') return 'windows-workbuddy'\n return 'none'\n}\n\n/**\n * The at-rest key provider one variant's store should use. Shared by the\n * plugin host and the CLI entry so the browser card and `doctor`/`status` can\n * never disagree about which binary a variant resolves.\n */\nexport function atRestKeyProviderFor(variant: Pick<WorkBuddyVariant, 'id' | 'electron'>): WorkBuddyAtRestKeyProvider {\n return new WorkBuddyAtRestKeyProvider({\n product: electronProfileFor(variant),\n discovery: electronDiscoveryFor(),\n })\n}\n\n/** Absolute tool paths: never resolved through PATH, which a user can change. */\nconst MDFIND_BIN = '/usr/bin/mdfind'\nconst PLUTIL_BIN = '/usr/bin/plutil'\nconst WINDOWS_REGISTRY_ROOTS = [\n 'HKCU\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall',\n 'HKLM\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall',\n 'HKLM\\\\Software\\\\WOW6432Node\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall',\n] as const\nconst WINDOWS_REGISTRY_OUTPUT_MAX_BYTES = 1024 * 1024\nconst WINDOWS_ELECTRON_VERSION_PATTERN = /^\\d+\\.\\d+\\.\\d+(?:[-+][0-9A-Za-z.-]+)?$/u\n\n/**\n * The replacement character Node substitutes for bytes that are not valid\n * UTF-8. Its presence is the *only* thing this file treats as evidence about\n * encoding (#88).\n *\n * It is a signal, not a guess. `reg.exe` output that decodes cleanly here was\n * genuinely UTF-8, so its paths can be trusted as-is. Output containing U+FFFD\n * means the bytes were in some other code page \u2014 which one cannot be\n * determined from the bytes, and this file never tries. The response is to\n * re-read the same root through a path that bypasses code pages entirely.\n *\n * A real Windows path cannot contain U+FFFD, so there is no false trigger to\n * worry about; and a *missed* trigger (some code page whose bytes happen to be\n * valid UTF-8) is still not a wrong answer \u2014 the ASCII skeleton of a `reg\n * query` document is identical in every code page, so a mis-decoded non-ASCII\n * path simply fails the later `statSync` exactly as it did before this fix.\n */\nconst WINDOWS_REPLACEMENT_CHARACTER = '\\uFFFD'\n\n/**\n * The PowerShell command that re-reads one uninstall root as UTF-8.\n *\n * Used *only* as a fallback, and only to supply data: the caller feeds its\n * output through the same {@link parseWindowsRegistryOutput} and\n * {@link inspectWindowsElectronCandidate} as the `reg.exe` path, so candidate\n * validation, uniqueness, and the \"we could not check\" rules are unchanged.\n *\n * Why a different tool rather than a smarter decode: `reg.exe` writes in a\n * code page chosen by the console it inherits, and no inspection of the\n * resulting bytes can recover which one. .NET's registry API returns strings,\n * so the question never arises.\n *\n * Structure notes, each one a defect fixed after review:\n *\n * - **`param` is the first statement.** A `param` block must lead the script\n * block; putting the encoding assignment before it is a parse error in\n * Windows PowerShell 5.1.\n * - **`[Console]::OutputEncoding` is set explicitly.** Windows PowerShell 5.1\n * encodes redirected stdout with it, so UTF-8 is *defined* for this child\n * rather than inferred from what comes back.\n * - **Exit codes distinguish \"root absent\" from \"root unreadable\"** (`2` and\n * `3`). The caller branches on the code, never on message text, so the\n * localized diagnostics below cannot change an outcome.\n * - **An unopenable subkey is `3`, not `continue`.** Skipping it silently\n * could drop a real candidate and make the product look absent, which is\n * precisely the confusion the caller's `incomplete` state exists to prevent.\n * - **Output is JSON.** PowerShell does the escaping, so paths containing\n * spaces, commas, or quotes no longer depend on column positions, and only\n * the two values this plugin reads are collected.\n * - **The invocation wraps this script in a call-operator script block.**\n * Windows PowerShell 5.1 joins every argument after `-Command` into one\n * command string and parses that string as code, so a script whose text\n * merely starts with `param` never receives the trailing `-Root` tokens \u2014\n * they land inside the script text, `$Root` stays empty, and every\n * fallback query fails as exit 2/3 (#105/#106/#107). See\n * {@link WINDOWS_POWERSHELL_QUERY_COMMAND}.\n *\n * The root is passed as a `-Root` argument, never interpolated into the\n * command text, and it must pass {@link WINDOWS_REGISTRY_ROOT_PATTERN}\n * before the process starts \u2014 `-Command` arguments are re-parsed as code, so\n * only provably inert path characters may ride along.\n */\nconst WINDOWS_REGISTRY_RELATIVE_POWERSHELL = 'System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe'\n/** Exit code meaning the root key does not exist (a normal, expected outcome). */\nconst WINDOWS_POWERSHELL_ROOT_ABSENT = 2\n/** Exit code meaning the root exists but a part of it could not be read. */\nconst WINDOWS_POWERSHELL_ROOT_UNREADABLE = 3\nconst WINDOWS_POWERSHELL_QUERY_SCRIPT = [\n 'param([string]$Root)',\n '[Console]::OutputEncoding=[Text.Encoding]::UTF8;',\n '$ErrorActionPreference=\"Stop\";',\n '$path=\"Registry::\"+$Root;',\n 'if (-not (Test-Path -LiteralPath $path)) { [Console]::Error.Write(\"root absent\"); exit 2 };',\n 'try { $k=Get-Item -LiteralPath $path -ErrorAction Stop } catch { [Console]::Error.Write(\"root unreadable\"); exit 3 };',\n '$out=@();',\n 'foreach ($n in $k.GetSubKeyNames()) {',\n ' try { $p=$k.OpenSubKey($n); if ($null -eq $p) { throw \"null\" } } catch { [Console]::Error.Write(\"subkey unreadable\"); exit 3 };',\n ' $d=$p.GetValue(\"DisplayName\");$i=$p.GetValue(\"DisplayIcon\");',\n ' if ($null -ne $d -or $null -ne $i) { $out += [pscustomobject]@{ displayName=[string]$d; displayIcon=[string]$i } }',\n '};',\n 'ConvertTo-Json -InputObject @($out) -Compress -Depth 3',\n].join(' ')\n\n/**\n * The `-Command` value actually handed to `powershell.exe`: the query script\n * wrapped in a call-operator script block.\n *\n * Windows PowerShell 5.1 joins every argument that follows `-Command` into\n * one command string and runs that string as code. A bare `param(...)`\n * script therefore never binds the trailing `-Root <path>` tokens \u2014 they end\n * up inside the script text, `$Root` is empty, and the query ends as exit\n * 2/3: discovery incomplete, the app binary is never located, and at-rest\n * key resolution fails as a silent `signed-out` (#105/#106/#107, three\n * independent Windows reports on 0.7.2). The call operator makes the binding\n * explicit: the joined command becomes `& { \u2026script\u2026 } -Root <path>`, and\n * `&` applies the named argument to the script block's `param` block \u2014 the\n * form #106 verified on a real 5.1 machine.\n *\n * Exported for the Windows-only integration spec, which replays this exact\n * text against a real `powershell.exe` 5.1 and derives the pre-fix 0.7.2\n * argv from it by removing the wrapper. `src/index.ts` does not re-export\n * it, so it is not part of the package's public API.\n */\nexport const WINDOWS_POWERSHELL_QUERY_COMMAND = `& { ${WINDOWS_POWERSHELL_QUERY_SCRIPT} }`\n\n/**\n * The only roots this tool will name on a `-Command` command line.\n *\n * `powershell.exe` re-parses everything after `-Command` as code, so a root\n * is handed over only when it is provably inert in that position: a hive\n * this file actually queries, then subkey components of plain path\n * characters \u2014 no spaces, quotes, subexpressions, or any other byte that\n * could change what the joined command does. Production roots are the fixed\n * {@link WINDOWS_REGISTRY_ROOTS}; anything else is refused before any\n * process starts, as \"we could not check\", never as executable text.\n */\nconst WINDOWS_REGISTRY_ROOT_PATTERN = /^HK(?:LM|CU)(?:\\\\[A-Za-z0-9._-]+)+$/u\n\n/**\n * One discovery subprocess's own limits; see {@link WorkBuddyAtRestKeyProviderOptions}.\n *\n * Governs the macOS discovery tools (Spotlight, plutil). The Windows registry\n * readers have their own, larger limit \u2014 {@link WINDOWS_REGISTRY_STEP_TIMEOUT_MS}.\n */\nexport const WORKBUDDY_DISCOVERY_STEP_TIMEOUT_MS = 3_000\n/** Whole-discovery budget, independent of the helper's own timeout. */\nexport const WORKBUDDY_DISCOVERY_BUDGET_MS = 10_000\n/**\n * One Windows registry subprocess's own limit: `reg.exe` or the PowerShell\n * 5.1 fallback.\n *\n * Why larger than the macOS step limit: `reg query <root> /s` over a\n * software-dense uninstall tree takes seconds, not milliseconds. On GitHub's\n * windows-2022 and windows-2025 runner images (hundreds of installed\n * programs) the plain HKLM uninstall read exceeds 3s while HKCU finishes in\n * ~20ms; on a real user machine the PowerShell fallback itself ran\n * 135\u2013270ms (#106). A 3s cap therefore cuts the HKLM read in half on\n * ordinary developer machines and reports the product absent when it is\n * merely slow to enumerate.\n *\n * Why this is safe to raise without touching the budget: the whole-discovery\n * budget ({@link WORKBUDDY_DISCOVERY_BUDGET_MS}, 10s) still bounds what a\n * user waits for \u2014 during a real discovery the budget abort remains the\n * effective ceiling, so this limit only decides whether a root that would\n * have finished inside the budget gets to finish, instead of being cut at 3s\n * mid-enumeration. For direct `queryUninstallRoot` callers (no outer\n * budget), this limit is the cap.\n *\n * Invariant, asserted by tests: never above the discovery budget. The\n * remaining known bound \u2014 a machine where every root is both slow *and*\n * non-ASCII, needing more than the budget in total \u2014 still ends as a safe\n * \"we could not check\" rather than a wrong answer.\n */\nexport const WINDOWS_REGISTRY_STEP_TIMEOUT_MS = 10_000\nconst MDFIND_MAX_OUTPUT_BYTES = 1024 * 1024\nconst PLUTIL_MAX_OUTPUT_BYTES = 64 * 1024\n\n/**\n * Why a discovery step could not produce an answer. Every one of these means\n * \"we do not know\", explicitly *not* \"the candidate does not exist\" \u2014 the\n * distinction is what keeps a half-finished check from being mistaken for a\n * unique candidate.\n */\nclass DiscoveryIncompleteError extends Error {}\n\n/** A discovered app: its `.app` bundle and the Electron binary inside it. */\ninterface DiscoveredApp {\n bundlePath: string\n electronPath: string\n /** Display version, best effort; absent when unreadable. */\n version?: string\n}\n\n/** Seams the discovery flow runs through, so tests never spawn a process. */\nexport interface WorkBuddyDiscoveryTools {\n /** Candidate `.app` bundles for the product's bundle id, or a throw for an unusable tool. */\n findApps: (signal: AbortSignal) => Promise<readonly string[]>\n /**\n * `CFBundleIdentifier` of a bundle, or `undefined` when the tool could not\n * read it \u2014 which is \"we could not check this candidate\", never \"it does not\n * match\". A successful read of a *different* id returns that id, and the\n * caller excludes the candidate.\n */\n bundleIdentifier: (bundlePath: string, signal: AbortSignal) => Promise<string | undefined>\n /** Display version, best effort; `undefined` when unavailable. */\n bundleVersion: (bundlePath: string, signal: AbortSignal) => Promise<string | undefined>\n}\n\n/** Windows-only seam for querying one uninstall registry root. */\nexport interface WorkBuddyWindowsDiscoveryTools {\n queryUninstallRoot: (root: string, signal: AbortSignal) => Promise<string>\n}\n\n/** Provider options. */\nexport interface WorkBuddyAtRestKeyProviderOptions {\n /**\n * Which product's Electron this provider resolves. Required and the only\n * source of product identity: it names the explicit-path env var, the bundle\n * id / registry name / exe basename discovery must match, and the platform\n * default. Without it the provider could not even decide which env var to\n * read \u2014 the discovery setting alone cannot carry this (both products are\n * `none` on Linux, yet each must read its own variable).\n */\n product: WorkBuddyElectronProduct\n /** Explicit Electron binary; overrides the platform default and env. */\n electronPath?: string\n /** Helper timeout in milliseconds; default 10s. */\n timeoutMs?: number\n /**\n * Where the payload comes from. Defaults to spawning WorkBuddy's own\n * Electron with `ELECTRON_RUN_AS_NODE=1`; tests supply a stand-in so no\n * test ever touches the real binary or a real key. Supplying this replaces\n * path *resolution* too, so tests about resolution use\n * {@link spawnHelper} instead.\n */\n source?: WorkBuddyKeyPayloadSource\n /**\n * Runs the helper at the resolved path. Distinct from {@link source}, which\n * replaces the whole payload path: this seam keeps resolution \u2014 explicit\n * config, platform default, discovery \u2014 real, so tests can exercise it\n * without spawning anything.\n */\n spawnHelper?: (electronPath: string) => Promise<string>\n /**\n * Automatic discovery budget; defaults to `'none'` (see\n * {@link WorkBuddyElectronDiscovery}). Passed explicitly per variant at the\n * composition root, never inferred from the environment.\n */\n discovery?: WorkBuddyElectronDiscovery\n /**\n * Platform default binary, consulted only when `discovery` is enabled and no\n * explicit path is configured. Injectable so tests can force the fallback\n * branch without moving the real app; `null` means \"no default here\".\n */\n defaultElectronPath?: string | undefined\n /** Discovery subprocesses; injectable so tests never spawn. */\n tools?: WorkBuddyDiscoveryTools\n /** Windows registry discovery subprocess; injectable so tests never spawn. */\n windowsTools?: WorkBuddyWindowsDiscoveryTools\n /** Platform override for deterministic discovery tests. */\n platform?: NodeJS.Platform\n /**\n * Total budget for one discovery run, covering the search and every\n * candidate check. Injectable so tests can exercise exhaustion without\n * waiting out the production 10s.\n */\n discoveryBudgetMs?: number\n}\n\n/**\n * The default discovery tools: Spotlight for the bundle, `/usr/bin/plutil` for\n * identity. Every failure that means \"we could not tell\" \u2014 a missing tool, a\n * timeout, an oversized answer \u2014 is raised as {@link DiscoveryIncompleteError}\n * so it can never be silently read as \"no such app\".\n *\n * `bundleId` is the product being searched for; the Spotlight query and the\n * caller's identity comparison both use it, so the two can never disagree\n * about which app they are looking for.\n */\nexport function workBuddyDiscoveryTools(bundleId: string): WorkBuddyDiscoveryTools {\n const runTool = (bin: string, args: readonly string[], maxBytes: number, signal: AbortSignal): Promise<string> =>\n new Promise<string>((resolve, reject) => {\n if (signal.aborted) {\n reject(new DiscoveryIncompleteError(`${bin} was not started: the discovery budget was already spent`))\n return\n }\n let settled = false\n const child = execFile(bin, [...args], { maxBuffer: maxBytes, timeout: WORKBUDDY_DISCOVERY_STEP_TIMEOUT_MS }, (error, stdout) => {\n if (settled) return\n settled = true\n if (error !== null && error !== undefined) {\n reject(new DiscoveryIncompleteError(`${bin} could not complete (${error.killed === true ? 'timed out' : String(error.code ?? 'unavailable')})`))\n return\n }\n resolve(stdout)\n })\n const abort = (): void => {\n if (settled) return\n settled = true\n child.kill()\n reject(new DiscoveryIncompleteError(`${bin} was abandoned: the discovery budget was spent`))\n }\n signal.addEventListener('abort', abort, { once: true })\n child.on('close', () => { signal.removeEventListener('abort', abort) })\n })\n\n return {\n findApps: async signal => {\n const out = await runTool(\n MDFIND_BIN,\n [`kMDItemCFBundleIdentifier == '${bundleId}'`],\n MDFIND_MAX_OUTPUT_BYTES,\n signal,\n )\n return out.split('\\n').map(line => line.trim()).filter(line => line.endsWith('.app'))\n },\n bundleIdentifier: async (bundlePath, signal) => {\n try {\n const out = await runTool(\n PLUTIL_BIN,\n ['-extract', 'CFBundleIdentifier', 'raw', '-o', '-', join(bundlePath, 'Contents', 'Info.plist')],\n PLUTIL_MAX_OUTPUT_BYTES,\n signal,\n )\n return out.trim()\n } catch {\n // An unreadable plist is \"we could not check this one\", not \"this one\n // does not match\" \u2014 the candidate stays unresolved and the whole\n // discovery reports incomplete rather than quietly dropping it.\n return undefined\n }\n },\n bundleVersion: async (bundlePath, signal) => {\n try {\n const out = await runTool(\n PLUTIL_BIN,\n ['-extract', 'CFBundleShortVersionString', 'raw', '-o', '-', join(bundlePath, 'Contents', 'Info.plist')],\n PLUTIL_MAX_OUTPUT_BYTES,\n signal,\n )\n const version = out.trim()\n return version === '' ? undefined : version\n } catch {\n return undefined\n }\n },\n }\n}\n\n/**\n * The Windows registry discovery tool. It is deliberately separate from the\n * macOS Spotlight/plutil seam: the two platforms have different identity and\n * candidate rules, and neither tool should accidentally become cross-platform.\n */\nexport function workBuddyWindowsDiscoveryTools(): WorkBuddyWindowsDiscoveryTools {\n const systemRoot = process.env.SystemRoot?.trim()\n const regPath = systemRoot === undefined || systemRoot === ''\n ? undefined\n : join(systemRoot, 'System32', 'reg.exe')\n /**\n * The fallback interpreter. Resolved by absolute path from SystemRoot, like\n * `reg.exe`: never through PATH, which a user can change.\n *\n * Windows PowerShell 5.1 ships with Windows, so unlike `pwsh` it can be\n * relied on; the script is written to its syntax (see\n * {@link WINDOWS_POWERSHELL_QUERY_SCRIPT}).\n */\n const powershellPath = systemRoot === undefined || systemRoot === ''\n ? undefined\n : join(systemRoot, WINDOWS_REGISTRY_RELATIVE_POWERSHELL)\n const runTool = (root: string, signal: AbortSignal): Promise<Buffer> => new Promise<Buffer>((resolve, reject) => {\n if (regPath === undefined) {\n reject(new DiscoveryIncompleteError('SystemRoot is not configured'))\n return\n }\n if (signal.aborted) {\n reject(new DiscoveryIncompleteError('reg.exe was not started: the discovery budget was already spent'))\n return\n }\n let settled = false\n const child = execFile(regPath, ['query', root, '/s'], {\n maxBuffer: WINDOWS_REGISTRY_OUTPUT_MAX_BYTES,\n timeout: WINDOWS_REGISTRY_STEP_TIMEOUT_MS,\n windowsHide: true,\n // Raw bytes, not a decode: whether this output is ambiguous is decided\n // from the bytes themselves (#88), so Node must not pick an encoding.\n encoding: 'buffer',\n }, (error, stdout, stderr) => {\n if (settled) return\n settled = true\n // `reg query` uses exit code 1 for more than a missing key. Only a\n // confirmed missing-key diagnostic is an empty result; every other\n // failure stays incomplete rather than becoming \"not installed\".\n //\n // Both supported diagnostics are ASCII in every code page, so reading\n // stderr as UTF-8 cannot change whether this regex matches; a diagnostic\n // that is not one of them stays incomplete, as before.\n if (error !== null && error !== undefined) {\n if (error.killed !== true && (error.code === 1 || error.code === '1')\n && windowsRegistryKeyMissing(stderr.toString('utf8'))) {\n resolve(Buffer.alloc(0))\n return\n }\n reject(new DiscoveryIncompleteError(`reg.exe could not complete (${error.killed === true ? 'timed out' : String(error.code ?? 'unavailable')})`))\n return\n }\n resolve(stdout)\n })\n const abort = (): void => {\n if (settled) return\n settled = true\n child.kill()\n reject(new DiscoveryIncompleteError('reg.exe was abandoned: the discovery budget was spent'))\n }\n signal.addEventListener('abort', abort, { once: true })\n child.on('close', () => { signal.removeEventListener('abort', abort) })\n })\n\n /**\n * Re-read one root through PowerShell's Unicode registry API (#88).\n *\n * Returns the same column-shaped document the `reg.exe` path produces, so\n * the caller's parser and candidate checks apply unchanged. Every failure\n * that means \"we could not tell\" is a {@link DiscoveryIncompleteError}, and\n * a root that simply does not exist yields an empty document \u2014 one of the\n * three roots being absent is normal and must not fail the search.\n */\n const runFallback = (root: string, signal: AbortSignal): Promise<string> => new Promise<string>((resolve, reject) => {\n // Guarded before anything starts: this root is about to ride a command\n // line that is re-parsed as code, so it must be a plain path (see\n // WINDOWS_REGISTRY_ROOT_PATTERN).\n if (!WINDOWS_REGISTRY_ROOT_PATTERN.test(root)) {\n reject(new DiscoveryIncompleteError('the registry root was not a plain HKLM/HKCU path this tool may query'))\n return\n }\n if (powershellPath === undefined) {\n reject(new DiscoveryIncompleteError('SystemRoot is not configured'))\n return\n }\n if (signal.aborted) {\n reject(new DiscoveryIncompleteError('powershell.exe was not started: the discovery budget was already spent'))\n return\n }\n let settled = false\n const child = execFile(powershellPath, [\n '-NoProfile',\n '-NonInteractive',\n '-Command',\n WINDOWS_POWERSHELL_QUERY_COMMAND,\n '-Root',\n root,\n ], {\n maxBuffer: WINDOWS_REGISTRY_OUTPUT_MAX_BYTES,\n timeout: WINDOWS_REGISTRY_STEP_TIMEOUT_MS,\n windowsHide: true,\n encoding: 'utf8',\n }, (error, stdout) => {\n if (settled) return\n settled = true\n if (error !== null && error !== undefined) {\n // Classification is by exit code, never by stderr text: these\n // diagnostics are written by PowerShell and may themselves be\n // unreadable in a non-UTF-8 console.\n const code = error.killed === true ? undefined : Number(error.code)\n if (code === WINDOWS_POWERSHELL_ROOT_ABSENT) {\n resolve('')\n return\n }\n if (code === WINDOWS_POWERSHELL_ROOT_UNREADABLE) {\n reject(new DiscoveryIncompleteError(`powershell.exe could not read the registry root ${root}`))\n return\n }\n reject(new DiscoveryIncompleteError(`powershell.exe could not complete (${error.killed === true ? 'timed out' : String(error.code ?? 'unavailable')})`))\n return\n }\n const records = parseWindowsUninstallJson(stdout)\n if (records === undefined) {\n reject(new DiscoveryIncompleteError('powershell.exe output was not the expected registry document'))\n return\n }\n resolve(records)\n })\n const abort = (): void => {\n if (settled) return\n settled = true\n child.kill()\n reject(new DiscoveryIncompleteError('powershell.exe was abandoned: the discovery budget was spent'))\n }\n signal.addEventListener('abort', abort, { once: true })\n child.on('close', () => { signal.removeEventListener('abort', abort) })\n })\n\n return {\n queryUninstallRoot: async (root, signal) => {\n const raw = await runTool(root, signal)\n // Fall back only when the primary output cannot be read unambiguously\n // (#88). The trigger is a property of the *bytes*, never of a decoding:\n // ASCII-only output means every code page agrees, so nothing is\n // ambiguous; one byte at or above 0x80 means the code page is\n // unknowable from the bytes, so no decode of them can be trusted.\n //\n // Checking for U+FFFD instead would have been wrong: 1920 distinct GBK\n // byte pairs decode as valid UTF-8 with no replacement character at all,\n // so the reported case could pass silently. Byte range has no such blind\n // spot.\n //\n // Known cost, deliberately kept (recorded as an independent follow-up to\n // #105/#106/#107, not changed in the hotfix): any non-ASCII byte\n // anywhere in the root's output \u2014 another product's localized\n // DisplayName included \u2014 re-reads the whole root through PowerShell.\n // Narrowing the trigger to this product's own entries would mean\n // associating value lines with their key headers before the bytes can\n // be decoded, and a wrong association silently drops a real Chinese\n // WorkBuddy path back into the code-page trap #88 fixed. Until that\n // association can be made safely, the over-trigger costs one extra\n // process per affected root, not correctness.\n if (isAsciiOnly(raw)) return raw.toString('utf8')\n return await runFallback(root, signal)\n },\n }\n}\n\n/**\n * Whether every byte is ASCII, the one case where a decode cannot be wrong.\n *\n * @param bytes - the child's raw stdout.\n */\nfunction isAsciiOnly(bytes: Buffer): boolean {\n for (const byte of bytes) {\n if (byte >= 0x80) return false\n }\n return true\n}\n\n/**\n * Turn the fallback's JSON into the same column-shaped document\n * {@link parseWindowsRegistryOutput} already consumes.\n *\n * Re-encoding into the `reg query` text form on purpose: the parser and\n * {@link parseWindowsDisplayIcon} carry the candidate-quoting rules that are\n * shared with existing tests, and the seam between this tool and the provider\n * is a string. Records carrying neither value are skipped, and the key name is\n * synthetic because only the values are read.\n *\n * @param output - the child's UTF-8 stdout.\n * @returns the document, or `undefined` when it was not the expected JSON.\n */\nfunction parseWindowsUninstallJson(output: string): string | undefined {\n let document: unknown\n try {\n document = JSON.parse(output)\n } catch {\n return undefined\n }\n // `ConvertTo-Json` collapses a one-element array into a bare object.\n const rows = Array.isArray(document) ? document : [document]\n const lines: string[] = []\n for (const [index, row] of rows.entries()) {\n if (typeof row !== 'object' || row === null) continue\n const record = row as Record<string, unknown>\n const displayName = record['displayName']\n const displayIcon = record['displayIcon']\n if (typeof displayName !== 'string' && typeof displayIcon !== 'string') continue\n lines.push(`HKEY_CURRENT_USER\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall\\\\{PS-${String(index)}}`)\n if (typeof displayName === 'string') lines.push(` DisplayName REG_SZ ${displayName}`)\n if (typeof displayIcon === 'string') lines.push(` DisplayIcon REG_SZ ${displayIcon}`)\n }\n return lines.join('\\r\\n')\n}\n\n/**\n * In-memory protector-key resolver: one spawn per key id, single-flight, never\n * persisted. The cache is keyed by the id envelopes ask for, so an envelope\n * sealed under a rotated key triggers exactly one fresh resolution.\n */export class WorkBuddyAtRestKeyProvider {\n /**\n * The explicit binary, when one was configured. `undefined` here means \"the\n * caller did not name one\", which is what lets discovery run \u2014 an explicit\n * path that turns out to be unusable is an error, never a reason to look for\n * a different app.\n */\n private readonly explicitPath: string | undefined\n private readonly product: WorkBuddyElectronProduct\n private readonly defaultPath: string | undefined\n private readonly discovery: WorkBuddyElectronDiscovery\n private readonly tools: WorkBuddyDiscoveryTools\n private readonly windowsTools: WorkBuddyWindowsDiscoveryTools\n private readonly platform: NodeJS.Platform\n private readonly discoveryBudgetMs: number\n private readonly timeoutMs: number\n private readonly source: WorkBuddyKeyPayloadSource\n private readonly spawnHelper: (electronPath: string) => Promise<string>\n /**\n * The path discovery settled on, cached only on success. A failure leaves\n * this unset so the next attempt tries again \u2014 the user may install or move\n * the app without restarting DSH.\n */\n private discoveredPath: string | undefined\n private cache: ResolvedKey | undefined\n private inflight: Promise<ResolvedKey> | undefined\n\n constructor(options: WorkBuddyAtRestKeyProviderOptions) {\n this.product = options.product\n const fromEnv = process.env[options.product.envVar]?.trim()\n const envPath = fromEnv === undefined || fromEnv === '' ? undefined : fromEnv\n // Explicit sources are authoritative and mutually exclusive with\n // discovery: naming a binary means \"use this one\", so an unusable one is\n // an error, not an invitation to go looking for another app.\n this.explicitPath = options.electronPath ?? envPath\n this.discovery = options.discovery ?? 'none'\n this.platform = options.platform ?? process.platform\n this.defaultPath = this.discovery === 'none'\n ? undefined\n : options.defaultElectronPath === undefined\n ? defaultWorkBuddyElectronPath(options.product, this.platform)\n : options.defaultElectronPath ?? undefined\n this.tools = options.tools ?? workBuddyDiscoveryTools(options.product.macOS.bundleId)\n this.windowsTools = options.windowsTools ?? workBuddyWindowsDiscoveryTools()\n this.discoveryBudgetMs = options.discoveryBudgetMs ?? WORKBUDDY_DISCOVERY_BUDGET_MS\n this.timeoutMs = options.timeoutMs ?? 10_000\n this.spawnHelper = options.spawnHelper ?? (path => this.spawnAt(path))\n this.source = options.source ?? (() => this.spawnPayload())\n }\n\n /**\n * The binary the default helper would use, for diagnostics.\n *\n * Reports a *discovery result* once one exists, so diagnostics describe what\n * would actually run rather than the default that was bypassed. Discovery\n * itself stays in {@link resolveElectronPath}: this accessor never triggers a\n * search (the constructor must remain I/O-free, and callers may ask before\n * any resolution has happened).\n */\n helperPath(): string | undefined {\n if (this.explicitPath !== undefined) return this.explicitPath\n if (this.discovery === 'none') return undefined\n return this.discoveredPath ?? this.defaultPath\n }\n\n /**\n * A protector key matching one of the requested envelope key ids. The first\n * id the cache answers wins; otherwise one spawn resolves the current key,\n * which must match a request \u2014 a mismatch means the envelopes were sealed by\n * a different install than the one this machine now runs, and no key we can\n * reach will open them.\n */\n async protectorKeyFor(requested: readonly string[]): Promise<Buffer> {\n if (requested.length === 0) {\n throw new WorkBuddyElectronPathError(\n 'encrypted-credential-unreadable',\n 'encrypted desktop credential carries no key ids',\n )\n }\n const cached = this.cache\n if (cached !== undefined && requested.includes(cached.keyId)) return cached.key\n this.inflight ??= this.source().then(text => this.ingest(text))\n .finally(() => {\n this.inflight = undefined\n })\n const resolved = await this.inflight\n if (!requested.includes(resolved.keyId)) {\n throw new WorkBuddyElectronPathError(\n 'encrypted-credential-unreadable',\n `WorkBuddy's current at-rest key (id ${resolved.keyId}) does not match the credential's envelope (id ${requested.join(' or ')});`\n + ' the desktop credential was sealed by a different WorkBuddy installation',\n )\n }\n return resolved.key\n }\n\n private ingest(text: string): ResolvedKey {\n const payload = parseAtRestPayload(text)\n if (payload === undefined) {\n throw new WorkBuddyElectronPathError(\n 'encrypted-credential-unreadable',\n 'WorkBuddy key helper returned an unusable at-rest payload (expected {version:1, atRestSecretKey})',\n )\n }\n const key = deriveProtectorKey(payload.atRestSecretKey)\n const resolved: ResolvedKey = {\n key,\n keyId: createHash('sha256').update(key).digest('hex').slice(0, 16),\n }\n this.cache = resolved\n return resolved\n }\n\n /**\n * The binary to spawn, or a diagnosable error saying why there is none.\n *\n * Order is the contract: an explicit path is used as-is and never falls back;\n * discovery runs only for a provider that was configured for it, and only\n * after the platform default has been tried and found unusable.\n */\n private async resolveElectronPath(): Promise<string> {\n if (this.explicitPath !== undefined) {\n if (!isExecutable(this.explicitPath)) {\n throw new WorkBuddyElectronPathError(\n 'electron-path-invalid',\n `the configured ${this.product.productName} Electron binary is not available at ${this.explicitPath};`\n + ` check ${this.product.envVar} or unset it to let the plugin look for the app itself`,\n )\n }\n return this.explicitPath\n }\n if (this.discovery === 'none') {\n // A platform without a verified layout: \"not configured\", never \"we\n // searched and failed\".\n throw new WorkBuddyElectronPathError(\n 'electron-binary-unavailable',\n `no ${this.product.productName} Electron binary is configured for this platform;`\n + ` set ${this.product.envVar} to the app's Electron binary`,\n )\n }\n // The default path is the ordinary case and costs one stat; discovery is\n // reserved for the installations the default misses.\n if (this.defaultPath !== undefined && isExecutable(this.defaultPath)) return this.defaultPath\n // A previously discovered path is re-checked rather than trusted: the app\n // may have been moved or removed since, and a stale path must not win.\n if (this.discoveredPath !== undefined) {\n if (isExecutable(this.discoveredPath)) return this.discoveredPath\n this.discoveredPath = undefined\n }\n const found = this.discovery === 'macos-workbuddy'\n ? await this.discoverMacosApp()\n : await this.discoverWindowsApp()\n this.discoveredPath = found\n return found\n }\n\n /**\n * Resolve this product's app through Spotlight, then prove each candidate's\n * identity before it can be executed.\n *\n * The whole flow shares one budget: a hang in one candidate must not extend\n * the wait for the others, and running out of budget is reported as an\n * unfinished check rather than an absent app.\n */\n private async discoverMacosApp(): Promise<string> {\n if (this.platform !== 'darwin') {\n throw new WorkBuddyElectronPathError(\n 'electron-binary-unavailable',\n `no ${this.product.productName} Electron binary is configured for this platform;`\n + ` set ${this.product.envVar} to the app's Electron binary`,\n )\n }\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), this.discoveryBudgetMs)\n try {\n let candidates: readonly string[]\n try {\n candidates = await this.tools.findApps(controller.signal)\n } catch {\n throw discoveryIncomplete(this.product.productName, 'the app search did not complete')\n }\n // Several Spotlight rows can name one bundle (path aliases, the\n // /System/Volumes/Data view). Identity + realpath collapse those into\n // one candidate; only genuinely distinct apps may count as \"more than\n // one\", or a single app would look ambiguous.\n const seen = new Map<string, DiscoveredApp>()\n let unresolved = false\n for (const candidate of candidates) {\n // A Spotlight index keeps rows for apps deleted since the last sweep,\n // and a stale row is a *decidable* exclusion: the candidate is gone,\n // which is not the same as \"we could not check it\". Skipping it here\n // is what stops one dead row from sinking a live app beside it \u2014 the\n // plan's \"\u660E\u786E\u4E0D\u53EF\u7528 \u2192 \u6392\u9664\u8BE5\u5019\u9009\" case (issue #48 \u00A73.7).\n //\n // Only ENOENT qualifies. `existsSync` is not usable here: it answers\n // `false` for *any* error, so an EACCES/EPERM parent (or an\n // ENAMETOOLONG path) would be read as \"this app was deleted\" and a\n // live sibling would be chosen over a candidate we merely could not\n // inspect. `statSync` distinguishes them, and anything other than a\n // confirmed absence stays unresolved.\n try {\n statSync(candidate)\n } catch (error: unknown) {\n if (isENOENT(error)) continue\n unresolved = true\n continue\n }\n let bundleIdentifier: string | undefined\n try {\n bundleIdentifier = await this.tools.bundleIdentifier(candidate, controller.signal)\n } catch {\n unresolved = true\n continue\n }\n if (bundleIdentifier === undefined) {\n unresolved = true\n continue\n }\n if (bundleIdentifier !== this.product.macOS.bundleId) continue\n const electronPath = join(candidate, 'Contents', 'MacOS', 'Electron')\n if (!isExecutable(electronPath)) continue\n let identity: string\n try {\n identity = realpathSync(candidate)\n } catch {\n identity = candidate\n }\n if (seen.has(identity)) continue\n let version: string | undefined\n try {\n version = await this.tools.bundleVersion(candidate, controller.signal)\n } catch {\n // Version is display-only; an unreadable one must not sink an\n // otherwise identified candidate.\n version = undefined\n }\n seen.set(identity, { bundlePath: candidate, electronPath, ...version === undefined ? {} : { version } })\n }\n if (seen.size > 1) {\n const listed = [...seen.values()]\n .map(app => ` - ${app.bundlePath}${app.version === undefined ? '' : ` (${app.version})`}`)\n .join('\\n')\n throw new WorkBuddyElectronPathError(\n 'electron-binary-ambiguous',\n `more than one ${this.product.productName} application was found, so none was chosen:\\n${listed}\\n`\n + ` set ${this.product.envVar} to the one to use`,\n )\n }\n // A candidate nobody could check might have been a second copy, so its\n // existence forbids claiming the rest are unique. This is the difference\n // between \"we know there is exactly one\" and \"we only found one of the\n // ones we could read\" (\u00A73.4).\n if (unresolved) throw discoveryIncomplete(this.product.productName, 'some candidates could not be checked')\n if (seen.size === 0) {\n throw new WorkBuddyElectronPathError(\n 'electron-binary-not-found',\n `no ${this.product.productName} application was found in the default location or the system index;`\n + ' if it is installed elsewhere, it may not be indexed yet;'\n + ` set ${this.product.envVar} to the app's Electron binary`,\n )\n }\n return [...seen.values()][0]!.electronPath\n } finally {\n clearTimeout(timer)\n controller.abort()\n }\n }\n\n /**\n * Resolve this product's app through Windows uninstall records. Registry\n * entries provide hints, not trust: every DisplayIcon candidate must still\n * be the product's Electron binary with the known Electron layout before\n * execution.\n */\n private async discoverWindowsApp(): Promise<string> {\n if (this.platform !== 'win32') {\n throw new WorkBuddyElectronPathError(\n 'electron-binary-unavailable',\n `no ${this.product.productName} Electron binary is configured for this platform;`\n + ` set ${this.product.envVar} to the app's Electron binary`,\n )\n }\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), this.discoveryBudgetMs)\n try {\n const candidates: string[] = []\n let unresolved = false\n for (const root of WINDOWS_REGISTRY_ROOTS) {\n let output: string\n try {\n output = await this.windowsTools.queryUninstallRoot(root, controller.signal)\n } catch {\n unresolved = true\n continue\n }\n const parsed = parseWindowsRegistryOutput(output, this.product.windows.displayNamePattern)\n candidates.push(...parsed.candidates)\n unresolved ||= parsed.incomplete\n }\n\n const seen = new Map<string, string>()\n const rejected: string[] = []\n for (const candidate of new Set(candidates)) {\n const inspection = inspectWindowsElectronCandidate(candidate, this.platform, this.product.windows.exeBasename)\n if (inspection === 'unresolved') {\n unresolved = true\n continue\n }\n if (inspection === undefined) {\n rejected.push(candidate)\n continue\n }\n seen.set(inspection.identity, inspection.electronPath)\n }\n if (unresolved) throw discoveryIncomplete(this.product.productName, 'some registry entries or candidates could not be checked')\n if (seen.size > 1) {\n const listed = [...seen.values()].map(path => ` - ${path}`).join('\\n')\n throw new WorkBuddyElectronPathError(\n 'electron-binary-ambiguous',\n `more than one ${this.product.productName} application was found, so none was chosen:\\n${listed}\\n`\n + ` set ${this.product.envVar} to the one to use`,\n )\n }\n if (seen.size === 0) {\n // #66: \"nothing was found\" and \"candidates were found but each failed\n // the layout check\" are different diagnoses; the old single wording\n // claimed the former even when the latter was true, sending users\n // hunting for an install that was right there. The counts stay, the\n // candidate paths deliberately do not \u2014 this text reaches /status and\n // doctor, and local install paths are not for every loopback reader.\n const message = rejected.length === 0\n ? `no usable ${this.product.productName} Electron binary was found in the default location or Windows uninstall records;`\n + ` set ${this.product.envVar} to the app's Electron binary`\n : `Windows uninstall records found ${rejected.length} ${this.product.productName} candidate${rejected.length > 1 ? 's' : ''},`\n + ` but ${rejected.length > 1 ? 'none' : 'it'} did not match the expected app layout (the app's exe beside a version file and resources\\\\app.asar);`\n + ` set ${this.product.envVar} to the installed app's executable to use it`\n throw new WorkBuddyElectronPathError('electron-binary-not-found', message)\n }\n return [...seen.values()][0]!\n } finally {\n clearTimeout(timer)\n controller.abort()\n }\n }\n\n private async spawnPayload(): Promise<string> {\n return await this.spawnHelper(await this.resolveElectronPath())\n }\n\n private async spawnAt(electronPath: string): Promise<string> {\n return await new Promise<string>((resolve, reject) => {\n execFile(electronPath, [HELPER_SCRIPT_ARGUMENT_FLAG, HELPER_SCRIPT], {\n timeout: this.timeoutMs,\n maxBuffer: 1024 * 1024,\n windowsHide: true,\n env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },\n }, (error, stdout) => {\n if (error !== null && error !== undefined) {\n // Code and reason only: stdout/stderr can carry paths or crash dumps,\n // and the payload must never appear in a message.\n const reason = error.killed === true\n ? `timed out or was killed after ${String(this.timeoutMs)}ms`\n : error.code !== undefined\n ? `exited with code ${String(error.code)}`\n : 'could not be started'\n reject(new WorkBuddyElectronPathError(\n 'encrypted-credential-unreadable',\n `the WorkBuddy key helper (${electronPath}) ${reason}`,\n ))\n return\n }\n const output = stdout.trim()\n if (output === '') {\n reject(new WorkBuddyElectronPathError(\n 'encrypted-credential-unreadable',\n `the WorkBuddy key helper (${electronPath}) produced no payload`,\n ))\n return\n }\n resolve(output)\n })\n })\n }\n}\n\n/** Only known missing-key diagnostics can safely make a failed query empty. */\nfunction windowsRegistryKeyMissing(stderr: string): boolean {\n const detail = stderr.trim()\n return /^ERROR:\\s*The system was unable to find the specified registry key or value\\.?$/iu.test(detail)\n || /^\u9519\u8BEF[:\uFF1A]\\s*\u7CFB\u7EDF\u627E\u4E0D\u5230\u6307\u5B9A\u7684\u6CE8\u518C\u8868\u9879\u6216\u503C[\u3002.]?$/u.test(detail)\n}\n\n/**\n * Parse the value columns emitted by `reg query ... /s`.\n *\n * Entries are filtered by the product's DisplayName pattern *before* the\n * DisplayIcon is judged, so another product's records \u2014 however broken \u2014 are\n * excluded as decisively not ours and can never mark this product's search\n * incomplete.\n */\nfunction parseWindowsRegistryOutput(output: string, displayNamePattern: RegExp): { candidates: string[], incomplete: boolean } {\n const entries = new Map<string, { displayName?: string, displayIcon?: string }>()\n let currentKey: string | undefined\n for (const line of output.split(/\\r?\\n/u)) {\n const keyMatch = /^\\s*(HKEY_[^\\r\\n]+?)\\s*$/iu.exec(line)\n if (keyMatch !== null) {\n currentKey = keyMatch[1]!\n entries.set(currentKey, {})\n continue\n }\n if (currentKey === undefined) continue\n const valueMatch = /^\\s+(DisplayName|DisplayIcon)\\s+REG_[A-Z0-9_]+\\s*(.*?)\\s*$/iu.exec(line)\n if (valueMatch === null) continue\n const entry = entries.get(currentKey)\n if (entry === undefined) continue\n const value = valueMatch[2] ?? ''\n if (valueMatch[1]!.toLowerCase() === 'displayname') entry.displayName = value\n else entry.displayIcon = value\n }\n const candidates: string[] = []\n let incomplete = false\n for (const entry of entries.values()) {\n if (entry.displayName === undefined) continue\n if (!displayNamePattern.test(entry.displayName.trim())) continue\n const displayIcon = entry.displayIcon === undefined ? undefined : parseWindowsDisplayIcon(entry.displayIcon)\n if (displayIcon === undefined) incomplete = true\n else candidates.push(displayIcon)\n }\n return { candidates, incomplete }\n}\n\n/** Read a quoted DisplayIcon path and remove the Windows icon-index suffix. */\nfunction parseWindowsDisplayIcon(value: string): string | undefined {\n const raw = value.trim()\n let path: string\n if (raw.startsWith('\"')) {\n const closingQuote = raw.indexOf('\"', 1)\n if (closingQuote < 0) return undefined\n const suffix = raw.slice(closingQuote + 1).trim()\n if (suffix !== '' && !/^,\\d+$/u.test(suffix)) return undefined\n path = raw.slice(1, closingQuote).replace(/,\\d+$/u, '')\n } else {\n const match = /^(.+?\\.exe)(?:,\\d+)?$/iu.exec(raw)\n if (match === null) return undefined\n path = match[1]!\n }\n path = path.trim()\n return /\\.exe$/iu.test(path) ? path : undefined\n}\n\ninterface WindowsCandidateInspection {\n electronPath: string\n identity: string\n}\n\n/**\n * Validate the known Windows layout for the product's exe. `undefined` is a\n * decidable exclusion; `unresolved` is reserved for errors that prevent\n * checking.\n */\nfunction inspectWindowsElectronCandidate(\n electronPath: string,\n platform: NodeJS.Platform,\n exeBasename: string,\n): WindowsCandidateInspection | 'unresolved' | undefined {\n if (platform !== 'win32' || basename(electronPath).toLowerCase() !== exeBasename) return undefined\n let binaryStat\n try {\n binaryStat = statSync(electronPath)\n } catch (error: unknown) {\n return isENOENT(error) ? undefined : 'unresolved'\n }\n if (!binaryStat.isFile()) return undefined\n try {\n accessSync(electronPath, constants.X_OK)\n } catch (error: unknown) {\n return isENOENT(error) ? undefined : 'unresolved'\n }\n\n const installRoot = dirname(electronPath)\n let version: string\n try {\n version = readFileSync(join(installRoot, 'version'), 'utf8').trim()\n } catch (error: unknown) {\n return isENOENT(error) ? undefined : 'unresolved'\n }\n if (!WINDOWS_ELECTRON_VERSION_PATTERN.test(version)) return undefined\n\n try {\n // The archive path must not go through fs.stat: under an Electron host,\n // asar interception stats app.asar as a directory (isFile() false, size\n // 0), which deterministically excluded every registry candidate (#66).\n // Listing the real resources directory is asar-independent \u2014 identical\n // on plain Node and inside Electron.\n if (!readdirSync(join(installRoot, 'resources')).includes('app.asar')) return undefined\n } catch (error: unknown) {\n return isENOENT(error) ? undefined : 'unresolved'\n }\n\n let identity: string\n try {\n identity = realpathSync(electronPath)\n } catch (error: unknown) {\n return isENOENT(error) ? undefined : 'unresolved'\n }\n return {\n electronPath,\n // Windows paths are case-insensitive even when a registry entry preserved\n // a different casing from the filesystem spelling.\n identity: platform === 'win32' ? identity.toLowerCase() : identity,\n }\n}\n\n/** Whether a path exists and is executable; never throws. */\nfunction isExecutable(path: string): boolean {\n try {\n accessSync(path, constants.X_OK)\n return true\n } catch {\n return false\n }\n}\n\n/**\n * A failure the card must be able to classify. The code travels with the error\n * so the store can promote it to `reasonCode` without re-deriving the cause\n * from prose.\n */\nexport class WorkBuddyElectronPathError extends Error {\n readonly reasonCode: WorkBuddySignedOutReasonCode\n\n constructor(reasonCode: WorkBuddySignedOutReasonCode, message: string) {\n super(message)\n this.name = 'WorkBuddyElectronPathError'\n this.reasonCode = reasonCode\n }\n}\n\n/** Read the reason code off an arbitrary thrown value, when it carries one. */\nexport function reasonCodeOf(error: unknown): WorkBuddySignedOutReasonCode | undefined {\n return error instanceof WorkBuddyElectronPathError ? error.reasonCode : undefined\n}\n\n/** Whether a filesystem error reports an absent path (`existsSync` cannot tell). */\nfunction isENOENT(error: unknown): boolean {\n return (error as NodeJS.ErrnoException | null)?.code === 'ENOENT'\n}\n\nfunction discoveryIncomplete(productName: string, detail: string): WorkBuddyElectronPathError {\n return new WorkBuddyElectronPathError(\n 'electron-discovery-incomplete',\n `the ${productName} application search did not finish (${detail});`\n + ' this is not proof that the app is missing',\n )\n}\n\n/**\n * The helper: run inside WorkBuddy's Electron as plain Node, where the\n * private `workbuddyStorage` binding exists, and print only the payload. It\n * writes nothing else, so whatever reaches stdout is the payload.\n */\nconst HELPER_SCRIPT = 'process.stdout.write(String(process._linkedBinding(\"electron_browser_workbuddy_storage\").loggerGet()))'\nconst HELPER_SCRIPT_ARGUMENT_FLAG = '-e'\n", "/**\n * WorkBuddy credential resolution. The primary source is the WorkBuddy\n * desktop app's own auth file, read-only; a plugin-owned copy under\n * `$DSH_HOME` holds token refreshes so the desktop file is never written.\n * The effective credential is whichever of the two expires later, so a\n * refresh by either side wins.\n *\n * @module dsh-workbuddy-connect/auth\n */\n\nimport { readFile, rm } from 'node:fs/promises'\nimport { homedir, release } from 'node:os'\nimport { basename, dirname, join } from 'node:path'\nimport { withFileLock, writeFileAtomic } from '@deepseek-ai/dsh-atomic-write'\nimport { resolveDshHome } from '@deepseek-ai/dsh-home-paths'\nimport { regionOf } from './upstream.ts'\nimport {\n WorkBuddyAtRestKeyProvider,\n WorkBuddyElectronPathError,\n classifyDesktopAuthDocument,\n keyIdsOf,\n openAuthField,\n reasonCodeOf,\n unwrapDesktopAuthDocument,\n} from './desktop-credential-protection.ts'\nimport type { DesktopAuthClassification, DesktopAuthFormat } from './desktop-credential-protection.ts'\nimport type { WorkBuddySignedOutReasonCode } from './status-paths.ts'\nimport { CN_VARIANT, electronProfileFor, type WorkBuddyVariant } from './variants.ts'\nimport type { WorkBuddyRefreshOutcome } from './upstream.ts'\n\n/** Normalized WorkBuddy credential, timestamps in epoch milliseconds. */\nexport interface WorkBuddyCredential {\n accessToken: string\n refreshToken: string\n expiresAtMs: number\n refreshExpiresAtMs?: number\n domain: string\n uid: string\n enterpriseId?: string\n nickname?: string\n /** Which storage the credential was read from; refreshes are always `dsh`. */\n source: 'desktop' | 'dsh'\n}\n\n/** Read-only sign-in summary for status and doctor output. */\nexport interface WorkBuddyAuthStatus {\n state: 'signed-in' | 'signed-out'\n expiresAtMs?: number\n refreshExpiresAtMs?: number\n nickname?: string\n domain?: string\n source?: 'desktop' | 'dsh'\n /**\n * Why no credential is usable, when the reason is diagnosable rather than\n * \"nobody is signed in\" \u2014 a region mismatch being the case that matters.\n * Present only on `signed-out`, and never a substitute for fixing the file.\n */\n reason?: string\n /**\n * Machine-readable companion to {@link reason}, for callers that must branch\n * on the cause. Never derived by matching `reason` text.\n */\n reasonCode?: WorkBuddySignedOutReasonCode\n}\n\n/** Constructor options; only {@link refresh} is required. */\nexport interface WorkBuddyStoreOptions {\n variant?: WorkBuddyVariant\n /** Explicit desktop auth-file path, overriding env and platform defaults. */\n desktopPath?: string\n /** Explicit plugin-owned copy path, defaulting under `$DSH_HOME`. */\n ownPath?: string\n /** Performs the upstream token refresh. */\n refresh: (credential: WorkBuddyCredential) => Promise<WorkBuddyRefreshOutcome>\n /** Refresh this long before actual expiry; default five minutes. */\n refreshMarginMs?: number\n /**\n * Resolver for WorkBuddy 5.6's at-rest protector key, needed when the\n * desktop file stores encrypted token fields. Defaults to the real\n * provider, which spawns the WorkBuddy Electron binary; tests stand in a\n * stub. Structural so a store never depends on how the key is reached.\n */\n keyProvider?: Pick<WorkBuddyAtRestKeyProvider, 'protectorKeyFor' | 'helperPath'>\n}\n\n/** Basename of the plugin-owned credential copy inside the Harness home. */\nexport const WORKBUDDY_AUTH_FILENAME = '.workbuddy-auth.json'\n\n/** Env variable that overrides the desktop auth-file location. */\nexport const WORKBUDDY_AUTH_FILE_ENV = 'WORKBUDDY_AUTH_FILE'\n\n/** Current on-disk format of the plugin-owned copy; readers reject others. */\nconst OWN_FORMAT_VERSION = 1\n\ninterface OwnDocument {\n version: typeof OWN_FORMAT_VERSION\n credential: WorkBuddyCredential\n}\n\n/** Plugin-owned copy path inside the Harness home. */\nexport function workbuddyOwnAuthPath(): string {\n return join(resolveDshHome(), WORKBUDDY_AUTH_FILENAME)\n}\n\nconst DESKTOP_AUTH_RELATIVE_PATH = ['CodeBuddyExtension', 'Data', 'Public', 'auth', 'workbuddy-desktop.info'] as const\n\n/** Whether this Linux process is running inside Windows Subsystem for Linux. */\nfunction isWsl(): boolean {\n if (process.platform !== 'linux') return false\n if (process.env['WSL_DISTRO_NAME'] !== undefined || process.env['WSL_INTEROP'] !== undefined) return true\n return release().toLowerCase().includes('microsoft')\n}\n\n/** Convert a Windows drive path to WSL's conventional `/mnt/<drive>` form. */\nfunction windowsPathForWsl(value: string | undefined): string | undefined {\n const path = value?.trim()\n if (!path) return undefined\n if (path.startsWith('/')) return path\n const drivePath = /^([a-z]):[\\\\/](.*)$/iu.exec(path)\n if (drivePath === null) return undefined\n return join('/mnt', drivePath[1]!.toLowerCase(), ...drivePath[2]!.split(/[\\\\/]+/u))\n}\n\n/** Windows desktop credential candidates visible from a WSL process. */\nfunction wslDesktopAuthCandidates(home: string): string[] {\n const profile = windowsPathForWsl(process.env['USERPROFILE'])\n ?? join('/mnt/c/Users', basename(home))\n const localAppData = windowsPathForWsl(process.env['LOCALAPPDATA'])\n ?? join(profile, 'AppData', 'Local')\n const roamingAppData = windowsPathForWsl(process.env['APPDATA'])\n ?? join(profile, 'AppData', 'Roaming')\n return [\n join(localAppData, ...DESKTOP_AUTH_RELATIVE_PATH),\n join(roamingAppData, ...DESKTOP_AUTH_RELATIVE_PATH),\n ]\n}\n\n/**\n * Platform-default candidates for the WorkBuddy desktop app's auth file, in\n * probe order. Windows probes both AppData roots: current builds write under\n * `%LOCALAPPDATA%` (Local), older ones under `%APPDATA%` (Roaming). Linux\n * probes both XDG bases \u2014 most distributions write under the config home,\n * but UOS/deepin builds write under the data home (issue #43), and probing\n * only one silently reads a signed-in app as signed out. WSL probes those\n * same Windows locations through its mounted Windows profile before the\n * native Linux locations.\n */\nexport function defaultDesktopAuthCandidates(): string[] {\n const home = homedir()\n if (process.platform === 'darwin') {\n return [join(home, 'Library', 'Application Support', 'CodeBuddyExtension', 'Data', 'Public', 'auth', 'workbuddy-desktop.info')]\n }\n if (process.platform === 'win32') {\n return [\n join(home, 'AppData', 'Local', 'CodeBuddyExtension', 'Data', 'Public', 'auth', 'workbuddy-desktop.info'),\n join(home, 'AppData', 'Roaming', 'CodeBuddyExtension', 'Data', 'Public', 'auth', 'workbuddy-desktop.info'),\n ]\n }\n if (process.platform === 'linux') {\n // An XDG override is adopted only as a non-empty absolute path; an\n // invalid value falls back to the platform default rather than joining a\n // relative path onto it.\n const configHome = xdgBase('XDG_CONFIG_HOME', join(home, '.config'))\n const dataHome = xdgBase('XDG_DATA_HOME', join(home, '.local', 'share'))\n // Config home first, keeping the probe order existing installs hit.\n const linux = dedupeCandidates([\n join(configHome, ...DESKTOP_AUTH_RELATIVE_PATH),\n join(dataHome, ...DESKTOP_AUTH_RELATIVE_PATH),\n ])\n return isWsl() ? dedupeCandidates([...wslDesktopAuthCandidates(home), ...linux]) : linux\n }\n return []\n}\n\n/** The XDG base directory for one env variable, or its platform default. */\nfunction xdgBase(envName: string, fallback: string): string {\n const value = process.env[envName]?.trim()\n if (value !== undefined && value !== '' && value.startsWith('/')) return value\n return fallback\n}\n\n/** Drop duplicate candidates while keeping probe order. */\nfunction dedupeCandidates(candidates: readonly string[]): string[] {\n return [...new Set(candidates)]\n}\n\n/**\n * The platform-default candidates for one variant, in probe order.\n *\n * Both apps write into the *same* shared `CodeBuddyExtension` auth directory\n * and differ only in the file's basename, so the per-platform ordering above\n * is reused verbatim and just the filename is swapped.\n */\nexport function desktopAuthCandidatesFor(variant: WorkBuddyVariant): string[] {\n return dedupeCandidates(defaultDesktopAuthCandidates().map(path => join(dirname(path), variant.desktopFilename)))\n}\n\n/** First platform-default candidate; see {@link defaultDesktopAuthCandidates}. */\nexport function defaultDesktopAuthPath(variant?: WorkBuddyVariant): string | undefined {\n const candidates = variant === undefined ? defaultDesktopAuthCandidates() : desktopAuthCandidatesFor(variant)\n return candidates[0]\n}\n\n/** Normalize an expiry that may arrive in seconds or milliseconds. */\nfunction expiryToMs(value: number): number {\n if (value <= 0) return 0\n return value > 1e12 ? value : value * 1000\n}\n\nfunction optionalString(value: unknown): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined\n}\n\n/**\n * Parse a WorkBuddy auth document in either on-disk shape: the plugin OAuth\n * nested form `{\"auth\":{...},\"account\":{...}}` and the flat panel form.\n * Returns undefined when the document carries no access token.\n */\nexport function parseWorkBuddyAuth(text: string): WorkBuddyCredential | undefined {\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n return undefined\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return undefined\n const document = parsed as Record<string, unknown>\n let auth: Record<string, unknown>\n let identity: Record<string, unknown>\n if (typeof document['auth'] === 'object' && document['auth'] !== null) {\n auth = document['auth'] as Record<string, unknown>\n identity = typeof document['account'] === 'object' && document['account'] !== null\n ? document['account'] as Record<string, unknown>\n : {}\n } else {\n auth = document\n identity = document\n }\n const accessToken = typeof auth['accessToken'] === 'string' ? auth['accessToken'] : ''\n if (accessToken === '') return undefined\n const expiresAtMs = typeof auth['expiresAt'] === 'number' ? expiryToMs(auth['expiresAt']) : 0\n const refreshExpiresAtMs = typeof auth['refreshExpiresAt'] === 'number' ? expiryToMs(auth['refreshExpiresAt']) : undefined\n const enterpriseId = optionalString(identity['enterpriseId'])\n const nickname = optionalString(identity['nickname'])\n const credential: WorkBuddyCredential = {\n accessToken,\n refreshToken: typeof auth['refreshToken'] === 'string' ? auth['refreshToken'] : '',\n expiresAtMs,\n ...refreshExpiresAtMs === undefined ? {} : { refreshExpiresAtMs },\n domain: optionalString(auth['domain']) ?? '',\n uid: optionalString(identity['uid']) ?? '',\n ...enterpriseId === undefined ? {} : { enterpriseId },\n ...nickname === undefined ? {} : { nickname },\n source: 'desktop',\n }\n return credential\n}\n\n/** Serialize the plugin-owned copy. */\nfunction ownDocument(credential: WorkBuddyCredential): OwnDocument {\n return { version: OWN_FORMAT_VERSION, credential }\n}\n\n/** Parse the plugin-owned copy; other versions and shapes are rejected. */\nfunction parseOwnDocument(text: string): WorkBuddyCredential | undefined {\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n return undefined\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return undefined\n const document = parsed as Record<string, unknown>\n if (document['version'] !== OWN_FORMAT_VERSION) return undefined\n if (typeof document['credential'] !== 'object' || document['credential'] === null) return undefined\n // The owned copy stores the normalized credential itself (camelCase\n // `expiresAtMs`, identity fields at the top level), not the desktop\n // document shape. Round-tripping through parseWorkBuddyAuth reads\n // `expiresAt` and an `account` object, finds neither, zeroes the expiry,\n // and drops uid/enterprise/nickname \u2014 so a surviving copy refreshed on\n // every request and lost its identity headers.\n const stored = document['credential'] as Record<string, unknown>\n const accessToken = typeof stored['accessToken'] === 'string' ? stored['accessToken'] : ''\n if (accessToken === '') return undefined\n const refreshExpiresAtMs = typeof stored['refreshExpiresAtMs'] === 'number' ? stored['refreshExpiresAtMs'] : undefined\n const enterpriseId = optionalString(stored['enterpriseId'])\n const nickname = optionalString(stored['nickname'])\n return {\n accessToken,\n refreshToken: typeof stored['refreshToken'] === 'string' ? stored['refreshToken'] : '',\n expiresAtMs: typeof stored['expiresAtMs'] === 'number' ? stored['expiresAtMs'] : 0,\n ...refreshExpiresAtMs === undefined ? {} : { refreshExpiresAtMs },\n domain: optionalString(stored['domain']) ?? '',\n uid: optionalString(stored['uid']) ?? '',\n ...enterpriseId === undefined ? {} : { enterpriseId },\n ...nickname === undefined ? {} : { nickname },\n source: 'dsh',\n }\n}\n\n/** Whether a filesystem error reports an absent path. */\nfunction isENOENT(error: unknown): boolean {\n return (error as NodeJS.ErrnoException | null)?.code === 'ENOENT'\n}\n\n/**\n * Read-only credential store with demand-driven refresh.\n *\n * Refresh policy: refresh only when the access token is inside the margin\n * (or already expired), keep the refreshed credential in the plugin-owned\n * copy, and never write the desktop app's file. A failed refresh still\n * returns a not-yet-expired token so an unreachable refresh endpoint does\n * not take down a working session.\n */\nexport class WorkBuddyCredentialStore {\n private readonly variant: WorkBuddyVariant | undefined\n private readonly refresh: WorkBuddyStoreOptions['refresh']\n private readonly refreshMarginMs: number\n private readonly ownPath: string\n private readonly keyProvider: NonNullable<WorkBuddyStoreOptions['keyProvider']>\n private desktopPathOverride: string | undefined\n private inflight: Promise<WorkBuddyCredential> | undefined\n\n constructor(options: WorkBuddyStoreOptions) {\n this.variant = options.variant\n this.refresh = options.refresh\n this.refreshMarginMs = options.refreshMarginMs ?? 5 * 60 * 1000\n this.ownPath = options.ownPath ?? (options.variant ? join(resolveDshHome(), options.variant.ownFilename) : workbuddyOwnAuthPath())\n // Legacy stores without a variant stay on the CN product the store's other\n // defaults already assume (own-copy filename, auth env var); a variant\n // without an electron profile falls back by id, keeping externally\n // assembled descriptors source-compatible.\n this.keyProvider = options.keyProvider\n ?? new WorkBuddyAtRestKeyProvider({ product: electronProfileFor(options.variant) })\n this.desktopPathOverride = options.desktopPath\n }\n\n /**\n * Configuration precedence for the desktop file: the plugin's configured\n * path, then the environment variable, then the platform defaults. An\n * explicit path is used verbatim; the defaults are a probe order.\n */\n private resolveDesktopCandidates(): string[] {\n const fromEnv = process.env[this.variant?.env ?? WORKBUDDY_AUTH_FILE_ENV]\n const explicit = this.desktopPathOverride\n ?? (fromEnv !== undefined && fromEnv.trim() !== '' ? fromEnv : undefined)\n if (explicit !== undefined) return [explicit]\n return this.variant === undefined\n ? defaultDesktopAuthCandidates()\n : desktopAuthCandidatesFor(this.variant)\n }\n\n private resolveDesktopPath(): string | undefined {\n return this.resolveDesktopCandidates()[0]\n }\n\n /**\n * Repoint the desktop file; a settings change applies on the next read.\n */\n setDesktopPath(path: string | undefined): void {\n this.desktopPathOverride = path\n }\n\n /** The resolved desktop auth-file path, for diagnostics. */\n desktopAuthPath(): string | undefined {\n return this.resolveDesktopPath()\n }\n\n /** The plugin-owned copy path, for diagnostics. */\n ownAuthPath(): string {\n return this.ownPath\n }\n\n /** Read the freshest stored credential without refreshing anything. */\n async current(): Promise<WorkBuddyCredential | undefined> {\n const [desktop, own] = await Promise.all([this.readDesktop(), this.readOwn()])\n // A credential belonging to the other product is refused rather than used:\n // the two apps share one auth directory and differ only by filename, so a\n // misconfigured `authFile` / env var is a realistic mistake, and sending one\n // region's token to the other's endpoint would leak it across products.\n // Naming the file and the expected region is what makes it fixable.\n if (this.variant !== undefined) {\n for (const [label, credential] of [['desktop file', desktop], ['plugin copy', own]] as const) {\n if (credential === undefined) continue\n const region = regionOf(credential.domain)\n if (region !== this.variant.region) {\n throw new WorkBuddyElectronPathError(\n 'credential-region-mismatch',\n `${this.variant.displayName} received a ${region === 'cn' ? 'WorkBuddy (CN)' : 'WorkBuddy AI'} credential`\n + ` in its ${label} (domain ${JSON.stringify(credential.domain)});`\n + ` point ${this.variant.env} at the ${this.variant.appName} sign-in, or remove the mismatched file`,\n )\n }\n }\n }\n if (desktop === undefined) return own\n if (own === undefined) return desktop\n // Identity beats expiry. The plugin's own copy is written by its own\n // refreshes, so after the user switches accounts in the desktop app the copy\n // still belongs to the *previous* account \u2014 and may well expire later,\n // because the plugin refreshed it. Preferring it by expiry would send the old\n // account's uid in `X-User-Id` and answer as the wrong user. The desktop\n // file is the authority on who is signed in now; a differing identity means\n // the copy is stale regardless of its timestamp.\n if (desktop.uid !== own.uid || desktop.enterpriseId !== own.enterpriseId) return desktop\n return own.expiresAtMs > desktop.expiresAtMs ? own : desktop\n }\n\n /**\n * The credential to send upstream: {@link current}, refreshed on demand.\n * Single-flight, so parallel requests share one refresh.\n */\n async resolve(): Promise<WorkBuddyCredential> {\n const credential = await this.current()\n if (credential === undefined) {\n const candidates = this.resolveDesktopCandidates()\n const desktop = candidates.length > 0 ? candidates.join(' or ') : '(no desktop path on this platform)'\n const app = this.variant?.appName ?? 'WorkBuddy'\n throw new Error(\n `workbuddy: no signed-in ${app} account found; sign in once in the ${app} desktop app`\n + ` (expected ${desktop} or ${this.variant?.env ?? WORKBUDDY_AUTH_FILE_ENV}), or refresh an existing session`,\n )\n }\n if (!this.needsRefresh(credential)) return credential\n this.inflight ??= this.refreshNow(credential)\n .finally(() => {\n this.inflight = undefined\n })\n return this.inflight\n }\n\n /** Read-only sign-in summary; never refreshes and never throws. */\n async status(): Promise<WorkBuddyAuthStatus> {\n try {\n const credential = await this.current()\n if (credential === undefined) return { state: 'signed-out', reasonCode: 'no-credential' }\n return {\n state: 'signed-in',\n expiresAtMs: credential.expiresAtMs,\n ...credential.refreshExpiresAtMs === undefined ? {} : { refreshExpiresAtMs: credential.refreshExpiresAtMs },\n ...credential.nickname === undefined ? {} : { nickname: credential.nickname },\n ...credential.domain === '' ? {} : { domain: credential.domain },\n source: credential.source,\n }\n } catch (error: unknown) {\n // A region mismatch (or an unreadable file, or an unusable key helper) is\n // a *diagnosable* signed-out state, not a silent one: the user needs the\n // path to the file that is wrong, and which provider it actually belongs\n // to. Reported as a status rather than thrown, because `status()` is\n // documented never to throw and the card renders `reason` verbatim.\n //\n // The code travels beside the prose so the card can branch on the cause\n // without ever matching the message text.\n return {\n state: 'signed-out',\n reason: error instanceof Error ? error.message : String(error),\n ...reasonCodeOf(error) === undefined\n ? {}\n : { reasonCode: reasonCodeOf(error) as WorkBuddySignedOutReasonCode },\n }\n }\n }\n\n /** Remove the plugin-owned copy; the desktop file is untouched. */\n async logout(): Promise<void> {\n await rm(this.ownPath, { force: true })\n await rm(`${this.ownPath}.lock`, { force: true })\n }\n\n private needsRefresh(credential: WorkBuddyCredential): boolean {\n if (credential.expiresAtMs <= 0) return true\n return Date.now() + this.refreshMarginMs >= credential.expiresAtMs\n }\n\n private async refreshNow(credential: WorkBuddyCredential): Promise<WorkBuddyCredential> {\n if (credential.refreshToken === '') {\n if (credential.expiresAtMs > Date.now() + 30_000) return credential\n throw new Error('workbuddy: access token expired and no refresh token is stored; sign in again in the WorkBuddy desktop app')\n }\n try {\n const outcome = await this.refresh(credential)\n const refreshed: WorkBuddyCredential = {\n ...credential,\n accessToken: outcome.accessToken,\n ...outcome.refreshToken === undefined ? {} : { refreshToken: outcome.refreshToken },\n expiresAtMs: outcome.expiresInSec !== undefined\n ? Date.now() + outcome.expiresInSec * 1000\n : credential.expiresAtMs,\n ...outcome.domain === undefined || outcome.domain === '' ? {} : { domain: outcome.domain },\n source: 'dsh',\n }\n await this.saveOwn(refreshed)\n return refreshed\n } catch (error: unknown) {\n if (credential.expiresAtMs > Date.now() + 30_000) return credential\n throw new Error(\n `workbuddy: token refresh failed and the access token is expired (${String(error)});`\n + ' open the WorkBuddy desktop app once to sign in again',\n )\n }\n }\n\n private async saveOwn(credential: WorkBuddyCredential): Promise<void> {\n await withFileLock(this.ownPath, async () => {\n await writeFileAtomic(this.ownPath, `${JSON.stringify(ownDocument(credential), null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n })\n })\n }\n\n /**\n * Read the first desktop candidate that exists. Only an absent file\n * (ENOENT) falls through to the next candidate; a file that is present\n * but unparsable is authoritative for its slot, so a stale older-version\n * file never silently wins over a broken newer one.\n *\n * Since WorkBuddy 5.6 the token fields may arrive in at-rest envelopes, so\n * the text is classified before the regular parser sees it. An encrypted\n * document must be *opened*, never skipped; an unrecognized one must fail\n * loudly. The desktop file, as long as it exists, is the identity\n * authority \u2014 a document this plugin cannot read must surface as a\n * diagnosis rather than be papered over by the plugin-owned copy, which\n * belongs to whatever account was signed in when it was last refreshed.\n * Only an absent (or empty) file lets the probe continue.\n */\n private async readDesktop(): Promise<WorkBuddyCredential | undefined> {\n for (const desktopPath of this.resolveDesktopCandidates()) {\n let text: string\n try {\n text = await readFile(desktopPath, 'utf8')\n } catch (error: unknown) {\n if (!isENOENT(error)) throw error\n continue\n }\n const classification = classifyDesktopAuthDocument(text)\n if (classification.format === 'plaintext') return parseWorkBuddyAuth(text)\n if (classification.format === 'absent') continue\n if (classification.format === 'unrecognized') {\n throw new Error(\n `the desktop auth file at ${desktopPath} exists but is unreadable`\n + ' (neither a plaintext credential nor a decodable WorkBuddy 5.6 envelope);'\n + ' fix or remove the file \u2014 it outranks the plugin-owned credential copy',\n )\n }\n return await this.openEncryptedDesktop(classification)\n }\n return undefined\n }\n\n /** Open a 5.6 encrypted desktop document into the regular credential shape. */\n private async openEncryptedDesktop(\n classification: Extract<DesktopAuthClassification, { format: 'encrypted' }>,\n ): Promise<WorkBuddyCredential | undefined> {\n const wrapped = classification.wrapped\n const key = await this.keyProvider.protectorKeyFor(keyIdsOf(wrapped.fields))\n const text = unwrapDesktopAuthDocument(classification, field => {\n const plaintext = openAuthField(key, field.envelope)\n if (plaintext === undefined) {\n throw new WorkBuddyElectronPathError(\n 'encrypted-credential-unreadable',\n `the encrypted desktop credential's ${field.field} could not be decrypted`\n + ` (envelope key id ${field.envelope.keyId});`\n + ' the WorkBuddy app may hold a different at-rest key \u2014 open it once to reseal the sign-in',\n )\n }\n return plaintext\n })\n return parseWorkBuddyAuth(text)\n }\n\n /**\n * Classify the first desktop candidate that exists and carries content;\n * `absent` when none does. An empty first file is skipped so it cannot mask\n * a real document on the next candidate. Diagnostics only \u2014 it never spawns\n * the key helper and never decrypts, so doctor can describe the file\n * without attempting the unlock.\n */\n async desktopAuthFormat(): Promise<DesktopAuthFormat> {\n for (const desktopPath of this.resolveDesktopCandidates()) {\n let text: string\n try {\n text = await readFile(desktopPath, 'utf8')\n } catch (error: unknown) {\n if (!isENOENT(error)) throw error\n continue\n }\n const format = classifyDesktopAuthDocument(text).format\n if (format !== 'absent') return format\n }\n return 'absent'\n }\n\n private async readOwn(): Promise<WorkBuddyCredential | undefined> {\n try {\n return parseOwnDocument(await readFile(this.ownPath, 'utf8'))\n } catch (error: unknown) {\n if (isENOENT(error)) return undefined\n return undefined\n }\n }\n\n /**\n * The first desktop candidate the probe would actually read from; `undefined`\n * when none qualifies. Semantics deliberately match the probe: empty files\n * are skipped (the probe classifies them as absent and moves on), so on an\n * XDG layout where the config-home file is empty but the data-home file\n * holds the credential, diagnostics name the *data-home* file \u2014 the one\n * authentication really uses. Like the probe it never parses or decrypts.\n */\n async resolvedDesktopAuthPath(): Promise<string | undefined> {\n for (const desktopPath of this.resolveDesktopCandidates()) {\n let text: string\n try {\n text = await readFile(desktopPath, 'utf8')\n } catch (error: unknown) {\n if (!isENOENT(error)) throw error\n continue\n }\n if (text.trim() === '') continue\n return desktopPath\n }\n return undefined\n }\n\n /** Whether any desktop-file candidate exists as a regular file; diagnostics only. */\n async desktopFilePresent(): Promise<boolean> {\n return await this.resolvedDesktopAuthPath() !== undefined\n }\n}\n", "import { homedir } from 'node:os'\nimport { join } from 'node:path'\n\nexport type TraeEdition = 'cn' | 'sg' | 'solo' | 'solo-sg'\n\n/**\n * Where a local sign-in was persisted. `desktop` candidates hold an Electron\n * `globalStorage/storage.json` whose auth value is encrypted; `cli` candidates\n * hold a bare JWT written by the Trae CLI, which needs no decryption.\n */\nexport type TraeCredentialSource = 'desktop' | 'cli'\n\nexport interface TraeStorageCandidate {\n edition: TraeEdition\n path: string\n source: TraeCredentialSource\n}\n\nconst APP_NAMES: Readonly<Record<TraeEdition, string>> = {\n cn: 'Trae CN',\n sg: 'Trae',\n solo: 'TRAE SOLO CN',\n 'solo-sg': 'TRAE SOLO',\n}\n\n/**\n * Directory names the Trae CLI uses for its own home. These are deliberately\n * separate from the Electron app-support names above: the CLI keeps a dotfile\n * home (observed on macOS as `~/.trae-cn`) rather than an `Application Support`\n * entry, so a machine with only the CLI installed has no `storage.json` at all.\n */\nconst CLI_HOME_NAMES: readonly string[] = ['.trae-cn', '.trae']\n\n/** Basename of the CLI's persisted bare JWT. */\nexport const TRAE_CLI_TOKEN_FILENAME = 'trae-jwt-token'\n\n/**\n * Linux desktop config directory names. Electron apps on Linux normally use a\n * lowercase, space-free name rather than the macOS `Trae CN` spelling, so both\n * are probed: guessing only the macOS spelling would silently miss a real\n * install, and guessing only the Linux spelling would break every existing\n * user. The actual name is unverified on a real Linux host.\n */\nconst LINUX_APP_NAMES: Readonly<Record<TraeEdition, readonly string[]>> = {\n cn: ['trae-cn', 'Trae CN', 'trae', 'Trae'],\n sg: ['trae', 'Trae'],\n solo: ['trae-solo-cn', 'TRAE SOLO CN'],\n 'solo-sg': ['trae-solo', 'TRAE SOLO'],\n}\n\n/**\n * Windows desktop config directory names.\n *\n * Trae is a VS Code-family Electron app, and that family names its per-user\n * data directory from the installer-registered product name \u2014 which on Windows\n * is `product.json`'s `win32DirName`, NOT the macOS bundle spelling. Measured\n * from the shipped bundles (2026-09-26):\n *\n * Trae CN -> win32DirName = \"Trae CN\" (applicationName trae-cn)\n * TRAE SOLO CN -> win32DirName = \"TRAE SOLO CN\" (applicationName trae-solo-cn)\n *\n * So the macOS spellings happen to be right here, and `win32DirName` is the\n * authority that says so. The lowercase `applicationName` spellings\n * (`trae-cn`, `trae-solo-cn`) are probed as well because the same family uses\n * them for the Linux config directory, and which of the two a given installer\n * writes has never been confirmed on a real Windows host\n * (docs/WINDOWS_TOKEN_PROBE.md). Windows file systems are case-insensitive, so\n * listing `trae cn` beside `Trae CN` would be the same directory twice \u2014 only\n * genuinely different spellings are listed.\n */\nconst WINDOWS_APP_NAMES: Readonly<Record<TraeEdition, readonly string[]>> = {\n cn: ['Trae CN', 'trae-cn'],\n sg: ['Trae'],\n solo: ['TRAE SOLO CN', 'trae-solo-cn'],\n 'solo-sg': ['TRAE SOLO'],\n}\n\n/**\n * One edition's plausible Windows directory spellings, in probe order.\n *\n * Exported so the identity reader and the credential scanner probe the SAME\n * names: the two resolve different files (the install's `product.json` vs the\n * per-user `storage.json`) but they describe one installation, and a spelling\n * that works for one but not the other is a bug rather than a preference.\n */\nexport function traeWindowsAppNames(edition: TraeEdition): readonly string[] {\n return WINDOWS_APP_NAMES[edition]\n}\n\nexport function traeStorageCandidates(\n platform: NodeJS.Platform = process.platform,\n home: string = homedir(),\n env: NodeJS.ProcessEnv = process.env,\n): TraeStorageCandidate[] {\n const result: TraeStorageCandidate[] = []\n for (const edition of ['cn', 'sg', 'solo', 'solo-sg'] as const) {\n const app = APP_NAMES[edition]\n let roots: string[]\n let appNames: readonly string[]\n if (platform === 'darwin') {\n roots = [join(home, 'Library', 'Application Support')]\n appNames = [app]\n } else if (platform === 'win32') {\n roots = [env.APPDATA, join(home, 'AppData', 'Roaming')].filter((value, index, all): value is string =>\n typeof value === 'string' && value !== '' && all.indexOf(value) === index)\n appNames = WINDOWS_APP_NAMES[edition]\n } else if (platform === 'linux') {\n roots = [env.XDG_CONFIG_HOME || join(home, '.config')]\n appNames = LINUX_APP_NAMES[edition]\n } else {\n roots = []\n appNames = [app]\n }\n for (const root of roots) {\n for (const appName of appNames) {\n result.push({ edition, path: join(root, appName, 'User', 'globalStorage', 'storage.json'), source: 'desktop' })\n }\n }\n }\n return [...result, ...traeCliCandidates(platform, home, env)]\n}\n\n/**\n * Candidate CLI token paths. Only CN/SOLO editions are targeted here for the\n * same reason the store ignores SG desktop installs, and `.trae-cn` is mapped\n * to `cn` while `.trae` is the CLI's international home and is therefore\n * skipped by the store's edition filter.\n *\n * The CLI home is a dotfile directory directly under `$HOME` on every platform\n * observed so far, but this is only verified on macOS; the Windows and Linux\n * spellings are probed speculatively and a miss is harmless because every\n * candidate is tried in order.\n */\nexport function traeCliCandidates(\n platform: NodeJS.Platform = process.platform,\n home: string = homedir(),\n env: NodeJS.ProcessEnv = process.env,\n): TraeStorageCandidate[] {\n const roots: string[] = []\n if (platform === 'win32') {\n for (const value of [env.USERPROFILE, home]) {\n if (typeof value === 'string' && value !== '' && !roots.includes(value)) roots.push(value)\n }\n } else {\n roots.push(home)\n }\n const result: TraeStorageCandidate[] = []\n for (const root of roots) {\n for (const name of CLI_HOME_NAMES) {\n // `.trae-cn` is the CN CLI home. `.trae` is kept as a low-priority\n // fallback so a renamed CN home is still discovered on a machine that has\n // no international install; the store filters by edition afterwards.\n const edition: TraeEdition = name === '.trae-cn' ? 'cn' : 'sg'\n result.push({ edition, path: join(root, name, TRAE_CLI_TOKEN_FILENAME), source: 'cli' })\n }\n }\n return result\n}\n", "import { readFile, rm, stat } from 'node:fs/promises'\nimport { createHash } from 'node:crypto'\nimport { join } from 'node:path'\nimport { withFileLock, writeFileAtomic } from '@deepseek-ai/dsh-atomic-write'\nimport { resolveDshHome } from '@deepseek-ai/dsh-home-paths'\nimport { parseTraeCliToken, parseTraeStorageDocument } from './decrypt.ts'\nimport { traeStorageCandidates, type TraeCredentialSource, type TraeEdition, type TraeStorageCandidate } from './paths.ts'\nimport { regionOfCredential, regionOfEdition, type TraeRegion } from './region.ts'\n\nexport interface TraeCredential {\n accessToken: string\n refreshToken?: string\n userId: string\n accountName?: string\n host: string\n /**\n * Region claim from the decrypted storage document (`userRegion.region`,\n * 'CN' | 'SG', possibly lowercase). Drives the routing bucket together with\n * `host`; see `regionOfCredential`.\n */\n userRegion?: string\n expiresAtMs: number\n refreshExpiresAtMs?: number\n edition: TraeEdition\n source: 'desktop' | 'dsh' | 'cli'\n}\n\nexport interface TraeRefreshOutcome {\n accessToken: string\n refreshToken?: string\n expiresAtMs: number\n refreshExpiresAtMs?: number\n host?: string\n}\n\nexport interface TraeCredentialStoreOptions {\n storagePath?: string\n edition?: TraeEdition | 'auto'\n accountId?: string\n ownPath?: string\n /**\n * Region this store serves. When set, only credentials whose own claim maps\n * to this region are discovered, selected, or refreshed \u2014 the two regions'\n * stores run side by side without seeing each other's accounts.\n */\n region?: TraeRegion\n /** Legacy single-copy path read as a migration source; injectable for tests. */\n legacyOwnPath?: string\n refresh: (credential: TraeCredential) => Promise<TraeRefreshOutcome>\n refreshMarginMs?: number\n}\n\nexport interface TraeAccountChoice {\n id: string\n accountName: string\n edition: TraeEdition\n /** Routing bucket of this account (`cn` | `ai`), derived from its credential. */\n region: TraeRegion\n source: 'desktop' | 'dsh' | 'cli'\n tokenExpiresAtMs: number\n selected: boolean\n}\n\n/**\n * Why one candidate path did not yield an account. These are safe to surface:\n * they carry paths and error text, never token material.\n */\nexport interface TraeCandidateFailure {\n path: string\n edition: TraeEdition\n source: TraeCredentialSource\n reason: 'missing' | 'unreadable' | 'invalid'\n message?: string\n}\n\n/** Host used for CLI tokens, which carry no host claim of their own. */\nconst CLI_DEFAULT_HOST = 'https://api.trae.cn'\n\nconst OWN_VERSION = 1\nexport const TRAE_AUTH_FILENAME = '.trae-auth.json'\n\n/** Prefix of the plugin-owned per-region credential copies. */\nconst TRAE_OWN_PREFIX = '.trae-auth'\n\n/**\n * Plugin-owned copy path for one region. Each region's store refreshes into\n * its own file so two simultaneously signed-in regions never overwrite each\n * other's refreshed token.\n */\nexport function traeOwnAuthPath(region: TraeRegion): string {\n return join(resolveDshHome(), `${TRAE_OWN_PREFIX}.${region}.json`)\n}\n\n/**\n * Pre-dual-provider single-copy path. Still read as a migration source (a\n * legacy credential serves the region it belongs to until that region's own\n * first refresh writes the per-region file), and removed by `logout`.\n */\nexport function legacyTraeOwnAuthPath(): string {\n return join(resolveDshHome(), TRAE_AUTH_FILENAME)\n}\n\nfunction optionalString(value: unknown): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined\n}\n\nfunction timeToMs(value: unknown): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value) && value > 0) return value > 1e12 ? value : value * 1000\n if (typeof value !== 'string' || value.trim() === '') return undefined\n const numeric = Number(value)\n if (Number.isFinite(numeric) && numeric > 0) return numeric > 1e12 ? numeric : numeric * 1000\n const parsed = Date.parse(value)\n return Number.isFinite(parsed) ? parsed : undefined\n}\n\n/** Extract the `userRegion.region` string from either on-disk shape. */\nfunction userRegionOf(value: unknown): string | undefined {\n const raw = typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)['region']\n : value\n return typeof raw === 'string' && raw.trim() !== '' ? raw.trim() : undefined\n}\n\nexport function normalizeTraeCredential(raw: unknown, edition: TraeEdition, source: TraeCredential['source']): TraeCredential | undefined {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined\n const value = raw as Record<string, unknown>\n const accessToken = optionalString(value['token']) ?? optionalString(value['accessToken'])\n if (accessToken === undefined) return undefined\n const expiresAtMs = timeToMs(value['expiredAt'] ?? value['expiresAt']) ?? 0\n const refreshExpiresAtMs = timeToMs(value['refreshExpiredAt'] ?? value['refreshExpiresAt'])\n const refreshToken = optionalString(value['refreshToken'])\n const userRegion = userRegionOf(value['userRegion'])\n const account = typeof value['account'] === 'object' && value['account'] !== null && !Array.isArray(value['account'])\n ? value['account'] as Record<string, unknown>\n : undefined\n const accountName = optionalString(account?.['username'])\n return {\n accessToken,\n ...refreshToken === undefined ? {} : { refreshToken },\n userId: optionalString(value['userId']) ?? '',\n ...accountName === undefined ? {} : { accountName },\n host: optionalString(value['host']) ?? '',\n ...userRegion === undefined ? {} : { userRegion },\n expiresAtMs,\n ...refreshExpiresAtMs === undefined ? {} : { refreshExpiresAtMs },\n edition,\n source,\n }\n}\n\nexport function traeAccountId(credential: Pick<TraeCredential, 'edition' | 'userId' | 'accountName'>): string {\n const stable = `${credential.edition}\\0${credential.userId || credential.accountName || 'unknown'}`\n return createHash('sha256').update(stable).digest('hex').slice(0, 24)\n}\n\nfunction parseOwn(text: string): TraeCredential | undefined {\n try {\n const document = JSON.parse(text) as { version?: unknown; credential?: unknown }\n if (document.version !== OWN_VERSION || typeof document.credential !== 'object' || document.credential === null) return undefined\n const stored = document.credential as Record<string, unknown>\n const edition = stored['edition']\n if (edition !== 'cn' && edition !== 'sg' && edition !== 'solo' && edition !== 'solo-sg') return undefined\n return normalizeTraeCredential({\n token: stored['accessToken'], refreshToken: stored['refreshToken'], userId: stored['userId'], host: stored['host'],\n userRegion: stored['userRegion'],\n account: stored['accountName'] === undefined ? undefined : { username: stored['accountName'] },\n expiredAt: stored['expiresAtMs'], refreshExpiredAt: stored['refreshExpiresAtMs'],\n }, edition, 'dsh')\n } catch { return undefined }\n}\n\nexport class TraeCredentialStore {\n private storagePathOverride: string | undefined\n private edition: TraeEdition | 'auto'\n private accountId: string | undefined\n private readonly region: TraeRegion | undefined\n private readonly ownPathExplicit: string | undefined\n private readonly legacyOwnPath: string\n private readonly legacyOwnPathExplicit: string | undefined\n private readonly refresh: TraeCredentialStoreOptions['refresh']\n private readonly refreshMarginMs: number\n private inflight: Promise<TraeCredential> | undefined\n\n constructor(options: TraeCredentialStoreOptions) {\n this.storagePathOverride = options.storagePath\n this.edition = options.edition ?? 'auto'\n this.accountId = options.accountId\n this.region = options.region\n this.ownPathExplicit = options.ownPath\n this.legacyOwnPath = options.legacyOwnPath ?? legacyTraeOwnAuthPath()\n this.legacyOwnPathExplicit = options.legacyOwnPath\n this.refresh = options.refresh\n this.refreshMarginMs = options.refreshMarginMs ?? 5 * 60_000\n }\n\n /** Whether a credential's own claim belongs to this store's region. */\n private matchesRegion(credential: TraeCredential): boolean {\n return this.region === undefined || regionOfCredential(credential) === this.region\n }\n\n /**\n * The path this store refreshes into: the per-region file for a\n * region-scoped store, the legacy single file otherwise, or an explicitly\n * injected path in tests.\n */\n ownAuthPath(): string {\n if (this.ownPathExplicit !== undefined) return this.ownPathExplicit\n return this.region !== undefined ? traeOwnAuthPath(this.region) : this.legacyOwnPath\n }\n\n /**\n * Every plugin-owned copy to read, most preferred first. A region-scoped\n * store reads the legacy single copy as its migration source (readAll's\n * region filter drops it when it carries the other region's credential); an\n * unscoped store reads everything so diagnostics see both regions.\n *\n * With an explicitly injected own path the legacy source is read ONLY when\n * it was injected too \u2014 a test that pins one file must not accidentally see\n * the real machine's legacy copy.\n */\n private ownCandidates(): string[] {\n if (this.ownPathExplicit !== undefined) {\n return this.legacyOwnPathExplicit !== undefined\n ? [this.ownPathExplicit, this.legacyOwnPathExplicit]\n : [this.ownPathExplicit]\n }\n if (this.region !== undefined) {\n return [traeOwnAuthPath(this.region), this.legacyOwnPath]\n }\n return [this.legacyOwnPath, traeOwnAuthPath('cn'), traeOwnAuthPath('ai')]\n }\n\n setSource(storagePath: string | undefined, edition: TraeEdition | 'auto' = 'auto', accountId?: string): void {\n this.storagePathOverride = storagePath\n this.edition = edition\n this.accountId = accountId\n this.inflight = undefined\n }\n\n selectAccount(accountId: string | undefined): void {\n this.accountId = accountId\n this.inflight = undefined\n }\n\n candidates(): TraeStorageCandidate[] {\n if (this.storagePathOverride !== undefined) {\n const edition = this.edition === 'auto' ? 'cn' : this.edition\n // An explicit override points at a user-supplied file whose shape is not\n // known ahead of time, so it is probed as both a desktop storage document\n // and a CLI token file.\n return [\n { edition, path: this.storagePathOverride, source: 'desktop' },\n { edition, path: this.storagePathOverride, source: 'cli' },\n ]\n }\n const all = traeStorageCandidates()\n // Every desktop edition is discovered (the plugin routes by the\n // credential's own region, see region.ts); an explicit `edition` config\n // narrows the scan. The international CLI home (`~/.trae`) stays excluded:\n // its bare JWT carries no host claim and the SG default host has not been\n // verified (docs/INTL_SG_EVIDENCE.md \u00A75), so only the CN CLI home\n // (`.trae-cn`) is probed.\n const cliEdition: TraeEdition = 'cn'\n return this.edition === 'auto'\n ? all.filter(candidate => candidate.source === 'desktop' || candidate.edition === cliEdition)\n : all.filter(candidate => candidate.edition === this.edition && (candidate.source === 'desktop' || candidate.edition === cliEdition))\n }\n\n /**\n * Deterministic default when no account is explicitly selected: the account\n * the Trae desktop app is signed in to RIGHT NOW, else the first discovered\n * one. This is NOT credit-seeking \u2014 it never reorders accounts to find one\n * with general credits. The plugin bills exactly the account the user\n * selected, the app's current sign-in when nothing has been selected, and\n * only then the first account.\n *\n * The app's live sign-in outranks the plugin's own refreshed copies (issue\n * #29): after the user switches accounts in Trae, the desktop storage file\n * holds the NEW login while the plugin's copy of the old one still resolves,\n * so a bare `credentials[0]` kept defaulting to a sign-in the app has\n * abandoned \u2014 and `dsh-connect-workbuddy`, whose `preferred()` ranks the live\n * file first, followed the app instead. Ordering only: the VALUE behind an\n * account id is still whichever copy expires later (`readAll`), so a refresh\n * the plugin performed is never discarded by this preference.\n */\n private preferred(credentials: TraeCredential[]): TraeCredential | undefined {\n return credentials.find(credential => credential.source === 'desktop') ?? credentials[0]\n }\n\n /**\n * The account the Trae app is signed in to right now, when that differs from\n * the account this store is bound to (issue #29).\n *\n * This is a READ, not a rebind: `current()` keeps resolving the bound\n * account verbatim so billing never moves without a decision \u2014 the store\n * only reports the mismatch, and the card (hint row) or the host (follow\n * switch) turns it into a settings write the user can see and undo. Absent\n * when nothing is live, when the live account IS the bound one, or when the\n * binding itself already fell through to the live account.\n */\n async liveLogin(): Promise<TraeAccountChoice | undefined> {\n // No explicit bind: the default (`preferred`) already IS the live login,\n // so `current()` resolves it \u2014 there is no mismatch to report.\n if (this.accountId === undefined || this.accountId === '') return undefined\n const credentials = await this.readAll()\n const live = this.preferred(credentials)\n if (live === undefined) return undefined\n const liveId = traeAccountId(live)\n if (liveId === this.accountId) return undefined\n return {\n id: liveId,\n accountName: live.accountName ?? (live.userId || `${live.edition} account`),\n edition: live.edition,\n region: regionOfCredential(live),\n source: live.source,\n tokenExpiresAtMs: live.expiresAtMs,\n selected: false,\n }\n }\n\n async accounts(): Promise<TraeAccountChoice[]> {\n const credentials = await this.readAll()\n const selectedExists = this.accountId !== undefined && credentials.some(credential => traeAccountId(credential) === this.accountId)\n const defaultSelected = this.preferred(credentials)\n return credentials.map(credential => ({\n id: traeAccountId(credential),\n accountName: credential.accountName ?? (credential.userId || `${credential.edition} account`),\n edition: credential.edition,\n region: regionOfCredential(credential),\n source: credential.source,\n tokenExpiresAtMs: credential.expiresAtMs,\n selected: selectedExists ? traeAccountId(credential) === this.accountId : credential === defaultSelected,\n }))\n }\n\n async current(): Promise<TraeCredential | undefined> {\n const credentials = await this.readAll()\n if (this.accountId === undefined) return this.preferred(credentials)\n const selected = credentials.find(credential => traeAccountId(credential) === this.accountId)\n // A saved account can disappear when Trae replaces its local login. Do NOT\n // silently fall back to a different account: that would bill a different\n // account than the one the user explicitly selected. Return undefined so the\n // caller surfaces \"no signed-in account\" and the user can re-select, instead\n // of the plugin quietly switching accounts behind their back.\n return selected\n }\n\n /**\n * The stored credential of one specific account, without changing which\n * account this store is bound to (issue #25).\n *\n * The card needs to answer \"the account I am bound to has run out of credits\n * \u2014 is another account on this machine usable?\" and {@link resolve} cannot\n * help: it always returns the BOUND account, and switching the bound account\n * just to read one number would race every in-flight chat request sharing\n * this store, and would persist a selection the user never made.\n *\n * So this is a pure lookup: read-only, no refresh side effects (a stale token\n * is returned as-is and the caller's request then fails honestly), and\n * `accountId` is left untouched. An unknown id yields undefined rather than a\n * fallback, for the same reason {@link current} refuses to fall back.\n */\n async credentialOf(accountId: string): Promise<TraeCredential | undefined> {\n if (accountId === '') return undefined\n const credentials = await this.readAll()\n return credentials.find(credential => traeAccountId(credential) === accountId)\n }\n\n async resolve(): Promise<TraeCredential> {\n const credential = await this.current()\n if (credential === undefined) throw new Error(`trae: no signed-in account found (${this.candidates().map(item => item.path).join(' or ')})`)\n if (credential.expiresAtMs > Date.now() + this.refreshMarginMs) return credential\n this.inflight ??= this.refreshNow(credential).finally(() => { this.inflight = undefined })\n return this.inflight\n }\n\n async status(): Promise<{ state: 'signed-in' | 'signed-out'; edition?: TraeEdition; expiresAtMs?: number; source?: TraeCredential['source'] }> {\n try {\n const value = await this.current()\n return value === undefined ? { state: 'signed-out' } : { state: 'signed-in', edition: value.edition, expiresAtMs: value.expiresAtMs, source: value.source }\n } catch { return { state: 'signed-out' } }\n }\n\n async desktopFilePresent(): Promise<boolean> {\n for (const candidate of this.candidates()) {\n try { if ((await stat(candidate.path)).isFile()) return true } catch {}\n }\n return false\n }\n\n /**\n * Remove every plugin-owned copy this store could read (per-region file,\n * legacy single file, and their lock siblings); the desktop storage files\n * are untouched. A region store's logout therefore also clears the legacy\n * migration source \u2014 deliberate: `logout` is the user's \"forget what the\n * plugin stored\" action, not a per-account toggle.\n */\n async logout(): Promise<void> {\n for (const path of this.ownCandidates()) {\n await rm(path, { force: true })\n await rm(`${path}.lock`, { force: true })\n }\n }\n\n /**\n * Every local credential of this store's region, deduplicated by account id.\n * A region-scoped store sees only its own region's credentials: the other\n * region's accounts are invisible to selection, refresh, and status alike,\n * which is what keeps the two regions' providers from cross-billing.\n */\n private async readAll(): Promise<TraeCredential[]> {\n const { credentials: desktop } = await this.readDesktopAll()\n // One entry per ACCOUNT, holding the FRESHEST copy of it.\n //\n // Keeping the desktop copy whenever both exist looks harmless \u2014 the desktop\n // file is the Trae app's own login \u2014 but it silently discards every refresh\n // this plugin performs, because a refreshed credential is written to the\n // plugin's own file, not to the app's. The account then reads as \"token\n // expired\" forever while a valid token sits on disk one file over: the\n // composer table showed a dash for an account whose own copy was refreshed\n // minutes earlier (`.trae-auth.cn.json` valid to 10-14, desktop copy from\n // 09-27 winning the dedupe).\n //\n // Insertion order still follows the desktop list, so `preferred()` and the\n // default selection are unchanged; only the VALUE behind a duplicate id can\n // be replaced, and only by a copy that lives longer.\n const byAccount = new Map<string, TraeCredential>()\n const consider = (credential: TraeCredential): void => {\n if (!this.matchesRegion(credential)) return\n const id = traeAccountId(credential)\n const incumbent = byAccount.get(id)\n if (incumbent === undefined || credential.expiresAtMs > incumbent.expiresAtMs) byAccount.set(id, credential)\n }\n for (const credential of desktop) consider(credential)\n // The own copies are accepted for every edition: they are refresh results\n // the plugin itself wrote, so an international account's refreshed\n // credential must not be dropped just because it is not a CN edition.\n for (const own of await this.readOwns()) consider(own)\n return [...byAccount.values()]\n }\n\n /**\n * Which paths were tried and why each one failed. Read-only and token-free:\n * it exists so a signed-out card can explain itself instead of showing a bare\n * \"not signed in\", which is undiagnosable on a machine whose layout differs\n * from the ones the plugin was written against.\n */\n async diagnose(): Promise<{ tried: TraeStorageCandidate[]; failures: TraeCandidateFailure[] }> {\n const tried = this.candidates()\n const failures: TraeCandidateFailure[] = []\n for (const candidate of tried) {\n const raw = await readFile(candidate.path, 'utf8').then(\n text => ({ text }),\n (error: unknown) => ({ error }),\n )\n if ('error' in raw) {\n const code = typeof raw.error === 'object' && raw.error !== null && 'code' in raw.error\n ? (raw.error as { code?: unknown }).code\n : undefined\n failures.push({\n path: candidate.path,\n edition: candidate.edition,\n source: candidate.source,\n reason: code === 'ENOENT' ? 'missing' : 'unreadable',\n ...code === 'ENOENT' ? {} : { message: String(raw.error) },\n })\n continue\n }\n try {\n this.credentialFrom(candidate, raw.text)\n } catch (error: unknown) {\n failures.push({\n path: candidate.path,\n edition: candidate.edition,\n source: candidate.source,\n reason: 'invalid',\n message: error instanceof Error ? error.message : String(error),\n })\n }\n }\n return { tried, failures }\n }\n\n /** Parse one candidate file's text into a credential, or throw. */\n private credentialFrom(candidate: TraeStorageCandidate, text: string): TraeCredential {\n let credential: TraeCredential | undefined\n if (candidate.source === 'cli') {\n // The CLI token carries no host claim and no userRegion, so the CN host\n // is used rather than an empty string. Only the CN CLI home\n // (`.trae-cn`) is verified: an international CLI token cannot be routed\n // correctly yet (see docs/INTL_SG_EVIDENCE.md \u00A75) and is rejected with\n // a diagnosable error instead of being silently misrouted to the CN\n // gateway.\n if (regionOfEdition(candidate.edition) !== 'cn') {\n throw new Error(`Trae CLI tokens are only verified for the CN region; ${candidate.edition} CLI homes are not supported yet`)\n }\n const claims = parseTraeCliToken(text)\n credential = normalizeTraeCredential({\n token: claims.accessToken,\n userId: claims.userId,\n host: CLI_DEFAULT_HOST,\n expiredAt: claims.expiresAtMs,\n }, candidate.edition, 'cli')\n } else {\n credential = normalizeTraeCredential(parseTraeStorageDocument(text), candidate.edition, 'desktop')\n }\n if (credential === undefined) throw new Error(`${candidate.source} candidate could not be normalized into a credential`)\n return credential\n }\n\n private async readDesktopAll(): Promise<{ credentials: TraeCredential[]; failures: TraeCandidateFailure[] }> {\n const credentials: TraeCredential[] = []\n const failures: TraeCandidateFailure[] = []\n for (const candidate of this.candidates()) {\n try {\n const credential = this.credentialFrom(candidate, await readFile(candidate.path, 'utf8'))\n if (!credentials.some(existing => traeAccountId(existing) === traeAccountId(credential))) credentials.push(credential)\n } catch (error: unknown) {\n // One stale, partially written, unsupported, or signed-out Trae\n // installation must not hide valid accounts from the others. The\n // failure is recorded rather than dropped so `diagnose()` can explain\n // an otherwise silent \"not signed in\".\n const code = typeof error === 'object' && error !== null && 'code' in error\n ? (error as { code?: unknown }).code\n : undefined\n failures.push({\n path: candidate.path,\n edition: candidate.edition,\n source: candidate.source,\n reason: code === 'ENOENT' ? 'missing' : code === undefined ? 'invalid' : 'unreadable',\n ...code === 'ENOENT' || (code === undefined && !(error instanceof Error)) ? {} : { message: error instanceof Error ? error.message : String(error) },\n })\n continue\n }\n }\n return { credentials, failures }\n }\n\n /**\n * Every readable plugin-owned copy, in candidate order; absent or corrupt\n * files are skipped rather than propagated.\n */\n private async readOwns(): Promise<TraeCredential[]> {\n const copies: TraeCredential[] = []\n for (const path of this.ownCandidates()) {\n try {\n const parsed = parseOwn(await readFile(path, 'utf8'))\n if (parsed !== undefined) copies.push(parsed)\n } catch {\n // absent or unreadable \u2014 the next candidate is tried\n }\n }\n return copies\n }\n\n private async refreshNow(credential: TraeCredential): Promise<TraeCredential> {\n if (credential.refreshToken === undefined || (credential.refreshExpiresAtMs !== undefined && credential.refreshExpiresAtMs <= Date.now())) {\n if (credential.expiresAtMs > Date.now() + 30_000) return credential\n throw new Error('trae: access token expired and no valid refresh token is available; sign in again in Trae')\n }\n try {\n const outcome = await this.refresh(credential)\n const refreshed: TraeCredential = {\n ...credential,\n accessToken: outcome.accessToken,\n ...outcome.refreshToken === undefined ? {} : { refreshToken: outcome.refreshToken },\n expiresAtMs: outcome.expiresAtMs,\n ...outcome.refreshExpiresAtMs === undefined ? {} : { refreshExpiresAtMs: outcome.refreshExpiresAtMs },\n ...outcome.host === undefined ? {} : { host: outcome.host },\n source: 'dsh',\n }\n const ownPath = this.ownAuthPath()\n await withFileLock(ownPath, async () => {\n await writeFileAtomic(ownPath, `${JSON.stringify({ version: OWN_VERSION, credential: refreshed }, null, 2)}\\n`, { mode: 0o600, dirMode: 0o700 })\n })\n return refreshed\n } catch (error: unknown) {\n if (credential.expiresAtMs > Date.now() + 30_000) return credential\n throw new Error(`trae: token refresh failed and access token is expired (${String(error)}); sign in again in Trae`)\n }\n }\n}\n", "import { createDecipheriv, createHash } from 'node:crypto'\n\nexport const TRAE_AUTH_STORAGE_KEY = 'iCubeAuthInfo://icube.cloudide'\n\ntype EncryptionType = 'aes' | 'aes-private'\n\nconst SALT_A = Uint8Array.from([82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37])\nconst SALT_B = Uint8Array.from([31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125])\nconst SALT_C = Uint8Array.from([191,192,216,250,122,246,220,97,31,254,98,27,8,72,71,176,135,99,96,18,127,101,203,104,211,102,191,125,37,72,150,156,51,229,121,35,17,153,141,177,110,131,150,128,172,255,254,6,18,140,55,62,236,249,135,64,135,12,117,4,89,149,168,209])\nconst SALT_D = Uint8Array.from([246,204,26,232,232,70,129,109,223,146,169,242,23,241,105,145,50,196,165,42,254,120,3,54,244,207,209,85,53,6,138,106,175,148,31,204,186,186,165,182,87,142,49,10,39,110,26,154,86,56,173,125,18,64,198,225,99,99,83,82,191,134,76,170])\n\nfunction xor(a: Uint8Array, b: Uint8Array): Buffer {\n return Buffer.from(a.map((value, index) => value ^ (b[index] ?? 0)))\n}\n\nfunction encryptionType(header: Buffer): EncryptionType {\n if (header.equals(Buffer.from([0x74, 0x63, 0x05, 0x10, 0x00, 0x00]))) return 'aes'\n if (header.equals(Buffer.from([18, 57, 32, 32, 2, 3]))) return 'aes-private'\n throw new Error('unsupported Trae auth encryption header')\n}\n\nexport function decryptTraeStorageValue(encoded: string): string {\n const buffer = Buffer.from(encoded, 'base64')\n if (buffer.length <= 102) throw new Error('Trae auth ciphertext is too short')\n const type = encryptionType(buffer.subarray(0, 6))\n const random = buffer.subarray(6, 38)\n const encrypted = buffer.subarray(38)\n const salt = type === 'aes-private' ? xor(SALT_C, SALT_D) : xor(SALT_A, SALT_B)\n const first = createHash('sha512').update(random).digest()\n const derived = createHash('sha512').update(Buffer.concat([first, salt])).digest()\n const decipher = createDecipheriv('aes-128-cbc', derived.subarray(0, 16), derived.subarray(16, 32))\n const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()])\n if (decrypted.length < 64) throw new Error('Trae auth plaintext is too short')\n const expected = decrypted.subarray(0, 64)\n const plaintext = decrypted.subarray(64)\n const actual = createHash('sha512').update(plaintext).digest()\n if (!expected.equals(actual)) throw new Error('Trae auth integrity check failed')\n return plaintext.toString('utf8')\n}\n\nexport function parseTraeAuthValue(value: string): unknown {\n const trimmed = value.trim()\n if (trimmed === '') throw new Error('Trae auth value is empty')\n const plaintext = trimmed.startsWith('{') ? trimmed : decryptTraeStorageValue(trimmed)\n return JSON.parse(plaintext) as unknown\n}\n\nexport function parseTraeStorageDocument(text: string): unknown {\n const parsed = JSON.parse(text) as unknown\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) throw new Error('Trae storage document must be an object')\n const value = (parsed as Record<string, unknown>)[TRAE_AUTH_STORAGE_KEY]\n if (typeof value !== 'string') throw new Error(`Trae storage document has no ${TRAE_AUTH_STORAGE_KEY}`)\n return parseTraeAuthValue(value)\n}\n\n/**\n * One decoded claim set from a Trae CLI `trae-jwt-token` file.\n *\n * The CLI writes a bare, unencrypted JWT \u2014 there is no `iCubeAuthInfo` wrapper\n * and no AES layer, so this deliberately bypasses `parseTraeAuthValue`. Only\n * the claims the credential store needs are read; the signature is not\n * verified because the token is consumed locally and re-validated by the\n * upstream service on every request.\n */\nexport interface TraeCliTokenClaims {\n /** Token used directly as the `Cloud-IDE-JWT` bearer value. */\n accessToken: string\n /** `data.user_id`; matches the desktop `userId` for the same account. */\n userId: string\n /** `exp` as epoch milliseconds, or undefined when absent/unparseable. */\n expiresAtMs?: number\n}\n\nfunction decodeBase64UrlJson(segment: string): Record<string, unknown> | undefined {\n try {\n const padded = segment.replace(/-/g, '+').replace(/_/g, '/')\n const decoded = Buffer.from(padded, 'base64').toString('utf8')\n const parsed = JSON.parse(decoded) as unknown\n return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? parsed as Record<string, unknown> : undefined\n } catch { return undefined }\n}\n\n/**\n * Parse the CLI token file. Accepts either the bare JWT itself or a JSON\n * envelope containing one, since the on-disk shape is only verified on macOS\n * and a future CLI revision may wrap it.\n */\nexport function parseTraeCliToken(text: string): TraeCliTokenClaims {\n const trimmed = text.trim()\n if (trimmed === '') throw new Error('Trae CLI token file is empty')\n let token = trimmed\n if (trimmed.startsWith('{')) {\n const envelope = JSON.parse(trimmed) as Record<string, unknown>\n const candidate = envelope['token'] ?? envelope['accessToken'] ?? envelope['jwt']\n if (typeof candidate !== 'string' || candidate.trim() === '') throw new Error('Trae CLI token document has no token field')\n token = candidate.trim()\n }\n const segments = token.split('.')\n if (segments.length !== 3 || segments.some(segment => segment === '')) throw new Error('Trae CLI token is not a three-part JWT')\n const payload = decodeBase64UrlJson(segments[1]!)\n if (payload === undefined) throw new Error('Trae CLI token payload is not decodable JSON')\n const data = typeof payload['data'] === 'object' && payload['data'] !== null && !Array.isArray(payload['data'])\n ? payload['data'] as Record<string, unknown>\n : undefined\n const userId = typeof data?.['user_id'] === 'string' ? data['user_id'] : undefined\n if (userId === undefined || userId === '') throw new Error('Trae CLI token has no data.user_id claim')\n const exp = payload['exp']\n const expiresAtMs = typeof exp === 'number' && Number.isFinite(exp) && exp > 0 ? exp * 1000 : undefined\n return { accessToken: token, userId, ...expiresAtMs === undefined ? {} : { expiresAtMs } }\n}\n", "import { createHash } from 'node:crypto'\nimport { readFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport { cpus, homedir, release, userInfo } from 'node:os'\nimport type { TraeEdition, TraeStorageCandidate } from './paths.ts'\nimport { traeWindowsAppNames } from './paths.ts'\nimport { parseTraeAuthValue } from './decrypt.ts'\n\n/**\n * The per-install ECDSA P-256 keypair the official client registers with the\n * device, and signs its token-refresh proof with.\n *\n * It lives in the same `storage.json` as the credential, under\n * `iCubeAuthInfo://icube-dc:<deviceId>`, encrypted with the same codec \u2014 so the\n * key that PROVES a device is the key stored beside the login it protects.\n * Without it the new refresh contract cannot be satisfied at all (the server\n * rejects a proof signed by any other key with `20403 Token device not match`).\n */\nexport interface TraeDeviceKeyPair {\n privateKeyPEM: string\n publicKeyPEM: string\n}\n\nexport interface TraeIdentity {\n edition: TraeEdition\n machineId: string\n deviceId: string\n appVersion?: string\n buildVersion?: string\n deviceBrand?: string\n deviceCpu?: string\n osVersion?: string\n /**\n * Device display name; the official client sends the OS account's full name.\n * Optional because the new refresh contract does not read it.\n */\n deviceName?: string\n /** Device model, e.g. `MacBookPro18,2`. Optional; not required by the server. */\n deviceModel?: string\n /** The install's registered device keypair, when `storage.json` carries one. */\n deviceKeyPair?: TraeDeviceKeyPair\n platform: NodeJS.Platform\n}\n\nfunction nonEmpty(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined\n}\n\nfunction deviceCenterId(storage: Record<string, unknown>): string | undefined {\n const prefix = 'iCubeAuthInfo://icube-dc:'\n const ids = Object.keys(storage).filter(key => key.startsWith(prefix)).map(key => key.slice(prefix.length)).filter(Boolean)\n return ids.length === 1 ? ids[0] : undefined\n}\n\n/**\n * Read the install's device keypair out of `storage.json`.\n *\n * Tolerant on purpose: an older install (or one that has never refreshed on the\n * new contract) simply has no keypair, and the caller must still be able to\n * resolve an identity for the chat/usage paths \u2014 only a refresh then degrades.\n * A malformed entry is treated as absent rather than failing the read.\n */\nexport function deviceKeyPairOf(storage: Record<string, unknown>): TraeDeviceKeyPair | undefined {\n const key = Object.keys(storage).find(name => name.startsWith('iCubeAuthInfo://icube-dc:'))\n if (key === undefined) return undefined\n const encoded = storage[key]\n if (typeof encoded !== 'string' || encoded.trim() === '') return undefined\n try {\n const plaintext = parseTraeAuthValue(encoded)\n if (typeof plaintext !== 'object' || plaintext === null || Array.isArray(plaintext)) return undefined\n const value = plaintext as Record<string, unknown>\n const privateKeyPEM = nonEmpty(value['privateKeyPEM'])\n const publicKeyPEM = nonEmpty(value['publicKeyPEM'])\n // Both halves are required: the proof needs the private key to sign, and the\n // public key is what the server bound the device to at registration.\n return privateKeyPEM === undefined || publicKeyPEM === undefined ? undefined : { privateKeyPEM, publicKeyPEM }\n } catch {\n return undefined\n }\n}\n\nexport interface TraeIdentityReadOptions {\n /** Platform override for testing; defaults to process.platform. */\n platform?: NodeJS.Platform\n /** Home-directory override for testing; defaults to homedir(). */\n home?: string\n /** Environment override for testing; defaults to process.env. */\n env?: NodeJS.ProcessEnv\n}\n\n/** Read stable identity from Trae-owned files without generating impersonated IDs. */\nexport async function readTraeIdentity(candidate: TraeStorageCandidate, options: TraeIdentityReadOptions = {}): Promise<TraeIdentity> {\n const platform = options.platform ?? process.platform\n const home = options.home ?? homedir()\n const env = options.env ?? process.env\n const storage = JSON.parse(await readFile(candidate.path, 'utf8')) as Record<string, unknown>\n const appRoot = dirname(dirname(dirname(candidate.path)))\n const machineFile = nonEmpty(await readFile(join(appRoot, 'machineid'), 'utf8').catch(() => ''))\n const telemetryMachine = nonEmpty(storage['telemetry.machineId'])\n const devDevice = nonEmpty(storage['telemetry.devDeviceId'])\n const dcDevice = deviceCenterId(storage)\n // Historical official chat logs use the 64-char telemetry.machineId as\n // x-machine-id. The root machineid file remains a fallback only.\n const machineId = telemetryMachine ?? machineFile\n if (machineId === undefined) throw new Error(`Trae ${candidate.edition} has no stable machine identity`)\n // The numeric suffix of iCubeAuthInfo://icube-dc:<id> exactly matches the\n // x-device-id observed in official CN chat logs. Telemetry remains fallback.\n const deviceId = dcDevice ?? devDevice ?? createHash('sha256').update(machineId).digest('hex').slice(0, 32)\n const buildVersion = nonEmpty(storage['iCubeLastVersion'])\n // product.json holds the app version that the real client sends as\n // x-app-version / x-ide-version. On macOS the file sits inside the `.app`\n // bundle, whose name is the product name; on Windows it sits under\n // `%LOCALAPPDATA%\\Programs\\<install dir>\\resources\\app`, where the install\n // directory name is the installer's choice and has never been confirmed on a\n // real host \u2014 hence the same spelling list the credential scanner uses\n // (`traeWindowsAppNames`), so both halves of one installation agree.\n // Failures here must not break identity resolution, so each path is tried in\n // order and non-existent candidates are simply skipped.\n const APP_NAMES_BY_EDITION: Readonly<Record<TraeEdition, string>> = {\n cn: 'Trae CN',\n sg: 'Trae',\n solo: 'TRAE SOLO CN',\n 'solo-sg': 'TRAE SOLO',\n }\n const appName = APP_NAMES_BY_EDITION[candidate.edition]\n const productPaths: string[] = []\n if (appName !== undefined && (platform === 'darwin' || platform === 'win32')) {\n if (platform === 'darwin') {\n productPaths.push(join('/Applications', `${appName}.app`, 'Contents', 'Resources', 'app', 'product.json'))\n } else {\n const localRoots = [env.LOCALAPPDATA, join(home, 'AppData', 'Local')]\n .filter((value): value is string => typeof value === 'string' && value !== '')\n .filter((value, index, all) => all.indexOf(value) === index)\n for (const root of localRoots) {\n for (const spelling of traeWindowsAppNames(candidate.edition)) {\n productPaths.push(join(root, 'Programs', spelling, 'resources', 'app', 'product.json'))\n }\n }\n }\n }\n let product: Record<string, unknown> = {}\n for (const path of productPaths) {\n try { product = JSON.parse(await readFile(path, 'utf8')) as Record<string, unknown>; break } catch {}\n }\n const appVersion = nonEmpty(product['appVersion'])\n const deviceBrand = platform === 'darwin' ? nonEmpty(env['TRAE_DEVICE_BRAND']) : undefined\n const deviceCpu = cpus()[0]?.model.split(' ')[0]\n const osVersion = `${platform === 'darwin' ? 'macOS' : platform === 'win32' ? 'Windows' : platform} ${release()}`\n // The OS account's full name is what the official client sends as DeviceName,\n // and the host's hardware model is what it sends as DeviceModel. Both are\n // best-effort: neither is read by the server, and an unreadable user record\n // must not fail identity resolution.\n const deviceName = ((): string | undefined => {\n try { return nonEmpty(userInfo().username) } catch { return undefined }\n })()\n const deviceModel = nonEmpty(env['TRAE_DEVICE_MODEL'])\n const deviceKeyPair = deviceKeyPairOf(storage)\n return {\n edition: candidate.edition,\n machineId,\n deviceId,\n ...appVersion === undefined ? {} : { appVersion },\n ...buildVersion === undefined ? {} : { buildVersion },\n ...deviceBrand === undefined ? {} : { deviceBrand },\n ...deviceCpu === undefined ? {} : { deviceCpu },\n ...deviceName === undefined ? {} : { deviceName },\n ...deviceModel === undefined ? {} : { deviceModel },\n ...deviceKeyPair === undefined ? {} : { deviceKeyPair },\n osVersion,\n platform,\n }\n}\n\n/** Detect a missing storage file (as opposed to a parse/identity error). */\nfunction isFileMissing(error: unknown): boolean {\n return typeof error === 'object' && error !== null && 'code' in error && (error as { code?: unknown }).code === 'ENOENT'\n}\n\n/** Prefix of the \"no candidate exists on disk\" error; see {@link resolveTraeIdentity}. */\nconst STORAGE_MISSING_PREFIX = 'Trae storage was not found'\n\n/**\n * Try candidates in order and return the first that yields a valid identity;\n * fail hard only when none do. Mirrors the credential store's skip-missing\n * semantics so a machine with only SOLO (no CN install) resolves correctly\n * instead of pinning the first candidate and throwing on a missing file.\n * When every candidate is absent from disk the error names all tried paths;\n * a candidate that exists but fails to parse still surfaces its own error.\n */\nexport async function pickTraeStorageIdentity(\n candidates: readonly TraeStorageCandidate[],\n options: TraeIdentityReadOptions = {},\n): Promise<TraeIdentity> {\n let lastError: unknown\n let anyPresent = false\n for (const candidate of candidates) {\n try {\n return await readTraeIdentity(candidate, options)\n } catch (error) {\n lastError = error\n if (!isFileMissing(error)) anyPresent = true\n }\n }\n const tried = candidates.map(item => item.path).join(' or ')\n if (!anyPresent) throw new Error(`${STORAGE_MISSING_PREFIX} (${tried})`)\n throw lastError instanceof Error ? lastError : new Error(`Trae identity could not be resolved (${tried})`)\n}\n\n/** CLI dotfile home per edition; the CLI keeps its own home, not an Application Support entry. */\nconst CLI_HOME_BY_EDITION: Readonly<Record<TraeEdition, string>> = {\n cn: '.trae-cn',\n solo: '.trae-cn',\n sg: '.trae',\n 'solo-sg': '.trae',\n}\n\n/**\n * Deterministic identity for a machine that only has the Trae CLI (`traecli`).\n *\n * A CLI-only machine has no desktop `storage.json`, so the desktop identity\n * reader has nothing to read \u2014 yet the request headers still need stable\n * machine/device ids. Everything here comes from identifiers the CLI itself\n * persists (never a per-request random value):\n *\n * - `argv.json`'s `crash-reporter-id` \u2014 a stable per-install UUID the CLI\n * writes on first run; used directly as the device id.\n * - `builtin/ide_version.json`'s `version` \u2014 the CLI build, sent as\n * `x-app-version` (the desktop reader gets this from `product.json`).\n * - a SHA-256 over the device id, host name and user name for `machineId`,\n * matching the 64-char hex shape the official clients send.\n *\n * When `crash-reporter-id` is absent the device id falls back to the same\n * hash (still deterministic). A machine with no CLI home at all keeps failing\n * loudly \u2014 a fabricated identity is worse than a visible \"not signed in\".\n */\nexport async function readTraeCliIdentity(\n edition: TraeEdition,\n options: TraeIdentityReadOptions = {},\n): Promise<TraeIdentity> {\n const platform = options.platform ?? process.platform\n const home = options.home ?? homedir()\n const env = options.env ?? process.env\n const cliHome = join(home, CLI_HOME_BY_EDITION[edition])\n const argv = await readJsonFile(join(cliHome, 'argv.json'))\n const version = await readJsonFile(join(cliHome, 'builtin', 'ide_version.json'))\n const crashReporterId = nonEmpty(argv?.['crash-reporter-id'])\n const host = nonEmpty(env['HOSTNAME']) ?? await readHostname() ?? 'unknown-host'\n const user = nonEmpty(env['USER']) ?? nonEmpty(env['USERNAME']) ?? 'unknown-user'\n const deviceId = crashReporterId ?? createHash('sha256').update(`trae-cli\\0${host}\\0${user}`).digest('hex').slice(0, 32)\n const machineId = createHash('sha256').update(`trae-cli-machine\\0${deviceId}\\0${host}`).digest('hex')\n const appVersion = nonEmpty(version?.['version'])\n const deviceCpu = cpus()[0]?.model.split(' ')[0]\n const osVersion = `${platform === 'darwin' ? 'macOS' : platform === 'win32' ? 'Windows' : platform} ${release()}`\n return {\n edition,\n machineId,\n deviceId,\n ...appVersion === undefined ? {} : { appVersion },\n ...deviceCpu === undefined ? {} : { deviceCpu },\n osVersion,\n platform,\n }\n}\n\n/** Read and parse a JSON file, tolerating absence and malformed content. */\nasync function readJsonFile(path: string): Promise<Record<string, unknown> | undefined> {\n try {\n const parsed = JSON.parse(await readFile(path, 'utf8')) as unknown\n return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)\n ? parsed as Record<string, unknown>\n : undefined\n } catch {\n return undefined\n }\n}\n\n/** OS host name, or undefined when unavailable. */\nasync function readHostname(): Promise<string | undefined> {\n try {\n const { hostname } = await import('node:os')\n return nonEmpty(hostname())\n } catch {\n return undefined\n }\n}\n\n/**\n * Resolve the request identity for one region: the desktop storage identity\n * when any desktop install exists, otherwise the CLI home's deterministic\n * identity (see {@link readTraeCliIdentity}).\n *\n * This is the seam the WSL2 / CLI-only case needs: `traecli` writes its token\n * to `~/.trae-cn/trae-jwt-token` and no `storage.json` exists anywhere, so\n * desktop-only resolution used to fail every directory refresh and chat\n * request even though the account itself was found.\n */\nexport async function resolveTraeIdentity(\n candidates: readonly TraeStorageCandidate[],\n edition: TraeEdition,\n options: TraeIdentityReadOptions = {},\n): Promise<TraeIdentity> {\n try {\n return await pickTraeStorageIdentity(candidates, options)\n } catch (error) {\n if (!(error instanceof Error) || !error.message.startsWith(STORAGE_MISSING_PREFIX)) throw error\n return readTraeCliIdentity(edition, options)\n }\n}\n\n/** Headers derived from actual persisted identity, never a new random identity per request. */\nexport function identityHeaders(identity: TraeIdentity): Record<string, string> {\n return {\n 'x-machine-id': identity.machineId,\n 'x-device-id': identity.deviceId,\n 'x-device-type': identity.platform === 'darwin' ? 'mac' : identity.platform === 'win32' ? 'windows' : identity.platform,\n ...identity.deviceBrand === undefined ? {} : { 'x-device-brand': identity.deviceBrand },\n ...identity.deviceCpu === undefined ? {} : { 'x-device-cpu': identity.deviceCpu },\n ...identity.osVersion === undefined ? {} : { 'x-os-version': identity.osVersion },\n ...identity.appVersion === undefined ? {} : { 'x-app-version': identity.appVersion, 'x-ide-version': identity.appVersion },\n ...identity.buildVersion === undefined ? {} : { 'x-app-version-code': identity.buildVersion, 'x-ide-version-code': identity.buildVersion },\n 'x-ide-version-type': 'stable',\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;AAGO,IAAM,wBAAwB;AAW9B,IAAM,uBAAuB;AAU7B,IAAM,2BAA2B;AACjC,IAAM,0BAA0B;;;ACgFhC,IAAM,qBAAkD;AAAA,EAC7D;AAAA,IACE,IAAI;AAAA,IACJ,aAAa;AAAA,IACb,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,UAAU;AAAA,MACR,aAAa;AAAA,MACb,QAAQ;AAAA,MACR,OAAO;AAAA,QACL,UAAU;AAAA,QACV,aAAa;AAAA,MACf;AAAA,MACA,SAAS;AAAA,QACP,oBAAoB;AAAA,QACpB,aAAa;AAAA,QACb,qBAAqB,CAAC,YAAY,aAAa,eAAe;AAAA,MAChE;AAAA,IACF;AAAA,IACA,iBAAiB;AAAA,IACjB,aAAa;AAAA,IACb,eAAe;AAAA,IACf,iBAAiB;AAAA,IACjB,oBAAoB;AAAA,IACpB,YAAY;AAAA,IACZ,WAAW;AAAA,EACb;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,aAAa;AAAA,IACb,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,UAAU;AAAA,MACR,aAAa;AAAA,MACb,QAAQ;AAAA,MACR,OAAO;AAAA,QACL,UAAU;AAAA,QACV,aAAa;AAAA,MACf;AAAA,MACA,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA,QAKP,oBAAoB;AAAA,QACpB,aAAa;AAAA,MACf;AAAA,IACF;AAAA,IACA,iBAAiB;AAAA,IACjB,aAAa;AAAA,IACb,eAAe;AAAA,IACf,iBAAiB;AAAA,IACjB,oBAAoB;AAAA,IACpB,YAAY;AAAA,IAC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AC,IAAI,EAAE,gBAAgB,SAAS,UAAU;AAAA,IAChF,GAAG,SAAS,cAAc,SAAY,CAAC,IAAI,EAAE,gBAAgB,SAAS,UAAU;AAAA,IAChF,GAAG,SAAS,eAAe,SAAY,CAAC,IAAI,EAAE,iBAAiB,SAAS,YAAY,iBAAiB,SAAS,WAAW;AAAA,IACzH,GAAG,SAAS,iBAAiB,SAAY,CAAC,IAAI,EAAE,sBAAsB,SAAS,cAAc,sBAAsB,SAAS,aAAa;AAAA,IACzI,sBAAsB;AAAA,EACxB;AACF;",
|
|
6
|
-
"names": ["basename", "dirname", "join", "join", "basename", "dirname", "isENOENT", "homedir", "join", "readFile", "rm", "createHash", "join", "withFileLock", "writeFileAtomic", "resolveDshHome", "createDecipheriv", "createHash", "join", "resolveDshHome", "optionalString", "createHash", "rm", "readFile", "withFileLock", "writeFileAtomic", "createHash", "readFile", "dirname", "join", "homedir", "release", "homedir", "readFile", "dirname", "join", "createHash", "release"]
|
|
5
|
+
"mappings": ";;;;;;;;;AAGO,IAAM,wBAAwB;AAW9B,IAAM,uBAAuB;AAU7B,IAAM,2BAA2B;AACjC,IAAM,0BAA0B;;;ACgFhC,IAAM,qBAAkD;AAAA,EAC7D;AAAA,IACE,IAAI;AAAA,IACJ,aAAa;AAAA,IACb,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,UAAU;AAAA,MACR,aAAa;AAAA,MACb,QAAQ;AAAA,MACR,OAAO;AAAA,QACL,UAAU;AAAA,QACV,aAAa;AAAA,MACf;AAAA,MACA,SAAS;AAAA,QACP,oBAAoB;AAAA,QACpB,aAAa;AAAA,QACb,qBAAqB,CAAC,YAAY,aAAa,eAAe;AAAA,MAChE;AAAA,IACF;AAAA,IACA,iBAAiB;AAAA,IACjB,aAAa;AAAA,IACb,eAAe;AAAA,IACf,iBAAiB;AAAA,IACjB,oBAAoB;AAAA,IACpB,YAAY;AAAA,IACZ,WAAW;AAAA,EACb;AAAA,EACA;AAAA,IAC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EACF;AACF;AA2IO,SAAS,gBAAgB,UAAgD;AAC9E,SAAO;AAAA,IACL,gBAAgB,SAAS;AAAA,IACzB,eAAe,SAAS;AAAA,IACxB,iBAAiB,SAAS,aAAa,WAAW,QAAQ,SAAS,aAAa,UAAU,YAAY,SAAS;AAAA,IAC/G,GAAG,SAAS,gBAAgB,SAAY,CAAC,IAAI,EAAE,kBAAkB,SAAS,YAAY;AAAA,IACtF,GAAG,SAAS,cAAc,SAAY,CAAC,IAAI,EAAE,gBAAgB,SAAS,UAAU;AAAA,IAChF,GAAG,SAAS,cAAc,SAAY,CAAC,IAAI,EAAE,gBAAgB,SAAS,UAAU;AAAA,IAChF,GAAG,SAAS,eAAe,SAAY,CAAC,IAAI,EAAE,iBAAiB,SAAS,YAAY,iBAAiB,SAAS,WAAW;AAAA,IACzH,GAAG,SAAS,iBAAiB,SAAY,CAAC,IAAI,EAAE,sBAAsB,SAAS,cAAc,sBAAsB,SAAS,aAAa;AAAA,IACzI,sBAAsB;AAAA,EACxB;AACF;",
|
|
6
|
+
"names": ["basename", "dirname", "join", "join", "basename", "dirname", "isENOENT", "join", "homedir", "join", "readFile", "rm", "createHash", "join", "withFileLock", "writeFileAtomic", "resolveDshHome", "createDecipheriv", "createHash", "join", "resolveDshHome", "optionalString", "createHash", "rm", "readFile", "withFileLock", "writeFileAtomic", "createHash", "readFile", "dirname", "join", "homedir", "release", "homedir", "readFile", "dirname", "join", "createHash", "release"]
|
|
7
7
|
}
|