dsh-clash-subscription 0.5.0 → 0.6.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/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,22 @@ 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: '正则无效,未生效:',
183
+ blockedEmpty: '还没有节点清单——先启动一次,这里就会出现可勾选的节点。',
184
+ blockedSearch: '筛选节点…',
185
+ blockedSelected: '已屏蔽 {count} / 共 {total}',
186
+ blockedSelectAll: '屏蔽当前筛选结果',
187
+ blockedClear: '全部取消',
188
+ blockedApply: '应用',
189
+ blockedApplied: '已应用',
190
+ blockedStale: '订阅里已没有',
191
+ blockedPick: '勾选屏蔽(图形化)',
169
192
  reselect: '按能力重挑节点',
170
193
  reselecting: '正在测节点…',
171
194
  chosenNode: '已选:{node}',
@@ -216,6 +239,27 @@ function fill(template, values) {
216
239
  }
217
240
 
218
241
  /** Read the row form's saved values as a flat object. */
242
+ /**
243
+ * Split a saved blocklist into its two kinds of entry.
244
+ *
245
+ * The picker owns literal names; regex lines are the person's own hand-written rules and are
246
+ * preserved verbatim so ticking a checkbox never rewrites them.
247
+ *
248
+ * @param text - the configured blocklist field.
249
+ * @returns the regex lines and the literal names, in their original order.
250
+ */
251
+ function splitBlocklist(text) {
252
+ const regex = []
253
+ const literals = []
254
+ for (const raw of String(text ?? '').split(/\r?\n/)) {
255
+ const line = raw.trim()
256
+ if (line === '') continue
257
+ if (line.startsWith('/') || line.startsWith('#')) regex.push(line)
258
+ else literals.push(line)
259
+ }
260
+ return { regex, literals }
261
+ }
262
+
219
263
  const readValues = (value) => (value !== null && typeof value === 'object' ? { ...value } : {})
220
264
 
221
265
  /**
@@ -275,6 +319,16 @@ const CSS = `
275
319
  .clxp-sub { display: flex; flex-wrap: wrap; gap: 4px 10px; align-items: center; padding: 6px 8px; border: 1px solid var(--dsh-border-muted, #eaeef2); border-radius: 6px; }
276
320
  .clxp-sub .clxp-node-name { flex: 1 1 140px; }
277
321
  .clxp-probe { display: flex; flex-direction: column; gap: 2px; }
322
+ .clxp-picker { display: flex; flex-direction: column; gap: 8px; }
323
+ .clxp-pickbar { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
324
+ .clxp-pickbar > input[type="search"] { flex: 1 1 180px; min-width: 120px; }
325
+ .clxp-picklist { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 2px 10px; max-height: 320px; overflow-y: auto; padding: 4px; border: 1px solid var(--dsh-border-muted, #eaeef2); border-radius: 6px; }
326
+ .clxp-pick { display: flex; align-items: center; gap: 6px; padding: 2px 4px; border-radius: 4px; cursor: pointer; font-size: 12px; }
327
+ .clxp-pick:hover { background: var(--dsh-surface-subtle, #f6f8fa); }
328
+ .clxp-pick.off { text-decoration: line-through; opacity: 0.55; }
329
+ .clxp-pick.stale { opacity: 0.45; }
330
+ .clxp-pick-name { flex: 1 1 auto; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
331
+ .clxp-pick-tag { flex: 0 0 auto; font-size: 10px; padding: 0 4px; border-radius: 3px; background: var(--dsh-surface-subtle, #f6f8fa); color: var(--dsh-text-tertiary, #8b949e); }
278
332
  .clxp-probe > p { margin: 0; }
279
333
  .clxp button { font: inherit; padding: 4px 10px; border-radius: 6px; border: 1px solid var(--dsh-border-default, #d8dee4); background: var(--dsh-surface-default, #fff); color: inherit; cursor: pointer; }
280
334
  .clxp button:hover:not(:disabled) { background: var(--dsh-surface-subtle, #f6f8fa); }
@@ -325,6 +379,14 @@ function sections(t) {
325
379
  { key: 'probes', kind: 'text', label: t('probes'), hint: t('probesHint'), placeholder: 'hf=https://huggingface.co' },
326
380
  ],
327
381
  },
382
+ {
383
+ id: 'blocklist',
384
+ title: t('blocked'),
385
+ collapsed: true,
386
+ fields: [
387
+ { key: 'blocklist', kind: 'textarea', label: t('blockedLabel'), hint: t('blockedHint'), placeholder: t('blockedPlaceholder') },
388
+ ],
389
+ },
328
390
  {
329
391
  id: 'lists',
330
392
  title: t('lists'),
@@ -350,6 +412,86 @@ function sections(t) {
350
412
  * @param props - see {@link CONFIG_FIELDS}; `editable` decides whether fields render as controls.
351
413
  * @returns the panel.
352
414
  */
415
+ /**
416
+ * The blocklist picker: a checkbox per node, with a filter box.
417
+ *
418
+ * The core removes blocked nodes from its proxy table, so the group cannot supply their names
419
+ * back. The status route therefore serves `blocklist.knownNodes` from the plugin's own
420
+ * inventory, and this component renders that list rather than `live.nodes`.
421
+ *
422
+ * Selection is optimistic-free: the checkbox state comes from the server every poll, and a save
423
+ * posts the complete set of names to hide. Sending the whole set rather than a delta means a
424
+ * lost response cannot leave the panel and the core disagreeing about what is blocked.
425
+ */
426
+ function BlocklistPicker(props) {
427
+ const { t, live, busy, editable } = props
428
+ const [query, setQuery] = useState('')
429
+ const [selected, setSelected] = useState(undefined)
430
+
431
+ // Seed from the server on every status poll, unless the person has unsaved ticks.
432
+ const known = Array.isArray(live?.blocklist?.knownNodes) ? live.blocklist.knownNodes : []
433
+ const serverBlocked = known.filter((row) => row.blocked).map((row) => row.name)
434
+ const current = selected === undefined ? serverBlocked : selected
435
+ const dirty = selected !== undefined && (current.length !== serverBlocked.length || current.some((name) => !serverBlocked.includes(name)))
436
+
437
+ const alive = known.filter((row) => row.live)
438
+ const gone = known.filter((row) => !row.live)
439
+ const needle = query.trim().toLowerCase()
440
+ const matches = (row) => needle === '' || row.name.toLowerCase().includes(needle)
441
+
442
+ const toggle = (name) => {
443
+ const set = new Set(current)
444
+ if (set.has(name)) set.delete(name)
445
+ else set.add(name)
446
+ setSelected([...set])
447
+ }
448
+
449
+ const save = () => {
450
+ // Whole-set save: the raw regex lines the person may have added are preserved untouched.
451
+ props.onBlock([...current], props.keepRegex ?? '')
452
+ }
453
+
454
+ if (known.length === 0) {
455
+ return h('p', { className: 'clxp-note' }, t('blockedEmpty'))
456
+ }
457
+
458
+ const row = (entry) => h('label', {
459
+ key: entry.name,
460
+ className: `clxp-pick${current.includes(entry.name) ? ' off' : ''}${entry.live ? '' : ' stale'}`,
461
+ title: entry.name,
462
+ }, [
463
+ h('input', {
464
+ key: 'i',
465
+ type: 'checkbox',
466
+ checked: current.includes(entry.name),
467
+ disabled: !editable || busy !== '',
468
+ onChange: () => toggle(entry.name),
469
+ }),
470
+ h('span', { key: 'n', className: 'clxp-pick-name' }, entry.name),
471
+ entry.live ? null : h('span', { key: 's', className: 'clxp-pick-tag' }, t('blockedStale')),
472
+ ].filter(Boolean))
473
+
474
+ const shown = [...alive.filter(matches), ...gone.filter(matches)]
475
+
476
+ return h('div', { className: 'clxp-picker' }, [
477
+ h('div', { key: 'bar', className: 'clxp-pickbar' }, [
478
+ h('input', {
479
+ key: 'q',
480
+ type: 'search',
481
+ value: query,
482
+ placeholder: t('blockedSearch'),
483
+ disabled: !editable,
484
+ onChange: (event) => setQuery(event.target.value),
485
+ }),
486
+ h('span', { key: 'c', className: 'clxp-note' }, fill(t('blockedSelected'), { count: current.length, total: known.length })),
487
+ h('button', { key: 'a', type: 'button', disabled: !editable || busy !== '', onClick: () => setSelected(shown.filter(matches).map((r) => r.name)) }, t('blockedSelectAll')),
488
+ h('button', { key: 'z', type: 'button', disabled: !editable || busy !== '', onClick: () => setSelected([]) }, t('blockedClear')),
489
+ h('button', { key: 's', type: 'button', className: 'clxp-primary', disabled: !editable || busy !== '' || !dirty, onClick: save }, dirty ? t('blockedApply') : t('blockedApplied')),
490
+ ]),
491
+ h('div', { key: 'list', className: 'clxp-picklist' }, shown.map(row)),
492
+ ].filter(Boolean))
493
+ }
494
+
353
495
  function Panel(props) {
354
496
  const { t, draft, live, delays, busy, message, probe, saving, dirty, open, editable } = props
355
497
  const nodes = Array.isArray(live?.nodes) ? live.nodes : []
@@ -543,6 +685,19 @@ function Panel(props) {
543
685
  h('h4', { key: 'ti' }, t('routing')),
544
686
  h('p', { key: 'hi', className: 'clxp-hint' }, t('routingHint')),
545
687
  h('p', { key: 'cu', className: 'clxp-note' }, fill(t('currentNode'), { node: live?.node ?? t('autoSelect') })),
688
+ live?.blocklist !== undefined && live.blocklist.hidden !== undefined && live.blocklist.hidden.length > 0
689
+ ? h('p', { key: 'bh', className: 'clxp-note' }, fill(t('blockedCount'), { count: live.blocklist.hidden.length }) + (live.blocklist.filter === '' ? '' : ' · ' + live.blocklist.filter))
690
+ : null,
691
+ live?.blocklist !== undefined && Array.isArray(live.blocklist.problems) && live.blocklist.problems.length > 0
692
+ ? h('p', { key: 'bp', className: 'clxp-error', role: 'status' }, t('blockedInvalid') + ' ' + live.blocklist.problems.map((p) => p.source).join(', '))
693
+ : null,
694
+ live?.blocklist !== undefined && Array.isArray(live.blocklist.hidden)
695
+ ? h('div', { key: 'bl', className: 'clxp-subs' },
696
+ live.blocklist.hidden.slice(0, 20).map((name) => h('div', { key: name, className: 'clxp-sub' }, [
697
+ h('span', { key: 'n', className: 'clxp-node-name' }, name),
698
+ h('span', { key: 's', className: 'clxp-delay bad' }, t('blockedTag')),
699
+ ])))
700
+ : null,
546
701
  live?.capability !== undefined && Array.isArray(live.capability.nodes) && live.capability.nodes.length > 0
547
702
  ? h('p', { key: 'cp', className: 'clxp-note' }, fill(t('usableCount'), {
548
703
  usable: live.capability.nodes.filter((row) => row.usable).length,
@@ -595,6 +750,22 @@ function Panel(props) {
595
750
  ]),
596
751
  ]),
597
752
 
753
+ // A checkbox per node. This is the primary way to hide nodes; the text field below stays
754
+ // for regex rules and for pasting a list.
755
+ h('section', { key: 'blockpick', className: 'clxp-card' }, [
756
+ h('h4', { key: 'ti' }, t('blockedPick')),
757
+ h('p', { key: 'hi', className: 'clxp-hint' }, t('blockedHint')),
758
+ h(BlocklistPicker, {
759
+ key: 'pk',
760
+ t,
761
+ live,
762
+ busy,
763
+ editable,
764
+ keepRegex: splitBlocklist(live?.blocklist?.text ?? (editable ? draft.blocklist : '')).regex.join('\n'),
765
+ onBlock: (names, keepRegex) => void props.onAction('blockSelection', { names, keepRegex }),
766
+ }),
767
+ ]),
768
+
598
769
  // Configurable fields.
599
770
  ...sectionsList.map((group) => {
600
771
  const isOpen = expanded[group.id] ?? group.collapsed !== true
package/index.js CHANGED
@@ -21,6 +21,8 @@ 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, isBlocked, partitionNodes, validateBlocklist } from './lib/blocklist.js'
25
+ import { readInventory, rememberNodes } from './lib/inventory.js'
24
26
  import { installName, loadHttpProxyModule, locateInstallRoot, resolveFromInstall } from './lib/install.js'
25
27
  import { Routing } from './lib/routing.js'
26
28
  import {
@@ -73,6 +75,11 @@ export const CONFIG_DEFAULTS = {
73
75
  coreVersion: '',
74
76
  /** Fetch GeoIP databases after routing works; they are an upgrade, not a requirement. */
75
77
  autoFetchGeo: true,
78
+ /**
79
+ * Nodes to hide, one per line. A literal name matches exactly; /regex/flags removes a group.
80
+ * The core removes them from its proxy table entirely, so nothing can select or route to them.
81
+ */
82
+ blocklist: '',
76
83
  /** Extra capability probes as `id=url` lines; built-ins cover gstatic/google/openai/anthropic. */
77
84
  probes: '',
78
85
  /**
@@ -126,6 +133,7 @@ async function buildConfigSchema() {
126
133
  autoFetchCore: z.boolean().default(false),
127
134
  coreVersion: z.string().default(''),
128
135
  autoFetchGeo: z.boolean().default(true),
136
+ blocklist: z.string().default(''),
129
137
  probes: z.string().default(''),
130
138
  requiredProbes: z.string().default(''),
131
139
  selectBudgetMs: z.number().default(90000),
@@ -162,6 +170,8 @@ export function resolveConfig(raw) {
162
170
  for (const field of ['subscriptionUrls', 'subscriptionUrl', 'node', 'corePath', 'coreVersion', 'dnsServers', 'directDomains', 'proxyDomains', 'dataDir', 'probes', 'requiredProbes']) {
163
171
  config[field] = String(config[field] ?? '').trim()
164
172
  }
173
+ // A blocklist is multi-line by nature; only its outer whitespace is noise.
174
+ config.blocklist = String(config.blocklist ?? '').replace(/\r\n/g, '\n').trim()
165
175
  // A profile written by 0.2 carries only `subscriptionUrl`. Normalizing it into the
166
176
  // list here means every downstream reader sees one shape, and the panel shows the
167
177
  // user's existing subscription in the list editor on first open.
@@ -220,6 +230,8 @@ export class Runtime {
220
230
  this.bootstrapping = false
221
231
  /** Last capability matrix, so the panel can explain a selection. */
222
232
  this.lastMatrix = []
233
+ /** Every node name seen so far, so blocked ones can still be listed. */
234
+ this.lastKnownNodes = []
223
235
  /** When the line last became idle, so a switch waits for a quiet moment. */
224
236
  this.idleSince = undefined
225
237
  /** When the current node was last verified. */
@@ -349,7 +361,10 @@ export class Runtime {
349
361
  healthCheckMinutes: this.config.healthCheckMinutes,
350
362
  directDomains: this.config.directDomains,
351
363
  proxyDomains: this.config.proxyDomains,
364
+ blocklist: this.config.blocklist,
352
365
  dnsServers: this.config.dnsServers,
366
+ blocklist: this.config.blocklist,
367
+ blocklistFilter: buildExcludeFilter(this.config.blocklist),
353
368
  corePath: this.config.corePath,
354
369
  coreVersion: this.config.coreVersion,
355
370
  source: 'configured',
@@ -1039,6 +1054,8 @@ export class Runtime {
1039
1054
  dnsServers: splitList(this.config.dnsServers),
1040
1055
  directDomains: this.config.directDomains,
1041
1056
  proxyDomains: this.config.proxyDomains,
1057
+ // Blocked nodes are removed by the core, so they never enter the proxy table.
1058
+ blocklist: this.config.blocklist,
1042
1059
  // No geo directories are passed: the core's own data directory is authoritative,
1043
1060
  // and discovery supplies a machine-level fallback only when that copy is absent.
1044
1061
  })
@@ -1050,6 +1067,9 @@ export class Runtime {
1050
1067
  // "unreachable" next to 54 working nodes. Probe after the node table arrives, and
1051
1068
  // wait per provider so a large second subscription is not cut short.
1052
1069
  const group = await this.waitForNodes(parsed.entries.length)
1070
+ // Capture the inventory before anything is filtered: once the blocklist hides a node the
1071
+ // core stops reporting it, and a hidden node whose name is lost can never be un-hidden.
1072
+ rememberNodes(this.dataDir, group.all.filter((entry) => entry !== 'DIRECT'))
1053
1073
  this.lastProbe = await this.probeEntries(parsed.entries)
1054
1074
 
1055
1075
  const preferred = String(options.node ?? this.preferredNode ?? '').trim()
@@ -1186,6 +1206,13 @@ export class Runtime {
1186
1206
  async status() {
1187
1207
  const running = this.core?.running === true
1188
1208
  const group = running ? await this.core.group().catch(() => ({ all: [], now: undefined })) : { all: [], now: undefined }
1209
+ // The core hides blocked nodes, so it never reports them. Keep every name this runtime has
1210
+ // seen, otherwise the panel has no way to show what the blocklist is currently removing.
1211
+ if (running) {
1212
+ const visible = group.all.filter((name) => name !== 'DIRECT')
1213
+ if (visible.length > 0) this.lastKnownNodes = [...new Set([...(this.lastKnownNodes ?? []), ...visible])]
1214
+ if (visible.length > 0) rememberNodes(this.dataDir, visible)
1215
+ }
1189
1216
  const provider = running
1190
1217
  ? await this.core.providerStatus()
1191
1218
  : { updatedAt: null, vehicleType: null, providers: [], ok: false, healthy: 0, total: 0 }
@@ -1262,6 +1289,22 @@ export class Runtime {
1262
1289
  cnRuleSet: this.core?.cnRuleSet === undefined
1263
1290
  ? undefined
1264
1291
  : { name: 'cn-cidr', count: this.core.cnRuleSet.count },
1292
+ /**
1293
+ * Everything the blocklist picker needs: every node ever seen, whether it is hidden now,
1294
+ * and whether the core still carries it. A blocked node is absent from `group.all`, so
1295
+ * the inventory is the only source that can show it for un-blocking.
1296
+ */
1297
+ blocklist: {
1298
+ text: this.config.blocklist,
1299
+ filter: buildExcludeFilter(this.config.blocklist),
1300
+ entries: this.config.blocklist.split('\n').filter((line) => line.trim() !== '' && !line.trim().startsWith('#')).length,
1301
+ problems: validateBlocklist(this.config.blocklist),
1302
+ knownNodes: readInventory(this.dataDir).map((name) => ({
1303
+ name,
1304
+ blocked: isBlocked(name, this.config.blocklist),
1305
+ live: group.all.includes(name),
1306
+ })),
1307
+ },
1265
1308
  /** Whether a download could be attempted at all on this platform. */
1266
1309
  platformSupported: platformKey() !== undefined,
1267
1310
  degraded: this.degraded,
@@ -1470,7 +1513,50 @@ function subscriptionTool(runtime) {
1470
1513
  const report = await runtime.start()
1471
1514
  return { ...report, summary: `已启动:${report.endpoint},节点「${report.group.now ?? '未选择'}」,共 ${Math.max(0, report.group.all.length - 1)} 个可选节点。` }
1472
1515
  }
1473
- if (action === 'reselect') {
1516
+ if (action === 'blockSelection') {
1517
+ // The picker sends exact node names, so each becomes an anchored literal entry. Raw
1518
+ // regex text stays available in the blocklist field for whole-region removal; keeping
1519
+ // them apart means a checkbox can never accidentally behave as a pattern.
1520
+ const names = Array.isArray(body.names)
1521
+ ? body.names.filter((name) => typeof name === 'string' && name.trim() !== '').map((name) => name.trim())
1522
+ : []
1523
+ const keepRegex = String(body.keepRegex ?? '').trim()
1524
+ const literals = names.join('\n')
1525
+ const list = [keepRegex, literals].filter((part) => part !== '').join('\n')
1526
+ const problems = validateBlocklist(list)
1527
+ if (problems.length > 0) {
1528
+ sendJson(response, 400, { ok: false, error: 'invalid regex', problems })
1529
+ return
1530
+ }
1531
+ const saved = await runtime.saveConfig({ blocklist: list })
1532
+ sendJson(response, 200, {
1533
+ ok: true,
1534
+ blocked: names.length,
1535
+ filter: buildExcludeFilter(list),
1536
+ config: saved.config,
1537
+ warnings: saved.warnings,
1538
+ })
1539
+ return
1540
+ }
1541
+ if (action === 'blocklist') {
1542
+ const raw = String(body.list ?? '')
1543
+ const problems = validateBlocklist(raw)
1544
+ // An invalid regex makes the core reject the whole provider, which empties the node table
1545
+ // — a far worse symptom than a rejected save. Catch it here instead.
1546
+ if (problems.length > 0) {
1547
+ sendJson(response, 400, { ok: false, error: 'invalid regex', problems })
1548
+ return
1549
+ }
1550
+ const saved = await runtime.saveConfig({ blocklist: raw })
1551
+ sendJson(response, 200, {
1552
+ ok: true,
1553
+ filter: buildExcludeFilter(raw),
1554
+ config: saved.config,
1555
+ warnings: saved.warnings,
1556
+ })
1557
+ return
1558
+ }
1559
+ if (action === 'reselect') {
1474
1560
  const result = await runtime.autoReselect({ force: true })
1475
1561
  return {
1476
1562
  ...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
 
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Remembering every node a subscription carried, before any of them are hidden.
3
+ *
4
+ * The core removes blocked nodes from its proxy table, so it stops reporting them. That is
5
+ * correct for routing and fatal for a picker: a node hidden once could never be un-hidden,
6
+ * because its name would be gone from every source the panel can read.
7
+ *
8
+ * The subscription's own cache file is not a fallback either — mihomo writes it already
9
+ * filtered, so it agrees with the core rather than with the subscription.
10
+ *
11
+ * So the node list is captured on every start, before the filter applies to it (the group is
12
+ * read right after the provider downloads and before the blocklist is next saved), and kept in
13
+ * a JSON file next to the core config. It is an inventory, not a decision: nothing routes by
14
+ * it, and losing it costs only the ability to list a hidden node.
15
+ *
16
+ * @module dsh-clash-proxy/inventory
17
+ */
18
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
19
+ import { join } from 'node:path'
20
+
21
+ /** File name of the inventory, kept beside the core config. */
22
+ const INVENTORY_FILE = 'nodes-seen.json'
23
+
24
+ /**
25
+ * The inventory path for one data directory.
26
+ *
27
+ * @param dataDir - the plugin's data directory.
28
+ * @returns the absolute path.
29
+ */
30
+ export function inventoryPath(dataDir) {
31
+ return join(dataDir, INVENTORY_FILE)
32
+ }
33
+
34
+ /**
35
+ * Read the remembered node names.
36
+ *
37
+ * @param dataDir - the plugin's data directory.
38
+ * @returns the names, newest set first; an empty array when nothing was recorded yet.
39
+ */
40
+ export function readInventory(dataDir) {
41
+ try {
42
+ const parsed = JSON.parse(readFileSync(inventoryPath(dataDir), 'utf8'))
43
+ const names = Array.isArray(parsed?.names) ? parsed.names.filter((name) => typeof name === 'string') : []
44
+ return names
45
+ } catch {
46
+ return []
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Merge newly seen names into the inventory and write it back.
52
+ *
53
+ * Union rather than replace: a node hidden yesterday is absent from today's group, and
54
+ * replacing the file with today's visible set would forget it permanently — exactly the state
55
+ * that makes it impossible to un-hide.
56
+ *
57
+ * @param dataDir - the plugin's data directory.
58
+ * @param names - names currently reported by the core.
59
+ * @returns the merged list and whether the file changed.
60
+ */
61
+ export function rememberNodes(dataDir, names) {
62
+ const incoming = (Array.isArray(names) ? names : []).filter(
63
+ (name) => typeof name === 'string' && name !== '' && name !== 'DIRECT',
64
+ )
65
+ const previous = readInventory(dataDir)
66
+ const merged = [...new Set([...previous, ...incoming])]
67
+ // Stable order keeps the picker from reshuffling between polls.
68
+ merged.sort((a, b) => a.localeCompare(b))
69
+ const changed = merged.length !== previous.length || merged.some((name, index) => name !== previous[index])
70
+ if (!changed) return { names: merged, changed: false }
71
+ try {
72
+ mkdirSync(dataDir, { recursive: true })
73
+ writeFileSync(
74
+ inventoryPath(dataDir),
75
+ `${JSON.stringify({ updatedAt: new Date().toISOString(), names: merged }, null, 2)}\n`,
76
+ 'utf8',
77
+ )
78
+ } catch {
79
+ // A read-only data directory only costs the inventory, never routing.
80
+ }
81
+ return { names: merged, changed: true }
82
+ }
83
+
84
+ /**
85
+ * Drop names that a subscription no longer carries.
86
+ *
87
+ * Called with the full set a provider just delivered, so an inventory cannot grow forever as
88
+ * a provider rotates node names. Only names absent from *every* current provider are dropped.
89
+ *
90
+ * @param dataDir - the plugin's data directory.
91
+ * @param current - the union of names every provider currently reports.
92
+ * @returns the pruned list.
93
+ */
94
+ export function pruneInventory(dataDir, current) {
95
+ const live = new Set((Array.isArray(current) ? current : []).filter((name) => typeof name === 'string'))
96
+ if (live.size === 0) return readInventory(dataDir)
97
+ const previous = readInventory(dataDir)
98
+ const kept = previous.filter((name) => live.has(name))
99
+ if (kept.length === previous.length) return previous
100
+ try {
101
+ writeFileSync(
102
+ inventoryPath(dataDir),
103
+ `${JSON.stringify({ updatedAt: new Date().toISOString(), names: kept }, null, 2)}\n`,
104
+ 'utf8',
105
+ )
106
+ } catch {
107
+ // Same trade as above: the inventory is a convenience.
108
+ }
109
+ return kept
110
+ }
111
+
112
+ /**
113
+ * Whether the inventory file exists, for a diagnostic in the panel.
114
+ *
115
+ * @param dataDir - the plugin's data directory.
116
+ * @returns true when the file is present.
117
+ */
118
+ export function inventoryExists(dataDir) {
119
+ return existsSync(inventoryPath(dataDir))
120
+ }
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.6.0",
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
+ }