Compare commits

...
4 Commits
Author SHA1 Message Date
Pascal LinxweilerandClaude Opus 5.5 8447289649 Release 0.23.0: run without login
Release / release (push) Successful in 2m59s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:20:49 +01:00
Pascal LinxweilerandClaude Opus 5.5 a13ac85f7c 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>
2026-11-11 22:18:47 +01:00
Pascal LinxweilerandClaude Opus 5.5 1fe61142f4 README: show the full compose.yaml and .env in the install steps
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:16:38 +01:00
Pascal LinxweilerandClaude Opus 5.5 15d8ae155e Simplify compose files and .env.example
Folders, port and image are written straight into compose.yaml; the
KANAME_DATA_DIR, KANAME_MODELS_DIR, WEB_PORT and KANAME_IMAGE variables
are gone. .env.example is down to the settings people actually set.
README and CHANGELOG updated accordingly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:14:15 +01:00
18 changed files with 309 additions and 153 deletions

No files matched your search

+20 -56
View File
@@ -1,64 +1,28 @@
# Kaname settings. Copy to .env next to compose.yaml and fill in the "Required" part; everything # Kaname settings: copy to .env next to compose.yaml and fill in.
# else has working defaults. Full reference: https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Configuration # All options: https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Configuration
# --------------------------------------------------------------------------- # Read-only Hugging Face token (needed for gated repos, higher rate limits)
# Required HF_TOKEN=
# --------------------------------------------------------------------------- MAX_CONCURRENT_DOWNLOADS=1
UPDATE_CHECK_INTERVAL_HOURS=12
# The address you open Kaname at in the browser (no trailing slash). The OIDC redirect URI to # Login (optional). Leave OIDC_* empty (or at these placeholders) to run without any login:
# register with your provider is <AUTH_URL>/api/auth/callback/pocket-id # 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=
AUTH_URL=http://localhost:3000 AUTH_URL=http://localhost:3000
# OIDC provider (e.g. Pocket ID): authorization code flow with PKCE
OIDC_ISSUER=https://auth.example.com OIDC_ISSUER=https://auth.example.com
OIDC_CLIENT_ID= OIDC_CLIENT_ID=
OIDC_CLIENT_SECRET= OIDC_CLIENT_SECRET=
# Optional, comma-separated: only these groups may log in
# ---------------------------------------------------------------------------
# Recommended
# ---------------------------------------------------------------------------
# Hugging Face token: read-only is enough. Needed for gated/private repos, recommended anyway
# (higher rate limits). Stays on the server; never sent to the browser or written to logs.
HF_TOKEN=
# Optional, comma-separated: only members of these groups (`groups` claim) can log in.
OIDC_ALLOWED_GROUPS= OIDC_ALLOWED_GROUPS=
# --------------------------------------------------------------------------- # Optional: pin an image version (default: latest)
# Folders, port and image (deploy/compose.yaml) # KANAME_VERSION=0.23.0
# --------------------------------------------------------------------------- # Optional: user/group Kaname runs as (default 1000); set to the owner of your models folder
# PUID=1000
# SQLite database and benchmark results. Must be on local disk, not NFS. # PGID=1000
KANAME_DATA_DIR=./data # Optional: launch80.com publish token, to publish benchmark runs
# Downloaded models. Can be a NAS share mounted on the host, e.g. /mnt/nas/models. # L80_TOKEN=
KANAME_MODELS_DIR=./models
# Host port of the web UI
WEB_PORT=3000
# The user Kaname runs as (and owns the files it writes). Set these to the owner of your models
# folder, e.g. the uid/gid of a NAS share (`ls -ln /mnt/nas/models`). New, empty folders are set up
# for this user automatically.
PUID=1000
PGID=1000
# Image tag, e.g. 0.16.0 (default: latest). KANAME_IMAGE replaces the registry/name if you build or
# mirror the image yourself.
KANAME_VERSION=
KANAME_IMAGE=
# ---------------------------------------------------------------------------
# Optional
# ---------------------------------------------------------------------------
# Random secret for session cookies. Empty: generated on first start and kept in the data folder.
AUTH_SECRET=
# launch80.com publish token (comes with the launch80 Supporter role). Lets you publish a benchmark
# run as a public launch80 page, after a preview and an explicit confirmation. Stays on the server.
L80_TOKEN=
MAX_CONCURRENT_DOWNLOADS=1
# How often the worker checks every model on the Hub (still there? newer commit?); 0 disables it
UPDATE_CHECK_INTERVAL_HOURS=12
# 1 (default): hf downloads over plain HTTP, so progress can be measured from bytes on disk.
# 0: use Xet (chunk-level dedup on updates). Files over 50 GB always use Xet.
HF_HUB_DISABLE_XET=1
+21
View File
@@ -6,6 +6,27 @@ step 1 (Hugging Face downloader) is released as a minor version.
## [Unreleased] ## [Unreleased]
## [0.23.0] - 2026-11-11
Kaname can run without any login: leave the `OIDC_*` settings empty and it opens straight into
the library.
**Upgrading:** `deploy/compose.yaml` and `.env.example` are simpler: folders, port and image are
written straight into `compose.yaml` (`./data`, `./models`, `3000`). `KANAME_DATA_DIR`,
`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`.
## [0.22.0] - 2026-11-11 ## [0.22.0] - 2026-11-11
The API for AI agents is back, for models: a token-authenticated `/api/v1` lets an agent look up The API for AI agents is back, for models: a token-authenticated `/api/v1` lets an agent look up
+121 -11
View File
@@ -25,26 +25,136 @@ 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. Get the compose file and the config template** **1. Create a folder with two files**
```bash ```bash
mkdir kaname && cd kaname mkdir kaname && cd kaname
```
`compose.yaml` (same as [`deploy/compose.yaml`](deploy/compose.yaml)):
```yaml
# Kaname: put this file and a filled-in .env (from .env.example) in one folder, then
# docker compose up -d
name: kaname
services:
web:
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
env_file: .env
ports:
- "3000:3000"
volumes:
- ./data:/data
restart: unless-stopped
worker:
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
command: worker
env_file: .env
environment:
SANDBOX_DIR: /sandbox
volumes:
- ./data:/data
- ./models:/models # where models are downloaded to, e.g. /mnt/models
- sandbox:/sandbox
restart: unless-stopped
# Runs the coding answers of the quality eval (Python written by the model under test), locked
# down: no network, no secrets, read-only. Optional: without it the eval skips the coding part.
sandbox:
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
command: sandbox
user: "65534:65534"
network_mode: none
read_only: true
tmpfs:
- /tmp:size=64m,mode=1777
cap_drop: [ALL]
security_opt: ["no-new-privileges:true"]
mem_limit: 512m
pids_limit: 64
cpus: 1
volumes:
- sandbox:/sandbox
depends_on: [worker]
restart: unless-stopped
volumes:
sandbox:
```
The database goes to `./data` and models to `./models` next to this file. To keep models somewhere
else (e.g. a NAS share mounted on the host), change the worker's `./models:/models` line, e.g. to
`/mnt/models:/models`. To use another port, change the left side of `"3000:3000"`.
`.env` (same as [`.env.example`](.env.example)):
```env
# Kaname settings: copy to .env next to compose.yaml and fill in.
# All options: https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Configuration
# Read-only Hugging Face token (needed for gated repos, higher rate limits)
HF_TOKEN=
MAX_CONCURRENT_DOWNLOADS=1
UPDATE_CHECK_INTERVAL_HOURS=12
# Login. 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=
AUTH_URL=http://localhost:3000
OIDC_ISSUER=https://auth.example.com
OIDC_CLIENT_ID=
OIDC_CLIENT_SECRET=
# Optional, comma-separated: only these groups may log in
OIDC_ALLOWED_GROUPS=
# Optional: pin an image version (default: latest)
# KANAME_VERSION=0.23.0
# Optional: user/group Kaname runs as (default 1000); set to the owner of your models folder
# PUID=1000
# PGID=1000
# Optional: launch80.com publish token, to publish benchmark runs
# L80_TOKEN=
```
Or download both instead of copying:
```bash
curl -fsSLo compose.yaml https://git.linxweiler.xyz/pascallinxweiler/Kaname/raw/branch/main/deploy/compose.yaml curl -fsSLo compose.yaml https://git.linxweiler.xyz/pascallinxweiler/Kaname/raw/branch/main/deploy/compose.yaml
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 has `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`, and ideally a read-only `HF_TOKEN`. Everything else can
defaults. Models go to `./models` and the database to `./data` next to the compose file; point stay as it is. A filled-in example:
`KANAME_MODELS_DIR` at another folder (e.g. a NAS share mounted on the host) if you like.
```env
HF_TOKEN=hf_...
MAX_CONCURRENT_DOWNLOADS=1
UPDATE_CHECK_INTERVAL_HOURS=12
AUTH_SECRET=
AUTH_URL=http://192.168.1.10:3000
OIDC_ISSUER=https://auth.example.com
OIDC_CLIENT_ID=...
OIDC_CLIENT_SECRET=...
OIDC_ALLOWED_GROUPS=admin
```
**4. Start** **4. Start**
@@ -56,11 +166,11 @@ Open your `AUTH_URL`, sign in, click **Add model**. That's it.
Kaname creates and takes over `./data` itself, and an empty models folder too. It runs as uid/gid Kaname creates and takes over `./data` itself, and an empty models folder too. It runs as uid/gid
1000 by default; if your models folder already holds files that belong to another user (common for 1000 by default; if your models folder already holds files that belong to another user (common for
NAS shares), set `PUID`/`PGID` in `.env` to that owner (`ls -ln /path/to/models`). Kaname never NAS shares), add `PUID`/`PGID` to `.env` for that owner (`ls -ln /path/to/models`). Kaname never
changes the ownership of a models folder that has files in it. changes the ownership of a models folder that has files in it.
**Updating:** `docker compose pull && docker compose up -d`. To stay on a version, set e.g. **Updating:** `docker compose pull && docker compose up -d`. To stay on a version, set e.g.
`KANAME_VERSION=0.16.0` in `.env`. The running version is shown next to the app name. Read the `KANAME_VERSION=0.23.0` in `.env`. The running version is shown next to the app name. Read the
[changelog](CHANGELOG.md) before jumping minor versions: it says when the compose file changed. [changelog](CHANGELOG.md) before jumping minor versions: it says when the compose file changed.
### The image ### The image
@@ -70,8 +180,8 @@ changes the ownership of a models folder that has files in it.
| Tag | What it is | | Tag | What it is |
| --- | --- | | --- | --- |
| `latest` | the newest release | | `latest` | the newest release |
| `0.16` | the newest 0.16.x release | | `0.23` | the newest 0.23.x release |
| `0.16.0` | exactly that release | | `0.23.0` | exactly that release |
It is built for x86-64 (`linux/amd64`). One image serves all three services (`web`, `worker`, It is built for x86-64 (`linux/amd64`). One image serves all three services (`web`, `worker`,
`sandbox`); the compose file picks the role. To build it yourself (e.g. for ARM) from this `sandbox`); the compose file picks the role. To build it yourself (e.g. for ARM) from this
@@ -82,7 +192,7 @@ git clone https://git.linxweiler.xyz/pascallinxweiler/Kaname.git && cd Kaname
docker build -t kaname:mine --build-arg APP_VERSION=$(git describe --tags) . docker build -t kaname:mine --build-arg APP_VERSION=$(git describe --tags) .
``` ```
and set `KANAME_IMAGE=kaname` and `KANAME_VERSION=mine` in `.env`. and change the three `image:` lines in `compose.yaml` to `kaname:mine`.
## Configuration ## Configuration
+26 -25
View File
@@ -1,50 +1,51 @@
# Builds the image from this checkout. For the server use deploy/compose.yaml (released image). # Builds the image from this checkout. For the server use deploy/compose.yaml (released image).
name: kaname name: kaname
x-app: &app
image: kaname:local
build: .
env_file: .env
# Container paths win over local-dev paths in .env.
environment:
DATABASE_URL: file:/data/app.db
MODELS_DIR: /models
HF_HOME: /data/hf-home
restart: unless-stopped
services: services:
web:
build: .
image: kaname:local
env_file: .env
environment:
DATABASE_URL: file:/data/app.db # container paths win over local-dev paths in .env
MODELS_DIR: /models
ports:
- "3000:3000"
volumes:
- data:/data
restart: unless-stopped
worker: worker:
<<: *app image: kaname:local
command: worker command: worker
env_file: .env
environment: environment:
DATABASE_URL: file:/data/app.db DATABASE_URL: file:/data/app.db
MODELS_DIR: /models MODELS_DIR: /models
HF_HOME: /data/hf-home
SANDBOX_DIR: /sandbox SANDBOX_DIR: /sandbox
volumes: [data:/data, models:/models, sandbox:/sandbox] volumes:
- data:/data
- models:/models
- sandbox:/sandbox
depends_on: [web]
restart: unless-stopped
web:
<<: *app
ports: ["${WEB_PORT:-3000}:3000"]
volumes: [data:/data]
# Runs the quality eval's coding answers (Python written by the model under test) with no
# network, a read-only root, no capabilities, small limits and an unprivileged user. It shares only
# the exchange folder with the worker. Optional: without it the quality eval skips coding.
sandbox: sandbox:
image: kaname:local image: kaname:local
command: sandbox command: sandbox
user: "65534:65534" user: "65534:65534"
depends_on: [worker]
network_mode: none network_mode: none
read_only: true read_only: true
tmpfs: ["/tmp:size=64m,mode=1777"] tmpfs:
- /tmp:size=64m,mode=1777
cap_drop: [ALL] cap_drop: [ALL]
security_opt: ["no-new-privileges:true"] security_opt: ["no-new-privileges:true"]
mem_limit: 512m mem_limit: 512m
pids_limit: 64 pids_limit: 64
cpus: 1 cpus: 1
volumes: [sandbox:/sandbox] volumes:
- sandbox:/sandbox
depends_on: [worker]
restart: unless-stopped restart: unless-stopped
volumes: volumes:
+19 -20
View File
@@ -1,49 +1,48 @@
# Kaname: put this file and a filled-in .env (from .env.example) in one folder, then # Kaname: put this file and a filled-in .env (from .env.example) in one folder, then
# docker compose up -d # docker compose up -d
# The data and models folders are created next to this file unless .env points elsewhere.
name: kaname name: kaname
x-kaname: &kaname
# Public image, no login needed. Pin a version with KANAME_VERSION=0.15.2 in .env.
image: ${KANAME_IMAGE:-git.linxweiler.xyz/pascallinxweiler/kaname}:${KANAME_VERSION:-latest}
restart: unless-stopped
services: services:
web: web:
<<: *kaname image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
env_file: .env env_file: .env
ports: ["${WEB_PORT:-3000}:3000"] ports:
- "3000:3000"
volumes: volumes:
- ${KANAME_DATA_DIR:-./data}:/data # SQLite database and results, shared with the worker (local disk, not NFS) - ./data:/data
restart: unless-stopped
worker: worker:
<<: *kaname image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
command: worker command: worker
env_file: .env env_file: .env
environment: environment:
SANDBOX_DIR: /sandbox SANDBOX_DIR: /sandbox
volumes: volumes:
- ${KANAME_DATA_DIR:-./data}:/data - ./data:/data
- ${KANAME_MODELS_DIR:-./models}:/models # downloaded models (a NAS share mounted on the host works) - ./models:/models # where models are downloaded to, e.g. /mnt/models
- sandbox:/sandbox # exchange folder with the code sandbox - sandbox:/sandbox
restart: unless-stopped
# Runs the quality eval's coding answers (Python written by the model under test): no network, a # Runs the coding answers of the quality eval (Python written by the model under test), locked
# read-only root, no capabilities, small limits, an unprivileged user, and only the exchange # down: no network, no secrets, read-only. Optional: without it the eval skips the coding part.
# folder shared with the worker. No .env (no secrets). Optional: without it the eval skips coding.
sandbox: sandbox:
<<: *kaname image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
command: sandbox command: sandbox
user: "65534:65534" user: "65534:65534"
depends_on: [worker]
network_mode: none network_mode: none
read_only: true read_only: true
tmpfs: ["/tmp:size=64m,mode=1777"] tmpfs:
- /tmp:size=64m,mode=1777
cap_drop: [ALL] cap_drop: [ALL]
security_opt: ["no-new-privileges:true"] security_opt: ["no-new-privileges:true"]
mem_limit: 512m mem_limit: 512m
pids_limit: 64 pids_limit: 64
cpus: 1 cpus: 1
volumes: [sandbox:/sandbox] volumes:
- sandbox:/sandbox
depends_on: [worker]
restart: unless-stopped
volumes: volumes:
sandbox: sandbox:
+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 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
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "kaname", "name": "kaname",
"version": "0.22.0", "version": "0.23.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "kaname", "name": "kaname",
"version": "0.22.0", "version": "0.23.0",
"dependencies": { "dependencies": {
"@base-ui/react": "^1.8.0", "@base-ui/react": "^1.8.0",
"@libsql/client": "^0.18.0", "@libsql/client": "^0.18.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "kaname", "name": "kaname",
"version": "0.22.0", "version": "0.23.0",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"", "dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
+12 -7
View File
@@ -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>
+2 -2
View File
@@ -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">
+3 -2
View File
@@ -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
View File
@@ -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;
}
+24 -13
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 { 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
View File
@@ -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 });
}; };
} }
+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 * 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
View File
@@ -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 -1
View File
@@ -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
View File
@@ -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);
} }