dev #3
@@ -364,7 +364,6 @@ Custom
|
|||||||
padding: 0.25rem 0.5rem;
|
padding: 0.25rem 0.5rem;
|
||||||
border-radius: 9999px;
|
border-radius: 9999px;
|
||||||
border: 1px solid;
|
border: 1px solid;
|
||||||
text-transform: uppercase;
|
|
||||||
letter-spacing: 0.025em;
|
letter-spacing: 0.025em;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -29,10 +29,19 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.mobile-menu-dropdown.open {
|
.mobile-menu-dropdown.open {
|
||||||
max-height: 500px;
|
max-height: none;
|
||||||
|
overflow: visible;
|
||||||
|
padding-bottom: 0.75rem;
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.mobile-menu-dropdown a {
|
||||||
|
font-size: 0.95rem;
|
||||||
|
line-height: 1.25rem;
|
||||||
|
padding: 0.6rem 0.75rem;
|
||||||
|
border-radius: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
@media (min-width: 768px) {
|
@media (min-width: 768px) {
|
||||||
.mobile-menu-dropdown {
|
.mobile-menu-dropdown {
|
||||||
display: none;
|
display: none;
|
||||||
|
|||||||
@@ -46,7 +46,8 @@ export interface RootProps {
|
|||||||
|
|
||||||
export default function Root({ child, user = undefined, ...props }: RootProps): React.ReactElement {
|
export default function Root({ child, user = undefined, ...props }: RootProps): React.ReactElement {
|
||||||
window.toast = toast;
|
window.toast = toast;
|
||||||
const theme = document.documentElement.getAttribute("data-theme")
|
const theme = document.documentElement.getAttribute("data-theme") ?? null;
|
||||||
|
const toastTheme = theme ?? undefined;
|
||||||
const loggedIn = props.loggedIn ?? Boolean(user);
|
const loggedIn = props.loggedIn ?? Boolean(user);
|
||||||
usePrimeReactThemeSwitcher(theme);
|
usePrimeReactThemeSwitcher(theme);
|
||||||
// Avoid adding the Player island for subsite requests. We expose a
|
// Avoid adding the Player island for subsite requests. We expose a
|
||||||
@@ -81,7 +82,7 @@ export default function Root({ child, user = undefined, ...props }: RootProps):
|
|||||||
let mounted = true;
|
let mounted = true;
|
||||||
if (wantPlayer) {
|
if (wantPlayer) {
|
||||||
if (import.meta.env.DEV) { try { console.debug('[AppLayout] dynamic-import: requesting AudioPlayer'); } catch (e) { } }
|
if (import.meta.env.DEV) { try { console.debug('[AppLayout] dynamic-import: requesting AudioPlayer'); } catch (e) { } }
|
||||||
import('./AudioPlayer.jsx')
|
import('./Radio.js')
|
||||||
.then((mod) => {
|
.then((mod) => {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
// set the component factory
|
// set the component factory
|
||||||
@@ -102,7 +103,7 @@ export default function Root({ child, user = undefined, ...props }: RootProps):
|
|||||||
return (
|
return (
|
||||||
<PrimeReactProvider>
|
<PrimeReactProvider>
|
||||||
<CustomToastContainer
|
<CustomToastContainer
|
||||||
theme={theme}
|
theme={toastTheme}
|
||||||
newestOnTop={true}
|
newestOnTop={true}
|
||||||
closeOnClick={true} />
|
closeOnClick={true} />
|
||||||
<JoyUIRootIsland>
|
<JoyUIRootIsland>
|
||||||
@@ -114,22 +115,22 @@ export default function Root({ child, user = undefined, ...props }: RootProps):
|
|||||||
Work in progress... bugs are to be expected.
|
Work in progress... bugs are to be expected.
|
||||||
</Alert> */}
|
</Alert> */}
|
||||||
{child == "LoginPage" && (<LoginPage {...props} loggedIn={loggedIn} />)}
|
{child == "LoginPage" && (<LoginPage {...props} loggedIn={loggedIn} />)}
|
||||||
{child == "LyricSearch" && (<LyricSearch {...props} client:only="react" />)}
|
{child == "LyricSearch" && (<LyricSearch />)}
|
||||||
{child == "Player" && !isSubsite && PlayerComp && (
|
{child == "Player" && !isSubsite && PlayerComp && (
|
||||||
<Suspense fallback={null}>
|
<Suspense fallback={null}>
|
||||||
<PlayerComp client:only="react" user={user} />
|
<PlayerComp user={user} />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
)}
|
)}
|
||||||
{child == "Memes" && <Memes client:only="react" />}
|
{child == "Memes" && <Memes />}
|
||||||
{child == "DiscordLogs" && (
|
{child == "DiscordLogs" && (
|
||||||
<Suspense fallback={<div style={{ padding: '2rem', textAlign: 'center' }}>Loading...</div>}>
|
<Suspense fallback={<div style={{ padding: '2rem', textAlign: 'center' }}>Loading...</div>}>
|
||||||
<DiscordLogs client:only="react" />
|
<DiscordLogs />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
)}
|
)}
|
||||||
{child == "qs2.MediaRequestForm" && <MediaRequestForm client:only="react" />}
|
{child == "qs2.MediaRequestForm" && <MediaRequestForm />}
|
||||||
{child == "qs2.RequestManagement" && <RequestManagement client:only="react" />}
|
{child == "qs2.RequestManagement" && <RequestManagement />}
|
||||||
{child == "ReqForm" && <ReqForm {...props} client:only="react" />}
|
{child == "ReqForm" && <ReqForm />}
|
||||||
{child == "Lighting" && <Lighting key={window.location.pathname + Math.random()} client:only="react" />}
|
{child == "Lighting" && <Lighting key={window.location.pathname + Math.random()} />}
|
||||||
</JoyUIRootIsland>
|
</JoyUIRootIsland>
|
||||||
</PrimeReactProvider>
|
</PrimeReactProvider>
|
||||||
);
|
);
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -4,11 +4,13 @@
|
|||||||
* This is a minimal version that avoids importing from shared modules
|
* This is a minimal version that avoids importing from shared modules
|
||||||
* that would pull in heavy CSS (AppLayout, Components, etc.)
|
* that would pull in heavy CSS (AppLayout, Components, etc.)
|
||||||
*/
|
*/
|
||||||
import React, { Suspense, lazy, ReactNode } from 'react';
|
import React, { Suspense, lazy } from 'react';
|
||||||
|
import type { ReactNode } from 'react';
|
||||||
import { ToastContainer, toast } from 'react-toastify';
|
import { ToastContainer, toast } from 'react-toastify';
|
||||||
import { CssVarsProvider } from "@mui/joy";
|
import { CssVarsProvider } from "@mui/joy";
|
||||||
import { CacheProvider, EmotionCache } from "@emotion/react";
|
import { CacheProvider } from "@emotion/react";
|
||||||
import createCache from "@emotion/cache";
|
import createCache from "@emotion/cache";
|
||||||
|
import type { EmotionCache } from "@emotion/cache";
|
||||||
import { PrimeReactProvider } from "primereact/api";
|
import { PrimeReactProvider } from "primereact/api";
|
||||||
|
|
||||||
// Import only minimal CSS - no theme CSS, no primeicons
|
// Import only minimal CSS - no theme CSS, no primeicons
|
||||||
|
|||||||
1349
src/components/TRip/MediaRequestForm.jsx
Normal file
1349
src/components/TRip/MediaRequestForm.jsx
Normal file
File diff suppressed because it is too large
Load Diff
@@ -17,9 +17,9 @@ interface RequestJob {
|
|||||||
tracks: number;
|
tracks: number;
|
||||||
quality: string;
|
quality: string;
|
||||||
status: string;
|
status: string;
|
||||||
progress: number;
|
progress: number | string | null;
|
||||||
type?: string;
|
type?: string;
|
||||||
tarball_path?: string;
|
tarball?: string;
|
||||||
created_at?: string;
|
created_at?: string;
|
||||||
updated_at?: string;
|
updated_at?: string;
|
||||||
[key: string]: unknown;
|
[key: string]: unknown;
|
||||||
@@ -40,9 +40,13 @@ export default function RequestManagement() {
|
|||||||
const pollingDetailRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
const pollingDetailRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||||
|
|
||||||
|
|
||||||
|
const resolveTarballPath = (job: RequestJob) => job.tarball;
|
||||||
|
|
||||||
const tarballUrl = (absPath: string | undefined, quality: string) => {
|
const tarballUrl = (absPath: string | undefined, quality: string) => {
|
||||||
if (!absPath) return null;
|
if (!absPath) return null;
|
||||||
const filename = absPath.split("/").pop(); // get "SOMETHING.tar.gz"
|
const filename = absPath.split("/").pop(); // get "SOMETHING.tar.gz"
|
||||||
|
// If the backend already stores a fully qualified URL, return as-is
|
||||||
|
if (/^https?:\/\//i.test(absPath)) return absPath;
|
||||||
return `${TAR_BASE_URL}/${quality}/${filename}`;
|
return `${TAR_BASE_URL}/${quality}/${filename}`;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -172,24 +176,21 @@ export default function RequestManagement() {
|
|||||||
|
|
||||||
const formatProgress = (p: unknown) => {
|
const formatProgress = (p: unknown) => {
|
||||||
if (p === null || p === undefined || p === "") return "—";
|
if (p === null || p === undefined || p === "") return "—";
|
||||||
const num = Number(p);
|
const pct = computePct(p);
|
||||||
if (Number.isNaN(num)) return "—";
|
|
||||||
const pct = num > 1 ? Math.round(num) : num;
|
|
||||||
return `${pct}%`;
|
return `${pct}%`;
|
||||||
};
|
};
|
||||||
|
|
||||||
const computePct = (p: unknown) => {
|
const computePct = (p: unknown) => {
|
||||||
if (p === null || p === undefined || p === "") return 0;
|
if (p === null || p === undefined || p === "") return 0;
|
||||||
const num = Number(p);
|
const num = Number(p);
|
||||||
if (Number.isNaN(num)) return 0;
|
if (!Number.isFinite(num)) return 0;
|
||||||
return Math.min(100, Math.max(0, num > 1 ? Math.round(num) : Math.round(num * 100)));
|
const normalized = num > 1 ? num : num * 100;
|
||||||
|
return Math.min(100, Math.max(0, Math.round(normalized)));
|
||||||
};
|
};
|
||||||
|
|
||||||
const progressBarTemplate = (rowData: RequestJob) => {
|
const progressBarTemplate = (rowData: RequestJob) => {
|
||||||
const p = rowData.progress;
|
const p = rowData.progress;
|
||||||
if (p === null || p === undefined || p === 0) return "—";
|
if (p === null || p === undefined || p === "") return "—";
|
||||||
const num = Number(p);
|
|
||||||
if (Number.isNaN(num)) return "—";
|
|
||||||
const pct = computePct(p);
|
const pct = computePct(p);
|
||||||
|
|
||||||
const getProgressColor = () => {
|
const getProgressColor = () => {
|
||||||
@@ -341,7 +342,7 @@ export default function RequestManagement() {
|
|||||||
</span>
|
</span>
|
||||||
}
|
}
|
||||||
body={(row: RequestJob) => {
|
body={(row: RequestJob) => {
|
||||||
const url = tarballUrl(row.tarball_path, row.quality || "FLAC");
|
const url = tarballUrl(resolveTarballPath(row as RequestJob), row.quality || "FLAC");
|
||||||
if (!url) return "—";
|
if (!url) return "—";
|
||||||
const encodedURL = encodeURI(url);
|
const encodedURL = encodeURI(url);
|
||||||
|
|
||||||
@@ -409,18 +410,25 @@ export default function RequestManagement() {
|
|||||||
<strong>Progress:</strong>
|
<strong>Progress:</strong>
|
||||||
<div className="rm-progress-container mt-2">
|
<div className="rm-progress-container mt-2">
|
||||||
<div className="rm-progress-track rm-progress-track-lg">
|
<div className="rm-progress-track rm-progress-track-lg">
|
||||||
|
{(() => {
|
||||||
|
const pctDialog = computePct(selectedRequest.progress);
|
||||||
|
const status = selectedRequest.status;
|
||||||
|
const fillColor = status === "Failed" ? "bg-red-500" : status === "Finished" ? "bg-green-500" : "bg-blue-500";
|
||||||
|
return (
|
||||||
<div
|
<div
|
||||||
className={`rm-progress-fill ${selectedRequest.status === "Failed" ? "bg-red-500" : selectedRequest.status === "Finished" ? "bg-green-500" : "bg-blue-500"}`}
|
className={`rm-progress-fill ${fillColor}`}
|
||||||
style={{
|
style={{
|
||||||
['--rm-progress' as string]: (computePct(selectedRequest.progress) / 100).toString(),
|
['--rm-progress' as string]: (pctDialog / 100).toString(),
|
||||||
borderTopRightRadius: computePct(selectedRequest.progress) >= 100 ? '999px' : 0,
|
borderTopRightRadius: pctDialog >= 100 ? '999px' : 0,
|
||||||
borderBottomRightRadius: computePct(selectedRequest.progress) >= 100 ? '999px' : 0
|
borderBottomRightRadius: pctDialog >= 100 ? '999px' : 0
|
||||||
}}
|
}}
|
||||||
data-pct={computePct(selectedRequest.progress)}
|
data-pct={pctDialog}
|
||||||
aria-valuenow={Math.min(100, Math.max(0, Number(selectedRequest.progress) > 1 ? Math.round(selectedRequest.progress) : selectedRequest.progress * 100))}
|
aria-valuenow={pctDialog}
|
||||||
aria-valuemin={0}
|
aria-valuemin={0}
|
||||||
aria-valuemax={100}
|
aria-valuemax={100}
|
||||||
/>
|
/>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
</div>
|
</div>
|
||||||
<span className="rm-progress-text">{formatProgress(selectedRequest.progress)}</span>
|
<span className="rm-progress-text">{formatProgress(selectedRequest.progress)}</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -437,17 +445,17 @@ export default function RequestManagement() {
|
|||||||
|
|
||||||
{/* --- Tarball Card --- */}
|
{/* --- Tarball Card --- */}
|
||||||
{
|
{
|
||||||
selectedRequest.tarball_path && (
|
selectedRequest.tarball && (
|
||||||
<div className="p-3 bg-gray-100 dark:bg-neutral-800 rounded-md">
|
<div className="p-3 bg-gray-100 dark:bg-neutral-800 rounded-md">
|
||||||
<p>
|
<p>
|
||||||
<strong>Tarball:</strong>{" "}
|
<strong>Tarball:</strong>{" "}
|
||||||
<a
|
<a
|
||||||
href={encodeURI(tarballUrl(selectedRequest.tarball_path, selectedRequest.quality) || "")}
|
href={encodeURI(tarballUrl(resolveTarballPath(selectedRequest), selectedRequest.quality) || "")}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
className="text-blue-500 hover:underline"
|
className="text-blue-500 hover:underline"
|
||||||
>
|
>
|
||||||
{tarballUrl(selectedRequest.tarball_path, selectedRequest.quality)?.split("/").pop()}
|
{tarballUrl(resolveTarballPath(selectedRequest), selectedRequest.quality)?.split("/").pop()}
|
||||||
</a>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -5,19 +5,46 @@ import { Button } from "@mui/joy";
|
|||||||
import { AutoComplete } from "primereact/autocomplete";
|
import { AutoComplete } from "primereact/autocomplete";
|
||||||
import { InputText } from "primereact/inputtext";
|
import { InputText } from "primereact/inputtext";
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
interface Window {
|
||||||
|
_t?: string;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type MediaType = 'movie' | 'tv' | string;
|
||||||
|
|
||||||
|
interface SearchItem {
|
||||||
|
label: string;
|
||||||
|
year?: string;
|
||||||
|
mediaType?: MediaType;
|
||||||
|
poster_path?: string | null;
|
||||||
|
overview?: string;
|
||||||
|
title?: string;
|
||||||
|
type?: string;
|
||||||
|
requester?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SubmittedRequest {
|
||||||
|
title: string;
|
||||||
|
year: string;
|
||||||
|
type: string;
|
||||||
|
requester: string;
|
||||||
|
poster_path?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
export default function ReqForm() {
|
export default function ReqForm() {
|
||||||
const [type, setType] = useState("");
|
const [type, setType] = useState<string>("");
|
||||||
const [title, setTitle] = useState("");
|
const [title, setTitle] = useState<string>("");
|
||||||
const [year, setYear] = useState("");
|
const [year, setYear] = useState<string>("");
|
||||||
const [requester, setRequester] = useState("");
|
const [requester, setRequester] = useState<string>("");
|
||||||
const [selectedItem, setSelectedItem] = useState(null);
|
const [selectedItem, setSelectedItem] = useState<SearchItem | null>(null);
|
||||||
const [selectedOverview, setSelectedOverview] = useState("");
|
const [selectedOverview, setSelectedOverview] = useState<string>("");
|
||||||
const [selectedTitle, setSelectedTitle] = useState("");
|
const [selectedTitle, setSelectedTitle] = useState<string>("");
|
||||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
|
||||||
const [suggestions, setSuggestions] = useState([]);
|
const [suggestions, setSuggestions] = useState<SearchItem[]>([]);
|
||||||
const [posterLoading, setPosterLoading] = useState(true);
|
const [posterLoading, setPosterLoading] = useState<boolean>(true);
|
||||||
const [submittedRequest, setSubmittedRequest] = useState(null); // Track successful submission
|
const [submittedRequest, setSubmittedRequest] = useState<SubmittedRequest | null>(null); // Track successful submission
|
||||||
const [csrfToken, setCsrfToken] = useState(null);
|
const [csrfToken, setCsrfToken] = useState<string | null>(null);
|
||||||
|
|
||||||
// Get CSRF token from window global on mount
|
// Get CSRF token from window global on mount
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -36,7 +63,7 @@ export default function ReqForm() {
|
|||||||
}
|
}
|
||||||
}, [title, selectedTitle, selectedOverview, selectedItem, type]);
|
}, [title, selectedTitle, selectedOverview, selectedItem, type]);
|
||||||
|
|
||||||
const searchTitles = async (event) => {
|
const searchTitles = async (event: { query: string }) => {
|
||||||
const query = event.query;
|
const query = event.query;
|
||||||
if (query.length < 2) {
|
if (query.length < 2) {
|
||||||
setSuggestions([]);
|
setSuggestions([]);
|
||||||
@@ -48,7 +75,7 @@ export default function ReqForm() {
|
|||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(`API error: ${response.status}`);
|
throw new Error(`API error: ${response.status}`);
|
||||||
}
|
}
|
||||||
const data = await response.json();
|
const data: SearchItem[] = await response.json();
|
||||||
setSuggestions(data);
|
setSuggestions(data);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching suggestions:', error);
|
console.error('Error fetching suggestions:', error);
|
||||||
@@ -56,7 +83,7 @@ export default function ReqForm() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSubmit = async (e) => {
|
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!title.trim()) {
|
if (!title.trim()) {
|
||||||
toast.error("Please fill in the required fields.");
|
toast.error("Please fill in the required fields.");
|
||||||
@@ -101,7 +128,7 @@ export default function ReqForm() {
|
|||||||
year,
|
year,
|
||||||
type,
|
type,
|
||||||
requester,
|
requester,
|
||||||
poster_path: selectedItem?.poster_path,
|
poster_path: selectedItem?.poster_path ?? null,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Submission error:', error);
|
console.error('Submission error:', error);
|
||||||
@@ -126,13 +153,13 @@ export default function ReqForm() {
|
|||||||
|
|
||||||
const attachScrollFix = () => {
|
const attachScrollFix = () => {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
const panel = document.querySelector(".p-autocomplete-panel");
|
const panel = document.querySelector<HTMLElement>(".p-autocomplete-panel");
|
||||||
const items = panel?.querySelector(".p-autocomplete-items");
|
const items = panel?.querySelector<HTMLElement>(".p-autocomplete-items");
|
||||||
if (items) {
|
if (items) {
|
||||||
items.style.maxHeight = "200px";
|
items.style.maxHeight = "200px";
|
||||||
items.style.overflowY = "auto";
|
items.style.overflowY = "auto";
|
||||||
items.style.overscrollBehavior = "contain";
|
items.style.overscrollBehavior = "contain";
|
||||||
const wheelHandler = (e) => {
|
const wheelHandler = (e: WheelEvent) => {
|
||||||
const delta = e.deltaY;
|
const delta = e.deltaY;
|
||||||
const atTop = items.scrollTop === 0;
|
const atTop = items.scrollTop === 0;
|
||||||
const atBottom = items.scrollTop + items.clientHeight >= items.scrollHeight;
|
const atBottom = items.scrollTop + items.clientHeight >= items.scrollHeight;
|
||||||
@@ -148,7 +175,7 @@ export default function ReqForm() {
|
|||||||
}, 0);
|
}, 0);
|
||||||
};
|
};
|
||||||
|
|
||||||
const formatMediaType = (mediaTypeValue) => {
|
const formatMediaType = (mediaTypeValue: MediaType | undefined) => {
|
||||||
if (!mediaTypeValue) return "";
|
if (!mediaTypeValue) return "";
|
||||||
if (mediaTypeValue === "tv") return "TV Series";
|
if (mediaTypeValue === "tv") return "TV Series";
|
||||||
if (mediaTypeValue === "movie") return "Movie";
|
if (mediaTypeValue === "movie") return "Movie";
|
||||||
@@ -239,16 +266,17 @@ export default function ReqForm() {
|
|||||||
delay={300}
|
delay={300}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
// Handle both string input and object selection
|
// Handle both string input and object selection
|
||||||
const val = e.target?.value ?? e.value;
|
const val = (e as any).target?.value ?? e.value;
|
||||||
setTitle(typeof val === 'string' ? val : val?.label || '');
|
setTitle(typeof val === 'string' ? val : (val as SearchItem | undefined)?.label || '');
|
||||||
}}
|
}}
|
||||||
onSelect={(e) => {
|
onSelect={(e: { value: SearchItem }) => {
|
||||||
setType(e.value.mediaType === 'tv' ? 'tv' : 'movie');
|
const item = e.value;
|
||||||
setTitle(e.value.label);
|
setType(item.mediaType === 'tv' ? 'tv' : 'movie');
|
||||||
setSelectedTitle(e.value.label);
|
setTitle(item.label);
|
||||||
setSelectedItem(e.value);
|
setSelectedTitle(item.label);
|
||||||
if (e.value.year) setYear(e.value.year);
|
setSelectedItem(item);
|
||||||
setSelectedOverview(e.value.overview || "");
|
if (item.year) setYear(item.year);
|
||||||
|
setSelectedOverview(item.overview || "");
|
||||||
}}
|
}}
|
||||||
placeholder="Enter movie or TV title"
|
placeholder="Enter movie or TV title"
|
||||||
title="Enter movie or TV show title"
|
title="Enter movie or TV show title"
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ export const RADIO_API_URL: string = "https://radio-api.codey.lol";
|
|||||||
export const socialLinks: Record<string, string> = {
|
export const socialLinks: Record<string, string> = {
|
||||||
};
|
};
|
||||||
|
|
||||||
export const MAJOR_VERSION: string = "0.5"
|
export const MAJOR_VERSION: string = "0.6"
|
||||||
export const RELEASE_FLAG: string | null = null;
|
export const RELEASE_FLAG: string | null = null;
|
||||||
export const ENVIRONMENT: "Dev" | "Prod" = import.meta.env.DEV ? "Dev" : "Prod";
|
export const ENVIRONMENT: "Dev" | "Prod" = import.meta.env.DEV ? "Dev" : "Prod";
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import React, { ReactNode, CSSProperties } from 'react';
|
import React from 'react';
|
||||||
|
import type { ReactNode, CSSProperties } from 'react';
|
||||||
|
|
||||||
interface WhitelabelLayoutProps {
|
interface WhitelabelLayoutProps {
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
|
|||||||
511
src/middleware.js
Normal file
511
src/middleware.js
Normal file
@@ -0,0 +1,511 @@
|
|||||||
|
import { defineMiddleware } from 'astro:middleware';
|
||||||
|
import { SUBSITES, PROTECTED_ROUTES, PUBLIC_ROUTES } from './config.js';
|
||||||
|
import { getSubsiteByHost, getSubsiteFromSignal } from './utils/subsites.js';
|
||||||
|
|
||||||
|
// Polyfill Headers.getSetCookie for environments where it's not present.
|
||||||
|
// Astro's Node adapter expects headers.getSetCookie() to exist when
|
||||||
|
// 'set-cookie' headers are present; in some Node runtimes Headers lacks it
|
||||||
|
// which leads to TypeError: headers.getSetCookie is not a function.
|
||||||
|
if (typeof globalThis.Headers !== 'undefined' && typeof globalThis.Headers.prototype.getSetCookie !== 'function') {
|
||||||
|
try {
|
||||||
|
Object.defineProperty(globalThis.Headers.prototype, 'getSetCookie', {
|
||||||
|
value: function () {
|
||||||
|
const cookies = [];
|
||||||
|
for (const [name, val] of this.entries()) {
|
||||||
|
if (name && name.toLowerCase() === 'set-cookie') cookies.push(val);
|
||||||
|
}
|
||||||
|
return cookies;
|
||||||
|
},
|
||||||
|
configurable: true,
|
||||||
|
writable: true,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
// If we can't patch Headers, swallow silently — code will still try to
|
||||||
|
// access getSetCookie, but our other guards handle missing function calls.
|
||||||
|
console.warn('[middleware] Failed to polyfill Headers.getSetCookie', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const API_URL = "https://api.codey.lol";
|
||||||
|
const AUTH_TIMEOUT_MS = 3000; // 3 second timeout for auth requests
|
||||||
|
|
||||||
|
// Deduplication for concurrent refresh requests (prevents race condition where
|
||||||
|
// multiple SSR requests try to refresh simultaneously, causing 401s after the
|
||||||
|
// first one rotates the refresh token)
|
||||||
|
let refreshPromise = null;
|
||||||
|
let lastRefreshResult = null;
|
||||||
|
let lastRefreshTime = 0;
|
||||||
|
const REFRESH_RESULT_TTL = 5000; // Cache successful refresh result for 5 seconds
|
||||||
|
|
||||||
|
// Auth check function (mirrors requireAuthHook logic but for middleware)
|
||||||
|
async function checkAuth(request) {
|
||||||
|
try {
|
||||||
|
const cookieHeader = request.headers.get("cookie") ?? "";
|
||||||
|
|
||||||
|
// Add timeout to prevent hanging
|
||||||
|
let controller = new AbortController;
|
||||||
|
let timeout = setTimeout(() => controller.abort(), AUTH_TIMEOUT_MS);
|
||||||
|
let res;
|
||||||
|
try {
|
||||||
|
res = await fetch(`${API_URL}/auth/id`, {
|
||||||
|
headers: { Cookie: cookieHeader },
|
||||||
|
credentials: "include",
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
console.error("[middleware] auth/id failed or timed out", err.name === 'AbortError' ? 'timeout' : err);
|
||||||
|
return { authenticated: false, user: null, cookies: null };
|
||||||
|
}
|
||||||
|
clearTimeout(timeout);
|
||||||
|
|
||||||
|
if (res.status === 401) {
|
||||||
|
// Check if we even have a refresh token before attempting refresh
|
||||||
|
if (!cookieHeader.includes('refresh_token=')) {
|
||||||
|
return { authenticated: false, user: null, cookies: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if we have a recent successful refresh result we can reuse
|
||||||
|
const now = Date.now();
|
||||||
|
if (lastRefreshResult && (now - lastRefreshTime) < REFRESH_RESULT_TTL) {
|
||||||
|
console.log(`[middleware] Reusing cached refresh result from ${now - lastRefreshTime}ms ago`);
|
||||||
|
return lastRefreshResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deduplicate concurrent refresh requests
|
||||||
|
if (refreshPromise) {
|
||||||
|
console.log(`[middleware] Waiting for in-flight refresh request`);
|
||||||
|
return refreshPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start a new refresh request
|
||||||
|
refreshPromise = (async () => {
|
||||||
|
console.log(`[middleware] Starting token refresh...`);
|
||||||
|
let controller = new AbortController();
|
||||||
|
let timeout = setTimeout(() => controller.abort(), AUTH_TIMEOUT_MS);
|
||||||
|
let refreshRes;
|
||||||
|
try {
|
||||||
|
refreshRes = await fetch(`${API_URL}/auth/refresh`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { Cookie: cookieHeader },
|
||||||
|
credentials: "include",
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
console.error("[middleware] auth/refresh failed or timed out", err.name === 'AbortError' ? 'timeout' : err);
|
||||||
|
return { authenticated: false, user: null, cookies: null };
|
||||||
|
}
|
||||||
|
clearTimeout(timeout);
|
||||||
|
|
||||||
|
if (!refreshRes.ok) {
|
||||||
|
// Log the response body for debugging
|
||||||
|
let errorDetail = '';
|
||||||
|
try {
|
||||||
|
const errorBody = await refreshRes.text();
|
||||||
|
errorDetail = ` - ${errorBody}`;
|
||||||
|
} catch {}
|
||||||
|
console.error(`[middleware] Token refresh failed ${refreshRes.status}${errorDetail}`);
|
||||||
|
return { authenticated: false, user: null, cookies: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`[middleware] Token refresh succeeded`);
|
||||||
|
|
||||||
|
// Get refreshed cookies
|
||||||
|
let setCookies = [];
|
||||||
|
if (typeof refreshRes.headers.getSetCookie === 'function') {
|
||||||
|
setCookies = refreshRes.headers.getSetCookie();
|
||||||
|
} else {
|
||||||
|
const setCookieHeader = refreshRes.headers.get("set-cookie");
|
||||||
|
if (setCookieHeader) {
|
||||||
|
setCookies = setCookieHeader.split(/,(?=\s*[a-zA-Z_][a-zA-Z0-9_]*=)/);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (setCookies.length === 0) {
|
||||||
|
console.error("[middleware] No set-cookie headers in refresh response");
|
||||||
|
return { authenticated: false, user: null, cookies: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build new cookie header for retry
|
||||||
|
const newCookieHeader = setCookies.map(c => c.split(";")[0].trim()).join("; ");
|
||||||
|
|
||||||
|
// Retry auth/id with new cookies and timeout
|
||||||
|
controller = new AbortController();
|
||||||
|
timeout = setTimeout(() => controller.abort(), AUTH_TIMEOUT_MS);
|
||||||
|
let retryRes;
|
||||||
|
try {
|
||||||
|
retryRes = await fetch(`${API_URL}/auth/id`, {
|
||||||
|
headers: { Cookie: newCookieHeader },
|
||||||
|
credentials: "include",
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
console.error("[middleware] auth/id retry failed or timed out", err.name === 'AbortError' ? 'timeout' : err);
|
||||||
|
return { authenticated: false, user: null, cookies: null };
|
||||||
|
}
|
||||||
|
clearTimeout(timeout);
|
||||||
|
|
||||||
|
if (!retryRes.ok) {
|
||||||
|
console.error(`[middleware] auth/id retry failed with status ${retryRes.status}`);
|
||||||
|
return { authenticated: false, user: null, cookies: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await retryRes.json();
|
||||||
|
return { authenticated: true, user, cookies: setCookies };
|
||||||
|
})();
|
||||||
|
|
||||||
|
// Clear the promise when done and cache the result
|
||||||
|
refreshPromise.then(result => {
|
||||||
|
if (result.authenticated) {
|
||||||
|
lastRefreshResult = result;
|
||||||
|
lastRefreshTime = Date.now();
|
||||||
|
}
|
||||||
|
refreshPromise = null;
|
||||||
|
}).catch(() => {
|
||||||
|
refreshPromise = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
return refreshPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
return { authenticated: false, user: null, cookies: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await res.json();
|
||||||
|
return { authenticated: true, user, cookies: null };
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[middleware] Auth check error:", err);
|
||||||
|
return { authenticated: false, user: null, cookies: null };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if a path matches any protected route and return the config
|
||||||
|
function getProtectedRouteConfig(pathname) {
|
||||||
|
// Normalize pathname for comparison (lowercase)
|
||||||
|
const normalizedPath = pathname.toLowerCase();
|
||||||
|
|
||||||
|
for (const route of PROTECTED_ROUTES) {
|
||||||
|
const routePath = typeof route === 'string' ? route : route.path;
|
||||||
|
const normalizedRoute = routePath.toLowerCase();
|
||||||
|
const matches = normalizedPath === normalizedRoute || normalizedPath.startsWith(normalizedRoute + '/');
|
||||||
|
if (matches) {
|
||||||
|
// Check if this path is excluded from protection
|
||||||
|
const excludes = (typeof route === 'object' && route.exclude) || [];
|
||||||
|
for (const excludePath of excludes) {
|
||||||
|
const normalizedExclude = excludePath.toLowerCase();
|
||||||
|
if (normalizedPath === normalizedExclude || normalizedPath.startsWith(normalizedExclude + '/')) {
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Path ${pathname} excluded from protection by ${excludePath}`);
|
||||||
|
return null; // Excluded, not protected
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return typeof route === 'string' ? { path: route, roles: null } : route;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if a path is explicitly public (but NOT if it matches a protected route)
|
||||||
|
function isPublicRoute(pathname) {
|
||||||
|
// If the path matches a protected route, it's NOT public
|
||||||
|
if (getProtectedRouteConfig(pathname)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const route of PUBLIC_ROUTES) {
|
||||||
|
// For routes ending with /, match any path starting with that prefix
|
||||||
|
if (route.endsWith('/') && route !== '/') {
|
||||||
|
if (pathname.startsWith(route)) {
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] isPublicRoute: ${pathname} matched ${route} (prefix)`);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// For other routes, match exactly or as a path prefix (route + /)
|
||||||
|
if (pathname === route) {
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] isPublicRoute: ${pathname} matched ${route} (exact)`);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// Special case: don't treat / as a prefix for all paths
|
||||||
|
if (route !== '/' && pathname.startsWith(route + '/')) {
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] isPublicRoute: ${pathname} matched ${route}/ (subpath)`);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] isPublicRoute(${pathname}) = false`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const onRequest = defineMiddleware(async (context, next) => {
|
||||||
|
try {
|
||||||
|
const pathname = context.url.pathname;
|
||||||
|
|
||||||
|
// Skip auth check for static assets
|
||||||
|
const skipAuthPrefixes = ['/_astro', '/_', '/assets', '/scripts', '/favicon', '/images', '/_static'];
|
||||||
|
const shouldSkipAuth = skipAuthPrefixes.some(p => pathname.startsWith(p));
|
||||||
|
|
||||||
|
// Check if route is protected (requires auth)
|
||||||
|
const protectedConfig = getProtectedRouteConfig(pathname);
|
||||||
|
const isApiRoute = pathname.startsWith('/api/');
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Path: ${pathname}, Protected: ${!!protectedConfig}, SkipAuth: ${shouldSkipAuth}`);
|
||||||
|
|
||||||
|
// Always attempt auth for non-static routes to populate user info
|
||||||
|
if (!shouldSkipAuth) {
|
||||||
|
const { authenticated, user, cookies } = await checkAuth(context.request);
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Auth result: authenticated=${authenticated}`);
|
||||||
|
|
||||||
|
// Expose authenticated user and refreshed cookies to downstream handlers/layouts
|
||||||
|
if (authenticated && user) {
|
||||||
|
context.locals.user = user;
|
||||||
|
if (cookies && cookies.length > 0) {
|
||||||
|
context.locals.refreshedCookies = cookies;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// For protected routes, enforce authentication
|
||||||
|
if (protectedConfig && !isPublicRoute(pathname)) {
|
||||||
|
if (!authenticated) {
|
||||||
|
if (isApiRoute) {
|
||||||
|
// Return JSON 401 for API routes
|
||||||
|
return new Response(JSON.stringify({ error: 'Unauthorized', message: 'Authentication required' }), {
|
||||||
|
status: 401,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// Redirect to login with return URL
|
||||||
|
const returnUrl = encodeURIComponent(pathname + context.url.search);
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Auth required for ${pathname}, redirecting to login`);
|
||||||
|
return context.redirect(`/login?returnUrl=${returnUrl}`, 302);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check role-based access if roles are specified
|
||||||
|
if (protectedConfig.roles && protectedConfig.roles.length > 0) {
|
||||||
|
const userRoles = user?.roles || [];
|
||||||
|
const isAdmin = userRoles.includes('admin');
|
||||||
|
const hasRequiredRole = isAdmin || protectedConfig.roles.some(role => userRoles.includes(role));
|
||||||
|
if (!hasRequiredRole) {
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] User lacks required role for ${pathname}`);
|
||||||
|
if (isApiRoute) {
|
||||||
|
// Return JSON 403 for API routes
|
||||||
|
return new Response(JSON.stringify({
|
||||||
|
error: 'Forbidden',
|
||||||
|
message: 'Insufficient permissions',
|
||||||
|
requiredRoles: protectedConfig.roles
|
||||||
|
}), {
|
||||||
|
status: 403,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// Store required roles in locals for the login page to access
|
||||||
|
context.locals.accessDenied = true;
|
||||||
|
context.locals.requiredRoles = protectedConfig.roles;
|
||||||
|
context.locals.returnUrl = pathname + context.url.search;
|
||||||
|
// Rewrite to login page - this renders /login but keeps the URL and locals
|
||||||
|
return context.rewrite('/login');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Auth OK for ${pathname}, user: ${user?.username || user?.id || 'unknown'}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check the Host header to differentiate subdomains
|
||||||
|
// Build a headers map safely because Headers.get(':authority') throws
|
||||||
|
const headersMap = {};
|
||||||
|
for (const [k, v] of context.request.headers) {
|
||||||
|
headersMap[k.toLowerCase()] = v;
|
||||||
|
}
|
||||||
|
const hostHeader = headersMap['host'] || '';
|
||||||
|
// Node/http2 might store host as :authority (pseudo header); it appears under iteration as ':authority'
|
||||||
|
const authorityHeader = headersMap[':authority'] || '';
|
||||||
|
// Fallback to context.url.hostname if available (some environments populate it)
|
||||||
|
const urlHost = context.url?.hostname || '';
|
||||||
|
const host = (hostHeader || authorityHeader || urlHost).split(':')[0]; // normalize remove port
|
||||||
|
|
||||||
|
const requestIp = (headersMap['x-forwarded-for']?.split(',')[0]?.trim())
|
||||||
|
|| headersMap['x-real-ip']
|
||||||
|
|| headersMap['cf-connecting-ip']
|
||||||
|
|| headersMap['forwarded']?.split(';').find(kv => kv.trim().startsWith('for='))?.split('=')[1]?.replace(/"/g, '')
|
||||||
|
|| context.request.headers.get('x-client-ip')
|
||||||
|
|| 'unknown';
|
||||||
|
|
||||||
|
// Cloudflare geo data (available in production)
|
||||||
|
const cfCountry = headersMap['cf-ipcountry'] || null;
|
||||||
|
const userAgent = headersMap['user-agent'] || null;
|
||||||
|
|
||||||
|
// Debug info for incoming requests
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] incoming: host=${hostHeader} ip=${requestIp} path=${context.url.pathname}`);
|
||||||
|
|
||||||
|
|
||||||
|
// When the host header is missing, log all headers for debugging and
|
||||||
|
// attempt to determine host from forwarded headers or a dev query header.
|
||||||
|
if (!host) {
|
||||||
|
if (import.meta.env.DEV) console.log('[middleware] WARNING: Host header missing. Dumping headers:');
|
||||||
|
for (const [k, v] of context.request.headers) {
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] header: ${k}=${v}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine if how the request says it wants the whitelabel
|
||||||
|
const forwardedHost = headersMap['x-forwarded-host'] || '';
|
||||||
|
const xWhitelabel = headersMap['x-whitelabel'] || '';
|
||||||
|
const forceWhitelabelQuery = context.url.searchParams.get('whitelabel');
|
||||||
|
|
||||||
|
// Make whitelabel detection dynamic based on `SUBSITES` mapping and incoming signals
|
||||||
|
// We'll detect by full host (host/forwarded/authority) or by short-name match
|
||||||
|
const subsiteHosts = Object.keys(SUBSITES || {});
|
||||||
|
|
||||||
|
const hostSubsite = getSubsiteByHost(host);
|
||||||
|
const forwardedSubsite = getSubsiteByHost(forwardedHost);
|
||||||
|
const authoritySubsite = getSubsiteByHost(authorityHeader);
|
||||||
|
const headerSignalSubsite = getSubsiteFromSignal(xWhitelabel);
|
||||||
|
const querySignalSubsite = getSubsiteFromSignal(forceWhitelabelQuery);
|
||||||
|
|
||||||
|
const wantsSubsite = Boolean(hostSubsite || forwardedSubsite || authoritySubsite || headerSignalSubsite || querySignalSubsite);
|
||||||
|
|
||||||
|
// Use central SUBSITES mapping
|
||||||
|
// import from config.js near top to ensure single source of truth
|
||||||
|
// (we import lazily here for compatibility with middleware runtime)
|
||||||
|
const subsites = SUBSITES || {};
|
||||||
|
|
||||||
|
// Check if the request matches a subsite
|
||||||
|
const subsitePath = subsites[host];
|
||||||
|
if (subsitePath) {
|
||||||
|
const skipPrefixes = ['/_astro', '/_', '/assets', '/scripts', '/favicon', '/api', '/robots.txt', '/_static'];
|
||||||
|
const shouldSkip = skipPrefixes.some((p) => context.url.pathname.startsWith(p));
|
||||||
|
|
||||||
|
if (!shouldSkip && !context.url.pathname.startsWith(subsitePath)) {
|
||||||
|
const newPath = `${subsitePath}${context.url.pathname}`;
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Rewriting ${host} ${context.url.pathname} -> ${newPath}`);
|
||||||
|
return context.rewrite(newPath);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// If the path appears to be a subsite path (like /subsites/req) but the host isn't a subsite,
|
||||||
|
// block so the main site doesn't accidentally serve that content.
|
||||||
|
const allPaths = Object.values(subsites || {});
|
||||||
|
const pathLooksLikeSubsite = allPaths.some((p) => context.url.pathname.startsWith(p));
|
||||||
|
if (pathLooksLikeSubsite) {
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Blocking subsite path on main domain: ${host}${context.url.pathname}`);
|
||||||
|
return new Response('Not found', { status: 404 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Block /subsites/req/* on main domain (codey.lol, local.codey.lol, etc)
|
||||||
|
const isMainDomain = !wantsSubsite;
|
||||||
|
if (isMainDomain && Object.values(subsites || {}).some(p => context.url.pathname.startsWith(p))) {
|
||||||
|
// Immediately return a 404 for /req on the main domain
|
||||||
|
if (Object.values(subsites || {}).includes(context.url.pathname)) {
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Blocking subsite root on main domain: ${hostHeader}${context.url.pathname}`);
|
||||||
|
return new Response('Not found', { status: 404 });
|
||||||
|
}
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Blocking subsite wildcard path on main domain: ${hostHeader}${context.url.pathname}`);
|
||||||
|
return new Response('Not found', { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Explicitly handle the forceWhitelabelQuery to rewrite the path
|
||||||
|
if (forceWhitelabelQuery) {
|
||||||
|
const forced = getSubsiteFromSignal(forceWhitelabelQuery);
|
||||||
|
const subsitePath = forced?.path || (`/${forceWhitelabelQuery}`.startsWith('/') ? `/${forceWhitelabelQuery}` : `/${forceWhitelabelQuery}`);
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Forcing whitelabel via query: ${forceWhitelabelQuery} -> rewrite to ${subsitePath}${context.url.pathname}`);
|
||||||
|
context.url.pathname = `${subsitePath}${context.url.pathname}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pass the whitelabel value explicitly to context.locals
|
||||||
|
// set a normalized whitelabel short name if available
|
||||||
|
const chosen = querySignalSubsite?.short || headerSignalSubsite?.short || hostSubsite?.short || forwardedSubsite?.short || authoritySubsite?.short || null;
|
||||||
|
context.locals.whitelabel = chosen;
|
||||||
|
context.locals.isSubsite = Boolean(wantsSubsite);
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Setting context.locals.whitelabel: ${context.locals.whitelabel}`);
|
||||||
|
|
||||||
|
// Final debug: show the final pathname we hand to Astro
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Final pathname: ${context.url.pathname}`);
|
||||||
|
|
||||||
|
// Let Astro handle the request first
|
||||||
|
const response = await next();
|
||||||
|
|
||||||
|
// Add security headers to response
|
||||||
|
const securityHeaders = new Headers(response.headers);
|
||||||
|
|
||||||
|
// Prevent clickjacking
|
||||||
|
securityHeaders.set('X-Frame-Options', 'SAMEORIGIN');
|
||||||
|
|
||||||
|
// Prevent MIME type sniffing
|
||||||
|
securityHeaders.set('X-Content-Type-Options', 'nosniff');
|
||||||
|
|
||||||
|
// XSS protection (legacy, but still useful)
|
||||||
|
securityHeaders.set('X-XSS-Protection', '1; mode=block');
|
||||||
|
|
||||||
|
// Referrer policy - send origin only on cross-origin requests
|
||||||
|
securityHeaders.set('Referrer-Policy', 'strict-origin-when-cross-origin');
|
||||||
|
|
||||||
|
// HSTS - enforce HTTPS (only in production)
|
||||||
|
if (!import.meta.env.DEV) {
|
||||||
|
securityHeaders.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Permissions policy - restrict sensitive APIs
|
||||||
|
securityHeaders.set('Permissions-Policy', 'geolocation=(), microphone=(), camera=()');
|
||||||
|
|
||||||
|
// Content Security Policy - restrict resource loading
|
||||||
|
// Note: 'unsafe-inline' and 'unsafe-eval' needed for React/Astro hydration
|
||||||
|
// In production, consider using nonces or hashes for stricter CSP
|
||||||
|
const cspDirectives = [
|
||||||
|
"default-src 'self'",
|
||||||
|
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://www.youtube.com https://www.youtube-nocookie.com https://s.ytimg.com https://challenges.cloudflare.com https://static.cloudflareinsights.com",
|
||||||
|
// Allow Cloudflare's inline event handlers (for Turnstile/challenges)
|
||||||
|
"script-src-attr 'unsafe-inline'",
|
||||||
|
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
|
||||||
|
"font-src 'self' https://fonts.gstatic.com data:",
|
||||||
|
"img-src 'self' data: blob: https: http:",
|
||||||
|
"media-src 'self' blob: https:",
|
||||||
|
"connect-src 'self' https://api.codey.lol https://*.codey.lol https://*.audio.tidal.com wss:",
|
||||||
|
// Allow YouTube for video embeds and Cloudflare for challenges/Turnstile
|
||||||
|
"frame-src 'self' https://www.youtube.com https://www.youtube-nocookie.com https://challenges.cloudflare.com",
|
||||||
|
"object-src 'none'",
|
||||||
|
"base-uri 'self'",
|
||||||
|
"form-action 'self'",
|
||||||
|
"frame-ancestors 'self'",
|
||||||
|
"upgrade-insecure-requests",
|
||||||
|
].join('; ');
|
||||||
|
securityHeaders.set('Content-Security-Policy', cspDirectives);
|
||||||
|
|
||||||
|
// Forward any refreshed auth cookies to the client
|
||||||
|
if (context.locals.refreshedCookies && context.locals.refreshedCookies.length > 0) {
|
||||||
|
const newResponse = new Response(response.body, {
|
||||||
|
status: response.status,
|
||||||
|
statusText: response.statusText,
|
||||||
|
headers: securityHeaders,
|
||||||
|
});
|
||||||
|
context.locals.refreshedCookies.forEach(cookie => {
|
||||||
|
newResponse.headers.append('set-cookie', cookie.trim());
|
||||||
|
});
|
||||||
|
|
||||||
|
// If it's a 404, redirect to home
|
||||||
|
if (newResponse.status === 404 && !context.url.pathname.startsWith('/api/')) {
|
||||||
|
if (import.meta.env.DEV) console.log(`404 redirect: ${context.url.pathname} -> /`);
|
||||||
|
return context.redirect('/', 302);
|
||||||
|
}
|
||||||
|
|
||||||
|
return newResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If it's a 404, redirect to home
|
||||||
|
if (response.status === 404 && !context.url.pathname.startsWith('/api/')) {
|
||||||
|
if (import.meta.env.DEV) console.log(`404 redirect: ${context.url.pathname} -> /`);
|
||||||
|
return context.redirect('/', 302);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return response with security headers
|
||||||
|
return new Response(response.body, {
|
||||||
|
status: response.status,
|
||||||
|
statusText: response.statusText,
|
||||||
|
headers: securityHeaders,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// Handle any middleware errors by redirecting to home
|
||||||
|
console.error('Middleware error:', error);
|
||||||
|
return context.redirect('/', 302);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -2,6 +2,30 @@ import { defineMiddleware } from 'astro:middleware';
|
|||||||
import { SUBSITES, PROTECTED_ROUTES, PUBLIC_ROUTES, type ProtectedRoute } from './config.ts';
|
import { SUBSITES, PROTECTED_ROUTES, PUBLIC_ROUTES, type ProtectedRoute } from './config.ts';
|
||||||
import { getSubsiteByHost, getSubsiteFromSignal, type SubsiteInfo } from './utils/subsites.ts';
|
import { getSubsiteByHost, getSubsiteFromSignal, type SubsiteInfo } from './utils/subsites.ts';
|
||||||
|
|
||||||
|
declare module 'astro' {
|
||||||
|
interface Locals {
|
||||||
|
user?: AuthUser;
|
||||||
|
refreshedCookies?: string[];
|
||||||
|
accessDenied?: boolean;
|
||||||
|
requiredRoles?: string[];
|
||||||
|
returnUrl?: string;
|
||||||
|
whitelabel?: string | null;
|
||||||
|
isSubsite?: boolean;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
declare module 'astro:middleware' {
|
||||||
|
interface Locals {
|
||||||
|
user?: AuthUser;
|
||||||
|
refreshedCookies?: string[];
|
||||||
|
accessDenied?: boolean;
|
||||||
|
requiredRoles?: string[];
|
||||||
|
returnUrl?: string;
|
||||||
|
whitelabel?: string | null;
|
||||||
|
isSubsite?: boolean;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export interface AuthUser {
|
export interface AuthUser {
|
||||||
id?: string;
|
id?: string;
|
||||||
username?: string;
|
username?: string;
|
||||||
@@ -313,9 +337,9 @@ export const onRequest = defineMiddleware(async (context, next) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
// Store required roles in locals for the login page to access
|
// Store required roles in locals for the login page to access
|
||||||
context.locals.accessDenied = true;
|
(context.locals as any).accessDenied = true;
|
||||||
context.locals.requiredRoles = protectedConfig.roles;
|
(context.locals as any).requiredRoles = protectedConfig.roles;
|
||||||
context.locals.returnUrl = pathname + context.url.search;
|
(context.locals as any).returnUrl = pathname + context.url.search;
|
||||||
// Rewrite to login page - this renders /login but keeps the URL and locals
|
// Rewrite to login page - this renders /login but keeps the URL and locals
|
||||||
return context.rewrite('/login');
|
return context.rewrite('/login');
|
||||||
}
|
}
|
||||||
@@ -374,8 +398,8 @@ export const onRequest = defineMiddleware(async (context, next) => {
|
|||||||
const hostSubsite = getSubsiteByHost(host);
|
const hostSubsite = getSubsiteByHost(host);
|
||||||
const forwardedSubsite = getSubsiteByHost(forwardedHost);
|
const forwardedSubsite = getSubsiteByHost(forwardedHost);
|
||||||
const authoritySubsite = getSubsiteByHost(authorityHeader);
|
const authoritySubsite = getSubsiteByHost(authorityHeader);
|
||||||
const headerSignalSubsite = getSubsiteFromSignal(xWhitelabel);
|
const headerSignalSubsite = getSubsiteFromSignal(xWhitelabel || undefined);
|
||||||
const querySignalSubsite = getSubsiteFromSignal(forceWhitelabelQuery);
|
const querySignalSubsite = getSubsiteFromSignal(forceWhitelabelQuery || undefined);
|
||||||
|
|
||||||
const wantsSubsite = Boolean(hostSubsite || forwardedSubsite || authoritySubsite || headerSignalSubsite || querySignalSubsite);
|
const wantsSubsite = Boolean(hostSubsite || forwardedSubsite || authoritySubsite || headerSignalSubsite || querySignalSubsite);
|
||||||
|
|
||||||
@@ -420,7 +444,7 @@ export const onRequest = defineMiddleware(async (context, next) => {
|
|||||||
|
|
||||||
// Explicitly handle the forceWhitelabelQuery to rewrite the path
|
// Explicitly handle the forceWhitelabelQuery to rewrite the path
|
||||||
if (forceWhitelabelQuery) {
|
if (forceWhitelabelQuery) {
|
||||||
const forced = getSubsiteFromSignal(forceWhitelabelQuery);
|
const forced = getSubsiteFromSignal(forceWhitelabelQuery || undefined);
|
||||||
const subsitePath = forced?.path || (`/${forceWhitelabelQuery}`.startsWith('/') ? `/${forceWhitelabelQuery}` : `/${forceWhitelabelQuery}`);
|
const subsitePath = forced?.path || (`/${forceWhitelabelQuery}`.startsWith('/') ? `/${forceWhitelabelQuery}` : `/${forceWhitelabelQuery}`);
|
||||||
if (import.meta.env.DEV) console.log(`[middleware] Forcing whitelabel via query: ${forceWhitelabelQuery} -> rewrite to ${subsitePath}${context.url.pathname}`);
|
if (import.meta.env.DEV) console.log(`[middleware] Forcing whitelabel via query: ${forceWhitelabelQuery} -> rewrite to ${subsitePath}${context.url.pathname}`);
|
||||||
context.url.pathname = `${subsitePath}${context.url.pathname}`;
|
context.url.pathname = `${subsitePath}${context.url.pathname}`;
|
||||||
@@ -433,7 +457,6 @@ export const onRequest = defineMiddleware(async (context, next) => {
|
|||||||
// Also make it explicit whether this request maps to a subsite (any configured SUBSITES value)
|
// Also make it explicit whether this request maps to a subsite (any configured SUBSITES value)
|
||||||
// Middleware already resolved `wantsSubsite` which is true if host/forwarded/authority/header/query indicate a subsite.
|
// Middleware already resolved `wantsSubsite` which is true if host/forwarded/authority/header/query indicate a subsite.
|
||||||
// Expose a simple boolean so server-rendered pages/layouts or components can opt-out of loading/hydrating
|
// Expose a simple boolean so server-rendered pages/layouts or components can opt-out of loading/hydrating
|
||||||
// heavyweight subsystems (like the AudioPlayer) when the request is for a subsite.
|
|
||||||
context.locals.isSubsite = Boolean(wantsSubsite);
|
context.locals.isSubsite = Boolean(wantsSubsite);
|
||||||
if (import.meta.env.DEV) console.log(`[middleware] Setting context.locals.whitelabel: ${context.locals.whitelabel}`);
|
if (import.meta.env.DEV) console.log(`[middleware] Setting context.locals.whitelabel: ${context.locals.whitelabel}`);
|
||||||
|
|
||||||
|
|||||||
@@ -120,6 +120,10 @@ export async function GET({ request }: APIContext): Promise<Response> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Partial content
|
// Partial content
|
||||||
|
if (result.start == null || result.end == null) {
|
||||||
|
console.error('[cached-video] Missing range bounds in partial response');
|
||||||
|
return new Response('Invalid range', { status: 500 });
|
||||||
|
}
|
||||||
headers.set('Content-Range', `bytes ${result.start}-${result.end}/${result.total}`);
|
headers.set('Content-Range', `bytes ${result.start}-${result.end}/${result.total}`);
|
||||||
headers.set('Content-Length', String(result.end - result.start + 1));
|
headers.set('Content-Length', String(result.end - result.start + 1));
|
||||||
return new Response(result.stream, { status: 206, headers });
|
return new Response(result.stream, { status: 206, headers });
|
||||||
|
|||||||
@@ -27,9 +27,9 @@ interface ChannelRow {
|
|||||||
export async function GET({ request }: APIContext): Promise<Response> {
|
export async function GET({ request }: APIContext): Promise<Response> {
|
||||||
// Rate limit check
|
// Rate limit check
|
||||||
const rateCheck = checkRateLimit(request, {
|
const rateCheck = checkRateLimit(request, {
|
||||||
limit: 20,
|
limit: 60,
|
||||||
windowMs: 1000,
|
windowMs: 1000,
|
||||||
burstLimit: 100,
|
burstLimit: 240,
|
||||||
burstWindowMs: 10_000,
|
burstWindowMs: 10_000,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,12 @@ const ADMINISTRATOR = 0x8n; // 8
|
|||||||
* 3. Apply member-specific overwrites (allow/deny)
|
* 3. Apply member-specific overwrites (allow/deny)
|
||||||
* 4. Check if VIEW_CHANNEL permission is granted
|
* 4. Check if VIEW_CHANNEL permission is granted
|
||||||
*/
|
*/
|
||||||
async function getChannelVisibleMembers(channelId, guildId) {
|
interface RoleOverwrite {
|
||||||
|
allow: bigint;
|
||||||
|
deny: bigint;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getChannelVisibleMembers(channelId: string, guildId: string): Promise<Set<string>> {
|
||||||
// Get guild info including owner
|
// Get guild info including owner
|
||||||
const guildInfo = await sql`
|
const guildInfo = await sql`
|
||||||
SELECT owner_id FROM guilds WHERE guild_id = ${guildId}
|
SELECT owner_id FROM guilds WHERE guild_id = ${guildId}
|
||||||
@@ -43,8 +48,8 @@ async function getChannelVisibleMembers(channelId, guildId) {
|
|||||||
`;
|
`;
|
||||||
|
|
||||||
// Build overwrite lookups
|
// Build overwrite lookups
|
||||||
const roleOverwrites = new Map();
|
const roleOverwrites = new Map<string, RoleOverwrite>();
|
||||||
const memberOverwrites = new Map();
|
const memberOverwrites = new Map<string, RoleOverwrite>();
|
||||||
for (const ow of overwrites) {
|
for (const ow of overwrites) {
|
||||||
const targetId = ow.target_id.toString();
|
const targetId = ow.target_id.toString();
|
||||||
const allow = BigInt(ow.allow_permissions);
|
const allow = BigInt(ow.allow_permissions);
|
||||||
@@ -67,16 +72,16 @@ async function getChannelVisibleMembers(channelId, guildId) {
|
|||||||
const allRoles = await sql`
|
const allRoles = await sql`
|
||||||
SELECT role_id, permissions FROM roles WHERE guild_id = ${guildId}
|
SELECT role_id, permissions FROM roles WHERE guild_id = ${guildId}
|
||||||
`;
|
`;
|
||||||
const rolePermissions = new Map();
|
const rolePermissions = new Map<string, bigint>();
|
||||||
for (const role of allRoles) {
|
for (const role of allRoles) {
|
||||||
rolePermissions.set(role.role_id.toString(), BigInt(role.permissions || 0));
|
rolePermissions.set(role.role_id.toString(), BigInt(role.permissions || 0));
|
||||||
}
|
}
|
||||||
|
|
||||||
const visibleMemberIds = new Set();
|
const visibleMemberIds = new Set<string>();
|
||||||
|
|
||||||
for (const member of members) {
|
for (const member of members) {
|
||||||
const userId = member.user_id.toString();
|
const userId = member.user_id.toString();
|
||||||
const memberRoles = (member.roles || []).map(r => r.toString());
|
const memberRoles = (member.roles || []).map((r: bigint | string) => r.toString());
|
||||||
|
|
||||||
// Owner always has access
|
// Owner always has access
|
||||||
if (ownerId && member.user_id.toString() === ownerId.toString()) {
|
if (ownerId && member.user_id.toString() === ownerId.toString()) {
|
||||||
@@ -138,9 +143,9 @@ async function getChannelVisibleMembers(channelId, guildId) {
|
|||||||
export async function GET({ request }) {
|
export async function GET({ request }) {
|
||||||
// Rate limit check
|
// Rate limit check
|
||||||
const rateCheck = checkRateLimit(request, {
|
const rateCheck = checkRateLimit(request, {
|
||||||
limit: 20,
|
limit: 80,
|
||||||
windowMs: 1000,
|
windowMs: 1000,
|
||||||
burstLimit: 100,
|
burstLimit: 320,
|
||||||
burstWindowMs: 10_000,
|
burstWindowMs: 10_000,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -187,7 +192,7 @@ export async function GET({ request }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// If channelId provided, get visible members for that channel
|
// If channelId provided, get visible members for that channel
|
||||||
let visibleMemberIds = null;
|
let visibleMemberIds: Set<string> | null = null;
|
||||||
if (channelId) {
|
if (channelId) {
|
||||||
visibleMemberIds = await getChannelVisibleMembers(channelId, guildId);
|
visibleMemberIds = await getChannelVisibleMembers(channelId, guildId);
|
||||||
}
|
}
|
||||||
@@ -226,14 +231,22 @@ export async function GET({ request }) {
|
|||||||
`;
|
`;
|
||||||
|
|
||||||
// Create role lookup map
|
// Create role lookup map
|
||||||
const roleMap = {};
|
interface RoleInfo {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
color: string | null;
|
||||||
|
position: number;
|
||||||
|
hoist: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const roleMap: Record<string, RoleInfo> = {};
|
||||||
roles.forEach(role => {
|
roles.forEach(role => {
|
||||||
roleMap[role.role_id.toString()] = {
|
roleMap[role.role_id.toString()] = {
|
||||||
id: role.role_id.toString(),
|
id: role.role_id.toString(),
|
||||||
name: role.name,
|
name: role.name,
|
||||||
color: role.color ? `#${role.color.toString(16).padStart(6, '0')}` : null,
|
color: role.color ? `#${Number(role.color).toString(16).padStart(6, '0')}` : null,
|
||||||
position: role.position,
|
position: Number(role.position ?? 0),
|
||||||
hoist: role.hoist, // "hoist" means the role is displayed separately in member list
|
hoist: Boolean(role.hoist), // "hoist" means the role is displayed separately in member list
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -243,11 +256,24 @@ export async function GET({ request }) {
|
|||||||
: members;
|
: members;
|
||||||
|
|
||||||
// Format members with their highest role for color
|
// Format members with their highest role for color
|
||||||
const formattedMembers = filteredMembers.map(member => {
|
interface FormattedMember {
|
||||||
const memberRoles = (member.roles || []).map(r => r.toString());
|
id: string;
|
||||||
|
username: string;
|
||||||
|
displayName: string;
|
||||||
|
avatar: string | null;
|
||||||
|
isBot: boolean;
|
||||||
|
color: string | null;
|
||||||
|
primaryRoleId: string | null;
|
||||||
|
primaryRoleName: string | null;
|
||||||
|
roles: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const formattedMembers: FormattedMember[] = filteredMembers.map(member => {
|
||||||
|
const memberRoles = (member.roles || []).map((r: bigint | string) => r.toString());
|
||||||
|
|
||||||
// Find highest positioned role with color for display
|
// Find highest positioned role with color for display
|
||||||
let displayRole = null;
|
let displayRole: RoleInfo | null = null;
|
||||||
|
let displayRoleColor: string | null = null;
|
||||||
let highestPosition = -1;
|
let highestPosition = -1;
|
||||||
|
|
||||||
memberRoles.forEach(roleId => {
|
memberRoles.forEach(roleId => {
|
||||||
@@ -256,6 +282,7 @@ export async function GET({ request }) {
|
|||||||
highestPosition = role.position;
|
highestPosition = role.position;
|
||||||
if (role.color && role.color !== '#000000') {
|
if (role.color && role.color !== '#000000') {
|
||||||
displayRole = role;
|
displayRole = role;
|
||||||
|
displayRoleColor = role.color;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -263,7 +290,7 @@ export async function GET({ request }) {
|
|||||||
// Find all hoisted roles for grouping
|
// Find all hoisted roles for grouping
|
||||||
const hoistedRoles = memberRoles
|
const hoistedRoles = memberRoles
|
||||||
.map(rid => roleMap[rid])
|
.map(rid => roleMap[rid])
|
||||||
.filter(r => r && r.hoist)
|
.filter((r): r is RoleInfo => Boolean(r && r.hoist))
|
||||||
.sort((a, b) => b.position - a.position);
|
.sort((a, b) => b.position - a.position);
|
||||||
|
|
||||||
const primaryRole = hoistedRoles[0] || displayRole || null;
|
const primaryRole = hoistedRoles[0] || displayRole || null;
|
||||||
@@ -284,7 +311,7 @@ export async function GET({ request }) {
|
|||||||
displayName: member.nickname || member.global_name || member.username,
|
displayName: member.nickname || member.global_name || member.username,
|
||||||
avatar: avatarUrl,
|
avatar: avatarUrl,
|
||||||
isBot: member.is_bot || false,
|
isBot: member.is_bot || false,
|
||||||
color: displayRole?.color || null,
|
color: displayRoleColor,
|
||||||
primaryRoleId: primaryRole?.id || null,
|
primaryRoleId: primaryRole?.id || null,
|
||||||
primaryRoleName: primaryRole?.name || null,
|
primaryRoleName: primaryRole?.name || null,
|
||||||
roles: memberRoles,
|
roles: memberRoles,
|
||||||
@@ -292,8 +319,8 @@ export async function GET({ request }) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Group members by their primary (highest hoisted) role
|
// Group members by their primary (highest hoisted) role
|
||||||
const membersByRole = {};
|
const membersByRole: Record<string, { role: RoleInfo; members: FormattedMember[] }> = {};
|
||||||
const noRoleMembers = [];
|
const noRoleMembers: FormattedMember[] = [];
|
||||||
|
|
||||||
formattedMembers.forEach(member => {
|
formattedMembers.forEach(member => {
|
||||||
if (member.primaryRoleId) {
|
if (member.primaryRoleId) {
|
||||||
@@ -316,7 +343,7 @@ export async function GET({ request }) {
|
|||||||
// Add "Online" or default group for members without hoisted roles
|
// Add "Online" or default group for members without hoisted roles
|
||||||
if (noRoleMembers.length > 0) {
|
if (noRoleMembers.length > 0) {
|
||||||
sortedGroups.push({
|
sortedGroups.push({
|
||||||
role: { id: 'none', name: 'Members', color: null, position: -1 },
|
role: { id: 'none', name: 'Members', color: null, position: -1, hoist: false },
|
||||||
members: noRoleMembers,
|
members: noRoleMembers,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -99,9 +99,9 @@ function getSafeImageUrl(originalUrl: string | null, baseUrl: string): string |
|
|||||||
export async function GET({ request }: APIContext) {
|
export async function GET({ request }: APIContext) {
|
||||||
// Rate limit check
|
// Rate limit check
|
||||||
const rateCheck = checkRateLimit(request, {
|
const rateCheck = checkRateLimit(request, {
|
||||||
limit: 30,
|
limit: 100,
|
||||||
windowMs: 1000,
|
windowMs: 1000,
|
||||||
burstLimit: 150,
|
burstLimit: 400,
|
||||||
burstWindowMs: 10_000,
|
burstWindowMs: 10_000,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -920,7 +920,7 @@ export async function GET({ request }: APIContext) {
|
|||||||
}
|
}
|
||||||
const ext = stickerExtensions[sticker.format_type] || 'png';
|
const ext = stickerExtensions[sticker.format_type] || 'png';
|
||||||
// Use cached sticker image if available, otherwise fall back to Discord CDN
|
// Use cached sticker image if available, otherwise fall back to Discord CDN
|
||||||
let stickerUrl = null;
|
let stickerUrl: string | null = null;
|
||||||
if (sticker.cached_image_id) {
|
if (sticker.cached_image_id) {
|
||||||
const sig = signImageId(sticker.cached_image_id);
|
const sig = signImageId(sticker.cached_image_id);
|
||||||
stickerUrl = `${baseUrl}/api/discord/cached-image?id=${sticker.cached_image_id}&sig=${sig}`;
|
stickerUrl = `${baseUrl}/api/discord/cached-image?id=${sticker.cached_image_id}&sig=${sig}`;
|
||||||
|
|||||||
@@ -182,7 +182,20 @@ export async function GET({ request }) {
|
|||||||
LEFT JOIN video_cache vc ON a.cached_video_id = vc.video_id
|
LEFT JOIN video_cache vc ON a.cached_video_id = vc.video_id
|
||||||
WHERE a.message_id = ANY(${messageIds})
|
WHERE a.message_id = ANY(${messageIds})
|
||||||
ORDER BY a.attachment_id
|
ORDER BY a.attachment_id
|
||||||
`;
|
` as unknown as Array<{
|
||||||
|
message_id: string;
|
||||||
|
attachment_id: string;
|
||||||
|
filename: string | null;
|
||||||
|
url: string;
|
||||||
|
proxy_url: string | null;
|
||||||
|
content_type: string | null;
|
||||||
|
size: number | null;
|
||||||
|
width: number | null;
|
||||||
|
height: number | null;
|
||||||
|
cached_image_id: number | null;
|
||||||
|
cached_video_id: number | null;
|
||||||
|
video_file_path: string | null;
|
||||||
|
}>;
|
||||||
|
|
||||||
// Fetch cached video URLs for video attachments
|
// Fetch cached video URLs for video attachments
|
||||||
const videoUrls = attachments
|
const videoUrls = attachments
|
||||||
@@ -193,9 +206,9 @@ export async function GET({ request }) {
|
|||||||
SELECT source_url, video_id
|
SELECT source_url, video_id
|
||||||
FROM video_cache
|
FROM video_cache
|
||||||
WHERE source_url = ANY(${videoUrls})
|
WHERE source_url = ANY(${videoUrls})
|
||||||
` : [];
|
` as unknown as Array<{ source_url: string; video_id: number }> : [];
|
||||||
|
|
||||||
const videoCacheMap = {};
|
const videoCacheMap: Record<string, number> = {};
|
||||||
cachedVideos.forEach(v => {
|
cachedVideos.forEach(v => {
|
||||||
videoCacheMap[v.source_url] = v.video_id;
|
videoCacheMap[v.source_url] = v.video_id;
|
||||||
});
|
});
|
||||||
@@ -234,7 +247,13 @@ export async function GET({ request }) {
|
|||||||
.filter(m => m.reference_message_id)
|
.filter(m => m.reference_message_id)
|
||||||
.map(m => m.reference_message_id);
|
.map(m => m.reference_message_id);
|
||||||
|
|
||||||
let referencedMessages = [];
|
let referencedMessages: Array<{
|
||||||
|
message_id: string;
|
||||||
|
content: string;
|
||||||
|
author_id: string;
|
||||||
|
author_username: string;
|
||||||
|
author_display_name: string;
|
||||||
|
}> = [];
|
||||||
if (referencedIds.length > 0) {
|
if (referencedIds.length > 0) {
|
||||||
referencedMessages = await sql`
|
referencedMessages = await sql`
|
||||||
SELECT
|
SELECT
|
||||||
|
|||||||
@@ -263,7 +263,8 @@ export async function GET({ request }) {
|
|||||||
return proxyResponse;
|
return proxyResponse;
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('[image-proxy] Error fetching image:', err.message);
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
|
console.error('[image-proxy] Error fetching image:', message);
|
||||||
return new Response('Failed to fetch image', { status: 500 });
|
return new Response('Failed to fetch image', { status: 500 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ interface LinkPreviewMeta {
|
|||||||
type: string | null;
|
type: string | null;
|
||||||
video: string | null;
|
video: string | null;
|
||||||
themeColor: string | null;
|
themeColor: string | null;
|
||||||
|
trusted: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Trusted domains that can be loaded client-side
|
// Trusted domains that can be loaded client-side
|
||||||
@@ -73,6 +74,7 @@ function parseMetaTags(html: string, url: string): LinkPreviewMeta {
|
|||||||
type: null,
|
type: null,
|
||||||
video: null,
|
video: null,
|
||||||
themeColor: null,
|
themeColor: null,
|
||||||
|
trusted: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
const decode = str => str?.replace(/&(#(?:x[0-9a-fA-F]+|\d+)|[a-zA-Z]+);/g,
|
const decode = str => str?.replace(/&(#(?:x[0-9a-fA-F]+|\d+)|[a-zA-Z]+);/g,
|
||||||
@@ -253,6 +255,13 @@ export async function GET({ request }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Read first 50KB
|
// Read first 50KB
|
||||||
|
if (!response.body) {
|
||||||
|
return new Response(JSON.stringify({ error: 'Empty response body' }), {
|
||||||
|
status: 502,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const reader = response.body.getReader();
|
const reader = response.body.getReader();
|
||||||
let html = '';
|
let html = '';
|
||||||
let bytesRead = 0;
|
let bytesRead = 0;
|
||||||
@@ -281,7 +290,8 @@ export async function GET({ request }) {
|
|||||||
return resp;
|
return resp;
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('[link-preview] Error fetching URL:', err.message);
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
|
console.error('[link-preview] Error fetching URL:', message);
|
||||||
// Don't expose internal error details to client
|
// Don't expose internal error details to client
|
||||||
return new Response(JSON.stringify({ error: 'Failed to fetch preview' }), {
|
return new Response(JSON.stringify({ error: 'Failed to fetch preview' }), {
|
||||||
status: 500,
|
status: 500,
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ interface SearchSuggestion {
|
|||||||
|
|
||||||
export async function GET({ request }: APIContext): Promise<Response> {
|
export async function GET({ request }: APIContext): Promise<Response> {
|
||||||
const host = request.headers.get('host');
|
const host = request.headers.get('host');
|
||||||
const subsite = getSubsiteByHost(host);
|
const subsite = getSubsiteByHost(host || undefined);
|
||||||
|
|
||||||
if (!subsite || subsite.short !== 'req') {
|
if (!subsite || subsite.short !== 'req') {
|
||||||
return new Response('Not found', { status: 404 });
|
return new Response('Not found', { status: 404 });
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import Root from "@/components/AppLayout.jsx";
|
|||||||
const user = Astro.locals.user as any;
|
const user = Astro.locals.user as any;
|
||||||
---
|
---
|
||||||
|
|
||||||
<Base>
|
<Base title="Lighting">
|
||||||
<section class="page-section">
|
<section class="page-section">
|
||||||
<Root child="Lighting" user?={user} client:only="react" />
|
<Root child="Lighting" user?={user} client:only="react" />
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ const accessDenied = Astro.locals.accessDenied || false;
|
|||||||
const requiredRoles = Astro.locals.requiredRoles || [];
|
const requiredRoles = Astro.locals.requiredRoles || [];
|
||||||
|
|
||||||
---
|
---
|
||||||
<Base>
|
<Base title="Login">
|
||||||
<section class="page-section">
|
<section class="page-section">
|
||||||
<Root child="LoginPage" loggedIn={isLoggedIn} accessDenied={accessDenied} requiredRoles={requiredRoles} client:only="react" />
|
<Root child="LoginPage" loggedIn={isLoggedIn} accessDenied={accessDenied} requiredRoles={requiredRoles} client:only="react" />
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import Root from "../components/AppLayout.jsx";
|
|||||||
import "@styles/MemeGrid.css";
|
import "@styles/MemeGrid.css";
|
||||||
---
|
---
|
||||||
|
|
||||||
<Base hideFooter>
|
<Base hideFooter title="Memes">
|
||||||
<section class="page-section">
|
<section class="page-section">
|
||||||
<Root child="Memes" client:only="react" />
|
<Root child="Memes" client:only="react" />
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ export async function requireApiAuth(request: Request): Promise<AuthResult> {
|
|||||||
}
|
}
|
||||||
clearTimeout(timeout);
|
clearTimeout(timeout);
|
||||||
|
|
||||||
let newSetCookieHeader = null;
|
let newSetCookieHeader: string[] | null = null;
|
||||||
|
|
||||||
// If unauthorized, try to refresh the token
|
// If unauthorized, try to refresh the token
|
||||||
if (res.status === 401) {
|
if (res.status === 401) {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import postgres from 'postgres';
|
|||||||
import type { Sql } from 'postgres';
|
import type { Sql } from 'postgres';
|
||||||
|
|
||||||
// Database connection configuration
|
// Database connection configuration
|
||||||
const sql: Sql = postgres({
|
const sql: Sql<any> = postgres({
|
||||||
host: import.meta.env.DISCORD_DB_HOST || 'localhost',
|
host: import.meta.env.DISCORD_DB_HOST || 'localhost',
|
||||||
port: parseInt(import.meta.env.DISCORD_DB_PORT || '5432', 10),
|
port: parseInt(import.meta.env.DISCORD_DB_PORT || '5432', 10),
|
||||||
database: import.meta.env.DISCORD_DB_NAME || 'discord',
|
database: import.meta.env.DISCORD_DB_NAME || 'discord',
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { SUBSITES, WHITELABELS, WhitelabelConfig } from '../config.ts';
|
import { SUBSITES, WHITELABELS, type WhitelabelConfig } from '../config.ts';
|
||||||
|
|
||||||
export interface SubsiteInfo {
|
export interface SubsiteInfo {
|
||||||
host: string;
|
host: string;
|
||||||
|
|||||||
Reference in New Issue
Block a user