dsh-crate 0.0.0-stage → 0.5.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 (132) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +288 -2
  3. package/README.zh.md +263 -0
  4. package/UPDATE-API-V1.md +207 -0
  5. package/assets/logo.svg +37 -0
  6. package/client/client.js +18964 -0
  7. package/cordis.patch.yml +4 -0
  8. package/lib/accelerate.js +194 -0
  9. package/lib/agents.js +67 -0
  10. package/lib/backup.js +688 -0
  11. package/lib/body-progress.js +173 -0
  12. package/lib/catalog-local-match.js +160 -0
  13. package/lib/catalog-npm.js +180 -0
  14. package/lib/changelog.js +462 -0
  15. package/lib/channels.js +64 -0
  16. package/lib/check.js +1557 -0
  17. package/lib/compatibility.js +243 -0
  18. package/lib/crate-catalog.js +179 -0
  19. package/lib/diagnostics.js +49 -0
  20. package/lib/discovery-compatibility.js +447 -0
  21. package/lib/drain-journal.js +164 -0
  22. package/lib/drain.js +1043 -0
  23. package/lib/dsh-cli.js +1373 -0
  24. package/lib/dsh-install.js +259 -0
  25. package/lib/entry-identity.js +85 -0
  26. package/lib/gist.js +369 -0
  27. package/lib/groups.js +108 -0
  28. package/lib/home-paths.js +29 -0
  29. package/lib/host-recovery.js +187 -0
  30. package/lib/hot.js +871 -0
  31. package/lib/http.js +252 -0
  32. package/lib/index.js +394 -0
  33. package/lib/install.js +1147 -0
  34. package/lib/lifecycle.js +37 -0
  35. package/lib/log-redaction.js +24 -0
  36. package/lib/log.js +204 -0
  37. package/lib/ndjson.js +154 -0
  38. package/lib/net.js +174 -0
  39. package/lib/official-desktop.js +619 -0
  40. package/lib/order.js +284 -0
  41. package/lib/patch.js +943 -0
  42. package/lib/pending-rows.js +142 -0
  43. package/lib/pending-updates.js +346 -0
  44. package/lib/pnpm-compat.js +972 -0
  45. package/lib/presets.js +282 -0
  46. package/lib/probe-context.js +20 -0
  47. package/lib/proc-text.js +69 -0
  48. package/lib/profile.js +1978 -0
  49. package/lib/recovery.js +1059 -0
  50. package/lib/region-probe.js +93 -0
  51. package/lib/regions.js +283 -0
  52. package/lib/registry.js +308 -0
  53. package/lib/release-candidates.js +115 -0
  54. package/lib/release-updates.js +70 -0
  55. package/lib/restart.js +688 -0
  56. package/lib/routes.js +7960 -0
  57. package/lib/settings.js +164 -0
  58. package/lib/shelfry-catalog.js +179 -0
  59. package/lib/snapshot.js +506 -0
  60. package/lib/source-migration.js +164 -0
  61. package/lib/sources.js +1005 -0
  62. package/lib/state.js +38 -0
  63. package/lib/store.js +163 -0
  64. package/lib/themes.js +350 -0
  65. package/lib/trial.js +125 -0
  66. package/lib/types/accelerate.d.ts +85 -0
  67. package/lib/types/agents.d.ts +52 -0
  68. package/lib/types/backup.d.ts +171 -0
  69. package/lib/types/body-progress.d.ts +94 -0
  70. package/lib/types/catalog-local-match.d.ts +39 -0
  71. package/lib/types/catalog-npm.d.ts +77 -0
  72. package/lib/types/changelog.d.ts +131 -0
  73. package/lib/types/channels.d.ts +56 -0
  74. package/lib/types/check.d.ts +353 -0
  75. package/lib/types/compatibility.d.ts +83 -0
  76. package/lib/types/crate-catalog.d.ts +48 -0
  77. package/lib/types/diagnostics.d.ts +29 -0
  78. package/lib/types/discovery-compatibility.d.ts +145 -0
  79. package/lib/types/drain-journal.d.ts +25 -0
  80. package/lib/types/drain.d.ts +306 -0
  81. package/lib/types/dsh-cli.d.ts +481 -0
  82. package/lib/types/dsh-install.d.ts +106 -0
  83. package/lib/types/entry-identity.d.ts +68 -0
  84. package/lib/types/gist.d.ts +79 -0
  85. package/lib/types/groups.d.ts +34 -0
  86. package/lib/types/home-paths.d.ts +13 -0
  87. package/lib/types/host-recovery.d.ts +95 -0
  88. package/lib/types/hot.d.ts +405 -0
  89. package/lib/types/http.d.ts +114 -0
  90. package/lib/types/index.d.ts +52 -0
  91. package/lib/types/install.d.ts +463 -0
  92. package/lib/types/lifecycle.d.ts +14 -0
  93. package/lib/types/log-redaction.d.ts +2 -0
  94. package/lib/types/log.d.ts +43 -0
  95. package/lib/types/ndjson.d.ts +52 -0
  96. package/lib/types/net.d.ts +94 -0
  97. package/lib/types/official-desktop.d.ts +59 -0
  98. package/lib/types/order.d.ts +100 -0
  99. package/lib/types/patch.d.ts +218 -0
  100. package/lib/types/pending-rows.d.ts +81 -0
  101. package/lib/types/pending-updates.d.ts +161 -0
  102. package/lib/types/pnpm-compat.d.ts +102 -0
  103. package/lib/types/presets.d.ts +94 -0
  104. package/lib/types/probe-context.d.ts +14 -0
  105. package/lib/types/proc-text.d.ts +29 -0
  106. package/lib/types/profile.d.ts +551 -0
  107. package/lib/types/recovery.d.ts +342 -0
  108. package/lib/types/region-probe.d.ts +50 -0
  109. package/lib/types/regions.d.ts +134 -0
  110. package/lib/types/registry.d.ts +160 -0
  111. package/lib/types/release-candidates.d.ts +42 -0
  112. package/lib/types/release-updates.d.ts +15 -0
  113. package/lib/types/restart.d.ts +279 -0
  114. package/lib/types/routes.d.ts +130 -0
  115. package/lib/types/settings.d.ts +112 -0
  116. package/lib/types/shelfry-catalog.d.ts +48 -0
  117. package/lib/types/snapshot.d.ts +93 -0
  118. package/lib/types/source-migration.d.ts +100 -0
  119. package/lib/types/sources.d.ts +391 -0
  120. package/lib/types/state.d.ts +20 -0
  121. package/lib/types/store.d.ts +47 -0
  122. package/lib/types/themes.d.ts +46 -0
  123. package/lib/types/trial.d.ts +61 -0
  124. package/lib/types/update-api-v1.d.ts +83 -0
  125. package/lib/types/updates.d.ts +273 -0
  126. package/lib/types/verify.d.ts +277 -0
  127. package/lib/update-api-v1.js +273 -0
  128. package/lib/updates.js +981 -0
  129. package/lib/verify.js +904 -0
  130. package/locale/en.json +5 -0
  131. package/locale/zh.json +6 -0
  132. package/package.json +113 -4
package/lib/backup.js ADDED
@@ -0,0 +1,688 @@
1
+ /**
2
+ * Portable profile backups: configuration only, never installed packages.
3
+ *
4
+ * The profile directory is plain user data — aside from package.json it can
5
+ * hold API keys (config.toml), tokens, or the WebDAV password when stored
6
+ * server-side. Backups therefore behave like `dsh export` and carry the same
7
+ * credential-warning disclaimer in the UI (review #63).
8
+ */
9
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
10
+ import { lookup } from 'node:dns/promises';
11
+ import { request as httpsRequest } from 'node:https';
12
+ import { isIP } from 'node:net';
13
+ import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
14
+ import { profileDir } from './profile.js';
15
+ export const BACKUP_FORMAT = 'dsh-profile-backup';
16
+ export const MAX_BACKUP_BYTES = 2 * 1024 * 1024;
17
+ const MAX_FILES = 256;
18
+ const SKIP_NAMES = new Set(['node_modules', '.dsh-crate', '.dsh-shelfry', '.git', 'pnpm-lock.yaml']);
19
+ /**
20
+ * Directories that are caches by name, wherever they sit.
21
+ *
22
+ * The market's own cache is `.dsh-crate` (skipped above), but another
23
+ * component writes `<profile>/cache` — not hidden, so the dot rule below let
24
+ * it through and the whole thing was read as configuration. With a few
25
+ * multi-megabyte json files in there the profile could not be backed up at
26
+ * all, and the error blamed the profile's own configuration (#1064).
27
+ *
28
+ * Only the exporter skips these; `validatedBackup` still accepts a document
29
+ * that carries them, because backups written before this rule put them in.
30
+ */
31
+ const SKIP_DIRS = new Set(['cache']);
32
+ /**
33
+ * Said when the profile does not fit: the way out has to be one that works.
34
+ *
35
+ * The old sentence offered "只导出选中的插件" unconditionally, but that path
36
+ * walks the same profile once "包含配置文件" is ticked and fails with the
37
+ * same words (#1064) — so it now names the trap as well.
38
+ */
39
+ const EXPORT_SELECTED_ZH = '可以改成只导出选中的插件,并且别勾「包含配置文件」,那会撞同一个上限';
40
+ const EXPORT_SELECTED_EN = 'export selected plugins instead, and leave "Include config files" unticked — ticking it hits the same cap';
41
+ const BACKUP_TOO_LARGE = `这个 profile 的配置超过 ${MAX_BACKUP_BYTES / (1024 * 1024)} MB,整份备份放不下。${EXPORT_SELECTED_ZH}。 / this profile's configuration is larger than ${MAX_BACKUP_BYTES / (1024 * 1024)} MB, which is too much for one whole-profile backup; ${EXPORT_SELECTED_EN}.`;
42
+ /** File names that routinely contain credentials (backup exports).
43
+ * Values are never masked in place — the export is one-to-one for
44
+ * faithful restores — but presence is surfaced by the UI warning. */
45
+ export const SECRET_FILE_HINTS = /(^|\/)(config\.toml|\.env(\.\w+)?|secrets?\.\w+t?j?s?o?n|pnpm-workspace\.yaml)$/i;
46
+ /** Count of exported files whose names look like they carry credentials. */
47
+ export function secretFileCount(profile, explicitDir) {
48
+ let count = 0;
49
+ for (const path of profileFiles(explicitDir ?? profileDir(profile))) {
50
+ if (SECRET_FILE_HINTS.test(path))
51
+ count += 1;
52
+ }
53
+ return count;
54
+ }
55
+ function profileFiles(root, dir = root) {
56
+ const files = [];
57
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
58
+ // Any .bak marker, not just the numeric-suffixed one this codebase
59
+ // writes. Recovery and the host's own repair paths leave other shapes —
60
+ // `package.json.bak-asm`, `cordis.patch.yml.rp-merged.bak` — and a
61
+ // backup that carried them restored them too, so the profile came back
62
+ // with the wreckage that made it need repairing (#205 by @Rudyy898).
63
+ if (SKIP_NAMES.has(entry.name) || /\.bak\b/.test(entry.name))
64
+ continue;
65
+ // Plugin caches live in hidden directories (`.dsh-mattskillsdeck-cache`,
66
+ // `.plugin-manager`, …). Walking them counted megabytes of logs as
67
+ // "configuration" and blew the 2 MB cap (#972). Hidden FILES stay —
68
+ // `.env` and `.npmrc` are real profile config.
69
+ if (entry.isDirectory() && entry.name.startsWith('.'))
70
+ continue;
71
+ // Same rule, one name the dot check cannot cover (#1064).
72
+ if (entry.isDirectory() && SKIP_DIRS.has(entry.name))
73
+ continue;
74
+ const path = resolve(dir, entry.name);
75
+ if (entry.isSymbolicLink())
76
+ continue;
77
+ if (entry.isDirectory())
78
+ files.push(...profileFiles(root, path));
79
+ else if (entry.isFile())
80
+ files.push(relative(root, path).split(sep).join('/'));
81
+ // Told in the user's words, with the way out: this is the cap a heavy
82
+ // profile actually hits, and the per-plugin export is the answer.
83
+ if (files.length > MAX_FILES) {
84
+ throw new Error(`这个 profile 的配置文件超过 ${MAX_FILES} 个,整份备份放不下。${EXPORT_SELECTED_ZH}。 / this profile has more than ${MAX_FILES} configuration files, which is too many for one whole-profile backup; ${EXPORT_SELECTED_EN}.`);
85
+ }
86
+ }
87
+ return files;
88
+ }
89
+ /**
90
+ * Serialize every profile file except dependencies, lock state, and market
91
+ * cache — or, with {@link BackupOptions.includeDeps}, only the manifest with
92
+ * the selected plugins (plus, optionally, the other config files).
93
+ */
94
+ export function createProfileBackup(profile, explicitDir, opts) {
95
+ const root = resolve(explicitDir ?? profileDir(profile));
96
+ const manifestFile = resolve(root, 'package.json');
97
+ if (!existsSync(manifestFile))
98
+ throw new Error('profile package.json is missing');
99
+ const manifest = JSON.parse(readFileSync(manifestFile, 'utf8'));
100
+ if (opts?.includeDeps !== undefined) {
101
+ const include = new Set(opts.includeDeps);
102
+ if (include.size === 0)
103
+ throw new Error('no plugins selected');
104
+ const dependencies = manifest.dependencies === null || typeof manifest.dependencies !== 'object' || Array.isArray(manifest.dependencies)
105
+ ? {}
106
+ : manifest.dependencies;
107
+ const filteredDeps = {};
108
+ for (const [name, spec] of Object.entries(dependencies))
109
+ if (include.has(name))
110
+ filteredDeps[name] = spec;
111
+ const dsh = manifest.dsh === null || typeof manifest.dsh !== 'object' || Array.isArray(manifest.dsh)
112
+ ? undefined
113
+ : manifest.dsh;
114
+ const profileBlock = dsh?.profile === null || typeof dsh?.profile !== 'object' || Array.isArray(dsh?.profile)
115
+ ? undefined
116
+ : dsh.profile;
117
+ const bundles = Array.isArray(profileBlock?.bundles) ? profileBlock.bundles : [];
118
+ const filteredBundles = bundles.filter((name) => typeof name === 'string' && include.has(name));
119
+ if (Object.keys(filteredDeps).length === 0 && filteredBundles.length === 0) {
120
+ throw new Error('none of the selected plugins are in this profile');
121
+ }
122
+ const filteredManifest = { ...manifest };
123
+ filteredManifest.dependencies = filteredDeps;
124
+ if (dsh !== undefined) {
125
+ filteredManifest.dsh = { ...dsh, profile: { ...(profileBlock ?? {}), bundles: filteredBundles } };
126
+ }
127
+ const files = [{ path: 'package.json', json: filteredManifest }];
128
+ if (opts.includeConfig === true) {
129
+ for (const path of profileFiles(root).sort()) {
130
+ if (path === 'package.json')
131
+ continue;
132
+ files.push({ path, lines: readFileSync(resolve(root, path), 'utf8').split(/\r?\n/) });
133
+ }
134
+ }
135
+ const partial = { format: BACKUP_FORMAT, version: 0.2, createdAt: new Date().toISOString(), profile, files };
136
+ if (Buffer.byteLength(JSON.stringify(partial)) > MAX_BACKUP_BYTES)
137
+ throw new Error(BACKUP_TOO_LARGE);
138
+ return partial;
139
+ }
140
+ const files = profileFiles(root).sort().map((path) => {
141
+ const content = readFileSync(resolve(root, path), 'utf8');
142
+ return path === 'package.json'
143
+ ? { path, json: JSON.parse(content) }
144
+ : { path, lines: content.split(/\r?\n/) };
145
+ });
146
+ if (!files.some(file => file.path === 'package.json'))
147
+ throw new Error('profile package.json is missing');
148
+ const backup = { format: BACKUP_FORMAT, version: 0.2, createdAt: new Date().toISOString(), profile, files };
149
+ if (Buffer.byteLength(JSON.stringify(backup)) > MAX_BACKUP_BYTES)
150
+ throw new Error(BACKUP_TOO_LARGE);
151
+ return backup;
152
+ }
153
+ export function validatedBackup(value) {
154
+ if (value === null || typeof value !== 'object')
155
+ throw new Error('invalid backup');
156
+ const backup = value;
157
+ if (backup.format !== BACKUP_FORMAT || backup.version !== 0.2 || !Array.isArray(backup.files)) {
158
+ throw new Error('unsupported backup format');
159
+ }
160
+ if (backup.files.length > MAX_FILES)
161
+ throw new Error('invalid backup contents');
162
+ const files = [];
163
+ const paths = new Set();
164
+ for (const value of backup.files) {
165
+ if (value === null || typeof value !== 'object')
166
+ throw new Error('invalid backup contents');
167
+ const file = value;
168
+ const path = file.path;
169
+ if (typeof path !== 'string')
170
+ throw new Error('invalid backup contents');
171
+ if (path === '' || isAbsolute(path) || path.split(/[\\/]/).includes('..'))
172
+ throw new Error(`unsafe backup path: ${path}`);
173
+ const normalized = path.replaceAll('\\', '/');
174
+ const parts = normalized.split('/');
175
+ if (parts.some(part => SKIP_NAMES.has(part)))
176
+ throw new Error(`excluded backup path: ${path}`);
177
+ // Official exports before #972 carried plugin cache/log dirs whenever
178
+ // they still fit under 2 MB. Those files are not configuration; dropping
179
+ // them keeps the rest of the backup restorable. Names this exporter has
180
+ // never written (SKIP_NAMES) still refuse the document.
181
+ if (parts.some((part, index) => part.startsWith('.') && index < parts.length - 1))
182
+ continue;
183
+ if (paths.has(normalized))
184
+ throw new Error(`duplicate backup path: ${path}`);
185
+ paths.add(normalized);
186
+ if (path === 'package.json') {
187
+ if (file.json === null || typeof file.json !== 'object' || Array.isArray(file.json))
188
+ throw new Error('backup package.json is invalid');
189
+ files.push({ path, json: file.json });
190
+ }
191
+ else {
192
+ if (!Array.isArray(file.lines) || !file.lines.every(line => typeof line === 'string'))
193
+ throw new Error(`invalid file content: ${path}`);
194
+ files.push({ path, lines: file.lines });
195
+ }
196
+ }
197
+ if (!files.some(file => file.path === 'package.json'))
198
+ throw new Error('invalid backup contents');
199
+ if (Buffer.byteLength(JSON.stringify(backup)) > MAX_BACKUP_BYTES)
200
+ throw new Error('backup is too large');
201
+ return { ...backup, files };
202
+ }
203
+ /** Atomically overwrite backed-up files and return a rollback for install failure. */
204
+ export function restoreProfileBackup(profile, value, explicitDir) {
205
+ const backup = validatedBackup(value);
206
+ const root = resolve(explicitDir ?? profileDir(profile));
207
+ const previous = new Map();
208
+ mkdirSync(root, { recursive: true });
209
+ const rollback = () => {
210
+ for (const [target, content] of previous) {
211
+ if (content === null)
212
+ rmSync(target, { force: true });
213
+ else
214
+ writeFileSync(target, content);
215
+ }
216
+ };
217
+ try {
218
+ for (const file of backup.files) {
219
+ const { path } = file;
220
+ const target = resolve(root, path);
221
+ if (!target.startsWith(root + sep))
222
+ throw new Error(`unsafe backup path: ${path}`);
223
+ ensureSafeParent(root, dirname(target), path);
224
+ if (existsSync(target) && !lstatSync(target).isFile())
225
+ throw new Error(`backup path is not a file: ${path}`);
226
+ previous.set(target, existsSync(target) ? readFileSync(target) : null);
227
+ const temp = `${target}.dsh-restore-${String(process.pid)}`;
228
+ writeFileSync(temp, 'json' in file ? `${JSON.stringify(file.json, null, 2)}\n` : file.lines.join('\n'), 'utf8');
229
+ renameSync(temp, target);
230
+ }
231
+ }
232
+ catch (error) {
233
+ rollback();
234
+ throw error;
235
+ }
236
+ return {
237
+ files: previous.size,
238
+ rollback,
239
+ };
240
+ }
241
+ /** Create missing parents one level at a time and refuse existing symlinks. */
242
+ function ensureSafeParent(root, parent, backupPath) {
243
+ const relativeParent = relative(root, parent);
244
+ if (relativeParent === '')
245
+ return;
246
+ let current = root;
247
+ for (const part of relativeParent.split(sep)) {
248
+ current = resolve(current, part);
249
+ if (!existsSync(current)) {
250
+ mkdirSync(current);
251
+ continue;
252
+ }
253
+ const stat = lstatSync(current);
254
+ if (stat.isSymbolicLink() || !stat.isDirectory())
255
+ throw new Error(`unsafe backup path: ${backupPath}`);
256
+ }
257
+ }
258
+ async function webdavRequest(url, username, password, method, body) {
259
+ const parsed = new URL(url);
260
+ // SSRF hardening (review #63): https-only by default, and always refuse
261
+ // private/link-local targets — so a same-origin script cannot tunnel into
262
+ // the host network. Besides the obvious metadata surfaces (169.254.169.254),
263
+ // loopback matters because other services on this machine may expose HTTP
264
+ // APIs of their own.
265
+ if (parsed.protocol === 'http:')
266
+ throw new Error('WebDAV requires an https:// URL');
267
+ if (parsed.protocol !== 'https:')
268
+ throw new WebdavUrlError('webdav_bad_url', 'invalid WebDAV URL');
269
+ if (parsed.username !== '' || parsed.password !== '')
270
+ throw new WebdavUrlError('webdav_bad_url', 'invalid WebDAV URL');
271
+ const address = await resolvePublicAddress(parsed.hostname);
272
+ const headers = { host: parsed.host };
273
+ if (body !== undefined) {
274
+ headers['content-type'] = 'application/json';
275
+ headers['content-length'] = String(Buffer.byteLength(body));
276
+ }
277
+ if (username !== '')
278
+ headers.authorization = `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`;
279
+ // Connect to the address that was checked above instead of resolving the
280
+ // hostname a second time. This closes the DNS-rebinding window between the
281
+ // allow/deny decision and the actual socket connection.
282
+ return await new Promise((resolveRequest, reject) => {
283
+ const originalHostname = unbracketedHostname(parsed.hostname);
284
+ const request = httpsRequest({
285
+ protocol: 'https:',
286
+ hostname: address.address,
287
+ family: address.family,
288
+ port: parsed.port === '' ? 443 : Number(parsed.port),
289
+ path: `${parsed.pathname}${parsed.search}`,
290
+ method,
291
+ headers,
292
+ servername: isIP(originalHostname) === 0 ? originalHostname : undefined,
293
+ signal: AbortSignal.timeout(30_000),
294
+ }, (response) => {
295
+ const chunks = [];
296
+ let size = 0;
297
+ const maxBytes = method === 'GET' ? MAX_BACKUP_BYTES : 64 * 1024;
298
+ response.once('error', reject);
299
+ const declared = Number(response.headers['content-length']);
300
+ if (Number.isFinite(declared) && declared > maxBytes) {
301
+ response.destroy(new Error('WebDAV response is too large'));
302
+ return;
303
+ }
304
+ response.on('data', (chunk) => {
305
+ const value = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
306
+ size += value.byteLength;
307
+ if (size > maxBytes) {
308
+ response.destroy(new Error('WebDAV response is too large'));
309
+ return;
310
+ }
311
+ chunks.push(value);
312
+ });
313
+ response.once('end', () => resolveRequest({
314
+ status: response.statusCode ?? 0,
315
+ body: Buffer.concat(chunks),
316
+ ...(typeof response.headers.location === 'string' ? { location: response.headers.location } : {}),
317
+ }));
318
+ });
319
+ request.once('error', reject);
320
+ request.end(body);
321
+ });
322
+ }
323
+ /**
324
+ * Ancestor collection URLs of a WebDAV file, outermost first.
325
+ * `https://dav.example/a/b/x.json` → [`https://dav.example/a/`, `https://dav.example/a/b/`].
326
+ * The server root itself is never included — it always exists, and some
327
+ * providers reject MKCOL on it.
328
+ */
329
+ export function webdavParentCollections(url) {
330
+ let parsed;
331
+ try {
332
+ parsed = new URL(url);
333
+ }
334
+ catch {
335
+ return [];
336
+ }
337
+ const parts = parsed.pathname.split('/').filter(part => part !== '');
338
+ parts.pop(); // the file itself
339
+ const collections = [];
340
+ let path = '';
341
+ for (const part of parts) {
342
+ path += `/${part}`;
343
+ collections.push(`${parsed.origin}${path}/`);
344
+ }
345
+ return collections;
346
+ }
347
+ /**
348
+ * Upload the backup, creating missing parent collections first (#102).
349
+ *
350
+ * WebDAV servers do not create intermediate collections implicitly, so a PUT
351
+ * into a folder that does not exist yet fails — Jianguoyun answers 404, which
352
+ * read as "sync is broken" rather than "make the folder first". MKCOL on an
353
+ * existing collection answers 405, which is success for our purposes; any
354
+ * other failure is left to the PUT to report, since some providers restrict
355
+ * MKCOL while still accepting the upload.
356
+ */
357
+ export async function uploadWebdav(url, username, password, backup) {
358
+ for (const collection of webdavParentCollections(url)) {
359
+ try {
360
+ await webdavRequest(collection, username, password, 'MKCOL');
361
+ }
362
+ catch { /* fall through: the PUT below reports the real problem */ }
363
+ }
364
+ const response = await webdavRequest(url, username, password, 'PUT', JSON.stringify(backup));
365
+ if (response.status < 200 || response.status >= 300) {
366
+ throw new Error(describeUploadFailure(response.status));
367
+ }
368
+ }
369
+ /**
370
+ * What an upload failure means, in the three things a report needs (#1058).
371
+ *
372
+ * A bare `HTTP 401` is the worst of them: it is by far the most common
373
+ * answer, it happens for a reason the user can fix in one field, and the
374
+ * message said nothing about either. The password is deliberately never
375
+ * stored, so "re-entered after a page reload" is the ordinary cause, not an
376
+ * edge case.
377
+ *
378
+ * @param status - the HTTP status the PUT answered with.
379
+ * @returns a bilingual sentence: what happened, why, and what to do.
380
+ */
381
+ function describeUploadFailure(status) {
382
+ if (status === 401) {
383
+ return 'WebDAV 上传被拒绝(HTTP 401):服务端不认这个用户名或密码。密码不会保存到磁盘,刷新页面或重启后需要重新输入;填好后点「上传备份」重试。 / The WebDAV server rejected these credentials (HTTP 401). The password is never stored, so it has to be entered again after a reload or restart; fill it in and press Upload backup.';
384
+ }
385
+ if (status === 403) {
386
+ return 'WebDAV 上传被拒绝(HTTP 403):凭据有效,但这个账号没有写入该路径的权限。换一个可写的目录,或检查服务商的权限设置。 / The WebDAV server refused the write (HTTP 403): the credentials are valid but this account cannot write to that path. Use a writable folder, or check the provider\'s permissions.';
387
+ }
388
+ if (status === 404) {
389
+ return 'WebDAV upload failed: HTTP 404 — the target folder does not exist and could not be created. Some providers (e.g. Jianguoyun) refuse files at the root: use a path inside a folder, e.g. https://dav.example.com/dsh/backup.json / 目标目录不存在且无法自动创建;部分服务商(如坚果云)不允许在根目录放文件,请使用形如 https://dav.example.com/dsh/backup.json 的子目录路径';
390
+ }
391
+ return `WebDAV upload failed: HTTP ${status}`;
392
+ }
393
+ /** Refuse non-global IPv4 targets, including metadata and carrier NAT ranges. */
394
+ export function isPublicIpv4(ip) {
395
+ const octets = ip.split('.').map(Number);
396
+ if (octets.length !== 4 || octets.some(part => !Number.isInteger(part) || part < 0 || part > 255))
397
+ return false;
398
+ const [a, b] = octets;
399
+ if (a === 0 || a === 10 || a === 127 || a >= 224)
400
+ return false;
401
+ if (a === 100 && b >= 64 && b <= 127)
402
+ return false;
403
+ if (a === 169 && b === 254)
404
+ return false;
405
+ if (a === 172 && b >= 16 && b <= 31)
406
+ return false;
407
+ if (a === 192 && (b === 0 || b === 168))
408
+ return false;
409
+ if (a === 198 && (b === 18 || b === 19))
410
+ return false;
411
+ return true;
412
+ }
413
+ /** Only public internet target hostnames are reachable for WebDAV. */
414
+ export function isPublicHostname(hostname) {
415
+ const lower = unbracketedHostname(hostname).toLowerCase();
416
+ const bare = lower.endsWith('.') ? lower.slice(0, -1) : lower;
417
+ return bare !== '' && bare !== 'localhost' && bare !== 'metadata.google.internal'
418
+ && !bare.endsWith('.localhost') && !bare.endsWith('.internal') && !bare.endsWith('.local');
419
+ }
420
+ /**
421
+ * Whether a WebDAV hostname may be fetched: public https targets only.
422
+ * Exported for tests.
423
+ */
424
+ export function isPublicTarget(hostname) {
425
+ const bare = unbracketedHostname(hostname);
426
+ const family = isIP(bare);
427
+ if (family === 4)
428
+ return isPublicIpv4(bare);
429
+ if (family === 6)
430
+ return isPublicIpv6(bare);
431
+ return isPublicHostname(bare);
432
+ }
433
+ /** Only global-unicast IPv6 is usable for a server-side WebDAV connection. */
434
+ export function isPublicIpv6(ip) {
435
+ const bare = unbracketedHostname(ip);
436
+ if (isIP(bare) !== 6)
437
+ return false;
438
+ const first = Number.parseInt(bare.split(':', 1)[0] || '0', 16);
439
+ return Number.isFinite(first) && first >= 0x2000 && first <= 0x3fff;
440
+ }
441
+ function unbracketedHostname(hostname) {
442
+ return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;
443
+ }
444
+ /** Resolve once, reject every unsafe answer, and return the address to pin. */
445
+ export async function resolvePublicAddress(hostname) {
446
+ const bare = unbracketedHostname(hostname);
447
+ const family = isIP(bare);
448
+ if (family === 4 || family === 6) {
449
+ if (!isPublicTarget(bare))
450
+ throw privateResolution(bare, bare);
451
+ return { address: bare, family };
452
+ }
453
+ if (!isPublicHostname(bare))
454
+ throw new WebdavUrlError('webdav_bad_url', 'invalid WebDAV URL');
455
+ const addresses = await lookup(bare, { all: true, verbatim: true });
456
+ if (addresses.length === 0) {
457
+ throw new WebdavUrlError('webdav_unresolvable', `域名 ${bare} 没有解析出任何地址,市场无法连接。请检查域名拼写和本机 DNS。 / ${bare} did not resolve to any address, so the market could not connect. Check the hostname and the machine's DNS.`);
458
+ }
459
+ const unsafe = addresses.find(({ address }) => !isPublicTarget(address));
460
+ if (unsafe !== undefined)
461
+ throw privateResolution(bare, unsafe.address);
462
+ const selected = addresses[0];
463
+ if (selected.family !== 4 && selected.family !== 6) {
464
+ throw new WebdavUrlError('webdav_unresolvable', `域名 ${bare} 的解析结果不可用 / the addresses ${bare} resolved to are not usable`);
465
+ }
466
+ return { address: selected.address, family: selected.family };
467
+ }
468
+ /**
469
+ * How many redirects a download will follow before giving up. Providers use
470
+ * one hop (WebDAV endpoint -> signed CDN link); five tolerates a CDN's own
471
+ * indirection without letting two servers ping-pong forever.
472
+ */
473
+ const MAX_REDIRECTS = 5;
474
+ export class WebdavUrlError extends Error {
475
+ code;
476
+ address;
477
+ constructor(code, message, address) {
478
+ super(message);
479
+ this.code = code;
480
+ this.address = address;
481
+ this.name = 'WebdavUrlError';
482
+ }
483
+ }
484
+ /** The refusal a private or reserved resolution deserves: what, why, and the way out. */
485
+ function privateResolution(hostname, address) {
486
+ return new WebdavUrlError('webdav_private_resolution', `WebDAV 域名 ${hostname} 解析到私有或保留地址 ${address},市场不会连过去。如果你在用 fake-ip 模式的代理(Clash/Mihomo 默认如此,任何域名都答成 198.18.x.x),请把这个域名加入代理的 fake-ip-filter 列表,或改用它的真实地址,然后重试。 / The WebDAV host ${hostname} resolved to ${address}, a private or reserved address, so the market did not connect. If you use a proxy in fake-ip mode (Clash/Mihomo answers 198.18.x.x for every proxied name), add this host to its fake-ip-filter list or use its real address, then try again.`, address);
487
+ }
488
+ export async function downloadWebdav(url, username, password) {
489
+ // Some providers answer a WebDAV GET with 302 to a time-limited signed CDN
490
+ // link while accepting PUT directly on the same path (#480 by @zhyx1996,
491
+ // measured against 123pan) — so upload worked and restore failed with
492
+ // "HTTP 302". Only GET follows: the upload path is direct on every
493
+ // provider seen, and replaying a PUT body across redirects is a can of
494
+ // worms nothing currently needs opened.
495
+ //
496
+ // Every hop goes back through webdavRequest, so the full SSRF gate —
497
+ // https-only, no credentials in the URL, resolvePublicAddress with the
498
+ // rebinding-safe direct-IP connect — is re-run per target, not only on the
499
+ // first one. A redirect is the server choosing the next URL; trusting it
500
+ // half as much as the user's own input would invert the threat model.
501
+ //
502
+ // Credentials do NOT cross origins. The signed link authorizes itself;
503
+ // forwarding Basic auth to whatever host the server named would hand the
504
+ // user's WebDAV password to a third party on the server's say-so.
505
+ let currentUrl = url;
506
+ let response = await webdavRequest(currentUrl, username, password, 'GET');
507
+ for (let hop = 0; hop < MAX_REDIRECTS; hop += 1) {
508
+ if (response.status !== 301 && response.status !== 302 && response.status !== 303
509
+ && response.status !== 307 && response.status !== 308)
510
+ break;
511
+ if (response.location === undefined)
512
+ break;
513
+ const next = new URL(response.location, currentUrl);
514
+ const sameOrigin = next.origin === new URL(currentUrl).origin;
515
+ currentUrl = next.toString();
516
+ response = sameOrigin
517
+ ? await webdavRequest(currentUrl, username, password, 'GET')
518
+ : await webdavRequest(currentUrl, '', '', 'GET');
519
+ }
520
+ if (response.status < 200 || response.status >= 300) {
521
+ throw new Error(response.status === 404
522
+ ? 'WebDAV download failed: HTTP 404 — no backup at that path yet. Upload one first, and check the URL points at the backup FILE (…/dsh/backup.json), not its folder / 该路径下还没有备份文件。请先执行一次上传,并确认地址指向备份文件本身(…/dsh/backup.json)而不是目录'
523
+ : `WebDAV download failed: HTTP ${response.status}`);
524
+ }
525
+ // Validate strictly server-side so the fetch result is never a generic
526
+ // echo of an internal response: restore only accepts real backups.
527
+ const body = JSON.parse(response.body.toString('utf8'));
528
+ validatedBackup(body);
529
+ return body;
530
+ }
531
+ /**
532
+ * The selected plugins' dependency specs and bundle entries from a backup's
533
+ * manifest. Only string specs survive — everything else in the manifest is
534
+ * untrusted and ignored (partial restore touches nothing but these).
535
+ */
536
+ export function extractPluginSelection(backup, includeDeps) {
537
+ const manifest = backup.files.find(file => file.path === 'package.json' && 'json' in file);
538
+ if (manifest === undefined || !('json' in manifest))
539
+ throw new Error('backup has no package.json');
540
+ const include = new Set(includeDeps);
541
+ const json = manifest.json;
542
+ const dependencies = json.dependencies === null || typeof json.dependencies !== 'object' || Array.isArray(json.dependencies)
543
+ ? {}
544
+ : json.dependencies;
545
+ const deps = {};
546
+ for (const [name, spec] of Object.entries(dependencies)) {
547
+ if (typeof spec === 'string' && include.has(name))
548
+ deps[name] = spec;
549
+ }
550
+ const dsh = json.dsh === null || typeof json.dsh !== 'object' || Array.isArray(json.dsh)
551
+ ? undefined
552
+ : json.dsh;
553
+ const profileBlock = dsh?.profile === null || typeof dsh?.profile !== 'object' || Array.isArray(dsh?.profile)
554
+ ? undefined
555
+ : dsh.profile;
556
+ const bundles = Array.isArray(profileBlock?.bundles) ? profileBlock.bundles : [];
557
+ return {
558
+ deps,
559
+ bundles: bundles.filter((name) => typeof name === 'string' && include.has(name)),
560
+ };
561
+ }
562
+ /**
563
+ * Merge a backup's manifest into the profile's current manifest so a restore
564
+ * never deletes plugins the target machine already has: current deps stay,
565
+ * backup specs win on name conflicts; bundle lists are unioned. When
566
+ * `selection` is given, only the selected plugins are merged in.
567
+ */
568
+ /**
569
+ * Dependencies whose spec points at an absolute local path — `link:/Users/…`
570
+ * or `file:/home/…` (#205 by @Rudyy898).
571
+ *
572
+ * These are perfectly valid on the machine that wrote them and meaningless
573
+ * anywhere else, so a backup carrying one restores a manifest that `pnpm
574
+ * install` cannot satisfy: the path does not exist on the new machine and
575
+ * the whole restore fails on it.
576
+ *
577
+ * Reported, NOT rewritten. Turning `link:/Users/me/dev/plugin` into
578
+ * something portable means deciding where those files should live and
579
+ * whether to carry them at all, which is a design question and not
580
+ * something a restore should answer on the user's behalf. Naming them lets
581
+ * the operator decide before the install runs — which is the part that was
582
+ * missing.
583
+ *
584
+ * Relative `file:./vendor/x` specs are left alone: they resolve against the
585
+ * profile directory, which the restore recreates, so they travel fine.
586
+ */
587
+ export function unportableDeps(dependencies) {
588
+ if (dependencies === null || typeof dependencies !== 'object' || Array.isArray(dependencies))
589
+ return [];
590
+ const found = [];
591
+ for (const [name, raw] of Object.entries(dependencies)) {
592
+ if (typeof raw !== 'string')
593
+ continue;
594
+ const match = /^(?:link|file):(.+)$/i.exec(raw);
595
+ if (match === null)
596
+ continue;
597
+ let path = match[1];
598
+ try {
599
+ path = decodeURIComponent(path);
600
+ }
601
+ catch { /* keep the literal spec */ }
602
+ // POSIX absolute, Windows drive-letter, or UNC — every shape that names
603
+ // a location outside this profile.
604
+ if (/^\//.test(path) || /^[A-Za-z]:[\\/]/.test(path) || /^\\\\/.test(path))
605
+ found.push({ name, spec: raw });
606
+ }
607
+ return found;
608
+ }
609
+ export function mergeRestoreManifest(backupManifest, current, selection) {
610
+ const merged = { ...backupManifest };
611
+ const backupDeps = backupManifest.dependencies === null || typeof backupManifest.dependencies !== 'object' || Array.isArray(backupManifest.dependencies)
612
+ ? {}
613
+ : backupManifest.dependencies;
614
+ const backupBundles = Array.isArray(backupManifest.dsh?.profile?.bundles)
615
+ ? (backupManifest.dsh.profile.bundles)
616
+ : [];
617
+ const currentDeps = current.dependencies === null || typeof current.dependencies !== 'object' || Array.isArray(current.dependencies)
618
+ ? {}
619
+ : current.dependencies;
620
+ const currentBundles = Array.isArray(current.dsh?.profile?.bundles)
621
+ ? (current.dsh.profile.bundles)
622
+ : [];
623
+ // Deps: keep the target's, overlay the backup's (or only the selection).
624
+ const deps = { ...currentDeps };
625
+ const sourceDeps = selection !== undefined ? selection.deps : backupDeps;
626
+ for (const [name, spec] of Object.entries(sourceDeps))
627
+ deps[name] = spec;
628
+ merged.dependencies = deps;
629
+ // Bundles: union of target and backup (or selection), de-duplicated.
630
+ const bundles = new Set();
631
+ for (const name of currentBundles)
632
+ if (typeof name === 'string')
633
+ bundles.add(name);
634
+ const sourceBundles = selection !== undefined ? selection.bundles : backupBundles;
635
+ for (const name of sourceBundles)
636
+ if (typeof name === 'string')
637
+ bundles.add(name);
638
+ const currentDsh = current.dsh === null || typeof current.dsh !== 'object' || Array.isArray(current.dsh)
639
+ ? undefined
640
+ : current.dsh;
641
+ const currentProfile = currentDsh?.profile === null || typeof currentDsh?.profile !== 'object' || Array.isArray(currentDsh?.profile)
642
+ ? undefined
643
+ : currentDsh.profile;
644
+ const backupDsh = merged.dsh === null || typeof merged.dsh !== 'object' || Array.isArray(merged.dsh)
645
+ ? undefined
646
+ : merged.dsh;
647
+ const backupProfile = backupDsh?.profile === null || typeof backupDsh?.profile !== 'object' || Array.isArray(backupDsh?.profile)
648
+ ? undefined
649
+ : backupDsh.profile;
650
+ const profileMerged = { ...(backupProfile ?? {}), ...(currentProfile ?? {}), bundles: [...bundles] };
651
+ const dshMerged = { ...(backupDsh ?? {}), ...(currentDsh ?? {}), profile: profileMerged };
652
+ merged.dsh = dshMerged;
653
+ return merged;
654
+ }
655
+ /**
656
+ * Dependencies a restore must leave at the spec the target already has — the
657
+ * market itself, while it is the package running the restore.
658
+ *
659
+ * A restore applies the backup's manifest through `pnpm install`, which
660
+ * rewrites whatever that manifest pins. When the backup was written by a
661
+ * different market version, that install replaces THIS package's files under
662
+ * the live module: the mixed state the update route refuses (#608), made
663
+ * worse here because the code answering the restore request is the code being
664
+ * swapped out. The running spec therefore wins, and the backup's spec is
665
+ * returned so the caller can report it — the update flow can apply it later,
666
+ * with its restart and rollback machinery.
667
+ *
668
+ * Only string specs take part: anything else is not a pin this can compare.
669
+ */
670
+ export function pinRunningDeps(merged, current, names) {
671
+ const mergedDeps = merged.dependencies === null || typeof merged.dependencies !== 'object' || Array.isArray(merged.dependencies)
672
+ ? {}
673
+ : merged.dependencies;
674
+ const currentDeps = current.dependencies === null || typeof current.dependencies !== 'object' || Array.isArray(current.dependencies)
675
+ ? {}
676
+ : current.dependencies;
677
+ const dependencies = { ...mergedDeps };
678
+ const pinned = [];
679
+ for (const name of names) {
680
+ const wanted = mergedDeps[name];
681
+ const running = currentDeps[name];
682
+ if (typeof wanted !== 'string' || typeof running !== 'string' || wanted === running)
683
+ continue;
684
+ dependencies[name] = running;
685
+ pinned.push({ name, from: wanted, to: running });
686
+ }
687
+ return { dependencies, pinned };
688
+ }