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
|
// (e.g. http://localhost:8929) does NOT resolve from inside the frontend
|
||||||
// container and would make every authenticated Zero query fail with a 503.
|
// container and would make every authenticated Zero query fail with a 503.
|
||||||
const backendURL = SERVER_BACKEND_URL.replace(/\/$/, "");
|
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(
|
async function authenticateRequest(
|
||||||
request: Request
|
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");
|
const authHeader = request.headers.get("Authorization");
|
||||||
if (!authHeader?.startsWith("Bearer ")) {
|
const cookieHeader = request.headers.get("Cookie");
|
||||||
return { ctx: undefined };
|
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 {
|
try {
|
||||||
const res = await fetch(`${backendURL}/users/me`, {
|
const res = await fetch(`${backendURL}/zero/context`, {
|
||||||
headers: { Authorization: authHeader },
|
headers,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
return { error: NextResponse.json({ error: "Unauthorized" }, { status: 401 }) };
|
return { error: NextResponse.json({ error: "Unauthorized" }, { status: 401 }) };
|
||||||
}
|
}
|
||||||
|
|
||||||
const user = await res.json();
|
const ctx = (await res.json()) as Exclude<Context, undefined>;
|
||||||
return { ctx: { userId: String(user.id) } };
|
return { ctx };
|
||||||
} catch {
|
} catch {
|
||||||
return { error: NextResponse.json({ error: "Auth service unavailable" }, { status: 503 }) };
|
return { error: NextResponse.json({ error: "Auth service unavailable" }, { status: 503 }) };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
|
const forbidden = validateZeroCacheRequest(request);
|
||||||
|
if (forbidden) {
|
||||||
|
return forbidden;
|
||||||
|
}
|
||||||
|
|
||||||
const auth = await authenticateRequest(request);
|
const auth = await authenticateRequest(request);
|
||||||
if (auth.error) {
|
if (auth.error) {
|
||||||
return auth.error;
|
return auth.error;
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await handleQueryRequest(
|
const result = await handleQueryRequest({
|
||||||
(name, args) => {
|
handler: (name, args) => {
|
||||||
const query = mustGetQuery(queries, name);
|
const query = mustGetQuery(queries, name);
|
||||||
return query.fn({ args, ctx: auth.ctx });
|
return query.fn({ args, ctx: auth.ctx });
|
||||||
},
|
},
|
||||||
schema,
|
schema,
|
||||||
request
|
request,
|
||||||
);
|
userID: auth.ctx.userId,
|
||||||
|
});
|
||||||
|
|
||||||
return NextResponse.json(result);
|
return NextResponse.json(result);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -6,9 +6,16 @@ import {
|
||||||
ZeroProvider as ZeroReactProvider,
|
ZeroProvider as ZeroReactProvider,
|
||||||
} from "@rocicorp/zero/react";
|
} from "@rocicorp/zero/react";
|
||||||
import { useAtomValue } from "jotai";
|
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 { 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 { queries } from "@/zero/queries";
|
||||||
import { schema } from "@/zero/schema";
|
import { schema } from "@/zero/schema";
|
||||||
|
|
||||||
|
|
@ -22,48 +29,74 @@ function getCacheURL() {
|
||||||
return "http://localhost:4848";
|
return "http://localhost:4848";
|
||||||
}
|
}
|
||||||
|
|
||||||
function ZeroAuthSync() {
|
function ZeroAuthSync({ isDesktop }: { isDesktop: boolean }) {
|
||||||
const zero = useZero();
|
const zero = useZero();
|
||||||
const connectionState = useConnectionState();
|
const connectionState = useConnectionState();
|
||||||
const isRefreshingRef = useRef(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
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()
|
if (isDesktop) {
|
||||||
.then((newToken) => {
|
zero.connection.connect({ auth: newToken });
|
||||||
if (newToken) {
|
} else {
|
||||||
zero.connection.connect({ auth: newToken });
|
zero.connection.connect();
|
||||||
} else {
|
}
|
||||||
handleUnauthorized();
|
});
|
||||||
}
|
}, [connectionState.name, isDesktop, zero]);
|
||||||
})
|
|
||||||
.finally(() => {
|
useEffect(() => {
|
||||||
isRefreshingRef.current = false;
|
if (typeof window === "undefined" || !window.electronAPI?.onAuthChanged) return;
|
||||||
});
|
return window.electronAPI.onAuthChanged(({ accessToken }) => {
|
||||||
}, [connectionState, zero]);
|
if (accessToken) {
|
||||||
|
zero.connection.connect({ auth: accessToken });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}, [zero]);
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ZeroProvider({ children }: { children: React.ReactNode }) {
|
function AuthenticatedZeroProvider({
|
||||||
const { data: user } = useAtomValue(currentUserAtom);
|
children,
|
||||||
const cacheURL = useMemo(() => getCacheURL(), []);
|
isDesktop,
|
||||||
|
}: {
|
||||||
|
children: React.ReactNode;
|
||||||
|
isDesktop: boolean;
|
||||||
|
}) {
|
||||||
|
const { data: user, isLoading } = useAtomValue(currentUserAtom);
|
||||||
|
|
||||||
const userId = user?.id;
|
const userId = user?.id;
|
||||||
const hasUser = !!userId;
|
const userID = userId ? String(userId) : undefined;
|
||||||
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 context = useMemo(
|
if (isLoading || !userID) {
|
||||||
() => (hasUser ? { userId: String(userId) } : undefined),
|
return <>{children}</>;
|
||||||
[hasUser, userId]
|
}
|
||||||
|
|
||||||
|
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(
|
const opts = useMemo(
|
||||||
() => ({
|
() => ({
|
||||||
|
|
@ -79,8 +112,37 @@ export function ZeroProvider({ children }: { children: React.ReactNode }) {
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ZeroReactProvider {...opts}>
|
<ZeroReactProvider {...opts}>
|
||||||
{hasUser && <ZeroAuthSync />}
|
<ZeroAuthSync isDesktop={isDesktop} />
|
||||||
{children}
|
{children}
|
||||||
</ZeroReactProvider>
|
</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 =
|
export type Context =
|
||||||
| {
|
| {
|
||||||
userId: string;
|
userId: string;
|
||||||
|
allowedSpaceIds?: number[];
|
||||||
}
|
}
|
||||||
| undefined;
|
| 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