mirror of
https://github.com/1Panel-dev/1Panel.git
synced 2026-10-30 08:05:43 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89eb284136 | ||
|
|
8885463a75 | ||
|
|
01feaa6059 | ||
|
|
ecb264f087 | ||
|
|
8bae2f6779 |
@@ -1394,19 +1394,10 @@ func (a AgentService) VerifyAccount(req dto.AgentAccountVerifyReq) error {
|
||||
func (a AgentService) DeleteAccount(req dto.AgentAccountDeleteReq) error {
|
||||
agentAccountMutationMu.Lock()
|
||||
defer agentAccountMutationMu.Unlock()
|
||||
account, err := agentAccountRepo.GetFirst(repo.WithByID(req.ID))
|
||||
_, err := agentAccountRepo.GetFirst(repo.WithByID(req.ID))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if account.AppInstallID != 0 && account.Provider != "ollama" {
|
||||
_, err := appInstallRepo.GetFirst(repo.WithByID(account.AppInstallID))
|
||||
if err == nil {
|
||||
return buserr.WithDetail("ErrInvalidParams", "Delete the local inference engine instead", nil)
|
||||
}
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := global.DB.Transaction(func(tx *gorm.DB) error {
|
||||
var agentCount int64
|
||||
|
||||
@@ -259,6 +259,15 @@ func (a *AppInstallService) Operate(req request.AppInstalledOperate) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if install.Status == constant.StatusRestarting && (req.Operate == constant.Stop || req.Operate == constant.Delete) && !req.ForceDelete {
|
||||
count, err := taskRepo.CountExecutingTask(repo.WithByType(task.TaskScopeApp), taskRepo.WithResourceID(install.ID), taskRepo.WithOperate(task.TaskRestart))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count > 0 {
|
||||
return buserr.New("TaskIsExecuting")
|
||||
}
|
||||
}
|
||||
if !req.ForceDelete && !files.NewFileOp().Stat(install.GetPath()) {
|
||||
return buserr.New("ErrInstallDirNotFound")
|
||||
}
|
||||
@@ -342,9 +351,6 @@ func operateAppWithLifecycleScripts(install model.AppInstall, req request.AppIns
|
||||
return errors.New("lifecycle script operation not supported")
|
||||
}
|
||||
install.Message = ""
|
||||
if err := appInstallRepo.Save(context.Background(), &install); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
operationTask, err := task.NewTaskWithOps(install.Name, taskType, task.TaskScopeApp, req.TaskID, install.ID)
|
||||
if err != nil {
|
||||
@@ -355,10 +361,17 @@ func operateAppWithLifecycleScripts(install model.AppInstall, req request.AppIns
|
||||
}
|
||||
return err
|
||||
}
|
||||
ready := make(chan error, 1)
|
||||
started := make(chan struct{})
|
||||
operation := string(req.Operate)
|
||||
operationTask.AddSubTaskWithOps(
|
||||
task.GetTaskName(install.Name, taskType, task.TaskScopeApp),
|
||||
func(t *task.Task) error {
|
||||
if err := appInstallRepo.Save(context.Background(), &install); err != nil {
|
||||
return err
|
||||
}
|
||||
close(started)
|
||||
ready <- nil
|
||||
if err := runScript(t, &install, operation); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -385,6 +398,12 @@ func operateAppWithLifecycleScripts(install model.AppInstall, req request.AppIns
|
||||
)
|
||||
go func() {
|
||||
if taskErr := operationTask.Execute(); taskErr != nil {
|
||||
select {
|
||||
case <-started:
|
||||
default:
|
||||
ready <- taskErr
|
||||
return
|
||||
}
|
||||
if onFailure != nil {
|
||||
onFailure(taskErr)
|
||||
return
|
||||
@@ -394,7 +413,7 @@ func operateAppWithLifecycleScripts(install model.AppInstall, req request.AppIns
|
||||
_ = appInstallRepo.Save(context.Background(), &install)
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
return <-ready
|
||||
}
|
||||
|
||||
func (a *AppInstallService) UpdateAppConfig(req request.AppConfigUpdate) error {
|
||||
@@ -1036,8 +1055,16 @@ func syncAppInstallStatus(appInstall *model.AppInstall, force bool) error {
|
||||
}
|
||||
switch appInstall.Status {
|
||||
case constant.StatusInstalling, constant.StatusRebuilding, constant.StatusUpgrading, constant.StatusUninstalling,
|
||||
constant.StatusStarting, constant.StatusRestarting, constant.StatusWaiting:
|
||||
constant.StatusStarting, constant.StatusWaiting:
|
||||
return nil
|
||||
case constant.StatusRestarting:
|
||||
count, err := taskRepo.CountExecutingTask(repo.WithByType(task.TaskScopeApp), taskRepo.WithResourceID(appInstall.ID), taskRepo.WithOperate(task.TaskRestart))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count > 0 {
|
||||
return nil
|
||||
}
|
||||
case constant.StatusInstallErr, constant.StatusUpgradeErr, constant.StatusUpErr:
|
||||
if !force {
|
||||
return nil
|
||||
|
||||
@@ -316,6 +316,8 @@ func (t *Task) ExecuteQueued(slots chan struct{}, waitingStep string, onFinish f
|
||||
|
||||
func (t *Task) Execute() error {
|
||||
if err := t.taskRepo.Save(context.Background(), t.Task); err != nil {
|
||||
_ = t.logFile.Close()
|
||||
global.RemoveTaskCancel(t.TaskID)
|
||||
return err
|
||||
}
|
||||
return t.executeRegistered()
|
||||
|
||||
+144
-2
@@ -15,7 +15,7 @@ import (
|
||||
)
|
||||
|
||||
func bindAPIKeyRequest(c *gin.Context, value interface{}) bool {
|
||||
if _, err := auth.RequireAPIKeySession(c); err != nil {
|
||||
if _, err := auth.RequireAPIKeyManagement(c); err != nil {
|
||||
helper.BadAuth(c, "ErrNotLogin", nil)
|
||||
return false
|
||||
}
|
||||
@@ -41,6 +41,24 @@ func apiKeyError(c *gin.Context, err error) {
|
||||
helper.InternalServer(c, err)
|
||||
}
|
||||
|
||||
// Swag's legacy || syntax combines schemes in one requirement (AND);
|
||||
// separate @Security lines represent alternative authentication methods.
|
||||
// @Tags API Key
|
||||
// @Summary List the current account's API keys
|
||||
// @Description Accepts a panel login session with CSRF protection, or a valid API Key signature. The authenticated account determines ownership; another account cannot be selected in the request.
|
||||
// @Description Returns key metadata and masked hints, never plaintext secrets. The legacy key is included when present; deleted keys are excluded.
|
||||
// @Description Authentication and business errors use HTTP 200 with envelope code 400, 401 or 500; check code rather than HTTP status alone.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body dto.APIKeySearch true "Pagination and revoked-key filter"
|
||||
// @Param 1Panel-Key-ID header string false "Optional ID of the authenticating independent key; omit for legacy keys"
|
||||
// @Param 1Panel-Signature-Version header string false "Signature algorithm; omission accepts either supported algorithm" Enums(v1,md5,hmac-sha256)
|
||||
// @Success 200 {object} dto.Response{data=dto.APIKeyPage} "code=200 on success; data is null on errors"
|
||||
// @Failure 403 {object} dto.Response "Invalid or missing CSRF token for a session request"
|
||||
// @Header 200 {string} Cache-Control "no-store"
|
||||
// @Security ApiKeyAuth || Timestamp
|
||||
// @Security PanelSession || CSRFToken
|
||||
// @Router /core/auth/api/keys/search [post]
|
||||
func (b *BaseApi) SearchAPIKeys(c *gin.Context) {
|
||||
var req dto.APIKeySearch
|
||||
if !bindAPIKeyRequest(c, &req) {
|
||||
@@ -55,6 +73,25 @@ func (b *BaseApi) SearchAPIKeys(c *gin.Context) {
|
||||
helper.SuccessWithData(c, result)
|
||||
}
|
||||
|
||||
// @Tags API Key
|
||||
// @Summary Create an API key for the current account
|
||||
// @Description Accepts a panel login session with CSRF protection, or a valid API Key signature. The new key belongs to the authenticated account.
|
||||
// @Description requestID is optional. Omitted or empty values are generated by the server. For idempotent retries, supply a UUID and reuse it with the same payload.
|
||||
// @Description A successful first request returns the plaintext secret. Repeating the same requestID and payload returns alreadyCreated=true and an empty apiKey; changing the payload for that requestID is rejected.
|
||||
// @Description Omitted expiresAt defaults to 90 days; explicit null means no expiration. Omitted apiKeyValidityTime defaults to 120 minutes; zero disables timestamp validation.
|
||||
// @Description API-created keys may have a longer lifetime or broader IP policy than the calling key. Revoking the calling key does not revoke keys it created.
|
||||
// @Description Authentication and business errors use HTTP 200 with envelope code 400, 401 or 500; check code rather than HTTP status alone. Unknown fields and bodies larger than 32 KiB are rejected.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body dto.APIKeyCreate true "Key policy and an optional UUID requestID for idempotency"
|
||||
// @Param 1Panel-Key-ID header string false "Optional ID of the authenticating independent key; omit for legacy keys"
|
||||
// @Param 1Panel-Signature-Version header string false "Signature algorithm; omission accepts either supported algorithm" Enums(v1,md5,hmac-sha256)
|
||||
// @Success 200 {object} dto.Response{data=dto.APIKeyCreated} "code=200 on success; data is null on errors"
|
||||
// @Failure 403 {object} dto.Response "Invalid or missing CSRF token for a session request"
|
||||
// @Header 200 {string} Cache-Control "no-store"
|
||||
// @Security ApiKeyAuth || Timestamp
|
||||
// @Security PanelSession || CSRFToken
|
||||
// @Router /core/auth/api/keys/create [post]
|
||||
func (b *BaseApi) CreateAPIKey(c *gin.Context) {
|
||||
req := dto.APIKeyCreate{APIKeyFields: dto.APIKeyFields{APIKeyValidityTime: 120}}
|
||||
if !bindAPIKeyRequest(c, &req) {
|
||||
@@ -69,6 +106,22 @@ func (b *BaseApi) CreateAPIKey(c *gin.Context) {
|
||||
helper.SuccessWithData(c, result)
|
||||
}
|
||||
|
||||
// @Tags API Key
|
||||
// @Summary Update an API key's policy
|
||||
// @Description Accepts a panel login session with CSRF protection, or a valid API Key signature. Only keys owned by the authenticated account can be changed.
|
||||
// @Description Submit the current revision returned by search; stale revisions are rejected. This replaces editable policy fields without changing the secret. expiresAt must be supplied as an RFC 3339 timestamp or null.
|
||||
// @Description Use id=legacy for the legacy key; its name is fixed and expiresAt must be null. Revoked or deleted independent keys cannot be updated.
|
||||
// @Description Success increments the revision; search again before another mutation. Authentication and business errors use HTTP 200 with envelope code 400, 401 or 500.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body dto.APIKeyUpdate true "Key ID, current revision and complete editable policy"
|
||||
// @Param 1Panel-Key-ID header string false "Optional ID of the authenticating independent key; omit for legacy keys"
|
||||
// @Param 1Panel-Signature-Version header string false "Signature algorithm; omission accepts either supported algorithm" Enums(v1,md5,hmac-sha256)
|
||||
// @Success 200 {object} dto.Response{data=dto.APIKeyMutationResult} "code=200 on success; data is null on errors"
|
||||
// @Failure 403 {object} dto.Response "Invalid or missing CSRF token for a session request"
|
||||
// @Security ApiKeyAuth || Timestamp
|
||||
// @Security PanelSession || CSRFToken
|
||||
// @Router /core/auth/api/keys/update [post]
|
||||
func (b *BaseApi) UpdateAPIKey(c *gin.Context) {
|
||||
var req dto.APIKeyUpdate
|
||||
if !bindAPIKeyRequest(c, &req) {
|
||||
@@ -81,6 +134,21 @@ func (b *BaseApi) UpdateAPIKey(c *gin.Context) {
|
||||
apiKeyMutationSuccess(c)
|
||||
}
|
||||
|
||||
// @Tags API Key
|
||||
// @Summary Enable or disable an API key
|
||||
// @Description Accepts a panel login session with CSRF protection, or a valid API Key signature. Only keys owned by the authenticated account can be changed; id=legacy is supported.
|
||||
// @Description Submit the current revision returned by search. Revoked or deleted keys cannot be enabled; expired keys must first receive a future expiration time. Disabling a key also closes its active terminal sessions.
|
||||
// @Description Success increments the revision; search again before another mutation. Authentication and business errors use HTTP 200 with envelope code 400, 401 or 500.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body dto.APIKeyStatus true "Key ID, current revision and Enable or Disable status"
|
||||
// @Param 1Panel-Key-ID header string false "Optional ID of the authenticating independent key; omit for legacy keys"
|
||||
// @Param 1Panel-Signature-Version header string false "Signature algorithm; omission accepts either supported algorithm" Enums(v1,md5,hmac-sha256)
|
||||
// @Success 200 {object} dto.Response{data=dto.APIKeyMutationResult} "code=200 on success; data is null on errors"
|
||||
// @Failure 403 {object} dto.Response "Invalid or missing CSRF token for a session request"
|
||||
// @Security ApiKeyAuth || Timestamp
|
||||
// @Security PanelSession || CSRFToken
|
||||
// @Router /core/auth/api/keys/status [post]
|
||||
func (b *BaseApi) SetAPIKeyStatus(c *gin.Context) {
|
||||
var req dto.APIKeyStatus
|
||||
if !bindAPIKeyRequest(c, &req) {
|
||||
@@ -93,6 +161,22 @@ func (b *BaseApi) SetAPIKeyStatus(c *gin.Context) {
|
||||
apiKeyMutationSuccess(c)
|
||||
}
|
||||
|
||||
// @Tags API Key
|
||||
// @Summary Revoke an API key
|
||||
// @Description Accepts a panel login session with CSRF protection, or a valid API Key signature. Only keys owned by the authenticated account can be revoked.
|
||||
// @Description Submit the current revision returned by search. Revocation destroys the independent key's stored secret and cannot be undone; its metadata remains listed. For id=legacy, the legacy secret is cleared and API access is disabled.
|
||||
// @Description A key can revoke itself; subsequent requests signed with it fail. Keys previously created by the revoked key remain independent. Success increments the revision and closes associated terminal sessions.
|
||||
// @Description Authentication and business errors use HTTP 200 with envelope code 400, 401 or 500.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body dto.APIKeyMutation true "Key ID and current revision"
|
||||
// @Param 1Panel-Key-ID header string false "Optional ID of the authenticating independent key; omit for legacy keys"
|
||||
// @Param 1Panel-Signature-Version header string false "Signature algorithm; omission accepts either supported algorithm" Enums(v1,md5,hmac-sha256)
|
||||
// @Success 200 {object} dto.Response{data=dto.APIKeyMutationResult} "code=200 on success; data is null on errors"
|
||||
// @Failure 403 {object} dto.Response "Invalid or missing CSRF token for a session request"
|
||||
// @Security ApiKeyAuth || Timestamp
|
||||
// @Security PanelSession || CSRFToken
|
||||
// @Router /core/auth/api/keys/revoke [post]
|
||||
func (b *BaseApi) RevokeAPIKey(c *gin.Context) {
|
||||
var req dto.APIKeyMutation
|
||||
if !bindAPIKeyRequest(c, &req) {
|
||||
@@ -106,5 +190,63 @@ func (b *BaseApi) RevokeAPIKey(c *gin.Context) {
|
||||
}
|
||||
|
||||
func apiKeyMutationSuccess(c *gin.Context) {
|
||||
helper.SuccessWithData(c, gin.H{"terminalClosePending": c.GetBool("API_KEY_TERMINAL_CLOSE_PENDING")})
|
||||
helper.SuccessWithData(c, dto.APIKeyMutationResult{TerminalClosePending: c.GetBool("API_KEY_TERMINAL_CLOSE_PENDING")})
|
||||
}
|
||||
|
||||
// @Tags API Key
|
||||
// @Summary Delete an independent API key
|
||||
// @Description Accepts a panel login session with CSRF protection, or a valid API Key signature. Only keys owned by the authenticated account can be deleted; id=legacy is not supported.
|
||||
// @Description Submit the current revision returned by search. Deletion immediately revokes the key, destroys its stored secret and removes it from lists. Audit and idempotency records are retained. Already-revoked keys can be deleted; deletion cannot be undone.
|
||||
// @Description A key can delete itself; subsequent requests signed with it fail. Authentication and business errors use HTTP 200 with envelope code 400, 401 or 500.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body dto.APIKeyMutation true "Independent key ID and current revision"
|
||||
// @Param 1Panel-Key-ID header string false "Optional ID of the authenticating independent key; omit for legacy keys"
|
||||
// @Param 1Panel-Signature-Version header string false "Signature algorithm; omission accepts either supported algorithm" Enums(v1,md5,hmac-sha256)
|
||||
// @Success 200 {object} dto.Response{data=dto.APIKeyMutationResult} "code=200 on success; data is null on errors"
|
||||
// @Failure 403 {object} dto.Response "Invalid or missing CSRF token for a session request"
|
||||
// @Security ApiKeyAuth || Timestamp
|
||||
// @Security PanelSession || CSRFToken
|
||||
// @Router /core/auth/api/keys/delete [post]
|
||||
func (b *BaseApi) DeleteAPIKey(c *gin.Context) {
|
||||
var req dto.APIKeyMutation
|
||||
if !bindAPIKeyRequest(c, &req) {
|
||||
return
|
||||
}
|
||||
if err := service.NewAPIKeyService().Delete(c, req); err != nil {
|
||||
apiKeyError(c, err)
|
||||
return
|
||||
}
|
||||
apiKeyMutationSuccess(c)
|
||||
}
|
||||
|
||||
// @Tags API Key
|
||||
// @Summary Reveal an independent API key's plaintext secret
|
||||
// @Description Requires a panel login session and CSRF token. API Key authentication is not supported, including requests that also contain a valid session cookie; omit all 1Panel authentication headers.
|
||||
// @Description Only the current account's independent keys can be revealed. Submit the current revision returned by search. Legacy, revoked and deleted keys are rejected; disabled or expired keys can still be revealed.
|
||||
// @Description Secret disclosure is audited. Authentication and business errors use HTTP 200 with envelope code 400, 401 or 500. The response must not be cached or logged.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body dto.APIKeyMutation true "Independent key ID and current revision"
|
||||
// @Success 200 {object} dto.Response{data=dto.APIKeyRevealed} "code=200 on success; data is null on errors"
|
||||
// @Failure 403 {object} dto.Response "Invalid or missing CSRF token"
|
||||
// @Header 200 {string} Cache-Control "no-store"
|
||||
// @Security PanelSession || CSRFToken
|
||||
// @Router /core/auth/api/keys/reveal [post]
|
||||
func (b *BaseApi) RevealAPIKey(c *gin.Context) {
|
||||
c.Header("Cache-Control", "no-store")
|
||||
if _, err := auth.RequireAPIKeySession(c); err != nil {
|
||||
helper.BadAuth(c, "ErrNotLogin", nil)
|
||||
return
|
||||
}
|
||||
var req dto.APIKeyMutation
|
||||
if !bindAPIKeyRequest(c, &req) {
|
||||
return
|
||||
}
|
||||
result, err := service.NewAPIKeyService().Reveal(c, req)
|
||||
if err != nil {
|
||||
apiKeyError(c, err)
|
||||
return
|
||||
}
|
||||
helper.SuccessWithData(c, result)
|
||||
}
|
||||
|
||||
+11
-8
@@ -417,11 +417,13 @@ func (b *BaseApi) MFAClose(c *gin.Context) {
|
||||
}
|
||||
|
||||
// @Tags Auth
|
||||
// @Summary generate api key
|
||||
// @Summary Generate or reset the legacy API key
|
||||
// @Description Requires a panel login session and CSRF token. API Key authentication is not supported. This replaces the current account's legacy secret; existing clients using the previous secret must be updated. Independent API keys are unaffected.
|
||||
// @Accept json
|
||||
// @Success 200 {string} key
|
||||
// @Security ApiKeyAuth
|
||||
// @Security Timestamp
|
||||
// @Produce json
|
||||
// @Success 200 {object} dto.Response{data=string} "code=200 with the new secret; authentication and business errors use envelope code 400, 401 or 500"
|
||||
// @Header 200 {string} Cache-Control "no-store"
|
||||
// @Security PanelSession || CSRFToken
|
||||
// @Router /core/auth/api/generate [post]
|
||||
// @x-panel-log {"bodyKeys":[],"paramKeys":[],"BeforeFunctions":[],"formatZH":"生成 API 接口密钥","formatEN":"generate api key"}
|
||||
func (b *BaseApi) GenerateApiKey(c *gin.Context) {
|
||||
@@ -440,12 +442,13 @@ func (b *BaseApi) GenerateApiKey(c *gin.Context) {
|
||||
}
|
||||
|
||||
// @Tags Auth
|
||||
// @Summary Update api config
|
||||
// @Summary Update the legacy API key configuration
|
||||
// @Description Requires a panel login session and CSRF token. API Key authentication is not supported. This updates only the current account's legacy API configuration.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body dto.ApiInterfaceConfig true "request"
|
||||
// @Success 200
|
||||
// @Security ApiKeyAuth
|
||||
// @Security Timestamp
|
||||
// @Success 200 {object} dto.Response "code=200 on success; authentication and business errors use envelope code 400, 401 or 500"
|
||||
// @Security PanelSession || CSRFToken
|
||||
// @Router /core/auth/api/update [post]
|
||||
// @x-panel-log {"bodyKeys":["ipWhiteList","apiTrustedProxies"],"paramKeys":[],"BeforeFunctions":[],"formatZH":"更新 API 接口配置 => IP 白名单: [ipWhiteList], API 可信代理: [apiTrustedProxies]","formatEN":"update api config => IP Allowlist: [ipWhiteList], API Trusted Proxies: [apiTrustedProxies]"}
|
||||
func (b *BaseApi) UpdateApiConfig(c *gin.Context) {
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -42,7 +43,7 @@ func APIAuthMiddleware(loadConfig APIAuthConfigLoader, onSuccess APIAuthSuccessH
|
||||
ownerProvider = ownerProviders[0]
|
||||
}
|
||||
return func(c *gin.Context) {
|
||||
if strings.HasPrefix(c.Request.URL.Path, "/api/v2/core/auth") {
|
||||
if strings.HasPrefix(c.Request.URL.Path, "/api/v2/core/auth") && !isAPIKeyManagementRequest(c) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
@@ -97,6 +98,20 @@ func APIAuthMiddleware(loadConfig APIAuthConfigLoader, onSuccess APIAuthSuccessH
|
||||
}
|
||||
}
|
||||
|
||||
func isAPIKeyManagementRequest(c *gin.Context) bool {
|
||||
if c.Request.Method != http.MethodPost {
|
||||
return false
|
||||
}
|
||||
switch c.Request.URL.Path {
|
||||
case "/api/v2/core/auth/api/keys/search", "/api/v2/core/auth/api/keys/create",
|
||||
"/api/v2/core/auth/api/keys/update", "/api/v2/core/auth/api/keys/status",
|
||||
"/api/v2/core/auth/api/keys/revoke", "/api/v2/core/auth/api/keys/delete":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func LoadAPIAuthConfig(_ *gin.Context) (APIAuthConfig, error) {
|
||||
settingRepo := repo.NewISettingRepo()
|
||||
config := APIAuthConfig{}
|
||||
|
||||
@@ -66,6 +66,26 @@ func RequireAPIKeySession(c *gin.Context) (psession.SessionUser, error) {
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func RequireAPIKeyManagement(c *gin.Context) (psession.SessionUser, error) {
|
||||
if c == nil || !c.GetBool("API_AUTH") {
|
||||
return RequireAPIKeySession(c)
|
||||
}
|
||||
if c.GetBool("LOCAL_REQUEST") {
|
||||
return psession.SessionUser{}, buserr.New("ErrNotLogin")
|
||||
}
|
||||
kind, keyID := c.GetString("API_AUTH_KEY_KIND"), c.GetString("API_AUTH_KEY_ID")
|
||||
if (kind != "apiKey" && kind != "legacy") || keyID == "" || (kind == "legacy") != (keyID == "legacy") {
|
||||
return psession.SessionUser{}, buserr.New("ErrNotLogin")
|
||||
}
|
||||
ownerType, ownerID := c.GetString("API_AUTH_OWNER_TYPE"), c.GetString("API_AUTH_OWNER_ID")
|
||||
value, _ := c.Get(psession.GinContextSessionUserKey)
|
||||
u, ok := value.(psession.SessionUser)
|
||||
if (ownerType != APIKeyOwnerPanelAdmin && ownerType != APIKeyOwnerEnterpriseUser) || ownerID == "" || !ok || u.ID != ownerID || u.Name == "" {
|
||||
return psession.SessionUser{}, buserr.New("ErrNotLogin")
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func HasAPICredentials(c *gin.Context) bool {
|
||||
return c.GetHeader("1Panel-Token") != "" || c.GetHeader("1Panel-Timestamp") != "" || c.GetHeader("1Panel-Key-ID") != "" || c.GetHeader("1Panel-Signature-Version") != ""
|
||||
}
|
||||
@@ -87,7 +107,7 @@ func LegacyAPIKeyFingerprint(owner APIKeyOwner, config APIAuthConfig, policy mod
|
||||
}
|
||||
|
||||
func APIKeySecret(key model.APIKey) (string, error) {
|
||||
if key.SecretVersion != 1 || key.SecretCiphertext == "" {
|
||||
if key.DeletedAt != nil || key.Status == "Revoked" || key.SecretVersion != 1 || key.SecretCiphertext == "" {
|
||||
return "", buserr.New("ErrApiConfigKeyInvalid")
|
||||
}
|
||||
master, err := encrypt.APIKeyEncryptionKey()
|
||||
@@ -98,7 +118,7 @@ func APIKeySecret(key model.APIKey) (string, error) {
|
||||
}
|
||||
|
||||
func ValidateAPIKeyState(key model.APIKey, now time.Time) error {
|
||||
if key.Status != constant.StatusEnable {
|
||||
if key.DeletedAt != nil || key.Status != constant.StatusEnable {
|
||||
return buserr.New("ErrApiConfigStatusInvalid")
|
||||
}
|
||||
if key.ExpiresAt != nil && !now.Before(*key.ExpiresAt) {
|
||||
@@ -113,7 +133,7 @@ func configForAPIKey(key model.APIKey, secret string, owner APIKeyOwner) APIAuth
|
||||
|
||||
func loadMultiAPIKeyConfig(c *gin.Context, legacy APIAuthConfigLoader, provider APIKeyOwnerProvider) (APIAuthConfig, error) {
|
||||
keyID := c.GetHeader("1Panel-Key-ID")
|
||||
q := global.DB.Model(&model.APIKey{}).Select("id", "secret_ciphertext", "secret_version", "revision")
|
||||
q := global.DB.Model(&model.APIKey{}).Where("deleted_at IS NULL").Select("id", "secret_ciphertext", "secret_version", "revision")
|
||||
if keyID != "" {
|
||||
q = q.Where("id = ?", keyID)
|
||||
} else {
|
||||
|
||||
+35
-27
@@ -6,41 +6,42 @@ import (
|
||||
)
|
||||
|
||||
type APIKeyItem struct {
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
KeyHint string `json:"keyHint"`
|
||||
Status string `json:"status"`
|
||||
IPWhiteList string `json:"ipWhiteList"`
|
||||
APITrustedProxies string `json:"apiTrustedProxies"`
|
||||
APIKeyValidityTime int `json:"apiKeyValidityTime"`
|
||||
ExpiresAt *time.Time `json:"expiresAt"`
|
||||
AllowAppBinding bool `json:"allowAppBinding"`
|
||||
Revision uint64 `json:"revision"`
|
||||
CreatedAt *time.Time `json:"createdAt"`
|
||||
ID string `json:"id" example:"8a8f0f77-1ec8-4d46-8f5a-0ea8807e2d8a"`
|
||||
Kind string `json:"kind" enums:"apiKey,legacy" example:"apiKey"`
|
||||
Name string `json:"name" example:"Deployment automation"`
|
||||
Description string `json:"description" example:"Used by the deployment service"`
|
||||
KeyHint string `json:"keyHint" example:"abcd••••1234"`
|
||||
Status string `json:"status" enums:"Enable,Disable,Revoked,Expired" example:"Enable"`
|
||||
IPWhiteList string `json:"ipWhiteList" example:"192.0.2.10"`
|
||||
APITrustedProxies string `json:"apiTrustedProxies" example:"192.0.2.1"`
|
||||
APIKeyValidityTime int `json:"apiKeyValidityTime" example:"120"`
|
||||
ExpiresAt *time.Time `json:"expiresAt" format:"date-time" extensions:"x-nullable"`
|
||||
AllowAppBinding bool `json:"allowAppBinding" example:"false"`
|
||||
Revision uint64 `json:"revision" minimum:"1" example:"1"`
|
||||
CreatedAt *time.Time `json:"createdAt" format:"date-time" extensions:"x-nullable"`
|
||||
}
|
||||
|
||||
type APIKeySearch struct {
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"pageSize"`
|
||||
ExcludeRevoked bool `json:"excludeRevoked"`
|
||||
Page int `json:"page" minimum:"1" example:"1"`
|
||||
PageSize int `json:"pageSize" minimum:"1" maximum:"100" example:"20"`
|
||||
ExcludeRevoked bool `json:"excludeRevoked" default:"false"`
|
||||
}
|
||||
type APIKeyPage struct {
|
||||
Items []APIKeyItem `json:"items"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
type APIKeyFields struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
IPWhiteList string `json:"ipWhiteList"`
|
||||
APITrustedProxies string `json:"apiTrustedProxies"`
|
||||
APIKeyValidityTime int `json:"apiKeyValidityTime"`
|
||||
ExpiresAt json.RawMessage `json:"expiresAt"`
|
||||
AllowAppBinding bool `json:"allowAppBinding"`
|
||||
Name string `json:"name" minLength:"1" maxLength:"64" example:"Deployment automation"`
|
||||
Description string `json:"description" maxLength:"256" example:"Used by the deployment service"`
|
||||
IPWhiteList string `json:"ipWhiteList" maxLength:"4096" example:"192.0.2.10"`
|
||||
APITrustedProxies string `json:"apiTrustedProxies" maxLength:"4096" example:"192.0.2.1"`
|
||||
APIKeyValidityTime int `json:"apiKeyValidityTime" minimum:"0" maximum:"1440" example:"120"`
|
||||
ExpiresAt json.RawMessage `json:"expiresAt" swaggertype:"string" format:"date-time" extensions:"x-nullable" example:"2030-01-01T00:00:00Z"`
|
||||
AllowAppBinding bool `json:"allowAppBinding" default:"false"`
|
||||
}
|
||||
type APIKeyCreate struct {
|
||||
RequestID string `json:"requestID"`
|
||||
// Optional client-generated UUID for idempotent retries. Omitted or empty values are generated by the server.
|
||||
RequestID string `json:"requestID" format:"uuid" example:"df1a75a3-5f56-4fa3-9e7a-a573a853d894"`
|
||||
APIKeyFields
|
||||
}
|
||||
type APIKeyCreated struct {
|
||||
@@ -49,8 +50,15 @@ type APIKeyCreated struct {
|
||||
AlreadyCreated bool `json:"alreadyCreated,omitempty"`
|
||||
}
|
||||
type APIKeyMutation struct {
|
||||
ID string `json:"id"`
|
||||
Revision uint64 `json:"revision"`
|
||||
ID string `json:"id" example:"8a8f0f77-1ec8-4d46-8f5a-0ea8807e2d8a"`
|
||||
Revision uint64 `json:"revision" minimum:"1" example:"1"`
|
||||
}
|
||||
type APIKeyMutationResult struct {
|
||||
TerminalClosePending bool `json:"terminalClosePending"`
|
||||
}
|
||||
type APIKeyRevealed struct {
|
||||
APIKeyMutation
|
||||
APIKey string `json:"apiKey"`
|
||||
}
|
||||
type APIKeyUpdate struct {
|
||||
APIKeyMutation
|
||||
@@ -58,5 +66,5 @@ type APIKeyUpdate struct {
|
||||
}
|
||||
type APIKeyStatus struct {
|
||||
APIKeyMutation
|
||||
Status string `json:"status"`
|
||||
Status string `json:"status" enums:"Enable,Disable" example:"Disable"`
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ type APIKey struct {
|
||||
CreatedAt time.Time `json:"-"`
|
||||
UpdatedAt time.Time `json:"-"`
|
||||
RevokedAt *time.Time `json:"-"`
|
||||
DeletedAt *time.Time `json:"-"`
|
||||
}
|
||||
|
||||
type LegacyAPIKeyPolicy struct {
|
||||
|
||||
@@ -14,12 +14,12 @@ func APIKeyOwnerQuery(db *gorm.DB, ownerType, ownerID string) *gorm.DB {
|
||||
}
|
||||
func (r *APIKeyRepo) Get(id string) (model.APIKey, error) {
|
||||
var key model.APIKey
|
||||
err := global.DB.Where("id = ?", id).First(&key).Error
|
||||
err := global.DB.Where("id = ? AND deleted_at IS NULL", id).First(&key).Error
|
||||
return key, err
|
||||
}
|
||||
func (r *APIKeyRepo) List(ownerType, ownerID string, excludeRevoked bool) ([]model.APIKey, error) {
|
||||
items := make([]model.APIKey, 0)
|
||||
q := APIKeyOwnerQuery(global.DB, ownerType, ownerID)
|
||||
q := APIKeyOwnerQuery(global.DB, ownerType, ownerID).Where("deleted_at IS NULL")
|
||||
if excludeRevoked {
|
||||
q = q.Where("status <> ?", "Revoked")
|
||||
}
|
||||
|
||||
@@ -52,6 +52,27 @@ func (s *APIKeyService) owner(c *gin.Context) (auth.APIKeyOwner, error) {
|
||||
return s.Provider.CurrentAPIKeyOwner(c)
|
||||
}
|
||||
|
||||
func (s *APIKeyService) managementOwner(c *gin.Context) (auth.APIKeyOwner, error) {
|
||||
if _, err := auth.RequireAPIKeyManagement(c); err != nil {
|
||||
return auth.APIKeyOwner{}, err
|
||||
}
|
||||
if s.Provider == nil {
|
||||
return auth.APIKeyOwner{}, buserr.New("ErrApiConfigStatusInvalid")
|
||||
}
|
||||
if !c.GetBool("API_AUTH") {
|
||||
return s.Provider.CurrentAPIKeyOwner(c)
|
||||
}
|
||||
ownerType, ownerID := c.GetString("API_AUTH_OWNER_TYPE"), c.GetString("API_AUTH_OWNER_ID")
|
||||
owner, err := s.Provider.ResolveAPIKeyOwner(c, ownerType, ownerID)
|
||||
if err != nil {
|
||||
return auth.APIKeyOwner{}, err
|
||||
}
|
||||
if owner.Type != ownerType || owner.ID != ownerID {
|
||||
return auth.APIKeyOwner{}, buserr.New("ErrNotLogin")
|
||||
}
|
||||
return owner, nil
|
||||
}
|
||||
|
||||
func apiKeyItem(key model.APIKey) dto.APIKeyItem {
|
||||
status := key.Status
|
||||
if status != "Revoked" && key.ExpiresAt != nil && !time.Now().Before(*key.ExpiresAt) {
|
||||
@@ -75,7 +96,7 @@ func (s *APIKeyService) legacy(owner auth.APIKeyOwner) (dto.APIKeyItem, auth.API
|
||||
}
|
||||
|
||||
func (s *APIKeyService) Search(c *gin.Context, req dto.APIKeySearch) (*dto.APIKeyPage, error) {
|
||||
owner, err := s.owner(c)
|
||||
owner, err := s.managementOwner(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -146,11 +167,13 @@ func keyHint(secret string) string {
|
||||
}
|
||||
|
||||
func (s *APIKeyService) Create(c *gin.Context, req dto.APIKeyCreate) (*dto.APIKeyCreated, error) {
|
||||
owner, err := s.owner(c)
|
||||
owner, err := s.managementOwner(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err = uuid.Parse(req.RequestID); err != nil {
|
||||
if req.RequestID == "" {
|
||||
req.RequestID = uuid.NewString()
|
||||
} else if _, err = uuid.Parse(req.RequestID); err != nil {
|
||||
return nil, buserr.New("ErrInvalidParams")
|
||||
}
|
||||
expires, err := validateAPIKeyFields(&req.APIKeyFields, true)
|
||||
@@ -172,6 +195,9 @@ func (s *APIKeyService) Create(c *gin.Context, req dto.APIKeyCreate) (*dto.APIKe
|
||||
q := repo.APIKeyOwnerQuery(tx, owner.Type, owner.ID)
|
||||
err := q.Where("request_id = ?", req.RequestID).First(&key).Error
|
||||
if err == nil {
|
||||
if key.DeletedAt != nil {
|
||||
return buserr.New("ErrAPIKeyNotFound")
|
||||
}
|
||||
if key.RequestHash != requestHash {
|
||||
return buserr.New("ErrAPIKeyConflict")
|
||||
}
|
||||
@@ -219,7 +245,7 @@ func ensureAPIKeyName(tx *gorm.DB, owner auth.APIKeyOwner, name, id string) erro
|
||||
}
|
||||
|
||||
func (s *APIKeyService) Update(c *gin.Context, req dto.APIKeyUpdate) error {
|
||||
owner, err := s.owner(c)
|
||||
owner, err := s.managementOwner(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -247,7 +273,7 @@ func (s *APIKeyService) Update(c *gin.Context, req dto.APIKeyUpdate) error {
|
||||
}
|
||||
|
||||
func (s *APIKeyService) Status(c *gin.Context, req dto.APIKeyStatus) error {
|
||||
owner, err := s.owner(c)
|
||||
owner, err := s.managementOwner(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -271,7 +297,7 @@ func (s *APIKeyService) Status(c *gin.Context, req dto.APIKeyStatus) error {
|
||||
}
|
||||
|
||||
func (s *APIKeyService) Revoke(c *gin.Context, req dto.APIKeyMutation) error {
|
||||
owner, err := s.owner(c)
|
||||
owner, err := s.managementOwner(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -289,21 +315,75 @@ func (s *APIKeyService) Revoke(c *gin.Context, req dto.APIKeyMutation) error {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *APIKeyService) Delete(c *gin.Context, req dto.APIKeyMutation) error {
|
||||
owner, err := s.managementOwner(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if req.ID == "legacy" {
|
||||
return buserr.New("ErrInvalidParams")
|
||||
}
|
||||
return s.mutate(c, owner, req, "delete", func(_ *gorm.DB, key *model.APIKey) error {
|
||||
now := time.Now()
|
||||
key.Status = "Revoked"
|
||||
if key.RevokedAt == nil {
|
||||
key.RevokedAt = &now
|
||||
}
|
||||
key.DeletedAt = &now
|
||||
key.ActiveName = nil
|
||||
key.SecretCiphertext = ""
|
||||
key.KeyHint = ""
|
||||
key.AllowAppBinding = false
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *APIKeyService) Reveal(c *gin.Context, req dto.APIKeyMutation) (*dto.APIKeyRevealed, error) {
|
||||
owner, err := s.owner(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if req.ID == "" || req.ID == "legacy" || req.Revision == 0 {
|
||||
return nil, buserr.New("ErrInvalidParams")
|
||||
}
|
||||
// Serialize the snapshot and disclosure audit with revocation/deletion.
|
||||
apiKeyMutationMu.Lock()
|
||||
defer apiKeyMutationMu.Unlock()
|
||||
var key model.APIKey
|
||||
if err = repo.APIKeyOwnerQuery(global.DB, owner.Type, owner.ID).Where("id = ? AND deleted_at IS NULL", req.ID).First(&key).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, buserr.New("ErrAPIKeyNotFound")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if key.Revision != req.Revision || key.Status == "Revoked" {
|
||||
return nil, buserr.New("ErrAPIKeyConflict")
|
||||
}
|
||||
secret, err := auth.APIKeySecret(key)
|
||||
if err != nil {
|
||||
return nil, buserr.New("ErrApiConfigKeyInvalid")
|
||||
}
|
||||
if err = apikey_audit.Record(c, apikey_audit.Event{OwnerType: owner.Type, OwnerID: owner.ID, KeyID: key.ID, KeyName: key.Name, Action: "reveal", Status: constant.StatusSuccess}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dto.APIKeyRevealed{APIKeyMutation: req, APIKey: secret}, nil
|
||||
}
|
||||
|
||||
func (s *APIKeyService) mutate(c *gin.Context, owner auth.APIKeyOwner, req dto.APIKeyMutation, action string, change func(*gorm.DB, *model.APIKey) error) error {
|
||||
if req.ID == "" || req.Revision == 0 {
|
||||
return buserr.New("ErrInvalidParams")
|
||||
}
|
||||
apiKeyMutationMu.Lock()
|
||||
var key model.APIKey
|
||||
closeTerminals := action == "disable" || action == "revoke"
|
||||
closeTerminals := action == "disable" || action == "revoke" || action == "delete"
|
||||
err := global.DB.Transaction(func(tx *gorm.DB) error {
|
||||
if err := repo.APIKeyOwnerQuery(tx, owner.Type, owner.ID).Where("id = ?", req.ID).First(&key).Error; err != nil {
|
||||
if err := repo.APIKeyOwnerQuery(tx, owner.Type, owner.ID).Where("id = ? AND deleted_at IS NULL", req.ID).First(&key).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return buserr.New("ErrAPIKeyNotFound")
|
||||
}
|
||||
return err
|
||||
}
|
||||
if key.Revision != req.Revision || key.Status == "Revoked" {
|
||||
if key.Revision != req.Revision || (key.Status == "Revoked" && action != "delete") {
|
||||
return buserr.New("ErrAPIKeyConflict")
|
||||
}
|
||||
before := key
|
||||
|
||||
+2143
-267
File diff suppressed because it is too large
Load Diff
@@ -18,7 +18,10 @@ import (
|
||||
// @schemes http https
|
||||
|
||||
// @securityDefinitions.apikey ApiKeyAuth
|
||||
// @description Custom Token Format, Format: md5('1panel' + API-Key + UnixTimestamp).
|
||||
// @description Signed API Key authentication. Send the signature, never the plaintext API Key, in 1Panel-Token.
|
||||
// @description Supported formats: hex(HMAC-SHA256(API-Key, '1panel:' + UnixTimestamp)) or md5('1panel' + API-Key + UnixTimestamp).
|
||||
// @description Send the matching Unix timestamp in 1Panel-Timestamp. Optionally set 1Panel-Signature-Version to hmac-sha256, v1 or md5; omission accepts either algorithm.
|
||||
// @description Independent keys may include their ID in 1Panel-Key-ID to select the credential; omit that header for a legacy key.
|
||||
// @description ```
|
||||
// @description eg:
|
||||
// @description curl -X GET "http://{host}:{port}/api/v2/toolbox/device/base" \
|
||||
@@ -27,7 +30,7 @@ import (
|
||||
// @description ```
|
||||
// @description - `1Panel-Token` is the key for the panel API Key.
|
||||
// @type apiKey
|
||||
// @in Header
|
||||
// @in header
|
||||
// @name 1Panel-Token
|
||||
// @securityDefinitions.apikey Timestamp
|
||||
// @type apiKey
|
||||
|
||||
@@ -72,5 +72,6 @@ func coreMigrations() []*gormigrate.Migration {
|
||||
migrations.UpdateAiMenuOrder,
|
||||
migrations.UpdateAiMenuOrderV2,
|
||||
migrations.AddPanelMCP,
|
||||
migrations.AddAPIKeyDeletedAt,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,3 +15,8 @@ var AddOperationLogAPIKey = &gormigrate.Migration{
|
||||
ID: "20260915-add-operation-log-api-key",
|
||||
Migrate: func(tx *gorm.DB) error { return tx.AutoMigrate(&model.OperationLog{}) },
|
||||
}
|
||||
|
||||
var AddAPIKeyDeletedAt = &gormigrate.Migration{
|
||||
ID: "20261028-api-key-deleted-at",
|
||||
Migrate: func(tx *gorm.DB) error { return tx.AutoMigrate(&model.APIKey{}) },
|
||||
}
|
||||
|
||||
@@ -42,6 +42,10 @@ func OperationLog() gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
switch c.Request.URL.Path {
|
||||
case "/api/v2/core/auth/api/keys/reveal":
|
||||
// Disclosure has its own audit and must not enter response-body capture.
|
||||
c.Next()
|
||||
return
|
||||
case "/api/v2/core/mcp/credentials/create", "/api/v2/core/mcp/credentials/reveal", "/api/v2/core/mcp/credentials/rotate", "/api/v2/core/mcp/credentials/export":
|
||||
c.Next()
|
||||
return
|
||||
|
||||
@@ -40,6 +40,8 @@ func (s *BaseRouter) InitRouter(Router *gin.RouterGroup) {
|
||||
authRouter.POST("/api/keys/update", baseApi.UpdateAPIKey)
|
||||
authRouter.POST("/api/keys/status", baseApi.SetAPIKeyStatus)
|
||||
authRouter.POST("/api/keys/revoke", baseApi.RevokeAPIKey)
|
||||
authRouter.POST("/api/keys/delete", baseApi.DeleteAPIKey)
|
||||
authRouter.POST("/api/keys/reveal", baseApi.RevealAPIKey)
|
||||
|
||||
authRouter.GET("/current", baseApi.GetCurrentUser)
|
||||
authRouter.POST("/current/update", baseApi.UpdateCurrentUser)
|
||||
|
||||
@@ -45,6 +45,8 @@ func Build(c *gin.Context, event Event) (*model.OperationLog, error) {
|
||||
"enable": {"启用 API Key", "Enable API key"},
|
||||
"disable": {"停用 API Key", "Disable API key"},
|
||||
"revoke": {"撤销 API Key", "Revoke API key"},
|
||||
"delete": {"删除 API Key", "Delete API key"},
|
||||
"reveal": {"查看 API Key", "Reveal API key"},
|
||||
"app_binding": {"向 APP 交付 API Key", "Deliver API key to APP"},
|
||||
}
|
||||
label, ok := labels[event.Action]
|
||||
@@ -80,6 +82,17 @@ func Build(c *gin.Context, event Event) (*model.OperationLog, error) {
|
||||
record.UserAgent = c.Request.UserAgent()
|
||||
record.IP = c.ClientIP()
|
||||
}
|
||||
if c.GetBool("API_AUTH") && event.Action != "app_binding" {
|
||||
record.AuthMethod = "api_key"
|
||||
record.APIKeyID = c.GetString("API_AUTH_KEY_ID")
|
||||
record.APIKeyName = c.GetString("API_AUTH_KEY_NAME")
|
||||
if c.GetString("API_AUTH_KEY_KIND") == "legacy" {
|
||||
record.APIKeyID = "legacy:" + c.GetString("API_AUTH_OWNER_TYPE") + ":" + c.GetString("API_AUTH_OWNER_ID")
|
||||
}
|
||||
if clientIP := c.GetString("API_AUTH_CLIENT_IP"); clientIP != "" {
|
||||
record.IP = clientIP
|
||||
}
|
||||
}
|
||||
}
|
||||
if event.ClientIP != "" {
|
||||
record.IP = event.ClientIP
|
||||
|
||||
@@ -30,4 +30,7 @@ export namespace APIKey {
|
||||
id: string;
|
||||
revision: number;
|
||||
}
|
||||
export interface Revealed extends Reference {
|
||||
apiKey: string;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ const prefix = '/core/auth/api/keys';
|
||||
export const searchAPIKeys = (params: { page: number; pageSize: number; excludeRevoked?: boolean }) => {
|
||||
return http.post<APIKey.Search>(`${prefix}/search`, params);
|
||||
};
|
||||
export const createAPIKey = (params: APIKey.Editable & { requestID: string }) => {
|
||||
export const createAPIKey = (params: APIKey.Editable & { requestID?: string }) => {
|
||||
return http.post<APIKey.Created>(`${prefix}/create`, params);
|
||||
};
|
||||
export const updateAPIKey = (params: APIKey.Editable & APIKey.Reference) => {
|
||||
@@ -18,3 +18,9 @@ export const setAPIKeyStatus = (params: APIKey.Reference & { status: 'Enable' |
|
||||
export const revokeAPIKey = (params: APIKey.Reference) => {
|
||||
return http.post<{ terminalClosePending: boolean }>(`${prefix}/revoke`, params);
|
||||
};
|
||||
export const deleteAPIKey = (params: APIKey.Reference) => {
|
||||
return http.post<{ terminalClosePending: boolean }>(`${prefix}/delete`, params);
|
||||
};
|
||||
export const revealAPIKey = (params: APIKey.Reference) => {
|
||||
return http.post<APIKey.Revealed>(`${prefix}/reveal`, params);
|
||||
};
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 424 KiB After Width: | Height: | Size: 382 KiB |
@@ -6,27 +6,14 @@
|
||||
:confirm-before-close="true"
|
||||
@before-close="beforeClose"
|
||||
>
|
||||
<template v-if="created">
|
||||
<el-alert
|
||||
:title="$t(secret ? 'apiKeyManagement.saveSecret' : 'apiKeyManagement.alreadyCreated')"
|
||||
:type="secret ? 'warning' : 'info'"
|
||||
:closable="false"
|
||||
show-icon
|
||||
class="mb-4"
|
||||
/>
|
||||
<el-form label-position="top">
|
||||
<el-form-item :label="$t('commons.table.name')">{{ created.name }}</el-form-item>
|
||||
<el-form-item v-if="secret" :label="$t('setting.apiKey')">
|
||||
<el-input :model-value="secret" readonly autocomplete="off">
|
||||
<template #append>
|
||||
<CopyButton :content="secret" :is-icon="false" />
|
||||
</template>
|
||||
</el-input>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<el-checkbox v-if="secret" v-model="saved">{{ $t('apiKeyManagement.saved') }}</el-checkbox>
|
||||
</template>
|
||||
<el-form v-else ref="formRef" :model="form" :rules="rules" label-position="top" @submit.prevent="submit">
|
||||
<el-form
|
||||
ref="formRef"
|
||||
:model="form"
|
||||
:rules="rules"
|
||||
label-position="top"
|
||||
class="text-[var(--el-text-color-regular)]"
|
||||
@submit.prevent="submit"
|
||||
>
|
||||
<el-alert v-if="!item" type="warning" :closable="false" class="!mb-4">
|
||||
<ul class="m-0 list-disc space-y-1 pl-4 break-words leading-6">
|
||||
<li>
|
||||
@@ -139,13 +126,10 @@
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button v-if="!created" :disabled="busy" @click="beforeClose(() => (visible = false))">
|
||||
<el-button :disabled="busy" @click="beforeClose(() => (visible = false))">
|
||||
{{ $t('commons.button.cancel') }}
|
||||
</el-button>
|
||||
<el-button v-if="created" type="primary" :disabled="!!secret && !saved" @click="finish">
|
||||
{{ $t('commons.button.confirm') }}
|
||||
</el-button>
|
||||
<el-button v-else type="primary" :loading="busy" @click="submit">
|
||||
<el-button type="primary" :loading="busy" @click="submit">
|
||||
{{ $t(item ? 'commons.button.save' : 'apiKeyManagement.create') }}
|
||||
</el-button>
|
||||
</template>
|
||||
@@ -154,7 +138,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, reactive, ref, watch } from 'vue';
|
||||
import { ElMessageBox, type FormInstance } from 'element-plus';
|
||||
import type { FormInstance } from 'element-plus';
|
||||
import { isAxiosError } from 'axios';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { onBeforeRouteLeave } from 'vue-router';
|
||||
@@ -174,9 +158,6 @@ const visible = ref(false);
|
||||
const busy = ref(false);
|
||||
const uncertain = ref(false);
|
||||
const item = ref<APIKey.Item>();
|
||||
const created = ref<APIKey.Item>();
|
||||
const secret = ref('');
|
||||
const saved = ref(false);
|
||||
const formRef = ref<FormInstance>();
|
||||
const ipMode = ref('restricted');
|
||||
const neverExpires = ref(false);
|
||||
@@ -196,8 +177,6 @@ let editorVersion = 0;
|
||||
|
||||
const discardEditor = () => {
|
||||
editorVersion++;
|
||||
secret.value = '';
|
||||
created.value = undefined;
|
||||
visible.value = false;
|
||||
busy.value = false;
|
||||
};
|
||||
@@ -240,9 +219,6 @@ const rules = {
|
||||
const open = (existing?: APIKey.Item, fromApp = false) => {
|
||||
editorVersion++;
|
||||
item.value = existing;
|
||||
created.value = undefined;
|
||||
secret.value = '';
|
||||
saved.value = false;
|
||||
uncertain.value = false;
|
||||
pendingCreate = undefined;
|
||||
requestID = uuidv4();
|
||||
@@ -269,19 +245,9 @@ const open = (existing?: APIKey.Item, fromApp = false) => {
|
||||
nextTick(() => formRef.value?.clearValidate());
|
||||
};
|
||||
|
||||
const finish = () => {
|
||||
secret.value = '';
|
||||
visible.value = false;
|
||||
if (created.value) emit('created', created.value);
|
||||
};
|
||||
const beforeClose = async (done: () => void) => {
|
||||
const beforeClose = (done: () => void) => {
|
||||
if (busy.value) return;
|
||||
if (secret.value && !saved.value) {
|
||||
await ElMessageBox.alert(i18n.global.t('apiKeyManagement.saveSecret'), i18n.global.t('apiKeyManagement.title'));
|
||||
return;
|
||||
}
|
||||
if (created.value) finish();
|
||||
else if (uncertain.value) emit('changed');
|
||||
if (uncertain.value) emit('changed');
|
||||
done();
|
||||
};
|
||||
|
||||
@@ -310,9 +276,13 @@ const submit = async () => {
|
||||
pendingCreate ??= { ...payload, requestID };
|
||||
const response = await createAPIKey(pendingCreate);
|
||||
if (ticket !== editorVersion) return;
|
||||
created.value = response.data.item;
|
||||
secret.value = response.data.apiKey;
|
||||
uncertain.value = false;
|
||||
pendingCreate = undefined;
|
||||
MsgSuccess(i18n.global.t('commons.msg.createSuccess'));
|
||||
visible.value = false;
|
||||
emit('changed');
|
||||
emit('created', response.data.item);
|
||||
return;
|
||||
}
|
||||
emit('changed');
|
||||
} catch (error) {
|
||||
@@ -341,16 +311,12 @@ watch(
|
||||
{ flush: 'sync' },
|
||||
);
|
||||
onBeforeUnmount(discardEditor);
|
||||
onBeforeRouteLeave(async (to) => {
|
||||
onBeforeRouteLeave((to) => {
|
||||
if (!globalStore.isLogin || ['entrance', 'Expired', 'EnterpriseLicenseRequired'].includes(String(to.name))) {
|
||||
discardEditor();
|
||||
return true;
|
||||
}
|
||||
if (busy.value) return false;
|
||||
if (secret.value && !saved.value) {
|
||||
await ElMessageBox.alert(i18n.global.t('apiKeyManagement.saveSecret'), i18n.global.t('apiKeyManagement.title'));
|
||||
return false;
|
||||
}
|
||||
discardEditor();
|
||||
return true;
|
||||
});
|
||||
|
||||
@@ -2,6 +2,11 @@ import { getFuLocaleMessage } from '@/lang/fu';
|
||||
|
||||
const message = {
|
||||
apiKeyManagement: {
|
||||
reveal: 'Show secret',
|
||||
hideSecret: 'Hide secret',
|
||||
revealHelp: 'Keep this secret secure. Disabled or expired keys remain unusable even when displayed.',
|
||||
deleteConfirm:
|
||||
'Delete “{0}”? Its secret will be destroyed and the key removed from the list. New requests will be rejected and terminal connections closed. Audit records are retained; running jobs are not cancelled. This cannot be undone.',
|
||||
title: 'API Key',
|
||||
manage: 'Manage API Keys',
|
||||
personalEntry: 'Manage your keys, access conditions, and APP binding in Settings.',
|
||||
@@ -23,10 +28,6 @@ const message = {
|
||||
allowAppBinding: 'Allow APP QR binding',
|
||||
bindingDisableHelp:
|
||||
'Disabling QR binding prevents new device bindings. Devices already bound can continue to use the key until it is disabled, revoked, or expires.',
|
||||
saveSecret: 'Copy and save this secret now. After closing, ordinary key management cannot display it again.',
|
||||
saved: 'I have saved the secret',
|
||||
alreadyCreated:
|
||||
'This key was already created. Its secret will not be shown again. If the original response was lost, revoke and recreate it, or use QR binding if allowed.',
|
||||
uncertain:
|
||||
'The request result is uncertain. Retry with the same details to avoid duplicate keys, or close and check the list before creating another.',
|
||||
legacyHelp:
|
||||
|
||||
@@ -2,6 +2,11 @@ import { getFuLocaleMessage } from '@/lang/fu';
|
||||
|
||||
const message = {
|
||||
apiKeyManagement: {
|
||||
reveal: 'Mostrar secreto',
|
||||
hideSecret: 'Ocultar secreto',
|
||||
revealHelp: 'Guarde el secreto de forma segura. Mostrarlo no reactiva claves deshabilitadas o caducadas.',
|
||||
deleteConfirm:
|
||||
'¿Eliminar «{0}»? Se destruirá el secreto y se quitará la clave de la lista. Se rechazarán nuevas solicitudes y se cerrarán sus terminales. Se conservará la auditoría; las tareas en ejecución no se cancelarán. Esta acción es irreversible.',
|
||||
title: 'API Key',
|
||||
manage: 'Gestionar claves API',
|
||||
personalEntry: 'Gestiona tus claves, condiciones de acceso y vinculación de la APP en Ajustes.',
|
||||
@@ -23,10 +28,6 @@ const message = {
|
||||
allowAppBinding: 'Permitir vinculación de APP por QR',
|
||||
bindingDisableHelp:
|
||||
'Desactivar la vinculación por QR impide nuevas vinculaciones. Los dispositivos ya vinculados pueden seguir usando la clave hasta que se desactive, se revoque o caduque.',
|
||||
saveSecret: 'Copia y guarda la clave ahora. Tras cerrar, la gestión normal no podrá mostrarla de nuevo.',
|
||||
saved: 'He guardado la clave',
|
||||
alreadyCreated:
|
||||
'La clave ya se creó y no se mostrará de nuevo. Si se perdió la respuesta original, revócala y crea otra, o usa QR si está permitido.',
|
||||
uncertain:
|
||||
'El resultado es incierto. Reintenta con los mismos datos para evitar duplicados, o cierra y revisa la lista antes de crear otra.',
|
||||
legacyHelp:
|
||||
|
||||
@@ -2,6 +2,11 @@ import { getFuLocaleMessage } from '@/lang/fu';
|
||||
|
||||
const message = {
|
||||
apiKeyManagement: {
|
||||
reveal: 'نمایش کلید محرمانه',
|
||||
hideSecret: 'پنهان کردن کلید محرمانه',
|
||||
revealHelp: 'کلید را در جای امن نگه دارید. نمایش آن، کلید غیرفعال یا منقضیشده را قابل استفاده نمیکند.',
|
||||
deleteConfirm:
|
||||
'«{0}» حذف شود؟ کلید محرمانه نابود و از فهرست حذف میشود. درخواستهای جدید رد و اتصالهای ترمینال مرتبط بسته میشوند. سوابق حسابرسی حفظ و کارهای در حال اجرا لغو نمیشوند. این عملیات برگشتپذیر نیست.',
|
||||
title: 'API Key',
|
||||
manage: 'مدیریت کلیدهای API',
|
||||
personalEntry: 'کلیدها، شرایط دسترسی و اتصال برنامه را در تنظیمات مدیریت کنید.',
|
||||
@@ -23,10 +28,6 @@ const message = {
|
||||
allowAppBinding: 'اجازه اتصال برنامه با QR',
|
||||
bindingDisableHelp:
|
||||
'با غیرفعال کردن اتصال از طریق QR، اتصال دستگاههای جدید متوقف میشود. دستگاههای متصل میتوانند تا زمان غیرفعالسازی، لغو یا انقضای کلید به استفاده از آن ادامه دهند.',
|
||||
saveSecret: 'اکنون کلید را کپی و ذخیره کنید. پس از بستن، مدیریت عادی نمیتواند کلید کامل را دوباره نشان دهد.',
|
||||
saved: 'کلید را ذخیره کردم',
|
||||
alreadyCreated:
|
||||
'این کلید قبلاً ایجاد شده و دوباره نمایش داده نمیشود. اگر پاسخ اصلی گم شده است، کلید را لغو و دوباره ایجاد کنید یا در صورت اجازه از QR استفاده کنید.',
|
||||
uncertain:
|
||||
'نتیجه درخواست نامشخص است. برای جلوگیری از تکرار، با همان اطلاعات دوباره تلاش کنید یا ببندید و پیش از ایجاد کلید دیگر فهرست را بررسی کنید.',
|
||||
legacyHelp:
|
||||
|
||||
@@ -2,6 +2,11 @@ import { getFuLocaleMessage } from '@/lang/fu';
|
||||
|
||||
const message = {
|
||||
apiKeyManagement: {
|
||||
reveal: 'シークレットを表示',
|
||||
hideSecret: 'シークレットを隠す',
|
||||
revealHelp: 'シークレットを安全に保管してください。表示しても無効または期限切れのキーは使用できません。',
|
||||
deleteConfirm:
|
||||
'「{0}」を削除しますか?シークレットは破棄され、キーは一覧から削除されます。新しいリクエストは拒否され、関連ターミナルは切断されます。監査記録は保持され、実行中のタスクは中止されません。この操作は元に戻せません。',
|
||||
title: 'API Key',
|
||||
manage: 'API Key を管理',
|
||||
personalEntry: '設定で自分のキー、アクセス条件、APP の QR 連携を管理します。',
|
||||
@@ -23,10 +28,6 @@ const message = {
|
||||
allowAppBinding: 'APP の QR 連携を許可',
|
||||
bindingDisableHelp:
|
||||
'QR 連携を無効にすると、新規の連携を受け付けなくなります。連携済みの端末は、キーが無効化、失効、または期限切れになるまで引き続き利用できます。',
|
||||
saveSecret: '今すぐキーをコピーして保存してください。閉じると通常のキー管理から完全なキーを再表示できません。',
|
||||
saved: 'キーを保存しました',
|
||||
alreadyCreated:
|
||||
'このキーは作成済みで、再表示できません。最初の応答を受け取れなかった場合は失効させて再作成するか、許可されていれば QR を使用してください。',
|
||||
uncertain: 'リクエスト結果が不明です。重複を避けるため同じ設定で再試行するか、閉じて一覧を確認してください。',
|
||||
legacyHelp:
|
||||
'旧版キーは従来の API 接続との互換性を維持します。有効化、無効化、リセットはこのキーにのみ適用されます。',
|
||||
|
||||
@@ -2,6 +2,11 @@ import { getFuLocaleMessage } from '@/lang/fu';
|
||||
|
||||
const message = {
|
||||
apiKeyManagement: {
|
||||
reveal: '비밀 키 표시',
|
||||
hideSecret: '비밀 키 숨기기',
|
||||
revealHelp: '비밀 키를 안전하게 보관하세요. 표시해도 비활성화되거나 만료된 키는 사용할 수 없습니다.',
|
||||
deleteConfirm:
|
||||
'“{0}”을(를) 삭제하시겠습니까? 비밀 키가 파기되고 목록에서 제거됩니다. 새 요청은 거부되고 연결된 터미널은 종료됩니다. 감사 기록은 유지되며 실행 중인 작업은 취소되지 않습니다. 이 작업은 되돌릴 수 없습니다.',
|
||||
title: 'API Key',
|
||||
manage: 'API Key 관리',
|
||||
personalEntry: '설정에서 내 키, 접근 조건 및 APP QR 연결을 관리합니다.',
|
||||
@@ -23,10 +28,6 @@ const message = {
|
||||
allowAppBinding: 'APP QR 연결 허용',
|
||||
bindingDisableHelp:
|
||||
'QR 연결을 비활성화하면 새로운 기기를 연결할 수 없습니다. 이미 연결된 기기는 키가 비활성화, 폐기 또는 만료될 때까지 계속 사용할 수 있습니다.',
|
||||
saveSecret: '지금 키를 복사하여 저장하세요. 닫으면 일반 키 관리에서 전체 키를 다시 표시할 수 없습니다.',
|
||||
saved: '키를 저장했습니다',
|
||||
alreadyCreated:
|
||||
'이 키는 이미 생성되어 다시 표시할 수 없습니다. 원래 응답을 잃었다면 폐기 후 다시 만들거나 허용된 QR 연결을 사용하세요.',
|
||||
uncertain:
|
||||
'요청 결과를 확인할 수 없습니다. 중복 생성을 피하려면 같은 설정으로 재시도하거나 닫고 목록을 확인하세요.',
|
||||
legacyHelp:
|
||||
|
||||
@@ -2,6 +2,11 @@ import { getFuLocaleMessage } from '@/lang/fu';
|
||||
|
||||
const message = {
|
||||
apiKeyManagement: {
|
||||
reveal: 'ສະແດງຄີລັບ',
|
||||
hideSecret: 'ເຊື່ອງຄີລັບ',
|
||||
revealHelp: 'ກະລຸນາເກັບຄີລັບໃຫ້ປອດໄພ. ການສະແດງບໍ່ເຮັດໃຫ້ຄີທີ່ປິດໃຊ້ງານ ຫຼືໝົດອາຍຸກັບມາໃຊ້ໄດ້.',
|
||||
deleteConfirm:
|
||||
'ລຶບ “{0}” ຫຼືບໍ່? ຄີລັບຈະຖືກທຳລາຍ ແລະລຶບອອກຈາກລາຍການ. ຄຳຮ້ອງຂໍໃໝ່ຈະຖືກປະຕິເສດ ແລະປິດເທີມິນັລທີ່ກ່ຽວຂ້ອງ. ບັນທຶກການກວດສອບຈະຍັງຄົງຢູ່; ວຽກທີ່ກຳລັງເຮັດຈະບໍ່ຖືກຍົກເລີກ. ບໍ່ສາມາດກູ້ຄືນໄດ້.',
|
||||
title: 'API Key',
|
||||
manage: 'ຈັດການ API Key',
|
||||
personalEntry: 'ຈັດການກະແຈ, ເງື່ອນໄຂເຂົ້າໃຊ້ ແລະ ການຜູກ APP ໃນການຕັ້ງຄ່າ.',
|
||||
@@ -23,9 +28,6 @@ const message = {
|
||||
allowAppBinding: 'ອະນຸຍາດຜູກ APP ຜ່ານ QR',
|
||||
bindingDisableHelp:
|
||||
'ເມື່ອປິດການຜູກມັດຜ່ານ QR, ລະບົບຈະບໍ່ຮັບການຜູກມັດໃໝ່. ອຸປະກອນທີ່ຜູກມັດແລ້ວຍັງສາມາດໃຊ້ງານໄດ້ ຈົນກວ່າກະແຈຈະຖືກປິດໃຊ້, ຖອນ ຫຼື ໝົດອາຍຸ.',
|
||||
saveSecret: 'ຄັດລອກ ແລະ ບັນທຶກກະແຈດຽວນີ້. ຫຼັງປິດແລ້ວ ການຈັດການປົກກະຕິຈະບໍ່ສະແດງກະແຈເຕັມອີກ.',
|
||||
saved: 'ຂ້ອຍບັນທຶກກະແຈແລ້ວ',
|
||||
alreadyCreated: 'ກະແຈນີ້ສ້າງແລ້ວ ແລະ ບໍ່ສະແດງອີກ. ຖ້າຄຳຕອບເກົ່າຫາຍ ໃຫ້ຖອນແລ້ວສ້າງໃໝ່ ຫຼື ໃຊ້ QR ຖ້າອະນຸຍາດ.',
|
||||
uncertain: 'ຍັງບໍ່ແນ່ໃຈຜົນຄຳຮ້ອງ. ລອງໃໝ່ດ້ວຍຂໍ້ມູນເດີມເພື່ອບໍ່ສ້າງຊ້ຳ ຫຼື ປິດແລ້ວກວດລາຍການກ່ອນສ້າງອີກ.',
|
||||
legacyHelp:
|
||||
'ກະແຈເກົ່າໃຊ້ເພື່ອຮອງຮັບການເຊື່ອມຕໍ່ API ເກົ່າ. ການເປີດໃຊ້, ປິດໃຊ້ ແລະ ຣີເຊັດ ມີຜົນສະເພາະກະແຈນີ້ເທົ່ານັ້ນ.',
|
||||
|
||||
@@ -2,6 +2,12 @@ import { getFuLocaleMessage } from '@/lang/fu';
|
||||
|
||||
const message = {
|
||||
apiKeyManagement: {
|
||||
reveal: 'Papar rahsia',
|
||||
hideSecret: 'Sembunyikan rahsia',
|
||||
revealHelp:
|
||||
'Simpan rahsia ini dengan selamat. Memaparkannya tidak mengaktifkan semula kunci yang dinyahdayakan atau tamat tempoh.',
|
||||
deleteConfirm:
|
||||
'Padam “{0}”? Rahsianya akan dimusnahkan dan kunci dibuang daripada senarai. Permintaan baharu akan ditolak dan terminal berkaitan ditutup. Rekod audit dikekalkan; tugas yang sedang berjalan tidak dibatalkan. Tindakan ini tidak boleh dibuat asal.',
|
||||
title: 'API Key',
|
||||
manage: 'Urus kunci API',
|
||||
personalEntry: 'Urus kunci, syarat akses dan pautan APP anda dalam Tetapan.',
|
||||
@@ -23,11 +29,6 @@ const message = {
|
||||
allowAppBinding: 'Benarkan pautan APP melalui QR',
|
||||
bindingDisableHelp:
|
||||
'Menyahdayakan pautan QR menghalang pautan peranti baharu. Peranti yang telah dipautkan boleh terus digunakan sehingga kunci dinyahdayakan, dibatalkan atau tamat tempoh.',
|
||||
saveSecret:
|
||||
'Salin dan simpan kunci sekarang. Selepas ditutup, pengurusan biasa tidak dapat memaparkan kunci penuh lagi.',
|
||||
saved: 'Saya telah menyimpan kunci',
|
||||
alreadyCreated:
|
||||
'Kunci ini telah dicipta dan tidak akan dipaparkan semula. Jika respons asal hilang, batalkan dan cipta semula atau gunakan QR jika dibenarkan.',
|
||||
uncertain:
|
||||
'Hasil permintaan belum pasti. Cuba semula dengan butiran sama untuk mengelakkan pendua, atau tutup dan semak senarai sebelum mencipta lagi.',
|
||||
legacyHelp:
|
||||
|
||||
@@ -2,6 +2,11 @@ import { getFuLocaleMessage } from '@/lang/fu';
|
||||
|
||||
const message = {
|
||||
apiKeyManagement: {
|
||||
reveal: 'Mostrar segredo',
|
||||
hideSecret: 'Ocultar segredo',
|
||||
revealHelp: 'Guarde o segredo com segurança. Exibi-lo não reativa chaves desabilitadas ou expiradas.',
|
||||
deleteConfirm:
|
||||
'Excluir “{0}”? O segredo será destruído e a chave removida da lista. Novas solicitações serão rejeitadas e os terminais associados serão fechados. Os registros de auditoria serão mantidos; tarefas em execução não serão canceladas. Esta ação é irreversível.',
|
||||
title: 'API Key',
|
||||
manage: 'Gerenciar chaves API',
|
||||
personalEntry: 'Gerencie suas chaves, condições de acesso e vínculo do APP nas Configurações.',
|
||||
@@ -23,10 +28,6 @@ const message = {
|
||||
allowAppBinding: 'Permitir vínculo do APP por QR',
|
||||
bindingDisableHelp:
|
||||
'Desativar a vinculação por QR impede novas vinculações. Os dispositivos já vinculados podem continuar usando a chave até que ela seja desativada, revogada ou expire.',
|
||||
saveSecret: 'Copie e salve a chave agora. Após fechar, o gerenciamento normal não poderá exibi-la novamente.',
|
||||
saved: 'Salvei a chave',
|
||||
alreadyCreated:
|
||||
'Esta chave já foi criada e não será exibida novamente. Se a resposta original foi perdida, revogue e recrie a chave ou use o QR, se permitido.',
|
||||
uncertain:
|
||||
'O resultado é incerto. Tente novamente com os mesmos dados para evitar duplicações ou feche e verifique a lista antes de criar outra.',
|
||||
legacyHelp:
|
||||
|
||||
@@ -2,6 +2,11 @@ import { getFuLocaleMessage } from '@/lang/fu';
|
||||
|
||||
const message = {
|
||||
apiKeyManagement: {
|
||||
reveal: 'Показать секрет',
|
||||
hideSecret: 'Скрыть секрет',
|
||||
revealHelp: 'Храните секрет в безопасности. Просмотр не активирует отключённые или просроченные ключи.',
|
||||
deleteConfirm:
|
||||
'Удалить «{0}»? Секрет будет уничтожен, а ключ удалён из списка. Новые запросы будут отклонены, связанные терминалы закрыты. Журнал аудита сохранится; выполняющиеся задачи не отменяются. Действие необратимо.',
|
||||
title: 'API Key',
|
||||
manage: 'Управление API-ключами',
|
||||
personalEntry: 'Управляйте своими ключами, условиями доступа и привязкой приложения в настройках.',
|
||||
@@ -23,11 +28,6 @@ const message = {
|
||||
allowAppBinding: 'Разрешить привязку приложения по QR',
|
||||
bindingDisableHelp:
|
||||
'Отключение привязки по QR-коду запрещает новые привязки. Уже привязанные устройства могут продолжать работу, пока ключ не будет отключён, отозван или не истечёт срок его действия.',
|
||||
saveSecret:
|
||||
'Скопируйте и сохраните ключ сейчас. После закрытия обычное управление не сможет показать полный ключ снова.',
|
||||
saved: 'Ключ сохранён',
|
||||
alreadyCreated:
|
||||
'Ключ уже создан и не будет показан повторно. Если исходный ответ потерян, отзовите и создайте ключ заново либо используйте разрешённую привязку по QR.',
|
||||
uncertain:
|
||||
'Результат запроса неизвестен. Повторите с теми же данными, чтобы избежать дублей, или закройте и проверьте список.',
|
||||
legacyHelp:
|
||||
|
||||
@@ -2,6 +2,12 @@ import { getFuLocaleMessage } from '@/lang/fu';
|
||||
|
||||
const message = {
|
||||
apiKeyManagement: {
|
||||
reveal: 'Gizli anahtarı göster',
|
||||
hideSecret: 'Gizli anahtarı gizle',
|
||||
revealHelp:
|
||||
'Gizli anahtarı güvenli tutun. Görüntülemek, devre dışı veya süresi dolmuş anahtarı kullanılabilir yapmaz.',
|
||||
deleteConfirm:
|
||||
'“{0}” silinsin mi? Gizli anahtar yok edilecek ve listeden kaldırılacaktır. Yeni istekler reddedilecek ve ilgili terminaller kapatılacaktır. Denetim kayıtları korunur; çalışan işler iptal edilmez. Bu işlem geri alınamaz.',
|
||||
title: 'API Key',
|
||||
manage: 'API anahtarlarını yönet',
|
||||
personalEntry: 'Ayarlar bölümünde anahtarlarınızı, erişim koşullarını ve uygulama QR bağlantısını yönetin.',
|
||||
@@ -23,11 +29,6 @@ const message = {
|
||||
allowAppBinding: 'Uygulama QR bağlantısına izin ver',
|
||||
bindingDisableHelp:
|
||||
'QR eşleştirmesini devre dışı bırakmak yeni eşleştirmeleri engeller. Eşleştirilmiş cihazlar, anahtar devre dışı bırakılana, iptal edilene veya süresi dolana kadar kullanılmaya devam edebilir.',
|
||||
saveSecret:
|
||||
'Anahtarı şimdi kopyalayıp kaydedin. Kapattıktan sonra normal anahtar yönetimi tam anahtarı yeniden gösteremez.',
|
||||
saved: 'Anahtarı kaydettim',
|
||||
alreadyCreated:
|
||||
'Bu anahtar zaten oluşturuldu ve yeniden gösterilmez. İlk yanıt kaybolduysa iptal edip yeniden oluşturun veya izin veriliyorsa QR bağlantısını kullanın.',
|
||||
uncertain:
|
||||
'İstek sonucu belirsiz. Tekrarları önlemek için aynı bilgilerle yeniden deneyin veya kapatıp yeni anahtar oluşturmadan listeyi kontrol edin.',
|
||||
legacyHelp:
|
||||
|
||||
@@ -2,6 +2,11 @@ import { getFuLocaleMessage } from '@/lang/fu';
|
||||
|
||||
const message = {
|
||||
apiKeyManagement: {
|
||||
reveal: '檢視密鑰',
|
||||
hideSecret: '隱藏密鑰',
|
||||
revealHelp: '請妥善保管密鑰。檢視不會恢復已停用或已過期密鑰的使用權限。',
|
||||
deleteConfirm:
|
||||
'確定刪除「{0}」嗎?密鑰將被銷毀並從列表移除,拒絕後續請求並關閉關聯終端。稽核記錄仍保留,執行中的工作不會取消,此操作無法復原。',
|
||||
title: 'API Key',
|
||||
manage: '管理 API Key',
|
||||
personalEntry: '前往設定管理自己的金鑰、存取條件與 APP 掃碼綁定。',
|
||||
@@ -22,10 +27,6 @@ const message = {
|
||||
futureExpiry: '請選擇晚於目前時間的到期時間。',
|
||||
allowAppBinding: '允許 APP 掃碼綁定',
|
||||
bindingDisableHelp: '關閉掃碼綁定後,將停止接受新的綁定;已綁定裝置可繼續使用,直至金鑰被停用、撤銷或到期。',
|
||||
saveSecret: '請立即複製並儲存金鑰。關閉後,一般金鑰管理無法再次顯示完整金鑰。',
|
||||
saved: '我已儲存金鑰',
|
||||
alreadyCreated:
|
||||
'這把金鑰已建立,無法再次顯示明文。若原回應遺失,請撤銷後重新建立;允許掃碼綁定時,也可透過掃碼交付。',
|
||||
uncertain: '請求結果尚不確定。請保持原設定重試,避免重複建立;或關閉並檢查清單後再建立其他金鑰。',
|
||||
legacyHelp: '舊版 Key 用於相容歷史 API 連線,啟用、停用及重設操作僅對該 Key 生效。',
|
||||
showLegacy: '檢視舊版金鑰',
|
||||
|
||||
@@ -2,6 +2,11 @@ import { getFuLocaleMessage } from '@/lang/fu';
|
||||
|
||||
const message = {
|
||||
apiKeyManagement: {
|
||||
reveal: '查看密钥',
|
||||
hideSecret: '隐藏密钥',
|
||||
revealHelp: '请妥善保管密钥。查看不会恢复已停用或已过期密钥的使用权限。',
|
||||
deleteConfirm:
|
||||
'确定删除“{0}”吗?密钥将被销毁并从列表移除,拒绝后续请求并关闭关联终端。审计记录仍保留,运行中的任务不会取消,此操作不可恢复。',
|
||||
title: 'API Key',
|
||||
manage: '管理 API Key',
|
||||
personalEntry: '前往设置管理自己的密钥、访问条件和 APP 扫码绑定。',
|
||||
@@ -22,10 +27,6 @@ const message = {
|
||||
futureExpiry: '请选择晚于当前时间的到期时间。',
|
||||
allowAppBinding: '允许 APP 扫码绑定',
|
||||
bindingDisableHelp: '关闭扫码绑定后,将停止接受新的绑定;已绑定设备可继续使用,直至密钥被停用、撤销或到期。',
|
||||
saveSecret: '请立即复制并保存密钥。关闭后,普通密钥管理无法再次显示完整密钥。',
|
||||
saved: '我已保存密钥',
|
||||
alreadyCreated:
|
||||
'这把密钥已创建,无法再次展示明文。若原响应丢失,请撤销后重新创建;允许扫码绑定时,也可通过扫码交付。',
|
||||
uncertain: '请求结果尚不确定。请保持原配置重试,避免重复创建;或关闭并检查列表后再创建其他密钥。',
|
||||
legacyHelp: '旧版 Key 用于兼容历史 API 连接,启用、停用和重置操作仅对该 Key 生效。',
|
||||
showLegacy: '查看旧版密钥',
|
||||
|
||||
@@ -357,7 +357,9 @@ const deploymentButtons = [
|
||||
{
|
||||
label: i18n.global.t('commons.button.delete'),
|
||||
permission: true,
|
||||
disabled: (row: Deployment) => operationDisabled(row) && row.status !== 'Uninstalling',
|
||||
disabled: (row: Deployment) =>
|
||||
deleteLoading.value ||
|
||||
(operationDisabled(row) && !['Uninstalling', 'ReStarting', 'Restarting'].includes(row.status)),
|
||||
click: (row: Deployment) => {
|
||||
deleting.value = row;
|
||||
forceDelete.value = false;
|
||||
|
||||
@@ -230,8 +230,13 @@
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('commons.table.status')" min-width="150">
|
||||
<template #default="{ row }">
|
||||
<el-dropdown placement="bottom" :disabled="statusDisabled(row)">
|
||||
<Status v-permission :status="row.status" operate :disabled="statusDisabled(row)" />
|
||||
<el-dropdown placement="bottom" :disabled="statusDisabled(row, 'stop')">
|
||||
<Status
|
||||
v-permission
|
||||
:status="row.status"
|
||||
operate
|
||||
:disabled="statusDisabled(row, 'stop')"
|
||||
/>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item
|
||||
@@ -242,7 +247,8 @@
|
||||
</el-dropdown-item>
|
||||
<el-dropdown-item
|
||||
:disabled="
|
||||
statusDisabled(row) || ['Stopped', 'Exited'].includes(row.status)
|
||||
statusDisabled(row, 'stop') ||
|
||||
['Stopped', 'Exited'].includes(row.status)
|
||||
"
|
||||
@click="operate(row, 'stop')"
|
||||
>
|
||||
@@ -556,7 +562,6 @@ const accountButtons = [
|
||||
{
|
||||
label: i18n.global.t('commons.button.delete'),
|
||||
permission: true,
|
||||
show: (row: AI.AgentAccountItem) => !row.appInstallId || row.provider === 'ollama',
|
||||
click: async (row: AI.AgentAccountItem) => {
|
||||
await ElMessageBox.confirm(
|
||||
i18n.global.t('commons.msg.delete', [row.name]),
|
||||
@@ -570,22 +575,23 @@ const accountButtons = [
|
||||
];
|
||||
const taskRef = ref();
|
||||
const pending = ref('');
|
||||
const operationDisabled = (row: Deployment) =>
|
||||
const operationDisabled = (row: Deployment, operation = '') =>
|
||||
Boolean(pending.value) ||
|
||||
['Installing', 'Starting', 'ReStarting', 'Restarting', 'Rebuilding', 'Waiting', 'Uninstalling'].includes(
|
||||
row.status,
|
||||
);
|
||||
const statusDisabled = (row: Deployment) =>
|
||||
operationDisabled(row) || !hasManagePermissionAccess() || (row.engine === 'ollama' && !hasPermission('app_manage'));
|
||||
['Installing', 'Starting', 'Rebuilding', 'Waiting', 'Uninstalling'].includes(row.status) ||
|
||||
(['ReStarting', 'Restarting'].includes(row.status) && !['stop', 'delete'].includes(operation));
|
||||
const statusDisabled = (row: Deployment, operation = '') =>
|
||||
operationDisabled(row, operation) ||
|
||||
!hasManagePermissionAccess() ||
|
||||
(row.engine === 'ollama' && !hasPermission('app_manage'));
|
||||
const operate = async (row: Deployment, operation: 'start' | 'stop' | 'restart') => {
|
||||
if (statusDisabled(row)) return;
|
||||
if (statusDisabled(row, operation)) return;
|
||||
const node = currentNode.value;
|
||||
await ElMessageBox.confirm(
|
||||
i18n.global.t('app.operatorHelper', [i18n.global.t('commons.operate.' + operation)]),
|
||||
i18n.global.t('commons.operate.' + operation),
|
||||
{ type: 'warning' },
|
||||
);
|
||||
if (node !== currentNode.value || statusDisabled(row)) return;
|
||||
if (node !== currentNode.value || statusDisabled(row, operation)) return;
|
||||
pending.value = `${row.engine}:${row.id}`;
|
||||
try {
|
||||
if (row.engine === 'ollama') {
|
||||
@@ -653,7 +659,7 @@ const deploymentButtons = [
|
||||
label: i18n.global.t('commons.button.delete'),
|
||||
permission: true,
|
||||
show: (row: Deployment) => row.engine === 'ollama' && hasPermission('app_manage'),
|
||||
disabled: operationDisabled,
|
||||
disabled: (row: Deployment) => operationDisabled(row, 'delete'),
|
||||
click: async (row: Deployment) => {
|
||||
const node = currentNode.value;
|
||||
const path = route.fullPath;
|
||||
@@ -683,7 +689,7 @@ const deploymentButtons = [
|
||||
label: i18n.global.t('commons.button.delete'),
|
||||
permission: true,
|
||||
show: (row: Deployment) => row.engine === 'vllm',
|
||||
disabled: (row: Deployment) => operationDisabled(row) && row.status !== 'Uninstalling',
|
||||
disabled: (row: Deployment) => operationDisabled(row, 'delete') && row.status !== 'Uninstalling',
|
||||
click: (row: Deployment) => manageRef.value.open(row, 'delete', true),
|
||||
},
|
||||
];
|
||||
|
||||
@@ -211,7 +211,7 @@ const buttons = [
|
||||
label: i18n.global.t('commons.button.stop'),
|
||||
permission: true,
|
||||
disabled: (row: AI.TensorRTLLM) => {
|
||||
return row.status !== 'Running';
|
||||
return !['Running', 'ReStarting', 'Restarting'].includes(row.status);
|
||||
},
|
||||
click: (row: AI.TensorRTLLM) => {
|
||||
operate(row, 'stop');
|
||||
|
||||
@@ -72,8 +72,14 @@
|
||||
</template>
|
||||
</CardWithHeader>
|
||||
<CardWithHeader :header="$t('commons.table.status')" class="card-interval">
|
||||
<template #header-r>
|
||||
<el-radio-group v-if="hasGPU" v-model="statusView">
|
||||
<el-radio-button value="system">{{ $t('menu.system') }}</el-radio-button>
|
||||
<el-radio-button value="gpu">GPU</el-radio-button>
|
||||
</el-radio-group>
|
||||
</template>
|
||||
<template #body>
|
||||
<SystemStatus ref="statusRef" style="margin-bottom: 33px" />
|
||||
<SystemStatus ref="statusRef" :view="statusView" style="margin-bottom: 33px" />
|
||||
</template>
|
||||
</CardWithHeader>
|
||||
<CardWithHeader
|
||||
@@ -544,6 +550,7 @@ const welcomeOpen = ref();
|
||||
const shadowContainer = ref();
|
||||
|
||||
const chartOption = ref('network');
|
||||
const statusOption = ref(localStorage.getItem('dashboard_status_view') === 'gpu' ? 'gpu' : 'system');
|
||||
let timer: ReturnType<typeof setInterval> | null = null;
|
||||
let initialSampleTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isInit = ref<boolean>(true);
|
||||
@@ -678,6 +685,16 @@ const currentInfo = ref<Dashboard.CurrentInfo>({
|
||||
|
||||
shotTime: new Date(),
|
||||
});
|
||||
const hasGPU = computed(() =>
|
||||
[currentInfo.value.gpuData, currentInfo.value.npuData, currentInfo.value.xpuData].some((items) => items?.length),
|
||||
);
|
||||
const statusView = computed({
|
||||
get: () => (hasGPU.value && statusOption.value === 'gpu' ? 'gpu' : 'system'),
|
||||
set: (value: 'system' | 'gpu') => {
|
||||
statusOption.value = value;
|
||||
localStorage.setItem('dashboard_status_view', value);
|
||||
},
|
||||
});
|
||||
const currentChartInfo = reactive({
|
||||
ioReadBytes: 0,
|
||||
ioWriteBytes: 0,
|
||||
|
||||
@@ -0,0 +1,407 @@
|
||||
<template>
|
||||
<div class="gpu-status">
|
||||
<div class="gpu-summary">
|
||||
<div class="gpu-summary-header">
|
||||
<span class="metric-label">{{ $t('aiTools.gpu.deviceInfo') }}</span>
|
||||
<el-button link type="primary" size="small" @click="$emit('open')">
|
||||
{{ $t('aiTools.gpu.gpu') }}
|
||||
<el-icon><ArrowRight /></el-icon>
|
||||
</el-button>
|
||||
</div>
|
||||
<div class="summary-devices">
|
||||
<div class="device-counts">
|
||||
<strong v-for="group in deviceGroups" :key="group.type">
|
||||
{{ group.type }} × {{ group.count }}
|
||||
</strong>
|
||||
</div>
|
||||
<div class="model-list">
|
||||
<span v-for="model in modelGroups" :key="model.name">{{ model.name }} × {{ model.count }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="summary-memory">
|
||||
<span class="metric-label">{{ $t('aiTools.gpu.memoryTotal') }}</span>
|
||||
<strong>{{ formatMemory(totalMemory) }}</strong>
|
||||
<span class="metric-label">{{ $t('home.used') }} {{ formatMemory(usedMemory) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="gpu-grid">
|
||||
<article v-for="device in visibleDevices" :key="device.key" class="gpu-card">
|
||||
<div class="device-header">
|
||||
<span class="device-id">{{ device.id }}</span>
|
||||
<el-popover :width="360" trigger="click" popper-class="dashboard-gpu-popover">
|
||||
<el-descriptions :title="device.name" :column="1" size="small">
|
||||
<el-descriptions-item
|
||||
v-for="detail in device.details.filter((item) => isAvailable(item[1]))"
|
||||
:key="detail[0]"
|
||||
:label="detail[0]"
|
||||
>
|
||||
{{ detail[1] }}
|
||||
</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
<template #reference>
|
||||
<el-button link type="primary" size="small">{{ $t('commons.button.view') }}</el-button>
|
||||
</template>
|
||||
</el-popover>
|
||||
</div>
|
||||
<div class="device-identity">
|
||||
<h3>{{ device.name }}</h3>
|
||||
<span class="memory-capacity">{{ formatMemory(device.memoryTotal) }}</span>
|
||||
</div>
|
||||
<div class="device-metric">
|
||||
<div class="metric-heading">
|
||||
<span class="metric-label">
|
||||
{{ device.type === 'NPU' ? $t('aiTools.gpu.aiCore') : $t('aiTools.gpu.gpuUtil') }}
|
||||
</span>
|
||||
<strong>{{ device.utilization === null ? '—' : `${device.utilization}%` }}</strong>
|
||||
</div>
|
||||
<el-progress :percentage="device.utilization ?? 0" :show-text="false" :stroke-width="6" />
|
||||
</div>
|
||||
<div class="device-metric">
|
||||
<div class="metric-heading">
|
||||
<span class="metric-label">{{ $t('aiTools.gpu.memoryUsed') }}</span>
|
||||
<strong>
|
||||
{{ formatMemory(device.memoryUsed) }}
|
||||
<span class="metric-total">/ {{ formatMemory(device.memoryTotal) }}</span>
|
||||
</strong>
|
||||
</div>
|
||||
<el-progress
|
||||
:percentage="device.memoryPercent ?? 0"
|
||||
:show-text="false"
|
||||
:stroke-width="6"
|
||||
color="var(--el-color-success)"
|
||||
/>
|
||||
</div>
|
||||
<div class="device-footer">
|
||||
<div>
|
||||
<span class="metric-label">{{ $t('aiTools.gpu.temperature') }}</span>
|
||||
<strong>{{ device.temperature }}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span class="metric-label">{{ $t('aiTools.gpu.powerUsage') }}</span>
|
||||
<strong>{{ device.power }}</strong>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<div v-if="devices.length > 4" class="gpu-expand">
|
||||
<el-button link type="primary" @click="showAll = !showAll">
|
||||
{{ $t(showAll ? 'tabs.hide' : 'tabs.more') }}
|
||||
<el-icon>
|
||||
<ArrowUp v-if="showAll" />
|
||||
<ArrowDown v-else />
|
||||
</el-icon>
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { ArrowDown, ArrowRight, ArrowUp } from '@element-plus/icons-vue';
|
||||
import { Dashboard } from '@/api/interface/dashboard';
|
||||
import { computeSizeForDocker } from '@/utils/size';
|
||||
import i18n from '@/lang';
|
||||
|
||||
const props = defineProps<{ current: Dashboard.CurrentInfo }>();
|
||||
defineEmits<{ open: [] }>();
|
||||
const showAll = ref(false);
|
||||
const t = i18n.global.t;
|
||||
|
||||
const isAvailable = (value?: string) =>
|
||||
Boolean(value?.trim() && !/^(N\/A|NA|NOT SUPPORTED|\[NOT SUPPORTED\])$/i.test(value.trim()));
|
||||
|
||||
const memoryBytes = (value?: string): number | null => {
|
||||
const match = value?.trim().match(/^(\d+(?:\.\d+)?)\s*(B|bytes?|[KMGT]i?B)?$/i);
|
||||
if (!match) return null;
|
||||
const units: Record<string, number> = {
|
||||
'': 1024 ** 2,
|
||||
b: 1,
|
||||
byte: 1,
|
||||
bytes: 1,
|
||||
kb: 1000,
|
||||
kib: 1024,
|
||||
mb: 1000 ** 2,
|
||||
mib: 1024 ** 2,
|
||||
gb: 1000 ** 3,
|
||||
gib: 1024 ** 3,
|
||||
tb: 1000 ** 4,
|
||||
tib: 1024 ** 4,
|
||||
};
|
||||
const bytes = Number(match[1]) * units[(match[2] || '').toLowerCase()];
|
||||
return Number.isFinite(bytes) ? bytes : null;
|
||||
};
|
||||
|
||||
const formatMemory = (value: number | null) => (value === null ? '—' : computeSizeForDocker(value));
|
||||
|
||||
const devices = computed(() =>
|
||||
[
|
||||
...(props.current.gpuData || []).map((item) => ({
|
||||
key: `gpu-${item.type}-${item.busID || item.index}`,
|
||||
type: 'GPU',
|
||||
card: `${item.type}-${item.busID || item.index}`,
|
||||
id: `GPU ${item.index}`,
|
||||
name: item.productName || 'GPU',
|
||||
util: item.gpuUtil,
|
||||
used: item.memUsed || item.memoryUsage?.split('/')[0],
|
||||
total: item.memTotal || item.memoryUsage?.split('/')[1],
|
||||
temperature: item.temperature,
|
||||
power: item.powerUsage || item.powerDraw,
|
||||
details: [
|
||||
[t('aiTools.gpu.busID'), item.busID],
|
||||
[t('aiTools.gpu.fanSpeed'), item.fanSpeed],
|
||||
[t('aiTools.gpu.performanceState'), item.performanceState],
|
||||
[t('aiTools.gpu.powerUsage'), item.powerUsage || item.powerDraw],
|
||||
],
|
||||
})),
|
||||
...(props.current.npuData || []).map((item) => ({
|
||||
key: `npu-${item.npuIndex}-${item.chipIndex}`,
|
||||
type: 'NPU',
|
||||
card: item.npuIndex,
|
||||
id: `NPU ${item.npuIndex} · Chip ${item.chipIndex}`,
|
||||
name: item.productName || 'NPU',
|
||||
util: item.aiCore,
|
||||
used: item.memUsed,
|
||||
total: item.memTotal,
|
||||
temperature: item.temperature,
|
||||
power: item.powerDraw,
|
||||
details: [
|
||||
[t('aiTools.gpu.busID'), item.busID],
|
||||
[t('commons.table.status'), item.health],
|
||||
[t('aiTools.gpu.ddrUsage'), `${item.memoryUsed || '—'} / ${item.memoryTotal || '—'}`],
|
||||
[t('aiTools.gpu.hbmUsage'), `${item.hbmUsed || '—'} / ${item.hbmTotal || '—'}`],
|
||||
[t('aiTools.gpu.hugepagesUsage'), `${item.hugepagesUsed || '—'} / ${item.hugepagesTotal || '—'}`],
|
||||
],
|
||||
})),
|
||||
...(props.current.xpuData || []).map((item) => ({
|
||||
key: `xpu-${item.deviceID}`,
|
||||
type: 'XPU',
|
||||
card: item.deviceID,
|
||||
id: `XPU ${item.deviceID}`,
|
||||
name: item.deviceName || 'XPU',
|
||||
util: item.gpuUtil,
|
||||
used: item.memoryUsed,
|
||||
total: item.memory,
|
||||
temperature: item.temperature,
|
||||
power: item.power,
|
||||
details: [[t('aiTools.gpu.busID'), item.pciBdfAddress]],
|
||||
})),
|
||||
].map((item) => {
|
||||
const memoryUsed = memoryBytes(item.used);
|
||||
const memoryTotal = memoryBytes(item.total);
|
||||
const utilization = item.util?.trim().match(/^(\d+(?:\.\d+)?)\s*%?$/);
|
||||
return {
|
||||
...item,
|
||||
memoryUsed,
|
||||
memoryTotal,
|
||||
utilization: utilization ? Math.min(100, Number(utilization[1])) : null,
|
||||
memoryPercent:
|
||||
memoryUsed !== null && memoryTotal !== null && memoryTotal > 0
|
||||
? Math.min(100, Number(((memoryUsed / memoryTotal) * 100).toFixed(1)))
|
||||
: null,
|
||||
temperature: isAvailable(item.temperature) ? item.temperature.replace(/\s*°?C\b/, ' °C') : '—',
|
||||
power: isAvailable(item.power) ? item.power : '—',
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
const visibleDevices = computed(() => (showAll.value ? devices.value : devices.value.slice(0, 4)));
|
||||
const deviceGroups = computed(() =>
|
||||
['GPU', 'NPU', 'XPU']
|
||||
.map((type) => ({
|
||||
type,
|
||||
count: new Set(devices.value.filter((item) => item.type === type).map((item) => item.card)).size,
|
||||
}))
|
||||
.filter((item) => item.count > 0),
|
||||
);
|
||||
const modelGroups = computed(() => {
|
||||
const models = new Map<string, Set<string>>();
|
||||
for (const device of devices.value) {
|
||||
if (!models.has(device.name)) models.set(device.name, new Set());
|
||||
models.get(device.name)!.add(`${device.type}-${device.card}`);
|
||||
}
|
||||
return Array.from(models, ([name, cards]) => ({ name, count: cards.size }));
|
||||
});
|
||||
const totalMemory = computed(() =>
|
||||
devices.value.some((item) => item.memoryTotal === null)
|
||||
? null
|
||||
: devices.value.reduce((sum, item) => sum + item.memoryTotal!, 0),
|
||||
);
|
||||
const usedMemory = computed(() =>
|
||||
devices.value.some((item) => item.memoryUsed === null)
|
||||
? null
|
||||
: devices.value.reduce((sum, item) => sum + item.memoryUsed!, 0),
|
||||
);
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.gpu-status {
|
||||
container-type: inline-size;
|
||||
grid-column: 1 / -1;
|
||||
min-width: 0;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
.gpu-summary {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: space-between;
|
||||
gap: 12px 24px;
|
||||
padding: 18px 20px;
|
||||
margin-bottom: 16px;
|
||||
border-radius: 8px;
|
||||
background: var(--el-fill-color-light);
|
||||
}
|
||||
.gpu-summary-header {
|
||||
display: flex;
|
||||
flex: 0 0 100%;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
.metric-label {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
.summary-devices {
|
||||
flex: 1 1 200px;
|
||||
min-width: 0;
|
||||
}
|
||||
.device-counts {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 20px;
|
||||
margin: 8px 0;
|
||||
font-size: 22px;
|
||||
}
|
||||
.model-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 16px;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-regular);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.summary-memory {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
padding-left: 24px;
|
||||
border-left: 1px solid var(--el-border-color-lighter);
|
||||
}
|
||||
.summary-memory > strong {
|
||||
font-size: 22px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.gpu-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 14px;
|
||||
}
|
||||
.gpu-card {
|
||||
padding: 16px;
|
||||
border: 1px solid var(--el-border-color-lighter);
|
||||
border-radius: 8px;
|
||||
min-width: 0;
|
||||
background: var(--el-bg-color);
|
||||
}
|
||||
.device-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
.device-id {
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
.device-identity {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px 10px;
|
||||
margin: 10px 0 20px;
|
||||
}
|
||||
.device-identity h3 {
|
||||
flex: 1 1 150px;
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
line-height: 1.5;
|
||||
font-weight: 600;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.memory-capacity {
|
||||
padding: 3px 7px;
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
color: var(--el-color-primary);
|
||||
background: var(--el-color-primary-light-9);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.device-metric + .device-metric {
|
||||
margin-top: 16px;
|
||||
}
|
||||
.metric-heading {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 8px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.metric-heading strong {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.metric-total {
|
||||
font-weight: 400;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
.device-footer {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px 20px;
|
||||
justify-content: space-between;
|
||||
margin-top: 18px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid var(--el-border-color-extra-light);
|
||||
}
|
||||
.device-footer > div {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
.device-footer strong {
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
}
|
||||
.gpu-expand {
|
||||
margin-top: 16px;
|
||||
text-align: center;
|
||||
}
|
||||
@container (max-width: 560px) {
|
||||
.gpu-grid {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
.gpu-summary {
|
||||
padding: 16px;
|
||||
flex-wrap: wrap;
|
||||
gap: 16px;
|
||||
}
|
||||
.summary-memory {
|
||||
padding-left: 0;
|
||||
border-left: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<style lang="scss">
|
||||
.dashboard-gpu-popover.el-popover {
|
||||
max-width: calc(100vw - 24px);
|
||||
max-height: calc(100dvh - 24px);
|
||||
overflow: auto;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
</style>
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div class="custom-row">
|
||||
<el-col :xs="6" :sm="6" :md="3" :lg="3" :xl="3" align="center">
|
||||
<el-col v-if="view === 'system'" :xs="6" :sm="6" :md="3" :lg="3" :xl="3" align="center">
|
||||
<el-popover
|
||||
:hide-after="20"
|
||||
:teleported="false"
|
||||
@@ -52,7 +52,7 @@
|
||||
</el-popover>
|
||||
<span class="input-help">{{ loadStatus(currentInfo.loadUsagePercent) }}</span>
|
||||
</el-col>
|
||||
<el-col :xs="6" :sm="6" :md="3" :lg="3" :xl="3">
|
||||
<el-col v-if="view === 'system'" :xs="6" :sm="6" :md="3" :lg="3" :xl="3">
|
||||
<el-popover
|
||||
:hide-after="20"
|
||||
:teleported="false"
|
||||
@@ -160,7 +160,7 @@
|
||||
</span>
|
||||
</div>
|
||||
</el-col>
|
||||
<el-col :xs="6" :sm="6" :md="3" :lg="3" :xl="3" align="center">
|
||||
<el-col v-if="view === 'system'" :xs="6" :sm="6" :md="3" :lg="3" :xl="3" align="center">
|
||||
<el-popover
|
||||
:hide-after="20"
|
||||
:teleported="false"
|
||||
@@ -254,7 +254,15 @@
|
||||
</span>
|
||||
</el-col>
|
||||
<template v-for="(item, index) of currentInfo.diskData" :key="index">
|
||||
<el-col :xs="6" :sm="6" :md="3" :lg="3" :xl="3" align="center" v-if="isShow('disk', index)">
|
||||
<el-col
|
||||
:xs="6"
|
||||
:sm="6"
|
||||
:md="3"
|
||||
:lg="3"
|
||||
:xl="3"
|
||||
align="center"
|
||||
v-if="view === 'system' && (showMore || index < (currentInfo.diskData.length > 5 ? 4 : 5))"
|
||||
>
|
||||
<el-popover
|
||||
:hide-after="20"
|
||||
:teleported="false"
|
||||
@@ -310,157 +318,16 @@
|
||||
<span class="input-help">{{ computeSize(item.used) }} / {{ computeSize(item.total) }}</span>
|
||||
</el-col>
|
||||
</template>
|
||||
<template v-for="(item, index) of currentInfo.gpuData" :key="index">
|
||||
<el-col :xs="6" :sm="6" :md="3" :lg="3" :xl="3" align="center" v-if="isShow('gpu', index)">
|
||||
<el-popover
|
||||
:hide-after="20"
|
||||
:teleported="false"
|
||||
:width="450"
|
||||
popper-class="dashboard-status-popover"
|
||||
v-if="chartsOption[`gpu${index}`]"
|
||||
>
|
||||
<el-descriptions :title="item.productName" direction="vertical" :column="3" size="small">
|
||||
<el-descriptions-item :label="$t('aiTools.gpu.gpuUtil')">
|
||||
{{ item.gpuUtil }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item :label="$t('aiTools.gpu.temperature')">
|
||||
{{ formatDashboardTemperature(item.temperature) }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item :label="$t('aiTools.gpu.memoryUsage')">
|
||||
{{ item.memoryUsage }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item v-if="hasField(item.busID)" :label="$t('aiTools.gpu.busID')">
|
||||
{{ item.busID }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item v-if="hasField(item.fanSpeed)" :label="$t('aiTools.gpu.fanSpeed')">
|
||||
{{ item.fanSpeed }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item
|
||||
v-if="hasField(item.performanceState)"
|
||||
:label="$t('aiTools.gpu.performanceState')"
|
||||
>
|
||||
{{ item.performanceState }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item v-if="hasField(item.powerDraw)" :label="$t('aiTools.gpu.powerUsage')">
|
||||
{{ item.powerUsage }}
|
||||
</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
<template #reference>
|
||||
<v-charts
|
||||
@click="goGPU()"
|
||||
height="160px"
|
||||
:id="`gpu${index}`"
|
||||
type="pie"
|
||||
:option="chartsOption[`gpu${index}`]"
|
||||
v-if="chartsOption[`gpu${index}`]"
|
||||
/>
|
||||
</template>
|
||||
</el-popover>
|
||||
<el-tooltip :content="item.productName" v-if="item.productName.length > 25">
|
||||
<span class="input-help">{{ item.productName.substring(0, 22) }}...</span>
|
||||
</el-tooltip>
|
||||
<span class="input-help" v-else>{{ item.productName }}</span>
|
||||
</el-col>
|
||||
</template>
|
||||
<template v-for="(item, index) of currentInfo.npuData" :key="index">
|
||||
<el-col :xs="6" :sm="6" :md="3" :lg="3" :xl="3" align="center" v-if="isShow('npu', index)">
|
||||
<el-popover
|
||||
:hide-after="20"
|
||||
:teleported="false"
|
||||
:width="450"
|
||||
popper-class="dashboard-status-popover"
|
||||
v-if="chartsOption[`npu${index}`]"
|
||||
>
|
||||
<el-descriptions :title="item.productName" direction="vertical" :column="3" size="small">
|
||||
<el-descriptions-item v-if="hasField(item.aiCore)" label="AICore(%)">
|
||||
{{ item.aiCore }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item v-if="hasField(item.temperature)" :label="$t('aiTools.gpu.temperature')">
|
||||
{{ formatDashboardTemperature(item.temperature) }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item
|
||||
v-if="hasMetricPair(item.memUsed, item.memTotal)"
|
||||
:label="$t('aiTools.gpu.memoryUsage')"
|
||||
>
|
||||
{{ formatMetricPair(item.memUsed, item.memTotal) }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item v-if="hasField(item.powerDraw)" :label="$t('aiTools.gpu.powerUsage')">
|
||||
{{ item.powerDraw }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item
|
||||
v-if="hasMetricPair(item.hugepagesUsed, item.hugepagesTotal)"
|
||||
label="Hugepages-Usage(page)"
|
||||
>
|
||||
{{ formatMetricPair(item.hugepagesUsed, item.hugepagesTotal) }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item v-if="hasField(item.busID)" :label="$t('aiTools.gpu.busID')">
|
||||
{{ item.busID }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item v-if="hasMetricPair(item.hbmUsed, item.hbmTotal)" label="HBM-Usage">
|
||||
{{ formatMetricPair(item.hbmUsed, item.hbmTotal) }}
|
||||
</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
<template #reference>
|
||||
<v-charts
|
||||
@click="goGPU()"
|
||||
height="160px"
|
||||
:id="`npu${index}`"
|
||||
type="pie"
|
||||
:option="chartsOption[`npu${index}`]"
|
||||
v-if="chartsOption[`npu${index}`]"
|
||||
/>
|
||||
</template>
|
||||
</el-popover>
|
||||
<el-tooltip :content="item.productName" v-if="item.productName.length > 25">
|
||||
<span class="input-help">{{ item.productName.substring(0, 22) }}...</span>
|
||||
</el-tooltip>
|
||||
<span class="input-help" v-else>{{ item.productName }}</span>
|
||||
</el-col>
|
||||
</template>
|
||||
<template v-for="(item, index) of currentInfo.xpuData" :key="index">
|
||||
<el-col :xs="6" :sm="6" :md="3" :lg="3" :xl="3" align="center" v-if="isShow('xpu', index)">
|
||||
<el-popover
|
||||
:hide-after="20"
|
||||
:teleported="false"
|
||||
:width="400"
|
||||
popper-class="dashboard-status-popover"
|
||||
v-if="chartsOption[`xpu${index}`]"
|
||||
>
|
||||
<el-descriptions :title="item.deviceName" direction="vertical" :column="3" size="small">
|
||||
<el-descriptions-item v-if="hasField(item.gpuUtil)" :label="$t('aiTools.gpu.gpuUtil')">
|
||||
{{ item.gpuUtil }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item v-if="hasField(item.temperature)" :label="$t('aiTools.gpu.temperature')">
|
||||
{{ item.temperature }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item :label="$t('aiTools.gpu.memoryUsage')">
|
||||
{{ item.memoryUsed }}/{{ item.memory }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item v-if="hasField(item.pciBdfAddress)" :label="$t('aiTools.gpu.busID')">
|
||||
{{ item.pciBdfAddress }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item v-if="hasField(item.power)" :label="$t('aiTools.gpu.powerUsage')">
|
||||
{{ item.power }}
|
||||
</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
<template #reference>
|
||||
<v-charts
|
||||
@click="goGPU()"
|
||||
height="160px"
|
||||
:id="`xpu${index}`"
|
||||
type="pie"
|
||||
:option="chartsOption[`xpu${index}`]"
|
||||
v-if="chartsOption[`xpu${index}`]"
|
||||
/>
|
||||
</template>
|
||||
</el-popover>
|
||||
<el-tooltip :content="item.deviceName" v-if="item.deviceName.length > 25">
|
||||
<span class="input-help">{{ item.deviceName.substring(0, 22) }}...</span>
|
||||
</el-tooltip>
|
||||
<span class="input-help" v-else>{{ item.deviceName }}</span>
|
||||
</el-col>
|
||||
</template>
|
||||
<el-col :xs="6" :sm="6" :md="3" :lg="3" :xl="3" align="center" v-if="totalCount > 5">
|
||||
<GPUStatus v-if="view === 'gpu'" :current="currentInfo" @open="routerToName('GPU')" />
|
||||
<el-col
|
||||
:xs="6"
|
||||
:sm="6"
|
||||
:md="3"
|
||||
:lg="3"
|
||||
:xl="3"
|
||||
align="center"
|
||||
v-if="view === 'system' && currentInfo.diskData.length > 5"
|
||||
>
|
||||
<el-button v-if="!showMore" link type="primary" @click="changeShowMore(true)" class="buttonClass">
|
||||
{{ $t('tabs.more') }}
|
||||
<el-icon><Bottom /></el-icon>
|
||||
@@ -478,7 +345,8 @@
|
||||
import { Dashboard } from '@/api/interface/dashboard';
|
||||
import { computeSize } from '@/utils/size';
|
||||
import i18n from '@/lang';
|
||||
import { nextTick, onBeforeUnmount, ref } from 'vue';
|
||||
import { nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import GPUStatus from './gpu.vue';
|
||||
import { useMediaQuery } from '@vueuse/core';
|
||||
import { routerToFileWithPath, routerToName } from '@/utils/router';
|
||||
import { stopProcess } from '@/api/modules/process';
|
||||
@@ -486,9 +354,8 @@ import { loadTopCPU, loadTopMem } from '@/api/modules/dashboard';
|
||||
import { MsgSuccess } from '@/utils/message';
|
||||
|
||||
const hasFinePointer = useMediaQuery('(hover: hover) and (pointer: fine)');
|
||||
const props = defineProps<{ view: 'system' | 'gpu' }>();
|
||||
const showMore = ref(false);
|
||||
const totalCount = ref();
|
||||
|
||||
let cpuPopoverTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let memPopoverTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let cpuLoading = false;
|
||||
@@ -606,57 +473,10 @@ const acceptParams = (current: Dashboard.CurrentInfo, base: Dashboard.BaseInfo):
|
||||
data: formatNumber(currentInfo.value.diskData[i].usedPercent),
|
||||
};
|
||||
}
|
||||
currentInfo.value.gpuData = currentInfo.value.gpuData || [];
|
||||
for (let i = 0; i < currentInfo.value.gpuData.length; i++) {
|
||||
chartsOption.value['gpu' + i] = {
|
||||
title: 'GPU-' + currentInfo.value.gpuData[i].index,
|
||||
data: metricPercentage(currentInfo.value.gpuData[i].gpuUtil),
|
||||
};
|
||||
}
|
||||
currentInfo.value.npuData = currentInfo.value.npuData || [];
|
||||
for (let i = 0; i < currentInfo.value.npuData.length; i++) {
|
||||
chartsOption.value['npu' + i] = {
|
||||
title: 'NPU-' + currentInfo.value.npuData[i].npuIndex + '/' + currentInfo.value.npuData[i].chipIndex,
|
||||
data: metricPercentage(currentInfo.value.npuData[i].aiCore),
|
||||
};
|
||||
}
|
||||
currentInfo.value.xpuData = currentInfo.value.xpuData || [];
|
||||
for (let i = 0; i < currentInfo.value.xpuData.length; i++) {
|
||||
chartsOption.value['xpu' + i] = {
|
||||
title: 'XPU-' + currentInfo.value.xpuData[i].deviceID,
|
||||
data: metricPercentage(currentInfo.value.xpuData[i].gpuUtil || currentInfo.value.xpuData[i].memoryUtil),
|
||||
};
|
||||
}
|
||||
totalCount.value =
|
||||
currentInfo.value.diskData.length +
|
||||
currentInfo.value.gpuData.length +
|
||||
currentInfo.value.npuData.length +
|
||||
currentInfo.value.xpuData.length;
|
||||
showMore.value = localStorage.getItem('dashboard_show') === 'more';
|
||||
});
|
||||
};
|
||||
|
||||
const isShow = (val: string, index: number) => {
|
||||
let showCount = totalCount.value < 6 ? 5 : 4;
|
||||
switch (val) {
|
||||
case 'disk':
|
||||
return showMore.value || index < showCount;
|
||||
case 'gpu':
|
||||
let gpuCount = showCount - currentInfo.value.diskData.length;
|
||||
return showMore.value || index < gpuCount;
|
||||
case 'npu':
|
||||
let npuCount = showCount - currentInfo.value.diskData.length - currentInfo.value.gpuData.length;
|
||||
return showMore.value || index < npuCount;
|
||||
case 'xpu':
|
||||
let xpuCount =
|
||||
showCount -
|
||||
currentInfo.value.diskData.length -
|
||||
currentInfo.value.gpuData.length -
|
||||
currentInfo.value.npuData.length;
|
||||
return showMore.value || index < xpuCount;
|
||||
}
|
||||
};
|
||||
|
||||
const changeShowMore = (show: boolean) => {
|
||||
showMore.value = show;
|
||||
localStorage.setItem('dashboard_show', show ? 'more' : 'hide');
|
||||
@@ -690,35 +510,10 @@ function loadStatus(val: number) {
|
||||
return i18n.global.t('home.runJam');
|
||||
}
|
||||
|
||||
const goGPU = () => {
|
||||
routerToName('GPU');
|
||||
};
|
||||
|
||||
function formatNumber(val: number) {
|
||||
return Number(val.toFixed(2));
|
||||
}
|
||||
|
||||
const hasField = (value?: string) => {
|
||||
return typeof value === 'string' && value.trim() !== '';
|
||||
};
|
||||
|
||||
const hasMetricPair = (used?: string, total?: string) => {
|
||||
return hasField(used) || hasField(total);
|
||||
};
|
||||
|
||||
const formatMetricPair = (used?: string, total?: string) => {
|
||||
return `${used || 'N/A'} / ${total || 'N/A'}`;
|
||||
};
|
||||
|
||||
const formatDashboardTemperature = (value: string) => {
|
||||
return value.replace(/\s*°?C\b/, ' °C');
|
||||
};
|
||||
|
||||
const metricPercentage = (value?: string) => {
|
||||
const matched = value?.match(/[0-9]+(?:\.[0-9]+)?/);
|
||||
return matched ? formatNumber(Number.parseFloat(matched[0])) : 0;
|
||||
};
|
||||
|
||||
const normalizeDashboardAccelerators = (current: Dashboard.CurrentInfo) => {
|
||||
const legacyNPUs = (current.gpuData || [])
|
||||
.filter((item) => item.type === 'ascend')
|
||||
@@ -820,6 +615,14 @@ const loadTopMemData = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.view,
|
||||
() => {
|
||||
onCpuPopoverHide();
|
||||
onMemPopoverHide();
|
||||
},
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (cpuPopoverTimer) {
|
||||
clearInterval(Number(cpuPopoverTimer));
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
/>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
<div class="text-xs text-gray-500 break-all">{{ row.keyHint }}</div>
|
||||
<div class="text-xs text-[var(--el-text-color-secondary)] break-all">{{ row.keyHint }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('commons.table.status')" min-width="100" prop="status">
|
||||
@@ -137,26 +137,50 @@
|
||||
v-model="detailVisible"
|
||||
:header="$t('apiKeyManagement.details')"
|
||||
size="min(640px, 100vw)"
|
||||
@close="clearLegacySecret"
|
||||
@close="clearSecret"
|
||||
>
|
||||
<APIKeySummary v-if="detail" :item="detail" />
|
||||
<div v-if="detail?.kind === 'legacy' && detail.status !== 'Revoked'" class="mt-5 flex flex-col gap-3">
|
||||
<el-alert :title="$t('apiKeyManagement.legacyHelp')" type="info" :closable="false" show-icon />
|
||||
<el-space wrap>
|
||||
<el-button type="primary" plain :loading="legacyBusy" @click="revealLegacy">
|
||||
{{ $t('apiKeyManagement.showLegacy') }}
|
||||
<div v-if="detail && detail.status !== 'Revoked'" class="mt-5 flex flex-col gap-3">
|
||||
<el-alert
|
||||
:title="
|
||||
$t(detail.kind === 'legacy' ? 'apiKeyManagement.legacyHelp' : 'apiKeyManagement.revealHelp')
|
||||
"
|
||||
type="info"
|
||||
:closable="false"
|
||||
show-icon
|
||||
/>
|
||||
<el-space v-if="detail.kind === 'legacy'" wrap>
|
||||
<el-button :disabled="secretBusy" @click="resetLegacy">
|
||||
{{ $t('setting.apiKeyReset') }}
|
||||
</el-button>
|
||||
<el-button :disabled="legacyBusy" @click="resetLegacy">{{ $t('setting.apiKeyReset') }}</el-button>
|
||||
</el-space>
|
||||
<el-input
|
||||
v-if="legacySecret"
|
||||
:model-value="legacySecret"
|
||||
:model-value="secret || '********'"
|
||||
:type="secret ? 'text' : 'password'"
|
||||
:aria-label="$t('setting.apiKey')"
|
||||
readonly
|
||||
autocomplete="off"
|
||||
>
|
||||
<template #suffix>
|
||||
<el-button
|
||||
link
|
||||
:icon="secret ? Hide : View"
|
||||
:loading="secretBusy && secretAction === 'reveal'"
|
||||
:disabled="loading || secretBusy"
|
||||
:aria-label="$t(secret ? 'apiKeyManagement.hideSecret' : 'apiKeyManagement.reveal')"
|
||||
:title="$t(secret ? 'apiKeyManagement.hideSecret' : 'apiKeyManagement.reveal')"
|
||||
:aria-pressed="!!secret"
|
||||
@click="toggleSecret"
|
||||
/>
|
||||
</template>
|
||||
<template #append>
|
||||
<CopyButton :content="legacySecret" :is-icon="false" />
|
||||
<el-button
|
||||
:loading="secretBusy && secretAction === 'copy'"
|
||||
:disabled="loading || secretBusy"
|
||||
@click="copySecret"
|
||||
>
|
||||
{{ $t('commons.button.copy') }}
|
||||
</el-button>
|
||||
</template>
|
||||
</el-input>
|
||||
</div>
|
||||
@@ -165,10 +189,11 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onActivated, onBeforeUnmount, onDeactivated, onMounted, reactive, ref } from 'vue';
|
||||
import { computed, onActivated, onBeforeUnmount, onDeactivated, onMounted, reactive, ref, watch } from 'vue';
|
||||
import { ElMessageBox } from 'element-plus';
|
||||
import { Hide, View } from '@element-plus/icons-vue';
|
||||
import type { APIKey } from '@/api/interface/api-key';
|
||||
import { revokeAPIKey, searchAPIKeys, setAPIKeyStatus } from '@/api/modules/api-key';
|
||||
import { deleteAPIKey, revealAPIKey, revokeAPIKey, searchAPIKeys, setAPIKeyStatus } from '@/api/modules/api-key';
|
||||
import { generateApiKey, getUserInfo } from '@/api/modules/auth';
|
||||
import APIKeyEditor from '@/components/api-key-management/editor.vue';
|
||||
import APIKeySummary from '@/components/api-key-management/summary.vue';
|
||||
@@ -176,35 +201,38 @@ import DrawerPro from '@/components/drawer-pro/index.vue';
|
||||
import type { FuTableOperationButton } from '@/components/table/shared';
|
||||
import { isAnyAPIKeyIP, normalizeAPIKeyIPs } from '@/utils/api-key';
|
||||
import { MsgSuccess, MsgWarning } from '@/utils/message';
|
||||
import { copyText } from '@/utils/clipboard';
|
||||
import i18n from '@/lang';
|
||||
import { useGlobalStore } from '@/composables/useGlobalStore';
|
||||
|
||||
const { isMobile } = useGlobalStore();
|
||||
const { isMobile, globalStore } = useGlobalStore();
|
||||
|
||||
const items = ref<APIKey.Item[]>([]);
|
||||
const loading = ref(false);
|
||||
const editor = ref<InstanceType<typeof APIKeyEditor>>();
|
||||
const detail = ref<APIKey.Item>();
|
||||
const detailVisible = ref(false);
|
||||
const legacySecret = ref('');
|
||||
const legacyBusy = ref(false);
|
||||
const secret = ref('');
|
||||
const secretBusy = ref(false);
|
||||
const secretAction = ref<'reveal' | 'copy'>('reveal');
|
||||
const pagination = reactive({ currentPage: 1, pageSize: 20, total: 0 });
|
||||
let searchVersion = 0;
|
||||
let secretRequestVersion = 0;
|
||||
let active = false;
|
||||
let operationPending = false;
|
||||
|
||||
const whitelistEntries = (value: string) =>
|
||||
normalizeAPIKeyIPs(value || '')
|
||||
.split('\n')
|
||||
.filter(Boolean);
|
||||
|
||||
const clearLegacySecret = () => {
|
||||
const clearSecret = () => {
|
||||
secretRequestVersion++;
|
||||
legacySecret.value = '';
|
||||
legacyBusy.value = false;
|
||||
secret.value = '';
|
||||
secretBusy.value = false;
|
||||
};
|
||||
|
||||
const search = async (preserveLegacyRequest?: number) => {
|
||||
const search = async (preserveSecretRequest?: number) => {
|
||||
const ticket = ++searchVersion;
|
||||
loading.value = true;
|
||||
try {
|
||||
@@ -213,7 +241,7 @@ const search = async (preserveLegacyRequest?: number) => {
|
||||
const lastPage = Math.max(1, Math.ceil(response.data.total / pagination.pageSize));
|
||||
if (pagination.currentPage > lastPage) {
|
||||
pagination.currentPage = lastPage;
|
||||
await search(preserveLegacyRequest);
|
||||
await search(preserveSecretRequest);
|
||||
return;
|
||||
}
|
||||
items.value = response.data.items || [];
|
||||
@@ -221,8 +249,8 @@ const search = async (preserveLegacyRequest?: number) => {
|
||||
if (detail.value) {
|
||||
const previousRevision = detail.value.revision;
|
||||
detail.value = items.value.find((entry) => entry.id === detail.value?.id);
|
||||
if (detail.value?.revision !== previousRevision && preserveLegacyRequest !== secretRequestVersion)
|
||||
clearLegacySecret();
|
||||
if (detail.value?.revision !== previousRevision && preserveSecretRequest !== secretRequestVersion)
|
||||
clearSecret();
|
||||
if (!detail.value) detailVisible.value = false;
|
||||
}
|
||||
} finally {
|
||||
@@ -230,7 +258,7 @@ const search = async (preserveLegacyRequest?: number) => {
|
||||
}
|
||||
};
|
||||
const showDetail = (entry: APIKey.Item) => {
|
||||
clearLegacySecret();
|
||||
clearSecret();
|
||||
detail.value = entry;
|
||||
detailVisible.value = true;
|
||||
};
|
||||
@@ -239,15 +267,19 @@ const operate = async (entry: APIKey.Item, action: string) => {
|
||||
editor.value?.open(entry);
|
||||
return;
|
||||
}
|
||||
if (action !== 'status' && action !== 'revoke') return;
|
||||
if (!active || operationPending || !['status', 'revoke', 'delete'].includes(action)) return;
|
||||
operationPending = true;
|
||||
const requestVersion = searchVersion;
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
i18n.global.t(
|
||||
action === 'revoke'
|
||||
? 'apiKeyManagement.revokeConfirm'
|
||||
: entry.status === 'Enable'
|
||||
? 'apiKeyManagement.disableConfirm'
|
||||
: 'apiKeyManagement.enableConfirm',
|
||||
action === 'delete'
|
||||
? 'apiKeyManagement.deleteConfirm'
|
||||
: action === 'revoke'
|
||||
? 'apiKeyManagement.revokeConfirm'
|
||||
: entry.status === 'Enable'
|
||||
? 'apiKeyManagement.disableConfirm'
|
||||
: 'apiKeyManagement.enableConfirm',
|
||||
[entry.name],
|
||||
),
|
||||
i18n.global.t('apiKeyManagement.title'),
|
||||
@@ -258,20 +290,29 @@ const operate = async (entry: APIKey.Item, action: string) => {
|
||||
},
|
||||
);
|
||||
} catch {
|
||||
operationPending = false;
|
||||
return;
|
||||
}
|
||||
if (!active || requestVersion !== searchVersion) {
|
||||
operationPending = false;
|
||||
return;
|
||||
}
|
||||
clearSecret();
|
||||
loading.value = true;
|
||||
try {
|
||||
const reference = { id: entry.id, revision: entry.revision };
|
||||
const response =
|
||||
action === 'revoke'
|
||||
? await revokeAPIKey(reference)
|
||||
: await setAPIKeyStatus({ ...reference, status: entry.status === 'Enable' ? 'Disable' : 'Enable' });
|
||||
clearLegacySecret();
|
||||
action === 'delete'
|
||||
? await deleteAPIKey(reference)
|
||||
: action === 'revoke'
|
||||
? await revokeAPIKey(reference)
|
||||
: await setAPIKeyStatus({ ...reference, status: entry.status === 'Enable' ? 'Disable' : 'Enable' });
|
||||
clearSecret();
|
||||
if (response.data?.terminalClosePending) MsgWarning(i18n.global.t('apiKeyManagement.closePending'));
|
||||
else MsgSuccess(i18n.global.t('commons.msg.operationSuccess'));
|
||||
} finally {
|
||||
await search();
|
||||
operationPending = false;
|
||||
if (active) await search();
|
||||
}
|
||||
};
|
||||
const buttons = computed<FuTableOperationButton<APIKey.Item>[]>(() => [
|
||||
@@ -300,21 +341,59 @@ const buttons = computed<FuTableOperationButton<APIKey.Item>[]>(() => [
|
||||
show: (row) => row.status !== 'Revoked',
|
||||
click: (row) => operate(row, 'revoke'),
|
||||
},
|
||||
{
|
||||
label: i18n.global.t('commons.button.delete'),
|
||||
show: (row) => row.kind === 'apiKey',
|
||||
click: (row) => operate(row, 'delete'),
|
||||
},
|
||||
]);
|
||||
const revealLegacy = async () => {
|
||||
if (legacyBusy.value || !detailVisible.value || detail.value?.kind !== 'legacy') return;
|
||||
const toggleSecret = async () => {
|
||||
if (secretBusy.value || loading.value) return;
|
||||
if (secret.value) clearSecret();
|
||||
else await revealSecret();
|
||||
};
|
||||
const accessSecret = async (action: 'reveal' | 'copy') => {
|
||||
if (secretBusy.value || loading.value || !active || !detailVisible.value || !detail.value) return;
|
||||
if (detail.value.status === 'Revoked') return;
|
||||
const reference = { id: detail.value.id, revision: detail.value.revision };
|
||||
const kind = detail.value.kind;
|
||||
const ticket = ++secretRequestVersion;
|
||||
legacyBusy.value = true;
|
||||
secretAction.value = action;
|
||||
secretBusy.value = true;
|
||||
try {
|
||||
const response = await getUserInfo();
|
||||
if (ticket === secretRequestVersion && detailVisible.value && active && detail.value?.kind === 'legacy')
|
||||
legacySecret.value = response.data.apiKey;
|
||||
if (action === 'copy' && secret.value) {
|
||||
await copyText(secret.value);
|
||||
return;
|
||||
}
|
||||
secret.value = '';
|
||||
const data =
|
||||
kind === 'legacy'
|
||||
? { ...reference, apiKey: (await getUserInfo()).data.apiKey }
|
||||
: (await revealAPIKey(reference)).data;
|
||||
if (
|
||||
ticket === secretRequestVersion &&
|
||||
active &&
|
||||
detailVisible.value &&
|
||||
detail.value?.id === reference.id &&
|
||||
detail.value?.kind === kind &&
|
||||
detail.value?.revision === reference.revision &&
|
||||
data.id === reference.id &&
|
||||
data.revision === reference.revision &&
|
||||
data.apiKey
|
||||
) {
|
||||
if (action === 'copy') await copyText(data.apiKey);
|
||||
else secret.value = data.apiKey;
|
||||
}
|
||||
} catch {
|
||||
if (ticket === secretRequestVersion && active) await search();
|
||||
} finally {
|
||||
if (ticket === secretRequestVersion) legacyBusy.value = false;
|
||||
if (ticket === secretRequestVersion) secretBusy.value = false;
|
||||
}
|
||||
};
|
||||
const revealSecret = () => accessSecret('reveal');
|
||||
const copySecret = () => accessSecret('copy');
|
||||
const resetLegacy = async () => {
|
||||
if (legacyBusy.value || !detailVisible.value || detail.value?.kind !== 'legacy') return;
|
||||
if (secretBusy.value || !detailVisible.value || detail.value?.kind !== 'legacy') return;
|
||||
const ticket = ++secretRequestVersion;
|
||||
try {
|
||||
await ElMessageBox.confirm(i18n.global.t('setting.apiKeyResetHelper'), i18n.global.t('setting.apiKeyReset'));
|
||||
@@ -322,17 +401,18 @@ const resetLegacy = async () => {
|
||||
return;
|
||||
}
|
||||
if (ticket !== secretRequestVersion || !detailVisible.value || !active) return;
|
||||
legacyBusy.value = true;
|
||||
legacySecret.value = '';
|
||||
secretAction.value = 'reveal';
|
||||
secretBusy.value = true;
|
||||
secret.value = '';
|
||||
try {
|
||||
const response = await generateApiKey();
|
||||
await search(ticket);
|
||||
// A reset changes the revision and deliberately clears any older reveal.
|
||||
// Never restore a secret after the original details drawer was closed.
|
||||
if (ticket === secretRequestVersion && detailVisible.value && active && detail.value?.kind === 'legacy')
|
||||
legacySecret.value = response.data;
|
||||
secret.value = response.data;
|
||||
} finally {
|
||||
if (ticket === secretRequestVersion) legacyBusy.value = false;
|
||||
if (ticket === secretRequestVersion) secretBusy.value = false;
|
||||
}
|
||||
};
|
||||
const activate = () => {
|
||||
@@ -343,9 +423,16 @@ const activate = () => {
|
||||
const deactivate = () => {
|
||||
active = false;
|
||||
searchVersion++;
|
||||
clearLegacySecret();
|
||||
clearSecret();
|
||||
detailVisible.value = false;
|
||||
};
|
||||
watch(
|
||||
() => globalStore.isLogin,
|
||||
(loggedIn) => {
|
||||
if (!loggedIn) deactivate();
|
||||
},
|
||||
{ flush: 'sync' },
|
||||
);
|
||||
onMounted(activate);
|
||||
onActivated(activate);
|
||||
onDeactivated(deactivate);
|
||||
|
||||
Reference in New Issue
Block a user