fix: preserve SSO identities and polish sharing interface

This commit is contained in:
SantaSpeen committed 2026-10-21 21:47:13 +03:00
1 parent 2e3b56f250
commit bd9bf33bc9
22 files changed
+430 -106

No files matched your search

+4
View File
@@ -1,5 +1,9 @@
# Вход через SSO # Вход через SSO
При входе профиль дополнительно загружается через OIDC UserInfo: имя пользователя, полное имя и email. `sub` обязан совпадать с проверенным ID token; роли берутся только из подписанного токена. Внутренний ключ `sso:…` хранится отдельно от отображаемого имени и не изменяется при сохранении настроек.
Повторный вход использует тот же локальный ID. Если предыдущая версия уже создала несколько записей с одинаковым ключом, используется самая ранняя запись, включая после перезапуска; существующие дубли, их настройки и публичные ссылки автоматически не удаляются. В списке пользователей отображаются ID записей. Перед обновлением сохраните резервную копию базы.
Поддерживается OpenID Connect Authorization Code Flow с PKCE S256. Настройка выполняется через `filebrowser init`, который создаёт `.filebrowser.json` и печатает callback URL. Подробности — [установка](deployment.md). Поддерживается OpenID Connect Authorization Code Flow с PKCE S256. Настройка выполняется через `filebrowser init`, который создаёт `.filebrowser.json` и печатает callback URL. Подробности — [установка](deployment.md).
Проверяются state, nonce, RSA-подпись, issuer, audience, срок действия ID token и привязка access token через at_hash. Идентичность привязана к issuer и стабильному sub. Логин или почта, совпавшие с прежним локальным аккаунтом, не дают доступ к нему. Проверяются state, nonce, RSA-подпись, issuer, audience, срок действия ID token и привязка access token через at_hash. Идентичность привязана к issuer и стабильному sub. Логин или почта, совпавшие с прежним локальным аккаунтом, не дают доступ к нему.
Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

+25 -33
View File
@@ -4,7 +4,10 @@
<template v-if="isLoggedIn"> <template v-if="isLoggedIn">
<button @click="toAccountSettings" class="action"> <button @click="toAccountSettings" class="action">
<i class="material-icons">person</i> <i class="material-icons">person</i>
<span>{{ user.username }}</span> <span class="sidebar-profile"
><strong>{{ user.username }}</strong
><small v-if="user.profileName">{{ user.profileName }}</small></span
>
</button> </button>
<button <button
class="action" class="action"
@@ -86,31 +89,22 @@
</template> </template>
<div <div
class="credits" class="disk-usage"
v-if="isFiles && !disableUsedPercentage" v-if="isFiles && !disableUsedPercentage && usage.total !== '0 B'"
style="width: 90%; margin: 2em 2.5em 3em 2.5em"
> >
<progress-bar :val="usage.usedPercentage" size="small"></progress-bar> <div class="disk-usage-heading">
<br /> <span>{{ $t("sso.storage") }}</span
{{ $t("sidebar.diskUsed", { used: usage.used, total: usage.total }) }} ><strong>{{ usage.usedPercentage }}%</strong>
</div>
<progress
:value="usage.usedPercentage"
max="100"
:aria-label="$t('sso.storage')"
></progress>
<small>{{
$t("sidebar.diskUsed", { used: usage.used, total: usage.total })
}}</small>
</div> </div>
<p class="credits">
<span>
<span v-if="disableExternal">File Browser</span>
<a
v-else
rel="noopener noreferrer"
target="_blank"
href="https://github.com/filebrowser/filebrowser"
>File Browser</a
>
<span> {{ " " }} {{ version }}</span>
</span>
<span>
<a @click="help">{{ $t("sidebar.help") }}</a>
</span>
</p>
</nav> </nav>
</template> </template>
@@ -123,17 +117,14 @@ import { useLayoutStore } from "@/stores/layout";
import * as auth from "@/utils/auth"; import * as auth from "@/utils/auth";
import { import {
version,
signup, signup,
hideLoginButton, hideLoginButton,
disableExternal,
disableUsedPercentage, disableUsedPercentage,
noAuth, noAuth,
logoutPage, logoutPage,
loginPage, loginPage,
} from "@/utils/constants"; } from "@/utils/constants";
import { files as api } from "@/api"; import { files as api } from "@/api";
import ProgressBar from "@/components/ProgressBar.vue";
import prettyBytes from "pretty-bytes"; import prettyBytes from "pretty-bytes";
const USAGE_DEFAULT = { used: "0 B", total: "0 B", usedPercentage: 0 }; const USAGE_DEFAULT = { used: "0 B", total: "0 B", usedPercentage: 0 };
@@ -144,9 +135,6 @@ export default {
const usage = reactive(USAGE_DEFAULT); const usage = reactive(USAGE_DEFAULT);
return { usage, usageAbortController: new AbortController() }; return { usage, usageAbortController: new AbortController() };
}, },
components: {
ProgressBar,
},
inject: ["$showError"], inject: ["$showError"],
computed: { computed: {
...mapState(useAuthStore, ["user", "isLoggedIn"]), ...mapState(useAuthStore, ["user", "isLoggedIn"]),
@@ -157,8 +145,6 @@ export default {
}, },
signup: () => signup, signup: () => signup,
hideLoginButton: () => hideLoginButton, hideLoginButton: () => hideLoginButton,
version: () => version,
disableExternal: () => disableExternal,
disableUsedPercentage: () => disableUsedPercentage, disableUsedPercentage: () => disableUsedPercentage,
canLogout: () => !noAuth && (loginPage || logoutPage !== "/login"), canLogout: () => !noAuth && (loginPage || logoutPage !== "/login"),
}, },
@@ -182,7 +168,13 @@ export default {
usageStats = { usageStats = {
used: prettyBytes(usage.used, { binary: true }), used: prettyBytes(usage.used, { binary: true }),
total: prettyBytes(usage.total, { binary: true }), total: prettyBytes(usage.total, { binary: true }),
usedPercentage: Math.round((usage.used / usage.total) * 100), usedPercentage:
usage.total > 0
? Math.min(
100,
Math.max(0, Math.round((usage.used / usage.total) * 100))
)
: 0,
}; };
} finally { } finally {
return Object.assign(this.usage, usageStats); return Object.assign(this.usage, usageStats);
+34 -30
View File
@@ -6,34 +6,40 @@
<template v-if="listing"> <template v-if="listing">
<div class="card-content"> <div class="card-content">
<table> <div class="share-links">
<tr> <article
<th>#</th> v-for="link in links"
<th>{{ $t("settings.shareDuration") }}</th> :key="link.hash"
<th></th> class="share-link-card"
<th></th> >
<th></th> <div class="share-link-details">
</tr> <a
:href="buildLink(link)"
<tr v-for="link in links" :key="link.hash"> target="_blank"
<td>{{ link.hash }}</td> rel="noopener noreferrer"
<td> class="share-link-name"
<template v-if="link.expire !== 0">{{ >/s/{{ link.hash }}</a
humanTime(link.expire) >
}}</template> <small
<template v-else>{{ $t("permanent") }}</template> ><i class="material-icons" aria-hidden="true">schedule</i
</td> >{{ link.expire ? humanTime(link.expire) : $t("permanent")
<td class="small"> }}<i
v-if="link.hasPassword"
class="material-icons"
:title="$t('login.password')"
>lock</i
></small
>
</div>
<div class="share-link-actions">
<button <button
class="action" class="action"
:aria-label="$t('buttons.copyToClipboard')" :aria-label="$t('buttons.copyToClipboard')"
:title="$t('buttons.copyToClipboard')" :title="$t('buttons.copyToClipboard')"
@click="copyToClipboard(buildLink(link))" @click="copyToClipboard(buildLink(link))"
> >
<i class="material-icons">content_paste</i> <i class="material-icons">link</i>
</button> </button>
</td>
<td class="small">
<button <button
class="action" class="action"
:aria-label="$t('buttons.copyDownloadLinkToClipboard')" :aria-label="$t('buttons.copyDownloadLinkToClipboard')"
@@ -41,21 +47,19 @@
:disabled="!!link.hasPassword" :disabled="!!link.hasPassword"
@click="copyToClipboard(buildDownloadLink(link))" @click="copyToClipboard(buildDownloadLink(link))"
> >
<i class="material-icons">content_paste_go</i> <i class="material-icons">download</i>
</button> </button>
</td>
<td class="small">
<button <button
class="action" class="action share-link-delete"
@click="deleteLink($event, link)"
:aria-label="$t('buttons.delete')" :aria-label="$t('buttons.delete')"
:title="$t('buttons.delete')" :title="$t('buttons.delete')"
@click="deleteLink($event, link)"
> >
<i class="material-icons">delete</i> <i class="material-icons">delete_outline</i>
</button> </button>
</td> </div>
</tr> </article>
</table> </div>
</div> </div>
<div class="card-action"> <div class="card-action">
+155
View File
@@ -1,4 +1,159 @@
/* Lightweight workspace: system fonts, solid surfaces, no blur or filter layers. */ /* Lightweight workspace: system fonts, solid surfaces, no blur or filter layers. */
.user-record-id {
display: block;
color: var(--textPrimary);
font-size: 11px;
}
.without-sidebar main {
width: auto;
max-width: 1200px;
margin: 0 auto 24px;
padding-inline: 24px;
}
.without-sidebar .menu-button {
display: none;
}
.sidebar-profile {
display: inline-flex;
flex-direction: column;
min-width: 0;
max-width: calc(100% - 38px);
}
.sidebar-profile strong,
.sidebar-profile small {
overflow: hidden;
text-overflow: ellipsis;
}
.sidebar-profile small {
color: var(--textPrimary);
font-weight: 400;
font-size: 11px;
}
nav .disk-usage {
margin: 28px 4px 12px;
padding: 14px;
border: 1px solid var(--borderPrimary);
border-radius: 12px;
background: var(--background);
}
.disk-usage-heading {
display: flex;
justify-content: space-between;
font-size: 12px;
color: var(--textSecondary);
}
.disk-usage progress {
display: block;
width: 100%;
height: 6px;
margin: 10px 0;
border: 0;
border-radius: 8px;
overflow: hidden;
background: var(--borderPrimary);
accent-color: var(--blue);
}
.disk-usage progress::-webkit-progress-bar {
background: var(--borderPrimary);
}
.disk-usage progress::-webkit-progress-value {
background: var(--blue);
border-radius: 8px;
}
.disk-usage progress::-moz-progress-bar {
background: var(--blue);
border-radius: 8px;
}
.disk-usage small {
display: block;
font-size: 11px;
color: var(--textPrimary);
}
.profile-summary {
display: flex;
flex-direction: column;
gap: 4px;
padding-bottom: 20px;
margin-bottom: 20px;
border-bottom: 1px solid var(--divider);
overflow-wrap: anywhere;
}
.profile-summary strong {
font-size: 20px;
color: var(--textSecondary);
}
#share.card {
width: min(620px, calc(100vw - 32px));
max-width: calc(100vw - 32px);
}
#share .card-content {
padding: 20px;
}
.share-links {
display: grid;
gap: 12px;
}
.share-link-card {
padding: 14px;
border: 1px solid var(--borderPrimary);
border-radius: 10px;
background: var(--background);
}
.share-link-details {
min-width: 0;
}
.share-link-name {
display: block;
overflow-wrap: anywhere;
color: var(--textSecondary);
font-weight: 600;
}
.share-link-details small {
display: flex;
align-items: center;
gap: 6px;
margin-top: 7px;
color: var(--textPrimary);
}
.share-link-details small i {
font-size: 16px;
}
.share-link-actions {
display: flex;
justify-content: flex-end;
gap: 6px;
margin-top: 8px;
}
.share-link-actions .action {
border: 1px solid var(--borderPrimary);
border-radius: 8px;
width: 38px;
height: 36px;
padding: 4px;
}
.share-link-actions .action:hover {
background: var(--hover);
}
.share-link-actions .share-link-delete {
color: var(--red);
}
.share-link-actions .action:disabled {
opacity: 0.4;
cursor: default;
}
.share__box__info {
max-width: 560px;
}
.share__box__center svg {
max-width: min(240px, 100%);
height: auto;
padding: 12px;
background: white;
border-radius: 10px;
}
.share__box__icon i {
font-size: 80px;
}
:root { :root {
--blue: #3563e9; --blue: #3563e9;
--dark-blue: #244bc2; --dark-blue: #244bc2;
+16 -5
View File
@@ -200,7 +200,7 @@
"allowNew": "Create new files and directories", "allowNew": "Create new files and directories",
"allowPublish": "Publish new posts and pages", "allowPublish": "Publish new posts and pages",
"allowSignup": "Allow users to signup", "allowSignup": "Allow users to signup",
"hideLoginButton": "Hide the login button from public pages", "hideLoginButton": "Hide the sidebar on public pages",
"avoidChanges": "(leave blank to avoid changes)", "avoidChanges": "(leave blank to avoid changes)",
"branding": "Branding", "branding": "Branding",
"brandingDirectoryPath": "Branding directory path", "brandingDirectoryPath": "Branding directory path",
@@ -247,10 +247,10 @@
"execute": "Execute commands", "execute": "Execute commands",
"modify": "Edit files", "modify": "Edit files",
"rename": "Rename or move files and directories", "rename": "Rename or move files and directories",
"share": "Share files (require download permission)" "share": "Share files (requires download permission)"
}, },
"permissions": "Permissions", "permissions": "Permissions",
"permissionsHelp": "You can set the user to be an administrator or choose the permissions individually. If you select \"Administrator\", all of the other options will be automatically checked. The management of users remains a privilege of an administrator.\n", "permissionsHelp": "File access permissions. Administrators are determined by SSO roles.",
"profileSettings": "Profile Settings", "profileSettings": "Profile Settings",
"redirectAfterCopyMove": "Redirect to destination after copy/move", "redirectAfterCopyMove": "Redirect to destination after copy/move",
"ruleExample1": "prevents the access to any dotfile (such as .git, .gitignore) in every folder.\n", "ruleExample1": "prevents the access to any dotfile (such as .git, .gitignore) in every folder.\n",
@@ -260,7 +260,7 @@
"scope": "Scope", "scope": "Scope",
"setDateFormat": "Set exact date format", "setDateFormat": "Set exact date format",
"settingsUpdated": "Settings updated!", "settingsUpdated": "Settings updated!",
"shareDuration": "Share Duration", "shareDuration": "Link expiration",
"shareManagement": "Share Management", "shareManagement": "Share Management",
"shareDeleted": "Share deleted!", "shareDeleted": "Share deleted!",
"singleClick": "Use single clicks to open files and directories", "singleClick": "Use single clicks to open files and directories",
@@ -318,6 +318,17 @@
"shortHint": "2–64 letters, digits, underscores or hyphens. Public names are discoverable; protect sensitive shares with a password.", "shortHint": "2–64 letters, digits, underscores or hyphens. Public names are discoverable; protect sensitive shares with a password.",
"workspace": "Your workspace", "workspace": "Your workspace",
"toggleTheme": "Switch theme", "toggleTheme": "Switch theme",
"itemsCount": "{count} items" "itemsCount": "{count} items",
"storage": "Storage",
"editorTheme": "The editor follows the interface theme automatically."
},
"permissions": {
"create": "Create files and directories",
"delete": "Delete files and directories",
"download": "Download",
"execute": "Execute commands",
"modify": "Edit files",
"rename": "Rename or move files and directories",
"share": "Share files (requires download permission)"
} }
} }
+17 -6
View File
@@ -200,7 +200,7 @@
"allowNew": "Создание новых файлов или каталогов", "allowNew": "Создание новых файлов или каталогов",
"allowPublish": "Публикация новых записей и страниц", "allowPublish": "Публикация новых записей и страниц",
"allowSignup": "Разрешить пользователям регистрироваться", "allowSignup": "Разрешить пользователям регистрироваться",
"hideLoginButton": "Спрятать кнопку входа с публичных страниц", "hideLoginButton": "Спрятать боковое меню с публичных страниц",
"avoidChanges": "(оставьте поле пустым, чтобы избежать изменений)", "avoidChanges": "(оставьте поле пустым, чтобы избежать изменений)",
"branding": "Брендинг", "branding": "Брендинг",
"brandingDirectoryPath": "Путь к каталогу брендов", "brandingDirectoryPath": "Путь к каталогу брендов",
@@ -247,10 +247,10 @@
"execute": "Выполнять команды", "execute": "Выполнять команды",
"modify": "Редактировать файлы", "modify": "Редактировать файлы",
"rename": "Переименовывать или перемещать файлы и каталоги", "rename": "Переименовывать или перемещать файлы и каталоги",
"share": "Share files (require download permission)" "share": "Делиться файлами (требует разрешения на скачивание)"
}, },
"permissions": "Права доступа", "permissions": "Права доступа",
"permissionsHelp": "Можно настроить пользователя как администратора или выбрать разрешения индивидуально. При выборе \"Администратор\", все остальные параметры будут автоматически выбраны. Управление пользователями - привилегия администратора.\n", "permissionsHelp": "Права на работу с файлами. Администраторы определяются ролями SSO.",
"profileSettings": "Настройки профиля", "profileSettings": "Настройки профиля",
"redirectAfterCopyMove": "Redirect to destination after copy/move", "redirectAfterCopyMove": "Redirect to destination after copy/move",
"ruleExample1": "предотвратить доступ к любому скрытому файлу (например: .git, .gitignore) в каждой папке.\n", "ruleExample1": "предотвратить доступ к любому скрытому файлу (например: .git, .gitignore) в каждой папке.\n",
@@ -260,7 +260,7 @@
"scope": "Область", "scope": "Область",
"setDateFormat": "Установить точный формат даты", "setDateFormat": "Установить точный формат даты",
"settingsUpdated": "Настройки применены!", "settingsUpdated": "Настройки применены!",
"shareDuration": "Время расшаренной ссылки", "shareDuration": "Срок действия ссылки",
"shareManagement": "Управление расшаренными ссылками", "shareManagement": "Управление расшаренными ссылками",
"shareDeleted": "Расшаренная ссылка удалена!", "shareDeleted": "Расшаренная ссылка удалена!",
"singleClick": "Открытие файлов и каталогов одним кликом", "singleClick": "Открытие файлов и каталогов одним кликом",
@@ -283,7 +283,7 @@
"currentPassword": "Your Current Password" "currentPassword": "Your Current Password"
}, },
"sidebar": { "sidebar": {
"diskUsed": "{used} of {total} used", "diskUsed": "Занято {used} из {total}",
"help": "Помощь", "help": "Помощь",
"hugoNew": "Hugo New", "hugoNew": "Hugo New",
"login": "Войти", "login": "Войти",
@@ -315,6 +315,17 @@
"shortHint": "2–64 латинские буквы, цифры, дефис или подчёркивание. Для конфиденциальных файлов установите пароль ссылки.", "shortHint": "2–64 латинские буквы, цифры, дефис или подчёркивание. Для конфиденциальных файлов установите пароль ссылки.",
"workspace": "Файловое пространство", "workspace": "Файловое пространство",
"toggleTheme": "Переключить тему", "toggleTheme": "Переключить тему",
"itemsCount": "Объектов: {count}" "itemsCount": "Объектов: {count}",
"storage": "Хранилище",
"editorTheme": "Тема редактора автоматически соответствует теме интерфейса."
},
"permissions": {
"create": "Создавать файлы и каталоги",
"delete": "Удалять файлы и каталоги",
"download": "Скачивать",
"execute": "Выполнять команды",
"modify": "Редактировать файлы",
"rename": "Переименовывать или перемещать файлы и каталоги",
"share": "Делиться файлами (требует разрешения на скачивание)"
} }
} }
+2
View File
@@ -1,5 +1,7 @@
interface IUser { interface IUser {
displayName?: string; displayName?: string;
profileName?: string;
email?: string;
id: number; id: number;
username: string; username: string;
password: string; password: string;
+3 -5
View File
@@ -1,9 +1,7 @@
import "ace-builds"; import "ace-builds/src-noconflict/theme-chrome";
import { themesByName } from "ace-builds/src-noconflict/ext-themelist"; import "ace-builds/src-noconflict/theme-twilight";
import { getTheme } from "./theme"; import { getTheme } from "./theme";
export const getEditorTheme = (themeName: string) => { export const getEditorTheme = () => {
const key = themeName.replace(/^ace\/theme\//, "");
if (themesByName[key] !== undefined) return `ace/theme/${key}`;
return getTheme() === "dark" ? "ace/theme/twilight" : "ace/theme/chrome"; return getTheme() === "dark" ? "ace/theme/twilight" : "ace/theme/chrome";
}; };
+4 -3
View File
@@ -1,5 +1,5 @@
<template> <template>
<div> <div :class="{ 'without-sidebar': hideSidebar }">
<div v-if="uploadStore.totalBytes" class="progress"> <div v-if="uploadStore.totalBytes" class="progress">
<div <div
v-bind:style="{ v-bind:style="{
@@ -7,7 +7,7 @@
}" }"
></div> ></div>
</div> </div>
<sidebar></sidebar> <sidebar v-if="!hideSidebar"></sidebar>
<main> <main>
<router-view></router-view> <router-view></router-view>
<shell <shell
@@ -30,7 +30,7 @@ import Sidebar from "@/components/Sidebar.vue";
import Prompts from "@/components/prompts/Prompts.vue"; import Prompts from "@/components/prompts/Prompts.vue";
import Shell from "@/components/Shell.vue"; import Shell from "@/components/Shell.vue";
import UploadFiles from "@/components/prompts/UploadFiles.vue"; import UploadFiles from "@/components/prompts/UploadFiles.vue";
import { enableExec } from "@/utils/constants"; import { enableExec, hideLoginButton } from "@/utils/constants";
import { computed, watch } from "vue"; import { computed, watch } from "vue";
import { useRoute } from "vue-router"; import { useRoute } from "vue-router";
@@ -39,6 +39,7 @@ const authStore = useAuthStore();
const fileStore = useFileStore(); const fileStore = useFileStore();
const uploadStore = useUploadStore(); const uploadStore = useUploadStore();
const route = useRoute(); const route = useRoute();
const hideSidebar = computed(() => route.name === "Share" && hideLoginButton);
const sentPercent = computed(() => const sentPercent = computed(() =>
((uploadStore.sentBytes / uploadStore.totalBytes) * 100).toFixed(2) ((uploadStore.sentBytes / uploadStore.totalBytes) * 100).toFixed(2)
+2 -1
View File
@@ -1,6 +1,6 @@
<template> <template>
<div> <div>
<header-bar showMenu showLogo> <header-bar :showMenu="!hideLoginButton" showLogo>
<title /> <title />
<action <action
@@ -301,6 +301,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { hideLoginButton } from "@/utils/constants";
import { pub as api } from "@/api"; import { pub as api } from "@/api";
import { filesize } from "@/utils"; import { filesize } from "@/utils";
import dayjs from "dayjs"; import dayjs from "dayjs";
+9 -1
View File
@@ -113,6 +113,9 @@ const route = useRoute();
const router = useRouter(); const router = useRouter();
const editor = ref<Ace.Editor | null>(null); const editor = ref<Ace.Editor | null>(null);
const themeObserver = new MutationObserver(() => {
editor.value?.setTheme(getEditorTheme());
});
const fontSize = ref(parseInt(localStorage.getItem("editorFontSize") || "14")); const fontSize = ref(parseInt(localStorage.getItem("editorFontSize") || "14"));
const isPreview = ref(false); const isPreview = ref(false);
@@ -191,6 +194,7 @@ onMounted(() => {
}); });
onBeforeUnmount(() => { onBeforeUnmount(() => {
themeObserver.disconnect();
window.removeEventListener("keydown", keyEvent); window.removeEventListener("keydown", keyEvent);
window.removeEventListener("beforeunload", handlePageChange); window.removeEventListener("beforeunload", handlePageChange);
editor.value?.destroy(); editor.value?.destroy();
@@ -217,12 +221,16 @@ onBeforeRouteUpdate((to, from, next) => {
}); });
const initEditor = (fileContent: string) => { const initEditor = (fileContent: string) => {
themeObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ["class"],
});
editor.value = ace.edit("editor", { editor.value = ace.edit("editor", {
value: fileContent, value: fileContent,
showPrintMargin: false, showPrintMargin: false,
useWorker: false, useWorker: false,
readOnly: fileStore.req?.type === "textImmutable", readOnly: fileStore.req?.type === "textImmutable",
theme: getEditorTheme(authStore.user?.aceEditorTheme ?? ""), theme: getEditorTheme(),
mode: modelist.getModeForPath(fileStore.req!.name).mode, mode: modelist.getModeForPath(fileStore.req!.name).mode,
wrap: true, wrap: true,
enableBasicAutocompletion: true, enableBasicAutocompletion: true,
+9 -7
View File
@@ -7,6 +7,14 @@
</div> </div>
<div class="card-content"> <div class="card-content">
<div class="profile-summary">
<strong>{{ authStore.user?.username }}</strong
><span v-if="authStore.user?.profileName">{{
authStore.user.profileName
}}</span
><span v-if="authStore.user?.email">{{ authStore.user.email }}</span
><small>{{ t("sso.managed") }}</small>
</div>
<p> <p>
<input type="checkbox" name="hideDotfiles" v-model="hideDotfiles" /> <input type="checkbox" name="hideDotfiles" v-model="hideDotfiles" />
{{ t("settings.hideDotfiles") }} {{ t("settings.hideDotfiles") }}
@@ -33,12 +41,7 @@
v-model:locale="locale" v-model:locale="locale"
></languages> ></languages>
<h3>{{ t("settings.aceEditorTheme") }}</h3> <p class="field-hint">{{ t("sso.editorTheme") }}</p>
<AceEditorTheme
class="input input--block"
v-model:aceEditorTheme="aceEditorTheme"
id="aceTheme"
></AceEditorTheme>
</div> </div>
<div class="card-action"> <div class="card-action">
@@ -58,7 +61,6 @@
import { useAuthStore } from "@/stores/auth"; import { useAuthStore } from "@/stores/auth";
import { useLayoutStore } from "@/stores/layout"; import { useLayoutStore } from "@/stores/layout";
import { users as api } from "@/api"; import { users as api } from "@/api";
import AceEditorTheme from "@/components/settings/AceEditorTheme.vue";
import Languages from "@/components/settings/Languages.vue"; import Languages from "@/components/settings/Languages.vue";
import { inject, onMounted, ref } from "vue"; import { inject, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n"; import { useI18n } from "vue-i18n";
+4 -1
View File
@@ -17,7 +17,10 @@
</tr> </tr>
<tr v-for="user in users" :key="user.id"> <tr v-for="user in users" :key="user.id">
<td>{{ user.displayName || user.username }}</td> <td>
{{ user.displayName || user.username
}}<small class="user-record-id">ID {{ user.id }}</small>
</td>
<td>{{ user.scope }}</td> <td>{{ user.scope }}</td>
<td class="small"> <td class="small">
<router-link :to="'/settings/users/' + user.id" <router-link :to="'/settings/users/' + user.id"
+2
View File
@@ -17,6 +17,8 @@ type userInfo struct {
HideDotfiles bool `json:"hideDotfiles"` HideDotfiles bool `json:"hideDotfiles"`
DateFormat bool `json:"dateFormat"` DateFormat bool `json:"dateFormat"`
Username string `json:"username"` Username string `json:"username"`
ProfileName string `json:"profileName,omitempty"`
Email string `json:"email,omitempty"`
AceEditorTheme string `json:"aceEditorTheme"` AceEditorTheme string `json:"aceEditorTheme"`
} }
+58 -9
View File
@@ -31,6 +31,8 @@ type sessionIdentity struct {
type ssoClaims struct { type ssoClaims struct {
Subject string `json:"sub"` Subject string `json:"sub"`
Username string `json:"preferred_username"` Username string `json:"preferred_username"`
Name string `json:"name"`
Email string `json:"email"`
Roles []string `json:"roles"` Roles []string `json:"roles"`
} }
type loginAttempt struct { type loginAttempt struct {
@@ -57,6 +59,7 @@ type SSO struct {
server *settings.Server server *settings.Server
mu sync.Mutex mu sync.Mutex
provision sync.Mutex provision sync.Mutex
userIDs map[string]uint
attempts map[string]loginAttempt attempts map[string]loginAttempt
sessions map[[32]byte]*ssoSession sessions map[[32]byte]*ssoSession
} }
@@ -101,6 +104,12 @@ func NewSSO(ctx context.Context, store *storage.Storage, server *settings.Server
return nil, err return nil, err
} }
for _, u := range legacy { for _, u := range legacy {
if s.userIDs == nil {
s.userIDs = map[string]uint{}
}
if previous, ok := s.userIDs[u.Username]; !ok || u.ID < previous {
s.userIDs[u.Username] = u.ID
}
if u.Password != "!sso-disabled" || !u.LockPassword || u.Perm.Execute || len(u.Commands) > 0 || u.Perm.Admin { if u.Password != "!sso-disabled" || !u.LockPassword || u.Perm.Execute || len(u.Commands) > 0 || u.Perm.Admin {
u.Password = "!sso-disabled" u.Password = "!sso-disabled"
u.LockPassword = true u.LockPassword = true
@@ -219,6 +228,35 @@ func (s *SSO) callback(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Invalid SSO expiry", 401) http.Error(w, "Invalid SSO expiry", 401)
return return
} }
// Fetch profile data as VTNL Panel does, retaining signed identity and roles.
var metadata struct {
UserInfoURL string `json:"userinfo_endpoint"`
}
if err = s.provider.Claims(&metadata); err != nil {
http.Error(w, "Invalid SSO metadata", 401)
return
}
if metadata.UserInfoURL != "" {
profile, profileErr := s.provider.UserInfo(ctx, oauth2.StaticTokenSource(token))
if profileErr != nil || profile.Subject != claims.Subject {
http.Error(w, "Invalid SSO profile", 401)
return
}
var info ssoClaims
if err = profile.Claims(&info); err != nil {
http.Error(w, "Invalid SSO profile claims", 401)
return
}
if claims.Username == "" {
claims.Username = info.Username
}
if claims.Name == "" {
claims.Name = info.Name
}
if claims.Email == "" {
claims.Email = info.Email
}
}
identity, err := s.provisionUser(claims) identity, err := s.provisionUser(claims)
if err != nil { if err != nil {
http.Error(w, "Cannot provision SSO user", 500) http.Error(w, "Cannot provision SSO user", 500)
@@ -250,7 +288,11 @@ func (s *SSO) provisionUser(c ssoClaims) (sessionIdentity, error) {
// Namespace by issuer and subject, never by a renameable login or email. // Namespace by issuer and subject, never by a renameable login or email.
identityHash := sha256.Sum256([]byte(s.issuer + "\x00" + c.Subject)) identityHash := sha256.Sum256([]byte(s.issuer + "\x00" + c.Subject))
username := "sso:" + base64.RawURLEncoding.EncodeToString(identityHash[:]) username := "sso:" + base64.RawURLEncoding.EncodeToString(identityHash[:])
u, err := s.store.Users.Get(s.server.Root, s.server.FollowExternalSymlinks, username) var lookup interface{} = username
if id, ok := s.userIDs[username]; ok {
lookup = id
}
u, err := s.store.Users.Get(s.server.Root, s.server.FollowExternalSymlinks, lookup)
if errors.Is(err, fberrors.ErrNotExist) { if errors.Is(err, fberrors.ErrNotExist) {
st, err := s.store.Settings.Get() st, err := s.store.Settings.Get()
if err != nil { if err != nil {
@@ -269,19 +311,26 @@ func (s *SSO) provisionUser(c ssoClaims) (sessionIdentity, error) {
if err = s.store.Users.SaveProvisioned(u, derived); err != nil { if err = s.store.Users.SaveProvisioned(u, derived); err != nil {
return sessionIdentity{}, err return sessionIdentity{}, err
} }
if s.userIDs == nil {
s.userIDs = map[string]uint{}
}
s.userIDs[username] = u.ID
} else if err != nil { } else if err != nil {
return sessionIdentity{}, err return sessionIdentity{}, err
} }
if u.DisplayName != c.Username {
u.DisplayName = c.Username
if err = s.store.Users.Update(u, "DisplayName"); err != nil {
return sessionIdentity{}, err
}
}
name := c.Username name := c.Username
if name == "" {
name = c.Name
}
if name == "" { if name == "" {
name = c.Subject name = c.Subject
} }
if u.DisplayName != name || u.ProfileName != c.Name || u.Email != c.Email {
u.DisplayName, u.ProfileName, u.Email = name, c.Name, c.Email
if err = s.store.Users.Update(u, "DisplayName", "ProfileName", "Email"); err != nil {
return sessionIdentity{}, err
}
}
return sessionIdentity{ID: u.ID, Name: name, Admin: ssoAdmin(c.Roles)}, nil return sessionIdentity{ID: u.ID, Name: name, Admin: ssoAdmin(c.Roles)}, nil
} }
@@ -384,8 +433,8 @@ func applySSOIdentity(u *users.User, i sessionIdentity) {
u.Perm.Execute = false u.Perm.Execute = false
u.LockPassword = true u.LockPassword = true
u.Commands = []string{} u.Commands = []string{}
u.Username = i.Name u.DisplayName = i.Name
} }
func ssoUserInfo(u *users.User) userInfo { func ssoUserInfo(u *users.User) userInfo {
return userInfo{ID: u.ID, Username: u.Username, Locale: u.Locale, ViewMode: u.ViewMode, SingleClick: u.SingleClick, RedirectAfterCopyMove: u.RedirectAfterCopyMove, Perm: u.Perm, Commands: []string{}, LockPassword: true, HideDotfiles: u.HideDotfiles, DateFormat: u.DateFormat, AceEditorTheme: u.AceEditorTheme} return userInfo{ID: u.ID, Username: u.DisplayName, ProfileName: u.ProfileName, Email: u.Email, Locale: u.Locale, ViewMode: u.ViewMode, SingleClick: u.SingleClick, RedirectAfterCopyMove: u.RedirectAfterCopyMove, Perm: u.Perm, Commands: []string{}, LockPassword: true, HideDotfiles: u.HideDotfiles, DateFormat: u.DateFormat, AceEditorTheme: u.AceEditorTheme}
} }
+45 -2
View File
@@ -29,6 +29,7 @@ func TestOIDCSessionLifecycle(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
var issuer, nonce, challenge string var issuer, nonce, challenge string
profileSubject := "subject-123"
roles := []string{"FS Admin"} roles := []string{"FS Admin"}
enabled := true enabled := true
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -51,7 +52,7 @@ func TestOIDCSessionLifecycle(t *testing.T) {
t.Error("client authentication mismatch") t.Error("client authentication mismatch")
} }
hash := sha256.Sum256([]byte("access")) hash := sha256.Sum256([]byte("access"))
claims := map[string]any{"iss": issuer, "aud": "client", "sub": "subject-123", "preferred_username": "alice", "roles": roles, "nonce": nonce, "exp": time.Now().Add(5 * time.Minute).Unix(), "iat": time.Now().Unix(), "at_hash": base64.RawURLEncoding.EncodeToString(hash[:16])} claims := map[string]any{"iss": issuer, "aud": "client", "sub": "subject-123", "roles": roles, "nonce": nonce, "exp": time.Now().Add(5 * time.Minute).Unix(), "iat": time.Now().Unix(), "at_hash": base64.RawURLEncoding.EncodeToString(hash[:16])}
b, _ := json.Marshal(claims) b, _ := json.Marshal(claims)
signed, _ := signer.Sign(b) signed, _ := signer.Sign(b)
token, _ := signed.CompactSerialize() token, _ := signed.CompactSerialize()
@@ -61,7 +62,10 @@ func TestOIDCSessionLifecycle(t *testing.T) {
w.WriteHeader(401) w.WriteHeader(401)
return return
} }
_ = json.NewEncoder(w).Encode(ssoClaims{Subject: "subject-123", Username: "alice", Roles: roles}) if r.Header.Get("Authorization") != "Bearer access" {
t.Error("missing UserInfo bearer")
}
_ = json.NewEncoder(w).Encode(ssoClaims{Subject: profileSubject, Username: "alice", Name: "Alice Example", Email: "alice@example.test", Roles: []string{"User"}})
default: default:
w.WriteHeader(404) w.WriteHeader(404)
} }
@@ -116,6 +120,25 @@ func TestOIDCSessionLifecycle(t *testing.T) {
if check.Code != 200 || !strings.Contains(check.Body.String(), `"admin":true`) { if check.Code != 200 || !strings.Contains(check.Body.String(), `"admin":true`) {
t.Fatalf("session: %d %s", check.Code, check.Body.String()) t.Fatalf("session: %d %s", check.Code, check.Body.String())
} }
if !strings.Contains(check.Body.String(), `"username":"alice"`) || !strings.Contains(check.Body.String(), `"email":"alice@example.test"`) {
t.Fatalf("UserInfo profile not loaded: %s", check.Body.String())
}
// Repeated logins after changing preferences retain one local identity.
var firstID uint
for i := 0; i < 3; i++ {
identity, err := s.provisionUser(ssoClaims{Subject: "subject-123", Username: "alice"})
if err != nil {
t.Fatal(err)
}
if i == 0 {
firstID = identity.ID
} else if identity.ID != firstID {
t.Fatal("new user on repeated login")
}
if err = st.Users.Update(&users.User{ID: identity.ID, Username: "alice", Locale: "ru"}, "Locale"); err != nil {
t.Fatal(err)
}
}
roles = []string{"User"} roles = []string{"User"}
check = request("GET", "/api/session") check = request("GET", "/api/session")
if check.Code != 200 || !strings.Contains(check.Body.String(), `"admin":true`) { if check.Code != 200 || !strings.Contains(check.Body.String(), `"admin":true`) {
@@ -143,7 +166,27 @@ func TestOIDCSessionLifecycle(t *testing.T) {
if w.Code != 400 { if w.Code != 400 {
t.Fatal("callback replay accepted") t.Fatal("callback replay accepted")
} }
login = httptest.NewRecorder()
h.ServeHTTP(login, httptest.NewRequest("GET", "/auth/login", nil))
u, _ = url.Parse(login.Header().Get("Location"))
nonce, challenge = u.Query().Get("nonce"), u.Query().Get("code_challenge")
profileSubject = "another-subject"
callback = httptest.NewRequest("GET", "/auth/callback?code=test&state="+u.Query().Get("state"), nil)
callback.AddCookie(login.Result().Cookies()[0])
w = httptest.NewRecorder()
h.ServeHTTP(w, callback)
if w.Code != 401 {
t.Fatal("mismatched UserInfo subject accepted")
}
// Expired/idle sessions are rejected, even with an otherwise valid cookie. // Expired/idle sessions are rejected, even with an otherwise valid cookie.
restarted, err := NewSSO(context.Background(), st, &settings.Server{Root: root}, SSOConfig{Issuer: issuer, ClientID: "client", ClientSecret: "secret", PublicURL: "http://127.0.0.1:9111"})
if err != nil {
t.Fatal(err)
}
identity, err := restarted.provisionUser(ssoClaims{Subject: "subject-123", Username: "alice"})
if err != nil || identity.ID != firstID {
t.Fatalf("identity changed after restart: %+v %v", identity, err)
}
sessionKey := sha256.Sum256([]byte(sessionCookie.Value)) sessionKey := sha256.Sum256([]byte(sessionCookie.Value))
for _, tc := range []struct{ expires, touched time.Time }{{time.Now().Add(-time.Second), time.Now()}, {time.Now().Add(time.Hour), time.Now().Add(-31 * time.Minute)}} { for _, tc := range []struct{ expires, touched time.Time }{{time.Now().Add(-time.Second), time.Now()}, {time.Now().Add(time.Hour), time.Now().Add(-31 * time.Minute)}} {
s.mu.Lock() s.mu.Lock()
+1 -1
View File
@@ -1,4 +1,4 @@
param([string]$Version = '3.0.0-sso.1') param([string]$Version = '3.0.0-sso.2')
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
$repo = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path $repo = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Push-Location $repo Push-Location $repo
+1 -1
View File
@@ -1,7 +1,7 @@
#!/bin/sh #!/bin/sh
set -eu set -eu
cd "$(dirname "$0")/.." cd "$(dirname "$0")/.."
VERSION="${VERSION:-3.0.0-sso.1}" VERSION="${VERSION:-3.0.0-sso.2}"
COMMIT=$(git rev-parse --short HEAD) COMMIT=$(git rev-parse --short HEAD)
(cd frontend && pnpm install --frozen-lockfile && pnpm run build) (cd frontend && pnpm install --frozen-lockfile && pnpm run build)
mkdir -p build/release/linux-amd64 mkdir -p build/release/linux-amd64
+8 -1
View File
@@ -78,6 +78,12 @@ func (st usersBackend) Update(user *users.User, fields ...string) error {
if len(fields) == 0 { if len(fields) == 0 {
return st.Save(user) return st.Save(user)
} }
// Storm extracts every index from the object passed to UpdateField, even
// for a non-indexed field. Never index partial/request presentation data.
current, err := st.GetBy(user.ID)
if err != nil {
return err
}
for _, field := range fields { for _, field := range fields {
userField := reflect.ValueOf(user).Elem().FieldByName(field) userField := reflect.ValueOf(user).Elem().FieldByName(field)
@@ -85,7 +91,8 @@ func (st usersBackend) Update(user *users.User, fields ...string) error {
return fmt.Errorf("invalid field: %s", field) return fmt.Errorf("invalid field: %s", field)
} }
val := userField.Interface() val := userField.Interface()
if err := st.db.UpdateField(user, field, val); err != nil { reflect.ValueOf(current).Elem().FieldByName(field).Set(userField)
if err := st.db.UpdateField(current, field, val); err != nil {
return err return err
} }
} }
+29
View File
@@ -11,6 +11,35 @@ import (
"github.com/filebrowser/filebrowser/v2/users" "github.com/filebrowser/filebrowser/v2/users"
) )
func TestPartialUserUpdatePreservesIdentityIndex(t *testing.T) {
db, err := storm.Open(filepath.Join(t.TempDir(), "db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Close() })
st, err := NewStorage(db)
if err != nil {
t.Fatal(err)
}
u := &users.User{Username: "sso:stable-subject", Password: "!sso-disabled", Scope: "/", Locale: "en"}
if err = st.Users.Save(u); err != nil {
t.Fatal(err)
}
// The session/API uses a presentation name and may omit other fields.
for _, presentation := range []string{"Alice", "", "Alice Renamed"} {
if err = st.Users.Update(&users.User{ID: u.ID, Username: presentation, Locale: "ru"}, "Locale"); err != nil {
t.Fatal(err)
}
got, err := st.Users.Get("", false, "sso:stable-subject")
if err != nil {
t.Fatalf("identity lookup lost after preference update: %v", err)
}
if got.ID != u.ID || got.Username != u.Username || got.Locale != "ru" {
t.Fatalf("unexpected user: %+v", got)
}
}
}
// GetByScope must match case-insensitively: on a case-insensitive filesystem // GetByScope must match case-insensitively: on a case-insensitive filesystem
// two scopes that differ only in case resolve to the same home directory, so // two scopes that differ only in case resolve to the same home directory, so
// the provisioning collision check has to treat them as the same scope. // the provisioning collision check has to treat them as the same scope.
+2
View File
@@ -22,6 +22,8 @@ type User struct {
ID uint `storm:"id,increment" json:"id"` ID uint `storm:"id,increment" json:"id"`
Username string `storm:"unique" json:"username"` Username string `storm:"unique" json:"username"`
DisplayName string `json:"displayName,omitempty"` DisplayName string `json:"displayName,omitempty"`
ProfileName string `json:"profileName,omitempty"`
Email string `json:"email,omitempty"`
Password string `json:"password"` Password string `json:"password"`
Scope string `json:"scope"` Scope string `json:"scope"`
Locale string `json:"locale"` Locale string `json:"locale"`