Files
opencode-manager/backend/src/auth/middleware.ts
T
Chris Scott 5de419ee28 fix issues (#136)
* fix: prevent delete button click when card is not swiped open

* refactor: improve CreateRepoInput type safety

* security: require AUTH_SECRET and use secure random generation

* fix: SSH key path validation, async passphrase stripping, and port handling

* fix: use correct console methods for logger levels

* Add error handling to DB update functions and improve migration logging

* Add error handling for session lookup in auth middleware

* Add structured git error handling with user-friendly messages

- Parse git errors with specific error codes (AUTH_FAILED, REPO_NOT_FOUND,
  PUSH_REJECTED, MERGE_CONFLICT, etc.) and appropriate HTTP status codes
- Return structured error responses with summary and detail from backend
- Add GitErrorBanner component for better error display in UI
- Add optional onError callback to useGit hook for external error handling

* Make IPC server initialization/disposal async and fix SSH host key handler

* add try-catch error handling in frontend lib utilities

* remove unresolved promise handlers in speech synthesizer callbacks

* Extract error types to shared package

* Import GitErrorCode from shared package

* Refactor API layer to use shared FetchError and fetchWrapper

* Update prompt parser and source control components

* Extract MCP server list to separate component with improved badge menu UX

* merge useSettingsDialogUrl into useSettingsDialog and extract getRepoDisplayName utility

* add separate loading state for passkey sign in

* refactor hooks: use fetchWrapper, improve error handling, add proper types

* replace browser confirm() with DeleteDialog component in settings

* fix: add missing variables parameter in React Query onError callbacks

* Refactor message parts to use separate Zustand store

* Update QuestionPrompt styling for light/dark mode
2026-02-15 19:48:03 -05:00

102 lines
2.6 KiB
TypeScript

import { createMiddleware } from 'hono/factory'
import type { AuthInstance, Session } from './index'
import { logger } from '../utils/logger'
export function createAuthMiddleware(auth: AuthInstance) {
return createMiddleware<{
Variables: {
session: Session['session']
user: Session['user']
}
}>(async (c, next) => {
const cookies = c.req.header('cookie')
const origin = c.req.header('origin')
logger.debug(`Auth check - Path: ${c.req.path}, Origin: ${origin}, Has cookies: ${!!cookies}`)
if (cookies) {
const cookieNames = cookies.split(';').map(c => c.trim().split('=')[0]).join(', ')
logger.debug(`Cookie names: ${cookieNames}`)
}
let session
try {
session = await auth.api.getSession({
headers: c.req.raw.headers,
})
} catch (error) {
logger.error('Session lookup failed', { error })
return c.json({ error: 'Internal Server Error' }, 500)
}
logger.debug(`Session result: ${session ? 'found' : 'not found'}`)
if (!session) {
return c.json({ error: 'Unauthorized' }, 401)
}
c.set('session', session.session as Session['session'])
c.set('user', session.user as Session['user'])
await next()
})
}
export function createOptionalAuthMiddleware(auth: AuthInstance) {
return createMiddleware<{
Variables: {
session: Session['session'] | null
user: Session['user'] | null
}
}>(async (c, next) => {
try {
const session = await auth.api.getSession({
headers: c.req.raw.headers,
})
if (session) {
c.set('session', session.session as Session['session'])
c.set('user', session.user as Session['user'])
} else {
c.set('session', null)
c.set('user', null)
}
} catch {
c.set('session', null)
c.set('user', null)
}
await next()
})
}
export function createAdminMiddleware(auth: AuthInstance) {
return createMiddleware<{
Variables: {
session: Session['session']
user: Session['user']
}
}>(async (c, next) => {
let session
try {
session = await auth.api.getSession({
headers: c.req.raw.headers,
})
} catch (error) {
logger.error('Session lookup failed', { error })
return c.json({ error: 'Internal Server Error' }, 500)
}
if (!session) {
return c.json({ error: 'Unauthorized' }, 401)
}
const user = session.user as Session['user']
if (user.role !== 'admin') {
return c.json({ error: 'Forbidden: Admin access required' }, 403)
}
c.set('session', session.session as Session['session'])
c.set('user', user)
await next()
})
}