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:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-11-11 22:18:47 +01:00
1 parent 1fe61142f4
commit a13ac85f7c
14 files changed
+103 -28

No files matched your search

+3 -1
View File
@@ -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
# <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=
+7
View File
@@ -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`.
+7 -2
View File
@@ -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
`<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
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:
+1 -1
View File
@@ -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
+10 -5
View File
@@ -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<"/">) {
<WorkerIndicator initial={worker} />
<UserMenu
user={{ name: session.user.name ?? null, email: session.user.email ?? null, image: session.user.image ?? null }}
signOutAction={async () => {
signOutAction={
authEnabled()
? async () => {
"use server";
await signOut({ redirectTo: "/login" });
}}
}
: undefined
}
/>
</div>
</div>
+2 -2
View File
@@ -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 (
<div className="flex flex-col gap-4">
+3 -2
View File
@@ -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;
+17 -2
View File
@@ -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<Session | null> {
if (!authEnabled()) return NO_LOGIN_SESSION;
const session = await auth();
return session?.user ? session : null;
}
+13 -2
View File
@@ -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 [signingOut, startSignOut] = useTransition();
@@ -49,6 +52,7 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio
<UserAvatar user={user} />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-64">
{signOutAction ? (
<div className="flex items-center gap-3 px-1.5 py-2">
<UserAvatar user={user} size="lg" />
<div className="flex min-w-0 flex-col">
@@ -56,6 +60,9 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio
{user.email && <span className="truncate text-xs text-muted-foreground">{user.email}</span>}
</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 />
<DropdownMenuGroup>
<DropdownMenuLabel>Settings</DropdownMenuLabel>
@@ -94,11 +101,15 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio
</DropdownMenuRadioItem>
</DropdownMenuRadioGroup>
</DropdownMenuGroup>
{signOutAction && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" disabled={signingOut} onClick={() => startSignOut(() => signOutAction())}>
<LogOutIcon />
{signingOut ? "Signing out…" : "Sign out"}
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
);
+4 -4
View File
@@ -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<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>) {
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 });
};
}
+1 -1
View File
@@ -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
* 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>) {
const need = scopes == null ? [] : Array.isArray(scopes) ? scopes : [scopes];
+30 -4
View File
@@ -55,7 +55,17 @@ export type CoreEnv = z.infer<typeof coreSchema>;
export type AuthEnv = z.infer<typeof authSchema>;
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> {
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;
}
+1 -1
View File
@@ -1,3 +1,3 @@
import "server-only";
export { coreEnv, authEnv } from "@/lib/env";
export { coreEnv, authEnv, authEnabled } from "@/lib/env";
+4 -1
View File
@@ -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<Response | undefined>;
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);
}