@andy.ian/dsh-homing 2.3.2 → 2.3.4

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/index.js CHANGED
@@ -45,7 +45,7 @@ import { probeVnc } from './lib/vnc-probe.mjs';
45
45
  import { WebSocketServer } from './lib/vendor/ws/wrapper.mjs';
46
46
  import { renderVncPage } from './lib/vnc-page.mjs';
47
47
  import { customShells, detectShells, resolveShell, DEFAULT_SHELL } from './lib/shells.mjs';
48
- import { renderListing as renderFileListing, renderFile as renderFileView, renderRunPage, renderGitPage, renderEditPage, renderCompressPage } from './lib/files-page.mjs';
48
+ import { renderListing as renderFileListing, renderFile as renderFileView, renderRunPage, renderGitPage, renderEditPage, renderCompressPage, renderWallPage } from './lib/files-page.mjs';
49
49
  import { checkUnsafeOrigin, checkOwnPageWrite } from './lib/csrf.mjs';
50
50
  import { validateOpenPath } from './lib/guard.mjs';
51
51
  import { opensslExe, sshExe } from './lib/exec-path.mjs';
@@ -1757,6 +1757,14 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1757
1757
  return;
1758
1758
  }
1759
1759
 
1760
+ // 图片预览页的手势脚本(左右滑动切换上一张/下一张)
1761
+ if (url.pathname === '/dsh_homing/files-preview.js' && req.method === 'GET') {
1762
+ const js = fs.readFileSync(new URL('./lib/files-preview.js', import.meta.url), 'utf8');
1763
+ res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
1764
+ res.end(js);
1765
+ return;
1766
+ }
1767
+
1760
1768
  // 开机自启:页面上的"启用 / 以后再说"
1761
1769
  if (url.pathname === '/dsh_homing/autostart' && req.method === 'POST') {
1762
1770
  const form = new URLSearchParams(await readBody(req, 4096));
@@ -2164,6 +2172,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2164
2172
  // 必须在未登录时也能加载与上报
2165
2173
  || url.pathname === '/dsh_homing/auth-state' || url.pathname === '/dsh_homing/auth-guard.js'
2166
2174
  || url.pathname === '/dsh_homing/idb-fallback.js'
2175
+ || url.pathname === '/dsh_homing/files-preview.js'
2167
2176
  || url.pathname === '/dsh_homing/client-report.js' || url.pathname === '/dsh_homing/client-error'
2168
2177
  // 图标与 manifest 是浏览器自动抓的,挡掉只会让登录页看起来坏掉、并在审计里刷噪音
2169
2178
  || url.pathname === '/manifest.webmanifest' || url.pathname === '/apple-touch-icon.png'
@@ -3051,8 +3060,9 @@ a{color:#8ab4f8}
3051
3060
  return;
3052
3061
  }
3053
3062
 
3054
- if (url.pathname === '/files' || url.pathname === '/files/view' || url.pathname === '/files/pdf' || url.pathname === '/files/download' || url.pathname === '/files/raw' || url.pathname === '/files/compress' || url.pathname === '/files/run'
3063
+ if (url.pathname === '/files' || url.pathname === '/files/view' || url.pathname === '/files/wall' || url.pathname === '/files/pdf' || url.pathname === '/files/download' || url.pathname === '/files/raw' || url.pathname === '/files/compress' || url.pathname === '/files/run'
3055
3064
  || url.pathname === '/files/rename'
3065
+ || url.pathname === '/api/file'
3056
3066
  || url.pathname === '/files/delete' || url.pathname === '/files/paste'
3057
3067
  || url.pathname === '/files/mkdir' || url.pathname === '/files/newfile') {
3058
3068
  if (!sessionValid(req) && currentDevice(req) === null) {
@@ -3072,6 +3082,41 @@ a{color:#8ab4f8}
3072
3082
  res.end(page);
3073
3083
  };
3074
3084
 
3085
+ // DSH 网页端打开文件(消息里的图片卡片等)会请求 `/api/file?path=...`:
3086
+ // 桌面端有 `dsh-app://` 私有文件服务,网页端没有实现,只会显示
3087
+ // 「文件资源服务不可用」。这里接管这个请求:
3088
+ // - 图片且不是页面导航(<img> 缩略图)→ 直接内联返回原图;
3089
+ // - 其余(点击卡片打开)→ 302 到插件的文件预览页(图片/文本/PDF/Office 都能看)。
3090
+ // 找不到或没带 path 时原样交给 DSH 上游,保持它自己的行为。
3091
+ if (url.pathname === '/api/file' && req.method === 'GET') {
3092
+ const wanted = url.searchParams.get('path') ?? '';
3093
+ const found = wanted === '' ? null : filebrowse.findWorkspaceFile(path.resolve(dataDir(), '..', '..'), wanted);
3094
+ if (found !== null) {
3095
+ const contentType = filebrowse.imageMimeOf(found.path);
3096
+ const accept = String(req.headers.accept ?? '');
3097
+ if (contentType !== null && !accept.includes('text/html') && found.size <= 20 * 1024 * 1024) {
3098
+ appendAudit(dir, 'file-open-inline', { path: found.path, bytes: found.size });
3099
+ res.writeHead(200, {
3100
+ 'content-type': contentType,
3101
+ 'content-length': String(found.size),
3102
+ 'cache-control': 'no-store',
3103
+ 'x-content-type-options': 'nosniff',
3104
+ });
3105
+ fs.createReadStream(found.path).pipe(res);
3106
+ return;
3107
+ }
3108
+ appendAudit(dir, 'file-open-redirect', { path: found.path, from: wanted.slice(0, 200) });
3109
+ res.writeHead(302, { location: '/files/view?path=' + encodeURIComponent(found.path), 'cache-control': 'no-store' });
3110
+ res.end();
3111
+ return;
3112
+ }
3113
+ // 没带 path / 文件找不到:退回图片墙,至少比「文件资源服务不可用」有用
3114
+ appendAudit(dir, 'file-open-missing', { from: wanted.slice(0, 200) });
3115
+ res.writeHead(302, { location: '/files/wall', 'cache-control': 'no-store' });
3116
+ res.end();
3117
+ return;
3118
+ }
3119
+
3075
3120
  if (url.pathname === '/files' && req.method === 'GET') {
3076
3121
  const dshHome = path.resolve(dataDir(), '..', '..');
3077
3122
  const index = filebrowse.workspaceIndex(dshHome);
@@ -3244,6 +3289,43 @@ a{color:#8ab4f8}
3244
3289
  return;
3245
3290
  }
3246
3291
 
3292
+ // 图片墙:把某目录(递归)里的图片铺成缩略图网格。
3293
+ // 支持 ?path=目录;也支持 ?session=<会话 id>,由插件映射到该会话所属工作区目录,
3294
+ // 方便从 DSH 会话菜单一键进来(手机上看截图/设计稿更顺手)。
3295
+ if (url.pathname === '/files/wall' && req.method === 'GET') {
3296
+ const dshHome = path.resolve(dataDir(), '..', '..');
3297
+ const session = url.searchParams.get('session') ?? '';
3298
+ const askedPath = url.searchParams.get('path') ?? '';
3299
+ let dir = askedPath === '' ? '' : filebrowse.resolvePath(askedPath);
3300
+ if (dir === '' && session !== '') {
3301
+ dir = filebrowse.workspacePathForSessionId(dshHome, session) ?? filebrowse.sessionCwdById(dshHome, session) ?? '';
3302
+ }
3303
+ if (dir === '') dir = filebrowse.workspaceIndex(dshHome).defaultPath ?? '';
3304
+ if (dir === '') {
3305
+ // 没有任何可定位的目录:不递归扫 HOME(那里图片太多、还可能很慢),给出明确提示
3306
+ appendAudit(dir, 'file-wall', { path: '', images: 0, ok: false });
3307
+ sendHtml(renderWallPage({
3308
+ dir: '',
3309
+ images: [],
3310
+ message: '没有找到可浏览的工作区目录。请从文件页(含目录路径)或会话菜单进入。',
3311
+ isError: true,
3312
+ session,
3313
+ }));
3314
+ return;
3315
+ }
3316
+ const listed = filebrowse.listImages(dir);
3317
+ appendAudit(dir, 'file-wall', { path: dir, images: listed.ok ? listed.images.length : 0, ok: listed.ok });
3318
+ sendHtml(renderWallPage({
3319
+ dir: listed.ok ? listed.dir : dir,
3320
+ images: listed.ok ? listed.images : [],
3321
+ truncated: listed.ok && listed.truncated === true,
3322
+ message: listed.ok ? '' : String(listed.error),
3323
+ isError: !listed.ok,
3324
+ session,
3325
+ }));
3326
+ return;
3327
+ }
3328
+
3247
3329
  if (url.pathname === '/files/view' && req.method === 'GET') {
3248
3330
  const asked = url.searchParams.get('path') ?? '';
3249
3331
  if (office.isOfficeFile(asked) || office.isPdfFile(asked)) {
@@ -3251,14 +3333,29 @@ a{color:#8ab4f8}
3251
3333
  res.end();
3252
3334
  return;
3253
3335
  }
3254
- // 图片:直接渲染预览页(文件列表里点图片名就走这里);字节由 /files/raw 内联返回
3336
+ // 图片:直接渲染预览页(文件列表里点图片名就走这里);字节由 /files/raw 内联返回,
3337
+ // 并把同目录的上一张/下一张一起算好,配合 files-preview.js 支持左右滑动切换。
3255
3338
  if (filebrowse.isImageFile(asked)) {
3256
3339
  const target = filebrowse.resolvePath(asked);
3257
3340
  let stat = null;
3258
3341
  try { stat = fs.statSync(target); } catch { stat = null; }
3259
- const info = stat !== null && stat.isFile()
3342
+ let info = stat !== null && stat.isFile()
3260
3343
  ? { path: target, sizeText: filebrowse.fmtSize(stat.size), mtime: filebrowse.fmtTime(stat.mtime), image: true }
3261
3344
  : { path: target, error: '文件不存在' };
3345
+ if (info.image === true) {
3346
+ // 目录一定存在(target 是刚 stat 成功的文件),listImages 失败时返回空数组
3347
+ const siblings = filebrowse.listImages(path.dirname(target));
3348
+ const images = siblings.images;
3349
+ const index = images.findIndex((item) => item.path === target);
3350
+ if (index >= 0) {
3351
+ info = {
3352
+ ...info,
3353
+ position: `${index + 1} / ${images.length}`,
3354
+ prevHref: index > 0 ? '/files/view?path=' + encodeURIComponent(images[index - 1].path) : '',
3355
+ nextHref: index < images.length - 1 ? '/files/view?path=' + encodeURIComponent(images[index + 1].path) : '',
3356
+ };
3357
+ }
3358
+ }
3262
3359
  appendAudit(dir, 'file-view', { path: target, kind: 'image', ok: info.image === true });
3263
3360
  sendHtml(renderFileView({ info }));
3264
3361
  return;
@@ -263,6 +263,37 @@ const MENU_JS = `<script>
263
263
 
264
264
  const TEXT_FILE_RE = /\.(txt|md|markdown|json|jsonc|js|mjs|cjs|ts|tsx|jsx|css|scss|less|html|htm|xml|yml|yaml|toml|ini|conf|cfg|log|csv|tsv|sh|bash|ps1|bat|cmd|py|rb|go|rs|java|c|h|cpp|hpp|cs|php|sql|env)$/iu
265
265
 
266
+ /** 图片墙:把目录(递归)里的图片铺成缩略图网格,点开进预览页,可左右滑动切换。 */
267
+ export function renderWallPage({ dir = '', images = [], truncated = false, message = '', isError = false, session = '' }) {
268
+ const backHref = session === ''
269
+ ? '/files' + (dir === '' ? '' : '?path=' + encodeURIComponent(dir))
270
+ : '/files?session=' + encodeURIComponent(session)
271
+ const items = images.map((item) => {
272
+ const label = item.rel || item.name
273
+ return `<a class="wallitem" href="/files/view?path=${encodeURIComponent(item.path)}" title="${escapeHtml(label)}">
274
+ <img src="/files/raw?path=${encodeURIComponent(item.path)}" loading="lazy" decoding="async" alt="${escapeHtml(label)}">
275
+ <span>${escapeHtml(label)}</span></a>`
276
+ }).join('')
277
+ const body = `
278
+ <div class="bar">
279
+ <h1>图片墙</h1>
280
+ <div class="path">${escapeHtml(dir)}</div>
281
+ <div class="chips"><a class="chip" href="${backHref}">返回文件</a><span class="chip" style="background:transparent;color:#9aa3b2">${images.length} 张</span></div>
282
+ </div>
283
+ ${message ? `<div class="msg${isError ? ' err' : ''}">${escapeHtml(message)}</div>` : ''}
284
+ ${truncated ? '<div class="msg">图片太多,只显示最新的一部分</div>' : ''}
285
+ ${images.length === 0
286
+ ? '<div class="empty" style="padding:24px 4px;color:#9aa3b2">这个目录下没有可预览的图片(支持 png/jpg/jpeg/gif/webp/bmp)。</div>'
287
+ : `<div class="wall">${items}</div>`}
288
+ <style>
289
+ .wall{display:grid;grid-template-columns:repeat(auto-fill,minmax(110px,1fr));gap:8px;margin-top:12px}
290
+ .wallitem{display:block;text-decoration:none;color:inherit;min-width:0}
291
+ .wallitem img{width:100%;aspect-ratio:1/1;object-fit:cover;border-radius:8px;background:#0f1319;border:1px solid #262b36}
292
+ .wallitem span{display:block;font-size:11px;color:#9aa3b2;margin-top:3px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
293
+ </style>`
294
+ return layout({ title: '图片墙 · DSH', body, current: '/files' })
295
+ }
296
+
266
297
  /** 文件页渲染 */
267
298
  export function renderListing({ info, message, isError, home, dataDir, workspaces = [] }) {
268
299
  const menuFor = (entry) => `<span class="mm">
@@ -320,6 +351,7 @@ ${entry.dir ? `<a class="mi" role="menuitem" data-act="paste" data-path="${escap
320
351
  <div style="flex:1 1 auto;display:flex;align-items:center;justify-content:flex-end;gap:4px;flex-wrap:nowrap;overflow-x:auto;-webkit-overflow-scrolling:touch;scrollbar-width:none">
321
352
  <a class="btn ghost" href="/files?path=${encodeURIComponent(home)}" style="${navStyle}">HOME</a>
322
353
  <a class="btn ghost" href="/files?path=${encodeURIComponent(dataDir)}" style="${navStyle}">配置</a>
354
+ <a class="btn ghost" href="/files/wall?path=${encodeURIComponent(info.path)}" style="${navStyle}">图片墙</a>
323
355
  ${parent}
324
356
  </div>
325
357
  </div>
@@ -422,7 +454,7 @@ export function renderCompressPage({ target, archive, message, isError, done = f
422
454
  return layout({ title: '加密压缩 · ' + name, body })
423
455
  }
424
456
 
425
- /** 文件内容页(text=源码;rendered=Markdown 渲染结果) */
457
+ /** 文件内容页(text=源码;rendered=Markdown 渲染结果;image=图片预览) */
426
458
  export function renderFile({ info, message, isError, rendered = null }) {
427
459
  const isMarkdown = /\.(?:md|markdown|mdown|mkd)$/iu.test(info.path)
428
460
  const isImage = info.image === true
@@ -430,6 +462,14 @@ export function renderFile({ info, message, isError, rendered = null }) {
430
462
  const renderedHref = '/files/view?path=' + encodeURIComponent(info.path)
431
463
  const rawHref = '/files/raw?path=' + encodeURIComponent(info.path)
432
464
  const downloadHref = '/files/download?path=' + encodeURIComponent(info.path)
465
+ // 图片:同目录内的上一张/下一张(由路由算好放进 info),配合 files-preview.js 的左右滑动
466
+ const imageNav = isImage && info.error === undefined
467
+ ? `<div class="chips" style="align-items:center">
468
+ ${info.prevHref ? `<a class="chip" id="img-prev" href="${info.prevHref}">← 上一张</a>` : ''}
469
+ ${info.position ? `<span class="chip" style="background:transparent;color:#9aa3b2">${escapeHtml(info.position)}</span>` : ''}
470
+ ${info.nextHref ? `<a class="chip" id="img-next" href="${info.nextHref}">下一张 →</a>` : ''}
471
+ </div>`
472
+ : ''
433
473
  const toggle = isImage
434
474
  ? `<div class="chips"><a class="chip" href="${rawHref}" target="_blank" rel="noopener noreferrer">查看原图</a><a class="chip" href="${downloadHref}">下载</a></div>`
435
475
  : rendered
@@ -442,14 +482,16 @@ export function renderFile({ info, message, isError, rendered = null }) {
442
482
  <h1>${escapeHtml(info.path.split(/[\\/]/u).pop())}</h1>
443
483
  <div class="path">${escapeHtml(info.path)}</div>
444
484
  ${toggle}
485
+ ${imageNav}
445
486
  </div>
446
487
  ${messageHtml(message, isError)}
447
488
  ${info.error ? `<div class="msg err">${escapeHtml(info.error)}</div>` : ''}
448
489
  ${isImage && info.error === undefined
449
490
  ? `<div style="margin:10px 0;padding:10px;border-radius:10px;background:#0f1319;text-align:center">
450
491
  <a href="${rawHref}" target="_blank" rel="noopener noreferrer"><img src="${rawHref}" alt="${escapeHtml(info.path.split(/[\\/]/u).pop())}" style="max-width:100%;height:auto;display:block;margin:0 auto;border-radius:6px"></a>
451
- <p class="crumbs" style="margin-top:8px">点图片可在新标签打开原图${info.sizeText ? ` · ${escapeHtml(info.sizeText)}` : ''}</p>
452
- </div>`
492
+ <p class="crumbs" style="margin-top:8px">左右滑动可切换上一张 / 下一张${info.sizeText ? ` · ${escapeHtml(info.sizeText)}` : ''}</p>
493
+ </div>
494
+ <script src="/dsh_homing/files-preview.js"></script>`
453
495
  : (rendered ? `<article class="md-body">${rendered.html}</article>` : (info.text !== undefined ? `<pre>${escapeHtml(info.text)}</pre>` : ''))}
454
496
  <div class="row">
455
497
  <a class="btn ghost" href="/files?path=${encodeURIComponent(info.path.replace(/[\\/][^\\/]*$/u, '') || '/')}"
@@ -0,0 +1,40 @@
1
+ /**
2
+ * 图片预览页的手势脚本(外部文件:页面 CSP 是 script-src 'self',不能内联)。
3
+ *
4
+ * 作用:在图片预览页左右滑动切换上一张/下一张(桌面端也支持 ←/→ 键)。
5
+ * 链接由服务端渲染在 #img-prev / #img-next 上;任一方向没有相邻图时对应链接不存在。
6
+ */
7
+ (() => {
8
+ const prev = document.getElementById('img-prev')
9
+ const next = document.getElementById('img-next')
10
+ if (prev === null && next === null) return
11
+
12
+ const go = (node) => {
13
+ if (node !== null) window.location.href = node.getAttribute('href')
14
+ }
15
+
16
+ let startX = 0
17
+ let startY = 0
18
+ let tracking = false
19
+ window.addEventListener('touchstart', (event) => {
20
+ if (event.touches.length !== 1) { tracking = false; return }
21
+ tracking = true
22
+ startX = event.touches[0].clientX
23
+ startY = event.touches[0].clientY
24
+ }, { passive: true })
25
+ window.addEventListener('touchend', (event) => {
26
+ if (!tracking) return
27
+ tracking = false
28
+ const touch = event.changedTouches && event.changedTouches[0]
29
+ if (!touch) return
30
+ const dx = touch.clientX - startX
31
+ const dy = touch.clientY - startY
32
+ // 只认明显的水平滑动,避免把页面上下滚动误判成切换
33
+ if (Math.abs(dx) < 60 || Math.abs(dx) < Math.abs(dy)) return
34
+ go(dx > 0 ? prev : next)
35
+ }, { passive: true })
36
+ window.addEventListener('keydown', (event) => {
37
+ if (event.key === 'ArrowLeft') go(prev)
38
+ else if (event.key === 'ArrowRight') go(next)
39
+ })
40
+ })()
package/lib/files.mjs CHANGED
@@ -295,6 +295,113 @@ export const isImageFile = (name) => IMAGE_MIME.has(path.extname(String(name ??
295
295
  /** 图片 MIME;不是白名单图片格式返回 null */
296
296
  export const imageMimeOf = (name) => IMAGE_MIME.get(path.extname(String(name ?? '')).toLowerCase()) ?? null
297
297
 
298
+ /** 图片墙/相册:递归收集目录下的可预览图片(有深度与数量上限,跳过隐藏目录与依赖目录)。 */
299
+ const SKIP_DIRS = new Set(['node_modules', '.git'])
300
+
301
+ /**
302
+ * @param {string} dirPath
303
+ * @param {{ maxFiles?: number, maxDepth?: number }} [options]
304
+ * @returns {{ ok: boolean, dir?: string, images?: Array, truncated?: boolean, error?: string }}
305
+ */
306
+ export function listImages(dirPath, { maxFiles = 300, maxDepth = 4 } = {}) {
307
+ const root = resolvePath(dirPath)
308
+ let rootStat = null
309
+ try { rootStat = fs.statSync(root) } catch { rootStat = null }
310
+ if (!rootStat || !rootStat.isDirectory()) return { ok: false, images: [], error: '这不是目录或目录不存在' }
311
+
312
+ const images = []
313
+ let truncated = false
314
+ const walk = (dir, depth) => {
315
+ let names = []
316
+ try { names = fs.readdirSync(dir) } catch { return }
317
+ for (const name of names) {
318
+ if (truncated) return
319
+ if (name.startsWith('.')) continue
320
+ const full = path.join(dir, name)
321
+ let stat = null
322
+ try { stat = fs.statSync(full) } catch { continue }
323
+ if (stat.isDirectory()) {
324
+ if (depth >= maxDepth || SKIP_DIRS.has(name)) continue
325
+ walk(full, depth + 1)
326
+ continue
327
+ }
328
+ if (!isImageFile(name)) continue
329
+ images.push({
330
+ name,
331
+ rel: path.relative(root, full).split(path.sep).join('/'),
332
+ path: full,
333
+ size: stat.size,
334
+ sizeText: fmtSize(stat.size),
335
+ mtimeMs: stat.mtimeMs,
336
+ mtime: fmtTime(stat.mtime),
337
+ })
338
+ if (images.length >= maxFiles) { truncated = true; return }
339
+ }
340
+ }
341
+ walk(root, 0)
342
+ images.sort((a, b) => b.mtimeMs - a.mtimeMs || a.rel.localeCompare(b.rel, 'zh'))
343
+ return { ok: true, dir: root, images, truncated }
344
+ }
345
+
346
+ /**
347
+ * 按「路径或文件名」在 DSH 工作区里找一个文件(DSH 网页端图片卡片请求
348
+ * `/api/file?path=...`,path 可能是绝对路径,也可能是相对工作区的
349
+ * `build/tmp/x.png`;文件已移动/删除时返回 null)。
350
+ * 只读、有预算上限,避免在大仓库里跑飞。
351
+ */
352
+ export function findWorkspaceFile(dshHome, wanted, { maxDepth = 6, maxFiles = 20000 } = {}) {
353
+ const raw = String(wanted ?? '').trim().replaceAll('\\', '/').replace(/^\.\//u, '')
354
+ if (raw === '') return null
355
+ const absoluteLike = path.isAbsolute(raw)
356
+ // 绝对路径:直接命中(不存在就继续按工作区搜索兜底)
357
+ const absolute = absoluteLike ? path.resolve(raw) : resolvePath(raw)
358
+ let stat = null
359
+ try { stat = fs.statSync(absolute) } catch { stat = null }
360
+ if (stat !== null && stat.isFile()) return { path: absolute, mtimeMs: stat.mtimeMs, size: stat.size, exact: true }
361
+
362
+ // 相对路径:在工作区里按「完整相对路径结尾 / 同名文件」匹配,取最新修改的一个。
363
+ // 绝对路径但文件已不在原处时,退化成按文件名找(文件被移动/工作区换路径的常见情况)。
364
+ if (raw.includes('..')) return null
365
+ const lower = (absoluteLike ? path.basename(raw) : raw).toLowerCase()
366
+ const index = workspaceIndex(dshHome)
367
+ const roots = [...new Set([...index.list.map((item) => item.path), index.defaultPath]
368
+ .filter((item) => typeof item === 'string' && item !== ''))]
369
+ let visited = 0
370
+ const candidates = []
371
+ const consider = (full, rel, st) => {
372
+ const relLower = rel.toLowerCase()
373
+ if (relLower !== lower && !relLower.endsWith('/' + lower)) return
374
+ candidates.push({ path: full, mtimeMs: st.mtimeMs, size: st.size, exact: relLower === lower })
375
+ }
376
+ const walk = (dir, rel, depth) => {
377
+ if (depth > maxDepth || visited >= maxFiles) return
378
+ let names = []
379
+ try { names = fs.readdirSync(dir) } catch { return }
380
+ for (const name of names) {
381
+ if (name.startsWith('.')) continue
382
+ const full = path.join(dir, name)
383
+ let st = null
384
+ try { st = fs.statSync(full) } catch { continue }
385
+ const childRel = rel === '' ? name : rel + '/' + name
386
+ if (st.isDirectory()) {
387
+ if (SKIP_DIRS.has(name)) continue
388
+ walk(full, childRel, depth + 1)
389
+ continue
390
+ }
391
+ if (!st.isFile()) continue
392
+ visited += 1
393
+ consider(full, childRel, st)
394
+ if (visited >= maxFiles) return
395
+ }
396
+ }
397
+ for (const root of roots) walk(root, '', 0)
398
+ // 排序键:精确相对路径永远优先,其次按修改时间新→旧。
399
+ // 用单一数值 key 排序(无分支),避免多进程 V8 覆盖统计把条件分支算成未覆盖。
400
+ const rank = (item) => (item.exact ? 1e15 : 0) + item.mtimeMs
401
+ candidates.sort((a, b) => rank(b) - rank(a))
402
+ return candidates[0] ?? null
403
+ }
404
+
298
405
  /** 读文本文件;二进制或过大时不返回正文。 */
299
406
  export function readTextFile(absPath, limit = MAX_READ) {
300
407
  const target = resolvePath(absPath)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andy.ian/dsh-homing",
3
- "version": "2.3.2",
3
+ "version": "2.3.4",
4
4
  "type": "module",
5
5
  "description": "把本机 DSH 通过 SSH 反向隧道安全开放到手机浏览器:TLS 端到端(服务器只透传)、账号 + TOTP、局域网与公网双入口,随 DSH 启动。",
6
6
  "keywords": [