Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9f777bafbc | ||
|
|
be4a1ac807 | ||
|
|
55f2474660 | ||
|
|
c02bf755f2 | ||
|
|
c209f1effc | ||
|
|
7fd7ae6733 | ||
|
|
705762d57c | ||
|
|
86dc0e8d95 | ||
|
|
68a6801690 | ||
|
|
6873f04bfb | ||
|
|
6d8faa7d03 | ||
|
|
7371c29111 | ||
|
|
852140c3a7 | ||
|
|
6e36b6c4b7 | ||
|
|
bc9709e500 | ||
|
|
5cb1b463ea | ||
|
|
1afa755d4f | ||
|
|
c05293a948 | ||
|
|
ab7b77de39 | ||
|
|
54761e4ef2 | ||
|
|
042392f611 | ||
|
|
6aca927851 | ||
|
|
d8bdf5f390 | ||
|
|
2366035c72 | ||
|
|
9110c8a9d5 | ||
|
|
d3d164910b | ||
|
|
fa1832dfa7 | ||
|
|
b87f8cb961 | ||
|
|
a69fdf2e09 | ||
|
|
7a1d18dfc6 | ||
|
|
dd29258828 | ||
|
|
b569f68300 | ||
|
|
7fc7465f71 | ||
|
|
5dda0dc5f3 | ||
|
|
618fccd7bb | ||
|
|
a0de540dbd | ||
|
|
bd9bf33bc9 | ||
|
|
2e3b56f250 | ||
|
|
87bc33e675 |
No files matched your search
@@ -1,160 +0,0 @@
|
||||
# CLAUDE.md
|
||||
|
||||
Guidance for Claude when working in this repository (File Browser, `filebrowser/filebrowser`).
|
||||
|
||||
## Repo orientation
|
||||
|
||||
- Go backend (`github.com/filebrowser/filebrowser/v2`, ecosystem `go`) + Vue frontend under `frontend/`.
|
||||
- The project is in **maintenance-only mode** (see `SECURITY.md`). Prefer small, surgical, well-tested changes.
|
||||
- Version scheme: `v2.63.x`. Conventional-commit messages (`fix(scope): …`, `feat: …`, `chore: …`).
|
||||
- Verify with `go build ./...`, `go vet ./...`, `go test ./...`. Reuse existing test harnesses (e.g. `signToken`, `scopedUserStorage`, `handle`, `customFSUser`, `mockUserStore`).
|
||||
|
||||
---
|
||||
|
||||
# Handling security advisories
|
||||
|
||||
Use this playbook when asked to triage, verify, fix, or manage GitHub security advisories.
|
||||
All advisory state lives on GitHub and is driven with the `gh` CLI. States are
|
||||
`triage → draft → published`, plus `closed`.
|
||||
|
||||
## 1. Fetch
|
||||
|
||||
```bash
|
||||
# List by state (also: published, draft, closed)
|
||||
gh api '/repos/filebrowser/filebrowser/security-advisories?state=triage&per_page=100' \
|
||||
--jq '.[] | {ghsa_id, severity, summary, state}'
|
||||
|
||||
# Full report for one advisory (read .summary and .description)
|
||||
gh api /repos/filebrowser/filebrowser/security-advisories/GHSA-xxxx-xxxx-xxxx \
|
||||
--jq '.summary, "---", .description'
|
||||
```
|
||||
|
||||
Always pull the **published** set too — you need it to dedup against.
|
||||
|
||||
## 2. Verify each report — do NOT trust the report text
|
||||
|
||||
Read the actual source **at HEAD** and reach one verdict per advisory:
|
||||
|
||||
- **CONFIRMED** — defect exists at HEAD. Quote the exact `file:line`.
|
||||
- **FIXED** — already patched (find the fix commit).
|
||||
- **FALSE / NOT APPLICABLE** — claim is wrong, or targets a different project.
|
||||
- **NOT EXPLOITABLE** — pattern exists but no code path can reach the precondition.
|
||||
- **DUPLICATE** — of a published advisory, or of another triage advisory.
|
||||
|
||||
Common traps — check each before accepting a report:
|
||||
|
||||
- **"Incomplete fix of a prior advisory."** Read the original fix commit and confirm the *specific*
|
||||
sibling code path is actually still unguarded — a prior fix may already cover a related path.
|
||||
- **Wrong project.** Confirm the referenced files, symbols, and endpoints exist in this repo; reports
|
||||
sometimes describe a fork. If the cited code isn't here, close as not applicable.
|
||||
- **"Legacy / upgraded / imported records are affected."** Trace the field's git history and confirm that
|
||||
some released version could actually produce such a record before believing it
|
||||
(`git log -S'Field' -- path`, `git show <commit>`, `git tag --contains <commit>`).
|
||||
- **Overlapping reports.** Two triage advisories may share one root cause — consolidate and fix once.
|
||||
- **Known, intentionally-unaddressed classes.** Some areas are known and tracked but not fixed (see
|
||||
`SECURITY.md`'s Known Issues); matching reports are duplicates.
|
||||
|
||||
Record, per advisory: verdict, the `file:line` evidence, exploitability preconditions
|
||||
(default config? platform-specific? auth required?), and the disposition.
|
||||
|
||||
## 3. Fix (one commit per advisory)
|
||||
|
||||
- Branch off `master` first; never commit fixes directly to `master`.
|
||||
- **One commit per fix**, each referencing the GHSA in the body (`Refs GHSA-xxxx-xxxx-xxxx`).
|
||||
- When several advisories share a root cause because parallel code paths diverged, **centralize** the logic
|
||||
(e.g. `settings.CreateUserHome` used by signup, proxy, and hook provisioning) so they cannot drift again.
|
||||
- Keep it surgical; match surrounding style.
|
||||
|
||||
## 4. Add a regression test per fix
|
||||
|
||||
- Reuse the existing harnesses; add a focused test asserting the fixed behavior (and that the legitimate
|
||||
path still works). Commit tests alongside the fixes (`test(scope): …`, `Refs GHSA-…`).
|
||||
- Run `go test ./... && go vet ./...` before finishing.
|
||||
|
||||
## 5. Severity — set a CVSS vector, don't hand-assert
|
||||
|
||||
Set a CVSS v3.1 vector; GitHub derives the score **and** severity from it (overriding the plain `severity`
|
||||
field). Encode the real preconditions in the vector so the band is defensible:
|
||||
|
||||
- Requires a specific target configuration/platform (e.g. case-insensitive FS) → **AC:H**.
|
||||
- Unauthenticated vs needs an account → **PR:N / PR:L**.
|
||||
- Keep it consistent with the **predecessor CVE's** rating (an incomplete-fix follow-up should not outrank
|
||||
its parent). Bands: `0.1–3.9` low, `4.0–6.9` medium, `7.0–8.9` high, `9.0–10.0` critical.
|
||||
|
||||
```bash
|
||||
gh api -X PATCH /repos/filebrowser/filebrowser/security-advisories/GHSA-xxxx-xxxx-xxxx \
|
||||
-f cvss_vector_string='CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H' \
|
||||
--jq '{ghsa_id, severity, score: .cvss.score, vector: .cvss.vector_string}'
|
||||
```
|
||||
|
||||
## 6. Clean up the title
|
||||
|
||||
Rewrite reporter titles to the concise, sentence-case, backtick-free style of the published advisories
|
||||
(state the vuln; drop "Incomplete fix of…" prefixes and jargon). The title is the `summary` field:
|
||||
|
||||
```bash
|
||||
gh api -X PATCH .../security-advisories/GHSA-xxxx-xxxx-xxxx \
|
||||
-f summary='Proxy-auth auto-provisioning ignores createUserDir and grants the server root scope'
|
||||
```
|
||||
|
||||
## 7. Rewrite the body into the standard structure
|
||||
|
||||
Reporter reports arrive in whatever shape the reporter used. Before drafting, rewrite the
|
||||
`description` into the sections below — **reusing the reporter's own wording wherever it is
|
||||
accurate**, rather than paraphrasing it. Drop the greeting, the offer to help, and any claim the
|
||||
verification in step 2 disproved. Keep sections in this order and omit the ones that don't apply:
|
||||
|
||||
| Section | Contents |
|
||||
| --- | --- |
|
||||
| `## Summary` | What the defect is, in two or three sentences. Note the version it was reported against and the range it was verified over. |
|
||||
| `## Details` | Root cause, naming `file.go`, the function, and a short quote of the **pre-fix** code. |
|
||||
| `## PoC` | The reporter's reproduction steps and observed result, trimmed to the essentials. |
|
||||
| `## Impact` | Who can exploit it (privilege level, preconditions) and what they get. |
|
||||
| `## Patches` | Fixed version plus a link to the fix commit, and one sentence on what the fix does. Mention it if the reporter re-tested and confirmed. |
|
||||
| `## Workarounds` | Real mitigations, or `None. Upgrade to vX.Y.Z.` |
|
||||
| `## Out of scope` | Anything in the original report deliberately **not** treated as a vulnerability, with the reasoning. Needed whenever the advisory is narrower than the report. |
|
||||
| `## References` | Fix and regression-test commit links. |
|
||||
|
||||
Use `##` headings (matching the published advisories) and keep the body in the maintainer's voice —
|
||||
first person ("I reproduced…") belongs only inside quoted PoC steps.
|
||||
|
||||
Send it as a file so the Markdown survives shell quoting:
|
||||
|
||||
```bash
|
||||
jq -Rs '{description: .}' desc.md \
|
||||
| gh api -X PATCH .../security-advisories/GHSA-xxxx-xxxx-xxxx --input -
|
||||
```
|
||||
|
||||
## 8. Set affected & patched versions
|
||||
|
||||
The package is always `{ecosystem: "go", name: "github.com/filebrowser/filebrowser/v2"}`.
|
||||
|
||||
- `vulnerable_version_range` — `<= <latest released version>` (the newest tag; find it with
|
||||
`git tag --list 'v2.*' --sort=-version:refname | head -1`).
|
||||
- `patched_versions` — the **next** release that will actually ship the fix. It doesn't exist just
|
||||
because the branch does; it still has to be cut. **When unsure which version that will be, ask.**
|
||||
|
||||
Replace the placeholder versions below before sending:
|
||||
|
||||
```bash
|
||||
printf '%s' '{"vulnerabilities":[{"package":{"ecosystem":"go","name":"github.com/filebrowser/filebrowser/v2"},"vulnerable_version_range":"<= <latest>","patched_versions":"<next>","vulnerable_functions":[]}]}' \
|
||||
| gh api -X PATCH .../security-advisories/GHSA-xxxx-xxxx-xxxx --input -
|
||||
```
|
||||
|
||||
## 9. Move state / close, by disposition
|
||||
|
||||
```bash
|
||||
gh api -X PATCH .../security-advisories/GHSA-xxxx-xxxx-xxxx -f state=draft # fixed, awaiting release
|
||||
gh api -X PATCH .../security-advisories/GHSA-xxxx-xxxx-xxxx -f state=closed # duplicate / N-A / not-exploitable
|
||||
```
|
||||
|
||||
- **CONFIRMED & fixed** → metadata done → **draft**. Publish after the patched release ships.
|
||||
- **DUPLICATE / NOT APPLICABLE / NOT EXPLOITABLE** → **closed**.
|
||||
- **DEFERRED** (confirmed but not yet fixed) → leave in **triage** with a note.
|
||||
- The REST API **cannot post advisory comments** — replies to reporters (dup notice, evidence, links to
|
||||
the relevant tracking issue) must be posted manually in the advisory UI. Draft the text for the maintainer.
|
||||
|
||||
## 10. Release & publish
|
||||
|
||||
Push the branch, open a PR, merge, tag/release the `patched_versions` you set, then publish the drafts.
|
||||
Confirm outward-facing/irreversible advisory actions (close, publish) with the maintainer before doing them.
|
||||
@@ -0,0 +1,12 @@
|
||||
*.go text eol=lf
|
||||
*.sh text eol=lf
|
||||
*.ps1 text eol=lf
|
||||
*.service text eol=lf
|
||||
|
||||
# Keep frontend checkout consistent with Prettier on Windows.
|
||||
*.vue text eol=lf
|
||||
*.ts text eol=lf
|
||||
*.js text eol=lf
|
||||
*.cjs text eol=lf
|
||||
*.css text eol=lf
|
||||
*.json text eol=lf
|
||||
@@ -1 +0,0 @@
|
||||
* @filebrowser/maintainers
|
||||
@@ -37,3 +37,11 @@ build/
|
||||
|
||||
default.nix
|
||||
Dockerfile.dev
|
||||
|
||||
# SSO secrets and local setup
|
||||
.filebrowser.json
|
||||
.filebrowser.*.json
|
||||
|
||||
# Downloaded optional editor bundles
|
||||
/addons/*
|
||||
!/addons/.gitkeep
|
||||
@@ -1,115 +1,13 @@
|
||||
# Building File Browser
|
||||
# Сборка и разработка
|
||||
|
||||
This project is archived on 2026-09-01. Pull requests are not accepted and no further changes are merged. This document is kept as build documentation for anyone wishing to build the project from source.
|
||||
Go 1.26+, Node.js 24+, pnpm 10.33.4. Разработка ведётся в dev, исходная версия сохранена в master-copy.
|
||||
|
||||
## Project Structure
|
||||
Сборка интерфейса: `cd frontend && pnpm install --frozen-lockfile && pnpm run build`.
|
||||
Затем из корня: `go build -o filebrowser .` и `./filebrowser init`.
|
||||
|
||||
The backend side of the application is written in [Go](https://golang.org/), while the frontend (located on a subdirectory of the same name) is written in [Vue.js](https://vuejs.org/). Due to the tight coupling required by some features, basic knowledge of both Go and Vue.js is recommended.
|
||||
Проверки: `go test ./...`, `go vet ./...`, `pnpm run typecheck`, `pnpm run test`, `pnpm run lint` в frontend.
|
||||
Аудит: `govulncheck ./...`, `pnpm audit`; для Linux на другой ОС установите GOOS=linux и GOARCH=amd64 при запуске govulncheck.
|
||||
|
||||
* Learn Go: [https://github.com/golang/go/wiki/Learn](https://github.com/golang/go/wiki/Learn)
|
||||
* Learn Vue.js: [https://vuejs.org/guide/introduction.html](https://vuejs.org/guide/introduction.html)
|
||||
|
||||
We encourage you to use git to manage your fork. To clone the main repository, just run:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/filebrowser/filebrowser
|
||||
```
|
||||
|
||||
We use [Taskfile](https://taskfile.dev/) to manage the different processes (building, releasing, etc) automatically.
|
||||
|
||||
## Build
|
||||
|
||||
You can fully build the project in order to produce a binary by running:
|
||||
|
||||
```bash
|
||||
task build
|
||||
```
|
||||
|
||||
## Development
|
||||
|
||||
For development, there are a few things to have in mind.
|
||||
|
||||
### Frontend
|
||||
|
||||
We use [Node.js](https://nodejs.org/en/) on the frontend to manage the build process. Prepare the frontend environment:
|
||||
|
||||
```bash
|
||||
# From the root of the repo, go to frontend/
|
||||
cd frontend
|
||||
|
||||
# Install the dependencies
|
||||
pnpm install
|
||||
```
|
||||
|
||||
If you just want to develop the backend, you can create a static build of the frontend:
|
||||
|
||||
```bash
|
||||
pnpm run build
|
||||
```
|
||||
|
||||
If you want to develop the frontend, start a development server which watches for changes:
|
||||
|
||||
```bash
|
||||
pnpm run dev
|
||||
```
|
||||
|
||||
Please note that you need to access File Browser's interface through the development server of the frontend.
|
||||
|
||||
### Backend
|
||||
|
||||
First prepare the backend environment by downloading all required dependencies:
|
||||
|
||||
```bash
|
||||
go mod download
|
||||
```
|
||||
|
||||
You can now build or run File Browser as any other Go project:
|
||||
|
||||
```bash
|
||||
# Build
|
||||
go build
|
||||
|
||||
# Run
|
||||
go run .
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
Documentation lives in [`docs`](docs) as plain Markdown and is no longer built into a site. The command line reference in [`docs/cli`](docs/cli) is generated from the commands themselves:
|
||||
|
||||
```bash
|
||||
task docs:cli:generate
|
||||
```
|
||||
|
||||
## Release
|
||||
|
||||
To make a release, just run:
|
||||
|
||||
```bash
|
||||
task release
|
||||
```
|
||||
|
||||
## Translations
|
||||
|
||||
The Transifex integration stopped on 2026-09-01 and translations submitted there no longer reach this repository. Locale files live in [`frontend/src/i18n`](frontend/src/i18n) and can be edited directly.
|
||||
|
||||
## Authentication Provider
|
||||
|
||||
To build a new authentication provider, you need to implement the [Auther interface](https://github.com/filebrowser/filebrowser/blob/master/auth/auth.go), whose method will be called on the login page after the user has submitted their login data.
|
||||
|
||||
```go
|
||||
// Auther is the authentication interface.
|
||||
type Auther interface {
|
||||
// Auth is called to authenticate a request.
|
||||
Auth(r *http.Request, s *users.Storage, root string) (*users.User, error)
|
||||
}
|
||||
```
|
||||
|
||||
After implementing the interface you should:
|
||||
|
||||
1. Add it to [`auth` directory](https://github.com/filebrowser/filebrowser/blob/master/auth).
|
||||
2. Add it to the [configuration parser](https://github.com/filebrowser/filebrowser/blob/master/cmd/config.go) for the CLI.
|
||||
3. Add it to the [`authBackend.Get`](https://github.com/filebrowser/filebrowser/blob/master/storage/bolt/auth.go).
|
||||
|
||||
If you need to add more flags, please update the function `addConfigFlags`.
|
||||
Для интерфейса в режиме разработки выполните `pnpm run dev`; запросы API проксируются на 127.0.0.1:8080. Полный OIDC-вход проверяйте через собранный интерфейс: публичный URL и Origin должны совпадать с конфигурацией SSO.
|
||||
|
||||
Готовый Debian-архив: `sh scripts/build-release.sh` либо `./scripts/build-release.ps1`. Инструкция — [docs/deployment.md](docs/deployment.md).
|
||||
@@ -1,36 +1,48 @@
|
||||
> [!WARNING]
|
||||
>
|
||||
> **File Browser is archived on 2026-09-01**. The last planned release has already shipped. There will be no further releases, bug fixes, or security fixes.
|
||||
# File Browser
|
||||
|
||||
<p align="center">
|
||||
<img src="./branding/banner.png" width="550"/>
|
||||
</p>
|
||||
**Ваши файлы, ссылки и браузерные инструменты — на своём сервере.**
|
||||
|
||||
File Browser provides a file managing interface within a specified directory and it can be used to upload, delete, preview and edit your files. It is a **create-your-own-cloud**-kind of software where you can just install it on your server, direct it to a path and access your files through a nice web interface.
|
||||
[Скачать](https://git.anidev.ru/SantaSpeen/filebrowser/releases) · [Установка](docs/deployment.md) · [Разработка](#сборка)
|
||||
|
||||
**Background:** [Goodbye File Browser, for Real This Time](https://hacdias.com/2026/07/28/filebrowser/), July 2026.
|
||||

|
||||
|
||||
## Security
|
||||
[Мобильный интерфейс](docs/images/workspace-mobile.png)
|
||||
|
||||
Published advisories are listed under [security advisories](https://github.com/filebrowser/filebrowser/security/advisories),
|
||||
and reporting instructions are in [SECURITY.md](SECURITY.md). Two known issue classes
|
||||
remain unaddressed and will not be fixed:
|
||||
- **Общая сессия SSO.** Текущий аккаунт и роли проверяются на сервере; переключение синхронизируется между приложениями.
|
||||
- **Удобное пространство.** Дерево папок, закладки, поиск, меню действий, светлая и тёмная темы, мобильная вёрстка.
|
||||
- **Мои ссылки.** Короткие адреса `/s/имя`, несколько ссылок на файл, необязательные пароль и срок действия.
|
||||
- **Предпросмотр.** Изображения, PDF, DICOM 2D, текст, Markdown, CSV, книги, аудио и видео. ZIP показывает дерево без распаковки.
|
||||
- **Craft-аддоны.** Установка и обновление из панели управления; совместимые редакторы открывают и сохраняют файлы на сервере.
|
||||
- **Один бинарник.** Debian amd64 и Windows amd64; отдельная СУБД и Node.js для запуска не нужны.
|
||||
|
||||
- **Command execution, runner, and hooks.** This feature is plagued with vulnerabilities across many published advisories, and would need a full rewrite to be made safe. It is disabled by default; if you re-enable it with `--disable-exec=false`, treat the ability to run commands as equivalent to shell access on the host. Background: [#5199](https://github.com/filebrowser/filebrowser/issues/5199).
|
||||
- **Session and JWT handling.** Sessions are self-contained JWTs rather than server-side identifiers, so they cannot be revoked, which means that logout, password changes, and renewal leave previously issued tokens valid until they expire, and the same refresh token can be redeemed repeatedly. Assume a leaked token is valid until expiry. Background: [#5216](https://github.com/filebrowser/filebrowser/issues/5216).
|
||||
## Запуск
|
||||
|
||||
If you keep running File Browser, treat it as unmaintained software:
|
||||
```sh
|
||||
chmod +x filebrowser
|
||||
./filebrowser init
|
||||
./filebrowser
|
||||
```
|
||||
|
||||
- **Do not expose it directly to the internet.** Put it behind a reverse proxy that terminates TLS and performs its own authentication.
|
||||
- **Keep the command runner disabled.** It is off by default, so leave it off. See [#5199](https://github.com/filebrowser/filebrowser/issues/5199) and [`docs/command-execution.md`](docs/command-execution.md).
|
||||
- **Run it unprivileged, inside a container**, with only the directory you intend to serve mounted into it.
|
||||
На Windows: `filebrowser.exe init`, затем `filebrowser.exe`. Мастер настраивает хранилище и SSO без `.env`. Подробности, systemd и nginx — в [инструкции](docs/deployment.md).
|
||||
|
||||
## Documentation
|
||||
Без SSO и пароля: `./filebrowser --no-sso` — все посетители получают административный доступ. [Как работает вход](docs/authentication.md).
|
||||
|
||||
Documentation on how to install, configure, and build this project lives in [`docs`](docs) in this repository.
|
||||
## Сборка
|
||||
|
||||
[CONTRIBUTING.md](CONTRIBUTING.md) documents how to build and develop the project, which remains useful to anyone forking it.
|
||||
Go 1.26+, Node.js 24+, pnpm 10.33.4.
|
||||
|
||||
## License
|
||||
```sh
|
||||
cd frontend
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm run build
|
||||
pnpm test
|
||||
cd ..
|
||||
go test ./...
|
||||
go build -o filebrowser .
|
||||
```
|
||||
|
||||
[Apache License 2.0](LICENSE) © File Browser Contributors
|
||||
Релиз для Debian: `sh scripts/build-release.sh` или `./scripts/build-release.ps1`. Архивы и контрольные суммы находятся в `build/`.
|
||||
|
||||
`dev` — разработка · `master` — страница проекта · `master-copy` — исходная версия upstream.
|
||||
|
||||
Независимый форк [File Browser](https://github.com/filebrowser/filebrowser). [Apache-2.0](LICENSE). [Безопасность и ограничения](docs/SECURITY-REVIEW.md).
|
||||
@@ -1,30 +1,9 @@
|
||||
# Security Policy
|
||||
# Безопасность
|
||||
|
||||
## Supported Versions
|
||||
Этот репозиторий — независимый форк File Browser. Политика архивированного upstream к нему не относится.
|
||||
|
||||
No version receives security fixes. The last planned release has already shipped and no further changes will be merged.
|
||||
Ограничения и выполненные проверки: [обзор безопасности](docs/SECURITY-REVIEW.md).
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | --------- |
|
||||
| 2.x | ❌ |
|
||||
| < 2.0 | ❌ |
|
||||
При обнаружении уязвимости сообщите владельцу этого форка приватно. Укажите версию или коммит, шаги воспроизведения и влияние. Не публикуйте токены, пароли и реальные медицинские файлы.
|
||||
|
||||
## Before Reporting
|
||||
|
||||
This project is being wound down. To avoid duplicates, first check the [existing advisories](https://github.com/filebrowser/filebrowser/security/advisories) and open issues, and confirm:
|
||||
|
||||
- **It concerns this project, not a fork.** Reports about code, features, or endpoints that don't exist here belong to the relevant fork.
|
||||
- **It isn't an already-known class** that remains unaddressed. Those are listed under [Security](README.md#security) in the README; reports covering them are likely to be closed as duplicates.
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Until 2026-09-01, report privately via the [Security](https://github.com/filebrowser/filebrowser/security) page. After that date this repository is read-only and reports can no longer be submitted.
|
||||
|
||||
Please include, where possible:
|
||||
|
||||
- The commit the issue was found at
|
||||
- A plaintext proof of concept (no binaries)
|
||||
- Steps to reproduce
|
||||
- Recommended remediation, if any
|
||||
|
||||
No fix will ship for any report: the last planned release has already shipped and no further changes will be merged. Reports may still be published as advisories so that people running File Browser can assess their exposure.
|
||||
Для размещения в интернете используйте HTTPS и своевременно обновляйте сервер и аддоны. Наличие проверок не гарантирует отсутствия уязвимостей.
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
@@ -14,3 +15,12 @@ type Auther interface {
|
||||
// LoginPage indicates if this auther needs a login page.
|
||||
LoginPage() bool
|
||||
}
|
||||
|
||||
const MethodSSO settings.AuthMethod = "sso"
|
||||
|
||||
type SSOAuth struct{}
|
||||
|
||||
func (SSOAuth) Auth(*http.Request, users.Store, *settings.Settings, *settings.Server) (*users.User, error) {
|
||||
return nil, errors.New("use OpenID Connect")
|
||||
}
|
||||
func (SSOAuth) LoginPage() bool { return true }
|
||||
@@ -1,288 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
fberrors "github.com/filebrowser/filebrowser/v2/errors"
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
// MethodHookAuth is used to identify hook auth.
|
||||
const MethodHookAuth settings.AuthMethod = "hook"
|
||||
|
||||
type hookCred struct {
|
||||
Password string `json:"password"`
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
// HookAuth is a hook implementation of an Auther.
|
||||
type HookAuth struct {
|
||||
Users users.Store `json:"-"`
|
||||
Settings *settings.Settings `json:"-"`
|
||||
Server *settings.Server `json:"-"`
|
||||
Cred hookCred `json:"-"`
|
||||
Fields hookFields `json:"-"`
|
||||
Command string `json:"command"`
|
||||
}
|
||||
|
||||
// Auth authenticates the user via a json in content body.
|
||||
func (a *HookAuth) Auth(r *http.Request, usr users.Store, stg *settings.Settings, srv *settings.Server) (*users.User, error) {
|
||||
var cred hookCred
|
||||
|
||||
if r.Body == nil {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
|
||||
err := json.NewDecoder(r.Body).Decode(&cred)
|
||||
if err != nil {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
|
||||
a.Users = usr
|
||||
a.Settings = stg
|
||||
a.Server = srv
|
||||
a.Cred = cred
|
||||
|
||||
action, err := a.RunCommand()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch action {
|
||||
case "auth":
|
||||
u, err := a.SaveUser()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
case "block":
|
||||
return nil, os.ErrPermission
|
||||
case "pass":
|
||||
u, err := a.Users.Get(a.Server.Root, a.Server.FollowExternalSymlinks, a.Cred.Username)
|
||||
if err != nil || !users.CheckPwd(a.Cred.Password, u.Password) {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
return u, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid hook action: %s", action)
|
||||
}
|
||||
}
|
||||
|
||||
// LoginPage tells that hook auth requires a login page.
|
||||
func (a *HookAuth) LoginPage() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// RunCommand starts the hook command and returns the action
|
||||
func (a *HookAuth) RunCommand() (string, error) {
|
||||
command := strings.Split(a.Command, " ")
|
||||
|
||||
cmd := exec.Command(command[0], command[1:]...)
|
||||
cmd.Env = append(os.Environ(), fmt.Sprintf("USERNAME=%s", a.Cred.Username))
|
||||
cmd.Env = append(cmd.Env, fmt.Sprintf("PASSWORD=%s", a.Cred.Password))
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
a.GetValues(string(out))
|
||||
|
||||
return a.Fields.Values["hook.action"], nil
|
||||
}
|
||||
|
||||
// GetValues creates a map with values from the key-value format string
|
||||
func (a *HookAuth) GetValues(s string) {
|
||||
m := map[string]string{}
|
||||
|
||||
// make line breaks consistent on Windows platform
|
||||
s = strings.ReplaceAll(s, "\r\n", "\n")
|
||||
|
||||
// iterate input lines
|
||||
for val := range strings.Lines(s) {
|
||||
v := strings.SplitN(val, "=", 2)
|
||||
|
||||
// skips non key and value format
|
||||
if len(v) != 2 {
|
||||
continue
|
||||
}
|
||||
|
||||
fieldKey := strings.TrimSpace(v[0])
|
||||
fieldValue := strings.TrimSpace(v[1])
|
||||
|
||||
if a.Fields.IsValid(fieldKey) {
|
||||
m[fieldKey] = fieldValue
|
||||
}
|
||||
}
|
||||
|
||||
a.Fields.Values = m
|
||||
}
|
||||
|
||||
// SaveUser updates the existing user or creates a new one when not found
|
||||
func (a *HookAuth) SaveUser() (*users.User, error) {
|
||||
u, err := a.Users.Get(a.Server.Root, a.Server.FollowExternalSymlinks, a.Cred.Username)
|
||||
if err != nil && !errors.Is(err, fberrors.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if u == nil {
|
||||
pass, err := users.ValidateAndHashPwd(a.Cred.Password, a.Settings.MinimumPasswordLength)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// create user with the provided credentials
|
||||
d := &users.User{
|
||||
Username: a.Cred.Username,
|
||||
Password: pass,
|
||||
Scope: a.Settings.Defaults.Scope,
|
||||
Locale: a.Settings.Defaults.Locale,
|
||||
ViewMode: a.Settings.Defaults.ViewMode,
|
||||
SingleClick: a.Settings.Defaults.SingleClick,
|
||||
RedirectAfterCopyMove: a.Settings.Defaults.RedirectAfterCopyMove,
|
||||
Sorting: a.Settings.Defaults.Sorting,
|
||||
Perm: a.Settings.Defaults.Perm,
|
||||
Commands: a.Settings.Defaults.Commands,
|
||||
DateFormat: a.Settings.Defaults.DateFormat,
|
||||
HideDotfiles: a.Settings.Defaults.HideDotfiles,
|
||||
}
|
||||
u = a.GetUser(d)
|
||||
|
||||
// A scope explicitly returned by the hook takes precedence over the
|
||||
// automatic per-user home directory derivation.
|
||||
_, explicitScope := a.Fields.Values["user.scope"]
|
||||
derivedScope, err := a.Settings.CreateUserHome(u, a.Server.Root, explicitScope)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
log.Printf("user: %s, home dir: [%s].", u.Username, u.Scope)
|
||||
|
||||
if err := a.Users.SaveProvisioned(u, derivedScope); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else if p := !users.CheckPwd(a.Cred.Password, u.Password); len(a.Fields.Values) > 1 || p {
|
||||
u = a.GetUser(u)
|
||||
|
||||
// update the password when it doesn't match the current
|
||||
if p {
|
||||
pass, err := users.ValidateAndHashPwd(a.Cred.Password, a.Settings.MinimumPasswordLength)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u.Password = pass
|
||||
}
|
||||
|
||||
// update user with provided fields
|
||||
err := a.Users.Update(u)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// GetUser returns a User filled with hook values or provided defaults
|
||||
func (a *HookAuth) GetUser(d *users.User) *users.User {
|
||||
// adds all permissions when user is admin
|
||||
isAdmin := a.Fields.GetBoolean("user.perm.admin", d.Perm.Admin)
|
||||
perms := users.Permissions{
|
||||
Admin: isAdmin,
|
||||
Execute: isAdmin || a.Fields.GetBoolean("user.perm.execute", d.Perm.Execute),
|
||||
Create: isAdmin || a.Fields.GetBoolean("user.perm.create", d.Perm.Create),
|
||||
Rename: isAdmin || a.Fields.GetBoolean("user.perm.rename", d.Perm.Rename),
|
||||
Modify: isAdmin || a.Fields.GetBoolean("user.perm.modify", d.Perm.Modify),
|
||||
Delete: isAdmin || a.Fields.GetBoolean("user.perm.delete", d.Perm.Delete),
|
||||
Share: isAdmin || a.Fields.GetBoolean("user.perm.share", d.Perm.Share),
|
||||
Download: isAdmin || a.Fields.GetBoolean("user.perm.download", d.Perm.Download),
|
||||
}
|
||||
user := users.User{
|
||||
ID: d.ID,
|
||||
Username: d.Username,
|
||||
Password: d.Password,
|
||||
Scope: a.Fields.GetString("user.scope", d.Scope),
|
||||
Locale: a.Fields.GetString("user.locale", d.Locale),
|
||||
ViewMode: users.ViewMode(a.Fields.GetString("user.viewMode", string(d.ViewMode))),
|
||||
SingleClick: a.Fields.GetBoolean("user.singleClick", d.SingleClick),
|
||||
RedirectAfterCopyMove: a.Fields.GetBoolean("user.redirectAfterCopyMove", d.RedirectAfterCopyMove),
|
||||
Sorting: files.Sorting{
|
||||
Asc: a.Fields.GetBoolean("user.sorting.asc", d.Sorting.Asc),
|
||||
By: a.Fields.GetString("user.sorting.by", d.Sorting.By),
|
||||
},
|
||||
Commands: a.Fields.GetArray("user.commands", d.Commands),
|
||||
DateFormat: a.Fields.GetBoolean("user.dateFormat", d.DateFormat),
|
||||
HideDotfiles: a.Fields.GetBoolean("user.hideDotfiles", d.HideDotfiles),
|
||||
Perm: perms,
|
||||
LockPassword: true,
|
||||
}
|
||||
|
||||
return &user
|
||||
}
|
||||
|
||||
// hookFields is used to access fields from the hook
|
||||
type hookFields struct {
|
||||
Values map[string]string
|
||||
}
|
||||
|
||||
// validHookFields contains names of the fields that can be used
|
||||
var validHookFields = []string{
|
||||
"hook.action",
|
||||
"user.scope",
|
||||
"user.locale",
|
||||
"user.viewMode",
|
||||
"user.singleClick",
|
||||
"user.redirectAfterCopyMove",
|
||||
"user.sorting.by",
|
||||
"user.sorting.asc",
|
||||
"user.commands",
|
||||
"user.hideDotfiles",
|
||||
"user.perm.admin",
|
||||
"user.perm.execute",
|
||||
"user.perm.create",
|
||||
"user.perm.rename",
|
||||
"user.perm.modify",
|
||||
"user.perm.delete",
|
||||
"user.perm.share",
|
||||
"user.perm.download",
|
||||
}
|
||||
|
||||
// IsValid checks if the provided field is on the valid fields list
|
||||
func (hf *hookFields) IsValid(field string) bool {
|
||||
return slices.Contains(validHookFields, field)
|
||||
}
|
||||
|
||||
// GetString returns the string value or provided default
|
||||
func (hf *hookFields) GetString(k, dv string) string {
|
||||
val, ok := hf.Values[k]
|
||||
if ok {
|
||||
return val
|
||||
}
|
||||
return dv
|
||||
}
|
||||
|
||||
// GetBoolean returns the bool value or provided default
|
||||
func (hf *hookFields) GetBoolean(k string, dv bool) bool {
|
||||
val, ok := hf.Values[k]
|
||||
if ok {
|
||||
return val == "true"
|
||||
}
|
||||
return dv
|
||||
}
|
||||
|
||||
// GetArray returns the array value or provided default
|
||||
func (hf *hookFields) GetArray(k string, dv []string) []string {
|
||||
val, ok := hf.Values[k]
|
||||
if ok && strings.TrimSpace(val) != "" {
|
||||
return strings.Split(val, " ")
|
||||
}
|
||||
return dv
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
// writeHookScript writes a POSIX shell script to a temp file and returns its
|
||||
// path, marking it executable.
|
||||
func writeHookScript(t *testing.T, body string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "hook.sh")
|
||||
if err := os.WriteFile(path, []byte("#!/bin/sh\n"+body), 0o700); err != nil {
|
||||
t.Fatalf("failed to write hook script: %v", err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// TestRunCommandNoCredentialInjection ensures that attacker-controlled
|
||||
// credentials submitted at the unauthenticated login endpoint cannot be
|
||||
// injected into the hook command string. Credentials must only ever reach the
|
||||
// hook through the USERNAME/PASSWORD environment variables, never via string
|
||||
// substitution into the command itself (CWE-78/CWE-88).
|
||||
func TestRunCommandNoCredentialInjection(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("uses POSIX shell")
|
||||
}
|
||||
|
||||
marker := filepath.Join(t.TempDir(), "pwned")
|
||||
|
||||
// The hook simply blocks. If the credential were ever interpolated into the
|
||||
// command string and evaluated by a shell, the embedded `touch` would
|
||||
// create the marker file.
|
||||
script := writeHookScript(t, "echo hook.action=block\n")
|
||||
|
||||
a := &HookAuth{
|
||||
Command: script,
|
||||
Cred: hookCred{
|
||||
Username: `"; touch ` + marker + `; #`,
|
||||
Password: `$(touch ` + marker + `)`,
|
||||
},
|
||||
}
|
||||
|
||||
action, err := a.RunCommand()
|
||||
if err != nil {
|
||||
t.Fatalf("RunCommand returned error: %v", err)
|
||||
}
|
||||
if action != "block" {
|
||||
t.Fatalf("expected action %q, got %q", "block", action)
|
||||
}
|
||||
if _, err := os.Stat(marker); err == nil {
|
||||
t.Fatalf("credential injection executed: marker file %q was created", marker)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunCommandReceivesCredentialsViaEnv verifies the supported contract: the
|
||||
// hook receives credentials through the USERNAME and PASSWORD environment
|
||||
// variables.
|
||||
func TestRunCommandReceivesCredentialsViaEnv(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("uses POSIX shell")
|
||||
}
|
||||
|
||||
script := writeHookScript(t, `if [ "$USERNAME" = alice ] && [ "$PASSWORD" = secret ]; then
|
||||
echo hook.action=auth
|
||||
else
|
||||
echo hook.action=block
|
||||
fi
|
||||
`)
|
||||
|
||||
a := &HookAuth{
|
||||
Command: script,
|
||||
Cred: hookCred{
|
||||
Username: "alice",
|
||||
Password: "secret",
|
||||
},
|
||||
}
|
||||
|
||||
action, err := a.RunCommand()
|
||||
if err != nil {
|
||||
t.Fatalf("RunCommand returned error: %v", err)
|
||||
}
|
||||
if action != "auth" {
|
||||
t.Fatalf("expected action %q, got %q", "auth", action)
|
||||
}
|
||||
}
|
||||
|
||||
// newHookAuth builds a HookAuth for a freshly provisioned user with the given
|
||||
// parsed hook fields (hook.action=auth is added automatically).
|
||||
func newHookAuth(store *mockUserStore, s *settings.Settings, srv *settings.Server, username string, fields map[string]string) *HookAuth {
|
||||
fields["hook.action"] = "auth"
|
||||
return &HookAuth{
|
||||
Users: store,
|
||||
Settings: s,
|
||||
Server: srv,
|
||||
Cred: hookCred{Username: username, Password: "a-strong-password"},
|
||||
Fields: hookFields{Values: fields},
|
||||
}
|
||||
}
|
||||
|
||||
// With CreateUserDir enabled and no explicit scope from the hook, a provisioned
|
||||
// hook user must receive its own home directory rather than the server root.
|
||||
func TestHookSaveUserCreateUserDirIsolatesScope(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := &mockUserStore{users: make(map[string]*users.User)}
|
||||
srv := &settings.Server{Root: t.TempDir()}
|
||||
s := &settings.Settings{
|
||||
Key: []byte("key"),
|
||||
CreateUserDir: true,
|
||||
UserHomeBasePath: "/users",
|
||||
Defaults: settings.UserDefaults{
|
||||
Scope: ".",
|
||||
Perm: users.Permissions{Create: true},
|
||||
},
|
||||
}
|
||||
|
||||
u, err := newHookAuth(store, s, srv, "alice", map[string]string{}).SaveUser()
|
||||
if err != nil {
|
||||
t.Fatalf("SaveUser error: %v", err)
|
||||
}
|
||||
if u.Scope != "/users/alice" {
|
||||
t.Errorf("hook user without explicit scope: expected /users/alice, got %q", u.Scope)
|
||||
}
|
||||
}
|
||||
|
||||
// A scope explicitly returned by the hook takes precedence over the automatic
|
||||
// per-user home directory derivation.
|
||||
func TestHookSaveUserRespectsExplicitScope(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := &mockUserStore{users: make(map[string]*users.User)}
|
||||
srv := &settings.Server{Root: t.TempDir()}
|
||||
s := &settings.Settings{
|
||||
Key: []byte("key"),
|
||||
CreateUserDir: true,
|
||||
UserHomeBasePath: "/users",
|
||||
Defaults: settings.UserDefaults{
|
||||
Scope: ".",
|
||||
Perm: users.Permissions{Create: true},
|
||||
},
|
||||
}
|
||||
|
||||
u, err := newHookAuth(store, s, srv, "teamlead", map[string]string{"user.scope": "/shared/team"}).SaveUser()
|
||||
if err != nil {
|
||||
t.Fatalf("SaveUser error: %v", err)
|
||||
}
|
||||
if u.Scope != "/shared/team" {
|
||||
t.Errorf("explicit hook scope should win, got %q", u.Scope)
|
||||
}
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
// MethodJSONAuth is used to identify json auth.
|
||||
const MethodJSONAuth settings.AuthMethod = "json"
|
||||
|
||||
// dummyHash is used to prevent user enumeration timing attacks.
|
||||
// It MUST be a valid bcrypt hash.
|
||||
const dummyHash = "$2a$10$O4mEMeOL/nit6zqe.WQXauLRbRlzb3IgLHsa26Pf0N/GiU9b.wK1m"
|
||||
|
||||
type jsonCred struct {
|
||||
Password string `json:"password"`
|
||||
Username string `json:"username"`
|
||||
ReCaptcha string `json:"recaptcha"`
|
||||
}
|
||||
|
||||
// JSONAuth is a json implementation of an Auther.
|
||||
type JSONAuth struct {
|
||||
ReCaptcha *ReCaptcha `json:"recaptcha" yaml:"recaptcha"`
|
||||
}
|
||||
|
||||
// Auth authenticates the user via a json in content body.
|
||||
func (a JSONAuth) Auth(r *http.Request, usr users.Store, _ *settings.Settings, srv *settings.Server) (*users.User, error) {
|
||||
var cred jsonCred
|
||||
|
||||
if r.Body == nil {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
|
||||
err := json.NewDecoder(r.Body).Decode(&cred)
|
||||
if err != nil {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
|
||||
// If ReCaptcha is enabled, check the code.
|
||||
if a.ReCaptcha != nil && a.ReCaptcha.Secret != "" {
|
||||
ok, err := a.ReCaptcha.Ok(cred.ReCaptcha)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !ok {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
}
|
||||
|
||||
u, err := usr.Get(srv.Root, srv.FollowExternalSymlinks, cred.Username)
|
||||
|
||||
hash := dummyHash
|
||||
if err == nil {
|
||||
hash = u.Password
|
||||
}
|
||||
|
||||
if !users.CheckPwd(cred.Password, hash) {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// LoginPage tells that json auth doesn't require a login page.
|
||||
func (a JSONAuth) LoginPage() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
const reCaptchaAPI = "/recaptcha/api/siteverify"
|
||||
|
||||
// ReCaptcha identifies a recaptcha connection.
|
||||
type ReCaptcha struct {
|
||||
Host string `json:"host"`
|
||||
Key string `json:"key"`
|
||||
Secret string `json:"secret"`
|
||||
}
|
||||
|
||||
// Ok checks if a reCaptcha responde is correct.
|
||||
func (r *ReCaptcha) Ok(response string) (bool, error) {
|
||||
body := url.Values{}
|
||||
body.Set("secret", r.Secret)
|
||||
body.Add("response", response)
|
||||
|
||||
client := &http.Client{}
|
||||
|
||||
resp, err := client.Post(
|
||||
r.Host+reCaptchaAPI,
|
||||
"application/x-www-form-urlencoded",
|
||||
strings.NewReader(body.Encode()),
|
||||
)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
var data struct {
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
err = json.NewDecoder(resp.Body).Decode(&data)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return data.Success, nil
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
// MethodNoAuth is used to identify no auth.
|
||||
const MethodNoAuth settings.AuthMethod = "noauth"
|
||||
|
||||
// NoAuth is no auth implementation of auther.
|
||||
type NoAuth struct{}
|
||||
|
||||
// Auth uses authenticates user 1.
|
||||
func (a NoAuth) Auth(_ *http.Request, usr users.Store, _ *settings.Settings, srv *settings.Server) (*users.User, error) {
|
||||
return usr.Get(srv.Root, srv.FollowExternalSymlinks, uint(1))
|
||||
}
|
||||
|
||||
// LoginPage tells that no auth doesn't require a login page.
|
||||
func (a NoAuth) LoginPage() bool {
|
||||
return false
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
fberrors "github.com/filebrowser/filebrowser/v2/errors"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
// MethodProxyAuth is used to identify no auth.
|
||||
const MethodProxyAuth settings.AuthMethod = "proxy"
|
||||
|
||||
// ProxyAuth is a proxy implementation of an auther.
|
||||
type ProxyAuth struct {
|
||||
Header string `json:"header"`
|
||||
}
|
||||
|
||||
// Auth authenticates the user via an HTTP header.
|
||||
func (a ProxyAuth) Auth(r *http.Request, usr users.Store, setting *settings.Settings, srv *settings.Server) (*users.User, error) {
|
||||
username := r.Header.Get(a.Header)
|
||||
user, err := usr.Get(srv.Root, srv.FollowExternalSymlinks, username)
|
||||
if errors.Is(err, fberrors.ErrNotExist) {
|
||||
return a.createUser(usr, setting, srv, username)
|
||||
}
|
||||
return user, err
|
||||
}
|
||||
|
||||
func (a ProxyAuth) createUser(usr users.Store, setting *settings.Settings, srv *settings.Server, username string) (*users.User, error) {
|
||||
const randomPasswordLength = settings.DefaultMinimumPasswordLength + 10
|
||||
pwd, err := users.RandomPwd(randomPasswordLength)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var hashedRandomPassword string
|
||||
hashedRandomPassword, err = users.ValidateAndHashPwd(pwd, setting.MinimumPasswordLength)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user := &users.User{
|
||||
Username: username,
|
||||
Password: hashedRandomPassword,
|
||||
LockPassword: true,
|
||||
}
|
||||
setting.Defaults.Apply(user)
|
||||
user.Perm.Admin = false
|
||||
user.Perm.Execute = false
|
||||
user.Commands = []string{}
|
||||
|
||||
var derivedScope bool
|
||||
if derivedScope, err = setting.CreateUserHome(user, srv.Root, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err = usr.SaveProvisioned(user, derivedScope); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// LoginPage tells that proxy auth doesn't require a login page.
|
||||
func (a ProxyAuth) LoginPage() bool {
|
||||
return false
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
fberrors "github.com/filebrowser/filebrowser/v2/errors"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
type mockUserStore struct {
|
||||
users map[string]*users.User
|
||||
}
|
||||
|
||||
func (m *mockUserStore) Get(_ string, _ bool, id interface{}) (*users.User, error) {
|
||||
if v, ok := id.(string); ok {
|
||||
if u, ok := m.users[v]; ok {
|
||||
return u, nil
|
||||
}
|
||||
}
|
||||
return nil, fberrors.ErrNotExist
|
||||
}
|
||||
|
||||
func (m *mockUserStore) GetByScope(scope string) (*users.User, error) {
|
||||
for _, u := range m.users {
|
||||
if strings.EqualFold(u.Scope, scope) {
|
||||
return u, nil
|
||||
}
|
||||
}
|
||||
return nil, fberrors.ErrNotExist
|
||||
}
|
||||
|
||||
func (m *mockUserStore) Gets(_ string, _ bool) ([]*users.User, error) { return nil, nil }
|
||||
func (m *mockUserStore) Update(_ *users.User, _ ...string) error { return nil }
|
||||
func (m *mockUserStore) Save(user *users.User) error {
|
||||
m.users[user.Username] = user
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockUserStore) SaveProvisioned(user *users.User, derivedScope bool) error {
|
||||
if derivedScope {
|
||||
if _, err := m.GetByScope(user.Scope); err == nil {
|
||||
return fberrors.ErrExist
|
||||
}
|
||||
}
|
||||
return m.Save(user)
|
||||
}
|
||||
|
||||
func (m *mockUserStore) Delete(_ interface{}) error { return nil }
|
||||
func (m *mockUserStore) LastUpdate(_ uint) int64 { return 0 }
|
||||
|
||||
func TestProxyAuthCreateUserRestrictsDefaults(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := &mockUserStore{users: make(map[string]*users.User)}
|
||||
srv := &settings.Server{Root: t.TempDir()}
|
||||
|
||||
s := &settings.Settings{
|
||||
Key: []byte("key"),
|
||||
AuthMethod: MethodProxyAuth,
|
||||
Defaults: settings.UserDefaults{
|
||||
Perm: users.Permissions{
|
||||
Admin: true,
|
||||
Execute: true,
|
||||
Create: true,
|
||||
Rename: true,
|
||||
Modify: true,
|
||||
Delete: true,
|
||||
Share: true,
|
||||
Download: true,
|
||||
},
|
||||
Commands: []string{"git", "ls", "cat", "id"},
|
||||
},
|
||||
}
|
||||
|
||||
auth := ProxyAuth{Header: "X-Remote-User"}
|
||||
req, _ := http.NewRequest(http.MethodGet, "/", http.NoBody)
|
||||
req.Header.Set("X-Remote-User", "newproxyuser")
|
||||
|
||||
user, err := auth.Auth(req, store, s, srv)
|
||||
if err != nil {
|
||||
t.Fatalf("Auth() error: %v", err)
|
||||
}
|
||||
|
||||
if user.Perm.Admin {
|
||||
t.Error("auto-provisioned proxy user should not have Admin permission")
|
||||
}
|
||||
if user.Perm.Execute {
|
||||
t.Error("auto-provisioned proxy user should not have Execute permission")
|
||||
}
|
||||
if len(user.Commands) != 0 {
|
||||
t.Errorf("auto-provisioned proxy user should have empty Commands, got %v", user.Commands)
|
||||
}
|
||||
if !user.Perm.Create {
|
||||
t.Error("auto-provisioned proxy user should retain Create permission from defaults")
|
||||
}
|
||||
}
|
||||
|
||||
// With CreateUserDir enabled, two distinct proxy-authenticated users must each
|
||||
// receive their own home directory instead of both inheriting the server root.
|
||||
func TestProxyAuthCreateUserDirIsolatesScope(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := &mockUserStore{users: make(map[string]*users.User)}
|
||||
srv := &settings.Server{Root: t.TempDir()}
|
||||
s := &settings.Settings{
|
||||
Key: []byte("key"),
|
||||
AuthMethod: MethodProxyAuth,
|
||||
CreateUserDir: true,
|
||||
UserHomeBasePath: "/users",
|
||||
Defaults: settings.UserDefaults{
|
||||
Scope: ".",
|
||||
Perm: users.Permissions{Create: true},
|
||||
},
|
||||
}
|
||||
|
||||
auth := ProxyAuth{Header: "X-Remote-User"}
|
||||
provision := func(name string) *users.User {
|
||||
req, _ := http.NewRequest(http.MethodGet, "/", http.NoBody)
|
||||
req.Header.Set("X-Remote-User", name)
|
||||
u, err := auth.Auth(req, store, s, srv)
|
||||
if err != nil {
|
||||
t.Fatalf("Auth(%q) error: %v", name, err)
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
alice := provision("alice")
|
||||
bob := provision("bob")
|
||||
|
||||
if alice.Scope == "/" || bob.Scope == "/" {
|
||||
t.Fatalf("provisioned users inherited the server root: alice=%q bob=%q", alice.Scope, bob.Scope)
|
||||
}
|
||||
if alice.Scope == bob.Scope {
|
||||
t.Fatalf("distinct users must get distinct scopes, both got %q", alice.Scope)
|
||||
}
|
||||
if alice.Scope != "/users/alice" {
|
||||
t.Errorf("expected /users/alice, got %q", alice.Scope)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,3 @@
|
||||
package cmd
|
||||
|
||||
// Execute executes the commands.
|
||||
func Execute() error {
|
||||
return rootCmd.Execute()
|
||||
}
|
||||
func Execute() error { return rootCmd.Execute() }
|
||||
@@ -48,10 +48,10 @@ func TestGetSettingsFollowExternalSymlinks(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
set := &settings.Settings{AuthMethod: auth.MethodJSONAuth}
|
||||
set := &settings.Settings{AuthMethod: auth.MethodSSO}
|
||||
ser := &settings.Server{}
|
||||
|
||||
if _, err := getSettings(flags, set, ser, &auth.JSONAuth{}, false); err != nil {
|
||||
if _, err := getSettings(flags, set, ser, &auth.SSOAuth{}, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ import (
|
||||
"github.com/spf13/pflag"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/auth"
|
||||
fberrors "github.com/filebrowser/filebrowser/v2/errors"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
)
|
||||
|
||||
@@ -35,26 +34,15 @@ func addConfigFlags(flags *pflag.FlagSet) {
|
||||
flags.Bool("hideLoginButton", false, "hide login button from public pages")
|
||||
flags.Bool("createUserDir", false, "generate user's home directory automatically")
|
||||
flags.Uint("minimumPasswordLength", settings.DefaultMinimumPasswordLength, "minimum password length for new users")
|
||||
flags.String("shell", "", "shell command to which other commands should be appended")
|
||||
|
||||
// NB: these are string so they can be presented as octal in the help text
|
||||
// as that's the conventional representation for modes in Unix.
|
||||
flags.String("fileMode", fmt.Sprintf("%O", settings.DefaultFileMode), "mode bits that new files are created with")
|
||||
flags.String("dirMode", fmt.Sprintf("%O", settings.DefaultDirMode), "mode bits that new directories are created with")
|
||||
|
||||
flags.String("auth.method", string(auth.MethodJSONAuth), "authentication type")
|
||||
flags.String("auth.header", "", "HTTP header for auth.method=proxy")
|
||||
flags.String("auth.command", "", "command for auth.method=hook")
|
||||
flags.String("auth.logoutPage", "", "url of custom logout page")
|
||||
|
||||
flags.String("recaptcha.host", "https://www.google.com", "use another host for ReCAPTCHA. recaptcha.net might be useful in China")
|
||||
flags.String("recaptcha.key", "", "ReCaptcha site key")
|
||||
flags.String("recaptcha.secret", "", "ReCaptcha secret")
|
||||
|
||||
flags.String("branding.name", "", "replace 'File Browser' by this name")
|
||||
flags.String("branding.theme", "", "set the theme")
|
||||
flags.String("branding.color", "", "set the theme color")
|
||||
flags.String("branding.files", "", "path to directory with images and custom styles")
|
||||
flags.Bool("branding.disableExternal", false, "disable external links such as GitHub links")
|
||||
flags.Bool("branding.disableUsedPercentage", false, "disable used disk percentage graph")
|
||||
|
||||
@@ -93,107 +81,8 @@ func getAuthMethod(flags *pflag.FlagSet, defaults ...interface{}) (settings.Auth
|
||||
return method, defaultAuther, nil
|
||||
}
|
||||
|
||||
func getProxyAuth(flags *pflag.FlagSet, defaultAuther map[string]interface{}) (auth.Auther, error) {
|
||||
header, err := flags.GetString("auth.header")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if header == "" && defaultAuther != nil {
|
||||
header = defaultAuther["header"].(string)
|
||||
}
|
||||
|
||||
if header == "" {
|
||||
return nil, errors.New("you must set the flag 'auth.header' for method 'proxy'")
|
||||
}
|
||||
|
||||
return &auth.ProxyAuth{Header: header}, nil
|
||||
}
|
||||
|
||||
func getNoAuth() auth.Auther {
|
||||
return &auth.NoAuth{}
|
||||
}
|
||||
|
||||
func getJSONAuth(flags *pflag.FlagSet, defaultAuther map[string]interface{}) (auth.Auther, error) {
|
||||
jsonAuth := &auth.JSONAuth{}
|
||||
host, err := flags.GetString("recaptcha.host")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
key, err := flags.GetString("recaptcha.key")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
secret, err := flags.GetString("recaptcha.secret")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if key == "" {
|
||||
if kmap, ok := defaultAuther["recaptcha"].(map[string]interface{}); ok {
|
||||
key = kmap["key"].(string)
|
||||
}
|
||||
}
|
||||
|
||||
if secret == "" {
|
||||
if smap, ok := defaultAuther["recaptcha"].(map[string]interface{}); ok {
|
||||
secret = smap["secret"].(string)
|
||||
}
|
||||
}
|
||||
|
||||
if key != "" && secret != "" {
|
||||
jsonAuth.ReCaptcha = &auth.ReCaptcha{
|
||||
Host: host,
|
||||
Key: key,
|
||||
Secret: secret,
|
||||
}
|
||||
}
|
||||
return jsonAuth, nil
|
||||
}
|
||||
|
||||
func getHookAuth(flags *pflag.FlagSet, defaultAuther map[string]interface{}) (auth.Auther, error) {
|
||||
command, err := flags.GetString("auth.command")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if command == "" {
|
||||
command = defaultAuther["command"].(string)
|
||||
}
|
||||
|
||||
if command == "" {
|
||||
return nil, errors.New("you must set the flag 'auth.command' for method 'hook'")
|
||||
}
|
||||
|
||||
return &auth.HookAuth{Command: command}, nil
|
||||
}
|
||||
|
||||
func getAuthentication(flags *pflag.FlagSet, defaults ...interface{}) (settings.AuthMethod, auth.Auther, error) {
|
||||
method, defaultAuther, err := getAuthMethod(flags, defaults...)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
var auther auth.Auther
|
||||
switch method {
|
||||
case auth.MethodProxyAuth:
|
||||
auther, err = getProxyAuth(flags, defaultAuther)
|
||||
case auth.MethodNoAuth:
|
||||
auther = getNoAuth()
|
||||
case auth.MethodJSONAuth:
|
||||
auther, err = getJSONAuth(flags, defaultAuther)
|
||||
case auth.MethodHookAuth:
|
||||
auther, err = getHookAuth(flags, defaultAuther)
|
||||
default:
|
||||
return "", nil, fberrors.ErrInvalidAuthMethod
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
return method, auther, nil
|
||||
func getAuthentication(_ *pflag.FlagSet, _ ...interface{}) (settings.AuthMethod, auth.Auther, error) {
|
||||
return auth.MethodSSO, &auth.SSOAuth{}, nil
|
||||
}
|
||||
|
||||
func printSettings(ser *settings.Server, set *settings.Settings, auther auth.Auther) error {
|
||||
@@ -209,7 +98,6 @@ func printSettings(ser *settings.Server, set *settings.Settings, auther auth.Aut
|
||||
|
||||
fmt.Fprintln(w, "\nBranding:")
|
||||
fmt.Fprintf(w, "\tName:\t%s\n", set.Branding.Name)
|
||||
fmt.Fprintf(w, "\tFiles override:\t%s\n", set.Branding.Files)
|
||||
fmt.Fprintf(w, "\tDisable external links:\t%t\n", set.Branding.DisableExternal)
|
||||
fmt.Fprintf(w, "\tDisable used disk percentage graph:\t%t\n", set.Branding.DisableUsedPercentage)
|
||||
fmt.Fprintf(w, "\tColor:\t%s\n", set.Branding.Color)
|
||||
@@ -346,8 +234,6 @@ func getSettings(flags *pflag.FlagSet, set *settings.Settings, ser *settings.Ser
|
||||
set.Branding.Theme, err = flags.GetString(flag.Name)
|
||||
case "branding.color":
|
||||
set.Branding.Color, err = flags.GetString(flag.Name)
|
||||
case "branding.files":
|
||||
set.Branding.Files, err = flags.GetString(flag.Name)
|
||||
case "branding.disableExternal":
|
||||
set.Branding.DisableExternal, err = flags.GetBool(flag.Name)
|
||||
case "branding.disableUsedPercentage":
|
||||
|
||||
@@ -67,37 +67,12 @@ The path must be for a json or yaml file.`,
|
||||
return err
|
||||
}
|
||||
|
||||
var rawAuther = file.Auther
|
||||
|
||||
var auther auth.Auther
|
||||
var autherErr error
|
||||
switch file.Settings.AuthMethod {
|
||||
case auth.MethodJSONAuth:
|
||||
var a interface{}
|
||||
a, autherErr = getAuther(auth.JSONAuth{}, rawAuther)
|
||||
auther = a.(*auth.JSONAuth)
|
||||
case auth.MethodNoAuth:
|
||||
var a interface{}
|
||||
a, autherErr = getAuther(auth.NoAuth{}, rawAuther)
|
||||
auther = a.(*auth.NoAuth)
|
||||
case auth.MethodProxyAuth:
|
||||
var a interface{}
|
||||
a, autherErr = getAuther(auth.ProxyAuth{}, rawAuther)
|
||||
auther = a.(*auth.ProxyAuth)
|
||||
case auth.MethodHookAuth:
|
||||
var a interface{}
|
||||
a, autherErr = getAuther(&auth.HookAuth{}, rawAuther)
|
||||
auther = a.(*auth.HookAuth)
|
||||
default:
|
||||
return errors.New("invalid auth method")
|
||||
file.Settings.AuthMethod = auth.MethodSSO
|
||||
auther := &auth.SSOAuth{}
|
||||
if err = st.Settings.Save(file.Settings); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if autherErr != nil {
|
||||
return autherErr
|
||||
}
|
||||
|
||||
err = st.Auth.Save(auther)
|
||||
if err != nil {
|
||||
if err = st.Auth.Save(auther); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
fbhttp "github.com/filebrowser/filebrowser/v2/http"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
type initialConfig struct {
|
||||
CacheDir string `json:"cacheDir"`
|
||||
ImageProcessors int `json:"imageProcessors"`
|
||||
Address string `json:"address"`
|
||||
Port string `json:"port"`
|
||||
Root string `json:"root"`
|
||||
Database string `json:"database"`
|
||||
BaseURL string `json:"baseURL"`
|
||||
DisableExec bool `json:"disableExec"`
|
||||
SSO fbhttp.SSOConfig `json:"sso"`
|
||||
}
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(initCmd)
|
||||
initCmd.Flags().String("output", ".filebrowser.json", "configuration file to create; existing files are never overwritten")
|
||||
}
|
||||
|
||||
var initCmd = &cobra.Command{
|
||||
Use: "init", Short: "Initial setup: SSO, file directory and database", Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
out, _ := cmd.Flags().GetString("output")
|
||||
out, err := filepath.Abs(out)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = os.Stat(out); err == nil {
|
||||
return errors.New("configuration already exists; edit it or select another --output")
|
||||
} else if !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
reader := bufio.NewReader(cmd.InOrStdin())
|
||||
ask := func(label, fallback string) (string, error) {
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "%s [%s]: ", label, fallback)
|
||||
line, err := reader.ReadString('\n')
|
||||
if err != nil && !(errors.Is(err, io.EOF) && line != "") {
|
||||
return "", err
|
||||
}
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
line = fallback
|
||||
}
|
||||
return line, nil
|
||||
}
|
||||
var c initialConfig
|
||||
fmt.Fprintln(cmd.OutOrStdout(), "File Browser — initial setup\nSSO roles Master Admin and FS Admin grant administrator access.")
|
||||
if c.SSO.Issuer, err = ask("SSO issuer URL", "https://sso.anidev.ru"); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.SSO.ClientID, err = ask("SSO Client ID", ""); err != nil {
|
||||
return err
|
||||
}
|
||||
if term.IsTerminal(int(os.Stdin.Fd())) && cmd.InOrStdin() == os.Stdin {
|
||||
fmt.Fprint(cmd.OutOrStdout(), "SSO Client secret (hidden): ")
|
||||
var secret []byte
|
||||
secret, err = term.ReadPassword(int(os.Stdin.Fd()))
|
||||
c.SSO.ClientSecret = strings.TrimSpace(string(secret))
|
||||
fmt.Fprintln(cmd.OutOrStdout())
|
||||
} else {
|
||||
c.SSO.ClientSecret, err = ask("SSO Client secret", "")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if c.SSO.PublicURL, err = ask("Public File Browser URL", "https://files.anidev.ru"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = validateSetupURL(c.SSO.Issuer); err != nil {
|
||||
return fmt.Errorf("issuer: %w", err)
|
||||
}
|
||||
if err = validateSetupURL(c.SSO.PublicURL); err != nil {
|
||||
return fmt.Errorf("public URL: %w", err)
|
||||
}
|
||||
if c.SSO.ClientID == "" || c.SSO.ClientSecret == "" {
|
||||
return errors.New("Client ID and secret are required")
|
||||
}
|
||||
if c.Root, err = ask("File directory", "./files"); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.Database, err = ask("Database path", "./filebrowser.db"); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.Address, err = ask("Listen address", "127.0.0.1"); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.Port, err = ask("Listen port", "8080"); err != nil {
|
||||
return err
|
||||
}
|
||||
port, e := strconv.Atoi(c.Port)
|
||||
if e != nil || port < 1 || port > 65535 {
|
||||
return errors.New("invalid port")
|
||||
}
|
||||
c.Root, err = filepath.Abs(c.Root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.Database, err = filepath.Abs(c.Database)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.CacheDir = filepath.Join(filepath.Dir(c.Database), "cache")
|
||||
c.ImageProcessors = min(2, runtime.NumCPU())
|
||||
public, _ := url.Parse(c.SSO.PublicURL)
|
||||
c.BaseURL = strings.TrimRight(public.Path, "/")
|
||||
c.SSO.RedirectURI = strings.TrimRight(c.SSO.PublicURL, "/") + "/auth/callback"
|
||||
c.DisableExec = true
|
||||
if err = os.MkdirAll(c.Root, 0750); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = os.MkdirAll(filepath.Dir(c.Database), 0700); err != nil {
|
||||
return err
|
||||
}
|
||||
b, err := json.MarshalIndent(c, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.OpenFile(out, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = f.Write(append(b, '\n'))
|
||||
closeErr := f.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if closeErr != nil {
|
||||
return closeErr
|
||||
}
|
||||
bootstrapCmd := &cobra.Command{Use: "bootstrap"}
|
||||
bootstrapCmd.Flags().String("config", out, "")
|
||||
bootstrapCmd.Flags().String("database", c.Database, "")
|
||||
addServerFlags(bootstrapCmd.Flags())
|
||||
bootstrap := withViperAndStore(func(_ *cobra.Command, _ []string, v *viper.Viper, st *store) error {
|
||||
if !st.databaseExisted {
|
||||
return quickSetup(v, st.Storage)
|
||||
}
|
||||
return nil
|
||||
}, storeOptions{allowsNoDatabase: true})
|
||||
if err = bootstrap(bootstrapCmd, nil); err != nil {
|
||||
return fmt.Errorf("configuration saved; database setup failed: %w", err)
|
||||
}
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "\nSaved %s (0600).\nRegister this callback in SSO:\n%s/auth/callback\nStart: filebrowser --config %q\n", out, strings.TrimRight(c.SSO.PublicURL, "/"), out)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func validateSetupURL(raw string) error {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Scheme != "https" && !(u.Scheme == "http" && (u.Hostname() == "localhost" || u.Hostname() == "127.0.0.1"))) {
|
||||
return errors.New("use an HTTPS URL; HTTP is allowed only on loopback")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInitWizard(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
configPath := filepath.Join(dir, "settings.json")
|
||||
input := strings.Join([]string{"https://sso.example.test", "client-id", "client-secret", "https://files.example.test", filepath.Join(dir, "files"), filepath.Join(dir, "files.db"), "127.0.0.1", "8080", ""}, "\n")
|
||||
var output bytes.Buffer
|
||||
initCmd.SetIn(strings.NewReader(input))
|
||||
initCmd.SetOut(&output)
|
||||
defer func() { initCmd.SetIn(nil); initCmd.SetOut(nil) }()
|
||||
if err := initCmd.Flags().Set("output", configPath); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := initCmd.RunE(initCmd, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var c initialConfig
|
||||
b, err := os.ReadFile(configPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = json.Unmarshal(b, &c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.SSO.ClientSecret != "client-secret" || !c.DisableExec || c.Root != filepath.Join(dir, "files") {
|
||||
t.Fatal("configuration lost")
|
||||
}
|
||||
if strings.Contains(output.String(), "client-secret") {
|
||||
t.Fatal("secret leaked to output")
|
||||
}
|
||||
if _, err = os.Stat(c.Database); err != nil {
|
||||
t.Fatal("database not initialized", err)
|
||||
}
|
||||
if !strings.Contains(output.String(), "https://files.example.test/auth/callback") {
|
||||
t.Fatal("callback missing")
|
||||
}
|
||||
initCmd.SetIn(strings.NewReader(input))
|
||||
if err = initCmd.RunE(initCmd, nil); err == nil {
|
||||
t.Fatal("existing configuration overwritten")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestOnlyExplicitNoSSOFlagSkipsInitialSSOSetup(t *testing.T) {
|
||||
for _, enabled := range []bool{false, true} {
|
||||
dir := t.TempDir()
|
||||
config := filepath.Join(dir, "config.json")
|
||||
// A JSON setting must not enable this process-only bypass.
|
||||
if err := os.WriteFile(config, []byte(`{"no-sso":true}`), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
command := &cobra.Command{Use: "filebrowser"}
|
||||
command.Flags().String("config", config, "")
|
||||
command.Flags().String("database", filepath.Join(dir, "test.db"), "")
|
||||
command.Flags().Bool("no-sso", false, "")
|
||||
if enabled {
|
||||
command.Flags().Set("no-sso", "true")
|
||||
}
|
||||
called := false
|
||||
err := withViperAndStore(func(_ *cobra.Command, _ []string, _ *viper.Viper, _ *store) error { called = true; return nil }, storeOptions{allowsNoDatabase: true})(command, nil)
|
||||
if enabled && (err != nil || !called) {
|
||||
t.Fatalf("explicit flag blocked: %v", err)
|
||||
}
|
||||
if !enabled && (err == nil || called) {
|
||||
t.Fatal("configuration silently enabled no-sso")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -85,9 +85,7 @@ func init() {
|
||||
|
||||
// Runtime flags for the root command
|
||||
flags := rootCmd.Flags()
|
||||
flags.Bool("noauth", false, "use the noauth auther when using quick setup")
|
||||
flags.String("username", "admin", "username for the first user when using quick setup")
|
||||
flags.String("password", "", "hashed password for the first user when using quick setup")
|
||||
flags.Bool("no-sso", false, "start without SSO or passwords; everyone with network access is an administrator")
|
||||
flags.Uint32("socketPerm", 0666, "unix socket file permissions")
|
||||
flags.String("cacheDir", "", "file cache directory (disabled if empty)")
|
||||
flags.String("redisCacheUrl", "", "redis cache URL (for multi-instance deployments), e.g. redis://user:pass@host:port")
|
||||
@@ -122,41 +120,8 @@ var rootCmd = &cobra.Command{
|
||||
manage your users and all the configurations without accessing the
|
||||
web interface.
|
||||
|
||||
If you've never run File Browser, you'll need to have a database for
|
||||
it. Don't worry: you don't need to setup a separate database server.
|
||||
We're using Bolt DB which is a single file database and all managed
|
||||
by ourselves.
|
||||
|
||||
For this command, all flags are available as environmental variables,
|
||||
except for "--config", which specifies the configuration file to use.
|
||||
The environment variables are prefixed by "FB_" followed by the flag name in
|
||||
UPPER_SNAKE_CASE. For example, the flag "--disablePreviewResize" is available
|
||||
as FB_DISABLE_PREVIEW_RESIZE.
|
||||
|
||||
If "--config" is not specified, File Browser will look for a configuration
|
||||
file named .filebrowser.{json, toml, yaml, yml} in the following directories:
|
||||
|
||||
- ./
|
||||
- $HOME/
|
||||
- /etc/filebrowser/
|
||||
|
||||
**Note:** Only the options listed below can be set via the config file or
|
||||
environment variables. Other configuration options live exclusively in the
|
||||
database and so they must be set by the "config set" or "config
|
||||
import" commands.
|
||||
|
||||
The precedence of the configuration values are as follows:
|
||||
|
||||
- Flags
|
||||
- Environment variables
|
||||
- Configuration file
|
||||
- Database values
|
||||
- Defaults
|
||||
|
||||
Also, if the database path doesn't exist, File Browser will enter into
|
||||
the quick setup mode and a new database will be bootstrapped and a new
|
||||
user created with the credentials from options "username" and "password".`,
|
||||
RunE: withViperAndStore(func(_ *cobra.Command, _ []string, v *viper.Viper, st *store) error {
|
||||
Run filebrowser init for initial setup. It creates the configuration file, prepares the database and prints the SSO callback URL. Local password accounts and command execution are not supported. Use --no-sso to start without SSO or passwords, granting administrator access to all visitors. Runtime options can still be overridden using flags or FB_ environment variables.`,
|
||||
RunE: withViperAndStore(func(cmd *cobra.Command, _ []string, v *viper.Viper, st *store) error {
|
||||
if !st.databaseExisted {
|
||||
err := quickSetup(v, st.Storage)
|
||||
if err != nil {
|
||||
@@ -192,10 +157,7 @@ user created with the credentials from options "username" and "password".`,
|
||||
}
|
||||
setupLog(server.Log)
|
||||
|
||||
log.Println("NOTICE: File Browser is being wound down.")
|
||||
log.Println("NOTICE: The project is archived on 2026-09-01, after which there will be no")
|
||||
log.Println("NOTICE: further releases and no security fixes. Known unfixed issues are at")
|
||||
log.Println("NOTICE: https://github.com/filebrowser/filebrowser/security/advisories")
|
||||
log.Println("File Browser")
|
||||
|
||||
root, err := filepath.Abs(server.Root)
|
||||
if err != nil {
|
||||
@@ -242,6 +204,23 @@ user created with the credentials from options "username" and "password".`,
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Execution hooks and external symlinks are never enabled in this fork.
|
||||
server.EnableExec = false
|
||||
server.FollowExternalSymlinks = false
|
||||
var authentication interface {
|
||||
Wrap(http.Handler) http.Handler
|
||||
}
|
||||
noSSO, _ := cmd.Flags().GetBool("no-sso")
|
||||
if noSSO {
|
||||
authentication, err = fbhttp.NewNoSSO(st.Storage, server)
|
||||
log.Println("--no-sso: authentication disabled; all visitors have administrator access")
|
||||
} else {
|
||||
authentication, err = fbhttp.NewSSO(context.Background(), st.Storage, server, fbhttp.SSOConfig{Issuer: v.GetString("sso.issuer"), ClientID: v.GetString("sso.clientID"), ClientSecret: v.GetString("sso.clientSecret"), PublicURL: v.GetString("sso.publicURL"), RedirectURI: v.GetString("sso.redirectURI")})
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
handler, err := fbhttp.NewHandler(imageService, fileCache, uploadCache, st.Storage, server, assetsFs)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -251,8 +230,10 @@ user created with the credentials from options "username" and "password".`,
|
||||
|
||||
log.Println("Listening on", listener.Addr().String())
|
||||
srv := &http.Server{
|
||||
Handler: handler,
|
||||
ReadHeaderTimeout: 60 * time.Second,
|
||||
Handler: authentication.Wrap(handler),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
IdleTimeout: 90 * time.Second,
|
||||
MaxHeaderBytes: 1 << 20,
|
||||
}
|
||||
|
||||
go func() {
|
||||
@@ -438,7 +419,7 @@ func quickSetup(v *viper.Viper, s *storage.Storage) error {
|
||||
AceEditorTheme: v.GetString("defaults.aceEditorTheme"),
|
||||
Perm: users.Permissions{
|
||||
Admin: false,
|
||||
Execute: true,
|
||||
Execute: false,
|
||||
Create: true,
|
||||
Rename: true,
|
||||
Modify: true,
|
||||
@@ -458,18 +439,11 @@ func quickSetup(v *viper.Viper, s *storage.Storage) error {
|
||||
Rules: nil,
|
||||
}
|
||||
|
||||
var err error
|
||||
if v.GetBool("noauth") {
|
||||
set.AuthMethod = auth.MethodNoAuth
|
||||
err = s.Auth.Save(&auth.NoAuth{})
|
||||
} else {
|
||||
set.AuthMethod = auth.MethodJSONAuth
|
||||
err = s.Auth.Save(&auth.JSONAuth{})
|
||||
}
|
||||
set.AuthMethod = auth.MethodSSO
|
||||
err := s.Auth.Save(&auth.SSOAuth{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = s.Settings.Save(set)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -497,37 +471,5 @@ func quickSetup(v *viper.Viper, s *storage.Storage) error {
|
||||
return err
|
||||
}
|
||||
|
||||
username := v.GetString("username")
|
||||
password := v.GetString("password")
|
||||
|
||||
if password == "" {
|
||||
var pwd string
|
||||
pwd, err = users.RandomPwd(set.MinimumPasswordLength)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log.Printf("User '%s' initialized with randomly generated password: %s\n", username, pwd)
|
||||
password, err = users.ValidateAndHashPwd(pwd, set.MinimumPasswordLength)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
log.Printf("User '%s' initialize wth user-provided password\n", username)
|
||||
}
|
||||
|
||||
if username == "" || password == "" {
|
||||
log.Fatal("username and password cannot be empty during quick setup")
|
||||
}
|
||||
|
||||
user := &users.User{
|
||||
Username: username,
|
||||
Password: password,
|
||||
LockPassword: false,
|
||||
}
|
||||
|
||||
set.Defaults.Apply(user)
|
||||
user.Perm.Admin = true
|
||||
|
||||
return s.Users.Save(user)
|
||||
return nil
|
||||
}
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(usersCmd)
|
||||
// Local password account management is removed; users are provisioned by SSO.
|
||||
}
|
||||
|
||||
var usersCmd = &cobra.Command{
|
||||
|
||||
@@ -153,6 +153,10 @@ func withViperAndStore(fn func(cmd *cobra.Command, args []string, v *viper.Viper
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
noSSO, _ := cmd.Flags().GetBool("no-sso")
|
||||
if cmd.Parent() == nil && cmd.Use == "filebrowser" && !noSSO && (v.GetString("sso.issuer") == "" || v.GetString("sso.clientID") == "" || v.GetString("sso.clientSecret") == "" || v.GetString("sso.publicURL") == "") {
|
||||
return errors.New("initial setup required: run filebrowser init")
|
||||
}
|
||||
|
||||
path, err := filepath.Abs(v.GetString("database"))
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
[Unit]
|
||||
Description=File Browser SSO workspace
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=filebrowser
|
||||
Group=filebrowser
|
||||
WorkingDirectory=/var/lib/filebrowser
|
||||
ExecStart=/opt/filebrowser/filebrowser --config /var/lib/filebrowser/.filebrowser.json
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
UMask=0027
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ReadWritePaths=/var/lib/filebrowser /srv/filebrowser
|
||||
RestrictSUIDSGID=true
|
||||
LockPersonality=true
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,41 @@
|
||||
# Проверка 3.1.0
|
||||
|
||||
Edge/Chromium, Windows amd64; 1440×1000 и 390×844. Изолированное временное хранилище, настоящие HTTP-обработчики сервера, синтетические файлы. Реальные пользовательские данные и SSO не использовались.
|
||||
|
||||
## Интерфейс и файловые операции
|
||||
|
||||
- Предпросмотр PNG, JPEG, GIF, BMP, TIFF, WebP, SVG, PDF, DICOM 2D, TXT, Markdown, CSV, JSON, XML, HTML, JavaScript, ZIP, EPUB, WAV; WebM проверен отдельно.
|
||||
- Настройки, панель управления, пользователи, публичная ссылка и парольная форма, длинные имена, серверный диалог открытия. Проверены снимки экранов и горизонтальное переполнение.
|
||||
- Создание папки, загрузка, копирование, перемещение, изменение, скачивание и удаление через реальный сервер.
|
||||
- Загрузка 3 МиБ по частям, новая статистика и отмена; сравнение полученного файла с исходными байтами.
|
||||
- Несколько ссылок на один файл, независимые пароль и срок действия.
|
||||
|
||||
## Craft
|
||||
|
||||
| Инструмент | Результат |
|
||||
| --- | --- |
|
||||
| WordCraft | Изменённый текст найден внутри DOCX; сохранение и повторное открытие |
|
||||
| GridCraft | Значение ячейки найдено внутри XLSX; сохранение и повторное открытие |
|
||||
| DeckCraft | Сохранение и повторное открытие собственного `.deckcraft` |
|
||||
| PdfCraft | Пометка сохранена в PDF; повторное открытие |
|
||||
| PhotoCraft | Рисование, сохранение отдельного PSD и повторное открытие; исходный PNG сохранён |
|
||||
| VectorCraft | SVG открыт, проект сохранён в `.vectorcraft` и открыт повторно |
|
||||
| DesignCraft | Валидный проект сохранён и повторно открыт |
|
||||
| CADCraft | DXF сохранён и повторно открыт |
|
||||
| SoundCraft | Отключён: официальная веб-сборка работает только с демосессией |
|
||||
| FigCraft | Отключён: надёжная загрузка/выгрузка серверного проекта не подтверждена |
|
||||
| LightCraft | Отключён: изображение открывается, надёжный экспорт на сервер не подтверждён |
|
||||
|
||||
Открытие второго документа из WordCraft через серверный диалог проверено отдельно: изменения записаны во второй файл, первый остался неизменным.
|
||||
|
||||
Для проверенных сохранений сопоставлены отправленные данные и файл на диске. Это проверка представительных форматов, а не гарантия совместимости каждого импортируемого формата или сложного документа. Мобильная вёрстка сторонних Craft-инструментов определяется самими инструментами.
|
||||
|
||||
DICOM 3D временно выключен; сохранённые предпочтения не удалены. Проверки 2D и декодирования остаются.
|
||||
|
||||
## Повторение
|
||||
|
||||
Обычные проверки: `pnpm --dir frontend test`, `pnpm --dir frontend lint`, `pnpm --dir frontend build`, `go test ./...`, `go vet ./...`.
|
||||
|
||||
Для браузерных сценариев предусмотрен `TestWorkspaceBrowserQA`: задайте `FILEBROWSER_QA=1`, `FILEBROWSER_QA_SCRIPT` (абсолютный путь к `frontend/scripts/check-workspace.cjs` или `check-previews.cjs`), `FILEBROWSER_QA_FIXTURES`, `FILEBROWSER_QA_ADDONS`, `FILEBROWSER_QA_OUTPUT`, `PLAYWRIGHT_MODULE` и `BROWSER_EXECUTABLE`. Затем `go test ./http -run TestWorkspaceBrowserQA -v -count=1`. Сценарии требуют тестовые файлы с именами, перечисленными в их исходниках; авторизация подставляется только внутри тестового бинарника.
|
||||
|
||||
Linux-бинарник собран для amd64/v1 без CGO; запуск на Debian в этой среде не проверялся.
|
||||
@@ -0,0 +1,12 @@
|
||||
# Проверка 3.2.0
|
||||
|
||||
- OIDC: PKCE S256, HTTP Basic, nonce/at_hash/RS256-проверка, повтор callback, изолированные cookies транзакций и host-only Secure/HttpOnly handle.
|
||||
- Внутренний resolve: запрос на каждую операцию без положительного кеша, строгие client_id/sub/expiry, текущие роли, отказ при ошибке провайдера/невалидном ответе без удаления cookie.
|
||||
- Два настоящих HTTP-сервера File Browser с тестовыми БД/файлами и общий имитатор SSO: Alice → Bob в двух открытых приложениях без OAuth-обмена, независимое устройство остаётся Alice, отказ Bob, сбой/восстановление SSO, общий logout и недостающий фактор.
|
||||
- Поздний ответ Alice задержан до перехода на Bob; данные Alice не возвращаются в интерфейс. Старая форма отвергается с 409. Тестируется также недоступный iframe-брокер — работает запасной опрос backend.
|
||||
- TUS: другой аккаунт или новая версия сессии не продолжает старую загрузку; очередь и запросы отменяются при смене аккаунта.
|
||||
- Без SSO: административный доступ без cookie/пароля, неизменный локальный профиль, CSRF-защита сохраняется. В этот режим нельзя перейти из-за отказа SSO.
|
||||
|
||||
Среда: Windows amd64, Edge/Chromium, изолированные данные и синтетический провайдер. Реальные аккаунты SSO не переключались. Проверка с установленным SSO требует внутреннего клиента и зарегистрированных redirect/origin.
|
||||
|
||||
Повторение: обычные `go test ./...`, `go vet ./...`, `pnpm --dir frontend test`, `pnpm --dir frontend lint`, `pnpm --dir frontend build`. Для браузера: `FILEBROWSER_INTERNAL_QA=1`, `FILEBROWSER_INTERNAL_QA_SCRIPT` — абсолютный путь к `frontend/scripts/check-internal-session.cjs`; также задайте `PLAYWRIGHT_MODULE`, `BROWSER_EXECUTABLE`, `FILEBROWSER_QA_OUTPUT`. Запуск: `go test ./http -run TestInternalSessionBrowser -v -count=1`.
|
||||
@@ -1,49 +1,9 @@
|
||||
<p align="center">
|
||||
<img src="../branding/banner.png" width="550"/>
|
||||
</p>
|
||||
# Документация File Browser SSO
|
||||
|
||||
> [!WARNING]
|
||||
>
|
||||
> **File Browser is archived on 2026-09-01.** There will be no further releases and no security fixes. Existing releases and Docker images stay online. For the known unaddressed security issues and hardening guidance, read the [README](../README.md#security).
|
||||
- [Установка на Debian, первоначальная настройка, SSO и systemd](deployment.md)
|
||||
- [Авторизация и сессии](authentication.md)
|
||||
- [Проверки безопасности и ограничения](SECURITY-REVIEW.md)
|
||||
- [Настройка внешнего вида](customization.md)
|
||||
- [CLI](cli/filebrowser.md)
|
||||
|
||||
File Browser provides a file managing interface within a specified directory and it can be used to upload, delete, preview and edit your files. It is a **create-your-own-cloud**-kind of software where you can just install it on your server, direct it to a path and access your files through a nice web interface.
|
||||
|
||||

|
||||
|
||||
## Contents
|
||||
|
||||
- [Installation](installation.md)
|
||||
- [Customization](customization.md)
|
||||
- [Authentication](authentication.md)
|
||||
- [Command Execution](command-execution.md)
|
||||
- [Deployment](deployment.md)
|
||||
- [Troubleshooting](troubleshooting.md)
|
||||
- [Command Line Usage](cli/filebrowser.md)
|
||||
|
||||
Project-level documents live in the repository root: [README](../README.md), [Building File Browser](../CONTRIBUTING.md), [Security Policy](../SECURITY.md), [Code of Conduct](../CODE-OF-CONDUCT.md), [Changelog](../CHANGELOG.md) and [License](../LICENSE).
|
||||
|
||||
## Features
|
||||
|
||||
- **Easy Login System**
|
||||
|
||||

|
||||
|
||||
- **Sleek Interface**
|
||||
|
||||

|
||||
|
||||
- **User Management**
|
||||
|
||||

|
||||
|
||||
- **File Editing**
|
||||
|
||||

|
||||
|
||||
- **Custom Commands**
|
||||
|
||||

|
||||
|
||||
- **Customization**
|
||||
|
||||

|
||||
Актуальная точка входа — `filebrowser init`. Руководства исходного архивированного File Browser по локальным паролям, proxy-auth, hook-auth и выполнению команд к этому форку не применяются.
|
||||
@@ -0,0 +1,34 @@
|
||||
# Проверки безопасности и ограничения
|
||||
|
||||
Проверено 21 октября 2026 года. Это результат проверок конкретного состояния исходников, а не гарантия отсутствия всех возможных уязвимостей.
|
||||
|
||||
## Сделано
|
||||
|
||||
- Удалены JSON/password, no-auth, proxy и hook способы входа, регистрация, выпуск и продление JWT File Browser. Локальные пароли в существующей базе при миграции заменяются заблокированным значением.
|
||||
- OIDC Authorization Code с PKCE S256, state, nonce, RS256, issuer/audience/expiry и at_hash. Идентичность привязана к issuer и sub; совпадение имени с локальным пользователем не повышает права.
|
||||
- Административная роль берётся только из подтверждённого SSO-входа: Master Admin / FS Admin. Флаг admin в локальном профиле не даёт административный доступ.
|
||||
- С версии 3.2.0: host-only Secure/HttpOnly cookie с внутренним handle; свежий resolve для каждого защищённого запроса, общий logout и защита изменений ожидаемым session_state. Самостоятельных локальных SSO-сессий нет.
|
||||
- Проверка Origin и специального заголовка для меняющих состояние запросов, запрет cross-site запросов. CSP с nonce для HTML bootstrap, запрет скриптов при выдаче пользовательских файлов, nosniff.
|
||||
- Выполнение команд и файловые хуки принудительно выключены; /api/command не зарегистрирован. Внешние симлинки запрещены. Старый вспомогательный CLI-код локальных аккаунтов не подключён к корневой команде; часть legacy-кода оставлена отключённой.
|
||||
- Короткие ссылки: валидация имени, атомарная вставка в BoltDB, отказ 409 при занятом имени; случайные ключи увеличены с 48 до 128 бит.
|
||||
- Исправлено удаление соседних просроченных ссылок: прежний цикл менял срез во время range и мог пропускать записи или выходить за границы.
|
||||
- Исправлен откат слишком большого TUS-чанка на Windows: используется запись с явным смещением, позволяющая Truncate; проверены последовательные чанки и повторное использование HTTP-соединения.
|
||||
- Ошибка чтения настроек больше не завершает процесс сервера через log.Fatalf.
|
||||
- Обновлены frontend-зависимости и x/net, x/crypto, x/image. Удалена цепочка линтера с неисправленной advisory braces; вместо неё используется flat config typescript-eslint. Режимы и темы Ace включены в бинарник, загрузка с CDN больше не нужна.
|
||||
|
||||
## Результаты
|
||||
|
||||
- go test ./... — успешно на Windows, включая OIDC, роли, logout, отказе/смене аккаунта, CSRF, callback replay, короткие ссылки и конкурентную вставку.
|
||||
- go vet ./... — успешно.
|
||||
- Frontend: TypeScript, production build, 29 тестов и ESLint без ошибок — успешно. У старых неизменённых файлов при полном lint остаются предупреждения Prettier из-за CRLF-выгрузки Windows.
|
||||
- pnpm audit — 0 известных уязвимостей в установленном дереве.
|
||||
- govulncheck для linux/amd64 — 0 уязвимостей в вызываемом коде и импортируемых пакетах. Одна advisory остаётся на уровне требуемого модуля: GO-2026-5932 (неиспользуемый пакет golang.org/x/crypto/openpgp). Приложение openpgp не импортирует и не вызывает; исправленной версии для этого устаревшего пакета нет.
|
||||
- В браузере: тестовый локальный OIDC-провайдер, список файлов, создание именованной ссылки и маршрут /s/{key}. Настоящие Client ID/secret не использовались и в репозиторий не добавлялись.
|
||||
|
||||
## Ограничения эксплуатации
|
||||
|
||||
Новый контракт и проверки общей сессии описаны в [авторизации](authentication.md). При недоступности SSO доступ закрыт без резервной локальной авторизации. Режим без входа включается только явным `--no-sso` и предоставляет всем посетителям административный доступ.
|
||||
|
||||
Debian-бинарник собирается из Windows для linux/amd64 с отключённым CGO и GOAMD64=v1. Нативный запуск и тесты на Debian в этой среде не выполнялись. POSIX-тест с именами, содержащими обратные слеши, не применим к файловой системе Windows и пропускается там.
|
||||
|
||||
Конфигурация содержит Client secret и должна принадлежать только пользователю службы (0600). Рекомендуемый systemd-файл отделяет исполняемые файлы от изменяемых данных. Обновляйте зависимости и повторяйте аудит перед публикацией новых версий.
|
||||
@@ -0,0 +1,45 @@
|
||||
# Craft-аддоны
|
||||
|
||||
В «Панель управления → Аддоны» доступны 11 инструментов: скачать/обновить, включить/отключить, увидеть версию, этап загрузки и ошибку. Настройки доступны администратору; для редактирования нужны права скачивания и изменения файла. Создание и «Сохранить как» дополнительно требуют права создания.
|
||||
|
||||
| Инструмент | Открытие | Сохранение |
|
||||
| --- | --- | --- |
|
||||
| WordCraft / GridCraft / PdfCraft | DOCX / XLSX / PDF | Исходный формат, PDF |
|
||||
| DeckCraft | PPTX, DeckCraft | Штатное сохранение DeckCraft; экспорт PPTX/PDF |
|
||||
| PhotoCraft | PCraft, PSD/PSB, PNG/JPEG/WebP/GIF/BMP/TIFF | Эти же форматы |
|
||||
| VectorCraft | VectorCraft/DrawCraft, SVG | Нативный формат, SVG/PDF/PNG/JPEG |
|
||||
| LightCraft | DNG/CR2/CR3/NEF/NRW/ARW/PEF/ORF/RW2/RAF, JPEG/PNG/TIFF | Экспорт JPEG/PNG/TIFF отдельным файлом |
|
||||
| DesignCraft | DesignCraft, IDML | Нативный формат, IDML/PDF/PNG/JPEG |
|
||||
| FigCraft | FigCraft | Нативный формат, SVG/PDF/PNG/JPEG |
|
||||
| SoundCraft | SCraftZ, WAV/FLAC/MP3/Ogg/AIFF/M4A, MIDI | SCraftZ со встроенными аудио, поддерживаемые аудио/MIDI-экспорты |
|
||||
| CADCraft | DXF/DWG | DXF/PDF/SVG/PNG; DWG не перезаписывается |
|
||||
|
||||
Для нескольких подходящих редакторов доступны отдельные команды «Открыть в…». Двойной клик использует встроенный быстрый просмотр; PDF открывается в доступном PdfCraft. Для форматов без быстрого просмотра выбирается первый подходящий установленный включённый инструмент. У LightCraft каждая вкладка использует отдельный каталог в памяти (`store=memory`); настройки обработки и каталог не синхронизируются с сервером. RAW-оригиналы не перезаписываются, экспорт требует права создания.
|
||||
|
||||
FilmCraft и EffectCraft изучены, но не включены: для сохранения и повторного открытия их проектов на другом устройстве нужна привязка ссылок на исходные видео, аудио и прочие медиа к файловому серверу. Простой перенос одного проекта этого не обеспечивает.
|
||||
|
||||
Веб-сборки хранятся в `addons` относительно рабочего каталога процесса. Для штатного Debian systemd unit это `/var/lib/filebrowser/addons`. Папка не входит в бинарник и архивы релиза: на другом сервере инструменты скачиваются кнопкой или переносится вся готовая папка `addons` с сохранением структуры. Отдельных служб редакторов нет.
|
||||
|
||||
Структура: `addons/<id>/active.json` — активная версия; `addons/<id>/versions/<tag>-<sha>/` — неизменяемые веб-файлы и оригинальные лицензии. Установка берёт только стабильный официальный GitHub Release из фиксированного каталога репозиториев `storytold`, заданного в `internal/addons/catalog.go`. Проверяются размер и SHA-256 из метаданных GitHub, затем ZIP распаковывается в отдельную временную папку. Ограничения: архив 128 МиБ, распакованные файлы суммарно 512 МиБ, отдельный файл 128 МиБ, 4096 записей, 16 уровней. Запрещены ссылки, пути наружу и совпадающие без учёта регистра имена. После успешной проверки указатель версии заменяется атомарно. Неудачное обновление оставляет прежнюю версию. Повторная проверка уже установленного релиза не скачивает архив заново.
|
||||
|
||||
Для HTML, JS и WASM создаются gzip-копии; корректные MIME, CSP для WASM и same-origin iframe задаются только страницам аддонов. Основная CSP File Browser не ослабляется. Старые версии остаются на диске: открытые редакторы продолжают загружать свои файлы. Удалять старые версии и оставшиеся после аварийной остановки `.install-*` можно вручную при остановленном сервере. Каталог `addons` закрыт от чтения/изменения через обычный файловый API, включая псевдонимы через ссылки и операции над родительскими папками.
|
||||
|
||||
В ПКМ и панели предпросмотра появляется «Открыть в WordCraft/GridCraft/DeckCraft/PdfCraft». В «Создать» — DOCX/XLSX/PPTX/PDF, если соответствующий аддон установлен и включён; сервер генерирует корректные пустые документы. Двойной клик сначала использует встроенный быстрый просмотр; PDF открывается в установленном включённом PdfCraft. Для файлов без быстрого просмотра открывается подходящий редактор в отдельной вкладке без панелей File Browser. Команда «Открыть в…» и создание документов также открывают отдельную вкладку. Для остальных файлов сохраняется обычное открытие.
|
||||
|
||||
CADCraft/GridCraft/PdfCraft используют официальный `?host=parent`/`postMessage`. Для остальных редакторов сервер добавляет собственный адаптер в отдаваемую HTML-страницу: открытие через штатную обработку перетаскивания, сохранение разрешённых форматов через перехват браузерного сохранения. Успех асинхронного сохранения подтверждается после ответа сервера. Остальные экспорты остаются обычными скачиваниями браузера. Исходные файлы установленных сборок не изменяются; HTML с адаптером не кешируется. Для обоих способов проверяются origin и конкретное окно iframe. Данные передаются без токенов SSO. Файлы загружаются и сохраняются через собственный API File Browser, с проверкой области доступа, правил и текущих разрешений. Размер документа ограничен 64 МиБ; Архивные документы и проекты дополнительно ограничены 4096 записями и суммарно 256 МиБ заявленного распакованного содержимого. Одновременно обрабатываются не более двух запросов документов.
|
||||
|
||||
Сохранение сначала пишет временный файл и выполняет Sync; затем проверяет SHA-256 ETag и заменяет оригинал. Если документ изменился, возвращается 412; «Сохранить как» не перезаписывает занятое имя (409). Проверка и замена синхронизированы с файловыми операциями данного процесса File Browser. Изменения сторонними процессами не блокируются. Успех показывается только после ответа сервера, а при ошибке доступны повтор, другое имя и скачивание копии. При истечении сессии можно войти в соседней вкладке и повторить запись без автоматического ухода из редактора. Активность пользователя в iframe поддерживает текущую сессию, но простаивающая вкладка её не продлевает.
|
||||
|
||||
Инструменты исполняются в браузере: нужны современный браузер и WebGL2/WebGPU. Совместного редактирования в реальном времени нет. Для редакторов с адаптером состояние изменений определяется консервативно по действиям пользователя: предупреждение перед закрытием возможно и после действий, которые не меняют документ. Графический запуск проверяет пользователь; автоматические проверки не запускают GPU-интерфейс.
|
||||
|
||||
Проверка официальных сборок вручную: установить `FB_TEST_OFFICIAL_ADDONS=1`, при необходимости `FB_TEST_ADDONS_DIR` в абсолютный путь целевого `addons`, затем выполнить `go test ./internal/addons -run TestOfficialBundles -v -count=1`. Обычно тест пропускается и не использует сеть.
|
||||
|
||||
## Совместимость DeckCraft v0.9.0
|
||||
|
||||
Официальная WASM-сборка вызывает `std::process::id()` в `recovery::instance_id`, что паникует на wasm32. `http/deckcraft_compat.js` перед `__wbindgen_start` инициализирует этот `OnceLock<u64>` случайным идентификатором браузера с теми же ограничениями: меньше 2^53, младшие 24 бита нулевые. Последующий счётчик документов остаётся штатным.
|
||||
|
||||
Обход добавляется только для `v0.9.0-38076027b9c1` и независимо сверяет полный SHA-256 WASM (`e0849d8de375fe7726a621f7e98112b76a7b0d0bc361d701bcae66b639c8e354`), размер памяти и исходное нулевое состояние. Другие сборки не затрагиваются. Файлы аддона на диске и SRI остаются исходными. При обновлении DeckCraft это исправление необходимо перепроверять; адрес внутренней структуры нельзя переносить на другую WASM-сборку.
|
||||
|
||||
Редактор запускается с `blank`, чтобы не открывать демонстрационную презентацию перед документом пользователя. Штатное браузерное Save сохраняет `.deckcraft` (архив с `presentation.json` и встроенными медиа); этот формат теперь открывается и сохраняется через FS с теми же лимитами, правами и ETag. Для PPTX используется экспорт редактора. Первая запись в новом формате запрашивает имя отдельной копии.
|
||||
|
||||
Проверено программным тестом в фоновом Edge/WebGL2: запуск, импорт тестового PPTX, Ctrl+S и получение `smoke.deckcraft`. Снимки экрана и визуальная оценка не выполнялись. `http/testdata/deckcraft-blank.deckcraft` — результат этого теста без пользовательских данных.
|
||||
@@ -1,167 +1,29 @@
|
||||
# Authentication
|
||||
# Авторизация
|
||||
|
||||
There are three possible authentication methods. Each one of them has its own capabilities and specification. Adding another authentication method is described in [Building File Browser](../CONTRIBUTING.md#authentication-provider).
|
||||
## Общая сессия SSO
|
||||
|
||||
## JSON Auth (default)
|
||||
File Browser использует внутренний контракт общей браузерной сессии. В SSO приложение должно иметь тип **«Внутреннее»**, PKCE S256 и точный callback. Настройка — через `filebrowser init`; секрет хранится только в конфигурации сервера.
|
||||
|
||||
We call it JSON Authentication but it is just the default authentication method and the one that is provided by default if you don't make any changes. It is set by default, but if you've made changes before you can revert to using JSON auth:
|
||||
Первичный вход: discovery → Authorization Code + PKCE S256 с `internal_sync=1`. Проверяются одноразовый state, nonce, RS256/JWKS, issuer, audience, exp и at_hash. Параллельные попытки входа имеют отдельные cookies. Для восстановления привязки доступен `prompt=none`; при необходимости фактора продолжается обычный поток без принудительного запроса пароля.
|
||||
|
||||
SSO выдаёт `session_handle`. Он хранится в собственной cookie `__Host-internal_session`: Secure, HttpOnly, SameSite=Lax, Path=/, без Domain. Срок не превышает выданный SSO и 30 суток. Cookie не заменяет родительскую сессию SSO и не продлевает её. Access/ID tokens и watch не сохраняются; handle не передаётся в JavaScript, URL или localStorage.
|
||||
|
||||
**Каждый защищённый запрос** обращается к `/internal/session/resolve` с Basic client ID/secret. Используются только текущие `sub` и роли из resolve; положительный результат между запросами не кешируется. Локальная база хранит настройки и файловые права, а не самостоятельный вход. Связка issuer + sub сохраняет прежние ID, настройки и ссылки. Роли `Master Admin` и `FS Admin` дают административный доступ.
|
||||
|
||||
`GET /auth/session` возвращает текущий статус и разрешённый профиль без credentials. Копия SDK `internal-session.js` синхронизирует открытые вкладки: смена аккаунта отменяет запросы/загрузки, очищает данные и монтирует интерфейс нового аккаунта. Старые формы отвергаются по `X-FB-Session-State` с `409 session_changed`. TUS-загрузка привязана к аккаунту и версии сессии; продолжить её от другого аккаунта нельзя. Долгие чтения/записи перепроверяются не реже чем при следующем чтении/записи после двух секунд, сохранение Craft — также перед атомарной заменой файла.
|
||||
|
||||
При отказе в доступе данные скрываются; при недостающем факторе предлагается пройти TOTP/Passkey. Подключение фактора выполняется в настройках аккаунта. Ошибка SSO/TLS/ответа закрывает защищённые действия с 503, сохраняя cookie для восстановления. Автоматического перехода на старую локальную сессию нет.
|
||||
|
||||
Выход — защищённый POST, общий для текущей браузерной сессии SSO. Другие устройства не выходят. Если аккаунт успел смениться, logout получает 409 и не повторяется для нового пользователя. «Сменить аккаунт» сначала выполняет этот выход, затем открывает обычный поток входа.
|
||||
|
||||
При обновлении старые восьмичасовые сессии File Browser больше не принимаются. Требуется новая PKCE-привязка; существующий вход SSO обычно позволяет сделать её без повторного пароля. Для всех приложений используйте одинаковый issuer; общие Domain-cookies не нужны.
|
||||
|
||||
## Без входа
|
||||
|
||||
```sh
|
||||
filebrowser config set --auth.method=json
|
||||
./filebrowser --no-sso
|
||||
```
|
||||
|
||||
This method can also be extended with **reCAPTCHA** verification during login:
|
||||
Этот явный флаг запускает приложение без SSO и пароля. Все посетители получают права администратора в настроенном файловом корне. Конфигурация SSO и доступность провайдера не проверяются. Настройки локального профиля сохраняются между запусками. Без флага обязательна проверка через SSO; ошибка провайдера режим без входа не включает.
|
||||
|
||||
```sh
|
||||
filebrowser config set --auth.method=json \
|
||||
--recaptcha.key site-key \
|
||||
--recaptcha.secret private-key
|
||||
```
|
||||
|
||||
By default, we use [Google's reCAPTCHA](https://developers.google.com/recaptcha/docs/display) service. If you live in China, or want to use other provider, you can change the host with the following command:
|
||||
|
||||
```sh
|
||||
filebrowser config set --recaptcha.host https://recaptcha.net
|
||||
```
|
||||
|
||||
Where `https://recaptcha.net` is any provider you want.
|
||||
|
||||
## Proxy Header
|
||||
|
||||
If you have a reverse proxy you want to use to login your users, you do it via our `proxy` authentication method. To configure this method, your proxy must send an HTTP header containing the username of the logged in user:
|
||||
|
||||
```sh
|
||||
filebrowser config set --auth.method=proxy --auth.header=X-My-Header
|
||||
```
|
||||
|
||||
Where `X-My-Header` is the HTTP header provided by your proxy with the username.
|
||||
|
||||
> [!WARNING]
|
||||
>
|
||||
> File Browser will blindly trust the provided header. If the proxy can be bypassed, an attacker could simply attach the header and get admin access. Please ensure that File Browser is not accessible from untrusted networks, and that the proxy is correctly configured to strip/overwrite the header from client requests.
|
||||
|
||||
## Hook Authentication
|
||||
|
||||
The Hook Authentication method in FileBrowser allows developers to delegate user authentication to an external script or program. Instead of validating credentials internally, FileBrowser sends the username and password to a custom command defined by the administrator. This command receives the credentials through environment variables and returns key‑value pairs indicating whether the user should be authenticated, blocked, or passed through.
|
||||
|
||||
The hook’s output controls user permissions, scope, locale, and other attributes, making it a powerful and extensible authentication mechanism.
|
||||
|
||||
> [!WARNING]
|
||||
>
|
||||
> The submitted username and password are attacker-controlled and are handed to your hook command as the `USERNAME` and `PASSWORD` environment variables. File Browser runs the command directly, without a shell, so the values themselves are inert. However, your script must treat them as untrusted: always quote them (`"$USERNAME"`, `"$PASSWORD"`) and never pass them unquoted to a shell, `eval`, `bash -c`, command substitution, or backticks. A hook script that shell-evaluates these values turns any login request into remote code execution.
|
||||
|
||||
For example, the following code delegates filebrowser authentication to a PowerShell script on Windows. You can configure any command (for example, a script in Python, Node.js, etc.).
|
||||
|
||||
```sh
|
||||
filebrowser config set --auth.method=hook --auth.command="powershell.exe -File C:\route\to\your\script\auth.ps1"
|
||||
```
|
||||
|
||||
This is the code for the auth.ps1 script
|
||||
|
||||
```sh
|
||||
param()
|
||||
|
||||
# Get FileBrowser credentials from environment variables
|
||||
$username = $env:USERNAME
|
||||
$password = $env:PASSWORD
|
||||
|
||||
# Users dictionary (for testing purposes only)
|
||||
$users = @{
|
||||
"admin" = "kideW48v7-SdE*"
|
||||
"test" = "2sDd3-etrytñK"
|
||||
}
|
||||
|
||||
# Check if the user exists in the dictionary and verify the password
|
||||
if ($users.ContainsKey($username) -and $users[$username] -eq $password) {
|
||||
|
||||
# Successful authentication
|
||||
Write-Output "hook.action=auth" # Hook action (in this case, "auth", is required for successful authentication)
|
||||
|
||||
Write-Output "user.perm.admin=true" # Set admin role (all permissions)
|
||||
#You can also define specific permissions like this:
|
||||
Write-Output "user.perm.execute=true"
|
||||
Write-Output "user.perm.create=true"
|
||||
Write-Output "user.perm.rename=true"
|
||||
Write-Output "user.perm.modify=true"
|
||||
Write-Output "user.perm.delete=true"
|
||||
Write-Output "user.perm.share=true"
|
||||
Write-Output "user.perm.download=true"
|
||||
|
||||
Write-Output "user.locale=es" # Set language
|
||||
Write-Output "user.viewMode=list" # Set view mode
|
||||
Write-Output "user.scope=/" # Set FileBrowser scope
|
||||
Write-Output "user.singleClick=true" # Set single click user configuration
|
||||
Write-Output "user.hideDotfiles=false" # Set hide dot files user configuration
|
||||
|
||||
#Set other configuration
|
||||
} else {
|
||||
# Block authentication
|
||||
Write-Output "hook.action=block"
|
||||
}
|
||||
```
|
||||
|
||||
### Hook Output Format
|
||||
|
||||
A hook authentication script must output a series of key–value pairs, one per line, using the format:
|
||||
|
||||
```
|
||||
key=value
|
||||
```
|
||||
|
||||
FileBrowser reads these lines and applies the corresponding authentication action and user configuration.
|
||||
|
||||
#### Required Fields
|
||||
|
||||
The hook must output one of the following actions:
|
||||
|
||||
| Key | Description |
|
||||
|--------|------------ |
|
||||
| hook.action=auth | Authenticates the user. FileBrowser will create or update the user if needed. |
|
||||
| hook.action=block | Rejects authentication. The login attempt fails. |
|
||||
| hook.action=pass | Delegates authentication to FileBrowser’s internal password validation. |
|
||||
|
||||
For most custom authentication flows, auth or block are used.
|
||||
|
||||
Example of a successful authentication:
|
||||
|
||||
```sh
|
||||
hook.action=auth
|
||||
```
|
||||
|
||||
#### Optional User Fields
|
||||
|
||||
When `hook.action=auth` is returned, the hook may also define additional user attributes. These fields override FileBrowser defaults and allow full customization of the authenticated user.
|
||||
|
||||
1. Permissions
|
||||
```
|
||||
user.perm.admin=true
|
||||
user.perm.execute=true
|
||||
user.perm.create=true
|
||||
user.perm.rename=true
|
||||
user.perm.modify=true
|
||||
user.perm.delete=true
|
||||
user.perm.share=true
|
||||
user.perm.download=true
|
||||
```
|
||||
> Setting user.perm.admin=true automatically enables all permissions.
|
||||
|
||||
2. User Interface and Behavior
|
||||
```
|
||||
user.locale=es
|
||||
user.viewMode=list
|
||||
user.singleClick=true
|
||||
user.hideDotfiles=false
|
||||
```
|
||||
|
||||
3. User Scope
|
||||
```
|
||||
user.scope=/
|
||||
```
|
||||
|
||||
## No Authentication
|
||||
|
||||
We also provide a no authentication mechanism for users that want to use File Browser privately such in a home network. By setting this authentication method, the user with **id 1** will be used as the default users. Creating more users won't have any effect.
|
||||
|
||||
```sh
|
||||
filebrowser config set --auth.method=noauth
|
||||
```
|
||||
Пароли публичных ссылок остаются независимыми и работают в обоих режимах.
|
||||
@@ -19,15 +19,10 @@ filebrowser config init [flags]
|
||||
```
|
||||
--aceEditorTheme string ace editor's syntax highlighting theme for users
|
||||
-a, --address string address to listen on (default "127.0.0.1")
|
||||
--auth.command string command for auth.method=hook
|
||||
--auth.header string HTTP header for auth.method=proxy
|
||||
--auth.logoutPage string url of custom logout page
|
||||
--auth.method string authentication type (default "json")
|
||||
-b, --baseURL string base url
|
||||
--branding.color string set the theme color
|
||||
--branding.disableExternal disable external links such as GitHub links
|
||||
--branding.disableUsedPercentage disable used disk percentage graph
|
||||
--branding.files string path to directory with images and custom styles
|
||||
--branding.name string replace 'File Browser' by this name
|
||||
--branding.theme string set the theme
|
||||
-t, --cert string tls certificate
|
||||
@@ -59,13 +54,9 @@ filebrowser config init [flags]
|
||||
--perm.rename rename perm for users (default true)
|
||||
--perm.share share perm for users (default true)
|
||||
-p, --port string port to listen on (default "8080")
|
||||
--recaptcha.host string use another host for ReCAPTCHA. recaptcha.net might be useful in China (default "https://www.google.com")
|
||||
--recaptcha.key string ReCaptcha site key
|
||||
--recaptcha.secret string ReCaptcha secret
|
||||
--redirectAfterCopyMove redirect to destination after copy/move
|
||||
-r, --root string root to prepend to relative paths (default ".")
|
||||
--scope string scope for users (default ".")
|
||||
--shell string shell command to which other commands should be appended
|
||||
-s, --signup allow users to signup
|
||||
--singleClick use single clicks only
|
||||
--socket string socket to listen to (cannot be used with address, port, cert nor key flags)
|
||||
|
||||
@@ -16,15 +16,10 @@ filebrowser config set [flags]
|
||||
```
|
||||
--aceEditorTheme string ace editor's syntax highlighting theme for users
|
||||
-a, --address string address to listen on (default "127.0.0.1")
|
||||
--auth.command string command for auth.method=hook
|
||||
--auth.header string HTTP header for auth.method=proxy
|
||||
--auth.logoutPage string url of custom logout page
|
||||
--auth.method string authentication type (default "json")
|
||||
-b, --baseURL string base url
|
||||
--branding.color string set the theme color
|
||||
--branding.disableExternal disable external links such as GitHub links
|
||||
--branding.disableUsedPercentage disable used disk percentage graph
|
||||
--branding.files string path to directory with images and custom styles
|
||||
--branding.name string replace 'File Browser' by this name
|
||||
--branding.theme string set the theme
|
||||
-t, --cert string tls certificate
|
||||
@@ -56,13 +51,9 @@ filebrowser config set [flags]
|
||||
--perm.rename rename perm for users (default true)
|
||||
--perm.share share perm for users (default true)
|
||||
-p, --port string port to listen on (default "8080")
|
||||
--recaptcha.host string use another host for ReCAPTCHA. recaptcha.net might be useful in China (default "https://www.google.com")
|
||||
--recaptcha.key string ReCaptcha site key
|
||||
--recaptcha.secret string ReCaptcha secret
|
||||
--redirectAfterCopyMove redirect to destination after copy/move
|
||||
-r, --root string root to prepend to relative paths (default ".")
|
||||
--scope string scope for users (default ".")
|
||||
--shell string shell command to which other commands should be appended
|
||||
-s, --signup allow users to signup
|
||||
--singleClick use single clicks only
|
||||
--socket string socket to listen to (cannot be used with address, port, cert nor key flags)
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# filebrowser init
|
||||
|
||||
Initial setup: SSO, file directory and database
|
||||
|
||||
```
|
||||
filebrowser init [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-h, --help help for init
|
||||
--output string configuration file to create; existing files are never overwritten (default ".filebrowser.json")
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
-c, --config string config file path
|
||||
-d, --database string database path (default "./filebrowser.db")
|
||||
```
|
||||
|
||||
## See Also
|
||||
|
||||
* [filebrowser](filebrowser.md) - A stylish web-based file browser
|
||||
@@ -8,40 +8,7 @@ File Browser CLI lets you create the database to use with File Browser,
|
||||
manage your users and all the configurations without accessing the
|
||||
web interface.
|
||||
|
||||
If you've never run File Browser, you'll need to have a database for
|
||||
it. Don't worry: you don't need to setup a separate database server.
|
||||
We're using Bolt DB which is a single file database and all managed
|
||||
by ourselves.
|
||||
|
||||
For this command, all flags are available as environmental variables,
|
||||
except for "--config", which specifies the configuration file to use.
|
||||
The environment variables are prefixed by "FB_" followed by the flag name in
|
||||
UPPER_SNAKE_CASE. For example, the flag "--disablePreviewResize" is available
|
||||
as FB_DISABLE_PREVIEW_RESIZE.
|
||||
|
||||
If "--config" is not specified, File Browser will look for a configuration
|
||||
file named .filebrowser.{json, toml, yaml, yml} in the following directories:
|
||||
|
||||
- ./
|
||||
- $HOME/
|
||||
- /etc/filebrowser/
|
||||
|
||||
**Note:** Only the options listed below can be set via the config file or
|
||||
environment variables. Other configuration options live exclusively in the
|
||||
database and so they must be set by the "config set" or "config
|
||||
import" commands.
|
||||
|
||||
The precedence of the configuration values are as follows:
|
||||
|
||||
- Flags
|
||||
- Environment variables
|
||||
- Configuration file
|
||||
- Database values
|
||||
- Defaults
|
||||
|
||||
Also, if the database path doesn't exist, File Browser will enter into
|
||||
the quick setup mode and a new database will be bootstrapped and a new
|
||||
user created with the credentials from options "username" and "password".
|
||||
Run filebrowser init for initial setup. It creates the configuration file, prepares the database and prints the SSO callback URL. Local password accounts and command execution are not supported. Runtime options can still be overridden using flags or FB_ environment variables.
|
||||
|
||||
```
|
||||
filebrowser [flags]
|
||||
@@ -66,15 +33,12 @@ filebrowser [flags]
|
||||
--imageProcessors int image processors count (default 4)
|
||||
-k, --key string tls key
|
||||
-l, --log string log output (default "stdout")
|
||||
--noauth use the noauth auther when using quick setup
|
||||
--password string hashed password for the first user when using quick setup
|
||||
-p, --port string port to listen on (default "8080")
|
||||
--redisCacheUrl string redis cache URL (for multi-instance deployments), e.g. redis://user:pass@host:port
|
||||
-r, --root string root to prepend to relative paths (default ".")
|
||||
--socket string socket to listen to (cannot be used with address, port, cert nor key flags)
|
||||
--socketPerm uint32 unix socket file permissions (default 438)
|
||||
--tokenExpirationTime string user session timeout (default "2h")
|
||||
--username string username for the first user when using quick setup (default "admin")
|
||||
```
|
||||
|
||||
## See Also
|
||||
@@ -83,7 +47,7 @@ filebrowser [flags]
|
||||
* [filebrowser completion](filebrowser-completion.md) - Generate the autocompletion script for the specified shell
|
||||
* [filebrowser config](filebrowser-config.md) - Configuration management utility
|
||||
* [filebrowser hash](filebrowser-hash.md) - Hashes a password
|
||||
* [filebrowser init](filebrowser-init.md) - Initial setup: SSO, file directory and database
|
||||
* [filebrowser rules](filebrowser-rules.md) - Rules management utility
|
||||
* [filebrowser users](filebrowser-users.md) - Users management utility
|
||||
* [filebrowser version](filebrowser-version.md) - Print the version number
|
||||
|
||||
@@ -1,54 +1,5 @@
|
||||
# Command Execution
|
||||
# Выполнение команд
|
||||
|
||||
> [!CAUTION]
|
||||
>
|
||||
> The **hook runner** and **interactive shell** functionalities have been disabled for all existent and new installations by default from version v2.33.8 and onwards, due to continuous and known security vulnerabilities. You should only use this feature if you are aware of all of the security risks involved. For more up to date information, consult issue [#5199](https://github.com/filebrowser/filebrowser/issues/5199).
|
||||
В этом форке выполнение команд, shell API и файловые хуки отключены без возможности включения через пользовательские настройки. Веб-маршрут `/api/command` отсутствует.
|
||||
|
||||
## Hook Runner
|
||||
|
||||
The hook runner is a feature that enables you to execute any shell command you want before or after a certain event. Right now, these are the events:
|
||||
|
||||
* Copy
|
||||
* Rename
|
||||
* Upload
|
||||
* Delete
|
||||
* Save
|
||||
|
||||
Also, during the execution of the commands set for those hooks, there will be some environment variables available to help you perform your commands:
|
||||
|
||||
* `FILE` with the full absolute path to the changed file.
|
||||
* `SCOPE` with the path to user's scope.
|
||||
* `TRIGGER` with the name of the event.
|
||||
* `USERNAME` with the user's username.
|
||||
* `DESTINATION` with the absolute path to the destination. Only used for **copy** and **rename.**
|
||||
|
||||
At this moment, you can edit the commands via the command line interface, using the following commands \(please check the flag `--help` to know more about them\):
|
||||
|
||||
```bash
|
||||
filebrowser cmds add before_copy "echo $FILE"
|
||||
filebrowser cmds rm before_copy 0
|
||||
filebrowser cmds ls
|
||||
```
|
||||
|
||||
Or you can use the web interface to manage them via **Settings** → **Global Settings**.
|
||||
|
||||
## Interactive Shell
|
||||
|
||||
Within File Browser you can toggle the shell (`< >` icon at the top right) and this will open a shell command window at the bottom of the screen. This functionality can be turned on using the environment variable `FB_DISABLE_EXEC=false` or the flag `--disable-exec=false`.
|
||||
|
||||
By default no commands are available as the command list is empty. To enable commands these need to either be done on a per-user basis (including for the Admin user).
|
||||
|
||||
You can do this by adding them in Settings > User Management > (edit user) > Commands or to *apply to all new users created from that point forward* they can be set in Settings > Global Settings
|
||||
|
||||
> [!NOTE]
|
||||
>
|
||||
> If using a proxy manager then remember to enable websockets support for the File Browser proxy
|
||||
|
||||
> [!NOTE]
|
||||
>
|
||||
> If using Docker and you want to add a new command that is not in the base image then you will need to build a custom Docker image using `filebrowser/filebrowser` as a base image. For example to add 7z:
|
||||
>
|
||||
> ```docker
|
||||
> FROM filebrowser/filebrowser
|
||||
> RUN sudo apt install p7zip-full
|
||||
> ```
|
||||
Если нужна автоматическая обработка файлов, запускайте её отдельной службой ОС с самостоятельными разрешениями.
|
||||
@@ -1,45 +1,11 @@
|
||||
# Customization
|
||||
|
||||
You can customize the styles, branding and icons of your File Browser instance in order to give it a personal touch.
|
||||
The interface assets are embedded in the executable. The administrator can configure the instance name, default theme, external links and storage usage indicator in **Settings → Global Settings**.
|
||||
|
||||
## Custom Branding
|
||||
|
||||
You can customize File Browser to use your own branding. This includes the following:
|
||||
|
||||
- **Name**: the name of the instance that shows up on the tab title, login pages, and some other places.
|
||||
- **Disable External Links**: disables all external links, except to the documentation.
|
||||
- **Disable Used Percentage**: disables the disk usage information on the sidebar.
|
||||
- **Branding Folder**: directory which can contain two items:
|
||||
- `custom.css`, containing a global stylesheet to apply to all users.
|
||||
- `img`, a directory which can replace all the [default logotypes](https://github.com/filebrowser/filebrowser/tree/master/frontend/public/img) from the application.
|
||||
|
||||
This can be configured by the administrator user, under **Settings → Global Settings**. You can also update the configuration directly using the [CLI](cli/filebrowser-config-set.md):
|
||||
The same options are available through the CLI:
|
||||
|
||||
```sh
|
||||
filebrowser config set --branding.name "My Name" \
|
||||
--branding.files "/abs/path/to/my/dir" \
|
||||
--branding.disableExternal
|
||||
filebrowser config set --branding.name "My Files" --branding.theme dark
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
>
|
||||
> If you are using Docker, you need to mount a volume with the `branding` directory in order for it to be accessible from within the container.
|
||||
|
||||
### Custom Icons
|
||||
|
||||
To replace the default logotype and favicons, you need to create an `img` directory under the branding directory. The structure of this directory must mimic the one from the [default logotypes](https://github.com/filebrowser/filebrowser/tree/master/frontend/public/img):
|
||||
|
||||
```
|
||||
img/
|
||||
logo.svg
|
||||
icons/
|
||||
favicon.ico
|
||||
favicon.svg
|
||||
(...)
|
||||
```
|
||||
|
||||
Note that there are different versions of the same favicon in multiple sizes. To replace all of them, you need to add versions for all of them. You can use the [Real Favicon Generator](https://realfavicongenerator.net/) to generate these for you from your base image.
|
||||
|
||||
> [!NOTE]
|
||||
>
|
||||
> The icons are cached by the browser, so you may not see your changes immediately. You can address this by clearing your browser's cache.
|
||||
To change the built-in icons or styles, edit the frontend sources and rebuild the executable. Runtime branding directories and custom stylesheet overrides are no longer supported.
|
||||
@@ -1,46 +1,113 @@
|
||||
## Self-Registration (Signup)
|
||||
# File Browser SSO — Debian amd64
|
||||
|
||||
File Browser allows you to enable user self-registration (signup). This can be enabled via **Settings → Global Settings**, or with `filebrowser config set --signup`. Self-registered users inherit the configured **user defaults**, including the scope.
|
||||
Сборка для `linux/amd64`, базовый набор инструкций `GOAMD64=v1`, `CGO_ENABLED=0`.
|
||||
Node.js и Go на сервере не нужны: интерфейс встроен в исполняемый файл.
|
||||
|
||||
> [!WARNING]
|
||||
>
|
||||
> By default, the user scope is the server's root, so a self-registered user could read,
|
||||
> modify, and delete every file File Browser serves. To prevent this, either:
|
||||
>
|
||||
> a. Enable `createUserDir` so each user gets their own directory; or
|
||||
> b. If users are meant to share files, set the default scope to something other than the root.
|
||||
## Первоначальная настройка
|
||||
|
||||
## Fail2ban
|
||||
Распакуйте архив в `/opt/filebrowser`. Пример отдельного системного пользователя:
|
||||
|
||||
File Browser does not natively support protection against brute force attacks. Therefore, we suggest using something like [fail2ban](https://github.com/fail2ban/fail2ban), which takes care of that by tracking the logs of your File Browser instance. For more information on how fail2ban works, please refer to their [wiki](https://github.com/fail2ban/fail2ban/wiki).
|
||||
|
||||
### Filter Configuration
|
||||
|
||||
An example filter configuration targeted at matching File Browser's logs.
|
||||
|
||||
```ini
|
||||
[INCLUDES]
|
||||
before = common.conf
|
||||
|
||||
[Definition]
|
||||
datepattern = `^%%Y\/%%m\/%%d %%H:%%M:%%S`
|
||||
failregex = `\/api\/login: 403 <HOST> *`
|
||||
```sh
|
||||
sudo useradd --system --home /opt/filebrowser --shell /usr/sbin/nologin filebrowser
|
||||
sudo install -d -m 0750 -o filebrowser -g filebrowser /var/lib/filebrowser /srv/filebrowser
|
||||
sudo chmod 0755 /opt/filebrowser/filebrowser
|
||||
cd /var/lib/filebrowser
|
||||
sudo -u filebrowser /opt/filebrowser/filebrowser init
|
||||
```
|
||||
|
||||
### Jail Configuration
|
||||
Мастер запросит issuer SSO, Client ID, Client secret (без эха в терминале),
|
||||
публичный URL File Browser, папку файлов, путь базы, адрес и порт прослушивания.
|
||||
Для приведённого systemd-файла используйте `/srv/filebrowser` как папку файлов,
|
||||
`/var/lib/filebrowser/filebrowser.db` как базу и `127.0.0.1:8080` как адрес сервера.
|
||||
Публичный URL — внешний HTTPS-адрес, например `https://files.anidev.ru`.
|
||||
|
||||
An example jail configuration. You should fill it with the path of the logs of File Browser, as well as the port where it is running at.
|
||||
Конфигурация сохраняется в `.filebrowser.json` с правами `0600`. Настройка через
|
||||
`.env` не нужна. Мастер не перезаписывает существующую конфигурацию; для другого
|
||||
файла используйте `./filebrowser init --output /полный/путь/settings.json`.
|
||||
Запуск с нестандартной конфигурацией: `./filebrowser --config /полный/путь/settings.json`.
|
||||
|
||||
```ini
|
||||
[filebrowser]
|
||||
В вашем SSO зарегистрируйте приложение с PKCE S256 и callback, напечатанным мастером:
|
||||
|
||||
enabled = true
|
||||
port = [your_port]
|
||||
filter = filebrowser
|
||||
logpath = [your_log_path]
|
||||
maxretry = 10
|
||||
bantime = 10m
|
||||
findtime = 10m
|
||||
banaction = iptables-allports
|
||||
banaction_allports = iptables-allports
|
||||
```text
|
||||
https://files.anidev.ru/auth/callback
|
||||
```
|
||||
|
||||
Если приложение размещено в подпапке, например `https://example.com/files`,
|
||||
мастер сохранит `baseURL=/files`, а callback будет `/files/auth/callback`.
|
||||
|
||||
Нужны scopes `openid profile email`. Claim `roles` — массив строк;
|
||||
точные имена `Master Admin` и `FS Admin` дают права администратора.
|
||||
Остальные пользователи получают локальные файловые разрешения по умолчанию.
|
||||
Создавать пароли и пользователей File Browser не нужно: профиль создаётся при
|
||||
первом входе. Идентичность привязана к issuer и `sub`, а не к логину или почте.
|
||||
|
||||
## Сессии
|
||||
|
||||
В SSO выберите тип приложения **«Внутреннее»**. Используется общая браузерная сессия: каждый защищённый запрос проверяется через `/internal/session/resolve`, роли и текущий аккаунт обновляются без нового OAuth-обмена. Смена аккаунта и общий выход распространяются на открытые приложения; другие устройства независимы.
|
||||
|
||||
Конфигурация содержит точный `sso.redirectURI` (мастер заполняет его автоматически). Прежние конфигурации без этого поля используют callback, полученный из `sso.publicURL`. Все приложения установки должны использовать одинаковый issuer. Настройка cookie Domain не требуется; для SSO используйте HTTPS.
|
||||
|
||||
Для запуска без SSO и пароля: `./filebrowser --no-sso`. В этом режиме все посетители получают административный доступ к настроенному корню.
|
||||
|
||||
Подробности и миграция старых сессий: [авторизация](authentication.md).
|
||||
|
||||
## Запуск через systemd
|
||||
|
||||
```sh
|
||||
sudo install -m 0644 filebrowser.service /etc/systemd/system/filebrowser.service
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now filebrowser
|
||||
sudo journalctl -u filebrowser -f
|
||||
```
|
||||
|
||||
Перед приложением нужен reverse proxy с HTTPS. Пример nginx:
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 443 ssl;
|
||||
server_name files.anidev.ru;
|
||||
# Укажите свои ssl_certificate и ssl_certificate_key.
|
||||
client_max_body_size 0;
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8080;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_request_buffering off;
|
||||
proxy_read_timeout 3600s;
|
||||
proxy_send_timeout 3600s;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Исполняемые команды и хуки всегда выключены, внешние симлинки запрещены.
|
||||
Файлы, которые разрешено отдавать пользователям, держите в отдельном каталоге.
|
||||
При изменении пути файлов поправьте `ReadWritePaths` и `ProtectHome` в systemd-файле.
|
||||
|
||||
Публичные ссылки создаются как `/s/{key}`. Можно задать имя длиной 2–64 символа
|
||||
из латинских букв, цифр, `_` и `-`. Имена чувствительны к регистру. Занятое имя
|
||||
возвращает 409 и никогда не перезаписывает существующую ссылку. Без имени генерируется
|
||||
случайный ключ из 128 бит. Старые `/share/{key}` остаются доступными.
|
||||
|
||||
Понятные имена легче угадать; для приватных материалов используйте пароль ссылки и срок действия.
|
||||
|
||||
## Обновление и резервное копирование
|
||||
|
||||
Остановите службу, сохраните `.filebrowser.json`, базу и пользовательские файлы,
|
||||
замените бинарник и запустите службу. Перед миграцией старой установки особенно
|
||||
важно сохранить базу: при запуске удаляются пригодные для входа локальные пароли.
|
||||
Старые локальные пользователи автоматически не связываются с SSO по имени — это
|
||||
предотвращает захват аккаунта совпадающим логином. Их файловые области при необходимости
|
||||
назначьте новым SSO-профилям через настройки администратора.
|
||||
|
||||
## Сборка из исходников
|
||||
|
||||
Нужны Go 1.26+, Node.js 24+ и pnpm 10.33.4. Сборка использует системные шрифты,
|
||||
переводы и тяжёлые экраны загружаются по требованию. Для старых ПК используйте
|
||||
поддерживаемый браузер с JavaScript Proxy (Vue 3); Internet Explorer не поддерживается.
|
||||
|
||||
```sh
|
||||
sh scripts/build-release.sh
|
||||
```
|
||||
|
||||
На Windows: `./scripts/build-release.ps1`. Архив и SHA256 появятся в `build/`.
|
||||
@@ -0,0 +1,31 @@
|
||||
# DICOM 2D/3D в браузере
|
||||
|
||||
Для текущего интерфейса FS предпочтителен **Cornerstone3D**: библиотека для собственного просмотрщика на Vue, с отдельными Stack/Volume/Volume3D viewport, инструментами измерений, MPR и объёмным рендерингом. Загрузчик `@cornerstonejs/dicom-image-loader` умеет получать DICOM P10 через HTTP; отдельный PACS для такого варианта не обязателен. Лицензия MIT.
|
||||
|
||||
Источники: [область применения и загрузчики](https://www.cornerstonejs.org/docs/getting-started/scope/), [построение объёма](https://www.cornerstonejs.org/docs/tutorials/basic-volume/), [лицензия](https://github.com/cornerstonejs/cornerstone3D/blob/main/LICENSE).
|
||||
|
||||
**OHIF** — готовый просмотрщик с собственным интерфейсом и расширениями. Его можно раздавать как статические файлы и встраивать через iframe. Потребуется настроить источник данных. Помимо DICOMweb есть JSON-манифест с метаданными исследования/серий и URL отдельных DICOM-файлов. Лицензия MIT.
|
||||
|
||||
Источники: [развёртывание](https://docs.ohif.org/deployment/), [источник DICOM JSON](https://docs.ohif.org/configuration/datasources/dicom-json/), [лицензия](https://github.com/OHIF/Viewers/blob/master/LICENSE).
|
||||
|
||||
Для FS потребуется индексировать файлы выбранной папки по StudyInstanceUID и SeriesInstanceUID, учитывать ориентацию, положение и расстояние между срезами. Объём строится из согласованной серии срезов или подходящего многокадрового DICOM; из одиночной обычной 2D-проекции полноценный объём не получается. Доступ к файлам и метаданным должен наследовать текущие права пользователя либо публичной ссылки.
|
||||
|
||||
## Реализация в FS
|
||||
|
||||
В предпросмотр встроен лёгкий 2D-режим на Daikon и отдельный, лениво загружаемый объёмный просмотр на Cornerstone3D. Внешний PACS и отдельный сервер просмотрщика не нужны. Декодирование выполняется в существующем Web Worker; поддерживаются те же пиксельные форматы и кодеки, что и в 2D. Cornerstone получает готовые значения с применёнными rescale slope/intercept.
|
||||
|
||||
Если открыто имя вида `prefix_123.dcm` и все файлы родительской папки принадлежат этой нумерованной серии, появляется кнопка **Открыть как 3D**. Подпапки не учитываются. Имена определяют только предложение: после нажатия проверяются Study/Series/FrameOfReference UID, уникальность SOPInstanceUID, размеры, ориентация, PixelSpacing и ImagePositionPatient. Порядок определяется координатами пациента, а не именами. Дубликаты позиций, неравномерный шаг, несовпадающие серии и наклонённые относительно сетки срезы отклоняются. Обычные одиночные снимки и многокадровые файлы остаются в 2D; сборка объёма сейчас поддерживает серии однокадровых монохромных файлов с обычными верхнеуровневыми тегами геометрии.
|
||||
|
||||
Объёмный режим включает вращение и масштабирование 3D, аксиальную/сагиттальную/корональную реконструкцию, прокрутку срезов, перемещение, яркость/контрастность и непрозрачность. Нужен WebGL2. На неподходящем устройстве сохраняется 2D.
|
||||
|
||||
В настройках профиля есть раздел **DICOM — 3D-просмотр**: качество (автоматическое, исходное, половинное, четверть), лимит памяти вокселей 128–1536 МиБ и начальная непрозрачность. Настройки хранятся в аккаунте. По умолчанию автоматический режим подбирает разрешение под 1536 МиБ: большие срезы уменьшаются билинейной интерполяцией с сохранением поля обзора, координат пациента и физического масштаба; все срезы сохраняются. В просмотрщике показывается уменьшенное разрешение. Исходные DICOM-файлы не изменяются. При выборе исходного или фиксированного качества превышение персонального лимита по-прежнему останавливает просмотр.
|
||||
|
||||
Ограничения: до 2048 файлов, 64 МиБ на исходный файл, 1,5 ГиБ суммарной загрузки и 1,5 ГиБ Float32-вокселей. Это лимит массива объёма, а не всей памяти браузера: сборка и GPU требуют дополнительной памяти. Файлы читаются последовательно только после нажатия кнопки, загрузку можно отменить. При закрытии удаляются движок, GPU-ресурсы и принадлежащие просмотру записи кеша.
|
||||
|
||||
При запуске 3D в консоль браузера выводятся сообщения `[DICOM 3D]`: число файлов, общий и максимальный исходный размер, а после декодирования первого среза — размеры сетки и оценка Float32-объёма. При превышении лимита выводятся конкретная причина, фактическое значение и порог. Размеры указаны в байтах и ГиБ; пути, токены и медицинские теги не логируются.
|
||||
|
||||
Для приватных файлов используются обычные авторизованные API; для публичных — только API текущей ссылки с её токеном. Публичная ссылка на отдельный файл не запрашивает содержимое его родительской папки.
|
||||
|
||||
В сборщике `xmlbuilder2` направлен на официальный браузерный bundle: серверный entry зависимости VTK требует Node EventEmitter и не запускается в браузере. CSP страницы не ослабляется, сторонние CDN не используются.
|
||||
|
||||
Встроенные ресурсы включают служебные чанки Vite с начальным `__`; сервер отдаёт исходный JS, если gzip-копия не создана из-за малого размера. Go-тесты проверяют полноту встраивания и оба варианта отдачи. Дополнительная функциональная проверка: `DICOM_BROWSER_TEST=1 go test ./http -run TestProductionDICOMPreviewBrowser -v`. Нужны собранный frontend, Node 24, Playwright (путь можно задать в `PLAYWRIGHT_MODULE`) и браузер (`BROWSER_EXECUTABLE`). Проверка использует синтетические DICOM, настоящий встроенный сервер и CSP, без скриншотов и пользовательских данных.
|
||||
|
After Width: | Height: | Size: 37 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 43 KiB |
|
After Width: | Height: | Size: 41 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 99 KiB |
@@ -0,0 +1,22 @@
|
||||
# Навигация и миниатюры
|
||||
|
||||
Переходы выполняются внутри SPA: текущая папка остаётся на экране, пока сервер готовит следующую. Список и адрес обновляются вместе; шапка, поиск и дерево каталогов сохраняют свои компоненты. Для долгих запросов показывается тонкая полоса загрузки с задержкой 160 мс. Быстрый повторный переход отменяет предыдущий; запоздавшие ответы и ответы прежнего аккаунта не применяются. Крупные модули просмотра загружаются по необходимости до переключения страницы.
|
||||
|
||||
При смене аккаунта открывается его домашняя папка, в том числе после промежуточного выхода или OAuth-перехода. Обычный повторный вход в тот же аккаунт сохраняет прямую ссылку.
|
||||
|
||||
Боковая панель содержит закладки и раскрывающееся дерево каталогов. Текущий путь раскрывается автоматически; для остальных папок запрашивается только непосредственное содержимое при раскрытии. Обновления текущего каталога берутся из уже загруженного списка файлов. Скрытые каталоги учитывают настройку профиля. Права и область доступа проверяются существующим API.
|
||||
|
||||
Кнопка закладки закрепляет текущую папку. Закладки хранятся в браузере отдельно для каждого аккаунта и базового URL приложения. Крестик удаляет только закладку. Нижняя строка аккаунта открывает профиль, управление ссылками, административные разделы и выход в соответствии с правами пользователя. Меню поддерживает клавиатуру и закрывается по Escape или нажатию снаружи.
|
||||
|
||||
«Настройки профиля → Показ превью» сохраняется в базе пользователя и действует после повторного входа. По умолчанию показ включён, если миниатюры разрешены сервером. При отключении запросов миниатюр нет. Изображения загружаются по мере приближения к видимой области как в таблице, так и в плитках; ошибки миниатюр заменяются иконкой типа файла. DICOM отображается отдельной иконкой `.dcm`, без попытки генерации серверной миниатюры.
|
||||
|
||||
Настройки интерфейса находятся в разделе «Интерфейс»: внешний вид, работа с файлами, язык и даты. Кнопка «Управление» напротив профиля ведёт через `/auth/account` на `/settings` настроенного провайдера входа. Аватар берётся из проверенного `picture` при входе, преобразуется в небольшую PNG-миниатюру и хранится только в локальной сессии. Загружаются только изображения из `/avatars/` того же провайдера, без перенаправлений и передачи cookies или токенов. Если аватара нет, отображается первая буква имени.
|
||||
|
||||
Раздел ссылок называется «Мои ссылки» (My Shares). Уведомления отображаются справа под верхней панелью, учитывают тему и уменьшаются по ширине на мобильных устройствах. Ошибки остаются видимыми до закрытия; успешные действия закрываются автоматически.
|
||||
Меню действий открывается правой кнопкой на файле или на пустой области, а также кнопкой «Действия» в шапке. ПКМ на пустом месте снимает выделение и показывает действия с текущей папкой. Меню ограничено размерами экрана, прокручивается, поддерживает стрелки и Escape. Верхняя панель освобождена для поиска, доступного и на мобильных устройствах.
|
||||
|
||||
Скачивание начинается сразу. Для папок и нескольких файлов формат задаётся в «Глобальные настройки → Скачивание → Формат архива», по умолчанию ZIP. Настройка действует и на публичные ссылки; отдельный файл передаётся без упаковки. Старые URL с явным параметром algo продолжают работать.
|
||||
|
||||
Навигация настроек находится в меню аккаунта: «Аккаунт» ведёт на управление аккаунтом, «Настройки» — личные предпочтения, «Мои ссылки» — созданные ссылки, «Административные настройки» — серверные параметры (только для администратора). Вкладок больше нет. Плитка «Управление пользователями» открывает таблицу и редактирование доступа в одном модальном окне; старые адреса управления пользователями перенаправляются туда.
|
||||
|
||||
Подменю «Создать» содержит папку и шаблоны текстовых форматов. Расширение добавляется автоматически без дублирования; JSON, HTML и XML получают корректное начальное содержимое. Реестр frontend/src/utils/file-templates.ts предназначен для расширения типов при подключении редакторов. Office-документы пока не создаются, чтобы не выдавать пустой файл за корректный DOCX/XLSX.
|
||||
@@ -0,0 +1,21 @@
|
||||
# Предпросмотр файлов
|
||||
|
||||
PDF отображается локальным PDF.js в canvas, без плагинов браузера и внешних CDN. Страницы рисуются по одной; доступны переключение страницы и масштаб. CSP `object-src 'none'` сохраняется. Шрифты и таблицы символов входят в сборку.
|
||||
|
||||
В панели PDF есть кнопка открытия в новой вкладке: там документ отображает сам браузер. Общая кнопка «Открыть файл» удалена.
|
||||
|
||||
Обычные и публичные страницы поддерживают изображения, аудио и видео в форматах браузера, TIFF, текст, Markdown, CSV и EPUB. Текстовые форматы ограничены 5 МиБ, TIFF — 64 МиБ и 16 миллионами пикселей. HTML показывается текстом; Markdown очищается от активного содержимого. Если формат не поддерживается, остаются иконка и скачивание.
|
||||
|
||||
ZIP показывает только дерево имён из центрального каталога, без чтения содержимого записей, распаковки или открытия вложенных архивов. Используются частичные HTTP-запросы; ответ без поддержки Range отклоняется. Лимиты: 4 МиБ центрального каталога, 10 000 записей, 20 000 узлов с учётом папок, 32 уровня вложенности, 1024 байта на имя. Одновременно отображаются до 1000 строк. Проверяются границы записей и ответа сервера; пути с переходом к родителю отклоняются. ZIP64 и составные архивы не поддерживаются. Заявленный распакованный размер не используется для выделения памяти; ZIP-бомбы не распаковываются. Время загрузки ограничено 30 секундами.
|
||||
|
||||
Параметры DICOM подписаны «Контраст (ширина окна)» и «Яркость (уровень окна)». Это медицинское окно отображения интенсивности: его ширина задаёт диапазон, а уровень — центр диапазона; исходные пиксели не изменяются.
|
||||
|
||||
Файлы `.dcm` и `.dicom` открываются локальным DICOM-декодером в отдельном Worker. Поддерживаются 8/16-битные монохромные изображения (MONOCHROME1/2), 8-битный RGB и сжатые данные, поддерживаемые декодером Daikon. Доступны выбор кадра, ширина/уровень окна и сброс настроек. Неподдерживаемый формат сообщает об ошибке; файл остаётся доступен для скачивания.
|
||||
|
||||
Изображение DICOM целиком вписывается в доступную область под панелью инструментов с сохранением пропорций. Большие изображения уменьшаются, небольшие не увеличиваются.
|
||||
|
||||
Окно сведений показывает свойства файла и таблицу DICOM-тегов с поиском по коду, имени и значению: данные пациента, исследования, серии, оборудования и параметры изображения, если они присутствуют в файле. Чтение метаданных не требует распаковки пикселей и работает независимо от поддержки формата изображения. Бинарные данные и последовательности не выводятся; таблица ограничена 512 тегами, 64 значениями на тег и 2048 символами на значение. Метаданные обрабатываются локально, без внешних сервисов.
|
||||
|
||||
Для ограничения памяти DICOM-предпросмотр принимает файлы до 64 МиБ, изображения до 16 миллионов пикселей на кадр и до 128 МиБ распакованных пикселей. Первичное декодирование ограничено 30 секундами. Просмотр доступен в файловом менеджере и по публичным ссылкам с теми же проверками доступа, что и скачивание.
|
||||
|
||||
Текстовые теги декодируются из исходных байтов. Автоматический режим распознаёт корректный UTF-8 и учитывает объявленную кодировку; при неверной маркировке UTF-8 использует Windows-1256. Для неоднозначных файлов кодировку можно выбрать вручную, в том числе Windows-1251 и Windows-1256, без повторной загрузки файла. Тег Specific Character Set сохраняет исходное значение из файла, а поле «Используется» показывает фактическую кодировку отображения.
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
@@ -41,9 +42,9 @@ func TestScopedFs(t *testing.T) {
|
||||
if err := os.WriteFile(f, []byte("x"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fs := NewScopedFs(afero.NewOsFs(), "/")
|
||||
fs := NewScopedFs(afero.NewOsFs(), filepath.VolumeName(f)+string(filepath.Separator))
|
||||
|
||||
if _, err := fs.Stat(f); err != nil {
|
||||
if _, err := fs.Stat(strings.TrimPrefix(f, filepath.VolumeName(f))); err != nil {
|
||||
t.Fatalf("expected a path under root scope to be accessible, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -4,7 +4,9 @@ package frontend
|
||||
|
||||
import "embed"
|
||||
|
||||
//go:embed dist/*
|
||||
// Vite emits shared chunks beginning with underscores. The default recursive
|
||||
// embed walk excludes those files, breaking dynamic imports in release builds.
|
||||
//go:embed all:dist/*
|
||||
var assets embed.FS
|
||||
|
||||
func Assets() embed.FS {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build !dev
|
||||
|
||||
package frontend
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReleaseEmbedsEveryBuiltAsset(t *testing.T) {
|
||||
// Check the build output itself, including Vite's __vite-* chunks. Missing
|
||||
// optional gzip files are valid; missing originals in the binary are not.
|
||||
err := fs.WalkDir(os.DirFS("."), "dist", func(path string, entry fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if entry.IsDir() {
|
||||
return nil
|
||||
}
|
||||
if _, err := fs.Stat(Assets(), path); err != nil {
|
||||
t.Errorf("asset absent from release binary: %s: %v", path, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -1,37 +1,26 @@
|
||||
import pluginVue from "eslint-plugin-vue";
|
||||
import {
|
||||
defineConfigWithVueTs,
|
||||
vueTsConfigs,
|
||||
} from "@vue/eslint-config-typescript";
|
||||
import tseslint from "typescript-eslint";
|
||||
import prettierConfig from "@vue/eslint-config-prettier";
|
||||
|
||||
export default defineConfigWithVueTs(
|
||||
// No filesystem glob dependency: Vue and TypeScript parsers share flat configs.
|
||||
export default tseslint.config(
|
||||
{ ignores: ["**/dist/**", "**/dist-ssr/**", "**/coverage/**"] },
|
||||
...tseslint.configs.recommended,
|
||||
...pluginVue.configs["flat/essential"],
|
||||
{
|
||||
name: "app/files-to-lint",
|
||||
files: ["**/*.{ts,mts,tsx,vue}"],
|
||||
files: ["**/*.vue"],
|
||||
languageOptions: {
|
||||
parserOptions: { parser: tseslint.parser, extraFileExtensions: [".vue"] },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "app/files-to-ignore",
|
||||
ignores: ["**/dist/**", "**/dist-ssr/**", "**/coverage/**"],
|
||||
},
|
||||
pluginVue.configs["flat/essential"],
|
||||
vueTsConfigs.recommended,
|
||||
prettierConfig,
|
||||
{
|
||||
rules: {
|
||||
// Note: you must disable the base rule as it can report incorrect errors
|
||||
"@typescript-eslint/no-unused-expressions": "off",
|
||||
// TODO: theres too many of these from before ts
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
// TODO: finish the ts conversion
|
||||
"vue/block-lang": "off",
|
||||
"vue/multi-word-component-names": "off",
|
||||
"vue/no-mutating-props": [
|
||||
"error",
|
||||
{
|
||||
shallowOnly: true,
|
||||
},
|
||||
],
|
||||
"vue/no-mutating-props": ["error", { shallowOnly: true }],
|
||||
},
|
||||
}
|
||||
);
|
||||
@@ -10,8 +10,8 @@
|
||||
|
||||
<title>File Browser</title>
|
||||
|
||||
<link rel="icon" type="image/svg+xml" href="/img/icons/favicon.svg" />
|
||||
<link rel="shortcut icon" href="/img/icons/favicon.ico" />
|
||||
<link rel="icon" type="image/svg+xml" href="/img/icons/folder-open.svg" />
|
||||
<link rel="shortcut icon" href="/img/icons/folder-open.ico" />
|
||||
<link
|
||||
rel="apple-touch-icon"
|
||||
sizes="180x180"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "filebrowser-frontend",
|
||||
"version": "3.0.0",
|
||||
"version": "3.2.3",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"engines": {
|
||||
@@ -9,7 +9,7 @@
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
"build": "pnpm run typecheck && vite build",
|
||||
"build": "pnpm run typecheck && vite build && node scripts/check-dicom-worker.mjs",
|
||||
"clean": "find ./dist -maxdepth 1 -mindepth 1 ! -name '.gitkeep' -exec rm -r {} +",
|
||||
"typecheck": "vue-tsc -p ./tsconfig.app.json --noEmit",
|
||||
"lint": "eslint src/",
|
||||
@@ -19,60 +19,62 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@chenfengyuan/vue-number-input": "^2.0.1",
|
||||
"@vueuse/core": "^14.0.0",
|
||||
"@vueuse/integrations": "^14.0.0",
|
||||
"ace-builds": "^1.43.2",
|
||||
"csv-parse": "^6.1.0",
|
||||
"dayjs": "^1.11.13",
|
||||
"dompurify": "^3.2.6",
|
||||
"@cornerstonejs/core": "^5.13.1",
|
||||
"@vueuse/core": "^14.4.0",
|
||||
"@vueuse/integrations": "^14.4.0",
|
||||
"ace-builds": "^1.45.2",
|
||||
"csv-parse": "^6.2.1",
|
||||
"daikon": "^1.2.46",
|
||||
"dayjs": "^1.11.23",
|
||||
"dompurify": "^3.4.17",
|
||||
"epubjs": "^0.3.93",
|
||||
"filesize": "^11.0.13",
|
||||
"js-base64": "^3.7.7",
|
||||
"jwt-decode": "^4.0.0",
|
||||
"lodash-es": "^4.17.21",
|
||||
"marked": "^18.0.0",
|
||||
"marked-katex-extension": "^5.1.6",
|
||||
"material-icons": "^1.13.14",
|
||||
"filesize": "^11.0.27",
|
||||
"js-base64": "^3.9.4",
|
||||
"katex": "^0.18.10",
|
||||
"lodash-es": "^4.18.1",
|
||||
"marked": "^18.1.1",
|
||||
"marked-katex-extension": "^5.1.13",
|
||||
"normalize.css": "^8.0.1",
|
||||
"pdfjs-dist": "^6.4.299",
|
||||
"pinia": "^3.0.4",
|
||||
"pretty-bytes": "^7.1.0",
|
||||
"qrcode.vue": "^3.6.0",
|
||||
"pretty-bytes": "^7.2.0",
|
||||
"tus-js-client": "^4.3.1",
|
||||
"utif": "^3.1.0",
|
||||
"video.js": "^8.23.3",
|
||||
"videojs-hotkeys": "^0.2.28",
|
||||
"videojs-mobile-ui": "^1.1.1",
|
||||
"vue": "^3.5.17",
|
||||
"vue-i18n": "^11.1.10",
|
||||
"utif": "^3.2.0",
|
||||
"video.js": "^8.24.2",
|
||||
"videojs-hotkeys": "^0.2.30",
|
||||
"videojs-mobile-ui": "^1.2.7",
|
||||
"vue": "^3.5.44",
|
||||
"vue-i18n": "^11.4.16",
|
||||
"vue-lazyload": "^3.0.0",
|
||||
"vue-reader": "^1.2.17",
|
||||
"vue-router": "^5.0.0",
|
||||
"vue-toastification": "^2.0.0-rc.5"
|
||||
"vue-reader": "^1.3.9",
|
||||
"vue-router": "^5.4.0",
|
||||
"vue-toastification": "2.0.0-rc.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@intlify/unplugin-vue-i18n": "^11.0.1",
|
||||
"@tsconfig/node24": "^24.0.2",
|
||||
"@intlify/unplugin-vue-i18n": "^11.2.7",
|
||||
"@tsconfig/node24": "^24.0.5",
|
||||
"@types/lodash-es": "^4.17.12",
|
||||
"@types/node": "^24.10.1",
|
||||
"@typescript-eslint/eslint-plugin": "^8.37.0",
|
||||
"@vitejs/plugin-legacy": "^8.0.0",
|
||||
"@vitejs/plugin-vue": "^6.0.1",
|
||||
"@types/node": "^24.19.2",
|
||||
"@typescript-eslint/eslint-plugin": "^8.72.0",
|
||||
"@vitejs/plugin-legacy": "^8.2.3",
|
||||
"@vitejs/plugin-vue": "^6.0.10",
|
||||
"@vue/eslint-config-prettier": "^10.2.0",
|
||||
"@vue/eslint-config-typescript": "^14.6.0",
|
||||
"@vue/tsconfig": "^0.9.0",
|
||||
"autoprefixer": "^10.4.21",
|
||||
"eslint": "^10.0.0",
|
||||
"eslint-config-prettier": "^10.1.5",
|
||||
"eslint-plugin-prettier": "^5.5.1",
|
||||
"eslint-plugin-vue": "^10.5.1",
|
||||
"postcss": "^8.5.6",
|
||||
"prettier": "^3.6.2",
|
||||
"terser": "^5.43.1",
|
||||
"@vue/tsconfig": "^0.9.1",
|
||||
"autoprefixer": "^10.6.1",
|
||||
"eslint": "^10.13.0",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-plugin-prettier": "^5.5.7",
|
||||
"eslint-plugin-vue": "^10.11.1",
|
||||
"postcss": "^8.5.31",
|
||||
"prettier": "^3.9.10",
|
||||
"terser": "^5.51.2",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^8.0.0",
|
||||
"vite-plugin-compression2": "^2.3.1",
|
||||
"vitest": "^4.1.0",
|
||||
"vue-tsc": "^3.1.3"
|
||||
"typescript-eslint": "^8.72.0",
|
||||
"vite": "^8.3.5",
|
||||
"vite-plugin-compression2": "^2.5.3",
|
||||
"vitest": "^4.1.12",
|
||||
"vue-tsc": "^3.3.13",
|
||||
"xmlbuilder2": "4.0.3"
|
||||
},
|
||||
"packageManager": "pnpm@10.33.4+sha512.1c67b3b359b2d408119ba1ed289f34b8fc3c6873412bec6fd264fbdc82489e510fcbecb9ce9d22dae7f3b76269d8441046014bdca53b9979cd7a561ad631b800"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
overrides:
|
||||
'@xmldom/xmldom': ^0.8.15
|
||||
rollup: ^4.59.0
|
||||
esbuild@>=0.27.3 <0.28.1: ^0.28.1
|
||||
csv-parse: ^7.0.2
|
||||
katex: ^0.18.2
|
||||
|
Before Width: | Height: | Size: 9.1 KiB After Width: | Height: | Size: 3.3 KiB |
|
Before Width: | Height: | Size: 23 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 8.3 KiB After Width: | Height: | Size: 3.2 KiB |
|
Before Width: | Height: | Size: 15 KiB |
@@ -1,3 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="560" height="560" viewBox="0 0 560 560"><image width="560" height="560" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAjAAAAIwCAYAAACY8VFvAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAOxAAADsQBlSsOGwAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAACAASURBVHic7N13nJxVof/xz5nZlrJJSEJ6I9mUzQZIAaSLSLGASAkKioIi2FDBC4TAz7veK0nArlwLFmwXFcTrFQsgXgtNpEM2jZBAICHZnt1smd2Z5/z+mIAJabuzz8x5zjPf9+vFy5TdZ75ZN/N8c855zjGISNGqqbVlvb0cXJJhDAlGBgEjjGGENYwwlhEGRljLCBKUYxluocTAcKDMwBALQ4CyN1x2GJB8w69lgLY3/FrKQKeFDqDHwnYDaQzbsXRbaDWGVmtpNbDdWloTCVoJaE4nqS8tpaGu1vTk5ysjIlFnXAcQkfDV1NqyTDcTEobJWKZYmGQNEw2MxTAOOBjLOOAg11kHqBnDNqABy1YL24xls4FXMGwKLC8nK9iioiMSPyowIp6qudqOsyXMDAwzDFRhmQFMByYD49Df79dYYCuwCdgIrLeGF5IZ1hOwvu6LZqvbeCKSC73BiUTYostsaWoEVTZJTWCpxlBjYY6BKrLTNzJwOyy8YGANlrqEYbXJUFfeyvonbjW9rsOJyN6pwIhERPVSOx7LAgPzrWE+lrnALKDUdbYi1Qusw7DKWJ7G8JSFp1cvM6+6DiYiKjAiTtRca6eQ4ChrWBhkS8sCYKzrXNInWy08nTA8ZSxPEvDPupvMJtehRIqNCoxIntXU2qF0MT9IsgjLIuAEYJrjWBKurcDjxvBEYHiiNMODz60wLa5DicSZCoxIyOYttWODgBMDwwkG3gzUsOdjxRJvGQsrgb8n4e/G8MDKZWab61AicaICIzJAs663E0ssb7GWE7GciGG260wSPQbWYPg78EDa8Jd1N5rNrjOJ+EwFRqSfDvs3O6S3hGNIcAqWU4CF6O+S9JOBDRjuJ+D+bst9G24y211nEvGJ3nRFDsia2dezKJHh7RhOBY5GTwZJuHoxPILlT9byxzUreBKMdR1KJMpUYET2YtKVdlBlOcdZw5nAOQYmuc4kRaUBuMdY7s4E3LP2ZtPuOpBI1KjAiOy0cx+Wd1t4l4GTgArXmUSAbix/MfBbm+B/tQ+NSJYKjBS1mmvtlCDJ2VjOIFtaShxHEtmfAHjKGH5nE/z36i+Y510HEnFFBUaKTs0SW2UN51s4B1jkOo9IjizwhIW7Assd61aYDa4DiRSSCowUhTnX2VFYzk0YPmDhWPS9L/GzCstPSPATTTNJMdCbuMTW9Gvt8IoE51i4ADgZbSYnxSED/Nkafp4u49fra02b60Ai+aACI/FSaxM1XRxrk1xkLe9DJzZLcevGcLc1/HTNOv7AnSbjOpBIWFRgJBbmXW8nZzJcaAyXWZjuOo9IBG3G8LNkgu+t/IJ5wXUYkYFSgRFvVV1hy0sqOddYPkL2zCF9P4scmAX+Zi23pjv49fpvmpTrQCK50Bu+eKfqGjuprIRLA8vHDIxxnUfEY60WfhJYvq6nmMQ3KjDih8U2OXc6ZwQJPmrgNCDhOpJIjAQW7ksEfGfVBn6ntTLiAxUYibSqWjustIdLsHwGmOY6j0gR2GIM3zNlfKOu1jS7DiOyLyowEkk1S2xVxnCFgQ8BQ13nESlCO4zhdmP5et1ys8p1GJE3UoGRSKleak8l4EoMb0PfnyJREAD3YPnq6hXmftdhRF6jG4S4V2sTc3p5pwm4ATjKdRwR2TsLzxjDV8aWcftfa03adR4pbiow4kxNrS0LengvAUsxzHadR0T6bCOGr7d3cesrXzVdrsNIcVKBkYKbfY2tNAk+aQyfBsa6ziMiOdtm4Ws2w3+tvdm0uw4jxUUFRgqmptYODbr5BIZrgJGu84hIaJqN4ZtlZXzt6VrT6jqMFAcVGMm72dfYykSCj2O4FjjIdR4RyZt2DN8qCbjpuRWmxXUYiTcVGMmbnadBX2Xh08Bw13lEpGBareVr6Qq+qtOwJV9UYCR0NbW2LNPNxRj+U1v9ixS1Ziw3t6f4hhb7SthUYCQ0iy6zpR0jucQYPgdMdJ1HRCJjM4YvJsr4dl2t6XEdRuJBBUZCYM2cJbzXGP4DqHKdRkQiyvI88P9Wr+AOMNZ1HPGbCowMSPX19mgT8CULx7nOIiLeeJyAz66+yfzddRDxlwqM5KT6BjuTgBuxnIe+j0QkN79LWK6sW2HWuw4i/tGNR/qlptaODHq4Zufp0OWu84iI93qN4bYeyw3rl5sG12HEHyow0je1NlHdw/uBL2MZ7TqOiMROC4bPr36eW7jTZFyHkehTgZEDqr7WnmgTfMPA4a6ziEjsPW3gU6uWmwdcB5FoU4GRfapeasdjuQl4P/peEZHC+l0i4BN1N5lNroNINOmmJHtYdJkt7RzNZ7B8DhjqOo+IFK12A/8xppyv/bXWpF2HkWhRgZHdzFliFxnDd4FFrrOIiOz0rIWPrlluHnEdRKJDBUYAmF9rR3Sn+LyBTwBJ13lERN7AAj+zcOWa5abJdRhxTwVGmHO9PZOAbxmY5DqLiMgBbMVw7epl5ieug4hbKjBFrHqpHQ98G8tZrrOIiPSL5Y/JJJevvNG87DqKuJFwHUDcmLvELsayUuVFRLxkeHsm4Lk5S+xlYPWP8SKk/9OLzJwldpox3Aqc6jqLREcyASOHZP87uBKGD4bKChg2CCorbPbHO3+eTMCQcigvgfJSGFIGJbusmhr8hp8DpDPQ2bP7zzt6INULqTR0pCATQFsXtHVDeze0dxvaurI/bu2ExnZo7sj+lwkK83URb9xHgstW32hech1ECkcFpmhYU72Ej2G4CT0aXVTKSmDSQTBuOIwdDuOH29d/PHYYjBoCBw0B48m7gbXQ0gFNHbCtDbZth63b4dVWw9Y22NoKm1uhRw/dFpt24NrVy/mOTrouDp68ZclAzLreTkwG3IZGXWIrYWDiQTB7PEwZCZNHWqaMgimjssUlUWR/0wObLTWbmnb+12zY1ATrtsIrLdkSJLF1XybBh9bdaDa7DiL5VWRva8Vn7hK72Bq+DYxynUXCUVmRLSYzxsDcCZaaCTBnQnbqRg6sNwMvNULdFli1xfBCPazdCs07XCeTEG0Hrli93PzUdRDJHxWYmKqptSODFN8C3uM6i+Ru6iiYOxFmjbXMHg+zxsL4Ea5TxdOrrdkis24rrNtmWLUZXtJuI777eYnlE8+tMC2ug0j4VGBiqHqpPRXLj4AJrrNI35UmoWYizJ8CC6da5k+BUVqt5FTTDnjqJXhqk+Gpl7KjNmmdk+ybzVguXr3C3O86iIRLBSZGTqq1JfU93GAt/w89Ih95Q8rhsMmwYIpl4VRYMBUqSl2nkv1JZ7KjNE/uLDX/3JBdUCyRZy18M1nO1XW1pufAHy4+UIGJiVlL7PSk4efAUa6zyN4NKYejZ8BxVZYjDoHpB/vz5I/snbXwQj088SI8tN7wyPrdHxeXiLH8IyjhwrVfMBtdR5GB09tnDNRcZ88L4HuAVkdEzOSR8OY5cNJsy6Jp2UeaJb4yATyzCf62LltmVm3RE08R1GYsH1+1wvy36yAyMCowHltUawd3pLjFwCWus0jW0HI4pgqOm2k5YVb2EWYpXlu3wwPr4MHns4WmI+U6keziB+3dXPHKV02X6yCSGxUYT825zs4y8CvgUNdZit2kg+C0eXDCrOxaljfuQisC2fUzT7wED6wz3LcSNuu5GOcsPGOSLF79BfO86yzSfyowHqq+zr4buA1NGTkzdjicWgOn11gWTNVaFum/9dvg3pVw99OGl5tdpylq7cZw6apl5g7XQaR/9LbrkZNqbcm2Hr6A5Rr0/13BHTQkW1rOPFylRcJVtxl++3R2ZKa+zXWa4mQMt5oyrtBTSv7QW7Anqq6xk0oT3InhaNdZisnIoXD6PDh9XnYRbrFtyS+FFVh4fCPcu9JwX512By40Aw9lMpy/9mazxXUWOTC9HXug5lp7fJDgTmCc6yzFoDQJJ8+FcxdZjp6RPX1ZpNAyATzyAtz1uOEvq7NHIEhBvGoTnLfmRvOw6yCyfyowETdnib3MGL4J6KSbPJs6Cs5ZZDlnUXbkRSQq2rrgnufg9n8Ynt/mOk1R6LHwyTXLzfdcB5F9U4GJqJNqbcnWFF828CnXWeKsrATeUg2Lj8iOtmhdi0Rd3Wb41eOG3z4F3b2u08Sb1sVEm96uI6jmajvOlvArC8e5zhJXM8bAeUdYzloIwwe5TiPSf62d8NunsmXmhXrXaWLM8GASzlu5zGjsK2JUYCJm9lJ7WMJyNzDFdZa4SSayC3IvODq7X4tIXDz5Evz8H4Z7V2bXzkjoXrIBZ665yTznOoj8iwpMhNQssW8LDL8EhrnOEieDy+CcI+CDx1kmaOccibEtrfDLfxp++Si0d7tOEzs7EvC+uuXmt66DSJYKTERUL7WfxvJlQPu4hmR0JZx/pOX9x2qaSIpLRwp+/QT86EHD1u2u08RKBsv1q1eYm1wHERUY506qtSXbUnwN+ITrLHExexy8903Z9S3lOjxRilg6A39eBT980LDyFddpYsTw/cGNfPyJW42WUTukAuNQVa0dVpriLuAU11l8ZwwcWwUXH285tsp1GpFosRYeXp8dkXl4ves08WDg3kyGxWtvNu2usxQrFRhHZl9jJySS/B6Y7zqL794yBz7xVkv1BNdJRKJv1Ra45X7D39a6ThILTybSvLPui2ar6yDFSAXGgXnX2Line truncated
|
||||
@media (prefers-color-scheme: dark) { :root { filter: none; } }
|
||||
</style></svg>
|
||||
|
Before Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 20 KiB |
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" fill="none">
|
||||
<rect width="36" height="36" rx="9" fill="#273650"/>
|
||||
<svg x="7" y="7" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#88a7ff" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M3 10V5h7l2 2h9v3 M3 10h19l-3 10H3z"/>
|
||||
</svg>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 355 B |
@@ -21,9 +21,9 @@
|
||||
<link
|
||||
rel="icon"
|
||||
type="image/svg+xml"
|
||||
href="[{[ .StaticURL ]}]/img/icons/favicon.svg"
|
||||
href="[{[ .StaticURL ]}]/img/icons/folder-open.svg"
|
||||
/>
|
||||
<link rel="shortcut icon" href="[{[ .StaticURL ]}]/img/icons/favicon.ico" />
|
||||
<link rel="shortcut icon" href="[{[ .StaticURL ]}]/img/icons/folder-open.ico" />
|
||||
<link
|
||||
rel="apple-touch-icon"
|
||||
sizes="180x180"
|
||||
@@ -167,9 +167,5 @@
|
||||
</div>
|
||||
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
|
||||
[{[ if .CSS -]}]
|
||||
<link rel="stylesheet" href="[{[ .StaticURL ]}]/custom.css" />
|
||||
[{[ end ]}]
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,151 @@
|
||||
// Run by the optional Go browser regression. Every API response is synthetic;
|
||||
// HTML, CSP and static assets come from the real embedded Go server.
|
||||
const path = require("node:path"),
|
||||
http = require("node:http");
|
||||
const { pathToFileURL } = require("node:url");
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
(async () => {
|
||||
const { fixture } = await import(
|
||||
pathToFileURL(
|
||||
path.join(__dirname, "../src/utils/__tests__/fixtures/dicom.ts")
|
||||
)
|
||||
);
|
||||
const item = (i) => ({
|
||||
name: `scan_${i}.dcm`,
|
||||
path: `/series/scan_${i}.dcm`,
|
||||
extension: ".dcm",
|
||||
type: "blob",
|
||||
isDir: false,
|
||||
size: 500,
|
||||
modified: "2026-10-22T00:00:00Z",
|
||||
mode: 420,
|
||||
});
|
||||
const listing = {
|
||||
name: "series",
|
||||
path: "/series/",
|
||||
isDir: true,
|
||||
type: "dir",
|
||||
items: [item(0), item(1), item(2)],
|
||||
sorting: { by: "name", asc: true },
|
||||
numFiles: 3,
|
||||
numDirs: 0,
|
||||
};
|
||||
const perm = {
|
||||
admin: true,
|
||||
create: true,
|
||||
rename: true,
|
||||
modify: true,
|
||||
delete: true,
|
||||
share: true,
|
||||
download: true,
|
||||
};
|
||||
const user = {
|
||||
id: 1,
|
||||
username: "smoke",
|
||||
locale: "en",
|
||||
perm,
|
||||
scope: "/",
|
||||
viewMode: "list",
|
||||
sorting: { by: "name", asc: true },
|
||||
rules: [],
|
||||
commands: [],
|
||||
theme: "dark",
|
||||
showPreview: true,
|
||||
};
|
||||
const server = http.createServer((req, res) => {
|
||||
const u = new URL(req.url, "http://localhost");
|
||||
const json = (data) => {
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify(data));
|
||||
};
|
||||
if (u.pathname === "/api/session") return json(user);
|
||||
if (u.pathname === "/api/users/1" && req.method === "PUT") {
|
||||
let body = "";
|
||||
req.on("data", (chunk) => {
|
||||
body += chunk;
|
||||
});
|
||||
req.on("end", () => {
|
||||
const update = JSON.parse(body);
|
||||
if (!update.which.includes("dicom3D")) {
|
||||
res.writeHead(400);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
Object.assign(user, update.data);
|
||||
json({});
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (u.pathname === "/api/addons") return json([]);
|
||||
if (u.pathname.startsWith("/api/resources"))
|
||||
return json(
|
||||
/scan_(\d+)\.dcm$/.test(u.pathname)
|
||||
? item(Number(u.pathname.match(/scan_(\d+)/)[1]))
|
||||
: listing
|
||||
);
|
||||
if (u.pathname.startsWith("/api/usage"))
|
||||
return json({ used: 0, total: 1000 });
|
||||
if (u.pathname.startsWith("/api/raw")) {
|
||||
res.setHeader("Content-Type", "application/dicom");
|
||||
return res.end(
|
||||
Buffer.from(
|
||||
fixture(16, {
|
||||
slice: Number(u.pathname.match(/scan_(\d+)/)?.[1] || 0),
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
res.writeHead(404);
|
||||
res.end();
|
||||
});
|
||||
await new Promise((r) => server.listen(0, "127.0.0.1", r));
|
||||
const browser = await chromium.launch({
|
||||
executablePath: process.env.BROWSER_EXECUTABLE,
|
||||
headless: true,
|
||||
args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"],
|
||||
});
|
||||
try {
|
||||
const page = await browser.newPage(),
|
||||
errors = [];
|
||||
page.on("pageerror", (e) => errors.push(String(e)));
|
||||
page.on("response", (r) => {
|
||||
if (r.status() >= 400 && new URL(r.url()).pathname.startsWith("/static/"))
|
||||
errors.push(`HTTP ${r.status()}: ${r.url()}`);
|
||||
});
|
||||
const base = process.env.FILEBROWSER_PREVIEW_URL;
|
||||
if (!base) throw new Error("FILEBROWSER_PREVIEW_URL is required");
|
||||
await page.route(base + "/api/**", async (route) => {
|
||||
const response = await route.fetch({
|
||||
url:
|
||||
"http://127.0.0.1:" +
|
||||
server.address().port +
|
||||
new URL(route.request().url()).pathname,
|
||||
});
|
||||
await route.fulfill({ response });
|
||||
});
|
||||
await page.goto(base + "/settings/profile");
|
||||
if (await page.getByLabel("3D preview quality").count())
|
||||
throw new Error("Disabled 3D settings are still visible");
|
||||
await page.goto(base + "/files/series/scan_1.dcm");
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
document.querySelector(".dicom-viewer .document-stage canvas")
|
||||
?.width === 2,
|
||||
null,
|
||||
{ timeout: 20000 }
|
||||
);
|
||||
if (
|
||||
(await page.locator(".dicom-volume-stage").count()) ||
|
||||
(await page.getByRole("button", { name: /Open as 3D/ }).count())
|
||||
)
|
||||
throw new Error("3D must remain disabled");
|
||||
if (errors.length) throw new Error(errors.join("\n"));
|
||||
console.log("DICOM preview: 2D passed; 3D is disabled");
|
||||
} finally {
|
||||
await browser.close();
|
||||
server.close();
|
||||
}
|
||||
})().catch((e) => {
|
||||
console.error(e);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import vm from "node:vm";
|
||||
import { fixture } from "../src/utils/__tests__/fixtures/dicom.ts";
|
||||
|
||||
// Exercise the shipped bundle without Node's require or module globals.
|
||||
// Source-module tests alone miss broken CommonJS imports in browser workers.
|
||||
const assets = path.resolve(import.meta.dirname, "../dist/assets");
|
||||
const name = fs
|
||||
.readdirSync(assets)
|
||||
.find((n) => /^dicom\.worker-.*\.js$/.test(n));
|
||||
assert.ok(name, "Production DICOM worker is missing");
|
||||
const replies = [];
|
||||
const self = { postMessage: (data) => replies.push(data) };
|
||||
vm.runInNewContext(fs.readFileSync(path.join(assets, name), "utf8"), {
|
||||
self,
|
||||
console,
|
||||
TextEncoder,
|
||||
TextDecoder,
|
||||
ArrayBuffer,
|
||||
DataView,
|
||||
Uint8Array,
|
||||
Uint8ClampedArray,
|
||||
Uint16Array,
|
||||
Int16Array,
|
||||
Int32Array,
|
||||
Uint32Array,
|
||||
Float32Array,
|
||||
Float64Array,
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
});
|
||||
self.onmessage({ data: { id: 1, buffer: fixture() } });
|
||||
assert.equal(replies[0]?.error, undefined);
|
||||
assert.equal(replies[0]?.frames, 2);
|
||||
assert.equal(replies[0]?.cols, 2);
|
||||
assert.equal(replies[0]?.rows, 2);
|
||||
assert.equal(replies[0]?.rgba[0], 0);
|
||||
assert.equal(replies[0]?.rgba[12], 255);
|
||||
self.onmessage({ data: { id: 2, frame: 1 } });
|
||||
assert.equal(replies[1]?.error, undefined);
|
||||
assert.equal(replies[1]?.rgba[0], 255);
|
||||
self.onmessage({ data: { id: 3, mode: "metadata", buffer: fixture(32) } });
|
||||
assert.equal(replies[2]?.error, undefined);
|
||||
assert.ok(
|
||||
replies[2]?.metadata.some(
|
||||
(entry) => entry.tag === "(0010,0010)" && entry.value === "Example Patient"
|
||||
)
|
||||
);
|
||||
assert.ok(!replies[2]?.metadata.some((entry) => entry.tag === "(7FE0,0010)"));
|
||||
self.onmessage({
|
||||
data: {
|
||||
id: 4,
|
||||
mode: "metadata",
|
||||
buffer: fixture(16, {
|
||||
charset: "ISO_IR 192",
|
||||
patientBytes: [0xe3, 0xcd, 0xe3, 0xcf],
|
||||
}),
|
||||
},
|
||||
});
|
||||
assert.equal(replies[3]?.encoding, "windows-1256");
|
||||
assert.ok(replies[3]?.metadata.some((entry) => entry.value === "محمد"));
|
||||
self.onmessage({
|
||||
data: {
|
||||
id: 5,
|
||||
mode: "metadata",
|
||||
buffer: fixture(16, {
|
||||
charset: "WINDOWS-1256",
|
||||
patientBytes: Array.from(new TextEncoder().encode("Иван^Петров")),
|
||||
}),
|
||||
},
|
||||
});
|
||||
assert.equal(replies[4]?.encoding, "utf-8");
|
||||
assert.ok(replies[4]?.metadata.some((entry) => entry.value === "Иван Петров"));
|
||||
self.onmessage({
|
||||
data: { id: 6, mode: "volumeSlice", buffer: fixture(16, { slice: 2 }) },
|
||||
});
|
||||
assert.equal(replies[5]?.error, undefined);
|
||||
assert.deepEqual(Array.from(replies[5].slice.position), [0, 0, 2]);
|
||||
assert.deepEqual(Array.from(replies[5].slice.orientation), [1, 0, 0, 0, 1, 0]);
|
||||
assert.equal(replies[5].slice.pixels[0], -2048);
|
||||
console.log(
|
||||
"Production DICOM worker: decode, metadata, text encodings and volume slices passed"
|
||||
);
|
||||
@@ -0,0 +1,229 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE);
|
||||
(async () => {
|
||||
const browser = await chromium.launch({
|
||||
executablePath: process.env.BROWSER_EXECUTABLE,
|
||||
headless: true,
|
||||
args: ["--host-resolver-rules=MAP *.localhost 127.0.0.1"],
|
||||
});
|
||||
const output = process.env.FILEBROWSER_QA_OUTPUT;
|
||||
fs.mkdirSync(output, { recursive: true });
|
||||
const errors = [];
|
||||
const contexts = [];
|
||||
const change = async (values) => {
|
||||
const response = await contexts[0].request.post(
|
||||
process.env.QA_ISSUER + "/__qa/change",
|
||||
{
|
||||
headers: { "X-QA-Control": process.env.QA_CONTROL },
|
||||
data: {
|
||||
Name: "Alice",
|
||||
Version: "A-1",
|
||||
Status: "authenticated",
|
||||
Denied: false,
|
||||
Offline: false,
|
||||
...values,
|
||||
},
|
||||
}
|
||||
);
|
||||
assert.equal(response.status(), 204);
|
||||
};
|
||||
try {
|
||||
const context = await browser.newContext({
|
||||
ignoreHTTPSErrors: true,
|
||||
viewport: { width: 1300, height: 900 },
|
||||
locale: "en-US",
|
||||
});
|
||||
contexts.push(context);
|
||||
await context.route("**/internal/session/frame?**", (route) =>
|
||||
route.abort()
|
||||
);
|
||||
const cookies = (device) =>
|
||||
[
|
||||
["one", process.env.QA_APP_ONE],
|
||||
["two", process.env.QA_APP_TWO],
|
||||
].map(([id, url]) => ({
|
||||
name: "__Host-internal_session",
|
||||
value: id + "-" + device + "-binding-123456789",
|
||||
url,
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: "Lax",
|
||||
}));
|
||||
await context.addCookies(cookies("device-one"));
|
||||
const a = await context.newPage(),
|
||||
b = await context.newPage();
|
||||
for (const p of [a, b]) p.on("pageerror", (e) => errors.push(String(e)));
|
||||
await Promise.all([
|
||||
a.goto(process.env.QA_APP_ONE + "/files/"),
|
||||
b.goto(process.env.QA_APP_TWO + "/files/"),
|
||||
]);
|
||||
try {
|
||||
await Promise.all([
|
||||
a.getByText("Alice-private.txt", { exact: true }).waitFor(),
|
||||
b.getByText("Alice-private.txt", { exact: true }).waitFor(),
|
||||
]);
|
||||
} catch (error) {
|
||||
console.log("INITIAL ERRORS", errors);
|
||||
for (const [index, page] of [a, b].entries()) {
|
||||
console.log("BODY", index, await page.locator("body").innerText());
|
||||
console.log(
|
||||
"SESSION",
|
||||
await (
|
||||
await context.request.get(
|
||||
(index === 0 ? process.env.QA_APP_ONE : process.env.QA_APP_TWO) +
|
||||
"/auth/session"
|
||||
)
|
||||
).text()
|
||||
);
|
||||
await page.screenshot({
|
||||
path: path.join(output, `initial-${index}.png`),
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const device2 = await browser.newContext({ ignoreHTTPSErrors: true });
|
||||
contexts.push(device2);
|
||||
await device2.addCookies(cookies("device-two"));
|
||||
const independent = await device2.newPage();
|
||||
await independent.goto(process.env.QA_APP_ONE + "/files/");
|
||||
await independent.getByText("Alice-private.txt", { exact: true }).waitFor();
|
||||
// The destination account has no such directory: switch must go home first.
|
||||
await b
|
||||
.locator("#listing")
|
||||
.getByRole("button", { name: "Alice-only", exact: true })
|
||||
.dblclick();
|
||||
await b.getByText("nested-Alice.txt", { exact: true }).waitFor();
|
||||
// Hold a valid A response until after both applications have switched to B.
|
||||
let release;
|
||||
const held = new Promise((r) => (release = r));
|
||||
let ready;
|
||||
const captured = new Promise((r) => (ready = r));
|
||||
let didHold = false;
|
||||
await a.route("**/api/resources/", async (route) => {
|
||||
if (didHold) {
|
||||
await route.continue();
|
||||
return;
|
||||
}
|
||||
didHold = true;
|
||||
const response = await route.fetch();
|
||||
ready();
|
||||
await held;
|
||||
await route.fulfill({ response }).catch(() => {});
|
||||
});
|
||||
await a.getByRole("button", { name: "Actions", exact: true }).click();
|
||||
await a.getByRole("menuitem", { name: "Refresh", exact: true }).click();
|
||||
await captured;
|
||||
await change({ Name: "Bob", Version: "B-1" });
|
||||
await Promise.all([
|
||||
a
|
||||
.getByText("Bob-private.txt", { exact: true })
|
||||
.waitFor({ timeout: 15000 }),
|
||||
b
|
||||
.getByText("Bob-private.txt", { exact: true })
|
||||
.waitFor({ timeout: 15000 }),
|
||||
]);
|
||||
release();
|
||||
assert.equal(new URL(a.url()).pathname, "/files/");
|
||||
assert.equal(new URL(b.url()).pathname, "/files/");
|
||||
|
||||
await a.unroute("**/api/resources/");
|
||||
await a.waitForTimeout(200);
|
||||
assert.equal(
|
||||
await a.getByText("Alice-private.txt", { exact: true }).count(),
|
||||
0
|
||||
);
|
||||
assert.equal(
|
||||
await b.getByText("Alice-private.txt", { exact: true }).count(),
|
||||
0
|
||||
);
|
||||
assert(
|
||||
await independent
|
||||
.getByText("Alice-private.txt", { exact: true })
|
||||
.isVisible()
|
||||
);
|
||||
assert(!new URL(a.url()).pathname.startsWith("/auth/"));
|
||||
assert(!new URL(b.url()).pathname.startsWith("/auth/"));
|
||||
await a.screenshot({ path: path.join(output, "account-B.png") });
|
||||
const stale = await context.request.post(
|
||||
process.env.QA_APP_ONE + "/api/resources/stale.txt",
|
||||
{
|
||||
headers: { "X-FB-Request": "1", "X-FB-Session-State": "A-1" },
|
||||
data: "must not write",
|
||||
}
|
||||
);
|
||||
assert.equal(stale.status(), 409);
|
||||
await change({ Name: "Bob", Version: "B-1", Denied: true });
|
||||
await b
|
||||
.getByRole("heading", { name: "Access denied", exact: true })
|
||||
.waitFor({ timeout: 15000 });
|
||||
assert.equal(
|
||||
await b.getByText("Alice-private.txt", { exact: true }).count(),
|
||||
0
|
||||
);
|
||||
assert.equal(
|
||||
await b.getByText("Bob-private.txt", { exact: true }).count(),
|
||||
0
|
||||
);
|
||||
await change({ Name: "Bob", Version: "B-1", Offline: true });
|
||||
await a
|
||||
.getByRole("heading", {
|
||||
name: "Sign-in service unavailable",
|
||||
exact: true,
|
||||
})
|
||||
.waitFor({ timeout: 15000 });
|
||||
assert.equal(
|
||||
await a.getByText("Bob-private.txt", { exact: true }).count(),
|
||||
0
|
||||
);
|
||||
assert(
|
||||
(await context.cookies(process.env.QA_APP_ONE)).some(
|
||||
(c) => c.name === "__Host-internal_session"
|
||||
)
|
||||
);
|
||||
await change({ Name: "Bob", Version: "B-2" });
|
||||
await a
|
||||
.getByText("Bob-private.txt", { exact: true })
|
||||
.waitFor({ timeout: 15000 });
|
||||
const logout = await context.request.post(
|
||||
process.env.QA_APP_ONE + "/auth/logout",
|
||||
{ headers: { "X-FB-Request": "1", "X-FB-Session-State": "B-2" } }
|
||||
);
|
||||
assert.equal(logout.status(), 204);
|
||||
await b
|
||||
.getByRole("heading", { name: "Signed out", exact: true })
|
||||
.waitFor({ timeout: 15000 });
|
||||
assert(
|
||||
await independent
|
||||
.getByText("Alice-private.txt", { exact: true })
|
||||
.isVisible()
|
||||
);
|
||||
await change({ Status: "factor_required", Version: "factor" });
|
||||
await b
|
||||
.getByRole("heading", { name: "Verify your sign-in", exact: true })
|
||||
.waitFor({ timeout: 15000 });
|
||||
assert(!new URL(b.url()).pathname.startsWith("/auth/"));
|
||||
const cookiesAtEnd = await context.cookies(process.env.QA_APP_TWO);
|
||||
const binding = cookiesAtEnd.find(
|
||||
(c) => c.name === "__Host-internal_session"
|
||||
);
|
||||
assert(
|
||||
binding &&
|
||||
binding.secure &&
|
||||
binding.httpOnly &&
|
||||
binding.path === "/" &&
|
||||
!binding.domain.startsWith(".")
|
||||
);
|
||||
assert.equal(errors.length, 0, errors.join("\n"));
|
||||
console.log(
|
||||
"Two apps: A→B, stale form, denied access, outage/recovery, shared logout, missing factor and independent device passed."
|
||||
);
|
||||
} finally {
|
||||
for (const c of contexts) await c.close();
|
||||
await browser.close();
|
||||
}
|
||||
})().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,243 @@
|
||||
const fs = require("node:fs"),
|
||||
path = require("node:path"),
|
||||
assert = require("node:assert/strict"),
|
||||
{ spawn } = require("node:child_process");
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE);
|
||||
(async () => {
|
||||
const root = fs.mkdtempSync(
|
||||
path.join(process.env.FILEBROWSER_QA_OUTPUT, "navigation-")
|
||||
);
|
||||
const files = path.join(root, "files");
|
||||
fs.mkdirSync(files);
|
||||
fs.writeFileSync(path.join(files, "anonymous.txt"), "NO PASSWORD");
|
||||
for (const folder of ["Fast", "Slow", "Empty"])
|
||||
fs.mkdirSync(path.join(files, folder));
|
||||
fs.writeFileSync(path.join(files, "Fast", "fast.txt"), "FAST");
|
||||
fs.writeFileSync(path.join(files, "Slow", "slow.txt"), "SLOW");
|
||||
fs.mkdirSync(path.join(files, "Fast", "Nested"));
|
||||
fs.writeFileSync(path.join(files, "Fast", "Nested", "nested.txt"), "NESTED");
|
||||
const config = path.join(root, "config.json"),
|
||||
db = path.join(root, "test.db");
|
||||
fs.writeFileSync(
|
||||
config,
|
||||
JSON.stringify({
|
||||
root: files,
|
||||
database: db,
|
||||
sso: { issuer: "invalid-provider-configuration" },
|
||||
})
|
||||
);
|
||||
const args = [
|
||||
"--config",
|
||||
config,
|
||||
"--root",
|
||||
files,
|
||||
"--database",
|
||||
db,
|
||||
"--port",
|
||||
"0",
|
||||
];
|
||||
const processOne = spawn(process.env.FILEBROWSER_EXE, [...args, "--no-sso"], {
|
||||
cwd: root,
|
||||
windowsHide: true,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
let logs = "",
|
||||
browser;
|
||||
const started = new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(
|
||||
() => reject(Error("startup timeout " + logs)),
|
||||
12000
|
||||
);
|
||||
const read = (chunk) => {
|
||||
logs += chunk.toString();
|
||||
const found = logs.match(/Listening on (127\.0\.0\.1:\d+)/);
|
||||
if (found) {
|
||||
clearTimeout(timeout);
|
||||
resolve("http://" + found[1]);
|
||||
}
|
||||
};
|
||||
processOne.stdout.on("data", read);
|
||||
processOne.stderr.on("data", read);
|
||||
processOne.once("exit", (code) => {
|
||||
clearTimeout(timeout);
|
||||
reject(Error("exited " + code + " " + logs));
|
||||
});
|
||||
});
|
||||
try {
|
||||
const url = await started;
|
||||
browser = await chromium.launch({
|
||||
executablePath: process.env.BROWSER_EXECUTABLE,
|
||||
headless: true,
|
||||
});
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
const errors = [];
|
||||
page.on("pageerror", (error) => errors.push(String(error)));
|
||||
const response = await context.request.get(url + "/api/session");
|
||||
assert.equal(response.status(), 200);
|
||||
const user = await response.json();
|
||||
assert.equal(user.authMode, "no-sso");
|
||||
assert.equal(user.perm.admin, true);
|
||||
await page.goto(url + "/files/");
|
||||
await page.getByText("anonymous.txt", { exact: true }).waitFor();
|
||||
assert.equal(await page.locator("iframe").count(), 0);
|
||||
assert.equal(await page.locator('a[href$="/auth/account"]').count(), 0);
|
||||
// Sample every rendered frame and observe removals: a single missing frame fails.
|
||||
await page.evaluate(() => {
|
||||
window.navNodes = [
|
||||
document.querySelector("#listing"),
|
||||
document.querySelector("header"),
|
||||
document.querySelector(".workspace-sidebar"),
|
||||
];
|
||||
window.navRemoved = [];
|
||||
window.navBlankFrames = 0;
|
||||
window.navObserver = new MutationObserver((changes) => {
|
||||
for (const change of changes)
|
||||
for (const removed of change.removedNodes)
|
||||
for (let i = 0; i < window.navNodes.length; i++)
|
||||
if (
|
||||
removed === window.navNodes[i] ||
|
||||
removed.contains?.(window.navNodes[i])
|
||||
)
|
||||
window.navRemoved.push(i);
|
||||
});
|
||||
window.navObserver.observe(document.body, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
});
|
||||
window.navSampling = true;
|
||||
function frame() {
|
||||
if (!window.navSampling) return;
|
||||
if (
|
||||
!document.querySelector("#listing") ||
|
||||
!document.querySelector("header")
|
||||
)
|
||||
window.navBlankFrames++;
|
||||
requestAnimationFrame(frame);
|
||||
}
|
||||
requestAnimationFrame(frame);
|
||||
});
|
||||
let releaseSlow;
|
||||
const slowGate = new Promise((resolve) => (releaseSlow = resolve));
|
||||
await page.route("**/api/resources/Slow/", async (route) => {
|
||||
await slowGate;
|
||||
try {
|
||||
await route.continue();
|
||||
} catch {
|
||||
/* superseded request was aborted */
|
||||
}
|
||||
});
|
||||
const slowRequest = page
|
||||
.waitForRequest((r) => r.url().endsWith("/api/resources/Slow/"))
|
||||
.catch(() => null);
|
||||
await page
|
||||
.locator("#listing")
|
||||
.getByRole("button", { name: "Slow", exact: true })
|
||||
.dblclick();
|
||||
await slowRequest;
|
||||
await page.waitForTimeout(250);
|
||||
assert.equal(new URL(page.url()).pathname, "/files/");
|
||||
await page.getByText("anonymous.txt", { exact: true }).waitFor();
|
||||
assert(await page.locator(".navigation-progress").isVisible());
|
||||
await page
|
||||
.locator("#listing")
|
||||
.getByRole("button", { name: "Fast", exact: true })
|
||||
.dblclick();
|
||||
await page.waitForURL("**/files/Fast/");
|
||||
await page.getByText("fast.txt", { exact: true }).waitFor();
|
||||
releaseSlow();
|
||||
await page.waitForTimeout(150);
|
||||
assert.equal(new URL(page.url()).pathname, "/files/Fast/");
|
||||
assert.equal(await page.getByText("slow.txt", { exact: true }).count(), 0);
|
||||
await page
|
||||
.locator("#listing")
|
||||
.getByRole("button", { name: "Nested", exact: true })
|
||||
.dblclick();
|
||||
await page.waitForURL("**/files/Fast/Nested/");
|
||||
await page.getByText("nested.txt", { exact: true }).waitFor();
|
||||
await page.goBack();
|
||||
await page.waitForURL("**/files/Fast/");
|
||||
await page.getByText("fast.txt", { exact: true }).waitFor();
|
||||
const stability = await page.evaluate(() => {
|
||||
window.navSampling = false;
|
||||
window.navObserver.disconnect();
|
||||
return {
|
||||
removed: window.navRemoved,
|
||||
blankFrames: window.navBlankFrames,
|
||||
sameNodes: window.navNodes.map((node) => document.contains(node)),
|
||||
};
|
||||
});
|
||||
assert.deepEqual(stability.removed, []);
|
||||
assert.equal(stability.blankFrames, 0);
|
||||
assert(stability.sameNodes.every(Boolean));
|
||||
assert.equal(await page.locator(".navigation-progress").count(), 0);
|
||||
await page.locator(".account-button").click();
|
||||
await page.locator('a[href="/settings/profile"]').click();
|
||||
await page.waitForURL("**/settings/profile");
|
||||
await page.locator(".settings-page").waitFor();
|
||||
assert(await page.evaluate(() => document.contains(window.navNodes[2])));
|
||||
await page.goBack();
|
||||
await page.waitForURL("**/files/Fast/");
|
||||
await page.getByText("fast.txt", { exact: true }).waitFor();
|
||||
// The same workspace works on a phone, including an empty directory and back.
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.goBack();
|
||||
await page.waitForURL("**/files/");
|
||||
await page
|
||||
.locator("#listing")
|
||||
.getByRole("button", { name: "Empty", exact: true })
|
||||
.dblclick();
|
||||
await page.waitForURL("**/files/Empty/");
|
||||
await page.locator(".message").waitFor();
|
||||
assert(
|
||||
await page.evaluate(
|
||||
() => document.documentElement.scrollWidth <= innerWidth
|
||||
)
|
||||
);
|
||||
await page.goBack();
|
||||
await page.waitForURL("**/files/");
|
||||
await page.getByText("anonymous.txt", { exact: true }).waitFor();
|
||||
// Preview entry and return are client-side transitions too.
|
||||
await page
|
||||
.getByRole("button", { name: "anonymous.txt", exact: true })
|
||||
.dblclick();
|
||||
await page.waitForURL("**/files/anonymous.txt");
|
||||
await page.locator("#previewer").waitFor();
|
||||
await page.goBack();
|
||||
await page.waitForURL("**/files/");
|
||||
await page.getByText("anonymous.txt", { exact: true }).waitFor();
|
||||
assert.equal(
|
||||
await page.evaluate(
|
||||
() => performance.getEntriesByType("navigation").length
|
||||
),
|
||||
1
|
||||
);
|
||||
assert.deepEqual(errors, []);
|
||||
await page.screenshot({ path: path.join(root, "mobile-navigation.png") });
|
||||
console.log(
|
||||
"Atomic SPA navigation: persistent listing/header/sidebar; zero blank frames; slow and superseded requests; nested/back/empty/mobile/preview passed."
|
||||
);
|
||||
} catch (error) {
|
||||
if (browser) {
|
||||
for (const ctx of browser.contexts())
|
||||
for (const tab of ctx.pages()) {
|
||||
fs.writeFileSync(
|
||||
path.join(root, "failure.html"),
|
||||
await tab.content()
|
||||
);
|
||||
await tab.screenshot({ path: path.join(root, "failure.png") });
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
if (browser) await browser.close();
|
||||
if (processOne.exitCode === null) {
|
||||
processOne.kill();
|
||||
await new Promise((r) => processOne.once("exit", r));
|
||||
}
|
||||
fs.writeFileSync(path.join(root, "server.log"), logs);
|
||||
}
|
||||
})().catch((e) => {
|
||||
console.error(e);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
const fs = require("node:fs"),
|
||||
path = require("node:path"),
|
||||
assert = require("node:assert/strict"),
|
||||
{ spawn } = require("node:child_process");
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE);
|
||||
(async () => {
|
||||
const root = fs.mkdtempSync(
|
||||
path.join(process.env.FILEBROWSER_QA_OUTPUT, "no-sso-")
|
||||
);
|
||||
const files = path.join(root, "files");
|
||||
fs.mkdirSync(files);
|
||||
fs.writeFileSync(path.join(files, "anonymous.txt"), "NO PASSWORD");
|
||||
const config = path.join(root, "config.json"),
|
||||
db = path.join(root, "test.db");
|
||||
fs.writeFileSync(
|
||||
config,
|
||||
JSON.stringify({
|
||||
root: files,
|
||||
database: db,
|
||||
sso: { issuer: "invalid-provider-configuration" },
|
||||
})
|
||||
);
|
||||
const args = [
|
||||
"--config",
|
||||
config,
|
||||
"--root",
|
||||
files,
|
||||
"--database",
|
||||
db,
|
||||
"--port",
|
||||
"0",
|
||||
];
|
||||
const processOne = spawn(process.env.FILEBROWSER_EXE, [...args, "--no-sso"], {
|
||||
cwd: root,
|
||||
windowsHide: true,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
let logs = "",
|
||||
browser;
|
||||
const started = new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(
|
||||
() => reject(Error("startup timeout " + logs)),
|
||||
12000
|
||||
);
|
||||
const read = (chunk) => {
|
||||
logs += chunk.toString();
|
||||
const found = logs.match(/Listening on (127\.0\.0\.1:\d+)/);
|
||||
if (found) {
|
||||
clearTimeout(timeout);
|
||||
resolve("http://" + found[1]);
|
||||
}
|
||||
};
|
||||
processOne.stdout.on("data", read);
|
||||
processOne.stderr.on("data", read);
|
||||
processOne.once("exit", (code) => {
|
||||
clearTimeout(timeout);
|
||||
reject(Error("exited " + code + " " + logs));
|
||||
});
|
||||
});
|
||||
try {
|
||||
const url = await started;
|
||||
browser = await chromium.launch({
|
||||
executablePath: process.env.BROWSER_EXECUTABLE,
|
||||
headless: true,
|
||||
});
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
const response = await context.request.get(url + "/api/session");
|
||||
assert.equal(response.status(), 200);
|
||||
const user = await response.json();
|
||||
assert.equal(user.authMode, "no-sso");
|
||||
assert.equal(user.perm.admin, true);
|
||||
await page.goto(url + "/files/");
|
||||
await page.getByText("anonymous.txt", { exact: true }).waitFor();
|
||||
assert.equal(await page.locator("iframe").count(), 0);
|
||||
assert.equal(await page.locator('a[href$="/auth/account"]').count(), 0);
|
||||
const write = await context.request.post(
|
||||
url + "/api/resources/created.txt",
|
||||
{ headers: { "X-FB-Request": "1" }, data: "CREATED WITHOUT PASSWORD" }
|
||||
);
|
||||
assert.equal(write.status(), 200);
|
||||
assert.equal(
|
||||
fs.readFileSync(path.join(files, "created.txt"), "utf8"),
|
||||
"CREATED WITHOUT PASSWORD"
|
||||
);
|
||||
await page.screenshot({ path: path.join(root, "anonymous-workspace.png") });
|
||||
} finally {
|
||||
if (browser) await browser.close();
|
||||
if (processOne.exitCode === null) {
|
||||
processOne.kill();
|
||||
await new Promise((r) => processOne.once("exit", r));
|
||||
}
|
||||
fs.writeFileSync(path.join(root, "server.log"), logs);
|
||||
}
|
||||
const normal = spawn(process.env.FILEBROWSER_EXE, args, {
|
||||
cwd: root,
|
||||
windowsHide: true,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
let normalLogs = "";
|
||||
normal.stdout.on("data", (d) => (normalLogs += d));
|
||||
normal.stderr.on("data", (d) => (normalLogs += d));
|
||||
const code = await new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
normal.kill();
|
||||
reject(Error("SSO mode unexpectedly started"));
|
||||
}, 12000);
|
||||
normal.once("exit", (code) => {
|
||||
clearTimeout(timer);
|
||||
resolve(code);
|
||||
});
|
||||
});
|
||||
assert.notEqual(code, 0);
|
||||
assert(!normalLogs.includes("Listening on"));
|
||||
console.log(
|
||||
"CLI --no-sso: no provider, cookie or password; reads/writes and administrator UI passed. Without flag, invalid SSO cannot start."
|
||||
);
|
||||
})().catch((e) => {
|
||||
console.error(e);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,156 @@
|
||||
const fs = require("node:fs"),
|
||||
path = require("node:path"),
|
||||
{ pathToFileURL } = require("node:url");
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE);
|
||||
(async () => {
|
||||
const base = process.env.FILEBROWSER_QA_URL,
|
||||
root = process.env.FILEBROWSER_QA_ROOT,
|
||||
out = process.env.FILEBROWSER_QA_OUTPUT;
|
||||
fs.mkdirSync(out, { recursive: true });
|
||||
const { fixture } = await import(
|
||||
pathToFileURL(
|
||||
path.resolve(__dirname, "../src/utils/__tests__/fixtures/dicom.ts")
|
||||
)
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(root, "scan_1.dcm"),
|
||||
Buffer.from(fixture(16, { slice: 0 }))
|
||||
);
|
||||
const browser = await chromium.launch({
|
||||
executablePath: process.env.BROWSER_EXECUTABLE,
|
||||
headless: true,
|
||||
args: [
|
||||
"--use-angle=swiftshader",
|
||||
"--enable-unsafe-swiftshader",
|
||||
"--autoplay-policy=no-user-gesture-required",
|
||||
],
|
||||
});
|
||||
const results = [];
|
||||
try {
|
||||
for (const mobile of [false, true]) {
|
||||
const context = await browser.newContext({
|
||||
viewport: mobile
|
||||
? { width: 390, height: 844 }
|
||||
: { width: 1440, height: 1000 },
|
||||
isMobile: mobile,
|
||||
hasTouch: mobile,
|
||||
acceptDownloads: true,
|
||||
});
|
||||
const page = await context.newPage();
|
||||
let errors = [];
|
||||
page.on("pageerror", (e) => errors.push(String(e)));
|
||||
page.on("response", (r) => {
|
||||
if (
|
||||
r.status() >= 400 &&
|
||||
new URL(r.url()).pathname.startsWith("/static/")
|
||||
)
|
||||
errors.push(`${r.status()} ${r.url()}`);
|
||||
});
|
||||
await page.goto(base + "/files/");
|
||||
await page.waitForTimeout(1200);
|
||||
await page.screenshot({
|
||||
path: path.join(out, `${mobile ? "mobile" : "desktop"}-listing.png`),
|
||||
fullPage: true,
|
||||
});
|
||||
for (const name of [
|
||||
"image.png",
|
||||
"image.jpg",
|
||||
"image.gif",
|
||||
"image.bmp",
|
||||
"image.tiff",
|
||||
"image.webp",
|
||||
"image.svg",
|
||||
"notes.txt",
|
||||
"report.md",
|
||||
"table.csv",
|
||||
"data.json",
|
||||
"config.xml",
|
||||
"index.html",
|
||||
"script.js",
|
||||
"document.pdf",
|
||||
"archive.zip",
|
||||
"book.epub",
|
||||
"sound.wav",
|
||||
"scan_1.dcm",
|
||||
"unsupported.bin",
|
||||
]) {
|
||||
errors = [];
|
||||
await page.goto(base + "/files/" + encodeURIComponent(name));
|
||||
await page.waitForTimeout(name.endsWith(".epub") ? 1800 : 800);
|
||||
if (/^image\./.test(name)) {
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
[...document.querySelectorAll("#previewer img")].some(
|
||||
(i) => i.naturalWidth > 0
|
||||
),
|
||||
null,
|
||||
{ timeout: 15000 }
|
||||
);
|
||||
}
|
||||
const state = await page.evaluate(() => ({
|
||||
overflow: document.documentElement.scrollWidth > innerWidth + 1,
|
||||
text: document.body.innerText.slice(-500),
|
||||
canvas: [...document.querySelectorAll("canvas")].map((c) => [
|
||||
c.width,
|
||||
c.height,
|
||||
]),
|
||||
images: [...document.querySelectorAll("#previewer img")].map((i) => [
|
||||
i.naturalWidth,
|
||||
i.naturalHeight,
|
||||
]),
|
||||
}));
|
||||
const label =
|
||||
(mobile ? "mobile" : "desktop") + "-" + name.replaceAll(".", "-");
|
||||
await page.screenshot({
|
||||
path: path.join(out, label + ".png"),
|
||||
fullPage: true,
|
||||
});
|
||||
results.push({ mobile, name, ...state, errors: [...errors] });
|
||||
fs.writeFileSync(
|
||||
path.join(out, "results.json"),
|
||||
JSON.stringify(results, null, 2)
|
||||
);
|
||||
}
|
||||
for (const route of [
|
||||
"/settings/profile",
|
||||
"/settings/shares",
|
||||
"/settings/global",
|
||||
]) {
|
||||
errors = [];
|
||||
await page.goto(base + route);
|
||||
await page.waitForTimeout(800);
|
||||
await page.screenshot({
|
||||
path: path.join(
|
||||
out,
|
||||
(mobile ? "mobile" : "desktop") +
|
||||
route.replaceAll("/", "-") +
|
||||
".png"
|
||||
),
|
||||
fullPage: true,
|
||||
});
|
||||
results.push({
|
||||
mobile,
|
||||
route,
|
||||
overflow: await page.evaluate(
|
||||
() => document.documentElement.scrollWidth > innerWidth + 1
|
||||
),
|
||||
errors: [...errors],
|
||||
});
|
||||
}
|
||||
await context.close();
|
||||
}
|
||||
for (const r of results) {
|
||||
if (r.overflow || r.errors?.length) throw Error(JSON.stringify(r));
|
||||
}
|
||||
console.log("QA completed", results.length);
|
||||
fs.writeFileSync(
|
||||
path.join(out, "results.json"),
|
||||
JSON.stringify(results, null, 2)
|
||||
);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
})().catch((e) => {
|
||||
console.error(e);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,192 @@
|
||||
const fs = require("node:fs"),
|
||||
path = require("node:path"),
|
||||
assert = require("node:assert/strict");
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE);
|
||||
(async () => {
|
||||
const base = process.env.FILEBROWSER_QA_URL,
|
||||
root = process.env.FILEBROWSER_QA_ROOT,
|
||||
out = process.env.FILEBROWSER_QA_OUTPUT;
|
||||
fs.mkdirSync(out, { recursive: true });
|
||||
const b = await chromium.launch({
|
||||
executablePath: process.env.BROWSER_EXECUTABLE,
|
||||
headless: true,
|
||||
args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"],
|
||||
});
|
||||
const result = [];
|
||||
try {
|
||||
const p = await b.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
p.on("dialog", (d) => d.accept());
|
||||
const request = async (method, url, data) => {
|
||||
let r = await p.request.fetch(base + url, {
|
||||
method,
|
||||
data,
|
||||
headers: { "X-FB-Request": "1" },
|
||||
});
|
||||
assert(
|
||||
r.ok(),
|
||||
method + " " + url + ":" + r.status() + " " + (await r.text())
|
||||
);
|
||||
return r;
|
||||
};
|
||||
await request("POST", "/api/resources/projects/");
|
||||
await request("POST", "/api/resources/projects/test.txt", "Hello server");
|
||||
await request(
|
||||
"PATCH",
|
||||
"/api/resources/projects/test.txt?action=copy&destination=%2Fprojects%2Fcopy.txt"
|
||||
);
|
||||
await request(
|
||||
"PATCH",
|
||||
"/api/resources/projects/copy.txt?action=rename&destination=%2Frenamed.txt"
|
||||
);
|
||||
await request("PUT", "/api/resources/renamed.txt", "Updated file");
|
||||
assert.equal(
|
||||
await (await request("GET", "/api/raw/renamed.txt")).text(),
|
||||
"Updated file"
|
||||
);
|
||||
await request("DELETE", "/api/resources/renamed.txt");
|
||||
assert(!fs.existsSync(path.join(root, "renamed.txt")));
|
||||
result.push("create/upload/copy/move/update/download/delete");
|
||||
await request("POST", "/api/share/notes.txt", { key: "qa-main" });
|
||||
await request("POST", "/api/share/notes.txt", {
|
||||
key: "qa-protected",
|
||||
password: "test-password",
|
||||
expires: "1",
|
||||
unit: "hours",
|
||||
});
|
||||
let links = await (await request("GET", "/api/share/notes.txt")).json();
|
||||
assert.equal(links.length, 2);
|
||||
result.push("multiple shares, optional password and expiration");
|
||||
await p.goto(base + "/files/");
|
||||
let video = await p.evaluate(async () => {
|
||||
const c = document.createElement("canvas");
|
||||
c.width = 320;
|
||||
c.height = 180;
|
||||
let ctx = c.getContext("2d");
|
||||
ctx.fillStyle = "#21334d";
|
||||
ctx.fillRect(0, 0, 320, 180);
|
||||
ctx.fillStyle = "white";
|
||||
ctx.font = "22px sans-serif";
|
||||
ctx.fillText("Video preview", 70, 90);
|
||||
let rec = new MediaRecorder(c.captureStream(10), {
|
||||
mimeType: "video/webm",
|
||||
}),
|
||||
chunks = [];
|
||||
rec.ondataavailable = (e) => chunks.push(e.data);
|
||||
let done = new Promise(
|
||||
(resolve) =>
|
||||
(rec.onstop = async () =>
|
||||
resolve([...new Uint8Array(await new Blob(chunks).arrayBuffer())]))
|
||||
);
|
||||
rec.start();
|
||||
await new Promise((r) => setTimeout(r, 1200));
|
||||
rec.stop();
|
||||
return done;
|
||||
});
|
||||
fs.writeFileSync(path.join(root, "movie.webm"), Buffer.from(video));
|
||||
await p.route("**/api/tus/**", async (route) => {
|
||||
if (route.request().method() === "PATCH")
|
||||
await new Promise((r) => setTimeout(r, 1800));
|
||||
await route.continue().catch(() => {});
|
||||
});
|
||||
let payload = Buffer.alloc(3 * 1024 * 1024, 65);
|
||||
await p
|
||||
.locator("#upload-input")
|
||||
.setInputFiles({
|
||||
name: "upload-check.txt",
|
||||
mimeType: "text/plain",
|
||||
buffer: payload,
|
||||
});
|
||||
await p.locator(".upload-files").waitFor();
|
||||
await p.screenshot({ path: path.join(out, "desktop-upload.png") });
|
||||
await p.locator(".transfer-header button").first().click();
|
||||
await p.screenshot({ path: path.join(out, "desktop-upload-expanded.png") });
|
||||
await p
|
||||
.locator(".upload-files")
|
||||
.waitFor({ state: "hidden", timeout: 30000 });
|
||||
assert(
|
||||
fs.readFileSync(path.join(root, "upload-check.txt")).equals(payload)
|
||||
);
|
||||
result.push("UI chunked upload and transfer panel");
|
||||
await p
|
||||
.locator("#upload-input")
|
||||
.setInputFiles({
|
||||
name: "cancel-check.txt",
|
||||
mimeType: "text/plain",
|
||||
buffer: payload,
|
||||
});
|
||||
await p.locator(".upload-files").waitFor();
|
||||
await p.locator(".transfer-header button").last().click();
|
||||
await p.locator(".upload-files").waitFor({ state: "hidden" });
|
||||
await p.waitForTimeout(2300);
|
||||
assert(!fs.existsSync(path.join(root, "cancel-check.txt")));
|
||||
result.push("upload cancellation");
|
||||
await p.unroute("**/api/tus/**");
|
||||
for (let mobile of [false, true]) {
|
||||
await p.setViewportSize(
|
||||
mobile ? { width: 390, height: 844 } : { width: 1440, height: 1000 }
|
||||
);
|
||||
for (let route of [
|
||||
"/files/",
|
||||
"/files/movie.webm",
|
||||
"/settings/profile",
|
||||
"/settings/shares",
|
||||
"/settings/global",
|
||||
"/s/qa-main",
|
||||
"/s/qa-protected",
|
||||
]) {
|
||||
await p.goto(base + route);
|
||||
await p.waitForTimeout(650);
|
||||
assert.equal(
|
||||
await p.evaluate(
|
||||
() => document.documentElement.scrollWidth > innerWidth + 1
|
||||
),
|
||||
false,
|
||||
"overflow " + route
|
||||
);
|
||||
await p.screenshot({
|
||||
path: path.join(
|
||||
out,
|
||||
(mobile ? "mobile" : "desktop") +
|
||||
route.replaceAll("/", "-") +
|
||||
".png"
|
||||
),
|
||||
fullPage: true,
|
||||
});
|
||||
}
|
||||
await p.goto(base + "/settings/global");
|
||||
await p.locator(".admin-users-tile").click();
|
||||
await p.locator(".users-management").waitFor();
|
||||
await p.screenshot({
|
||||
path: path.join(out, (mobile ? "mobile" : "desktop") + "-users.png"),
|
||||
fullPage: true,
|
||||
});
|
||||
await p.keyboard.press("Escape");
|
||||
await p.goto(base + "/editor/wordcraft?path=%2Fdocument.docx");
|
||||
await p.waitForTimeout(5000);
|
||||
let f = p.frames().find((x) => x !== p.mainFrame());
|
||||
await f
|
||||
.locator("canvas")
|
||||
.click({ position: { x: Math.min(mobile ? 190 : 550, 550), y: 350 } });
|
||||
await p.keyboard.press("Control+o");
|
||||
await p.locator(".server-picker").waitFor();
|
||||
await p.locator(".server-picker li").first().waitFor();
|
||||
await p.screenshot({
|
||||
path: path.join(
|
||||
out,
|
||||
(mobile ? "mobile" : "desktop") + "-server-picker.png"
|
||||
),
|
||||
});
|
||||
await p.locator(".picker-header button").click();
|
||||
}
|
||||
console.log(JSON.stringify(result));
|
||||
fs.writeFileSync(
|
||||
path.join(out, "functional.json"),
|
||||
JSON.stringify(result, null, 2)
|
||||
);
|
||||
} finally {
|
||||
await b.close();
|
||||
}
|
||||
})().catch((e) => {
|
||||
console.error(e);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { Plugin } from "vite";
|
||||
|
||||
export function daikonCommonJS(): Plugin {
|
||||
return {
|
||||
name: "daikon-commonjs",
|
||||
enforce: "pre",
|
||||
transform(code, id) {
|
||||
if (!/\/daikon\/(src|lib)\/.*\.js$/.test(id.replaceAll("\\", "/")))
|
||||
return;
|
||||
// Daikon guards static CommonJS imports with a runtime require check.
|
||||
// Bundlers replace the calls, but leave the check false in browsers.
|
||||
return code.replace(/typeof require\s*!==\s*['"]undefined['"]/g, "true");
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,23 +1,84 @@
|
||||
<template>
|
||||
<div>
|
||||
<h1 class="sr-only">{{ name }}</h1>
|
||||
<router-view></router-view>
|
||||
<div
|
||||
v-if="auth.accountChanged && route.meta.requiresAuth && !blocked"
|
||||
class="message"
|
||||
role="status"
|
||||
>
|
||||
{{ $t("files.loading") }}
|
||||
</div>
|
||||
<SessionGate v-else-if="blocked" />
|
||||
<router-view v-else :key="auth.epoch"></router-view>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, watch } from "vue";
|
||||
import { ref, onMounted, onBeforeUnmount, computed, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { setHtmlLocale } from "./i18n";
|
||||
import { getMediaPreference, getTheme, setTheme } from "./utils/theme";
|
||||
import { name } from "./utils/constants";
|
||||
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { acceptSession, setSessionRecheck } from "@/utils/auth";
|
||||
import SessionGate from "@/components/SessionGate.vue";
|
||||
import "@/utils/internal-session.js";
|
||||
import { baseURL, noAuth } from "@/utils/constants";
|
||||
const auth = useAuthStore(),
|
||||
route = useRoute(),
|
||||
router = useRouter();
|
||||
watch(
|
||||
() => auth.accountChanged,
|
||||
(changed) => {
|
||||
if (changed && route.meta.requiresAuth)
|
||||
void router.replace({ path: "/files/", force: true });
|
||||
}
|
||||
);
|
||||
watch(
|
||||
() => auth.user?.perm.admin,
|
||||
(admin) => {
|
||||
if (admin === false && !auth.accountChanged && route.meta.requiresAdmin)
|
||||
void router.replace("/403");
|
||||
}
|
||||
);
|
||||
const blocked = computed(
|
||||
() =>
|
||||
!["Login", "Share"].includes(String(route.name)) &&
|
||||
auth.sessionStatus !== "authenticated"
|
||||
);
|
||||
let sync: { stop: () => void } | undefined;
|
||||
onBeforeUnmount(() => {
|
||||
sync?.stop();
|
||||
setSessionRecheck();
|
||||
});
|
||||
const { locale } = useI18n();
|
||||
|
||||
const userTheme = ref<UserTheme>(getTheme() || getMediaPreference());
|
||||
|
||||
onMounted(() => {
|
||||
setTheme(userTheme.value);
|
||||
onMounted(async () => {
|
||||
await router.isReady();
|
||||
if (
|
||||
!noAuth &&
|
||||
window.FileBrowser.SSOIssuer &&
|
||||
window.FileBrowser.SSOClientID
|
||||
) {
|
||||
const restart = () => {
|
||||
sync?.stop();
|
||||
sync = window.SSOInternalSession.start({
|
||||
issuer: window.FileBrowser.SSOIssuer,
|
||||
clientId: window.FileBrowser.SSOClientID,
|
||||
checkUrl: baseURL + "/auth/session",
|
||||
onChange: acceptSession,
|
||||
onUnavailable: () =>
|
||||
acceptSession({ status: "unavailable", authenticated: false }),
|
||||
});
|
||||
};
|
||||
restart();
|
||||
setSessionRecheck(restart);
|
||||
}
|
||||
setTheme(userTheme.value, false);
|
||||
setHtmlLocale(locale.value);
|
||||
// this might be null during HMR
|
||||
const loading = document.getElementById("loading");
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { sessionScope, sessionIsCurrent } from "@/utils/session-scope";
|
||||
import { useLayoutStore } from "@/stores/layout";
|
||||
import { baseURL } from "@/utils/constants";
|
||||
import { upload as postTus, useTus } from "./tus";
|
||||
import { createURL, fetchURL, removePrefix, StatusError } from "./utils";
|
||||
import { isEncodableResponse, makeRawResource } from "@/utils/encodings";
|
||||
const resourceUploads = new Set<XMLHttpRequest>();
|
||||
export function abortResourceUploads() {
|
||||
for (const request of resourceUploads) request.abort();
|
||||
}
|
||||
|
||||
export async function fetch(url: string, signal?: AbortSignal) {
|
||||
const encoding = isEncodableResponse(url);
|
||||
@@ -100,7 +104,7 @@ export function download(format: any, ...files: string[]) {
|
||||
url += `algo=${format}&`;
|
||||
}
|
||||
|
||||
window.open(url);
|
||||
window.location.assign(url);
|
||||
}
|
||||
|
||||
export async function post(
|
||||
@@ -109,6 +113,7 @@ export async function post(
|
||||
overwrite = false,
|
||||
onupload: any = () => {}
|
||||
) {
|
||||
const scope = sessionScope();
|
||||
// Use the pre-existing API if:
|
||||
const useResourcesApi =
|
||||
// a folder is being created
|
||||
@@ -118,6 +123,7 @@ export async function post(
|
||||
!["http:", "https:"].includes(window.location.protocol)) ||
|
||||
// Tus is disabled / not applicable
|
||||
!(await useTus(content));
|
||||
if (!sessionIsCurrent(scope.generation)) throw new Error("Upload aborted");
|
||||
return useResourcesApi
|
||||
? postResources(url, content, overwrite, onupload)
|
||||
: postTus(url, content, overwrite, onupload);
|
||||
@@ -139,21 +145,29 @@ async function postResources(
|
||||
bufferContent = await new Response(content).arrayBuffer();
|
||||
}
|
||||
|
||||
const authStore = useAuthStore();
|
||||
return new Promise((resolve, reject) => {
|
||||
const scope = sessionScope();
|
||||
const request = new XMLHttpRequest();
|
||||
resourceUploads.add(request);
|
||||
request.onloadend = () => resourceUploads.delete(request);
|
||||
request.onabort = () => reject(new Error("Upload aborted"));
|
||||
request.open(
|
||||
"POST",
|
||||
`${baseURL}/api/resources${url}?override=${overwrite}`,
|
||||
true
|
||||
);
|
||||
request.setRequestHeader("X-Auth", authStore.jwt);
|
||||
request.setRequestHeader("X-FB-Request", "1");
|
||||
request.setRequestHeader("X-FB-Session-State", scope.state);
|
||||
|
||||
if (typeof onupload === "function") {
|
||||
request.upload.onprogress = onupload;
|
||||
}
|
||||
|
||||
request.onload = () => {
|
||||
if (!sessionIsCurrent(scope.generation)) {
|
||||
reject(new Error("Upload aborted"));
|
||||
return;
|
||||
}
|
||||
if (request.status === 200) {
|
||||
resolve(request.responseText);
|
||||
} else if (request.status === 409) {
|
||||
@@ -220,6 +234,7 @@ export function getPreviewURL(file: ResourceItem, size: string) {
|
||||
const params = {
|
||||
inline: "true",
|
||||
key: Date.parse(file.modified),
|
||||
account: sessionScope().generation,
|
||||
};
|
||||
|
||||
return createURL("api/preview/" + size + file.path, params);
|
||||
|
||||
@@ -1,19 +1,24 @@
|
||||
import { fetchURL, removePrefix, createURL } from "./utils";
|
||||
import { baseURL } from "@/utils/constants";
|
||||
|
||||
export async function fetch(url: string, password: string = "") {
|
||||
export async function fetch(
|
||||
url: string,
|
||||
password: string = "",
|
||||
options: { signal?: AbortSignal; token?: string } = {}
|
||||
) {
|
||||
url = removePrefix(url);
|
||||
|
||||
const res = await fetchURL(
|
||||
`/api/public/share${url}`,
|
||||
`/api/public/share${url}${options.token ? `?token=${encodeURIComponent(options.token)}` : ""}`,
|
||||
{
|
||||
signal: options.signal,
|
||||
headers: { "X-SHARE-PASSWORD": encodeURIComponent(password) },
|
||||
},
|
||||
false
|
||||
);
|
||||
|
||||
const data = (await res.json()) as Resource;
|
||||
data.url = `/share${url}`;
|
||||
data.url = `/s${url}`;
|
||||
|
||||
if (data.isDir) {
|
||||
if (!data.url.endsWith("/")) data.url += "/";
|
||||
@@ -62,7 +67,7 @@ export function download(
|
||||
url += `token=${token}&`;
|
||||
}
|
||||
|
||||
window.open(url);
|
||||
window.location.assign(url);
|
||||
}
|
||||
|
||||
export function getDownloadURL(res: Resource, inline = false) {
|
||||
|
||||
@@ -19,7 +19,8 @@ export async function create(
|
||||
url: string,
|
||||
password = "",
|
||||
expires = "",
|
||||
unit = "hours"
|
||||
unit = "hours",
|
||||
key = ""
|
||||
) {
|
||||
url = removePrefix(url);
|
||||
url = `/api/share${url}`;
|
||||
@@ -27,8 +28,9 @@ export async function create(
|
||||
url += `?expires=${expires}&unit=${unit}`;
|
||||
}
|
||||
let body = "{}";
|
||||
if (password != "" || expires !== "" || unit !== "hours") {
|
||||
if (password != "" || expires !== "" || unit !== "hours" || key !== "") {
|
||||
body = JSON.stringify({
|
||||
key,
|
||||
password: password,
|
||||
expires: expires.toString(), // backend expects string not number
|
||||
unit: unit,
|
||||
@@ -41,5 +43,5 @@ export async function create(
|
||||
}
|
||||
|
||||
export function getShareURL(share: Share) {
|
||||
return createURL("share/" + share.hash, {});
|
||||
return createURL("s/" + share.hash, {});
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { sessionScope } from "@/utils/session-scope";
|
||||
import * as tus from "tus-js-client";
|
||||
import { baseURL, tusEndpoint, tusSettings, origin } from "@/utils/constants";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { removePrefix } from "@/api/utils";
|
||||
|
||||
const RETRY_BASE_DELAY = 1000;
|
||||
@@ -18,11 +18,10 @@ export async function upload(
|
||||
throw new Error("Tus.io settings are not defined");
|
||||
}
|
||||
|
||||
const scope = sessionScope();
|
||||
filePath = removePrefix(filePath);
|
||||
const resourcePath = `${tusEndpoint}${filePath}?override=${overwrite}`;
|
||||
|
||||
const authStore = useAuthStore();
|
||||
|
||||
// Exit early because of typescript, tus content can't be a string
|
||||
if (content === "") {
|
||||
return false;
|
||||
@@ -35,7 +34,8 @@ export async function upload(
|
||||
parallelUploads: 1,
|
||||
storeFingerprintForResuming: false,
|
||||
headers: {
|
||||
"X-Auth": authStore.jwt,
|
||||
"X-FB-Request": "1",
|
||||
"X-FB-Session-State": scope.state,
|
||||
},
|
||||
onShouldRetry: function (err) {
|
||||
const status = err.originalResponse
|
||||
@@ -43,7 +43,7 @@ export async function upload(
|
||||
: 0;
|
||||
|
||||
// Do not retry for file conflict.
|
||||
if (status === 409) {
|
||||
if ([409, 401, 403, 428, 503].includes(status)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -112,7 +112,9 @@ function isTusSupported() {
|
||||
export function abortAllUploads() {
|
||||
for (const filePath in CURRENT_UPLOAD_LIST) {
|
||||
if (CURRENT_UPLOAD_LIST[filePath]) {
|
||||
CURRENT_UPLOAD_LIST[filePath].abort(true);
|
||||
void CURRENT_UPLOAD_LIST[filePath].abort(true).catch(() => {
|
||||
/* A switched account cannot cancel the previous account's server transfer. */
|
||||
});
|
||||
CURRENT_UPLOAD_LIST[filePath].options!.onError!(
|
||||
new Error("Upload aborted")
|
||||
);
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { renew, logout } from "@/utils/auth";
|
||||
import {
|
||||
sessionScope,
|
||||
sessionIsCurrent,
|
||||
mergeSignals,
|
||||
} from "@/utils/session-scope";
|
||||
import { validateLogin, acceptSession } from "@/utils/auth";
|
||||
import { baseURL } from "@/utils/constants";
|
||||
import { encodePath } from "@/utils/url";
|
||||
|
||||
@@ -19,7 +23,7 @@ export async function fetchURL(
|
||||
opts: ApiOpts,
|
||||
auth = true
|
||||
): Promise<Response> {
|
||||
const authStore = useAuthStore();
|
||||
const scope = sessionScope();
|
||||
|
||||
opts = opts || {};
|
||||
opts.headers = opts.headers || {};
|
||||
@@ -29,10 +33,14 @@ export async function fetchURL(
|
||||
try {
|
||||
res = await fetch(`${baseURL}${url}`, {
|
||||
headers: {
|
||||
"X-Auth": authStore.jwt,
|
||||
"X-FB-Request": "1",
|
||||
"X-FB-Session-State": scope.state,
|
||||
...headers,
|
||||
},
|
||||
...rest,
|
||||
signal: opts.signal
|
||||
? mergeSignals(opts.signal, scope.signal)
|
||||
: scope.signal,
|
||||
});
|
||||
} catch (e) {
|
||||
// Check if the error is an intentional cancellation
|
||||
@@ -42,10 +50,19 @@ export async function fetchURL(
|
||||
throw new StatusError("000 No connection", 0);
|
||||
}
|
||||
|
||||
if (auth && res.headers.get("X-Renew-Token") === "true") {
|
||||
await renew(authStore.jwt);
|
||||
if (!sessionIsCurrent(scope.generation))
|
||||
throw new StatusError("Session changed", 409, true);
|
||||
for (const method of ["json", "text", "arrayBuffer", "blob"] as const) {
|
||||
const read = res[method].bind(res);
|
||||
Object.defineProperty(res, method, {
|
||||
value: async () => {
|
||||
const result = await read();
|
||||
if (!sessionIsCurrent(scope.generation))
|
||||
throw new StatusError("Session changed", 409, true);
|
||||
return result;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (res.status < 200 || res.status > 299) {
|
||||
const body = await res.text();
|
||||
const error = new StatusError(
|
||||
@@ -53,9 +70,26 @@ export async function fetchURL(
|
||||
res.status
|
||||
);
|
||||
|
||||
if (auth && res.status == 401) {
|
||||
logout();
|
||||
if (
|
||||
[401, 403, 409, 428, 503].includes(res.status) &&
|
||||
!url.startsWith("/api/public/")
|
||||
) {
|
||||
try {
|
||||
const state = JSON.parse(body);
|
||||
if (typeof state.status === "string")
|
||||
acceptSession({
|
||||
status:
|
||||
state.status === "session_changed" ? "checking" : state.status,
|
||||
authenticated: false,
|
||||
session_state: state.session_state,
|
||||
required_factors: state.required_factors,
|
||||
});
|
||||
} catch {
|
||||
/* Ordinary file permission errors do not change identity. */
|
||||
}
|
||||
void validateLogin();
|
||||
}
|
||||
void auth;
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
<template>
|
||||
<span class="account-avatar" aria-hidden="true">
|
||||
<img
|
||||
v-if="user?.picture && !failed"
|
||||
:src="user.picture"
|
||||
alt=""
|
||||
@error="failed = true"
|
||||
/>
|
||||
<template v-else>{{
|
||||
(user?.username || "?").slice(0, 1).toUpperCase()
|
||||
}}</template>
|
||||
</span>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from "vue";
|
||||
const props = defineProps<{
|
||||
user: { picture?: string; username?: string } | null;
|
||||
}>();
|
||||
const failed = ref(false);
|
||||
watch(
|
||||
() => props.user?.picture,
|
||||
() => (failed.value = false)
|
||||
);
|
||||
</script>
|
||||
@@ -0,0 +1,18 @@
|
||||
<template>
|
||||
<svg
|
||||
class="app-icon"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.65"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path :d="iconPath(name || 'file')" />
|
||||
</svg>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { iconPath } from "@/utils/icons";
|
||||
defineProps<{ name?: string | null }>();
|
||||
</script>
|
||||
@@ -6,13 +6,11 @@
|
||||
:aria-label="t('files.home')"
|
||||
:title="t('files.home')"
|
||||
>
|
||||
<i class="material-icons">home</i>
|
||||
<AppIcon name="home" />
|
||||
</component>
|
||||
|
||||
<span v-for="(link, index) in items" :key="index">
|
||||
<span class="chevron"
|
||||
><i class="material-icons">keyboard_arrow_right</i></span
|
||||
>
|
||||
<span class="chevron"><AppIcon name="keyboard_arrow_right" /></span>
|
||||
<component :is="element" :to="link.url">{{ link.name }}</component>
|
||||
</span>
|
||||
</div>
|
||||
@@ -20,6 +18,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { breadcrumbItems } from "@/utils/breadcrumbs";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRoute } from "vue-router";
|
||||
|
||||
@@ -32,44 +31,7 @@ const props = defineProps<{
|
||||
noLink?: boolean;
|
||||
}>();
|
||||
|
||||
const items = computed(() => {
|
||||
const relativePath = route.path.replace(props.base, "");
|
||||
const parts = relativePath.split("/");
|
||||
|
||||
if (parts[0] === "") {
|
||||
parts.shift();
|
||||
}
|
||||
|
||||
if (parts[parts.length - 1] === "") {
|
||||
parts.pop();
|
||||
}
|
||||
|
||||
const breadcrumbs: BreadCrumb[] = [];
|
||||
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
if (i === 0) {
|
||||
breadcrumbs.push({
|
||||
name: decodeURIComponent(parts[i]),
|
||||
url: props.base + "/" + parts[i] + "/",
|
||||
});
|
||||
} else {
|
||||
breadcrumbs.push({
|
||||
name: decodeURIComponent(parts[i]),
|
||||
url: breadcrumbs[i - 1].url + parts[i] + "/",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (breadcrumbs.length > 3) {
|
||||
while (breadcrumbs.length !== 4) {
|
||||
breadcrumbs.shift();
|
||||
}
|
||||
|
||||
breadcrumbs[0].name = "...";
|
||||
}
|
||||
|
||||
return breadcrumbs;
|
||||
});
|
||||
const items = computed(() => breadcrumbItems(route.path, props.base));
|
||||
|
||||
const element = computed(() => {
|
||||
if (props.noLink) {
|
||||
|
||||
@@ -1,47 +1,135 @@
|
||||
<template>
|
||||
<div
|
||||
class="context-menu"
|
||||
ref="contextMenu"
|
||||
v-show="show"
|
||||
:style="{
|
||||
top: `${props.pos.y}px`,
|
||||
left: `${left}px`,
|
||||
}"
|
||||
>
|
||||
<slot />
|
||||
</div>
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="show"
|
||||
ref="contextMenu"
|
||||
class="context-menu"
|
||||
role="menu"
|
||||
tabindex="-1"
|
||||
:style="{ top: top + 'px', left: left + 'px' }"
|
||||
@click="menuClick"
|
||||
@click.capture="schedulePosition"
|
||||
@contextmenu.prevent.stop
|
||||
@keydown="keyboard"
|
||||
>
|
||||
<slot />
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, computed, onUnmounted } from "vue";
|
||||
|
||||
import { ref, watch, nextTick, onBeforeUnmount, provide, useId } from "vue";
|
||||
import { contextMenuKey } from "@/utils/context-menu";
|
||||
const emit = defineEmits(["hide"]);
|
||||
const props = defineProps<{ show: boolean; pos: { x: number; y: number } }>();
|
||||
const contextMenu = ref<HTMLElement | null>(null);
|
||||
|
||||
const left = computed(() => {
|
||||
return Math.min(
|
||||
props.pos.x,
|
||||
window.innerWidth - (contextMenu.value?.clientWidth ?? 0)
|
||||
const contextMenu = ref<HTMLElement | null>(null),
|
||||
left = ref(0),
|
||||
top = ref(0);
|
||||
let previousFocus: HTMLElement | null = null;
|
||||
const hide = () => emit("hide");
|
||||
const menuId = useId();
|
||||
provide(contextMenuKey, { id: menuId, close: hide });
|
||||
function menuClick(event: MouseEvent) {
|
||||
if (
|
||||
event.target instanceof Element &&
|
||||
event.target.closest('button[aria-haspopup="menu"]')
|
||||
)
|
||||
return;
|
||||
hide();
|
||||
}
|
||||
function position() {
|
||||
if (!contextMenu.value) return;
|
||||
const rect = contextMenu.value.getBoundingClientRect();
|
||||
left.value = Math.max(
|
||||
8,
|
||||
Math.min(props.pos.x, window.innerWidth - rect.width - 8)
|
||||
);
|
||||
});
|
||||
|
||||
const hideContextMenu = () => {
|
||||
emit("hide");
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.show,
|
||||
(val) => {
|
||||
if (val) {
|
||||
document.addEventListener("click", hideContextMenu);
|
||||
} else {
|
||||
document.removeEventListener("click", hideContextMenu);
|
||||
}
|
||||
top.value = Math.max(
|
||||
8,
|
||||
Math.min(props.pos.y, window.innerHeight - rect.height - 8)
|
||||
);
|
||||
}
|
||||
async function schedulePosition() {
|
||||
await nextTick();
|
||||
position();
|
||||
}
|
||||
function outside(event: Event) {
|
||||
if (
|
||||
event.target instanceof Element &&
|
||||
event.target
|
||||
.closest("[data-context-owner]")
|
||||
?.getAttribute("data-context-owner") === menuId
|
||||
)
|
||||
return;
|
||||
if (
|
||||
event.target instanceof Node &&
|
||||
!contextMenu.value?.contains(event.target)
|
||||
)
|
||||
hide();
|
||||
}
|
||||
function keyboard(event: KeyboardEvent) {
|
||||
schedulePosition();
|
||||
const buttons = Array.from(
|
||||
contextMenu.value?.querySelectorAll<HTMLButtonElement>(
|
||||
"button:not(:disabled)"
|
||||
) || []
|
||||
);
|
||||
const index = buttons.indexOf(document.activeElement as HTMLButtonElement);
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
hide();
|
||||
previousFocus?.focus();
|
||||
} else if (event.key === "Tab") hide();
|
||||
else if (
|
||||
["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key) &&
|
||||
buttons.length
|
||||
) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const next =
|
||||
event.key === "Home"
|
||||
? 0
|
||||
: event.key === "End"
|
||||
? buttons.length - 1
|
||||
: (index + (event.key === "ArrowDown" ? 1 : -1) + buttons.length) %
|
||||
buttons.length;
|
||||
buttons[next].focus();
|
||||
}
|
||||
}
|
||||
function removeListeners() {
|
||||
document.removeEventListener("pointerdown", outside, true);
|
||||
window.removeEventListener("scroll", outside, true);
|
||||
window.removeEventListener("resize", hide);
|
||||
}
|
||||
watch(
|
||||
[() => props.show, () => props.pos],
|
||||
async ([visible]) => {
|
||||
removeListeners();
|
||||
if (!visible) return;
|
||||
previousFocus =
|
||||
document.activeElement instanceof HTMLElement
|
||||
? document.activeElement
|
||||
: null;
|
||||
await nextTick();
|
||||
if (!props.show || !contextMenu.value) return;
|
||||
const rect = contextMenu.value.getBoundingClientRect();
|
||||
left.value = Math.max(
|
||||
8,
|
||||
Math.min(props.pos.x, window.innerWidth - rect.width - 8)
|
||||
);
|
||||
top.value = Math.max(
|
||||
8,
|
||||
Math.min(props.pos.y, window.innerHeight - rect.height - 8)
|
||||
);
|
||||
const buttons =
|
||||
contextMenu.value.querySelectorAll<HTMLButtonElement>("button");
|
||||
buttons.forEach((button) => button.setAttribute("role", "menuitem"));
|
||||
buttons[0]?.focus({ preventScroll: true });
|
||||
document.addEventListener("pointerdown", outside, true);
|
||||
window.addEventListener("scroll", outside, true);
|
||||
window.addEventListener("resize", hide);
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
onUnmounted(() => {
|
||||
document.removeEventListener("click", hideContextMenu);
|
||||
});
|
||||
onBeforeUnmount(removeListeners);
|
||||
</script>
|
||||
@@ -1,45 +1,15 @@
|
||||
<template>
|
||||
<div class="t-container">
|
||||
<span>{{ message }}</span>
|
||||
<button v-if="isReport" class="action" @click.stop="clicked">
|
||||
{{ reportText }}
|
||||
</button>
|
||||
<div class="notification-content" :class="kind">
|
||||
<AppIcon
|
||||
:name="kind === 'error' ? 'error_outline' : 'check_circle'"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<div>
|
||||
<strong>{{ title }}</strong>
|
||||
<p>{{ message }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
defineProps<{
|
||||
message: string;
|
||||
reportText?: string;
|
||||
isReport?: boolean;
|
||||
}>();
|
||||
|
||||
const clicked = () => {
|
||||
window.open("https://github.com/filebrowser/filebrowser/issues/new/choose");
|
||||
};
|
||||
defineProps<{ message: string; title: string; kind: "success" | "error" }>();
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.t-container {
|
||||
width: 100%;
|
||||
padding: 5px 0;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
.action {
|
||||
text-align: center;
|
||||
height: 40px;
|
||||
padding: 0 10px;
|
||||
margin-left: 20px;
|
||||
border-radius: 5px;
|
||||
color: white;
|
||||
cursor: pointer;
|
||||
border: thin solid currentColor;
|
||||
}
|
||||
|
||||
html[dir="rtl"] .action {
|
||||
margin-left: initial;
|
||||
margin-right: 20px;
|
||||
}
|
||||
</style>
|
||||
@@ -85,7 +85,7 @@ export default {
|
||||
>
|
||||
<button @click="isOpen = !isOpen" class="dropdown-modal-trigger">
|
||||
<slot></slot>
|
||||
<i class="material-icons">chevron_right</i>
|
||||
<AppIcon name="chevron_right" />
|
||||
</button>
|
||||
|
||||
<teleport to="body">
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
<template>
|
||||
<li class="folder-node">
|
||||
<div
|
||||
class="folder-row"
|
||||
:class="{ selected }"
|
||||
:style="{ paddingInlineStart: `${depth * 14}px` }"
|
||||
>
|
||||
<button
|
||||
class="folder-expand"
|
||||
:aria-expanded="expanded"
|
||||
:aria-label="name"
|
||||
@click="expanded = !expanded"
|
||||
>
|
||||
<AppIcon :name="expanded ? 'expand_more' : 'chevron_right'" />
|
||||
</button>
|
||||
<router-link
|
||||
:to="url"
|
||||
:title="name"
|
||||
:aria-current="selected ? 'page' : undefined"
|
||||
@click="layout.closeHovers"
|
||||
>
|
||||
<AppIcon :name="expanded ? 'folder_open' : 'folder'" /><span>{{
|
||||
name
|
||||
}}</span>
|
||||
</router-link>
|
||||
</div>
|
||||
<ul v-if="expanded">
|
||||
<li v-if="loading" class="tree-status">{{ t("files.loading") }}</li>
|
||||
<li v-else-if="error" class="tree-status">
|
||||
<button @click="load">{{ t("explorer.retry") }}</button>
|
||||
</li>
|
||||
<FolderTreeNode
|
||||
v-for="folder in folders"
|
||||
:key="folder.url"
|
||||
:url="folder.url"
|
||||
:name="folder.name"
|
||||
:depth="depth + 1"
|
||||
/>
|
||||
</ul>
|
||||
</li>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { useRoute } from "vue-router";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useFileStore } from "@/stores/file";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { useLayoutStore } from "@/stores/layout";
|
||||
import { files as api } from "@/api";
|
||||
const props = defineProps<{ url: string; name: string; depth: number }>();
|
||||
const route = useRoute(),
|
||||
file = useFileStore(),
|
||||
auth = useAuthStore(),
|
||||
layout = useLayoutStore();
|
||||
const { t } = useI18n();
|
||||
const normalized = (url: string) => url.replace(/\/+$/, "") + "/";
|
||||
const expanded = ref(props.depth === 0),
|
||||
loading = ref(false),
|
||||
error = ref(false);
|
||||
const children = ref<ResourceItem[]>([]);
|
||||
const selected = computed(
|
||||
() => !!file.req?.isDir && normalized(file.req.url) === normalized(props.url)
|
||||
);
|
||||
const folders = computed(() =>
|
||||
children.value
|
||||
.filter(
|
||||
(item) =>
|
||||
item.isDir && (!auth.user?.hideDotfiles || !item.name.startsWith("."))
|
||||
)
|
||||
.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }))
|
||||
);
|
||||
let controller: AbortController | undefined;
|
||||
function useCurrentListing() {
|
||||
if (!selected.value || !file.req) return false;
|
||||
controller?.abort();
|
||||
children.value = file.req.items;
|
||||
loading.value = false;
|
||||
error.value = false;
|
||||
return true;
|
||||
}
|
||||
async function load() {
|
||||
if (useCurrentListing()) return;
|
||||
controller?.abort();
|
||||
const request = (controller = new AbortController());
|
||||
loading.value = true;
|
||||
error.value = false;
|
||||
try {
|
||||
const result = await api.fetch(props.url, request.signal);
|
||||
if (request.signal.aborted) return;
|
||||
children.value = result.items || [];
|
||||
} catch {
|
||||
if (!request.signal.aborted) error.value = true;
|
||||
} finally {
|
||||
if (controller === request) loading.value = false;
|
||||
}
|
||||
}
|
||||
watch(
|
||||
() => file.req,
|
||||
() => {
|
||||
if (expanded.value) useCurrentListing();
|
||||
}
|
||||
);
|
||||
watch(
|
||||
() => route.path,
|
||||
(path) => {
|
||||
if (normalized(path).startsWith(normalized(props.url)))
|
||||
expanded.value = true;
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
watch(
|
||||
expanded,
|
||||
(value) => {
|
||||
if (value) load();
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
onBeforeUnmount(() => controller?.abort());
|
||||
</script>
|
||||
@@ -8,10 +8,10 @@
|
||||
:aria-label="closeButtonTitle"
|
||||
:title="closeButtonTitle"
|
||||
>
|
||||
<i v-if="ongoing" class="material-icons">stop_circle</i>
|
||||
<i v-else class="material-icons">arrow_back</i>
|
||||
<AppIcon name="stop_circle" v-if="ongoing" />
|
||||
<AppIcon name="arrow_back" v-else />
|
||||
</button>
|
||||
<i v-else class="material-icons">search</i>
|
||||
<AppIcon name="search" v-else />
|
||||
<input
|
||||
type="text"
|
||||
@keyup.exact="keyup"
|
||||
@@ -22,12 +22,12 @@
|
||||
:aria-label="$t('search.search')"
|
||||
:placeholder="$t('search.search')"
|
||||
/>
|
||||
<i
|
||||
<AppIcon
|
||||
name="autorenew"
|
||||
v-show="ongoing"
|
||||
class="material-icons spin"
|
||||
class="spin"
|
||||
style="display: inline-block"
|
||||
>autorenew
|
||||
</i>
|
||||
/>
|
||||
<span style="margin-top: 5px" v-show="results.length > 0">
|
||||
{{ results.length }}
|
||||
</span>
|
||||
@@ -50,7 +50,7 @@
|
||||
@click="init('type:' + k)"
|
||||
:aria-label="$t('search.' + v.label)"
|
||||
>
|
||||
<i class="material-icons">{{ v.icon }}</i>
|
||||
<AppIcon :name="v.icon" />
|
||||
<p>{{ $t("search." + v.label) }}</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -60,8 +60,8 @@
|
||||
<ul v-show="results.length > 0">
|
||||
<li v-for="(s, k) in filteredResults" :key="k">
|
||||
<router-link v-on:click="close" :to="s.url">
|
||||
<i v-if="s.dir" class="material-icons">folder</i>
|
||||
<i v-else class="material-icons">insert_drive_file</i>
|
||||
<AppIcon name="folder" v-if="s.dir" />
|
||||
<AppIcon name="insert_drive_file" v-else />
|
||||
<span>./{{ s.path }}</span>
|
||||
</router-link>
|
||||
</li>
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
<template>
|
||||
<main class="sso-welcome" role="alert">
|
||||
<div class="sso-symbol"><AppIcon name="account_circle" /></div>
|
||||
<h1>{{ t("session." + message) }}</h1>
|
||||
<p>{{ t("session." + message + "Hint") }}</p>
|
||||
<button
|
||||
v-if="
|
||||
['factor_required', 'rebind_required', 'signed_out'].includes(
|
||||
auth.sessionStatus
|
||||
)
|
||||
"
|
||||
class="button"
|
||||
@click="startLogin(undefined, auth.sessionStatus === 'rebind_required')"
|
||||
>
|
||||
{{ t("session.continue") }}
|
||||
</button>
|
||||
<a
|
||||
v-if="
|
||||
auth.sessionStatus === 'access_denied' ||
|
||||
auth.sessionStatus === 'factor_enrollment_required'
|
||||
"
|
||||
class="button"
|
||||
:href="baseURL + '/auth/account'"
|
||||
>{{ t("preferences.manage") }}</a
|
||||
>
|
||||
<button
|
||||
v-if="auth.sessionStatus === 'unavailable'"
|
||||
class="button"
|
||||
@click="validateLogin"
|
||||
>
|
||||
{{ t("session.retry") }}
|
||||
</button>
|
||||
</main>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { baseURL } from "@/utils/constants";
|
||||
import { startLogin, validateLogin } from "@/utils/auth";
|
||||
const auth = useAuthStore(),
|
||||
{ t } = useI18n();
|
||||
const message = computed(() =>
|
||||
[
|
||||
"checking",
|
||||
"access_denied",
|
||||
"factor_required",
|
||||
"rebind_required",
|
||||
"signed_out",
|
||||
"factor_enrollment_required",
|
||||
].includes(auth.sessionStatus)
|
||||
? auth.sessionStatus
|
||||
: "unavailable"
|
||||
);
|
||||
</script>
|
||||
@@ -13,7 +13,7 @@
|
||||
<div @click="focus" class="shell__content" ref="scrollable">
|
||||
<div v-for="(c, index) in content" :key="index" class="shell__result">
|
||||
<div class="shell__prompt">
|
||||
<i class="material-icons">chevron_right</i>
|
||||
<AppIcon name="chevron_right" />
|
||||
</div>
|
||||
<pre class="shell__text">{{ c.text }}</pre>
|
||||
</div>
|
||||
@@ -23,7 +23,7 @@
|
||||
:class="{ 'shell__result--hidden': !canInput }"
|
||||
>
|
||||
<div class="shell__prompt">
|
||||
<i class="material-icons">chevron_right</i>
|
||||
<AppIcon name="chevron_right" />
|
||||
</div>
|
||||
<pre
|
||||
tabindex="0"
|
||||
|
||||
@@ -1,222 +1,331 @@
|
||||
<template>
|
||||
<div v-show="active" @click="closeHovers" class="overlay"></div>
|
||||
<nav :class="{ active }">
|
||||
<template v-if="isLoggedIn">
|
||||
<button @click="toAccountSettings" class="action">
|
||||
<i class="material-icons">person</i>
|
||||
<span>{{ user.username }}</span>
|
||||
</button>
|
||||
<button
|
||||
class="action"
|
||||
@click="toRoot"
|
||||
:aria-label="$t('sidebar.myFiles')"
|
||||
:title="$t('sidebar.myFiles')"
|
||||
>
|
||||
<i class="material-icons">folder</i>
|
||||
<span>{{ $t("sidebar.myFiles") }}</span>
|
||||
</button>
|
||||
|
||||
<div v-if="user.perm.create">
|
||||
<button
|
||||
@click="showHover('newDir')"
|
||||
class="action"
|
||||
:aria-label="$t('sidebar.newFolder')"
|
||||
:title="$t('sidebar.newFolder')"
|
||||
<div v-show="active" @click="layout.closeHovers" class="overlay"></div>
|
||||
<nav
|
||||
class="workspace-sidebar"
|
||||
@keydown.stop
|
||||
:class="{ active }"
|
||||
:aria-label="t('explorer.navigation')"
|
||||
>
|
||||
<template v-if="auth.isLoggedIn && auth.user">
|
||||
<div class="sidebar-scroll">
|
||||
<div class="sidebar-section-title">
|
||||
<span>{{ t("explorer.bookmarks") }}</span>
|
||||
<button
|
||||
v-if="file.isFiles"
|
||||
:disabled="bookmarked || bookmarks.length >= 40"
|
||||
@click="addBookmark"
|
||||
:title="t('explorer.pinCurrent')"
|
||||
:aria-label="t('explorer.pinCurrent')"
|
||||
>
|
||||
<AppIcon name="bookmark_add" />
|
||||
</button>
|
||||
</div>
|
||||
<router-link
|
||||
class="explorer-link"
|
||||
to="/files/"
|
||||
@click="layout.closeHovers"
|
||||
><AppIcon name="home" /><span>{{
|
||||
t("sidebar.myFiles")
|
||||
}}</span></router-link
|
||||
>
|
||||
<i class="material-icons">create_new_folder</i>
|
||||
<span>{{ $t("sidebar.newFolder") }}</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
@click="showHover('newFile')"
|
||||
class="action"
|
||||
:aria-label="$t('sidebar.newFile')"
|
||||
:title="$t('sidebar.newFile')"
|
||||
<div
|
||||
v-for="bookmark in bookmarks"
|
||||
:key="bookmark.url"
|
||||
class="bookmark-row"
|
||||
>
|
||||
<i class="material-icons">note_add</i>
|
||||
<span>{{ $t("sidebar.newFile") }}</span>
|
||||
</button>
|
||||
<router-link
|
||||
class="explorer-link"
|
||||
:to="bookmark.url"
|
||||
:title="bookmark.name"
|
||||
@click="layout.closeHovers"
|
||||
><AppIcon name="star_outline" /><span>{{
|
||||
bookmark.name
|
||||
}}</span></router-link
|
||||
>
|
||||
<button
|
||||
@click="removeBookmark(bookmark.url)"
|
||||
:aria-label="t('explorer.unpin')"
|
||||
:title="t('explorer.unpin')"
|
||||
>
|
||||
<AppIcon name="close" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="sidebar-section-title">
|
||||
<span>{{ t("explorer.folders") }}</span>
|
||||
<button
|
||||
v-if="file.isFiles && file.req?.isDir && auth.user.perm.create"
|
||||
@click="layout.showHover('newDir')"
|
||||
:title="t('sidebar.newFolder')"
|
||||
:aria-label="t('sidebar.newFolder')"
|
||||
>
|
||||
<AppIcon name="create_new_folder" />
|
||||
</button>
|
||||
<button
|
||||
v-if="file.isFiles && file.req?.isDir && auth.user.perm.create"
|
||||
@click="layout.showHover('create')"
|
||||
:title="t('buttons.create')"
|
||||
:aria-label="t('buttons.create')"
|
||||
>
|
||||
<AppIcon name="add" />
|
||||
</button>
|
||||
</div>
|
||||
<ul class="folder-tree" :aria-label="t('explorer.folders')">
|
||||
<FolderTreeNode
|
||||
v-if="file.req || route.name !== 'Files'"
|
||||
:key="auth.user.id"
|
||||
url="/files/"
|
||||
:name="t('sidebar.myFiles')"
|
||||
:depth="0"
|
||||
/>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div v-if="user.perm.admin">
|
||||
<button
|
||||
class="action"
|
||||
@click="toGlobalSettings"
|
||||
:aria-label="$t('sidebar.settings')"
|
||||
:title="$t('sidebar.settings')"
|
||||
<div class="sidebar-bottom">
|
||||
<div
|
||||
class="disk-usage"
|
||||
v-if="file.isFiles && !disableUsedPercentage && usage.total"
|
||||
>
|
||||
<i class="material-icons">settings_applications</i>
|
||||
<span>{{ $t("sidebar.settings") }}</span>
|
||||
</button>
|
||||
<div class="disk-usage-heading">
|
||||
<span>{{ t("sso.storage") }}</span
|
||||
><strong>{{ usage.percent }}%</strong>
|
||||
</div>
|
||||
<progress
|
||||
:value="usage.percent"
|
||||
max="100"
|
||||
:aria-label="t('sso.storage')"
|
||||
></progress>
|
||||
<small>{{
|
||||
t("sidebar.diskUsed", {
|
||||
used: prettyBytes(usage.used, { binary: true }),
|
||||
total: prettyBytes(usage.total, { binary: true }),
|
||||
})
|
||||
}}</small>
|
||||
</div>
|
||||
<div
|
||||
ref="account"
|
||||
class="sidebar-account"
|
||||
@keydown.esc.stop.prevent="closeAccount"
|
||||
>
|
||||
<div
|
||||
v-if="accountOpen"
|
||||
id="sidebar-account-menu"
|
||||
class="account-menu"
|
||||
role="menu"
|
||||
@keydown="menuKey"
|
||||
>
|
||||
<a
|
||||
v-if="!noAuth"
|
||||
role="menuitem"
|
||||
:href="baseURL + '/auth/account'"
|
||||
@click="navigate"
|
||||
><AppIcon name="account_circle" />{{ t("explorer.account") }}</a
|
||||
>
|
||||
<router-link
|
||||
role="menuitem"
|
||||
to="/settings/profile"
|
||||
@click="navigate"
|
||||
><AppIcon name="settings" />{{
|
||||
t("sidebar.settings")
|
||||
}}</router-link
|
||||
>
|
||||
<router-link
|
||||
v-if="auth.user.perm.share"
|
||||
role="menuitem"
|
||||
to="/settings/shares"
|
||||
@click="navigate"
|
||||
><AppIcon name="link" />{{
|
||||
t("settings.shareManagement")
|
||||
}}</router-link
|
||||
>
|
||||
<router-link
|
||||
v-if="auth.user.perm.admin"
|
||||
role="menuitem"
|
||||
to="/settings/global"
|
||||
@click="navigate"
|
||||
><AppIcon name="settings" />{{
|
||||
t("explorer.adminSettings")
|
||||
}}</router-link
|
||||
>
|
||||
|
||||
<button v-if="canLogout" role="menuitem" @click="signOut(true)">
|
||||
<AppIcon name="account_circle" />{{ t("session.switchAccount") }}
|
||||
</button>
|
||||
<button v-if="canLogout" role="menuitem" @click="logout">
|
||||
<AppIcon name="logout" />{{ t("sidebar.logout") }}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
ref="accountButton"
|
||||
class="account-button"
|
||||
aria-haspopup="menu"
|
||||
:aria-expanded="accountOpen"
|
||||
aria-controls="sidebar-account-menu"
|
||||
@click="accountOpen = !accountOpen"
|
||||
@keydown.down.prevent="openAccount"
|
||||
>
|
||||
<AccountAvatar :user="auth.user" />
|
||||
<span class="account-label"
|
||||
><strong>{{ auth.user.username }}</strong
|
||||
><small>{{
|
||||
auth.user.email || auth.user.profileName || ""
|
||||
}}</small></span
|
||||
><AppIcon name="more_horiz" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
v-if="canLogout"
|
||||
@click="logout"
|
||||
class="action"
|
||||
id="logout"
|
||||
:aria-label="$t('sidebar.logout')"
|
||||
:title="$t('sidebar.logout')"
|
||||
>
|
||||
<i class="material-icons">exit_to_app</i>
|
||||
<span>{{ $t("sidebar.logout") }}</span>
|
||||
</button>
|
||||
</template>
|
||||
<template v-else>
|
||||
<router-link
|
||||
v-if="!hideLoginButton"
|
||||
class="action"
|
||||
to="/login"
|
||||
:aria-label="$t('sidebar.login')"
|
||||
:title="$t('sidebar.login')"
|
||||
>
|
||||
<i class="material-icons">exit_to_app</i>
|
||||
<span>{{ $t("sidebar.login") }}</span>
|
||||
</router-link>
|
||||
|
||||
<router-link
|
||||
v-if="signup"
|
||||
class="action"
|
||||
to="/login"
|
||||
:aria-label="$t('sidebar.signup')"
|
||||
:title="$t('sidebar.signup')"
|
||||
>
|
||||
<i class="material-icons">person_add</i>
|
||||
<span>{{ $t("sidebar.signup") }}</span>
|
||||
</router-link>
|
||||
</template>
|
||||
|
||||
<div
|
||||
class="credits"
|
||||
v-if="isFiles && !disableUsedPercentage"
|
||||
style="width: 90%; margin: 2em 2.5em 3em 2.5em"
|
||||
<router-link v-else-if="!hideLoginButton" class="explorer-link" to="/login"
|
||||
><AppIcon name="login" />{{ t("sidebar.login") }}</router-link
|
||||
>
|
||||
<progress-bar :val="usage.usedPercentage" size="small"></progress-bar>
|
||||
<br />
|
||||
{{ $t("sidebar.diskUsed", { used: usage.used, total: usage.total }) }}
|
||||
</div>
|
||||
|
||||
<p class="credits">
|
||||
<span>
|
||||
<span v-if="disableExternal">File Browser</span>
|
||||
<a
|
||||
v-else
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
href="https://github.com/filebrowser/filebrowser"
|
||||
>File Browser</a
|
||||
>
|
||||
<span> {{ " " }} {{ version }}</span>
|
||||
</span>
|
||||
<span>
|
||||
<a @click="help">{{ $t("sidebar.help") }}</a>
|
||||
</span>
|
||||
</p>
|
||||
</nav>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { reactive } from "vue";
|
||||
import { mapActions, mapState } from "pinia";
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRoute } from "vue-router";
|
||||
import { onClickOutside } from "@vueuse/core";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { useFileStore } from "@/stores/file";
|
||||
import { useLayoutStore } from "@/stores/layout";
|
||||
|
||||
import * as auth from "@/utils/auth";
|
||||
import {
|
||||
version,
|
||||
signup,
|
||||
hideLoginButton,
|
||||
disableExternal,
|
||||
disableUsedPercentage,
|
||||
noAuth,
|
||||
logoutPage,
|
||||
loginPage,
|
||||
} from "@/utils/constants";
|
||||
import { files as api } from "@/api";
|
||||
import ProgressBar from "@/components/ProgressBar.vue";
|
||||
import { logout as signOut } from "@/utils/auth";
|
||||
import {
|
||||
disableUsedPercentage,
|
||||
hideLoginButton,
|
||||
noAuth,
|
||||
loginPage,
|
||||
logoutPage,
|
||||
baseURL,
|
||||
} from "@/utils/constants";
|
||||
import { parseBookmarks, type Bookmark } from "@/utils/bookmarks";
|
||||
import FolderTreeNode from "./FolderTreeNode.vue";
|
||||
import AccountAvatar from "./AccountAvatar.vue";
|
||||
import prettyBytes from "pretty-bytes";
|
||||
|
||||
const USAGE_DEFAULT = { used: "0 B", total: "0 B", usedPercentage: 0 };
|
||||
|
||||
export default {
|
||||
name: "sidebar",
|
||||
setup() {
|
||||
const usage = reactive(USAGE_DEFAULT);
|
||||
return { usage, usageAbortController: new AbortController() };
|
||||
const auth = useAuthStore(),
|
||||
file = useFileStore(),
|
||||
layout = useLayoutStore(),
|
||||
route = useRoute();
|
||||
const { t } = useI18n();
|
||||
const active = computed(() => layout.currentPromptName === "sidebar");
|
||||
const canLogout = !noAuth && (loginPage || logoutPage !== "/login");
|
||||
const account = ref<HTMLElement>(),
|
||||
accountButton = ref<HTMLButtonElement>(),
|
||||
accountOpen = ref(false);
|
||||
onClickOutside(account, () => (accountOpen.value = false));
|
||||
function closeAccount() {
|
||||
accountOpen.value = false;
|
||||
accountButton.value?.focus();
|
||||
}
|
||||
function navigate() {
|
||||
accountOpen.value = false;
|
||||
layout.closeHovers();
|
||||
}
|
||||
async function openAccount() {
|
||||
accountOpen.value = true;
|
||||
await nextTick();
|
||||
account.value?.querySelector<HTMLElement>("[role=menuitem]")?.focus();
|
||||
}
|
||||
function menuKey(event: KeyboardEvent) {
|
||||
if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;
|
||||
event.preventDefault();
|
||||
const items = Array.from(
|
||||
account.value?.querySelectorAll<HTMLElement>("[role=menuitem]") || []
|
||||
);
|
||||
const index = items.indexOf(document.activeElement as HTMLElement);
|
||||
items[
|
||||
event.key === "Home"
|
||||
? 0
|
||||
: event.key === "End"
|
||||
? items.length - 1
|
||||
: (index + (event.key === "ArrowUp" ? -1 : 1) + items.length) %
|
||||
items.length
|
||||
]?.focus();
|
||||
}
|
||||
function logout() {
|
||||
accountOpen.value = false;
|
||||
signOut();
|
||||
}
|
||||
watch(
|
||||
() => route.path,
|
||||
() => (accountOpen.value = false)
|
||||
);
|
||||
const bookmarks = ref<Bookmark[]>([]);
|
||||
const bookmarkKey = computed(
|
||||
() => `filebrowser:${baseURL}:bookmarks:${auth.user?.id}`
|
||||
);
|
||||
watch(
|
||||
bookmarkKey,
|
||||
(key) => {
|
||||
try {
|
||||
bookmarks.value = parseBookmarks(localStorage.getItem(key));
|
||||
} catch {
|
||||
bookmarks.value = [];
|
||||
}
|
||||
},
|
||||
components: {
|
||||
ProgressBar,
|
||||
{ immediate: true }
|
||||
);
|
||||
function saveBookmarks() {
|
||||
try {
|
||||
localStorage.setItem(bookmarkKey.value, JSON.stringify(bookmarks.value));
|
||||
} catch {
|
||||
/* Private browsing can disable storage. */
|
||||
}
|
||||
}
|
||||
const currentFolder = computed(() => {
|
||||
const req = file.req;
|
||||
if (!req) return { name: t("sidebar.myFiles"), url: "/files/" };
|
||||
const url = req.isDir
|
||||
? req.url
|
||||
: req.url.slice(0, req.url.lastIndexOf("/") + 1);
|
||||
const part = url.replace(/\/+$/, "").split("/").pop() || "";
|
||||
return {
|
||||
name:
|
||||
url.replace(/\/+$/, "") === "/files"
|
||||
? t("sidebar.myFiles")
|
||||
: decodeURIComponent(part),
|
||||
url: url.replace(/\/+$/, "") + "/",
|
||||
};
|
||||
});
|
||||
const bookmarked = computed(
|
||||
() =>
|
||||
currentFolder.value.url === "/files/" ||
|
||||
bookmarks.value.some((entry) => entry.url === currentFolder.value.url)
|
||||
);
|
||||
function addBookmark() {
|
||||
if (bookmarked.value || bookmarks.value.length >= 40) return;
|
||||
bookmarks.value.push(currentFolder.value);
|
||||
saveBookmarks();
|
||||
}
|
||||
function removeBookmark(url: string) {
|
||||
bookmarks.value = bookmarks.value.filter((entry) => entry.url !== url);
|
||||
saveBookmarks();
|
||||
}
|
||||
const usage = ref({ used: 0, total: 0, percent: 0 });
|
||||
let usageController: AbortController | undefined;
|
||||
watch(
|
||||
() => file.req?.url,
|
||||
async () => {
|
||||
if (!file.isFiles || disableUsedPercentage || !file.req) return;
|
||||
usageController?.abort();
|
||||
const request = (usageController = new AbortController());
|
||||
try {
|
||||
const stats = await api.usage(currentFolder.value.url, request.signal);
|
||||
if (request.signal.aborted) return;
|
||||
usage.value = {
|
||||
used: stats.used,
|
||||
total: stats.total,
|
||||
percent:
|
||||
stats.total > 0
|
||||
? Math.max(
|
||||
0,
|
||||
Math.min(100, Math.round((stats.used / stats.total) * 100))
|
||||
)
|
||||
: 0,
|
||||
};
|
||||
} catch {
|
||||
/* Storage usage is optional. */
|
||||
}
|
||||
},
|
||||
inject: ["$showError"],
|
||||
computed: {
|
||||
...mapState(useAuthStore, ["user", "isLoggedIn"]),
|
||||
...mapState(useFileStore, ["isFiles", "reload"]),
|
||||
...mapState(useLayoutStore, ["currentPromptName"]),
|
||||
active() {
|
||||
return this.currentPromptName === "sidebar";
|
||||
},
|
||||
signup: () => signup,
|
||||
hideLoginButton: () => hideLoginButton,
|
||||
version: () => version,
|
||||
disableExternal: () => disableExternal,
|
||||
disableUsedPercentage: () => disableUsedPercentage,
|
||||
canLogout: () => !noAuth && (loginPage || logoutPage !== "/login"),
|
||||
},
|
||||
methods: {
|
||||
...mapActions(useLayoutStore, ["closeHovers", "showHover"]),
|
||||
abortOngoingFetchUsage() {
|
||||
this.usageAbortController.abort();
|
||||
},
|
||||
async fetchUsage() {
|
||||
const path = this.$route.path.endsWith("/")
|
||||
? this.$route.path
|
||||
: this.$route.path + "/";
|
||||
let usageStats = USAGE_DEFAULT;
|
||||
if (this.disableUsedPercentage) {
|
||||
return Object.assign(this.usage, usageStats);
|
||||
}
|
||||
try {
|
||||
this.abortOngoingFetchUsage();
|
||||
this.usageAbortController = new AbortController();
|
||||
const usage = await api.usage(path, this.usageAbortController.signal);
|
||||
usageStats = {
|
||||
used: prettyBytes(usage.used, { binary: true }),
|
||||
total: prettyBytes(usage.total, { binary: true }),
|
||||
usedPercentage: Math.round((usage.used / usage.total) * 100),
|
||||
};
|
||||
} finally {
|
||||
return Object.assign(this.usage, usageStats);
|
||||
}
|
||||
},
|
||||
toRoot() {
|
||||
this.$router.push({ path: "/files" });
|
||||
this.closeHovers();
|
||||
},
|
||||
toAccountSettings() {
|
||||
this.$router.push({ path: "/settings/profile" });
|
||||
this.closeHovers();
|
||||
},
|
||||
toGlobalSettings() {
|
||||
this.$router.push({ path: "/settings/global" });
|
||||
this.closeHovers();
|
||||
},
|
||||
help() {
|
||||
this.showHover("help");
|
||||
},
|
||||
logout: auth.logout,
|
||||
},
|
||||
watch: {
|
||||
$route: {
|
||||
handler(to) {
|
||||
if (to.path.includes("/files")) {
|
||||
this.fetchUsage();
|
||||
}
|
||||
},
|
||||
immediate: true,
|
||||
},
|
||||
},
|
||||
unmounted() {
|
||||
this.abortOngoingFetchUsage();
|
||||
},
|
||||
};
|
||||
{ immediate: true }
|
||||
);
|
||||
onBeforeUnmount(() => usageController?.abort());
|
||||
</script>
|
||||
@@ -0,0 +1,42 @@
|
||||
<template>
|
||||
<Action
|
||||
v-for="tool in tools"
|
||||
:key="tool.id"
|
||||
icon="edit_note"
|
||||
:label="t('addons.openWith', { name: tool.name })"
|
||||
@action="openCraftTab(router, tool.id, file!.url)"
|
||||
/>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { addonAccepts, openCraftTab } from "@/utils/craft";
|
||||
import { computed, onMounted } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { useAddonsStore } from "@/stores/addons";
|
||||
import Action from "@/components/header/Action.vue";
|
||||
const props = defineProps<{
|
||||
file?: { name: string; url: string; isDir: boolean } | null;
|
||||
}>();
|
||||
const store = useAddonsStore(),
|
||||
auth = useAuthStore(),
|
||||
router = useRouter(),
|
||||
{ t } = useI18n();
|
||||
const tools = computed(() =>
|
||||
props.file &&
|
||||
!props.file.isDir &&
|
||||
auth.user?.perm.download &&
|
||||
auth.user?.perm.modify
|
||||
? store.items.filter(
|
||||
(item) =>
|
||||
item.enabled &&
|
||||
!item.compatibilityIssue &&
|
||||
item.build &&
|
||||
addonAccepts(item, props.file!.name)
|
||||
)
|
||||
: []
|
||||
);
|
||||
onMounted(() => {
|
||||
store.refresh().catch(() => {});
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,135 @@
|
||||
<template>
|
||||
<button
|
||||
ref="trigger"
|
||||
class="action"
|
||||
type="button"
|
||||
aria-haspopup="menu"
|
||||
:aria-expanded="expanded"
|
||||
@click.stop="expanded = !expanded"
|
||||
@keydown.right.stop.prevent="expand"
|
||||
>
|
||||
<AppIcon name="add" /><span>{{ t("buttons.create") }}</span
|
||||
><AppIcon name="chevron_right" />
|
||||
</button>
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="expanded"
|
||||
ref="submenu"
|
||||
class="context-menu context-submenu"
|
||||
role="menu"
|
||||
:data-context-owner="owner?.id"
|
||||
:aria-label="t('buttons.create')"
|
||||
:style="{ left: left + 'px', top: top + 'px' }"
|
||||
@click.stop="choose"
|
||||
@contextmenu.prevent.stop
|
||||
@keydown.stop="keyboard"
|
||||
>
|
||||
<button
|
||||
v-if="compact"
|
||||
type="button"
|
||||
class="action"
|
||||
@click.stop="collapse"
|
||||
>
|
||||
<AppIcon name="arrow_back" /><span>{{ t("buttons.create") }}</span>
|
||||
</button>
|
||||
<CreateOptions />
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { inject, nextTick, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { contextMenuKey, submenuPosition } from "@/utils/context-menu";
|
||||
import CreateOptions from "./CreateOptions.vue";
|
||||
const { t } = useI18n(),
|
||||
owner = inject(contextMenuKey);
|
||||
const expanded = ref(false),
|
||||
compact = ref(false),
|
||||
left = ref(0),
|
||||
top = ref(0);
|
||||
const submenu = ref<HTMLElement>(),
|
||||
trigger = ref<HTMLElement>();
|
||||
function position() {
|
||||
if (!submenu.value || !trigger.value) return;
|
||||
const parent = trigger.value
|
||||
.closest(".context-menu")
|
||||
?.getBoundingClientRect();
|
||||
if (!parent) return;
|
||||
const row = trigger.value.getBoundingClientRect(),
|
||||
panel = submenu.value.getBoundingClientRect();
|
||||
compact.value = window.innerWidth < parent.width + panel.width + 24;
|
||||
const coordinates = submenuPosition(
|
||||
{ left: parent.left, right: parent.right, top: row.top - 6 },
|
||||
panel.width,
|
||||
panel.height,
|
||||
{ width: window.innerWidth, height: window.innerHeight }
|
||||
);
|
||||
left.value = compact.value
|
||||
? Math.max(8, Math.min(parent.left, window.innerWidth - panel.width - 8))
|
||||
: coordinates.left;
|
||||
top.value = coordinates.top;
|
||||
}
|
||||
async function expand() {
|
||||
expanded.value = true;
|
||||
await nextTick();
|
||||
position();
|
||||
submenu.value?.querySelector("button")?.focus({ preventScroll: true });
|
||||
}
|
||||
function collapse() {
|
||||
expanded.value = false;
|
||||
trigger.value?.focus({ preventScroll: true });
|
||||
}
|
||||
function choose(event: MouseEvent) {
|
||||
if (!(event.target instanceof Element) || !event.target.closest("button"))
|
||||
return;
|
||||
expanded.value = false;
|
||||
owner?.close();
|
||||
}
|
||||
function keyboard(event: KeyboardEvent) {
|
||||
if (event.key === "Escape" || event.key === "ArrowLeft") {
|
||||
event.preventDefault();
|
||||
collapse();
|
||||
return;
|
||||
}
|
||||
if (event.key === "Tab") {
|
||||
expanded.value = false;
|
||||
owner?.close();
|
||||
return;
|
||||
}
|
||||
if (!["ArrowUp", "ArrowDown", "Home", "End"].includes(event.key)) return;
|
||||
event.preventDefault();
|
||||
const buttons = Array.from(
|
||||
submenu.value?.querySelectorAll<HTMLButtonElement>(
|
||||
"button:not(:disabled)"
|
||||
) || []
|
||||
);
|
||||
if (!buttons.length) return;
|
||||
const index = buttons.indexOf(document.activeElement as HTMLButtonElement);
|
||||
const next =
|
||||
event.key === "Home"
|
||||
? 0
|
||||
: event.key === "End"
|
||||
? buttons.length - 1
|
||||
: (index + (event.key === "ArrowUp" ? -1 : 1) + buttons.length) %
|
||||
buttons.length;
|
||||
buttons[next].focus();
|
||||
}
|
||||
function scroll(event: Event) {
|
||||
if (!(event.target instanceof Node) || !submenu.value?.contains(event.target))
|
||||
position();
|
||||
}
|
||||
watch(expanded, async (open) => {
|
||||
window.removeEventListener("scroll", scroll, true);
|
||||
if (!open) return;
|
||||
await nextTick();
|
||||
if (!expanded.value) return;
|
||||
position();
|
||||
await nextTick();
|
||||
position();
|
||||
submenu.value
|
||||
?.querySelectorAll("button")
|
||||
.forEach((button) => button.setAttribute("role", "menuitem"));
|
||||
window.addEventListener("scroll", scroll, true);
|
||||
});
|
||||
onBeforeUnmount(() => window.removeEventListener("scroll", scroll, true));
|
||||
</script>
|
||||
@@ -0,0 +1,45 @@
|
||||
<template>
|
||||
<button type="button" class="action" @click="open('newDir')">
|
||||
<AppIcon name="folder" /><span>{{ t("sidebar.newFolder") }}</span>
|
||||
</button>
|
||||
<div class="context-menu-separator" />
|
||||
<button
|
||||
v-for="template in templates"
|
||||
:key="template.id"
|
||||
type="button"
|
||||
class="action"
|
||||
@click="open('newFile', template.id)"
|
||||
>
|
||||
<AppIcon :name="template.icon" /><span>{{
|
||||
t("createTypes." + template.id)
|
||||
}}</span>
|
||||
</button>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useLayoutStore } from "@/stores/layout";
|
||||
import { fileTemplates } from "@/utils/file-templates";
|
||||
import { computed, onMounted } from "vue";
|
||||
import { useAddonsStore } from "@/stores/addons";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
const addons = useAddonsStore(),
|
||||
auth = useAuthStore();
|
||||
const templates = computed(() =>
|
||||
fileTemplates.filter(
|
||||
(template) =>
|
||||
!template.craft ||
|
||||
(addons.available(template.craft) &&
|
||||
auth.user?.perm.modify &&
|
||||
auth.user?.perm.download)
|
||||
)
|
||||
);
|
||||
onMounted(() => {
|
||||
addons.refresh().catch(() => {});
|
||||
});
|
||||
const { t } = useI18n(),
|
||||
layout = useLayoutStore();
|
||||
function open(prompt: string, template?: string) {
|
||||
if (layout.currentPromptName === "create") layout.closeHovers();
|
||||
layout.showHover({ prompt, props: { template } });
|
||||
}
|
||||
</script>
|
||||
@@ -37,7 +37,7 @@
|
||||
/>
|
||||
<div class="encoding-list">
|
||||
<div v-if="encodingList.length == 0" class="message">
|
||||
<i class="material-icons">sentiment_dissatisfied</i>
|
||||
<AppIcon name="sentiment_dissatisfied" />
|
||||
<span>{{ $t("files.lonely") }}</span>
|
||||
</div>
|
||||
<button
|
||||
@@ -55,11 +55,11 @@
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="displayError" class="csv-error">
|
||||
<i class="material-icons">error</i>
|
||||
<AppIcon name="error" />
|
||||
<p>{{ displayError }}</p>
|
||||
</div>
|
||||
<div v-else-if="parsed.headers.length === 0" class="csv-empty">
|
||||
<i class="material-icons">description</i>
|
||||
<AppIcon name="description" />
|
||||
<p>{{ $t("files.lonely") }}</p>
|
||||
</div>
|
||||
<div v-else class="csv-table-container" @wheel.stop @touchmove.stop>
|
||||
@@ -81,7 +81,7 @@
|
||||
</table>
|
||||
<div class="csv-footer">
|
||||
<div class="csv-info" v-if="parsed.rows.length > 100">
|
||||
<i class="material-icons">info</i>
|
||||
<AppIcon name="info" />
|
||||
<span>
|
||||
{{ $t("files.showingRows", { count: parsed.rows.length }) }}
|
||||
</span>
|
||||
@@ -177,7 +177,7 @@ watch(selectedEncoding, () => {
|
||||
background-color: var(--surfacePrimary);
|
||||
color: var(--textSecondary);
|
||||
padding: 1rem;
|
||||
padding-top: 4em;
|
||||
padding-top: 1rem;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
<template>
|
||||
<div
|
||||
class="document-viewer dicom-viewer"
|
||||
@wheel.stop
|
||||
@touchmove.stop
|
||||
@keydown.stop
|
||||
>
|
||||
<div class="document-tools">
|
||||
<strong>DICOM</strong>
|
||||
<button
|
||||
v-if="series.length && !volume && !volumeLoading"
|
||||
class="button button--flat"
|
||||
@click="openVolume"
|
||||
>
|
||||
{{ t("documents.open3d") }} ({{ series.length }})
|
||||
</button>
|
||||
<button
|
||||
v-if="volume || volumeLoading"
|
||||
class="button button--flat"
|
||||
@click="closeVolume"
|
||||
>
|
||||
{{ t("documents.back2d") }}
|
||||
</button>
|
||||
<template v-if="ready && !volume && !volumeLoading">
|
||||
<label
|
||||
>{{ t("documents.frame") }}
|
||||
<input
|
||||
v-model.number="frame"
|
||||
type="number"
|
||||
min="1"
|
||||
:max="frames" /></label
|
||||
><span>/ {{ frames }}</span>
|
||||
<template v-if="!color"
|
||||
><label
|
||||
>{{ t("documents.window") }}
|
||||
<input v-model.number="width" type="number" min="1" /></label
|
||||
><label
|
||||
>{{ t("documents.level") }}
|
||||
<input v-model.number="center" type="number" /></label
|
||||
></template>
|
||||
<button class="button button--flat" @click="reset">
|
||||
{{ t("documents.reset") }}
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
<p v-if="volumeError" role="alert" class="document-error">
|
||||
{{ volumeError }}
|
||||
</p>
|
||||
<p v-if="volumeLoading" role="status">
|
||||
{{ t("documents.loading3d", { count: loaded, total: series.length }) }}
|
||||
<button class="button button--flat" @click="closeVolume">
|
||||
{{ t("buttons.cancel") }}
|
||||
</button>
|
||||
</p>
|
||||
<DicomVolumeViewer v-if="volume" :volume="volume" @failed="volumeFailed" />
|
||||
<p v-if="error" role="alert" class="document-error">{{ error }}</p>
|
||||
<p v-else-if="!ready">{{ t("files.loading") }}</p>
|
||||
<div v-show="!volume && !volumeLoading" class="document-stage">
|
||||
<canvas
|
||||
v-show="ready && !error"
|
||||
ref="canvas"
|
||||
:aria-label="t('documents.dicomImage')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
defineAsyncComponent,
|
||||
nextTick,
|
||||
onBeforeUnmount,
|
||||
ref,
|
||||
shallowRef,
|
||||
watch,
|
||||
} from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import DicomWorker from "@/utils/dicom.worker?worker";
|
||||
import { readDicomFile } from "@/utils/dicom-file";
|
||||
import { findDicomSeries } from "@/utils/dicom-context";
|
||||
import { loadDicomVolume } from "@/utils/dicom-volume";
|
||||
import type { DicomSource, DicomVolume } from "@/utils/dicom-series";
|
||||
import { DICOM_3D_ENABLED } from "@/utils/dicom-series";
|
||||
const DicomVolumeViewer = defineAsyncComponent({
|
||||
loader: () => import("./DicomVolumeViewer.vue"),
|
||||
onError: (_error, _retry, fail) => {
|
||||
volumeFailed();
|
||||
fail();
|
||||
},
|
||||
});
|
||||
const props = defineProps<{ source: string; resource?: Resource }>();
|
||||
const { t } = useI18n();
|
||||
const auth = useAuthStore();
|
||||
const series = shallowRef<DicomSource[]>([]),
|
||||
volume = shallowRef<DicomVolume>();
|
||||
const volumeLoading = ref(false),
|
||||
volumeError = ref(""),
|
||||
loaded = ref(0);
|
||||
let seriesController: AbortController | undefined,
|
||||
volumeController: AbortController | undefined;
|
||||
function closeVolume() {
|
||||
volumeController?.abort();
|
||||
volumeController = undefined;
|
||||
volume.value = undefined;
|
||||
volumeLoading.value = false;
|
||||
}
|
||||
function volumeFailed() {
|
||||
closeVolume();
|
||||
volumeError.value = t("documents.volumeUnavailable");
|
||||
}
|
||||
async function openVolume() {
|
||||
if (!DICOM_3D_ENABLED) return;
|
||||
closeVolume();
|
||||
volumeError.value = "";
|
||||
const probe = document.createElement("canvas");
|
||||
const gl = probe.getContext("webgl2");
|
||||
if (!gl) {
|
||||
volumeFailed();
|
||||
return;
|
||||
}
|
||||
gl.getExtension("WEBGL_lose_context")?.loseContext();
|
||||
const request = (volumeController = new AbortController());
|
||||
volumeLoading.value = true;
|
||||
loaded.value = 0;
|
||||
try {
|
||||
const result = await loadDicomVolume(
|
||||
series.value,
|
||||
request.signal,
|
||||
(count) => {
|
||||
loaded.value = count;
|
||||
},
|
||||
auth.user?.dicom3D
|
||||
);
|
||||
if (!request.signal.aborted) volume.value = result;
|
||||
} catch (e) {
|
||||
if (!request.signal.aborted)
|
||||
volumeError.value = t(
|
||||
e instanceof Error &&
|
||||
["DICOM_VOLUME_LIMIT", "DICOM_TOO_LARGE"].includes(e.message)
|
||||
? "documents.volumeLimit"
|
||||
: "documents.volumeInvalid"
|
||||
);
|
||||
} finally {
|
||||
if (volumeController === request) volumeLoading.value = false;
|
||||
}
|
||||
}
|
||||
watch(
|
||||
() => props.resource,
|
||||
async (resource) => {
|
||||
seriesController?.abort();
|
||||
closeVolume();
|
||||
volumeError.value = "";
|
||||
series.value = [];
|
||||
if (!resource || !DICOM_3D_ENABLED) return;
|
||||
const request = (seriesController = new AbortController());
|
||||
try {
|
||||
const found = await findDicomSeries(resource, request.signal);
|
||||
if (!request.signal.aborted) series.value = found;
|
||||
} catch {
|
||||
/* A file-only share or denied parent must not reveal siblings. */
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
const canvas = ref<HTMLCanvasElement>();
|
||||
const ready = ref(false),
|
||||
error = ref(""),
|
||||
frame = ref(1),
|
||||
frames = ref(1),
|
||||
color = ref(false);
|
||||
const center = ref(0),
|
||||
width = ref(1);
|
||||
let worker: Worker | undefined, controller: AbortController | undefined;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined,
|
||||
timeout: ReturnType<typeof setTimeout> | undefined;
|
||||
let sequence = 0,
|
||||
defaults = { center: 0, width: 1 };
|
||||
function stop() {
|
||||
controller?.abort();
|
||||
worker?.terminate();
|
||||
worker = undefined;
|
||||
clearTimeout(timer);
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
function reset() {
|
||||
center.value = defaults.center;
|
||||
width.value = defaults.width;
|
||||
frame.value = 1;
|
||||
}
|
||||
function render() {
|
||||
if (
|
||||
!worker ||
|
||||
!ready.value ||
|
||||
!Number.isInteger(frame.value) ||
|
||||
frame.value < 1 ||
|
||||
frame.value > frames.value ||
|
||||
!Number.isFinite(center.value) ||
|
||||
!Number.isFinite(width.value) ||
|
||||
width.value < 1
|
||||
)
|
||||
return;
|
||||
worker.postMessage({
|
||||
id: ++sequence,
|
||||
frame: frame.value - 1,
|
||||
center: center.value,
|
||||
width: width.value,
|
||||
});
|
||||
}
|
||||
watch([frame, center, width], () => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(render, 100);
|
||||
});
|
||||
watch(
|
||||
() => props.source,
|
||||
async (source) => {
|
||||
stop();
|
||||
const id = ++sequence;
|
||||
ready.value = false;
|
||||
error.value = "";
|
||||
frame.value = 1;
|
||||
controller = new AbortController();
|
||||
const signal = controller.signal;
|
||||
try {
|
||||
const buffer = await readDicomFile(source, signal);
|
||||
if (signal.aborted || id !== sequence) return;
|
||||
worker = new DicomWorker();
|
||||
timeout = setTimeout(() => {
|
||||
error.value = t("documents.loadFailed");
|
||||
worker?.terminate();
|
||||
}, 30000);
|
||||
worker.onerror = () => {
|
||||
clearTimeout(timeout);
|
||||
error.value = t("documents.loadFailed");
|
||||
worker?.terminate();
|
||||
};
|
||||
worker.onmessage = async ({ data: result }) => {
|
||||
if (result.id !== sequence) return;
|
||||
clearTimeout(timeout);
|
||||
if (result.error) {
|
||||
error.value = `${t("documents.loadFailed")}: ${result.error}`;
|
||||
return;
|
||||
}
|
||||
if (!ready.value) {
|
||||
defaults = { center: result.center, width: result.width };
|
||||
center.value = result.center;
|
||||
width.value = result.width;
|
||||
frames.value = result.frames;
|
||||
color.value = result.color;
|
||||
ready.value = true;
|
||||
}
|
||||
await nextTick();
|
||||
const target = canvas.value;
|
||||
if (!target || result.id !== sequence) return;
|
||||
target.width = result.cols;
|
||||
target.height = result.rows;
|
||||
target
|
||||
.getContext("2d")
|
||||
?.putImageData(
|
||||
new ImageData(result.rgba, result.cols, result.rows),
|
||||
0,
|
||||
0
|
||||
);
|
||||
};
|
||||
worker.postMessage({ id, buffer }, [buffer]);
|
||||
} catch (e) {
|
||||
if (!signal.aborted && id === sequence)
|
||||
error.value =
|
||||
e instanceof Error && e.message === "DICOM_TOO_LARGE"
|
||||
? t("documents.tooLarge")
|
||||
: e instanceof Error
|
||||
? e.message
|
||||
: t("documents.loadFailed");
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
onBeforeUnmount(() => {
|
||||
stop();
|
||||
closeVolume();
|
||||
seriesController?.abort();
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,346 @@
|
||||
<template>
|
||||
<div class="dicom-volume">
|
||||
<div class="document-tools">
|
||||
<button
|
||||
v-for="view in views"
|
||||
:key="view"
|
||||
class="button button--flat"
|
||||
:aria-pressed="mode === view"
|
||||
@click="switchView(view)"
|
||||
>
|
||||
{{ view === "3d" ? "3D" : t(`documents.${view}`) }}
|
||||
</button>
|
||||
<template>
|
||||
<label
|
||||
>{{ t("documents.window") }}
|
||||
<input v-model.number="width" type="number" min="1"
|
||||
/></label>
|
||||
<label
|
||||
>{{ t("documents.level") }}
|
||||
<input v-model.number="center" type="number"
|
||||
/></label>
|
||||
</template>
|
||||
<template v-if="mode === '3d'">
|
||||
<label
|
||||
>{{ t("documents.opacity") }}
|
||||
<input
|
||||
v-model.number="opacity"
|
||||
type="range"
|
||||
min="0.05"
|
||||
max="1"
|
||||
step="0.05"
|
||||
/></label>
|
||||
</template>
|
||||
<button class="button button--flat" @click="reset">
|
||||
{{ t("documents.reset") }}
|
||||
</button>
|
||||
</div>
|
||||
<p class="dicom-volume-hint">
|
||||
{{ t(mode === "3d" ? "documents.volumeHint" : "documents.sliceHint") }}
|
||||
<span v-if="volume.sampling && volume.sampling.factor > 1">
|
||||
·
|
||||
{{
|
||||
t("documents.reduced3d", {
|
||||
factor: volume.sampling.factor,
|
||||
width: volume.dimensions[0],
|
||||
height: volume.dimensions[1],
|
||||
slices: volume.dimensions[2],
|
||||
})
|
||||
}}</span
|
||||
>
|
||||
</p>
|
||||
<div
|
||||
ref="element"
|
||||
class="dicom-volume-stage"
|
||||
@wheel.prevent="wheel"
|
||||
@pointerdown="pointerDown"
|
||||
@pointermove="pointerMove"
|
||||
@pointerup="pointerUp"
|
||||
@pointercancel="pointerUp"
|
||||
@contextmenu.prevent
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import * as core from "@cornerstonejs/core";
|
||||
import type { DicomVolume } from "@/utils/dicom-series";
|
||||
const props = defineProps<{ volume: DicomVolume }>();
|
||||
const emit = defineEmits<{ failed: [] }>();
|
||||
const { t } = useI18n();
|
||||
const element = ref<HTMLDivElement>();
|
||||
const views = ["3d", "axial", "sagittal", "coronal"] as const;
|
||||
type Mode = (typeof views)[number];
|
||||
const mode = ref<Mode>("3d"),
|
||||
center = ref(props.volume.first.center),
|
||||
width = ref(props.volume.first.width),
|
||||
opacity = ref(props.volume.opacity ?? 0.3);
|
||||
const id = `fs-dicom-${crypto.getRandomValues(new Uint32Array(2)).join("-")}`;
|
||||
const viewportID = `${id}-viewport`;
|
||||
let engine: InstanceType<typeof core.RenderingEngine> | undefined;
|
||||
let observer: ResizeObserver | undefined,
|
||||
disposed = false,
|
||||
changing = false;
|
||||
let drag: { id: number; x: number; y: number } | undefined;
|
||||
let frame = 0;
|
||||
const viewport = () => engine?.getViewport<core.BaseVolumeViewport>(viewportID);
|
||||
function schedule() {
|
||||
if (!frame)
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = 0;
|
||||
engine?.render();
|
||||
});
|
||||
}
|
||||
function applyWindow() {
|
||||
if (
|
||||
Number.isFinite(width.value) &&
|
||||
width.value >= 1 &&
|
||||
Number.isFinite(center.value)
|
||||
) {
|
||||
viewport()?.setProperties({
|
||||
...(mode.value === "3d" && { colormap: volumeColormap() }),
|
||||
voiRange: {
|
||||
lower: center.value - width.value / 2,
|
||||
upper: center.value + width.value / 2,
|
||||
},
|
||||
});
|
||||
schedule();
|
||||
}
|
||||
}
|
||||
function volumeColormap() {
|
||||
return {
|
||||
opacity: opacity.value,
|
||||
opacityMapping: [
|
||||
{ value: center.value - width.value / 2, opacity: 0 },
|
||||
{ value: center.value + width.value / 2, opacity: 1 },
|
||||
],
|
||||
};
|
||||
}
|
||||
watch([center, width, opacity], applyWindow);
|
||||
async function switchView(value: Mode) {
|
||||
if (!engine || !element.value || disposed || changing) return;
|
||||
changing = true;
|
||||
try {
|
||||
mode.value = value;
|
||||
engine.setViewports([
|
||||
{
|
||||
viewportId: viewportID,
|
||||
type:
|
||||
value === "3d"
|
||||
? core.Enums.ViewportType.VOLUME_3D
|
||||
: core.Enums.ViewportType.ORTHOGRAPHIC,
|
||||
element: element.value,
|
||||
defaultOptions: {
|
||||
background: [0, 0, 0],
|
||||
orientation:
|
||||
value === "sagittal"
|
||||
? core.Enums.OrientationAxis.SAGITTAL
|
||||
: value === "coronal"
|
||||
? core.Enums.OrientationAxis.CORONAL
|
||||
: core.Enums.OrientationAxis.AXIAL,
|
||||
},
|
||||
},
|
||||
]);
|
||||
await core.setVolumesForViewports(engine, [{ volumeId: id }], [viewportID]);
|
||||
if (disposed) return;
|
||||
viewport()?.resetCamera();
|
||||
if (value === "3d")
|
||||
viewport()?.setProperties({
|
||||
colormap: volumeColormap(),
|
||||
voiRange: {
|
||||
lower: center.value - width.value / 2,
|
||||
upper: center.value + width.value / 2,
|
||||
},
|
||||
sampleDistanceMultiplier: 2,
|
||||
});
|
||||
else applyWindow();
|
||||
engine.render();
|
||||
} catch {
|
||||
if (!disposed) emit("failed");
|
||||
} finally {
|
||||
changing = false;
|
||||
}
|
||||
}
|
||||
function reset() {
|
||||
center.value = props.volume.first.center;
|
||||
width.value = props.volume.first.width;
|
||||
opacity.value = props.volume.opacity ?? 0.3;
|
||||
viewport()?.resetCamera();
|
||||
schedule();
|
||||
}
|
||||
function wheel(event: WheelEvent) {
|
||||
const view = viewport();
|
||||
if (!view || changing) return;
|
||||
if (mode.value !== "3d" && !event.ctrlKey)
|
||||
view.scroll(event.deltaY > 0 ? 1 : -1);
|
||||
else
|
||||
view.setZoom(
|
||||
Math.max(
|
||||
0.1,
|
||||
Math.min(20, view.getZoom() * (event.deltaY > 0 ? 0.9 : 1.1))
|
||||
)
|
||||
);
|
||||
schedule();
|
||||
}
|
||||
function pointerDown(event: PointerEvent) {
|
||||
if (event.button !== 0 || !viewport()) return;
|
||||
drag = { id: event.pointerId, x: event.clientX, y: event.clientY };
|
||||
element.value?.setPointerCapture(event.pointerId);
|
||||
}
|
||||
// Rodrigues rotation around the camera's axes keeps oblique patient geometry intact.
|
||||
function rotate(
|
||||
vector: number[],
|
||||
axis: number[],
|
||||
angle: number
|
||||
): [number, number, number] {
|
||||
const length = Math.hypot(...axis),
|
||||
a = axis.map((v) => v / length),
|
||||
c = Math.cos(angle),
|
||||
s = Math.sin(angle);
|
||||
const dot = vector.reduce((n, v, i) => n + v * a[i], 0);
|
||||
const cross = [
|
||||
a[1] * vector[2] - a[2] * vector[1],
|
||||
a[2] * vector[0] - a[0] * vector[2],
|
||||
a[0] * vector[1] - a[1] * vector[0],
|
||||
];
|
||||
return vector.map((v, i) => v * c + cross[i] * s + a[i] * dot * (1 - c)) as [
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
];
|
||||
}
|
||||
function pointerMove(event: PointerEvent) {
|
||||
const view = viewport();
|
||||
if (!drag || drag.id !== event.pointerId || !view || changing) return;
|
||||
const dx = event.clientX - drag.x,
|
||||
dy = event.clientY - drag.y;
|
||||
drag.x = event.clientX;
|
||||
drag.y = event.clientY;
|
||||
if (mode.value === "3d") {
|
||||
const camera = view.getCamera(),
|
||||
up = camera.viewUp!,
|
||||
focus = camera.focalPoint!,
|
||||
position = camera.position!;
|
||||
let offset = position.map((v, i) => v - focus[i]);
|
||||
offset = rotate(offset, up, -dx * 0.008);
|
||||
const right = [
|
||||
up[1] * offset[2] - up[2] * offset[1],
|
||||
up[2] * offset[0] - up[0] * offset[2],
|
||||
up[0] * offset[1] - up[1] * offset[0],
|
||||
];
|
||||
offset = rotate(offset, right, -dy * 0.008);
|
||||
view.setCamera({
|
||||
position: offset.map((v, i) => v + focus[i]) as [number, number, number],
|
||||
viewUp: rotate(up, right, -dy * 0.008),
|
||||
});
|
||||
} else {
|
||||
const pan = view.getPan();
|
||||
view.setPan([pan[0] + dx, pan[1] + dy]);
|
||||
}
|
||||
schedule();
|
||||
}
|
||||
function pointerUp() {
|
||||
drag = undefined;
|
||||
}
|
||||
onMounted(async () => {
|
||||
try {
|
||||
core.init({ rendering: { useGenericViewport: false }, debug: {} });
|
||||
if (core.getShouldUseCPURendering()) throw new Error("WebGL2 unavailable");
|
||||
const { first, scalarData, dimensions, spacing, origin, direction } =
|
||||
props.volume;
|
||||
core.volumeLoader.createLocalVolume(id, {
|
||||
scalarData,
|
||||
dimensions,
|
||||
spacing,
|
||||
origin,
|
||||
direction,
|
||||
metadata: {
|
||||
BitsAllocated: 32,
|
||||
BitsStored: 32,
|
||||
HighBit: 31,
|
||||
SamplesPerPixel: 1,
|
||||
PixelRepresentation: 1,
|
||||
PhotometricInterpretation: "MONOCHROME2",
|
||||
Modality: first.modality,
|
||||
FrameOfReferenceUID: first.reference,
|
||||
SeriesInstanceUID: first.series,
|
||||
Columns: first.cols,
|
||||
Rows: first.rows,
|
||||
ImageOrientationPatient: first.orientation,
|
||||
PixelSpacing: first.spacing,
|
||||
voiLut: [],
|
||||
VOILUTFunction: "LINEAR",
|
||||
},
|
||||
});
|
||||
engine = new core.RenderingEngine(id);
|
||||
await switchView("3d");
|
||||
if (disposed) return;
|
||||
observer = new ResizeObserver(() => {
|
||||
if (!disposed) {
|
||||
engine?.resize(true, true);
|
||||
}
|
||||
});
|
||||
observer.observe(element.value!);
|
||||
} catch {
|
||||
if (!disposed) emit("failed");
|
||||
}
|
||||
});
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true;
|
||||
observer?.disconnect();
|
||||
cancelAnimationFrame(frame);
|
||||
engine?.destroy();
|
||||
engine = undefined;
|
||||
const volume = core.cache.getVolume(id);
|
||||
// Also remove slices if allocation failed before the volume entered the cache.
|
||||
const images = Array.from(
|
||||
{ length: props.volume.dimensions[2] },
|
||||
(_, i) => `${id}_slice_${i}`
|
||||
);
|
||||
if (volume) {
|
||||
volume.vtkOpenGLTexture.releaseGraphicsResources();
|
||||
volume.vtkOpenGLTexture.delete();
|
||||
core.cache.removeVolumeLoadObject(id);
|
||||
volume.voxelManager?.clear();
|
||||
}
|
||||
for (const image of images)
|
||||
if (core.cache.getImage(image))
|
||||
core.cache.removeImageLoadObject(image, { force: true });
|
||||
});
|
||||
</script>
|
||||
<style scoped>
|
||||
.dicom-volume {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.dicom-volume-stage {
|
||||
flex: 1;
|
||||
min-height: 240px;
|
||||
position: relative;
|
||||
width: 100%;
|
||||
background: #000;
|
||||
touch-action: none;
|
||||
}
|
||||
.dicom-volume-hint {
|
||||
font-size: 12px;
|
||||
margin: 8px 12px;
|
||||
text-align: center;
|
||||
}
|
||||
button[aria-pressed="true"] {
|
||||
background: var(--surfaceSecondary);
|
||||
color: var(--primaryColor);
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.document-tools {
|
||||
gap: 5px;
|
||||
padding: 6px;
|
||||
}
|
||||
.document-tools input {
|
||||
width: 65px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,12 @@
|
||||
<template>
|
||||
<div class="resource-epub">
|
||||
<VueReader
|
||||
:url="source"
|
||||
:epubOptions="{ allowScriptedContent: false, allowPopups: false }"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { VueReader } from "vue-reader";
|
||||
defineProps<{ source: string }>();
|
||||
</script>
|
||||
@@ -10,7 +10,12 @@
|
||||
@mouseup="mouseUp"
|
||||
@wheel="wheelMove"
|
||||
>
|
||||
<img class="image-ex-img image-ex-img-center" ref="imgex" @load="onLoad" />
|
||||
<img
|
||||
class="image-ex-img image-ex-img-center"
|
||||
ref="imgex"
|
||||
@load="onLoad"
|
||||
@error="emit('error')"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
@@ -25,11 +30,13 @@ interface IProps {
|
||||
zoomStep?: number;
|
||||
}
|
||||
|
||||
const pendingImages = new Set<XMLHttpRequest>();
|
||||
const props = withDefaults(defineProps<IProps>(), {
|
||||
moveDisabledTime: () => 200,
|
||||
classList: () => [],
|
||||
zoomStep: () => 0.25,
|
||||
});
|
||||
const emit = defineEmits<{ (event: "error"): void }>();
|
||||
|
||||
const scale = ref<number>(1);
|
||||
const lastX = ref<number | null>(null);
|
||||
@@ -82,6 +89,15 @@ onMounted(() => {
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
for (const xhr of pendingImages) {
|
||||
xhr.abort();
|
||||
const i = UTIF._xhrs.indexOf(xhr);
|
||||
if (i >= 0) {
|
||||
UTIF._xhrs.splice(i, 1);
|
||||
UTIF._imgs.splice(i, 1);
|
||||
}
|
||||
}
|
||||
pendingImages.clear();
|
||||
window.removeEventListener("resize", onResize);
|
||||
document.removeEventListener("mouseup", onMouseUp);
|
||||
});
|
||||
@@ -113,11 +129,15 @@ const decodeUTIF = () => {
|
||||
|
||||
if (sufs.indexOf(suff) == -1) return false;
|
||||
const xhr = new XMLHttpRequest();
|
||||
pendingImages.add(xhr);
|
||||
UTIF._xhrs.push(xhr);
|
||||
UTIF._imgs.push(imgex.value);
|
||||
xhr.open("GET", props.src);
|
||||
xhr.responseType = "arraybuffer";
|
||||
xhr.onload = UTIF._imgLoaded;
|
||||
xhr.onload = (event) => {
|
||||
pendingImages.delete(xhr);
|
||||
UTIF._imgLoaded(event);
|
||||
};
|
||||
xhr.send();
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
<template>
|
||||
<svg
|
||||
class="app-icon file-icon"
|
||||
:class="`file-icon--${icon.kind}`"
|
||||
viewBox="0 0 32 32"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<template v-if="!directory">
|
||||
<path
|
||||
d="M6 2h14l7 7v19a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2z"
|
||||
fill="currentColor"
|
||||
fill-opacity=".09"
|
||||
/>
|
||||
<path d="M20 2v7h7" fill="currentColor" fill-opacity=".18" />
|
||||
</template>
|
||||
<path
|
||||
:d="icon.path"
|
||||
:fill="directory ? 'currentColor' : 'none'"
|
||||
:fill-opacity="directory ? '.16' : undefined"
|
||||
/>
|
||||
<text
|
||||
v-if="!directory"
|
||||
x="15.5"
|
||||
y="27"
|
||||
text-anchor="middle"
|
||||
fill="currentColor"
|
||||
stroke="none"
|
||||
font-size="4.5"
|
||||
font-weight="750"
|
||||
letter-spacing=".25"
|
||||
font-family="system-ui, sans-serif"
|
||||
>
|
||||
{{ icon.label }}
|
||||
</text>
|
||||
</svg>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { fileIcon } from "@/utils/file-icons";
|
||||
const props = defineProps<{ name: string; directory?: boolean }>();
|
||||
const icon = computed(() => fileIcon(props.name, props.directory));
|
||||
</script>
|
||||
@@ -1,6 +1,8 @@
|
||||
<template>
|
||||
<div
|
||||
class="item"
|
||||
ref="itemElement"
|
||||
:class="{ 'has-thumbnail': showThumbnail }"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
:draggable="isDraggable"
|
||||
@@ -22,13 +24,16 @@
|
||||
:data-ext="getExtension(name).toLowerCase()"
|
||||
@contextmenu="contextMenu"
|
||||
>
|
||||
<div>
|
||||
<div class="file-symbol">
|
||||
<FileIcon v-if="isDicom" :name="name" />
|
||||
<img
|
||||
v-if="!readOnly && type === 'image' && isThumbsEnabled"
|
||||
v-lazy="thumbnailUrl"
|
||||
:alt="name"
|
||||
v-else-if="showThumbnail && thumbnailVisible && !thumbnailFailed"
|
||||
:src="thumbnailUrl"
|
||||
alt=""
|
||||
decoding="async"
|
||||
@error="thumbnailFailed = true"
|
||||
/>
|
||||
<i v-else class="material-icons"></i>
|
||||
<FileIcon v-else :name="name" :directory="isDir" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
@@ -45,6 +50,8 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useAddonsStore } from "@/stores/addons";
|
||||
import { defaultCraftTool, openCraftTab } from "@/utils/craft";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { useFileStore } from "@/stores/file";
|
||||
import { useLayoutStore } from "@/stores/layout";
|
||||
@@ -54,7 +61,8 @@ import { filesize } from "@/utils";
|
||||
import dayjs from "dayjs";
|
||||
import { files as api } from "@/api";
|
||||
import * as upload from "@/utils/upload";
|
||||
import { computed, inject, ref } from "vue";
|
||||
import { computed, inject, ref, watch, onMounted, onBeforeUnmount } from "vue";
|
||||
import FileIcon from "./FileIcon.vue";
|
||||
import { useRouter } from "vue-router";
|
||||
|
||||
const touches = ref<number>(0);
|
||||
@@ -81,6 +89,7 @@ const props = defineProps<{
|
||||
}>();
|
||||
|
||||
const authStore = useAuthStore();
|
||||
const addons = useAddonsStore();
|
||||
const fileStore = useFileStore();
|
||||
const layoutStore = useLayoutStore();
|
||||
|
||||
@@ -116,7 +125,52 @@ const thumbnailUrl = computed(() => {
|
||||
});
|
||||
|
||||
const isThumbsEnabled = computed(() => {
|
||||
return enableThumbs;
|
||||
return enableThumbs && !authStore.user?.hidePreviews;
|
||||
});
|
||||
const isDicom = computed(() => /\.(dcm|dicom)$/i.test(props.name));
|
||||
const showThumbnail = computed(
|
||||
() =>
|
||||
!props.readOnly &&
|
||||
!props.isDir &&
|
||||
props.type === "image" &&
|
||||
!isDicom.value &&
|
||||
isThumbsEnabled.value
|
||||
);
|
||||
const thumbnailFailed = ref(false),
|
||||
thumbnailVisible = ref(false);
|
||||
const itemElement = ref<HTMLElement>();
|
||||
let thumbnailObserver: IntersectionObserver | undefined;
|
||||
function observeThumbnail() {
|
||||
thumbnailObserver?.disconnect();
|
||||
if (!showThumbnail.value || !itemElement.value) return;
|
||||
if (typeof IntersectionObserver === "undefined") {
|
||||
thumbnailVisible.value = true;
|
||||
return;
|
||||
}
|
||||
thumbnailObserver = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (entries.some((entry) => entry.isIntersecting)) {
|
||||
thumbnailVisible.value = true;
|
||||
thumbnailObserver?.disconnect();
|
||||
}
|
||||
},
|
||||
{ rootMargin: "150px" }
|
||||
);
|
||||
thumbnailObserver.observe(itemElement.value);
|
||||
}
|
||||
watch(
|
||||
[thumbnailUrl, showThumbnail],
|
||||
() => {
|
||||
thumbnailFailed.value = false;
|
||||
thumbnailVisible.value = false;
|
||||
observeThumbnail();
|
||||
},
|
||||
{ flush: "post" }
|
||||
);
|
||||
onMounted(observeThumbnail);
|
||||
onBeforeUnmount(() => {
|
||||
thumbnailObserver?.disconnect();
|
||||
cancelLongPress();
|
||||
});
|
||||
|
||||
const humanSize = () => {
|
||||
@@ -276,9 +330,12 @@ const click = (event: Event | KeyboardEvent) => {
|
||||
touches.value = 0;
|
||||
}, 300);
|
||||
|
||||
touches.value++;
|
||||
if (touches.value > 1) {
|
||||
open();
|
||||
if (!(event instanceof MouseEvent) || event.button === 0) {
|
||||
touches.value++;
|
||||
if (touches.value > 1) {
|
||||
touches.value = 0;
|
||||
open();
|
||||
}
|
||||
}
|
||||
|
||||
if (fileStore.selected.indexOf(props.index) !== -1) {
|
||||
@@ -326,6 +383,17 @@ const click = (event: Event | KeyboardEvent) => {
|
||||
};
|
||||
|
||||
const open = () => {
|
||||
const tool =
|
||||
!props.readOnly &&
|
||||
!props.isDir &&
|
||||
authStore.user?.perm.modify &&
|
||||
authStore.user?.perm.download
|
||||
? defaultCraftTool(addons.items, props.name, props.type)
|
||||
: undefined;
|
||||
if (tool) {
|
||||
openCraftTab(router, tool.id, props.url);
|
||||
return;
|
||||
}
|
||||
router.push({ path: props.url });
|
||||
};
|
||||
|
||||
|
||||