Run without login when OIDC isn't configured
With OIDC_ISSUER, OIDC_CLIENT_ID and OIDC_CLIENT_SECRET empty (or at the .env.example placeholders) Kaname needs no login. With all three set, OIDC works as before; only some set is an error. /api/v1 still requires tokens. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1fe61142f4
commit
a13ac85f7c
14 files changed
+116
-41
No files matched your search
+3
-1
@@ -6,7 +6,9 @@ HF_TOKEN=
|
|||||||
MAX_CONCURRENT_DOWNLOADS=1
|
MAX_CONCURRENT_DOWNLOADS=1
|
||||||
UPDATE_CHECK_INTERVAL_HOURS=12
|
UPDATE_CHECK_INTERVAL_HOURS=12
|
||||||
|
|
||||||
# Login. AUTH_URL is the address you open Kaname at; register
|
# Login (optional). Leave OIDC_* empty (or at these placeholders) to run without any login:
|
||||||
|
# then anyone who can reach Kaname can use it. To require an OIDC login, set all three.
|
||||||
|
# AUTH_URL is the address you open Kaname at; register
|
||||||
# <AUTH_URL>/api/auth/callback/pocket-id as redirect URI with your OIDC provider.
|
# <AUTH_URL>/api/auth/callback/pocket-id as redirect URI with your OIDC provider.
|
||||||
# AUTH_SECRET: any random string (openssl rand -base64 32); empty = generated on first start.
|
# AUTH_SECRET: any random string (openssl rand -base64 32); empty = generated on first start.
|
||||||
AUTH_SECRET=
|
AUTH_SECRET=
|
||||||
|
|||||||
@@ -11,6 +11,13 @@ written straight into `compose.yaml` (`./data`, `./models`, `3000`). `KANAME_DAT
|
|||||||
`KANAME_MODELS_DIR`, `WEB_PORT` and `KANAME_IMAGE` are gone; if you set them, put those values into
|
`KANAME_MODELS_DIR`, `WEB_PORT` and `KANAME_IMAGE` are gone; if you set them, put those values into
|
||||||
`compose.yaml` instead. `KANAME_VERSION`, `PUID` and `PGID` still work.
|
`compose.yaml` instead. `KANAME_VERSION`, `PUID` and `PGID` still work.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Running without login:** leave `OIDC_ISSUER`, `OIDC_CLIENT_ID` and `OIDC_CLIENT_SECRET` empty
|
||||||
|
(or at the `.env.example` placeholders) and Kaname needs no login; anyone who can reach it can use
|
||||||
|
it. With all three set, OIDC login works as before. Only some of them set is an error on start.
|
||||||
|
`/api/v1` still requires API tokens either way.
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|
||||||
- Simpler `deploy/compose.yaml` (no YAML anchors or variables) and a short `.env.example`.
|
- Simpler `deploy/compose.yaml` (no YAML anchors or variables) and a short `.env.example`.
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ their speed and answer quality with [BetterBench](https://github.com/GGZ14/Bette
|
|||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|
||||||
You need a Linux server with Docker and Compose, and an OIDC provider for the login (e.g.
|
You need a Linux server with Docker and Compose, and optionally an OIDC provider for the login (e.g.
|
||||||
[Pocket ID](https://pocket-id.org), Authelia, Authentik, Keycloak).
|
[Pocket ID](https://pocket-id.org), Authelia, Authentik, Keycloak).
|
||||||
|
|
||||||
**1. Create a folder with two files**
|
**1. Create a folder with two files**
|
||||||
@@ -129,11 +129,16 @@ curl -fsSLo compose.yaml https://git.linxweiler.xyz/pascallinxweiler/Kaname/raw/
|
|||||||
curl -fsSLo .env https://git.linxweiler.xyz/pascallinxweiler/Kaname/raw/branch/main/.env.example
|
curl -fsSLo .env https://git.linxweiler.xyz/pascallinxweiler/Kaname/raw/branch/main/.env.example
|
||||||
```
|
```
|
||||||
|
|
||||||
**2. Create an OIDC client** in your identity provider with the redirect URI
|
**2. Create an OIDC client** (optional) in your identity provider with the redirect URI
|
||||||
`<AUTH_URL>/api/auth/callback/pocket-id`, e.g. `http://192.168.1.10:3000/api/auth/callback/pocket-id`
|
`<AUTH_URL>/api/auth/callback/pocket-id`, e.g. `http://192.168.1.10:3000/api/auth/callback/pocket-id`
|
||||||
(the path says `pocket-id` whatever provider you use). Request the `groups` scope if you want to
|
(the path says `pocket-id` whatever provider you use). Request the `groups` scope if you want to
|
||||||
restrict access by group.
|
restrict access by group.
|
||||||
|
|
||||||
|
Without OIDC, skip this step and leave the `OIDC_*` lines empty: Kaname then runs without any
|
||||||
|
login, and anyone who can reach it can use it. Only do that on a trusted network (or behind a proxy
|
||||||
|
that does the login). Setting only some of the `OIDC_*` values is an error, so a typo never turns
|
||||||
|
the login off.
|
||||||
|
|
||||||
**3. Fill in `.env`:** `AUTH_URL` (the address you open in the browser), `OIDC_ISSUER`,
|
**3. Fill in `.env`:** `AUTH_URL` (the address you open in the browser), `OIDC_ISSUER`,
|
||||||
`OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`, and ideally a read-only `HF_TOKEN`. Everything else can
|
`OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`, and ideally a read-only `HF_TOKEN`. Everything else can
|
||||||
stay as it is. A filled-in example:
|
stay as it is. A filled-in example:
|
||||||
|
|||||||
+1
-1
@@ -5,7 +5,7 @@ downloads and follow them, verify and repair models, and tag them. Everything a
|
|||||||
bounded by [guardrails](#guardrails). No token can delete models or files, update a model to
|
bounded by [guardrails](#guardrails). No token can delete models or files, update a model to
|
||||||
another commit, change settings, manage tokens, or touch jobs it didn't request.
|
another commit, change settings, manage tokens, or touch jobs it didn't request.
|
||||||
|
|
||||||
The rest of Kaname (the web UI and its internal `/api/*` routes) stays behind your OIDC login. Only
|
The rest of Kaname (the web UI and its internal `/api/*` routes) stays behind your OIDC login (or is open, if you run Kaname without login). Only
|
||||||
`/api/v1` accepts tokens, and it accepts *only* tokens: a browser session doesn't work there.
|
`/api/v1` accepts tokens, and it accepts *only* tokens: a browser session doesn't work there.
|
||||||
|
|
||||||
For agents there's a ready-made skill: [docs/agent/SKILL.md](agent/SKILL.md). Give it to the agent
|
For agents there's a ready-made skill: [docs/agent/SKILL.md](agent/SKILL.md). Give it to the agent
|
||||||
|
|||||||
@@ -1,18 +1,19 @@
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { auth, signOut } from "@/auth";
|
import { currentSession, signOut } from "@/auth";
|
||||||
import { AppNav } from "@/components/app-nav";
|
import { AppNav } from "@/components/app-nav";
|
||||||
import { CommandPalette, CommandPaletteButton } from "@/components/command-palette";
|
import { CommandPalette, CommandPaletteButton } from "@/components/command-palette";
|
||||||
import { BackdropProvider } from "@/components/hero/dot-painting";
|
import { BackdropProvider } from "@/components/hero/dot-painting";
|
||||||
import { LabelSettingsProvider } from "@/components/labels";
|
import { LabelSettingsProvider } from "@/components/labels";
|
||||||
import { UserMenu } from "@/components/user-menu";
|
import { UserMenu } from "@/components/user-menu";
|
||||||
import { WorkerIndicator } from "@/components/worker-indicator";
|
import { WorkerIndicator } from "@/components/worker-indicator";
|
||||||
|
import { authEnabled } from "@/lib/server-env";
|
||||||
import { getBackdrop, getFileRoleStyles, getRecommendedRoles } from "@/lib/settings";
|
import { getBackdrop, getFileRoleStyles, getRecommendedRoles } from "@/lib/settings";
|
||||||
import { getWorkerStatus } from "@/lib/worker-status";
|
import { getWorkerStatus } from "@/lib/worker-status";
|
||||||
|
|
||||||
export default async function AppLayout({ children }: LayoutProps<"/">) {
|
export default async function AppLayout({ children }: LayoutProps<"/">) {
|
||||||
const session = await auth();
|
const session = await currentSession();
|
||||||
if (!session?.user) redirect("/login");
|
if (!session) redirect("/login");
|
||||||
|
|
||||||
const [worker, fileRoles, recommendedRoles, backdrop] = await Promise.all([
|
const [worker, fileRoles, recommendedRoles, backdrop] = await Promise.all([
|
||||||
getWorkerStatus(),
|
getWorkerStatus(),
|
||||||
@@ -38,10 +39,14 @@ export default async function AppLayout({ children }: LayoutProps<"/">) {
|
|||||||
<WorkerIndicator initial={worker} />
|
<WorkerIndicator initial={worker} />
|
||||||
<UserMenu
|
<UserMenu
|
||||||
user={{ name: session.user.name ?? null, email: session.user.email ?? null, image: session.user.image ?? null }}
|
user={{ name: session.user.name ?? null, email: session.user.email ?? null, image: session.user.image ?? null }}
|
||||||
signOutAction={async () => {
|
signOutAction={
|
||||||
"use server";
|
authEnabled()
|
||||||
await signOut({ redirectTo: "/login" });
|
? async () => {
|
||||||
}}
|
"use server";
|
||||||
|
await signOut({ redirectTo: "/login" });
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { auth } from "@/auth";
|
import { currentSession } from "@/auth";
|
||||||
import { listLibrary } from "@/lib/library";
|
import { listLibrary } from "@/lib/library";
|
||||||
import { listLocalFolders } from "@/lib/local-folders";
|
import { listLocalFolders } from "@/lib/local-folders";
|
||||||
import { getWorkerStatus } from "@/lib/worker-status";
|
import { getWorkerStatus } from "@/lib/worker-status";
|
||||||
@@ -8,7 +8,7 @@ import { LibraryView } from "./library-view";
|
|||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
export default async function LibraryPage({ searchParams }: PageProps<"/">) {
|
export default async function LibraryPage({ searchParams }: PageProps<"/">) {
|
||||||
const [rows, worker, folders, session] = await Promise.all([listLibrary(), getWorkerStatus(), listLocalFolders(), auth()]);
|
const [rows, worker, folders, session] = await Promise.all([listLibrary(), getWorkerStatus(), listLocalFolders(), currentSession()]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-4">
|
<div className="flex flex-col gap-4">
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { auth, OIDC_PROVIDER_ID, signIn } from "@/auth";
|
import { currentSession, OIDC_PROVIDER_ID, signIn } from "@/auth";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
|
||||||
@@ -19,7 +19,8 @@ export default async function LoginPage({ searchParams }: PageProps<"/login">) {
|
|||||||
const params = await searchParams;
|
const params = await searchParams;
|
||||||
const callbackUrl = safeCallback(params.callbackUrl);
|
const callbackUrl = safeCallback(params.callbackUrl);
|
||||||
|
|
||||||
if ((await auth())?.user) redirect(callbackUrl);
|
// Also covers login off: currentSession() is never null then.
|
||||||
|
if (await currentSession()) redirect(callbackUrl);
|
||||||
|
|
||||||
const errorKey = typeof params.error === "string" ? params.error : undefined;
|
const errorKey = typeof params.error === "string" ? params.error : undefined;
|
||||||
const error = errorKey ? (ERRORS[errorKey] ?? "Login failed. Please try again.") : undefined;
|
const error = errorKey ? (ERRORS[errorKey] ?? "Login failed. Please try again.") : undefined;
|
||||||
|
|||||||
+17
-2
@@ -1,5 +1,5 @@
|
|||||||
import NextAuth, { type NextAuthConfig } from "next-auth";
|
import NextAuth, { type NextAuthConfig, type Session } from "next-auth";
|
||||||
import { authEnv } from "@/lib/server-env";
|
import { authEnabled, authEnv } from "@/lib/server-env";
|
||||||
|
|
||||||
declare module "next-auth" {
|
declare module "next-auth" {
|
||||||
interface Session {
|
interface Session {
|
||||||
@@ -24,6 +24,8 @@ function groupsFromProfile(profile: unknown): string[] {
|
|||||||
// Config is built lazily (per request) so `next build` doesn't need OIDC env vars.
|
// Config is built lazily (per request) so `next build` doesn't need OIDC env vars.
|
||||||
export const { handlers, auth, signIn, signOut } = NextAuth((): NextAuthConfig => {
|
export const { handlers, auth, signIn, signOut } = NextAuth((): NextAuthConfig => {
|
||||||
const env = authEnv();
|
const env = authEnv();
|
||||||
|
// Login off: no provider. Nothing calls signIn then (see currentSession, proxy.ts, /login).
|
||||||
|
if (!env) return { trustHost: true, session: { strategy: "jwt" }, providers: [] };
|
||||||
const restrictGroups = env.OIDC_ALLOWED_GROUPS.length > 0;
|
const restrictGroups = env.OIDC_ALLOWED_GROUPS.length > 0;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -62,3 +64,16 @@ export const { handlers, auth, signIn, signOut } = NextAuth((): NextAuthConfig =
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/** Stand-in user while login is off (no OIDC_* configured). */
|
||||||
|
const NO_LOGIN_SESSION: Session = { user: { name: null, email: null, image: null, groups: [] }, expires: "" };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The signed-in user's session, or null. With login off (see authEnabled), everyone counts as
|
||||||
|
* signed in. Use this instead of auth() everywhere outside proxy.ts.
|
||||||
|
*/
|
||||||
|
export async function currentSession(): Promise<Session | null> {
|
||||||
|
if (!authEnabled()) return NO_LOGIN_SESSION;
|
||||||
|
const session = await auth();
|
||||||
|
return session?.user ? session : null;
|
||||||
|
}
|
||||||
@@ -34,8 +34,11 @@ function UserAvatar({ user, size }: { user: MenuUser; size?: "sm" | "default" |
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Avatar from the OIDC profile; opens a menu with account info, settings, theme and sign out. */
|
/**
|
||||||
export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutAction: () => Promise<void> }) {
|
* Avatar from the OIDC profile; opens a menu with account info, settings, theme and sign out.
|
||||||
|
* Without signOutAction (login off) there's no account to show or sign out of.
|
||||||
|
*/
|
||||||
|
export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutAction?: () => Promise<void> }) {
|
||||||
const { theme, setTheme } = useTheme();
|
const { theme, setTheme } = useTheme();
|
||||||
const [signingOut, startSignOut] = useTransition();
|
const [signingOut, startSignOut] = useTransition();
|
||||||
|
|
||||||
@@ -49,13 +52,17 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio
|
|||||||
<UserAvatar user={user} />
|
<UserAvatar user={user} />
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end" className="w-64">
|
<DropdownMenuContent align="end" className="w-64">
|
||||||
<div className="flex items-center gap-3 px-1.5 py-2">
|
{signOutAction ? (
|
||||||
<UserAvatar user={user} size="lg" />
|
<div className="flex items-center gap-3 px-1.5 py-2">
|
||||||
<div className="flex min-w-0 flex-col">
|
<UserAvatar user={user} size="lg" />
|
||||||
<span className="truncate text-sm font-medium">{user.name ?? "Signed in"}</span>
|
<div className="flex min-w-0 flex-col">
|
||||||
{user.email && <span className="truncate text-xs text-muted-foreground">{user.email}</span>}
|
<span className="truncate text-sm font-medium">{user.name ?? "Signed in"}</span>
|
||||||
|
{user.email && <span className="truncate text-xs text-muted-foreground">{user.email}</span>}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
) : (
|
||||||
|
<p className="px-1.5 py-2 text-xs text-muted-foreground">Login is off: anyone who can reach Kaname can use it.</p>
|
||||||
|
)}
|
||||||
<DropdownMenuSeparator />
|
<DropdownMenuSeparator />
|
||||||
<DropdownMenuGroup>
|
<DropdownMenuGroup>
|
||||||
<DropdownMenuLabel>Settings</DropdownMenuLabel>
|
<DropdownMenuLabel>Settings</DropdownMenuLabel>
|
||||||
@@ -94,11 +101,15 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio
|
|||||||
</DropdownMenuRadioItem>
|
</DropdownMenuRadioItem>
|
||||||
</DropdownMenuRadioGroup>
|
</DropdownMenuRadioGroup>
|
||||||
</DropdownMenuGroup>
|
</DropdownMenuGroup>
|
||||||
<DropdownMenuSeparator />
|
{signOutAction && (
|
||||||
<DropdownMenuItem variant="destructive" disabled={signingOut} onClick={() => startSignOut(() => signOutAction())}>
|
<>
|
||||||
<LogOutIcon />
|
<DropdownMenuSeparator />
|
||||||
{signingOut ? "Signing out…" : "Sign out"}
|
<DropdownMenuItem variant="destructive" disabled={signingOut} onClick={() => startSignOut(() => signOutAction())}>
|
||||||
</DropdownMenuItem>
|
<LogOutIcon />
|
||||||
|
{signingOut ? "Signing out…" : "Sign out"}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
);
|
);
|
||||||
|
|||||||
+4
-4
@@ -1,15 +1,15 @@
|
|||||||
import "server-only";
|
import "server-only";
|
||||||
import type { Session } from "next-auth";
|
import type { Session } from "next-auth";
|
||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { auth } from "@/auth";
|
import { currentSession } from "@/auth";
|
||||||
|
|
||||||
type Handler<Ctx> = (req: Request, ctx: Ctx & { session: Session }) => Promise<Response> | Response;
|
type Handler<Ctx> = (req: Request, ctx: Ctx & { session: Session }) => Promise<Response> | Response;
|
||||||
|
|
||||||
/** Wraps a route handler so it only runs for a logged-in user (defense in depth behind proxy.ts). */
|
/** Wraps a route handler so it only runs for a logged-in user (anyone while login is off) (defense in depth behind proxy.ts). */
|
||||||
export function withAuth<Ctx = unknown>(handler: Handler<Ctx>) {
|
export function withAuth<Ctx = unknown>(handler: Handler<Ctx>) {
|
||||||
return async (req: Request, ctx: Ctx) => {
|
return async (req: Request, ctx: Ctx) => {
|
||||||
const session = await auth();
|
const session = await currentSession();
|
||||||
if (!session?.user) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
|
if (!session) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
|
||||||
return handler(req, { ...ctx, session });
|
return handler(req, { ...ctx, session });
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -95,7 +95,7 @@ type Handler<Ctx> = (req: Request, ctx: Ctx & { token: TokenIdentity }) => Promi
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Wraps a /api/v1 route: requires `Authorization: Bearer <token>` with one of `scopes` (null: any
|
* Wraps a /api/v1 route: requires `Authorization: Bearer <token>` with one of `scopes` (null: any
|
||||||
* valid token). Login sessions don't count here; the rest of the app is OIDC-only.
|
* valid token). Login sessions don't count here; the rest of the app uses the OIDC login (or none).
|
||||||
*/
|
*/
|
||||||
export function withToken<Ctx = unknown>(scopes: TokenScope | TokenScope[] | null, handler: Handler<Ctx>) {
|
export function withToken<Ctx = unknown>(scopes: TokenScope | TokenScope[] | null, handler: Handler<Ctx>) {
|
||||||
const need = scopes == null ? [] : Array.isArray(scopes) ? scopes : [scopes];
|
const need = scopes == null ? [] : Array.isArray(scopes) ? scopes : [scopes];
|
||||||
|
|||||||
+30
-4
@@ -55,7 +55,17 @@ export type CoreEnv = z.infer<typeof coreSchema>;
|
|||||||
export type AuthEnv = z.infer<typeof authSchema>;
|
export type AuthEnv = z.infer<typeof authSchema>;
|
||||||
|
|
||||||
let core: CoreEnv | undefined;
|
let core: CoreEnv | undefined;
|
||||||
let auth: AuthEnv | undefined;
|
let auth: AuthEnv | null | undefined;
|
||||||
|
|
||||||
|
/** The placeholder issuer from .env.example: counts as "not set". */
|
||||||
|
const EXAMPLE_ISSUER = "https://auth.example.com";
|
||||||
|
const OIDC_KEYS = ["OIDC_ISSUER", "OIDC_CLIENT_ID", "OIDC_CLIENT_SECRET"] as const;
|
||||||
|
|
||||||
|
function oidcValue(key: (typeof OIDC_KEYS)[number]): string | undefined {
|
||||||
|
const v = process.env[key]?.trim();
|
||||||
|
if (!v || (key === "OIDC_ISSUER" && v.replace(/\/+$/, "") === EXAMPLE_ISSUER)) return undefined;
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
function parse<T extends z.ZodType>(schema: T, name: string): z.infer<T> {
|
function parse<T extends z.ZodType>(schema: T, name: string): z.infer<T> {
|
||||||
const result = schema.safeParse(process.env);
|
const result = schema.safeParse(process.env);
|
||||||
@@ -71,7 +81,23 @@ export function coreEnv(): CoreEnv {
|
|||||||
return (core ??= parse(coreSchema, "core"));
|
return (core ??= parse(coreSchema, "core"));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** OIDC config, only needed by the web app. */
|
/**
|
||||||
export function authEnv(): AuthEnv {
|
* OIDC config, only needed by the web app. null: login is off (no OIDC_* set, or only the
|
||||||
return (auth ??= parse(authSchema, "auth"));
|
* .env.example placeholders), and everyone who can reach Kaname uses it without signing in.
|
||||||
|
* Partly set throws instead of silently running without login.
|
||||||
|
*/
|
||||||
|
export function authEnv(): AuthEnv | null {
|
||||||
|
if (auth !== undefined) return auth;
|
||||||
|
const set = OIDC_KEYS.filter((k) => oidcValue(k) !== undefined);
|
||||||
|
if (set.length === 0) return (auth = null);
|
||||||
|
if (set.length < OIDC_KEYS.length) {
|
||||||
|
const missing = OIDC_KEYS.filter((k) => !set.includes(k)).join(", ");
|
||||||
|
throw new Error(`Invalid auth environment: ${set.join(", ")} set but ${missing} missing. Set all three for OIDC login, or none to run without login.`);
|
||||||
|
}
|
||||||
|
return (auth = parse(authSchema, "auth"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether the web UI requires an OIDC login (see authEnv). */
|
||||||
|
export function authEnabled(): boolean {
|
||||||
|
return authEnv() !== null;
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
import "server-only";
|
import "server-only";
|
||||||
|
|
||||||
export { coreEnv, authEnv } from "@/lib/env";
|
export { coreEnv, authEnv, authEnabled } from "@/lib/env";
|
||||||
+4
-1
@@ -1,7 +1,8 @@
|
|||||||
import { type NextFetchEvent, type NextRequest, NextResponse } from "next/server";
|
import { type NextFetchEvent, type NextRequest, NextResponse } from "next/server";
|
||||||
import { auth } from "@/auth";
|
import { auth } from "@/auth";
|
||||||
|
import { authEnabled } from "@/lib/server-env";
|
||||||
|
|
||||||
// Gate every page and API route. Unauthenticated page requests go to /login,
|
// Gate every page and API route (only while OIDC login is configured). Unauthenticated page requests go to /login,
|
||||||
// API requests get a 401. Route handlers check the session again (see lib/api-auth.ts).
|
// API requests get a 401. Route handlers check the session again (see lib/api-auth.ts).
|
||||||
const gate = auth((req) => {
|
const gate = auth((req) => {
|
||||||
if (req.auth) return;
|
if (req.auth) return;
|
||||||
@@ -21,6 +22,8 @@ const gate = auth((req) => {
|
|||||||
type ProxyHandler = (req: NextRequest, event: NextFetchEvent) => Promise<Response | undefined>;
|
type ProxyHandler = (req: NextRequest, event: NextFetchEvent) => Promise<Response | undefined>;
|
||||||
|
|
||||||
export async function proxy(req: NextRequest, event: NextFetchEvent) {
|
export async function proxy(req: NextRequest, event: NextFetchEvent) {
|
||||||
|
// Login off (no OIDC_* configured): nothing to gate.
|
||||||
|
if (!authEnabled()) return;
|
||||||
const handler = (await gate) as unknown as ProxyHandler;
|
const handler = (await gate) as unknown as ProxyHandler;
|
||||||
return handler(req, event);
|
return handler(req, event);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user