@andy.ian/dsh-homing 2.3.3 → 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.
Files changed (3) hide show
  1. package/index.js +36 -0
  2. package/lib/files.mjs +59 -0
  3. package/package.json +1 -1
package/index.js CHANGED
@@ -3062,6 +3062,7 @@ a{color:#8ab4f8}
3062
3062
 
3063
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'
3064
3064
  || url.pathname === '/files/rename'
3065
+ || url.pathname === '/api/file'
3065
3066
  || url.pathname === '/files/delete' || url.pathname === '/files/paste'
3066
3067
  || url.pathname === '/files/mkdir' || url.pathname === '/files/newfile') {
3067
3068
  if (!sessionValid(req) && currentDevice(req) === null) {
@@ -3081,6 +3082,41 @@ a{color:#8ab4f8}
3081
3082
  res.end(page);
3082
3083
  };
3083
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
+
3084
3120
  if (url.pathname === '/files' && req.method === 'GET') {
3085
3121
  const dshHome = path.resolve(dataDir(), '..', '..');
3086
3122
  const index = filebrowse.workspaceIndex(dshHome);
package/lib/files.mjs CHANGED
@@ -343,6 +343,65 @@ export function listImages(dirPath, { maxFiles = 300, maxDepth = 4 } = {}) {
343
343
  return { ok: true, dir: root, images, truncated }
344
344
  }
345
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
+
346
405
  /** 读文本文件;二进制或过大时不返回正文。 */
347
406
  export function readTextFile(absPath, limit = MAX_READ) {
348
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.3",
3
+ "version": "2.3.4",
4
4
  "type": "module",
5
5
  "description": "把本机 DSH 通过 SSH 反向隧道安全开放到手机浏览器:TLS 端到端(服务器只透传)、账号 + TOTP、局域网与公网双入口,随 DSH 启动。",
6
6
  "keywords": [