feat: adopt shared internal SSO sessions and add no-sso launch mode
This commit is contained in:
1 parent
c209f1effc
commit
c02bf755f2
51 files changed
+2131
-362
No files matched your search
+57
-3
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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")
|
||||
);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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": "Сменить аккаунт"
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
Vendored
+2
@@ -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
@@ -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");
|
||||
}
|
||||
@@ -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
@@ -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 };
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
},
|
||||
};
|
||||
})();
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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}` },
|
||||
|
||||
@@ -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>
|
||||
@@ -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";
|
||||
|
||||
Reference in new issue
Block a user