("$showSuccess")!;
const { t } = useI18n({});
const route = useRoute();
+const router = useRouter();
+const landing = ref
(null);
+const directoryShare = ref(false);
+const showFiles = computed(() => route.query.view === "files");
+const setFileView = (files: boolean) =>
+ router.push({
+ path: route.path,
+ query: { ...route.query, view: files ? "files" : undefined },
+ hash: route.hash,
+ });
const fileStore = useFileStore();
const layoutStore = useLayoutStore();
+watch(
+ [landing, showFiles, () => layoutStore.loading, error],
+ () => {
+ layoutStore.publicLanding =
+ !!landing.value && !showFiles.value && !error.value;
+ },
+ { immediate: true }
+);
-watch(route, () => {
- showLimit.value = 100;
- fetchData();
-});
+watch(
+ () => route.path,
+ () => {
+ showLimit.value = 100;
+ fetchData();
+ }
+);
const req = computed(() => fileStore.req);
const sharedPreview = computed(
@@ -270,6 +313,14 @@ const modTime = computed(() =>
// Functions
const base64 = (name: any) => Base64.encodeURI(name);
const fetchData = async () => {
+ const generation = ++fetchGeneration;
+ if (activeHash !== hash.value) {
+ activeHash = hash.value;
+ password.value = "";
+ token.value = "";
+ attemptedPasswordLogin.value = false;
+ landing.value = null;
+ }
fileStore.reload = false;
fileStore.selected = [];
fileStore.multiple = false;
@@ -287,21 +338,51 @@ const fetchData = async () => {
if (url[0] !== "/") url = "/" + url;
try {
- const file = await api.fetch(url, password.value);
+ const file = await api.fetch(url, password.value, { token: token.value });
+ if (generation !== fetchGeneration) return;
file.hash = hash.value;
token.value = file.token || "";
+ // Discover the root once per request, also when entering a nested URL.
+ const root =
+ file.isDir && url.replace(/\/+$/, "") === shareBase(url)
+ ? file
+ : await api.fetch(shareBase(url), password.value, {
+ token: token.value,
+ });
+ if (generation !== fetchGeneration) return;
+ directoryShare.value = root.isDir;
+ landing.value = null;
+ if (!file.isDir && /\.(md|markdown|html?)$/i.test(file.name))
+ landing.value = file;
+ else if (root === file) {
+ const page = file.items.find(
+ (item) => item.name === "page.md" && !item.isDir
+ );
+ if (page)
+ landing.value = {
+ ...file,
+ ...page,
+ items: [],
+ hash: hash.value,
+ token: file.token,
+ };
+ }
+
fileStore.updateRequest(file);
document.title = `${file.name} - ${document.title}`;
} catch (err) {
+ if (generation !== fetchGeneration) return;
if (err instanceof Error) {
error.value = err;
}
} finally {
- layoutStore.loading = false;
+ if (generation === fetchGeneration) layoutStore.loading = false;
}
};
+let fetchGeneration = 0;
+let activeHash = hash.value;
const keyEvent = (event: KeyboardEvent) => {
if (event.key === "Escape") {
@@ -368,6 +449,8 @@ onMounted(async () => {
});
onBeforeUnmount(() => {
+ fetchGeneration++;
+ layoutStore.publicLanding = false;
// Destroyed
window.removeEventListener("keydown", keyEvent);
});
diff --git a/frontend/src/views/files/Editor.vue b/frontend/src/views/files/Editor.vue
index b9dd6baa..a08eac1c 100644
--- a/frontend/src/views/files/Editor.vue
+++ b/frontend/src/views/files/Editor.vue
@@ -38,6 +38,34 @@
+
+
+
+
+
+
+
+
+
+
+
+
{
next();
},
saveAction: async () => {
- await save();
+ await save(true);
next();
},
});
@@ -221,13 +249,15 @@ const initEditor = (fileContent: string) => {
editor.value = ace.edit("editor", {
value: fileContent,
showPrintMargin: false,
+ showGutter: true,
+ showLineNumbers: true,
useWorker: false,
readOnly: fileStore.req?.type === "textImmutable",
theme: getEditorTheme(),
mode: modelist.getModeForPath(fileStore.req!.name).mode,
wrap: true,
enableBasicAutocompletion: true,
- enableLiveAutocompletion: true,
+ enableLiveAutocompletion: fileContent.length < 200_000,
enableSnippets: true,
});
diff --git a/http/http.go b/http/http.go
index 787251d1..e1cfe9a4 100644
--- a/http/http.go
+++ b/http/http.go
@@ -110,6 +110,7 @@ func NewHandler(
api.PathPrefix("/subtitle").Handler(monkey(subtitleHandler, "/api/subtitle")).Methods("GET")
public := api.PathPrefix("/public").Subrouter()
+ public.HandleFunc("/landing-shell", publicLandingShell).Methods("GET")
public.PathPrefix("/dl").Handler(monkey(publicDlHandler, "/api/public/dl/")).Methods("GET")
public.PathPrefix("/share").Handler(monkey(publicShareHandler, "/api/public/share/")).Methods("GET")
diff --git a/http/public.go b/http/public.go
index b8fdf52c..8aa7cb09 100644
--- a/http/public.go
+++ b/http/public.go
@@ -17,6 +17,9 @@ import (
var withHashFile = func(fn handleFunc) handleFunc {
return func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
id, ifPath := ifPathWithName(r)
+ if !validSharePath(r.URL.Path) {
+ return http.StatusBadRequest, nil
+ }
link, err := d.store.Share.GetByHash(id)
if err != nil {
return errToStatus(err), err
@@ -62,14 +65,18 @@ var withHashFile = func(fn handleFunc) handleFunc {
if file.IsDir {
filePath = ifPath
+ } else if ifPath != "/" && ifPath != "." && ifPath != "/"+file.Name {
+ // Keep the legacy /key/original-filename download alias, but never
+ // interpret a suffix on a single-file share as an attachment path.
+ return http.StatusNotFound, nil
}
- // set fs root to the shared file/folder. Unless external symlinks are
- // explicitly allowed, this is a ScopedFs (not a bare BasePathFs) so the
+ // Set fs root to the shared file/folder. Public access always uses a
+ // ScopedFs (not a bare BasePathFs) so the
// share is also symlink-confined: a link inside the shared subtree that
// points elsewhere in the owner's scope — outside the share — must not be
// followed.
- d.user.Fs = files.NewFs(d.user.Fs, basePath, d.server.FollowExternalSymlinks)
+ d.user.Fs = files.NewScopedFs(d.user.Fs, basePath)
// the filesystem is now rebased onto basePath, so paths handed to the
// rule checker are relative to it. Resolve them back to the user's
diff --git a/http/public_landing.go b/http/public_landing.go
new file mode 100644
index 00000000..092e15b7
--- /dev/null
+++ b/http/public_landing.go
@@ -0,0 +1,52 @@
+package fbhttp
+
+import (
+ "net/http"
+ "strings"
+)
+
+// URL.Path has already been decoded once by net/http. Refuse alternate
+// separators and residual escapes rather than interpreting a second time.
+func validSharePath(p string) bool {
+ if strings.ContainsAny(p, "\\%\x00:") {
+ return false
+ }
+ depth := 0
+ for i, part := range strings.Split(p, "/") {
+ if i == 0 {
+ continue
+ }
+ if part == ".." {
+ depth--
+ if depth < 0 {
+ return false
+ }
+ } else if part != "" && part != "." {
+ depth++
+ }
+ }
+ return true
+}
+
+// This empty, credential-free shell is the only place user scripts execute.
+// A response CSP (not an editable meta tag) survives document.write. The opaque
+// sandbox origin cannot read cookies, storage, or the File Browser parent.
+func publicLandingShell(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("Referrer-Policy", "no-referrer")
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ w.Header().Set("Content-Security-Policy", "sandbox allow-scripts; default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src blob: data:; media-src blob: data:; font-src data:; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'")
+ _, _ = w.Write([]byte(` `))
+}
diff --git a/http/public_landing_test.go b/http/public_landing_test.go
new file mode 100644
index 00000000..59c039b0
--- /dev/null
+++ b/http/public_landing_test.go
@@ -0,0 +1,97 @@
+package fbhttp
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/asdine/storm/v3"
+ "github.com/filebrowser/filebrowser/v2/files"
+ "github.com/filebrowser/filebrowser/v2/settings"
+ "github.com/filebrowser/filebrowser/v2/share"
+ "github.com/filebrowser/filebrowser/v2/storage/bolt"
+ "github.com/filebrowser/filebrowser/v2/users"
+ "github.com/spf13/afero"
+)
+
+func TestLandingSharePaths(t *testing.T) {
+ for _, p := range []string{"h/../secret", "h/a/../../secret", "h/%2e%2e/secret", "h/%252e/secret", "h/..\\secret", "h/C:/secret", "h/\x00"} {
+ if validSharePath(p) {
+ t.Errorf("accepted unsafe path %q", p)
+ }
+ }
+ for _, p := range []string{"h", "h/", "h/a/b.png", "h/a/../b.png", "h/фото.png"} {
+ if !validSharePath(p) {
+ t.Errorf("rejected safe path %q", p)
+ }
+ }
+}
+func TestLandingShellIsolation(t *testing.T) {
+ w := httptest.NewRecorder()
+ publicLandingShell(w, httptest.NewRequest("GET", "/api/public/landing-shell", nil))
+ csp := w.Header().Get("Content-Security-Policy")
+ for _, rule := range []string{"sandbox allow-scripts;", "default-src 'none'", "connect-src 'none'", "frame-src 'none'", "form-action 'none'", "frame-ancestors 'self'"} {
+ if !strings.Contains(csp, rule) {
+ t.Errorf("missing %q in CSP %q", rule, csp)
+ }
+ }
+ if strings.Contains(csp, "allow-same-origin") {
+ t.Fatal("shell can access session origin")
+ }
+ if strings.Contains(w.Body.String(), "token") {
+ t.Fatal("shell contains credentials")
+ }
+}
+
+func TestPublicLandingAttachmentBoundaries(t *testing.T) {
+ scope := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(scope, "site", "images"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ for name, body := range map[string]string{"site/page.md": "# Landing", "site/images/a.svg": " ", "single.md": "# Single", "secret.txt": "private"} {
+ if err := os.WriteFile(filepath.Join(scope, filepath.FromSlash(name)), []byte(body), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ db, err := storm.Open(filepath.Join(t.TempDir(), "db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ st, err := bolt.NewStorage(db)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := st.Users.Save(&users.User{Username: "owner", Password: "unused", Perm: users.Permissions{Share: true, Download: true}}); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.Settings.Save(&settings.Settings{Key: []byte("key")}); err != nil {
+ t.Fatal(err)
+ }
+ st.Users = &customFSUser{Store: st.Users, fs: files.NewScopedFs(afero.NewOsFs(), scope)}
+ for _, link := range []*share.Link{{Hash: "folder", UserID: 1, Path: "/site"}, {Hash: "single", UserID: 1, Path: "/single.md"}} {
+ if err := st.Share.Save(link); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, tc := range []struct {
+ path string
+ status int
+ }{
+ {"folder/page.md", 200}, {"folder/images/a.svg", 200}, {"folder/../secret.txt", 400},
+ {"folder/%2e%2e/secret.txt", 400}, {"folder/%252e%252e/secret.txt", 400}, {"folder/..\\secret.txt", 400},
+ {"single/", 200}, {"single/single.md", 200}, {"single/secret.txt", 404},
+ } {
+ for _, handler := range []handleFunc{publicDlHandler, publicShareHandler} {
+ req := newHTTPRequest(t, func(r *http.Request) { r.URL.Path = tc.path })
+ recorder := httptest.NewRecorder()
+ handle(handler, "", st, &settings.Server{}).ServeHTTP(recorder, req)
+ if recorder.Code != tc.status {
+ t.Errorf("%s: got %d, want %d: %s", tc.path, recorder.Code, tc.status, recorder.Body.String())
+ }
+ }
+ }
+}
diff --git a/http/public_symlink_test.go b/http/public_symlink_test.go
index 0343046e..26735589 100644
--- a/http/public_symlink_test.go
+++ b/http/public_symlink_test.go
@@ -126,83 +126,23 @@ func TestPublicShareSymlinkListingOmitsEscapingLink(t *testing.T) {
}
}
-// With Server.FollowExternalSymlinks enabled (the opt-in for issue #5998), a
-// symlink inside a public share that points outside it is followed: the file
-// behind it downloads and the link shows up in the share listing. This is the
-// inverse of TestPublicShareSymlinkDescendantDisclosure / ...ListingOmitsEscapingLink.
-func TestPublicShareSymlinkFollowedWhenEnabled(t *testing.T) {
- scope := t.TempDir()
- if err := os.MkdirAll(filepath.Join(scope, "shared"), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.MkdirAll(filepath.Join(scope, "outside"), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(scope, "outside", "data.txt"), []byte("payload"), 0o600); err != nil {
- t.Fatal(err)
- }
- if err := os.Symlink(filepath.Join(scope, "outside"), filepath.Join(scope, "shared", "link")); err != nil {
- t.Skipf("cannot create symlink on this platform: %v", err)
- }
-
- db, err := storm.Open(filepath.Join(t.TempDir(), "db"))
+// Public shares remain confined even when an owner filesystem follows links.
+func TestPublicShareSymlinkConfinedWhenEnabled(t *testing.T) {
+ st := symlinkShareStorage(t)
+ owner := st.Users.(*customFSUser)
+ root, err := files.BasePath(owner.fs).RealPath("/")
if err != nil {
- t.Fatalf("failed to open db: %v", err)
+ t.Fatal(err)
}
- t.Cleanup(func() { _ = db.Close() })
-
- st, err := bolt.NewStorage(db)
- if err != nil {
- t.Fatalf("failed to get storage: %v", err)
- }
- if err := st.Share.Save(&share.Link{Hash: "h", UserID: 1, Path: "/shared"}); err != nil {
- t.Fatalf("failed to save share: %v", err)
- }
- if err := st.Users.Save(&users.User{
- Username: "username",
- Password: "pw",
- Perm: users.Permissions{Share: true, Download: true},
- }); err != nil {
- t.Fatalf("failed to save user: %v", err)
- }
- if err := st.Settings.Save(&settings.Settings{Key: []byte("key")}); err != nil {
- t.Fatalf("failed to save settings: %v", err)
- }
- // Follow-external mode: the user filesystem is a bare BasePathFs.
- st.Users = &customFSUser{
- Store: st.Users,
- fs: files.NewFs(afero.NewOsFs(), scope, true),
- followExternal: true,
- }
-
- srv := &settings.Server{FollowExternalSymlinks: true}
-
- // The file behind the symlink downloads.
- req := newHTTPRequest(t, func(r *http.Request) { r.URL.Path = "h/link/data.txt" })
- recorder := httptest.NewRecorder()
- handle(publicDlHandler, "", st, srv).ServeHTTP(recorder, req)
- result := recorder.Result()
- defer result.Body.Close()
- body, _ := io.ReadAll(result.Body)
- if result.StatusCode != http.StatusOK {
- t.Fatalf("expected to download file behind followed symlink, got status=%d body=%q", result.StatusCode, string(body))
- }
- if !strings.Contains(string(body), "payload") {
- t.Fatalf("expected payload content, got %q", string(body))
- }
-
- // The link shows up in the share root listing.
- req = newHTTPRequest(t, func(r *http.Request) { r.URL.Path = "h/" })
- recorder = httptest.NewRecorder()
- handle(publicShareHandler, "", st, srv).ServeHTTP(recorder, req)
- result = recorder.Result()
- defer result.Body.Close()
- body, _ = io.ReadAll(result.Body)
- if result.StatusCode != http.StatusOK {
- t.Fatalf("share root listing failed: status=%d body=%q", result.StatusCode, string(body))
- }
- if !strings.Contains(string(body), "\"link\"") {
- t.Fatalf("expected followed symlink to appear in listing: %s", string(body))
+ owner.fs = files.NewFs(afero.NewOsFs(), root, true)
+ owner.followExternal = true
+ for _, handler := range []handleFunc{publicDlHandler, publicShareHandler} {
+ req := newHTTPRequest(t, func(r *http.Request) { r.URL.Path = "h/link/secret.txt" })
+ recorder := httptest.NewRecorder()
+ handle(handler, "", st, &settings.Server{FollowExternalSymlinks: true}).ServeHTTP(recorder, req)
+ if recorder.Code == http.StatusOK {
+ t.Fatal("public share followed escaping symlink")
+ }
}
}
diff --git a/http/public_test.go b/http/public_test.go
index c728102d..8a032f60 100644
--- a/http/public_test.go
+++ b/http/public_test.go
@@ -35,6 +35,7 @@ func TestPublicShareHandlerAuthentication(t *testing.T) {
downloadPerm: true,
expectedStatusCode: 200,
},
+ "Expired share, 404": {share: &share.Link{Hash: "h", UserID: 1, Expire: 1}, req: newHTTPRequest(t), sharePerm: true, downloadPerm: true, expectedStatusCode: 404},
"Private share, no auth provided, 401": {
share: &share.Link{Hash: "h", UserID: 1, PasswordHash: passwordBcrypt, Token: "123"},
req: newHTTPRequest(t),
diff --git a/scripts/build-release.ps1 b/scripts/build-release.ps1
index 5887c339..47d8969c 100644
--- a/scripts/build-release.ps1
+++ b/scripts/build-release.ps1
@@ -1,4 +1,4 @@
-param([string]$Version = '3.2.3')
+param([string]$Version = '3.2.4')
$ErrorActionPreference = 'Stop'
$repo = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Push-Location $repo
diff --git a/scripts/build-release.sh b/scripts/build-release.sh
index b0462b18..3ef63649 100644
--- a/scripts/build-release.sh
+++ b/scripts/build-release.sh
@@ -1,7 +1,7 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
-VERSION="${VERSION:-3.2.3}"
+VERSION="${VERSION:-3.2.4}"
COMMIT=$(git rev-parse --short HEAD)
(cd frontend && pnpm install --frozen-lockfile && pnpm run build)
mkdir -p build/release/linux-amd64