dsh-cliproxyapi-pro 1.9.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.en.md +24 -408
  3. package/README.md +24 -408
  4. package/lib/client.js +265 -27
  5. package/lib/host/accounts.js +178 -0
  6. package/lib/host/apply/agent-tool.js +406 -0
  7. package/lib/host/apply/commands.js +122 -0
  8. package/lib/host/apply/controller.js +121 -0
  9. package/lib/host/apply/http-routes.js +273 -0
  10. package/lib/host/apply/image-jobs.js +171 -0
  11. package/lib/host/apply/index.js +41 -0
  12. package/lib/host/apply/interpret.js +72 -0
  13. package/lib/host/apply/lifecycle.js +50 -0
  14. package/lib/host/apply/media-failures.js +68 -0
  15. package/lib/host/apply/media-service.js +202 -0
  16. package/lib/host/apply/quota-service.js +42 -0
  17. package/lib/host/apply/references.js +43 -0
  18. package/lib/host/apply/session-status.js +104 -0
  19. package/lib/host/apply/state.js +78 -0
  20. package/lib/host/apply/updates.js +55 -0
  21. package/lib/host/apply/video-command.js +152 -0
  22. package/lib/host/apply/video-edit.js +253 -0
  23. package/lib/host/apply/video-jobs.js +206 -0
  24. package/lib/host/apply-utils.js +39 -0
  25. package/lib/host/config.js +210 -0
  26. package/lib/host/controller.js +464 -0
  27. package/lib/host/discovery.js +301 -0
  28. package/lib/host/http-gate.js +144 -0
  29. package/lib/host/model-info.js +363 -0
  30. package/lib/host/model-names.js +152 -0
  31. package/lib/host/models.js +75 -0
  32. package/lib/host/mount-guard.js +56 -0
  33. package/lib/host/recommend.js +367 -0
  34. package/lib/host/routes.js +165 -0
  35. package/lib/host/runtime.js +471 -0
  36. package/lib/host/state-store.js +39 -0
  37. package/lib/host/status-text.js +93 -0
  38. package/lib/index.js +18 -4417
  39. package/lib/media/agent-tool.js +255 -0
  40. package/lib/media/choice.js +83 -0
  41. package/lib/media/classify.js +65 -0
  42. package/lib/media/codec/fit.js +76 -0
  43. package/lib/media/codec/jpeg.js +158 -0
  44. package/lib/media/codec/png.js +102 -0
  45. package/lib/media/commands/parsing.js +269 -0
  46. package/lib/media/constants.js +46 -0
  47. package/lib/media/diagnose.js +134 -0
  48. package/lib/media/images.js +165 -0
  49. package/lib/media/index.js +29 -0
  50. package/lib/media/interpret.js +126 -0
  51. package/lib/media/job-store.js +99 -0
  52. package/lib/media/mp4.js +44 -0
  53. package/lib/media/output-files.js +59 -0
  54. package/lib/media/session-store.js +293 -0
  55. package/lib/media/settings.js +255 -0
  56. package/lib/media/util.js +45 -0
  57. package/lib/media/video.js +326 -0
  58. package/lib/quota/auth-state.js +33 -0
  59. package/lib/quota/constants.js +86 -0
  60. package/lib/quota/controller.js +467 -0
  61. package/lib/quota/helpers.js +325 -0
  62. package/lib/quota/index.js +19 -0
  63. package/lib/quota/management.js +216 -0
  64. package/lib/quota/matching.js +143 -0
  65. package/lib/quota/parsers.js +352 -0
  66. package/lib/quota/probes/billing.js +80 -0
  67. package/lib/quota/probes/google.js +120 -0
  68. package/lib/quota/probes/oauth.js +27 -0
  69. package/lib/quota/probes/plugin.js +18 -0
  70. package/lib/updater/constants.js +23 -0
  71. package/lib/updater/errors.js +8 -0
  72. package/lib/updater/index.js +11 -0
  73. package/lib/updater/registry.js +83 -0
  74. package/lib/updater/settings.js +45 -0
  75. package/lib/updater/store.js +23 -0
  76. package/lib/updater/updater.js +148 -0
  77. package/lib/updater/verify.js +110 -0
  78. package/lib/updater/version.js +31 -0
  79. package/locale/en.json +1 -1
  80. package/locale/zh.json +1 -1
  81. package/package.json +6 -9
  82. package/lib/media.js +0 -2542
  83. package/lib/quota.js +0 -1748
  84. package/lib/updater.js +0 -443
package/lib/updater.js DELETED
@@ -1,443 +0,0 @@
1
- // Plugin update checks and verified offline downloads. Never writes installed code.
2
- // Only Node.js built-ins; npm / DSH remain responsible for installation.
3
- import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
4
- import { mkdirSync, readFileSync, renameSync, writeFileSync, unlinkSync } from "node:fs";
5
- import { dirname, join } from "node:path";
6
- import { gunzipSync } from "node:zlib";
7
-
8
- export const UPDATE_PACKAGE = "dsh-cliproxyapi-pro";
9
- export const UPDATE_REGISTRIES = Object.freeze({
10
- global: "https://registry.npmjs.org",
11
- cn: "https://registry.npmmirror.com",
12
- });
13
- export const UPDATE_TAGS = Object.freeze({ stable: "latest", beta: "beta", dev: "dev" });
14
- export const UPDATE_INTERVAL_MS = 6 * 60 * 60 * 1000;
15
- export const DEFAULT_UPDATE_SETTINGS = Object.freeze({
16
- autoCheck: true, autoDownload: false, autoInstall: false, channel: "stable", region: "auto",
17
- });
18
- const BOOLEAN_SETTINGS = ["autoCheck", "autoDownload", "autoInstall"];
19
- const MAX_METADATA_BYTES = 512 * 1024;
20
- const MAX_PACKAGE_BYTES = 8 * 1024 * 1024;
21
- const MAX_UNPACKED_BYTES = 16 * 1024 * 1024;
22
- const MAX_PACKAGE_ENTRIES = 1000;
23
- const MAX_PATH_SEGMENTS = 6;
24
- // Plain names only: no dotfiles, spaces, shell/glob characters or non-ASCII.
25
- const SAFE_SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9._-]{0,99}$/;
26
- // npm packs these root files whether or not `files` lists them.
27
- const ALWAYS_PACKED = /^(?:package\.json|(?:README|LICEN[CS]E|NOTICE)(?:\.[A-Za-z0-9_-]+)*)$/i;
28
- const REQUIRED_FILES = ["package.json", "lib/index.js", "lib/client.js", "cordis.patch.yml", "locale/en.json", "locale/zh.json"];
29
-
30
- export class UpdateError extends Error {
31
- /** `detail` is a short diagnostic for logs only; the UI shows `code`. */
32
- constructor(code, detail) { super(code); this.code = code; if (detail) this.detail = detail; }
33
- }
34
- const fail = (code, detail) => { throw new UpdateError(code, detail); };
35
- const printable = (value) => String(value).replace(/[^\x20-\x7e]/g, "?").slice(0, 160);
36
-
37
- /**
38
- * Compile the package's own `files` field (npm semantics: a matched directory
39
- * includes its contents, `*` stays within a segment, `**` spans segments).
40
- * Negations only remove files from what npm packs, so they are ignored here;
41
- * absolute or traversing patterns never match.
42
- */
43
- export function packageFilePatterns(files) {
44
- if (!Array.isArray(files) || files.length === 0 || files.length > 200) fail("invalid-package", "package.json has no usable \"files\" list");
45
- const patterns = [];
46
- for (const raw of files) {
47
- if (typeof raw !== "string") fail("invalid-package", "package.json \"files\" contains a non-string entry");
48
- const pattern = raw.trim().replace(/^\.\//, "").replace(/\/+$/, "");
49
- if (!pattern || pattern.startsWith("!") || pattern.startsWith("/") || pattern.includes("\\") ||
50
- pattern.split("/").some((part) => part === "" || part === "." || part === "..")) continue;
51
- const parts = pattern.split("/");
52
- const body = parts.map((part, i) => {
53
- const last = i === parts.length - 1;
54
- if (part === "**") return last ? ".*" : "(?:[^/]+/)*";
55
- return part.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]") + (last ? "" : "/");
56
- }).join("");
57
- patterns.push(new RegExp(`^${body}(?:/.*)?$`));
58
- }
59
- return patterns;
60
- }
61
-
62
- export function normalizeUpdateSettings(raw = {}) {
63
- return {
64
- autoCheck: typeof raw?.autoCheck === "boolean" ? raw.autoCheck : true,
65
- autoDownload: raw?.autoDownload === true,
66
- // Consumed by the Web client, which delegates installation to dshmarket.
67
- autoInstall: raw?.autoInstall === true,
68
- channel: Object.hasOwn(UPDATE_TAGS, raw?.channel ?? "") ? raw.channel : "stable",
69
- region: ["auto", "global", "cn"].includes(raw?.region) ? raw.region : "auto",
70
- };
71
- }
72
-
73
- export function loadUpdateSettings(file) {
74
- try {
75
- const raw = JSON.parse(readFileSync(file, "utf8"));
76
- if (!raw || typeof raw !== "object" || Array.isArray(raw) || raw.version !== 1 ||
77
- BOOLEAN_SETTINGS.some((key) => raw[key] !== undefined && typeof raw[key] !== "boolean") ||
78
- raw.channel !== undefined && !Object.hasOwn(UPDATE_TAGS, raw.channel) ||
79
- raw.region !== undefined && !["auto", "global", "cn"].includes(raw.region)) fail("invalid-settings");
80
- return normalizeUpdateSettings(raw);
81
- }
82
- catch (error) {
83
- if (error.code === "ENOENT") return { ...DEFAULT_UPDATE_SETTINGS };
84
- // Corrupt or unreadable settings must not silently enable network access.
85
- return { ...DEFAULT_UPDATE_SETTINGS, autoCheck: false };
86
- }
87
- }
88
-
89
- export function saveUpdateSettings(file, settings) {
90
- const temporary = `${file}.${randomUUID()}.tmp`;
91
- try {
92
- mkdirSync(dirname(file), { recursive: true });
93
- writeFileSync(temporary, `${JSON.stringify({ version: 1, ...normalizeUpdateSettings(settings) }, null, 2)}\n`, { mode: 0o600, flag: "wx" });
94
- renameSync(temporary, file);
95
- } catch {
96
- try { unlinkSync(temporary); } catch {}
97
- fail("storage-error");
98
- }
99
- }
100
-
101
- // Strict SemVer, including prerelease precedence. Never reuse model-name sorting.
102
- export function parseUpdateVersion(value) {
103
- if (typeof value !== "string" || value.length > 128) return null;
104
- const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/.exec(value);
105
- if (!match) return null;
106
- const parts = match.slice(1, 4).map(Number);
107
- if (parts.some((n) => !Number.isSafeInteger(n))) return null;
108
- const pre = match[4]?.split(".") ?? [];
109
- if (pre.some((p) => /^\d+$/.test(p) && (p.length > 1 && p.startsWith("0") || !Number.isSafeInteger(Number(p))))) return null;
110
- return { parts, pre };
111
- }
112
-
113
- export function compareUpdateVersions(a, b) {
114
- const x = parseUpdateVersion(a), y = parseUpdateVersion(b);
115
- if (!x || !y) fail("invalid-metadata");
116
- for (let i = 0; i < 3; i++) if (x.parts[i] !== y.parts[i]) return x.parts[i] > y.parts[i] ? 1 : -1;
117
- if (!x.pre.length || !y.pre.length) return x.pre.length ? -1 : y.pre.length ? 1 : 0;
118
- for (let i = 0; i < Math.max(x.pre.length, y.pre.length); i++) {
119
- if (x.pre[i] === undefined || y.pre[i] === undefined) return x.pre[i] === undefined ? -1 : 1;
120
- const p = x.pre[i], q = y.pre[i];
121
- if (p === q) continue;
122
- const pn = /^\d+$/.test(p), qn = /^\d+$/.test(q);
123
- if (pn && qn) return Number(p) > Number(q) ? 1 : -1;
124
- if (pn !== qn) return pn ? -1 : 1;
125
- return p > q ? 1 : -1;
126
- }
127
- return 0;
128
- }
129
-
130
- function integrityDigest(integrity) {
131
- if (typeof integrity !== "string") fail("invalid-metadata");
132
- const token = integrity.split(/\s+/).find((part) => /^sha512-[A-Za-z0-9+/]{86}==$/.test(part));
133
- if (!token) fail("invalid-metadata");
134
- const digest = Buffer.from(token.slice(7), "base64");
135
- if (digest.length !== 64) fail("invalid-metadata");
136
- return digest;
137
- }
138
-
139
- export function validateUpdateMetadata(raw, channel) {
140
- if (!Object.hasOwn(UPDATE_TAGS, channel)) fail("invalid-metadata");
141
- const parsed = parseUpdateVersion(raw?.version);
142
- if (raw?.name !== UPDATE_PACKAGE || !parsed || channel === "stable" && parsed.pre.length) fail("invalid-metadata");
143
- // Keep channels honest even if an upstream dist-tag is accidentally moved.
144
- if (channel !== "stable" && parsed.pre.length && !parsed.pre.some((p) => p === channel)) fail("invalid-metadata");
145
- let url;
146
- try { url = new URL(raw?.dist?.tarball); } catch { fail("invalid-metadata"); }
147
- const hosts = ["registry.npmjs.org", "registry.npmmirror.com"];
148
- if (url.protocol !== "https:" || !hosts.includes(url.hostname) || url.port || url.username || url.password || url.search || url.hash) fail("invalid-metadata");
149
- if (url.pathname !== `/${UPDATE_PACKAGE}/-/${UPDATE_PACKAGE}-${raw.version}.tgz`) fail("invalid-metadata");
150
- integrityDigest(raw.dist.integrity);
151
- return { version: raw.version, integrity: raw.dist.integrity };
152
- }
153
-
154
- async function readBounded(response, maxBytes) {
155
- const declared = Number(response.headers.get("content-length"));
156
- if (Number.isFinite(declared) && declared > maxBytes) { await response.body?.cancel(); fail("invalid-package"); }
157
- const chunks = [];
158
- let length = 0;
159
- if (!response.body) fail("network-error");
160
- const reader = response.body.getReader();
161
- try {
162
- while (true) {
163
- const { done, value } = await reader.read();
164
- if (done) break;
165
- length += value.length;
166
- if (length > maxBytes) { await reader.cancel(); fail("invalid-package"); }
167
- chunks.push(Buffer.from(value));
168
- }
169
- } finally { reader.releaseLock(); }
170
- return Buffer.concat(chunks, length);
171
- }
172
-
173
- function allowedDownloadUrl(value, version, region) {
174
- let url;
175
- try { url = new URL(value); } catch { fail("invalid-package"); }
176
- if (url.protocol !== "https:" || url.port || url.username || url.password || url.search || url.hash) fail("invalid-package");
177
- const registryPath = `/${UPDATE_PACKAGE}/-/${UPDATE_PACKAGE}-${version}.tgz`;
178
- const cdnPath = `/packages/${UPDATE_PACKAGE}/${version}/${UPDATE_PACKAGE}-${version}.tgz`;
179
- if (region === "global") {
180
- if (url.hostname !== "registry.npmjs.org" || url.pathname !== registryPath) fail("invalid-package");
181
- } else if (!(url.hostname === "registry.npmmirror.com" && url.pathname === registryPath ||
182
- url.hostname === "cdn.npmmirror.com" && url.pathname === cdnPath)) fail("invalid-package");
183
- return url.href;
184
- }
185
-
186
- async function fetchBytes(fetcher, url, signal, limit, download = null) {
187
- // npmmirror redirects tarballs to its official CDN. Follow only bounded,
188
- // exact package/version URLs; never let fetch follow an unvalidated location.
189
- for (let redirects = 0; ; redirects++) {
190
- const response = await fetcher(url, {
191
- signal, redirect: download ? "manual" : "error", credentials: "omit",
192
- headers: { accept: "application/json, application/octet-stream" },
193
- });
194
- if ([301, 302, 303, 307, 308].includes(response.status)) {
195
- const location = response.headers.get("location");
196
- await response.body?.cancel();
197
- if (!download || redirects >= 3 || !location) fail("invalid-package");
198
- let next;
199
- try { next = new URL(location, url).href; } catch { fail("invalid-package"); }
200
- url = allowedDownloadUrl(next, download.version, download.region);
201
- continue;
202
- }
203
- if (response.status === 404) { await response.body?.cancel(); fail("channel-unavailable"); }
204
- if (!response.ok) { await response.body?.cancel(); fail("network-error"); }
205
- return readBounded(response, limit);
206
- }
207
- }
208
-
209
- /**
210
- * Validate checksum and a restricted npm tar archive without extracting any file.
211
- * Which files may appear is not hard-coded: every regular file must be declared
212
- * by the package's own `files` field (or be one npm always packs), so a future
213
- * release can ship new files without this version rejecting it. Structural
214
- * safety rules (paths, entry types, sizes, dependencies, scripts) are fixed.
215
- */
216
- export function verifyUpdatePackage(bytes, expected) {
217
- const digest = createHash("sha512").update(bytes).digest();
218
- if (!timingSafeEqual(digest, integrityDigest(expected.integrity))) fail("integrity-error");
219
- let tar;
220
- try { tar = gunzipSync(bytes, { maxOutputLength: MAX_UNPACKED_BYTES }); }
221
- catch { fail("invalid-package", "not a gzip archive within the size limit"); }
222
- const seen = new Set();
223
- const files = [];
224
- const directories = [];
225
- let manifest;
226
- let ended = false;
227
- const text = (buffer) => buffer.toString("utf8").replace(/\0.*$/s, "");
228
- for (let offset = 0; offset + 512 <= tar.length;) {
229
- const header = tar.subarray(offset, offset + 512);
230
- if (header.every((b) => b === 0)) {
231
- if (tar.subarray(offset).some((b) => b !== 0)) fail("invalid-package", "data after the tar terminator");
232
- ended = true;
233
- break;
234
- }
235
- const octal = (buffer) => {
236
- const value = text(buffer).trim();
237
- if (!/^[0-7]+$/.test(value)) fail("invalid-package", "malformed tar header");
238
- return parseInt(value, 8);
239
- };
240
- const size = octal(header.subarray(124, 136));
241
- const checksum = octal(header.subarray(148, 156));
242
- let sum = 0;
243
- for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 32 : header[i];
244
- if (sum !== checksum || size > MAX_UNPACKED_BYTES || offset + 512 + size > tar.length) fail("invalid-package", "corrupt tar entry");
245
- const prefix = text(header.subarray(345, 500));
246
- const path = `${prefix ? `${prefix}/` : ""}${text(header.subarray(0, 100))}`;
247
- const type = header[156];
248
- const directory = type === 53;
249
- let relative = path.startsWith("package/") ? path.slice(8) : null;
250
- if (directory && relative?.endsWith("/")) relative = relative.slice(0, -1);
251
- const parts = relative?.split("/") ?? [];
252
- if (relative === null || (relative !== "" || !directory) && (parts.length > MAX_PATH_SEGMENTS ||
253
- parts.some((part) => !SAFE_SEGMENT.test(part) || part === "node_modules")) || seen.has(path)) {
254
- fail("invalid-package", `unsafe path ${printable(path)}`);
255
- }
256
- seen.add(path);
257
- if (seen.size > MAX_PACKAGE_ENTRIES) fail("invalid-package", "too many entries");
258
- if (directory) {
259
- if (size !== 0) fail("invalid-package", `non-empty directory entry ${printable(path)}`);
260
- directories.push(relative);
261
- } else if (type === 0 || type === 48) {
262
- files.push(relative);
263
- if (relative === "package.json") {
264
- try { manifest = JSON.parse(tar.subarray(offset + 512, offset + 512 + size).toString("utf8")); }
265
- catch { fail("invalid-package", "package.json is not valid JSON"); }
266
- }
267
- } else fail("invalid-package", `link or special entry ${printable(path)}`);
268
- offset += 512 + Math.ceil(size / 512) * 512;
269
- }
270
- if (!ended) fail("invalid-package", "missing tar terminator");
271
- const missing = REQUIRED_FILES.find((p) => !files.includes(p));
272
- if (missing) fail("invalid-package", `missing ${missing}`);
273
- if (!manifest || typeof manifest !== "object" || Array.isArray(manifest) || manifest.name !== UPDATE_PACKAGE ||
274
- manifest.version !== expected.version || manifest.dsh?.bundle?.patch !== "./cordis.patch.yml") {
275
- fail("invalid-package", "package.json does not describe this plugin version");
276
- }
277
- if (["dependencies", "optionalDependencies", "bundledDependencies", "bundleDependencies"].some((key) => manifest[key] && Object.keys(manifest[key]).length)) fail("invalid-package", "declares dependencies");
278
- const script = Object.keys(manifest.scripts ?? {}).find((key) => /^(?:preinstall|install|postinstall|prepare|prepublish|prepublishOnly|prepack|postpack)$/.test(key));
279
- if (script) fail("invalid-package", `declares lifecycle script ${printable(script)}`);
280
- const patterns = packageFilePatterns(manifest.files);
281
- const undeclared = files.find((file) => !(!file.includes("/") && ALWAYS_PACKED.test(file)) && !patterns.some((re) => re.test(file)));
282
- if (undeclared) fail("invalid-package", `file not declared in package.json "files": ${printable(undeclared)}`);
283
- const stray = directories.find((dir) => dir !== "" && !files.some((file) => file.startsWith(`${dir}/`)));
284
- if (stray !== undefined) fail("invalid-package", `directory without files ${printable(stray)}`);
285
- return manifest;
286
- }
287
-
288
- function quotedArgument(value) {
289
- // CLI examples must not turn local paths/profile names into shell syntax.
290
- // Both PowerShell and POSIX shells accept single-quoted strings without apostrophes.
291
- if (typeof value !== "string" || /['\r\n\0]/.test(value)) return null;
292
- return `'${value}'`;
293
- }
294
-
295
- /** Injected I/O makes every update test offline and independent of the real profile. */
296
- export function createPluginUpdater(deps) {
297
- const fetcher = deps.fetch ?? globalThis.fetch;
298
- const now = deps.now ?? (() => new Date().toISOString());
299
- let settings = normalizeUpdateSettings(deps.readSettings());
300
- let candidate = null;
301
- let generation = 0;
302
- let disposed = false;
303
- let checkPromise = null;
304
- let downloadPromise = null;
305
- let saving = false;
306
- const abort = new AbortController();
307
- const initial = {
308
- currentVersion: deps.currentVersion, latestVersion: null, available: false,
309
- effectiveRegion: null, lastCheckedAt: null, error: null, errorCode: null,
310
- downloadedVersion: null, downloadPath: null, upgradeCommand: null,
311
- blockedReason: deps.linkedInstall ? "linked-install" : null,
312
- };
313
- let state = { ...initial };
314
- const status = () => ({ ...state, ...settings, checking: checkPromise !== null, downloading: downloadPromise !== null });
315
- const assertLive = () => { if (disposed) fail("disposed"); };
316
- const recordError = (error) => {
317
- const code = error instanceof UpdateError ? error.code : "network-error";
318
- state.error = code;
319
- state.errorCode = code;
320
- // The page shows only the localized code; the concrete reason goes to the Host log.
321
- if (error instanceof UpdateError && error.detail) deps.logger?.warn?.(`[dsh-cliproxyapi] update ${code}: ${error.detail}`);
322
- };
323
-
324
- const lookup = async (region, snapshot, signal) => {
325
- const bytes = await fetchBytes(fetcher, `${UPDATE_REGISTRIES[region]}/${UPDATE_PACKAGE}/${UPDATE_TAGS[snapshot.channel]}`, signal, MAX_METADATA_BYTES);
326
- let raw;
327
- try { raw = JSON.parse(bytes.toString("utf8")); } catch { fail("invalid-metadata"); }
328
- return { ...validateUpdateMetadata(raw, snapshot.channel), region };
329
- };
330
-
331
- const download = (version) => {
332
- assertLive();
333
- if (downloadPromise) return downloadPromise;
334
- if (checkPromise || saving) fail("busy");
335
- if (!candidate || !state.available || version !== candidate.version) fail("stale-version");
336
- const selected = { ...candidate };
337
- state.error = state.errorCode = null;
338
- downloadPromise = Promise.resolve().then(async () => {
339
- const signal = AbortSignal.any([abort.signal, AbortSignal.timeout(60_000)]);
340
- const url = `${UPDATE_REGISTRIES[selected.region]}/${UPDATE_PACKAGE}/-/${UPDATE_PACKAGE}-${selected.version}.tgz`;
341
- const bytes = await fetchBytes(fetcher, url, signal, MAX_PACKAGE_BYTES, selected);
342
- assertLive();
343
- verifyUpdatePackage(bytes, selected);
344
- let path;
345
- try { path = await deps.storePackage(selected.version, bytes); }
346
- catch { fail("storage-error"); }
347
- assertLive();
348
- const profile = quotedArgument(deps.profileName);
349
- const target = quotedArgument(path);
350
- state.downloadedVersion = selected.version;
351
- state.downloadPath = path;
352
- state.upgradeCommand = !deps.linkedInstall && profile && target ? `dsh plugin --profile ${profile} add ${target}` : null;
353
- }).catch((error) => {
354
- recordError(error);
355
- }).finally(() => { downloadPromise = null; }).then(status);
356
- return downloadPromise;
357
- };
358
-
359
- const check = ({ automatic = false } = {}) => {
360
- assertLive();
361
- if (checkPromise) return checkPromise;
362
- if (downloadPromise || saving) fail("busy");
363
- if (automatic && !settings.autoCheck) return Promise.resolve(status());
364
- const snapshot = { ...settings };
365
- const revision = generation;
366
- state.error = state.errorCode = null;
367
- checkPromise = Promise.resolve().then(async () => {
368
- const winnerAbort = new AbortController();
369
- const signal = AbortSignal.any([abort.signal, winnerAbort.signal, AbortSignal.timeout(15_000)]);
370
- let result;
371
- try {
372
- result = snapshot.region === "auto"
373
- ? await Promise.any([lookup("global", snapshot, signal), lookup("cn", snapshot, signal)]).catch((error) => {
374
- const failures = error.errors ?? [];
375
- throw failures.find((e) => e.code === "invalid-metadata") ?? failures.find((e) => e.code === "channel-unavailable") ?? new UpdateError("network-error");
376
- })
377
- : await lookup(snapshot.region, snapshot, signal);
378
- } finally { winnerAbort.abort(); }
379
- assertLive();
380
- if (revision !== generation) return;
381
- candidate = result;
382
- state.latestVersion = result.version;
383
- state.available = compareUpdateVersions(result.version, deps.currentVersion) > 0;
384
- state.effectiveRegion = result.region;
385
- state.lastCheckedAt = now();
386
- }).catch((error) => {
387
- if (revision !== generation || disposed) return;
388
- candidate = null;
389
- state.available = false;
390
- state.latestVersion = null;
391
- state.lastCheckedAt = now();
392
- recordError(error);
393
- }).finally(() => { checkPromise = null; }).then(async () => {
394
- if (!disposed && automatic && settings.autoCheck && settings.autoDownload && revision === generation && state.available && state.downloadedVersion !== candidate?.version) {
395
- await download(candidate.version);
396
- }
397
- return status();
398
- });
399
- return checkPromise;
400
- };
401
-
402
- return {
403
- status, check, download,
404
- async save(patch = {}) {
405
- assertLive();
406
- if (checkPromise || downloadPromise || saving) fail("busy");
407
- if (!patch || typeof patch !== "object" || Array.isArray(patch)) fail("invalid-settings");
408
- if (Object.keys(patch).some((key) => !Object.hasOwn(DEFAULT_UPDATE_SETTINGS, key))) fail("invalid-settings");
409
- if (Object.hasOwn(patch, "channel") && !Object.hasOwn(UPDATE_TAGS, patch.channel) || Object.hasOwn(patch, "region") && !["auto", "global", "cn"].includes(patch.region)) fail("invalid-settings");
410
- for (const key of BOOLEAN_SETTINGS) if (Object.hasOwn(patch, key) && typeof patch[key] !== "boolean") fail("invalid-settings");
411
- const next = normalizeUpdateSettings({ ...settings, ...patch });
412
- saving = true;
413
- try {
414
- try { await deps.writeSettings(next); } catch { fail("storage-error"); }
415
- assertLive();
416
- const changedSource = next.channel !== settings.channel || next.region !== settings.region;
417
- settings = next;
418
- state.error = state.errorCode = null;
419
- generation += 1;
420
- if (changedSource) { candidate = null; state = { ...initial }; }
421
- deps.onSettingsChanged?.(settings);
422
- return status();
423
- } finally { saving = false; }
424
- },
425
- dispose() { disposed = true; generation += 1; abort.abort(); },
426
- };
427
- }
428
-
429
- /** Atomic same-directory writes; no package extraction, install or profile edits. */
430
- export function storeUpdatePackage(directory, version, bytes) {
431
- if (!parseUpdateVersion(version)) fail("invalid-package");
432
- const path = join(directory, `${UPDATE_PACKAGE}-${version}.tgz`);
433
- const temporary = join(directory, `.${randomUUID()}.tmp`);
434
- try {
435
- mkdirSync(directory, { recursive: true });
436
- writeFileSync(temporary, bytes, { flag: "wx", mode: 0o600 });
437
- renameSync(temporary, path);
438
- } catch {
439
- try { unlinkSync(temporary); } catch {}
440
- fail("storage-error");
441
- }
442
- return path;
443
- }