fix(mcp): подготовить доступ и отзыв разрешений для приёмки
This commit is contained in:
commit
ef7bb79d4e
311 files changed
+73119
No files matched your search
@@ -0,0 +1,10 @@
|
||||
import { defineConfig } from 'drizzle-kit'
|
||||
|
||||
export default defineConfig({
|
||||
schema: './src/schema/index.ts',
|
||||
out: './migrations',
|
||||
dialect: 'sqlite',
|
||||
dbCredentials: {
|
||||
url: process.env.DATABASE_URL?.replace(/^sqlite:/, '') ?? './data/app.db',
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,21 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.ts'],
|
||||
extends: [js.configs.recommended, tseslint.configs.recommended],
|
||||
languageOptions: {
|
||||
globals: globals.node,
|
||||
},
|
||||
rules: {
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'error',
|
||||
{ ignoreRestSiblings: true, argsIgnorePattern: '^_', varsIgnorePattern: '^_' },
|
||||
],
|
||||
},
|
||||
},
|
||||
])
|
||||
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"name": "@authportal/db",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"files": [
|
||||
"dist",
|
||||
"migrations",
|
||||
"package.json"
|
||||
],
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"development": "./src/index.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsup src/index.ts --format esm --dts",
|
||||
"lint": "eslint .",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"test:perf": "vitest run --config vitest.perf.config.ts",
|
||||
"dev": "tsup src/index.ts --format esm --dts --watch",
|
||||
"db:generate": "drizzle-kit generate",
|
||||
"db:push": "drizzle-kit push"
|
||||
},
|
||||
"dependencies": {
|
||||
"@authportal/shared": "workspace:*",
|
||||
"better-sqlite3": "^11.10.0",
|
||||
"drizzle-orm": "^0.44.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "catalog:",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@vitest/coverage-v8": "4.1.10",
|
||||
"drizzle-kit": "^0.31.1",
|
||||
"eslint": "catalog:",
|
||||
"globals": "catalog:",
|
||||
"tsup": "^8.5.0",
|
||||
"typescript": "catalog:",
|
||||
"typescript-eslint": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
import { and, desc, eq, gte, lt, or, sql } from 'drizzle-orm'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import {
|
||||
DEFAULT_AUDIT_RETENTION_DAYS,
|
||||
type AuditKind,
|
||||
type AuditLogEntry,
|
||||
type AuditSeverity,
|
||||
type AuditSourceApp,
|
||||
type AuditTargetType,
|
||||
} from '@authportal/shared'
|
||||
import type { AppDb } from './index.js'
|
||||
import { auditLog, portalSettings } from './schema/index.js'
|
||||
import { withTransaction } from './tx.js'
|
||||
|
||||
const SETTINGS_ID = 'main'
|
||||
|
||||
export type AppendAuditInput = {
|
||||
eventId?: string | null
|
||||
sourceApp?: AuditSourceApp
|
||||
action: string
|
||||
severity?: AuditSeverity
|
||||
actorUserId?: string | null
|
||||
actorEmail?: string | null
|
||||
actorName?: string | null
|
||||
targetType?: AuditTargetType | null
|
||||
targetId?: string | null
|
||||
summary: string
|
||||
details?: Record<string, unknown> | null
|
||||
ip?: string | null
|
||||
createdAt?: string | null
|
||||
}
|
||||
|
||||
function mapRow(row: typeof auditLog.$inferSelect): AuditLogEntry {
|
||||
let details: Record<string, unknown> | null = null
|
||||
if (row.detailsJson) {
|
||||
try {
|
||||
details = JSON.parse(row.detailsJson) as Record<string, unknown>
|
||||
} catch {
|
||||
details = { raw: row.detailsJson }
|
||||
}
|
||||
}
|
||||
return {
|
||||
id: row.id,
|
||||
event_id: row.eventId,
|
||||
source_app: (row.sourceApp as AuditSourceApp) || 'portal',
|
||||
action: row.action,
|
||||
severity: row.severity as AuditSeverity,
|
||||
actor_user_id: row.actorUserId,
|
||||
actor_email: row.actorEmail,
|
||||
actor_name: row.actorName,
|
||||
target_type: (row.targetType as AuditTargetType | null) ?? null,
|
||||
target_id: row.targetId,
|
||||
summary: row.summary,
|
||||
details,
|
||||
ip: row.ip,
|
||||
created_at: row.createdAt,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Append an audit event.
|
||||
* @returns true if inserted, false if duplicate event_id
|
||||
*/
|
||||
export function appendAudit(db: AppDb, input: AppendAuditInput): boolean {
|
||||
const now = input.createdAt ?? new Date().toISOString()
|
||||
const eventId = input.eventId ?? null
|
||||
|
||||
// Дубликат event_id отсекается уникальным индексом: без SELECT и гонок.
|
||||
const res = db
|
||||
.insert(auditLog)
|
||||
.values({
|
||||
id: randomUUID(),
|
||||
eventId,
|
||||
sourceApp: input.sourceApp ?? 'portal',
|
||||
action: input.action,
|
||||
severity: input.severity ?? 'info',
|
||||
actorUserId: input.actorUserId ?? null,
|
||||
actorEmail: input.actorEmail ?? null,
|
||||
actorName: input.actorName ?? null,
|
||||
targetType: input.targetType ?? null,
|
||||
targetId: input.targetId ?? null,
|
||||
summary: input.summary,
|
||||
detailsJson: input.details ? JSON.stringify(input.details) : null,
|
||||
ip: input.ip ?? null,
|
||||
createdAt: now,
|
||||
})
|
||||
.onConflictDoNothing()
|
||||
.run()
|
||||
return res.changes > 0
|
||||
}
|
||||
|
||||
/** Пачка событий в одной транзакции — один коммит вместо N. */
|
||||
export function appendAuditBatch(
|
||||
db: AppDb,
|
||||
inputs: AppendAuditInput[],
|
||||
): { accepted: number; duplicates: number; failed: number } {
|
||||
let accepted = 0
|
||||
let duplicates = 0
|
||||
let failed = 0
|
||||
withTransaction(db, () => {
|
||||
for (const input of inputs) {
|
||||
try {
|
||||
// SAVEPOINT: сбой одного события не откатывает остальные.
|
||||
const ok = withTransaction(db, () => appendAudit(db, input))
|
||||
if (ok) accepted += 1
|
||||
else duplicates += 1
|
||||
} catch {
|
||||
failed += 1
|
||||
}
|
||||
}
|
||||
})
|
||||
return { accepted, duplicates, failed }
|
||||
}
|
||||
|
||||
export function listAudit(
|
||||
db: AppDb,
|
||||
opts: {
|
||||
action?: string
|
||||
severity?: AuditSeverity
|
||||
userId?: string
|
||||
actorEmail?: string
|
||||
sourceApp?: AuditSourceApp
|
||||
kind?: AuditKind
|
||||
limit?: number
|
||||
} = {},
|
||||
): AuditLogEntry[] {
|
||||
const limit = opts.limit ?? 200
|
||||
const conditions = []
|
||||
if (opts.action) conditions.push(eq(auditLog.action, opts.action))
|
||||
if (opts.severity) conditions.push(eq(auditLog.severity, opts.severity))
|
||||
if (opts.sourceApp) conditions.push(eq(auditLog.sourceApp, opts.sourceApp))
|
||||
if (opts.kind === 'logins') {
|
||||
// Диапазон по индексу action: 'auth.' <= action < 'auth/' ('/' идёт сразу после '.').
|
||||
conditions.push(gte(auditLog.action, 'auth.'), lt(auditLog.action, 'auth/'))
|
||||
} else if (opts.kind === 'changes') {
|
||||
conditions.push(
|
||||
or(lt(auditLog.action, 'auth.'), gte(auditLog.action, 'auth/'))!,
|
||||
)
|
||||
}
|
||||
if (opts.actorEmail && opts.userId) {
|
||||
conditions.push(
|
||||
or(
|
||||
eq(auditLog.actorEmail, opts.actorEmail.toLowerCase()),
|
||||
eq(auditLog.actorUserId, opts.userId),
|
||||
eq(auditLog.targetId, opts.userId),
|
||||
)!,
|
||||
)
|
||||
} else if (opts.actorEmail) {
|
||||
conditions.push(eq(auditLog.actorEmail, opts.actorEmail.toLowerCase()))
|
||||
} else if (opts.userId) {
|
||||
conditions.push(
|
||||
or(
|
||||
eq(auditLog.actorUserId, opts.userId),
|
||||
eq(auditLog.targetId, opts.userId),
|
||||
)!,
|
||||
)
|
||||
}
|
||||
|
||||
const rows =
|
||||
conditions.length > 0
|
||||
? db
|
||||
.select()
|
||||
.from(auditLog)
|
||||
.where(and(...conditions))
|
||||
.orderBy(desc(auditLog.createdAt))
|
||||
.limit(limit)
|
||||
.all()
|
||||
: db
|
||||
.select()
|
||||
.from(auditLog)
|
||||
.orderBy(desc(auditLog.createdAt))
|
||||
.limit(limit)
|
||||
.all()
|
||||
|
||||
return rows.map(mapRow)
|
||||
}
|
||||
|
||||
export function purgeAuditOlderThan(db: AppDb, days: number): number {
|
||||
const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString()
|
||||
const result = db
|
||||
.delete(auditLog)
|
||||
.where(lt(auditLog.createdAt, cutoff))
|
||||
.run()
|
||||
return result.changes
|
||||
}
|
||||
|
||||
export function getAuditRetentionDays(db: AppDb): number {
|
||||
const row = db
|
||||
.select()
|
||||
.from(portalSettings)
|
||||
.where(eq(portalSettings.id, SETTINGS_ID))
|
||||
.get()
|
||||
return row?.auditRetentionDays ?? DEFAULT_AUDIT_RETENTION_DAYS
|
||||
}
|
||||
|
||||
export function setAuditRetentionDays(db: AppDb, days: number): number {
|
||||
const now = new Date().toISOString()
|
||||
const existing = db
|
||||
.select()
|
||||
.from(portalSettings)
|
||||
.where(eq(portalSettings.id, SETTINGS_ID))
|
||||
.get()
|
||||
if (existing) {
|
||||
db.update(portalSettings)
|
||||
.set({ auditRetentionDays: days, updatedAt: now })
|
||||
.where(eq(portalSettings.id, SETTINGS_ID))
|
||||
.run()
|
||||
} else {
|
||||
db.insert(portalSettings)
|
||||
.values({
|
||||
id: SETTINGS_ID,
|
||||
appSwitcherJson: null,
|
||||
auditRetentionDays: days,
|
||||
updatedAt: now,
|
||||
})
|
||||
.run()
|
||||
}
|
||||
return days
|
||||
}
|
||||
|
||||
export function countAudit(db: AppDb): number {
|
||||
const row = db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(auditLog)
|
||||
.get()
|
||||
return Number(row?.count ?? 0)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { mkdirSync, readdirSync, renameSync, rmSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import Database from 'better-sqlite3'
|
||||
import type { Sqlite } from './index.js'
|
||||
|
||||
const BACKUP_RE = /^app-\d{8}-\d{6}-\d{3}\.db$/
|
||||
|
||||
function stamp(d: Date): string {
|
||||
const p = (n: number, w = 2) => String(n).padStart(w, '0')
|
||||
return (
|
||||
`${d.getUTCFullYear()}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}` +
|
||||
`-${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}` +
|
||||
`-${p(d.getUTCMilliseconds(), 3)}`
|
||||
)
|
||||
}
|
||||
|
||||
/** PRAGMA integrity_check для файла БД; true, если результат 'ok'. */
|
||||
export function checkIntegrity(path: string): boolean {
|
||||
const db = new Database(path, { readonly: true, fileMustExist: true })
|
||||
try {
|
||||
return db.pragma('integrity_check', { simple: true }) === 'ok'
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
export function listBackups(dir: string): string[] {
|
||||
try {
|
||||
return readdirSync(dir)
|
||||
.filter((f) => BACKUP_RE.test(f))
|
||||
.sort()
|
||||
.reverse()
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Согласованный онлайн-бэкап (better-sqlite3 backup API работает с WAL без
|
||||
* остановки сервиса), проверка integrity_check, ротация по числу копий.
|
||||
*/
|
||||
export async function backupDatabase(
|
||||
sqlite: Sqlite,
|
||||
opts: { dir: string; keep: number; now?: Date },
|
||||
): Promise<{ file: string; removed: string[] }> {
|
||||
mkdirSync(opts.dir, { recursive: true })
|
||||
const name = `app-${stamp(opts.now ?? new Date())}.db`
|
||||
const finalPath = join(opts.dir, name)
|
||||
const partial = `${finalPath}.partial`
|
||||
try {
|
||||
await sqlite.backup(partial)
|
||||
if (!checkIntegrity(partial)) {
|
||||
throw new Error('backup integrity_check failed')
|
||||
}
|
||||
renameSync(partial, finalPath)
|
||||
} catch (err) {
|
||||
rmSync(partial, { force: true })
|
||||
throw err
|
||||
}
|
||||
const removed: string[] = []
|
||||
for (const old of listBackups(opts.dir).slice(Math.max(1, opts.keep))) {
|
||||
rmSync(join(opts.dir, old), { force: true })
|
||||
removed.push(old)
|
||||
}
|
||||
return { file: finalPath, removed }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Счётчик «поколения» данных пользователей: растёт при любой записи в
|
||||
* users/user_apps/user_permissions через функции этого пакета. Кэши верхнего
|
||||
* уровня сверяют поколение, поэтому блокировка и смена прав действуют сразу.
|
||||
*/
|
||||
let userDataGeneration = 0
|
||||
|
||||
export function getUserDataGeneration(): number {
|
||||
return userDataGeneration
|
||||
}
|
||||
|
||||
export function bumpUserDataGeneration(): void {
|
||||
userDataGeneration += 1
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { sql } from 'drizzle-orm'
|
||||
import type { AppDb } from './index.js'
|
||||
|
||||
const BATCH = 1000
|
||||
|
||||
/** Удаляет пачками по BATCH строк, чтобы не держать писательскую блокировку надолго. */
|
||||
function deleteInBatches(
|
||||
db: AppDb,
|
||||
table: string,
|
||||
where: ReturnType<typeof sql>,
|
||||
): number {
|
||||
let total = 0
|
||||
for (;;) {
|
||||
const res = db.run(
|
||||
sql`DELETE FROM ${sql.raw(table)} WHERE rowid IN (
|
||||
SELECT rowid FROM ${sql.raw(table)} WHERE ${where} LIMIT ${BATCH}
|
||||
)`,
|
||||
)
|
||||
total += res.changes
|
||||
if (res.changes < BATCH) return total
|
||||
}
|
||||
}
|
||||
|
||||
/** Сессии, истёкшие или отозванные раньше cutoff (ISO). */
|
||||
export function purgeStaleRefreshSessions(db: AppDb, cutoffIso: string): number {
|
||||
return deleteInBatches(
|
||||
db,
|
||||
'refresh_sessions',
|
||||
sql`expires_at < ${cutoffIso} OR (revoked_at IS NOT NULL AND revoked_at < ${cutoffIso})`,
|
||||
)
|
||||
}
|
||||
|
||||
/** Коды авторизации: истёкшие раньше cutoff, либо использованные раньше cutoff. */
|
||||
export function purgeStaleOidcAuthCodes(db: AppDb, cutoffIso: string): number {
|
||||
return deleteInBatches(
|
||||
db,
|
||||
'oidc_auth_codes',
|
||||
sql`expires_at < ${cutoffIso} OR (used_at IS NOT NULL AND used_at < ${cutoffIso})`,
|
||||
)
|
||||
}
|
||||
|
||||
export function purgeExpiredChallenges(db: AppDb, nowIso: string): number {
|
||||
return deleteInBatches(db, 'webauthn_challenges', sql`expires_at < ${nowIso}`)
|
||||
}
|
||||
|
||||
export type HousekeepingResult = {
|
||||
sessions: number
|
||||
authCodes: number
|
||||
challenges: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Одна проходка очистки. Записи хранятся ещё retentionDays после
|
||||
* истечения/отзыва — для разбора инцидентов в списке сессий.
|
||||
*/
|
||||
export function runHousekeeping(
|
||||
db: AppDb,
|
||||
opts: { retentionDays: number; now?: Date } = { retentionDays: 7 },
|
||||
): HousekeepingResult {
|
||||
const now = opts.now ?? new Date()
|
||||
const cutoff = new Date(
|
||||
now.getTime() - opts.retentionDays * 24 * 60 * 60 * 1000,
|
||||
).toISOString()
|
||||
return {
|
||||
sessions: purgeStaleRefreshSessions(db, cutoff),
|
||||
authCodes: purgeStaleOidcAuthCodes(db, cutoff),
|
||||
challenges: purgeExpiredChallenges(db, now.toISOString()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
import Database from 'better-sqlite3'
|
||||
import { drizzle } from 'drizzle-orm/better-sqlite3'
|
||||
import * as schema from './schema/index.js'
|
||||
import { migratePortalRevocations } from './portal-revocations.js'
|
||||
|
||||
export type Sqlite = Database.Database
|
||||
export type AppDb = ReturnType<typeof drizzle<typeof schema>>
|
||||
|
||||
export function resolveDatabasePath(databaseUrl: string): string {
|
||||
return databaseUrl.startsWith('sqlite:')
|
||||
? databaseUrl.slice('sqlite:'.length)
|
||||
: databaseUrl
|
||||
}
|
||||
|
||||
export function createDb(databaseUrl: string): { db: AppDb; sqlite: Sqlite } {
|
||||
const path = resolveDatabasePath(databaseUrl)
|
||||
const sqlite = new Database(path)
|
||||
sqlite.pragma('journal_mode = WAL')
|
||||
sqlite.pragma('foreign_keys = ON')
|
||||
sqlite.pragma('synchronous = NORMAL')
|
||||
// Без busy_timeout любая конкуренция за блокировку сразу даёт SQLITE_BUSY.
|
||||
sqlite.pragma('busy_timeout = 5000')
|
||||
sqlite.pragma('cache_size = -16000') // ~16 МиБ
|
||||
sqlite.pragma('temp_store = MEMORY')
|
||||
sqlite.pragma('mmap_size = 67108864') // 64 МиБ
|
||||
sqlite.pragma('wal_autocheckpoint = 1000')
|
||||
sqlite.pragma('journal_size_limit = 67108864')
|
||||
const db = drizzle(sqlite, { schema })
|
||||
return { db, sqlite }
|
||||
}
|
||||
|
||||
export function createMemoryDb(): { db: AppDb; sqlite: Sqlite } {
|
||||
const sqlite = new Database(':memory:')
|
||||
sqlite.pragma('foreign_keys = ON')
|
||||
const db = drizzle(sqlite, { schema })
|
||||
return { db, sqlite }
|
||||
}
|
||||
|
||||
/** Версия схемы в PRAGMA user_version; при совпадении migrateSchema ничего не делает. */
|
||||
// ВАЖНО: любое изменение baseMigrate()/migrateV1() требует увеличить SCHEMA_VERSION
|
||||
// (+ новая migrateVN), иначе существующие БД со скипом по user_version его не применят.
|
||||
export const SCHEMA_VERSION = 2
|
||||
|
||||
export function migrateSchema(sqlite: Sqlite): void {
|
||||
const current = sqlite.pragma('user_version', { simple: true }) as number
|
||||
if (current >= SCHEMA_VERSION) return
|
||||
sqlite.transaction(() => {
|
||||
if (current < 1) { baseMigrate(sqlite); migrateV1(sqlite) }
|
||||
if (current < 2) migratePortalRevocations(sqlite)
|
||||
sqlite.pragma(`user_version = ${SCHEMA_VERSION}`)
|
||||
})()
|
||||
}
|
||||
|
||||
/** v1: дедупликация доступа, уникальные индексы и индексы под очистку/фильтры. */
|
||||
function migrateV1(sqlite: Sqlite): void {
|
||||
sqlite.exec(`
|
||||
DELETE FROM user_apps WHERE rowid NOT IN (
|
||||
SELECT MIN(rowid) FROM user_apps GROUP BY user_id, app_id
|
||||
);
|
||||
DELETE FROM user_permissions WHERE rowid NOT IN (
|
||||
SELECT MIN(rowid) FROM user_permissions GROUP BY user_id, permission
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_user_apps ON user_apps(user_id, app_id);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_user_permissions ON user_permissions(user_id, permission);
|
||||
CREATE INDEX IF NOT EXISTS idx_refresh_sessions_expires ON refresh_sessions(expires_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_oidc_auth_codes_expires ON oidc_auth_codes(expires_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_log_severity ON audit_log(severity, created_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_log_actor_email ON audit_log(actor_email);
|
||||
`)
|
||||
}
|
||||
|
||||
function baseMigrate(sqlite: Sqlite): void {
|
||||
sqlite.exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
email TEXT NOT NULL UNIQUE,
|
||||
name TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
disabled INTEGER NOT NULL DEFAULT 0,
|
||||
last_login_at TEXT,
|
||||
last_login_ip TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_apps (
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
app_id TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_permissions (
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
permission TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS refresh_sessions (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL,
|
||||
revoked_at TEXT,
|
||||
ip TEXT,
|
||||
user_agent TEXT,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS portal_settings (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
app_switcher_json TEXT,
|
||||
audit_retention_days INTEGER NOT NULL DEFAULT 90,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS audit_log (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
event_id TEXT,
|
||||
source_app TEXT NOT NULL DEFAULT 'portal',
|
||||
action TEXT NOT NULL,
|
||||
severity TEXT NOT NULL,
|
||||
actor_user_id TEXT,
|
||||
actor_email TEXT,
|
||||
actor_name TEXT,
|
||||
target_type TEXT,
|
||||
target_id TEXT,
|
||||
summary TEXT NOT NULL,
|
||||
details_json TEXT,
|
||||
ip TEXT,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_user_apps_user ON user_apps(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_permissions_user ON user_permissions(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_refresh_sessions_user ON refresh_sessions(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_refresh_sessions_token ON refresh_sessions(token_hash);
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_log_created ON audit_log(created_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_log_action ON audit_log(action);
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_log_actor ON audit_log(actor_user_id, created_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_log_target ON audit_log(target_id, created_at);
|
||||
`)
|
||||
|
||||
// Existing DBs: CREATE TABLE IF NOT EXISTS skips schema — ALTER before indexes on new cols.
|
||||
const settingsCols = sqlite
|
||||
.prepare(`PRAGMA table_info(portal_settings)`)
|
||||
.all() as Array<{ name: string }>
|
||||
if (!settingsCols.some((c) => c.name === 'audit_retention_days')) {
|
||||
sqlite.exec(
|
||||
`ALTER TABLE portal_settings ADD COLUMN audit_retention_days INTEGER NOT NULL DEFAULT 90`,
|
||||
)
|
||||
}
|
||||
|
||||
const userCols = sqlite
|
||||
.prepare(`PRAGMA table_info(users)`)
|
||||
.all() as Array<{ name: string }>
|
||||
if (!userCols.some((c) => c.name === 'last_login_at')) {
|
||||
sqlite.exec(`ALTER TABLE users ADD COLUMN last_login_at TEXT`)
|
||||
}
|
||||
if (!userCols.some((c) => c.name === 'last_login_ip')) {
|
||||
sqlite.exec(`ALTER TABLE users ADD COLUMN last_login_ip TEXT`)
|
||||
}
|
||||
|
||||
const sessionCols = sqlite
|
||||
.prepare(`PRAGMA table_info(refresh_sessions)`)
|
||||
.all() as Array<{ name: string }>
|
||||
if (!sessionCols.some((c) => c.name === 'ip')) {
|
||||
sqlite.exec(`ALTER TABLE refresh_sessions ADD COLUMN ip TEXT`)
|
||||
}
|
||||
if (!sessionCols.some((c) => c.name === 'user_agent')) {
|
||||
sqlite.exec(`ALTER TABLE refresh_sessions ADD COLUMN user_agent TEXT`)
|
||||
}
|
||||
|
||||
const auditCols = sqlite
|
||||
.prepare(`PRAGMA table_info(audit_log)`)
|
||||
.all() as Array<{ name: string }>
|
||||
if (!auditCols.some((c) => c.name === 'event_id')) {
|
||||
sqlite.exec(`ALTER TABLE audit_log ADD COLUMN event_id TEXT`)
|
||||
}
|
||||
if (!auditCols.some((c) => c.name === 'source_app')) {
|
||||
sqlite.exec(
|
||||
`ALTER TABLE audit_log ADD COLUMN source_app TEXT NOT NULL DEFAULT 'portal'`,
|
||||
)
|
||||
}
|
||||
sqlite.exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_log_source ON audit_log(source_app, created_at);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_audit_log_event_id ON audit_log(event_id) WHERE event_id IS NOT NULL;
|
||||
`)
|
||||
|
||||
sqlite.exec(`
|
||||
CREATE TABLE IF NOT EXISTS oidc_clients (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
client_id TEXT NOT NULL UNIQUE,
|
||||
client_secret_hash TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
redirect_uris_json TEXT NOT NULL,
|
||||
scopes_json TEXT NOT NULL,
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS oidc_auth_codes (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
code_hash TEXT NOT NULL UNIQUE,
|
||||
client_id TEXT NOT NULL,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
redirect_uri TEXT NOT NULL,
|
||||
scope TEXT NOT NULL,
|
||||
nonce TEXT,
|
||||
code_challenge TEXT,
|
||||
code_challenge_method TEXT,
|
||||
expires_at TEXT NOT NULL,
|
||||
used_at TEXT,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS oidc_signing_keys (
|
||||
kid TEXT PRIMARY KEY NOT NULL,
|
||||
private_pem TEXT NOT NULL,
|
||||
public_jwk_json TEXT NOT NULL,
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_oidc_auth_codes_client ON oidc_auth_codes(client_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_oidc_auth_codes_user ON oidc_auth_codes(user_id);
|
||||
`)
|
||||
|
||||
sqlite.exec(`
|
||||
CREATE TABLE IF NOT EXISTS webauthn_credentials (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
credential_id TEXT NOT NULL UNIQUE,
|
||||
public_key TEXT NOT NULL,
|
||||
counter INTEGER NOT NULL DEFAULT 0,
|
||||
device_type TEXT,
|
||||
backed_up INTEGER NOT NULL DEFAULT 0,
|
||||
transports_json TEXT,
|
||||
name TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
last_used_at TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS webauthn_challenges (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
user_id TEXT REFERENCES users(id) ON DELETE CASCADE,
|
||||
purpose TEXT NOT NULL,
|
||||
challenge TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_webauthn_credentials_user
|
||||
ON webauthn_credentials(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_webauthn_challenges_expires
|
||||
ON webauthn_challenges(expires_at);
|
||||
`)
|
||||
}
|
||||
|
||||
/** Идемпотентное закрытие: checkpoint WAL, обновление статистики планировщика, close. */
|
||||
export function closeDb(sqlite: Sqlite): void {
|
||||
if (!sqlite.open) return
|
||||
try {
|
||||
if (!sqlite.memory) sqlite.pragma('wal_checkpoint(TRUNCATE)')
|
||||
sqlite.pragma('optimize')
|
||||
} finally {
|
||||
sqlite.close()
|
||||
}
|
||||
}
|
||||
|
||||
export function healthCheck(sqlite: Sqlite): void {
|
||||
sqlite.prepare('SELECT 1').get()
|
||||
}
|
||||
|
||||
export * from './schema/index.js'
|
||||
export * from './tx.js'
|
||||
export * from './backup.js'
|
||||
export * from './generation.js'
|
||||
export * from './housekeeping.js'
|
||||
export * from './users.js'
|
||||
export * from './settings.js'
|
||||
export * from './audit-log.js'
|
||||
export * from './oidc.js'
|
||||
export * from './webauthn.js'
|
||||
|
||||
export * from './portal-revocations.js'
|
||||
@@ -0,0 +1,217 @@
|
||||
import { and, desc, eq, gte, isNull } from 'drizzle-orm'
|
||||
import { randomBytes, randomUUID } from 'node:crypto'
|
||||
import type { AppDb } from './index.js'
|
||||
import { withTransaction } from './tx.js'
|
||||
import { oidcAuthCodes, oidcClients, oidcSigningKeys } from './schema/index.js'
|
||||
import { hashToken } from './users.js'
|
||||
|
||||
export type OidcClientRow = typeof oidcClients.$inferSelect
|
||||
export type OidcAuthCodeRow = typeof oidcAuthCodes.$inferSelect
|
||||
export type OidcSigningKeyRow = typeof oidcSigningKeys.$inferSelect
|
||||
|
||||
export function parseJsonStringArray(raw: string): string[] {
|
||||
try {
|
||||
const v = JSON.parse(raw) as unknown
|
||||
if (!Array.isArray(v)) return []
|
||||
return v.filter((x): x is string => typeof x === 'string')
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
export function listOidcClients(db: AppDb): OidcClientRow[] {
|
||||
return db
|
||||
.select()
|
||||
.from(oidcClients)
|
||||
.all()
|
||||
.sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))
|
||||
}
|
||||
|
||||
export function getOidcClientById(
|
||||
db: AppDb,
|
||||
id: string,
|
||||
): OidcClientRow | undefined {
|
||||
return db.select().from(oidcClients).where(eq(oidcClients.id, id)).get()
|
||||
}
|
||||
|
||||
export function getOidcClientByClientId(
|
||||
db: AppDb,
|
||||
clientId: string,
|
||||
): OidcClientRow | undefined {
|
||||
return db
|
||||
.select()
|
||||
.from(oidcClients)
|
||||
.where(eq(oidcClients.clientId, clientId))
|
||||
.get()
|
||||
}
|
||||
|
||||
export function createOidcClient(
|
||||
db: AppDb,
|
||||
input: {
|
||||
name: string
|
||||
clientSecretHash: string
|
||||
redirectUris: string[]
|
||||
scopes: string[]
|
||||
enabled: boolean
|
||||
clientId?: string
|
||||
},
|
||||
): OidcClientRow {
|
||||
const now = new Date().toISOString()
|
||||
const id = randomUUID()
|
||||
const clientId = input.clientId ?? randomUUID()
|
||||
db.insert(oidcClients)
|
||||
.values({
|
||||
id,
|
||||
clientId,
|
||||
clientSecretHash: input.clientSecretHash,
|
||||
name: input.name,
|
||||
redirectUrisJson: JSON.stringify(input.redirectUris),
|
||||
scopesJson: JSON.stringify(input.scopes),
|
||||
enabled: input.enabled,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
.run()
|
||||
return getOidcClientById(db, id)!
|
||||
}
|
||||
|
||||
export function updateOidcClient(
|
||||
db: AppDb,
|
||||
id: string,
|
||||
patch: {
|
||||
name?: string
|
||||
redirectUris?: string[]
|
||||
scopes?: string[]
|
||||
enabled?: boolean
|
||||
clientSecretHash?: string
|
||||
},
|
||||
): OidcClientRow | undefined {
|
||||
const existing = getOidcClientById(db, id)
|
||||
if (!existing) return undefined
|
||||
const now = new Date().toISOString()
|
||||
db.update(oidcClients)
|
||||
.set({
|
||||
name: patch.name ?? existing.name,
|
||||
redirectUrisJson: patch.redirectUris
|
||||
? JSON.stringify(patch.redirectUris)
|
||||
: existing.redirectUrisJson,
|
||||
scopesJson: patch.scopes
|
||||
? JSON.stringify(patch.scopes)
|
||||
: existing.scopesJson,
|
||||
enabled: patch.enabled ?? existing.enabled,
|
||||
clientSecretHash: patch.clientSecretHash ?? existing.clientSecretHash,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(eq(oidcClients.id, id))
|
||||
.run()
|
||||
return getOidcClientById(db, id)
|
||||
}
|
||||
|
||||
export function deleteOidcClient(db: AppDb, id: string): boolean {
|
||||
const result = db.delete(oidcClients).where(eq(oidcClients.id, id)).run()
|
||||
return result.changes > 0
|
||||
}
|
||||
|
||||
export function generateOidcClientSecret(): string {
|
||||
return randomBytes(32).toString('base64url')
|
||||
}
|
||||
|
||||
export function createOidcAuthCode(
|
||||
db: AppDb,
|
||||
input: {
|
||||
rawCode: string
|
||||
clientId: string
|
||||
userId: string
|
||||
redirectUri: string
|
||||
scope: string
|
||||
nonce?: string | null
|
||||
codeChallenge?: string | null
|
||||
codeChallengeMethod?: string | null
|
||||
expiresAt: Date
|
||||
},
|
||||
): string {
|
||||
const id = randomUUID()
|
||||
db.insert(oidcAuthCodes)
|
||||
.values({
|
||||
id,
|
||||
codeHash: hashToken(input.rawCode),
|
||||
clientId: input.clientId,
|
||||
userId: input.userId,
|
||||
redirectUri: input.redirectUri,
|
||||
scope: input.scope,
|
||||
nonce: input.nonce ?? null,
|
||||
codeChallenge: input.codeChallenge ?? null,
|
||||
codeChallengeMethod: input.codeChallengeMethod ?? null,
|
||||
expiresAt: input.expiresAt.toISOString(),
|
||||
usedAt: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
})
|
||||
.run()
|
||||
return id
|
||||
}
|
||||
|
||||
export function consumeOidcAuthCode(
|
||||
db: AppDb,
|
||||
rawCode: string,
|
||||
): OidcAuthCodeRow | undefined {
|
||||
const now = new Date().toISOString()
|
||||
// Атомарно: UPDATE … RETURNING исключает двойное использование кода.
|
||||
return db
|
||||
.update(oidcAuthCodes)
|
||||
.set({ usedAt: now })
|
||||
.where(
|
||||
and(
|
||||
eq(oidcAuthCodes.codeHash, hashToken(rawCode)),
|
||||
isNull(oidcAuthCodes.usedAt),
|
||||
gte(oidcAuthCodes.expiresAt, now),
|
||||
),
|
||||
)
|
||||
.returning()
|
||||
.get()
|
||||
}
|
||||
|
||||
export function getActiveOidcSigningKey(
|
||||
db: AppDb,
|
||||
): OidcSigningKeyRow | undefined {
|
||||
return db
|
||||
.select()
|
||||
.from(oidcSigningKeys)
|
||||
.where(eq(oidcSigningKeys.active, true))
|
||||
.orderBy(desc(oidcSigningKeys.createdAt))
|
||||
.limit(1)
|
||||
.get()
|
||||
}
|
||||
|
||||
export function listOidcSigningKeys(db: AppDb): OidcSigningKeyRow[] {
|
||||
return db.select().from(oidcSigningKeys).all()
|
||||
}
|
||||
|
||||
export function insertOidcSigningKey(
|
||||
db: AppDb,
|
||||
input: {
|
||||
kid: string
|
||||
privatePem: string
|
||||
publicJwkJson: string
|
||||
},
|
||||
): OidcSigningKeyRow {
|
||||
withTransaction(db, () => {
|
||||
db.update(oidcSigningKeys)
|
||||
.set({ active: false })
|
||||
.where(eq(oidcSigningKeys.active, true))
|
||||
.run()
|
||||
db.insert(oidcSigningKeys)
|
||||
.values({
|
||||
kid: input.kid,
|
||||
privatePem: input.privatePem,
|
||||
publicJwkJson: input.publicJwkJson,
|
||||
active: true,
|
||||
createdAt: new Date().toISOString(),
|
||||
})
|
||||
.run()
|
||||
})
|
||||
return db
|
||||
.select()
|
||||
.from(oidcSigningKeys)
|
||||
.where(eq(oidcSigningKeys.kid, input.kid))
|
||||
.get()!
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { createHash, randomUUID } from 'node:crypto'
|
||||
import type { AppDb, Sqlite } from './index.js'
|
||||
|
||||
const enabled = new WeakSet<AppDb>()
|
||||
export type PortalRevocationType = 'permissions.changed' | 'user.disabled' | 'sessions.revoked'
|
||||
export const portalRevocationLimit = 4096
|
||||
|
||||
export function migratePortalRevocations(sqlite: Sqlite): void {
|
||||
sqlite.exec(`
|
||||
CREATE TABLE portal_revocation_target (id INTEGER PRIMARY KEY CHECK(id=1), target_sha256 TEXT NOT NULL);
|
||||
CREATE TABLE portal_revocation_outbox (
|
||||
sequence INTEGER PRIMARY KEY AUTOINCREMENT, event_id TEXT NOT NULL UNIQUE,
|
||||
body TEXT NOT NULL CHECK(length(body)<=4096), occurred_at INTEGER NOT NULL,
|
||||
attempts INTEGER NOT NULL DEFAULT 0, next_attempt_at INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
`)
|
||||
}
|
||||
|
||||
/** Explicit startup opt-in. FULL precedes all enabled mutations, never an async hook. */
|
||||
export function enablePortalRevocations(db: AppDb, target: string): void {
|
||||
db.$client.pragma('synchronous = FULL')
|
||||
if (db.$client.pragma('synchronous', { simple: true }) !== 2) throw new Error('PORTAL_REVOCATION_DURABILITY_UNAVAILABLE')
|
||||
const fingerprint = createHash('sha256').update(target).digest('hex')
|
||||
db.$client.transaction(() => {
|
||||
const existing = db.$client.prepare('SELECT target_sha256 FROM portal_revocation_target WHERE id=1').get() as { target_sha256: string } | undefined
|
||||
if (existing && existing.target_sha256 !== fingerprint) throw new Error('PORTAL_REVOCATION_TARGET_CHANGED')
|
||||
if (!existing) db.$client.prepare('INSERT INTO portal_revocation_target(id,target_sha256) VALUES(1,?)').run(fingerprint)
|
||||
})()
|
||||
enabled.add(db)
|
||||
}
|
||||
|
||||
/** Called INSIDE the same synchronous transaction as the genuine user mutation. */
|
||||
export function enqueuePortalRevocation(db: AppDb, userId: string, type: PortalRevocationType): void {
|
||||
if (!enabled.has(db)) return
|
||||
if (!db.$client.inTransaction) throw new Error('PORTAL_REVOCATION_TRANSACTION_REQUIRED')
|
||||
const count = db.$client.prepare('SELECT count(*) AS count FROM portal_revocation_outbox').get() as { count: number }
|
||||
if (count.count >= portalRevocationLimit) throw new Error('PORTAL_REVOCATION_OUTBOX_FULL')
|
||||
const eventOccurredAt = Date.now(), eventId = randomUUID()
|
||||
const body = JSON.stringify({ version: 2, eventId, userId, type, eventOccurredAt })
|
||||
if (!Number.isSafeInteger(eventOccurredAt) || eventOccurredAt <= 0 || Buffer.byteLength(body) > 4096) throw new Error('PORTAL_REVOCATION_EVENT_INVALID')
|
||||
// No user FK: a genuine user deletion must not cascade-delete its own revocation.
|
||||
db.$client.prepare('INSERT INTO portal_revocation_outbox(event_id,body,occurred_at) VALUES(?,?,?)').run(eventId, body, eventOccurredAt)
|
||||
}
|
||||
|
||||
export type PortalRevocationDelivery = { sequence: number; body: string; attempts: number }
|
||||
export function nextPortalRevocation(db: AppDb): PortalRevocationDelivery | undefined {
|
||||
// Stable FIFO; a failed oldest event cannot be starved by subsequent mutations.
|
||||
const row = db.$client.prepare('SELECT sequence,body,attempts,next_attempt_at FROM portal_revocation_outbox ORDER BY sequence LIMIT 1').get() as (PortalRevocationDelivery & { next_attempt_at: number }) | undefined
|
||||
return row && row.next_attempt_at <= Date.now() ? row : undefined
|
||||
}
|
||||
export function completePortalRevocation(db: AppDb, event: PortalRevocationDelivery, delivered: boolean): void {
|
||||
if (delivered) db.$client.prepare('DELETE FROM portal_revocation_outbox WHERE sequence=? AND body=?').run(event.sequence, event.body)
|
||||
else db.$client.prepare('UPDATE portal_revocation_outbox SET attempts=min(attempts+1,30),next_attempt_at=? WHERE sequence=? AND body=?')
|
||||
.run(Date.now() + Math.min(60000, 1000 * 2 ** Math.min(event.attempts, 6)), event.sequence, event.body)
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core'
|
||||
|
||||
export const users = sqliteTable('users', {
|
||||
id: text('id').primaryKey(),
|
||||
email: text('email').notNull().unique(),
|
||||
name: text('name').notNull(),
|
||||
passwordHash: text('password_hash').notNull(),
|
||||
isAdmin: integer('is_admin', { mode: 'boolean' }).notNull().default(false),
|
||||
disabled: integer('disabled', { mode: 'boolean' }).notNull().default(false),
|
||||
lastLoginAt: text('last_login_at'),
|
||||
lastLoginIp: text('last_login_ip'),
|
||||
createdAt: text('created_at').notNull(),
|
||||
updatedAt: text('updated_at').notNull(),
|
||||
})
|
||||
|
||||
export const userApps = sqliteTable('user_apps', {
|
||||
userId: text('user_id')
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: 'cascade' }),
|
||||
appId: text('app_id').notNull(),
|
||||
})
|
||||
|
||||
export const userPermissions = sqliteTable('user_permissions', {
|
||||
userId: text('user_id')
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: 'cascade' }),
|
||||
permission: text('permission').notNull(),
|
||||
})
|
||||
|
||||
export const refreshSessions = sqliteTable('refresh_sessions', {
|
||||
id: text('id').primaryKey(),
|
||||
userId: text('user_id')
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: 'cascade' }),
|
||||
tokenHash: text('token_hash').notNull(),
|
||||
expiresAt: text('expires_at').notNull(),
|
||||
revokedAt: text('revoked_at'),
|
||||
ip: text('ip'),
|
||||
userAgent: text('user_agent'),
|
||||
createdAt: text('created_at').notNull(),
|
||||
})
|
||||
|
||||
/** Singleton row id = 'main' */
|
||||
export const portalSettings = sqliteTable('portal_settings', {
|
||||
id: text('id').primaryKey(),
|
||||
appSwitcherJson: text('app_switcher_json'),
|
||||
auditRetentionDays: integer('audit_retention_days').notNull().default(90),
|
||||
updatedAt: text('updated_at').notNull(),
|
||||
})
|
||||
|
||||
export const auditLog = sqliteTable('audit_log', {
|
||||
id: text('id').primaryKey(),
|
||||
eventId: text('event_id'),
|
||||
sourceApp: text('source_app').notNull().default('portal'),
|
||||
action: text('action').notNull(),
|
||||
severity: text('severity').notNull(),
|
||||
actorUserId: text('actor_user_id'),
|
||||
actorEmail: text('actor_email'),
|
||||
actorName: text('actor_name'),
|
||||
targetType: text('target_type'),
|
||||
targetId: text('target_id'),
|
||||
summary: text('summary').notNull(),
|
||||
detailsJson: text('details_json'),
|
||||
ip: text('ip'),
|
||||
createdAt: text('created_at').notNull(),
|
||||
})
|
||||
|
||||
export const oidcClients = sqliteTable('oidc_clients', {
|
||||
id: text('id').primaryKey(),
|
||||
clientId: text('client_id').notNull().unique(),
|
||||
clientSecretHash: text('client_secret_hash').notNull(),
|
||||
name: text('name').notNull(),
|
||||
redirectUrisJson: text('redirect_uris_json').notNull(),
|
||||
scopesJson: text('scopes_json').notNull(),
|
||||
enabled: integer('enabled', { mode: 'boolean' }).notNull().default(true),
|
||||
createdAt: text('created_at').notNull(),
|
||||
updatedAt: text('updated_at').notNull(),
|
||||
})
|
||||
|
||||
export const oidcAuthCodes = sqliteTable('oidc_auth_codes', {
|
||||
id: text('id').primaryKey(),
|
||||
codeHash: text('code_hash').notNull().unique(),
|
||||
clientId: text('client_id').notNull(),
|
||||
userId: text('user_id')
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: 'cascade' }),
|
||||
redirectUri: text('redirect_uri').notNull(),
|
||||
scope: text('scope').notNull(),
|
||||
nonce: text('nonce'),
|
||||
codeChallenge: text('code_challenge'),
|
||||
codeChallengeMethod: text('code_challenge_method'),
|
||||
expiresAt: text('expires_at').notNull(),
|
||||
usedAt: text('used_at'),
|
||||
createdAt: text('created_at').notNull(),
|
||||
})
|
||||
|
||||
export const oidcSigningKeys = sqliteTable('oidc_signing_keys', {
|
||||
kid: text('kid').primaryKey(),
|
||||
privatePem: text('private_pem').notNull(),
|
||||
publicJwkJson: text('public_jwk_json').notNull(),
|
||||
active: integer('active', { mode: 'boolean' }).notNull().default(true),
|
||||
createdAt: text('created_at').notNull(),
|
||||
})
|
||||
|
||||
export const webauthnCredentials = sqliteTable('webauthn_credentials', {
|
||||
id: text('id').primaryKey(),
|
||||
userId: text('user_id')
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: 'cascade' }),
|
||||
credentialId: text('credential_id').notNull().unique(),
|
||||
publicKey: text('public_key').notNull(),
|
||||
counter: integer('counter').notNull().default(0),
|
||||
deviceType: text('device_type'),
|
||||
backedUp: integer('backed_up', { mode: 'boolean' }).notNull().default(false),
|
||||
transportsJson: text('transports_json'),
|
||||
name: text('name').notNull(),
|
||||
createdAt: text('created_at').notNull(),
|
||||
lastUsedAt: text('last_used_at'),
|
||||
})
|
||||
|
||||
export const webauthnChallenges = sqliteTable('webauthn_challenges', {
|
||||
id: text('id').primaryKey(),
|
||||
userId: text('user_id').references(() => users.id, { onDelete: 'cascade' }),
|
||||
purpose: text('purpose').notNull(),
|
||||
challenge: text('challenge').notNull(),
|
||||
expiresAt: text('expires_at').notNull(),
|
||||
createdAt: text('created_at').notNull(),
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
import { eq } from 'drizzle-orm'
|
||||
import {
|
||||
defaultAppSwitcherConfig,
|
||||
normalizeAppSwitcherConfig,
|
||||
parseAppSwitcherConfig,
|
||||
type AppSwitcherConfig,
|
||||
} from '@authportal/shared'
|
||||
import type { AppDb } from './index.js'
|
||||
import { portalSettings } from './schema/index.js'
|
||||
|
||||
const SETTINGS_ID = 'main'
|
||||
|
||||
/** Разобранный конфиг на соединение; сбрасывается в setAppSwitcherConfig. */
|
||||
const switcherCache = new WeakMap<AppDb, AppSwitcherConfig>()
|
||||
|
||||
export function getAppSwitcherConfig(db: AppDb): AppSwitcherConfig {
|
||||
const hit = switcherCache.get(db)
|
||||
// клон: вызывающий код вправе мутировать результат
|
||||
if (hit) return structuredClone(hit)
|
||||
const config = loadAppSwitcherConfig(db)
|
||||
switcherCache.set(db, config)
|
||||
return structuredClone(config)
|
||||
}
|
||||
|
||||
/** Сброс кэша (если БД правили в обход setAppSwitcherConfig). */
|
||||
export function invalidateAppSwitcherConfig(db: AppDb): void {
|
||||
switcherCache.delete(db)
|
||||
}
|
||||
|
||||
function loadAppSwitcherConfig(db: AppDb): AppSwitcherConfig {
|
||||
const row = db
|
||||
.select()
|
||||
.from(portalSettings)
|
||||
.where(eq(portalSettings.id, SETTINGS_ID))
|
||||
.get()
|
||||
if (!row?.appSwitcherJson) return defaultAppSwitcherConfig()
|
||||
try {
|
||||
return parseAppSwitcherConfig(JSON.parse(row.appSwitcherJson))
|
||||
} catch {
|
||||
return defaultAppSwitcherConfig()
|
||||
}
|
||||
}
|
||||
|
||||
export function setAppSwitcherConfig(
|
||||
db: AppDb,
|
||||
config: AppSwitcherConfig,
|
||||
): AppSwitcherConfig {
|
||||
const normalized = normalizeAppSwitcherConfig(config)
|
||||
const now = new Date().toISOString()
|
||||
const json = JSON.stringify(normalized)
|
||||
const existing = db
|
||||
.select()
|
||||
.from(portalSettings)
|
||||
.where(eq(portalSettings.id, SETTINGS_ID))
|
||||
.get()
|
||||
if (existing) {
|
||||
db.update(portalSettings)
|
||||
.set({ appSwitcherJson: json, updatedAt: now })
|
||||
.where(eq(portalSettings.id, SETTINGS_ID))
|
||||
.run()
|
||||
} else {
|
||||
db.insert(portalSettings)
|
||||
.values({
|
||||
id: SETTINGS_ID,
|
||||
appSwitcherJson: json,
|
||||
auditRetentionDays: 90,
|
||||
updatedAt: now,
|
||||
})
|
||||
.run()
|
||||
}
|
||||
switcherCache.delete(db)
|
||||
return normalized
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { AppDb } from './index.js'
|
||||
|
||||
/**
|
||||
* Выполняет fn в транзакции better-sqlite3. Вложенные вызовы превращаются
|
||||
* в SAVEPOINT, поэтому безопасно вызывать из функций, уже работающих в транзакции.
|
||||
*/
|
||||
export function withTransaction<T>(db: AppDb, fn: () => T): T {
|
||||
return db.$client.transaction(fn)()
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
import { and, desc, eq, gt, gte, isNull, or, sql } from 'drizzle-orm'
|
||||
import { createHash, randomUUID } from 'node:crypto'
|
||||
import type { AppDb } from './index.js'
|
||||
import { bumpUserDataGeneration } from './generation.js'
|
||||
import { withTransaction } from './tx.js'
|
||||
import { enqueuePortalRevocation } from './portal-revocations.js'
|
||||
import {
|
||||
refreshSessions,
|
||||
userApps,
|
||||
userPermissions,
|
||||
users,
|
||||
} from './schema/index.js'
|
||||
|
||||
export type UserRow = typeof users.$inferSelect
|
||||
|
||||
export function hashToken(token: string): string {
|
||||
return createHash('sha256').update(token).digest('hex')
|
||||
}
|
||||
|
||||
export function listUsers(db: AppDb): UserRow[] {
|
||||
return db.select().from(users).all()
|
||||
}
|
||||
|
||||
/** Есть ли хотя бы один пользователь (LIMIT 1 вместо загрузки всей таблицы). */
|
||||
export function hasAnyUser(db: AppDb): boolean {
|
||||
return db.select({ id: users.id }).from(users).limit(1).get() !== undefined
|
||||
}
|
||||
|
||||
export function listAdmins(db: AppDb): UserRow[] {
|
||||
return db.select().from(users).where(eq(users.isAdmin, true)).all()
|
||||
}
|
||||
|
||||
/**
|
||||
* Подготовленные запросы горячего пути: компиляция SQL один раз на соединение
|
||||
* вместо prepare на каждый вызов.
|
||||
*/
|
||||
function buildPrepared(db: AppDb) {
|
||||
return {
|
||||
userById: db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.id, sql.placeholder('id')))
|
||||
.prepare(),
|
||||
apps: db
|
||||
.select({ appId: userApps.appId })
|
||||
.from(userApps)
|
||||
.where(eq(userApps.userId, sql.placeholder('userId')))
|
||||
.prepare(),
|
||||
permissions: db
|
||||
.select({ permission: userPermissions.permission })
|
||||
.from(userPermissions)
|
||||
.where(eq(userPermissions.userId, sql.placeholder('userId')))
|
||||
.prepare(),
|
||||
sessionByHash: db
|
||||
.select()
|
||||
.from(refreshSessions)
|
||||
.where(eq(refreshSessions.tokenHash, sql.placeholder('hash')))
|
||||
.prepare(),
|
||||
}
|
||||
}
|
||||
|
||||
const preparedByDb = new WeakMap<AppDb, ReturnType<typeof buildPrepared>>()
|
||||
|
||||
function prepared(db: AppDb) {
|
||||
let p = preparedByDb.get(db)
|
||||
if (!p) {
|
||||
p = buildPrepared(db)
|
||||
preparedByDb.set(db, p)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
export function getUserById(db: AppDb, id: string): UserRow | undefined {
|
||||
return prepared(db).userById.get({ id })
|
||||
}
|
||||
|
||||
export function getUserByEmail(
|
||||
db: AppDb,
|
||||
email: string,
|
||||
): UserRow | undefined {
|
||||
return db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.email, email.toLowerCase()))
|
||||
.get()
|
||||
}
|
||||
|
||||
export function getUserApps(db: AppDb, userId: string): string[] {
|
||||
return prepared(db)
|
||||
.apps.all({ userId })
|
||||
.map((r) => r.appId)
|
||||
}
|
||||
|
||||
export function getUserPermissions(db: AppDb, userId: string): string[] {
|
||||
return prepared(db)
|
||||
.permissions.all({ userId })
|
||||
.map((r) => r.permission)
|
||||
}
|
||||
|
||||
/** Apps всех пользователей одним запросом — для списков без N+1. */
|
||||
export function listUserAppsBatch(db: AppDb): Map<string, string[]> {
|
||||
const rows = db.select().from(userApps).all()
|
||||
const byUser = new Map<string, string[]>()
|
||||
for (const row of rows) {
|
||||
const list = byUser.get(row.userId)
|
||||
if (list) list.push(row.appId)
|
||||
else byUser.set(row.userId, [row.appId])
|
||||
}
|
||||
return byUser
|
||||
}
|
||||
|
||||
/** Permissions всех пользователей одним запросом — для списков без N+1. */
|
||||
export function listUserPermissionsBatch(db: AppDb): Map<string, string[]> {
|
||||
const rows = db.select().from(userPermissions).all()
|
||||
const byUser = new Map<string, string[]>()
|
||||
for (const row of rows) {
|
||||
const list = byUser.get(row.userId)
|
||||
if (list) list.push(row.permission)
|
||||
else byUser.set(row.userId, [row.permission])
|
||||
}
|
||||
return byUser
|
||||
}
|
||||
|
||||
export function createUser(
|
||||
db: AppDb,
|
||||
input: {
|
||||
email: string
|
||||
name: string
|
||||
passwordHash: string
|
||||
isAdmin: boolean
|
||||
},
|
||||
): UserRow {
|
||||
const now = new Date().toISOString()
|
||||
const id = randomUUID()
|
||||
db.insert(users)
|
||||
.values({
|
||||
id,
|
||||
email: input.email.toLowerCase(),
|
||||
name: input.name,
|
||||
passwordHash: input.passwordHash,
|
||||
isAdmin: input.isAdmin,
|
||||
disabled: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
.run()
|
||||
bumpUserDataGeneration()
|
||||
return getUserById(db, id)!
|
||||
}
|
||||
|
||||
export function updateUser(
|
||||
db: AppDb,
|
||||
id: string,
|
||||
patch: {
|
||||
email?: string
|
||||
name?: string
|
||||
passwordHash?: string
|
||||
isAdmin?: boolean
|
||||
disabled?: boolean
|
||||
},
|
||||
): UserRow | undefined {
|
||||
return withTransaction(db, () => {
|
||||
const existing = getUserById(db, id)
|
||||
if (!existing) return undefined
|
||||
const now = new Date().toISOString()
|
||||
db.update(users)
|
||||
.set({
|
||||
email: patch.email?.toLowerCase() ?? existing.email,
|
||||
name: patch.name ?? existing.name,
|
||||
passwordHash: patch.passwordHash ?? existing.passwordHash,
|
||||
isAdmin: patch.isAdmin ?? existing.isAdmin,
|
||||
disabled: patch.disabled ?? existing.disabled,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(eq(users.id, id))
|
||||
.run()
|
||||
bumpUserDataGeneration()
|
||||
if (patch.disabled === true && !existing.disabled) enqueuePortalRevocation(db, id, 'user.disabled')
|
||||
else if (patch.isAdmin !== undefined && patch.isAdmin !== existing.isAdmin) enqueuePortalRevocation(db, id, 'permissions.changed')
|
||||
return getUserById(db, id)
|
||||
})
|
||||
}
|
||||
|
||||
export function deleteUser(db: AppDb, id: string): boolean {
|
||||
return withTransaction(db, () => {
|
||||
const result = db.delete(users).where(eq(users.id, id)).run()
|
||||
if (result.changes > 0) enqueuePortalRevocation(db, id, 'user.disabled')
|
||||
bumpUserDataGeneration()
|
||||
return result.changes > 0
|
||||
})
|
||||
}
|
||||
|
||||
export function setUserAccess(
|
||||
db: AppDb,
|
||||
userId: string,
|
||||
apps: string[],
|
||||
permissions: string[],
|
||||
): void {
|
||||
const uniqApps = [...new Set(apps)]
|
||||
const uniqPerms = [...new Set(permissions)]
|
||||
withTransaction(db, () => {
|
||||
const changed = JSON.stringify(getUserApps(db, userId).sort()) !== JSON.stringify([...uniqApps].sort())
|
||||
|| JSON.stringify(getUserPermissions(db, userId).sort()) !== JSON.stringify([...uniqPerms].sort())
|
||||
db.delete(userApps).where(eq(userApps.userId, userId)).run()
|
||||
db.delete(userPermissions).where(eq(userPermissions.userId, userId)).run()
|
||||
if (uniqApps.length > 0) {
|
||||
db.insert(userApps)
|
||||
.values(uniqApps.map((appId) => ({ userId, appId })))
|
||||
.run()
|
||||
}
|
||||
if (uniqPerms.length > 0) {
|
||||
db.insert(userPermissions)
|
||||
.values(uniqPerms.map((permission) => ({ userId, permission })))
|
||||
.run()
|
||||
}
|
||||
db.update(users)
|
||||
.set({ updatedAt: new Date().toISOString() })
|
||||
.where(eq(users.id, userId))
|
||||
.run()
|
||||
if (changed) enqueuePortalRevocation(db, userId, 'permissions.changed')
|
||||
})
|
||||
bumpUserDataGeneration()
|
||||
}
|
||||
|
||||
/** Поиск для каталога пользователей: только нужные колонки, LIKE и LIMIT в SQL. */
|
||||
export function searchDirectoryUsers(
|
||||
db: AppDb,
|
||||
query: string,
|
||||
limit = 50,
|
||||
): Array<{ id: string; email: string; name: string }> {
|
||||
const q = query.trim().toLowerCase().replace(/[\\%_]/g, (c) => `\\${c}`)
|
||||
const pattern = `%${q}%`
|
||||
return db
|
||||
.select({ id: users.id, email: users.email, name: users.name })
|
||||
.from(users)
|
||||
.where(
|
||||
and(
|
||||
eq(users.disabled, false),
|
||||
q
|
||||
? or(
|
||||
sql`lower(${users.email}) LIKE ${pattern} ESCAPE '\\'`,
|
||||
sql`lower(${users.name}) LIKE ${pattern} ESCAPE '\\'`,
|
||||
sql`lower(${users.id}) LIKE ${pattern} ESCAPE '\\'`,
|
||||
)
|
||||
: undefined,
|
||||
),
|
||||
)
|
||||
.orderBy(users.email)
|
||||
.limit(limit)
|
||||
.all()
|
||||
}
|
||||
|
||||
export function touchLastLogin(
|
||||
db: AppDb,
|
||||
userId: string,
|
||||
ip?: string | null,
|
||||
): void {
|
||||
const now = new Date().toISOString()
|
||||
db.update(users)
|
||||
.set({
|
||||
lastLoginAt: now,
|
||||
lastLoginIp: ip ?? null,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(eq(users.id, userId))
|
||||
.run()
|
||||
}
|
||||
|
||||
export function createRefreshSession(
|
||||
db: AppDb,
|
||||
userId: string,
|
||||
rawToken: string,
|
||||
expiresAt: Date,
|
||||
meta?: { ip?: string | null; userAgent?: string | null },
|
||||
): string {
|
||||
const id = randomUUID()
|
||||
db.insert(refreshSessions)
|
||||
.values({
|
||||
id,
|
||||
userId,
|
||||
tokenHash: hashToken(rawToken),
|
||||
expiresAt: expiresAt.toISOString(),
|
||||
revokedAt: null,
|
||||
ip: meta?.ip ?? null,
|
||||
userAgent: meta?.userAgent ?? null,
|
||||
createdAt: new Date().toISOString(),
|
||||
})
|
||||
.run()
|
||||
return id
|
||||
}
|
||||
|
||||
export function revokeRefreshSession(db: AppDb, rawToken: string): void {
|
||||
withTransaction(db, () => {
|
||||
const session = db.select().from(refreshSessions).where(eq(refreshSessions.tokenHash, hashToken(rawToken))).get()
|
||||
const now = new Date().toISOString()
|
||||
db.update(refreshSessions)
|
||||
.set({ revokedAt: now })
|
||||
.where(eq(refreshSessions.tokenHash, hashToken(rawToken)))
|
||||
.run()
|
||||
if (session && !session.revokedAt) enqueuePortalRevocation(db, session.userId, 'sessions.revoked')
|
||||
})
|
||||
}
|
||||
|
||||
/** Active refresh session → user (for OIDC authorize cookie). */
|
||||
export function getUserByRefreshToken(
|
||||
db: AppDb,
|
||||
rawToken: string,
|
||||
): UserRow | undefined {
|
||||
const now = new Date().toISOString()
|
||||
const session = prepared(db).sessionByHash.get({
|
||||
hash: hashToken(rawToken),
|
||||
})
|
||||
if (!session || session.revokedAt) return undefined
|
||||
if (session.expiresAt < now) return undefined
|
||||
const user = getUserById(db, session.userId)
|
||||
if (!user || user.disabled) return undefined
|
||||
return user
|
||||
}
|
||||
|
||||
export type ActiveSessionRow = {
|
||||
id: string
|
||||
userId: string
|
||||
email: string
|
||||
name: string
|
||||
ip: string | null
|
||||
userAgent: string | null
|
||||
createdAt: string
|
||||
expiresAt: string
|
||||
}
|
||||
|
||||
export function listActiveSessions(
|
||||
db: AppDb,
|
||||
opts: { userId?: string } = {},
|
||||
): ActiveSessionRow[] {
|
||||
const now = new Date().toISOString()
|
||||
return db
|
||||
.select({
|
||||
id: refreshSessions.id,
|
||||
userId: refreshSessions.userId,
|
||||
email: users.email,
|
||||
name: users.name,
|
||||
ip: refreshSessions.ip,
|
||||
userAgent: refreshSessions.userAgent,
|
||||
createdAt: refreshSessions.createdAt,
|
||||
expiresAt: refreshSessions.expiresAt,
|
||||
})
|
||||
.from(refreshSessions)
|
||||
.innerJoin(users, eq(refreshSessions.userId, users.id))
|
||||
.where(
|
||||
and(
|
||||
isNull(refreshSessions.revokedAt),
|
||||
gte(refreshSessions.expiresAt, now),
|
||||
opts.userId ? eq(refreshSessions.userId, opts.userId) : undefined,
|
||||
),
|
||||
)
|
||||
.orderBy(desc(refreshSessions.createdAt))
|
||||
.all()
|
||||
}
|
||||
|
||||
export function revokeSessionById(db: AppDb, sessionId: string): boolean {
|
||||
return withTransaction(db, () => {
|
||||
const row = db
|
||||
.select()
|
||||
.from(refreshSessions)
|
||||
.where(eq(refreshSessions.id, sessionId))
|
||||
.get()
|
||||
if (!row || row.revokedAt) return false
|
||||
db.update(refreshSessions)
|
||||
.set({ revokedAt: new Date().toISOString() })
|
||||
.where(eq(refreshSessions.id, sessionId))
|
||||
.run()
|
||||
enqueuePortalRevocation(db, row.userId, 'sessions.revoked')
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
export function revokeAllSessionsForUser(db: AppDb, userId: string): number {
|
||||
return withTransaction(db, () => {
|
||||
const now = new Date().toISOString()
|
||||
// Активная сессия = не отозвана и не истекла; один UPDATE вместо цикла.
|
||||
const result = db
|
||||
.update(refreshSessions)
|
||||
.set({ revokedAt: now })
|
||||
.where(
|
||||
and(
|
||||
eq(refreshSessions.userId, userId),
|
||||
isNull(refreshSessions.revokedAt),
|
||||
gt(refreshSessions.expiresAt, now),
|
||||
),
|
||||
)
|
||||
.run()
|
||||
if (getUserById(db, userId)) enqueuePortalRevocation(db, userId, 'sessions.revoked')
|
||||
return result.changes
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import { and, desc, eq, lt, sql } from 'drizzle-orm'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type { AppDb } from './index.js'
|
||||
import { webauthnChallenges, webauthnCredentials } from './schema/index.js'
|
||||
|
||||
export type WebauthnCredentialRow = typeof webauthnCredentials.$inferSelect
|
||||
export type WebauthnChallengeRow = typeof webauthnChallenges.$inferSelect
|
||||
export type WebauthnChallengePurpose = 'register' | 'authenticate'
|
||||
|
||||
const CHALLENGE_TTL_MS = 5 * 60 * 1000
|
||||
|
||||
export function purgeExpiredWebauthnChallenges(db: AppDb): void {
|
||||
const now = new Date().toISOString()
|
||||
db.delete(webauthnChallenges)
|
||||
.where(lt(webauthnChallenges.expiresAt, now))
|
||||
.run()
|
||||
}
|
||||
|
||||
export function createWebauthnChallenge(
|
||||
db: AppDb,
|
||||
input: {
|
||||
purpose: WebauthnChallengePurpose
|
||||
challenge: string
|
||||
userId?: string | null
|
||||
},
|
||||
): WebauthnChallengeRow {
|
||||
purgeExpiredWebauthnChallenges(db)
|
||||
const now = new Date()
|
||||
const id = randomUUID()
|
||||
db.insert(webauthnChallenges)
|
||||
.values({
|
||||
id,
|
||||
userId: input.userId ?? null,
|
||||
purpose: input.purpose,
|
||||
challenge: input.challenge,
|
||||
expiresAt: new Date(now.getTime() + CHALLENGE_TTL_MS).toISOString(),
|
||||
createdAt: now.toISOString(),
|
||||
})
|
||||
.run()
|
||||
return getWebauthnChallengeById(db, id)!
|
||||
}
|
||||
|
||||
export function getWebauthnChallengeById(
|
||||
db: AppDb,
|
||||
id: string,
|
||||
): WebauthnChallengeRow | undefined {
|
||||
return db
|
||||
.select()
|
||||
.from(webauthnChallenges)
|
||||
.where(eq(webauthnChallenges.id, id))
|
||||
.get()
|
||||
}
|
||||
|
||||
export function consumeWebauthnChallenge(
|
||||
db: AppDb,
|
||||
id: string,
|
||||
purpose: WebauthnChallengePurpose,
|
||||
userId?: string | null,
|
||||
): WebauthnChallengeRow | undefined {
|
||||
const row = getWebauthnChallengeById(db, id)
|
||||
if (!row) return undefined
|
||||
if (row.purpose !== purpose) return undefined
|
||||
if (row.expiresAt < new Date().toISOString()) {
|
||||
db.delete(webauthnChallenges).where(eq(webauthnChallenges.id, id)).run()
|
||||
return undefined
|
||||
}
|
||||
if (userId != null && row.userId && row.userId !== userId) return undefined
|
||||
db.delete(webauthnChallenges).where(eq(webauthnChallenges.id, id)).run()
|
||||
return row
|
||||
}
|
||||
|
||||
export function listWebauthnCredentials(
|
||||
db: AppDb,
|
||||
userId: string,
|
||||
): WebauthnCredentialRow[] {
|
||||
return db
|
||||
.select()
|
||||
.from(webauthnCredentials)
|
||||
.where(eq(webauthnCredentials.userId, userId))
|
||||
.orderBy(desc(webauthnCredentials.createdAt))
|
||||
.all()
|
||||
}
|
||||
|
||||
export function countWebauthnCredentials(db: AppDb, userId: string): number {
|
||||
const row = db
|
||||
.select({ total: sql<number>`count(*)` })
|
||||
.from(webauthnCredentials)
|
||||
.where(eq(webauthnCredentials.userId, userId))
|
||||
.get()
|
||||
return Number(row?.total ?? 0)
|
||||
}
|
||||
|
||||
/** Число passkey-ов по всем пользователям одним GROUP BY — для списков без N+1. */
|
||||
export function countWebauthnCredentialsBatch(db: AppDb): Map<string, number> {
|
||||
const rows = db
|
||||
.select({
|
||||
userId: webauthnCredentials.userId,
|
||||
total: sql<number>`count(*)`,
|
||||
})
|
||||
.from(webauthnCredentials)
|
||||
.groupBy(webauthnCredentials.userId)
|
||||
.all()
|
||||
return new Map(rows.map((r) => [r.userId, Number(r.total)]))
|
||||
}
|
||||
|
||||
export function getWebauthnCredentialById(
|
||||
db: AppDb,
|
||||
id: string,
|
||||
): WebauthnCredentialRow | undefined {
|
||||
return db
|
||||
.select()
|
||||
.from(webauthnCredentials)
|
||||
.where(eq(webauthnCredentials.id, id))
|
||||
.get()
|
||||
}
|
||||
|
||||
export function getWebauthnCredentialByCredentialId(
|
||||
db: AppDb,
|
||||
credentialId: string,
|
||||
): WebauthnCredentialRow | undefined {
|
||||
return db
|
||||
.select()
|
||||
.from(webauthnCredentials)
|
||||
.where(eq(webauthnCredentials.credentialId, credentialId))
|
||||
.get()
|
||||
}
|
||||
|
||||
export function createWebauthnCredential(
|
||||
db: AppDb,
|
||||
input: {
|
||||
userId: string
|
||||
credentialId: string
|
||||
publicKey: string
|
||||
counter: number
|
||||
deviceType?: string | null
|
||||
backedUp?: boolean
|
||||
transports?: string[]
|
||||
name: string
|
||||
},
|
||||
): WebauthnCredentialRow {
|
||||
const id = randomUUID()
|
||||
const now = new Date().toISOString()
|
||||
db.insert(webauthnCredentials)
|
||||
.values({
|
||||
id,
|
||||
userId: input.userId,
|
||||
credentialId: input.credentialId,
|
||||
publicKey: input.publicKey,
|
||||
counter: input.counter,
|
||||
deviceType: input.deviceType ?? null,
|
||||
backedUp: input.backedUp ?? false,
|
||||
transportsJson: input.transports
|
||||
? JSON.stringify(input.transports)
|
||||
: null,
|
||||
name: input.name,
|
||||
createdAt: now,
|
||||
lastUsedAt: null,
|
||||
})
|
||||
.run()
|
||||
return getWebauthnCredentialById(db, id)!
|
||||
}
|
||||
|
||||
export function updateWebauthnCredentialName(
|
||||
db: AppDb,
|
||||
id: string,
|
||||
userId: string,
|
||||
name: string,
|
||||
): WebauthnCredentialRow | undefined {
|
||||
const existing = getWebauthnCredentialById(db, id)
|
||||
if (!existing || existing.userId !== userId) return undefined
|
||||
db.update(webauthnCredentials)
|
||||
.set({ name })
|
||||
.where(
|
||||
and(
|
||||
eq(webauthnCredentials.id, id),
|
||||
eq(webauthnCredentials.userId, userId),
|
||||
),
|
||||
)
|
||||
.run()
|
||||
return getWebauthnCredentialById(db, id)
|
||||
}
|
||||
|
||||
export function touchWebauthnCredential(
|
||||
db: AppDb,
|
||||
id: string,
|
||||
counter: number,
|
||||
): void {
|
||||
db.update(webauthnCredentials)
|
||||
.set({
|
||||
counter,
|
||||
lastUsedAt: new Date().toISOString(),
|
||||
})
|
||||
.where(eq(webauthnCredentials.id, id))
|
||||
.run()
|
||||
}
|
||||
|
||||
export function deleteWebauthnCredential(
|
||||
db: AppDb,
|
||||
id: string,
|
||||
userId: string,
|
||||
): boolean {
|
||||
const result = db
|
||||
.delete(webauthnCredentials)
|
||||
.where(
|
||||
and(
|
||||
eq(webauthnCredentials.id, id),
|
||||
eq(webauthnCredentials.userId, userId),
|
||||
),
|
||||
)
|
||||
.run()
|
||||
return result.changes > 0
|
||||
}
|
||||
|
||||
export function deleteWebauthnCredentialsForUser(
|
||||
db: AppDb,
|
||||
userId: string,
|
||||
): number {
|
||||
const result = db
|
||||
.delete(webauthnCredentials)
|
||||
.where(eq(webauthnCredentials.userId, userId))
|
||||
.run()
|
||||
return result.changes
|
||||
}
|
||||
|
||||
export function parseTransportsJson(raw: string | null): string[] {
|
||||
if (!raw) return []
|
||||
try {
|
||||
const v = JSON.parse(raw) as unknown
|
||||
if (!Array.isArray(v)) return []
|
||||
return v.filter((x): x is string => typeof x === 'string')
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import Database from 'better-sqlite3'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
backupDatabase,
|
||||
checkIntegrity,
|
||||
closeDb,
|
||||
createDb,
|
||||
createUser,
|
||||
getUserByEmail,
|
||||
listBackups,
|
||||
migrateSchema,
|
||||
} from '../src/index.js'
|
||||
|
||||
const dirs: string[] = []
|
||||
const dbs: Array<ReturnType<typeof createDb>['sqlite']> = []
|
||||
afterEach(() => {
|
||||
for (const s of dbs.splice(0)) closeDb(s)
|
||||
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function fileDb() {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'ap-bk-'))
|
||||
dirs.push(dir)
|
||||
const r = createDb(join(dir, 'app.db'))
|
||||
migrateSchema(r.sqlite)
|
||||
dbs.push(r.sqlite)
|
||||
return { dir, ...r }
|
||||
}
|
||||
|
||||
describe('backupDatabase', () => {
|
||||
it('создаёт консистентную копию с данными из WAL', async () => {
|
||||
const { dir, db, sqlite } = fileDb()
|
||||
createUser(db, { email: 'a@x.io', name: 'A', passwordHash: 'h', isAdmin: false })
|
||||
const res = await backupDatabase(sqlite, { dir: join(dir, 'backups'), keep: 3 })
|
||||
expect(existsSync(res.file)).toBe(true)
|
||||
expect(checkIntegrity(res.file)).toBe(true)
|
||||
|
||||
const copy = new Database(res.file, { readonly: true })
|
||||
const row = copy.prepare('SELECT email FROM users').get()
|
||||
copy.close()
|
||||
expect(row).toEqual({ email: 'a@x.io' })
|
||||
})
|
||||
|
||||
it('бэкап во время записи остаётся валидным', async () => {
|
||||
const { dir, db, sqlite } = fileDb()
|
||||
const writer = setInterval(() => {
|
||||
try {
|
||||
createUser(db, {
|
||||
email: `u${Math.random()}@x.io`,
|
||||
name: 'U',
|
||||
passwordHash: 'h',
|
||||
isAdmin: false,
|
||||
})
|
||||
} catch {
|
||||
/* БД могла закрыться */
|
||||
}
|
||||
}, 1)
|
||||
const res = await backupDatabase(sqlite, { dir, keep: 3 })
|
||||
clearInterval(writer)
|
||||
expect(checkIntegrity(res.file)).toBe(true)
|
||||
})
|
||||
|
||||
it('ротация оставляет keep последних', async () => {
|
||||
const { dir, sqlite } = fileDb()
|
||||
const bdir = join(dir, 'b')
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await backupDatabase(sqlite, {
|
||||
dir: bdir,
|
||||
keep: 2,
|
||||
now: new Date(Date.UTC(2026, 0, 1, 0, 0, i)),
|
||||
})
|
||||
}
|
||||
const left = listBackups(bdir)
|
||||
expect(left).toHaveLength(2)
|
||||
expect(left[0]).toContain('000004')
|
||||
})
|
||||
|
||||
it('восстановленная копия открывается и содержит данные', async () => {
|
||||
const { dir, db, sqlite } = fileDb()
|
||||
createUser(db, { email: 'r@x.io', name: 'R', passwordHash: 'h', isAdmin: false })
|
||||
const res = await backupDatabase(sqlite, { dir, keep: 1 })
|
||||
const restored = createDb(res.file)
|
||||
dbs.push(restored.sqlite)
|
||||
migrateSchema(restored.sqlite)
|
||||
expect(getUserByEmail(restored.db, 'r@x.io')?.name).toBe('R')
|
||||
})
|
||||
|
||||
it('битый файл не проходит integrity_check', () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'ap-bad-'))
|
||||
dirs.push(dir)
|
||||
const p = join(dir, 'bad.db')
|
||||
writeFileSync(p, 'not a sqlite file'.repeat(100))
|
||||
expect(() => checkIntegrity(p)).toThrow()
|
||||
})
|
||||
|
||||
it('ошибка бэкапа не оставляет .partial', async () => {
|
||||
const { dir, sqlite } = fileDb()
|
||||
closeDb(sqlite)
|
||||
await expect(backupDatabase(sqlite, { dir: join(dir, 'x'), keep: 1 })).rejects.toThrow()
|
||||
expect(listBackups(join(dir, 'x'))).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,426 @@
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import Database from 'better-sqlite3'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
SCHEMA_VERSION,
|
||||
appendAudit,
|
||||
appendAuditBatch,
|
||||
closeDb,
|
||||
consumeOidcAuthCode,
|
||||
countWebauthnCredentials,
|
||||
createDb,
|
||||
createOidcAuthCode,
|
||||
createRefreshSession,
|
||||
createUser,
|
||||
createWebauthnCredential,
|
||||
getActiveOidcSigningKey,
|
||||
getUserApps,
|
||||
getUserById,
|
||||
getUserPermissions,
|
||||
insertOidcSigningKey,
|
||||
listActiveSessions,
|
||||
listAudit,
|
||||
migrateSchema,
|
||||
revokeSessionById,
|
||||
runHousekeeping,
|
||||
searchDirectoryUsers,
|
||||
setUserAccess,
|
||||
withTransaction,
|
||||
type AppDb,
|
||||
type Sqlite,
|
||||
} from '../src/index.js'
|
||||
|
||||
const open: Sqlite[] = []
|
||||
const dirs: string[] = []
|
||||
|
||||
function memDb(): { db: AppDb; sqlite: Sqlite } {
|
||||
const r = createDb('sqlite::memory:')
|
||||
migrateSchema(r.sqlite)
|
||||
open.push(r.sqlite)
|
||||
return r
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const s of open.splice(0)) closeDb(s)
|
||||
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function mkUser(db: AppDb, email: string, extra: { name?: string } = {}) {
|
||||
return createUser(db, {
|
||||
email,
|
||||
name: extra.name ?? email.split('@')[0]!,
|
||||
passwordHash: 'x',
|
||||
isAdmin: false,
|
||||
})
|
||||
}
|
||||
|
||||
describe('createDb / closeDb', () => {
|
||||
it('выставляет pragma на файловой БД', () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'ap-db-'))
|
||||
dirs.push(dir)
|
||||
const { sqlite } = createDb(join(dir, 'app.db'))
|
||||
open.push(sqlite)
|
||||
expect(sqlite.pragma('journal_mode', { simple: true })).toBe('wal')
|
||||
expect(sqlite.pragma('busy_timeout', { simple: true })).toBe(5000)
|
||||
expect(sqlite.pragma('synchronous', { simple: true })).toBe(1)
|
||||
expect(sqlite.pragma('temp_store', { simple: true })).toBe(2)
|
||||
expect(sqlite.pragma('cache_size', { simple: true })).toBe(-16000)
|
||||
expect(sqlite.pragma('foreign_keys', { simple: true })).toBe(1)
|
||||
})
|
||||
|
||||
it('closeDb идемпотентен', () => {
|
||||
const { sqlite } = memDb()
|
||||
closeDb(sqlite)
|
||||
expect(sqlite.open).toBe(false)
|
||||
expect(() => closeDb(sqlite)).not.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('migrateSchema', () => {
|
||||
it('ставит user_version и повторный запуск — no-op', () => {
|
||||
const { sqlite } = memDb()
|
||||
expect(sqlite.pragma('user_version', { simple: true })).toBe(SCHEMA_VERSION)
|
||||
expect(() => migrateSchema(sqlite)).not.toThrow()
|
||||
})
|
||||
|
||||
it('создаёт новые индексы', () => {
|
||||
const { sqlite } = memDb()
|
||||
const names = (
|
||||
sqlite
|
||||
.prepare(`SELECT name FROM sqlite_master WHERE type='index'`)
|
||||
.all() as Array<{ name: string }>
|
||||
).map((r) => r.name)
|
||||
for (const n of [
|
||||
'uq_user_apps',
|
||||
'uq_user_permissions',
|
||||
'idx_refresh_sessions_expires',
|
||||
'idx_oidc_auth_codes_expires',
|
||||
'idx_audit_log_severity',
|
||||
'idx_audit_log_actor_email',
|
||||
]) {
|
||||
expect(names).toContain(n)
|
||||
}
|
||||
})
|
||||
|
||||
it('мигрирует «старую» схему: дедупликация и недостающие колонки', () => {
|
||||
const sqlite = new Database(':memory:')
|
||||
open.push(sqlite)
|
||||
sqlite.pragma('foreign_keys = ON')
|
||||
sqlite.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY NOT NULL, email TEXT NOT NULL UNIQUE,
|
||||
name TEXT NOT NULL, password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0, disabled INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL, updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE user_apps (user_id TEXT NOT NULL, app_id TEXT NOT NULL);
|
||||
CREATE TABLE user_permissions (user_id TEXT NOT NULL, permission TEXT NOT NULL);
|
||||
INSERT INTO users VALUES ('u1','a@b.c','A','h',0,0,'t','t');
|
||||
INSERT INTO user_apps VALUES ('u1','dns'),('u1','dns'),('u1','vps');
|
||||
INSERT INTO user_permissions VALUES ('u1','p'),('u1','p');
|
||||
`)
|
||||
migrateSchema(sqlite)
|
||||
expect(
|
||||
sqlite.prepare('SELECT COUNT(*) c FROM user_apps').get(),
|
||||
).toEqual({ c: 2 })
|
||||
expect(
|
||||
sqlite.prepare('SELECT COUNT(*) c FROM user_permissions').get(),
|
||||
).toEqual({ c: 1 })
|
||||
const cols = (
|
||||
sqlite.prepare('PRAGMA table_info(users)').all() as Array<{ name: string }>
|
||||
).map((c) => c.name)
|
||||
expect(cols).toContain('last_login_at')
|
||||
expect(sqlite.pragma('user_version', { simple: true })).toBe(SCHEMA_VERSION)
|
||||
expect(() =>
|
||||
sqlite.prepare(`INSERT INTO user_apps VALUES ('u1','dns')`).run(),
|
||||
).toThrow(/UNIQUE/)
|
||||
})
|
||||
|
||||
it('откатывается целиком при ошибке', () => {
|
||||
const sqlite = new Database(':memory:')
|
||||
open.push(sqlite)
|
||||
// users — это view-подобная помеха: таблица с несовместимой схемой user_apps без user_id
|
||||
sqlite.exec(`CREATE TABLE user_apps (foo TEXT)`)
|
||||
expect(() => migrateSchema(sqlite)).toThrow()
|
||||
expect(sqlite.pragma('user_version', { simple: true })).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('withTransaction / setUserAccess', () => {
|
||||
it('откатывает все изменения при исключении', () => {
|
||||
const { db } = memDb()
|
||||
const u = mkUser(db, 'a@x.io')
|
||||
setUserAccess(db, u.id, ['dns'], ['p1'])
|
||||
expect(() =>
|
||||
withTransaction(db, () => {
|
||||
setUserAccess(db, u.id, ['vps', 'bgp'], ['p2'])
|
||||
throw new Error('boom')
|
||||
}),
|
||||
).toThrow('boom')
|
||||
expect(getUserApps(db, u.id)).toEqual(['dns'])
|
||||
expect(getUserPermissions(db, u.id)).toEqual(['p1'])
|
||||
})
|
||||
|
||||
it('схлопывает дубликаты во входе', () => {
|
||||
const { db } = memDb()
|
||||
const u = mkUser(db, 'a@x.io')
|
||||
setUserAccess(db, u.id, ['dns', 'dns'], ['p', 'p'])
|
||||
expect(getUserApps(db, u.id)).toEqual(['dns'])
|
||||
expect(getUserPermissions(db, u.id)).toEqual(['p'])
|
||||
})
|
||||
|
||||
it('вложенная транзакция откатывается как savepoint', () => {
|
||||
const { db } = memDb()
|
||||
const u = mkUser(db, 'a@x.io')
|
||||
withTransaction(db, () => {
|
||||
setUserAccess(db, u.id, ['dns'], [])
|
||||
try {
|
||||
withTransaction(db, () => {
|
||||
setUserAccess(db, u.id, ['vps'], [])
|
||||
throw new Error('inner')
|
||||
})
|
||||
} catch {
|
||||
/* ожидаемо */
|
||||
}
|
||||
})
|
||||
expect(getUserApps(db, u.id)).toEqual(['dns'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('сессии и каталог', () => {
|
||||
it('listActiveSessions: только активные, фильтр по пользователю, сортировка', () => {
|
||||
const { db } = memDb()
|
||||
const a = mkUser(db, 'a@x.io')
|
||||
const b = mkUser(db, 'b@x.io')
|
||||
const future = new Date(Date.now() + 3600_000)
|
||||
const past = new Date(Date.now() - 3600_000)
|
||||
const s1 = createRefreshSession(db, a.id, 't1', future)
|
||||
createRefreshSession(db, a.id, 't2', past)
|
||||
const s3 = createRefreshSession(db, b.id, 't3', future)
|
||||
const s4 = createRefreshSession(db, b.id, 't4', future)
|
||||
revokeSessionById(db, s4)
|
||||
|
||||
const all = listActiveSessions(db).map((s) => s.id)
|
||||
expect(new Set(all)).toEqual(new Set([s1, s3]))
|
||||
expect(listActiveSessions(db, { userId: a.id }).map((s) => s.id)).toEqual([
|
||||
s1,
|
||||
])
|
||||
})
|
||||
|
||||
it('searchDirectoryUsers: без passwordHash, без disabled, LIMIT, экранирование', () => {
|
||||
const { db } = memDb()
|
||||
for (let i = 0; i < 60; i++) mkUser(db, `user${i}@x.io`)
|
||||
const weird = mkUser(db, 'pct@x.io', { name: '100%' })
|
||||
const dis = mkUser(db, 'off@x.io')
|
||||
db.$client.prepare('UPDATE users SET disabled=1 WHERE id=?').run(dis.id)
|
||||
|
||||
const page = searchDirectoryUsers(db, '', 50)
|
||||
expect(page).toHaveLength(50)
|
||||
expect(Object.keys(page[0]!).sort()).toEqual(['email', 'id', 'name'])
|
||||
expect(searchDirectoryUsers(db, 'off@x.io')).toEqual([])
|
||||
expect(searchDirectoryUsers(db, 'USER7@').map((u) => u.email)).toEqual([
|
||||
'user7@x.io',
|
||||
])
|
||||
expect(searchDirectoryUsers(db, '%').map((u) => u.id)).toEqual([weird.id])
|
||||
expect(searchDirectoryUsers(db, weird.id)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('countWebauthnCredentials считает COUNT(*)', () => {
|
||||
const { db } = memDb()
|
||||
const u = mkUser(db, 'a@x.io')
|
||||
expect(countWebauthnCredentials(db, u.id)).toBe(0)
|
||||
for (const id of ['c1', 'c2']) {
|
||||
createWebauthnCredential(db, {
|
||||
userId: u.id,
|
||||
credentialId: id,
|
||||
publicKey: 'k',
|
||||
counter: 0,
|
||||
name: id,
|
||||
})
|
||||
}
|
||||
expect(countWebauthnCredentials(db, u.id)).toBe(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('OIDC', () => {
|
||||
function code(db: AppDb, userId: string, raw: string, expiresAt: Date) {
|
||||
createOidcAuthCode(db, {
|
||||
rawCode: raw,
|
||||
clientId: 'c',
|
||||
userId,
|
||||
redirectUri: 'https://x/cb',
|
||||
scope: 'openid',
|
||||
expiresAt,
|
||||
})
|
||||
}
|
||||
|
||||
it('consumeOidcAuthCode: одноразовый, просроченный отклоняется', () => {
|
||||
const { db } = memDb()
|
||||
const u = mkUser(db, 'a@x.io')
|
||||
code(db, u.id, 'ok', new Date(Date.now() + 60_000))
|
||||
code(db, u.id, 'old', new Date(Date.now() - 60_000))
|
||||
expect(consumeOidcAuthCode(db, 'ok')?.userId).toBe(u.id)
|
||||
expect(consumeOidcAuthCode(db, 'ok')).toBeUndefined()
|
||||
expect(consumeOidcAuthCode(db, 'old')).toBeUndefined()
|
||||
expect(consumeOidcAuthCode(db, 'missing')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('insertOidcSigningKey оставляет один активный ключ — новый', () => {
|
||||
const { db } = memDb()
|
||||
insertOidcSigningKey(db, { kid: 'k1', privatePem: 'p', publicJwkJson: '{}' })
|
||||
insertOidcSigningKey(db, { kid: 'k2', privatePem: 'p', publicJwkJson: '{}' })
|
||||
expect(getActiveOidcSigningKey(db)?.kid).toBe('k2')
|
||||
const active = db.$client
|
||||
.prepare('SELECT COUNT(*) c FROM oidc_signing_keys WHERE active=1')
|
||||
.get()
|
||||
expect(active).toEqual({ c: 1 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('audit', () => {
|
||||
it('appendAudit: дубликат event_id → false', () => {
|
||||
const { db } = memDb()
|
||||
expect(appendAudit(db, { eventId: 'e1', action: 'a', summary: 's' })).toBe(
|
||||
true,
|
||||
)
|
||||
expect(appendAudit(db, { eventId: 'e1', action: 'a', summary: 's' })).toBe(
|
||||
false,
|
||||
)
|
||||
expect(appendAudit(db, { action: 'a', summary: 's' })).toBe(true)
|
||||
expect(appendAudit(db, { action: 'a', summary: 's' })).toBe(true)
|
||||
})
|
||||
|
||||
it('appendAuditBatch: принимает, пропускает дубли, не теряет остальные', () => {
|
||||
const { db } = memDb()
|
||||
const events = Array.from({ length: 500 }, (_, i) => ({
|
||||
eventId: `e${i % 400}`,
|
||||
action: 'x.y',
|
||||
summary: 's',
|
||||
}))
|
||||
const res = appendAuditBatch(db, events)
|
||||
expect(res).toEqual({ accepted: 400, duplicates: 100, failed: 0 })
|
||||
expect(listAudit(db, { limit: 1000 })).toHaveLength(400)
|
||||
})
|
||||
|
||||
it('listAudit kind=logins/changes делит по префиксу auth.', () => {
|
||||
const { db } = memDb()
|
||||
appendAudit(db, { action: 'auth.login', summary: 's' })
|
||||
appendAudit(db, { action: 'auth.login_failed', summary: 's' })
|
||||
appendAudit(db, { action: 'user.create', summary: 's' })
|
||||
appendAudit(db, { action: 'audit.purge', summary: 's' })
|
||||
appendAudit(db, { action: 'authz.other', summary: 's' })
|
||||
const logins = listAudit(db, { kind: 'logins' }).map((e) => e.action)
|
||||
const changes = listAudit(db, { kind: 'changes' }).map((e) => e.action)
|
||||
expect(logins.sort()).toEqual(['auth.login', 'auth.login_failed'])
|
||||
expect(changes.sort()).toEqual(['audit.purge', 'authz.other', 'user.create'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('runHousekeeping', () => {
|
||||
it('удаляет старые истёкшие/отозванные, оставляя активные и свежие', () => {
|
||||
const { db } = memDb()
|
||||
const u = mkUser(db, 'a@x.io')
|
||||
const day = 86_400_000
|
||||
const active = createRefreshSession(db, u.id, 'a', new Date(Date.now() + day))
|
||||
createRefreshSession(db, u.id, 'oldexp', new Date(Date.now() - 10 * day))
|
||||
createRefreshSession(db, u.id, 'freshexp', new Date(Date.now() - day))
|
||||
const oldRevoked = createRefreshSession(
|
||||
db,
|
||||
u.id,
|
||||
'oldrev',
|
||||
new Date(Date.now() + day),
|
||||
)
|
||||
db.$client
|
||||
.prepare('UPDATE refresh_sessions SET revoked_at=? WHERE id=?')
|
||||
.run(new Date(Date.now() - 10 * day).toISOString(), oldRevoked)
|
||||
|
||||
createOidcAuthCode(db, {
|
||||
rawCode: 'stale',
|
||||
clientId: 'c',
|
||||
userId: u.id,
|
||||
redirectUri: 'r',
|
||||
scope: 's',
|
||||
expiresAt: new Date(Date.now() - 10 * day),
|
||||
})
|
||||
createOidcAuthCode(db, {
|
||||
rawCode: 'live',
|
||||
clientId: 'c',
|
||||
userId: u.id,
|
||||
redirectUri: 'r',
|
||||
scope: 's',
|
||||
expiresAt: new Date(Date.now() + 60_000),
|
||||
})
|
||||
db.$client
|
||||
.prepare(
|
||||
`INSERT INTO webauthn_challenges (id,purpose,challenge,expires_at,created_at)
|
||||
VALUES ('c1','register','x',?,?)`,
|
||||
)
|
||||
.run(new Date(Date.now() - 1000).toISOString(), new Date().toISOString())
|
||||
|
||||
const res = runHousekeeping(db, { retentionDays: 7 })
|
||||
expect(res).toEqual({ sessions: 2, authCodes: 1, challenges: 1 })
|
||||
const left = db.$client
|
||||
.prepare('SELECT id FROM refresh_sessions')
|
||||
.all() as Array<{ id: string }>
|
||||
expect(left).toHaveLength(2)
|
||||
expect(left.map((r) => r.id)).toContain(active)
|
||||
|
||||
expect(runHousekeeping(db, { retentionDays: 7 })).toEqual({
|
||||
sessions: 0,
|
||||
authCodes: 0,
|
||||
challenges: 0,
|
||||
})
|
||||
})
|
||||
|
||||
it('удаляет пачками > 1000 строк', () => {
|
||||
const { db } = memDb()
|
||||
const u = mkUser(db, 'a@x.io')
|
||||
const ins = db.$client.prepare(
|
||||
`INSERT INTO refresh_sessions (id,user_id,token_hash,expires_at,created_at)
|
||||
VALUES (?,?,?,?,?)`,
|
||||
)
|
||||
db.$client.transaction(() => {
|
||||
for (let i = 0; i < 2500; i++) {
|
||||
ins.run(`s${i}`, u.id, `h${i}`, '2000-01-01T00:00:00.000Z', 't')
|
||||
}
|
||||
})()
|
||||
expect(runHousekeeping(db, { retentionDays: 1 }).sessions).toBe(2500)
|
||||
})
|
||||
})
|
||||
|
||||
describe('подготовленные запросы', () => {
|
||||
it('горячие запросы не вызывают prepare повторно и дают прежние результаты', () => {
|
||||
const { db, sqlite } = memDb()
|
||||
const u = mkUser(db, 'p@x.io')
|
||||
setUserAccess(db, u.id, ['dns', 'vps'], ['dns:dns:read'])
|
||||
// прогрев: первая подготовка
|
||||
getUserById(db, u.id)
|
||||
getUserApps(db, u.id)
|
||||
getUserPermissions(db, u.id)
|
||||
|
||||
const calls: string[] = []
|
||||
const orig = sqlite.prepare.bind(sqlite)
|
||||
sqlite.prepare = ((sql: string) => {
|
||||
calls.push(sql)
|
||||
return orig(sql)
|
||||
}) as typeof sqlite.prepare
|
||||
|
||||
for (let i = 0; i < 20; i++) {
|
||||
expect(getUserById(db, u.id)?.email).toBe('p@x.io')
|
||||
expect(getUserApps(db, u.id).sort()).toEqual(['dns', 'vps'])
|
||||
expect(getUserPermissions(db, u.id)).toEqual(['dns:dns:read'])
|
||||
}
|
||||
expect(getUserById(db, 'missing')).toBeUndefined()
|
||||
expect(calls).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('независимые соединения не делят подготовленные запросы', () => {
|
||||
const a = memDb()
|
||||
const b = memDb()
|
||||
const ua = mkUser(a.db, 'a@x.io')
|
||||
expect(getUserById(a.db, ua.id)).toBeDefined()
|
||||
expect(getUserById(b.db, ua.id)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,100 @@
|
||||
import { afterAll, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
appendAuditBatch,
|
||||
closeDb,
|
||||
createDb,
|
||||
createUser,
|
||||
getUserApps,
|
||||
getUserById,
|
||||
listActiveSessions,
|
||||
listAudit,
|
||||
migrateSchema,
|
||||
runHousekeeping,
|
||||
searchDirectoryUsers,
|
||||
} from '../../src/index.js'
|
||||
|
||||
const { db, sqlite } = createDb('sqlite::memory:')
|
||||
migrateSchema(sqlite)
|
||||
afterAll(() => closeDb(sqlite))
|
||||
|
||||
function timed<T>(fn: () => T): { ms: number; value: T } {
|
||||
const t0 = performance.now()
|
||||
const value = fn()
|
||||
return { ms: performance.now() - t0, value }
|
||||
}
|
||||
|
||||
// Бюджеты щедрые (CI-раннеры шумные): ловим деградацию на порядок, а не на проценты.
|
||||
describe('бюджеты производительности БД', () => {
|
||||
const users = Array.from({ length: 200 }, (_, i) =>
|
||||
createUser(db, {
|
||||
email: `u${i}@x.io`,
|
||||
name: `User ${i}`,
|
||||
passwordHash: 'h',
|
||||
isAdmin: false,
|
||||
}),
|
||||
)
|
||||
|
||||
it('вставка 100k сессий и фильтр активных по пользователю < 150 мс', () => {
|
||||
const ins = sqlite.prepare(
|
||||
`INSERT INTO refresh_sessions (id,user_id,token_hash,expires_at,created_at)
|
||||
VALUES (?,?,?,?,?)`,
|
||||
)
|
||||
const future = new Date(Date.now() + 86_400_000).toISOString()
|
||||
const past = '2000-01-01T00:00:00.000Z'
|
||||
sqlite.transaction(() => {
|
||||
for (let i = 0; i < 100_000; i++) {
|
||||
ins.run(`s${i}`, users[i % users.length]!.id, `h${i}`, i % 10 === 0 ? future : past, `t${i}`)
|
||||
}
|
||||
})()
|
||||
listActiveSessions(db, { userId: users[0]!.id }) // прогрев
|
||||
const { ms, value } = timed(() => listActiveSessions(db, { userId: users[0]!.id }))
|
||||
console.log(`listActiveSessions(user) на 100k: ${ms.toFixed(1)} мс, ${value.length} строк`)
|
||||
expect(value.length).toBeGreaterThan(0)
|
||||
expect(ms).toBeLessThan(150)
|
||||
})
|
||||
|
||||
it('housekeeping 100k истёкших сессий < 3 с', () => {
|
||||
const { ms, value } = timed(() => runHousekeeping(db, { retentionDays: 1 }))
|
||||
console.log(`runHousekeeping: ${ms.toFixed(0)} мс, удалено ${value.sessions}`)
|
||||
expect(value.sessions).toBeGreaterThan(80_000)
|
||||
expect(ms).toBeLessThan(3000)
|
||||
})
|
||||
|
||||
it('пакетный ingest 10k событий одной транзакцией < 1.5 с', () => {
|
||||
const events = Array.from({ length: 10_000 }, (_, i) => ({
|
||||
eventId: `e${i}`,
|
||||
action: i % 2 ? 'auth.login' : 'user.update',
|
||||
summary: 'bench',
|
||||
}))
|
||||
const { ms, value } = timed(() => appendAuditBatch(db, events))
|
||||
console.log(`appendAuditBatch(10k): ${ms.toFixed(0)} мс`)
|
||||
expect(value.accepted).toBe(10_000)
|
||||
expect(ms).toBeLessThan(1500)
|
||||
})
|
||||
|
||||
it('listAudit по kind использует индекс: < 50 мс на 10k', () => {
|
||||
listAudit(db, { kind: 'logins', limit: 100 })
|
||||
const { ms, value } = timed(() => listAudit(db, { kind: 'logins', limit: 100 }))
|
||||
console.log(`listAudit(kind=logins): ${ms.toFixed(1)} мс`)
|
||||
expect(value.length).toBe(100)
|
||||
expect(ms).toBeLessThan(50)
|
||||
})
|
||||
|
||||
it('10k горячих запросов профиля (prepared) < 400 мс', () => {
|
||||
const id = users[0]!.id
|
||||
const { ms } = timed(() => {
|
||||
for (let i = 0; i < 10_000; i++) {
|
||||
getUserById(db, id)
|
||||
getUserApps(db, id)
|
||||
}
|
||||
})
|
||||
console.log(`20k prepared-запросов: ${ms.toFixed(0)} мс`)
|
||||
expect(ms).toBeLessThan(400)
|
||||
})
|
||||
|
||||
it('поиск каталога по 200 пользователям < 20 мс', () => {
|
||||
searchDirectoryUsers(db, 'user 1')
|
||||
const { ms } = timed(() => searchDirectoryUsers(db, 'user 1'))
|
||||
expect(ms).toBeLessThan(20)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
createMemoryDb, migrateSchema, closeDb, createUser, getUserById,
|
||||
getUserPermissions, setUserAccess, updateUser, deleteUser,
|
||||
createRefreshSession, revokeRefreshSession, revokeSessionById, revokeAllSessionsForUser,
|
||||
enablePortalRevocations,
|
||||
} from '../src/index.js'
|
||||
|
||||
const target = 'https://mm.example.invalid/_internal/mcp/portal/revocations'
|
||||
describe('integrated portal revocation outbox', () => {
|
||||
it('opts in explicitly and retains deletion event independently of user FK', () => {
|
||||
const { db, sqlite } = createMemoryDb(); migrateSchema(sqlite)
|
||||
try {
|
||||
const user = createUser(db, {email:'owned@example.invalid',name:'owned',passwordHash:'synthetic',isAdmin:false})
|
||||
setUserAccess(db,user.id,['mm'],['old'])
|
||||
expect(sqlite.prepare('SELECT count(*) AS n FROM portal_revocation_outbox').get()).toEqual({n:0})
|
||||
enablePortalRevocations(db,target)
|
||||
setUserAccess(db,user.id,['mm'],['new']); deleteUser(db,user.id)
|
||||
const rows = sqlite.prepare('SELECT body FROM portal_revocation_outbox ORDER BY sequence').all() as {body:string}[]
|
||||
expect(rows.map(row=>JSON.parse(row.body).type)).toEqual(['permissions.changed','user.disabled'])
|
||||
for (const row of rows) expect(JSON.parse(row.body)).toMatchObject({version:2,userId:user.id})
|
||||
expect(getUserById(db,user.id)).toBeUndefined()
|
||||
} finally { closeDb(sqlite) }
|
||||
})
|
||||
it('enqueue failure prevents success of every genuine access/disable/delete/session mutation', () => {
|
||||
const { db, sqlite } = createMemoryDb(); migrateSchema(sqlite)
|
||||
try {
|
||||
const user = createUser(db,{email:'atomic@example.invalid',name:'owned',passwordHash:'synthetic',isAdmin:false})
|
||||
setUserAccess(db,user.id,['mm'],['old'])
|
||||
const session = createRefreshSession(db,user.id,'owned-refresh',new Date(Date.now()+60000))
|
||||
enablePortalRevocations(db,target)
|
||||
sqlite.exec("CREATE TRIGGER deny_revocation BEFORE INSERT ON portal_revocation_outbox BEGIN SELECT RAISE(ABORT,'OWNED_ENQUEUE_FAILURE'); END")
|
||||
for (const mutation of [
|
||||
()=>setUserAccess(db,user.id,[],[]), ()=>updateUser(db,user.id,{isAdmin:true}),
|
||||
()=>updateUser(db,user.id,{disabled:true}), ()=>deleteUser(db,user.id),
|
||||
()=>revokeSessionById(db,session), ()=>revokeRefreshSession(db,'owned-refresh'),
|
||||
()=>revokeAllSessionsForUser(db,user.id),
|
||||
]) {
|
||||
expect(mutation).toThrow('OWNED_ENQUEUE_FAILURE')
|
||||
expect(getUserById(db,user.id)).toMatchObject({isAdmin:false,disabled:false})
|
||||
expect(getUserPermissions(db,user.id)).toEqual(['old'])
|
||||
expect(sqlite.prepare('SELECT revoked_at FROM refresh_sessions WHERE id=?').get(session)).toEqual({revoked_at:null})
|
||||
expect(sqlite.prepare('SELECT count(*) AS n FROM portal_revocation_outbox').get()).toEqual({n:0})
|
||||
}
|
||||
} finally { closeDb(sqlite) }
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"declaration": true,
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"ignoreDeprecations": "6.0"
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
passWithNoTests: true,
|
||||
include: ['test/**/*.test.ts'],
|
||||
coverage: {
|
||||
provider: 'v8',
|
||||
include: ['src/**/*.ts'],
|
||||
reporter: ['text-summary', 'lcov'],
|
||||
// Стартовые пороги: поднимать по мере роста покрытия, не снижать.
|
||||
thresholds: { lines: 50 },
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,6 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
// Бюджеты производительности БД (не входят в обычный test): pnpm --filter @authportal/db test:perf
|
||||
export default defineConfig({
|
||||
test: { include: ['test/perf/**/*.perf.ts'], testTimeout: 60_000 },
|
||||
})
|
||||
@@ -0,0 +1,21 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.ts'],
|
||||
extends: [js.configs.recommended, tseslint.configs.recommended],
|
||||
languageOptions: {
|
||||
globals: globals.node,
|
||||
},
|
||||
rules: {
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'error',
|
||||
{ ignoreRestSiblings: true, argsIgnorePattern: '^_', varsIgnorePattern: '^_' },
|
||||
],
|
||||
},
|
||||
},
|
||||
])
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"name": "@authportal/shared",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"files": [
|
||||
"dist",
|
||||
"package.json"
|
||||
],
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"development": "./src/index.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsup src/index.ts --format esm --dts",
|
||||
"dev": "tsup src/index.ts --format esm --dts --watch",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"lint": "eslint .",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"zod": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "catalog:",
|
||||
"@vitest/coverage-v8": "4.1.10",
|
||||
"eslint": "catalog:",
|
||||
"globals": "catalog:",
|
||||
"tsup": "^8.5.0",
|
||||
"typescript": "catalog:",
|
||||
"typescript-eslint": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
APP_IDS,
|
||||
APPS,
|
||||
appAuthModeSchema,
|
||||
appIdSchema,
|
||||
type AppAuthMode,
|
||||
type AppId,
|
||||
type AppMeta,
|
||||
} from './auth.js'
|
||||
|
||||
export const appSwitcherIconSchema = z.enum([
|
||||
'server',
|
||||
'cloud',
|
||||
'globe',
|
||||
'dashboard',
|
||||
'chart',
|
||||
])
|
||||
|
||||
export const appSwitcherEntrySchema = z.object({
|
||||
id: appIdSchema,
|
||||
name: z.string().min(1),
|
||||
subtitle: z.string().optional(),
|
||||
url: z.string().url(),
|
||||
icon: appSwitcherIconSchema,
|
||||
shortcut: z.string().optional(),
|
||||
enabled: z.boolean(),
|
||||
sort: z.number().int().optional(),
|
||||
/** App-scoped tenant (e.g. EvoBGP UUID) — goes into JWT, not public switcher. */
|
||||
tenantId: z.string().optional(),
|
||||
/** jwt = fragment SSO; oidc = open base URL. */
|
||||
authMode: appAuthModeSchema.optional(),
|
||||
})
|
||||
|
||||
export const appSwitcherConfigSchema = z.object({
|
||||
menuLabel: z.string().min(1),
|
||||
apps: z.array(appSwitcherEntrySchema).min(1),
|
||||
})
|
||||
|
||||
export type AppSwitcherIconName = z.infer<typeof appSwitcherIconSchema>
|
||||
export type AppSwitcherEntry = z.infer<typeof appSwitcherEntrySchema>
|
||||
export type AppSwitcherConfig = z.infer<typeof appSwitcherConfigSchema>
|
||||
|
||||
const DEFAULT_ICONS: Record<AppId, AppSwitcherIconName> = {
|
||||
cfdm: 'cloud',
|
||||
vps: 'server',
|
||||
bgp: 'globe',
|
||||
fw: 'server',
|
||||
dns: 'globe',
|
||||
cdn: 'cloud',
|
||||
mm: 'dashboard',
|
||||
}
|
||||
|
||||
const DEFAULT_AUTH_MODE: Record<AppId, AppAuthMode> = {
|
||||
cfdm: 'jwt',
|
||||
vps: 'jwt',
|
||||
bgp: 'jwt',
|
||||
fw: 'jwt',
|
||||
dns: 'oidc',
|
||||
cdn: 'jwt',
|
||||
mm: 'jwt',
|
||||
}
|
||||
|
||||
/** Seed / fallback when DB is empty. */
|
||||
export function defaultAppSwitcherConfig(): AppSwitcherConfig {
|
||||
return {
|
||||
menuLabel: 'Приложения',
|
||||
apps: APPS.map((app, index) => ({
|
||||
id: app.id,
|
||||
name: app.title,
|
||||
subtitle: app.description,
|
||||
url: app.url,
|
||||
icon: DEFAULT_ICONS[app.id],
|
||||
enabled: true,
|
||||
sort: index,
|
||||
authMode: DEFAULT_AUTH_MODE[app.id],
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
export function parseAppSwitcherConfig(raw: unknown): AppSwitcherConfig {
|
||||
const parsed = appSwitcherConfigSchema.safeParse(raw)
|
||||
if (!parsed.success) return defaultAppSwitcherConfig()
|
||||
return normalizeAppSwitcherConfig(parsed.data)
|
||||
}
|
||||
|
||||
/** Ensure all APP_IDS present; sort; drop unknown. */
|
||||
export function normalizeAppSwitcherConfig(
|
||||
config: AppSwitcherConfig,
|
||||
): AppSwitcherConfig {
|
||||
const byId = new Map(config.apps.map((a) => [a.id, a]))
|
||||
const defaults = defaultAppSwitcherConfig()
|
||||
const apps = APP_IDS.map((id, index) => {
|
||||
const existing = byId.get(id)
|
||||
const fallback = defaults.apps.find((a) => a.id === id)!
|
||||
return {
|
||||
...fallback,
|
||||
...existing,
|
||||
id,
|
||||
sort: existing?.sort ?? index,
|
||||
enabled: existing?.enabled ?? true,
|
||||
icon: existing?.icon ?? fallback.icon,
|
||||
tenantId: existing?.tenantId?.trim() || undefined,
|
||||
authMode:
|
||||
existing?.authMode ??
|
||||
fallback.authMode ??
|
||||
DEFAULT_AUTH_MODE[id],
|
||||
}
|
||||
}).sort((a, b) => (a.sort ?? 0) - (b.sort ?? 0))
|
||||
|
||||
return {
|
||||
menuLabel: config.menuLabel || 'Приложения',
|
||||
apps,
|
||||
}
|
||||
}
|
||||
|
||||
/** Public GET must not expose tenant IDs. */
|
||||
export function publicAppSwitcherConfig(
|
||||
config: AppSwitcherConfig,
|
||||
): AppSwitcherConfig {
|
||||
const normalized = normalizeAppSwitcherConfig(config)
|
||||
return {
|
||||
menuLabel: normalized.menuLabel,
|
||||
apps: normalized.apps.map(({ tenantId: _tid, ...rest }) => rest),
|
||||
}
|
||||
}
|
||||
|
||||
/** Map appId → tenantId for JWT (only apps the user may access). */
|
||||
export function tenantsClaimForUser(
|
||||
config: AppSwitcherConfig,
|
||||
userApps: readonly string[],
|
||||
): Record<string, string> {
|
||||
const allowed = new Set(userApps)
|
||||
const out: Record<string, string> = {}
|
||||
for (const app of normalizeAppSwitcherConfig(config).apps) {
|
||||
if (!allowed.has(app.id)) continue
|
||||
const tid = app.tenantId?.trim()
|
||||
if (tid) out[app.id] = tid
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** AppMeta list with URLs from switcher store (for /apps + catalog). */
|
||||
export function appsMetaFromSwitcher(config: AppSwitcherConfig): AppMeta[] {
|
||||
const normalized = normalizeAppSwitcherConfig(config)
|
||||
return normalized.apps
|
||||
.filter((a) => a.enabled !== false)
|
||||
.map((a) => ({
|
||||
id: a.id,
|
||||
title: a.name,
|
||||
description: a.subtitle ?? APPS.find((x) => x.id === a.id)?.description ?? '',
|
||||
url: a.url,
|
||||
authMode: a.authMode ?? DEFAULT_AUTH_MODE[a.id],
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const AUDIT_SEVERITIES = ['info', 'warning', 'critical'] as const
|
||||
export type AuditSeverity = (typeof AUDIT_SEVERITIES)[number]
|
||||
export const auditSeveritySchema = z.enum(AUDIT_SEVERITIES)
|
||||
|
||||
export const AUDIT_SOURCE_APPS = [
|
||||
'portal',
|
||||
'vps',
|
||||
'cfdm',
|
||||
'bgp',
|
||||
'fw',
|
||||
'dns',
|
||||
'cdn',
|
||||
'mm',
|
||||
] as const
|
||||
export type AuditSourceApp = (typeof AUDIT_SOURCE_APPS)[number]
|
||||
export const auditSourceAppSchema = z.enum(AUDIT_SOURCE_APPS)
|
||||
|
||||
export const AUDIT_TARGET_TYPES = [
|
||||
'user',
|
||||
'settings',
|
||||
'session',
|
||||
'system',
|
||||
'app_resource',
|
||||
'credential',
|
||||
] as const
|
||||
export type AuditTargetType = (typeof AUDIT_TARGET_TYPES)[number]
|
||||
export const auditTargetTypeSchema = z.enum(AUDIT_TARGET_TYPES)
|
||||
|
||||
/** Well-known portal-native action keys. */
|
||||
export const AUDIT_ACTIONS = [
|
||||
'auth.login',
|
||||
'auth.login_failed',
|
||||
'auth.logout',
|
||||
'auth.sso_handoff',
|
||||
'user.create',
|
||||
'user.update',
|
||||
'user.delete',
|
||||
'user.access_update',
|
||||
'app_switcher.update',
|
||||
'audit.settings_update',
|
||||
'audit.purge',
|
||||
] as const
|
||||
export type AuditAction = (typeof AUDIT_ACTIONS)[number]
|
||||
export const auditActionSchema = z.enum(AUDIT_ACTIONS)
|
||||
|
||||
export const AUDIT_KINDS = ['logins', 'changes'] as const
|
||||
export type AuditKind = (typeof AUDIT_KINDS)[number]
|
||||
export const auditKindSchema = z.enum(AUDIT_KINDS)
|
||||
|
||||
export const AUTH_AUDIT_ACTIONS = [
|
||||
'auth.login',
|
||||
'auth.login_failed',
|
||||
'auth.logout',
|
||||
'auth.sso_handoff',
|
||||
] as const
|
||||
|
||||
export const auditLogEntrySchema = z.object({
|
||||
id: z.string(),
|
||||
event_id: z.string().nullable(),
|
||||
source_app: auditSourceAppSchema,
|
||||
action: z.string(),
|
||||
severity: auditSeveritySchema,
|
||||
actor_user_id: z.string().nullable(),
|
||||
actor_email: z.string().nullable(),
|
||||
actor_name: z.string().nullable(),
|
||||
target_type: auditTargetTypeSchema.nullable(),
|
||||
target_id: z.string().nullable(),
|
||||
summary: z.string(),
|
||||
details: z.record(z.string(), z.unknown()).nullable(),
|
||||
ip: z.string().nullable(),
|
||||
created_at: z.string(),
|
||||
})
|
||||
export type AuditLogEntry = z.infer<typeof auditLogEntrySchema>
|
||||
|
||||
export const auditListQuerySchema = z.object({
|
||||
action: z.string().optional(),
|
||||
severity: auditSeveritySchema.optional(),
|
||||
user_id: z.string().optional(),
|
||||
actor_email: z.string().email().optional(),
|
||||
source_app: auditSourceAppSchema.optional(),
|
||||
kind: auditKindSchema.optional(),
|
||||
limit: z.coerce.number().int().min(1).max(500).default(200),
|
||||
})
|
||||
export type AuditListQuery = z.infer<typeof auditListQuerySchema>
|
||||
|
||||
export const DEFAULT_AUDIT_RETENTION_DAYS = 90
|
||||
export const MIN_AUDIT_RETENTION_DAYS = 7
|
||||
export const MAX_AUDIT_RETENTION_DAYS = 3650
|
||||
|
||||
export const auditSettingsSchema = z.object({
|
||||
retention_days: z
|
||||
.number()
|
||||
.int()
|
||||
.min(MIN_AUDIT_RETENTION_DAYS)
|
||||
.max(MAX_AUDIT_RETENTION_DAYS),
|
||||
})
|
||||
export type AuditSettings = z.infer<typeof auditSettingsSchema>
|
||||
|
||||
export const putAuditSettingsSchema = auditSettingsSchema
|
||||
export type PutAuditSettings = z.infer<typeof putAuditSettingsSchema>
|
||||
|
||||
export const auditPurgeResponseSchema = z.object({
|
||||
deleted: z.number().int().nonnegative(),
|
||||
retention_days: z.number().int(),
|
||||
})
|
||||
export type AuditPurgeResponse = z.infer<typeof auditPurgeResponseSchema>
|
||||
|
||||
export const ingestAuditEventSchema = z.object({
|
||||
event_id: z.string().min(1).max(128),
|
||||
source_app: z.enum(['vps', 'cfdm', 'bgp', 'fw', 'dns', 'cdn', 'mm']),
|
||||
action: z.string().min(1).max(200),
|
||||
severity: auditSeveritySchema.optional(),
|
||||
actor_user_id: z.string().nullable().optional(),
|
||||
actor_email: z.string().email().nullable().optional(),
|
||||
actor_name: z.string().nullable().optional(),
|
||||
target_type: auditTargetTypeSchema.nullable().optional(),
|
||||
target_id: z.string().nullable().optional(),
|
||||
summary: z.string().min(1).max(500),
|
||||
details: z.record(z.string(), z.unknown()).nullable().optional(),
|
||||
ip: z.string().nullable().optional(),
|
||||
created_at: z.string().optional(),
|
||||
})
|
||||
export type IngestAuditEvent = z.infer<typeof ingestAuditEventSchema>
|
||||
|
||||
export const ingestAuditRequestSchema = z.object({
|
||||
events: z.array(ingestAuditEventSchema).min(1).max(50),
|
||||
})
|
||||
export type IngestAuditRequest = z.infer<typeof ingestAuditRequestSchema>
|
||||
|
||||
export const ingestAuditResponseSchema = z.object({
|
||||
accepted: z.number().int().nonnegative(),
|
||||
duplicates: z.number().int().nonnegative(),
|
||||
})
|
||||
export type IngestAuditResponse = z.infer<typeof ingestAuditResponseSchema>
|
||||
@@ -0,0 +1,541 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const APP_IDS = ['cfdm', 'vps', 'bgp', 'fw', 'dns', 'cdn', 'mm'] as const
|
||||
export type AppId = (typeof APP_IDS)[number]
|
||||
export const appIdSchema = z.enum(APP_IDS)
|
||||
|
||||
export const APP_AUTH_MODES = ['jwt', 'oidc'] as const
|
||||
export type AppAuthMode = (typeof APP_AUTH_MODES)[number]
|
||||
export const appAuthModeSchema = z.enum(APP_AUTH_MODES)
|
||||
|
||||
export const PERMISSION_ACTIONS = ['read', 'write', 'admin', 'approve', 'pause'] as const
|
||||
export type PermissionAction = (typeof PERMISSION_ACTIONS)[number]
|
||||
export const permissionActionSchema = z.enum(PERMISSION_ACTIONS)
|
||||
|
||||
export const PERMISSION_ACTION_LABELS: Readonly<Record<PermissionAction, string>> = Object.freeze({
|
||||
read: 'Чтение', write: 'Редактирование', admin: 'Администрирование',
|
||||
approve: 'Одобрение планов', pause: 'Пауза автоматизации',
|
||||
})
|
||||
export function isIndependentPermissionSection(appId: AppId, sectionId: string): boolean {
|
||||
return appId === 'mm' && sectionId === 'mcp'
|
||||
}
|
||||
/** Toggle ONE explicitly supported independent key; never cascade or normalize unrelated grants. */
|
||||
export function withIndependentPermission(granted: readonly string[], appId: AppId, sectionId: string, action: PermissionAction, enabled: boolean): string[] {
|
||||
const section = PERMISSION_CATALOG.find(app => app.appId === appId)?.sections.find(section => section.id === sectionId)
|
||||
if (!isIndependentPermissionSection(appId, sectionId) || !section?.actions.includes(action)) throw new Error('Unsupported independent permission')
|
||||
const key = permissionKey(appId, sectionId, action)
|
||||
return enabled ? granted.includes(key) ? [...granted] : [...granted, key] : granted.filter(value => value !== key)
|
||||
}
|
||||
|
||||
|
||||
export type AppMeta = {
|
||||
id: AppId
|
||||
title: string
|
||||
description: string
|
||||
url: string
|
||||
/** jwt = fragment SSO; oidc = open base URL (external OIDC RP). */
|
||||
authMode: AppAuthMode
|
||||
}
|
||||
|
||||
export const APPS: AppMeta[] = [
|
||||
{
|
||||
id: 'cfdm',
|
||||
title: 'Cloudflare Domain Manager',
|
||||
description: 'Домены, DNS, сертификаты, группы и сервисы',
|
||||
url: 'https://cfdm.shnt.top',
|
||||
authMode: 'jwt',
|
||||
},
|
||||
{
|
||||
id: 'vps',
|
||||
title: 'VPS Tracker',
|
||||
description: 'Серверы, аккаунты, платежи и синхронизация',
|
||||
url: 'https://vps.shnt.top',
|
||||
authMode: 'jwt',
|
||||
},
|
||||
{
|
||||
id: 'bgp',
|
||||
title: 'EvoBGP',
|
||||
description: 'Модули, сеть, операции и мониторинг BGP',
|
||||
url: 'https://bgp.shnt.top',
|
||||
authMode: 'jwt',
|
||||
},
|
||||
{
|
||||
id: 'fw',
|
||||
title: 'EvoFirewall',
|
||||
description: 'Централизованный firewall: агенты, списки, политики',
|
||||
url: 'https://fw.shnt.top',
|
||||
authMode: 'jwt',
|
||||
},
|
||||
{
|
||||
id: 'dns',
|
||||
title: 'Technitium DNS',
|
||||
description: 'DNS-сервер: зоны, DHCP, блокировки (OIDC SSO)',
|
||||
url: 'https://dns.shnt.top',
|
||||
authMode: 'oidc',
|
||||
},
|
||||
{
|
||||
id: 'cdn',
|
||||
title: 'CDN Manager',
|
||||
description: 'Флот DNS: ноды, алиасы, sync Cloudflare',
|
||||
url: 'https://cdn.shnt.top',
|
||||
authMode: 'jwt',
|
||||
},
|
||||
{
|
||||
id: 'mm',
|
||||
title: 'MikrotikManager',
|
||||
description: 'MikroTik: серверы, фильтры, BGP, uptime',
|
||||
url: 'https://mm.shnt.top',
|
||||
authMode: 'jwt',
|
||||
},
|
||||
]
|
||||
|
||||
export type CatalogSection = {
|
||||
id: string
|
||||
title: string
|
||||
description: string
|
||||
actions: PermissionAction[]
|
||||
}
|
||||
|
||||
export type AppPermissionCatalog = {
|
||||
appId: AppId
|
||||
title: string
|
||||
sections: CatalogSection[]
|
||||
}
|
||||
|
||||
function section(
|
||||
id: string,
|
||||
title: string,
|
||||
description: string,
|
||||
actions: PermissionAction[] = ['read', 'write'],
|
||||
): CatalogSection {
|
||||
return { id, title, description, actions }
|
||||
}
|
||||
|
||||
export const PERMISSION_CATALOG: AppPermissionCatalog[] = [
|
||||
{
|
||||
appId: 'cfdm',
|
||||
title: 'Cloudflare Domain Manager',
|
||||
sections: [
|
||||
section('domains', 'Домены', 'Список и карточки доменов'),
|
||||
section('dns', 'DNS', 'DNS-записи'),
|
||||
section('certificates', 'Сертификаты', 'TLS-сертификаты'),
|
||||
section('groups', 'Группы', 'Группы доменов'),
|
||||
section('services', 'Сервисы', 'Сервисы и привязки'),
|
||||
section('settings', 'Настройки', 'Настройки приложения', ['admin']),
|
||||
],
|
||||
},
|
||||
{
|
||||
appId: 'vps',
|
||||
title: 'VPS Tracker',
|
||||
sections: [
|
||||
section('dashboard', 'Дашборд', 'Обзор и KPI', ['read']),
|
||||
section('vps', 'VPS', 'Виртуальные серверы'),
|
||||
section('accounts', 'Аккаунты', 'Аккаунты провайдеров'),
|
||||
section('payments', 'Платежи', 'Платежи и баланс'),
|
||||
section('sync', 'Синхронизация', 'Запуск sync', ['write']),
|
||||
section('spaces', 'Пространства', 'Управление пространствами и выдачей доступа', [
|
||||
'admin',
|
||||
]),
|
||||
section('settings', 'Настройки', 'Настройки приложения', ['admin']),
|
||||
],
|
||||
},
|
||||
{
|
||||
appId: 'bgp',
|
||||
title: 'EvoBGP',
|
||||
sections: [
|
||||
section('dashboard', 'Панель', 'KPI и обзор', ['read']),
|
||||
section('modules', 'Модули', 'Модули префиксов'),
|
||||
section('lookup', 'Проверка', 'IP/домен в списках и community', ['read']),
|
||||
section('network', 'Сеть', 'BGP-пиры и спикеры'),
|
||||
section('directories', 'Справочники', 'Communities и DoH'),
|
||||
section('operations', 'Операции', 'Ревизии (read/write) и apply/rollback (admin)', [
|
||||
'read',
|
||||
'write',
|
||||
'admin',
|
||||
]),
|
||||
section('schedule', 'Задачи', 'Расписание refresh'),
|
||||
section('monitoring', 'Мониторинг', 'Health и BIRD', ['read']),
|
||||
section('access', 'Доступ', 'API-ключи', ['admin']),
|
||||
section('tenant_settings', 'Настройки BIRD', 'Tenant BIRD config', [
|
||||
'admin',
|
||||
]),
|
||||
section('settings', 'Настройки UI', 'Токен и подключение', ['read']),
|
||||
],
|
||||
},
|
||||
{
|
||||
appId: 'fw',
|
||||
title: 'EvoFirewall',
|
||||
sections: [
|
||||
section('dashboard', 'Дашборд', 'KPI и обзор', ['read']),
|
||||
section('agents', 'Агенты', 'Linux / MikroTik клиенты'),
|
||||
section('lists', 'Списки IP', 'static / JSON / domains / EvoBGP'),
|
||||
section('policies', 'Правила', 'Allow/deny политики и overrides'),
|
||||
section('stats', 'Статистика', 'Пакеты и история', ['read']),
|
||||
section('settings', 'Настройки', 'Enroll seed и интеграции', ['admin']),
|
||||
],
|
||||
},
|
||||
{
|
||||
appId: 'dns',
|
||||
title: 'Technitium DNS',
|
||||
sections: [
|
||||
section('console', 'Консоль', 'Полный доступ Administrators', ['admin']),
|
||||
section('dns', 'DNS', 'Зоны и записи (DNS Administrators)'),
|
||||
section('dhcp', 'DHCP', 'DHCP scopes (DHCP Administrators)'),
|
||||
section('settings', 'Настройки', 'SSO и системные настройки', ['admin']),
|
||||
],
|
||||
},
|
||||
{
|
||||
appId: 'cdn',
|
||||
title: 'CDN Manager',
|
||||
sections: [
|
||||
section('dashboard', 'Панель', 'KPI и обзор', ['read']),
|
||||
section('nodes', 'Ноды', 'Канонические хосты A/AAAA'),
|
||||
section('aliases', 'Алиасы', 'CNAME и retarget'),
|
||||
section('zones', 'Зоны', 'Cloudflare zones и BIND export'),
|
||||
section('sync', 'Синхронизация', 'Pull/diff/apply DNS', ['write']),
|
||||
section('topology', 'Топология', 'Схема флота', ['read']),
|
||||
section('settings', 'Настройки', 'Naming, TTL, Cloudflare', ['admin']),
|
||||
],
|
||||
},
|
||||
{
|
||||
appId: 'mm',
|
||||
title: 'MikrotikManager',
|
||||
sections: [
|
||||
section('dashboard', 'Дашборд', 'Обзор и KPI', ['read']),
|
||||
section('servers', 'Серверы', 'MikroTik / CHR хосты'),
|
||||
section('filters', 'Фильтры', 'Firewall и address-list'),
|
||||
section('bgp', 'BGP', 'BGP-сессии и префиксы'),
|
||||
section('uptime', 'Uptime', 'Пинги и speed-probes'),
|
||||
section('traffic', 'Трафик', 'Интерфейсы и графики'),
|
||||
section('alerts', 'Алерты', 'Правила и Telegram'),
|
||||
section('backups', 'Бэкапы', 'Конфиги и расписание'),
|
||||
section('certificates', 'Сертификаты', 'ACME / TLS'),
|
||||
section('network', 'Сеть', 'GRE, OSPF, пути'),
|
||||
section('users', 'Пользователи MM', 'Учётные записи и привязки интерфейсов в MikrotikManager', ['read', 'write']),
|
||||
section('mcp', 'MCP', 'Одобрение и пауза назначаются отдельно; администрирование включает чтение', ['read', 'approve', 'pause', 'admin']),
|
||||
section('settings', 'Настройки', 'Настройки приложения', ['admin']),
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
export function permissionKey(
|
||||
appId: AppId,
|
||||
sectionId: string,
|
||||
action: PermissionAction,
|
||||
): string {
|
||||
return `${appId}:${sectionId}:${action}`
|
||||
}
|
||||
|
||||
/** Hierarchy: admin ⊃ write ⊃ read within the same section. */
|
||||
export function hasPermission(
|
||||
granted: readonly string[],
|
||||
required: string,
|
||||
): boolean {
|
||||
if (granted.includes(required)) return true
|
||||
const parts = required.split(':')
|
||||
if (parts.length !== 3) return false
|
||||
const [app, section, action] = parts
|
||||
if (action === 'read') {
|
||||
return (
|
||||
granted.includes(`${app}:${section}:write`) ||
|
||||
granted.includes(`${app}:${section}:admin`)
|
||||
)
|
||||
}
|
||||
if (action === 'write') {
|
||||
return granted.includes(`${app}:${section}:admin`)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Allowlist entries: `.shnt.top`, `localhost`, full origins `http://localhost:5173`,
|
||||
* or token `private` for RFC1918 LAN hosts (192.168/10/172.16-31).
|
||||
*/
|
||||
export function isReturnToAllowed(
|
||||
returnTo: string,
|
||||
allowlistCsv: string,
|
||||
): boolean {
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(returnTo)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false
|
||||
|
||||
const entries = allowlistCsv
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
const allowPrivate = entries.some((e) => e.toLowerCase() === 'private')
|
||||
if (allowPrivate && isPrivateHostname(url.hostname)) return true
|
||||
|
||||
for (const entry of entries) {
|
||||
if (entry.toLowerCase() === 'private') continue
|
||||
if (entry.startsWith('.')) {
|
||||
const suffix = entry.slice(1)
|
||||
if (url.hostname === suffix || url.hostname.endsWith(entry)) return true
|
||||
continue
|
||||
}
|
||||
if (entry.includes('://')) {
|
||||
try {
|
||||
if (url.origin === new URL(entry).origin) return true
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (url.hostname === entry || url.hostname.endsWith(`.${entry}`)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function isPrivateHostname(hostname: string): boolean {
|
||||
if (hostname === 'localhost' || hostname.endsWith('.local')) return true
|
||||
const m = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(hostname)
|
||||
if (!m) return false
|
||||
const a = Number(m[1])
|
||||
const b = Number(m[2])
|
||||
if (a === 10) return true
|
||||
if (a === 192 && b === 168) return true
|
||||
if (a === 172 && b >= 16 && b <= 31) return true
|
||||
return false
|
||||
}
|
||||
|
||||
/** Decode JWT payload without verifying signature (claims sync only). */
|
||||
export function readJwtPayload(token: string): Record<string, unknown> | null {
|
||||
try {
|
||||
const parts = token.split('.')
|
||||
if (parts.length < 2) return null
|
||||
const json = atob(parts[1]!.replace(/-/g, '+').replace(/_/g, '/'))
|
||||
return JSON.parse(json) as Record<string, unknown>
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** Decode JWT `exp` without verifying signature. Returns null if missing/invalid. */
|
||||
export function readJwtExp(token: string): number | null {
|
||||
const payload = readJwtPayload(token)
|
||||
if (!payload) return null
|
||||
return typeof payload.exp === 'number' ? payload.exp : null
|
||||
}
|
||||
|
||||
/** True when token is missing exp or exp is in the past (30s clock-skew grace). */
|
||||
export function isJwtExpired(token: string, nowMs: number = Date.now()): boolean {
|
||||
const exp = readJwtExp(token)
|
||||
if (exp == null) return true
|
||||
return exp * 1000 < nowMs - 30_000
|
||||
}
|
||||
|
||||
export function buildSsoRedirectUrl(
|
||||
returnTo: string,
|
||||
accessToken: string,
|
||||
expiresAt: string,
|
||||
): string {
|
||||
const hash = new URLSearchParams({
|
||||
access_token: accessToken,
|
||||
expires_at: expiresAt,
|
||||
})
|
||||
const base = returnTo.split('#')[0] ?? returnTo
|
||||
return `${base}#${hash.toString()}`
|
||||
}
|
||||
|
||||
export function allPermissionKeys(): string[] {
|
||||
const keys: string[] = []
|
||||
for (const app of PERMISSION_CATALOG) {
|
||||
for (const sec of app.sections) {
|
||||
for (const action of sec.actions) {
|
||||
keys.push(permissionKey(app.appId, sec.id, action))
|
||||
}
|
||||
}
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
/** Old bgp section ids → current catalog (peers/apply/settings renamed). */
|
||||
const LEGACY_PERMISSION_MAP: Record<string, string> = {
|
||||
'bgp:peers:read': 'bgp:network:read',
|
||||
'bgp:peers:write': 'bgp:network:write',
|
||||
'bgp:apply:write': 'bgp:operations:admin',
|
||||
'bgp:settings:admin': 'bgp:tenant_settings:admin',
|
||||
}
|
||||
|
||||
/**
|
||||
* Map legacy keys and drop anything not in the current catalog.
|
||||
* Safe for JWT issue and admin save after catalog changes.
|
||||
*/
|
||||
export function normalizePermissionKeys(
|
||||
permissions: readonly string[],
|
||||
): string[] {
|
||||
const allowed = new Set(allPermissionKeys())
|
||||
const out = new Set<string>()
|
||||
for (const raw of permissions) {
|
||||
const mapped = LEGACY_PERMISSION_MAP[raw] ?? raw
|
||||
if (allowed.has(mapped)) {
|
||||
out.add(mapped)
|
||||
}
|
||||
}
|
||||
return [...out].sort()
|
||||
}
|
||||
|
||||
export const permissionKeySchema = z
|
||||
.string()
|
||||
.regex(/^(?:[a-z]+:[a-z0-9_]+:(?:read|write|admin)|mm:mcp:(?:approve|pause))$/)
|
||||
|
||||
export const meResponseSchema = z.object({
|
||||
id: z.string(),
|
||||
email: z.string().email(),
|
||||
name: z.string(),
|
||||
is_admin: z.boolean(),
|
||||
apps: z.array(appIdSchema),
|
||||
permissions: z.array(z.string()),
|
||||
})
|
||||
export type MeResponse = z.infer<typeof meResponseSchema>
|
||||
|
||||
export const loginRequestSchema = z.object({
|
||||
email: z.string().email(),
|
||||
password: z.string().min(1),
|
||||
return_to: z.string().url().optional(),
|
||||
})
|
||||
export type LoginRequest = z.infer<typeof loginRequestSchema>
|
||||
|
||||
export const loginResponseSchema = z.object({
|
||||
access_token: z.string(),
|
||||
expires_at: z.string(),
|
||||
token_type: z.literal('Bearer'),
|
||||
user: meResponseSchema,
|
||||
})
|
||||
export type LoginResponse = z.infer<typeof loginResponseSchema>
|
||||
|
||||
export const accessTokenClaimsSchema = z.object({
|
||||
sub: z.string(),
|
||||
email: z.string().email(),
|
||||
name: z.string(),
|
||||
apps: z.array(z.string()),
|
||||
permissions: z.array(z.string()),
|
||||
is_admin: z.boolean().optional(),
|
||||
iss: z.string(),
|
||||
aud: z.string().optional(),
|
||||
exp: z.number(),
|
||||
iat: z.number(),
|
||||
})
|
||||
export type AccessTokenClaims = z.infer<typeof accessTokenClaimsSchema>
|
||||
|
||||
export const catalogResponseSchema = z.object({
|
||||
apps: z.array(
|
||||
z.object({
|
||||
id: appIdSchema,
|
||||
title: z.string(),
|
||||
description: z.string(),
|
||||
url: z.string(),
|
||||
authMode: appAuthModeSchema.optional(),
|
||||
}),
|
||||
),
|
||||
permissions: z.array(
|
||||
z.object({
|
||||
appId: appIdSchema,
|
||||
title: z.string(),
|
||||
sections: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
title: z.string(),
|
||||
description: z.string(),
|
||||
actions: z.array(permissionActionSchema),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
})
|
||||
export type CatalogResponse = z.infer<typeof catalogResponseSchema>
|
||||
|
||||
export const adminUserSchema = z.object({
|
||||
id: z.string(),
|
||||
email: z.string().email(),
|
||||
name: z.string(),
|
||||
is_admin: z.boolean(),
|
||||
disabled: z.boolean(),
|
||||
apps: z.array(appIdSchema),
|
||||
permissions: z.array(z.string()),
|
||||
last_login_at: z.string().nullable(),
|
||||
last_login_ip: z.string().nullable(),
|
||||
passkey_count: z.number().int().nonnegative().default(0),
|
||||
created_at: z.string(),
|
||||
updated_at: z.string(),
|
||||
})
|
||||
export type AdminUser = z.infer<typeof adminUserSchema>
|
||||
|
||||
export const passkeyCredentialSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
created_at: z.string(),
|
||||
last_used_at: z.string().nullable(),
|
||||
device_type: z.string().nullable(),
|
||||
})
|
||||
export type PasskeyCredential = z.infer<typeof passkeyCredentialSchema>
|
||||
|
||||
export const webauthnOptionsResponseSchema = z.object({
|
||||
challenge_id: z.string(),
|
||||
options: z.record(z.string(), z.unknown()),
|
||||
})
|
||||
export type WebauthnOptionsResponse = z.infer<
|
||||
typeof webauthnOptionsResponseSchema
|
||||
>
|
||||
|
||||
export const webauthnVerifyRequestSchema = z.object({
|
||||
challenge_id: z.string().min(1),
|
||||
response: z.unknown(),
|
||||
return_to: z.string().url().optional(),
|
||||
name: z.string().min(1).max(80).optional(),
|
||||
})
|
||||
export type WebauthnVerifyRequest = z.infer<typeof webauthnVerifyRequestSchema>
|
||||
|
||||
export const patchPasskeyRequestSchema = z.object({
|
||||
name: z.string().min(1).max(80),
|
||||
})
|
||||
export type PatchPasskeyRequest = z.infer<typeof patchPasskeyRequestSchema>
|
||||
|
||||
export const adminSessionSchema = z.object({
|
||||
id: z.string(),
|
||||
user_id: z.string(),
|
||||
email: z.string().email(),
|
||||
name: z.string(),
|
||||
ip: z.string().nullable(),
|
||||
user_agent: z.string().nullable(),
|
||||
created_at: z.string(),
|
||||
expires_at: z.string(),
|
||||
})
|
||||
export type AdminSession = z.infer<typeof adminSessionSchema>
|
||||
|
||||
export const ssoAccessRequestSchema = z.object({
|
||||
return_to: z.string().url(),
|
||||
})
|
||||
export type SsoAccessRequest = z.infer<typeof ssoAccessRequestSchema>
|
||||
|
||||
export const createUserRequestSchema = z.object({
|
||||
email: z.string().email(),
|
||||
name: z.string().min(1),
|
||||
password: z.string().min(6),
|
||||
is_admin: z.boolean().default(false),
|
||||
apps: z.array(appIdSchema).default([]),
|
||||
permissions: z.array(permissionKeySchema).default([]),
|
||||
})
|
||||
export type CreateUserRequest = z.infer<typeof createUserRequestSchema>
|
||||
|
||||
export const patchUserRequestSchema = z.object({
|
||||
email: z.string().email().optional(),
|
||||
name: z.string().min(1).optional(),
|
||||
password: z.string().min(6).optional(),
|
||||
is_admin: z.boolean().optional(),
|
||||
disabled: z.boolean().optional(),
|
||||
})
|
||||
export type PatchUserRequest = z.infer<typeof patchUserRequestSchema>
|
||||
|
||||
export const putUserAccessRequestSchema = z.object({
|
||||
apps: z.array(appIdSchema),
|
||||
permissions: z.array(permissionKeySchema),
|
||||
})
|
||||
export type PutUserAccessRequest = z.infer<typeof putUserAccessRequestSchema>
|
||||
@@ -0,0 +1,101 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const OIDC_SCOPES = ['openid', 'profile', 'email', 'groups'] as const
|
||||
export type OidcScope = (typeof OIDC_SCOPES)[number]
|
||||
|
||||
/** Remote groups for Technitium Group Map (and similar RPs). */
|
||||
export const TECHNITIUM_OIDC_GROUPS = {
|
||||
admins: 'technitium_admins',
|
||||
dnsAdmins: 'technitium_dns_admins',
|
||||
dhcpAdmins: 'technitium_dhcp_admins',
|
||||
} as const
|
||||
|
||||
/**
|
||||
* Map portal permissions / admin flag → OIDC group names for Technitium.
|
||||
* Used in id_token + userinfo `groups` and `roles` claims.
|
||||
*/
|
||||
export function oidcGroupsForUser(input: {
|
||||
isAdmin: boolean
|
||||
permissions: readonly string[]
|
||||
}): string[] {
|
||||
const granted = new Set(input.permissions)
|
||||
const groups: string[] = []
|
||||
if (input.isAdmin || granted.has('dns:console:admin')) {
|
||||
groups.push(TECHNITIUM_OIDC_GROUPS.admins)
|
||||
}
|
||||
if (
|
||||
granted.has('dns:dns:write') ||
|
||||
granted.has('dns:dns:admin') ||
|
||||
granted.has('dns:console:admin') ||
|
||||
input.isAdmin
|
||||
) {
|
||||
groups.push(TECHNITIUM_OIDC_GROUPS.dnsAdmins)
|
||||
}
|
||||
if (
|
||||
granted.has('dns:dhcp:write') ||
|
||||
granted.has('dns:dhcp:admin') ||
|
||||
granted.has('dns:console:admin') ||
|
||||
input.isAdmin
|
||||
) {
|
||||
groups.push(TECHNITIUM_OIDC_GROUPS.dhcpAdmins)
|
||||
}
|
||||
return [...new Set(groups)]
|
||||
}
|
||||
|
||||
export const createOidcClientRequestSchema = z.object({
|
||||
name: z.string().min(1).max(200),
|
||||
redirect_uris: z.array(z.string().url()).min(1),
|
||||
scopes: z
|
||||
.array(z.enum(OIDC_SCOPES))
|
||||
.min(1)
|
||||
.default([...OIDC_SCOPES]),
|
||||
enabled: z.boolean().default(true),
|
||||
})
|
||||
export type CreateOidcClientRequest = z.infer<
|
||||
typeof createOidcClientRequestSchema
|
||||
>
|
||||
|
||||
export const patchOidcClientRequestSchema = z.object({
|
||||
name: z.string().min(1).max(200).optional(),
|
||||
redirect_uris: z.array(z.string().url()).min(1).optional(),
|
||||
scopes: z.array(z.enum(OIDC_SCOPES)).min(1).optional(),
|
||||
enabled: z.boolean().optional(),
|
||||
})
|
||||
export type PatchOidcClientRequest = z.infer<
|
||||
typeof patchOidcClientRequestSchema
|
||||
>
|
||||
|
||||
export const oidcClientPublicSchema = z.object({
|
||||
id: z.string(),
|
||||
client_id: z.string(),
|
||||
name: z.string(),
|
||||
redirect_uris: z.array(z.string()),
|
||||
scopes: z.array(z.string()),
|
||||
enabled: z.boolean(),
|
||||
created_at: z.string(),
|
||||
updated_at: z.string(),
|
||||
})
|
||||
export type OidcClientPublic = z.infer<typeof oidcClientPublicSchema>
|
||||
|
||||
export const oidcClientCreatedSchema = oidcClientPublicSchema.extend({
|
||||
client_secret: z.string(),
|
||||
})
|
||||
export type OidcClientCreated = z.infer<typeof oidcClientCreatedSchema>
|
||||
|
||||
/** True when return_to is portal OIDC authorize (no JWT fragment handoff). */
|
||||
export function isPortalOidcAuthorizeUrl(
|
||||
returnTo: string,
|
||||
issuer: string,
|
||||
): boolean {
|
||||
try {
|
||||
const url = new URL(returnTo)
|
||||
const iss = new URL(issuer)
|
||||
if (url.origin !== iss.origin) return false
|
||||
return (
|
||||
url.pathname === '/oauth/authorize' ||
|
||||
url.pathname === '/oauth/authorize/'
|
||||
)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export * from './contracts/auth.js'
|
||||
export * from './contracts/app-switcher.js'
|
||||
export * from './contracts/audit.js'
|
||||
export * from './contracts/oidc.js'
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
APP_IDS,
|
||||
allPermissionKeys,
|
||||
appsMetaFromSwitcher,
|
||||
buildSsoRedirectUrl,
|
||||
createOidcClientRequestSchema,
|
||||
defaultAppSwitcherConfig,
|
||||
hasPermission,
|
||||
isJwtExpired,
|
||||
isPortalOidcAuthorizeUrl,
|
||||
isReturnToAllowed,
|
||||
loginRequestSchema,
|
||||
normalizeAppSwitcherConfig,
|
||||
normalizePermissionKeys,
|
||||
oidcGroupsForUser,
|
||||
parseAppSwitcherConfig,
|
||||
permissionKey,
|
||||
publicAppSwitcherConfig,
|
||||
readJwtExp,
|
||||
readJwtPayload,
|
||||
tenantsClaimForUser,
|
||||
} from '../src/index.js'
|
||||
|
||||
function jwt(payload: object): string {
|
||||
const b64 = (o: object) => Buffer.from(JSON.stringify(o)).toString('base64url')
|
||||
return `${b64({ alg: 'none' })}.${b64(payload)}.sig`
|
||||
}
|
||||
|
||||
describe('permissions', () => {
|
||||
it('иерархия admin ⊃ write ⊃ read в пределах секции', () => {
|
||||
expect(hasPermission(['dns:dns:admin'], 'dns:dns:write')).toBe(true)
|
||||
expect(hasPermission(['dns:dns:admin'], 'dns:dns:read')).toBe(true)
|
||||
expect(hasPermission(['dns:dns:write'], 'dns:dns:read')).toBe(true)
|
||||
expect(hasPermission(['dns:dns:read'], 'dns:dns:write')).toBe(false)
|
||||
expect(hasPermission(['dns:dns:admin'], 'dns:dhcp:read')).toBe(false)
|
||||
expect(hasPermission([], 'broken')).toBe(false)
|
||||
})
|
||||
|
||||
it('permissionKey / allPermissionKeys согласованы', () => {
|
||||
expect(permissionKey('dns', 'dns', 'read')).toBe('dns:dns:read')
|
||||
const all = allPermissionKeys()
|
||||
expect(new Set(all).size).toBe(all.length)
|
||||
expect(all).toContain('dns:dns:read')
|
||||
})
|
||||
|
||||
it('normalizePermissionKeys: легаси мапятся, неизвестные отбрасываются, результат отсортирован', () => {
|
||||
const out = normalizePermissionKeys([
|
||||
'bgp:peers:read',
|
||||
'bgp:settings:admin',
|
||||
'nope:x:read',
|
||||
'dns:dns:read',
|
||||
'dns:dns:read',
|
||||
])
|
||||
expect(out).toEqual([...out].sort())
|
||||
expect(out).toContain('bgp:network:read')
|
||||
expect(out).toContain('bgp:tenant_settings:admin')
|
||||
expect(out).toContain('dns:dns:read')
|
||||
expect(out).not.toContain('nope:x:read')
|
||||
expect(out.filter((k) => k === 'dns:dns:read')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('oidcGroupsForUser', () => {
|
||||
it('админ получает все группы Technitium', () => {
|
||||
expect(oidcGroupsForUser({ isAdmin: true, permissions: [] })).toEqual([
|
||||
'technitium_admins',
|
||||
'technitium_dns_admins',
|
||||
'technitium_dhcp_admins',
|
||||
])
|
||||
})
|
||||
|
||||
it('права dns/dhcp дают соответствующие группы', () => {
|
||||
expect(
|
||||
oidcGroupsForUser({ isAdmin: false, permissions: ['dns:dns:write'] }),
|
||||
).toEqual(['technitium_dns_admins'])
|
||||
expect(
|
||||
oidcGroupsForUser({ isAdmin: false, permissions: ['dns:dhcp:admin'] }),
|
||||
).toEqual(['technitium_dhcp_admins'])
|
||||
expect(oidcGroupsForUser({ isAdmin: false, permissions: [] })).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('isReturnToAllowed', () => {
|
||||
it.each([
|
||||
['https://cfdm.shnt.top/x', '.shnt.top', true],
|
||||
['https://shnt.top', '.shnt.top', true],
|
||||
['https://evilshnt.top', '.shnt.top', false],
|
||||
['http://localhost:5173/cb', 'localhost', true],
|
||||
['http://192.168.1.5/x', 'private', true],
|
||||
['http://172.32.0.1/x', 'private', false],
|
||||
['https://8.8.8.8', 'private', false],
|
||||
['http://localhost:5173/a', 'http://localhost:5173', true],
|
||||
['http://localhost:5174/a', 'http://localhost:5173', false],
|
||||
['javascript:alert(1)', 'localhost', false],
|
||||
['not a url', 'localhost', false],
|
||||
])('%s vs %s → %s', (url, list, expected) => {
|
||||
expect(isReturnToAllowed(url, list)).toBe(expected)
|
||||
})
|
||||
})
|
||||
|
||||
describe('JWT helpers', () => {
|
||||
it('читает payload и exp, определяет протухание с запасом 30 c', () => {
|
||||
const exp = Math.floor(Date.now() / 1000) + 3600
|
||||
const t = jwt({ sub: 'u1', exp })
|
||||
expect(readJwtPayload(t)).toMatchObject({ sub: 'u1' })
|
||||
expect(readJwtExp(t)).toBe(exp)
|
||||
expect(isJwtExpired(t)).toBe(false)
|
||||
expect(isJwtExpired(jwt({ exp: 1 }))).toBe(true)
|
||||
const justExpired = jwt({ exp: Math.floor(Date.now() / 1000) - 10 })
|
||||
expect(isJwtExpired(justExpired)).toBe(false)
|
||||
expect(isJwtExpired(jwt({ sub: 'no-exp' }))).toBe(true)
|
||||
expect(readJwtPayload('garbage')).toBeNull()
|
||||
expect(readJwtExp('a.b')).toBeNull()
|
||||
})
|
||||
|
||||
it('buildSsoRedirectUrl кладёт токен во фрагмент и заменяет старый', () => {
|
||||
const url = buildSsoRedirectUrl('https://a.shnt.top/p?x=1#old', 'T', 'E')
|
||||
expect(url.startsWith('https://a.shnt.top/p?x=1#')).toBe(true)
|
||||
expect(url).toContain('access_token=T')
|
||||
expect(url).not.toContain('old')
|
||||
})
|
||||
})
|
||||
|
||||
describe('app switcher', () => {
|
||||
it('default содержит все приложения', () => {
|
||||
const d = defaultAppSwitcherConfig()
|
||||
expect(d.apps.map((a) => a.id).sort()).toEqual([...APP_IDS].sort())
|
||||
})
|
||||
|
||||
it('parseAppSwitcherConfig: мусор → default, неполный конфиг дополняется', () => {
|
||||
expect(parseAppSwitcherConfig({ nope: 1 })).toEqual(defaultAppSwitcherConfig())
|
||||
const partial = parseAppSwitcherConfig({
|
||||
menuLabel: 'Меню',
|
||||
apps: [
|
||||
{
|
||||
id: 'dns',
|
||||
name: 'DNS!',
|
||||
url: 'https://dns.example.com',
|
||||
icon: 'globe',
|
||||
enabled: false,
|
||||
tenantId: ' ',
|
||||
},
|
||||
],
|
||||
})
|
||||
expect(partial.menuLabel).toBe('Меню')
|
||||
expect(partial.apps).toHaveLength(APP_IDS.length)
|
||||
const dns = partial.apps.find((a) => a.id === 'dns')!
|
||||
expect(dns.name).toBe('DNS!')
|
||||
expect(dns.enabled).toBe(false)
|
||||
expect(dns.tenantId).toBeUndefined()
|
||||
})
|
||||
|
||||
it('public-конфиг без tenantId; tenants-claim только по доступным приложениям', () => {
|
||||
const base = defaultAppSwitcherConfig()
|
||||
const cfg = normalizeAppSwitcherConfig({
|
||||
...base,
|
||||
apps: base.apps.map((a) => (a.id === 'bgp' ? { ...a, tenantId: 'tenant-1' } : a)),
|
||||
})
|
||||
expect(JSON.stringify(publicAppSwitcherConfig(cfg))).not.toContain('tenant-1')
|
||||
expect(tenantsClaimForUser(cfg, ['bgp'])).toEqual({ bgp: 'tenant-1' })
|
||||
expect(tenantsClaimForUser(cfg, ['dns'])).toEqual({})
|
||||
})
|
||||
|
||||
it('appsMetaFromSwitcher скрывает отключённые приложения', () => {
|
||||
const cfg = defaultAppSwitcherConfig()
|
||||
cfg.apps = cfg.apps.map((a) => (a.id === 'dns' ? { ...a, enabled: false } : a))
|
||||
expect(appsMetaFromSwitcher(cfg).some((a) => a.id === 'dns')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('zod-схемы', () => {
|
||||
it('login: email и непустой пароль обязательны', () => {
|
||||
expect(loginRequestSchema.safeParse({ email: 'a@b.co', password: 'x' }).success).toBe(true)
|
||||
expect(loginRequestSchema.safeParse({ email: 'bad', password: 'x' }).success).toBe(false)
|
||||
expect(loginRequestSchema.safeParse({ email: 'a@b.co', password: '' }).success).toBe(false)
|
||||
})
|
||||
|
||||
it('createOidcClient: scopes по умолчанию, redirect_uris не пустой', () => {
|
||||
const ok = createOidcClientRequestSchema.parse({
|
||||
name: 'c',
|
||||
redirect_uris: ['https://x.example/cb'],
|
||||
})
|
||||
expect(ok.scopes).toContain('openid')
|
||||
expect(ok.enabled).toBe(true)
|
||||
expect(
|
||||
createOidcClientRequestSchema.safeParse({ name: 'c', redirect_uris: [] }).success,
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('isPortalOidcAuthorizeUrl', () => {
|
||||
const iss = 'https://auth.shnt.top'
|
||||
expect(isPortalOidcAuthorizeUrl(`${iss}/oauth/authorize?x=1`, iss)).toBe(true)
|
||||
expect(isPortalOidcAuthorizeUrl(`${iss}/oauth/authorize/`, iss)).toBe(true)
|
||||
expect(isPortalOidcAuthorizeUrl('https://evil.example/oauth/authorize', iss)).toBe(false)
|
||||
expect(isPortalOidcAuthorizeUrl(`${iss}/other`, iss)).toBe(false)
|
||||
expect(isPortalOidcAuthorizeUrl('nope', iss)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"declaration": true,
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"ignoreDeprecations": "6.0"
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
passWithNoTests: true,
|
||||
include: ['test/**/*.test.ts'],
|
||||
coverage: {
|
||||
provider: 'v8',
|
||||
include: ['src/**/*.ts'],
|
||||
reporter: ['text-summary', 'lcov'],
|
||||
// Стартовые пороги: поднимать по мере роста покрытия, не снижать.
|
||||
thresholds: { lines: 90 },
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "base-nova",
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/styles/globals.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"iconLibrary": "lucide",
|
||||
"rtl": false,
|
||||
"aliases": {
|
||||
"components": "@authportal/ui/components",
|
||||
"utils": "@authportal/ui/lib/utils",
|
||||
"ui": "@authportal/ui/components",
|
||||
"lib": "@authportal/ui/lib",
|
||||
"hooks": "@authportal/ui/hooks"
|
||||
},
|
||||
"menuColor": "default",
|
||||
"menuAccent": "subtle"
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "@authportal/ui",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
"./globals.css": "./src/styles/globals.css",
|
||||
"./components/*": "./src/components/*.tsx",
|
||||
"./lib/*": "./src/lib/*.ts",
|
||||
"./hooks/*": "./src/hooks/*.ts"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "catalog:",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "catalog:",
|
||||
"react-day-picker": "^10.0.1",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"tw-animate-css": "^1.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"tailwindcss": "^4.3.1",
|
||||
"typescript": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import * as React from "react"
|
||||
import { AlertDialog as AlertDialogPrimitive } from "@base-ui/react/alert-dialog"
|
||||
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
import { Button } from "@authportal/ui/components/button"
|
||||
|
||||
function AlertDialog({ ...props }: AlertDialogPrimitive.Root.Props) {
|
||||
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
|
||||
}
|
||||
|
||||
function AlertDialogTrigger({ ...props }: AlertDialogPrimitive.Trigger.Props) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogPortal({ ...props }: AlertDialogPrimitive.Portal.Props) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: AlertDialogPrimitive.Backdrop.Props) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Backdrop
|
||||
data-slot="alert-dialog-overlay"
|
||||
className={cn(
|
||||
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogContent({
|
||||
className,
|
||||
size = "default",
|
||||
...props
|
||||
}: AlertDialogPrimitive.Popup.Props & {
|
||||
size?: "default" | "sm"
|
||||
}) {
|
||||
return (
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay />
|
||||
<AlertDialogPrimitive.Popup
|
||||
data-slot="alert-dialog-content"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid w-full -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none data-[size=default]:max-w-xs data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</AlertDialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogHeader({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-header"
|
||||
className={cn(
|
||||
"grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-4 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogFooter({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-footer"
|
||||
className={cn(
|
||||
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogMedia({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-media"
|
||||
className={cn(
|
||||
"mb-2 inline-flex size-10 items-center justify-center rounded-md bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-6",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Title
|
||||
data-slot="alert-dialog-title"
|
||||
className={cn(
|
||||
"text-base font-medium sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Description
|
||||
data-slot="alert-dialog-description"
|
||||
className={cn(
|
||||
"text-sm text-balance text-muted-foreground md:text-pretty *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogAction({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
return (
|
||||
<Button
|
||||
data-slot="alert-dialog-action"
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogCancel({
|
||||
className,
|
||||
variant = "outline",
|
||||
size = "default",
|
||||
...props
|
||||
}: AlertDialogPrimitive.Close.Props &
|
||||
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Close
|
||||
data-slot="alert-dialog-cancel"
|
||||
className={cn(className)}
|
||||
render={<Button variant={variant} size={size} />}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogMedia,
|
||||
AlertDialogOverlay,
|
||||
AlertDialogPortal,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Avatar as AvatarPrimitive } from "@base-ui/react/avatar"
|
||||
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
|
||||
function Avatar({
|
||||
className,
|
||||
size = "default",
|
||||
...props
|
||||
}: AvatarPrimitive.Root.Props & {
|
||||
size?: "default" | "sm" | "lg"
|
||||
}) {
|
||||
return (
|
||||
<AvatarPrimitive.Root
|
||||
data-slot="avatar"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarImage({ className, ...props }: AvatarPrimitive.Image.Props) {
|
||||
return (
|
||||
<AvatarPrimitive.Image
|
||||
data-slot="avatar-image"
|
||||
className={cn(
|
||||
"aspect-square size-full rounded-full object-cover",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarFallback({
|
||||
className,
|
||||
...props
|
||||
}: AvatarPrimitive.Fallback.Props) {
|
||||
return (
|
||||
<AvatarPrimitive.Fallback
|
||||
data-slot="avatar-fallback"
|
||||
className={cn(
|
||||
"flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="avatar-badge"
|
||||
className={cn(
|
||||
"absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground bg-blend-color ring-2 ring-background select-none",
|
||||
"group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
|
||||
"group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",
|
||||
"group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="avatar-group"
|
||||
className={cn(
|
||||
"group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarGroupCount({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="avatar-group-count"
|
||||
className={cn(
|
||||
"relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm text-muted-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Avatar,
|
||||
AvatarImage,
|
||||
AvatarFallback,
|
||||
AvatarGroup,
|
||||
AvatarGroupCount,
|
||||
AvatarBadge,
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import * as React from "react"
|
||||
import { mergeProps } from "@base-ui/react/merge-props"
|
||||
import { useRender } from "@base-ui/react/use-render"
|
||||
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
import { ChevronRightIcon, MoreHorizontalIcon } from "lucide-react"
|
||||
|
||||
function Breadcrumb({ className, ...props }: React.ComponentProps<"nav">) {
|
||||
return (
|
||||
<nav
|
||||
aria-label="breadcrumb"
|
||||
data-slot="breadcrumb"
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
|
||||
return (
|
||||
<ol
|
||||
data-slot="breadcrumb-list"
|
||||
className={cn(
|
||||
"flex flex-wrap items-center gap-1.5 text-sm wrap-break-word text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="breadcrumb-item"
|
||||
className={cn("inline-flex items-center gap-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbLink({
|
||||
className,
|
||||
render,
|
||||
...props
|
||||
}: useRender.ComponentProps<"a">) {
|
||||
return useRender({
|
||||
defaultTagName: "a",
|
||||
props: mergeProps<"a">(
|
||||
{
|
||||
className: cn("transition-colors hover:text-foreground", className),
|
||||
},
|
||||
props
|
||||
),
|
||||
render,
|
||||
state: {
|
||||
slot: "breadcrumb-link",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function BreadcrumbPage({ className, ...props }: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="breadcrumb-page"
|
||||
role="link"
|
||||
aria-disabled="true"
|
||||
aria-current="page"
|
||||
className={cn("font-normal text-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbSeparator({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="breadcrumb-separator"
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
className={cn("[&>svg]:size-3.5", className)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? (
|
||||
<ChevronRightIcon />
|
||||
)}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbEllipsis({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="breadcrumb-ellipsis"
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"flex size-5 items-center justify-center [&>svg]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<MoreHorizontalIcon
|
||||
/>
|
||||
<span className="sr-only">More</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Breadcrumb,
|
||||
BreadcrumbList,
|
||||
BreadcrumbItem,
|
||||
BreadcrumbLink,
|
||||
BreadcrumbPage,
|
||||
BreadcrumbSeparator,
|
||||
BreadcrumbEllipsis,
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { mergeProps } from "@base-ui/react/merge-props"
|
||||
import { useRender } from "@base-ui/react/use-render"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
|
||||
import { Separator } from "@authportal/ui/components/separator"
|
||||
|
||||
const buttonGroupVariants = cva(
|
||||
"flex w-fit items-stretch *:focus-visible:relative *:focus-visible:z-10 has-[>[data-slot=button-group]]:gap-2 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-lg [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1",
|
||||
{
|
||||
variants: {
|
||||
orientation: {
|
||||
horizontal:
|
||||
"*:data-slot:rounded-r-none [&>[data-slot]:not(:has(~[data-slot]))]:rounded-r-lg! [&>[data-slot]~[data-slot]]:rounded-l-none [&>[data-slot]~[data-slot]]:border-l-0",
|
||||
vertical:
|
||||
"flex-col *:data-slot:rounded-b-none [&>[data-slot]:not(:has(~[data-slot]))]:rounded-b-lg! [&>[data-slot]~[data-slot]]:rounded-t-none [&>[data-slot]~[data-slot]]:border-t-0",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
orientation: "horizontal",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function ButtonGroup({
|
||||
className,
|
||||
orientation,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & VariantProps<typeof buttonGroupVariants>) {
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
data-slot="button-group"
|
||||
data-orientation={orientation}
|
||||
className={cn(buttonGroupVariants({ orientation }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ButtonGroupText({
|
||||
className,
|
||||
render,
|
||||
...props
|
||||
}: useRender.ComponentProps<"div">) {
|
||||
return useRender({
|
||||
defaultTagName: "div",
|
||||
props: mergeProps<"div">(
|
||||
{
|
||||
className: cn(
|
||||
"flex items-center gap-2 rounded-lg border bg-muted px-2.5 text-sm font-medium [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
),
|
||||
},
|
||||
props
|
||||
),
|
||||
render,
|
||||
state: {
|
||||
slot: "button-group-text",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function ButtonGroupSeparator({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: React.ComponentProps<typeof Separator>) {
|
||||
return (
|
||||
<Separator
|
||||
data-slot="button-group-separator"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"relative self-stretch bg-input data-horizontal:mx-px data-horizontal:w-auto data-vertical:my-px data-vertical:h-auto",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
ButtonGroup,
|
||||
ButtonGroupSeparator,
|
||||
ButtonGroupText,
|
||||
buttonGroupVariants,
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Button as ButtonPrimitive } from "@base-ui/react/button"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/80",
|
||||
outline:
|
||||
"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
|
||||
ghost:
|
||||
"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
|
||||
destructive:
|
||||
"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default:
|
||||
"h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
||||
xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
|
||||
sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
|
||||
lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
||||
icon: "size-8",
|
||||
"icon-xs":
|
||||
"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
|
||||
"icon-sm":
|
||||
"size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
|
||||
"icon-lg": "size-9",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
...props
|
||||
}: ButtonPrimitive.Props & VariantProps<typeof buttonVariants>) {
|
||||
return (
|
||||
<ButtonPrimitive
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
@@ -0,0 +1,221 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
DayPicker,
|
||||
getDefaultClassNames,
|
||||
type DayButton,
|
||||
type Locale,
|
||||
} from "react-day-picker"
|
||||
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
import { Button, buttonVariants } from "@authportal/ui/components/button"
|
||||
import { ChevronLeftIcon, ChevronRightIcon, ChevronDownIcon } from "lucide-react"
|
||||
|
||||
function Calendar({
|
||||
className,
|
||||
classNames,
|
||||
showOutsideDays = true,
|
||||
captionLayout = "label",
|
||||
buttonVariant = "ghost",
|
||||
locale,
|
||||
formatters,
|
||||
components,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DayPicker> & {
|
||||
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
|
||||
}) {
|
||||
const defaultClassNames = getDefaultClassNames()
|
||||
|
||||
return (
|
||||
<DayPicker
|
||||
showOutsideDays={showOutsideDays}
|
||||
className={cn(
|
||||
"group/calendar bg-background p-2 [--cell-radius:var(--radius-md)] [--cell-size:--spacing(7)] in-data-[slot=card-content]:bg-transparent in-data-[slot=popover-content]:bg-transparent",
|
||||
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
|
||||
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
|
||||
className
|
||||
)}
|
||||
captionLayout={captionLayout}
|
||||
locale={locale}
|
||||
formatters={{
|
||||
formatMonthDropdown: (date) =>
|
||||
date.toLocaleString(locale?.code, { month: "short" }),
|
||||
...formatters,
|
||||
}}
|
||||
classNames={{
|
||||
root: cn("w-fit", defaultClassNames.root),
|
||||
months: cn(
|
||||
"relative flex flex-col gap-4 md:flex-row",
|
||||
defaultClassNames.months
|
||||
),
|
||||
month: cn("flex w-full flex-col gap-4", defaultClassNames.month),
|
||||
nav: cn(
|
||||
"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",
|
||||
defaultClassNames.nav
|
||||
),
|
||||
button_previous: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
||||
defaultClassNames.button_previous
|
||||
),
|
||||
button_next: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
||||
defaultClassNames.button_next
|
||||
),
|
||||
month_caption: cn(
|
||||
"flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)",
|
||||
defaultClassNames.month_caption
|
||||
),
|
||||
dropdowns: cn(
|
||||
"flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium",
|
||||
defaultClassNames.dropdowns
|
||||
),
|
||||
dropdown_root: cn(
|
||||
"relative rounded-(--cell-radius)",
|
||||
defaultClassNames.dropdown_root
|
||||
),
|
||||
dropdown: cn(
|
||||
"absolute inset-0 bg-popover opacity-0",
|
||||
defaultClassNames.dropdown
|
||||
),
|
||||
caption_label: cn(
|
||||
"font-medium select-none",
|
||||
captionLayout === "label"
|
||||
? "text-sm"
|
||||
: "flex items-center gap-1 rounded-(--cell-radius) text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground",
|
||||
defaultClassNames.caption_label
|
||||
),
|
||||
month_grid: cn("w-full border-collapse", defaultClassNames.month_grid),
|
||||
weekdays: cn("flex", defaultClassNames.weekdays),
|
||||
weekday: cn(
|
||||
"flex-1 rounded-(--cell-radius) text-[0.8rem] font-normal text-muted-foreground select-none",
|
||||
defaultClassNames.weekday
|
||||
),
|
||||
week: cn("mt-2 flex w-full", defaultClassNames.week),
|
||||
week_number_header: cn(
|
||||
"w-(--cell-size) select-none",
|
||||
defaultClassNames.week_number_header
|
||||
),
|
||||
week_number: cn(
|
||||
"text-[0.8rem] text-muted-foreground select-none",
|
||||
defaultClassNames.week_number
|
||||
),
|
||||
day: cn(
|
||||
"group/day relative aspect-square h-full w-full rounded-(--cell-radius) p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-(--cell-radius)",
|
||||
props.showWeekNumber
|
||||
? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-(--cell-radius)"
|
||||
: "[&:first-child[data-selected=true]_button]:rounded-l-(--cell-radius)",
|
||||
defaultClassNames.day
|
||||
),
|
||||
range_start: cn(
|
||||
"relative isolate z-0 rounded-l-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:right-0 after:w-4 after:bg-muted",
|
||||
defaultClassNames.range_start
|
||||
),
|
||||
range_middle: cn("rounded-none", defaultClassNames.range_middle),
|
||||
range_end: cn(
|
||||
"relative isolate z-0 rounded-r-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:left-0 after:w-4 after:bg-muted",
|
||||
defaultClassNames.range_end
|
||||
),
|
||||
today: cn(
|
||||
"rounded-(--cell-radius) bg-muted text-foreground data-[selected=true]:rounded-none",
|
||||
defaultClassNames.today
|
||||
),
|
||||
outside: cn(
|
||||
"text-muted-foreground aria-selected:text-muted-foreground",
|
||||
defaultClassNames.outside
|
||||
),
|
||||
disabled: cn(
|
||||
"text-muted-foreground opacity-50",
|
||||
defaultClassNames.disabled
|
||||
),
|
||||
hidden: cn("invisible", defaultClassNames.hidden),
|
||||
...classNames,
|
||||
}}
|
||||
components={{
|
||||
Root: ({ className, rootRef, ...props }) => {
|
||||
return (
|
||||
<div
|
||||
data-slot="calendar"
|
||||
ref={rootRef}
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
},
|
||||
Chevron: ({ className, orientation, ...props }) => {
|
||||
if (orientation === "left") {
|
||||
return (
|
||||
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
if (orientation === "right") {
|
||||
return (
|
||||
<ChevronRightIcon className={cn("size-4", className)} {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<ChevronDownIcon className={cn("size-4", className)} {...props} />
|
||||
)
|
||||
},
|
||||
DayButton: ({ ...props }) => (
|
||||
<CalendarDayButton locale={locale} {...props} />
|
||||
),
|
||||
WeekNumber: ({ children, ...props }) => {
|
||||
return (
|
||||
<td {...props}>
|
||||
<div className="flex size-(--cell-size) items-center justify-center text-center">
|
||||
{children}
|
||||
</div>
|
||||
</td>
|
||||
)
|
||||
},
|
||||
...components,
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CalendarDayButton({
|
||||
className,
|
||||
day,
|
||||
modifiers,
|
||||
locale,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DayButton> & { locale?: Partial<Locale> }) {
|
||||
const defaultClassNames = getDefaultClassNames()
|
||||
|
||||
const ref = React.useRef<HTMLButtonElement>(null)
|
||||
React.useEffect(() => {
|
||||
if (modifiers.focused) ref.current?.focus()
|
||||
}, [modifiers.focused])
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
data-day={day.date.toLocaleDateString(locale?.code)}
|
||||
data-selected-single={
|
||||
modifiers.selected &&
|
||||
!modifiers.range_start &&
|
||||
!modifiers.range_end &&
|
||||
!modifiers.range_middle
|
||||
}
|
||||
data-range-start={modifiers.range_start}
|
||||
data-range-end={modifiers.range_end}
|
||||
data-range-middle={modifiers.range_middle}
|
||||
className={cn(
|
||||
"relative isolate z-10 flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 border-0 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-(--cell-radius) data-[range-end=true]:rounded-r-(--cell-radius) data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-muted data-[range-middle=true]:text-foreground data-[range-start=true]:rounded-(--cell-radius) data-[range-start=true]:rounded-l-(--cell-radius) data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-foreground [&>span]:text-xs [&>span]:opacity-70",
|
||||
defaultClassNames.day,
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Calendar, CalendarDayButton }
|
||||
@@ -0,0 +1,103 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
|
||||
function Card({
|
||||
className,
|
||||
size = "default",
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-xl bg-card py-(--card-spacing) text-sm text-card-foreground ring-1 ring-foreground/10 [--card-spacing:--spacing(4)] has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(3)] data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-(--card-spacing) has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-(--card-spacing)",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn(
|
||||
"text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-(--card-spacing)", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn(
|
||||
"flex items-center rounded-b-xl border-t bg-muted/50 p-(--card-spacing)",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardAction,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
"use client"
|
||||
|
||||
import { Checkbox as CheckboxPrimitive } from "@base-ui/react/checkbox"
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
import { CheckIcon } from "lucide-react"
|
||||
|
||||
function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) {
|
||||
return (
|
||||
<CheckboxPrimitive.Root
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
"peer relative flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-input transition-colors outline-none group-has-disabled/field:opacity-50 group-has-[:focus-visible]/field-label:ring-0 group-has-[:focus-visible]/field-label:not-data-checked:border-input after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground group-has-[:focus-visible]/field-label:data-checked:border-primary dark:data-checked:bg-primary",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
data-slot="checkbox-indicator"
|
||||
className="grid place-content-center text-current transition-none [&>svg]:size-3.5"
|
||||
>
|
||||
<CheckIcon
|
||||
/>
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Checkbox }
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Collapsible as CollapsiblePrimitive } from "@base-ui/react/collapsible"
|
||||
|
||||
function Collapsible({ ...props }: CollapsiblePrimitive.Root.Props) {
|
||||
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
|
||||
}
|
||||
|
||||
function CollapsibleTrigger({ ...props }: CollapsiblePrimitive.Trigger.Props) {
|
||||
return (
|
||||
<CollapsiblePrimitive.Trigger data-slot="collapsible-trigger" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function CollapsibleContent({ ...props }: CollapsiblePrimitive.Panel.Props) {
|
||||
return (
|
||||
<CollapsiblePrimitive.Panel data-slot="collapsible-content" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
export { Collapsible, CollapsibleTrigger, CollapsibleContent }
|
||||
@@ -0,0 +1,295 @@
|
||||
import * as React from "react"
|
||||
import { Combobox as ComboboxPrimitive } from "@base-ui/react"
|
||||
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
import { Button } from "@authportal/ui/components/button"
|
||||
import {
|
||||
InputGroup,
|
||||
InputGroupAddon,
|
||||
InputGroupButton,
|
||||
InputGroupInput,
|
||||
} from "@authportal/ui/components/input-group"
|
||||
import { ChevronDownIcon, XIcon, CheckIcon } from "lucide-react"
|
||||
|
||||
const Combobox = ComboboxPrimitive.Root
|
||||
|
||||
function ComboboxValue({ ...props }: ComboboxPrimitive.Value.Props) {
|
||||
return <ComboboxPrimitive.Value data-slot="combobox-value" {...props} />
|
||||
}
|
||||
|
||||
function ComboboxTrigger({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: ComboboxPrimitive.Trigger.Props) {
|
||||
return (
|
||||
<ComboboxPrimitive.Trigger
|
||||
data-slot="combobox-trigger"
|
||||
className={cn("[&_svg:not([class*='size-'])]:size-4", className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />
|
||||
</ComboboxPrimitive.Trigger>
|
||||
)
|
||||
}
|
||||
|
||||
function ComboboxClear({ className, ...props }: ComboboxPrimitive.Clear.Props) {
|
||||
return (
|
||||
<ComboboxPrimitive.Clear
|
||||
data-slot="combobox-clear"
|
||||
render={<InputGroupButton variant="ghost" size="icon-xs" />}
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
>
|
||||
<XIcon className="pointer-events-none" />
|
||||
</ComboboxPrimitive.Clear>
|
||||
)
|
||||
}
|
||||
|
||||
function ComboboxInput({
|
||||
className,
|
||||
children,
|
||||
disabled = false,
|
||||
showTrigger = true,
|
||||
showClear = false,
|
||||
...props
|
||||
}: ComboboxPrimitive.Input.Props & {
|
||||
showTrigger?: boolean
|
||||
showClear?: boolean
|
||||
}) {
|
||||
return (
|
||||
<InputGroup className={cn("w-auto", className)}>
|
||||
<ComboboxPrimitive.Input
|
||||
render={<InputGroupInput disabled={disabled} />}
|
||||
{...props}
|
||||
/>
|
||||
<InputGroupAddon align="inline-end">
|
||||
{showTrigger && (
|
||||
<InputGroupButton
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
render={<ComboboxTrigger />}
|
||||
data-slot="input-group-button"
|
||||
className="group-has-data-[slot=combobox-clear]/input-group:hidden data-pressed:bg-transparent"
|
||||
disabled={disabled}
|
||||
/>
|
||||
)}
|
||||
{showClear && <ComboboxClear disabled={disabled} />}
|
||||
</InputGroupAddon>
|
||||
{children}
|
||||
</InputGroup>
|
||||
)
|
||||
}
|
||||
|
||||
function ComboboxContent({
|
||||
className,
|
||||
side = "bottom",
|
||||
sideOffset = 6,
|
||||
align = "start",
|
||||
alignOffset = 0,
|
||||
anchor,
|
||||
...props
|
||||
}: ComboboxPrimitive.Popup.Props &
|
||||
Pick<
|
||||
ComboboxPrimitive.Positioner.Props,
|
||||
"side" | "align" | "sideOffset" | "alignOffset" | "anchor"
|
||||
>) {
|
||||
return (
|
||||
<ComboboxPrimitive.Portal>
|
||||
<ComboboxPrimitive.Positioner
|
||||
side={side}
|
||||
sideOffset={sideOffset}
|
||||
align={align}
|
||||
alignOffset={alignOffset}
|
||||
anchor={anchor}
|
||||
className="isolate z-50"
|
||||
>
|
||||
<ComboboxPrimitive.Popup
|
||||
data-slot="combobox-content"
|
||||
data-chips={!!anchor}
|
||||
className={cn("group/combobox-content relative max-h-(--available-height) w-(--anchor-width) max-w-(--available-width) min-w-[calc(var(--anchor-width)+--spacing(7))] origin-(--transform-origin) overflow-hidden rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[chips=true]:min-w-(--anchor-width) data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 *:data-[slot=input-group]:m-1 *:data-[slot=input-group]:mb-0 *:data-[slot=input-group]:h-8 *:data-[slot=input-group]:border-input/30 *:data-[slot=input-group]:bg-input/30 *:data-[slot=input-group]:shadow-none data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
|
||||
{...props}
|
||||
/>
|
||||
</ComboboxPrimitive.Positioner>
|
||||
</ComboboxPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function ComboboxList({ className, ...props }: ComboboxPrimitive.List.Props) {
|
||||
return (
|
||||
<ComboboxPrimitive.List
|
||||
data-slot="combobox-list"
|
||||
className={cn(
|
||||
"no-scrollbar max-h-[min(calc(--spacing(72)---spacing(9)),calc(var(--available-height)---spacing(9)))] scroll-py-1 overflow-y-auto overscroll-contain p-1 data-empty:p-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ComboboxItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: ComboboxPrimitive.Item.Props) {
|
||||
return (
|
||||
<ComboboxPrimitive.Item
|
||||
data-slot="combobox-item"
|
||||
className={cn(
|
||||
"relative flex w-full cursor-default items-center gap-2 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground not-data-[variant=destructive]:data-highlighted:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ComboboxPrimitive.ItemIndicator
|
||||
render={
|
||||
<span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center" />
|
||||
}
|
||||
>
|
||||
<CheckIcon className="pointer-events-none" />
|
||||
</ComboboxPrimitive.ItemIndicator>
|
||||
</ComboboxPrimitive.Item>
|
||||
)
|
||||
}
|
||||
|
||||
function ComboboxGroup({ className, ...props }: ComboboxPrimitive.Group.Props) {
|
||||
return (
|
||||
<ComboboxPrimitive.Group
|
||||
data-slot="combobox-group"
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ComboboxLabel({
|
||||
className,
|
||||
...props
|
||||
}: ComboboxPrimitive.GroupLabel.Props) {
|
||||
return (
|
||||
<ComboboxPrimitive.GroupLabel
|
||||
data-slot="combobox-label"
|
||||
className={cn("px-2 py-1.5 text-xs text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ComboboxCollection({ ...props }: ComboboxPrimitive.Collection.Props) {
|
||||
return (
|
||||
<ComboboxPrimitive.Collection data-slot="combobox-collection" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ComboboxEmpty({ className, ...props }: ComboboxPrimitive.Empty.Props) {
|
||||
return (
|
||||
<ComboboxPrimitive.Empty
|
||||
data-slot="combobox-empty"
|
||||
className={cn(
|
||||
"hidden w-full justify-center py-2 text-center text-sm text-muted-foreground group-data-empty/combobox-content:flex",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ComboboxSeparator({
|
||||
className,
|
||||
...props
|
||||
}: ComboboxPrimitive.Separator.Props) {
|
||||
return (
|
||||
<ComboboxPrimitive.Separator
|
||||
data-slot="combobox-separator"
|
||||
className={cn("-mx-1 my-1 h-px bg-border", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ComboboxChips({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentPropsWithRef<typeof ComboboxPrimitive.Chips> &
|
||||
ComboboxPrimitive.Chips.Props) {
|
||||
return (
|
||||
<ComboboxPrimitive.Chips
|
||||
data-slot="combobox-chips"
|
||||
className={cn(
|
||||
"flex min-h-8 flex-wrap items-center gap-1 rounded-lg border border-input bg-transparent bg-clip-padding px-2.5 py-1 text-sm transition-colors focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50 has-aria-invalid:border-destructive has-aria-invalid:ring-3 has-aria-invalid:ring-destructive/20 has-data-[slot=combobox-chip]:px-1 dark:bg-input/30 dark:has-aria-invalid:border-destructive/50 dark:has-aria-invalid:ring-destructive/40",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ComboboxChip({
|
||||
className,
|
||||
children,
|
||||
showRemove = true,
|
||||
...props
|
||||
}: ComboboxPrimitive.Chip.Props & {
|
||||
showRemove?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ComboboxPrimitive.Chip
|
||||
data-slot="combobox-chip"
|
||||
className={cn(
|
||||
"flex h-[calc(--spacing(5.25))] w-fit items-center justify-center gap-1 rounded-sm bg-muted px-1.5 text-xs font-medium whitespace-nowrap text-foreground has-disabled:pointer-events-none has-disabled:cursor-not-allowed has-disabled:opacity-50 has-data-[slot=combobox-chip-remove]:pr-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showRemove && (
|
||||
<ComboboxPrimitive.ChipRemove
|
||||
render={<Button variant="ghost" size="icon-xs" />}
|
||||
className="-ml-1 opacity-50 hover:opacity-100"
|
||||
data-slot="combobox-chip-remove"
|
||||
>
|
||||
<XIcon className="pointer-events-none" />
|
||||
</ComboboxPrimitive.ChipRemove>
|
||||
)}
|
||||
</ComboboxPrimitive.Chip>
|
||||
)
|
||||
}
|
||||
|
||||
function ComboboxChipsInput({
|
||||
className,
|
||||
...props
|
||||
}: ComboboxPrimitive.Input.Props) {
|
||||
return (
|
||||
<ComboboxPrimitive.Input
|
||||
data-slot="combobox-chip-input"
|
||||
className={cn("min-w-16 flex-1 outline-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function useComboboxAnchor() {
|
||||
return React.useRef<HTMLDivElement | null>(null)
|
||||
}
|
||||
|
||||
export {
|
||||
Combobox,
|
||||
ComboboxInput,
|
||||
ComboboxContent,
|
||||
ComboboxList,
|
||||
ComboboxItem,
|
||||
ComboboxGroup,
|
||||
ComboboxLabel,
|
||||
ComboboxCollection,
|
||||
ComboboxEmpty,
|
||||
ComboboxSeparator,
|
||||
ComboboxChips,
|
||||
ComboboxChip,
|
||||
ComboboxChipsInput,
|
||||
ComboboxTrigger,
|
||||
ComboboxValue,
|
||||
useComboboxAnchor,
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"
|
||||
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
import { Button } from "@authportal/ui/components/button"
|
||||
import { XIcon } from "lucide-react"
|
||||
|
||||
function Dialog({ ...props }: DialogPrimitive.Root.Props) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
}
|
||||
|
||||
function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
}
|
||||
|
||||
function DialogClose({ ...props }: DialogPrimitive.Close.Props) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: DialogPrimitive.Backdrop.Props) {
|
||||
return (
|
||||
<DialogPrimitive.Backdrop
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: DialogPrimitive.Popup.Props & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Popup
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close
|
||||
data-slot="dialog-close"
|
||||
render={
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="absolute top-2 right-2"
|
||||
size="icon-sm"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<XIcon
|
||||
/>
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Popup>
|
||||
</DialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogFooter({
|
||||
className,
|
||||
showCloseButton = false,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close render={<Button variant="outline" />}>
|
||||
Close
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn(
|
||||
"text-base leading-none font-medium",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: DialogPrimitive.Description.Props) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn(
|
||||
"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Menu as MenuPrimitive } from "@base-ui/react/menu"
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
import { ChevronRightIcon, CheckIcon } from "lucide-react"
|
||||
|
||||
function DropdownMenu({ ...props }: MenuPrimitive.Root.Props) {
|
||||
return <MenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuPortal({ ...props }: MenuPrimitive.Portal.Props) {
|
||||
return <MenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuTrigger({ ...props }: MenuPrimitive.Trigger.Props) {
|
||||
return <MenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuContent({
|
||||
align = "start",
|
||||
alignOffset = 0,
|
||||
side = "bottom",
|
||||
sideOffset = 4,
|
||||
className,
|
||||
...props
|
||||
}: MenuPrimitive.Popup.Props &
|
||||
Pick<
|
||||
MenuPrimitive.Positioner.Props,
|
||||
"align" | "alignOffset" | "side" | "sideOffset"
|
||||
>) {
|
||||
return (
|
||||
<MenuPrimitive.Portal>
|
||||
<MenuPrimitive.Positioner
|
||||
className="isolate z-50 outline-none"
|
||||
align={align}
|
||||
alignOffset={alignOffset}
|
||||
side={side}
|
||||
sideOffset={sideOffset}
|
||||
>
|
||||
<MenuPrimitive.Popup
|
||||
data-slot="dropdown-menu-content"
|
||||
className={cn("z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95", className )}
|
||||
{...props}
|
||||
/>
|
||||
</MenuPrimitive.Positioner>
|
||||
</MenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuGroup({ ...props }: MenuPrimitive.Group.Props) {
|
||||
return <MenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: MenuPrimitive.GroupLabel.Props & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<MenuPrimitive.GroupLabel
|
||||
data-slot="dropdown-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: MenuPrimitive.Item.Props & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<MenuPrimitive.Item
|
||||
data-slot="dropdown-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSub({ ...props }: MenuPrimitive.SubmenuRoot.Props) {
|
||||
return <MenuPrimitive.SubmenuRoot data-slot="dropdown-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: MenuPrimitive.SubmenuTrigger.Props & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<MenuPrimitive.SubmenuTrigger
|
||||
data-slot="dropdown-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-popup-open:bg-accent data-popup-open:text-accent-foreground data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto" />
|
||||
</MenuPrimitive.SubmenuTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSubContent({
|
||||
align = "start",
|
||||
alignOffset = -3,
|
||||
side = "right",
|
||||
sideOffset = 0,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuContent>) {
|
||||
return (
|
||||
<DropdownMenuContent
|
||||
data-slot="dropdown-menu-sub-content"
|
||||
className={cn("w-auto min-w-[96px] rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
|
||||
align={align}
|
||||
alignOffset={alignOffset}
|
||||
side={side}
|
||||
sideOffset={sideOffset}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
inset,
|
||||
...props
|
||||
}: MenuPrimitive.CheckboxItem.Props & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<MenuPrimitive.CheckboxItem
|
||||
data-slot="dropdown-menu-checkbox-item"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span
|
||||
className="pointer-events-none absolute right-2 flex items-center justify-center"
|
||||
data-slot="dropdown-menu-checkbox-item-indicator"
|
||||
>
|
||||
<MenuPrimitive.CheckboxItemIndicator>
|
||||
<CheckIcon
|
||||
/>
|
||||
</MenuPrimitive.CheckboxItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</MenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioGroup({ ...props }: MenuPrimitive.RadioGroup.Props) {
|
||||
return (
|
||||
<MenuPrimitive.RadioGroup
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
inset,
|
||||
...props
|
||||
}: MenuPrimitive.RadioItem.Props & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<MenuPrimitive.RadioItem
|
||||
data-slot="dropdown-menu-radio-item"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span
|
||||
className="pointer-events-none absolute right-2 flex items-center justify-center"
|
||||
data-slot="dropdown-menu-radio-item-indicator"
|
||||
>
|
||||
<MenuPrimitive.RadioItemIndicator>
|
||||
<CheckIcon
|
||||
/>
|
||||
</MenuPrimitive.RadioItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</MenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: MenuPrimitive.Separator.Props) {
|
||||
return (
|
||||
<MenuPrimitive.Separator
|
||||
data-slot="dropdown-menu-separator"
|
||||
className={cn("-mx-1 my-1 h-px bg-border", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="dropdown-menu-shortcut"
|
||||
className={cn(
|
||||
"ml-auto text-xs tracking-widest text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
DropdownMenu,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSubContent,
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
|
||||
function Empty({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="empty"
|
||||
className={cn(
|
||||
"flex w-full min-w-0 flex-1 flex-col items-center justify-center gap-4 rounded-xl border-dashed p-6 text-center text-balance",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="empty-header"
|
||||
className={cn("flex max-w-sm flex-col items-center gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const emptyMediaVariants = cva(
|
||||
"mb-2 flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-transparent",
|
||||
icon: "flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground [&_svg:not([class*='size-'])]:size-4",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function EmptyMedia({
|
||||
className,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & VariantProps<typeof emptyMediaVariants>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="empty-icon"
|
||||
data-variant={variant}
|
||||
className={cn(emptyMediaVariants({ variant, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="empty-title"
|
||||
className={cn(
|
||||
"text-sm font-medium tracking-tight",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="empty-description"
|
||||
className={cn(
|
||||
"text-sm/relaxed text-muted-foreground [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="empty-content"
|
||||
className={cn(
|
||||
"flex w-full max-w-sm min-w-0 flex-col items-center gap-2.5 text-sm text-balance",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Empty,
|
||||
EmptyHeader,
|
||||
EmptyTitle,
|
||||
EmptyDescription,
|
||||
EmptyContent,
|
||||
EmptyMedia,
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
import { useMemo } from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
import { Label } from "@authportal/ui/components/label"
|
||||
import { Separator } from "@authportal/ui/components/separator"
|
||||
|
||||
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
|
||||
return (
|
||||
<fieldset
|
||||
data-slot="field-set"
|
||||
className={cn(
|
||||
"flex flex-col gap-4 has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FieldLegend({
|
||||
className,
|
||||
variant = "legend",
|
||||
...props
|
||||
}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
|
||||
return (
|
||||
<legend
|
||||
data-slot="field-legend"
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"mb-1.5 font-medium data-[variant=label]:text-sm data-[variant=legend]:text-base",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="field-group"
|
||||
className={cn(
|
||||
"group/field-group @container/field-group flex w-full flex-col gap-5 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const fieldVariants = cva(
|
||||
"group/field flex w-full gap-2 data-[invalid=true]:text-destructive",
|
||||
{
|
||||
variants: {
|
||||
orientation: {
|
||||
vertical: "flex-col *:w-full [&>.sr-only]:w-auto",
|
||||
horizontal:
|
||||
"flex-row items-center has-[>[data-slot=field-content]]:items-start *:data-[slot=field-label]:flex-auto has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
|
||||
responsive:
|
||||
"flex-col *:w-full @md/field-group:flex-row @md/field-group:items-center @md/field-group:*:w-auto @md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:*:data-[slot=field-label]:flex-auto [&>.sr-only]:w-auto @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
orientation: "vertical",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Field({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
data-slot="field"
|
||||
data-orientation={orientation}
|
||||
className={cn(fieldVariants({ orientation }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="field-content"
|
||||
className={cn(
|
||||
"group/field-content flex flex-1 flex-col gap-0.5 leading-snug",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FieldLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Label>) {
|
||||
return (
|
||||
<Label
|
||||
data-slot="field-label"
|
||||
className={cn(
|
||||
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50 has-data-checked:border-primary/30 has-data-checked:bg-primary/5 has-[>[data-slot=field]]:rounded-lg has-[>[data-slot=field]]:border *:data-[slot=field]:p-2.5 dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10",
|
||||
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="field-label"
|
||||
className={cn(
|
||||
"flex w-fit items-center gap-2 text-sm font-medium group-data-[disabled=true]/field:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||
return (
|
||||
<p
|
||||
data-slot="field-description"
|
||||
className={cn(
|
||||
"text-left text-sm leading-normal font-normal text-muted-foreground group-has-data-horizontal/field:text-balance [[data-variant=legend]+&]:-mt-1.5",
|
||||
"last:mt-0 nth-last-2:-mt-1",
|
||||
"[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FieldSeparator({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
children?: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
data-slot="field-separator"
|
||||
data-content={!!children}
|
||||
className={cn(
|
||||
"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<Separator className="absolute inset-0 top-1/2" />
|
||||
{children && (
|
||||
<span
|
||||
className="relative mx-auto block w-fit bg-background px-2 text-muted-foreground"
|
||||
data-slot="field-separator-content"
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function FieldError({
|
||||
className,
|
||||
children,
|
||||
errors,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
errors?: Array<{ message?: string } | undefined>
|
||||
}) {
|
||||
const content = useMemo(() => {
|
||||
if (children) {
|
||||
return children
|
||||
}
|
||||
|
||||
if (!errors?.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
const uniqueErrors = [
|
||||
...new Map(errors.map((error) => [error?.message, error])).values(),
|
||||
]
|
||||
|
||||
if (uniqueErrors?.length == 1) {
|
||||
return uniqueErrors[0]?.message
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className="ml-4 flex list-disc flex-col gap-1">
|
||||
{uniqueErrors.map(
|
||||
(error, index) =>
|
||||
error?.message && <li key={index}>{error.message}</li>
|
||||
)}
|
||||
</ul>
|
||||
)
|
||||
}, [children, errors])
|
||||
|
||||
if (!content) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
data-slot="field-error"
|
||||
className={cn("text-sm font-normal text-destructive", className)}
|
||||
{...props}
|
||||
>
|
||||
{content}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Field,
|
||||
FieldLabel,
|
||||
FieldDescription,
|
||||
FieldError,
|
||||
FieldGroup,
|
||||
FieldLegend,
|
||||
FieldSeparator,
|
||||
FieldSet,
|
||||
FieldContent,
|
||||
FieldTitle,
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
import { Button } from "@authportal/ui/components/button"
|
||||
import { Input } from "@authportal/ui/components/input"
|
||||
import { Textarea } from "@authportal/ui/components/textarea"
|
||||
|
||||
function InputGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="input-group"
|
||||
role="group"
|
||||
className={cn(
|
||||
"group/input-group relative flex h-8 w-full min-w-0 items-center rounded-lg border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const inputGroupAddonVariants = cva(
|
||||
"flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
align: {
|
||||
"inline-start":
|
||||
"order-first pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem]",
|
||||
"inline-end":
|
||||
"order-last pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem]",
|
||||
"block-start":
|
||||
"order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-2 [.border-b]:pb-2",
|
||||
"block-end":
|
||||
"order-last w-full justify-start px-2.5 pb-2 group-has-[>input]/input-group:pb-2 [.border-t]:pt-2",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
align: "inline-start",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function InputGroupAddon({
|
||||
className,
|
||||
align = "inline-start",
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & VariantProps<typeof inputGroupAddonVariants>) {
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
data-slot="input-group-addon"
|
||||
data-align={align}
|
||||
className={cn(inputGroupAddonVariants({ align }), className)}
|
||||
onClick={(e) => {
|
||||
if ((e.target as HTMLElement).closest("button")) {
|
||||
return
|
||||
}
|
||||
e.currentTarget.parentElement?.querySelector("input")?.focus()
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const inputGroupButtonVariants = cva(
|
||||
"flex items-center gap-2 text-sm shadow-none",
|
||||
{
|
||||
variants: {
|
||||
size: {
|
||||
xs: "h-6 gap-1 rounded-[calc(var(--radius)-3px)] px-1.5 [&>svg:not([class*='size-'])]:size-3.5",
|
||||
sm: "",
|
||||
"icon-xs":
|
||||
"size-6 rounded-[calc(var(--radius)-3px)] p-0 has-[>svg]:p-0",
|
||||
"icon-sm": "size-8 p-0 has-[>svg]:p-0",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
size: "xs",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function InputGroupButton({
|
||||
className,
|
||||
type = "button",
|
||||
variant = "ghost",
|
||||
size = "xs",
|
||||
...props
|
||||
}: Omit<React.ComponentProps<typeof Button>, "size" | "type"> &
|
||||
VariantProps<typeof inputGroupButtonVariants> & {
|
||||
type?: "button" | "submit" | "reset"
|
||||
}) {
|
||||
return (
|
||||
<Button
|
||||
type={type}
|
||||
data-size={size}
|
||||
variant={variant}
|
||||
className={cn(inputGroupButtonVariants({ size }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function InputGroupText({ className, ...props }: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm text-muted-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function InputGroupInput({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<Input
|
||||
data-slot="input-group-control"
|
||||
className={cn(
|
||||
"flex-1 rounded-none border-0 bg-transparent shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function InputGroupTextarea({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"textarea">) {
|
||||
return (
|
||||
<Textarea
|
||||
data-slot="input-group-control"
|
||||
className={cn(
|
||||
"flex-1 resize-none rounded-none border-0 bg-transparent py-2 shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
InputGroup,
|
||||
InputGroupAddon,
|
||||
InputGroupButton,
|
||||
InputGroupText,
|
||||
InputGroupInput,
|
||||
InputGroupTextarea,
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import * as React from "react"
|
||||
import { Input as InputPrimitive } from "@base-ui/react/input"
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<InputPrimitive
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Input }
|
||||
@@ -0,0 +1,201 @@
|
||||
import * as React from "react"
|
||||
import { mergeProps } from "@base-ui/react/merge-props"
|
||||
import { useRender } from "@base-ui/react/use-render"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
import { Separator } from "@authportal/ui/components/separator"
|
||||
|
||||
function ItemGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
role="list"
|
||||
data-slot="item-group"
|
||||
className={cn(
|
||||
"group/item-group flex w-full flex-col gap-4 has-data-[size=sm]:gap-2.5 has-data-[size=xs]:gap-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ItemSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Separator>) {
|
||||
return (
|
||||
<Separator
|
||||
data-slot="item-separator"
|
||||
orientation="horizontal"
|
||||
className={cn("my-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const itemVariants = cva(
|
||||
"group/item flex w-full flex-wrap items-center rounded-lg border text-sm transition-colors duration-100 outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 [a]:transition-colors [a]:hover:bg-muted",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "border-transparent",
|
||||
outline: "border-border",
|
||||
muted: "border-transparent bg-muted/50",
|
||||
},
|
||||
size: {
|
||||
default: "gap-2.5 px-3 py-2.5",
|
||||
sm: "gap-2.5 px-3 py-2.5",
|
||||
xs: "gap-2 px-2.5 py-2 in-data-[slot=dropdown-menu-content]:p-0",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Item({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
render,
|
||||
...props
|
||||
}: useRender.ComponentProps<"div"> & VariantProps<typeof itemVariants>) {
|
||||
return useRender({
|
||||
defaultTagName: "div",
|
||||
props: mergeProps<"div">(
|
||||
{
|
||||
className: cn(itemVariants({ variant, size, className })),
|
||||
},
|
||||
props
|
||||
),
|
||||
render,
|
||||
state: {
|
||||
slot: "item",
|
||||
variant,
|
||||
size,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const itemMediaVariants = cva(
|
||||
"flex shrink-0 items-center justify-center gap-2 group-has-data-[slot=item-description]/item:translate-y-0.5 group-has-data-[slot=item-description]/item:self-start [&_svg]:pointer-events-none",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-transparent",
|
||||
icon: "[&_svg:not([class*='size-'])]:size-4",
|
||||
image:
|
||||
"size-10 overflow-hidden rounded-sm group-data-[size=sm]/item:size-8 group-data-[size=xs]/item:size-6 [&_img]:size-full [&_img]:object-cover",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function ItemMedia({
|
||||
className,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & VariantProps<typeof itemMediaVariants>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="item-media"
|
||||
data-variant={variant}
|
||||
className={cn(itemMediaVariants({ variant, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ItemContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="item-content"
|
||||
className={cn(
|
||||
"flex flex-1 flex-col gap-1 group-data-[size=xs]/item:gap-0 [&+[data-slot=item-content]]:flex-none",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ItemTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="item-title"
|
||||
className={cn(
|
||||
"line-clamp-1 flex w-fit items-center gap-2 text-sm leading-snug font-medium underline-offset-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ItemDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||
return (
|
||||
<p
|
||||
data-slot="item-description"
|
||||
className={cn(
|
||||
"line-clamp-2 text-left text-sm leading-normal font-normal text-muted-foreground group-data-[size=xs]/item:text-xs [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ItemActions({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="item-actions"
|
||||
className={cn("flex items-center gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ItemHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="item-header"
|
||||
className={cn(
|
||||
"flex basis-full items-center justify-between gap-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ItemFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="item-footer"
|
||||
className={cn(
|
||||
"flex basis-full items-center justify-between gap-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Item,
|
||||
ItemMedia,
|
||||
ItemContent,
|
||||
ItemActions,
|
||||
ItemGroup,
|
||||
ItemSeparator,
|
||||
ItemTitle,
|
||||
ItemDescription,
|
||||
ItemHeader,
|
||||
ItemFooter,
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
|
||||
function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {
|
||||
return (
|
||||
<kbd
|
||||
data-slot="kbd"
|
||||
className={cn(
|
||||
"pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm bg-muted px-1 font-sans text-xs font-medium text-muted-foreground select-none in-data-[slot=tooltip-content]:bg-background/20 in-data-[slot=tooltip-content]:text-background dark:in-data-[slot=tooltip-content]:bg-background/10 [&_svg:not([class*='size-'])]:size-3",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function KbdGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<kbd
|
||||
data-slot="kbd-group"
|
||||
className={cn("inline-flex items-center gap-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Kbd, KbdGroup }
|
||||
@@ -0,0 +1,18 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
|
||||
function Label({ className, ...props }: React.ComponentProps<"label">) {
|
||||
return (
|
||||
<label
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Label }
|
||||
@@ -0,0 +1,87 @@
|
||||
import * as React from "react"
|
||||
import { Popover as PopoverPrimitive } from "@base-ui/react/popover"
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
|
||||
function Popover({ ...props }: PopoverPrimitive.Root.Props) {
|
||||
return <PopoverPrimitive.Root data-slot="popover" {...props} />
|
||||
}
|
||||
|
||||
function PopoverTrigger({ ...props }: PopoverPrimitive.Trigger.Props) {
|
||||
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
|
||||
}
|
||||
|
||||
function PopoverContent({
|
||||
className,
|
||||
align = "center",
|
||||
alignOffset = 0,
|
||||
side = "bottom",
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: PopoverPrimitive.Popup.Props &
|
||||
Pick<
|
||||
PopoverPrimitive.Positioner.Props,
|
||||
"align" | "alignOffset" | "side" | "sideOffset"
|
||||
>) {
|
||||
return (
|
||||
<PopoverPrimitive.Portal>
|
||||
<PopoverPrimitive.Positioner
|
||||
align={align}
|
||||
alignOffset={alignOffset}
|
||||
side={side}
|
||||
sideOffset={sideOffset}
|
||||
className="isolate z-50"
|
||||
>
|
||||
<PopoverPrimitive.Popup
|
||||
data-slot="popover-content"
|
||||
className={cn(
|
||||
"z-50 flex w-72 origin-(--transform-origin) flex-col gap-2.5 rounded-lg bg-popover p-2.5 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPrimitive.Positioner>
|
||||
</PopoverPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function PopoverHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="popover-header"
|
||||
className={cn("flex flex-col gap-0.5 text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function PopoverTitle({ className, ...props }: PopoverPrimitive.Title.Props) {
|
||||
return (
|
||||
<PopoverPrimitive.Title
|
||||
data-slot="popover-title"
|
||||
className={cn("font-medium", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function PopoverDescription({
|
||||
className,
|
||||
...props
|
||||
}: PopoverPrimitive.Description.Props) {
|
||||
return (
|
||||
<PopoverPrimitive.Description
|
||||
data-slot="popover-description"
|
||||
className={cn("text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverDescription,
|
||||
PopoverHeader,
|
||||
PopoverTitle,
|
||||
PopoverTrigger,
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import * as React from "react"
|
||||
import { ScrollArea as ScrollAreaPrimitive } from "@base-ui/react/scroll-area"
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
|
||||
function ScrollArea({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: ScrollAreaPrimitive.Root.Props) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
data-slot="scroll-area"
|
||||
className={cn("relative", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport
|
||||
data-slot="scroll-area-viewport"
|
||||
className="size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1"
|
||||
>
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
function ScrollBar({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: ScrollAreaPrimitive.Scrollbar.Props) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Scrollbar
|
||||
data-slot="scroll-area-scrollbar"
|
||||
data-orientation={orientation}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none p-px transition-colors select-none data-horizontal:h-2.5 data-horizontal:flex-col data-horizontal:border-t data-horizontal:border-t-transparent data-vertical:h-full data-vertical:w-2.5 data-vertical:border-l data-vertical:border-l-transparent",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Thumb
|
||||
data-slot="scroll-area-thumb"
|
||||
className="relative flex-1 rounded-full bg-border"
|
||||
/>
|
||||
</ScrollAreaPrimitive.Scrollbar>
|
||||
)
|
||||
}
|
||||
|
||||
export { ScrollArea, ScrollBar }
|
||||
@@ -0,0 +1,198 @@
|
||||
import * as React from "react"
|
||||
import { Select as SelectPrimitive } from "@base-ui/react/select"
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from "lucide-react"
|
||||
|
||||
const Select = SelectPrimitive.Root
|
||||
|
||||
function SelectGroup({ className, ...props }: SelectPrimitive.Group.Props) {
|
||||
return (
|
||||
<SelectPrimitive.Group
|
||||
data-slot="select-group"
|
||||
className={cn("scroll-my-1 p-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectValue({ className, ...props }: SelectPrimitive.Value.Props) {
|
||||
return (
|
||||
<SelectPrimitive.Value
|
||||
data-slot="select-value"
|
||||
className={cn("flex flex-1 text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectTrigger({
|
||||
className,
|
||||
size = "default",
|
||||
children,
|
||||
...props
|
||||
}: SelectPrimitive.Trigger.Props & {
|
||||
size?: "sm" | "default"
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
data-slot="select-trigger"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"flex w-fit items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon
|
||||
render={
|
||||
<ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />
|
||||
}
|
||||
/>
|
||||
</SelectPrimitive.Trigger>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectContent({
|
||||
className,
|
||||
children,
|
||||
side = "bottom",
|
||||
sideOffset = 4,
|
||||
align = "center",
|
||||
alignOffset = 0,
|
||||
alignItemWithTrigger = true,
|
||||
...props
|
||||
}: SelectPrimitive.Popup.Props &
|
||||
Pick<
|
||||
SelectPrimitive.Positioner.Props,
|
||||
"align" | "alignOffset" | "side" | "sideOffset" | "alignItemWithTrigger"
|
||||
>) {
|
||||
return (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Positioner
|
||||
side={side}
|
||||
sideOffset={sideOffset}
|
||||
align={align}
|
||||
alignOffset={alignOffset}
|
||||
alignItemWithTrigger={alignItemWithTrigger}
|
||||
className="isolate z-50"
|
||||
>
|
||||
<SelectPrimitive.Popup
|
||||
data-slot="select-content"
|
||||
data-align-trigger={alignItemWithTrigger}
|
||||
className={cn("relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.List>{children}</SelectPrimitive.List>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Popup>
|
||||
</SelectPrimitive.Positioner>
|
||||
</SelectPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectLabel({
|
||||
className,
|
||||
...props
|
||||
}: SelectPrimitive.GroupLabel.Props) {
|
||||
return (
|
||||
<SelectPrimitive.GroupLabel
|
||||
data-slot="select-label"
|
||||
className={cn("px-1.5 py-1 text-xs text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: SelectPrimitive.Item.Props) {
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
data-slot="select-item"
|
||||
className={cn(
|
||||
"relative flex w-full cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SelectPrimitive.ItemText className="flex flex-1 shrink-0 gap-2 whitespace-nowrap">
|
||||
{children}
|
||||
</SelectPrimitive.ItemText>
|
||||
<SelectPrimitive.ItemIndicator
|
||||
render={
|
||||
<span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center" />
|
||||
}
|
||||
>
|
||||
<CheckIcon className="pointer-events-none" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</SelectPrimitive.Item>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectSeparator({
|
||||
className,
|
||||
...props
|
||||
}: SelectPrimitive.Separator.Props) {
|
||||
return (
|
||||
<SelectPrimitive.Separator
|
||||
data-slot="select-separator"
|
||||
className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectScrollUpButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpArrow>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollUpArrow
|
||||
data-slot="select-scroll-up-button"
|
||||
className={cn(
|
||||
"top-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon
|
||||
/>
|
||||
</SelectPrimitive.ScrollUpArrow>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectScrollDownButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownArrow>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollDownArrow
|
||||
data-slot="select-scroll-down-button"
|
||||
className={cn(
|
||||
"bottom-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon
|
||||
/>
|
||||
</SelectPrimitive.ScrollDownArrow>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectScrollDownButton,
|
||||
SelectScrollUpButton,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
"use client"
|
||||
|
||||
import { Separator as SeparatorPrimitive } from "@base-ui/react/separator"
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
...props
|
||||
}: SeparatorPrimitive.Props) {
|
||||
return (
|
||||
<SeparatorPrimitive
|
||||
data-slot="separator"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Separator }
|
||||
@@ -0,0 +1,135 @@
|
||||
import * as React from "react"
|
||||
import { Dialog as SheetPrimitive } from "@base-ui/react/dialog"
|
||||
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
import { Button } from "@authportal/ui/components/button"
|
||||
import { XIcon } from "lucide-react"
|
||||
|
||||
function Sheet({ ...props }: SheetPrimitive.Root.Props) {
|
||||
return <SheetPrimitive.Root data-slot="sheet" {...props} />
|
||||
}
|
||||
|
||||
function SheetTrigger({ ...props }: SheetPrimitive.Trigger.Props) {
|
||||
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
|
||||
}
|
||||
|
||||
function SheetClose({ ...props }: SheetPrimitive.Close.Props) {
|
||||
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
|
||||
}
|
||||
|
||||
function SheetPortal({ ...props }: SheetPrimitive.Portal.Props) {
|
||||
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
|
||||
}
|
||||
|
||||
function SheetOverlay({ className, ...props }: SheetPrimitive.Backdrop.Props) {
|
||||
return (
|
||||
<SheetPrimitive.Backdrop
|
||||
data-slot="sheet-overlay"
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/10 transition-opacity duration-150 data-ending-style:opacity-0 data-starting-style:opacity-0 supports-backdrop-filter:backdrop-blur-xs",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetContent({
|
||||
className,
|
||||
children,
|
||||
side = "right",
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: SheetPrimitive.Popup.Props & {
|
||||
side?: "top" | "right" | "bottom" | "left"
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<SheetPrimitive.Popup
|
||||
data-slot="sheet-content"
|
||||
data-side={side}
|
||||
className={cn(
|
||||
"fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-ending-style:opacity-0 data-starting-style:opacity-0 data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=bottom]:data-ending-style:translate-y-[2.5rem] data-[side=bottom]:data-starting-style:translate-y-[2.5rem] data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=left]:data-ending-style:translate-x-[-2.5rem] data-[side=left]:data-starting-style:translate-x-[-2.5rem] data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=right]:data-ending-style:translate-x-[2.5rem] data-[side=right]:data-starting-style:translate-x-[2.5rem] data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=top]:data-ending-style:translate-y-[-2.5rem] data-[side=top]:data-starting-style:translate-y-[-2.5rem] data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<SheetPrimitive.Close
|
||||
data-slot="sheet-close"
|
||||
render={
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="absolute top-3 right-3"
|
||||
size="icon-sm"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<XIcon aria-hidden="true" />
|
||||
<span className="sr-only">Закрыть</span>
|
||||
</SheetPrimitive.Close>
|
||||
)}
|
||||
</SheetPrimitive.Popup>
|
||||
</SheetPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-header"
|
||||
className={cn("flex flex-col gap-0.5 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-footer"
|
||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetTitle({ className, ...props }: SheetPrimitive.Title.Props) {
|
||||
return (
|
||||
<SheetPrimitive.Title
|
||||
data-slot="sheet-title"
|
||||
className={cn(
|
||||
"text-base font-medium text-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetDescription({
|
||||
className,
|
||||
...props
|
||||
}: SheetPrimitive.Description.Props) {
|
||||
return (
|
||||
<SheetPrimitive.Description
|
||||
data-slot="sheet-description"
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
SheetTrigger,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetFooter,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
}
|
||||
@@ -0,0 +1,726 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { mergeProps } from "@base-ui/react/merge-props"
|
||||
import { useRender } from "@base-ui/react/use-render"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { useIsMobile } from "@authportal/ui/hooks/use-mobile"
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
import { Button } from "@authportal/ui/components/button"
|
||||
import { Input } from "@authportal/ui/components/input"
|
||||
import { Separator } from "@authportal/ui/components/separator"
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@authportal/ui/components/sheet"
|
||||
import { Skeleton } from "@authportal/ui/components/skeleton"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@authportal/ui/components/tooltip"
|
||||
import { PanelLeftIcon } from "lucide-react"
|
||||
|
||||
const SIDEBAR_COOKIE_NAME = "sidebar_state"
|
||||
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
|
||||
const SIDEBAR_WIDTH = "240px"
|
||||
const SIDEBAR_WIDTH_MOBILE = "18rem"
|
||||
const SIDEBAR_WIDTH_ICON = "3rem"
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
|
||||
|
||||
type SidebarContextProps = {
|
||||
state: "expanded" | "collapsed"
|
||||
open: boolean
|
||||
setOpen: (open: boolean) => void
|
||||
openMobile: boolean
|
||||
setOpenMobile: (open: boolean) => void
|
||||
isMobile: boolean
|
||||
toggleSidebar: () => void
|
||||
}
|
||||
|
||||
const SidebarContext = React.createContext<SidebarContextProps | null>(null)
|
||||
|
||||
function useSidebar() {
|
||||
const context = React.useContext(SidebarContext)
|
||||
if (!context) {
|
||||
throw new Error("useSidebar must be used within a SidebarProvider.")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function SidebarProvider({
|
||||
defaultOpen = true,
|
||||
open: openProp,
|
||||
onOpenChange: setOpenProp,
|
||||
className,
|
||||
style,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
defaultOpen?: boolean
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
}) {
|
||||
const isMobile = useIsMobile()
|
||||
const [openMobile, setOpenMobile] = React.useState(false)
|
||||
|
||||
// This is the internal state of the sidebar.
|
||||
// We use openProp and setOpenProp for control from outside the component.
|
||||
const [_open, _setOpen] = React.useState(defaultOpen)
|
||||
const open = openProp ?? _open
|
||||
const setOpen = React.useCallback(
|
||||
(value: boolean | ((value: boolean) => boolean)) => {
|
||||
const openState = typeof value === "function" ? value(open) : value
|
||||
if (setOpenProp) {
|
||||
setOpenProp(openState)
|
||||
} else {
|
||||
_setOpen(openState)
|
||||
}
|
||||
|
||||
// This sets the cookie to keep the sidebar state.
|
||||
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
|
||||
},
|
||||
[setOpenProp, open]
|
||||
)
|
||||
|
||||
// Helper to toggle the sidebar.
|
||||
const toggleSidebar = React.useCallback(() => {
|
||||
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)
|
||||
}, [isMobile, setOpen, setOpenMobile])
|
||||
|
||||
// Adds a keyboard shortcut to toggle the sidebar.
|
||||
React.useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (
|
||||
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
|
||||
(event.metaKey || event.ctrlKey)
|
||||
) {
|
||||
event.preventDefault()
|
||||
toggleSidebar()
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown)
|
||||
return () => window.removeEventListener("keydown", handleKeyDown)
|
||||
}, [toggleSidebar])
|
||||
|
||||
// We add a state so that we can do data-state="expanded" or "collapsed".
|
||||
// This makes it easier to style the sidebar with Tailwind classes.
|
||||
const state = open ? "expanded" : "collapsed"
|
||||
|
||||
const contextValue = React.useMemo<SidebarContextProps>(
|
||||
() => ({
|
||||
state,
|
||||
open,
|
||||
setOpen,
|
||||
isMobile,
|
||||
openMobile,
|
||||
setOpenMobile,
|
||||
toggleSidebar,
|
||||
}),
|
||||
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
|
||||
)
|
||||
|
||||
return (
|
||||
<SidebarContext.Provider value={contextValue}>
|
||||
<div
|
||||
data-slot="sidebar-wrapper"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH,
|
||||
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
|
||||
...style,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
className={cn(
|
||||
"group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</SidebarContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function Sidebar({
|
||||
side = "left",
|
||||
variant = "sidebar",
|
||||
collapsible = "offcanvas",
|
||||
className,
|
||||
children,
|
||||
dir,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
side?: "left" | "right"
|
||||
variant?: "sidebar" | "floating" | "inset"
|
||||
collapsible?: "offcanvas" | "icon" | "none"
|
||||
}) {
|
||||
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
|
||||
|
||||
if (collapsible === "none") {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar"
|
||||
className={cn(
|
||||
"flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
|
||||
<SheetContent
|
||||
dir={dir}
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar"
|
||||
data-mobile="true"
|
||||
className="w-(--sidebar-width) bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
side={side}
|
||||
>
|
||||
<SheetHeader className="sr-only">
|
||||
<SheetTitle>Боковое меню</SheetTitle>
|
||||
<SheetDescription>Навигация по приложению</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="flex h-full w-full flex-col">{children}</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="group peer hidden text-sidebar-foreground md:block"
|
||||
data-state={state}
|
||||
data-collapsible={state === "collapsed" ? collapsible : ""}
|
||||
data-variant={variant}
|
||||
data-side={side}
|
||||
data-slot="sidebar"
|
||||
>
|
||||
{/* This is what handles the sidebar gap on desktop */}
|
||||
<div
|
||||
data-slot="sidebar-gap"
|
||||
className={cn(
|
||||
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
|
||||
"group-data-[collapsible=offcanvas]:w-0",
|
||||
"group-data-[side=right]:rotate-180",
|
||||
variant === "floating" || variant === "inset"
|
||||
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
data-slot="sidebar-container"
|
||||
data-side={side}
|
||||
className={cn(
|
||||
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear data-[side=left]:left-0 data-[side=left]:group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)] data-[side=right]:right-0 data-[side=right]:group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)] md:flex",
|
||||
// Adjust the padding for floating and inset variants.
|
||||
variant === "floating" || variant === "inset"
|
||||
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar-inner"
|
||||
className="flex size-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:shadow-sm group-data-[variant=floating]:ring-1 group-data-[variant=floating]:ring-sidebar-border"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarTrigger({
|
||||
className,
|
||||
onClick,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { toggleSidebar, open, openMobile, isMobile } = useSidebar()
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-sidebar="trigger"
|
||||
data-slot="sidebar-trigger"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
type="button"
|
||||
aria-label="Боковое меню"
|
||||
aria-expanded={isMobile ? openMobile : open}
|
||||
className={cn(className)}
|
||||
onClick={(event) => {
|
||||
onClick?.(event)
|
||||
toggleSidebar()
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<PanelLeftIcon aria-hidden="true" />
|
||||
<span className="sr-only">Боковое меню</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<button
|
||||
data-sidebar="rail"
|
||||
data-slot="sidebar-rail"
|
||||
aria-label="Боковое меню"
|
||||
tabIndex={-1}
|
||||
onClick={toggleSidebar}
|
||||
title="Боковое меню"
|
||||
className={cn(
|
||||
"absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:start-1/2 after:w-[2px] hover:after:bg-sidebar-border sm:flex ltr:-translate-x-1/2 rtl:-translate-x-1/2",
|
||||
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
|
||||
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
|
||||
"group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full hover:group-data-[collapsible=offcanvas]:bg-sidebar",
|
||||
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
|
||||
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
|
||||
return (
|
||||
<main
|
||||
data-slot="sidebar-inset"
|
||||
className={cn(
|
||||
"relative flex w-full flex-1 flex-col bg-background md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarInput({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Input>) {
|
||||
return (
|
||||
<Input
|
||||
data-slot="sidebar-input"
|
||||
data-sidebar="input"
|
||||
className={cn("h-8 w-full bg-background shadow-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-header"
|
||||
data-sidebar="header"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-footer"
|
||||
data-sidebar="footer"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Separator>) {
|
||||
return (
|
||||
<Separator
|
||||
data-slot="sidebar-separator"
|
||||
data-sidebar="separator"
|
||||
className={cn("mx-2 w-auto bg-sidebar-border", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-content"
|
||||
data-sidebar="content"
|
||||
className={cn(
|
||||
"no-scrollbar flex min-h-0 flex-1 flex-col gap-0 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-group"
|
||||
data-sidebar="group"
|
||||
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupLabel({
|
||||
className,
|
||||
render,
|
||||
...props
|
||||
}: useRender.ComponentProps<"div"> & React.ComponentProps<"div">) {
|
||||
return useRender({
|
||||
defaultTagName: "div",
|
||||
props: mergeProps<"div">(
|
||||
{
|
||||
className: cn(
|
||||
"flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 ring-sidebar-ring outline-hidden transition-[margin,opacity] duration-200 ease-linear group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0 focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
className
|
||||
),
|
||||
},
|
||||
props
|
||||
),
|
||||
render,
|
||||
state: {
|
||||
slot: "sidebar-group-label",
|
||||
sidebar: "group-label",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function SidebarGroupAction({
|
||||
className,
|
||||
render,
|
||||
...props
|
||||
}: useRender.ComponentProps<"button"> & React.ComponentProps<"button">) {
|
||||
return useRender({
|
||||
defaultTagName: "button",
|
||||
props: mergeProps<"button">(
|
||||
{
|
||||
className: cn(
|
||||
"absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground ring-sidebar-ring outline-hidden transition-transform group-data-[collapsible=icon]:hidden after:absolute after:-inset-2 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 md:after:hidden [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
className
|
||||
),
|
||||
},
|
||||
props
|
||||
),
|
||||
render,
|
||||
state: {
|
||||
slot: "sidebar-group-action",
|
||||
sidebar: "group-action",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function SidebarGroupContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-group-content"
|
||||
data-sidebar="group-content"
|
||||
className={cn("w-full text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="sidebar-menu"
|
||||
data-sidebar="menu"
|
||||
className={cn("flex w-full min-w-0 flex-col gap-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="sidebar-menu-item"
|
||||
data-sidebar="menu-item"
|
||||
className={cn("group/menu-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button group/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm ring-sidebar-ring outline-hidden transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-open:hover:bg-sidebar-accent data-open:hover:text-sidebar-accent-foreground data-active:bg-sidebar-accent data-active:font-medium data-active:text-sidebar-accent-foreground [&_svg]:size-4 [&_svg]:shrink-0 [&>span:last-child]:truncate",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
|
||||
outline:
|
||||
"bg-background shadow-[0_0_0_1px_var(--sidebar-border)] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_var(--sidebar-accent)]",
|
||||
},
|
||||
size: {
|
||||
default: "h-8 text-sm",
|
||||
sm: "h-7 text-xs",
|
||||
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function SidebarMenuButton({
|
||||
render,
|
||||
isActive = false,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
tooltip,
|
||||
className,
|
||||
...props
|
||||
}: useRender.ComponentProps<"button"> &
|
||||
React.ComponentProps<"button"> & {
|
||||
isActive?: boolean
|
||||
tooltip?: string | React.ComponentProps<typeof TooltipContent>
|
||||
} & VariantProps<typeof sidebarMenuButtonVariants>) {
|
||||
const { isMobile, state } = useSidebar()
|
||||
const comp = useRender({
|
||||
defaultTagName: "button",
|
||||
props: mergeProps<"button">(
|
||||
{
|
||||
className: cn(sidebarMenuButtonVariants({ variant, size }), className),
|
||||
},
|
||||
props
|
||||
),
|
||||
render: !tooltip ? render : <TooltipTrigger render={render} />,
|
||||
state: {
|
||||
slot: "sidebar-menu-button",
|
||||
sidebar: "menu-button",
|
||||
size,
|
||||
active: isActive,
|
||||
},
|
||||
})
|
||||
|
||||
if (!tooltip) {
|
||||
return comp
|
||||
}
|
||||
|
||||
if (typeof tooltip === "string") {
|
||||
tooltip = {
|
||||
children: tooltip,
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
{comp}
|
||||
<TooltipContent
|
||||
side="right"
|
||||
align="center"
|
||||
hidden={state !== "collapsed" || isMobile}
|
||||
{...tooltip}
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuAction({
|
||||
className,
|
||||
render,
|
||||
showOnHover = false,
|
||||
...props
|
||||
}: useRender.ComponentProps<"button"> &
|
||||
React.ComponentProps<"button"> & {
|
||||
showOnHover?: boolean
|
||||
}) {
|
||||
return useRender({
|
||||
defaultTagName: "button",
|
||||
props: mergeProps<"button">(
|
||||
{
|
||||
className: cn(
|
||||
"absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground ring-sidebar-ring outline-hidden transition-transform group-data-[collapsible=icon]:hidden peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1 after:absolute after:-inset-2 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 md:after:hidden [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
showOnHover &&
|
||||
"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 peer-data-active/menu-button:text-sidebar-accent-foreground aria-expanded:opacity-100 md:opacity-0",
|
||||
className
|
||||
),
|
||||
},
|
||||
props
|
||||
),
|
||||
render,
|
||||
state: {
|
||||
slot: "sidebar-menu-action",
|
||||
sidebar: "menu-action",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function SidebarMenuBadge({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-menu-badge"
|
||||
data-sidebar="menu-badge"
|
||||
className={cn(
|
||||
"pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium text-sidebar-foreground tabular-nums select-none group-data-[collapsible=icon]:hidden peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1 peer-data-active/menu-button:text-sidebar-accent-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSkeleton({
|
||||
className,
|
||||
showIcon = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showIcon?: boolean
|
||||
}) {
|
||||
// Random width between 50 to 90%.
|
||||
const [width] = React.useState(() => {
|
||||
return `${Math.floor(Math.random() * 40) + 50}%`
|
||||
})
|
||||
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-menu-skeleton"
|
||||
data-sidebar="menu-skeleton"
|
||||
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
|
||||
{...props}
|
||||
>
|
||||
{showIcon && (
|
||||
<Skeleton
|
||||
className="size-4 rounded-md"
|
||||
data-sidebar="menu-skeleton-icon"
|
||||
/>
|
||||
)}
|
||||
<Skeleton
|
||||
className="h-4 max-w-(--skeleton-width) flex-1"
|
||||
data-sidebar="menu-skeleton-text"
|
||||
style={
|
||||
{
|
||||
"--skeleton-width": width,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="sidebar-menu-sub"
|
||||
data-sidebar="menu-sub"
|
||||
className={cn(
|
||||
"mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5 group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSubItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="sidebar-menu-sub-item"
|
||||
data-sidebar="menu-sub-item"
|
||||
className={cn("group/menu-sub-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSubButton({
|
||||
render,
|
||||
size = "md",
|
||||
isActive = false,
|
||||
className,
|
||||
...props
|
||||
}: useRender.ComponentProps<"a"> &
|
||||
React.ComponentProps<"a"> & {
|
||||
size?: "sm" | "md"
|
||||
isActive?: boolean
|
||||
}) {
|
||||
return useRender({
|
||||
defaultTagName: "a",
|
||||
props: mergeProps<"a">(
|
||||
{
|
||||
className: cn(
|
||||
"flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground ring-sidebar-ring outline-hidden group-data-[collapsible=icon]:hidden hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[size=md]:text-sm data-[size=sm]:text-xs data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
|
||||
className
|
||||
),
|
||||
},
|
||||
props
|
||||
),
|
||||
render,
|
||||
state: {
|
||||
slot: "sidebar-menu-sub-button",
|
||||
sidebar: "menu-sub-button",
|
||||
size,
|
||||
active: isActive,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarGroupAction,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarHeader,
|
||||
SidebarInput,
|
||||
SidebarInset,
|
||||
SidebarMenu,
|
||||
SidebarMenuAction,
|
||||
SidebarMenuBadge,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuSkeleton,
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
SidebarProvider,
|
||||
SidebarRail,
|
||||
SidebarSeparator,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
|
||||
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="skeleton"
|
||||
className={cn("animate-pulse rounded-md bg-muted", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Skeleton }
|
||||
@@ -0,0 +1,10 @@
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
import { Loader2Icon } from "lucide-react"
|
||||
|
||||
function Spinner({ className, ...props }: React.ComponentProps<"svg">) {
|
||||
return (
|
||||
<Loader2Icon data-slot="spinner" role="status" aria-label="Loading" className={cn("size-4 animate-spin", className)} {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
export { Spinner }
|
||||
@@ -0,0 +1,32 @@
|
||||
"use client"
|
||||
|
||||
import { Switch as SwitchPrimitive } from "@base-ui/react/switch"
|
||||
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
|
||||
function Switch({
|
||||
className,
|
||||
size = "default",
|
||||
...props
|
||||
}: SwitchPrimitive.Root.Props & {
|
||||
size?: "sm" | "default"
|
||||
}) {
|
||||
return (
|
||||
<SwitchPrimitive.Root
|
||||
data-slot="switch"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SwitchPrimitive.Thumb
|
||||
data-slot="switch-thumb"
|
||||
className="pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"
|
||||
/>
|
||||
</SwitchPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Switch }
|
||||
@@ -0,0 +1,89 @@
|
||||
"use client"
|
||||
|
||||
import { Tabs as TabsPrimitive } from "@base-ui/react/tabs"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
|
||||
function Tabs({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
...props
|
||||
}: TabsPrimitive.Root.Props) {
|
||||
return (
|
||||
<TabsPrimitive.Root
|
||||
data-slot="tabs"
|
||||
data-orientation={orientation}
|
||||
// Tailwind group-data-horizontal/vertical expects these attrs (Base UI only sets data-orientation).
|
||||
{...(orientation === "vertical"
|
||||
? { "data-vertical": "" as const }
|
||||
: { "data-horizontal": "" as const })}
|
||||
className={cn(
|
||||
"group/tabs flex gap-2 data-horizontal:flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const tabsListVariants = cva(
|
||||
"group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-muted group-data-horizontal/tabs:h-8",
|
||||
line: "h-auto gap-1 bg-transparent p-0",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function TabsList({
|
||||
className,
|
||||
variant = "default",
|
||||
...props
|
||||
}: TabsPrimitive.List.Props & VariantProps<typeof tabsListVariants>) {
|
||||
return (
|
||||
<TabsPrimitive.List
|
||||
data-slot="tabs-list"
|
||||
data-variant={variant}
|
||||
className={cn(tabsListVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsTrigger({ className, ...props }: TabsPrimitive.Tab.Props) {
|
||||
return (
|
||||
<TabsPrimitive.Tab
|
||||
data-slot="tabs-trigger"
|
||||
className={cn(
|
||||
"relative inline-flex items-center justify-center gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 aria-disabled:pointer-events-none aria-disabled:opacity-50 dark:text-muted-foreground dark:hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
"group-data-[variant=default]/tabs-list:h-[calc(100%-1px)] group-data-[variant=default]/tabs-list:flex-1 group-data-[variant=default]/tabs-list:data-active:shadow-sm",
|
||||
"group-data-[variant=line]/tabs-list:flex-none group-data-[variant=line]/tabs-list:rounded-none group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:shadow-none group-data-[variant=line]/tabs-list:data-active:bg-transparent group-data-[variant=line]/tabs-list:data-active:shadow-none dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent",
|
||||
"group-data-[variant=default]/tabs-list:data-active:bg-background group-data-[variant=default]/tabs-list:data-active:text-foreground dark:group-data-[variant=default]/tabs-list:data-active:border-input dark:group-data-[variant=default]/tabs-list:data-active:bg-input/30 dark:group-data-[variant=default]/tabs-list:data-active:text-foreground",
|
||||
"data-active:text-foreground",
|
||||
// Line underline: bottom-0 so FramePanel overflow-hidden does not clip
|
||||
"after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-0 group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsContent({ className, ...props }: TabsPrimitive.Panel.Props) {
|
||||
return (
|
||||
<TabsPrimitive.Panel
|
||||
data-slot="tabs-content"
|
||||
className={cn("flex-1 text-sm outline-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants }
|
||||
@@ -0,0 +1,18 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
|
||||
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||
return (
|
||||
<textarea
|
||||
data-slot="textarea"
|
||||
className={cn(
|
||||
"flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Textarea }
|
||||
@@ -0,0 +1,65 @@
|
||||
"use client"
|
||||
|
||||
import { Tooltip as TooltipPrimitive } from "@base-ui/react/tooltip"
|
||||
import { cn } from "@authportal/ui/lib/utils"
|
||||
|
||||
function TooltipProvider({
|
||||
delay = 0,
|
||||
...props
|
||||
}: TooltipPrimitive.Provider.Props) {
|
||||
return (
|
||||
<TooltipPrimitive.Provider
|
||||
data-slot="tooltip-provider"
|
||||
delay={delay}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function Tooltip({ ...props }: TooltipPrimitive.Root.Props) {
|
||||
return <TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
||||
}
|
||||
|
||||
function TooltipTrigger({ ...props }: TooltipPrimitive.Trigger.Props) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
|
||||
}
|
||||
|
||||
function TooltipContent({
|
||||
className,
|
||||
side = "top",
|
||||
sideOffset = 4,
|
||||
align = "center",
|
||||
alignOffset = 0,
|
||||
children,
|
||||
...props
|
||||
}: TooltipPrimitive.Popup.Props &
|
||||
Pick<
|
||||
TooltipPrimitive.Positioner.Props,
|
||||
"align" | "alignOffset" | "side" | "sideOffset"
|
||||
>) {
|
||||
return (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Positioner
|
||||
align={align}
|
||||
alignOffset={alignOffset}
|
||||
side={side}
|
||||
sideOffset={sideOffset}
|
||||
className="isolate z-50"
|
||||
>
|
||||
<TooltipPrimitive.Popup
|
||||
data-slot="tooltip-content"
|
||||
className={cn(
|
||||
"z-50 inline-flex w-fit max-w-xs origin-(--transform-origin) items-center gap-1.5 rounded-md bg-foreground px-3 py-1.5 text-xs text-background has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground data-[side=bottom]:top-1 data-[side=inline-end]:top-1/2! data-[side=inline-end]:-left-1 data-[side=inline-end]:-translate-y-1/2 data-[side=inline-start]:top-1/2! data-[side=inline-start]:-right-1 data-[side=inline-start]:-translate-y-1/2 data-[side=left]:top-1/2! data-[side=left]:-right-1 data-[side=left]:-translate-y-1/2 data-[side=right]:top-1/2! data-[side=right]:-left-1 data-[side=right]:-translate-y-1/2 data-[side=top]:-bottom-2.5" />
|
||||
</TooltipPrimitive.Popup>
|
||||
</TooltipPrimitive.Positioner>
|
||||
</TooltipPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
||||
@@ -0,0 +1,19 @@
|
||||
import * as React from "react"
|
||||
|
||||
const MOBILE_BREAKPOINT = 768
|
||||
|
||||
export function useIsMobile() {
|
||||
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
|
||||
|
||||
React.useEffect(() => {
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
|
||||
const onChange = () => {
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
}
|
||||
mql.addEventListener("change", onChange)
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
return () => mql.removeEventListener("change", onChange)
|
||||
}, [])
|
||||
|
||||
return !!isMobile
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { type ClassValue, clsx } from 'clsx'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
|
||||
@source "../";
|
||||
@source "../../../apps/web/src";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
:root {
|
||||
--radius: 0.625rem;
|
||||
--background: oklch(0.973 0.004 247.858);
|
||||
--foreground: oklch(0.141 0.006 264.0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.141 0.006 264.0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.141 0.006 264.0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.958 0.005 247.858);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.958 0.005 247.858);
|
||||
--muted-foreground: oklch(0.520 0.010 264.0);
|
||||
--accent: oklch(0.942 0.016 264.376);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.904 0.006 264.0);
|
||||
--input: oklch(0.904 0.006 264.0);
|
||||
--ring: oklch(0.488 0.243 264.376);
|
||||
--chart-1: oklch(0.546 0.215 264.376);
|
||||
--chart-2: oklch(0.527 0.154 150.069);
|
||||
--chart-3: oklch(0.625 0.162 41.500);
|
||||
--chart-4: oklch(0.591 0.224 296.400);
|
||||
--chart-5: oklch(0.577 0.245 27.325);
|
||||
--sidebar: oklch(0.152 0.010 264.376);
|
||||
--sidebar-foreground: oklch(0.920 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.240 0.012 264.376);
|
||||
--sidebar-accent-foreground: oklch(0.950 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 8%);
|
||||
--sidebar-ring: oklch(0.488 0.243 264.376);
|
||||
--destructive-foreground: var(--color-red-800);
|
||||
--success: var(--color-emerald-500);
|
||||
--success-foreground: var(--color-emerald-900);
|
||||
--info: var(--color-violet-500);
|
||||
--info-foreground: var(--color-violet-900);
|
||||
--warning: var(--color-yellow-500);
|
||||
--warning-foreground: var(--color-yellow-900);
|
||||
--invert: var(--color-zinc-900);
|
||||
--invert-foreground: var(--color-zinc-50);
|
||||
--focus: var(--color-blue-500);
|
||||
--focus-foreground: var(--color-blue-900);
|
||||
--chart-line-1: oklch(0.527 0.154 150.069);
|
||||
--chart-line-2: oklch(0.546 0.215 264.376);
|
||||
--chart-line-3: oklch(0.625 0.162 41.500);
|
||||
--chart-line-4: oklch(0.591 0.224 296.400);
|
||||
--chart-rx: oklch(0.527 0.154 150.069);
|
||||
--chart-tx: oklch(0.546 0.215 264.376);
|
||||
--status-online: oklch(0.527 0.154 150.069);
|
||||
--status-offline: oklch(0.577 0.245 27.325);
|
||||
--status-degraded: oklch(0.666 0.179 58.318);
|
||||
--status-online-fg: oklch(0.437 0.149 150.069);
|
||||
--status-online-bg: oklch(0.527 0.154 150.069 / 0.10);
|
||||
--status-offline-fg: oklch(0.505 0.213 27.325);
|
||||
--status-offline-bg: oklch(0.577 0.245 27.325 / 0.10);
|
||||
--status-degraded-fg: oklch(0.555 0.163 58.318);
|
||||
--status-degraded-bg: oklch(0.666 0.179 58.318 / 0.10);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.133 0.011 264.376);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.191 0.011 264.376);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.191 0.011 264.376);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.922 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--secondary: oklch(0.252 0.010 264.376);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.252 0.010 264.376);
|
||||
--muted-foreground: oklch(0.648 0.008 264.376);
|
||||
--accent: oklch(0.285 0.022 264.376);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.488 0.243 264.376);
|
||||
--chart-1: oklch(0.637 0.222 264.376);
|
||||
--chart-2: oklch(0.696 0.170 151.328);
|
||||
--chart-3: oklch(0.713 0.176 47.600);
|
||||
--chart-4: oklch(0.714 0.173 303.900);
|
||||
--chart-5: oklch(0.704 0.191 22.216);
|
||||
--sidebar: oklch(0.191 0.011 264.376);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.262 0.014 264.376);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.488 0.243 264.376);
|
||||
--destructive-foreground: var(--color-red-600);
|
||||
--success: var(--color-emerald-500);
|
||||
--success-foreground: var(--color-emerald-600);
|
||||
--info: var(--color-violet-500);
|
||||
--info-foreground: var(--color-violet-600);
|
||||
--warning: var(--color-yellow-500);
|
||||
--warning-foreground: var(--color-yellow-600);
|
||||
--invert: var(--color-zinc-700);
|
||||
--invert-foreground: var(--color-zinc-50);
|
||||
--focus: var(--color-blue-500);
|
||||
--focus-foreground: var(--color-blue-600);
|
||||
--chart-line-1: oklch(0.696 0.170 151.328);
|
||||
--chart-line-2: oklch(0.637 0.222 264.376);
|
||||
--chart-line-3: oklch(0.713 0.176 47.600);
|
||||
--chart-line-4: oklch(0.714 0.173 303.900);
|
||||
--chart-rx: oklch(0.696 0.170 151.328);
|
||||
--chart-tx: oklch(0.637 0.222 264.376);
|
||||
--status-online: oklch(0.527 0.154 150.069);
|
||||
--status-offline: oklch(0.577 0.245 27.325);
|
||||
--status-degraded: oklch(0.666 0.179 58.318);
|
||||
--status-online-fg: oklch(0.696 0.170 151.328);
|
||||
--status-online-bg: oklch(0.527 0.154 150.069 / 0.12);
|
||||
--status-offline-fg: oklch(0.704 0.191 22.216);
|
||||
--status-offline-bg: oklch(0.577 0.245 27.325 / 0.12);
|
||||
--status-degraded-fg: oklch(0.769 0.149 70.080);
|
||||
--status-degraded-bg: oklch(0.666 0.179 58.318 / 0.12);
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--radius-sm: calc(var(--radius) * 0.6);
|
||||
--radius-md: calc(var(--radius) * 0.8);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) * 1.4);
|
||||
--radius-2xl: calc(var(--radius) * 1.8);
|
||||
--radius-3xl: calc(var(--radius) * 2.2);
|
||||
--radius-4xl: calc(var(--radius) * 2.6);
|
||||
--color-invert-foreground: var(--invert-foreground);
|
||||
--color-invert: var(--invert);
|
||||
--color-warning-foreground: var(--warning-foreground);
|
||||
--color-warning: var(--warning);
|
||||
--color-info-foreground: var(--info-foreground);
|
||||
--color-info: var(--info);
|
||||
--color-success-foreground: var(--success-foreground);
|
||||
--color-success: var(--success);
|
||||
--color-destructive-foreground: var(--destructive-foreground);
|
||||
--color-focus: var(--focus);
|
||||
--color-focus-foreground: var(--focus-foreground);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user