Compare commits

...
57 Commits
Author SHA1 Message Date
SantaSpeen 9f777bafbc fix: refresh browser tab icon URLs to bypass legacy favicon cache 2026-10-25 21:45:15 +03:00
SantaSpeen be4a1ac807 fix: match browser and app icons to workspace folder branding 2026-10-25 21:37:56 +03:00
SantaSpeen 55f2474660 fix: make workspace navigation atomic and return home on account switch 2026-10-25 21:19:10 +03:00
SantaSpeen c02bf755f2 feat: adopt shared internal SSO sessions and add no-sso launch mode 2026-10-24 15:41:39 +03:00
SantaSpeen c209f1effc feat: polish workspace transfers and verify Craft server file workflows 2026-10-24 02:01:28 +03:00
SantaSpeen 7fd7ae6733 Add profile 3D preferences and adapt DICOM preview resolution to memory budget 2026-10-22 22:29:28 +03:00
SantaSpeen 705762d57c Raise source and decoded DICOM series limits to 1.5 GiB 2026-10-22 22:15:16 +03:00
SantaSpeen 86dc0e8d95 Log DICOM series sizes and exact volume limit failures 2026-10-22 22:12:56 +03:00
SantaSpeen 68a6801690 Raise DICOM volume limit to 1 GiB and simplify image controls 2026-10-22 21:58:43 +03:00
SantaSpeen 6873f04bfb Fix embedded preview chunks and serve JavaScript without gzip copies 2026-10-22 21:50:55 +03:00
SantaSpeen 6d8faa7d03 Add scoped DICOM series previews with 3D volume and MPR views 2026-10-22 21:06:46 +03:00
SantaSpeen 7371c29111 Fix DeckCraft WASM startup and prefer built-in file previews 2026-10-22 20:16:12 +03:00
SantaSpeen 852140c3a7 Integrate graphics, RAW, audio and CAD Craft tools with protected saves 2026-10-22 19:48:16 +03:00
SantaSpeen 6e36b6c4b7 Add WordCraft and DeckCraft office editors with protected server saves 2026-10-22 19:25:22 +03:00
SantaSpeen bc9709e500 Open Craft editors in standalone tabs and improve addon settings 2026-10-22 19:02:35 +03:00
SantaSpeen 5cb1b463ea Add managed Craft addons with secure installation and document editing 2026-10-22 18:46:46 +03:00
SantaSpeen 1afa755d4f Open create submenu beside context menu and distinguish rename icons 2026-10-22 16:28:41 +03:00
SantaSpeen c05293a948 Rename administrative settings to control panel 2026-10-22 16:16:33 +03:00
SantaSpeen ab7b77de39 Use settings gear for personal settings menu item 2026-10-22 16:14:29 +03:00
SantaSpeen 54761e4ef2 Move settings navigation to account menu and add file creation templates 2026-10-22 16:07:59 +03:00
SantaSpeen 042392f611 Redesign file context menus and download archives using global preference 2026-10-22 15:35:25 +03:00
SantaSpeen 6aca927851 Add expressive unified file icons for popular extension families 2026-10-22 15:19:41 +03:00
SantaSpeen d8bdf5f390 Preserve SVG icon drawing size when action padding is applied 2026-10-22 15:07:36 +03:00
SantaSpeen 2366035c72 Modernize icons and file previews; add bounded ZIP directory viewer 2026-10-22 14:24:50 +03:00
SantaSpeen 9110c8a9d5 fix: align settings, modernize notifications and remove branding overrides 2026-10-22 13:17:18 +03:00
SantaSpeen d3d164910b feat: refresh settings, sync account avatars and link account management 2026-10-22 12:52:37 +03:00
SantaSpeen fa1832dfa7 feat: add explorer sidebar, account menu and preview preferences 2026-10-22 12:33:16 +03:00
SantaSpeen b87f8cb961 fix: widen file information and decode DICOM text encodings 2026-10-22 11:20:33 +03:00
SantaSpeen a69fdf2e09 feat: fit DICOM previews and show searchable file metadata 2026-10-22 11:07:27 +03:00
SantaSpeen 7a1d18dfc6 fix: initialize DICOM decoder modules in browser workers 2026-10-22 01:34:55 +03:00
SantaSpeen dd29258828 feat: add local DICOM and canvas PDF previews 2026-10-22 01:25:48 +03:00
SantaSpeen b569f68300 ui: use compact table in share dialog 2026-10-22 01:04:58 +03:00
SantaSpeen 7fc7465f71 feat: simplify public shares and add compact link management 2026-10-22 00:58:05 +03:00
SantaSpeen 5dda0dc5f3 fix: redesign share management and remove public QR codes 2026-10-22 00:37:34 +03:00
SantaSpeen 618fccd7bb fix: align share actions and collapse advanced options 2026-10-21 22:28:46 +03:00
SantaSpeen a0de540dbd fix: retain active identity when upgrading duplicate SSO records 2026-10-21 21:49:39 +03:00
SantaSpeen bd9bf33bc9 fix: preserve SSO identities and polish sharing interface 2026-10-21 21:47:13 +03:00
SantaSpeen 2e3b56f250 docs: tidy generated setup command reference 2026-10-21 20:58:16 +03:00
SantaSpeen 87bc33e675 feat: add SSO workspace, named shares and Debian release tooling 2026-10-21 20:57:44 +03:00
Henrique Dias 833d908884 docs: update post link 2026-07-28 07:53:06 +02:00
Henrique Dias 1cd18d7ead docs: include issue summary in readme 2026-07-27 22:04:46 +02:00
Henrique Dias e8a388f840 chore(release): 2.63.23 2026-07-27 21:50:03 +02:00
Henrique Dias 0dfe44649c docs: cleanup header 2026-07-27 21:49:14 +02:00
Henrique Dias 05ee853eef docs: clear inconsistencies, point at repo instead of website 2026-07-27 21:47:58 +02:00
Henrique Dias afeb478ee1 chore(release): 2.63.22 2026-07-27 17:29:26 +02:00
Henrique Dias df2869993a chore: remove renovate.json 2026-07-27 17:29:12 +02:00
transifex-integration[bot] d49ab67904 chore: update translations 2026-07-27 17:24:27 +02:00
superafun cfff84306a fix: use absolute URLs for the PWA manifest icon sources (#6032) 2026-07-27 17:23:54 +02:00
Henrique Dias 72faf6dd3c fix: enforce rules on recursive operations and expired proxy tokens (#6053) 2026-07-27 17:16:58 +02:00
superafun a789f29cee fix: make the sidebar scrollable when content overflows (#6031) 2026-07-27 17:10:57 +02:00
Henrique Dias 74b13db3fa docs: fix date 2026-07-27 17:02:02 +02:00
Henrique Dias 773b30102c docs: add wind down notice 2026-07-27 16:58:50 +02:00
Henrique Dias 0b925cbca9 fix: unblock stalled and frozen uploads
A TUS PATCH rejected before its body was read left the client still streaming
a chunk. net/http gives up draining an unread request body after 256KiB and
then closes the connection, so the status we replied with was lost and the
browser saw a bare transport error instead. The client could not tell a
conflict from a network fault, retried blindly, and the upload stalled after
the first chunk — while curl, which reads the response as it writes, still
reported the status and appeared to work. Drain what is left of a rejected
chunk so the answer arrives on a connection that stays usable. The explicit
r.Body.Close() had to go with it: it ran before the drain, and the server
closes the request body itself once the handler returns.

Pressing Upload awaited a recursive listing of the whole destination subtree
before a single byte was sent, with no sign that anything was happening. On a
large destination that reads as a dead button, and the walk kept running after
the client gave up, then reported the failed write as a 500. A flat upload can
only collide with a direct child of the destination, so walk recursively only
for folder uploads, stop the walk once the request is done, and show the action
as busy while the destination is checked.

Along the way: a failed upload was credited as fully sent, so the progress bar
reported 100% when nothing had been written; the progress timer was recreated
without clearing the previous one; and the chunk size field threw on a value
with no unit and raced its own debounce on submit, so it appeared to refuse
every change.

Fixes #6006
Refs #5987
2026-07-27 16:28:17 +02:00
renovate[bot] 9dd7c7d099 chore(deps): update dependency postcss to v8.5.18 [security] (#6047) 2026-07-27 07:47:17 +02:00
Henrique Dias b24e43b06c chore: fix renovate.json order 2026-07-27 07:42:09 +02:00
renovate[bot] 91e68edb8c chore(deps): update dependency dompurify to v3.4.12 [security] (#6046) 2026-07-27 07:41:48 +02:00
Henrique Dias ac11538f08 chore: update renovate.json 2026-07-26 22:41:19 +02:00
378 changed files with 22685 additions and 8849 deletions

No files matched your search

-160
View File
@@ -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.
+12
View File
@@ -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
View File
@@ -1 +0,0 @@
* @filebrowser/maintainers
+2 -2
View File
@@ -10,7 +10,7 @@
Before submitting your PR, please indicate which issues are either fixed or closed by this PR. See [GitHub Help: Closing issues using keywords](https://help.github.com/articles/closing-issues-via-commit-messages/).
- [ ] I am aware the project is currently in **maintenance-only** mode and new feature requests won't be accepted. See [README](https://github.com/filebrowser/community/blob/master/README.md)
- [ ] I am aware this project is being **archived on 2026-09-01** and that no further changes will be merged, including bug fixes. See [README](https://github.com/filebrowser/filebrowser/blob/master/README.md)
- [ ] I am aware that translations MUST be made through [Transifex](https://app.transifex.com/file-browser/file-browser/) and that this PR is NOT a translation update
- [ ] I am making a PR against the `master` branch.
- [ ] I am sure File Browser can be successfully built. See [builds](https://github.com/filebrowser/community/blob/master/builds.md) and [development](https://github.com/filebrowser/community/blob/master/development.md).
- [ ] I am sure File Browser can be successfully built. See [CONTRIBUTING.md](https://github.com/filebrowser/filebrowser/blob/master/CONTRIBUTING.md).
-52
View File
@@ -1,52 +0,0 @@
name: Docs
on:
pull_request:
paths:
- 'www'
- '*.md'
push:
branches:
- master
jobs:
build:
name: Build Docs
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Install Task
uses: go-task/setup-task@v2
- name: Build site
run: task docs
build-and-release:
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
name: Build and Release Docs
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Install Task
uses: go-task/setup-task@v2
- name: Build site
run: task docs
- name: Upload static files as artifact
uses: actions/upload-pages-artifact@v5
with:
path: www/public
- name: Deploy to GitHub Pages
uses: actions/deploy-pages@v5
+8
View File
@@ -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
+9
View File
@@ -2,6 +2,15 @@
All notable changes to this project will be documented in this file. See [commit-and-tag-version](https://github.com/absolute-version/commit-and-tag-version) for commit guidelines.
## [2.63.23](https://github.com/filebrowser/filebrowser/compare/v2.63.22...v2.63.23) (2026-07-27)
## [2.63.22](https://github.com/filebrowser/filebrowser/compare/v2.63.21...v2.63.22) (2026-07-27)
### Bug Fixes
* enforce rules on recursive operations and expired proxy tokens ([#6053](https://github.com/filebrowser/filebrowser/issues/6053)) ([72faf6d](https://github.com/filebrowser/filebrowser/commit/72faf6dd3c85628e332d3e567124b86708ce2695))
* make the sidebar scrollable when content overflows ([#6031](https://github.com/filebrowser/filebrowser/issues/6031)) ([a789f29](https://github.com/filebrowser/filebrowser/commit/a789f29ceec4734e7471592921d1ce67f1a10a7e))
* unblock stalled and frozen uploads ([0b925cb](https://github.com/filebrowser/filebrowser/commit/0b925cbca940fe0b2726827cf66783da05c64f5e)), closes [#6006](https://github.com/filebrowser/filebrowser/issues/6006), references [#5987](https://github.com/filebrowser/filebrowser/issues/5987)
* use absolute URLs for the PWA manifest icon sources ([#6032](https://github.com/filebrowser/filebrowser/issues/6032)) ([cfff843](https://github.com/filebrowser/filebrowser/commit/cfff84306af66deedfdc9248300919b3ddd9a7f0))
## [2.63.21](https://github.com/filebrowser/filebrowser/compare/v2.63.20...v2.63.21) (2026-07-26)
### Bug Fixes
+8 -123
View File
@@ -1,128 +1,13 @@
# Contributing
# Сборка и разработка
If you're interested in contributing to this project, this is the best place to start. Before contributing to this project, please take a bit of time to read our [Code of Conduct](code-of-conduct.md). Also, note that this project is open-source and licensed under [Apache License 2.0](LICENSE).
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
We rely on Docker to abstract all the dependencies required for building the documentation.
To build the documentation to `www/public`:
```bash
task docs
```
To start a local server on port `8000` to view the built documentation:
```bash
task docs:serve
```
## Release
To make a release, just run:
```bash
task release
```
## Translations
Translations are managed on Transifex, which is an online website where everyone can contribute and translate strings for our project. It automatically syncs with the main language file \(in English\) and,, for you to contribute, you just need to:
1. Go to our Transifex web page: [app.transifex.com/file-browser/file-browser](https://app.transifex.com/file-browser/file-browser/)
2. Click on **Join the project** and pick your language. We'll accept you as soon as possible. If you're language is not on the list, please request it via the interface.
Translations are automatically pushed to GitHub via an integration.
## 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).
+36 -19
View File
@@ -1,31 +1,48 @@
<p align="center">
<img src="https://raw.githubusercontent.com/filebrowser/filebrowser/master/branding/banner.png" width="550"/>
</p>
# File Browser
[![Build](https://github.com/filebrowser/filebrowser/actions/workflows/ci.yaml/badge.svg)](https://github.com/filebrowser/filebrowser/actions/workflows/ci.yaml)
[![Version](https://img.shields.io/github/release/filebrowser/filebrowser.svg)](https://github.com/filebrowser/filebrowser/releases/latest)
**Ваши файлы, ссылки и браузерные инструменты — на своём сервере.**
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) · [Разработка](#сборка)
## Documentation
![Файловое пространство](docs/images/workspace.png)
Documentation on how to install, configure, and contribute to this project is hosted at [filebrowser.org](https://filebrowser.org).
[Мобильный интерфейс](docs/images/workspace-mobile.png)
## Project Status
- **Общая сессия SSO.** Текущий аккаунт и роли проверяются на сервере; переключение синхронизируется между приложениями.
- **Удобное пространство.** Дерево папок, закладки, поиск, меню действий, светлая и тёмная темы, мобильная вёрстка.
- **Мои ссылки.** Короткие адреса `/s/имя`, несколько ссылок на файл, необязательные пароль и срок действия.
- **Предпросмотр.** Изображения, PDF, DICOM 2D, текст, Markdown, CSV, книги, аудио и видео. ZIP показывает дерево без распаковки.
- **Craft-аддоны.** Установка и обновление из панели управления; совместимые редакторы открывают и сохраняют файлы на сервере.
- **Один бинарник.** Debian amd64 и Windows amd64; отдельная СУБД и Node.js для запуска не нужны.
This project is a finished product which fulfills its goal: be a single binary web File Browser which can be run by anyone anywhere. That means that File Browser is currently on **maintenance-only** mode. Therefore, please note the following:
## Запуск
- It can take a while until someone gets back to you. Please be patient.
- [Issues](https://github.com/filebrowser/filebrowser/issues) are meant to track bugs. Unrelated issues will be converted into [discussions](https://github.com/filebrowser/filebrowser/discussions).
- The priority is triaging issues, addressing security issues and reviewing pull requests meant to solve bugs.
- No new features are planned. Pull requests for new features will not be reviewed.
```sh
chmod +x filebrowser
./filebrowser init
./filebrowser
```
Please read [@hacdias' personal reflection](https://hacdias.com/2026/03/11/filebrowser/) on the project status.
На Windows: `filebrowser.exe init`, затем `filebrowser.exe`. Мастер настраивает хранилище и SSO без `.env`. Подробности, systemd и nginx — в [инструкции](docs/deployment.md).
## Contributing
Без SSO и пароля: `./filebrowser --no-sso` — все посетители получают административный доступ. [Как работает вход](docs/authentication.md).
Contributions are always welcome. To start contributing to this project, read our [guidelines](CONTRIBUTING.md) first.
## Сборка
## License
Go 1.26+, Node.js 24+, pnpm 10.33.4.
[Apache License 2.0](LICENSE) © File Browser Contributors
```sh
cd frontend
pnpm install --frozen-lockfile
pnpm run build
pnpm test
cd ..
go test ./...
go build -o filebrowser .
```
Релиз для 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).
+5 -29
View File
@@ -1,33 +1,9 @@
# Security Policy
# Безопасность
## Supported Versions
Этот репозиторий — независимый форк File Browser. Политика архивированного upstream к нему не относится.
| Version | Supported |
| ------- | --------- |
| 2.x | ✅ |
| < 2.0 | ❌ |
Ограничения и выполненные проверки: [обзор безопасности](docs/SECURITY-REVIEW.md).
## Before Reporting
При обнаружении уязвимости сообщите владельцу этого форка приватно. Укажите версию или коммит, шаги воспроизведения и влияние. Не публикуйте токены, пароли и реальные медицинские файлы.
This project is in maintenance-only mode. 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:
- Command execution, runner, and hooks (opt-in, disabled by default) — [#5199](https://github.com/filebrowser/filebrowser/issues/5199)
- Session and JWT handling — [#5216](https://github.com/filebrowser/filebrowser/issues/5216)
Reports covering these are likely to be closed as duplicates.
## Reporting a Vulnerability
- **Critical:** report privately via the [Security](https://github.com/filebrowser/filebrowser/security) page.
- **Non-critical:** open a public issue so the community can help; we'll label it as a security issue.
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
We're a volunteer effort, so responses can take a while, and we may reach out for clarification.
Для размещения в интернете используйте HTTPS и своевременно обновляйте сервер и аддоны. Наличие проверок не гарантирует отсутствия уязвимостей.
+5 -31
View File
@@ -1,14 +1,5 @@
version: '3'
vars:
SITE_DOCKER_FLAGS: >-
-v ./www:/docs
-v ./LICENSE:/docs/docs/LICENSE
-v ./SECURITY.md:/docs/docs/security.md
-v ./CHANGELOG.md:/docs/docs/changelog.md
-v ./CODE-OF-CONDUCT.md:/docs/docs/code-of-conduct.md
-v ./CONTRIBUTING.md:/docs/docs/contributing.md
tasks:
build:frontend:
desc: Build frontend assets
@@ -48,9 +39,9 @@ tasks:
desc: Create a new release
cmds:
- task: docs:cli:generate
- git add www/docs/cli
- git add docs/cli
- |
if [[ `git status www/docs/cli --porcelain` ]]; then
if [[ `git status docs/cli --porcelain` ]]; then
git commit -m 'chore(docs): update CLI documentation'
fi
- task: release:dry-run
@@ -58,26 +49,9 @@ tasks:
docs:cli:generate:
cmds:
- rm -rf www/docs/cli
- mkdir -p www/docs/cli
- rm -rf docs/cli
- mkdir -p docs/cli
- go run . docs
generates:
- www/docs/cli
- docs/cli
docs:docker:generate:
internal: true
cmds:
- docker build -f www/Dockerfile --progress=plain -t filebrowser.site www
docs:
desc: Generate documentation
cmds:
- rm -rf www/public
- task: docs:docker:generate
- docker run --rm {{.SITE_DOCKER_FLAGS}} filebrowser.site build -d "public"
docs:serve:
desc: Serve documentation
cmds:
- task: docs:docker:generate
- docker run --rm -it -p 8000:8000 {{.SITE_DOCKER_FLAGS}} filebrowser.site
+1
View File
@@ -0,0 +1 @@
+10
View File
@@ -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 }
-288
View File
@@ -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
}
-156
View File
@@ -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)
}
}
-122
View File
@@ -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
}
-24
View File
@@ -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
}
-68
View File
@@ -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
}
-142
View File
@@ -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 -4
View File
@@ -1,6 +1,3 @@
package cmd
// Execute executes the commands.
func Execute() error {
return rootCmd.Execute()
}
func Execute() error { return rootCmd.Execute() }
+2 -2
View File
@@ -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)
}
+2 -116
View File
@@ -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":
+5 -30
View File
@@ -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
}
+1 -1
View File
@@ -14,7 +14,7 @@ import (
func init() {
rootCmd.AddCommand(docsCmd)
docsCmd.Flags().String("out", "www/docs/cli", "directory to write the docs to")
docsCmd.Flags().String("out", "docs/cli", "directory to write the docs to")
}
var docsCmd = &cobra.Command{
+173
View File
@@ -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
}
+50
View File
@@ -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")
}
}
+35
View File
@@ -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")
}
}
}
+30 -83
View File
@@ -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,6 +157,8 @@ user created with the credentials from options "username" and "password".`,
}
setupLog(server.Log)
log.Println("File Browser")
root, err := filepath.Abs(server.Root)
if err != nil {
return err
@@ -237,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
@@ -246,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() {
@@ -433,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,
@@ -453,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
@@ -492,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
}
+1 -1
View File
@@ -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{
+4
View File
@@ -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 {
+24
View File
@@ -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
+41
View File
@@ -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 в этой среде не проверялся.
+12
View File
@@ -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`.
+9
View File
@@ -0,0 +1,9 @@
# Документация File Browser SSO
- [Установка на Debian, первоначальная настройка, SSO и systemd](deployment.md)
- [Авторизация и сессии](authentication.md)
- [Проверки безопасности и ограничения](SECURITY-REVIEW.md)
- [Настройка внешнего вида](customization.md)
- [CLI](cli/filebrowser.md)
Актуальная точка входа — `filebrowser init`. Руководства исходного архивированного File Browser по локальным паролям, proxy-auth, hook-auth и выполнению команд к этому форку не применяются.
+34
View File
@@ -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-файл отделяет исполняемые файлы от изменяемых данных. Обновляйте зависимости и повторяйте аудит перед публикацией новых версий.
+45
View File
@@ -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` — результат этого теста без пользовательских данных.
+29
View File
@@ -0,0 +1,29 @@
# Авторизация
## Общая сессия SSO
File Browser использует внутренний контракт общей браузерной сессии. В SSO приложение должно иметь тип **«Внутреннее»**, PKCE S256 и точный callback. Настройка — через `filebrowser init`; секрет хранится только в конфигурации сервера.
Первичный вход: 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 --no-sso
```
Этот явный флаг запускает приложение без SSO и пароля. Все посетители получают права администратора в настроенном файловом корне. Конфигурация SSO и доступность провайдера не проверяются. Настройки локального профиля сохраняются между запусками. Без флага обязательна проверка через SSO; ошибка провайдера режим без входа не включает.
Пароли публичных ссылок остаются независимыми и работают в обоих режимах.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -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)
File renamed without changes.
File renamed without changes.
+25
View File
@@ -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
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -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
+5
View File
@@ -0,0 +1,5 @@
# Выполнение команд
В этом форке выполнение команд, shell API и файловые хуки отключены без возможности включения через пользовательские настройки. Веб-маршрут `/api/command` отсутствует.
Если нужна автоматическая обработка файлов, запускайте её отдельной службой ОС с самостоятельными разрешениями.
+11
View File
@@ -0,0 +1,11 @@
# Customization
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**.
The same options are available through the CLI:
```sh
filebrowser config set --branding.name "My Files" --branding.theme dark
```
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.
+113
View File
@@ -0,0 +1,113 @@
# File Browser SSO — Debian amd64
Сборка для `linux/amd64`, базовый набор инструкций `GOAMD64=v1`, `CGO_ENABLED=0`.
Node.js и Go на сервере не нужны: интерфейс встроен в исполняемый файл.
## Первоначальная настройка
Распакуйте архив в `/opt/filebrowser`. Пример отдельного системного пользователя:
```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
```
Мастер запросит 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`.
Конфигурация сохраняется в `.filebrowser.json` с правами `0600`. Настройка через
`.env` не нужна. Мастер не перезаписывает существующую конфигурацию; для другого
файла используйте `./filebrowser init --output /полный/путь/settings.json`.
Запуск с нестандартной конфигурацией: `./filebrowser --config /полный/путь/settings.json`.
В вашем SSO зарегистрируйте приложение с PKCE S256 и callback, напечатанным мастером:
```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/`.
+31
View File
@@ -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, без скриншотов и пользовательских данных.
Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

@@ -6,29 +6,29 @@ File Browser is a single binary and can be used as standalone executable. Howeve
The quickest and easiest way to install File Browser is to use a package manager, or our download script, which automatically fetches the latest version of File Browser for your platform. Alternatively, you can manually download the binary from the [releases page](https://github.com/filebrowser/filebrowser/releases).
=== "Brew"
### Brew
```sh
brew tap filebrowser/tap
brew install filebrowser
filebrowser -r /path/to/your/files
```
```sh
brew tap filebrowser/tap
brew install filebrowser
filebrowser -r /path/to/your/files
```
=== "Unix"
### Unix
```sh
curl -fsSL https://raw.githubusercontent.com/filebrowser/get/master/get.sh | bash
filebrowser -r /path/to/your/files
```
```sh
curl -fsSL https://raw.githubusercontent.com/filebrowser/get/master/get.sh | bash
filebrowser -r /path/to/your/files
```
=== "Windows"
### Windows
```sh
iwr -useb https://raw.githubusercontent.com/filebrowser/get/master/get.ps1 | iex
filebrowser -r /path/to/your/files
```
```sh
iwr -useb https://raw.githubusercontent.com/filebrowser/get/master/get.ps1 | iex
filebrowser -r /path/to/your/files
```
File Browser is now up and running. Read some [first boot](#first-boot) for more information.
File Browser is now up and running. Read the ["First Boot"](#first-boot) section for more information.
## Docker
+22
View File
@@ -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.
+21
View File
@@ -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 сохраняет исходное значение из файла, а поле «Используется» показывает фактическую кодировку отображения.
View File
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
File renamed without changes.
File renamed without changes.
View File
File renamed without changes.
File renamed without changes.
+3 -2
View File
@@ -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)
}
})
+3 -1
View File
@@ -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 {
+29
View File
@@ -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)
}
}
+11 -22
View File
@@ -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 }],
},
}
);
+2 -2
View File
@@ -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"
+48 -46
View File
@@ -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"
}
+2338 -2557
View File
File diff suppressed because it is too large. Load diff
+6
View File
@@ -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
Loaded 100 of 378 files, more files were not shown because too many files have changed in this diff. Show more