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/policy.js ADDED
@@ -0,0 +1,326 @@
1
+ /**
2
+ * The organization policy file: admin-owned, read-only, never written here.
3
+ *
4
+ * Where it lives, first found wins:
5
+ * 1. `DSH_MARKET_POLICY` (an absolute path)
6
+ * 2. macOS / Linux `/etc/dsh-market/policy.json`;
7
+ * Windows `%ProgramData%\dsh-market\policy.json`
8
+ * 3. `<DSH_HOME>/dsh-market/policy.json`
9
+ *
10
+ * "Employees cannot change it" comes from file permissions on 1 and 2 (a file
11
+ * only an administrator can write). Location 3 sits in the user's own home, so
12
+ * it is for single-user setups and enforces nothing against the user.
13
+ *
14
+ * Every field is optional and an absent file means "no policy": the
15
+ * permissive {@link NO_POLICY}, which is what keeps the market exactly as it
16
+ * was for everyone who configures nothing.
17
+ *
18
+ * Adding a field later (pins, telemetry, comments, externalImages) is one
19
+ * entry in {@link readPolicyFields} and one property on {@link Policy}; the
20
+ * location, caching and failure handling below do not change.
21
+ *
22
+ * ## A policy that cannot be read
23
+ *
24
+ * An unreadable file must not quietly turn into "no policy": an administrator
25
+ * who wrote one expects it to hold. So a file that exists but is not valid
26
+ * JSON applies `allow: []` — browsing keeps working, installing is refused —
27
+ * and says so in {@link Policy.problems} so the settings list can show it.
28
+ * A single bad field is ignored on its own and reported; only `allow` fails
29
+ * closed, since a malformed allowlist read as "no allowlist" is the unsafe
30
+ * direction.
31
+ */
32
+ import { existsSync, readFileSync, statSync } from 'node:fs';
33
+ import { isAbsolute, join } from 'node:path';
34
+ import { resolveDshHome } from './home-paths.js';
35
+ /** Split the `中文 / English` form the messages below are written in. */
36
+ function bilingual(text) {
37
+ const at = text.indexOf(' / ');
38
+ return at < 0 ? { zh: text, en: text } : { zh: text.slice(0, at), en: text.slice(at + 3) };
39
+ }
40
+ export const NO_POLICY = Object.freeze({
41
+ path: null,
42
+ catalogs: [],
43
+ publicCatalog: true,
44
+ userCatalogs: true,
45
+ allow: null,
46
+ mirrors: {},
47
+ pins: {},
48
+ telemetry: true,
49
+ comments: true,
50
+ externalImages: true,
51
+ problems: [],
52
+ });
53
+ export const CATALOG_ID_RE = /^[a-z0-9][a-z0-9-]{0,39}$/;
54
+ /** The public catalog's own id: reserved, so a private source can never pose as it. */
55
+ export const PUBLIC_SOURCE_ID = 'public';
56
+ /** Candidate policy files in precedence order. */
57
+ export function policyLocations(env = process.env, platform = process.platform, home = resolveDshHome()) {
58
+ const out = [];
59
+ const explicit = env.DSH_MARKET_POLICY?.trim();
60
+ if (explicit !== undefined && explicit !== '')
61
+ out.push(explicit);
62
+ if (platform === 'win32') {
63
+ const programData = env.ProgramData?.trim();
64
+ if (programData !== undefined && programData !== '')
65
+ out.push(join(programData, 'dsh-market', 'policy.json'));
66
+ }
67
+ else {
68
+ out.push('/etc/dsh-market/policy.json');
69
+ }
70
+ out.push(join(home, 'dsh-market', 'policy.json'));
71
+ return out;
72
+ }
73
+ function isRecord(value) {
74
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
75
+ }
76
+ /** A label is a string or a per-language object; anything else is no label. */
77
+ export function asLabel(value) {
78
+ if (typeof value === 'string' && value.trim() !== '') {
79
+ const text = value.trim().slice(0, 60);
80
+ return { zh: text, en: text };
81
+ }
82
+ if (!isRecord(value))
83
+ return null;
84
+ const out = {};
85
+ for (const [lang, text] of Object.entries(value)) {
86
+ if (typeof text === 'string' && text.trim() !== '')
87
+ out[lang] = text.trim().slice(0, 60);
88
+ }
89
+ return Object.keys(out).length > 0 ? out : null;
90
+ }
91
+ /** The label to show for a language: that language, then English, then anything. */
92
+ export function pickLabel(label, lang) {
93
+ return label[lang] ?? label.en ?? label.zh ?? Object.values(label)[0] ?? '';
94
+ }
95
+ function asHttpUrl(value) {
96
+ if (typeof value !== 'string')
97
+ return null;
98
+ try {
99
+ const url = new URL(value.trim());
100
+ return url.protocol === 'https:' || url.protocol === 'http:' ? url.href : null;
101
+ }
102
+ catch {
103
+ return null;
104
+ }
105
+ }
106
+ function readCatalogs(value, problems) {
107
+ if (value === undefined)
108
+ return [];
109
+ if (!Array.isArray(value)) {
110
+ problems.push('"catalogs" 不是列表,已忽略 / "catalogs" is not a list and was ignored');
111
+ return [];
112
+ }
113
+ const out = [];
114
+ const seen = new Set([PUBLIC_SOURCE_ID]);
115
+ for (const [index, raw] of value.entries()) {
116
+ const where = `catalogs[${String(index)}]`;
117
+ if (!isRecord(raw)) {
118
+ problems.push(`${where} 不是对象,已忽略 / ${where} is not an object and was ignored`);
119
+ continue;
120
+ }
121
+ const id = typeof raw.id === 'string' ? raw.id : '';
122
+ if (!CATALOG_ID_RE.test(id) || seen.has(id)) {
123
+ problems.push(`${where} 的 id 不合法或重复,已忽略 / ${where} has an invalid or duplicate id and was ignored`);
124
+ continue;
125
+ }
126
+ const url = raw.url === undefined ? undefined : asHttpUrl(raw.url);
127
+ const file = typeof raw.file === 'string' && isAbsolute(raw.file) ? raw.file : undefined;
128
+ if ((url === undefined) === (file === undefined) || url === null) {
129
+ problems.push(`${where}(${id})需要一个 url 或一个绝对路径的 file,已忽略 / ${where} (${id}) needs either a url or an absolute file path and was ignored`);
130
+ continue;
131
+ }
132
+ const headers = {};
133
+ if (isRecord(raw.headers)) {
134
+ for (const [name, text] of Object.entries(raw.headers)) {
135
+ if (/^[A-Za-z0-9-]+$/u.test(name) && typeof text === 'string')
136
+ headers[name] = text;
137
+ }
138
+ }
139
+ seen.add(id);
140
+ out.push({
141
+ id,
142
+ label: asLabel(raw.label) ?? { zh: id, en: id },
143
+ ...(url !== undefined ? { url } : {}),
144
+ ...(file !== undefined ? { file } : {}),
145
+ headers,
146
+ });
147
+ }
148
+ return out;
149
+ }
150
+ function readAllow(value, problems) {
151
+ if (value === undefined)
152
+ return null;
153
+ if (!Array.isArray(value) || value.some(item => typeof item !== 'string')) {
154
+ // The unsafe reading of a broken allowlist is "no allowlist".
155
+ problems.push('"allow" 不是文字列表,现在不能安装任何插件 / "allow" is not a list of strings, so nothing can be installed right now');
156
+ return [];
157
+ }
158
+ return value.map(item => item.trim()).filter(item => item !== '');
159
+ }
160
+ function readMirrors(value, problems) {
161
+ if (value === undefined)
162
+ return {};
163
+ if (!isRecord(value)) {
164
+ problems.push('"mirrors" 不是对象,已忽略 / "mirrors" is not an object and was ignored');
165
+ return {};
166
+ }
167
+ const out = {};
168
+ for (const key of ['catalog', 'npm', 'githubProxy']) {
169
+ const raw = value[key];
170
+ if (raw === undefined)
171
+ continue;
172
+ const url = asHttpUrl(raw);
173
+ if (url === null) {
174
+ problems.push(`mirrors.${key} 不是有效的网址,已忽略 / mirrors.${key} is not a valid URL and was ignored`);
175
+ continue;
176
+ }
177
+ out[key] = url.replace(/\/+$/u, '');
178
+ }
179
+ return out;
180
+ }
181
+ const VERSION_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u;
182
+ const PIN_NAME_RE = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/u;
183
+ function readPins(value, problems) {
184
+ if (value === undefined)
185
+ return {};
186
+ if (!isRecord(value)) {
187
+ problems.push('"pins" 不是对象,已忽略 / "pins" is not an object and was ignored');
188
+ return {};
189
+ }
190
+ const out = {};
191
+ for (const [name, version] of Object.entries(value)) {
192
+ if (!PIN_NAME_RE.test(name) || typeof version !== 'string' || !VERSION_RE.test(version)) {
193
+ problems.push(`pins 里的「${name}」需要一个 npm 包名和一个完整版本号(如 1.2.3),已忽略 / the pin for "${name}" needs an npm package name and an exact version such as 1.2.3 and was ignored`);
194
+ continue;
195
+ }
196
+ out[name] = version;
197
+ }
198
+ return out;
199
+ }
200
+ /** The exact version an administrator pinned this npm package to, if any. */
201
+ export function pinnedVersion(name, policy = getPolicy()) {
202
+ if (typeof name !== 'string' || name === '')
203
+ return undefined;
204
+ const key = name.toLowerCase();
205
+ for (const [pinned, version] of Object.entries(policy.pins)) {
206
+ if (pinned.toLowerCase() === key)
207
+ return version;
208
+ }
209
+ return undefined;
210
+ }
211
+ /** Interpret a parsed policy document. Pure. */
212
+ export function readPolicyFields(doc, path) {
213
+ if (!isRecord(doc)) {
214
+ return { ...NO_POLICY, path, allow: [], problems: [bilingual('策略文件的内容不是一个 JSON 对象,现在不能安装任何插件 / The policy file is not a JSON object, so nothing can be installed right now')] };
215
+ }
216
+ const problems = [];
217
+ const flag = (key) => {
218
+ const raw = doc[key];
219
+ if (raw === undefined || typeof raw === 'boolean')
220
+ return raw !== false;
221
+ problems.push(`"${key}" 应该是 true 或 false,已忽略 / "${key}" should be true or false and was ignored`);
222
+ return true;
223
+ };
224
+ return {
225
+ path,
226
+ catalogs: readCatalogs(doc.catalogs, problems),
227
+ publicCatalog: flag('publicCatalog'),
228
+ userCatalogs: flag('userCatalogs'),
229
+ allow: readAllow(doc.allow, problems),
230
+ mirrors: readMirrors(doc.mirrors, problems),
231
+ pins: readPins(doc.pins, problems),
232
+ telemetry: flag('telemetry'),
233
+ comments: flag('comments'),
234
+ externalImages: flag('externalImages'),
235
+ problems: problems.map(bilingual),
236
+ };
237
+ }
238
+ /** Read the first policy file that exists. Pure apart from the file reads. */
239
+ export function loadPolicy(env = process.env, platform = process.platform, home = resolveDshHome()) {
240
+ const path = policyLocations(env, platform, home).find(candidate => existsSync(candidate));
241
+ if (path === undefined)
242
+ return NO_POLICY;
243
+ try {
244
+ return readPolicyFields(JSON.parse(readFileSync(path, 'utf8')), path);
245
+ }
246
+ catch (error) {
247
+ const why = error instanceof Error ? error.message : String(error);
248
+ return {
249
+ ...NO_POLICY,
250
+ path,
251
+ allow: [],
252
+ problems: [{
253
+ zh: `策略文件 ${path} 读不了:${why.slice(0, 160)}。出于安全,现在不能安装任何插件,浏览不受影响。请联系管理员修好这个文件。`,
254
+ en: `The policy file ${path} could not be read: ${why.slice(0, 160)}. For safety nothing can be installed right now; browsing still works. Ask your administrator to fix this file.`,
255
+ }],
256
+ };
257
+ }
258
+ }
259
+ const RECHECK_MS = 2_000;
260
+ let cached = null;
261
+ /**
262
+ * The policy in force, re-read when the file changes. A stat per couple of
263
+ * seconds rather than per request: the callers sit on hot paths (every
264
+ * outbound request asks for the mirrors).
265
+ */
266
+ export function getPolicy(env = process.env, now = performance.now()) {
267
+ const home = resolveDshHome(undefined, env);
268
+ const candidates = policyLocations(env, process.platform, home);
269
+ const where = candidates.join('|');
270
+ if (cached !== null && cached.where === where && now - cached.at < RECHECK_MS)
271
+ return cached.policy;
272
+ const stamp = candidates.map(candidate => {
273
+ try {
274
+ const info = statSync(candidate);
275
+ return `${candidate}:${String(info.mtimeMs)}:${String(info.size)}`;
276
+ }
277
+ catch {
278
+ return `${candidate}:-`;
279
+ }
280
+ }).join('|');
281
+ if (cached !== null && cached.key === stamp) {
282
+ cached = { ...cached, at: now, where };
283
+ return cached.policy;
284
+ }
285
+ const policy = loadPolicy(env, process.platform, home);
286
+ cached = { at: now, key: stamp, where, policy };
287
+ return policy;
288
+ }
289
+ /** Forget the cached policy (tests, and after a deliberate re-read). */
290
+ export function resetPolicyCache() {
291
+ cached = null;
292
+ }
293
+ /**
294
+ * Expand `${NAME}` from the environment, the way npm does. Names with no value
295
+ * are reported rather than silently becoming empty, so the caller can say
296
+ * which variable is missing instead of sending a half-made credential.
297
+ */
298
+ export function expandEnv(text, env = process.env) {
299
+ const missing = [];
300
+ const value = text.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/gu, (_match, name) => {
301
+ const found = env[name];
302
+ if (found === undefined || found === '') {
303
+ if (!missing.includes(name))
304
+ missing.push(name);
305
+ return '';
306
+ }
307
+ return found;
308
+ });
309
+ return { value, missing };
310
+ }
311
+ /** Glob match with `*` only, case-insensitive (npm names are lowercase). */
312
+ export function globMatch(pattern, text) {
313
+ const re = new RegExp(`^${pattern.split('*').map(part => part.replace(/[.+?^${}()|[\]\\]/gu, String.raw `\$&`)).join('.*')}$`, 'iu');
314
+ return re.test(text);
315
+ }
316
+ /**
317
+ * What the browser needs to know to reflect the policy: only the switches an
318
+ * administrator turned OFF. Empty — and so absent from the response — for
319
+ * everyone with no policy. The server enforces; the page only follows.
320
+ */
321
+ export function clientPolicy(policy = getPolicy()) {
322
+ return {
323
+ ...(policy.externalImages ? {} : { externalImages: false }),
324
+ ...(policy.comments ? {} : { comments: false }),
325
+ };
326
+ }
package/lib/regions.js CHANGED
@@ -18,6 +18,7 @@
18
18
  * fallbacks; those come and go, and a user whose routes have died needs a way
19
19
  * out that is not "wait for the next release".
20
20
  */
21
+ import { getPolicy } from './policy.js';
21
22
  /** Every region a user may pick. */
22
23
  export const REGIONS = ['global', 'china'];
23
24
  /** Narrow an untrusted value to a Region, or null. */
@@ -211,9 +212,18 @@ export function setCustomGithubProxy(proxy) {
211
212
  customGithubProxy = next;
212
213
  resetGithubRoutePreferences();
213
214
  }
215
+ /** The policy's GitHub prefix, when it names a usable one. */
216
+ function policyGithubProxy() {
217
+ const value = getPolicy().mirrors.githubProxy;
218
+ return value === undefined ? null : normalizeGithubProxy(value);
219
+ }
220
+ /** Whether an administrator's policy (not just the environment) fixed the GitHub route. */
221
+ export function githubProxyByPolicy() {
222
+ return policyGithubProxy() !== null;
223
+ }
214
224
  /** Whether the operator-owned environment variable disables UI changes. */
215
225
  export function githubProxyManaged(env = process.env) {
216
- return override(env, 'DSHM_GITHUB_PROXY') !== null;
226
+ return policyGithubProxy() !== null || override(env, 'DSHM_GITHUB_PROXY') !== null;
217
227
  }
218
228
  /** Remember one verified route without changing other GitHub services. */
219
229
  export function rememberGithubRoute(service, route) {
@@ -258,9 +268,12 @@ function withCustomProxy(proxy, base) {
258
268
  */
259
269
  export function routesFor(region, env = process.env) {
260
270
  const base = ROUTES[region];
261
- const npmMirror = override(env, 'DSHM_NPM_MIRROR');
262
- const githubProxy = override(env, 'DSHM_GITHUB_PROXY') ?? customGithubProxy;
263
- const catalog = override(env, 'DSHM_REGISTRY_URL');
271
+ // An administrator's policy outranks the environment and the region: it is
272
+ // the one setting a user cannot be left to override (src/policy.ts).
273
+ const mirrors = getPolicy().mirrors;
274
+ const npmMirror = mirrors.npm ?? override(env, 'DSHM_NPM_MIRROR');
275
+ const githubProxy = policyGithubProxy() ?? override(env, 'DSHM_GITHUB_PROXY') ?? customGithubProxy;
276
+ const catalog = mirrors.catalog ?? override(env, 'DSHM_REGISTRY_URL');
264
277
  const registry = npmMirror ?? base.npmRegistry;
265
278
  const githubRoutes = githubProxy === null
266
279
  ? {
package/lib/registry.js CHANGED
@@ -8,6 +8,7 @@ import { configuredProxy, marketFetch } from './net.js';
8
8
  import { catalogFromPackage } from './catalog-npm.js';
9
9
  import { activeRegion, catalogSourcesFor, routesFor } from './regions.js';
10
10
  import { NPM_NAME_RE } from './sources.js';
11
+ import { catalogConfig, forgetExtraCatalogs, loadExtra, mergeSources, PUBLIC_LABEL, } from './catalogs.js';
11
12
  /**
12
13
  * How long a successful catalog load may take before it leaves a line behind.
13
14
  *
@@ -138,6 +139,9 @@ function asRegistry(value) {
138
139
  export function forgetCatalog() {
139
140
  served = null;
140
141
  pendingCatalog = null;
142
+ pendingMerged = null;
143
+ lastMerged = null;
144
+ forgetExtraCatalogs();
141
145
  catalogRevision += 1;
142
146
  }
143
147
  /**
@@ -161,7 +165,7 @@ export function forgetCatalog() {
161
165
  * would rebuild exactly the fallback this replaced.
162
166
  * @throws when the catalog cannot be fetched or does not look like one.
163
167
  */
164
- export function loadRegistry(region = activeRegion()) {
168
+ function loadPublicCatalog(region) {
165
169
  const ownSources = routesFor(region).catalog.length;
166
170
  const catalogSources = catalogSourcesFor(region);
167
171
  const key = JSON.stringify([region, ownSources, catalogSources.map(sourceKey)]);
@@ -175,6 +179,89 @@ export function loadRegistry(region = activeRegion()) {
175
179
  pendingCatalog = { key, result };
176
180
  return result;
177
181
  }
182
+ /** Every source failed (or the only one did): the message for the page, and what each source said. */
183
+ export class CatalogLoadError extends Error {
184
+ sources;
185
+ constructor(message, sources) {
186
+ super(message);
187
+ this.name = 'CatalogLoadError';
188
+ this.sources = sources;
189
+ }
190
+ }
191
+ let pendingMerged = null;
192
+ /** The last merge, reused while none of its inputs changed (callers key caches on the object). */
193
+ let lastMerged = null;
194
+ /**
195
+ * The catalog, revalidated on each new load: the public catalog plus whatever
196
+ * the organization's policy and the user added.
197
+ *
198
+ * With nothing configured this IS {@link loadPublicCatalog} — the same
199
+ * requests, the same object — which is the promise that a user with no policy
200
+ * and no extra catalogs sees no change. Otherwise every source is read on its
201
+ * own, in parallel: one that fails costs the user that source and is reported
202
+ * in `sources`, never the others.
203
+ * @throws when nothing could be loaded; {@link CatalogLoadError} carries the per-source detail.
204
+ */
205
+ export function loadRegistry(region = activeRegion()) {
206
+ const config = catalogConfig();
207
+ if (!config.active)
208
+ return loadPublicCatalog(region);
209
+ const key = JSON.stringify([region, config.signature]);
210
+ if (pendingMerged?.key === key)
211
+ return pendingMerged.result;
212
+ const result = loadMerged(region, config).finally(() => {
213
+ if (pendingMerged?.result === result)
214
+ pendingMerged = null;
215
+ });
216
+ pendingMerged = { key, result };
217
+ return result;
218
+ }
219
+ async function loadMerged(region, config) {
220
+ const publicLoad = config.publicEnabled
221
+ ? loadPublicCatalog(region).then(registry => ({ registry }), (error) => ({ error }))
222
+ : null;
223
+ const extras = await Promise.all(config.extras.map(source => loadExtra(source)));
224
+ const publicResult = publicLoad === null ? null : await publicLoad;
225
+ const publicRegistry = publicResult !== null && 'registry' in publicResult ? publicResult.registry : null;
226
+ const publicInfo = {
227
+ id: 'public',
228
+ kind: 'public',
229
+ label: PUBLIC_LABEL,
230
+ where: '',
231
+ status: publicResult === null ? 'off' : publicRegistry !== null ? 'ok' : 'failed',
232
+ count: publicRegistry?.plugins.length ?? 0,
233
+ skipped: 0,
234
+ locked: config.policy.publicCatalog === false,
235
+ ...(publicResult !== null && 'error' in publicResult
236
+ ? { error: { code: 'network', detail: (publicResult.error instanceof Error ? publicResult.error.message : String(publicResult.error)).slice(0, 400) } }
237
+ : {}),
238
+ };
239
+ const loaded = extras.filter(extra => extra.registry !== null);
240
+ if (publicRegistry === null && loaded.length === 0) {
241
+ const sources = [...(publicResult === null ? [] : [publicInfo]), ...extras.map(extra => extra.info)];
242
+ // The public catalog's own explanation reads best when it is the only
243
+ // source there is; otherwise name the first thing that broke.
244
+ const message = publicResult !== null && 'error' in publicResult && config.extras.length === 0
245
+ ? (publicResult.error instanceof Error ? publicResult.error.message : String(publicResult.error))
246
+ : sources.map(source => `${source.id}: ${source.error?.code ?? 'off'}${source.error?.detail ? ` ${source.error.detail}` : ''}`).join(' · ');
247
+ throw new CatalogLoadError(message === '' ? 'no catalog is available' : message, sources);
248
+ }
249
+ const inputs = [publicRegistry, ...extras.map(extra => extra.registry)];
250
+ const stamp = JSON.stringify([config.policy.allow, config.policy.pins, publicInfo, extras.map(extra => extra.info)]);
251
+ if (lastMerged !== null && lastMerged.allow === stamp
252
+ && lastMerged.inputs.length === inputs.length && lastMerged.inputs.every((value, index) => value === inputs[index])) {
253
+ return lastMerged.out;
254
+ }
255
+ const out = mergeSources({
256
+ publicRegistry,
257
+ publicInfo: publicResult === null ? null : publicInfo,
258
+ extras,
259
+ allow: config.policy.allow,
260
+ pins: config.policy.pins,
261
+ });
262
+ lastMerged = { inputs, allow: stamp, out };
263
+ return out;
264
+ }
178
265
  async function fetchCatalog(region, ownSources, catalogSources, revision) {
179
266
  const started = Date.now();
180
267
  const previous = served;