dsh-postbox 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +531 -2
- package/client.js +2717 -0
- package/cordis.patch.yml +83 -0
- package/docs/DETAIL.md +56 -0
- package/icon.svg +1 -0
- package/index.js +2312 -0
- package/lib/backend-sqlite.js +65 -0
- package/lib/bridge.js +940 -0
- package/lib/config.js +289 -0
- package/lib/digest.js +213 -0
- package/lib/errors.js +83 -0
- package/lib/ft.js +211 -0
- package/lib/host-settings.js +237 -0
- package/lib/imap.js +635 -0
- package/lib/importance.js +83 -0
- package/lib/llm.js +411 -0
- package/lib/log.js +75 -0
- package/lib/mime.js +381 -0
- package/lib/mutf7.js +54 -0
- package/lib/notify.js +328 -0
- package/lib/oauth.js +275 -0
- package/lib/schema.js +177 -0
- package/lib/search.js +129 -0
- package/lib/settings.js +395 -0
- package/lib/smtp.js +153 -0
- package/lib/store.js +1068 -0
- package/lib/sync.js +899 -0
- package/lib/tool.js +232 -0
- package/lib/tools-m4.js +863 -0
- package/lib/update.js +642 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +60 -4
package/lib/update.js
ADDED
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
// lib/update.js — 插件自更新(M4 · 学自 @xmanrui/dsh-im 的更新器契约)。
|
|
2
|
+
//
|
|
3
|
+
// 为什么需要:opencode2dsh 2026-10-15 那次升级暴露出问题 —— Desktop 的插件管理器
|
|
4
|
+
// 里**没有更新按钮**,只能手工 pnpm。本模块让 mailbox 自己能检查/安装新版本。
|
|
5
|
+
//
|
|
6
|
+
// 契约照搬 dsh-im(它踩过的坑都写在注释里):
|
|
7
|
+
// 1. 三个动作 `status` / `check` / `install`,install 必须带 `checkId`(确认票据,带 TTL)
|
|
8
|
+
// —— 防止「查到新版」和「真的去装」之间隔太久,装到一个已经不是当初查到的版本。
|
|
9
|
+
// 2. **绝不自己重启**:装完只报 `restart-required`,重启交给 Host/用户。
|
|
10
|
+
// 4.24.1 之前它的历史任务会永久堵住后续安装,所以这里「恢复状态一律从当前安装推导,
|
|
11
|
+
// 不信任持久化的标记」。
|
|
12
|
+
// 3. **安装锁 + pid**:一个 profile 同时只允许一个安装作业;过期/死进程的锁可接管。
|
|
13
|
+
// 4. **装前只快照清单文件**(package.json / pnpm-lock.yaml / pnpm-workspace.yaml),
|
|
14
|
+
// 「绝不备份凭据或整个 home」。
|
|
15
|
+
// 5. **装后必须校验**:重新 inspect,installedVersion 必须等于目标版本,否则 verify-failed。
|
|
16
|
+
// 6. **注册表载荷只用于取版本号,绝不据此决定执行什么命令** —— 固定包名 + 固定安装命令。
|
|
17
|
+
// 7. 元数据抓取有体积上限与超时;错误码走白名单,内部细节不外泄。
|
|
18
|
+
//
|
|
19
|
+
// 与 dsh-im 的关键差异:本插件是**零依赖**(junction 装法导致 bare specifier 解析不到),
|
|
20
|
+
// 所以这里自带一个够用的 semver 子集(严格校验 + 比较 + 简单的 range 判定),
|
|
21
|
+
// 不引 semver 包。
|
|
22
|
+
//
|
|
23
|
+
// ⚠️ 关于 mailbox 自己的安装形态:当前 profile 用 `link:` 把它链到一个**非 git** 的本地目录,
|
|
24
|
+
// 这种形态没有上游可更新。本模块会如实报 `source-install`,并在 config.update.source
|
|
25
|
+
// 显式配置了 `npm:<pkg>` 或 `github:<owner>/<repo>` 后才真正可用。
|
|
26
|
+
|
|
27
|
+
import fs from "node:fs";
|
|
28
|
+
import path from "node:path";
|
|
29
|
+
import os from "node:os";
|
|
30
|
+
import crypto from "node:crypto";
|
|
31
|
+
import { spawn } from "node:child_process";
|
|
32
|
+
|
|
33
|
+
export const PACKAGE_NAME = "dsh-postbox";
|
|
34
|
+
|
|
35
|
+
/** 可外泄的错误码白名单(其余一律归 update-failed,不把内部细节漏出去)。 */
|
|
36
|
+
export const PUBLIC_ERRORS = new Set([
|
|
37
|
+
"update-failed", "bad-request", "check-failed", "invalid-release", "check-expired",
|
|
38
|
+
"installation-changed", "update-busy", "install-failed", "verify-failed",
|
|
39
|
+
"state-unavailable", "interrupted", "disposed", "source-install", "unknown-source",
|
|
40
|
+
"unsupported-source", "registry-check-failed", "install-timeout", "install-interrupted",
|
|
41
|
+
"invalid-version", "no-source", "history-unchanged",
|
|
42
|
+
]);
|
|
43
|
+
|
|
44
|
+
const ACTIVE_STATES = new Set(["installing", "verifying"]);
|
|
45
|
+
const JOB_STATES = new Set([...ACTIVE_STATES, "restart-required", "completed", "failed", "interrupted"]);
|
|
46
|
+
const MAX_METADATA_BYTES = 256 * 1024;
|
|
47
|
+
const SNAPSHOT_FILES = ["package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"];
|
|
48
|
+
const NO_LOCK = Symbol("no update lock");
|
|
49
|
+
|
|
50
|
+
export function updateError(code) {
|
|
51
|
+
return Object.assign(new Error(code), { code });
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// ---------------------------------------------------------------- semver 子集
|
|
55
|
+
const SEMVER_RE = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z.-]+))?$/;
|
|
56
|
+
|
|
57
|
+
/** 严格校验:必须是 x.y.z(可选 -prerelease / +build),不带前导 v、不带范围符。 */
|
|
58
|
+
export function isValidSemver(v) {
|
|
59
|
+
return typeof v === "string" && SEMVER_RE.test(v) && !v.startsWith("v");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function parseSemver(v) {
|
|
63
|
+
const m = SEMVER_RE.exec(v);
|
|
64
|
+
if (!m) return null;
|
|
65
|
+
return {
|
|
66
|
+
major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]),
|
|
67
|
+
prerelease: m[4] ? m[4].split(".") : [], build: m[5] ?? "",
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function cmpPrerelease(a, b) {
|
|
72
|
+
// 语义:有 prerelease 的版本**小于**同号 release;逐个标识比较,数字 < 字符串
|
|
73
|
+
if (!a.length && !b.length) return 0;
|
|
74
|
+
if (!a.length) return 1;
|
|
75
|
+
if (!b.length) return -1;
|
|
76
|
+
const n = Math.max(a.length, b.length);
|
|
77
|
+
for (let i = 0; i < n; i++) {
|
|
78
|
+
const x = a[i], y = b[i];
|
|
79
|
+
if (x === undefined) return -1;
|
|
80
|
+
if (y === undefined) return 1;
|
|
81
|
+
const nx = /^\d+$/.test(x), ny = /^\d+$/.test(y);
|
|
82
|
+
if (nx && ny) { const d = Number(x) - Number(y); if (d) return d < 0 ? -1 : 1; continue; }
|
|
83
|
+
if (nx !== ny) return nx ? -1 : 1; // 数字标识符 < 字母标识符
|
|
84
|
+
if (x !== y) return x < y ? -1 : 1;
|
|
85
|
+
}
|
|
86
|
+
return 0;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** 严格 semver 比较:仅接受两个合法版本号。 */
|
|
90
|
+
export function compareSemver(a, b) {
|
|
91
|
+
const pa = parseSemver(a), pb = parseSemver(b);
|
|
92
|
+
if (!pa || !pb) throw updateError("invalid-version");
|
|
93
|
+
for (const k of ["major", "minor", "patch"]) {
|
|
94
|
+
if (pa[k] !== pb[k]) return pa[k] < pb[k] ? -1 : 1;
|
|
95
|
+
}
|
|
96
|
+
return cmpPrerelease(pa.prerelease, pb.prerelease);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function gtSemver(a, b) { return compareSemver(a, b) > 0; }
|
|
100
|
+
|
|
101
|
+
/** range 支持:`*`、`>=x`、`>=x.y`、`>=x.y.z`(缺省段补 0)、`>`/`<=`/`<`/`=`,
|
|
102
|
+
* 以及空格分隔的多个条件(AND)。
|
|
103
|
+
* 不认识的形态一律抛 unsupported-range —— **宁可拒绝也不猜**(否则会把不兼容的包装上)。
|
|
104
|
+
* 注意:`engines.node` 写 `">=22.19"`(两段)极其常见,所以必须容忍缺省补丁号。 */
|
|
105
|
+
export function satisfiesRange(version, range) {
|
|
106
|
+
const v = parseSemver(version);
|
|
107
|
+
if (!v) throw updateError("invalid-version");
|
|
108
|
+
const spec = String(range ?? "*").trim();
|
|
109
|
+
if (spec === "" || spec === "*" || spec === "x" || spec === "X") return true;
|
|
110
|
+
for (const part of spec.split(/\s+/)) {
|
|
111
|
+
const m = /^(>=|<=|>|<|=)?\s*(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?$/.exec(part);
|
|
112
|
+
if (!m) throw Object.assign(new Error(`unsupported range "${part}"`), { code: "unsupported-range" });
|
|
113
|
+
const want = `${m[2]}.${m[3] ?? 0}.${m[4] ?? 0}${m[5] ? `-${m[5]}` : ""}`;
|
|
114
|
+
if (!isValidSemver(want)) throw updateError("unsupported-range");
|
|
115
|
+
const c = compareSemver(version, want);
|
|
116
|
+
const op = m[1] ?? "=";
|
|
117
|
+
const ok = op === ">=" ? c >= 0 : op === ">" ? c > 0 : op === "<=" ? c <= 0
|
|
118
|
+
: op === "<" ? c < 0 : c === 0;
|
|
119
|
+
if (!ok) return false;
|
|
120
|
+
}
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// ---------------------------------------------------------------- 安装形态识别
|
|
125
|
+
/** 读 profile 的 package.json 里本包的声明(决定它是 link / git / registry 装的)。 */
|
|
126
|
+
export function readProfileSpecifier(profileDir, packageName) {
|
|
127
|
+
try {
|
|
128
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(profileDir, "package.json"), "utf8"));
|
|
129
|
+
const spec = pkg?.dependencies?.[packageName];
|
|
130
|
+
return typeof spec === "string" ? spec : null;
|
|
131
|
+
} catch { return null; }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** 从 codeload tarball URL 反解 `github:owner/repo`。 */
|
|
135
|
+
export function githubSourceFromSpecifier(spec) {
|
|
136
|
+
const m = /codeload\.github\.com\/([^/]+)\/([^/]+)\/tar\.gz\//.exec(String(spec ?? ""));
|
|
137
|
+
if (!m) return null;
|
|
138
|
+
return `github:${m[1]}/${m[2].replace(/\.git$/, "")}`;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** `link:` → link;codeload/github: → git;npm scope(含别名)或 semver range → registry。 */
|
|
142
|
+
export function kindOfSpecifier(spec) {
|
|
143
|
+
if (!spec) return "unknown";
|
|
144
|
+
if (spec.startsWith("link:")) return "link";
|
|
145
|
+
if (spec.startsWith("github:") || /codeload\.github\.com/.test(spec)) return "git";
|
|
146
|
+
if (/^npm:/.test(spec)) return "registry";
|
|
147
|
+
if (/^\^|~|>=|\*/.test(spec)) return "registry";
|
|
148
|
+
if (isValidSemver(spec)) return "registry";
|
|
149
|
+
// npm scope 包名(`@scope/name`)或 npm 别名(`npm:@scope/name@1.2.3`)
|
|
150
|
+
if (/^@[a-z0-9-~][a-z0-9-._~]*\/[a-z0-9-~][a-z0-9-._~]*$/.test(spec)) return "registry";
|
|
151
|
+
return "unknown";
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** 解析出**可执行**的更新源。返回 {kind, spec, packageName?, owner?, repo?, ref?} 或 null。 */
|
|
155
|
+
export function resolveSource({ configSource = "", environmentKind = "unknown", specifier = "" } = {}) {
|
|
156
|
+
const raw = String(configSource ?? "").trim();
|
|
157
|
+
if (raw) {
|
|
158
|
+
if (raw.startsWith("npm:")) {
|
|
159
|
+
const name = raw.slice(4).trim();
|
|
160
|
+
if (!/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(name)) {
|
|
161
|
+
throw updateError("unsupported-source");
|
|
162
|
+
}
|
|
163
|
+
return { kind: "registry", spec: raw, packageName: name };
|
|
164
|
+
}
|
|
165
|
+
const gh = /^github:([^/\s]+)\/([^/\s#]+)(?:#(.+))?$/.exec(raw);
|
|
166
|
+
if (gh) return { kind: "git", spec: raw, owner: gh[1], repo: gh[2].replace(/\.git$/, ""), ref: gh[3] ?? null };
|
|
167
|
+
throw updateError("unsupported-source");
|
|
168
|
+
}
|
|
169
|
+
// 未显式配置:尽量从安装形态推导
|
|
170
|
+
if (environmentKind === "git") {
|
|
171
|
+
const derived = githubSourceFromSpecifier(specifier);
|
|
172
|
+
if (derived) return { kind: "git", spec: derived, owner: derived.slice(7).split("/")[0], repo: derived.split("/")[1], ref: null };
|
|
173
|
+
}
|
|
174
|
+
if (environmentKind === "registry") return { kind: "registry", spec: `npm:${PACKAGE_NAME}`, packageName: PACKAGE_NAME };
|
|
175
|
+
// link / unknown:**没有上游**,如实报告
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// ---------------------------------------------------------------- 运行时巡检
|
|
180
|
+
function pathsFor(homeDir, profileDir) {
|
|
181
|
+
if (!homeDir || !profileDir || !path.isAbsolute(homeDir) || !path.isAbsolute(profileDir)) return null;
|
|
182
|
+
const key = crypto.createHash("sha256").update(profileDir).digest("hex").slice(0, 24);
|
|
183
|
+
const directory = path.join(homeDir, "updates", "mailbox", key);
|
|
184
|
+
return {
|
|
185
|
+
directory,
|
|
186
|
+
state: path.join(directory, "state.json"),
|
|
187
|
+
lock: path.join(directory, "install.lock"),
|
|
188
|
+
backup: path.join(directory, "before.json"),
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export async function inspectRuntime({
|
|
193
|
+
profileDir, homeDir = os.homedir(), packageName = PACKAGE_NAME,
|
|
194
|
+
runningVersion = null, env = process.env,
|
|
195
|
+
} = {}) {
|
|
196
|
+
if (!profileDir) throw updateError("state-unavailable");
|
|
197
|
+
const specifier = readProfileSpecifier(profileDir, packageName);
|
|
198
|
+
const environmentKind = kindOfSpecifier(specifier);
|
|
199
|
+
let installedVersion = null;
|
|
200
|
+
let packageValid = false;
|
|
201
|
+
try {
|
|
202
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(profileDir, "node_modules", packageName, "package.json"), "utf8"));
|
|
203
|
+
installedVersion = typeof pkg.version === "string" ? pkg.version : null;
|
|
204
|
+
packageValid = isValidSemver(installedVersion ?? "");
|
|
205
|
+
} catch { /* 没装 / 读不到:按未安装处理 */ }
|
|
206
|
+
|
|
207
|
+
const profilePkgRaw = (() => { try { return fs.readFileSync(path.join(profileDir, "package.json"), "utf8"); } catch { return ""; } })();
|
|
208
|
+
const installationKey = crypto.createHash("sha256").update(`${profileDir}\n${profilePkgRaw}`).digest("hex").slice(0, 24);
|
|
209
|
+
|
|
210
|
+
return {
|
|
211
|
+
profileDir, homeDir, profileName: path.basename(profileDir),
|
|
212
|
+
environmentKind, specifier,
|
|
213
|
+
installedVersion, runningVersion,
|
|
214
|
+
packageValid,
|
|
215
|
+
eligible: packageValid && environmentKind !== "link",
|
|
216
|
+
installationKey,
|
|
217
|
+
paths: pathsFor(homeDir, profileDir),
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// ---------------------------------------------------------------- 元数据抓取
|
|
222
|
+
/** 抓 npm latest。**只取版本号与装法**,校验很严:名字/语义/无预发布/integrity 格式/tarball 归属。 */
|
|
223
|
+
export async function fetchNpmRelease({ packageName, fetchImpl = globalThis.fetch, timeoutMs = 10_000 } = {}) {
|
|
224
|
+
const registry = "https://registry.npmjs.org";
|
|
225
|
+
let response;
|
|
226
|
+
try {
|
|
227
|
+
response = await fetchImpl(`${registry}/${encodeURIComponent(packageName).replace("%40", "@")}/latest`, {
|
|
228
|
+
headers: { accept: "application/json" }, redirect: "error", signal: AbortSignal.timeout(timeoutMs),
|
|
229
|
+
});
|
|
230
|
+
if (!response.ok) throw updateError("check-failed");
|
|
231
|
+
const declared = Number(response.headers.get("content-length") ?? 0);
|
|
232
|
+
if (declared > MAX_METADATA_BYTES) throw updateError("invalid-release");
|
|
233
|
+
const chunks = [];
|
|
234
|
+
let length = 0;
|
|
235
|
+
for await (const chunk of response.body) {
|
|
236
|
+
length += chunk.byteLength;
|
|
237
|
+
if (length > MAX_METADATA_BYTES) throw updateError("invalid-release");
|
|
238
|
+
chunks.push(Buffer.from(chunk));
|
|
239
|
+
}
|
|
240
|
+
const value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
241
|
+
const version = value?.version;
|
|
242
|
+
// 预发布**不能**当稳定版推给用户(dsh-im 同规则:semver.prerelease(version) 即拒)
|
|
243
|
+
if (value?.name !== packageName || !isValidSemver(version) || /-/.test(version)) {
|
|
244
|
+
throw updateError("invalid-release");
|
|
245
|
+
}
|
|
246
|
+
const nodeRange = value.engines?.node;
|
|
247
|
+
if (nodeRange !== undefined && typeof nodeRange !== "string") throw updateError("invalid-release");
|
|
248
|
+
const tarball = value?.dist?.tarball, integrity = value?.dist?.integrity;
|
|
249
|
+
if (typeof tarball !== "string" || typeof integrity !== "string"
|
|
250
|
+
|| !/^sha512-[A-Za-z0-9+/]{86}==$/.test(integrity)) throw updateError("invalid-release");
|
|
251
|
+
let url;
|
|
252
|
+
try { url = new URL(tarball); } catch { throw updateError("invalid-release"); }
|
|
253
|
+
if (url.origin !== new URL(registry).origin || url.username || url.password || url.search || url.hash) {
|
|
254
|
+
throw updateError("invalid-release");
|
|
255
|
+
}
|
|
256
|
+
return { version, nodeRange: nodeRange ?? "*", integrity, tarball: url.href };
|
|
257
|
+
} catch (error) {
|
|
258
|
+
if (error?.code === "invalid-release") throw error;
|
|
259
|
+
if (error instanceof SyntaxError || error instanceof TypeError) throw updateError("invalid-release");
|
|
260
|
+
throw updateError("check-failed");
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** 抓 GitHub 最新 release(非预发布)。 */
|
|
265
|
+
export async function fetchGithubRelease({ owner, repo, fetchImpl = globalThis.fetch, timeoutMs = 10_000 } = {}) {
|
|
266
|
+
let response;
|
|
267
|
+
try {
|
|
268
|
+
response = await fetchImpl(`https://api.github.com/repos/${owner}/${repo}/releases/latest`, {
|
|
269
|
+
headers: { accept: "application/vnd.github+json", "user-agent": "dsh-mailbox-updater" },
|
|
270
|
+
redirect: "error", signal: AbortSignal.timeout(timeoutMs),
|
|
271
|
+
});
|
|
272
|
+
if (!response.ok) throw updateError("check-failed");
|
|
273
|
+
const declared = Number(response.headers.get("content-length") ?? 0);
|
|
274
|
+
if (declared > MAX_METADATA_BYTES) throw updateError("invalid-release");
|
|
275
|
+
const chunks = [];
|
|
276
|
+
let length = 0;
|
|
277
|
+
for await (const chunk of response.body) {
|
|
278
|
+
length += chunk.byteLength;
|
|
279
|
+
if (length > MAX_METADATA_BYTES) throw updateError("invalid-release");
|
|
280
|
+
chunks.push(Buffer.from(chunk));
|
|
281
|
+
}
|
|
282
|
+
const value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
283
|
+
if (value?.draft === true || value?.prerelease === true) throw updateError("invalid-release");
|
|
284
|
+
const tag = String(value?.tag_name ?? "");
|
|
285
|
+
const version = tag.replace(/^v/, "");
|
|
286
|
+
if (!isValidSemver(version)) throw updateError("invalid-release");
|
|
287
|
+
const tarball = typeof value?.tarball_url === "string" ? new URL(value.tarball_url) : null;
|
|
288
|
+
if (!tarball || tarball.origin !== "https://api.github.com") throw updateError("invalid-release");
|
|
289
|
+
return { version, tag, nodeRange: "*", tarball: tarball.href, source: `github:${owner}/${repo}` };
|
|
290
|
+
} catch (error) {
|
|
291
|
+
if (error?.code === "invalid-release") throw error;
|
|
292
|
+
if (error instanceof SyntaxError || error instanceof TypeError) throw updateError("invalid-release");
|
|
293
|
+
throw updateError("check-failed");
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** 统一的「装法」:固定命令,不把版本号拼进可执行路径以外的任何地方。 */
|
|
298
|
+
export function installCommand(source, version) {
|
|
299
|
+
if (source.kind === "registry") return { cmd: "pnpm", args: ["add", `${source.packageName}@${version}`] };
|
|
300
|
+
const ref = source.ref ? source.ref.replace(/^v?(?=\d)/, "v") : `v${version}`;
|
|
301
|
+
return { cmd: "pnpm", args: ["add", `github:${source.owner}/${source.repo}#${ref}`] };
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// ---------------------------------------------------------------- 状态存取
|
|
305
|
+
async function readJson(file, missing = null) {
|
|
306
|
+
try {
|
|
307
|
+
const st = await fs.promises.stat(file);
|
|
308
|
+
if (st.size > 10 * 1024 * 1024) throw updateError("state-unavailable");
|
|
309
|
+
return JSON.parse(await fs.promises.readFile(file, "utf8"));
|
|
310
|
+
} catch (error) {
|
|
311
|
+
if (error?.code === "ENOENT") return missing;
|
|
312
|
+
throw updateError("state-unavailable");
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
async function writeJson(file, value) {
|
|
317
|
+
const tmp = `${file}.${crypto.randomUUID()}.tmp`;
|
|
318
|
+
try {
|
|
319
|
+
await fs.promises.writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: "wx" });
|
|
320
|
+
await fs.promises.rename(tmp, file);
|
|
321
|
+
} catch { throw updateError("state-unavailable"); }
|
|
322
|
+
finally { await fs.promises.unlink(tmp).catch((e) => { if (e?.code !== "ENOENT") throw updateError("state-unavailable"); }); }
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function processAlive(pid) {
|
|
326
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
327
|
+
try { process.kill(pid, 0); return true; } catch (e) { return e?.code !== "ESRCH"; }
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function publicJob(job) {
|
|
331
|
+
if (!job) return null;
|
|
332
|
+
const { id, state, targetVersion, previousVersion, message } = job;
|
|
333
|
+
return { id, state, targetVersion: targetVersion ?? null, previousVersion: previousVersion ?? null, message: message ?? null, recoverable: job.recoverable === true };
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// ---------------------------------------------------------------- 服务主体
|
|
337
|
+
export function createUpdateService({
|
|
338
|
+
runningVersion = null,
|
|
339
|
+
nodeVersion = process.versions.node,
|
|
340
|
+
fetchImpl = globalThis.fetch,
|
|
341
|
+
now = Date.now,
|
|
342
|
+
checkTimeoutMs = 10_000,
|
|
343
|
+
confirmationTtlMs = 10 * 60_000,
|
|
344
|
+
installTimeoutMs = 15 * 60_000,
|
|
345
|
+
inspect = inspectRuntime,
|
|
346
|
+
log = () => {},
|
|
347
|
+
spawnImpl = spawn,
|
|
348
|
+
} = {}) {
|
|
349
|
+
let checked = null;
|
|
350
|
+
let checking = null;
|
|
351
|
+
let lastCheckAt = -Infinity;
|
|
352
|
+
let activeJob = null;
|
|
353
|
+
let activeTask = null;
|
|
354
|
+
let abortController = null;
|
|
355
|
+
let unsavedJob = null;
|
|
356
|
+
let disposed = false;
|
|
357
|
+
|
|
358
|
+
const assertActive = () => { if (disposed) throw updateError("disposed"); };
|
|
359
|
+
|
|
360
|
+
/** 恢复状态一律**从当前安装推导**,不信任持久化标记(dsh-im 4.24.1 的教训)。 */
|
|
361
|
+
async function readJob(environment) {
|
|
362
|
+
const p = environment.paths;
|
|
363
|
+
if (!p) return null;
|
|
364
|
+
if (unsavedJob?.statePath === p.state) return unsavedJob.job;
|
|
365
|
+
let job = await readJson(p.state);
|
|
366
|
+
const lock = await readJson(p.lock, NO_LOCK);
|
|
367
|
+
if (!job) {
|
|
368
|
+
if (lock !== NO_LOCK) return { id: "locked", state: "interrupted", message: "recovery-required", targetVersion: null };
|
|
369
|
+
return null;
|
|
370
|
+
}
|
|
371
|
+
if (!JOB_STATES.has(job.state) || typeof job.id !== "string" || !isValidSemver(job.targetVersion ?? "")) {
|
|
372
|
+
throw updateError("state-unavailable");
|
|
373
|
+
}
|
|
374
|
+
job = { ...job, recoverable: false };
|
|
375
|
+
const historical = job.id !== activeJob?.id;
|
|
376
|
+
if (ACTIVE_STATES.has(job.state) && historical) {
|
|
377
|
+
if (lock === NO_LOCK || lock?.id !== job.id || !processAlive(lock?.pid)) {
|
|
378
|
+
job = { ...job, state: "interrupted", message: "recovery-required" };
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
if (historical && !ACTIVE_STATES.has(job.state) && lock !== NO_LOCK) {
|
|
382
|
+
return { ...job, state: "interrupted", message: "recovery-required" };
|
|
383
|
+
}
|
|
384
|
+
if (job.state === "restart-required" || job.state === "completed") {
|
|
385
|
+
if (environment.installedVersion !== job.targetVersion || environment.packageValid !== true) {
|
|
386
|
+
job = { ...job, state: "interrupted", message: "installation-changed" };
|
|
387
|
+
} else {
|
|
388
|
+
job = { ...job, state: environment.runningVersion === job.targetVersion ? "completed" : "restart-required" };
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
if (historical && lock === NO_LOCK && ["failed", "interrupted"].includes(job.state)
|
|
392
|
+
&& environment.packageValid === true && environment.eligible === true
|
|
393
|
+
&& environment.installedVersion === environment.runningVersion) {
|
|
394
|
+
return job.targetVersion === environment.runningVersion
|
|
395
|
+
? { ...job, state: "completed", message: "recovered" }
|
|
396
|
+
: { ...job, recoverable: true };
|
|
397
|
+
}
|
|
398
|
+
return job;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function resolveSourceOrThrow(environment, configSource) {
|
|
402
|
+
const source = resolveSource({ configSource, environmentKind: environment.environmentKind, specifier: environment.specifier });
|
|
403
|
+
if (!source) {
|
|
404
|
+
throw Object.assign(updateError("source-install"), {
|
|
405
|
+
detail: `当前是 ${environment.environmentKind} 安装(声明:${environment.specifier ?? "无"}),没有可更新的上游。`
|
|
406
|
+
+ "发布到 npm 或 GitHub 后,在 config 里写 update.source=\"npm:<包名>\" 或 \"github:<owner>/<repo>\"。",
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
return source;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
async function fetchRelease(source) {
|
|
413
|
+
if (source.kind === "registry") return fetchNpmRelease({ packageName: source.packageName, fetchImpl });
|
|
414
|
+
return fetchGithubRelease({ owner: source.owner, repo: source.repo, fetchImpl });
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function snapshot(environment, job, { latest = null, source = null } = {}) {
|
|
418
|
+
let blockedReason = environment.blockedReason ?? null;
|
|
419
|
+
if (job?.state === "interrupted" && !job.recoverable
|
|
420
|
+
|| (job?.state === "failed" && environment.installedVersion !== environment.runningVersion)) {
|
|
421
|
+
blockedReason = "recovery-required";
|
|
422
|
+
} else if (job?.state === "restart-required"
|
|
423
|
+
|| (environment.installedVersion && environment.installedVersion !== environment.runningVersion)) {
|
|
424
|
+
blockedReason = "pending-restart";
|
|
425
|
+
}
|
|
426
|
+
const busy = ACTIVE_STATES.has(job?.state);
|
|
427
|
+
const canInstall = Boolean(
|
|
428
|
+
environment.eligible && !blockedReason && !busy
|
|
429
|
+
&& checked?.checkId && now() < checked.expiresAt
|
|
430
|
+
&& checked.installationKey === environment.installationKey
|
|
431
|
+
&& isValidSemver(environment.runningVersion ?? "")
|
|
432
|
+
&& latest && gtSemver(latest.version, environment.runningVersion),
|
|
433
|
+
);
|
|
434
|
+
return {
|
|
435
|
+
runningVersion: environment.runningVersion,
|
|
436
|
+
installedVersion: environment.installedVersion ?? null,
|
|
437
|
+
latestVersion: latest?.version ?? null,
|
|
438
|
+
profileName: environment.profileName ?? null,
|
|
439
|
+
environmentKind: environment.environmentKind,
|
|
440
|
+
sourceSpec: source?.spec ?? null,
|
|
441
|
+
sourceInstall: environment.environmentKind === "link",
|
|
442
|
+
canInstall,
|
|
443
|
+
blockedReason,
|
|
444
|
+
checkedAt: checked?.checkedAt ?? null,
|
|
445
|
+
checkId: canInstall ? checked.checkId : null,
|
|
446
|
+
job: publicJob(job),
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** 统一取运行时环境,并把**本服务认定的运行版本**注入进去。
|
|
451
|
+
* (inspectRuntime 自己不知道运行版本;不注入的话 canInstall 永远为 false —— 踩过) */
|
|
452
|
+
const environmentOf = async (configSource) => {
|
|
453
|
+
const env = await inspect({ profileDir: configSource?.profileDir });
|
|
454
|
+
return { ...env, runningVersion: runningVersion ?? env.runningVersion ?? null };
|
|
455
|
+
};
|
|
456
|
+
|
|
457
|
+
async function status(configSource) {
|
|
458
|
+
assertActive();
|
|
459
|
+
const env = await environmentOf(configSource);
|
|
460
|
+
const source = (() => { try { return resolveSourceOrThrow(env, configSource?.source); } catch { return null; } })();
|
|
461
|
+
const latest = checked?.release ?? null;
|
|
462
|
+
return snapshot(env, await readJob(env), { latest, source });
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
async function check(configSource) {
|
|
466
|
+
assertActive();
|
|
467
|
+
if (checking) return checking;
|
|
468
|
+
if (checked?.checkId && now() - lastCheckAt < 2_000) return status(configSource);
|
|
469
|
+
lastCheckAt = now();
|
|
470
|
+
checking = (async () => {
|
|
471
|
+
try {
|
|
472
|
+
const env = await environmentOf(configSource);
|
|
473
|
+
const source = resolveSourceOrThrow(env, configSource?.source);
|
|
474
|
+
const release = await fetchRelease(source);
|
|
475
|
+
assertActive();
|
|
476
|
+
// node 兼容性:**不满足就拒装**,而不是装完才发现跑不起来
|
|
477
|
+
if (release.nodeRange && release.nodeRange !== "*") {
|
|
478
|
+
let ok = false;
|
|
479
|
+
try { ok = satisfiesRange(nodeVersion, release.nodeRange); }
|
|
480
|
+
catch (e) { if (e?.code !== "unsupported-range") throw e; ok = true; } // 认不出的 range 不拦
|
|
481
|
+
if (!ok) throw Object.assign(updateError("check-failed"), { detail: `目标版本要求 node ${release.nodeRange},当前 ${nodeVersion}` });
|
|
482
|
+
}
|
|
483
|
+
checked = {
|
|
484
|
+
release, source, checkId: crypto.randomUUID(),
|
|
485
|
+
checkedAt: now(), expiresAt: now() + confirmationTtlMs,
|
|
486
|
+
installationKey: env.installationKey, profileDir: env.profileDir,
|
|
487
|
+
};
|
|
488
|
+
return snapshot(env, await readJob(env), { latest: release, source });
|
|
489
|
+
} catch (error) {
|
|
490
|
+
if (checked) checked = { ...checked, checkId: null, expiresAt: 0 };
|
|
491
|
+
throw error;
|
|
492
|
+
} finally { checking = null; }
|
|
493
|
+
})();
|
|
494
|
+
return checking;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
async function releaseLock(p, id) {
|
|
498
|
+
const lock = await readJson(p.lock);
|
|
499
|
+
if (lock?.id === id) await fs.promises.unlink(p.lock).catch(() => {});
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** 装前快照:**只存清单文件**,绝不碰凭据或整个 home。 */
|
|
503
|
+
async function backupProfile(environment, p, job) {
|
|
504
|
+
const files = {};
|
|
505
|
+
for (const name of SNAPSHOT_FILES) {
|
|
506
|
+
try {
|
|
507
|
+
const st = await fs.promises.stat(path.join(environment.profileDir, name));
|
|
508
|
+
if (st.size > 3 * 1024 * 1024) throw updateError("state-unavailable");
|
|
509
|
+
files[name] = await fs.promises.readFile(path.join(environment.profileDir, name), "utf8");
|
|
510
|
+
} catch (error) { if (error?.code !== "ENOENT") throw updateError("state-unavailable"); }
|
|
511
|
+
}
|
|
512
|
+
await writeJson(p.backup, { jobId: job.id, previousVersion: job.previousVersion, files });
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
const rememberUnsavedJob = (p) => {
|
|
516
|
+
activeJob = { ...activeJob, state: "interrupted", message: "state-unavailable" };
|
|
517
|
+
unsavedJob = { statePath: p.state, job: activeJob };
|
|
518
|
+
};
|
|
519
|
+
|
|
520
|
+
async function runInstall(p, job, originalEnvironment) {
|
|
521
|
+
const deadline = AbortSignal.timeout(installTimeoutMs);
|
|
522
|
+
try {
|
|
523
|
+
const { cmd, args } = installCommand(job.source, job.targetVersion);
|
|
524
|
+
await new Promise((resolve, reject) => {
|
|
525
|
+
const child = spawnImpl(cmd, args, {
|
|
526
|
+
cwd: originalEnvironment.profileDir,
|
|
527
|
+
shell: process.platform === "win32",
|
|
528
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
529
|
+
env: process.env,
|
|
530
|
+
});
|
|
531
|
+
let out = "";
|
|
532
|
+
const onAbort = () => { try { child.kill("SIGTERM"); } catch { /* 已退出 */ } };
|
|
533
|
+
if (AbortSignal.any) {
|
|
534
|
+
const combined = AbortSignal.any([abortController.signal, deadline]);
|
|
535
|
+
combined.addEventListener("abort", onAbort, { once: true });
|
|
536
|
+
}
|
|
537
|
+
child.stdout?.on("data", (b) => { out += String(b); if (out.length > 8000) out = out.slice(-8000); });
|
|
538
|
+
child.stderr?.on("data", (b) => { out += String(b); if (out.length > 8000) out = out.slice(-8000); });
|
|
539
|
+
child.on("error", reject);
|
|
540
|
+
child.on("close", (code) => (code === 0 ? resolve(out) : reject(updateError(code === null ? "install-interrupted" : "install-failed"))));
|
|
541
|
+
});
|
|
542
|
+
if (disposed) throw updateError("interrupted");
|
|
543
|
+
activeJob = { ...activeJob, state: "verifying", updatedAt: now() };
|
|
544
|
+
await writeJson(p.state, activeJob);
|
|
545
|
+
const after = await inspect({ profileDir: originalEnvironment.profileDir });
|
|
546
|
+
if (after.profileDir !== originalEnvironment.profileDir || after.installationKey !== originalEnvironment.installationKey) {
|
|
547
|
+
throw updateError("installation-changed");
|
|
548
|
+
}
|
|
549
|
+
if (after.installedVersion !== job.targetVersion || after.packageValid !== true) throw updateError("verify-failed");
|
|
550
|
+
activeJob = { ...activeJob, state: "restart-required", message: null, updatedAt: now() };
|
|
551
|
+
await writeJson(p.state, activeJob);
|
|
552
|
+
log("info", `自更新完成:${job.previousVersion} → ${job.targetVersion}(需重启 DSH 生效)`);
|
|
553
|
+
} catch (error) {
|
|
554
|
+
const timedOut = deadline.aborted || error?.code === "install-timeout";
|
|
555
|
+
const interrupted = disposed || abortController?.signal?.aborted
|
|
556
|
+
|| (!timedOut && ["interrupted", "install-interrupted"].includes(error?.code));
|
|
557
|
+
activeJob = {
|
|
558
|
+
...activeJob,
|
|
559
|
+
state: interrupted ? "interrupted" : "failed",
|
|
560
|
+
message: interrupted ? "interrupted" : timedOut ? "install-timeout" : error?.code ?? "install-failed",
|
|
561
|
+
updatedAt: now(),
|
|
562
|
+
};
|
|
563
|
+
log("warn", `自更新失败(${activeJob.message}):${job.previousVersion} → ${job.targetVersion}`);
|
|
564
|
+
try { await writeJson(p.state, activeJob); }
|
|
565
|
+
catch { rememberUnsavedJob(p); return; }
|
|
566
|
+
}
|
|
567
|
+
await releaseLock(p, job.id);
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
async function install({ checkId, requestId, configSource = {} }) {
|
|
571
|
+
assertActive();
|
|
572
|
+
const environment = await environmentOf(configSource);
|
|
573
|
+
const previous = await readJob(environment);
|
|
574
|
+
if (previous?.requestId === requestId) return snapshot(environment, previous, { latest: checked?.release, source: checked?.source });
|
|
575
|
+
if (ACTIVE_STATES.has(previous?.state) || previous?.state === "restart-required") throw updateError("update-busy");
|
|
576
|
+
const confirmation = checked;
|
|
577
|
+
if (!confirmation || !checkId || confirmation.checkId !== checkId || now() >= confirmation.expiresAt) {
|
|
578
|
+
throw updateError("check-expired");
|
|
579
|
+
}
|
|
580
|
+
if (environment.profileDir !== confirmation.profileDir || environment.installationKey !== confirmation.installationKey) {
|
|
581
|
+
throw updateError("installation-changed");
|
|
582
|
+
}
|
|
583
|
+
if (!environment.eligible) throw updateError("source-install");
|
|
584
|
+
const p = environment.paths;
|
|
585
|
+
if (!p) throw updateError("state-unavailable");
|
|
586
|
+
|
|
587
|
+
const job = {
|
|
588
|
+
id: crypto.randomUUID(), requestId, state: "installing", message: null,
|
|
589
|
+
targetVersion: confirmation.release.version,
|
|
590
|
+
previousVersion: environment.installedVersion,
|
|
591
|
+
source: confirmation.source,
|
|
592
|
+
startedAt: now(), updatedAt: now(),
|
|
593
|
+
};
|
|
594
|
+
let locked = false;
|
|
595
|
+
try {
|
|
596
|
+
await fs.promises.mkdir(p.directory, { recursive: true, mode: 0o700 });
|
|
597
|
+
const lock = await fs.promises.open(p.lock, "wx", 0o600);
|
|
598
|
+
locked = true;
|
|
599
|
+
try { await lock.writeFile(JSON.stringify({ id: job.id, pid: process.pid, startedAt: now() })); }
|
|
600
|
+
finally { await lock.close(); }
|
|
601
|
+
// 装之前再确认一次注册表给的还是同一个版本(防止隔太久目标漂移)
|
|
602
|
+
const current = await fetchRelease(confirmation.source);
|
|
603
|
+
if (current.version !== confirmation.release.version) throw updateError("check-expired");
|
|
604
|
+
await backupProfile(environment, p, job);
|
|
605
|
+
await writeJson(p.state, job);
|
|
606
|
+
assertActive();
|
|
607
|
+
} catch (error) {
|
|
608
|
+
if (locked) await releaseLock(p, job.id);
|
|
609
|
+
if (error?.code === "EEXIST") throw updateError("update-busy");
|
|
610
|
+
if (typeof error?.code === "string" && error.code.startsWith("E")) throw updateError("state-unavailable");
|
|
611
|
+
throw error;
|
|
612
|
+
}
|
|
613
|
+
activeJob = job;
|
|
614
|
+
abortController = new AbortController();
|
|
615
|
+
activeTask = runInstall(p, job, environment).catch(() => rememberUnsavedJob(p));
|
|
616
|
+
return snapshot(environment, job, { latest: confirmation.release, source: confirmation.source });
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** 只清本地作业历史(不影响已安装版本)。用于把卡住的 recovery-required 放掉。 */
|
|
620
|
+
async function reset(configSource = {}) {
|
|
621
|
+
assertActive();
|
|
622
|
+
const environment = await environmentOf(configSource);
|
|
623
|
+
const p = environment.paths;
|
|
624
|
+
if (!p) throw updateError("state-unavailable");
|
|
625
|
+
// cleared 要说实话:目录本来不存在就不是"清理成功"
|
|
626
|
+
const existed = fs.existsSync(p.directory);
|
|
627
|
+
if (existed) {
|
|
628
|
+
await fs.promises.rm(p.directory, { recursive: true, force: true }).catch((error) => {
|
|
629
|
+
throw updateError("state-unavailable");
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
return { ok: true, cleared: existed, directory: p.directory, runningVersion: environment.runningVersion };
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
async function close() {
|
|
636
|
+
disposed = true;
|
|
637
|
+
abortController?.abort();
|
|
638
|
+
if (activeTask) await activeTask.catch(() => {});
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
return Object.freeze({ status, check, install, reset, close });
|
|
642
|
+
}
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Mailbox · Outlook / Hotmail",
|
|
4
|
+
"description": "Read, send and archive Outlook / Hotmail mail inside DeepSeek Harness: OAuth2 device-code sign-in, per-account panels, local full-text archive, and desktop notifications that surface one-time codes. Zero-dependency pure Node.",
|
|
5
|
+
"detail": "docs/DETAIL.md"
|
|
6
|
+
}
|
|
7
|
+
}
|