diff --git a/.env.example b/.env.example index 90f5c6f..24b3c99 100644 --- a/.env.example +++ b/.env.example @@ -6,7 +6,9 @@ HF_TOKEN= MAX_CONCURRENT_DOWNLOADS=1 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 # /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= diff --git a/CHANGELOG.md b/CHANGELOG.md index 8fa15f4..59908c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 `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 - Simpler `deploy/compose.yaml` (no YAML anchors or variables) and a short `.env.example`. diff --git a/README.md b/README.md index a55864b..cdab8bd 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ their speed and answer quality with [BetterBench](https://github.com/GGZ14/Bette ## 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). **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 ``` -**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 `/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 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`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`, and ideally a read-only `HF_TOKEN`. Everything else can stay as it is. A filled-in example: diff --git a/docs/api.md b/docs/api.md index f093698..65c9bc4 100644 --- a/docs/api.md +++ b/docs/api.md @@ -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 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. For agents there's a ready-made skill: [docs/agent/SKILL.md](agent/SKILL.md). Give it to the agent diff --git a/src/app/(app)/layout.tsx b/src/app/(app)/layout.tsx index fc1dafd..43b9056 100644 --- a/src/app/(app)/layout.tsx +++ b/src/app/(app)/layout.tsx @@ -1,18 +1,19 @@ import Link from "next/link"; import { redirect } from "next/navigation"; -import { auth, signOut } from "@/auth"; +import { currentSession, signOut } from "@/auth"; import { AppNav } from "@/components/app-nav"; import { CommandPalette, CommandPaletteButton } from "@/components/command-palette"; import { BackdropProvider } from "@/components/hero/dot-painting"; import { LabelSettingsProvider } from "@/components/labels"; import { UserMenu } from "@/components/user-menu"; import { WorkerIndicator } from "@/components/worker-indicator"; +import { authEnabled } from "@/lib/server-env"; import { getBackdrop, getFileRoleStyles, getRecommendedRoles } from "@/lib/settings"; import { getWorkerStatus } from "@/lib/worker-status"; export default async function AppLayout({ children }: LayoutProps<"/">) { - const session = await auth(); - if (!session?.user) redirect("/login"); + const session = await currentSession(); + if (!session) redirect("/login"); const [worker, fileRoles, recommendedRoles, backdrop] = await Promise.all([ getWorkerStatus(), @@ -38,10 +39,14 @@ export default async function AppLayout({ children }: LayoutProps<"/">) { { - "use server"; - await signOut({ redirectTo: "/login" }); - }} + signOutAction={ + authEnabled() + ? async () => { + "use server"; + await signOut({ redirectTo: "/login" }); + } + : undefined + } /> diff --git a/src/app/(app)/page.tsx b/src/app/(app)/page.tsx index ea7cd90..e19d38b 100644 --- a/src/app/(app)/page.tsx +++ b/src/app/(app)/page.tsx @@ -1,4 +1,4 @@ -import { auth } from "@/auth"; +import { currentSession } from "@/auth"; import { listLibrary } from "@/lib/library"; import { listLocalFolders } from "@/lib/local-folders"; import { getWorkerStatus } from "@/lib/worker-status"; @@ -8,7 +8,7 @@ import { LibraryView } from "./library-view"; export const dynamic = "force-dynamic"; 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 (
diff --git a/src/app/login/page.tsx b/src/app/login/page.tsx index 6b0fdf1..82ea14c 100644 --- a/src/app/login/page.tsx +++ b/src/app/login/page.tsx @@ -1,5 +1,5 @@ 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 { 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 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 error = errorKey ? (ERRORS[errorKey] ?? "Login failed. Please try again.") : undefined; diff --git a/src/auth.ts b/src/auth.ts index 665f62d..ffa2574 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -1,5 +1,5 @@ -import NextAuth, { type NextAuthConfig } from "next-auth"; -import { authEnv } from "@/lib/server-env"; +import NextAuth, { type NextAuthConfig, type Session } from "next-auth"; +import { authEnabled, authEnv } from "@/lib/server-env"; declare module "next-auth" { 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. export const { handlers, auth, signIn, signOut } = NextAuth((): NextAuthConfig => { 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; 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 { + if (!authEnabled()) return NO_LOGIN_SESSION; + const session = await auth(); + return session?.user ? session : null; +} diff --git a/src/components/user-menu.tsx b/src/components/user-menu.tsx index 04a5215..c5e9f3f 100644 --- a/src/components/user-menu.tsx +++ b/src/components/user-menu.tsx @@ -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 }) { +/** + * 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 }) { const { theme, setTheme } = useTheme(); const [signingOut, startSignOut] = useTransition(); @@ -49,13 +52,17 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio -
- -
- {user.name ?? "Signed in"} - {user.email && {user.email}} + {signOutAction ? ( +
+ +
+ {user.name ?? "Signed in"} + {user.email && {user.email}} +
-
+ ) : ( +

Login is off: anyone who can reach Kaname can use it.

+ )} Settings @@ -94,11 +101,15 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio - - startSignOut(() => signOutAction())}> - - {signingOut ? "Signing out…" : "Sign out"} - + {signOutAction && ( + <> + + startSignOut(() => signOutAction())}> + + {signingOut ? "Signing out…" : "Sign out"} + + + )} ); diff --git a/src/lib/api-auth.ts b/src/lib/api-auth.ts index 97e2259..6ef3f90 100644 --- a/src/lib/api-auth.ts +++ b/src/lib/api-auth.ts @@ -1,15 +1,15 @@ import "server-only"; import type { Session } from "next-auth"; import { NextResponse } from "next/server"; -import { auth } from "@/auth"; +import { currentSession } from "@/auth"; type Handler = (req: Request, ctx: Ctx & { session: Session }) => Promise | 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(handler: Handler) { return async (req: Request, ctx: Ctx) => { - const session = await auth(); - if (!session?.user) return NextResponse.json({ error: "unauthorized" }, { status: 401 }); + const session = await currentSession(); + if (!session) return NextResponse.json({ error: "unauthorized" }, { status: 401 }); return handler(req, { ...ctx, session }); }; } diff --git a/src/lib/api-tokens.ts b/src/lib/api-tokens.ts index 8017e32..6b8ee80 100644 --- a/src/lib/api-tokens.ts +++ b/src/lib/api-tokens.ts @@ -95,7 +95,7 @@ type Handler = (req: Request, ctx: Ctx & { token: TokenIdentity }) => Promi /** * Wraps a /api/v1 route: requires `Authorization: Bearer ` 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(scopes: TokenScope | TokenScope[] | null, handler: Handler) { const need = scopes == null ? [] : Array.isArray(scopes) ? scopes : [scopes]; diff --git a/src/lib/env.ts b/src/lib/env.ts index 05df0f5..87c9c23 100644 --- a/src/lib/env.ts +++ b/src/lib/env.ts @@ -55,7 +55,17 @@ export type CoreEnv = z.infer; export type AuthEnv = z.infer; 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(schema: T, name: string): z.infer { const result = schema.safeParse(process.env); @@ -71,7 +81,23 @@ export function coreEnv(): CoreEnv { return (core ??= parse(coreSchema, "core")); } -/** OIDC config, only needed by the web app. */ -export function authEnv(): AuthEnv { - return (auth ??= parse(authSchema, "auth")); +/** + * OIDC config, only needed by the web app. null: login is off (no OIDC_* set, or only the + * .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; } diff --git a/src/lib/server-env.ts b/src/lib/server-env.ts index c9f06b0..49151b5 100644 --- a/src/lib/server-env.ts +++ b/src/lib/server-env.ts @@ -1,3 +1,3 @@ import "server-only"; -export { coreEnv, authEnv } from "@/lib/env"; +export { coreEnv, authEnv, authEnabled } from "@/lib/env"; diff --git a/src/proxy.ts b/src/proxy.ts index d27a225..2453e09 100644 --- a/src/proxy.ts +++ b/src/proxy.ts @@ -1,7 +1,8 @@ import { type NextFetchEvent, type NextRequest, NextResponse } from "next/server"; 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). const gate = auth((req) => { if (req.auth) return; @@ -21,6 +22,8 @@ const gate = auth((req) => { type ProxyHandler = (req: NextRequest, event: NextFetchEvent) => Promise; 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; return handler(req, event); }