dsh-crate 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/routes.js CHANGED
@@ -15,10 +15,14 @@ import { isDeepStrictEqual } from 'node:util';
15
15
  import { load as loadYaml } from 'js-yaml';
16
16
  import { packageFileFromRegistry } from './catalog-npm.js';
17
17
  import { aiRecommend, aiSearch, FindPluginError, resultFor, setUserPluginsReader, setUsesMyPlugins, usesMyPlugins } from './find-plugin.js';
18
- import { forgetCatalog, loadRegistry, pluginCategories } from './registry.js';
18
+ import { CatalogLoadError, forgetCatalog, loadRegistry, pluginCategories } from './registry.js';
19
+ import { catalogConfig, entryAllowed, MAX_USER_CATALOGS, parseCatalogInput, probeCatalog, setUserCatalogs, userCatalogId, } from './catalogs.js';
20
+ import { clientPolicy, getPolicy, pinnedVersion } from './policy.js';
21
+ import { setNpmrcProfileDir } from './npmrc.js';
22
+ import { BundleError, extractBundle, isInsideOfflineRoot, MAX_BUNDLE_BYTES } from './offline.js';
19
23
  import { settingsNamespaceState } from './settings.js';
20
24
  import { statePath } from './state.js';
21
- import { buildEnvFromUnknown, cleanHotDir, forgetInstalled, hotMount, hotMountFailure, hotUnmount, listHotMounts, listLiveHotMounts, MAX_BLOCKED, MAX_BLOCKED_NAME, MAX_FAVORITES, MAX_NOTE, MAX_UPDATE_EXEMPT, mountClientOnlyDeps, purgeMarketState, readMarketState, recordInstalled, recordUpdated, writeMarketState, } from './hot.js';
25
+ import { buildEnvFromUnknown, cleanHotDir, forgetInstalled, hotMount, hotMountFailure, hotUnmount, listHotMounts, listLiveHotMounts, resetHotState, MAX_BLOCKED, MAX_BLOCKED_NAME, MAX_FAVORITES, MAX_NOTE, MAX_UPDATE_EXEMPT, mountClientOnlyDeps, purgeMarketState, readMarketState, recordInstalled, recordUpdated, writeMarketState, } from './hot.js';
22
26
  import { createGroup, deleteGroup, removeFromGroups, renameGroup, setGroupMembers } from './groups.js';
23
27
  import { dshHostInfo, findDshInstallDir } from './dsh-install.js';
24
28
  import { catalogReleaseManifest, deriveHostCompatibility, DiscoveryManifestIndex, findCompatibleVersion, githubCompatibilityRevision } from './discovery-compatibility.js';
@@ -46,20 +50,21 @@ import { catalogRepoKey, findCatalogEntryForLocal, findInstalledAlias, gitCommit
46
50
  import { checkoutSourceExists, detachCheckoutLink, failureDetail, groupConflictsByOwner, installApplied, isHostPortCollision, isStaleUpdate, keepCheckoutDetached, parseIgnoredBuildEntries, parseIgnoredBuilds, parsePrepareKey, parsePrepareNotAllowed, pnpmBlockedByOpenFiles, pnpmNeverStarted, pnpmRefusedYoungRelease, recordedCheckoutLink, RELEASE_AGE_OVERRIDE, removeDanglingHostBridge, removeLeftoverProfileLink, restoreCheckoutLink, retargetCollections, updateApplied, validateAddedPlugins, withHoistRecovery } from './install.js';
47
51
  import { classifyPnpmFailure } from './pnpm-compat.js';
48
52
  import { asChannel, CHANNELS, DIST_TAG, resolveChannel } from './channels.js';
49
- import { asRegion, githubProxyManaged, normalizeGithubProxy, REGIONS, routesFor, setActiveRegion, setCustomGithubProxy, } from './regions.js';
53
+ import { asRegion, githubProxyByPolicy, githubProxyManaged, normalizeGithubProxy, REGIONS, routesFor, setActiveRegion, setCustomGithubProxy, } from './regions.js';
50
54
  import { resolveRegion } from './region-probe.js';
51
55
  import { acceleratedTarget, resolveHeadCommit } from './accelerate.js';
52
56
  import { mismatchedWorkspaceRoot } from './github-install-target.js';
53
57
  import { sourceWebUrl, updateNotesFor } from './changelog.js';
54
58
  import { isCommitId } from './release-history.js';
55
59
  import { activeReleaseBlockers, headlineBlocker, releaseBlockedMessage } from './release-blockers.js';
56
- import { applyProfileBlockers, checkUpdates, isUpdatablePlugin, compareVersions, fetchNpmLatest, invalidateUpdates, readVersionMaturity, resolveDesktopMatureUpdate, resolveGitRemoteHead, isUpgrade, latestPublishedRecently, setUpdateRegistry, versionOnChannel } from './updates.js';
60
+ import { applyProfileBlockers, checkUpdates, isUpdatablePlugin, compareVersions, fetchNpmLatest, fetchRegistryLatest, invalidateUpdates, readVersionMaturity, resolveDesktopMatureUpdate, resolveGitRemoteHead, isUpgrade, latestPublishedRecently, setUpdateRegistry, versionOnChannel } from './updates.js';
57
61
  import { isExactReleaseVersion, isStableReleaseVersion } from './release-candidates.js';
58
62
  import { createUpdateNotificationMonitor } from './update-notifications.js';
59
63
  import { DEFAULT_UPDATE_CHECK_INTERVAL_HOURS, isUpdateCheckIntervalHours } from './update-notification-settings.js';
60
64
  import { createThemeManager } from './themes.js';
61
- import { readJsonBody, refuseUnadmitted, sameOrigin, sendJson } from './http.js';
65
+ import { readJsonBody, readRawBody, refuseUnadmitted, sameOrigin, sendJson } from './http.js';
62
66
  import { resolveDshHome } from './home-paths.js';
67
+ import { asHmr, claimInstance, reloadSelf, selfReloadReply } from './self-reload.js';
63
68
  import { readTelemetryState, sendOpened, setTelemetryEnabled, startHeartbeat } from './telemetry.js';
64
69
  import { clearWebdavSecret, readWebdavSecret, webdavSecretFor, writeWebdavSecret } from './webdav-secret.js';
65
70
  import { detectedDebugger, detectedSupervisor, restartAllowed, scheduleRestart, servingPort, trustedRestartRequest, trustedDownloadRequest, trustedSelfUninstallRequest, selfUninstallReachableFrom, restartReachableFrom } from './restart.js';
@@ -77,7 +82,9 @@ function discoveryCatalog(registry) {
77
82
  if (previous !== undefined)
78
83
  return previous;
79
84
  const revisions = new Map();
80
- const plugins = registry.plugins.map((entry) => {
85
+ const plugins = registry.plugins.map((original) => {
86
+ // Where a bundle's package file sits on this machine is the server's business, not the page's.
87
+ const entry = original.offlineTarball === undefined ? original : (({ offlineTarball: _path, ...rest }) => rest)(original);
81
88
  if ((entry.npm == null || entry.npm === '') && typeof entry.url === 'string' && parseSourceUrl(entry.url) !== null) {
82
89
  const revision = githubCompatibilityRevision(entry);
83
90
  revisions.set(entry.url, { entry, revision });
@@ -135,6 +142,27 @@ function isGitHubReleaseTarballSpec(spec) {
135
142
  * in frame the first reply always has to ask which one it was.
136
143
  */
137
144
  let cachedVersion = null;
145
+ /**
146
+ * Forget the version read from disk. Called when the routes unload: a module
147
+ * the host did not replace (its file did not change) stays loaded across an
148
+ * in-process reload (src/self-reload.ts), and the instance that comes next
149
+ * must report the package.json that is on disk now, not the one it started
150
+ * beside.
151
+ */
152
+ export function forgetMarketVersion() {
153
+ cachedVersion = null;
154
+ }
155
+ /**
156
+ * True only while this market is asking the host to swap in its own new build.
157
+ *
158
+ * The version a market reports must be the version of the CODE that is
159
+ * running. Any other reason this instance unloads (a settings change makes
160
+ * the host restart the entry) leaves the same code running, so the version
161
+ * read at first use stays true even though a newer package.json is on disk —
162
+ * forgetting it there would report the new version over the old code and
163
+ * hide exactly the mismatch the page needs to see.
164
+ */
165
+ let swappingSelf = false;
138
166
  export function marketVersion() {
139
167
  if (cachedVersion !== null)
140
168
  return cachedVersion;
@@ -604,21 +632,25 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
604
632
  // group, install and uninstall mutates this shared state and persists it.
605
633
  const marketState = readMarketState(activeProfileDir);
606
634
  setCustomGithubProxy(marketState.githubProxy ?? null);
635
+ setUserCatalogs(marketState.userCatalogs ?? []);
636
+ // The profile's own .npmrc is the first place a private registry is named.
637
+ setNpmrcProfileDir(activeProfileDir);
607
638
  const disabled = marketState.disabled;
608
639
  /**
609
640
  * The saved answer to "which doors into the market are open" (#1015).
610
641
  *
611
642
  * The HOST decides which doors exist; this only combines the user's
612
643
  * preferences, because a request handler cannot see the browser's slots.
613
- * `sidebarEntry` defaults off while the two page tabs default on, so
614
- * "every door closed" is expressible — and has to be refused before it
615
- * reaches disk. A market with no entry can only be recovered by editing
644
+ * The Plugins page tab and the sidebar row default on; the settings page
645
+ * entry defaults off (it is the old door, kept for hosts without the other
646
+ * two — the browser shows it there anyway). "Every door closed" is still
647
+ * expressible, and has to be refused before it reaches disk. A market with no entry can only be recovered by editing
616
648
  * state.json or removing the package, which the card must never cause.
617
649
  */
618
650
  const entryDoors = (state = marketState) => ({
619
- settingsSection: state.settingsSection !== false,
651
+ settingsSection: state.settingsSection === true,
620
652
  pluginsTab: state.pluginsTab !== false,
621
- sidebarEntry: state.sidebarEntry === true,
653
+ sidebarEntry: state.sidebarEntry !== false,
622
654
  });
623
655
  const closesEveryDoor = (doors) => !doors.settingsSection && !doors.pluginsTab && !doors.sidebarEntry;
624
656
  /**
@@ -738,6 +770,8 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
738
770
  updateNotifications.setEnabled(fresh.backgroundUpdateChecks === true);
739
771
  updateNotifications.setIntervalHours(fresh.backgroundUpdateIntervalHours ?? DEFAULT_UPDATE_CHECK_INTERVAL_HOURS);
740
772
  marketState.githubProxy = fresh.githubProxy;
773
+ marketState.userCatalogs = fresh.userCatalogs;
774
+ setUserCatalogs(fresh.userCatalogs ?? []);
741
775
  // A restore or an external writer can change these two too; a stale copy
742
776
  // here would put the old answer back on the next whole-state save (#435).
743
777
  marketState.settingsSection = fresh.settingsSection;
@@ -2624,7 +2658,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2624
2658
  catch {
2625
2659
  return null;
2626
2660
  }
2627
- return `目录条目指向的子目录在仓库里已不存在(${repo} 的 ${subpath}),多半是作者改名或移动了它——这不是你的环境的问题。请到 awesome-dsh-plugin 反馈这条收录已失效。 / This catalog entry points at a subdirectory that no longer exists in the repository (${subpath} in ${repo}); the author most likely renamed or moved it. Nothing is wrong with your setup — please report the stale entry to awesome-dsh-plugin.`;
2661
+ return `目录条目指向的子目录在仓库里已不存在(${repo} 的 ${subpath}),多半是作者改名或移动了它——这不是你的环境的问题。请到 dshcrate 反馈这条收录已失效。 / This catalog entry points at a subdirectory that no longer exists in the repository (${subpath} in ${repo}); the author most likely renamed or moved it. Nothing is wrong with your setup — please report the stale entry to dshcrate.`;
2628
2662
  }
2629
2663
  async function restoreBackup(value) {
2630
2664
  if (!await probePnpm())
@@ -3223,6 +3257,18 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3223
3257
  kind: () => (config.desktopHost === true ? 'desktop' : 'web'),
3224
3258
  region: () => region,
3225
3259
  };
3260
+ /**
3261
+ * In-process reload of the market itself (see src/self-reload.ts).
3262
+ *
3263
+ * Available when the host can replace modules (its HMR service, DSH 0.2.1
3264
+ * and later) and the market is an installed package of this profile — a
3265
+ * development checkout has no newer files on disk to switch to.
3266
+ */
3267
+ const selfPackageName = () => readInstalled(config.profile, activeProfileDir)['dsh-crate'] !== undefined ? 'dsh-crate' : null;
3268
+ const hostHmr = () => asHmr(host.get?.('hmr'));
3269
+ const selfReloadAvailable = () => hostHmr() !== undefined && host.get?.('profileContext') !== undefined && selfPackageName() !== null;
3270
+ // Announced once the routes below are up; handlers read it lazily.
3271
+ let instanceClaim;
3226
3272
  const disposers = [
3227
3273
  // 页面打开:页面每次加载上报一次,服务端每天只保留第一次;立即返回,页面不等网络。
3228
3274
  registerRoute({
@@ -3248,7 +3294,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3248
3294
  path: '/dsh-crate/telemetry',
3249
3295
  handler: async (request, response) => {
3250
3296
  if (request.method === 'GET') {
3251
- sendJson(response, 200, { enabled: readTelemetryState().enabled });
3297
+ sendJson(response, 200, { enabled: readTelemetryState().enabled && getPolicy().telemetry !== false, ...(getPolicy().telemetry === false ? { locked: true } : {}) });
3252
3298
  return;
3253
3299
  }
3254
3300
  if (request.method !== 'POST') {
@@ -3260,6 +3306,10 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3260
3306
  sendJson(response, 403, { error: 'untrusted origin' });
3261
3307
  return;
3262
3308
  }
3309
+ if (getPolicy().telemetry === false) {
3310
+ sendJson(response, 403, { ok: false, code: 'locked', error: '你的组织已关闭匿名使用统计,这里不能改。 / Your organization turned the anonymous count off; it cannot be changed here.' });
3311
+ return;
3312
+ }
3263
3313
  try {
3264
3314
  const body = await readJsonBody(request);
3265
3315
  if (body === null || typeof body !== 'object' || typeof body.enabled !== 'boolean') {
@@ -4081,6 +4131,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4081
4131
  const registry = await loadRegistry();
4082
4132
  sendJson(response, 200, {
4083
4133
  registry: discoveryCatalog(registry).response,
4134
+ ...(Object.keys(clientPolicy()).length > 0 ? { policy: clientPolicy() } : {}),
4084
4135
  hostVersion: dshHostInfo()?.version ?? null,
4085
4136
  });
4086
4137
  }
@@ -4090,7 +4141,11 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4090
4141
  // reachable one with fewer plugins in it.
4091
4142
  const message = error instanceof Error ? error.message : String(error);
4092
4143
  logEvent('warn', 'registry', `catalog fetch failed: ${message}`);
4093
- sendJson(response, 502, { error: message });
4144
+ sendJson(response, 502, {
4145
+ error: message,
4146
+ // Which source said what, so the page can name the one to fix.
4147
+ ...(error instanceof CatalogLoadError ? { sources: error.sources } : {}),
4148
+ });
4094
4149
  }
4095
4150
  }
4096
4151
  catch (error) {
@@ -5032,6 +5087,213 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5032
5087
  }
5033
5088
  },
5034
5089
  }),
5090
+ /**
5091
+ * The catalogs list in Settings: what is configured and how each source
5092
+ * answered the last read. Never carries a header, a token or a query string.
5093
+ */
5094
+ registerRoute({
5095
+ kind: 'exact',
5096
+ path: '/dsh-crate/catalogs',
5097
+ handler: async (request, response) => {
5098
+ if (request.method !== 'GET') {
5099
+ response.writeHead(405, { allow: 'GET' });
5100
+ response.end();
5101
+ return;
5102
+ }
5103
+ try {
5104
+ const config = catalogConfig();
5105
+ let sources = [];
5106
+ if (config.active) {
5107
+ // Reading also refreshes each source's status; a total failure
5108
+ // still carries the per-source answers.
5109
+ sources = await loadRegistry().then(registry => registry.sources ?? [], (error) => (error instanceof CatalogLoadError ? error.sources : []));
5110
+ }
5111
+ sendJson(response, 200, {
5112
+ sources,
5113
+ publicCatalog: { enabled: config.publicEnabled, locked: config.policy.publicCatalog === false },
5114
+ userCatalogsAllowed: config.policy.userCatalogs,
5115
+ limit: MAX_USER_CATALOGS,
5116
+ problems: config.policy.problems,
5117
+ });
5118
+ }
5119
+ catch (error) {
5120
+ sendJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
5121
+ }
5122
+ },
5123
+ }),
5124
+ /**
5125
+ * Add a catalog of the user's own: one URL or absolute file path, read
5126
+ * once to prove it is a catalog, then saved. Refused wholesale while the
5127
+ * organization's policy says users may not add catalogs.
5128
+ */
5129
+ registerRoute({
5130
+ kind: 'exact',
5131
+ path: '/dsh-crate/catalogs/add',
5132
+ handler: async (request, response) => {
5133
+ if (request.method !== 'POST') {
5134
+ response.writeHead(405, { allow: 'POST' });
5135
+ response.end();
5136
+ return;
5137
+ }
5138
+ if (!sameOrigin(request)) {
5139
+ sendJson(response, 403, { error: 'untrusted origin' });
5140
+ return;
5141
+ }
5142
+ try {
5143
+ await withMutationQueued(async () => {
5144
+ if (!getPolicy().userCatalogs) {
5145
+ sendJson(response, 403, { ok: false, code: 'locked', error: '你的组织不允许添加目录 / your organization does not allow adding catalogs' });
5146
+ return;
5147
+ }
5148
+ const body = (await readJsonBody(request));
5149
+ const parsed = parseCatalogInput(typeof body?.source === 'string' ? body.source : '');
5150
+ if ('error' in parsed) {
5151
+ sendJson(response, 400, { ok: false, code: parsed.error, error: `invalid catalog address (${parsed.error}) / 目录地址不对` });
5152
+ return;
5153
+ }
5154
+ const state = readMarketState(activeProfileDir);
5155
+ const saved = [...(state.userCatalogs ?? [])];
5156
+ const id = userCatalogId(parsed);
5157
+ if (saved.some(entry => entry.id === id) || catalogConfig().extras.some(source => source.id === id)) {
5158
+ sendJson(response, 409, { ok: false, code: 'duplicate', error: 'this catalog is already added / 这个目录已经添加过了' });
5159
+ return;
5160
+ }
5161
+ if (saved.length >= MAX_USER_CATALOGS) {
5162
+ sendJson(response, 400, { ok: false, code: 'limit', limit: MAX_USER_CATALOGS, error: `at most ${String(MAX_USER_CATALOGS)} catalogs / 最多添加 ${String(MAX_USER_CATALOGS)} 个目录` });
5163
+ return;
5164
+ }
5165
+ // Read it once before keeping it: what is saved is known to work.
5166
+ const probe = await probeCatalog(parsed);
5167
+ if (probe.registry === null) {
5168
+ sendJson(response, 400, { ok: false, code: 'unreadable', source: probe.info.error, error: `could not read the catalog (${probe.info.error?.code ?? 'unknown'}) / 读不了这个目录` });
5169
+ return;
5170
+ }
5171
+ writeMarketState(activeProfileDir, { ...readMarketState(activeProfileDir), userCatalogs: [...saved, { id, ...parsed }] });
5172
+ refreshMarketState();
5173
+ forgetCatalog();
5174
+ invalidateUpdates();
5175
+ logEvent('info', 'catalog', `added catalog ${id} (${probe.info.where}), ${String(probe.info.count)} plugins`);
5176
+ sendJson(response, 200, { ok: true, id, count: probe.info.count, label: probe.info.label });
5177
+ });
5178
+ }
5179
+ catch (error) {
5180
+ sendJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
5181
+ }
5182
+ },
5183
+ }),
5184
+ /**
5185
+ * Import an offline bundle: the request body IS the archive. It is
5186
+ * unpacked under the market's own directory with strict rules (see
5187
+ * offline.ts), read once as a catalog, and only then saved as one of the
5188
+ * user's catalogs.
5189
+ */
5190
+ registerRoute({
5191
+ kind: 'exact',
5192
+ path: '/dsh-crate/offline/import',
5193
+ handler: async (request, response) => {
5194
+ if (request.method !== 'POST') {
5195
+ response.writeHead(405, { allow: 'POST' });
5196
+ response.end();
5197
+ return;
5198
+ }
5199
+ if (!sameOrigin(request)) {
5200
+ sendJson(response, 403, { error: 'untrusted origin' });
5201
+ return;
5202
+ }
5203
+ try {
5204
+ await withMutationQueued(async () => {
5205
+ if (!getPolicy().userCatalogs) {
5206
+ sendJson(response, 403, { ok: false, code: 'locked', error: '你的组织不允许添加目录 / your organization does not allow adding catalogs' });
5207
+ return;
5208
+ }
5209
+ let archive;
5210
+ try {
5211
+ archive = await readRawBody(request, MAX_BUNDLE_BYTES);
5212
+ }
5213
+ catch {
5214
+ sendJson(response, 413, { ok: false, code: 'too-big', error: 'the bundle is too large / 离线包太大' });
5215
+ return;
5216
+ }
5217
+ let extracted;
5218
+ try {
5219
+ extracted = extractBundle(archive);
5220
+ }
5221
+ catch (error) {
5222
+ const refused = error instanceof BundleError ? error : null;
5223
+ logEvent('warn', 'offline', `bundle refused: ${refused === null ? String(error) : `${refused.code} ${refused.detail}`}`);
5224
+ sendJson(response, 400, { ok: false, code: refused?.code ?? 'not-archive', detail: refused?.detail ?? '', error: 'not a usable offline bundle / 这不是可用的离线包' });
5225
+ return;
5226
+ }
5227
+ const entry = { file: extracted.catalogFile };
5228
+ const probe = await probeCatalog(entry);
5229
+ if (probe.registry === null) {
5230
+ rmSync(extracted.dir, { recursive: true, force: true });
5231
+ sendJson(response, 400, { ok: false, code: 'unreadable', source: probe.info.error, error: 'the bundle has no readable catalog / 离线包里的目录读不了' });
5232
+ return;
5233
+ }
5234
+ const state = readMarketState(activeProfileDir);
5235
+ const id = userCatalogId(entry);
5236
+ const saved = (state.userCatalogs ?? []).filter(item => item.id !== id);
5237
+ if (saved.length >= MAX_USER_CATALOGS) {
5238
+ rmSync(extracted.dir, { recursive: true, force: true });
5239
+ sendJson(response, 400, { ok: false, code: 'limit', limit: MAX_USER_CATALOGS, error: `at most ${String(MAX_USER_CATALOGS)} catalogs / 最多添加 ${String(MAX_USER_CATALOGS)} 个目录` });
5240
+ return;
5241
+ }
5242
+ writeMarketState(activeProfileDir, { ...state, userCatalogs: [...saved, { id, ...entry }] });
5243
+ refreshMarketState();
5244
+ forgetCatalog();
5245
+ invalidateUpdates();
5246
+ logEvent('info', 'offline', `imported bundle ${extracted.id}: ${String(probe.info.count)} plugins, ${String(extracted.files)} files`);
5247
+ sendJson(response, 200, { ok: true, id, count: probe.info.count, label: probe.info.label });
5248
+ });
5249
+ }
5250
+ catch (error) {
5251
+ sendJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
5252
+ }
5253
+ },
5254
+ }),
5255
+ registerRoute({
5256
+ kind: 'exact',
5257
+ path: '/dsh-crate/catalogs/remove',
5258
+ handler: async (request, response) => {
5259
+ if (request.method !== 'POST') {
5260
+ response.writeHead(405, { allow: 'POST' });
5261
+ response.end();
5262
+ return;
5263
+ }
5264
+ if (!sameOrigin(request)) {
5265
+ sendJson(response, 403, { error: 'untrusted origin' });
5266
+ return;
5267
+ }
5268
+ try {
5269
+ await withMutationQueued(async () => {
5270
+ const body = (await readJsonBody(request));
5271
+ const id = typeof body?.id === 'string' ? body.id : '';
5272
+ const state = readMarketState(activeProfileDir);
5273
+ const saved = state.userCatalogs ?? [];
5274
+ // A catalog the organization set is not the user's to remove.
5275
+ if (!saved.some(entry => entry.id === id)) {
5276
+ sendJson(response, 404, { ok: false, error: 'no such catalog / 没有这个目录' });
5277
+ return;
5278
+ }
5279
+ const gone = saved.find(entry => entry.id === id);
5280
+ writeMarketState(activeProfileDir, { ...state, userCatalogs: saved.filter(entry => entry.id !== id) });
5281
+ // An imported bundle is the market's own copy: removing the catalog removes its files.
5282
+ if (gone?.file !== undefined && isInsideOfflineRoot(gone.file)) {
5283
+ rmSync(dirname(gone.file), { recursive: true, force: true });
5284
+ }
5285
+ refreshMarketState();
5286
+ forgetCatalog();
5287
+ invalidateUpdates();
5288
+ logEvent('info', 'catalog', `removed catalog ${id}`);
5289
+ sendJson(response, 200, { ok: true });
5290
+ });
5291
+ }
5292
+ catch (error) {
5293
+ sendJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
5294
+ }
5295
+ },
5296
+ }),
5035
5297
  registerRoute({
5036
5298
  kind: 'exact',
5037
5299
  path: '/dsh-crate/favorite',
@@ -5442,7 +5704,9 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5442
5704
  channels: CHANNELS,
5443
5705
  region,
5444
5706
  regions: REGIONS,
5445
- anonymousCount: readTelemetryState().enabled,
5707
+ anonymousCount: readTelemetryState().enabled && getPolicy().telemetry !== false,
5708
+ // Set by the organization: shown, not switchable.
5709
+ anonymousCountLocked: getPolicy().telemetry === false,
5446
5710
  // The padded/PATH- and CI-safe build environment currently pinned
5447
5711
  // (issue #336): composition plus any card-saved override. The card
5448
5712
  // edits exactly what this reports, so the form never shows a stale
@@ -5458,11 +5722,14 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5458
5722
  githubRoutes: routesFor(region).githubRoutes,
5459
5723
  githubProxyCustom: marketState.githubProxy ?? null,
5460
5724
  githubProxyManaged: githubProxyManaged(),
5725
+ githubProxyByPolicy: githubProxyByPolicy(),
5461
5726
  // Whether the region was decided by the network check rather than
5462
5727
  // by the user — the card explains a choice it made on their behalf
5463
5728
  // exactly once, so nobody has to wonder why downloads moved.
5464
5729
  regionAuto,
5465
- sidebarEntry: marketState.sidebarEntry === true,
5730
+ sidebarEntry: marketState.sidebarEntry !== false,
5731
+ // Whether DSH Desktop owns this process (the market cannot restart it).
5732
+ desktopHost: config.desktopHost === true,
5466
5733
  restart: restartAllowed(config),
5467
5734
  // Named so the UI can say WHY the button is gone. A blank
5468
5735
  // "no restart button" is the state #229 reported as broken.
@@ -5480,7 +5747,12 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5480
5747
  // Same door, one notch wider for the desktop proxy (#903): the
5481
5748
  // card hides a remove button that could only ever answer 403.
5482
5749
  selfUninstallReachable: selfUninstallReachableFrom(request),
5483
- selfManaged: installed['dsh-crate'] !== undefined || installed['dsh-crate'] !== undefined,
5750
+ selfManaged: installed['dsh-crate'] !== undefined,
5751
+ // Whether POST /dsh-crate/reload-self can swap a newer build of the
5752
+ // market in without restarting DSH. The page that has just loaded a
5753
+ // newer client than this server reads it to choose between "reload
5754
+ // the market" and "restart DSH".
5755
+ selfReload: selfReloadAvailable(),
5484
5756
  // Whether the host took the market's settings namespace (#677).
5485
5757
  // `unsupported-by-host` is 0.1.7 and newer, where settings come from
5486
5758
  // a plugin's Config schema and no third-party namespace is served —
@@ -6216,15 +6488,17 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6216
6488
  }
6217
6489
  }
6218
6490
  if (desktopStable) {
6219
- const endpointLatest = await fetchNpmLatest(name);
6491
+ const endpointLatest = await fetchRegistryLatest(name);
6492
+ // What the organization allows as the newest, when it pinned one.
6493
+ const orgNewest = pinnedVersion(name) ?? endpointLatest;
6220
6494
  // Repeated legacy requests are already complete. An explicit
6221
6495
  // client target must still pass the stale-target checks below.
6222
- if (body.eligibleVersion === undefined && compatVersion === null && endpointLatest === installedVersion) {
6496
+ if (body.eligibleVersion === undefined && compatVersion === null && orgNewest === installedVersion) {
6223
6497
  invalidateUpdates();
6224
6498
  sendJson(response, 200, { ok: true, skipped: 'current', name, version: installedVersion });
6225
6499
  return;
6226
6500
  }
6227
- const eligible = await resolveDesktopMatureUpdate(name, installedVersion, config.profile, activeProfileDir, endpointLatest, compatVersion ?? undefined);
6501
+ const eligible = await resolveDesktopMatureUpdate(name, installedVersion, config.profile, activeProfileDir, endpointLatest, compatVersion ?? pinnedVersion(name));
6228
6502
  if (body.eligibleVersion !== undefined && body.eligibleVersion !== eligible.candidate) {
6229
6503
  invalidateUpdates();
6230
6504
  sendJson(response, 409, {
@@ -6244,7 +6518,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6244
6518
  // Older clients have no target token. They may still install
6245
6519
  // a mature latest, but cannot silently get a different build
6246
6520
  // from the version their UI presented.
6247
- if (compatVersion === null && body.eligibleVersion === undefined && eligible.candidate !== endpointLatest) {
6521
+ if (compatVersion === null && body.eligibleVersion === undefined && eligible.candidate !== orgNewest) {
6248
6522
  invalidateUpdates();
6249
6523
  sendJson(response, 409, { staleTarget: true, error: '当前最新版仍在等待期;请刷新市场以确认可安装的成熟版本。 / The latest release is held. Refresh the market to confirm the exact mature target.' });
6250
6524
  return;
@@ -7617,7 +7891,8 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7617
7891
  handler: async (request, response) => {
7618
7892
  if (request.method === 'GET') {
7619
7893
  sendJson(response, 200, {
7620
- enabled: marketState.sidebarEntry === true,
7894
+ // Shown unless turned off (the default changed from off to on).
7895
+ enabled: marketState.sidebarEntry !== false,
7621
7896
  // Absent means nobody has ever chosen. On a host with no settings
7622
7897
  // page the row is then shown by default, because it is the only
7623
7898
  // way into the market (#846).
@@ -7680,7 +7955,13 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7680
7955
  handler: async (request, response) => {
7681
7956
  if (request.method === 'GET') {
7682
7957
  const doors = entryDoors();
7683
- sendJson(response, 200, { settingsSection: doors.settingsSection, pluginsTab: doors.pluginsTab });
7958
+ sendJson(response, 200, {
7959
+ settingsSection: doors.settingsSection,
7960
+ pluginsTab: doors.pluginsTab,
7961
+ // Unchosen, the browser still shows the settings entry when it is
7962
+ // the host's only door.
7963
+ settingsSectionChosen: typeof marketState.settingsSection === 'boolean',
7964
+ });
7684
7965
  return;
7685
7966
  }
7686
7967
  if (request.method !== 'POST') {
@@ -7863,7 +8144,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7863
8144
  return;
7864
8145
  }
7865
8146
  const installed = readInstalled(config.profile, activeProfileDir);
7866
- const selfName = ['dsh-crate', 'dsh-crate'].find(candidate => installed[candidate] !== undefined);
8147
+ const selfName = installed['dsh-crate'] !== undefined ? 'dsh-crate' : undefined;
7867
8148
  if (selfName === undefined) {
7868
8149
  sendJson(response, 400, { error: 'the market is not an installed dependency of this profile' });
7869
8150
  return;
@@ -7941,6 +8222,56 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7941
8222
  }
7942
8223
  },
7943
8224
  }),
8225
+ registerRoute({
8226
+ kind: 'exact',
8227
+ path: '/dsh-crate/reload-self',
8228
+ handler: async (request, response) => {
8229
+ if (request.method !== 'POST') {
8230
+ response.writeHead(405, { allow: 'POST' });
8231
+ response.end();
8232
+ return;
8233
+ }
8234
+ if (!sameOrigin(request)) {
8235
+ sendJson(response, 403, { error: 'untrusted origin' });
8236
+ return;
8237
+ }
8238
+ if (restarting) {
8239
+ sendJson(response, 409, { busy: true, error: 'restart already scheduled' });
8240
+ return;
8241
+ }
8242
+ try {
8243
+ // Under the same lock as every other change: a swap ends the instance
8244
+ // that would have finished a running install, so none may be running,
8245
+ // and none may start while it happens. A second request answers 409.
8246
+ const outcome = await withMutationLock(response, 'write', async () => {
8247
+ const name = selfPackageName();
8248
+ swappingSelf = true;
8249
+ try {
8250
+ return await reloadSelf({
8251
+ hmr: hostHmr,
8252
+ runningVersion: marketVersion(),
8253
+ installedVersion: () => name === null ? null : readInstalledVersion(config.profile, name, activeProfileDir),
8254
+ packageDir: () => join(activeProfileDir, 'node_modules', name ?? 'dsh-crate'),
8255
+ instanceId: instanceClaim?.id ?? '',
8256
+ log: (level, detail) => logEvent(level, 'reload', detail),
8257
+ });
8258
+ }
8259
+ finally {
8260
+ swappingSelf = false;
8261
+ }
8262
+ });
8263
+ if (outcome === null)
8264
+ return;
8265
+ const reply = selfReloadReply(outcome);
8266
+ sendJson(response, reply.status, reply.body);
8267
+ }
8268
+ catch (error) {
8269
+ const message = error instanceof Error ? error.message : String(error);
8270
+ logEvent('error', 'reload', `route error: ${message}`);
8271
+ sendJson(response, 500, { ok: false, error: message });
8272
+ }
8273
+ },
8274
+ }),
7944
8275
  registerRoute(captureLegacy('/dsh-crate/restart', {
7945
8276
  kind: 'exact',
7946
8277
  path: '/dsh-crate/restart',
@@ -8616,7 +8947,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
8616
8947
  // A release the user picked from the refusal dialog's own search
8617
8948
  // (#581): it was confirmed compatible by /dsh-crate/find-compatible,
8618
8949
  // so it is pinned below instead of resolving `latest` again.
8619
- const requestedVersion = typeof body.version === 'string' && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(body.version)
8950
+ let requestedVersion = typeof body.version === 'string' && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(body.version)
8620
8951
  ? body.version
8621
8952
  : null;
8622
8953
  const registry = await loadRegistry();
@@ -8626,6 +8957,19 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
8626
8957
  sendJson(response, 400, { error: 'plugin is not in the curated registry' });
8627
8958
  return;
8628
8959
  }
8960
+ // The list above is already narrowed by the policy's `allow`; asked
8961
+ // again here so this route does not depend on that happening
8962
+ // upstream (the check that matters is the one next to the install).
8963
+ if (!entryAllowed(entry, getPolicy().allow)) {
8964
+ logEvent('warn', 'install-rejected', `not allowed by policy: ${entry.name}`);
8965
+ sendJson(response, 403, { error: '你的组织不允许安装这个插件 / your organization does not allow installing this plugin' });
8966
+ return;
8967
+ }
8968
+ // The organization fixed this package's version: that exact release
8969
+ // installs, whatever the page asked for.
8970
+ const orgPin = typeof entry.npm === 'string' ? pinnedVersion(entry.npm) : undefined;
8971
+ if (orgPin !== undefined)
8972
+ requestedVersion = orgPin;
8629
8973
  const plainTarget = installTargetFor(entry);
8630
8974
  if (plainTarget === null) {
8631
8975
  sendJson(response, 400, { error: 'unsupported source url' });
@@ -9279,8 +9623,13 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
9279
9623
  ];
9280
9624
  startCheckoutRepair();
9281
9625
  const stopHeartbeat = startHeartbeat(telemetryOptions);
9626
+ instanceClaim = claimInstance(marketVersion());
9282
9627
  return async () => {
9283
9628
  disposed = true;
9629
+ instanceClaim?.release();
9630
+ if (swappingSelf)
9631
+ forgetMarketVersion();
9632
+ resetHotState();
9284
9633
  stopHeartbeat();
9285
9634
  checkoutRepairRound = undefined;
9286
9635
  if (checkoutRepairTimer !== undefined)