fileAccess.ts 5.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
  2. import { basename, dirname, join, posix } from 'node:path'
  3. import { randomUUID } from 'node:crypto'
  4. import { serverFilePath } from '../shared/serverFiles.js'
  5. import type { ServerConfig } from './config.js'
  6. import type { UpstreamServiceSession } from './localAuth.js'
  7. import { HttpError } from './errors.js'
  8. import { configuredWorkingDirectory } from './sessionWorkingDirectory.js'
  9. type FileHost = Pick<UpstreamServiceSession, 'request'>
  10. export interface FileAccessSettings { mode: 'all' | 'folders'; folders: string[] }
  11. const settingsPath = (home: string) => join(home, 'file-access.json')
  12. export function parseFileAccess(value: unknown): FileAccessSettings {
  13. const input = value as Partial<FileAccessSettings> | null
  14. if (!input || !['all', 'folders'].includes(String(input.mode)) || !Array.isArray(input.folders) || input.folders.length > 100)
  15. throw new HttpError(400, '请选择全部目录或指定目录,目录最多 100 个', 'invalid_file_access')
  16. const folders = input.folders.map(folder => {
  17. const path = typeof folder === 'string' && folder.length <= 8192 ? serverFilePath(folder, false) : undefined
  18. if (!path) throw new HttpError(400, '目录必须使用服务器上的绝对路径,不能包含 ..', 'invalid_file_access_folder')
  19. return posix.normalize(path)
  20. })
  21. return { mode: input.mode!, folders: [...new Set(folders)] }
  22. }
  23. export function readFileAccess(home: string): FileAccessSettings {
  24. if (!existsSync(settingsPath(home))) return { mode: 'folders', folders: [] }
  25. try { return parseFileAccess(JSON.parse(readFileSync(settingsPath(home), 'utf8'))) }
  26. catch { throw new HttpError(503, '文件访问设置无法读取,请由管理员重新保存', 'file_access_configuration_error') }
  27. }
  28. export function saveFileAccess(home: string, value: unknown): FileAccessSettings {
  29. const settings = parseFileAccess(value)
  30. mkdirSync(home, { recursive: true, mode: 0o700 })
  31. const temporary = settingsPath(home) + '.' + randomUUID()
  32. writeFileSync(temporary, JSON.stringify(settings, null, 2) + '\n', { mode: 0o600 })
  33. renameSync(temporary, settingsPath(home))
  34. return settings
  35. }
  36. export async function fileAccessWorkingDirectory(upstream: FileHost, profile: string): Promise<string> {
  37. const configured = await configuredWorkingDirectory((path, options) => upstream.request(path, options), profile)
  38. const absolute = configured ? serverFilePath(configured, false) : undefined
  39. if (absolute) return absolute
  40. // Let Hermes expand its own home/relative directory; never use the Web process cwd.
  41. const response = await upstream.request('/api/fs/default-cwd', { search: new URLSearchParams({ profile }), cache: 'reload' })
  42. let path: string | undefined
  43. try { path = serverFilePath(JSON.parse(response.body.toString()).cwd ?? '', false) } catch { /* Refuse an unresolved cwd. */ }
  44. if (response.status !== 200 || !path) throw new HttpError(503, '无法解析服务端 terminal.cwd,请在服务器配置有效工作目录', 'file_cwd_unavailable')
  45. return path
  46. }
  47. export async function authorizeFileRead(config: Pick<ServerConfig, 'home'>, upstream: FileHost, raw: string, profile = 'default', directoryRequest = false): Promise<string> {
  48. const path = serverFilePath(raw, false)
  49. if (!path) throw new HttpError(400, '文件路径无效', 'invalid_file_path')
  50. const policy = readFileAccess(config.home)
  51. if (policy.mode === 'all') return path // Upstream authentication and filesystem restrictions still apply.
  52. const cwd = await fileAccessWorkingDirectory(upstream, profile)
  53. const allowed = [cwd, ...policy.folders]
  54. const contains = (file: string, roots: string[]) => roots.some(root => file === root || file.startsWith(root.replace(/\/$/, '') + '/'))
  55. // Even a loopback gateway can be in a container. Canonical paths must come
  56. // from Hermes, never from the Web process's filesystem or working directory.
  57. const directories = new Map<string, Promise<{path: string; entries: Array<{name: string; path: string}>}>>()
  58. const directory = (folder: string) => {
  59. if (!directories.has(folder)) directories.set(folder, (async () => {
  60. const response = await upstream.request('/api/files', { search: new URLSearchParams({ path: folder, profile }), cache: 'reload' })
  61. if (response.status !== 200) throw new HttpError(response.status === 404 ? 404 : 403, '无法核对服务器文件目录,请检查目录权限或文件是否存在', 'remote_file_directory_unverified')
  62. try {
  63. const value = JSON.parse(response.body.toString())
  64. if (typeof value.path !== 'string' || !Array.isArray(value.entries)) throw new Error()
  65. return value
  66. } catch { throw new HttpError(502, '服务器文件目录响应无效', 'remote_file_directory_unverified') }
  67. })())
  68. return directories.get(folder)!
  69. }
  70. const roots = (await Promise.all(allowed.map(async root => {
  71. try { return serverFilePath((await directory(root)).path, false) } catch { return undefined }
  72. }))).filter((value): value is string => Boolean(value))
  73. if (!contains(path, [...allowed, ...roots])) throw new HttpError(403, '文件不在工作目录或额外授权目录内,请检查服务端「设置 → 文件访问」', 'file_directory_not_allowed')
  74. const parent = directoryRequest ? undefined : await directory(dirname(path))
  75. const selected = parent?.entries.find(entry => entry.name === basename(path))
  76. if (!directoryRequest && !selected) throw new HttpError(404, '服务器文件不存在、已被移动或不可读取', 'file_not_found')
  77. const canonical = serverFilePath(directoryRequest ? (await directory(path)).path : selected!.path, false)
  78. if (!canonical || !contains(canonical, roots)) throw new HttpError(403, '文件不在工作目录或额外授权目录内,请检查服务端「设置 → 文件访问」', 'file_directory_not_allowed')
  79. return canonical
  80. }