feat: adopt shared internal SSO sessions and add no-sso launch mode

This commit is contained in:
SantaSpeen committed 2026-10-24 15:41:39 +03:00
1 parent c209f1effc
commit c02bf755f2
51 files changed
+2131 -362

No files matched your search

+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "filebrowser-frontend",
"version": "3.1.0",
"version": "3.2.0",
"private": true,
"type": "module",
"engines": {
@@ -39,7 +39,7 @@
"pinia": "^3.0.4",
"pretty-bytes": "^7.2.0",
"tus-js-client": "^4.3.1",
"utif": "^3.1.0",
"utif": "^3.2.0",
"video.js": "^8.24.2",
"videojs-hotkeys": "^0.2.30",
"videojs-mobile-ui": "^1.2.7",
+221
View File
@@ -0,0 +1,221 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const { chromium } = require(process.env.PLAYWRIGHT_MODULE);
(async () => {
const browser = await chromium.launch({
executablePath: process.env.BROWSER_EXECUTABLE,
headless: true,
args: ["--host-resolver-rules=MAP *.localhost 127.0.0.1"],
});
const output = process.env.FILEBROWSER_QA_OUTPUT;
fs.mkdirSync(output, { recursive: true });
const errors = [];
const contexts = [];
const change = async (values) => {
const response = await contexts[0].request.post(
process.env.QA_ISSUER + "/__qa/change",
{
headers: { "X-QA-Control": process.env.QA_CONTROL },
data: {
Name: "Alice",
Version: "A-1",
Status: "authenticated",
Denied: false,
Offline: false,
...values,
},
}
);
assert.equal(response.status(), 204);
};
try {
const context = await browser.newContext({
ignoreHTTPSErrors: true,
viewport: { width: 1300, height: 900 },
locale: "en-US",
});
contexts.push(context);
await context.route("**/internal/session/frame?**", (route) =>
route.abort()
);
const cookies = (device) =>
[
["one", process.env.QA_APP_ONE],
["two", process.env.QA_APP_TWO],
].map(([id, url]) => ({
name: "__Host-internal_session",
value: id + "-" + device + "-binding-123456789",
url,
secure: true,
httpOnly: true,
sameSite: "Lax",
}));
await context.addCookies(cookies("device-one"));
const a = await context.newPage(),
b = await context.newPage();
for (const p of [a, b]) p.on("pageerror", (e) => errors.push(String(e)));
await Promise.all([
a.goto(process.env.QA_APP_ONE + "/files/"),
b.goto(process.env.QA_APP_TWO + "/files/"),
]);
try {
await Promise.all([
a.getByText("Alice-private.txt", { exact: true }).waitFor(),
b.getByText("Alice-private.txt", { exact: true }).waitFor(),
]);
} catch (error) {
console.log("INITIAL ERRORS", errors);
for (const [index, page] of [a, b].entries()) {
console.log("BODY", index, await page.locator("body").innerText());
console.log(
"SESSION",
await (
await context.request.get(
(index === 0 ? process.env.QA_APP_ONE : process.env.QA_APP_TWO) +
"/auth/session"
)
).text()
);
await page.screenshot({
path: path.join(output, `initial-${index}.png`),
});
}
throw error;
}
const device2 = await browser.newContext({ ignoreHTTPSErrors: true });
contexts.push(device2);
await device2.addCookies(cookies("device-two"));
const independent = await device2.newPage();
await independent.goto(process.env.QA_APP_ONE + "/files/");
await independent.getByText("Alice-private.txt", { exact: true }).waitFor();
// Hold a valid A response until after both applications have switched to B.
let release;
const held = new Promise((r) => (release = r));
let ready;
const captured = new Promise((r) => (ready = r));
let didHold = false;
await a.route("**/api/resources/", async (route) => {
if (didHold) {
await route.continue();
return;
}
didHold = true;
const response = await route.fetch();
ready();
await held;
await route.fulfill({ response }).catch(() => {});
});
await a.getByRole("button", { name: "Actions", exact: true }).click();
await a.getByRole("menuitem", { name: "Refresh", exact: true }).click();
await captured;
await change({ Name: "Bob", Version: "B-1" });
await Promise.all([
a
.getByText("Bob-private.txt", { exact: true })
.waitFor({ timeout: 15000 }),
b
.getByText("Bob-private.txt", { exact: true })
.waitFor({ timeout: 15000 }),
]);
release();
await a.unroute("**/api/resources/");
await a.waitForTimeout(200);
assert.equal(
await a.getByText("Alice-private.txt", { exact: true }).count(),
0
);
assert.equal(
await b.getByText("Alice-private.txt", { exact: true }).count(),
0
);
assert(
await independent
.getByText("Alice-private.txt", { exact: true })
.isVisible()
);
assert(!new URL(a.url()).pathname.startsWith("/auth/"));
assert(!new URL(b.url()).pathname.startsWith("/auth/"));
await a.screenshot({ path: path.join(output, "account-B.png") });
const stale = await context.request.post(
process.env.QA_APP_ONE + "/api/resources/stale.txt",
{
headers: { "X-FB-Request": "1", "X-FB-Session-State": "A-1" },
data: "must not write",
}
);
assert.equal(stale.status(), 409);
await change({ Name: "Bob", Version: "B-1", Denied: true });
await b
.getByRole("heading", { name: "Access denied", exact: true })
.waitFor({ timeout: 15000 });
assert.equal(
await b.getByText("Alice-private.txt", { exact: true }).count(),
0
);
assert.equal(
await b.getByText("Bob-private.txt", { exact: true }).count(),
0
);
await change({ Name: "Bob", Version: "B-1", Offline: true });
await a
.getByRole("heading", {
name: "Sign-in service unavailable",
exact: true,
})
.waitFor({ timeout: 15000 });
assert.equal(
await a.getByText("Bob-private.txt", { exact: true }).count(),
0
);
assert(
(await context.cookies(process.env.QA_APP_ONE)).some(
(c) => c.name === "__Host-internal_session"
)
);
await change({ Name: "Bob", Version: "B-2" });
await a
.getByText("Bob-private.txt", { exact: true })
.waitFor({ timeout: 15000 });
const logout = await context.request.post(
process.env.QA_APP_ONE + "/auth/logout",
{ headers: { "X-FB-Request": "1", "X-FB-Session-State": "B-2" } }
);
assert.equal(logout.status(), 204);
await b
.getByRole("heading", { name: "Signed out", exact: true })
.waitFor({ timeout: 15000 });
assert(
await independent
.getByText("Alice-private.txt", { exact: true })
.isVisible()
);
await change({ Status: "factor_required", Version: "factor" });
await b
.getByRole("heading", { name: "Verify your sign-in", exact: true })
.waitFor({ timeout: 15000 });
assert(!new URL(b.url()).pathname.startsWith("/auth/"));
const cookiesAtEnd = await context.cookies(process.env.QA_APP_TWO);
const binding = cookiesAtEnd.find(
(c) => c.name === "__Host-internal_session"
);
assert(
binding &&
binding.secure &&
binding.httpOnly &&
binding.path === "/" &&
!binding.domain.startsWith(".")
);
assert.equal(errors.length, 0, errors.join("\n"));
console.log(
"Two apps: A→B, stale form, denied access, outage/recovery, shared logout, missing factor and independent device passed."
);
} finally {
for (const c of contexts) await c.close();
await browser.close();
}
})().catch((error) => {
console.error(error);
process.exitCode = 1;
});
+121
View File
@@ -0,0 +1,121 @@
const fs = require("node:fs"),
path = require("node:path"),
assert = require("node:assert/strict"),
{ spawn } = require("node:child_process");
const { chromium } = require(process.env.PLAYWRIGHT_MODULE);
(async () => {
const root = fs.mkdtempSync(
path.join(process.env.FILEBROWSER_QA_OUTPUT, "no-sso-")
);
const files = path.join(root, "files");
fs.mkdirSync(files);
fs.writeFileSync(path.join(files, "anonymous.txt"), "NO PASSWORD");
const config = path.join(root, "config.json"),
db = path.join(root, "test.db");
fs.writeFileSync(
config,
JSON.stringify({
root: files,
database: db,
sso: { issuer: "invalid-provider-configuration" },
})
);
const args = [
"--config",
config,
"--root",
files,
"--database",
db,
"--port",
"0",
];
const processOne = spawn(process.env.FILEBROWSER_EXE, [...args, "--no-sso"], {
cwd: root,
windowsHide: true,
stdio: ["ignore", "pipe", "pipe"],
});
let logs = "",
browser;
const started = new Promise((resolve, reject) => {
const timeout = setTimeout(
() => reject(Error("startup timeout " + logs)),
12000
);
const read = (chunk) => {
logs += chunk.toString();
const found = logs.match(/Listening on (127\.0\.0\.1:\d+)/);
if (found) {
clearTimeout(timeout);
resolve("http://" + found[1]);
}
};
processOne.stdout.on("data", read);
processOne.stderr.on("data", read);
processOne.once("exit", (code) => {
clearTimeout(timeout);
reject(Error("exited " + code + " " + logs));
});
});
try {
const url = await started;
browser = await chromium.launch({
executablePath: process.env.BROWSER_EXECUTABLE,
headless: true,
});
const context = await browser.newContext();
const page = await context.newPage();
const response = await context.request.get(url + "/api/session");
assert.equal(response.status(), 200);
const user = await response.json();
assert.equal(user.authMode, "no-sso");
assert.equal(user.perm.admin, true);
await page.goto(url + "/files/");
await page.getByText("anonymous.txt", { exact: true }).waitFor();
assert.equal(await page.locator("iframe").count(), 0);
assert.equal(await page.locator('a[href$="/auth/account"]').count(), 0);
const write = await context.request.post(
url + "/api/resources/created.txt",
{ headers: { "X-FB-Request": "1" }, data: "CREATED WITHOUT PASSWORD" }
);
assert.equal(write.status(), 200);
assert.equal(
fs.readFileSync(path.join(files, "created.txt"), "utf8"),
"CREATED WITHOUT PASSWORD"
);
await page.screenshot({ path: path.join(root, "anonymous-workspace.png") });
} finally {
if (browser) await browser.close();
if (processOne.exitCode === null) {
processOne.kill();
await new Promise((r) => processOne.once("exit", r));
}
fs.writeFileSync(path.join(root, "server.log"), logs);
}
const normal = spawn(process.env.FILEBROWSER_EXE, args, {
cwd: root,
windowsHide: true,
stdio: ["ignore", "pipe", "pipe"],
});
let normalLogs = "";
normal.stdout.on("data", (d) => (normalLogs += d));
normal.stderr.on("data", (d) => (normalLogs += d));
const code = await new Promise((resolve, reject) => {
const timer = setTimeout(() => {
normal.kill();
reject(Error("SSO mode unexpectedly started"));
}, 12000);
normal.once("exit", (code) => {
clearTimeout(timer);
resolve(code);
});
});
assert.notEqual(code, 0);
assert(!normalLogs.includes("Listening on"));
console.log(
"CLI --no-sso: no provider, cookie or password; reads/writes and administrator UI passed. Without flag, invalid SSO cannot start."
);
})().catch((e) => {
console.error(e);
process.exitCode = 1;
});
+57 -3
View File
@@ -1,22 +1,76 @@
<template>
<div>
<h1 class="sr-only">{{ name }}</h1>
<router-view></router-view>
<SessionGate v-if="blocked" />
<router-view v-else :key="auth.epoch"></router-view>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { ref, onMounted, onBeforeUnmount, computed, watch } from "vue";
import { useI18n } from "vue-i18n";
import { setHtmlLocale } from "./i18n";
import { getMediaPreference, getTheme, setTheme } from "./utils/theme";
import { name } from "./utils/constants";
import { useRoute, useRouter } from "vue-router";
import { useAuthStore } from "@/stores/auth";
import { acceptSession, setSessionRecheck } from "@/utils/auth";
import SessionGate from "@/components/SessionGate.vue";
import "@/utils/internal-session.js";
import { baseURL, noAuth } from "@/utils/constants";
const auth = useAuthStore(),
route = useRoute(),
router = useRouter();
watch(
() => auth.user?.id,
(id, old) => {
if (id && old && id !== old && route.meta.requiresAuth)
void router.replace("/files/");
}
);
watch(
() => auth.user?.perm.admin,
(admin) => {
if (admin === false && route.meta.requiresAdmin)
void router.replace("/403");
}
);
const blocked = computed(
() =>
!["Login", "Share"].includes(String(route.name)) &&
auth.sessionStatus !== "authenticated"
);
let sync: { stop: () => void } | undefined;
onBeforeUnmount(() => {
sync?.stop();
setSessionRecheck();
});
const { locale } = useI18n();
const userTheme = ref<UserTheme>(getTheme() || getMediaPreference());
onMounted(() => {
onMounted(async () => {
await router.isReady();
if (
!noAuth &&
window.FileBrowser.SSOIssuer &&
window.FileBrowser.SSOClientID
) {
const restart = () => {
sync?.stop();
sync = window.SSOInternalSession.start({
issuer: window.FileBrowser.SSOIssuer,
clientId: window.FileBrowser.SSOClientID,
checkUrl: baseURL + "/auth/session",
onChange: acceptSession,
onUnavailable: () =>
acceptSession({ status: "unavailable", authenticated: false }),
});
};
restart();
setSessionRecheck(restart);
}
setTheme(userTheme.value, false);
setHtmlLocale(locale.value);
// this might be null during HMR
+10
View File
@@ -1,3 +1,4 @@
import { sessionScope, sessionIsCurrent } from "@/utils/session-scope";
import { useLayoutStore } from "@/stores/layout";
import { baseURL } from "@/utils/constants";
import { upload as postTus, useTus } from "./tus";
@@ -112,6 +113,7 @@ export async function post(
overwrite = false,
onupload: any = () => {}
) {
const scope = sessionScope();
// Use the pre-existing API if:
const useResourcesApi =
// a folder is being created
@@ -121,6 +123,7 @@ export async function post(
!["http:", "https:"].includes(window.location.protocol)) ||
// Tus is disabled / not applicable
!(await useTus(content));
if (!sessionIsCurrent(scope.generation)) throw new Error("Upload aborted");
return useResourcesApi
? postResources(url, content, overwrite, onupload)
: postTus(url, content, overwrite, onupload);
@@ -143,6 +146,7 @@ async function postResources(
}
return new Promise((resolve, reject) => {
const scope = sessionScope();
const request = new XMLHttpRequest();
resourceUploads.add(request);
request.onloadend = () => resourceUploads.delete(request);
@@ -153,12 +157,17 @@ async function postResources(
true
);
request.setRequestHeader("X-FB-Request", "1");
request.setRequestHeader("X-FB-Session-State", scope.state);
if (typeof onupload === "function") {
request.upload.onprogress = onupload;
}
request.onload = () => {
if (!sessionIsCurrent(scope.generation)) {
reject(new Error("Upload aborted"));
return;
}
if (request.status === 200) {
resolve(request.responseText);
} else if (request.status === 409) {
@@ -225,6 +234,7 @@ export function getPreviewURL(file: ResourceItem, size: string) {
const params = {
inline: "true",
key: Date.parse(file.modified),
account: sessionScope().generation,
};
return createURL("api/preview/" + size + file.path, params);
+7 -2
View File
@@ -1,3 +1,4 @@
import { sessionScope } from "@/utils/session-scope";
import * as tus from "tus-js-client";
import { baseURL, tusEndpoint, tusSettings, origin } from "@/utils/constants";
import { removePrefix } from "@/api/utils";
@@ -17,6 +18,7 @@ export async function upload(
throw new Error("Tus.io settings are not defined");
}
const scope = sessionScope();
filePath = removePrefix(filePath);
const resourcePath = `${tusEndpoint}${filePath}?override=${overwrite}`;
@@ -33,6 +35,7 @@ export async function upload(
storeFingerprintForResuming: false,
headers: {
"X-FB-Request": "1",
"X-FB-Session-State": scope.state,
},
onShouldRetry: function (err) {
const status = err.originalResponse
@@ -40,7 +43,7 @@ export async function upload(
: 0;
// Do not retry for file conflict.
if (status === 409 || status === 401 || status === 403) {
if ([409, 401, 403, 428, 503].includes(status)) {
return false;
}
@@ -109,7 +112,9 @@ function isTusSupported() {
export function abortAllUploads() {
for (const filePath in CURRENT_UPLOAD_LIST) {
if (CURRENT_UPLOAD_LIST[filePath]) {
CURRENT_UPLOAD_LIST[filePath].abort(true);
void CURRENT_UPLOAD_LIST[filePath].abort(true).catch(() => {
/* A switched account cannot cancel the previous account's server transfer. */
});
CURRENT_UPLOAD_LIST[filePath].options!.onError!(
new Error("Upload aborted")
);
+43 -6
View File
@@ -1,5 +1,9 @@
import { useAuthStore } from "@/stores/auth";
import { startLogin } from "@/utils/auth";
import {
sessionScope,
sessionIsCurrent,
mergeSignals,
} from "@/utils/session-scope";
import { validateLogin, acceptSession } from "@/utils/auth";
import { baseURL } from "@/utils/constants";
import { encodePath } from "@/utils/url";
@@ -19,7 +23,7 @@ export async function fetchURL(
opts: ApiOpts,
auth = true
): Promise<Response> {
const authStore = useAuthStore();
const scope = sessionScope();
opts = opts || {};
opts.headers = opts.headers || {};
@@ -30,9 +34,13 @@ export async function fetchURL(
res = await fetch(`${baseURL}${url}`, {
headers: {
"X-FB-Request": "1",
"X-FB-Session-State": scope.state,
...headers,
},
...rest,
signal: opts.signal
? mergeSignals(opts.signal, scope.signal)
: scope.signal,
});
} catch (e) {
// Check if the error is an intentional cancellation
@@ -42,6 +50,19 @@ export async function fetchURL(
throw new StatusError("000 No connection", 0);
}
if (!sessionIsCurrent(scope.generation))
throw new StatusError("Session changed", 409, true);
for (const method of ["json", "text", "arrayBuffer", "blob"] as const) {
const read = res[method].bind(res);
Object.defineProperty(res, method, {
value: async () => {
const result = await read();
if (!sessionIsCurrent(scope.generation))
throw new StatusError("Session changed", 409, true);
return result;
},
});
}
if (res.status < 200 || res.status > 299) {
const body = await res.text();
const error = new StatusError(
@@ -49,10 +70,26 @@ export async function fetchURL(
res.status
);
if (auth && res.status == 401) {
authStore.clearUser();
startLogin();
if (
[401, 403, 409, 428, 503].includes(res.status) &&
!url.startsWith("/api/public/")
) {
try {
const state = JSON.parse(body);
if (typeof state.status === "string")
acceptSession({
status:
state.status === "session_changed" ? "checking" : state.status,
authenticated: false,
session_state: state.session_state,
required_factors: state.required_factors,
});
} catch {
/* Ordinary file permission errors do not change identity. */
}
void validateLogin();
}
void auth;
throw error;
}
+55
View File
@@ -0,0 +1,55 @@
<template>
<main class="sso-welcome" role="alert">
<div class="sso-symbol"><AppIcon name="account_circle" /></div>
<h1>{{ t("session." + message) }}</h1>
<p>{{ t("session." + message + "Hint") }}</p>
<button
v-if="
['factor_required', 'rebind_required', 'signed_out'].includes(
auth.sessionStatus
)
"
class="button"
@click="startLogin(undefined, auth.sessionStatus === 'rebind_required')"
>
{{ t("session.continue") }}
</button>
<a
v-if="
auth.sessionStatus === 'access_denied' ||
auth.sessionStatus === 'factor_enrollment_required'
"
class="button"
:href="baseURL + '/auth/account'"
>{{ t("preferences.manage") }}</a
>
<button
v-if="auth.sessionStatus === 'unavailable'"
class="button"
@click="validateLogin"
>
{{ t("session.retry") }}
</button>
</main>
</template>
<script setup lang="ts">
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { useAuthStore } from "@/stores/auth";
import { baseURL } from "@/utils/constants";
import { startLogin, validateLogin } from "@/utils/auth";
const auth = useAuthStore(),
{ t } = useI18n();
const message = computed(() =>
[
"checking",
"access_denied",
"factor_required",
"rebind_required",
"signed_out",
"factor_enrollment_required",
].includes(auth.sessionStatus)
? auth.sessionStatus
: "unavailable"
);
</script>
+4
View File
@@ -113,6 +113,7 @@
@keydown="menuKey"
>
<a
v-if="!noAuth"
role="menuitem"
:href="baseURL + '/auth/account'"
@click="navigate"
@@ -145,6 +146,9 @@
}}</router-link
>
<button v-if="canLogout" role="menuitem" @click="signOut(true)">
<AppIcon name="account_circle" />{{ t("session.switchAccount") }}
</button>
<button v-if="canLogout" role="menuitem" @click="logout">
<AppIcon name="logout" />{{ t("sidebar.logout") }}
</button>
@@ -30,6 +30,7 @@ interface IProps {
zoomStep?: number;
}
const pendingImages = new Set<XMLHttpRequest>();
const props = withDefaults(defineProps<IProps>(), {
moveDisabledTime: () => 200,
classList: () => [],
@@ -88,6 +89,15 @@ onMounted(() => {
});
onBeforeUnmount(() => {
for (const xhr of pendingImages) {
xhr.abort();
const i = UTIF._xhrs.indexOf(xhr);
if (i >= 0) {
UTIF._xhrs.splice(i, 1);
UTIF._imgs.splice(i, 1);
}
}
pendingImages.clear();
window.removeEventListener("resize", onResize);
document.removeEventListener("mouseup", onMouseUp);
});
@@ -119,11 +129,15 @@ const decodeUTIF = () => {
if (sufs.indexOf(suff) == -1) return false;
const xhr = new XMLHttpRequest();
pendingImages.add(xhr);
UTIF._xhrs.push(xhr);
UTIF._imgs.push(imgex.value);
xhr.open("GET", props.src);
xhr.responseType = "arraybuffer";
xhr.onload = UTIF._imgLoaded;
xhr.onload = (event) => {
pendingImages.delete(xhr);
UTIF._imgLoaded(event);
};
xhr.send();
return true;
};
+19
View File
@@ -490,5 +490,24 @@
"remaining": "{time} remaining",
"seconds": "s",
"minutes": "min"
},
"session": {
"checking": "Checking session",
"checkingHint": "Verifying your current session.",
"access_denied": "Access denied",
"access_deniedHint": "The current account cannot access this application.",
"factor_required": "Verify your sign-in",
"factor_requiredHint": "Complete TOTP or Passkey verification in the sign-in service.",
"factor_enrollment_required": "Set up account protection",
"factor_enrollment_requiredHint": "Add TOTP or a Passkey in your account settings to continue.",
"rebind_required": "Sign-in required",
"rebind_requiredHint": "Restore the connection to your current account.",
"signed_out": "Signed out",
"signed_outHint": "Sign in to continue.",
"unavailable": "Sign-in service unavailable",
"unavailableHint": "Access is temporarily blocked. Try again later.",
"continue": "Continue",
"retry": "Retry",
"switchAccount": "Switch account"
}
}
+19
View File
@@ -487,5 +487,24 @@
"remaining": "Осталось {time}",
"seconds": "с",
"minutes": "мин"
},
"session": {
"checking": "Проверка входа",
"checkingHint": "Проверяем текущую сессию.",
"access_denied": "Нет доступа",
"access_deniedHint": "У текущего аккаунта нет доступа к этому приложению.",
"factor_required": "Подтвердите вход",
"factor_requiredHint": "Завершите проверку TOTP или Passkey в сервисе входа.",
"factor_enrollment_required": "Подключите защиту аккаунта",
"factor_enrollment_requiredHint": "Для доступа необходимо подключить TOTP или Passkey в настройках аккаунта.",
"rebind_required": "Требуется вход",
"rebind_requiredHint": "Восстановите привязку к текущему аккаунту.",
"signed_out": "Вы вышли из аккаунта",
"signed_outHint": "Войдите, чтобы продолжить.",
"unavailable": "Сервис входа недоступен",
"unavailableHint": "Доступ временно закрыт. Повторите проверку позже.",
"continue": "Продолжить",
"retry": "Повторить",
"switchAccount": "Сменить аккаунт"
}
}
+2
View File
@@ -45,6 +45,8 @@ app.use(Toast, {
newestOnTop: true,
} satisfies PluginOptions);
window.addEventListener("fb-session-boundary", () => useToast().clear());
app.use(i18n);
app.use(pinia);
app.use(router);
+11 -3
View File
@@ -1,3 +1,4 @@
import { sessionScope } from "@/utils/session-scope";
import { defineStore } from "pinia";
import { fetchJSON } from "@/api/utils";
export interface Addon {
@@ -17,21 +18,28 @@ export interface Addon {
total: number;
}
let request: Promise<void> | undefined;
let requestGeneration = -1;
export const useAddonsStore = defineStore("addons", {
state: () => ({ items: [] as Addon[], loaded: false }),
actions: {
async refresh(force = false): Promise<void> {
const generation = sessionScope().generation;
if (requestGeneration !== generation) {
request = undefined;
requestGeneration = generation;
}
if (request)
return request.then(() => (force ? this.refresh() : undefined));
request = fetchJSON<Addon[]>("/api/addons")
const active: Promise<void> = fetchJSON<Addon[]>("/api/addons")
.then((items) => {
this.items = items;
this.loaded = true;
})
.finally(() => {
request = undefined;
if (request === active) request = undefined;
});
return request;
request = active;
return active;
},
available(id: string) {
return this.items.some(
+8
View File
@@ -7,9 +7,17 @@ export const useAuthStore = defineStore("auth", {
state: (): {
user: IUser | null;
logoutTimer: number | null;
sessionStatus: string;
sessionState: string;
requiredFactors: string[];
epoch: number;
} => ({
user: null,
logoutTimer: null,
sessionStatus: "checking",
sessionState: "",
requiredFactors: [],
epoch: 0,
}),
getters: {
isLoggedIn: (state) => state.user !== null,
+8
View File
@@ -2,9 +2,17 @@ import { createPinia as _createPinia } from "pinia";
import { markRaw } from "vue";
import type { Router } from "vue-router";
const accountStores = new Set<any>();
export function resetAccountStores() {
for (const store of accountStores) {
if (["auth", "router", "upload"].includes(store.$id)) continue;
store.$reset();
}
}
export default function createPinia(router: Router) {
const pinia = _createPinia();
pinia.use(({ store }) => {
accountStores.add(store);
store.router = markRaw(router);
});
+11 -2
View File
@@ -17,6 +17,7 @@ const beforeUnload = (event: Event) => {
export const useUploadStore = defineStore("upload", () => {
const $showError = inject<IToastError>("$showError")!;
let generation = 0;
let progressInterval: number | null = null;
//
@@ -97,6 +98,7 @@ export const useUploadStore = defineStore("upload", () => {
const isActiveUploadsOnLimit = () => activeUploads.value.size < UPLOADS_LIMIT;
const processUploads = async () => {
const started = generation;
if (!hasActiveUploads() && !hasPendingUploads()) {
const fileStore = useFileStore();
window.removeEventListener("beforeunload", beforeUnload);
@@ -130,11 +132,12 @@ export const useUploadStore = defineStore("upload", () => {
.post(upload.path, upload.file!, upload.overwrite, onUpload)
.catch((err) => {
succeeded = false;
if (err.message !== "Upload aborted") $showError(err);
if (generation === started && err.message !== "Upload aborted")
$showError(err);
});
}
finishUpload(upload, succeeded);
if (generation === started) finishUpload(upload, succeeded);
}
};
@@ -186,6 +189,12 @@ export const useUploadStore = defineStore("upload", () => {
};
return {
resetForAccount() {
generation++;
abort();
reset();
window.removeEventListener("beforeunload", beforeUnload);
},
// STATE
activeUploads,
totalBytes,
+2
View File
@@ -1,4 +1,6 @@
interface IUser {
authMode?: string;
sessionState?: string;
displayName?: string;
profileName?: string;
email?: string;
@@ -0,0 +1,49 @@
import { expect, it, vi } from "vitest";
import {
changeSessionScope,
sessionScope,
sessionIsCurrent,
scopedFetch,
mergeSignals,
} from "../session-scope";
it("aborts work when account or session state changes, not on an unchanged poll", () => {
changeSessionScope("A:one", "one");
const a = sessionScope();
expect(changeSessionScope("A:one", "one")).toBe(false);
expect(a.signal.aborted).toBe(false);
changeSessionScope("B:two", "two");
expect(a.signal.aborted).toBe(true);
expect(sessionIsCurrent(a.generation)).toBe(false);
expect(sessionScope().state).toBe("two");
});
it("rejects an A response arriving after B even when the transport ignores cancellation", async () => {
changeSessionScope("A:late", "late");
let deliver!: (r: Response) => void;
vi.stubGlobal(
"fetch",
vi.fn(
() =>
new Promise<Response>((resolve) => {
deliver = resolve;
})
)
);
const pending = scopedFetch("https://files.test/api/private");
changeSessionScope("B:new", "new");
deliver(new Response("private A"));
await expect(pending).rejects.toMatchObject({ name: "AbortError" });
vi.unstubAllGlobals();
});
it("combines cancellation on browsers without AbortSignal.any", () => {
vi.stubGlobal("AbortSignal", { any: undefined });
try {
const first = new AbortController(),
second = new AbortController();
const signal = mergeSignals(first.signal, second.signal);
second.abort();
expect(signal.aborted).toBe(true);
} finally {
vi.unstubAllGlobals();
}
});
+71 -20
View File
@@ -1,41 +1,92 @@
import { useAuthStore } from "@/stores/auth";
import { useUploadStore } from "@/stores/upload";
import { resetAccountStores } from "@/stores";
import { baseURL } from "./constants";
import { setLocale, detectLocale } from "@/i18n";
import { changeSessionScope } from "./session-scope";
export interface SessionState {
status: string;
authenticated: boolean;
session_state?: string;
user?: IUser;
required_factors?: string[];
}
export function startLogin(
target = window.location.pathname + window.location.search
target = window.location.pathname + window.location.search,
silent = false
) {
window.location.assign(
baseURL + "/auth/login?return=" + encodeURIComponent(target)
baseURL +
"/auth/login?return=" +
encodeURIComponent(target) +
(silent ? "&silent=1" : "")
);
}
export function acceptSession(state: SessionState) {
const auth = useAuthStore();
const valid =
state.authenticated === true &&
!!state.user &&
state.status === "authenticated";
const next = valid
? `${state.user!.id}:${state.session_state}:${JSON.stringify(state.user!.perm)}`
: state.status;
if (changeSessionScope(next, state.session_state || "")) {
// Hide the old account before any new identity or data can be rendered.
auth.user = null;
useUploadStore().resetForAccount();
resetAccountStores();
window.dispatchEvent(new Event("fb-session-boundary"));
auth.epoch++;
}
auth.sessionStatus = valid ? "authenticated" : state.status;
auth.sessionState = state.session_state || "";
auth.requiredFactors = state.required_factors || [];
if (valid) auth.setUser(state.user!);
else auth.user = null;
}
let pending: Promise<void> | null = null;
let liveRecheck: (() => void) | undefined;
export function setSessionRecheck(check?: () => void) {
liveRecheck = check;
}
export function validateLogin(): Promise<void> {
if (liveRecheck) {
liveRecheck();
return Promise.resolve();
}
if (pending) return pending;
pending = (async () => {
const res = await fetch(baseURL + "/api/session", {
credentials: "same-origin",
cache: "no-store",
});
if (res.ok) {
const user = await res.json();
useAuthStore().setUser(user);
await setLocale(user.locale || detectLocale());
} else if (res.status === 401) useAuthStore().clearUser();
else throw new Error("SSO session is temporarily unavailable");
try {
const res = await fetch(baseURL + "/auth/session", {
credentials: "same-origin",
cache: "no-store",
});
if (!res.ok) throw new Error("Session unavailable");
acceptSession(await res.json());
} catch {
acceptSession({ status: "unavailable", authenticated: false });
}
})().finally(() => {
pending = null;
});
return pending;
}
export async function logout() {
export async function logout(switchAccount = false) {
const auth = useAuthStore();
const res = await fetch(baseURL + "/auth/logout", {
method: "POST",
headers: { "X-FB-Request": "1" },
headers: { "X-FB-Request": "1", "X-FB-Session-State": auth.sessionState },
credentials: "same-origin",
});
if (!res.ok) throw new Error("Sign out failed. Please try again.");
useAuthStore().clearUser();
localStorage.removeItem("jwt");
document.cookie = "auth=; Max-Age=0; Path=/; SameSite=Strict";
window.location.assign(baseURL + "/login?logged-out=1");
if (res.status === 409) {
await validateLogin();
return;
}
if (!res.ok) {
await validateLogin();
throw new Error("Sign out failed");
}
acceptSession({ status: "signed_out", authenticated: false });
if (switchAccount) startLogin(baseURL + "/files/");
else window.location.assign(baseURL + "/login?logged-out=1");
}
+5 -1
View File
@@ -1,5 +1,9 @@
import { scopedFetch } from "./session-scope";
export async function readDicomFile(source: string, signal: AbortSignal) {
const response = await fetch(source, { credentials: "same-origin", signal });
const response = await scopedFetch(source, {
credentials: "same-origin",
signal,
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const limit = 64 * 1024 * 1024;
if (Number(response.headers.get("Content-Length")) > limit) {
+14
View File
@@ -0,0 +1,14 @@
export {};
declare global {
interface Window {
SSOInternalSession: {
start(options: {
issuer: string;
clientId: string;
checkUrl: string;
onChange: (state: any) => void;
onUnavailable: () => void;
}): { check: () => Promise<void>; stop: () => void };
};
}
}
+111
View File
@@ -0,0 +1,111 @@
/* Client SDK. Credentials and session handles belong exclusively on the application's backend. */
(() => {
window.SSOInternalSession = {
start({
issuer,
clientId,
checkUrl,
onChange,
onUnavailable = () => {},
interval = 2000,
}) {
const authority = new URL(issuer);
const endpoint = new URL(checkUrl, location.href);
if (
endpoint.origin !== location.origin ||
authority.username ||
authority.password ||
(authority.protocol !== "https:" &&
!(
authority.protocol === "http:" &&
["localhost", "127.0.0.1"].includes(authority.hostname)
))
) {
throw new Error("Invalid session configuration");
}
let stopped = false,
pending = false,
previous,
timer;
const controller = new AbortController();
const frame = document.createElement("iframe");
frame.hidden = true;
frame.title = "Session synchronization";
const broker = new URL("/internal/session/frame", authority.origin);
broker.searchParams.set("client_id", clientId);
broker.searchParams.set("origin", location.origin);
frame.src = broker.href;
async function check() {
if (pending || stopped) return;
pending = true;
try {
const response = await fetch(endpoint, {
credentials: "same-origin",
cache: "no-store",
signal: controller.signal,
});
if (!response.ok) throw new Error("Session unavailable");
const state = await response.json();
const fingerprint = JSON.stringify(state);
if (fingerprint !== previous && !stopped) {
previous = fingerprint;
onChange(state);
}
} catch (error) {
if (!stopped) {
previous = undefined;
onUnavailable(error);
}
} finally {
pending = false;
}
}
const message = (event) => {
if (
event.origin === authority.origin &&
event.source === frame.contentWindow &&
event.data?.type === "sso:session-changed"
)
check();
};
function schedule() {
clearTimeout(timer);
if (stopped) return;
timer = setTimeout(
async () => {
await check();
schedule();
},
document.hidden ? 10000 : Math.max(1000, interval)
);
}
const focus = () => {
check();
schedule();
};
const hide = (event) => {
if (!event.persisted) stop();
};
function stop() {
stopped = true;
clearTimeout(timer);
controller.abort();
frame.remove();
window.removeEventListener("message", message);
window.removeEventListener("focus", focus);
document.removeEventListener("visibilitychange", focus);
window.removeEventListener("pagehide", hide);
window.removeEventListener("pageshow", focus);
}
window.addEventListener("message", message);
window.addEventListener("focus", focus);
window.addEventListener("pagehide", hide);
window.addEventListener("pageshow", focus);
document.addEventListener("visibilitychange", focus);
document.body.append(frame);
check();
schedule();
return { check, stop };
},
};
})();
+5 -1
View File
@@ -1,3 +1,4 @@
import { scopedFetch } from "./session-scope";
export type PreviewKind =
| "zip"
| "pdf"
@@ -88,7 +89,10 @@ export async function previewBuffer(
signal: AbortSignal,
limit = 5 * 1024 * 1024
): Promise<ArrayBuffer> {
const response = await fetch(source, { credentials: "same-origin", signal });
const response = await scopedFetch(source, {
credentials: "same-origin",
signal,
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
if (Number(response.headers.get("Content-Length")) > limit) {
await response.body?.cancel();
+58
View File
@@ -0,0 +1,58 @@
// A boundary invalidates all work started by the previous account/state.
let generation = 0;
let state = "";
let key = "";
let controller = new AbortController();
export function sessionScope() {
return { generation, state, signal: controller.signal };
}
export function sessionIsCurrent(value: number) {
return value === generation;
}
export function changeSessionScope(next: string, version: string) {
if (key === next) {
state = version;
return false;
}
controller.abort();
controller = new AbortController();
generation++;
key = next;
state = version;
return true;
}
export async function scopedFetch(
input: RequestInfo | URL,
options: RequestInit = {}
) {
const scope = sessionScope();
const response = await fetch(input, {
...options,
signal: options.signal
? mergeSignals(options.signal, scope.signal)
: scope.signal,
});
if (!sessionIsCurrent(scope.generation))
throw new DOMException("Session changed", "AbortError");
return response;
}
// Older browsers may support AbortController without AbortSignal.any.
export function mergeSignals(
...values: (AbortSignal | undefined | null)[]
): AbortSignal {
const signals = values.filter((s): s is AbortSignal => !!s);
if (signals.length === 1) return signals[0];
if (typeof AbortSignal.any === "function") return AbortSignal.any(signals);
const combined = new AbortController();
const cancel = () => {
combined.abort();
for (const signal of signals) signal.removeEventListener("abort", cancel);
};
if (signals.some((s) => s.aborted)) cancel();
else
for (const signal of signals)
signal.addEventListener("abort", cancel, { once: true });
return combined.signal;
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { scopedFetch } from "./session-scope";
// List the central directory only. Never read, inflate or follow file entries.
const MAX_DIRECTORY = 4 * 1024 * 1024;
const MAX_ENTRIES = 10000;
@@ -81,7 +82,7 @@ async function range(
size: number,
signal: AbortSignal
) {
const response = await fetch(source, {
const response = await scopedFetch(source, {
credentials: "same-origin",
signal,
headers: { Range: `bytes=${start}-${end}` },
+14 -5
View File
@@ -1,5 +1,15 @@
<template>
<main class="sso-welcome">
<SessionGate
v-if="
[
'access_denied',
'factor_required',
'factor_enrollment_required',
'unavailable',
].includes(auth.sessionStatus)
"
/>
<main v-else class="sso-welcome">
<div class="sso-symbol" aria-hidden="true">
<AppIcon name="folder_open" />
</div>
@@ -12,7 +22,9 @@
</main>
</template>
<script setup lang="ts">
import { onMounted } from "vue";
import { useAuthStore } from "@/stores/auth";
import SessionGate from "@/components/SessionGate.vue";
const auth = useAuthStore();
import { useRoute } from "vue-router";
import { name, baseURL } from "@/utils/constants";
import { startLogin } from "@/utils/auth";
@@ -25,7 +37,4 @@ function signIn() {
: "/files/")
);
}
onMounted(() => {
if (route.query.redirect && !route.query["logged-out"]) signIn();
});
</script>
+5 -2
View File
@@ -8,7 +8,10 @@
<p>{{ authStore.user?.email || authStore.user?.username }}</p>
</div>
</div>
<a class="button account-management" :href="baseURL + '/auth/account'"
<a
v-if="!noAuth"
class="button account-management"
:href="baseURL + '/auth/account'"
>{{ t("preferences.manage") }}<AppIcon name="north_east"
/></a>
</section>
@@ -109,7 +112,7 @@ import { useLayoutStore } from "@/stores/layout";
import { users as api } from "@/api";
import Languages from "@/components/settings/Languages.vue";
import AccountAvatar from "@/components/AccountAvatar.vue";
import { baseURL } from "@/utils/constants";
import { baseURL, noAuth } from "@/utils/constants";
import { getTheme, getMediaPreference, setTheme } from "@/utils/theme";
import { dicomPreferences } from "@/utils/dicom-quality";
import { detectLocale } from "@/i18n";