mirror of
https://github.com/QuantumNous/new-api.git
synced 2026-12-05 08:03:01 +00:00
feat(security): add access token management and audit logs
Move account security settings into a dedicated page and add token status, rotation, revocation, and access history. Store audit events with role snapshots and JSON metadata, add audit.read authorization and an independent audit page, and upgrade the ClickHouse driver to v2.46.0.
This commit is contained in:
112 files changed
+6872
-953
No files matched your search
@@ -0,0 +1,78 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/model"
|
||||
"github.com/gin-gonic/gin"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func GetAccessTokenStatus(c *gin.Context) {
|
||||
status, err := model.GetUserAccessTokenStatus(c.GetInt("id"))
|
||||
if err != nil {
|
||||
common.ApiError(c, err)
|
||||
return
|
||||
}
|
||||
common.ApiSuccess(c, status)
|
||||
}
|
||||
|
||||
func RevokeAccessToken(c *gin.Context) {
|
||||
ref, err := model.RevokeUserAccessToken(c.GetInt("id"))
|
||||
if err != nil {
|
||||
common.ApiError(c, err)
|
||||
return
|
||||
}
|
||||
if ref != "" {
|
||||
recordUserSecurityAudit(c, c.GetInt("id"), "access_token.revoke", map[string]interface{}{"token_ref": ref})
|
||||
}
|
||||
common.ApiSuccess(c, nil)
|
||||
}
|
||||
|
||||
func GetAuditLogs(c *gin.Context) {
|
||||
page := common.GetPageQuery(c)
|
||||
if page.Page < 1 || page.PageSize < 1 || page.Page > 100000000 {
|
||||
common.ApiErrorMsg(c, "Invalid audit pagination")
|
||||
return
|
||||
}
|
||||
filter := model.AuditLogFilter{Username: c.Query("username"), Category: c.Query("category"), TokenRef: c.Query("token_ref"), ExcludeTokenRef: c.Query("exclude_token_ref"), RequestId: c.Query("request_id")}
|
||||
viewerRole := c.GetInt("role")
|
||||
if c.FullPath() == "/api/audit/self" {
|
||||
filter.UserId = c.GetInt("id")
|
||||
filter.Username = ""
|
||||
filter.SelfView = true
|
||||
}
|
||||
if !model.ValidAuditCategory(filter.Category) || !model.ValidTokenFingerprint(filter.TokenRef) || !model.ValidTokenFingerprint(filter.ExcludeTokenRef) {
|
||||
common.ApiErrorMsg(c, "Invalid audit filters")
|
||||
return
|
||||
}
|
||||
for name, target := range map[string]*int64{"start_timestamp": &filter.StartTimestamp, "end_timestamp": &filter.EndTimestamp} {
|
||||
if raw := c.Query(name); raw != "" {
|
||||
parsed, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || parsed < 0 {
|
||||
common.ApiErrorMsg(c, "Invalid audit time range")
|
||||
return
|
||||
}
|
||||
*target = parsed
|
||||
}
|
||||
}
|
||||
if filter.EndTimestamp > 0 && filter.EndTimestamp < filter.StartTimestamp {
|
||||
common.ApiErrorMsg(c, "Invalid audit time range")
|
||||
return
|
||||
}
|
||||
if raw := c.Query("success"); raw != "" {
|
||||
if raw != "true" && raw != "false" {
|
||||
common.ApiErrorMsg(c, "Invalid audit result")
|
||||
return
|
||||
}
|
||||
success := raw == "true"
|
||||
filter.Success = &success
|
||||
}
|
||||
logs, total, err := model.GetAuditLogs(filter, page.GetStartIdx(), page.GetPageSize(), viewerRole)
|
||||
if err != nil {
|
||||
common.ApiError(c, err)
|
||||
return
|
||||
}
|
||||
page.SetItems(logs)
|
||||
page.SetTotal(int(total))
|
||||
common.ApiSuccess(c, page)
|
||||
}
|
||||
@@ -0,0 +1,855 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
sqlmysql "github.com/go-sql-driver/mysql"
|
||||
"gorm.io/driver/clickhouse"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/middleware"
|
||||
"github.com/QuantumNous/new-api/model"
|
||||
"github.com/QuantumNous/new-api/service"
|
||||
"github.com/QuantumNous/new-api/service/authz"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/glebarez/sqlite"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func setupAccessTokenAudit(t *testing.T) (*model.User, string) {
|
||||
t.Helper()
|
||||
previousDB, previousLogDB := model.DB, model.LOG_DB
|
||||
previousMain, previousLog := common.MainDatabaseType(), common.LogDatabaseType()
|
||||
previousRedis := common.RedisEnabled
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&model.User{}, &model.UserSession{}, &model.Log{}, &model.AuditLog{}, &model.CasbinRule{}, &model.AuthzRole{}))
|
||||
model.DB, model.LOG_DB = db, db
|
||||
common.SetDatabaseTypes(common.DatabaseTypeSQLite, common.DatabaseTypeSQLite)
|
||||
common.RedisEnabled = false
|
||||
previousMaster := common.IsMasterNode
|
||||
common.IsMasterNode = true
|
||||
require.NoError(t, authz.Init(db))
|
||||
t.Cleanup(func() {
|
||||
model.DB, model.LOG_DB = previousDB, previousLogDB
|
||||
common.IsMasterNode = previousMaster
|
||||
common.SetDatabaseTypes(previousMain, previousLog)
|
||||
common.RedisEnabled = previousRedis
|
||||
})
|
||||
token := "legacy-opaque-token"
|
||||
user := &model.User{Username: "audit-owner", Password: "placeholder", Role: common.RoleAdminUser, Status: common.UserStatusEnabled, Group: "default", AccessToken: &token, AuthVersion: 1, AffCode: "audit-owner"}
|
||||
require.NoError(t, db.Create(user).Error)
|
||||
return user, token
|
||||
}
|
||||
|
||||
func auditRequest(router http.Handler, method, path, token string) *httptest.ResponseRecorder {
|
||||
request := httptest.NewRequest(method, path, strings.NewReader(`{"secret":"body-must-not-be-logged"}`))
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
request.Header.Set("User-Agent", "audit-test-client")
|
||||
request.RemoteAddr = "192.0.2.8:4567"
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
return response
|
||||
}
|
||||
|
||||
func TestAccessTokenLifecycleAndLateRequests(t *testing.T) {
|
||||
user, old := setupAccessTokenAudit(t)
|
||||
router := gin.New()
|
||||
router.Use(middleware.RequestId(), middleware.AccessTokenAudit())
|
||||
router.GET("/api/user/token/status", middleware.UserAuth(), GetAccessTokenStatus)
|
||||
router.GET("/api/user/token", middleware.UserAuth(), GenerateAccessToken)
|
||||
router.POST("/api/user/token", middleware.UserAuth(), GenerateAccessToken)
|
||||
router.DELETE("/api/user/token", middleware.UserAuth(), RevokeAccessToken)
|
||||
// Rotate during the handler, after authentication has captured the old PAT.
|
||||
router.POST("/rotate-in-flight", middleware.UserAuth(), func(c *gin.Context) {
|
||||
require.NoError(t, model.UpdateUserAccessToken(user.Id, "new-token"))
|
||||
c.JSON(200, gin.H{"success": true})
|
||||
})
|
||||
status, err := model.GetUserAccessTokenStatus(user.Id)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, status.Exists)
|
||||
assert.Nil(t, status.CreatedAt)
|
||||
assert.Nil(t, status.LastUsedAt)
|
||||
assert.NotContains(t, auditRequest(router, "GET", "/api/user/token/status", old).Body.String(), old)
|
||||
require.Equal(t, 200, auditRequest(router, "POST", "/rotate-in-flight", old).Code)
|
||||
status, err = model.GetUserAccessTokenStatus(user.Id)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, model.AccessTokenFingerprint("new-token"), status.TokenRef)
|
||||
assert.NotNil(t, status.CreatedAt)
|
||||
assert.Nil(t, status.LastUsedAt, "in-flight old requests must not mark the new generation as used")
|
||||
assert.Equal(t, 401, auditRequest(router, "GET", "/api/user/token/status", old).Code)
|
||||
for _, method := range []string{"POST", "GET"} {
|
||||
response := auditRequest(router, method, "/api/user/token", "new-token")
|
||||
var result struct {
|
||||
Success bool
|
||||
Data string
|
||||
}
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result))
|
||||
require.True(t, result.Success)
|
||||
require.GreaterOrEqual(t, len(result.Data), 28)
|
||||
require.LessOrEqual(t, len(result.Data), 32)
|
||||
assert.Equal(t, 401, auditRequest(router, "GET", "/api/user/token/status", "new-token").Code)
|
||||
require.NoError(t, model.UpdateUserAccessToken(user.Id, "new-token"))
|
||||
}
|
||||
response := auditRequest(router, "DELETE", "/api/user/token", "new-token")
|
||||
assert.Contains(t, response.Body.String(), `"success":true`)
|
||||
assert.Equal(t, 401, auditRequest(router, "GET", "/api/user/token/status", "new-token").Code)
|
||||
ref, err := model.RevokeUserAccessToken(user.Id)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, ref, "repeated revocation is idempotent")
|
||||
status, err = model.GetUserAccessTokenStatus(user.Id)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, status.Exists)
|
||||
assert.Nil(t, status.CreatedAt)
|
||||
var history []model.AuditLog
|
||||
require.NoError(t, model.LOG_DB.Find(&history).Error)
|
||||
require.NotEmpty(t, history)
|
||||
encoded, err := common.Marshal(history)
|
||||
require.NoError(t, err)
|
||||
for _, secret := range []string{old, "new-token", "body-must-not-be-logged", "Authorization"} {
|
||||
assert.NotContains(t, string(encoded), secret)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccessTokenAuditsResultsAndExcludesBrowserSessions(t *testing.T) {
|
||||
user, pat := setupAccessTokenAudit(t)
|
||||
router := gin.New()
|
||||
router.Use(middleware.RequestId(), middleware.AccessTokenAudit())
|
||||
router.NoRoute(func(c *gin.Context) { c.JSON(404, gin.H{"success": false}) })
|
||||
router.GET("/public", func(c *gin.Context) { c.JSON(200, gin.H{"success": true}) })
|
||||
router.GET("/rate-limited", func(c *gin.Context) { c.AbortWithStatusJSON(429, gin.H{"success": false}) }, middleware.UserAuth())
|
||||
router.GET("/read/:id", middleware.UserAuth(), func(c *gin.Context) { c.JSON(200, gin.H{"success": true}) })
|
||||
router.POST("/write", middleware.AdminAuth(), func(c *gin.Context) {
|
||||
recordManageAudit(c, "option.update", map[string]interface{}{"key": "safe-setting"})
|
||||
c.JSON(200, gin.H{"success": true})
|
||||
})
|
||||
router.POST("/business-failure", middleware.AdminAuth(), func(c *gin.Context) { c.JSON(200, gin.H{"success": false, "message": "secret-response"}) })
|
||||
router.GET("/forbidden", middleware.RootAuth(), func(c *gin.Context) { c.Status(204) })
|
||||
cases := []struct {
|
||||
method, path string
|
||||
status int
|
||||
success bool
|
||||
}{{"GET", "/missing", 404, false}, {"GET", "/public", 200, true}, {"GET", "/rate-limited", 429, false}, {"GET", "/read/sensitive-id?password=secret-query", 200, true}, {"POST", "/write", 200, true}, {"POST", "/business-failure", 200, false}, {"GET", "/forbidden", 403, false}}
|
||||
for _, tc := range cases {
|
||||
response := auditRequest(router, tc.method, tc.path, pat)
|
||||
require.Equal(t, tc.status, response.Code)
|
||||
var access model.AuditLog
|
||||
require.NoError(t, model.LOG_DB.Where("request_id = ? AND category = ?", response.Header().Get(common.RequestIdKey), model.AuditCategoryAccessToken).First(&access).Error)
|
||||
assert.Equal(t, tc.success, access.Success)
|
||||
assert.Equal(t, tc.status, access.Status)
|
||||
assert.Equal(t, user.Id, access.UserId)
|
||||
assert.Equal(t, "192.0.2.8", access.Ip)
|
||||
assert.Equal(t, "audit-test-client", access.UserAgent)
|
||||
assert.NotContains(t, access.Route, "sensitive-id")
|
||||
}
|
||||
var operationCount int64
|
||||
require.NoError(t, model.LOG_DB.Model(&model.AuditLog{}).Where("category = ?", model.AuditCategoryOperation).Count(&operationCount).Error)
|
||||
assert.EqualValues(t, 2, operationCount, "manual operation must not be duplicated by fallback")
|
||||
now := time.Now().Unix()
|
||||
session := &model.UserSession{SID: "audit-session", UserID: user.Id, Version: 1, UserAuthVersion: 1, Status: model.UserSessionStatusActive, RefreshHash: "refresh-placeholder", LoginMethod: "password", LastActiveAt: now, ExpiresAt: now + 3600}
|
||||
require.NoError(t, model.CreateUserSession(session))
|
||||
jwt, _, err := service.IssueAccessToken(service.AuthIdentity{UserID: user.Id, SessionID: session.SID, UserAuthVersion: 1, SessionVersion: 1})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 200, auditRequest(router, "GET", "/read/123", jwt).Code)
|
||||
assert.Equal(t, 401, auditRequest(router, "GET", "/read/123", "unknown-token").Code)
|
||||
entries, total, err := model.GetAuditLogs(model.AuditLogFilter{Category: model.AuditCategoryAccessToken}, 0, 20, common.RoleRootUser)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 7, total)
|
||||
encoded, err := common.Marshal(entries)
|
||||
require.NoError(t, err)
|
||||
for _, secret := range []string{pat, jwt, "secret-query", "secret-response", "body-must-not-be-logged", "sensitive-id"} {
|
||||
assert.NotContains(t, string(encoded), secret)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditIsolationVisibilityAndFailureContracts(t *testing.T) {
|
||||
user, pat := setupAccessTokenAudit(t)
|
||||
metadata := model.AuditOther{
|
||||
Op: &model.AuditOperation{Action: "generic"},
|
||||
AdminInfo: &model.AuditAdminInfo{AdminID: 1},
|
||||
RootInfo: model.AuditFields{"private": "root-only"},
|
||||
}
|
||||
for _, owner := range []int{user.Id, user.Id + 1} {
|
||||
model.RecordAuditLog(nil, model.AuditLog{ActorRole: common.RoleAdminUser, UserId: owner, Username: fmt.Sprint(owner), Category: model.AuditCategorySecurity, Success: false, Other: metadata})
|
||||
}
|
||||
router := gin.New()
|
||||
router.Use(middleware.RequestId(), middleware.AccessTokenAudit())
|
||||
router.GET("/api/audit/self", middleware.UserAuth(), GetAuditLogs)
|
||||
router.GET("/api/audit", middleware.AdminAuth(), middleware.RequirePermission(authz.AuditRead), GetAuditLogs)
|
||||
response := auditRequest(router, "GET", "/api/audit/self?username=other&user_id=2&category=security&success=false&page_size=1", pat)
|
||||
var result struct {
|
||||
Success bool
|
||||
Data struct {
|
||||
Items []model.AuditLog
|
||||
Total int
|
||||
}
|
||||
}
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result))
|
||||
require.True(t, result.Success)
|
||||
require.Equal(t, 1, result.Data.Total)
|
||||
require.Len(t, result.Data.Items, 1)
|
||||
assert.Equal(t, user.Id, result.Data.Items[0].UserId)
|
||||
assert.NotContains(t, response.Body.String(), "admin_info")
|
||||
assert.NotContains(t, response.Body.String(), "root-only")
|
||||
var payload struct {
|
||||
Data struct {
|
||||
Items []struct {
|
||||
Other map[string]interface{} `json:"other"`
|
||||
}
|
||||
}
|
||||
}
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &payload), "audit metadata must be a JSON object, not an encoded string")
|
||||
require.Len(t, payload.Data.Items, 1)
|
||||
assert.Contains(t, payload.Data.Items[0].Other, "op")
|
||||
require.NoError(t, authz.SetUserPermissions(user.Id, authz.PermissionsMap{authz.ResourceAudit: {authz.ActionRead: true}}))
|
||||
response = auditRequest(router, "GET", "/api/audit?category=security", pat)
|
||||
assert.Contains(t, response.Body.String(), "admin_info")
|
||||
assert.NotContains(t, response.Body.String(), "root-only")
|
||||
for _, query := range []string{"success=bad", "category=bad", "token_ref=secret", "start_timestamp=-1", "start_timestamp=2&end_timestamp=1", "p=-1", "page_size=-1"} {
|
||||
assert.Contains(t, auditRequest(router, "GET", "/api/audit/self?"+query, pat).Body.String(), `"success":false`)
|
||||
}
|
||||
require.NoError(t, model.LOG_DB.Callback().Query().Before("gorm:query").Register("audit:fail", func(tx *gorm.DB) {
|
||||
if tx.Statement.Table == "audit_logs" {
|
||||
tx.AddError(errors.New("audit store unavailable"))
|
||||
}
|
||||
}))
|
||||
_, err := model.GetUserAccessTokenStatus(user.Id)
|
||||
require.Error(t, err, "audit query failure must not look like never used")
|
||||
model.LOG_DB.Callback().Query().Remove("audit:fail")
|
||||
require.NoError(t, model.DB.Callback().Update().Before("gorm:update").Register("audit:write-fail", func(tx *gorm.DB) { tx.AddError(errors.New("write unavailable")) }))
|
||||
require.Error(t, model.UpdateUserAccessToken(user.Id, "replacement"))
|
||||
_, err = model.RevokeUserAccessToken(user.Id)
|
||||
require.Error(t, err)
|
||||
model.DB.Callback().Update().Remove("audit:write-fail")
|
||||
status, err := model.GetUserAccessTokenStatus(user.Id)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, model.AccessTokenFingerprint(pat), status.TokenRef)
|
||||
}
|
||||
|
||||
func TestAuditRoleVisibilityAndPermissions(t *testing.T) {
|
||||
admin, pat := setupAccessTokenAudit(t)
|
||||
rootToken := "root-audit-token"
|
||||
root := &model.User{Username: "root-audit", Role: common.RoleRootUser, Status: common.UserStatusEnabled, AuthVersion: 1, AccessToken: &rootToken, AffCode: "root-audit"}
|
||||
require.NoError(t, model.DB.Create(root).Error)
|
||||
metadata := model.AuditOther{
|
||||
AdminInfo: &model.AuditAdminInfo{AdminID: 1},
|
||||
RootInfo: model.AuditFields{"private": "root-only"},
|
||||
}
|
||||
for i, role := range []int{1, 10, 100, 0, -1, 99} {
|
||||
model.RecordAuditLog(nil, model.AuditLog{ActorRole: role, UserId: admin.Id, Username: admin.Username, Category: model.AuditCategorySecurity, RequestId: fmt.Sprintf("role-%d", role), CreatedAt: int64(100 + i), Other: metadata})
|
||||
}
|
||||
model.RecordAuditLog(nil, model.AuditLog{ActorRole: 100, UserId: root.Id, Username: root.Username, Category: model.AuditCategorySecurity, RequestId: "root-owned", Other: metadata})
|
||||
router := gin.New()
|
||||
router.Use(middleware.RequestId(), middleware.AccessTokenAudit())
|
||||
router.GET("/api/audit", middleware.AdminAuth(), middleware.RequirePermission(authz.AuditRead), GetAuditLogs)
|
||||
router.GET("/api/audit/self", middleware.UserAuth(), GetAuditLogs)
|
||||
now := time.Now().Unix()
|
||||
session := &model.UserSession{SID: "audit-permissions-session", UserID: admin.Id, Version: 1, UserAuthVersion: 1, Status: model.UserSessionStatusActive, RefreshHash: "placeholder", LoginMethod: "password", LastActiveAt: now, ExpiresAt: now + 3600}
|
||||
require.NoError(t, model.CreateUserSession(session))
|
||||
jwt, _, err := service.IssueAccessToken(service.AuthIdentity{UserID: admin.Id, SessionID: session.SID, UserAuthVersion: 1, SessionVersion: 1})
|
||||
require.NoError(t, err)
|
||||
for _, credential := range []string{pat, jwt} {
|
||||
assert.Equal(t, http.StatusForbidden, auditRequest(router, "GET", "/api/audit", credential).Code)
|
||||
}
|
||||
require.NoError(t, model.DB.Transaction(func(tx *gorm.DB) error {
|
||||
return authz.SetUserPermissionsInTx(tx, admin.Id, authz.PermissionsMap{authz.ResourceAudit: {authz.ActionRead: true}})
|
||||
}))
|
||||
require.NoError(t, authz.ReloadPolicy())
|
||||
for _, credential := range []string{pat, jwt} {
|
||||
for _, endpoint := range []string{"/api/audit", "/api/audit/self"} {
|
||||
response := auditRequest(router, "GET", endpoint+"?category=security&page_size=1", credential)
|
||||
assert.Equal(t, http.StatusOK, response.Code)
|
||||
var result struct {
|
||||
Data struct {
|
||||
Total int
|
||||
Items []model.AuditLog
|
||||
}
|
||||
}
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result))
|
||||
assert.Equal(t, 2, result.Data.Total)
|
||||
require.Len(t, result.Data.Items, 1)
|
||||
assert.Equal(t, 10, result.Data.Items[0].ActorRole)
|
||||
assert.NotContains(t, response.Body.String(), "root-only")
|
||||
for _, filter := range []string{"request_id=role-100", "username=" + root.Username, "request_id=role-0"} {
|
||||
filtered := auditRequest(router, "GET", endpoint+"?category=security&"+filter, credential)
|
||||
// self ignores supplied usernames, while still excluding every root row.
|
||||
if endpoint == "/api/audit/self" && strings.HasPrefix(filter, "username=") {
|
||||
continue
|
||||
}
|
||||
assert.Contains(t, filtered.Body.String(), `"total":0`)
|
||||
}
|
||||
}
|
||||
}
|
||||
rootSelf := auditRequest(router, "GET", "/api/audit/self?category=security", rootToken)
|
||||
assert.Contains(t, rootSelf.Body.String(), `"actor_role":100`)
|
||||
assert.NotContains(t, rootSelf.Body.String(), "admin_info")
|
||||
rootAll := auditRequest(router, "GET", "/api/audit?category=security", rootToken)
|
||||
assert.Contains(t, rootAll.Body.String(), `"total":7`)
|
||||
assert.Contains(t, rootAll.Body.String(), "root-only")
|
||||
require.NoError(t, authz.SetUserPermissions(admin.Id, authz.PermissionsMap{authz.ResourceAudit: {authz.ActionRead: false}}))
|
||||
for _, credential := range []string{pat, jwt} {
|
||||
assert.Equal(t, http.StatusForbidden, auditRequest(router, "GET", "/api/audit", credential).Code)
|
||||
assert.Equal(t, http.StatusOK, auditRequest(router, "GET", "/api/audit/self", credential).Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditRoleSnapshotSurvivesActorChanges(t *testing.T) {
|
||||
user, pat := setupAccessTokenAudit(t)
|
||||
user.Role = common.RoleRootUser
|
||||
require.NoError(t, model.DB.Model(user).Update("role", user.Role).Error)
|
||||
router := gin.New()
|
||||
router.Use(middleware.RequestId(), middleware.AccessTokenAudit())
|
||||
router.POST("/change-role", middleware.UserAuth(), func(c *gin.Context) {
|
||||
recordLoginAudit(user, c)
|
||||
recordUserSecurityAudit(c, user.Id, "user.security_verify", nil)
|
||||
recordSubscriptionResetUserLogs(c, &model.SubscriptionResetResult{ResetCount: 1, PlanId: 1, PlanTitle: "Plan", AffectedUserIds: []int{999}}, auditOperatorInfo(c))
|
||||
require.NoError(t, model.DB.Model(user).Update("role", common.RoleAdminUser).Error)
|
||||
c.Status(200)
|
||||
})
|
||||
require.Equal(t, http.StatusOK, auditRequest(router, "POST", "/change-role", pat).Code)
|
||||
entries, total, err := model.GetAuditLogs(model.AuditLogFilter{}, 0, 20, common.RoleAdminUser)
|
||||
require.NoError(t, err)
|
||||
assert.Zero(t, total)
|
||||
assert.Empty(t, entries)
|
||||
status, err := model.GetUserAccessTokenStatus(user.Id)
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, status.LastUsedAt, "a root request must not leak through the last-use summary after demotion")
|
||||
require.NoError(t, model.DB.Unscoped().Delete(user).Error)
|
||||
entries, total, err = model.GetAuditLogs(model.AuditLogFilter{}, 0, 20, common.RoleRootUser)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 4, total)
|
||||
for _, entry := range entries {
|
||||
assert.Equal(t, common.RoleRootUser, entry.ActorRole)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecurityAndOperationEventsUseAuditTable(t *testing.T) {
|
||||
user, _ := setupAccessTokenAudit(t)
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest("POST", "/event", nil)
|
||||
c.Set("id", user.Id)
|
||||
c.Set("username", user.Username)
|
||||
c.Set("role", user.Role)
|
||||
c.Set(common.RequestIdKey, "correlated-request")
|
||||
recordLoginAudit(user, c)
|
||||
for _, action := range []string{"user.passkey_register", "user.passkey_delete", "user.2fa_setup", "user.2fa_enable", "user.2fa_disable_self", "user.2fa_backup_codes", "user.security_verify"} {
|
||||
recordUserSecurityAudit(c, user.Id, action, nil)
|
||||
}
|
||||
recordManageAudit(c, "option.update", map[string]interface{}{"key": "safe"})
|
||||
recordSubscriptionResetUserLogs(c, &model.SubscriptionResetResult{ResetCount: 1, PlanId: 1, PlanTitle: "Plan", AffectedUserIds: []int{user.Id}}, &model.AuditAdminInfo{AdminID: user.Id})
|
||||
for _, typ := range []int{model.LogTypeTopup, model.LogTypeConsume, model.LogTypeRefund, model.LogTypeSystem} {
|
||||
model.RecordLog(user.Id, typ, "business entry")
|
||||
}
|
||||
var audits []model.AuditLog
|
||||
require.NoError(t, model.LOG_DB.Find(&audits).Error)
|
||||
assert.Len(t, audits, 10)
|
||||
for _, entry := range audits {
|
||||
assert.Equal(t, "correlated-request", entry.RequestId)
|
||||
assert.Equal(t, user.Role, entry.ActorRole)
|
||||
}
|
||||
var logs []model.Log
|
||||
require.NoError(t, model.LOG_DB.Find(&logs).Error)
|
||||
assert.Len(t, logs, 4)
|
||||
_, err := model.DeleteOldLogBatch(context.Background(), time.Now().Unix()+1, 100)
|
||||
require.NoError(t, err)
|
||||
var count int64
|
||||
require.NoError(t, model.LOG_DB.Model(&model.AuditLog{}).Count(&count).Error)
|
||||
assert.EqualValues(t, 10, count)
|
||||
}
|
||||
|
||||
// Released schemas copied from v1.0.0-rc.33; only the Go type names differ.
|
||||
|
||||
type releasedAuditUser struct {
|
||||
Id int `json:"id"`
|
||||
Username string `json:"username" gorm:"unique;index" validate:"max=20"`
|
||||
Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"`
|
||||
OriginalPassword string `json:"original_password" gorm:"-:all"` // this field is only for Password change verification, don't save it to database!
|
||||
DisplayName string `json:"display_name" gorm:"index" validate:"max=20"`
|
||||
Role int `json:"role" gorm:"type:int;default:1"` // admin, common
|
||||
Status int `json:"status" gorm:"type:int;default:1"` // enabled, disabled
|
||||
Email string `json:"email" gorm:"index" validate:"max=50"`
|
||||
GitHubId string `json:"github_id" gorm:"column:github_id;index"`
|
||||
DiscordId string `json:"discord_id" gorm:"column:discord_id;index"`
|
||||
OidcId string `json:"oidc_id" gorm:"column:oidc_id;index"`
|
||||
WeChatId string `json:"wechat_id" gorm:"column:wechat_id;index"`
|
||||
TelegramId string `json:"telegram_id" gorm:"column:telegram_id;index"`
|
||||
VerificationCode string `json:"verification_code" gorm:"-:all"` // this field is only for Email verification, don't save it to database!
|
||||
AccessToken *string `json:"-" gorm:"type:char(32);column:access_token;uniqueIndex"` // this token is for system management
|
||||
Quota int `json:"quota" gorm:"type:int;default:0"`
|
||||
UsedQuota int `json:"used_quota" gorm:"type:int;default:0;column:used_quota"` // used quota
|
||||
RequestCount int `json:"request_count" gorm:"type:int;default:0;"` // request number
|
||||
Group string `json:"group" gorm:"type:varchar(64);default:'default'"`
|
||||
AffCode string `json:"aff_code" gorm:"type:varchar(32);column:aff_code;uniqueIndex"`
|
||||
AffCount int `json:"aff_count" gorm:"type:int;default:0;column:aff_count"`
|
||||
AffQuota int `json:"aff_quota" gorm:"type:int;default:0;column:aff_quota"` // 邀请剩余额度
|
||||
AffHistoryQuota int `json:"aff_history_quota" gorm:"type:int;default:0;column:aff_history"` // 邀请历史额度
|
||||
InviterId int `json:"inviter_id" gorm:"type:int;column:inviter_id;index"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index"`
|
||||
LinuxDOId string `json:"linux_do_id" gorm:"column:linux_do_id;index"`
|
||||
Setting string `json:"setting" gorm:"type:text;column:setting"`
|
||||
Remark string `json:"remark,omitempty" gorm:"type:varchar(255)" validate:"max=255"`
|
||||
StripeCustomer string `json:"stripe_customer" gorm:"type:varchar(64);column:stripe_customer;index"`
|
||||
CreatedAt int64 `json:"created_at" gorm:"autoCreateTime;column:created_at"`
|
||||
LastLoginAt int64 `json:"last_login_at" gorm:"default:0;column:last_login_at"`
|
||||
AuthVersion int64 `json:"-" gorm:"type:bigint;not null;default:1;column:auth_version"`
|
||||
AdminPermissions map[string]map[string]bool `json:"admin_permissions,omitempty" gorm:"-:all"`
|
||||
}
|
||||
|
||||
func (releasedAuditUser) TableName() string { return "users" }
|
||||
|
||||
type releasedAuditLog struct {
|
||||
Id int `json:"id" gorm:"index:idx_created_at_id,priority:2;index:idx_user_id_id,priority:2"`
|
||||
UserId int `json:"user_id" gorm:"index;index:idx_user_id_id,priority:1"`
|
||||
CreatedAt int64 `json:"created_at" gorm:"bigint;index:idx_created_at_id,priority:1;index:idx_created_at_type"`
|
||||
Type int `json:"type" gorm:"index:idx_created_at_type"`
|
||||
Content string `json:"content"`
|
||||
Username string `json:"username" gorm:"index;index:index_username_model_name,priority:2;default:''"`
|
||||
TokenName string `json:"token_name" gorm:"index;default:''"`
|
||||
ModelName string `json:"model_name" gorm:"index;index:index_username_model_name,priority:1;default:''"`
|
||||
Quota int `json:"quota" gorm:"default:0"`
|
||||
PromptTokens int `json:"prompt_tokens" gorm:"default:0"`
|
||||
CompletionTokens int `json:"completion_tokens" gorm:"default:0"`
|
||||
UseTime int `json:"use_time" gorm:"default:0"`
|
||||
IsStream bool `json:"is_stream"`
|
||||
ChannelId int `json:"channel" gorm:"index"`
|
||||
ChannelName string `json:"channel_name" gorm:"->"`
|
||||
TokenId int `json:"token_id" gorm:"default:0;index"`
|
||||
Group string `json:"group" gorm:"index"`
|
||||
Ip string `json:"ip" gorm:"index;default:''"`
|
||||
RequestId string `json:"request_id,omitempty" gorm:"type:varchar(64);index:idx_logs_request_id;default:''"`
|
||||
UpstreamRequestId string `json:"upstream_request_id,omitempty" gorm:"type:varchar(128);index:idx_logs_upstream_request_id;default:''"`
|
||||
Other string `json:"other"`
|
||||
}
|
||||
|
||||
func (releasedAuditLog) TableName() string { return "logs" }
|
||||
|
||||
// External tests create a new database per case on a loopback-only disposable
|
||||
// instance. They never drop databases or tables supplied through an environment variable.
|
||||
func newAuditTestDatabase(t *testing.T, kind, dsn string) (*gorm.DB, string) {
|
||||
t.Helper()
|
||||
if kind == "sqlite" {
|
||||
path := t.TempDir() + "/audit.db"
|
||||
db, err := gorm.Open(sqlite.Open(path), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
return db, path
|
||||
}
|
||||
require.NotEmpty(t, dsn)
|
||||
name := fmt.Sprintf("newapi_audit_%d", time.Now().UnixNano())
|
||||
var original, isolated gorm.Dialector
|
||||
var newDSN string
|
||||
if kind == "mysql" {
|
||||
config, err := sqlmysql.ParseDSN(dsn)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "tcp", config.Net)
|
||||
host, _, err := net.SplitHostPort(config.Addr)
|
||||
require.NoError(t, err)
|
||||
require.True(t, net.ParseIP(host).IsLoopback(), "database tests only permit loopback instances")
|
||||
original = mysql.Open(dsn)
|
||||
config.DBName = name
|
||||
newDSN = config.FormatDSN()
|
||||
isolated = mysql.Open(newDSN)
|
||||
} else {
|
||||
parsed, err := url.Parse(dsn)
|
||||
require.NoError(t, err)
|
||||
require.True(t, net.ParseIP(parsed.Hostname()).IsLoopback(), "database tests only permit loopback instances")
|
||||
parsed.Path = "/" + name
|
||||
newDSN = parsed.String()
|
||||
if kind == "clickhouse" {
|
||||
original = clickhouse.Open(dsn)
|
||||
isolated = clickhouse.Open(newDSN)
|
||||
} else {
|
||||
original = postgres.Open(dsn)
|
||||
isolated = postgres.Open(newDSN)
|
||||
}
|
||||
}
|
||||
admin, err := gorm.Open(original, &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
// No IF NOT EXISTS: a collision fails before any test data can be written.
|
||||
createSQL := "CREATE DATABASE " + name
|
||||
if kind == "mysql" {
|
||||
createSQL += " CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
|
||||
}
|
||||
require.NoError(t, admin.Exec(createSQL).Error)
|
||||
sqlDB, err := admin.DB()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, sqlDB.Close())
|
||||
db, err := gorm.Open(isolated, &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
t.Logf("isolated database: %s (%s)", name, kind)
|
||||
t.Cleanup(func() {
|
||||
connection, err := db.DB()
|
||||
if err == nil {
|
||||
_ = connection.Close()
|
||||
}
|
||||
})
|
||||
return db, newDSN
|
||||
}
|
||||
|
||||
func verifyAuditRoleStorage(t *testing.T) {
|
||||
t.Helper()
|
||||
for i, role := range []int{1, 10, 100, 0, 99} {
|
||||
model.RecordAuditLog(nil, model.AuditLog{ActorRole: role, UserId: 1, Username: "role-owner", CreatedAt: int64(200 + i), Category: model.AuditCategoryOperation, RequestId: fmt.Sprintf("matrix-role-%d", role)})
|
||||
}
|
||||
filter := model.AuditLogFilter{Category: model.AuditCategoryOperation}
|
||||
visible, total, err := model.GetAuditLogs(filter, 0, 1, common.RoleAdminUser)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 2, total)
|
||||
require.Len(t, visible, 1)
|
||||
assert.Equal(t, common.RoleAdminUser, visible[0].ActorRole)
|
||||
visible, total, err = model.GetAuditLogs(filter, 1, 1, common.RoleCommonUser)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 2, total)
|
||||
require.Len(t, visible, 1)
|
||||
assert.Equal(t, common.RoleCommonUser, visible[0].ActorRole)
|
||||
filter.RequestId = "matrix-role-100"
|
||||
visible, total, err = model.GetAuditLogs(filter, 0, 20, common.RoleAdminUser)
|
||||
require.NoError(t, err)
|
||||
assert.Zero(t, total)
|
||||
assert.Empty(t, visible)
|
||||
visible, total, err = model.GetAuditLogs(filter, 0, 20, common.RoleRootUser)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 1, total)
|
||||
require.Len(t, visible, 1)
|
||||
assert.Equal(t, common.RoleRootUser, visible[0].ActorRole)
|
||||
}
|
||||
|
||||
func verifyAuditJSONStorage(t *testing.T) {
|
||||
t.Helper()
|
||||
columns, err := model.LOG_DB.Migrator().ColumnTypes(&model.AuditLog{})
|
||||
require.NoError(t, err)
|
||||
var otherType string
|
||||
for _, column := range columns {
|
||||
if column.Name() == "other" {
|
||||
otherType = strings.ToLower(column.DatabaseTypeName())
|
||||
}
|
||||
}
|
||||
assert.Equal(t, "json", otherType)
|
||||
|
||||
metadata := model.AuditOther{
|
||||
Op: &model.AuditOperation{Action: "channel.update", Params: model.AuditFields{
|
||||
"id": 42, "name": "渠道", "changed_fields": []string{}, "large_id": uint64(9007199254740993),
|
||||
"extra": map[string]interface{}{"attempts": 0, "permitted": false, "ratio": 1.25, "targets": []int{1, 2}},
|
||||
}},
|
||||
AdminInfo: &model.AuditAdminInfo{AdminID: 1},
|
||||
AuditInfo: &model.AuditRequestInfo{Method: "PUT", Route: "/api/channel/", Path: "/api/channel/", Status: 200, Success: false},
|
||||
RootInfo: model.AuditFields{"private": "root-only"},
|
||||
}
|
||||
model.RecordAuditLog(nil, model.AuditLog{ActorRole: common.RoleCommonUser, UserId: 1, Username: "json-owner", Category: model.AuditCategorySecurity, RequestId: "matrix-json", Other: metadata})
|
||||
filter := model.AuditLogFilter{RequestId: "matrix-json"}
|
||||
entries, total, err := model.GetAuditLogs(filter, 0, 20, common.RoleRootUser)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 1, total)
|
||||
require.Len(t, entries, 1)
|
||||
stored, err := common.Marshal(entries[0].Other)
|
||||
require.NoError(t, err)
|
||||
expected, err := common.Marshal(metadata)
|
||||
require.NoError(t, err)
|
||||
assert.JSONEq(t, string(expected), string(stored))
|
||||
require.NotNil(t, entries[0].Other.Op)
|
||||
assert.Equal(t, "channel.update", entries[0].Other.Op.Action)
|
||||
require.NotNil(t, entries[0].Other.AuditInfo)
|
||||
assert.False(t, entries[0].Other.AuditInfo.Success)
|
||||
var details struct {
|
||||
Op struct {
|
||||
Params struct {
|
||||
LargeId uint64 `json:"large_id"`
|
||||
}
|
||||
}
|
||||
}
|
||||
require.NoError(t, common.Unmarshal(stored, &details))
|
||||
assert.EqualValues(t, 9007199254740993, details.Op.Params.LargeId, "JSON numbers must retain their type and precision")
|
||||
for _, role := range []int{common.RoleCommonUser, common.RoleAdminUser} {
|
||||
entries, _, err = model.GetAuditLogs(filter, 0, 20, role)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, 1)
|
||||
assert.Nil(t, entries[0].Other.RootInfo)
|
||||
if role == common.RoleCommonUser {
|
||||
assert.Nil(t, entries[0].Other.AdminInfo)
|
||||
assert.Nil(t, entries[0].Other.AuditInfo)
|
||||
} else {
|
||||
assert.NotNil(t, entries[0].Other.AdminInfo)
|
||||
assert.NotNil(t, entries[0].Other.AuditInfo)
|
||||
}
|
||||
}
|
||||
model.RecordAuditLog(nil, model.AuditLog{ActorRole: common.RoleCommonUser, UserId: 1, Username: "json-owner", RequestId: "matrix-json-empty", Other: model.AuditOther{}})
|
||||
entries, _, err = model.GetAuditLogs(model.AuditLogFilter{RequestId: "matrix-json-empty"}, 0, 20, common.RoleRootUser)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, 1)
|
||||
empty, err := common.Marshal(entries[0].Other)
|
||||
require.NoError(t, err)
|
||||
assert.JSONEq(t, `{}`, string(empty))
|
||||
for i := 0; i < 2; i++ {
|
||||
require.NoError(t, model.InitLogDB())
|
||||
}
|
||||
entries, total, err = model.GetAuditLogs(filter, 0, 20, common.RoleRootUser)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 1, total)
|
||||
require.Len(t, entries, 1)
|
||||
stored, err = common.Marshal(entries[0].Other)
|
||||
require.NoError(t, err)
|
||||
assert.JSONEq(t, string(expected), string(stored), "repeated startup must retain structured audit metadata")
|
||||
}
|
||||
|
||||
func TestAuditOtherDatabaseEncoding(t *testing.T) {
|
||||
const payload = `{"op":{"action":"channel.update","params":{"id":9007199254740993,"nested":{"count":0,"enabled":false}}},"admin_info":{"admin_id":1,"admin_username":"root","admin_role":100,"auth_method":"session"},"audit_info":{"method":"PUT","route":"/api/channel/","path":"/api/channel/","status":200,"success":false},"root_info":{"generation":18446744073709551615}}`
|
||||
for _, input := range []interface{}{payload, []byte(payload)} {
|
||||
var other model.AuditOther
|
||||
require.NoError(t, other.Scan(input))
|
||||
require.NotNil(t, other.Op)
|
||||
assert.Equal(t, "channel.update", other.Op.Action)
|
||||
require.NotNil(t, other.AdminInfo)
|
||||
assert.Equal(t, 100, other.AdminInfo.AdminRole)
|
||||
require.NotNil(t, other.AuditInfo)
|
||||
assert.False(t, other.AuditInfo.Success)
|
||||
encoded, err := other.Value()
|
||||
require.NoError(t, err)
|
||||
text, ok := encoded.(string)
|
||||
require.True(t, ok, "PostgreSQL simple protocol requires a string parameter")
|
||||
assert.JSONEq(t, payload, text)
|
||||
assert.Contains(t, text, "9007199254740993")
|
||||
assert.Contains(t, text, "18446744073709551615")
|
||||
for _, empty := range []interface{}{nil, "", []byte(`null`), "{}"} {
|
||||
require.NoError(t, other.Scan(input))
|
||||
require.NoError(t, other.Scan(empty))
|
||||
encoded, err = other.Value()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "{}", encoded, "empty input must clear fields from the previous row")
|
||||
}
|
||||
}
|
||||
var invalid model.AuditOther
|
||||
assert.Error(t, invalid.Scan(42))
|
||||
assert.Error(t, invalid.Scan([]byte(`{broken`)))
|
||||
}
|
||||
|
||||
func TestAuditDatabaseMatrix(t *testing.T) {
|
||||
previousDB, previousLogDB := model.DB, model.LOG_DB
|
||||
previousMain, previousLog := common.MainDatabaseType(), common.LogDatabaseType()
|
||||
previousRedis := common.RedisEnabled
|
||||
previousMaster, previousSQLite := common.IsMasterNode, common.SQLitePath
|
||||
common.IsMasterNode = true
|
||||
common.RedisEnabled = false
|
||||
t.Cleanup(func() {
|
||||
common.IsMasterNode, common.SQLitePath = previousMaster, previousSQLite
|
||||
model.DB, model.LOG_DB = previousDB, previousLogDB
|
||||
common.SetDatabaseTypes(previousMain, previousLog)
|
||||
common.RedisEnabled = previousRedis
|
||||
})
|
||||
cases := []struct {
|
||||
name, env string
|
||||
typ common.DatabaseType
|
||||
}{
|
||||
{"sqlite", "", common.DatabaseTypeSQLite}, {"mysql", "AUDIT_MYSQL_DSN", common.DatabaseTypeMySQL}, {"postgres", "AUDIT_POSTGRES_DSN", common.DatabaseTypePostgreSQL},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dsn := os.Getenv(tc.env)
|
||||
if tc.env != "" && dsn == "" {
|
||||
t.Skip(tc.env + " is not configured")
|
||||
}
|
||||
for _, upgrade := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("upgrade=%v", upgrade), func(t *testing.T) {
|
||||
db, isolatedDSN := newAuditTestDatabase(t, tc.name, dsn)
|
||||
t.Setenv("LOG_SQL_DSN", "")
|
||||
if tc.name == "sqlite" {
|
||||
common.SQLitePath = isolatedDSN
|
||||
t.Setenv("SQL_DSN", "local")
|
||||
} else {
|
||||
t.Setenv("SQL_DSN", isolatedDSN)
|
||||
}
|
||||
model.DB, model.LOG_DB = db, db
|
||||
common.SetDatabaseTypes(tc.typ, tc.typ)
|
||||
versionSQL := "SELECT version()"
|
||||
if tc.name == "sqlite" {
|
||||
versionSQL = "SELECT sqlite_version()"
|
||||
}
|
||||
var version string
|
||||
require.NoError(t, db.Raw(versionSQL).Scan(&version).Error)
|
||||
t.Logf("database version: %s", version)
|
||||
if upgrade {
|
||||
require.NoError(t, db.AutoMigrate(&releasedAuditUser{}, &releasedAuditLog{}))
|
||||
legacy := "released-token"
|
||||
require.NoError(t, db.Create(&releasedAuditUser{Username: "released-owner", Password: "placeholder", AccessToken: &legacy, AffCode: "released-aff", Quota: 1234}).Error)
|
||||
require.NoError(t, db.Create(&releasedAuditLog{UserId: 1, Type: model.LogTypeLogin, Content: "historical login", CreatedAt: 100, RequestId: "legacy-request"}).Error)
|
||||
}
|
||||
for i := 0; i < 2; i++ {
|
||||
require.NoError(t, model.InitDB())
|
||||
require.NoError(t, model.InitLogDB())
|
||||
}
|
||||
if !upgrade {
|
||||
require.NoError(t, db.Create(&model.User{Username: "fresh-owner", Password: "placeholder", AffCode: "fresh-aff"}).Error)
|
||||
}
|
||||
status, err := model.GetUserAccessTokenStatus(1)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, upgrade, status.Exists)
|
||||
assert.Nil(t, status.CreatedAt)
|
||||
if upgrade {
|
||||
assert.Equal(t, model.AccessTokenFingerprint("released-token"), status.TokenRef)
|
||||
legacyUser, validationErr := model.ValidateAccessToken("released-token")
|
||||
require.NoError(t, validationErr)
|
||||
require.NotNil(t, legacyUser)
|
||||
var user model.User
|
||||
require.NoError(t, db.First(&user, 1).Error)
|
||||
assert.Equal(t, 1234, user.Quota)
|
||||
var old model.Log
|
||||
require.NoError(t, db.First(&old).Error)
|
||||
assert.Equal(t, "historical login", old.Content)
|
||||
}
|
||||
require.NoError(t, model.UpdateUserAccessToken(1, "matrix-token"))
|
||||
require.Error(t, db.Create(&model.User{Username: "duplicate", Password: "placeholder", AffCode: "duplicate-aff", AccessToken: common.GetPointer("matrix-token")}).Error, "PAT uniqueness must survive upgrade")
|
||||
for _, timestamp := range []int64{101, 102, 103} {
|
||||
model.RecordAuditLog(nil, model.AuditLog{ActorRole: common.RoleAdminUser, UserId: 1, Username: "owner", CreatedAt: timestamp, Category: model.AuditCategoryAccessToken, TokenRef: model.AccessTokenFingerprint("matrix-token"), Ip: "192.0.2.1", Success: timestamp != 102})
|
||||
}
|
||||
first, total, err := model.GetAuditLogs(model.AuditLogFilter{UserId: 1}, 0, 2, common.RoleCommonUser)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 3, total)
|
||||
require.Len(t, first, 2)
|
||||
assert.EqualValues(t, 103, first[0].CreatedAt)
|
||||
second, _, err := model.GetAuditLogs(model.AuditLogFilter{UserId: 1}, 2, 2, common.RoleCommonUser)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, second, 1)
|
||||
assert.EqualValues(t, 101, second[0].CreatedAt)
|
||||
failure := false
|
||||
failed, _, err := model.GetAuditLogs(model.AuditLogFilter{UserId: 1, Success: &failure}, 0, 10, 1)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, failed, 1)
|
||||
assert.EqualValues(t, 102, failed[0].CreatedAt)
|
||||
status, err = model.GetUserAccessTokenStatus(1)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, status.LastUsedAt)
|
||||
assert.EqualValues(t, 103, *status.LastUsedAt)
|
||||
_, err = model.RevokeUserAccessToken(1)
|
||||
require.NoError(t, err)
|
||||
_, err = model.RevokeUserAccessToken(1)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, model.MigrateAuditLogs())
|
||||
_, total, err = model.GetAuditLogs(model.AuditLogFilter{UserId: 1}, 0, 10, 1)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 3, total)
|
||||
verifyAuditRoleStorage(t)
|
||||
verifyAuditJSONStorage(t)
|
||||
require.NoError(t, authz.Init(model.DB))
|
||||
assert.False(t, authz.Can(1, common.RoleAdminUser, authz.AuditRead))
|
||||
require.NoError(t, model.DB.Transaction(func(tx *gorm.DB) error {
|
||||
return authz.SetUserPermissionsInTx(tx, 1, authz.PermissionsMap{authz.ResourceAudit: {authz.ActionRead: true}})
|
||||
}))
|
||||
require.NoError(t, authz.ReloadPolicy())
|
||||
assert.True(t, authz.Can(1, common.RoleAdminUser, authz.AuditRead))
|
||||
require.NoError(t, authz.Init(model.DB))
|
||||
require.NoError(t, authz.Init(model.DB))
|
||||
assert.True(t, authz.Can(1, common.RoleAdminUser, authz.AuditRead))
|
||||
require.NoError(t, model.DB.Transaction(func(tx *gorm.DB) error {
|
||||
return authz.SetUserPermissionsInTx(tx, 1, authz.PermissionsMap{authz.ResourceAudit: {authz.ActionRead: false}})
|
||||
}))
|
||||
require.NoError(t, authz.ReloadPolicy())
|
||||
assert.False(t, authz.Can(1, common.RoleAdminUser, authz.AuditRead))
|
||||
assert.True(t, authz.Can(1, common.RoleRootUser, authz.AuditRead))
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIndependentAuditLogStores(t *testing.T) {
|
||||
_, _ = setupAccessTokenAudit(t)
|
||||
previousMaster := common.IsMasterNode
|
||||
common.IsMasterNode = true
|
||||
t.Cleanup(func() { common.IsMasterNode = previousMaster })
|
||||
for _, tc := range []struct{ kind, env string }{{"mysql", "AUDIT_MYSQL_DSN"}, {"postgres", "AUDIT_POSTGRES_DSN"}, {"clickhouse", "AUDIT_CLICKHOUSE_DSN"}} {
|
||||
for _, upgrade := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("%s/upgrade=%v", tc.kind, upgrade), func(t *testing.T) {
|
||||
dsn := os.Getenv(tc.env)
|
||||
if dsn == "" {
|
||||
t.Skip(tc.env + " is not configured")
|
||||
}
|
||||
logDB, isolatedDSN := newAuditTestDatabase(t, tc.kind, dsn)
|
||||
if upgrade {
|
||||
if tc.kind == "clickhouse" {
|
||||
require.NoError(t, logDB.Exec(releasedClickHouseLogSchema).Error)
|
||||
} else {
|
||||
require.NoError(t, logDB.AutoMigrate(&releasedAuditLog{}))
|
||||
}
|
||||
require.NoError(t, logDB.Create(&releasedAuditLog{UserId: 1, Username: "legacy", CreatedAt: time.Now().Unix(), Type: model.LogTypeLogin, Content: "retained historical login", RequestId: "legacy-split-request"}).Error)
|
||||
}
|
||||
t.Setenv("LOG_SQL_DSN", isolatedDSN)
|
||||
t.Setenv("LOG_SQL_CLICKHOUSE_TTL_DAYS", "7")
|
||||
require.NoError(t, model.InitLogDB())
|
||||
require.NoError(t, model.InitLogDB())
|
||||
if upgrade {
|
||||
var old model.Log
|
||||
require.NoError(t, model.LOG_DB.Where("request_id = ?", "legacy-split-request").Take(&old).Error)
|
||||
assert.Equal(t, "retained historical login", old.Content)
|
||||
}
|
||||
require.NoError(t, model.UpdateUserAccessToken(1, "independent-pat"))
|
||||
model.RecordAuditLog(nil, model.AuditLog{ActorRole: common.RoleAdminUser, UserId: 1, Username: "independent", Category: model.AuditCategoryAccessToken, TokenRef: model.AccessTokenFingerprint("independent-pat"), Ip: "192.0.2.8", Success: false, Status: 403})
|
||||
entries, total, err := model.GetAuditLogs(model.AuditLogFilter{UserId: 1}, 0, 20, common.RoleAdminUser)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 1, total)
|
||||
require.Len(t, entries, 1)
|
||||
assert.False(t, entries[0].Success)
|
||||
status, err := model.GetUserAccessTokenStatus(1)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, status.LastUsedAt)
|
||||
assert.Equal(t, "192.0.2.8", status.LastUsedIp)
|
||||
model.RecordLog(1, model.LogTypeTopup, "independent business")
|
||||
_, err = model.DeleteOldLogBatch(context.Background(), time.Now().Unix()+1, 100)
|
||||
require.NoError(t, err)
|
||||
_, total, err = model.GetAuditLogs(model.AuditLogFilter{UserId: 1}, 0, 20, 1)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 1, total)
|
||||
var mainCount int64
|
||||
require.NoError(t, model.DB.Model(&model.AuditLog{}).Count(&mainCount).Error)
|
||||
assert.Zero(t, mainCount)
|
||||
verifyAuditRoleStorage(t)
|
||||
verifyAuditJSONStorage(t)
|
||||
if tc.kind == "clickhouse" {
|
||||
var create string
|
||||
require.NoError(t, model.LOG_DB.Raw("SHOW CREATE TABLE audit_logs").Scan(&create).Error)
|
||||
assert.NotContains(t, strings.ToUpper(create), "TTL")
|
||||
require.NoError(t, model.LOG_DB.Raw("SHOW CREATE TABLE logs").Scan(&create).Error)
|
||||
assert.Contains(t, strings.ToUpper(create), "TTL")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ClickHouse logs schema from v1.0.0-rc.33.
|
||||
const releasedClickHouseLogSchema = `
|
||||
CREATE TABLE IF NOT EXISTS logs (
|
||||
id Int64 DEFAULT 0,
|
||||
user_id Int32 DEFAULT 0,
|
||||
created_at Int64 DEFAULT 0,
|
||||
type Int32 DEFAULT 0,
|
||||
content String DEFAULT '',
|
||||
username String DEFAULT '',
|
||||
token_name String DEFAULT '',
|
||||
model_name String DEFAULT '',
|
||||
quota Int32 DEFAULT 0,
|
||||
prompt_tokens Int32 DEFAULT 0,
|
||||
completion_tokens Int32 DEFAULT 0,
|
||||
use_time Int32 DEFAULT 0,
|
||||
is_stream UInt8 DEFAULT 0,
|
||||
channel_id Int32 DEFAULT 0,
|
||||
token_id Int32 DEFAULT 0,
|
||||
` + "`group`" + ` String DEFAULT '',
|
||||
ip String DEFAULT '',
|
||||
request_id String DEFAULT '',
|
||||
upstream_request_id String DEFAULT '',
|
||||
other String DEFAULT ''
|
||||
)
|
||||
ENGINE = MergeTree()
|
||||
PARTITION BY toYYYYMM(toDateTime(created_at))
|
||||
ORDER BY (created_at, request_id)`
|
||||
+15
-8
@@ -26,6 +26,13 @@ var auditContentTemplates = map[string]string{
|
||||
"user.binding_clear": "Cleared ${bindingType} binding for user ${username}",
|
||||
"user.2fa_disable": "Force-disabled two-factor authentication for the user",
|
||||
"user.passkey_register": "Registered a passkey",
|
||||
"access_token.generate": "Generated a system access token",
|
||||
"access_token.revoke": "Revoked the system access token",
|
||||
"user.2fa_setup": "Started two-factor authentication setup",
|
||||
"user.2fa_enable": "Enabled two-factor authentication",
|
||||
"user.2fa_disable_self": "Disabled two-factor authentication",
|
||||
"user.2fa_backup_codes": "Regenerated two-factor backup codes",
|
||||
"user.security_verify": "Completed security verification",
|
||||
"user.passkey_delete": "Deleted a passkey",
|
||||
"user.reset_passkey": "Reset the user passkey",
|
||||
"option.update": "Updated system setting ${key}",
|
||||
@@ -66,12 +73,12 @@ func auditContentEN(action string, params map[string]interface{}) string {
|
||||
}
|
||||
|
||||
// auditOperatorInfo 从上下文构建操作者身份信息(管理员 id/用户名/角色)。
|
||||
func auditOperatorInfo(c *gin.Context) map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"admin_id": c.GetInt("id"),
|
||||
"admin_username": c.GetString("username"),
|
||||
"admin_role": c.GetInt("role"),
|
||||
"auth_method": auditAuthMethod(c),
|
||||
func auditOperatorInfo(c *gin.Context) *model.AuditAdminInfo {
|
||||
return &model.AuditAdminInfo{
|
||||
AdminID: c.GetInt("id"),
|
||||
AdminUsername: c.GetString("username"),
|
||||
AdminRole: c.GetInt("role"),
|
||||
AuthMethod: auditAuthMethod(c),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,12 +111,12 @@ func recordManageAuditFor(c *gin.Context, targetUserId int, action string, param
|
||||
if _, ok := params["target_user_id"]; !ok && targetUserId > 0 && targetUserId != operatorUserId {
|
||||
params["target_user_id"] = targetUserId
|
||||
}
|
||||
model.RecordOperationAuditLog(operatorUserId, auditContentEN(action, params), c.ClientIP(), action, params, auditOperatorInfo(c), nil)
|
||||
model.RecordOperationAuditLog(operatorUserId, c.GetInt("role"), auditContentEN(action, params), c.ClientIP(), action, params, auditOperatorInfo(c), nil, c)
|
||||
markAuditLogged(c)
|
||||
}
|
||||
|
||||
// recordUserSecurityAudit 记录普通用户自己的安全敏感操作(如 passkey 绑定/解绑)。
|
||||
// 这类日志没有管理员操作者,不写 admin_info;同时不依赖 AdminAuth/RootAuth 的兜底。
|
||||
func recordUserSecurityAudit(c *gin.Context, userId int, action string, params map[string]interface{}) {
|
||||
model.RecordOperationAuditLog(userId, auditContentEN(action, params), c.ClientIP(), action, params, nil, nil)
|
||||
model.RecordOperationAuditLog(userId, c.GetInt("role"), auditContentEN(action, params), c.ClientIP(), action, params, nil, nil, c)
|
||||
}
|
||||
@@ -113,7 +113,7 @@ func setupBillingAliasOptionDB(t *testing.T) {
|
||||
previousRedis := common.RedisEnabled
|
||||
database, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, database.AutoMigrate(&model.Channel{}, &model.Option{}, &model.Log{}, &model.User{}))
|
||||
require.NoError(t, database.AutoMigrate(&model.Channel{}, &model.Option{}, &model.Log{}, &model.AuditLog{}, &model.User{}))
|
||||
model.DB = database
|
||||
model.LOG_DB = database
|
||||
common.SetMainDatabaseType(common.DatabaseTypeSQLite)
|
||||
|
||||
@@ -31,7 +31,7 @@ func setupTaskPluginBindChannelTest(t *testing.T) {
|
||||
sqlDB, err := database.DB()
|
||||
require.NoError(t, err)
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
require.NoError(t, database.AutoMigrate(&model.Channel{}, &model.Ability{}, &model.CasbinRule{}, &model.AuthzRole{}, &model.Log{}, &model.User{}))
|
||||
require.NoError(t, database.AutoMigrate(&model.Channel{}, &model.Ability{}, &model.CasbinRule{}, &model.AuthzRole{}, &model.Log{}, &model.AuditLog{}, &model.User{}))
|
||||
model.DB = database
|
||||
model.LOG_DB = database
|
||||
require.NoError(t, authz.Init(database))
|
||||
|
||||
@@ -166,7 +166,7 @@ func TestCopyChannelRejectsInvalidLegacyProxySettings(t *testing.T) {
|
||||
|
||||
func TestDeleteChannelResetsProxyCacheWhenPreReadFails(t *testing.T) {
|
||||
db := setupModelListControllerTestDB(t)
|
||||
require.NoError(t, db.AutoMigrate(&model.Log{}))
|
||||
require.NoError(t, db.AutoMigrate(&model.Log{}, &model.AuditLog{}))
|
||||
service.ResetProxyClientCache()
|
||||
t.Cleanup(service.ResetProxyClientCache)
|
||||
|
||||
@@ -189,7 +189,7 @@ func TestDeleteChannelResetsProxyCacheWhenPreReadFails(t *testing.T) {
|
||||
|
||||
func TestDeleteChannelBatchReportsAndAuditsActualDeletedCount(t *testing.T) {
|
||||
db := setupModelListControllerTestDB(t)
|
||||
require.NoError(t, db.AutoMigrate(&model.Log{}))
|
||||
require.NoError(t, db.AutoMigrate(&model.Log{}, &model.AuditLog{}))
|
||||
channel := &model.Channel{Name: "existing", Key: "test-key"}
|
||||
require.NoError(t, db.Create(channel).Error)
|
||||
|
||||
@@ -210,14 +210,16 @@ func TestDeleteChannelBatchReportsAndAuditsActualDeletedCount(t *testing.T) {
|
||||
assert.True(t, response.Success)
|
||||
assert.Equal(t, int64(1), response.Data)
|
||||
|
||||
var auditLog model.Log
|
||||
var auditLog model.AuditLog
|
||||
require.NoError(t, db.Order("id desc").First(&auditLog).Error)
|
||||
var auditData struct {
|
||||
Operation struct {
|
||||
Params map[string]any `json:"params"`
|
||||
} `json:"op"`
|
||||
}
|
||||
require.NoError(t, common.UnmarshalJsonStr(auditLog.Other, &auditData))
|
||||
encodedAudit, err := common.Marshal(auditLog.Other)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, common.Unmarshal(encodedAudit, &auditData))
|
||||
assert.Equal(t, float64(1), auditData.Operation.Params["count"])
|
||||
}
|
||||
|
||||
|
||||
@@ -535,7 +535,7 @@ func TestCheckUpdatePasswordRejectsHistoricalEmptyPassword(t *testing.T) {
|
||||
|
||||
func TestSetupLoginDoesNotTouchPasswordWhenPasswordFieldOmitted(t *testing.T) {
|
||||
db := setupModelListControllerTestDB(t)
|
||||
require.NoError(t, db.AutoMigrate(&model.Log{}, &model.UserSession{}))
|
||||
require.NoError(t, db.AutoMigrate(&model.Log{}, &model.AuditLog{}, &model.UserSession{}))
|
||||
|
||||
hashedPassword, err := common.Password2Hash("CurrentPassword123")
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -486,6 +486,11 @@ func RelayNotImplemented(c *gin.Context) {
|
||||
}
|
||||
|
||||
func RelayNotFound(c *gin.Context) {
|
||||
// The web fallback may already have applied static-asset cache headers.
|
||||
// A missing API or asset can appear after an upgrade; never cache its 404.
|
||||
c.Header("Cache-Control", "no-store, no-cache, must-revalidate, private, max-age=0")
|
||||
c.Header("Pragma", "no-cache")
|
||||
c.Header("Expires", "0")
|
||||
err := types.OpenAIError{
|
||||
Message: fmt.Sprintf("Invalid URL (%s %s)", c.Request.Method, c.Request.URL.Path),
|
||||
Type: "invalid_request_error",
|
||||
|
||||
@@ -65,7 +65,7 @@ func UniversalVerify(c *gin.Context) {
|
||||
common.ApiError(c, err)
|
||||
return
|
||||
}
|
||||
model.RecordLog(identity.UserID, model.LogTypeSystem, "通用安全验证成功 (验证方式: 2FA)")
|
||||
recordUserSecurityAudit(c, identity.UserID, "user.security_verify", map[string]interface{}{"method": "2fa"})
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "验证成功",
|
||||
|
||||
@@ -407,13 +407,13 @@ func resolveAdvanceResetTime(value *bool) bool {
|
||||
return *value
|
||||
}
|
||||
|
||||
func recordSubscriptionResetUserLogs(result *model.SubscriptionResetResult, adminInfo map[string]interface{}) {
|
||||
func recordSubscriptionResetUserLogs(c *gin.Context, result *model.SubscriptionResetResult, adminInfo *model.AuditAdminInfo) {
|
||||
if result == nil || result.ResetCount == 0 {
|
||||
return
|
||||
}
|
||||
content := fmt.Sprintf("管理员重置订阅套餐 %s(ID: %d)额度", result.PlanTitle, result.PlanId)
|
||||
for _, userId := range result.AffectedUserIds {
|
||||
model.RecordLogWithAdminInfo(userId, model.LogTypeManage, content, adminInfo)
|
||||
model.RecordLogWithAdminInfo(userId, model.LogTypeManage, content, adminInfo, c)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -466,7 +466,7 @@ func AdminResetUserSubscriptionsByPlan(c *gin.Context) {
|
||||
common.ApiError(c, err)
|
||||
return
|
||||
}
|
||||
recordSubscriptionResetUserLogs(result, auditOperatorInfo(c))
|
||||
recordSubscriptionResetUserLogs(c, result, auditOperatorInfo(c))
|
||||
recordManageAuditFor(c, userId, "subscription.user_plan_reset", map[string]interface{}{
|
||||
"target_user_id": userId,
|
||||
"plan_id": result.PlanId,
|
||||
@@ -495,7 +495,7 @@ func AdminResetPlanSubscriptions(c *gin.Context) {
|
||||
common.ApiError(c, err)
|
||||
return
|
||||
}
|
||||
recordSubscriptionResetUserLogs(result, auditOperatorInfo(c))
|
||||
recordSubscriptionResetUserLogs(c, result, auditOperatorInfo(c))
|
||||
common.SysLog(fmt.Sprintf("admin reset subscription plan %d quota: reset_count=%d user_count=%d advance_reset_time=%t",
|
||||
result.PlanId, result.ResetCount, result.UserCount, result.AdvanceResetTime))
|
||||
recordManageAudit(c, "subscription.plan_reset", map[string]interface{}{
|
||||
|
||||
+4
-4
@@ -117,7 +117,7 @@ func Setup2FA(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 记录操作日志
|
||||
model.RecordLog(userId, model.LogTypeSystem, "开始设置两步验证")
|
||||
recordUserSecurityAudit(c, userId, "user.2fa_setup", nil)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
@@ -199,7 +199,7 @@ func Enable2FA(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 记录操作日志
|
||||
model.RecordLog(userId, model.LogTypeSystem, "成功启用两步验证")
|
||||
recordUserSecurityAudit(c, userId, "user.2fa_enable", nil)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
@@ -282,7 +282,7 @@ func Disable2FA(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 记录操作日志
|
||||
model.RecordLog(userId, model.LogTypeSystem, "禁用两步验证")
|
||||
recordUserSecurityAudit(c, userId, "user.2fa_disable_self", nil)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
@@ -412,7 +412,7 @@ func RegenerateBackupCodes(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 记录操作日志
|
||||
model.RecordLog(userId, model.LogTypeSystem, "重新生成两步验证备用码")
|
||||
recordUserSecurityAudit(c, userId, "user.2fa_backup_codes", nil)
|
||||
|
||||
data := authRotationData(bundle)
|
||||
data["backup_codes"] = backupCodes
|
||||
|
||||
+7
-5
@@ -169,14 +169,14 @@ func loginMethodFromContext(c *gin.Context) string {
|
||||
func recordLoginAudit(user *model.User, c *gin.Context) {
|
||||
method := loginMethodFromContext(c)
|
||||
ip := c.ClientIP()
|
||||
extra := map[string]interface{}{
|
||||
"login_method": method,
|
||||
"user_agent": c.Request.UserAgent(),
|
||||
extra := model.AuditOther{
|
||||
LoginMethod: method,
|
||||
UserAgent: c.Request.UserAgent(),
|
||||
}
|
||||
content := fmt.Sprintf("Logged in successfully via %s", method)
|
||||
model.RecordLoginLog(user.Id, user.Username, content, ip, "login", map[string]interface{}{
|
||||
model.RecordLoginLog(user.Id, user.Role, user.Username, content, ip, "login", map[string]interface{}{
|
||||
"method": method,
|
||||
}, extra)
|
||||
}, extra, c)
|
||||
}
|
||||
|
||||
// setupLogin creates a server-controlled login Session and returns the shared
|
||||
@@ -447,6 +447,8 @@ func GenerateAccessToken(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
recordUserSecurityAudit(c, id, "access_token.generate", map[string]interface{}{"token_ref": model.AccessTokenFingerprint(key)})
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "",
|
||||
|
||||
@@ -32,7 +32,7 @@ func setupManageUserTestDB(t *testing.T) *gorm.DB {
|
||||
require.NoError(t, err)
|
||||
model.DB, model.LOG_DB = db, db
|
||||
require.NoError(t, db.AutoMigrate(
|
||||
&model.User{}, &model.UserSession{}, &model.Log{}, &model.CasbinRule{}, &model.AuthzRole{},
|
||||
&model.User{}, &model.UserSession{}, &model.Log{}, &model.AuditLog{}, &model.CasbinRule{}, &model.AuthzRole{},
|
||||
))
|
||||
|
||||
t.Cleanup(func() {
|
||||
|
||||
@@ -6,7 +6,7 @@ go 1.25.1
|
||||
require (
|
||||
github.com/Calcium-Ion/go-epay v0.0.4
|
||||
github.com/abema/go-mp4 v1.4.1
|
||||
github.com/andybalholm/brotli v1.1.1
|
||||
github.com/andybalholm/brotli v1.2.0
|
||||
github.com/anknown/ahocorasick v0.0.0-20190904063843-d75dbd5169c0
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.5
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.10
|
||||
@@ -31,7 +31,7 @@ require (
|
||||
github.com/jfreymuth/oggvorbis v1.0.5
|
||||
github.com/jinzhu/copier v0.4.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
github.com/klauspost/compress v1.18.0
|
||||
github.com/klauspost/compress v1.18.3
|
||||
github.com/mewkiz/flac v1.0.13
|
||||
github.com/nicksnyder/go-i18n/v2 v2.6.1
|
||||
github.com/pkg/errors v0.9.1
|
||||
@@ -67,7 +67,7 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/ClickHouse/ch-go v0.65.0 // indirect
|
||||
github.com/ClickHouse/ch-go v0.71.0 // indirect
|
||||
github.com/bmatcuk/doublestar/v4 v4.6.1 // indirect
|
||||
github.com/casbin/govaluate v1.10.0 // indirect
|
||||
github.com/dlclark/regexp2/v2 v2.2.2 // indirect
|
||||
@@ -75,14 +75,15 @@ require (
|
||||
github.com/go-faster/errors v0.7.1 // indirect
|
||||
github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e // indirect
|
||||
github.com/hashicorp/go-version v1.7.0 // indirect
|
||||
github.com/paulmach/orb v0.11.1 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.22 // indirect
|
||||
github.com/hashicorp/go-version v1.8.0 // indirect
|
||||
github.com/paulmach/orb v0.12.0 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.25 // indirect
|
||||
github.com/rogpeppe/go-internal v1.13.1 // indirect
|
||||
github.com/segmentio/asm v1.2.0 // indirect
|
||||
github.com/segmentio/asm v1.2.1 // indirect
|
||||
github.com/yuin/gopher-lua v1.1.1 // indirect
|
||||
go.opentelemetry.io/otel v1.34.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.34.0 // indirect
|
||||
go.opentelemetry.io/otel v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.41.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -157,7 +158,7 @@ require (
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||
github.com/x448/float16 v0.8.4 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.3 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||
golang.org/x/arch v0.21.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect
|
||||
google.golang.org/protobuf v1.36.5 // indirect
|
||||
@@ -168,7 +169,7 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/ClickHouse/clickhouse-go/v2 v2.32.0
|
||||
github.com/ClickHouse/clickhouse-go/v2 v2.46.0
|
||||
github.com/QuantumNous/new-api/relaykit v0.0.0
|
||||
)
|
||||
|
||||
|
||||
@@ -634,12 +634,12 @@ github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym
|
||||
github.com/Calcium-Ion/go-epay v0.0.4 h1:C96M7WfRLadcIVscWzwLiYs8etI1wrDmtFMuK2zP22A=
|
||||
github.com/Calcium-Ion/go-epay v0.0.4/go.mod h1:cxo/ZOg8ClvE3VAnCmEzbuyAZINSq7kFEN9oHj5WQ2U=
|
||||
github.com/ClickHouse/ch-go v0.58.2/go.mod h1:Ap/0bEmiLa14gYjCiRkYGbXvbe8vwdrfTYWhsuQ99aw=
|
||||
github.com/ClickHouse/ch-go v0.65.0 h1:vZAXfTQliuNNefqkPDewX3kgRxN6Q4vUENnnY+ynTRY=
|
||||
github.com/ClickHouse/ch-go v0.65.0/go.mod h1:tCM0XEH5oWngoi9Iu/8+tjPBo04I/FxNIffpdjtwx3k=
|
||||
github.com/ClickHouse/ch-go v0.71.0 h1:bUdZ/EZj/LcVHsMqaRUP2holqygrPWQKeMjc6nZoyRM=
|
||||
github.com/ClickHouse/ch-go v0.71.0/go.mod h1:NwbNc+7jaqfY58dmdDUbG4Jl22vThgx1cYjBw0vtgXw=
|
||||
github.com/ClickHouse/clickhouse-go v1.5.4/go.mod h1:EaI/sW7Azgz9UATzd5ZdZHRUhHgv5+JMS9NSr2smCJI=
|
||||
github.com/ClickHouse/clickhouse-go/v2 v2.15.0/go.mod h1:kXt1SRq0PIRa6aKZD7TnFnY9PQKmc2b13sHtOYcK6cQ=
|
||||
github.com/ClickHouse/clickhouse-go/v2 v2.32.0 h1:zVWJUmUGdtCApM/vRfQhruGXIm1M643bk68B3IYbR1I=
|
||||
github.com/ClickHouse/clickhouse-go/v2 v2.32.0/go.mod h1:rGFIgeNbJVggBp2C+0FXOdfjsMlpsKx7FUYnHHyy2KE=
|
||||
github.com/ClickHouse/clickhouse-go/v2 v2.46.0 h1:s3eRy+hYmu5uzotB6ZhDofgHu8kDgGN/fpmjxRkqSpk=
|
||||
github.com/ClickHouse/clickhouse-go/v2 v2.46.0/go.mod h1:giJfUVlMkcfUEPVfRpt51zZaGEx9i17gCos8gBl392c=
|
||||
github.com/DmitriyVTitov/size v1.5.0 h1:/PzqxYrOyOUX1BXj6J9OuVRVGe+66VL4D9FlUaW515g=
|
||||
github.com/DmitriyVTitov/size v1.5.0/go.mod h1:le6rNI4CoLQV1b9gzp1+3d7hMAD/uu2QcJ+aYbNgiU0=
|
||||
github.com/JohnCGriffin/overflow v0.0.0-20211019200055-46fa312c352c/go.mod h1:X0CRv0ky0k6m906ixxpzmDRLvX58TFUKS2eePweuyxk=
|
||||
@@ -704,8 +704,8 @@ github.com/alicebob/miniredis/v2 v2.38.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj
|
||||
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8=
|
||||
github.com/andybalholm/brotli v1.0.4/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
|
||||
github.com/andybalholm/brotli v1.0.6/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
|
||||
github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
|
||||
github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
|
||||
github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ=
|
||||
github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/anknown/ahocorasick v0.0.0-20190904063843-d75dbd5169c0 h1:onfun1RA+KcxaMk1lfrRnwCd1UUuOjJM/lri5eM1qMs=
|
||||
github.com/anknown/ahocorasick v0.0.0-20190904063843-d75dbd5169c0/go.mod h1:4yg+jNTYlDEzBjhGS96v+zjyA3lfXlFd5CiTLIkPBLI=
|
||||
github.com/anknown/darts v0.0.0-20151216065714-83ff685239e6 h1:HblK3eJHq54yET63qPCTJnks3loDse5xRmmqHgHzwoI=
|
||||
@@ -1411,8 +1411,8 @@ github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdv
|
||||
github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
|
||||
github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
|
||||
github.com/hashicorp/go-version v1.6.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
|
||||
github.com/hashicorp/go-version v1.7.0 h1:5tqGy27NaOTB8yJKUZELlFAS/LTKJkrmONwQKeRZfjY=
|
||||
github.com/hashicorp/go-version v1.7.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
|
||||
github.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=
|
||||
github.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
|
||||
github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90=
|
||||
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
|
||||
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
|
||||
@@ -1501,8 +1501,8 @@ github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47e
|
||||
github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU=
|
||||
github.com/klauspost/compress v1.16.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
|
||||
github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
|
||||
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
|
||||
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
|
||||
github.com/klauspost/compress v1.18.3 h1:9PJRvfbmTabkOX8moIpXPbMMbYN60bWImDDU7L+/6zw=
|
||||
github.com/klauspost/compress v1.18.3/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
|
||||
github.com/klauspost/cpuid/v2 v2.0.4/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
@@ -1734,8 +1734,8 @@ github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FI
|
||||
github.com/pascaldekloe/name v1.0.0/go.mod h1:Z//MfYJnH4jVpQ9wkclwu2I2MkHmXTlT9wR5UZScttM=
|
||||
github.com/pascaldekloe/name v1.0.1/go.mod h1:Z//MfYJnH4jVpQ9wkclwu2I2MkHmXTlT9wR5UZScttM=
|
||||
github.com/paulmach/orb v0.10.0/go.mod h1:5mULz1xQfs3bmQm63QEJA6lNGujuRafwA5S/EnuLaLU=
|
||||
github.com/paulmach/orb v0.11.1 h1:3koVegMC4X/WeiXYz9iswopaTwMem53NzTJuTF20JzU=
|
||||
github.com/paulmach/orb v0.11.1/go.mod h1:5mULz1xQfs3bmQm63QEJA6lNGujuRafwA5S/EnuLaLU=
|
||||
github.com/paulmach/orb v0.12.0 h1:z+zOwjmG3MyEEqzv92UN49Lg1JFYx0L9GpGKNVDKk1s=
|
||||
github.com/paulmach/orb v0.12.0/go.mod h1:5mULz1xQfs3bmQm63QEJA6lNGujuRafwA5S/EnuLaLU=
|
||||
github.com/paulmach/protoscan v0.2.1/go.mod h1:SpcSwydNLrxUGSDvXvO0P7g7AuhJ7lcKfDlhJCDw2gY=
|
||||
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
|
||||
github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc=
|
||||
@@ -1753,8 +1753,8 @@ github.com/phpdave11/gofpdi v1.0.13/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk
|
||||
github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY=
|
||||
github.com/pierrec/lz4/v4 v4.1.15/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
|
||||
github.com/pierrec/lz4/v4 v4.1.18/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
|
||||
github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU=
|
||||
github.com/pierrec/lz4/v4 v4.1.22/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
|
||||
github.com/pierrec/lz4/v4 v4.1.25 h1:kocOqRffaIbU5djlIBr7Wh+cx82C0vtFb0fOurZHqD0=
|
||||
github.com/pierrec/lz4/v4 v4.1.25/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
|
||||
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
|
||||
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/errors v0.8.1-0.20171018195549-f15c970de5b7/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
@@ -1860,8 +1860,9 @@ github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg
|
||||
github.com/seccomp/libseccomp-golang v0.9.1/go.mod h1:GbW5+tmTXfcxTToHLXlScSlAvWlF4P2Ca7zGrPiEpWo=
|
||||
github.com/seccomp/libseccomp-golang v0.9.2-0.20210429002308-3879420cc921/go.mod h1:JA8cRccbGaA1s33RQf7Y1+q9gHmZX1yB/z9WDN1C6fg=
|
||||
github.com/seccomp/libseccomp-golang v0.9.2-0.20220502022130-f33da4d89646/go.mod h1:JA8cRccbGaA1s33RQf7Y1+q9gHmZX1yB/z9WDN1C6fg=
|
||||
github.com/segmentio/asm v1.2.0 h1:9BQrFxC+YOHJlTlHGkTrFWf59nbL3XnCoFLTwDCI7ys=
|
||||
github.com/segmentio/asm v1.2.0/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
|
||||
github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0=
|
||||
github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
|
||||
github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
|
||||
github.com/shirou/gopsutil v2.19.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
|
||||
github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI=
|
||||
@@ -2038,8 +2039,9 @@ github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
|
||||
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
|
||||
github.com/yusufpapurcu/wmi v1.2.3 h1:E1ctvB7uKFMOJw3fdOW32DwGE9I7t++CRUEMKvFoFiw=
|
||||
github.com/yusufpapurcu/wmi v1.2.3/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
|
||||
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
|
||||
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
|
||||
github.com/yvasiyarov/go-metrics v0.0.0-20140926110328-57bccd1ccd43/go.mod h1:aX5oPXxHm3bOH+xeAttToC8pqch2ScQN/JoXYupl6xs=
|
||||
github.com/yvasiyarov/gorelic v0.0.0-20141212073537-a9bba5b9ab50/go.mod h1:NUSPSUX/bi6SeDMUh6brw0nXpxHnc96TguQh0+r/ssA=
|
||||
github.com/yvasiyarov/newrelic_platform_go v0.0.0-20140908184405-b21fdbd4370f/go.mod h1:GlGEuHIJweS1mbCqG+7vt2nvWLzLLnRHbXz5JKd/Qbg=
|
||||
@@ -2094,8 +2096,8 @@ go.opentelemetry.io/otel v1.10.0/go.mod h1:NbvWjCthWHKBEUMpf0/v8ZRZlni86PpGFEMA9
|
||||
go.opentelemetry.io/otel v1.14.0/go.mod h1:o4buv+dJzx8rohcUeRmWUZhqupFvzWis188WlggnNeU=
|
||||
go.opentelemetry.io/otel v1.16.0/go.mod h1:vl0h9NUa1D5s1nv3A5vZOYWn8av4K8Ml6JDeHrT/bx4=
|
||||
go.opentelemetry.io/otel v1.19.0/go.mod h1:i0QyjOq3UPoTzff0PJB2N66fb4S0+rSbSB15/oyH9fY=
|
||||
go.opentelemetry.io/otel v1.34.0 h1:zRLXxLCgL1WyKsPVrgbSdMN4c0FMkDAskSTQP+0hdUY=
|
||||
go.opentelemetry.io/otel v1.34.0/go.mod h1:OWFPOQ+h4G8xpyjgqo4SxJYdDQ/qmRH+wivy7zzx9oI=
|
||||
go.opentelemetry.io/otel v1.41.0 h1:YlEwVsGAlCvczDILpUXpIpPSL/VPugt7zHThEMLce1c=
|
||||
go.opentelemetry.io/otel v1.41.0/go.mod h1:Yt4UwgEKeT05QbLwbyHXEwhnjxNO6D8L5PQP51/46dE=
|
||||
go.opentelemetry.io/otel/exporters/otlp v0.20.0/go.mod h1:YIieizyaN77rtLJra0buKiNBOm9XQfkPEKBeuhoMwAM=
|
||||
go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.3.0/go.mod h1:VpP4/RMn8bv8gNo9uK7/IMY4mtWLELsS+JIP0inH0h4=
|
||||
go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.7.0/go.mod h1:M1hVZHNxcbkAlcvrOMlpQ4YOO3Awf+4N2dxkZL3xm04=
|
||||
@@ -2138,8 +2140,8 @@ go.opentelemetry.io/otel/trace v1.10.0/go.mod h1:Sij3YYczqAdz+EhmGhE6TpTxUO5/F/A
|
||||
go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+gozhnZjy/rw9G8=
|
||||
go.opentelemetry.io/otel/trace v1.16.0/go.mod h1:Yt9vYq1SdNz3xdjZZK7wcXv1qv2pwLkqr2QVwea0ef0=
|
||||
go.opentelemetry.io/otel/trace v1.19.0/go.mod h1:mfaSyvGyEJEI0nyV2I4qhNQnbBOUUmYZpYojqMnX2vo=
|
||||
go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC8mh/k=
|
||||
go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE=
|
||||
go.opentelemetry.io/otel/trace v1.41.0 h1:Vbk2co6bhj8L59ZJ6/xFTskY+tGAbOnCtQGVVa9TIN0=
|
||||
go.opentelemetry.io/otel/trace v1.41.0/go.mod h1:U1NU4ULCoxeDKc09yCWdWe+3QoyweJcISEVa1RBzOis=
|
||||
go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI=
|
||||
go.opentelemetry.io/proto/otlp v0.9.0/go.mod h1:1vKfU9rv61e9EVGthD1zNvUbiwPcimSsOPU9brfSHJg=
|
||||
go.opentelemetry.io/proto/otlp v0.11.0/go.mod h1:QpEjXPrNQzrFDZgoTo49dgHR9RYRSrg3NAKnUGl9YpQ=
|
||||
|
||||
+66
-18
@@ -6,8 +6,8 @@ import (
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/constant"
|
||||
"github.com/QuantumNous/new-api/model"
|
||||
"github.com/QuantumNous/new-api/service"
|
||||
|
||||
"github.com/bytedance/gopkg/util/gopool"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -158,26 +158,22 @@ func finishAdminAudit(c *gin.Context, writer *auditResponseWriter) {
|
||||
// content 为英文兜底文本(供导出等非本地化消费者使用)。
|
||||
content := method + " " + route
|
||||
|
||||
adminInfo := map[string]interface{}{
|
||||
"admin_id": operatorId,
|
||||
"admin_username": operatorName,
|
||||
"admin_role": operatorRole,
|
||||
"auth_method": auditAuthMethod(c),
|
||||
adminInfo := &model.AuditAdminInfo{
|
||||
AdminID: operatorId,
|
||||
AdminUsername: operatorName,
|
||||
AdminRole: operatorRole,
|
||||
AuthMethod: auditAuthMethod(c),
|
||||
}
|
||||
auditInfo := map[string]interface{}{
|
||||
"method": method,
|
||||
"route": route,
|
||||
"path": c.Request.URL.Path,
|
||||
"status": status,
|
||||
"success": success,
|
||||
}
|
||||
if len(routeParams) > 0 {
|
||||
auditInfo["params"] = routeParams
|
||||
auditInfo := &model.AuditRequestInfo{
|
||||
Method: method,
|
||||
Route: route,
|
||||
Path: route,
|
||||
Status: status,
|
||||
Success: success,
|
||||
Params: routeParams,
|
||||
}
|
||||
|
||||
gopool.Go(func() {
|
||||
model.RecordOperationAuditLog(operatorId, content, ip, action, opParams, adminInfo, auditInfo)
|
||||
})
|
||||
model.RecordOperationAuditLog(operatorId, operatorRole, content, ip, action, opParams, adminInfo, auditInfo, c)
|
||||
}
|
||||
|
||||
func auditAuthMethod(c *gin.Context) string {
|
||||
@@ -204,3 +200,55 @@ func auditResponseSuccess(status int, body []byte) bool {
|
||||
}
|
||||
return status < 400
|
||||
}
|
||||
|
||||
const accessTokenAuditContextKey = "access_token_request_audit"
|
||||
|
||||
type accessTokenRequestAudit struct {
|
||||
entry model.AuditLog
|
||||
writer *auditResponseWriter
|
||||
}
|
||||
|
||||
// AccessTokenAudit also captures public reads and rejections before route-level
|
||||
// authentication (for example, rate limiting). It does not grant authentication.
|
||||
func AccessTokenAudit() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
raw, present := authorizationToken(c.GetHeader("Authorization"))
|
||||
if present {
|
||||
_, internal, _ := service.ParseDashboardAccessToken(raw)
|
||||
if !internal {
|
||||
user, err := model.ValidateAccessToken(raw)
|
||||
if err == nil && user != nil && user.Id > 0 {
|
||||
beginAccessTokenAudit(c, user, raw)
|
||||
defer finishAccessTokenAudit(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func beginAccessTokenAudit(c *gin.Context, user *model.User, token string) {
|
||||
if _, exists := c.Get(accessTokenAuditContextKey); exists {
|
||||
return
|
||||
}
|
||||
writer := &auditResponseWriter{ResponseWriter: c.Writer, body: bytes.NewBuffer(nil), maxSize: 64 * 1024}
|
||||
c.Writer = writer
|
||||
c.Set(accessTokenAuditContextKey, &accessTokenRequestAudit{
|
||||
entry: model.AuditLog{UserId: user.Id, Username: user.Username, ActorRole: user.Role, Category: model.AuditCategoryAccessToken, AuthMethod: "access_token", TokenRef: model.AccessTokenFingerprint(token), CreatedAt: common.GetTimestamp(), EventId: common.NewRequestId()},
|
||||
writer: writer,
|
||||
})
|
||||
}
|
||||
|
||||
func finishAccessTokenAudit(c *gin.Context) {
|
||||
value, exists := c.Get(accessTokenAuditContextKey)
|
||||
if !exists {
|
||||
return
|
||||
}
|
||||
audit, ok := value.(*accessTokenRequestAudit)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
audit.entry.Status = audit.writer.Status()
|
||||
audit.entry.Success = auditResponseSuccess(audit.entry.Status, audit.writer.body.Bytes())
|
||||
model.RecordAuditLog(c, audit.entry)
|
||||
}
|
||||
@@ -45,6 +45,9 @@ func validUserInfo(username string, role int) bool {
|
||||
}
|
||||
|
||||
func authHelper(c *gin.Context, minRole int) {
|
||||
if _, started := c.Get(accessTokenAuditContextKey); !started {
|
||||
defer finishAccessTokenAudit(c)
|
||||
}
|
||||
user, identity, useAccessToken, err := authenticateDashboardRequest(c)
|
||||
if err != nil {
|
||||
writeDashboardAuthError(c, err)
|
||||
@@ -79,6 +82,9 @@ func authHelper(c *gin.Context, minRole int) {
|
||||
|
||||
func TryUserAuth() func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
if _, started := c.Get(accessTokenAuditContextKey); !started {
|
||||
defer finishAccessTokenAudit(c)
|
||||
}
|
||||
user, identity, credentialKind, err := classifyDashboardCredential(c)
|
||||
if err != nil {
|
||||
writeDashboardAuthError(c, err)
|
||||
@@ -172,6 +178,7 @@ func classifyDashboardCredential(c *gin.Context) (*model.UserBase, service.AuthI
|
||||
if patUser == nil || patUser.Id <= 0 {
|
||||
return nil, service.AuthIdentity{}, dashboardCredentialUnmatched, nil
|
||||
}
|
||||
beginAccessTokenAudit(c, patUser, raw)
|
||||
user, err := model.GetUserCache(patUser.Id)
|
||||
if err != nil {
|
||||
return nil, service.AuthIdentity{}, dashboardCredentialPAT, err
|
||||
|
||||
@@ -24,18 +24,21 @@ import (
|
||||
func setupDashboardAuthMiddlewareTest(t *testing.T) {
|
||||
t.Helper()
|
||||
previousDB := model.DB
|
||||
previousLogDB := model.LOG_DB
|
||||
previousType := common.MainDatabaseType()
|
||||
previousRedis := common.RedisEnabled
|
||||
previousSecret := common.SessionSecret
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&model.User{}, &model.UserSession{}))
|
||||
require.NoError(t, db.AutoMigrate(&model.User{}, &model.UserSession{}, &model.AuditLog{}))
|
||||
model.DB = db
|
||||
model.LOG_DB = db
|
||||
common.SetMainDatabaseType(common.DatabaseTypeSQLite)
|
||||
common.RedisEnabled = false
|
||||
common.SessionSecret = "middleware-auth-test-secret"
|
||||
t.Cleanup(func() {
|
||||
model.DB = previousDB
|
||||
model.LOG_DB = previousLogDB
|
||||
common.SetMainDatabaseType(previousType)
|
||||
common.RedisEnabled = previousRedis
|
||||
common.SessionSecret = previousSecret
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/ClickHouse/clickhouse-go/v2"
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/logger"
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
AuditCategoryLogin = "login"
|
||||
AuditCategorySecurity = "security"
|
||||
AuditCategoryOperation = "operation"
|
||||
AuditCategoryAccessToken = "access_token"
|
||||
)
|
||||
|
||||
// AuditLog is retained independently of usage logs and their cleanup/TTL policy.
|
||||
// TokenRef identifies a PAT generation without storing its bearer credential.
|
||||
type AuditLog struct {
|
||||
Id int `json:"id"`
|
||||
EventId string `json:"event_id" gorm:"type:varchar(64);uniqueIndex"`
|
||||
UserId int `json:"user_id" gorm:"index:idx_audit_user_time,priority:1"`
|
||||
Username string `json:"username" gorm:"type:varchar(64);index"`
|
||||
ActorRole int `json:"actor_role"` // Immutable role of the actor when the event began, not the log owner.
|
||||
CreatedAt int64 `json:"created_at" gorm:"type:bigint;index:idx_audit_user_time,priority:2;index:idx_audit_token_time,priority:2;index"`
|
||||
Category string `json:"category" gorm:"type:varchar(24);index"`
|
||||
Action string `json:"action" gorm:"type:varchar(128)"`
|
||||
TokenRef string `json:"token_ref" gorm:"type:varchar(64);index:idx_audit_token_time,priority:1"`
|
||||
AuthMethod string `json:"auth_method" gorm:"type:varchar(24)"`
|
||||
Ip string `json:"ip" gorm:"type:varchar(64)"`
|
||||
UserAgent string `json:"user_agent" gorm:"type:varchar(512)"`
|
||||
Method string `json:"method" gorm:"type:varchar(16)"`
|
||||
Route string `json:"route" gorm:"type:varchar(255)"`
|
||||
Status int `json:"status"`
|
||||
Success bool `json:"success"`
|
||||
RequestId string `json:"request_id" gorm:"type:varchar(64);index"`
|
||||
Content string `json:"content" gorm:"type:text"`
|
||||
Other AuditOther `json:"other" gorm:"type:json"`
|
||||
}
|
||||
|
||||
type AuditLogFilter struct {
|
||||
SelfView bool // Server-selected metadata projection, independent of the viewer's actual role.
|
||||
UserId int
|
||||
Username string
|
||||
Category string
|
||||
TokenRef string
|
||||
ExcludeTokenRef string
|
||||
RequestId string
|
||||
StartTimestamp int64
|
||||
EndTimestamp int64
|
||||
Success *bool
|
||||
}
|
||||
|
||||
func AccessTokenFingerprint(token string) string {
|
||||
// PostgreSQL returns CHAR(32) tokens padded with spaces. Normalize that
|
||||
// storage padding so persisted tokens and incoming credentials share a ref.
|
||||
token = strings.TrimRight(token, " ")
|
||||
if token == "" {
|
||||
return ""
|
||||
}
|
||||
digest := sha256.Sum256([]byte(token))
|
||||
return fmt.Sprintf("%x", digest)
|
||||
}
|
||||
|
||||
// RecordAuditLog captures safe request metadata only; raw URLs, query strings,
|
||||
// credentials and response/request bodies must never enter this table.
|
||||
func RecordAuditLog(c *gin.Context, entry AuditLog) {
|
||||
ctx := context.Background()
|
||||
if c != nil && c.Request != nil {
|
||||
ctx = c.Request.Context()
|
||||
entry.RequestId = c.GetString(common.RequestIdKey)
|
||||
entry.Ip = c.ClientIP()
|
||||
entry.UserAgent = c.Request.UserAgent()
|
||||
entry.Method = c.Request.Method
|
||||
entry.Route = c.FullPath()
|
||||
if entry.Status == 0 {
|
||||
entry.Status = c.Writer.Status()
|
||||
}
|
||||
if entry.AuthMethod == "" {
|
||||
entry.AuthMethod = "session"
|
||||
if c.GetBool("use_access_token") {
|
||||
entry.AuthMethod = "access_token"
|
||||
}
|
||||
}
|
||||
}
|
||||
if entry.CreatedAt == 0 {
|
||||
entry.CreatedAt = common.GetTimestamp()
|
||||
}
|
||||
if entry.RequestId == "" {
|
||||
entry.RequestId = common.NewRequestId()
|
||||
}
|
||||
if entry.EventId == "" {
|
||||
entry.EventId = common.NewRequestId()
|
||||
}
|
||||
switch entry.ActorRole {
|
||||
case common.RoleCommonUser, common.RoleAdminUser, common.RoleRootUser:
|
||||
default:
|
||||
logger.LogError(ctx, fmt.Sprintf("audit actor role unavailable (request_id=%s, actor_role=%d)", entry.RequestId, entry.ActorRole))
|
||||
entry.ActorRole = 0 // Unknown actors remain visible to root only.
|
||||
}
|
||||
if entry.Username == "" {
|
||||
entry.Username, _ = GetUsernameById(entry.UserId, false)
|
||||
}
|
||||
ua := []rune(entry.UserAgent)
|
||||
if len(ua) > 512 {
|
||||
entry.UserAgent = string(ua[:512])
|
||||
}
|
||||
if LOG_DB == nil {
|
||||
logger.LogError(ctx, fmt.Sprintf("audit log write failed (request_id=%s): log database unavailable", entry.RequestId))
|
||||
return
|
||||
}
|
||||
var row interface{} = &entry
|
||||
if common.UsingLogDatabase(common.DatabaseTypeClickHouse) {
|
||||
encoded, err := common.Marshal(entry.Other)
|
||||
if err != nil {
|
||||
logger.LogError(ctx, fmt.Sprintf("audit log write failed (request_id=%s): %v", entry.RequestId, err))
|
||||
return
|
||||
}
|
||||
// The ClickHouse GORM insert callback passes structs to the native
|
||||
// driver without resolving their Valuer. Bind this column's JSON
|
||||
// encoding while retaining AuditOther in the domain and API models.
|
||||
row = &struct {
|
||||
AuditLog `gorm:"embedded"`
|
||||
EncodedOther string `gorm:"column:other;type:json"`
|
||||
}{AuditLog: entry, EncodedOther: string(encoded)}
|
||||
}
|
||||
if err := LOG_DB.Table("audit_logs").Create(row).Error; err != nil {
|
||||
logger.LogError(ctx, fmt.Sprintf("audit log write failed (request_id=%s): %v", entry.RequestId, err))
|
||||
}
|
||||
}
|
||||
|
||||
func GetAuditLogs(filter AuditLogFilter, start, limit, viewerRole int) ([]*AuditLog, int64, error) {
|
||||
query := LOG_DB.Model(&AuditLog{})
|
||||
if common.UsingLogDatabase(common.DatabaseTypeClickHouse) {
|
||||
// Decode native JSON through database/sql as text for AuditOther.Scan.
|
||||
// Preserve numeric metadata instead of returning quoted Int64 values.
|
||||
query = query.WithContext(clickhouse.Context(query.Statement.Context, clickhouse.WithSettings(clickhouse.Settings{
|
||||
"output_format_native_write_json_as_string": 1,
|
||||
"output_format_json_quote_64bit_integers": 0,
|
||||
})))
|
||||
}
|
||||
if viewerRole < common.RoleRootUser {
|
||||
query = query.Where("actor_role IN ?", []int{common.RoleCommonUser, common.RoleAdminUser})
|
||||
}
|
||||
if filter.UserId > 0 {
|
||||
query = query.Where("user_id = ?", filter.UserId)
|
||||
}
|
||||
if filter.Username != "" {
|
||||
query = query.Where("username = ?", filter.Username)
|
||||
}
|
||||
if filter.Category != "" {
|
||||
query = query.Where("category = ?", filter.Category)
|
||||
}
|
||||
if filter.TokenRef != "" {
|
||||
query = query.Where("token_ref = ?", filter.TokenRef)
|
||||
}
|
||||
if filter.ExcludeTokenRef != "" {
|
||||
query = query.Where("token_ref <> ?", filter.ExcludeTokenRef)
|
||||
}
|
||||
if filter.RequestId != "" {
|
||||
query = query.Where("request_id = ?", filter.RequestId)
|
||||
}
|
||||
if filter.StartTimestamp > 0 {
|
||||
query = query.Where("created_at >= ?", filter.StartTimestamp)
|
||||
}
|
||||
if filter.EndTimestamp > 0 {
|
||||
query = query.Where("created_at <= ?", filter.EndTimestamp)
|
||||
}
|
||||
if filter.Success != nil {
|
||||
query = query.Where("success = ?", *filter.Success)
|
||||
}
|
||||
var total int64
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
logs := make([]*AuditLog, 0)
|
||||
if err := query.Order("created_at DESC").Order("event_id DESC").Offset(start).Limit(limit).Find(&logs).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
visibility := logOtherVisibilityUser
|
||||
if !filter.SelfView && viewerRole >= common.RoleRootUser {
|
||||
visibility = logOtherVisibilityRoot
|
||||
} else if !filter.SelfView && viewerRole >= common.RoleAdminUser {
|
||||
visibility = logOtherVisibilityAdmin
|
||||
}
|
||||
for _, entry := range logs {
|
||||
if visibility != logOtherVisibilityRoot {
|
||||
entry.Other.RootInfo = nil
|
||||
}
|
||||
if visibility == logOtherVisibilityUser {
|
||||
entry.Other.AdminInfo = nil
|
||||
entry.Other.AuditInfo = nil
|
||||
}
|
||||
}
|
||||
return logs, total, nil
|
||||
}
|
||||
|
||||
type UserAccessTokenStatus struct {
|
||||
Exists bool `json:"exists"`
|
||||
TokenRef string `json:"token_ref"`
|
||||
CreatedAt *int64 `json:"created_at"`
|
||||
LastUsedAt *int64 `json:"last_used_at"`
|
||||
LastUsedIp string `json:"last_used_ip"`
|
||||
}
|
||||
|
||||
func GetUserAccessTokenStatus(userId int) (*UserAccessTokenStatus, error) {
|
||||
var user User
|
||||
if err := DB.Select("id", "role", "access_token", "access_token_created_at").First(&user, userId).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
status := &UserAccessTokenStatus{Exists: user.GetAccessToken() != ""}
|
||||
if !status.Exists {
|
||||
return status, nil
|
||||
}
|
||||
status.TokenRef = AccessTokenFingerprint(user.GetAccessToken())
|
||||
status.CreatedAt = user.AccessTokenCreatedAt
|
||||
var latest AuditLog
|
||||
query := LOG_DB.Select("created_at", "ip").Where("user_id = ? AND token_ref = ? AND category = ?", userId, status.TokenRef, AuditCategoryAccessToken)
|
||||
if user.Role < common.RoleRootUser {
|
||||
query = query.Where("actor_role IN ?", []int{common.RoleCommonUser, common.RoleAdminUser})
|
||||
}
|
||||
err := query.Order("created_at DESC").Order("event_id DESC").Take(&latest).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return status, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
status.LastUsedAt = &latest.CreatedAt
|
||||
status.LastUsedIp = latest.Ip
|
||||
return status, nil
|
||||
}
|
||||
|
||||
// MigrateAuditLogs also supports independently configured ClickHouse log stores.
|
||||
// No TTL clause or usage-log cleanup integration is intentional.
|
||||
func MigrateAuditLogs() error {
|
||||
if !common.UsingLogDatabase(common.DatabaseTypeClickHouse) {
|
||||
return LOG_DB.AutoMigrate(&AuditLog{})
|
||||
}
|
||||
return LOG_DB.Exec(`CREATE TABLE IF NOT EXISTS audit_logs (
|
||||
id Int64 DEFAULT 0, event_id String, user_id Int64, username String, actor_role Int32,
|
||||
created_at Int64, category String, action String, token_ref String,
|
||||
auth_method String, ip String, user_agent String, method String, route String,
|
||||
status Int32, success UInt8, request_id String, content String, other JSON
|
||||
) ENGINE = MergeTree()
|
||||
PARTITION BY toYYYYMM(toDateTime(created_at))
|
||||
ORDER BY (created_at, event_id)`).Error
|
||||
}
|
||||
|
||||
func ValidAuditCategory(category string) bool {
|
||||
return category == "" || category == AuditCategoryLogin || category == AuditCategorySecurity || category == AuditCategoryOperation || category == AuditCategoryAccessToken
|
||||
}
|
||||
|
||||
func ValidTokenFingerprint(value string) bool {
|
||||
if value == "" {
|
||||
return true
|
||||
}
|
||||
if len(value) != 64 {
|
||||
return false
|
||||
}
|
||||
return strings.Trim(value, "0123456789abcdef") == ""
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
)
|
||||
|
||||
// AuditOther is the structured metadata stored with an audit event. Privileged
|
||||
// fields are separate so API projections can remove them without re-encoding JSON.
|
||||
type AuditOther struct {
|
||||
Op *AuditOperation `json:"op,omitempty"`
|
||||
AdminInfo *AuditAdminInfo `json:"admin_info,omitempty"`
|
||||
AuditInfo *AuditRequestInfo `json:"audit_info,omitempty"`
|
||||
RootInfo AuditFields `json:"root_info,omitempty"`
|
||||
LoginMethod string `json:"login_method,omitempty"`
|
||||
UserAgent string `json:"user_agent,omitempty"`
|
||||
}
|
||||
|
||||
type AuditOperation struct {
|
||||
Action string `json:"action"`
|
||||
Params AuditFields `json:"params,omitempty"`
|
||||
}
|
||||
|
||||
type AuditAdminInfo struct {
|
||||
AdminID int `json:"admin_id,omitempty"`
|
||||
AdminUsername string `json:"admin_username,omitempty"`
|
||||
AdminRole int `json:"admin_role,omitempty"`
|
||||
AuthMethod string `json:"auth_method,omitempty"`
|
||||
}
|
||||
|
||||
type AuditRequestInfo struct {
|
||||
Method string `json:"method"`
|
||||
Route string `json:"route"`
|
||||
Path string `json:"path"`
|
||||
Status int `json:"status"`
|
||||
Success bool `json:"success"`
|
||||
Params map[string]string `json:"params,omitempty"`
|
||||
}
|
||||
|
||||
// AuditFields holds action-specific parameters and root-only extensions.
|
||||
// Retain their encoded values when reading so arbitrary nested integers do not
|
||||
// round-trip through float64 and lose precision before the API returns them.
|
||||
type AuditFields map[string]any
|
||||
|
||||
func (fields *AuditFields) UnmarshalJSON(data []byte) error {
|
||||
var values map[string]json.RawMessage
|
||||
if err := common.Unmarshal(data, &values); err != nil {
|
||||
return err
|
||||
}
|
||||
if values == nil {
|
||||
*fields = nil
|
||||
return nil
|
||||
}
|
||||
decoded := make(AuditFields, len(values))
|
||||
for key, value := range values {
|
||||
decoded[key] = value
|
||||
}
|
||||
*fields = decoded
|
||||
return nil
|
||||
}
|
||||
|
||||
func (other AuditOther) Value() (driver.Value, error) {
|
||||
data, err := common.Marshal(other)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// PostgreSQL's simple protocol requires string, not a bytea parameter.
|
||||
return string(data), nil
|
||||
}
|
||||
|
||||
func (other *AuditOther) Scan(value any) error {
|
||||
var data []byte
|
||||
switch value := value.(type) {
|
||||
case nil:
|
||||
*other = AuditOther{}
|
||||
return nil
|
||||
case string:
|
||||
data = []byte(value)
|
||||
case []byte:
|
||||
data = value
|
||||
default:
|
||||
return fmt.Errorf("unsupported audit metadata database type %T", value)
|
||||
}
|
||||
var decoded AuditOther
|
||||
if len(data) > 0 {
|
||||
if err := common.Unmarshal(data, &decoded); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
*other = decoded
|
||||
return nil
|
||||
}
|
||||
+47
-51
@@ -166,7 +166,7 @@ func RecordLog(userId int, logType int, content string) {
|
||||
}
|
||||
|
||||
// RecordLogWithAdminInfo 记录操作日志,并将管理员相关信息存入 Other.admin_info,
|
||||
func RecordLogWithAdminInfo(userId int, logType int, content string, adminInfo map[string]interface{}) {
|
||||
func RecordLogWithAdminInfo(userId int, logType int, content string, adminInfo *AuditAdminInfo, request ...*gin.Context) {
|
||||
if logType == LogTypeConsume && !common.LogConsumeEnabled {
|
||||
return
|
||||
}
|
||||
@@ -178,75 +178,71 @@ func RecordLogWithAdminInfo(userId int, logType int, content string, adminInfo m
|
||||
Type: logType,
|
||||
Content: content,
|
||||
}
|
||||
if len(adminInfo) > 0 {
|
||||
other := NewLogOther()
|
||||
other.MergeAdmin(adminInfo)
|
||||
log.Other = other.JSONString()
|
||||
if logType == LogTypeManage {
|
||||
var c *gin.Context
|
||||
if len(request) > 0 {
|
||||
c = request[0]
|
||||
}
|
||||
actorRole := 0
|
||||
if c != nil {
|
||||
actorRole = c.GetInt("role")
|
||||
}
|
||||
RecordAuditLog(c, AuditLog{UserId: userId, Username: username, ActorRole: actorRole, Category: AuditCategoryOperation, Content: content, Other: AuditOther{AdminInfo: adminInfo}, Success: true})
|
||||
return
|
||||
}
|
||||
if adminInfo != nil {
|
||||
data, err := common.Marshal(AuditOther{AdminInfo: adminInfo})
|
||||
if err != nil {
|
||||
common.SysError("failed to encode log admin info: " + err.Error())
|
||||
return
|
||||
}
|
||||
log.Other = string(data)
|
||||
}
|
||||
if err := createLog(log); err != nil {
|
||||
common.SysLog("failed to record log: " + err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// buildOpField 构建语言无关的操作描述(写入 Other.op)。
|
||||
// 前端依据 action(稳定操作标识) + params(结构化参数) 在渲染期用 i18n 本地化展示,
|
||||
// 因此不在数据库中存储自然语言句子。
|
||||
func buildOpField(action string, params map[string]interface{}) map[string]interface{} {
|
||||
op := map[string]interface{}{
|
||||
"action": action,
|
||||
}
|
||||
if len(params) > 0 {
|
||||
op["params"] = params
|
||||
}
|
||||
return op
|
||||
}
|
||||
|
||||
// RecordLoginLog 记录用户登录成功的审计日志(type=LogTypeLogin)。
|
||||
// RecordLoginLog writes new login events to the independent audit table.
|
||||
// username 由调用方传入(登录流程已持有用户对象),避免额外的数据库查询。
|
||||
// content 为英文兜底文本(用于导出);action+params 供前端本地化渲染。
|
||||
// extra 可携带 login_method、user_agent 等附加信息(普通用户可见)。
|
||||
func RecordLoginLog(userId int, username string, content string, ip string, action string, params map[string]interface{}, extra map[string]interface{}) {
|
||||
other := NewLogOther()
|
||||
other.MergePublic(extra)
|
||||
other.SetPublic("op", buildOpField(action, params))
|
||||
log := &Log{
|
||||
UserId: userId,
|
||||
Username: username,
|
||||
CreatedAt: common.GetTimestamp(),
|
||||
Type: LogTypeLogin,
|
||||
Content: content,
|
||||
Ip: ip,
|
||||
Other: other.JSONString(),
|
||||
}
|
||||
if err := createLog(log); err != nil {
|
||||
common.SysLog("failed to record login log: " + err.Error())
|
||||
// other 包含 login_method、user_agent 等结构化信息。
|
||||
func RecordLoginLog(userId, actorRole int, username string, content string, ip string, action string, params map[string]interface{}, other AuditOther, request ...*gin.Context) {
|
||||
other.Op = &AuditOperation{Action: action, Params: params}
|
||||
var c *gin.Context
|
||||
if len(request) > 0 {
|
||||
c = request[0]
|
||||
}
|
||||
RecordAuditLog(c, AuditLog{UserId: userId, Username: username, ActorRole: actorRole, Category: AuditCategoryLogin, Action: action, Content: content, Ip: ip, Other: other, Success: true})
|
||||
}
|
||||
|
||||
// RecordOperationAuditLog 记录管理/高危操作审计日志(type=LogTypeManage)。
|
||||
// RecordOperationAuditLog writes new operation/security events to the audit table.
|
||||
// logUserId 为日志归属者,管理审计日志应归属实际操作者;目标资源/用户放入
|
||||
// action params。username 内部按 logUserId 查询。content 为英文兜底文本(供导出使用)。
|
||||
// action+params 写入 Other.op,供前端本地化渲染(普通用户可见,不含敏感信息)。
|
||||
// adminInfo 存放操作者身份(写入 Other.admin_info,普通用户查询时剥离);
|
||||
// auditInfo 存放路由/方法/结果等中间件兜底信息(写入 Other.audit_info,普通用户查询时剥离)。
|
||||
func RecordOperationAuditLog(logUserId int, content string, ip string, action string, params map[string]interface{}, adminInfo map[string]interface{}, auditInfo map[string]interface{}) {
|
||||
func RecordOperationAuditLog(logUserId, actorRole int, content string, ip string, action string, params map[string]interface{}, adminInfo *AuditAdminInfo, auditInfo *AuditRequestInfo, request ...*gin.Context) {
|
||||
username, _ := GetUsernameById(logUserId, false)
|
||||
other := NewLogOther()
|
||||
other.SetPublic("op", buildOpField(action, params))
|
||||
other.MergeAdmin(adminInfo)
|
||||
other.MergeAudit(auditInfo)
|
||||
log := &Log{
|
||||
UserId: logUserId,
|
||||
Username: username,
|
||||
CreatedAt: common.GetTimestamp(),
|
||||
Type: LogTypeManage,
|
||||
Content: content,
|
||||
Ip: ip,
|
||||
Other: other.JSONString(),
|
||||
other := AuditOther{
|
||||
Op: &AuditOperation{Action: action, Params: params},
|
||||
AdminInfo: adminInfo,
|
||||
AuditInfo: auditInfo,
|
||||
}
|
||||
if err := createLog(log); err != nil {
|
||||
common.SysLog("failed to record operation audit log: " + err.Error())
|
||||
var c *gin.Context
|
||||
if len(request) > 0 {
|
||||
c = request[0]
|
||||
}
|
||||
category := AuditCategoryOperation
|
||||
if adminInfo == nil {
|
||||
category = AuditCategorySecurity
|
||||
}
|
||||
status, success := 200, true
|
||||
if auditInfo != nil {
|
||||
status = auditInfo.Status
|
||||
success = auditInfo.Success
|
||||
}
|
||||
RecordAuditLog(c, AuditLog{UserId: logUserId, Username: username, ActorRole: actorRole, Category: category, Action: action, Content: content, Ip: ip, Status: status, Success: success, Other: other})
|
||||
}
|
||||
|
||||
func RecordTopupLog(userId int, content string, callerIp string, paymentMethod string, callbackPaymentMethod string) {
|
||||
|
||||
@@ -232,6 +232,9 @@ func InitLogDB() (err error) {
|
||||
LOG_DB = DB
|
||||
common.SetLogDatabaseType(common.MainDatabaseType())
|
||||
initCol()
|
||||
if common.IsMasterNode {
|
||||
return MigrateAuditLogs()
|
||||
}
|
||||
return
|
||||
}
|
||||
db, dbType, err := chooseDB("LOG_SQL_DSN", true)
|
||||
@@ -387,6 +390,9 @@ func migrateDB() error {
|
||||
}
|
||||
|
||||
func migrateLOGDB() error {
|
||||
if err := MigrateAuditLogs(); err != nil {
|
||||
return err
|
||||
}
|
||||
if common.UsingLogDatabase(common.DatabaseTypeClickHouse) {
|
||||
return migrateClickHouseLogDB()
|
||||
}
|
||||
|
||||
+54
-34
@@ -77,39 +77,40 @@ func resolveUserSortOptions(sortOptions []UserSortOptions) UserSortOptions {
|
||||
// User if you add sensitive fields, don't forget to clean them in setupLogin function.
|
||||
// Otherwise, the sensitive information will be saved on local storage in plain text!
|
||||
type User struct {
|
||||
Id int `json:"id"`
|
||||
Username string `json:"username" gorm:"unique;index" validate:"max=20"`
|
||||
Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"`
|
||||
OriginalPassword string `json:"original_password" gorm:"-:all"` // this field is only for Password change verification, don't save it to database!
|
||||
DisplayName string `json:"display_name" gorm:"index" validate:"max=20"`
|
||||
Role int `json:"role" gorm:"type:int;default:1"` // admin, common
|
||||
Status int `json:"status" gorm:"type:int;default:1"` // enabled, disabled
|
||||
Email string `json:"email" gorm:"index" validate:"max=50"`
|
||||
GitHubId string `json:"github_id" gorm:"column:github_id;index"`
|
||||
DiscordId string `json:"discord_id" gorm:"column:discord_id;index"`
|
||||
OidcId string `json:"oidc_id" gorm:"column:oidc_id;index"`
|
||||
WeChatId string `json:"wechat_id" gorm:"column:wechat_id;index"`
|
||||
TelegramId string `json:"telegram_id" gorm:"column:telegram_id;index"`
|
||||
VerificationCode string `json:"verification_code" gorm:"-:all"` // this field is only for Email verification, don't save it to database!
|
||||
AccessToken *string `json:"-" gorm:"type:char(32);column:access_token;uniqueIndex"` // this token is for system management
|
||||
Quota int `json:"quota" gorm:"type:int;default:0"`
|
||||
UsedQuota int `json:"used_quota" gorm:"type:int;default:0;column:used_quota"` // used quota
|
||||
RequestCount int `json:"request_count" gorm:"type:int;default:0;"` // request number
|
||||
Group string `json:"group" gorm:"type:varchar(64);default:'default'"`
|
||||
AffCode string `json:"aff_code" gorm:"type:varchar(32);column:aff_code;uniqueIndex"`
|
||||
AffCount int `json:"aff_count" gorm:"type:int;default:0;column:aff_count"`
|
||||
AffQuota int `json:"aff_quota" gorm:"type:int;default:0;column:aff_quota"` // 邀请剩余额度
|
||||
AffHistoryQuota int `json:"aff_history_quota" gorm:"type:int;default:0;column:aff_history"` // 邀请历史额度
|
||||
InviterId int `json:"inviter_id" gorm:"type:int;column:inviter_id;index"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index"`
|
||||
LinuxDOId string `json:"linux_do_id" gorm:"column:linux_do_id;index"`
|
||||
Setting string `json:"setting" gorm:"type:text;column:setting"`
|
||||
Remark string `json:"remark,omitempty" gorm:"type:varchar(255)" validate:"max=255"`
|
||||
StripeCustomer string `json:"stripe_customer" gorm:"type:varchar(64);column:stripe_customer;index"`
|
||||
CreatedAt int64 `json:"created_at" gorm:"autoCreateTime;column:created_at"`
|
||||
LastLoginAt int64 `json:"last_login_at" gorm:"default:0;column:last_login_at"`
|
||||
AuthVersion int64 `json:"-" gorm:"type:bigint;not null;default:1;column:auth_version"`
|
||||
AdminPermissions map[string]map[string]bool `json:"admin_permissions,omitempty" gorm:"-:all"`
|
||||
Id int `json:"id"`
|
||||
Username string `json:"username" gorm:"unique;index" validate:"max=20"`
|
||||
Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"`
|
||||
OriginalPassword string `json:"original_password" gorm:"-:all"` // this field is only for Password change verification, don't save it to database!
|
||||
DisplayName string `json:"display_name" gorm:"index" validate:"max=20"`
|
||||
Role int `json:"role" gorm:"type:int;default:1"` // admin, common
|
||||
Status int `json:"status" gorm:"type:int;default:1"` // enabled, disabled
|
||||
Email string `json:"email" gorm:"index" validate:"max=50"`
|
||||
GitHubId string `json:"github_id" gorm:"column:github_id;index"`
|
||||
DiscordId string `json:"discord_id" gorm:"column:discord_id;index"`
|
||||
OidcId string `json:"oidc_id" gorm:"column:oidc_id;index"`
|
||||
WeChatId string `json:"wechat_id" gorm:"column:wechat_id;index"`
|
||||
TelegramId string `json:"telegram_id" gorm:"column:telegram_id;index"`
|
||||
VerificationCode string `json:"verification_code" gorm:"-:all"` // this field is only for Email verification, don't save it to database!
|
||||
AccessToken *string `json:"-" gorm:"type:char(32);column:access_token;uniqueIndex"` // this token is for system management
|
||||
AccessTokenCreatedAt *int64 `json:"-" gorm:"type:bigint;column:access_token_created_at"`
|
||||
Quota int `json:"quota" gorm:"type:int;default:0"`
|
||||
UsedQuota int `json:"used_quota" gorm:"type:int;default:0;column:used_quota"` // used quota
|
||||
RequestCount int `json:"request_count" gorm:"type:int;default:0;"` // request number
|
||||
Group string `json:"group" gorm:"type:varchar(64);default:'default'"`
|
||||
AffCode string `json:"aff_code" gorm:"type:varchar(32);column:aff_code;uniqueIndex"`
|
||||
AffCount int `json:"aff_count" gorm:"type:int;default:0;column:aff_count"`
|
||||
AffQuota int `json:"aff_quota" gorm:"type:int;default:0;column:aff_quota"` // 邀请剩余额度
|
||||
AffHistoryQuota int `json:"aff_history_quota" gorm:"type:int;default:0;column:aff_history"` // 邀请历史额度
|
||||
InviterId int `json:"inviter_id" gorm:"type:int;column:inviter_id;index"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index"`
|
||||
LinuxDOId string `json:"linux_do_id" gorm:"column:linux_do_id;index"`
|
||||
Setting string `json:"setting" gorm:"type:text;column:setting"`
|
||||
Remark string `json:"remark,omitempty" gorm:"type:varchar(255)" validate:"max=255"`
|
||||
StripeCustomer string `json:"stripe_customer" gorm:"type:varchar(64);column:stripe_customer;index"`
|
||||
CreatedAt int64 `json:"created_at" gorm:"autoCreateTime;column:created_at"`
|
||||
LastLoginAt int64 `json:"last_login_at" gorm:"default:0;column:last_login_at"`
|
||||
AuthVersion int64 `json:"-" gorm:"type:bigint;not null;default:1;column:auth_version"`
|
||||
AdminPermissions map[string]map[string]bool `json:"admin_permissions,omitempty" gorm:"-:all"`
|
||||
}
|
||||
|
||||
func (user *User) ToBaseUser() *UserBase {
|
||||
@@ -145,7 +146,9 @@ func UpdateUserAccessToken(id int, token string) error {
|
||||
if id == 0 {
|
||||
return errors.New("id 为空!")
|
||||
}
|
||||
result := DB.Model(&User{}).Where("id = ?", id).Update("access_token", token)
|
||||
result := DB.Model(&User{}).Where("id = ?", id).Updates(map[string]interface{}{
|
||||
"access_token": token, "access_token_created_at": common.GetTimestamp(),
|
||||
})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
@@ -155,6 +158,23 @@ func UpdateUserAccessToken(id int, token string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// RevokeUserAccessToken returns the generation actually revoked under the row lock.
|
||||
func RevokeUserAccessToken(id int) (string, error) {
|
||||
var tokenRef string
|
||||
err := DB.Transaction(func(tx *gorm.DB) error {
|
||||
var user User
|
||||
if err := lockForUpdate(tx).Select("id", "access_token").First(&user, id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
tokenRef = AccessTokenFingerprint(user.GetAccessToken())
|
||||
if tokenRef == "" {
|
||||
return nil
|
||||
}
|
||||
return tx.Model(&User{}).Where("id = ?", id).Updates(map[string]interface{}{"access_token": nil, "access_token_created_at": nil}).Error
|
||||
})
|
||||
return tokenRef, err
|
||||
}
|
||||
|
||||
func (user *User) GetSetting() dto.UserSetting {
|
||||
setting := dto.UserSetting{}
|
||||
if user.Setting != "" {
|
||||
|
||||
@@ -16,6 +16,7 @@ func SetApiRouter(router *gin.Engine) {
|
||||
apiRouter := router.Group("/api")
|
||||
apiRouter.Use(middleware.RouteTag("api"))
|
||||
apiRouter.Use(gzip.Gzip(gzip.DefaultCompression))
|
||||
apiRouter.Use(middleware.AccessTokenAudit())
|
||||
apiRouter.Use(middleware.BodyStorageCleanup()) // 清理请求体存储
|
||||
apiRouter.Use(middleware.GlobalAPIRateLimit())
|
||||
anonymousRequestBodyLimit := middleware.AnonymousRequestBodyLimit()
|
||||
@@ -82,7 +83,7 @@ func SetApiRouter(router *gin.Engine) {
|
||||
userRoute.GET("/groups", controller.GetUserGroups)
|
||||
|
||||
selfRoute := userRoute.Group("/")
|
||||
selfRoute.Use(middleware.UserAuth())
|
||||
selfRoute.Use(middleware.DisableCache(), middleware.UserAuth())
|
||||
{
|
||||
selfRoute.GET("/sessions", middleware.DisableCache(), controller.GetLoginSessions)
|
||||
selfRoute.DELETE("/sessions/:sid", middleware.DisableCache(), controller.DeleteLoginSession)
|
||||
@@ -93,6 +94,9 @@ func SetApiRouter(router *gin.Engine) {
|
||||
selfRoute.PUT("/self", middleware.CriticalRateLimit(), middleware.DisableCache(), controller.UpdateSelf)
|
||||
selfRoute.DELETE("/self", controller.DeleteSelf)
|
||||
selfRoute.GET("/token", middleware.CriticalRateLimit(), middleware.UserCriticalRateLimit("access-token"), middleware.DisableCache(), controller.GenerateAccessToken)
|
||||
selfRoute.GET("/token/status", middleware.DisableCache(), controller.GetAccessTokenStatus)
|
||||
selfRoute.POST("/token", middleware.CriticalRateLimit(), middleware.UserCriticalRateLimit("access-token"), middleware.DisableCache(), controller.GenerateAccessToken)
|
||||
selfRoute.DELETE("/token", middleware.CriticalRateLimit(), middleware.DisableCache(), controller.RevokeAccessToken)
|
||||
selfRoute.GET("/passkey", controller.PasskeyStatus)
|
||||
selfRoute.POST("/passkey/register/begin", middleware.DisableCache(), controller.PasskeyRegisterBegin)
|
||||
selfRoute.POST("/passkey/register/finish", middleware.DisableCache(), controller.PasskeyRegisterFinish)
|
||||
@@ -288,6 +292,8 @@ func SetApiRouter(router *gin.Engine) {
|
||||
redemptionRoute.DELETE("/invalid", controller.DeleteInvalidRedemption)
|
||||
redemptionRoute.DELETE("/:id", controller.DeleteRedemption)
|
||||
}
|
||||
apiRouter.GET("/audit", middleware.DisableCache(), middleware.AdminAuth(), middleware.RequirePermission(authz.AuditRead), controller.GetAuditLogs)
|
||||
apiRouter.GET("/audit/self", middleware.DisableCache(), middleware.UserAuth(), controller.GetAuditLogs)
|
||||
logRoute := apiRouter.Group("/log")
|
||||
logRoute.GET("/", middleware.AdminAuth(), controller.GetAllLogs)
|
||||
logRoute.GET("/stat", middleware.AdminAuth(), controller.GetLogsStat)
|
||||
|
||||
@@ -32,6 +32,7 @@ func SetRouter(router *gin.Engine, assets WebAssets) {
|
||||
router.NoRoute(
|
||||
pluginDispatcher,
|
||||
middleware.RouteTag("web"),
|
||||
middleware.AccessTokenAudit(),
|
||||
func(c *gin.Context) {
|
||||
c.Redirect(http.StatusMovedPermanently, fmt.Sprintf("%s%s", frontendBaseUrl, c.Request.RequestURI))
|
||||
},
|
||||
|
||||
@@ -882,3 +882,33 @@ func performPluginRequest(handler http.Handler, method, path string) *httptest.R
|
||||
handler.ServeHTTP(recorder, request)
|
||||
return recorder
|
||||
}
|
||||
|
||||
func TestWebFallbackDoesNotCacheMissingAPIOrAssets(t *testing.T) {
|
||||
outer := gin.New()
|
||||
SetWebRouter(outer, WebAssets{IndexPage: []byte("dashboard")}, func(c *gin.Context) { c.Next() })
|
||||
for _, path := range []string{"/api/user/token/status", "/api/audit/self?p=1", "/v1/missing", "/assets/missing.js"} {
|
||||
t.Run(path, func(t *testing.T) {
|
||||
response := performPluginRequest(outer, http.MethodGet, path)
|
||||
assert.Equal(t, http.StatusNotFound, response.Code)
|
||||
assert.Contains(t, response.Body.String(), "Invalid URL")
|
||||
assert.Contains(t, response.Header().Get("Cache-Control"), "no-store")
|
||||
assert.NotContains(t, response.Header().Get("Cache-Control"), "604800")
|
||||
})
|
||||
}
|
||||
page := performPluginRequest(outer, http.MethodGet, "/security")
|
||||
assert.Equal(t, http.StatusOK, page.Code)
|
||||
assert.Equal(t, "dashboard", page.Body.String())
|
||||
assert.Equal(t, "no-cache", page.Header().Get("Cache-Control"))
|
||||
}
|
||||
|
||||
func TestSecurityRoutesDisableCachingBeforeAuthentication(t *testing.T) {
|
||||
outer := gin.New()
|
||||
SetApiRouter(outer)
|
||||
for _, path := range []string{"/api/user/token/status", "/api/user/token", "/api/audit/self", "/api/audit"} {
|
||||
t.Run(path, func(t *testing.T) {
|
||||
response := performPluginRequest(outer, http.MethodGet, path)
|
||||
assert.Equal(t, http.StatusUnauthorized, response.Code)
|
||||
assert.Contains(t, response.Header().Get("Cache-Control"), "no-store")
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ func SetWebRouter(router *gin.Engine, assets WebAssets, pluginDispatcher gin.Han
|
||||
pluginDispatcher,
|
||||
middleware.RouteTag("web"),
|
||||
gzip.Gzip(gzip.DefaultCompression),
|
||||
middleware.AccessTokenAudit(),
|
||||
middleware.GlobalWebRateLimit(),
|
||||
middleware.Cache(),
|
||||
static.Serve("/", frontendFS),
|
||||
|
||||
@@ -108,6 +108,7 @@ func TestSetUserPermissionsStoresOnlyOverrides(t *testing.T) {
|
||||
ResourceTaskPlugin: {
|
||||
ActionBind: false,
|
||||
},
|
||||
ResourceAudit: {ActionRead: false},
|
||||
}, ExplicitUserPermissions(42))
|
||||
assert.Equal(t, PermissionsMap{
|
||||
ResourceChannel: {
|
||||
@@ -139,6 +140,7 @@ func TestSetUserPermissionsStoresOnlyOverrides(t *testing.T) {
|
||||
ResourceTaskPlugin: {
|
||||
ActionBind: false,
|
||||
},
|
||||
ResourceAudit: {ActionRead: false},
|
||||
}, ExplicitUserPermissions(42))
|
||||
assert.Empty(t, ExplicitUserOverrides(42))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package authz
|
||||
|
||||
const ResourceAudit = "audit"
|
||||
|
||||
var AuditRead = Permission{Resource: ResourceAudit, Action: ActionRead}
|
||||
|
||||
func init() {
|
||||
RegisterResource(ResourceDefinition{
|
||||
Resource: ResourceAudit,
|
||||
LabelKey: "Audit Logs",
|
||||
Actions: []ActionDefinition{{
|
||||
Action: ActionRead,
|
||||
LabelKey: "View other accounts' audit logs",
|
||||
DescriptionKey: "View audit records from user and admin roles. Root records are always excluded.",
|
||||
}},
|
||||
})
|
||||
}
|
||||
@@ -17,7 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { X, User, Wallet, LogOut } from 'lucide-react'
|
||||
import { X, User, Wallet, LogOut, ShieldCheck } from 'lucide-react'
|
||||
import { AnimatePresence, motion, type Variants } from 'motion/react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
@@ -26,6 +26,7 @@ import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import useDialogState from '@/hooks/use-dialog'
|
||||
import { useIsSidebarModuleVisible } from '@/hooks/use-sidebar-config'
|
||||
import { useUserDisplay } from '@/hooks/use-user-display'
|
||||
import type { AuthUser } from '@/stores/auth-store'
|
||||
|
||||
@@ -81,6 +82,7 @@ function MobileUserProfile({ user, onNavigate }: MobileUserProfileProps) {
|
||||
const { t } = useTranslation()
|
||||
const [signOutOpen, setSignOutOpen] = useDialogState()
|
||||
const { displayName, initials, roleLabel } = useUserDisplay(user)
|
||||
const isSecurityVisible = useIsSidebarModuleVisible('/security')
|
||||
|
||||
if (!user) return null
|
||||
|
||||
@@ -122,6 +124,17 @@ function MobileUserProfile({ user, onNavigate }: MobileUserProfileProps) {
|
||||
{t('Profile')}
|
||||
</Link>
|
||||
|
||||
{isSecurityVisible && (
|
||||
<Link
|
||||
to='/security'
|
||||
onClick={onNavigate}
|
||||
className='text-primary/60 hover:text-primary/80 border-border flex items-center gap-2.5 border-b p-2.5 transition-colors'
|
||||
>
|
||||
<ShieldCheck className='size-4' />
|
||||
{t('Security & Access')}
|
||||
</Link>
|
||||
)}
|
||||
|
||||
<Link
|
||||
to='/wallet'
|
||||
onClick={onNavigate}
|
||||
@@ -261,9 +274,9 @@ export function MobileDrawer({
|
||||
</div>
|
||||
) : (
|
||||
<AnimatePresence>
|
||||
{mobileLinksList.map((link, index) => (
|
||||
{mobileLinksList.map((link) => (
|
||||
<motion.div
|
||||
key={`${link.href}-${index}`}
|
||||
key={link.href}
|
||||
className='border-border border-b p-2.5 last:border-b-0'
|
||||
variants={MOBILE_DRAWER_ANIMATION.menuItem as Variants}
|
||||
>
|
||||
|
||||
@@ -17,7 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { User, Wallet, LogOut, Settings } from 'lucide-react'
|
||||
import { User, Wallet, LogOut, Settings, ShieldCheck } from 'lucide-react'
|
||||
import { useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
@@ -48,6 +48,7 @@ export function ProfileDropdown() {
|
||||
const { displayName, roleLabel } = useUserDisplay(user)
|
||||
const isSuperAdmin = user?.role === ROLE.SUPER_ADMIN
|
||||
const isWalletVisible = useIsSidebarModuleVisible('/wallet')
|
||||
const isSecurityVisible = useIsSidebarModuleVisible('/security')
|
||||
const avatarName = user?.username || displayName
|
||||
const avatarFallback = getUserAvatarFallback(avatarName)
|
||||
const avatarFallbackStyle = useMemo(
|
||||
@@ -107,6 +108,13 @@ export function ProfileDropdown() {
|
||||
{t('Profile')}
|
||||
</DropdownMenuItem>
|
||||
|
||||
{isSecurityVisible && (
|
||||
<DropdownMenuItem onClick={() => navigate({ to: '/security' })}>
|
||||
<ShieldCheck className='size-4' />
|
||||
{t('Security & Access')}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
|
||||
{isWalletVisible && (
|
||||
<DropdownMenuItem onClick={() => navigate({ to: '/wallet' })}>
|
||||
<Wallet className='size-4' />
|
||||
|
||||
@@ -73,7 +73,9 @@ export function SecureVerificationDialog({
|
||||
state.description ??
|
||||
(availableTabs.length
|
||||
? 'Confirm your identity before accessing this sensitive action.'
|
||||
: 'Enable Two-factor Authentication or Passkey in your profile settings to continue.')
|
||||
: t(
|
||||
'Enable Two-factor Authentication or Passkey in Security & Access to continue.'
|
||||
))
|
||||
|
||||
const handleVerify = () => {
|
||||
if (!activeMethod) return
|
||||
@@ -132,7 +134,7 @@ export function SecureVerificationDialog({
|
||||
</div>
|
||||
<p className='text-muted-foreground text-sm'>
|
||||
{t(
|
||||
'Enable Two-factor Authentication or Passkey in your profile to unlock sensitive operations.'
|
||||
'Enable Two-factor Authentication or Passkey in Security & Access to unlock sensitive operations.'
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
import { updateUserSettings } from '../api'
|
||||
import { NotificationTab } from '../components/tabs/notification-tab'
|
||||
import type { UserProfile } from '../types'
|
||||
|
||||
const profile: UserProfile = {
|
||||
id: 1,
|
||||
username: 'alice',
|
||||
display_name: 'Alice',
|
||||
role: 1,
|
||||
group: 'default',
|
||||
quota: 1000000,
|
||||
used_quota: 0,
|
||||
request_count: 0,
|
||||
status: 1,
|
||||
aff_count: 0,
|
||||
aff_quota: 0,
|
||||
aff_history_quota: 0,
|
||||
created_time: 0,
|
||||
}
|
||||
const settings = {
|
||||
notify_type: 'webhook',
|
||||
quota_warning_threshold: 1200,
|
||||
notification_email: '',
|
||||
webhook_url: 'https://example.com/notify',
|
||||
webhook_secret: 'webhook-secret',
|
||||
bark_url: '',
|
||||
gotify_url: '',
|
||||
gotify_token: '',
|
||||
gotify_priority: 5,
|
||||
accept_unset_model_ratio_model: true,
|
||||
record_ip_log: true,
|
||||
upstream_model_update_notify_enabled: true,
|
||||
}
|
||||
|
||||
afterEach(() => vi.restoreAllMocks())
|
||||
|
||||
describe('user settings saves across profile and security', () => {
|
||||
it('disabling IP recording sends the latest complete notification settings', async () => {
|
||||
const get = vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: { ...profile, setting: JSON.stringify(settings) },
|
||||
},
|
||||
})
|
||||
const put = vi
|
||||
.spyOn(api, 'put')
|
||||
.mockResolvedValue({ data: { success: true } })
|
||||
await updateUserSettings({ record_ip_log: false })
|
||||
expect(get).toHaveBeenCalledWith('/api/user/self')
|
||||
expect(put).toHaveBeenCalledWith('/api/user/setting', {
|
||||
...settings,
|
||||
record_ip_log: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('saving IP recording for a user with no settings supplies the existing defaults', async () => {
|
||||
vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: { success: true, data: profile },
|
||||
})
|
||||
const put = vi
|
||||
.spyOn(api, 'put')
|
||||
.mockResolvedValue({ data: { success: true } })
|
||||
await updateUserSettings({ record_ip_log: true })
|
||||
expect(put).toHaveBeenCalledWith('/api/user/setting', {
|
||||
notify_type: 'email',
|
||||
quota_warning_threshold: 500000,
|
||||
notification_email: '',
|
||||
webhook_url: '',
|
||||
webhook_secret: '',
|
||||
bark_url: '',
|
||||
gotify_url: '',
|
||||
gotify_token: '',
|
||||
gotify_priority: 5,
|
||||
accept_unset_model_ratio_model: false,
|
||||
record_ip_log: true,
|
||||
upstream_model_update_notify_enabled: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('alternating notification and IP saves retains the latest values from each page', async () => {
|
||||
let saved = { ...settings }
|
||||
vi.spyOn(api, 'get').mockImplementation(async () => ({
|
||||
data: {
|
||||
success: true,
|
||||
data: { ...profile, setting: JSON.stringify(saved) },
|
||||
},
|
||||
}))
|
||||
vi.spyOn(api, 'put').mockImplementation(async (_url, body) => {
|
||||
saved = body as typeof settings
|
||||
return { data: { success: true } }
|
||||
})
|
||||
await updateUserSettings({ record_ip_log: false })
|
||||
await updateUserSettings({ quota_warning_threshold: 2500 })
|
||||
await updateUserSettings({ record_ip_log: true })
|
||||
expect(saved).toEqual({
|
||||
...settings,
|
||||
quota_warning_threshold: 2500,
|
||||
record_ip_log: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('a rejected profile read prevents the settings write', async () => {
|
||||
vi.spyOn(api, 'get').mockRejectedValue(new Error('offline'))
|
||||
const put = vi.spyOn(api, 'put')
|
||||
await expect(updateUserSettings({ record_ip_log: false })).rejects.toThrow(
|
||||
'offline'
|
||||
)
|
||||
expect(put).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('an unsuccessful profile response prevents the settings write', async () => {
|
||||
vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: { success: false, message: 'Unavailable' },
|
||||
})
|
||||
const put = vi.spyOn(api, 'put')
|
||||
expect(await updateUserSettings({ record_ip_log: false })).toEqual({
|
||||
success: false,
|
||||
message: 'Unavailable',
|
||||
})
|
||||
expect(put).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('an unsuccessful settings write is returned to the caller', async () => {
|
||||
vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: { success: true, data: profile },
|
||||
})
|
||||
vi.spyOn(api, 'put').mockResolvedValue({
|
||||
data: { success: false, message: 'Save failed' },
|
||||
})
|
||||
expect(await updateUserSettings({ record_ip_log: true })).toEqual({
|
||||
success: false,
|
||||
message: 'Save failed',
|
||||
})
|
||||
})
|
||||
|
||||
it('saving a stale notification form keeps the current IP setting and the notification edits', async () => {
|
||||
const onUpdate = vi.fn()
|
||||
vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
...profile,
|
||||
setting: JSON.stringify({ ...settings, record_ip_log: false }),
|
||||
},
|
||||
},
|
||||
})
|
||||
const put = vi
|
||||
.spyOn(api, 'put')
|
||||
.mockResolvedValue({ data: { success: true } })
|
||||
render(
|
||||
<NotificationTab
|
||||
profile={{ ...profile, setting: JSON.stringify(settings) }}
|
||||
onUpdate={onUpdate}
|
||||
/>
|
||||
)
|
||||
expect(
|
||||
screen.queryByRole('switch', { name: 'Record IP Address' })
|
||||
).not.toBeInTheDocument()
|
||||
fireEvent.change(
|
||||
screen.getByRole('spinbutton', { name: 'Quota Warning Threshold' }),
|
||||
{ target: { value: '2700' } }
|
||||
)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save Settings' }))
|
||||
await waitFor(() => expect(onUpdate).toHaveBeenCalled())
|
||||
expect(put).toHaveBeenCalledWith('/api/user/setting', {
|
||||
...settings,
|
||||
quota_warning_threshold: 2700,
|
||||
record_ip_log: false,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -20,6 +20,7 @@ import { api } from '@/lib/api'
|
||||
import type { CustomOAuthBinding } from '@/lib/oauth'
|
||||
import type { LoginSession } from '@/stores/auth-store'
|
||||
|
||||
import { normalizeUserSettings } from './lib/user-settings'
|
||||
import type {
|
||||
ApiResponse,
|
||||
UserProfile,
|
||||
@@ -60,7 +61,12 @@ export async function updateUserProfile(
|
||||
export async function updateUserSettings(
|
||||
data: UpdateUserSettingsRequest
|
||||
): Promise<ApiResponse> {
|
||||
const res = await api.put('/api/user/setting', data)
|
||||
const profile = await getUserProfile()
|
||||
if (!profile.success || !profile.data) {
|
||||
return { success: false, message: profile.message }
|
||||
}
|
||||
const settings = normalizeUserSettings(profile.data.setting)
|
||||
const res = await api.put('/api/user/setting', { ...settings, ...data })
|
||||
return res.data
|
||||
}
|
||||
|
||||
@@ -84,14 +90,6 @@ export async function deleteUserAccount(
|
||||
return res.data
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate/regenerate system access token
|
||||
*/
|
||||
export async function generateAccessToken(): Promise<ApiResponse<string>> {
|
||||
const res = await api.get('/api/user/token')
|
||||
return res.data
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Account Binding APIs
|
||||
// ============================================================================
|
||||
|
||||
@@ -1,198 +0,0 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { KeyRound, Loader2, RefreshCw } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog'
|
||||
import { CopyButton } from '@/components/copy-button'
|
||||
import { Dialog } from '@/components/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Empty,
|
||||
EmptyDescription,
|
||||
EmptyHeader,
|
||||
EmptyMedia,
|
||||
EmptyTitle,
|
||||
} from '@/components/ui/empty'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
|
||||
import { useAccessToken } from '../../hooks'
|
||||
|
||||
// ============================================================================
|
||||
// Access Token Dialog Component
|
||||
// ============================================================================
|
||||
|
||||
interface AccessTokenDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
export function AccessTokenDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
}: AccessTokenDialogProps) {
|
||||
const { t } = useTranslation()
|
||||
const { token, generating, generate, clearToken } = useAccessToken()
|
||||
const [confirmOpen, setConfirmOpen] = useState(false)
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
if (generating) return
|
||||
|
||||
if (!nextOpen) {
|
||||
setConfirmOpen(false)
|
||||
clearToken()
|
||||
}
|
||||
onOpenChange(nextOpen)
|
||||
}
|
||||
|
||||
const handleGenerate = async () => {
|
||||
if (await generate()) {
|
||||
setConfirmOpen(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={t('Access Token')}
|
||||
description={t(
|
||||
"Your system access token for API authentication. Keep it secure and don't share it with others."
|
||||
)}
|
||||
contentClassName='sm:max-w-md'
|
||||
contentHeight='auto'
|
||||
bodyClassName='space-y-4'
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
onClick={() => handleOpenChange(false)}
|
||||
disabled={generating}
|
||||
>
|
||||
{t('Close')}
|
||||
</Button>
|
||||
<Button
|
||||
type='button'
|
||||
onClick={() => setConfirmOpen(true)}
|
||||
disabled={generating}
|
||||
className='gap-2'
|
||||
>
|
||||
{generating ? (
|
||||
<Loader2 className='h-4 w-4 animate-spin' aria-hidden='true' />
|
||||
) : (
|
||||
<RefreshCw className='h-4 w-4' aria-hidden='true' />
|
||||
)}
|
||||
{generating ? t('Generating...') : t('Regenerate')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className='my-6'>
|
||||
{token ? (
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='token'>{t('Token')}</Label>
|
||||
<div className='flex gap-2'>
|
||||
<Input
|
||||
id='token'
|
||||
type='text'
|
||||
value={token}
|
||||
readOnly
|
||||
className='font-mono text-xs'
|
||||
/>
|
||||
<CopyButton
|
||||
value={token}
|
||||
variant='outline'
|
||||
className='size-9'
|
||||
iconClassName='size-4'
|
||||
tooltip={t('Copy token')}
|
||||
aria-label={t('Copy token')}
|
||||
/>
|
||||
</div>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t(
|
||||
"Save this token now. You won't be able to view it again after closing this dialog."
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<Empty className='border py-8'>
|
||||
<EmptyHeader>
|
||||
<EmptyMedia variant='icon'>
|
||||
<KeyRound aria-hidden='true' />
|
||||
</EmptyMedia>
|
||||
<EmptyTitle>
|
||||
{t('Access tokens are shown only once')}
|
||||
</EmptyTitle>
|
||||
<EmptyDescription>
|
||||
{t(
|
||||
'For security, existing access tokens cannot be displayed. Regenerate only when you need a new token.'
|
||||
)}
|
||||
</EmptyDescription>
|
||||
<EmptyDescription>
|
||||
{t(
|
||||
'Regenerating immediately invalidates any existing token.'
|
||||
)}
|
||||
</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
)}
|
||||
</div>
|
||||
</Dialog>
|
||||
|
||||
<ConfirmDialog
|
||||
open={confirmOpen}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!generating) setConfirmOpen(nextOpen)
|
||||
}}
|
||||
title={t('Regenerate access token?')}
|
||||
desc={
|
||||
<div className='space-y-2'>
|
||||
<p>
|
||||
{t(
|
||||
'This will immediately invalidate your existing access token. Any applications or scripts using it will stop working.'
|
||||
)}
|
||||
</p>
|
||||
<p>
|
||||
{t(
|
||||
'The new token will only be shown once. Copy it and store it securely.'
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
confirmText={
|
||||
generating ? (
|
||||
<>
|
||||
<Loader2 className='h-4 w-4 animate-spin' aria-hidden='true' />
|
||||
{t('Generating...')}
|
||||
</>
|
||||
) : (
|
||||
t('Regenerate token')
|
||||
)
|
||||
}
|
||||
destructive
|
||||
isLoading={generating}
|
||||
handleConfirm={handleGenerate}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { Shield, Key, Trash2 } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { Card, CardContent, CardHeader } from '@/components/ui/card'
|
||||
import { IconBadge } from '@/components/ui/icon-badge'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { TitledCard } from '@/components/ui/titled-card'
|
||||
import { useDialogs } from '@/hooks/use-dialog'
|
||||
|
||||
import type { UserProfile } from '../types'
|
||||
import { AccessTokenDialog } from './dialogs/access-token-dialog'
|
||||
import { ChangePasswordDialog } from './dialogs/change-password-dialog'
|
||||
import { DeleteAccountDialog } from './dialogs/delete-account-dialog'
|
||||
|
||||
// ============================================================================
|
||||
// Profile Security Card Component
|
||||
// ============================================================================
|
||||
|
||||
interface ProfileSecurityCardProps {
|
||||
profile: UserProfile | null
|
||||
loading: boolean
|
||||
}
|
||||
|
||||
type DialogKey = 'password' | 'token' | 'delete'
|
||||
|
||||
export function ProfileSecurityCard({
|
||||
profile,
|
||||
loading,
|
||||
}: ProfileSecurityCardProps) {
|
||||
const { t } = useTranslation()
|
||||
const dialogs = useDialogs<DialogKey>()
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Card data-card-hover='false' className='gap-0 overflow-hidden py-0'>
|
||||
<CardHeader className='border-b p-3 !pb-3 sm:p-5 sm:!pb-5'>
|
||||
<Skeleton className='h-6 w-32' />
|
||||
<Skeleton className='mt-2 h-4 w-48' />
|
||||
</CardHeader>
|
||||
<CardContent className='space-y-3 p-3 sm:p-5'>
|
||||
{['password', 'token', 'delete'].map((key) => (
|
||||
<Skeleton key={key} className='h-16 w-full' />
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
if (!profile) return null
|
||||
|
||||
const securityActions = [
|
||||
{
|
||||
icon: Shield,
|
||||
title: t('Change Password'),
|
||||
description: t('Update your password to keep your account secure'),
|
||||
action: () => dialogs.open('password'),
|
||||
variant: 'default' as const,
|
||||
},
|
||||
{
|
||||
icon: Key,
|
||||
title: t('Access Token'),
|
||||
description: t('Generate and manage your API access token'),
|
||||
action: () => dialogs.open('token'),
|
||||
variant: 'default' as const,
|
||||
},
|
||||
{
|
||||
icon: Trash2,
|
||||
title: t('Delete Account'),
|
||||
description: t('Permanently delete your account and all data'),
|
||||
action: () => dialogs.open('delete'),
|
||||
variant: 'destructive' as const,
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<>
|
||||
<TitledCard
|
||||
title={t('Security')}
|
||||
description={t('Manage your security settings and account access')}
|
||||
icon={<Shield className='h-4 w-4' />}
|
||||
iconTone='success'
|
||||
disableHoverEffect
|
||||
>
|
||||
<div className='grid grid-cols-1 gap-2.5 sm:gap-3 md:grid-cols-3'>
|
||||
{securityActions.map((item) => (
|
||||
<button
|
||||
key={item.title}
|
||||
type='button'
|
||||
onClick={item.action}
|
||||
className={`flex items-center gap-3 rounded-lg border p-3 text-left md:flex-col md:gap-2 md:p-4 md:text-center ${
|
||||
item.variant === 'destructive' ? 'border-destructive/30' : ''
|
||||
}`}
|
||||
>
|
||||
<IconBadge tone='neutral' size='sm'>
|
||||
<item.icon />
|
||||
</IconBadge>
|
||||
<div className='min-w-0 md:contents'>
|
||||
<p className='text-sm font-medium'>{item.title}</p>
|
||||
<p className='text-muted-foreground line-clamp-1 text-xs md:line-clamp-none'>
|
||||
{item.description}
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</TitledCard>
|
||||
|
||||
{/* Dialogs */}
|
||||
<ChangePasswordDialog
|
||||
open={dialogs.isOpen('password')}
|
||||
onOpenChange={(open) =>
|
||||
open ? dialogs.open('password') : dialogs.close('password')
|
||||
}
|
||||
username={profile.username}
|
||||
/>
|
||||
|
||||
<AccessTokenDialog
|
||||
open={dialogs.isOpen('token')}
|
||||
onOpenChange={(open) =>
|
||||
open ? dialogs.open('token') : dialogs.close('token')
|
||||
}
|
||||
/>
|
||||
|
||||
<DeleteAccountDialog
|
||||
open={dialogs.isOpen('delete')}
|
||||
onOpenChange={(open) =>
|
||||
open ? dialogs.open('delete') : dialogs.close('delete')
|
||||
}
|
||||
username={profile.username}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -16,17 +16,14 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { Link2, Settings } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { Settings } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { Card, CardContent, CardHeader } from '@/components/ui/card'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { TitledCard } from '@/components/ui/titled-card'
|
||||
|
||||
import type { UserProfile } from '../types'
|
||||
import { AccountBindingsTab } from './tabs/account-bindings-tab'
|
||||
import { NotificationTab } from './tabs/notification-tab'
|
||||
|
||||
// ============================================================================
|
||||
@@ -45,7 +42,6 @@ export function ProfileSettingsCard({
|
||||
onProfileUpdate,
|
||||
}: ProfileSettingsCardProps) {
|
||||
const { t } = useTranslation()
|
||||
const [activeTab, setActiveTab] = useState('bindings')
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
@@ -55,8 +51,7 @@ export function ProfileSettingsCard({
|
||||
<Skeleton className='mt-2 h-4 w-48' />
|
||||
</CardHeader>
|
||||
<CardContent className='space-y-4 p-3 sm:p-5'>
|
||||
<Skeleton className='h-10 w-full' />
|
||||
{['bindings', 'preferences', 'notifications'].map((key) => (
|
||||
{['notifications', 'threshold', 'preferences'].map((key) => (
|
||||
<Skeleton key={key} className='h-20 w-full' />
|
||||
))}
|
||||
</CardContent>
|
||||
@@ -67,41 +62,12 @@ export function ProfileSettingsCard({
|
||||
return (
|
||||
<TitledCard
|
||||
title={t('Settings')}
|
||||
description={t('Configure your account preferences and integrations')}
|
||||
description={t('Settings & Preferences')}
|
||||
icon={<Settings className='h-4 w-4' />}
|
||||
iconTone='info'
|
||||
disableHoverEffect
|
||||
>
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab}>
|
||||
<TabsList className='grid w-full grid-cols-2 items-stretch gap-1 rounded-xl p-1 group-data-horizontal/tabs:h-10'>
|
||||
<TabsTrigger
|
||||
value='bindings'
|
||||
className='h-full gap-2 rounded-lg px-3 py-0 leading-none'
|
||||
>
|
||||
<Link2 className='h-4 w-4' />
|
||||
<span className='hidden sm:inline'>{t('Account Bindings')}</span>
|
||||
<span className='sm:hidden'>{t('Bindings')}</span>
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
value='settings'
|
||||
className='h-full gap-2 rounded-lg px-3 py-0 leading-none'
|
||||
>
|
||||
<Settings className='h-4 w-4' />
|
||||
<span className='hidden sm:inline'>
|
||||
{t('Settings & Preferences')}
|
||||
</span>
|
||||
<span className='sm:hidden'>{t('Settings')}</span>
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value='bindings' className='mt-4 sm:mt-6'>
|
||||
<AccountBindingsTab profile={profile} onUpdate={onProfileUpdate} />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value='settings' className='mt-4 sm:mt-6'>
|
||||
<NotificationTab profile={profile} onUpdate={onProfileUpdate} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
<NotificationTab profile={profile} onUpdate={onProfileUpdate} />
|
||||
</TitledCard>
|
||||
)
|
||||
}
|
||||
@@ -93,6 +93,11 @@ export function SidebarModulesCard() {
|
||||
title: t('Usage Logs'),
|
||||
description: t('API usage records'),
|
||||
},
|
||||
{
|
||||
key: 'audit',
|
||||
title: t('Audit Logs'),
|
||||
description: t('Login, security and access records'),
|
||||
},
|
||||
{
|
||||
key: 'midjourney',
|
||||
title: t('Drawing Logs'),
|
||||
@@ -120,6 +125,11 @@ export function SidebarModulesCard() {
|
||||
title: t('Personal Settings'),
|
||||
description: t('Personal info settings'),
|
||||
},
|
||||
{
|
||||
key: 'security',
|
||||
title: t('Security & Access'),
|
||||
description: t('Manage your security settings and account access'),
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
@@ -30,12 +30,9 @@ import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'
|
||||
import { ROLE } from '@/lib/roles'
|
||||
|
||||
import { updateUserSettings } from '../../api'
|
||||
import {
|
||||
DEFAULT_QUOTA_WARNING_THRESHOLD,
|
||||
NOTIFICATION_METHODS,
|
||||
} from '../../constants'
|
||||
import { parseUserSettings } from '../../lib'
|
||||
import type { UserProfile, UserSettings, NotifyType } from '../../types'
|
||||
import { NOTIFICATION_METHODS } from '../../constants'
|
||||
import { normalizeUserSettings } from '../../lib/user-settings'
|
||||
import type { UserProfile, NotifyType } from '../../types'
|
||||
|
||||
const NOTIFICATION_ICONS: Record<NotifyType, typeof Mail> = {
|
||||
email: Mail,
|
||||
@@ -44,17 +41,6 @@ const NOTIFICATION_ICONS: Record<NotifyType, typeof Mail> = {
|
||||
gotify: Server,
|
||||
}
|
||||
|
||||
const NOTIFICATION_VALUES = new Set<NotifyType>(
|
||||
NOTIFICATION_METHODS.map((method) => method.value)
|
||||
)
|
||||
|
||||
function normalizeNotifyType(value: unknown): NotifyType {
|
||||
return typeof value === 'string' &&
|
||||
NOTIFICATION_VALUES.has(value as NotifyType)
|
||||
? (value as NotifyType)
|
||||
: 'email'
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Settings Tab Component
|
||||
// ============================================================================
|
||||
@@ -68,24 +54,14 @@ export function NotificationTab({ profile, onUpdate }: NotificationTabProps) {
|
||||
const { t } = useTranslation()
|
||||
const isAdmin = (profile?.role ?? 0) >= ROLE.ADMIN
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [settings, setSettings] = useState<UserSettings>({
|
||||
notify_type: 'email',
|
||||
quota_warning_threshold: DEFAULT_QUOTA_WARNING_THRESHOLD,
|
||||
notification_email: '',
|
||||
webhook_url: '',
|
||||
webhook_secret: '',
|
||||
bark_url: '',
|
||||
gotify_url: '',
|
||||
gotify_token: '',
|
||||
gotify_priority: 5,
|
||||
accept_unset_model_ratio_model: false,
|
||||
record_ip_log: false,
|
||||
upstream_model_update_notify_enabled: false,
|
||||
})
|
||||
const [settings, setSettings] = useState(() => normalizeUserSettings())
|
||||
|
||||
// Update form field helper
|
||||
const updateField = useCallback(
|
||||
<K extends keyof UserSettings>(field: K, value: UserSettings[K]) => {
|
||||
<K extends keyof typeof settings>(
|
||||
field: K,
|
||||
value: (typeof settings)[K]
|
||||
) => {
|
||||
setSettings((prev) => ({ ...prev, [field]: value }))
|
||||
},
|
||||
[]
|
||||
@@ -93,31 +69,15 @@ export function NotificationTab({ profile, onUpdate }: NotificationTabProps) {
|
||||
|
||||
useEffect(() => {
|
||||
if (profile?.setting) {
|
||||
const parsed = parseUserSettings(profile.setting)
|
||||
setSettings({
|
||||
notify_type: normalizeNotifyType(parsed.notify_type),
|
||||
quota_warning_threshold:
|
||||
parsed.quota_warning_threshold ?? DEFAULT_QUOTA_WARNING_THRESHOLD,
|
||||
notification_email: parsed.notification_email ?? '',
|
||||
webhook_url: parsed.webhook_url ?? '',
|
||||
webhook_secret: parsed.webhook_secret ?? '',
|
||||
bark_url: parsed.bark_url ?? '',
|
||||
gotify_url: parsed.gotify_url ?? '',
|
||||
gotify_token: parsed.gotify_token ?? '',
|
||||
gotify_priority: parsed.gotify_priority ?? 5,
|
||||
accept_unset_model_ratio_model:
|
||||
parsed.accept_unset_model_ratio_model || false,
|
||||
record_ip_log: parsed.record_ip_log || false,
|
||||
upstream_model_update_notify_enabled:
|
||||
parsed.upstream_model_update_notify_enabled || false,
|
||||
})
|
||||
setSettings(normalizeUserSettings(profile.setting))
|
||||
}
|
||||
}, [profile])
|
||||
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
setLoading(true)
|
||||
const response = await updateUserSettings(settings)
|
||||
const { record_ip_log: _recordIpLog, ...notificationSettings } = settings
|
||||
const response = await updateUserSettings(notificationSettings)
|
||||
|
||||
if (response.success) {
|
||||
toast.success(t('Settings updated successfully'))
|
||||
@@ -125,14 +85,14 @@ export function NotificationTab({ profile, onUpdate }: NotificationTabProps) {
|
||||
} else {
|
||||
toast.error(response.message || t('Failed to update settings'))
|
||||
}
|
||||
} catch (_error) {
|
||||
} catch {
|
||||
toast.error(t('Failed to update settings'))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const notifyType = normalizeNotifyType(settings.notify_type)
|
||||
const notifyType = settings.notify_type
|
||||
|
||||
return (
|
||||
<div className='space-y-4 sm:space-y-6'>
|
||||
@@ -143,8 +103,7 @@ export function NotificationTab({ profile, onUpdate }: NotificationTabProps) {
|
||||
value={[notifyType]}
|
||||
onValueChange={(value) => {
|
||||
const nextValue = value.find((item) => item !== notifyType)
|
||||
if (nextValue)
|
||||
updateField('notify_type', normalizeNotifyType(nextValue))
|
||||
if (nextValue) updateField('notify_type', nextValue as NotifyType)
|
||||
}}
|
||||
aria-label={t('Notification Method')}
|
||||
variant='outline'
|
||||
@@ -375,22 +334,6 @@ export function NotificationTab({ profile, onUpdate }: NotificationTabProps) {
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Record IP Log */}
|
||||
<div className='flex items-start justify-between gap-3 rounded-lg border p-3 sm:items-center sm:p-4'>
|
||||
<div className='space-y-0.5'>
|
||||
<Label htmlFor='recordIp'>{t('Record IP Address')}</Label>
|
||||
<p className='text-muted-foreground text-xs sm:text-sm'>
|
||||
{t('Log IP address for usage and error logs')}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id='recordIp'
|
||||
className='shrink-0'
|
||||
checked={settings.record_ip_log}
|
||||
onCheckedChange={(checked) => updateField('record_ip_log', checked)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Save Button */}
|
||||
|
||||
@@ -17,5 +17,3 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
export * from './use-profile'
|
||||
export * from './use-access-token'
|
||||
export * from './use-two-fa'
|
||||
@@ -1,71 +0,0 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import i18next from 'i18next'
|
||||
import { useState, useCallback } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import { useCopyToClipboard } from '@/hooks/use-copy-to-clipboard'
|
||||
|
||||
import { generateAccessToken } from '../api'
|
||||
|
||||
// ============================================================================
|
||||
// Access Token Hook
|
||||
// ============================================================================
|
||||
|
||||
export function useAccessToken() {
|
||||
const [token, setToken] = useState<string>('')
|
||||
const [generating, setGenerating] = useState(false)
|
||||
const { copyToClipboard } = useCopyToClipboard({ notify: false })
|
||||
|
||||
// Generate new access token
|
||||
const generate = useCallback(async (): Promise<boolean> => {
|
||||
try {
|
||||
setGenerating(true)
|
||||
const response = await generateAccessToken()
|
||||
|
||||
if (response.success && response.data) {
|
||||
setToken(response.data)
|
||||
copyToClipboard(response.data)
|
||||
toast.success(i18next.t('Token regenerated and copied to clipboard'))
|
||||
return true
|
||||
}
|
||||
|
||||
toast.error(response.message || i18next.t('Failed to generate token'))
|
||||
return false
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('Failed to generate token:', error)
|
||||
toast.error(i18next.t('Failed to generate token'))
|
||||
return false
|
||||
} finally {
|
||||
setGenerating(false)
|
||||
}
|
||||
}, [copyToClipboard])
|
||||
|
||||
const clearToken = useCallback(() => {
|
||||
setToken('')
|
||||
}, [])
|
||||
|
||||
return {
|
||||
token,
|
||||
generating,
|
||||
generate,
|
||||
clearToken,
|
||||
}
|
||||
}
|
||||
@@ -26,13 +26,9 @@ import { useAuthStore } from '@/stores/auth-store'
|
||||
|
||||
import { CheckinCalendarCard } from './components/checkin-calendar-card'
|
||||
import { LanguagePreferencesCard } from './components/language-preferences-card'
|
||||
import { LoginSessionsCard } from './components/login-sessions-card'
|
||||
import { PasskeyCard } from './components/passkey-card'
|
||||
import { ProfileHeader } from './components/profile-header'
|
||||
import { ProfileSecurityCard } from './components/profile-security-card'
|
||||
import { ProfileSettingsCard } from './components/profile-settings-card'
|
||||
import { SidebarModulesCard } from './components/sidebar-modules-card'
|
||||
import { TwoFACard } from './components/two-fa-card'
|
||||
import { useProfile } from './hooks'
|
||||
|
||||
export function Profile() {
|
||||
@@ -67,8 +63,6 @@ export function Profile() {
|
||||
profile={profile}
|
||||
onProfileUpdate={refreshProfile}
|
||||
/>
|
||||
<ProfileSecurityCard profile={profile} loading={loading} />
|
||||
<LoginSessionsCard />
|
||||
</div>
|
||||
|
||||
<div className='space-y-4 sm:space-y-6 xl:sticky xl:top-6'>
|
||||
@@ -80,8 +74,6 @@ export function Profile() {
|
||||
/>
|
||||
)}
|
||||
{canConfigureSidebar && <SidebarModulesCard />}
|
||||
<PasskeyCard loading={loading} />
|
||||
<TwoFACard loading={loading} />
|
||||
</div>
|
||||
</div>
|
||||
</CardStaggerItem>
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import {
|
||||
DEFAULT_QUOTA_WARNING_THRESHOLD,
|
||||
NOTIFICATION_METHODS,
|
||||
} from '../constants'
|
||||
import type { NotifyType, UpdateUserSettingsRequest } from '../types'
|
||||
import { parseUserSettings } from './format'
|
||||
|
||||
export function normalizeUserSettings(
|
||||
setting?: string
|
||||
): Required<UpdateUserSettingsRequest> & { notify_type: NotifyType } {
|
||||
const parsed = parseUserSettings(setting)
|
||||
const notifyType =
|
||||
NOTIFICATION_METHODS.find((method) => method.value === parsed.notify_type)
|
||||
?.value ?? 'email'
|
||||
return {
|
||||
notify_type: notifyType,
|
||||
quota_warning_threshold:
|
||||
parsed.quota_warning_threshold ?? DEFAULT_QUOTA_WARNING_THRESHOLD,
|
||||
notification_email: parsed.notification_email ?? '',
|
||||
webhook_url: parsed.webhook_url ?? '',
|
||||
webhook_secret: parsed.webhook_secret ?? '',
|
||||
bark_url: parsed.bark_url ?? '',
|
||||
gotify_url: parsed.gotify_url ?? '',
|
||||
gotify_token: parsed.gotify_token ?? '',
|
||||
gotify_priority: parsed.gotify_priority ?? 5,
|
||||
accept_unset_model_ratio_model:
|
||||
parsed.accept_unset_model_ratio_model || false,
|
||||
record_ip_log: parsed.record_ip_log || false,
|
||||
upstream_model_update_notify_enabled:
|
||||
parsed.upstream_model_update_notify_enabled || false,
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import type { UserPermissions } from '@/stores/auth-store'
|
||||
|
||||
// ============================================================================
|
||||
// Profile Type Definitions
|
||||
// ============================================================================
|
||||
@@ -33,6 +35,7 @@ export interface ApiResponse<T = unknown> {
|
||||
* User profile data
|
||||
*/
|
||||
export interface UserProfile {
|
||||
permissions?: UserPermissions
|
||||
/** User ID */
|
||||
id: number
|
||||
/** Username */
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import {
|
||||
createMemoryHistory,
|
||||
createRootRoute,
|
||||
createRoute,
|
||||
createRouter,
|
||||
RouterProvider,
|
||||
} from '@tanstack/react-router'
|
||||
import {
|
||||
cleanup,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
within,
|
||||
} from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { Profile } from '@/features/profile'
|
||||
import type { UserProfile } from '@/features/profile/types'
|
||||
import { api } from '@/lib/api'
|
||||
import { useAuthStore } from '@/stores/auth-store'
|
||||
|
||||
import { Security } from '../index'
|
||||
|
||||
const profile: UserProfile = {
|
||||
id: 1,
|
||||
username: 'alice',
|
||||
display_name: 'Alice',
|
||||
role: 1,
|
||||
group: 'default',
|
||||
quota: 1000000,
|
||||
used_quota: 0,
|
||||
request_count: 0,
|
||||
status: 1,
|
||||
aff_count: 0,
|
||||
aff_quota: 0,
|
||||
aff_history_quota: 0,
|
||||
created_time: 0,
|
||||
setting: JSON.stringify({
|
||||
notify_type: 'email',
|
||||
quota_warning_threshold: 500000,
|
||||
}),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('localStorage', {
|
||||
getItem: () => null,
|
||||
setItem: () => undefined,
|
||||
removeItem: () => undefined,
|
||||
})
|
||||
vi.spyOn(window, 'scrollTo').mockImplementation(() => undefined)
|
||||
useAuthStore
|
||||
.getState()
|
||||
.auth.setUser({ ...profile, permissions: { sidebar_settings: false } })
|
||||
vi.spyOn(api, 'get').mockImplementation(async (url) => {
|
||||
if (url === '/api/user/token/status') {
|
||||
return {
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
exists: false,
|
||||
token_ref: '',
|
||||
created_at: null,
|
||||
last_used_at: null,
|
||||
last_used_ip: '',
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
if (url === '/api/user/self') {
|
||||
return { data: { success: true, data: profile } }
|
||||
}
|
||||
if (url === '/api/user/passkey') {
|
||||
return { data: { success: true, data: { enabled: false } } }
|
||||
}
|
||||
if (url === '/api/user/2fa/status') {
|
||||
return {
|
||||
data: {
|
||||
success: true,
|
||||
data: { enabled: false, locked: false, backup_codes_remaining: 0 },
|
||||
},
|
||||
}
|
||||
}
|
||||
if (url === '/api/user/sessions') {
|
||||
return { data: { success: true, data: [] } }
|
||||
}
|
||||
throw new Error(`Unexpected GET ${url}`)
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.unstubAllGlobals()
|
||||
useAuthStore.getState().auth.reset()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function renderPage(path = '/security') {
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
client.setQueryData(['status'], {
|
||||
checkin_enabled: false,
|
||||
wechat_login: true,
|
||||
github_oauth: true,
|
||||
oidc_enabled: true,
|
||||
custom_oauth_providers: [
|
||||
{
|
||||
id: 1,
|
||||
name: 'Gitea',
|
||||
slug: 'gitea',
|
||||
client_id: 'test-client',
|
||||
authorization_endpoint: 'https://example.com/oauth/authorize',
|
||||
scopes: 'openid',
|
||||
},
|
||||
],
|
||||
})
|
||||
const root = createRootRoute()
|
||||
const security = createRoute({
|
||||
getParentRoute: () => root,
|
||||
path: '/security',
|
||||
component: Security,
|
||||
})
|
||||
const personal = createRoute({
|
||||
getParentRoute: () => root,
|
||||
path: '/profile',
|
||||
component: Profile,
|
||||
})
|
||||
const router = createRouter({
|
||||
routeTree: root.addChildren([security, personal]),
|
||||
history: createMemoryHistory({ initialEntries: [path] }),
|
||||
})
|
||||
await router.load()
|
||||
const rendered = render(
|
||||
<QueryClientProvider client={client}>
|
||||
<RouterProvider router={router} />
|
||||
</QueryClientProvider>
|
||||
)
|
||||
return { ...rendered, router }
|
||||
}
|
||||
|
||||
describe('security page migration', () => {
|
||||
it('places account management on the left and verification and privacy on the right', async () => {
|
||||
await renderPage()
|
||||
const login = await screen.findByRole('region', {
|
||||
name: 'Login & Authentication',
|
||||
})
|
||||
expect(
|
||||
screen
|
||||
.getAllByRole('region')
|
||||
.map((region) => within(region).getAllByRole('heading')[0].textContent)
|
||||
).toEqual([
|
||||
'Login & Authentication',
|
||||
'Sessions & Access',
|
||||
'Account Actions',
|
||||
'Privacy',
|
||||
])
|
||||
expect(
|
||||
within(login).getByRole('button', { name: 'Change Password' })
|
||||
).toBeVisible()
|
||||
expect(within(login).getByText('Account Bindings')).toBeVisible()
|
||||
const verification = screen.getByRole('complementary', {
|
||||
name: 'Security verification',
|
||||
})
|
||||
expect(await within(verification).findByText('Passkey Login')).toBeVisible()
|
||||
expect(
|
||||
await within(verification).findByText('Two-Factor Authentication')
|
||||
).toBeVisible()
|
||||
expect(
|
||||
within(verification).getByRole('switch', { name: 'Record IP Address' })
|
||||
).toBeVisible()
|
||||
expect(verification).toHaveClass('xl:sticky', 'xl:top-0')
|
||||
expect(verification.parentElement).toHaveClass(
|
||||
'grid',
|
||||
'xl:grid-cols-[minmax(0,1fr)_minmax(360px,0.46fr)]'
|
||||
)
|
||||
const access = screen.getByRole('region', { name: 'Sessions & Access' })
|
||||
expect(
|
||||
within(access).getByRole('heading', { name: 'Access Token' })
|
||||
).toBeVisible()
|
||||
expect(
|
||||
await within(access).findByText('No active login sessions')
|
||||
).toBeVisible()
|
||||
expect(
|
||||
screen.getByRole('switch', { name: 'Record IP Address' })
|
||||
).toBeVisible()
|
||||
expect(
|
||||
within(screen.getByRole('region', { name: 'Account Actions' })).getByRole(
|
||||
'button',
|
||||
{ name: 'Delete Account' }
|
||||
)
|
||||
).toBeVisible()
|
||||
})
|
||||
|
||||
it('built-in and custom bindings share one compact responsive grid', async () => {
|
||||
await renderPage()
|
||||
const bindings = await screen.findByRole('list', {
|
||||
name: 'Account Bindings',
|
||||
})
|
||||
expect(within(bindings).getAllByRole('listitem')).toHaveLength(5)
|
||||
expect(within(bindings).getByText('Gitea')).toBeVisible()
|
||||
expect(bindings).toHaveClass(
|
||||
'grid-cols-1',
|
||||
'sm:grid-cols-2',
|
||||
'lg:grid-cols-3',
|
||||
'gap-2'
|
||||
)
|
||||
expect(screen.queryByText('Custom OAuth')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('the password action opens the existing dialog by keyboard and Escape closes it', async () => {
|
||||
const user = userEvent.setup()
|
||||
await renderPage()
|
||||
const action = await screen.findByRole('button', {
|
||||
name: 'Change Password',
|
||||
})
|
||||
action.focus()
|
||||
await user.keyboard('{Enter}')
|
||||
const dialog = await screen.findByRole('dialog', {
|
||||
name: 'Change Password',
|
||||
})
|
||||
expect(within(dialog).getByLabelText('Current Password')).toBeVisible()
|
||||
expect(
|
||||
within(dialog).getByLabelText('New Password', { exact: true })
|
||||
).toBeVisible()
|
||||
await user.keyboard('{Escape}')
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
)
|
||||
})
|
||||
|
||||
it('Profile retains preferences and no longer mounts security controls or requests', async () => {
|
||||
await renderPage('/profile')
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'Save Settings' })
|
||||
).toBeVisible()
|
||||
)
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'Change Password' })
|
||||
).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Account Bindings')).not.toBeInTheDocument()
|
||||
expect(
|
||||
screen.queryByRole('switch', { name: 'Record IP Address' })
|
||||
).not.toBeInTheDocument()
|
||||
expect(api.get).not.toHaveBeenCalledWith('/api/user/passkey')
|
||||
expect(api.get).not.toHaveBeenCalledWith('/api/user/2fa/status')
|
||||
expect(api.get).not.toHaveBeenCalledWith('/api/user/sessions')
|
||||
})
|
||||
|
||||
it('a failed profile load offers retry before exposing account actions', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: { success: false } })
|
||||
const user = userEvent.setup()
|
||||
await renderPage()
|
||||
expect(await screen.findByText('Failed to load profile')).toBeVisible()
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'Delete Account' })
|
||||
).not.toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'Retry' }))
|
||||
expect(
|
||||
await screen.findByRole('button', { name: 'Delete Account' })
|
||||
).toBeVisible()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import type { ApiResponse } from '@/features/profile/types'
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
export interface AccessTokenStatus {
|
||||
exists: boolean
|
||||
token_ref: string
|
||||
created_at: number | null
|
||||
last_used_at: number | null
|
||||
last_used_ip: string
|
||||
}
|
||||
|
||||
export async function getAccessTokenStatus(): Promise<AccessTokenStatus> {
|
||||
const response = await api.get<ApiResponse<AccessTokenStatus>>(
|
||||
'/api/user/token/status'
|
||||
)
|
||||
if (!response.data.success || !response.data.data) {
|
||||
throw new Error(response.data.message || 'Failed to load token status')
|
||||
}
|
||||
return response.data.data
|
||||
}
|
||||
|
||||
export async function createAccessToken(): Promise<string> {
|
||||
const response = await api.post<ApiResponse<string>>('/api/user/token')
|
||||
if (!response.data.success || !response.data.data) {
|
||||
throw new Error(response.data.message || 'Failed to generate token')
|
||||
}
|
||||
return response.data.data
|
||||
}
|
||||
|
||||
export async function revokeAccessToken(): Promise<void> {
|
||||
const response = await api.delete<ApiResponse>('/api/user/token')
|
||||
if (!response.data.success) {
|
||||
throw new Error(response.data.message || 'Failed to revoke token')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import {
|
||||
cleanup,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
within,
|
||||
} from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { Toaster, toast } from 'sonner'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { api } from '@/lib/api'
|
||||
import { useAuthStore } from '@/stores/auth-store'
|
||||
|
||||
import type { AccessTokenStatus } from '../../api'
|
||||
import { AccessTokenCard } from '../access-token-card'
|
||||
|
||||
let status: AccessTokenStatus
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('localStorage', {
|
||||
getItem: () => null,
|
||||
setItem: () => undefined,
|
||||
removeItem: () => undefined,
|
||||
})
|
||||
status = {
|
||||
exists: false,
|
||||
token_ref: '',
|
||||
created_at: null,
|
||||
last_used_at: null,
|
||||
last_used_ip: '',
|
||||
}
|
||||
vi.spyOn(api, 'get').mockImplementation(async (url) => {
|
||||
if (url === '/api/audit/self') {
|
||||
return { data: { success: true, data: { items: [], total: 0 } } }
|
||||
}
|
||||
return { data: { success: true, data: status } }
|
||||
})
|
||||
})
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
useAuthStore.getState().auth.reset()
|
||||
toast.dismiss()
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
function renderCard() {
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
})
|
||||
render(
|
||||
<QueryClientProvider client={client}>
|
||||
<AccessTokenCard />
|
||||
<Toaster />
|
||||
</QueryClientProvider>
|
||||
)
|
||||
return client
|
||||
}
|
||||
|
||||
describe('system access token management', () => {
|
||||
it('generates a missing token and clears the one-time plaintext on Escape', async () => {
|
||||
const token = 'one-time-private-token'
|
||||
vi.spyOn(api, 'post').mockImplementation(async () => {
|
||||
status = {
|
||||
...status,
|
||||
exists: true,
|
||||
token_ref: 'a'.repeat(64),
|
||||
created_at: 1700000000,
|
||||
}
|
||||
return { data: { success: true, data: token } }
|
||||
})
|
||||
const client = renderCard()
|
||||
const user = userEvent.setup()
|
||||
await user.click(await screen.findByRole('button', { name: 'Generate' }))
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Access Token' })
|
||||
expect(within(dialog).getByLabelText('Token')).toHaveValue(token)
|
||||
expect(api.post).toHaveBeenCalledWith('/api/user/token')
|
||||
await user.keyboard('{Escape}')
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByDisplayValue(token)).not.toBeInTheDocument()
|
||||
)
|
||||
expect(
|
||||
JSON.stringify(
|
||||
client
|
||||
.getQueryCache()
|
||||
.getAll()
|
||||
.map((entry) => entry.state.data)
|
||||
)
|
||||
).not.toContain(token)
|
||||
expect(
|
||||
JSON.stringify(
|
||||
client
|
||||
.getMutationCache()
|
||||
.getAll()
|
||||
.map((entry) => entry.state.data)
|
||||
)
|
||||
).not.toContain(token)
|
||||
expect(await screen.findByText('Not used yet')).toBeVisible()
|
||||
})
|
||||
|
||||
it('legacy tokens show unknown creation and usage until records exist', async () => {
|
||||
status = { ...status, exists: true, token_ref: 'a'.repeat(64) }
|
||||
renderCard()
|
||||
expect(await screen.findAllByText('Unknown')).toHaveLength(2)
|
||||
expect(screen.queryByText('Not used yet')).not.toBeInTheDocument()
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'Generate' })
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('status failures offer retry without asserting that a token is missing or unused', async () => {
|
||||
vi.mocked(api.get).mockRejectedValueOnce(new Error('offline'))
|
||||
renderCard()
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(
|
||||
'Failed to load token status'
|
||||
)
|
||||
expect(screen.queryByText('Not generated')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Not used yet')).not.toBeInTheDocument()
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'Generate' })
|
||||
).not.toBeInTheDocument()
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Retry' }))
|
||||
expect(await screen.findByText('Not generated')).toBeVisible()
|
||||
})
|
||||
|
||||
it('rotation requires confirmation and a failed rotation keeps the existing token state', async () => {
|
||||
status = { ...status, exists: true, token_ref: 'a'.repeat(64) }
|
||||
const post = vi
|
||||
.spyOn(api, 'post')
|
||||
.mockResolvedValue({ data: { success: false } })
|
||||
renderCard()
|
||||
const user = userEvent.setup()
|
||||
await user.click(await screen.findByRole('button', { name: 'Regenerate' }))
|
||||
const confirmation = await screen.findByRole('alertdialog')
|
||||
expect(post).not.toHaveBeenCalled()
|
||||
await user.click(
|
||||
within(confirmation).getByRole('button', { name: 'Regenerate token' })
|
||||
)
|
||||
expect(await screen.findByText('Failed to generate token')).toBeVisible()
|
||||
expect(
|
||||
screen.queryByRole('dialog', { name: 'Access Token' })
|
||||
).not.toBeInTheDocument()
|
||||
expect(screen.getByText('Generated')).toBeVisible()
|
||||
})
|
||||
|
||||
it('revocation failures can be retried and success restores the generate action', async () => {
|
||||
status = { ...status, exists: true, token_ref: 'a'.repeat(64) }
|
||||
vi.spyOn(api, 'delete')
|
||||
.mockRejectedValueOnce(new Error('offline'))
|
||||
.mockImplementation(async () => {
|
||||
status = { ...status, exists: false, token_ref: '' }
|
||||
return { data: { success: true } }
|
||||
})
|
||||
renderCard()
|
||||
const user = userEvent.setup()
|
||||
await user.click(await screen.findByRole('button', { name: 'Revoke' }))
|
||||
const confirm = within(await screen.findByRole('alertdialog')).getByRole(
|
||||
'button',
|
||||
{ name: 'Revoke' }
|
||||
)
|
||||
await user.click(confirm)
|
||||
expect(await screen.findByText('Failed to revoke token')).toBeVisible()
|
||||
await waitFor(() => expect(confirm).toBeEnabled())
|
||||
await user.click(confirm)
|
||||
expect(
|
||||
await screen.findByRole('button', { name: 'Generate' })
|
||||
).toBeVisible()
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
|
||||
)
|
||||
})
|
||||
|
||||
it('access history opens by keyboard in a full-width mobile sheet and Escape closes it', async () => {
|
||||
useAuthStore
|
||||
.getState()
|
||||
.auth.setUser({ id: 1, username: 'admin', role: 100 })
|
||||
renderCard()
|
||||
const user = userEvent.setup()
|
||||
const trigger = screen.getByRole('button', { name: 'Access records' })
|
||||
trigger.focus()
|
||||
await user.keyboard('{Enter}')
|
||||
const sheet = await screen.findByRole('dialog', { name: 'Access records' })
|
||||
expect(sheet).toHaveClass('w-full', 'sm:max-w-5xl')
|
||||
await waitFor(() =>
|
||||
expect(api.get).toHaveBeenCalledWith('/api/audit/self', {
|
||||
params: expect.objectContaining({ category: 'access_token' }),
|
||||
})
|
||||
)
|
||||
expect(api.get).not.toHaveBeenCalledWith('/api/audit', expect.anything())
|
||||
expect(
|
||||
within(sheet).queryByRole('tablist', { name: 'View scope' })
|
||||
).not.toBeInTheDocument()
|
||||
expect(
|
||||
within(sheet).getByRole('combobox', { name: 'Token scope' })
|
||||
).toBeVisible()
|
||||
await user.keyboard('{Escape}')
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
)
|
||||
expect(trigger).toHaveFocus()
|
||||
})
|
||||
})
|
||||
File renamed without changes.
@@ -0,0 +1,120 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { Toaster, toast } from 'sonner'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type { UserProfile } from '@/features/profile/types'
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
import { PrivacyCard } from '../privacy-card'
|
||||
|
||||
const profile: UserProfile = {
|
||||
id: 1,
|
||||
username: 'alice',
|
||||
display_name: 'Alice',
|
||||
role: 1,
|
||||
group: 'default',
|
||||
quota: 1000000,
|
||||
used_quota: 0,
|
||||
request_count: 0,
|
||||
status: 1,
|
||||
aff_count: 0,
|
||||
aff_quota: 0,
|
||||
aff_history_quota: 0,
|
||||
created_time: 0,
|
||||
setting: JSON.stringify({ record_ip_log: true }),
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
toast.dismiss()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
function renderPrivacy() {
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
})
|
||||
const onUpdate = vi.fn()
|
||||
const rendered = render(
|
||||
<QueryClientProvider client={client}>
|
||||
<PrivacyCard profile={profile} onUpdate={onUpdate} />
|
||||
<Toaster />
|
||||
</QueryClientProvider>
|
||||
)
|
||||
return { ...rendered, onUpdate }
|
||||
}
|
||||
|
||||
describe('privacy settings', () => {
|
||||
it('keyboard toggling off saves false and refreshes the displayed profile', async () => {
|
||||
vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: { success: true, data: profile },
|
||||
})
|
||||
const put = vi
|
||||
.spyOn(api, 'put')
|
||||
.mockResolvedValue({ data: { success: true } })
|
||||
const user = userEvent.setup()
|
||||
const { onUpdate } = renderPrivacy()
|
||||
const toggle = screen.getByRole('switch', { name: 'Record IP Address' })
|
||||
expect(toggle).toBeChecked()
|
||||
toggle.focus()
|
||||
await user.keyboard(' ')
|
||||
expect(toggle).not.toBeChecked()
|
||||
await user.click(screen.getByRole('button', { name: 'Save Settings' }))
|
||||
await waitFor(() => expect(onUpdate).toHaveBeenCalled())
|
||||
expect(put).toHaveBeenCalledWith(
|
||||
'/api/user/setting',
|
||||
expect.objectContaining({ record_ip_log: false })
|
||||
)
|
||||
})
|
||||
|
||||
it('failed configuration reads preserve the edited toggle and do not submit or refresh', async () => {
|
||||
vi.spyOn(api, 'get').mockRejectedValue(new Error('offline'))
|
||||
const put = vi.spyOn(api, 'put')
|
||||
const user = userEvent.setup()
|
||||
const { onUpdate } = renderPrivacy()
|
||||
await user.click(screen.getByRole('switch', { name: 'Record IP Address' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Save Settings' }))
|
||||
expect(await screen.findByText('Failed to update settings')).toBeVisible()
|
||||
expect(put).not.toHaveBeenCalled()
|
||||
expect(onUpdate).not.toHaveBeenCalled()
|
||||
expect(
|
||||
screen.getByRole('switch', { name: 'Record IP Address' })
|
||||
).not.toBeChecked()
|
||||
expect(screen.getByRole('button', { name: 'Save Settings' })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('failed saves keep the draft available for retry without refreshing the profile', async () => {
|
||||
vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: { success: true, data: profile },
|
||||
})
|
||||
vi.spyOn(api, 'put').mockResolvedValue({ data: { success: false } })
|
||||
const user = userEvent.setup()
|
||||
const { onUpdate } = renderPrivacy()
|
||||
await user.click(screen.getByRole('switch', { name: 'Record IP Address' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Save Settings' }))
|
||||
expect(await screen.findByText('Failed to update settings')).toBeVisible()
|
||||
expect(onUpdate).not.toHaveBeenCalled()
|
||||
expect(
|
||||
screen.getByRole('switch', { name: 'Record IP Address' })
|
||||
).not.toBeChecked()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,221 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card } from '@/components/ui/card'
|
||||
import {
|
||||
Sheet,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from '@/components/ui/sheet'
|
||||
import { AuditLogViewer } from '@/features/usage-logs/audit/components/audit-log-viewer'
|
||||
import dayjs from '@/lib/dayjs'
|
||||
|
||||
import { useAccessToken } from '../hooks/use-access-token'
|
||||
import { AccessTokenDialog } from './dialogs/access-token-dialog'
|
||||
|
||||
export function AccessTokenCard() {
|
||||
const { t } = useTranslation()
|
||||
const access = useAccessToken()
|
||||
const [confirmation, setConfirmation] = useState<'rotate' | 'revoke' | null>(
|
||||
null
|
||||
)
|
||||
const [historyOpen, setHistoryOpen] = useState(false)
|
||||
const pending = access.generate.isPending || access.revoke.isPending
|
||||
const status = access.status.data
|
||||
const ready = !access.status.isError && !access.status.isPending && !!status
|
||||
let lastUsed = t('Unknown')
|
||||
if (status?.last_used_at) {
|
||||
lastUsed = dayjs.unix(status.last_used_at).format('YYYY-MM-DD HH:mm:ss')
|
||||
} else if (status?.created_at) lastUsed = t('Not used yet')
|
||||
const confirm = async () => {
|
||||
try {
|
||||
if (confirmation === 'revoke') await access.revoke.mutateAsync()
|
||||
else await access.generate.mutateAsync()
|
||||
setConfirmation(null)
|
||||
} catch {
|
||||
/* The mutation displays the error and preserves the confirmation. */
|
||||
}
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<Card data-card-hover='false' className='gap-3 p-3 sm:p-4'>
|
||||
<div className='flex flex-wrap items-center justify-between gap-2'>
|
||||
<h4 className='text-sm font-semibold'>{t('Access Token')}</h4>
|
||||
<Button
|
||||
size='sm'
|
||||
variant='outline'
|
||||
onClick={() => setHistoryOpen(true)}
|
||||
>
|
||||
{t('Access records')}
|
||||
</Button>
|
||||
</div>
|
||||
{access.status.isPending && (
|
||||
<p role='status' className='text-muted-foreground text-xs'>
|
||||
{t('Loading...')}
|
||||
</p>
|
||||
)}
|
||||
{access.status.isError && (
|
||||
<div role='alert' className='flex flex-wrap items-center gap-2'>
|
||||
<span className='text-destructive text-sm'>
|
||||
{t('Failed to load token status')}
|
||||
</span>
|
||||
<Button
|
||||
size='sm'
|
||||
variant='outline'
|
||||
disabled={access.status.isFetching}
|
||||
onClick={() => void access.status.refetch()}
|
||||
>
|
||||
{t('Retry')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{ready && (
|
||||
<>
|
||||
<dl className='grid grid-cols-2 gap-x-4 gap-y-2 text-xs sm:grid-cols-4'>
|
||||
<div>
|
||||
<dt className='text-muted-foreground'>{t('Status')}</dt>
|
||||
<dd className='mt-1 font-medium'>
|
||||
{status.exists ? t('Generated') : t('Not generated')}
|
||||
</dd>
|
||||
</div>
|
||||
{status.exists && (
|
||||
<>
|
||||
<div>
|
||||
<dt className='text-muted-foreground'>{t('Created At')}</dt>
|
||||
<dd className='mt-1'>
|
||||
{status.created_at
|
||||
? dayjs
|
||||
.unix(status.created_at)
|
||||
.format('YYYY-MM-DD HH:mm:ss')
|
||||
: t('Unknown')}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className='text-muted-foreground'>{t('Last used')}</dt>
|
||||
<dd className='mt-1'>{lastUsed}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className='text-muted-foreground'>
|
||||
{t('Last used IP')}
|
||||
</dt>
|
||||
<dd className='mt-1 break-all'>
|
||||
{status.last_used_ip || '—'}
|
||||
</dd>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
<div className='flex flex-wrap justify-end gap-2'>
|
||||
{status.exists ? (
|
||||
<>
|
||||
<Button
|
||||
size='sm'
|
||||
variant='outline'
|
||||
disabled={pending}
|
||||
onClick={() => setConfirmation('rotate')}
|
||||
>
|
||||
{t('Regenerate')}
|
||||
</Button>
|
||||
<Button
|
||||
size='sm'
|
||||
variant='destructive'
|
||||
disabled={pending}
|
||||
onClick={() => setConfirmation('revoke')}
|
||||
>
|
||||
{t('Revoke')}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button
|
||||
size='sm'
|
||||
disabled={pending}
|
||||
onClick={() => access.generate.mutate()}
|
||||
>
|
||||
{t('Generate')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
{access.token && (
|
||||
<AccessTokenDialog token={access.token} onClose={access.clearToken} />
|
||||
)}
|
||||
<ConfirmDialog
|
||||
open={confirmation !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open && !pending) setConfirmation(null)
|
||||
}}
|
||||
title={
|
||||
confirmation === 'revoke'
|
||||
? t('Revoke access token?')
|
||||
: t('Regenerate access token?')
|
||||
}
|
||||
desc={t(
|
||||
'This will immediately invalidate your existing access token. Any applications or scripts using it will stop working.'
|
||||
)}
|
||||
confirmText={
|
||||
confirmation === 'revoke' ? t('Revoke') : t('Regenerate token')
|
||||
}
|
||||
destructive
|
||||
isLoading={pending}
|
||||
handleConfirm={() => void confirm()}
|
||||
/>
|
||||
<Sheet open={historyOpen} onOpenChange={setHistoryOpen}>
|
||||
<SheetContent className='w-full sm:max-w-5xl' showCloseButton={false}>
|
||||
<SheetHeader className='border-b pr-20'>
|
||||
<SheetTitle>{t('Access records')}</SheetTitle>
|
||||
<SheetDescription>
|
||||
{t(
|
||||
'Audit records start after this feature was enabled. Earlier records remain in Common Logs.'
|
||||
)}
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
<SheetClose
|
||||
render={
|
||||
<Button
|
||||
size='sm'
|
||||
variant='ghost'
|
||||
className='absolute top-3 right-3'
|
||||
/>
|
||||
}
|
||||
>
|
||||
{t('Close')}
|
||||
</SheetClose>
|
||||
<div className='min-h-0 flex-1 px-4 pb-4'>
|
||||
{historyOpen && (
|
||||
<AuditLogViewer
|
||||
scope='self'
|
||||
accessOnly
|
||||
currentTokenRef={ready ? status.token_ref : undefined}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { Shield, Trash2 } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card } from '@/components/ui/card'
|
||||
import { IconBadge } from '@/components/ui/icon-badge'
|
||||
|
||||
import { ChangePasswordDialog } from './dialogs/change-password-dialog'
|
||||
import { DeleteAccountDialog } from './dialogs/delete-account-dialog'
|
||||
|
||||
type AccountActionCardProps = {
|
||||
action: 'password' | 'delete'
|
||||
username: string
|
||||
}
|
||||
|
||||
export function AccountActionCard(props: AccountActionCardProps) {
|
||||
const { t } = useTranslation()
|
||||
const [open, setOpen] = useState(false)
|
||||
const actions = {
|
||||
password: {
|
||||
title: t('Change Password'),
|
||||
description: t('Update your password to keep your account secure'),
|
||||
icon: Shield,
|
||||
},
|
||||
delete: {
|
||||
title: t('Delete Account'),
|
||||
description: t('Permanently delete your account and all data'),
|
||||
icon: Trash2,
|
||||
},
|
||||
}
|
||||
const action = actions[props.action]
|
||||
return (
|
||||
<>
|
||||
<Card
|
||||
data-card-hover='false'
|
||||
className={`gap-0 py-0 ${props.action === 'delete' ? 'ring-destructive/30' : ''}`}
|
||||
>
|
||||
<div className='flex items-center gap-3 px-3 py-2.5 sm:px-4'>
|
||||
<IconBadge tone='neutral' size='sm'>
|
||||
<action.icon />
|
||||
</IconBadge>
|
||||
<div className='min-w-0 flex-1 space-y-0.5'>
|
||||
<p className='text-sm font-medium'>{action.title}</p>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{action.description}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
type='button'
|
||||
size='sm'
|
||||
variant={props.action === 'delete' ? 'destructive' : 'outline'}
|
||||
onClick={() => setOpen(true)}
|
||||
>
|
||||
{action.title}
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
{props.action === 'password' && (
|
||||
<ChangePasswordDialog
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
username={props.username}
|
||||
/>
|
||||
)}
|
||||
{props.action === 'delete' && (
|
||||
<DeleteAccountDialog
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
username={props.username}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
+80
-83
@@ -26,7 +26,6 @@ import { IconDiscord } from '@/assets/brand-icons'
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog'
|
||||
import { StatusBadge } from '@/components/status-badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { createOAuthFlow } from '@/features/auth/api'
|
||||
import {
|
||||
OAUTH_BIND_CALLBACK_MESSAGE,
|
||||
@@ -38,6 +37,8 @@ import {
|
||||
markOAuthBindPopup,
|
||||
} from '@/features/auth/lib/oauth-callback-mode'
|
||||
import type { CustomOAuthProviderInfo } from '@/features/auth/types'
|
||||
import { getSelfOAuthBindings, unbindCustomOAuth } from '@/features/profile/api'
|
||||
import type { UserProfile, BindingItem } from '@/features/profile/types'
|
||||
import { useDialogs } from '@/hooks/use-dialog'
|
||||
import { useStatus } from '@/hooks/use-status'
|
||||
import { api } from '@/lib/api'
|
||||
@@ -50,17 +51,15 @@ import {
|
||||
type CustomOAuthBinding,
|
||||
} from '@/lib/oauth'
|
||||
|
||||
import { getSelfOAuthBindings, unbindCustomOAuth } from '../../api'
|
||||
import type { UserProfile, BindingItem } from '../../types'
|
||||
import { EmailBindDialog } from '../dialogs/email-bind-dialog'
|
||||
import { TelegramBindDialog } from '../dialogs/telegram-bind-dialog'
|
||||
import { WeChatBindDialog } from '../dialogs/wechat-bind-dialog'
|
||||
import { EmailBindDialog } from './dialogs/email-bind-dialog'
|
||||
import { TelegramBindDialog } from './dialogs/telegram-bind-dialog'
|
||||
import { WeChatBindDialog } from './dialogs/wechat-bind-dialog'
|
||||
|
||||
// ============================================================================
|
||||
// Account Bindings Tab Component
|
||||
// ============================================================================
|
||||
|
||||
interface AccountBindingsTabProps {
|
||||
interface AccountBindingsProps {
|
||||
profile: UserProfile | null
|
||||
onUpdate: () => void
|
||||
}
|
||||
@@ -83,10 +82,7 @@ interface OAuthBindingCallback {
|
||||
errorDescription?: string
|
||||
}
|
||||
|
||||
export function AccountBindingsTab({
|
||||
profile,
|
||||
onUpdate,
|
||||
}: AccountBindingsTabProps) {
|
||||
export function AccountBindings({ profile, onUpdate }: AccountBindingsProps) {
|
||||
const { t } = useTranslation()
|
||||
const dialogs = useDialogs<DialogKey>()
|
||||
const { status, loading } = useStatus()
|
||||
@@ -419,7 +415,10 @@ export function AccountBindingsTab({
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='grid grid-cols-1 gap-2.5 sm:grid-cols-2 sm:gap-3'>
|
||||
<ul
|
||||
aria-label={t('Account Bindings')}
|
||||
className='grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-3'
|
||||
>
|
||||
{bindings.map((binding) => {
|
||||
let actionLabel = t('Bind')
|
||||
if (binding.isBound && binding.id === 'email') {
|
||||
@@ -429,17 +428,22 @@ export function AccountBindingsTab({
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
<li
|
||||
key={binding.id}
|
||||
className='flex items-center justify-between gap-2.5 rounded-lg border p-2.5 sm:gap-3 sm:p-3'
|
||||
className='flex min-w-0 items-center justify-between gap-2 rounded-lg border px-2.5 py-2'
|
||||
>
|
||||
<div className='flex min-w-0 items-center gap-2.5 sm:gap-3'>
|
||||
<div className='bg-muted shrink-0 rounded-md p-1.5 sm:p-2'>
|
||||
<div className='flex min-w-0 items-center gap-2'>
|
||||
<div className='bg-muted shrink-0 rounded-md p-1.5'>
|
||||
<binding.icon className='h-4 w-4' />
|
||||
</div>
|
||||
<div className='min-w-0'>
|
||||
<div className='flex items-center gap-1.5'>
|
||||
<p className='text-sm font-medium'>{binding.label}</p>
|
||||
<p
|
||||
className='truncate text-sm font-medium'
|
||||
title={binding.label}
|
||||
>
|
||||
{binding.label}
|
||||
</p>
|
||||
{binding.isBound && (
|
||||
<StatusBadge
|
||||
label={t('Bound')}
|
||||
@@ -462,75 +466,68 @@ export function AccountBindingsTab({
|
||||
>
|
||||
{actionLabel}
|
||||
</Button>
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Custom OAuth Bindings */}
|
||||
{customProviders && customProviders.length > 0 && (
|
||||
<>
|
||||
<Separator className='my-4' />
|
||||
<p className='text-muted-foreground mb-3 text-sm font-medium'>
|
||||
{t('Custom OAuth')}
|
||||
</p>
|
||||
<div className='grid grid-cols-1 gap-2.5 sm:grid-cols-2 sm:gap-3'>
|
||||
{customProviders.map((provider) => {
|
||||
const binding = customBindingsByProviderId.get(provider.id)
|
||||
const isBound = !!binding
|
||||
return (
|
||||
<div
|
||||
key={provider.id}
|
||||
className='flex items-center justify-between gap-2.5 rounded-lg border p-2.5 sm:gap-3 sm:p-3'
|
||||
>
|
||||
<div className='flex min-w-0 items-center gap-2.5 sm:gap-3'>
|
||||
<div className='bg-muted shrink-0 rounded-md p-1.5 sm:p-2'>
|
||||
<Link2 className='h-4 w-4' />
|
||||
</div>
|
||||
<div className='min-w-0'>
|
||||
<div className='flex items-center gap-1.5'>
|
||||
<p className='text-sm font-medium'>{provider.name}</p>
|
||||
{isBound && (
|
||||
<StatusBadge
|
||||
label={t('Bound')}
|
||||
variant='success'
|
||||
copyable={false}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<p className='text-muted-foreground truncate text-xs'>
|
||||
{isBound
|
||||
? binding?.provider_user_id || t('Bound')
|
||||
: t('Not bound')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{isBound ? (
|
||||
<Button
|
||||
variant='ghost'
|
||||
size='sm'
|
||||
className='text-destructive h-7 shrink-0 px-2.5 text-xs'
|
||||
onClick={() => setUnbindTarget(binding)}
|
||||
>
|
||||
<Unlink className='mr-1 h-3 w-3' />
|
||||
{t('Unbind')}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-7 shrink-0 px-2.5 text-xs'
|
||||
onClick={() => handleBindCustomOAuth(provider)}
|
||||
>
|
||||
{t('Bind')}
|
||||
</Button>
|
||||
)}
|
||||
{customProviders?.map((provider) => {
|
||||
const binding = customBindingsByProviderId.get(provider.id)
|
||||
const isBound = !!binding
|
||||
return (
|
||||
<li
|
||||
key={provider.id}
|
||||
className='flex min-w-0 items-center justify-between gap-2 rounded-lg border px-2.5 py-2'
|
||||
>
|
||||
<div className='flex min-w-0 items-center gap-2'>
|
||||
<div className='bg-muted shrink-0 rounded-md p-1.5'>
|
||||
<Link2 className='h-4 w-4' />
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<div className='min-w-0'>
|
||||
<div className='flex items-center gap-1.5'>
|
||||
<p
|
||||
className='truncate text-sm font-medium'
|
||||
title={provider.name}
|
||||
>
|
||||
{provider.name}
|
||||
</p>
|
||||
{isBound && (
|
||||
<StatusBadge
|
||||
label={t('Bound')}
|
||||
variant='success'
|
||||
copyable={false}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<p className='text-muted-foreground truncate text-xs'>
|
||||
{isBound
|
||||
? binding?.provider_user_id || t('Bound')
|
||||
: t('Not bound')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{isBound ? (
|
||||
<Button
|
||||
variant='ghost'
|
||||
size='sm'
|
||||
className='text-destructive h-7 shrink-0 px-2.5 text-xs'
|
||||
onClick={() => setUnbindTarget(binding)}
|
||||
>
|
||||
<Unlink className='mr-1 h-3 w-3' />
|
||||
{t('Unbind')}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-7 shrink-0 px-2.5 text-xs'
|
||||
onClick={() => handleBindCustomOAuth(provider)}
|
||||
>
|
||||
{t('Bind')}
|
||||
</Button>
|
||||
)}
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
|
||||
{/* Custom OAuth Unbind Confirmation */}
|
||||
<ConfirmDialog
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { CopyButton } from '@/components/copy-button'
|
||||
import { Dialog } from '@/components/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
|
||||
export function AccessTokenDialog(props: {
|
||||
token: string
|
||||
onClose: () => void
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (!open) props.onClose()
|
||||
}}
|
||||
title={t('Access Token')}
|
||||
description={t(
|
||||
"Save this token now. You won't be able to view it again after closing this dialog."
|
||||
)}
|
||||
contentClassName='sm:max-w-md'
|
||||
contentHeight='auto'
|
||||
footer={<Button onClick={props.onClose}>{t('Close')}</Button>}
|
||||
>
|
||||
<div className='space-y-2 py-2'>
|
||||
<Label htmlFor='generated-access-token'>{t('Token')}</Label>
|
||||
<div className='flex gap-2'>
|
||||
<Input
|
||||
id='generated-access-token'
|
||||
value={props.token}
|
||||
readOnly
|
||||
autoComplete='off'
|
||||
className='font-mono text-xs'
|
||||
/>
|
||||
<CopyButton
|
||||
value={props.token}
|
||||
variant='outline'
|
||||
tooltip={t('Copy token')}
|
||||
aria-label={t('Copy token')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
+2
-3
@@ -25,8 +25,7 @@ import { Dialog } from '@/components/dialog'
|
||||
import { PasswordInput } from '@/components/password-input'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Label } from '@/components/ui/label'
|
||||
|
||||
import { updateUserProfile } from '../../api'
|
||||
import { updateUserProfile } from '@/features/profile/api'
|
||||
|
||||
// ============================================================================
|
||||
// Change Password Dialog Component
|
||||
@@ -102,7 +101,7 @@ export function ChangePasswordDialog({
|
||||
} else {
|
||||
toast.error(response.message || t('Failed to change password'))
|
||||
}
|
||||
} catch (_error) {
|
||||
} catch {
|
||||
toast.error(t('Failed to change password'))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
+1
-2
@@ -28,10 +28,9 @@ import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { logout } from '@/features/auth/api'
|
||||
import { deleteUserAccount } from '@/features/profile/api'
|
||||
import { clearAuthentication } from '@/lib/api'
|
||||
|
||||
import { deleteUserAccount } from '../../api'
|
||||
|
||||
// ============================================================================
|
||||
// Delete Account Dialog Component
|
||||
// ============================================================================
|
||||
+8
-9
@@ -25,10 +25,9 @@ import { Dialog } from '@/components/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { sendEmailVerification, bindEmail } from '@/features/profile/api'
|
||||
import { useCountdown } from '@/hooks/use-countdown'
|
||||
|
||||
import { sendEmailVerification, bindEmail } from '../../api'
|
||||
|
||||
// ============================================================================
|
||||
// Email Bind Dialog Component
|
||||
// ============================================================================
|
||||
@@ -76,7 +75,7 @@ export function EmailBindDialog({
|
||||
} else {
|
||||
toast.error(response.message || t('Failed to send verification code'))
|
||||
}
|
||||
} catch (_error) {
|
||||
} catch {
|
||||
toast.error(t('Failed to send verification code'))
|
||||
} finally {
|
||||
setSendingCode(false)
|
||||
@@ -104,7 +103,7 @@ export function EmailBindDialog({
|
||||
} else {
|
||||
toast.error(response.message || t('Failed to bind email'))
|
||||
}
|
||||
} catch (_error) {
|
||||
} catch {
|
||||
toast.error(t('Failed to bind email'))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
@@ -123,6 +122,10 @@ export function EmailBindDialog({
|
||||
}
|
||||
}
|
||||
|
||||
let sendLabel = t('Send')
|
||||
if (sendingCode) sendLabel = t('Sending...')
|
||||
if (isActive) sendLabel = `${secondsLeft}s`
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
@@ -189,11 +192,7 @@ export function EmailBindDialog({
|
||||
onClick={handleSendCode}
|
||||
disabled={sendingCode || isActive || !email}
|
||||
>
|
||||
{isActive
|
||||
? `${secondsLeft}s`
|
||||
: sendingCode
|
||||
? t('Sending...')
|
||||
: t('Send')}
|
||||
{sendLabel}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
+1
-2
@@ -26,10 +26,9 @@ import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { TELEGRAM_BIND_RESULT_MESSAGE } from '@/features/auth/constants'
|
||||
import { startTelegramBind } from '@/features/profile/api'
|
||||
import { getServerErrorMessageKey } from '@/lib/server-error-message'
|
||||
|
||||
import { startTelegramBind } from '../../api'
|
||||
|
||||
// ============================================================================
|
||||
// Telegram Bind Dialog Component
|
||||
// ============================================================================
|
||||
+20
-22
@@ -65,7 +65,7 @@ export function TwoFABackupDialog({
|
||||
} else {
|
||||
toast.error(response.message || t('Failed to regenerate backup codes'))
|
||||
}
|
||||
} catch (_error) {
|
||||
} catch {
|
||||
toast.error(t('Failed to regenerate backup codes'))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
@@ -107,25 +107,23 @@ export function TwoFABackupDialog({
|
||||
contentHeight='auto'
|
||||
bodyClassName='space-y-4'
|
||||
footer={
|
||||
<>
|
||||
{backupCodes.length === 0 ? (
|
||||
<>
|
||||
<Button
|
||||
variant='outline'
|
||||
onClick={() => handleOpenChange(false)}
|
||||
disabled={loading}
|
||||
>
|
||||
{t('Cancel')}
|
||||
</Button>
|
||||
<Button onClick={handleRegenerate} disabled={loading || !code}>
|
||||
{loading && <Loader2 className='mr-2 h-4 w-4 animate-spin' />}
|
||||
{loading ? t('Generating...') : t('Generate New Codes')}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button onClick={handleDone}>{t('Done')}</Button>
|
||||
)}
|
||||
</>
|
||||
backupCodes.length === 0 ? (
|
||||
<>
|
||||
<Button
|
||||
variant='outline'
|
||||
onClick={() => handleOpenChange(false)}
|
||||
disabled={loading}
|
||||
>
|
||||
{t('Cancel')}
|
||||
</Button>
|
||||
<Button onClick={handleRegenerate} disabled={loading || !code}>
|
||||
{loading && <Loader2 className='mr-2 h-4 w-4 animate-spin' />}
|
||||
{loading ? t('Generating...') : t('Generate New Codes')}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button onClick={handleDone}>{t('Done')}</Button>
|
||||
)
|
||||
}
|
||||
>
|
||||
<div className='space-y-4 py-4'>
|
||||
@@ -163,9 +161,9 @@ export function TwoFABackupDialog({
|
||||
|
||||
<div className='rounded-lg border p-4'>
|
||||
<div className='grid grid-cols-2 gap-2'>
|
||||
{backupCodes.map((code, index) => (
|
||||
{backupCodes.map((code) => (
|
||||
<div
|
||||
key={index}
|
||||
key={code}
|
||||
className='bg-muted rounded-md p-2 text-center font-mono text-sm'
|
||||
>
|
||||
{code}
|
||||
+1
-1
@@ -74,7 +74,7 @@ export function TwoFADisableDialog({
|
||||
} else {
|
||||
toast.error(response.message || t('Failed to disable 2FA'))
|
||||
}
|
||||
} catch (_error) {
|
||||
} catch {
|
||||
toast.error(t('Failed to disable 2FA'))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
+9
-8
@@ -28,10 +28,9 @@ import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import type { TwoFASetupData } from '@/features/profile/types'
|
||||
import { setup2FA, enable2FA } from '@/lib/api'
|
||||
|
||||
import type { TwoFASetupData } from '../../types'
|
||||
|
||||
// ============================================================================
|
||||
// Two-FA Setup Dialog Component
|
||||
// ============================================================================
|
||||
@@ -102,7 +101,7 @@ export function TwoFASetupDialog({
|
||||
} else {
|
||||
toast.error(response.message || t('Failed to enable 2FA'))
|
||||
}
|
||||
} catch (_error) {
|
||||
} catch {
|
||||
toast.error(t('Failed to enable 2FA'))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
@@ -177,20 +176,22 @@ export function TwoFASetupDialog({
|
||||
}
|
||||
>
|
||||
<div className='space-y-4 py-4'>
|
||||
{initializing ? (
|
||||
{initializing && (
|
||||
<div className='flex flex-col items-center justify-center gap-3 py-8'>
|
||||
<div className='border-primary h-8 w-8 animate-spin rounded-full border-4 border-t-transparent' />
|
||||
<div className='text-muted-foreground text-sm'>
|
||||
{t('Setting up 2FA...')}
|
||||
</div>
|
||||
</div>
|
||||
) : !setupData ? (
|
||||
)}
|
||||
{!initializing && !setupData && (
|
||||
<div className='flex justify-center py-8'>
|
||||
<div className='text-muted-foreground'>
|
||||
{t('Failed to load setup data')}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
)}
|
||||
{!initializing && setupData && (
|
||||
<>
|
||||
{/* Step 0: QR Code */}
|
||||
{step === 0 && (
|
||||
@@ -236,9 +237,9 @@ export function TwoFASetupDialog({
|
||||
</Alert>
|
||||
<div className='rounded-lg border p-4'>
|
||||
<div className='grid grid-cols-2 gap-2'>
|
||||
{setupData.backup_codes.map((code, index) => (
|
||||
{setupData.backup_codes.map((code) => (
|
||||
<div
|
||||
key={index}
|
||||
key={code}
|
||||
className='bg-muted rounded-md p-2 text-center font-mono text-sm'
|
||||
>
|
||||
{code}
|
||||
+1
-2
@@ -25,8 +25,7 @@ import { Button } from '@/components/ui/button'
|
||||
import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
|
||||
import { bindWeChat } from '../../api'
|
||||
import { bindWeChat } from '@/features/profile/api'
|
||||
|
||||
interface WeChatBindDialogProps {
|
||||
open: boolean
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
+4
-4
@@ -42,14 +42,14 @@ import {
|
||||
} from '@/components/ui/empty'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { clearAuthenticatedClientState } from '@/lib/api'
|
||||
import type { LoginSession } from '@/stores/auth-store'
|
||||
|
||||
import {
|
||||
getLoginSessions,
|
||||
revokeLoginSession,
|
||||
revokeOtherLoginSessions,
|
||||
} from '../api'
|
||||
} from '@/features/profile/api'
|
||||
import { clearAuthenticatedClientState } from '@/lib/api'
|
||||
import type { LoginSession } from '@/stores/auth-store'
|
||||
|
||||
import { LoginSessionDialogs } from './login-session-dialogs'
|
||||
import { LoginSessionItem } from './login-session-item'
|
||||
|
||||
File renamed without changes.
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { TitledCard } from '@/components/ui/titled-card'
|
||||
import { updateUserSettings } from '@/features/profile/api'
|
||||
import { parseUserSettings } from '@/features/profile/lib/format'
|
||||
import type { UserProfile } from '@/features/profile/types'
|
||||
|
||||
type PrivacyCardProps = {
|
||||
profile: UserProfile
|
||||
onUpdate: () => void
|
||||
}
|
||||
|
||||
export function PrivacyCard(props: PrivacyCardProps) {
|
||||
const { t } = useTranslation()
|
||||
const [recordIpLog, setRecordIpLog] = useState(() =>
|
||||
Boolean(parseUserSettings(props.profile.setting).record_ip_log)
|
||||
)
|
||||
useEffect(() => {
|
||||
setRecordIpLog(
|
||||
Boolean(parseUserSettings(props.profile.setting).record_ip_log)
|
||||
)
|
||||
}, [props.profile.setting])
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: async () => {
|
||||
const response = await updateUserSettings({ record_ip_log: recordIpLog })
|
||||
if (!response.success) {
|
||||
throw new Error(response.message || t('Failed to update settings'))
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success(t('Settings updated successfully'))
|
||||
props.onUpdate()
|
||||
},
|
||||
onError: () => toast.error(t('Failed to update settings')),
|
||||
})
|
||||
|
||||
return (
|
||||
<TitledCard
|
||||
title={t('Record IP Address')}
|
||||
description={t('Log IP address for usage and error logs')}
|
||||
disableHoverEffect
|
||||
>
|
||||
<div className='flex items-center justify-between gap-4'>
|
||||
<Label htmlFor='security-record-ip'>{t('Record IP Address')}</Label>
|
||||
<Switch
|
||||
id='security-record-ip'
|
||||
checked={recordIpLog}
|
||||
onCheckedChange={setRecordIpLog}
|
||||
disabled={save.isPending}
|
||||
/>
|
||||
</div>
|
||||
<div className='mt-4 flex justify-end'>
|
||||
<Button
|
||||
type='button'
|
||||
onClick={() => save.mutate()}
|
||||
disabled={save.isPending}
|
||||
>
|
||||
{save.isPending && <Loader2 className='size-4 animate-spin' />}
|
||||
{save.isPending ? t('Saving...') : t('Save Settings')}
|
||||
</Button>
|
||||
</div>
|
||||
</TitledCard>
|
||||
)
|
||||
}
|
||||
+1
-1
@@ -32,7 +32,7 @@ import { IconBadge } from '@/components/ui/icon-badge'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useDialogs } from '@/hooks/use-dialog'
|
||||
|
||||
import { useTwoFA } from '../hooks'
|
||||
import { useTwoFA } from '../hooks/use-two-fa'
|
||||
import { TwoFABackupDialog } from './dialogs/two-fa-backup-dialog'
|
||||
import { TwoFADisableDialog } from './dialogs/two-fa-disable-dialog'
|
||||
import { TwoFASetupDialog } from './dialogs/two-fa-setup-dialog'
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import { useAuthStore } from '@/stores/auth-store'
|
||||
|
||||
import {
|
||||
createAccessToken,
|
||||
getAccessTokenStatus,
|
||||
revokeAccessToken,
|
||||
} from '../api'
|
||||
|
||||
export function useAccessToken() {
|
||||
const { t } = useTranslation()
|
||||
const client = useQueryClient()
|
||||
const userId = useAuthStore((state) => state.auth.user?.id)
|
||||
const statusKey = ['security', 'access-token', 'status', userId] as const
|
||||
const [token, setToken] = useState('')
|
||||
const status = useQuery({
|
||||
queryKey: statusKey,
|
||||
queryFn: getAccessTokenStatus,
|
||||
retry: false,
|
||||
})
|
||||
const refresh = () => client.invalidateQueries({ queryKey: statusKey })
|
||||
const generate = useMutation({
|
||||
// Keep plaintext out of the query/mutation cache and persistent storage.
|
||||
mutationFn: async () => {
|
||||
setToken(await createAccessToken())
|
||||
},
|
||||
onSuccess: refresh,
|
||||
onError: () => {
|
||||
toast.error(t('Failed to generate token'))
|
||||
void refresh()
|
||||
},
|
||||
})
|
||||
const revoke = useMutation({
|
||||
mutationFn: revokeAccessToken,
|
||||
onSuccess: () => {
|
||||
setToken('')
|
||||
toast.success(t('Access token revoked'))
|
||||
return refresh()
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('Failed to revoke token'))
|
||||
void refresh()
|
||||
},
|
||||
})
|
||||
return { status, token, clearToken: () => setToken(''), generate, revoke }
|
||||
}
|
||||
+1
-2
@@ -18,10 +18,9 @@ For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
|
||||
import type { TwoFAStatus } from '@/features/profile/types'
|
||||
import { get2FAStatus } from '@/lib/api'
|
||||
|
||||
import type { TwoFAStatus } from '../types'
|
||||
|
||||
// ============================================================================
|
||||
// Two-FA Hook
|
||||
// ============================================================================
|
||||
@@ -0,0 +1,144 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { Link2 } from 'lucide-react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { SectionPageLayout } from '@/components/layout/components/section-page-layout'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Empty,
|
||||
EmptyDescription,
|
||||
EmptyHeader,
|
||||
EmptyTitle,
|
||||
} from '@/components/ui/empty'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { TitledCard } from '@/components/ui/titled-card'
|
||||
import { useProfile } from '@/features/profile/hooks/use-profile'
|
||||
|
||||
import { AccessTokenCard } from './components/access-token-card'
|
||||
import { AccountActionCard } from './components/account-action-card'
|
||||
import { AccountBindings } from './components/account-bindings'
|
||||
import { LoginSessionsCard } from './components/login-sessions-card'
|
||||
import { PasskeyCard } from './components/passkey-card'
|
||||
import { PrivacyCard } from './components/privacy-card'
|
||||
import { TwoFACard } from './components/two-fa-card'
|
||||
|
||||
export function Security() {
|
||||
const { t } = useTranslation()
|
||||
const { profile, loading, refreshProfile, fetchProfile } = useProfile()
|
||||
|
||||
let content: ReactNode
|
||||
if (loading) {
|
||||
content = (
|
||||
<div role='status' aria-label={t('Loading...')} className='space-y-4'>
|
||||
<Skeleton className='h-28 w-full' />
|
||||
<Skeleton className='h-52 w-full' />
|
||||
<Skeleton className='h-52 w-full' />
|
||||
</div>
|
||||
)
|
||||
} else if (!profile) {
|
||||
content = (
|
||||
<Empty>
|
||||
<EmptyHeader>
|
||||
<EmptyTitle>{t('Failed to load profile')}</EmptyTitle>
|
||||
<EmptyDescription>
|
||||
{t('Refresh the list and try again.')}
|
||||
</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
onClick={() => void fetchProfile()}
|
||||
>
|
||||
{t('Retry')}
|
||||
</Button>
|
||||
</Empty>
|
||||
)
|
||||
} else {
|
||||
content = (
|
||||
<div className='grid gap-4 sm:gap-5 xl:grid-cols-[minmax(0,1fr)_minmax(360px,0.46fr)] xl:items-start'>
|
||||
<div className='min-w-0 space-y-4 sm:space-y-6'>
|
||||
<section
|
||||
aria-labelledby='security-authentication'
|
||||
className='space-y-3'
|
||||
>
|
||||
<h3 id='security-authentication' className='text-sm font-semibold'>
|
||||
{t('Login & Authentication')}
|
||||
</h3>
|
||||
<AccountActionCard action='password' username={profile.username} />
|
||||
<TitledCard
|
||||
title={t('Account Bindings')}
|
||||
icon={<Link2 className='size-4' />}
|
||||
headerClassName='px-3 py-2.5 !pb-2.5 sm:px-4 sm:py-2.5 sm:!pb-2.5'
|
||||
contentClassName='p-3 sm:p-3'
|
||||
titleClassName='text-sm sm:text-sm'
|
||||
iconClassName='size-7 sm:size-7'
|
||||
disableHoverEffect
|
||||
>
|
||||
<AccountBindings profile={profile} onUpdate={refreshProfile} />
|
||||
</TitledCard>
|
||||
</section>
|
||||
<section aria-labelledby='security-access' className='space-y-4'>
|
||||
<h3 id='security-access' className='text-sm font-semibold'>
|
||||
{t('Sessions & Access')}
|
||||
</h3>
|
||||
<LoginSessionsCard />
|
||||
<AccessTokenCard />
|
||||
</section>
|
||||
<section aria-labelledby='security-account' className='space-y-4'>
|
||||
<h3 id='security-account' className='text-sm font-semibold'>
|
||||
{t('Account Actions')}
|
||||
</h3>
|
||||
<AccountActionCard action='delete' username={profile.username} />
|
||||
</section>
|
||||
</div>
|
||||
<aside
|
||||
aria-labelledby='security-verification'
|
||||
className='min-w-0 space-y-4 sm:space-y-6 xl:sticky xl:top-0'
|
||||
>
|
||||
<div className='space-y-3'>
|
||||
<h3 id='security-verification' className='text-sm font-semibold'>
|
||||
{t('Security verification')}
|
||||
</h3>
|
||||
<PasskeyCard loading={loading} />
|
||||
<TwoFACard loading={loading} />
|
||||
</div>
|
||||
<section aria-labelledby='security-privacy' className='space-y-4'>
|
||||
<h3 id='security-privacy' className='text-sm font-semibold'>
|
||||
{t('Privacy')}
|
||||
</h3>
|
||||
<PrivacyCard profile={profile} onUpdate={refreshProfile} />
|
||||
</section>
|
||||
</aside>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<SectionPageLayout>
|
||||
<SectionPageLayout.Title>
|
||||
{t('Security & Access')}
|
||||
</SectionPageLayout.Title>
|
||||
<SectionPageLayout.Content>
|
||||
<div className='mx-auto w-full max-w-7xl'>{content}</div>
|
||||
</SectionPageLayout.Content>
|
||||
</SectionPageLayout>
|
||||
)
|
||||
}
|
||||
@@ -64,6 +64,7 @@ export const SIDEBAR_MODULES_DEFAULT: SidebarModulesAdminConfig = {
|
||||
detail: true,
|
||||
token: true,
|
||||
log: true,
|
||||
audit: true,
|
||||
midjourney: true,
|
||||
task: true,
|
||||
},
|
||||
@@ -71,6 +72,7 @@ export const SIDEBAR_MODULES_DEFAULT: SidebarModulesAdminConfig = {
|
||||
enabled: true,
|
||||
topup: true,
|
||||
personal: true,
|
||||
security: true,
|
||||
},
|
||||
admin: {
|
||||
enabled: true,
|
||||
|
||||
@@ -110,6 +110,10 @@ export function SidebarModulesSection({
|
||||
title: t('Usage logs'),
|
||||
description: t('Detailed request logs for investigations.'),
|
||||
},
|
||||
audit: {
|
||||
title: t('Audit Logs'),
|
||||
description: t('Login, security and access records'),
|
||||
},
|
||||
midjourney: {
|
||||
title: t('Drawing logs'),
|
||||
description: t('History of MjProxy-style image tasks.'),
|
||||
@@ -128,6 +132,10 @@ export function SidebarModulesSection({
|
||||
title: t('Profile'),
|
||||
description: t('Personal settings and profile management.'),
|
||||
},
|
||||
security: {
|
||||
title: t('Security & Access'),
|
||||
description: t('Manage your security settings and account access'),
|
||||
},
|
||||
},
|
||||
admin: {
|
||||
channel: {
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import {
|
||||
render,
|
||||
screen,
|
||||
within,
|
||||
waitFor,
|
||||
cleanup,
|
||||
} from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { createInstance } from 'i18next'
|
||||
import { I18nextProvider } from 'react-i18next'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
|
||||
import zh from '@/i18n/locales/zh.json'
|
||||
|
||||
import type { AuditLog } from '../api'
|
||||
import { AuditLogDetailsDialog } from '../components/audit-log-details-dialog'
|
||||
|
||||
const userAgent =
|
||||
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/152.0.0.0 Safari/537.36'
|
||||
const entry: AuditLog = {
|
||||
event_id: 'audit-event-1',
|
||||
user_id: 1,
|
||||
username: 'root',
|
||||
actor_role: 100,
|
||||
created_at: 1788600600,
|
||||
category: 'operation',
|
||||
action: 'channel.update',
|
||||
token_ref: '',
|
||||
ip: '::1',
|
||||
user_agent: userAgent,
|
||||
method: 'PUT',
|
||||
route: '/api/channel/',
|
||||
status: 200,
|
||||
success: true,
|
||||
request_id: '20260905092951096890008268d9d6b7oeNCj3',
|
||||
content: 'Updated channel batch (ID: 42)',
|
||||
other: {
|
||||
admin_info: {
|
||||
admin_id: 1,
|
||||
admin_username: 'root',
|
||||
admin_role: 100,
|
||||
auth_method: 'session',
|
||||
},
|
||||
op: {
|
||||
action: 'channel.update',
|
||||
params: { id: 42, name: 'batch', changed_fields: [] },
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it.each([
|
||||
[100, 'root'],
|
||||
[10, 'admin'],
|
||||
[1, 'user'],
|
||||
] as const)('keeps role %i as %s in Chinese', async (role, label) => {
|
||||
const i18n = createInstance()
|
||||
await i18n.init({ lng: 'zh', resources: { zh } })
|
||||
const log = {
|
||||
...entry,
|
||||
actor_role: role,
|
||||
other: {
|
||||
admin_info: { admin_username: 'literal-name', admin_role: role },
|
||||
op: { action: 'channel.update', params: { id: 42, name: 'batch' } },
|
||||
},
|
||||
}
|
||||
render(
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<AuditLogDetailsDialog entry={log} />
|
||||
</I18nextProvider>
|
||||
)
|
||||
await userEvent.click(screen.getByRole('button', { name: '详情' }))
|
||||
const dialog = await screen.findByRole('dialog', { name: '日志详情' })
|
||||
expect(within(dialog).getByText(label)).toBeVisible()
|
||||
expect(within(dialog).getByText('literal-name (ID: 1)')).toBeVisible()
|
||||
})
|
||||
|
||||
it('uses the returned authentication method for personal access records', async () => {
|
||||
const { dialog } = await openDetails({
|
||||
...entry,
|
||||
auth_method: 'access_token',
|
||||
})
|
||||
expect(within(dialog).getByText('Access Token')).toBeVisible()
|
||||
expect(within(dialog).queryByText('Session')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
async function openDetails(log: AuditLog = entry) {
|
||||
render(<AuditLogDetailsDialog entry={log} />)
|
||||
const trigger = screen.getByRole('button', { name: 'Details' })
|
||||
trigger.focus()
|
||||
await userEvent.keyboard('{Enter}')
|
||||
return {
|
||||
trigger,
|
||||
dialog: await screen.findByRole('dialog', { name: 'Log Details' }),
|
||||
}
|
||||
}
|
||||
|
||||
it('renders the channel update as a readable summary and compact operation rows without JSON or empty token fields', async () => {
|
||||
const { dialog } = await openDetails()
|
||||
expect(
|
||||
within(dialog).getByText('Updated channel batch (ID: 42)')
|
||||
).toBeVisible()
|
||||
expect(
|
||||
within(dialog).getByText('Field change details were not recorded')
|
||||
).toBeVisible()
|
||||
expect(within(dialog).getByText('root')).toBeVisible()
|
||||
expect(within(dialog).getByText('Session')).toBeVisible()
|
||||
expect(within(dialog).getByText(userAgent)).toBeVisible()
|
||||
expect(within(dialog).queryByText('Token identifier')).not.toBeInTheDocument()
|
||||
expect(
|
||||
within(dialog).queryByRole('button', { name: /Expand|Collapse/ })
|
||||
).not.toBeInTheDocument()
|
||||
expect(dialog.querySelector('pre')).not.toBeInTheDocument()
|
||||
expect(dialog).not.toHaveTextContent('changed_fields')
|
||||
})
|
||||
|
||||
it('aligns every request field in the same label and value columns', async () => {
|
||||
const { dialog } = await openDetails({
|
||||
...entry,
|
||||
token_ref: 'token-fingerprint',
|
||||
})
|
||||
for (const label of [
|
||||
'Method',
|
||||
'HTTP',
|
||||
'IP',
|
||||
'Client',
|
||||
'Route',
|
||||
'Request ID',
|
||||
'Token identifier',
|
||||
]) {
|
||||
const row = within(dialog).getByText(label, { exact: true }).parentElement
|
||||
expect(row).toHaveClass(
|
||||
'grid',
|
||||
'grid-cols-[5.25rem_minmax(0,1fr)]',
|
||||
'sm:grid-cols-[7rem_minmax(0,1fr)]'
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it('shows long values in full, copies the complete identifier, and restores focus when dismissed', async () => {
|
||||
const user = userEvent.setup()
|
||||
const writeText = vi
|
||||
.spyOn(navigator.clipboard, 'writeText')
|
||||
.mockResolvedValue()
|
||||
const requestId = `request-${'x'.repeat(100)}`
|
||||
const { trigger, dialog } = await openDetails({
|
||||
...entry,
|
||||
request_id: requestId,
|
||||
})
|
||||
expect(within(dialog).getByText(requestId)).toBeVisible()
|
||||
expect(within(dialog).getByText(requestId)).not.toHaveClass('truncate')
|
||||
expect(
|
||||
within(dialog).queryByRole('button', { name: /Expand|Collapse/ })
|
||||
).not.toBeInTheDocument()
|
||||
await user.click(
|
||||
within(dialog).getByRole('button', { name: 'Copy Request ID' })
|
||||
)
|
||||
expect(writeText).toHaveBeenCalledWith(requestId)
|
||||
expect(within(dialog).getByText(userAgent)).toBeVisible()
|
||||
await user.keyboard('{Escape}')
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
)
|
||||
await waitFor(() => expect(trigger).toHaveFocus())
|
||||
})
|
||||
|
||||
it.each([
|
||||
[
|
||||
'channel.status_update',
|
||||
{ id: 42, status: 2, changed: false },
|
||||
['Disabled', 'No'],
|
||||
],
|
||||
[
|
||||
'channel.status_update_batch',
|
||||
{ count: 0, total: 3, status: 1 },
|
||||
['Enabled', '0 / 3'],
|
||||
],
|
||||
['user.create', { username: 'alice', role: 10 }, ['admin', 'alice']],
|
||||
])(
|
||||
'formats known parameters for %s without losing zero or false',
|
||||
async (action, params, values) => {
|
||||
const { dialog } = await openDetails({
|
||||
...entry,
|
||||
action,
|
||||
other: { op: { action, params } },
|
||||
})
|
||||
for (const value of values) {
|
||||
expect(
|
||||
within(dialog)
|
||||
.getAllByText(value)
|
||||
.some((node) => node.textContent === value)
|
||||
).toBe(true)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it('translates changed field names and shows unknown nested metadata as readable fields', async () => {
|
||||
const { dialog } = await openDetails({
|
||||
...entry,
|
||||
other: {
|
||||
op: {
|
||||
action: 'channel.update',
|
||||
params: {
|
||||
id: 42,
|
||||
name: 'batch',
|
||||
changed_fields: ['models', 'group'],
|
||||
custom: { attempts: 0, permitted: false },
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
expect(within(dialog).getByText('Models, Group')).toBeVisible()
|
||||
expect(within(dialog).getByText('custom')).toBeVisible()
|
||||
expect(
|
||||
within(dialog).queryByRole('button', { name: 'custom' })
|
||||
).not.toBeInTheDocument()
|
||||
expect(within(dialog).getByText('attempts')).toBeVisible()
|
||||
expect(within(dialog).getByText('0')).toBeVisible()
|
||||
expect(within(dialog).getByText('No')).toBeVisible()
|
||||
expect(dialog).not.toHaveTextContent('[object Object]')
|
||||
expect(dialog.querySelector('pre')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each([null, undefined, '', '{broken', [], 42])(
|
||||
'preserves request details when metadata is missing or invalid (%s)',
|
||||
async (other) => {
|
||||
const { dialog } = await openDetails({
|
||||
...entry,
|
||||
other: other as unknown as AuditLog['other'],
|
||||
})
|
||||
expect(within(dialog).getByText(entry.request_id)).toBeVisible()
|
||||
expect(within(dialog).getByText(entry.ip)).toBeVisible()
|
||||
expect(dialog).not.toHaveTextContent('{broken')
|
||||
expect(dialog.querySelector('pre')).not.toBeInTheDocument()
|
||||
}
|
||||
)
|
||||
|
||||
it.each([
|
||||
[
|
||||
'login',
|
||||
'login',
|
||||
{ method: 'password' },
|
||||
'Logged in successfully via Password',
|
||||
],
|
||||
['security', 'user.2fa_enable', {}, 'Enabled two-factor authentication'],
|
||||
['access_token', 'access_token.request', {}, 'Access Token'],
|
||||
])(
|
||||
'shows summary and result for %s records',
|
||||
async (category, action, params, summary) => {
|
||||
const { dialog } = await openDetails({
|
||||
...entry,
|
||||
category,
|
||||
action,
|
||||
actor_role: 1,
|
||||
content: '',
|
||||
success: false,
|
||||
status: 403,
|
||||
other: { op: { action, params } },
|
||||
})
|
||||
expect(within(dialog).getAllByText(summary).length).toBeGreaterThan(0)
|
||||
expect(within(dialog).getByText('Failed')).toBeVisible()
|
||||
expect(within(dialog).getByText('403')).toBeVisible()
|
||||
expect(within(dialog).queryByText('root')).not.toBeInTheDocument()
|
||||
expect(within(dialog).getByText('user')).toBeVisible()
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,561 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import {
|
||||
cleanup,
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
within,
|
||||
} from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { AxiosError, type AxiosResponse } from 'axios'
|
||||
import { createInstance } from 'i18next'
|
||||
import { I18nextProvider } from 'react-i18next'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
|
||||
import en from '@/i18n/locales/en.json'
|
||||
import fr from '@/i18n/locales/fr.json'
|
||||
import ja from '@/i18n/locales/ja.json'
|
||||
import ru from '@/i18n/locales/ru.json'
|
||||
import viLocale from '@/i18n/locales/vi.json'
|
||||
import zhTW from '@/i18n/locales/zh-TW.json'
|
||||
import zh from '@/i18n/locales/zh.json'
|
||||
import { api } from '@/lib/api'
|
||||
import { useAuthStore } from '@/stores/auth-store'
|
||||
|
||||
import { AuditLogs } from '..'
|
||||
import { AuditLogViewer } from '../components/audit-log-viewer'
|
||||
|
||||
it('uses the shared log toolbar and opens details in a keyboard-accessible dialog without expanding the row', async () => {
|
||||
vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
total: 1,
|
||||
items: [
|
||||
{
|
||||
event_id: 'request-1',
|
||||
created_at: 1788600600,
|
||||
username: 'alice',
|
||||
category: 'access_token',
|
||||
action: 'access_token.request',
|
||||
content: '',
|
||||
other: {},
|
||||
request_id: 'audit-request-42',
|
||||
token_ref: 'a'.repeat(64),
|
||||
user_agent: 'Browser client with a long version description',
|
||||
method: 'GET',
|
||||
route: '/api/user/self',
|
||||
ip: '127.0.0.1',
|
||||
status: 200,
|
||||
success: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
})
|
||||
renderViewer()
|
||||
expect(screen.getByRole('button', { name: 'Date Range' })).toBeVisible()
|
||||
expect(screen.getByRole('button', { name: 'Search' })).toBeVisible()
|
||||
expect(
|
||||
await screen.findByRole('button', { name: 'Go to next page' })
|
||||
).toBeDisabled()
|
||||
const trigger = await screen.findByRole('button', { name: 'Details' })
|
||||
const row = screen.getByRole('row', { name: /127.0.0.1/ })
|
||||
const clientCell = within(row).getByRole('cell', {
|
||||
name: 'Browser client with a long version description',
|
||||
})
|
||||
expect(clientCell.querySelector('.truncate')).toBeInTheDocument()
|
||||
expect(row.querySelector('details')).not.toBeInTheDocument()
|
||||
trigger.focus()
|
||||
await userEvent.keyboard('{Enter}')
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Log Details' })
|
||||
expect(within(dialog).getByText('audit-request-42')).toBeVisible()
|
||||
expect(
|
||||
within(dialog).getByText('Browser client with a long version description')
|
||||
).toBeVisible()
|
||||
await userEvent.keyboard('{Escape}')
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
)
|
||||
await waitFor(() => expect(trigger).toHaveFocus())
|
||||
})
|
||||
|
||||
it.each([
|
||||
[
|
||||
'en',
|
||||
en,
|
||||
'Updated channel status (ID: 42)',
|
||||
'Batch updated channel status (1/2 changed)',
|
||||
],
|
||||
['zh', zh, '更新渠道状态(ID: 42)', '批量更新渠道状态(1/2 个已变更)'],
|
||||
['zh-TW', zhTW, '更新渠道狀態(ID: 42)', '批次更新渠道狀態(1/2 個已變更)'],
|
||||
[
|
||||
'fr',
|
||||
fr,
|
||||
'Statut du canal mis à jour (ID : 42)',
|
||||
'Statuts des canaux mis à jour par lot (1/2 modifiés)',
|
||||
],
|
||||
[
|
||||
'ja',
|
||||
ja,
|
||||
'チャネルの状態を更新(ID: 42)',
|
||||
'チャネルの状態を一括更新(1/2 件変更)',
|
||||
],
|
||||
[
|
||||
'ru',
|
||||
ru,
|
||||
'Обновлён статус канала (ID: 42)',
|
||||
'Массовое обновление статусов каналов (изменено: 1/2)',
|
||||
],
|
||||
[
|
||||
'vi',
|
||||
viLocale,
|
||||
'Đã cập nhật trạng thái kênh (ID: 42)',
|
||||
'Đã cập nhật trạng thái kênh hàng loạt (1/2 đã thay đổi)',
|
||||
],
|
||||
] as const)(
|
||||
'renders existing channel status audit records in %s',
|
||||
async (locale, resources, single, batch) => {
|
||||
const i18n = createInstance()
|
||||
await i18n.init({
|
||||
lng: locale,
|
||||
fallbackLng: false,
|
||||
resources: { [locale]: resources },
|
||||
})
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
total: 2,
|
||||
items: [
|
||||
{
|
||||
event_id: 'single-status',
|
||||
created_at: 0,
|
||||
username: 'alice',
|
||||
action: 'channel.status_update',
|
||||
content: 'channel.status_update',
|
||||
other: {
|
||||
op: {
|
||||
action: 'channel.status_update',
|
||||
params: { id: 42, status: 2, changed: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
event_id: 'batch-status',
|
||||
created_at: 0,
|
||||
username: 'alice',
|
||||
action: 'channel.status_update_batch',
|
||||
content: 'channel.status_update_batch',
|
||||
other: {
|
||||
op: {
|
||||
action: 'channel.status_update_batch',
|
||||
params: { count: 1, total: 2, status: 1 },
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
})
|
||||
render(
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<QueryClientProvider client={client}>
|
||||
<AuditLogViewer scope='self' />
|
||||
</QueryClientProvider>
|
||||
</I18nextProvider>
|
||||
)
|
||||
expect(await screen.findByRole('cell', { name: single })).toBeVisible()
|
||||
expect(screen.getByRole('cell', { name: batch })).toBeVisible()
|
||||
expect(
|
||||
screen.queryByRole('cell', { name: 'channel.status_update' })
|
||||
).not.toBeInTheDocument()
|
||||
expect(
|
||||
screen.queryByRole('cell', { name: 'channel.status_update_batch' })
|
||||
).not.toBeInTheDocument()
|
||||
}
|
||||
)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('localStorage', {
|
||||
getItem: () => null,
|
||||
setItem: () => undefined,
|
||||
removeItem: () => undefined,
|
||||
})
|
||||
})
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
useAuthStore.getState().auth.reset()
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
function renderViewer(scope: 'all' | 'self' = 'self') {
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
render(
|
||||
<QueryClientProvider client={client}>
|
||||
<AuditLogViewer
|
||||
scope={scope}
|
||||
accessOnly
|
||||
currentTokenRef={'a'.repeat(64)}
|
||||
/>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
it('filters own access history by result, generation and time and resets pagination', async () => {
|
||||
const get = vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: { success: true, data: { items: [], total: 45 } },
|
||||
})
|
||||
renderViewer()
|
||||
const user = userEvent.setup()
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'Go to next page' })
|
||||
).toBeEnabled()
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'Go to next page' }))
|
||||
await waitFor(() =>
|
||||
expect(get).toHaveBeenLastCalledWith('/api/audit/self', {
|
||||
params: expect.objectContaining({ p: 2, category: 'access_token' }),
|
||||
})
|
||||
)
|
||||
await user.click(screen.getByRole('combobox', { name: 'Result' }))
|
||||
await user.click(await screen.findByRole('option', { name: 'Failed' }))
|
||||
await user.click(screen.getByRole('combobox', { name: 'Token scope' }))
|
||||
await user.click(
|
||||
await screen.findByRole('option', { name: 'Historical tokens' })
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'Date Range' }))
|
||||
fireEvent.change(screen.getByLabelText('Start Time'), {
|
||||
target: { value: '2026-09-01T12:00' },
|
||||
})
|
||||
await user.click(screen.getByRole('button', { name: 'Confirm' }))
|
||||
await waitFor(() =>
|
||||
expect(get).toHaveBeenLastCalledWith('/api/audit/self', {
|
||||
params: expect.objectContaining({
|
||||
p: 1,
|
||||
success: 'false',
|
||||
exclude_token_ref: 'a'.repeat(64),
|
||||
start_timestamp: expect.any(Number),
|
||||
}),
|
||||
})
|
||||
)
|
||||
await user.click(screen.getByRole('combobox', { name: 'Token scope' }))
|
||||
await user.click(await screen.findByRole('option', { name: 'Current token' }))
|
||||
await waitFor(() =>
|
||||
expect(get).toHaveBeenLastCalledWith('/api/audit/self', {
|
||||
params: expect.objectContaining({ token_ref: 'a'.repeat(64) }),
|
||||
})
|
||||
)
|
||||
expect(screen.queryByLabelText('Username')).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('table').style.minWidth).toMatch(/max\(100%, \d+px\)/)
|
||||
})
|
||||
|
||||
it('a failed history query exposes retry and no empty history claim', async () => {
|
||||
vi.spyOn(api, 'get')
|
||||
.mockRejectedValueOnce(new Error('offline'))
|
||||
.mockResolvedValue({
|
||||
data: { success: true, data: { items: [], total: 0 } },
|
||||
})
|
||||
renderViewer()
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(
|
||||
'Failed to load audit records'
|
||||
)
|
||||
expect(screen.queryByText('No records')).not.toBeInTheDocument()
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Retry' }))
|
||||
expect(await screen.findByText('No records')).toBeVisible()
|
||||
})
|
||||
|
||||
it('administrator scope uses the admin endpoint and exposes the username filter', async () => {
|
||||
const get = vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: { success: true, data: { items: [], total: 0 } },
|
||||
})
|
||||
renderViewer('all')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Expand' }))
|
||||
fireEvent.change(screen.getByLabelText('Username'), {
|
||||
target: { value: 'alice' },
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(get).toHaveBeenLastCalledWith('/api/audit', {
|
||||
params: expect.objectContaining({ username: 'alice' }),
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('changing rows per page resets pagination and sends the selected page size', async () => {
|
||||
const get = vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: { success: true, data: { items: [], total: 80 } },
|
||||
})
|
||||
renderViewer()
|
||||
const user = userEvent.setup()
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'Go to next page' })
|
||||
).toBeEnabled()
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'Go to next page' }))
|
||||
await waitFor(() =>
|
||||
expect(get).toHaveBeenLastCalledWith('/api/audit/self', {
|
||||
params: expect.objectContaining({ p: 2 }),
|
||||
})
|
||||
)
|
||||
await user.click(screen.getByRole('combobox', { name: '' }))
|
||||
await user.click(await screen.findByRole('option', { name: '50' }))
|
||||
await waitFor(() =>
|
||||
expect(get).toHaveBeenLastCalledWith('/api/audit/self', {
|
||||
params: expect.objectContaining({ p: 1, page_size: 50 }),
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it.each([10, 100])(
|
||||
'role %i defaults to all audit records and can switch both ways',
|
||||
async (role) => {
|
||||
useAuthStore.getState().auth.setUser({
|
||||
id: 1,
|
||||
username: 'admin',
|
||||
role,
|
||||
permissions: { admin_permissions: { audit: { read: role === 10 } } },
|
||||
})
|
||||
const get = vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: { success: true, data: { items: [], total: 0 } },
|
||||
})
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
render(
|
||||
<QueryClientProvider client={client}>
|
||||
<AuditLogs />
|
||||
</QueryClientProvider>
|
||||
)
|
||||
expect(screen.getByRole('tab', { name: 'All' })).toHaveAttribute(
|
||||
'aria-selected',
|
||||
'true'
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(get).toHaveBeenCalledWith('/api/audit', expect.anything())
|
||||
)
|
||||
expect(get).not.toHaveBeenCalledWith('/api/audit/self', expect.anything())
|
||||
await userEvent.click(screen.getByRole('tab', { name: 'Only Mine' }))
|
||||
await waitFor(() =>
|
||||
expect(get).toHaveBeenLastCalledWith('/api/audit/self', expect.anything())
|
||||
)
|
||||
expect(screen.getByRole('tab', { name: 'Only Mine' })).toHaveAttribute(
|
||||
'aria-selected',
|
||||
'true'
|
||||
)
|
||||
await userEvent.click(screen.getByRole('tab', { name: 'All' }))
|
||||
await waitFor(() =>
|
||||
expect(get).toHaveBeenLastCalledWith('/api/audit', expect.anything())
|
||||
)
|
||||
expect(screen.getByRole('tab', { name: 'All' })).toHaveAttribute(
|
||||
'aria-selected',
|
||||
'true'
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
it.each([1, 10])(
|
||||
'role %i without an audit grant queries only its own records without scope tabs',
|
||||
async (role) => {
|
||||
useAuthStore.getState().auth.setUser({ id: 2, username: 'alice', role })
|
||||
const get = vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: { success: true, data: { items: [], total: 0 } },
|
||||
})
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
render(
|
||||
<QueryClientProvider client={client}>
|
||||
<AuditLogs />
|
||||
</QueryClientProvider>
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(get).toHaveBeenCalledWith('/api/audit/self', expect.anything())
|
||||
)
|
||||
expect(get).not.toHaveBeenCalledWith('/api/audit', expect.anything())
|
||||
expect(
|
||||
screen.queryByRole('tablist', { name: 'View scope' })
|
||||
).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('tab', { name: 'All' })).not.toBeInTheDocument()
|
||||
}
|
||||
)
|
||||
|
||||
it('clears global records and open details on revocation, falls back to self, and refreshes permissions', async () => {
|
||||
const admin = {
|
||||
id: 1,
|
||||
username: 'admin',
|
||||
role: 10,
|
||||
permissions: { admin_permissions: { audit: { read: true } } },
|
||||
}
|
||||
useAuthStore.getState().auth.setUser(admin)
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
const forbidden = new AxiosError(
|
||||
'Forbidden',
|
||||
'ERR_BAD_REQUEST',
|
||||
undefined,
|
||||
undefined,
|
||||
{ status: 403 } as AxiosResponse
|
||||
)
|
||||
let revoked = false
|
||||
const get = vi.spyOn(api, 'get').mockImplementation(async (url) => {
|
||||
if (url === '/api/user/self') {
|
||||
return {
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
...admin,
|
||||
permissions: { admin_permissions: { audit: { read: false } } },
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
if (url === '/api/audit' && revoked) throw forbidden
|
||||
return {
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
total: url === '/api/audit' ? 1 : 0,
|
||||
items:
|
||||
url === '/api/audit'
|
||||
? [
|
||||
{
|
||||
event_id: 'private-event',
|
||||
user_id: 2,
|
||||
username: 'other-account',
|
||||
actor_role: 10,
|
||||
created_at: 1788600600,
|
||||
category: 'operation',
|
||||
action: 'channel.update',
|
||||
content: 'Private operation',
|
||||
other: {},
|
||||
request_id: 'private-request',
|
||||
token_ref: '',
|
||||
user_agent: '',
|
||||
method: 'PUT',
|
||||
route: '/api/channel/',
|
||||
ip: '',
|
||||
status: 200,
|
||||
success: true,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
},
|
||||
},
|
||||
}
|
||||
})
|
||||
client.setQueryData(['audit', 99, 'all'], { items: ['separate-session'] })
|
||||
render(
|
||||
<QueryClientProvider client={client}>
|
||||
<AuditLogs />
|
||||
</QueryClientProvider>
|
||||
)
|
||||
await screen.findByText('other-account')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Details' }))
|
||||
expect(
|
||||
await screen.findByRole('dialog', { name: 'Log Details' })
|
||||
).toBeVisible()
|
||||
revoked = true
|
||||
await client.invalidateQueries({ queryKey: ['audit', 1, 'all'] })
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(get).toHaveBeenCalledWith('/api/audit/self', expect.anything())
|
||||
)
|
||||
await waitFor(() => expect(get).toHaveBeenCalledWith('/api/user/self'))
|
||||
expect(screen.queryByText('other-account')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('tab', { name: 'All' })).not.toBeInTheDocument()
|
||||
expect(client.getQueriesData({ queryKey: ['audit', 1, 'all'] })).toHaveLength(
|
||||
0
|
||||
)
|
||||
expect(client.getQueryData(['audit', 99, 'all'])).toEqual({
|
||||
items: ['separate-session'],
|
||||
})
|
||||
expect(
|
||||
useAuthStore.getState().auth.user?.permissions?.admin_permissions?.audit
|
||||
.read
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('mobile access history keeps pagination visible and puts result filters in a drawer', async () => {
|
||||
const pointerCapture = Object.getOwnPropertyDescriptor(
|
||||
HTMLElement.prototype,
|
||||
'setPointerCapture'
|
||||
)
|
||||
// JSDOM does not implement the pointer-capture API used by the mobile drawer.
|
||||
Object.defineProperty(HTMLElement.prototype, 'setPointerCapture', {
|
||||
configurable: true,
|
||||
value: () => undefined,
|
||||
})
|
||||
try {
|
||||
const matchMedia = window.matchMedia.bind(window)
|
||||
vi.spyOn(window, 'matchMedia').mockImplementation((query) => ({
|
||||
...matchMedia(query),
|
||||
matches: query === '(max-width: 640px)',
|
||||
}))
|
||||
const get = vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: { success: true, data: { items: [], total: 0 } },
|
||||
})
|
||||
renderViewer()
|
||||
const user = userEvent.setup()
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'Go to next page' })
|
||||
).toBeVisible()
|
||||
expect(
|
||||
screen.queryByRole('combobox', { name: 'Result' })
|
||||
).not.toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'Filter' }))
|
||||
const drawer = await screen.findByRole('dialog', { name: 'Filter' })
|
||||
await user.click(within(drawer).getByRole('combobox', { name: 'Result' }))
|
||||
await user.click(await screen.findByRole('option', { name: 'Failed' }))
|
||||
await waitFor(() =>
|
||||
expect(get).toHaveBeenLastCalledWith('/api/audit/self', {
|
||||
params: expect.objectContaining({ success: 'false', p: 1 }),
|
||||
})
|
||||
)
|
||||
await user.click(within(drawer).getByRole('button', { name: 'Search' }))
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
)
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'Go to next page' })
|
||||
).toBeVisible()
|
||||
} finally {
|
||||
if (pointerCapture) {
|
||||
Object.defineProperty(
|
||||
HTMLElement.prototype,
|
||||
'setPointerCapture',
|
||||
pointerCapture
|
||||
)
|
||||
} else {
|
||||
Reflect.deleteProperty(HTMLElement.prototype, 'setPointerCapture')
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import type { ApiResponse } from '@/features/profile/types'
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
export interface AuditLog {
|
||||
event_id: string
|
||||
user_id: number
|
||||
username: string
|
||||
actor_role: number
|
||||
created_at: number
|
||||
category: string
|
||||
action: string
|
||||
token_ref: string
|
||||
auth_method?: string
|
||||
ip: string
|
||||
user_agent: string
|
||||
method: string
|
||||
route: string
|
||||
status: number
|
||||
success: boolean
|
||||
request_id: string
|
||||
content: string
|
||||
other: Record<string, unknown> | null
|
||||
}
|
||||
export interface AuditFilters {
|
||||
p: number
|
||||
page_size: number
|
||||
start_timestamp?: number
|
||||
end_timestamp?: number
|
||||
success?: string
|
||||
category?: string
|
||||
token_ref?: string
|
||||
exclude_token_ref?: string
|
||||
username?: string
|
||||
request_id?: string
|
||||
}
|
||||
export async function getAuditLogs(
|
||||
scope: 'all' | 'self',
|
||||
params: AuditFilters
|
||||
): Promise<{ items: AuditLog[]; total: number }> {
|
||||
const response = await api.get<
|
||||
ApiResponse<{ items: AuditLog[]; total: number }>
|
||||
>(scope === 'all' ? '/api/audit' : '/api/audit/self', { params })
|
||||
if (!response.data.success || !response.data.data) {
|
||||
throw new Error(response.data.message || 'Failed to load audit records')
|
||||
}
|
||||
return response.data.data
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { DetailRow } from '../../components/dialogs/log-detail-layout'
|
||||
import { auditFieldLabel, isAuditDetailObject } from '../lib/audit-details'
|
||||
import { AuditDetailValue } from './audit-detail-value'
|
||||
|
||||
export function AuditDetailFields(props: {
|
||||
fields: { label: string; value: unknown }[]
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
return props.fields.map((field) => {
|
||||
const value = field.value
|
||||
if (value === null || value === undefined || value === '') return null
|
||||
if (isAuditDetailObject(value) || Array.isArray(value)) {
|
||||
const entries = Array.isArray(value)
|
||||
? value.map((item, i) => [String(i + 1), item] as const)
|
||||
: Object.entries(value)
|
||||
if (!entries.length) return null
|
||||
return (
|
||||
<div key={field.label} className='min-w-0 space-y-1'>
|
||||
<div className='text-muted-foreground text-xs break-all'>
|
||||
{field.label}
|
||||
</div>
|
||||
<div className='space-y-1 border-l pl-2'>
|
||||
<AuditDetailFields
|
||||
fields={entries.map(([key, item]) => ({
|
||||
label: auditFieldLabel(key, t),
|
||||
value: item,
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
let text = String(value)
|
||||
if (typeof value === 'boolean') text = value ? t('Yes') : t('No')
|
||||
return (
|
||||
<DetailRow
|
||||
key={field.label}
|
||||
label={field.label}
|
||||
value={<AuditDetailValue label={field.label} value={text} />}
|
||||
/>
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { CopyButton } from '@/components/copy-button'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export function AuditDetailValue(props: {
|
||||
label: string
|
||||
value: string
|
||||
mono?: boolean
|
||||
copyable?: boolean
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<div className='flex min-w-0 items-start gap-1 text-xs'>
|
||||
<span
|
||||
className={cn(
|
||||
'min-w-0 flex-1 leading-5 wrap-anywhere break-normal whitespace-pre-wrap',
|
||||
props.mono && 'font-mono'
|
||||
)}
|
||||
>
|
||||
{props.value}
|
||||
</span>
|
||||
{(props.copyable || props.value.length > 48) && (
|
||||
<CopyButton
|
||||
value={props.value}
|
||||
className='size-5'
|
||||
iconClassName='size-3'
|
||||
aria-label={t('Copy {{field}}', { field: props.label })}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import type { ColumnDef } from '@tanstack/react-table'
|
||||
import { useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { TruncatedCell } from '@/components/data-table'
|
||||
import { StatusBadge } from '@/components/status-badge'
|
||||
import dayjs from '@/lib/dayjs'
|
||||
|
||||
import type { AuditLog } from '../api'
|
||||
import { buildAuditDetails } from '../lib/audit-details'
|
||||
import { AuditLogDetailsDialog } from './audit-log-details-dialog'
|
||||
|
||||
export function useAuditLogColumns(
|
||||
accessOnly?: boolean
|
||||
): ColumnDef<AuditLog>[] {
|
||||
const { t } = useTranslation()
|
||||
return useMemo(() => {
|
||||
const columns: ColumnDef<AuditLog>[] = [
|
||||
{
|
||||
accessorKey: 'created_at',
|
||||
header: t('Time'),
|
||||
size: 180,
|
||||
cell: ({ row }) => (
|
||||
<span className='font-mono tabular-nums'>
|
||||
{dayjs.unix(row.original.created_at).format('YYYY-MM-DD HH:mm:ss')}
|
||||
</span>
|
||||
),
|
||||
meta: { label: t('Time'), mobileTitle: true },
|
||||
},
|
||||
]
|
||||
if (!accessOnly) {
|
||||
columns.push(
|
||||
{
|
||||
accessorKey: 'username',
|
||||
header: t('Username'),
|
||||
size: 100,
|
||||
meta: { label: t('Username') },
|
||||
},
|
||||
{
|
||||
id: 'event',
|
||||
header: t('Event'),
|
||||
size: 260,
|
||||
accessorFn: (entry) => buildAuditDetails(entry, t).summary,
|
||||
cell: ({ getValue }) => (
|
||||
<TruncatedCell className='max-w-64'>
|
||||
{getValue<string>()}
|
||||
</TruncatedCell>
|
||||
),
|
||||
meta: { label: t('Event') },
|
||||
}
|
||||
)
|
||||
}
|
||||
columns.push(
|
||||
{
|
||||
accessorKey: 'ip',
|
||||
header: 'IP',
|
||||
size: 120,
|
||||
cell: ({ row }) => (
|
||||
<span className='font-mono'>{row.original.ip || '—'}</span>
|
||||
),
|
||||
meta: { label: 'IP' },
|
||||
},
|
||||
{
|
||||
accessorKey: 'user_agent',
|
||||
header: t('Client'),
|
||||
size: 180,
|
||||
cell: ({ row }) => (
|
||||
<TruncatedCell className='max-w-48'>
|
||||
{row.original.user_agent || '—'}
|
||||
</TruncatedCell>
|
||||
),
|
||||
meta: { label: t('Client'), mobileHidden: true },
|
||||
},
|
||||
{
|
||||
accessorKey: 'method',
|
||||
header: t('Method'),
|
||||
size: 76,
|
||||
cell: ({ row }) => (
|
||||
<span className='text-muted-foreground font-mono'>
|
||||
{row.original.method || '—'}
|
||||
</span>
|
||||
),
|
||||
meta: { label: t('Method') },
|
||||
},
|
||||
{
|
||||
accessorKey: 'route',
|
||||
header: t('Route'),
|
||||
size: 220,
|
||||
cell: ({ row }) => (
|
||||
<TruncatedCell className='max-w-60 font-mono'>
|
||||
{row.original.route || '—'}
|
||||
</TruncatedCell>
|
||||
),
|
||||
meta: { label: t('Route') },
|
||||
},
|
||||
{
|
||||
accessorKey: 'status',
|
||||
header: 'HTTP',
|
||||
size: 60,
|
||||
cell: ({ row }) => (
|
||||
<span className='font-mono tabular-nums'>
|
||||
{row.original.status || '—'}
|
||||
</span>
|
||||
),
|
||||
meta: { label: 'HTTP' },
|
||||
},
|
||||
{
|
||||
accessorKey: 'success',
|
||||
header: t('Result'),
|
||||
size: 82,
|
||||
cell: ({ row }) => (
|
||||
<StatusBadge
|
||||
label={row.original.success ? t('Success') : t('Failed')}
|
||||
variant={row.original.success ? 'success' : 'danger'}
|
||||
copyable={false}
|
||||
/>
|
||||
),
|
||||
meta: { label: t('Result'), mobileBadge: true },
|
||||
},
|
||||
{
|
||||
id: 'details',
|
||||
header: t('Details'),
|
||||
size: 70,
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => <AuditLogDetailsDialog entry={row.original} />,
|
||||
meta: { label: t('Details') },
|
||||
}
|
||||
)
|
||||
return columns
|
||||
}, [accessOnly, t])
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { Dialog } from '@/components/dialog'
|
||||
import { StatusBadge } from '@/components/status-badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import dayjs from '@/lib/dayjs'
|
||||
|
||||
import {
|
||||
DetailRow,
|
||||
DetailSection,
|
||||
} from '../../components/dialogs/log-detail-layout'
|
||||
import type { AuditLog } from '../api'
|
||||
import { auditFieldLabel, buildAuditDetails } from '../lib/audit-details'
|
||||
import { AuditDetailFields } from './audit-detail-fields'
|
||||
import { AuditDetailValue } from './audit-detail-value'
|
||||
|
||||
export function AuditLogDetailsDialog(props: { entry: AuditLog }) {
|
||||
const { t } = useTranslation()
|
||||
const detail = buildAuditDetails(props.entry, t)
|
||||
const identifiers = [
|
||||
{ label: t('Route'), value: props.entry.route },
|
||||
{ label: t('Request ID'), value: props.entry.request_id },
|
||||
{ label: t('Token identifier'), value: props.entry.token_ref },
|
||||
].filter((field) => !!field.value)
|
||||
const hasOperation =
|
||||
detail.actor ||
|
||||
detail.target ||
|
||||
detail.authentication ||
|
||||
detail.fields.length ||
|
||||
detail.metadataUnavailable
|
||||
const hasRequest = Boolean(
|
||||
props.entry.method ||
|
||||
props.entry.status ||
|
||||
props.entry.ip ||
|
||||
props.entry.user_agent ||
|
||||
identifiers.length
|
||||
)
|
||||
return (
|
||||
<Dialog
|
||||
title={t('Log Details')}
|
||||
description={t('View the complete details for this log entry')}
|
||||
descriptionClassName='sr-only'
|
||||
trigger={
|
||||
<Button variant='ghost' size='sm' className='h-7 px-2'>
|
||||
{t('Details')}
|
||||
</Button>
|
||||
}
|
||||
contentClassName='min-w-0 sm:max-w-lg max-sm:max-h-[calc(100dvh-1.5rem)] max-sm:w-[calc(100vw-1.5rem)] max-sm:max-w-[calc(100vw-1.5rem)]'
|
||||
titleClassName='text-base'
|
||||
contentHeight='auto'
|
||||
bodyClassName='space-y-3'
|
||||
>
|
||||
<div className='min-w-0 space-y-1.5'>
|
||||
<p className='text-sm leading-relaxed font-medium break-words'>
|
||||
{detail.summary}
|
||||
</p>
|
||||
<div className='flex flex-wrap items-center gap-2 text-xs'>
|
||||
<StatusBadge
|
||||
label={props.entry.success ? t('Success') : t('Failed')}
|
||||
variant={props.entry.success ? 'success' : 'danger'}
|
||||
copyable={false}
|
||||
/>
|
||||
{Number.isFinite(props.entry.created_at) && (
|
||||
<span className='text-muted-foreground tabular-nums'>
|
||||
{dayjs.unix(props.entry.created_at).format('YYYY-MM-DD HH:mm:ss')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{hasOperation && (
|
||||
<DetailSection label={t('Operation Audit Info')}>
|
||||
{detail.actor && (
|
||||
<DetailRow label={t('Operator')} value={detail.actor} />
|
||||
)}
|
||||
{detail.actorRole && (
|
||||
<DetailRow label={t('Role')} value={detail.actorRole} />
|
||||
)}
|
||||
{detail.target && (
|
||||
<DetailRow label={t('Target')} value={detail.target} />
|
||||
)}
|
||||
{detail.authentication && (
|
||||
<DetailRow
|
||||
label={t('Authentication Method')}
|
||||
value={detail.authentication}
|
||||
/>
|
||||
)}
|
||||
<AuditDetailFields fields={detail.fields} />
|
||||
{detail.metadataUnavailable && (
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('Audit metadata is unavailable')}
|
||||
</p>
|
||||
)}
|
||||
</DetailSection>
|
||||
)}
|
||||
{hasRequest && (
|
||||
<DetailSection label={t('Request')}>
|
||||
{props.entry.method && (
|
||||
<DetailRow label={t('Method')} value={props.entry.method} mono />
|
||||
)}
|
||||
{!!props.entry.status && (
|
||||
<DetailRow label='HTTP' value={props.entry.status} mono />
|
||||
)}
|
||||
{props.entry.ip && (
|
||||
<DetailRow label='IP' value={props.entry.ip} mono />
|
||||
)}
|
||||
{props.entry.user_agent && (
|
||||
<DetailRow
|
||||
label={t('Client')}
|
||||
value={
|
||||
<AuditDetailValue
|
||||
label={t('User Agent')}
|
||||
value={props.entry.user_agent}
|
||||
mono
|
||||
copyable
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{identifiers.map((field) => (
|
||||
<DetailRow
|
||||
key={field.label}
|
||||
label={field.label}
|
||||
value={
|
||||
<AuditDetailValue
|
||||
label={field.label}
|
||||
value={field.value}
|
||||
mono
|
||||
copyable
|
||||
/>
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</DetailSection>
|
||||
)}
|
||||
{!!Object.keys(detail.extra).length && (
|
||||
<DetailSection label={t('Additional information')}>
|
||||
<AuditDetailFields
|
||||
fields={Object.entries(detail.extra).map(([key, value]) => ({
|
||||
label: auditFieldLabel(key, t),
|
||||
value,
|
||||
}))}
|
||||
/>
|
||||
</DetailSection>
|
||||
)}
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import type { Table } from '@tanstack/react-table'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
|
||||
import { CompactDateTimeRangePicker } from '../../components/compact-date-time-range-picker'
|
||||
import {
|
||||
LogsFilterField,
|
||||
LogsFilterInput,
|
||||
LogsFilterToolbar,
|
||||
} from '../../components/logs-filter-toolbar'
|
||||
import type { AuditFilters, AuditLog } from '../api'
|
||||
|
||||
function AuditFilterSelect(props: {
|
||||
label: string
|
||||
value: string
|
||||
options: { value: string; label: string; disabled?: boolean }[]
|
||||
onChange: (value: string) => void
|
||||
}) {
|
||||
return (
|
||||
<LogsFilterField>
|
||||
<Select
|
||||
items={props.options}
|
||||
value={props.value}
|
||||
onValueChange={(value) => {
|
||||
if (value !== null) props.onChange(value)
|
||||
}}
|
||||
>
|
||||
<SelectTrigger aria-label={props.label}>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
{props.options.map((option) => (
|
||||
<SelectItem
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
disabled={option.disabled}
|
||||
>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</LogsFilterField>
|
||||
)
|
||||
}
|
||||
|
||||
export function AuditLogFilterBar(props: {
|
||||
table: Table<AuditLog>
|
||||
filters: AuditFilters
|
||||
onChange: (patch: Partial<AuditFilters>) => void
|
||||
scope: 'all' | 'self'
|
||||
accessOnly?: boolean
|
||||
tokenScope: string
|
||||
currentTokenRef?: string
|
||||
onTokenScopeChange: (value: string) => void
|
||||
isFetching: boolean
|
||||
onSearch: () => void
|
||||
onReset: () => void
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const dateFilter = (
|
||||
<LogsFilterField wide>
|
||||
<CompactDateTimeRangePicker
|
||||
start={
|
||||
props.filters.start_timestamp === undefined
|
||||
? undefined
|
||||
: new Date(props.filters.start_timestamp * 1000)
|
||||
}
|
||||
end={
|
||||
props.filters.end_timestamp === undefined
|
||||
? undefined
|
||||
: new Date(props.filters.end_timestamp * 1000)
|
||||
}
|
||||
onChange={({ start, end }) =>
|
||||
props.onChange({
|
||||
start_timestamp: start
|
||||
? Math.floor(start.getTime() / 1000)
|
||||
: undefined,
|
||||
end_timestamp: end ? Math.floor(end.getTime() / 1000) : undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</LogsFilterField>
|
||||
)
|
||||
const mainFilters = (
|
||||
<>
|
||||
<AuditFilterSelect
|
||||
label={t('Result')}
|
||||
value={props.filters.success ?? 'all'}
|
||||
options={[
|
||||
{ value: 'all', label: t('All results') },
|
||||
{ value: 'true', label: t('Success') },
|
||||
{ value: 'false', label: t('Failed') },
|
||||
]}
|
||||
onChange={(value) =>
|
||||
props.onChange({ success: value === 'all' ? undefined : value })
|
||||
}
|
||||
/>
|
||||
{props.accessOnly ? (
|
||||
<AuditFilterSelect
|
||||
label={t('Token scope')}
|
||||
value={props.tokenScope}
|
||||
options={[
|
||||
{ value: 'all', label: t('All tokens') },
|
||||
{
|
||||
value: 'current',
|
||||
label: t('Current token'),
|
||||
disabled: !props.currentTokenRef,
|
||||
},
|
||||
{
|
||||
value: 'historical',
|
||||
label: t('Historical tokens'),
|
||||
disabled: props.currentTokenRef === undefined,
|
||||
},
|
||||
]}
|
||||
onChange={props.onTokenScopeChange}
|
||||
/>
|
||||
) : (
|
||||
<AuditFilterSelect
|
||||
label={t('Category')}
|
||||
value={props.filters.category ?? 'all'}
|
||||
options={[
|
||||
{ value: 'all', label: t('All categories') },
|
||||
{ value: 'login', label: t('Login') },
|
||||
{ value: 'security', label: t('Account security') },
|
||||
{ value: 'operation', label: t('Operation audit') },
|
||||
{ value: 'access_token', label: t('Access Token') },
|
||||
]}
|
||||
onChange={(value) =>
|
||||
props.onChange({ category: value === 'all' ? undefined : value })
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
const advancedFilters =
|
||||
!props.accessOnly || props.scope === 'all' ? (
|
||||
<>
|
||||
{!props.accessOnly && (
|
||||
<>
|
||||
<LogsFilterField>
|
||||
<LogsFilterInput
|
||||
aria-label={t('Token identifier')}
|
||||
placeholder={t('Token identifier')}
|
||||
value={props.filters.token_ref ?? ''}
|
||||
onChange={(event) =>
|
||||
props.onChange({ token_ref: event.target.value || undefined })
|
||||
}
|
||||
/>
|
||||
</LogsFilterField>
|
||||
<LogsFilterField>
|
||||
<LogsFilterInput
|
||||
aria-label={t('Request ID')}
|
||||
placeholder={t('Request ID')}
|
||||
value={props.filters.request_id ?? ''}
|
||||
onChange={(event) =>
|
||||
props.onChange({
|
||||
request_id: event.target.value || undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</LogsFilterField>
|
||||
</>
|
||||
)}
|
||||
{props.scope === 'all' && (
|
||||
<LogsFilterField>
|
||||
<LogsFilterInput
|
||||
aria-label={t('Username')}
|
||||
placeholder={t('Username')}
|
||||
value={props.filters.username ?? ''}
|
||||
onChange={(event) =>
|
||||
props.onChange({ username: event.target.value || undefined })
|
||||
}
|
||||
/>
|
||||
</LogsFilterField>
|
||||
)}
|
||||
</>
|
||||
) : undefined
|
||||
const advancedCount = [
|
||||
props.filters.token_ref,
|
||||
props.filters.request_id,
|
||||
props.filters.username,
|
||||
].filter(Boolean).length
|
||||
const filterCount =
|
||||
advancedCount +
|
||||
[
|
||||
props.filters.success,
|
||||
props.filters.category,
|
||||
props.tokenScope !== 'all',
|
||||
].filter(Boolean).length
|
||||
const hasFilters =
|
||||
filterCount > 0 ||
|
||||
props.filters.start_timestamp !== undefined ||
|
||||
props.filters.end_timestamp !== undefined
|
||||
return (
|
||||
<LogsFilterToolbar
|
||||
table={props.table}
|
||||
primaryFilters={
|
||||
<>
|
||||
{dateFilter}
|
||||
{mainFilters}
|
||||
</>
|
||||
}
|
||||
advancedFilters={advancedFilters}
|
||||
mobilePinnedFilters={dateFilter}
|
||||
mobileFilters={
|
||||
<>
|
||||
{mainFilters}
|
||||
{advancedFilters}
|
||||
</>
|
||||
}
|
||||
mobileFilterCount={filterCount}
|
||||
advancedFilterCount={advancedCount}
|
||||
hasActiveFilters={hasFilters}
|
||||
hasAdvancedActiveFilters={advancedCount > 0}
|
||||
searchLoading={props.isFetching}
|
||||
onSearch={props.onSearch}
|
||||
onReset={props.onReset}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { isAxiosError } from 'axios'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { DataTablePage, useDataTable } from '@/components/data-table'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useAuthStore } from '@/stores/auth-store'
|
||||
|
||||
import { getAuditLogs, type AuditFilters, type AuditLog } from '../api'
|
||||
import { useAuditLogColumns } from './audit-log-columns'
|
||||
import { AuditLogFilterBar } from './audit-log-filter-bar'
|
||||
|
||||
const EMPTY_LOGS: AuditLog[] = []
|
||||
|
||||
export function AuditLogViewer(props: {
|
||||
scope: 'all' | 'self'
|
||||
accessOnly?: boolean
|
||||
currentTokenRef?: string
|
||||
onAccessDenied?: () => Promise<void>
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const userId = useAuthStore((state) => state.auth.user?.id)
|
||||
const [filters, setFilters] = useState<AuditFilters>({ p: 1, page_size: 20 })
|
||||
const [tokenScope, setTokenScope] = useState('all')
|
||||
const params = { ...filters }
|
||||
if (props.accessOnly) params.category = 'access_token'
|
||||
if (tokenScope === 'current') params.token_ref = props.currentTokenRef
|
||||
if (tokenScope === 'historical') {
|
||||
params.exclude_token_ref = props.currentTokenRef
|
||||
}
|
||||
const canQuery =
|
||||
tokenScope === 'all' ||
|
||||
(props.currentTokenRef !== undefined &&
|
||||
(tokenScope === 'historical' || !!props.currentTokenRef))
|
||||
const invalidRange =
|
||||
filters.start_timestamp !== undefined &&
|
||||
filters.end_timestamp !== undefined &&
|
||||
filters.start_timestamp > filters.end_timestamp
|
||||
const query = useQuery({
|
||||
queryKey: ['audit', userId, props.scope, params],
|
||||
queryFn: () => getAuditLogs(props.scope, params),
|
||||
enabled: canQuery && !invalidRange,
|
||||
retry: false,
|
||||
})
|
||||
const accessDenied =
|
||||
props.scope === 'all' &&
|
||||
isAxiosError(query.error) &&
|
||||
query.error.response?.status === 403
|
||||
const onAccessDenied = props.onAccessDenied
|
||||
useEffect(() => {
|
||||
if (accessDenied) void onAccessDenied?.()
|
||||
}, [accessDenied, onAccessDenied])
|
||||
const columns = useAuditLogColumns(props.accessOnly)
|
||||
const { table } = useDataTable({
|
||||
columns,
|
||||
data:
|
||||
canQuery && !query.isError
|
||||
? (query.data?.items ?? EMPTY_LOGS)
|
||||
: EMPTY_LOGS,
|
||||
getRowId: (entry) => entry.event_id,
|
||||
totalCount: query.isError ? 0 : (query.data?.total ?? 0),
|
||||
pagination: { pageIndex: filters.p - 1, pageSize: filters.page_size },
|
||||
onPaginationChange: (updater) => {
|
||||
if (query.isFetching || query.isError || invalidRange || !canQuery) return
|
||||
setFilters((previous) => {
|
||||
const current = {
|
||||
pageIndex: previous.p - 1,
|
||||
pageSize: previous.page_size,
|
||||
}
|
||||
const next = typeof updater === 'function' ? updater(current) : updater
|
||||
return {
|
||||
...previous,
|
||||
p: next.pageSize === previous.page_size ? next.pageIndex + 1 : 1,
|
||||
page_size: next.pageSize,
|
||||
}
|
||||
})
|
||||
},
|
||||
enableRowSelection: false,
|
||||
enableSorting: false,
|
||||
manualFiltering: true,
|
||||
manualPagination: true,
|
||||
})
|
||||
const update = (patch: Partial<AuditFilters>) =>
|
||||
setFilters((previous) => ({ ...previous, ...patch, p: 1 }))
|
||||
|
||||
return (
|
||||
<div className='flex h-full min-h-0 flex-col'>
|
||||
<DataTablePage
|
||||
table={table}
|
||||
columns={columns}
|
||||
isLoading={query.isPending && canQuery && !invalidRange}
|
||||
isFetching={query.isFetching}
|
||||
emptyTitle={
|
||||
query.isError ? t('Failed to load audit records') : t('No records')
|
||||
}
|
||||
hideMobile={props.accessOnly}
|
||||
paginationInFooter={!props.accessOnly}
|
||||
className='h-auto min-h-0 flex-1'
|
||||
applyHeaderSize
|
||||
getColumnClassName={() => 'py-2'}
|
||||
tableClassName='[&_[data-slot=table]]:text-[13px] [&_[data-slot=table]_td]:text-[13px] [&_[data-slot=table]_td_*]:text-[13px] [&_[data-slot=table]_th]:text-[13px] [&_[data-slot=table]_th_*]:text-[13px]'
|
||||
toolbar={
|
||||
<div className='shrink-0 space-y-2'>
|
||||
<AuditLogFilterBar
|
||||
table={table}
|
||||
filters={filters}
|
||||
onChange={update}
|
||||
scope={props.scope}
|
||||
accessOnly={props.accessOnly}
|
||||
tokenScope={tokenScope}
|
||||
currentTokenRef={props.currentTokenRef}
|
||||
onTokenScopeChange={(value) => {
|
||||
setTokenScope(value)
|
||||
update({})
|
||||
}}
|
||||
isFetching={query.isFetching}
|
||||
onSearch={() => {
|
||||
if (!invalidRange && canQuery) void query.refetch()
|
||||
}}
|
||||
onReset={() => {
|
||||
setTokenScope('all')
|
||||
setFilters({ p: 1, page_size: filters.page_size })
|
||||
}}
|
||||
/>
|
||||
{invalidRange && (
|
||||
<Alert variant='destructive'>
|
||||
<AlertDescription>
|
||||
{t('End time must be after start time')}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{query.isError && (
|
||||
<Alert variant='destructive'>
|
||||
<AlertDescription className='flex items-center justify-between gap-2'>
|
||||
<span>{t('Failed to load audit records')}</span>
|
||||
<Button
|
||||
size='sm'
|
||||
variant='outline'
|
||||
onClick={() => void query.refetch()}
|
||||
>
|
||||
{t('Retry')}
|
||||
</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { useCallback, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { SectionPageLayout } from '@/components/layout'
|
||||
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { getUserProfile } from '@/features/profile/api'
|
||||
import {
|
||||
ADMIN_PERMISSION_RESOURCES,
|
||||
ADMIN_PERMISSION_ACTIONS,
|
||||
hasPermission,
|
||||
} from '@/lib/admin-permissions'
|
||||
import { ROLE } from '@/lib/roles'
|
||||
import { useAuthStore } from '@/stores/auth-store'
|
||||
|
||||
import { AuditLogViewer } from './components/audit-log-viewer'
|
||||
|
||||
export function AuditLogs() {
|
||||
const { t } = useTranslation()
|
||||
const user = useAuthStore((state) => state.auth.user)
|
||||
const queryClient = useQueryClient()
|
||||
const [scope, setScope] = useState<'all' | 'self'>('all')
|
||||
const [accessRevoked, setAccessRevoked] = useState(false)
|
||||
const canReadAll =
|
||||
!!user &&
|
||||
user.role >= ROLE.ADMIN &&
|
||||
hasPermission(
|
||||
user,
|
||||
ADMIN_PERMISSION_RESOURCES.AUDIT,
|
||||
ADMIN_PERMISSION_ACTIONS.READ
|
||||
)
|
||||
const effectiveScope = canReadAll && !accessRevoked ? scope : 'self'
|
||||
const userId = user?.id
|
||||
const handleAccessDenied = useCallback(async () => {
|
||||
setAccessRevoked(true)
|
||||
setScope('self')
|
||||
const current = useAuthStore.getState().auth.user
|
||||
if (current && current.id === userId) {
|
||||
useAuthStore.getState().auth.setUser({
|
||||
...current,
|
||||
permissions: {
|
||||
...current.permissions,
|
||||
admin_permissions: {
|
||||
...current.permissions?.admin_permissions,
|
||||
audit: { read: false },
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
await queryClient.cancelQueries({ queryKey: ['audit', userId, 'all'] })
|
||||
queryClient.removeQueries({ queryKey: ['audit', userId, 'all'] })
|
||||
try {
|
||||
const profile = await getUserProfile()
|
||||
const latest = useAuthStore.getState().auth.user
|
||||
if (
|
||||
profile.success &&
|
||||
profile.data &&
|
||||
latest &&
|
||||
profile.data.id === userId &&
|
||||
latest.id === userId
|
||||
) {
|
||||
useAuthStore.getState().auth.setUser({
|
||||
...latest,
|
||||
role: profile.data.role,
|
||||
permissions: profile.data.permissions,
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
// Keep the denied scope closed when refreshing capabilities fails.
|
||||
}
|
||||
}, [queryClient, userId])
|
||||
return (
|
||||
<SectionPageLayout fixedContent>
|
||||
<SectionPageLayout.Title>{t('Audit Logs')}</SectionPageLayout.Title>
|
||||
<SectionPageLayout.Actions>
|
||||
{canReadAll && !accessRevoked && (
|
||||
<Tabs
|
||||
value={scope}
|
||||
onValueChange={(value) =>
|
||||
setScope(value === 'all' ? 'all' : 'self')
|
||||
}
|
||||
>
|
||||
<TabsList aria-label={t('View scope')}>
|
||||
<TabsTrigger value='all'>{t('All')}</TabsTrigger>
|
||||
<TabsTrigger value='self'>{t('Only Mine')}</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
)}
|
||||
</SectionPageLayout.Actions>
|
||||
<SectionPageLayout.Content>
|
||||
<div className='flex h-full min-h-0 flex-col gap-3'>
|
||||
{accessRevoked && (
|
||||
<p role='status' className='text-muted-foreground shrink-0 text-xs'>
|
||||
{t('Audit access changed. Showing only your records.')}
|
||||
</p>
|
||||
)}
|
||||
<div className='min-h-0 flex-1'>
|
||||
<AuditLogViewer
|
||||
key={`${userId}:${effectiveScope}`}
|
||||
scope={effectiveScope}
|
||||
onAccessDenied={handleAccessDenied}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</SectionPageLayout.Content>
|
||||
</SectionPageLayout>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import type { TFunction } from 'i18next'
|
||||
|
||||
import { loginMethodLabel } from '@/features/security/components/login-session-utils'
|
||||
import { ROLE } from '@/lib/roles'
|
||||
|
||||
import { renderAuditContent } from '../../lib/format'
|
||||
import type { LogOtherData } from '../../types'
|
||||
import type { AuditLog } from '../api'
|
||||
|
||||
const AUDIT_ROLE_NAMES: Record<number, string> = {
|
||||
[ROLE.GUEST]: 'guest',
|
||||
[ROLE.USER]: 'user',
|
||||
[ROLE.ADMIN]: 'admin',
|
||||
[ROLE.SUPER_ADMIN]: 'root',
|
||||
}
|
||||
|
||||
export function isAuditDetailObject(
|
||||
value: unknown
|
||||
): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
||||
}
|
||||
|
||||
export function auditFieldLabel(key: string, t: TFunction): string {
|
||||
switch (key) {
|
||||
case 'status':
|
||||
return t('Status')
|
||||
case 'role':
|
||||
return t('Role')
|
||||
case 'changed_fields':
|
||||
return t('Changed Fields')
|
||||
case 'changed':
|
||||
return t('State changed')
|
||||
case 'count':
|
||||
return t('Count')
|
||||
case 'total':
|
||||
return t('Total')
|
||||
case 'sourceId':
|
||||
return t('Source ID')
|
||||
case 'id':
|
||||
return 'ID'
|
||||
case 'name':
|
||||
return t('Name')
|
||||
case 'username':
|
||||
return t('Username')
|
||||
case 'target_user_id':
|
||||
return t('User ID')
|
||||
case 'plan_id':
|
||||
return t('Plan ID')
|
||||
case 'plan_title':
|
||||
return t('Plan Title')
|
||||
case 'reset_count':
|
||||
return t('Reset Count')
|
||||
case 'user_count':
|
||||
return t('User Count')
|
||||
case 'advance_reset_time':
|
||||
return t('Advance next reset time')
|
||||
case 'bindingType':
|
||||
return t('Binding Type')
|
||||
case 'from':
|
||||
return t('Previous value')
|
||||
case 'to':
|
||||
return t('New value')
|
||||
case 'action':
|
||||
return t('Operation')
|
||||
case 'method':
|
||||
return t('Authentication Method')
|
||||
case 'key':
|
||||
return t('Key')
|
||||
case 'tag':
|
||||
return t('Tag')
|
||||
case 'group':
|
||||
return t('Group')
|
||||
case 'models':
|
||||
return t('Models')
|
||||
case 'type':
|
||||
return t('Type')
|
||||
case 'base_url':
|
||||
return t('Base URL')
|
||||
case 'quota':
|
||||
return t('Quota')
|
||||
case 'admin_info':
|
||||
return t('Operator Admin')
|
||||
case 'audit_info':
|
||||
return t('Request')
|
||||
default:
|
||||
return key
|
||||
}
|
||||
}
|
||||
|
||||
export function buildAuditDetails(entry: AuditLog, t: TFunction) {
|
||||
const metadata = isAuditDetailObject(entry.other) ? entry.other : {}
|
||||
const metadataUnavailable =
|
||||
entry.other != null && !isAuditDetailObject(entry.other)
|
||||
const op = isAuditDetailObject(metadata.op) ? metadata.op : {}
|
||||
const action = typeof op.action === 'string' ? op.action : entry.action
|
||||
const params = isAuditDetailObject(op.params) ? { ...op.params } : {}
|
||||
const summaryParams: NonNullable<NonNullable<LogOtherData['op']>['params']> =
|
||||
{}
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (
|
||||
typeof value === 'string' ||
|
||||
typeof value === 'number' ||
|
||||
typeof value === 'boolean'
|
||||
) {
|
||||
summaryParams[key] = value
|
||||
} else if (
|
||||
Array.isArray(value) &&
|
||||
value.every((item) => typeof item === 'string')
|
||||
) {
|
||||
summaryParams[key] = value
|
||||
}
|
||||
}
|
||||
if (typeof summaryParams.method === 'string') {
|
||||
summaryParams.method = loginMethodLabel(summaryParams.method, t)
|
||||
}
|
||||
if (
|
||||
typeof summaryParams.role === 'number' &&
|
||||
[0, 1, 10, 100].includes(summaryParams.role)
|
||||
) {
|
||||
summaryParams.role = AUDIT_ROLE_NAMES[summaryParams.role]
|
||||
}
|
||||
|
||||
let fallback = t('Operation audit')
|
||||
if (entry.category === 'login') fallback = t('Login')
|
||||
if (entry.category === 'security') fallback = t('Account security')
|
||||
if (entry.category === 'access_token') fallback = t('Access Token')
|
||||
const summary =
|
||||
renderAuditContent({ op: { action, params: summaryParams } }, t) ||
|
||||
(entry.content && entry.content !== action ? entry.content : fallback)
|
||||
const admin = isAuditDetailObject(metadata.admin_info)
|
||||
? metadata.admin_info
|
||||
: {}
|
||||
const actorName =
|
||||
typeof admin.admin_username === 'string'
|
||||
? admin.admin_username
|
||||
: entry.username
|
||||
const actorId =
|
||||
typeof admin.admin_id === 'number' || typeof admin.admin_id === 'string'
|
||||
? admin.admin_id
|
||||
: entry.user_id
|
||||
let actor = actorName
|
||||
if (actorId) {
|
||||
actor = actorName ? `${actorName} (ID: ${actorId})` : `ID: ${actorId}`
|
||||
}
|
||||
let actorRole = ''
|
||||
if ([1, 10, 100].includes(entry.actor_role)) {
|
||||
actorRole = AUDIT_ROLE_NAMES[entry.actor_role]
|
||||
}
|
||||
const authMethod =
|
||||
entry.auth_method ||
|
||||
(typeof admin.auth_method === 'string' ? admin.auth_method : '')
|
||||
let authentication = authMethod
|
||||
if (authMethod === 'session') authentication = t('Session')
|
||||
else if (authMethod === 'access_token') authentication = t('Access Token')
|
||||
else if (authMethod) authentication = loginMethodLabel(authMethod, t)
|
||||
|
||||
let targetName = ''
|
||||
if (typeof params.name === 'string') targetName = params.name
|
||||
else if (typeof params.username === 'string') targetName = params.username
|
||||
const targetId =
|
||||
typeof params.id === 'number' || typeof params.id === 'string'
|
||||
? params.id
|
||||
: undefined
|
||||
let target = targetName
|
||||
if (targetId !== undefined) {
|
||||
target = targetName ? `${targetName} (ID: ${targetId})` : `ID: ${targetId}`
|
||||
}
|
||||
if (target) {
|
||||
delete params.id
|
||||
delete params.name
|
||||
delete params.username
|
||||
}
|
||||
|
||||
const fields: { label: string; value: unknown }[] = []
|
||||
if (
|
||||
Array.isArray(params.changed_fields) &&
|
||||
params.changed_fields.every((field) => typeof field === 'string')
|
||||
) {
|
||||
fields.push({
|
||||
label: t('Changed Fields'),
|
||||
value: params.changed_fields.length
|
||||
? params.changed_fields
|
||||
.map((field) => auditFieldLabel(String(field), t))
|
||||
.join(', ')
|
||||
: t('Field change details were not recorded'),
|
||||
})
|
||||
delete params.changed_fields
|
||||
}
|
||||
if (action.startsWith('channel.') && typeof params.status === 'number') {
|
||||
if (params.status === 1) params.status = t('Enabled')
|
||||
else if (params.status === 2) params.status = t('Disabled')
|
||||
else if (params.status === 3) params.status = t('Auto Disabled')
|
||||
}
|
||||
if (
|
||||
typeof params.role === 'number' &&
|
||||
[0, 1, 10, 100].includes(params.role)
|
||||
) {
|
||||
params.role = AUDIT_ROLE_NAMES[params.role]
|
||||
}
|
||||
if (typeof params.method === 'string') {
|
||||
params.method = loginMethodLabel(params.method, t)
|
||||
}
|
||||
if (
|
||||
action === 'channel.status_update_batch' &&
|
||||
typeof params.count === 'number' &&
|
||||
typeof params.total === 'number'
|
||||
) {
|
||||
fields.push({
|
||||
label: t('Changed / Total'),
|
||||
value: `${params.count} / ${params.total}`,
|
||||
})
|
||||
delete params.count
|
||||
delete params.total
|
||||
}
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
fields.push({ label: auditFieldLabel(key, t), value })
|
||||
}
|
||||
if (
|
||||
typeof metadata.login_method === 'string' &&
|
||||
params.method === undefined
|
||||
) {
|
||||
fields.push({
|
||||
label: t('Login Method'),
|
||||
value: loginMethodLabel(metadata.login_method, t),
|
||||
})
|
||||
}
|
||||
|
||||
const extra = { ...metadata }
|
||||
delete extra.op
|
||||
delete extra.admin_info
|
||||
delete extra.audit_info
|
||||
delete extra.login_method
|
||||
delete extra.user_agent
|
||||
const adminExtra = { ...admin }
|
||||
for (const key of [
|
||||
'admin_id',
|
||||
'admin_username',
|
||||
'admin_role',
|
||||
'auth_method',
|
||||
]) {
|
||||
delete adminExtra[key]
|
||||
}
|
||||
if (Object.keys(adminExtra).length) extra.admin_info = adminExtra
|
||||
if (isAuditDetailObject(metadata.audit_info)) {
|
||||
const auditExtra = { ...metadata.audit_info }
|
||||
for (const key of ['method', 'route', 'path', 'status', 'success']) {
|
||||
delete auditExtra[key]
|
||||
}
|
||||
if (Object.keys(auditExtra).length) extra.audit_info = auditExtra
|
||||
}
|
||||
return {
|
||||
summary,
|
||||
actor,
|
||||
actorRole,
|
||||
target,
|
||||
authentication,
|
||||
fields,
|
||||
extra,
|
||||
metadataUnavailable,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import {
|
||||
createMemoryHistory,
|
||||
createRootRoute,
|
||||
createRoute,
|
||||
createRouter,
|
||||
RouterProvider,
|
||||
} from '@tanstack/react-router'
|
||||
import { getCoreRowModel, useReactTable } from '@tanstack/react-table'
|
||||
import {
|
||||
cleanup,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
within,
|
||||
} from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
import { CommonLogsFilterBar } from '../common-logs-filter-bar'
|
||||
import { UsageLogsProvider } from '../usage-logs-provider'
|
||||
|
||||
function FilterFixture() {
|
||||
const table = useReactTable({
|
||||
data: [],
|
||||
columns: [],
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
})
|
||||
return (
|
||||
<UsageLogsProvider>
|
||||
<CommonLogsFilterBar table={table} />
|
||||
</UsageLogsProvider>
|
||||
)
|
||||
}
|
||||
|
||||
async function renderFilter() {
|
||||
vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: { success: true, data: { quota: 0, rpm: 0, tpm: 0 } },
|
||||
})
|
||||
const root = createRootRoute()
|
||||
const auth = createRoute({ getParentRoute: () => root, id: '_authenticated' })
|
||||
const logs = createRoute({
|
||||
getParentRoute: () => auth,
|
||||
path: '/usage-logs/$section',
|
||||
component: FilterFixture,
|
||||
validateSearch: (search: Record<string, unknown>) => search,
|
||||
})
|
||||
const router = createRouter({
|
||||
routeTree: root.addChildren([auth.addChildren([logs])]),
|
||||
history: createMemoryHistory({ initialEntries: ['/usage-logs/common'] }),
|
||||
})
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
render(
|
||||
<QueryClientProvider client={client}>
|
||||
<RouterProvider router={router} />
|
||||
</QueryClientProvider>
|
||||
)
|
||||
await screen.findByRole('combobox')
|
||||
return router
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('marks only retired log types as deprecated while keeping historical filters selectable', async () => {
|
||||
const router = await renderFilter()
|
||||
await userEvent.click(screen.getByRole('combobox'))
|
||||
for (const label of ['Manage', 'Login']) {
|
||||
expect(
|
||||
within(
|
||||
screen.getByRole('option', { name: new RegExp(`^${label}`) })
|
||||
).getByText('Deprecated')
|
||||
).toBeVisible()
|
||||
}
|
||||
for (const label of [
|
||||
'All Types',
|
||||
'Top-up',
|
||||
'Consume',
|
||||
'System',
|
||||
'Error',
|
||||
'Refund',
|
||||
]) {
|
||||
expect(
|
||||
within(screen.getByRole('option', { name: label })).queryByText(
|
||||
'Deprecated'
|
||||
)
|
||||
).not.toBeInTheDocument()
|
||||
}
|
||||
await userEvent.click(screen.getByRole('option', { name: /^Manage/ }))
|
||||
expect(screen.getByRole('combobox')).toHaveTextContent('Deprecated')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Search' }))
|
||||
await waitFor(() =>
|
||||
expect(router.state.location.search).toMatchObject({ type: ['3'], page: 1 })
|
||||
)
|
||||
await userEvent.click(screen.getByRole('combobox'))
|
||||
await userEvent.click(screen.getByRole('option', { name: /^Login/ }))
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Search' }))
|
||||
await waitFor(() =>
|
||||
expect(router.state.location.search).toMatchObject({ type: ['7'], page: 1 })
|
||||
)
|
||||
})
|
||||
@@ -23,6 +23,7 @@ import { Eye, EyeOff } from 'lucide-react'
|
||||
import { useState, useCallback, useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Select,
|
||||
@@ -259,11 +260,14 @@ export function CommonLogsFilterBar<TData>(
|
||||
LOG_TYPE_FILTERS.map((type) => ({
|
||||
value: type.value,
|
||||
label: t(type.label),
|
||||
deprecated: type.deprecated,
|
||||
})),
|
||||
[t]
|
||||
)
|
||||
const logTypeLabel =
|
||||
logTypeItems.find((type) => type.value === logType)?.label ?? t('All Types')
|
||||
const selectedLogType = logTypeItems.find((type) => type.value === logType)
|
||||
const deprecatedTypeDescription = t(
|
||||
'Only used to find historical logs. New records are available in Audit Logs.'
|
||||
)
|
||||
|
||||
const statsBar = (
|
||||
<div className='flex flex-wrap items-center gap-2'>
|
||||
@@ -345,14 +349,50 @@ export function CommonLogsFilterBar<TData>(
|
||||
})
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue>{logTypeLabel}</SelectValue>
|
||||
<SelectTrigger
|
||||
aria-description={
|
||||
selectedLogType?.deprecated ? deprecatedTypeDescription : undefined
|
||||
}
|
||||
>
|
||||
<SelectValue className='min-w-0'>
|
||||
<span className='truncate'>
|
||||
{selectedLogType?.label ?? t('All Types')}
|
||||
</span>
|
||||
{selectedLogType?.deprecated && (
|
||||
<Badge
|
||||
variant='secondary'
|
||||
className='h-4 px-1.5 text-[10px] font-normal'
|
||||
title={deprecatedTypeDescription}
|
||||
>
|
||||
{t('Deprecated')}
|
||||
</Badge>
|
||||
)}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent alignItemWithTrigger={false}>
|
||||
<SelectContent
|
||||
alignItemWithTrigger={false}
|
||||
className='max-w-[calc(100vw-2rem)] min-w-52'
|
||||
>
|
||||
<SelectGroup>
|
||||
{LOG_TYPE_FILTERS.map((type) => (
|
||||
<SelectItem key={type.value} value={type.value}>
|
||||
<SelectItem
|
||||
key={type.value}
|
||||
value={type.value}
|
||||
className='[&_[data-slot=select-item-text]]:items-center'
|
||||
aria-description={
|
||||
type.deprecated ? deprecatedTypeDescription : undefined
|
||||
}
|
||||
>
|
||||
{t(type.label)}
|
||||
{type.deprecated && (
|
||||
<Badge
|
||||
variant='secondary'
|
||||
className='h-4 px-1.5 text-[10px] font-normal'
|
||||
title={deprecatedTypeDescription}
|
||||
>
|
||||
{t('Deprecated')}
|
||||
</Badge>
|
||||
)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
|
||||
@@ -147,6 +147,7 @@ export function CompactDateTimeRangePicker({
|
||||
<Input
|
||||
type='datetime-local'
|
||||
value={draftStart}
|
||||
aria-label={t('Start Time')}
|
||||
onChange={(e) => setDraftStart(e.target.value)}
|
||||
className='h-8 text-sm leading-5 tabular-nums'
|
||||
/>
|
||||
@@ -161,6 +162,7 @@ export function CompactDateTimeRangePicker({
|
||||
<Input
|
||||
type='datetime-local'
|
||||
value={draftEnd}
|
||||
aria-label={t('End Time')}
|
||||
onChange={(e) => setDraftEnd(e.target.value)}
|
||||
className='h-8 text-sm leading-5 tabular-nums'
|
||||
/>
|
||||
|
||||
@@ -55,7 +55,6 @@ import { useTranslation } from 'react-i18next'
|
||||
import { Dialog } from '@/components/dialog'
|
||||
import { StatusBadge, type StatusBadgeProps } from '@/components/status-badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { IconBadge, type IconBadgeTone } from '@/components/ui/icon-badge'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { DynamicPricingBreakdown } from '@/features/pricing/components/dynamic-pricing-breakdown'
|
||||
import { usePricingData } from '@/features/pricing/hooks/use-pricing-data'
|
||||
@@ -85,6 +84,7 @@ import {
|
||||
} from '../../lib/utils'
|
||||
import { USAGE_BILLING_PATH, type LogOtherData } from '../../types'
|
||||
import { PluginAuthorLink } from '../plugin-author-link'
|
||||
import { DetailRow, DetailSection } from './log-detail-layout'
|
||||
|
||||
// Maps a channel-update changed-field token (as recorded by the backend audit)
|
||||
// to its i18n label key for display in the audit details.
|
||||
@@ -105,68 +105,6 @@ function timingTextColorClass(
|
||||
return 'text-rose-600'
|
||||
}
|
||||
|
||||
function DetailRow(props: {
|
||||
label: React.ReactNode
|
||||
value: React.ReactNode
|
||||
mono?: boolean
|
||||
muted?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div className='grid min-w-0 grid-cols-[5.25rem_minmax(0,1fr)] gap-2 text-sm sm:grid-cols-[7rem_minmax(0,1fr)] sm:gap-3'>
|
||||
<span className='text-muted-foreground min-w-0 text-xs'>
|
||||
{props.label}
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
'max-w-full min-w-0 text-xs break-all sm:wrap-break-word',
|
||||
props.mono && 'font-mono',
|
||||
props.muted && 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
{props.value}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DetailSection(props: {
|
||||
icon?: React.ReactNode
|
||||
iconTone?: IconBadgeTone
|
||||
label: string
|
||||
variant?: 'default' | 'danger'
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const isDanger = props.variant === 'danger'
|
||||
const iconTone = isDanger ? 'destructive' : props.iconTone
|
||||
return (
|
||||
<div className='min-w-0 space-y-1.5'>
|
||||
<Label
|
||||
className={cn(
|
||||
'flex items-center gap-1.5 text-xs font-semibold',
|
||||
isDanger && 'text-red-500'
|
||||
)}
|
||||
>
|
||||
{props.icon && (
|
||||
<IconBadge tone={iconTone} size='xs'>
|
||||
{props.icon}
|
||||
</IconBadge>
|
||||
)}
|
||||
{props.label}
|
||||
</Label>
|
||||
<div
|
||||
className={cn(
|
||||
'min-w-0 space-y-1 overflow-hidden rounded-md border p-2.5 max-sm:p-2',
|
||||
isDanger
|
||||
? 'border-red-200 bg-red-50 dark:border-red-900 dark:bg-red-950/20'
|
||||
: 'bg-muted/30'
|
||||
)}
|
||||
>
|
||||
{props.children}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function formatRatio(ratio: number | undefined): string {
|
||||
if (ratio == null) return '-'
|
||||
return ratio.toFixed(4)
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
import { IconBadge, type IconBadgeTone } from '@/components/ui/icon-badge'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export function DetailRow(props: {
|
||||
label: ReactNode
|
||||
value: ReactNode
|
||||
mono?: boolean
|
||||
muted?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div className='grid min-w-0 grid-cols-[5.25rem_minmax(0,1fr)] gap-2 text-sm sm:grid-cols-[7rem_minmax(0,1fr)] sm:gap-3'>
|
||||
<span className='text-muted-foreground min-w-0 text-xs'>
|
||||
{props.label}
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
'max-w-full min-w-0 text-xs break-all sm:wrap-break-word',
|
||||
props.mono && 'font-mono',
|
||||
props.muted && 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
{props.value}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function DetailSection(props: {
|
||||
icon?: ReactNode
|
||||
iconTone?: IconBadgeTone
|
||||
label: string
|
||||
variant?: 'default' | 'danger'
|
||||
children: ReactNode
|
||||
}) {
|
||||
const isDanger = props.variant === 'danger'
|
||||
const iconTone = isDanger ? 'destructive' : props.iconTone
|
||||
return (
|
||||
<div className='min-w-0 space-y-1.5'>
|
||||
<Label
|
||||
className={cn(
|
||||
'flex items-center gap-1.5 text-xs font-semibold',
|
||||
isDanger && 'text-red-500'
|
||||
)}
|
||||
>
|
||||
{props.icon && (
|
||||
<IconBadge tone={iconTone} size='xs'>
|
||||
{props.icon}
|
||||
</IconBadge>
|
||||
)}
|
||||
{props.label}
|
||||
</Label>
|
||||
<div
|
||||
className={cn(
|
||||
'min-w-0 space-y-1 overflow-hidden rounded-md border p-2.5 max-sm:p-2',
|
||||
isDanger
|
||||
? 'border-red-200 bg-red-50 dark:border-red-900 dark:bg-red-950/20'
|
||||
: 'bg-muted/30'
|
||||
)}
|
||||
>
|
||||
{props.children}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -106,11 +106,14 @@ export const LOG_TYPES = [
|
||||
* must not expose the display-only "Unknown" label for that value.
|
||||
*/
|
||||
export const LOG_TYPE_FILTERS = [
|
||||
{ label: 'All Types', value: LOG_TYPE_ALL_VALUE },
|
||||
{ label: 'All Types', value: LOG_TYPE_ALL_VALUE, deprecated: false },
|
||||
...LOG_TYPES.filter((type) => type.value !== LOG_TYPE_ENUM.UNKNOWN).map(
|
||||
(type) => ({
|
||||
label: type.label,
|
||||
value: String(type.value),
|
||||
deprecated:
|
||||
type.value === LOG_TYPE_ENUM.MANAGE ||
|
||||
type.value === LOG_TYPE_ENUM.LOGIN,
|
||||
})
|
||||
),
|
||||
] as const
|
||||
|
||||
@@ -128,16 +128,16 @@ function UsageLogsContent() {
|
||||
<SectionPageLayout.Title>
|
||||
{t(pageMeta.titleKey)}
|
||||
</SectionPageLayout.Title>
|
||||
{canManageScope && (
|
||||
<SectionPageLayout.Actions>
|
||||
<SectionPageLayout.Actions>
|
||||
{canManageScope && (
|
||||
<Tabs value={viewScope} onValueChange={handleViewScopeChange}>
|
||||
<TabsList>
|
||||
<TabsTrigger value='all'>{t('All')}</TabsTrigger>
|
||||
<TabsTrigger value='self'>{t('Only Mine')}</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
</SectionPageLayout.Actions>
|
||||
)}
|
||||
)}
|
||||
</SectionPageLayout.Actions>
|
||||
<SectionPageLayout.Content>
|
||||
<div className='flex h-full min-h-0 flex-col gap-4'>
|
||||
{showTaskSwitcher && (
|
||||
|
||||
@@ -389,6 +389,14 @@ export function formatDuration(
|
||||
* translatable instead of being frozen to whatever language was written to DB.
|
||||
*/
|
||||
const AUDIT_TEMPLATES: Record<string, string> = {
|
||||
'access_token.generate': 'Generated a system access token',
|
||||
'access_token.revoke': 'Revoked the system access token',
|
||||
'user.2fa_setup': 'Started two-factor authentication setup',
|
||||
'user.2fa_enable': 'Enabled two-factor authentication',
|
||||
'user.2fa_disable_self': 'Disabled two-factor authentication',
|
||||
'user.2fa_backup_codes': 'Regenerated two-factor backup codes',
|
||||
'user.security_verify': 'Completed security verification',
|
||||
|
||||
login: 'Logged in successfully via {{method}}',
|
||||
// User management
|
||||
'user.create': 'Created user {{username}} (role {{role}})',
|
||||
@@ -421,6 +429,9 @@ const AUDIT_TEMPLATES: Record<string, string> = {
|
||||
// Channel
|
||||
'channel.create': 'Created channel {{name}} (type {{type}}, count {{count}})',
|
||||
'channel.update': 'Updated channel {{name}} (ID: {{id}})',
|
||||
'channel.status_update': 'Updated channel status (ID: {{id}})',
|
||||
'channel.status_update_batch':
|
||||
'Batch updated channel status ({{count}}/{{total}} changed)',
|
||||
'channel.delete': 'Deleted channel {{name}} (ID: {{id}})',
|
||||
'channel.delete_batch': 'Batch deleted {{count}} channels',
|
||||
'channel.delete_disabled': 'Deleted all disabled channels ({{count}})',
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { cleanup, render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
|
||||
import { api } from '@/lib/api'
|
||||
import { useAuthStore } from '@/stores/auth-store'
|
||||
|
||||
import type { User } from '../../types'
|
||||
import { UsersMutateDrawer } from '../users-mutate-drawer'
|
||||
import { UsersProvider } from '../users-provider'
|
||||
|
||||
const target: User = {
|
||||
id: 2,
|
||||
username: 'managed-admin',
|
||||
display_name: 'Managed admin',
|
||||
role: 10,
|
||||
status: 1,
|
||||
quota: 0,
|
||||
used_quota: 0,
|
||||
request_count: 0,
|
||||
group: 'default',
|
||||
}
|
||||
const label = "View other accounts' audit logs"
|
||||
const description =
|
||||
'View audit records from user and admin roles. Root records are always excluded.'
|
||||
|
||||
function renderPermissions(viewerRole: number, allowed?: boolean) {
|
||||
useAuthStore
|
||||
.getState()
|
||||
.auth.setUser({ id: 1, username: 'operator', role: viewerRole })
|
||||
vi.spyOn(api, 'get').mockImplementation(async (url) => {
|
||||
if (url === '/api/authz/catalog') {
|
||||
return {
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
resources: [
|
||||
{
|
||||
resource: 'audit',
|
||||
label_key: 'Audit Logs',
|
||||
actions: [
|
||||
{
|
||||
action: 'read',
|
||||
label_key: label,
|
||||
description_key: description,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
roles: [{ key: 'admin', grants: { audit: { read: false } } }],
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
if (url === '/api/group/') {
|
||||
return { data: { success: true, data: ['default'] } }
|
||||
}
|
||||
return {
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
...target,
|
||||
admin_permissions:
|
||||
allowed === undefined ? {} : { audit: { read: allowed } },
|
||||
},
|
||||
},
|
||||
}
|
||||
})
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
return render(
|
||||
<QueryClientProvider client={client}>
|
||||
<UsersProvider>
|
||||
<UsersMutateDrawer
|
||||
open
|
||||
onOpenChange={() => undefined}
|
||||
currentRow={target}
|
||||
/>
|
||||
</UsersProvider>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.restoreAllMocks()
|
||||
useAuthStore.getState().auth.reset()
|
||||
})
|
||||
|
||||
it.each([undefined, true])(
|
||||
'root can save an audit grant or revocation from the existing editor (previous=%s)',
|
||||
async (allowed) => {
|
||||
const put = vi
|
||||
.spyOn(api, 'put')
|
||||
.mockResolvedValue({ data: { success: true } })
|
||||
renderPermissions(100, allowed)
|
||||
await screen.findByDisplayValue('Managed admin')
|
||||
const checkbox = await screen.findByRole('checkbox', {
|
||||
name: new RegExp(label),
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(checkbox).toHaveAttribute('aria-checked', String(!!allowed))
|
||||
)
|
||||
expect(screen.getByText(description)).toBeVisible()
|
||||
await userEvent.click(checkbox)
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Save changes' }))
|
||||
await waitFor(() =>
|
||||
expect(put).toHaveBeenCalledWith(
|
||||
'/api/user/',
|
||||
expect.objectContaining({
|
||||
id: 2,
|
||||
admin_permissions: { audit: { read: !allowed } },
|
||||
})
|
||||
)
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
it('admin cannot edit the audit permission even when the catalog is available', async () => {
|
||||
renderPermissions(10)
|
||||
await screen.findByDisplayValue('Managed admin')
|
||||
expect(
|
||||
screen.queryByRole('checkbox', { name: new RegExp(label) })
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
@@ -89,7 +89,7 @@ import {
|
||||
transformFormDataToPayload,
|
||||
transformUserToFormDefaults,
|
||||
} from '../lib'
|
||||
import { type User } from '../types'
|
||||
import type { User } from '../types'
|
||||
import { UserQuotaDialog } from './user-quota-dialog'
|
||||
import { useUsers } from './users-provider'
|
||||
|
||||
@@ -136,11 +136,13 @@ export function UsersMutateDrawer({
|
||||
useEffect(() => {
|
||||
if (open && isUpdate && currentRow) {
|
||||
// For update, fetch fresh data
|
||||
getUser(currentRow.id).then((result) => {
|
||||
if (result.success && result.data) {
|
||||
form.reset(transformUserToFormDefaults(result.data))
|
||||
}
|
||||
})
|
||||
getUser(currentRow.id)
|
||||
.then((result) => {
|
||||
if (result.success && result.data) {
|
||||
form.reset(transformUserToFormDefaults(result.data))
|
||||
}
|
||||
})
|
||||
.catch(() => undefined)
|
||||
} else if (open && !isUpdate) {
|
||||
// For create, reset to defaults
|
||||
form.reset(USER_FORM_DEFAULT_VALUES)
|
||||
@@ -195,7 +197,7 @@ export function UsersMutateDrawer({
|
||||
: t(ERROR_MESSAGES.CREATE_FAILED))
|
||||
)
|
||||
}
|
||||
} catch (_error) {
|
||||
} catch {
|
||||
toast.error(t(ERROR_MESSAGES.UNEXPECTED))
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
@@ -360,12 +362,10 @@ export function UsersMutateDrawer({
|
||||
<FormItem>
|
||||
<FormLabel>{t('Group')}</FormLabel>
|
||||
<Select
|
||||
items={[
|
||||
...groups.map((group) => ({
|
||||
value: group,
|
||||
label: group,
|
||||
})),
|
||||
]}
|
||||
items={groups.map((group) => ({
|
||||
value: group,
|
||||
label: group,
|
||||
}))}
|
||||
onValueChange={field.onChange}
|
||||
value={field.value}
|
||||
>
|
||||
@@ -549,7 +549,7 @@ export function UsersMutateDrawer({
|
||||
</h3>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t(
|
||||
'Third-party account bindings (read-only, managed by user in profile settings)'
|
||||
'Third-party account bindings (read-only, managed by user in Security & Access)'
|
||||
)}
|
||||
</p>
|
||||
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { cleanup, renderHook } from '@testing-library/react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { checkIsActive } from '@/components/layout/lib/url-utils'
|
||||
import {
|
||||
parseSidebarModulesAdmin,
|
||||
serializeSidebarModulesAdmin,
|
||||
} from '@/features/system-settings/maintenance/config'
|
||||
import { useAuthStore } from '@/stores/auth-store'
|
||||
|
||||
import { useSidebarConfig } from '../use-sidebar-config'
|
||||
import { useSidebarData } from '../use-sidebar-data'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('localStorage', {
|
||||
getItem: () => null,
|
||||
setItem: () => undefined,
|
||||
removeItem: () => undefined,
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.unstubAllGlobals()
|
||||
useAuthStore.getState().auth.reset()
|
||||
})
|
||||
|
||||
function sidebarFor(admin?: object, user?: object, canConfigure = true) {
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
client.setQueryData(['status'], {
|
||||
SidebarModulesAdmin: admin ? JSON.stringify(admin) : '',
|
||||
})
|
||||
useAuthStore.getState().auth.setUser({
|
||||
id: 1,
|
||||
username: 'alice',
|
||||
role: 1,
|
||||
permissions: { sidebar_settings: canConfigure },
|
||||
sidebar_modules: user ? JSON.stringify(user) : '',
|
||||
})
|
||||
function Wrapper(props: { children: ReactNode }) {
|
||||
return (
|
||||
<QueryClientProvider client={client}>
|
||||
{props.children}
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
const result = renderHook(
|
||||
() => useSidebarConfig(useSidebarData().navGroups),
|
||||
{ wrapper: Wrapper }
|
||||
)
|
||||
return result
|
||||
}
|
||||
|
||||
describe('security sidebar visibility', () => {
|
||||
it('old configurations show Security & Access immediately after Profile and keep API Keys', () => {
|
||||
const { result } = sidebarFor(
|
||||
{ personal: { enabled: true, personal: true, topup: true } },
|
||||
{ personal: { enabled: true, personal: true } }
|
||||
)
|
||||
expect(
|
||||
result.current
|
||||
.find((group) => group.id === 'personal')
|
||||
?.items.map((item) => item.title)
|
||||
).toEqual(['Wallet', 'Profile', 'Security & Access'])
|
||||
expect(
|
||||
result.current
|
||||
.flatMap((group) => group.items)
|
||||
.some((item) => item.title === 'API Keys')
|
||||
).toBe(true)
|
||||
})
|
||||
it.each([
|
||||
[{ personal: { enabled: true, security: false } }, undefined],
|
||||
[{ personal: { enabled: false } }, { personal: { security: true } }],
|
||||
[undefined, { personal: { enabled: true, security: false } }],
|
||||
[undefined, { personal: { enabled: false } }],
|
||||
])(
|
||||
'admin or user disablement hides Security & Access (%j, %j)',
|
||||
(admin, user) => {
|
||||
const { result } = sidebarFor(admin, user)
|
||||
expect(
|
||||
result.current
|
||||
.flatMap((group) => group.items)
|
||||
.some((item) => item.title === 'Security & Access')
|
||||
).toBe(false)
|
||||
}
|
||||
)
|
||||
it('users without sidebar configuration permission retain the admin view', () => {
|
||||
const { result } = sidebarFor(
|
||||
undefined,
|
||||
{ personal: { security: false } },
|
||||
false
|
||||
)
|
||||
expect(
|
||||
result.current
|
||||
.flatMap((group) => group.items)
|
||||
.some((item) => item.title === 'Security & Access')
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('audit log sidebar entry', () => {
|
||||
it('admin settings default Audit Logs to visible and preserve its independent toggle when saved', () => {
|
||||
const config = parseSidebarModulesAdmin(
|
||||
'{"console":{"enabled":true,"log":true}}'
|
||||
)
|
||||
expect(config.console.audit).toBe(true)
|
||||
config.console.audit = false
|
||||
const saved = parseSidebarModulesAdmin(serializeSidebarModulesAdmin(config))
|
||||
const { result } = sidebarFor(saved)
|
||||
const titles = result.current
|
||||
.flatMap((group) => group.items)
|
||||
.map((item) => item.title)
|
||||
expect(titles).not.toContain('Audit Logs')
|
||||
expect(titles).toContain('Usage Logs')
|
||||
})
|
||||
|
||||
it('legacy configurations show a separate Audit Logs link immediately after Usage Logs', () => {
|
||||
const { result } = sidebarFor(
|
||||
{ console: { enabled: true, log: true } },
|
||||
{ console: { enabled: true, log: true } }
|
||||
)
|
||||
const items =
|
||||
result.current.find((group) => group.id === 'general')?.items ?? []
|
||||
const usageIndex = items.findIndex((item) => item.title === 'Usage Logs')
|
||||
expect(items[usageIndex + 1]).toMatchObject({
|
||||
title: 'Audit Logs',
|
||||
url: '/usage-logs/audit',
|
||||
})
|
||||
const selected = items.filter((item) =>
|
||||
checkIsActive('/usage-logs/audit', item)
|
||||
)
|
||||
expect(selected.map((item) => item.title)).toEqual(['Audit Logs'])
|
||||
})
|
||||
|
||||
it.each([
|
||||
[{ console: { enabled: true, audit: false } }, undefined],
|
||||
[{ console: { enabled: false } }, { console: { audit: true } }],
|
||||
[undefined, { console: { enabled: true, audit: false } }],
|
||||
[undefined, { console: { enabled: false } }],
|
||||
])(
|
||||
'admin and personal visibility rules can hide Audit Logs (%j, %j)',
|
||||
(admin, user) => {
|
||||
const { result } = sidebarFor(admin, user)
|
||||
expect(
|
||||
result.current
|
||||
.flatMap((group) => group.items)
|
||||
.some((item) => item.title === 'Audit Logs')
|
||||
).toBe(false)
|
||||
}
|
||||
)
|
||||
|
||||
it('hiding Usage Logs does not hide the independently configured Audit Logs entry', () => {
|
||||
const { result } = sidebarFor({ console: { enabled: true, log: false } })
|
||||
const titles = result.current
|
||||
.flatMap((group) => group.items)
|
||||
.map((item) => item.title)
|
||||
expect(titles).not.toContain('Usage Logs')
|
||||
expect(titles).toContain('Audit Logs')
|
||||
})
|
||||
})
|
||||
@@ -47,6 +47,7 @@ const DEFAULT_SIDEBAR_MODULES: SidebarModulesAdminConfig = {
|
||||
detail: true,
|
||||
token: true,
|
||||
log: true,
|
||||
audit: true,
|
||||
midjourney: true,
|
||||
task: true,
|
||||
},
|
||||
@@ -54,6 +55,7 @@ const DEFAULT_SIDEBAR_MODULES: SidebarModulesAdminConfig = {
|
||||
enabled: true,
|
||||
topup: true,
|
||||
personal: true,
|
||||
security: true,
|
||||
},
|
||||
admin: {
|
||||
enabled: true,
|
||||
@@ -103,10 +105,12 @@ const URL_TO_CONFIG_MAP: Record<string, { section: string; module: string }> = {
|
||||
'/keys': { section: 'console', module: 'token' },
|
||||
'/usage-logs': { section: 'console', module: 'log' },
|
||||
'/usage-logs/common': { section: 'console', module: 'log' },
|
||||
'/usage-logs/audit': { section: 'console', module: 'audit' },
|
||||
'/usage-logs/drawing': { section: 'console', module: 'midjourney' },
|
||||
'/usage-logs/task': { section: 'console', module: 'task' },
|
||||
'/wallet': { section: 'personal', module: 'topup' },
|
||||
'/profile': { section: 'personal', module: 'personal' },
|
||||
'/security': { section: 'personal', module: 'security' },
|
||||
'/channels': { section: 'admin', module: 'channel' },
|
||||
'/models': { section: 'admin', module: 'models' },
|
||||
'/models/metadata': { section: 'admin', module: 'models' },
|
||||
|
||||
@@ -19,6 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
|
||||
import {
|
||||
Activity,
|
||||
Box,
|
||||
ClipboardList,
|
||||
CreditCard,
|
||||
FileText,
|
||||
FlaskConical,
|
||||
@@ -30,6 +31,7 @@ import {
|
||||
Radio,
|
||||
ServerCog,
|
||||
Settings,
|
||||
ShieldCheck,
|
||||
Ticket,
|
||||
User,
|
||||
Users,
|
||||
@@ -37,7 +39,7 @@ import {
|
||||
} from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { type SidebarData } from '@/components/layout/types'
|
||||
import type { SidebarData } from '@/components/layout/types'
|
||||
import { ROLE } from '@/lib/roles'
|
||||
|
||||
/**
|
||||
@@ -91,6 +93,11 @@ export function useSidebarData(): SidebarData {
|
||||
url: '/usage-logs/common',
|
||||
icon: FileText,
|
||||
},
|
||||
{
|
||||
title: t('Audit Logs'),
|
||||
url: '/usage-logs/audit',
|
||||
icon: ClipboardList,
|
||||
},
|
||||
{
|
||||
title: t('Task Logs'),
|
||||
url: '/usage-logs/task',
|
||||
@@ -114,6 +121,11 @@ export function useSidebarData(): SidebarData {
|
||||
url: '/profile',
|
||||
icon: User,
|
||||
},
|
||||
{
|
||||
title: t('Security & Access'),
|
||||
url: '/security',
|
||||
icon: ShieldCheck,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -138,15 +138,19 @@
|
||||
"Access Forbidden": "Access Forbidden",
|
||||
"Access Policy (JSON)": "Access Policy (JSON)",
|
||||
"Access previous conversations and start new ones.": "Access previous conversations and start new ones.",
|
||||
"Access records": "Access records",
|
||||
"Access Token": "Access Token",
|
||||
"Access token revoked": "Access token revoked",
|
||||
"Access tokens are shown only once": "Access tokens are shown only once",
|
||||
"AccessKey / SecretAccessKey": "AccessKey / SecretAccessKey",
|
||||
"Account Actions": "Account Actions",
|
||||
"Account Binding Management": "Account Binding Management",
|
||||
"Account Bindings": "Account Bindings",
|
||||
"Account created! Please sign in": "Account created! Please sign in",
|
||||
"Account deleted successfully": "Account deleted successfully",
|
||||
"Account ID *": "Account ID *",
|
||||
"Account Info": "Account Info",
|
||||
"Account security": "Account security",
|
||||
"Account used when authenticating with the SMTP server": "Account used when authenticating with the SMTP server",
|
||||
"acknowledge the related legal risks": "acknowledge the related legal risks",
|
||||
"Across all groups": "Across all groups",
|
||||
@@ -315,11 +319,13 @@
|
||||
"All nodes": "All nodes",
|
||||
"All playground messages saved in this browser will be removed. This cannot be undone.": "All playground messages saved in this browser will be removed. This cannot be undone.",
|
||||
"All requests must include": "All requests must include",
|
||||
"All results": "All results",
|
||||
"All routes": "All routes",
|
||||
"All Status": "All Status",
|
||||
"All Sync Status": "All Sync Status",
|
||||
"All systems operational": "All systems operational",
|
||||
"All Tags": "All Tags",
|
||||
"All tokens": "All tokens",
|
||||
"All Types": "All Types",
|
||||
"All upstream data is trusted": "All upstream data is trusted",
|
||||
"All users": "All users",
|
||||
@@ -510,6 +516,10 @@
|
||||
"Audio Preview": "Audio Preview",
|
||||
"Audio ratio": "Audio ratio",
|
||||
"Audio Tokens": "Audio Tokens",
|
||||
"Audit access changed. Showing only your records.": "Audit access changed. Showing only your records.",
|
||||
"Audit Logs": "Audit Logs",
|
||||
"Audit metadata is unavailable": "Audit metadata is unavailable",
|
||||
"Audit records start after this feature was enabled. Earlier records remain in Common Logs.": "Audit records start after this feature was enabled. Earlier records remain in Common Logs.",
|
||||
"Auth": "Auth",
|
||||
"Auth configured": "Auth configured",
|
||||
"Auth name": "Auth name",
|
||||
@@ -645,6 +655,7 @@
|
||||
"Batch test completed: {{success}} succeeded, {{failed}} failed": "Batch test completed: {{success}} succeeded, {{failed}} failed",
|
||||
"Batch test stopped: {{completed}}/{{total}} completed, {{success}} succeeded, {{failed}} failed": "Batch test stopped: {{completed}}/{{total}} completed, {{success}} succeeded, {{failed}} failed",
|
||||
"Batch testing models...": "Batch testing models...",
|
||||
"Batch updated channel status ({{count}}/{{total}} changed)": "Batch updated channel status ({{count}}/{{total}} changed)",
|
||||
"Batch upstream model update": "Batch upstream model update",
|
||||
"Batch upstream model updates applied: {{channels}} channels, {{added}} added, {{removed}} removed, {{fails}} failed": "Batch upstream model updates applied: {{channels}} channels, {{added}} added, {{removed}} removed, {{fails}} failed",
|
||||
"Best for single-tenant deployments. Pricing and billing options stay hidden.": "Best for single-tenant deployments. Pricing and billing options stay hidden.",
|
||||
@@ -677,6 +688,7 @@
|
||||
"Bind WeChat Account": "Bind WeChat Account",
|
||||
"Binding Information": "Binding Information",
|
||||
"Binding successful!": "Binding successful!",
|
||||
"Binding Type": "Binding Type",
|
||||
"Binding your {{provider}} account": "Binding your {{provider}} account",
|
||||
"Binding...": "Binding...",
|
||||
"Bindings": "Bindings",
|
||||
@@ -782,6 +794,7 @@
|
||||
"Change language": "Change language",
|
||||
"Change Password": "Change Password",
|
||||
"Change To": "Change To",
|
||||
"Changed / Total": "Changed / Total",
|
||||
"Changed Fields": "Changed Fields",
|
||||
"Changes are written to the settings draft on save.": "Changes are written to the settings draft on save.",
|
||||
"Changing...": "Changing...",
|
||||
@@ -928,6 +941,7 @@
|
||||
"Click to view full error message": "Click to view full error message",
|
||||
"Click to view full prompt": "Click to view full prompt",
|
||||
"Click to view image": "Click to view image",
|
||||
"Client": "Client",
|
||||
"Client header value": "Client header value",
|
||||
"Client ID": "Client ID",
|
||||
"Client model": "Client model",
|
||||
@@ -990,6 +1004,7 @@
|
||||
"Complete Order": "Complete Order",
|
||||
"Complete these steps to finish the initial installation.": "Complete these steps to finish the initial installation.",
|
||||
"Completed": "Completed",
|
||||
"Completed security verification": "Completed security verification",
|
||||
"Completed top-up order for the user": "Completed top-up order for the user",
|
||||
"Completion": "Completion",
|
||||
"Completion price": "Completion price",
|
||||
@@ -1132,6 +1147,7 @@
|
||||
"Copied: {{model}}": "Copied: {{model}}",
|
||||
"Copied!": "Copied!",
|
||||
"Copy": "Copy",
|
||||
"Copy {{field}}": "Copy {{field}}",
|
||||
"Copy {{name}} pricing": "Copy {{name}} pricing",
|
||||
"Copy a request header": "Copy a request header",
|
||||
"Copy All": "Copy All",
|
||||
@@ -1264,6 +1280,7 @@
|
||||
"Current Password": "Current Password",
|
||||
"Current Price": "Current Price",
|
||||
"Current quota": "Current quota",
|
||||
"Current token": "Current token",
|
||||
"Current Value": "Current Value",
|
||||
"Current version": "Current version",
|
||||
"Current:": "Current:",
|
||||
@@ -1419,6 +1436,7 @@
|
||||
"Deployment Region *": "Deployment Region *",
|
||||
"Deployment requested": "Deployment requested",
|
||||
"Deployments": "Deployments",
|
||||
"Deprecated": "Deprecated",
|
||||
"Desc": "Desc",
|
||||
"Describe": "Describe",
|
||||
"Describe this model...": "Describe this model...",
|
||||
@@ -1465,6 +1483,7 @@
|
||||
"Disabled lanes are omitted on save.": "Disabled lanes are omitted on save.",
|
||||
"Disabled Reason": "Disabled Reason",
|
||||
"Disabled Time": "Disabled Time",
|
||||
"Disabled two-factor authentication": "Disabled two-factor authentication",
|
||||
"Disabled; fell back to factory": "Disabled; fell back to factory",
|
||||
"Disabled; platform unavailable": "Disabled; platform unavailable",
|
||||
"Disabling...": "Disabling...",
|
||||
@@ -1688,6 +1707,8 @@
|
||||
"Enable test mode for Creem payments": "Enable test mode for Creem payments",
|
||||
"Enable this key?": "Enable this key?",
|
||||
"Enable Turnstile": "Enable Turnstile",
|
||||
"Enable Two-factor Authentication or Passkey in Security & Access to continue.": "Enable Two-factor Authentication or Passkey in Security & Access to continue.",
|
||||
"Enable Two-factor Authentication or Passkey in Security & Access to unlock sensitive operations.": "Enable Two-factor Authentication or Passkey in Security & Access to unlock sensitive operations.",
|
||||
"Enable Two-factor Authentication or Passkey in your profile to unlock sensitive operations.": "Enable Two-factor Authentication or Passkey in your profile to unlock sensitive operations.",
|
||||
"Enable unlimited quota for this API key": "Enable unlimited quota for this API key",
|
||||
"Enable violation deduction": "Enable violation deduction",
|
||||
@@ -1699,6 +1720,7 @@
|
||||
"Enabled all channels with tag: {{tag}}": "Enabled all channels with tag: {{tag}}",
|
||||
"Enabled channels with tag {{tag}}": "Enabled channels with tag {{tag}}",
|
||||
"Enabled Status": "Enabled Status",
|
||||
"Enabled two-factor authentication": "Enabled two-factor authentication",
|
||||
"Enabling...": "Enabling...",
|
||||
"Encourages introducing new topics": "Encourages introducing new topics",
|
||||
"Encourages new topics": "Encourages new topics",
|
||||
@@ -1706,6 +1728,7 @@
|
||||
"End Error": "End Error",
|
||||
"End Reason": "End Reason",
|
||||
"End Time": "End Time",
|
||||
"End time must be after start time": "End time must be after start time",
|
||||
"End-user identifier for abuse monitoring": "End-user identifier for abuse monitoring",
|
||||
"Endpoint": "Endpoint",
|
||||
"Endpoint config": "Endpoint config",
|
||||
@@ -1818,6 +1841,7 @@
|
||||
"Estimated cost": "Estimated cost",
|
||||
"Estimated quota cost": "Estimated quota cost",
|
||||
"Evaluate fields from the provider user info response. Conditions and nested groups use and/or logic.": "Evaluate fields from the provider user info response. Conditions and nested groups use and/or logic.",
|
||||
"Event": "Event",
|
||||
"Every group name in the pricing table can be used in two places: on a user (the user group, assigned by admins) and on a token (the token group, chosen when creating the token). Same name pool, two different jobs.": "Every group name in the pricing table can be used in two places: on a user (the user group, assigned by admins) and on a token (the token group, chosen when creating the token). Same name pool, two different jobs.",
|
||||
"Every other device will lose access immediately. This device will remain signed in.": "Every other device will lose access immediately. This device will remain signed in.",
|
||||
"Everything configured for this group, in one place.": "Everything configured for this group, in one place.",
|
||||
@@ -1950,6 +1974,7 @@
|
||||
"Failed to load": "Failed to load",
|
||||
"Failed to load API keys": "Failed to load API keys",
|
||||
"Failed to load artifacts": "Failed to load artifacts",
|
||||
"Failed to load audit records": "Failed to load audit records",
|
||||
"Failed to load billing history": "Failed to load billing history",
|
||||
"Failed to load enabled models": "Failed to load enabled models",
|
||||
"Failed to load home page content": "Failed to load home page content",
|
||||
@@ -1965,6 +1990,7 @@
|
||||
"Failed to load setup data": "Failed to load setup data",
|
||||
"Failed to load setup status": "Failed to load setup status",
|
||||
"Failed to load tag data": "Failed to load tag data",
|
||||
"Failed to load token status": "Failed to load token status",
|
||||
"Failed to load users": "Failed to load users",
|
||||
"Failed to parse group items": "Failed to parse group items",
|
||||
"Failed to parse JSON file: {{name}}": "Failed to parse JSON file: {{name}}",
|
||||
@@ -1979,6 +2005,7 @@
|
||||
"Failed to reset model ratios": "Failed to reset model ratios",
|
||||
"Failed to reset Passkey": "Failed to reset Passkey",
|
||||
"Failed to reset usage": "Failed to reset usage",
|
||||
"Failed to revoke token": "Failed to revoke token",
|
||||
"Failed to save": "Failed to save",
|
||||
"Failed to save announcements": "Failed to save announcements",
|
||||
"Failed to save API info": "Failed to save API info",
|
||||
@@ -2054,6 +2081,7 @@
|
||||
"Fetching upstream ratios...": "Fetching upstream ratios...",
|
||||
"Fetching...": "Fetching...",
|
||||
"field": "field",
|
||||
"Field change details were not recorded": "Field change details were not recorded",
|
||||
"Field Mapping": "Field Mapping",
|
||||
"Field passthrough controls": "Field passthrough controls",
|
||||
"Field Path": "Field Path",
|
||||
@@ -2202,12 +2230,15 @@
|
||||
"Gemini will continue to auto-detect thinking mode even with the adapter disabled. Enable this only when you need finer control over pricing and budgeting.": "Gemini will continue to auto-detect thinking mode even with the adapter disabled. Enable this only when you need finer control over pricing and budgeting.",
|
||||
"General": "General",
|
||||
"General Settings": "General Settings",
|
||||
"Generate": "Generate",
|
||||
"Generate and manage your API access token": "Generate and manage your API access token",
|
||||
"Generate Lyrics": "Generate Lyrics",
|
||||
"Generate Music": "Generate Music",
|
||||
"Generate new backup codes for account recovery": "Generate new backup codes for account recovery",
|
||||
"Generate New Codes": "Generate New Codes",
|
||||
"Generate tokens from the Tokens page; you can scope them to specific models, groups, IPs, and rate-limits.": "Generate tokens from the Tokens page; you can scope them to specific models, groups, IPs, and rate-limits.",
|
||||
"Generated": "Generated",
|
||||
"Generated a system access token": "Generated a system access token",
|
||||
"Generated image": "Generated image",
|
||||
"Generating new codes will invalidate all existing backup codes.": "Generating new codes will invalidate all existing backup codes.",
|
||||
"Generating...": "Generating...",
|
||||
@@ -2322,6 +2353,7 @@
|
||||
"High-risk status code retry risk check 4": "I voluntarily accept the system stability risks, including severe client timeouts and possible service crashes, and take responsibility for any resulting request backlog or service outage.",
|
||||
"High-risk status code retry risk disclaimer": "### ⚠️ High-risk operation: 504/524 status code retry risk notice and disclaimer\n\nBy default, this project does not retry status codes `400` (bad request), `504` (gateway timeout), or `524` (a timeout occurred). Status codes 504 and 524 usually mean that **the request successfully reached the upstream AI service and upstream processing had begun, but the connection was closed because upstream processing took too long**. This usually points to an upstream service bottleneck.\n\nEnabling redirection/retry for these timeout status codes is an **extremely high-risk operation**. Before enabling it, you must carefully read and understand the following consequences:\n\n#### 1. Core risks (read carefully)\n\n1. 💸 Duplicate or multiple billing: Most upstream AI providers **still charge** for requests that started processing but were interrupted by a network timeout (504/524). A retry sends a brand-new upstream request and can result in **duplicate or multiple charges**.\n2. ⏳ Severe client timeout: Once a request has already timed out, adding retries can multiply total latency and cause severe or unacceptable timeouts for the final client or caller.\n3. 💥 Request backlog and service crash: Forced retries keep threads and connections occupied for longer. Under high concurrency, this can cause a serious **request backlog**, exhaust system resources, trigger cascading failures, and crash the proxy service.\n\n#### 2. Risk acknowledgement\n\nIf you still choose to enable this feature, you acknowledge all of the following:",
|
||||
"Higher priority channels are selected first": "Higher priority channels are selected first",
|
||||
"Historical tokens": "Historical tokens",
|
||||
"Historical Usage": "Historical Usage",
|
||||
"History of MjProxy-style image tasks.": "History of MjProxy-style image tasks.",
|
||||
"Hit criteria: If cached tokens exist in usage, it counts as a hit.": "Hit criteria: If cached tokens exist in usage, it counts as a hit.",
|
||||
@@ -2577,7 +2609,9 @@
|
||||
"Last Seen": "Last Seen",
|
||||
"Last Tested": "Last Tested",
|
||||
"Last updated:": "Last updated:",
|
||||
"Last used": "Last used",
|
||||
"Last Used": "Last Used",
|
||||
"Last used IP": "Last used IP",
|
||||
"Last used:": "Last used:",
|
||||
"Latency": "Latency",
|
||||
"Latency check": "Latency check",
|
||||
@@ -2679,11 +2713,13 @@
|
||||
"Logged in successfully via {{method}}": "Logged in successfully via {{method}}",
|
||||
"Logic": "Logic",
|
||||
"Login": "Login",
|
||||
"Login & Authentication": "Login & Authentication",
|
||||
"Login failed": "Login failed",
|
||||
"Login flow expired. Please sign in again.": "Login flow expired. Please sign in again.",
|
||||
"Login Info": "Login Info",
|
||||
"Login Method": "Login Method",
|
||||
"Login sessions": "Login sessions",
|
||||
"Login, security and access records": "Login, security and access records",
|
||||
"Logo": "Logo",
|
||||
"Logo URL": "Logo URL",
|
||||
"Logs": "Logs",
|
||||
@@ -2779,6 +2815,7 @@
|
||||
"Merge into Other": "Merge into Other",
|
||||
"Message Priority": "Message Priority",
|
||||
"Metadata": "Metadata",
|
||||
"Method": "Method",
|
||||
"min downtime": "min downtime",
|
||||
"Min Top-up": "Min Top-up",
|
||||
"Min Top-up:": "Min Top-up:",
|
||||
@@ -2993,6 +3030,7 @@
|
||||
"New Password": "New Password",
|
||||
"New password must be different from current password": "New password must be different from current password",
|
||||
"New User Quota": "New User Quota",
|
||||
"New value": "New value",
|
||||
"New version available: {{version}}": "New version available: {{version}}",
|
||||
"NewAPI": "NewAPI",
|
||||
"Newly released": "Newly released",
|
||||
@@ -3133,6 +3171,7 @@
|
||||
"No Quota": "No Quota",
|
||||
"No ratio differences found": "No ratio differences found",
|
||||
"No recent usage": "No recent usage",
|
||||
"No records": "No records",
|
||||
"No records found. Try adjusting your filters.": "No records found. Try adjusting your filters.",
|
||||
"No redemption codes available. Create your first redemption code to get started.": "No redemption codes available. Create your first redemption code to get started.",
|
||||
"No Redemption Codes Found": "No Redemption Codes Found",
|
||||
@@ -3192,6 +3231,7 @@
|
||||
"Not configured": "Not configured",
|
||||
"Not declared": "Not declared",
|
||||
"Not Equals": "Not Equals",
|
||||
"Not generated": "Not generated",
|
||||
"Not in pricing table": "Not in pricing table",
|
||||
"Not included": "Not included",
|
||||
"Not installed": "Not installed",
|
||||
@@ -3285,6 +3325,7 @@
|
||||
"Only successful requests": "Only successful requests",
|
||||
"Only successful requests count toward this limit.": "Only successful requests count toward this limit.",
|
||||
"Only the last {{value}} log files will be retained; the rest will be deleted.": "Only the last {{value}} log files will be retained; the rest will be deleted.",
|
||||
"Only used to find historical logs. New records are available in Audit Logs.": "Only used to find historical logs. New records are available in Audit Logs.",
|
||||
"Oops! Page Not Found!": "Oops! Page Not Found!",
|
||||
"Oops! Something went wrong": "Oops! Something went wrong",
|
||||
"Open": "Open",
|
||||
@@ -3325,11 +3366,13 @@
|
||||
"Operate channels": "Operate channels",
|
||||
"Operation": "Operation",
|
||||
"operation and charging behavior": "operation and charging behavior",
|
||||
"Operation audit": "Operation audit",
|
||||
"Operation Audit Info": "Operation Audit Info",
|
||||
"Operation failed": "Operation failed",
|
||||
"Operation successful": "Operation successful",
|
||||
"Operation Type": "Operation Type",
|
||||
"Operations": "Operations",
|
||||
"Operator": "Operator",
|
||||
"Operator Admin": "Operator Admin",
|
||||
"Optimize system for self-hosted single-user usage": "Optimize system for self-hosted single-user usage",
|
||||
"Optimized network architecture ensures millisecond response times": "Optimized network architecture ensures millisecond response times",
|
||||
@@ -3545,6 +3588,7 @@
|
||||
"Pick or create both a store and a product before saving.": "Pick or create both a store and a product before saving.",
|
||||
"Ping Interval (seconds)": "Ping Interval (seconds)",
|
||||
"Plan": "Plan",
|
||||
"Plan ID": "Plan ID",
|
||||
"Plan Name": "Plan Name",
|
||||
"Plan Price": "Plan Price",
|
||||
"Plan price must be greater than zero": "Plan price must be greater than zero",
|
||||
@@ -3684,6 +3728,7 @@
|
||||
"Previous": "Previous",
|
||||
"Previous branch": "Previous branch",
|
||||
"Previous page": "Previous page",
|
||||
"Previous value": "Previous value",
|
||||
"Price": "Price",
|
||||
"Price ($/1K calls)": "Price ($/1K calls)",
|
||||
"Price (local currency / USD)": "Price (local currency / USD)",
|
||||
@@ -3719,6 +3764,7 @@
|
||||
"Priority level from 0 (lowest) to 10 (highest), default is 5": "Priority level from 0 (lowest) to 10 (highest), default is 5",
|
||||
"Priority order for automatic group assignment. New tokens rotate through this list.": "Priority order for automatic group assignment. New tokens rotate through this list.",
|
||||
"Priority order for tokens in the auto group. The system tries groups from top to bottom.": "Priority order for tokens in the auto group. The system tries groups from top to bottom.",
|
||||
"Privacy": "Privacy",
|
||||
"Privacy Policy": "Privacy Policy",
|
||||
"Private Deployment URL": "Private Deployment URL",
|
||||
"Processing OAuth response...": "Processing OAuth response...",
|
||||
@@ -3910,6 +3956,7 @@
|
||||
"Regenerate access token?": "Regenerate access token?",
|
||||
"Regenerate Backup Codes": "Regenerate Backup Codes",
|
||||
"Regenerate token": "Regenerate token",
|
||||
"Regenerated two-factor backup codes": "Regenerated two-factor backup codes",
|
||||
"Regenerating immediately invalidates any existing token.": "Regenerating immediately invalidates any existing token.",
|
||||
"Regex": "Regex",
|
||||
"Regex Pattern": "Regex Pattern",
|
||||
@@ -4043,6 +4090,7 @@
|
||||
"Reset balance and used quota": "Reset balance and used quota",
|
||||
"Reset completed": "Reset completed",
|
||||
"Reset completed. Latest usage has been refreshed.": "Reset completed. Latest usage has been refreshed.",
|
||||
"Reset Count": "Reset Count",
|
||||
"Reset count:": "Reset count:",
|
||||
"Reset Credit": "Reset Credit",
|
||||
"Reset Credits": "Reset Credits",
|
||||
@@ -4105,7 +4153,9 @@
|
||||
"Review your payment details": "Review your payment details",
|
||||
"Review your purchase details before proceeding.": "Review your purchase details before proceeding.",
|
||||
"Revoke": "Revoke",
|
||||
"Revoke access token?": "Revoke access token?",
|
||||
"Revoke session?": "Revoke session?",
|
||||
"Revoked the system access token": "Revoked the system access token",
|
||||
"Rewards will be added directly to your balance": "Rewards will be added directly to your balance",
|
||||
"Rewrite callback URLs to the local server": "Rewrite callback URLs to the local server",
|
||||
"Right to Left": "Right to Left",
|
||||
@@ -4255,6 +4305,7 @@
|
||||
"Secure & Reliable": "Secure & Reliable",
|
||||
"Secured": "Secured",
|
||||
"Security": "Security",
|
||||
"Security & Access": "Security & Access",
|
||||
"Security & Limits": "Security & Limits",
|
||||
"Security Check": "Security Check",
|
||||
"Security verification": "Security verification",
|
||||
@@ -4372,6 +4423,7 @@
|
||||
"Session expired!": "Session expired!",
|
||||
"Session expired?": "Session expired?",
|
||||
"Session signed out": "Session signed out",
|
||||
"Sessions & Access": "Sessions & Access",
|
||||
"Set": "Set",
|
||||
"Set a discount rate for a specific recharge amount threshold.": "Set a discount rate for a specific recharge amount threshold.",
|
||||
"Set a secure password (min. 8 characters)": "Set a secure password (min. 8 characters)",
|
||||
@@ -4486,6 +4538,7 @@
|
||||
"Source Endpoint": "Source Endpoint",
|
||||
"Source Field": "Source Field",
|
||||
"Source Header": "Source Header",
|
||||
"Source ID": "Source ID",
|
||||
"Source name": "Source name",
|
||||
"sources": "sources",
|
||||
"Space-separated OAuth scopes": "Space-separated OAuth scopes",
|
||||
@@ -4515,7 +4568,9 @@
|
||||
"Start for free with generous limits. No credit card required.": "Start for free with generous limits. No credit card required.",
|
||||
"Start Time": "Start Time",
|
||||
"Started": "Started",
|
||||
"Started two-factor authentication setup": "Started two-factor authentication setup",
|
||||
"STARTTLS": "STARTTLS",
|
||||
"State changed": "State changed",
|
||||
"Static page describing the platform.": "Static page describing the platform.",
|
||||
"Statistical count": "Statistical count",
|
||||
"Statistical quota": "Statistical quota",
|
||||
@@ -4664,6 +4719,7 @@
|
||||
"Tags": "Tags",
|
||||
"Take photo": "Take photo",
|
||||
"Take screenshot": "Take screenshot",
|
||||
"Target": "Target",
|
||||
"Target Endpoint": "Target Endpoint",
|
||||
"Target Field": "Target Field",
|
||||
"Target Field Path": "Target Field Path",
|
||||
@@ -4788,6 +4844,7 @@
|
||||
"Third-party": "Third-party",
|
||||
"Third-party — use at your own risk": "Third-party — use at your own risk",
|
||||
"Third-party account bindings (read-only, managed by user in profile settings)": "Third-party account bindings (read-only, managed by user in profile settings)",
|
||||
"Third-party account bindings (read-only, managed by user in Security & Access)": "Third-party account bindings (read-only, managed by user in Security & Access)",
|
||||
"Third-party Payment Config": "Third-party Payment Config",
|
||||
"Third-party plugin risk": "Third-party plugin risk",
|
||||
"Third-party source risk": "Third-party source risk",
|
||||
@@ -4924,6 +4981,7 @@
|
||||
"Token estimator": "Token estimator",
|
||||
"Token group": "Token group",
|
||||
"Token has no group": "Token has no group",
|
||||
"Token identifier": "Token identifier",
|
||||
"Token Limits": "Token Limits",
|
||||
"Token management": "Token management",
|
||||
"Token Management": "Token Management",
|
||||
@@ -4937,6 +4995,7 @@
|
||||
"Token price for image input.": "Token price for image input.",
|
||||
"Token prices": "Token prices",
|
||||
"Token regenerated and copied to clipboard": "Token regenerated and copied to clipboard",
|
||||
"Token scope": "Token scope",
|
||||
"Token share by model author across the last 24 hours": "Token share by model author across the last 24 hours",
|
||||
"Token share by model author across the past few weeks": "Token share by model author across the past few weeks",
|
||||
"Token share by model author across the past month": "Token share by model author across the past month",
|
||||
@@ -4986,6 +5045,7 @@
|
||||
"Top-up ratio": "Top-up ratio",
|
||||
"Topup Amount": "Topup Amount",
|
||||
"Total": "Total",
|
||||
"Total {{count}} records": "Total {{count}} records",
|
||||
"Total Allocated": "Total Allocated",
|
||||
"Total check-ins": "Total check-ins",
|
||||
"Total consumed": "Total consumed",
|
||||
@@ -5133,6 +5193,7 @@
|
||||
"Updated a subscription plan": "Updated a subscription plan",
|
||||
"Updated a vendor": "Updated a vendor",
|
||||
"Updated channel {{name}} (ID: {{id}})": "Updated channel {{name}} (ID: {{id}})",
|
||||
"Updated channel status (ID: {{id}})": "Updated channel status (ID: {{id}})",
|
||||
"Updated daily": "Updated daily",
|
||||
"Updated successfully": "Updated successfully",
|
||||
"Updated system setting {{key}}": "Updated system setting {{key}}",
|
||||
@@ -5260,6 +5321,7 @@
|
||||
"User Analytics": "User Analytics",
|
||||
"User Consumption Ranking": "User Consumption Ranking",
|
||||
"User Consumption Trend": "User Consumption Trend",
|
||||
"User Count": "User Count",
|
||||
"User created successfully": "User created successfully",
|
||||
"User dashboard and quota controls.": "User dashboard and quota controls.",
|
||||
"User deleted successfully": "User deleted successfully",
|
||||
@@ -5354,6 +5416,7 @@
|
||||
"Vidu": "Vidu",
|
||||
"View": "View",
|
||||
"View all currently available models": "View all currently available models",
|
||||
"View audit records from user and admin roles. Root records are always excluded.": "View audit records from user and admin roles. Root records are always excluded.",
|
||||
"View channel lists and details without secrets.": "View channel lists and details without secrets.",
|
||||
"View channel secrets": "View channel secrets",
|
||||
"View detailed information about this user including balance, usage statistics, and invitation details.": "View detailed information about this user including balance, usage statistics, and invitation details.",
|
||||
@@ -5363,7 +5426,9 @@
|
||||
"View logs": "View logs",
|
||||
"View mode": "View mode",
|
||||
"View model statistics and charts": "View model statistics and charts",
|
||||
"View other accounts' audit logs": "View other accounts' audit logs",
|
||||
"View Pricing": "View Pricing",
|
||||
"View scope": "View scope",
|
||||
"View the complete details for this": "View the complete details for this",
|
||||
"View the complete details for this log entry": "View the complete details for this log entry",
|
||||
"View the complete details for this task": "View the complete details for this task",
|
||||
|
||||
@@ -138,15 +138,19 @@
|
||||
"Access Forbidden": "Accès interdit",
|
||||
"Access Policy (JSON)": "Politique d'accès (JSON)",
|
||||
"Access previous conversations and start new ones.": "Accéder aux conversations précédentes et en démarrer de nouvelles.",
|
||||
"Access records": "Historique d’accès",
|
||||
"Access Token": "Jeton d'accès",
|
||||
"Access token revoked": "Jeton d’accès révoqué",
|
||||
"Access tokens are shown only once": "Les jetons d'accès ne sont affichés qu'une seule fois",
|
||||
"AccessKey / SecretAccessKey": "AccessKey / SecretAccessKey",
|
||||
"Account Actions": "Actions sur le compte",
|
||||
"Account Binding Management": "Gestion des liaisons de compte",
|
||||
"Account Bindings": "Associations de compte",
|
||||
"Account created! Please sign in": "Compte créé ! Veuillez vous connecter",
|
||||
"Account deleted successfully": "Compte supprimé avec succès",
|
||||
"Account ID *": "ID de compte *",
|
||||
"Account Info": "Informations du compte",
|
||||
"Account security": "Sécurité du compte",
|
||||
"Account used when authenticating with the SMTP server": "Compte utilisé lors de l'authentification auprès du serveur SMTP",
|
||||
"acknowledge the related legal risks": "reconnais les risques juridiques associés",
|
||||
"Across all groups": "Tous groupes confondus",
|
||||
@@ -315,11 +319,13 @@
|
||||
"All nodes": "Tous les nœuds",
|
||||
"All playground messages saved in this browser will be removed. This cannot be undone.": "Tous les messages du Playground enregistrés dans ce navigateur seront supprimés. Cette action est irréversible.",
|
||||
"All requests must include": "Toutes les requêtes doivent inclure",
|
||||
"All results": "Tous les résultats",
|
||||
"All routes": "Toutes les routes",
|
||||
"All Status": "Tous les statuts",
|
||||
"All Sync Status": "Tous les statuts de synchronisation",
|
||||
"All systems operational": "Tous les systèmes opérationnels",
|
||||
"All Tags": "Tous les tags",
|
||||
"All tokens": "Tous les jetons",
|
||||
"All Types": "Tous les types",
|
||||
"All upstream data is trusted": "Toutes les données en amont sont fiables",
|
||||
"All users": "Tous les utilisateurs",
|
||||
@@ -510,6 +516,10 @@
|
||||
"Audio Preview": "Aperçu audio",
|
||||
"Audio ratio": "Ratio audio",
|
||||
"Audio Tokens": "Jetons audio",
|
||||
"Audit access changed. Showing only your records.": "Les droits d’accès aux audits ont changé. Seuls vos événements sont affichés.",
|
||||
"Audit Logs": "Journaux d’audit",
|
||||
"Audit metadata is unavailable": "Les informations supplémentaires de cet audit sont indisponibles",
|
||||
"Audit records start after this feature was enabled. Earlier records remain in Common Logs.": "Les audits commencent à l’activation de cette fonction. Les anciens événements restent dans les journaux généraux.",
|
||||
"Auth": "Auth",
|
||||
"Auth configured": "Authentification configurée",
|
||||
"Auth name": "Nom auth",
|
||||
@@ -645,6 +655,7 @@
|
||||
"Batch test completed: {{success}} succeeded, {{failed}} failed": "Test par lots terminé : {{success}} réussi(s), {{failed}} échoué(s)",
|
||||
"Batch test stopped: {{completed}}/{{total}} completed, {{success}} succeeded, {{failed}} failed": "Test par lots arrêté : {{completed}}/{{total}} terminé(s), {{success}} réussi(s), {{failed}} échoué(s)",
|
||||
"Batch testing models...": "Test des modèles par lots...",
|
||||
"Batch updated channel status ({{count}}/{{total}} changed)": "Statuts des canaux mis à jour par lot ({{count}}/{{total}} modifiés)",
|
||||
"Batch upstream model update": "Mise à jour groupée des modèles en amont",
|
||||
"Batch upstream model updates applied: {{channels}} channels, {{added}} added, {{removed}} removed, {{fails}} failed": "Mises à jour par lot des modèles en amont appliquées : {{channels}} canaux, {{added}} ajoutés, {{removed}} supprimés, {{fails}} échoués",
|
||||
"Best for single-tenant deployments. Pricing and billing options stay hidden.": "Idéal pour les déploiements mono-utilisateur. Les options de tarification et de facturation restent masquées.",
|
||||
@@ -677,6 +688,7 @@
|
||||
"Bind WeChat Account": "Lier le compte WeChat",
|
||||
"Binding Information": "Informations de liaison",
|
||||
"Binding successful!": "Liaison réussie !",
|
||||
"Binding Type": "Type de liaison",
|
||||
"Binding your {{provider}} account": "Liaison de votre compte {{provider}}",
|
||||
"Binding...": "Liaison en cours...",
|
||||
"Bindings": "Liages",
|
||||
@@ -782,6 +794,7 @@
|
||||
"Change language": "Changer de langue",
|
||||
"Change Password": "Changer le mot de passe",
|
||||
"Change To": "Changer en",
|
||||
"Changed / Total": "Modifiés / Total",
|
||||
"Changed Fields": "Champs modifiés",
|
||||
"Changes are written to the settings draft on save.": "Les modifications sont écrites dans le brouillon des paramètres lors de l’enregistrement.",
|
||||
"Changing...": "Modification en cours...",
|
||||
@@ -928,6 +941,7 @@
|
||||
"Click to view full error message": "Cliquez pour voir le message d'erreur complet",
|
||||
"Click to view full prompt": "Cliquez pour voir l'invite complète",
|
||||
"Click to view image": "Cliquer pour voir l’image",
|
||||
"Client": "Client",
|
||||
"Client header value": "Valeur d'en-tête client",
|
||||
"Client ID": "ID client",
|
||||
"Client model": "Modèle client",
|
||||
@@ -990,6 +1004,7 @@
|
||||
"Complete Order": "Compléter la commande",
|
||||
"Complete these steps to finish the initial installation.": "Suivez ces étapes pour terminer l'installation initiale.",
|
||||
"Completed": "Terminé",
|
||||
"Completed security verification": "Vérification de sécurité terminée",
|
||||
"Completed top-up order for the user": "Commande de recharge complétée pour l'utilisateur",
|
||||
"Completion": "Achèvement",
|
||||
"Completion price": "Prix de complétion",
|
||||
@@ -1132,6 +1147,7 @@
|
||||
"Copied: {{model}}": "Copié : {{model}}",
|
||||
"Copied!": "Copié !",
|
||||
"Copy": "Copier",
|
||||
"Copy {{field}}": "Copier {{field}}",
|
||||
"Copy {{name}} pricing": "Copier la tarification de {{name}}",
|
||||
"Copy a request header": "Copier un en-tête de requête",
|
||||
"Copy All": "Tout copier",
|
||||
@@ -1264,6 +1280,7 @@
|
||||
"Current Password": "Mot de passe actuel",
|
||||
"Current Price": "Prix actuel",
|
||||
"Current quota": "Quota actuel",
|
||||
"Current token": "Jeton actuel",
|
||||
"Current Value": "Valeur actuelle",
|
||||
"Current version": "Version actuelle",
|
||||
"Current:": "Actuel :",
|
||||
@@ -1419,6 +1436,7 @@
|
||||
"Deployment Region *": "Région de déploiement *",
|
||||
"Deployment requested": "Déploiement demandé",
|
||||
"Deployments": "Déploiements",
|
||||
"Deprecated": "Obsolète",
|
||||
"Desc": "Desc.",
|
||||
"Describe": "Décrire",
|
||||
"Describe this model...": "Décrire ce modèle...",
|
||||
@@ -1465,6 +1483,7 @@
|
||||
"Disabled lanes are omitted on save.": "Les voies désactivées sont omises à l’enregistrement.",
|
||||
"Disabled Reason": "Raison de la désactivation",
|
||||
"Disabled Time": "Heure de désactivation",
|
||||
"Disabled two-factor authentication": "Authentification à deux facteurs désactivée",
|
||||
"Disabled; fell back to factory": "Désactivé ; retour à la version intégrée",
|
||||
"Disabled; platform unavailable": "Désactivé ; plateforme indisponible",
|
||||
"Disabling...": "Désactivation en cours...",
|
||||
@@ -1688,6 +1707,8 @@
|
||||
"Enable test mode for Creem payments": "Activer le mode test pour les paiements Creem",
|
||||
"Enable this key?": "Activer cette clé ?",
|
||||
"Enable Turnstile": "Activer Turnstile",
|
||||
"Enable Two-factor Authentication or Passkey in Security & Access to continue.": "Activez la double authentification ou une clé d’accès dans « Sécurité et accès » pour continuer.",
|
||||
"Enable Two-factor Authentication or Passkey in Security & Access to unlock sensitive operations.": "Activez la double authentification ou une clé d’accès dans « Sécurité et accès » pour autoriser les opérations sensibles.",
|
||||
"Enable Two-factor Authentication or Passkey in your profile to unlock sensitive operations.": "Activez l'authentification à deux facteurs ou Passkey dans votre profil pour déverrouiller les opérations sensibles.",
|
||||
"Enable unlimited quota for this API key": "Activer le quota illimité pour cette clé API",
|
||||
"Enable violation deduction": "Activer la déduction pour violation",
|
||||
@@ -1699,6 +1720,7 @@
|
||||
"Enabled all channels with tag: {{tag}}": "Tous les canaux avec le tag {{tag}} ont été activés",
|
||||
"Enabled channels with tag {{tag}}": "Canaux avec l'étiquette {{tag}} activés",
|
||||
"Enabled Status": "Statut activé",
|
||||
"Enabled two-factor authentication": "Authentification à deux facteurs activée",
|
||||
"Enabling...": "Activation en cours...",
|
||||
"Encourages introducing new topics": "Encourage l'introduction de nouveaux sujets",
|
||||
"Encourages new topics": "Encourage de nouveaux sujets",
|
||||
@@ -1706,6 +1728,7 @@
|
||||
"End Error": "Erreur finale",
|
||||
"End Reason": "Raison de fin",
|
||||
"End Time": "Heure de fin",
|
||||
"End time must be after start time": "La fin doit être postérieure au début",
|
||||
"End-user identifier for abuse monitoring": "Identifiant d'utilisateur final pour la surveillance des abus",
|
||||
"Endpoint": "Point d'accès",
|
||||
"Endpoint config": "Configuration de l'endpoint",
|
||||
@@ -1818,6 +1841,7 @@
|
||||
"Estimated cost": "Coût estimé",
|
||||
"Estimated quota cost": "Coût de quota estimé",
|
||||
"Evaluate fields from the provider user info response. Conditions and nested groups use and/or logic.": "Évalue les champs de la réponse d'informations utilisateur du fournisseur. Les conditions et groupes imbriqués utilisent la logique and/or.",
|
||||
"Event": "Événement",
|
||||
"Every group name in the pricing table can be used in two places: on a user (the user group, assigned by admins) and on a token (the token group, chosen when creating the token). Same name pool, two different jobs.": "Chaque nom de groupe du tableau tarifaire peut être utilisé à deux endroits : sur un utilisateur (groupe d’utilisateurs, attribué par les admins) et sur un jeton (groupe de jetons, choisi à la création du jeton). Même ensemble de noms, deux rôles différents.",
|
||||
"Every other device will lose access immediately. This device will remain signed in.": "Tous les autres appareils perdront immédiatement l’accès. Cet appareil restera connecté.",
|
||||
"Everything configured for this group, in one place.": "Toute la configuration de ce groupe, au même endroit.",
|
||||
@@ -1950,6 +1974,7 @@
|
||||
"Failed to load": "Échec du chargement",
|
||||
"Failed to load API keys": "Échec du chargement des Clés API",
|
||||
"Failed to load artifacts": "Échec du chargement des artefacts",
|
||||
"Failed to load audit records": "Échec du chargement des audits",
|
||||
"Failed to load billing history": "Échec du chargement de l'historique de facturation",
|
||||
"Failed to load enabled models": "Échec du chargement des modèles activés",
|
||||
"Failed to load home page content": "Échec du chargement du contenu de la page d'accueil",
|
||||
@@ -1965,6 +1990,7 @@
|
||||
"Failed to load setup data": "Échec du chargement des données de configuration",
|
||||
"Failed to load setup status": "Échec du chargement de l'état de configuration",
|
||||
"Failed to load tag data": "Échec du chargement des données de tags",
|
||||
"Failed to load token status": "Échec du chargement de l’état du jeton",
|
||||
"Failed to load users": "Échec du chargement des utilisateurs",
|
||||
"Failed to parse group items": "Échec de l'analyse des éléments de groupe",
|
||||
"Failed to parse JSON file: {{name}}": "Échec de l'analyse du fichier JSON : {{name}}",
|
||||
@@ -1979,6 +2005,7 @@
|
||||
"Failed to reset model ratios": "Échec de la réinitialisation des ratios du modèle",
|
||||
"Failed to reset Passkey": "Échec de la réinitialisation de la Passkey",
|
||||
"Failed to reset usage": "Échec de la réinitialisation de l’utilisation",
|
||||
"Failed to revoke token": "Échec de la révocation du jeton",
|
||||
"Failed to save": "Échec de la sauvegarde",
|
||||
"Failed to save announcements": "Échec de la sauvegarde des annonces",
|
||||
"Failed to save API info": "Échec de l'enregistrement des informations API",
|
||||
@@ -2054,6 +2081,7 @@
|
||||
"Fetching upstream ratios...": "Récupération des ratios amont...",
|
||||
"Fetching...": "Récupération…",
|
||||
"field": "champ",
|
||||
"Field change details were not recorded": "Le détail des champs modifiés n’a pas été enregistré",
|
||||
"Field Mapping": "Mappage de champs",
|
||||
"Field passthrough controls": "Contrôles de transmission des champs",
|
||||
"Field Path": "Chemin du champ",
|
||||
@@ -2202,12 +2230,15 @@
|
||||
"Gemini will continue to auto-detect thinking mode even with the adapter disabled. Enable this only when you need finer control over pricing and budgeting.": "Gemini continuera à détecter automatiquement le mode de pensée même avec l'adaptateur désactivé. Activez ceci uniquement lorsque vous avez besoin d'un contrôle plus fin sur la tarification et le budget.",
|
||||
"General": "Général",
|
||||
"General Settings": "Paramètres généraux",
|
||||
"Generate": "Générer",
|
||||
"Generate and manage your API access token": "Générer et gérer votre jeton d'accès API",
|
||||
"Generate Lyrics": "Générer des paroles",
|
||||
"Generate Music": "Générer de la musique",
|
||||
"Generate new backup codes for account recovery": "Générer de nouveaux codes de secours pour la récupération du compte",
|
||||
"Generate New Codes": "Générer de nouveaux codes",
|
||||
"Generate tokens from the Tokens page; you can scope them to specific models, groups, IPs, and rate-limits.": "Générez des jetons depuis la page Jetons ; vous pouvez les restreindre par modèle, groupe, IP et limites de débit.",
|
||||
"Generated": "Généré",
|
||||
"Generated a system access token": "Jeton d’accès système généré",
|
||||
"Generated image": "Image générée",
|
||||
"Generating new codes will invalidate all existing backup codes.": "La génération de nouveaux codes invalidera tous les codes de sauvegarde existants.",
|
||||
"Generating...": "Génération...",
|
||||
@@ -2322,6 +2353,7 @@
|
||||
"High-risk status code retry risk check 4": "J'accepte volontairement les risques pour la stabilité du système, notamment les délais d'attente sévères côté client et les pannes possibles du service, et j'assume toute accumulation de requêtes ou indisponibilité qui en résulterait.",
|
||||
"High-risk status code retry risk disclaimer": "### ⚠️ Opération à haut risque : avertissement et clause de non-responsabilité pour la relance des codes 504/524\n\nPar défaut, ce projet ne relance pas les codes `400` (requête incorrecte), `504` (délai d'attente de la passerelle) et `524` (délai d'attente dépassé). Les codes 504 et 524 signifient généralement que **la requête est bien parvenue au service IA en amont et que le traitement avait commencé, mais que la connexion s'est fermée parce que le traitement en amont a pris trop de temps**. Cela indique généralement un goulot d'étranglement du service en amont.\n\nActiver la redirection ou la relance pour ces codes de délai d'attente est une **opération à risque extrêmement élevé**. Avant de l'activer, vous devez lire attentivement et comprendre les conséquences suivantes :\n\n#### 1. Risques principaux (à lire attentivement)\n\n1. 💸 Facturation double ou multiple : la plupart des fournisseurs d'IA en amont **facturent quand même** les requêtes dont le traitement a commencé mais qui ont été interrompues par un délai réseau (504/524). Une relance envoie une toute nouvelle requête en amont et peut entraîner une **facturation double ou multiple**.\n2. ⏳ Délai d'attente sévère côté client : lorsqu'une requête a déjà expiré, les relances peuvent multiplier la latence totale et provoquer des délais sévères ou inacceptables pour le client final.\n3. 💥 Accumulation de requêtes et panne du service : les relances forcées occupent plus longtemps les threads et les connexions. En cas de forte concurrence, cela peut provoquer une importante **accumulation de requêtes**, épuiser les ressources, déclencher des défaillances en cascade et faire tomber le proxy.\n\n#### 2. Acceptation des risques\n\nSi vous choisissez malgré tout d'activer cette fonction, vous reconnaissez les éléments suivants :",
|
||||
"Higher priority channels are selected first": "Les canaux de priorité plus élevée sont sélectionnés en premier",
|
||||
"Historical tokens": "Anciens jetons",
|
||||
"Historical Usage": "Utilisation historique",
|
||||
"History of MjProxy-style image tasks.": "Historique des tâches d'images style MjProxy.",
|
||||
"Hit criteria: If cached tokens exist in usage, it counts as a hit.": "Critère de hit : si des tokens en cache existent dans l'utilisation, cela compte comme un hit.",
|
||||
@@ -2577,7 +2609,9 @@
|
||||
"Last Seen": "Dernier signal",
|
||||
"Last Tested": "Dernier testé",
|
||||
"Last updated:": "Dernière mise à jour :",
|
||||
"Last used": "Dernière utilisation",
|
||||
"Last Used": "Dernière utilisation",
|
||||
"Last used IP": "Dernière adresse IP",
|
||||
"Last used:": "Dernière utilisation :",
|
||||
"Latency": "Latence",
|
||||
"Latency check": "Contrôle de latence",
|
||||
@@ -2679,11 +2713,13 @@
|
||||
"Logged in successfully via {{method}}": "Connexion réussie via {{method}}",
|
||||
"Logic": "Logique",
|
||||
"Login": "Connexion",
|
||||
"Login & Authentication": "Connexion et authentification",
|
||||
"Login failed": "Échec de la connexion",
|
||||
"Login flow expired. Please sign in again.": "Le processus de connexion a expiré. Veuillez vous reconnecter.",
|
||||
"Login Info": "Informations de connexion",
|
||||
"Login Method": "Méthode de connexion",
|
||||
"Login sessions": "Sessions de connexion",
|
||||
"Login, security and access records": "Historique des connexions, de la sécurité et des accès",
|
||||
"Logo": "Logo",
|
||||
"Logo URL": "URL du logo",
|
||||
"Logs": "Journaux",
|
||||
@@ -2779,6 +2815,7 @@
|
||||
"Merge into Other": "Fusionner dans Autres",
|
||||
"Message Priority": "Priorité du message",
|
||||
"Metadata": "Métadonnées",
|
||||
"Method": "Méthode",
|
||||
"min downtime": "min d'interruption",
|
||||
"Min Top-up": "Recharge min.",
|
||||
"Min Top-up:": "Recharge min. :",
|
||||
@@ -2993,6 +3030,7 @@
|
||||
"New Password": "Nouveau mot de passe",
|
||||
"New password must be different from current password": "Le nouveau mot de passe doit être différent de l'actuel",
|
||||
"New User Quota": "Quota nouvel utilisateur",
|
||||
"New value": "Nouvelle valeur",
|
||||
"New version available: {{version}}": "Nouvelle version disponible : {{version}}",
|
||||
"NewAPI": "NewAPI",
|
||||
"Newly released": "Récemment publiés",
|
||||
@@ -3133,6 +3171,7 @@
|
||||
"No Quota": "Aucun quota",
|
||||
"No ratio differences found": "Aucune différence de ratio trouvée",
|
||||
"No recent usage": "Aucune utilisation récente",
|
||||
"No records": "Aucun enregistrement",
|
||||
"No records found. Try adjusting your filters.": "Aucun enregistrement trouvé. Essayez d'ajuster vos filtres.",
|
||||
"No redemption codes available. Create your first redemption code to get started.": "Aucun code d'échange disponible. Créez votre premier code d'échange pour commencer.",
|
||||
"No Redemption Codes Found": "Aucun code d'échange trouvé",
|
||||
@@ -3192,6 +3231,7 @@
|
||||
"Not configured": "Non configuré",
|
||||
"Not declared": "Non déclaré",
|
||||
"Not Equals": "Différent de",
|
||||
"Not generated": "Non généré",
|
||||
"Not in pricing table": "Absent du tableau tarifaire",
|
||||
"Not included": "Non inclus",
|
||||
"Not installed": "Non installé",
|
||||
@@ -3285,6 +3325,7 @@
|
||||
"Only successful requests": "Uniquement les requêtes réussies",
|
||||
"Only successful requests count toward this limit.": "Seules les requêtes réussies comptent pour cette limite.",
|
||||
"Only the last {{value}} log files will be retained; the rest will be deleted.": "Seuls les {{value}} derniers fichiers journaux seront conservés ; le reste sera supprimé.",
|
||||
"Only used to find historical logs. New records are available in Audit Logs.": "Uniquement pour consulter les anciens journaux. Les nouveaux événements figurent dans les journaux d’audit.",
|
||||
"Oops! Page Not Found!": "Oups ! Page introuvable !",
|
||||
"Oops! Something went wrong": "Oups ! Quelque chose s'est mal passé",
|
||||
"Open": "Ouvrir",
|
||||
@@ -3325,11 +3366,13 @@
|
||||
"Operate channels": "Exploiter les canaux",
|
||||
"Operation": "Opération",
|
||||
"operation and charging behavior": "à l’exploitation et à la facturation",
|
||||
"Operation audit": "Audit des opérations",
|
||||
"Operation Audit Info": "Informations d'audit d'opération",
|
||||
"Operation failed": "Opération échouée",
|
||||
"Operation successful": "Opération réussie",
|
||||
"Operation Type": "Type d'opération",
|
||||
"Operations": "Opérations",
|
||||
"Operator": "Auteur de l’opération",
|
||||
"Operator Admin": "Admin opérateur",
|
||||
"Optimize system for self-hosted single-user usage": "Optimiser le système pour une utilisation auto-hébergée par un seul utilisateur",
|
||||
"Optimized network architecture ensures millisecond response times": "Architecture réseau optimisée garantissant des temps de réponse en millisecondes",
|
||||
@@ -3545,6 +3588,7 @@
|
||||
"Pick or create both a store and a product before saving.": "Choisissez ou créez à la fois une boutique et un produit avant d’enregistrer.",
|
||||
"Ping Interval (seconds)": "Intervalle de ping (secondes)",
|
||||
"Plan": "Plan",
|
||||
"Plan ID": "ID du forfait",
|
||||
"Plan Name": "Nom du plan",
|
||||
"Plan Price": "Prix du forfait",
|
||||
"Plan price must be greater than zero": "Le prix du forfait doit être supérieur à zéro",
|
||||
@@ -3684,6 +3728,7 @@
|
||||
"Previous": "Précédent",
|
||||
"Previous branch": "Branche précédente",
|
||||
"Previous page": "Page précédente",
|
||||
"Previous value": "Valeur précédente",
|
||||
"Price": "Prix",
|
||||
"Price ($/1K calls)": "Prix ($/1K appels)",
|
||||
"Price (local currency / USD)": "Prix (devise locale / USD)",
|
||||
@@ -3719,6 +3764,7 @@
|
||||
"Priority level from 0 (lowest) to 10 (highest), default is 5": "Niveau de priorité de 0 (le plus bas) à 10 (le plus élevé), la valeur par défaut est 5",
|
||||
"Priority order for automatic group assignment. New tokens rotate through this list.": "Ordre de priorité pour l'attribution automatique des groupes. Les nouveaux jetons alternent dans cette liste.",
|
||||
"Priority order for tokens in the auto group. The system tries groups from top to bottom.": "Ordre de priorité pour les jetons du groupe auto. Le système essaie les groupes de haut en bas.",
|
||||
"Privacy": "Confidentialité",
|
||||
"Privacy Policy": "Politique de confidentialité",
|
||||
"Private Deployment URL": "URL de déploiement privé",
|
||||
"Processing OAuth response...": "Traitement de la réponse OAuth...",
|
||||
@@ -3910,6 +3956,7 @@
|
||||
"Regenerate access token?": "Régénérer le jeton d'accès ?",
|
||||
"Regenerate Backup Codes": "Régénérer les codes de secours",
|
||||
"Regenerate token": "Régénérer le jeton",
|
||||
"Regenerated two-factor backup codes": "Codes de secours à deux facteurs régénérés",
|
||||
"Regenerating immediately invalidates any existing token.": "La régénération invalide immédiatement tout jeton existant.",
|
||||
"Regex": "Regex",
|
||||
"Regex Pattern": "Expression régulière",
|
||||
@@ -4043,6 +4090,7 @@
|
||||
"Reset balance and used quota": "Réinitialiser le solde et le quota utilisé",
|
||||
"Reset completed": "Réinitialisation terminée",
|
||||
"Reset completed. Latest usage has been refreshed.": "Réinitialisation terminée. La dernière utilisation a été actualisée.",
|
||||
"Reset Count": "Nombre de réinitialisations",
|
||||
"Reset count:": "Nombre de réinitialisations :",
|
||||
"Reset Credit": "Crédit de réinitialisation",
|
||||
"Reset Credits": "Crédits de réinitialisation",
|
||||
@@ -4105,7 +4153,9 @@
|
||||
"Review your payment details": "Vérifier vos détails de paiement",
|
||||
"Review your purchase details before proceeding.": "Vérifiez les détails de votre achat avant de continuer.",
|
||||
"Revoke": "Révoquer",
|
||||
"Revoke access token?": "Révoquer le jeton d’accès ?",
|
||||
"Revoke session?": "Révoquer cette session ?",
|
||||
"Revoked the system access token": "Jeton d’accès système révoqué",
|
||||
"Rewards will be added directly to your balance": "Les récompenses seront ajoutées directement à votre solde",
|
||||
"Rewrite callback URLs to the local server": "Réécrire les URLs de callback vers le serveur local",
|
||||
"Right to Left": "De droite à gauche",
|
||||
@@ -4255,6 +4305,7 @@
|
||||
"Secure & Reliable": "Sécurisé et fiable",
|
||||
"Secured": "Sécurisé",
|
||||
"Security": "Sécurité",
|
||||
"Security & Access": "Sécurité et accès",
|
||||
"Security & Limits": "Sécurité et limites",
|
||||
"Security Check": "Vérification de sécurité",
|
||||
"Security verification": "Vérification de sécurité",
|
||||
@@ -4372,6 +4423,7 @@
|
||||
"Session expired!": "Session expirée !",
|
||||
"Session expired?": "Session expirée ?",
|
||||
"Session signed out": "Session déconnectée",
|
||||
"Sessions & Access": "Sessions et accès",
|
||||
"Set": "Définir",
|
||||
"Set a discount rate for a specific recharge amount threshold.": "Définir un taux de réduction pour un seuil de montant de recharge spécifique.",
|
||||
"Set a secure password (min. 8 characters)": "Définir un mot de passe sécurisé (min. 8 caractères)",
|
||||
@@ -4486,6 +4538,7 @@
|
||||
"Source Endpoint": "Point source",
|
||||
"Source Field": "Champ source",
|
||||
"Source Header": "En-tête source",
|
||||
"Source ID": "ID source",
|
||||
"Source name": "Nom de la source",
|
||||
"sources": "sources",
|
||||
"Space-separated OAuth scopes": "Scopes OAuth séparés par des espaces",
|
||||
@@ -4515,7 +4568,9 @@
|
||||
"Start for free with generous limits. No credit card required.": "Commencez gratuitement avec des limites généreuses. Aucune carte de crédit requise.",
|
||||
"Start Time": "Heure de début",
|
||||
"Started": "Démarré",
|
||||
"Started two-factor authentication setup": "Configuration de l’authentification à deux facteurs commencée",
|
||||
"STARTTLS": "STARTTLS",
|
||||
"State changed": "État modifié",
|
||||
"Static page describing the platform.": "Page statique décrivant la plateforme.",
|
||||
"Statistical count": "Nombre statistique",
|
||||
"Statistical quota": "Quota statistique",
|
||||
@@ -4664,6 +4719,7 @@
|
||||
"Tags": "Balises",
|
||||
"Take photo": "Prendre une photo",
|
||||
"Take screenshot": "Prendre une capture d'écran",
|
||||
"Target": "Cible",
|
||||
"Target Endpoint": "Point cible",
|
||||
"Target Field": "Champ cible",
|
||||
"Target Field Path": "Chemin du champ cible",
|
||||
@@ -4788,6 +4844,7 @@
|
||||
"Third-party": "Tiers",
|
||||
"Third-party — use at your own risk": "Tiers — à vos risques et périls",
|
||||
"Third-party account bindings (read-only, managed by user in profile settings)": "Liaisons de comptes tiers (lecture seule, gérées par l'utilisateur dans les paramètres de profil)",
|
||||
"Third-party account bindings (read-only, managed by user in Security & Access)": "Comptes tiers liés (lecture seule, gérés par l’utilisateur dans « Sécurité et accès »)",
|
||||
"Third-party Payment Config": "Configuration de paiement tiers",
|
||||
"Third-party plugin risk": "Risque des plugins tiers",
|
||||
"Third-party source risk": "Risque des sources tierces",
|
||||
@@ -4924,6 +4981,7 @@
|
||||
"Token estimator": "Estimation des jetons",
|
||||
"Token group": "Groupe de jetons",
|
||||
"Token has no group": "Jeton sans groupe",
|
||||
"Token identifier": "Identifiant du jeton",
|
||||
"Token Limits": "Limites de jetons",
|
||||
"Token management": "Gestion des jetons",
|
||||
"Token Management": "Gestion des tokens",
|
||||
@@ -4937,6 +4995,7 @@
|
||||
"Token price for image input.": "Prix par token pour l’entrée image.",
|
||||
"Token prices": "Prix des tokens",
|
||||
"Token regenerated and copied to clipboard": "Jeton régénéré et copié dans le presse-papiers",
|
||||
"Token scope": "Portée des jetons",
|
||||
"Token share by model author across the last 24 hours": "Part des tokens par auteur de modèle sur les dernières 24 heures",
|
||||
"Token share by model author across the past few weeks": "Part des tokens par auteur de modèle au cours des dernières semaines",
|
||||
"Token share by model author across the past month": "Part des tokens par auteur de modèle au cours du dernier mois",
|
||||
@@ -4986,6 +5045,7 @@
|
||||
"Top-up ratio": "Taux de recharge",
|
||||
"Topup Amount": "Montant de la recharge",
|
||||
"Total": "Total",
|
||||
"Total {{count}} records": "{{count}} enregistrements au total",
|
||||
"Total Allocated": "Total alloué",
|
||||
"Total check-ins": "Total des connexions",
|
||||
"Total consumed": "Consommé total",
|
||||
@@ -5133,6 +5193,7 @@
|
||||
"Updated a subscription plan": "Forfait d'abonnement mis à jour",
|
||||
"Updated a vendor": "Fournisseur mis à jour",
|
||||
"Updated channel {{name}} (ID: {{id}})": "Canal {{name}} mis à jour (ID : {{id}})",
|
||||
"Updated channel status (ID: {{id}})": "Statut du canal mis à jour (ID : {{id}})",
|
||||
"Updated daily": "Mis à jour quotidiennement",
|
||||
"Updated successfully": "Mise à jour réussie",
|
||||
"Updated system setting {{key}}": "Paramètre système {{key}} mis à jour",
|
||||
@@ -5260,6 +5321,7 @@
|
||||
"User Analytics": "Statistiques utilisateur",
|
||||
"User Consumption Ranking": "Classement de consommation",
|
||||
"User Consumption Trend": "Tendance de consommation",
|
||||
"User Count": "Nombre d’utilisateurs",
|
||||
"User created successfully": "Utilisateur créé avec succès",
|
||||
"User dashboard and quota controls.": "Tableau de bord utilisateur et contrôles de quotas.",
|
||||
"User deleted successfully": "Utilisateur supprimé avec succès",
|
||||
@@ -5354,6 +5416,7 @@
|
||||
"Vidu": "Vidu",
|
||||
"View": "Afficher",
|
||||
"View all currently available models": "Voir tous les modèles actuellement disponibles",
|
||||
"View audit records from user and admin roles. Root records are always excluded.": "Consulter les audits des rôles user et admin. Les événements du rôle root sont toujours exclus.",
|
||||
"View channel lists and details without secrets.": "Afficher les listes et détails des canaux sans secrets.",
|
||||
"View channel secrets": "Voir les secrets des canaux",
|
||||
"View detailed information about this user including balance, usage statistics, and invitation details.": "Afficher des informations détaillées sur cet utilisateur, y compris le solde, les statistiques d'utilisation et les détails d'invitation.",
|
||||
@@ -5363,7 +5426,9 @@
|
||||
"View logs": "Voir les logs",
|
||||
"View mode": "Mode d'affichage",
|
||||
"View model statistics and charts": "Afficher les statistiques et graphiques des modèles",
|
||||
"View other accounts' audit logs": "Voir les journaux d’audit des autres comptes",
|
||||
"View Pricing": "Voir les tarifs",
|
||||
"View scope": "Portée de la vue",
|
||||
"View the complete details for this": "Voir les détails complets de ce",
|
||||
"View the complete details for this log entry": "Voir les détails complets de cette entrée de journal",
|
||||
"View the complete details for this task": "Afficher tous les détails de cette tâche",
|
||||
|
||||
@@ -138,15 +138,19 @@
|
||||
"Access Forbidden": "アクセス禁止",
|
||||
"Access Policy (JSON)": "アクセスポリシー (JSON)",
|
||||
"Access previous conversations and start new ones.": "以前の会話にアクセスし、新しい会話を開始します。",
|
||||
"Access records": "アクセス履歴",
|
||||
"Access Token": "アクセストークン",
|
||||
"Access token revoked": "アクセストークンを取り消しました",
|
||||
"Access tokens are shown only once": "アクセストークンは一度だけ表示されます",
|
||||
"AccessKey / SecretAccessKey": "AccessKey/SecretAccessKey",
|
||||
"Account Actions": "アカウント操作",
|
||||
"Account Binding Management": "アカウント連携管理",
|
||||
"Account Bindings": "アカウントバインディング",
|
||||
"Account created! Please sign in": "アカウントが作成されました!ログインしてください",
|
||||
"Account deleted successfully": "アカウントが正常に削除されました",
|
||||
"Account ID *": "アカウントID *",
|
||||
"Account Info": "アカウント情報",
|
||||
"Account security": "アカウントのセキュリティ",
|
||||
"Account used when authenticating with the SMTP server": "SMTPサーバーで認証する際に使用されるアカウント",
|
||||
"acknowledge the related legal risks": "関連する法的リスクを認識します",
|
||||
"Across all groups": "全グループを通じて",
|
||||
@@ -315,11 +319,13 @@
|
||||
"All nodes": "すべてのノード",
|
||||
"All playground messages saved in this browser will be removed. This cannot be undone.": "このブラウザに保存されたすべての Playground メッセージが削除されます。この操作は元に戻せません。",
|
||||
"All requests must include": "すべてのリクエストには",
|
||||
"All results": "すべての結果",
|
||||
"All routes": "すべてのルート",
|
||||
"All Status": "すべてのステータス",
|
||||
"All Sync Status": "すべての同期状態",
|
||||
"All systems operational": "すべて正常稼働中",
|
||||
"All Tags": "すべてのタグ",
|
||||
"All tokens": "すべてのトークン",
|
||||
"All Types": "すべてのタイプ",
|
||||
"All upstream data is trusted": "すべてのアップストリームデータは信頼されています",
|
||||
"All users": "すべてのユーザー",
|
||||
@@ -510,6 +516,10 @@
|
||||
"Audio Preview": "音声プレビュー",
|
||||
"Audio ratio": "音声倍率",
|
||||
"Audio Tokens": "音声トークン",
|
||||
"Audit access changed. Showing only your records.": "監査ログへのアクセス権限が変更されました。自分の記録のみ表示しています。",
|
||||
"Audit Logs": "監査ログ",
|
||||
"Audit metadata is unavailable": "監査の追加情報を取得できません",
|
||||
"Audit records start after this feature was enabled. Earlier records remain in Common Logs.": "この機能の有効化以降の監査記録を表示します。それ以前の記録は通常ログに残ります。",
|
||||
"Auth": "認証",
|
||||
"Auth configured": "認証設定済み",
|
||||
"Auth name": "認証名",
|
||||
@@ -645,6 +655,7 @@
|
||||
"Batch test completed: {{success}} succeeded, {{failed}} failed": "バッチテストが完了しました: {{success}} 件成功、{{failed}} 件失敗",
|
||||
"Batch test stopped: {{completed}}/{{total}} completed, {{success}} succeeded, {{failed}} failed": "バッチテストを停止しました: {{completed}}/{{total}} 完了、{{success}} 件成功、{{failed}} 件失敗",
|
||||
"Batch testing models...": "モデルをバッチテスト中...",
|
||||
"Batch updated channel status ({{count}}/{{total}} changed)": "チャネルの状態を一括更新({{count}}/{{total}} 件変更)",
|
||||
"Batch upstream model update": "上流モデル一括更新",
|
||||
"Batch upstream model updates applied: {{channels}} channels, {{added}} added, {{removed}} removed, {{fails}} failed": "一括上流モデル更新を処理しました:{{channels}} チャネル、{{added}} 個追加、{{removed}} 個削除、{{fails}} 個失敗",
|
||||
"Best for single-tenant deployments. Pricing and billing options stay hidden.": "シングルテナント環境に最適です。料金設定や請求オプションは非表示になります。",
|
||||
@@ -677,6 +688,7 @@
|
||||
"Bind WeChat Account": "WeChatアカウント連携",
|
||||
"Binding Information": "連携情報",
|
||||
"Binding successful!": "紐付けが成功しました!",
|
||||
"Binding Type": "連携の種類",
|
||||
"Binding your {{provider}} account": "{{provider}} アカウントをバインド中",
|
||||
"Binding...": "連携中...",
|
||||
"Bindings": "バインド",
|
||||
@@ -782,6 +794,7 @@
|
||||
"Change language": "言語を変更",
|
||||
"Change Password": "パスワードの変更",
|
||||
"Change To": "変更先",
|
||||
"Changed / Total": "変更件数 / 合計",
|
||||
"Changed Fields": "変更されたフィールド",
|
||||
"Changes are written to the settings draft on save.": "保存すると変更は設定ドラフトに書き込まれます。",
|
||||
"Changing...": "変更中...",
|
||||
@@ -928,6 +941,7 @@
|
||||
"Click to view full error message": "クリックしてエラーメッセージ全文を表示",
|
||||
"Click to view full prompt": "クリックしてプロンプト全文を表示",
|
||||
"Click to view image": "クリックして画像を表示",
|
||||
"Client": "クライアント",
|
||||
"Client header value": "クライアントヘッダー値",
|
||||
"Client ID": "クライアントID",
|
||||
"Client model": "クライアント model",
|
||||
@@ -990,6 +1004,7 @@
|
||||
"Complete Order": "手動チャージ",
|
||||
"Complete these steps to finish the initial installation.": "初期インストールを完了するには、これらの手順を完了してください。",
|
||||
"Completed": "完了",
|
||||
"Completed security verification": "セキュリティ確認を完了しました",
|
||||
"Completed top-up order for the user": "ユーザーのチャージ注文を完了しました",
|
||||
"Completion": "補完",
|
||||
"Completion price": "補完価格",
|
||||
@@ -1132,6 +1147,7 @@
|
||||
"Copied: {{model}}": "コピーしました: {{model}}",
|
||||
"Copied!": "コピーしました!",
|
||||
"Copy": "コピー",
|
||||
"Copy {{field}}": "{{field}}をコピー",
|
||||
"Copy {{name}} pricing": "{{name}} の料金をコピー",
|
||||
"Copy a request header": "リクエストヘッダーをコピー",
|
||||
"Copy All": "すべてコピー",
|
||||
@@ -1264,6 +1280,7 @@
|
||||
"Current Password": "現在のパスワード",
|
||||
"Current Price": "現在の価格",
|
||||
"Current quota": "現在のクォータ",
|
||||
"Current token": "現在のトークン",
|
||||
"Current Value": "現在の値",
|
||||
"Current version": "現在のバージョン",
|
||||
"Current:": "現在:",
|
||||
@@ -1419,6 +1436,7 @@
|
||||
"Deployment Region *": "デプロイリージョン *",
|
||||
"Deployment requested": "デプロイメントが要求されました",
|
||||
"Deployments": "デプロイ",
|
||||
"Deprecated": "非推奨",
|
||||
"Desc": "降順",
|
||||
"Describe": "説明",
|
||||
"Describe this model...": "このモデルを説明...",
|
||||
@@ -1465,6 +1483,7 @@
|
||||
"Disabled lanes are omitted on save.": "無効な価格レーンは保存時に省略されます。",
|
||||
"Disabled Reason": "無効化の理由",
|
||||
"Disabled Time": "無効化された時刻",
|
||||
"Disabled two-factor authentication": "二要素認証を無効にしました",
|
||||
"Disabled; fell back to factory": "無効;組み込み版へフォールバック",
|
||||
"Disabled; platform unavailable": "無効;プラットフォーム利用不可",
|
||||
"Disabling...": "無効化中...",
|
||||
@@ -1688,6 +1707,8 @@
|
||||
"Enable test mode for Creem payments": "Creem 決済のテストモードを有効にする",
|
||||
"Enable this key?": "このキーを有効にしますか?",
|
||||
"Enable Turnstile": "Turnstileを有効にする",
|
||||
"Enable Two-factor Authentication or Passkey in Security & Access to continue.": "「セキュリティとアクセス」で二要素認証またはパスキーを有効にして続行してください。",
|
||||
"Enable Two-factor Authentication or Passkey in Security & Access to unlock sensitive operations.": "機密性の高い操作を行うには、「セキュリティとアクセス」で二要素認証またはパスキーを有効にしてください。",
|
||||
"Enable Two-factor Authentication or Passkey in your profile to unlock sensitive operations.": "機密性の高い操作を解除するには、プロフィールで二要素認証またはPasskeyを有効にしてください。",
|
||||
"Enable unlimited quota for this API key": "このAPIキーの無制限のクォータを有効にする",
|
||||
"Enable violation deduction": "違反料金控除を有効にする",
|
||||
@@ -1699,6 +1720,7 @@
|
||||
"Enabled all channels with tag: {{tag}}": "タグ「{{tag}}」の全チャネルを有効にしました",
|
||||
"Enabled channels with tag {{tag}}": "タグ {{tag}} のチャネルを有効化しました",
|
||||
"Enabled Status": "有効ステータス",
|
||||
"Enabled two-factor authentication": "二要素認証を有効にしました",
|
||||
"Enabling...": "有効化中...",
|
||||
"Encourages introducing new topics": "新しい話題への展開を促進します",
|
||||
"Encourages new topics": "新しい話題を促します",
|
||||
@@ -1706,6 +1728,7 @@
|
||||
"End Error": "終了エラー",
|
||||
"End Reason": "終了理由",
|
||||
"End Time": "終了時間",
|
||||
"End time must be after start time": "終了時刻は開始時刻より後にしてください",
|
||||
"End-user identifier for abuse monitoring": "悪用検知用のエンドユーザー識別子",
|
||||
"Endpoint": "エンドポイント",
|
||||
"Endpoint config": "エンドポイント設定",
|
||||
@@ -1818,6 +1841,7 @@
|
||||
"Estimated cost": "推定コスト",
|
||||
"Estimated quota cost": "想定クォートコスト",
|
||||
"Evaluate fields from the provider user info response. Conditions and nested groups use and/or logic.": "プロバイダーのユーザー情報レスポンスのフィールドを評価します。条件とネストしたグループでは and/or ロジックを使用します。",
|
||||
"Event": "イベント",
|
||||
"Every group name in the pricing table can be used in two places: on a user (the user group, assigned by admins) and on a token (the token group, chosen when creating the token). Same name pool, two different jobs.": "料金表の各グループ名は2つの場所で使えます。ユーザー側(ユーザーグループ、管理者が割り当て)とトークン側(トークングループ、トークン作成時に選択)です。同じ名前プールで、役割は2つです。",
|
||||
"Every other device will lose access immediately. This device will remain signed in.": "他のすべてのデバイスは直ちにアクセスできなくなります。このデバイスはログイン状態を維持します。",
|
||||
"Everything configured for this group, in one place.": "このグループのすべての設定を一か所で確認できます。",
|
||||
@@ -1950,6 +1974,7 @@
|
||||
"Failed to load": "読み込みに失敗しました",
|
||||
"Failed to load API keys": "APIキーの読み込みに失敗しました",
|
||||
"Failed to load artifacts": "成果物の読み込みに失敗しました",
|
||||
"Failed to load audit records": "監査記録の読み込みに失敗しました",
|
||||
"Failed to load billing history": "請求履歴の読み込みに失敗しました",
|
||||
"Failed to load enabled models": "有効なモデルの取得に失敗しました",
|
||||
"Failed to load home page content": "ホームページの内容の読み込みに失敗しました",
|
||||
@@ -1965,6 +1990,7 @@
|
||||
"Failed to load setup data": "セットアップデータの読み込みに失敗しました",
|
||||
"Failed to load setup status": "セットアップ状態の読み込みに失敗しました",
|
||||
"Failed to load tag data": "タグデータの読み込みに失敗しました",
|
||||
"Failed to load token status": "トークン状態の読み込みに失敗しました",
|
||||
"Failed to load users": "ユーザーの読み込みに失敗しました",
|
||||
"Failed to parse group items": "グループアイテムの解析に失敗しました",
|
||||
"Failed to parse JSON file: {{name}}": "JSONファイルの解析に失敗しました: __ PH_0 __",
|
||||
@@ -1979,6 +2005,7 @@
|
||||
"Failed to reset model ratios": "モデル比率のリセットに失敗しました",
|
||||
"Failed to reset Passkey": "パスキーのリセットに失敗しました",
|
||||
"Failed to reset usage": "使用量のリセットに失敗しました",
|
||||
"Failed to revoke token": "トークンの取り消しに失敗しました",
|
||||
"Failed to save": "保存に失敗",
|
||||
"Failed to save announcements": "お知らせの保存に失敗しました",
|
||||
"Failed to save API info": "API情報の保存に失敗しました",
|
||||
@@ -2054,6 +2081,7 @@
|
||||
"Fetching upstream ratios...": "アップストリーム比率をフェッチ中...",
|
||||
"Fetching...": "取得中…",
|
||||
"field": "フィールド",
|
||||
"Field change details were not recorded": "フィールドの変更詳細は記録されていません",
|
||||
"Field Mapping": "フィールドマッピング",
|
||||
"Field passthrough controls": "フィールドパススルーコントロール",
|
||||
"Field Path": "フィールドパス",
|
||||
@@ -2202,12 +2230,15 @@
|
||||
"Gemini will continue to auto-detect thinking mode even with the adapter disabled. Enable this only when you need finer control over pricing and budgeting.": "アダプターが無効になっていても、Geminiは思考モードを自動検出します。価格設定と予算編成をより細かく制御する必要がある場合にのみ、これを有効にしてください。",
|
||||
"General": "一般",
|
||||
"General Settings": "一般設定",
|
||||
"Generate": "生成",
|
||||
"Generate and manage your API access token": "API アクセス トークンを生成および管理",
|
||||
"Generate Lyrics": "歌詞を生成",
|
||||
"Generate Music": "音楽を生成",
|
||||
"Generate new backup codes for account recovery": "アカウント復旧用の新しいバックアップコードを生成",
|
||||
"Generate New Codes": "新しいコードを生成",
|
||||
"Generate tokens from the Tokens page; you can scope them to specific models, groups, IPs, and rate-limits.": "トークンページから API キーを発行できます。モデル、グループ、IP、レート制限ごとに細かく権限を設定可能です。",
|
||||
"Generated": "生成済み",
|
||||
"Generated a system access token": "システムアクセストークンを生成しました",
|
||||
"Generated image": "生成された画像",
|
||||
"Generating new codes will invalidate all existing backup codes.": "新しいコードを生成すると、既存のすべてのバックアップコードが無効になります。",
|
||||
"Generating...": "生成中...",
|
||||
@@ -2322,6 +2353,7 @@
|
||||
"High-risk status code retry risk check 4": "深刻なクライアントタイムアウトやサービス停止を含むシステム安定性のリスクを自発的に受け入れ、その結果生じるリクエスト滞留やサービス停止の責任を負います。",
|
||||
"High-risk status code retry risk disclaimer": "### ⚠️ 高リスク操作:504/524 ステータスコードのリトライに関するリスク通知と免責事項\n\n本プロジェクトは既定で、`400`(不正なリクエスト)、`504`(ゲートウェイタイムアウト)、`524`(タイムアウト発生)をリトライしません。504 と 524 は通常、**リクエストが上流 AI サービスに正常に到達して上流側で処理が始まっているものの、上流処理に時間がかかりすぎて接続が切断された**ことを意味します。多くの場合、これは上流サービス側のボトルネックです。\n\nこれらのタイムアウトコードでリダイレクトまたはリトライを有効にすることは、**極めて高リスクな操作**です。有効にする前に、次の重大な影響を必ず読み、理解してください。\n\n#### 1. 主なリスク(必ずお読みください)\n\n1. 💸 二重・多重課金:多くの上流 AI プロバイダーは、処理開始後にネットワークタイムアウト(504/524)で中断されたリクエストにも**通常どおり課金します**。リトライでは新しい上流リクエストが送信されるため、**二重または多重課金**になる可能性があります。\n2. ⏳ 深刻なクライアントタイムアウト:すでにタイムアウトしたリクエストにリトライを重ねると、総待ち時間が何倍にもなり、最終クライアントで深刻または許容できないタイムアウトが発生する可能性があります。\n3. 💥 リクエスト滞留とサービス停止:強制リトライはスレッドと接続を長時間占有します。高負荷時には深刻な**リクエスト滞留**、リソース枯渇、連鎖障害を招き、プロキシサービスが停止する可能性があります。\n\n#### 2. リスクの確認\n\nそれでもこの機能を有効にする場合は、以下のすべてを確認したものとみなされます。",
|
||||
"Higher priority channels are selected first": "優先度の高いチャネルが先に選択されます",
|
||||
"Historical tokens": "過去のトークン",
|
||||
"Historical Usage": "履歴使用状況",
|
||||
"History of MjProxy-style image tasks.": "MjProxyスタイルの画像タスクの履歴。",
|
||||
"Hit criteria: If cached tokens exist in usage, it counts as a hit.": "ヒット判定:usage に cached tokens が存在すればヒットとみなします。",
|
||||
@@ -2577,7 +2609,9 @@
|
||||
"Last Seen": "最終報告",
|
||||
"Last Tested": "最終テスト日時",
|
||||
"Last updated:": "最終更新日:",
|
||||
"Last used": "最終使用",
|
||||
"Last Used": "最終使用",
|
||||
"Last used IP": "最終使用 IP",
|
||||
"Last used:": "最終使用日:",
|
||||
"Latency": "レイテンシ",
|
||||
"Latency check": "レイテンシ確認",
|
||||
@@ -2679,11 +2713,13 @@
|
||||
"Logged in successfully via {{method}}": "{{method}} でログインに成功しました",
|
||||
"Logic": "ロジック",
|
||||
"Login": "ログイン",
|
||||
"Login & Authentication": "ログインと認証",
|
||||
"Login failed": "ログインに失敗しました",
|
||||
"Login flow expired. Please sign in again.": "ログイン手続きの有効期限が切れました。もう一度サインインしてください。",
|
||||
"Login Info": "ログイン情報",
|
||||
"Login Method": "ログイン方法",
|
||||
"Login sessions": "ログインセッション",
|
||||
"Login, security and access records": "ログイン、セキュリティ、アクセスの記録",
|
||||
"Logo": "ロゴ",
|
||||
"Logo URL": "ロゴURL",
|
||||
"Logs": "ログ",
|
||||
@@ -2779,6 +2815,7 @@
|
||||
"Merge into Other": "その他にまとめる",
|
||||
"Message Priority": "メッセージの優先度",
|
||||
"Metadata": "メタデータ",
|
||||
"Method": "メソッド",
|
||||
"min downtime": "分のダウンタイム",
|
||||
"Min Top-up": "最低チャージ額",
|
||||
"Min Top-up:": "最小チャージ額:",
|
||||
@@ -2993,6 +3030,7 @@
|
||||
"New Password": "新しいパスワード",
|
||||
"New password must be different from current password": "新しいパスワードは現在のものと異なっていなければなりません",
|
||||
"New User Quota": "新しいユーザー割り当て",
|
||||
"New value": "新しい値",
|
||||
"New version available: {{version}}": "新しいバージョンが利用可能です:{{version}}",
|
||||
"NewAPI": "NewAPI",
|
||||
"Newly released": "最新リリース",
|
||||
@@ -3133,6 +3171,7 @@
|
||||
"No Quota": "クォータなし",
|
||||
"No ratio differences found": "比率の差異は見つかりませんでした",
|
||||
"No recent usage": "最近の使用なし",
|
||||
"No records": "記録がありません",
|
||||
"No records found. Try adjusting your filters.": "記録が見つかりません。フィルターを調整してみてください。",
|
||||
"No redemption codes available. Create your first redemption code to get started.": "利用可能な引き換えコードがありません。最初の引き換えコードを作成して開始してください。",
|
||||
"No Redemption Codes Found": "引き換えコードが見つかりません",
|
||||
@@ -3192,6 +3231,7 @@
|
||||
"Not configured": "未設定",
|
||||
"Not declared": "未宣言",
|
||||
"Not Equals": "等しくない",
|
||||
"Not generated": "未生成",
|
||||
"Not in pricing table": "料金グループ表にありません",
|
||||
"Not included": "未登録",
|
||||
"Not installed": "未インストール",
|
||||
@@ -3285,6 +3325,7 @@
|
||||
"Only successful requests": "成功したリクエストのみ",
|
||||
"Only successful requests count toward this limit.": "成功したリクエストのみがこの制限にカウントされます。",
|
||||
"Only the last {{value}} log files will be retained; the rest will be deleted.": "最新の{{value}}個のログファイルのみ保持され、残りは削除されます。",
|
||||
"Only used to find historical logs. New records are available in Audit Logs.": "過去のログの検索専用です。新しい記録は監査ログで確認できます。",
|
||||
"Oops! Page Not Found!": "おっと!ページが見つかりません!",
|
||||
"Oops! Something went wrong": "おっと!何か問題が発生しました",
|
||||
"Open": "開く",
|
||||
@@ -3325,11 +3366,13 @@
|
||||
"Operate channels": "チャネルを運用",
|
||||
"Operation": "操作",
|
||||
"operation and charging behavior": "運用および課金行為に起因する法的責任を負うことを確認します",
|
||||
"Operation audit": "操作監査",
|
||||
"Operation Audit Info": "操作監査情報",
|
||||
"Operation failed": "操作に失敗しました",
|
||||
"Operation successful": "操作が成功しました",
|
||||
"Operation Type": "操作タイプ",
|
||||
"Operations": "運用",
|
||||
"Operator": "操作者",
|
||||
"Operator Admin": "オペレーター管理",
|
||||
"Optimize system for self-hosted single-user usage": "セルフホスト型の単一ユーザー使用向けにシステムを最適化する",
|
||||
"Optimized network architecture ensures millisecond response times": "最適化されたネットワークアーキテクチャによりミリ秒単位の応答時間を保証",
|
||||
@@ -3545,6 +3588,7 @@
|
||||
"Pick or create both a store and a product before saving.": "保存する前に、ストアと商品の両方を選択または作成してください。",
|
||||
"Ping Interval (seconds)": "Ping間隔(秒)",
|
||||
"Plan": "プラン",
|
||||
"Plan ID": "プラン ID",
|
||||
"Plan Name": "プラン名",
|
||||
"Plan Price": "プラン価格",
|
||||
"Plan price must be greater than zero": "プラン価格は 0 より大きい必要があります",
|
||||
@@ -3684,6 +3728,7 @@
|
||||
"Previous": "前へ",
|
||||
"Previous branch": "前のブランチ",
|
||||
"Previous page": "前のページ",
|
||||
"Previous value": "以前の値",
|
||||
"Price": "価格",
|
||||
"Price ($/1K calls)": "価格($/1K 回)",
|
||||
"Price (local currency / USD)": "価格 (現地通貨 / USD)",
|
||||
@@ -3719,6 +3764,7 @@
|
||||
"Priority level from 0 (lowest) to 10 (highest), default is 5": "優先度レベル (0が最低、10が最高、デフォルトは5)",
|
||||
"Priority order for automatic group assignment. New tokens rotate through this list.": "自動グループ割り当ての優先順位。新しいトークンはこのリストをローテーションします。",
|
||||
"Priority order for tokens in the auto group. The system tries groups from top to bottom.": "auto グループのトークンの優先順位。システムは上から順にグループを試します。",
|
||||
"Privacy": "プライバシー",
|
||||
"Privacy Policy": "プライバシーポリシー",
|
||||
"Private Deployment URL": "プライベートデプロイメントURL",
|
||||
"Processing OAuth response...": "OAuth応答を処理中...",
|
||||
@@ -3910,6 +3956,7 @@
|
||||
"Regenerate access token?": "アクセストークンを再生成しますか?",
|
||||
"Regenerate Backup Codes": "バックアップコードを再生成",
|
||||
"Regenerate token": "トークンを再生成",
|
||||
"Regenerated two-factor backup codes": "二要素認証のバックアップコードを再生成しました",
|
||||
"Regenerating immediately invalidates any existing token.": "再生成すると、既存のトークンは直ちに無効になります。",
|
||||
"Regex": "正規表現",
|
||||
"Regex Pattern": "正規表現パターン",
|
||||
@@ -4043,6 +4090,7 @@
|
||||
"Reset balance and used quota": "残高と使用済みクォータをリセット",
|
||||
"Reset completed": "リセット完了",
|
||||
"Reset completed. Latest usage has been refreshed.": "リセットが完了しました。最新の使用状況を更新しました。",
|
||||
"Reset Count": "リセット件数",
|
||||
"Reset count:": "リセット回数:",
|
||||
"Reset Credit": "リセット回数",
|
||||
"Reset Credits": "リセット回数",
|
||||
@@ -4105,7 +4153,9 @@
|
||||
"Review your payment details": "支払い詳細を確認",
|
||||
"Review your purchase details before proceeding.": "続行前に購入詳細を確認してください。",
|
||||
"Revoke": "取り消す",
|
||||
"Revoke access token?": "アクセストークンを取り消しますか?",
|
||||
"Revoke session?": "このセッションを取り消しますか?",
|
||||
"Revoked the system access token": "システムアクセストークンを取り消しました",
|
||||
"Rewards will be added directly to your balance": "報酬は直接残高に追加されます",
|
||||
"Rewrite callback URLs to the local server": "コールバック URL をローカルサーバーに書き換え",
|
||||
"Right to Left": "右から左",
|
||||
@@ -4255,6 +4305,7 @@
|
||||
"Secure & Reliable": "セキュア&信頼性",
|
||||
"Secured": "保護済み",
|
||||
"Security": "セキュリティ",
|
||||
"Security & Access": "セキュリティとアクセス",
|
||||
"Security & Limits": "セキュリティと制限",
|
||||
"Security Check": "セキュリティチェック",
|
||||
"Security verification": "セキュリティ確認",
|
||||
@@ -4372,6 +4423,7 @@
|
||||
"Session expired!": "セッションが期限切れです!",
|
||||
"Session expired?": "セッションが期限切れになりましたか?",
|
||||
"Session signed out": "セッションからサインアウトしました",
|
||||
"Sessions & Access": "セッションとアクセス",
|
||||
"Set": "設定",
|
||||
"Set a discount rate for a specific recharge amount threshold.": "特定のチャージ金額のしきい値に対して割引率を設定します。",
|
||||
"Set a secure password (min. 8 characters)": "安全なパスワードを設定してください (最低8文字)",
|
||||
@@ -4486,6 +4538,7 @@
|
||||
"Source Endpoint": "ソースエンドポイント",
|
||||
"Source Field": "コピー元フィールド",
|
||||
"Source Header": "コピー元ヘッダー",
|
||||
"Source ID": "コピー元 ID",
|
||||
"Source name": "ソース名",
|
||||
"sources": "ソース",
|
||||
"Space-separated OAuth scopes": "スペース区切りのOAuthスコープ",
|
||||
@@ -4515,7 +4568,9 @@
|
||||
"Start for free with generous limits. No credit card required.": "豊富な無料枠で始められます。クレジットカードは不要です。",
|
||||
"Start Time": "開始時間",
|
||||
"Started": "起動時刻",
|
||||
"Started two-factor authentication setup": "二要素認証の設定を開始しました",
|
||||
"STARTTLS": "STARTTLS",
|
||||
"State changed": "状態の変更",
|
||||
"Static page describing the platform.": "プラットフォームを説明する静的ページ。",
|
||||
"Statistical count": "統計数",
|
||||
"Statistical quota": "統計クォータ",
|
||||
@@ -4664,6 +4719,7 @@
|
||||
"Tags": "タグ",
|
||||
"Take photo": "写真を撮る",
|
||||
"Take screenshot": "スクリーンショットを撮る",
|
||||
"Target": "操作対象",
|
||||
"Target Endpoint": "ターゲットエンドポイント",
|
||||
"Target Field": "コピー先フィールド",
|
||||
"Target Field Path": "ターゲットフィールドパス",
|
||||
@@ -4788,6 +4844,7 @@
|
||||
"Third-party": "サードパーティ",
|
||||
"Third-party — use at your own risk": "サードパーティ — 自己責任",
|
||||
"Third-party account bindings (read-only, managed by user in profile settings)": "サードパーティアカウントのバインディング(読み取り専用、プロファイル設定でユーザーが管理)",
|
||||
"Third-party account bindings (read-only, managed by user in Security & Access)": "外部アカウント連携(読み取り専用、ユーザーが「セキュリティとアクセス」で管理)",
|
||||
"Third-party Payment Config": "サードパーティ決済設定",
|
||||
"Third-party plugin risk": "サードパーティプラグインのリスク",
|
||||
"Third-party source risk": "サードパーティソースのリスク",
|
||||
@@ -4924,6 +4981,7 @@
|
||||
"Token estimator": "トークン見積り",
|
||||
"Token group": "トークングループ",
|
||||
"Token has no group": "トークンにグループなし",
|
||||
"Token identifier": "トークン識別子",
|
||||
"Token Limits": "トークン制限",
|
||||
"Token management": "トークン管理",
|
||||
"Token Management": "トークン管理",
|
||||
@@ -4937,6 +4995,7 @@
|
||||
"Token price for image input.": "画像入力のトークン価格。",
|
||||
"Token prices": "トークン価格",
|
||||
"Token regenerated and copied to clipboard": "トークンが再生成され、クリップボードにコピーされました",
|
||||
"Token scope": "トークンの範囲",
|
||||
"Token share by model author across the last 24 hours": "過去 24 時間におけるモデル提供者別のトークンシェア",
|
||||
"Token share by model author across the past few weeks": "過去数週間におけるモデル提供者別のトークンシェア",
|
||||
"Token share by model author across the past month": "過去 1 か月におけるモデル提供者別のトークンシェア",
|
||||
@@ -4986,6 +5045,7 @@
|
||||
"Top-up ratio": "チャージ倍率",
|
||||
"Topup Amount": "チャージ額",
|
||||
"Total": "合計",
|
||||
"Total {{count}} records": "全 {{count}} 件",
|
||||
"Total Allocated": "総割り当て",
|
||||
"Total check-ins": "総チェックイン数",
|
||||
"Total consumed": "合計消費量",
|
||||
@@ -5133,6 +5193,7 @@
|
||||
"Updated a subscription plan": "サブスクリプションプランを更新しました",
|
||||
"Updated a vendor": "ベンダーを更新しました",
|
||||
"Updated channel {{name}} (ID: {{id}})": "チャネル {{name}} を更新しました(ID: {{id}})",
|
||||
"Updated channel status (ID: {{id}})": "チャネルの状態を更新(ID: {{id}})",
|
||||
"Updated daily": "毎日更新",
|
||||
"Updated successfully": "正常に更新されました",
|
||||
"Updated system setting {{key}}": "システム設定 {{key}} を更新しました",
|
||||
@@ -5260,6 +5321,7 @@
|
||||
"User Analytics": "ユーザー統計",
|
||||
"User Consumption Ranking": "ユーザー消費ランキング",
|
||||
"User Consumption Trend": "ユーザー消費トレンド",
|
||||
"User Count": "ユーザー数",
|
||||
"User created successfully": "ユーザーの作成に成功しました",
|
||||
"User dashboard and quota controls.": "ユーザーダッシュボードとクォータ制御。",
|
||||
"User deleted successfully": "ユーザーを削除しました",
|
||||
@@ -5354,6 +5416,7 @@
|
||||
"Vidu": "Vidu",
|
||||
"View": "表示",
|
||||
"View all currently available models": "現在利用可能なすべてのモデルを表示",
|
||||
"View audit records from user and admin roles. Root records are always excluded.": "user と admin ロールの監査記録を表示します。root ロールの記録は常に除外されます。",
|
||||
"View channel lists and details without secrets.": "シークレットを含まないチャネル一覧と詳細を表示します。",
|
||||
"View channel secrets": "チャンネルシークレットを表示",
|
||||
"View detailed information about this user including balance, usage statistics, and invitation details.": "残高、使用統計、招待の詳細など、このユーザーに関する詳細情報を表示します。",
|
||||
@@ -5363,7 +5426,9 @@
|
||||
"View logs": "ログを表示",
|
||||
"View mode": "表示モード",
|
||||
"View model statistics and charts": "モデルの統計とグラフを表示",
|
||||
"View other accounts' audit logs": "他のアカウントの監査ログを表示",
|
||||
"View Pricing": "価格を見る",
|
||||
"View scope": "表示範囲",
|
||||
"View the complete details for this": "この",
|
||||
"View the complete details for this log entry": "このログエントリの完全な詳細を表示",
|
||||
"View the complete details for this task": "このタスクの完全な詳細を表示します",
|
||||
|
||||
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user