Skip to content

A full-featured download manager.

14.7 KB
Raw Blame
import { constants } from 'node:fs'
import { access, lstat, mkdir, opendir, realpath, stat } from 'node:fs/promises'
import { homedir } from 'node:os'
import path from 'node:path'
import { AppError } from '@shared/errors'
import {
  CreateServerDirectoryRequestSchema,
  type CreateServerDirectoryResult,
  CreateServerDirectoryResultSchema,
  type DirectoryErrorCode,
  ListServerDirectoriesRequestSchema,
  type ListServerDirectoriesResult,
  ListServerDirectoriesResultSchema,
  ListServerDirectoryLocationsRequestSchema,
  type ListServerDirectoryLocationsResult,
  ListServerDirectoryLocationsResultSchema,
  SERVER_DIRECTORY_ENTRY_LIMIT,
  SERVER_DIRECTORY_PATH_LIMIT,
  SERVER_DIRECTORY_SCAN_LIMIT,
  type ServerDirectoryLocations,
  ValidateServerDirectoryRequestSchema,
  type ValidateServerDirectoryResult,
  ValidateServerDirectoryResultSchema,
  ValidateServerFileRequestSchema,
} from '@shared/schemas/server-directory'
import type { MotrixAppSettings } from '@shared/types/settings'
import {
  type AuthorizedServerDirectory,
  DirectoryAuthorizationError,
  type ServerDownloadPathPolicy,
} from './download-path-policy'

const filesystem = { access, mkdir, opendir }

function errorCode(error: unknown): DirectoryErrorCode {
  if (error instanceof DirectoryAuthorizationError) return error.directoryCode
  if (error instanceof AppError) return 'invalidPath'
  switch ((error as NodeJS.ErrnoException | null)?.code) {
    case 'ENOENT':
      return 'notFound'
    case 'ENOTDIR':
      return 'notDirectory'
    case 'EPERM':
    case 'EROFS':
    case 'EACCES':
      return 'permissionDenied'
    case 'EEXIST':
      return 'alreadyExists'
    case 'ENAMETOOLONG':
      return 'tooLarge'
    case 'EINVAL':
      return 'invalidPath'
    default:
      return 'unavailable'
  }
}

function failure(code: DirectoryErrorCode) {
  return { ok: false as const, error: { code } }
}

function validName(name: string): boolean {
  if (
    name === '.' ||
    name === '..' ||
    /[/\\]/u.test(name) ||
    Array.from(name).some(
      (character) =>
        character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127
    )
  )
    return false
  if (process.platform !== 'win32') return true
  return !(
    /[<>:"|?*]/u.test(name) ||
    /[. ]$/u.test(name) ||
    /^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/iu.test(name)
  )
}

function navigation(directory: AuthorizedServerDirectory) {
  const breadcrumbs = [
    {
      name: path.basename(directory.rootPath) || directory.rootPath,
      path: directory.rootPath,
    },
  ]
  const suffix = path.relative(directory.rootPath, directory.path)
  let current = directory.rootPath
  for (const name of suffix ? suffix.split(path.sep) : []) {
    current = path.join(current, name)
    breadcrumbs.push({ name, path: current })
  }
  return {
    breadcrumbs,
    parentPath: suffix === '' ? null : path.dirname(directory.path),
  }
}

/** Read operations never prepare directories or create write probes. */
export class ServerDirectoryService {
  constructor(
    private readonly policy: ServerDownloadPathPolicy,
    private readonly fs: typeof filesystem = filesystem,
    private readonly homeDirectory: () => string = homedir,
    private readonly authorizeFile?: (path: string) => Promise<unknown>
  ) {}

  async resolvePreferenceDirectory(value: string): Promise<string> {
    if (!path.isAbsolute(value) || value.includes('\0')) {
      throw new DirectoryAuthorizationError('invalidPath', 'Invalid directory')
    }
    const directory = await this.policy.authorizeDirectory(value)
    await this.fs.access(
      directory.canonicalPath,
      constants.R_OK | constants.X_OK
    )
    return directory.path
  }

  async locations(
    raw: unknown,
    settings: Pick<MotrixAppSettings, 'defaultSaveDir' | 'directoryPreferences'>
  ): Promise<ListServerDirectoryLocationsResult> {
    if (!ListServerDirectoryLocationsRequestSchema.safeParse(raw).success)
      return failure('invalidPath')
    try {
      const home = this.homeDirectory()
      const value: ServerDirectoryLocations = {
        common: [],
        favorites: [],
        recent: [],
      }
      const candidates: ServerDirectoryLocations['common'] = [
        { kind: 'default', path: settings.defaultSaveDir },
        { kind: 'home', path: home },
        { kind: 'desktop', path: path.join(home, 'Desktop') },
        { kind: 'documents', path: path.join(home, 'Documents') },
        { kind: 'downloads', path: path.join(home, 'Downloads') },
        { kind: 'root', path: path.parse(settings.defaultSaveDir).root },
      ]
      const aliases = new Map<string, string>()
      const authorize = async (candidate: string) => {
        if (!candidate || candidate.length > SERVER_DIRECTORY_PATH_LIMIT)
          return null
        try {
          const directory = await this.policy.authorizeDirectory(candidate)
          await this.fs.access(
            directory.canonicalPath,
            constants.R_OK | constants.X_OK
          )
          const logical = aliases.get(directory.canonicalPath) ?? directory.path
          aliases.set(directory.canonicalPath, logical)
          return { canonical: directory.canonicalPath, path: logical }
        } catch {
          // Discovery never removes saved records or creates unavailable places.
          return null
        }
      }
      for (const candidate of candidates) {
        const directory = await authorize(candidate.path)
        if (directory)
          value.common.push({ kind: candidate.kind, path: directory.path })
      }
      for (const section of ['favorites', 'recent'] as const) {
        const groups = new Map<
          string,
          ServerDirectoryLocations[typeof section][number]
        >()
        for (const saved of settings.directoryPreferences[section]) {
          const directory = await authorize(saved)
          if (!directory) continue
          const existing = groups.get(directory.canonical)
          if (existing) {
            if (!existing.sourcePaths.includes(saved))
              existing.sourcePaths.push(saved)
          } else {
            const location = {
              name: path.basename(directory.path) || directory.path,
              path: directory.path,
              sourcePaths: [saved],
            }
            groups.set(directory.canonical, location)
            value[section].push(location)
          }
        }
      }
      return ListServerDirectoryLocationsResultSchema.parse({ ok: true, value })
    } catch {
      return failure('unavailable')
    }
  }

  private async writable(
    directory: AuthorizedServerDirectory
  ): Promise<boolean> {
    try {
      await this.fs.access(
        directory.canonicalPath,
        constants.W_OK | constants.X_OK
      )
      return true
    } catch (error) {
      if (errorCode(error) === 'permissionDenied') return false
      throw error
    }
  }

  private async readableFile(value: string) {
    // Check both the user-visible parent and the resolved target's parent, so
    // a symlink cannot expose a file outside the configured download roots.
    const parent = await this.policy.authorizeDirectory(path.dirname(value))
    const logicalPath = path.join(parent.path, path.basename(value))
    const canonical = await realpath(logicalPath)
    await this.policy.authorizeDirectory(path.dirname(canonical))
    await this.authorizeFile?.(canonical)
    const info = await stat(canonical)
    if (!info.isFile())
      throw new DirectoryAuthorizationError('notFile', 'Not a regular file')
    await this.fs.access(canonical, constants.R_OK)
    return { path: logicalPath, modifiedAt: info.mtimeMs }
  }

  async validateFile(raw: unknown): Promise<ValidateServerDirectoryResult> {
    const parsed = ValidateServerFileRequestSchema.safeParse(raw)
    if (!parsed.success) return failure('invalidPath')
    const request = parsed.data
    try {
      const name =
        request.kind === 'open' ? path.basename(request.path) : request.name
      if (!validName(name)) return failure('invalidName')
      if (
        request.extensions?.length &&
        !request.extensions.some((ext) =>
          name.toLowerCase().endsWith(`.${ext.toLowerCase()}`)
        )
      )
        return failure('unsupportedFileType')
      if (request.kind === 'open') {
        const file = await this.readableFile(request.path)
        return { ok: true, value: { path: file.path } }
      }
      const parent = await this.policy.authorizeDirectory(request.parentPath)
      if (!(await this.writable(parent))) return failure('permissionDenied')
      const output = path.join(parent.path, request.name)
      if (output.length > SERVER_DIRECTORY_PATH_LIMIT)
        return failure('tooLarge')
      try {
        await lstat(output)
        return failure('alreadyExists')
      } catch (error) {
        if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
      }
      // Validation never creates an output file. The merge service still owns
      // atomic non-replacing publication if a name appears after selection.
      return { ok: true, value: { path: output } }
    } catch (error) {
      return failure(errorCode(error))
    }
  }

  async list(raw: unknown): Promise<ListServerDirectoriesResult> {
    const request = ListServerDirectoriesRequestSchema.safeParse(raw)
    if (!request.success) return failure('invalidPath')
    try {
      const initialFile = request.data.includeFiles && request.data.initialFile
      const directory = await this.policy.authorizeDirectory(
        initialFile ? path.dirname(request.data.path) : request.data.path
      )
      await this.fs.access(
        directory.canonicalPath,
        constants.R_OK | constants.X_OK
      )
      const entries: Extract<
        ListServerDirectoriesResult,
        { ok: true }
      >['value']['entries'] = []
      const handle = await this.fs.opendir(directory.canonicalPath)
      let scanned = 0
      let truncated = false
      try {
        while (
          scanned < SERVER_DIRECTORY_SCAN_LIMIT &&
          entries.length < SERVER_DIRECTORY_ENTRY_LIMIT
        ) {
          const entry = await handle.read()
          if (!entry) break
          scanned++
          if (!request.data.showHidden && entry.name.startsWith('.')) continue
          if (
            !entry.isDirectory() &&
            !entry.isSymbolicLink() &&
            !(request.data.includeFiles && entry.isFile())
          )
            continue
          const childPath = path.join(directory.path, entry.name)
          if (childPath.length > SERVER_DIRECTORY_PATH_LIMIT) {
            truncated = true
            continue
          }
          try {
            let kind: 'directory' | 'file' = 'directory'
            let child: { path: string; modifiedAt?: number }
            try {
              child = await this.policy.authorizeDirectory(childPath)
            } catch (error) {
              if (
                !request.data.includeFiles ||
                errorCode(error) !== 'notDirectory'
              )
                throw error
              child = await this.readableFile(childPath)
              kind = 'file'
            }
            entries.push({
              name: entry.name,
              path: child.path,
              ...(request.data.includeFiles ? { kind } : {}),
              ...(Number.isFinite(child.modifiedAt)
                ? { modifiedAt: child.modifiedAt }
                : {}),
            })
          } catch (error) {
            // An unresolvable child link must not hide its healthy siblings.
            // Direct requests still fail through the outer error boundary.
            const code = (error as NodeJS.ErrnoException | null)?.code
            if (code === 'ELOOP' || code === 'ENAMETOOLONG') continue
            if (
              ![
                'outsideRoots',
                'notFound',
                'notDirectory',
                'notFile',
                'permissionDenied',
              ].includes(errorCode(error))
            )
              throw error
          }
        }
        truncated ||=
          scanned === SERVER_DIRECTORY_SCAN_LIMIT ||
          entries.length === SERVER_DIRECTORY_ENTRY_LIMIT
      } finally {
        await handle.close()
      }
      entries.sort(
        (a, b) =>
          a.name.localeCompare(b.name, 'en', {
            numeric: true,
            sensitivity: 'base',
          }) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)
      )
      return ListServerDirectoriesResultSchema.parse({
        ok: true,
        value: {
          path: directory.path,
          ...navigation(directory),
          entries,
          truncated,
          canCreate: await this.writable(directory),
          ...(request.data.includeFiles ? { separator: path.sep } : {}),
          ...(initialFile
            ? { initialName: path.basename(request.data.path) }
            : {}),
        },
      })
    } catch (error) {
      return failure(errorCode(error))
    }
  }

  async validate(raw: unknown): Promise<ValidateServerDirectoryResult> {
    const request = ValidateServerDirectoryRequestSchema.safeParse(raw)
    if (!request.success) return failure('invalidPath')
    try {
      const directory = await this.policy.authorizeDirectory(request.data.path)
      if (request.data.access === 'read')
        await this.fs.access(
          directory.canonicalPath,
          constants.R_OK | constants.X_OK
        )
      else if (!(await this.writable(directory)))
        return failure('permissionDenied')
      return ValidateServerDirectoryResultSchema.parse({
        ok: true,
        value: { path: directory.path },
      })
    } catch (error) {
      return failure(errorCode(error))
    }
  }

  async create(raw: unknown): Promise<CreateServerDirectoryResult> {
    const request = CreateServerDirectoryRequestSchema.safeParse(raw)
    if (!request.success)
      return failure(
        request.error.issues.some((issue) => issue.path[0] === 'name')
          ? 'invalidName'
          : 'invalidPath'
      )
    if (!validName(request.data.name)) return failure('invalidName')
    let created = false
    try {
      const parent = await this.policy.authorizeDirectory(
        request.data.parentPath
      )
      const childPath = path.join(parent.path, request.data.name)
      if (childPath.length > SERVER_DIRECTORY_PATH_LIMIT)
        return failure('tooLarge')
      if (!(await this.writable(parent))) return failure('permissionDenied')
      await this.fs.mkdir(childPath, { recursive: false })
      created = true
      const child = await this.policy.authorizeDirectory(childPath)
      return CreateServerDirectoryResultSchema.parse({
        ok: true,
        value: { path: child.path, name: request.data.name },
      })
    } catch (error) {
      // A completed mkdir is persistent even if its post-check cannot certify
      // the result. Never remove a path that could have changed concurrently.
      return failure(created ? 'creationOutcomeUnknown' : errorCode(error))
    }
  }
}