Milestone (a): project skeleton and OIDC login

- Next.js 16 + Tailwind + shadcn/ui skeleton
- Auth.js v5 generic OIDC (Pocket ID, PKCE) with optional group gate
- proxy.ts gates all pages and API routes
- Drizzle schema (models, files, jobs, logs, worker state) on SQLite/libsql
- Worker skeleton: migrations, interrupted-job recovery, heartbeat

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-05 15:32:52 +02:00
commit 891e496157
47 files changed
+14945

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
import "server-only";
import type { Session } from "next-auth";
import { NextResponse } from "next/server";
import { auth } 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). */
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 });
return handler(req, { ...ctx, session });
};
}
+42
View File
@@ -0,0 +1,42 @@
import { mkdirSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { createClient, type Client } from "@libsql/client";
import { drizzle, type LibSQLDatabase } from "drizzle-orm/libsql";
import { coreEnv } from "@/lib/env";
import * as schema from "./schema";
export type Db = LibSQLDatabase<typeof schema>;
type Holder = { client?: Client; db?: Db };
// Survive Next.js dev hot reloads without opening a new pool each time.
const holder = ((globalThis as { __kanameDb?: Holder }).__kanameDb ??= {});
function ensureParentDir(url: string) {
if (!url.startsWith("file:")) return;
const path = url.slice("file:".length);
if (path === ":memory:") return;
mkdirSync(dirname(resolve(path)), { recursive: true });
}
/**
* Shared Drizzle instance. Web and worker each open their own pool on the same SQLite file;
* WAL mode lets the web app read while the worker writes.
*/
export function db(): Db {
if (!holder.db) {
const url = coreEnv().DATABASE_URL;
ensureParentDir(url);
// `timeout` is SQLite's busy timeout (ms) and applies to every pooled connection.
holder.client = createClient({ url, timeout: 5000 });
holder.db = drizzle(holder.client, { schema });
}
return holder.db;
}
/** Database-level settings. journal_mode=WAL is persistent, so running it once per process is enough. */
export async function initDb(): Promise<void> {
db();
await holder.client!.execute("PRAGMA journal_mode=WAL");
}
export { schema };
+8
View File
@@ -0,0 +1,8 @@
import { runMigrations } from "./migrate";
runMigrations()
.then(() => console.log("migrations applied"))
.catch((err) => {
console.error(err);
process.exit(1);
});
+9
View File
@@ -0,0 +1,9 @@
import { resolve } from "node:path";
import { migrate } from "drizzle-orm/libsql/migrator";
import { db, initDb } from "./client";
/** Applies pending migrations from ./drizzle. Run by the worker at startup (and `npm run db:migrate`). */
export async function runMigrations(): Promise<void> {
await initDb();
await migrate(db(), { migrationsFolder: resolve(process.cwd(), "drizzle") });
}
+246
View File
@@ -0,0 +1,246 @@
import { sql } from "drizzle-orm";
import {
index,
integer,
primaryKey,
sqliteTable,
text,
uniqueIndex,
} from "drizzle-orm/sqlite-core";
import { ulid } from "ulid";
// Conventions (keep these when adding tables in later steps, they keep a Postgres port simple):
// - Primary keys are ULID strings, generated in the app, never reused.
// - Timestamps are integer milliseconds (mode "timestamp_ms").
// - Byte counts are integers (safe up to 2^53).
// - Enums are text columns with a TS-level enum, not DB enums.
// - Foreign keys are declared, but deletes cascade in app code: SQLite only enforces
// FKs per connection with PRAGMA foreign_keys=ON, which libsql's pool doesn't guarantee.
const id = () =>
text("id")
.primaryKey()
.$defaultFn(() => ulid());
const createdAt = () =>
integer("created_at", { mode: "timestamp_ms" })
.notNull()
.$defaultFn(() => new Date());
const updatedAt = () =>
integer("updated_at", { mode: "timestamp_ms" })
.notNull()
.$defaultFn(() => new Date())
.$onUpdateFn(() => new Date());
const ts = (name: string) => integer(name, { mode: "timestamp_ms" });
// ---------------------------------------------------------------------------
// Models
// ---------------------------------------------------------------------------
export const MODEL_STATUSES = [
"pending", // added, nothing downloaded yet
"downloading",
"ready", // all selected files present at pinned SHA
"incomplete", // verify found missing/broken files, or an update/repair didn't finish
"failed", // last download failed
"deleting",
] as const;
export type ModelStatus = (typeof MODEL_STATUSES)[number];
export const models = sqliteTable(
"models",
{
id: id(),
repoType: text("repo_type", { enum: ["model"] }).notNull().default("model"),
repoId: text("repo_id").notNull(), // "org/name"
trackedRevision: text("tracked_revision").notNull().default("main"),
pinnedSha: text("pinned_sha").notNull(),
/** Relative to MODELS_DIR, e.g. "unsloth/Qwen3-27B-GGUF". */
localPath: text("local_path").notNull(),
/**
* Selection rule, applied to the repo's file list. Checkbox picks are stored as escaped
* exact-path globs, so the same rule can be re-applied to a newer revision.
*/
includePatterns: text("include_patterns", { mode: "json" })
.$type<string[]>()
.notNull()
.default(sql`'[]'`),
excludePatterns: text("exclude_patterns", { mode: "json" })
.$type<string[]>()
.notNull()
.default(sql`'[]'`),
status: text("status", { enum: MODEL_STATUSES }).notNull().default("pending"),
/** Latest SHA of trackedRevision seen on the Hub (update check). */
remoteSha: text("remote_sha"),
lastCheckedAt: ts("last_checked_at"),
lastCheckError: text("last_check_error"),
lastVerifiedAt: ts("last_verified_at"),
downloadedAt: ts("downloaded_at"),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
(t) => [uniqueIndex("models_repo_uq").on(t.repoType, t.repoId)],
);
/** History of SHAs a model has been pinned to. */
export const modelRevisions = sqliteTable(
"model_revisions",
{
id: id(),
modelId: text("model_id")
.notNull()
.references(() => models.id),
sha: text("sha").notNull(),
pinnedAt: ts("pinned_at")
.notNull()
.$defaultFn(() => new Date()),
supersededAt: ts("superseded_at"),
},
(t) => [index("model_revisions_model_idx").on(t.modelId)],
);
export const MODEL_FILE_STATES = [
"pending", // not downloaded yet / not checked
"present", // exists with the expected size
"missing",
"size_mismatch",
"hash_mismatch",
"verified", // deep verify: hash matches
] as const;
export type ModelFileState = (typeof MODEL_FILE_STATES)[number];
/** All files in the repo at the pinned SHA. `selected` marks what we keep locally. */
export const modelFiles = sqliteTable(
"model_files",
{
id: id(),
modelId: text("model_id")
.notNull()
.references(() => models.id),
path: text("path").notNull(),
size: integer("size").notNull(),
/** Git blob SHA-1 from the Hub tree API. */
blobOid: text("blob_oid"),
/** SHA-256 for LFS/Xet files (null for small git-stored files). */
lfsSha256: text("lfs_sha256"),
selected: integer("selected", { mode: "boolean" }).notNull().default(false),
state: text("state", { enum: MODEL_FILE_STATES }).notNull().default("pending"),
checkedAt: ts("checked_at"),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
(t) => [uniqueIndex("model_files_model_path_uq").on(t.modelId, t.path)],
);
// ---------------------------------------------------------------------------
// Jobs (executed by the worker)
// ---------------------------------------------------------------------------
export const JOB_KINDS = ["download", "verify", "deep_verify"] as const;
export type JobKind = (typeof JOB_KINDS)[number];
export const JOB_PURPOSES = ["initial", "repair", "update"] as const;
export type JobPurpose = (typeof JOB_PURPOSES)[number];
export const JOB_STATES = [
"queued",
"downloading",
"verifying",
"completed",
"failed",
"cancelled",
"interrupted",
] as const;
export type JobState = (typeof JOB_STATES)[number];
export const ACTIVE_JOB_STATES = ["downloading", "verifying"] as const satisfies JobState[];
export const JOB_ERROR_CODES = [
"auth", // invalid/missing token
"gated", // gated repo, access not granted
"repo_not_found",
"revision_not_found",
"disk_full",
"network",
"size_mismatch", // finished but files don't match expected sizes
"unknown",
] as const;
export type JobErrorCode = (typeof JOB_ERROR_CODES)[number];
export const jobs = sqliteTable(
"jobs",
{
id: id(),
modelId: text("model_id")
.notNull()
.references(() => models.id),
kind: text("kind", { enum: JOB_KINDS }).notNull(),
purpose: text("purpose", { enum: JOB_PURPOSES }),
targetSha: text("target_sha").notNull(),
state: text("state", { enum: JOB_STATES }).notNull().default("queued"),
attempt: integer("attempt").notNull().default(0),
totalBytes: integer("total_bytes").notNull().default(0),
doneBytes: integer("done_bytes").notNull().default(0),
speedBps: integer("speed_bps"),
etaSeconds: integer("eta_seconds"),
exitCode: integer("exit_code"),
errorCode: text("error_code", { enum: JOB_ERROR_CODES }),
errorMessage: text("error_message"),
/** Set by the web app; the worker picks it up and stops the job. */
cancelRequestedAt: ts("cancel_requested_at"),
startedAt: ts("started_at"),
finishedAt: ts("finished_at"),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
(t) => [index("jobs_state_idx").on(t.state), index("jobs_model_idx").on(t.modelId)],
);
export const JOB_FILE_STATES = ["pending", "downloading", "done", "failed"] as const;
export type JobFileState = (typeof JOB_FILE_STATES)[number];
export const jobFiles = sqliteTable(
"job_files",
{
jobId: text("job_id")
.notNull()
.references(() => jobs.id),
modelFileId: text("model_file_id")
.notNull()
.references(() => modelFiles.id),
path: text("path").notNull(),
expectedBytes: integer("expected_bytes").notNull(),
doneBytes: integer("done_bytes").notNull().default(0),
state: text("state", { enum: JOB_FILE_STATES }).notNull().default("pending"),
},
(t) => [primaryKey({ columns: [t.jobId, t.modelFileId] })],
);
export const LOG_STREAMS = ["stdout", "stderr", "system"] as const;
export type LogStream = (typeof LOG_STREAMS)[number];
export const jobLogs = sqliteTable(
"job_logs",
{
id: integer("id").primaryKey({ autoIncrement: true }),
jobId: text("job_id")
.notNull()
.references(() => jobs.id),
ts: ts("ts")
.notNull()
.$defaultFn(() => new Date()),
stream: text("stream", { enum: LOG_STREAMS }).notNull(),
line: text("line").notNull(),
},
(t) => [index("job_logs_job_idx").on(t.jobId, t.id)],
);
// ---------------------------------------------------------------------------
// Worker liveness
// ---------------------------------------------------------------------------
export const workerState = sqliteTable("worker_state", {
id: text("id").primaryKey(), // "worker"
pid: integer("pid"),
hfVersion: text("hf_version"),
startedAt: ts("started_at").notNull(),
heartbeatAt: ts("heartbeat_at").notNull(),
});
+56
View File
@@ -0,0 +1,56 @@
import { z } from "zod";
// Shared by the web app and the worker. Never import this from a client component:
// it contains HF_TOKEN. Web code should go through "@/lib/server-env", which is guarded
// by "server-only".
const emptyToUndefined = (v: unknown) => (v === "" ? undefined : v);
const coreSchema = z.object({
HF_TOKEN: z.preprocess(emptyToUndefined, z.string().optional()),
MODELS_DIR: z.preprocess(emptyToUndefined, z.string().default("/models")),
DATABASE_URL: z.preprocess(emptyToUndefined, z.string().default("file:/data/app.db")),
MAX_CONCURRENT_DOWNLOADS: z.preprocess(emptyToUndefined, z.coerce.number().int().min(1).default(1)),
UPDATE_CHECK_INTERVAL_HOURS: z.preprocess(emptyToUndefined, z.coerce.number().min(0).default(12)),
});
const authSchema = z.object({
OIDC_ISSUER: z.url(),
OIDC_CLIENT_ID: z.string().min(1),
OIDC_CLIENT_SECRET: z.string().min(1),
OIDC_ALLOWED_GROUPS: z.preprocess(
(v) =>
typeof v === "string"
? v
.split(",")
.map((g) => g.trim())
.filter(Boolean)
: [],
z.array(z.string()),
),
});
export type CoreEnv = z.infer<typeof coreSchema>;
export type AuthEnv = z.infer<typeof authSchema>;
let core: CoreEnv | undefined;
let auth: AuthEnv | undefined;
function parse<T extends z.ZodType>(schema: T, name: string): z.infer<T> {
const result = schema.safeParse(process.env);
if (!result.success) {
const issues = result.error.issues.map((i) => ` ${i.path.join(".")}: ${i.message}`).join("\n");
throw new Error(`Invalid ${name} environment:\n${issues}`);
}
return result.data;
}
/** Config needed by both web and worker. Parsed lazily so `next build` works without env. */
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"));
}
+3
View File
@@ -0,0 +1,3 @@
import "server-only";
export { coreEnv, authEnv } from "@/lib/env";
+1
View File
@@ -0,0 +1 @@
export { cn } from "cn"
+28
View File
@@ -0,0 +1,28 @@
import "server-only";
import { eq } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { workerState } from "@/lib/db/schema";
/** The worker writes a heartbeat every 5s; after this long without one we call it offline. */
const OFFLINE_AFTER_MS = 20_000;
export type WorkerStatus = {
online: boolean;
heartbeatAt: string | null;
hfVersion: string | null;
};
export async function getWorkerStatus(): Promise<WorkerStatus> {
try {
const row = await db().query.workerState.findFirst({ where: eq(workerState.id, "worker") });
if (!row) return { online: false, heartbeatAt: null, hfVersion: null };
return {
online: Date.now() - row.heartbeatAt.getTime() < OFFLINE_AFTER_MS,
heartbeatAt: row.heartbeatAt.toISOString(),
hfVersion: row.hfVersion,
};
} catch {
// Table missing (worker never ran migrations yet) or DB unavailable.
return { online: false, heartbeatAt: null, hfVersion: null };
}
}