dsh-clash-subscription 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -68,6 +68,13 @@ const en = {
68
68
  requiredProbesHint: 'Comma-separated probe ids a node must reach, e.g. openai, google. Empty means every probe. Built-ins: gstatic, google, openai, anthropic.',
69
69
  probes: 'Extra probes',
70
70
  probesHint: 'One id=url per line, for services the built-in list does not cover. Example: hf=https://huggingface.co',
71
+ blocked: 'Blocked nodes',
72
+ blockedLabel: 'Hide these nodes',
73
+ blockedHint: 'One per line. A plain name is matched exactly; /regex/flags removes a whole group. Hidden nodes are removed by the core itself, so nothing can select or route to them.',
74
+ blockedPlaceholder: '香港高倍02 3x流量\n/^🇺🇸/',
75
+ blockedTag: 'blocked',
76
+ blockedCount: '{count} nodes hidden',
77
+ blockedInvalid: 'Invalid regex, not applied:',
71
78
  reselect: 'Re-pick node by capability',
72
79
  reselecting: 'Testing nodes…',
73
80
  chosenNode: 'Chosen: {node}',
@@ -166,6 +173,13 @@ const zh = {
166
173
  requiredProbesHint: '逗号分隔的探测项,节点必须全部可达,例如 openai, google。留空表示全部。内置:gstatic、google、openai、anthropic。',
167
174
  probes: '额外探测',
168
175
  probesHint: '一行一个 id=url,用于补充内置清单之外的服务。例:hf=https://huggingface.co',
176
+ blocked: '屏蔽节点',
177
+ blockedLabel: '屏蔽以下节点',
178
+ blockedHint: '一行一条。写普通名字则精确匹配;写 /正则/标志 可整组屏蔽。屏蔽由内核直接排除,选中、测速、自动挑选都不可能再用到它。',
179
+ blockedPlaceholder: '香港高倍02 3x流量\n/^🇺🇸/',
180
+ blockedTag: '已屏蔽',
181
+ blockedCount: '已屏蔽 {count} 个节点',
182
+ blockedInvalid: '正则无效,未生效:',
169
183
  reselect: '按能力重挑节点',
170
184
  reselecting: '正在测节点…',
171
185
  chosenNode: '已选:{node}',
@@ -325,6 +339,14 @@ function sections(t) {
325
339
  { key: 'probes', kind: 'text', label: t('probes'), hint: t('probesHint'), placeholder: 'hf=https://huggingface.co' },
326
340
  ],
327
341
  },
342
+ {
343
+ id: 'blocklist',
344
+ title: t('blocked'),
345
+ collapsed: true,
346
+ fields: [
347
+ { key: 'blocklist', kind: 'textarea', label: t('blockedLabel'), hint: t('blockedHint'), placeholder: t('blockedPlaceholder') },
348
+ ],
349
+ },
328
350
  {
329
351
  id: 'lists',
330
352
  title: t('lists'),
@@ -543,6 +565,19 @@ function Panel(props) {
543
565
  h('h4', { key: 'ti' }, t('routing')),
544
566
  h('p', { key: 'hi', className: 'clxp-hint' }, t('routingHint')),
545
567
  h('p', { key: 'cu', className: 'clxp-note' }, fill(t('currentNode'), { node: live?.node ?? t('autoSelect') })),
568
+ live?.blocklist !== undefined && live.blocklist.hidden !== undefined && live.blocklist.hidden.length > 0
569
+ ? h('p', { key: 'bh', className: 'clxp-note' }, fill(t('blockedCount'), { count: live.blocklist.hidden.length }) + (live.blocklist.filter === '' ? '' : ' · ' + live.blocklist.filter))
570
+ : null,
571
+ live?.blocklist !== undefined && Array.isArray(live.blocklist.problems) && live.blocklist.problems.length > 0
572
+ ? h('p', { key: 'bp', className: 'clxp-error', role: 'status' }, t('blockedInvalid') + ' ' + live.blocklist.problems.map((p) => p.source).join(', '))
573
+ : null,
574
+ live?.blocklist !== undefined && Array.isArray(live.blocklist.hidden)
575
+ ? h('div', { key: 'bl', className: 'clxp-subs' },
576
+ live.blocklist.hidden.slice(0, 20).map((name) => h('div', { key: name, className: 'clxp-sub' }, [
577
+ h('span', { key: 'n', className: 'clxp-node-name' }, name),
578
+ h('span', { key: 's', className: 'clxp-delay bad' }, t('blockedTag')),
579
+ ])))
580
+ : null,
546
581
  live?.capability !== undefined && Array.isArray(live.capability.nodes) && live.capability.nodes.length > 0
547
582
  ? h('p', { key: 'cp', className: 'clxp-note' }, fill(t('usableCount'), {
548
583
  usable: live.capability.nodes.filter((row) => row.usable).length,
package/index.js CHANGED
@@ -21,6 +21,7 @@ import { installCore, installCoreFromFile, platformKey } from './lib/corefetch.j
21
21
  import { installVendoredCore, vendoredFor } from './lib/vendored.js'
22
22
  import { fetchGeoDatabases, hasGeoDatabase } from './lib/geo.js'
23
23
  import { DEFAULT_PROBES, judgeNode, rankNodes, resolveProbes } from './lib/select.js'
24
+ import { buildExcludeFilter, partitionNodes, validateBlocklist } from './lib/blocklist.js'
24
25
  import { installName, loadHttpProxyModule, locateInstallRoot, resolveFromInstall } from './lib/install.js'
25
26
  import { Routing } from './lib/routing.js'
26
27
  import {
@@ -73,6 +74,11 @@ export const CONFIG_DEFAULTS = {
73
74
  coreVersion: '',
74
75
  /** Fetch GeoIP databases after routing works; they are an upgrade, not a requirement. */
75
76
  autoFetchGeo: true,
77
+ /**
78
+ * Nodes to hide, one per line. A literal name matches exactly; /regex/flags removes a group.
79
+ * The core removes them from its proxy table entirely, so nothing can select or route to them.
80
+ */
81
+ blocklist: '',
76
82
  /** Extra capability probes as `id=url` lines; built-ins cover gstatic/google/openai/anthropic. */
77
83
  probes: '',
78
84
  /**
@@ -126,6 +132,7 @@ async function buildConfigSchema() {
126
132
  autoFetchCore: z.boolean().default(false),
127
133
  coreVersion: z.string().default(''),
128
134
  autoFetchGeo: z.boolean().default(true),
135
+ blocklist: z.string().default(''),
129
136
  probes: z.string().default(''),
130
137
  requiredProbes: z.string().default(''),
131
138
  selectBudgetMs: z.number().default(90000),
@@ -162,6 +169,8 @@ export function resolveConfig(raw) {
162
169
  for (const field of ['subscriptionUrls', 'subscriptionUrl', 'node', 'corePath', 'coreVersion', 'dnsServers', 'directDomains', 'proxyDomains', 'dataDir', 'probes', 'requiredProbes']) {
163
170
  config[field] = String(config[field] ?? '').trim()
164
171
  }
172
+ // A blocklist is multi-line by nature; only its outer whitespace is noise.
173
+ config.blocklist = String(config.blocklist ?? '').replace(/\r\n/g, '\n').trim()
165
174
  // A profile written by 0.2 carries only `subscriptionUrl`. Normalizing it into the
166
175
  // list here means every downstream reader sees one shape, and the panel shows the
167
176
  // user's existing subscription in the list editor on first open.
@@ -220,6 +229,8 @@ export class Runtime {
220
229
  this.bootstrapping = false
221
230
  /** Last capability matrix, so the panel can explain a selection. */
222
231
  this.lastMatrix = []
232
+ /** Every node name seen so far, so blocked ones can still be listed. */
233
+ this.lastKnownNodes = []
223
234
  /** When the line last became idle, so a switch waits for a quiet moment. */
224
235
  this.idleSince = undefined
225
236
  /** When the current node was last verified. */
@@ -349,7 +360,10 @@ export class Runtime {
349
360
  healthCheckMinutes: this.config.healthCheckMinutes,
350
361
  directDomains: this.config.directDomains,
351
362
  proxyDomains: this.config.proxyDomains,
363
+ blocklist: this.config.blocklist,
352
364
  dnsServers: this.config.dnsServers,
365
+ blocklist: this.config.blocklist,
366
+ blocklistFilter: buildExcludeFilter(this.config.blocklist),
353
367
  corePath: this.config.corePath,
354
368
  coreVersion: this.config.coreVersion,
355
369
  source: 'configured',
@@ -1039,6 +1053,8 @@ export class Runtime {
1039
1053
  dnsServers: splitList(this.config.dnsServers),
1040
1054
  directDomains: this.config.directDomains,
1041
1055
  proxyDomains: this.config.proxyDomains,
1056
+ // Blocked nodes are removed by the core, so they never enter the proxy table.
1057
+ blocklist: this.config.blocklist,
1042
1058
  // No geo directories are passed: the core's own data directory is authoritative,
1043
1059
  // and discovery supplies a machine-level fallback only when that copy is absent.
1044
1060
  })
@@ -1186,6 +1202,12 @@ export class Runtime {
1186
1202
  async status() {
1187
1203
  const running = this.core?.running === true
1188
1204
  const group = running ? await this.core.group().catch(() => ({ all: [], now: undefined })) : { all: [], now: undefined }
1205
+ // The core hides blocked nodes, so it never reports them. Keep every name this runtime has
1206
+ // seen, otherwise the panel has no way to show what the blocklist is currently removing.
1207
+ if (running) {
1208
+ const visible = group.all.filter((name) => name !== 'DIRECT')
1209
+ if (visible.length > 0) this.lastKnownNodes = [...new Set([...(this.lastKnownNodes ?? []), ...visible])]
1210
+ }
1189
1211
  const provider = running
1190
1212
  ? await this.core.providerStatus()
1191
1213
  : { updatedAt: null, vehicleType: null, providers: [], ok: false, healthy: 0, total: 0 }
@@ -1470,7 +1492,25 @@ function subscriptionTool(runtime) {
1470
1492
  const report = await runtime.start()
1471
1493
  return { ...report, summary: `已启动:${report.endpoint},节点「${report.group.now ?? '未选择'}」,共 ${Math.max(0, report.group.all.length - 1)} 个可选节点。` }
1472
1494
  }
1473
- if (action === 'reselect') {
1495
+ if (action === 'blocklist') {
1496
+ const raw = String(body.list ?? '')
1497
+ const problems = validateBlocklist(raw)
1498
+ // An invalid regex makes the core reject the whole provider, which empties the node table
1499
+ // — a far worse symptom than a rejected save. Catch it here instead.
1500
+ if (problems.length > 0) {
1501
+ sendJson(response, 400, { ok: false, error: 'invalid regex', problems })
1502
+ return
1503
+ }
1504
+ const saved = await runtime.saveConfig({ blocklist: raw })
1505
+ sendJson(response, 200, {
1506
+ ok: true,
1507
+ filter: buildExcludeFilter(raw),
1508
+ config: saved.config,
1509
+ warnings: saved.warnings,
1510
+ })
1511
+ return
1512
+ }
1513
+ if (action === 'reselect') {
1474
1514
  const result = await runtime.autoReselect({ force: true })
1475
1515
  return {
1476
1516
  ...result,
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Hiding nodes a person does not want to use.
3
+ *
4
+ * Exclusion happens in the core, not in the panel. mihomo's `proxy-provider` accepts an
5
+ * `exclude-filter` regex, so a hidden node never enters the proxy table at all — it cannot be
6
+ * auto-selected, cannot be picked by name, and cannot carry traffic even if something asks for
7
+ * it. Filtering only in the UI would leave a blocked node reachable through the tool, the
8
+ * startup search and the watchdog, which is three ways for a "hidden" node to still be used.
9
+ *
10
+ * Measured on the bundled core: `exclude-filter: '^block-.*$'` dropped both matching nodes from
11
+ * the group while leaving every other node, including Chinese-named ones, untouched.
12
+ *
13
+ * @module dsh-clash-proxy/blocklist
14
+ */
15
+
16
+ /** Characters that must survive a trip through a regex unchanged. */
17
+ const REGEX_SPECIAL = /[.*+?^${}()|[\]\\]/g
18
+
19
+ /**
20
+ * Escape one literal so it matches only itself.
21
+ *
22
+ * @param text - literal node name.
23
+ * @returns the escaped form.
24
+ */
25
+ export function escapeLiteral(text) {
26
+ return String(text ?? '').replace(REGEX_SPECIAL, '\\$&')
27
+ }
28
+
29
+ /**
30
+ * Parse the blocklist field into entries.
31
+ *
32
+ * One entry per line. A line that starts and ends with `/` is treated as a regular expression,
33
+ * which is what makes a whole region removable in one entry ("`/香港|HK/i`"); anything else is a
34
+ * literal node name. Blank lines and `#` comments are dropped.
35
+ *
36
+ * @param text - the configured field.
37
+ * @returns entries as `{ kind: 'literal'|'regex', value, source }`.
38
+ */
39
+ export function parseBlocklist(text) {
40
+ const entries = []
41
+ for (const raw of String(text ?? '').split(/\r?\n/)) {
42
+ const line = raw.trim()
43
+ if (line === '' || line.startsWith('#')) continue
44
+ const asRegex = /^\/(.+)\/([a-z]*)$/.exec(line)
45
+ if (asRegex !== null) {
46
+ entries.push({ kind: 'regex', value: asRegex[1], flags: asRegex[2] ?? '', source: line })
47
+ continue
48
+ }
49
+ entries.push({ kind: 'literal', value: line, source: line })
50
+ }
51
+ return entries
52
+ }
53
+
54
+ /**
55
+ * Turn the blocklist into one `exclude-filter` pattern.
56
+ *
57
+ * The core takes a single regex, so literals and user regexes are combined with alternation.
58
+ * Every literal is escaped and anchored, which keeps `香港01` from also hiding `香港010` — a
59
+ * substring match would hide nodes the user did not name, and the mistake is invisible until a
60
+ * node goes missing.
61
+ *
62
+ * @param text - the configured blocklist field.
63
+ * @returns the pattern, or an empty string when nothing is blocked.
64
+ */
65
+ export function buildExcludeFilter(text) {
66
+ const entries = parseBlocklist(text)
67
+ if (entries.length === 0) return ''
68
+ const parts = entries.map((entry) =>
69
+ entry.kind === 'literal' ? `^(?:${escapeLiteral(entry.value)})$` : `(?:${entry.value})`,
70
+ )
71
+ // `(?i)` is not portable across every regex flavour mihomo accepts on all platforms, so case
72
+ // insensitivity is left to the user's own flags on a regex entry.
73
+ return parts.join('|')
74
+ }
75
+
76
+ /**
77
+ * Whether a node name would be hidden by the pattern.
78
+ *
79
+ * Used to explain a selection ("this node is blocked") and to keep the panel honest, since the
80
+ * core no longer reports blocked nodes at all.
81
+ *
82
+ * @param name - node name.
83
+ * @param text - the configured blocklist field.
84
+ * @returns true when the name matches an entry.
85
+ */
86
+ export function isBlocked(name, text) {
87
+ for (const entry of parseBlocklist(text)) {
88
+ try {
89
+ const pattern = entry.kind === 'literal' ? `^(?:${escapeLiteral(entry.value)})$` : entry.value
90
+ if (new RegExp(pattern, entry.kind === 'regex' ? entry.flags : '').test(String(name))) return true
91
+ } catch {
92
+ // An unusable user regex blocks nothing; the core would reject the whole provider rather
93
+ // than silently ignore it, so this path only protects the preview.
94
+ }
95
+ }
96
+ return false
97
+ }
98
+
99
+ /**
100
+ * Check that every regex entry compiles, so a typo is caught before it reaches the core.
101
+ *
102
+ * The core treats an invalid `exclude-filter` as a provider load failure, which would empty the
103
+ * node table — a much worse symptom than a rejected save.
104
+ *
105
+ * @param text - the configured blocklist field.
106
+ * @returns the invalid entries, with the reason.
107
+ */
108
+ export function validateBlocklist(text) {
109
+ const problems = []
110
+ for (const entry of parseBlocklist(text)) {
111
+ if (entry.kind !== 'regex') continue
112
+ try {
113
+ new RegExp(entry.value, entry.flags)
114
+ } catch (error) {
115
+ problems.push({ source: entry.source, reason: String(error?.message ?? error) })
116
+ }
117
+ }
118
+ return problems
119
+ }
120
+
121
+ /**
122
+ * Split a node list into visible and blocked names, for the panel and for diagnostics.
123
+ *
124
+ * @param names - every node name the subscription carries.
125
+ * @param text - the configured blocklist field.
126
+ * @returns the two lists and the pattern that produced them.
127
+ */
128
+ export function partitionNodes(names, text) {
129
+ const list = Array.isArray(names) ? names : []
130
+ const visible = []
131
+ const blocked = []
132
+ for (const name of list) {
133
+ if (isBlocked(name, text)) blocked.push(name)
134
+ else visible.push(name)
135
+ }
136
+ return { visible, blocked, filter: buildExcludeFilter(text) }
137
+ }
package/lib/core.js CHANGED
@@ -16,6 +16,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
16
16
  import { createServer } from 'node:net'
17
17
  import { join } from 'node:path'
18
18
  import { CN_CIDR } from './cn-cidr.js'
19
+ import { buildExcludeFilter } from './blocklist.js'
19
20
  import { findCoreBinary } from './discovery.js'
20
21
 
21
22
  /**
@@ -188,6 +189,7 @@ export function buildConfig(options) {
188
189
  proxyDomains,
189
190
  cnRuleSet,
190
191
  cnRuleSetPath,
192
+ blocklist,
191
193
  singleUrl,
192
194
  subscriptionUrl,
193
195
  providerPath,
@@ -227,11 +229,14 @@ export function buildConfig(options) {
227
229
  const name = String(entry?.provider ?? `sub${at}`)
228
230
  names.push(name)
229
231
  const path = Array.isArray(providerPaths) ? providerPaths[at] : providerPath
232
+ // A blocked node is removed by the core itself, so it cannot be selected, tested or routed
233
+ // to by anything downstream. Filtering in the panel only would leave three ways to reach it.
230
234
  providers[name] = {
231
235
  type: 'http',
232
236
  url: String(entry?.url ?? ''),
233
237
  interval: 3600,
234
238
  path: path ?? `providers/${name}.yaml`,
239
+ ...(String(blocklist ?? '').trim() === '' ? {} : { 'exclude-filter': buildExcludeFilter(blocklist) }),
235
240
  'health-check': {
236
241
  enable: true,
237
242
  url: 'http://www.gstatic.com/generate_204',
@@ -368,6 +373,7 @@ export class Core {
368
373
  // bypass no longer depends on whether a GeoIP database happens to be present.
369
374
  cnRuleSet: 'cn-cidr',
370
375
  cnRuleSetPath: this.cnRuleSetPath,
376
+ blocklist: options.blocklist,
371
377
  })
372
378
  writeFileSync(this.configPath, `${JSON.stringify(config, null, 2)}\n`, 'utf8')
373
379
 
package/lib/routes.js CHANGED
@@ -38,6 +38,7 @@ export const EDITABLE_FIELDS = [
38
38
  'autoFetchGeo',
39
39
  'probes',
40
40
  'requiredProbes',
41
+ 'blocklist',
41
42
  'selectBudgetMs',
42
43
  ]
43
44
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-clash-subscription",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "description": "Import one or more Clash/mihomo subscriptions and route the Harness outbound traffic through the private core bundled with this plugin, so blocked sites work while domestic traffic stays direct — no other software involved.",
5
5
  "keywords": [
6
6
  "dsh",
@@ -70,4 +70,4 @@
70
70
  "test:client": "node test/client-sim.mjs",
71
71
  "test:e2e": "node test/e2e.mjs"
72
72
  }
73
- }
73
+ }