dsh-workbuddy-xdpool 1.4.0 → 1.5.2
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 +122 -0
- package/lib/bin.js +525 -27
- package/lib/client.js +89 -30
- package/lib/index.d.ts +15 -2
- package/lib/index.js +574 -46
- package/package.json +1 -1
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 } from "node:child_process";
|
|
6
|
+
import { existsSync, readFileSync, readdirSync, statSync } 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,375 @@ 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
|
+
/** File name of the WorkBuddy desktop executable on Windows. */
|
|
1646
|
+
const APP_EXECUTABLE_NAME = "WorkBuddy.exe";
|
|
1647
|
+
/**
|
|
1648
|
+
* macOS bundles the desktop app may be installed as, in probe order.
|
|
1649
|
+
*
|
|
1650
|
+
* `WorkBuddy.app` is the domestic build; `WorkBuddy AI.app` is the
|
|
1651
|
+
* international one, and a machine may carry either or both. The user-level
|
|
1652
|
+
* `~/Applications` location is included because macOS lets an app live there,
|
|
1653
|
+
* and installs have been observed under a subdirectory of /Applications too —
|
|
1654
|
+
* hence {@link findWorkbuddyAppExecutable}'s parent scan, which covers those
|
|
1655
|
+
* without guessing any particular folder name.
|
|
1656
|
+
*/
|
|
1657
|
+
const MACOS_APP_BUNDLE_NAMES = ["WorkBuddy.app", "WorkBuddy AI.app"];
|
|
1658
|
+
function encodeUint32(value) {
|
|
1659
|
+
const bytes = Buffer.allocUnsafe(4);
|
|
1660
|
+
bytes.writeUInt32BE(value);
|
|
1661
|
+
return bytes;
|
|
1662
|
+
}
|
|
1663
|
+
/** Length-prefixed UTF-8 string: uint32 big-endian length followed by the bytes. */
|
|
1664
|
+
function encodeLengthPrefixed(value) {
|
|
1665
|
+
const bytes = Buffer.from(value, "utf8");
|
|
1666
|
+
return Buffer.concat([encodeUint32(bytes.length), bytes]);
|
|
1667
|
+
}
|
|
1668
|
+
/**
|
|
1669
|
+
* The authenticated additional data for one `sym-v1` FIELD-framed envelope.
|
|
1670
|
+
*
|
|
1671
|
+
* Only the field framing is implemented: it is the shape the desktop app uses
|
|
1672
|
+
* for credential fields, and it is also the shape that cannot be confused with
|
|
1673
|
+
* a whole-file envelope, so an unexpected framing is a parse error rather than
|
|
1674
|
+
* a silently wrong transcript.
|
|
1675
|
+
*/
|
|
1676
|
+
function fieldAad(keyId, suite, scheme = SYMMETRIC_SCHEME) {
|
|
1677
|
+
if (!/^[0-9a-f]{16}$/u.test(keyId)) throw new Error(`workbuddy: envelope keyId is malformed`);
|
|
1678
|
+
return Buffer.concat([
|
|
1679
|
+
AAD_DOMAIN,
|
|
1680
|
+
Buffer.from([1]),
|
|
1681
|
+
encodeLengthPrefixed(STANDARD_FORMAT_ID["field"]),
|
|
1682
|
+
encodeLengthPrefixed(scheme),
|
|
1683
|
+
encodeUint32(suite),
|
|
1684
|
+
encodeLengthPrefixed(keyId),
|
|
1685
|
+
Buffer.from([FRAMING_CODE["field"]]),
|
|
1686
|
+
Buffer.from([0]),
|
|
1687
|
+
Buffer.from([0])
|
|
1688
|
+
]);
|
|
1689
|
+
}
|
|
1690
|
+
/** Whether a value is the app's encrypted-field wrapper. */
|
|
1691
|
+
function isEncryptedFieldWrapper(value) {
|
|
1692
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
1693
|
+
const wrapper = value;
|
|
1694
|
+
const keys = Object.keys(wrapper).sort();
|
|
1695
|
+
return keys.length === 2 && keys[0] === "$wbEncrypted" && keys[1] === "envelope" && wrapper["$wbEncrypted"] === 1 && typeof wrapper["envelope"] === "string";
|
|
1696
|
+
}
|
|
1697
|
+
/**
|
|
1698
|
+
* The at-rest key id for a derived 32-byte key: the first 16 hex characters of
|
|
1699
|
+
* its SHA-256. This is what the envelope's `keyId` is checked against, so a
|
|
1700
|
+
* mismatched key fails loudly instead of returning garbage.
|
|
1701
|
+
*/
|
|
1702
|
+
function deriveAtRestKeyId(key) {
|
|
1703
|
+
return createHash("sha256").update(key).digest("hex").slice(0, 16);
|
|
1704
|
+
}
|
|
1705
|
+
/**
|
|
1706
|
+
* Derive the 32-byte field key from the app's key payload JSON.
|
|
1707
|
+
*
|
|
1708
|
+
* The app hashes the payload's base64 STRING — not its decoded bytes — so the
|
|
1709
|
+
* same spelling is required here; hashing the decoded secret would produce a
|
|
1710
|
+
* different key and every field would fail to open.
|
|
1711
|
+
*/
|
|
1712
|
+
function deriveAtRestKey(payloadJson) {
|
|
1713
|
+
let payload;
|
|
1714
|
+
try {
|
|
1715
|
+
payload = JSON.parse(payloadJson);
|
|
1716
|
+
} catch {
|
|
1717
|
+
throw new Error("workbuddy: at-rest key payload is not valid JSON");
|
|
1718
|
+
}
|
|
1719
|
+
if (typeof payload !== "object" || payload === null || Array.isArray(payload)) throw new Error("workbuddy: at-rest key payload is not an object");
|
|
1720
|
+
const secret = payload["atRestSecretKey"];
|
|
1721
|
+
if (typeof secret !== "string" || secret === "") throw new Error("workbuddy: at-rest key payload carries no atRestSecretKey");
|
|
1722
|
+
return createHash("sha256").update(secret, "utf8").digest();
|
|
1723
|
+
}
|
|
1724
|
+
/**
|
|
1725
|
+
* Open one encrypted field with a derived key and return its plaintext.
|
|
1726
|
+
*
|
|
1727
|
+
* Throws when the envelope is malformed, belongs to another key, or fails
|
|
1728
|
+
* authentication — a GCM tag mismatch is the signal that the transcript or the
|
|
1729
|
+
* key is wrong, and it must never degrade into a truncated token.
|
|
1730
|
+
*/
|
|
1731
|
+
function openEncryptedField(field, key) {
|
|
1732
|
+
let envelope;
|
|
1733
|
+
try {
|
|
1734
|
+
envelope = JSON.parse(Buffer.from(field.envelope, "base64").toString("utf8"));
|
|
1735
|
+
} catch {
|
|
1736
|
+
throw new Error("workbuddy: encrypted field envelope is not valid JSON");
|
|
1737
|
+
}
|
|
1738
|
+
if (typeof envelope !== "object" || envelope === null || Array.isArray(envelope)) throw new Error("workbuddy: encrypted field envelope is not an object");
|
|
1739
|
+
const record = envelope;
|
|
1740
|
+
const suite = record["suite"];
|
|
1741
|
+
const keyId = record["keyId"];
|
|
1742
|
+
const nonce = record["nonce"];
|
|
1743
|
+
const authTag = record["authTag"];
|
|
1744
|
+
const ciphertext = record["ciphertext"];
|
|
1745
|
+
if (typeof suite !== "number" || typeof keyId !== "string") throw new Error("workbuddy: encrypted field envelope is missing suite or keyId");
|
|
1746
|
+
if (typeof nonce !== "string" || typeof authTag !== "string" || typeof ciphertext !== "string") throw new Error("workbuddy: encrypted field envelope is missing nonce, authTag or ciphertext");
|
|
1747
|
+
const expectedKeyId = deriveAtRestKeyId(key);
|
|
1748
|
+
if (keyId !== expectedKeyId) throw new Error(`workbuddy: encrypted field belongs to key ${keyId}, not the available key ${expectedKeyId}`);
|
|
1749
|
+
const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(nonce, "base64"), { authTagLength: 16 });
|
|
1750
|
+
decipher.setAAD(fieldAad(keyId, suite));
|
|
1751
|
+
decipher.setAuthTag(Buffer.from(authTag, "base64"));
|
|
1752
|
+
return Buffer.concat([decipher.update(Buffer.from(ciphertext, "base64")), decipher.final()]).toString("utf8");
|
|
1753
|
+
}
|
|
1754
|
+
/**
|
|
1755
|
+
* The executable inside a macOS app bundle, read from the bundle's own
|
|
1756
|
+
* `Info.plist`.
|
|
1757
|
+
*
|
|
1758
|
+
* The binary is NOT reliably named after the app: the WorkBuddy bundles ship
|
|
1759
|
+
* with `CFBundleExecutable` set to `Electron`, so a path assembled as
|
|
1760
|
+
* `<bundle>/Contents/MacOS/WorkBuddy` does not exist and the app looks absent
|
|
1761
|
+
* even when it is installed in the default location. Because the bundle
|
|
1762
|
+
* documents the real name, asking it is both correct and robust to a future
|
|
1763
|
+
* build that renames the binary.
|
|
1764
|
+
*
|
|
1765
|
+
* Returns undefined when the plist is absent, unreadable, or carries no usable
|
|
1766
|
+
* name — never a guessed path, so a caller can keep probing.
|
|
1767
|
+
*/
|
|
1768
|
+
function macosBundleExecutable(bundle) {
|
|
1769
|
+
let plist;
|
|
1770
|
+
try {
|
|
1771
|
+
plist = readFileSync(join(bundle, "Contents", "Info.plist"), "utf8");
|
|
1772
|
+
} catch {
|
|
1773
|
+
return;
|
|
1774
|
+
}
|
|
1775
|
+
const name = /<key>\s*CFBundleExecutable\s*<\/key>\s*<string>([^<]*)<\/string>/u.exec(plist)?.[1]?.trim();
|
|
1776
|
+
if (name === void 0 || name === "" || name.includes("/") || name.includes("\\") || name === "." || name === "..") return;
|
|
1777
|
+
return join(bundle, "Contents", "MacOS", name);
|
|
1778
|
+
}
|
|
1779
|
+
/**
|
|
1780
|
+
* Candidate paths of the WorkBuddy desktop executable, in probe order.
|
|
1781
|
+
*
|
|
1782
|
+
* The Windows build is the one that encrypts credentials, so Windows leads;
|
|
1783
|
+
* the macOS bundles are listed because the same native module ships there and
|
|
1784
|
+
* the encryption policy is enabled on macOS builds too (observed from 5.6.x),
|
|
1785
|
+
* and `undefined` entries (an unset env variable) are dropped.
|
|
1786
|
+
*
|
|
1787
|
+
* On macOS the executable name comes from each bundle (see
|
|
1788
|
+
* {@link macosBundleExecutable}) rather than being assembled from the app name.
|
|
1789
|
+
*
|
|
1790
|
+
* `readBundleExecutable` is injectable, in the same spirit as `platform`/`home`/
|
|
1791
|
+
* `env`: the macOS branch consults the real filesystem, so without a seam the
|
|
1792
|
+
* expected candidates would depend on whether the host machine happens to have
|
|
1793
|
+
* the app installed — and the test would pass on a developer's Mac while
|
|
1794
|
+
* failing in CI.
|
|
1795
|
+
*/
|
|
1796
|
+
function workbuddyAppExecutableCandidates(platform = process.platform, home = homedir(), env = process.env, readBundleExecutable = macosBundleExecutable) {
|
|
1797
|
+
const candidates = [env[WORKBUDDY_APP_EXECUTABLE_ENV]?.trim()];
|
|
1798
|
+
if (platform === "win32") {
|
|
1799
|
+
const local = env["LOCALAPPDATA"]?.trim();
|
|
1800
|
+
const programFiles = env["ProgramFiles"]?.trim();
|
|
1801
|
+
const programFilesX86 = env["ProgramFiles(x86)"]?.trim();
|
|
1802
|
+
candidates.push(local === void 0 || local === "" ? void 0 : join(local, "Programs", "WorkBuddy", APP_EXECUTABLE_NAME), local === void 0 || local === "" ? void 0 : join(local, "WorkBuddy", APP_EXECUTABLE_NAME), programFiles === void 0 || programFiles === "" ? void 0 : join(programFiles, "WorkBuddy", APP_EXECUTABLE_NAME), programFilesX86 === void 0 || programFilesX86 === "" ? void 0 : join(programFilesX86, "WorkBuddy", APP_EXECUTABLE_NAME));
|
|
1803
|
+
} else if (platform === "darwin") for (const name of MACOS_APP_BUNDLE_NAMES) candidates.push(readBundleExecutable(join("/Applications", name)), readBundleExecutable(join(home, "Applications", name)));
|
|
1804
|
+
return candidates.filter((candidate) => candidate !== void 0 && candidate !== "");
|
|
1805
|
+
}
|
|
1806
|
+
/**
|
|
1807
|
+
* Bundle identifier PREFIXES the desktop app is signed with — `com.tencent.
|
|
1808
|
+
* workbuddy` (domestic, observed as `…workbuddy.mac`) and `com.workbuddy`
|
|
1809
|
+
* (international, observed as `com.workbuddy.workbuddy-ai`).
|
|
1810
|
+
*
|
|
1811
|
+
* Used to CONFIRM that a discovered bundle really is WorkBuddy before it is
|
|
1812
|
+
* launched. This matters because the discovery below scans directories and then
|
|
1813
|
+
* execs what it finds: every Electron app is built around a binary called
|
|
1814
|
+
* `Electron`, so a name-only match could pick a different product's bundle and
|
|
1815
|
+
* run it. The identifier is the app's own claim about itself, so it is the
|
|
1816
|
+
* check that makes the scan safe.
|
|
1817
|
+
*/
|
|
1818
|
+
const APP_BUNDLE_IDENTIFIER_PREFIXES = ["com.tencent.workbuddy", "com.workbuddy"];
|
|
1819
|
+
/**
|
|
1820
|
+
* Whether a bundle identifies itself as the WorkBuddy desktop app.
|
|
1821
|
+
*
|
|
1822
|
+
* The match is on dot boundaries, so a hypothetical `com.workbuddyish` cannot
|
|
1823
|
+
* pass as `com.workbuddy`.
|
|
1824
|
+
*
|
|
1825
|
+
* An unreadable or identifier-less plist is treated as NOT WorkBuddy: refusing
|
|
1826
|
+
* a candidate only costs a fallback to another path, whereas accepting the
|
|
1827
|
+
* wrong one would execute an unrelated application.
|
|
1828
|
+
*/
|
|
1829
|
+
function isWorkbuddyBundle(bundle) {
|
|
1830
|
+
let plist;
|
|
1831
|
+
try {
|
|
1832
|
+
plist = readFileSync(join(bundle, "Contents", "Info.plist"), "utf8");
|
|
1833
|
+
} catch {
|
|
1834
|
+
return false;
|
|
1835
|
+
}
|
|
1836
|
+
const identifier = /<key>\s*CFBundleIdentifier\s*<\/key>\s*<string>([^<]*)<\/string>/u.exec(plist)?.[1]?.trim().toLowerCase();
|
|
1837
|
+
if (identifier === void 0 || identifier === "") return false;
|
|
1838
|
+
return APP_BUNDLE_IDENTIFIER_PREFIXES.some((prefix) => identifier === prefix || identifier.startsWith(`${prefix}.`));
|
|
1839
|
+
}
|
|
1840
|
+
/**
|
|
1841
|
+
* Bundles of the desktop app found one level BELOW a macOS applications
|
|
1842
|
+
* directory.
|
|
1843
|
+
*
|
|
1844
|
+
* Users do file apps into subfolders (`/Applications/IDE/WorkBuddy.app`), and
|
|
1845
|
+
* a hardcoded `/Applications/<name>` then reports the app as missing while it
|
|
1846
|
+
* is installed and signed in. The scan is deliberately ONE level deep and
|
|
1847
|
+
* matches the known bundle names only, so it stays predictable and cheap; each
|
|
1848
|
+
* candidate is then confirmed by {@link isWorkbuddyBundle} before use.
|
|
1849
|
+
*
|
|
1850
|
+
* Returns [] when the parent is absent or unreadable — a missing directory is
|
|
1851
|
+
* the normal case, not an error.
|
|
1852
|
+
*/
|
|
1853
|
+
function macosNestedAppBundles(parent) {
|
|
1854
|
+
let entries;
|
|
1855
|
+
try {
|
|
1856
|
+
entries = readdirSync(parent);
|
|
1857
|
+
} catch {
|
|
1858
|
+
return [];
|
|
1859
|
+
}
|
|
1860
|
+
const bundles = [];
|
|
1861
|
+
for (const entry of entries) {
|
|
1862
|
+
const nested = join(parent, entry);
|
|
1863
|
+
for (const name of MACOS_APP_BUNDLE_NAMES) {
|
|
1864
|
+
const bundle = join(nested, name);
|
|
1865
|
+
try {
|
|
1866
|
+
if (!statSync(bundle).isDirectory()) continue;
|
|
1867
|
+
} catch {
|
|
1868
|
+
continue;
|
|
1869
|
+
}
|
|
1870
|
+
if (isWorkbuddyBundle(bundle)) bundles.push(bundle);
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
return bundles;
|
|
1874
|
+
}
|
|
1875
|
+
/**
|
|
1876
|
+
* The first candidate that exists as a file, or undefined when the desktop app
|
|
1877
|
+
* is not installed where this platform expects it.
|
|
1878
|
+
*/
|
|
1879
|
+
function findWorkbuddyAppExecutable(platform = process.platform, home = homedir(), env = process.env) {
|
|
1880
|
+
for (const candidate of workbuddyAppExecutableCandidates(platform, home, env)) try {
|
|
1881
|
+
if (existsSync(candidate)) return candidate;
|
|
1882
|
+
} catch {}
|
|
1883
|
+
if (platform === "darwin") for (const parent of ["/Applications", join(home, "Applications")]) for (const bundle of macosNestedAppBundles(parent)) {
|
|
1884
|
+
const executable = macosBundleExecutable(bundle);
|
|
1885
|
+
if (executable === void 0) continue;
|
|
1886
|
+
try {
|
|
1887
|
+
if (existsSync(executable)) return executable;
|
|
1888
|
+
} catch {}
|
|
1889
|
+
}
|
|
1890
|
+
}
|
|
1891
|
+
/**
|
|
1892
|
+
* Ask the installed desktop app for its key payload by running its own binary
|
|
1893
|
+
* as plain Node (`ELECTRON_RUN_AS_NODE`) and calling the native binding.
|
|
1894
|
+
*
|
|
1895
|
+
* The binding is the app's own public surface for this value, so the plugin
|
|
1896
|
+
* never has to carry a copy of a build-specific constant: it asks the very
|
|
1897
|
+
* build that wrote the file. The child is given no stdin and a hard timeout,
|
|
1898
|
+
* and its stdout is the only thing read.
|
|
1899
|
+
*/
|
|
1900
|
+
function fetchAtRestKeyPayload(executable) {
|
|
1901
|
+
return new Promise((resolve, reject) => {
|
|
1902
|
+
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))}"], {
|
|
1903
|
+
env: {
|
|
1904
|
+
...process.env,
|
|
1905
|
+
ELECTRON_RUN_AS_NODE: "1"
|
|
1906
|
+
},
|
|
1907
|
+
timeout: KEY_FETCH_TIMEOUT_MS,
|
|
1908
|
+
windowsHide: true,
|
|
1909
|
+
maxBuffer: 1048576
|
|
1910
|
+
}, (error, stdout, stderr) => {
|
|
1911
|
+
if (error !== null) {
|
|
1912
|
+
reject(/* @__PURE__ */ new Error(`workbuddy: the desktop app did not provide its at-rest key (${stderr.trim() || error.message})`));
|
|
1913
|
+
return;
|
|
1914
|
+
}
|
|
1915
|
+
const payload = stdout.trim();
|
|
1916
|
+
if (payload === "") {
|
|
1917
|
+
reject(/* @__PURE__ */ new Error("workbuddy: the desktop app returned an empty at-rest key payload"));
|
|
1918
|
+
return;
|
|
1919
|
+
}
|
|
1920
|
+
resolve(payload);
|
|
1921
|
+
});
|
|
1922
|
+
});
|
|
1923
|
+
}
|
|
1924
|
+
/** Process-lifetime cache of the derived key; never persisted. */
|
|
1925
|
+
let cachedKey;
|
|
1926
|
+
let inflightKey;
|
|
1927
|
+
/**
|
|
1928
|
+
* The desktop app's at-rest field key, or undefined when it cannot be obtained
|
|
1929
|
+
* (app not installed, an older build without the native module, or a future
|
|
1930
|
+
* build that rotates the payload). Cached after the first success so the app is
|
|
1931
|
+
* spawned at most once per process; a failure is retried on the next call,
|
|
1932
|
+
* because the user may install or start the app between reads.
|
|
1933
|
+
*/
|
|
1934
|
+
function readAtRestKey() {
|
|
1935
|
+
if (cachedKey !== void 0) return Promise.resolve(cachedKey);
|
|
1936
|
+
inflightKey ??= (async () => {
|
|
1937
|
+
const executable = findWorkbuddyAppExecutable();
|
|
1938
|
+
if (executable === void 0) return void 0;
|
|
1939
|
+
const key = deriveAtRestKey(await fetchAtRestKeyPayload(executable));
|
|
1940
|
+
cachedKey = key;
|
|
1941
|
+
return key;
|
|
1942
|
+
})().finally(() => {
|
|
1943
|
+
inflightKey = void 0;
|
|
1944
|
+
});
|
|
1945
|
+
return inflightKey;
|
|
1946
|
+
}
|
|
1947
|
+
//#endregion
|
|
1577
1948
|
//#region src/accounts.ts
|
|
1578
1949
|
/**
|
|
1579
1950
|
* Account pool: discovers every WorkBuddy credential snapshot the desktop app
|
|
@@ -1621,11 +1992,81 @@ function optionalString(value) {
|
|
|
1621
1992
|
return typeof value === "string" && value !== "" ? value : void 0;
|
|
1622
1993
|
}
|
|
1623
1994
|
/**
|
|
1995
|
+
* Read one string-valued field that may arrive as a plain string (older builds)
|
|
1996
|
+
* or as the desktop app's `$wbEncrypted` envelope. The app started encrypting
|
|
1997
|
+
* `accessToken` / `refreshToken` / `nickname` in 5.6.0 on BOTH macOS and Windows
|
|
1998
|
+
* — the earlier "Windows first" reading was wrong, and it is why a signed-in Mac
|
|
1999
|
+
* showed no account at all: the value is an object, `typeof === 'string'` failed,
|
|
2000
|
+
* and the parser reported "no credential" for a perfectly good sign-in.
|
|
2001
|
+
*
|
|
2002
|
+
* `decrypt` is injected rather than called here so this parser stays synchronous
|
|
2003
|
+
* and testable; the async key fetch lives in `readCredential`. A field that IS
|
|
2004
|
+
* encrypted but could not be opened is reported as `failed` rather than as an
|
|
2005
|
+
* empty string — the caller must tell the user the app is missing or unreachable,
|
|
2006
|
+
* not send them to sign in again (the one action that cannot help).
|
|
2007
|
+
*/
|
|
2008
|
+
/**
|
|
2009
|
+
* Marker for "the credential is encrypted and we could not obtain the key".
|
|
2010
|
+
*
|
|
2011
|
+
* Carried as a `code` rather than left to `instanceof` because the value crosses
|
|
2012
|
+
* the packaged-plugin boundary; the same convention the sibling error types use.
|
|
2013
|
+
* This is deliberately NOT "not signed in": the user IS signed in, and telling
|
|
2014
|
+
* them to sign in again sends them to the one action that cannot help.
|
|
2015
|
+
*/
|
|
2016
|
+
const ENCRYPTED_CREDENTIAL_CODE = "ENCRYPTED_CREDENTIAL";
|
|
2017
|
+
var WorkBuddyEncryptedCredentialError = class extends Error {
|
|
2018
|
+
code = ENCRYPTED_CREDENTIAL_CODE;
|
|
2019
|
+
constructor(sourcePath) {
|
|
2020
|
+
super(`workbuddy: ${sourcePath} holds encrypted credentials but the desktop app could not provide the key. Install the WorkBuddy desktop app (or point WORKBUDDY_APP_EXECUTABLE at it) — signing in again will not help.`);
|
|
2021
|
+
this.name = "WorkBuddyEncryptedCredentialError";
|
|
2022
|
+
}
|
|
2023
|
+
};
|
|
2024
|
+
/** True when a thrown value is the encrypted-credential marker (cross-bundle safe). */
|
|
2025
|
+
function isEncryptedCredentialError(value) {
|
|
2026
|
+
return typeof value === "object" && value !== null && value.code === "ENCRYPTED_CREDENTIAL";
|
|
2027
|
+
}
|
|
2028
|
+
function decryptableString(value, decrypt) {
|
|
2029
|
+
if (typeof value === "string") return {
|
|
2030
|
+
value,
|
|
2031
|
+
encrypted: false,
|
|
2032
|
+
failed: false
|
|
2033
|
+
};
|
|
2034
|
+
if (isEncryptedFieldWrapper(value)) {
|
|
2035
|
+
if (decrypt === void 0) return {
|
|
2036
|
+
value: "",
|
|
2037
|
+
encrypted: true,
|
|
2038
|
+
failed: true
|
|
2039
|
+
};
|
|
2040
|
+
try {
|
|
2041
|
+
return {
|
|
2042
|
+
value: decrypt(value),
|
|
2043
|
+
encrypted: true,
|
|
2044
|
+
failed: false
|
|
2045
|
+
};
|
|
2046
|
+
} catch {
|
|
2047
|
+
return {
|
|
2048
|
+
value: "",
|
|
2049
|
+
encrypted: true,
|
|
2050
|
+
failed: true
|
|
2051
|
+
};
|
|
2052
|
+
}
|
|
2053
|
+
}
|
|
2054
|
+
return {
|
|
2055
|
+
value: "",
|
|
2056
|
+
encrypted: false,
|
|
2057
|
+
failed: false
|
|
2058
|
+
};
|
|
2059
|
+
}
|
|
2060
|
+
/**
|
|
1624
2061
|
* Parse a WorkBuddy auth document. Accepts the nested desktop shape
|
|
1625
2062
|
* `{"auth":{...},"account":{...}}` and the flat panel shape; returns undefined
|
|
1626
2063
|
* when there is no usable access token.
|
|
2064
|
+
*
|
|
2065
|
+
* `decrypt` opens the desktop app's `$wbEncrypted` field wrapper (5.6.0+, both
|
|
2066
|
+
* platforms). Absent means "plain-string builds only", which is what every
|
|
2067
|
+
* caller without an at-rest key should pass.
|
|
1627
2068
|
*/
|
|
1628
|
-
function parseWorkBuddyAuth(text, sourcePath) {
|
|
2069
|
+
function parseWorkBuddyAuth(text, sourcePath, decrypt) {
|
|
1629
2070
|
let parsed;
|
|
1630
2071
|
try {
|
|
1631
2072
|
parsed = JSON.parse(text);
|
|
@@ -1643,18 +2084,20 @@ function parseWorkBuddyAuth(text, sourcePath) {
|
|
|
1643
2084
|
auth = document;
|
|
1644
2085
|
identity = document;
|
|
1645
2086
|
}
|
|
1646
|
-
const
|
|
2087
|
+
const accessField = decryptableString(auth["accessToken"], decrypt);
|
|
2088
|
+
if (accessField.encrypted && accessField.failed) throw new WorkBuddyEncryptedCredentialError(sourcePath);
|
|
2089
|
+
const accessToken = accessField.value;
|
|
1647
2090
|
if (accessToken === "") return void 0;
|
|
1648
2091
|
const refreshExpiresAtMs = typeof auth["refreshExpiresAt"] === "number" ? expiryToMs(auth["refreshExpiresAt"]) : void 0;
|
|
1649
2092
|
if (refreshExpiresAtMs !== void 0 && refreshExpiresAtMs > 0 && refreshExpiresAtMs < Date.now()) return;
|
|
1650
2093
|
const lastRefreshAtMs = typeof auth["lastRefreshTime"] === "number" ? expiryToMs(auth["lastRefreshTime"]) : void 0;
|
|
1651
2094
|
return {
|
|
1652
2095
|
accessToken,
|
|
1653
|
-
refreshToken:
|
|
2096
|
+
refreshToken: decryptableString(auth["refreshToken"], decrypt).value,
|
|
1654
2097
|
expiresAtMs: typeof auth["expiresAt"] === "number" ? expiryToMs(auth["expiresAt"]) : 0,
|
|
1655
2098
|
...refreshExpiresAtMs === void 0 ? {} : { refreshExpiresAtMs },
|
|
1656
2099
|
...lastRefreshAtMs === void 0 ? {} : { lastRefreshAtMs },
|
|
1657
|
-
...optionalString(identity["nickname"]) === void 0 ? {} : { nickname: optionalString(identity["nickname"]) },
|
|
2100
|
+
...optionalString(decryptableString(identity["nickname"], decrypt).value) === void 0 ? {} : { nickname: optionalString(decryptableString(identity["nickname"], decrypt).value) },
|
|
1658
2101
|
...optionalString(identity["uin"]) === void 0 ? {} : { uin: optionalString(identity["uin"]) },
|
|
1659
2102
|
...optionalString(identity["uid"]) === void 0 ? {} : { uid: optionalString(identity["uid"]) },
|
|
1660
2103
|
...optionalString(identity["enterpriseId"]) === void 0 ? {} : { enterpriseId: optionalString(identity["enterpriseId"]) },
|
|
@@ -1736,11 +2179,34 @@ async function authFilesIn(dir) {
|
|
|
1736
2179
|
return files.map((name) => join(dir, name));
|
|
1737
2180
|
}
|
|
1738
2181
|
async function readCredential(path) {
|
|
2182
|
+
let text;
|
|
1739
2183
|
try {
|
|
1740
|
-
|
|
2184
|
+
text = await readFile(path, "utf8");
|
|
1741
2185
|
} catch {
|
|
1742
2186
|
return;
|
|
1743
2187
|
}
|
|
2188
|
+
const decrypt = text.includes("\"$wbEncrypted\"") ? await encryptedFieldOpener() : void 0;
|
|
2189
|
+
try {
|
|
2190
|
+
return parseWorkBuddyAuth(text, path, decrypt);
|
|
2191
|
+
} catch (error) {
|
|
2192
|
+
if (isEncryptedCredentialError(error)) throw error;
|
|
2193
|
+
return;
|
|
2194
|
+
}
|
|
2195
|
+
}
|
|
2196
|
+
/**
|
|
2197
|
+
* Build the field opener, or undefined when the app cannot supply its key.
|
|
2198
|
+
*
|
|
2199
|
+
* Split out so the key lookup is testable without a real desktop install, and so
|
|
2200
|
+
* a lookup failure degrades to "encrypted, unopenable" rather than to a parse
|
|
2201
|
+
* error that would look like a corrupt file.
|
|
2202
|
+
*/
|
|
2203
|
+
async function encryptedFieldOpener() {
|
|
2204
|
+
const key = await readAtRestKey().catch(() => void 0);
|
|
2205
|
+
if (key === void 0) return void 0;
|
|
2206
|
+
return (field) => {
|
|
2207
|
+
if (!isEncryptedFieldWrapper(field)) throw new Error("workbuddy: not an encrypted field wrapper");
|
|
2208
|
+
return openEncryptedField(field, key);
|
|
2209
|
+
};
|
|
1744
2210
|
}
|
|
1745
2211
|
/** Every directory the pool should scan, in probe order. */
|
|
1746
2212
|
function candidateAuthDirs(env = process.env) {
|
|
@@ -2261,8 +2727,8 @@ const FALLBACK_WORKBUDDY_MODELS = [
|
|
|
2261
2727
|
{
|
|
2262
2728
|
id: "hy3",
|
|
2263
2729
|
name: "Hy3",
|
|
2264
|
-
contextWindow:
|
|
2265
|
-
maxOutputTokens:
|
|
2730
|
+
contextWindow: 32e3,
|
|
2731
|
+
maxOutputTokens: 8e3,
|
|
2266
2732
|
supportsImages: true
|
|
2267
2733
|
},
|
|
2268
2734
|
{
|
|
@@ -2848,10 +3314,37 @@ function diffEarnings(before, after) {
|
|
|
2848
3314
|
accounts
|
|
2849
3315
|
};
|
|
2850
3316
|
}
|
|
2851
|
-
|
|
2852
|
-
|
|
2853
|
-
|
|
2854
|
-
|
|
3317
|
+
/**
|
|
3318
|
+
* The timezone every hour in this file is interpreted in.
|
|
3319
|
+
*
|
|
3320
|
+
* The activity windows these jobs target are defined in Beijing time, but the
|
|
3321
|
+
* scheduler used `getHours()`, which answers in the host machine's local zone.
|
|
3322
|
+
* On a machine set to anything else, "09:00" was 09:00 local — a check-in that
|
|
3323
|
+
* simply never came due. Naming the zone makes the hour mean the same instant
|
|
3324
|
+
* everywhere DSH runs, and is also what lets a test pin the behaviour.
|
|
3325
|
+
*/
|
|
3326
|
+
const AUTOMATION_TIME_ZONE = "Asia/Shanghai";
|
|
3327
|
+
/** Calendar parts of `date` in `timeZone`, all as zero-padded strings. */
|
|
3328
|
+
function zonedParts(date, timeZone = AUTOMATION_TIME_ZONE) {
|
|
3329
|
+
const parts = new Intl.DateTimeFormat("en-CA", {
|
|
3330
|
+
timeZone,
|
|
3331
|
+
year: "numeric",
|
|
3332
|
+
month: "2-digit",
|
|
3333
|
+
day: "2-digit",
|
|
3334
|
+
hour: "2-digit",
|
|
3335
|
+
hourCycle: "h23"
|
|
3336
|
+
}).formatToParts(date);
|
|
3337
|
+
const pick = (type) => parts.find((part) => part.type === type)?.value ?? "00";
|
|
3338
|
+
return {
|
|
3339
|
+
year: pick("year"),
|
|
3340
|
+
month: pick("month"),
|
|
3341
|
+
day: pick("day"),
|
|
3342
|
+
hour: pick("hour")
|
|
3343
|
+
};
|
|
3344
|
+
}
|
|
3345
|
+
function dayKey(date, timeZone = AUTOMATION_TIME_ZONE) {
|
|
3346
|
+
const { year, month, day } = zonedParts(date, timeZone);
|
|
3347
|
+
return `${year}-${month}-${day}`;
|
|
2855
3348
|
}
|
|
2856
3349
|
/**
|
|
2857
3350
|
* The scheduled SLOT `date` falls in, as `YYYY-MM-DDTHH`.
|
|
@@ -2860,20 +3353,9 @@ function dayKey(date) {
|
|
|
2860
3353
|
* for several hours runs in each of them while a second tick inside the same
|
|
2861
3354
|
* hour is still refused.
|
|
2862
3355
|
*/
|
|
2863
|
-
function slotKey(date) {
|
|
2864
|
-
|
|
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());
|
|
3356
|
+
function slotKey(date, timeZone = AUTOMATION_TIME_ZONE) {
|
|
3357
|
+
const { hour } = zonedParts(date, timeZone);
|
|
3358
|
+
return `${dayKey(date, timeZone)}T${hour}`;
|
|
2877
3359
|
}
|
|
2878
3360
|
/** Whether this account may be used: not switched off, not cooling. */
|
|
2879
3361
|
function eligible(account, now) {
|
|
@@ -3136,6 +3618,22 @@ var WorkBuddyScheduler = class {
|
|
|
3136
3618
|
* rate-limits per account, so overlapping passes would only trip that limit.
|
|
3137
3619
|
* A job that throws is recorded and the loop continues.
|
|
3138
3620
|
*/
|
|
3621
|
+
/**
|
|
3622
|
+
* Whether `kind` is due at `now`: its earliest configured hour has passed in
|
|
3623
|
+
* the scheduling timezone, and no hour of today has been consumed yet.
|
|
3624
|
+
*
|
|
3625
|
+
* Hours are consumed per SLOT (one entry per configured hour), so a job with
|
|
3626
|
+
* two hours still runs twice a day — but a job whose hour passed while DSH was
|
|
3627
|
+
* closed runs immediately on the next tick instead of waiting for tomorrow.
|
|
3628
|
+
*/
|
|
3629
|
+
isDue(kind, now) {
|
|
3630
|
+
const hours = this.hoursOf(kind);
|
|
3631
|
+
if (hours.length === 0) return false;
|
|
3632
|
+
const { hour } = zonedParts(now);
|
|
3633
|
+
const current = Number(hour);
|
|
3634
|
+
const today = dayKey(now);
|
|
3635
|
+
return hours.some((candidate) => candidate <= current && this.states[kind].lastRunSlot !== `${today}T${String(candidate).padStart(2, "0")}`);
|
|
3636
|
+
}
|
|
3139
3637
|
async tick() {
|
|
3140
3638
|
if (!this.enabled || this.stopped || this.busy) return;
|
|
3141
3639
|
this.busy = true;
|
|
@@ -3146,7 +3644,7 @@ var WorkBuddyScheduler = class {
|
|
|
3146
3644
|
for (const kind of JOB_KINDS) {
|
|
3147
3645
|
if (this.stopped) return;
|
|
3148
3646
|
if (this.states[kind].lastRunSlot === slot) continue;
|
|
3149
|
-
if (!
|
|
3647
|
+
if (!this.isDue(kind, now)) continue;
|
|
3150
3648
|
await this.runJob(kind, today);
|
|
3151
3649
|
}
|
|
3152
3650
|
} catch (error) {
|