dsh-workbuddy-xdpool 1.4.1 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/bin.js CHANGED
@@ -1,7 +1,9 @@
1
- import { createHash, randomUUID } from "node:crypto";
1
+ import { createDecipheriv, createHash, randomUUID } from "node:crypto";
2
2
  import { copyFile, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
3
3
  import { homedir, platform } from "node:os";
4
4
  import { basename, join, resolve } from "node:path";
5
+ import { execFile, execFileSync } from "node:child_process";
6
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
5
7
  import z from "@deepseek-ai/schemastery";
6
8
  import "@earendil-works/pi-ai";
7
9
  import "@earendil-works/pi-ai/api/openai-completions.lazy";
@@ -1574,6 +1576,489 @@ var WorkBuddyUpstreamClient = class {
1574
1576
  }
1575
1577
  };
1576
1578
  //#endregion
1579
+ //#region src/at-rest.ts
1580
+ /**
1581
+ * WorkBuddy desktop "at-rest" credential decryption.
1582
+ *
1583
+ * From 5.6.0 the WorkBuddy desktop app no longer stores `auth.accessToken` /
1584
+ * `auth.refreshToken` as plain strings. It writes a field wrapper:
1585
+ *
1586
+ * { "$wbEncrypted": 1, "envelope": "<base64 of a JSON envelope>" }
1587
+ *
1588
+ * where the envelope is `{suite, keyId, nonce, authTag, ciphertext}` for
1589
+ * AES-256-GCM with a 12-byte nonce and a 16-byte tag. The authenticated
1590
+ * additional data is a length-prefixed transcript over the scheme, suite,
1591
+ * keyId and framing, so the ciphertext can only be opened for the exact field
1592
+ * shape it was sealed for.
1593
+ *
1594
+ * The field key itself is NOT a user secret: it is a build-time constant
1595
+ * compiled into the app's own Electron native module
1596
+ * (`electron_browser_workbuddy_storage`). The app fetches it through
1597
+ * `loggerGet()` and hashes the returned base64 STRING (not the decoded bytes)
1598
+ * to obtain the 32-byte key; `keyId` is the first 16 hex characters of that
1599
+ * key's SHA-256.
1600
+ *
1601
+ * This module re-derives the same key by asking the installed app for the same
1602
+ * payload, and caches it in memory for the process lifetime. Nothing is ever
1603
+ * written to disk, and the payload is never logged.
1604
+ *
1605
+ * 溯源:本文件移植自 dingminhua/dsh-connect-workbuddy 的 src/at-rest.ts
1606
+ * (MIT,Copyright (c) 2026 LaoDing)——该模块最先定位并修复了「5.6.0 起
1607
+ * macOS 与 Windows 同样加密凭据」这一问题(其 issue #15 真机取证)。移植时
1608
+ * 保留其全部判定逻辑(CFBundleExecutable 向 bundle 自己问、按 bundle id
1609
+ * 确认身份后才 exec、field framing 的 AAD 转录、keyId 校验),未作改动。
1610
+ *
1611
+ * 改动:**「macOS 也加密」这一事实**(issue #15 真机取证)。本模块原先假设该
1612
+ * policy 是 Windows 先行、macOS 只是「将来可能」,于是 macOS 的可执行文件
1613
+ * 路径用 App 名拼成 `<bundle>/Contents/MacOS/WorkBuddy`——而两个真实 bundle
1614
+ * 的 `CFBundleExecutable` 都是 `Electron`,该路径并不存在。结果是 macOS 上
1615
+ * 加密凭据**永远**取不到密钥,用户却被报成「未登录」。现在二进制名向 bundle
1616
+ * 自己问(`macosBundleExecutable()`),候选含国际版 `WorkBuddy AI.app`,
1617
+ * 并允许 App 被归入 applications 目录的子目录——扫到的候选必须先用
1618
+ * `CFBundleIdentifier` 确认身份才 `execFile`,因为**每个 Electron 应用的
1619
+ * 二进制都叫 `Electron`**,只按名字匹配就可能启动另一个产品。
1620
+ *
1621
+ * @module dsh-workbuddy-xdpool/at-rest
1622
+ */
1623
+ /** Envelope framing names, mapped to the single-byte AAD framing code. */
1624
+ const FRAMING_CODE = {
1625
+ file: 1,
1626
+ field: 2,
1627
+ record: 3,
1628
+ stream: 4
1629
+ };
1630
+ /** Standard (symmetric) format identifiers, transcripted into the AAD. */
1631
+ const STANDARD_FORMAT_ID = {
1632
+ file: "WBEF1",
1633
+ field: "WBEV1",
1634
+ record: "WBER1",
1635
+ stream: "WBES1"
1636
+ };
1637
+ /** Domain separator the AAD transcript starts with. */
1638
+ const AAD_DOMAIN = Buffer.from("WB-AAD\0", "ascii");
1639
+ /** Scheme name of the symmetric envelope this module opens. */
1640
+ const SYMMETRIC_SCHEME = "sym-v1";
1641
+ /** Env override pointing at the WorkBuddy desktop executable. */
1642
+ const WORKBUDDY_APP_EXECUTABLE_ENV = "WORKBUDDY_APP_EXECUTABLE";
1643
+ /** How long the app is given to answer with its key payload. */
1644
+ const KEY_FETCH_TIMEOUT_MS = 1e4;
1645
+ /**
1646
+ * Executable file names the desktop app ships under, in probe order.
1647
+ *
1648
+ * `WorkBuddyAI.exe` is the INTERNATIONAL build; both apps can be installed side
1649
+ * by side (observed on a real machine: `D:\\workbuddy\\WorkBuddy.exe` for the
1650
+ * domestic one and `D:\\workbuddyai\\WorkBuddyAI.exe` for the international one),
1651
+ * so the name cannot be assumed.
1652
+ */
1653
+ const APP_EXECUTABLE_NAMES = ["WorkBuddy.exe", "WorkBuddyAI.exe"];
1654
+ /**
1655
+ * macOS bundles the desktop app may be installed as, in probe order.
1656
+ *
1657
+ * `WorkBuddy.app` is the domestic build; `WorkBuddy AI.app` is the
1658
+ * international one, and a machine may carry either or both. The user-level
1659
+ * `~/Applications` location is included because macOS lets an app live there,
1660
+ * and installs have been observed under a subdirectory of /Applications too —
1661
+ * hence {@link findWorkbuddyAppExecutable}'s parent scan, which covers those
1662
+ * without guessing any particular folder name.
1663
+ */
1664
+ const MACOS_APP_BUNDLE_NAMES = ["WorkBuddy.app", "WorkBuddy AI.app"];
1665
+ function encodeUint32(value) {
1666
+ const bytes = Buffer.allocUnsafe(4);
1667
+ bytes.writeUInt32BE(value);
1668
+ return bytes;
1669
+ }
1670
+ /** Length-prefixed UTF-8 string: uint32 big-endian length followed by the bytes. */
1671
+ function encodeLengthPrefixed(value) {
1672
+ const bytes = Buffer.from(value, "utf8");
1673
+ return Buffer.concat([encodeUint32(bytes.length), bytes]);
1674
+ }
1675
+ /**
1676
+ * The authenticated additional data for one `sym-v1` FIELD-framed envelope.
1677
+ *
1678
+ * Only the field framing is implemented: it is the shape the desktop app uses
1679
+ * for credential fields, and it is also the shape that cannot be confused with
1680
+ * a whole-file envelope, so an unexpected framing is a parse error rather than
1681
+ * a silently wrong transcript.
1682
+ */
1683
+ function fieldAad(keyId, suite, scheme = SYMMETRIC_SCHEME) {
1684
+ if (!/^[0-9a-f]{16}$/u.test(keyId)) throw new Error(`workbuddy: envelope keyId is malformed`);
1685
+ return Buffer.concat([
1686
+ AAD_DOMAIN,
1687
+ Buffer.from([1]),
1688
+ encodeLengthPrefixed(STANDARD_FORMAT_ID["field"]),
1689
+ encodeLengthPrefixed(scheme),
1690
+ encodeUint32(suite),
1691
+ encodeLengthPrefixed(keyId),
1692
+ Buffer.from([FRAMING_CODE["field"]]),
1693
+ Buffer.from([0]),
1694
+ Buffer.from([0])
1695
+ ]);
1696
+ }
1697
+ /** Whether a value is the app's encrypted-field wrapper. */
1698
+ function isEncryptedFieldWrapper(value) {
1699
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
1700
+ const wrapper = value;
1701
+ const keys = Object.keys(wrapper).sort();
1702
+ return keys.length === 2 && keys[0] === "$wbEncrypted" && keys[1] === "envelope" && wrapper["$wbEncrypted"] === 1 && typeof wrapper["envelope"] === "string";
1703
+ }
1704
+ /**
1705
+ * The at-rest key id for a derived 32-byte key: the first 16 hex characters of
1706
+ * its SHA-256. This is what the envelope's `keyId` is checked against, so a
1707
+ * mismatched key fails loudly instead of returning garbage.
1708
+ */
1709
+ function deriveAtRestKeyId(key) {
1710
+ return createHash("sha256").update(key).digest("hex").slice(0, 16);
1711
+ }
1712
+ /**
1713
+ * Derive the 32-byte field key from the app's key payload JSON.
1714
+ *
1715
+ * The app hashes the payload's base64 STRING — not its decoded bytes — so the
1716
+ * same spelling is required here; hashing the decoded secret would produce a
1717
+ * different key and every field would fail to open.
1718
+ */
1719
+ function deriveAtRestKey(payloadJson) {
1720
+ let payload;
1721
+ try {
1722
+ payload = JSON.parse(payloadJson);
1723
+ } catch {
1724
+ throw new Error("workbuddy: at-rest key payload is not valid JSON");
1725
+ }
1726
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) throw new Error("workbuddy: at-rest key payload is not an object");
1727
+ const secret = payload["atRestSecretKey"];
1728
+ if (typeof secret !== "string" || secret === "") throw new Error("workbuddy: at-rest key payload carries no atRestSecretKey");
1729
+ return createHash("sha256").update(secret, "utf8").digest();
1730
+ }
1731
+ /**
1732
+ * Open one encrypted field with a derived key and return its plaintext.
1733
+ *
1734
+ * Throws when the envelope is malformed, belongs to another key, or fails
1735
+ * authentication — a GCM tag mismatch is the signal that the transcript or the
1736
+ * key is wrong, and it must never degrade into a truncated token.
1737
+ */
1738
+ function openEncryptedField(field, key) {
1739
+ let envelope;
1740
+ try {
1741
+ envelope = JSON.parse(Buffer.from(field.envelope, "base64").toString("utf8"));
1742
+ } catch {
1743
+ throw new Error("workbuddy: encrypted field envelope is not valid JSON");
1744
+ }
1745
+ if (typeof envelope !== "object" || envelope === null || Array.isArray(envelope)) throw new Error("workbuddy: encrypted field envelope is not an object");
1746
+ const record = envelope;
1747
+ const suite = record["suite"];
1748
+ const keyId = record["keyId"];
1749
+ const nonce = record["nonce"];
1750
+ const authTag = record["authTag"];
1751
+ const ciphertext = record["ciphertext"];
1752
+ if (typeof suite !== "number" || typeof keyId !== "string") throw new Error("workbuddy: encrypted field envelope is missing suite or keyId");
1753
+ if (typeof nonce !== "string" || typeof authTag !== "string" || typeof ciphertext !== "string") throw new Error("workbuddy: encrypted field envelope is missing nonce, authTag or ciphertext");
1754
+ const expectedKeyId = deriveAtRestKeyId(key);
1755
+ if (keyId !== expectedKeyId) throw new Error(`workbuddy: encrypted field belongs to key ${keyId}, not the available key ${expectedKeyId}`);
1756
+ const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(nonce, "base64"), { authTagLength: 16 });
1757
+ decipher.setAAD(fieldAad(keyId, suite));
1758
+ decipher.setAuthTag(Buffer.from(authTag, "base64"));
1759
+ return Buffer.concat([decipher.update(Buffer.from(ciphertext, "base64")), decipher.final()]).toString("utf8");
1760
+ }
1761
+ /**
1762
+ * The key id an encrypted field envelope demands, or undefined when the
1763
+ * envelope cannot be read.
1764
+ *
1765
+ * The account pool uses it to pick the right desktop build's key when more
1766
+ * than one build (domestic and international) is installed on the same machine:
1767
+ * each `.info` file names the key id its fields were sealed under, so the opener
1768
+ * must select the matching derived key rather than assume one build exists.
1769
+ */
1770
+ function encryptedFieldKeyId(field) {
1771
+ try {
1772
+ const record = JSON.parse(Buffer.from(field.envelope, "base64").toString("utf8"));
1773
+ return typeof record["keyId"] === "string" ? record["keyId"] : void 0;
1774
+ } catch {
1775
+ return;
1776
+ }
1777
+ }
1778
+ /**
1779
+ * The executable inside a macOS app bundle, read from the bundle's own
1780
+ * `Info.plist`.
1781
+ *
1782
+ * The binary is NOT reliably named after the app: the WorkBuddy bundles ship
1783
+ * with `CFBundleExecutable` set to `Electron`, so a path assembled as
1784
+ * `<bundle>/Contents/MacOS/WorkBuddy` does not exist and the app looks absent
1785
+ * even when it is installed in the default location. Because the bundle
1786
+ * documents the real name, asking it is both correct and robust to a future
1787
+ * build that renames the binary.
1788
+ *
1789
+ * Returns undefined when the plist is absent, unreadable, or carries no usable
1790
+ * name — never a guessed path, so a caller can keep probing.
1791
+ */
1792
+ function macosBundleExecutable(bundle) {
1793
+ let plist;
1794
+ try {
1795
+ plist = readFileSync(join(bundle, "Contents", "Info.plist"), "utf8");
1796
+ } catch {
1797
+ return;
1798
+ }
1799
+ const name = /<key>\s*CFBundleExecutable\s*<\/key>\s*<string>([^<]*)<\/string>/u.exec(plist)?.[1]?.trim();
1800
+ if (name === void 0 || name === "" || name.includes("/") || name.includes("\\") || name === "." || name === "..") return;
1801
+ return join(bundle, "Contents", "MacOS", name);
1802
+ }
1803
+ /**
1804
+ * Windows install locations recorded by the app's own uninstaller.
1805
+ *
1806
+ * The registry is the authoritative answer: it survives a non-default drive, a
1807
+ * renamed folder and a differently-named executable, none of which any fixed
1808
+ * path list can predict. Real machines put the app at `D:\workbuddy\WorkBuddy.exe`
1809
+ * and `D:\workbuddyai\WorkBuddyAI.exe` — exactly the layouts a
1810
+ * `%ProgramFiles%\WorkBuddy\WorkBuddy.exe` probe cannot see, which is why the
1811
+ * plugin reported "the desktop app could not provide the key" for an app that was
1812
+ * installed and running.
1813
+ *
1814
+ * `DisplayIcon` is the field that actually carries the path (observed as
1815
+ * `D:\workbuddy\WorkBuddy.exe,0`); `InstallLocation` is usually empty for these
1816
+ * installers, so both are read and either may contribute.
1817
+ *
1818
+ * Returns [] on any failure — a missing registry key is the normal case on
1819
+ * non-Windows, not an error.
1820
+ */
1821
+ function windowsRegistryAppPaths() {
1822
+ if (process.platform !== "win32") return [];
1823
+ const roots = [
1824
+ ["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", "/**"],
1825
+ ["HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall", "/**"],
1826
+ ["HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", "/**"]
1827
+ ];
1828
+ const out = [];
1829
+ for (const [root] of roots) {
1830
+ let listing;
1831
+ try {
1832
+ listing = execFileSync("reg", [
1833
+ "query",
1834
+ root,
1835
+ "/s",
1836
+ "/v",
1837
+ "DisplayName"
1838
+ ], {
1839
+ encoding: "utf8",
1840
+ timeout: 1e4,
1841
+ windowsHide: true,
1842
+ maxBuffer: 8388608
1843
+ });
1844
+ } catch {
1845
+ continue;
1846
+ }
1847
+ const keys = listing.split(/\r?\n(?=HKEY_)/u).filter((block) => /WorkBuddy|CodeBuddy/iu.test(block));
1848
+ for (const key of keys) {
1849
+ const keyPath = /^(HKEY_[^\r\n]+)/u.exec(key)?.[1]?.trim();
1850
+ if (keyPath === void 0) continue;
1851
+ for (const name of ["DisplayIcon", "InstallLocation"]) try {
1852
+ const value = execFileSync("reg", [
1853
+ "query",
1854
+ keyPath,
1855
+ "/v",
1856
+ name
1857
+ ], {
1858
+ encoding: "utf8",
1859
+ timeout: 5e3,
1860
+ windowsHide: true
1861
+ });
1862
+ const raw = /REG_(?:SZ|EXPAND_SZ)\s+(.+)$/mu.exec(value)?.[1]?.trim();
1863
+ if (raw === void 0 || raw === "") continue;
1864
+ const cleaned = raw.replace(/^"/u, "").replace(/",-?\d+$/u, "").replace(/,-?\d+$/u, "").trim();
1865
+ out.push(cleaned);
1866
+ } catch {}
1867
+ }
1868
+ }
1869
+ return out;
1870
+ }
1871
+ /**
1872
+ * Windows fallbacks for an app the registry did not cover: the well-known
1873
+ * per-user and machine-wide locations, plus every fixed drive's `Program Files`.
1874
+ *
1875
+ * Drive enumeration matters because installing to a non-system drive is common
1876
+ * on Windows and no environment variable points there.
1877
+ */
1878
+ function windowsFallbackAppPaths(env) {
1879
+ const out = [];
1880
+ const roots = /* @__PURE__ */ new Set();
1881
+ for (const key of [
1882
+ "ProgramFiles",
1883
+ "ProgramW6432",
1884
+ "ProgramFiles(x86)",
1885
+ "LOCALAPPDATA"
1886
+ ]) {
1887
+ const value = env[key]?.trim();
1888
+ if (value !== void 0 && value !== "") roots.add(value);
1889
+ }
1890
+ for (let code = 67; code <= 90; code += 1) {
1891
+ const drive = String.fromCharCode(code) + ":\\";
1892
+ try {
1893
+ if (!existsSync(drive)) continue;
1894
+ } catch {
1895
+ continue;
1896
+ }
1897
+ roots.add(join(drive, "Program Files"));
1898
+ roots.add(join(drive, "Program Files (x86)"));
1899
+ }
1900
+ for (const root of roots) for (const name of APP_EXECUTABLE_NAMES) {
1901
+ out.push(join(root, "WorkBuddy", name));
1902
+ out.push(join(root, "WorkBuddy AI", name));
1903
+ out.push(join(root, "Programs", "WorkBuddy", name));
1904
+ }
1905
+ for (const root of roots) try {
1906
+ for (const entry of readdirSync(root)) {
1907
+ if (!/^(workbuddy|codebuddy)/iu.test(entry)) continue;
1908
+ for (const name of APP_EXECUTABLE_NAMES) out.push(join(root, entry, name));
1909
+ }
1910
+ } catch {}
1911
+ return out;
1912
+ }
1913
+ /**
1914
+ * Candidate paths of the WorkBuddy desktop executable, in probe order.
1915
+ *
1916
+ * Order is deliberate:
1917
+ * 1. the explicit override, because a user who set it knows where the app is;
1918
+ * 2. the registry, which is what the installer itself recorded;
1919
+ * 3. derived fallbacks (per-user, machine-wide, every fixed drive).
1920
+ *
1921
+ * Only the Windows branch consults the registry (it is the only platform with
1922
+ * one). macOS asks each bundle for its own `CFBundleExecutable` instead, because
1923
+ * the WorkBuddy bundles ship a binary named `Electron`, not after the app.
1924
+ *
1925
+ * `readBundleExecutable` and `registryPaths` are injectable in the same spirit as
1926
+ * `platform`/`home`/`env`: both consult the real machine, so without a seam the
1927
+ * expected candidates would depend on what happens to be installed where the
1928
+ * suite runs — passing on a developer's box and failing in CI.
1929
+ */
1930
+ function workbuddyAppExecutableCandidates(platform = process.platform, home = homedir(), env = process.env, readBundleExecutable = macosBundleExecutable, registryPaths = windowsRegistryAppPaths) {
1931
+ const candidates = [env[WORKBUDDY_APP_EXECUTABLE_ENV]?.trim()];
1932
+ if (platform === "win32") {
1933
+ candidates.push(...registryPaths());
1934
+ candidates.push(...windowsFallbackAppPaths(env));
1935
+ } else if (platform === "darwin") for (const name of MACOS_APP_BUNDLE_NAMES) candidates.push(readBundleExecutable(join("/Applications", name)), readBundleExecutable(join(home, "Applications", name)));
1936
+ return candidates.filter((candidate) => candidate !== void 0 && candidate !== "");
1937
+ }
1938
+ /**
1939
+ * Ask the installed desktop app for its key payload by running its own binary
1940
+ * as plain Node (`ELECTRON_RUN_AS_NODE`) and calling the native binding.
1941
+ *
1942
+ * The binding is the app's own public surface for this value, so the plugin
1943
+ * never has to carry a copy of a build-specific constant: it asks the very
1944
+ * build that wrote the file. The child is given no stdin and a hard timeout,
1945
+ * and its stdout is the only thing read.
1946
+ */
1947
+ function fetchAtRestKeyPayload(executable) {
1948
+ return new Promise((resolve, reject) => {
1949
+ execFile(executable, ["-e", "try{process.stdout.write(process._linkedBinding('electron_browser_workbuddy_storage').loggerGet())}catch(e){process.exitCode=3;process.stderr.write(String(e&&e.message||e))}"], {
1950
+ env: {
1951
+ ...process.env,
1952
+ ELECTRON_RUN_AS_NODE: "1"
1953
+ },
1954
+ timeout: KEY_FETCH_TIMEOUT_MS,
1955
+ windowsHide: true,
1956
+ maxBuffer: 1048576
1957
+ }, (error, stdout, stderr) => {
1958
+ if (error !== null) {
1959
+ reject(/* @__PURE__ */ new Error(`workbuddy: the desktop app did not provide its at-rest key (${stderr.trim() || error.message})`));
1960
+ return;
1961
+ }
1962
+ const payload = stdout.trim();
1963
+ if (payload === "") {
1964
+ reject(/* @__PURE__ */ new Error("workbuddy: the desktop app returned an empty at-rest key payload"));
1965
+ return;
1966
+ }
1967
+ resolve(payload);
1968
+ });
1969
+ });
1970
+ }
1971
+ /**
1972
+ * The desktop app's at-rest keys, indexed by the key id each derived key
1973
+ * reports (the first 16 hex of its SHA-256).
1974
+ *
1975
+ * More than one build can be installed on one machine — the domestic
1976
+ * `WorkBuddy.exe` and the international `WorkBuddyAI.exe` share a key id on the
1977
+ * builds seen here, but a future build may rotate it, and the discovery below
1978
+ * must keep working if they ever diverge. A field envelope names the key id it
1979
+ * was sealed under, so the opener selects the matching derived key instead of
1980
+ * assuming a single build exists. Cached per process and never persisted.
1981
+ */
1982
+ const atRestKeyById = /* @__PURE__ */ new Map();
1983
+ let inflightKeys;
1984
+ /**
1985
+ * When the last full key sweep failed, and how long that failure is trusted.
1986
+ *
1987
+ * Without this, EVERY credential read spawned the app and waited out the
1988
+ * 10-second timeout before giving up — which is what made "rescan accounts" and
1989
+ * every status poll crawl on a machine where the app could not be found. A
1990
+ * failure is negative-cached briefly: long enough that a burst of reads costs
1991
+ * one sweep, short enough that installing or starting the app is picked up
1992
+ * without restarting DSH.
1993
+ */
1994
+ let lastKeyFailureAtMs = 0;
1995
+ const KEY_FAILURE_BACKOFF_MS = 6e4;
1996
+ /**
1997
+ * Load every desktop build's key id into {@link atRestKeyById}.
1998
+ *
1999
+ * Mirrors the reference `provideTheKey` shape: probe EVERY candidate executable
2000
+ * (not just the first that exists) and keep the key each one yields. A build
2001
+ * that fails to answer — a timeout, a single-instance lock, an older build
2002
+ * without the native module — is skipped on its own and does NOT poison the
2003
+ * other builds, which is exactly the failure mode the single-candidate path
2004
+ * had: one bad spawn cached `undefined` for the whole process and every
2005
+ * encrypted field then reported "no app could be located".
2006
+ */
2007
+ function ensureAtRestKeys() {
2008
+ if (atRestKeyById.size > 0) return Promise.resolve();
2009
+ if (Date.now() - lastKeyFailureAtMs < KEY_FAILURE_BACKOFF_MS) return Promise.resolve();
2010
+ inflightKeys ??= (async () => {
2011
+ const candidates = workbuddyAppExecutableCandidates().filter((candidate) => {
2012
+ try {
2013
+ return existsSync(candidate);
2014
+ } catch {
2015
+ return false;
2016
+ }
2017
+ });
2018
+ if (candidates.length === 0) {
2019
+ lastKeyFailureAtMs = Date.now();
2020
+ return;
2021
+ }
2022
+ let anySuccess = false;
2023
+ await Promise.all(candidates.map(async (executable) => {
2024
+ try {
2025
+ const key = deriveAtRestKey(await fetchAtRestKeyPayload(executable));
2026
+ atRestKeyById.set(deriveAtRestKeyId(key), key);
2027
+ anySuccess = true;
2028
+ } catch {}
2029
+ }));
2030
+ if (anySuccess) lastKeyFailureAtMs = 0;
2031
+ else lastKeyFailureAtMs = Date.now();
2032
+ })().finally(() => {
2033
+ inflightKeys = void 0;
2034
+ });
2035
+ return inflightKeys;
2036
+ }
2037
+ /**
2038
+ * Synchronous key lookup for a key id already loaded by {@link ensureAtRestKeys}.
2039
+ *
2040
+ * The account pool warms the cache up front (via {@link readAtRestKey}) and then
2041
+ * opens each encrypted field through a synchronous closure, because the parser
2042
+ * runs `decrypt` inline. Lookups that race the warm-up, or ask for a key id no
2043
+ * installed build produced, return undefined and are reported as the
2044
+ * encrypted-but-unavailable error rather than a silently empty token.
2045
+ */
2046
+ function atRestKeyFor(keyId) {
2047
+ return atRestKeyById.get(keyId);
2048
+ }
2049
+ /**
2050
+ * Backwards-compatible single-key view: the first key any build provided.
2051
+ *
2052
+ * Kept so callers that do not yet carry a key id (and the legacy tests) still
2053
+ * resolve to a usable key on single-build machines. Multi-build callers should
2054
+ * prefer {@link readAtRestKeyById} and select by the field's own key id.
2055
+ */
2056
+ function readAtRestKey() {
2057
+ return ensureAtRestKeys().then(() => {
2058
+ for (const key of atRestKeyById.values()) return key;
2059
+ });
2060
+ }
2061
+ //#endregion
1577
2062
  //#region src/accounts.ts
1578
2063
  /**
1579
2064
  * Account pool: discovers every WorkBuddy credential snapshot the desktop app
@@ -1621,11 +2106,81 @@ function optionalString(value) {
1621
2106
  return typeof value === "string" && value !== "" ? value : void 0;
1622
2107
  }
1623
2108
  /**
2109
+ * Read one string-valued field that may arrive as a plain string (older builds)
2110
+ * or as the desktop app's `$wbEncrypted` envelope. The app started encrypting
2111
+ * `accessToken` / `refreshToken` / `nickname` in 5.6.0 on BOTH macOS and Windows
2112
+ * — the earlier "Windows first" reading was wrong, and it is why a signed-in Mac
2113
+ * showed no account at all: the value is an object, `typeof === 'string'` failed,
2114
+ * and the parser reported "no credential" for a perfectly good sign-in.
2115
+ *
2116
+ * `decrypt` is injected rather than called here so this parser stays synchronous
2117
+ * and testable; the async key fetch lives in `readCredential`. A field that IS
2118
+ * encrypted but could not be opened is reported as `failed` rather than as an
2119
+ * empty string — the caller must tell the user the app is missing or unreachable,
2120
+ * not send them to sign in again (the one action that cannot help).
2121
+ */
2122
+ /**
2123
+ * Marker for "the credential is encrypted and we could not obtain the key".
2124
+ *
2125
+ * Carried as a `code` rather than left to `instanceof` because the value crosses
2126
+ * the packaged-plugin boundary; the same convention the sibling error types use.
2127
+ * This is deliberately NOT "not signed in": the user IS signed in, and telling
2128
+ * them to sign in again sends them to the one action that cannot help.
2129
+ */
2130
+ const ENCRYPTED_CREDENTIAL_CODE = "ENCRYPTED_CREDENTIAL";
2131
+ var WorkBuddyEncryptedCredentialError = class extends Error {
2132
+ code = ENCRYPTED_CREDENTIAL_CODE;
2133
+ constructor(sourcePath) {
2134
+ super(`workbuddy: ${sourcePath} holds encrypted credentials, but no WorkBuddy desktop app could be located to provide the key. If the app IS installed, it is simply outside the paths this plugin probes — set WORKBUDDY_APP_EXECUTABLE to its full .exe path (then restart DSH) and the credential will open. Signing in again will not help: the credential itself is intact. Run \`dsh-workbuddy-xdpool doctor\` to see which paths were probed.`);
2135
+ this.name = "WorkBuddyEncryptedCredentialError";
2136
+ }
2137
+ };
2138
+ /** True when a thrown value is the encrypted-credential marker (cross-bundle safe). */
2139
+ function isEncryptedCredentialError(value) {
2140
+ return typeof value === "object" && value !== null && value.code === "ENCRYPTED_CREDENTIAL";
2141
+ }
2142
+ function decryptableString(value, decrypt) {
2143
+ if (typeof value === "string") return {
2144
+ value,
2145
+ encrypted: false,
2146
+ failed: false
2147
+ };
2148
+ if (isEncryptedFieldWrapper(value)) {
2149
+ if (decrypt === void 0) return {
2150
+ value: "",
2151
+ encrypted: true,
2152
+ failed: true
2153
+ };
2154
+ try {
2155
+ return {
2156
+ value: decrypt(value),
2157
+ encrypted: true,
2158
+ failed: false
2159
+ };
2160
+ } catch {
2161
+ return {
2162
+ value: "",
2163
+ encrypted: true,
2164
+ failed: true
2165
+ };
2166
+ }
2167
+ }
2168
+ return {
2169
+ value: "",
2170
+ encrypted: false,
2171
+ failed: false
2172
+ };
2173
+ }
2174
+ /**
1624
2175
  * Parse a WorkBuddy auth document. Accepts the nested desktop shape
1625
2176
  * `{"auth":{...},"account":{...}}` and the flat panel shape; returns undefined
1626
2177
  * when there is no usable access token.
2178
+ *
2179
+ * `decrypt` opens the desktop app's `$wbEncrypted` field wrapper (5.6.0+, both
2180
+ * platforms). Absent means "plain-string builds only", which is what every
2181
+ * caller without an at-rest key should pass.
1627
2182
  */
1628
- function parseWorkBuddyAuth(text, sourcePath) {
2183
+ function parseWorkBuddyAuth(text, sourcePath, decrypt) {
1629
2184
  let parsed;
1630
2185
  try {
1631
2186
  parsed = JSON.parse(text);
@@ -1643,18 +2198,20 @@ function parseWorkBuddyAuth(text, sourcePath) {
1643
2198
  auth = document;
1644
2199
  identity = document;
1645
2200
  }
1646
- const accessToken = typeof auth["accessToken"] === "string" ? auth["accessToken"] : "";
2201
+ const accessField = decryptableString(auth["accessToken"], decrypt);
2202
+ if (accessField.encrypted && accessField.failed) throw new WorkBuddyEncryptedCredentialError(sourcePath);
2203
+ const accessToken = accessField.value;
1647
2204
  if (accessToken === "") return void 0;
1648
2205
  const refreshExpiresAtMs = typeof auth["refreshExpiresAt"] === "number" ? expiryToMs(auth["refreshExpiresAt"]) : void 0;
1649
2206
  if (refreshExpiresAtMs !== void 0 && refreshExpiresAtMs > 0 && refreshExpiresAtMs < Date.now()) return;
1650
2207
  const lastRefreshAtMs = typeof auth["lastRefreshTime"] === "number" ? expiryToMs(auth["lastRefreshTime"]) : void 0;
1651
2208
  return {
1652
2209
  accessToken,
1653
- refreshToken: typeof auth["refreshToken"] === "string" ? auth["refreshToken"] : "",
2210
+ refreshToken: decryptableString(auth["refreshToken"], decrypt).value,
1654
2211
  expiresAtMs: typeof auth["expiresAt"] === "number" ? expiryToMs(auth["expiresAt"]) : 0,
1655
2212
  ...refreshExpiresAtMs === void 0 ? {} : { refreshExpiresAtMs },
1656
2213
  ...lastRefreshAtMs === void 0 ? {} : { lastRefreshAtMs },
1657
- ...optionalString(identity["nickname"]) === void 0 ? {} : { nickname: optionalString(identity["nickname"]) },
2214
+ ...optionalString(decryptableString(identity["nickname"], decrypt).value) === void 0 ? {} : { nickname: optionalString(decryptableString(identity["nickname"], decrypt).value) },
1658
2215
  ...optionalString(identity["uin"]) === void 0 ? {} : { uin: optionalString(identity["uin"]) },
1659
2216
  ...optionalString(identity["uid"]) === void 0 ? {} : { uid: optionalString(identity["uid"]) },
1660
2217
  ...optionalString(identity["enterpriseId"]) === void 0 ? {} : { enterpriseId: optionalString(identity["enterpriseId"]) },
@@ -1736,11 +2293,37 @@ async function authFilesIn(dir) {
1736
2293
  return files.map((name) => join(dir, name));
1737
2294
  }
1738
2295
  async function readCredential(path) {
2296
+ let text;
1739
2297
  try {
1740
- return parseWorkBuddyAuth(await readFile(path, "utf8"), path);
2298
+ text = await readFile(path, "utf8");
1741
2299
  } catch {
1742
2300
  return;
1743
2301
  }
2302
+ const decrypt = text.includes("\"$wbEncrypted\"") ? await encryptedFieldOpener() : void 0;
2303
+ try {
2304
+ return parseWorkBuddyAuth(text, path, decrypt);
2305
+ } catch (error) {
2306
+ if (isEncryptedCredentialError(error)) throw error;
2307
+ return;
2308
+ }
2309
+ }
2310
+ /**
2311
+ * Build the field opener, or undefined when the app cannot supply its key.
2312
+ *
2313
+ * Split out so the key lookup is testable without a real desktop install, and so
2314
+ * a lookup failure degrades to "encrypted, unopenable" rather than to a parse
2315
+ * error that would look like a corrupt file.
2316
+ */
2317
+ async function encryptedFieldOpener() {
2318
+ await readAtRestKey().catch(() => void 0);
2319
+ return (field) => {
2320
+ if (!isEncryptedFieldWrapper(field)) throw new Error("workbuddy: not an encrypted field wrapper");
2321
+ const keyId = encryptedFieldKeyId(field);
2322
+ if (keyId === void 0) throw new Error("workbuddy: encrypted field has no key id");
2323
+ const key = atRestKeyFor(keyId);
2324
+ if (key === void 0) throw new Error("workbuddy: no at-rest key available for this encrypted field");
2325
+ return openEncryptedField(field, key);
2326
+ };
1744
2327
  }
1745
2328
  /** Every directory the pool should scan, in probe order. */
1746
2329
  function candidateAuthDirs(env = process.env) {
@@ -2848,10 +3431,37 @@ function diffEarnings(before, after) {
2848
3431
  accounts
2849
3432
  };
2850
3433
  }
2851
- function dayKey(date) {
2852
- const month = String(date.getMonth() + 1).padStart(2, "0");
2853
- const day = String(date.getDate()).padStart(2, "0");
2854
- return `${date.getFullYear()}-${month}-${day}`;
3434
+ /**
3435
+ * The timezone every hour in this file is interpreted in.
3436
+ *
3437
+ * The activity windows these jobs target are defined in Beijing time, but the
3438
+ * scheduler used `getHours()`, which answers in the host machine's local zone.
3439
+ * On a machine set to anything else, "09:00" was 09:00 local — a check-in that
3440
+ * simply never came due. Naming the zone makes the hour mean the same instant
3441
+ * everywhere DSH runs, and is also what lets a test pin the behaviour.
3442
+ */
3443
+ const AUTOMATION_TIME_ZONE = "Asia/Shanghai";
3444
+ /** Calendar parts of `date` in `timeZone`, all as zero-padded strings. */
3445
+ function zonedParts(date, timeZone = AUTOMATION_TIME_ZONE) {
3446
+ const parts = new Intl.DateTimeFormat("en-CA", {
3447
+ timeZone,
3448
+ year: "numeric",
3449
+ month: "2-digit",
3450
+ day: "2-digit",
3451
+ hour: "2-digit",
3452
+ hourCycle: "h23"
3453
+ }).formatToParts(date);
3454
+ const pick = (type) => parts.find((part) => part.type === type)?.value ?? "00";
3455
+ return {
3456
+ year: pick("year"),
3457
+ month: pick("month"),
3458
+ day: pick("day"),
3459
+ hour: pick("hour")
3460
+ };
3461
+ }
3462
+ function dayKey(date, timeZone = AUTOMATION_TIME_ZONE) {
3463
+ const { year, month, day } = zonedParts(date, timeZone);
3464
+ return `${year}-${month}-${day}`;
2855
3465
  }
2856
3466
  /**
2857
3467
  * The scheduled SLOT `date` falls in, as `YYYY-MM-DDTHH`.
@@ -2860,20 +3470,9 @@ function dayKey(date) {
2860
3470
  * for several hours runs in each of them while a second tick inside the same
2861
3471
  * hour is still refused.
2862
3472
  */
2863
- function slotKey(date) {
2864
- return `${dayKey(date)}T${String(date.getHours()).padStart(2, "0")}`;
2865
- }
2866
- /**
2867
- * Whether `now`'s local hour is one of `hours`.
2868
- *
2869
- * The reference panel computes a `nextFire` instant and sleeps until it; this
2870
- * loop instead wakes every minute and asks "is any job due now". Both fire at
2871
- * the top of a configured hour, but the polling form cannot miss a slot to a
2872
- * suspended process — a laptop that slept through 10:00 still runs the job the
2873
- * moment it wakes, on the same day.
2874
- */
2875
- function isFireHour(now, hours) {
2876
- return hours.includes(now.getHours());
3473
+ function slotKey(date, timeZone = AUTOMATION_TIME_ZONE) {
3474
+ const { hour } = zonedParts(date, timeZone);
3475
+ return `${dayKey(date, timeZone)}T${hour}`;
2877
3476
  }
2878
3477
  /** Whether this account may be used: not switched off, not cooling. */
2879
3478
  function eligible(account, now) {
@@ -3136,6 +3735,22 @@ var WorkBuddyScheduler = class {
3136
3735
  * rate-limits per account, so overlapping passes would only trip that limit.
3137
3736
  * A job that throws is recorded and the loop continues.
3138
3737
  */
3738
+ /**
3739
+ * Whether `kind` is due at `now`: its earliest configured hour has passed in
3740
+ * the scheduling timezone, and no hour of today has been consumed yet.
3741
+ *
3742
+ * Hours are consumed per SLOT (one entry per configured hour), so a job with
3743
+ * two hours still runs twice a day — but a job whose hour passed while DSH was
3744
+ * closed runs immediately on the next tick instead of waiting for tomorrow.
3745
+ */
3746
+ isDue(kind, now) {
3747
+ const hours = this.hoursOf(kind);
3748
+ if (hours.length === 0) return false;
3749
+ const { hour } = zonedParts(now);
3750
+ const current = Number(hour);
3751
+ const today = dayKey(now);
3752
+ return hours.some((candidate) => candidate <= current && this.states[kind].lastRunSlot !== `${today}T${String(candidate).padStart(2, "0")}`);
3753
+ }
3139
3754
  async tick() {
3140
3755
  if (!this.enabled || this.stopped || this.busy) return;
3141
3756
  this.busy = true;
@@ -3146,7 +3761,7 @@ var WorkBuddyScheduler = class {
3146
3761
  for (const kind of JOB_KINDS) {
3147
3762
  if (this.stopped) return;
3148
3763
  if (this.states[kind].lastRunSlot === slot) continue;
3149
- if (!isFireHour(now, this.hoursOf(kind))) continue;
3764
+ if (!this.isDue(kind, now)) continue;
3150
3765
  await this.runJob(kind, today);
3151
3766
  }
3152
3767
  } catch (error) {