From 45c3fbe8aeb049f03c13e14298a40b87aea5bd87 Mon Sep 17 00:00:00 2001 From: CaIon Date: Sun, 6 Sep 2026 02:03:30 +0800 Subject: [PATCH] fix(security): bind verification proofs to sessions and actions Require single-use operation proofs for passkey enrollment, two-factor setup, and channel key access. Add password and OAuth verification flows, enforce session-bound enrollment, and redact OAuth callback secrets from logs. Validation: affected Go packages pass; frontend typecheck, changed-file lint, and 111 tests pass. Security enrollment regressions pass on SQLite 3.50.4, MySQL 8.0.46, and PostgreSQL 16.15. Full frontend lint has pre-existing errors outside the changed files. --- AGENTS.md | 3 + common/json.go | 14 + common/json_test.go | 42 + controller/channel.go | 23 +- controller/oauth.go | 112 +- controller/passkey.go | 248 ++-- controller/passkey_test.go | 110 +- controller/secure_verification.go | 128 +- controller/security_enrollment_test.go | 1132 +++++++++++++++++ controller/twofa.go | 297 +---- middleware/auth_test.go | 5 +- middleware/logger.go | 9 +- middleware/secure_verification.go | 41 +- model/auth_flow.go | 75 +- model/passkey.go | 29 + model/twofa.go | 103 +- model/twofa_enrollment.go | 114 ++ model/user_authentication_test.go | 30 +- oauth/discord.go | 2 - oauth/generic.go | 4 - oauth/github.go | 2 - oauth/linuxdo.go | 2 - oauth/oidc.go | 2 - router/api-router.go | 15 +- service/auth_token.go | 64 +- service/auth_token_test.go | 42 +- service/oauth_verification.go | 44 + service/passkey/session.go | 61 +- service/security_verification.go | 438 +++++++ service/twofa.go | 66 + web/AGENTS.md | 24 +- web/src/features/auth/api.ts | 26 +- .../auth/components/oauth-callback-screen.tsx | 43 +- web/src/features/auth/constants.ts | 4 +- .../lib/__tests__/oauth-callback-mode.test.ts | 40 +- .../auth/lib/__tests__/oauth-popup.test.ts | 192 +++ .../features/auth/lib/oauth-callback-mode.ts | 56 +- web/src/features/auth/lib/oauth-popup.ts | 183 +++ web/src/features/auth/passkey/api.ts | 101 +- .../passkey/hooks/use-passkey-management.ts | 215 ++-- .../__tests__/verification-api.test.ts | 314 +++++ .../__tests__/verification-flow.test.tsx | 280 ++++ .../features/auth/secure-verification/api.ts | 325 ++--- .../components/secure-verification-dialog.tsx | 346 ++--- .../hooks/use-secure-verification.ts | 402 +++--- .../auth/secure-verification/types.ts | 60 +- web/src/features/channels/api.ts | 6 +- .../drawers/channel-mutate-drawer.tsx | 94 +- .../__tests__/channel-key-disclosure.test.tsx | 153 +++ .../hooks/use-channel-key-disclosure.ts | 94 ++ web/src/features/profile/types.ts | 9 - .../security/__tests__/enrollment.test.tsx | 542 ++++++++ web/src/features/security/api.ts | 47 +- .../security/components/account-bindings.tsx | 272 ++-- .../dialogs/two-fa-setup-dialog.tsx | 139 +- .../security/components/passkey-card.tsx | 166 +-- .../security/components/two-fa-card.tsx | 32 +- .../security/hooks/use-two-fa-setup.ts | 164 +++ web/src/features/security/hooks/use-two-fa.ts | 15 +- web/src/i18n/locales/en.json | 43 + web/src/i18n/locales/fr.json | 43 + web/src/i18n/locales/ja.json | 43 + web/src/i18n/locales/ru.json | 43 + web/src/i18n/locales/vi.json | 43 + web/src/i18n/locales/zh-TW.json | 43 + web/src/i18n/locales/zh.json | 43 + web/src/i18n/static-keys.ts | 4 + web/src/lib/api.ts | 19 - web/src/lib/http-client.ts | 17 +- web/src/lib/oauth.ts | 53 + web/src/lib/passkey.ts | 13 +- web/src/lib/secure-verification.ts | 102 +- web/src/lib/server-error-message.ts | 33 + web/src/routes/oauth/$provider.tsx | 29 +- 74 files changed, 5960 insertions(+), 2212 deletions(-) create mode 100644 controller/security_enrollment_test.go create mode 100644 model/twofa_enrollment.go create mode 100644 service/oauth_verification.go create mode 100644 service/security_verification.go create mode 100644 service/twofa.go create mode 100644 web/src/features/auth/lib/__tests__/oauth-popup.test.ts create mode 100644 web/src/features/auth/lib/oauth-popup.ts create mode 100644 web/src/features/auth/secure-verification/__tests__/verification-api.test.ts create mode 100644 web/src/features/auth/secure-verification/__tests__/verification-flow.test.tsx create mode 100644 web/src/features/channels/hooks/__tests__/channel-key-disclosure.test.tsx create mode 100644 web/src/features/channels/hooks/use-channel-key-disclosure.ts create mode 100644 web/src/features/security/__tests__/enrollment.test.tsx create mode 100644 web/src/features/security/hooks/use-two-fa-setup.ts diff --git a/AGENTS.md b/AGENTS.md index d363804b33..8dd73335da 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -139,6 +139,9 @@ Do NOT directly import or call `encoding/json` in business code. `json.RawMessag ### Frontend Rules +- **Reuse existing UI components first (mandatory):** Before implementing or changing frontend UI, read `web/AGENTS.md` and the project `shadcn-ui` skill, search `web/src/components/` and the relevant feature for existing components, and read matching implementations and call sites. Do not start from custom markup or registry installation without checking the repository first. +- Prefer the project's shared business components over lower-level UI primitives when they cover the use case. Evaluate existing props, composition, and a compatible extension before introducing a replacement. Importing `Button` or `AlertDialog` does not satisfy this rule if the same behavior is already provided by a shared component such as `CopyButton` or `ConfirmDialog`. +- New implementations of common UI behavior require a concrete capability gap: identify the existing candidates and explain why reuse, composition, or a compatible extension is unsuitable in the change summary or PR description. Different text, dimensions, colors, or feature location alone do not justify duplication. Feature components may compose shared components with business data and actions. Follow the reuse workflow and component entry points in `web/AGENTS.md`; generic library or registry guidance does not override this project-specific priority. - Use `bun` as the preferred package manager and script runner for the frontend (`web/`): - `bun install` for dependency installation - `bun run dev` for development server diff --git a/common/json.go b/common/json.go index d7effa36ef..7fcb4fb32f 100644 --- a/common/json.go +++ b/common/json.go @@ -4,6 +4,8 @@ import ( "bytes" "encoding/json" "io" + + "github.com/gin-gonic/gin/binding" ) func Unmarshal(data []byte, v any) error { @@ -18,6 +20,18 @@ func DecodeJson(reader io.Reader, v any) error { return json.NewDecoder(reader).Decode(v) } +// DecodeJsonWithValidation decodes JSON and applies Gin's configured binding-tag +// validator, including binding:"required" and any registered custom validators. +func DecodeJsonWithValidation(reader io.Reader, v any) error { + if err := DecodeJson(reader, v); err != nil { + return err + } + if binding.Validator == nil { + return nil + } + return binding.Validator.ValidateStruct(v) +} + func Marshal(v any) ([]byte, error) { return json.Marshal(v) } diff --git a/common/json_test.go b/common/json_test.go index b599494516..18b2a58856 100644 --- a/common/json_test.go +++ b/common/json_test.go @@ -2,8 +2,11 @@ package common import ( "encoding/json" + "strings" "testing" + "github.com/go-playground/validator/v10" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -41,3 +44,42 @@ func TestJsonRawMessageToString(t *testing.T) { }) } } + +func TestDecodeJsonWithValidation(t *testing.T) { + type request struct { + Code string `json:"code" binding:"required"` + } + for _, test := range []struct { + name, body string + validationError bool + decodeError bool + }{ + {name: "valid", body: `{"code":"123456"}`}, + {name: "missing required field", body: `{}`, validationError: true}, + {name: "empty required field", body: `{"code":""}`, validationError: true}, + {name: "malformed JSON", body: `{"code":`, decodeError: true}, + {name: "wrong field type", body: `{"code":123456}`, decodeError: true}, + } { + t.Run(test.name, func(t *testing.T) { + var value request + err := DecodeJsonWithValidation(strings.NewReader(test.body), &value) + if test.validationError { + var validationErrors validator.ValidationErrors + require.ErrorAs(t, err, &validationErrors) + require.Len(t, validationErrors, 1) + assert.Equal(t, "Code", validationErrors[0].Field()) + assert.Equal(t, "required", validationErrors[0].Tag()) + return + } + if test.decodeError { + require.Error(t, err) + return + } + require.NoError(t, err) + assert.Equal(t, "123456", value.Code) + }) + } + // Existing decoding callers opt into validation explicitly. + var unvalidated request + require.NoError(t, DecodeJson(strings.NewReader(`{}`), &unvalidated)) +} diff --git a/controller/channel.go b/controller/channel.go index 19ddca8e6a..f26ff6a07b 100644 --- a/controller/channel.go +++ b/controller/channel.go @@ -422,19 +422,19 @@ func GetChannel(c *gin.Context) { func GetChannelKey(c *gin.Context) { channelId, err := strconv.Atoi(c.Param("id")) if err != nil { - common.ApiError(c, fmt.Errorf("渠道ID格式错误: %v", err)) + common.ApiErrorMsg(c, "渠道ID格式错误") return } // 获取渠道信息(包含密钥) channel, err := model.GetChannelById(channelId, true) if err != nil { - common.ApiError(c, fmt.Errorf("获取渠道信息失败: %v", err)) + writeSecurityOperationError(c, err) return } if channel == nil { - common.ApiError(c, fmt.Errorf("渠道不存在")) + common.ApiErrorMsg(c, "渠道不存在") return } @@ -454,23 +454,6 @@ func GetChannelKey(c *gin.Context) { }) } -// validateTwoFactorAuth 统一的2FA验证函数 -func validateTwoFactorAuth(twoFA *model.TwoFA, code string) bool { - // 尝试验证TOTP - if cleanCode, err := common.ValidateNumericCode(code); err == nil { - if isValid, _ := twoFA.ValidateTOTPAndUpdateUsage(cleanCode); isValid { - return true - } - } - - // 尝试验证备用码 - if isValid, err := twoFA.ValidateBackupCodeAndUpdateUsage(code); err == nil && isValid { - return true - } - - return false -} - // validateChannel 通用的渠道校验函数 func validateChannel(channel *model.Channel, isAdd bool) error { if channel == nil { diff --git a/controller/oauth.go b/controller/oauth.go index 4d9725c1cc..2e1e65c464 100644 --- a/controller/oauth.go +++ b/controller/oauth.go @@ -1,6 +1,7 @@ package controller import ( + "encoding/json" "errors" "fmt" "net/http" @@ -13,6 +14,7 @@ import ( "github.com/QuantumNous/new-api/middleware" "github.com/QuantumNous/new-api/model" "github.com/QuantumNous/new-api/oauth" + "github.com/QuantumNous/new-api/service" "github.com/gin-gonic/gin" "gorm.io/gorm" ) @@ -20,13 +22,16 @@ import ( const oauthAuthFlowTTL = 10 * time.Minute type oauthStateRequest struct { - Provider string `json:"provider"` - Intent string `json:"intent"` - Aff string `json:"aff,omitempty"` + Provider string `json:"provider"` + Intent string `json:"intent"` + Aff string `json:"aff,omitempty"` + Scope string `json:"scope,omitempty"` + Context json.RawMessage `json:"context,omitempty"` } type oauthFlowPayload struct { - AffiliateCode string `json:"affiliate_code,omitempty"` + AffiliateCode string `json:"affiliate_code,omitempty"` + Verification *service.OAuthVerificationFlow `json:"verification,omitempty"` } // providerParams returns map with Provider key for i18n templates @@ -45,15 +50,17 @@ func GenerateOAuthCode(c *gin.Context) { request.Intent = strings.TrimSpace(request.Intent) request.Aff = strings.TrimSpace(request.Aff) if oauth.GetProvider(request.Provider) == nil || - (request.Intent != model.AuthFlowIntentLogin && request.Intent != model.AuthFlowIntentBind) || + (request.Intent != model.AuthFlowIntentLogin && request.Intent != model.AuthFlowIntentBind && request.Intent != model.AuthFlowIntentVerify) || len(request.Aff) > 32 || - (request.Intent == model.AuthFlowIntentBind && request.Aff != "") { + (request.Intent != model.AuthFlowIntentLogin && request.Aff != "") || + (request.Intent != model.AuthFlowIntentVerify && (request.Scope != "" || len(request.Context) != 0)) { common.ApiErrorI18n(c, i18n.MsgInvalidParams) return } userID := 0 sessionID := "" - if request.Intent == model.AuthFlowIntentBind { + flowPayload := oauthFlowPayload{AffiliateCode: request.Aff} + if request.Intent == model.AuthFlowIntentBind || request.Intent == model.AuthFlowIntentVerify { identity, ok := middleware.GetSessionAuthIdentity(c) if !ok { c.JSON(http.StatusUnauthorized, gin.H{"success": false, "message": "绑定操作需要登录"}) @@ -61,10 +68,18 @@ func GenerateOAuthCode(c *gin.Context) { } userID = identity.UserID sessionID = identity.SessionID + if request.Intent == model.AuthFlowIntentVerify { + verification, err := service.StartOAuthVerification(identity, service.VerificationOperation{Scope: request.Scope, Context: request.Context}, request.Provider) + if err != nil { + writeSecurityOperationError(c, err) + return + } + flowPayload.Verification = verification + } } - payload, err := common.Marshal(oauthFlowPayload{AffiliateCode: request.Aff}) + payload, err := common.Marshal(flowPayload) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } expiresAt := time.Now().Add(oauthAuthFlowTTL) @@ -78,7 +93,7 @@ func GenerateOAuthCode(c *gin.Context) { ExpiresAt: expiresAt, }) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } c.JSON(http.StatusOK, gin.H{ @@ -122,8 +137,8 @@ func HandleOAuth(c *gin.Context) { Provider: providerName, Intent: pendingFlow.Intent, } - // 2. Bind flows are bound to the live dashboard Session that created them. - if pendingFlow.Intent == model.AuthFlowIntentBind { + // Bind and verification callbacks must use the dashboard session that started them. + if pendingFlow.Intent == model.AuthFlowIntentBind || pendingFlow.Intent == model.AuthFlowIntentVerify { identity, ok := middleware.GetSessionAuthIdentity(c) if !ok || identity.UserID != pendingFlow.UserId || identity.SessionID != pendingFlow.SessionId { c.JSON(http.StatusForbidden, gin.H{ @@ -162,11 +177,6 @@ func HandleOAuth(c *gin.Context) { }) return } - if pendingFlow.Intent == model.AuthFlowIntentBind { - handleOAuthBind(c, provider, pendingFlow, state) - return - } - // 5. Exchange code for token code := c.Query("code") token, err := provider.ExchangeToken(c.Request.Context(), code, c) @@ -187,10 +197,37 @@ func HandleOAuth(c *gin.Context) { return } + switch flow.Intent { + case model.AuthFlowIntentLogin: + handleOAuthLogin(c, provider, oauthUser, flow) + case model.AuthFlowIntentBind: + handleOAuthBind(c, provider, oauthUser, flow) + case model.AuthFlowIntentVerify: + handleOAuthVerification(c, providerName, oauthUser, flow) + } +} + +func handleOAuthVerification(c *gin.Context, provider string, oauthUser *oauth.OAuthUser, flow *model.AuthFlow) { + var payload oauthFlowPayload + if err := common.UnmarshalJsonStr(flow.Payload, &payload); err != nil { + writeSecurityOperationError(c, err) + return + } + identity, _ := middleware.GetSessionAuthIdentity(c) + proof, err := service.FinishOAuthVerification(identity, provider, oauthUser.ProviderUserID, payload.Verification) + if err != nil { + writeSecurityOperationError(c, err) + return + } + recordUserSecurityAudit(c, identity.UserID, "user.security_verify", map[string]interface{}{"method": proof.Method, "scope": proof.Scope, "provider": provider}) + common.ApiSuccess(c, proof) +} + +func handleOAuthLogin(c *gin.Context, provider oauth.Provider, oauthUser *oauth.OAuthUser, flow *model.AuthFlow) { // 7. Find or create user var payload oauthFlowPayload if err := common.UnmarshalJsonStr(flow.Payload, &payload); err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } user, err := findOrCreateOAuthUser(c, provider, oauthUser, payload.AffiliateCode) @@ -207,7 +244,7 @@ func HandleOAuth(c *gin.Context) { case *OAuthEmailAlreadyTakenError: common.ApiErrorI18n(c, i18n.MsgUserEmailAlreadyTaken) default: - common.ApiError(c, err) + writeSecurityOperationError(c, err) } return } @@ -223,22 +260,7 @@ func HandleOAuth(c *gin.Context) { } // handleOAuthBind handles binding OAuth account to existing user -func handleOAuthBind(c *gin.Context, provider oauth.Provider, pendingFlow *model.AuthFlow, flowToken string) { - // Exchange code for token - code := c.Query("code") - token, err := provider.ExchangeToken(c.Request.Context(), code, c) - if err != nil { - handleOAuthError(c, err) - return - } - - // Get user info - oauthUser, err := provider.GetUserInfo(c.Request.Context(), token) - if err != nil { - handleOAuthError(c, err) - return - } - +func handleOAuthBind(c *gin.Context, provider oauth.Provider, oauthUser *oauth.OAuthUser, flow *model.AuthFlow) { // Check if this OAuth account is already bound (check both new ID and legacy ID) if provider.IsUserIDTaken(oauthUser.ProviderUserID) { common.ApiErrorI18n(c, i18n.MsgOAuthAlreadyBound, providerParams(provider.GetName())) @@ -252,25 +274,15 @@ func handleOAuthBind(c *gin.Context, provider oauth.Provider, pendingFlow *model } } - if _, err := model.ConsumeAuthFlow(flowToken, model.AuthFlowMatch{ - Purpose: model.AuthFlowPurposeOAuth, - Provider: pendingFlow.Provider, - Intent: model.AuthFlowIntentBind, - UserId: pendingFlow.UserId, - SessionId: pendingFlow.SessionId, - }); err != nil { - c.JSON(http.StatusForbidden, gin.H{"success": false, "message": i18n.T(c, i18n.MsgOAuthStateInvalid)}) - return - } - - userId := pendingFlow.UserId + userId := flow.UserId + var err error // Handle binding based on provider type if genericProvider, ok := provider.(*oauth.GenericOAuthProvider); ok { // Custom provider: use user_oauth_bindings table err = model.UpdateUserOAuthBinding(userId, genericProvider.GetProviderId(), oauthUser.ProviderUserID) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } } else { @@ -278,7 +290,7 @@ func handleOAuthBind(c *gin.Context, provider oauth.Provider, pendingFlow *model // role/status/group 一并写回,覆盖并发发生的封禁、降权或分组变更。 err = model.UpdateUserBindColumn(userId, provider.ProviderUserIDColumn(), oauthUser.ProviderUserID) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } } @@ -461,6 +473,6 @@ func handleOAuthError(c *gin.Context, err error) { case *oauth.TrustLevelError: common.ApiErrorI18n(c, i18n.MsgOAuthTrustLevelLow) default: - common.ApiError(c, err) + writeSecurityOperationError(c, err) } } diff --git a/controller/passkey.go b/controller/passkey.go index 198df804b8..a130aab9da 100644 --- a/controller/passkey.go +++ b/controller/passkey.go @@ -20,19 +20,14 @@ import ( webauthnlib "github.com/go-webauthn/webauthn/webauthn" ) -const ( - securityProofScopeChannelKeyRead = "channel.key.read" - securityProofScopePasskeyRegister = "passkey.register" - securityProofScopePasskeyDelete = "passkey.delete" -) - type passkeyFinishRequest struct { FlowToken string `json:"flow_token"` Credential json.RawMessage `json:"credential"` } type passkeyVerifyBeginRequest struct { - Scope string `json:"scope"` + Scope string `json:"scope"` + Context json.RawMessage `json:"context,omitempty"` } func parsePasskeyFinishRequest(c *gin.Context) (*passkeyFinishRequest, error) { @@ -57,20 +52,18 @@ func PasskeyRegisterBegin(c *gin.Context) { user, err := getAuthenticatedUser(c) if err != nil { - c.JSON(http.StatusUnauthorized, gin.H{ - "success": false, - "message": err.Error(), - }) + writeSecurityOperationError(c, err) return } - if !requirePasskeyRegistrationVerification(c, user.Id) { + authorization := middleware.RequireSecurityProof(c, service.VerificationOperation{Scope: service.VerificationScopePasskeyRegister}) + if authorization == nil { return } credential, err := model.GetPasskeyByUserID(user.Id) if err != nil && !errors.Is(err, model.ErrPasskeyNotFound) { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } if errors.Is(err, model.ErrPasskeyNotFound) { @@ -79,7 +72,7 @@ func PasskeyRegisterBegin(c *gin.Context) { wa, err := passkeysvc.BuildWebAuthn(c.Request) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } @@ -92,24 +85,22 @@ func PasskeyRegisterBegin(c *gin.Context) { creation, sessionData, err := wa.BeginRegistration(waUser, options...) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } identity, ok := middleware.GetSessionAuthIdentity(c) if !ok { - common.ApiError(c, errors.New("当前认证方式不支持安全验证")) + common.ApiErrorMsg(c, "当前认证方式不支持安全验证") return } flowToken, expiresAt, err := passkeysvc.CreateSessionDataFlow( model.AuthFlowPurposePasskeyRegister, - user.Id, - identity.SessionID, - securityProofScopePasskeyRegister, + passkeysvc.FlowSecurity{AuthSessionIdentity: identity, Scope: authorization.Scope, ContextHash: authorization.ContextHash, Authorization: authorization}, sessionData, ) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } @@ -135,36 +126,29 @@ func PasskeyRegisterFinish(c *gin.Context) { user, err := getAuthenticatedUser(c) if err != nil { - c.JSON(http.StatusUnauthorized, gin.H{ - "success": false, - "message": err.Error(), - }) + writeSecurityOperationError(c, err) return } - if !requirePasskeyRegistrationVerification(c, user.Id) { - return - } - request, err := parsePasskeyFinishRequest(c) if err != nil { - common.ApiError(c, err) + common.ApiErrorMsg(c, "无效的 Passkey 验证请求") return } parsedCredential, err := protocol.ParseCredentialCreationResponseBytes(request.Credential) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } wa, err := passkeysvc.BuildWebAuthn(c.Request) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } credentialRecord, err := model.GetPasskeyByUserID(user.Id) if err != nil && !errors.Is(err, model.ErrPasskeyNotFound) { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } if errors.Is(err, model.ErrPasskeyNotFound) { @@ -173,24 +157,27 @@ func PasskeyRegisterFinish(c *gin.Context) { identity, ok := middleware.GetSessionAuthIdentity(c) if !ok { - common.ApiError(c, errors.New("当前认证方式不支持安全验证")) + common.ApiErrorMsg(c, "当前认证方式不支持安全验证") return } - sessionData, _, err := passkeysvc.PopSessionDataFlow( + sessionData, security, err := passkeysvc.PopSessionDataFlow( request.FlowToken, model.AuthFlowPurposePasskeyRegister, - user.Id, - identity.SessionID, + identity, ) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) + return + } + if err := service.ValidateFlowAuthorization(identity, service.VerificationOperation{Scope: service.VerificationScopePasskeyRegister}, security.Authorization); err != nil { + writeSecurityOperationError(c, err) return } waUser := passkeysvc.NewWebAuthnUser(user, credentialRecord) credential, err := wa.CreateCredential(waUser, *sessionData, parsedCredential) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } @@ -200,13 +187,13 @@ func PasskeyRegisterFinish(c *gin.Context) { return } - if err := model.UpsertPasskeyCredentialWithAuthVersion(passkeyCredential); err != nil { - common.ApiError(c, err) + if err := model.RegisterPasskeyForSession(identity, passkeyCredential); err != nil { + writeSecurityOperationError(c, err) return } bundle, err := service.AdvanceCurrentSessionToUserVersion(identity, "passkey_registered") if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } @@ -221,29 +208,26 @@ func PasskeyRegisterFinish(c *gin.Context) { func PasskeyDelete(c *gin.Context) { user, err := getAuthenticatedUser(c) if err != nil { - c.JSON(http.StatusUnauthorized, gin.H{ - "success": false, - "message": err.Error(), - }) + writeSecurityOperationError(c, err) return } - if !requirePasskeyDeleteVerification(c, user.Id) { + if middleware.RequireSecurityProof(c, service.VerificationOperation{Scope: service.VerificationScopePasskeyDelete}) == nil { return } identity, ok := middleware.GetSessionAuthIdentity(c) if !ok { - common.ApiError(c, errors.New("当前认证方式不支持安全验证")) + common.ApiErrorMsg(c, "当前认证方式不支持安全验证") return } - if err := model.DeletePasskeyByUserIDWithAuthVersion(user.Id); err != nil { - common.ApiError(c, err) + if err := model.DeletePasskeyForSession(identity); err != nil { + writeSecurityOperationError(c, err) return } bundle, err := service.AdvanceCurrentSessionToUserVersion(identity, "passkey_deleted") if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } @@ -258,10 +242,7 @@ func PasskeyDelete(c *gin.Context) { func PasskeyStatus(c *gin.Context) { user, err := getAuthenticatedUser(c) if err != nil { - c.JSON(http.StatusUnauthorized, gin.H{ - "success": false, - "message": err.Error(), - }) + writeSecurityOperationError(c, err) return } @@ -277,7 +258,7 @@ func PasskeyStatus(c *gin.Context) { return } if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } @@ -304,25 +285,23 @@ func PasskeyLoginBegin(c *gin.Context) { wa, err := passkeysvc.BuildWebAuthn(c.Request) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } assertion, sessionData, err := wa.BeginDiscoverableLogin() if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } flowToken, expiresAt, err := passkeysvc.CreateSessionDataFlow( model.AuthFlowPurposePasskeyLogin, - 0, - "", - "", + passkeysvc.FlowSecurity{}, sessionData, ) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } @@ -348,29 +327,28 @@ func PasskeyLoginFinish(c *gin.Context) { request, err := parsePasskeyFinishRequest(c) if err != nil { - common.ApiError(c, err) + common.ApiErrorMsg(c, "无效的 Passkey 验证请求") return } parsedCredential, err := protocol.ParseCredentialRequestResponseBytes(request.Credential) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } wa, err := passkeysvc.BuildWebAuthn(c.Request) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } sessionData, _, err := passkeysvc.PopSessionDataFlow( request.FlowToken, model.AuthFlowPurposePasskeyLogin, - 0, - "", + service.AuthIdentity{}, ) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } @@ -388,7 +366,7 @@ func PasskeyLoginFinish(c *gin.Context) { } if user.Status != common.UserStatusEnabled { - return nil, errors.New("该用户已被禁用") + return nil, model.ErrUserSessionInactive } if len(userHandle) > 0 { @@ -406,7 +384,7 @@ func PasskeyLoginFinish(c *gin.Context) { waUser, credential, err := wa.ValidatePasskeyLogin(handler, *sessionData, parsedCredential) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } @@ -428,7 +406,7 @@ func PasskeyLoginFinish(c *gin.Context) { } if err := model.UpdatePasskeyAssertionState(modelUser.Id, credential, time.Now()); err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } @@ -444,7 +422,7 @@ func AdminResetPasskey(c *gin.Context) { user := &model.User{Id: id} if err := user.FillUserById(); err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } myRole := c.GetInt("role") @@ -461,16 +439,16 @@ func AdminResetPasskey(c *gin.Context) { }) return } - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } if err := model.DeletePasskeyByUserIDWithAuthVersion(user.Id); err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } if _, err := model.RevokeAllUserSessions(user.Id, "admin_passkey_reset"); err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } @@ -495,19 +473,26 @@ func PasskeyVerifyBegin(c *gin.Context) { user, err := getAuthenticatedUser(c) if err != nil { - c.JSON(http.StatusUnauthorized, gin.H{ - "success": false, - "message": err.Error(), - }) + writeSecurityOperationError(c, err) return } var request passkeyVerifyBeginRequest if err := common.DecodeJson(c.Request.Body, &request); err != nil { - common.ApiError(c, errors.New("无效的 Passkey 验证请求")) + common.ApiErrorMsg(c, "无效的 Passkey 验证请求") return } - if !isAllowedSecurityProofScope(request.Scope) { - common.ApiError(c, errors.New("不支持的安全验证范围")) + binding, err := service.BindVerificationOperation(service.VerificationOperation{Scope: request.Scope, Context: request.Context}) + if err != nil { + writeSecurityOperationError(c, err) + return + } + identity, ok := middleware.GetSessionAuthIdentity(c) + if !ok { + writeSecurityOperationError(c, service.ErrAuthTokenInvalid) + return + } + if _, err := service.RequireVerificationMethod(identity, request.Scope, service.VerificationMethodPasskey); err != nil { + writeSecurityOperationError(c, err) return } @@ -522,31 +507,24 @@ func PasskeyVerifyBegin(c *gin.Context) { wa, err := passkeysvc.BuildWebAuthn(c.Request) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } waUser := passkeysvc.NewWebAuthnUser(user, credential) assertion, sessionData, err := wa.BeginLogin(waUser) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } - identity, ok := middleware.GetSessionAuthIdentity(c) - if !ok { - common.ApiError(c, errors.New("当前认证方式不支持安全验证")) - return - } flowToken, expiresAt, err := passkeysvc.CreateSessionDataFlow( model.AuthFlowPurposePasskeyStepUp, - user.Id, - identity.SessionID, - request.Scope, + passkeysvc.FlowSecurity{AuthSessionIdentity: identity, Scope: binding.Scope, ContextHash: binding.ContextHash}, sessionData, ) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } @@ -572,27 +550,24 @@ func PasskeyVerifyFinish(c *gin.Context) { user, err := getAuthenticatedUser(c) if err != nil { - c.JSON(http.StatusUnauthorized, gin.H{ - "success": false, - "message": err.Error(), - }) + writeSecurityOperationError(c, err) return } request, err := parsePasskeyFinishRequest(c) if err != nil { - common.ApiError(c, err) + common.ApiErrorMsg(c, "无效的 Passkey 验证请求") return } parsedCredential, err := protocol.ParseCredentialRequestResponseBytes(request.Credential) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } wa, err := passkeysvc.BuildWebAuthn(c.Request) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } @@ -607,99 +582,52 @@ func PasskeyVerifyFinish(c *gin.Context) { identity, ok := middleware.GetSessionAuthIdentity(c) if !ok { - common.ApiError(c, errors.New("当前认证方式不支持安全验证")) + common.ApiErrorMsg(c, "当前认证方式不支持安全验证") return } - sessionData, scope, err := passkeysvc.PopSessionDataFlow( + sessionData, security, err := passkeysvc.PopSessionDataFlow( request.FlowToken, model.AuthFlowPurposePasskeyStepUp, - user.Id, - identity.SessionID, + identity, ) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } waUser := passkeysvc.NewWebAuthnUser(user, credential) validatedCredential, err := wa.ValidateLogin(waUser, *sessionData, parsedCredential) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } if err := model.UpdatePasskeyAssertionState(user.Id, validatedCredential, time.Now()); err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } - proofToken, proofExpiresAt, err := service.IssueSecurityProof(identity, secureVerificationMethodPasskey, []string{scope}) + proof, err := service.CompleteSecurityVerification(identity, service.VerificationBinding{Scope: security.Scope, ContextHash: security.ContextHash}, service.VerificationMethodPasskey) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } - c.JSON(http.StatusOK, gin.H{ - "success": true, - "message": "Passkey 验证成功", - "data": gin.H{ - "proof_token": proofToken, - "expires_at": proofExpiresAt, - "method": secureVerificationMethodPasskey, - "scope": scope, - }, - }) + recordUserSecurityAudit(c, user.Id, "user.security_verify", map[string]interface{}{"method": proof.Method, "scope": proof.Scope}) + common.ApiSuccess(c, proof) } func getAuthenticatedUser(c *gin.Context) (*model.User, error) { id := c.GetInt("id") if id == 0 { - return nil, errors.New("未登录") + return nil, service.ErrAuthTokenInvalid } - user := &model.User{Id: id} - if err := user.FillUserById(); err != nil { + user, err := model.GetUserById(id, false) + if err != nil { return nil, err } if user.Status != common.UserStatusEnabled { - return nil, errors.New("该用户已被禁用") + return nil, model.ErrUserSessionInactive } return user, nil } - -func requirePasskeyRegistrationVerification(c *gin.Context, userID int) bool { - twoFA, err := model.GetTwoFAByUserId(userID) - if err != nil { - common.ApiError(c, err) - return false - } - if twoFA == nil || !twoFA.IsEnabled { - return true - } - return middleware.RequireSecurityProof(c, securityProofScopePasskeyRegister, []string{secureVerificationMethod2FA}) -} - -func requirePasskeyDeleteVerification(c *gin.Context, userID int) bool { - twoFA, err := model.GetTwoFAByUserId(userID) - if err != nil { - common.ApiError(c, err) - return false - } - if twoFA != nil && twoFA.IsEnabled { - return middleware.RequireSecurityProof(c, securityProofScopePasskeyDelete, []string{secureVerificationMethod2FA}) - } - - _, err = model.GetPasskeyByUserID(userID) - if err != nil { - if errors.Is(err, model.ErrPasskeyNotFound) { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "message": "该用户尚未绑定 Passkey", - }) - return false - } - common.ApiError(c, err) - return false - } - - return middleware.RequireSecurityProof(c, securityProofScopePasskeyDelete, []string{secureVerificationMethodPasskey}) -} diff --git a/controller/passkey_test.go b/controller/passkey_test.go index 84cdbf4ecb..f1150f7ec3 100644 --- a/controller/passkey_test.go +++ b/controller/passkey_test.go @@ -1,7 +1,9 @@ package controller import ( - "fmt" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" "net/http" "net/http/httptest" "strings" @@ -13,10 +15,8 @@ import ( "github.com/QuantumNous/new-api/service" "github.com/QuantumNous/new-api/setting/system_setting" "github.com/gin-gonic/gin" - "github.com/glebarez/sqlite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "gorm.io/gorm" ) type passkeyTestBody struct { @@ -43,88 +43,30 @@ func TestParsePasskeyFinishRequestDoesNotRewriteRequestBody(t *testing.T) { assert.Equal(t, int64(len(bodyText)), context.Request.ContentLength) } -func TestPasskeyRegisterFinishRejectsMissingOrWrongProofWithoutConsumingFlow(t *testing.T) { - previousDB := model.DB - previousType := common.MainDatabaseType() - previousRedis := common.RedisEnabled - previousSecret := common.SessionSecret - settings := system_setting.GetPasskeySettings() - previousSettings := *settings - dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared", strings.ReplaceAll(t.Name(), "/", "_")) - db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{}) +func TestPasskeyRegisterFinishRejectsUnapprovedFlowWithoutConsumingIt(t *testing.T) { + _, identity := setupSecurityEnrollmentTest(t) + system_setting.GetPasskeySettings().UserVerification = "required" + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) require.NoError(t, err) - require.NoError(t, db.AutoMigrate(&model.User{}, &model.TwoFA{}, &model.AuthFlow{})) - model.DB = db - common.SetMainDatabaseType(common.DatabaseTypeSQLite) - common.RedisEnabled = false - common.SessionSecret = "passkey-register-proof-test-secret" - *settings = system_setting.PasskeySettings{Enabled: true} - t.Cleanup(func() { - model.DB = previousDB - common.SetMainDatabaseType(previousType) - common.RedisEnabled = previousRedis - common.SessionSecret = previousSecret - *settings = previousSettings - sqlDB, dbErr := db.DB() - if dbErr == nil { - _ = sqlDB.Close() - } + payload, err := common.Marshal(map[string]any{"scope": service.VerificationScopePasskeyRegister}) + require.NoError(t, err) + token, _, err := model.CreateAuthFlow(model.AuthFlowCreate{ + Purpose: model.AuthFlowPurposePasskeyRegister, UserId: identity.UserID, SessionId: identity.SessionID, + Payload: string(payload), ExpiresAt: time.Now().Add(time.Minute), }) - - user := &model.User{ - Username: "passkey-proof-user", Password: "password-placeholder", Role: common.RoleCommonUser, - Status: common.UserStatusEnabled, Group: "default", AuthVersion: 1, - } - require.NoError(t, db.Create(user).Error) - require.NoError(t, db.Create(&model.TwoFA{UserId: user.Id, Secret: "totp-secret", IsEnabled: true}).Error) - identity := service.AuthIdentity{ - UserID: user.Id, SessionID: "passkey-proof-session", UserAuthVersion: 1, SessionVersion: 1, - } - wrongScopeProof, _, err := service.IssueSecurityProof(identity, secureVerificationMethod2FA, []string{securityProofScopePasskeyDelete}) require.NoError(t, err) - - tests := []struct { - name string - proof string - expectedCode string - }{ - {name: "missing proof", expectedCode: "SECURITY_PROOF_REQUIRED"}, - {name: "wrong scope proof", proof: wrongScopeProof, expectedCode: "SECURITY_PROOF_SCOPE_MISMATCH"}, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - flowToken, _, err := model.CreateAuthFlow(model.AuthFlowCreate{ - Purpose: model.AuthFlowPurposePasskeyRegister, UserId: user.Id, SessionId: identity.SessionID, - Payload: `{}`, ExpiresAt: time.Now().Add(time.Minute), - }) - require.NoError(t, err) - body := fmt.Sprintf(`{"flow_token":%q,"credential":{}}`, flowToken) - request := httptest.NewRequest(http.MethodPost, "/api/user/passkey/register/finish", strings.NewReader(body)) - request.Header.Set("Content-Type", "application/json") - if test.proof != "" { - request.Header.Set("X-Security-Proof", test.proof) - } - response := httptest.NewRecorder() - context, _ := gin.CreateTestContext(response) - context.Request = request - context.Set("id", identity.UserID) - context.Set("session_id", identity.SessionID) - context.Set("auth_version", identity.UserAuthVersion) - context.Set("session_version", identity.SessionVersion) - - PasskeyRegisterFinish(context) - - assert.Equal(t, http.StatusForbidden, response.Code) - var responseBody struct { - Code string `json:"code"` - } - require.NoError(t, common.Unmarshal(response.Body.Bytes(), &responseBody)) - assert.Equal(t, test.expectedCode, responseBody.Code) - flow, err := model.GetAuthFlow(flowToken, model.AuthFlowMatch{ - Purpose: model.AuthFlowPurposePasskeyRegister, UserId: user.Id, SessionId: identity.SessionID, - }) - require.NoError(t, err) - assert.Nil(t, flow.ConsumedAt) - }) - } + body, err := common.Marshal(passkeyFinishRequest{ + FlowToken: token, Credential: securityPasskeyResponse(t, key, "test-challenge", true, 0), + }) + require.NoError(t, err) + response := securityEnrollmentRequest("POST", "/api/user/passkey/register/finish", string(body), "", identity, PasskeyRegisterFinish) + var result securityEnrollmentResponse + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result)) + assert.False(t, result.Success) + assert.Equal(t, "AUTH_FLOW_INVALID", result.Code) + _, err = model.GetPasskeyByUserID(identity.UserID) + assert.ErrorIs(t, err, model.ErrPasskeyNotFound) + flow, err := model.GetAuthFlow(token, model.AuthFlowMatch{Purpose: model.AuthFlowPurposePasskeyRegister}) + require.NoError(t, err) + assert.Nil(t, flow.ConsumedAt) } diff --git a/controller/secure_verification.go b/controller/secure_verification.go index 4095225073..54a1396822 100644 --- a/controller/secure_verification.go +++ b/controller/secure_verification.go @@ -2,26 +2,79 @@ package controller import ( "errors" - "fmt" "net/http" - "strings" "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/middleware" "github.com/QuantumNous/new-api/model" "github.com/QuantumNous/new-api/service" "github.com/gin-gonic/gin" + "github.com/go-webauthn/webauthn/protocol" ) -const ( - secureVerificationMethod2FA = "2fa" - secureVerificationMethodPasskey = "passkey" -) +func GetVerificationMethods(c *gin.Context) { + identity, ok := middleware.GetSessionAuthIdentity(c) + if !ok { + c.JSON(http.StatusUnauthorized, gin.H{"success": false, "message": "当前认证方式不支持安全验证"}) + return + } + requirements, err := service.GetVerificationRequirements(identity, c.Query("scope")) + if err != nil { + writeSecurityOperationError(c, err) + return + } + common.ApiSuccess(c, requirements) +} -type UniversalVerifyRequest struct { - Method string `json:"method"` - Code string `json:"code,omitempty"` - Scope string `json:"scope"` +// writeSecurityOperationError only exposes known, fixed business messages. +// Unexpected errors retain their cause for the existing server-side auth logger. +func writeSecurityOperationError(c *gin.Context, err error) { + status := http.StatusOK + var code, message string + var protocolError *protocol.Error + switch { + case errors.Is(err, service.ErrVerificationContextInvalid): + status = http.StatusBadRequest + code, message = "SECURITY_CONTEXT_INVALID", service.ErrVerificationContextInvalid.Error() + case errors.Is(err, service.ErrVerificationForbidden): + status = http.StatusForbidden + code, message = "SECURITY_ACTION_FORBIDDEN", service.ErrVerificationForbidden.Error() + case errors.Is(err, service.ErrVerificationFailed), errors.As(err, &protocolError): + code, message = "SECURITY_VERIFICATION_FAILED", service.ErrVerificationFailed.Error() + case errors.Is(err, service.ErrVerificationLocked): + code, message = "SECURITY_VERIFICATION_LOCKED", service.ErrVerificationLocked.Error() + case errors.Is(err, service.ErrVerificationUnavailable): + code, message = "SECURITY_METHOD_UNAVAILABLE", service.ErrVerificationUnavailable.Error() + case errors.Is(err, service.ErrVerificationFlowRequired): + status = http.StatusBadRequest + code, message = "SECURITY_VERIFICATION_FLOW_REQUIRED", service.ErrVerificationFlowRequired.Error() + case errors.Is(err, service.ErrProofMethod): + code, message = "SECURITY_PROOF_METHOD_MISMATCH", "This verification method is not allowed for this action." + case errors.Is(err, service.ErrProofScope): + code, message = "SECURITY_PROOF_SCOPE_MISMATCH", "Verification does not match this action." + case errors.Is(err, service.ErrOAuthAccountMismatch): + code, message = "OAUTH_ACCOUNT_MISMATCH", service.ErrOAuthAccountMismatch.Error() + case errors.Is(err, model.ErrTwoFASetupInvalid): + status = http.StatusConflict + code, message = "TWOFA_SETUP_INVALID", model.ErrTwoFASetupInvalid.Error() + case errors.Is(err, model.ErrTwoFACodeInvalid): + code, message = "TWOFA_CODE_INVALID", model.ErrTwoFACodeInvalid.Error() + case errors.Is(err, model.ErrTwoFAAlreadyEnabled): + code, message = "TWOFA_ALREADY_ENABLED", "Two-factor authentication is already enabled." + case errors.Is(err, model.ErrTwoFANotEnabled): + code, message = "TWOFA_NOT_ENABLED", "Two-factor authentication is not enabled." + case errors.Is(err, model.ErrPasskeyNotFound): + code, message = "PASSKEY_NOT_FOUND", "No Passkey is registered." + case errors.Is(err, model.ErrAuthFlowInvalid), errors.Is(err, model.ErrAuthFlowExpired), errors.Is(err, model.ErrAuthFlowConsumed): + code, message = "AUTH_FLOW_INVALID", "Verification flow expired" + case errors.Is(err, model.ErrUserSessionInvalid), errors.Is(err, model.ErrUserSessionInactive): + writeAuthSessionError(c, service.ErrAuthTokenInvalid) + return + default: + writeAuthSessionError(c, err) + return + } + c.JSON(status, gin.H{"success": false, "code": code, "message": message}) } func UniversalVerify(c *gin.Context) { @@ -30,59 +83,16 @@ func UniversalVerify(c *gin.Context) { c.JSON(http.StatusUnauthorized, gin.H{"success": false, "message": "当前认证方式不支持安全验证"}) return } - var request UniversalVerifyRequest + var request service.VerificationInput if err := common.DecodeJson(c.Request.Body, &request); err != nil { - common.ApiError(c, fmt.Errorf("参数错误: %v", err)) + common.ApiErrorMsg(c, "参数错误") return } - if request.Method != secureVerificationMethod2FA { - common.ApiError(c, errors.New("Passkey 验证必须使用 Passkey verify 流程")) - return - } - if !isAllowedSecurityProofScope(request.Scope) { - common.ApiError(c, errors.New("不支持的安全验证范围")) - return - } - if strings.TrimSpace(request.Code) == "" { - common.ApiError(c, errors.New("验证码不能为空")) - return - } - twoFA, err := model.GetTwoFAByUserId(identity.UserID) + proof, err := service.VerifySecurityInput(identity, request) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } - if twoFA == nil || !twoFA.IsEnabled { - common.ApiError(c, errors.New("用户未启用2FA")) - return - } - if !validateTwoFactorAuth(twoFA, request.Code) { - common.ApiError(c, errors.New("验证失败,请检查验证码")) - return - } - proofToken, expiresAt, err := service.IssueSecurityProof(identity, request.Method, []string{request.Scope}) - if err != nil { - common.ApiError(c, err) - return - } - recordUserSecurityAudit(c, identity.UserID, "user.security_verify", map[string]interface{}{"method": "2fa"}) - c.JSON(http.StatusOK, gin.H{ - "success": true, - "message": "验证成功", - "data": gin.H{ - "proof_token": proofToken, - "expires_at": expiresAt, - "method": request.Method, - "scope": request.Scope, - }, - }) -} - -func isAllowedSecurityProofScope(scope string) bool { - switch scope { - case securityProofScopeChannelKeyRead, securityProofScopePasskeyRegister, securityProofScopePasskeyDelete: - return true - default: - return false - } + recordUserSecurityAudit(c, identity.UserID, "user.security_verify", map[string]interface{}{"method": proof.Method, "scope": proof.Scope}) + common.ApiSuccess(c, proof) } diff --git a/controller/security_enrollment_test.go b/controller/security_enrollment_test.go new file mode 100644 index 0000000000..0639899147 --- /dev/null +++ b/controller/security_enrollment_test.go @@ -0,0 +1,1132 @@ +package controller + +import ( + "bytes" + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "crypto/x509" + "encoding/base64" + "encoding/binary" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/i18n" + "github.com/QuantumNous/new-api/middleware" + "github.com/QuantumNous/new-api/model" + "github.com/QuantumNous/new-api/oauth" + "github.com/QuantumNous/new-api/service" + "github.com/QuantumNous/new-api/setting/system_setting" + "github.com/fxamacker/cbor/v2" + "github.com/gin-gonic/gin" + "github.com/golang-jwt/jwt/v5" + "github.com/pquerna/otp/totp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/gorm" + "gorm.io/gorm/logger" +) + +func setupSecurityEnrollmentTest(t *testing.T) (*model.User, service.AuthIdentity) { + t.Helper() + require.NoError(t, i18n.Init()) + gin.SetMode(gin.TestMode) + previousDB, previousLogDB := model.DB, model.LOG_DB + previousMain, previousLog := common.MainDatabaseType(), common.LogDatabaseType() + previousRedis, previousSecret := common.RedisEnabled, common.SessionSecret + previousEncryption := common.PasswordLoginEncryptionEnabled + previousSettings := *system_setting.GetPasskeySettings() + dialect := os.Getenv("TEST_SECURITY_DIALECT") + if dialect == "" { + dialect = "sqlite" + } + dsn := os.Getenv("TEST_" + strings.ToUpper(dialect) + "_DSN") + db, _ := newAuditTestDatabase(t, dialect, dsn) + logDB, _ := newAuditTestDatabase(t, dialect, dsn) + db.Logger = logger.Default.LogMode(logger.Silent) + logDB.Logger = logger.Default.LogMode(logger.Silent) + versionQuery := "SELECT VERSION()" + if dialect == "sqlite" { + versionQuery = "SELECT sqlite_version()" + } + var version string + require.NoError(t, db.Raw(versionQuery).Scan(&version).Error) + t.Logf("database: %s %s", dialect, version) + require.NoError(t, db.AutoMigrate(&model.User{}, &model.UserSession{}, &model.TwoFA{}, &model.TwoFABackupCode{}, &model.PasskeyCredential{}, &model.AuthFlow{}, &model.UserOAuthBinding{})) + require.NoError(t, logDB.AutoMigrate(&model.AuditLog{})) + model.DB, model.LOG_DB = db, logDB + dbType := common.DatabaseTypeSQLite + if dialect == "mysql" { + dbType = common.DatabaseTypeMySQL + } + if dialect == "postgres" { + dbType = common.DatabaseTypePostgreSQL + } + common.SetDatabaseTypes(dbType, dbType) + common.PasswordLoginEncryptionEnabled = false + common.RedisEnabled = false + common.SessionSecret = "security-enrollment-test-secret" + *system_setting.GetPasskeySettings() = system_setting.PasskeySettings{Enabled: true, RPID: "example.com", Origins: "https://example.com", RPDisplayName: "new-api"} + t.Cleanup(func() { + model.DB, model.LOG_DB = previousDB, previousLogDB + common.SetDatabaseTypes(previousMain, previousLog) + common.RedisEnabled, common.SessionSecret = previousRedis, previousSecret + common.PasswordLoginEncryptionEnabled = previousEncryption + *system_setting.GetPasskeySettings() = previousSettings + connection, err := db.DB() + if err == nil { + _ = connection.Close() + } + }) + password, err := common.Password2Hash("enrollment-password") + require.NoError(t, err) + user := &model.User{Username: "enrollment-user", Password: password, Role: common.RoleCommonUser, Status: common.UserStatusEnabled, Group: "default", AuthVersion: 1} + require.NoError(t, db.Create(user).Error) + require.NoError(t, model.PublishUserAuthCache(user.Id)) + bundle, err := service.CreateLoginSession(user.Id, "password", "127.0.0.1", "enrollment-test") + require.NoError(t, err) + identity, err := service.ParseAccessToken(bundle.AccessToken) + require.NoError(t, err) + return user, identity +} + +func securityEnrollmentRequest(method, path, body, proof string, identity service.AuthIdentity, handler gin.HandlerFunc) *httptest.ResponseRecorder { + response := httptest.NewRecorder() + c, _ := gin.CreateTestContext(response) + c.Request = httptest.NewRequest(method, path, strings.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + c.Request.Header.Set("X-Security-Proof", proof) + c.Set("id", identity.UserID) + c.Set("role", common.RoleCommonUser) + c.Set("session_id", identity.SessionID) + c.Set("auth_version", identity.UserAuthVersion) + c.Set("session_version", identity.SessionVersion) + handler(c) + return response +} + +func issueSecurityEnrollmentProof(t *testing.T, identity service.AuthIdentity, operation service.VerificationOperation, method string) string { + t.Helper() + binding, err := service.BindVerificationOperation(operation) + require.NoError(t, err) + proof, _, err := service.IssueSecurityProof(identity, method, binding) + require.NoError(t, err) + return proof +} + +func authorizeSecurityEnrollment(t *testing.T, identity service.AuthIdentity) *model.AuthFlowAuthorization { + t.Helper() + operation := service.VerificationOperation{Scope: service.VerificationScopeTwoFASetup} + proof := issueSecurityEnrollmentProof(t, identity, operation, service.VerificationMethodPassword) + authorization, err := service.ConsumeOperationProof(proof, identity, operation) + require.NoError(t, err) + return authorization +} + +// securityPasskeyResponse acts as a software authenticator at the browser boundary. +// The handlers still validate the real WebAuthn challenge, origin and signature. +func securityPasskeyResponse(t *testing.T, key *ecdsa.PrivateKey, challenge string, registration bool, counter uint32) json.RawMessage { + t.Helper() + ceremony := "webauthn.get" + if registration { + ceremony = "webauthn.create" + } + clientData, err := common.Marshal(map[string]any{"type": ceremony, "challenge": challenge, "origin": "https://example.com"}) + require.NoError(t, err) + credentialID := sha256.Sum256(elliptic.Marshal(key.Curve, key.X, key.Y)) + rpIDHash := sha256.Sum256([]byte("example.com")) + authData := append([]byte{}, rpIDHash[:]...) + response := map[string]any{"clientDataJSON": base64.RawURLEncoding.EncodeToString(clientData)} + if registration { + authData = append(authData, 0x45) // user present, user verified, attested credential + authData = append(authData, make([]byte, 4+16)...) + authData = binary.BigEndian.AppendUint16(authData, uint16(len(credentialID))) + authData = append(authData, credentialID[:]...) + publicKey, err := cbor.Marshal(map[int]any{ + 1: 2, 3: -7, -1: 1, -2: key.X.FillBytes(make([]byte, 32)), -3: key.Y.FillBytes(make([]byte, 32)), + }) + require.NoError(t, err) + authData = append(authData, publicKey...) + attestation, err := cbor.Marshal(map[string]any{"fmt": "none", "authData": authData, "attStmt": map[string]any{}}) + require.NoError(t, err) + response["attestationObject"] = base64.RawURLEncoding.EncodeToString(attestation) + } else { + authData = append(authData, 0x05) // user present and verified + authData = binary.BigEndian.AppendUint32(authData, counter) + clientHash := sha256.Sum256(clientData) + signedData := append(append([]byte{}, authData...), clientHash[:]...) + signedHash := sha256.Sum256(signedData) + signature, err := ecdsa.SignASN1(rand.Reader, key, signedHash[:]) + require.NoError(t, err) + response["authenticatorData"] = base64.RawURLEncoding.EncodeToString(authData) + response["signature"] = base64.RawURLEncoding.EncodeToString(signature) + } + id := base64.RawURLEncoding.EncodeToString(credentialID[:]) + credential, err := common.Marshal(map[string]any{"id": id, "rawId": id, "type": "public-key", "response": response}) + require.NoError(t, err) + return credential +} + +func TestSecurityEnrollmentRejectsMissingProofBeforeCreatingCredentials(t *testing.T) { + user, identity := setupSecurityEnrollmentTest(t) + for _, test := range []struct { + path string + handler gin.HandlerFunc + }{ + {"/api/user/2fa/setup", Setup2FA}, + {"/api/user/passkey/register/begin", PasskeyRegisterBegin}, + } { + t.Run(test.path, func(t *testing.T) { + response := securityEnrollmentRequest(http.MethodPost, test.path, `{}`, "", identity, test.handler) + assert.Equal(t, http.StatusForbidden, response.Code) + assert.Contains(t, response.Body.String(), "SECURITY_PROOF_REQUIRED") + assert.NotContains(t, response.Body.String(), "qr_code_data") + }) + } + pending, err := model.GetTwoFAByUserId(user.Id) + require.NoError(t, err) + assert.Nil(t, pending) +} + +type securityEnrollmentResponse struct { + Success bool `json:"success"` + Message string `json:"message"` + Code string `json:"code"` + Data json.RawMessage `json:"data"` +} + +func TestSecurityEnrollmentMethodPolicy(t *testing.T) { + for _, test := range []struct { + name string + password, passkey, twoFA, locked, disabledPasskey bool + method string + available bool + }{ + {name: "first factor uses password", password: true, method: "password", available: true}, + {name: "existing passkey takes precedence", password: true, passkey: true, method: "passkey", available: true}, + {name: "twofa takes precedence over passkey", password: true, passkey: true, twoFA: true, method: "2fa", available: true}, + {name: "locked twofa does not fall back", password: true, passkey: true, twoFA: true, locked: true, method: "2fa"}, + {name: "disabled passkey does not fall back", password: true, passkey: true, disabledPasskey: true, method: "passkey"}, + {name: "disabled registration does not request a password", password: true, disabledPasskey: true, method: "password"}, + {name: "passwordless account without providers is unavailable", method: "oauth"}, + } { + t.Run(test.name, func(t *testing.T) { + user, identity := setupSecurityEnrollmentTest(t) + if !test.password { + require.NoError(t, model.DB.Model(user).Update("password", "").Error) + } + if test.passkey { + require.NoError(t, model.DB.Create(&model.PasskeyCredential{UserID: user.Id, CredentialID: "enrolled-passkey", PublicKey: "public-key"}).Error) + } + if test.twoFA { + twoFA := &model.TwoFA{UserId: user.Id, Secret: "JBSWY3DPEHPK3PXP", IsEnabled: true} + if test.locked { + until := time.Now().Add(time.Minute) + twoFA.LockedUntil = &until + } + require.NoError(t, model.DB.Create(twoFA).Error) + } + system_setting.GetPasskeySettings().Enabled = !test.disabledPasskey + requirements, err := service.GetVerificationRequirements(identity, "passkey.register") + require.NoError(t, err) + require.Len(t, requirements.Methods, 1) + assert.Equal(t, test.method, requirements.Methods[0].Method) + assert.Equal(t, test.available, requirements.Methods[0].Available) + if test.passkey && !test.twoFA { + requirements, err = service.GetVerificationRequirements(identity, "2fa.setup") + require.NoError(t, err) + assert.Equal(t, "passkey", requirements.Methods[0].Method) + } + }) + } +} + +func TestSecurityEnrollmentPasswordProofIsBoundToSessionAndAction(t *testing.T) { + user, identity := setupSecurityEnrollmentTest(t) + response := securityEnrollmentRequest("POST", "/api/verify", `{"method":"password","scope":"2fa.setup","password":"wrong"}`, "", identity, UniversalVerify) + assert.NotContains(t, response.Body.String(), "proof_token") + response = securityEnrollmentRequest("POST", "/api/verify", `{"method":"password","scope":"2fa.setup","password":"enrollment-password"}`, "", identity, UniversalVerify) + var body securityEnrollmentResponse + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body)) + require.True(t, body.Success, body.Message) + var proof service.SecurityProof + require.NoError(t, common.Unmarshal(body.Data, &proof)) + _, err := service.ConsumeOperationProof(proof.ProofToken, identity, service.VerificationOperation{Scope: "passkey.register"}) + assert.ErrorIs(t, err, service.ErrProofScope) + other := identity + other.SessionID = "another-session" + _, err = service.ConsumeOperationProof(proof.ProofToken, other, service.VerificationOperation{Scope: "2fa.setup"}) + assert.ErrorIs(t, err, service.ErrAuthTokenInvalid) + _, err = service.ConsumeOperationProof(proof.ProofToken, identity, service.VerificationOperation{Scope: "2fa.setup"}) + require.NoError(t, err) + response = securityEnrollmentRequest("POST", "/api/verify", `{"method":"password","scope":"channel.key.read","password":"enrollment-password"}`, "", identity, UniversalVerify) + assert.NotContains(t, response.Body.String(), "proof_token") + common.PasswordLoginEncryptionEnabled = true + response = securityEnrollmentRequest("POST", "/api/verify", `{"method":"password","scope":"2fa.setup","password":"enrollment-password"}`, "", identity, UniversalVerify) + assert.NotContains(t, response.Body.String(), "proof_token", "encryption-required mode must reject plaintext") + common.PasswordLoginEncryptionEnabled = false + require.NoError(t, model.DB.Model(user).Update("auth_version", 2).Error) + _, err = service.ConsumeOperationProof(proof.ProofToken, identity, service.VerificationOperation{Scope: "2fa.setup"}) + assert.ErrorIs(t, err, service.ErrLoginSessionRevoked) +} + +func TestSecurityEnrollmentProofStartsOnlyOneSetup(t *testing.T) { + _, identity := setupSecurityEnrollmentTest(t) + proof := issueSecurityEnrollmentProof(t, identity, service.VerificationOperation{Scope: "2fa.setup"}, "password") + first := securityEnrollmentRequest("POST", "/api/user/2fa/setup", `{}`, proof, identity, Setup2FA) + var body securityEnrollmentResponse + require.NoError(t, common.Unmarshal(first.Body.Bytes(), &body)) + require.True(t, body.Success, body.Message) + second := securityEnrollmentRequest("POST", "/api/user/2fa/setup", `{}`, proof, identity, Setup2FA) + assert.Equal(t, http.StatusForbidden, second.Code) + require.NoError(t, common.Unmarshal(second.Body.Bytes(), &body)) + assert.False(t, body.Success) + assert.Equal(t, "SECURITY_PROOF_CONSUMED", body.Code) +} + +func TestSecurityEnrollmentOperationContext(t *testing.T) { + for _, test := range []struct { + name, scope, context string + err error + }{ + {"channel", "channel.key.read", `{"channel_id":123}`, nil}, + {"missing channel", "channel.key.read", ``, service.ErrVerificationContextInvalid}, + {"null channel", "channel.key.read", `{"channel_id":null}`, service.ErrVerificationContextInvalid}, + {"string channel", "channel.key.read", `{"channel_id":"123"}`, service.ErrVerificationContextInvalid}, + {"fractional channel", "channel.key.read", `{"channel_id":123.5}`, service.ErrVerificationContextInvalid}, + {"zero channel", "channel.key.read", `{"channel_id":0}`, service.ErrVerificationContextInvalid}, + {"negative channel", "channel.key.read", `{"channel_id":-1}`, service.ErrVerificationContextInvalid}, + {"overflow channel", "channel.key.read", `{"channel_id":18446744073709551615}`, service.ErrVerificationContextInvalid}, + {"extra field", "channel.key.read", `{"channel_id":123,"extra":true}`, service.ErrVerificationContextInvalid}, + {"null context", "passkey.register", `null`, service.ErrVerificationContextInvalid}, + {"array context", "passkey.register", `[]`, service.ErrVerificationContextInvalid}, + {"empty enrollment", "passkey.register", `{}`, nil}, + {"implicit enrollment", "passkey.register", ``, nil}, + {"enrollment target injection", "passkey.register", `{"user_id":42}`, service.ErrVerificationContextInvalid}, + {"unknown scope", "user.email.change", `{}`, service.ErrProofScope}, + } { + t.Run(test.name, func(t *testing.T) { + _, err := service.BindVerificationOperation(service.VerificationOperation{Scope: test.scope, Context: []byte(test.context)}) + assert.ErrorIs(t, err, test.err) + }) + } + var first, reordered service.VerificationOperation + require.NoError(t, common.UnmarshalJsonStr(`{"scope":"channel.key.read","context":{"channel_id":123}}`, &first)) + require.NoError(t, common.UnmarshalJsonStr(`{"context": { "channel_id": 123 }, "scope":"channel.key.read"}`, &reordered)) + firstBinding, err := service.BindVerificationOperation(first) + require.NoError(t, err) + secondBinding, err := service.BindVerificationOperation(reordered) + require.NoError(t, err) + assert.Equal(t, firstBinding, secondBinding) +} + +func TestSecurityEnrollmentChannelProofRejectsMismatchesBeforeConsumption(t *testing.T) { + user, identity := setupSecurityEnrollmentTest(t) + require.NoError(t, model.DB.Model(user).Update("role", common.RoleRootUser).Error) + require.NoError(t, model.PublishUserAuthCache(user.Id)) + twoFA := &model.TwoFA{UserId: user.Id, Secret: "JBSWY3DPEHPK3PXP", IsEnabled: true} + require.NoError(t, model.DB.Create(twoFA).Error) + operation := service.VerificationOperation{Scope: service.VerificationScopeChannelKeyRead, Context: []byte(`{"channel_id":123}`)} + code, err := totp.GenerateCode(twoFA.Secret, time.Now()) + require.NoError(t, err) + proof, err := service.VerifySecurityInput(identity, service.VerificationInput{Method: "2fa", Scope: operation.Scope, Context: operation.Context, Code: code}) + require.NoError(t, err) + for _, test := range []struct { + name string + identity service.AuthIdentity + operation service.VerificationOperation + err error + }{ + {"channel", identity, service.VerificationOperation{Scope: operation.Scope, Context: []byte(`{"channel_id":456}`)}, service.ErrProofContext}, + {"scope", identity, service.VerificationOperation{Scope: "passkey.delete"}, service.ErrProofScope}, + {"user", service.AuthIdentity{UserID: user.Id + 1, SessionID: identity.SessionID, UserAuthVersion: identity.UserAuthVersion, SessionVersion: identity.SessionVersion}, operation, service.ErrAuthTokenInvalid}, + {"session", service.AuthIdentity{UserID: user.Id, SessionID: "other-session", UserAuthVersion: identity.UserAuthVersion, SessionVersion: identity.SessionVersion}, operation, service.ErrAuthTokenInvalid}, + {"session version", service.AuthIdentity{UserID: user.Id, SessionID: identity.SessionID, UserAuthVersion: identity.UserAuthVersion, SessionVersion: identity.SessionVersion + 1}, operation, service.ErrAuthTokenInvalid}, + {"user version", service.AuthIdentity{UserID: user.Id, SessionID: identity.SessionID, UserAuthVersion: identity.UserAuthVersion + 1, SessionVersion: identity.SessionVersion}, operation, service.ErrAuthTokenInvalid}, + } { + t.Run(test.name, func(t *testing.T) { + _, err := service.ConsumeOperationProof(proof.ProofToken, test.identity, test.operation) + assert.ErrorIs(t, err, test.err) + }) + } + require.NoError(t, model.DB.Model(twoFA).Update("is_enabled", false).Error) + _, err = service.ConsumeOperationProof(proof.ProofToken, identity, operation) + assert.ErrorIs(t, err, service.ErrProofMethod) + require.NoError(t, model.DB.Model(twoFA).Update("is_enabled", true).Error) + authorization, err := service.ConsumeOperationProof(proof.ProofToken, identity, operation) + require.NoError(t, err) + assert.Positive(t, authorization.ProofID) + _, err = service.ConsumeOperationProof(proof.ProofToken, identity, operation) + assert.ErrorIs(t, err, service.ErrProofConsumed) +} + +func TestSecurityEnrollmentProofConcurrentConsumption(t *testing.T) { + _, identity := setupSecurityEnrollmentTest(t) + operation := service.VerificationOperation{Scope: "passkey.register"} + proof := issueSecurityEnrollmentProof(t, identity, operation, "password") + start := make(chan struct{}) + results := make(chan error, 2) + for range 2 { + go func() { + <-start + _, err := service.ConsumeOperationProof(proof, identity, operation) + results <- err + }() + } + close(start) + successes := 0 + for range 2 { + if err := <-results; err != nil { + assert.ErrorIs(t, err, service.ErrProofConsumed) + } else { + successes++ + } + } + assert.Equal(t, 1, successes) +} + +func TestSecurityEnrollmentProofRequiresLiveRecordAndExactDeadline(t *testing.T) { + _, identity := setupSecurityEnrollmentTest(t) + operation := service.VerificationOperation{Scope: "passkey.register"} + proof := issueSecurityEnrollmentProof(t, identity, operation, "password") + claims := jwt.MapClaims{} + _, _, err := jwt.NewParser().ParseUnverified(proof, claims) + require.NoError(t, err) + assert.Equal(t, float64(60), claims["exp"].(float64)-claims["iat"].(float64)) + assert.NotEmpty(t, claims["context_hash"]) + assert.NotContains(t, claims, "context") + assert.NotContains(t, claims, "channel_id") + var stored model.AuthFlow + require.NoError(t, model.DB.Where("purpose = ?", model.AuthFlowPurposeSecurityProof).First(&stored).Error) + assert.Equal(t, int64(claims["exp"].(float64)), stored.ExpiresAt.Unix()) + assert.NotEqual(t, proof, stored.TokenHash) + assert.NotEqual(t, claims["jti"], stored.TokenHash) + require.NoError(t, model.DB.Model(&stored).Update("expires_at", time.Now()).Error) + _, err = service.ConsumeOperationProof(proof, identity, operation) + assert.ErrorIs(t, err, service.ErrAuthTokenExpired, "database deadline must reject even while the JWT is within its clock tolerance") + require.NoError(t, model.DB.Delete(&stored).Error) + _, err = service.ConsumeOperationProof(proof, identity, operation) + assert.ErrorIs(t, err, service.ErrAuthTokenInvalid) +} + +func TestSecurityEnrollmentProofIsBurnedAfterBusinessFailure(t *testing.T) { + _, identity := setupSecurityEnrollmentTest(t) + proof := issueSecurityEnrollmentProof(t, identity, service.VerificationOperation{Scope: "passkey.register"}, "password") + require.NoError(t, model.DB.Callback().Create().Before("gorm:create").Register("security_flow_creation_failure", func(tx *gorm.DB) { + if tx.Statement.Table == "auth_flows" { + tx.AddError(errors.New("injected creation failure")) + } + })) + response := securityEnrollmentRequest("POST", "/api/user/passkey/register/begin", "", proof, identity, PasskeyRegisterBegin) + assert.Equal(t, http.StatusInternalServerError, response.Code) + require.NoError(t, model.DB.Callback().Create().Remove("security_flow_creation_failure")) + response = securityEnrollmentRequest("POST", "/api/user/passkey/register/begin", "", proof, identity, PasskeyRegisterBegin) + assert.Equal(t, http.StatusForbidden, response.Code) + assert.Contains(t, response.Body.String(), "SECURITY_PROOF_CONSUMED") +} + +func TestSecurityEnrollmentProofStorageErrorsFailClosed(t *testing.T) { + for _, stage := range []string{"issuance", "consumption"} { + t.Run(stage, func(t *testing.T) { + _, identity := setupSecurityEnrollmentTest(t) + proof := "" + if stage == "consumption" { + proof = issueSecurityEnrollmentProof(t, identity, service.VerificationOperation{Scope: "passkey.register"}, "password") + } + failure := func(tx *gorm.DB) { + if tx.Statement.Table == "auth_flows" { + tx.AddError(errors.New("private proof database failure")) + } + } + if stage == "issuance" { + require.NoError(t, model.DB.Callback().Create().Before("gorm:create").Register("proof_storage_failure", failure)) + } else { + require.NoError(t, model.DB.Callback().Update().Before("gorm:update").Register("proof_storage_failure", failure)) + } + var response *httptest.ResponseRecorder + if stage == "issuance" { + response = securityEnrollmentRequest("POST", "/api/verify", `{"method":"password","scope":"passkey.register","password":"enrollment-password"}`, "", identity, UniversalVerify) + require.NoError(t, model.DB.Callback().Create().Remove("proof_storage_failure")) + } else { + response = securityEnrollmentRequest("POST", "/api/user/passkey/register/begin", "", proof, identity, PasskeyRegisterBegin) + require.NoError(t, model.DB.Callback().Update().Remove("proof_storage_failure")) + } + assert.Equal(t, http.StatusInternalServerError, response.Code) + assert.Contains(t, response.Body.String(), "AUTH_INTERNAL_ERROR") + assert.NotContains(t, response.Body.String(), "private") + assert.NotContains(t, response.Body.String(), "proof_token") + assert.NotContains(t, response.Body.String(), "flow_token") + var count int64 + require.NoError(t, model.DB.Model(&model.AuthFlow{}).Where("purpose = ?", model.AuthFlowPurposePasskeyRegister).Count(&count).Error) + assert.Zero(t, count) + if stage == "consumption" { + response = securityEnrollmentRequest("POST", "/api/user/passkey/register/begin", "", proof, identity, PasskeyRegisterBegin) + var result securityEnrollmentResponse + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result)) + assert.True(t, result.Success, "a failed consumption transaction must not burn the proof") + } + }) + } +} + +func TestSecurityEnrollmentVerificationTransportsRejectInvalidContext(t *testing.T) { + _, identity := setupSecurityEnrollmentTest(t) + oauth.Register("enrollment-oauth", &enrollmentOAuthProvider{externalID: "linked-user"}) + t.Cleanup(func() { oauth.Unregister("enrollment-oauth") }) + for _, test := range []struct { + path, body string + handler gin.HandlerFunc + }{ + {"/api/verify", `{"method":"password","scope":"passkey.register","context":{"user_id":999},"password":"enrollment-password"}`, UniversalVerify}, + {"/api/user/passkey/verify/begin", `{"scope":"passkey.register","context":{"user_id":999}}`, PasskeyVerifyBegin}, + {"/api/oauth/state", `{"provider":"enrollment-oauth","intent":"verify","scope":"passkey.register","context":{"user_id":999}}`, GenerateOAuthCode}, + } { + t.Run(test.path, func(t *testing.T) { + response := securityEnrollmentRequest("POST", test.path, test.body, "", identity, test.handler) + assert.Equal(t, http.StatusBadRequest, response.Code) + assert.Contains(t, response.Body.String(), "SECURITY_CONTEXT_INVALID") + }) + } + var count int64 + require.NoError(t, model.DB.Model(&model.AuthFlow{}).Count(&count).Error) + assert.Zero(t, count) +} + +func TestSecurityEnrollmentPendingPasskeyRejectsChangedAuthorization(t *testing.T) { + for _, change := range []string{"expired", "revoked", "session version", "user version", "method", "other session"} { + t.Run(change, func(t *testing.T) { + user, identity := setupSecurityEnrollmentTest(t) + proof := issueSecurityEnrollmentProof(t, identity, service.VerificationOperation{Scope: "passkey.register"}, "password") + response := securityEnrollmentRequest("POST", "/api/user/passkey/register/begin", "", proof, identity, PasskeyRegisterBegin) + var result securityEnrollmentResponse + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result)) + require.True(t, result.Success, result.Message) + var begin struct { + FlowToken string `json:"flow_token"` + Options struct { + PublicKey struct { + Challenge string `json:"challenge"` + } `json:"publicKey"` + } `json:"options"` + } + require.NoError(t, common.Unmarshal(result.Data, &begin)) + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + body, err := common.Marshal(passkeyFinishRequest{ + FlowToken: begin.FlowToken, Credential: securityPasskeyResponse(t, key, begin.Options.PublicKey.Challenge, true, 0), + }) + require.NoError(t, err) + switch change { + case "expired": + require.NoError(t, model.DB.Model(&model.AuthFlow{}).Where("purpose = ?", model.AuthFlowPurposePasskeyRegister).Update("expires_at", time.Now().Add(-time.Minute)).Error) + case "revoked": + _, err = model.RevokeUserSession(user.Id, identity.SessionID, "security-test") + require.NoError(t, err) + case "session version": + require.NoError(t, model.DB.Model(&model.UserSession{}).Where("sid = ?", identity.SessionID).Update("version", 2).Error) + case "user version": + require.NoError(t, model.DB.Model(user).Update("auth_version", 2).Error) + case "method": + require.NoError(t, model.DB.Model(user).Update("password", "").Error) + case "other session": + other, err := service.CreateLoginSession(user.Id, "password", "127.0.0.1", "other-session") + require.NoError(t, err) + identity, err = service.ParseAccessToken(other.AccessToken) + require.NoError(t, err) + } + response = securityEnrollmentRequest("POST", "/api/user/passkey/register/finish", string(body), "", identity, PasskeyRegisterFinish) + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result)) + assert.False(t, result.Success) + _, err = model.GetPasskeyByUserID(user.Id) + assert.ErrorIs(t, err, model.ErrPasskeyNotFound) + }) + } +} + +func TestSecurityEnrollmentPasskeyProofProtectsChannelKeyRead(t *testing.T) { + user, identity := setupSecurityEnrollmentTest(t) + require.NoError(t, model.DB.Model(user).Update("role", common.RoleRootUser).Error) + require.NoError(t, model.PublishUserAuthCache(user.Id)) + require.NoError(t, model.DB.AutoMigrate(&model.Channel{})) + for _, channel := range []model.Channel{ + {Id: 123, Name: "first", Key: "first-channel-secret", Type: 1, Status: 1}, + {Id: 456, Name: "second", Key: "second-channel-secret", Type: 1, Status: 1}, + } { + require.NoError(t, model.DB.Create(&channel).Error) + } + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + registrationProof := issueSecurityEnrollmentProof(t, identity, service.VerificationOperation{Scope: "passkey.register"}, "password") + response := securityEnrollmentRequest("POST", "/api/user/passkey/register/begin", "", registrationProof, identity, PasskeyRegisterBegin) + var body securityEnrollmentResponse + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body)) + require.True(t, body.Success, body.Message) + var begin struct { + FlowToken string `json:"flow_token"` + Options struct { + PublicKey struct { + Challenge string `json:"challenge"` + } `json:"publicKey"` + } `json:"options"` + } + require.NoError(t, common.Unmarshal(body.Data, &begin)) + require.NotEmpty(t, begin.Options.PublicKey.Challenge) + registrationBody, err := common.Marshal(passkeyFinishRequest{ + FlowToken: begin.FlowToken, Credential: securityPasskeyResponse(t, key, begin.Options.PublicKey.Challenge, true, 0), + }) + require.NoError(t, err) + // The dedicated registration flow remains authorized after the consumed proof expires. + require.NoError(t, model.DB.Model(&model.AuthFlow{}).Where("purpose = ?", model.AuthFlowPurposeSecurityProof).Update("expires_at", time.Now().Add(-time.Minute)).Error) + response = securityEnrollmentRequest("POST", "/api/user/passkey/register/finish", string(registrationBody), "", identity, PasskeyRegisterFinish) + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body)) + require.True(t, body.Success, body.Message) + var rotation struct { + AccessToken string `json:"access_token"` + } + require.NoError(t, common.Unmarshal(body.Data, &rotation)) + identity, err = service.ParseAccessToken(rotation.AccessToken) + require.NoError(t, err) + assert.EqualValues(t, 2, identity.UserAuthVersion) + response = securityEnrollmentRequest("POST", "/api/user/passkey/register/finish", string(registrationBody), "", identity, PasskeyRegisterFinish) + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body)) + assert.False(t, body.Success) + + response = securityEnrollmentRequest("POST", "/api/user/passkey/verify/begin", `{"scope":"channel.key.read","context":{"channel_id":123}}`, "", identity, PasskeyVerifyBegin) + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body)) + require.True(t, body.Success, body.Message) + require.NoError(t, common.Unmarshal(body.Data, &begin)) + assertionBody, err := common.Marshal(map[string]any{ + "flow_token": begin.FlowToken, "credential": securityPasskeyResponse(t, key, begin.Options.PublicKey.Challenge, false, 1), + "scope": "passkey.delete", "context": map[string]any{"channel_id": 456}, + }) + require.NoError(t, err) + response = securityEnrollmentRequest("POST", "/api/user/passkey/verify/finish", string(assertionBody), "", identity, PasskeyVerifyFinish) + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body)) + require.True(t, body.Success, body.Message) + var proof service.SecurityProof + require.NoError(t, common.Unmarshal(body.Data, &proof)) + assert.Equal(t, "passkey", proof.Method) + assert.Equal(t, "channel.key.read", proof.Scope, "finish cannot replace the operation approved at begin") + + router := gin.New() + router.POST("/api/channel/:id/key", middleware.RootAuth(), middleware.SecureVerificationRequired(), GetChannelKey) + for _, test := range []struct { + name, path, proof, code, key string + status int + }{ + {"login token only", "/api/channel/123/key", "", "SECURITY_PROOF_REQUIRED", "", http.StatusForbidden}, + {"access token as proof", "/api/channel/123/key", rotation.AccessToken, "SECURITY_PROOF_INVALID", "", http.StatusForbidden}, + {"other channel", "/api/channel/456/key", proof.ProofToken, "SECURITY_PROOF_CONTEXT_MISMATCH", "", http.StatusForbidden}, + {"authorized channel", "/api/channel/123/key", proof.ProofToken, "", "first-channel-secret", http.StatusOK}, + {"replay", "/api/channel/123/key", proof.ProofToken, "SECURITY_PROOF_CONSUMED", "", http.StatusForbidden}, + } { + t.Run(test.name, func(t *testing.T) { + request := httptest.NewRequest("POST", test.path, nil) + request.Header.Set("Authorization", "Bearer "+rotation.AccessToken) + request.Header.Set("X-Security-Proof", test.proof) + result := httptest.NewRecorder() + router.ServeHTTP(result, request) + assert.Equal(t, test.status, result.Code) + var response securityEnrollmentResponse + require.NoError(t, common.Unmarshal(result.Body.Bytes(), &response)) + assert.Equal(t, test.code, response.Code) + if test.key != "" { + assert.Contains(t, string(response.Data), test.key) + } else { + assert.NotContains(t, result.Body.String(), "channel-secret") + } + }) + } + var logs []model.AuditLog + require.NoError(t, model.LOG_DB.Where("action = ?", "channel.key_view").Find(&logs).Error) + require.Len(t, logs, 1) + encodedLogs, err := common.Marshal(logs) + require.NoError(t, err) + assert.NotContains(t, string(encodedLogs), "first-channel-secret") + assert.NotContains(t, string(encodedLogs), proof.ProofToken) + + response = securityEnrollmentRequest("POST", "/api/user/passkey/verify/begin", `{"scope":"passkey.delete"}`, "", identity, PasskeyVerifyBegin) + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body)) + require.True(t, body.Success, body.Message) + require.NoError(t, common.Unmarshal(body.Data, &begin)) + deleteAssertion, err := common.Marshal(passkeyFinishRequest{ + FlowToken: begin.FlowToken, Credential: securityPasskeyResponse(t, key, begin.Options.PublicKey.Challenge, false, 2), + }) + require.NoError(t, err) + response = securityEnrollmentRequest("POST", "/api/user/passkey/verify/finish", string(deleteAssertion), "", identity, PasskeyVerifyFinish) + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body)) + require.True(t, body.Success, body.Message) + require.NoError(t, common.Unmarshal(body.Data, &proof)) + response = securityEnrollmentRequest("DELETE", "/api/user/passkey", "", proof.ProofToken, identity, PasskeyDelete) + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body)) + require.True(t, body.Success, body.Message) + _, err = model.GetPasskeyByUserID(user.Id) + assert.ErrorIs(t, err, model.ErrPasskeyNotFound) +} + +func TestSecurityEnrollmentVerifyRequiresDedicatedFlowForInteractiveMethods(t *testing.T) { + for _, method := range []string{service.VerificationMethodPasskey, service.VerificationMethodOAuth} { + t.Run(method, func(t *testing.T) { + user, identity := setupSecurityEnrollmentTest(t) + if method == service.VerificationMethodPasskey { + require.NoError(t, model.DB.Create(&model.PasskeyCredential{UserID: user.Id, CredentialID: "enrolled-passkey", PublicKey: "public-key"}).Error) + } else { + require.NoError(t, model.DB.Model(user).Updates(map[string]any{"password": "", "github_id": "linked-user"}).Error) + oauth.Register("enrollment-oauth", &enrollmentOAuthProvider{externalID: "linked-user"}) + t.Cleanup(func() { oauth.Unregister("enrollment-oauth") }) + } + _, err := service.RequireVerificationMethod(identity, service.VerificationScopeTwoFASetup, method) + require.NoError(t, err) + payload, err := common.Marshal(service.VerificationInput{Method: method, Scope: service.VerificationScopeTwoFASetup}) + require.NoError(t, err) + response := securityEnrollmentRequest("POST", "/api/verify", string(payload), "", identity, UniversalVerify) + var body securityEnrollmentResponse + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body)) + assert.Equal(t, http.StatusBadRequest, response.Code) + assert.False(t, body.Success) + assert.Equal(t, "SECURITY_VERIFICATION_FLOW_REQUIRED", body.Code) + assert.Equal(t, "This verification method requires its dedicated verification flow.", body.Message) + assert.Empty(t, body.Data) + }) + } +} + +func TestSecurityEnrollmentTwoFAFlowAndSessionRotation(t *testing.T) { + user, identity := setupSecurityEnrollmentTest(t) + other, err := service.CreateLoginSession(user.Id, "password", "127.0.0.1", "other-device") + require.NoError(t, err) + var proof string + var setups []service.TwoFASetup + for range 2 { + proof = issueSecurityEnrollmentProof(t, identity, service.VerificationOperation{Scope: "2fa.setup"}, "password") + response := securityEnrollmentRequest("POST", "/api/user/2fa/setup", `{}`, proof, identity, Setup2FA) + var body securityEnrollmentResponse + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body)) + require.True(t, body.Success, body.Message) + var setup service.TwoFASetup + require.NoError(t, common.Unmarshal(body.Data, &setup)) + require.NotEmpty(t, setup.FlowToken) + require.Len(t, setup.BackupCodes, common.BackupCodeCount) + setups = append(setups, setup) + } + oldCode, err := totp.GenerateCode(setups[0].Secret, time.Now()) + require.NoError(t, err) + assert.ErrorIs(t, service.FinishTwoFASetup(identity, setups[0].FlowToken, oldCode), model.ErrTwoFASetupInvalid) + assert.ErrorIs(t, service.FinishTwoFASetup(identity, setups[1].FlowToken, "not-a-code"), model.ErrTwoFACodeInvalid) + _, err = model.GetAuthFlow(setups[1].FlowToken, model.AuthFlowMatch{Purpose: model.AuthFlowPurposeTwoFASetup}) + require.NoError(t, err, "invalid code must not consume setup") + code, err := totp.GenerateCode(setups[1].Secret, time.Now()) + require.NoError(t, err) + require.NoError(t, model.DB.Model(&model.AuthFlow{}).Where("purpose = ?", model.AuthFlowPurposeSecurityProof).Update("expires_at", time.Now().Add(-time.Minute)).Error) + payload, err := common.Marshal(Verify2FARequest{Code: code, FlowToken: setups[1].FlowToken}) + require.NoError(t, err) + response := securityEnrollmentRequest("POST", "/api/user/2fa/enable", string(payload), "", identity, Enable2FA) + var body securityEnrollmentResponse + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body)) + require.True(t, body.Success, body.Message) + var rotated struct { + AccessToken string `json:"access_token"` + } + require.NoError(t, common.Unmarshal(body.Data, &rotated)) + newIdentity, err := service.ParseAccessToken(rotated.AccessToken) + require.NoError(t, err) + assert.EqualValues(t, 2, newIdentity.UserAuthVersion) + assert.Equal(t, identity.SessionID, newIdentity.SessionID) + otherSession, err := model.GetUserSessionBySID(other.Session.SID) + require.NoError(t, err) + assert.Equal(t, model.UserSessionStatusRevoked, otherSession.Status) + _, err = model.GetAuthFlow(setups[1].FlowToken, model.AuthFlowMatch{Purpose: model.AuthFlowPurposeTwoFASetup}) + assert.ErrorIs(t, err, model.ErrAuthFlowConsumed) + _, err = service.ConsumeOperationProof(proof, newIdentity, service.VerificationOperation{Scope: "2fa.setup"}) + assert.Error(t, err) + enabled, err := model.GetTwoFAByUserId(user.Id) + require.NoError(t, err) + assert.True(t, enabled.IsEnabled) + var logs []model.AuditLog + require.NoError(t, model.LOG_DB.Find(&logs).Error) + require.NotEmpty(t, logs) + encoded, err := common.Marshal(logs) + require.NoError(t, err) + for _, secret := range []string{setups[0].Secret, setups[1].Secret, proof, code, setups[1].FlowToken} { + assert.NotContains(t, string(encoded), secret) + } +} + +func TestSecurityEnrollmentSetupAndEnableRollback(t *testing.T) { + user, identity := setupSecurityEnrollmentTest(t) + setup, err := service.StartTwoFASetup(identity, authorizeSecurityEnrollment(t, identity)) + require.NoError(t, err) + failure := errors.New("injected storage failure") + authorization := authorizeSecurityEnrollment(t, identity) + require.NoError(t, model.DB.Callback().Create().Before("gorm:create").Register("security_setup_failure", func(tx *gorm.DB) { + if tx.Statement.Table == "auth_flows" { + tx.AddError(failure) + } + })) + _, err = service.StartTwoFASetup(identity, authorization) + assert.ErrorIs(t, err, failure) + require.NoError(t, model.DB.Callback().Create().Remove("security_setup_failure")) + pending, err := model.GetTwoFAByUserId(user.Id) + require.NoError(t, err) + assert.Equal(t, setup.Secret, pending.Secret) + count, err := model.GetUnusedBackupCodeCount(user.Id) + require.NoError(t, err) + assert.Equal(t, common.BackupCodeCount, count) + code, err := totp.GenerateCode(setup.Secret, time.Now()) + require.NoError(t, err) + require.NoError(t, model.DB.Callback().Update().Before("gorm:update").Register("security_enable_failure", func(tx *gorm.DB) { + if tx.Statement.Table == "two_fas" { + tx.AddError(failure) + } + })) + assert.ErrorIs(t, service.FinishTwoFASetup(identity, setup.FlowToken, code), failure) + require.NoError(t, model.DB.Callback().Update().Remove("security_enable_failure")) + _, err = model.GetAuthFlow(setup.FlowToken, model.AuthFlowMatch{Purpose: model.AuthFlowPurposeTwoFASetup}) + require.NoError(t, err) + storedUser, err := model.GetUserById(user.Id, false) + require.NoError(t, err) + assert.Equal(t, identity.UserAuthVersion, storedUser.AuthVersion) + require.NoError(t, service.FinishTwoFASetup(identity, setup.FlowToken, code)) +} + +type enrollmentOAuthProvider struct { + authFlowTestOAuthProvider + externalID string + disabled bool +} + +func (*enrollmentOAuthProvider) ProviderUserIDColumn() string { return "github_id" } +func (p *enrollmentOAuthProvider) IsEnabled() bool { return !p.disabled } +func (p *enrollmentOAuthProvider) GetUserInfo(context.Context, *oauth.OAuthToken) (*oauth.OAuthUser, error) { + return &oauth.OAuthUser{ProviderUserID: p.externalID, Email: "same@example.com"}, nil +} + +func TestSecurityEnrollmentOAuthVerificationNeverChangesLoginOrBindings(t *testing.T) { + for _, scenario := range []string{"success", "different account", "binding changed", "session changed", "auth version changed", "provider disabled", "cancelled"} { + t.Run(scenario, func(t *testing.T) { + user, identity := setupSecurityEnrollmentTest(t) + require.NoError(t, model.DB.Model(user).Updates(map[string]interface{}{"password": "", "github_id": "linked-user", "email": "same@example.com"}).Error) + provider := &enrollmentOAuthProvider{externalID: "linked-user"} + oauth.Register("enrollment-oauth", provider) + t.Cleanup(func() { oauth.Unregister("enrollment-oauth") }) + response := securityEnrollmentRequest("POST", "/api/oauth/state", `{"provider":"enrollment-oauth","intent":"verify","scope":"2fa.setup"}`, "", identity, GenerateOAuthCode) + var body securityEnrollmentResponse + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body)) + require.True(t, body.Success, body.Message) + var started struct { + FlowToken string `json:"flow_token"` + } + require.NoError(t, common.Unmarshal(body.Data, &started)) + callbackIdentity := identity + query := "&code=authorization-code" + switch scenario { + case "different account": + provider.externalID = "other-user" + case "binding changed": + require.NoError(t, model.DB.Model(user).Update("github_id", "replacement-user").Error) + case "session changed": + callbackIdentity.SessionID = "different-session" + case "auth version changed": + require.NoError(t, model.DB.Model(user).Update("auth_version", 2).Error) + case "cancelled": + query = "&error=access_denied" + case "provider disabled": + provider.disabled = true + } + handler := func(c *gin.Context) { + c.Params = gin.Params{{Key: "provider", Value: "enrollment-oauth"}} + HandleOAuth(c) + } + path := "/api/oauth/enrollment-oauth?state=" + started.FlowToken + query + response = securityEnrollmentRequest("GET", path, "", "", callbackIdentity, handler) + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body)) + assert.Equal(t, scenario == "success", body.Success, body.Message) + assert.NotContains(t, response.Body.String(), "access_token") + assert.Empty(t, response.Header().Values("Set-Cookie")) + if scenario == "success" { + var proof service.SecurityProof + require.NoError(t, common.Unmarshal(body.Data, &proof)) + _, err := service.ConsumeOperationProof(proof.ProofToken, identity, service.VerificationOperation{Scope: "2fa.setup"}) + require.NoError(t, err) + replayed := securityEnrollmentRequest("GET", path, "", "", identity, handler) + assert.Equal(t, http.StatusForbidden, replayed.Code) + } + var users, sessions, bindings int64 + require.NoError(t, model.DB.Model(&model.User{}).Count(&users).Error) + require.NoError(t, model.DB.Model(&model.UserSession{}).Count(&sessions).Error) + require.NoError(t, model.DB.Model(&model.UserOAuthBinding{}).Count(&bindings).Error) + assert.EqualValues(t, 1, users) + assert.EqualValues(t, 1, sessions) + assert.Zero(t, bindings) + stored, err := model.GetUserById(user.Id, false) + require.NoError(t, err) + expectedBinding := "linked-user" + if scenario == "binding changed" { + expectedBinding = "replacement-user" + } + assert.Equal(t, expectedBinding, stored.GitHubId) + }) + } +} + +func TestSecurityEnrollmentEncryptedPasswordVerification(t *testing.T) { + _, identity := setupSecurityEnrollmentTest(t) + keyID, publicPEM := common.PasswordEncryptionPublicKey() + if keyID == "" { + privatePEM, err := common.GeneratePasswordEncryptionPrivateKey() + require.NoError(t, err) + require.NoError(t, common.LoadPasswordEncryptionPrivateKey(privatePEM)) + keyID, publicPEM = common.PasswordEncryptionPublicKey() + } + block, _ := pem.Decode([]byte(publicPEM)) + require.NotNil(t, block) + parsed, err := x509.ParsePKIXPublicKey(block.Bytes) + require.NoError(t, err) + publicKey, ok := parsed.(*rsa.PublicKey) + require.True(t, ok) + ciphertext, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, []byte("enrollment-password"), nil) + require.NoError(t, err) + common.PasswordLoginEncryptionEnabled = true + input := service.VerificationInput{Method: "password", Scope: "passkey.register", PasswordEncrypted: base64.StdEncoding.EncodeToString(ciphertext), EncryptionKeyID: keyID} + proof, err := service.VerifySecurityInput(identity, input) + require.NoError(t, err) + _, err = service.ConsumeOperationProof(proof.ProofToken, identity, service.VerificationOperation{Scope: input.Scope}) + require.NoError(t, err) + input.EncryptionKeyID = "incorrect-key-id" + _, err = service.VerifySecurityInput(identity, input) + assert.ErrorIs(t, err, service.ErrVerificationFailed) +} + +func TestSecurityEnrollmentTwoFAFailureAccountingAndStorageErrors(t *testing.T) { + user, identity := setupSecurityEnrollmentTest(t) + twoFA := &model.TwoFA{UserId: user.Id, Secret: "JBSWY3DPEHPK3PXP", IsEnabled: true} + require.NoError(t, model.DB.Create(twoFA).Error) + for _, endpoint := range []struct { + path string + handler gin.HandlerFunc + }{ + {"/api/user/2fa/disable", Disable2FA}, + {"/api/user/2fa/backup_codes", RegenerateBackupCodes}, + {"/api/user/login/2fa", Verify2FALogin}, + } { + response := securityEnrollmentRequest("POST", endpoint.path, `{}`, "", identity, endpoint.handler) + var body securityEnrollmentResponse + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body)) + assert.False(t, body.Success, endpoint.path) + assert.Equal(t, "参数错误", body.Message, endpoint.path) + } + stored, err := model.GetTwoFAByUserId(user.Id) + require.NoError(t, err) + assert.Zero(t, stored.FailedAttempts, "missing required input must not count as a failed verification") + wrongCode := "" + for _, candidate := range []string{"000000", "111111", "222222", "333333"} { + if !common.ValidateTOTPCode(twoFA.Secret, candidate) { + wrongCode = candidate + break + } + } + require.NotEmpty(t, wrongCode) + assert.ErrorIs(t, service.VerifyTwoFactorCode(twoFA, wrongCode), service.ErrVerificationFailed) + stored, err = model.GetTwoFAByUserId(user.Id) + require.NoError(t, err) + assert.Equal(t, 1, stored.FailedAttempts) + hash, err := common.HashBackupCode("ABCD-1234") + require.NoError(t, err) + require.NoError(t, model.DB.Create(&model.TwoFABackupCode{UserId: user.Id, CodeHash: hash}).Error) + require.NoError(t, service.VerifyTwoFactorCode(stored, "ABCD-1234")) + assert.ErrorIs(t, service.VerifyTwoFactorCode(stored, "ABCD-1234"), service.ErrVerificationFailed) + until := time.Now().Add(time.Minute) + stored.LockedUntil = &until + assert.ErrorIs(t, service.VerifyTwoFactorCode(stored, "ABCD-1234"), service.ErrVerificationLocked) + stored.LockedUntil = nil + code, err := totp.GenerateCode(stored.Secret, time.Now()) + require.NoError(t, err) + failure := errors.New("usage storage failed") + require.NoError(t, model.DB.Callback().Update().Before("gorm:update").Register("security_usage_failure", func(tx *gorm.DB) { + if tx.Statement.Table == "two_fas" { + tx.AddError(failure) + } + })) + assert.ErrorIs(t, service.VerifyTwoFactorCode(stored, code), failure) + require.NoError(t, model.DB.Callback().Update().Remove("security_usage_failure")) +} + +func TestSecurityEnrollmentDatabaseErrorsAreNotReturned(t *testing.T) { + for _, test := range []struct { + name, method, path, body, table string + create bool + handler gin.HandlerFunc + }{ + {"methods", "GET", "/api/verify/methods?scope=2fa.setup", "", "users", false, GetVerificationMethods}, + {"password", "POST", "/api/verify", `{"method":"password","scope":"2fa.setup","password":"enrollment-password"}`, "users", false, UniversalVerify}, + {"passkey", "POST", "/api/user/passkey/register/begin", "", "users", false, PasskeyRegisterBegin}, + {"2fa status", "GET", "/api/user/2fa/status", "", "two_fas", false, Get2FAStatus}, + {"2fa setup", "POST", "/api/user/2fa/setup", "", "two_fas", true, Setup2FA}, + {"2fa flow", "POST", "/api/user/2fa/setup", "", "auth_flows", true, Setup2FA}, + {"oauth state", "POST", "/api/oauth/state", `{"provider":"enrollment-oauth","intent":"verify","scope":"2fa.setup"}`, "users", false, GenerateOAuthCode}, + {"channel key", "POST", "/api/channel/1/key", "", "channels", false, func(c *gin.Context) { + c.Params = gin.Params{{Key: "id", Value: "1"}} + GetChannelKey(c) + }}, + } { + t.Run(test.name, func(t *testing.T) { + _, identity := setupSecurityEnrollmentTest(t) + oauth.Register("enrollment-oauth", &enrollmentOAuthProvider{externalID: "linked-user"}) + t.Cleanup(func() { oauth.Unregister("enrollment-oauth") }) + proof := issueSecurityEnrollmentProof(t, identity, service.VerificationOperation{Scope: service.VerificationScopeTwoFASetup}, service.VerificationMethodPassword) + privateError := errors.New("database connection failed: private-db-host private_table SELECT secret_column") + callback := func(tx *gorm.DB) { + if tx.Statement.Table == test.table { + tx.AddError(privateError) + } + } + if test.create { + require.NoError(t, model.DB.Callback().Create().Before("gorm:create").Register("security_private_error", callback)) + } else { + require.NoError(t, model.DB.Callback().Query().Before("gorm:query").Register("security_private_error", callback)) + } + response := securityEnrollmentRequest(test.method, test.path, test.body, proof, identity, test.handler) + var body securityEnrollmentResponse + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body)) + assert.Equal(t, http.StatusInternalServerError, response.Code) + assert.False(t, body.Success) + assert.Equal(t, "AUTH_INTERNAL_ERROR", body.Code) + assert.Equal(t, "Internal Server Error", body.Message) + assert.NotContains(t, response.Body.String(), "private") + assert.NotContains(t, response.Body.String(), "SELECT") + }) + } +} + +func TestSecurityEnrollmentPublicErrorsDiscardWrappedDetails(t *testing.T) { + for _, test := range []struct { + err error + code string + message string + }{ + {service.ErrVerificationFailed, "SECURITY_VERIFICATION_FAILED", service.ErrVerificationFailed.Error()}, + {service.ErrVerificationLocked, "SECURITY_VERIFICATION_LOCKED", service.ErrVerificationLocked.Error()}, + {service.ErrOAuthAccountMismatch, "OAUTH_ACCOUNT_MISMATCH", service.ErrOAuthAccountMismatch.Error()}, + {model.ErrTwoFASetupInvalid, "TWOFA_SETUP_INVALID", model.ErrTwoFASetupInvalid.Error()}, + } { + t.Run(test.code, func(t *testing.T) { + response := securityEnrollmentRequest("POST", "/api/verify", "", "", service.AuthIdentity{}, func(c *gin.Context) { + writeSecurityOperationError(c, fmt.Errorf("private database details: %w", test.err)) + }) + var body securityEnrollmentResponse + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body)) + assert.False(t, body.Success) + assert.Equal(t, test.code, body.Code) + assert.Equal(t, test.message, body.Message) + assert.NotContains(t, response.Body.String(), "private") + }) + } +} + +func TestSecurityEnrollmentExpiredAndCrossSessionSetupsCannotActivate(t *testing.T) { + user, identity := setupSecurityEnrollmentTest(t) + setup, err := service.StartTwoFASetup(identity, authorizeSecurityEnrollment(t, identity)) + require.NoError(t, err) + code, err := totp.GenerateCode(setup.Secret, time.Now()) + require.NoError(t, err) + other, err := service.CreateLoginSession(user.Id, "password", "127.0.0.1", "other-session") + require.NoError(t, err) + otherIdentity, err := service.ParseAccessToken(other.AccessToken) + require.NoError(t, err) + assert.ErrorIs(t, service.FinishTwoFASetup(otherIdentity, setup.FlowToken, code), model.ErrTwoFASetupInvalid) + flow, err := model.GetAuthFlow(setup.FlowToken, model.AuthFlowMatch{Purpose: model.AuthFlowPurposeTwoFASetup}) + require.NoError(t, err) + require.NoError(t, model.DB.Model(flow).Update("expires_at", time.Now().Add(-time.Minute)).Error) + assert.ErrorIs(t, service.FinishTwoFASetup(identity, setup.FlowToken, code), model.ErrTwoFASetupInvalid) + stored, err := model.GetTwoFAByUserId(user.Id) + require.NoError(t, err) + assert.False(t, stored.IsEnabled) + storedUser, err := model.GetUserById(user.Id, false) + require.NoError(t, err) + assert.Equal(t, identity.UserAuthVersion, storedUser.AuthVersion) +} + +func TestSecurityEnrollmentOAuthQueriesReachHandlerWithoutLeakingToAccessLogs(t *testing.T) { + var output bytes.Buffer + previous := gin.DefaultWriter + gin.DefaultWriter = &output + t.Cleanup(func() { gin.DefaultWriter = previous }) + router := gin.New() + middleware.SetUpLogger(router) + router.GET("/api/oauth/:provider", func(c *gin.Context) { + assert.Equal(t, "private-code", c.Query("code")) + assert.Equal(t, "private-state", c.Query("state")) + c.Status(http.StatusNoContent) + }) + response := httptest.NewRecorder() + router.ServeHTTP(response, httptest.NewRequest("GET", "/api/oauth/github?code=private-code&state=private-state", nil)) + assert.Equal(t, http.StatusNoContent, response.Code) + assert.Contains(t, output.String(), "/api/oauth/github") + assert.NotContains(t, output.String(), "private-code") + assert.NotContains(t, output.String(), "private-state") +} + +func TestSecurityEnrollmentCustomOAuthUsesExistingBinding(t *testing.T) { + user, identity := setupSecurityEnrollmentTest(t) + require.NoError(t, model.DB.Model(user).Update("password", "").Error) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/token": + assert.NoError(t, r.ParseForm()) + assert.Equal(t, "custom-code", r.Form.Get("code")) + _, _ = w.Write([]byte(`{"access_token":"provider-access-token","token_type":"Bearer"}`)) + case "/userinfo": + assert.Equal(t, "Bearer provider-access-token", r.Header.Get("Authorization")) + _, _ = w.Write([]byte(`{"sub":"custom-user","name":"Existing user"}`)) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(upstream.Close) + provider := oauth.NewGenericOAuthProvider(&model.CustomOAuthProvider{ + Id: 42, Slug: "enrollment-custom", Name: "Custom provider", Enabled: true, + ClientId: "client", ClientSecret: "secret", UserIdField: "sub", + TokenEndpoint: upstream.URL + "/token", UserInfoEndpoint: upstream.URL + "/userinfo", + }) + oauth.RegisterCustom("enrollment-custom", provider) + t.Cleanup(func() { oauth.Unregister("enrollment-custom") }) + require.NoError(t, model.DB.Create(&model.UserOAuthBinding{UserId: user.Id, ProviderId: 42, ProviderUserId: "custom-user"}).Error) + response := securityEnrollmentRequest("GET", "/api/verify/methods?scope=2fa.setup", "", "", identity, GetVerificationMethods) + assert.Contains(t, response.Body.String(), "enrollment-custom") + assert.NotContains(t, response.Body.String(), "custom-user") + response = securityEnrollmentRequest("POST", "/api/oauth/state", `{"provider":"enrollment-custom","intent":"verify","scope":"2fa.setup"}`, "", identity, GenerateOAuthCode) + var body securityEnrollmentResponse + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body)) + require.True(t, body.Success, body.Message) + var started struct { + FlowToken string `json:"flow_token"` + } + require.NoError(t, common.Unmarshal(body.Data, &started)) + response = securityEnrollmentRequest("GET", "/api/oauth/enrollment-custom?state="+started.FlowToken+"&code=custom-code", "", "", identity, func(c *gin.Context) { + c.Params = gin.Params{{Key: "provider", Value: "enrollment-custom"}} + HandleOAuth(c) + }) + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body)) + require.True(t, body.Success, body.Message) + var proof service.SecurityProof + require.NoError(t, common.Unmarshal(body.Data, &proof)) + _, err := service.ConsumeOperationProof(proof.ProofToken, identity, service.VerificationOperation{Scope: "2fa.setup"}) + require.NoError(t, err) + bindings, err := model.GetUserOAuthBindingsByUserId(user.Id) + require.NoError(t, err) + require.Len(t, bindings, 1) + assert.Equal(t, "custom-user", bindings[0].ProviderUserId) +} diff --git a/controller/twofa.go b/controller/twofa.go index ff73707443..1c0d674d1b 100644 --- a/controller/twofa.go +++ b/controller/twofa.go @@ -13,12 +13,6 @@ import ( "github.com/gin-gonic/gin" ) -// Setup2FARequest 设置2FA请求结构 -type Setup2FARequest struct { - Code string `json:"code" binding:"required"` -} - -// Verify2FARequest 验证2FA请求结构 type Verify2FARequest struct { Code string `json:"code" binding:"required"` FlowToken string `json:"flow_token,omitempty"` @@ -28,190 +22,49 @@ type twoFALoginFlowPayload struct { AuthVersion int64 `json:"auth_version"` } -// Setup2FAResponse 设置2FA响应结构 -type Setup2FAResponse struct { - Secret string `json:"secret"` - QRCodeData string `json:"qr_code_data"` - BackupCodes []string `json:"backup_codes"` -} - -// Setup2FA 初始化2FA设置 func Setup2FA(c *gin.Context) { - userId := c.GetInt("id") - - // 检查用户是否已经启用2FA - existing, err := model.GetTwoFAByUserId(userId) + authorization := middleware.RequireSecurityProof(c, service.VerificationOperation{Scope: service.VerificationScopeTwoFASetup}) + if authorization == nil { + return + } + identity, _ := middleware.GetSessionAuthIdentity(c) + setup, err := service.StartTwoFASetup(identity, authorization) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } - if existing != nil && existing.IsEnabled { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "message": "用户已启用2FA,请先禁用后重新设置", - }) - return - } - - // 如果存在已禁用的2FA记录,先删除它 - if existing != nil && !existing.IsEnabled { - if err := existing.DeletePendingTwoFASetup(); err != nil { - common.ApiError(c, err) - return - } - existing = nil // 重置为nil,后续将创建新记录 - } - - // 获取用户信息 - user, err := model.GetUserById(userId, false) - if err != nil { - common.ApiError(c, err) - return - } - - // 生成TOTP密钥 - key, err := common.GenerateTOTPSecret(user.Username) - if err != nil { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "message": "生成2FA密钥失败", - }) - common.SysLog("生成TOTP密钥失败: " + err.Error()) - return - } - - // 生成备用码 - backupCodes, err := common.GenerateBackupCodes() - if err != nil { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "message": "生成备用码失败", - }) - common.SysLog("生成备用码失败: " + err.Error()) - return - } - - // 生成二维码数据 - qrCodeData := common.GenerateQRCodeData(key.Secret(), user.Username) - - // 创建或更新2FA记录(暂未启用) - twoFA := &model.TwoFA{ - UserId: userId, - Secret: key.Secret(), - IsEnabled: false, - } - - if err := twoFA.CreatePendingTwoFASetup(); err != nil { - common.ApiError(c, err) - return - } - - // 创建备用码记录 - if err := model.CreatePendingTwoFASetupBackupCodes(userId, backupCodes); err != nil { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "message": "保存备用码失败", - }) - common.SysLog("保存备用码失败: " + err.Error()) - return - } - - // 记录操作日志 - recordUserSecurityAudit(c, userId, "user.2fa_setup", nil) - - c.JSON(http.StatusOK, gin.H{ - "success": true, - "message": "2FA设置初始化成功,请使用认证器扫描二维码并输入验证码完成设置", - "data": Setup2FAResponse{ - Secret: key.Secret(), - QRCodeData: qrCodeData, - BackupCodes: backupCodes, - }, - }) + recordUserSecurityAudit(c, identity.UserID, "user.2fa_setup", nil) + common.ApiSuccess(c, setup) } -// Enable2FA 启用2FA func Enable2FA(c *gin.Context) { - var req Setup2FARequest - if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "message": "参数错误", - }) - return - } - - userId := c.GetInt("id") - - // 获取2FA记录 - twoFA, err := model.GetTwoFAByUserId(userId) - if err != nil { - common.ApiError(c, err) - return - } - if twoFA == nil { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "message": "请先完成2FA初始化设置", - }) - return - } - if twoFA.IsEnabled { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "message": "2FA已经启用", - }) - return - } - - // 验证TOTP验证码 - cleanCode, err := common.ValidateNumericCode(req.Code) - if err != nil { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "message": err.Error(), - }) - return - } - - if !common.ValidateTOTPCode(twoFA.Secret, cleanCode) { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "message": "验证码或备用码错误,请重试", - }) - return - } - identity, ok := middleware.GetSessionAuthIdentity(c) if !ok { - common.ApiError(c, errors.New("当前认证方式不支持安全验证")) + writeSecurityOperationError(c, service.ErrAuthTokenInvalid) return } - // 启用2FA并原子推进用户鉴权版本 - if err := twoFA.EnableWithAuthVersion(); err != nil { - common.ApiError(c, err) + var req Verify2FARequest + if err := common.DecodeJson(c.Request.Body, &req); err != nil { + common.ApiErrorMsg(c, "参数错误") + return + } + if err := service.FinishTwoFASetup(identity, req.FlowToken, req.Code); err != nil { + writeSecurityOperationError(c, err) return } bundle, err := service.AdvanceCurrentSessionToUserVersion(identity, "twofa_enabled") if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } - - // 记录操作日志 - recordUserSecurityAudit(c, userId, "user.2fa_enable", nil) - - c.JSON(http.StatusOK, gin.H{ - "success": true, - "message": "两步验证启用成功", - "data": authRotationData(bundle), - }) + recordUserSecurityAudit(c, identity.UserID, "user.2fa_enable", nil) + common.ApiSuccess(c, authRotationData(bundle)) } // Disable2FA 禁用2FA func Disable2FA(c *gin.Context) { var req Verify2FARequest - if err := c.ShouldBindJSON(&req); err != nil { + if err := common.DecodeJsonWithValidation(c.Request.Body, &req); err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, "message": "参数错误", @@ -224,7 +77,7 @@ func Disable2FA(c *gin.Context) { // 获取2FA记录 twoFA, err := model.GetTwoFAByUserId(userId) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } if twoFA == nil || !twoFA.IsEnabled { @@ -235,49 +88,24 @@ func Disable2FA(c *gin.Context) { return } - // 验证TOTP验证码或备用码 - cleanCode, err := common.ValidateNumericCode(req.Code) - isValidTOTP := false - isValidBackup := false - - if err == nil { - // 尝试验证TOTP - isValidTOTP, _ = twoFA.ValidateTOTPAndUpdateUsage(cleanCode) - } - - if !isValidTOTP { - // 尝试验证备用码 - isValidBackup, err = twoFA.ValidateBackupCodeAndUpdateUsage(req.Code) - if err != nil { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "message": err.Error(), - }) - return - } - } - - if !isValidTOTP && !isValidBackup { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "message": "验证码或备用码错误,请重试", - }) + if err := service.VerifyTwoFactorCode(twoFA, req.Code); err != nil { + writeSecurityOperationError(c, err) return } identity, ok := middleware.GetSessionAuthIdentity(c) if !ok { - common.ApiError(c, errors.New("当前认证方式不支持安全验证")) + common.ApiErrorMsg(c, "当前认证方式不支持安全验证") return } // 禁用2FA并原子推进用户鉴权版本 if err := model.DisableTwoFAWithAuthVersion(userId); err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } bundle, err := service.AdvanceCurrentSessionToUserVersion(identity, "twofa_disabled") if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } @@ -297,7 +125,7 @@ func Get2FAStatus(c *gin.Context) { twoFA, err := model.GetTwoFAByUserId(userId) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } @@ -330,7 +158,7 @@ func Get2FAStatus(c *gin.Context) { // RegenerateBackupCodes 重新生成备用码 func RegenerateBackupCodes(c *gin.Context) { var req Verify2FARequest - if err := c.ShouldBindJSON(&req); err != nil { + if err := common.DecodeJsonWithValidation(c.Request.Body, &req); err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, "message": "参数错误", @@ -343,7 +171,7 @@ func RegenerateBackupCodes(c *gin.Context) { // 获取2FA记录 twoFA, err := model.GetTwoFAByUserId(userId) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } if twoFA == nil || !twoFA.IsEnabled { @@ -357,26 +185,12 @@ func RegenerateBackupCodes(c *gin.Context) { // 验证TOTP验证码 cleanCode, err := common.ValidateNumericCode(req.Code) if err != nil { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "message": err.Error(), - }) + common.ApiErrorMsg(c, "验证码必须是6位数字") return } - valid, err := twoFA.ValidateTOTPAndUpdateUsage(cleanCode) - if err != nil { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "message": err.Error(), - }) - return - } - if !valid { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "message": "验证码或备用码错误,请重试", - }) + if err := service.VerifyTwoFactorCode(twoFA, cleanCode); err != nil { + writeSecurityOperationError(c, err) return } @@ -393,7 +207,7 @@ func RegenerateBackupCodes(c *gin.Context) { identity, ok := middleware.GetSessionAuthIdentity(c) if !ok { - common.ApiError(c, errors.New("当前认证方式不支持安全验证")) + common.ApiErrorMsg(c, "当前认证方式不支持安全验证") return } // 保存新的备用码并原子推进用户鉴权版本 @@ -407,7 +221,7 @@ func RegenerateBackupCodes(c *gin.Context) { } bundle, err := service.AdvanceCurrentSessionToUserVersion(identity, "twofa_backup_codes_regenerated") if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } @@ -426,7 +240,7 @@ func RegenerateBackupCodes(c *gin.Context) { // Verify2FALogin 登录时验证2FA func Verify2FALogin(c *gin.Context) { var req Verify2FARequest - if err := c.ShouldBindJSON(&req); err != nil { + if err := common.DecodeJsonWithValidation(c.Request.Body, &req); err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, "message": "参数错误", @@ -470,7 +284,7 @@ func Verify2FALogin(c *gin.Context) { // 获取2FA记录 twoFA, err := model.GetTwoFAByUserId(user.Id) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } if twoFA == nil || !twoFA.IsEnabled { @@ -481,33 +295,8 @@ func Verify2FALogin(c *gin.Context) { return } - // 验证TOTP验证码或备用码 - cleanCode, err := common.ValidateNumericCode(req.Code) - isValidTOTP := false - isValidBackup := false - - if err == nil { - // 尝试验证TOTP - isValidTOTP, _ = twoFA.ValidateTOTPAndUpdateUsage(cleanCode) - } - - if !isValidTOTP { - // 尝试验证备用码 - isValidBackup, err = twoFA.ValidateBackupCodeAndUpdateUsage(req.Code) - if err != nil { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "message": err.Error(), - }) - return - } - } - - if !isValidTOTP && !isValidBackup { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "message": "验证码或备用码错误,请重试", - }) + if err := service.VerifyTwoFactorCode(twoFA, req.Code); err != nil { + writeSecurityOperationError(c, err) return } @@ -529,7 +318,7 @@ func Verify2FALogin(c *gin.Context) { func Admin2FAStats(c *gin.Context) { stats, err := model.GetTwoFAStats() if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } @@ -555,7 +344,7 @@ func AdminDisable2FA(c *gin.Context) { // 检查目标用户权限 targetUser, err := model.GetUserById(userId, false) if err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } @@ -577,11 +366,11 @@ func AdminDisable2FA(c *gin.Context) { }) return } - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } if _, err := model.RevokeAllUserSessions(userId, "admin_twofa_disabled"); err != nil { - common.ApiError(c, err) + writeSecurityOperationError(c, err) return } diff --git a/middleware/auth_test.go b/middleware/auth_test.go index 040ec62c03..3893390f47 100644 --- a/middleware/auth_test.go +++ b/middleware/auth_test.go @@ -156,7 +156,10 @@ func TestTryUserAuthCredentialClassification(t *testing.T) { } accessToken, _, err := service.IssueAccessToken(identity) require.NoError(t, err) - securityProof, _, err := service.IssueSecurityProof(identity, "2fa", []string{"channel.key.read"}) + require.NoError(t, model.DB.AutoMigrate(&model.AuthFlow{})) + binding, err := service.BindVerificationOperation(service.VerificationOperation{Scope: "channel.key.read", Context: []byte(`{"channel_id":123}`)}) + require.NoError(t, err) + securityProof, _, err := service.IssueSecurityProof(identity, "2fa", binding) require.NoError(t, err) externalToken, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "iss": "external-issuer", diff --git a/middleware/logger.go b/middleware/logger.go index 90b2d2eef8..bf16b6b61d 100644 --- a/middleware/logger.go +++ b/middleware/logger.go @@ -2,6 +2,7 @@ package middleware import ( "fmt" + "strings" "github.com/QuantumNous/new-api/common" "github.com/gin-gonic/gin" @@ -27,6 +28,12 @@ func SetUpLogger(server *gin.Engine) { if tag == "" { tag = "web" } + path := param.Path + // OAuth callbacks carry one-time codes and state in the query string. + // Redact the log value only; the handler still needs the original query. + if strings.HasPrefix(path, "/api/oauth/") || strings.HasPrefix(path, "/oauth/") { + path, _, _ = strings.Cut(path, "?") + } return fmt.Sprintf("[GIN] %s | %s | %s | %3d | %13v | %15s | %7s %s\n", param.TimeStamp.Format("2006/01/02 - 15:04:05"), tag, @@ -35,7 +42,7 @@ func SetUpLogger(server *gin.Engine) { param.Latency, param.ClientIP, param.Method, - param.Path, + path, ) })) } diff --git a/middleware/secure_verification.go b/middleware/secure_verification.go index 53c47c8859..d60cdaf4c5 100644 --- a/middleware/secure_verification.go +++ b/middleware/secure_verification.go @@ -3,8 +3,11 @@ package middleware import ( "errors" "net/http" + "strconv" "strings" + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/model" "github.com/QuantumNous/new-api/service" "github.com/gin-gonic/gin" ) @@ -13,7 +16,17 @@ import ( // operations validate their narrower proof scopes in their controller. func SecureVerificationRequired() gin.HandlerFunc { return func(c *gin.Context) { - if !RequireSecurityProof(c, "channel.key.read", []string{"2fa", "passkey"}) { + channelID, err := strconv.Atoi(c.Param("id")) + if err != nil || channelID <= 0 { + c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"success": false, "code": "SECURITY_CONTEXT_INVALID", "message": service.ErrVerificationContextInvalid.Error()}) + return + } + context, err := common.Marshal(service.ChannelKeyReadContext{ChannelID: channelID}) + if err != nil { + c.AbortWithStatus(http.StatusInternalServerError) + return + } + if RequireSecurityProof(c, service.VerificationOperation{Scope: service.VerificationScopeChannelKeyRead, Context: context}) == nil { return } c.Set("secure_verified", true) @@ -23,31 +36,43 @@ func SecureVerificationRequired() gin.HandlerFunc { // RequireSecurityProof validates a proof against the authenticated dashboard // session and writes the shared proof error contract on failure. -func RequireSecurityProof(c *gin.Context, requiredScope string, allowedMethods []string) bool { +func RequireSecurityProof(c *gin.Context, operation service.VerificationOperation) *model.AuthFlowAuthorization { identity, ok := GetSessionAuthIdentity(c) if !ok { securityProofError(c, "SECURITY_PROOF_INVALID", "安全验证状态无效") - return false + return nil } raw := strings.TrimSpace(c.GetHeader("X-Security-Proof")) if raw == "" { securityProofError(c, "SECURITY_PROOF_REQUIRED", "需要安全验证") - return false + return nil } - if _, err := service.VerifySecurityProof(raw, identity, requiredScope, allowedMethods); err != nil { + authorization, err := service.ConsumeOperationProof(raw, identity, operation) + if err != nil { switch { case errors.Is(err, service.ErrAuthTokenExpired): securityProofError(c, "SECURITY_PROOF_EXPIRED", "安全验证已过期") case errors.Is(err, service.ErrProofScope): securityProofError(c, "SECURITY_PROOF_SCOPE_MISMATCH", "安全验证范围不匹配") + case errors.Is(err, service.ErrVerificationUnavailable): + securityProofError(c, "SECURITY_METHOD_UNAVAILABLE", service.ErrVerificationUnavailable.Error()) case errors.Is(err, service.ErrProofMethod): securityProofError(c, "SECURITY_PROOF_METHOD_MISMATCH", "安全验证方式不匹配") - default: + case errors.Is(err, service.ErrProofConsumed): + securityProofError(c, "SECURITY_PROOF_CONSUMED", "This verification has already been used. Please verify again.") + case errors.Is(err, service.ErrProofContext): + securityProofError(c, "SECURITY_PROOF_CONTEXT_MISMATCH", "Verification does not match this action's details. Please verify again.") + case errors.Is(err, service.ErrVerificationForbidden): + securityProofError(c, "SECURITY_ACTION_FORBIDDEN", service.ErrVerificationForbidden.Error()) + case errors.Is(err, service.ErrAuthTokenInvalid), errors.Is(err, service.ErrLoginSessionInvalid), errors.Is(err, service.ErrLoginSessionRevoked), errors.Is(err, model.ErrUserSessionInactive): securityProofError(c, "SECURITY_PROOF_INVALID", "安全验证状态无效") + default: + _ = c.Error(err) + c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"success": false, "code": "AUTH_INTERNAL_ERROR", "message": "Please try again later."}) } - return false + return nil } - return true + return authorization } func securityProofError(c *gin.Context, code, message string) { diff --git a/model/auth_flow.go b/model/auth_flow.go index 96bb72065a..5555e79d78 100644 --- a/model/auth_flow.go +++ b/model/auth_flow.go @@ -24,6 +24,9 @@ const ( AuthFlowPurposeTelegramAssertion = "telegram_assertion" AuthFlowIntentLogin = "login" AuthFlowIntentBind = "bind" + AuthFlowIntentVerify = "verify" + AuthFlowPurposeTwoFASetup = "2fa_setup" + AuthFlowPurposeSecurityProof = "security_proof" AuthFlowTokenBytes = 32 AuthFlowDefaultCleanupRetention = 24 * time.Hour ) @@ -72,6 +75,47 @@ type AuthFlowMatch struct { SessionId string } +// AuthSessionIdentity binds an authentication flow to a specific session version. +type AuthSessionIdentity struct { + UserID int `json:"user_id"` + SessionID string `json:"session_id"` + UserAuthVersion int64 `json:"auth_version"` + SessionVersion int64 `json:"session_version"` +} + +// AuthFlowAuthorization is server-owned state carried into a configuration flow +// after a proof has been consumed. ProofID is a database ID, never the proof token. +type AuthFlowAuthorization struct { + AuthSessionIdentity + ProofID int64 `json:"proof_id"` + Scope string `json:"scope"` + ContextHash string `json:"context_hash"` + Method string `json:"method"` +} + +// ValidateAuthSessionWithTx rechecks the authoritative identity while holding the +// user/session locks until the caller's credential change or flow consumption commits. +func ValidateAuthSessionWithTx(tx *gorm.DB, identity AuthSessionIdentity) error { + if identity.UserID <= 0 || identity.SessionID == "" || identity.UserAuthVersion <= 0 || identity.SessionVersion <= 0 { + return ErrUserSessionInactive + } + var user User + if err := lockForUpdate(tx).First(&user, identity.UserID).Error; err != nil { + return err + } + if user.Status != common.UserStatusEnabled || user.AuthVersion != identity.UserAuthVersion { + return ErrUserSessionInactive + } + var session UserSession + if err := lockForUpdate(tx).Where("sid = ? AND user_id = ?", identity.SessionID, identity.UserID).First(&session).Error; err != nil { + return err + } + if session.Status != UserSessionStatusActive || session.RevokedAt != 0 || session.ExpiresAt <= time.Now().Unix() || session.UserAuthVersion != identity.UserAuthVersion || session.Version != identity.SessionVersion { + return ErrUserSessionInactive + } + return nil +} + func applyAuthFlowMatch(query *gorm.DB, token string, match AuthFlowMatch) *gorm.DB { query = query.Where("token_hash = ? AND purpose = ?", authFlowTokenHash(token), match.Purpose) if match.Provider != "" { @@ -94,6 +138,10 @@ func authFlowTokenHash(token string) string { } func CreateAuthFlow(input AuthFlowCreate) (string, *AuthFlow, error) { + return createAuthFlowWithTx(DB, input) +} + +func createAuthFlowWithTx(tx *gorm.DB, input AuthFlowCreate) (string, *AuthFlow, error) { if strings.TrimSpace(input.Purpose) == "" || input.ExpiresAt.IsZero() || !input.ExpiresAt.After(time.Now()) { return "", nil, ErrAuthFlowInvalid } @@ -112,7 +160,7 @@ func CreateAuthFlow(input AuthFlowCreate) (string, *AuthFlow, error) { Payload: input.Payload, ExpiresAt: input.ExpiresAt, } - if err := DB.Create(flow).Error; err != nil { + if err := tx.Create(flow).Error; err != nil { return "", nil, err } return token, flow, nil @@ -192,30 +240,31 @@ func ConsumeAuthFlowWithAction(token string, match AuthFlowMatch, action func(tx } var consumed AuthFlow err := DB.Transaction(func(tx *gorm.DB) error { - query := applyAuthFlowMatch(lockForUpdate(tx), token, match) + // Claim with the first write, rather than upgrading a prior read lock. + // SQLite cannot reliably upgrade two concurrent deferred read transactions. + now := time.Now() + result := applyAuthFlowMatch(tx.Model(&AuthFlow{}), token, match). + Where("consumed_at IS NULL AND expires_at > ?", now). + Update("consumed_at", now) + if result.Error != nil { + return result.Error + } + query := applyAuthFlowMatch(tx, token, match) if err := query.First(&consumed).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return ErrAuthFlowInvalid } return err } - if consumed.ConsumedAt != nil { + if result.RowsAffected != 1 && consumed.ConsumedAt != nil { return ErrAuthFlowConsumed } - now := time.Now() - if !consumed.ExpiresAt.After(now) { + if !consumed.ExpiresAt.After(time.Now()) { return ErrAuthFlowExpired } - result := tx.Model(&AuthFlow{}). - Where("id = ? AND consumed_at IS NULL AND expires_at > ?", consumed.Id, now). - Update("consumed_at", now) - if result.Error != nil { - return result.Error - } if result.RowsAffected != 1 { - return ErrAuthFlowConsumed + return ErrAuthFlowInvalid } - consumed.ConsumedAt = &now if action != nil { if err := action(tx, &consumed); err != nil { return err diff --git a/model/passkey.go b/model/passkey.go index 5bb24d4045..aabaad646b 100644 --- a/model/passkey.go +++ b/model/passkey.go @@ -201,10 +201,26 @@ func upsertPasskeyCredentialWithTx(tx *gorm.DB, credential *PasskeyCredential) e // UpsertPasskeyCredentialWithAuthVersion is reserved for enrollment changes; // assertion sign-count updates must use UpdatePasskeyAssertionState. func UpsertPasskeyCredentialWithAuthVersion(credential *PasskeyCredential) error { + return upsertPasskeyCredentialWithAuthVersion(credential, nil) +} + +func RegisterPasskeyForSession(identity AuthSessionIdentity, credential *PasskeyCredential) error { + return upsertPasskeyCredentialWithAuthVersion(credential, &identity) +} + +func upsertPasskeyCredentialWithAuthVersion(credential *PasskeyCredential, identity *AuthSessionIdentity) error { if credential == nil || credential.UserID <= 0 { return fmt.Errorf("Passkey 保存失败,请重试") } if err := DB.Transaction(func(tx *gorm.DB) error { + if identity != nil { + if identity.UserID != credential.UserID { + return ErrUserSessionInactive + } + if err := ValidateAuthSessionWithTx(tx, *identity); err != nil { + return err + } + } if _, err := IncrementUserAuthVersionWithTx(tx, credential.UserID); err != nil { return err } @@ -216,10 +232,23 @@ func UpsertPasskeyCredentialWithAuthVersion(credential *PasskeyCredential) error } func DeletePasskeyByUserIDWithAuthVersion(userID int) error { + return deletePasskeyWithAuthVersion(userID, nil) +} + +func DeletePasskeyForSession(identity AuthSessionIdentity) error { + return deletePasskeyWithAuthVersion(identity.UserID, &identity) +} + +func deletePasskeyWithAuthVersion(userID int, identity *AuthSessionIdentity) error { if userID == 0 { return fmt.Errorf("删除失败,请重试") } if err := DB.Transaction(func(tx *gorm.DB) error { + if identity != nil { + if err := ValidateAuthSessionWithTx(tx, *identity); err != nil { + return err + } + } var credential PasskeyCredential if err := lockForUpdate(tx).Where("user_id = ?", userID).First(&credential).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { diff --git a/model/twofa.go b/model/twofa.go index 9f2f1f1b84..7775f7ee6e 100644 --- a/model/twofa.go +++ b/model/twofa.go @@ -62,33 +62,6 @@ func IsTwoFAEnabled(userId int) (bool, error) { return twoFA != nil && twoFA.IsEnabled, nil } -// CreatePendingTwoFASetup stores a disabled factor while the user completes -// enrollment. Enabling a factor must use EnableWithAuthVersion. -func (t *TwoFA) CreatePendingTwoFASetup() error { - if t == nil || t.UserId <= 0 || t.IsEnabled { - return errors.New("无效的2FA待验证设置") - } - // 检查用户是否已存在2FA设置 - existing, err := GetTwoFAByUserId(t.UserId) - if err != nil { - return err - } - if existing != nil { - return errors.New("用户已存在2FA设置") - } - - // 验证用户存在 - var user User - if err := DB.First(&user, t.UserId).Error; err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return errors.New("用户不存在") - } - return err - } - - return DB.Create(t).Error -} - func (t *TwoFA) updateUsageState() error { if t.Id == 0 { return errors.New("2FA记录ID不能为空") @@ -100,27 +73,6 @@ func (t *TwoFA) updateUsageState() error { }).Error } -// DeletePendingTwoFASetup removes only an unverified setup. Enabled factors -// must use DisableTwoFAWithAuthVersion. -func (t *TwoFA) DeletePendingTwoFASetup() error { - if t == nil || t.Id == 0 || t.UserId <= 0 { - return errors.New("2FA记录ID不能为空") - } - - return DB.Transaction(func(tx *gorm.DB) error { - var pending TwoFA - if err := lockForUpdate(tx). - Where("id = ? AND user_id = ? AND is_enabled = ?", t.Id, t.UserId, false). - First(&pending).Error; err != nil { - return err - } - if err := tx.Unscoped().Where("user_id = ?", t.UserId).Delete(&TwoFABackupCode{}).Error; err != nil { - return err - } - return tx.Unscoped().Delete(&pending).Error - }) -} - // ResetFailedAttempts 重置失败尝试次数 func (t *TwoFA) ResetFailedAttempts() error { t.FailedAttempts = 0 @@ -184,18 +136,6 @@ func (t *TwoFA) IsLocked() bool { return time.Now().Before(*t.LockedUntil) } -// CreatePendingTwoFASetupBackupCodes stores recovery codes for an unverified -// setup. Regeneration for an enabled factor must advance auth_version. -func CreatePendingTwoFASetupBackupCodes(userId int, codes []string) error { - return DB.Transaction(func(tx *gorm.DB) error { - var pending TwoFA - if err := lockForUpdate(tx).Where("user_id = ? AND is_enabled = ?", userId, false).First(&pending).Error; err != nil { - return err - } - return replaceBackupCodesWithTx(tx, userId, codes) - }) -} - func replaceBackupCodesWithTx(tx *gorm.DB, userId int, codes []string) error { if err := tx.Where("user_id = ?", userId).Delete(&TwoFABackupCode{}).Error; err != nil { return err @@ -298,41 +238,6 @@ func DisableTwoFAWithAuthVersion(userId int) error { return PublishUserAuthCache(userId) } -// EnableWithAuthVersion atomically enables this factor and advances the user -// authentication version so pre-enrollment sessions cannot remain valid. -func (t *TwoFA) EnableWithAuthVersion() error { - if t == nil || t.Id == 0 || t.UserId == 0 { - return errors.New("2FA记录ID不能为空") - } - if err := DB.Transaction(func(tx *gorm.DB) error { - var pending TwoFA - if err := lockForUpdate(tx).Where("id = ? AND user_id = ? AND is_enabled = ?", t.Id, t.UserId, false).First(&pending).Error; err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return ErrTwoFAAlreadyEnabled - } - return err - } - if _, err := IncrementUserAuthVersionWithTx(tx, t.UserId); err != nil { - return err - } - result := tx.Model(&pending). - Updates(map[string]interface{}{"is_enabled": true, "failed_attempts": 0, "locked_until": nil}) - if result.Error != nil { - return result.Error - } - if result.RowsAffected != 1 { - return ErrTwoFAAlreadyEnabled - } - return nil - }); err != nil { - return err - } - t.IsEnabled = true - t.FailedAttempts = 0 - t.LockedUntil = nil - return PublishUserAuthCache(t.UserId) -} - // ValidateTOTPAndUpdateUsage 验证TOTP并更新使用记录 func (t *TwoFA) ValidateTOTPAndUpdateUsage(code string) (bool, error) { // 检查是否被锁定 @@ -344,7 +249,7 @@ func (t *TwoFA) ValidateTOTPAndUpdateUsage(code string) (bool, error) { if !common.ValidateTOTPCode(t.Secret, code) { // 增加失败次数 if err := t.IncrementFailedAttempts(); err != nil { - common.SysLog("更新2FA失败次数失败: " + err.Error()) + return false, err } return false, nil } @@ -356,7 +261,7 @@ func (t *TwoFA) ValidateTOTPAndUpdateUsage(code string) (bool, error) { t.LastUsedAt = &now if err := t.updateUsageState(); err != nil { - common.SysLog("更新2FA使用记录失败: " + err.Error()) + return false, err } return true, nil @@ -378,7 +283,7 @@ func (t *TwoFA) ValidateBackupCodeAndUpdateUsage(code string) (bool, error) { if !valid { // 增加失败次数 if err := t.IncrementFailedAttempts(); err != nil { - common.SysLog("更新2FA失败次数失败: " + err.Error()) + return false, err } return false, nil } @@ -390,7 +295,7 @@ func (t *TwoFA) ValidateBackupCodeAndUpdateUsage(code string) (bool, error) { t.LastUsedAt = &now if err := t.updateUsageState(); err != nil { - common.SysLog("更新2FA使用记录失败: " + err.Error()) + return false, err } return true, nil diff --git a/model/twofa_enrollment.go b/model/twofa_enrollment.go new file mode 100644 index 0000000000..9c38837dfa --- /dev/null +++ b/model/twofa_enrollment.go @@ -0,0 +1,114 @@ +package model + +import ( + "crypto/hmac" + "errors" + "time" + + "github.com/QuantumNous/new-api/common" + "gorm.io/gorm" +) + +var ErrTwoFASetupInvalid = errors.New("The two-factor setup has expired or changed. Start setup again.") +var ErrTwoFACodeInvalid = errors.New("The authenticator code is incorrect.") + +type twoFAEnrollmentPayload struct { + TwoFAID int `json:"twofa_id"` + SecretHash string `json:"secret_hash"` + Authorization *AuthFlowAuthorization `json:"authorization"` +} + +// CreateTwoFAEnrollment stores the pending credential, recovery codes and +// session-bound flow atomically. Reinitialization invalidates the previous setup. +func CreateTwoFAEnrollment(identity AuthSessionIdentity, authorization *AuthFlowAuthorization, secret string, backupCodes []string, expiresAt time.Time) (string, error) { + if authorization == nil || authorization.ProofID <= 0 || authorization.AuthSessionIdentity != identity { + return "", ErrTwoFASetupInvalid + } + var token string + err := DB.Transaction(func(tx *gorm.DB) error { + if err := ValidateAuthSessionWithTx(tx, identity); err != nil { + return err + } + var existing TwoFA + err := lockForUpdate(tx).Where("user_id = ?", identity.UserID).First(&existing).Error + if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { + return err + } + if err == nil { + if existing.IsEnabled { + return ErrTwoFAAlreadyEnabled + } + if err := tx.Unscoped().Delete(&existing).Error; err != nil { + return err + } + } + pending := &TwoFA{UserId: identity.UserID, Secret: secret} + if err := tx.Create(pending).Error; err != nil { + return err + } + if err := replaceBackupCodesWithTx(tx, identity.UserID, backupCodes); err != nil { + return err + } + payload, err := common.Marshal(twoFAEnrollmentPayload{ + TwoFAID: pending.Id, SecretHash: common.GenerateHMACWithKey([]byte("twofa-enrollment:"+common.SessionSecret), secret), + Authorization: authorization, + }) + if err != nil { + return err + } + token, _, err = createAuthFlowWithTx(tx, AuthFlowCreate{ + Purpose: AuthFlowPurposeTwoFASetup, UserId: identity.UserID, SessionId: identity.SessionID, + Payload: string(payload), ExpiresAt: expiresAt, + }) + return err + }) + return token, err +} + +// EnableTwoFAEnrollment validates and consumes one setup in the same transaction +// as factor activation and auth_version advancement. A bad code can be retried. +func EnableTwoFAEnrollment(identity AuthSessionIdentity, token, code string) error { + cleanCode, err := common.ValidateNumericCode(code) + if err != nil { + return ErrTwoFACodeInvalid + } + _, err = ConsumeAuthFlowWithAction(token, AuthFlowMatch{ + Purpose: AuthFlowPurposeTwoFASetup, UserId: identity.UserID, SessionId: identity.SessionID, + }, func(tx *gorm.DB, flow *AuthFlow) error { + var payload twoFAEnrollmentPayload + if err := common.UnmarshalJsonStr(flow.Payload, &payload); err != nil { + return err + } + if payload.Authorization == nil || payload.Authorization.ProofID <= 0 || payload.Authorization.AuthSessionIdentity != identity { + return ErrTwoFASetupInvalid + } + if err := ValidateAuthSessionWithTx(tx, identity); err != nil { + return err + } + var pending TwoFA + if err := lockForUpdate(tx).Where("id = ? AND user_id = ? AND is_enabled = ?", payload.TwoFAID, identity.UserID, false).First(&pending).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return ErrTwoFASetupInvalid + } + return err + } + secretHash := common.GenerateHMACWithKey([]byte("twofa-enrollment:"+common.SessionSecret), pending.Secret) + if !hmac.Equal([]byte(payload.SecretHash), []byte(secretHash)) { + return ErrTwoFASetupInvalid + } + if !common.ValidateTOTPCode(pending.Secret, cleanCode) { + return ErrTwoFACodeInvalid + } + if _, err := IncrementUserAuthVersionWithTx(tx, identity.UserID); err != nil { + return err + } + return tx.Model(&pending).Updates(map[string]any{"is_enabled": true, "failed_attempts": 0, "locked_until": nil}).Error + }) + if errors.Is(err, ErrAuthFlowInvalid) || errors.Is(err, ErrAuthFlowExpired) || errors.Is(err, ErrAuthFlowConsumed) { + return ErrTwoFASetupInvalid + } + if err != nil { + return err + } + return PublishUserAuthCache(identity.UserID) +} diff --git a/model/user_authentication_test.go b/model/user_authentication_test.go index 179232798d..571c9bd482 100644 --- a/model/user_authentication_test.go +++ b/model/user_authentication_test.go @@ -12,6 +12,7 @@ import ( "github.com/QuantumNous/new-api/common" "github.com/go-redis/redis/v8" "github.com/go-webauthn/webauthn/webauthn" + "github.com/pquerna/otp/totp" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gorm.io/gorm" @@ -165,7 +166,9 @@ func TestValidateBackupCodeCanOnlySucceedOnce(t *testing.T) { user := User{Id: 123, Username: "backup-code-user", Password: "password", AuthVersion: 1} require.NoError(t, DB.Create(&user).Error) require.NoError(t, DB.Create(&TwoFA{UserId: user.Id, Secret: "secret", IsEnabled: false}).Error) - require.NoError(t, CreatePendingTwoFASetupBackupCodes(user.Id, []string{code})) + hashedCode, err := common.HashBackupCode(code) + require.NoError(t, err) + require.NoError(t, DB.Create(&TwoFABackupCode{UserId: user.Id, CodeHash: hashedCode}).Error) const attempts = 2 results := make(chan bool, attempts) @@ -203,13 +206,17 @@ func TestValidateBackupCodeCanOnlySucceedOnce(t *testing.T) { func TestPendingTwoFASetupAPIsRejectEnabledFactor(t *testing.T) { truncateTables(t) - user := User{Username: "enabled-twofa-guard", Password: "password", AuthVersion: 1} + user := User{Username: "enabled-twofa-guard", Password: "password", Status: common.UserStatusEnabled, AuthVersion: 1} require.NoError(t, DB.Create(&user).Error) twoFA := TwoFA{UserId: user.Id, Secret: "secret", IsEnabled: true} require.NoError(t, DB.Create(&twoFA).Error) - require.Error(t, CreatePendingTwoFASetupBackupCodes(user.Id, []string{"ABCD-1234"})) - require.Error(t, twoFA.DeletePendingTwoFASetup()) + session := UserSession{SID: "enabled-factor-session", UserID: user.Id, Version: 1, UserAuthVersion: 1, Status: UserSessionStatusActive, ExpiresAt: time.Now().Add(time.Hour).Unix()} + require.NoError(t, DB.Create(&session).Error) + identity := AuthSessionIdentity{UserID: user.Id, SessionID: session.SID, UserAuthVersion: 1, SessionVersion: 1} + authorization := &AuthFlowAuthorization{AuthSessionIdentity: identity, ProofID: 1, Scope: "2fa.setup", ContextHash: "setup-context", Method: "password"} + _, err := CreateTwoFAEnrollment(identity, authorization, "replacement-secret", []string{"ABCD-1234"}, time.Now().Add(time.Minute)) + require.ErrorIs(t, err, ErrTwoFAAlreadyEnabled) var stored TwoFA require.NoError(t, DB.First(&stored, twoFA.Id).Error) @@ -231,12 +238,17 @@ func TestSecurityFactorMutationsAdvanceUserAuthVersion(t *testing.T) { AuthVersion: 1, } require.NoError(t, DB.Create(&user).Error) - twoFA := TwoFA{UserId: user.Id, Secret: "secret", IsEnabled: false} - require.NoError(t, DB.Create(&twoFA).Error) - - require.NoError(t, twoFA.EnableWithAuthVersion()) + session := UserSession{SID: "factor-version-session", UserID: user.Id, Version: 1, UserAuthVersion: 1, Status: UserSessionStatusActive, ExpiresAt: time.Now().Add(time.Hour).Unix()} + require.NoError(t, DB.Create(&session).Error) + identity := AuthSessionIdentity{UserID: user.Id, SessionID: session.SID, UserAuthVersion: 1, SessionVersion: 1} + authorization := &AuthFlowAuthorization{AuthSessionIdentity: identity, ProofID: 1, Scope: "2fa.setup", ContextHash: "setup-context", Method: "password"} + token, err := CreateTwoFAEnrollment(identity, authorization, "JBSWY3DPEHPK3PXP", []string{"ABCD-1234"}, time.Now().Add(time.Minute)) + require.NoError(t, err) + code, err := totp.GenerateCode("JBSWY3DPEHPK3PXP", time.Now()) + require.NoError(t, err) + require.NoError(t, EnableTwoFAEnrollment(identity, token, code)) assertUserAuthVersion(t, user.Id, 2) - assert.ErrorIs(t, twoFA.EnableWithAuthVersion(), ErrTwoFAAlreadyEnabled) + assert.ErrorIs(t, EnableTwoFAEnrollment(identity, token, code), ErrTwoFASetupInvalid) assertUserAuthVersion(t, user.Id, 2) require.NoError(t, ReplaceBackupCodesWithAuthVersion(user.Id, []string{"ABCD-1234"})) assertUserAuthVersion(t, user.Id, 3) diff --git a/oauth/discord.go b/oauth/discord.go index 7f1ce9a696..7ae81aa5ae 100644 --- a/oauth/discord.go +++ b/oauth/discord.go @@ -51,8 +51,6 @@ func (p *DiscordProvider) ExchangeToken(ctx context.Context, code string, c *gin return nil, NewOAuthError(i18n.MsgOAuthInvalidCode, nil) } - logger.LogDebug(ctx, "[OAuth-Discord] ExchangeToken: code=%s...", code[:min(len(code), 10)]) - settings := system_setting.GetDiscordSettings() redirectUri := fmt.Sprintf("%s/oauth/discord", system_setting.ServerAddress) values := url.Values{} diff --git a/oauth/generic.go b/oauth/generic.go index 23ae2273fa..71ca6aeaa7 100644 --- a/oauth/generic.go +++ b/oauth/generic.go @@ -92,8 +92,6 @@ func (p *GenericOAuthProvider) ExchangeToken(ctx context.Context, code string, c return nil, NewOAuthError(i18n.MsgOAuthInvalidCode, nil) } - logger.LogDebug(ctx, "[OAuth-Generic-%s] ExchangeToken: code=%s...", p.config.Slug, code[:min(len(code), 10)]) - redirectUri := fmt.Sprintf("%s/oauth/%s", system_setting.ServerAddress, p.config.Slug) values := url.Values{} values.Set("grant_type", "authorization_code") @@ -150,7 +148,6 @@ func (p *GenericOAuthProvider) ExchangeToken(ctx context.Context, code string, c } bodyStr := string(body) - logger.LogDebug(ctx, "[OAuth-Generic-%s] ExchangeToken response body: %s", p.config.Slug, bodyStr[:min(len(bodyStr), 500)]) // Try to parse as JSON first var tokenResponse struct { @@ -236,7 +233,6 @@ func (p *GenericOAuthProvider) GetUserInfo(ctx context.Context, token *OAuthToke } bodyStr := string(body) - logger.LogDebug(ctx, "[OAuth-Generic-%s] GetUserInfo response body: %s", p.config.Slug, bodyStr[:min(len(bodyStr), 500)]) // Extract fields using gjson (supports JSONPath-like syntax) userId := gjson.Get(bodyStr, p.config.UserIdField).String() diff --git a/oauth/github.go b/oauth/github.go index 524e0fdda3..2274094b8c 100644 --- a/oauth/github.go +++ b/oauth/github.go @@ -50,8 +50,6 @@ func (p *GitHubProvider) ExchangeToken(ctx context.Context, code string, c *gin. return nil, NewOAuthError(i18n.MsgOAuthInvalidCode, nil) } - logger.LogDebug(ctx, "[OAuth-GitHub] ExchangeToken: code=%s...", code[:min(len(code), 10)]) - values := map[string]string{ "client_id": common.GitHubClientId, "client_secret": common.GitHubClientSecret, diff --git a/oauth/linuxdo.go b/oauth/linuxdo.go index cba54b83af..10d7a43e52 100644 --- a/oauth/linuxdo.go +++ b/oauth/linuxdo.go @@ -47,8 +47,6 @@ func (p *LinuxDOProvider) ExchangeToken(ctx context.Context, code string, c *gin return nil, NewOAuthError(i18n.MsgOAuthInvalidCode, nil) } - logger.LogDebug(ctx, "[OAuth-LinuxDO] ExchangeToken: code=%s...", code[:min(len(code), 10)]) - // Get access token using Basic auth tokenEndpoint := common.GetEnvOrDefaultString("LINUX_DO_TOKEN_ENDPOINT", "https://connect.linux.do/oauth2/token") credentials := common.LinuxDOClientId + ":" + common.LinuxDOClientSecret diff --git a/oauth/oidc.go b/oauth/oidc.go index 79582a4edb..df9e51bfe2 100644 --- a/oauth/oidc.go +++ b/oauth/oidc.go @@ -53,8 +53,6 @@ func (p *OIDCProvider) ExchangeToken(ctx context.Context, code string, c *gin.Co return nil, NewOAuthError(i18n.MsgOAuthInvalidCode, nil) } - logger.LogDebug(ctx, "[OAuth-OIDC] ExchangeToken: code=%s...", code[:min(len(code), 10)]) - settings := system_setting.GetOIDCSettings() redirectUri := fmt.Sprintf("%s/oauth/oidc", system_setting.ServerAddress) values := url.Values{} diff --git a/router/api-router.go b/router/api-router.go index f8ff56902c..120ab856b9 100644 --- a/router/api-router.go +++ b/router/api-router.go @@ -65,7 +65,8 @@ func SetApiRouter(router *gin.Engine) { apiRouter.POST("/waffo-pancake/webhook/:env", anonymousRequestBodyLimit, controller.WaffoPancakeWebhook) // Universal secure verification routes - apiRouter.POST("/verify", middleware.UserAuth(), middleware.CriticalRateLimit(), middleware.DisableCache(), controller.UniversalVerify) + apiRouter.GET("/verify/methods", middleware.UserAuth(), middleware.DisableCache(), controller.GetVerificationMethods) + apiRouter.POST("/verify", middleware.UserAuth(), middleware.CriticalRateLimit(), middleware.UserCriticalRateLimit("security-verification"), middleware.DisableCache(), controller.UniversalVerify) userRoute := apiRouter.Group("/user") { @@ -98,10 +99,10 @@ func SetApiRouter(router *gin.Engine) { selfRoute.POST("/token", middleware.CriticalRateLimit(), middleware.UserCriticalRateLimit("access-token"), middleware.DisableCache(), controller.GenerateAccessToken) selfRoute.DELETE("/token", middleware.CriticalRateLimit(), middleware.DisableCache(), controller.RevokeAccessToken) selfRoute.GET("/passkey", controller.PasskeyStatus) - selfRoute.POST("/passkey/register/begin", middleware.DisableCache(), controller.PasskeyRegisterBegin) - selfRoute.POST("/passkey/register/finish", middleware.DisableCache(), controller.PasskeyRegisterFinish) - selfRoute.POST("/passkey/verify/begin", middleware.DisableCache(), controller.PasskeyVerifyBegin) - selfRoute.POST("/passkey/verify/finish", middleware.DisableCache(), controller.PasskeyVerifyFinish) + selfRoute.POST("/passkey/register/begin", middleware.UserCriticalRateLimit("security-verification"), middleware.DisableCache(), controller.PasskeyRegisterBegin) + selfRoute.POST("/passkey/register/finish", middleware.UserCriticalRateLimit("security-verification"), middleware.DisableCache(), controller.PasskeyRegisterFinish) + selfRoute.POST("/passkey/verify/begin", middleware.UserCriticalRateLimit("security-verification"), middleware.DisableCache(), controller.PasskeyVerifyBegin) + selfRoute.POST("/passkey/verify/finish", middleware.UserCriticalRateLimit("security-verification"), middleware.DisableCache(), controller.PasskeyVerifyFinish) selfRoute.DELETE("/passkey", middleware.DisableCache(), controller.PasskeyDelete) selfRoute.GET("/aff", controller.GetAffCode) selfRoute.GET("/topup/info", controller.GetTopUpInfo) @@ -121,8 +122,8 @@ func SetApiRouter(router *gin.Engine) { // 2FA routes selfRoute.GET("/2fa/status", controller.Get2FAStatus) - selfRoute.POST("/2fa/setup", middleware.DisableCache(), controller.Setup2FA) - selfRoute.POST("/2fa/enable", middleware.DisableCache(), controller.Enable2FA) + selfRoute.POST("/2fa/setup", middleware.UserCriticalRateLimit("security-verification"), middleware.DisableCache(), controller.Setup2FA) + selfRoute.POST("/2fa/enable", middleware.UserCriticalRateLimit("security-verification"), middleware.DisableCache(), controller.Enable2FA) selfRoute.POST("/2fa/disable", middleware.DisableCache(), controller.Disable2FA) selfRoute.POST("/2fa/backup_codes", middleware.DisableCache(), controller.RegenerateBackupCodes) diff --git a/service/auth_token.go b/service/auth_token.go index 309e8dd086..b6ea1df929 100644 --- a/service/auth_token.go +++ b/service/auth_token.go @@ -10,13 +10,14 @@ import ( "time" "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/model" "github.com/golang-jwt/jwt/v5" "github.com/google/uuid" ) const ( AccessTokenTTL = 15 * time.Minute - SecurityProofTTL = 5 * time.Minute + SecurityProofTTL = time.Minute LoginSessionTTL = 30 * 24 * time.Hour RefreshReplayWindow = 30 * time.Second accessTokenUse = "access" @@ -30,16 +31,13 @@ var ( ErrAuthTokenExpired = errors.New("authentication token has expired") ErrProofScope = errors.New("security proof scope mismatch") ErrProofMethod = errors.New("security proof method mismatch") + ErrProofContext = errors.New("security proof context mismatch") + ErrProofConsumed = errors.New("security proof has already been consumed") ) // AuthIdentity is the server-validated identity attached to dashboard requests. // Role, status and group are deliberately loaded from the user cache instead of JWT claims. -type AuthIdentity struct { - UserID int - SessionID string - UserAuthVersion int64 - SessionVersion int64 -} +type AuthIdentity = model.AuthSessionIdentity type authClaims struct { TokenUse string `json:"token_use"` @@ -48,6 +46,7 @@ type authClaims struct { SessionVersion int64 `json:"sv"` Method string `json:"method,omitempty"` Scopes []string `json:"scopes,omitempty"` + ContextHash string `json:"context_hash,omitempty"` jwt.RegisteredClaims } @@ -129,20 +128,28 @@ func ParseDashboardAccessToken(raw string) (identity AuthIdentity, internal bool return identity, true, err } -func IssueSecurityProof(identity AuthIdentity, method string, scopes []string) (string, int64, error) { +func IssueSecurityProof(identity AuthIdentity, method string, binding VerificationBinding) (string, int64, error) { method = strings.TrimSpace(method) - if identity.UserID <= 0 || identity.SessionID == "" || identity.UserAuthVersion <= 0 || identity.SessionVersion <= 0 || method == "" || len(scopes) == 0 { + if identity.UserID <= 0 || identity.SessionID == "" || identity.UserAuthVersion <= 0 || identity.SessionVersion <= 0 || method == "" || binding.Scope == "" || binding.ContextHash == "" { return "", 0, ErrAuthTokenInvalid } now := time.Now() - expiresAt := now.Add(SecurityProofTTL) + expiresAt := now.Add(SecurityProofTTL).Truncate(time.Second) + proofID, _, err := model.CreateAuthFlow(model.AuthFlowCreate{ + Purpose: model.AuthFlowPurposeSecurityProof, UserId: identity.UserID, + SessionId: identity.SessionID, ExpiresAt: expiresAt, + }) + if err != nil { + return "", 0, err + } claims := authClaims{ TokenUse: securityProofTokenUse, SessionID: identity.SessionID, UserAuthVersion: identity.UserAuthVersion, SessionVersion: identity.SessionVersion, Method: method, - Scopes: append([]string(nil), scopes...), + Scopes: []string{binding.Scope}, + ContextHash: binding.ContextHash, RegisteredClaims: jwt.RegisteredClaims{ Issuer: authTokenIssuer, Subject: strconv.Itoa(identity.UserID), @@ -150,45 +157,32 @@ func IssueSecurityProof(identity AuthIdentity, method string, scopes []string) ( ExpiresAt: jwt.NewNumericDate(expiresAt), NotBefore: jwt.NewNumericDate(now.Add(-5 * time.Second)), IssuedAt: jwt.NewNumericDate(now), - ID: uuid.NewString(), + ID: proofID, }, } signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(authSigningKey(securityProofTokenUse)) return signed, expiresAt.Unix(), err } -func VerifySecurityProof(raw string, identity AuthIdentity, requiredScope string, allowedMethods []string) (string, error) { +func verifySecurityProof(raw string, identity AuthIdentity, binding VerificationBinding) (*authClaims, error) { claims, err := parseAuthClaims(raw, securityProofTokenUse, authSigningKey(securityProofTokenUse)) if err != nil { - return "", err + return nil, err } userID, err := strconv.Atoi(claims.Subject) if err != nil || userID != identity.UserID || claims.SessionID != identity.SessionID || claims.UserAuthVersion != identity.UserAuthVersion || claims.SessionVersion != identity.SessionVersion { - return "", ErrAuthTokenInvalid + return nil, ErrAuthTokenInvalid } - methodAllowed := len(allowedMethods) == 0 - for _, method := range allowedMethods { - if hmac.Equal([]byte(claims.Method), []byte(method)) { - methodAllowed = true - break - } + if len(claims.Scopes) != 1 || claims.Scopes[0] != binding.Scope { + return nil, ErrProofScope } - if !methodAllowed { - return "", ErrProofMethod + if claims.ContextHash == "" { + return nil, ErrAuthTokenInvalid } - if requiredScope != "" { - found := false - for _, scope := range claims.Scopes { - if hmac.Equal([]byte(scope), []byte(requiredScope)) { - found = true - break - } - } - if !found { - return "", ErrProofScope - } + if !hmac.Equal([]byte(claims.ContextHash), []byte(binding.ContextHash)) { + return nil, ErrProofContext } - return claims.Method, nil + return claims, nil } func parseAuthClaims(raw, expectedUse string, key []byte) (*authClaims, error) { diff --git a/service/auth_token_test.go b/service/auth_token_test.go index e99573576a..9fa82383dc 100644 --- a/service/auth_token_test.go +++ b/service/auth_token_test.go @@ -19,6 +19,7 @@ func useTestSessionSecret(t *testing.T) { } func TestAccessTokenRoundTripAndPurposeIsolation(t *testing.T) { + setupAuthSessionTestDB(t) useTestSessionSecret(t) identity := AuthIdentity{UserID: 42, SessionID: "session-1", UserAuthVersion: 3, SessionVersion: 2} @@ -30,7 +31,9 @@ func TestAccessTokenRoundTripAndPurposeIsolation(t *testing.T) { require.NoError(t, err) assert.Equal(t, identity, parsed) - proof, _, err := IssueSecurityProof(identity, "2fa", []string{"channel.key.read"}) + binding, err := BindVerificationOperation(VerificationOperation{Scope: "channel.key.read", Context: []byte(`{"channel_id":123}`)}) + require.NoError(t, err) + proof, _, err := IssueSecurityProof(identity, "2fa", binding) require.NoError(t, err) _, err = ParseAccessToken(proof) assert.ErrorIs(t, err, ErrAuthTokenInvalid) @@ -57,6 +60,7 @@ func TestAccessTokenRejectsTampering(t *testing.T) { } func TestDashboardAccessTokenClassification(t *testing.T) { + setupAuthSessionTestDB(t) useTestSessionSecret(t) identity, internal, err := ParseDashboardAccessToken("opaque.key.with-dots") @@ -87,9 +91,11 @@ func TestDashboardAccessTokenClassification(t *testing.T) { require.NoError(t, err) assert.False(t, internal) + binding, err := BindVerificationOperation(VerificationOperation{Scope: "channel.key.read", Context: []byte(`{"channel_id":123}`)}) + require.NoError(t, err) proof, _, err := IssueSecurityProof(AuthIdentity{ UserID: 42, SessionID: "session-1", UserAuthVersion: 1, SessionVersion: 1, - }, "2fa", []string{"channel.key.read"}) + }, "2fa", binding) require.NoError(t, err) _, internal, err = ParseDashboardAccessToken(proof) assert.True(t, internal) @@ -117,24 +123,40 @@ func TestDashboardAccessTokenClassification(t *testing.T) { assert.ErrorIs(t, err, ErrAuthTokenExpired) } -func TestSecurityProofBindsIdentityMethodAndScope(t *testing.T) { +func TestSecurityProofBindsIdentityAndOperation(t *testing.T) { + setupAuthSessionTestDB(t) useTestSessionSecret(t) identity := AuthIdentity{UserID: 42, SessionID: "session-1", UserAuthVersion: 3, SessionVersion: 2} - proof, _, err := IssueSecurityProof(identity, "2fa", []string{"channel.key.read"}) + operation := VerificationOperation{Scope: "channel.key.read", Context: []byte(`{"channel_id":123}`)} + binding, err := BindVerificationOperation(operation) + require.NoError(t, err) + proof, _, err := IssueSecurityProof(identity, "2fa", binding) require.NoError(t, err) - method, err := VerifySecurityProof(proof, identity, "channel.key.read", []string{"2fa", "passkey"}) + claims, err := verifySecurityProof(proof, identity, binding) require.NoError(t, err) - assert.Equal(t, "2fa", method) + assert.Equal(t, "2fa", claims.Method) - _, err = VerifySecurityProof(proof, identity, "passkey.delete", []string{"2fa"}) + wrongScope, err := BindVerificationOperation(VerificationOperation{Scope: "passkey.delete"}) + require.NoError(t, err) + _, err = verifySecurityProof(proof, identity, wrongScope) assert.ErrorIs(t, err, ErrProofScope) - _, err = VerifySecurityProof(proof, identity, "channel.key.read", []string{"passkey"}) - assert.ErrorIs(t, err, ErrProofMethod) + otherChannel, err := BindVerificationOperation(VerificationOperation{Scope: "channel.key.read", Context: []byte(`{"channel_id":456}`)}) + require.NoError(t, err) + _, err = verifySecurityProof(proof, identity, otherChannel) + assert.ErrorIs(t, err, ErrProofContext) otherSession := identity otherSession.SessionID = "session-2" - _, err = VerifySecurityProof(proof, otherSession, "channel.key.read", []string{"2fa"}) + _, err = verifySecurityProof(proof, otherSession, binding) assert.True(t, errors.Is(err, ErrAuthTokenInvalid)) + + claims, err = parseAuthClaims(proof, securityProofTokenUse, authSigningKey(securityProofTokenUse)) + require.NoError(t, err) + claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(-time.Minute)) + expired, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(authSigningKey(securityProofTokenUse)) + require.NoError(t, err) + _, err = ConsumeOperationProof(expired, identity, operation) + assert.ErrorIs(t, err, ErrAuthTokenExpired) } diff --git a/service/oauth_verification.go b/service/oauth_verification.go new file mode 100644 index 0000000000..4c7a2ef590 --- /dev/null +++ b/service/oauth_verification.go @@ -0,0 +1,44 @@ +package service + +import "errors" + +var ErrOAuthAccountMismatch = errors.New("The OAuth account does not match the account linked to your profile.") + +type OAuthVerificationFlow struct { + Scope string `json:"scope"` + ContextHash string `json:"context_hash"` + ProviderUserID string `json:"provider_user_id"` + UserAuthVersion int64 `json:"auth_version"` + SessionVersion int64 `json:"session_version"` +} + +func StartOAuthVerification(identity AuthIdentity, operation VerificationOperation, provider string) (*OAuthVerificationFlow, error) { + binding, err := BindVerificationOperation(operation) + if err != nil { + return nil, err + } + providerUserID, err := GetOAuthVerificationBinding(identity, binding.Scope, provider) + if err != nil { + return nil, err + } + return &OAuthVerificationFlow{ + Scope: binding.Scope, ContextHash: binding.ContextHash, ProviderUserID: providerUserID, + UserAuthVersion: identity.UserAuthVersion, SessionVersion: identity.SessionVersion, + }, nil +} + +// FinishOAuthVerification only verifies an existing binding. It deliberately +// never calls OAuth's login or find-or-create-user paths. +func FinishOAuthVerification(identity AuthIdentity, provider, actualUserID string, flow *OAuthVerificationFlow) (*SecurityProof, error) { + if flow == nil || flow.ContextHash == "" || flow.UserAuthVersion != identity.UserAuthVersion || flow.SessionVersion != identity.SessionVersion { + return nil, ErrAuthTokenInvalid + } + expectedUserID, err := GetOAuthVerificationBinding(identity, flow.Scope, provider) + if err != nil { + return nil, err + } + if actualUserID == "" || actualUserID != expectedUserID || actualUserID != flow.ProviderUserID { + return nil, ErrOAuthAccountMismatch + } + return CompleteSecurityVerification(identity, VerificationBinding{Scope: flow.Scope, ContextHash: flow.ContextHash}, VerificationMethodOAuth) +} diff --git a/service/passkey/session.go b/service/passkey/session.go index 3753f5158e..c5d5c59573 100644 --- a/service/passkey/session.go +++ b/service/passkey/session.go @@ -8,30 +8,42 @@ import ( "github.com/QuantumNous/new-api/model" webauthn "github.com/go-webauthn/webauthn/webauthn" + "gorm.io/gorm" ) -var errSessionNotFound = errors.New("Passkey 会话不存在或已过期") - const passkeyFlowTTL = 5 * time.Minute type flowPayload struct { SessionData webauthn.SessionData `json:"session_data"` - Scope string `json:"scope,omitempty"` + Security FlowSecurity `json:"security"` } -func CreateSessionDataFlow(purpose string, userID int, sessionID, scope string, data *webauthn.SessionData) (string, int64, error) { +type FlowSecurity struct { + model.AuthSessionIdentity + Scope string `json:"scope"` + ContextHash string `json:"context_hash"` + Authorization *model.AuthFlowAuthorization `json:"authorization,omitempty"` +} + +func CreateSessionDataFlow(purpose string, security FlowSecurity, data *webauthn.SessionData) (string, int64, error) { if data == nil { return "", 0, errors.New("Passkey 会话数据不能为空") } - payload, err := common.Marshal(flowPayload{SessionData: *data, Scope: scope}) + if purpose != model.AuthFlowPurposePasskeyLogin && (security.UserID <= 0 || security.SessionID == "" || security.Scope == "" || security.ContextHash == "" || security.UserAuthVersion <= 0 || security.SessionVersion <= 0) { + return "", 0, model.ErrAuthFlowInvalid + } + if purpose == model.AuthFlowPurposePasskeyRegister && (security.Authorization == nil || security.Authorization.ProofID <= 0 || security.Authorization.AuthSessionIdentity != security.AuthSessionIdentity) { + return "", 0, model.ErrAuthFlowInvalid + } + payload, err := common.Marshal(flowPayload{SessionData: *data, Security: security}) if err != nil { return "", 0, err } expiresAt := time.Now().Add(passkeyFlowTTL) token, _, err := model.CreateAuthFlow(model.AuthFlowCreate{ Purpose: purpose, - UserId: userID, - SessionId: sessionID, + UserId: security.UserID, + SessionId: security.SessionID, Payload: string(payload), ExpiresAt: expiresAt, }) @@ -41,21 +53,30 @@ func CreateSessionDataFlow(purpose string, userID int, sessionID, scope string, return token, expiresAt.Unix(), nil } -func PopSessionDataFlow(token, purpose string, userID int, sessionID string) (*webauthn.SessionData, string, error) { - flow, err := model.ConsumeAuthFlow(token, model.AuthFlowMatch{ +func PopSessionDataFlow(token, purpose string, identity model.AuthSessionIdentity) (*webauthn.SessionData, *FlowSecurity, error) { + var payload flowPayload + _, err := model.ConsumeAuthFlowWithAction(token, model.AuthFlowMatch{ Purpose: purpose, - UserId: userID, - SessionId: sessionID, + UserId: identity.UserID, + SessionId: identity.SessionID, + }, func(tx *gorm.DB, flow *model.AuthFlow) error { + if err := common.UnmarshalJsonStr(flow.Payload, &payload); err != nil { + return err + } + if purpose == model.AuthFlowPurposePasskeyLogin { + return nil + } + security := payload.Security + if security.AuthSessionIdentity != identity || security.Scope == "" || security.ContextHash == "" { + return model.ErrAuthFlowInvalid + } + if purpose == model.AuthFlowPurposePasskeyRegister && (security.Authorization == nil || security.Authorization.ProofID <= 0 || security.Authorization.AuthSessionIdentity != identity) { + return model.ErrAuthFlowInvalid + } + return model.ValidateAuthSessionWithTx(tx, identity) }) if err != nil { - if errors.Is(err, model.ErrAuthFlowInvalid) || errors.Is(err, model.ErrAuthFlowExpired) || errors.Is(err, model.ErrAuthFlowConsumed) { - return nil, "", errSessionNotFound - } - return nil, "", err + return nil, nil, err } - var payload flowPayload - if err := common.UnmarshalJsonStr(flow.Payload, &payload); err != nil { - return nil, "", err - } - return &payload.SessionData, payload.Scope, nil + return &payload.SessionData, &payload.Security, nil } diff --git a/service/security_verification.go b/service/security_verification.go new file mode 100644 index 0000000000..4c880f0e20 --- /dev/null +++ b/service/security_verification.go @@ -0,0 +1,438 @@ +package service + +import ( + "crypto/hmac" + "encoding/json" + "errors" + "sort" + "strings" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/model" + "github.com/QuantumNous/new-api/oauth" + "github.com/QuantumNous/new-api/setting/system_setting" + "gorm.io/gorm" +) + +const ( + VerificationMethodTwoFA = "2fa" + VerificationMethodPasskey = "passkey" + VerificationMethodPassword = "password" + VerificationMethodOAuth = "oauth" + VerificationScopeChannelKeyRead = "channel.key.read" + VerificationScopePasskeyRegister = "passkey.register" + VerificationScopePasskeyDelete = "passkey.delete" + VerificationScopeTwoFASetup = "2fa.setup" +) + +var ( + ErrVerificationFailed = errors.New("Verification failed. Please try again.") + ErrVerificationUnavailable = errors.New("This verification method is currently unavailable.") + ErrVerificationLocked = errors.New("Two-factor authentication is temporarily locked.") + ErrVerificationFlowRequired = errors.New("This verification method requires its dedicated verification flow.") + ErrVerificationContextInvalid = errors.New("The action details are invalid.") + ErrVerificationForbidden = errors.New("You do not have permission to perform this action.") +) + +// VerificationOperation describes the action being authorized, independently of +// its authentication method. Each scope owns a strict, normalized context schema. +type VerificationOperation struct { + Scope string `json:"scope"` + Context json.RawMessage `json:"context,omitempty"` +} + +type ChannelKeyReadContext struct { + ChannelID int `json:"channel_id"` +} + +// VerificationBinding contains no original operation parameters. It can safely +// travel through a signed proof or a server-owned interactive verification flow. +type VerificationBinding struct { + Scope string `json:"scope"` + ContextHash string `json:"context_hash"` +} + +func BindVerificationOperation(operation VerificationOperation) (VerificationBinding, error) { + var fields map[string]json.RawMessage + if len(operation.Context) > 0 { + if common.GetJsonType(operation.Context) != "object" || common.Unmarshal(operation.Context, &fields) != nil { + return VerificationBinding{}, ErrVerificationContextInvalid + } + } + var normalized any + switch operation.Scope { + case VerificationScopeChannelKeyRead: + var context ChannelKeyReadContext + if len(fields) != 1 || common.Unmarshal(fields["channel_id"], &context.ChannelID) != nil || context.ChannelID <= 0 { + return VerificationBinding{}, ErrVerificationContextInvalid + } + normalized = context + case VerificationScopePasskeyRegister, VerificationScopePasskeyDelete, VerificationScopeTwoFASetup: + if len(fields) != 0 { + return VerificationBinding{}, ErrVerificationContextInvalid + } + normalized = struct{}{} + default: + return VerificationBinding{}, ErrProofScope + } + payload, err := common.Marshal(struct { + Scope string `json:"scope"` + Context any `json:"context"` + }{Scope: operation.Scope, Context: normalized}) + if err != nil { + return VerificationBinding{}, err + } + return VerificationBinding{ + Scope: operation.Scope, + ContextHash: common.GenerateHMACWithKey(authSigningKey("verification-context"), string(payload)), + }, nil +} + +type SecurityProof struct { + ProofToken string `json:"proof_token"` + ExpiresAt int64 `json:"expires_at"` + Method string `json:"method"` + Scope string `json:"scope"` +} + +type VerificationMethodOption struct { + Method string `json:"method"` + Available bool `json:"available"` + Reason string `json:"reason,omitempty"` +} + +type VerificationOAuthProvider struct { + Slug string `json:"slug"` + Name string `json:"name"` + UserID string `json:"-"` +} + +type VerificationRequirements struct { + Scope string `json:"scope"` + Methods []VerificationMethodOption `json:"methods"` + OAuthProviders []VerificationOAuthProvider `json:"oauth_providers"` + PasswordEncryptionEnabled bool `json:"password_encryption_enabled"` +} + +type verificationAccountState struct { + HasPassword bool + HasTwoFA bool + TwoFALocked bool + HasPasskey bool + PasskeyEnabled bool +} + +// securityVerificationPolicy is the only operation-to-method policy. Device +// support and disabled providers never turn an enrolled factor into an absent one. +func securityVerificationPolicy(scope string, state verificationAccountState) ([]VerificationMethodOption, error) { + var methods []string + switch scope { + case VerificationScopeChannelKeyRead: + if state.HasTwoFA { + methods = append(methods, VerificationMethodTwoFA) + } + if state.HasPasskey { + methods = append(methods, VerificationMethodPasskey) + } + case VerificationScopePasskeyDelete: + if state.HasTwoFA { + methods = []string{VerificationMethodTwoFA} + } else if state.HasPasskey { + methods = []string{VerificationMethodPasskey} + } + case VerificationScopePasskeyRegister, VerificationScopeTwoFASetup: + if scope == VerificationScopeTwoFASetup && state.HasTwoFA { + return nil, model.ErrTwoFAAlreadyEnabled + } + switch { + case state.HasTwoFA: + methods = []string{VerificationMethodTwoFA} + case state.HasPasskey: + methods = []string{VerificationMethodPasskey} + case state.HasPassword: + methods = []string{VerificationMethodPassword} + default: + methods = []string{VerificationMethodOAuth} + } + default: + return nil, ErrProofScope + } + options := make([]VerificationMethodOption, 0, len(methods)) + for _, method := range methods { + option := VerificationMethodOption{Method: method, Available: true} + if method == VerificationMethodTwoFA && state.TwoFALocked { + option.Available, option.Reason = false, ErrVerificationLocked.Error() + } + if !state.PasskeyEnabled && (method == VerificationMethodPasskey || scope == VerificationScopePasskeyRegister) { + option.Available, option.Reason = false, "Passkey authentication is disabled." + } + options = append(options, option) + } + return options, nil +} + +func GetVerificationRequirements(identity AuthIdentity, scope string) (*VerificationRequirements, error) { + user, err := model.GetUserById(identity.UserID, true) + if err != nil { + return nil, err + } + if user.Status != common.UserStatusEnabled || user.AuthVersion != identity.UserAuthVersion { + return nil, ErrAuthTokenInvalid + } + if scope == VerificationScopeChannelKeyRead && user.Role != common.RoleRootUser { + return nil, ErrVerificationForbidden + } + twoFA, err := model.GetTwoFAByUserId(user.Id) + if err != nil { + return nil, err + } + _, err = model.GetPasskeyByUserID(user.Id) + if err != nil && !errors.Is(err, model.ErrPasskeyNotFound) { + return nil, err + } + state := verificationAccountState{ + HasPassword: user.Password != "", HasTwoFA: twoFA != nil && twoFA.IsEnabled, + TwoFALocked: twoFA != nil && twoFA.IsLocked(), HasPasskey: err == nil, + PasskeyEnabled: system_setting.GetPasskeySettings().Enabled, + } + methods, err := securityVerificationPolicy(scope, state) + if err != nil { + return nil, err + } + requirements := &VerificationRequirements{Scope: scope, Methods: methods, OAuthProviders: []VerificationOAuthProvider{}, PasswordEncryptionEnabled: common.PasswordLoginEncryptionEnabled} + for i := range methods { + if methods[i].Method != VerificationMethodOAuth { + continue + } + requirements.OAuthProviders, err = verificationOAuthProviders(user) + if err != nil { + return nil, err + } + if len(requirements.OAuthProviders) == 0 { + methods[i].Available, methods[i].Reason = false, "No linked OAuth provider is available." + } + } + return requirements, nil +} + +func verificationOAuthProviders(user *model.User) ([]VerificationOAuthProvider, error) { + bindings := map[int]string{} + if len(oauth.GetEnabledCustomProviders()) > 0 { + stored, err := model.GetUserOAuthBindingsByUserId(user.Id) + if err != nil { + return nil, err + } + for _, binding := range stored { + bindings[binding.ProviderId] = binding.ProviderUserId + } + } + providers := []VerificationOAuthProvider{} + for slug, provider := range oauth.GetAllProviders() { + if !provider.IsEnabled() { + continue + } + var userID string + if custom, ok := provider.(*oauth.GenericOAuthProvider); ok { + userID = bindings[custom.GetProviderId()] + } else { + switch provider.ProviderUserIDColumn() { + case "github_id": + userID = user.GitHubId + case "discord_id": + userID = user.DiscordId + case "oidc_id": + userID = user.OidcId + case "linux_do_id": + userID = user.LinuxDOId + } + } + if userID != "" { + providers = append(providers, VerificationOAuthProvider{Slug: slug, Name: provider.GetName(), UserID: userID}) + } + } + sort.Slice(providers, func(i, j int) bool { return providers[i].Slug < providers[j].Slug }) + return providers, nil +} + +func RequireVerificationMethod(identity AuthIdentity, scope, method string) (*VerificationRequirements, error) { + requirements, err := GetVerificationRequirements(identity, scope) + if err != nil { + return nil, err + } + for _, option := range requirements.Methods { + if option.Method != method { + continue + } + if !option.Available { + return nil, ErrVerificationUnavailable + } + return requirements, nil + } + return nil, ErrProofMethod +} + +// CompleteSecurityVerification runs after the concrete authentication ceremony. +// Recheck the session and policy after potentially slow external authentication. +func CompleteSecurityVerification(identity AuthIdentity, binding VerificationBinding, method string) (*SecurityProof, error) { + if _, _, err := ValidateLoginSession(identity); err != nil { + return nil, err + } + if _, err := RequireVerificationMethod(identity, binding.Scope, method); err != nil { + return nil, err + } + token, expiresAt, err := IssueSecurityProof(identity, method, binding) + if err != nil { + return nil, err + } + return &SecurityProof{ProofToken: token, ExpiresAt: expiresAt, Method: method, Scope: binding.Scope}, nil +} + +// ConsumeOperationProof accepts a proof at most once. The consumption commits +// before the caller performs its action; an action failure must not restore it. +func ConsumeOperationProof(raw string, identity AuthIdentity, operation VerificationOperation) (*model.AuthFlowAuthorization, error) { + binding, err := BindVerificationOperation(operation) + if err != nil { + return nil, err + } + claims, err := verifySecurityProof(raw, identity, binding) + if err != nil { + return nil, err + } + if _, _, err := ValidateLoginSession(identity); err != nil { + return nil, err + } + if _, err := RequireVerificationMethod(identity, binding.Scope, claims.Method); err != nil { + return nil, err + } + flow, err := model.ConsumeAuthFlowWithAction(claims.ID, model.AuthFlowMatch{ + Purpose: model.AuthFlowPurposeSecurityProof, UserId: identity.UserID, SessionId: identity.SessionID, + }, func(tx *gorm.DB, _ *model.AuthFlow) error { + return model.ValidateAuthSessionWithTx(tx, identity) + }) + switch { + case errors.Is(err, model.ErrAuthFlowConsumed): + return nil, ErrProofConsumed + case errors.Is(err, model.ErrAuthFlowExpired): + return nil, ErrAuthTokenExpired + case errors.Is(err, model.ErrAuthFlowInvalid): + return nil, ErrAuthTokenInvalid + case err != nil: + return nil, err + } + return &model.AuthFlowAuthorization{ + AuthSessionIdentity: identity, ProofID: flow.Id, Scope: binding.Scope, + ContextHash: binding.ContextHash, Method: claims.Method, + }, nil +} + +// ValidateFlowAuthorization permits a dedicated configuration flow to outlive +// its consumed proof, while retaining its operation, session and method policy. +func ValidateFlowAuthorization(identity AuthIdentity, operation VerificationOperation, authorization *model.AuthFlowAuthorization) error { + if authorization == nil || authorization.ProofID <= 0 || authorization.AuthSessionIdentity != identity { + return model.ErrAuthFlowInvalid + } + binding, err := BindVerificationOperation(operation) + if err != nil { + return err + } + if authorization.Scope != binding.Scope || !hmac.Equal([]byte(authorization.ContextHash), []byte(binding.ContextHash)) { + return model.ErrAuthFlowInvalid + } + if _, _, err := ValidateLoginSession(identity); err != nil { + return err + } + _, err = RequireVerificationMethod(identity, binding.Scope, authorization.Method) + return err +} + +type VerificationInput struct { + Method string `json:"method"` + Scope string `json:"scope"` + Context json.RawMessage `json:"context,omitempty"` + Code string `json:"code,omitempty"` + Password string `json:"password,omitempty"` + PasswordEncrypted string `json:"password_encrypted,omitempty"` + EncryptionKeyID string `json:"encryption_key_id,omitempty"` +} + +func VerifySecurityInput(identity AuthIdentity, input VerificationInput) (*SecurityProof, error) { + binding, err := BindVerificationOperation(VerificationOperation{Scope: input.Scope, Context: input.Context}) + if err != nil { + return nil, err + } + if _, err := RequireVerificationMethod(identity, input.Scope, input.Method); err != nil { + return nil, err + } + switch input.Method { + case VerificationMethodPassword: + password := input.Password + if common.PasswordLoginEncryptionEnabled { + var err error + password, err = common.DecryptPassword(input.PasswordEncrypted, input.EncryptionKeyID) + if err != nil { + return nil, ErrVerificationFailed + } + } + user, err := model.GetUserById(identity.UserID, true) + if err != nil { + return nil, err + } + if password == "" || user.Password == "" || !common.ValidatePasswordAndHash(password, user.Password) { + return nil, ErrVerificationFailed + } + case VerificationMethodTwoFA: + twoFA, err := model.GetTwoFAByUserId(identity.UserID) + if err != nil { + return nil, err + } + if err := VerifyTwoFactorCode(twoFA, input.Code); err != nil { + return nil, err + } + case VerificationMethodPasskey, VerificationMethodOAuth: + return nil, ErrVerificationFlowRequired + default: + return nil, ErrProofMethod + } + return CompleteSecurityVerification(identity, binding, input.Method) +} + +// VerifyTwoFactorCode classifies the input before verification so one failed +// submission cannot increment the failure counter for both TOTP and backup codes. +func VerifyTwoFactorCode(twoFA *model.TwoFA, code string) error { + if twoFA == nil || !twoFA.IsEnabled { + return model.ErrTwoFANotEnabled + } + if twoFA.IsLocked() { + return ErrVerificationLocked + } + code = strings.TrimSpace(code) + var valid bool + var err error + if numeric, numericErr := common.ValidateNumericCode(code); numericErr == nil { + valid, err = twoFA.ValidateTOTPAndUpdateUsage(numeric) + } else if common.ValidateBackupCode(code) { + valid, err = twoFA.ValidateBackupCodeAndUpdateUsage(code) + } else { + err = twoFA.IncrementFailedAttempts() + } + if err != nil { + return err + } + if !valid { + return ErrVerificationFailed + } + return nil +} + +func GetOAuthVerificationBinding(identity AuthIdentity, scope, provider string) (string, error) { + requirements, err := RequireVerificationMethod(identity, scope, VerificationMethodOAuth) + if err != nil { + return "", err + } + for _, linked := range requirements.OAuthProviders { + if linked.Slug == provider { + return linked.UserID, nil + } + } + return "", ErrVerificationUnavailable +} diff --git a/service/twofa.go b/service/twofa.go new file mode 100644 index 0000000000..a9d22d874b --- /dev/null +++ b/service/twofa.go @@ -0,0 +1,66 @@ +package service + +import ( + "errors" + "time" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/model" +) + +type TwoFASetup struct { + Secret string `json:"secret"` + QRCodeData string `json:"qr_code_data"` + BackupCodes []string `json:"backup_codes"` + FlowToken string `json:"flow_token"` + ExpiresAt int64 `json:"expires_at"` +} + +func StartTwoFASetup(identity AuthIdentity, authorization *model.AuthFlowAuthorization) (*TwoFASetup, error) { + if err := ValidateFlowAuthorization(identity, VerificationOperation{Scope: VerificationScopeTwoFASetup}, authorization); err != nil { + return nil, err + } + user, err := model.GetUserById(identity.UserID, false) + if err != nil { + return nil, err + } + key, err := common.GenerateTOTPSecret(user.Username) + if err != nil { + return nil, err + } + codes, err := common.GenerateBackupCodes() + if err != nil { + return nil, err + } + expiresAt := time.Now().Add(5 * time.Minute) + flowToken, err := model.CreateTwoFAEnrollment(identity, authorization, key.Secret(), codes, expiresAt) + if err != nil { + return nil, err + } + return &TwoFASetup{Secret: key.Secret(), QRCodeData: common.GenerateQRCodeData(key.Secret(), user.Username), BackupCodes: codes, FlowToken: flowToken, ExpiresAt: expiresAt.Unix()}, nil +} + +func FinishTwoFASetup(identity AuthIdentity, flowToken, code string) error { + flow, err := model.GetAuthFlow(flowToken, model.AuthFlowMatch{ + Purpose: model.AuthFlowPurposeTwoFASetup, UserId: identity.UserID, SessionId: identity.SessionID, + }) + if errors.Is(err, model.ErrAuthFlowInvalid) || errors.Is(err, model.ErrAuthFlowExpired) || errors.Is(err, model.ErrAuthFlowConsumed) { + return model.ErrTwoFASetupInvalid + } + if err != nil { + return err + } + var payload struct { + Authorization *model.AuthFlowAuthorization `json:"authorization"` + } + if err := common.UnmarshalJsonStr(flow.Payload, &payload); err != nil { + return err + } + if err := ValidateFlowAuthorization(identity, VerificationOperation{Scope: VerificationScopeTwoFASetup}, payload.Authorization); err != nil { + if errors.Is(err, model.ErrAuthFlowInvalid) { + return model.ErrTwoFASetupInvalid + } + return err + } + return model.EnableTwoFAEnrollment(identity, flowToken, code) +} diff --git a/web/AGENTS.md b/web/AGENTS.md index a85898bdc8..cee313ba1d 100644 --- a/web/AGENTS.md +++ b/web/AGENTS.md @@ -22,7 +22,7 @@ | 图表 | @visactor/vchart、@visactor/react-vchart | | 工具 | qrcode.react、oxfmt、oxlint、vitest(可选) | -优先选用成熟、维护良好的开源库;仅在现有库无法满足或需特殊适配时自行实现,并评估可维护性与通用性。 +优先复用项目已有组件与能力(见 [3.3 组件](#33-组件));项目内无合适实现时,再评估已安装依赖及成熟、维护良好的开源库。仅在复用、组合或合理扩展仍无法满足需求时自行实现,并说明具体能力缺口。 --- @@ -81,6 +81,26 @@ ### 3.3 组件 +**先检索,再复用,最后才新增(强制)** + +- **开发前检索**:新增或修改 UI 前,必须读取项目 `shadcn-ui` 技能,使用 `rg --files` / `rg` 检索 `src/components/` 和相关 `src/features/`;涉及通用交互时同时检查 `src/hooks/`。按用途和行为查找,不能只查准备新增的组件名。阅读候选组件的实现、props 和实际调用示例后再确定方案。 +- **复用顺序**:优先使用满足场景的项目业务封装;能力不足时,先评估现有 props、插槽、组合方式或兼容扩展。业务封装确实不适用时,再用 `src/components/ui/` 中已有基础组件组合。项目内仍有能力缺口时,才评估引入组件或新增实现;查外部 registry 不能替代项目内检索。 +- **复用到行为层**:仅使用 `Button`、`Dialog`、`AlertDialog` 等基础组件,不代表已经复用了对应的复制、确认、弹窗布局等通用能力。已有业务封装能覆盖时,必须使用该封装,禁止在 feature 内重新拼装同一套交互、状态和样式。 +- **新增条件**:新增替代实现前,必须明确候选组件缺少的具体能力,并在变更说明或 PR 中记录候选路径及不能复用、组合或兼容扩展的原因。文案、图标、尺寸、颜色或所在页面不同,不构成重复实现的理由;优先通过已有 API 和主题约定处理这些差异。 +- **合理组合**:允许新增承载业务数据、权限、事件和内容的 feature 组件,但其中的通用 UI 与交互必须继续复用。扩展公共组件需保持已有调用行为,不能为单个页面塞入无关业务逻辑,也不能为消除少量相似代码建立过度通用的抽象。 +- **基础元素边界**:业务代码中,已有基础组件覆盖的按钮、输入框、选择器、弹层等控件,必须使用项目组件,不能手写同等控件或直接绕过封装调用底层库。普通语义化布局、隐藏字段及现有组件无法表达的特殊控件可使用原生元素;特殊控件仍须说明能力缺口并满足可访问性要求。 + +以下为常用检索入口,不能把本表当作完整组件清单: + +| 场景 | 优先检查的项目入口 | +| --- | --- | +| 通用弹窗布局 | `@/components/dialog` | +| 删除、危险操作及普通确认 | `@/components/confirm-dialog` | +| 复制按钮与剪贴板交互 | `@/components/copy-button`、`@/hooks/use-copy-to-clipboard` | +| 空状态、加载状态、错误状态 | `@/components/empty-state`、`@/components/loading-state`、`@/components/error-state` | +| 表格、分页、工具栏及列表布局 | `@/components/data-table`,先读该目录的 `README.md` 和公开导出 | +| 按钮、输入、选择、提示等基础控件 | `@/components/ui/`,以 `components.json` 和本地实现为准 | + - 使用函数式组件与 Hooks,单一职责;组件 props 须有明确类型(接口或类型别名)。 - **Props 使用**:组件 props 非必要不要解构,直接使用 `props.xxx` 访问属性,保持代码清晰(详见 [3.2 代码风格与类型](#32-代码风格与类型))。 - 单文件超过约 200 行时考虑拆分子组件或将逻辑抽到自定义 Hooks;类型定义可与组件同文件或放在同模块的 `types` 中。 @@ -182,6 +202,7 @@ - 提交信息清晰、符合项目约定,描述变更内容与原因,中英文统一即可。 - 变更需经过代码审查,符合本文档规范,并关注质量、性能与安全。 +- UI 变更完成前必须检查新增组件、基础组件导入及手写交互是否绕过已有业务封装;发现重复实现应在本次变更范围内改为复用。保留的新实现需在变更说明中说明能力缺口,typecheck、lint 和测试通过不能替代此项检查。 - 重大功能或规范变更时更新相关文档与 `AGENTS.md`。 --- @@ -193,3 +214,4 @@ - **2026-01-29**:重组文档结构,合并重复内容,明确主次与交叉引用。 - **2026-01-31**:在 3.2 中补充「类型检查」要求:改动 TS/TSX 后须执行 typecheck 并修复至无错。 - **2026-06-21**:在 3.2 中补充「Lint 检查」要求:完成代码改动前须修复所涉及文件的所有 lint error。 +- **2026-09-06**:明确组件复用的强制检索流程、业务封装优先级、新增条件、常用入口及审查要求。 diff --git a/web/src/features/auth/api.ts b/web/src/features/auth/api.ts index d1257483b9..a83ce78f53 100644 --- a/web/src/features/auth/api.ts +++ b/web/src/features/auth/api.ts @@ -19,6 +19,7 @@ For commercial licensing, please contact support@quantumnous.com import axios from 'axios' import { api, refreshAuthentication, type RefreshOutcome } from '@/lib/api' +import { AuthOperationError } from '@/lib/secure-verification' import { useAuthStore } from '@/stores/auth-store' import { @@ -27,6 +28,7 @@ import { } from './lib/password-encryption' import { getAffiliateCode } from './lib/storage' import type { TelegramAuthorization } from './lib/telegram-login' +import type { VerificationOperation } from './secure-verification/types' import type { LoginPayload, LoginResponse, @@ -166,13 +168,26 @@ export async function githubOAuthStart(clientId: string, state: string) { // Get OAuth state for CSRF protection export async function createOAuthFlow( provider: string, - intent: 'login' | 'bind' + intent: 'login' | 'bind' | 'verify', + operation?: VerificationOperation, + signal?: AbortSignal ): Promise { const aff = intent === 'login' ? getAffiliateCode() : '' const res = await api.post( '/api/oauth/state', - { provider, intent, aff: aff || undefined }, - { skipAuthRefresh: intent === 'login' } + { + provider, + intent, + aff: aff || undefined, + scope: operation?.scope, + ...(operation?.context ? { context: operation.context } : {}), + }, + { + skipAuthRefresh: intent === 'login', + signal, + skipBusinessError: true, + skipErrorHandler: true, + } ) if (res.data?.success) { if (typeof res.data.data === 'string') return res.data.data @@ -180,7 +195,10 @@ export async function createOAuthFlow( return res.data.data.flow_token } } - throw new Error(res.data?.message || 'Failed to initialize OAuth') + throw new AuthOperationError( + res.data?.message || 'Failed to initialize OAuth', + res.data?.code + ) } // WeChat login by authorization code diff --git a/web/src/features/auth/components/oauth-callback-screen.tsx b/web/src/features/auth/components/oauth-callback-screen.tsx index 100bdf1219..77cbffb2ac 100644 --- a/web/src/features/auth/components/oauth-callback-screen.tsx +++ b/web/src/features/auth/components/oauth-callback-screen.tsx @@ -25,7 +25,7 @@ import { AuthLayout } from '../auth-layout' type OAuthCallbackScreenProps = { provider: string - mode: 'login' | 'bind' + mode: 'login' | 'bind' | 'verify' } type ProviderMeta = { @@ -72,23 +72,30 @@ export function OAuthCallbackScreen({ }, [provider]) const providerLabel = t(label) - const isBindMode = mode === 'bind' - - const headline = isBindMode - ? t('Binding your {{provider}} account', { provider: providerLabel }) - : t('Signing you in with {{provider}}', { provider: providerLabel }) - - const description = isBindMode - ? t('Hang tight while we securely link this account to your profile.') - : t('Hang tight while we finish connecting your account.') - - const secondaryNote = isBindMode - ? t( - 'You can close this tab once the binding completes or a success message appears in the original window.' - ) - : t( - "You'll be redirected automatically. You can return to the previous page if nothing happens after a few seconds." - ) + let headline = t('Signing you in with {{provider}}', { + provider: providerLabel, + }) + let description = t('Hang tight while we finish connecting your account.') + let secondaryNote = t( + "You'll be redirected automatically. You can return to the previous page if nothing happens after a few seconds." + ) + if (mode === 'bind') { + headline = t('Binding your {{provider}} account', { + provider: providerLabel, + }) + description = t( + 'Hang tight while we securely link this account to your profile.' + ) + } + if (mode === 'verify') { + headline = t('Verifying your {{provider}} account', { + provider: providerLabel, + }) + description = t('Confirming the account linked to your profile.') + } + if (mode !== 'login') { + secondaryNote = t('Return to the original window to continue.') + } return ( diff --git a/web/src/features/auth/constants.ts b/web/src/features/auth/constants.ts index 687a81efb7..b3293320c3 100644 --- a/web/src/features/auth/constants.ts +++ b/web/src/features/auth/constants.ts @@ -75,6 +75,6 @@ export const PASSWORD_RESET_COUNTDOWN = 30 // seconds // OAuth Constants // ============================================================================ -export const OAUTH_BIND_CALLBACK_MESSAGE = 'oauth:binding:callback' -export const OAUTH_BIND_RESULT_MESSAGE = 'oauth:binding:result' +export const OAUTH_POPUP_CALLBACK_MESSAGE = 'oauth:popup:callback' +export const OAUTH_POPUP_RESULT_MESSAGE = 'oauth:popup:result' export const TELEGRAM_BIND_RESULT_MESSAGE = 'telegram:binding:result' diff --git a/web/src/features/auth/lib/__tests__/oauth-callback-mode.test.ts b/web/src/features/auth/lib/__tests__/oauth-callback-mode.test.ts index 75b87c79e1..ca3a214784 100644 --- a/web/src/features/auth/lib/__tests__/oauth-callback-mode.test.ts +++ b/web/src/features/auth/lib/__tests__/oauth-callback-mode.test.ts @@ -20,7 +20,7 @@ import { describe, expect, test } from 'vitest' import { getOAuthSessionStorage, - markOAuthBindPopup, + markOAuthPopup, resolveOAuthCallbackMode, type OAuthModeStorage, } from '../oauth-callback-mode' @@ -39,7 +39,7 @@ const bindState = 'bind-state' describe('resolveOAuthCallbackMode', () => { test('matching provider and state mark is treated as a bind flow', () => { const storage = fakeStorage() - expect(markOAuthBindPopup(storage, 'oidc', bindState)).toBe(true) + expect(markOAuthPopup(storage, 'oidc', bindState, 'bind')).toBe(true) expect( resolveOAuthCallbackMode('oidc', bindState, { @@ -49,6 +49,25 @@ describe('resolveOAuthCallbackMode', () => { ).toBe('bind') }) + test('verification markers cannot be confused with account binding', () => { + const storage = fakeStorage() + expect( + markOAuthPopup(storage, 'oidc', 'verification-state', 'verify') + ).toBe(true) + expect( + resolveOAuthCallbackMode('oidc', 'verification-state', { + opener: openOpener, + storage, + }) + ).toBe('verify') + expect( + resolveOAuthCallbackMode('oidc', bindState, { + opener: openOpener, + storage, + }) + ).toBe('login') + }) + // Regression: a tab opened from an external link (Slack, e-mail, another // site) keeps a live window.opener across the cross-origin round trip to the // identity provider. Treating that opener as proof of a bind flow made every @@ -66,7 +85,7 @@ describe('resolveOAuthCallbackMode', () => { test('bind marker for another provider does not hijack this callback', () => { const storage = fakeStorage() - markOAuthBindPopup(storage, 'github', bindState) + markOAuthPopup(storage, 'github', bindState, 'bind') expect( resolveOAuthCallbackMode('oidc', bindState, { @@ -78,7 +97,7 @@ describe('resolveOAuthCallbackMode', () => { test('stale bind marker does not hijack a later callback', () => { const storage = fakeStorage() - markOAuthBindPopup(storage, 'oidc', 'previous-state') + markOAuthPopup(storage, 'oidc', 'previous-state', 'bind') expect( resolveOAuthCallbackMode('oidc', bindState, { @@ -90,7 +109,7 @@ describe('resolveOAuthCallbackMode', () => { test('bind marker without an opener falls back to login', () => { const storage = fakeStorage() - markOAuthBindPopup(storage, 'oidc', bindState) + markOAuthPopup(storage, 'oidc', bindState, 'bind') expect( resolveOAuthCallbackMode('oidc', bindState, { @@ -102,7 +121,7 @@ describe('resolveOAuthCallbackMode', () => { test('closed opener falls back to login', () => { const storage = fakeStorage() - markOAuthBindPopup(storage, 'oidc', bindState) + markOAuthPopup(storage, 'oidc', bindState, 'bind') expect( resolveOAuthCallbackMode('oidc', bindState, { @@ -157,16 +176,17 @@ describe('OAuth bind popup storage', () => { }, } - expect(markOAuthBindPopup(null, 'oidc', bindState)).toBe(false) - expect(markOAuthBindPopup(storage, 'oidc', bindState)).toBe(false) + expect(markOAuthPopup(null, 'oidc', bindState, 'bind')).toBe(false) + expect(markOAuthPopup(storage, 'oidc', bindState, 'bind')).toBe(false) expect( - markOAuthBindPopup( + markOAuthPopup( { getItem: () => null, setItem: () => undefined, }, 'oidc', - bindState + bindState, + 'bind' ) ).toBe(false) }) diff --git a/web/src/features/auth/lib/__tests__/oauth-popup.test.ts b/web/src/features/auth/lib/__tests__/oauth-popup.test.ts new file mode 100644 index 0000000000..ac02309588 --- /dev/null +++ b/web/src/features/auth/lib/__tests__/oauth-popup.test.ts @@ -0,0 +1,192 @@ +/* +Copyright (C) 2023-2026 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ +import { afterEach, expect, it, vi } from 'vitest' + +import { AuthOperationError } from '@/lib/secure-verification' + +import { OAUTH_POPUP_CALLBACK_MESSAGE } from '../../constants' +import { openOAuthPopup } from '../oauth-popup' + +function popupWindow() { + const storage = new Map() + const popup = { + closed: false, + location: { replace: vi.fn() }, + sessionStorage: { + setItem: (key: string, value: string) => storage.set(key, value), + getItem: (key: string) => storage.get(key) ?? null, + }, + close: vi.fn(() => { + popup.closed = true + }), + postMessage: vi.fn(), + } + vi.spyOn(window, 'open').mockReturnValue(popup as unknown as Window) + return popup +} + +function callbackMessage( + popup: unknown, + overrides: Record = {}, + origin = window.location.origin +) { + const event = new MessageEvent('message', { + origin, + data: { + type: OAUTH_POPUP_CALLBACK_MESSAGE, + intent: 'verify', + provider: 'github', + state: 'state', + code: 'code', + ...overrides, + }, + }) + Object.defineProperty(event, 'source', { value: popup }) + window.dispatchEvent(event) +} + +afterEach(() => { + vi.restoreAllMocks() + vi.useRealTimers() +}) + +it('accepts only the matching popup, origin, intent, provider and state', async () => { + const popup = popupWindow() + const controller = new AbortController() + const prepared = Promise.resolve({ + state: 'state', + url: 'https://example.com/authorize', + }) + const resolved = vi.fn() + const result = openOAuthPopup({ + provider: 'github', + intent: 'verify', + signal: controller.signal, + prepare: () => prepared, + }).then((exchange) => { + resolved(exchange) + return exchange + }) + await prepared + expect(popup.location.replace).toHaveBeenCalledWith( + 'https://example.com/authorize' + ) + callbackMessage({}, {}) + callbackMessage(popup, {}, 'https://untrusted.example') + callbackMessage(popup, { intent: 'bind' }) + callbackMessage(popup, { provider: 'discord' }) + callbackMessage(popup, { state: 'old-state' }) + await Promise.resolve() + expect(resolved).not.toHaveBeenCalled() + callbackMessage(popup) + callbackMessage(popup) + const exchange = await result + expect(resolved).toHaveBeenCalledTimes(1) + expect(exchange.callback).toEqual({ + provider: 'github', + state: 'state', + code: 'code', + error: undefined, + errorDescription: undefined, + }) + exchange.finish({ success: true }) + expect(popup.closed).toBe(true) +}) + +it('closes an aborted popup and ignores a late authorization response', async () => { + const popup = popupWindow() + const controller = new AbortController() + let complete!: (value: { state: string; url: string }) => void + const prepared = new Promise<{ state: string; url: string }>((resolve) => { + complete = resolve + }) + const result = openOAuthPopup({ + provider: 'github', + intent: 'bind', + signal: controller.signal, + prepare: () => prepared, + }) + const rejected = expect(result).rejects.toBeInstanceOf(AuthOperationError) + controller.abort() + await rejected + complete({ state: 'state', url: 'https://example.com/authorize' }) + await prepared + expect(popup.closed).toBe(true) + expect(popup.location.replace).not.toHaveBeenCalled() +}) + +it('aborts the callback request if the user closes the popup before it finishes', async () => { + vi.useFakeTimers() + const popup = popupWindow() + const prepared = Promise.resolve({ + state: 'state', + url: 'https://example.com/authorize', + }) + const result = openOAuthPopup({ + provider: 'github', + intent: 'verify', + signal: new AbortController().signal, + prepare: () => prepared, + }) + await prepared + callbackMessage(popup) + const exchange = await result + popup.closed = true + await vi.advanceTimersByTimeAsync(500) + expect(exchange.signal.aborted).toBe(true) + expect(exchange.signal.reason).toMatchObject({ code: 'AUTH_CANCELLED' }) + expect(vi.getTimerCount()).toBe(0) +}) + +it('reports a blocked popup without starting authorization', async () => { + vi.spyOn(window, 'open').mockReturnValue(null) + const prepare = vi.fn() + await expect( + openOAuthPopup({ + provider: 'github', + intent: 'verify', + signal: new AbortController().signal, + prepare, + }) + ).rejects.toThrow('OAuth pop-up was blocked') + expect(prepare).not.toHaveBeenCalled() +}) + +it('times out an unfinished authorization and clears its listeners and timers', async () => { + vi.useFakeTimers() + const popup = popupWindow() + const prepared = Promise.resolve({ + state: 'state', + url: 'https://example.com/authorize', + }) + const result = openOAuthPopup({ + provider: 'github', + intent: 'verify', + signal: new AbortController().signal, + prepare: () => prepared, + }) + const rejected = expect(result).rejects.toThrow( + 'OAuth authorization timed out. Please try again.' + ) + await prepared + await vi.advanceTimersByTimeAsync(10 * 60_000) + await rejected + expect(popup.closed).toBe(true) + expect(vi.getTimerCount()).toBe(0) +}) diff --git a/web/src/features/auth/lib/oauth-callback-mode.ts b/web/src/features/auth/lib/oauth-callback-mode.ts index 64c136c8d7..4a830ed880 100644 --- a/web/src/features/auth/lib/oauth-callback-mode.ts +++ b/web/src/features/auth/lib/oauth-callback-mode.ts @@ -17,25 +17,7 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ -/** - * Tells apart the two OAuth callbacks that land on the same `/oauth/:provider` - * route: an account **bind**, which runs inside a popup we opened, and a plain - * **login** redirect, which runs in the user's own tab. - * - * `window.opener` alone cannot make that call. Any tab opened from an external - * link (`target="_blank"`, Slack, mail clients, another site) carries a live - * opener, and that opener survives the cross-origin round trip to the identity - * provider. Such a login callback used to be misread as a bind, so it posted a - * handshake to a window that speaks no such protocol and sat on the binding - * screen until the deadline elapsed. - * - * The popup we open for a bind is same-origin (`about:blank`) before it is sent - * to the provider, so we stamp its own sessionStorage. That stamp rides along - * through the provider round trip and is scoped to the popup alone, which makes - * it positive proof of a bind flow. - */ - -const OAUTH_BIND_FLOW_KEY_PREFIX = 'oauth_bind_flow:' +const OAUTH_POPUP_FLOW_KEY_PREFIX = 'oauth_popup_flow:' /** Minimal shape of `sessionStorage`, kept structural so tests can fake it. */ export interface OAuthModeStorage { @@ -58,7 +40,7 @@ export interface OAuthCallbackModeContext { storage: OAuthModeStorage | null | undefined } -export type OAuthCallbackMode = 'login' | 'bind' +export type OAuthCallbackMode = 'login' | 'bind' | 'verify' /** * Access `sessionStorage` without letting browser privacy settings crash the @@ -75,20 +57,22 @@ export function getOAuthSessionStorage( } /** - * Stamp a freshly opened, still same-origin popup as an OAuth bind flow. + * Stamp a freshly opened, still same-origin popup as an OAuth popup flow. * Call this before navigating the popup to the provider. */ -export function markOAuthBindPopup( +export function markOAuthPopup( storage: OAuthModeStorage | null | undefined, provider: string, - state: string + state: string, + intent: 'bind' | 'verify' ): boolean { if (!storage || !provider || !state) return false try { - const key = `${OAUTH_BIND_FLOW_KEY_PREFIX}${provider}` - storage.setItem(key, state) - return storage.getItem(key) === state + const key = `${OAUTH_POPUP_FLOW_KEY_PREFIX}${provider}` + const marker = JSON.stringify({ state, intent }) + storage.setItem(key, marker) + return storage.getItem(key) === marker } catch { return false } @@ -109,12 +93,24 @@ export function resolveOAuthCallbackMode( ): OAuthCallbackMode { if (!opener || opener.closed || !storage || !state) return 'login' - let markedState: string | null = null try { - markedState = storage.getItem(`${OAUTH_BIND_FLOW_KEY_PREFIX}${provider}`) + const value = storage.getItem(`${OAUTH_POPUP_FLOW_KEY_PREFIX}${provider}`) + if (!value) return 'login' + const marker: unknown = JSON.parse(value) + if ( + !marker || + typeof marker !== 'object' || + !('state' in marker) || + !('intent' in marker) + ) { + return 'login' + } + if (marker.state !== state) return 'login' + if (marker.intent === 'bind' || marker.intent === 'verify') { + return marker.intent + } } catch { return 'login' } - - return markedState === state ? 'bind' : 'login' + return 'login' } diff --git a/web/src/features/auth/lib/oauth-popup.ts b/web/src/features/auth/lib/oauth-popup.ts new file mode 100644 index 0000000000..7180503830 --- /dev/null +++ b/web/src/features/auth/lib/oauth-popup.ts @@ -0,0 +1,183 @@ +/* +Copyright (C) 2023-2026 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ +import { AuthOperationError } from '@/lib/secure-verification' + +import { + OAUTH_POPUP_CALLBACK_MESSAGE, + OAUTH_POPUP_RESULT_MESSAGE, +} from '../constants' +import { watchOAuthPopupClosed } from './oauth-bind-window' +import { getOAuthSessionStorage, markOAuthPopup } from './oauth-callback-mode' + +export interface OAuthPopupCallback { + provider: string + state: string + code?: string + error?: string + errorDescription?: string +} + +export interface OAuthPopupExchange { + callback: OAuthPopupCallback + signal: AbortSignal + finish: (result: { success: boolean; message?: string }) => void +} + +interface OAuthPopupOptions { + provider: string + intent: 'bind' | 'verify' + signal: AbortSignal + prepare: (signal: AbortSignal) => Promise<{ state: string; url: string }> +} + +// Window transport only: account binding and security verification each submit +// their own authenticated callback request after receiving the exchange. +export function openOAuthPopup( + options: OAuthPopupOptions +): Promise { + if (options.signal.aborted) return Promise.reject(options.signal.reason) + const popup = window.open('', '_blank') + if (!popup) { + return Promise.reject(new AuthOperationError('OAuth pop-up was blocked')) + } + const controller = new AbortController() + return new Promise((resolve, reject) => { + let state = '' + let received = false + let finished = false + let stopCloseWatcher: () => void = () => undefined + + const cleanup = () => { + window.removeEventListener('message', onMessage) + options.signal.removeEventListener('abort', onAbort) + stopCloseWatcher() + clearTimeout(deadline) + } + const fail = (error: unknown) => { + if (finished) return + finished = true + const failure = AuthOperationError.from(error) + controller.abort(failure) + cleanup() + if (!popup.closed) popup.close() + reject(failure) + } + const onAbort = () => fail(options.signal.reason) + const finish: OAuthPopupExchange['finish'] = (result) => { + if (finished) return + finished = true + cleanup() + if (!popup.closed) { + popup.postMessage( + { + type: OAUTH_POPUP_RESULT_MESSAGE, + intent: options.intent, + provider: options.provider, + state, + ...result, + }, + window.location.origin + ) + popup.close() + } + } + const onMessage = (event: MessageEvent) => { + if ( + received || + finished || + !state || + event.origin !== window.location.origin || + event.source !== popup + ) { + return + } + const message = event.data as + | (Partial & { type?: string; intent?: string }) + | null + if ( + !message || + message.type !== OAUTH_POPUP_CALLBACK_MESSAGE || + message.intent !== options.intent || + message.provider !== options.provider || + message.state !== state + ) { + return + } + if ( + typeof message.code !== 'string' && + typeof message.error !== 'string' + ) { + return + } + received = true + resolve({ + callback: { + provider: options.provider, + state, + code: message.code, + error: message.error, + errorDescription: + typeof message.errorDescription === 'string' + ? message.errorDescription + : undefined, + }, + signal: controller.signal, + finish, + }) + } + + window.addEventListener('message', onMessage) + options.signal.addEventListener('abort', onAbort, { once: true }) + stopCloseWatcher = watchOAuthPopupClosed(popup, () => + fail( + new AuthOperationError( + 'OAuth authorization was cancelled.', + 'AUTH_CANCELLED' + ) + ) + ) + const deadline = setTimeout( + () => + fail( + new AuthOperationError( + 'OAuth authorization timed out. Please try again.' + ) + ), + 10 * 60_000 + ) + void options + .prepare(controller.signal) + .then((authorization) => { + if (finished || popup.closed) return + state = authorization.state + if ( + !markOAuthPopup( + getOAuthSessionStorage(popup), + options.provider, + state, + options.intent + ) + ) { + throw new AuthOperationError('OAuth popup storage is unavailable.') + } + popup.location.replace(authorization.url) + }) + .catch(fail) + }) +} diff --git a/web/src/features/auth/passkey/api.ts b/web/src/features/auth/passkey/api.ts index b714531631..3bfd7cfe7d 100644 --- a/web/src/features/auth/passkey/api.ts +++ b/web/src/features/auth/passkey/api.ts @@ -17,10 +17,11 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ import { api } from '@/lib/api' +import { authRequestOptions, authResult } from '@/lib/secure-verification' import type { SecurityProof, - SecurityProofScope, + VerificationOperation, } from '../secure-verification/types' import type { ApiResponse, PasskeyOptionsPayload, PasskeyStatus } from './types' @@ -33,39 +34,50 @@ export async function getPasskeyStatus(): Promise> { return res.data } -export async function beginPasskeyRegistration( - proofToken?: string -): Promise> { - const res = await api.post>( - '/api/user/passkey/register/begin', - undefined, - { headers: proofHeaders(proofToken) } +export function beginPasskeyRegistration( + proofToken: string, + signal?: AbortSignal +): Promise { + return authResult( + api.post('/api/user/passkey/register/begin', undefined, { + ...authRequestOptions, + headers: proofHeaders(proofToken), + signal, + }) ) - return res.data } -export async function finishPasskeyRegistration( +export function finishPasskeyRegistration( flowToken: string, payload: Record, - proofToken?: string -): Promise { - const res = await api.post( - '/api/user/passkey/register/finish', - { - flow_token: flowToken, - credential: payload, - }, - { headers: proofHeaders(proofToken), acceptAuthRotation: true } + signal?: AbortSignal +): Promise { + return authResult( + api.post( + '/api/user/passkey/register/finish', + { flow_token: flowToken, credential: payload }, + { + ...authRequestOptions, + acceptAuthRotation: true, + singleUseAuthorization: true, + signal, + } + ) ) - return res.data } -export async function deletePasskey(proofToken?: string): Promise { - const res = await api.delete('/api/user/passkey', { - headers: proofHeaders(proofToken), - acceptAuthRotation: true, - }) - return res.data +export function deletePasskey( + proofToken: string, + signal?: AbortSignal +): Promise { + return authResult( + api.delete('/api/user/passkey', { + ...authRequestOptions, + headers: proofHeaders(proofToken), + acceptAuthRotation: true, + signal, + }) + ) } export async function beginPasskeyLogin(): Promise< @@ -89,23 +101,32 @@ export async function finishPasskeyLogin( return res.data } -export async function beginPasskeyVerification( - scope: SecurityProofScope -): Promise> { - const res = await api.post>( - '/api/user/passkey/verify/begin', - { scope } +export function beginPasskeyVerification( + operation: VerificationOperation, + signal?: AbortSignal +): Promise { + return authResult( + api.post( + '/api/user/passkey/verify/begin', + { + scope: operation.scope, + ...(operation.context ? { context: operation.context } : {}), + }, + { ...authRequestOptions, signal } + ) ) - return res.data } -export async function finishPasskeyVerification( +export function finishPasskeyVerification( flowToken: string, - payload: Record -): Promise> { - const res = await api.post>( - '/api/user/passkey/verify/finish', - { flow_token: flowToken, credential: payload } + payload: Record, + signal?: AbortSignal +): Promise { + return authResult( + api.post( + '/api/user/passkey/verify/finish', + { flow_token: flowToken, credential: payload }, + { ...authRequestOptions, singleUseAuthorization: true, signal } + ) ) - return res.data } diff --git a/web/src/features/auth/passkey/hooks/use-passkey-management.ts b/web/src/features/auth/passkey/hooks/use-passkey-management.ts index 1c74d4fc03..31a92b4ac5 100644 --- a/web/src/features/auth/passkey/hooks/use-passkey-management.ts +++ b/web/src/features/auth/passkey/hooks/use-passkey-management.ts @@ -16,16 +16,15 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ -import i18next from 'i18next' -import { useCallback, useEffect, useMemo, useState } from 'react' -import { toast } from 'sonner' +import { useCallback, useEffect, useRef, useState } from 'react' import { buildRegistrationResult, createCredential, - isPasskeySupported as detectPasskeySupport, + isPasskeySupported, prepareCredentialCreationOptions, } from '@/lib/passkey' +import { AuthOperationError } from '@/lib/secure-verification' import { beginPasskeyRegistration, @@ -35,168 +34,156 @@ import { } from '../api' import type { PasskeyStatus } from '../types' -interface UsePasskeyManagementOptions { - onStatusChange?: (status: PasskeyStatus | null) => void -} - -export function usePasskeyManagement( - options: UsePasskeyManagementOptions = {} -) { - const { onStatusChange } = options - +export function usePasskeyManagement() { const [status, setStatus] = useState(null) + const [statusError, setStatusError] = useState(null) const [loading, setLoading] = useState(true) const [registering, setRegistering] = useState(false) const [removing, setRemoving] = useState(false) const [supported, setSupported] = useState(false) + const operation = useRef(null) + const mounted = useRef(true) const fetchStatus = useCallback(async () => { + setLoading(true) try { - setLoading(true) - const res = await getPasskeyStatus() - if (res.success) { - setStatus(res.data ?? null) - onStatusChange?.(res.data ?? null) - } else { - setStatus(null) - toast.error(res.message || i18next.t('Failed to load Passkey status')) + const response = await getPasskeyStatus() + if (!response.success || !response.data) { + throw new AuthOperationError( + response.message || 'Failed to load Passkey status' + ) } + if (!mounted.current) return + setStatus(response.data) + setStatusError(null) } catch (error) { - // eslint-disable-next-line no-console - console.error('[Passkey] Failed to fetch status', error) - toast.error(i18next.t('Failed to load Passkey status')) - setStatus(null) + if (mounted.current) { + setStatusError(AuthOperationError.from(error).message) + } } finally { - setLoading(false) + if (mounted.current) setLoading(false) } - }, [onStatusChange]) - - useEffect(() => { - fetchStatus() - }, [fetchStatus]) - - useEffect(() => { - detectPasskeySupport() - .then(setSupported) - .catch(() => setSupported(false)) }, []) - const register = useCallback( - async (proofToken?: string) => { - if (!supported) { - toast.error(i18next.t('This device does not support Passkey')) - return false - } - if (!navigator?.credentials) { - toast.error(i18next.t('Passkey is not supported in this environment')) - return false - } + useEffect(() => { + mounted.current = true + void fetchStatus() + void isPasskeySupported().then((value) => { + if (mounted.current) setSupported(value) + }) + return () => { + mounted.current = false + operation.current?.abort() + } + }, [fetchStatus]) + const register = useCallback( + async (proofToken: string) => { + if (!supported || !navigator.credentials) { + throw new AuthOperationError('This device does not support Passkey') + } + if (operation.current) { + throw new AuthOperationError( + 'A security operation is already in progress.' + ) + } + const controller = new AbortController() + operation.current = controller setRegistering(true) try { - const beginResponse = await beginPasskeyRegistration(proofToken) - if (!beginResponse.success) { - toast.error( - beginResponse.message || - i18next.t('Failed to start Passkey registration') - ) - return false - } - - const publicKey = prepareCredentialCreationOptions( - beginResponse.data?.options ?? beginResponse.data + const begin = await beginPasskeyRegistration( + proofToken, + controller.signal ) - const flowToken = beginResponse.data?.flow_token - if (!flowToken) { - toast.error(i18next.t('Registration flow expired. Please try again.')) - return false + if (!begin.flow_token) { + throw new AuthOperationError( + 'Registration flow expired. Please try again.' + ) } - const credential = (await createCredential( - publicKey + prepareCredentialCreationOptions(begin.options ?? begin), + controller.signal )) as PublicKeyCredential | null + controller.signal.throwIfAborted() if (!credential) { - toast.error(i18next.t('Passkey registration was cancelled')) - return false + throw new AuthOperationError( + 'Passkey registration was cancelled', + 'AUTH_CANCELLED' + ) } - const attestation = buildRegistrationResult(credential) if (!attestation) { - toast.error(i18next.t('Invalid Passkey registration response')) - return false + throw new AuthOperationError('Invalid Passkey registration response') } - - const finishResponse = await finishPasskeyRegistration( - flowToken, + await finishPasskeyRegistration( + begin.flow_token, attestation, - proofToken + controller.signal ) - if (!finishResponse.success) { - toast.error( - finishResponse.message || i18next.t('Failed to register Passkey') - ) - return false - } - - toast.success(i18next.t('Passkey registered successfully')) + controller.signal.throwIfAborted() await fetchStatus() - return true - } catch (error: unknown) { - if (error instanceof DOMException && error.name === 'NotAllowedError') { - toast.info(i18next.t('Passkey registration was cancelled')) - return false + } catch (error) { + if (mounted.current && !controller.signal.aborted) await fetchStatus() + if ( + controller.signal.aborted || + (error instanceof DOMException && error.name === 'NotAllowedError') + ) { + throw new AuthOperationError( + 'Passkey registration was cancelled', + 'AUTH_CANCELLED', + { cause: error } + ) } - // eslint-disable-next-line no-console - console.error('[Passkey] Registration error', error) - toast.error( - error instanceof Error - ? error.message - : i18next.t('Failed to register Passkey') - ) - return false + throw AuthOperationError.from(error, 'Failed to register Passkey') } finally { - setRegistering(false) + if (operation.current === controller) operation.current = null + if (mounted.current) setRegistering(false) } }, - [supported, fetchStatus] + [fetchStatus, supported] ) const remove = useCallback( - async (proofToken?: string) => { + async (proofToken: string) => { + if (operation.current) { + throw new AuthOperationError( + 'A security operation is already in progress.' + ) + } + const controller = new AbortController() + operation.current = controller setRemoving(true) try { - const res = await deletePasskey(proofToken) - if (!res.success) { - toast.error(res.message || i18next.t('Failed to remove Passkey')) - return false - } - - toast.success(i18next.t('Passkey removed successfully')) + await deletePasskey(proofToken, controller.signal) + controller.signal.throwIfAborted() await fetchStatus() - return true } catch (error) { - // eslint-disable-next-line no-console - console.error('[Passkey] Removal error', error) - toast.error(i18next.t('Failed to remove Passkey')) - return false + if (mounted.current && !controller.signal.aborted) await fetchStatus() + if (controller.signal.aborted) { + throw new AuthOperationError( + 'Operation cancelled', + 'AUTH_CANCELLED', + { cause: error } + ) + } + throw AuthOperationError.from(error, 'Failed to remove Passkey') } finally { - setRemoving(false) + if (operation.current === controller) operation.current = null + if (mounted.current) setRemoving(false) } }, [fetchStatus] ) - const enabled = useMemo(() => Boolean(status?.enabled), [status]) - const lastUsed = useMemo(() => status?.last_used_at ?? null, [status]) - return { status, + statusError, loading, registering, removing, supported, - enabled, - lastUsed, + enabled: Boolean(status?.enabled), + lastUsed: status?.last_used_at ?? null, fetchStatus, register, remove, diff --git a/web/src/features/auth/secure-verification/__tests__/verification-api.test.ts b/web/src/features/auth/secure-verification/__tests__/verification-api.test.ts new file mode 100644 index 0000000000..267d45c014 --- /dev/null +++ b/web/src/features/auth/secure-verification/__tests__/verification-api.test.ts @@ -0,0 +1,314 @@ +/* +Copyright (C) 2023-2026 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ +import { AxiosError, type InternalAxiosRequestConfig } from 'axios' +import { afterEach, expect, it, vi } from 'vitest' + +import { api } from '@/lib/api' +import { AuthOperationError, authResult } from '@/lib/secure-verification' +import { useAuthStore, type AuthBundle } from '@/stores/auth-store' + +import { createOAuthFlow } from '../../api' +import { checkVerificationMethods, verify } from '../api' + +const originalAdapter = api.defaults.adapter +const originalLocation = window.location.href +const sessionBundle = { + access_token: 'access-token', + token_type: 'Bearer' as const, + access_expires_at: Math.floor(Date.now() / 1000) + 600, + user: { id: 42, username: 'user', role: 1 }, + session: { + sid: 'session', + current: true, + login_method: 'password', + ip: '127.0.0.1', + user_agent: 'test', + created_at: 1, + last_active_at: 1, + expires_at: Math.floor(Date.now() / 1000) + 3600, + }, +} + +function mockRefreshResponse(bundle: AuthBundle, onRequest?: () => void) { + const requests = vi.fn() + vi.stubGlobal( + 'XMLHttpRequest', + class { + status = 200 + statusText = 'OK' + readyState = 4 + responseText = JSON.stringify({ success: true, data: bundle }) + onloadend: (() => void) | null = null + url = '' + open(_method: string, url: string) { + this.url = url + } + setRequestHeader() {} + getAllResponseHeaders() { + return 'content-type: application/json' + } + abort() {} + send() { + requests(this.url) + onRequest?.() + queueMicrotask(() => this.onloadend?.()) + } + } + ) + return requests +} + +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() + api.defaults.adapter = originalAdapter + useAuthStore.getState().auth.reset('idle') + window.history.replaceState(null, '', originalLocation) +}) + +it.each(['proof', 'flow'] as const)( + 'never replays a %s request after a 401 response', + async (kind) => { + window.history.replaceState(null, '', '/sign-in') + useAuthStore.getState().auth.setBundle(sessionBundle) + const refresh = mockRefreshResponse(sessionBundle) + const adapter = vi.fn(async (config: InternalAxiosRequestConfig) => { + throw new AxiosError( + 'Unauthorized', + 'ERR_BAD_REQUEST', + config, + undefined, + { + status: 401, + statusText: 'Unauthorized', + config, + headers: {}, + data: { code: 'AUTH_SESSION_REVOKED' }, + } + ) + }) + api.defaults.adapter = adapter + await expect( + api.post( + '/protected', + {}, + { + skipErrorHandler: true, + ...(kind === 'proof' + ? { headers: { 'X-Security-Proof': 'one-use-proof' } } + : { singleUseAuthorization: true }), + } + ) + ).rejects.toThrow('Unauthorized') + expect(adapter).toHaveBeenCalledTimes(1) + expect(refresh).not.toHaveBeenCalled() + } +) + +it('refreshes an expiring login token before submitting a one-time proof', async () => { + useAuthStore.getState().auth.setBundle({ + ...sessionBundle, + access_expires_at: Math.floor(Date.now() / 1000) + 10, + }) + const order: string[] = [] + mockRefreshResponse({ ...sessionBundle, access_token: 'fresh-access' }, () => + order.push('refresh') + ) + const adapter = vi.fn(async (config: InternalAxiosRequestConfig) => { + order.push('action') + return { + status: 200, + statusText: 'OK', + config, + headers: {}, + data: { success: true }, + } + }) + api.defaults.adapter = adapter + await api.post( + '/protected', + {}, + { headers: { 'X-Security-Proof': 'one-use-proof' } } + ) + expect(order).toEqual(['refresh', 'action']) + expect(adapter).toHaveBeenCalledTimes(1) + expect(adapter.mock.calls[0]?.[0].headers.Authorization).toBe( + 'Bearer fresh-access' + ) +}) + +it('binds a channel verification to the requested channel context', async () => { + const proof = { + proof_token: 'channel-proof', + method: '2fa', + scope: 'channel.key.read', + expires_at: Math.floor(Date.now() / 1000) + 60, + } + const post = vi.spyOn(api, 'post').mockResolvedValue({ + data: { success: true, data: proof }, + }) + await expect( + verify( + { method: '2fa', code: '123456' }, + { scope: 'channel.key.read', context: { channel_id: 123 } }, + false, + new AbortController().signal + ) + ).resolves.toEqual(proof) + expect(post).toHaveBeenCalledWith( + '/api/verify', + { + method: '2fa', + code: '123456', + scope: 'channel.key.read', + context: { channel_id: 123 }, + }, + expect.anything() + ) +}) + +it('passes the operation context to Passkey begin and completes with only its flow and assertion', async () => { + vi.stubGlobal('navigator', { + credentials: { + get: vi.fn().mockResolvedValue({ + id: 'credential', + rawId: new Uint8Array([1, 2, 3]).buffer, + type: 'public-key', + response: { + clientDataJSON: new Uint8Array([1]).buffer, + authenticatorData: new Uint8Array([2]).buffer, + signature: new Uint8Array([3]).buffer, + userHandle: null, + }, + getClientExtensionResults: () => ({}), + }), + }, + }) + const proof = { + proof_token: 'passkey-proof', + scope: 'channel.key.read', + method: 'passkey', + expires_at: Math.floor(Date.now() / 1000) + 60, + } + const post = vi + .spyOn(api, 'post') + .mockResolvedValueOnce({ + data: { + success: true, + data: { + flow_token: 'flow', + options: { publicKey: { challenge: 'AQID', allowCredentials: [] } }, + }, + }, + }) + .mockResolvedValueOnce({ data: { success: true, data: proof } }) + await expect( + verify( + { method: 'passkey' }, + { scope: 'channel.key.read', context: { channel_id: 123 } }, + false, + new AbortController().signal + ) + ).resolves.toEqual(proof) + expect(post).toHaveBeenNthCalledWith( + 1, + '/api/user/passkey/verify/begin', + { + scope: 'channel.key.read', + context: { channel_id: 123 }, + }, + expect.anything() + ) + expect(post.mock.calls[1]?.[1]).toEqual({ + flow_token: 'flow', + credential: expect.anything(), + }) +}) + +it('passes an enrollment operation through OAuth state creation', async () => { + const post = vi.spyOn(api, 'post').mockResolvedValue({ + data: { success: true, data: { flow_token: 'oauth-flow' } }, + }) + await expect( + createOAuthFlow('github', 'verify', { + scope: 'passkey.register', + context: {}, + }) + ).resolves.toBe('oauth-flow') + expect(post).toHaveBeenCalledWith( + '/api/oauth/state', + expect.objectContaining({ + provider: 'github', + intent: 'verify', + scope: 'passkey.register', + context: {}, + }), + expect.anything() + ) +}) + +it.each([ + [ + 'SECURITY_PROOF_CONSUMED', + 'This verification has already been used. Please verify again.', + ], + [ + 'SECURITY_PROOF_CONTEXT_MISMATCH', + "Verification does not match this action's details. Please verify again.", + ], +])('provides a re-verification message for %s', async (code, message) => { + await expect( + authResult( + Promise.resolve({ + data: { success: false, code, message: 'untranslated backend text' }, + }) + ) + ).rejects.toMatchObject({ code, message }) +}) + +it('reports a failed method query instead of treating the account as unenrolled', async () => { + vi.spyOn(api, 'get').mockRejectedValue( + new Error('Unable to load verification methods') + ) + await expect(checkVerificationMethods('passkey.register')).rejects.toThrow( + 'Unable to load verification methods' + ) +}) + +it('displays a generic internal error even if the server includes database details', async () => { + await expect( + authResult( + Promise.resolve({ + data: { + success: false, + code: 'AUTH_INTERNAL_ERROR', + message: 'SELECT private_table at private-db-host', + }, + }) + ) + ).rejects.toThrow('Please try again later.') + const failure = AuthOperationError.from({ + isAxiosError: true, + response: { + status: 500, + data: { message: 'SELECT private_table at private-db-host' }, + }, + }) + expect(failure.message).toBe('Please try again later.') +}) diff --git a/web/src/features/auth/secure-verification/__tests__/verification-flow.test.tsx b/web/src/features/auth/secure-verification/__tests__/verification-flow.test.tsx new file mode 100644 index 0000000000..721fc78a89 --- /dev/null +++ b/web/src/features/auth/secure-verification/__tests__/verification-flow.test.tsx @@ -0,0 +1,280 @@ +/* +Copyright (C) 2023-2026 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { afterEach, expect, it, vi } from 'vitest' + +import { api } from '@/lib/api' + +import { SecureVerificationDialog } from '../components/secure-verification-dialog' +import { useSecureVerification } from '../hooks/use-secure-verification' +import type { + RequestVerificationOptions, + SecurityProof, + VerificationRequirements, +} from '../types' + +const passwordRequirements: VerificationRequirements = { + scope: 'passkey.register', + methods: [{ method: 'password', available: true }], + oauth_providers: [], + password_encryption_enabled: false, +} + +function Harness(props: { + onResult: (proof: SecurityProof | null) => void + operation?: RequestVerificationOptions +}) { + const verification = useSecureVerification() + return ( + <> + + + + ) +} + +function pendingResponse() { + let resolve!: (value: T) => void + const promise = new Promise((finish) => { + resolve = finish + }) + return { promise, resolve } +} + +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + +it('keeps the requested channel context fixed while verification is open', async () => { + vi.spyOn(api, 'get').mockResolvedValue({ + data: { + success: true, + data: { + scope: 'channel.key.read', + methods: [{ method: '2fa', available: true }], + oauth_providers: [], + password_encryption_enabled: false, + }, + }, + }) + const post = vi.spyOn(api, 'post').mockResolvedValue({ + data: { + success: true, + data: { + proof_token: 'channel-proof', + scope: 'channel.key.read', + method: '2fa', + expires_at: Math.floor(Date.now() / 1000) + 60, + }, + }, + }) + const operation: RequestVerificationOptions = { + scope: 'channel.key.read', + context: { channel_id: 123 }, + } + const user = userEvent.setup() + const result = vi.fn() + render() + await user.click(screen.getByText('Protected action')) + await user.type( + await screen.findByLabelText('Authenticator code or backup code'), + '123456' + ) + operation.context.channel_id = 456 + await user.click(screen.getByRole('button', { name: 'Verify' })) + await waitFor(() => expect(result).toHaveBeenCalledTimes(1)) + expect(post).toHaveBeenCalledWith( + '/api/verify', + { + scope: 'channel.key.read', + context: { channel_id: 123 }, + method: '2fa', + code: '123456', + }, + expect.anything() + ) +}) + +it('shows query errors and reloads requirements only when the user retries', async () => { + const requests = vi + .spyOn(api, 'get') + .mockRejectedValueOnce(new Error('Unable to load methods')) + .mockResolvedValue({ data: { success: true, data: passwordRequirements } }) + const result = vi.fn() + const user = userEvent.setup() + render() + await user.click(screen.getByText('Protected action')) + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Unable to load methods' + ) + expect( + screen.queryByText('No verification method is available for this action.') + ).not.toBeInTheDocument() + await user.click(screen.getByRole('button', { name: 'Retry' })) + expect( + await screen.findByLabelText('Password', { selector: 'input' }) + ).toBeVisible() + expect(requests).toHaveBeenCalledTimes(2) + await user.click(screen.getByRole('button', { name: 'Cancel' })) + await waitFor(() => expect(result).toHaveBeenCalledWith(null)) +}) + +it('returns a proof only after successful verification and clears a rejected password', async () => { + vi.spyOn(api, 'get').mockResolvedValue({ + data: { success: true, data: passwordRequirements }, + }) + const proof: SecurityProof = { + proof_token: 'proof', + method: 'password', + scope: 'passkey.register', + expires_at: Math.floor(Date.now() / 1000) + 300, + } + const posts = vi + .spyOn(api, 'post') + .mockResolvedValueOnce({ + data: { success: false, message: 'Wrong password' }, + }) + .mockResolvedValueOnce({ data: { success: true, data: proof } }) + const result = vi.fn() + const user = userEvent.setup() + render() + await user.click(screen.getByText('Protected action')) + await user.type( + await screen.findByLabelText('Password', { selector: 'input' }), + 'incorrect' + ) + await user.click(screen.getByRole('button', { name: 'Verify' })) + expect(await screen.findByRole('alert')).toHaveTextContent('Wrong password') + expect(screen.getByLabelText('Password', { selector: 'input' })).toHaveValue( + '' + ) + expect(result).not.toHaveBeenCalled() + await user.type( + screen.getByLabelText('Password', { selector: 'input' }), + 'correct' + ) + await user.keyboard('{Enter}') + await waitFor(() => expect(result).toHaveBeenCalledWith(proof)) + expect(posts).toHaveBeenLastCalledWith( + '/api/verify', + { method: 'password', scope: 'passkey.register', password: 'correct' }, + expect.objectContaining({ signal: expect.any(AbortSignal) }) + ) + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() +}) + +it('discards a late proof after cancellation and prevents a duplicate submission', async () => { + vi.spyOn(api, 'get').mockResolvedValue({ + data: { success: true, data: passwordRequirements }, + }) + const reply = pendingResponse<{ + data: { success: boolean; data: SecurityProof } + }>() + const posts = vi.spyOn(api, 'post').mockReturnValue(reply.promise) + const result = vi.fn() + const user = userEvent.setup() + render() + await user.click(screen.getByText('Protected action')) + await user.type( + await screen.findByLabelText('Password', { selector: 'input' }), + 'password' + ) + const submit = screen.getByRole('button', { name: 'Verify' }) + fireEvent.click(submit) + fireEvent.click(submit) + await waitFor(() => expect(posts).toHaveBeenCalledTimes(1)) + expect(submit).toBeDisabled() + await user.click(screen.getByRole('button', { name: 'Cancel' })) + await waitFor(() => expect(result).toHaveBeenCalledExactlyOnceWith(null)) + await act(async () => { + reply.resolve({ + data: { + success: true, + data: { + proof_token: 'late-proof', + method: 'password', + scope: 'passkey.register', + expires_at: Math.floor(Date.now() / 1000) + 300, + }, + }, + }) + await reply.promise + }) + expect(result).toHaveBeenCalledTimes(1) + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() +}) + +it('does not reopen after a cancelled method query finishes', async () => { + const reply = pendingResponse<{ + data: { success: boolean; data: VerificationRequirements } + }>() + vi.spyOn(api, 'get').mockReturnValue(reply.promise) + const result = vi.fn() + const user = userEvent.setup() + render() + await user.click(screen.getByText('Protected action')) + expect(screen.getByRole('status')).toHaveTextContent( + 'Loading verification methods...' + ) + await user.click(screen.getByRole('button', { name: 'Cancel' })) + await act(async () => { + reply.resolve({ data: { success: true, data: passwordRequirements } }) + await reply.promise + }) + expect(result).toHaveBeenCalledExactlyOnceWith(null) + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() +}) + +it('keeps an enrolled Passkey unavailable when this browser cannot use it', async () => { + vi.stubGlobal('PublicKeyCredential', undefined) + vi.spyOn(api, 'get').mockResolvedValue({ + data: { + success: true, + data: { + ...passwordRequirements, + methods: [{ method: 'passkey', available: true }], + }, + }, + }) + const user = userEvent.setup() + render() + await user.click(screen.getByText('Protected action')) + expect( + await screen.findByText( + 'This device does not support Passkey verification.' + ) + ).toBeVisible() + expect(screen.getByRole('button', { name: 'Verify' })).toBeDisabled() + expect(screen.queryByLabelText('Password')).not.toBeInTheDocument() +}) diff --git a/web/src/features/auth/secure-verification/api.ts b/web/src/features/auth/secure-verification/api.ts index 8eab7e9ec7..c0d93a0cc3 100644 --- a/web/src/features/auth/secure-verification/api.ts +++ b/web/src/features/auth/secure-verification/api.ts @@ -16,176 +16,215 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ -import i18next from 'i18next' - -import type { ApiResponse } from '@/features/auth/types' -import { api, get2FAStatus } from '@/lib/api' +import { api } from '@/lib/api' +import { buildOAuthAuthorizationUrl } from '@/lib/oauth' import { buildAssertionResult, + isPasskeySupported, prepareCredentialRequestOptions, - isPasskeySupported as detectPasskeySupport, } from '@/lib/passkey' +import { + AuthOperationError, + authRequestOptions, + authResult, +} from '@/lib/secure-verification' +import { createOAuthFlow } from '../api' +import { openOAuthPopup } from '../lib/oauth-popup' +import { encryptPassword } from '../lib/password-encryption' import { beginPasskeyVerification, finishPasskeyVerification, - getPasskeyStatus, -} from '../passkey' +} from '../passkey/api' +import type { SystemStatus } from '../types' import type { SecurityProof, SecurityProofScope, - VerificationMethod, - VerificationMethods, + VerificationInput, + VerificationOperation, + VerificationRequirements, } from './types' -/** - * Fetch available verification methods for the current user. - */ -export async function checkVerificationMethods(): Promise { - try { - const [twoFAResponse, passkeyResponse, passkeySupported] = - await Promise.all([ - get2FAStatus(), - getPasskeyStatus(), - detectPasskeySupport(), - ]) - - const has2FA = - Boolean(twoFAResponse?.success) && Boolean(twoFAResponse?.data?.enabled) - const hasPasskey = - Boolean(passkeyResponse?.success) && - Boolean(passkeyResponse?.data?.enabled) - - return { - has2FA, - hasPasskey, - passkeySupported, - } - } catch (error) { - // eslint-disable-next-line no-console - console.error('[Secure Verification] Failed to check methods', error) - return { - has2FA: false, - hasPasskey: false, - passkeySupported: false, - } +export async function checkVerificationMethods( + scope: SecurityProofScope, + signal?: AbortSignal +): Promise { + const [requirements, passkeySupported] = await Promise.all([ + authResult( + api.get('/api/verify/methods', { + ...authRequestOptions, + params: { scope }, + signal, + disableDuplicate: true, + }) + ), + isPasskeySupported(), + ]) + return { + ...requirements, + methods: requirements.methods.map((option) => { + if ( + option.method === 'passkey' && + option.available && + !passkeySupported + ) { + return { + ...option, + available: false, + reason: 'This device does not support Passkey verification.', + } + } + return option + }), } } -/** - * Execute a verification flow based on the method type. - */ export async function verify( - method: VerificationMethod, - scope: SecurityProofScope, - code?: string + input: VerificationInput, + operation: VerificationOperation, + passwordEncryptionEnabled: boolean, + signal: AbortSignal ): Promise { - switch (method) { - case '2fa': - return verifyTwoFA(scope, code) - case 'passkey': - return verifyPasskey(scope) - default: - throw new Error( - i18next.t('Unsupported verification method: {{method}}', { method }) - ) - } -} - -/** - * Perform 2FA verification flow. - */ -async function verifyTwoFA( - scope: SecurityProofScope, - code?: string | null -): Promise { - const trimmed = code?.trim() - if (!trimmed) { - throw new Error( - i18next.t('Please enter the verification code or backup code') - ) - } - - const res = await api.post>('/api/verify', { - method: '2fa', - code: trimmed, - scope, - }) - - if (!res.data?.success) { - throw new Error(res.data?.message || i18next.t('Verification failed')) - } - if (!res.data.data?.proof_token) { - throw new Error(i18next.t('Verification proof was not returned')) - } - return res.data.data -} - -/** - * Perform Passkey verification flow. - */ -async function verifyPasskey( - scope: SecurityProofScope -): Promise { - if (typeof navigator === 'undefined' || !navigator.credentials) { - throw new Error( - i18next.t('Passkey verification is not supported in this environment') - ) - } - try { - const beginResponse = await beginPasskeyVerification(scope) - if (!beginResponse.success) { - throw new Error( - beginResponse.message || i18next.t('Failed to start verification') - ) + const operationFields = { + scope: operation.scope, + ...(operation.context ? { context: operation.context } : {}), } - - const publicKey = prepareCredentialRequestOptions( - beginResponse.data?.options ?? beginResponse.data - ) - const flowToken = beginResponse.data?.flow_token - if (!flowToken) { - throw new Error(i18next.t('Verification flow expired')) + let proof: SecurityProof + switch (input.method) { + case '2fa': + proof = await authResult( + api.post( + '/api/verify', + { + method: input.method, + ...operationFields, + code: input.code.trim(), + }, + { ...authRequestOptions, signal } + ) + ) + break + case 'password': { + const passwordFields = passwordEncryptionEnabled + ? await encryptPassword(input.password) + : { password: input.password } + signal.throwIfAborted() + proof = await authResult( + api.post( + '/api/verify', + { method: input.method, ...operationFields, ...passwordFields }, + { ...authRequestOptions, signal } + ) + ) + break + } + case 'passkey': + proof = await verifyPasskey(operation, signal) + break + case 'oauth': + proof = await verifyOAuth(input.provider, operation, signal) + break } + signal.throwIfAborted() + if ( + !proof.proof_token || + proof.scope !== operation.scope || + proof.method !== input.method || + proof.expires_at * 1000 <= Date.now() + ) { + throw new AuthOperationError('Verification proof was not returned') + } + return proof + } catch (error) { + throw AuthOperationError.from(error) + } +} - const credential = (await navigator.credentials.get({ +async function verifyPasskey( + operation: VerificationOperation, + signal: AbortSignal +): Promise { + const begin = await beginPasskeyVerification(operation, signal) + if (!begin.flow_token) { + throw new AuthOperationError('Verification flow expired') + } + const publicKey = prepareCredentialRequestOptions(begin.options ?? begin) + let credential: PublicKeyCredential | null + try { + credential = (await navigator.credentials.get({ publicKey, + signal, })) as PublicKeyCredential | null - - if (!credential) { - throw new Error(i18next.t('Passkey verification was cancelled')) - } - - const assertion = buildAssertionResult(credential) - if (!assertion) { - throw new Error(i18next.t('Unable to build Passkey assertion')) - } - - const finishResponse = await finishPasskeyVerification(flowToken, assertion) - if (!finishResponse.success) { - throw new Error( - finishResponse.message || i18next.t('Passkey verification failed') - ) - } - - if (!finishResponse.data?.proof_token) { - throw new Error(i18next.t('Verification proof was not returned')) - } - return finishResponse.data - } catch (error: unknown) { + } catch (error) { if (error instanceof DOMException && error.name === 'NotAllowedError') { - throw new Error( - i18next.t('Passkey verification was cancelled or timed out'), - { cause: error } - ) - } - if (error instanceof DOMException && error.name === 'InvalidStateError') { - throw new Error( - i18next.t('Passkey verification is not available in the current state'), - { cause: error } + throw new AuthOperationError( + 'Passkey verification was cancelled or timed out' ) } throw error } + signal.throwIfAborted() + if (!credential) { + throw new AuthOperationError( + 'Passkey verification was cancelled', + 'AUTH_CANCELLED' + ) + } + const assertion = buildAssertionResult(credential) + if (!assertion) { + throw new AuthOperationError('Unable to build Passkey assertion') + } + return finishPasskeyVerification(begin.flow_token, assertion, signal) +} + +async function verifyOAuth( + provider: string, + operation: VerificationOperation, + signal: AbortSignal +): Promise { + const exchange = await openOAuthPopup({ + provider, + intent: 'verify', + signal, + prepare: async (popupSignal) => { + const [state, status] = await Promise.all([ + createOAuthFlow(provider, 'verify', operation, popupSignal), + authResult( + api.get('/api/status', { + ...authRequestOptions, + signal: popupSignal, + disableDuplicate: true, + }) + ), + ]) + return { state, url: buildOAuthAuthorizationUrl(provider, state, status) } + }, + }) + try { + const callback = exchange.callback + const proof = await authResult( + api.get(`/api/oauth/${provider}`, { + ...authRequestOptions, + singleUseAuthorization: true, + disableDuplicate: true, + signal: exchange.signal, + params: { + state: callback.state, + code: callback.code, + error: callback.error, + error_description: callback.errorDescription, + }, + }) + ) + exchange.signal.throwIfAborted() + exchange.finish({ success: true }) + return proof + } catch (error) { + const failure = AuthOperationError.from( + exchange.signal.aborted ? exchange.signal.reason : error + ) + exchange.finish({ success: false, message: failure.message }) + throw failure + } } diff --git a/web/src/features/auth/secure-verification/components/secure-verification-dialog.tsx b/web/src/features/auth/secure-verification/components/secure-verification-dialog.tsx index 7d40010c38..c258ce746a 100644 --- a/web/src/features/auth/secure-verification/components/secure-verification-dialog.tsx +++ b/web/src/features/auth/secure-verification/components/secure-verification-dialog.tsx @@ -16,189 +16,247 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ -import { ShieldCheck, KeyRound, Loader2 } from 'lucide-react' -import { useMemo } from 'react' +import { KeyRound, Loader2, ShieldCheck } from 'lucide-react' +import { useId } from 'react' import { useTranslation } from 'react-i18next' import { Dialog } from '@/components/dialog' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' import type { SecureVerificationState, + VerificationInput, VerificationMethod, - VerificationMethods, } from '../types' interface SecureVerificationDialogProps { - open: boolean - onOpenChange: (open: boolean) => void - methods: VerificationMethods state: SecureVerificationState - onVerify: (method: VerificationMethod, code?: string) => void | Promise + onVerify: () => void | Promise onCancel: () => void - onCodeChange: (code: string) => void - onMethodChange: (method: VerificationMethod) => void + onRetry: () => void + onInputChange: (input: VerificationInput) => void } -export function SecureVerificationDialog({ - open, - onOpenChange, - methods, - state, - onVerify, - onCancel, - onCodeChange, - onMethodChange, -}: SecureVerificationDialogProps) { +const methodLabels: Record = { + '2fa': 'Authenticator code', + passkey: 'Passkey', + password: 'Password', + oauth: 'Linked account', +} + +export function SecureVerificationDialog(props: SecureVerificationDialogProps) { const { t } = useTranslation() - const availableTabs: VerificationMethod[] = useMemo(() => { - const tabs: VerificationMethod[] = [] - if (methods.has2FA) tabs.push('2fa') - if (methods.hasPasskey && methods.passkeySupported) tabs.push('passkey') - return tabs - }, [methods]) - - const activeMethod = - state.method ?? (availableTabs.length > 0 ? availableTabs[0] : null) - - const title = - state.title ?? - (availableTabs.length - ? 'Additional verification required' - : 'Verification unavailable') - - const description = - state.description ?? - (availableTabs.length - ? 'Confirm your identity before accessing this sensitive action.' - : t( - 'Enable Two-factor Authentication or Passkey in Security & Access to continue.' - )) - - const handleVerify = () => { - if (!activeMethod) return - const payload = activeMethod === '2fa' ? state.code : undefined - onVerify(activeMethod, payload) + const inputId = useId() + const state = props.state + if (state.phase === 'idle') return null + const ready = + state.phase === 'ready' || state.phase === 'verifying' ? state : null + const input = ready?.input + const verifying = state.phase === 'verifying' + let canVerify = state.phase === 'ready' && Boolean(input) + if (input?.method === 'password') { + canVerify = canVerify && input.password.length > 0 } + if (input?.method === '2fa') { + canVerify = canVerify && input.code.trim().length >= 6 + } + if (input?.method === 'oauth') { + canVerify = canVerify && Boolean(input.provider) + } + const error = 'error' in state ? state.error : undefined + const formId = `${inputId}-form` - const verifyDisabled = - state.loading || - (activeMethod === '2fa' && (!state.code.trim() || state.code.length < 6)) + const selectMethod = (method: string) => { + switch (method) { + case '2fa': + props.onInputChange({ method, code: '' }) + break + case 'password': + props.onInputChange({ method, password: '' }) + break + case 'passkey': + props.onInputChange({ method }) + break + case 'oauth': + props.onInputChange({ + method, + provider: ready?.requirements.oauth_providers[0]?.slug ?? '', + }) + break + } + } return ( { + if (!open) props.onCancel() + }} title={ <> - - {title} + + {state.request.title ?? t('Security verification')} } - description={description} - contentClassName='top-[8vh] max-w-[calc(100%-1.5rem)] translate-y-0 overflow-hidden border-none shadow-xl sm:top-1/2 sm:max-w-md sm:translate-y-[-50%] sm:rounded-xl' - headerClassName='border-b pb-4 text-left' - titleClassName='flex items-center gap-2 text-lg font-semibold' - descriptionClassName='text-left' + description={ + state.request.description ?? + t('Confirm your identity before accessing this sensitive action.') + } + contentClassName='sm:max-w-md' contentHeight='auto' - bodyClassName='px-1 py-1' - showCloseButton={!state.loading} - footerClassName='bg-muted/30 border-t px-6 py-4 sm:flex-row sm:justify-end' + titleClassName='flex items-center gap-2' footer={ <> - - + {state.phase === 'error' ? ( + + ) : ( + + )} } > - {availableTabs.length === 0 ? ( -
-
- -
-

- {t( - 'Enable Two-factor Authentication or Passkey in Security & Access to unlock sensitive operations.' - )} -

+ {state.phase === 'loading' && ( +
+ + {t('Loading verification methods...')}
- ) : ( - onMethodChange(value as VerificationMethod)} - className='gap-4' + )} + {error && ( +

+ {t(error)} +

+ )} + {ready && ( +
{ + event.preventDefault() + if (canVerify) void props.onVerify() + }} + className='space-y-4 py-2' > - - {methods.has2FA && ( - {t('Authenticator code')} - )} - {methods.hasPasskey && methods.passkeySupported && ( - {t('Passkey')} - )} - - - -

- {t( - 'Enter the 6-digit Time-based One-Time Password or 8-character backup code from your authenticator app.' + {!input ? ( +

+

{t('No verification method is available for this action.')}

+ {ready.requirements.methods.map( + (option) => + option.reason && ( +

+ {t(option.reason)} +

+ ) )} -

- onCodeChange(event.target.value)} - placeholder={t('Enter verification code')} - disabled={state.loading} - autoFocus={activeMethod === '2fa'} - onKeyDown={(event) => { - if (event.key === 'Enter' && !verifyDisabled) { - event.preventDefault() - handleVerify() - } - }} - /> - - - -
-
- -
-

- {t('Use your Passkey')} -

-

- {t( - 'We will prompt your device to confirm using biometrics or your hardware key.' - )} -

-
-
- {!methods.passkeySupported && ( -

- {t('This device does not support Passkey verification.')} -

- )} -
- + ) : ( + + + {ready.requirements.methods.map((option) => ( + + {t(methodLabels[option.method])} + + ))} + + + + + props.onInputChange({ + method: 'password', + password: event.target.value, + }) + } + /> + + + + + props.onInputChange({ + method: '2fa', + code: event.target.value, + }) + } + /> +

+ {t( + 'Enter the 6-digit authenticator code or an unused backup code.' + )} +

+
+ +

+ + {t( + 'We will prompt your device to confirm using biometrics or your hardware key.' + )} +

+
+ +

+ {t( + 'Continue with an account already linked to your profile.' + )} +

+
+ {ready.requirements.oauth_providers.map((provider) => ( + + ))} +
+
+
+ )} + )}
) diff --git a/web/src/features/auth/secure-verification/hooks/use-secure-verification.ts b/web/src/features/auth/secure-verification/hooks/use-secure-verification.ts index bb274c9620..fee1d629d7 100644 --- a/web/src/features/auth/secure-verification/hooks/use-secure-verification.ts +++ b/web/src/features/auth/secure-verification/hooks/use-secure-verification.ts @@ -16,241 +16,211 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ -import i18next from 'i18next' -import { useCallback, useEffect, useMemo, useState } from 'react' -import { toast } from 'sonner' +import { useCallback, useEffect, useReducer, useRef } from 'react' -import { - extractVerificationInfo, - isVerificationRequiredError, -} from '@/lib/secure-verification' +import { AuthOperationError } from '@/lib/secure-verification' import { checkVerificationMethods, verify } from '../api' import type { + RequestVerificationOptions, SecureVerificationState, - StartVerificationOptions, - UseSecureVerificationOptions, - VerificationMethod, - VerificationMethods, + SecurityProof, + VerificationInput, + VerificationRequirements, } from '../types' -type ApiCall = ((proofToken?: string) => Promise) | null +type VerificationAction = + | { type: 'reset' } + | { type: 'loading'; request: RequestVerificationOptions } + | { type: 'loaded'; requirements: VerificationRequirements } + | { type: 'input'; input: VerificationInput } + | { type: 'submit' } + | { type: 'error'; error: string } -interface InternalState extends SecureVerificationState { - apiCall: ApiCall -} - -const defaultMethods: VerificationMethods = { - has2FA: false, - hasPasskey: false, - passkeySupported: false, -} - -const initialState: InternalState = { - method: null, - loading: false, - code: '', - title: undefined, - description: undefined, - apiCall: null, -} - -export function useSecureVerification( - options: UseSecureVerificationOptions = {} -) { - const { onSuccess, onError, successMessage, autoReset = true } = options - - const [methods, setMethods] = useState(defaultMethods) - const [state, setState] = useState(initialState) - const [open, setOpen] = useState(false) - - const fetchVerificationMethods = useCallback(async () => { - const result = await checkVerificationMethods() - setMethods(result) - return result - }, []) - - useEffect(() => { - fetchVerificationMethods() - }, [fetchVerificationMethods]) - - const reset = useCallback(() => { - setState(initialState) - setOpen(false) - }, []) - - const startVerification = useCallback( - async ( - apiCall: (proofToken?: string) => Promise, - config: StartVerificationOptions - ) => { - const { preferredMethod, scope, title, description } = config - const availableMethods = await fetchVerificationMethods() - - if (!availableMethods.has2FA && !availableMethods.hasPasskey) { - toast.error( - i18next.t( - 'Please enable Two-factor Authentication or Passkey before proceeding' - ) - ) - onError?.( - new Error( - 'No verification methods available. Enable 2FA or Passkey to continue.' - ) - ) - return false +function verificationReducer( + state: SecureVerificationState, + action: VerificationAction +): SecureVerificationState { + switch (action.type) { + case 'reset': + return { phase: 'idle' } + case 'loading': + return { phase: 'loading', request: action.request } + case 'loaded': { + if (state.phase !== 'loading') return state + const methods = action.requirements.methods.filter( + (option) => option.available + ) + const preferred = + methods.find((option) => option.method === 'passkey') ?? methods[0] + let input: VerificationInput | null = null + switch (preferred?.method) { + case '2fa': + input = { method: '2fa', code: '' } + break + case 'password': + input = { method: 'password', password: '' } + break + case 'passkey': + input = { method: 'passkey' } + break + case 'oauth': + input = { + method: 'oauth', + provider: action.requirements.oauth_providers[0]?.slug ?? '', + } + break } - - let defaultMethod: VerificationMethod | null = preferredMethod ?? null + return { + phase: 'ready', + request: state.request, + requirements: action.requirements, + input, + } + } + case 'input': if ( - (defaultMethod === 'passkey' && - (!availableMethods.hasPasskey || - !availableMethods.passkeySupported)) || - (defaultMethod === '2fa' && !availableMethods.has2FA) - ) { - defaultMethod = null - } - if (!defaultMethod) { - if (availableMethods.hasPasskey && availableMethods.passkeySupported) { - defaultMethod = 'passkey' - } else if (availableMethods.has2FA) { - defaultMethod = '2fa' - } - } - - setState((prev) => ({ - ...prev, - apiCall, - method: defaultMethod, - scope, - title, - description, - })) - setOpen(true) - return true - }, - [fetchVerificationMethods, onError] - ) - - const executeVerification = useCallback( - async (method?: VerificationMethod, code?: string) => { - if (!state.apiCall) { - toast.error(i18next.t('Verification is not configured properly')) - return - } - - const actualMethod = method ?? state.method - if (!actualMethod) { - toast.error(i18next.t('Select a verification method first')) - return - } - - setState((prev) => ({ ...prev, loading: true })) - - try { - if (!state.scope) { - throw new Error(i18next.t('Verification scope is missing')) - } - const proof = await verify( - actualMethod, - state.scope, - code ?? state.code + state.phase !== 'ready' || + !state.requirements.methods.some( + (option) => option.method === action.input.method && option.available ) - const result = await state.apiCall(proof.proof_token) - - if (successMessage) { - toast.success(successMessage) - } - - onSuccess?.(result, actualMethod) - - if (autoReset) { - reset() - } - - return result - } catch (error) { - const message = - error instanceof Error - ? error.message - : i18next.t('Verification failed') - toast.error(message) - onError?.(error) - throw error - } finally { - setState((prev) => ({ ...prev, loading: false })) + ) { + return state } - }, - [state, successMessage, onSuccess, onError, autoReset, reset] - ) - - const setCode = useCallback((code: string) => { - setState((prev) => ({ ...prev, code })) - }, []) - - const switchMethod = useCallback((method: VerificationMethod) => { - setState((prev) => ({ ...prev, method, code: '' })) - }, []) - - const cancel = useCallback(() => { - reset() - }, [reset]) - - const withVerification = useCallback( - async ( - apiCall: (proofToken?: string) => Promise, - config: StartVerificationOptions - ) => { - try { - return await apiCall() - } catch (error) { - if (isVerificationRequiredError(error)) { - const info = extractVerificationInfo(error) - toast.info(info.message) - await startVerification(apiCall, config) - return null - } - throw error + return { ...state, input: action.input, error: undefined } + case 'submit': { + if (state.phase !== 'ready') return state + let input = state.input + if (input?.method === 'password') { + input = { method: 'password', password: '' } } - }, - [startVerification] - ) - - const canUseMethod = useCallback( - (method: VerificationMethod) => { - if (method === '2fa') return methods.has2FA - if (method === 'passkey') { - return methods.hasPasskey && methods.passkeySupported + if (input?.method === '2fa') input = { method: '2fa', code: '' } + return { ...state, phase: 'verifying', input, error: undefined } + } + case 'error': + if (state.phase === 'idle') return state + if (state.phase === 'loading' || state.phase === 'error') { + return { phase: 'error', request: state.request, error: action.error } } - return false + return { ...state, phase: 'ready', error: action.error } + } +} + +interface PendingVerification { + request: RequestVerificationOptions + controller: AbortController + resolve: (proof: SecurityProof | null) => void + submitting: boolean +} + +export function useSecureVerification() { + const [state, dispatch] = useReducer(verificationReducer, { phase: 'idle' }) + const pending = useRef(null) + + const cancel = useCallback(() => { + const current = pending.current + pending.current = null + current?.controller.abort() + current?.resolve(null) + dispatch({ type: 'reset' }) + }, []) + + useEffect(() => cancel, [cancel]) + + const loadRequirements = useCallback(async (current: PendingVerification) => { + dispatch({ type: 'loading', request: current.request }) + try { + const requirements = await checkVerificationMethods( + current.request.scope, + current.controller.signal + ) + if (pending.current === current) { + dispatch({ type: 'loaded', requirements }) + } + } catch (error) { + if (pending.current === current) { + dispatch({ + type: 'error', + error: AuthOperationError.from(error).message, + }) + } + } + }, []) + + const requestVerification = useCallback( + (request: RequestVerificationOptions): Promise => { + if (pending.current) return Promise.resolve(null) + return new Promise((resolve) => { + const current: PendingVerification = { + request: structuredClone(request), + resolve, + controller: new AbortController(), + submitting: false, + } + pending.current = current + void loadRequirements(current) + }) }, - [methods] + [loadRequirements] ) + + const executeVerification = useCallback(async () => { + const current = pending.current + if ( + !current || + current.submitting || + state.phase !== 'ready' || + !state.input + ) { + return + } + current.submitting = true + const input = state.input + dispatch({ type: 'submit' }) + try { + const proof = await verify( + input, + current.request, + state.requirements.password_encryption_enabled, + current.controller.signal + ) + if (pending.current !== current) return + pending.current = null + dispatch({ type: 'reset' }) + current.resolve(proof) + } catch (error) { + if (pending.current !== current) return + const failure = AuthOperationError.from(error) + if (failure.code === 'AUTH_CANCELLED') { + cancel() + return + } + dispatch({ type: 'error', error: failure.message }) + } finally { + current.submitting = false + } + }, [cancel, state]) - const recommendedMethod = useMemo(() => { - if (methods.hasPasskey && methods.passkeySupported) return 'passkey' - if (methods.has2FA) return '2fa' - return null - }, [methods]) + const retry = useCallback(() => { + if (pending.current && state.phase === 'error') { + void loadRequirements(pending.current) + } + }, [loadRequirements, state.phase]) + const setInput = useCallback( + (input: VerificationInput) => dispatch({ type: 'input', input }), + [] + ) return { - open, - setOpen, - methods, - state, - startVerification, - executeVerification, + requestVerification, cancel, - reset, - setCode, - switchMethod, - withVerification, - fetchVerificationMethods, - canUseMethod, - recommendedMethod, - hasAnyMethod: methods.has2FA || methods.hasPasskey, - isLoading: state.loading, - currentMethod: state.method, - code: state.code, + isActive: state.phase !== 'idle', + dialogProps: { + state, + onCancel: cancel, + onRetry: retry, + onInputChange: setInput, + onVerify: executeVerification, + }, } } diff --git a/web/src/features/auth/secure-verification/types.ts b/web/src/features/auth/secure-verification/types.ts index 9d368225b9..83ae5e6d16 100644 --- a/web/src/features/auth/secure-verification/types.ts +++ b/web/src/features/auth/secure-verification/types.ts @@ -16,12 +16,19 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ -export type VerificationMethod = '2fa' | 'passkey' - +export type VerificationMethod = '2fa' | 'passkey' | 'password' | 'oauth' export type SecurityProofScope = | 'channel.key.read' | 'passkey.register' | 'passkey.delete' + | '2fa.setup' + +export type VerificationOperation = + | { scope: 'channel.key.read'; context: { channel_id: number } } + | { + scope: Exclude + context?: Record + } export interface SecurityProof { proof_token: string @@ -30,31 +37,32 @@ export interface SecurityProof { scope: SecurityProofScope } -export interface VerificationMethods { - has2FA: boolean - hasPasskey: boolean - passkeySupported: boolean -} - -export interface SecureVerificationState { - method: VerificationMethod | null - scope?: SecurityProofScope - loading: boolean - code: string - title?: string - description?: string -} - -export interface UseSecureVerificationOptions { - onSuccess?: (result: unknown, method: VerificationMethod) => void - onError?: (error: unknown) => void - successMessage?: string - autoReset?: boolean -} - -export interface StartVerificationOptions { +export interface VerificationRequirements { scope: SecurityProofScope - preferredMethod?: VerificationMethod + methods: { method: VerificationMethod; available: boolean; reason?: string }[] + oauth_providers: { slug: string; name: string }[] + password_encryption_enabled: boolean +} + +export type VerificationInput = + | { method: '2fa'; code: string } + | { method: 'password'; password: string } + | { method: 'passkey' } + | { method: 'oauth'; provider: string } + +export type RequestVerificationOptions = VerificationOperation & { title?: string description?: string } + +export type SecureVerificationState = + | { phase: 'idle' } + | { phase: 'loading'; request: RequestVerificationOptions } + | { phase: 'error'; request: RequestVerificationOptions; error: string } + | { + phase: 'ready' | 'verifying' + request: RequestVerificationOptions + requirements: VerificationRequirements + input: VerificationInput | null + error?: string + } diff --git a/web/src/features/channels/api.ts b/web/src/features/channels/api.ts index fa13a186c5..b9f4868f13 100644 --- a/web/src/features/channels/api.ts +++ b/web/src/features/channels/api.ts @@ -305,13 +305,15 @@ export async function deleteDisabledChannels(): Promise<{ */ export async function getChannelKey( id: number, - proofToken?: string + proofToken: string, + signal?: AbortSignal ): Promise<{ success: boolean; message?: string; data?: { key: string } }> { const res = await api.post( `/api/channel/${id}/key`, undefined, channelActionConfig({ - headers: proofToken ? { 'X-Security-Proof': proofToken } : undefined, + headers: { 'X-Security-Proof': proofToken }, + signal, }) ) return res.data diff --git a/web/src/features/channels/components/drawers/channel-mutate-drawer.tsx b/web/src/features/channels/components/drawers/channel-mutate-drawer.tsx index 93f6a0a176..ce19fb5c72 100644 --- a/web/src/features/channels/components/drawers/channel-mutate-drawer.tsx +++ b/web/src/features/channels/components/drawers/channel-mutate-drawer.tsx @@ -107,10 +107,7 @@ import { TooltipContent, TooltipTrigger, } from '@/components/ui/tooltip' -import { - SecureVerificationDialog, - useSecureVerification, -} from '@/features/auth/secure-verification' +import { SecureVerificationDialog } from '@/features/auth/secure-verification' import { useCopyToClipboard } from '@/hooks/use-copy-to-clipboard' import { useHiddenClickUnlock } from '@/hooks/use-hidden-click-unlock' import { @@ -131,7 +128,6 @@ import { fetchModels, getAllModels, getChannel, - getChannelKey, getGroups, getPrefillGroups, getTaskPluginOptions, @@ -152,6 +148,7 @@ import { MODEL_FETCHABLE_TYPES, OPENAI_FIELD_PASSTHROUGH_TYPES, } from '../../constants' +import { useChannelKeyDisclosure } from '../../hooks/use-channel-key-disclosure' import { useChannelMutateForm } from '../../hooks/use-channel-mutate-form' import { CHANNEL_FORM_DEFAULT_VALUES, @@ -630,8 +627,6 @@ export function ChannelMutateDrawer({ ) const canRevealChannelKey = currentUser?.role === ROLE.SUPER_ADMIN const [fetchModelsDialogOpen, setFetchModelsDialogOpen] = useState(false) - const [channelKey, setChannelKey] = useState(null) - const [isChannelKeyLoading, setIsChannelKeyLoading] = useState(false) const [isCodexCredentialRefreshing, setIsCodexCredentialRefreshing] = useState(false) const initialModelsRef = useRef([]) @@ -695,25 +690,8 @@ export function ChannelMutateDrawer({ const { copyToClipboard } = useCopyToClipboard() - const { - open: verificationOpen, - methods: verificationMethods, - state: verificationState, - executeVerification, - withVerification, - cancel: cancelVerification, - setCode: setVerificationCode, - switchMethod: switchVerificationMethod, - } = useSecureVerification() - - useEffect(() => { - if (!open) { - setChannelKey(null) - setIsChannelKeyLoading(false) - } else if (channelId) { - setChannelKey(null) - } - }, [open, channelId]) + const { channelKey, isChannelKeyLoading, handleRevealKey, verification } = + useChannelKeyDisclosure(open, channelId) // Check if this is a multi-key channel const isMultiKeyChannel = @@ -1372,49 +1350,6 @@ export function ChannelMutateDrawer({ } } - const fetchChannelKey = useCallback( - async (proofToken?: string) => { - if (!channelId) { - throw new Error('Channel is not selected') - } - - setIsChannelKeyLoading(true) - try { - const res = await getChannelKey(channelId, proofToken) - if (!res.success) { - throw new Error(res.message || t('Failed to fetch channel key')) - } - - const keyValue = res.data?.key ?? '' - setChannelKey(keyValue) - toast.success(t('Channel key unlocked')) - return res - } finally { - setIsChannelKeyLoading(false) - } - }, - [channelId, t] - ) - - const handleRevealKey = useCallback(async () => { - if (!channelId) return - - try { - await withVerification(fetchChannelKey, { - scope: 'channel.key.read', - preferredMethod: 'passkey', - title: t('Verify to view channel key'), - description: t( - 'Use Passkey or 2FA to confirm your identity before revealing this channel key.' - ), - }) - } catch (error) { - if (error instanceof Error) { - toast.error(error.message) - } - } - }, [channelId, withVerification, fetchChannelKey, t]) - const handleRefreshCodexCredential = useCallback(async () => { if (!channelId) return setIsCodexCredentialRefreshing(true) @@ -3132,11 +3067,11 @@ export function ChannelMutateDrawer({ onClick={handleRevealKey} disabled={ isChannelKeyLoading || - verificationState.loading + verification.isActive } > {isChannelKeyLoading || - verificationState.loading ? ( + verification.isActive ? ( ) : ( @@ -4931,22 +4866,7 @@ export function ChannelMutateDrawer({ existingModelsOverride={currentModelsArray} /> - { - if (!open) { - cancelVerification() - } - }} - methods={verificationMethods} - state={verificationState} - onVerify={async (method, code) => { - await executeVerification(method, code) - }} - onCancel={cancelVerification} - onCodeChange={setVerificationCode} - onMethodChange={switchVerificationMethod} - /> + {/* Missing Models Confirmation Dialog */} . + +For commercial licensing, please contact support@quantumnous.com +*/ +import { act, render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { afterEach, expect, it, vi } from 'vitest' + +import { SecureVerificationDialog } from '@/features/auth/secure-verification' +import { api } from '@/lib/api' + +import { useChannelKeyDisclosure } from '../use-channel-key-disclosure' + +function Harness(props: { open: boolean; channelId: number }) { + const disclosure = useChannelKeyDisclosure(props.open, props.channelId) + return ( + <> + + + {disclosure.channelKey ?? 'Hidden'} + + + + ) +} + +function deferredResponse() { + let resolve!: (value: T) => void + const promise = new Promise((finish) => { + resolve = finish + }) + return { promise, resolve } +} + +function channelVerification() { + vi.spyOn(api, 'get').mockResolvedValue({ + data: { + success: true, + data: { + scope: 'channel.key.read', + methods: [{ method: '2fa', available: true }], + oauth_providers: [], + password_encryption_enabled: false, + }, + }, + }) + return { + data: { + success: true, + data: { + proof_token: 'channel-proof', + method: '2fa', + scope: 'channel.key.read', + expires_at: Math.floor(Date.now() / 1000) + 60, + }, + }, + } +} + +afterEach(() => vi.restoreAllMocks()) + +it.each(['switch', 'close'] as const)( + 'discards a pending channel key response after %s', + async (change) => { + const proof = channelVerification() + const keyReply = deferredResponse<{ + data: { success: boolean; data: { key: string } } + }>() + const post = vi.spyOn(api, 'post').mockImplementation((url) => { + if (url === '/api/verify') return Promise.resolve(proof) + if (url === '/api/channel/123/key') return keyReply.promise + throw new Error(`Unexpected POST ${url}`) + }) + const user = userEvent.setup() + const view = render() + await user.click(screen.getByRole('button', { name: 'Reveal' })) + await user.type( + await screen.findByLabelText('Authenticator code or backup code'), + '123456' + ) + await user.click(screen.getByRole('button', { name: 'Verify' })) + await waitFor(() => + expect(post).toHaveBeenCalledWith( + '/api/channel/123/key', + undefined, + expect.anything() + ) + ) + view.rerender( + + ) + await act(async () => { + keyReply.resolve({ + data: { success: true, data: { key: 'CHANNEL_A_SECRET' } }, + }) + await keyReply.promise + }) + expect(screen.getByLabelText('Channel key')).toHaveTextContent('Hidden') + expect(screen.queryByText('CHANNEL_A_SECRET')).not.toBeInTheDocument() + } +) + +it('cancels a pending verification when the selected channel changes', async () => { + channelVerification() + const reply = deferredResponse<{ + data: { success: boolean; data: Record } + }>() + const post = vi.spyOn(api, 'post').mockReturnValue(reply.promise) + const user = userEvent.setup() + const view = render() + await user.click(screen.getByRole('button', { name: 'Reveal' })) + await user.type( + await screen.findByLabelText('Authenticator code or backup code'), + '123456' + ) + await user.click(screen.getByRole('button', { name: 'Verify' })) + view.rerender() + await act(async () => { + reply.resolve({ + data: { + success: true, + data: { + proof_token: 'late-proof', + scope: 'channel.key.read', + method: '2fa', + expires_at: Math.floor(Date.now() / 1000) + 60, + }, + }, + }) + await reply.promise + }) + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() + expect(post.mock.calls.map(([url]) => url)).toEqual(['/api/verify']) +}) diff --git a/web/src/features/channels/hooks/use-channel-key-disclosure.ts b/web/src/features/channels/hooks/use-channel-key-disclosure.ts new file mode 100644 index 0000000000..3d97dd1f32 --- /dev/null +++ b/web/src/features/channels/hooks/use-channel-key-disclosure.ts @@ -0,0 +1,94 @@ +/* +Copyright (C) 2023-2026 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ +import { useCallback, useEffect, useRef, useState } from 'react' +import { useTranslation } from 'react-i18next' +import { toast } from 'sonner' + +import { useSecureVerification } from '@/features/auth/secure-verification' +import { AuthOperationError } from '@/lib/secure-verification' + +import { getChannelKey } from '../api' + +export function useChannelKeyDisclosure( + open: boolean, + channelId: number | null +) { + const { t } = useTranslation() + const verification = useSecureVerification() + const cancelVerification = verification.cancel + const requestVerification = verification.requestVerification + const [disclosedKey, setDisclosedKey] = useState<{ + channelId: number + key: string + } | null>(null) + const [isChannelKeyLoading, setIsChannelKeyLoading] = useState(false) + const operation = useRef(null) + + useEffect(() => { + setDisclosedKey(null) + setIsChannelKeyLoading(false) + return () => { + operation.current?.abort() + operation.current = null + cancelVerification() + } + }, [open, channelId, cancelVerification]) + + const handleRevealKey = useCallback(async () => { + if (!channelId || !open || operation.current) return + const current = new AbortController() + operation.current = current + try { + const proof = await requestVerification({ + scope: 'channel.key.read', + context: { channel_id: channelId }, + title: t('Verify to view channel key'), + description: t( + 'Use Passkey or 2FA to confirm your identity before revealing this channel key.' + ), + }) + if (!proof || operation.current !== current) return + setIsChannelKeyLoading(true) + const res = await getChannelKey( + channelId, + proof.proof_token, + current.signal + ) + if (operation.current !== current) return + if (!res.success) { + throw new Error(res.message || t('Failed to fetch channel key')) + } + setDisclosedKey({ channelId, key: res.data?.key ?? '' }) + toast.success(t('Channel key unlocked')) + } catch (error) { + if (operation.current === current && !current.signal.aborted) { + toast.error(t(AuthOperationError.from(error).message)) + } + } finally { + if (operation.current === current) { + operation.current = null + setIsChannelKeyLoading(false) + } + } + }, [channelId, open, requestVerification, t]) + + const channelKey = + open && disclosedKey?.channelId === channelId ? disclosedKey.key : null + return { channelKey, isChannelKeyLoading, handleRevealKey, verification } +} diff --git a/web/src/features/profile/types.ts b/web/src/features/profile/types.ts index 6fb4cac955..8aa2773aa3 100644 --- a/web/src/features/profile/types.ts +++ b/web/src/features/profile/types.ts @@ -179,15 +179,6 @@ export interface TwoFAStatus { backup_codes_remaining: number } -/** - * Two-Factor Authentication Setup Data - */ -export interface TwoFASetupData { - secret: string - qr_code_data: string - backup_codes: string[] -} - // ============================================================================ // Checkin Type Definitions // ============================================================================ diff --git a/web/src/features/security/__tests__/enrollment.test.tsx b/web/src/features/security/__tests__/enrollment.test.tsx new file mode 100644 index 0000000000..ae4d89412a --- /dev/null +++ b/web/src/features/security/__tests__/enrollment.test.tsx @@ -0,0 +1,542 @@ +/* +Copyright (C) 2023-2026 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ +import { render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { toast } from 'sonner' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' + +import { api } from '@/lib/api' + +import { PasskeyCard } from '../components/passkey-card' +import { TwoFACard } from '../components/two-fa-card' + +const credentialsDescriptor = Object.getOwnPropertyDescriptor( + navigator, + 'credentials' +) +const expiresAt = () => Math.floor(Date.now() / 1000) + 300 +const credential = { + id: 'credential', + rawId: new Uint8Array([1, 2, 3]).buffer, + type: 'public-key', + response: { + clientDataJSON: new Uint8Array([1]).buffer, + authenticatorData: new Uint8Array([2]).buffer, + signature: new Uint8Array([3]).buffer, + attestationObject: new Uint8Array([4]).buffer, + userHandle: null, + }, + getClientExtensionResults: () => ({}), +} + +beforeEach(() => { + vi.stubGlobal( + 'PublicKeyCredential', + class { + static isUserVerifyingPlatformAuthenticatorAvailable() { + return Promise.resolve(true) + } + } + ) + Object.defineProperty(navigator, 'credentials', { + configurable: true, + value: { + get: vi.fn().mockResolvedValue(credential), + create: vi.fn().mockResolvedValue(credential), + }, + }) +}) + +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() + if (credentialsDescriptor) { + Object.defineProperty(navigator, 'credentials', credentialsDescriptor) + } else Reflect.deleteProperty(navigator, 'credentials') +}) + +it('shows a retry when the 2FA status query fails instead of offering enrollment', async () => { + const get = vi + .spyOn(api, 'get') + .mockRejectedValue(new Error('Status unavailable')) + const user = userEvent.setup() + render() + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Status unavailable' + ) + expect( + screen.queryByRole('button', { name: 'Enable' }) + ).not.toBeInTheDocument() + get.mockResolvedValue({ + data: { + success: true, + data: { enabled: false, locked: false, backup_codes_remaining: 0 }, + }, + }) + await user.click(screen.getByRole('button', { name: 'Retry' })) + expect(await screen.findByRole('button', { name: 'Enable' })).toBeEnabled() +}) + +it('consumes Passkey authorization at setup and activates using only the dedicated flow', async () => { + let enabled = false + vi.spyOn(api, 'get').mockImplementation(async (url) => { + if (url === '/api/user/2fa/status') { + return { + data: { + success: true, + data: { enabled, locked: false, backup_codes_remaining: 4 }, + }, + } + } + if (url === '/api/verify/methods') { + return { + data: { + success: true, + data: { + scope: '2fa.setup', + methods: [{ method: 'passkey', available: true }], + oauth_providers: [], + password_encryption_enabled: false, + }, + }, + } + } + throw new Error(`Unexpected GET ${url}`) + }) + const posts = vi.spyOn(api, 'post').mockImplementation(async (url) => { + if (url === '/api/user/passkey/verify/begin') { + return { + data: { + success: true, + data: { + flow_token: 'passkey-flow', + options: { publicKey: { challenge: 'AQID', allowCredentials: [] } }, + }, + }, + } + } + if (url === '/api/user/passkey/verify/finish') { + return { + data: { + success: true, + data: { + proof_token: 'passkey-proof', + scope: '2fa.setup', + method: 'passkey', + expires_at: expiresAt(), + }, + }, + } + } + if (url === '/api/user/2fa/setup') { + return { + data: { + success: true, + data: { + secret: 'NEW_SECRET', + qr_code_data: 'otpauth://totp/account?secret=NEW_SECRET', + backup_codes: ['ABCD-1234'], + flow_token: 'setup-flow', + expires_at: expiresAt(), + }, + }, + } + } + if (url === '/api/user/2fa/enable') { + enabled = true + return { + data: { success: true, data: { access_token: 'rotated-session' } }, + } + } + throw new Error(`Unexpected POST ${url}`) + }) + const success = vi.spyOn(toast, 'success') + const user = userEvent.setup() + render() + await user.click(await screen.findByRole('button', { name: 'Enable' })) + await screen.findByText( + 'We will prompt your device to confirm using biometrics or your hardware key.' + ) + expect(posts.mock.calls.some(([url]) => url === '/api/user/2fa/setup')).toBe( + false + ) + expect(screen.queryByText('NEW_SECRET')).not.toBeInTheDocument() + await user.click(screen.getByRole('button', { name: 'Verify' })) + expect(await screen.findByText('NEW_SECRET')).toBeVisible() + expect(posts).toHaveBeenCalledWith( + '/api/user/2fa/setup', + undefined, + expect.objectContaining({ + headers: { 'X-Security-Proof': 'passkey-proof' }, + }) + ) + await user.click(screen.getByRole('button', { name: 'Next' })) + await user.click(screen.getByRole('button', { name: 'Next' })) + await user.type(screen.getByLabelText('Verification Code'), '123456') + await user.click(screen.getByRole('button', { name: 'Enable 2FA' })) + await waitFor(() => + expect(success).toHaveBeenCalledExactlyOnceWith( + 'Two-factor authentication enabled successfully!' + ) + ) + expect(posts).toHaveBeenCalledWith( + '/api/user/2fa/enable', + { code: '123456', flow_token: 'setup-flow' }, + expect.objectContaining({ + acceptAuthRotation: true, + }) + ) + expect( + posts.mock.calls.find(([url]) => url === '/api/user/2fa/enable')?.[2] + ?.headers + ).toBeUndefined() + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() +}) + +it('reports registration failure without treating a successful password check as a successful binding', async () => { + vi.spyOn(api, 'get').mockImplementation(async (url) => { + if (url === '/api/user/passkey') { + return { data: { success: true, data: { enabled: false } } } + } + if (url === '/api/verify/methods') { + return { + data: { + success: true, + data: { + scope: 'passkey.register', + methods: [{ method: 'password', available: true }], + oauth_providers: [], + password_encryption_enabled: false, + }, + }, + } + } + throw new Error(`Unexpected GET ${url}`) + }) + const posts = vi.spyOn(api, 'post').mockImplementation(async (url) => { + if (url === '/api/verify') { + return { + data: { + success: true, + data: { + proof_token: 'password-proof', + scope: 'passkey.register', + method: 'password', + expires_at: expiresAt(), + }, + }, + } + } + if (url === '/api/user/passkey/register/begin') { + return { + data: { + success: true, + data: { + flow_token: 'registration-flow', + options: { + publicKey: { + challenge: 'AQID', + rp: { name: 'Test', id: 'localhost' }, + user: { id: 'AQID', name: 'user', displayName: 'User' }, + pubKeyCredParams: [{ type: 'public-key', alg: -7 }], + }, + }, + }, + }, + } + } + if (url === '/api/user/passkey/register/finish') { + return { data: { success: false, message: 'Registration rejected' } } + } + throw new Error(`Unexpected POST ${url}`) + }) + const success = vi.spyOn(toast, 'success') + const failure = vi.spyOn(toast, 'error') + const user = userEvent.setup() + render() + const enable = await screen.findByRole('button', { name: 'Enable Passkey' }) + await waitFor(() => expect(enable).toBeEnabled()) + await user.click(enable) + await user.type( + await screen.findByLabelText('Password', { selector: 'input' }), + 'password' + ) + await user.click(screen.getByRole('button', { name: 'Verify' })) + await waitFor(() => + expect(failure).toHaveBeenCalledWith('Registration rejected') + ) + expect(success).not.toHaveBeenCalled() + expect(posts).toHaveBeenCalledWith( + '/api/user/passkey/register/begin', + undefined, + expect.objectContaining({ + headers: { 'X-Security-Proof': 'password-proof' }, + }) + ) + expect(posts).toHaveBeenCalledWith( + '/api/user/passkey/register/finish', + expect.objectContaining({ flow_token: 'registration-flow' }), + expect.objectContaining({ + acceptAuthRotation: true, + }) + ) + expect( + posts.mock.calls.find( + ([url]) => url === '/api/user/passkey/register/finish' + )?.[2]?.headers + ).toBeUndefined() +}) + +it.each(['proof', 'setup'] as const)( + 'handles an expired %s without reusing a proof or replacing an active setup', + async (expired) => { + const issuedAt = Date.now() + const clock = vi.spyOn(Date, 'now').mockReturnValue(issuedAt) + vi.spyOn(api, 'get').mockImplementation(async (url) => { + if (url === '/api/user/2fa/status') { + return { + data: { success: true, data: { enabled: false, locked: false } }, + } + } + if (url === '/api/verify/methods') { + return { + data: { + success: true, + data: { + scope: '2fa.setup', + methods: [{ method: 'password', available: true }], + oauth_providers: [], + password_encryption_enabled: false, + }, + }, + } + } + throw new Error(`Unexpected GET ${url}`) + }) + let proofCount = 0 + let setupCount = 0 + const posts = vi.spyOn(api, 'post').mockImplementation(async (url) => { + if (url === '/api/verify') { + proofCount += 1 + return { + data: { + success: true, + data: { + proof_token: `proof-${proofCount}`, + scope: '2fa.setup', + method: 'password', + expires_at: Math.floor(Date.now() / 1000) + 60, + }, + }, + } + } + if (url === '/api/user/2fa/setup') { + setupCount += 1 + return { + data: { + success: true, + data: { + secret: setupCount === 1 ? 'OLD_SECRET' : 'NEW_SECRET', + qr_code_data: 'otpauth://totp/account?secret=SECRET', + backup_codes: [setupCount === 1 ? 'OLD-CODE' : 'NEW-CODE'], + flow_token: `setup-${setupCount}`, + expires_at: expiresAt(), + }, + }, + } + } + if (url === '/api/user/2fa/enable') { + return { data: { success: true, data: {} } } + } + throw new Error(`Unexpected POST ${url}`) + }) + const user = userEvent.setup() + const info = vi.spyOn(toast, 'info') + const success = vi.spyOn(toast, 'success') + render() + await user.click(await screen.findByRole('button', { name: 'Enable' })) + await user.type( + await screen.findByLabelText('Password', { selector: 'input' }), + 'password' + ) + await user.click(screen.getByRole('button', { name: 'Verify' })) + expect(await screen.findByText('OLD_SECRET')).toBeVisible() + await user.click(screen.getByRole('button', { name: 'Next' })) + await user.click(screen.getByRole('button', { name: 'Next' })) + await user.type(screen.getByLabelText('Verification Code'), '123456') + + clock.mockReturnValue(issuedAt + (expired === 'proof' ? 150_000 : 301_000)) + await user.click(screen.getByRole('button', { name: 'Enable 2FA' })) + if (expired === 'proof') { + await waitFor(() => + expect(success).toHaveBeenCalledExactlyOnceWith( + 'Two-factor authentication enabled successfully!' + ) + ) + expect(posts).toHaveBeenCalledWith( + '/api/user/2fa/enable', + { code: '123456', flow_token: 'setup-1' }, + expect.objectContaining({ acceptAuthRotation: true }) + ) + expect(proofCount).toBe(1) + expect( + screen.queryByLabelText('Password', { selector: 'input' }) + ).not.toBeInTheDocument() + expect( + posts.mock.calls.filter(([url]) => url === '/api/user/2fa/setup') + ).toHaveLength(1) + } else { + const password = await screen.findByLabelText('Password', { + selector: 'input', + }) + expect(password).toHaveValue('') + expect( + posts.mock.calls.filter(([url]) => url === '/api/user/2fa/enable') + ).toHaveLength(0) + await user.type(password, 'password') + await user.click(screen.getByRole('button', { name: 'Verify' })) + expect(await screen.findByText('NEW_SECRET')).toBeVisible() + expect(screen.queryByText('OLD_SECRET')).not.toBeInTheDocument() + expect(info).toHaveBeenCalledWith( + 'Setup expired. Scan the new QR code and save the new backup codes.' + ) + expect( + posts.mock.calls.filter(([url]) => url === '/api/user/2fa/enable') + ).toHaveLength(0) + await user.click(screen.getByRole('button', { name: 'Next' })) + expect(await screen.findByText('NEW-CODE')).toBeVisible() + expect(screen.queryByText('OLD-CODE')).not.toBeInTheDocument() + } + } +) + +it.each(['wrong code', 'response lost'] as const)( + 'handles %s during activation without reusing the setup proof', + async (failure) => { + let enabled = false + const get = vi.spyOn(api, 'get').mockImplementation(async (url) => { + if (url === '/api/user/2fa/status') { + return { data: { success: true, data: { enabled, locked: false } } } + } + if (url === '/api/verify/methods') { + return { + data: { + success: true, + data: { + scope: '2fa.setup', + methods: [{ method: 'password', available: true }], + oauth_providers: [], + password_encryption_enabled: false, + }, + }, + } + } + throw new Error(`Unexpected GET ${url}`) + }) + let enableAttempts = 0 + const post = vi.spyOn(api, 'post').mockImplementation(async (url) => { + if (url === '/api/verify') { + return { + data: { + success: true, + data: { + proof_token: 'setup-proof', + scope: '2fa.setup', + method: 'password', + expires_at: expiresAt(), + }, + }, + } + } + if (url === '/api/user/2fa/setup') { + return { + data: { + success: true, + data: { + secret: 'SETUP_SECRET', + qr_code_data: 'otpauth://totp/account?secret=SETUP_SECRET', + backup_codes: ['ABCD-1234'], + flow_token: 'setup-flow', + expires_at: expiresAt(), + }, + }, + } + } + if (url === '/api/user/2fa/enable') { + enableAttempts++ + if (failure === 'response lost') { + enabled = true + throw new Error('Connection lost') + } + if (enableAttempts === 1) { + return { data: { success: false, code: 'TWOFA_CODE_INVALID' } } + } + enabled = true + return { data: { success: true, data: {} } } + } + throw new Error(`Unexpected POST ${url}`) + }) + const user = userEvent.setup() + render() + await user.click(await screen.findByRole('button', { name: 'Enable' })) + await user.type( + await screen.findByLabelText('Password', { selector: 'input' }), + 'password' + ) + await user.click(screen.getByRole('button', { name: 'Verify' })) + await screen.findByText('SETUP_SECRET') + await user.click(screen.getByRole('button', { name: 'Next' })) + await user.click(screen.getByRole('button', { name: 'Next' })) + await user.type(screen.getByLabelText('Verification Code'), '123456') + await user.click(screen.getByRole('button', { name: 'Enable 2FA' })) + if (failure === 'wrong code') { + expect( + await screen.findByText('The authenticator code is incorrect.') + ).toBeVisible() + await user.clear(screen.getByLabelText('Verification Code')) + await user.type(screen.getByLabelText('Verification Code'), '654321') + await user.click(screen.getByRole('button', { name: 'Enable 2FA' })) + } + await waitFor(() => + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() + ) + await waitFor(() => + expect( + get.mock.calls.filter(([url]) => url === '/api/user/2fa/status') + ).toHaveLength(2) + ) + expect( + post.mock.calls.filter(([url]) => url === '/api/verify') + ).toHaveLength(1) + expect( + post.mock.calls.filter(([url]) => url === '/api/user/2fa/setup') + ).toHaveLength(1) + const activations = post.mock.calls.filter( + ([url]) => url === '/api/user/2fa/enable' + ) + expect(activations).toHaveLength(failure === 'wrong code' ? 2 : 1) + for (const [, body, config] of activations) { + expect(body).toMatchObject({ flow_token: 'setup-flow' }) + expect(config?.headers).toBeUndefined() + } + expect( + screen.queryByRole('button', { name: 'Enable' }) + ).not.toBeInTheDocument() + } +) diff --git a/web/src/features/security/api.ts b/web/src/features/security/api.ts index b9cbf72a7b..9cbb513ed2 100644 --- a/web/src/features/security/api.ts +++ b/web/src/features/security/api.ts @@ -16,8 +16,9 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ -import type { ApiResponse } from '@/features/profile/types' +import type { ApiResponse, TwoFAStatus } from '@/features/profile/types' import { api } from '@/lib/api' +import { authRequestOptions, authResult } from '@/lib/secure-verification' export interface AccessTokenStatus { exists: boolean @@ -51,3 +52,47 @@ export async function revokeAccessToken(): Promise { throw new Error(response.data.message || 'Failed to revoke token') } } + +export interface TwoFASetupData { + secret: string + qr_code_data: string + backup_codes: string[] + flow_token: string + expires_at: number +} + +export function get2FAStatus(): Promise { + return authResult(api.get('/api/user/2fa/status', authRequestOptions)) +} + +export function setup2FA( + proofToken: string, + signal: AbortSignal +): Promise { + return authResult( + api.post('/api/user/2fa/setup', undefined, { + ...authRequestOptions, + signal, + headers: { 'X-Security-Proof': proofToken }, + }) + ) +} + +export function enable2FA( + code: string, + flowToken: string, + signal: AbortSignal +): Promise { + return authResult( + api.post( + '/api/user/2fa/enable', + { code, flow_token: flowToken }, + { + ...authRequestOptions, + signal, + acceptAuthRotation: true, + singleUseAuthorization: true, + } + ) + ) +} diff --git a/web/src/features/security/components/account-bindings.tsx b/web/src/features/security/components/account-bindings.tsx index 0f7e45fbac..e6615e3c59 100644 --- a/web/src/features/security/components/account-bindings.tsx +++ b/web/src/features/security/components/account-bindings.tsx @@ -28,14 +28,9 @@ import { StatusBadge } from '@/components/status-badge' import { Button } from '@/components/ui/button' import { createOAuthFlow } from '@/features/auth/api' import { - OAUTH_BIND_CALLBACK_MESSAGE, - OAUTH_BIND_RESULT_MESSAGE, -} from '@/features/auth/constants' -import { watchOAuthPopupClosed } from '@/features/auth/lib/oauth-bind-window' -import { - getOAuthSessionStorage, - markOAuthBindPopup, -} from '@/features/auth/lib/oauth-callback-mode' + openOAuthPopup, + type OAuthPopupExchange, +} from '@/features/auth/lib/oauth-popup' import type { CustomOAuthProviderInfo } from '@/features/auth/types' import { getSelfOAuthBindings, unbindCustomOAuth } from '@/features/profile/api' import type { UserProfile, BindingItem } from '@/features/profile/types' @@ -43,13 +38,15 @@ import { useDialogs } from '@/hooks/use-dialog' import { useStatus } from '@/hooks/use-status' import { api } from '@/lib/api' import { - buildDiscordOAuthUrl, - buildGitHubOAuthUrl, + buildOAuthAuthorizationUrl, indexCustomOAuthBindings, - buildLinuxDOOAuthUrl, - buildOIDCOAuthUrl, type CustomOAuthBinding, } from '@/lib/oauth' +import { + AuthOperationError, + authRequestOptions, + authResult, +} from '@/lib/secure-verification' import { EmailBindDialog } from './dialogs/email-bind-dialog' import { TelegramBindDialog } from './dialogs/telegram-bind-dialog' @@ -66,22 +63,6 @@ interface AccountBindingsProps { type DialogKey = 'email' | 'wechat' | 'telegram' -interface PendingOAuthBinding { - provider: string - state: string - popup: Window - stopCloseWatcher: () => void -} - -interface OAuthBindingCallback { - type: typeof OAUTH_BIND_CALLBACK_MESSAGE - provider: string - state: string - code?: string - error?: string - errorDescription?: string -} - export function AccountBindings({ profile, onUpdate }: AccountBindingsProps) { const { t } = useTranslation() const dialogs = useDialogs() @@ -91,17 +72,7 @@ export function AccountBindings({ profile, onUpdate }: AccountBindingsProps) { null ) const [unbinding, setUnbinding] = useState(false) - const pendingOAuthBinding = useRef(null) - - const clearPendingOAuthBinding = useCallback( - (expected?: PendingOAuthBinding) => { - const pending = pendingOAuthBinding.current - if (!pending || (expected && pending !== expected)) return - pending.stopCloseWatcher() - pendingOAuthBinding.current = null - }, - [] - ) + const pendingOAuthBinding = useRef(null) const customProviders = status?.custom_oauth_providers as | CustomOAuthProviderInfo[] @@ -152,143 +123,76 @@ export function AccountBindings({ profile, onUpdate }: AccountBindingsProps) { } const startOAuthBinding = useCallback( - async (provider: string, buildUrl: (state: string) => string) => { - const previous = pendingOAuthBinding.current - if (previous) { - clearPendingOAuthBinding(previous) - if (!previous.popup.closed) previous.popup.close() - } - - const popup = window.open('', '_blank') - if (!popup) { - toast.error(t('OAuth pop-up was blocked')) - return - } - const pending: PendingOAuthBinding = { - provider, - state: '', - popup, - stopCloseWatcher: () => undefined, - } - pending.stopCloseWatcher = watchOAuthPopupClosed(popup, () => - clearPendingOAuthBinding(pending) - ) - pendingOAuthBinding.current = pending + async (provider: string) => { + pendingOAuthBinding.current?.abort() + const controller = new AbortController() + pendingOAuthBinding.current = controller + let exchange: OAuthPopupExchange | undefined try { - const state = await createOAuthFlow(provider, 'bind') - if (pendingOAuthBinding.current !== pending || popup.closed) return - // Stamp the popup while it is still same-origin (about:blank). Tying - // the mark to this state prevents a stale popup from claiming a later - // login callback. If storage is blocked, do not navigate into a - // callback that cannot safely identify the bind flow. - if ( - !markOAuthBindPopup(getOAuthSessionStorage(popup), provider, state) - ) { - throw new Error('OAuth bind popup storage is unavailable') + exchange = await openOAuthPopup({ + provider, + intent: 'bind', + signal: controller.signal, + prepare: async (signal) => { + const state = await createOAuthFlow( + provider, + 'bind', + undefined, + signal + ) + return { + state, + url: buildOAuthAuthorizationUrl(provider, state, status ?? {}), + } + }, + }) + const callback = exchange.callback + await authResult( + api.get(`/api/oauth/${provider}`, { + ...authRequestOptions, + disableDuplicate: true, + signal: exchange.signal, + params: { + state: callback.state, + code: callback.code, + error: callback.error, + error_description: callback.errorDescription, + }, + }) + ) + exchange.signal.throwIfAborted() + exchange.finish({ success: true }) + toast.success(t('Binding successful!')) + onUpdate() + await fetchCustomBindings() + } catch (error) { + const failure = AuthOperationError.from( + exchange?.signal.aborted ? exchange.signal.reason : error + ) + exchange?.finish({ success: false, message: failure.message }) + if (!controller.signal.aborted && failure.code !== 'AUTH_CANCELLED') { + toast.error(t(failure.message)) + } + } finally { + if (pendingOAuthBinding.current === controller) { + pendingOAuthBinding.current = null } - pending.state = state - popup.location.replace(buildUrl(state)) - } catch { - const isCurrent = pendingOAuthBinding.current === pending - clearPendingOAuthBinding(pending) - popup.close() - if (isCurrent) toast.error(t('Failed to initialize OAuth')) } }, - [clearPendingOAuthBinding, t] + [fetchCustomBindings, onUpdate, status, t] ) - const handleBindCustomOAuth = async (provider: CustomOAuthProviderInfo) => { - await startOAuthBinding(provider.slug, (state) => { - const redirectUri = `${window.location.origin}/oauth/${provider.slug}` - const url = new URL(provider.authorization_endpoint) - url.searchParams.set('client_id', provider.client_id) - url.searchParams.set('redirect_uri', redirectUri) - url.searchParams.set('response_type', 'code') - url.searchParams.set('state', state) - if (provider.scopes) url.searchParams.set('scope', provider.scopes) - return url.toString() - }) - } - - useEffect(() => { - if (typeof window === 'undefined') return - - const handleMessage = async (event: MessageEvent) => { - if (event.origin !== window.location.origin) return - const message = event.data as Partial | null - const pending = pendingOAuthBinding.current - if ( - !message || - message.type !== OAUTH_BIND_CALLBACK_MESSAGE || - !pending || - message.provider !== pending.provider || - message.state !== pending.state || - event.source !== pending.popup - ) { - return - } - - clearPendingOAuthBinding(pending) - let success = false - let resultMessage = t('OAuth failed') - try { - if (!message.code && !message.error) { - throw new Error(t('Missing code')) - } - const params: Record = { state: message.state } - if (message.code) params.code = message.code - if (message.error) params.error = message.error - if (message.errorDescription) { - params.error_description = message.errorDescription - } - const response = await api.get(`/api/oauth/${message.provider}`, { - params, - skipBusinessError: true, - }) - success = Boolean(response.data?.success) - resultMessage = response.data?.message || resultMessage - if (success) { - toast.success(t('Binding successful!')) - onUpdate() - await fetchCustomBindings() - } else { - toast.error(resultMessage) - } - } catch (error: unknown) { - resultMessage = - (error as { response?: { data?: { message?: string } } }).response - ?.data?.message || - (error instanceof Error ? error.message : resultMessage) - toast.error(resultMessage) - } - - pending.popup.postMessage( - { - type: OAUTH_BIND_RESULT_MESSAGE, - provider: message.provider, - state: message.state, - success, - message: resultMessage, - }, - window.location.origin - ) - } - - window.addEventListener('message', handleMessage) - return () => window.removeEventListener('message', handleMessage) - }, [clearPendingOAuthBinding, fetchCustomBindings, onUpdate, t]) + const handleBindCustomOAuth = (provider: CustomOAuthProviderInfo) => + startOAuthBinding(provider.slug) useEffect( () => () => { - const pending = pendingOAuthBinding.current - clearPendingOAuthBinding(pending ?? undefined) - if (pending && !pending.popup.closed) pending.popup.close() + pendingOAuthBinding.current?.abort() + pendingOAuthBinding.current = null }, - [clearPendingOAuthBinding] + [] ) - // Memoize bindings to prevent unnecessary recalculations const bindings: BindingItem[] = useMemo(() => { if (!profile || !status) return [] @@ -324,14 +228,7 @@ export function AccountBindings({ profile, onUpdate }: AccountBindingsProps) { (profile as unknown as Record).github_id ), isEnabled: status?.github_oauth || false, - onBind: () => { - const clientId = status?.github_client_id - if (clientId) { - void startOAuthBinding('github', (state) => - buildGitHubOAuthUrl(clientId, state) - ) - } - }, + onBind: () => void startOAuthBinding('github'), }, { id: 'discord', @@ -344,14 +241,7 @@ export function AccountBindings({ profile, onUpdate }: AccountBindingsProps) { (profile as unknown as Record).discord_id ), isEnabled: status?.discord_oauth || false, - onBind: () => { - const clientId = status?.discord_client_id - if (clientId) { - void startOAuthBinding('discord', (state) => - buildDiscordOAuthUrl(clientId, state) - ) - } - }, + onBind: () => void startOAuthBinding('discord'), }, { id: 'oidc', @@ -364,15 +254,7 @@ export function AccountBindings({ profile, onUpdate }: AccountBindingsProps) { (profile as unknown as Record).oidc_id ), isEnabled: status?.oidc_enabled || false, - onBind: () => { - const authorizationEndpoint = status?.oidc_authorization_endpoint - const clientId = status?.oidc_client_id - if (authorizationEndpoint && clientId) { - void startOAuthBinding('oidc', (state) => - buildOIDCOAuthUrl(authorizationEndpoint, clientId, state) - ) - } - }, + onBind: () => void startOAuthBinding('oidc'), }, { id: 'telegram', @@ -398,18 +280,10 @@ export function AccountBindings({ profile, onUpdate }: AccountBindingsProps) { (profile as unknown as Record).linux_do_id ), isEnabled: status?.linuxdo_oauth || false, - onBind: () => { - const clientId = status?.linuxdo_client_id - if (clientId) { - void startOAuthBinding('linuxdo', (state) => - buildLinuxDOOAuthUrl(clientId, state) - ) - } - }, + onBind: () => void startOAuthBinding('linuxdo'), }, ].filter((binding) => binding.isEnabled) - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [profile, status, t]) + }, [profile, status, startOAuthBinding, dialogs, t]) if (!profile || loading) return null diff --git a/web/src/features/security/components/dialogs/two-fa-setup-dialog.tsx b/web/src/features/security/components/dialogs/two-fa-setup-dialog.tsx index a31f474090..27f6c36494 100644 --- a/web/src/features/security/components/dialogs/two-fa-setup-dialog.tsx +++ b/web/src/features/security/components/dialogs/two-fa-setup-dialog.tsx @@ -18,9 +18,8 @@ For commercial licensing, please contact support@quantumnous.com */ import { Loader2 } from 'lucide-react' import { QRCodeSVG } from 'qrcode.react' -import { useState, useEffect, useCallback } from 'react' +import { useState } from 'react' import { useTranslation } from 'react-i18next' -import { toast } from 'sonner' import { CopyButton } from '@/components/copy-button' import { Dialog } from '@/components/dialog' @@ -28,8 +27,8 @@ import { Alert, AlertDescription } from '@/components/ui/alert' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' -import type { TwoFASetupData } from '@/features/profile/types' -import { setup2FA, enable2FA } from '@/lib/api' + +import type { TwoFASetupData } from '../../api' // ============================================================================ // Two-FA Setup Dialog Component @@ -37,102 +36,29 @@ import { setup2FA, enable2FA } from '@/lib/api' interface TwoFASetupDialogProps { open: boolean - onOpenChange: (open: boolean) => void - onSuccess: () => void + setupData: TwoFASetupData | null + loading: boolean + initializing: boolean + error?: string + onCancel: () => void + onEnable: (code: string) => Promise } -export function TwoFASetupDialog({ - open, - onOpenChange, - onSuccess, -}: TwoFASetupDialogProps) { +export function TwoFASetupDialog(props: TwoFASetupDialogProps) { const { t } = useTranslation() - const [loading, setLoading] = useState(false) - const [initializing, setInitializing] = useState(false) const [step, setStep] = useState(0) - const [setupData, setSetupData] = useState(null) const [code, setCode] = useState('') const stepLabels = [ t('Scan QR Code'), t('Save Backup Codes'), t('Verify Setup'), ] - - const handleSetup = useCallback(async () => { - try { - setInitializing(true) - const response = await setup2FA() - - if (response.success && response.data) { - setSetupData(response.data) - setStep(0) - } else { - toast.error(response.message || t('Failed to setup 2FA')) - onOpenChange(false) - } - } catch (error) { - // eslint-disable-next-line no-console - console.error('Setup 2FA error:', error) - toast.error(t('Failed to setup 2FA')) - onOpenChange(false) - } finally { - setInitializing(false) - } - }, [onOpenChange, t]) - - const handleEnable = async () => { - if (!code) { - toast.error(t('Please enter the verification code')) - return - } - - try { - setLoading(true) - const response = await enable2FA(code) - - if (response.success) { - toast.success(t('Two-factor authentication enabled successfully!')) - onOpenChange(false) - onSuccess() - // Reset - setStep(0) - setCode('') - setSetupData(null) - } else { - toast.error(response.message || t('Failed to enable 2FA')) - } - } catch { - toast.error(t('Failed to enable 2FA')) - } finally { - setLoading(false) - } - } - - const handleOpenChange = (open: boolean) => { - if (!loading && !initializing) { - if (open && !setupData) { - handleSetup() - } - if (!open) { - setStep(0) - setCode('') - setSetupData(null) - } - onOpenChange(open) - } - } - - // Initialize when dialog opens - useEffect(() => { - if (open && !setupData && !initializing) { - handleSetup() - } - }, [open, setupData, initializing, handleSetup]) - return ( { + if (!open) props.onCancel() + }} title={t('Setup Two-Factor Authentication')} description={ <> @@ -151,7 +77,7 @@ export function TwoFASetupDialog({ @@ -159,24 +85,31 @@ export function TwoFASetupDialog({ {step < 2 ? ( ) : ( )} } >
- {initializing && ( + {props.error && ( +

+ {t(props.error)} +

+ )} + {props.initializing && (
@@ -184,14 +117,14 @@ export function TwoFASetupDialog({
)} - {!initializing && !setupData && ( + {!props.initializing && !props.setupData && (
{t('Failed to load setup data')}
)} - {!initializing && setupData && ( + {!props.initializing && props.setupData && ( <> {/* Step 0: QR Code */} {step === 0 && ( @@ -202,7 +135,7 @@ export function TwoFASetupDialog({ )}

- +
@@ -211,11 +144,11 @@ export function TwoFASetupDialog({ {t('Or enter this key manually:')}

- {setupData.secret} + {props.setupData.secret}
- {setupData.backup_codes.map((code) => ( + {props.setupData.backup_codes.map((code) => (
setCode(e.target.value)} placeholder={t('Enter 6-digit code')} maxLength={6} - disabled={loading} + disabled={props.loading} />

{t('Enter the 6-digit code from your authenticator app')} diff --git a/web/src/features/security/components/passkey-card.tsx b/web/src/features/security/components/passkey-card.tsx index 21fd59cc33..3823ae8b21 100644 --- a/web/src/features/security/components/passkey-card.tsx +++ b/web/src/features/security/components/passkey-card.tsx @@ -17,7 +17,7 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ import { AlertTriangle, KeyRound, Loader2, ShieldAlert } from 'lucide-react' -import { useCallback, useMemo, useState } from 'react' +import { useCallback, useState } from 'react' import { useTranslation } from 'react-i18next' import { toast } from 'sonner' @@ -47,10 +47,9 @@ import { usePasskeyManagement } from '@/features/auth/passkey' import { SecureVerificationDialog, useSecureVerification, - type VerificationMethod, - type VerificationMethods, } from '@/features/auth/secure-verification' import dayjs from '@/lib/dayjs' +import { AuthOperationError } from '@/lib/secure-verification' interface PasskeyCardProps { loading: boolean @@ -59,11 +58,10 @@ interface PasskeyCardProps { export function PasskeyCard({ loading: pageLoading }: PasskeyCardProps) { const { t } = useTranslation() const [confirmOpen, setConfirmOpen] = useState(false) - const [restrictedMethod, setRestrictedMethod] = - useState(null) - const { status, + statusError, + fetchStatus, loading, registering, removing, @@ -74,121 +72,38 @@ export function PasskeyCard({ loading: pageLoading }: PasskeyCardProps) { remove, } = usePasskeyManagement() - const { - open: verificationOpen, - setOpen: setVerificationOpen, - methods: verificationMethods, - state: verificationState, - startVerification, - executeVerification, - cancel: cancelVerification, - setCode, - switchMethod, - fetchVerificationMethods, - } = useSecureVerification({ - onSuccess: () => { - setRestrictedMethod(null) - }, - }) - - const dialogMethods = useMemo(() => { - if (!restrictedMethod) return verificationMethods - return { - ...verificationMethods, - has2FA: restrictedMethod === '2fa' && verificationMethods.has2FA, - hasPasskey: - restrictedMethod === 'passkey' && verificationMethods.hasPasskey, - } - }, [restrictedMethod, verificationMethods]) + const verification = useSecureVerification() const handleRegister = useCallback(async () => { - if (!supported) { - toast.info(t('This device does not support Passkey')) - return - } - - const methods = await fetchVerificationMethods() - if (!methods.has2FA) { - // Without 2FA enabled, register directly. The browser-level Passkey prompt - // is itself a strong proof of presence, so no extra verification is needed. - await register() - return - } - - setRestrictedMethod('2fa') - await startVerification(register, { + if (registering || removing || verification.isActive) return + const proof = await verification.requestVerification({ scope: 'passkey.register', - preferredMethod: '2fa', - title: t('Security verification'), - description: t( - 'Confirm your identity with Two-factor Authentication before registering a Passkey.' - ), }) - }, [fetchVerificationMethods, register, startVerification, supported, t]) + if (!proof) return + try { + await register(proof.proof_token) + toast.success(t('Passkey registered successfully')) + } catch (error) { + const failure = AuthOperationError.from(error) + if (failure.code !== 'AUTH_CANCELLED') toast.error(t(failure.message)) + } + }, [register, registering, removing, t, verification]) const handleRemove = useCallback(async () => { - const methods = await fetchVerificationMethods() - let required: VerificationMethod | null = null - if (methods.has2FA) { - required = '2fa' - } else if (methods.hasPasskey) { - required = 'passkey' - } - - if (!required) { - toast.error( - t( - 'Please enable Two-factor Authentication or Passkey before proceeding' - ) - ) - return - } - - if (required === 'passkey' && !methods.passkeySupported) { - toast.info(t('This device does not support Passkey')) - return - } - + if (registering || removing || verification.isActive) return setConfirmOpen(false) - setRestrictedMethod(required) - await startVerification(remove, { + const proof = await verification.requestVerification({ scope: 'passkey.delete', - preferredMethod: required, - title: t('Security verification'), - description: t( - 'Confirm your identity before removing this Passkey from your account.' - ), }) - }, [fetchVerificationMethods, remove, startVerification, t]) - - const handleVerificationCancel = useCallback(() => { - setRestrictedMethod(null) - cancelVerification() - }, [cancelVerification]) - - const handleVerificationOpenChange = useCallback( - (next: boolean) => { - if (!next) { - setRestrictedMethod(null) - } - setVerificationOpen(next) - }, - [setVerificationOpen] - ) - - // Adapt the hook's `Promise` return into the dialog's - // `void | Promise` signature without losing error propagation - // semantics (errors are surfaced via toast inside the hook). - const handleDialogVerify = useCallback( - async (method: VerificationMethod, code?: string) => { - try { - await executeVerification(method, code) - } catch { - // Errors are already surfaced by useSecureVerification via toast. - } - }, - [executeVerification] - ) + if (!proof) return + try { + await remove(proof.proof_token) + toast.success(t('Passkey removed successfully')) + } catch (error) { + const failure = AuthOperationError.from(error) + if (failure.code !== 'AUTH_CANCELLED') toast.error(t(failure.message)) + } + }, [registering, remove, removing, t, verification]) if (pageLoading || loading) { return ( @@ -204,6 +119,20 @@ export function PasskeyCard({ loading: pageLoading }: PasskeyCardProps) { ) } + if (statusError) { + return ( + + + {t('Passkey Login')} + + +

{t(statusError)}

+ + + + ) + } + const formattedLastUsed = lastUsed && !Number.isNaN(Date.parse(lastUsed)) ? dayjs(lastUsed).fromNow() @@ -276,7 +205,7 @@ export function PasskeyCard({ loading: pageLoading }: PasskeyCardProps) { + + + ) + } + return ( <> @@ -126,7 +143,8 @@ export function TwoFACard({ loading: pageLoading }: TwoFACardProps) { {!status.enabled && ( @@ -159,12 +177,10 @@ export function TwoFACard({ loading: pageLoading }: TwoFACardProps) { {/* Dialogs */} + - open ? dialogs.open('setup') : dialogs.close('setup') - } - onSuccess={refetch} + key={setup.setupDialogProps.setupData?.flow_token ?? 'initializing'} + {...setup.setupDialogProps} /> . + +For commercial licensing, please contact support@quantumnous.com +*/ +import { useCallback, useEffect, useRef, useState } from 'react' +import { useTranslation } from 'react-i18next' +import { toast } from 'sonner' + +import { useSecureVerification } from '@/features/auth/secure-verification' +import { AuthOperationError } from '@/lib/secure-verification' + +import { enable2FA, setup2FA, type TwoFASetupData } from '../api' + +type SetupState = + | { phase: 'closed' | 'initializing' } + | { phase: 'authorizing' } + | { phase: 'ready' | 'enabling'; setup: TwoFASetupData; error?: string } + +interface SetupFlow { + controller: AbortController + setup?: TwoFASetupData + submitting: boolean +} + +export function useTwoFASetup(refreshStatus: () => void | Promise) { + const { t } = useTranslation() + const verification = useSecureVerification() + const requestVerification = verification.requestVerification + const cancelVerification = verification.cancel + const [state, setState] = useState({ phase: 'closed' }) + const currentFlow = useRef(null) + + const cancel = useCallback(() => { + const current = currentFlow.current + currentFlow.current = null + current?.controller.abort() + cancelVerification() + setState({ phase: 'closed' }) + }, [cancelVerification]) + useEffect(() => cancel, [cancel]) + + const initialize = useCallback( + async (current: SetupFlow) => { + current.setup = undefined + setState({ phase: 'authorizing' }) + const proof = await requestVerification({ scope: '2fa.setup' }) + if (currentFlow.current !== current) return + if (!proof) { + cancel() + return + } + setState({ phase: 'initializing' }) + try { + const setup = await setup2FA( + proof.proof_token, + current.controller.signal + ) + if (currentFlow.current !== current) return + current.setup = setup + setState({ phase: 'ready', setup }) + } catch (error) { + if (currentFlow.current !== current) return + toast.error(t(AuthOperationError.from(error).message)) + cancel() + await refreshStatus() + } + }, + [cancel, refreshStatus, requestVerification, t] + ) + + const start = useCallback(() => { + if (currentFlow.current) return + const current: SetupFlow = { + controller: new AbortController(), + submitting: false, + } + currentFlow.current = current + void initialize(current) + }, [initialize]) + + const enable = useCallback( + async (code: string) => { + const current = currentFlow.current + if (!current?.setup || current.submitting || state.phase !== 'ready') { + return + } + current.submitting = true + const setup = current.setup + setState({ phase: 'enabling', setup }) + try { + if (setup.expires_at * 1000 <= Date.now()) { + toast.info( + t( + 'Setup expired. Scan the new QR code and save the new backup codes.' + ) + ) + await initialize(current) + return + } + await enable2FA(code, setup.flow_token, current.controller.signal) + if (currentFlow.current !== current) return + cancel() + toast.success(t('Two-factor authentication enabled successfully!')) + await refreshStatus() + } catch (error) { + if (currentFlow.current !== current) return + const failure = AuthOperationError.from(error) + if (failure.code === 'TWOFA_SETUP_INVALID') { + toast.info( + t( + 'Setup expired. Scan the new QR code and save the new backup codes.' + ) + ) + await initialize(current) + return + } + if (failure.code === 'TWOFA_CODE_INVALID') { + setState({ phase: 'ready', setup, error: failure.message }) + return + } + cancel() + toast.error(t(failure.message)) + toast.info(t('Verify again before retrying this action.')) + await refreshStatus() + } finally { + current.submitting = false + } + }, + [cancel, initialize, refreshStatus, state.phase, t] + ) + + const setup = 'setup' in state ? (state.setup ?? null) : null + return { + start, + active: state.phase !== 'closed', + verificationDialogProps: verification.dialogProps, + setupDialogProps: { + open: + state.phase === 'initializing' || + state.phase === 'ready' || + state.phase === 'enabling', + setupData: setup, + loading: state.phase === 'enabling', + initializing: state.phase === 'initializing', + error: 'error' in state ? state.error : undefined, + onCancel: cancel, + onEnable: enable, + }, + } +} diff --git a/web/src/features/security/hooks/use-two-fa.ts b/web/src/features/security/hooks/use-two-fa.ts index 2dbd3452b8..aa719db6f8 100644 --- a/web/src/features/security/hooks/use-two-fa.ts +++ b/web/src/features/security/hooks/use-two-fa.ts @@ -19,7 +19,9 @@ For commercial licensing, please contact support@quantumnous.com import { useState, useEffect, useCallback } from 'react' import type { TwoFAStatus } from '@/features/profile/types' -import { get2FAStatus } from '@/lib/api' +import { AuthOperationError } from '@/lib/secure-verification' + +import { get2FAStatus } from '../api' // ============================================================================ // Two-FA Hook @@ -34,19 +36,17 @@ const DEFAULT_STATUS: TwoFAStatus = { export function useTwoFA(enabled = true) { const [loading, setLoading] = useState(true) const [status, setStatus] = useState(DEFAULT_STATUS) + const [error, setError] = useState() const fetchStatus = useCallback(async () => { if (!enabled) return try { setLoading(true) - const response = await get2FAStatus() - if (response.success && response.data) { - setStatus(response.data) - } + setError(undefined) + setStatus(await get2FAStatus()) } catch (error) { - // eslint-disable-next-line no-console - console.error('Failed to fetch 2FA status:', error) + setError(AuthOperationError.from(error).message) } finally { setLoading(false) } @@ -59,6 +59,7 @@ export function useTwoFA(enabled = true) { return { status, loading, + error, refetch: fetchStatus, } } diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index fbed19452c..52ed52cc42 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -128,6 +128,7 @@ "80,443,8080": "80,443,8080", "A billing multiplier. Lower ratios mean lower API call costs.": "A billing multiplier. Lower ratios mean lower API call costs.", "A focused home for keys, balance, routing, and service health.": "A focused home for keys, balance, routing, and service health.", + "A security operation is already in progress.": "A security operation is already in progress.", "About": "About", "About {{days}} days left": "About {{days}} days left", "Accept Unpriced Models": "Accept Unpriced Models", @@ -243,6 +244,7 @@ "Add user group": "Add user group", "Add your API keys, set up channels and configure access permissions": "Add your API keys, set up channels and configure access permissions", "Added {{count}} model(s)": "Added {{count}} model(s)", + "Added {{count}} models from \"{{name}}\"": "Added {{count}} models from \"{{name}}\"", "Added successfully": "Added successfully", "Additional Conditions": "Additional Conditions", "Additional information": "Additional information", @@ -250,6 +252,7 @@ "Additional Limit": "Additional Limit", "Additional Limits": "Additional Limits", "Additional metered capability": "Additional metered capability", + "Additional verification required": "Additional verification required", "Adjust filters, then search to refresh the logs.": "Adjust filters, then search to refresh the logs.", "Adjust Quota": "Adjust Quota", "Adjust response formatting, prompt behavior, proxy, and upstream automation.": "Adjust response formatting, prompt behavior, proxy, and upstream automation.", @@ -536,6 +539,7 @@ "Authentication": "Authentication", "Authentication Method": "Authentication Method", "Authenticator code": "Authenticator code", + "Authenticator code or backup code": "Authenticator code or backup code", "Authorization callback URL": "Authorization callback URL", "Authorization Endpoint": "Authorization Endpoint", "Authorization Endpoint (Optional)": "Authorization Endpoint (Optional)", @@ -814,6 +818,7 @@ "Channel health checks": "Channel health checks", "Channel ID": "Channel ID", "Channel ID is required": "Channel ID is required", + "Channel is not selected": "Channel is not selected", "Channel key": "Channel key", "Channel key unlocked": "Channel key unlocked", "Channel Management": "Channel Management", @@ -1088,10 +1093,12 @@ "confirm that I bear legal responsibility arising from deployment": "confirm that I bear legal responsibility arising from deployment", "Confirm Unbind": "Confirm Unbind", "Confirm usage reset": "Confirm usage reset", + "Confirm your identity before accessing this sensitive action.": "Confirm your identity before accessing this sensitive action.", "Confirm your identity before removing this Passkey from your account.": "Confirm your identity before removing this Passkey from your account.", "Confirm your identity with Two-factor Authentication before registering a Passkey.": "Confirm your identity with Two-factor Authentication before registering a Passkey.", "Confirmed at {{time}} by user #{{userId}}": "Confirmed at {{time}} by user #{{userId}}", "Confirmed payment compliance": "Confirmed payment compliance", + "Confirming the account linked to your profile.": "Confirming the account linked to your profile.", "Conflict": "Conflict", "Connect": "Connect", "Connect through OpenAI, Claude, Gemini, and other compatible API routes": "Connect through OpenAI, Claude, Gemini, and other compatible API routes", @@ -1121,6 +1128,7 @@ "Context": "Context", "Continue": "Continue", "Continue with {{name}}": "Continue with {{name}}", + "Continue with an account already linked to your profile.": "Continue with an account already linked to your profile.", "Continue with Discord": "Continue with Discord", "Continue with GitHub": "Continue with GitHub", "Continue with LinuxDO": "Continue with LinuxDO", @@ -1792,6 +1800,7 @@ "Enter secret key": "Enter secret key", "Enter system prompt (user prompt takes priority)": "Enter system prompt (user prompt takes priority)", "Enter tag name (optional)": "Enter tag name (optional)", + "Enter the 6-digit authenticator code or an unused backup code.": "Enter the 6-digit authenticator code or an unused backup code.", "Enter the 6-digit code from your authenticator app": "Enter the 6-digit code from your authenticator app", "Enter the 6-digit Time-based One-Time Password or 8-character backup code from your authenticator app.": "Enter the 6-digit Time-based One-Time Password or 8-character backup code from your authenticator app.", "Enter the complete URL, supports": "Enter the complete URL, supports", @@ -2510,6 +2519,7 @@ "Invalid chat link. Please contact the administrator.": "Invalid chat link. Please contact the administrator.", "Invalid chat link. Please contact your administrator.": "Invalid chat link. Please contact your administrator.", "Invalid code": "Invalid code", + "Invalid items format": "Invalid items format", "Invalid JSON": "Invalid JSON", "Invalid JSON format": "Invalid JSON format", "Invalid JSON format or values out of allowed range": "Invalid JSON format or values out of allowed range", @@ -2666,6 +2676,7 @@ "Limits token selection to a probability mass": "Limits token selection to a probability mass", "LingYiWanWu": "LingYiWanWu", "Link to your documentation site": "Link to your documentation site", + "Linked account": "Linked account", "LinuxDO": "LinuxDO", "LinuxDO Client ID": "LinuxDO Client ID", "LinuxDO Client Secret": "LinuxDO Client Secret", @@ -2690,6 +2701,7 @@ "Loading maintenance settings...": "Loading maintenance settings...", "Loading settings...": "Loading settings...", "Loading setup status…": "Loading setup status…", + "Loading verification methods...": "Loading verification methods...", "Loading...": "Loading...", "Local": "Local", "Local Billing": "Local Billing", @@ -3115,6 +3127,7 @@ "No Inviter": "No Inviter", "No keys found": "No keys found", "No latency data available": "No latency data available", + "No linked OAuth provider is available.": "No linked OAuth provider is available.", "No log entries matched the selected time.": "No log entries matched the selected time.", "No logs": "No logs", "No Logs Found": "No Logs Found", @@ -3154,6 +3167,7 @@ "No notable climbers right now": "No notable climbers right now", "No notable drops right now": "No notable drops right now", "No parameter overrides configured.": "No parameter overrides configured.", + "No Passkey is registered.": "No Passkey is registered.", "No payment methods available. Please contact administrator.": "No payment methods available. Please contact administrator.", "No payment methods configured": "No payment methods configured", "No payment methods configured. Click \"Add method\" or use templates to get started.": "No payment methods configured. Click \"Add method\" or use templates to get started.", @@ -3214,6 +3228,7 @@ "No Users Found": "No Users Found", "No valid custom Auto groups remain. Add a group or restore global Auto.": "No valid custom Auto groups remain. Add a group or restore global Auto.", "No vendor data available": "No vendor data available", + "No verification method is available for this action.": "No verification method is available for this action.", "No X Found": "No X Found", "Node": "Node", "Node filters": "Node filters", @@ -3262,6 +3277,8 @@ "Number of top log probabilities returned per token": "Number of top log probabilities returned per token", "Number of users invited": "Number of users invited", "OAuth": "OAuth", + "OAuth authorization timed out. Please try again.": "OAuth authorization timed out. Please try again.", + "OAuth authorization was cancelled.": "OAuth authorization was cancelled.", "OAuth binding timed out. Please try again.": "OAuth binding timed out. Please try again.", "OAuth binding window is no longer available": "OAuth binding window is no longer available", "OAuth callback URL": "OAuth callback URL", @@ -3270,6 +3287,8 @@ "OAuth failed": "OAuth failed", "OAuth Integrations": "OAuth Integrations", "OAuth pop-up was blocked": "OAuth pop-up was blocked", + "OAuth popup storage is unavailable.": "OAuth popup storage is unavailable.", + "OAuth window is no longer available.": "OAuth window is no longer available.", "Object Prune Rules": "Object Prune Rules", "Observability": "Observability", "Obtain the API key, merchant ID, and RSA key pair from the Waffo dashboard, and configure the callback URL.": "Obtain the API key, merchant ID, and RSA key pair from the Waffo dashboard, and configure the callback URL.", @@ -3368,6 +3387,7 @@ "operation and charging behavior": "operation and charging behavior", "Operation audit": "Operation audit", "Operation Audit Info": "Operation Audit Info", + "Operation cancelled": "Operation cancelled", "Operation failed": "Operation failed", "Operation successful": "Operation successful", "Operation Type": "Operation Type", @@ -3474,6 +3494,7 @@ "Passive recovery only": "Passive recovery only", "Passkey": "Passkey", "Passkey Authentication": "Passkey Authentication", + "Passkey authentication is disabled.": "Passkey authentication is disabled.", "Passkey is not available in this browser": "Passkey is not available in this browser", "Passkey is not supported in this environment": "Passkey is not supported in this environment", "Passkey is not supported on this device": "Passkey is not supported on this device", @@ -4142,6 +4163,7 @@ "Return Error": "Return Error", "Return per-token log probabilities": "Return per-token log probabilities", "Return to dashboard": "Return to dashboard", + "Return to the original window to continue.": "Return to the original window to continue.", "Return vector embeddings for inputs": "Return vector embeddings for inputs", "Reveal API key": "Reveal API key", "Reveal key": "Reveal key", @@ -4309,6 +4331,8 @@ "Security & Limits": "Security & Limits", "Security Check": "Security Check", "Security verification": "Security verification", + "Security verification has expired. Please verify again.": "Security verification has expired. Please verify again.", + "Security verification is no longer valid. Please verify again.": "Security verification is no longer valid. Please verify again.", "Seed": "Seed", "Select": "Select", "Select a color": "Select a color", @@ -4452,6 +4476,7 @@ "Settings": "Settings", "Settings & Preferences": "Settings & Preferences", "Settings updated successfully": "Settings updated successfully", + "Setup expired. Scan the new QR code and save the new backup codes.": "Setup expired. Scan the new QR code and save the new backup codes.", "Setup guide": "Setup guide", "Setup guide complete": "Setup guide complete", "Setup guide is collapsed. Expand it anytime.": "Setup guide is collapsed. Expand it anytime.", @@ -4783,6 +4808,7 @@ "Text or array of texts to embed": "Text or array of texts to embed", "Text Output": "Text Output", "Text to Video": "Text to Video", + "The action details are invalid.": "The action details are invalid.", "The admin configured three groups and one special ratio rule:": "The admin configured three groups and one special ratio rule:", "The admin wants vip users to pay even less when they use premium. That needs an override rule: in the override matrix, set the cell at row vip, column premium to 0.3.": "The admin wants vip users to pay even less when they use premium. That needs an override rule: in the override matrix, set the cell at row vip, column premium to 0.3.", "The administrator account is already initialized. You can keep your existing credentials and continue to the next step.": "The administrator account is already initialized. You can keep your existing credentials and continue to the next step.", @@ -4791,6 +4817,7 @@ "The administrator has not configured a user agreement yet.": "The administrator has not configured a user agreement yet.", "The administrator has not configured any about content yet. You can set it in the settings page, supporting HTML or URL.": "The administrator has not configured any about content yet. You can set it in the settings page, supporting HTML or URL.", "The API key used for the requests": "The API key used for the requests", + "The authenticator code is incorrect.": "The authenticator code is incorrect.", "The binding will complete automatically after authorization": "The binding will complete automatically after authorization", "The bound Product powers wallet top-ups: when a user enters any amount, new-api runs the checkout against this single Pancake product and overrides the price per session — no need to pre-create $1 / $5 / $10 SKUs.": "The bound Product powers wallet top-ups: when a user enters any amount, new-api runs the checkout against this single Pancake product and overrides the price per session — no need to pre-create $1 / $5 / $10 SKUs.", "The bound Store is the parent container for every Pancake product new-api creates from this admin — both the wallet top-up product and any subscription-plan products. One store is enough; pin a different one only if you genuinely run separate Pancake catalogs.": "The bound Store is the parent container for every Pancake product new-api creates from this admin — both the wallet top-up product and any subscription-plan products. One store is enough; pin a different one only if you genuinely run separate Pancake catalogs.", @@ -4810,6 +4837,7 @@ "The model you're looking for doesn't exist.": "The model you're looking for doesn't exist.", "The name displayed across the application": "The name displayed across the application", "The new token will only be shown once. Copy it and store it securely.": "The new token will only be shown once. Copy it and store it securely.", + "The OAuth account does not match the account linked to your profile.": "The OAuth account does not match the account linked to your profile.", "The public URL of your server, used for OAuth callbacks, webhooks, and other external integrations": "The public URL of your server, used for OAuth callbacks, webhooks, and other external integrations", "The requested chat preset does not exist or has been removed.": "The requested chat preset does not exist or has been removed.", "The reset request stays disabled until a credit is available.": "The reset request stays disabled until a credit is available.", @@ -4821,6 +4849,7 @@ "The token group that will have a custom ratio": "The token group that will have a custom ratio", "The token has no group, so it is billed as the user group vip, using the base ratio of vip.": "The token has no group, so it is billed as the user group vip, using the base ratio of vip.", "The two roles of a group": "The two roles of a group", + "The two-factor setup has expired or changed. Start setup again.": "The two-factor setup has expired or changed. Start setup again.", "The unique identifier for this model": "The unique identifier for this model", "The unique name for this vendor": "The unique name for this vendor", "The upstream channel that served the requests": "The upstream channel that served the requests", @@ -4904,6 +4933,10 @@ "This user account no longer exists.": "This user account no longer exists.", "this user group": "this user group", "This user has no bindings": "This user has no bindings", + "This verification has already been used. Please verify again.": "This verification has already been used. Please verify again.", + "This verification method is currently unavailable.": "This verification method is currently unavailable.", + "This verification method is not allowed for this action.": "This verification method is not allowed for this action.", + "This verification method requires its dedicated verification flow.": "This verification method requires its dedicated verification flow.", "This week": "This week", "This will append 2 template rules (Codex CLI and Claude CLI) to the existing rule list.": "This will append 2 template rules (Codex CLI and Claude CLI) to the existing rule list.", "This will clear custom pricing ratios and revert to upstream defaults.": "This will clear custom pricing ratios and revert to upstream defaults.", @@ -5107,6 +5140,9 @@ "Two-Factor Authentication": "Two-Factor Authentication", "Two-factor authentication disabled": "Two-factor authentication disabled", "Two-factor authentication enabled successfully!": "Two-factor authentication enabled successfully!", + "Two-factor authentication is already enabled.": "Two-factor authentication is already enabled.", + "Two-factor authentication is not enabled.": "Two-factor authentication is not enabled.", + "Two-factor authentication is temporarily locked.": "Two-factor authentication is temporarily locked.", "Two-factor authentication reset": "Two-factor authentication reset", "Two-Step Verification": "Two-Step Verification", "Type": "Type", @@ -5125,6 +5161,7 @@ "Unable to load rankings": "Unable to load rankings", "Unable to load rankings data": "Unable to load rankings data", "Unable to open chat": "Unable to open chat", + "Unable to parse Passkey login options from response": "Unable to parse Passkey login options from response", "Unable to parse structured pricing": "Unable to parse structured pricing", "Unable to prepare chat link. Please ensure you have an enabled API key.": "Unable to prepare chat link. Please ensure you have an enabled API key.", "Unable to read clipboard": "Unable to read clipboard", @@ -5387,20 +5424,25 @@ "Verification code must be 6 digits": "Verification code must be 6 digits", "Verification code sent! Please check your email.": "Verification code sent! Please check your email.", "Verification code updates every 30 seconds.": "Verification code updates every 30 seconds.", + "Verification does not match this action.": "Verification does not match this action.", + "Verification does not match this action's details. Please verify again.": "Verification does not match this action's details. Please verify again.", "Verification email sent": "Verification email sent", "Verification failed": "Verification failed", + "Verification failed. Please try again.": "Verification failed. Please try again.", "Verification flow expired": "Verification flow expired", "Verification is not configured properly": "Verification is not configured properly", "Verification proof was not returned": "Verification proof was not returned", "Verification required to reveal the saved key.": "Verification required to reveal the saved key.", "Verification scope is missing": "Verification scope is missing", "Verify": "Verify", + "Verify again before retrying this action.": "Verify again before retrying this action.", "Verify and Sign In": "Verify and Sign In", "Verify routing with Playground or your client": "Verify routing with Playground or your client", "Verify Setup": "Verify Setup", "Verify to view channel key": "Verify to view channel key", "Verify your database connection": "Verify your database connection", "Verifying credentials and pulling stores from your Pancake account...": "Verifying credentials and pulling stores from your Pancake account...", + "Verifying your {{provider}} account": "Verifying your {{provider}} account", "Version": "Version", "Version history": "Version history", "Version Overrides": "Version Overrides", @@ -5572,6 +5614,7 @@ "You commit not to use this system to implement, assist with, or indirectly implement acts that violate applicable laws and regulations, regulatory requirements, platform rules, public interests, or the lawful rights and interests of third parties.": "You commit not to use this system to implement, assist with, or indirectly implement acts that violate applicable laws and regulations, regulatory requirements, platform rules, public interests, or the lawful rights and interests of third parties.", "You commit to using upstream APIs, accounts, keys, quotas, and service capabilities only within the scope of lawful authorization obtained from upstream service providers, model service providers, or relevant rights holders, and will not conduct unauthorized resale, trafficking, distribution, or other non-compliant commercialization.": "You commit to using upstream APIs, accounts, keys, quotas, and service capabilities only within the scope of lawful authorization obtained from upstream service providers, model service providers, or relevant rights holders, and will not conduct unauthorized resale, trafficking, distribution, or other non-compliant commercialization.", "You do not have permission to edit sensitive channel settings.": "You do not have permission to edit sensitive channel settings.", + "You do not have permission to perform this action.": "You do not have permission to perform this action.", "You don't have necessary permission": "You don't have necessary permission", "You have legally obtained authorization for the connected model APIs, accounts, keys, and quotas.": "You have legally obtained authorization for the connected model APIs, accounts, keys, and quotas.", "You have unsaved changes": "You have unsaved changes", diff --git a/web/src/i18n/locales/fr.json b/web/src/i18n/locales/fr.json index e7feb3c890..cb1dcbe784 100644 --- a/web/src/i18n/locales/fr.json +++ b/web/src/i18n/locales/fr.json @@ -128,6 +128,7 @@ "80,443,8080": "80,443,8080", "A billing multiplier. Lower ratios mean lower API call costs.": "Un multiplicateur de facturation. Plus le ratio est faible, plus le coût des appels API est bas.", "A focused home for keys, balance, routing, and service health.": "Un accueil dédié aux clés, au solde, au routage et à l'état du service.", + "A security operation is already in progress.": "Une opération de sécurité est déjà en cours.", "About": "À propos", "About {{days}} days left": "Environ {{days}} jours restants", "Accept Unpriced Models": "Accepter les modèles non tarifés", @@ -243,6 +244,7 @@ "Add user group": "Ajouter un groupe d'utilisateurs", "Add your API keys, set up channels and configure access permissions": "Ajoutez vos clés API, configurez les canaux et les permissions d'accès", "Added {{count}} model(s)": "{{count}} modèle(s) ajouté(s)", + "Added {{count}} models from \"{{name}}\"": "{{count}} modèles ajoutés depuis « {{name}} »", "Added successfully": "Ajouté avec succès", "Additional Conditions": "Conditions supplémentaires", "Additional information": "Informations supplémentaires", @@ -250,6 +252,7 @@ "Additional Limit": "Limite supplémentaire", "Additional Limits": "Limites supplémentaires", "Additional metered capability": "Fonctionnalité supplémentaire facturée à l’usage", + "Additional verification required": "Vérification supplémentaire requise", "Adjust filters, then search to refresh the logs.": "Ajustez les filtres, puis lancez la recherche pour actualiser les journaux.", "Adjust Quota": "Ajuster le quota", "Adjust response formatting, prompt behavior, proxy, and upstream automation.": "Ajustez le formatage des réponses, le comportement des prompts, le proxy et l’automatisation amont.", @@ -536,6 +539,7 @@ "Authentication": "Authentification", "Authentication Method": "Méthode d'authentification", "Authenticator code": "Code d'authentification", + "Authenticator code or backup code": "Code d’authentification ou de secours", "Authorization callback URL": "URL de rappel d'autorisation", "Authorization Endpoint": "Point de terminaison d'autorisation", "Authorization Endpoint (Optional)": "Point de terminaison d'autorisation (Facultatif)", @@ -814,6 +818,7 @@ "Channel health checks": "Contrôles de santé des canaux", "Channel ID": "ID du Canal", "Channel ID is required": "L'ID du canal est requis", + "Channel is not selected": "Aucun canal sélectionné", "Channel key": "Clé du canal", "Channel key unlocked": "Clé de canal déverrouillée", "Channel Management": "Gestion des canaux", @@ -1088,10 +1093,12 @@ "confirm that I bear legal responsibility arising from deployment": "confirme assumer la responsabilité juridique découlant du déploiement", "Confirm Unbind": "Confirmer la dissociation", "Confirm usage reset": "Confirmer la réinitialisation de l’utilisation", + "Confirm your identity before accessing this sensitive action.": "Confirmez votre identité avant cette opération sensible.", "Confirm your identity before removing this Passkey from your account.": "Confirmez votre identité avant de supprimer cette Passkey de votre compte.", "Confirm your identity with Two-factor Authentication before registering a Passkey.": "Confirmez votre identité avec l’authentification à deux facteurs avant d’enregistrer une Passkey.", "Confirmed at {{time}} by user #{{userId}}": "Confirmé le {{time}} par l’utilisateur #{{userId}}", "Confirmed payment compliance": "Conformité de paiement confirmée", + "Confirming the account linked to your profile.": "Vérification du compte associé à votre profil.", "Conflict": "Conflit", "Connect": "Connecter", "Connect through OpenAI, Claude, Gemini, and other compatible API routes": "Connectez-vous via OpenAI, Claude, Gemini et d'autres routes API compatibles", @@ -1121,6 +1128,7 @@ "Context": "Contexte", "Continue": "Continuer", "Continue with {{name}}": "Continuer avec {{name}}", + "Continue with an account already linked to your profile.": "Continuez avec un compte déjà associé à votre profil.", "Continue with Discord": "Continuer avec Discord", "Continue with GitHub": "Continuer avec GitHub", "Continue with LinuxDO": "Continuer avec LinuxDO", @@ -1792,6 +1800,7 @@ "Enter secret key": "Saisir la clé secrète", "Enter system prompt (user prompt takes priority)": "Saisir l'invite système (l'invite utilisateur est prioritaire)", "Enter tag name (optional)": "Saisir le nom du tag (facultatif)", + "Enter the 6-digit authenticator code or an unused backup code.": "Saisissez le code à 6 chiffres ou un code de secours inutilisé.", "Enter the 6-digit code from your authenticator app": "Saisir le code à 6 chiffres de votre application d'authentification", "Enter the 6-digit Time-based One-Time Password or 8-character backup code from your authenticator app.": "Saisir le mot de passe à usage unique basé sur le temps à 6 chiffres ou le code de secours à 8 caractères de votre application d'authentification.", "Enter the complete URL, supports": "Saisir l'URL complète, prend en charge", @@ -2510,6 +2519,7 @@ "Invalid chat link. Please contact the administrator.": "Lien de chat invalide. Veuillez contacter l'administrateur.", "Invalid chat link. Please contact your administrator.": "Lien de chat invalide. Veuillez contacter votre administrateur.", "Invalid code": "Code invalide", + "Invalid items format": "Format des éléments invalide", "Invalid JSON": "JSON invalide", "Invalid JSON format": "Format JSON invalide", "Invalid JSON format or values out of allowed range": "Format JSON invalide ou valeurs hors plage autorisée", @@ -2666,6 +2676,7 @@ "Limits token selection to a probability mass": "Limite la sélection des tokens par masse de probabilité", "LingYiWanWu": "LingYiWanWu", "Link to your documentation site": "Lien vers votre site de documentation", + "Linked account": "Compte associé", "LinuxDO": "LinuxDO", "LinuxDO Client ID": "ID client LinuxDO", "LinuxDO Client Secret": "Secret client LinuxDO", @@ -2690,6 +2701,7 @@ "Loading maintenance settings...": "Chargement des paramètres de maintenance...", "Loading settings...": "Chargement des paramètres...", "Loading setup status…": "Chargement du statut de configuration…", + "Loading verification methods...": "Chargement des méthodes de vérification…", "Loading...": "Chargement...", "Local": "Local", "Local Billing": "Facturation locale", @@ -3115,6 +3127,7 @@ "No Inviter": "Pas d'inviteur", "No keys found": "Aucune clé trouvée", "No latency data available": "Aucune donnée de latence disponible", + "No linked OAuth provider is available.": "Aucun fournisseur OAuth associé disponible.", "No log entries matched the selected time.": "Aucune entrée de journal ne correspond à l'heure sélectionnée.", "No logs": "Aucun journal", "No Logs Found": "Aucun journal trouvé", @@ -3154,6 +3167,7 @@ "No notable climbers right now": "Aucune progression notable pour le moment", "No notable drops right now": "Aucune chute notable pour le moment", "No parameter overrides configured.": "Aucune surcharge de paramètres configurée.", + "No Passkey is registered.": "Aucune Passkey n’est enregistrée.", "No payment methods available. Please contact administrator.": "Aucun moyen de paiement disponible. Veuillez contacter l'administrateur.", "No payment methods configured": "Aucun mode de paiement configuré", "No payment methods configured. Click \"Add method\" or use templates to get started.": "Aucune méthode de paiement configurée. Cliquez sur \"Ajouter une méthode\" ou utilisez des modèles pour commencer.", @@ -3214,6 +3228,7 @@ "No Users Found": "Aucun utilisateur trouvé", "No valid custom Auto groups remain. Add a group or restore global Auto.": "Aucun groupe Auto personnalisé valide ne subsiste. Ajoutez un groupe ou restaurez l’Auto global.", "No vendor data available": "Aucune donnée de fournisseur disponible", + "No verification method is available for this action.": "Aucune méthode de vérification disponible pour cette action.", "No X Found": "Aucun X trouvé", "Node": "Nœud", "Node filters": "Filtres de nœuds", @@ -3262,6 +3277,8 @@ "Number of top log probabilities returned per token": "Nombre de log-probabilités retournées par jeton", "Number of users invited": "Nombre d'utilisateurs invités", "OAuth": "OAuth", + "OAuth authorization timed out. Please try again.": "L’autorisation OAuth a expiré. Réessayez.", + "OAuth authorization was cancelled.": "L’autorisation OAuth a été annulée.", "OAuth binding timed out. Please try again.": "La liaison OAuth a expiré. Veuillez réessayer.", "OAuth binding window is no longer available": "La fenêtre d’association OAuth n’est plus disponible", "OAuth callback URL": "URL de rappel OAuth", @@ -3270,6 +3287,8 @@ "OAuth failed": "Échec de l'OAuth", "OAuth Integrations": "Intégrations OAuth", "OAuth pop-up was blocked": "La fenêtre contextuelle OAuth a été bloquée", + "OAuth popup storage is unavailable.": "Le stockage de la fenêtre OAuth est indisponible.", + "OAuth window is no longer available.": "La fenêtre OAuth n’est plus disponible.", "Object Prune Rules": "Règles de nettoyage d'objets", "Observability": "Observabilité", "Obtain the API key, merchant ID, and RSA key pair from the Waffo dashboard, and configure the callback URL.": "Obtenez la clé API, l'ID du commerçant et la paire de clés RSA depuis le tableau de bord Waffo, et configurez l'URL de rappel.", @@ -3368,6 +3387,7 @@ "operation and charging behavior": "à l’exploitation et à la facturation", "Operation audit": "Audit des opérations", "Operation Audit Info": "Informations d'audit d'opération", + "Operation cancelled": "Opération annulée", "Operation failed": "Opération échouée", "Operation successful": "Opération réussie", "Operation Type": "Type d'opération", @@ -3474,6 +3494,7 @@ "Passive recovery only": "Récupération passive uniquement", "Passkey": "Passkey", "Passkey Authentication": "Authentification Passkey", + "Passkey authentication is disabled.": "L’authentification Passkey est désactivée.", "Passkey is not available in this browser": "Passkey n'est pas disponible dans ce navigateur", "Passkey is not supported in this environment": "Passkey n'est pas pris en charge dans cet environnement", "Passkey is not supported on this device": "Passkey n'est pas pris en charge sur cet appareil", @@ -4142,6 +4163,7 @@ "Return Error": "Retourner l'erreur", "Return per-token log probabilities": "Retourner les log-probabilités par jeton", "Return to dashboard": "Retour au tableau de bord", + "Return to the original window to continue.": "Revenez à la fenêtre d’origine pour continuer.", "Return vector embeddings for inputs": "Renvoyer des embeddings vectoriels pour les entrées", "Reveal API key": "Afficher la clé API", "Reveal key": "Révéler la clé", @@ -4309,6 +4331,8 @@ "Security & Limits": "Sécurité et limites", "Security Check": "Vérification de sécurité", "Security verification": "Vérification de sécurité", + "Security verification has expired. Please verify again.": "La vérification de sécurité a expiré. Recommencez.", + "Security verification is no longer valid. Please verify again.": "La vérification de sécurité n’est plus valide. Recommencez.", "Seed": "Graine", "Select": "Sélectionner", "Select a color": "Sélectionner une couleur", @@ -4452,6 +4476,7 @@ "Settings": "Paramètres", "Settings & Preferences": "Paramètres et préférences", "Settings updated successfully": "Paramètres mis à jour avec succès", + "Setup expired. Scan the new QR code and save the new backup codes.": "La configuration a expiré. Scannez le nouveau code QR et conservez les nouveaux codes de secours.", "Setup guide": "Guide de configuration", "Setup guide complete": "Guide de configuration terminé", "Setup guide is collapsed. Expand it anytime.": "Le guide de configuration est réduit. Vous pouvez le rouvrir à tout moment.", @@ -4783,6 +4808,7 @@ "Text or array of texts to embed": "Texte ou tableau de textes à vectoriser", "Text Output": "Sortie texte", "Text to Video": "Texte vers vidéo", + "The action details are invalid.": "Les détails de l’action sont invalides.", "The admin configured three groups and one special ratio rule:": "L’administrateur a configuré trois groupes et une règle de taux spécial :", "The admin wants vip users to pay even less when they use premium. That needs an override rule: in the override matrix, set the cell at row vip, column premium to 0.3.": "L’administrateur veut que les utilisateurs vip paient encore moins lorsqu’ils utilisent premium. Il faut une règle de remplacement : dans la matrice, définissez la cellule ligne vip, colonne premium à 0,3.", "The administrator account is already initialized. You can keep your existing credentials and continue to the next step.": "Le compte administrateur est déjà initialisé. Vous pouvez conserver vos identifiants existants et passer à l'étape suivante.", @@ -4791,6 +4817,7 @@ "The administrator has not configured a user agreement yet.": "L'administrateur n'a pas encore configuré d'accord utilisateur.", "The administrator has not configured any about content yet. You can set it in the settings page, supporting HTML or URL.": "L'administrateur n'a pas encore configuré de contenu 'À propos'. Vous pouvez le définir dans la page des paramètres, en supportant le HTML ou l'URL.", "The API key used for the requests": "La clé API utilisée pour les requêtes", + "The authenticator code is incorrect.": "Le code d’authentification est incorrect.", "The binding will complete automatically after authorization": "La liaison se terminera automatiquement après l'autorisation", "The bound Product powers wallet top-ups: when a user enters any amount, new-api runs the checkout against this single Pancake product and overrides the price per session — no need to pre-create $1 / $5 / $10 SKUs.": "Le produit associé alimente les recharges de portefeuille : lorsqu’un utilisateur saisit un montant, new-api lance le paiement sur ce produit Pancake unique et remplace le prix pour la session, sans devoir précréer des SKU de 1 $, 5 $ ou 10 $.", "The bound Store is the parent container for every Pancake product new-api creates from this admin — both the wallet top-up product and any subscription-plan products. One store is enough; pin a different one only if you genuinely run separate Pancake catalogs.": "La boutique associée est le conteneur parent de tous les produits Pancake que new-api crée depuis cette administration, y compris le produit de recharge de portefeuille et les produits de forfaits d’abonnement. Une seule boutique suffit ; choisissez-en une autre uniquement si vous gérez réellement des catalogues Pancake séparés.", @@ -4810,6 +4837,7 @@ "The model you're looking for doesn't exist.": "Le modèle que vous recherchez n'existe pas.", "The name displayed across the application": "Le nom affiché dans l'application", "The new token will only be shown once. Copy it and store it securely.": "Le nouveau jeton ne sera affiché qu’une seule fois. Copiez-le et conservez-le en lieu sûr.", + "The OAuth account does not match the account linked to your profile.": "Ce compte OAuth ne correspond pas au compte associé à votre profil.", "The public URL of your server, used for OAuth callbacks, webhooks, and other external integrations": "L'URL publique de votre serveur, utilisée pour les rappels OAuth, les webhooks et autres intégrations externes", "The requested chat preset does not exist or has been removed.": "Le préréglage de discussion demandé n'existe pas ou a été supprimé.", "The reset request stays disabled until a credit is available.": "La demande de réinitialisation reste désactivée tant qu’aucun crédit n’est disponible.", @@ -4821,6 +4849,7 @@ "The token group that will have a custom ratio": "Le groupe de jetons qui aura un ratio personnalisé", "The token has no group, so it is billed as the user group vip, using the base ratio of vip.": "Le jeton n’a pas de groupe, il est donc facturé sous le groupe d’utilisateurs vip, avec le taux de base de vip.", "The two roles of a group": "Les deux rôles d’un groupe", + "The two-factor setup has expired or changed. Start setup again.": "La configuration à deux facteurs a expiré ou changé. Recommencez.", "The unique identifier for this model": "L'identifiant unique de ce modèle", "The unique name for this vendor": "Le nom unique de ce fournisseur", "The upstream channel that served the requests": "Le canal en amont ayant servi les requêtes", @@ -4904,6 +4933,10 @@ "This user account no longer exists.": "Ce compte utilisateur n’existe plus.", "this user group": "ce groupe d'utilisateurs", "This user has no bindings": "Cet utilisateur n'a aucune liaison", + "This verification has already been used. Please verify again.": "Cette vérification a déjà été utilisée. Veuillez vous authentifier à nouveau.", + "This verification method is currently unavailable.": "Cette méthode de vérification est actuellement indisponible.", + "This verification method is not allowed for this action.": "Cette méthode de vérification n’est pas autorisée pour cette action.", + "This verification method requires its dedicated verification flow.": "Cette méthode nécessite son propre parcours de vérification.", "This week": "Cette semaine", "This will append 2 template rules (Codex CLI and Claude CLI) to the existing rule list.": "Cela ajoutera 2 règles modèles (Codex CLI et Claude CLI) à la liste de règles existante.", "This will clear custom pricing ratios and revert to upstream defaults.": "Cela effacera les ratios de tarification personnalisés et rétablira les valeurs par défaut du fournisseur.", @@ -5107,6 +5140,9 @@ "Two-Factor Authentication": "Authentification à deux facteurs", "Two-factor authentication disabled": "Authentification à deux facteurs désactivée", "Two-factor authentication enabled successfully!": "Authentification à deux facteurs activée avec succès!", + "Two-factor authentication is already enabled.": "L’authentification à deux facteurs est déjà activée.", + "Two-factor authentication is not enabled.": "L’authentification à deux facteurs n’est pas activée.", + "Two-factor authentication is temporarily locked.": "L’authentification à deux facteurs est temporairement verrouillée.", "Two-factor authentication reset": "Authentification à deux facteurs réinitialisée", "Two-Step Verification": "Validation en deux étapes", "Type": "Type", @@ -5125,6 +5161,7 @@ "Unable to load rankings": "Impossible de charger les classements", "Unable to load rankings data": "Impossible de charger les données des classements", "Unable to open chat": "Impossible d'ouvrir la discussion", + "Unable to parse Passkey login options from response": "Impossible de lire les options de connexion Passkey dans la réponse", "Unable to parse structured pricing": "Impossible d'analyser la tarification structurée", "Unable to prepare chat link. Please ensure you have an enabled API key.": "Impossible de préparer le lien de chat. Veuillez vous assurer d'avoir une clé API activée.", "Unable to read clipboard": "Impossible de lire le presse-papiers", @@ -5387,20 +5424,25 @@ "Verification code must be 6 digits": "Le code de vérification doit comporter 6 chiffres", "Verification code sent! Please check your email.": "Code de vérification envoyé ! Veuillez vérifier votre email.", "Verification code updates every 30 seconds.": "Le code de vérification se met à jour toutes les 30 secondes.", + "Verification does not match this action.": "La vérification ne correspond pas à cette action.", + "Verification does not match this action's details. Please verify again.": "La vérification ne correspond pas aux détails de cette action. Veuillez vous authentifier à nouveau.", "Verification email sent": "Email de vérification envoyé", "Verification failed": "Échec de la vérification", + "Verification failed. Please try again.": "La vérification a échoué. Réessayez.", "Verification flow expired": "Le processus de vérification a expiré", "Verification is not configured properly": "La vérification n'est pas configurée correctement", "Verification proof was not returned": "La preuve de vérification n’a pas été renvoyée", "Verification required to reveal the saved key.": "Vérification requise pour révéler la clé enregistrée.", "Verification scope is missing": "La portée de vérification est manquante", "Verify": "Vérifier", + "Verify again before retrying this action.": "Veuillez vous authentifier à nouveau avant de réessayer cette action.", "Verify and Sign In": "Vérifier et se connecter", "Verify routing with Playground or your client": "Vérifiez le routage avec Playground ou votre client", "Verify Setup": "Vérifier la configuration", "Verify to view channel key": "Vérifier pour afficher la clé du canal", "Verify your database connection": "Vérifiez votre connexion à la base de données", "Verifying credentials and pulling stores from your Pancake account...": "Vérification des identifiants et récupération des boutiques depuis votre compte Pancake...", + "Verifying your {{provider}} account": "Vérification de votre compte {{provider}}", "Version": "Version", "Version history": "Historique des versions", "Version Overrides": "Remplacements de version", @@ -5572,6 +5614,7 @@ "You commit not to use this system to implement, assist with, or indirectly implement acts that violate applicable laws and regulations, regulatory requirements, platform rules, public interests, or the lawful rights and interests of third parties.": "Vous vous engagez à ne pas utiliser ce système pour mettre en œuvre, faciliter ou indirectement réaliser des actes violant les lois et règlements applicables, les exigences réglementaires, les règles des plateformes, l’intérêt public ou les droits et intérêts légitimes de tiers.", "You commit to using upstream APIs, accounts, keys, quotas, and service capabilities only within the scope of lawful authorization obtained from upstream service providers, model service providers, or relevant rights holders, and will not conduct unauthorized resale, trafficking, distribution, or other non-compliant commercialization.": "Vous vous engagez à utiliser les API, comptes, clés, quotas et capacités de service en amont uniquement dans le cadre d’une autorisation légale obtenue auprès des fournisseurs de services en amont, fournisseurs de modèles ou ayants droit concernés, et à ne pas effectuer de revente, trafic, distribution ou autre commercialisation non conforme sans autorisation.", "You do not have permission to edit sensitive channel settings.": "Vous n’avez pas l’autorisation de modifier les paramètres sensibles des canaux.", + "You do not have permission to perform this action.": "Vous n’avez pas l’autorisation d’effectuer cette action.", "You don't have necessary permission": "Vous n'avez pas la permission nécessaire", "You have legally obtained authorization for the connected model APIs, accounts, keys, and quotas.": "Vous avez légalement obtenu l’autorisation pour les API de modèles, comptes, clés et quotas connectés.", "You have unsaved changes": "Vous avez des modifications non enregistrées", diff --git a/web/src/i18n/locales/ja.json b/web/src/i18n/locales/ja.json index 20e7c7a408..c9d864732d 100644 --- a/web/src/i18n/locales/ja.json +++ b/web/src/i18n/locales/ja.json @@ -128,6 +128,7 @@ "80,443,8080": "80,443,8080", "A billing multiplier. Lower ratios mean lower API call costs.": "課金倍率です。倍率が低いほど API 呼び出しコストは低くなります。", "A focused home for keys, balance, routing, and service health.": "キー、残高、ルーティング、サービス状態を集約したホームです。", + "A security operation is already in progress.": "セキュリティ操作を実行中です。", "About": "このサービスについて", "About {{days}} days left": "約 {{days}} 日分", "Accept Unpriced Models": "価格設定されていないモデルを許可", @@ -243,6 +244,7 @@ "Add user group": "ユーザーグループを追加", "Add your API keys, set up channels and configure access permissions": "APIキーを追加し、チャネルを設定してアクセス権限を構成します", "Added {{count}} model(s)": "{{count}} 個のモデルを追加しました", + "Added {{count}} models from \"{{name}}\"": "「{{name}}」から {{count}} 個のモデルを追加しました", "Added successfully": "追加に成功しました", "Additional Conditions": "追加条件", "Additional information": "追加情報", @@ -250,6 +252,7 @@ "Additional Limit": "追加上限", "Additional Limits": "追加上限", "Additional metered capability": "追加の従量制機能", + "Additional verification required": "追加の確認が必要です", "Adjust filters, then search to refresh the logs.": "フィルターを調整してから検索し、ログを更新します。", "Adjust Quota": "クォータを調整", "Adjust response formatting, prompt behavior, proxy, and upstream automation.": "レスポンス形式、プロンプト動作、プロキシ、上流自動化を調整します。", @@ -536,6 +539,7 @@ "Authentication": "認証", "Authentication Method": "認証方式", "Authenticator code": "認証コード", + "Authenticator code or backup code": "認証アプリのコードまたはバックアップコード", "Authorization callback URL": "認可コールバック URL", "Authorization Endpoint": "認可エンドポイント", "Authorization Endpoint (Optional)": "認証エンドポイント (オプション)", @@ -814,6 +818,7 @@ "Channel health checks": "チャネルヘルスチェック", "Channel ID": "チャネルID", "Channel ID is required": "チャネル ID が必要です", + "Channel is not selected": "チャネルが選択されていません", "Channel key": "チャネルキー", "Channel key unlocked": "チャネルキーが解除されました", "Channel Management": "チャネル管理", @@ -1088,10 +1093,12 @@ "confirm that I bear legal responsibility arising from deployment": "デプロイ", "Confirm Unbind": "連携解除を確認", "Confirm usage reset": "使用量リセットの確認", + "Confirm your identity before accessing this sensitive action.": "この重要な操作を行う前に本人確認をしてください。", "Confirm your identity before removing this Passkey from your account.": "このパスキーをアカウントから削除する前に、本人確認を行ってください。", "Confirm your identity with Two-factor Authentication before registering a Passkey.": "パスキーを登録する前に、二要素認証で本人確認を行ってください。", "Confirmed at {{time}} by user #{{userId}}": "ユーザー #{{userId}} が {{time}} に確認しました", "Confirmed payment compliance": "支払いコンプライアンスを確認しました", + "Confirming the account linked to your profile.": "連携済みのアカウントを確認しています。", "Conflict": "競合", "Connect": "接続", "Connect through OpenAI, Claude, Gemini, and other compatible API routes": "OpenAI、Claude、Gemini、その他の互換APIルートから接続", @@ -1121,6 +1128,7 @@ "Context": "コンテキスト", "Continue": "続行", "Continue with {{name}}": "{{name}} で続行", + "Continue with an account already linked to your profile.": "連携済みのアカウントで続行してください。", "Continue with Discord": "Discord で続行", "Continue with GitHub": "GitHub で続行", "Continue with LinuxDO": "LinuxDO で続行", @@ -1792,6 +1800,7 @@ "Enter secret key": "シークレットキーを入力", "Enter system prompt (user prompt takes priority)": "システムプロンプトを入力 (ユーザープロンプトが優先されます)", "Enter tag name (optional)": "タグ名を入力 (オプション)", + "Enter the 6-digit authenticator code or an unused backup code.": "認証アプリの6桁のコードか、未使用のバックアップコードを入力してください。", "Enter the 6-digit code from your authenticator app": "認証アプリからの6桁のコードを入力", "Enter the 6-digit Time-based One-Time Password or 8-character backup code from your authenticator app.": "認証アプリからの6桁のワンタイムパスワードまたは8文字のバックアップコードを入力してください。", "Enter the complete URL, supports": "完全なURLを入力、サポート", @@ -2510,6 +2519,7 @@ "Invalid chat link. Please contact the administrator.": "無効なチャットリンクです。管理者に連絡してください。", "Invalid chat link. Please contact your administrator.": "無効なチャットリンクです。管理者に連絡してください。", "Invalid code": "無効なコード", + "Invalid items format": "項目の形式が無効です", "Invalid JSON": "JSON が無効です", "Invalid JSON format": "無効な JSON 形式", "Invalid JSON format or values out of allowed range": "無効な JSON 形式または値が許可された範囲外です", @@ -2666,6 +2676,7 @@ "Limits token selection to a probability mass": "確率質量でトークン選択を制限します", "LingYiWanWu": "LingYiWanWu", "Link to your documentation site": "ドキュメントサイトへのリンク", + "Linked account": "連携済みアカウント", "LinuxDO": "LinuxDO", "LinuxDO Client ID": "LinuxDO クライアントID", "LinuxDO Client Secret": "LinuxDO クライアントシークレット", @@ -2690,6 +2701,7 @@ "Loading maintenance settings...": "メンテナンス設定をロード中...", "Loading settings...": "設定をロード中...", "Loading setup status…": "セットアップステータスをロード中…", + "Loading verification methods...": "確認方法を読み込み中…", "Loading...": "読み込み中...", "Local": "ローカル", "Local Billing": "ローカル課金", @@ -3115,6 +3127,7 @@ "No Inviter": "招待者なし", "No keys found": "キーが見つかりません", "No latency data available": "レイテンシデータがありません", + "No linked OAuth provider is available.": "利用できる連携済みOAuthプロバイダーがありません。", "No log entries matched the selected time.": "選択した時間に一致するログエントリはありません。", "No logs": "ログがありません", "No Logs Found": "ログが見つかりません", @@ -3154,6 +3167,7 @@ "No notable climbers right now": "現在、目立った上昇はありません", "No notable drops right now": "現在、目立った下降はありません", "No parameter overrides configured.": "パラメータのオーバーライドが設定されていません。", + "No Passkey is registered.": "Passkeyが登録されていません。", "No payment methods available. Please contact administrator.": "利用可能な支払い方法がありません。管理者に連絡してください。", "No payment methods configured": "決済方法が設定されていません", "No payment methods configured. Click \"Add method\" or use templates to get started.": "支払い方法が設定されていません。「メソッドを追加」をクリックするか、テンプレートを使用して開始してください。", @@ -3214,6 +3228,7 @@ "No Users Found": "ユーザーが見つかりません", "No valid custom Auto groups remain. Add a group or restore global Auto.": "有効なカスタム Auto グループがありません。グループを追加するか、グローバル Auto に戻してください。", "No vendor data available": "ベンダーデータがありません", + "No verification method is available for this action.": "この操作に利用できる確認方法がありません。", "No X Found": "X が見つかりません", "Node": "ノード", "Node filters": "ノードフィルター", @@ -3262,6 +3277,8 @@ "Number of top log probabilities returned per token": "トークンごとに返される上位対数確率の数", "Number of users invited": "招待されたユーザー数", "OAuth": "OAuth", + "OAuth authorization timed out. Please try again.": "OAuth認可がタイムアウトしました。もう一度お試しください。", + "OAuth authorization was cancelled.": "OAuth認可がキャンセルされました。", "OAuth binding timed out. Please try again.": "OAuth 連携がタイムアウトしました。もう一度お試しください。", "OAuth binding window is no longer available": "OAuth 連携ウィンドウは利用できなくなりました", "OAuth callback URL": "OAuth コールバック URL", @@ -3270,6 +3287,8 @@ "OAuth failed": "OAuth に失敗しました", "OAuth Integrations": "OAuth連携", "OAuth pop-up was blocked": "OAuth ポップアップがブロックされました", + "OAuth popup storage is unavailable.": "OAuthポップアップのストレージを利用できません。", + "OAuth window is no longer available.": "OAuthウィンドウを利用できなくなりました。", "Object Prune Rules": "オブジェクト削除ルール", "Observability": "可観測性", "Obtain the API key, merchant ID, and RSA key pair from the Waffo dashboard, and configure the callback URL.": "Waffoダッシュボードから APIキー、マーチャントID、RSAキーペアを取得し、コールバックURLを設定してください。", @@ -3368,6 +3387,7 @@ "operation and charging behavior": "運用および課金行為に起因する法的責任を負うことを確認します", "Operation audit": "操作監査", "Operation Audit Info": "操作監査情報", + "Operation cancelled": "操作がキャンセルされました", "Operation failed": "操作に失敗しました", "Operation successful": "操作が成功しました", "Operation Type": "操作タイプ", @@ -3474,6 +3494,7 @@ "Passive recovery only": "パッシブ復旧のみ", "Passkey": "Passkey", "Passkey Authentication": "パスキー認証", + "Passkey authentication is disabled.": "Passkey認証は無効になっています。", "Passkey is not available in this browser": "このブラウザではパスキーが利用できません", "Passkey is not supported in this environment": "この環境ではパスキーはサポートされていません", "Passkey is not supported on this device": "このデバイスではパスキーがサポートされていません", @@ -4142,6 +4163,7 @@ "Return Error": "エラーを返す", "Return per-token log probabilities": "トークンごとの対数確率を返します", "Return to dashboard": "ダッシュボードに戻る", + "Return to the original window to continue.": "元のウィンドウに戻って続行してください。", "Return vector embeddings for inputs": "入力に対してベクトル埋め込みを返却", "Reveal API key": "APIキーを表示", "Reveal key": "キーを表示", @@ -4309,6 +4331,8 @@ "Security & Limits": "セキュリティと制限", "Security Check": "セキュリティチェック", "Security verification": "セキュリティ確認", + "Security verification has expired. Please verify again.": "セキュリティ確認の有効期限が切れました。再度確認してください。", + "Security verification is no longer valid. Please verify again.": "セキュリティ確認が無効になりました。再度確認してください。", "Seed": "シード", "Select": "選択", "Select a color": "色を選択", @@ -4452,6 +4476,7 @@ "Settings": "設定", "Settings & Preferences": "設定と環境設定", "Settings updated successfully": "設定が正常に更新されました", + "Setup expired. Scan the new QR code and save the new backup codes.": "設定の有効期限が切れました。新しいQRコードを読み取り、新しいバックアップコードを保存してください。", "Setup guide": "セットアップガイド", "Setup guide complete": "セットアップガイド完了", "Setup guide is collapsed. Expand it anytime.": "セットアップガイドは折りたたまれています。いつでも展開できます。", @@ -4783,6 +4808,7 @@ "Text or array of texts to embed": "ベクトル化するテキストまたは配列", "Text Output": "テキスト出力", "Text to Video": "テキストから動画", + "The action details are invalid.": "操作の詳細が無効です。", "The admin configured three groups and one special ratio rule:": "管理者は3つのグループと1つの特別倍率ルールを設定しました:", "The admin wants vip users to pay even less when they use premium. That needs an override rule: in the override matrix, set the cell at row vip, column premium to 0.3.": "管理者は vip ユーザーが premium を使うときにさらに安くしたいと考えています。それには上書きルールが必要です:上書きマトリクスで「行 vip、列 premium」のセルに 0.3 を設定します。", "The administrator account is already initialized. You can keep your existing credentials and continue to the next step.": "管理者アカウントはすでに初期化されています。既存の認証情報を保持して、次のステップに進むことができます。", @@ -4791,6 +4817,7 @@ "The administrator has not configured a user agreement yet.": "管理者がまだ利用規約を設定していません。", "The administrator has not configured any about content yet. You can set it in the settings page, supporting HTML or URL.": "管理者はまだ「概要」コンテンツを設定していません。設定ページでHTMLまたはURLをサポートして設定できます。", "The API key used for the requests": "リクエストに使用された API キー", + "The authenticator code is incorrect.": "認証アプリのコードが正しくありません。", "The binding will complete automatically after authorization": "認証後、バインディングは自動的に完了します", "The bound Product powers wallet top-ups: when a user enters any amount, new-api runs the checkout against this single Pancake product and overrides the price per session — no need to pre-create $1 / $5 / $10 SKUs.": "紐付け済み商品はウォレットチャージに使用されます。ユーザーが任意の金額を入力すると、new-api はこの単一の Pancake 商品でチェックアウトを実行し、セッションごとに価格を上書きします。$1 / $5 / $10 の SKU を事前作成する必要はありません。", "The bound Store is the parent container for every Pancake product new-api creates from this admin — both the wallet top-up product and any subscription-plan products. One store is enough; pin a different one only if you genuinely run separate Pancake catalogs.": "紐付け済みストアは、この管理画面から new-api が作成するすべての Pancake 商品の親コンテナです。ウォレットチャージ商品とサブスクリプションプラン商品が含まれます。通常は 1 つのストアで十分です。別々の Pancake カタログを本当に運用する場合のみ別のストアを固定してください。", @@ -4810,6 +4837,7 @@ "The model you're looking for doesn't exist.": "お探しのモデルは存在しません。", "The name displayed across the application": "アプリケーション全体に表示される名前", "The new token will only be shown once. Copy it and store it securely.": "新しいトークンは一度だけ表示されます。コピーして安全に保管してください。", + "The OAuth account does not match the account linked to your profile.": "このOAuthアカウントは連携済みのアカウントと一致しません。", "The public URL of your server, used for OAuth callbacks, webhooks, and other external integrations": "OAuthコールバック、Webhook、その他の外部統合に使用されるサーバーの公開URL", "The requested chat preset does not exist or has been removed.": "要求されたチャットプリセットは存在しないか、削除されました。", "The reset request stays disabled until a credit is available.": "リセット回数が利用可能になるまで、リセット要求は無効です。", @@ -4821,6 +4849,7 @@ "The token group that will have a custom ratio": "カスタム比率を持つトークングループ", "The token has no group, so it is billed as the user group vip, using the base ratio of vip.": "トークンにグループがないため、ユーザーグループ vip として課金され、vip の基本倍率が使われます。", "The two roles of a group": "グループの2つの役割", + "The two-factor setup has expired or changed. Start setup again.": "二段階認証の設定が期限切れか変更されています。設定をやり直してください。", "The unique identifier for this model": "このモデルの一意の識別子", "The unique name for this vendor": "このベンダーの一意の名前", "The upstream channel that served the requests": "リクエストを処理した上流チャネル", @@ -4904,6 +4933,10 @@ "This user account no longer exists.": "このユーザーアカウントは存在しません。", "this user group": "このユーザーグループ", "This user has no bindings": "このユーザーには連携がありません", + "This verification has already been used. Please verify again.": "この認証はすでに使用されています。もう一度認証してください。", + "This verification method is currently unavailable.": "この確認方法は現在利用できません。", + "This verification method is not allowed for this action.": "この操作ではこの確認方法を使用できません。", + "This verification method requires its dedicated verification flow.": "この確認方法では専用の確認フローを使用してください。", "This week": "今週", "This will append 2 template rules (Codex CLI and Claude CLI) to the existing rule list.": "既存のルールリストに2つのテンプレートルール(Codex CLIとClaude CLI)を追加します。", "This will clear custom pricing ratios and revert to upstream defaults.": "これにより、カスタム料金比率がクリアされ、上位のデフォルトに戻ります。", @@ -5107,6 +5140,9 @@ "Two-Factor Authentication": "2要素認証", "Two-factor authentication disabled": "二要素認証が無効になりました", "Two-factor authentication enabled successfully!": "二要素認証が正常に有効化されました!", + "Two-factor authentication is already enabled.": "二段階認証はすでに有効です。", + "Two-factor authentication is not enabled.": "二段階認証は有効になっていません。", + "Two-factor authentication is temporarily locked.": "二段階認証は一時的にロックされています。", "Two-factor authentication reset": "二要素認証がリセットされました", "Two-Step Verification": "2段階認証", "Type": "タイプ", @@ -5125,6 +5161,7 @@ "Unable to load rankings": "ランキングを読み込めません", "Unable to load rankings data": "ランキングデータを読み込めません", "Unable to open chat": "チャットを開けません", + "Unable to parse Passkey login options from response": "応答からPasskeyのログインオプションを読み取れません", "Unable to parse structured pricing": "構造化された価格を解析できません", "Unable to prepare chat link. Please ensure you have an enabled API key.": "チャットリンクを準備できません。有効な API キーが設定されていることを確認してください。", "Unable to read clipboard": "クリップボードを読み取れません", @@ -5387,20 +5424,25 @@ "Verification code must be 6 digits": "認証コードは6桁である必要があります", "Verification code sent! Please check your email.": "認証コードを送信しました!メールを確認してください。", "Verification code updates every 30 seconds.": "認証コードは 30 秒ごとに更新されます。", + "Verification does not match this action.": "確認がこの操作に対応していません。", + "Verification does not match this action's details. Please verify again.": "認証内容が今回の操作内容と一致しません。もう一度認証してください。", "Verification email sent": "認証メールを送信しました", "Verification failed": "認証に失敗しました", + "Verification failed. Please try again.": "確認に失敗しました。もう一度お試しください。", "Verification flow expired": "認証手続きの有効期限が切れました", "Verification is not configured properly": "認証が正しく設定されていません", "Verification proof was not returned": "認証証明が返されませんでした", "Verification required to reveal the saved key.": "保存されたキーを表示するには、認証が必要です。", "Verification scope is missing": "検証スコープがありません", "Verify": "認証", + "Verify again before retrying this action.": "この操作を再試行する前に、もう一度認証してください。", "Verify and Sign In": "確認してサインイン", "Verify routing with Playground or your client": "Playground またはクライアントでルーティングを確認", "Verify Setup": "設定を確認", "Verify to view channel key": "認証してチャネルキーを表示", "Verify your database connection": "データベース接続を確認", "Verifying credentials and pulling stores from your Pancake account...": "認証情報を検証し、Pancake アカウントからストアを取得しています...", + "Verifying your {{provider}} account": "{{provider}}アカウントを確認しています", "Version": "バージョン", "Version history": "バージョン履歴", "Version Overrides": "バージョンオーバーライド", @@ -5572,6 +5614,7 @@ "You commit not to use this system to implement, assist with, or indirectly implement acts that violate applicable laws and regulations, regulatory requirements, platform rules, public interests, or the lawful rights and interests of third parties.": "適用される法令、規制要件、プラットフォーム規則、公共の利益、または第三者の正当な権利利益に違反する行為を、このシステムを用いて実施、支援、または間接的に実施しないことを約束します。", "You commit to using upstream APIs, accounts, keys, quotas, and service capabilities only within the scope of lawful authorization obtained from upstream service providers, model service providers, or relevant rights holders, and will not conduct unauthorized resale, trafficking, distribution, or other non-compliant commercialization.": "上流 API、アカウント、キー、クォータ、サービス機能を、上流サービス提供者、モデルサービス提供者、または関連する権利者から取得した合法的な許可の範囲内でのみ使用し、無許可の再販売、転売、配布、その他の不適切な商業利用を行わないことを約束します。", "You do not have permission to edit sensitive channel settings.": "機密チャネル設定を編集する権限がありません。", + "You do not have permission to perform this action.": "この操作を実行する権限がありません。", "You don't have necessary permission": "必要な権限がありません", "You have legally obtained authorization for the connected model APIs, accounts, keys, and quotas.": "接続されたモデル API、アカウント、キー、クォータについて合法的な許可を取得しています。", "You have unsaved changes": "未保存の変更があります", diff --git a/web/src/i18n/locales/ru.json b/web/src/i18n/locales/ru.json index c62554b09b..23e7761717 100644 --- a/web/src/i18n/locales/ru.json +++ b/web/src/i18n/locales/ru.json @@ -128,6 +128,7 @@ "80,443,8080": "80,443,8080", "A billing multiplier. Lower ratios mean lower API call costs.": "Множитель тарификации. Чем ниже коэффициент, тем ниже стоимость вызовов API.", "A focused home for keys, balance, routing, and service health.": "Единый экран для ключей, баланса, маршрутов и состояния сервиса.", + "A security operation is already in progress.": "Операция безопасности уже выполняется.", "About": "О проекте", "About {{days}} days left": "Примерно {{days}} дней", "Accept Unpriced Models": "Принимать модели без цены", @@ -243,6 +244,7 @@ "Add user group": "Добавить группу пользователей", "Add your API keys, set up channels and configure access permissions": "Добавьте ваши API-ключи, настройте каналы и права доступа", "Added {{count}} model(s)": "Добавлено {{count}} моделей", + "Added {{count}} models from \"{{name}}\"": "Добавлено {{count}} моделей из «{{name}}»", "Added successfully": "Успешно добавлено", "Additional Conditions": "Дополнительные условия", "Additional information": "Дополнительная информация", @@ -250,6 +252,7 @@ "Additional Limit": "Доп. лимит", "Additional Limits": "Дополнительные лимиты", "Additional metered capability": "Дополнительная зарезервированная ёмкость (metered)", + "Additional verification required": "Требуется дополнительная проверка", "Adjust filters, then search to refresh the logs.": "Настройте фильтры, затем выполните поиск, чтобы обновить журналы.", "Adjust Quota": "Изменить квоту", "Adjust response formatting, prompt behavior, proxy, and upstream automation.": "Настройте форматирование ответов, поведение промпта, прокси и автоматизацию upstream.", @@ -536,6 +539,7 @@ "Authentication": "Аутентификация", "Authentication Method": "Метод аутентификации", "Authenticator code": "Код аутентификатора", + "Authenticator code or backup code": "Код аутентификатора или резервный код", "Authorization callback URL": "URL обратного вызова авторизации", "Authorization Endpoint": "Конечная точка авторизации", "Authorization Endpoint (Optional)": "Конечная точка авторизации (необязательно)", @@ -814,6 +818,7 @@ "Channel health checks": "Проверки состояния каналов", "Channel ID": "ID канала", "Channel ID is required": "Требуется ID канала", + "Channel is not selected": "Канал не выбран", "Channel key": "Ключ канала", "Channel key unlocked": "Ключ канала разблокирован", "Channel Management": "Управление каналами", @@ -1088,10 +1093,12 @@ "confirm that I bear legal responsibility arising from deployment": "подтверждаю, что несу юридическую ответственность, возникающую из развертывания", "Confirm Unbind": "Подтвердить отвязку", "Confirm usage reset": "Подтвердить сброс использования", + "Confirm your identity before accessing this sensitive action.": "Подтвердите личность перед выполнением этой важной операции.", "Confirm your identity before removing this Passkey from your account.": "Подтвердите свою личность перед удалением этой Passkey из вашей учётной записи.", "Confirm your identity with Two-factor Authentication before registering a Passkey.": "Подтвердите свою личность с помощью двухфакторной аутентификации перед регистрацией Passkey.", "Confirmed at {{time}} by user #{{userId}}": "Подтверждено {{time}} пользователем #{{userId}}", "Confirmed payment compliance": "Соответствие платежа подтверждено", + "Confirming the account linked to your profile.": "Проверяем привязанный к профилю аккаунт.", "Conflict": "Противоречие", "Connect": "Подключение", "Connect through OpenAI, Claude, Gemini, and other compatible API routes": "Подключайтесь через OpenAI, Claude, Gemini и другие совместимые API-маршруты", @@ -1121,6 +1128,7 @@ "Context": "Контекст", "Continue": "Продолжить", "Continue with {{name}}": "Продолжить с {{name}}", + "Continue with an account already linked to your profile.": "Продолжите с аккаунтом, уже привязанным к профилю.", "Continue with Discord": "Продолжить с Discord", "Continue with GitHub": "Продолжить с GitHub", "Continue with LinuxDO": "Продолжить с LinuxDO", @@ -1792,6 +1800,7 @@ "Enter secret key": "Введите секретный ключ", "Enter system prompt (user prompt takes priority)": "Введите системный промпт (пользовательский промпт имеет приоритет)", "Enter tag name (optional)": "Введите имя тега (необязательно)", + "Enter the 6-digit authenticator code or an unused backup code.": "Введите 6-значный код аутентификатора или неиспользованный резервный код.", "Enter the 6-digit code from your authenticator app": "Введите 6-значный код из вашего приложения-аутентификатора", "Enter the 6-digit Time-based One-Time Password or 8-character backup code from your authenticator app.": "Введите 6-значный одноразовый пароль на основе времени или 8-значный резервный код из вашего приложения-аутентификатора.", "Enter the complete URL, supports": "Введите полный URL, поддерживает", @@ -2510,6 +2519,7 @@ "Invalid chat link. Please contact the administrator.": "Неверная ссылка на чат. Пожалуйста, обратитесь к администратору.", "Invalid chat link. Please contact your administrator.": "Недействительная ссылка чата. Обратитесь к администратору.", "Invalid code": "Неверный код", + "Invalid items format": "Неверный формат элементов", "Invalid JSON": "Некорректный JSON", "Invalid JSON format": "Неверный формат JSON", "Invalid JSON format or values out of allowed range": "Неверный формат JSON или значения вне допустимого диапазона", @@ -2666,6 +2676,7 @@ "Limits token selection to a probability mass": "Ограничивает выбор токенов суммарной вероятностью", "LingYiWanWu": "LingYiWanWu", "Link to your documentation site": "Ссылка на ваш сайт документации", + "Linked account": "Привязанный аккаунт", "LinuxDO": "LinuxDO", "LinuxDO Client ID": "ID клиента LinuxDO", "LinuxDO Client Secret": "Секрет клиента LinuxDO", @@ -2690,6 +2701,7 @@ "Loading maintenance settings...": "Загрузка настроек обслуживания...", "Loading settings...": "Загрузка настроек...", "Loading setup status…": "Загрузка статуса установки...", + "Loading verification methods...": "Загрузка способов подтверждения…", "Loading...": "Загрузка...", "Local": "Локальный", "Local Billing": "Локальная тарификация", @@ -3115,6 +3127,7 @@ "No Inviter": "Нет пригласившего", "No keys found": "Ключи не найдены", "No latency data available": "Данные о задержке недоступны", + "No linked OAuth provider is available.": "Нет доступного привязанного провайдера OAuth.", "No log entries matched the selected time.": "Нет записей журнала, соответствующих выбранному времени.", "No logs": "Нет логов", "No Logs Found": "Логи не найдены", @@ -3154,6 +3167,7 @@ "No notable climbers right now": "Сейчас нет значимых поднявшихся моделей", "No notable drops right now": "Сейчас нет значимых упавших моделей", "No parameter overrides configured.": "Нет настроенных переопределений параметров.", + "No Passkey is registered.": "Passkey не зарегистрирован.", "No payment methods available. Please contact administrator.": "Нет доступных способов оплаты. Пожалуйста, свяжитесь с администратором.", "No payment methods configured": "Способы оплаты не настроены", "No payment methods configured. Click \"Add method\" or use templates to get started.": "Способы оплаты не настроены. Нажмите \"Добавить способ\" или используйте шаблоны, чтобы начать.", @@ -3214,6 +3228,7 @@ "No Users Found": "Пользователи не найдены", "No valid custom Auto groups remain. Add a group or restore global Auto.": "Доступных пользовательских групп Auto не осталось. Добавьте группу или восстановите глобальный порядок Auto.", "No vendor data available": "Данных по поставщикам нет", + "No verification method is available for this action.": "Для этой операции нет доступного способа подтверждения.", "No X Found": "X не найдено", "Node": "Узел", "Node filters": "Фильтры узлов", @@ -3262,6 +3277,8 @@ "Number of top log probabilities returned per token": "Количество top-вероятностей на токен", "Number of users invited": "Количество приглашенных пользователей", "OAuth": "OAuth", + "OAuth authorization timed out. Please try again.": "Время авторизации OAuth истекло. Повторите попытку.", + "OAuth authorization was cancelled.": "Авторизация OAuth отменена.", "OAuth binding timed out. Please try again.": "Время ожидания привязки OAuth истекло. Повторите попытку.", "OAuth binding window is no longer available": "Окно привязки OAuth больше недоступно", "OAuth callback URL": "URL обратного вызова OAuth", @@ -3270,6 +3287,8 @@ "OAuth failed": "OAuth не удался", "OAuth Integrations": "Интеграции OAuth", "OAuth pop-up was blocked": "Всплывающее окно OAuth заблокировано", + "OAuth popup storage is unavailable.": "Хранилище всплывающего окна OAuth недоступно.", + "OAuth window is no longer available.": "Окно OAuth больше недоступно.", "Object Prune Rules": "Правила очистки объектов", "Observability": "Наблюдаемость", "Obtain the API key, merchant ID, and RSA key pair from the Waffo dashboard, and configure the callback URL.": "Получите API-ключ, ID мерчанта и пару RSA-ключей в панели управления Waffo и настройте URL обратного вызова.", @@ -3368,6 +3387,7 @@ "operation and charging behavior": "эксплуатацию и взимание платы", "Operation audit": "Аудит операций", "Operation Audit Info": "Информация об аудите операций", + "Operation cancelled": "Операция отменена", "Operation failed": "Операция не удалась", "Operation successful": "Операция выполнена успешно", "Operation Type": "Тип операции", @@ -3474,6 +3494,7 @@ "Passive recovery only": "Только пассивное восстановление", "Passkey": "Passkey", "Passkey Authentication": "Аутентификация Passkey", + "Passkey authentication is disabled.": "Аутентификация Passkey отключена.", "Passkey is not available in this browser": "Passkey недоступен в этом браузере", "Passkey is not supported in this environment": "Passkey не поддерживается в этой среде", "Passkey is not supported on this device": "Passkey не поддерживается на этом устройстве", @@ -4142,6 +4163,7 @@ "Return Error": "Вернуть ошибку", "Return per-token log probabilities": "Возвращать логарифмические вероятности по токенам", "Return to dashboard": "Вернуться на панель управления", + "Return to the original window to continue.": "Вернитесь в исходное окно, чтобы продолжить.", "Return vector embeddings for inputs": "Возвращать векторные эмбеддинги для входных данных", "Reveal API key": "Показать API ключ", "Reveal key": "Показать ключ", @@ -4309,6 +4331,8 @@ "Security & Limits": "Безопасность и лимиты", "Security Check": "Проверка безопасности", "Security verification": "Подтверждение безопасности", + "Security verification has expired. Please verify again.": "Срок подтверждения безопасности истёк. Подтвердите личность снова.", + "Security verification is no longer valid. Please verify again.": "Подтверждение безопасности больше не действует. Пройдите его снова.", "Seed": "Seed", "Select": "Выбрать", "Select a color": "Выбрать цвет", @@ -4452,6 +4476,7 @@ "Settings": "Настройки", "Settings & Preferences": "Настройки и предпочтения", "Settings updated successfully": "Настройки успешно обновлены", + "Setup expired. Scan the new QR code and save the new backup codes.": "Срок настройки истёк. Отсканируйте новый QR-код и сохраните новые резервные коды.", "Setup guide": "Руководство по настройке", "Setup guide complete": "Руководство по настройке завершено", "Setup guide is collapsed. Expand it anytime.": "Руководство по настройке свернуто. Его можно открыть в любой момент.", @@ -4783,6 +4808,7 @@ "Text or array of texts to embed": "Текст или массив текстов для векторизации", "Text Output": "Текстовый выход", "Text to Video": "Текст в видео", + "The action details are invalid.": "Недопустимые параметры действия.", "The admin configured three groups and one special ratio rule:": "Администратор настроил три группы и одно правило особого коэффициента:", "The admin wants vip users to pay even less when they use premium. That needs an override rule: in the override matrix, set the cell at row vip, column premium to 0.3.": "Администратор хочет, чтобы пользователи vip платили ещё меньше при использовании premium. Для этого нужно правило переопределения: в матрице задайте ячейку на пересечении строки vip и столбца premium равной 0,3.", "The administrator account is already initialized. You can keep your existing credentials and continue to the next step.": "Учетная запись администратора уже инициализирована. Вы можете сохранить существующие учетные данные и перейти к следующему шагу.", @@ -4791,6 +4817,7 @@ "The administrator has not configured a user agreement yet.": "Администратор ещё не настроил пользовательское соглашение.", "The administrator has not configured any about content yet. You can set it in the settings page, supporting HTML or URL.": "Администратор еще не настроил содержимое раздела «О программе». Вы можете установить его на странице настроек, поддерживается HTML или URL.", "The API key used for the requests": "API-ключ, использованный для запросов", + "The authenticator code is incorrect.": "Неверный код аутентификатора.", "The binding will complete automatically after authorization": "Привязка завершится автоматически после авторизации", "The bound Product powers wallet top-ups: when a user enters any amount, new-api runs the checkout against this single Pancake product and overrides the price per session — no need to pre-create $1 / $5 / $10 SKUs.": "Привязанный продукт используется для пополнения кошелька: когда пользователь вводит любую сумму, new-api запускает оплату через этот единственный продукт Pancake и переопределяет цену для каждой сессии — не нужно заранее создавать SKU на $1 / $5 / $10.", "The bound Store is the parent container for every Pancake product new-api creates from this admin — both the wallet top-up product and any subscription-plan products. One store is enough; pin a different one only if you genuinely run separate Pancake catalogs.": "Привязанный магазин является родительским контейнером для всех продуктов Pancake, которые new-api создает из этой админки: как продукта пополнения кошелька, так и продуктов планов подписки. Одного магазина достаточно; выбирайте другой только если действительно ведете отдельные каталоги Pancake.", @@ -4810,6 +4837,7 @@ "The model you're looking for doesn't exist.": "Модель, которую вы ищете, не существует.", "The name displayed across the application": "Имя, отображаемое в приложении", "The new token will only be shown once. Copy it and store it securely.": "Новый токен будет показан только один раз. Скопируйте его и сохраните в безопасном месте.", + "The OAuth account does not match the account linked to your profile.": "Этот аккаунт OAuth не совпадает с аккаунтом, привязанным к профилю.", "The public URL of your server, used for OAuth callbacks, webhooks, and other external integrations": "Публичный URL вашего сервера, используемый для OAuth-перенаправлений, вебхуков и других внешних интеграций", "The requested chat preset does not exist or has been removed.": "Запрошенный предустановленный чат не существует или был удален.", "The reset request stays disabled until a credit is available.": "Запрос сброса недоступен, пока нет доступного сброса.", @@ -4821,6 +4849,7 @@ "The token group that will have a custom ratio": "Группа токенов, которая будет иметь пользовательское соотношение", "The token has no group, so it is billed as the user group vip, using the base ratio of vip.": "У токена нет группы, поэтому вызов тарифицируется по группе пользователя vip с базовым коэффициентом vip.", "The two roles of a group": "Две роли группы", + "The two-factor setup has expired or changed. Start setup again.": "Настройка двухфакторной аутентификации истекла или изменилась. Начните заново.", "The unique identifier for this model": "Уникальный идентификатор для этой модели", "The unique name for this vendor": "Уникальное имя для этого поставщика", "The upstream channel that served the requests": "Вышестоящий канал, обслуживший запросы", @@ -4904,6 +4933,10 @@ "This user account no longer exists.": "Эта учётная запись пользователя больше не существует.", "this user group": "эта группа пользователей", "This user has no bindings": "У этого пользователя нет привязок", + "This verification has already been used. Please verify again.": "Это подтверждение уже использовано. Подтвердите личность ещё раз.", + "This verification method is currently unavailable.": "Этот способ подтверждения сейчас недоступен.", + "This verification method is not allowed for this action.": "Этот способ подтверждения не разрешён для данной операции.", + "This verification method requires its dedicated verification flow.": "Для этого способа необходимо пройти отдельную процедуру подтверждения.", "This week": "На этой неделе", "This will append 2 template rules (Codex CLI and Claude CLI) to the existing rule list.": "Это добавит 2 шаблонных правила (Codex CLI и Claude CLI) к существующему списку правил.", "This will clear custom pricing ratios and revert to upstream defaults.": "Это очистит пользовательские ценовые коэффициенты и вернет к стандартным значениям поставщика.", @@ -5107,6 +5140,9 @@ "Two-Factor Authentication": "Двухфакторная аутентификация", "Two-factor authentication disabled": "Двухфакторная аутентификация отключена", "Two-factor authentication enabled successfully!": "Двухфакторная аутентификация успешно включена!", + "Two-factor authentication is already enabled.": "Двухфакторная аутентификация уже включена.", + "Two-factor authentication is not enabled.": "Двухфакторная аутентификация не включена.", + "Two-factor authentication is temporarily locked.": "Двухфакторная аутентификация временно заблокирована.", "Two-factor authentication reset": "Двухфакторная аутентификация сброшена", "Two-Step Verification": "Двухэтапная проверка", "Type": "Тип", @@ -5125,6 +5161,7 @@ "Unable to load rankings": "Не удалось загрузить рейтинги", "Unable to load rankings data": "Не удалось загрузить данные рейтингов", "Unable to open chat": "Не удалось открыть чат", + "Unable to parse Passkey login options from response": "Не удалось прочитать параметры входа Passkey из ответа", "Unable to parse structured pricing": "Не удалось разобрать структурированные цены", "Unable to prepare chat link. Please ensure you have an enabled API key.": "Не удается подготовить ссылку для чата. Убедитесь, что у вас есть активированный API-ключ.", "Unable to read clipboard": "Не удалось прочитать буфер обмена", @@ -5387,20 +5424,25 @@ "Verification code must be 6 digits": "Код подтверждения должен содержать 6 цифр", "Verification code sent! Please check your email.": "Код подтверждения отправлен! Пожалуйста, проверьте вашу электронную почту.", "Verification code updates every 30 seconds.": "Код подтверждения обновляется каждые 30 секунд.", + "Verification does not match this action.": "Подтверждение не соответствует этой операции.", + "Verification does not match this action's details. Please verify again.": "Подтверждение не соответствует параметрам этого действия. Подтвердите личность ещё раз.", "Verification email sent": "Письмо для подтверждения отправлено", "Verification failed": "Подтверждение не удалось", + "Verification failed. Please try again.": "Подтверждение не удалось. Повторите попытку.", "Verification flow expired": "Процесс проверки истёк", "Verification is not configured properly": "Подтверждение настроено неправильно", "Verification proof was not returned": "Подтверждение проверки не было получено", "Verification required to reveal the saved key.": "Требуется подтверждение для отображения сохраненного ключа.", "Verification scope is missing": "Область проверки не указана", "Verify": "Проверить", + "Verify again before retrying this action.": "Прежде чем повторить действие, подтвердите личность ещё раз.", "Verify and Sign In": "Подтвердить и войти", "Verify routing with Playground or your client": "Проверьте маршрутизацию через Playground или ваш клиент", "Verify Setup": "Проверить настройку", "Verify to view channel key": "Подтвердить для просмотра ключа канала", "Verify your database connection": "Проверьте подключение к базе данных", "Verifying credentials and pulling stores from your Pancake account...": "Проверяем учетные данные и загружаем магазины из вашего аккаунта Pancake...", + "Verifying your {{provider}} account": "Проверка аккаунта {{provider}}", "Version": "Версия", "Version history": "История версий", "Version Overrides": "Переопределения версий", @@ -5572,6 +5614,7 @@ "You commit not to use this system to implement, assist with, or indirectly implement acts that violate applicable laws and regulations, regulatory requirements, platform rules, public interests, or the lawful rights and interests of third parties.": "Вы обязуетесь не использовать эту систему для совершения, содействия или косвенного совершения действий, нарушающих применимые законы и нормы, регуляторные требования, правила платформ, общественные интересы либо законные права и интересы третьих лиц.", "You commit to using upstream APIs, accounts, keys, quotas, and service capabilities only within the scope of lawful authorization obtained from upstream service providers, model service providers, or relevant rights holders, and will not conduct unauthorized resale, trafficking, distribution, or other non-compliant commercialization.": "Вы обязуетесь использовать вышестоящие API, аккаунты, ключи, квоты и сервисные возможности только в пределах законного разрешения, полученного от вышестоящих поставщиков услуг, поставщиков моделей или соответствующих правообладателей, и не осуществлять несанкционированную перепродажу, оборот, распространение или иную несоответствующую коммерциализацию.", "You do not have permission to edit sensitive channel settings.": "У вас нет права изменять чувствительные настройки каналов.", + "You do not have permission to perform this action.": "У вас нет прав на выполнение этого действия.", "You don't have necessary permission": "У вас нет необходимых разрешений", "You have legally obtained authorization for the connected model APIs, accounts, keys, and quotas.": "Вы законно получили разрешение на подключенные API моделей, аккаунты, ключи и квоты.", "You have unsaved changes": "У вас есть несохранённые изменения", diff --git a/web/src/i18n/locales/vi.json b/web/src/i18n/locales/vi.json index 096373980f..3705b723c3 100644 --- a/web/src/i18n/locales/vi.json +++ b/web/src/i18n/locales/vi.json @@ -128,6 +128,7 @@ "80,443,8080": "80,443,8080", "A billing multiplier. Lower ratios mean lower API call costs.": "Hệ số tính phí. Tỷ lệ càng thấp thì chi phí gọi API càng thấp.", "A focused home for keys, balance, routing, and service health.": "Trang tổng quan tập trung cho khóa, số dư, định tuyến và trạng thái dịch vụ.", + "A security operation is already in progress.": "Một thao tác bảo mật đang được thực hiện.", "About": "Giới thiệu", "About {{days}} days left": "Còn khoảng {{days}} ngày", "Accept Unpriced Models": "Chấp nhận các Mô hình chưa định giá", @@ -243,6 +244,7 @@ "Add user group": "Thêm nhóm người dùng", "Add your API keys, set up channels and configure access permissions": "Thêm khóa API, thiết lập kênh và cấu hình quyền truy cập", "Added {{count}} model(s)": "Đã thêm {{count}} mô hình", + "Added {{count}} models from \"{{name}}\"": "Đã thêm {{count}} mô hình từ “{{name}}”", "Added successfully": "Thêm thành công", "Additional Conditions": "Điều kiện bổ sung", "Additional information": "Thông tin bổ sung", @@ -250,6 +252,7 @@ "Additional Limit": "Hạn mức bổ sung", "Additional Limits": "Các hạn mức bổ sung", "Additional metered capability": "Tính năng tính phí theo mức dùng bổ sung", + "Additional verification required": "Cần xác minh bổ sung", "Adjust filters, then search to refresh the logs.": "Điều chỉnh bộ lọc, sau đó tìm kiếm để làm mới nhật ký.", "Adjust Quota": "Điều chỉnh hạn mức", "Adjust response formatting, prompt behavior, proxy, and upstream automation.": "Điều chỉnh định dạng phản hồi, hành vi prompt, proxy và tự động hóa upstream.", @@ -536,6 +539,7 @@ "Authentication": "Xác thực", "Authentication Method": "Phương thức xác thực", "Authenticator code": "Mã xác thực", + "Authenticator code or backup code": "Mã xác thực hoặc mã dự phòng", "Authorization callback URL": "URL callback ủy quyền", "Authorization Endpoint": "Điểm cuối ủy quyền", "Authorization Endpoint (Optional)": "Điểm cuối ủy quyền (Tùy chọn)", @@ -814,6 +818,7 @@ "Channel health checks": "Kiểm tra tình trạng kênh", "Channel ID": "Mã kênh", "Channel ID is required": "Cần có ID kênh", + "Channel is not selected": "Chưa chọn kênh", "Channel key": "Khóa kênh", "Channel key unlocked": "Khóa kênh đã được mở khóa", "Channel Management": "Quản lý kênh", @@ -1088,10 +1093,12 @@ "confirm that I bear legal responsibility arising from deployment": "xác nhận rằng tôi chịu trách nhiệm pháp lý phát sinh từ việc triển khai", "Confirm Unbind": "Xác nhận hủy liên kết", "Confirm usage reset": "Xác nhận đặt lại mức dùng", + "Confirm your identity before accessing this sensitive action.": "Xác minh danh tính trước khi thực hiện thao tác nhạy cảm này.", "Confirm your identity before removing this Passkey from your account.": "Hãy xác minh danh tính trước khi gỡ Passkey khỏi tài khoản.", "Confirm your identity with Two-factor Authentication before registering a Passkey.": "Hãy xác minh danh tính bằng Xác thực hai yếu tố trước khi đăng ký Passkey.", "Confirmed at {{time}} by user #{{userId}}": "Được xác nhận lúc {{time}} bởi người dùng #{{userId}}", "Confirmed payment compliance": "Đã xác nhận tuân thủ thanh toán", + "Confirming the account linked to your profile.": "Đang xác minh tài khoản đã liên kết với hồ sơ của bạn.", "Conflict": "Xung đột", "Connect": "Kết nối", "Connect through OpenAI, Claude, Gemini, and other compatible API routes": "Kết nối qua OpenAI, Claude, Gemini và các tuyến API tương thích khác", @@ -1121,6 +1128,7 @@ "Context": "Ngữ cảnh", "Continue": "Tiếp tục", "Continue with {{name}}": "Tiếp tục với {{name}}", + "Continue with an account already linked to your profile.": "Tiếp tục bằng tài khoản đã liên kết với hồ sơ của bạn.", "Continue with Discord": "Tiếp tục với Discord", "Continue with GitHub": "Tiếp tục với GitHub", "Continue with LinuxDO": "Tiếp tục với LinuxDO", @@ -1792,6 +1800,7 @@ "Enter secret key": "Nhập khóa bí mật", "Enter system prompt (user prompt takes priority)": "Nhập lời nhắc hệ thống (lời nhắc người dùng được ưu tiên)", "Enter tag name (optional)": "Nhập tên thẻ (tùy chọn)", + "Enter the 6-digit authenticator code or an unused backup code.": "Nhập mã xác thực 6 chữ số hoặc mã dự phòng chưa sử dụng.", "Enter the 6-digit code from your authenticator app": "Nhập mã 6 chữ số từ ứng dụng xác thực của bạn", "Enter the 6-digit Time-based One-Time Password or 8-character backup code from your authenticator app.": "Nhập Mật khẩu dùng một lần dựa trên thời gian gồm 6 chữ số hoặc mã dự phòng gồm 8 ký tự từ ứng dụng xác thực của bạn.", "Enter the complete URL, supports": "Nhập địa chỉ URL hoàn chỉnh, hỗ trợ", @@ -2510,6 +2519,7 @@ "Invalid chat link. Please contact the administrator.": "Liên kết trò chuyện không hợp lệ. Vui lòng liên hệ quản trị viên.", "Invalid chat link. Please contact your administrator.": "Liên kết trò chuyện không hợp lệ. Vui lòng liên hệ với quản trị viên của bạn.", "Invalid code": "Mã không hợp lệ", + "Invalid items format": "Định dạng mục không hợp lệ", "Invalid JSON": "JSON không hợp lệ", "Invalid JSON format": "Định dạng JSON không hợp lệ", "Invalid JSON format or values out of allowed range": "Định dạng JSON không hợp lệ hoặc giá trị ngoài phạm vi cho phép", @@ -2666,6 +2676,7 @@ "Limits token selection to a probability mass": "Giới hạn lựa chọn token theo khối xác suất", "LingYiWanWu": "LingYiWanWu", "Link to your documentation site": "Liên kết đến trang web tài liệu của bạn", + "Linked account": "Tài khoản đã liên kết", "LinuxDO": "LinuxDO", "LinuxDO Client ID": "LinuxDO Mã khách hàng", "LinuxDO Client Secret": "LinuxDO Bí mật máy khách", @@ -2690,6 +2701,7 @@ "Loading maintenance settings...": "Đang tải cài đặt bảo trì...", "Loading settings...": "Đang tải cài đặt...", "Loading setup status…": "Đang tải trạng thái cài đặt…", + "Loading verification methods...": "Đang tải phương thức xác minh…", "Loading...": "Đang tải...", "Local": "Địa phương", "Local Billing": "Thanh toán nội địa", @@ -3115,6 +3127,7 @@ "No Inviter": "Không có người mời", "No keys found": "Không tìm thấy khóa", "No latency data available": "Không có dữ liệu độ trễ", + "No linked OAuth provider is available.": "Không có nhà cung cấp OAuth đã liên kết nào khả dụng.", "No log entries matched the selected time.": "Không có mục nhật ký nào khớp với thời gian đã chọn.", "No logs": "Không có nhật ký", "No Logs Found": "Không tìm thấy nhật ký", @@ -3154,6 +3167,7 @@ "No notable climbers right now": "Hiện chưa có mô hình nào tăng đáng kể", "No notable drops right now": "Hiện chưa có mô hình nào giảm đáng kể", "No parameter overrides configured.": "Không có ghi đè tham số nào được cấu hình.", + "No Passkey is registered.": "Chưa đăng ký Passkey.", "No payment methods available. Please contact administrator.": "Không có phương thức thanh toán nào khả dụng. Vui lòng liên hệ quản trị viên.", "No payment methods configured": "Chưa cấu hình phương thức thanh toán", "No payment methods configured. Click \"Add method\" or use templates to get started.": "Chưa cấu hình phương thức thanh toán. Nhấp vào \"Thêm phương thức\" hoặc sử dụng mẫu để bắt đầu.", @@ -3214,6 +3228,7 @@ "No Users Found": "Không tìm thấy người dùng nào", "No valid custom Auto groups remain. Add a group or restore global Auto.": "Không còn nhóm Auto tùy chỉnh hợp lệ. Hãy thêm nhóm hoặc khôi phục Auto toàn cục.", "No vendor data available": "Không có dữ liệu nhà cung cấp", + "No verification method is available for this action.": "Không có phương thức xác minh khả dụng cho thao tác này.", "No X Found": "Không tìm thấy X", "Node": "Nút", "Node filters": "Bộ lọc nút", @@ -3262,6 +3277,8 @@ "Number of top log probabilities returned per token": "Số log probabilities hàng đầu trên mỗi token", "Number of users invited": "Số người dùng được mời", "OAuth": "OAuth", + "OAuth authorization timed out. Please try again.": "Ủy quyền OAuth đã hết thời gian chờ. Vui lòng thử lại.", + "OAuth authorization was cancelled.": "Đã hủy ủy quyền OAuth.", "OAuth binding timed out. Please try again.": "Liên kết OAuth đã hết thời gian chờ. Vui lòng thử lại.", "OAuth binding window is no longer available": "Cửa sổ liên kết OAuth không còn khả dụng", "OAuth callback URL": "URL callback OAuth", @@ -3270,6 +3287,8 @@ "OAuth failed": "OAuth thất bại", "OAuth Integrations": "Tích hợp OAuth", "OAuth pop-up was blocked": "Cửa sổ bật lên OAuth đã bị chặn", + "OAuth popup storage is unavailable.": "Không thể sử dụng bộ nhớ của cửa sổ OAuth.", + "OAuth window is no longer available.": "Cửa sổ OAuth không còn khả dụng.", "Object Prune Rules": "Quy tắc dọn dẹp đối tượng", "Observability": "Khả năng quan sát", "Obtain the API key, merchant ID, and RSA key pair from the Waffo dashboard, and configure the callback URL.": "Lấy API key, mã thương gia và cặp khóa RSA từ bảng điều khiển Waffo, đồng thời cấu hình URL callback.", @@ -3368,6 +3387,7 @@ "operation and charging behavior": "vận hành và thu phí", "Operation audit": "Kiểm toán thao tác", "Operation Audit Info": "Thông tin kiểm toán thao tác", + "Operation cancelled": "Đã hủy thao tác", "Operation failed": "Thao tác thất bại", "Operation successful": "Thao tác thành công", "Operation Type": "Loại thao tác", @@ -3474,6 +3494,7 @@ "Passive recovery only": "Chỉ khôi phục thụ động", "Passkey": "Khóa truy cập", "Passkey Authentication": "Xác thực khóa truy cập", + "Passkey authentication is disabled.": "Xác thực Passkey đã bị tắt.", "Passkey is not available in this browser": "Passkey không khả dụng trong trình duyệt này", "Passkey is not supported in this environment": "Passkey không được hỗ trợ trong môi trường này", "Passkey is not supported on this device": "Passkey không được hỗ trợ trên thiết bị này", @@ -4142,6 +4163,7 @@ "Return Error": "Trả về lỗi", "Return per-token log probabilities": "Trả về log probabilities cho từng token", "Return to dashboard": "Quay lại bảng điều khiển", + "Return to the original window to continue.": "Quay lại cửa sổ ban đầu để tiếp tục.", "Return vector embeddings for inputs": "Trả về vector embedding cho đầu vào", "Reveal API key": "Hiển thị khóa API", "Reveal key": "Display key", @@ -4309,6 +4331,8 @@ "Security & Limits": "Bảo mật & giới hạn", "Security Check": "Kiểm tra bảo mật", "Security verification": "Xác minh bảo mật", + "Security verification has expired. Please verify again.": "Xác minh bảo mật đã hết hạn. Vui lòng xác minh lại.", + "Security verification is no longer valid. Please verify again.": "Xác minh bảo mật không còn hợp lệ. Vui lòng xác minh lại.", "Seed": "Seed", "Select": "Chọn", "Select a color": "Chọn một màu", @@ -4452,6 +4476,7 @@ "Settings": "Cài đặt", "Settings & Preferences": "Cài đặt & Tùy chọn", "Settings updated successfully": "Cài đặt đã được cập nhật thành công", + "Setup expired. Scan the new QR code and save the new backup codes.": "Thiết lập đã hết hạn. Quét mã QR mới và lưu các mã dự phòng mới.", "Setup guide": "Hướng dẫn thiết lập", "Setup guide complete": "Đã hoàn tất hướng dẫn thiết lập", "Setup guide is collapsed. Expand it anytime.": "Hướng dẫn thiết lập đã được thu gọn. Bạn có thể mở lại bất cứ lúc nào.", @@ -4783,6 +4808,7 @@ "Text or array of texts to embed": "Văn bản hoặc mảng văn bản cần vector hoá", "Text Output": "Đầu ra văn bản", "Text to Video": "Văn bản sang video", + "The action details are invalid.": "Thông tin thao tác không hợp lệ.", "The admin configured three groups and one special ratio rule:": "Quản trị viên đã cấu hình ba nhóm và một quy tắc hệ số đặc biệt:", "The admin wants vip users to pay even less when they use premium. That needs an override rule: in the override matrix, set the cell at row vip, column premium to 0.3.": "Quản trị viên muốn người dùng vip trả ít hơn nữa khi dùng premium. Điều đó cần một quy tắc ghi đè: trong ma trận ghi đè, đặt ô tại hàng vip, cột premium thành 0.3.", "The administrator account is already initialized. You can keep your existing credentials and continue to the next step.": "Tài khoản quản trị viên đã được khởi tạo. Bạn có thể giữ nguyên thông tin đăng nhập hiện có của mình và tiếp tục sang bước tiếp theo.", @@ -4791,6 +4817,7 @@ "The administrator has not configured a user agreement yet.": "Quản trị viên chưa cấu hình thỏa thuận người dùng.", "The administrator has not configured any about content yet. You can set it in the settings page, supporting HTML or URL.": "Quản trị viên chưa cấu hình bất kỳ nội dung giới thiệu nào. Bạn có thể thiết lập nó trong trang cài đặt, hỗ trợ HTML hoặc URL.", "The API key used for the requests": "Khóa API được dùng cho các yêu cầu", + "The authenticator code is incorrect.": "Mã xác thực không chính xác.", "The binding will complete automatically after authorization": "Việc liên kết sẽ hoàn tất tự động sau khi ủy quyền", "The bound Product powers wallet top-ups: when a user enters any amount, new-api runs the checkout against this single Pancake product and overrides the price per session — no need to pre-create $1 / $5 / $10 SKUs.": "Sản phẩm đã liên kết dùng cho nạp ví: khi người dùng nhập bất kỳ số tiền nào, new-api chạy thanh toán trên một sản phẩm Pancake duy nhất này và ghi đè giá theo từng phiên — không cần tạo trước SKU $1 / $5 / $10.", "The bound Store is the parent container for every Pancake product new-api creates from this admin — both the wallet top-up product and any subscription-plan products. One store is enough; pin a different one only if you genuinely run separate Pancake catalogs.": "Cửa hàng đã liên kết là vùng chứa cha cho mọi sản phẩm Pancake mà new-api tạo từ trang quản trị này — bao gồm sản phẩm nạp ví và mọi sản phẩm gói đăng ký. Một cửa hàng là đủ; chỉ ghim cửa hàng khác nếu bạn thực sự vận hành các catalog Pancake riêng.", @@ -4810,6 +4837,7 @@ "The model you're looking for doesn't exist.": "Mô hình bạn đang tìm kiếm không tồn tại.", "The name displayed across the application": "Tên hiển thị trên ứng dụng", "The new token will only be shown once. Copy it and store it securely.": "Token mới chỉ được hiển thị một lần. Hãy sao chép và lưu trữ an toàn.", + "The OAuth account does not match the account linked to your profile.": "Tài khoản OAuth không khớp với tài khoản đã liên kết với hồ sơ của bạn.", "The public URL of your server, used for OAuth callbacks, webhooks, and other external integrations": "URL công khai của máy chủ, dùng cho callback OAuth, webhook và các tích hợp bên ngoài khác", "The requested chat preset does not exist or has been removed.": "Cài đặt sẵn cuộc trò chuyện được yêu cầu không tồn tại hoặc đã bị xóa.", "The reset request stays disabled until a credit is available.": "Yêu cầu đặt lại sẽ bị tắt cho đến khi có lượt khả dụng.", @@ -4821,6 +4849,7 @@ "The token group that will have a custom ratio": "The token group will have a custom ratio.", "The token has no group, so it is billed as the user group vip, using the base ratio of vip.": "Token không có nhóm, nên được tính phí theo nhóm người dùng vip, dùng hệ số cơ bản của vip.", "The two roles of a group": "Hai vai trò của một nhóm", + "The two-factor setup has expired or changed. Start setup again.": "Thiết lập xác thực hai yếu tố đã hết hạn hoặc thay đổi. Vui lòng thiết lập lại.", "The unique identifier for this model": "Mã định danh duy nhất cho mô hình này", "The unique name for this vendor": "Tên duy nhất cho nhà cung cấp này", "The upstream channel that served the requests": "Kênh thượng nguồn đã phục vụ các yêu cầu", @@ -4904,6 +4933,10 @@ "This user account no longer exists.": "Tài khoản người dùng này không còn tồn tại.", "this user group": "nhóm người dùng này", "This user has no bindings": "Người dùng này không có liên kết nào", + "This verification has already been used. Please verify again.": "Xác minh này đã được sử dụng. Vui lòng xác minh lại.", + "This verification method is currently unavailable.": "Phương thức xác minh này hiện không khả dụng.", + "This verification method is not allowed for this action.": "Thao tác này không cho phép sử dụng phương thức xác minh này.", + "This verification method requires its dedicated verification flow.": "Phương thức này cần được thực hiện qua quy trình xác minh riêng.", "This week": "Tuần này", "This will append 2 template rules (Codex CLI and Claude CLI) to the existing rule list.": "Thao tác này sẽ thêm 2 quy tắc mẫu (Codex CLI và Claude CLI) vào danh sách quy tắc hiện có.", "This will clear custom pricing ratios and revert to upstream defaults.": "Điều này sẽ xóa các tỷ lệ giá tùy chỉnh và trở về mặc định ban đầu.", @@ -5107,6 +5140,9 @@ "Two-Factor Authentication": "Xác thực hai yếu tố", "Two-factor authentication disabled": "Xác thực hai yếu tố đã bị vô hiệu hóa", "Two-factor authentication enabled successfully!": "Xác thực hai yếu tố đã được bật thành công!", + "Two-factor authentication is already enabled.": "Xác thực hai yếu tố đã được bật.", + "Two-factor authentication is not enabled.": "Xác thực hai yếu tố chưa được bật.", + "Two-factor authentication is temporarily locked.": "Xác thực hai yếu tố tạm thời bị khóa.", "Two-factor authentication reset": "Xác thực hai yếu tố đã được đặt lại", "Two-Step Verification": "Xác minh hai bước", "Type": "Loại", @@ -5125,6 +5161,7 @@ "Unable to load rankings": "Không thể tải bảng xếp hạng", "Unable to load rankings data": "Không thể tải dữ liệu bảng xếp hạng", "Unable to open chat": "Không thể mở trò chuyện", + "Unable to parse Passkey login options from response": "Không thể đọc tùy chọn đăng nhập Passkey từ phản hồi", "Unable to parse structured pricing": "Không thể phân tích giá có cấu trúc", "Unable to prepare chat link. Please ensure you have an enabled API key.": "Không thể chuẩn bị liên kết chat. Vui lòng đảm bảo bạn có khóa API được kích hoạt.", "Unable to read clipboard": "Không thể đọc bảng tạm", @@ -5387,20 +5424,25 @@ "Verification code must be 6 digits": "Mã xác thực phải có 6 chữ số", "Verification code sent! Please check your email.": "Mã xác thực đã được gửi! Vui lòng kiểm tra email của bạn.", "Verification code updates every 30 seconds.": "Mã xác minh cập nhật mỗi 30 giây.", + "Verification does not match this action.": "Xác minh không khớp với thao tác này.", + "Verification does not match this action's details. Please verify again.": "Thông tin xác minh không khớp với thao tác này. Vui lòng xác minh lại.", "Verification email sent": "Email xác thực đã được gửi", "Verification failed": "Xác thực thất bại", + "Verification failed. Please try again.": "Xác minh thất bại. Vui lòng thử lại.", "Verification flow expired": "Quy trình xác minh đã hết hạn", "Verification is not configured properly": "Xác thực chưa được cấu hình đúng cách", "Verification proof was not returned": "Không nhận được bằng chứng xác minh", "Verification required to reveal the saved key.": "Yêu cầu xác minh để tiết lộ khóa đã lưu.", "Verification scope is missing": "Thiếu phạm vi xác minh", "Verify": "Kiểm tra", + "Verify again before retrying this action.": "Vui lòng xác minh lại trước khi thử lại thao tác này.", "Verify and Sign In": "Xác minh và Đăng nhập", "Verify routing with Playground or your client": "Xác minh định tuyến bằng Playground hoặc client của bạn", "Verify Setup": "Xác minh thiết lập", "Verify to view channel key": "Xác minh để xem khóa kênh", "Verify your database connection": "Xác minh kết nối cơ sở dữ liệu của bạn", "Verifying credentials and pulling stores from your Pancake account...": "Đang xác minh thông tin xác thực và lấy cửa hàng từ tài khoản Pancake của bạn...", + "Verifying your {{provider}} account": "Đang xác minh tài khoản {{provider}} của bạn", "Version": "Phiên bản", "Version history": "Lịch sử phiên bản", "Version Overrides": "Ghi đè phiên bản", @@ -5572,6 +5614,7 @@ "You commit not to use this system to implement, assist with, or indirectly implement acts that violate applicable laws and regulations, regulatory requirements, platform rules, public interests, or the lawful rights and interests of third parties.": "Bạn cam kết không sử dụng hệ thống này để thực hiện, hỗ trợ hoặc gián tiếp thực hiện các hành vi vi phạm luật và quy định hiện hành, yêu cầu quản lý, quy tắc nền tảng, lợi ích công cộng hoặc quyền và lợi ích hợp pháp của bên thứ ba.", "You commit to using upstream APIs, accounts, keys, quotas, and service capabilities only within the scope of lawful authorization obtained from upstream service providers, model service providers, or relevant rights holders, and will not conduct unauthorized resale, trafficking, distribution, or other non-compliant commercialization.": "Bạn cam kết chỉ sử dụng API upstream, tài khoản, khóa, hạn mức và năng lực dịch vụ trong phạm vi ủy quyền hợp pháp nhận được từ nhà cung cấp dịch vụ upstream, nhà cung cấp mô hình hoặc chủ thể quyền liên quan, và sẽ không thực hiện bán lại, giao dịch, phân phối trái phép hoặc thương mại hóa không tuân thủ khác.", "You do not have permission to edit sensitive channel settings.": "Bạn không có quyền chỉnh sửa cài đặt kênh nhạy cảm.", + "You do not have permission to perform this action.": "Bạn không có quyền thực hiện thao tác này.", "You don't have necessary permission": "Bạn không có quyền cần thiết", "You have legally obtained authorization for the connected model APIs, accounts, keys, and quotas.": "Bạn đã nhận được ủy quyền hợp pháp cho API mô hình, tài khoản, khóa và hạn mức được kết nối.", "You have unsaved changes": "Bạn có thay đổi chưa được lưu", diff --git a/web/src/i18n/locales/zh-TW.json b/web/src/i18n/locales/zh-TW.json index f7415994ae..78cb92b205 100644 --- a/web/src/i18n/locales/zh-TW.json +++ b/web/src/i18n/locales/zh-TW.json @@ -128,6 +128,7 @@ "80,443,8080": "80,443,8080", "A billing multiplier. Lower ratios mean lower API call costs.": "收費乘數,倍率越低,API 呼叫費用越低。", "A focused home for keys, balance, routing, and service health.": "集中展示金鑰、餘額、路由和服務健康狀態。", + "A security operation is already in progress.": "已有安全操作正在進行。", "About": "關於", "About {{days}} days left": "約剩 {{days}} 日", "Accept Unpriced Models": "接受未定價模型", @@ -243,6 +244,7 @@ "Add user group": "新增用戶分組", "Add your API keys, set up channels and configure access permissions": "新增 API 金鑰,設定渠道並設定存取權限", "Added {{count}} model(s)": "已新增 {{count}} 個模型", + "Added {{count}} models from \"{{name}}\"": "已從「{{name}}」新增 {{count}} 個模型", "Added successfully": "新增成功", "Additional Conditions": "附加條件", "Additional information": "附加資訊", @@ -250,6 +252,7 @@ "Additional Limit": "附加額度", "Additional Limits": "附加額度", "Additional metered capability": "附加收費能力", + "Additional verification required": "需要進一步驗證", "Adjust filters, then search to refresh the logs.": "調整篩選條件,然後搜尋以重新整理日誌。", "Adjust Quota": "調整額度", "Adjust response formatting, prompt behavior, proxy, and upstream automation.": "調整回應格式、提示詞行為、代理和上游自動化。", @@ -536,6 +539,7 @@ "Authentication": "身份驗證", "Authentication Method": "認證方式", "Authenticator code": "身份驗證器代碼", + "Authenticator code or backup code": "驗證器驗證碼或備用碼", "Authorization callback URL": "授權回呼 URL", "Authorization Endpoint": "授權端點", "Authorization Endpoint (Optional)": "授權端點(可選)", @@ -814,6 +818,7 @@ "Channel health checks": "渠道健康檢查", "Channel ID": "渠道 ID", "Channel ID is required": "缺少渠道 ID", + "Channel is not selected": "尚未選擇管道", "Channel key": "渠道金鑰", "Channel key unlocked": "渠道金鑰已解鎖", "Channel Management": "渠道管理", @@ -1088,10 +1093,12 @@ "confirm that I bear legal responsibility arising from deployment": "確認承擔因部署", "Confirm Unbind": "確認解綁", "Confirm usage reset": "確認重置用量", + "Confirm your identity before accessing this sensitive action.": "執行此敏感操作前,請先驗證身分。", "Confirm your identity before removing this Passkey from your account.": "在解綁目前賬號的 Passkey 前請確認你的身份。", "Confirm your identity with Two-factor Authentication before registering a Passkey.": "在註冊 Passkey 前請使用兩步驗證確認你的身份。", "Confirmed at {{time}} by user #{{userId}}": "用戶 #{{userId}} 於 {{time}} 確認", "Confirmed payment compliance": "確認支付合規", + "Confirming the account linked to your profile.": "正在確認已綁定的帳號。", "Conflict": "矛盾", "Connect": "連接", "Connect through OpenAI, Claude, Gemini, and other compatible API routes": "透過 OpenAI、Claude、Gemini 以及其他兼容 API 路由接入", @@ -1121,6 +1128,7 @@ "Context": "上下文", "Continue": "繼續", "Continue with {{name}}": "使用 {{name}} 繼續", + "Continue with an account already linked to your profile.": "使用已綁定的帳號繼續驗證。", "Continue with Discord": "使用 Discord 繼續", "Continue with GitHub": "使用 GitHub 繼續", "Continue with LinuxDO": "使用 LinuxDO 繼續", @@ -1792,6 +1800,7 @@ "Enter secret key": "輸入金鑰", "Enter system prompt (user prompt takes priority)": "輸入系統提示詞(用戶提示詞優先)", "Enter tag name (optional)": "輸入標籤名稱(可選)", + "Enter the 6-digit authenticator code or an unused backup code.": "輸入驗證器的 6 位驗證碼或未使用的備用碼。", "Enter the 6-digit code from your authenticator app": "輸入來自身份驗證器套用的 6 位代碼", "Enter the 6-digit Time-based One-Time Password or 8-character backup code from your authenticator app.": "輸入來自身份驗證器套用的 6 位基於時間的單次密碼或 8 位備份代碼。", "Enter the complete URL, supports": "輸入完整的 URL,支援", @@ -2510,6 +2519,7 @@ "Invalid chat link. Please contact the administrator.": "無效的聊天連結。請聯絡管理員。", "Invalid chat link. Please contact your administrator.": "無效的聊天連結。請聯絡您的管理員。", "Invalid code": "無效代碼", + "Invalid items format": "項目格式無效", "Invalid JSON": "JSON 無效", "Invalid JSON format": "無效的 JSON 格式", "Invalid JSON format or values out of allowed range": "無效的 JSON 格式或值超出允許範圍", @@ -2666,6 +2676,7 @@ "Limits token selection to a probability mass": "依機率質量限制詞元選擇範圍", "LingYiWanWu": "LingYiWanWu", "Link to your documentation site": "您的文件站點連結", + "Linked account": "已綁定帳號", "LinuxDO": "LinuxDO", "LinuxDO Client ID": "LinuxDO 用戶端 ID", "LinuxDO Client Secret": "LinuxDO 用戶端密鑰", @@ -2690,6 +2701,7 @@ "Loading maintenance settings...": "正在載入維護設定...", "Loading settings...": "正在載入設定...", "Loading setup status…": "正在載入設定狀態…", + "Loading verification methods...": "正在載入驗證方式…", "Loading...": "載入中...", "Local": "本地", "Local Billing": "本地收費", @@ -3115,6 +3127,7 @@ "No Inviter": "無邀請人", "No keys found": "未找到金鑰", "No latency data available": "暫無延遲數據", + "No linked OAuth provider is available.": "沒有可用的已綁定 OAuth 提供方。", "No log entries matched the selected time.": "沒有日誌條目匹配所選時間。", "No logs": "暫無日誌", "No Logs Found": "未找到日誌", @@ -3154,6 +3167,7 @@ "No notable climbers right now": "目前沒有顯著上升的模型", "No notable drops right now": "目前沒有顯著下降的模型", "No parameter overrides configured.": "未設定參數覆蓋。", + "No Passkey is registered.": "尚未註冊 Passkey。", "No payment methods available. Please contact administrator.": "沒有可用的支付方式。請聯絡管理員。", "No payment methods configured": "暫無支付方式", "No payment methods configured. Click \"Add method\" or use templates to get started.": "未設定支付方式。點擊「新增方式」或使用模板開始。", @@ -3214,6 +3228,7 @@ "No Users Found": "未找到用戶", "No valid custom Auto groups remain. Add a group or restore global Auto.": "沒有可用的自訂 Auto 分組。請新增分組或恢復全域 Auto。", "No vendor data available": "暫無廠商數據", + "No verification method is available for this action.": "此操作沒有可用的驗證方式。", "No X Found": "未找到 X", "Node": "節點", "Node filters": "節點篩選", @@ -3262,6 +3277,8 @@ "Number of top log probabilities returned per token": "每個 token 返回的 top 概率數量", "Number of users invited": "已邀請的用戶數量", "OAuth": "OAuth", + "OAuth authorization timed out. Please try again.": "OAuth 授權已逾時,請重試。", + "OAuth authorization was cancelled.": "OAuth 授權已取消。", "OAuth binding timed out. Please try again.": "OAuth 綁定逾時,請重試。", "OAuth binding window is no longer available": "OAuth 綁定視窗已無法使用", "OAuth callback URL": "OAuth 回呼 URL", @@ -3270,6 +3287,8 @@ "OAuth failed": "OAuth 失敗", "OAuth Integrations": "OAuth 整合", "OAuth pop-up was blocked": "OAuth 彈出式視窗遭瀏覽器封鎖", + "OAuth popup storage is unavailable.": "OAuth 彈出視窗儲存空間無法使用。", + "OAuth window is no longer available.": "OAuth 視窗已關閉或無法使用。", "Object Prune Rules": "物件清理規則", "Observability": "可觀測性", "Obtain the API key, merchant ID, and RSA key pair from the Waffo dashboard, and configure the callback URL.": "請在 Waffo 後台獲取 API 金鑰、商戶 ID 以及 RSA 金鑰對,並設定Callback地址。", @@ -3368,6 +3387,7 @@ "operation and charging behavior": "運營和收費行為產生的法律責任", "Operation audit": "操作稽核", "Operation Audit Info": "操作審計資訊", + "Operation cancelled": "操作已取消", "Operation failed": "操作失敗", "Operation successful": "操作成功", "Operation Type": "操作類型", @@ -3474,6 +3494,7 @@ "Passive recovery only": "僅被動恢復", "Passkey": "Passkey", "Passkey Authentication": "通行金鑰認證", + "Passkey authentication is disabled.": "Passkey 驗證已停用。", "Passkey is not available in this browser": "此瀏覽器中不支援 Passkey", "Passkey is not supported in this environment": "此環境中不支援 Passkey", "Passkey is not supported on this device": "此設備不支援 Passkey", @@ -4142,6 +4163,7 @@ "Return Error": "返回錯誤", "Return per-token log probabilities": "返回每個 token 的對數概率", "Return to dashboard": "返回儀表板", + "Return to the original window to continue.": "返回原視窗繼續操作。", "Return vector embeddings for inputs": "為輸入返回向量嵌入", "Reveal API key": "顯示 API 金鑰", "Reveal key": "顯示金鑰", @@ -4309,6 +4331,8 @@ "Security & Limits": "安全與限制", "Security Check": "安全驗證", "Security verification": "安全驗證", + "Security verification has expired. Please verify again.": "安全驗證已過期,請重新驗證。", + "Security verification is no longer valid. Please verify again.": "安全驗證已失效,請重新驗證。", "Seed": "隨機種子", "Select": "選擇", "Select a color": "選擇顏色", @@ -4452,6 +4476,7 @@ "Settings": "設定", "Settings & Preferences": "設定與偏好", "Settings updated successfully": "設定更新成功", + "Setup expired. Scan the new QR code and save the new backup codes.": "設定已過期,請掃描新的 QR 碼並儲存新的備用碼。", "Setup guide": "設定引導", "Setup guide complete": "設定引導已完成", "Setup guide is collapsed. Expand it anytime.": "設定引導已收起,可隨時展開。", @@ -4783,6 +4808,7 @@ "Text or array of texts to embed": "需要向量化的文字或文字陣列", "Text Output": "文字輸出", "Text to Video": "文生影片", + "The action details are invalid.": "操作資訊無效。", "The admin configured three groups and one special ratio rule:": "管理員設定了三個分組和一條特殊倍率規則:", "The admin wants vip users to pay even less when they use premium. That needs an override rule: in the override matrix, set the cell at row vip, column premium to 0.3.": "管理員希望 vip 用戶使用 premium 時價格更低。這就需要一條覆蓋規則:在覆蓋矩陣中,把「行 vip、列 premium」的單元格填成 0.3。", "The administrator account is already initialized. You can keep your existing credentials and continue to the next step.": "管理員用戶已初始化。您可以保留現有憑證並繼續下一步。", @@ -4791,6 +4817,7 @@ "The administrator has not configured a user agreement yet.": "管理員尚未設定用戶協議。", "The administrator has not configured any about content yet. You can set it in the settings page, supporting HTML or URL.": "管理員尚未設定任何關於內容。您可以在設定頁面中進行設定,支援 HTML 或 URL。", "The API key used for the requests": "請求所使用的 API 金鑰", + "The authenticator code is incorrect.": "驗證器驗證碼錯誤。", "The binding will complete automatically after authorization": "授權後連結將自動完成", "The bound Product powers wallet top-ups: when a user enters any amount, new-api runs the checkout against this single Pancake product and overrides the price per session — no need to pre-create $1 / $5 / $10 SKUs.": "已連結產品用於錢包儲值:當用戶輸入任意金額時,new-api 會基於這個單一 Pancake 產品發起結帳,並按對話覆蓋價格,無需預先建立 $1 / $5 / $10 的 SKU。", "The bound Store is the parent container for every Pancake product new-api creates from this admin — both the wallet top-up product and any subscription-plan products. One store is enough; pin a different one only if you genuinely run separate Pancake catalogs.": "已連結店鋪是 new-api 從此管理端建立的所有 Pancake 產品的父容器,包括錢包儲值產品和訂閱套餐產品。一個店鋪通常足夠;只有在確實運營多個 Pancake 目錄時才需要連結不同店鋪。", @@ -4810,6 +4837,7 @@ "The model you're looking for doesn't exist.": "您查找的模型不存在。", "The name displayed across the application": "在整個套用程式中顯示的名稱", "The new token will only be shown once. Copy it and store it securely.": "新令牌僅顯示一次。請複製並妥善保存。", + "The OAuth account does not match the account linked to your profile.": "此 OAuth 帳號與已綁定的帳號不一致。", "The public URL of your server, used for OAuth callbacks, webhooks, and other external integrations": "伺服器的公開URL,用於OAuthCallback、Webhook和其他外部整合", "The requested chat preset does not exist or has been removed.": "請求的聊天預設不存在或已被刪除。", "The reset request stays disabled until a credit is available.": "沒有可用次數時,重置請求會保持停用。", @@ -4821,6 +4849,7 @@ "The token group that will have a custom ratio": "將具有自訂比例的令牌分組", "The token has no group, so it is billed as the user group vip, using the base ratio of vip.": "令牌未設定分組,因此按用戶分組 vip 收費,使用 vip 的基礎倍率。", "The two roles of a group": "分組的兩種角色", + "The two-factor setup has expired or changed. Start setup again.": "兩步驗證設定已過期或變更,請重新設定。", "The unique identifier for this model": "此模型的唯一標識符", "The unique name for this vendor": "此供應商的唯一名稱", "The upstream channel that served the requests": "處理請求的上游渠道", @@ -4904,6 +4933,10 @@ "This user account no longer exists.": "此使用者帳號已不存在。", "this user group": "此用戶分組", "This user has no bindings": "該用戶無任何連結", + "This verification has already been used. Please verify again.": "此驗證憑證已使用,請重新驗證。", + "This verification method is currently unavailable.": "此驗證方式目前無法使用。", + "This verification method is not allowed for this action.": "此操作不允許使用該驗證方式。", + "This verification method requires its dedicated verification flow.": "此驗證方式需要透過專用驗證流程完成。", "This week": "本週", "This will append 2 template rules (Codex CLI and Claude CLI) to the existing rule list.": "這將在現有規則列表中追加 2 條模板規則(Codex CLI 和 Claude CLI)。", "This will clear custom pricing ratios and revert to upstream defaults.": "這將清除自訂定價比例並恢復到上游預設值。", @@ -5107,6 +5140,9 @@ "Two-Factor Authentication": "兩步驗證", "Two-factor authentication disabled": "兩因素認證已停用", "Two-factor authentication enabled successfully!": "兩步驗證已成功啟用!", + "Two-factor authentication is already enabled.": "兩步驗證已啟用。", + "Two-factor authentication is not enabled.": "兩步驗證尚未啟用。", + "Two-factor authentication is temporarily locked.": "兩步驗證已暫時鎖定。", "Two-factor authentication reset": "兩因素認證已重設", "Two-Step Verification": "兩步驗證", "Type": "類型", @@ -5125,6 +5161,7 @@ "Unable to load rankings": "無法載入排行榜", "Unable to load rankings data": "無法載入排行榜數據", "Unable to open chat": "無法打開聊天", + "Unable to parse Passkey login options from response": "無法解析回應中的 Passkey 登入選項", "Unable to parse structured pricing": "無法解析為結構化價格", "Unable to prepare chat link. Please ensure you have an enabled API key.": "無法準備聊天連結。請確保您有一個已啟用的 API 金鑰。", "Unable to read clipboard": "無法讀取剪貼簿", @@ -5387,20 +5424,25 @@ "Verification code must be 6 digits": "驗證碼必須是 6 位數字", "Verification code sent! Please check your email.": "驗證碼已發送!請檢查您的電郵。", "Verification code updates every 30 seconds.": "驗證碼每 30 秒更新一次。", + "Verification does not match this action.": "驗證與此操作不相符。", + "Verification does not match this action's details. Please verify again.": "驗證與本次操作的詳細內容不符,請重新驗證。", "Verification email sent": "驗證郵件已發送", "Verification failed": "驗證失敗", + "Verification failed. Please try again.": "驗證失敗,請重試。", "Verification flow expired": "驗證流程已過期", "Verification is not configured properly": "驗證未正確設定", "Verification proof was not returned": "伺服器未傳回驗證憑證", "Verification required to reveal the saved key.": "需要驗證才能顯示已儲存的金鑰。", "Verification scope is missing": "缺少驗證範圍", "Verify": "驗證", + "Verify again before retrying this action.": "重試此操作前,請重新驗證。", "Verify and Sign In": "驗證並登入", "Verify routing with Playground or your client": "使用 Playground 或你的用戶端驗證路由", "Verify Setup": "驗證設定", "Verify to view channel key": "驗證後查看渠道金鑰", "Verify your database connection": "驗證資料庫連接", "Verifying credentials and pulling stores from your Pancake account...": "正在驗證憑證並從你的 Pancake 用戶拉取店鋪...", + "Verifying your {{provider}} account": "正在驗證 {{provider}} 帳號", "Version": "版本", "Version history": "版本历史", "Version Overrides": "版本覆蓋", @@ -5572,6 +5614,7 @@ "You commit not to use this system to implement, assist with, or indirectly implement acts that violate applicable laws and regulations, regulatory requirements, platform rules, public interests, or the lawful rights and interests of third parties.": "你承諾不會使用本系統實施、協助實施或間接實施違反適用法律法規、監管要求、平台規則、公共利益或第三方合法權益的行為。", "You commit to using upstream APIs, accounts, keys, quotas, and service capabilities only within the scope of lawful authorization obtained from upstream service providers, model service providers, or relevant rights holders, and will not conduct unauthorized resale, trafficking, distribution, or other non-compliant commercialization.": "你承諾僅在從上游服務供應商、模型服務供應商或相關權利人處獲得合法授權的範圍內使用上游 API、用戶、金鑰、額度和服務能力,並不會進行未經授權的轉售、倒賣、分發或其他不合規商業化行為。", "You do not have permission to edit sensitive channel settings.": "你沒有權限編輯敏感渠道設定。", + "You do not have permission to perform this action.": "你沒有執行此操作的權限。", "You don't have necessary permission": "您沒有必要的權限", "You have legally obtained authorization for the connected model APIs, accounts, keys, and quotas.": "你已合法取得所連接模型 API、用戶、金鑰和額度的授權。", "You have unsaved changes": "您有未儲存的變更", diff --git a/web/src/i18n/locales/zh.json b/web/src/i18n/locales/zh.json index c2693360ed..257440fd6b 100644 --- a/web/src/i18n/locales/zh.json +++ b/web/src/i18n/locales/zh.json @@ -128,6 +128,7 @@ "80,443,8080": "80,443,8080", "A billing multiplier. Lower ratios mean lower API call costs.": "计费乘数,倍率越低,API 调用费用越低。", "A focused home for keys, balance, routing, and service health.": "集中展示密钥、余额、路由和服务健康状态。", + "A security operation is already in progress.": "已有安全操作正在进行。", "About": "关于", "About {{days}} days left": "约剩 {{days}} 天", "Accept Unpriced Models": "接受未定价模型", @@ -243,6 +244,7 @@ "Add user group": "添加用户分组", "Add your API keys, set up channels and configure access permissions": "添加 API 密钥,设置渠道并配置访问权限", "Added {{count}} model(s)": "已添加 {{count}} 个模型", + "Added {{count}} models from \"{{name}}\"": "已从“{{name}}”添加 {{count}} 个模型", "Added successfully": "新增成功", "Additional Conditions": "附加条件", "Additional information": "附加信息", @@ -250,6 +252,7 @@ "Additional Limit": "附加额度", "Additional Limits": "附加额度", "Additional metered capability": "附加计费能力", + "Additional verification required": "需要进一步验证", "Adjust filters, then search to refresh the logs.": "调整筛选条件,然后搜索以刷新日志。", "Adjust Quota": "调整额度", "Adjust response formatting, prompt behavior, proxy, and upstream automation.": "调整响应格式、提示词行为、代理和上游自动化。", @@ -536,6 +539,7 @@ "Authentication": "身份验证", "Authentication Method": "认证方式", "Authenticator code": "身份验证器代码", + "Authenticator code or backup code": "认证器验证码或备用码", "Authorization callback URL": "授权回调 URL", "Authorization Endpoint": "授权端点", "Authorization Endpoint (Optional)": "授权端点(可选)", @@ -814,6 +818,7 @@ "Channel health checks": "渠道健康检查", "Channel ID": "渠道 ID", "Channel ID is required": "缺少渠道 ID", + "Channel is not selected": "尚未选择渠道", "Channel key": "渠道密钥", "Channel key unlocked": "渠道密钥已解锁", "Channel Management": "渠道管理", @@ -1088,10 +1093,12 @@ "confirm that I bear legal responsibility arising from deployment": "确认承担因部署", "Confirm Unbind": "确认解绑", "Confirm usage reset": "确认重置用量", + "Confirm your identity before accessing this sensitive action.": "执行此敏感操作前,请先验证身份。", "Confirm your identity before removing this Passkey from your account.": "在解绑当前账号的 Passkey 前请确认你的身份。", "Confirm your identity with Two-factor Authentication before registering a Passkey.": "在注册 Passkey 前请使用两步验证确认你的身份。", "Confirmed at {{time}} by user #{{userId}}": "用户 #{{userId}} 于 {{time}} 确认", "Confirmed payment compliance": "确认支付合规", + "Confirming the account linked to your profile.": "正在确认已绑定的账号。", "Conflict": "矛盾", "Connect": "连接", "Connect through OpenAI, Claude, Gemini, and other compatible API routes": "通过 OpenAI、Claude、Gemini 以及其他兼容 API 路由接入", @@ -1121,6 +1128,7 @@ "Context": "上下文", "Continue": "继续", "Continue with {{name}}": "使用 {{name}} 继续", + "Continue with an account already linked to your profile.": "使用已绑定的账号继续验证。", "Continue with Discord": "使用 Discord 继续", "Continue with GitHub": "使用 GitHub 继续", "Continue with LinuxDO": "使用 LinuxDO 继续", @@ -1792,6 +1800,7 @@ "Enter secret key": "输入密钥", "Enter system prompt (user prompt takes priority)": "输入系统提示词(用户提示词优先)", "Enter tag name (optional)": "输入标签名称(可选)", + "Enter the 6-digit authenticator code or an unused backup code.": "输入认证器的 6 位验证码或未使用的备用码。", "Enter the 6-digit code from your authenticator app": "输入来自身份验证器应用的 6 位代码", "Enter the 6-digit Time-based One-Time Password or 8-character backup code from your authenticator app.": "输入来自身份验证器应用的 6 位基于时间的单次密码或 8 位备份代码。", "Enter the complete URL, supports": "输入完整的 URL,支持", @@ -2510,6 +2519,7 @@ "Invalid chat link. Please contact the administrator.": "无效的聊天链接。请联系管理员。", "Invalid chat link. Please contact your administrator.": "无效的聊天链接。请联系您的管理员。", "Invalid code": "无效代码", + "Invalid items format": "条目格式无效", "Invalid JSON": "JSON 无效", "Invalid JSON format": "无效的 JSON 格式", "Invalid JSON format or values out of allowed range": "无效的 JSON 格式或值超出允许范围", @@ -2666,6 +2676,7 @@ "Limits token selection to a probability mass": "按概率质量限制词元选择范围", "LingYiWanWu": "LingYiWanWu", "Link to your documentation site": "您的文档站点链接", + "Linked account": "已绑定账号", "LinuxDO": "LinuxDO", "LinuxDO Client ID": "LinuxDO 客户端 ID", "LinuxDO Client Secret": "LinuxDO 客户端密钥", @@ -2690,6 +2701,7 @@ "Loading maintenance settings...": "正在加载维护设置...", "Loading settings...": "正在加载设置...", "Loading setup status…": "正在加载设置状态…", + "Loading verification methods...": "正在加载验证方式…", "Loading...": "加载中...", "Local": "本地", "Local Billing": "本地计费", @@ -3115,6 +3127,7 @@ "No Inviter": "无邀请人", "No keys found": "未找到密钥", "No latency data available": "暂无延迟数据", + "No linked OAuth provider is available.": "没有可用的已绑定 OAuth 提供方。", "No log entries matched the selected time.": "没有日志条目匹配所选时间。", "No logs": "暂无日志", "No Logs Found": "未找到日志", @@ -3154,6 +3167,7 @@ "No notable climbers right now": "当前没有显著上升的模型", "No notable drops right now": "当前没有显著下降的模型", "No parameter overrides configured.": "未配置参数覆盖。", + "No Passkey is registered.": "尚未注册 Passkey。", "No payment methods available. Please contact administrator.": "没有可用的支付方式。请联系管理员。", "No payment methods configured": "暂无支付方式", "No payment methods configured. Click \"Add method\" or use templates to get started.": "未配置支付方式。点击\"添加方式\"或使用模板开始。", @@ -3214,6 +3228,7 @@ "No Users Found": "未找到用户", "No valid custom Auto groups remain. Add a group or restore global Auto.": "没有可用的自定义 Auto 分组。请添加分组或恢复全局 Auto。", "No vendor data available": "暂无厂商数据", + "No verification method is available for this action.": "此操作没有可用的验证方式。", "No X Found": "未找到 X", "Node": "节点", "Node filters": "节点筛选", @@ -3262,6 +3277,8 @@ "Number of top log probabilities returned per token": "每个 token 返回的 top 概率数量", "Number of users invited": "已邀请的用户数量", "OAuth": "OAuth", + "OAuth authorization timed out. Please try again.": "OAuth 授权已超时,请重试。", + "OAuth authorization was cancelled.": "OAuth 授权已取消。", "OAuth binding timed out. Please try again.": "OAuth 绑定超时,请重试。", "OAuth binding window is no longer available": "OAuth 绑定窗口已不可用", "OAuth callback URL": "OAuth 回调 URL", @@ -3270,6 +3287,8 @@ "OAuth failed": "OAuth 失败", "OAuth Integrations": "OAuth 集成", "OAuth pop-up was blocked": "OAuth 弹窗被浏览器拦截", + "OAuth popup storage is unavailable.": "OAuth 弹窗存储不可用。", + "OAuth window is no longer available.": "OAuth 窗口已关闭或不可用。", "Object Prune Rules": "对象清理规则", "Observability": "可观测性", "Obtain the API key, merchant ID, and RSA key pair from the Waffo dashboard, and configure the callback URL.": "请在 Waffo 后台获取 API 密钥、商户 ID 以及 RSA 密钥对,并配置回调地址。", @@ -3368,6 +3387,7 @@ "operation and charging behavior": "运营和收费行为产生的法律责任", "Operation audit": "操作审计", "Operation Audit Info": "操作审计信息", + "Operation cancelled": "操作已取消", "Operation failed": "操作失败", "Operation successful": "操作成功", "Operation Type": "操作类型", @@ -3474,6 +3494,7 @@ "Passive recovery only": "仅被动恢复", "Passkey": "Passkey", "Passkey Authentication": "通行密钥认证", + "Passkey authentication is disabled.": "Passkey 认证已关闭。", "Passkey is not available in this browser": "此浏览器中不支持 Passkey", "Passkey is not supported in this environment": "此环境中不支持 Passkey", "Passkey is not supported on this device": "此设备不支持 Passkey", @@ -4142,6 +4163,7 @@ "Return Error": "返回错误", "Return per-token log probabilities": "返回每个 token 的对数概率", "Return to dashboard": "返回仪表盘", + "Return to the original window to continue.": "返回原窗口继续操作。", "Return vector embeddings for inputs": "为输入返回向量嵌入", "Reveal API key": "显示 API 密钥", "Reveal key": "显示密钥", @@ -4309,6 +4331,8 @@ "Security & Limits": "安全与限制", "Security Check": "安全验证", "Security verification": "安全验证", + "Security verification has expired. Please verify again.": "安全验证已过期,请重新验证。", + "Security verification is no longer valid. Please verify again.": "安全验证已失效,请重新验证。", "Seed": "随机种子", "Select": "选择", "Select a color": "选择颜色", @@ -4452,6 +4476,7 @@ "Settings": "设置", "Settings & Preferences": "设置与偏好", "Settings updated successfully": "设置更新成功", + "Setup expired. Scan the new QR code and save the new backup codes.": "设置已过期,请扫描新的二维码并保存新的备用码。", "Setup guide": "设置引导", "Setup guide complete": "设置引导已完成", "Setup guide is collapsed. Expand it anytime.": "设置引导已收起,可随时展开。", @@ -4783,6 +4808,7 @@ "Text or array of texts to embed": "需要向量化的文本或文本数组", "Text Output": "文字输出", "Text to Video": "文生视频", + "The action details are invalid.": "操作信息无效。", "The admin configured three groups and one special ratio rule:": "管理员配置了三个分组和一条特殊倍率规则:", "The admin wants vip users to pay even less when they use premium. That needs an override rule: in the override matrix, set the cell at row vip, column premium to 0.3.": "管理员希望 vip 用户使用 premium 时价格更低。这就需要一条覆盖规则:在覆盖矩阵中,把「行 vip、列 premium」的单元格填成 0.3。", "The administrator account is already initialized. You can keep your existing credentials and continue to the next step.": "管理员账户已初始化。您可以保留现有凭据并继续下一步。", @@ -4791,6 +4817,7 @@ "The administrator has not configured a user agreement yet.": "管理员尚未配置用户协议。", "The administrator has not configured any about content yet. You can set it in the settings page, supporting HTML or URL.": "管理员尚未配置任何关于内容。您可以在设置页面中进行设置,支持 HTML 或 URL。", "The API key used for the requests": "请求所使用的 API 密钥", + "The authenticator code is incorrect.": "认证器验证码错误。", "The binding will complete automatically after authorization": "授权后绑定将自动完成", "The bound Product powers wallet top-ups: when a user enters any amount, new-api runs the checkout against this single Pancake product and overrides the price per session — no need to pre-create $1 / $5 / $10 SKUs.": "已绑定产品用于钱包充值:当用户输入任意金额时,new-api 会基于这个单一 Pancake 产品发起结账,并按会话覆盖价格,无需预先创建 $1 / $5 / $10 的 SKU。", "The bound Store is the parent container for every Pancake product new-api creates from this admin — both the wallet top-up product and any subscription-plan products. One store is enough; pin a different one only if you genuinely run separate Pancake catalogs.": "已绑定店铺是 new-api 从此管理端创建的所有 Pancake 产品的父容器,包括钱包充值产品和订阅套餐产品。一个店铺通常足够;只有在确实运营多个 Pancake 目录时才需要绑定不同店铺。", @@ -4810,6 +4837,7 @@ "The model you're looking for doesn't exist.": "您查找的模型不存在。", "The name displayed across the application": "在整个应用程序中显示的名称", "The new token will only be shown once. Copy it and store it securely.": "新令牌仅显示一次。请复制并妥善保存。", + "The OAuth account does not match the account linked to your profile.": "此 OAuth 账号与已绑定的账号不一致。", "The public URL of your server, used for OAuth callbacks, webhooks, and other external integrations": "服务器的公开URL,用于OAuth回调、Webhook和其他外部集成", "The requested chat preset does not exist or has been removed.": "请求的聊天预设不存在或已被删除。", "The reset request stays disabled until a credit is available.": "没有可用次数时,重置请求会保持禁用。", @@ -4821,6 +4849,7 @@ "The token group that will have a custom ratio": "将具有自定义比例的令牌分组", "The token has no group, so it is billed as the user group vip, using the base ratio of vip.": "令牌未设置分组,因此按用户分组 vip 计费,使用 vip 的基础倍率。", "The two roles of a group": "分组的两种角色", + "The two-factor setup has expired or changed. Start setup again.": "两步验证设置已过期或变更,请重新设置。", "The unique identifier for this model": "此模型的唯一标识符", "The unique name for this vendor": "此供应商的唯一名称", "The upstream channel that served the requests": "处理请求的上游渠道", @@ -4904,6 +4933,10 @@ "This user account no longer exists.": "此用户账户已不存在。", "this user group": "此用户分组", "This user has no bindings": "该用户无任何绑定", + "This verification has already been used. Please verify again.": "此验证凭证已使用,请重新验证。", + "This verification method is currently unavailable.": "此验证方式当前不可用。", + "This verification method is not allowed for this action.": "此操作不允许使用该验证方式。", + "This verification method requires its dedicated verification flow.": "此验证方式需要通过专用验证流程完成。", "This week": "本周", "This will append 2 template rules (Codex CLI and Claude CLI) to the existing rule list.": "这将在现有规则列表中追加 2 条模板规则(Codex CLI 和 Claude CLI)。", "This will clear custom pricing ratios and revert to upstream defaults.": "这将清除自定义定价比例并恢复到上游默认值。", @@ -5107,6 +5140,9 @@ "Two-Factor Authentication": "两步验证", "Two-factor authentication disabled": "两因素认证已禁用", "Two-factor authentication enabled successfully!": "两步验证已成功启用!", + "Two-factor authentication is already enabled.": "两步验证已启用。", + "Two-factor authentication is not enabled.": "两步验证尚未启用。", + "Two-factor authentication is temporarily locked.": "两步验证已暂时锁定。", "Two-factor authentication reset": "两因素认证已重置", "Two-Step Verification": "两步验证", "Type": "类型", @@ -5125,6 +5161,7 @@ "Unable to load rankings": "无法加载排行榜", "Unable to load rankings data": "无法加载排行榜数据", "Unable to open chat": "无法打开聊天", + "Unable to parse Passkey login options from response": "无法解析响应中的 Passkey 登录选项", "Unable to parse structured pricing": "无法解析为结构化价格", "Unable to prepare chat link. Please ensure you have an enabled API key.": "无法准备聊天链接。请确保您有一个已启用的 API 密钥。", "Unable to read clipboard": "无法读取剪贴板", @@ -5387,20 +5424,25 @@ "Verification code must be 6 digits": "验证码必须是 6 位数字", "Verification code sent! Please check your email.": "验证码已发送!请检查您的电子邮件。", "Verification code updates every 30 seconds.": "验证码每 30 秒更新一次。", + "Verification does not match this action.": "验证与此操作不匹配。", + "Verification does not match this action's details. Please verify again.": "验证与本次操作的具体内容不匹配,请重新验证。", "Verification email sent": "验证邮件已发送", "Verification failed": "验证失败", + "Verification failed. Please try again.": "验证失败,请重试。", "Verification flow expired": "验证流程已过期", "Verification is not configured properly": "验证未正确配置", "Verification proof was not returned": "服务端未返回验证凭证", "Verification required to reveal the saved key.": "需要验证才能显示已保存的密钥。", "Verification scope is missing": "缺少验证范围", "Verify": "验证", + "Verify again before retrying this action.": "重试此操作前,请重新验证。", "Verify and Sign In": "验证并登录", "Verify routing with Playground or your client": "使用 Playground 或你的客户端验证路由", "Verify Setup": "验证设置", "Verify to view channel key": "验证后查看渠道密钥", "Verify your database connection": "验证数据库连接", "Verifying credentials and pulling stores from your Pancake account...": "正在验证凭证并从你的 Pancake 账户拉取店铺...", + "Verifying your {{provider}} account": "正在验证 {{provider}} 账号", "Version": "版本", "Version history": "版本历史", "Version Overrides": "版本覆盖", @@ -5572,6 +5614,7 @@ "You commit not to use this system to implement, assist with, or indirectly implement acts that violate applicable laws and regulations, regulatory requirements, platform rules, public interests, or the lawful rights and interests of third parties.": "你承诺不会使用本系统实施、协助实施或间接实施违反适用法律法规、监管要求、平台规则、公共利益或第三方合法权益的行为。", "You commit to using upstream APIs, accounts, keys, quotas, and service capabilities only within the scope of lawful authorization obtained from upstream service providers, model service providers, or relevant rights holders, and will not conduct unauthorized resale, trafficking, distribution, or other non-compliant commercialization.": "你承诺仅在从上游服务提供商、模型服务提供商或相关权利人处获得合法授权的范围内使用上游 API、账户、密钥、额度和服务能力,并不会进行未经授权的转售、倒卖、分发或其他不合规商业化行为。", "You do not have permission to edit sensitive channel settings.": "你没有权限编辑敏感渠道设置。", + "You do not have permission to perform this action.": "你没有执行此操作的权限。", "You don't have necessary permission": "您没有必要的权限", "You have legally obtained authorization for the connected model APIs, accounts, keys, and quotas.": "你已合法取得所连接模型 API、账户、密钥和额度的授权。", "You have unsaved changes": "您有未保存的更改", diff --git a/web/src/i18n/static-keys.ts b/web/src/i18n/static-keys.ts index ce495676b1..c444645abc 100644 --- a/web/src/i18n/static-keys.ts +++ b/web/src/i18n/static-keys.ts @@ -579,4 +579,8 @@ export const STATIC_I18N_KEYS = [ 'This user account is disabled.', 'Telegram binding failed. Please try again.', 'Verification scope is missing', + 'This verification has already been used. Please verify again.', + "Verification does not match this action's details. Please verify again.", + 'The action details are invalid.', + 'You do not have permission to perform this action.', ] as const diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 81d0c69100..790e0eb5f4 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -93,25 +93,6 @@ export async function getNotice(): Promise<{ // 2FA Management APIs // ============================================================================ -export async function get2FAStatus() { - const res = await api.get('/api/user/2fa/status') - return res.data -} - -export async function setup2FA() { - const res = await api.post('/api/user/2fa/setup') - return res.data -} - -export async function enable2FA(code: string) { - const res = await api.post( - '/api/user/2fa/enable', - { code }, - { acceptAuthRotation: true } - ) - return res.data -} - export async function disable2FA(code: string) { const res = await api.post( '/api/user/2fa/disable', diff --git a/web/src/lib/http-client.ts b/web/src/lib/http-client.ts index f75e95df75..d25144f2b6 100644 --- a/web/src/lib/http-client.ts +++ b/web/src/lib/http-client.ts @@ -23,6 +23,7 @@ import { toast } from 'sonner' import { applyAuthRotation, clearAuthentication, + getFreshAuthHeaders, refreshAuthentication, } from '@/lib/auth-session' import { getServerErrorMessageKey } from '@/lib/server-error-message' @@ -36,6 +37,7 @@ declare module 'axios' { skipAuthRefresh?: boolean authRetry?: boolean acceptAuthRotation?: boolean + singleUseAuthorization?: boolean } } @@ -142,7 +144,20 @@ api.interceptors.response.use( } ) -api.interceptors.request.use((config) => { +api.interceptors.request.use(async (config) => { + if (config.singleUseAuthorization || config.headers.has('X-Security-Proof')) { + // Refresh before spending a proof/flow, never by replaying its request. + config.skipAuthRefresh = true + try { + const headers = await getFreshAuthHeaders() + for (const [name, value] of Object.entries(headers)) { + config.headers.set(name, value) + } + } catch (error) { + throw axios.AxiosError.from(error, undefined, config) + } + return config + } const accessToken = useAuthStore.getState().auth.accessToken if (accessToken) { config.headers.Authorization = `Bearer ${accessToken}` diff --git a/web/src/lib/oauth.ts b/web/src/lib/oauth.ts index d5f0394214..5c4066eb0e 100644 --- a/web/src/lib/oauth.ts +++ b/web/src/lib/oauth.ts @@ -16,6 +16,8 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ +import type { SystemStatus } from '@/features/auth/types' + // ============================================================================ // OAuth URL Builders // ============================================================================ @@ -80,3 +82,54 @@ export function buildOIDCOAuthUrl( export function buildLinuxDOOAuthUrl(clientId: string, state: string): string { return `https://connect.linux.do/oauth2/authorize?response_type=code&client_id=${clientId}&state=${state}` } + +export function buildOAuthAuthorizationUrl( + provider: string, + state: string, + status: SystemStatus +): string { + switch (provider) { + case 'github': + if (status.github_client_id) { + return buildGitHubOAuthUrl(status.github_client_id, state) + } + break + case 'discord': + if (status.discord_client_id) { + return buildDiscordOAuthUrl(status.discord_client_id, state) + } + break + case 'oidc': + if (status.oidc_authorization_endpoint && status.oidc_client_id) { + return buildOIDCOAuthUrl( + status.oidc_authorization_endpoint, + status.oidc_client_id, + state + ) + } + break + case 'linuxdo': + if (status.linuxdo_client_id) { + return buildLinuxDOOAuthUrl(status.linuxdo_client_id, state) + } + break + default: { + const custom = status.custom_oauth_providers?.find( + (candidate) => candidate.slug === provider + ) + if (custom) { + const url = new URL(custom.authorization_endpoint) + url.searchParams.set('client_id', custom.client_id) + url.searchParams.set( + 'redirect_uri', + `${window.location.origin}/oauth/${provider}` + ) + url.searchParams.set('response_type', 'code') + url.searchParams.set('state', state) + if (custom.scopes) url.searchParams.set('scope', custom.scopes) + return url.toString() + } + } + } + throw new Error('No linked OAuth provider is available.') +} diff --git a/web/src/lib/passkey.ts b/web/src/lib/passkey.ts index fed9ed8a6c..9a8aaeb45c 100644 --- a/web/src/lib/passkey.ts +++ b/web/src/lib/passkey.ts @@ -36,7 +36,7 @@ export function base64UrlToArrayBuffer(value?: string | null): ArrayBuffer { if (!value) return new ArrayBuffer(0) const padding = '='.repeat((4 - (value.length % 4)) % 4) - const base64 = (value + padding).replace(/-/g, '+').replace(/_/g, '/') + const base64 = (value + padding).replaceAll('-', '+').replaceAll('_', '/') const globalRef = globalThis as typeof globalThis & { Buffer?: NodeBufferCtor @@ -96,9 +96,9 @@ export function arrayBufferToBase64Url( } return encode(binary) - .replace(/\+/g, '-') - .replace(/\//g, '_') - .replace(/=+$/g, '') + .replaceAll('+', '-') + .replaceAll('/', '_') + .replaceAll(/=+$/g, '') } /** @@ -274,9 +274,10 @@ export async function isPasskeySupported(): Promise { * Execute an async Passkey credential creation flow. */ export async function createCredential( - options: PublicKeyCredentialCreationOptions + options: PublicKeyCredentialCreationOptions, + signal?: AbortSignal ) { - return navigator.credentials.create({ publicKey: options }) + return navigator.credentials.create({ publicKey: options, signal }) } /** diff --git a/web/src/lib/secure-verification.ts b/web/src/lib/secure-verification.ts index 84439cb910..9b28c3404a 100644 --- a/web/src/lib/secure-verification.ts +++ b/web/src/lib/secure-verification.ts @@ -16,56 +16,68 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ -import type { AxiosError } from 'axios' +import axios from 'axios' -export interface VerificationRequiredInfo { - code?: string - message: string - required: boolean -} +import { getServerErrorMessageKey } from './server-error-message' -/** - * Determine whether an Axios error indicates secure verification is required. - */ -export function isVerificationRequiredError( - error: unknown -): error is AxiosError { - if (!error || typeof error !== 'object') return false - const axiosError = error as AxiosError<{ code?: string }> - const status = axiosError.response?.status - if (status !== 403) return false +export class AuthOperationError extends Error { + constructor( + message: string, + readonly code?: string, + options?: ErrorOptions + ) { + super(message, options) + this.name = 'AuthOperationError' + } - const code = axiosError.response?.data?.code - if (!code) return false - - const verificationCodes = new Set([ - 'VERIFICATION_REQUIRED', - 'VERIFICATION_EXPIRED', - 'VERIFICATION_INVALID', - 'SECURITY_PROOF_REQUIRED', - 'SECURITY_PROOF_EXPIRED', - 'SECURITY_PROOF_INVALID', - 'SECURITY_PROOF_SCOPE_MISMATCH', - 'SECURITY_PROOF_METHOD_MISMATCH', - ]) + static from( + error: unknown, + fallback = 'Verification failed. Please try again.' + ): AuthOperationError { + if (error instanceof AuthOperationError) return error + if (axios.isAxiosError<{ message?: string; code?: string }>(error)) { + return new AuthOperationError( + getServerErrorMessageKey(error) || + (error.response && error.response.status >= 500 + ? 'Please try again later.' + : undefined) || + error.response?.data?.message || + error.message || + fallback, + error.response?.data?.code, + { cause: error } + ) + } + return new AuthOperationError( + error instanceof Error ? error.message : fallback, + undefined, + { cause: error } + ) + } +} - return verificationCodes.has(code) +export const authRequestOptions = { + skipBusinessError: true, + skipErrorHandler: true, } - -/** - * Extract verification requirement info from an Axios error. - */ -export function extractVerificationInfo( - error: unknown -): VerificationRequiredInfo { - const axiosError = error as AxiosError<{ code?: string; message?: string }> - const code = axiosError.response?.data?.code - const message = - axiosError.response?.data?.message ?? 'Secure verification is required' - return { - code, - message, - required: true, +export async function authResult( + request: Promise<{ + data: { success: boolean; message?: string; code?: string; data?: T } + }> +): Promise { + try { + const { data: response } = await request + if (!response.success || response.data === undefined) { + throw new AuthOperationError( + getServerErrorMessageKey(response) || + response.message || + 'Verification failed. Please try again.', + response.code + ) + } + return response.data + } catch (error) { + throw AuthOperationError.from(error) } } diff --git a/web/src/lib/server-error-message.ts b/web/src/lib/server-error-message.ts index 04b9394fa2..662df0a1d0 100644 --- a/web/src/lib/server-error-message.ts +++ b/web/src/lib/server-error-message.ts @@ -17,6 +17,39 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ const serverErrorMessageKeys = { + AUTH_INTERNAL_ERROR: 'Please try again later.', + SECURITY_VERIFICATION_FAILED: 'Verification failed. Please try again.', + SECURITY_VERIFICATION_FLOW_REQUIRED: + 'This verification method requires its dedicated verification flow.', + SECURITY_VERIFICATION_LOCKED: + 'Two-factor authentication is temporarily locked.', + OAUTH_ACCOUNT_MISMATCH: + 'The OAuth account does not match the account linked to your profile.', + TWOFA_CODE_INVALID: 'The authenticator code is incorrect.', + TWOFA_ALREADY_ENABLED: 'Two-factor authentication is already enabled.', + TWOFA_NOT_ENABLED: 'Two-factor authentication is not enabled.', + PASSKEY_NOT_FOUND: 'No Passkey is registered.', + AUTH_FLOW_INVALID: 'Verification flow expired', + SECURITY_PROOF_REQUIRED: 'Additional verification required', + SECURITY_PROOF_EXPIRED: + 'Security verification has expired. Please verify again.', + SECURITY_PROOF_INVALID: + 'Security verification is no longer valid. Please verify again.', + SECURITY_PROOF_SCOPE_MISMATCH: 'Verification does not match this action.', + SECURITY_PROOF_CONSUMED: + 'This verification has already been used. Please verify again.', + SECURITY_PROOF_CONTEXT_MISMATCH: + "Verification does not match this action's details. Please verify again.", + SECURITY_CONTEXT_INVALID: 'The action details are invalid.', + SECURITY_ACTION_FORBIDDEN: + 'You do not have permission to perform this action.', + SECURITY_PROOF_METHOD_MISMATCH: + 'This verification method is not allowed for this action.', + SECURITY_METHOD_UNAVAILABLE: + 'This verification method is currently unavailable.', + TWOFA_SETUP_INVALID: + 'The two-factor setup has expired or changed. Start setup again.', + AUTH_SESSION_LIMIT: 'Too many active login sessions. On a device where you are already signed in, open Login sessions and use “Sign out other sessions” to revoke them. If you cannot access a signed-in device, reset your password to sign out all sessions.', AUTH_SESSION_ISSUANCE_LIMIT: diff --git a/web/src/routes/oauth/$provider.tsx b/web/src/routes/oauth/$provider.tsx index cbe9c78642..660032233a 100644 --- a/web/src/routes/oauth/$provider.tsx +++ b/web/src/routes/oauth/$provider.tsx @@ -29,8 +29,8 @@ import { toast } from 'sonner' import { OAuthCallbackScreen } from '@/features/auth/components/oauth-callback-screen' import { - OAUTH_BIND_CALLBACK_MESSAGE, - OAUTH_BIND_RESULT_MESSAGE, + OAUTH_POPUP_CALLBACK_MESSAGE, + OAUTH_POPUP_RESULT_MESSAGE, } from '@/features/auth/constants' import { sanitizeAuthRedirect } from '@/features/auth/lib/auth-redirect' import { @@ -49,8 +49,9 @@ type OAuthRequestConfig = AxiosRequestConfig & { skipBusinessError?: boolean } -interface OAuthBindingResult { - type: typeof OAUTH_BIND_RESULT_MESSAGE +interface OAuthPopupResult { + intent: 'bind' | 'verify' + type: typeof OAUTH_POPUP_RESULT_MESSAGE provider: string state: string success: boolean @@ -76,7 +77,7 @@ function OAuthCallback() { const isTelegramBindCallback = provider === 'telegram' && (search.telegram_bind === 'success' || search.telegram_bind === 'error') - let mode: 'login' | 'bind' = 'login' + let mode: 'login' | 'bind' | 'verify' = 'login' if (isTelegramBindCallback) { mode = 'bind' } else if (typeof window !== 'undefined') { @@ -116,10 +117,10 @@ function OAuthCallback() { return } - if (mode === 'bind') { + if (mode === 'bind' || mode === 'verify') { const opener = window.opener if (!opener || opener.closed) { - toast.error(i18next.t('OAuth binding window is no longer available')) + toast.error(i18next.t('OAuth window is no longer available.')) return } @@ -132,10 +133,11 @@ function OAuthCallback() { ) { return } - const result = event.data as Partial | null + const result = event.data as Partial | null if ( !result || - result.type !== OAUTH_BIND_RESULT_MESSAGE || + result.type !== OAUTH_POPUP_RESULT_MESSAGE || + result.intent !== mode || result.provider !== provider || result.state !== state ) { @@ -143,7 +145,7 @@ function OAuthCallback() { } cancelResultTimeout() if (result.success) { - toast.success(i18next.t('Binding successful!')) + if (mode === 'bind') toast.success(i18next.t('Binding successful!')) window.close() return } @@ -153,12 +155,15 @@ function OAuthCallback() { window.addEventListener('message', handleBindingResult) cancelResultTimeout = startOAuthBindResponseDeadline(() => { - toast.error(i18next.t('OAuth binding timed out. Please try again.')) + toast.error( + i18next.t('OAuth authorization timed out. Please try again.') + ) delayedClose = window.setTimeout(() => window.close(), 1500) }) opener.postMessage( { - type: OAUTH_BIND_CALLBACK_MESSAGE, + type: OAUTH_POPUP_CALLBACK_MESSAGE, + intent: mode, provider, code, state,