@andy.ian/dsh-homing 2.3.2 → 2.3.3

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,7 +3060,7 @@ 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'
3056
3065
  || url.pathname === '/files/delete' || url.pathname === '/files/paste'
3057
3066
  || url.pathname === '/files/mkdir' || url.pathname === '/files/newfile') {
@@ -3244,6 +3253,43 @@ a{color:#8ab4f8}
3244
3253
  return;
3245
3254
  }
3246
3255
 
3256
+ // 图片墙:把某目录(递归)里的图片铺成缩略图网格。
3257
+ // 支持 ?path=目录;也支持 ?session=<会话 id>,由插件映射到该会话所属工作区目录,
3258
+ // 方便从 DSH 会话菜单一键进来(手机上看截图/设计稿更顺手)。
3259
+ if (url.pathname === '/files/wall' && req.method === 'GET') {
3260
+ const dshHome = path.resolve(dataDir(), '..', '..');
3261
+ const session = url.searchParams.get('session') ?? '';
3262
+ const askedPath = url.searchParams.get('path') ?? '';
3263
+ let dir = askedPath === '' ? '' : filebrowse.resolvePath(askedPath);
3264
+ if (dir === '' && session !== '') {
3265
+ dir = filebrowse.workspacePathForSessionId(dshHome, session) ?? filebrowse.sessionCwdById(dshHome, session) ?? '';
3266
+ }
3267
+ if (dir === '') dir = filebrowse.workspaceIndex(dshHome).defaultPath ?? '';
3268
+ if (dir === '') {
3269
+ // 没有任何可定位的目录:不递归扫 HOME(那里图片太多、还可能很慢),给出明确提示
3270
+ appendAudit(dir, 'file-wall', { path: '', images: 0, ok: false });
3271
+ sendHtml(renderWallPage({
3272
+ dir: '',
3273
+ images: [],
3274
+ message: '没有找到可浏览的工作区目录。请从文件页(含目录路径)或会话菜单进入。',
3275
+ isError: true,
3276
+ session,
3277
+ }));
3278
+ return;
3279
+ }
3280
+ const listed = filebrowse.listImages(dir);
3281
+ appendAudit(dir, 'file-wall', { path: dir, images: listed.ok ? listed.images.length : 0, ok: listed.ok });
3282
+ sendHtml(renderWallPage({
3283
+ dir: listed.ok ? listed.dir : dir,
3284
+ images: listed.ok ? listed.images : [],
3285
+ truncated: listed.ok && listed.truncated === true,
3286
+ message: listed.ok ? '' : String(listed.error),
3287
+ isError: !listed.ok,
3288
+ session,
3289
+ }));
3290
+ return;
3291
+ }
3292
+
3247
3293
  if (url.pathname === '/files/view' && req.method === 'GET') {
3248
3294
  const asked = url.searchParams.get('path') ?? '';
3249
3295
  if (office.isOfficeFile(asked) || office.isPdfFile(asked)) {
@@ -3251,14 +3297,29 @@ a{color:#8ab4f8}
3251
3297
  res.end();
3252
3298
  return;
3253
3299
  }
3254
- // 图片:直接渲染预览页(文件列表里点图片名就走这里);字节由 /files/raw 内联返回
3300
+ // 图片:直接渲染预览页(文件列表里点图片名就走这里);字节由 /files/raw 内联返回,
3301
+ // 并把同目录的上一张/下一张一起算好,配合 files-preview.js 支持左右滑动切换。
3255
3302
  if (filebrowse.isImageFile(asked)) {
3256
3303
  const target = filebrowse.resolvePath(asked);
3257
3304
  let stat = null;
3258
3305
  try { stat = fs.statSync(target); } catch { stat = null; }
3259
- const info = stat !== null && stat.isFile()
3306
+ let info = stat !== null && stat.isFile()
3260
3307
  ? { path: target, sizeText: filebrowse.fmtSize(stat.size), mtime: filebrowse.fmtTime(stat.mtime), image: true }
3261
3308
  : { path: target, error: '文件不存在' };
3309
+ if (info.image === true) {
3310
+ // 目录一定存在(target 是刚 stat 成功的文件),listImages 失败时返回空数组
3311
+ const siblings = filebrowse.listImages(path.dirname(target));
3312
+ const images = siblings.images;
3313
+ const index = images.findIndex((item) => item.path === target);
3314
+ if (index >= 0) {
3315
+ info = {
3316
+ ...info,
3317
+ position: `${index + 1} / ${images.length}`,
3318
+ prevHref: index > 0 ? '/files/view?path=' + encodeURIComponent(images[index - 1].path) : '',
3319
+ nextHref: index < images.length - 1 ? '/files/view?path=' + encodeURIComponent(images[index + 1].path) : '',
3320
+ };
3321
+ }
3322
+ }
3262
3323
  appendAudit(dir, 'file-view', { path: target, kind: 'image', ok: info.image === true });
3263
3324
  sendHtml(renderFileView({ info }));
3264
3325
  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,54 @@ 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
+
298
346
  /** 读文本文件;二进制或过大时不返回正文。 */
299
347
  export function readTextFile(absPath, limit = MAX_READ) {
300
348
  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.3",
4
4
  "type": "module",
5
5
  "description": "把本机 DSH 通过 SSH 反向隧道安全开放到手机浏览器:TLS 端到端(服务器只透传)、账号 + TOTP、局域网与公网双入口,随 DSH 启动。",
6
6
  "keywords": [