dsh-clash-subscription 0.5.1 → 0.6.2

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
@@ -107,6 +107,9 @@ const en = {
107
107
  statusDirect: 'Outbound policy not installed (direct)',
108
108
  measuredAt: 'Last measurement: {time}',
109
109
  never: 'never',
110
+ usableOk: 'usable',
111
+ usableBlocked: 'blocked',
112
+ usableUnknown: 'untested',
110
113
  readOnly: 'This panel is read-only here; open it from Settings to edit.',
111
114
  }
112
115
 
@@ -180,6 +183,18 @@ const zh = {
180
183
  blockedTag: '已屏蔽',
181
184
  blockedCount: '已屏蔽 {count} 个节点',
182
185
  blockedInvalid: '正则无效,未生效:',
186
+ usableOk: '可用',
187
+ usableBlocked: '受限',
188
+ usableUnknown: '未测',
189
+ blockedEmpty: '还没有节点清单——先启动一次,这里就会出现可勾选的节点。',
190
+ blockedSearch: '筛选节点…',
191
+ blockedSelected: '已屏蔽 {count} / 共 {total}',
192
+ blockedSelectAll: '屏蔽当前筛选结果',
193
+ blockedClear: '全部取消',
194
+ blockedApply: '应用',
195
+ blockedApplied: '已应用',
196
+ blockedStale: '订阅里已没有',
197
+ blockedPick: '勾选屏蔽(图形化)',
183
198
  reselect: '按能力重挑节点',
184
199
  reselecting: '正在测节点…',
185
200
  chosenNode: '已选:{node}',
@@ -230,6 +245,27 @@ function fill(template, values) {
230
245
  }
231
246
 
232
247
  /** Read the row form's saved values as a flat object. */
248
+ /**
249
+ * Split a saved blocklist into its two kinds of entry.
250
+ *
251
+ * The picker owns literal names; regex lines are the person's own hand-written rules and are
252
+ * preserved verbatim so ticking a checkbox never rewrites them.
253
+ *
254
+ * @param text - the configured blocklist field.
255
+ * @returns the regex lines and the literal names, in their original order.
256
+ */
257
+ function splitBlocklist(text) {
258
+ const regex = []
259
+ const literals = []
260
+ for (const raw of String(text ?? '').split(/\r?\n/)) {
261
+ const line = raw.trim()
262
+ if (line === '') continue
263
+ if (line.startsWith('/') || line.startsWith('#')) regex.push(line)
264
+ else literals.push(line)
265
+ }
266
+ return { regex, literals }
267
+ }
268
+
233
269
  const readValues = (value) => (value !== null && typeof value === 'object' ? { ...value } : {})
234
270
 
235
271
  /**
@@ -289,6 +325,16 @@ const CSS = `
289
325
  .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
326
  .clxp-sub .clxp-node-name { flex: 1 1 140px; }
291
327
  .clxp-probe { display: flex; flex-direction: column; gap: 2px; }
328
+ .clxp-picker { display: flex; flex-direction: column; gap: 8px; }
329
+ .clxp-pickbar { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
330
+ .clxp-pickbar > input[type="search"] { flex: 1 1 180px; min-width: 120px; }
331
+ .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; }
332
+ .clxp-pick { display: flex; align-items: center; gap: 6px; padding: 2px 4px; border-radius: 4px; cursor: pointer; font-size: 12px; }
333
+ .clxp-pick:hover { background: var(--dsh-surface-subtle, #f6f8fa); }
334
+ .clxp-pick.off { text-decoration: line-through; opacity: 0.55; }
335
+ .clxp-pick.stale { opacity: 0.45; }
336
+ .clxp-pick-name { flex: 1 1 auto; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
337
+ .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
338
  .clxp-probe > p { margin: 0; }
293
339
  .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
340
  .clxp button:hover:not(:disabled) { background: var(--dsh-surface-subtle, #f6f8fa); }
@@ -299,6 +345,10 @@ const CSS = `
299
345
  .clxp-node + .clxp-node { border-top: 1px solid var(--dsh-border-muted, #eaeef2); }
300
346
  .clxp-node-act { padding: 1px 6px; font-size: 12px; line-height: 1.4; border-radius: 4px; }
301
347
  .clxp-node.current { background: var(--dsh-surface-subtle, #f6f8fa); font-weight: 600; }
348
+ .clxp-usable { flex: 0 0 auto; font-size: 11px; padding: 0 5px; border-radius: 3px; line-height: 1.6; }
349
+ .clxp-usable.ok { color: #1a7f37; background: rgba(26, 127, 55, 0.1); }
350
+ .clxp-usable.blocked { color: #cf222e; background: rgba(207, 34, 46, 0.1); }
351
+ .clxp-usable.unknown { color: var(--dsh-text-tertiary, #8b949e); background: var(--dsh-surface-subtle, #f6f8fa); }
302
352
  .clxp-node-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
303
353
  .clxp-delay { font-variant-numeric: tabular-nums; color: var(--dsh-text-secondary, #57606a); font-size: 12px; }
304
354
  .clxp-delay.good { color: #1a7f37; }
@@ -372,9 +422,94 @@ function sections(t) {
372
422
  * @param props - see {@link CONFIG_FIELDS}; `editable` decides whether fields render as controls.
373
423
  * @returns the panel.
374
424
  */
425
+ /**
426
+ * The blocklist picker: a checkbox per node, with a filter box.
427
+ *
428
+ * The core removes blocked nodes from its proxy table, so the group cannot supply their names
429
+ * back. The status route therefore serves `blocklist.knownNodes` from the plugin's own
430
+ * inventory, and this component renders that list rather than `live.nodes`.
431
+ *
432
+ * Selection is optimistic-free: the checkbox state comes from the server every poll, and a save
433
+ * posts the complete set of names to hide. Sending the whole set rather than a delta means a
434
+ * lost response cannot leave the panel and the core disagreeing about what is blocked.
435
+ */
436
+ function BlocklistPicker(props) {
437
+ const { t, live, busy, editable } = props
438
+ const [query, setQuery] = useState('')
439
+ const [selected, setSelected] = useState(undefined)
440
+
441
+ // Seed from the server on every status poll, unless the person has unsaved ticks.
442
+ const known = Array.isArray(live?.blocklist?.knownNodes) ? live.blocklist.knownNodes : []
443
+ const serverBlocked = known.filter((row) => row.blocked).map((row) => row.name)
444
+ const current = selected === undefined ? serverBlocked : selected
445
+ const dirty = selected !== undefined && (current.length !== serverBlocked.length || current.some((name) => !serverBlocked.includes(name)))
446
+
447
+ const alive = known.filter((row) => row.live)
448
+ const gone = known.filter((row) => !row.live)
449
+ const needle = query.trim().toLowerCase()
450
+ const matches = (row) => needle === '' || row.name.toLowerCase().includes(needle)
451
+
452
+ const toggle = (name) => {
453
+ const set = new Set(current)
454
+ if (set.has(name)) set.delete(name)
455
+ else set.add(name)
456
+ setSelected([...set])
457
+ }
458
+
459
+ const save = () => {
460
+ // Whole-set save: the raw regex lines the person may have added are preserved untouched.
461
+ props.onBlock([...current], props.keepRegex ?? '')
462
+ }
463
+
464
+ if (known.length === 0) {
465
+ return h('p', { className: 'clxp-note' }, t('blockedEmpty'))
466
+ }
467
+
468
+ const row = (entry) => h('label', {
469
+ key: entry.name,
470
+ className: `clxp-pick${current.includes(entry.name) ? ' off' : ''}${entry.live ? '' : ' stale'}`,
471
+ title: entry.name,
472
+ }, [
473
+ h('input', {
474
+ key: 'i',
475
+ type: 'checkbox',
476
+ checked: current.includes(entry.name),
477
+ disabled: !editable || busy !== '',
478
+ onChange: () => toggle(entry.name),
479
+ }),
480
+ h('span', { key: 'n', className: 'clxp-pick-name' }, entry.name),
481
+ entry.live ? null : h('span', { key: 's', className: 'clxp-pick-tag' }, t('blockedStale')),
482
+ ].filter(Boolean))
483
+
484
+ const shown = [...alive.filter(matches), ...gone.filter(matches)]
485
+
486
+ return h('div', { className: 'clxp-picker' }, [
487
+ h('div', { key: 'bar', className: 'clxp-pickbar' }, [
488
+ h('input', {
489
+ key: 'q',
490
+ type: 'search',
491
+ value: query,
492
+ placeholder: t('blockedSearch'),
493
+ disabled: !editable,
494
+ onChange: (event) => setQuery(event.target.value),
495
+ }),
496
+ h('span', { key: 'c', className: 'clxp-note' }, fill(t('blockedSelected'), { count: current.length, total: known.length })),
497
+ h('button', { key: 'a', type: 'button', disabled: !editable || busy !== '', onClick: () => setSelected(shown.filter(matches).map((r) => r.name)) }, t('blockedSelectAll')),
498
+ h('button', { key: 'z', type: 'button', disabled: !editable || busy !== '', onClick: () => setSelected([]) }, t('blockedClear')),
499
+ h('button', { key: 's', type: 'button', className: 'clxp-primary', disabled: !editable || busy !== '' || !dirty, onClick: save }, dirty ? t('blockedApply') : t('blockedApplied')),
500
+ ]),
501
+ h('div', { key: 'list', className: 'clxp-picklist' }, shown.map(row)),
502
+ ].filter(Boolean))
503
+ }
504
+
375
505
  function Panel(props) {
376
506
  const { t, draft, live, delays, busy, message, probe, saving, dirty, open, editable } = props
377
507
  const nodes = Array.isArray(live?.nodes) ? live.nodes : []
508
+ // One row per node from the server: latency and usability measured together, so the list
509
+ // shows "120 ms · usable" instead of needing a second list to answer the same question.
510
+ const rowsByName = new Map(
511
+ (Array.isArray(live?.nodeRows?.rows) ? live.nodeRows.rows : []).map((row) => [row.name, row]),
512
+ )
378
513
  const subscriptions = Array.isArray(live?.subscriptions) && live.subscriptions.length > 0
379
514
  ? live.subscriptions
380
515
  : // Before the first status poll resolves, fall back to the draft's own lines so the
@@ -578,34 +713,30 @@ function Panel(props) {
578
713
  h('span', { key: 's', className: 'clxp-delay bad' }, t('blockedTag')),
579
714
  ])))
580
715
  : null,
581
- live?.capability !== undefined && Array.isArray(live.capability.nodes) && live.capability.nodes.length > 0
582
- ? h('p', { key: 'cp', className: 'clxp-note' }, fill(t('usableCount'), {
583
- usable: live.capability.nodes.filter((row) => row.usable).length,
584
- total: live.capability.nodes.length,
585
- }) + ' · ' + t('requiredProbes') + ': ' + (live.capability.required ?? []).join(', '))
586
- : null,
587
- live?.capability !== undefined && Array.isArray(live.capability.nodes)
588
- ? h('div', { key: 'cpl', className: 'clxp-subs' },
589
- live.capability.nodes
590
- .filter((row) => !row.usable)
591
- .slice(0, 6)
592
- .map((row) => h('div', { key: row.name, className: 'clxp-sub' }, [
593
- h('span', { key: 'n', className: 'clxp-node-name' }, row.name),
594
- h('span', { key: 'f', className: 'clxp-delay bad' }, (row.failed ?? []).join(', ') || '-'),
595
- ])))
596
- : null,
597
716
 
598
717
  nodes.length === 0
599
718
  ? h('p', { key: 'em', className: 'clxp-note' }, t('noNodes'))
600
719
  : h('div', { key: 'ls', className: 'clxp-nodes', role: 'listbox', 'aria-label': t('routing') },
601
- nodes.map((name) => h('div', {
720
+ nodes.map((name) => {
721
+ // Latency and usability come from one measurement, so they are rendered from one
722
+ // row. Splitting them into two lists let the panel show "fast" beside "blocked"
723
+ // with nothing connecting the two.
724
+ const nodeRow = rowsByName.get(name)
725
+ const usable = nodeRow?.usable ?? 'unknown'
726
+ const shownDelay = nodeRow?.delay === undefined ? delays[name] : nodeRow.delay
727
+ return h('div', {
602
728
  key: name,
603
729
  className: `clxp-node${name === live?.node ? ' current' : ''}`,
604
730
  role: 'option',
605
731
  'aria-selected': name === live?.node,
606
732
  }, [
607
733
  h('span', { key: 'n', className: 'clxp-node-name', title: name }, name),
608
- h('span', { key: 'd', className: delayClass(delays[name]) }, delayText(delays[name])),
734
+ h('span', { key: 'd', className: delayClass(shownDelay) }, delayText(shownDelay)),
735
+ h('span', {
736
+ key: 'u',
737
+ className: `clxp-usable ${usable}`,
738
+ title: (nodeRow?.failed ?? []).join(', '),
739
+ }, usable === 'ok' ? t('usableOk') : usable === 'blocked' ? t('usableBlocked') : t('usableUnknown')),
609
740
  h('button', {
610
741
  key: 't',
611
742
  type: 'button',
@@ -622,7 +753,8 @@ function Panel(props) {
622
753
  disabled: busy !== '' || !running || name === live?.node,
623
754
  onClick: () => void props.onAction('select', { node: name }),
624
755
  }, name === live?.node ? '✓' : t('select')),
625
- ]))),
756
+ ])
757
+ })),
626
758
  h('div', { key: 'ac', className: 'clxp-actions' }, [
627
759
  h('button', { key: 'te', type: 'button', disabled: busy !== '' || !running, onClick: () => void props.onAction('test') }, busy === 'test' ? t('testing') : t('testNow')),
628
760
  h('button', { key: 'ta', type: 'button', disabled: busy !== '' || !running, onClick: () => void props.onAction('test', { all: true }) }, busy === 'test' ? t('testing') : t('testAll')),
@@ -630,6 +762,22 @@ function Panel(props) {
630
762
  ]),
631
763
  ]),
632
764
 
765
+ // A checkbox per node. This is the primary way to hide nodes; the text field below stays
766
+ // for regex rules and for pasting a list.
767
+ h('section', { key: 'blockpick', className: 'clxp-card' }, [
768
+ h('h4', { key: 'ti' }, t('blockedPick')),
769
+ h('p', { key: 'hi', className: 'clxp-hint' }, t('blockedHint')),
770
+ h(BlocklistPicker, {
771
+ key: 'pk',
772
+ t,
773
+ live,
774
+ busy,
775
+ editable,
776
+ keepRegex: splitBlocklist(live?.blocklist?.text ?? (editable ? draft.blocklist : '')).regex.join('\n'),
777
+ onBlock: (names, keepRegex) => void props.onAction('blockSelection', { names, keepRegex }),
778
+ }),
779
+ ]),
780
+
633
781
  // Configurable fields.
634
782
  ...sectionsList.map((group) => {
635
783
  const isOpen = expanded[group.id] ?? group.collapsed !== true
package/index.js CHANGED
@@ -21,7 +21,9 @@ 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'
26
+ import { buildNodeRows, summariseRows } from './lib/health.js'
25
27
  import { installName, loadHttpProxyModule, locateInstallRoot, resolveFromInstall } from './lib/install.js'
26
28
  import { Routing } from './lib/routing.js'
27
29
  import {
@@ -317,15 +319,32 @@ export class Runtime {
317
319
  }
318
320
 
319
321
  const measured = new Map(this.measured)
322
+ const plan = resolveProbes(this.config.probes, this.config.requiredProbes)
323
+ const capability = new Map((this.lastMatrix ?? []).map((row) => [row.name, row]))
320
324
  const batchSize = 5
321
325
  for (let at = 0; at < candidates.length; at += batchSize) {
322
326
  const batch = candidates.slice(at, at + batchSize)
327
+ // Latency and usability are measured in the same pass: a row that reports "120 ms" without
328
+ // saying whether the node can reach the required services answers half the question, and
329
+ // measuring them separately let the two disagree.
323
330
  const answers = await Promise.all(
324
- batch.map(async (name) => ({ name, delay: await this.core.delay(name, 5000) })),
331
+ batch.map(async (name) => {
332
+ const delay = await this.core.delay(name, 5000)
333
+ const results = delay === null ? undefined : await this.core.capabilities(name, plan.probes, {
334
+ timeoutMs: this.config.probeTimeoutMs ?? 8000,
335
+ samples: this.config.probeSamples ?? 2,
336
+ })
337
+ return { name, delay, results }
338
+ }),
325
339
  )
326
- for (const answer of answers) measured.set(answer.name, answer.delay)
340
+ for (const answer of answers) {
341
+ measured.set(answer.name, answer.delay)
342
+ if (answer.results !== undefined) capability.set(answer.name, { name: answer.name, results: answer.results })
343
+ else capability.set(answer.name, { name: answer.name, results: {} })
344
+ }
327
345
  }
328
346
  this.measured = measured
347
+ this.lastMatrix = [...capability.values()]
329
348
  this.measuredAt = Date.now()
330
349
  return Object.fromEntries(measured)
331
350
  }
@@ -1066,6 +1085,9 @@ export class Runtime {
1066
1085
  // "unreachable" next to 54 working nodes. Probe after the node table arrives, and
1067
1086
  // wait per provider so a large second subscription is not cut short.
1068
1087
  const group = await this.waitForNodes(parsed.entries.length)
1088
+ // Capture the inventory before anything is filtered: once the blocklist hides a node the
1089
+ // core stops reporting it, and a hidden node whose name is lost can never be un-hidden.
1090
+ rememberNodes(this.dataDir, group.all.filter((entry) => entry !== 'DIRECT'))
1069
1091
  this.lastProbe = await this.probeEntries(parsed.entries)
1070
1092
 
1071
1093
  const preferred = String(options.node ?? this.preferredNode ?? '').trim()
@@ -1207,6 +1229,7 @@ export class Runtime {
1207
1229
  if (running) {
1208
1230
  const visible = group.all.filter((name) => name !== 'DIRECT')
1209
1231
  if (visible.length > 0) this.lastKnownNodes = [...new Set([...(this.lastKnownNodes ?? []), ...visible])]
1232
+ if (visible.length > 0) rememberNodes(this.dataDir, visible)
1210
1233
  }
1211
1234
  const provider = running
1212
1235
  ? await this.core.providerStatus()
@@ -1267,6 +1290,18 @@ export class Runtime {
1267
1290
  idleSince: this.idleSince === undefined ? null : new Date(this.idleSince).toISOString(),
1268
1291
  },
1269
1292
  /** Per-node probe results from the last selection, and which services gate it. */
1293
+ /**
1294
+ * One row per live node with its latency and usability together. The panel draws this and
1295
+ * nothing else for the node list, so latency and capability cannot drift apart on screen.
1296
+ */
1297
+ nodeRows: (() => {
1298
+ const live = group.all.filter((name) => name !== 'DIRECT')
1299
+ const rows = buildNodeRows(live, Object.fromEntries(this.measured), {
1300
+ required: resolveProbes(this.config.probes, this.config.requiredProbes).required,
1301
+ nodes: this.lastMatrix,
1302
+ })
1303
+ return { rows, summary: summariseRows(rows) }
1304
+ })(),
1270
1305
  capability: {
1271
1306
  required: resolveProbes(this.config.probes, this.config.requiredProbes).required,
1272
1307
  probes: resolveProbes(this.config.probes, this.config.requiredProbes).probes.map((probe) => ({ id: probe.id, label: probe.label })),
@@ -1284,6 +1319,22 @@ export class Runtime {
1284
1319
  cnRuleSet: this.core?.cnRuleSet === undefined
1285
1320
  ? undefined
1286
1321
  : { name: 'cn-cidr', count: this.core.cnRuleSet.count },
1322
+ /**
1323
+ * Everything the blocklist picker needs: every node ever seen, whether it is hidden now,
1324
+ * and whether the core still carries it. A blocked node is absent from `group.all`, so
1325
+ * the inventory is the only source that can show it for un-blocking.
1326
+ */
1327
+ blocklist: {
1328
+ text: this.config.blocklist,
1329
+ filter: buildExcludeFilter(this.config.blocklist),
1330
+ entries: this.config.blocklist.split('\n').filter((line) => line.trim() !== '' && !line.trim().startsWith('#')).length,
1331
+ problems: validateBlocklist(this.config.blocklist),
1332
+ knownNodes: readInventory(this.dataDir).map((name) => ({
1333
+ name,
1334
+ blocked: isBlocked(name, this.config.blocklist),
1335
+ live: group.all.includes(name),
1336
+ })),
1337
+ },
1287
1338
  /** Whether a download could be attempted at all on this platform. */
1288
1339
  platformSupported: platformKey() !== undefined,
1289
1340
  degraded: this.degraded,
@@ -1492,24 +1543,6 @@ function subscriptionTool(runtime) {
1492
1543
  const report = await runtime.start()
1493
1544
  return { ...report, summary: `已启动:${report.endpoint},节点「${report.group.now ?? '未选择'}」,共 ${Math.max(0, report.group.all.length - 1)} 个可选节点。` }
1494
1545
  }
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
1546
  if (action === 'reselect') {
1514
1547
  const result = await runtime.autoReselect({ force: true })
1515
1548
  return {
package/lib/health.js ADDED
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Per-node health as one row the panel can render: delay plus usability.
3
+ *
4
+ * The panel used to show latency in the node list and usability in a separate capability
5
+ * block, which meant two lists of the same nodes and a reader had to join them by name. A
6
+ * single row carrying both is the whole point: "120 ms, usable" or "260 ms, OpenAI blocked"
7
+ * answers the question someone actually has when picking an exit.
8
+ *
9
+ * Usability is a three-state, not a boolean:
10
+ *
11
+ * - `unknown` — never probed, or probed before the current required set changed;
12
+ * - `ok` — every required service answered;
13
+ * - `blocked` — at least one did not.
14
+ *
15
+ * @module dsh-clash-proxy/health
16
+ */
17
+
18
+ /**
19
+ * Build one row per node, joining the latency map with the capability matrix.
20
+ *
21
+ * @param names - node names the core currently carries.
22
+ * @param delays - node name to delay in ms, or null when it did not answer.
23
+ * @param capability - `{ required, nodes }` from the last selection, or undefined.
24
+ * @returns one row per node, in the order given.
25
+ */
26
+ export function buildNodeRows(names, delays, capability) {
27
+ const list = Array.isArray(names) ? names : []
28
+ const delayMap = delays !== null && typeof delays === 'object' ? delays : {}
29
+ const required = Array.isArray(capability?.required) ? capability.required : []
30
+ const results = new Map()
31
+ for (const row of Array.isArray(capability?.nodes) ? capability.nodes : []) {
32
+ if (row !== null && typeof row === 'object' && typeof row.name === 'string') results.set(row.name, row)
33
+ }
34
+
35
+ return list.map((name) => {
36
+ const delay = Object.hasOwn(delayMap, name) ? delayMap[name] : undefined
37
+ const measured = results.get(name)
38
+ let usable = 'unknown'
39
+ let failed = []
40
+ if (measured !== undefined && required.length > 0) {
41
+ failed = required.filter((id) => typeof measured.results?.[id] !== 'number')
42
+ usable = failed.length === 0 ? 'ok' : 'blocked'
43
+ }
44
+ return {
45
+ name,
46
+ /** ms, null for "did not answer", undefined for "not measured yet". */
47
+ delay: delay === undefined ? undefined : delay,
48
+ usable,
49
+ failed,
50
+ }
51
+ })
52
+ }
53
+
54
+ /**
55
+ * Summarise a row set for the panel header.
56
+ *
57
+ * `usable` counts only nodes positively confirmed for every required service; `unknown` is
58
+ * reported apart from it so a fresh start does not read as "nothing works".
59
+ *
60
+ * @param rows - output of {@link buildNodeRows}.
61
+ * @returns counts by state and the total.
62
+ */
63
+ export function summariseRows(rows) {
64
+ const list = Array.isArray(rows) ? rows : []
65
+ return {
66
+ total: list.length,
67
+ ok: list.filter((row) => row.usable === 'ok').length,
68
+ blocked: list.filter((row) => row.usable === 'blocked').length,
69
+ unknown: list.filter((row) => row.usable === 'unknown').length,
70
+ measured: list.filter((row) => typeof row.delay === 'number').length,
71
+ }
72
+ }
73
+
74
+ /**
75
+ * A short label for one row's usability, for the panel to translate.
76
+ *
77
+ * @param row - one output row.
78
+ * @returns `ok`, `blocked` or `unknown`.
79
+ */
80
+ export function usabilityLabel(row) {
81
+ return row?.usable === 'ok' || row?.usable === 'blocked' ? row.usable : 'unknown'
82
+ }
@@ -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
@@ -111,6 +111,8 @@ const methodOf = (request) => String(request.method ?? 'GET').toUpperCase()
111
111
  * @param log - logger for route failures.
112
112
  * @returns disposers for every registered route.
113
113
  */
114
+ import { buildExcludeFilter, validateBlocklist } from './blocklist.js'
115
+
114
116
  export function mountRoutes(webServer, runtime, log) {
115
117
  const disposers = []
116
118
 
@@ -200,6 +202,42 @@ export function mountRoutes(webServer, runtime, log) {
200
202
  sendJson(response, 200, { ok: true, ...report, binary: runtime.binary })
201
203
  return
202
204
  }
205
+ if (action === 'blockSelection') {
206
+ // The picker sends exact node names, so each becomes an anchored literal entry. Raw regex
207
+ // text stays in the blocklist field for whole-region removal; keeping them apart means a
208
+ // checkbox can never accidentally behave as a pattern.
209
+ const names = Array.isArray(body.names)
210
+ ? body.names.filter((name) => typeof name === 'string' && name.trim() !== '').map((name) => name.trim())
211
+ : []
212
+ const keepRegex = String(body.keepRegex ?? '').trim()
213
+ const list = [keepRegex, names.join('\n')].filter((part) => part !== '').join('\n')
214
+ const problems = validateBlocklist(list)
215
+ if (problems.length > 0) {
216
+ sendJson(response, 400, { ok: false, error: 'invalid regex', problems })
217
+ return
218
+ }
219
+ const saved = await runtime.saveConfig({ blocklist: list })
220
+ sendJson(response, 200, {
221
+ ok: true,
222
+ blocked: names.length,
223
+ filter: buildExcludeFilter(list),
224
+ warnings: saved.warnings,
225
+ })
226
+ return
227
+ }
228
+ if (action === 'blocklist') {
229
+ const raw = String(body.list ?? '')
230
+ const problems = validateBlocklist(raw)
231
+ // An invalid regex makes the core reject the whole provider, which empties the node table —
232
+ // a far worse symptom than a rejected save. Catch it here instead.
233
+ if (problems.length > 0) {
234
+ sendJson(response, 400, { ok: false, error: 'invalid regex', problems })
235
+ return
236
+ }
237
+ const saved = await runtime.saveConfig({ blocklist: raw })
238
+ sendJson(response, 200, { ok: true, filter: buildExcludeFilter(raw), warnings: saved.warnings })
239
+ return
240
+ }
203
241
  if (action === 'start') {
204
242
  const report = await runtime.start()
205
243
  sendJson(response, 200, {
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.2",
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",