dshmarket 1.77.0 → 1.78.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.
package/lib/routes.js CHANGED
@@ -15,7 +15,11 @@ 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 { 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';
21
25
  import { createGroup, deleteGroup, removeFromGroups, renameGroup, setGroupMembers } from './groups.js';
@@ -45,19 +49,19 @@ import { catalogRepoKey, findCatalogEntryForLocal, findInstalledAlias, gitCommit
45
49
  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';
46
50
  import { classifyPnpmFailure } from './pnpm-compat.js';
47
51
  import { asChannel, CHANNELS, DIST_TAG, resolveChannel } from './channels.js';
48
- import { asRegion, githubProxyManaged, normalizeGithubProxy, REGIONS, routesFor, setActiveRegion, setCustomGithubProxy, } from './regions.js';
52
+ import { asRegion, githubProxyByPolicy, githubProxyManaged, normalizeGithubProxy, REGIONS, routesFor, setActiveRegion, setCustomGithubProxy, } from './regions.js';
49
53
  import { resolveRegion } from './region-probe.js';
50
54
  import { acceleratedTarget, resolveHeadCommit } from './accelerate.js';
51
55
  import { mismatchedWorkspaceRoot } from './github-install-target.js';
52
56
  import { sourceWebUrl, updateNotesFor } from './changelog.js';
53
57
  import { isCommitId } from './release-history.js';
54
58
  import { activeReleaseBlockers, headlineBlocker, releaseBlockedMessage } from './release-blockers.js';
55
- import { applyProfileBlockers, checkUpdates, isUpdatablePlugin, compareVersions, fetchNpmLatest, invalidateUpdates, readVersionMaturity, resolveDesktopMatureUpdate, resolveGitRemoteHead, isUpgrade, latestPublishedRecently, setUpdateRegistry, versionOnChannel } from './updates.js';
59
+ import { applyProfileBlockers, checkUpdates, isUpdatablePlugin, compareVersions, fetchNpmLatest, fetchRegistryLatest, invalidateUpdates, readVersionMaturity, resolveDesktopMatureUpdate, resolveGitRemoteHead, isUpgrade, latestPublishedRecently, setUpdateRegistry, versionOnChannel } from './updates.js';
56
60
  import { isExactReleaseVersion, isStableReleaseVersion } from './release-candidates.js';
57
61
  import { createUpdateNotificationMonitor } from './update-notifications.js';
58
62
  import { DEFAULT_UPDATE_CHECK_INTERVAL_HOURS, isUpdateCheckIntervalHours } from './update-notification-settings.js';
59
63
  import { createThemeManager } from './themes.js';
60
- import { readJsonBody, refuseUnadmitted, sameOrigin, sendJson } from './http.js';
64
+ import { readJsonBody, readRawBody, refuseUnadmitted, sameOrigin, sendJson } from './http.js';
61
65
  import { resolveDshHome } from './home-paths.js';
62
66
  import { readTelemetryState, sendOpened, setTelemetryEnabled, startHeartbeat } from './telemetry.js';
63
67
  import { clearWebdavSecret, readWebdavSecret, webdavSecretFor, writeWebdavSecret } from './webdav-secret.js';
@@ -76,7 +80,9 @@ function discoveryCatalog(registry) {
76
80
  if (previous !== undefined)
77
81
  return previous;
78
82
  const revisions = new Map();
79
- const plugins = registry.plugins.map((entry) => {
83
+ const plugins = registry.plugins.map((original) => {
84
+ // Where a bundle's package file sits on this machine is the server's business, not the page's.
85
+ const entry = original.offlineTarball === undefined ? original : (({ offlineTarball: _path, ...rest }) => rest)(original);
80
86
  if ((entry.npm == null || entry.npm === '') && typeof entry.url === 'string' && parseSourceUrl(entry.url) !== null) {
81
87
  const revision = githubCompatibilityRevision(entry);
82
88
  revisions.set(entry.url, { entry, revision });
@@ -603,6 +609,9 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
603
609
  // group, install and uninstall mutates this shared state and persists it.
604
610
  const marketState = readMarketState(activeProfileDir);
605
611
  setCustomGithubProxy(marketState.githubProxy ?? null);
612
+ setUserCatalogs(marketState.userCatalogs ?? []);
613
+ // The profile's own .npmrc is the first place a private registry is named.
614
+ setNpmrcProfileDir(activeProfileDir);
606
615
  const disabled = marketState.disabled;
607
616
  /**
608
617
  * The saved answer to "which doors into the market are open" (#1015).
@@ -737,6 +746,8 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
737
746
  updateNotifications.setEnabled(fresh.backgroundUpdateChecks === true);
738
747
  updateNotifications.setIntervalHours(fresh.backgroundUpdateIntervalHours ?? DEFAULT_UPDATE_CHECK_INTERVAL_HOURS);
739
748
  marketState.githubProxy = fresh.githubProxy;
749
+ marketState.userCatalogs = fresh.userCatalogs;
750
+ setUserCatalogs(fresh.userCatalogs ?? []);
740
751
  // A restore or an external writer can change these two too; a stale copy
741
752
  // here would put the old answer back on the next whole-state save (#435).
742
753
  marketState.settingsSection = fresh.settingsSection;
@@ -3249,7 +3260,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3249
3260
  path: '/dsh-market/telemetry',
3250
3261
  handler: async (request, response) => {
3251
3262
  if (request.method === 'GET') {
3252
- sendJson(response, 200, { enabled: readTelemetryState().enabled });
3263
+ sendJson(response, 200, { enabled: readTelemetryState().enabled && getPolicy().telemetry !== false, ...(getPolicy().telemetry === false ? { locked: true } : {}) });
3253
3264
  return;
3254
3265
  }
3255
3266
  if (request.method !== 'POST') {
@@ -3261,6 +3272,10 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3261
3272
  sendJson(response, 403, { error: 'untrusted origin' });
3262
3273
  return;
3263
3274
  }
3275
+ if (getPolicy().telemetry === false) {
3276
+ sendJson(response, 403, { ok: false, code: 'locked', error: '你的组织已关闭匿名使用统计,这里不能改。 / Your organization turned the anonymous count off; it cannot be changed here.' });
3277
+ return;
3278
+ }
3264
3279
  try {
3265
3280
  const body = await readJsonBody(request);
3266
3281
  if (body === null || typeof body !== 'object' || typeof body.enabled !== 'boolean') {
@@ -4082,6 +4097,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4082
4097
  const registry = await loadRegistry();
4083
4098
  sendJson(response, 200, {
4084
4099
  registry: discoveryCatalog(registry).response,
4100
+ ...(Object.keys(clientPolicy()).length > 0 ? { policy: clientPolicy() } : {}),
4085
4101
  hostVersion: dshHostInfo()?.version ?? null,
4086
4102
  });
4087
4103
  }
@@ -4091,7 +4107,11 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4091
4107
  // reachable one with fewer plugins in it.
4092
4108
  const message = error instanceof Error ? error.message : String(error);
4093
4109
  logEvent('warn', 'registry', `catalog fetch failed: ${message}`);
4094
- sendJson(response, 502, { error: message });
4110
+ sendJson(response, 502, {
4111
+ error: message,
4112
+ // Which source said what, so the page can name the one to fix.
4113
+ ...(error instanceof CatalogLoadError ? { sources: error.sources } : {}),
4114
+ });
4095
4115
  }
4096
4116
  }
4097
4117
  catch (error) {
@@ -5033,6 +5053,213 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5033
5053
  }
5034
5054
  },
5035
5055
  }),
5056
+ /**
5057
+ * The catalogs list in Settings: what is configured and how each source
5058
+ * answered the last read. Never carries a header, a token or a query string.
5059
+ */
5060
+ registerRoute({
5061
+ kind: 'exact',
5062
+ path: '/dsh-market/catalogs',
5063
+ handler: async (request, response) => {
5064
+ if (request.method !== 'GET') {
5065
+ response.writeHead(405, { allow: 'GET' });
5066
+ response.end();
5067
+ return;
5068
+ }
5069
+ try {
5070
+ const config = catalogConfig();
5071
+ let sources = [];
5072
+ if (config.active) {
5073
+ // Reading also refreshes each source's status; a total failure
5074
+ // still carries the per-source answers.
5075
+ sources = await loadRegistry().then(registry => registry.sources ?? [], (error) => (error instanceof CatalogLoadError ? error.sources : []));
5076
+ }
5077
+ sendJson(response, 200, {
5078
+ sources,
5079
+ publicCatalog: { enabled: config.publicEnabled, locked: config.policy.publicCatalog === false },
5080
+ userCatalogsAllowed: config.policy.userCatalogs,
5081
+ limit: MAX_USER_CATALOGS,
5082
+ problems: config.policy.problems,
5083
+ });
5084
+ }
5085
+ catch (error) {
5086
+ sendJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
5087
+ }
5088
+ },
5089
+ }),
5090
+ /**
5091
+ * Add a catalog of the user's own: one URL or absolute file path, read
5092
+ * once to prove it is a catalog, then saved. Refused wholesale while the
5093
+ * organization's policy says users may not add catalogs.
5094
+ */
5095
+ registerRoute({
5096
+ kind: 'exact',
5097
+ path: '/dsh-market/catalogs/add',
5098
+ handler: async (request, response) => {
5099
+ if (request.method !== 'POST') {
5100
+ response.writeHead(405, { allow: 'POST' });
5101
+ response.end();
5102
+ return;
5103
+ }
5104
+ if (!sameOrigin(request)) {
5105
+ sendJson(response, 403, { error: 'untrusted origin' });
5106
+ return;
5107
+ }
5108
+ try {
5109
+ await withMutationQueued(async () => {
5110
+ if (!getPolicy().userCatalogs) {
5111
+ sendJson(response, 403, { ok: false, code: 'locked', error: '你的组织不允许添加目录 / your organization does not allow adding catalogs' });
5112
+ return;
5113
+ }
5114
+ const body = (await readJsonBody(request));
5115
+ const parsed = parseCatalogInput(typeof body?.source === 'string' ? body.source : '');
5116
+ if ('error' in parsed) {
5117
+ sendJson(response, 400, { ok: false, code: parsed.error, error: `invalid catalog address (${parsed.error}) / 目录地址不对` });
5118
+ return;
5119
+ }
5120
+ const state = readMarketState(activeProfileDir);
5121
+ const saved = [...(state.userCatalogs ?? [])];
5122
+ const id = userCatalogId(parsed);
5123
+ if (saved.some(entry => entry.id === id) || catalogConfig().extras.some(source => source.id === id)) {
5124
+ sendJson(response, 409, { ok: false, code: 'duplicate', error: 'this catalog is already added / 这个目录已经添加过了' });
5125
+ return;
5126
+ }
5127
+ if (saved.length >= MAX_USER_CATALOGS) {
5128
+ sendJson(response, 400, { ok: false, code: 'limit', limit: MAX_USER_CATALOGS, error: `at most ${String(MAX_USER_CATALOGS)} catalogs / 最多添加 ${String(MAX_USER_CATALOGS)} 个目录` });
5129
+ return;
5130
+ }
5131
+ // Read it once before keeping it: what is saved is known to work.
5132
+ const probe = await probeCatalog(parsed);
5133
+ if (probe.registry === null) {
5134
+ sendJson(response, 400, { ok: false, code: 'unreadable', source: probe.info.error, error: `could not read the catalog (${probe.info.error?.code ?? 'unknown'}) / 读不了这个目录` });
5135
+ return;
5136
+ }
5137
+ writeMarketState(activeProfileDir, { ...readMarketState(activeProfileDir), userCatalogs: [...saved, { id, ...parsed }] });
5138
+ refreshMarketState();
5139
+ forgetCatalog();
5140
+ invalidateUpdates();
5141
+ logEvent('info', 'catalog', `added catalog ${id} (${probe.info.where}), ${String(probe.info.count)} plugins`);
5142
+ sendJson(response, 200, { ok: true, id, count: probe.info.count, label: probe.info.label });
5143
+ });
5144
+ }
5145
+ catch (error) {
5146
+ sendJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
5147
+ }
5148
+ },
5149
+ }),
5150
+ /**
5151
+ * Import an offline bundle: the request body IS the archive. It is
5152
+ * unpacked under the market's own directory with strict rules (see
5153
+ * offline.ts), read once as a catalog, and only then saved as one of the
5154
+ * user's catalogs.
5155
+ */
5156
+ registerRoute({
5157
+ kind: 'exact',
5158
+ path: '/dsh-market/offline/import',
5159
+ handler: async (request, response) => {
5160
+ if (request.method !== 'POST') {
5161
+ response.writeHead(405, { allow: 'POST' });
5162
+ response.end();
5163
+ return;
5164
+ }
5165
+ if (!sameOrigin(request)) {
5166
+ sendJson(response, 403, { error: 'untrusted origin' });
5167
+ return;
5168
+ }
5169
+ try {
5170
+ await withMutationQueued(async () => {
5171
+ if (!getPolicy().userCatalogs) {
5172
+ sendJson(response, 403, { ok: false, code: 'locked', error: '你的组织不允许添加目录 / your organization does not allow adding catalogs' });
5173
+ return;
5174
+ }
5175
+ let archive;
5176
+ try {
5177
+ archive = await readRawBody(request, MAX_BUNDLE_BYTES);
5178
+ }
5179
+ catch {
5180
+ sendJson(response, 413, { ok: false, code: 'too-big', error: 'the bundle is too large / 离线包太大' });
5181
+ return;
5182
+ }
5183
+ let extracted;
5184
+ try {
5185
+ extracted = extractBundle(archive);
5186
+ }
5187
+ catch (error) {
5188
+ const refused = error instanceof BundleError ? error : null;
5189
+ logEvent('warn', 'offline', `bundle refused: ${refused === null ? String(error) : `${refused.code} ${refused.detail}`}`);
5190
+ sendJson(response, 400, { ok: false, code: refused?.code ?? 'not-archive', detail: refused?.detail ?? '', error: 'not a usable offline bundle / 这不是可用的离线包' });
5191
+ return;
5192
+ }
5193
+ const entry = { file: extracted.catalogFile };
5194
+ const probe = await probeCatalog(entry);
5195
+ if (probe.registry === null) {
5196
+ rmSync(extracted.dir, { recursive: true, force: true });
5197
+ sendJson(response, 400, { ok: false, code: 'unreadable', source: probe.info.error, error: 'the bundle has no readable catalog / 离线包里的目录读不了' });
5198
+ return;
5199
+ }
5200
+ const state = readMarketState(activeProfileDir);
5201
+ const id = userCatalogId(entry);
5202
+ const saved = (state.userCatalogs ?? []).filter(item => item.id !== id);
5203
+ if (saved.length >= MAX_USER_CATALOGS) {
5204
+ rmSync(extracted.dir, { recursive: true, force: true });
5205
+ sendJson(response, 400, { ok: false, code: 'limit', limit: MAX_USER_CATALOGS, error: `at most ${String(MAX_USER_CATALOGS)} catalogs / 最多添加 ${String(MAX_USER_CATALOGS)} 个目录` });
5206
+ return;
5207
+ }
5208
+ writeMarketState(activeProfileDir, { ...state, userCatalogs: [...saved, { id, ...entry }] });
5209
+ refreshMarketState();
5210
+ forgetCatalog();
5211
+ invalidateUpdates();
5212
+ logEvent('info', 'offline', `imported bundle ${extracted.id}: ${String(probe.info.count)} plugins, ${String(extracted.files)} files`);
5213
+ sendJson(response, 200, { ok: true, id, count: probe.info.count, label: probe.info.label });
5214
+ });
5215
+ }
5216
+ catch (error) {
5217
+ sendJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
5218
+ }
5219
+ },
5220
+ }),
5221
+ registerRoute({
5222
+ kind: 'exact',
5223
+ path: '/dsh-market/catalogs/remove',
5224
+ handler: async (request, response) => {
5225
+ if (request.method !== 'POST') {
5226
+ response.writeHead(405, { allow: 'POST' });
5227
+ response.end();
5228
+ return;
5229
+ }
5230
+ if (!sameOrigin(request)) {
5231
+ sendJson(response, 403, { error: 'untrusted origin' });
5232
+ return;
5233
+ }
5234
+ try {
5235
+ await withMutationQueued(async () => {
5236
+ const body = (await readJsonBody(request));
5237
+ const id = typeof body?.id === 'string' ? body.id : '';
5238
+ const state = readMarketState(activeProfileDir);
5239
+ const saved = state.userCatalogs ?? [];
5240
+ // A catalog the organization set is not the user's to remove.
5241
+ if (!saved.some(entry => entry.id === id)) {
5242
+ sendJson(response, 404, { ok: false, error: 'no such catalog / 没有这个目录' });
5243
+ return;
5244
+ }
5245
+ const gone = saved.find(entry => entry.id === id);
5246
+ writeMarketState(activeProfileDir, { ...state, userCatalogs: saved.filter(entry => entry.id !== id) });
5247
+ // An imported bundle is the market's own copy: removing the catalog removes its files.
5248
+ if (gone?.file !== undefined && isInsideOfflineRoot(gone.file)) {
5249
+ rmSync(dirname(gone.file), { recursive: true, force: true });
5250
+ }
5251
+ refreshMarketState();
5252
+ forgetCatalog();
5253
+ invalidateUpdates();
5254
+ logEvent('info', 'catalog', `removed catalog ${id}`);
5255
+ sendJson(response, 200, { ok: true });
5256
+ });
5257
+ }
5258
+ catch (error) {
5259
+ sendJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
5260
+ }
5261
+ },
5262
+ }),
5036
5263
  registerRoute({
5037
5264
  kind: 'exact',
5038
5265
  path: '/dsh-market/favorite',
@@ -5443,7 +5670,9 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5443
5670
  channels: CHANNELS,
5444
5671
  region,
5445
5672
  regions: REGIONS,
5446
- anonymousCount: readTelemetryState().enabled,
5673
+ anonymousCount: readTelemetryState().enabled && getPolicy().telemetry !== false,
5674
+ // Set by the organization: shown, not switchable.
5675
+ anonymousCountLocked: getPolicy().telemetry === false,
5447
5676
  // The padded/PATH- and CI-safe build environment currently pinned
5448
5677
  // (issue #336): composition plus any card-saved override. The card
5449
5678
  // edits exactly what this reports, so the form never shows a stale
@@ -5459,6 +5688,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5459
5688
  githubRoutes: routesFor(region).githubRoutes,
5460
5689
  githubProxyCustom: marketState.githubProxy ?? null,
5461
5690
  githubProxyManaged: githubProxyManaged(),
5691
+ githubProxyByPolicy: githubProxyByPolicy(),
5462
5692
  // Whether the region was decided by the network check rather than
5463
5693
  // by the user — the card explains a choice it made on their behalf
5464
5694
  // exactly once, so nobody has to wonder why downloads moved.
@@ -6217,15 +6447,17 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6217
6447
  }
6218
6448
  }
6219
6449
  if (desktopStable) {
6220
- const endpointLatest = await fetchNpmLatest(name);
6450
+ const endpointLatest = await fetchRegistryLatest(name);
6451
+ // What the organization allows as the newest, when it pinned one.
6452
+ const orgNewest = pinnedVersion(name) ?? endpointLatest;
6221
6453
  // Repeated legacy requests are already complete. An explicit
6222
6454
  // client target must still pass the stale-target checks below.
6223
- if (body.eligibleVersion === undefined && compatVersion === null && endpointLatest === installedVersion) {
6455
+ if (body.eligibleVersion === undefined && compatVersion === null && orgNewest === installedVersion) {
6224
6456
  invalidateUpdates();
6225
6457
  sendJson(response, 200, { ok: true, skipped: 'current', name, version: installedVersion });
6226
6458
  return;
6227
6459
  }
6228
- const eligible = await resolveDesktopMatureUpdate(name, installedVersion, config.profile, activeProfileDir, endpointLatest, compatVersion ?? undefined);
6460
+ const eligible = await resolveDesktopMatureUpdate(name, installedVersion, config.profile, activeProfileDir, endpointLatest, compatVersion ?? pinnedVersion(name));
6229
6461
  if (body.eligibleVersion !== undefined && body.eligibleVersion !== eligible.candidate) {
6230
6462
  invalidateUpdates();
6231
6463
  sendJson(response, 409, {
@@ -6245,7 +6477,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6245
6477
  // Older clients have no target token. They may still install
6246
6478
  // a mature latest, but cannot silently get a different build
6247
6479
  // from the version their UI presented.
6248
- if (compatVersion === null && body.eligibleVersion === undefined && eligible.candidate !== endpointLatest) {
6480
+ if (compatVersion === null && body.eligibleVersion === undefined && eligible.candidate !== orgNewest) {
6249
6481
  invalidateUpdates();
6250
6482
  sendJson(response, 409, { staleTarget: true, error: '当前最新版仍在等待期;请刷新市场以确认可安装的成熟版本。 / The latest release is held. Refresh the market to confirm the exact mature target.' });
6251
6483
  return;
@@ -8617,7 +8849,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
8617
8849
  // A release the user picked from the refusal dialog's own search
8618
8850
  // (#581): it was confirmed compatible by /dsh-market/find-compatible,
8619
8851
  // so it is pinned below instead of resolving `latest` again.
8620
- const requestedVersion = typeof body.version === 'string' && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(body.version)
8852
+ let requestedVersion = typeof body.version === 'string' && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(body.version)
8621
8853
  ? body.version
8622
8854
  : null;
8623
8855
  const registry = await loadRegistry();
@@ -8627,6 +8859,19 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
8627
8859
  sendJson(response, 400, { error: 'plugin is not in the curated registry' });
8628
8860
  return;
8629
8861
  }
8862
+ // The list above is already narrowed by the policy's `allow`; asked
8863
+ // again here so this route does not depend on that happening
8864
+ // upstream (the check that matters is the one next to the install).
8865
+ if (!entryAllowed(entry, getPolicy().allow)) {
8866
+ logEvent('warn', 'install-rejected', `not allowed by policy: ${entry.name}`);
8867
+ sendJson(response, 403, { error: '你的组织不允许安装这个插件 / your organization does not allow installing this plugin' });
8868
+ return;
8869
+ }
8870
+ // The organization fixed this package's version: that exact release
8871
+ // installs, whatever the page asked for.
8872
+ const orgPin = typeof entry.npm === 'string' ? pinnedVersion(entry.npm) : undefined;
8873
+ if (orgPin !== undefined)
8874
+ requestedVersion = orgPin;
8630
8875
  const plainTarget = installTargetFor(entry);
8631
8876
  if (plainTarget === null) {
8632
8877
  sendJson(response, 400, { error: 'unsupported source url' });
package/lib/sources.js CHANGED
@@ -504,9 +504,27 @@ export function pinnedAllowBuildsKeys(name, spec, sha) {
504
504
  * @returns the target spec, or null when the source url is unsupported.
505
505
  */
506
506
  export function installTargetFor(entry) {
507
+ // An entry from an offline bundle installs from the package file that came
508
+ // with it. The path was resolved and checked when the catalog was read.
509
+ if (entry.source !== undefined && typeof entry.offlineTarball === 'string' && entry.offlineTarball !== '')
510
+ return `file:${entry.offlineTarball}`;
511
+ const hasNpm = typeof entry.npm === 'string' && NPM_NAME_RE.test(entry.npm);
512
+ if (entry.source !== undefined && !hasNpm && typeof entry.git === 'string' && /^git\+(?:https?|ssh):\/\//u.test(entry.git))
513
+ return entry.git;
507
514
  const source = parseSourceUrl(entry.url);
508
- if (source === null)
509
- return null;
515
+ if (source === null) {
516
+ // An entry from a catalog the organization or the user added may link to
517
+ // anywhere (an internal repository host, a docs page). `source` is stamped
518
+ // by the market after merging and never read from a catalog's own text, so
519
+ // its presence means "a configured catalog listed this"; the install is
520
+ // then an ordinary registry install of that package.
521
+ if (entry.source === undefined)
522
+ return null;
523
+ if (typeof entry.npm === 'string' && NPM_NAME_RE.test(entry.npm))
524
+ return entry.npm;
525
+ // No registry name: an internal repository, as normalized when the catalog was read.
526
+ return typeof entry.git === 'string' && /^git\+(?:https?|ssh):\/\//u.test(entry.git) ? entry.git : null;
527
+ }
510
528
  // The market manages its own installation and is published to npm. Keep
511
529
  // legacy catalog snapshots and self-update requests on that prebuilt
512
530
  // registry package even when the entry has not yet gained its generated
package/lib/telemetry.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { getPolicy } from './policy.js';
1
2
  import { randomBytes } from 'node:crypto';
2
3
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
4
  import { dirname, join } from 'node:path';
@@ -49,6 +50,9 @@ export function setTelemetryEnabled(enabled, file = telemetryFile()) {
49
50
  const utcDay = (now) => new Date(now).toISOString().slice(0, 10);
50
51
  /** Why nothing may be sent right now, or null. Explicit opt-outs always win. */
51
52
  export function suppressedBy(env) {
53
+ // An organization that forbids the count wins over the user's own switch.
54
+ if (getPolicy().telemetry === false)
55
+ return 'organization policy';
52
56
  if (env.DSH_MARKET_TELEMETRY === '0')
53
57
  return 'DSH_MARKET_TELEMETRY=0';
54
58
  if (env.DO_NOT_TRACK === '1')
@@ -74,4 +74,4 @@ file?: string): Promise<{
74
74
  * @param pkg - package name.
75
75
  * @param file - exact entry name inside the tarball (`package/cordis.patch.yml`).
76
76
  */
77
- export declare function packageFileFromRegistry(registry: string, pkg: string, file: string): Promise<Buffer | null>;
77
+ export declare function packageFileFromRegistry(base: string, pkg: string, file: string): Promise<Buffer | null>;
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Catalog sources beyond the public one: an organization's own list of
3
+ * plugins, in the same shape as the public `plugins.json`.
4
+ *
5
+ * Where they come from:
6
+ * - the policy file's `catalogs` (locked; the user cannot remove them), and
7
+ * - the user's own, added in the market's settings (stored in the profile's
8
+ * market state) unless the policy says `"userCatalogs": false`.
9
+ *
10
+ * This module holds everything about them EXCEPT the public catalog, whose
11
+ * fetch path (and its 304 validator) stays in src/registry.ts exactly as it
12
+ * was. `loadRegistry` there calls in here only when something is configured;
13
+ * with nothing configured it never gets here, which is what makes "no policy,
14
+ * no user catalogs" the same requests as before.
15
+ *
16
+ * ## Failure
17
+ *
18
+ * A source that cannot be read costs the user that source, not the market:
19
+ * every source is fetched on its own, what loaded is merged, and each failure
20
+ * is reported per source as a code plus detail (`SourceError`) for the UI to
21
+ * say in the user's language. Secrets: header values and `.npmrc` tokens are
22
+ * never put into a message — {@link scrub} removes any configured header value
23
+ * and URL credentials from every failure text before it leaves this module.
24
+ */
25
+ import { type LocalizedLabel, type Policy } from './policy.ts';
26
+ import type { Registry, RegistryPlugin } from './registry.ts';
27
+ /** A saved user catalog: a URL or an absolute file path, nothing secret. */
28
+ export interface UserCatalog {
29
+ id: string;
30
+ url?: string;
31
+ file?: string;
32
+ }
33
+ export declare const MAX_USER_CATALOGS = 8;
34
+ export type SourceErrorCode = 'network' | 'timeout' | 'auth' | 'http' | 'invalid' | 'empty' | 'file' | 'env' | 'policy';
35
+ /** What went wrong with one source: a code the UI words, plus a short detail. */
36
+ export interface SourceError {
37
+ code: SourceErrorCode;
38
+ detail: string;
39
+ }
40
+ /** What the settings list and the Discover banner know about one source. No secrets, ever. */
41
+ export interface SourceInfo {
42
+ id: string;
43
+ kind: 'public' | 'policy' | 'user';
44
+ label: LocalizedLabel;
45
+ /** Host and path (or file path) for display; no credentials, no query. */
46
+ where: string;
47
+ /** `off`: the policy turned the public catalog off. */
48
+ status: 'ok' | 'failed' | 'off';
49
+ count: number;
50
+ /** Entries skipped because they were not usable (no name, no link, no category). */
51
+ skipped: number;
52
+ error?: SourceError;
53
+ /** Set by the organization: the user cannot remove or switch it. */
54
+ locked: boolean;
55
+ /** Its entries install from package files shipped with it, not from a registry. */
56
+ offline?: true;
57
+ }
58
+ /** The public catalog's label, as plugin cards and the source list show it. */
59
+ export declare const PUBLIC_LABEL: LocalizedLabel;
60
+ /** A source ready to fetch: what to read, and the headers it needs. */
61
+ export interface ExtraSource {
62
+ id: string;
63
+ kind: 'policy' | 'user';
64
+ label: LocalizedLabel;
65
+ url?: string;
66
+ file?: string;
67
+ /** Unexpanded; `${ENV}` is expanded per request. */
68
+ headers: Record<string, string>;
69
+ }
70
+ /** Replace the user's saved catalogs (read from the profile's market state). */
71
+ export declare function setUserCatalogs(list: readonly UserCatalog[]): void;
72
+ export declare function currentUserCatalogs(): readonly UserCatalog[];
73
+ export interface CatalogConfig {
74
+ policy: Policy;
75
+ publicEnabled: boolean;
76
+ extras: ExtraSource[];
77
+ /** Anything beyond "the public catalog and nothing else". */
78
+ active: boolean;
79
+ /** Changes whenever what would be fetched (or filtered) changes. */
80
+ signature: string;
81
+ }
82
+ /** Host name or file name: a label for a catalog that did not name itself. */
83
+ export declare function fallbackLabel(entry: Pick<UserCatalog, 'url' | 'file'>): LocalizedLabel;
84
+ /** The sources and filters in force right now. Cheap: the policy is cached. */
85
+ export declare function catalogConfig(): CatalogConfig;
86
+ /** Remove URL credentials, query strings, and any configured header value from a text. */
87
+ export declare function scrub(text: string, secrets?: readonly string[]): string;
88
+ /** The plain location of a source for display: host and path, or the file path. */
89
+ export declare function displayWhere(source: Pick<ExtraSource, 'url' | 'file'>): string;
90
+ /** Drop every validator, so the next read of each source is unconditional. */
91
+ export declare function forgetExtraCatalogs(): void;
92
+ /**
93
+ * A git source an entry may install from, as pnpm's spec, or null.
94
+ *
95
+ * https and ssh remotes (plus plain http for hosts that only speak it), an
96
+ * optional `#ref`. A password in the address is refused: a catalog is shared
97
+ * text, and a secret does not belong in it. ssh keys are the machine's own.
98
+ */
99
+ export declare function normalizeGitSpec(value: unknown): string | null;
100
+ export interface ExtraResult {
101
+ info: SourceInfo;
102
+ registry: Registry | null;
103
+ }
104
+ /** Read one source and report it; never throws. */
105
+ export declare function loadExtra(source: ExtraSource, options?: {
106
+ fresh?: boolean;
107
+ env?: NodeJS.ProcessEnv;
108
+ }): Promise<ExtraResult>;
109
+ /** Whether the policy's `allow` list lets this entry be shown and installed. */
110
+ export declare function entryAllowed(entry: Pick<RegistryPlugin, 'name' | 'npm'>, allow: readonly string[] | null): boolean;
111
+ export interface MergeInput {
112
+ /** The public catalog, or null when it is off or failed. */
113
+ publicRegistry: Registry | null;
114
+ publicInfo: SourceInfo | null;
115
+ /** In priority order: policy catalogs, then the user's. */
116
+ extras: readonly {
117
+ info: SourceInfo;
118
+ registry: Registry | null;
119
+ }[];
120
+ allow: readonly string[] | null;
121
+ /** The administrator's exact-version pins by npm package name. */
122
+ pins?: Readonly<Record<string, string>>;
123
+ }
124
+ /**
125
+ * Combine the sources. Pure.
126
+ *
127
+ * - The same repository URL, or the same npm package, in two sources: the
128
+ * private one wins (earlier private sources before later ones). One plugin
129
+ * must not appear as two cards because two catalogs both list it.
130
+ * - Private entries come first: they are why the organization set this up.
131
+ * - Categories merge; a category id a private entry uses that nothing
132
+ * describes shows under its own id.
133
+ * - `source` is stamped here on every private entry, and removed from public
134
+ * ones, so a catalog cannot pass itself off as another source.
135
+ * - `allow` filters the union; `pins` fix the version an entry shows and installs.
136
+ */
137
+ export declare function mergeSources(input: MergeInput): Registry;
138
+ /** What a person typed into the add box, as a source, or why not. */
139
+ export declare function parseCatalogInput(text: string): {
140
+ url?: string;
141
+ file?: string;
142
+ } | {
143
+ error: 'empty' | 'credentials' | 'unrecognized';
144
+ };
145
+ /** A stable id for a user catalog, so adding the same thing twice is one entry. */
146
+ export declare function userCatalogId(entry: {
147
+ url?: string;
148
+ file?: string;
149
+ }): string;
150
+ /** Read a candidate once, for the add box: the count on success, the reason on failure. */
151
+ export declare function probeCatalog(entry: {
152
+ url?: string;
153
+ file?: string;
154
+ }, env?: NodeJS.ProcessEnv): Promise<ExtraResult>;
155
+ /** The shape the id of a saved catalog must have; stored state is untrusted. */
156
+ export declare function validUserCatalog(value: unknown): UserCatalog | null;
@@ -18,6 +18,7 @@
18
18
  import { type UpdateCheckIntervalHours } from './update-notification-settings.ts';
19
19
  import { type Channel } from './channels.ts';
20
20
  import { type Region } from './regions.ts';
21
+ import { type UserCatalog } from './catalogs.ts';
21
22
  interface HotRow {
22
23
  id: string;
23
24
  name: string;
@@ -191,6 +192,14 @@ export interface MarketState {
191
192
  * pre-install list, unlike groups/notes which target installed packages.
192
193
  */
193
194
  favorites?: string[];
195
+ /**
196
+ * Extra catalogs the user added in the settings card: a URL or an absolute
197
+ * file path each, nothing secret. Optional on the way in like `favorites`
198
+ * (omitted means "the caller has nothing to say"); an explicit empty list
199
+ * is how the last one is removed. Ignored while the policy sets
200
+ * `userCatalogs: false`.
201
+ */
202
+ userCatalogs?: UserCatalog[];
194
203
  /**
195
204
  * Package names the user hid from Discover and Themes (#657).
196
205
  *
@@ -110,5 +110,7 @@ export declare function trustedAuthority(host: string, trustedHosts: readonly st
110
110
  */
111
111
  export declare function loopbackAuthority(host: string | undefined): boolean;
112
112
  export declare function sameOrigin(request: IncomingMessage): boolean;
113
+ /** Read a request body as bytes, refusing anything over `maxBytes` (stops reading as soon as it is over). */
114
+ export declare function readRawBody(request: IncomingMessage, maxBytes: number): Promise<Buffer>;
113
115
  /** Read and parse a JSON request body, rejecting anything over 4 KiB. */
114
116
  export declare function readJsonBody(request: IncomingMessage, maxBytes?: number): Promise<unknown>;
@@ -86,7 +86,7 @@ export declare function configuredProxy(): string | null;
86
86
  * through this module's own agent when it has none. Both paths pass the
87
87
  * dispatcher described on this module.
88
88
  */
89
- export declare function marketFetch(url: string, init?: {
89
+ export declare function marketFetch(url: string, given?: {
90
90
  signal?: AbortSignal;
91
91
  headers?: Record<string, string>;
92
92
  method?: 'GET' | 'HEAD' | 'POST';