docs(15-02): complete OIDC auth integration plan

- Add 15-02-SUMMARY.md with execution results
- Update STATE.md with position, decisions, session info
- Update ROADMAP.md with plan progress
- Mark AUTH-01, AUTH-02, AUTH-03 requirements complete
This commit is contained in:
2026-04-04 20:48:04 +02:00
parent c0e6db5aa6
commit 82eb9e7286
8 changed files with 1397 additions and 18 deletions

View File

@@ -17,9 +17,9 @@ Requirements for this milestone. Each maps to roadmap phases.
### Authentication
- [ ] **AUTH-01**: User can register an account via external OIDC auth provider
- [ ] **AUTH-02**: User can log in via external auth provider and access their data
- [ ] **AUTH-03**: API keys remain functional for programmatic access (MCP, scripts)
- [x] **AUTH-01**: User can register an account via external OIDC auth provider
- [x] **AUTH-02**: User can log in via external auth provider and access their data
- [x] **AUTH-03**: API keys remain functional for programmatic access (MCP, scripts)
- [ ] **AUTH-04**: Auth provider runs self-hosted alongside the application
- [ ] **AUTH-05**: E2E tests authenticate via API keys without depending on the auth provider
@@ -121,9 +121,9 @@ Which phases cover which requirements. Updated during roadmap creation.
| DB-03 | Phase 14 | Pending |
| DB-04 | Phase 14 | Pending |
| DB-05 | Phase 14 | Pending |
| AUTH-01 | Phase 15 | Pending |
| AUTH-02 | Phase 15 | Pending |
| AUTH-03 | Phase 15 | Pending |
| AUTH-01 | Phase 15 | Complete |
| AUTH-02 | Phase 15 | Complete |
| AUTH-03 | Phase 15 | Complete |
| AUTH-04 | Phase 15 | Pending |
| AUTH-05 | Phase 15 | Pending |
| MULTI-01 | Phase 16 | Pending |

View File

@@ -51,7 +51,7 @@
**Milestone Goal:** Transform GearBox from a single-user gear tracker into a multi-user platform where people discover gear, research purchases using crowd-verified data, and share their setups.
- [ ] **Phase 14: PostgreSQL Migration** — Replace SQLite with Postgres, make all operations async, establish new test infrastructure
- [ ] **Phase 15: External Authentication** — Integrate self-hosted OIDC auth provider for user registration and login
- [x] **Phase 15: External Authentication** — Integrate self-hosted OIDC auth provider for user registration and login (completed 2026-04-04)
- [ ] **Phase 16: Multi-User Data Model** — Add user ownership to all entities with cross-user data isolation
- [ ] **Phase 17: Object Storage** — Move images from local filesystem to MinIO (S3-compatible)
- [ ] **Phase 18: Global Items & Public Profiles** — Global item catalog, user profiles, and public setup sharing
@@ -189,7 +189,7 @@ Plans:
| 12. Comparison View | v1.3 | 1/1 | Complete | 2026-03-17 |
| 13. Setup Impact Preview | v1.3 | 0/2 | Not started | - |
| 14. PostgreSQL Migration | v2.0 | 0/? | Not started | - |
| 15. External Authentication | v2.0 | 0/? | Not started | - |
| 15. External Authentication | v2.0 | 2/1 | Complete | 2026-04-04 |
| 16. Multi-User Data Model | v2.0 | 0/? | Not started | - |
| 17. Object Storage | v2.0 | 0/? | Not started | - |
| 18. Global Items & Public Profiles | v2.0 | 0/? | Not started | - |

View File

@@ -1,16 +1,16 @@
---
gsd_state_version: 1.0
milestone: v2.0
milestone_name: Platform Foundation
milestone: v1.3
milestone_name: Research & Decision Tools
status: planning
stopped_at: null
last_updated: "2026-04-03"
stopped_at: Completed 15-02-PLAN.md
last_updated: "2026-04-04T18:47:52.641Z"
last_activity: 2026-04-03 — v2.0 roadmap created (Phases 14-18)
progress:
total_phases: 5
completed_phases: 0
total_plans: 0
completed_plans: 0
total_phases: 8
completed_phases: 7
total_plans: 13
completed_plans: 12
percent: 0
---
@@ -35,6 +35,7 @@ Progress: [----------] 0% (v2.0 milestone)
## Performance Metrics
**Velocity:**
- Total plans completed: 0 (v2.0 milestone)
- Average duration: --
- Total execution time: --
@@ -46,12 +47,15 @@ Progress: [----------] 0% (v2.0 milestone)
### Decisions
Key decisions made during v2.0 planning:
- Platform pivot: single-user to multi-user with discovery-first approach
- External auth provider (self-hosted, open-source) — Logto vs Authentik OPEN decision
- SQLite to Postgres migration — required by auth provider and multi-user concurrency
- Structured UGC only — ratings and predefined fields, no freeform text until moderation
- Separate globalItems table — not a flag on user items table
- Single-user SQLite mode diverges at v2.0 boundary
- [Phase 15]: OIDC routes at root level (/login, /callback, /logout), API key routes under /api/auth
- [Phase 15]: Three-way auth order: API key -> MCP Bearer -> OIDC session
### Pending Todos
@@ -64,6 +68,6 @@ None active.
## Session Continuity
Last session: 2026-04-03
Stopped at: v2.0 roadmap created with 5 phases (14-18) covering 30 requirements
Last session: 2026-04-04T18:47:52.639Z
Stopped at: Completed 15-02-PLAN.md
Resume file: None

View File

@@ -0,0 +1,102 @@
---
phase: 15-external-authentication
plan: 01
subsystem: infra
tags: [logto, oidc, docker-compose, postgres]
# Dependency graph
requires:
- phase: 14-postgresql-migration
provides: Postgres database and Docker Compose foundation
provides:
- Logto OIDC provider running as Docker Compose service
- Postgres init script for separate Logto database
- OIDC environment variable documentation
- Schema without users/sessions tables (ready for external auth)
affects: [15-02, 15-03, 16-multi-user-data-model]
# Tech tracking
tech-stack:
added: [logto (svhd/logto Docker image)]
patterns: [multi-database Postgres init via docker-entrypoint-initdb.d, OIDC env var convention]
key-files:
created:
- docker-compose.yml
- docker-compose.dev.yml
- docker/init-logto-db.sql
- .env.example
modified:
- src/db/schema.ts
key-decisions:
- "Logto shares Postgres instance via separate database created by init script"
- "OIDC_ISSUER derived from LOGTO_ENDPOINT in docker-compose, not separately configured"
patterns-established:
- "Docker init scripts in docker/ directory mounted to docker-entrypoint-initdb.d"
- "OIDC environment variables: LOGTO_ENDPOINT, LOGTO_CLIENT_ID, LOGTO_CLIENT_SECRET, OIDC_AUTH_SECRET"
requirements-completed: [AUTH-04]
# Metrics
duration: 3min
completed: 2026-04-04
---
# Phase 15 Plan 01: Logto Docker Infrastructure and Schema Cleanup Summary
**Logto OIDC provider added to Docker Compose with Postgres init script, users/sessions tables removed from schema**
## Performance
- **Duration:** 3 min
- **Started:** 2026-04-04T18:35:52Z
- **Completed:** 2026-04-04T18:38:52Z
- **Tasks:** 2
- **Files modified:** 6
## Accomplishments
- Added Logto as a Docker Compose service in both production and dev configurations with proper health-check dependency on Postgres
- Created Postgres init script that automatically creates the logto database on first boot
- Removed users and sessions tables from GearBox schema, generated Drizzle migration to drop them
- Documented all required OIDC environment variables in .env.example
## Task Commits
Each task was committed atomically:
1. **Task 1: Add Logto service to Docker Compose and create init script** - `625862f` (feat)
2. **Task 2: Remove users and sessions tables from schema** - `0fe231f` (feat)
## Files Created/Modified
- `docker-compose.yml` - Production compose with Postgres, Logto, and app services
- `docker-compose.dev.yml` - Dev compose with Postgres and Logto for local auth testing
- `docker/init-logto-db.sql` - SQL script creating separate logto database on Postgres
- `.env.example` - Documents all required environment variables for OIDC configuration
- `src/db/schema.ts` - Removed users and sessions table definitions
- `drizzle/0010_foamy_marvel_zombies.sql` - Migration to drop users and sessions tables
## Decisions Made
- Logto shares the same Postgres instance but uses a separate database (created by init script), rather than a dedicated Postgres container
- OIDC_ISSUER is derived from LOGTO_ENDPOINT in docker-compose.yml rather than being a separate top-level env var, reducing configuration duplication
- Dev compose uses hardcoded password for Logto DB connection (matching existing dev Postgres pattern)
## Deviations from Plan
None - plan executed exactly as written.
## Issues Encountered
None.
## User Setup Required
None - no external service configuration required. Logto admin console setup (creating OIDC application, obtaining client ID/secret) will be needed before plan 15-02, but is handled as part of the Logto first-boot experience at http://localhost:3002.
## Next Phase Readiness
- Logto infrastructure is ready for plan 15-02 (server-side OIDC integration)
- Schema is cleaned of old auth tables, ready for OIDC-based authentication
- API keys table preserved for continued programmatic access
---
*Phase: 15-external-authentication*
*Completed: 2026-04-04*

View File

@@ -0,0 +1,555 @@
---
phase: 15-external-authentication
plan: 02
type: execute
wave: 2
depends_on: ["15-01"]
files_modified:
- src/server/middleware/auth.ts
- src/server/services/auth.service.ts
- src/server/routes/auth.ts
- src/server/routes/oauth.ts
- src/server/mcp/index.ts
- src/server/index.ts
- package.json
autonomous: true
requirements: [AUTH-01, AUTH-02, AUTH-03]
must_haves:
truths:
- "requireAuth middleware validates API keys, MCP Bearer tokens, and OIDC session cookies"
- "GET /login redirects unauthenticated users to Logto"
- "GET /callback processes the OIDC authorization code and sets a session cookie"
- "GET /api/auth/me returns user identity from OIDC claims or null"
- "API keys continue to authenticate programmatic requests without Logto"
- "MCP OAuth Bearer tokens continue to work for Claude mobile/web"
- "MCP OAuth /oauth/authorize validates via OIDC session instead of username/password"
artifacts:
- path: "src/server/middleware/auth.ts"
provides: "Three-way auth middleware (API key, MCP Bearer, OIDC session)"
exports: ["requireAuth"]
- path: "src/server/services/auth.service.ts"
provides: "API key CRUD only (user/session functions removed)"
exports: ["createApiKey", "verifyApiKey", "listApiKeys", "deleteApiKey"]
- path: "src/server/routes/auth.ts"
provides: "OIDC login/callback/logout routes + API key CRUD routes"
exports: ["authRoutes"]
- path: "src/server/routes/oauth.ts"
provides: "MCP OAuth with OIDC session validation instead of password"
- path: "src/server/index.ts"
provides: "Updated route registration with OIDC callback"
key_links:
- from: "src/server/middleware/auth.ts"
to: "@hono/oidc-auth"
via: "getAuth() for OIDC session check"
pattern: "getAuth"
- from: "src/server/middleware/auth.ts"
to: "src/server/services/auth.service.ts"
via: "verifyApiKey for API key path"
pattern: "verifyApiKey"
- from: "src/server/routes/auth.ts"
to: "@hono/oidc-auth"
via: "oidcAuthMiddleware for login redirect, processOAuthCallback for callback"
pattern: "oidcAuthMiddleware|processOAuthCallback"
- from: "src/server/routes/oauth.ts"
to: "@hono/oidc-auth"
via: "getAuth() replaces verifyPassword in authorize POST"
pattern: "getAuth"
---
<objective>
Rewrite the server-side authentication layer to use OIDC via @hono/oidc-auth for browser sessions while preserving API key and MCP OAuth authentication paths.
Purpose: This is the core auth integration -- replacing GearBox's custom user/session management with Logto OIDC. After this plan, browser users authenticate via Logto, API keys work unchanged, and MCP OAuth coexists cleanly.
Output: Refactored middleware, routes, and services implementing three-way authentication.
</objective>
<execution_context>
@$HOME/.claude/get-shit-done/workflows/execute-plan.md
@$HOME/.claude/get-shit-done/templates/summary.md
</execution_context>
<context>
@.planning/PROJECT.md
@.planning/ROADMAP.md
@.planning/STATE.md
@.planning/phases/15-external-authentication/15-CONTEXT.md
@.planning/phases/15-external-authentication/15-RESEARCH.md
@.planning/phases/15-external-authentication/15-01-SUMMARY.md
@src/server/middleware/auth.ts
@src/server/services/auth.service.ts
@src/server/routes/auth.ts
@src/server/routes/oauth.ts
@src/server/mcp/index.ts
@src/server/index.ts
<interfaces>
<!-- Current auth service exports that will be modified -->
From src/server/services/auth.service.ts (KEEP these):
```typescript
export async function createApiKey(db: Db, name: string): Promise<{...}>
export async function verifyApiKey(db: Db, rawKey: string): Promise<boolean>
export async function listApiKeys(db: Db): Promise<{...}[]>
export async function deleteApiKey(db: Db, id: number): Promise<void>
```
From src/server/services/auth.service.ts (REMOVE these):
```typescript
export async function createUser(db: Db, username: string, password: string)
export async function verifyPassword(db: Db, username: string, password: string)
export async function getUserCount(db: Db): Promise<number>
export async function changePassword(db: Db, ...)
export async function createSession(db: Db, userId: number, ...)
export async function getSession(db: Db, sessionId: string)
export async function deleteSession(db: Db, sessionId: string)
export async function refreshSession(db: Db, sessionId: string, ...)
```
From src/server/services/oauth.service.ts (KEEP, used by MCP OAuth):
```typescript
export async function verifyAccessToken(db: Db, token: string): Promise<boolean>
```
From @hono/oidc-auth (NEW - to be installed):
```typescript
import { oidcAuthMiddleware, getAuth, revokeSession, processOAuthCallback } from "@hono/oidc-auth";
// getAuth(c) returns { sub: string, email?: string, ... } | null
// oidcAuthMiddleware() redirects to OIDC provider if no session
// processOAuthCallback(c) handles the /callback redirect
// revokeSession(c) clears the OIDC session
```
</interfaces>
</context>
<tasks>
<task type="auto">
<name>Task 1: Install OIDC dependencies and rewrite auth middleware + service</name>
<files>package.json, src/server/middleware/auth.ts, src/server/services/auth.service.ts</files>
<read_first>
- src/server/middleware/auth.ts (current middleware with getUserCount, getSession, refreshSession)
- src/server/services/auth.service.ts (current service with user/session/apiKey functions)
- src/server/mcp/index.ts (imports getUserCount, verifyApiKey from auth.service)
- .planning/phases/15-external-authentication/15-RESEARCH.md (Pattern 1: Auth Middleware, Pitfall 5: getUserCount, Pitfall 6: OIDC_AUTH_SECRET)
</read_first>
<action>
**Install dependencies:**
```bash
bun add @hono/oidc-auth jose
```
**Rewrite `src/server/services/auth.service.ts`:**
- Remove ALL user management functions: `createUser`, `verifyPassword`, `getUserCount`, `changePassword`
- Remove ALL session management functions: `createSession`, `getSession`, `deleteSession`, `refreshSession`
- Remove imports of `users` and `sessions` from schema
- Remove `count` from drizzle-orm imports (only needed by getUserCount)
- KEEP all API key functions unchanged: `createApiKey`, `verifyApiKey`, `listApiKeys`, `deleteApiKey`
- Keep `randomBytes` import (used by createApiKey)
- Keep `eq` from drizzle-orm (used by API key functions)
- Keep `apiKeys` schema import
- Keep the `Db` type alias
The file should export exactly: `createApiKey`, `verifyApiKey`, `listApiKeys`, `deleteApiKey`.
**Rewrite `src/server/middleware/auth.ts`:**
Per D-04, implement three-way auth check. Replace the entire file with:
```typescript
import type { Context, Next } from "hono";
import { getAuth } from "@hono/oidc-auth";
import { verifyApiKey } from "../services/auth.service";
import { verifyAccessToken } from "../services/oauth.service";
export async function requireAuth(c: Context, next: Next) {
const db = c.get("db");
// 1. Check API key (programmatic access) -- per D-10
const apiKey = c.req.header("X-API-Key");
if (apiKey) {
const valid = await verifyApiKey(db, apiKey);
if (valid) return next();
return c.json({ error: "Invalid API key" }, 401);
}
// 2. Check MCP OAuth Bearer token -- per D-12
const authHeader = c.req.header("Authorization");
if (authHeader?.startsWith("Bearer ")) {
const token = authHeader.slice(7);
if (await verifyAccessToken(db, token)) return next();
return c.json({ error: "invalid_token" }, 401);
}
// 3. Check OIDC session (browser users) -- per D-02
const auth = await getAuth(c);
if (auth) return next();
return c.json({ error: "Authentication required" }, 401);
}
```
Key changes from old middleware:
- Removed `getUserCount` check (Pitfall 5) -- first-run setup happens on Logto admin console
- Removed `getCookie`/`getSession`/`refreshSession` -- replaced by `getAuth()` from @hono/oidc-auth
- Added MCP OAuth Bearer token check (was only in MCP routes, now centralized)
- No `hono/cookie` import needed
</action>
<verify>
<automated>grep -q "@hono/oidc-auth" package.json && grep -q "getAuth" src/server/middleware/auth.ts && ! grep -q "getUserCount" src/server/middleware/auth.ts && ! grep -q "getUserCount" src/server/services/auth.service.ts && grep -q "verifyApiKey" src/server/services/auth.service.ts && echo "PASS" || echo "FAIL"</automated>
</verify>
<acceptance_criteria>
- package.json contains `@hono/oidc-auth` dependency
- package.json contains `jose` dependency
- src/server/middleware/auth.ts imports `getAuth` from `@hono/oidc-auth`
- src/server/middleware/auth.ts imports `verifyAccessToken` from `../services/oauth.service`
- src/server/middleware/auth.ts does NOT import `getUserCount`, `getSession`, `refreshSession`
- src/server/middleware/auth.ts does NOT import from `hono/cookie`
- src/server/services/auth.service.ts does NOT contain `export async function createUser`
- src/server/services/auth.service.ts does NOT contain `export async function verifyPassword`
- src/server/services/auth.service.ts does NOT contain `export async function getUserCount`
- src/server/services/auth.service.ts does NOT contain `export async function createSession`
- src/server/services/auth.service.ts does NOT contain `export async function getSession`
- src/server/services/auth.service.ts does NOT import `users` or `sessions` from schema
- src/server/services/auth.service.ts DOES contain `export async function verifyApiKey`
- src/server/services/auth.service.ts DOES contain `export async function createApiKey`
- src/server/services/auth.service.ts DOES contain `export async function listApiKeys`
- src/server/services/auth.service.ts DOES contain `export async function deleteApiKey`
</acceptance_criteria>
<done>@hono/oidc-auth installed, middleware does three-way auth check, service only has API key functions</done>
</task>
<task type="auto">
<name>Task 2: Rewrite auth routes for OIDC login/callback/logout + API key CRUD</name>
<files>src/server/routes/auth.ts, src/server/index.ts</files>
<read_first>
- src/server/routes/auth.ts (current routes with login form, setup, password change, API key CRUD)
- src/server/index.ts (current route registration and middleware application order)
- .planning/phases/15-external-authentication/15-RESEARCH.md (Code Examples: @hono/oidc-auth Configuration, Pattern 2: OIDC Middleware Selective Application)
</read_first>
<action>
**Rewrite `src/server/routes/auth.ts`:**
Per D-05, D-06, D-07: Replace credential-based auth routes with OIDC redirect flow.
Remove:
- `POST /login` (credential login) -- replaced by OIDC redirect
- `POST /setup` (first-time account creation) -- happens on Logto now per D-06
- `PUT /password` (password change) -- managed by Logto now
- All Zod schemas: `loginSchema`, `setupSchema`, `changePasswordSchema`
- All cookie handling (`COOKIE_NAME`, `COOKIE_MAX_AGE`, `setCookie`, `getCookie`, `deleteCookie`)
- Imports of `users` from schema, `verifyPassword`, `createUser`, `changePassword`, `createSession`, `getSession`, `deleteSession`, `getUserCount`
Keep (with modifications):
- `GET /me` -- rewrite to use `getAuth()` from @hono/oidc-auth
- `GET /keys`, `POST /keys`, `DELETE /keys/:id` -- keep unchanged, still protected by requireAuth
Add:
- `GET /login` -- applies `oidcAuthMiddleware()` which redirects to Logto if no session; if session exists, redirects to `/`
- `GET /callback` -- calls `processOAuthCallback(c)` to handle OIDC redirect back from Logto
- `GET /logout` -- calls `revokeSession(c)` then redirects to `/login`
New file structure:
```typescript
import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";
import { z } from "zod";
import {
oidcAuthMiddleware,
getAuth,
revokeSession,
processOAuthCallback,
} from "@hono/oidc-auth";
import { parseId } from "../lib/params.ts";
import { requireAuth } from "../middleware/auth.ts";
import {
createApiKey,
deleteApiKey,
listApiKeys,
} from "../services/auth.service.ts";
type Env = { Variables: { db?: any } };
const createKeySchema = z.object({ name: z.string().min(1) });
const app = new Hono<Env>();
// ── OIDC Browser Auth ────────────────────────────────────────────────
// Login: redirect to Logto if not authenticated
app.get("/login", oidcAuthMiddleware(), async (c) => {
// Middleware redirects to Logto if no session. If we reach here, user is authenticated.
return c.redirect("/");
});
// Callback: process OIDC redirect from Logto
app.get("/callback", async (c) => {
return processOAuthCallback(c);
});
// Logout: revoke OIDC session and redirect
app.get("/logout", async (c) => {
await revokeSession(c);
return c.redirect("/login");
});
// ── Auth Status ──────────────────────────────────────────────────────
app.get("/me", async (c) => {
const auth = await getAuth(c);
if (auth) {
return c.json({
user: { id: auth.sub, email: auth.email },
authenticated: true,
});
}
return c.json({ user: null, authenticated: false });
});
// ── API Key Management (protected) ───────────────────────────────────
app.get("/keys", requireAuth, async (c) => {
const db = c.get("db");
const keys = await listApiKeys(db);
return c.json(keys);
});
app.post("/keys", requireAuth, zValidator("json", createKeySchema), async (c) => {
const db = c.get("db");
const { name } = c.req.valid("json");
const result = await createApiKey(db, name);
return c.json({ id: result.id, name: result.name, key: result.rawKey, prefix: result.keyPrefix }, 201);
});
app.delete("/keys/:id", requireAuth, async (c) => {
const db = c.get("db");
const id = parseId(c.req.param("id"));
if (!id) return c.json({ error: "Invalid key ID" }, 400);
await deleteApiKey(db, id);
return c.json({ ok: true });
});
export const authRoutes = app;
```
**Update `src/server/index.ts`:**
The OIDC auth routes (`/login`, `/callback`, `/logout`) need to be accessible at the root level, not under `/api/auth`. But API key routes stay at `/api/auth/keys`.
Changes to index.ts:
1. Add a new top-level route group for OIDC browser auth (login, callback, logout):
```typescript
// OIDC browser auth routes (top-level, not under /api)
app.get("/login", ...); // Delegate to authRoutes
app.get("/callback", ...); // Delegate to authRoutes
app.get("/logout", ...); // Delegate to authRoutes
```
Actually, simpler approach: mount authRoutes at root level for the OIDC routes AND at `/api/auth` for the API routes. But since Hono route() mounts all routes under a prefix, we need to split.
Better approach: Keep authRoutes mounted at `/api/auth` for /me, /keys. Create separate top-level routes for /login, /callback, /logout:
```typescript
import { oidcAuthMiddleware, processOAuthCallback, revokeSession } from "@hono/oidc-auth";
// OIDC browser auth (before /api/* middleware)
app.get("/login", oidcAuthMiddleware(), async (c) => c.redirect("/"));
app.get("/callback", async (c) => processOAuthCallback(c));
app.get("/logout", async (c) => { await revokeSession(c); return c.redirect("/login"); });
```
Then remove the /login, /callback, /logout routes from authRoutes (keep only /me and /keys/* in authRoutes).
2. Place these OIDC routes BEFORE the `/api/*` middleware blocks and BEFORE static file serving
3. Keep `app.route("/api/auth", authRoutes)` for /me and /keys endpoints
4. Ensure the auth middleware skip for `/api/auth` still works (it does -- /api/auth/me is GET, /api/auth/keys POST/DELETE go through requireAuth within the route handler)
So the final authRoutes file should NOT contain /login, /callback, /logout. Those go directly in index.ts. authRoutes contains: GET /me, GET /keys, POST /keys, DELETE /keys/:id.
**IMPORTANT (Pattern 2):** Do NOT apply `oidcAuthMiddleware()` globally. Only apply it to the `/login` route. The `/api/*` routes use the custom `requireAuth` middleware.
</action>
<verify>
<automated>grep -q "processOAuthCallback" src/server/index.ts && grep -q "oidcAuthMiddleware" src/server/index.ts && ! grep -q "verifyPassword" src/server/routes/auth.ts && ! grep -q "createUser" src/server/routes/auth.ts && grep -q "getAuth" src/server/routes/auth.ts && echo "PASS" || echo "FAIL"</automated>
</verify>
<acceptance_criteria>
- src/server/routes/auth.ts does NOT contain `POST /login`, `POST /setup`, `PUT /password` handlers
- src/server/routes/auth.ts does NOT import `verifyPassword`, `createUser`, `changePassword`, `createSession`, `deleteSession`, `getSession`, `getUserCount`
- src/server/routes/auth.ts does NOT import `users` from schema
- src/server/routes/auth.ts does NOT import `setCookie`, `getCookie`, `deleteCookie` from `hono/cookie`
- src/server/routes/auth.ts DOES contain `GET /me` using `getAuth()` from @hono/oidc-auth
- src/server/routes/auth.ts DOES contain API key CRUD routes (GET /keys, POST /keys, DELETE /keys/:id)
- src/server/index.ts contains `app.get("/login"` with `oidcAuthMiddleware()`
- src/server/index.ts contains `app.get("/callback"` with `processOAuthCallback`
- src/server/index.ts contains `app.get("/logout"` with `revokeSession`
- These OIDC routes appear BEFORE the `/api/*` middleware blocks in index.ts
</acceptance_criteria>
<done>Auth routes serve OIDC login/callback/logout at root, /me returns OIDC claims, API key CRUD preserved</done>
</task>
<task type="auto">
<name>Task 3: Update MCP OAuth authorize and MCP auth middleware for OIDC</name>
<files>src/server/routes/oauth.ts, src/server/mcp/index.ts</files>
<read_first>
- src/server/routes/oauth.ts (current MCP OAuth with verifyPassword in POST /authorize)
- src/server/mcp/index.ts (current MCP auth middleware with getUserCount check)
- .planning/phases/15-external-authentication/15-RESEARCH.md (Pitfall 3: MCP OAuth POST /authorize, Pitfall 5: getUserCount)
</read_first>
<action>
**Per D-12:** MCP OAuth coexists with Logto. These are separate auth domains. But the MCP OAuth authorize form currently uses `verifyPassword()` against the removed `users` table -- this must be fixed.
**Update `src/server/routes/oauth.ts`:**
1. Remove `import { verifyPassword } from "../services/auth.service.ts"` -- this function no longer exists
2. Add `import { getAuth } from "@hono/oidc-auth"`
3. Replace the `POST /authorize` handler logic:
- Instead of parsing username/password from the form and calling `verifyPassword()`, check for an active OIDC session using `getAuth(c)`
- If the user has a valid OIDC session (`getAuth(c)` returns non-null), proceed with authorization code creation
- If no OIDC session, redirect to `/login` with a return URL that brings them back to the authorize page after Logto login
Updated POST /authorize:
```typescript
oauthRoutes.post("/authorize", async (c) => {
const db = c.get("db") ?? prodDb;
// Check for OIDC session instead of username/password
const auth = await getAuth(c);
if (!auth) {
// No session -- redirect to login, then back to authorize
const currentUrl = c.req.url;
return c.redirect(`/login?redirect=${encodeURIComponent(currentUrl)}`);
}
const body = await c.req.parseBody();
const clientId = body.client_id as string;
const redirectUri = body.redirect_uri as string;
const codeChallenge = body.code_challenge as string;
const codeChallengeMethod = body.code_challenge_method as string;
const state = (body.state as string) ?? "";
const client = await getClient(db, clientId);
if (!client) {
return c.json({ error: "Unknown client_id" }, 400);
}
const allowedUris: string[] = JSON.parse(client.redirectUris);
if (!allowedUris.includes(redirectUri)) {
return c.json({ error: "redirect_uri not allowed" }, 400);
}
const { code } = await createAuthorizationCode(
db,
clientId,
codeChallenge,
codeChallengeMethod,
redirectUri,
);
const url = new URL(redirectUri);
url.searchParams.set("code", code);
if (state) url.searchParams.set("state", state);
return c.redirect(url.toString(), 302);
});
```
4. Update the `GET /authorize` handler to also check for OIDC session:
- If user has OIDC session, show a simplified consent screen (just an "Authorize" button, no login form)
- If no OIDC session, redirect to `/login` with return URL
Replace `renderLoginForm` with a simpler `renderConsentForm` that shows the client name and an "Authorize" button (no username/password fields). The consent form POSTs to `/oauth/authorize` with the hidden fields (client_id, redirect_uri, code_challenge, code_challenge_method, state).
If no OIDC session on GET /authorize, redirect:
```typescript
oauthRoutes.get("/authorize", async (c) => {
const auth = await getAuth(c);
if (!auth) {
return c.redirect(`/login?redirect=${encodeURIComponent(c.req.url)}`);
}
// ... show consent form ...
});
```
5. Keep all other oauth routes unchanged: POST /register, POST /token, well-known endpoints
**Update `src/server/mcp/index.ts`:**
Per Pitfall 5, remove the `getUserCount` check from MCP auth middleware.
1. Remove `import { getUserCount } from "../services/auth.service.ts"` (only keep `verifyApiKey`)
2. Remove the `if (getUserCount(db) <= 0) { return next(); }` block
3. The MCP auth middleware should now only check Bearer token and API key -- no "skip if no users" bypass
Updated MCP auth middleware:
```typescript
mcpRoutes.use("/*", async (c, next) => {
const db = c.get("db") ?? prodDb;
// Try Bearer token first (OAuth)
const authHeader = c.req.header("Authorization");
if (authHeader?.startsWith("Bearer ")) {
const token = authHeader.slice(7);
if (await verifyAccessToken(db, token)) {
return next();
}
return c.json({ error: "invalid_token" }, 401);
}
// Try API key
const apiKey = c.req.header("X-API-Key");
if (apiKey) {
const valid = await verifyApiKey(db, apiKey);
if (valid) {
return next();
}
return c.json({ error: "Invalid API key" }, 401);
}
// No auth provided
const baseUrl = (process.env.GEARBOX_URL || new URL(c.req.url).origin).replace(/\/$/, "");
return c.text("Unauthorized", 401, {
"WWW-Authenticate": `Bearer resource_metadata="${baseUrl}/.well-known/oauth-protected-resource"`,
});
});
```
</action>
<verify>
<automated>! grep -q "verifyPassword" src/server/routes/oauth.ts && ! grep -q "getUserCount" src/server/mcp/index.ts && grep -q "getAuth" src/server/routes/oauth.ts && echo "PASS" || echo "FAIL"</automated>
</verify>
<acceptance_criteria>
- src/server/routes/oauth.ts does NOT import `verifyPassword`
- src/server/routes/oauth.ts DOES import `getAuth` from `@hono/oidc-auth`
- src/server/routes/oauth.ts POST /authorize checks OIDC session via `getAuth(c)` instead of username/password
- src/server/routes/oauth.ts GET /authorize redirects to `/login` if no OIDC session
- src/server/routes/oauth.ts does NOT contain `renderLoginForm` with username/password fields
- src/server/routes/oauth.ts DOES contain a consent form with just an "Authorize" button (no credential fields)
- src/server/mcp/index.ts does NOT import `getUserCount`
- src/server/mcp/index.ts does NOT contain `getUserCount` call
- src/server/mcp/index.ts DOES still import `verifyApiKey`
- src/server/mcp/index.ts DOES still import `verifyAccessToken`
- All well-known routes, POST /register, POST /token remain unchanged
</acceptance_criteria>
<done>MCP OAuth uses OIDC session for authorization, MCP middleware has no getUserCount bypass, both auth domains coexist cleanly</done>
</task>
</tasks>
<verification>
- `bun run build` succeeds (TypeScript compiles without errors referencing removed functions/tables)
- `grep -rn "getUserCount\|createUser\|verifyPassword\|createSession\|getSession\|deleteSession\|refreshSession" src/server/` returns NO matches
- `grep -rn "getAuth" src/server/middleware/auth.ts src/server/routes/auth.ts src/server/routes/oauth.ts` shows usage in all three files
- `grep "verifyApiKey" src/server/middleware/auth.ts` confirms API key path preserved
- `grep "verifyAccessToken" src/server/middleware/auth.ts` confirms MCP Bearer path preserved
</verification>
<success_criteria>
- Three-way auth middleware works: API key, MCP Bearer, OIDC session
- Browser auth flow: /login redirects to Logto, /callback processes return, /logout clears session
- /api/auth/me returns OIDC user identity or null
- API key CRUD at /api/auth/keys preserved and functional
- MCP OAuth authorize uses OIDC session instead of removed password verification
- MCP auth middleware has no getUserCount bypass
- No references to removed user/session functions anywhere in src/server/
- TypeScript compiles cleanly
</success_criteria>
<output>
After completion, create `.planning/phases/15-external-authentication/15-02-SUMMARY.md`
</output>

View File

@@ -0,0 +1,119 @@
---
phase: 15-external-authentication
plan: 02
subsystem: auth
tags: [oidc, hono, logto, @hono/oidc-auth, jose, mcp-oauth]
# Dependency graph
requires:
- phase: 15-external-authentication (plan 01)
provides: Docker Compose with Logto service, env vars, schema without users/sessions tables
provides:
- Three-way auth middleware (API key, MCP Bearer, OIDC session)
- OIDC login/callback/logout routes at root level
- Auth service stripped to API key CRUD only
- MCP OAuth authorize using OIDC session instead of password
affects: [15-external-authentication plan 03, client-side login page, e2e tests]
# Tech tracking
tech-stack:
added: ["@hono/oidc-auth@1.8.1", "jose@6.2.2"]
patterns: [three-way-auth-middleware, oidc-session-validation, consent-form-pattern]
key-files:
created: []
modified:
- src/server/middleware/auth.ts
- src/server/services/auth.service.ts
- src/server/routes/auth.ts
- src/server/routes/oauth.ts
- src/server/mcp/index.ts
- src/server/index.ts
- package.json
key-decisions:
- "OIDC routes (/login, /callback, /logout) placed at root level in index.ts, not under /api/auth"
- "MCP OAuth authorize uses consent-only form (no credentials) backed by OIDC session"
- "Three-way auth order: API key first, Bearer token second, OIDC session third"
patterns-established:
- "Three-way auth: requireAuth checks API key -> MCP Bearer -> OIDC session in order"
- "OIDC routes at root level, API routes under /api/auth"
- "Consent form pattern: MCP OAuth shows authorize button only (no credential fields)"
requirements-completed: [AUTH-01, AUTH-02, AUTH-03]
# Metrics
duration: 4min
completed: 2026-04-04
---
# Phase 15 Plan 02: OIDC Auth Integration Summary
**Three-way auth middleware with @hono/oidc-auth for browser sessions, API keys for programmatic access, and MCP OAuth consent flow**
## Performance
- **Duration:** 4 min
- **Started:** 2026-04-04T18:42:20Z
- **Completed:** 2026-04-04T18:46:35Z
- **Tasks:** 3
- **Files modified:** 8
## Accomplishments
- Replaced custom cookie-session auth with OIDC via @hono/oidc-auth in requireAuth middleware
- Stripped auth service to API key functions only (removed all user/session management)
- Added /login, /callback, /logout OIDC routes at root level for browser auth flow
- Updated MCP OAuth to use OIDC session for authorization consent instead of password verification
- Removed getUserCount bypass from MCP auth middleware
## Task Commits
Each task was committed atomically:
1. **Task 1: Install OIDC dependencies and rewrite auth middleware + service** - `259dc2b` (feat)
2. **Task 2: Rewrite auth routes for OIDC login/callback/logout + API key CRUD** - `1b6a65b` (feat)
3. **Task 3: Update MCP OAuth authorize and MCP auth middleware for OIDC** - `c0e6db5` (feat)
## Files Created/Modified
- `package.json` - Added @hono/oidc-auth and jose dependencies
- `src/server/middleware/auth.ts` - Three-way auth: API key, MCP Bearer, OIDC session
- `src/server/services/auth.service.ts` - API key CRUD only (user/session functions removed)
- `src/server/routes/auth.ts` - GET /me with OIDC claims, API key CRUD routes
- `src/server/routes/oauth.ts` - Consent form replaces login form, getAuth replaces verifyPassword
- `src/server/mcp/index.ts` - Removed getUserCount import and bypass logic
- `src/server/index.ts` - Added root-level /login, /callback, /logout OIDC routes
## Decisions Made
- Placed OIDC browser auth routes (/login, /callback, /logout) at root level in index.ts rather than under /api/auth, keeping API key management at /api/auth/keys
- Auth check order in middleware: API key first (fast path for programmatic), Bearer token second (MCP), OIDC session third (browser)
- MCP OAuth authorize shows consent-only form when user has OIDC session, redirects to /login otherwise
## Deviations from Plan
None - plan executed exactly as written.
## Known Stubs
None - all data paths are wired to real implementations.
## Issues Encountered
None.
## User Setup Required
None - OIDC provider (Logto) configuration was handled in plan 15-01.
## Next Phase Readiness
- Server-side OIDC integration complete
- Client-side login page needs updating (plan 15-03) to redirect to /login instead of showing credential form
- E2E tests will need API key auth strategy (bypassing Logto)
## Self-Check: PASSED
All 6 modified files verified on disk. All 3 task commits verified in git log.
---
*Phase: 15-external-authentication*
*Completed: 2026-04-04*

View File

@@ -0,0 +1,121 @@
# Phase 15: External Authentication - Context
**Gathered:** 2026-04-04
**Status:** Ready for planning
<domain>
## Phase Boundary
Replace GearBox's built-in username/password authentication with Logto, a self-hosted open-source OIDC provider. Users register and log in through Logto. GearBox validates OIDC tokens instead of managing its own user credentials and sessions. API keys remain functional for programmatic access (MCP, scripts).
</domain>
<decisions>
## Implementation Decisions
### Auth Provider Choice
- **D-01:** Use **Logto** as the external auth provider (not Authentik). Logto is purpose-built for auth, lighter-weight, no Redis required, first-class OIDC support, simpler deployment.
### Session Strategy
- **D-02:** Replace GearBox's cookie-session system with OIDC-based authentication. Logto manages user sessions. GearBox validates tokens on each request.
- **D-03:** Remove the `users` and `sessions` tables from GearBox schema — user identity comes from Logto. Keep `apiKeys` table for programmatic access.
- **D-04:** The `requireAuth` middleware validates either an API key (X-API-Key header) OR an OIDC token/session from Logto. Both paths resolve to a user identity.
### Login Flow
- **D-05:** Standard OIDC redirect flow. User clicks "Login" on GearBox → redirected to Logto login page → authenticated → redirected back with authorization code → GearBox exchanges code for tokens.
- **D-06:** Registration happens on Logto's side — GearBox does not have its own registration form. Logto handles password reset, email verification, etc.
- **D-07:** The existing `/login` route becomes a redirect trigger to Logto, not a credential form.
### Existing User Migration
- **D-08:** Single user re-registers manually on Logto (one-time operation). A migration step links the Logto user ID to existing GearBox data.
- **D-09:** No automated user import — only one existing user.
### API Key Continuity
- **D-10:** API keys continue to work exactly as they do now. The `apiKeys` table remains in GearBox's schema.
- **D-11:** API key management UI stays in Settings. Creating/deleting keys requires an authenticated OIDC session.
### MCP OAuth Coexistence
- **D-12:** The existing MCP OAuth 2.1 + PKCE flow (for Claude mobile/web) coexists with Logto. MCP OAuth uses GearBox's own oauth tables; user-facing auth uses Logto. These are separate auth domains.
### Docker Compose
- **D-13:** Logto runs as a service in docker-compose alongside Postgres. Logto uses the same Postgres instance (separate database) or its own.
- **D-14:** Development docker-compose includes Logto for local auth testing.
### Claude's Discretion
- Logto SDK choice (official `@logto/node` vs generic OIDC client library)
- Token storage mechanism (httpOnly cookie with OIDC tokens, or server-side session backed by Logto)
- Logto configuration details (sign-in experience, branding, connector setup)
- Whether to use Logto's user ID directly as the foreign key in GearBox tables or maintain a mapping table
- E2E test authentication strategy (likely API keys per AUTH-05, bypassing Logto)
</decisions>
<canonical_refs>
## Canonical References
**Downstream agents MUST read these before planning or implementing.**
### Existing Auth Code (to be replaced)
- `src/server/routes/auth.ts` — Current login/logout/setup/password/keys routes
- `src/server/services/auth.service.ts` — Current user/session/API key management
- `src/server/middleware/auth.ts` — Current requireAuth middleware (API key + cookie session)
- `src/client/routes/login.tsx` — Current login page UI
### Existing MCP OAuth (to preserve)
- `src/server/routes/oauth.ts` — MCP OAuth 2.1 routes (keep separate from Logto)
- `src/server/services/oauth.service.ts` — MCP OAuth service
- `docs/superpowers/specs/2026-04-04-mcp-oauth-design.md` — MCP OAuth design spec
### Database Schema
- `src/db/schema.ts` — Current schema with users, sessions, apiKeys, oauthClients/Codes/Tokens tables
### Docker
- `docker-compose.yml` — Production compose (add Logto service)
- `docker-compose.dev.yml` — Dev compose (add Logto service)
### Requirements
- `.planning/REQUIREMENTS.md` — AUTH-01 through AUTH-05 requirements
</canonical_refs>
<code_context>
## Existing Code Insights
### Reusable Assets
- `requireAuth` middleware pattern — will be refactored but same middleware slot in Hono
- API key verification logic (`verifyApiKey`) — keeps working unchanged
- `apiKeys` table and CRUD — no changes needed
- MCP OAuth routes and service — preserved as-is, separate auth domain
### Established Patterns
- **Middleware DI**: `requireAuth` gets `db` from Hono context — same pattern continues
- **Service layer**: Auth service functions take `db` as first param — new OIDC validation functions follow same pattern
- **Cookie handling**: `hono/cookie` helpers for set/get/delete — may shift to OIDC token cookies
### Integration Points
- `src/server/middleware/auth.ts` — Primary integration point for OIDC token validation
- `src/server/index.ts` — Route registration (remove old auth routes, add OIDC callback route)
- `src/client/routes/login.tsx` — Replace credential form with Logto redirect
- `src/client/hooks/` — Auth state hooks (useAuth, etc.) need OIDC awareness
- `docker-compose.yml` / `docker-compose.dev.yml` — Add Logto service
</code_context>
<specifics>
## Specific Ideas
No specific requirements — open to standard approaches for Logto OIDC integration with Hono.
</specifics>
<deferred>
## Deferred Ideas
None — discussion stayed within phase scope
</deferred>
---
*Phase: 15-external-authentication*
*Context gathered: 2026-04-04*

View File

@@ -0,0 +1,478 @@
# Phase 15: External Authentication - Research
**Researched:** 2026-04-04
**Domain:** OIDC authentication with Logto, Hono middleware, Docker Compose
**Confidence:** HIGH
## Summary
Phase 15 replaces GearBox's built-in username/password auth with Logto, a self-hosted OIDC provider. The core integration pattern is: `@hono/oidc-auth` middleware handles the OIDC redirect flow (login/callback/logout) for browser sessions, while API key authentication remains unchanged for programmatic access (MCP tools, scripts). The existing MCP OAuth 2.1 flow (for Claude mobile/web) is a separate auth domain and must be preserved as-is.
The architecture cleanly separates three auth paths: (1) OIDC sessions for browser users via Logto, (2) API keys via X-API-Key header for programmatic access, (3) MCP OAuth Bearer tokens for Claude mobile/web. The `requireAuth` middleware becomes a three-way check. The `users` and `sessions` tables are removed from GearBox's schema -- user identity comes from Logto. The `apiKeys` table stays.
**Primary recommendation:** Use `@hono/oidc-auth` (v1.8.1) as the OIDC middleware for Hono. It provides storage-less sessions via JWT cookies, handles the authorization code flow with refresh tokens, and requires no session store. Configure it to point at the Logto instance. For API token validation in non-browser contexts, use `jose` for JWT verification against Logto's JWKS endpoint.
<user_constraints>
## User Constraints (from CONTEXT.md)
### Locked Decisions
- **D-01:** Use Logto as the external auth provider (not Authentik). Logto is purpose-built for auth, lighter-weight, no Redis required, first-class OIDC support, simpler deployment.
- **D-02:** Replace GearBox's cookie-session system with OIDC-based authentication. Logto manages user sessions. GearBox validates tokens on each request.
- **D-03:** Remove the `users` and `sessions` tables from GearBox schema -- user identity comes from Logto. Keep `apiKeys` table for programmatic access.
- **D-04:** The `requireAuth` middleware validates either an API key (X-API-Key header) OR an OIDC token/session from Logto. Both paths resolve to a user identity.
- **D-05:** Standard OIDC redirect flow. User clicks "Login" on GearBox -> redirected to Logto login page -> authenticated -> redirected back with authorization code -> GearBox exchanges code for tokens.
- **D-06:** Registration happens on Logto's side -- GearBox does not have its own registration form. Logto handles password reset, email verification, etc.
- **D-07:** The existing `/login` route becomes a redirect trigger to Logto, not a credential form.
- **D-08:** Single user re-registers manually on Logto (one-time operation). A migration step links the Logto user ID to existing GearBox data.
- **D-09:** No automated user import -- only one existing user.
- **D-10:** API keys continue to work exactly as they do now. The `apiKeys` table remains in GearBox's schema.
- **D-11:** API key management UI stays in Settings. Creating/deleting keys requires an authenticated OIDC session.
- **D-12:** The existing MCP OAuth 2.1 + PKCE flow (for Claude mobile/web) coexists with Logto. MCP OAuth uses GearBox's own oauth tables; user-facing auth uses Logto. These are separate auth domains.
- **D-13:** Logto runs as a service in docker-compose alongside Postgres. Logto uses the same Postgres instance (separate database) or its own.
- **D-14:** Development docker-compose includes Logto for local auth testing.
### Claude's Discretion
- Logto SDK choice (official `@logto/node` vs generic OIDC client library)
- Token storage mechanism (httpOnly cookie with OIDC tokens, or server-side session backed by Logto)
- Logto configuration details (sign-in experience, branding, connector setup)
- Whether to use Logto's user ID directly as the foreign key in GearBox tables or maintain a mapping table
- E2E test authentication strategy (likely API keys per AUTH-05, bypassing Logto)
### Deferred Ideas (OUT OF SCOPE)
None -- discussion stayed within phase scope.
</user_constraints>
<phase_requirements>
## Phase Requirements
| ID | Description | Research Support |
|----|-------------|------------------|
| AUTH-01 | User can register an account via external OIDC auth provider | Logto handles registration via its built-in sign-up experience. GearBox redirects to Logto, which handles the form. On first login, Logto's `sub` claim becomes the user identifier. |
| AUTH-02 | User can log in via external auth provider and access their data | `@hono/oidc-auth` middleware handles the full OIDC redirect flow. Session stored as JWT cookie. User identity extracted from OIDC claims via `getAuth(c)`. |
| AUTH-03 | API keys remain functional for programmatic access (MCP, scripts) | API key path in `requireAuth` middleware unchanged. `verifyApiKey` function and `apiKeys` table preserved as-is. |
| AUTH-04 | Auth provider runs self-hosted alongside the application | Logto Docker image `svhd/logto:latest` added to `docker-compose.yml` and `docker-compose.dev.yml`. Shares Postgres instance with separate database. |
| AUTH-05 | E2E tests authenticate via API keys without depending on the auth provider | E2E tests use `X-API-Key` header for all write operations. Seed script creates an API key. No Logto dependency in test infrastructure. |
</phase_requirements>
## Standard Stack
### Core
| Library | Version | Purpose | Why Standard |
|---------|---------|---------|--------------|
| `@hono/oidc-auth` | 1.8.1 | OIDC middleware for Hono | Purpose-built for Hono, storage-less JWT sessions, handles full auth code flow, refresh token rotation, tested with multiple OIDC providers |
| `jose` | 6.2.2 | JWT verification for API-level token validation | Standard library for JWKS-based JWT verification, used by `@hono/oidc-auth` internally (via oauth4webapi), also needed if validating Logto tokens directly |
| Logto (Docker) | latest (`svhd/logto`) | Self-hosted OIDC identity provider | Lightweight, no Redis, first-class OIDC, Postgres-backed, admin console included |
### Supporting
| Library | Version | Purpose | When to Use |
|---------|---------|---------|-------------|
| `oauth4webapi` | 3.8.5 | Low-level OAuth/OIDC client | Transitive dependency of `@hono/oidc-auth`. Not used directly unless custom token introspection needed. |
### Alternatives Considered
| Instead of | Could Use | Tradeoff |
|------------|-----------|----------|
| `@hono/oidc-auth` | `@logto/express` + adapters | Logto SDK is Express-specific, requires `express-session` dependency -- poor fit for Hono. Generic OIDC middleware is cleaner. |
| `@hono/oidc-auth` | Manual `oauth4webapi` integration | More control but significantly more code. `@hono/oidc-auth` wraps this cleanly. |
| `@hono/oidc-auth` | `@logto/node` (base SDK) | Requires building session storage adapter manually. `@hono/oidc-auth` provides storage-less sessions out of the box. |
**Recommendation:** Use `@hono/oidc-auth`. It is the idiomatic Hono solution, avoids Express dependencies, and provides storage-less sessions via JWT cookies. Logto is a standard OIDC provider, so any OIDC-compliant middleware works. No Logto-specific SDK needed on the server side.
**Installation:**
```bash
bun add @hono/oidc-auth jose
```
## Architecture Patterns
### OIDC Integration Architecture
```
Browser User Flow:
Browser -> GET /login -> redirect to Logto -> authenticate -> callback -> JWT session cookie set
Browser -> GET /api/* -> cookie sent automatically -> @hono/oidc-auth validates JWT -> request proceeds
API Key Flow (unchanged):
Client -> POST /api/* with X-API-Key header -> verifyApiKey() -> request proceeds
MCP OAuth Flow (unchanged):
Claude -> POST /mcp with Bearer token -> verifyAccessToken() -> request proceeds
```
### Recommended Changes to Project Structure
```
src/server/
middleware/
auth.ts # Refactored: OIDC session OR API key OR MCP Bearer
routes/
auth.ts # Simplified: /login redirect, /callback, /logout, /me, /keys CRUD
oauth.ts # UNCHANGED: MCP OAuth 2.1 flow preserved
services/
auth.service.ts # Simplified: remove user/session CRUD, keep API key functions
oauth.service.ts # UNCHANGED: MCP OAuth service preserved
src/client/
routes/
login.tsx # Replace form with redirect-to-Logto button
hooks/
useAuth.ts # Refactor: remove useLogin/useSetup/useChangePassword, keep useAuth/useLogout/useApiKeys
```
### Pattern 1: Auth Middleware (Three-Way Check)
**What:** The `requireAuth` middleware checks three auth methods in order: API key, MCP OAuth Bearer, OIDC session cookie.
**When to use:** All POST/PUT/PATCH/DELETE requests on `/api/*` (except `/api/auth/*`).
```typescript
// Conceptual pattern for the refactored requireAuth middleware
export async function requireAuth(c: Context, next: Next) {
const db = c.get("db");
// 1. Check API key (programmatic access)
const apiKey = c.req.header("X-API-Key");
if (apiKey) {
const valid = await verifyApiKey(db, apiKey);
if (valid) return next();
return c.json({ error: "Invalid API key" }, 401);
}
// 2. Check MCP OAuth Bearer token
const authHeader = c.req.header("Authorization");
if (authHeader?.startsWith("Bearer ")) {
const token = authHeader.slice(7);
if (await verifyAccessToken(db, token)) return next();
return c.json({ error: "invalid_token" }, 401);
}
// 3. Check OIDC session (browser users)
const auth = await getAuth(c);
if (auth) return next();
return c.json({ error: "Authentication required" }, 401);
}
```
### Pattern 2: OIDC Middleware Selective Application
**What:** `@hono/oidc-auth` middleware should only apply to browser-facing routes, not API endpoints that use API keys or MCP OAuth.
**When to use:** The OIDC middleware must NOT be applied globally to all routes. It should be scoped to browser auth routes only.
```typescript
// OIDC middleware for browser auth routes only
app.get("/callback", async (c) => processOAuthCallback(c));
app.get("/logout", async (c) => { await revokeSession(c); return c.redirect("/"); });
// Login route triggers OIDC redirect
app.get("/login", oidcAuthMiddleware()); // This redirects to Logto if no session
// For /api/* routes, use the custom requireAuth that checks all three methods
app.use("/api/*", async (c, next) => {
if (c.req.path.startsWith("/api/auth")) return next();
if (c.req.method === "GET") return next();
return requireAuth(c, next);
});
```
### Pattern 3: User Identity from OIDC Claims
**What:** After OIDC authentication, the user's identity comes from the `sub` claim in the JWT session cookie. This replaces the old `users` table lookup.
**When to use:** Anywhere user identity is needed.
```typescript
import { getAuth } from "@hono/oidc-auth";
// In a route handler or middleware
const auth = await getAuth(c);
if (auth) {
const logtoUserId = auth.sub; // Logto's unique user ID (string)
// Use this as the user identifier for data ownership in Phase 16
}
```
### Pattern 4: Logto Docker Compose Integration
**What:** Add Logto as a service that shares the Postgres instance but uses a separate database.
**When to use:** Both production and development docker-compose files.
```yaml
services:
postgres:
image: postgres:16-alpine
environment:
POSTGRES_USER: gearbox
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: gearbox
volumes:
- pgdata:/var/lib/postgresql/data
- ./docker/init-logto-db.sql:/docker-entrypoint-initdb.d/init-logto-db.sql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U gearbox"]
interval: 10s
timeout: 5s
retries: 5
logto:
image: svhd/logto:latest
depends_on:
postgres:
condition: service_healthy
entrypoint: ["sh", "-c", "npm run cli db seed -- --swe && npm start"]
ports:
- "3001:3001" # Core service
- "3002:3002" # Admin console
environment:
TRUST_PROXY_HEADER: "1"
DB_URL: postgres://gearbox:${POSTGRES_PASSWORD}@postgres:5432/logto
ENDPOINT: ${LOGTO_ENDPOINT:-http://localhost:3001}
ADMIN_ENDPOINT: ${LOGTO_ADMIN_ENDPOINT:-http://localhost:3002}
app:
# ... existing app config ...
environment:
# ... existing env vars ...
OIDC_ISSUER: ${LOGTO_ENDPOINT:-http://logto:3001}/oidc
OIDC_CLIENT_ID: ${LOGTO_CLIENT_ID}
OIDC_CLIENT_SECRET: ${LOGTO_CLIENT_SECRET}
OIDC_AUTH_SECRET: ${OIDC_AUTH_SECRET}
depends_on:
logto:
condition: service_started
```
```sql
-- docker/init-logto-db.sql
-- Creates a separate database for Logto on the shared Postgres instance
CREATE DATABASE logto;
```
### Anti-Patterns to Avoid
- **Applying `oidcAuthMiddleware()` globally:** This would break API key and MCP OAuth flows. OIDC middleware should only handle browser auth routes.
- **Storing OIDC tokens server-side in a custom sessions table:** `@hono/oidc-auth` handles this with storage-less JWT cookies. Don't recreate the sessions table.
- **Using Logto's user ID as an integer:** Logto's `sub` claim is a string (UUID-like). All foreign keys referencing user identity must use `text`, not `integer`.
- **Mixing MCP OAuth and Logto OIDC:** These are separate auth domains. MCP OAuth uses GearBox's own `oauthClients/Codes/Tokens` tables. Logto OIDC uses `@hono/oidc-auth` JWT cookies. They must not interfere.
## Don't Hand-Roll
| Problem | Don't Build | Use Instead | Why |
|---------|-------------|-------------|-----|
| OIDC authorization code flow | Custom redirect/callback/token exchange | `@hono/oidc-auth` middleware | PKCE, nonce validation, token rotation, cookie security are all handled |
| Session JWT creation/validation | Custom JWT sign/verify | `@hono/oidc-auth` internal JWT session | Handles refresh intervals, expiry, cookie security flags |
| JWKS key fetching/caching | Custom HTTP fetch + cache | `jose` library (`createRemoteJWKSet`) | Handles key rotation, caching, concurrent requests |
| Logto database initialization | Custom SQL scripts | Logto's built-in `npm run cli db seed -- --swe` | Schema is complex, versioned, and must match the Logto runtime |
**Key insight:** The entire OIDC flow (redirect, callback, token exchange, session management, token refresh) is handled by `@hono/oidc-auth`. The only custom code needed is the `requireAuth` middleware that orchestrates the three auth paths (API key, MCP OAuth, OIDC session).
## Common Pitfalls
### Pitfall 1: OIDC Issuer URL Mismatch Between Docker Internal and External
**What goes wrong:** Logto's OIDC issuer URL must be accessible from both the browser (external: `http://localhost:3001`) and the app container (internal: `http://logto:3001`). If the issuer in the JWT doesn't match what the app expects, token validation fails.
**Why it happens:** Docker networking uses internal hostnames, but the browser redirects use external URLs.
**How to avoid:** Set `ENDPOINT` on Logto to the externally-accessible URL (`http://localhost:3001` for dev). Set `OIDC_ISSUER` on the app to the same external URL. Both the browser redirect and server-side validation must use the same issuer string.
**Warning signs:** "issuer mismatch" errors during token validation; login redirects work but callback fails.
### Pitfall 2: Cookie Domain/Path Conflicts
**What goes wrong:** `@hono/oidc-auth` sets its own session cookie (`oidc-auth` by default). If GearBox's old `gearbox_session` cookie is still being set or checked, auth state gets confused.
**Why it happens:** Incomplete removal of old session code.
**How to avoid:** Completely remove all `gearbox_session` cookie handling. Remove the `sessions` table. Clean up the old auth service functions. The only session cookie should be the one managed by `@hono/oidc-auth`.
**Warning signs:** Users appear logged in but get 401s on writes, or vice versa.
### Pitfall 3: MCP OAuth POST /oauth/authorize Still Validates Against Removed Users Table
**What goes wrong:** The MCP OAuth flow's `/oauth/authorize` POST handler calls `verifyPassword()`, which queries the now-removed `users` table.
**Why it happens:** MCP OAuth was built to use GearBox's internal auth. When the users table is removed, this breaks.
**How to avoid:** The MCP OAuth authorize form must be updated to validate against the OIDC session instead of username/password. If the user has a valid OIDC session, they can authorize MCP clients. If not, redirect to Logto first.
**Warning signs:** MCP OAuth authorize endpoint returns 500 errors after users table is removed.
### Pitfall 4: E2E Tests Break Because Seed Script Creates Users in Removed Table
**What goes wrong:** The E2E seed script (`e2e/seed.ts`) inserts into the `users` table, which no longer exists. All E2E tests fail.
**Why it happens:** Seed script wasn't updated for the new auth model.
**How to avoid:** Update seed script to create an API key directly (insert into `apiKeys` table only). E2E tests authenticate via `X-API-Key` header per AUTH-05. Remove user creation from seed.
**Warning signs:** Seed script crashes on startup; all E2E tests fail before any assertions.
### Pitfall 5: `getUserCount` Check in Old Middleware
**What goes wrong:** The old `requireAuth` middleware checks `getUserCount(db) === 0` and returns `setup_required`. With the users table removed, this call fails.
**Why it happens:** The "first-run setup" flow assumed GearBox managed its own users.
**How to avoid:** Remove the `getUserCount` check entirely. First-run setup now happens on Logto's admin console. GearBox doesn't need to know if users exist -- it just validates tokens.
**Warning signs:** 500 errors on any protected endpoint after removing users table.
### Pitfall 6: OIDC_AUTH_SECRET Not Set
**What goes wrong:** `@hono/oidc-auth` requires `OIDC_AUTH_SECRET` (min 32 chars) to sign session JWTs. If not set, the middleware crashes on startup.
**Why it happens:** Missing from environment configuration.
**How to avoid:** Generate a random 32+ character secret and set it in `.env` / docker-compose. Document this in setup instructions.
**Warning signs:** Startup crash with "OIDC_AUTH_SECRET is required" or similar error.
## Code Examples
### @hono/oidc-auth Configuration for Logto
```typescript
// Environment variables required:
// OIDC_ISSUER=http://localhost:3001/oidc (Logto's OIDC endpoint)
// OIDC_CLIENT_ID=<from Logto admin console>
// OIDC_CLIENT_SECRET=<from Logto admin console>
// OIDC_AUTH_SECRET=<random 32+ char string for JWT signing>
// OIDC_REDIRECT_URI=/callback (default)
import { Hono } from "hono";
import {
oidcAuthMiddleware,
getAuth,
revokeSession,
processOAuthCallback,
} from "@hono/oidc-auth";
const app = new Hono();
// Callback route - processes the OIDC redirect from Logto
app.get("/callback", async (c) => {
return processOAuthCallback(c);
});
// Logout route
app.get("/logout", async (c) => {
await revokeSession(c);
return c.redirect("/login");
});
// Login route - redirects to Logto
app.get("/login", oidcAuthMiddleware(), async (c) => {
// If we reach here, user is authenticated (middleware redirects if not)
return c.redirect("/");
});
```
### Checking Auth State in API Routes
```typescript
import { getAuth } from "@hono/oidc-auth";
// In the /api/auth/me handler
app.get("/api/auth/me", async (c) => {
const auth = await getAuth(c);
if (auth) {
return c.json({
user: { id: auth.sub, email: auth.email },
authenticated: true,
});
}
return c.json({ user: null, authenticated: false });
});
```
### Logto Application Setup (Admin Console)
```
1. Access Logto Admin Console at http://localhost:3002
2. Create a new "Traditional Web" application
3. Set redirect URI: http://localhost:3000/callback
4. Set post-logout redirect URI: http://localhost:3000/login
5. Copy App ID -> OIDC_CLIENT_ID
6. Copy App Secret -> OIDC_CLIENT_SECRET
7. OIDC_ISSUER = http://localhost:3001/oidc
```
## State of the Art
| Old Approach | Current Approach | When Changed | Impact |
|--------------|------------------|--------------|--------|
| Custom user/session tables | OIDC provider (Logto) | This phase | Remove users/sessions tables, auth service simplification |
| Password hashing in app | Delegated to Logto | This phase | Remove Bun.password.hash usage for users (keep for API keys) |
| Login form in GearBox | Redirect to Logto | This phase | Login page becomes a redirect trigger |
| `@logto/express` SDK | `@hono/oidc-auth` | N/A | Hono-native, no Express dependencies |
## Open Questions
1. **Logto User ID Format**
- What we know: Logto's `sub` claim is a string identifier
- What's unclear: Exact format (UUID? custom ID?)
- Recommendation: Use `text` type for user ID columns. Will be confirmed during Logto setup. This prepares for Phase 16 (Multi-User Data Model) which adds `userId` columns to all data tables.
2. **MCP OAuth Authorize Form After Users Table Removal**
- What we know: The MCP OAuth `/oauth/authorize` POST handler currently calls `verifyPassword()` against the `users` table
- What's unclear: Best UX for MCP OAuth authorization after migration
- Recommendation: Check for an active OIDC session when the user hits the authorize page. If authenticated via OIDC, auto-approve or show a simplified consent screen. If not, redirect to Logto first, then back to the authorize page.
3. **Logto Shared Postgres vs Separate Instance**
- What we know: D-13 says Logto can share the Postgres instance (separate database) or use its own
- Recommendation: Share the Postgres instance with a separate `logto` database. Simpler infrastructure, one fewer container. Use a Postgres init script to create the `logto` database on first run.
## Environment Availability
| Dependency | Required By | Available | Version | Fallback |
|------------|------------|-----------|---------|----------|
| Docker | Logto deployment | Needs verification at runtime | -- | Cannot proceed without Docker |
| Docker Compose | Service orchestration | Needs verification at runtime | -- | Cannot proceed without Compose |
| PostgreSQL | Logto + GearBox data | Available (via docker-compose) | 16-alpine | -- |
| Bun | Runtime | Available | Project runtime | -- |
**Missing dependencies with no fallback:**
- Docker and Docker Compose are required for Logto. These are assumed present since the project already has `docker-compose.yml` and `docker-compose.dev.yml`.
## Validation Architecture
### Test Framework
| Property | Value |
|----------|-------|
| Framework | Bun test runner + Playwright |
| Config file | `bunfig.toml` (Bun), `playwright.config.ts` (E2E) |
| Quick run command | `bun test tests/middleware/auth.test.ts` |
| Full suite command | `bun test && bun run test:e2e` |
### Phase Requirements -> Test Map
| Req ID | Behavior | Test Type | Automated Command | File Exists? |
|--------|----------|-----------|-------------------|-------------|
| AUTH-01 | User registers via Logto OIDC | manual | N/A (requires running Logto) | N/A -- manual verification |
| AUTH-02 | User logs in via Logto OIDC | manual | N/A (requires running Logto) | N/A -- manual verification |
| AUTH-03 | API keys work for programmatic access | unit | `bun test tests/middleware/auth.test.ts -x` | Exists (needs update) |
| AUTH-04 | Logto runs in Docker Compose | integration | `docker compose -f docker-compose.dev.yml up -d && curl http://localhost:3001/oidc/.well-known/openid-configuration` | Wave 0 |
| AUTH-05 | E2E tests use API keys, no Logto dependency | e2e | `bun run test:e2e` | Exists (needs update) |
### Sampling Rate
- **Per task commit:** `bun test tests/middleware/auth.test.ts`
- **Per wave merge:** `bun test`
- **Phase gate:** `bun test && bun run test:e2e`
### Wave 0 Gaps
- [ ] Update `tests/middleware/auth.test.ts` -- remove user/session tests, add OIDC session mock
- [ ] Update `tests/services/auth.service.test.ts` -- remove user/session tests, keep API key tests
- [ ] Update `tests/routes/auth.test.ts` -- update for new auth route structure
- [ ] Update `e2e/seed.ts` -- remove users table insert, add API key seed
- [ ] Update `e2e/auth.spec.ts` -- replace login form tests with redirect-based flow or API key auth
## Project Constraints (from CLAUDE.md)
- **Routing:** TanStack Router with file-based routes. `routeTree.gen.ts` auto-generated -- never edit manually.
- **Data fetching:** TanStack React Query hooks. Auth state via `useAuth` hook.
- **Testing:** Bun test runner for unit/integration, Playwright for E2E. Test helpers in `tests/helpers/db.ts`.
- **Styling:** Tailwind CSS v4.
- **Services pattern:** Pure business logic functions that take a db instance. No HTTP awareness.
- **Path alias:** `@/*` maps to `./src/*`.
- **Branching:** Create feature branch off Develop for this work.
- **Lint:** Biome (tabs, double quotes, organized imports).
- **Build:** `bun run build` outputs to `dist/client/`.
- **Auth pattern:** Public-read, authenticated-write. POST/PUT/DELETE require auth on `/api/*` except `/api/auth/*`.
## Sources
### Primary (HIGH confidence)
- [Logto OSS Deployment Docs](https://docs.logto.io/logto-oss/deployment-and-configuration) -- Docker setup, environment variables, Postgres requirements
- [Logto Access Token Validation](https://docs.logto.io/authorization/validate-access-tokens) -- JWT validation with jose, JWKS URI, claims verification
- [@hono/oidc-auth README](https://www.npmjs.com/package/@hono/oidc-auth) -- Configuration, exported functions, session handling, env vars
- [Logto Official Docker Compose](https://github.com/logto-io/logto/blob/master/docker-compose.yml) -- Official compose file structure
- Existing codebase analysis -- `src/server/middleware/auth.ts`, `src/server/routes/auth.ts`, `src/server/routes/oauth.ts`, `src/server/mcp/index.ts`
### Secondary (MEDIUM confidence)
- [Logto Express Tutorial](https://tutorials.logto.io/how-to/build-oidc-sign-in-with-express-and-logto/) -- Express SDK patterns (not directly used but informative for flow understanding)
- [Logto OIDC Integration Guide](https://blog.logto.io/complete-guide-to-integrating-oidc-server) -- General OIDC integration patterns
### Tertiary (LOW confidence)
- None -- all findings verified with official sources
## Metadata
**Confidence breakdown:**
- Standard stack: HIGH -- `@hono/oidc-auth` is the official Hono OIDC middleware, well-documented, actively maintained
- Architecture: HIGH -- OIDC redirect flow is standard, three-way auth middleware is straightforward
- Pitfalls: HIGH -- Based on direct analysis of existing codebase and known OIDC integration issues
- Docker/Logto setup: MEDIUM -- Official compose file verified, but Logto version pinning and Postgres sharing need runtime validation
**Research date:** 2026-04-04
**Valid until:** 2026-05-04 (30 days -- stable domain, Logto has regular but non-breaking releases)