dsh-cliproxyapi-pro 1.8.0 → 1.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.en.md +38 -409
  3. package/README.md +38 -409
  4. package/lib/client.js +131 -28
  5. package/lib/host/accounts.js +176 -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 +105 -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 +34 -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 +205 -0
  26. package/lib/host/controller.js +435 -0
  27. package/lib/host/discovery.js +295 -0
  28. package/lib/host/http-gate.js +144 -0
  29. package/lib/host/models.js +102 -0
  30. package/lib/host/mount-guard.js +56 -0
  31. package/lib/host/routes.js +165 -0
  32. package/lib/host/runtime.js +445 -0
  33. package/lib/host/state-store.js +39 -0
  34. package/lib/host/status-text.js +93 -0
  35. package/lib/index.js +17 -4330
  36. package/lib/media/agent-tool.js +255 -0
  37. package/lib/media/choice.js +83 -0
  38. package/lib/media/classify.js +65 -0
  39. package/lib/media/codec/fit.js +76 -0
  40. package/lib/media/codec/jpeg.js +158 -0
  41. package/lib/media/codec/png.js +102 -0
  42. package/lib/media/commands/parsing.js +269 -0
  43. package/lib/media/constants.js +46 -0
  44. package/lib/media/diagnose.js +134 -0
  45. package/lib/media/images.js +165 -0
  46. package/lib/media/index.js +29 -0
  47. package/lib/media/interpret.js +126 -0
  48. package/lib/media/job-store.js +99 -0
  49. package/lib/media/mp4.js +44 -0
  50. package/lib/media/output-files.js +59 -0
  51. package/lib/media/session-store.js +293 -0
  52. package/lib/media/settings.js +255 -0
  53. package/lib/media/util.js +45 -0
  54. package/lib/media/video.js +326 -0
  55. package/lib/quota/auth-state.js +33 -0
  56. package/lib/quota/constants.js +86 -0
  57. package/lib/quota/controller.js +467 -0
  58. package/lib/quota/helpers.js +325 -0
  59. package/lib/quota/index.js +19 -0
  60. package/lib/quota/management.js +216 -0
  61. package/lib/quota/matching.js +143 -0
  62. package/lib/quota/parsers.js +352 -0
  63. package/lib/quota/probes/billing.js +80 -0
  64. package/lib/quota/probes/google.js +120 -0
  65. package/lib/quota/probes/oauth.js +27 -0
  66. package/lib/quota/probes/plugin.js +18 -0
  67. package/lib/updater/constants.js +23 -0
  68. package/lib/updater/errors.js +8 -0
  69. package/lib/updater/index.js +11 -0
  70. package/lib/updater/registry.js +83 -0
  71. package/lib/updater/settings.js +45 -0
  72. package/lib/updater/store.js +23 -0
  73. package/lib/updater/updater.js +148 -0
  74. package/lib/updater/verify.js +110 -0
  75. package/lib/updater/version.js +31 -0
  76. package/locale/en.json +1 -1
  77. package/locale/zh.json +1 -1
  78. package/package.json +6 -9
  79. package/lib/media.js +0 -2528
  80. package/lib/quota.js +0 -1646
  81. package/lib/updater.js +0 -443
@@ -0,0 +1,120 @@
1
+ // Google Code Assist loading and Antigravity/Gemini quota requests and fallback order.
2
+ import { UPSTREAM, AG_META, GEMINI_META, AG_SUMMARY_UA, AG_MODELS_UA } from "../constants.js";
3
+ import { QuotaError, isObj, firstText, projectIdOf, extractPlan } from "../helpers.js";
4
+ import { antigravitySummaryWindows, antigravityModelWindows, googleBucketWindows } from "../parsers.js";
5
+
6
+ export function createGoogleProbes({ apiCall, now, agPreferred }) {
7
+ async function loadCodeAssist(ctx, authIndex, metadata) {
8
+ const headers = metadata.ideType === "ANTIGRAVITY"
9
+ ? { Authorization: "Bearer $TOKEN$", "Content-Type": "application/json", "User-Agent": AG_SUMMARY_UA }
10
+ : googleHeaders(metadata);
11
+ const body = await apiCall(ctx, { auth_index: authIndex, method: "POST", url: UPSTREAM.googleLoad, header: headers, data: JSON.stringify({ metadata }) });
12
+ const project = body.cloudaicompanionProject ?? body.cloudaicompanion_project;
13
+ return { body, projectID: isObj(project) ? firstText(project.id) : firstText(project) };
14
+ }
15
+
16
+ function googleHeaders(metadata) {
17
+ return {
18
+ Authorization: "Bearer $TOKEN$",
19
+ "Content-Type": "application/json",
20
+ "User-Agent": "google-api-nodejs-client/9.15.1",
21
+ "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1",
22
+ "Client-Metadata": JSON.stringify(metadata),
23
+ };
24
+ }
25
+
26
+ return {
27
+ async antigravity(ctx, entry, authIndex, currentPlan) {
28
+ let projectID = projectIdOf(entry);
29
+ let plan = "";
30
+ let tier = null;
31
+ if (projectID === "") {
32
+ const loaded = await loadCodeAssist(ctx, authIndex, AG_META);
33
+ projectID = loaded.projectID;
34
+ plan = extractPlan(loaded.body);
35
+ } else if (currentPlan === "") {
36
+ tier = loadCodeAssist(ctx, authIndex, AG_META).then((l) => extractPlan(l.body), () => "");
37
+ }
38
+ if (projectID === "") throw new QuotaError("missing-project");
39
+ const header = (url) => ({
40
+ Authorization: "Bearer $TOKEN$",
41
+ "Content-Type": "application/json",
42
+ "User-Agent": url.includes("retrieveUserQuotaSummary") ? AG_SUMMARY_UA : AG_MODELS_UA,
43
+ });
44
+ const urls = [...UPSTREAM.antigravityQuota, ...UPSTREAM.antigravityModels];
45
+ const preferred = agPreferred.get(ctx.origin);
46
+ const ordered = preferred === undefined ? urls : [preferred, ...urls.filter((u) => u !== preferred)];
47
+ let lastError = null;
48
+ let partial = null;
49
+ let windows = null;
50
+ for (const url of ordered) {
51
+ const summary = url.includes("retrieveUserQuotaSummary");
52
+ if (partial !== null && !summary) continue;
53
+ try {
54
+ const body = await apiCall(ctx, { auth_index: authIndex, method: "POST", url, header: header(url), data: JSON.stringify({ project: projectID }) });
55
+ plan = plan || extractPlan(body);
56
+ const rows = summary ? antigravitySummaryWindows(body) : [];
57
+ if (rows.length > 0) {
58
+ if (rows.some((r) => r.modelPrefixes?.includes("gemini"))) {
59
+ windows = rows;
60
+ agPreferred.set(ctx.origin, url);
61
+ break;
62
+ }
63
+ // A host without the Gemini group: keep looking at the other summary hosts.
64
+ if (partial === null) partial = { rows, url };
65
+ continue;
66
+ }
67
+ const modelRows = antigravityModelWindows(body, now());
68
+ if (modelRows.length > 0) {
69
+ windows = modelRows;
70
+ agPreferred.set(ctx.origin, url);
71
+ break;
72
+ }
73
+ } catch (error) {
74
+ if (error?.code === "aborted") throw error;
75
+ lastError = error;
76
+ }
77
+ }
78
+ if (windows === null && partial !== null) {
79
+ windows = partial.rows;
80
+ agPreferred.set(ctx.origin, partial.url);
81
+ try {
82
+ const body = await apiCall(ctx, {
83
+ auth_index: authIndex,
84
+ method: "POST",
85
+ url: UPSTREAM.googleQuota,
86
+ header: { Authorization: "Bearer $TOKEN$", "Content-Type": "application/json", "User-Agent": AG_SUMMARY_UA },
87
+ data: JSON.stringify({ project: projectID }),
88
+ });
89
+ windows = [...windows, ...googleBucketWindows(body, now(), "ag-gemini")];
90
+ } catch (error) {
91
+ if (error?.code === "aborted") throw error;
92
+ /* the supplementary Gemini read is best-effort */
93
+ }
94
+ }
95
+ if (tier !== null) plan = plan || (await tier);
96
+ if (windows === null) throw lastError ?? new QuotaError("invalid-response");
97
+ return { windows, plan };
98
+ },
99
+
100
+ async "gemini-cli"(ctx, entry, authIndex) {
101
+ let projectID = projectIdOf(entry);
102
+ let plan = "";
103
+ if (projectID === "") {
104
+ const loaded = await loadCodeAssist(ctx, authIndex, GEMINI_META);
105
+ projectID = loaded.projectID;
106
+ plan = extractPlan(loaded.body);
107
+ }
108
+ if (projectID === "") throw new QuotaError("missing-project");
109
+ const body = await apiCall(ctx, {
110
+ auth_index: authIndex,
111
+ method: "POST",
112
+ url: UPSTREAM.googleQuota,
113
+ header: googleHeaders({ ...GEMINI_META, duetProject: projectID }),
114
+ data: JSON.stringify({ project: projectID }),
115
+ });
116
+ return { windows: googleBucketWindows(body, now(), "gemini"), plan };
117
+ },
118
+
119
+ };
120
+ }
@@ -0,0 +1,27 @@
1
+ // Codex and Claude OAuth quota requests; tokens remain substituted inside CPA.
2
+ import { UPSTREAM, CODEX_UA } from "../constants.js";
3
+ import { codexAccountId, extractPlan } from "../helpers.js";
4
+ import { parseCodexWindows, parseClaudeWindows, claudeProfilePlan } from "../parsers.js";
5
+
6
+ export function createOAuthProbes({ apiCall, now }) {
7
+ return {
8
+ async codex(ctx, entry, authIndex) {
9
+ const header = { Authorization: "Bearer $TOKEN$", "Content-Type": "application/json", "User-Agent": CODEX_UA };
10
+ const accountId = codexAccountId(entry);
11
+ if (accountId !== "") header["Chatgpt-Account-Id"] = accountId;
12
+ const body = await apiCall(ctx, { auth_index: authIndex, method: "GET", url: UPSTREAM.codexUsage, header });
13
+ return { windows: parseCodexWindows(body, now()), plan: extractPlan(body) };
14
+ },
15
+
16
+ async claude(ctx, entry, authIndex) {
17
+ const header = { Authorization: "Bearer $TOKEN$", "Content-Type": "application/json", "anthropic-beta": "oauth-2025-04-20" };
18
+ const [usage, profile] = await Promise.allSettled([
19
+ apiCall(ctx, { auth_index: authIndex, method: "GET", url: UPSTREAM.claudeUsage, header }),
20
+ apiCall(ctx, { auth_index: authIndex, method: "GET", url: UPSTREAM.claudeProfile, header }),
21
+ ]);
22
+ if (usage.status === "rejected") throw usage.reason;
23
+ return { windows: parseClaudeWindows(usage.value), plan: profile.status === "fulfilled" ? claudeProfilePlan(profile.value) : "" };
24
+ },
25
+
26
+ };
27
+ }
@@ -0,0 +1,18 @@
1
+ // CPA normalized plugin/declarative quota-fetch probe.
2
+ import { QuotaError, isObj, text, firstText } from "../helpers.js";
3
+ import { parsePluginQuota } from "../parsers.js";
4
+
5
+ export function createPluginProbe({ management }) {
6
+ /** CPA plugin / declarative quota: POST /v0/management/quota/fetch. */
7
+ async function pluginProbe(ctx, entry, authIndex) {
8
+ const provider = text(firstText(entry.quota_provider, entry.quotaProvider, entry.provider, entry.type));
9
+ const body = await management(ctx, "/v0/management/quota/fetch", {
10
+ method: "POST",
11
+ body: { auth_index: authIndex, ...(provider === "" ? {} : { provider }) },
12
+ });
13
+ if (!isObj(body)) throw new QuotaError("invalid-response");
14
+ return parsePluginQuota(body);
15
+ }
16
+
17
+ return pluginProbe;
18
+ }
@@ -0,0 +1,23 @@
1
+ // Update package identity, registries, channels, default preferences and package limits.
2
+
3
+ export const UPDATE_PACKAGE = "dsh-cliproxyapi-pro";
4
+ export const UPDATE_REGISTRIES = Object.freeze({
5
+ global: "https://registry.npmjs.org",
6
+ cn: "https://registry.npmmirror.com",
7
+ });
8
+ export const UPDATE_TAGS = Object.freeze({ stable: "latest", beta: "beta", dev: "dev" });
9
+ export const UPDATE_INTERVAL_MS = 6 * 60 * 60 * 1000;
10
+ export const DEFAULT_UPDATE_SETTINGS = Object.freeze({
11
+ autoCheck: true, autoDownload: false, autoInstall: false, channel: "stable", region: "auto",
12
+ });
13
+ export const BOOLEAN_SETTINGS = ["autoCheck", "autoDownload", "autoInstall"];
14
+ export const MAX_METADATA_BYTES = 512 * 1024;
15
+ export const MAX_PACKAGE_BYTES = 8 * 1024 * 1024;
16
+ export const MAX_UNPACKED_BYTES = 16 * 1024 * 1024;
17
+ export const MAX_PACKAGE_ENTRIES = 1000;
18
+ export const MAX_PATH_SEGMENTS = 6;
19
+ // Plain names only: no dotfiles, spaces, shell/glob characters or non-ASCII.
20
+ export const SAFE_SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9._-]{0,99}$/;
21
+ // npm packs these root files whether or not `files` lists them.
22
+ export const ALWAYS_PACKED = /^(?:package\.json|(?:README|LICEN[CS]E|NOTICE)(?:\.[A-Za-z0-9_-]+)*)$/i;
23
+ export const REQUIRED_FILES = ["package.json", "lib/index.js", "lib/client.js", "cordis.patch.yml", "locale/en.json", "locale/zh.json"];
@@ -0,0 +1,8 @@
1
+ // Update error type: page-facing codes plus log-only details.
2
+
3
+ export class UpdateError extends Error {
4
+ /** `detail` is a short diagnostic for logs only; the UI shows `code`. */
5
+ constructor(code, detail) { super(code); this.code = code; if (detail) this.detail = detail; }
6
+ }
7
+ export const fail = (code, detail) => { throw new UpdateError(code, detail); };
8
+ export const printable = (value) => String(value).replace(/[^\x20-\x7e]/g, "?").slice(0, 160);
@@ -0,0 +1,11 @@
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
+ // Barrel: the updater's public surface; the modules below stay internal.
4
+ export { DEFAULT_UPDATE_SETTINGS, UPDATE_INTERVAL_MS, UPDATE_PACKAGE, UPDATE_REGISTRIES, UPDATE_TAGS } from "./constants.js";
5
+ export { UpdateError } from "./errors.js";
6
+ export { loadUpdateSettings, normalizeUpdateSettings, saveUpdateSettings } from "./settings.js";
7
+ export { compareUpdateVersions, parseUpdateVersion } from "./version.js";
8
+ export { validateUpdateMetadata } from "./registry.js";
9
+ export { packageFilePatterns, verifyUpdatePackage } from "./verify.js";
10
+ export { createPluginUpdater } from "./updater.js";
11
+ export { storeUpdatePackage } from "./store.js";
@@ -0,0 +1,83 @@
1
+ // Registry metadata validation and bounded fetches with validated tarball redirects.
2
+ import { UPDATE_PACKAGE, UPDATE_TAGS } from "./constants.js";
3
+ import { fail } from "./errors.js";
4
+ import { parseUpdateVersion } from "./version.js";
5
+
6
+ export function integrityDigest(integrity) {
7
+ if (typeof integrity !== "string") fail("invalid-metadata");
8
+ const token = integrity.split(/\s+/).find((part) => /^sha512-[A-Za-z0-9+/]{86}==$/.test(part));
9
+ if (!token) fail("invalid-metadata");
10
+ const digest = Buffer.from(token.slice(7), "base64");
11
+ if (digest.length !== 64) fail("invalid-metadata");
12
+ return digest;
13
+ }
14
+
15
+ export function validateUpdateMetadata(raw, channel) {
16
+ if (!Object.hasOwn(UPDATE_TAGS, channel)) fail("invalid-metadata");
17
+ const parsed = parseUpdateVersion(raw?.version);
18
+ if (raw?.name !== UPDATE_PACKAGE || !parsed || channel === "stable" && parsed.pre.length) fail("invalid-metadata");
19
+ // Keep channels honest even if an upstream dist-tag is accidentally moved.
20
+ if (channel !== "stable" && parsed.pre.length && !parsed.pre.some((p) => p === channel)) fail("invalid-metadata");
21
+ let url;
22
+ try { url = new URL(raw?.dist?.tarball); } catch { fail("invalid-metadata"); }
23
+ const hosts = ["registry.npmjs.org", "registry.npmmirror.com"];
24
+ if (url.protocol !== "https:" || !hosts.includes(url.hostname) || url.port || url.username || url.password || url.search || url.hash) fail("invalid-metadata");
25
+ if (url.pathname !== `/${UPDATE_PACKAGE}/-/${UPDATE_PACKAGE}-${raw.version}.tgz`) fail("invalid-metadata");
26
+ integrityDigest(raw.dist.integrity);
27
+ return { version: raw.version, integrity: raw.dist.integrity };
28
+ }
29
+
30
+ async function readBounded(response, maxBytes) {
31
+ const declared = Number(response.headers.get("content-length"));
32
+ if (Number.isFinite(declared) && declared > maxBytes) { await response.body?.cancel(); fail("invalid-package"); }
33
+ const chunks = [];
34
+ let length = 0;
35
+ if (!response.body) fail("network-error");
36
+ const reader = response.body.getReader();
37
+ try {
38
+ while (true) {
39
+ const { done, value } = await reader.read();
40
+ if (done) break;
41
+ length += value.length;
42
+ if (length > maxBytes) { await reader.cancel(); fail("invalid-package"); }
43
+ chunks.push(Buffer.from(value));
44
+ }
45
+ } finally { reader.releaseLock(); }
46
+ return Buffer.concat(chunks, length);
47
+ }
48
+
49
+ function allowedDownloadUrl(value, version, region) {
50
+ let url;
51
+ try { url = new URL(value); } catch { fail("invalid-package"); }
52
+ if (url.protocol !== "https:" || url.port || url.username || url.password || url.search || url.hash) fail("invalid-package");
53
+ const registryPath = `/${UPDATE_PACKAGE}/-/${UPDATE_PACKAGE}-${version}.tgz`;
54
+ const cdnPath = `/packages/${UPDATE_PACKAGE}/${version}/${UPDATE_PACKAGE}-${version}.tgz`;
55
+ if (region === "global") {
56
+ if (url.hostname !== "registry.npmjs.org" || url.pathname !== registryPath) fail("invalid-package");
57
+ } else if (!(url.hostname === "registry.npmmirror.com" && url.pathname === registryPath ||
58
+ url.hostname === "cdn.npmmirror.com" && url.pathname === cdnPath)) fail("invalid-package");
59
+ return url.href;
60
+ }
61
+
62
+ export async function fetchBytes(fetcher, url, signal, limit, download = null) {
63
+ // npmmirror redirects tarballs to its official CDN. Follow only bounded,
64
+ // exact package/version URLs; never let fetch follow an unvalidated location.
65
+ for (let redirects = 0; ; redirects++) {
66
+ const response = await fetcher(url, {
67
+ signal, redirect: download ? "manual" : "error", credentials: "omit",
68
+ headers: { accept: "application/json, application/octet-stream" },
69
+ });
70
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
71
+ const location = response.headers.get("location");
72
+ await response.body?.cancel();
73
+ if (!download || redirects >= 3 || !location) fail("invalid-package");
74
+ let next;
75
+ try { next = new URL(location, url).href; } catch { fail("invalid-package"); }
76
+ url = allowedDownloadUrl(next, download.version, download.region);
77
+ continue;
78
+ }
79
+ if (response.status === 404) { await response.body?.cancel(); fail("channel-unavailable"); }
80
+ if (!response.ok) { await response.body?.cancel(); fail("network-error"); }
81
+ return readBounded(response, limit);
82
+ }
83
+ }
@@ -0,0 +1,45 @@
1
+ // Independent update preferences: normalization, tolerant load and atomic save.
2
+ import { randomUUID } from "node:crypto";
3
+ import { mkdirSync, readFileSync, renameSync, writeFileSync, unlinkSync } from "node:fs";
4
+ import { dirname } from "node:path";
5
+ import { BOOLEAN_SETTINGS, DEFAULT_UPDATE_SETTINGS, UPDATE_TAGS } from "./constants.js";
6
+ import { fail } from "./errors.js";
7
+
8
+ export function normalizeUpdateSettings(raw = {}) {
9
+ return {
10
+ autoCheck: typeof raw?.autoCheck === "boolean" ? raw.autoCheck : true,
11
+ autoDownload: raw?.autoDownload === true,
12
+ // Consumed by the Web client, which delegates installation to dshmarket.
13
+ autoInstall: raw?.autoInstall === true,
14
+ channel: Object.hasOwn(UPDATE_TAGS, raw?.channel ?? "") ? raw.channel : "stable",
15
+ region: ["auto", "global", "cn"].includes(raw?.region) ? raw.region : "auto",
16
+ };
17
+ }
18
+
19
+ export function loadUpdateSettings(file) {
20
+ try {
21
+ const raw = JSON.parse(readFileSync(file, "utf8"));
22
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) || raw.version !== 1 ||
23
+ BOOLEAN_SETTINGS.some((key) => raw[key] !== undefined && typeof raw[key] !== "boolean") ||
24
+ raw.channel !== undefined && !Object.hasOwn(UPDATE_TAGS, raw.channel) ||
25
+ raw.region !== undefined && !["auto", "global", "cn"].includes(raw.region)) fail("invalid-settings");
26
+ return normalizeUpdateSettings(raw);
27
+ }
28
+ catch (error) {
29
+ if (error.code === "ENOENT") return { ...DEFAULT_UPDATE_SETTINGS };
30
+ // Corrupt or unreadable settings must not silently enable network access.
31
+ return { ...DEFAULT_UPDATE_SETTINGS, autoCheck: false };
32
+ }
33
+ }
34
+
35
+ export function saveUpdateSettings(file, settings) {
36
+ const temporary = `${file}.${randomUUID()}.tmp`;
37
+ try {
38
+ mkdirSync(dirname(file), { recursive: true });
39
+ writeFileSync(temporary, `${JSON.stringify({ version: 1, ...normalizeUpdateSettings(settings) }, null, 2)}\n`, { mode: 0o600, flag: "wx" });
40
+ renameSync(temporary, file);
41
+ } catch {
42
+ try { unlinkSync(temporary); } catch {}
43
+ fail("storage-error");
44
+ }
45
+ }
@@ -0,0 +1,23 @@
1
+ // Atomic storage of a verified offline package; no extraction, install or profile edits.
2
+ import { randomUUID } from "node:crypto";
3
+ import { mkdirSync, renameSync, writeFileSync, unlinkSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { UPDATE_PACKAGE } from "./constants.js";
6
+ import { fail } from "./errors.js";
7
+ import { parseUpdateVersion } from "./version.js";
8
+
9
+ /** Atomic same-directory writes; no package extraction, install or profile edits. */
10
+ export function storeUpdatePackage(directory, version, bytes) {
11
+ if (!parseUpdateVersion(version)) fail("invalid-package");
12
+ const path = join(directory, `${UPDATE_PACKAGE}-${version}.tgz`);
13
+ const temporary = join(directory, `.${randomUUID()}.tmp`);
14
+ try {
15
+ mkdirSync(directory, { recursive: true });
16
+ writeFileSync(temporary, bytes, { flag: "wx", mode: 0o600 });
17
+ renameSync(temporary, path);
18
+ } catch {
19
+ try { unlinkSync(temporary); } catch {}
20
+ fail("storage-error");
21
+ }
22
+ return path;
23
+ }
@@ -0,0 +1,148 @@
1
+ // The plugin updater: checks with region racing, candidate generations, downloads and preferences.
2
+ import { BOOLEAN_SETTINGS, DEFAULT_UPDATE_SETTINGS, MAX_METADATA_BYTES, MAX_PACKAGE_BYTES, UPDATE_PACKAGE, UPDATE_REGISTRIES, UPDATE_TAGS } from "./constants.js";
3
+ import { UpdateError, fail } from "./errors.js";
4
+ import { fetchBytes, validateUpdateMetadata } from "./registry.js";
5
+ import { normalizeUpdateSettings } from "./settings.js";
6
+ import { verifyUpdatePackage } from "./verify.js";
7
+ import { compareUpdateVersions } from "./version.js";
8
+
9
+ function quotedArgument(value) {
10
+ // CLI examples must not turn local paths/profile names into shell syntax.
11
+ // Both PowerShell and POSIX shells accept single-quoted strings without apostrophes.
12
+ if (typeof value !== "string" || /['\r\n\0]/.test(value)) return null;
13
+ return `'${value}'`;
14
+ }
15
+
16
+ /** Injected I/O makes every update test offline and independent of the real profile. */
17
+ export function createPluginUpdater(deps) {
18
+ const fetcher = deps.fetch ?? globalThis.fetch;
19
+ const now = deps.now ?? (() => new Date().toISOString());
20
+ let settings = normalizeUpdateSettings(deps.readSettings());
21
+ let candidate = null;
22
+ let generation = 0;
23
+ let disposed = false;
24
+ let checkPromise = null;
25
+ let downloadPromise = null;
26
+ let saving = false;
27
+ const abort = new AbortController();
28
+ const initial = {
29
+ currentVersion: deps.currentVersion, latestVersion: null, available: false,
30
+ effectiveRegion: null, lastCheckedAt: null, error: null, errorCode: null,
31
+ downloadedVersion: null, downloadPath: null, upgradeCommand: null,
32
+ blockedReason: deps.linkedInstall ? "linked-install" : null,
33
+ };
34
+ let state = { ...initial };
35
+ const status = () => ({ ...state, ...settings, checking: checkPromise !== null, downloading: downloadPromise !== null });
36
+ const assertLive = () => { if (disposed) fail("disposed"); };
37
+ const recordError = (error) => {
38
+ const code = error instanceof UpdateError ? error.code : "network-error";
39
+ state.error = code;
40
+ state.errorCode = code;
41
+ // The page shows only the localized code; the concrete reason goes to the Host log.
42
+ if (error instanceof UpdateError && error.detail) deps.logger?.warn?.(`[dsh-cliproxyapi] update ${code}: ${error.detail}`);
43
+ };
44
+
45
+ const lookup = async (region, snapshot, signal) => {
46
+ const bytes = await fetchBytes(fetcher, `${UPDATE_REGISTRIES[region]}/${UPDATE_PACKAGE}/${UPDATE_TAGS[snapshot.channel]}`, signal, MAX_METADATA_BYTES);
47
+ let raw;
48
+ try { raw = JSON.parse(bytes.toString("utf8")); } catch { fail("invalid-metadata"); }
49
+ return { ...validateUpdateMetadata(raw, snapshot.channel), region };
50
+ };
51
+
52
+ const download = (version) => {
53
+ assertLive();
54
+ if (downloadPromise) return downloadPromise;
55
+ if (checkPromise || saving) fail("busy");
56
+ if (!candidate || !state.available || version !== candidate.version) fail("stale-version");
57
+ const selected = { ...candidate };
58
+ state.error = state.errorCode = null;
59
+ downloadPromise = Promise.resolve().then(async () => {
60
+ const signal = AbortSignal.any([abort.signal, AbortSignal.timeout(60_000)]);
61
+ const url = `${UPDATE_REGISTRIES[selected.region]}/${UPDATE_PACKAGE}/-/${UPDATE_PACKAGE}-${selected.version}.tgz`;
62
+ const bytes = await fetchBytes(fetcher, url, signal, MAX_PACKAGE_BYTES, selected);
63
+ assertLive();
64
+ verifyUpdatePackage(bytes, selected);
65
+ let path;
66
+ try { path = await deps.storePackage(selected.version, bytes); }
67
+ catch { fail("storage-error"); }
68
+ assertLive();
69
+ const profile = quotedArgument(deps.profileName);
70
+ const target = quotedArgument(path);
71
+ state.downloadedVersion = selected.version;
72
+ state.downloadPath = path;
73
+ state.upgradeCommand = !deps.linkedInstall && profile && target ? `dsh plugin --profile ${profile} add ${target}` : null;
74
+ }).catch((error) => {
75
+ recordError(error);
76
+ }).finally(() => { downloadPromise = null; }).then(status);
77
+ return downloadPromise;
78
+ };
79
+
80
+ const check = ({ automatic = false } = {}) => {
81
+ assertLive();
82
+ if (checkPromise) return checkPromise;
83
+ if (downloadPromise || saving) fail("busy");
84
+ if (automatic && !settings.autoCheck) return Promise.resolve(status());
85
+ const snapshot = { ...settings };
86
+ const revision = generation;
87
+ state.error = state.errorCode = null;
88
+ checkPromise = Promise.resolve().then(async () => {
89
+ const winnerAbort = new AbortController();
90
+ const signal = AbortSignal.any([abort.signal, winnerAbort.signal, AbortSignal.timeout(15_000)]);
91
+ let result;
92
+ try {
93
+ result = snapshot.region === "auto"
94
+ ? await Promise.any([lookup("global", snapshot, signal), lookup("cn", snapshot, signal)]).catch((error) => {
95
+ const failures = error.errors ?? [];
96
+ throw failures.find((e) => e.code === "invalid-metadata") ?? failures.find((e) => e.code === "channel-unavailable") ?? new UpdateError("network-error");
97
+ })
98
+ : await lookup(snapshot.region, snapshot, signal);
99
+ } finally { winnerAbort.abort(); }
100
+ assertLive();
101
+ if (revision !== generation) return;
102
+ candidate = result;
103
+ state.latestVersion = result.version;
104
+ state.available = compareUpdateVersions(result.version, deps.currentVersion) > 0;
105
+ state.effectiveRegion = result.region;
106
+ state.lastCheckedAt = now();
107
+ }).catch((error) => {
108
+ if (revision !== generation || disposed) return;
109
+ candidate = null;
110
+ state.available = false;
111
+ state.latestVersion = null;
112
+ state.lastCheckedAt = now();
113
+ recordError(error);
114
+ }).finally(() => { checkPromise = null; }).then(async () => {
115
+ if (!disposed && automatic && settings.autoCheck && settings.autoDownload && revision === generation && state.available && state.downloadedVersion !== candidate?.version) {
116
+ await download(candidate.version);
117
+ }
118
+ return status();
119
+ });
120
+ return checkPromise;
121
+ };
122
+
123
+ return {
124
+ status, check, download,
125
+ async save(patch = {}) {
126
+ assertLive();
127
+ if (checkPromise || downloadPromise || saving) fail("busy");
128
+ if (!patch || typeof patch !== "object" || Array.isArray(patch)) fail("invalid-settings");
129
+ if (Object.keys(patch).some((key) => !Object.hasOwn(DEFAULT_UPDATE_SETTINGS, key))) fail("invalid-settings");
130
+ if (Object.hasOwn(patch, "channel") && !Object.hasOwn(UPDATE_TAGS, patch.channel) || Object.hasOwn(patch, "region") && !["auto", "global", "cn"].includes(patch.region)) fail("invalid-settings");
131
+ for (const key of BOOLEAN_SETTINGS) if (Object.hasOwn(patch, key) && typeof patch[key] !== "boolean") fail("invalid-settings");
132
+ const next = normalizeUpdateSettings({ ...settings, ...patch });
133
+ saving = true;
134
+ try {
135
+ try { await deps.writeSettings(next); } catch { fail("storage-error"); }
136
+ assertLive();
137
+ const changedSource = next.channel !== settings.channel || next.region !== settings.region;
138
+ settings = next;
139
+ state.error = state.errorCode = null;
140
+ generation += 1;
141
+ if (changedSource) { candidate = null; state = { ...initial }; }
142
+ deps.onSettingsChanged?.(settings);
143
+ return status();
144
+ } finally { saving = false; }
145
+ },
146
+ dispose() { disposed = true; generation += 1; abort.abort(); },
147
+ };
148
+ }
@@ -0,0 +1,110 @@
1
+ // Package verification without extraction: SHA-512 integrity, gzip/tar structure and declared files.
2
+ import { createHash, timingSafeEqual } from "node:crypto";
3
+ import { gunzipSync } from "node:zlib";
4
+ import { ALWAYS_PACKED, MAX_PACKAGE_ENTRIES, MAX_PATH_SEGMENTS, MAX_UNPACKED_BYTES, REQUIRED_FILES, SAFE_SEGMENT, UPDATE_PACKAGE } from "./constants.js";
5
+ import { fail, printable } from "./errors.js";
6
+ import { integrityDigest } from "./registry.js";
7
+
8
+ /**
9
+ * Compile the package's own `files` field (npm semantics: a matched directory
10
+ * includes its contents, `*` stays within a segment, `**` spans segments).
11
+ * Negations only remove files from what npm packs, so they are ignored here;
12
+ * absolute or traversing patterns never match.
13
+ */
14
+ export function packageFilePatterns(files) {
15
+ if (!Array.isArray(files) || files.length === 0 || files.length > 200) fail("invalid-package", "package.json has no usable \"files\" list");
16
+ const patterns = [];
17
+ for (const raw of files) {
18
+ if (typeof raw !== "string") fail("invalid-package", "package.json \"files\" contains a non-string entry");
19
+ const pattern = raw.trim().replace(/^\.\//, "").replace(/\/+$/, "");
20
+ if (!pattern || pattern.startsWith("!") || pattern.startsWith("/") || pattern.includes("\\") ||
21
+ pattern.split("/").some((part) => part === "" || part === "." || part === "..")) continue;
22
+ const parts = pattern.split("/");
23
+ const body = parts.map((part, i) => {
24
+ const last = i === parts.length - 1;
25
+ if (part === "**") return last ? ".*" : "(?:[^/]+/)*";
26
+ return part.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]") + (last ? "" : "/");
27
+ }).join("");
28
+ patterns.push(new RegExp(`^${body}(?:/.*)?$`));
29
+ }
30
+ return patterns;
31
+ }
32
+
33
+ /**
34
+ * Validate checksum and a restricted npm tar archive without extracting any file.
35
+ * Which files may appear is not hard-coded: every regular file must be declared
36
+ * by the package's own `files` field (or be one npm always packs), so a future
37
+ * release can ship new files without this version rejecting it. Structural
38
+ * safety rules (paths, entry types, sizes, dependencies, scripts) are fixed.
39
+ */
40
+ export function verifyUpdatePackage(bytes, expected) {
41
+ const digest = createHash("sha512").update(bytes).digest();
42
+ if (!timingSafeEqual(digest, integrityDigest(expected.integrity))) fail("integrity-error");
43
+ let tar;
44
+ try { tar = gunzipSync(bytes, { maxOutputLength: MAX_UNPACKED_BYTES }); }
45
+ catch { fail("invalid-package", "not a gzip archive within the size limit"); }
46
+ const seen = new Set();
47
+ const files = [];
48
+ const directories = [];
49
+ let manifest;
50
+ let ended = false;
51
+ const text = (buffer) => buffer.toString("utf8").replace(/\0.*$/s, "");
52
+ for (let offset = 0; offset + 512 <= tar.length;) {
53
+ const header = tar.subarray(offset, offset + 512);
54
+ if (header.every((b) => b === 0)) {
55
+ if (tar.subarray(offset).some((b) => b !== 0)) fail("invalid-package", "data after the tar terminator");
56
+ ended = true;
57
+ break;
58
+ }
59
+ const octal = (buffer) => {
60
+ const value = text(buffer).trim();
61
+ if (!/^[0-7]+$/.test(value)) fail("invalid-package", "malformed tar header");
62
+ return parseInt(value, 8);
63
+ };
64
+ const size = octal(header.subarray(124, 136));
65
+ const checksum = octal(header.subarray(148, 156));
66
+ let sum = 0;
67
+ for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 32 : header[i];
68
+ if (sum !== checksum || size > MAX_UNPACKED_BYTES || offset + 512 + size > tar.length) fail("invalid-package", "corrupt tar entry");
69
+ const prefix = text(header.subarray(345, 500));
70
+ const path = `${prefix ? `${prefix}/` : ""}${text(header.subarray(0, 100))}`;
71
+ const type = header[156];
72
+ const directory = type === 53;
73
+ let relative = path.startsWith("package/") ? path.slice(8) : null;
74
+ if (directory && relative?.endsWith("/")) relative = relative.slice(0, -1);
75
+ const parts = relative?.split("/") ?? [];
76
+ if (relative === null || (relative !== "" || !directory) && (parts.length > MAX_PATH_SEGMENTS ||
77
+ parts.some((part) => !SAFE_SEGMENT.test(part) || part === "node_modules")) || seen.has(path)) {
78
+ fail("invalid-package", `unsafe path ${printable(path)}`);
79
+ }
80
+ seen.add(path);
81
+ if (seen.size > MAX_PACKAGE_ENTRIES) fail("invalid-package", "too many entries");
82
+ if (directory) {
83
+ if (size !== 0) fail("invalid-package", `non-empty directory entry ${printable(path)}`);
84
+ directories.push(relative);
85
+ } else if (type === 0 || type === 48) {
86
+ files.push(relative);
87
+ if (relative === "package.json") {
88
+ try { manifest = JSON.parse(tar.subarray(offset + 512, offset + 512 + size).toString("utf8")); }
89
+ catch { fail("invalid-package", "package.json is not valid JSON"); }
90
+ }
91
+ } else fail("invalid-package", `link or special entry ${printable(path)}`);
92
+ offset += 512 + Math.ceil(size / 512) * 512;
93
+ }
94
+ if (!ended) fail("invalid-package", "missing tar terminator");
95
+ const missing = REQUIRED_FILES.find((p) => !files.includes(p));
96
+ if (missing) fail("invalid-package", `missing ${missing}`);
97
+ if (!manifest || typeof manifest !== "object" || Array.isArray(manifest) || manifest.name !== UPDATE_PACKAGE ||
98
+ manifest.version !== expected.version || manifest.dsh?.bundle?.patch !== "./cordis.patch.yml") {
99
+ fail("invalid-package", "package.json does not describe this plugin version");
100
+ }
101
+ if (["dependencies", "optionalDependencies", "bundledDependencies", "bundleDependencies"].some((key) => manifest[key] && Object.keys(manifest[key]).length)) fail("invalid-package", "declares dependencies");
102
+ const script = Object.keys(manifest.scripts ?? {}).find((key) => /^(?:preinstall|install|postinstall|prepare|prepublish|prepublishOnly|prepack|postpack)$/.test(key));
103
+ if (script) fail("invalid-package", `declares lifecycle script ${printable(script)}`);
104
+ const patterns = packageFilePatterns(manifest.files);
105
+ const undeclared = files.find((file) => !(!file.includes("/") && ALWAYS_PACKED.test(file)) && !patterns.some((re) => re.test(file)));
106
+ if (undeclared) fail("invalid-package", `file not declared in package.json "files": ${printable(undeclared)}`);
107
+ const stray = directories.find((dir) => dir !== "" && !files.some((file) => file.startsWith(`${dir}/`)));
108
+ if (stray !== undefined) fail("invalid-package", `directory without files ${printable(stray)}`);
109
+ return manifest;
110
+ }
@@ -0,0 +1,31 @@
1
+ // Strict SemVer parsing and precedence for update candidates.
2
+ import { fail } from "./errors.js";
3
+
4
+ // Strict SemVer, including prerelease precedence. Never reuse model-name sorting.
5
+ export function parseUpdateVersion(value) {
6
+ if (typeof value !== "string" || value.length > 128) return null;
7
+ 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);
8
+ if (!match) return null;
9
+ const parts = match.slice(1, 4).map(Number);
10
+ if (parts.some((n) => !Number.isSafeInteger(n))) return null;
11
+ const pre = match[4]?.split(".") ?? [];
12
+ if (pre.some((p) => /^\d+$/.test(p) && (p.length > 1 && p.startsWith("0") || !Number.isSafeInteger(Number(p))))) return null;
13
+ return { parts, pre };
14
+ }
15
+
16
+ export function compareUpdateVersions(a, b) {
17
+ const x = parseUpdateVersion(a), y = parseUpdateVersion(b);
18
+ if (!x || !y) fail("invalid-metadata");
19
+ for (let i = 0; i < 3; i++) if (x.parts[i] !== y.parts[i]) return x.parts[i] > y.parts[i] ? 1 : -1;
20
+ if (!x.pre.length || !y.pre.length) return x.pre.length ? -1 : y.pre.length ? 1 : 0;
21
+ for (let i = 0; i < Math.max(x.pre.length, y.pre.length); i++) {
22
+ if (x.pre[i] === undefined || y.pre[i] === undefined) return x.pre[i] === undefined ? -1 : 1;
23
+ const p = x.pre[i], q = y.pre[i];
24
+ if (p === q) continue;
25
+ const pn = /^\d+$/.test(p), qn = /^\d+$/.test(q);
26
+ if (pn && qn) return Number(p) > Number(q) ? 1 : -1;
27
+ if (pn !== qn) return pn ? -1 : 1;
28
+ return p > q ? 1 : -1;
29
+ }
30
+ return 0;
31
+ }