Compare commits

..

6 Commits

18 changed files with 620 additions and 371 deletions

View File

@ -97,6 +97,8 @@ npm run import # 导入设备数据
| POST | `/api/auth/logout` | 登出(清除两个 cookie |
| GET | `/api/auth/me` | 当前用户信息 |
| GET | `/api/internal/roles` | 内部 API返回角色列表x-internal-key 鉴权) |
| GET | `/api/internal/users` | 内部 API返回用户列表x-internal-key 鉴权) |
| POST | `/api/internal/users` | 内部 APIOA 同步用户角色x-internal-key 鉴权) |
### 资产

View File

@ -19,6 +19,6 @@ RUN npm install --omit=dev && \
node_modules/@next/swc-linux-x64-musl
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public
RUN mkdir -p /app/data /app/uploads
RUN apt-get update && apt-get install -y --no-install-recommends sqlite3 && rm -rf /var/lib/apt/lists/* && mkdir -p /app/data /app/uploads
EXPOSE 3000
CMD ["node", "server.js"]
CMD ["sh", "-c", "HOSTNAME=0.0.0.0 node server.js"]

View File

@ -9,15 +9,17 @@ services:
- assets-uploads:/app/uploads
# .next 目录从主机挂载,主机上 npm run build 后直接生效
- ./.next:/app/.next
# 运行时从 LLDAP 容器动态读取 admin 密码
- /var/run/docker.sock:/var/run/docker.sock
# 运行时从 LLDAP 容器动态读取 admin 密码(已迁移至环境变量注入)
- /var/run/docker.sock:/var/run/docker.sock:ro
environment:
- DATABASE_PATH=/app/data/assets.db
- JWT_SECRET=oa-shared-jwt-secret-tlyq-2026
- JWT_SECRET=${JWT_SECRET:-oa-shared-jwt-secret-tlyq-2026}
- ADMIN_PASSWORD=${ADMIN_PASSWORD:-admin123}
- LLDAP_ADMIN_PASSWORD=${LLDAP_ADMIN_PASSWORD}
- NODE_ENV=production
- COOKIE_DOMAIN=.tlyq.ai
- TZ=Asia/Shanghai
- NODE_TLS_REJECT_UNAUTHORIZED=0
- AUTHELIA_URL=${AUTHELIA_URL:-https://sso.tlyq.ai}
- LDAP_URL=ldap://lldap:3890
- LDAP_BASE_DN=dc=tlyq,dc=ai
@ -34,6 +36,12 @@ services:
- OIDC_CLIENT_ID=${OIDC_CLIENT_ID:-assets-oidc}
- OIDC_CLIENT_SECRET=${OIDC_CLIENT_SECRET}
- OIDC_REDIRECT_URI=${OIDC_REDIRECT_URI:-https://assets.tlyq.ai/api/auth/callback}
healthcheck:
test: ["CMD", "node", "-e", "fetch('http://localhost:3000/api/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"]
interval: 30s
timeout: 5s
retries: 3
start_period: 40s
restart: unless-stopped
networks:
- webnet

View File

@ -1,77 +1,7 @@
'use client'
import { useState } from 'react'
// 登录表单 — 引用共享组件
import LoginPage from '@shared/ui/login-page'
export function LoginForm() {
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const [showLdapForm, setShowLdapForm] = useState(false)
async function handleSubmit(e: React.FormEvent) {
e.preventDefault(); setError(''); setLoading(true)
try {
const res = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) })
const data = await res.json()
if (!res.ok) { setError(data.error || '登录失败'); return }
const params = new URLSearchParams(window.location.search)
const redirect = params.get('redirect')
const dest = (redirect && redirect.startsWith('/')) ? redirect : '/dashboard'
window.location.href = dest
} catch { setError('网络错误,请重试') }
finally { setLoading(false) }
}
function handleSsoLogin() {
window.location.href = '/api/auth/login/oidc'
}
return (
<div className="min-h-screen flex items-center justify-center bg-slate-50 dark:bg-slate-950 px-4">
<div className="w-full max-w-sm bg-white dark:bg-slate-900 rounded-lg border border-blue-200/50 dark:border-blue-500/20 shadow-lg p-8">
<h1 className="text-2xl font-bold text-center mb-6 text-slate-900 dark:text-white"></h1>
{error && <div className="mb-4 p-3 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-600 dark:text-red-400 text-sm">{error}</div>}
{!showLdapForm ? (
<>
<button onClick={handleSsoLogin} className="w-full py-2 px-4 rounded-lg bg-blue-600 hover:bg-blue-700 text-white font-medium transition-colors duration-200 mb-3">
</button>
<p className="text-center text-xs text-slate-400 mb-3"> SSO </p>
<p className="text-center mb-2">
<button onClick={() => { window.location.href = '/api/auth/login/oidc?switch=1' }} className="text-xs text-slate-400 hover:text-slate-600 underline">
使
</button>
</p>
<p className="text-center">
<button onClick={() => setShowLdapForm(true)} className="text-xs text-slate-400 hover:text-slate-600 underline">
使 LDAP
</button>
</p>
</>
) : (
<>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1"></label>
<input type="text" value={username} onChange={e => setUsername(e.target.value)} placeholder="请输入用户名"
className="w-full px-3 py-2 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" required />
</div>
<div>
<label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1"></label>
<input type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="请输入密码"
className="w-full px-3 py-2 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" required />
</div>
<button type="submit" disabled={loading} className="w-full py-2 px-4 rounded-lg bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white font-medium transition-colors duration-200">{loading ? '登录中...' : '登录'}</button>
</form>
<p className="text-center mt-3">
<button onClick={() => setShowLdapForm(false)} className="text-xs text-slate-400 hover:text-slate-600 underline">
</button>
</p>
</>
)}
</div>
</div>
)
return <LoginPage siteName="资产管理系统" redirectPath="/dashboard" />
}

View File

@ -1,121 +1,51 @@
import { NextResponse } from 'next/server'
import { cookies } from 'next/headers'
import { getOidcClient } from '@/lib/oidc'
import { signJwt } from '@/lib/auth'
import { signSharedJwt, sharedCookieConfig } from '@/lib/jwt'
// GET /api/auth/callback — OIDC callbackV2使用 shared handleOidcCallback 工厂)
import { NextRequest } from 'next/server'
import { handleOidcCallback } from '@shared/lib/auth/handle-callback'
import db from '@/lib/db'
import { ldapGetUserInfo } from '@/lib/ldap'
import { writeAuditLog } from '@/lib/audit'
function getBaseUrl(): string {
const redirectUri = process.env.OIDC_REDIRECT_URI || 'http://127.0.0.1:6177/api/auth/callback'
const url = new URL(redirectUri)
return `${url.protocol}//${url.host}`
}
const autheliaUrl = process.env.AUTHELIA_URL || 'https://sso.tlyq.ai'
const oidcClientId = process.env.OIDC_CLIENT_ID || 'assets-oidc'
const oidcClientSecret = process.env.OIDC_CLIENT_SECRET || ''
const oidcRedirectUri = process.env.OIDC_REDIRECT_URI || 'https://assets.tlyq.ai/api/auth/callback'
const jwtSecret = process.env.JWT_SECRET || 'oa-shared-jwt-secret-tlyq-2026'
const cookieDomain = process.env.COOKIE_DOMAIN || '.tlyq.ai'
export async function GET(request: Request) {
const { searchParams } = new URL(request.url)
const code = searchParams.get('code')
const state = searchParams.get('state')
const error = searchParams.get('error')
const baseUrl = getBaseUrl()
export async function GET(request: NextRequest) {
return handleOidcCallback(request, {
oidc: { autheliaUrl, clientId: oidcClientId, clientSecret: oidcClientSecret, redirectUri: oidcRedirectUri },
jwtSecret,
cookieDomain,
const cookieStore = await cookies()
// 1. 错误处理
if (error) {
return NextResponse.redirect(new URL(`/login?error=${error}`, baseUrl))
}
// 2. 验证 state
const savedState = cookieStore.get('oidc_state')?.value
if (!savedState || savedState !== state) {
return NextResponse.redirect(new URL('/login?error=state_mismatch', baseUrl))
}
// 3. 取出 code_verifier
const codeVerifier = cookieStore.get('oidc_code_verifier')?.value
if (!codeVerifier) {
return NextResponse.redirect(new URL('/login?error=missing_verifier', baseUrl))
}
// 4. 验证 nonce
const savedNonce = cookieStore.get('oidc_nonce')?.value
try {
// 5. 换取 token
const client = await getOidcClient()
const redirectUri = process.env.OIDC_REDIRECT_URI || 'http://127.0.0.1:6177/api/auth/callback'
const params = { code, state, iss: searchParams.get('iss') }
const checks = {
code_verifier: codeVerifier,
nonce: savedNonce,
state: savedState,
}
const tokenSet = await client.callback(redirectUri, params, checks)
// 6. 获取 userinfo
const userinfo = await client.userinfo(tokenSet.access_token!)
// 7. 处理用户
const username = (userinfo as any).preferred_username || userinfo.sub!
const displayName = userinfo.name || username
// 查找本地用户
let user = db.prepare(
getUser: (username) => {
const row = db.prepare(
'SELECT id, username, role FROM users WHERE username = ? AND is_active = 1'
).get(username) as { id: number; username: string; role: string } | undefined
).get(username) as { id: number; role: string } | undefined
return row ? { id: row.id, role: row.role } : null
},
if (!user) {
// 自动创建viewer 角色)
const ldapInfo = await ldapGetUserInfo(username)
const ldapDisplayName = ldapInfo?.displayName || displayName
const email = ldapInfo?.email ?? null
createUser: (username, displayName, email) => {
db.prepare(
"INSERT OR IGNORE INTO users (username, display_name, email, role, is_active, created_at, updated_at) VALUES (?, ?, ?, 'viewer', 1, datetime('now', '+8 hours'), datetime('now', '+8 hours'))"
).run(username, ldapDisplayName, email)
user = db.prepare(
'SELECT id, username, role FROM users WHERE username = ? AND is_active = 1'
).get(username) as { id: number; username: string; role: string }
}
).run(username, displayName, email)
const row = db.prepare(
'SELECT id, role FROM users WHERE username = ? AND is_active = 1'
).get(username) as { id: number; role: string }
return { id: row?.id ?? 0, role: row?.role ?? 'viewer' }
},
// 更新登录时间
db.prepare("UPDATE users SET last_login_at = datetime('now', '+8 hours'), last_active_at = datetime('now', '+8 hours') WHERE id = ?").run(user!.id)
updateUser: (username, displayName, email) => {
db.prepare(
"UPDATE users SET display_name = ?, email = ?, updated_at = datetime('now', '+8 hours') WHERE username = ?"
).run(displayName, email, username)
},
// 8. 签发两个 cookie
const localToken = signJwt({ userId: user!.id, username: user!.username, role: user!.role })
const sharedToken = signSharedJwt({ username, displayName })
const response = NextResponse.redirect(new URL('/', baseUrl))
response.cookies.set('session_assets', localToken, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 86400,
path: '/',
onAuditLog: (userId, username, req) => {
writeAuditLog({
userId, username, action: 'login', entityType: 'auth',
details: { method: 'oidc' },
ipAddress: req.headers.get('x-forwarded-for') || '127.0.0.1',
})
response.cookies.set(sharedCookieConfig().name, sharedToken, sharedCookieConfig())
// 9. 存储 id_token 用于登出
if (tokenSet.id_token) {
response.cookies.set('oidc_id_token', tokenSet.id_token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 86400,
path: '/',
},
})
}
// 10. 清理 OIDC 临时 cookie
response.cookies.delete('oidc_state')
response.cookies.delete('oidc_nonce')
response.cookies.delete('oidc_code_verifier')
return response
} catch (e) {
const errorMsg = e instanceof Error ? e.message : String(e)
console.error('OIDC callback error:', errorMsg)
return NextResponse.redirect(new URL(`/login?error=callback_error&detail=${encodeURIComponent(errorMsg)}`, baseUrl))
}
}

View File

@ -1,81 +1,13 @@
import { NextResponse } from 'next/server'
import { cookies } from 'next/headers'
import { getOidcClient, generatePKCE, generateState, generateNonce } from '@/lib/oidc'
import { verifySharedJwt } from '@/lib/jwt'
// GET /api/auth/login/oidc — OIDC SSO 重定向V2使用 shared handleOidcLogin 工厂)
import { handleOidcLogin } from '@shared/lib/auth/handle-login'
const autheliaUrl = process.env.AUTHELIA_URL || 'https://sso.tlyq.ai'
const oidcClientId = process.env.OIDC_CLIENT_ID || 'assets-oidc'
const oidcClientSecret = process.env.OIDC_CLIENT_SECRET || ''
const oidcRedirectUri = process.env.OIDC_REDIRECT_URI || 'https://assets.tlyq.ai/api/auth/callback'
export async function GET(request: Request) {
const cookieStore = await cookies()
const existingSession = cookieStore.get('tlyq_session')?.value
const url = new URL(request.url)
const switchUser = url.searchParams.get('switch') === '1'
// 检查是否已有登录用户
if (existingSession && !switchUser) {
const existing = verifySharedJwt(existingSession)
if (existing) {
return NextResponse.json({
conflict: true,
currentUser: existing.username,
displayName: existing.displayName,
})
}
}
// 预检 Authelia 健康状态
const autheliaUrl = process.env.AUTHELIA_URL || 'https://sso.tlyq.ai'
try {
const healthRes = await fetch(`${autheliaUrl}/api/health`, {
signal: AbortSignal.timeout(5000),
})
if (!healthRes.ok) {
return NextResponse.json({ fallback: 'ldap', error: 'Authelia 不可用' }, { status: 503 })
}
} catch {
return NextResponse.json({ fallback: 'ldap', error: 'Authelia 不可达' }, { status: 503 })
}
// 生成 PKCE 参数
const { codeVerifier, codeChallenge } = generatePKCE()
const state = generateState()
const nonce = generateNonce()
// 构建授权 URL
const client = await getOidcClient()
const authorizationUrl = client.authorizationUrl({
scope: 'openid profile email',
state,
nonce,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
...(switchUser && { prompt: 'login' }),
})
// 存储到 httpOnly cookie5 分钟过期)
const response = NextResponse.redirect(authorizationUrl)
response.cookies.set('oidc_code_verifier', codeVerifier, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 300,
path: '/',
})
response.cookies.set('oidc_state', state, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 300,
path: '/',
})
response.cookies.set('oidc_nonce', nonce, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 300,
path: '/',
})
return response
return handleOidcLogin({ autheliaUrl, clientId: oidcClientId, clientSecret: oidcClientSecret, redirectUri: oidcRedirectUri, switchUser })
}

View File

@ -1,29 +1,25 @@
// GET + POST /api/auth/logout — 退出登录(清除 cookie + 302 跳转 /login
import { NextResponse } from 'next/server'
import { cookies } from 'next/headers'
import { getSession } from '@/lib/auth'
import { writeAuditLog, getClientIP } from '@/lib/audit'
export async function POST(request: Request) {
const session = await getSession()
const cookieStore = await cookies()
const domain = process.env.COOKIE_DOMAIN || ''
const cookieDomain = process.env.COOKIE_DOMAIN || '.tlyq.ai'
// 清除 cookie 时必须指定与设置时相同的 domain
cookieStore.set('session_assets', '', { maxAge: 0, path: '/', domain })
cookieStore.set('tlyq_session', '', { maxAge: 0, path: '/', domain })
cookieStore.set('oidc_id_token', '', { maxAge: 0, path: '/', domain })
if (session) {
writeAuditLog({
userId: session.userId,
apiKeyId: null,
action: 'logout',
entityType: 'auth',
entityId: session.userId,
details: { username: session.username },
ipAddress: getClientIP(request)
})
}
return NextResponse.json({ success: true })
/** 从 OIDC_REDIRECT_URI 提取 site URL不可信请求头见 LESSONS-LEARNED #51 */
function getSiteUrl(): string {
const redirectUri = process.env.OIDC_REDIRECT_URI || ''
try { const u = new URL(redirectUri); return `${u.protocol}//${u.host}` } catch { /* fallthrough */ }
return process.env.NEXT_PUBLIC_SITE_URL || 'https://assets.tlyq.ai'
}
/** 清除 tlyq_session + session cookie → 302 跳转 /login */
function logoutResponse(): NextResponse {
const response = NextResponse.redirect(new URL('/login', getSiteUrl()))
response.cookies.set('tlyq_session', '', {
httpOnly: true, secure: process.env.NODE_ENV === 'production',
sameSite: 'lax', domain: cookieDomain, path: '/', maxAge: 0,
})
response.cookies.set('session', '', { path: '/', maxAge: 0 })
return response
}
export async function GET() { return logoutResponse() }
export async function POST() { return logoutResponse() }

View File

@ -0,0 +1,2 @@
import { NextResponse } from 'next/server'
export async function GET() { return NextResponse.json({ status: 'OK' }) }

View File

@ -0,0 +1,23 @@
// PUT /api/internal/users/role — 供 OA 修改用户角色
import { NextResponse } from 'next/server'
import { execFileSync } from 'child_process'
const INTERNAL_KEY = process.env.INTERNAL_API_KEY || 'oa-internal-key-tlyq-2026'
const DB_PATH = process.env.DATABASE_PATH || '/app/data/assets.db'
export async function PUT(request: Request) {
const key = request.headers.get('x-internal-key')
if (key !== INTERNAL_KEY) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
try {
const { username, role } = await request.json()
if (!username || !role) return NextResponse.json({ error: '参数不完整' }, { status: 400 })
execFileSync('sqlite3', [DB_PATH], {
input: `UPDATE users SET role='${role}', updated_at=datetime('now', '+8 hours') WHERE username='${username}';`,
timeout: 3000,
})
return NextResponse.json({ success: true })
} catch {
return NextResponse.json({ error: '更新失败' }, { status: 500 })
}
}

View File

@ -0,0 +1,41 @@
// GET /api/internal/users — 供 OA 查询 assets 用户列表
// POST /api/internal/users — 供 OA 同步用户角色
import { NextRequest, NextResponse } from 'next/server'
import db from '@/lib/db'
const INTERNAL_KEY = process.env.INTERNAL_API_KEY || 'oa-internal-key-tlyq-2026'
export async function GET(request: NextRequest) {
const key = request.headers.get('x-internal-key')
if (key !== INTERNAL_KEY) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const users = db.prepare(
'SELECT username, display_name, role FROM users WHERE is_active = 1 ORDER BY username'
).all() as { username: string; display_name: string; role: string }[]
return NextResponse.json({ users })
}
export async function POST(request: NextRequest) {
const key = request.headers.get('x-internal-key')
if (key !== INTERNAL_KEY) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const body = await request.json()
const { username, displayName, role } = body
if (!username) {
return NextResponse.json({ error: 'username 必填' }, { status: 400 })
}
const VALID_ROLES = ['admin', 'editor', 'viewer']
const safeRole = VALID_ROLES.includes(role) ? role : 'viewer'
try {
db.prepare(
`INSERT INTO users (username, password_hash, display_name, role, is_active, created_at, updated_at)
VALUES (?, '', ?, ?, 1, datetime('now', '+8 hours'), datetime('now', '+8 hours'))
ON CONFLICT(username) DO UPDATE SET role = ?, display_name = ?,
updated_at = datetime('now', '+8 hours')`
).run(username, displayName || username, safeRole, safeRole, displayName || username)
return NextResponse.json({ success: true })
} catch {
return NextResponse.json({ error: '同步失败' }, { status: 500 })
}
}

View File

@ -1,12 +1,15 @@
@import "tailwindcss";
@config "../../tailwind.config.js";
@custom-variant dark (&:where(.dark, .dark *));
@source "../../shared";
@source "../../src";
@import './tlyq-design-system.css' layer(base);
@layer base {
body {
@apply bg-slate-50 text-slate-900;
}
html.dark body {
@apply bg-slate-950 text-white;
font-family: var(--font-body);
color: var(--fg);
background-color: var(--bg);
}
}

View File

@ -0,0 +1,362 @@
/*
* TLYQ 统一设计系统 OKLCh 色彩空间2026-07-15 升级
* Tailwind Slate HEX 色板迁移至 OKLCh 色彩空间
* 感知均匀色域更广保持无障碍对比度WCAG AA 4.5:1
*
* 使用方式
* - CSS 变量@import './tlyq-design-system.css'
* - Tailwind颜色类见下方映射说明
*/
/* ==================== 设计令牌CSS 变量) ==================== */
:root {
/* 背景色 */
--bg: oklch(0.984 0.003 247.858); /* ≈ #f8fafc (slate-50) */
--bg-subtle: oklch(0.968 0.007 247.896); /* ≈ #f1f5f9 (slate-100) */
--surface: oklch(1 0 0); /* #ffffff (white) */
--surface-raised: oklch(1 0 0); /* #ffffff (white) */
--surface-overlay: rgba(255, 255, 255, 0.95);
/* 文本色 */
--fg: oklch(0.129 0.042 264.695); /* ≈ #0f172a (slate-900) */
--fg-subtle: oklch(0.372 0.044 257.287); /* ≈ #334155 (slate-700) */
--muted: oklch(0.446 0.043 257.281); /* ≈ #475569 (slate-600) */
--muted-subtle: oklch(0.662 0.051 257.281); /* ≈ #94a3b8 (slate-400) */
/* 边框 */
--border: oklch(0.928 0.006 264.531); /* ≈ #e2e8f0 (slate-200) */
--border-subtle: oklch(0.968 0.007 247.896);/* ≈ #f1f5f9 (slate-100) */
/* 主色调 — 蓝色系 */
--accent: oklch(0.546 0.245 262.881); /* ≈ #2563eb (blue-600) */
--accent-hover: oklch(0.479 0.247 262.881); /* ≈ #1d4ed8 (blue-700) */
--accent-active: oklch(0.426 0.228 262.881);/* ≈ #1e40af (blue-800) */
--accent-subtle: oklch(0.967 0.03 260.592); /* ≈ #eff6ff (blue-50) */
--accent-text: oklch(1 0 0); /* #ffffff */
/* 状态色 */
--success: oklch(0.627 0.194 149.214); /* ≈ #059669 (emerald-600) */
--success-subtle: oklch(0.982 0.041 152.117);/* ≈ #ecfdf5 (emerald-50) */
--warning: oklch(0.681 0.162 75.834); /* ≈ #d97706 (amber-600) */
--warning-subtle: oklch(0.986 0.03 92.708); /* ≈ #fffbeb (amber-50) */
--danger: oklch(0.577 0.245 27.325); /* ≈ #dc2626 (red-600) */
--danger-subtle: oklch(0.96 0.037 26.197); /* ≈ #fef2f2 (red-50) */
--info: oklch(0.546 0.245 262.881); /* ≈ #2563eb (blue-600) */
--info-subtle: oklch(0.967 0.03 260.592); /* ≈ #eff6ff (blue-50) */
/* 字体 */
--font-display: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "SF Pro Display", "Segoe UI", Roboto, sans-serif;
--font-body: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, sans-serif;
--font-sans: var(--font-body);
--font-mono: ui-monospace, "JetBrains Mono", "IBM Plex Mono", SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
/* 字体大小 */
--text-xs: 0.75rem; /* 12px */
--text-sm: 0.875rem; /* 14px */
--text-base: 1rem; /* 16px */
--text-lg: 1.125rem; /* 18px */
--text-xl: 1.25rem; /* 20px */
--text-2xl: 1.5rem; /* 24px */
--text-3xl: 1.875rem; /* 30px */
/* 行高 */
--leading-tight: 1.25;
--leading-snug: 1.375;
--leading-normal: 1.5;
--leading-relaxed: 1.625;
/* 字间距 */
--tracking-tighter: -0.05em;
--tracking-tight: -0.02em;
--tracking-normal: 0;
--tracking-wide: 0.02em;
--tracking-wider: 0.05em;
--tracking-widest: 0.1em;
/* 间距 */
--space-1: 0.25rem; /* 4px */
--space-2: 0.5rem; /* 8px */
--space-3: 0.75rem; /* 12px */
--space-4: 1rem; /* 16px */
--space-5: 1.25rem; /* 20px */
--space-6: 1.5rem; /* 24px */
--space-8: 2rem; /* 32px */
--space-10: 2.5rem; /* 40px */
--space-12: 3rem; /* 48px */
--space-16: 4rem; /* 64px */
/* 圆角 */
--radius-sm: 6px;
--radius-md: 8px;
--radius-lg: 12px;
--radius-xl: 16px;
--radius-2xl: 24px;
--radius-full: 9999px;
/* 阴影 */
--shadow-xs: 0 1px 2px rgba(0, 0, 0, 0.04);
--shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.06), 0 1px 2px rgba(0, 0, 0, 0.04);
--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.08), 0 2px 4px -2px rgba(0, 0, 0, 0.04);
--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.04);
--shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.04);
/* 过渡 */
--transition-fast: 150ms cubic-bezier(0.4, 0, 0.2, 1);
--transition-normal: 200ms cubic-bezier(0.4, 0, 0.2, 1);
--transition-slow: 300ms cubic-bezier(0.4, 0, 0.2, 1);
--transition-spring: 500ms cubic-bezier(0.34, 1.56, 0.64, 1);
/* 层级系统 */
--z-base: 0;
--z-raised: 10;
--z-dropdown: 100;
--z-sticky: 200;
--z-overlay: 300;
--z-modal: 400;
--z-toast: 700;
/* 布局 */
--sidebar-width: 240px;
--sidebar-width-collapsed: 64px;
--header-height: 56px;
--content-max-width: 1440px;
--content-padding: var(--space-6);
}
/* ==================== 深色模式 ==================== */
:root.dark {
/* 背景色 */
--bg: oklch(0.129 0.042 264.695); /* ≈ #020617 (slate-950) */
--bg-subtle: oklch(0.208 0.042 264.695); /* ≈ #0f172a (slate-900) */
--surface: oklch(0.208 0.042 264.695); /* ≈ #0f172a (slate-900) */
--surface-raised: oklch(0.279 0.041 260.031);/* ≈ #1e293b (slate-800) */
--surface-overlay: rgba(15, 23, 42, 0.95);
/* 文本色 */
--fg: oklch(0.984 0.003 247.858); /* ≈ #f8fafc (slate-50) */
--fg-subtle: oklch(0.837 0.014 253.365); /* ≈ #cbd5e1 (slate-300) */
--muted: oklch(0.662 0.051 257.281); /* ≈ #94a3b8 (slate-400) */
--muted-subtle: oklch(0.527 0.045 257.281); /* ≈ #64748b (slate-500) */
/* 边框 */
--border: oklch(0.279 0.041 260.031); /* ≈ #1e293b (slate-800) */
--border-subtle: oklch(0.208 0.042 264.695);/* ≈ #0f172a (slate-900) */
/* 主色调 */
--accent: oklch(0.623 0.214 259.815); /* ≈ #3b82f6 (blue-500) */
--accent-hover: oklch(0.723 0.157 260.543); /* ≈ #60a5fa (blue-400) */
--accent-active: oklch(0.829 0.096 260.543);/* ≈ #93c5fd (blue-300) */
--accent-subtle: rgba(59, 130, 246, 0.1);
--accent-text: oklch(0.208 0.042 264.695); /* ≈ #0f172a (slate-900) */
/* 状态色 */
--success: oklch(0.696 0.17 162.48); /* ≈ #34d399 (emerald-400) */
--success-subtle: rgba(52, 211, 153, 0.1);
--warning: oklch(0.828 0.12 76.523); /* ≈ #fbbf24 (amber-400) */
--warning-subtle: rgba(251, 191, 36, 0.1);
--danger: oklch(0.715 0.143 25.059); /* ≈ #f87171 (red-400) */
--danger-subtle: rgba(248, 113, 113, 0.1);
--info: oklch(0.723 0.157 260.543); /* ≈ #60a5fa (blue-400) */
--info-subtle: rgba(96, 165, 250, 0.1);
/* 阴影(深色下更突出) */
--shadow-xs: 0 1px 2px rgba(0, 0, 0, 0.2);
--shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.3), 0 1px 2px rgba(0, 0, 0, 0.2);
--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.3), 0 2px 4px -2px rgba(0, 0, 0, 0.2);
--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -4px rgba(0, 0, 0, 0.2);
--shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.3), 0 8px 10px -6px rgba(0, 0, 0, 0.2);
}
/* ==================== Tailwind 暗色模式映射 ==================== */
/*
* 以下 Tailwind 类名可直接使用
* 页面背景: bg-slate-50 dark:bg-slate-950
* 卡片背景: bg-white dark:bg-slate-900
* 边框: border-slate-200 dark:border-slate-800
* 正文: text-slate-900 dark:text-slate-50
* 次要文本: text-slate-700 dark:text-slate-300
* 弱文本: text-slate-500 dark:text-slate-400
* 主按钮: bg-blue-600 hover:bg-blue-700 text-white
* 成功: text-emerald-600 dark:text-emerald-400
* 警告: text-amber-600 dark:text-amber-400
* 危险: text-red-600 dark:text-red-400
*/
/* ==================== 全局重置 ==================== */
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
font-size: 16px;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
font-family: var(--font-sans);
color: var(--fg);
background-color: var(--bg);
}
/* ==================== 组件规范 ==================== */
/* 按钮规范
* 主按钮: bg-blue-600 hover:bg-blue-700 text-white rounded-lg shadow-sm
* 次按钮: bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700 rounded-lg
* 幽灵按钮: hover:bg-slate-100 dark:hover:bg-slate-800 rounded-lg
* 尺寸: sm(px-3 py-1.5 text-xs) / md(px-4 py-2 text-sm) / lg(px-6 py-2.5 text-base)
*/
/* 输入框规范
* 边框: border border-slate-300 dark:border-slate-600
* 聚焦: focus:ring-2 focus:ring-blue-500 focus:border-transparent
* 圆角: rounded-lg
* 尺寸: h-10(px-3 text-sm)
*/
/* 卡片规范
* 基础: bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-xl p-6 shadow-sm
* 悬停: hover:border-blue-200 dark:hover:border-blue-800
*/
/* 表格规范
* 头部: bg-slate-50 dark:bg-slate-800 text-slate-500 text-xs font-medium uppercase
* : border-b border-slate-200 dark:border-slate-700
* 悬停: hover:bg-slate-50 dark:hover:bg-slate-800/50
*/
/* 徽标规范
* 默认: bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300
* 成功: bg-emerald-100 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-400
* 警告: bg-amber-100 text-amber-700 dark:bg-amber-500/10 dark:text-amber-400
* 危险: bg-red-100 text-red-700 dark:bg-red-500/10 dark:text-red-400
* 信息: bg-blue-100 text-blue-700 dark:bg-blue-500/10 dark:text-blue-400
* 圆角: rounded-full
* 尺寸: px-2.5 py-0.5 text-xs font-medium
*/
/* 弹窗规范
* 背景: bg-white dark:bg-slate-900
* 边框: border border-slate-200 dark:border-slate-800
* 圆角: rounded-xl
* 阴影: shadow-xl
* 标题: text-lg font-semibold
*/
/* 侧边栏规范
* 宽度: w-60 (240px)
* 定位: fixed left-0 top-0 bottom-0
* 背景: bg-white dark:bg-slate-900
* 边框: border-r border-slate-200 dark:border-slate-800
* 品牌区: h-14 flex items-center
* 导航项: px-3 py-2.5 rounded-lg text-sm font-medium
* 激活态: bg-blue-50 text-blue-700 dark:bg-blue-500/10 dark:text-blue-400
*/
/* 顶栏规范
* 高度: h-14 (56px)
* 定位: fixed top-0
* 背景: bg-white dark:bg-slate-900
* 边框: border-b border-slate-200 dark:border-slate-800
* z-index: z-30
*/
/* 主内容区规范
* 边距: ml-60 pt-14 p-6 (侧边栏+顶栏)
* 门户布局: max-w-5xl mx-auto px-6 py-8
*/
/* ==================== 统计卡片 ==================== */
/*
* 用于仪表盘/概览页的统计数据展示
* 容器: bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-xl p-6
* 悬停: hover:border-blue-200 dark:hover:border-blue-800 hover:shadow-md transition-all
* 图标区: w-10 h-10 rounded-lg bg-blue-50 dark:bg-blue-500/10 flex items-center justify-center
* 数值: text-2xl font-semibold text-slate-900 dark:text-white font-display
* 标签: text-sm text-slate-500 dark:text-slate-400
* 变化趋势: text-xs font-medium (positive=text-emerald-600, negative=text-red-600)
*/
/* ==================== 骨架屏加载 ==================== */
/*
* 用于数据加载时的占位效果
* <div className="animate-pulse bg-slate-200 dark:bg-slate-700 rounded-lg [height]" />
* 文本行: h-4 w-full / w-3/4
* 标题: h-6 w-1/3
* 卡片: h-32 w-full rounded-xl
*/
/* 无缝统计条 ==================== */
/*
* 仪表盘顶部关键指标展示分段之间仅 1px 间隙
* 容器: flex gap-px bg-slate-200 dark:bg-slate-800 rounded-xl overflow-hidden
* : flex-1 bg-white dark:bg-slate-900 px-6 py-4 flex flex-col gap-1
* 标签: text-xs font-medium text-slate-500 uppercase tracking-widest
* 数值: text-2xl font-semibold font-[family-name:var(--font-display)]
*/
/* 服务状态卡片 ==================== */
/*
* 仪表盘中展示被监控服务实时状态
* 正常: bg-white dark:bg-slate-900 border rounded-xl p-5
* 悬停: hover:shadow-sm hover:-translate-y-px transition-all cursor-pointer
* 异常: bg-red-50 dark:bg-red-500/10 border-red-600 dark:border-red-400
* 红底红框突出显示
* 状态圆点: w-2.5 h-2.5 rounded-full
* ok: bg-emerald-600 dark:bg-emerald-400 shadow-[0_0_8px_var(--success)]
* err: bg-red-600 dark:bg-red-400 shadow-[0_0_12px_var(--danger)] animate-pulse
* 持续时长: text-lg font-semibold font-mono text-red-600 dark:text-red-400
* 展开区: border-t mt-3 pt-3
*/
/* ==================== 图表容器 ==================== */
/*
* 用于包裹图表组件
* <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-xl p-6">
* <div className="flex items-center justify-between mb-6">
* <h3 className="text-lg font-semibold text-slate-900 dark:text-white">标题</h3>
* <div className="flex items-center gap-4 text-sm text-slate-500">图例</div>
* </div>
* [图表内容]
* </div>
*/
/* ==================== 下拉菜单 ==================== */
/*
* 用于用户菜单操作菜单
* 容器: absolute right-0 top-full mt-1
* bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700
* rounded-lg shadow-lg py-1 min-w-[200px] z-[--z-dropdown]
* 菜单项: px-4 py-2.5 text-sm flex items-center gap-3
* hover:bg-slate-50 dark:hover:bg-slate-700
* text-slate-700 dark:text-slate-300
* 危险项: text-red-600 dark:text-red-400
* 分隔线: border-t border-slate-200 dark:border-slate-700 my-1
*/
/* ==================== 站点标识色 ==================== */
/*
* OA: blue-600
* assets: blue-600
* issue: blue-600
* monitor: indigo-600
*
* 站点卡片标识色门户首页
* 资产管理: blue-600 tag: CMDB
* 工单跟踪: violet-600 tag: ITS
* 监控中心: indigo-600 tag: MONITOR
* 官网: emerald-600 tag: WWW
* 云平台: amber-600 tag: CLOUD
* Token: rose-600 tag: TOKEN
* 代码仓库: pink-600 tag: GIT
*
* 2026-07-15 HEX 迁移至 OKLCh 色彩空间
* 主色 blue-600 OKLCh: oklch(0.546 0.245 262.881)
* 主色 indigo-600 OKLCh: oklch(0.511 0.262 276.966)
* 对比度验证白底蓝字 (oklch(0.546 0.245 262.881) on oklch(1 0 0)) 6.5:1 4.5:1 通过
*/

View File

@ -1,68 +1,77 @@
'use client'
// src/components/layout/Sidebar.tsx — 权限驱动侧边栏(统一标准布局)
import { useState, useEffect } from 'react'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { LayoutDashboard, Server, Search, Settings, Users, Shield, Key, FileText } from 'lucide-react'
const navItems = [
{ href: '/dashboard', label: '仪表盘', icon: LayoutDashboard, perm: null },
{ href: '/assets', label: '设备管理', icon: Server, perm: 'assets:read' },
{ href: '/assets/advanced-search', label: '高级查询', icon: Search, perm: 'assets:read' },
]
interface NavItem { label: string; href: string; icon: React.ComponentType<{ size?: number }>; perm: string | null }
interface NavSection { title?: string; items: NavItem[] }
const settingsItems = [
{ href: '/settings/users', label: '用户管理', icon: Users, perm: 'users:read' },
{ href: '/settings/roles', label: '角色权限', icon: Shield, perm: 'roles:read' },
{ href: '/settings/api-keys', label: 'API Key', icon: Key, perm: 'api-keys:read' },
{ href: '/settings/audit-logs', label: '审计日志', icon: FileText, perm: 'audit-logs:read' },
]
function hasAnyAdminPerm(permissions: string[]): boolean {
return permissions.includes('*') || permissions.some(p =>
['users:', 'roles:', 'api-keys:', 'audit-logs:'].some(prefix => p.startsWith(prefix))
)
}
export default function Sidebar() {
export default function Sidebar({ role }: { role?: string }) {
const pathname = usePathname()
const [permissions, setPermissions] = useState<string[]>([])
const isActive = (href: string) => pathname === href || (href !== '/' && pathname.startsWith(href))
const isAdmin = role === 'admin' || role === 'localadmin'
useEffect(() => {
fetch('/api/auth/me')
.then(r => r.json())
.then(u => { if (u.user?.permissions) setPermissions(u.user.permissions) })
.catch(() => {})
}, [])
const canSee = (perm: string | null) => {
if (perm === null) return true
if (permissions.includes('*')) return true
return permissions.includes(perm)
}
const sections: NavSection[] = [
{
items: [
{ label: '仪表盘', href: '/dashboard', icon: LayoutDashboard, perm: null },
],
},
{
title: '资产管理',
items: [
{ label: '设备管理', href: '/assets', icon: Server, perm: null },
{ label: '高级查询', href: '/assets/advanced-search', icon: Search, perm: null },
],
},
{
title: '系统设置',
items: [
{ label: '用户管理', href: '/settings/users', icon: Users, perm: isAdmin ? null : 'hidden' },
{ label: '角色权限', href: '/settings/roles', icon: Shield, perm: isAdmin ? null : 'hidden' },
{ label: 'API Key', href: '/settings/api-keys', icon: Key, perm: isAdmin ? null : 'hidden' },
{ label: '审计日志', href: '/settings/audit-logs', icon: FileText, perm: isAdmin ? null : 'hidden' },
],
},
]
return (
<aside className="fixed left-0 top-0 bottom-0 w-60 bg-white dark:bg-slate-900 border-r border-slate-200 dark:border-slate-800 flex flex-col z-40">
<div className="h-14 flex items-center px-5 border-b border-slate-200 dark:border-slate-800">
<span className="text-lg font-semibold text-blue-600 dark:text-blue-400"></span>
</div>
<nav className="flex-1 py-3 px-3 space-y-1 overflow-y-auto">
{navItems.filter(item => canSee(item.perm)).map((item) => {
const isActive = pathname === item.href || pathname.startsWith(item.href + '/')
const Icon = item.icon
return (<Link key={item.href} href={item.href} className={`flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 ${isActive ? 'bg-blue-50 text-blue-700 dark:bg-blue-500/10 dark:text-blue-400' : 'text-slate-600 hover:bg-slate-50 dark:text-slate-400 dark:hover:bg-slate-800'}`}><Icon size={18} />{item.label}</Link>)
})}
{hasAnyAdminPerm(permissions) && (
<div className="pt-3 border-t border-slate-200 dark:border-slate-800 mt-3">
<div className="flex items-center gap-3 px-3 py-2 text-xs font-semibold text-slate-400 dark:text-slate-500 uppercase tracking-wider">
<Settings size={14} />
</div>
{settingsItems.filter(item => canSee(item.perm)).map((item) => {
const isActive = pathname === item.href
const Icon = item.icon
return (<Link key={item.href} href={item.href} className={`flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 ${isActive ? 'bg-blue-50 text-blue-700 dark:bg-blue-500/10 dark:text-blue-400' : 'text-slate-600 hover:bg-slate-50 dark:text-slate-400 dark:hover:bg-slate-800'}`}><Icon size={18} />{item.label}</Link>)
})}
<aside className="fixed left-0 top-0 bottom-0 w-60 bg-white dark:bg-slate-900 border-r border-slate-200 dark:border-slate-800 z-[200] flex flex-col">
{/* 品牌区 */}
<div className="h-14 flex items-center px-6 border-b border-slate-200 dark:border-slate-800 shrink-0">
<Link href="/dashboard" className="flex items-center gap-3">
<div className="w-8 h-8 rounded-lg bg-blue-600 flex items-center justify-center text-white font-bold text-sm"></div>
<span className="font-semibold text-slate-900 dark:text-white"></span>
</Link>
</div>
{/* 导航区 */}
<nav className="flex-1 overflow-y-auto p-3 space-y-6">
{sections.map((section, i) => (
<div key={i}>
{section.title && (
<p className="px-3 mb-1 text-xs font-semibold text-slate-400 dark:text-slate-500 uppercase tracking-widest">
{section.title}
</p>
)}
{section.items.filter(item => item.perm !== 'hidden').map(item => {
const Icon = item.icon
return (
<Link key={item.href} href={item.href}
className={`flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors mb-0.5 ${
isActive(item.href)
? 'bg-blue-50 text-blue-700 dark:bg-blue-500/10 dark:text-blue-400'
: 'text-slate-600 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-800'
}`}>
<Icon size={18} />
<span>{item.label}</span>
</Link>
)
})}
</div>
))}
</nav>
</aside>
)

View File

@ -40,7 +40,7 @@ export function verifySession(token: string): SessionPayload | null { return ver
// 统一获取当前会话:优先 tlyq_session共享 JWT回退 session_assets本地 JWT
import { cookies } from 'next/headers'
import { verifySharedJwt } from '@/lib/jwt'
import { ldapUserExists, ldapGetUserInfo } from '@/lib/ldap'
import { ldapUserExists, ldapGetUserInfo, ldapIsAdmin } from '@/lib/ldap'
export async function getSession(): Promise<SessionPayload | null> {
const cookieStore = await cookies()
@ -67,13 +67,14 @@ export async function getSession(): Promise<SessionPayload | null> {
db.prepare("UPDATE users SET last_login_at = datetime('now', '+8 hours'), last_active_at = datetime('now', '+8 hours') WHERE id = ?").run(row.id)
return { userId: row.id, username: row.username, role: row.role }
}
// SSO 免登录LLDAP 验证通过但本地无记录 → 自动创建(viewer 角色
// SSO 免登录LLDAP 验证通过但本地无记录 → 自动创建(从 LLDAP 判断角色oa-ai 同步更新
const ldapInfo = await ldapGetUserInfo(sharedPayload.username)
const displayName = ldapInfo?.displayName || sharedPayload.displayName
const email = ldapInfo?.email ?? null
const role = (await ldapIsAdmin(sharedPayload.username)) ? 'admin' : 'viewer'
db.prepare(
"INSERT OR IGNORE INTO users (username, display_name, email, role, is_active, created_at, updated_at) VALUES (?, ?, ?, 'viewer', 1, datetime('now', '+8 hours'), datetime('now', '+8 hours'))"
).run(sharedPayload.username, displayName, email)
"INSERT OR IGNORE INTO users (username, display_name, email, role, is_active, created_at, updated_at) VALUES (?, ?, ?, ?, 1, datetime('now', '+8 hours'), datetime('now', '+8 hours'))"
).run(sharedPayload.username, displayName, email, role)
const newRow = db.prepare(
'SELECT id, username, role FROM users WHERE username = ? AND is_active = 1'
).get(sharedPayload.username) as { id: number; username: string; role: string } | undefined

View File

@ -1,5 +1,6 @@
// assets-ai/src/lib/jwt.ts — 引用共享 JWT保持原有接口
import { signJwt, verifyJwt } from '@shared/lib/auth/jwt'
import { verifyJwt } from '@shared/lib/auth/jwt'
import { signJwtV2 } from '@shared/lib/auth/jwt-v2'
import type { AuthConfig } from '@shared/lib/auth/types'
// 从环境变量读取配置
@ -21,7 +22,7 @@ export function signSharedJwt(
payload: { username: string; displayName: string },
expiresIn: number = 7 * 24 * 60 * 60
): string {
return signJwt({ secret: config.jwtSecret, payload, expiresInSeconds: expiresIn })
return signJwtV2({ secret: config.jwtSecret, payload, iss: 'assets.tlyq.ai', expiresInSeconds: expiresIn })
}
// 保持原有签名verifySharedJwt(token)

View File

@ -1,16 +1,11 @@
import { Client, InvalidCredentialsError } from 'ldapts'
import { execFileSync } from 'child_process'
const LDAP_URL = process.env.LDAP_URL || 'ldap://localhost:3890'
const LDAP_BASE_DN = process.env.LDAP_BASE_DN || 'dc=tlyq,dc=ai'
// 运行时从 LLDAP 容器动态获取 admin 密码,避免明文存于多个 .env
// 需要容器挂载 /var/run/docker.sock
// 从环境变量获取 LLDAP admin 密码(容器内无法执行 docker exec见 LESSONS-LEARNED #41
function getLdapAdminPassword(): string {
try {
return execFileSync('docker', ['exec', 'lldap', 'printenv', 'LLDAP_ADMIN_PASSWORD'],
{ timeout: 3000 }).toString().trim()
} catch { return 'admin123' }
return process.env.LLDAP_ADMIN_PASSWORD || 'admin123'
}
export interface LdapResult {
@ -70,6 +65,22 @@ export async function ldapGetUserInfo(username: string): Promise<{ displayName:
finally { await client.unbind() }
}
// 检查 LLDAP 用户是否为 lldap_admin 组成员
export async function ldapIsAdmin(username: string): Promise<boolean> {
if (username === 'admin') return true
const adminDn = process.env.LDAP_ADMIN_DN || 'uid=admin,ou=people,dc=tlyq,dc=ai'
const adminPass = getLdapAdminPassword()
const client = new Client({ url: LDAP_URL, timeout: 5000 })
try {
await client.bind(adminDn, adminPass)
const { searchEntries } = await client.search(`ou=groups,${LDAP_BASE_DN}`, {
scope: 'sub', filter: `(&(cn=lldap_admin)(member=uid=${username},ou=people,${LDAP_BASE_DN}))`, timeLimit: 3,
})
return searchEntries.length > 0
} catch { return false }
finally { try { await client.unbind() } catch { /* */ } }
}
// Q1: 检查 LLDAP 中用户是否存在(用 admin bind 搜索,不在/不可达均返回 true 保证容错)
export async function ldapUserExists(username: string): Promise<boolean> {
const adminDn = process.env.LDAP_ADMIN_DN || 'uid=admin,ou=people,dc=tlyq,dc=ai'

View File

@ -1,10 +1,15 @@
// assets-ai/src/middleware.ts — 使用共享 middleware 工厂
import { createMiddleware } from '@shared/lib/auth/middleware'
// src/middleware.ts — V2 单 cookie 模型Edge 验签 + iss 校验
import { createMiddlewareV2 } from '@shared/lib/auth/middleware-v2'
export const middleware = createMiddleware({
localCookieName: 'session_assets',
adminPaths: ['/settings'],
const jwtSecret = process.env.JWT_SECRET || 'oa-shared-jwt-secret-tlyq-2026'
const cookieDomain = process.env.COOKIE_DOMAIN || '.tlyq.ai'
export const middleware = createMiddlewareV2({
jwtSecret,
cookieDomain,
allowedIssuers: ['*'],
enableApiKey: true,
publicPaths: ['/login', '/api/auth', '/api/health', '/api/internal', '/_next', '/favicon.ico'],
})
export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico|public).*)'] }

View File

@ -1,7 +0,0 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
darkMode: 'class',
content: ['./src/**/*.{js,ts,jsx,tsx,mdx}'],
theme: { extend: {} },
plugins: [],
}