files.js 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. /**
  2. * 文件
  3. * ====
  4. * Web 版没有"老师的桌面",所有产物都落在该老师自己的工作区里,通过浏览器下载。
  5. * 页面函数投递需要"页面自己去取字节",所以另有一条**短时 token** 的读取地址:
  6. *
  7. * /_cc/blob/<token> —— 只对 token 里的那一个文件有效,60 秒过期,CORS 放开
  8. *
  9. * 为什么不在页面里直接塞 base64:PPT 动辄几十 MB,Runtime.evaluate 的参数体积
  10. * 会被 CDP 和内联脚本上限卡住,而且 base64 要占 1.33 倍内存。
  11. */
  12. import fs from 'node:fs'
  13. import fsp from 'node:fs/promises'
  14. import path from 'node:path'
  15. import crypto from 'node:crypto'
  16. const MAX_UPLOAD = 512 * 1024 * 1024
  17. const BLOB_TTL = 60_000
  18. export class Files {
  19. /** @param {{roots:string[]}} options 允许读写的根目录 */
  20. constructor (options) {
  21. this.roots = options.roots.filter(Boolean).map((r) => path.resolve(r))
  22. this.blobs = new Map()
  23. this.sweeper = setInterval(() => {
  24. const now = Date.now()
  25. for (const [token, entry] of this.blobs) if (entry.expires < now) this.blobs.delete(token)
  26. }, 30_000)
  27. this.sweeper.unref?.()
  28. }
  29. /** 把用户给的路径钉在允许的根里;越界返回 null,绝不返回一个"看起来对"的路径 */
  30. resolve (input) {
  31. const raw = String(input || '').trim()
  32. if (!raw) return null
  33. const abs = path.resolve(this.roots[0], raw)
  34. for (const root of this.roots) {
  35. const rel = path.relative(root, abs)
  36. if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) return abs
  37. if (abs === root) return abs
  38. }
  39. return null
  40. }
  41. async saveUpload (name, stream, maxBytes = MAX_UPLOAD) {
  42. const safeName = path.basename(String(name || 'upload.bin')).replace(/[\\/:*?"<>|]/g, '_').slice(0, 120)
  43. const dir = path.join(this.roots[0], 'uploads')
  44. await fsp.mkdir(dir, { recursive: true })
  45. const target = path.join(dir, `${Date.now()}-${safeName}`)
  46. let size = 0
  47. await new Promise((resolve, reject) => {
  48. const out = fs.createWriteStream(target)
  49. stream.on('data', (chunk) => {
  50. size += chunk.length
  51. if (size > maxBytes) {
  52. stream.destroy()
  53. out.destroy()
  54. fsp.unlink(target).catch(() => {})
  55. reject(Object.assign(new Error('文件超过 512MB 上限'), { code: 'too_large' }))
  56. }
  57. })
  58. stream.pipe(out)
  59. out.on('finish', resolve)
  60. out.on('error', reject)
  61. stream.on('error', reject)
  62. })
  63. return { path: target, size, name: safeName }
  64. }
  65. /** 给页面用的短时地址:只映射一个文件,过期自动失效 */
  66. blobUrl (filePath, publicBase) {
  67. const abs = this.resolve(filePath)
  68. if (!abs) return ''
  69. const token = crypto.randomBytes(24).toString('base64url')
  70. this.blobs.set(token, { path: abs, expires: Date.now() + BLOB_TTL })
  71. return `${publicBase}/_cc/blob/${token}`
  72. }
  73. takeBlob (token) {
  74. const entry = this.blobs.get(String(token || ''))
  75. if (!entry) return null
  76. if (entry.expires < Date.now()) {
  77. this.blobs.delete(token)
  78. return null
  79. }
  80. return entry.path
  81. }
  82. async stat (filePath) {
  83. return fsp.stat(filePath).catch(() => null)
  84. }
  85. /** 目录树:只列两层,够老师找产物;再深让他下载整包 */
  86. async list (dir, depth = 2) {
  87. const root = this.resolve(dir || this.roots[0])
  88. if (!root) return null
  89. const out = []
  90. const walk = async (current, level) => {
  91. let entries = []
  92. try { entries = await fsp.readdir(current, { withFileTypes: true }) } catch { return }
  93. for (const entry of entries) {
  94. if (entry.name.startsWith('.') || entry.name === 'node_modules') continue
  95. const full = path.join(current, entry.name)
  96. const rel = path.relative(this.roots[0], full)
  97. if (entry.isDirectory()) {
  98. out.push({ type: 'dir', path: rel, name: entry.name })
  99. if (level > 1) await walk(full, level - 1)
  100. } else if (entry.isFile()) {
  101. const info = await this.stat(full)
  102. out.push({ type: 'file', path: rel, name: entry.name, size: info ? info.size : 0, mtime: info ? info.mtimeMs : 0 })
  103. }
  104. if (out.length > 2000) return
  105. }
  106. }
  107. await walk(root, depth)
  108. return out
  109. }
  110. async readSmall (filePath, limit = 512 * 1024) {
  111. const abs = this.resolve(filePath)
  112. if (!abs) return null
  113. const info = await this.stat(abs)
  114. if (!info || !info.isFile() || info.size > limit) return null
  115. return fsp.readFile(abs)
  116. }
  117. dispose () {
  118. clearInterval(this.sweeper)
  119. this.blobs.clear()
  120. }
  121. }