mirror of
https://github.com/MODSetter/SurfSense.git
synced 2026-06-26 21:39:43 +02:00
fix(zero):load authz context for queries
This commit is contained in:
parent
54ff86dcc2
commit
3cbd109e8d
4 changed files with 155 additions and 42 deletions
|
|
@ -12,45 +12,67 @@ import { schema } from "@/zero/schema";
|
|||
// (e.g. http://localhost:8929) does NOT resolve from inside the frontend
|
||||
// container and would make every authenticated Zero query fail with a 503.
|
||||
const backendURL = SERVER_BACKEND_URL.replace(/\/$/, "");
|
||||
const zeroQueryApiKey = process.env.ZERO_QUERY_API_KEY;
|
||||
|
||||
function validateZeroCacheRequest(request: Request): NextResponse | null {
|
||||
if (!zeroQueryApiKey) return null;
|
||||
if (request.headers.get("X-Api-Key") === zeroQueryApiKey) return null;
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
}
|
||||
|
||||
async function authenticateRequest(
|
||||
request: Request
|
||||
): Promise<{ ctx: Context; error?: never } | { ctx?: never; error: NextResponse }> {
|
||||
): Promise<
|
||||
| { ctx: Exclude<Context, undefined>; error?: never }
|
||||
| { ctx?: never; error: NextResponse }
|
||||
> {
|
||||
const authHeader = request.headers.get("Authorization");
|
||||
if (!authHeader?.startsWith("Bearer ")) {
|
||||
return { ctx: undefined };
|
||||
const cookieHeader = request.headers.get("Cookie");
|
||||
const headers: HeadersInit = {};
|
||||
if (authHeader?.startsWith("Bearer ")) {
|
||||
headers.Authorization = authHeader;
|
||||
} else if (cookieHeader) {
|
||||
headers.Cookie = cookieHeader;
|
||||
} else {
|
||||
return { error: NextResponse.json({ error: "Unauthorized" }, { status: 401 }) };
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`${backendURL}/users/me`, {
|
||||
headers: { Authorization: authHeader },
|
||||
const res = await fetch(`${backendURL}/zero/context`, {
|
||||
headers,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
return { error: NextResponse.json({ error: "Unauthorized" }, { status: 401 }) };
|
||||
}
|
||||
|
||||
const user = await res.json();
|
||||
return { ctx: { userId: String(user.id) } };
|
||||
const ctx = (await res.json()) as Exclude<Context, undefined>;
|
||||
return { ctx };
|
||||
} catch {
|
||||
return { error: NextResponse.json({ error: "Auth service unavailable" }, { status: 503 }) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const forbidden = validateZeroCacheRequest(request);
|
||||
if (forbidden) {
|
||||
return forbidden;
|
||||
}
|
||||
|
||||
const auth = await authenticateRequest(request);
|
||||
if (auth.error) {
|
||||
return auth.error;
|
||||
}
|
||||
|
||||
const result = await handleQueryRequest(
|
||||
(name, args) => {
|
||||
const result = await handleQueryRequest({
|
||||
handler: (name, args) => {
|
||||
const query = mustGetQuery(queries, name);
|
||||
return query.fn({ args, ctx: auth.ctx });
|
||||
},
|
||||
schema,
|
||||
request
|
||||
);
|
||||
request,
|
||||
userID: auth.ctx.userId,
|
||||
});
|
||||
|
||||
return NextResponse.json(result);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,9 +6,16 @@ import {
|
|||
ZeroProvider as ZeroReactProvider,
|
||||
} from "@rocicorp/zero/react";
|
||||
import { useAtomValue } from "jotai";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { currentUserAtom } from "@/atoms/user/user-query.atoms";
|
||||
import { getBearerToken, handleUnauthorized, refreshAccessToken } from "@/lib/auth-utils";
|
||||
import { useSession } from "@/hooks/use-session";
|
||||
import {
|
||||
getBearerToken,
|
||||
handleUnauthorized,
|
||||
isPublicRoute,
|
||||
refreshAccessToken,
|
||||
} from "@/lib/auth-utils";
|
||||
import { queries } from "@/zero/queries";
|
||||
import { schema } from "@/zero/schema";
|
||||
|
||||
|
|
@ -22,48 +29,74 @@ function getCacheURL() {
|
|||
return "http://localhost:4848";
|
||||
}
|
||||
|
||||
function ZeroAuthSync() {
|
||||
function ZeroAuthSync({ isDesktop }: { isDesktop: boolean }) {
|
||||
const zero = useZero();
|
||||
const connectionState = useConnectionState();
|
||||
const isRefreshingRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (connectionState.name !== "needs-auth" || isRefreshingRef.current) return;
|
||||
if (connectionState.name !== "needs-auth") return;
|
||||
|
||||
isRefreshingRef.current = true;
|
||||
refreshAccessToken().then((newToken) => {
|
||||
if (!newToken) {
|
||||
handleUnauthorized();
|
||||
return;
|
||||
}
|
||||
|
||||
refreshAccessToken()
|
||||
.then((newToken) => {
|
||||
if (newToken) {
|
||||
zero.connection.connect({ auth: newToken });
|
||||
} else {
|
||||
handleUnauthorized();
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
isRefreshingRef.current = false;
|
||||
});
|
||||
}, [connectionState, zero]);
|
||||
if (isDesktop) {
|
||||
zero.connection.connect({ auth: newToken });
|
||||
} else {
|
||||
zero.connection.connect();
|
||||
}
|
||||
});
|
||||
}, [connectionState.name, isDesktop, zero]);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === "undefined" || !window.electronAPI?.onAuthChanged) return;
|
||||
return window.electronAPI.onAuthChanged(({ accessToken }) => {
|
||||
if (accessToken) {
|
||||
zero.connection.connect({ auth: accessToken });
|
||||
}
|
||||
});
|
||||
}, [zero]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function ZeroProvider({ children }: { children: React.ReactNode }) {
|
||||
const { data: user } = useAtomValue(currentUserAtom);
|
||||
const cacheURL = useMemo(() => getCacheURL(), []);
|
||||
function AuthenticatedZeroProvider({
|
||||
children,
|
||||
isDesktop,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
isDesktop: boolean;
|
||||
}) {
|
||||
const { data: user, isLoading } = useAtomValue(currentUserAtom);
|
||||
|
||||
const userId = user?.id;
|
||||
const hasUser = !!userId;
|
||||
const userID = hasUser ? String(userId) : "anon";
|
||||
// getBearerToken() returns a string (a primitive), so it's safe to read
|
||||
// on every render — reference equality holds as long as the token is
|
||||
// unchanged, which keeps the memoized `opts` below stable.
|
||||
const auth = hasUser ? getBearerToken() || undefined : undefined;
|
||||
const userID = userId ? String(userId) : undefined;
|
||||
|
||||
const context = useMemo(
|
||||
() => (hasUser ? { userId: String(userId) } : undefined),
|
||||
[hasUser, userId]
|
||||
if (isLoading || !userID) {
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
return (
|
||||
<ZeroClientProvider userID={userID} isDesktop={isDesktop}>
|
||||
{children}
|
||||
</ZeroClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function ZeroClientProvider({
|
||||
children,
|
||||
userID,
|
||||
isDesktop,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
userID: string;
|
||||
isDesktop: boolean;
|
||||
}) {
|
||||
const cacheURL = useMemo(() => getCacheURL(), []);
|
||||
const auth = isDesktop ? getBearerToken() || undefined : undefined;
|
||||
const context = useMemo(() => ({ userId: userID }), [userID]);
|
||||
|
||||
const opts = useMemo(
|
||||
() => ({
|
||||
|
|
@ -79,8 +112,37 @@ export function ZeroProvider({ children }: { children: React.ReactNode }) {
|
|||
|
||||
return (
|
||||
<ZeroReactProvider {...opts}>
|
||||
{hasUser && <ZeroAuthSync />}
|
||||
<ZeroAuthSync isDesktop={isDesktop} />
|
||||
{children}
|
||||
</ZeroReactProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function WebZeroProvider({ children }: { children: React.ReactNode }) {
|
||||
const session = useSession();
|
||||
|
||||
if (session.status !== "authenticated") {
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
return <AuthenticatedZeroProvider isDesktop={false}>{children}</AuthenticatedZeroProvider>;
|
||||
}
|
||||
|
||||
function DesktopZeroProvider({ children }: { children: React.ReactNode }) {
|
||||
return <AuthenticatedZeroProvider isDesktop>{children}</AuthenticatedZeroProvider>;
|
||||
}
|
||||
|
||||
export function ZeroProvider({ children }: { children: React.ReactNode }) {
|
||||
const pathname = usePathname();
|
||||
const isDesktop = typeof window !== "undefined" && !!window.electronAPI;
|
||||
|
||||
if (!isDesktop && isPublicRoute(pathname)) {
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
if (isDesktop) {
|
||||
return <DesktopZeroProvider>{children}</DesktopZeroProvider>;
|
||||
}
|
||||
|
||||
return <WebZeroProvider>{children}</WebZeroProvider>;
|
||||
}
|
||||
|
|
|
|||
1
surfsense_web/types/zero.d.ts
vendored
1
surfsense_web/types/zero.d.ts
vendored
|
|
@ -3,6 +3,7 @@ import type { Schema } from "@/zero/schema/index";
|
|||
export type Context =
|
||||
| {
|
||||
userId: string;
|
||||
allowedSpaceIds?: number[];
|
||||
}
|
||||
| undefined;
|
||||
|
||||
|
|
|
|||
28
surfsense_web/zero/queries/authz.ts
Normal file
28
surfsense_web/zero/queries/authz.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import type { Context } from "@/types/zero";
|
||||
|
||||
type SpaceScopedQuery = {
|
||||
where: (...args: unknown[]) => SpaceScopedQuery;
|
||||
};
|
||||
|
||||
const DENIED_SPACE_ID = -1;
|
||||
|
||||
export function canReadSpace(ctx: Context, searchSpaceId: number): boolean {
|
||||
return !!ctx?.allowedSpaceIds?.includes(searchSpaceId);
|
||||
}
|
||||
|
||||
export function denySpace<T extends SpaceScopedQuery>(query: T): T {
|
||||
return query.where("searchSpaceId", DENIED_SPACE_ID) as T;
|
||||
}
|
||||
|
||||
export function constrainToAllowedSpaces<T extends SpaceScopedQuery>(query: T, ctx: Context): T {
|
||||
const allowedSpaceIds = ctx?.allowedSpaceIds ?? [];
|
||||
if (allowedSpaceIds.length === 0) {
|
||||
return denySpace(query);
|
||||
}
|
||||
if (allowedSpaceIds.length === 1) {
|
||||
return query.where("searchSpaceId", allowedSpaceIds[0]) as T;
|
||||
}
|
||||
return query.where(({ cmp, or }: { cmp: (column: string, value: number) => unknown; or: (...args: unknown[]) => unknown }) =>
|
||||
or(...allowedSpaceIds.map((id) => cmp("searchSpaceId", id)))
|
||||
) as T;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue