dsh-clash-subscription 0.5.1 → 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
@@ -180,6 +180,15 @@ const zh = {
180
180
  blockedTag: '已屏蔽',
181
181
  blockedCount: '已屏蔽 {count} 个节点',
182
182
  blockedInvalid: '正则无效,未生效:',
183
+ blockedEmpty: '还没有节点清单——先启动一次,这里就会出现可勾选的节点。',
184
+ blockedSearch: '筛选节点…',
185
+ blockedSelected: '已屏蔽 {count} / 共 {total}',
186
+ blockedSelectAll: '屏蔽当前筛选结果',
187
+ blockedClear: '全部取消',
188
+ blockedApply: '应用',
189
+ blockedApplied: '已应用',
190
+ blockedStale: '订阅里已没有',
191
+ blockedPick: '勾选屏蔽(图形化)',
183
192
  reselect: '按能力重挑节点',
184
193
  reselecting: '正在测节点…',
185
194
  chosenNode: '已选:{node}',
@@ -230,6 +239,27 @@ function fill(template, values) {
230
239
  }
231
240
 
232
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
+
233
263
  const readValues = (value) => (value !== null && typeof value === 'object' ? { ...value } : {})
234
264
 
235
265
  /**
@@ -289,6 +319,16 @@ const CSS = `
289
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; }
290
320
  .clxp-sub .clxp-node-name { flex: 1 1 140px; }
291
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); }
292
332
  .clxp-probe > p { margin: 0; }
293
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; }
294
334
  .clxp button:hover:not(:disabled) { background: var(--dsh-surface-subtle, #f6f8fa); }
@@ -372,6 +412,86 @@ function sections(t) {
372
412
  * @param props - see {@link CONFIG_FIELDS}; `editable` decides whether fields render as controls.
373
413
  * @returns the panel.
374
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
+
375
495
  function Panel(props) {
376
496
  const { t, draft, live, delays, busy, message, probe, saving, dirty, open, editable } = props
377
497
  const nodes = Array.isArray(live?.nodes) ? live.nodes : []
@@ -630,6 +750,22 @@ function Panel(props) {
630
750
  ]),
631
751
  ]),
632
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
+
633
769
  // Configurable fields.
634
770
  ...sectionsList.map((group) => {
635
771
  const isOpen = expanded[group.id] ?? group.collapsed !== true
package/index.js CHANGED
@@ -21,7 +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, partitionNodes, validateBlocklist } from './lib/blocklist.js'
24
+ import { buildExcludeFilter, isBlocked, partitionNodes, validateBlocklist } from './lib/blocklist.js'
25
+ import { readInventory, rememberNodes } from './lib/inventory.js'
25
26
  import { installName, loadHttpProxyModule, locateInstallRoot, resolveFromInstall } from './lib/install.js'
26
27
  import { Routing } from './lib/routing.js'
27
28
  import {
@@ -1066,6 +1067,9 @@ export class Runtime {
1066
1067
  // "unreachable" next to 54 working nodes. Probe after the node table arrives, and
1067
1068
  // wait per provider so a large second subscription is not cut short.
1068
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'))
1069
1073
  this.lastProbe = await this.probeEntries(parsed.entries)
1070
1074
 
1071
1075
  const preferred = String(options.node ?? this.preferredNode ?? '').trim()
@@ -1207,6 +1211,7 @@ export class Runtime {
1207
1211
  if (running) {
1208
1212
  const visible = group.all.filter((name) => name !== 'DIRECT')
1209
1213
  if (visible.length > 0) this.lastKnownNodes = [...new Set([...(this.lastKnownNodes ?? []), ...visible])]
1214
+ if (visible.length > 0) rememberNodes(this.dataDir, visible)
1210
1215
  }
1211
1216
  const provider = running
1212
1217
  ? await this.core.providerStatus()
@@ -1284,6 +1289,22 @@ export class Runtime {
1284
1289
  cnRuleSet: this.core?.cnRuleSet === undefined
1285
1290
  ? undefined
1286
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
+ },
1287
1308
  /** Whether a download could be attempted at all on this platform. */
1288
1309
  platformSupported: platformKey() !== undefined,
1289
1310
  degraded: this.degraded,
@@ -1492,24 +1513,49 @@ function subscriptionTool(runtime) {
1492
1513
  const report = await runtime.start()
1493
1514
  return { ...report, summary: `已启动:${report.endpoint},节点「${report.group.now ?? '未选择'}」,共 ${Math.max(0, report.group.all.length - 1)} 个可选节点。` }
1494
1515
  }
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.
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)
1500
1527
  if (problems.length > 0) {
1501
1528
  sendJson(response, 400, { ok: false, error: 'invalid regex', problems })
1502
1529
  return
1503
1530
  }
1504
- const saved = await runtime.saveConfig({ blocklist: raw })
1531
+ const saved = await runtime.saveConfig({ blocklist: list })
1505
1532
  sendJson(response, 200, {
1506
1533
  ok: true,
1507
- filter: buildExcludeFilter(raw),
1534
+ blocked: names.length,
1535
+ filter: buildExcludeFilter(list),
1508
1536
  config: saved.config,
1509
1537
  warnings: saved.warnings,
1510
1538
  })
1511
1539
  return
1512
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
+ }
1513
1559
  if (action === 'reselect') {
1514
1560
  const result = await runtime.autoReselect({ force: true })
1515
1561
  return {
@@ -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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-clash-subscription",
3
- "version": "0.5.1",
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",