mirror of
https://github.com/QuantumNous/new-api.git
synced 2026-12-05 08:03:01 +00:00
feat(security): harden account binding and password changes
Require scoped, single-use verification for account bindings and password operations. Bind OAuth authorization and email confirmations to the initiating session; preserve the last usable login method and audit operation outcomes. Apply Unicode-aware password length limits, Argon2id writes with bcrypt compatibility, and long-password encryption. Return has_password with the existing profile SELECT without extra queries. Reuse the existing security dialogs and add all seven locale translations. Validation: - Go: go test ./common ./model ./service ./middleware ./controller ./router -count=1 - DB: SQLite 3.50.4, MySQL 8.4.11, PostgreSQL 16.15; separate main/log databases - MySQL/PostgreSQL: TEST_SECURITY_DIALECT=<dialect> with TEST_<DIALECT>_DSN, go test ./controller -run '^(TestSecurityAccount|TestSecurityEnrollment|TestGenerateOAuthCode|TestOAuthBind|TestTelegramOAuth)' -count=1 -v - Web: relevant Vitest suites, bun run typecheck, targeted oxlint/format, bun run i18n:sync, and bun run build Roll out dual-format readers to every instance with ACCOUNT_PASSWORD_HASH_ALGORITHM=bcrypt before enabling Argon2id writes and the new UI. Rollbacks must retain Argon2id and v2 envelope readers. Relevant controls: ASVS 5.0.0 6.2.1-6.2.3, 6.2.5-6.2.9, 6.3.7, 7.4.3, 7.5.1; this change does not assert application-wide ASVS certification.
This commit is contained in:
61 files changed
+3996
-991
No files matched your search
@@ -89,6 +89,13 @@
|
||||
# SESSION_SECRET=random_string
|
||||
# 登录密码请求体 RSA-OAEP 加密;默认关闭,且不能替代 HTTPS
|
||||
# PASSWORD_LOGIN_ENCRYPTION_ENABLED=true
|
||||
|
||||
# Account password storage. For a rolling upgrade, deploy every node with bcrypt
|
||||
# first (dual-format verification), then switch all nodes to argon2id before
|
||||
# enabling long passwords. A rollback must retain Argon2id verification and
|
||||
# v2 login-password envelope support (when login encryption is enabled).
|
||||
# Existing bcrypt hashes and MFA backup codes are not rewritten.
|
||||
# ACCOUNT_PASSWORD_HASH_ALGORITHM=argon2id
|
||||
# false/未配置:本地 HTTP 模式,关闭 refresh/logout OriginGuard,且不得设置 TRUSTED_URL;兼容本地开发代理。
|
||||
# true:启用 Secure Refresh Cookie 和严格 OriginGuard,必须同时列出全部可信 HTTPS Origin。
|
||||
# SESSION_COOKIE_TRUSTED_URL 多项用英文逗号分隔;不支持通配符、路径或域名后缀匹配。
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
MinAccountPasswordLength = 8
|
||||
MaxAccountPasswordLength = 128
|
||||
accountPasswordMemory = 19 * 1024
|
||||
accountPasswordTime = 2
|
||||
accountPasswordSaltBytes = 16
|
||||
accountPasswordKeyBytes = 32
|
||||
)
|
||||
|
||||
var (
|
||||
ErrAccountPasswordLength = errors.New("Password must contain between 8 and 128 characters.")
|
||||
ErrAccountPasswordSame = errors.New("New password must be different from current password")
|
||||
ErrPasswordLegacyLimit = errors.New("Long passwords are unavailable until the password storage upgrade is complete.")
|
||||
)
|
||||
|
||||
// ValidateNewAccountPassword applies only when a user chooses a new password.
|
||||
// Authentication must continue to accept historical passwords without applying
|
||||
// the new policy. Do not normalize passwords, including surrounding whitespace.
|
||||
func ValidateNewAccountPassword(password string) error {
|
||||
if !utf8.ValidString(password) || utf8.RuneCountInString(password) < MinAccountPasswordLength || utf8.RuneCountInString(password) > MaxAccountPasswordLength {
|
||||
return ErrAccountPasswordLength
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// HashAccountPassword is for account passwords, not MFA backup codes. The
|
||||
// temporary bcrypt mode permits rolling out dual-format readers to all nodes
|
||||
// before enabling Argon2id writes. Existing hashes are never rewritten in bulk.
|
||||
func HashAccountPassword(password string) (string, error) {
|
||||
if err := ValidateNewAccountPassword(password); err != nil {
|
||||
return "", err
|
||||
}
|
||||
switch os.Getenv("ACCOUNT_PASSWORD_HASH_ALGORITHM") {
|
||||
case "bcrypt":
|
||||
if len(password) > 72 {
|
||||
return "", ErrPasswordLegacyLimit
|
||||
}
|
||||
return Password2Hash(password)
|
||||
case "", "argon2id":
|
||||
default:
|
||||
return "", errors.New("Unsupported account password hashing configuration.")
|
||||
}
|
||||
salt := make([]byte, accountPasswordSaltBytes)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate account password salt: %w", err)
|
||||
}
|
||||
key := argon2.IDKey([]byte(password), salt, accountPasswordTime, accountPasswordMemory, 1, accountPasswordKeyBytes)
|
||||
return fmt.Sprintf("$argon2id$v=19$m=19456,t=2,p=1$%s$%s", base64.RawStdEncoding.EncodeToString(salt), base64.RawStdEncoding.EncodeToString(key)), nil
|
||||
}
|
||||
|
||||
func validateArgon2AccountPassword(password, encoded string) bool {
|
||||
// Bound both plaintext and parameters before invoking a memory-hard KDF.
|
||||
// Only the version/parameters emitted by this application are accepted.
|
||||
if len(password) > MaxAccountPasswordLength*utf8.UTFMax || len(encoded) > 256 {
|
||||
return false
|
||||
}
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" || parts[2] != "v=19" || parts[3] != "m=19456,t=2,p=1" {
|
||||
return false
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.Strict().DecodeString(parts[4])
|
||||
if err != nil || len(salt) != accountPasswordSaltBytes {
|
||||
return false
|
||||
}
|
||||
expected, err := base64.RawStdEncoding.Strict().DecodeString(parts[5])
|
||||
if err != nil || len(expected) != accountPasswordKeyBytes {
|
||||
return false
|
||||
}
|
||||
actual := argon2.IDKey([]byte(password), salt, accountPasswordTime, accountPasswordMemory, 1, accountPasswordKeyBytes)
|
||||
return subtle.ConstantTimeCompare(actual, expected) == 1
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
@@ -27,6 +28,9 @@ func Password2Hash(password string) (string, error) {
|
||||
}
|
||||
|
||||
func ValidatePasswordAndHash(password string, hash string) bool {
|
||||
if strings.HasPrefix(hash, "$argon2id$") {
|
||||
return validateArgon2AccountPassword(password, hash)
|
||||
}
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
@@ -12,6 +14,7 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const passwordEncryptionKeyBits = 2048
|
||||
@@ -92,9 +95,10 @@ func PasswordEncryptionPublicKey() (keyID string, publicKeyPEM string) {
|
||||
return passwordEncryptionState.keyID, passwordEncryptionState.publicKey
|
||||
}
|
||||
|
||||
// DecryptPassword decrypts a base64 RSA-OAEP/SHA-256 password submitted by a
|
||||
// browser. All malformed inputs share one error so callers do not expose
|
||||
// cryptographic details to unauthenticated clients.
|
||||
// DecryptPassword accepts legacy RSA-OAEP/SHA-256 ciphertext and v2 envelopes.
|
||||
// V2 wraps a fresh AES-256 key with RSA-OAEP and encrypts the password with GCM,
|
||||
// allowing long Unicode passwords to work with existing 2048-bit server keys.
|
||||
// Both formats share one public error for all malformed inputs.
|
||||
func DecryptPassword(ciphertextBase64 string, keyID string) (string, error) {
|
||||
passwordEncryptionState.RLock()
|
||||
privateKey := passwordEncryptionState.privateKey
|
||||
@@ -103,6 +107,44 @@ func DecryptPassword(ciphertextBase64 string, keyID string) (string, error) {
|
||||
if privateKey == nil || keyID == "" || keyID != activeKeyID {
|
||||
return "", ErrPasswordEncryptionInvalid
|
||||
}
|
||||
if strings.HasPrefix(ciphertextBase64, "v2.") {
|
||||
if len(ciphertextBase64) > 4096 {
|
||||
return "", ErrPasswordEncryptionInvalid
|
||||
}
|
||||
parts := strings.Split(ciphertextBase64, ".")
|
||||
if len(parts) != 4 {
|
||||
return "", ErrPasswordEncryptionInvalid
|
||||
}
|
||||
wrappedKey, err := base64.StdEncoding.Strict().DecodeString(parts[1])
|
||||
if err != nil || len(wrappedKey) != privateKey.Size() {
|
||||
return "", ErrPasswordEncryptionInvalid
|
||||
}
|
||||
nonce, err := base64.StdEncoding.Strict().DecodeString(parts[2])
|
||||
if err != nil || len(nonce) != 12 {
|
||||
return "", ErrPasswordEncryptionInvalid
|
||||
}
|
||||
ciphertext, err := base64.StdEncoding.Strict().DecodeString(parts[3])
|
||||
if err != nil || len(ciphertext) <= 16 || len(ciphertext) > MaxAccountPasswordLength*utf8.UTFMax+16 {
|
||||
return "", ErrPasswordEncryptionInvalid
|
||||
}
|
||||
key, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, privateKey, wrappedKey, []byte("password-v2"))
|
||||
if err != nil || len(key) != 32 {
|
||||
return "", ErrPasswordEncryptionInvalid
|
||||
}
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return "", ErrPasswordEncryptionInvalid
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return "", ErrPasswordEncryptionInvalid
|
||||
}
|
||||
plaintext, err := gcm.Open(nil, nonce, ciphertext, []byte("password-v2:"+keyID))
|
||||
if err != nil {
|
||||
return "", ErrPasswordEncryptionInvalid
|
||||
}
|
||||
return string(plaintext), nil
|
||||
}
|
||||
ciphertext, err := base64.StdEncoding.DecodeString(ciphertextBase64)
|
||||
if err != nil || len(ciphertext) != privateKey.Size() {
|
||||
return "", ErrPasswordEncryptionInvalid
|
||||
|
||||
+39
-21
@@ -16,26 +16,31 @@ import (
|
||||
// action 的 params 填充。本地化展示文案在前端 i18n 模板中维护,本表是语言中立的
|
||||
// 英文基线——调用方因此无需在每个埋点处手写句子(避免与 params 重复书写同一份值)。
|
||||
var auditContentTemplates = map[string]string{
|
||||
"user.create": "Created user ${username} (role ${role})",
|
||||
"user.update": "Updated user ${username} (ID: ${id})",
|
||||
"user.delete": "Deleted user ${username} (ID: ${id})",
|
||||
"user.manage": "Performed ${action} on user ${username} (ID: ${id})",
|
||||
"user.quota_add": "Increased user quota by ${quota}",
|
||||
"user.quota_subtract": "Decreased user quota by ${quota}",
|
||||
"user.quota_override": "Overrode user quota from ${from} to ${to}",
|
||||
"user.binding_clear": "Cleared ${bindingType} binding for user ${username}",
|
||||
"user.2fa_disable": "Force-disabled two-factor authentication for the user",
|
||||
"user.passkey_register": "Registered a passkey",
|
||||
"access_token.generate": "Generated a system access token",
|
||||
"access_token.revoke": "Revoked the system access token",
|
||||
"user.2fa_setup": "Started two-factor authentication setup",
|
||||
"user.2fa_enable": "Enabled two-factor authentication",
|
||||
"user.2fa_disable_self": "Disabled two-factor authentication",
|
||||
"user.2fa_backup_codes": "Regenerated two-factor backup codes",
|
||||
"user.security_verify": "Completed security verification",
|
||||
"user.passkey_delete": "Deleted a passkey",
|
||||
"user.reset_passkey": "Reset the user passkey",
|
||||
"option.update": "Updated system setting ${key}",
|
||||
"user.create": "Created user ${username} (role ${role})",
|
||||
"user.update": "Updated user ${username} (ID: ${id})",
|
||||
"user.delete": "Deleted user ${username} (ID: ${id})",
|
||||
"user.manage": "Performed ${action} on user ${username} (ID: ${id})",
|
||||
"user.quota_add": "Increased user quota by ${quota}",
|
||||
"user.quota_subtract": "Decreased user quota by ${quota}",
|
||||
"user.quota_override": "Overrode user quota from ${from} to ${to}",
|
||||
"user.binding_clear": "Cleared ${bindingType} binding for user ${username}",
|
||||
"user.2fa_disable": "Force-disabled two-factor authentication for the user",
|
||||
"user.passkey_register": "Registered a passkey",
|
||||
"access_token.generate": "Generated a system access token",
|
||||
"access_token.revoke": "Revoked the system access token",
|
||||
"user.2fa_setup": "Started two-factor authentication setup",
|
||||
"user.2fa_enable": "Enabled two-factor authentication",
|
||||
"user.2fa_disable_self": "Disabled two-factor authentication",
|
||||
"user.2fa_backup_codes": "Regenerated two-factor backup codes",
|
||||
"user.security_verify": "Completed security verification",
|
||||
"user.password_change": "Account password change",
|
||||
"user.binding_start": "Account binding request",
|
||||
"user.binding_bind": "Account binding",
|
||||
"user.binding_unbind": "Account unlinking",
|
||||
"user.email_binding_resend": "Email confirmation code resend",
|
||||
"user.passkey_delete": "Deleted a passkey",
|
||||
"user.reset_passkey": "Reset the user passkey",
|
||||
"option.update": "Updated system setting ${key}",
|
||||
|
||||
"channel.create": "Created channel ${name} (type ${type}, count ${count})",
|
||||
"channel.update": "Updated channel ${name} (ID: ${id})",
|
||||
@@ -118,5 +123,18 @@ func recordManageAuditFor(c *gin.Context, targetUserId int, action string, param
|
||||
// recordUserSecurityAudit 记录普通用户自己的安全敏感操作(如 passkey 绑定/解绑)。
|
||||
// 这类日志没有管理员操作者,不写 admin_info;同时不依赖 AdminAuth/RootAuth 的兜底。
|
||||
func recordUserSecurityAudit(c *gin.Context, userId int, action string, params map[string]interface{}) {
|
||||
model.RecordOperationAuditLog(userId, c.GetInt("role"), auditContentEN(action, params), c.ClientIP(), action, params, nil, nil, c)
|
||||
if code := c.GetString("security_error_code"); code != "" {
|
||||
if params == nil {
|
||||
params = map[string]interface{}{}
|
||||
}
|
||||
params["code"] = code
|
||||
}
|
||||
var auditInfo *model.AuditRequestInfo
|
||||
if success, ok := params["success"].(bool); ok {
|
||||
auditInfo = &model.AuditRequestInfo{
|
||||
Method: c.Request.Method, Route: c.FullPath(), Path: c.FullPath(),
|
||||
Status: c.Writer.Status(), Success: success,
|
||||
}
|
||||
}
|
||||
model.RecordOperationAuditLog(userId, c.GetInt("role"), auditContentEN(action, params), c.ClientIP(), action, params, nil, auditInfo, c)
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/model"
|
||||
"github.com/QuantumNous/new-api/oauth"
|
||||
"github.com/QuantumNous/new-api/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/glebarez/sqlite"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -50,18 +51,21 @@ func (*authFlowTestOAuthProvider) ProviderUserIDColumn() string
|
||||
|
||||
func setupAuthFlowControllerTest(t *testing.T) *authFlowTestOAuthProvider {
|
||||
t.Helper()
|
||||
previousDB := model.DB
|
||||
previousDB, previousLogDB := model.DB, model.LOG_DB
|
||||
previousRedis := common.RedisEnabled
|
||||
common.RedisEnabled = false
|
||||
previousType := common.MainDatabaseType()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&model.AuthFlow{}))
|
||||
model.DB = db
|
||||
require.NoError(t, db.AutoMigrate(&model.AuthFlow{}, &model.User{}, &model.UserSession{}, &model.AuditLog{}))
|
||||
model.DB, model.LOG_DB = db, db
|
||||
common.SetMainDatabaseType(common.DatabaseTypeSQLite)
|
||||
provider := &authFlowTestOAuthProvider{}
|
||||
oauth.Register("auth-flow-test", provider)
|
||||
t.Cleanup(func() {
|
||||
oauth.Unregister("auth-flow-test")
|
||||
model.DB = previousDB
|
||||
model.DB, model.LOG_DB = previousDB, previousLogDB
|
||||
common.RedisEnabled = previousRedis
|
||||
common.SetMainDatabaseType(previousType)
|
||||
})
|
||||
return provider
|
||||
@@ -97,34 +101,23 @@ func TestGenerateOAuthCodeCarriesAffiliateInLoginFlow(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestGenerateOAuthCodeBindsFlowToAuthenticatedSession(t *testing.T) {
|
||||
setupAuthFlowControllerTest(t)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/api/oauth/state", strings.NewReader(`{"provider":"auth-flow-test","intent":"bind"}`))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
c.Set("id", 42)
|
||||
c.Set("session_id", "session-42")
|
||||
c.Set("auth_version", int64(3))
|
||||
c.Set("session_version", int64(2))
|
||||
|
||||
GenerateOAuthCode(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, recorder.Code)
|
||||
var response struct {
|
||||
_, identity := setupSecurityEnrollmentTest(t)
|
||||
oauth.Register("auth-flow-test", &authFlowTestOAuthProvider{})
|
||||
t.Cleanup(func() { oauth.Unregister("auth-flow-test") })
|
||||
proof := issueSecurityEnrollmentProof(t, identity, service.VerificationOperation{Scope: service.VerificationScopeAccountBind, Context: []byte(`{"provider":"auth-flow-test"}`)}, service.VerificationMethodPassword)
|
||||
response := securityEnrollmentRequest(http.MethodPost, "/api/oauth/state", `{"provider":"auth-flow-test","intent":"bind"}`, proof, identity, GenerateOAuthCode)
|
||||
var result struct {
|
||||
Success bool `json:"success"`
|
||||
Data struct {
|
||||
FlowToken string `json:"flow_token"`
|
||||
} `json:"data"`
|
||||
}
|
||||
require.NoError(t, common.Unmarshal(recorder.Body.Bytes(), &response))
|
||||
require.True(t, response.Success)
|
||||
flow, err := model.GetAuthFlow(response.Data.FlowToken, model.AuthFlowMatch{
|
||||
Purpose: model.AuthFlowPurposeOAuth, Provider: "auth-flow-test", Intent: model.AuthFlowIntentBind,
|
||||
UserId: 42, SessionId: "session-42",
|
||||
})
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result))
|
||||
require.True(t, result.Success, response.Body.String())
|
||||
flow, err := model.GetAuthFlow(result.Data.FlowToken, model.AuthFlowMatch{Purpose: model.AuthFlowPurposeOAuth, Provider: "auth-flow-test", Intent: model.AuthFlowIntentBind, UserId: identity.UserID, SessionId: identity.SessionID})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 42, flow.UserId)
|
||||
assert.Equal(t, "session-42", flow.SessionId)
|
||||
assert.Equal(t, identity.UserID, flow.UserId)
|
||||
assert.Equal(t, identity.SessionID, flow.SessionId)
|
||||
}
|
||||
|
||||
func TestOAuthLoginConsumesFlowOnlyAfterProviderIdentity(t *testing.T) {
|
||||
@@ -198,27 +191,25 @@ func TestOAuthLoginConsumesFlowAfterProviderIdentityAndOnProviderError(t *testin
|
||||
}
|
||||
|
||||
func TestOAuthBindProviderErrorConsumesSessionBoundFlow(t *testing.T) {
|
||||
provider := setupAuthFlowControllerTest(t)
|
||||
flowToken, _, err := model.CreateAuthFlow(model.AuthFlowCreate{
|
||||
Purpose: model.AuthFlowPurposeOAuth, Provider: "auth-flow-test", Intent: model.AuthFlowIntentBind,
|
||||
UserId: 42, SessionId: "session-42", Payload: `{}`, ExpiresAt: time.Now().Add(time.Minute),
|
||||
_, identity := setupSecurityEnrollmentTest(t)
|
||||
provider := &authFlowTestOAuthProvider{}
|
||||
oauth.Register("auth-flow-test", provider)
|
||||
t.Cleanup(func() { oauth.Unregister("auth-flow-test") })
|
||||
proof := issueSecurityEnrollmentProof(t, identity, service.VerificationOperation{Scope: service.VerificationScopeAccountBind, Context: []byte(`{"provider":"auth-flow-test"}`)}, service.VerificationMethodPassword)
|
||||
started := securityEnrollmentRequest(http.MethodPost, "/api/oauth/state", `{"provider":"auth-flow-test","intent":"bind"}`, proof, identity, GenerateOAuthCode)
|
||||
var result struct {
|
||||
Data struct {
|
||||
FlowToken string `json:"flow_token"`
|
||||
} `json:"data"`
|
||||
}
|
||||
require.NoError(t, common.Unmarshal(started.Body.Bytes(), &result))
|
||||
require.NotEmpty(t, result.Data.FlowToken)
|
||||
response := securityEnrollmentRequest(http.MethodGet, "/api/oauth/auth-flow-test?state="+result.Data.FlowToken+"&error=access_denied&error_description=cancelled", "", "", identity, func(c *gin.Context) {
|
||||
c.Params = gin.Params{{Key: "provider", Value: "auth-flow-test"}}
|
||||
HandleOAuth(c)
|
||||
})
|
||||
require.NoError(t, err)
|
||||
router := gin.New()
|
||||
router.Use(func(c *gin.Context) {
|
||||
c.Set("id", 42)
|
||||
c.Set("session_id", "session-42")
|
||||
c.Set("auth_version", int64(1))
|
||||
c.Set("session_version", int64(1))
|
||||
c.Next()
|
||||
})
|
||||
router.GET("/api/oauth/:provider", HandleOAuth)
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/oauth/auth-flow-test?state="+flowToken+"&error=access_denied&error_description=cancelled", nil)
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
|
||||
assert.Equal(t, http.StatusOK, response.Code)
|
||||
_, err = model.GetAuthFlow(flowToken, model.AuthFlowMatch{Purpose: model.AuthFlowPurposeOAuth})
|
||||
_, err := model.GetAuthFlow(result.Data.FlowToken, model.AuthFlowMatch{Purpose: model.AuthFlowPurposeOAuth})
|
||||
assert.ErrorIs(t, err, model.ErrAuthFlowConsumed)
|
||||
assert.Zero(t, provider.exchangeCalls)
|
||||
assert.Zero(t, provider.userInfoCalls)
|
||||
|
||||
@@ -10,8 +10,10 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"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"
|
||||
)
|
||||
|
||||
@@ -521,27 +523,47 @@ func GetUserOAuthBindingsByAdmin(c *gin.Context) {
|
||||
|
||||
// UnbindCustomOAuth unbinds a custom OAuth provider from the current user
|
||||
func UnbindCustomOAuth(c *gin.Context) {
|
||||
userId := c.GetInt("id")
|
||||
if userId == 0 {
|
||||
common.ApiErrorMsg(c, "未登录")
|
||||
identity, ok := middleware.GetSessionAuthIdentity(c)
|
||||
if !ok {
|
||||
writeSecurityOperationError(c, service.ErrAuthTokenInvalid)
|
||||
return
|
||||
}
|
||||
|
||||
providerIdStr := c.Param("provider_id")
|
||||
providerId, err := strconv.Atoi(providerIdStr)
|
||||
if err != nil {
|
||||
if err != nil || providerId <= 0 {
|
||||
common.ApiErrorMsg(c, "无效的提供商 ID")
|
||||
return
|
||||
}
|
||||
|
||||
if err := model.DeleteUserOAuthBinding(userId, providerId); err != nil {
|
||||
common.ApiError(c, err)
|
||||
succeeded, notificationFailed := false, false
|
||||
defer func() {
|
||||
recordUserSecurityAudit(c, identity.UserID, "user.binding_unbind", map[string]interface{}{"provider_id": providerId, "success": succeeded, "notification_failed": notificationFailed})
|
||||
}()
|
||||
context, err := common.Marshal(service.AccountUnbindingContext{ProviderID: providerId})
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
if middleware.RequireSecurityProof(c, service.VerificationOperation{Scope: service.VerificationScopeAccountUnbind, Context: context}) == nil {
|
||||
return
|
||||
}
|
||||
if err := service.UnbindAccountOAuth(identity, providerId); err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
succeeded = true
|
||||
user, err := model.GetUserById(identity.UserID, false)
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
notificationFailed = service.NotifyAccountSecurityChange(user.Email, "Login account unlinked") != nil
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "解绑成功",
|
||||
"data": gin.H{"notification_warning": notificationFailed},
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
type emailBindRequest struct {
|
||||
Email string `json:"email"`
|
||||
FlowToken string `json:"flow_token"`
|
||||
NewCode string `json:"new_code"`
|
||||
OldCode string `json:"old_code"`
|
||||
}
|
||||
|
||||
func EmailBindStart(c *gin.Context) {
|
||||
identity, ok := middleware.GetSessionAuthIdentity(c)
|
||||
if !ok {
|
||||
writeSecurityOperationError(c, service.ErrAuthTokenInvalid)
|
||||
return
|
||||
}
|
||||
succeeded, notificationFailed := false, false
|
||||
defer func() {
|
||||
recordUserSecurityAudit(c, identity.UserID, "user.binding_start", map[string]interface{}{"provider": "email", "success": succeeded, "notification_failed": notificationFailed})
|
||||
}()
|
||||
var request emailBindRequest
|
||||
if err := common.DecodeJson(c.Request.Body, &request); err != nil {
|
||||
writeSecurityOperationError(c, service.ErrVerificationContextInvalid)
|
||||
return
|
||||
}
|
||||
email, err := service.ValidateAccountEmail(request.Email)
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
context, err := common.Marshal(service.AccountBindingContext{Provider: "email", Email: email})
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
authorization := middleware.RequireSecurityProof(c, service.VerificationOperation{Scope: service.VerificationScopeAccountBind, Context: context})
|
||||
if authorization == nil {
|
||||
return
|
||||
}
|
||||
data, err := service.StartEmailBinding(identity, authorization, email)
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
succeeded, notificationFailed = true, data.NotificationWarning
|
||||
common.ApiSuccess(c, data)
|
||||
}
|
||||
|
||||
func EmailBindResend(c *gin.Context) {
|
||||
identity, ok := middleware.GetSessionAuthIdentity(c)
|
||||
if !ok {
|
||||
writeSecurityOperationError(c, service.ErrAuthTokenInvalid)
|
||||
return
|
||||
}
|
||||
succeeded := false
|
||||
defer func() {
|
||||
recordUserSecurityAudit(c, identity.UserID, "user.email_binding_resend", map[string]interface{}{"success": succeeded})
|
||||
}()
|
||||
var request emailBindRequest
|
||||
if err := common.DecodeJson(c.Request.Body, &request); err != nil || request.FlowToken == "" {
|
||||
writeSecurityOperationError(c, model.ErrAuthFlowInvalid)
|
||||
return
|
||||
}
|
||||
data, err := service.ResendAccountEmailBinding(identity, request.FlowToken)
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
succeeded = true
|
||||
common.ApiSuccess(c, data)
|
||||
}
|
||||
|
||||
func EmailBind(c *gin.Context) {
|
||||
identity, ok := middleware.GetSessionAuthIdentity(c)
|
||||
if !ok {
|
||||
writeSecurityOperationError(c, service.ErrAuthTokenInvalid)
|
||||
return
|
||||
}
|
||||
succeeded, notificationFailed := false, false
|
||||
defer func() {
|
||||
recordUserSecurityAudit(c, identity.UserID, "user.binding_bind", map[string]interface{}{"provider": "email", "success": succeeded, "notification_failed": notificationFailed})
|
||||
}()
|
||||
var request emailBindRequest
|
||||
if err := common.DecodeJson(c.Request.Body, &request); err != nil || request.FlowToken == "" {
|
||||
writeSecurityOperationError(c, model.ErrAuthFlowInvalid)
|
||||
return
|
||||
}
|
||||
state, err := service.FinishEmailBinding(identity, request.FlowToken, request.NewCode, request.OldCode)
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
succeeded = true
|
||||
notificationFailed = service.NotifyAccountSecurityChange(state.CurrentEmail, "Email address changed") != nil
|
||||
if err := service.NotifyAccountSecurityChange(state.Email, "Email address confirmed"); err != nil {
|
||||
notificationFailed = true
|
||||
}
|
||||
if err := model.PublishUserAuthCache(identity.UserID); err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "message": "", "data": gin.H{"notification_warning": notificationFailed}})
|
||||
}
|
||||
+5
-41
@@ -5,7 +5,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/constant"
|
||||
@@ -14,6 +13,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/QuantumNous/new-api/setting"
|
||||
"github.com/QuantumNous/new-api/setting/console_setting"
|
||||
"github.com/QuantumNous/new-api/setting/operation_setting"
|
||||
@@ -216,47 +216,11 @@ func GetHomePageContent(c *gin.Context) {
|
||||
}
|
||||
|
||||
func SendEmailVerification(c *gin.Context) {
|
||||
email := model.NormalizeEmail(c.Query("email"))
|
||||
if err := common.Validate.Var(email, "required,email"); err != nil {
|
||||
common.ApiErrorI18n(c, i18n.MsgInvalidParams)
|
||||
email, err := service.ValidateAccountEmail(c.Query("email"))
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
parts := strings.Split(email, "@")
|
||||
if len(parts) != 2 {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": "无效的邮箱地址",
|
||||
})
|
||||
return
|
||||
}
|
||||
localPart := parts[0]
|
||||
domainPart := parts[1]
|
||||
if common.EmailDomainRestrictionEnabled {
|
||||
allowed := false
|
||||
for _, domain := range common.EmailDomainWhitelist {
|
||||
if domainPart == domain {
|
||||
allowed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !allowed {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": "The administrator has enabled the email domain name whitelist, and your email address is not allowed due to special symbols or it's not in the whitelist.",
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
if common.EmailAliasRestrictionEnabled {
|
||||
containsSpecialSymbols := strings.Contains(localPart, "+") || strings.Contains(localPart, ".")
|
||||
if containsSpecialSymbols {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": "管理员已启用邮箱地址别名限制,您的邮箱地址由于包含特殊符号而被拒绝。",
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if model.IsEmailAlreadyTaken(email) {
|
||||
common.ApiErrorI18n(c, i18n.MsgUserEmailAlreadyTaken)
|
||||
@@ -268,7 +232,7 @@ func SendEmailVerification(c *gin.Context) {
|
||||
content := fmt.Sprintf("<p>您好,你正在进行%s邮箱验证。</p>"+
|
||||
"<p>您的验证码为: <strong>%s</strong></p>"+
|
||||
"<p>验证码 %d 分钟内有效,如果不是本人操作,请忽略。</p>", common.SystemName, code, common.VerificationValidMinutes)
|
||||
err := common.SendEmail(subject, email, content)
|
||||
err = common.SendEmail(subject, email, content)
|
||||
if err != nil {
|
||||
common.ApiError(c, err)
|
||||
return
|
||||
|
||||
@@ -493,46 +493,6 @@ func TestListModelsTokenLimitUsesResolvedCustomAutoGroups(t *testing.T) {
|
||||
require.Empty(t, anthropicResponse.LastID)
|
||||
}
|
||||
|
||||
func TestCheckUpdatePasswordRequiresCurrentPassword(t *testing.T) {
|
||||
db := setupModelListControllerTestDB(t)
|
||||
hashedPassword, err := common.Password2Hash("CurrentPassword123")
|
||||
require.NoError(t, err)
|
||||
user := &model.User{
|
||||
Username: "password-user",
|
||||
Password: hashedPassword,
|
||||
Status: common.UserStatusEnabled,
|
||||
}
|
||||
require.NoError(t, db.Create(user).Error)
|
||||
|
||||
updatePassword, err := checkUpdatePassword("", "", user.Id)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, updatePassword)
|
||||
|
||||
updatePassword, err = checkUpdatePassword("", "NewPassword123", user.Id)
|
||||
require.Error(t, err)
|
||||
assert.False(t, updatePassword)
|
||||
assert.ErrorIs(t, err, errOriginalPasswordFail)
|
||||
|
||||
updatePassword, err = checkUpdatePassword("CurrentPassword123", "NewPassword123", user.Id)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, updatePassword)
|
||||
}
|
||||
|
||||
func TestCheckUpdatePasswordRejectsHistoricalEmptyPassword(t *testing.T) {
|
||||
db := setupModelListControllerTestDB(t)
|
||||
user := &model.User{
|
||||
Username: "legacy-passwordless-user",
|
||||
Password: "",
|
||||
Status: common.UserStatusEnabled,
|
||||
}
|
||||
require.NoError(t, db.Create(user).Error)
|
||||
|
||||
updatePassword, err := checkUpdatePassword("", "NewPassword123", user.Id)
|
||||
require.Error(t, err)
|
||||
assert.False(t, updatePassword)
|
||||
assert.ErrorIs(t, err, errUserPasswordUnset)
|
||||
}
|
||||
|
||||
func TestSetupLoginDoesNotTouchPasswordWhenPasswordFieldOmitted(t *testing.T) {
|
||||
db := setupModelListControllerTestDB(t)
|
||||
require.NoError(t, db.AutoMigrate(&model.Log{}, &model.AuditLog{}, &model.UserSession{}))
|
||||
|
||||
+86
-42
@@ -34,6 +34,7 @@ type oauthFlowPayload struct {
|
||||
Verification *service.OAuthVerificationFlow `json:"verification,omitempty"`
|
||||
Telegram *oauth.TelegramOAuthFlow `json:"telegram,omitempty"`
|
||||
SessionIdentity *service.AuthIdentity `json:"session_identity,omitempty"`
|
||||
Authorization *model.AuthFlowAuthorization `json:"authorization,omitempty"`
|
||||
}
|
||||
|
||||
// providerParams returns map with Provider key for i18n templates
|
||||
@@ -62,6 +63,7 @@ func GenerateOAuthCode(c *gin.Context) {
|
||||
userID := 0
|
||||
sessionID := ""
|
||||
flowPayload := oauthFlowPayload{AffiliateCode: request.Aff}
|
||||
bindingStarted := false
|
||||
if request.Provider == "telegram" {
|
||||
telegramFlow, err := oauth.NewTelegramOAuthFlow()
|
||||
if err != nil {
|
||||
@@ -78,6 +80,21 @@ func GenerateOAuthCode(c *gin.Context) {
|
||||
}
|
||||
userID = identity.UserID
|
||||
sessionID = identity.SessionID
|
||||
if request.Intent == model.AuthFlowIntentBind {
|
||||
defer func() {
|
||||
recordUserSecurityAudit(c, userID, "user.binding_start", map[string]interface{}{"provider": request.Provider, "success": bindingStarted})
|
||||
}()
|
||||
context, err := common.Marshal(service.AccountBindingContext{Provider: request.Provider})
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
flowPayload.Authorization = middleware.RequireSecurityProof(c, service.VerificationOperation{Scope: service.VerificationScopeAccountBind, Context: context})
|
||||
if flowPayload.Authorization == nil {
|
||||
return
|
||||
}
|
||||
flowPayload.SessionIdentity = &identity
|
||||
}
|
||||
if flowPayload.Telegram != nil {
|
||||
if _, _, err := service.ValidateLoginSession(identity); err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
@@ -113,6 +130,7 @@ func GenerateOAuthCode(c *gin.Context) {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
bindingStarted = request.Intent == model.AuthFlowIntentBind
|
||||
data := gin.H{"flow_token": state, "expires_at": expiresAt.Unix()}
|
||||
if flowPayload.Telegram != nil {
|
||||
data["authorization_url"] = flowPayload.Telegram.AuthorizationURL(state)
|
||||
@@ -155,6 +173,12 @@ func HandleOAuth(c *gin.Context) {
|
||||
Provider: providerName,
|
||||
Intent: pendingFlow.Intent,
|
||||
}
|
||||
bindSucceeded, notificationFailed := false, false
|
||||
if pendingFlow.Intent == model.AuthFlowIntentBind {
|
||||
defer func() {
|
||||
recordUserSecurityAudit(c, pendingFlow.UserId, "user.binding_bind", map[string]interface{}{"provider": providerName, "success": bindSucceeded, "notification_failed": notificationFailed})
|
||||
}()
|
||||
}
|
||||
// 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)
|
||||
@@ -167,6 +191,22 @@ func HandleOAuth(c *gin.Context) {
|
||||
}
|
||||
consumeMatch.UserId = identity.UserID
|
||||
consumeMatch.SessionId = identity.SessionID
|
||||
if pendingFlow.Intent == model.AuthFlowIntentBind {
|
||||
var payload oauthFlowPayload
|
||||
if err := common.UnmarshalJsonStr(pendingFlow.Payload, &payload); err != nil {
|
||||
writeSecurityOperationError(c, model.ErrAuthFlowInvalid)
|
||||
return
|
||||
}
|
||||
context, err := common.Marshal(service.AccountBindingContext{Provider: providerName})
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
if err := service.ValidateFlowAuthorization(identity, service.VerificationOperation{Scope: service.VerificationScopeAccountBind, Context: context}, payload.Authorization); err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
} else if pendingFlow.Intent != model.AuthFlowIntentLogin {
|
||||
common.ApiErrorI18n(c, i18n.MsgInvalidParams)
|
||||
return
|
||||
@@ -240,15 +280,8 @@ func HandleOAuth(c *gin.Context) {
|
||||
handleOAuthError(c, err)
|
||||
return
|
||||
}
|
||||
if providerName == "telegram" && pendingFlow.Intent == model.AuthFlowIntentBind {
|
||||
_, err := model.ConsumeAuthFlowWithAction(state, consumeMatch, func(tx *gorm.DB, _ *model.AuthFlow) error {
|
||||
return model.BindTelegramForSessionWithTx(tx, *telegramPayload.SessionIdentity, oauthUser.ProviderUserID)
|
||||
})
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
common.ApiSuccessI18n(c, i18n.MsgOAuthBindSuccess, gin.H{"action": "bind"})
|
||||
if pendingFlow.Intent == model.AuthFlowIntentBind {
|
||||
bindSucceeded, notificationFailed = handleOAuthBind(c, providerName, provider, oauthUser, pendingFlow, state, consumeMatch)
|
||||
return
|
||||
}
|
||||
flow, err := model.ConsumeAuthFlow(state, consumeMatch)
|
||||
@@ -260,8 +293,6 @@ func HandleOAuth(c *gin.Context) {
|
||||
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)
|
||||
}
|
||||
@@ -320,44 +351,57 @@ func handleOAuthLogin(c *gin.Context, provider oauth.Provider, oauthUser *oauth.
|
||||
}
|
||||
|
||||
// handleOAuthBind handles binding OAuth account to existing user
|
||||
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)
|
||||
func handleOAuthBind(c *gin.Context, providerName string, provider oauth.Provider, oauthUser *oauth.OAuthUser, flow *model.AuthFlow, state string, match model.AuthFlowMatch) (bool, bool) {
|
||||
identity, ok := middleware.GetSessionAuthIdentity(c)
|
||||
if !ok {
|
||||
writeSecurityOperationError(c, service.ErrAuthTokenInvalid)
|
||||
return false, false
|
||||
}
|
||||
var payload oauthFlowPayload
|
||||
if err := common.UnmarshalJsonStr(flow.Payload, &payload); err != nil {
|
||||
writeSecurityOperationError(c, model.ErrAuthFlowInvalid)
|
||||
return false, false
|
||||
}
|
||||
context, err := common.Marshal(service.AccountBindingContext{Provider: providerName})
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return false, false
|
||||
}
|
||||
// Recheck after the external provider round trip, then validate the session
|
||||
// under the transaction's locks before consuming the flow and writing.
|
||||
if err := service.ValidateFlowAuthorization(identity, service.VerificationOperation{Scope: service.VerificationScopeAccountBind, Context: context}, payload.Authorization); err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return false, false
|
||||
}
|
||||
if provider.IsUserIDTaken(oauthUser.ProviderUserID) {
|
||||
common.ApiErrorI18n(c, i18n.MsgOAuthAlreadyBound, providerParams(provider.GetName()))
|
||||
return
|
||||
return false, false
|
||||
}
|
||||
// Also check legacy ID to prevent duplicate bindings during migration period
|
||||
if legacyID, ok := oauthUser.Extra["legacy_id"].(string); ok && legacyID != "" {
|
||||
if provider.IsUserIDTaken(legacyID) {
|
||||
common.ApiErrorI18n(c, i18n.MsgOAuthAlreadyBound, providerParams(provider.GetName()))
|
||||
return
|
||||
}
|
||||
if legacyID, ok := oauthUser.Extra["legacy_id"].(string); ok && legacyID != "" && provider.IsUserIDTaken(legacyID) {
|
||||
common.ApiErrorI18n(c, i18n.MsgOAuthAlreadyBound, providerParams(provider.GetName()))
|
||||
return false, false
|
||||
}
|
||||
|
||||
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 {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
_, err = model.ConsumeAuthFlowWithAction(state, match, func(tx *gorm.DB, _ *model.AuthFlow) error {
|
||||
if providerName == "telegram" {
|
||||
return model.BindTelegramForSessionWithTx(tx, identity, oauthUser.ProviderUserID)
|
||||
}
|
||||
} else {
|
||||
// Built-in provider: 只更新绑定列。完整快照的 user.Update 会把读取时刻的
|
||||
// role/status/group 一并写回,覆盖并发发生的封禁、降权或分组变更。
|
||||
err = model.UpdateUserBindColumn(userId, provider.ProviderUserIDColumn(), oauthUser.ProviderUserID)
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
if custom, ok := provider.(*oauth.GenericOAuthProvider); ok {
|
||||
return model.UpdateUserOAuthBindingForSessionWithTx(tx, identity, custom.GetProviderId(), oauthUser.ProviderUserID)
|
||||
}
|
||||
}
|
||||
|
||||
common.ApiSuccessI18n(c, i18n.MsgOAuthBindSuccess, gin.H{
|
||||
"action": "bind",
|
||||
return model.UpdateUserBindColumnForSessionWithTx(tx, identity, provider.ProviderUserIDColumn(), oauthUser.ProviderUserID)
|
||||
})
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return false, false
|
||||
}
|
||||
user, err := model.GetUserById(identity.UserID, false)
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return true, true
|
||||
}
|
||||
notificationFailed := service.NotifyAccountSecurityChange(user.Email, "Login account linked: "+provider.GetName()) != nil
|
||||
common.ApiSuccessI18n(c, i18n.MsgOAuthBindSuccess, gin.H{"action": "bind", "notification_warning": notificationFailed})
|
||||
return true, notificationFailed
|
||||
}
|
||||
|
||||
// findOrCreateOAuthUser finds existing user or creates new user
|
||||
|
||||
@@ -512,7 +512,12 @@ func PasskeyVerifyBegin(c *gin.Context) {
|
||||
}
|
||||
|
||||
waUser := passkeysvc.NewWebAuthnUser(user, credential)
|
||||
assertion, sessionData, err := wa.BeginLogin(waUser)
|
||||
var options []webauthnlib.LoginOption
|
||||
switch request.Scope {
|
||||
case service.VerificationScopeAccountBind, service.VerificationScopeAccountUnbind, service.VerificationScopePasswordSet, service.VerificationScopePasswordChange:
|
||||
options = append(options, webauthnlib.WithUserVerification(protocol.VerificationRequired))
|
||||
}
|
||||
assertion, sessionData, err := wa.BeginLogin(waUser, options...)
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
|
||||
@@ -34,6 +34,28 @@ func writeSecurityOperationError(c *gin.Context, err error) {
|
||||
var code, message string
|
||||
var protocolError *protocol.Error
|
||||
switch {
|
||||
case errors.Is(err, service.ErrAccountEmailInvalid), errors.Is(err, service.ErrAccountEmailRestricted):
|
||||
code, message = "EMAIL_ADDRESS_REJECTED", err.Error()
|
||||
case errors.Is(err, model.ErrEmailAlreadyTaken):
|
||||
code, message = "EMAIL_ALREADY_TAKEN", "This email address is already in use."
|
||||
case errors.Is(err, service.ErrEmailBindingDelivery):
|
||||
code, message = "EMAIL_BINDING_DELIVERY_FAILED", err.Error()
|
||||
case errors.Is(err, model.ErrEmailBindingCodeInvalid):
|
||||
code, message = "EMAIL_BINDING_CODE_INVALID", err.Error()
|
||||
case errors.Is(err, model.ErrEmailBindingLocked):
|
||||
code, message = "EMAIL_BINDING_LOCKED", err.Error()
|
||||
case errors.Is(err, model.ErrEmailBindingResendWait):
|
||||
status = http.StatusTooManyRequests
|
||||
code, message = "EMAIL_BINDING_RESEND_WAIT", err.Error()
|
||||
case errors.Is(err, common.ErrAccountPasswordLength), errors.Is(err, common.ErrAccountPasswordSame), errors.Is(err, common.ErrPasswordLegacyLimit):
|
||||
code, message = "PASSWORD_POLICY_REJECTED", err.Error()
|
||||
case errors.Is(err, model.ErrCurrentPasswordInvalid):
|
||||
code, message = "CURRENT_PASSWORD_INVALID", err.Error()
|
||||
case errors.Is(err, model.ErrAccountPasswordState), errors.Is(err, model.ErrAccountBindingChanged):
|
||||
status = http.StatusConflict
|
||||
code, message = "ACCOUNT_SECURITY_STATE_CHANGED", err.Error()
|
||||
case errors.Is(err, model.ErrLastLoginMethod):
|
||||
code, message = "LAST_LOGIN_METHOD", err.Error()
|
||||
case errors.Is(err, oauth.ErrTelegramOAuthNotConfigured):
|
||||
code, message = "TELEGRAM_OAUTH_NOT_CONFIGURED", oauth.ErrTelegramOAuthNotConfigured.Error()
|
||||
case errors.Is(err, oauth.ErrTelegramOAuthConflict):
|
||||
@@ -43,7 +65,10 @@ func writeSecurityOperationError(c *gin.Context, err error) {
|
||||
case errors.Is(err, oauth.ErrTelegramAccountNotBound):
|
||||
code, message = "TELEGRAM_ACCOUNT_NOT_BOUND", oauth.ErrTelegramAccountNotBound.Error()
|
||||
case errors.Is(err, model.ErrExternalIdentityAlreadyClaimed):
|
||||
code, message = "TELEGRAM_BIND_ALREADY_BOUND", "This Telegram account is already bound."
|
||||
code, message = "ACCOUNT_ALREADY_BOUND", "This external account is already bound."
|
||||
if c.Param("provider") == "telegram" {
|
||||
code, message = "TELEGRAM_BIND_ALREADY_BOUND", "This Telegram account is already bound."
|
||||
}
|
||||
case errors.Is(err, service.ErrVerificationContextInvalid):
|
||||
status = http.StatusBadRequest
|
||||
code, message = "SECURITY_CONTEXT_INVALID", service.ErrVerificationContextInvalid.Error()
|
||||
@@ -82,9 +107,11 @@ func writeSecurityOperationError(c *gin.Context, err error) {
|
||||
writeAuthSessionError(c, service.ErrAuthTokenInvalid)
|
||||
return
|
||||
default:
|
||||
c.Set("security_error_code", "AUTH_INTERNAL_ERROR")
|
||||
writeAuthSessionError(c, err)
|
||||
return
|
||||
}
|
||||
c.Set("security_error_code", code)
|
||||
c.JSON(status, gin.H{"success": false, "code": code, "message": message})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,642 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/pem"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/textproto"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"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/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type securityMailbox struct {
|
||||
mutex sync.Mutex
|
||||
mail map[string][]string
|
||||
}
|
||||
|
||||
// Use a real local SMTP boundary so delivery, failure and code handling are
|
||||
// exercised without exporting test-only mail hooks from production packages.
|
||||
func newSecurityMailbox(t *testing.T) *securityMailbox {
|
||||
t.Helper()
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
require.NoError(t, err)
|
||||
mailbox := &securityMailbox{mail: map[string][]string{}}
|
||||
previousServer, previousPort := common.SMTPServer, common.SMTPPort
|
||||
previousAccount, previousFrom, previousToken := common.SMTPAccount, common.SMTPFrom, common.SMTPToken
|
||||
previousSSL, previousTLS := common.SMTPSSLEnabled, common.SMTPStartTLSEnabled
|
||||
common.SMTPServer, common.SMTPPort = "127.0.0.1", listener.Addr().(*net.TCPAddr).Port
|
||||
common.SMTPAccount, common.SMTPFrom, common.SMTPToken = "", "sender@example.com", ""
|
||||
common.SMTPSSLEnabled, common.SMTPStartTLSEnabled = false, false
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
for {
|
||||
connection, err := listener.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
mailbox.receive(connection)
|
||||
}
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
_ = listener.Close()
|
||||
<-done
|
||||
common.SMTPServer, common.SMTPPort = previousServer, previousPort
|
||||
common.SMTPAccount, common.SMTPFrom, common.SMTPToken = previousAccount, previousFrom, previousToken
|
||||
common.SMTPSSLEnabled, common.SMTPStartTLSEnabled = previousSSL, previousTLS
|
||||
})
|
||||
return mailbox
|
||||
}
|
||||
|
||||
func (mailbox *securityMailbox) receive(connection net.Conn) {
|
||||
defer connection.Close()
|
||||
_ = connection.SetDeadline(time.Now().Add(10 * time.Second))
|
||||
client := textproto.NewConn(connection)
|
||||
if client.PrintfLine("220 localhost ESMTP") != nil {
|
||||
return
|
||||
}
|
||||
receiver := ""
|
||||
for {
|
||||
line, err := client.ReadLine()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case strings.HasPrefix(line, "RCPT TO:"):
|
||||
receiver = strings.TrimSuffix(strings.TrimPrefix(line, "RCPT TO:<"), ">")
|
||||
case line == "DATA":
|
||||
if client.PrintfLine("354 Send message") != nil {
|
||||
return
|
||||
}
|
||||
message, err := io.ReadAll(client.DotReader())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
mailbox.mutex.Lock()
|
||||
mailbox.mail[receiver] = append(mailbox.mail[receiver], string(message))
|
||||
mailbox.mutex.Unlock()
|
||||
case line == "QUIT":
|
||||
_ = client.PrintfLine("221 Goodbye")
|
||||
return
|
||||
}
|
||||
if client.PrintfLine("250 OK") != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (mailbox *securityMailbox) code(t *testing.T, receiver string) string {
|
||||
t.Helper()
|
||||
mailbox.mutex.Lock()
|
||||
defer mailbox.mutex.Unlock()
|
||||
for index := len(mailbox.mail[receiver]) - 1; index >= 0; index-- {
|
||||
match := regexp.MustCompile(`<strong>([0-9]{6})</strong>`).FindStringSubmatch(mailbox.mail[receiver][index])
|
||||
if len(match) == 2 {
|
||||
return match[1]
|
||||
}
|
||||
}
|
||||
t.Fatalf("no verification email delivered to %s", receiver)
|
||||
return ""
|
||||
}
|
||||
|
||||
func startSecurityEmailBinding(t *testing.T, identity service.AuthIdentity, email, method string) service.EmailBindingData {
|
||||
t.Helper()
|
||||
context, err := common.Marshal(service.AccountBindingContext{Provider: "email", Email: email})
|
||||
require.NoError(t, err)
|
||||
proof := issueSecurityEnrollmentProof(t, identity, service.VerificationOperation{Scope: service.VerificationScopeAccountBind, Context: context}, method)
|
||||
request, err := common.Marshal(map[string]string{"email": email})
|
||||
require.NoError(t, err)
|
||||
response := securityEnrollmentRequest("POST", "/api/oauth/email/bind/start", string(request), proof, identity, EmailBindStart)
|
||||
var body securityEnrollmentResponse
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body))
|
||||
require.True(t, body.Success, response.Body.String())
|
||||
var flow service.EmailBindingData
|
||||
require.NoError(t, common.Unmarshal(body.Data, &flow))
|
||||
require.NotEmpty(t, flow.FlowToken)
|
||||
return flow
|
||||
}
|
||||
|
||||
func TestSecurityAccountRequiresProofBeforeMutation(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name, path, body string
|
||||
handler gin.HandlerFunc
|
||||
}{
|
||||
{"password", "/api/user/self", `{"password":"account-password!42","original_password":"enrollment-password"}`, UpdateSelf},
|
||||
{"oauth binding", "/api/oauth/state", `{"provider":"security-account-test","intent":"bind"}`, GenerateOAuthCode},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
user, identity := setupSecurityEnrollmentTest(t)
|
||||
oauth.Register("security-account-test", &authFlowTestOAuthProvider{})
|
||||
t.Cleanup(func() { oauth.Unregister("security-account-test") })
|
||||
response := securityEnrollmentRequest(http.MethodPost, test.path, test.body, "", identity, test.handler)
|
||||
var result securityEnrollmentResponse
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result))
|
||||
assert.Equal(t, http.StatusForbidden, response.Code)
|
||||
assert.Equal(t, "SECURITY_PROOF_REQUIRED", result.Code)
|
||||
stored, err := model.GetUserById(user.Id, true)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, common.ValidatePasswordAndHash("enrollment-password", stored.Password))
|
||||
var flows int64
|
||||
require.NoError(t, model.DB.Model(&model.AuthFlow{}).Count(&flows).Error)
|
||||
assert.Zero(t, flows)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecurityAccountPasswordRequiresCurrentPassword(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name, original string
|
||||
success bool
|
||||
}{
|
||||
{"missing", "", false},
|
||||
{"wrong", "wrong-password", false},
|
||||
{"correct", "enrollment-password", true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
user, identity := setupSecurityEnrollmentTest(t)
|
||||
proof := issueSecurityEnrollmentProof(t, identity, service.VerificationOperation{Scope: service.VerificationScopePasswordChange}, service.VerificationMethodPassword)
|
||||
request, err := common.Marshal(map[string]string{"password": "password123", "original_password": test.original})
|
||||
require.NoError(t, err)
|
||||
response := securityEnrollmentRequest(http.MethodPut, "/api/user/self", string(request), proof, identity, UpdateSelf)
|
||||
var result securityEnrollmentResponse
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result))
|
||||
assert.Equal(t, test.success, result.Success, response.Body.String())
|
||||
stored, err := model.GetUserById(user.Id, true)
|
||||
require.NoError(t, err)
|
||||
if test.success {
|
||||
assert.True(t, common.ValidatePasswordAndHash("password123", stored.Password))
|
||||
assert.True(t, strings.HasPrefix(stored.Password, "$argon2id$"))
|
||||
} else {
|
||||
assert.Equal(t, "CURRENT_PASSWORD_INVALID", result.Code)
|
||||
assert.Equal(t, user.Password, stored.Password)
|
||||
repeated := securityEnrollmentRequest(http.MethodPut, "/api/user/self", string(request), proof, identity, UpdateSelf)
|
||||
require.NoError(t, common.Unmarshal(repeated.Body.Bytes(), &result))
|
||||
assert.Equal(t, "SECURITY_PROOF_CONSUMED", result.Code)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecurityAccountProfileReadsPasswordStatusInOneQuery(t *testing.T) {
|
||||
for _, hasPassword := range []bool{true, false} {
|
||||
name := "password set"
|
||||
if !hasPassword {
|
||||
name = "password unset"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
user, identity := setupSecurityEnrollmentTest(t)
|
||||
updates := map[string]interface{}{"access_token": "private-profile-token", "remark": "private-profile-remark"}
|
||||
if !hasPassword {
|
||||
updates["password"] = ""
|
||||
}
|
||||
require.NoError(t, model.DB.Model(&model.User{}).Where("id = ?", user.Id).Updates(updates).Error)
|
||||
queries := 0
|
||||
require.NoError(t, model.DB.Callback().Query().Before("gorm:query").Register("profile_query_count", func(tx *gorm.DB) {
|
||||
queries++
|
||||
}))
|
||||
profile, err := model.GetSelfUserById(user.Id)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, queries)
|
||||
assert.Equal(t, hasPassword, profile.HasPassword)
|
||||
assert.Empty(t, profile.Password)
|
||||
assert.Nil(t, profile.AccessToken)
|
||||
assert.Empty(t, profile.Remark)
|
||||
assert.Equal(t, user.AuthVersion, profile.AuthVersion)
|
||||
assert.Equal(t, user.Group, profile.Group)
|
||||
require.NoError(t, model.DB.Callback().Query().Remove("profile_query_count"))
|
||||
|
||||
response := securityEnrollmentRequest(http.MethodGet, "/api/user/self", "", "", identity, GetSelf)
|
||||
var result struct {
|
||||
Success bool `json:"success"`
|
||||
Data map[string]interface{} `json:"data"`
|
||||
}
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result))
|
||||
require.True(t, result.Success, response.Body.String())
|
||||
assert.Equal(t, hasPassword, result.Data["has_password"])
|
||||
assert.NotContains(t, result.Data, "password")
|
||||
assert.NotContains(t, result.Data, "access_token")
|
||||
assert.NotContains(t, result.Data, "remark")
|
||||
|
||||
bundle, err := service.CreateLoginSession(user.Id, "profile-test", "127.0.0.1", "profile-test")
|
||||
require.NoError(t, err)
|
||||
_, refreshed, err := service.RefreshLoginSession(bundle.RefreshToken, "", "127.0.0.1", "profile-test")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, hasPassword, refreshed.HasPassword)
|
||||
assert.Empty(t, refreshed.Password)
|
||||
assert.Nil(t, refreshed.AccessToken)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecurityAccountProfileUpdateDoesNotRequireProof(t *testing.T) {
|
||||
user, identity := setupSecurityEnrollmentTest(t)
|
||||
response := securityEnrollmentRequest(http.MethodPut, "/api/user/self", `{"display_name":"Updated"}`, "", identity, UpdateSelf)
|
||||
var result securityEnrollmentResponse
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result))
|
||||
require.True(t, result.Success, response.Body.String())
|
||||
stored, err := model.GetUserById(user.Id, true)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "Updated", stored.DisplayName)
|
||||
assert.Equal(t, user.Password, stored.Password)
|
||||
}
|
||||
|
||||
func TestSecurityAccountLongUnicodePasswordAndSessionRotation(t *testing.T) {
|
||||
user, identity := setupSecurityEnrollmentTest(t)
|
||||
other, err := service.CreateLoginSession(user.Id, "password", "127.0.0.1", "other-device")
|
||||
require.NoError(t, err)
|
||||
otherIdentity, err := service.ParseAccessToken(other.AccessToken)
|
||||
require.NoError(t, err)
|
||||
password := strings.Repeat("安全🔒 ", 24)
|
||||
proof := issueSecurityEnrollmentProof(t, identity, service.VerificationOperation{Scope: service.VerificationScopePasswordChange}, service.VerificationMethodPassword)
|
||||
body, err := common.Marshal(map[string]string{"password": password, "original_password": "enrollment-password"})
|
||||
require.NoError(t, err)
|
||||
response := securityEnrollmentRequest(http.MethodPut, "/api/user/self", string(body), proof, identity, UpdateSelf)
|
||||
var result struct {
|
||||
Success bool `json:"success"`
|
||||
Data struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
HasPassword bool `json:"has_password"`
|
||||
} `json:"data"`
|
||||
}
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result))
|
||||
require.True(t, result.Success, response.Body.String())
|
||||
assert.True(t, result.Data.HasPassword)
|
||||
currentIdentity, err := service.ParseAccessToken(result.Data.AccessToken)
|
||||
require.NoError(t, err)
|
||||
_, _, err = service.ValidateLoginSession(currentIdentity)
|
||||
require.NoError(t, err)
|
||||
_, _, err = service.ValidateLoginSession(otherIdentity)
|
||||
require.Error(t, err)
|
||||
login := model.User{Username: user.Username, Password: password}
|
||||
require.NoError(t, login.ValidateAndFill())
|
||||
assert.False(t, common.ValidatePasswordAndHash(strings.TrimSpace(password), login.Password))
|
||||
assert.False(t, common.ValidatePasswordAndHash("enrollment-password", login.Password))
|
||||
}
|
||||
|
||||
func TestSecurityAccountPasswordPolicyAndHashCompatibility(t *testing.T) {
|
||||
t.Setenv("ACCOUNT_PASSWORD_HASH_ALGORITHM", "argon2id")
|
||||
for _, test := range []struct {
|
||||
name, password string
|
||||
valid bool
|
||||
}{
|
||||
{"common password accepted", "password123", true},
|
||||
{"short", "seven77", false},
|
||||
{"too long", strings.Repeat("界", 129), false},
|
||||
{"long Unicode", strings.Repeat("界🔒 ", 40), true},
|
||||
{"whitespace preserved", " phrase with whitespace ", true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
hash, err := common.HashAccountPassword(test.password)
|
||||
if !test.valid {
|
||||
require.Error(t, err)
|
||||
assert.Empty(t, hash)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
assert.True(t, common.ValidatePasswordAndHash(test.password, hash))
|
||||
assert.False(t, common.ValidatePasswordAndHash(test.password+"x", hash))
|
||||
})
|
||||
}
|
||||
legacy, err := common.Password2Hash("123456")
|
||||
require.NoError(t, err)
|
||||
assert.True(t, common.ValidatePasswordAndHash("123456", legacy), "login preserves historical passwords without applying new policy")
|
||||
for _, invalid := range []string{"$argon2id$", "$argon2id$v=19$m=4294967295,t=2,p=1$bad$bad", "$argon2id$v=19$m=19456,t=2,p=1$bad$bad"} {
|
||||
assert.False(t, common.ValidatePasswordAndHash("example-password", invalid))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecurityAccountEncryptedLongPasswordLogin(t *testing.T) {
|
||||
user, identity := setupSecurityEnrollmentTest(t)
|
||||
password := strings.Repeat("🔒", 128)
|
||||
hash, err := common.HashAccountPassword(password)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, model.DB.Model(user).Update("password", hash).Error)
|
||||
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)
|
||||
key, nonce := make([]byte, 32), make([]byte, 12)
|
||||
_, err = rand.Read(key)
|
||||
require.NoError(t, err)
|
||||
_, err = rand.Read(nonce)
|
||||
require.NoError(t, err)
|
||||
wrappedKey, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, key, []byte("password-v2"))
|
||||
require.NoError(t, err)
|
||||
aesBlock, err := aes.NewCipher(key)
|
||||
require.NoError(t, err)
|
||||
gcm, err := cipher.NewGCM(aesBlock)
|
||||
require.NoError(t, err)
|
||||
ciphertext := gcm.Seal(nil, nonce, []byte(password), []byte("password-v2:"+keyID))
|
||||
parts := []string{"v2", base64.StdEncoding.EncodeToString(wrappedKey), base64.StdEncoding.EncodeToString(nonce), base64.StdEncoding.EncodeToString(ciphertext)}
|
||||
encrypted := strings.Join(parts, ".")
|
||||
common.PasswordLoginEncryptionEnabled = true
|
||||
request, err := common.Marshal(LoginRequest{Username: user.Username, PasswordEncrypted: encrypted, EncryptionKeyID: keyID})
|
||||
require.NoError(t, err)
|
||||
response := securityEnrollmentRequest("POST", "/api/user/login", string(request), "", identity, Login)
|
||||
var result securityEnrollmentResponse
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result))
|
||||
require.True(t, result.Success, response.Body.String())
|
||||
assert.Contains(t, string(result.Data), `"has_password":true`)
|
||||
proof, err := service.VerifySecurityInput(identity, service.VerificationInput{Method: "password", Scope: service.VerificationScopePasswordChange, PasswordEncrypted: encrypted, EncryptionKeyID: keyID})
|
||||
require.NoError(t, err)
|
||||
assert.NotEmpty(t, proof.ProofToken)
|
||||
ciphertext[len(ciphertext)-1] ^= 1
|
||||
parts[3] = base64.StdEncoding.EncodeToString(ciphertext)
|
||||
for _, invalid := range []string{strings.Join(parts, "."), "v2.bad.bad.bad", "v2." + strings.Repeat("a", 4096)} {
|
||||
_, err := common.DecryptPassword(invalid, keyID)
|
||||
assert.ErrorIs(t, err, common.ErrPasswordEncryptionInvalid)
|
||||
}
|
||||
_, err = common.DecryptPassword(encrypted, "wrong-key-id")
|
||||
assert.ErrorIs(t, err, common.ErrPasswordEncryptionInvalid)
|
||||
}
|
||||
|
||||
func TestSecurityAccountEmailConfirmationAndAudit(t *testing.T) {
|
||||
for _, scenario := range []string{"first email", "replace without mfa", "replace with mfa"} {
|
||||
t.Run(scenario, func(t *testing.T) {
|
||||
user, identity := setupSecurityEnrollmentTest(t)
|
||||
mailbox := newSecurityMailbox(t)
|
||||
method, previous := service.VerificationMethodPassword, ""
|
||||
if scenario != "first email" {
|
||||
previous = "previous@example.com"
|
||||
require.NoError(t, model.DB.Model(user).Update("email", previous).Error)
|
||||
}
|
||||
if scenario == "replace with mfa" {
|
||||
require.NoError(t, model.DB.Create(&model.TwoFA{UserId: user.Id, Secret: "JBSWY3DPEHPK3PXP", IsEnabled: true}).Error)
|
||||
method = service.VerificationMethodTwoFA
|
||||
}
|
||||
flow := startSecurityEmailBinding(t, identity, "New@Example.com", method)
|
||||
assert.Equal(t, "new@example.com", flow.Email)
|
||||
assert.Equal(t, scenario == "replace without mfa", flow.OldEmailRequired)
|
||||
newCode, oldCode := mailbox.code(t, flow.Email), ""
|
||||
_, state, err := model.GetEmailBinding(identity, flow.FlowToken)
|
||||
require.NoError(t, err)
|
||||
assert.NotEqual(t, newCode, state.NewCodeHash)
|
||||
assert.True(t, common.ValidatePasswordAndHash(newCode, state.NewCodeHash))
|
||||
if flow.OldEmailRequired {
|
||||
oldCode = mailbox.code(t, previous)
|
||||
_, err := service.FinishEmailBinding(identity, flow.FlowToken, newCode, "")
|
||||
assert.ErrorIs(t, err, model.ErrEmailBindingCodeInvalid)
|
||||
stored, err := model.GetUserById(user.Id, false)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, previous, stored.Email)
|
||||
}
|
||||
request, err := common.Marshal(map[string]string{"flow_token": flow.FlowToken, "new_code": newCode, "old_code": oldCode})
|
||||
require.NoError(t, err)
|
||||
response := securityEnrollmentRequest("POST", "/api/oauth/email/bind", string(request), "", identity, EmailBind)
|
||||
var result securityEnrollmentResponse
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result))
|
||||
require.True(t, result.Success, response.Body.String())
|
||||
stored, err := model.GetUserById(user.Id, false)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, flow.Email, stored.Email)
|
||||
_, err = service.FinishEmailBinding(identity, flow.FlowToken, newCode, oldCode)
|
||||
assert.ErrorIs(t, err, model.ErrAuthFlowConsumed)
|
||||
legacy := securityEnrollmentRequest("POST", "/api/oauth/email/bind", `{"email":"other@example.com","code":"123456"}`, "", identity, EmailBind)
|
||||
assert.Contains(t, legacy.Body.String(), `"success":false`)
|
||||
var audits []model.AuditLog
|
||||
require.NoError(t, model.LOG_DB.Find(&audits).Error)
|
||||
require.NotEmpty(t, audits)
|
||||
assert.False(t, audits[len(audits)-1].Success, "a rejected legacy request must be recorded as failed")
|
||||
encoded, err := common.Marshal(audits)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, string(encoded), "user.binding_bind")
|
||||
assert.NotContains(t, string(encoded), flow.FlowToken)
|
||||
assert.NotContains(t, string(encoded), newCode)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecurityAccountEmailResendAndAttemptLimit(t *testing.T) {
|
||||
_, identity := setupSecurityEnrollmentTest(t)
|
||||
mailbox := newSecurityMailbox(t)
|
||||
flow := startSecurityEmailBinding(t, identity, "new@example.com", service.VerificationMethodPassword)
|
||||
_, err := service.ResendAccountEmailBinding(identity, flow.FlowToken)
|
||||
assert.ErrorIs(t, err, model.ErrEmailBindingResendWait)
|
||||
_, err = service.FinishEmailBinding(identity, flow.FlowToken, "invalid", "")
|
||||
assert.ErrorIs(t, err, model.ErrEmailBindingCodeInvalid)
|
||||
stored, state, err := model.GetEmailBinding(identity, flow.FlowToken)
|
||||
require.NoError(t, err)
|
||||
oldHash := state.NewCodeHash
|
||||
state.ResendAt = time.Now().Add(-time.Second).Unix()
|
||||
payload, err := common.Marshal(state)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, model.DB.Model(stored).Update("payload", string(payload)).Error)
|
||||
replacement, err := service.ResendAccountEmailBinding(identity, flow.FlowToken)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, flow.ExpiresAt, replacement.ExpiresAt)
|
||||
_, state, err = model.GetEmailBinding(identity, flow.FlowToken)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, state.FailedAttempts)
|
||||
assert.NotEqual(t, oldHash, state.NewCodeHash)
|
||||
assert.True(t, common.ValidatePasswordAndHash(mailbox.code(t, flow.Email), state.NewCodeHash))
|
||||
for attempt := 2; attempt <= model.EmailBindingMaxAttempts; attempt++ {
|
||||
_, err = service.FinishEmailBinding(identity, flow.FlowToken, "invalid", "")
|
||||
if attempt < model.EmailBindingMaxAttempts {
|
||||
assert.ErrorIs(t, err, model.ErrEmailBindingCodeInvalid)
|
||||
} else {
|
||||
assert.ErrorIs(t, err, model.ErrEmailBindingLocked)
|
||||
}
|
||||
}
|
||||
_, err = service.FinishEmailBinding(identity, flow.FlowToken, mailbox.code(t, flow.Email), "")
|
||||
assert.ErrorIs(t, err, model.ErrEmailBindingLocked)
|
||||
}
|
||||
|
||||
func TestSecurityAccountEmailConcurrentClaimsHaveOneOwner(t *testing.T) {
|
||||
user, firstIdentity := setupSecurityEnrollmentTest(t)
|
||||
mailbox := newSecurityMailbox(t)
|
||||
other := &model.User{Username: "other-user", AffCode: "other-account", Group: "default", Password: user.Password, Status: common.UserStatusEnabled, Role: common.RoleCommonUser, AuthVersion: 1}
|
||||
require.NoError(t, model.DB.Create(other).Error)
|
||||
require.NoError(t, model.PublishUserAuthCache(other.Id))
|
||||
bundle, err := service.CreateLoginSession(other.Id, "password", "127.0.0.1", "other-user")
|
||||
require.NoError(t, err)
|
||||
secondIdentity, err := service.ParseAccessToken(bundle.AccessToken)
|
||||
require.NoError(t, err)
|
||||
start, results := make(chan struct{}), make(chan error, 2)
|
||||
for _, identity := range []service.AuthIdentity{firstIdentity, secondIdentity} {
|
||||
flow := startSecurityEmailBinding(t, identity, "shared@example.com", service.VerificationMethodPassword)
|
||||
code := mailbox.code(t, flow.Email)
|
||||
go func(identity service.AuthIdentity, token, code string) {
|
||||
<-start
|
||||
_, err := service.FinishEmailBinding(identity, token, code, "")
|
||||
results <- err
|
||||
}(identity, flow.FlowToken, code)
|
||||
}
|
||||
close(start)
|
||||
first, second := <-results, <-results
|
||||
assert.NotEqual(t, first == nil, second == nil, "only one account may claim the address: %v / %v", first, second)
|
||||
var owners int64
|
||||
require.NoError(t, model.DB.Model(&model.User{}).Where("email = ?", "shared@example.com").Count(&owners).Error)
|
||||
assert.EqualValues(t, 1, owners)
|
||||
}
|
||||
|
||||
func TestSecurityAccountEmailRejectsChangedAuthorization(t *testing.T) {
|
||||
for _, scenario := range []string{"other session", "expired", "email changed", "mfa enabled", "notification failure"} {
|
||||
t.Run(scenario, func(t *testing.T) {
|
||||
user, identity := setupSecurityEnrollmentTest(t)
|
||||
mailbox := newSecurityMailbox(t)
|
||||
flow := startSecurityEmailBinding(t, identity, "new@example.com", service.VerificationMethodPassword)
|
||||
code := mailbox.code(t, flow.Email)
|
||||
stored, _, err := model.GetEmailBinding(identity, flow.FlowToken)
|
||||
require.NoError(t, err)
|
||||
switch scenario {
|
||||
case "other session":
|
||||
identity.SessionID = "different-session"
|
||||
case "expired":
|
||||
require.NoError(t, model.DB.Model(stored).Update("expires_at", time.Now().Add(-time.Second)).Error)
|
||||
case "email changed":
|
||||
require.NoError(t, model.DB.Model(user).Update("email", "changed@example.com").Error)
|
||||
case "mfa enabled":
|
||||
require.NoError(t, model.DB.Create(&model.TwoFA{UserId: user.Id, Secret: "JBSWY3DPEHPK3PXP", IsEnabled: true}).Error)
|
||||
case "notification failure":
|
||||
common.SMTPServer = ""
|
||||
}
|
||||
request, err := common.Marshal(map[string]string{"flow_token": flow.FlowToken, "new_code": code})
|
||||
require.NoError(t, err)
|
||||
response := securityEnrollmentRequest("POST", "/api/oauth/email/bind", string(request), "", identity, EmailBind)
|
||||
var result securityEnrollmentResponse
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result))
|
||||
assert.Equal(t, scenario == "notification failure", result.Success, response.Body.String())
|
||||
if scenario == "notification failure" {
|
||||
assert.Contains(t, string(result.Data), `"notification_warning":true`)
|
||||
}
|
||||
current, err := model.GetUserById(user.Id, false)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, scenario == "notification failure", current.Email == flow.Email)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecurityAccountOAuthBindingRejectsInvalidFlow(t *testing.T) {
|
||||
for _, scenario := range []string{"success and replay", "other session", "wrong provider", "expired", "old flow", "mfa enabled"} {
|
||||
t.Run(scenario, func(t *testing.T) {
|
||||
user, identity := setupSecurityEnrollmentTest(t)
|
||||
oauth.Register("account-oauth", &enrollmentOAuthProvider{externalID: "new-binding"})
|
||||
oauth.Register("other-oauth", &enrollmentOAuthProvider{externalID: "wrong-binding"})
|
||||
t.Cleanup(func() { oauth.Unregister("account-oauth"); oauth.Unregister("other-oauth") })
|
||||
operation := service.VerificationOperation{Scope: service.VerificationScopeAccountBind, Context: []byte(`{"provider":"account-oauth"}`)}
|
||||
proof := issueSecurityEnrollmentProof(t, identity, operation, service.VerificationMethodPassword)
|
||||
response := securityEnrollmentRequest("POST", "/api/oauth/state", `{"provider":"account-oauth","intent":"bind"}`, proof, identity, GenerateOAuthCode)
|
||||
var result securityEnrollmentResponse
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result))
|
||||
require.True(t, result.Success, response.Body.String())
|
||||
var started struct {
|
||||
FlowToken string `json:"flow_token"`
|
||||
}
|
||||
require.NoError(t, common.Unmarshal(result.Data, &started))
|
||||
flow, err := model.GetAuthFlow(started.FlowToken, model.AuthFlowMatch{Purpose: model.AuthFlowPurposeOAuth})
|
||||
require.NoError(t, err)
|
||||
provider := "account-oauth"
|
||||
switch scenario {
|
||||
case "other session":
|
||||
identity.SessionID = "different-session"
|
||||
case "wrong provider":
|
||||
provider = "other-oauth"
|
||||
case "expired":
|
||||
require.NoError(t, model.DB.Model(flow).Update("expires_at", time.Now().Add(-time.Second)).Error)
|
||||
case "old flow":
|
||||
require.NoError(t, model.DB.Model(flow).Update("payload", "{}").Error)
|
||||
case "mfa enabled":
|
||||
require.NoError(t, model.DB.Create(&model.TwoFA{UserId: user.Id, Secret: "JBSWY3DPEHPK3PXP", IsEnabled: true}).Error)
|
||||
}
|
||||
handler := func(c *gin.Context) { c.Params = gin.Params{{Key: "provider", Value: provider}}; HandleOAuth(c) }
|
||||
path := "/api/oauth/" + provider + "?state=" + started.FlowToken + "&code=provider-code"
|
||||
response = securityEnrollmentRequest("GET", path, "", "", identity, handler)
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result))
|
||||
assert.Equal(t, scenario == "success and replay", result.Success, response.Body.String())
|
||||
current, err := model.GetUserById(user.Id, false)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, scenario == "success and replay", current.GitHubId == "new-binding")
|
||||
if result.Success {
|
||||
replay := securityEnrollmentRequest("GET", path, "", "", identity, handler)
|
||||
assert.Contains(t, replay.Body.String(), `"success":false`)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecurityAccountFirstPasswordRace(t *testing.T) {
|
||||
user, identity := setupSecurityEnrollmentTest(t)
|
||||
require.NoError(t, model.DB.Model(user).Update("password", "").Error)
|
||||
require.NoError(t, model.DB.Create(&model.PasskeyCredential{UserID: user.Id, CredentialID: "existing-key", PublicKey: "public-key"}).Error)
|
||||
proof := issueSecurityEnrollmentProof(t, identity, service.VerificationOperation{Scope: service.VerificationScopePasswordSet}, service.VerificationMethodPasskey)
|
||||
request := `{"password":"initial-account-password!42"}`
|
||||
response := securityEnrollmentRequest("PUT", "/api/user/self", request, proof, identity, UpdateSelf)
|
||||
var result securityEnrollmentResponse
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result))
|
||||
require.True(t, result.Success, response.Body.String())
|
||||
user, identity = setupSecurityEnrollmentTest(t)
|
||||
require.NoError(t, model.DB.Model(user).Update("password", "").Error)
|
||||
start, results := make(chan struct{}), make(chan error, 2)
|
||||
for _, password := range []string{"first-password!42", "second-password!42"} {
|
||||
go func(password string) {
|
||||
<-start
|
||||
results <- model.ChangeUserPassword(identity, &model.User{Id: user.Id, Password: password}, true)
|
||||
}(password)
|
||||
}
|
||||
close(start)
|
||||
first, second := <-results, <-results
|
||||
assert.NotEqual(t, first == nil, second == nil, "only one concurrent first password may succeed: %v / %v", first, second)
|
||||
stored, err := model.GetUserById(user.Id, true)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, common.ValidatePasswordAndHash("first-password!42", stored.Password) || common.ValidatePasswordAndHash("second-password!42", stored.Password))
|
||||
}
|
||||
|
||||
func TestSecurityAccountUnbindPreservesUsableLoginMethod(t *testing.T) {
|
||||
for _, scenario := range []string{"password", "passkey", "email only", "twofa only", "disabled password", "disabled passkey"} {
|
||||
t.Run(scenario, func(t *testing.T) {
|
||||
user, identity := setupSecurityEnrollmentTest(t)
|
||||
previousPasswordEnabled := common.PasswordLoginEnabled
|
||||
t.Cleanup(func() { common.PasswordLoginEnabled = previousPasswordEnabled })
|
||||
common.PasswordLoginEnabled = scenario != "disabled password"
|
||||
require.NoError(t, model.DB.Create(&model.UserOAuthBinding{UserId: user.Id, ProviderId: 31, ProviderUserId: "linked-subject"}).Error)
|
||||
if scenario != "password" && scenario != "disabled password" {
|
||||
require.NoError(t, model.DB.Model(user).Updates(map[string]interface{}{"password": "", "email": "verified@example.com"}).Error)
|
||||
}
|
||||
if scenario == "passkey" || scenario == "disabled passkey" {
|
||||
require.NoError(t, model.DB.Create(&model.PasskeyCredential{UserID: user.Id, CredentialID: "existing-key", PublicKey: "public-key"}).Error)
|
||||
system_setting.GetPasskeySettings().Enabled = scenario == "passkey"
|
||||
}
|
||||
if scenario == "twofa only" {
|
||||
require.NoError(t, model.DB.Create(&model.TwoFA{UserId: user.Id, Secret: "JBSWY3DPEHPK3PXP", IsEnabled: true}).Error)
|
||||
}
|
||||
err := service.UnbindAccountOAuth(identity, 31)
|
||||
if scenario == "password" || scenario == "passkey" {
|
||||
require.NoError(t, err)
|
||||
} else {
|
||||
assert.ErrorIs(t, err, model.ErrLastLoginMethod)
|
||||
var binding model.UserOAuthBinding
|
||||
require.NoError(t, model.DB.Where("user_id = ? AND provider_id = ?", user.Id, 31).First(&binding).Error)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -193,14 +193,26 @@ func TestSecurityEnrollmentAccessTokenMethodPolicy(t *testing.T) {
|
||||
require.NoError(t, model.DB.Model(user).Update("wechat_id", "wechat-user").Error)
|
||||
}
|
||||
system_setting.GetPasskeySettings().Enabled = !test.disabledPasskey
|
||||
for _, scope := range []string{service.VerificationScopeAccessTokenGenerate, service.VerificationScopeAccessTokenRevoke} {
|
||||
passwordScope := service.VerificationScopePasswordChange
|
||||
if !test.password {
|
||||
passwordScope = service.VerificationScopePasswordSet
|
||||
}
|
||||
for _, scope := range []string{service.VerificationScopeAccessTokenGenerate, service.VerificationScopeAccessTokenRevoke,
|
||||
service.VerificationScopeAccountBind, service.VerificationScopeAccountUnbind, passwordScope} {
|
||||
requirements, err := service.GetVerificationRequirements(identity, scope)
|
||||
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.wechat {
|
||||
_, err := service.VerifySecurityInput(identity, service.VerificationInput{Scope: scope, Method: "session"})
|
||||
input := service.VerificationInput{Scope: scope, Method: "session"}
|
||||
switch scope {
|
||||
case service.VerificationScopeAccountBind:
|
||||
input.Context = []byte(`{"provider":"email","email":"new@example.com"}`)
|
||||
case service.VerificationScopeAccountUnbind:
|
||||
input.Context = []byte(`{"provider_id":1}`)
|
||||
}
|
||||
_, err := service.VerifySecurityInput(identity, input)
|
||||
assert.ErrorIs(t, err, service.ErrProofMethod)
|
||||
}
|
||||
}
|
||||
@@ -1420,6 +1432,11 @@ func TestSecurityEnrollmentTelegramAndWeChatFirstFactor(t *testing.T) {
|
||||
}
|
||||
var body securityEnrollmentResponse
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body))
|
||||
if provider == "wechat" {
|
||||
assert.False(t, body.Success)
|
||||
assert.NotContains(t, response.Body.String(), "proof_token")
|
||||
return
|
||||
}
|
||||
require.True(t, body.Success, response.Body.String())
|
||||
var proof service.SecurityProof
|
||||
require.NoError(t, common.Unmarshal(body.Data, &proof))
|
||||
@@ -1439,8 +1456,8 @@ func TestSecurityEnrollmentTelegramAndWeChatFirstFactor(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecurityEnrollmentWeChatExceptionRemainsNarrow(t *testing.T) {
|
||||
for _, scenario := range []string{"password", "passkey", "locked 2fa", "telegram", "github", "disabled custom binding", "no binding", "binding storage failure", "revoked session"} {
|
||||
func TestSecurityEnrollmentNeverTrustsSessionForFirstFactor(t *testing.T) {
|
||||
for _, scenario := range []string{"wechat only", "password", "passkey", "locked 2fa", "telegram", "github", "disabled custom binding", "no binding", "binding storage failure", "revoked session"} {
|
||||
t.Run(scenario, func(t *testing.T) {
|
||||
user, identity := setupSecurityEnrollmentTest(t)
|
||||
require.NoError(t, model.DB.Model(user).Updates(map[string]any{"password": "", "wechat_id": "wechat-user"}).Error)
|
||||
@@ -1555,7 +1572,9 @@ func TestSecurityEnrollmentRejectsChangedFirstFactorPolicy(t *testing.T) {
|
||||
} else {
|
||||
require.NoError(t, model.DB.Model(user).Update("wechat_id", "wechat-user").Error)
|
||||
proof, err = service.VerifySecurityInput(identity, service.VerificationInput{Scope: "2fa.setup", Method: "session"})
|
||||
require.NoError(t, err)
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, proof)
|
||||
return
|
||||
}
|
||||
_, err = service.ConsumeOperationProof(proof.ProofToken, identity, service.VerificationOperation{Scope: "passkey.register"})
|
||||
assert.Error(t, err)
|
||||
|
||||
+3
-3
@@ -85,16 +85,16 @@ func PostSetup(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if len(req.Password) < 8 {
|
||||
if err := common.ValidateNewAccountPassword(req.Password); err != nil {
|
||||
c.JSON(200, gin.H{
|
||||
"success": false,
|
||||
"message": "密码长度至少为8个字符",
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Create root user
|
||||
hashedPassword, err := common.Password2Hash(req.Password)
|
||||
hashedPassword, err := common.HashAccountPassword(req.Password)
|
||||
if err != nil {
|
||||
c.JSON(200, gin.H{
|
||||
"success": false,
|
||||
|
||||
@@ -156,7 +156,11 @@ func (fixture *telegramOAuthFixture) authorization(t *testing.T, intent string,
|
||||
t.Helper()
|
||||
request, err := common.Marshal(oauthStateRequest{Provider: "telegram", Intent: intent, Scope: scope})
|
||||
require.NoError(t, err)
|
||||
response := securityEnrollmentRequest("POST", "/api/oauth/state", string(request), "", identity, GenerateOAuthCode)
|
||||
proof := ""
|
||||
if intent == "bind" {
|
||||
proof = issueSecurityEnrollmentProof(t, identity, service.VerificationOperation{Scope: service.VerificationScopeAccountBind, Context: []byte(`{"provider":"telegram"}`)}, service.VerificationMethodPassword)
|
||||
}
|
||||
response := securityEnrollmentRequest("POST", "/api/oauth/state", string(request), proof, identity, GenerateOAuthCode)
|
||||
var body securityEnrollmentResponse
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &body))
|
||||
require.True(t, body.Success, response.Body.String())
|
||||
@@ -428,7 +432,7 @@ func TestTelegramOAuthConfigurationAndLegacyEndpoints(t *testing.T) {
|
||||
|
||||
func TestTelegramOAuthConcurrentBindingHasSingleOwner(t *testing.T) {
|
||||
fixture := setupTelegramOAuthTest(t)
|
||||
other := &model.User{Username: "other-owner", AffCode: "other-owner", Status: common.UserStatusEnabled, AuthVersion: 1}
|
||||
other := &model.User{Username: "other-owner", AffCode: "other-owner", Password: fixture.user.Password, Status: common.UserStatusEnabled, AuthVersion: 1}
|
||||
require.NoError(t, model.DB.Create(other).Error)
|
||||
bundle, err := service.CreateLoginSession(other.Id, "password", "127.0.0.1", "test")
|
||||
require.NoError(t, err)
|
||||
|
||||
+46
-117
@@ -34,11 +34,6 @@ type LoginRequest struct {
|
||||
EncryptionKeyID string `json:"encryption_key_id"`
|
||||
}
|
||||
|
||||
var (
|
||||
errUserPasswordUnset = errors.New("user password is not set")
|
||||
errOriginalPasswordFail = errors.New("original password is incorrect")
|
||||
)
|
||||
|
||||
func GetPasswordEncryptionKey(c *gin.Context) {
|
||||
if !common.PasswordLoginEncryptionEnabled {
|
||||
common.ApiSuccess(c, gin.H{"enabled": false})
|
||||
@@ -190,7 +185,7 @@ func setupLoginAtAuthVersion(user *model.User, expectedAuthVersion int64, c *gin
|
||||
common.ApiErrorI18n(c, i18n.MsgAuthUserBanned)
|
||||
return
|
||||
}
|
||||
currentUser, err := model.GetUserById(user.Id, false)
|
||||
currentUser, err := model.GetSelfUserById(user.Id)
|
||||
if err != nil {
|
||||
common.ApiError(c, err)
|
||||
return
|
||||
@@ -483,7 +478,7 @@ func GetAffCode(c *gin.Context) {
|
||||
func GetSelf(c *gin.Context) {
|
||||
id := c.GetInt("id")
|
||||
userRole := c.GetInt("role")
|
||||
user, err := model.GetUserById(id, false)
|
||||
user, err := model.GetSelfUserById(id)
|
||||
if err != nil {
|
||||
common.ApiError(c, err)
|
||||
return
|
||||
@@ -515,6 +510,7 @@ func buildSelfUserData(user *model.User) map[string]interface{} {
|
||||
"id": user.Id,
|
||||
"username": user.Username,
|
||||
"display_name": user.DisplayName,
|
||||
"has_password": user.HasPassword,
|
||||
"role": user.Role,
|
||||
"status": user.Status,
|
||||
"email": user.Email,
|
||||
@@ -676,10 +672,7 @@ func UpdateUser(c *gin.Context) {
|
||||
common.ApiErrorI18n(c, i18n.MsgInvalidParams)
|
||||
return
|
||||
}
|
||||
if updatedUser.Password == "" {
|
||||
updatedUser.Password = "$I_LOVE_U" // make Validator happy :)
|
||||
}
|
||||
if err := common.Validate.Struct(&updatedUser); err != nil {
|
||||
if err := common.Validate.StructExcept(&updatedUser, "Password"); err != nil {
|
||||
common.ApiErrorI18n(c, i18n.MsgUserInputInvalid, map[string]any{"Error": err.Error()})
|
||||
return
|
||||
}
|
||||
@@ -698,9 +691,6 @@ func UpdateUser(c *gin.Context) {
|
||||
common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
|
||||
return
|
||||
}
|
||||
if updatedUser.Password == "$I_LOVE_U" {
|
||||
updatedUser.Password = "" // rollback to what it should be
|
||||
}
|
||||
updatePassword := updatedUser.Password != ""
|
||||
authzTouched := false
|
||||
if err := model.DB.Transaction(func(tx *gorm.DB) error {
|
||||
@@ -789,8 +779,19 @@ func UpdateSelf(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
passwordRequested := false
|
||||
if value, exists := requestData["password"]; exists && value != nil {
|
||||
password, isString := value.(string)
|
||||
passwordRequested = !isString || password != ""
|
||||
}
|
||||
succeeded, notificationFailed := false, false
|
||||
if passwordRequested {
|
||||
defer func() {
|
||||
recordUserSecurityAudit(c, c.GetInt("id"), "user.password_change", map[string]interface{}{"success": succeeded, "notification_failed": notificationFailed})
|
||||
}()
|
||||
}
|
||||
// 检查是否是用户设置更新请求 (sidebar_modules 或 language)
|
||||
if sidebarModules, sidebarExists := requestData["sidebar_modules"]; sidebarExists {
|
||||
if sidebarModules, sidebarExists := requestData["sidebar_modules"]; sidebarExists && !passwordRequested {
|
||||
userId := c.GetInt("id")
|
||||
user, err := model.GetUserById(userId, false)
|
||||
if err != nil {
|
||||
@@ -816,7 +817,7 @@ func UpdateSelf(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 检查是否是语言偏好更新请求
|
||||
if language, langExists := requestData["language"]; langExists {
|
||||
if language, langExists := requestData["language"]; langExists && !passwordRequested {
|
||||
userId := c.GetInt("id")
|
||||
user, err := model.GetUserById(userId, false)
|
||||
if err != nil {
|
||||
@@ -853,10 +854,7 @@ func UpdateSelf(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if user.Password == "" {
|
||||
user.Password = "$I_LOVE_U" // make Validator happy :)
|
||||
}
|
||||
if err := common.Validate.Struct(&user); err != nil {
|
||||
if err := common.Validate.StructExcept(&user, "Password"); err != nil {
|
||||
common.ApiErrorI18n(c, i18n.MsgInvalidInput)
|
||||
return
|
||||
}
|
||||
@@ -867,52 +865,51 @@ func UpdateSelf(c *gin.Context) {
|
||||
Password: user.Password,
|
||||
DisplayName: user.DisplayName,
|
||||
}
|
||||
if user.Password == "$I_LOVE_U" {
|
||||
user.Password = "" // rollback to what it should be
|
||||
cleanUser.Password = ""
|
||||
}
|
||||
updatePassword, err := checkUpdatePassword(user.OriginalPassword, user.Password, cleanUser.Id)
|
||||
if err != nil {
|
||||
if errors.Is(err, errUserPasswordUnset) {
|
||||
common.ApiErrorI18n(c, i18n.MsgUserPasswordUnset)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, errOriginalPasswordFail) {
|
||||
common.ApiErrorI18n(c, i18n.MsgUserOriginalPasswordError)
|
||||
return
|
||||
}
|
||||
common.ApiError(c, err)
|
||||
return
|
||||
}
|
||||
if updatePassword {
|
||||
if user.Password != "" {
|
||||
identity, ok := middleware.GetSessionAuthIdentity(c)
|
||||
if !ok {
|
||||
common.ApiError(c, errors.New("当前认证方式不支持安全验证"))
|
||||
writeSecurityOperationError(c, service.ErrAuthTokenInvalid)
|
||||
return
|
||||
}
|
||||
if err := model.DB.Transaction(func(tx *gorm.DB) error {
|
||||
return cleanUser.UpdateWithTx(tx, true)
|
||||
}); err != nil {
|
||||
common.ApiError(c, err)
|
||||
current, err := model.GetUserById(identity.UserID, true)
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
firstPassword := current.Password == ""
|
||||
scope := service.VerificationScopePasswordChange
|
||||
if firstPassword {
|
||||
scope = service.VerificationScopePasswordSet
|
||||
}
|
||||
if middleware.RequireSecurityProof(c, service.VerificationOperation{Scope: scope}) == nil {
|
||||
return
|
||||
}
|
||||
cleanUser.OriginalPassword = user.OriginalPassword
|
||||
if err := model.ChangeUserPassword(identity, &cleanUser, firstPassword); err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
succeeded = true
|
||||
notificationFailed = service.NotifyAccountSecurityChange(current.Email, "Password updated") != nil
|
||||
if err := model.PublishUserAuthCache(cleanUser.Id); err != nil {
|
||||
common.ApiError(c, err)
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
bundle, err := service.AdvanceCurrentSessionToUserVersion(identity, "password_changed")
|
||||
if err != nil {
|
||||
common.ApiError(c, err)
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "",
|
||||
"data": gin.H{
|
||||
"access_token": bundle.AccessToken,
|
||||
"token_type": bundle.TokenType,
|
||||
"access_expires_at": bundle.AccessExpiresAt,
|
||||
"session": bundle.Session,
|
||||
"access_token": bundle.AccessToken,
|
||||
"token_type": bundle.TokenType,
|
||||
"access_expires_at": bundle.AccessExpiresAt,
|
||||
"session": bundle.Session,
|
||||
"has_password": true,
|
||||
"notification_warning": notificationFailed,
|
||||
},
|
||||
})
|
||||
return
|
||||
@@ -926,29 +923,6 @@ func UpdateSelf(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
func checkUpdatePassword(originalPassword string, newPassword string, userId int) (updatePassword bool, err error) {
|
||||
if newPassword == "" {
|
||||
return
|
||||
}
|
||||
var currentUser *model.User
|
||||
currentUser, err = model.GetUserById(userId, true)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 密码不为空,需要验证原密码
|
||||
if currentUser.Password == "" {
|
||||
err = errUserPasswordUnset
|
||||
return
|
||||
}
|
||||
if !common.ValidatePasswordAndHash(originalPassword, currentUser.Password) {
|
||||
err = errOriginalPasswordFail
|
||||
return
|
||||
}
|
||||
updatePassword = true
|
||||
return
|
||||
}
|
||||
|
||||
func DeleteUser(c *gin.Context) {
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
@@ -1272,51 +1246,6 @@ func ManageUser(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
type emailBindRequest struct {
|
||||
Email string `json:"email"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
func EmailBind(c *gin.Context) {
|
||||
var req emailBindRequest
|
||||
if err := common.DecodeJson(c.Request.Body, &req); err != nil {
|
||||
common.ApiError(c, errors.New("invalid request body"))
|
||||
return
|
||||
}
|
||||
email := req.Email
|
||||
email = model.NormalizeEmail(email)
|
||||
code := req.Code
|
||||
if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
|
||||
common.ApiErrorI18n(c, i18n.MsgUserVerificationCodeError)
|
||||
return
|
||||
}
|
||||
user := model.User{
|
||||
Id: c.GetInt("id"),
|
||||
}
|
||||
if user.Id == 0 {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "message": "not authenticated"})
|
||||
return
|
||||
}
|
||||
err := user.FillUserById()
|
||||
if err != nil {
|
||||
common.ApiError(c, err)
|
||||
return
|
||||
}
|
||||
if err := model.BindEmailToUser(&user, email); err != nil {
|
||||
if errors.Is(err, model.ErrEmailAlreadyTaken) {
|
||||
common.ApiErrorI18n(c, i18n.MsgUserEmailAlreadyTaken)
|
||||
return
|
||||
}
|
||||
common.ApiError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
type topUpRequest struct {
|
||||
Key string `json:"key"`
|
||||
}
|
||||
|
||||
+34
-8
@@ -6,12 +6,16 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/middleware"
|
||||
"github.com/QuantumNous/new-api/model"
|
||||
"github.com/QuantumNous/new-api/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type wechatLoginResponse struct {
|
||||
@@ -125,6 +129,15 @@ type wechatBindRequest struct {
|
||||
}
|
||||
|
||||
func WeChatBind(c *gin.Context) {
|
||||
identity, ok := middleware.GetSessionAuthIdentity(c)
|
||||
if !ok {
|
||||
writeSecurityOperationError(c, service.ErrAuthTokenInvalid)
|
||||
return
|
||||
}
|
||||
succeeded, notificationFailed := false, false
|
||||
defer func() {
|
||||
recordUserSecurityAudit(c, identity.UserID, "user.binding_bind", map[string]interface{}{"provider": "wechat", "success": succeeded, "notification_failed": notificationFailed})
|
||||
}()
|
||||
if !common.WeChatAuthEnabled {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "管理员未开启通过微信登录以及注册",
|
||||
@@ -140,7 +153,15 @@ func WeChatBind(c *gin.Context) {
|
||||
})
|
||||
return
|
||||
}
|
||||
code := req.Code
|
||||
code := strings.TrimSpace(req.Code)
|
||||
context, err := common.Marshal(service.AccountBindingContext{Provider: "wechat", Code: code})
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
if middleware.RequireSecurityProof(c, service.VerificationOperation{Scope: service.VerificationScopeAccountBind, Context: context}) == nil {
|
||||
return
|
||||
}
|
||||
wechatId, err := getWeChatIdByCode(code)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
@@ -156,19 +177,24 @@ func WeChatBind(c *gin.Context) {
|
||||
})
|
||||
return
|
||||
}
|
||||
userId := c.GetInt("id")
|
||||
if userId == 0 {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "message": "未登录"})
|
||||
return
|
||||
}
|
||||
// 只更新绑定列,避免完整用户快照覆盖并发的封禁、降权或分组变更。
|
||||
if err := model.UpdateUserBindColumn(userId, "wechat_id", wechatId); err != nil {
|
||||
common.ApiError(c, err)
|
||||
if err := model.DB.Transaction(func(tx *gorm.DB) error {
|
||||
return model.UpdateUserBindColumnForSessionWithTx(tx, identity, "wechat_id", wechatId)
|
||||
}); err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
succeeded = true
|
||||
user, err := model.GetUserById(identity.UserID, false)
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
notificationFailed = service.NotifyAccountSecurityChange(user.Email, "WeChat account linked") != nil
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "",
|
||||
"data": gin.H{"notification_warning": notificationFailed},
|
||||
})
|
||||
return
|
||||
}
|
||||
@@ -76,6 +76,7 @@ func RequireSecurityProof(c *gin.Context, operation service.VerificationOperatio
|
||||
}
|
||||
|
||||
func securityProofError(c *gin.Context, code, message string) {
|
||||
c.Set("security_error_code", code)
|
||||
c.JSON(http.StatusForbidden, gin.H{
|
||||
"success": false,
|
||||
"message": message,
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrCurrentPasswordInvalid = errors.New("Current password is incorrect.")
|
||||
ErrAccountPasswordState = errors.New("Password settings have changed. Reload the page and try again.")
|
||||
ErrLastLoginMethod = errors.New("Add another login method before unlinking this account.")
|
||||
ErrAccountBindingChanged = errors.New("Account bindings have changed. Start this operation again.")
|
||||
)
|
||||
|
||||
// ChangeUserPassword rechecks the authorized session, password state and current
|
||||
// password under the same user lock as the credential update. Only self-profile
|
||||
// fields are accepted; a stale snapshot cannot restore roles or account status.
|
||||
func ChangeUserPassword(identity AuthSessionIdentity, update *User, firstPassword bool) error {
|
||||
hash, err := common.HashAccountPassword(update.Password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return DB.Transaction(func(tx *gorm.DB) error {
|
||||
if err := ValidateAuthSessionWithTx(tx, identity); err != nil {
|
||||
return err
|
||||
}
|
||||
var current User
|
||||
if err := tx.First(¤t, identity.UserID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if firstPassword != (current.Password == "") {
|
||||
return ErrAccountPasswordState
|
||||
}
|
||||
if !firstPassword && !common.ValidatePasswordAndHash(update.OriginalPassword, current.Password) {
|
||||
return ErrCurrentPasswordInvalid
|
||||
}
|
||||
if current.Password != "" && common.ValidatePasswordAndHash(update.Password, current.Password) {
|
||||
return common.ErrAccountPasswordSame
|
||||
}
|
||||
changes := map[string]any{"password": hash}
|
||||
if update.Username != "" {
|
||||
changes["username"] = update.Username
|
||||
}
|
||||
if update.DisplayName != "" {
|
||||
changes["display_name"] = update.DisplayName
|
||||
}
|
||||
if _, err := IncrementUserAuthVersionWithTx(tx, identity.UserID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Model(&User{}).Where("id = ?", identity.UserID).Updates(changes).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.First(update, identity.UserID).Error
|
||||
})
|
||||
}
|
||||
|
||||
// AccountLoginMethods is a snapshot of administrator-enabled login mechanisms.
|
||||
// Enrollment is checked inside the transaction, not trusted from this snapshot.
|
||||
type AccountLoginMethods struct {
|
||||
Password bool
|
||||
Passkey bool
|
||||
WeChat bool
|
||||
OAuthColumns []string
|
||||
CustomProviderIDs []int
|
||||
}
|
||||
|
||||
func UnbindUserOAuthForSession(identity AuthSessionIdentity, providerID int, enabled AccountLoginMethods) error {
|
||||
return DB.Transaction(func(tx *gorm.DB) error {
|
||||
if err := ValidateAuthSessionWithTx(tx, identity); err != nil {
|
||||
return err
|
||||
}
|
||||
var current User
|
||||
if err := tx.First(¤t, identity.UserID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
var binding UserOAuthBinding
|
||||
if err := tx.Where("user_id = ? AND provider_id = ?", identity.UserID, providerID).First(&binding).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrAccountBindingChanged
|
||||
}
|
||||
return err
|
||||
}
|
||||
hasLogin := enabled.Password && current.Password != "" || enabled.WeChat && current.WeChatId != ""
|
||||
columns := map[string]string{
|
||||
"github_id": current.GitHubId, "discord_id": current.DiscordId,
|
||||
"oidc_id": current.OidcId, "linux_do_id": current.LinuxDOId, "telegram_id": current.TelegramId,
|
||||
}
|
||||
for _, column := range enabled.OAuthColumns {
|
||||
hasLogin = hasLogin || columns[column] != ""
|
||||
}
|
||||
if !hasLogin && enabled.Passkey {
|
||||
var count int64
|
||||
if err := tx.Model(&PasskeyCredential{}).Where("user_id = ?", identity.UserID).Count(&count).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
hasLogin = count > 0
|
||||
}
|
||||
if !hasLogin && len(enabled.CustomProviderIDs) > 0 {
|
||||
var count int64
|
||||
if err := tx.Model(&UserOAuthBinding{}).Where("user_id = ? AND provider_id <> ? AND provider_id IN ?", identity.UserID, providerID, enabled.CustomProviderIDs).Count(&count).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
hasLogin = count > 0
|
||||
}
|
||||
if !hasLogin {
|
||||
return ErrLastLoginMethod
|
||||
}
|
||||
return tx.Delete(&binding).Error
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateUserBindColumnForSessionWithTx(tx *gorm.DB, identity AuthSessionIdentity, column, value string) error {
|
||||
if !userBindColumns[column] || value == "" {
|
||||
return ErrAccountBindingChanged
|
||||
}
|
||||
if err := ValidateAuthSessionWithTx(tx, identity); err != nil {
|
||||
return err
|
||||
}
|
||||
// Preserve the existing ownership check within the transaction and update
|
||||
// only the chosen binding column, never a complete user snapshot.
|
||||
var count int64
|
||||
if err := tx.Model(&User{}).Where(column+" = ? AND id <> ?", value, identity.UserID).Count(&count).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if count != 0 {
|
||||
return ErrExternalIdentityAlreadyClaimed
|
||||
}
|
||||
return tx.Model(&User{}).Where("id = ?", identity.UserID).Update(column, value).Error
|
||||
}
|
||||
|
||||
func UpdateUserOAuthBindingForSessionWithTx(tx *gorm.DB, identity AuthSessionIdentity, providerID int, subject string) error {
|
||||
if providerID <= 0 || subject == "" || len(subject) > 256 {
|
||||
return ErrAccountBindingChanged
|
||||
}
|
||||
if err := ValidateAuthSessionWithTx(tx, identity); err != nil {
|
||||
return err
|
||||
}
|
||||
var binding UserOAuthBinding
|
||||
err := tx.Where("user_id = ? AND provider_id = ?", identity.UserID, providerID).First(&binding).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return CreateUserOAuthBindingWithTx(tx, &UserOAuthBinding{UserId: identity.UserID, ProviderId: providerID, ProviderUserId: subject})
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// The existing unique provider/subject index rejects concurrent ownership.
|
||||
return tx.Model(&binding).Update("provider_user_id", subject).Error
|
||||
}
|
||||
@@ -27,6 +27,7 @@ const (
|
||||
AuthFlowIntentVerify = "verify"
|
||||
AuthFlowPurposeTwoFASetup = "2fa_setup"
|
||||
AuthFlowPurposeSecurityProof = "security_proof"
|
||||
AuthFlowPurposeEmailBinding = "email_binding"
|
||||
AuthFlowTokenBytes = 32
|
||||
AuthFlowDefaultCleanupRetention = 24 * time.Hour
|
||||
)
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
EmailBindingTTL = 10 * time.Minute
|
||||
EmailBindingResendDelay = time.Minute
|
||||
EmailBindingMaxAttempts = 5
|
||||
)
|
||||
|
||||
var (
|
||||
ErrEmailBindingCodeInvalid = errors.New("Email verification code is incorrect.")
|
||||
ErrEmailBindingLocked = errors.New("Too many incorrect codes. Start email verification again.")
|
||||
ErrEmailBindingResendWait = errors.New("Please wait before requesting another verification code.")
|
||||
)
|
||||
|
||||
// EmailBindingState is server-owned payload. It deliberately contains only
|
||||
// salted code hashes and an already-consumed authorization, never usable codes
|
||||
// or proof tokens. Resending must retain the deadline and failure counter.
|
||||
type EmailBindingState struct {
|
||||
Authorization *AuthFlowAuthorization `json:"authorization"`
|
||||
CurrentEmail string `json:"current_email"`
|
||||
Email string `json:"email"`
|
||||
NewCodeHash string `json:"new_code_hash"`
|
||||
OldCodeHash string `json:"old_code_hash,omitempty"`
|
||||
FailedAttempts int `json:"failed_attempts"`
|
||||
ResendAt int64 `json:"resend_at"`
|
||||
}
|
||||
|
||||
func CreateEmailBinding(identity AuthSessionIdentity, state EmailBindingState) (string, *AuthFlow, error) {
|
||||
var token string
|
||||
var flow *AuthFlow
|
||||
err := DB.Transaction(func(tx *gorm.DB) error {
|
||||
if err := validateEmailBindingAccountWithTx(tx, identity, &state); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ensureEmailAvailableWithTx(tx, state.Email, identity.UserID); err != nil {
|
||||
return err
|
||||
}
|
||||
payload, err := common.Marshal(state)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
token, flow, err = createAuthFlowWithTx(tx, AuthFlowCreate{
|
||||
Purpose: AuthFlowPurposeEmailBinding, UserId: identity.UserID, SessionId: identity.SessionID,
|
||||
Payload: string(payload), ExpiresAt: time.Now().Add(EmailBindingTTL),
|
||||
})
|
||||
return err
|
||||
})
|
||||
return token, flow, err
|
||||
}
|
||||
|
||||
func GetEmailBinding(identity AuthSessionIdentity, token string) (*AuthFlow, *EmailBindingState, error) {
|
||||
flow, err := GetAuthFlow(token, AuthFlowMatch{Purpose: AuthFlowPurposeEmailBinding, UserId: identity.UserID, SessionId: identity.SessionID})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var state EmailBindingState
|
||||
if err := common.UnmarshalJsonStr(flow.Payload, &state); err != nil {
|
||||
return nil, nil, ErrAuthFlowInvalid
|
||||
}
|
||||
return flow, &state, nil
|
||||
}
|
||||
|
||||
func ResendEmailBinding(identity AuthSessionIdentity, token, newCodeHash, oldCodeHash string) (*AuthFlow, *EmailBindingState, error) {
|
||||
var flow *AuthFlow
|
||||
var state *EmailBindingState
|
||||
err := DB.Transaction(func(tx *gorm.DB) error {
|
||||
var err error
|
||||
flow, state, err = lockEmailBindingWithTx(tx, identity, token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
now := time.Now()
|
||||
if state.ResendAt > now.Unix() {
|
||||
return ErrEmailBindingResendWait
|
||||
}
|
||||
if newCodeHash == "" || (state.OldCodeHash != "") != (oldCodeHash != "") {
|
||||
return ErrAuthFlowInvalid
|
||||
}
|
||||
state.NewCodeHash, state.OldCodeHash = newCodeHash, oldCodeHash
|
||||
state.ResendAt = now.Add(EmailBindingResendDelay).Unix()
|
||||
payload, err := common.Marshal(state)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(flow).Update("payload", string(payload)).Error
|
||||
})
|
||||
return flow, state, err
|
||||
}
|
||||
|
||||
// CompleteEmailBinding commits failed attempts even though verification fails.
|
||||
// Successful confirmation consumes the flow in the same transaction as the
|
||||
// email update, preserving the existing cross-database email ownership lock.
|
||||
func CompleteEmailBinding(identity AuthSessionIdentity, token, email, newCode, oldCode string) (*EmailBindingState, error) {
|
||||
var state *EmailBindingState
|
||||
var verificationError error
|
||||
err := DB.Transaction(func(tx *gorm.DB) error {
|
||||
// Acquire ownership protection before the first consistent read. Under
|
||||
// MySQL REPEATABLE READ, a snapshot created before this lock could hide
|
||||
// an address claimed by a concurrent transaction while we were waiting.
|
||||
if email == "" || email != NormalizeEmail(email) {
|
||||
return ErrAuthFlowInvalid
|
||||
}
|
||||
if err := lockNormalizedEmail(tx, email); err != nil {
|
||||
return err
|
||||
}
|
||||
flow, lockedState, err := lockEmailBindingWithTx(tx, identity, token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
state = lockedState
|
||||
if state.Email != email {
|
||||
return ErrAuthFlowInvalid
|
||||
}
|
||||
newCode, newCodeError := common.ValidateNumericCode(newCode)
|
||||
oldCode, oldCodeError := common.ValidateNumericCode(oldCode)
|
||||
newValid := newCodeError == nil && common.ValidatePasswordAndHash(newCode, state.NewCodeHash)
|
||||
oldValid := state.OldCodeHash == "" || oldCodeError == nil && common.ValidatePasswordAndHash(oldCode, state.OldCodeHash)
|
||||
if !newValid || !oldValid {
|
||||
state.FailedAttempts++
|
||||
verificationError = ErrEmailBindingCodeInvalid
|
||||
if state.FailedAttempts >= EmailBindingMaxAttempts {
|
||||
verificationError = ErrEmailBindingLocked
|
||||
}
|
||||
payload, err := common.Marshal(state)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(flow).Update("payload", string(payload)).Error
|
||||
}
|
||||
if err := ensureEmailAvailableWithTx(tx, state.Email, identity.UserID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Model(&User{}).Where("id = ?", identity.UserID).Update("email", state.Email).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(flow).Update("consumed_at", time.Now()).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return state, verificationError
|
||||
}
|
||||
|
||||
func lockEmailBindingWithTx(tx *gorm.DB, identity AuthSessionIdentity, token string) (*AuthFlow, *EmailBindingState, error) {
|
||||
match := AuthFlowMatch{Purpose: AuthFlowPurposeEmailBinding, UserId: identity.UserID, SessionId: identity.SessionID}
|
||||
// Make the first statement a write so SQLite does not have to upgrade a
|
||||
// deferred read transaction. A no-op update also locks the row on MySQL and
|
||||
// PostgreSQL; do not interpret dialect-dependent RowsAffected as success.
|
||||
if err := applyAuthFlowMatch(tx.Model(&AuthFlow{}), token, match).
|
||||
Where("consumed_at IS NULL AND expires_at > ?", time.Now()).
|
||||
UpdateColumn("payload", gorm.Expr("payload")).Error; err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var flow AuthFlow
|
||||
if err := applyAuthFlowMatch(tx, token, match).First(&flow).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil, ErrAuthFlowInvalid
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
if flow.ConsumedAt != nil {
|
||||
return nil, nil, ErrAuthFlowConsumed
|
||||
}
|
||||
if !flow.ExpiresAt.After(time.Now()) {
|
||||
return nil, nil, ErrAuthFlowExpired
|
||||
}
|
||||
var state EmailBindingState
|
||||
if err := common.UnmarshalJsonStr(flow.Payload, &state); err != nil {
|
||||
return nil, nil, ErrAuthFlowInvalid
|
||||
}
|
||||
if err := validateEmailBindingAccountWithTx(tx, identity, &state); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if state.FailedAttempts >= EmailBindingMaxAttempts {
|
||||
return nil, nil, ErrEmailBindingLocked
|
||||
}
|
||||
return &flow, &state, nil
|
||||
}
|
||||
|
||||
func validateEmailBindingAccountWithTx(tx *gorm.DB, identity AuthSessionIdentity, state *EmailBindingState) error {
|
||||
if state.Authorization == nil || state.Authorization.ProofID <= 0 || state.Authorization.AuthSessionIdentity != identity ||
|
||||
state.Authorization.Scope != "account.binding.bind" || state.Authorization.ContextHash == "" ||
|
||||
state.Email == "" || state.Email != NormalizeEmail(state.Email) || state.NewCodeHash == "" {
|
||||
return ErrAuthFlowInvalid
|
||||
}
|
||||
if err := ValidateAuthSessionWithTx(tx, identity); err != nil {
|
||||
return err
|
||||
}
|
||||
var user User
|
||||
if err := tx.Select("email").First(&user, identity.UserID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if NormalizeEmail(user.Email) != state.CurrentEmail || state.CurrentEmail == state.Email {
|
||||
return ErrAccountBindingChanged
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+37
-7
@@ -79,7 +79,8 @@ func resolveUserSortOptions(sortOptions []UserSortOptions) UserSortOptions {
|
||||
type User struct {
|
||||
Id int `json:"id"`
|
||||
Username string `json:"username" gorm:"unique;index" validate:"max=20"`
|
||||
Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"`
|
||||
Password string `json:"password" gorm:"not null;" validate:"min=8,max=128"`
|
||||
HasPassword bool `json:"-" gorm:"-:all"`
|
||||
OriginalPassword string `json:"original_password" gorm:"-:all"` // this field is only for Password change verification, don't save it to database!
|
||||
DisplayName string `json:"display_name" gorm:"index" validate:"max=20"`
|
||||
Role int `json:"role" gorm:"type:int;default:1"` // admin, common
|
||||
@@ -382,9 +383,16 @@ func EnsureEmailAvailable(email string, excludeUserID int) error {
|
||||
//
|
||||
// An empty email is allowed to repeat and needs no serialization.
|
||||
func withNormalizedEmailLock(tx *gorm.DB, email string, fn func(tx *gorm.DB) error) error {
|
||||
if err := lockNormalizedEmail(tx, email); err != nil {
|
||||
return err
|
||||
}
|
||||
return fn(tx)
|
||||
}
|
||||
|
||||
func lockNormalizedEmail(tx *gorm.DB, email string) error {
|
||||
email = NormalizeEmail(email)
|
||||
if email == "" {
|
||||
return fn(tx)
|
||||
return nil
|
||||
}
|
||||
switch {
|
||||
case common.UsingMainDatabase(common.DatabaseTypePostgreSQL):
|
||||
@@ -397,7 +405,7 @@ func withNormalizedEmailLock(tx *gorm.DB, email string, fn func(tx *gorm.DB) err
|
||||
return err
|
||||
}
|
||||
}
|
||||
return fn(tx)
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetMaxUserId() int {
|
||||
@@ -524,6 +532,28 @@ func GetUserById(id int, selectAll bool) (*User, error) {
|
||||
return &user, err
|
||||
}
|
||||
|
||||
// GetSelfUserById reads dashboard profile data and password existence in one
|
||||
// query. The password hash and management access token are never selected.
|
||||
func GetSelfUserById(id int) (*User, error) {
|
||||
if id == 0 {
|
||||
return nil, errors.New("id 为空!")
|
||||
}
|
||||
var profile struct {
|
||||
User
|
||||
HasPassword bool `gorm:"column:has_password"`
|
||||
}
|
||||
err := DB.Model(&User{}).Select([]string{
|
||||
"id", "username", "display_name", "role", "status", "email",
|
||||
"github_id", "discord_id", "oidc_id", "wechat_id", "telegram_id",
|
||||
"group", "quota", "used_quota", "request_count", "aff_code", "aff_count",
|
||||
"aff_quota", "aff_history", "inviter_id", "linux_do_id", "setting",
|
||||
"stripe_customer", "auth_version",
|
||||
"CASE WHEN password <> '' THEN 1 ELSE 0 END AS has_password",
|
||||
}).First(&profile, "id = ?", id).Error
|
||||
profile.User.HasPassword = profile.HasPassword
|
||||
return &profile.User, err
|
||||
}
|
||||
|
||||
func GetUserIdByAffCode(affCode string) (int, error) {
|
||||
if affCode == "" {
|
||||
return 0, errors.New("affCode 为空!")
|
||||
@@ -610,7 +640,7 @@ func (user *User) prepareForInsert(tx *gorm.DB) error {
|
||||
return nil
|
||||
}
|
||||
var err error
|
||||
user.Password, err = common.Password2Hash(user.Password)
|
||||
user.Password, err = common.HashAccountPassword(user.Password)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -789,7 +819,7 @@ func (user *User) Update(updatePassword bool) error {
|
||||
func (user *User) UpdateWithTx(tx *gorm.DB, updatePassword bool) error {
|
||||
var err error
|
||||
if updatePassword {
|
||||
user.Password, err = common.Password2Hash(user.Password)
|
||||
user.Password, err = common.HashAccountPassword(user.Password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -850,7 +880,7 @@ func (user *User) Edit(updatePassword bool) error {
|
||||
func (user *User) EditWithTx(tx *gorm.DB, updatePassword bool) error {
|
||||
var err error
|
||||
if updatePassword {
|
||||
user.Password, err = common.Password2Hash(user.Password)
|
||||
user.Password, err = common.HashAccountPassword(user.Password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1150,7 +1180,7 @@ func ResetUserPasswordByEmail(email string, password string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
hashedPassword, err := common.Password2Hash(password)
|
||||
hashedPassword, err := common.HashAccountPassword(password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -46,7 +46,9 @@ func SetApiRouter(router *gin.Engine) {
|
||||
apiRouter.POST("/user/reset", middleware.CriticalRateLimit(), anonymousRequestBodyLimit, controller.ResetPassword)
|
||||
// OAuth routes - specific routes must come before :provider wildcard
|
||||
apiRouter.POST("/oauth/state", middleware.CriticalRateLimit(), middleware.DisableCache(), middleware.TryUserAuth(), anonymousRequestBodyLimit, controller.GenerateOAuthCode)
|
||||
apiRouter.POST("/oauth/email/bind", middleware.UserAuth(), middleware.CriticalRateLimit(), controller.EmailBind)
|
||||
apiRouter.POST("/oauth/email/bind/start", middleware.UserAuth(), middleware.CriticalRateLimit(), middleware.UserCriticalRateLimit("account-security"), middleware.EmailVerificationRateLimit(), middleware.DisableCache(), controller.EmailBindStart)
|
||||
apiRouter.POST("/oauth/email/bind/resend", middleware.UserAuth(), middleware.CriticalRateLimit(), middleware.UserCriticalRateLimit("account-security"), middleware.EmailVerificationRateLimit(), middleware.DisableCache(), controller.EmailBindResend)
|
||||
apiRouter.POST("/oauth/email/bind", middleware.UserAuth(), middleware.CriticalRateLimit(), middleware.UserCriticalRateLimit("account-security"), middleware.DisableCache(), controller.EmailBind)
|
||||
// WeChat uses its existing authorization-code service.
|
||||
apiRouter.GET("/oauth/wechat", middleware.CriticalRateLimit(), middleware.DisableCache(), controller.WeChatAuth)
|
||||
apiRouter.POST("/oauth/wechat/bind", middleware.UserAuth(), middleware.CriticalRateLimit(), controller.WeChatBind)
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"html"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
func UnbindAccountOAuth(identity AuthIdentity, providerID int) error {
|
||||
enabled := model.AccountLoginMethods{
|
||||
Password: common.PasswordLoginEnabled,
|
||||
Passkey: system_setting.GetPasskeySettings().Enabled,
|
||||
WeChat: common.WeChatAuthEnabled,
|
||||
}
|
||||
for _, provider := range oauth.GetAllProviders() {
|
||||
if !provider.IsEnabled() {
|
||||
continue
|
||||
}
|
||||
if custom, ok := provider.(*oauth.GenericOAuthProvider); ok {
|
||||
enabled.CustomProviderIDs = append(enabled.CustomProviderIDs, custom.GetProviderId())
|
||||
} else {
|
||||
enabled.OAuthColumns = append(enabled.OAuthColumns, provider.ProviderUserIDColumn())
|
||||
}
|
||||
}
|
||||
return model.UnbindUserOAuthForSession(identity, providerID, enabled)
|
||||
}
|
||||
|
||||
// NotifyAccountSecurityChange never includes credentials or tokens. The caller
|
||||
// records delivery failure independently from the already-committed change.
|
||||
func NotifyAccountSecurityChange(email, event string) error {
|
||||
if email == "" {
|
||||
return nil
|
||||
}
|
||||
subject := common.SystemName + " — Account security notification"
|
||||
content := fmt.Sprintf("<p>Your account security settings have changed: %s.</p><p>If you did not make this change, open your account security settings, revoke other login sessions, and contact your administrator.</p>", html.EscapeString(event))
|
||||
return common.SendEmail(subject, email, content)
|
||||
}
|
||||
@@ -227,7 +227,7 @@ func RefreshLoginSession(rawRefreshToken, expectedSID, ip, userAgent string) (*A
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
currentUser, err := model.GetUserById(session.UserID, false)
|
||||
currentUser, err := model.GetSelfUserById(session.UserID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html"
|
||||
"math/big"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/model"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrAccountEmailInvalid = errors.New("Please enter a valid email address")
|
||||
ErrAccountEmailRestricted = errors.New("This email address is not allowed by the administrator's email policy.")
|
||||
ErrEmailBindingDelivery = errors.New("Verification email could not be sent. Start email verification again.")
|
||||
)
|
||||
|
||||
type EmailBindingData struct {
|
||||
FlowToken string `json:"flow_token"`
|
||||
Email string `json:"email"`
|
||||
CurrentEmail string `json:"current_email,omitempty"`
|
||||
OldEmailRequired bool `json:"old_email_required"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
ResendAt int64 `json:"resend_at"`
|
||||
NotificationWarning bool `json:"notification_warning"`
|
||||
}
|
||||
|
||||
// ValidateAccountEmail is shared with registration mail delivery so binding
|
||||
// cannot bypass the site's existing domain, alias and address-length rules.
|
||||
func ValidateAccountEmail(email string) (string, error) {
|
||||
email = model.NormalizeEmail(email)
|
||||
if common.Validate.Var(email, "required,email,max=50") != nil {
|
||||
return "", ErrAccountEmailInvalid
|
||||
}
|
||||
parts := strings.Split(email, "@")
|
||||
if len(parts) != 2 {
|
||||
return "", ErrAccountEmailInvalid
|
||||
}
|
||||
if common.EmailDomainRestrictionEnabled {
|
||||
allowed := false
|
||||
for _, domain := range common.EmailDomainWhitelist {
|
||||
if parts[1] == domain {
|
||||
allowed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !allowed {
|
||||
return "", ErrAccountEmailRestricted
|
||||
}
|
||||
}
|
||||
if common.EmailAliasRestrictionEnabled && strings.ContainsAny(parts[0], "+.") {
|
||||
return "", ErrAccountEmailRestricted
|
||||
}
|
||||
return email, nil
|
||||
}
|
||||
|
||||
func StartEmailBinding(identity AuthIdentity, authorization *model.AuthFlowAuthorization, email string) (*EmailBindingData, error) {
|
||||
email, err := ValidateAccountEmail(email)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
context, err := common.Marshal(AccountBindingContext{Provider: "email", Email: email})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ValidateFlowAuthorization(identity, VerificationOperation{Scope: VerificationScopeAccountBind, Context: context}, authorization); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user, err := model.GetUserById(identity.UserID, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
state := model.EmailBindingState{Authorization: authorization, CurrentEmail: model.NormalizeEmail(user.Email), Email: email, ResendAt: time.Now().Add(model.EmailBindingResendDelay).Unix()}
|
||||
requireOld := state.CurrentEmail != "" && authorization.Method != VerificationMethodTwoFA && authorization.Method != VerificationMethodPasskey
|
||||
codes, err := generateEmailBindingCodes(requireOld)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
state.NewCodeHash, state.OldCodeHash = codes.NewHash, codes.OldHash
|
||||
token, flow, err := model.CreateEmailBinding(identity, state)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := sendEmailBindingCodes(state, codes); err != nil {
|
||||
// A partially delivered pair must not leave a usable change request.
|
||||
_, _ = model.ConsumeAuthFlow(token, model.AuthFlowMatch{Purpose: model.AuthFlowPurposeEmailBinding, UserId: identity.UserID, SessionId: identity.SessionID})
|
||||
return nil, ErrEmailBindingDelivery
|
||||
}
|
||||
data := emailBindingData(token, flow, &state)
|
||||
if state.CurrentEmail != "" && !requireOld {
|
||||
data.NotificationWarning = NotifyAccountSecurityChange(state.CurrentEmail, "A change of your email address was requested") != nil
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func ResendAccountEmailBinding(identity AuthIdentity, token string) (*EmailBindingData, error) {
|
||||
_, state, err := model.GetEmailBinding(identity, token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
context, err := common.Marshal(AccountBindingContext{Provider: "email", Email: state.Email})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ValidateFlowAuthorization(identity, VerificationOperation{Scope: VerificationScopeAccountBind, Context: context}, state.Authorization); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if state.ResendAt > time.Now().Unix() {
|
||||
return nil, model.ErrEmailBindingResendWait
|
||||
}
|
||||
if state.FailedAttempts >= model.EmailBindingMaxAttempts {
|
||||
return nil, model.ErrEmailBindingLocked
|
||||
}
|
||||
codes, err := generateEmailBindingCodes(state.OldCodeHash != "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
flow, state, err := model.ResendEmailBinding(identity, token, codes.NewHash, codes.OldHash)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := sendEmailBindingCodes(*state, codes); err != nil {
|
||||
_, _ = model.ConsumeAuthFlow(token, model.AuthFlowMatch{Purpose: model.AuthFlowPurposeEmailBinding, UserId: identity.UserID, SessionId: identity.SessionID})
|
||||
return nil, ErrEmailBindingDelivery
|
||||
}
|
||||
return emailBindingData(token, flow, state), nil
|
||||
}
|
||||
|
||||
func FinishEmailBinding(identity AuthIdentity, token, newCode, oldCode string) (*model.EmailBindingState, error) {
|
||||
_, state, err := model.GetEmailBinding(identity, token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
context, err := common.Marshal(AccountBindingContext{Provider: "email", Email: state.Email})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ValidateFlowAuthorization(identity, VerificationOperation{Scope: VerificationScopeAccountBind, Context: context}, state.Authorization); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := ValidateAccountEmail(state.Email); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return model.CompleteEmailBinding(identity, token, state.Email, newCode, oldCode)
|
||||
}
|
||||
|
||||
type emailBindingCodes struct {
|
||||
New, Old string
|
||||
NewHash, OldHash string
|
||||
}
|
||||
|
||||
func generateEmailBindingCodes(requireOld bool) (emailBindingCodes, error) {
|
||||
var codes emailBindingCodes
|
||||
count := 1
|
||||
if requireOld {
|
||||
count = 2
|
||||
}
|
||||
for index := 0; index < count; {
|
||||
number, err := rand.Int(rand.Reader, big.NewInt(1_000_000))
|
||||
if err != nil {
|
||||
return codes, err
|
||||
}
|
||||
code := fmt.Sprintf("%06d", number.Int64())
|
||||
if code == codes.New {
|
||||
continue
|
||||
}
|
||||
hash, err := common.Password2Hash(code)
|
||||
if err != nil {
|
||||
return codes, err
|
||||
}
|
||||
if index == 0 {
|
||||
codes.New, codes.NewHash = code, hash
|
||||
} else {
|
||||
codes.Old, codes.OldHash = code, hash
|
||||
}
|
||||
index++
|
||||
}
|
||||
return codes, nil
|
||||
}
|
||||
|
||||
func sendEmailBindingCodes(state model.EmailBindingState, codes emailBindingCodes) error {
|
||||
subject := common.SystemName + " — Confirm your email address"
|
||||
content := fmt.Sprintf("<p>Confirm linking this email address to your account.</p><p>Verification code: <strong>%s</strong></p><p>This code expires in 10 minutes. If you did not request this change, do not share this code.</p>", html.EscapeString(codes.New))
|
||||
if err := common.SendEmail(subject, state.Email, content); err != nil {
|
||||
return err
|
||||
}
|
||||
if codes.Old != "" {
|
||||
content = fmt.Sprintf("<p>A change to your account email address was requested. Confirm replacing your current address.</p><p>Verification code: <strong>%s</strong></p><p>This code expires in 10 minutes. If you did not request this change, do not share this code and contact your administrator.</p>", html.EscapeString(codes.Old))
|
||||
return common.SendEmail(subject, state.CurrentEmail, content)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func emailBindingData(token string, flow *model.AuthFlow, state *model.EmailBindingState) *EmailBindingData {
|
||||
return &EmailBindingData{
|
||||
FlowToken: token, Email: state.Email, CurrentEmail: common.MaskEmail(state.CurrentEmail),
|
||||
OldEmailRequired: state.OldCodeHash != "", ExpiresAt: flow.ExpiresAt.Unix(), ResendAt: state.ResendAt,
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,10 @@ const (
|
||||
VerificationScopeTwoFASetup = "2fa.setup"
|
||||
VerificationScopeAccessTokenGenerate = "access_token.generate"
|
||||
VerificationScopeAccessTokenRevoke = "access_token.revoke"
|
||||
VerificationScopeAccountBind = "account.binding.bind"
|
||||
VerificationScopeAccountUnbind = "account.binding.unbind"
|
||||
VerificationScopePasswordSet = "account.password.set"
|
||||
VerificationScopePasswordChange = "account.password.change"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -48,6 +52,16 @@ type ChannelKeyReadContext struct {
|
||||
ChannelID int `json:"channel_id"`
|
||||
}
|
||||
|
||||
type AccountBindingContext struct {
|
||||
Provider string `json:"provider"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Code string `json:"code,omitempty"`
|
||||
}
|
||||
|
||||
type AccountUnbindingContext struct {
|
||||
ProviderID int `json:"provider_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 {
|
||||
@@ -70,8 +84,38 @@ func BindVerificationOperation(operation VerificationOperation) (VerificationBin
|
||||
return VerificationBinding{}, ErrVerificationContextInvalid
|
||||
}
|
||||
normalized = context
|
||||
case VerificationScopeAccountBind:
|
||||
var context AccountBindingContext
|
||||
if common.Unmarshal(operation.Context, &context) != nil {
|
||||
return VerificationBinding{}, ErrVerificationContextInvalid
|
||||
}
|
||||
context.Provider = strings.TrimSpace(context.Provider)
|
||||
switch context.Provider {
|
||||
case "email":
|
||||
context.Email = model.NormalizeEmail(context.Email)
|
||||
if len(fields) != 2 || common.Validate.Var(context.Email, "required,email") != nil || context.Code != "" {
|
||||
return VerificationBinding{}, ErrVerificationContextInvalid
|
||||
}
|
||||
case "wechat":
|
||||
context.Code = strings.TrimSpace(context.Code)
|
||||
if len(fields) != 2 || context.Code == "" || len(context.Code) > 128 || context.Email != "" {
|
||||
return VerificationBinding{}, ErrVerificationContextInvalid
|
||||
}
|
||||
default:
|
||||
if len(fields) != 1 || context.Provider == "" || len(context.Provider) > 64 || oauth.GetProvider(context.Provider) == nil {
|
||||
return VerificationBinding{}, ErrVerificationContextInvalid
|
||||
}
|
||||
}
|
||||
normalized = context
|
||||
case VerificationScopeAccountUnbind:
|
||||
var context AccountUnbindingContext
|
||||
if len(fields) != 1 || common.Unmarshal(fields["provider_id"], &context.ProviderID) != nil || context.ProviderID <= 0 {
|
||||
return VerificationBinding{}, ErrVerificationContextInvalid
|
||||
}
|
||||
normalized = context
|
||||
case VerificationScopePasskeyRegister, VerificationScopePasskeyDelete, VerificationScopeTwoFASetup,
|
||||
VerificationScopeAccessTokenGenerate, VerificationScopeAccessTokenRevoke:
|
||||
VerificationScopeAccessTokenGenerate, VerificationScopeAccessTokenRevoke,
|
||||
VerificationScopePasswordSet, VerificationScopePasswordChange:
|
||||
if len(fields) != 0 {
|
||||
return VerificationBinding{}, ErrVerificationContextInvalid
|
||||
}
|
||||
@@ -124,7 +168,6 @@ type verificationAccountState struct {
|
||||
TwoFALocked bool
|
||||
HasPasskey bool
|
||||
PasskeyEnabled bool
|
||||
WeChatEnrollment bool
|
||||
}
|
||||
|
||||
// securityVerificationPolicy is the only operation-to-method policy. Device
|
||||
@@ -146,10 +189,15 @@ func securityVerificationPolicy(scope string, state verificationAccountState) ([
|
||||
methods = []string{VerificationMethodPasskey}
|
||||
}
|
||||
case VerificationScopePasskeyRegister, VerificationScopeTwoFASetup,
|
||||
VerificationScopeAccessTokenGenerate, VerificationScopeAccessTokenRevoke:
|
||||
VerificationScopeAccessTokenGenerate, VerificationScopeAccessTokenRevoke,
|
||||
VerificationScopeAccountBind, VerificationScopeAccountUnbind,
|
||||
VerificationScopePasswordSet, VerificationScopePasswordChange:
|
||||
if scope == VerificationScopeTwoFASetup && state.HasTwoFA {
|
||||
return nil, model.ErrTwoFAAlreadyEnabled
|
||||
}
|
||||
if (scope == VerificationScopePasswordSet && state.HasPassword) || (scope == VerificationScopePasswordChange && !state.HasPassword) {
|
||||
return nil, ErrVerificationForbidden
|
||||
}
|
||||
switch {
|
||||
case state.HasTwoFA:
|
||||
methods = []string{VerificationMethodTwoFA}
|
||||
@@ -157,8 +205,6 @@ func securityVerificationPolicy(scope string, state verificationAccountState) ([
|
||||
methods = []string{VerificationMethodPasskey}
|
||||
case state.HasPassword:
|
||||
methods = []string{VerificationMethodPassword}
|
||||
case state.WeChatEnrollment && (scope == VerificationScopePasskeyRegister || scope == VerificationScopeTwoFASetup):
|
||||
methods = []string{VerificationMethodSession}
|
||||
default:
|
||||
methods = []string{VerificationMethodOAuth}
|
||||
}
|
||||
@@ -203,22 +249,19 @@ func GetVerificationRequirements(identity AuthIdentity, scope string) (*Verifica
|
||||
TwoFALocked: twoFA != nil && twoFA.IsLocked(), HasPasskey: err == nil,
|
||||
PasskeyEnabled: system_setting.GetPasskeySettings().Enabled,
|
||||
}
|
||||
if (scope == VerificationScopeTwoFASetup || scope == VerificationScopePasskeyRegister) &&
|
||||
!state.HasPassword && !state.HasTwoFA && !state.HasPasskey &&
|
||||
user.WeChatId != "" && user.TelegramId == "" && user.GitHubId == "" &&
|
||||
user.DiscordId == "" && user.OidcId == "" && user.LinuxDOId == "" {
|
||||
bindings, err := model.GetUserOAuthBindingsByUserId(user.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
state.WeChatEnrollment = len(bindings) == 0
|
||||
}
|
||||
|
||||
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 == VerificationMethodPassword && !common.PasswordLoginEnabled {
|
||||
switch scope {
|
||||
case VerificationScopeAccountBind, VerificationScopeAccountUnbind, VerificationScopePasswordSet, VerificationScopePasswordChange:
|
||||
methods[i].Available, methods[i].Reason = false, "Password authentication is disabled."
|
||||
}
|
||||
}
|
||||
if methods[i].Method != VerificationMethodOAuth {
|
||||
continue
|
||||
}
|
||||
@@ -389,9 +432,6 @@ func VerifySecurityInput(identity AuthIdentity, input VerificationInput) (*Secur
|
||||
return nil, err
|
||||
}
|
||||
switch input.Method {
|
||||
case VerificationMethodSession:
|
||||
// The policy above permits only first enrollment for a WeChat-only
|
||||
// account. CompleteSecurityVerification rechecks its live session.
|
||||
case VerificationMethodPassword:
|
||||
password := input.Password
|
||||
if common.PasswordLoginEncryptionEnabled {
|
||||
|
||||
@@ -171,7 +171,8 @@ export async function createOAuthAuthorization(
|
||||
provider: string,
|
||||
intent: 'login' | 'bind' | 'verify',
|
||||
operation?: VerificationOperation,
|
||||
signal?: AbortSignal
|
||||
signal?: AbortSignal,
|
||||
proofToken?: string
|
||||
): Promise<{ state: string; authorizationUrl?: string }> {
|
||||
const aff = intent === 'login' ? getAffiliateCode() : ''
|
||||
const res = await api.post(
|
||||
@@ -185,6 +186,8 @@ export async function createOAuthAuthorization(
|
||||
},
|
||||
{
|
||||
skipAuthRefresh: intent === 'login',
|
||||
...(proofToken ? { headers: { 'X-Security-Proof': proofToken } } : {}),
|
||||
singleUseAuthorization: intent === 'bind',
|
||||
signal,
|
||||
skipBusinessError: true,
|
||||
skipErrorHandler: true,
|
||||
@@ -259,14 +262,21 @@ export async function sendEmailVerification(
|
||||
return res.data
|
||||
}
|
||||
|
||||
// Bind email to OAuth account
|
||||
// Confirm an authenticated, server-owned email binding flow.
|
||||
export async function bindEmail(
|
||||
email: string,
|
||||
code: string
|
||||
flowToken: string,
|
||||
newCode: string,
|
||||
oldCode = '',
|
||||
signal?: AbortSignal
|
||||
): Promise<ApiResponse> {
|
||||
const res = await api.post('/api/oauth/email/bind', {
|
||||
email,
|
||||
code,
|
||||
})
|
||||
const res = await api.post(
|
||||
'/api/oauth/email/bind',
|
||||
{
|
||||
flow_token: flowToken,
|
||||
new_code: newCode,
|
||||
old_code: oldCode,
|
||||
},
|
||||
{ singleUseAuthorization: true, signal }
|
||||
)
|
||||
return res.data
|
||||
}
|
||||
@@ -18,6 +18,8 @@ For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { z } from 'zod'
|
||||
|
||||
import { accountPasswordSchema } from '@/lib/password-policy'
|
||||
|
||||
// ============================================================================
|
||||
// Form Schemas
|
||||
// ============================================================================
|
||||
@@ -31,11 +33,7 @@ export const registerFormSchema = z
|
||||
.object({
|
||||
username: z.string().min(1, 'Please enter your username'),
|
||||
email: z.string().optional(),
|
||||
password: z
|
||||
.string()
|
||||
.min(1, 'Please enter your password')
|
||||
.min(8, 'Password must be between 8 and 20 characters')
|
||||
.max(20, 'Password must be at most 20 characters long'),
|
||||
password: accountPasswordSchema,
|
||||
confirmPassword: z.string().min(1, 'Please confirm your password'),
|
||||
})
|
||||
.refine((data) => data.password === data.confirmPassword, {
|
||||
|
||||
@@ -45,7 +45,7 @@ export async function encryptPassword(
|
||||
): Promise<EncryptedPassword> {
|
||||
try {
|
||||
const key = await getPasswordEncryptionKey()
|
||||
const ciphertext = await rsaOaepEncrypt(password, key.public_key)
|
||||
const ciphertext = await rsaOaepEncrypt(password, key.public_key, key.kid)
|
||||
return {
|
||||
password_encrypted: ciphertext,
|
||||
encryption_key_id: key.kid,
|
||||
@@ -77,7 +77,8 @@ async function getPasswordEncryptionKey(): Promise<PasswordEncryptionKey> {
|
||||
|
||||
async function rsaOaepEncrypt(
|
||||
password: string,
|
||||
publicKeyPEM: string
|
||||
publicKeyPEM: string,
|
||||
keyId: string
|
||||
): Promise<string> {
|
||||
if (typeof globalThis.crypto?.subtle !== 'undefined') {
|
||||
try {
|
||||
@@ -88,10 +89,48 @@ async function rsaOaepEncrypt(
|
||||
false,
|
||||
['encrypt']
|
||||
)
|
||||
const plaintext = new TextEncoder().encode(password)
|
||||
const algorithm = publicKey.algorithm as RsaHashedKeyAlgorithm
|
||||
if (plaintext.byteLength > algorithm.modulusLength / 8 - 66) {
|
||||
const secret = globalThis.crypto.getRandomValues(new Uint8Array(32))
|
||||
const nonce = globalThis.crypto.getRandomValues(new Uint8Array(12))
|
||||
const key = await globalThis.crypto.subtle.importKey(
|
||||
'raw',
|
||||
secret,
|
||||
'AES-GCM',
|
||||
false,
|
||||
['encrypt']
|
||||
)
|
||||
const [wrappedKey, ciphertext] = await Promise.all([
|
||||
globalThis.crypto.subtle.encrypt(
|
||||
{
|
||||
name: 'RSA-OAEP',
|
||||
label: new TextEncoder().encode('password-v2'),
|
||||
},
|
||||
publicKey,
|
||||
secret
|
||||
),
|
||||
globalThis.crypto.subtle.encrypt(
|
||||
{
|
||||
name: 'AES-GCM',
|
||||
iv: nonce,
|
||||
additionalData: new TextEncoder().encode(`password-v2:${keyId}`),
|
||||
},
|
||||
key,
|
||||
plaintext
|
||||
),
|
||||
])
|
||||
return [
|
||||
'v2',
|
||||
arrayBufferToBase64(wrappedKey),
|
||||
arrayBufferToBase64(nonce.buffer),
|
||||
arrayBufferToBase64(ciphertext),
|
||||
].join('.')
|
||||
}
|
||||
const ciphertext = await globalThis.crypto.subtle.encrypt(
|
||||
{ name: 'RSA-OAEP' },
|
||||
publicKey,
|
||||
new TextEncoder().encode(password)
|
||||
plaintext
|
||||
)
|
||||
return arrayBufferToBase64(ciphertext)
|
||||
} catch {
|
||||
@@ -104,11 +143,33 @@ async function rsaOaepEncrypt(
|
||||
// forge keeps the normal HTTPS bundle small while supporting HTTP intranets.
|
||||
const forge = await import('node-forge')
|
||||
const publicKey = forge.pki.publicKeyFromPem(publicKeyPEM)
|
||||
const ciphertext = publicKey.encrypt(
|
||||
forge.util.encodeUtf8(password),
|
||||
'RSA-OAEP',
|
||||
{ md: forge.md.sha256.create() }
|
||||
)
|
||||
const plaintext = forge.util.encodeUtf8(password)
|
||||
if (plaintext.length > publicKey.n.bitLength() / 8 - 66) {
|
||||
const secret = forge.random.getBytesSync(32)
|
||||
const nonce = forge.random.getBytesSync(12)
|
||||
const wrappedKey = publicKey.encrypt(secret, 'RSA-OAEP', {
|
||||
md: forge.md.sha256.create(),
|
||||
label: 'password-v2',
|
||||
})
|
||||
const cipher = forge.cipher.createCipher('AES-GCM', secret)
|
||||
cipher.start({
|
||||
iv: nonce,
|
||||
additionalData: `password-v2:${keyId}`,
|
||||
tagLength: 128,
|
||||
})
|
||||
cipher.update(forge.util.createBuffer(plaintext))
|
||||
if (!cipher.finish()) throw new Error('Password encryption failed')
|
||||
const ciphertext = cipher.output.getBytes() + cipher.mode.tag.getBytes()
|
||||
return [
|
||||
'v2',
|
||||
forge.util.encode64(wrappedKey),
|
||||
forge.util.encode64(nonce),
|
||||
forge.util.encode64(ciphertext),
|
||||
].join('.')
|
||||
}
|
||||
const ciphertext = publicKey.encrypt(plaintext, 'RSA-OAEP', {
|
||||
md: forge.md.sha256.create(),
|
||||
})
|
||||
return forge.util.encode64(ciphertext)
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,13 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import {
|
||||
createDecipheriv,
|
||||
generateKeyPairSync,
|
||||
privateDecrypt,
|
||||
webcrypto,
|
||||
} from 'node:crypto'
|
||||
|
||||
import { waitFor } from '@testing-library/react'
|
||||
import { AxiosError, type InternalAxiosRequestConfig } from 'axios'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
@@ -26,6 +33,10 @@ import { useAuthStore, type AuthBundle } from '@/stores/auth-store'
|
||||
|
||||
import { createOAuthFlow } from '../../api'
|
||||
import { OAUTH_POPUP_CALLBACK_MESSAGE } from '../../constants'
|
||||
import {
|
||||
clearPasswordEncryptionCache,
|
||||
encryptPassword,
|
||||
} from '../../lib/password-encryption'
|
||||
import { checkVerificationMethods, verify } from '../api'
|
||||
import type { SecurityProof } from '../types'
|
||||
|
||||
@@ -166,6 +177,7 @@ function mockRefreshResponse(bundle: AuthBundle, onRequest?: () => void) {
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
clearPasswordEncryptionCache()
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
api.defaults.adapter = originalAdapter
|
||||
@@ -173,6 +185,65 @@ afterEach(() => {
|
||||
window.history.replaceState(null, '', originalLocation)
|
||||
})
|
||||
|
||||
it.each([true, false])(
|
||||
'encrypts short and 128-character Unicode passwords with Web Crypto enabled: %s',
|
||||
async (useWebCrypto) => {
|
||||
vi.stubGlobal(
|
||||
'crypto',
|
||||
useWebCrypto
|
||||
? webcrypto
|
||||
: { getRandomValues: webcrypto.getRandomValues.bind(webcrypto) }
|
||||
)
|
||||
const { publicKey, privateKey } = generateKeyPairSync('rsa', {
|
||||
modulusLength: 2048,
|
||||
})
|
||||
vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
kid: 'test-encryption-key',
|
||||
public_key: publicKey
|
||||
.export({ type: 'spki', format: 'pem' })
|
||||
.toString(),
|
||||
},
|
||||
},
|
||||
})
|
||||
for (const password of ['legacy-password', '🔒'.repeat(128)]) {
|
||||
const encrypted = await encryptPassword(password)
|
||||
const parts = encrypted.password_encrypted.split('.')
|
||||
let decrypted: Buffer
|
||||
if (parts[0] === 'v2') {
|
||||
const key = privateDecrypt(
|
||||
{
|
||||
key: privateKey,
|
||||
oaepHash: 'sha256',
|
||||
oaepLabel: Buffer.from('password-v2'),
|
||||
},
|
||||
Buffer.from(parts[1], 'base64')
|
||||
)
|
||||
const ciphertext = Buffer.from(parts[3], 'base64')
|
||||
const decipher = createDecipheriv(
|
||||
'aes-256-gcm',
|
||||
key,
|
||||
Buffer.from(parts[2], 'base64')
|
||||
)
|
||||
decipher.setAAD(Buffer.from('password-v2:test-encryption-key'))
|
||||
decipher.setAuthTag(ciphertext.subarray(-16))
|
||||
decrypted = Buffer.concat([
|
||||
decipher.update(ciphertext.subarray(0, -16)),
|
||||
decipher.final(),
|
||||
])
|
||||
} else {
|
||||
decrypted = privateDecrypt(
|
||||
{ key: privateKey, oaepHash: 'sha256' },
|
||||
Buffer.from(encrypted.password_encrypted, 'base64')
|
||||
)
|
||||
}
|
||||
expect(decrypted.toString('utf8')).toBe(password)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it.each(['proof', 'flow'] as const)(
|
||||
'never replays a %s request after a 401 response',
|
||||
async (kind) => {
|
||||
|
||||
@@ -110,6 +110,8 @@ interface PendingVerification {
|
||||
request: RequestVerificationOptions
|
||||
controller: AbortController
|
||||
resolve: (proof: SecurityProof | null) => void
|
||||
reject: (error: unknown) => void
|
||||
initialPassword?: string
|
||||
submitting: boolean
|
||||
}
|
||||
|
||||
@@ -121,6 +123,7 @@ export function useSecureVerification() {
|
||||
const current = pending.current
|
||||
pending.current = null
|
||||
current?.controller.abort()
|
||||
if (current) current.initialPassword = undefined
|
||||
current?.resolve(null)
|
||||
dispatch({ type: 'reset' })
|
||||
}, [])
|
||||
@@ -135,6 +138,33 @@ export function useSecureVerification() {
|
||||
current.controller.signal
|
||||
)
|
||||
if (pending.current !== current) return
|
||||
const initialPassword = current.initialPassword
|
||||
current.initialPassword = undefined
|
||||
if (
|
||||
initialPassword !== undefined &&
|
||||
requirements.methods.length === 1 &&
|
||||
requirements.methods[0].method === 'password' &&
|
||||
requirements.methods[0].available
|
||||
) {
|
||||
try {
|
||||
const proof = await verify(
|
||||
{ method: 'password', password: initialPassword },
|
||||
current.request,
|
||||
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
|
||||
pending.current = null
|
||||
dispatch({ type: 'reset' })
|
||||
current.reject(error)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (
|
||||
requirements.methods.length === 1 &&
|
||||
requirements.methods[0].method === 'session' &&
|
||||
@@ -166,12 +196,17 @@ export function useSecureVerification() {
|
||||
}, [])
|
||||
|
||||
const requestVerification = useCallback(
|
||||
(request: RequestVerificationOptions): Promise<SecurityProof | null> => {
|
||||
(
|
||||
request: RequestVerificationOptions,
|
||||
initialPassword?: string
|
||||
): Promise<SecurityProof | null> => {
|
||||
if (pending.current) return Promise.resolve(null)
|
||||
return new Promise((resolve) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const current: PendingVerification = {
|
||||
request: structuredClone(request),
|
||||
resolve,
|
||||
reject,
|
||||
initialPassword,
|
||||
controller: new AbortController(),
|
||||
submitting: false,
|
||||
}
|
||||
|
||||
@@ -29,11 +29,23 @@ export type SecurityProofScope =
|
||||
| '2fa.setup'
|
||||
| 'access_token.generate'
|
||||
| 'access_token.revoke'
|
||||
| 'account.binding.bind'
|
||||
| 'account.binding.unbind'
|
||||
| 'account.password.set'
|
||||
| 'account.password.change'
|
||||
|
||||
export type VerificationOperation =
|
||||
| { scope: 'channel.key.read'; context: { channel_id: number } }
|
||||
| {
|
||||
scope: Exclude<SecurityProofScope, 'channel.key.read'>
|
||||
scope: 'account.binding.bind'
|
||||
context: { provider: string; email?: string; code?: string }
|
||||
}
|
||||
| { scope: 'account.binding.unbind'; context: { provider_id: number } }
|
||||
| {
|
||||
scope: Exclude<
|
||||
SecurityProofScope,
|
||||
'channel.key.read' | 'account.binding.bind' | 'account.binding.unbind'
|
||||
>
|
||||
context?: Record<string, never>
|
||||
}
|
||||
|
||||
|
||||
@@ -271,7 +271,7 @@ export function SignUpForm({
|
||||
<FormLabel>{t('Password')}</FormLabel>
|
||||
<FormControl>
|
||||
<PasswordInput
|
||||
placeholder={t('Enter password (8-20 characters)')}
|
||||
placeholder={t('Enter password (8–128 characters)')}
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
|
||||
@@ -54,8 +54,9 @@ export interface EmailVerificationPayload {
|
||||
}
|
||||
|
||||
export interface BindEmailPayload {
|
||||
email: string
|
||||
code: string
|
||||
flow_token: string
|
||||
new_code: string
|
||||
old_code?: string
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
|
||||
+100
-19
@@ -18,6 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { api } from '@/lib/api'
|
||||
import type { CustomOAuthBinding } from '@/lib/oauth'
|
||||
import { authRequestOptions, authResult } from '@/lib/secure-verification'
|
||||
import type { LoginSession } from '@/stores/auth-store'
|
||||
|
||||
import { normalizeUserSettings } from './lib/user-settings'
|
||||
@@ -29,6 +30,8 @@ import type {
|
||||
DeleteAccountRequest,
|
||||
CheckinStatusResponse,
|
||||
CheckinResponse,
|
||||
AccountSecurityResult,
|
||||
EmailBindingFlow,
|
||||
} from './types'
|
||||
|
||||
// ============================================================================
|
||||
@@ -55,6 +58,22 @@ export async function updateUserProfile(
|
||||
return res.data
|
||||
}
|
||||
|
||||
export function changeAccountPassword(
|
||||
data: UpdateUserRequest,
|
||||
proofToken: string,
|
||||
signal: AbortSignal
|
||||
): Promise<AccountSecurityResult & { has_password: boolean }> {
|
||||
return authResult(
|
||||
api.put('/api/user/self', data, {
|
||||
...authRequestOptions,
|
||||
headers: { 'X-Security-Proof': proofToken },
|
||||
acceptAuthRotation: true,
|
||||
singleUseAuthorization: true,
|
||||
signal,
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Update user settings
|
||||
*/
|
||||
@@ -112,27 +131,81 @@ export async function sendEmailVerification(
|
||||
/**
|
||||
* Bind email account
|
||||
*/
|
||||
export async function bindEmail(
|
||||
export function startEmailBinding(
|
||||
email: string,
|
||||
code: string
|
||||
): Promise<ApiResponse> {
|
||||
const res = await api.post('/api/oauth/email/bind', {
|
||||
email,
|
||||
code,
|
||||
})
|
||||
return res.data
|
||||
proofToken: string,
|
||||
signal: AbortSignal
|
||||
): Promise<EmailBindingFlow> {
|
||||
return authResult(
|
||||
api.post(
|
||||
'/api/oauth/email/bind/start',
|
||||
{ email },
|
||||
{
|
||||
...authRequestOptions,
|
||||
headers: { 'X-Security-Proof': proofToken },
|
||||
singleUseAuthorization: true,
|
||||
signal,
|
||||
}
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
export function resendEmailBinding(
|
||||
flowToken: string,
|
||||
signal: AbortSignal
|
||||
): Promise<EmailBindingFlow> {
|
||||
return authResult(
|
||||
api.post(
|
||||
'/api/oauth/email/bind/resend',
|
||||
{ flow_token: flowToken },
|
||||
{
|
||||
...authRequestOptions,
|
||||
singleUseAuthorization: true,
|
||||
signal,
|
||||
}
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
export function bindEmail(
|
||||
flowToken: string,
|
||||
newCode: string,
|
||||
oldCode: string,
|
||||
signal: AbortSignal
|
||||
): Promise<AccountSecurityResult> {
|
||||
return authResult(
|
||||
api.post(
|
||||
'/api/oauth/email/bind',
|
||||
{ flow_token: flowToken, new_code: newCode, old_code: oldCode },
|
||||
{
|
||||
...authRequestOptions,
|
||||
singleUseAuthorization: true,
|
||||
signal,
|
||||
}
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind WeChat account
|
||||
*/
|
||||
export async function bindWeChat(code: string): Promise<ApiResponse> {
|
||||
const res = await api.post(
|
||||
'/api/oauth/wechat/bind',
|
||||
{ code },
|
||||
{ skipBusinessError: true, skipErrorHandler: true }
|
||||
export function bindWeChat(
|
||||
code: string,
|
||||
proofToken: string,
|
||||
signal: AbortSignal
|
||||
): Promise<AccountSecurityResult> {
|
||||
return authResult(
|
||||
api.post(
|
||||
'/api/oauth/wechat/bind',
|
||||
{ code },
|
||||
{
|
||||
...authRequestOptions,
|
||||
headers: { 'X-Security-Proof': proofToken },
|
||||
singleUseAuthorization: true,
|
||||
signal,
|
||||
}
|
||||
)
|
||||
)
|
||||
return res.data
|
||||
}
|
||||
|
||||
export interface TelegramBindFlow {
|
||||
@@ -184,11 +257,19 @@ export async function getSelfOAuthBindings(): Promise<
|
||||
/**
|
||||
* Unbind a custom OAuth provider for current user
|
||||
*/
|
||||
export async function unbindCustomOAuth(
|
||||
providerId: number
|
||||
): Promise<ApiResponse> {
|
||||
const res = await api.delete(`/api/user/oauth/bindings/${providerId}`)
|
||||
return res.data
|
||||
export function unbindCustomOAuth(
|
||||
providerId: number,
|
||||
proofToken: string,
|
||||
signal: AbortSignal
|
||||
): Promise<AccountSecurityResult> {
|
||||
return authResult(
|
||||
api.delete(`/api/user/oauth/bindings/${providerId}`, {
|
||||
...authRequestOptions,
|
||||
headers: { 'X-Security-Proof': proofToken },
|
||||
singleUseAuthorization: true,
|
||||
signal,
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
|
||||
@@ -35,6 +35,7 @@ export interface ApiResponse<T = unknown> {
|
||||
* User profile data
|
||||
*/
|
||||
export interface UserProfile {
|
||||
has_password?: boolean
|
||||
permissions?: UserPermissions
|
||||
/** User ID */
|
||||
id: number
|
||||
@@ -132,6 +133,19 @@ export interface UpdateUserRequest {
|
||||
original_password?: string
|
||||
}
|
||||
|
||||
export interface AccountSecurityResult {
|
||||
notification_warning?: boolean
|
||||
}
|
||||
|
||||
export interface EmailBindingFlow extends AccountSecurityResult {
|
||||
flow_token: string
|
||||
email: string
|
||||
current_email?: string
|
||||
old_email_required: boolean
|
||||
expires_at: number
|
||||
resend_at: number
|
||||
}
|
||||
|
||||
/**
|
||||
* User settings update request
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { act, render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
|
||||
import { api } from '@/lib/api'
|
||||
import { useAuthStore } from '@/stores/auth-store'
|
||||
|
||||
import { ChangePasswordDialog } from '../components/dialogs/change-password-dialog'
|
||||
import { EmailBindDialog } from '../components/dialogs/email-bind-dialog'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
useAuthStore.getState().auth.reset('idle')
|
||||
})
|
||||
|
||||
it('allows a common new password after verifying the current password once', async () => {
|
||||
const get = vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
scope: 'account.password.change',
|
||||
methods: [{ method: 'password', available: true }],
|
||||
oauth_providers: [],
|
||||
password_encryption_enabled: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
const post = vi.spyOn(api, 'post').mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
scope: 'account.password.change',
|
||||
method: 'password',
|
||||
proof_token: 'password-proof',
|
||||
expires_at: Math.floor(Date.now() / 1000) + 60,
|
||||
},
|
||||
},
|
||||
})
|
||||
const put = vi.spyOn(api, 'put').mockResolvedValue({
|
||||
data: { success: true, data: { has_password: true } },
|
||||
})
|
||||
const user = userEvent.setup()
|
||||
const onOpenChange = vi.fn()
|
||||
render(
|
||||
<ChangePasswordDialog open username='user' onOpenChange={onOpenChange} />
|
||||
)
|
||||
expect(screen.getByText('Use 8–128 characters.')).toBeVisible()
|
||||
await user.type(screen.getByLabelText('Current Password'), 'current-password')
|
||||
await user.type(screen.getByLabelText('New Password'), 'password123')
|
||||
await user.type(screen.getByLabelText('Confirm New Password'), 'password123')
|
||||
await user.click(screen.getByRole('button', { name: 'Change Password' }))
|
||||
await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false))
|
||||
expect(get).toHaveBeenCalledWith(
|
||||
'/api/verify/methods',
|
||||
expect.objectContaining({ params: { scope: 'account.password.change' } })
|
||||
)
|
||||
expect(post).toHaveBeenCalledWith(
|
||||
'/api/verify',
|
||||
expect.objectContaining({
|
||||
method: 'password',
|
||||
password: 'current-password',
|
||||
scope: 'account.password.change',
|
||||
}),
|
||||
expect.anything()
|
||||
)
|
||||
expect(put).toHaveBeenCalledWith(
|
||||
'/api/user/self',
|
||||
expect.objectContaining({
|
||||
original_password: 'current-password',
|
||||
password: 'password123',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
headers: { 'X-Security-Proof': 'password-proof' },
|
||||
singleUseAuthorization: true,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it.each(['button', 'escape'])(
|
||||
'cancels additional verification and restores focus using %s',
|
||||
async (method) => {
|
||||
vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
scope: 'account.password.change',
|
||||
methods: [{ method: '2fa', available: true }],
|
||||
oauth_providers: [],
|
||||
password_encryption_enabled: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
const put = vi
|
||||
.spyOn(api, 'put')
|
||||
.mockResolvedValue({ data: { success: true } })
|
||||
const user = userEvent.setup()
|
||||
render(<ChangePasswordDialog open username='user' onOpenChange={vi.fn()} />)
|
||||
await user.type(
|
||||
screen.getByLabelText('Current Password'),
|
||||
'current-password'
|
||||
)
|
||||
await user.type(
|
||||
screen.getByLabelText('New Password'),
|
||||
'account-password!42'
|
||||
)
|
||||
await user.type(
|
||||
screen.getByLabelText('Confirm New Password'),
|
||||
'account-password!42'
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'Change Password' }))
|
||||
const verification = await screen.findByRole('dialog', {
|
||||
name: 'Security verification',
|
||||
})
|
||||
if (method === 'button') {
|
||||
await user.click(
|
||||
within(verification).getByRole('button', { name: 'Cancel' })
|
||||
)
|
||||
} else {
|
||||
await user.keyboard('{Escape}')
|
||||
}
|
||||
expect(await screen.findByLabelText('Current Password')).toBeVisible()
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByRole('dialog', { name: 'Change Password' })
|
||||
).toContainElement(document.activeElement as HTMLElement)
|
||||
)
|
||||
expect(put).not.toHaveBeenCalled()
|
||||
}
|
||||
)
|
||||
|
||||
it.each(['unmount', 'account change'])(
|
||||
'aborts a pending password operation on %s without duplicate submission',
|
||||
async (reason) => {
|
||||
useAuthStore
|
||||
.getState()
|
||||
.auth.setUser({ id: 1, username: 'first-user', role: 1 })
|
||||
vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
scope: 'account.password.change',
|
||||
methods: [{ method: 'password', available: true }],
|
||||
oauth_providers: [],
|
||||
password_encryption_enabled: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
const proofResponse = {
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
scope: 'account.password.change',
|
||||
method: 'password',
|
||||
proof_token: 'pending-proof',
|
||||
expires_at: Math.floor(Date.now() / 1000) + 60,
|
||||
},
|
||||
},
|
||||
}
|
||||
let resolveProof!: (response: typeof proofResponse) => void
|
||||
const pending = new Promise<typeof proofResponse>((resolve) => {
|
||||
resolveProof = resolve
|
||||
})
|
||||
const post = vi.spyOn(api, 'post').mockReturnValue(pending)
|
||||
const put = vi
|
||||
.spyOn(api, 'put')
|
||||
.mockResolvedValue({ data: { success: true, data: {} } })
|
||||
const user = userEvent.setup()
|
||||
const view = render(
|
||||
<ChangePasswordDialog open username='user' onOpenChange={vi.fn()} />
|
||||
)
|
||||
await user.type(
|
||||
screen.getByLabelText('Current Password'),
|
||||
'current-password'
|
||||
)
|
||||
await user.type(
|
||||
screen.getByLabelText('New Password'),
|
||||
'account-password!42'
|
||||
)
|
||||
await user.type(
|
||||
screen.getByLabelText('Confirm New Password'),
|
||||
'account-password!42'
|
||||
)
|
||||
const submit = screen.getByRole('button', { name: 'Change Password' })
|
||||
await user.click(submit)
|
||||
await waitFor(() => expect(post).toHaveBeenCalledOnce())
|
||||
expect(submit).toBeDisabled()
|
||||
await user.dblClick(submit)
|
||||
if (reason === 'unmount') {
|
||||
view.unmount()
|
||||
} else {
|
||||
act(() =>
|
||||
useAuthStore
|
||||
.getState()
|
||||
.auth.setUser({ id: 2, username: 'second-user', role: 1 })
|
||||
)
|
||||
expect(screen.getByLabelText('Current Password')).toHaveValue('')
|
||||
expect(screen.getByLabelText('New Password')).toHaveValue('')
|
||||
}
|
||||
expect(post.mock.calls[0][2]?.signal?.aborted).toBe(true)
|
||||
await act(async () => {
|
||||
resolveProof(proofResponse)
|
||||
})
|
||||
expect(post).toHaveBeenCalledOnce()
|
||||
expect(put).not.toHaveBeenCalled()
|
||||
}
|
||||
)
|
||||
|
||||
it('sets a first password after verifying an existing factor without asking for a current password', async () => {
|
||||
vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
scope: 'account.password.set',
|
||||
methods: [{ method: '2fa', available: true }],
|
||||
oauth_providers: [],
|
||||
password_encryption_enabled: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
const post = vi.spyOn(api, 'post').mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
scope: 'account.password.set',
|
||||
method: '2fa',
|
||||
proof_token: 'first-password-proof',
|
||||
expires_at: Math.floor(Date.now() / 1000) + 60,
|
||||
},
|
||||
},
|
||||
})
|
||||
const put = vi.spyOn(api, 'put').mockResolvedValue({
|
||||
data: { success: true, data: { has_password: true } },
|
||||
})
|
||||
const user = userEvent.setup()
|
||||
render(
|
||||
<ChangePasswordDialog
|
||||
open
|
||||
username='user'
|
||||
hasPassword={false}
|
||||
onOpenChange={vi.fn()}
|
||||
/>
|
||||
)
|
||||
expect(screen.queryByLabelText('Current Password')).not.toBeInTheDocument()
|
||||
await user.type(
|
||||
screen.getByLabelText('New Password'),
|
||||
'first-account-password!42'
|
||||
)
|
||||
await user.type(
|
||||
screen.getByLabelText('Confirm New Password'),
|
||||
'first-account-password!42'
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'Set Password' }))
|
||||
await user.type(
|
||||
await screen.findByLabelText('Authenticator code or backup code', {
|
||||
selector: 'input',
|
||||
}),
|
||||
'123456'
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'Verify' }))
|
||||
await waitFor(() => expect(put).toHaveBeenCalledTimes(1))
|
||||
expect(post).toHaveBeenCalledTimes(1)
|
||||
expect(put.mock.calls[0][1]).toEqual({
|
||||
password: 'first-account-password!42',
|
||||
})
|
||||
})
|
||||
|
||||
it('confirms both email addresses after identity verification and freezes the submitted address', async () => {
|
||||
vi.spyOn(api, 'get').mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
scope: 'account.binding.bind',
|
||||
methods: [{ method: 'password', available: true }],
|
||||
oauth_providers: [],
|
||||
password_encryption_enabled: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
const post = vi.spyOn(api, 'post').mockImplementation(async (url) => {
|
||||
if (url === '/api/verify') {
|
||||
return {
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
scope: 'account.binding.bind',
|
||||
method: 'password',
|
||||
proof_token: 'email-proof',
|
||||
expires_at: Math.floor(Date.now() / 1000) + 60,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
if (url === '/api/oauth/email/bind/start') {
|
||||
return {
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
flow_token: 'email-flow',
|
||||
email: 'new@example.com',
|
||||
current_email: 'o***@example.com',
|
||||
old_email_required: true,
|
||||
expires_at: Math.floor(Date.now() / 1000) + 600,
|
||||
resend_at: Math.floor(Date.now() / 1000) + 60,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
return { data: { success: true, data: {} } }
|
||||
})
|
||||
const onSuccess = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
render(
|
||||
<EmailBindDialog
|
||||
open
|
||||
currentEmail='old@example.com'
|
||||
onOpenChange={vi.fn()}
|
||||
onSuccess={onSuccess}
|
||||
/>
|
||||
)
|
||||
await user.type(screen.getByLabelText('Email Address'), 'new@example.com')
|
||||
await user.click(screen.getByRole('button', { name: 'Continue' }))
|
||||
await user.type(
|
||||
await screen.findByLabelText('Password', { selector: 'input' }),
|
||||
'current-password'
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'Verify' }))
|
||||
expect(await screen.findByLabelText('Email Address')).toBeDisabled()
|
||||
await user.type(
|
||||
await screen.findByLabelText('New email verification code'),
|
||||
'123456'
|
||||
)
|
||||
await user.type(
|
||||
screen.getByLabelText('Current email verification code'),
|
||||
'654321'
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'Confirm email' }))
|
||||
await waitFor(() => expect(onSuccess).toHaveBeenCalledOnce())
|
||||
expect(post).toHaveBeenCalledWith(
|
||||
'/api/oauth/email/bind',
|
||||
{ flow_token: 'email-flow', new_code: '123456', old_code: '654321' },
|
||||
expect.objectContaining({ singleUseAuthorization: true })
|
||||
)
|
||||
})
|
||||
@@ -123,15 +123,23 @@ it('refreshes Telegram bindings from the server result after the callback popup
|
||||
postMessage: vi.fn(),
|
||||
}
|
||||
vi.spyOn(window, 'open').mockReturnValue(popup as unknown as Window)
|
||||
vi.spyOn(api, 'post').mockResolvedValue({
|
||||
vi.spyOn(api, 'post').mockImplementation(async (url) => ({
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
flow_token: 'binding-state',
|
||||
authorization_url: 'https://oauth.telegram.org/auth?server=pkce',
|
||||
},
|
||||
data:
|
||||
url === '/api/verify'
|
||||
? {
|
||||
proof_token: 'binding-proof',
|
||||
method: 'password',
|
||||
scope: 'account.binding.bind',
|
||||
expires_at: expiresAt(),
|
||||
}
|
||||
: {
|
||||
flow_token: 'binding-state',
|
||||
authorization_url: 'https://oauth.telegram.org/auth?server=pkce',
|
||||
},
|
||||
},
|
||||
})
|
||||
}))
|
||||
let resolve!: (response: {
|
||||
data: { success: boolean; data: { action: string } }
|
||||
}) => void
|
||||
@@ -140,8 +148,21 @@ it('refreshes Telegram bindings from the server result after the callback popup
|
||||
}>((done) => {
|
||||
resolve = done
|
||||
})
|
||||
const get = vi.spyOn(api, 'get').mockImplementation((url) =>
|
||||
url === '/api/status'
|
||||
const get = vi.spyOn(api, 'get').mockImplementation((url) => {
|
||||
if (url === '/api/verify/methods') {
|
||||
return Promise.resolve({
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
scope: 'account.binding.bind',
|
||||
methods: [{ method: 'password', available: true }],
|
||||
oauth_providers: [],
|
||||
password_encryption_enabled: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
return url === '/api/status'
|
||||
? Promise.resolve({
|
||||
data: {
|
||||
success: true,
|
||||
@@ -149,7 +170,7 @@ it('refreshes Telegram bindings from the server result after the callback popup
|
||||
},
|
||||
})
|
||||
: response
|
||||
)
|
||||
})
|
||||
const onUpdate = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
const client = new QueryClient({
|
||||
@@ -166,6 +187,20 @@ it('refreshes Telegram bindings from the server result after the callback popup
|
||||
const telegram = (await screen.findByText('Telegram')).closest('li')
|
||||
if (!telegram) throw new Error('Telegram binding entry is missing')
|
||||
await user.click(within(telegram).getByRole('button', { name: 'Bind' }))
|
||||
const verification = await screen.findByRole('dialog', {
|
||||
name: 'Security verification',
|
||||
})
|
||||
await user.type(
|
||||
within(verification).getByLabelText('Password', { selector: 'input' }),
|
||||
'current-password'
|
||||
)
|
||||
await user.click(within(verification).getByRole('button', { name: 'Verify' }))
|
||||
const continuation = await screen.findByRole('alertdialog', {
|
||||
name: 'Continue account binding',
|
||||
})
|
||||
await user.click(
|
||||
within(continuation).getByRole('button', { name: 'Continue' })
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(popup.location.replace).toHaveBeenCalledWith(
|
||||
'https://oauth.telegram.org/auth?server=pkce'
|
||||
|
||||
@@ -30,6 +30,8 @@ import { DeleteAccountDialog } from './dialogs/delete-account-dialog'
|
||||
type AccountActionCardProps = {
|
||||
action: 'password' | 'delete'
|
||||
username: string
|
||||
hasPassword?: boolean
|
||||
onUpdate?: () => void
|
||||
}
|
||||
|
||||
export function AccountActionCard(props: AccountActionCardProps) {
|
||||
@@ -37,8 +39,14 @@ export function AccountActionCard(props: AccountActionCardProps) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const actions = {
|
||||
password: {
|
||||
title: t('Change Password'),
|
||||
description: t('Update your password to keep your account secure'),
|
||||
title: t(
|
||||
props.hasPassword === false ? 'Set Password' : 'Change Password'
|
||||
),
|
||||
description: t(
|
||||
props.hasPassword === false
|
||||
? 'Add a password after verifying your identity'
|
||||
: 'Update your password to keep your account secure'
|
||||
),
|
||||
icon: Shield,
|
||||
},
|
||||
delete: {
|
||||
@@ -79,6 +87,8 @@ export function AccountActionCard(props: AccountActionCardProps) {
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
username={props.username}
|
||||
hasPassword={props.hasPassword}
|
||||
onSuccess={props.onUpdate}
|
||||
/>
|
||||
)}
|
||||
{props.action === 'delete' && (
|
||||
|
||||
@@ -17,7 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { Mail, Shield, Send, Link2, Unlink } from 'lucide-react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { SiGithub, SiWechat, SiLinux } from 'react-icons/si'
|
||||
import { toast } from 'sonner'
|
||||
@@ -31,9 +31,14 @@ import {
|
||||
openOAuthPopup,
|
||||
type OAuthPopupExchange,
|
||||
} from '@/features/auth/lib/oauth-popup'
|
||||
import { SecureVerificationDialog } from '@/features/auth/secure-verification'
|
||||
import type { CustomOAuthProviderInfo } from '@/features/auth/types'
|
||||
import { getSelfOAuthBindings, unbindCustomOAuth } from '@/features/profile/api'
|
||||
import type { UserProfile, BindingItem } from '@/features/profile/types'
|
||||
import type {
|
||||
UserProfile,
|
||||
BindingItem,
|
||||
AccountSecurityResult,
|
||||
} from '@/features/profile/types'
|
||||
import { useDialogs } from '@/hooks/use-dialog'
|
||||
import { useStatus } from '@/hooks/use-status'
|
||||
import { api } from '@/lib/api'
|
||||
@@ -48,6 +53,7 @@ import {
|
||||
authResult,
|
||||
} from '@/lib/secure-verification'
|
||||
|
||||
import { useAccountSecurity } from '../hooks/use-account-security'
|
||||
import { EmailBindDialog } from './dialogs/email-bind-dialog'
|
||||
import { WeChatBindDialog } from './dialogs/wechat-bind-dialog'
|
||||
|
||||
@@ -62,6 +68,12 @@ interface AccountBindingsProps {
|
||||
|
||||
type DialogKey = 'email' | 'wechat'
|
||||
|
||||
type PreparedOAuthBinding = AccountSecurityResult & {
|
||||
provider: string
|
||||
state: string
|
||||
url: string
|
||||
}
|
||||
|
||||
export function AccountBindings({ profile, onUpdate }: AccountBindingsProps) {
|
||||
const { t } = useTranslation()
|
||||
const dialogs = useDialogs<DialogKey>()
|
||||
@@ -70,8 +82,12 @@ export function AccountBindings({ profile, onUpdate }: AccountBindingsProps) {
|
||||
const [unbindTarget, setUnbindTarget] = useState<CustomOAuthBinding | null>(
|
||||
null
|
||||
)
|
||||
const [unbinding, setUnbinding] = useState(false)
|
||||
const pendingOAuthBinding = useRef<AbortController | null>(null)
|
||||
const security = useAccountSecurity()
|
||||
const unbinding = security.pending
|
||||
const [preparedBinding, setPreparedBinding] =
|
||||
useState<PreparedOAuthBinding | null>(null)
|
||||
const bindingsLocked =
|
||||
security.pending || Boolean(preparedBinding) || dialogs.hasAnyOpen
|
||||
|
||||
const customProviders = status?.custom_oauth_providers as
|
||||
| CustomOAuthProviderInfo[]
|
||||
@@ -99,62 +115,76 @@ export function AccountBindings({ profile, onUpdate }: AccountBindingsProps) {
|
||||
|
||||
const handleUnbindCustom = async () => {
|
||||
if (!unbindTarget) return
|
||||
setUnbinding(true)
|
||||
try {
|
||||
const res = await unbindCustomOAuth(unbindTarget.provider_id)
|
||||
if (res.success) {
|
||||
toast.success(
|
||||
t('Unbound {{provider}}', {
|
||||
provider: unbindTarget.provider_name,
|
||||
})
|
||||
)
|
||||
await fetchCustomBindings()
|
||||
onUpdate()
|
||||
} else {
|
||||
toast.error(res.message || t('Unbind failed'))
|
||||
}
|
||||
} catch {
|
||||
toast.error(t('Unbind failed'))
|
||||
} finally {
|
||||
setUnbinding(false)
|
||||
setUnbindTarget(null)
|
||||
const target = unbindTarget
|
||||
setUnbindTarget(null)
|
||||
const result = await security.run(async (signal) => {
|
||||
const proof = await security.verify(
|
||||
{
|
||||
scope: 'account.binding.unbind',
|
||||
context: { provider_id: target.provider_id },
|
||||
},
|
||||
signal
|
||||
)
|
||||
return unbindCustomOAuth(target.provider_id, proof, signal)
|
||||
})
|
||||
if (result) {
|
||||
toast.success(
|
||||
t('Unbound {{provider}}', { provider: target.provider_name })
|
||||
)
|
||||
await fetchCustomBindings()
|
||||
onUpdate()
|
||||
}
|
||||
}
|
||||
|
||||
const startOAuthBinding = useCallback(
|
||||
async (provider: string) => {
|
||||
pendingOAuthBinding.current?.abort()
|
||||
const controller = new AbortController()
|
||||
pendingOAuthBinding.current = controller
|
||||
const startOAuthBinding = async (provider: string) => {
|
||||
const prepared = await security.run(async (signal) => {
|
||||
const proof = await security.verify(
|
||||
{ scope: 'account.binding.bind', context: { provider } },
|
||||
signal
|
||||
)
|
||||
const authorization = await createOAuthAuthorization(
|
||||
provider,
|
||||
'bind',
|
||||
undefined,
|
||||
signal,
|
||||
proof
|
||||
)
|
||||
return {
|
||||
provider,
|
||||
state: authorization.state,
|
||||
url:
|
||||
authorization.authorizationUrl ??
|
||||
buildOAuthAuthorizationUrl(
|
||||
provider,
|
||||
authorization.state,
|
||||
status ?? {}
|
||||
),
|
||||
notification_warning: false,
|
||||
}
|
||||
})
|
||||
if (prepared) setPreparedBinding(prepared)
|
||||
}
|
||||
|
||||
// A separate user click opens the provider popup. Opening it after an async
|
||||
// verification response would otherwise be blocked by browsers such as Safari.
|
||||
const completeOAuthBinding = async () => {
|
||||
if (!preparedBinding) return
|
||||
const prepared = preparedBinding
|
||||
setPreparedBinding(null)
|
||||
const result = await security.run(async (signal) => {
|
||||
let exchange: OAuthPopupExchange | undefined
|
||||
try {
|
||||
exchange = await openOAuthPopup({
|
||||
provider,
|
||||
provider: prepared.provider,
|
||||
intent: 'bind',
|
||||
signal: controller.signal,
|
||||
prepare: async (signal) => {
|
||||
const authorization = await createOAuthAuthorization(
|
||||
provider,
|
||||
'bind',
|
||||
undefined,
|
||||
signal
|
||||
)
|
||||
return {
|
||||
state: authorization.state,
|
||||
url:
|
||||
authorization.authorizationUrl ??
|
||||
buildOAuthAuthorizationUrl(
|
||||
provider,
|
||||
authorization.state,
|
||||
status ?? {}
|
||||
),
|
||||
}
|
||||
},
|
||||
signal,
|
||||
prepare: async () => ({ state: prepared.state, url: prepared.url }),
|
||||
})
|
||||
const callback = exchange.callback
|
||||
await authResult(
|
||||
api.get(`/api/oauth/${provider}`, {
|
||||
const outcome = await authResult<AccountSecurityResult>(
|
||||
api.get(`/api/oauth/${prepared.provider}`, {
|
||||
...authRequestOptions,
|
||||
singleUseAuthorization: true,
|
||||
disableDuplicate: true,
|
||||
signal: exchange.signal,
|
||||
params: {
|
||||
@@ -167,130 +197,119 @@ export function AccountBindings({ profile, onUpdate }: AccountBindingsProps) {
|
||||
)
|
||||
exchange.signal.throwIfAborted()
|
||||
exchange.finish({ success: true })
|
||||
toast.success(t('Binding successful!'))
|
||||
onUpdate()
|
||||
await fetchCustomBindings()
|
||||
return outcome
|
||||
} 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
|
||||
}
|
||||
throw failure
|
||||
}
|
||||
},
|
||||
[fetchCustomBindings, onUpdate, status, t]
|
||||
)
|
||||
})
|
||||
if (result) {
|
||||
toast.success(t('Binding successful!'))
|
||||
onUpdate()
|
||||
await fetchCustomBindings()
|
||||
}
|
||||
}
|
||||
|
||||
const handleBindCustomOAuth = (provider: CustomOAuthProviderInfo) =>
|
||||
startOAuthBinding(provider.slug)
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
pendingOAuthBinding.current?.abort()
|
||||
pendingOAuthBinding.current = null
|
||||
const closeDialogs = dialogs.closeAll
|
||||
useEffect(() => {
|
||||
setPreparedBinding(null)
|
||||
setUnbindTarget(null)
|
||||
closeDialogs()
|
||||
}, [security.sessionKey, closeDialogs])
|
||||
|
||||
if (!profile || !status || loading) return null
|
||||
|
||||
const bindings: BindingItem[] = [
|
||||
{
|
||||
id: 'email',
|
||||
label: t('Email'),
|
||||
icon: Mail,
|
||||
value: profile.email,
|
||||
isBound: Boolean(profile.email),
|
||||
isEnabled: true,
|
||||
onBind: () => dialogs.open('email'),
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
const bindings: BindingItem[] = useMemo(() => {
|
||||
if (!profile || !status) return []
|
||||
|
||||
return [
|
||||
{
|
||||
id: 'email',
|
||||
label: t('Email'),
|
||||
icon: Mail,
|
||||
value: profile.email,
|
||||
isBound: Boolean(profile.email),
|
||||
isEnabled: true,
|
||||
onBind: () => dialogs.open('email'),
|
||||
},
|
||||
{
|
||||
id: 'wechat',
|
||||
label: t('WeChat'),
|
||||
icon: SiWechat as React.ComponentType<{ className?: string }>,
|
||||
value: undefined,
|
||||
isBound: Boolean(
|
||||
(profile as unknown as Record<string, unknown>).wechat_id
|
||||
),
|
||||
isEnabled: status?.wechat_login || false,
|
||||
onBind: () => dialogs.open('wechat'),
|
||||
},
|
||||
{
|
||||
id: 'github',
|
||||
label: t('GitHub'),
|
||||
icon: SiGithub,
|
||||
value: (profile as unknown as Record<string, unknown>).github_id as
|
||||
| string
|
||||
| undefined,
|
||||
isBound: Boolean(
|
||||
(profile as unknown as Record<string, unknown>).github_id
|
||||
),
|
||||
isEnabled: status?.github_oauth || false,
|
||||
onBind: () => void startOAuthBinding('github'),
|
||||
},
|
||||
{
|
||||
id: 'discord',
|
||||
label: t('Discord'),
|
||||
icon: IconDiscord,
|
||||
value: (profile as unknown as Record<string, unknown>).discord_id as
|
||||
| string
|
||||
| undefined,
|
||||
isBound: Boolean(
|
||||
(profile as unknown as Record<string, unknown>).discord_id
|
||||
),
|
||||
isEnabled: status?.discord_oauth || false,
|
||||
onBind: () => void startOAuthBinding('discord'),
|
||||
},
|
||||
{
|
||||
id: 'oidc',
|
||||
label: t('OIDC'),
|
||||
icon: Shield,
|
||||
value: (profile as unknown as Record<string, unknown>).oidc_id as
|
||||
| string
|
||||
| undefined,
|
||||
isBound: Boolean(
|
||||
(profile as unknown as Record<string, unknown>).oidc_id
|
||||
),
|
||||
isEnabled: status?.oidc_enabled || false,
|
||||
onBind: () => void startOAuthBinding('oidc'),
|
||||
},
|
||||
{
|
||||
id: 'telegram',
|
||||
label: t('Telegram'),
|
||||
icon: Send,
|
||||
value: (profile as unknown as Record<string, unknown>).telegram_id as
|
||||
| string
|
||||
| undefined,
|
||||
isBound: Boolean(
|
||||
(profile as unknown as Record<string, unknown>).telegram_id
|
||||
),
|
||||
isEnabled: status?.telegram_oauth || false,
|
||||
onBind: () => void startOAuthBinding('telegram'),
|
||||
},
|
||||
{
|
||||
id: 'linuxdo',
|
||||
label: t('LinuxDO'),
|
||||
icon: SiLinux as React.ComponentType<{ className?: string }>,
|
||||
value: (profile as unknown as Record<string, unknown>).linux_do_id as
|
||||
| string
|
||||
| undefined,
|
||||
isBound: Boolean(
|
||||
(profile as unknown as Record<string, unknown>).linux_do_id
|
||||
),
|
||||
isEnabled: status?.linuxdo_oauth || false,
|
||||
onBind: () => void startOAuthBinding('linuxdo'),
|
||||
},
|
||||
].filter((binding) => binding.isEnabled)
|
||||
}, [profile, status, startOAuthBinding, dialogs, t])
|
||||
|
||||
if (!profile || loading) return null
|
||||
{
|
||||
id: 'wechat',
|
||||
label: t('WeChat'),
|
||||
icon: SiWechat as React.ComponentType<{ className?: string }>,
|
||||
value: undefined,
|
||||
isBound: Boolean(
|
||||
(profile as unknown as Record<string, unknown>).wechat_id
|
||||
),
|
||||
isEnabled: status?.wechat_login || false,
|
||||
onBind: () => dialogs.open('wechat'),
|
||||
},
|
||||
{
|
||||
id: 'github',
|
||||
label: t('GitHub'),
|
||||
icon: SiGithub,
|
||||
value: (profile as unknown as Record<string, unknown>).github_id as
|
||||
| string
|
||||
| undefined,
|
||||
isBound: Boolean(
|
||||
(profile as unknown as Record<string, unknown>).github_id
|
||||
),
|
||||
isEnabled: status?.github_oauth || false,
|
||||
onBind: () => void startOAuthBinding('github'),
|
||||
},
|
||||
{
|
||||
id: 'discord',
|
||||
label: t('Discord'),
|
||||
icon: IconDiscord,
|
||||
value: (profile as unknown as Record<string, unknown>).discord_id as
|
||||
| string
|
||||
| undefined,
|
||||
isBound: Boolean(
|
||||
(profile as unknown as Record<string, unknown>).discord_id
|
||||
),
|
||||
isEnabled: status?.discord_oauth || false,
|
||||
onBind: () => void startOAuthBinding('discord'),
|
||||
},
|
||||
{
|
||||
id: 'oidc',
|
||||
label: t('OIDC'),
|
||||
icon: Shield,
|
||||
value: (profile as unknown as Record<string, unknown>).oidc_id as
|
||||
| string
|
||||
| undefined,
|
||||
isBound: Boolean((profile as unknown as Record<string, unknown>).oidc_id),
|
||||
isEnabled: status?.oidc_enabled || false,
|
||||
onBind: () => void startOAuthBinding('oidc'),
|
||||
},
|
||||
{
|
||||
id: 'telegram',
|
||||
label: t('Telegram'),
|
||||
icon: Send,
|
||||
value: (profile as unknown as Record<string, unknown>).telegram_id as
|
||||
| string
|
||||
| undefined,
|
||||
isBound: Boolean(
|
||||
(profile as unknown as Record<string, unknown>).telegram_id
|
||||
),
|
||||
isEnabled: status?.telegram_oauth || false,
|
||||
onBind: () => void startOAuthBinding('telegram'),
|
||||
},
|
||||
{
|
||||
id: 'linuxdo',
|
||||
label: t('LinuxDO'),
|
||||
icon: SiLinux as React.ComponentType<{ className?: string }>,
|
||||
value: (profile as unknown as Record<string, unknown>).linux_do_id as
|
||||
| string
|
||||
| undefined,
|
||||
isBound: Boolean(
|
||||
(profile as unknown as Record<string, unknown>).linux_do_id
|
||||
),
|
||||
isEnabled: status?.linuxdo_oauth || false,
|
||||
onBind: () => void startOAuthBinding('linuxdo'),
|
||||
},
|
||||
].filter((binding) => binding.isEnabled)
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -341,7 +360,9 @@ export function AccountBindings({ profile, onUpdate }: AccountBindingsProps) {
|
||||
size='sm'
|
||||
className='h-7 shrink-0 px-2.5 text-xs'
|
||||
onClick={binding.onBind}
|
||||
disabled={binding.isBound && binding.id !== 'email'}
|
||||
disabled={
|
||||
bindingsLocked || (binding.isBound && binding.id !== 'email')
|
||||
}
|
||||
>
|
||||
{actionLabel}
|
||||
</Button>
|
||||
@@ -389,6 +410,7 @@ export function AccountBindings({ profile, onUpdate }: AccountBindingsProps) {
|
||||
size='sm'
|
||||
className='text-destructive h-7 shrink-0 px-2.5 text-xs'
|
||||
onClick={() => setUnbindTarget(binding)}
|
||||
disabled={bindingsLocked}
|
||||
>
|
||||
<Unlink className='mr-1 h-3 w-3' />
|
||||
{t('Unbind')}
|
||||
@@ -398,7 +420,8 @@ export function AccountBindings({ profile, onUpdate }: AccountBindingsProps) {
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-7 shrink-0 px-2.5 text-xs'
|
||||
onClick={() => handleBindCustomOAuth(provider)}
|
||||
onClick={() => void handleBindCustomOAuth(provider)}
|
||||
disabled={bindingsLocked}
|
||||
>
|
||||
{t('Bind')}
|
||||
</Button>
|
||||
@@ -408,6 +431,21 @@ export function AccountBindings({ profile, onUpdate }: AccountBindingsProps) {
|
||||
})}
|
||||
</ul>
|
||||
|
||||
{security.showVerification && (
|
||||
<SecureVerificationDialog {...security.verificationDialogProps} />
|
||||
)}
|
||||
<ConfirmDialog
|
||||
open={preparedBinding !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setPreparedBinding(null)
|
||||
}}
|
||||
title={t('Continue account binding')}
|
||||
desc={t(
|
||||
'Your identity has been verified. Continue to the provider to finish linking your account.'
|
||||
)}
|
||||
handleConfirm={() => void completeOAuthBinding()}
|
||||
confirmText={t('Continue')}
|
||||
/>
|
||||
{/* Custom OAuth Unbind Confirmation */}
|
||||
<ConfirmDialog
|
||||
open={!!unbindTarget}
|
||||
|
||||
@@ -16,171 +16,238 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { useEffect } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { toast } from 'sonner'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { Dialog } from '@/components/dialog'
|
||||
import { PasswordInput } from '@/components/password-input'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { updateUserProfile } from '@/features/profile/api'
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/form'
|
||||
import { SecureVerificationDialog } from '@/features/auth/secure-verification'
|
||||
import { changeAccountPassword } from '@/features/profile/api'
|
||||
import { accountPasswordSchema } from '@/lib/password-policy'
|
||||
|
||||
// ============================================================================
|
||||
// Change Password Dialog Component
|
||||
// ============================================================================
|
||||
import { useAccountSecurity } from '../../hooks/use-account-security'
|
||||
|
||||
const passwordChangeSchema = z
|
||||
.object({
|
||||
originalPassword: z.string(),
|
||||
newPassword: accountPasswordSchema,
|
||||
confirmPassword: z.string(),
|
||||
})
|
||||
.refine((data) => data.newPassword === data.confirmPassword, {
|
||||
message: 'Passwords do not match',
|
||||
path: ['confirmPassword'],
|
||||
})
|
||||
type PasswordChangeValues = z.infer<typeof passwordChangeSchema>
|
||||
const emptyPasswordForm: PasswordChangeValues = {
|
||||
originalPassword: '',
|
||||
newPassword: '',
|
||||
confirmPassword: '',
|
||||
}
|
||||
|
||||
interface ChangePasswordDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
username: string
|
||||
hasPassword?: boolean
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
export function ChangePasswordDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
username,
|
||||
}: ChangePasswordDialogProps) {
|
||||
export function ChangePasswordDialog(props: ChangePasswordDialogProps) {
|
||||
const { t } = useTranslation()
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [formData, setFormData] = useState({
|
||||
originalPassword: '',
|
||||
newPassword: '',
|
||||
confirmPassword: '',
|
||||
const security = useAccountSecurity()
|
||||
const hasPassword = props.hasPassword !== false
|
||||
const form = useForm<PasswordChangeValues>({
|
||||
resolver: zodResolver(passwordChangeSchema),
|
||||
defaultValues: emptyPasswordForm,
|
||||
})
|
||||
const reset = form.reset
|
||||
const cancel = security.cancel
|
||||
|
||||
const handleChange = (field: string, value: string) => {
|
||||
setFormData((prev) => ({ ...prev, [field]: value }))
|
||||
useEffect(() => {
|
||||
reset(emptyPasswordForm)
|
||||
}, [reset, security.sessionKey, hasPassword])
|
||||
useEffect(() => {
|
||||
if (!props.open) {
|
||||
cancel()
|
||||
reset(emptyPasswordForm)
|
||||
}
|
||||
}, [props.open, cancel, reset])
|
||||
|
||||
const handleOpenChange = (open: boolean) => {
|
||||
if (!open) {
|
||||
security.cancel()
|
||||
form.reset(emptyPasswordForm)
|
||||
}
|
||||
props.onOpenChange(open)
|
||||
}
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
|
||||
// Validation
|
||||
if (!formData.originalPassword) {
|
||||
toast.error(t('Please enter your current password'))
|
||||
const submit = async (values: PasswordChangeValues) => {
|
||||
if (hasPassword && !values.originalPassword) {
|
||||
form.setError(
|
||||
'originalPassword',
|
||||
{ message: 'Please enter your current password' },
|
||||
{ shouldFocus: true }
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (!formData.newPassword) {
|
||||
toast.error(t('Please enter a new password'))
|
||||
if (hasPassword && values.originalPassword === values.newPassword) {
|
||||
form.setError(
|
||||
'newPassword',
|
||||
{ message: 'New password must be different from current password' },
|
||||
{ shouldFocus: true }
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (formData.newPassword.length < 8) {
|
||||
toast.error(t('Password must be at least 8 characters'))
|
||||
return
|
||||
}
|
||||
|
||||
if (formData.originalPassword === formData.newPassword) {
|
||||
toast.error(t('New password must be different from current password'))
|
||||
return
|
||||
}
|
||||
|
||||
if (formData.newPassword !== formData.confirmPassword) {
|
||||
toast.error(t('Passwords do not match'))
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true)
|
||||
const response = await updateUserProfile({
|
||||
original_password: formData.originalPassword,
|
||||
password: formData.newPassword,
|
||||
})
|
||||
|
||||
if (response.success) {
|
||||
toast.success(t('Password changed successfully'))
|
||||
onOpenChange(false)
|
||||
setFormData({
|
||||
originalPassword: '',
|
||||
newPassword: '',
|
||||
confirmPassword: '',
|
||||
})
|
||||
} else {
|
||||
toast.error(response.message || t('Failed to change password'))
|
||||
}
|
||||
} catch {
|
||||
toast.error(t('Failed to change password'))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
const result = await security.run(async (signal) => {
|
||||
const proof = await security.verify(
|
||||
{
|
||||
scope: hasPassword
|
||||
? 'account.password.change'
|
||||
: 'account.password.set',
|
||||
},
|
||||
signal,
|
||||
hasPassword ? values.originalPassword : undefined
|
||||
)
|
||||
return changeAccountPassword(
|
||||
{
|
||||
password: values.newPassword,
|
||||
...(hasPassword
|
||||
? { original_password: values.originalPassword }
|
||||
: {}),
|
||||
},
|
||||
proof,
|
||||
signal
|
||||
)
|
||||
})
|
||||
if (!result) return
|
||||
form.reset(emptyPasswordForm)
|
||||
toast.success(
|
||||
t(
|
||||
hasPassword
|
||||
? 'Password changed successfully'
|
||||
: 'Password set successfully'
|
||||
)
|
||||
)
|
||||
props.onOpenChange(false)
|
||||
props.onSuccess?.()
|
||||
}
|
||||
|
||||
const formId = 'change-password-form'
|
||||
const title = t(hasPassword ? 'Change Password' : 'Set Password')
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
title={t('Change Password')}
|
||||
description={
|
||||
<>
|
||||
{t('Update your password for account:')} <strong>{username}</strong>
|
||||
</>
|
||||
}
|
||||
contentClassName='sm:max-w-md'
|
||||
contentHeight='auto'
|
||||
bodyClassName='space-y-4'
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={loading}
|
||||
<>
|
||||
<Dialog
|
||||
open={props.open && !security.showVerification}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={title}
|
||||
description={
|
||||
<>
|
||||
{t('Update your password for account:')}{' '}
|
||||
<strong>{props.username}</strong>
|
||||
</>
|
||||
}
|
||||
contentClassName='sm:max-w-md'
|
||||
contentHeight='auto'
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
onClick={() => handleOpenChange(false)}
|
||||
>
|
||||
{t('Cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
type='submit'
|
||||
form='change-password-form'
|
||||
disabled={security.pending}
|
||||
>
|
||||
{security.pending && <Loader2 className='size-4 animate-spin' />}
|
||||
{title}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='change-password-form'
|
||||
onSubmit={form.handleSubmit(submit)}
|
||||
className='space-y-4'
|
||||
>
|
||||
{t('Cancel')}
|
||||
</Button>
|
||||
<Button type='submit' form={formId} disabled={loading}>
|
||||
{loading && <Loader2 className='mr-2 h-4 w-4 animate-spin' />}
|
||||
{loading ? t('Changing...') : t('Change Password')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form id={formId} onSubmit={handleSubmit} className='space-y-4'>
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='currentPassword'>{t('Current Password')}</Label>
|
||||
<PasswordInput
|
||||
id='currentPassword'
|
||||
value={formData.originalPassword}
|
||||
onChange={(e) => handleChange('originalPassword', e.target.value)}
|
||||
disabled={loading}
|
||||
required
|
||||
autoComplete='current-password'
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='newPassword'>{t('New Password')}</Label>
|
||||
<PasswordInput
|
||||
id='newPassword'
|
||||
value={formData.newPassword}
|
||||
onChange={(e) => handleChange('newPassword', e.target.value)}
|
||||
disabled={loading}
|
||||
required
|
||||
minLength={8}
|
||||
autoComplete='new-password'
|
||||
/>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('Must be at least 8 characters')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='confirmPassword'>{t('Confirm New Password')}</Label>
|
||||
<PasswordInput
|
||||
id='confirmPassword'
|
||||
value={formData.confirmPassword}
|
||||
onChange={(e) => handleChange('confirmPassword', e.target.value)}
|
||||
disabled={loading}
|
||||
required
|
||||
autoComplete='new-password'
|
||||
/>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
{hasPassword && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='originalPassword'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('Current Password')}</FormLabel>
|
||||
<FormControl>
|
||||
<PasswordInput
|
||||
{...field}
|
||||
autoComplete='current-password'
|
||||
disabled={security.pending}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='newPassword'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('New Password')}</FormLabel>
|
||||
<FormControl>
|
||||
<PasswordInput
|
||||
{...field}
|
||||
autoComplete='new-password'
|
||||
disabled={security.pending}
|
||||
/>
|
||||
</FormControl>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('Use 8–128 characters.')}
|
||||
</p>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='confirmPassword'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('Confirm New Password')}</FormLabel>
|
||||
<FormControl>
|
||||
<PasswordInput
|
||||
{...field}
|
||||
autoComplete='new-password'
|
||||
disabled={security.pending}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</Dialog>
|
||||
{security.showVerification && (
|
||||
<SecureVerificationDialog {...security.verificationDialogProps} />
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -16,21 +16,50 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { toast } from 'sonner'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { Dialog } from '@/components/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/form'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { sendEmailVerification, bindEmail } from '@/features/profile/api'
|
||||
import { SecureVerificationDialog } from '@/features/auth/secure-verification'
|
||||
import {
|
||||
startEmailBinding,
|
||||
resendEmailBinding,
|
||||
bindEmail,
|
||||
} from '@/features/profile/api'
|
||||
import type { EmailBindingFlow } from '@/features/profile/types'
|
||||
import { useCountdown } from '@/hooks/use-countdown'
|
||||
|
||||
// ============================================================================
|
||||
// Email Bind Dialog Component
|
||||
// ============================================================================
|
||||
import { useAccountSecurity } from '../../hooks/use-account-security'
|
||||
|
||||
const emailBindingSchema = z.object({
|
||||
email: z
|
||||
.string()
|
||||
.email('Please enter a valid email address')
|
||||
.max(50, 'Please enter a valid email address'),
|
||||
newCode: z.string(),
|
||||
oldCode: z.string(),
|
||||
})
|
||||
type EmailBindingValues = z.infer<typeof emailBindingSchema>
|
||||
const emptyEmailForm: EmailBindingValues = {
|
||||
email: '',
|
||||
newCode: '',
|
||||
oldCode: '',
|
||||
}
|
||||
|
||||
interface EmailBindDialogProps {
|
||||
open: boolean
|
||||
@@ -39,164 +68,273 @@ interface EmailBindDialogProps {
|
||||
onSuccess: () => void
|
||||
}
|
||||
|
||||
export function EmailBindDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
currentEmail,
|
||||
onSuccess,
|
||||
}: EmailBindDialogProps) {
|
||||
export function EmailBindDialog(props: EmailBindDialogProps) {
|
||||
const { t } = useTranslation()
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [sendingCode, setSendingCode] = useState(false)
|
||||
const [email, setEmail] = useState('')
|
||||
const [code, setCode] = useState('')
|
||||
const {
|
||||
secondsLeft,
|
||||
isActive,
|
||||
start: startCountdown,
|
||||
reset: resetCountdown,
|
||||
} = useCountdown({
|
||||
initialSeconds: 60,
|
||||
const security = useAccountSecurity()
|
||||
const [flow, setFlow] = useState<EmailBindingFlow | null>(null)
|
||||
const form = useForm<EmailBindingValues>({
|
||||
resolver: zodResolver(emailBindingSchema),
|
||||
defaultValues: emptyEmailForm,
|
||||
})
|
||||
const resend = useCountdown({ initialSeconds: 60 })
|
||||
const deadline = useCountdown({ initialSeconds: 600 })
|
||||
const reset = form.reset
|
||||
const cancel = security.cancel
|
||||
const resetResend = resend.reset
|
||||
const resetDeadline = deadline.reset
|
||||
|
||||
const handleSendCode = async () => {
|
||||
if (!email || !email.includes('@')) {
|
||||
toast.error(t('Please enter a valid email address'))
|
||||
return
|
||||
useEffect(() => {
|
||||
reset(emptyEmailForm)
|
||||
setFlow(null)
|
||||
resetResend()
|
||||
resetDeadline()
|
||||
}, [security.sessionKey, reset, resetResend, resetDeadline])
|
||||
useEffect(() => {
|
||||
if (!props.open) {
|
||||
cancel()
|
||||
reset(emptyEmailForm)
|
||||
setFlow(null)
|
||||
resetResend()
|
||||
resetDeadline()
|
||||
}
|
||||
}, [props.open, cancel, reset, resetResend, resetDeadline])
|
||||
|
||||
try {
|
||||
setSendingCode(true)
|
||||
const response = await sendEmailVerification(email)
|
||||
|
||||
if (response.success) {
|
||||
toast.success(t('Verification code sent! Please check your email.'))
|
||||
startCountdown()
|
||||
} else {
|
||||
toast.error(response.message || t('Failed to send verification code'))
|
||||
}
|
||||
} catch {
|
||||
toast.error(t('Failed to send verification code'))
|
||||
} finally {
|
||||
setSendingCode(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleBind = async () => {
|
||||
if (!email || !code) {
|
||||
toast.error(t('Please enter email and verification code'))
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true)
|
||||
const response = await bindEmail(email, code)
|
||||
|
||||
if (response.success) {
|
||||
toast.success(t('Email bound successfully!'))
|
||||
onOpenChange(false)
|
||||
onSuccess()
|
||||
// Reset form
|
||||
setEmail('')
|
||||
setCode('')
|
||||
resetCountdown()
|
||||
} else {
|
||||
toast.error(response.message || t('Failed to bind email'))
|
||||
}
|
||||
} catch {
|
||||
toast.error(t('Failed to bind email'))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const terminalFailure =
|
||||
security.error?.code === 'EMAIL_BINDING_LOCKED' ||
|
||||
security.error?.code === 'AUTH_FLOW_INVALID' ||
|
||||
security.error?.code === 'ACCOUNT_SECURITY_STATE_CHANGED' ||
|
||||
security.error?.code === 'EMAIL_BINDING_DELIVERY_FAILED'
|
||||
const expired = Boolean(flow && (!deadline.isActive || terminalFailure))
|
||||
const handleOpenChange = (open: boolean) => {
|
||||
if (!loading) {
|
||||
onOpenChange(open)
|
||||
if (!open) {
|
||||
// Reset form when closing
|
||||
setEmail('')
|
||||
setCode('')
|
||||
resetCountdown()
|
||||
}
|
||||
if (!open) {
|
||||
security.cancel()
|
||||
form.reset(emptyEmailForm)
|
||||
setFlow(null)
|
||||
resend.reset()
|
||||
deadline.reset()
|
||||
}
|
||||
props.onOpenChange(open)
|
||||
}
|
||||
const applyFlow = (next: EmailBindingFlow) => {
|
||||
setFlow(next)
|
||||
form.setValue('email', next.email)
|
||||
form.setValue('newCode', '')
|
||||
form.setValue('oldCode', '')
|
||||
const now = Date.now() / 1000
|
||||
resend.start(Math.max(1, Math.ceil(next.resend_at - now)))
|
||||
deadline.start(Math.max(1, Math.ceil(next.expires_at - now)))
|
||||
}
|
||||
const submit = async (values: EmailBindingValues) => {
|
||||
if (!flow) {
|
||||
const email = values.email.trim().toLowerCase()
|
||||
const result = await security.run(async (signal) => {
|
||||
const proof = await security.verify(
|
||||
{
|
||||
scope: 'account.binding.bind',
|
||||
context: { provider: 'email', email },
|
||||
},
|
||||
signal
|
||||
)
|
||||
return startEmailBinding(email, proof, signal)
|
||||
})
|
||||
if (result) applyFlow(result)
|
||||
return
|
||||
}
|
||||
if (expired) return
|
||||
const newCode = values.newCode.trim()
|
||||
const oldCode = values.oldCode.trim()
|
||||
if (!/^\d{6}$/.test(newCode)) {
|
||||
form.setError(
|
||||
'newCode',
|
||||
{ message: 'Enter the 6-digit email verification code.' },
|
||||
{ shouldFocus: true }
|
||||
)
|
||||
return
|
||||
}
|
||||
if (flow.old_email_required && !/^\d{6}$/.test(oldCode)) {
|
||||
form.setError(
|
||||
'oldCode',
|
||||
{ message: 'Enter the 6-digit email verification code.' },
|
||||
{ shouldFocus: true }
|
||||
)
|
||||
return
|
||||
}
|
||||
const result = await security.run((signal) =>
|
||||
bindEmail(flow.flow_token, newCode, oldCode, signal)
|
||||
)
|
||||
if (!result) return
|
||||
toast.success(t('Email bound successfully!'))
|
||||
handleOpenChange(false)
|
||||
props.onSuccess()
|
||||
}
|
||||
const resendCodes = async () => {
|
||||
if (!flow || resend.isActive || expired) return
|
||||
const result = await security.run((signal) =>
|
||||
resendEmailBinding(flow.flow_token, signal)
|
||||
)
|
||||
if (result) {
|
||||
applyFlow(result)
|
||||
toast.success(t('Verification code sent! Please check your email.'))
|
||||
}
|
||||
}
|
||||
|
||||
let sendLabel = t('Send')
|
||||
if (sendingCode) sendLabel = t('Sending...')
|
||||
if (isActive) sendLabel = `${secondsLeft}s`
|
||||
const restart = () => {
|
||||
security.cancel()
|
||||
setFlow(null)
|
||||
form.setValue('newCode', '')
|
||||
form.setValue('oldCode', '')
|
||||
form.clearErrors()
|
||||
resend.reset()
|
||||
deadline.reset()
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={t('Bind Email')}
|
||||
description={
|
||||
currentEmail
|
||||
? t('Current email: {{email}}. Enter a new email to change.', {
|
||||
email: currentEmail,
|
||||
})
|
||||
: t('Bind an email address to your account.')
|
||||
}
|
||||
contentClassName='sm:max-w-md'
|
||||
contentHeight='auto'
|
||||
bodyClassName='space-y-4'
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
onClick={() => handleOpenChange(false)}
|
||||
disabled={loading}
|
||||
>
|
||||
{t('Cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
type='button'
|
||||
onClick={handleBind}
|
||||
disabled={loading || !email || !code}
|
||||
>
|
||||
{loading && <Loader2 className='mr-2 h-4 w-4 animate-spin' />}
|
||||
{loading ? t('Binding...') : t('Bind Email')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className='space-y-4 py-4'>
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='email'>{t('Email Address')}</Label>
|
||||
<Input
|
||||
id='email'
|
||||
type='email'
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder={t('Enter your email')}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='code'>{t('Verification Code')}</Label>
|
||||
<div className='flex gap-2'>
|
||||
<Input
|
||||
id='code'
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value)}
|
||||
placeholder={t('Enter code')}
|
||||
disabled={loading}
|
||||
maxLength={6}
|
||||
/>
|
||||
<>
|
||||
<Dialog
|
||||
open={props.open && !security.showVerification}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={t('Bind Email')}
|
||||
description={
|
||||
props.currentEmail
|
||||
? t('Current email: {{email}}. Enter a new email to change.', {
|
||||
email: props.currentEmail,
|
||||
})
|
||||
: t('Bind an email address to your account.')
|
||||
}
|
||||
contentClassName='sm:max-w-md'
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
onClick={handleSendCode}
|
||||
disabled={sendingCode || isActive || !email}
|
||||
onClick={() => handleOpenChange(false)}
|
||||
>
|
||||
{sendLabel}
|
||||
{t('Cancel')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
{expired ? (
|
||||
<Button type='button' onClick={restart}>
|
||||
{t('Start again')}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
type='submit'
|
||||
form='email-bind-form'
|
||||
disabled={security.pending}
|
||||
>
|
||||
{security.pending && (
|
||||
<Loader2 className='size-4 animate-spin' />
|
||||
)}
|
||||
{t(flow ? 'Confirm email' : 'Continue')}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='email-bind-form'
|
||||
onSubmit={form.handleSubmit(submit)}
|
||||
className='space-y-4'
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='email'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('Email Address')}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
type='email'
|
||||
autoComplete='email'
|
||||
disabled={security.pending || Boolean(flow)}
|
||||
placeholder={t('Enter your email')}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
{flow && (
|
||||
<>
|
||||
<p className='text-muted-foreground text-sm'>
|
||||
{t(
|
||||
flow.old_email_required
|
||||
? 'Confirm both your current and new email addresses to finish this change.'
|
||||
: 'Confirm the verification code sent to your new email address.'
|
||||
)}
|
||||
</p>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='newCode'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('New email verification code')}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
inputMode='numeric'
|
||||
autoComplete='one-time-code'
|
||||
maxLength={6}
|
||||
disabled={security.pending || expired}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
{flow.old_email_required && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='oldCode'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t('Current email verification code')}
|
||||
</FormLabel>
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{flow.current_email}
|
||||
</p>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
inputMode='numeric'
|
||||
autoComplete='one-time-code'
|
||||
maxLength={6}
|
||||
disabled={security.pending || expired}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{expired && (
|
||||
<p role='alert' className='text-destructive text-sm'>
|
||||
{t(
|
||||
'Email verification has ended. Start again to continue.'
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
onClick={() => void resendCodes()}
|
||||
disabled={security.pending || resend.isActive || expired}
|
||||
>
|
||||
{resend.isActive
|
||||
? t('Resend in {{seconds}}s', {
|
||||
seconds: resend.secondsLeft,
|
||||
})
|
||||
: t('Resend codes')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</form>
|
||||
</Form>
|
||||
</Dialog>
|
||||
{security.showVerification && (
|
||||
<SecureVerificationDialog {...security.verificationDialogProps} />
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -16,17 +16,38 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { useState } from 'react'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { useEffect } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { toast } from 'sonner'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { Dialog } from '@/components/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/form'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
import { SecureVerificationDialog } from '@/features/auth/secure-verification'
|
||||
import { bindWeChat } from '@/features/profile/api'
|
||||
|
||||
import { useAccountSecurity } from '../../hooks/use-account-security'
|
||||
|
||||
const wechatBindingSchema = z.object({
|
||||
code: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, 'Enter the verification code')
|
||||
.max(128, 'Invalid verification code'),
|
||||
})
|
||||
|
||||
interface WeChatBindDialogProps {
|
||||
open: boolean
|
||||
qrCodeUrl: string
|
||||
@@ -36,103 +57,118 @@ interface WeChatBindDialogProps {
|
||||
|
||||
export function WeChatBindDialog(props: WeChatBindDialogProps) {
|
||||
const { t } = useTranslation()
|
||||
const [verificationCode, setVerificationCode] = useState('')
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const security = useAccountSecurity()
|
||||
const form = useForm<z.infer<typeof wechatBindingSchema>>({
|
||||
resolver: zodResolver(wechatBindingSchema),
|
||||
defaultValues: { code: '' },
|
||||
})
|
||||
const reset = form.reset
|
||||
const cancel = security.cancel
|
||||
useEffect(() => {
|
||||
reset({ code: '' })
|
||||
}, [reset, security.sessionKey])
|
||||
useEffect(() => {
|
||||
if (!props.open) {
|
||||
cancel()
|
||||
reset({ code: '' })
|
||||
}
|
||||
}, [props.open, cancel, reset])
|
||||
|
||||
const handleOpenChange = (open: boolean) => {
|
||||
if (submitting) return
|
||||
if (!open) setVerificationCode('')
|
||||
if (!open) {
|
||||
security.cancel()
|
||||
form.reset({ code: '' })
|
||||
}
|
||||
props.onOpenChange(open)
|
||||
}
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault()
|
||||
const code = verificationCode.trim()
|
||||
if (!code || submitting) return
|
||||
|
||||
setSubmitting(true)
|
||||
try {
|
||||
const response = await bindWeChat(code)
|
||||
if (!response.success) {
|
||||
toast.error(t('Request failed'))
|
||||
return
|
||||
}
|
||||
|
||||
toast.success(t('Binding successful!'))
|
||||
setVerificationCode('')
|
||||
props.onOpenChange(false)
|
||||
props.onSuccess()
|
||||
} catch {
|
||||
toast.error(t('Request failed'))
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
const submit = async (values: z.infer<typeof wechatBindingSchema>) => {
|
||||
const result = await security.run(async (signal) => {
|
||||
const proof = await security.verify(
|
||||
{
|
||||
scope: 'account.binding.bind',
|
||||
context: { provider: 'wechat', code: values.code },
|
||||
},
|
||||
signal
|
||||
)
|
||||
return bindWeChat(values.code, proof, signal)
|
||||
})
|
||||
if (!result) return
|
||||
toast.success(t('Binding successful!'))
|
||||
handleOpenChange(false)
|
||||
props.onSuccess()
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={props.open}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={t('Bind WeChat Account')}
|
||||
description={t(
|
||||
'Scan the QR code to follow the official account and reply with “验证码” to receive your verification code.'
|
||||
)}
|
||||
contentClassName='max-w-sm'
|
||||
contentHeight='auto'
|
||||
bodyClassName='space-y-4'
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
disabled={submitting}
|
||||
onClick={() => handleOpenChange(false)}
|
||||
<>
|
||||
<Dialog
|
||||
open={props.open && !security.showVerification}
|
||||
onOpenChange={handleOpenChange}
|
||||
title={t('Bind WeChat')}
|
||||
contentClassName='sm:max-w-md'
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
onClick={() => handleOpenChange(false)}
|
||||
>
|
||||
{t('Cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
type='submit'
|
||||
form='wechat-bind-form'
|
||||
disabled={security.pending}
|
||||
>
|
||||
{security.pending && <Spinner data-icon='inline-start' />}
|
||||
{t('Bind')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='wechat-bind-form'
|
||||
onSubmit={form.handleSubmit(submit)}
|
||||
className='space-y-4'
|
||||
>
|
||||
{t('Cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
type='submit'
|
||||
form='wechat-bind-form'
|
||||
disabled={submitting || !verificationCode.trim()}
|
||||
>
|
||||
{submitting && <Spinner data-icon='inline-start' />}
|
||||
{t('Bind')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form id='wechat-bind-form' onSubmit={handleSubmit}>
|
||||
<FieldGroup>
|
||||
{props.qrCodeUrl ? (
|
||||
<div className='flex justify-center'>
|
||||
<img
|
||||
src={props.qrCodeUrl}
|
||||
alt={t('WeChat login QR code')}
|
||||
className='size-48 rounded-lg border object-contain'
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<p className='text-muted-foreground text-sm'>
|
||||
{t('QR code is not configured. Please contact support.')}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<Field data-disabled={submitting}>
|
||||
<FieldLabel htmlFor='wechat-bind-code'>
|
||||
{t('Verification code')}
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id='wechat-bind-code'
|
||||
value={verificationCode}
|
||||
onChange={(event) => setVerificationCode(event.target.value)}
|
||||
placeholder={t('Enter the verification code')}
|
||||
autoComplete='one-time-code'
|
||||
disabled={submitting}
|
||||
autoFocus
|
||||
{props.qrCodeUrl ? (
|
||||
<div className='flex justify-center'>
|
||||
<img
|
||||
src={props.qrCodeUrl}
|
||||
alt={t('WeChat login QR code')}
|
||||
className='size-48 rounded-lg border object-contain'
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<p className='text-muted-foreground text-sm'>
|
||||
{t('QR code is not configured. Please contact support.')}
|
||||
</p>
|
||||
)}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='code'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('Verification code')}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
placeholder={t('Enter the verification code')}
|
||||
autoComplete='one-time-code'
|
||||
disabled={security.pending}
|
||||
autoFocus
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
</form>
|
||||
</Dialog>
|
||||
</form>
|
||||
</Form>
|
||||
</Dialog>
|
||||
{security.showVerification && (
|
||||
<SecureVerificationDialog {...security.verificationDialogProps} />
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import {
|
||||
useSecureVerification,
|
||||
type RequestVerificationOptions,
|
||||
} from '@/features/auth/secure-verification'
|
||||
import type { AccountSecurityResult } from '@/features/profile/types'
|
||||
import { AuthOperationError } from '@/lib/secure-verification'
|
||||
import { useAuthStore } from '@/stores/auth-store'
|
||||
|
||||
// Account operations compose the shared verification ceremony with the
|
||||
// subsequent mutation. Both must be cancelled when the account/session changes.
|
||||
export function useAccountSecurity() {
|
||||
const { t } = useTranslation()
|
||||
const userId = useAuthStore((state) => state.auth.user?.id)
|
||||
const sessionId = useAuthStore((state) => state.auth.session?.sid)
|
||||
const sessionKey = `${userId ?? ''}:${sessionId ?? ''}`
|
||||
const verification = useSecureVerification()
|
||||
const cancelVerification = verification.cancel
|
||||
const requestVerification = verification.requestVerification
|
||||
const current = useRef<AbortController | null>(null)
|
||||
const [pending, setPending] = useState(false)
|
||||
const [error, setError] = useState<AuthOperationError | null>(null)
|
||||
|
||||
const cancel = useCallback(() => {
|
||||
current.current?.abort()
|
||||
current.current = null
|
||||
cancelVerification()
|
||||
setPending(false)
|
||||
setError(null)
|
||||
}, [cancelVerification])
|
||||
|
||||
useEffect(() => cancel, [cancel, sessionKey])
|
||||
|
||||
const run = useCallback(
|
||||
async <T extends AccountSecurityResult>(
|
||||
action: (signal: AbortSignal) => Promise<T>
|
||||
): Promise<T | undefined> => {
|
||||
if (current.current) return undefined
|
||||
const controller = new AbortController()
|
||||
current.current = controller
|
||||
setPending(true)
|
||||
setError(null)
|
||||
try {
|
||||
const result = await action(controller.signal)
|
||||
controller.signal.throwIfAborted()
|
||||
if (result.notification_warning) {
|
||||
toast.warning(
|
||||
t(
|
||||
'The change succeeded, but the notification email could not be sent.'
|
||||
)
|
||||
)
|
||||
}
|
||||
return result
|
||||
} catch (error) {
|
||||
if (!controller.signal.aborted) {
|
||||
const failure = AuthOperationError.from(error)
|
||||
if (failure.code !== 'AUTH_CANCELLED') {
|
||||
setError(failure)
|
||||
toast.error(t(failure.message))
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
} finally {
|
||||
if (current.current === controller) {
|
||||
current.current = null
|
||||
setPending(false)
|
||||
}
|
||||
}
|
||||
},
|
||||
[t]
|
||||
)
|
||||
|
||||
const verify = useCallback(
|
||||
async (
|
||||
operation: RequestVerificationOptions,
|
||||
signal: AbortSignal,
|
||||
initialPassword?: string
|
||||
) => {
|
||||
signal.throwIfAborted()
|
||||
const proof = await requestVerification(operation, initialPassword)
|
||||
signal.throwIfAborted()
|
||||
if (!proof) {
|
||||
throw new AuthOperationError('Verification cancelled', 'AUTH_CANCELLED')
|
||||
}
|
||||
return proof.proof_token
|
||||
},
|
||||
[requestVerification]
|
||||
)
|
||||
|
||||
const showVerification =
|
||||
verification.dialogProps.state.phase !== 'idle' &&
|
||||
verification.dialogProps.state.phase !== 'loading'
|
||||
return {
|
||||
run,
|
||||
verify,
|
||||
cancel,
|
||||
pending,
|
||||
error,
|
||||
sessionKey,
|
||||
showVerification,
|
||||
verificationDialogProps: verification.dialogProps,
|
||||
}
|
||||
}
|
||||
@@ -82,7 +82,12 @@ export function Security() {
|
||||
<h3 id='security-authentication' className='text-sm font-semibold'>
|
||||
{t('Login & Authentication')}
|
||||
</h3>
|
||||
<AccountActionCard action='password' username={profile.username} />
|
||||
<AccountActionCard
|
||||
action='password'
|
||||
username={profile.username}
|
||||
hasPassword={profile.has_password}
|
||||
onUpdate={refreshProfile}
|
||||
/>
|
||||
<TitledCard
|
||||
title={t('Account Bindings')}
|
||||
icon={<Link2 className='size-4' />}
|
||||
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
import { Form } from '@/components/ui/form'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useSystemConfig } from '@/hooks/use-system-config'
|
||||
import { accountPasswordSchema } from '@/lib/password-policy'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
import { buildSetupPayload, getSetupStatus, submitSetup } from './api'
|
||||
@@ -208,8 +209,8 @@ export function SetupWizard() {
|
||||
if (setupStatus?.root_init) return true
|
||||
|
||||
const username = form.getValues('username')?.trim()
|
||||
const password = form.getValues('password')?.trim()
|
||||
const confirmPassword = form.getValues('confirmPassword')?.trim()
|
||||
const password = form.getValues('password')
|
||||
const confirmPassword = form.getValues('confirmPassword')
|
||||
|
||||
if (!username) {
|
||||
form.setError('username', {
|
||||
@@ -220,12 +221,12 @@ export function SetupWizard() {
|
||||
return false
|
||||
}
|
||||
|
||||
if (!password || password.length < 8) {
|
||||
if (!accountPasswordSchema.safeParse(password).success) {
|
||||
form.setError('password', {
|
||||
type: 'manual',
|
||||
message: t('Password must be at least 8 characters'),
|
||||
message: t('Password must contain between 8 and 128 characters.'),
|
||||
})
|
||||
toast.error(t('Password must be at least 8 characters'))
|
||||
toast.error(t('Password must contain between 8 and 128 characters.'))
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -328,24 +329,20 @@ export function SetupWizard() {
|
||||
return (
|
||||
<li
|
||||
key={step.titleKey}
|
||||
className={cn(
|
||||
'rounded-xl border p-3',
|
||||
isActive
|
||||
? 'border-primary ring-primary/20 ring-2'
|
||||
: isCompleted
|
||||
? 'border-primary/40 bg-primary/5'
|
||||
: 'border-muted bg-card'
|
||||
)}
|
||||
className={cn('rounded-xl border p-3', {
|
||||
'border-primary ring-primary/20 ring-2': isActive,
|
||||
'border-primary/40 bg-primary/5':
|
||||
!isActive && isCompleted,
|
||||
'border-muted bg-card': !isActive && !isCompleted,
|
||||
})}
|
||||
>
|
||||
<div className='flex items-start gap-3'>
|
||||
<span
|
||||
className={cn(
|
||||
'flex size-6 items-center justify-center rounded-md border text-xs font-semibold',
|
||||
isActive
|
||||
isActive || isCompleted
|
||||
? 'border-primary bg-primary text-primary-foreground'
|
||||
: isCompleted
|
||||
? 'border-primary bg-primary text-primary-foreground'
|
||||
: 'border-muted-foreground/40 text-muted-foreground'
|
||||
: 'border-muted-foreground/40 text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
{index + 1}
|
||||
@@ -364,14 +361,14 @@ export function SetupWizard() {
|
||||
})}
|
||||
</ol>
|
||||
|
||||
{isLoading ? (
|
||||
<LoadingState message={t('Loading setup status…')} />
|
||||
) : isError ? (
|
||||
{isLoading && <LoadingState message={t('Loading setup status…')} />}
|
||||
{!isLoading && isError && (
|
||||
<ErrorState
|
||||
title={t('We could not load the setup status.')}
|
||||
onRetry={() => refetch()}
|
||||
/>
|
||||
) : (
|
||||
)}
|
||||
{!isLoading && !isError && (
|
||||
<Form {...form}>
|
||||
<form
|
||||
className='space-y-6'
|
||||
|
||||
@@ -396,6 +396,11 @@ const AUDIT_TEMPLATES: Record<string, string> = {
|
||||
'user.2fa_disable_self': 'Disabled two-factor authentication',
|
||||
'user.2fa_backup_codes': 'Regenerated two-factor backup codes',
|
||||
'user.security_verify': 'Completed security verification',
|
||||
'user.password_change': 'Account password change',
|
||||
'user.binding_start': 'Account binding request',
|
||||
'user.binding_bind': 'Account binding',
|
||||
'user.binding_unbind': 'Account unlinking',
|
||||
'user.email_binding_resend': 'Email confirmation code resend',
|
||||
|
||||
login: 'Logged in successfully via {{method}}',
|
||||
// User management
|
||||
|
||||
@@ -71,6 +71,7 @@ import {
|
||||
} from '@/lib/admin-permissions'
|
||||
import { getCurrencyDisplay, getCurrencyLabel } from '@/lib/currency'
|
||||
import { formatQuota, parseQuotaFromDollars } from '@/lib/format'
|
||||
import { accountPasswordSchema } from '@/lib/password-policy'
|
||||
import { ROLE } from '@/lib/roles'
|
||||
import { useAuthStore } from '@/stores/auth-store'
|
||||
|
||||
@@ -159,12 +160,11 @@ export function UsersMutateDrawer({
|
||||
const targetIsAdmin = (selectedRole ?? currentRow?.role ?? 0) >= ROLE.ADMIN
|
||||
|
||||
const onSubmit = async (data: UserFormValues) => {
|
||||
if (!isUpdate) {
|
||||
const passwordLength = data.password?.length || 0
|
||||
if (passwordLength < 8 || passwordLength > 20) {
|
||||
if (!isUpdate || data.password) {
|
||||
if (!accountPasswordSchema.safeParse(data.password ?? '').success) {
|
||||
form.setError('password', {
|
||||
type: 'manual',
|
||||
message: t('Password must be between 8 and 20 characters'),
|
||||
message: t('Password must contain between 8 and 128 characters.'),
|
||||
})
|
||||
return
|
||||
}
|
||||
@@ -340,7 +340,7 @@ export function UsersMutateDrawer({
|
||||
placeholder={
|
||||
isUpdate
|
||||
? t('Leave empty to keep unchanged')
|
||||
: t('Enter password (8-20 characters)')
|
||||
: t('Enter password (8–128 characters)')
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
|
||||
@@ -145,13 +145,18 @@
|
||||
"Access tokens are shown only once": "Access tokens are shown only once",
|
||||
"AccessKey / SecretAccessKey": "AccessKey / SecretAccessKey",
|
||||
"Account Actions": "Account Actions",
|
||||
"Account binding": "Account binding",
|
||||
"Account Binding Management": "Account Binding Management",
|
||||
"Account binding request": "Account binding request",
|
||||
"Account Bindings": "Account Bindings",
|
||||
"Account bindings have changed. Start this operation again.": "Account bindings have changed. Start this operation again.",
|
||||
"Account created! Please sign in": "Account created! Please sign in",
|
||||
"Account deleted successfully": "Account deleted successfully",
|
||||
"Account ID *": "Account ID *",
|
||||
"Account Info": "Account Info",
|
||||
"Account password change": "Account password change",
|
||||
"Account security": "Account security",
|
||||
"Account unlinking": "Account unlinking",
|
||||
"Account used when authenticating with the SMTP server": "Account used when authenticating with the SMTP server",
|
||||
"acknowledge the related legal risks": "acknowledge the related legal risks",
|
||||
"Across all groups": "Across all groups",
|
||||
@@ -187,6 +192,7 @@
|
||||
"Add an index URL to browse installable plugins.": "Add an index URL to browse installable plugins.",
|
||||
"Add and submit": "Add and submit",
|
||||
"Add Announcement": "Add Announcement",
|
||||
"Add another login method before unlinking this account.": "Add another login method before unlinking this account.",
|
||||
"Add API": "Add API",
|
||||
"Add API Shortcut": "Add API Shortcut",
|
||||
"Add auto group": "Add auto group",
|
||||
@@ -689,6 +695,7 @@
|
||||
"Bind Email": "Bind Email",
|
||||
"Bind task plugins": "Bind task plugins",
|
||||
"Bind Telegram Account": "Bind Telegram Account",
|
||||
"Bind WeChat": "Bind WeChat",
|
||||
"Bind WeChat Account": "Bind WeChat Account",
|
||||
"Binding Information": "Binding Information",
|
||||
"Binding successful!": "Binding successful!",
|
||||
@@ -1071,6 +1078,7 @@
|
||||
"Confirm and enable": "Confirm and enable",
|
||||
"Confirm Batch Update": "Confirm Batch Update",
|
||||
"Confirm Billing Conflicts": "Confirm Billing Conflicts",
|
||||
"Confirm both your current and new email addresses to finish this change.": "Confirm both your current and new email addresses to finish this change.",
|
||||
"Confirm Changes": "Confirm Changes",
|
||||
"Confirm Cleanup": "Confirm Cleanup",
|
||||
"Confirm cleanup of inactive disk cache?": "Confirm cleanup of inactive disk cache?",
|
||||
@@ -1081,6 +1089,7 @@
|
||||
"Confirm Creem Purchase": "Confirm Creem Purchase",
|
||||
"Confirm delete": "Confirm delete",
|
||||
"Confirm disable": "Confirm Disable",
|
||||
"Confirm email": "Confirm email",
|
||||
"Confirm enable": "Confirm Enable",
|
||||
"Confirm invalidate": "Confirm Invalidate",
|
||||
"Confirm log cleanup": "Confirm log cleanup",
|
||||
@@ -1091,6 +1100,7 @@
|
||||
"Confirm Selection": "Confirm Selection",
|
||||
"Confirm settings and finish setup": "Confirm settings and finish setup",
|
||||
"confirm that I bear legal responsibility arising from deployment": "confirm that I bear legal responsibility arising from deployment",
|
||||
"Confirm the verification code sent to your new email address.": "Confirm the verification code sent to your new email address.",
|
||||
"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.",
|
||||
@@ -1127,6 +1137,7 @@
|
||||
"Content width": "Content width",
|
||||
"Context": "Context",
|
||||
"Continue": "Continue",
|
||||
"Continue account binding": "Continue account binding",
|
||||
"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",
|
||||
@@ -1280,12 +1291,14 @@
|
||||
"Current Billing": "Current Billing",
|
||||
"Current Cache Size": "Current Cache Size",
|
||||
"Current domain": "Current domain",
|
||||
"Current email verification code": "Current email verification code",
|
||||
"Current email: {{email}}. Enter a new email to change.": "Current email: {{email}}. Enter a new email to change.",
|
||||
"Current key": "Current key",
|
||||
"Current legacy JSON is invalid, cannot append": "Current legacy JSON is invalid, cannot append",
|
||||
"Current Level Only": "Current Level Only",
|
||||
"Current models for the longest channel in this tag. May not include all models from all channels.": "Current models for the longest channel in this tag. May not include all models from all channels.",
|
||||
"Current Password": "Current Password",
|
||||
"Current password is incorrect.": "Current password is incorrect.",
|
||||
"Current Price": "Current Price",
|
||||
"Current quota": "Current quota",
|
||||
"Current token": "Current token",
|
||||
@@ -1668,10 +1681,13 @@
|
||||
"Email Address": "Email Address",
|
||||
"Email Alias Restriction": "Email Alias Restriction",
|
||||
"Email bound successfully!": "Email bound successfully!",
|
||||
"Email confirmation code resend": "Email confirmation code resend",
|
||||
"Email Domain Restriction": "Email Domain Restriction",
|
||||
"Email Domain Whitelist": "Email Domain Whitelist",
|
||||
"Email Field": "Email Field",
|
||||
"Email Verification": "Email Verification",
|
||||
"Email verification code is incorrect.": "Email verification code is incorrect.",
|
||||
"Email verification has ended. Start again to continue.": "Email verification has ended. Start again to continue.",
|
||||
"Email, summarisation, knowledge work": "Email, summarisation, knowledge work",
|
||||
"Embeddings": "Embeddings",
|
||||
"Empty": "Empty",
|
||||
@@ -1795,6 +1811,7 @@
|
||||
"Enter only a top-level callback domain, for example https://api.example.com, without any path.": "Enter only a top-level callback domain, for example https://api.example.com, without any path.",
|
||||
"Enter password": "Enter password",
|
||||
"Enter password (8-20 characters)": "Enter password (8-20 characters)",
|
||||
"Enter password (8–128 characters)": "Enter password (8–128 characters)",
|
||||
"Enter quota in {{currency}}": "Enter quota in {{currency}}",
|
||||
"Enter quota in tokens": "Enter quota in tokens",
|
||||
"Enter secret key": "Enter secret key",
|
||||
@@ -1802,6 +1819,7 @@
|
||||
"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 email verification code.": "Enter the 6-digit email verification code.",
|
||||
"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",
|
||||
"Enter the Coze agent ID": "Enter the Coze agent ID",
|
||||
@@ -2737,6 +2755,7 @@
|
||||
"Logo": "Logo",
|
||||
"Logo URL": "Logo URL",
|
||||
"Logs": "Logs",
|
||||
"Long passwords are unavailable until the password storage upgrade is complete.": "Long passwords are unavailable until the password storage upgrade is complete.",
|
||||
"Look for a special ratio rule matching this user group and this billing group. If one exists, use its ratio. Otherwise use the billing group base ratio from the pricing table.": "Look for a special ratio rule matching this user group and this billing group. If one exists, use its ratio. Otherwise use the billing group base ratio from the pricing table.",
|
||||
"Low balance": "Low balance",
|
||||
"Lowest median first-token latency": "Lowest median first-token latency",
|
||||
@@ -3035,6 +3054,7 @@
|
||||
"New API": "New API",
|
||||
"New API <noreply@example.com>": "New API <noreply@example.com>",
|
||||
"New API Project Repository:": "New API Project Repository:",
|
||||
"New email verification code": "New email verification code",
|
||||
"New Format Template": "New Format Template",
|
||||
"New Group": "New Group",
|
||||
"New model": "New model",
|
||||
@@ -3518,6 +3538,7 @@
|
||||
"Passthrough Template": "Passthrough Template",
|
||||
"Password": "Password",
|
||||
"Password / Access Token": "Password / Access Token",
|
||||
"Password authentication is disabled.": "Password authentication is disabled.",
|
||||
"Password changed successfully": "Password changed successfully",
|
||||
"Password copied to clipboard: {{password}}": "Password copied to clipboard: {{password}}",
|
||||
"Password has been copied to clipboard": "Password has been copied to clipboard",
|
||||
@@ -3525,9 +3546,12 @@
|
||||
"Password must be at least 8 characters": "Password must be at least 8 characters",
|
||||
"Password must be at most 20 characters long": "Password must be at most 20 characters long",
|
||||
"Password must be between 8 and 20 characters": "Password must be between 8 and 20 characters",
|
||||
"Password must contain between 8 and 128 characters.": "Password must contain between 8 and 128 characters.",
|
||||
"Password Registration": "Password Registration",
|
||||
"Password reset and copied to clipboard: {{password}}": "Password reset and copied to clipboard: {{password}}",
|
||||
"Password reset: {{password}}": "Password reset: {{password}}",
|
||||
"Password set successfully": "Password set successfully",
|
||||
"Password settings have changed. Reload the page and try again.": "Password settings have changed. Reload the page and try again.",
|
||||
"Passwords do not match": "Passwords do not match",
|
||||
"Passwords don't match.": "Passwords don't match.",
|
||||
"Paste Connection Info": "Paste Connection Info",
|
||||
@@ -3677,6 +3701,7 @@
|
||||
"Please wait a moment before trying again.": "Please wait a moment before trying again.",
|
||||
"Please wait a moment, human check is initializing...": "Please wait a moment, human check is initializing...",
|
||||
"Please wait before editing to avoid overwriting saved values.": "Please wait before editing to avoid overwriting saved values.",
|
||||
"Please wait before requesting another verification code.": "Please wait before requesting another verification code.",
|
||||
"Please wait for the current generation to complete": "Please wait for the current generation to complete",
|
||||
"Plugin": "Plugin",
|
||||
"Plugin author": "Plugin author",
|
||||
@@ -4099,6 +4124,8 @@
|
||||
"Reroll": "Reroll",
|
||||
"Research, analysis, scientific reasoning": "Research, analysis, scientific reasoning",
|
||||
"Resend ({{seconds}}s)": "Resend ({{seconds}}s)",
|
||||
"Resend codes": "Resend codes",
|
||||
"Resend in {{seconds}}s": "Resend in {{seconds}}s",
|
||||
"Reserved for viewing complete channel keys after secure verification.": "Reserved for viewing complete channel keys after secure verification.",
|
||||
"Reset": "Reset",
|
||||
"Reset {{count}} active subscriptions": "Reset {{count}} active subscriptions",
|
||||
@@ -4461,6 +4488,7 @@
|
||||
"Set filters to customize your dashboard statistics and charts.": "Set filters to customize your dashboard statistics and charts.",
|
||||
"Set filters to narrow down your log search results.": "Set filters to narrow down your log search results.",
|
||||
"Set Header": "Set Header",
|
||||
"Set Password": "Set Password",
|
||||
"Set Project to io.cloud when creating/selecting key": "Set Project to io.cloud when creating/selecting key",
|
||||
"Set quota amount and limits": "Set quota amount and limits",
|
||||
"Set Request Header": "Set Request Header",
|
||||
@@ -4591,6 +4619,7 @@
|
||||
"Start ≤ end: within the day; start > end: across midnight": "Start ≤ end: within the day; start > end: across midnight",
|
||||
"Start a conversation to see messages here": "Start a conversation to see messages here",
|
||||
"Start a playground chat": "Start a playground chat",
|
||||
"Start again": "Start again",
|
||||
"Start collecting payments globally without registering a company. Built for indie developers, OPC sole proprietorships, and startups. Waffo Pancake acts as your Merchant of Record, taking on the compliance burden of global payment collection — consumption tax, invoicing, subscription management, refunds, and chargebacks. Solo developers can launch fast and stay focused on product instead of compliance. Onboard in minutes — one prompt to a full integration.": "Start collecting payments globally without registering a company. Built for indie developers, OPC sole proprietorships, and startups. Waffo Pancake acts as your Merchant of Record, taking on the compliance burden of global payment collection — consumption tax, invoicing, subscription management, refunds, and chargebacks. Solo developers can launch fast and stay focused on product instead of compliance. Onboard in minutes — one prompt to a full integration.",
|
||||
"Start for free with generous limits. No credit card required.": "Start for free with generous limits. No credit card required.",
|
||||
"Start Time": "Start Time",
|
||||
@@ -4828,6 +4857,7 @@
|
||||
"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.",
|
||||
"The change succeeded, but the notification email could not be sent.": "The change succeeded, but the notification email could not be sent.",
|
||||
"The deployment node that handled the requests": "The deployment node that handled the requests",
|
||||
"The downloaded source does not match the sha256 declared in the index. Do not install it.": "The downloaded source does not match the sha256 declared in the index. Do not install it.",
|
||||
"The effective domain for Passkey registration. Must match the current domain or be its parent domain.": "The effective domain for Passkey registration. Must match the current domain or be its parent domain.",
|
||||
@@ -4902,8 +4932,11 @@
|
||||
"This data may be unreliable, use with caution": "This data may be unreliable, use with caution",
|
||||
"This device does not support Passkey": "This device does not support Passkey",
|
||||
"This device does not support Passkey verification.": "This device does not support Passkey verification.",
|
||||
"This email address is already in use.": "This email address is already in use.",
|
||||
"This email address is not allowed by the administrator's email policy.": "This email address is not allowed by the administrator's email policy.",
|
||||
"This expression does not price each combination exactly once, so it opens as a raw expression. Sparse or custom pricing stays in this editor.": "This expression does not price each combination exactly once, so it opens as a raw expression. Sparse or custom pricing stays in this editor.",
|
||||
"This expression is too complex for the visual editor. Please switch to expression mode to edit.": "This expression is too complex for the visual editor. Please switch to expression mode to edit.",
|
||||
"This external account is already bound.": "This external account is already bound.",
|
||||
"This FAQ entry will be removed from the list.": "This FAQ entry will be removed from the list.",
|
||||
"This feature is experimental. Configuration format and behavior may change.": "This feature is experimental. Configuration format and behavior may change.",
|
||||
"This field does not support wildcards or regular expressions.": "This field does not support wildcards or regular expressions.",
|
||||
@@ -5057,6 +5090,7 @@
|
||||
"Tokens-only mode will show raw quota values regardless of this toggle.": "Tokens-only mode will show raw quota values regardless of this toggle.",
|
||||
"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.": "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.",
|
||||
"Too many files. Some were not added.": "Too many files. Some were not added.",
|
||||
"Too many incorrect codes. Start email verification again.": "Too many incorrect codes. Start email verification again.",
|
||||
"Too many login sessions were created recently. Please wait for the rolling window to pass, then try again.": "Too many login sessions were created recently. Please wait for the rolling window to pass, then try again.",
|
||||
"Too many requests": "Too many requests",
|
||||
"Tool / function declarations the model may call": "Tool / function declarations the model may call",
|
||||
@@ -5200,6 +5234,7 @@
|
||||
"Unsaved changes": "Unsaved changes",
|
||||
"Unset price": "Unset price",
|
||||
"Unset price models": "Unset price models",
|
||||
"Unsupported account password hashing configuration.": "Unsupported account password hashing configuration.",
|
||||
"Unsupported verification method: {{method}}": "Unsupported verification method: {{method}}",
|
||||
"Until": "Until",
|
||||
"Untitled": "Untitled",
|
||||
@@ -5323,6 +5358,7 @@
|
||||
"USD price per 1M input tokens.": "USD price per 1M input tokens.",
|
||||
"USD price per 1M tokens.": "USD price per 1M tokens.",
|
||||
"Use +: to add a group, -: to remove a default selectable group, or no prefix to append a group.": "Use +: to add a group, -: to remove a default selectable group, or no prefix to append a group.",
|
||||
"Use 8–128 characters.": "Use 8–128 characters.",
|
||||
"Use a compatible browser or device with biometric authentication or a security key to register a Passkey.": "Use a compatible browser or device with biometric authentication or a security key to register a Passkey.",
|
||||
"Use a different stable value for each instance, then restart the service.": "Use a different stable value for each instance, then restart the service.",
|
||||
"Use a path to append it to the channel Base URL, or enter a full URL to override the Base URL for this route.": "Use a path to append it to the channel Base URL, or enter a full URL to override the Base URL for this route.",
|
||||
@@ -5435,6 +5471,7 @@
|
||||
"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 could not be sent. Start email verification again.": "Verification email could not be sent. Start email verification again.",
|
||||
"Verification email sent": "Verification email sent",
|
||||
"Verification failed": "Verification failed",
|
||||
"Verification failed. Please try again.": "Verification failed. Please try again.",
|
||||
@@ -5644,6 +5681,7 @@
|
||||
"Your Discord OAuth Client Secret": "Your Discord OAuth Client Secret",
|
||||
"Your GitHub OAuth Client ID": "Your GitHub OAuth Client ID",
|
||||
"Your GitHub OAuth Client Secret": "Your GitHub OAuth Client Secret",
|
||||
"Your identity has been verified. Continue to the provider to finish linking your account.": "Your identity has been verified. Continue to the provider to finish linking your account.",
|
||||
"Your new backup codes are ready": "Your new backup codes are ready",
|
||||
"Your Referral Link": "Your Referral Link",
|
||||
"Your setup guide is collapsed so usage stays in focus.": "Your setup guide is collapsed so usage stays in focus.",
|
||||
|
||||
@@ -145,13 +145,18 @@
|
||||
"Access tokens are shown only once": "Les jetons d'accès ne sont affichés qu'une seule fois",
|
||||
"AccessKey / SecretAccessKey": "AccessKey / SecretAccessKey",
|
||||
"Account Actions": "Actions sur le compte",
|
||||
"Account binding": "Liaison de compte",
|
||||
"Account Binding Management": "Gestion des liaisons de compte",
|
||||
"Account binding request": "Demande de liaison de compte",
|
||||
"Account Bindings": "Associations de compte",
|
||||
"Account bindings have changed. Start this operation again.": "Les comptes liés ont changé. Recommencez cette opération.",
|
||||
"Account created! Please sign in": "Compte créé ! Veuillez vous connecter",
|
||||
"Account deleted successfully": "Compte supprimé avec succès",
|
||||
"Account ID *": "ID de compte *",
|
||||
"Account Info": "Informations du compte",
|
||||
"Account password change": "Modification du mot de passe",
|
||||
"Account security": "Sécurité du compte",
|
||||
"Account unlinking": "Dissociation de compte",
|
||||
"Account used when authenticating with the SMTP server": "Compte utilisé lors de l'authentification auprès du serveur SMTP",
|
||||
"acknowledge the related legal risks": "reconnais les risques juridiques associés",
|
||||
"Across all groups": "Tous groupes confondus",
|
||||
@@ -187,6 +192,7 @@
|
||||
"Add an index URL to browse installable plugins.": "Ajoutez une URL d’index pour parcourir les plugins installables.",
|
||||
"Add and submit": "Ajouter et soumettre",
|
||||
"Add Announcement": "Ajouter une annonce",
|
||||
"Add another login method before unlinking this account.": "Ajoutez un autre mode de connexion avant de dissocier ce compte.",
|
||||
"Add API": "Ajouter une API",
|
||||
"Add API Shortcut": "Ajouter un raccourci API",
|
||||
"Add auto group": "Ajouter un groupe automatique",
|
||||
@@ -689,6 +695,7 @@
|
||||
"Bind Email": "Lier l'e-mail",
|
||||
"Bind task plugins": "Lier des plugins de tâche",
|
||||
"Bind Telegram Account": "Lier le compte Telegram",
|
||||
"Bind WeChat": "Lier WeChat",
|
||||
"Bind WeChat Account": "Lier le compte WeChat",
|
||||
"Binding Information": "Informations de liaison",
|
||||
"Binding successful!": "Liaison réussie !",
|
||||
@@ -1071,6 +1078,7 @@
|
||||
"Confirm and enable": "Confirmer et activer",
|
||||
"Confirm Batch Update": "Confirmer la mise à jour par lot",
|
||||
"Confirm Billing Conflicts": "Confirmer les conflits de facturation",
|
||||
"Confirm both your current and new email addresses to finish this change.": "Confirmez votre adresse actuelle et la nouvelle pour terminer cette modification.",
|
||||
"Confirm Changes": "Confirmer les modifications",
|
||||
"Confirm Cleanup": "Confirmer le nettoyage",
|
||||
"Confirm cleanup of inactive disk cache?": "Confirmer le nettoyage du cache disque inactif ?",
|
||||
@@ -1081,6 +1089,7 @@
|
||||
"Confirm Creem Purchase": "Confirmer l'achat Creem",
|
||||
"Confirm delete": "Confirmer la suppression",
|
||||
"Confirm disable": "Confirmer la désactivation",
|
||||
"Confirm email": "Confirmer l’adresse e-mail",
|
||||
"Confirm enable": "Confirmer l'activation",
|
||||
"Confirm invalidate": "Confirmer l'invalidation",
|
||||
"Confirm log cleanup": "Confirmer le nettoyage des journaux",
|
||||
@@ -1091,6 +1100,7 @@
|
||||
"Confirm Selection": "Confirmer la sélection",
|
||||
"Confirm settings and finish setup": "Confirmez les paramètres et terminez la configuration",
|
||||
"confirm that I bear legal responsibility arising from deployment": "confirme assumer la responsabilité juridique découlant du déploiement",
|
||||
"Confirm the verification code sent to your new email address.": "Saisissez le code de vérification envoyé à votre nouvelle adresse e-mail.",
|
||||
"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.",
|
||||
@@ -1127,6 +1137,7 @@
|
||||
"Content width": "Largeur du contenu",
|
||||
"Context": "Contexte",
|
||||
"Continue": "Continuer",
|
||||
"Continue account binding": "Poursuivre la liaison du compte",
|
||||
"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",
|
||||
@@ -1280,12 +1291,14 @@
|
||||
"Current Billing": "Facturation actuelle",
|
||||
"Current Cache Size": "Taille actuelle du cache",
|
||||
"Current domain": "Domaine actuel",
|
||||
"Current email verification code": "Code de vérification de l’adresse actuelle",
|
||||
"Current email: {{email}}. Enter a new email to change.": "E-mail actuel : {{email}}. Saisissez un nouvel e-mail pour le modifier.",
|
||||
"Current key": "Clé actuelle",
|
||||
"Current legacy JSON is invalid, cannot append": "Le JSON ancien format actuel n'est pas valide, impossible d'ajouter",
|
||||
"Current Level Only": "Niveau actuel uniquement",
|
||||
"Current models for the longest channel in this tag. May not include all models from all channels.": "Modèles actuels pour le canal le plus long de cette balise. Peut ne pas inclure tous les modèles de tous les canaux.",
|
||||
"Current Password": "Mot de passe actuel",
|
||||
"Current password is incorrect.": "Le mot de passe actuel est incorrect.",
|
||||
"Current Price": "Prix actuel",
|
||||
"Current quota": "Quota actuel",
|
||||
"Current token": "Jeton actuel",
|
||||
@@ -1668,10 +1681,13 @@
|
||||
"Email Address": "Adresse e-mail",
|
||||
"Email Alias Restriction": "Restriction d'alias d'e-mail",
|
||||
"Email bound successfully!": "E-mail lié avec succès !",
|
||||
"Email confirmation code resend": "Renvoi du code de confirmation par e-mail",
|
||||
"Email Domain Restriction": "Restriction de domaine d'e-mail",
|
||||
"Email Domain Whitelist": "Liste blanche de domaines d'e-mail",
|
||||
"Email Field": "Champ d'e-mail",
|
||||
"Email Verification": "Vérification d'e-mail",
|
||||
"Email verification code is incorrect.": "Le code de vérification par e-mail est incorrect.",
|
||||
"Email verification has ended. Start again to continue.": "La vérification de l’adresse e-mail a pris fin. Recommencez pour continuer.",
|
||||
"Email, summarisation, knowledge work": "Email, résumé, travail intellectuel",
|
||||
"Embeddings": "Embeddings",
|
||||
"Empty": "Vide",
|
||||
@@ -1795,6 +1811,7 @@
|
||||
"Enter only a top-level callback domain, for example https://api.example.com, without any path.": "Saisissez uniquement le domaine de callback principal, par exemple https://api.example.com, sans chemin.",
|
||||
"Enter password": "Saisir le mot de passe",
|
||||
"Enter password (8-20 characters)": "Saisir le mot de passe (8-20 caractères)",
|
||||
"Enter password (8–128 characters)": "Saisissez un mot de passe (8 à 128 caractères)",
|
||||
"Enter quota in {{currency}}": "Saisir le quota en {{currency}}",
|
||||
"Enter quota in tokens": "Saisir le quota en tokens",
|
||||
"Enter secret key": "Saisir la clé secrète",
|
||||
@@ -1802,6 +1819,7 @@
|
||||
"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 email verification code.": "Saisissez le code à 6 chiffres reçu par e-mail.",
|
||||
"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",
|
||||
"Enter the Coze agent ID": "Saisir l'ID de l'agent Coze",
|
||||
@@ -2737,6 +2755,7 @@
|
||||
"Logo": "Logo",
|
||||
"Logo URL": "URL du logo",
|
||||
"Logs": "Journaux",
|
||||
"Long passwords are unavailable until the password storage upgrade is complete.": "Les mots de passe longs seront disponibles après la mise à niveau du stockage des mots de passe.",
|
||||
"Look for a special ratio rule matching this user group and this billing group. If one exists, use its ratio. Otherwise use the billing group base ratio from the pricing table.": "Cherchez une règle de taux spécial correspondant à ce groupe d’utilisateurs et ce groupe de facturation. Si elle existe, utilisez son taux ; sinon le taux de base du groupe de facturation.",
|
||||
"Low balance": "Solde faible",
|
||||
"Lowest median first-token latency": "Latence médiane de premier jeton la plus faible",
|
||||
@@ -3035,6 +3054,7 @@
|
||||
"New API": "New API",
|
||||
"New API <noreply@example.com>": "New API <noreply@example.com>",
|
||||
"New API Project Repository:": "Dépôt du projet New API :",
|
||||
"New email verification code": "Code de vérification de la nouvelle adresse",
|
||||
"New Format Template": "Modèle nouveau format",
|
||||
"New Group": "Nouveau groupe",
|
||||
"New model": "Nouveau modèle",
|
||||
@@ -3518,6 +3538,7 @@
|
||||
"Passthrough Template": "Modèle de transmission",
|
||||
"Password": "Mot de passe",
|
||||
"Password / Access Token": "Mot de passe / Jeton d'accès",
|
||||
"Password authentication is disabled.": "L’authentification par mot de passe est désactivée.",
|
||||
"Password changed successfully": "Mot de passe changé avec succès",
|
||||
"Password copied to clipboard: {{password}}": "Mot de passe copié dans le presse-papiers : {{password}}",
|
||||
"Password has been copied to clipboard": "Le mot de passe a été copié dans le presse-papiers",
|
||||
@@ -3525,9 +3546,12 @@
|
||||
"Password must be at least 8 characters": "Le mot de passe doit comporter au moins 8 caractères",
|
||||
"Password must be at most 20 characters long": "Le mot de passe doit comporter au maximum 20 caractères",
|
||||
"Password must be between 8 and 20 characters": "Le mot de passe doit comporter entre 8 et 20 caractères",
|
||||
"Password must contain between 8 and 128 characters.": "Le mot de passe doit contenir entre 8 et 128 caractères.",
|
||||
"Password Registration": "Inscription par mot de passe",
|
||||
"Password reset and copied to clipboard: {{password}}": "Mot de passe réinitialisé et copié dans le presse-papiers : {{password}}",
|
||||
"Password reset: {{password}}": "Mot de passe réinitialisé : {{password}}",
|
||||
"Password set successfully": "Mot de passe défini",
|
||||
"Password settings have changed. Reload the page and try again.": "Les paramètres du mot de passe ont changé. Rechargez la page et réessayez.",
|
||||
"Passwords do not match": "Les mots de passe ne correspondent pas",
|
||||
"Passwords don't match.": "Les mots de passe ne correspondent pas.",
|
||||
"Paste Connection Info": "Coller les infos de connexion",
|
||||
@@ -3677,6 +3701,7 @@
|
||||
"Please wait a moment before trying again.": "Veuillez patienter un instant avant de réessayer.",
|
||||
"Please wait a moment, human check is initializing...": "Veuillez patienter un instant, la vérification humaine s'initialise...",
|
||||
"Please wait before editing to avoid overwriting saved values.": "Veuillez patienter avant de modifier afin d'éviter d'écraser les valeurs enregistrées.",
|
||||
"Please wait before requesting another verification code.": "Veuillez patienter avant de demander un nouveau code.",
|
||||
"Please wait for the current generation to complete": "Veuillez attendre la fin de la génération en cours",
|
||||
"Plugin": "Plugin",
|
||||
"Plugin author": "Auteur du plugin",
|
||||
@@ -4099,6 +4124,8 @@
|
||||
"Reroll": "Relancer",
|
||||
"Research, analysis, scientific reasoning": "Recherche, analyse, raisonnement scientifique",
|
||||
"Resend ({{seconds}}s)": "Renvoyer ({{seconds}}s)",
|
||||
"Resend codes": "Renvoyer les codes",
|
||||
"Resend in {{seconds}}s": "Renvoyer dans {{seconds}} s",
|
||||
"Reserved for viewing complete channel keys after secure verification.": "Réservé à l'affichage des clés complètes des canaux après une vérification sécurisée.",
|
||||
"Reset": "Réinitialiser",
|
||||
"Reset {{count}} active subscriptions": "{{count}} abonnements actifs réinitialisés",
|
||||
@@ -4461,6 +4488,7 @@
|
||||
"Set filters to customize your dashboard statistics and charts.": "Définir des filtres pour personnaliser les statistiques et les graphiques de votre tableau de bord.",
|
||||
"Set filters to narrow down your log search results.": "Définir des filtres pour affiner vos résultats de recherche de journaux.",
|
||||
"Set Header": "Définir l'en-tête",
|
||||
"Set Password": "Définir un mot de passe",
|
||||
"Set Project to io.cloud when creating/selecting key": "Définir le projet sur io.cloud lors de la création/sélection de la clé",
|
||||
"Set quota amount and limits": "Définir le quota et les limites",
|
||||
"Set Request Header": "Définir un en-tête de requête",
|
||||
@@ -4591,6 +4619,7 @@
|
||||
"Start ≤ end: within the day; start > end: across midnight": "Début ≤ fin : plage dans la journée ; début > fin : plage après minuit",
|
||||
"Start a conversation to see messages here": "Démarrez une conversation pour voir les messages ici",
|
||||
"Start a playground chat": "Démarrer une conversation dans le playground",
|
||||
"Start again": "Recommencer",
|
||||
"Start collecting payments globally without registering a company. Built for indie developers, OPC sole proprietorships, and startups. Waffo Pancake acts as your Merchant of Record, taking on the compliance burden of global payment collection — consumption tax, invoicing, subscription management, refunds, and chargebacks. Solo developers can launch fast and stay focused on product instead of compliance. Onboard in minutes — one prompt to a full integration.": "Commencez à encaisser des paiements dans le monde entier sans créer de société. Conçu pour les développeurs indépendants, les entrepreneurs individuels OPC et les startups. Waffo Pancake agit comme Merchant of Record et prend en charge la conformité liée à l’encaissement mondial : taxes à la consommation, facturation, gestion des abonnements, remboursements et rétrofacturations. Les développeurs solo peuvent lancer rapidement leur produit et rester concentrés sur celui-ci plutôt que sur la conformité. Intégration en quelques minutes, d’une seule invite à une intégration complète.",
|
||||
"Start for free with generous limits. No credit card required.": "Commencez gratuitement avec des limites généreuses. Aucune carte de crédit requise.",
|
||||
"Start Time": "Heure de début",
|
||||
@@ -4828,6 +4857,7 @@
|
||||
"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.",
|
||||
"The change succeeded, but the notification email could not be sent.": "La modification a réussi, mais l’e-mail de notification n’a pas pu être envoyé.",
|
||||
"The deployment node that handled the requests": "Le nœud de déploiement ayant traité les requêtes",
|
||||
"The downloaded source does not match the sha256 declared in the index. Do not install it.": "Le code téléchargé ne correspond pas au sha256 déclaré dans l’index. Ne l’installez pas.",
|
||||
"The effective domain for Passkey registration. Must match the current domain or be its parent domain.": "Le domaine effectif pour l'enregistrement de la clé d'accès. Doit correspondre au domaine actuel ou être son domaine parent.",
|
||||
@@ -4902,8 +4932,11 @@
|
||||
"This data may be unreliable, use with caution": "Ces données peuvent être peu fiables, utilisez-les avec prudence",
|
||||
"This device does not support Passkey": "Cet appareil ne prend pas en charge Passkey",
|
||||
"This device does not support Passkey verification.": "Cet appareil ne prend pas en charge la vérification par clé d'accès.",
|
||||
"This email address is already in use.": "Cette adresse e-mail est déjà utilisée.",
|
||||
"This email address is not allowed by the administrator's email policy.": "Cette adresse e-mail n’est pas autorisée par la politique de l’administrateur.",
|
||||
"This expression does not price each combination exactly once, so it opens as a raw expression. Sparse or custom pricing stays in this editor.": "Cette expression ne définit pas exactement un prix pour chaque combinaison ; elle s’ouvre donc dans l’éditeur d’expression brute. Les tarifs partiels ou personnalisés restent dans cet éditeur.",
|
||||
"This expression is too complex for the visual editor. Please switch to expression mode to edit.": "Cette expression est trop complexe pour l'éditeur visuel. Passez en mode expression pour la modifier.",
|
||||
"This external account is already bound.": "Ce compte externe est déjà lié.",
|
||||
"This FAQ entry will be removed from the list.": "Cette entrée de FAQ sera retirée de la liste.",
|
||||
"This feature is experimental. Configuration format and behavior may change.": "Cette fonctionnalité est expérimentale. Le format de configuration et le comportement peuvent changer.",
|
||||
"This field does not support wildcards or regular expressions.": "Ce champ ne prend pas en charge les jokers ni les expressions régulières.",
|
||||
@@ -5057,6 +5090,7 @@
|
||||
"Tokens-only mode will show raw quota values regardless of this toggle.": "Le mode Tokens uniquement affichera les valeurs de quota brutes indépendamment de ce basculement.",
|
||||
"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.": "Le nombre maximal de sessions de connexion actives est atteint. Sur un appareil déjà connecté, ouvrez « Sessions de connexion » et utilisez « Déconnecter les autres sessions » pour les révoquer. Si vous n’avez accès à aucun appareil connecté, réinitialisez votre mot de passe pour fermer toutes les sessions.",
|
||||
"Too many files. Some were not added.": "Trop de fichiers. Certains n'ont pas été ajoutés.",
|
||||
"Too many incorrect codes. Start email verification again.": "Trop de codes incorrects. Recommencez la vérification de l’adresse e-mail.",
|
||||
"Too many login sessions were created recently. Please wait for the rolling window to pass, then try again.": "Trop de sessions de connexion ont été créées récemment. Attendez la fin de la fenêtre glissante, puis réessayez.",
|
||||
"Too many requests": "Trop de requêtes",
|
||||
"Tool / function declarations the model may call": "Déclarations d'outils / fonctions que le modèle peut appeler",
|
||||
@@ -5200,6 +5234,7 @@
|
||||
"Unsaved changes": "Modifications non enregistrées",
|
||||
"Unset price": "Prix non défini",
|
||||
"Unset price models": "Modèles sans prix",
|
||||
"Unsupported account password hashing configuration.": "La configuration du hachage des mots de passe n’est pas prise en charge.",
|
||||
"Unsupported verification method: {{method}}": "Méthode de vérification non prise en charge : {{method}}",
|
||||
"Until": "Jusqu'au",
|
||||
"Untitled": "Sans titre",
|
||||
@@ -5323,6 +5358,7 @@
|
||||
"USD price per 1M input tokens.": "Prix en USD par million de tokens d’entrée.",
|
||||
"USD price per 1M tokens.": "Prix en USD par million de tokens.",
|
||||
"Use +: to add a group, -: to remove a default selectable group, or no prefix to append a group.": "Utilisez +: pour ajouter un groupe, -: pour supprimer un groupe sélectionnable par défaut, ou aucun préfixe pour annexer un groupe.",
|
||||
"Use 8–128 characters.": "Utilisez 8 à 128 caractères.",
|
||||
"Use a compatible browser or device with biometric authentication or a security key to register a Passkey.": "Utilisez un navigateur ou un appareil compatible avec l'authentification biométrique ou une clé de sécurité pour enregistrer une clé d'accès (Passkey).",
|
||||
"Use a different stable value for each instance, then restart the service.": "Utilisez une valeur stable différente pour chaque instance, puis redémarrez le service.",
|
||||
"Use a path to append it to the channel Base URL, or enter a full URL to override the Base URL for this route.": "Utilisez un chemin pour l’ajouter à la Base URL du canal, ou saisissez une URL complète pour remplacer la Base URL pour cette route.",
|
||||
@@ -5435,6 +5471,7 @@
|
||||
"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 could not be sent. Start email verification again.": "L’e-mail de vérification n’a pas pu être envoyé. Recommencez la vérification.",
|
||||
"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.",
|
||||
@@ -5644,6 +5681,7 @@
|
||||
"Your Discord OAuth Client Secret": "Votre secret client OAuth Discord",
|
||||
"Your GitHub OAuth Client ID": "Votre ID Client OAuth GitHub",
|
||||
"Your GitHub OAuth Client Secret": "Votre Secret Client OAuth GitHub",
|
||||
"Your identity has been verified. Continue to the provider to finish linking your account.": "Votre identité a été vérifiée. Poursuivez chez le fournisseur pour terminer la liaison du compte.",
|
||||
"Your new backup codes are ready": "Vos nouveaux codes de secours sont prêts",
|
||||
"Your Referral Link": "Votre lien de parrainage",
|
||||
"Your setup guide is collapsed so usage stays in focus.": "Le guide de configuration est réduit afin de garder l'utilisation au premier plan.",
|
||||
|
||||
@@ -145,13 +145,18 @@
|
||||
"Access tokens are shown only once": "アクセストークンは一度だけ表示されます",
|
||||
"AccessKey / SecretAccessKey": "AccessKey/SecretAccessKey",
|
||||
"Account Actions": "アカウント操作",
|
||||
"Account binding": "アカウント連携",
|
||||
"Account Binding Management": "アカウント連携管理",
|
||||
"Account binding request": "アカウント連携の申請",
|
||||
"Account Bindings": "アカウントバインディング",
|
||||
"Account bindings have changed. Start this operation again.": "アカウントの連携状態が変わりました。操作をやり直してください。",
|
||||
"Account created! Please sign in": "アカウントが作成されました!ログインしてください",
|
||||
"Account deleted successfully": "アカウントが正常に削除されました",
|
||||
"Account ID *": "アカウントID *",
|
||||
"Account Info": "アカウント情報",
|
||||
"Account password change": "アカウントのパスワード変更",
|
||||
"Account security": "アカウントのセキュリティ",
|
||||
"Account unlinking": "アカウントの連携解除",
|
||||
"Account used when authenticating with the SMTP server": "SMTPサーバーで認証する際に使用されるアカウント",
|
||||
"acknowledge the related legal risks": "関連する法的リスクを認識します",
|
||||
"Across all groups": "全グループを通じて",
|
||||
@@ -187,6 +192,7 @@
|
||||
"Add an index URL to browse installable plugins.": "インデックス URL を追加すると、インストール可能なプラグインを閲覧できます。",
|
||||
"Add and submit": "追加して送信",
|
||||
"Add Announcement": "お知らせを追加",
|
||||
"Add another login method before unlinking this account.": "このアカウントの連携を解除する前に、別のログイン方法を追加してください。",
|
||||
"Add API": "API追加",
|
||||
"Add API Shortcut": "API ショートカットを追加",
|
||||
"Add auto group": "自動グループを追加",
|
||||
@@ -689,6 +695,7 @@
|
||||
"Bind Email": "メールアドレス連携",
|
||||
"Bind task plugins": "タスクプラグインを紐付け",
|
||||
"Bind Telegram Account": "Telegram連携",
|
||||
"Bind WeChat": "WeChatを連携",
|
||||
"Bind WeChat Account": "WeChatアカウント連携",
|
||||
"Binding Information": "連携情報",
|
||||
"Binding successful!": "紐付けが成功しました!",
|
||||
@@ -1071,6 +1078,7 @@
|
||||
"Confirm and enable": "確認して有効化",
|
||||
"Confirm Batch Update": "バッチ更新の確認",
|
||||
"Confirm Billing Conflicts": "請求の競合を確認",
|
||||
"Confirm both your current and new email addresses to finish this change.": "現在と新しいメールアドレスの両方を確認して、変更を完了してください。",
|
||||
"Confirm Changes": "変更を確認",
|
||||
"Confirm Cleanup": "クリーンアップを確認",
|
||||
"Confirm cleanup of inactive disk cache?": "非アクティブなディスクキャッシュをクリーンアップしますか?",
|
||||
@@ -1081,6 +1089,7 @@
|
||||
"Confirm Creem Purchase": "Creem 購入を確認",
|
||||
"Confirm delete": "削除の確認",
|
||||
"Confirm disable": "無効化を確認",
|
||||
"Confirm email": "メールアドレスを確認",
|
||||
"Confirm enable": "有効化を確認",
|
||||
"Confirm invalidate": "無効化を確認",
|
||||
"Confirm log cleanup": "ログクリーンアップの確認",
|
||||
@@ -1091,6 +1100,7 @@
|
||||
"Confirm Selection": "選択の確認",
|
||||
"Confirm settings and finish setup": "設定を確認してセットアップを完了",
|
||||
"confirm that I bear legal responsibility arising from deployment": "デプロイ",
|
||||
"Confirm the verification code sent to your new email address.": "新しいメールアドレスに届いた確認コードを入力してください。",
|
||||
"Confirm Unbind": "連携解除を確認",
|
||||
"Confirm usage reset": "使用量リセットの確認",
|
||||
"Confirm your identity before accessing this sensitive action.": "この重要な操作を行う前に本人確認をしてください。",
|
||||
@@ -1127,6 +1137,7 @@
|
||||
"Content width": "コンテンツ幅",
|
||||
"Context": "コンテキスト",
|
||||
"Continue": "続行",
|
||||
"Continue account binding": "アカウント連携を続行",
|
||||
"Continue with {{name}}": "{{name}} で続行",
|
||||
"Continue with an account already linked to your profile.": "連携済みのアカウントで続行してください。",
|
||||
"Continue with Discord": "Discord で続行",
|
||||
@@ -1280,12 +1291,14 @@
|
||||
"Current Billing": "現在の請求",
|
||||
"Current Cache Size": "現在のキャッシュサイズ",
|
||||
"Current domain": "現在のドメイン",
|
||||
"Current email verification code": "現在のメールアドレスの確認コード",
|
||||
"Current email: {{email}}. Enter a new email to change.": "現在のメール: {{email}}。変更するには新しいメールアドレスを入力してください。",
|
||||
"Current key": "現在のキー",
|
||||
"Current legacy JSON is invalid, cannot append": "現在の旧形式JSONが無効なため、追加できません",
|
||||
"Current Level Only": "現在の階層のみ",
|
||||
"Current models for the longest channel in this tag. May not include all models from all channels.": "このタグ内の最も長いチャネルの現在のモデル。すべてのチャネルのすべてのモデルが含まれているわけではない場合があります。",
|
||||
"Current Password": "現在のパスワード",
|
||||
"Current password is incorrect.": "現在のパスワードが正しくありません。",
|
||||
"Current Price": "現在の価格",
|
||||
"Current quota": "現在のクォータ",
|
||||
"Current token": "現在のトークン",
|
||||
@@ -1668,10 +1681,13 @@
|
||||
"Email Address": "メールアドレス",
|
||||
"Email Alias Restriction": "メールエイリアスの制限",
|
||||
"Email bound successfully!": "メールが正常に紐付けられました!",
|
||||
"Email confirmation code resend": "メール確認コードの再送信",
|
||||
"Email Domain Restriction": "メールドメインの制限",
|
||||
"Email Domain Whitelist": "メールドメインのホワイトリスト",
|
||||
"Email Field": "メールフィールド",
|
||||
"Email Verification": "メール認証",
|
||||
"Email verification code is incorrect.": "メールの確認コードが正しくありません。",
|
||||
"Email verification has ended. Start again to continue.": "メール認証は終了しました。続行するにはやり直してください。",
|
||||
"Email, summarisation, knowledge work": "メール・要約・ナレッジワーク",
|
||||
"Embeddings": "埋め込み",
|
||||
"Empty": "空",
|
||||
@@ -1795,6 +1811,7 @@
|
||||
"Enter only a top-level callback domain, for example https://api.example.com, without any path.": "コールバックのトップレベルドメインのみを入力してください。例: https://api.example.com。パスは含めないでください。",
|
||||
"Enter password": "パスワードを入力",
|
||||
"Enter password (8-20 characters)": "パスワードを入力 (8~20文字)",
|
||||
"Enter password (8–128 characters)": "パスワードを入力(8~128文字)",
|
||||
"Enter quota in {{currency}}": "{{currency}} でクォータを入力",
|
||||
"Enter quota in tokens": "トークン単位でクォータを入力",
|
||||
"Enter secret key": "シークレットキーを入力",
|
||||
@@ -1802,6 +1819,7 @@
|
||||
"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 email verification code.": "メールで届いた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を入力、サポート",
|
||||
"Enter the Coze agent ID": "CozeエージェントIDを入力",
|
||||
@@ -2737,6 +2755,7 @@
|
||||
"Logo": "ロゴ",
|
||||
"Logo URL": "ロゴURL",
|
||||
"Logs": "ログ",
|
||||
"Long passwords are unavailable until the password storage upgrade is complete.": "パスワード保存方式の更新が完了するまで、長いパスワードは使用できません。",
|
||||
"Look for a special ratio rule matching this user group and this billing group. If one exists, use its ratio. Otherwise use the billing group base ratio from the pricing table.": "このユーザーグループと課金グループに一致する特別倍率ルールを探します。あればその倍率を、なければ料金表の課金グループの基本倍率を使います。",
|
||||
"Low balance": "残高不足",
|
||||
"Lowest median first-token latency": "最初のトークンまでの中央値レイテンシの最小値",
|
||||
@@ -3035,6 +3054,7 @@
|
||||
"New API": "新しいAPI",
|
||||
"New API <noreply@example.com>": "新しいAPI __ PH_0 __",
|
||||
"New API Project Repository:": "New APIプロジェクトリポジトリ:",
|
||||
"New email verification code": "新しいメールアドレスの確認コード",
|
||||
"New Format Template": "新フォーマットテンプレート",
|
||||
"New Group": "新しいグループ",
|
||||
"New model": "新しいモデル",
|
||||
@@ -3518,6 +3538,7 @@
|
||||
"Passthrough Template": "透過テンプレート",
|
||||
"Password": "パスワード",
|
||||
"Password / Access Token": "パスワード / アクセストークン",
|
||||
"Password authentication is disabled.": "パスワード認証は無効になっています。",
|
||||
"Password changed successfully": "パスワードが正常に変更されました",
|
||||
"Password copied to clipboard: {{password}}": "パスワードがクリップボードにコピーされました:{{password}}",
|
||||
"Password has been copied to clipboard": "パスワードがクリップボードにコピーされました",
|
||||
@@ -3525,9 +3546,12 @@
|
||||
"Password must be at least 8 characters": "パスワードは少なくとも8文字である必要があります",
|
||||
"Password must be at most 20 characters long": "パスワードは20文字以内で入力してください",
|
||||
"Password must be between 8 and 20 characters": "パスワードは8文字以上20文字以下である必要があります",
|
||||
"Password must contain between 8 and 128 characters.": "パスワードは8~128文字で入力してください。",
|
||||
"Password Registration": "パスワード登録",
|
||||
"Password reset and copied to clipboard: {{password}}": "パスワードがリセットされ、クリップボードにコピーされました:{{password}}",
|
||||
"Password reset: {{password}}": "パスワードがリセットされました:{{password}}",
|
||||
"Password set successfully": "パスワードを設定しました",
|
||||
"Password settings have changed. Reload the page and try again.": "パスワード設定が変わりました。ページを再読み込みしてお試しください。",
|
||||
"Passwords do not match": "パスワードが一致しません",
|
||||
"Passwords don't match.": "パスワードが一致しません。",
|
||||
"Paste Connection Info": "接続情報を貼り付け",
|
||||
@@ -3677,6 +3701,7 @@
|
||||
"Please wait a moment before trying again.": "しばらく待ってからもう一度お試しください。",
|
||||
"Please wait a moment, human check is initializing...": "しばらくお待ちください、人間チェックを初期化中です...",
|
||||
"Please wait before editing to avoid overwriting saved values.": "保存済みの値を上書きしないよう、編集前に読み込み完了をお待ちください。",
|
||||
"Please wait before requesting another verification code.": "しばらく待ってから確認コードを再送信してください。",
|
||||
"Please wait for the current generation to complete": "現在の生成が完了するまでお待ちください",
|
||||
"Plugin": "プラグイン",
|
||||
"Plugin author": "プラグイン作成者",
|
||||
@@ -4099,6 +4124,8 @@
|
||||
"Reroll": "やり直し",
|
||||
"Research, analysis, scientific reasoning": "リサーチ・分析・科学的推論",
|
||||
"Resend ({{seconds}}s)": "再送信 ({{seconds}}秒)",
|
||||
"Resend codes": "コードを再送信",
|
||||
"Resend in {{seconds}}s": "{{seconds}}秒後に再送信",
|
||||
"Reserved for viewing complete channel keys after secure verification.": "安全な検証後に完全なチャンネルキーを表示するために予約されています。",
|
||||
"Reset": "リセット",
|
||||
"Reset {{count}} active subscriptions": "{{count}} 件の有効なサブスクリプションをリセットしました",
|
||||
@@ -4461,6 +4488,7 @@
|
||||
"Set filters to customize your dashboard statistics and charts.": "ダッシュボードの統計とグラフをカスタマイズするためにフィルターを設定します。",
|
||||
"Set filters to narrow down your log search results.": "ログ検索結果を絞り込むためにフィルターを設定します。",
|
||||
"Set Header": "ヘッダーを設定",
|
||||
"Set Password": "パスワードを設定",
|
||||
"Set Project to io.cloud when creating/selecting key": "キーを作成/選択する際にプロジェクトを io.cloud に設定",
|
||||
"Set quota amount and limits": "クォータ量と制限を設定",
|
||||
"Set Request Header": "リクエストヘッダーを設定",
|
||||
@@ -4591,6 +4619,7 @@
|
||||
"Start ≤ end: within the day; start > end: across midnight": "開始 ≤ 終了は日内範囲、開始 > 終了は日をまたぐ範囲",
|
||||
"Start a conversation to see messages here": "会話を開始すると、ここにメッセージが表示されます",
|
||||
"Start a playground chat": "Playground でチャットを開始",
|
||||
"Start again": "やり直す",
|
||||
"Start collecting payments globally without registering a company. Built for indie developers, OPC sole proprietorships, and startups. Waffo Pancake acts as your Merchant of Record, taking on the compliance burden of global payment collection — consumption tax, invoicing, subscription management, refunds, and chargebacks. Solo developers can launch fast and stay focused on product instead of compliance. Onboard in minutes — one prompt to a full integration.": "法人を設立せずに世界中で決済を受け付けられます。個人開発者、OPC 個人事業主、スタートアップ向けに設計されています。Waffo Pancake は Merchant of Record として、消費税、請求書、サブスクリプション管理、返金、チャージバックなど、グローバル決済のコンプライアンス負担を引き受けます。個人開発者はコンプライアンスではなくプロダクトに集中しながら素早くローンチできます。数分でオンボーディングし、1 つのプロンプトから完全な統合まで進められます。",
|
||||
"Start for free with generous limits. No credit card required.": "豊富な無料枠で始められます。クレジットカードは不要です。",
|
||||
"Start Time": "開始時間",
|
||||
@@ -4828,6 +4857,7 @@
|
||||
"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 カタログを本当に運用する場合のみ別のストアを固定してください。",
|
||||
"The change succeeded, but the notification email could not be sent.": "変更は完了しましたが、通知メールを送信できませんでした。",
|
||||
"The deployment node that handled the requests": "リクエストを処理したデプロイノード",
|
||||
"The downloaded source does not match the sha256 declared in the index. Do not install it.": "ダウンロードしたソースがインデックスに記載された sha256 と一致しません。インストールしないでください。",
|
||||
"The effective domain for Passkey registration. Must match the current domain or be its parent domain.": "Passkey登録のための有効なドメイン。現在のドメインまたはその親ドメインと一致する必要があります。",
|
||||
@@ -4902,8 +4932,11 @@
|
||||
"This data may be unreliable, use with caution": "このデータは信頼できない可能性があります。注意して使用してください",
|
||||
"This device does not support Passkey": "このデバイスはPasskeyをサポートしていません",
|
||||
"This device does not support Passkey verification.": "このデバイスはPasskey認証をサポートしていません。",
|
||||
"This email address is already in use.": "このメールアドレスはすでに使用されています。",
|
||||
"This email address is not allowed by the administrator's email policy.": "このメールアドレスは管理者のメールポリシーで許可されていません。",
|
||||
"This expression does not price each combination exactly once, so it opens as a raw expression. Sparse or custom pricing stays in this editor.": "この式では各組み合わせの料金がちょうど1回ずつ定義されていないため、生の式として開きます。疎な料金設定やカスタム料金設定はこのエディターに保持されます。",
|
||||
"This expression is too complex for the visual editor. Please switch to expression mode to edit.": "この式はビジュアルエディタでは扱いにくいです。式モードに切り替えて編集してください。",
|
||||
"This external account is already bound.": "この外部アカウントはすでに連携されています。",
|
||||
"This FAQ entry will be removed from the list.": "この FAQ 項目はリストから削除されます。",
|
||||
"This feature is experimental. Configuration format and behavior may change.": "この機能は実験的です。設定フォーマットや動作は変更される可能性があります。",
|
||||
"This field does not support wildcards or regular expressions.": "このフィールドではワイルドカードや正規表現は使えません。",
|
||||
@@ -5057,6 +5090,7 @@
|
||||
"Tokens-only mode will show raw quota values regardless of this toggle.": "トークンのみモードでは、このトグルに関係なく生のクォータ値が表示されます。",
|
||||
"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.": "有効なログインセッション数が上限に達しました。すでにログイン済みの端末で「ログインセッション」を開き、「他のセッションからログアウト」を使用して取り消してください。ログイン済み端末を利用できない場合は、パスワードをリセットしてすべてのセッションからログアウトしてください。",
|
||||
"Too many files. Some were not added.": "ファイルが多すぎます。一部は追加されませんでした。",
|
||||
"Too many incorrect codes. Start email verification again.": "コードの入力ミスが多すぎます。メール認証をやり直してください。",
|
||||
"Too many login sessions were created recently. Please wait for the rolling window to pass, then try again.": "最近作成されたログインセッションが多すぎます。ローリングウィンドウが経過してから、もう一度お試しください。",
|
||||
"Too many requests": "リクエストが多すぎます",
|
||||
"Tool / function declarations the model may call": "モデルが呼び出せるツール / 関数の宣言",
|
||||
@@ -5200,6 +5234,7 @@
|
||||
"Unsaved changes": "未保存の変更",
|
||||
"Unset price": "価格未設定",
|
||||
"Unset price models": "価格が未設定のモデル",
|
||||
"Unsupported account password hashing configuration.": "アカウントのパスワードハッシュ設定がサポートされていません。",
|
||||
"Unsupported verification method: {{method}}": "サポートされていない認証方法です: {{method}}",
|
||||
"Until": "まで",
|
||||
"Untitled": "無題",
|
||||
@@ -5323,6 +5358,7 @@
|
||||
"USD price per 1M input tokens.": "100万入力トークンあたりのUSD価格。",
|
||||
"USD price per 1M tokens.": "100万トークンあたりのUSD価格。",
|
||||
"Use +: to add a group, -: to remove a default selectable group, or no prefix to append a group.": "+: はグループ追加、-: はデフォルト選択可能グループの削除、接頭辞なしはグループ追記に使います。",
|
||||
"Use 8–128 characters.": "8~128文字で設定してください。",
|
||||
"Use a compatible browser or device with biometric authentication or a security key to register a Passkey.": "生体認証またはセキュリティキーを備えた互換性のあるブラウザまたはデバイスを使用して、パスキーを登録してください。",
|
||||
"Use a different stable value for each instance, then restart the service.": "インスタンスごとに異なる安定した値を使用し、その後サービスを再起動してください。",
|
||||
"Use a path to append it to the channel Base URL, or enter a full URL to override the Base URL for this route.": "パスを入力するとチャネルの Base URL に追加されます。完全な URL を入力すると、このルートでは Base URL を使わずその URL を使用します。",
|
||||
@@ -5435,6 +5471,7 @@
|
||||
"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 could not be sent. Start email verification again.": "確認メールを送信できませんでした。メール認証をやり直してください。",
|
||||
"Verification email sent": "認証メールを送信しました",
|
||||
"Verification failed": "認証に失敗しました",
|
||||
"Verification failed. Please try again.": "確認に失敗しました。もう一度お試しください。",
|
||||
@@ -5644,6 +5681,7 @@
|
||||
"Your Discord OAuth Client Secret": "Discord OAuth クライアント シークレット",
|
||||
"Your GitHub OAuth Client ID": "あなたのGitHub OAuthクライアントID",
|
||||
"Your GitHub OAuth Client Secret": "あなたのGitHub OAuthクライアントシークレット",
|
||||
"Your identity has been verified. Continue to the provider to finish linking your account.": "本人確認が完了しました。連携先でアカウント連携を完了してください。",
|
||||
"Your new backup codes are ready": "新しいバックアップコードの準備ができました",
|
||||
"Your Referral Link": "あなたの紹介リンク",
|
||||
"Your setup guide is collapsed so usage stays in focus.": "利用状況に集中できるよう、セットアップガイドを折りたたみました。",
|
||||
|
||||
@@ -145,13 +145,18 @@
|
||||
"Access tokens are shown only once": "Токены доступа отображаются только один раз",
|
||||
"AccessKey / SecretAccessKey": "AccessKey / SecretAccessKey",
|
||||
"Account Actions": "Действия с аккаунтом",
|
||||
"Account binding": "Привязка аккаунта",
|
||||
"Account Binding Management": "Управление привязкой аккаунта",
|
||||
"Account binding request": "Запрос на привязку аккаунта",
|
||||
"Account Bindings": "Привязки аккаунта",
|
||||
"Account bindings have changed. Start this operation again.": "Привязки аккаунта изменились. Начните операцию заново.",
|
||||
"Account created! Please sign in": "Аккаунт создан! Пожалуйста, войдите в систему",
|
||||
"Account deleted successfully": "Аккаунт успешно удалён",
|
||||
"Account ID *": "ID аккаунта *",
|
||||
"Account Info": "Информация об аккаунте",
|
||||
"Account password change": "Изменение пароля аккаунта",
|
||||
"Account security": "Безопасность аккаунта",
|
||||
"Account unlinking": "Отвязка аккаунта",
|
||||
"Account used when authenticating with the SMTP server": "Учетная запись, используемая при аутентификации с SMTP-сервером",
|
||||
"acknowledge the related legal risks": "признаю связанные правовые риски",
|
||||
"Across all groups": "По всем группам",
|
||||
@@ -187,6 +192,7 @@
|
||||
"Add an index URL to browse installable plugins.": "Добавьте URL индекса, чтобы просматривать доступные для установки плагины.",
|
||||
"Add and submit": "Добавить и отправить",
|
||||
"Add Announcement": "Добавить объявление",
|
||||
"Add another login method before unlinking this account.": "Перед отвязкой этого аккаунта добавьте другой способ входа.",
|
||||
"Add API": "Добавить API",
|
||||
"Add API Shortcut": "Добавить ярлык API",
|
||||
"Add auto group": "Добавить автогруппу",
|
||||
@@ -689,6 +695,7 @@
|
||||
"Bind Email": "Привязать Email",
|
||||
"Bind task plugins": "Привязать плагины задач",
|
||||
"Bind Telegram Account": "Привязать аккаунт Telegram",
|
||||
"Bind WeChat": "Привязать WeChat",
|
||||
"Bind WeChat Account": "Привязка аккаунта WeChat",
|
||||
"Binding Information": "Информация о привязке",
|
||||
"Binding successful!": "Привязка успешна!",
|
||||
@@ -1071,6 +1078,7 @@
|
||||
"Confirm and enable": "Подтвердить и включить",
|
||||
"Confirm Batch Update": "Подтвердить пакетное обновление",
|
||||
"Confirm Billing Conflicts": "Подтвердить конфликты выставления счетов",
|
||||
"Confirm both your current and new email addresses to finish this change.": "Подтвердите текущий и новый адреса почты, чтобы завершить изменение.",
|
||||
"Confirm Changes": "Подтвердить изменения",
|
||||
"Confirm Cleanup": "Подтвердить очистку",
|
||||
"Confirm cleanup of inactive disk cache?": "Подтвердить очистку неактивного дискового кэша?",
|
||||
@@ -1081,6 +1089,7 @@
|
||||
"Confirm Creem Purchase": "Подтвердить покупку Creem",
|
||||
"Confirm delete": "Подтвердить удаление",
|
||||
"Confirm disable": "Подтвердить отключение",
|
||||
"Confirm email": "Подтвердить почту",
|
||||
"Confirm enable": "Подтвердить включение",
|
||||
"Confirm invalidate": "Подтвердить аннулирование",
|
||||
"Confirm log cleanup": "Подтвердить очистку логов",
|
||||
@@ -1091,6 +1100,7 @@
|
||||
"Confirm Selection": "Подтвердить выбор",
|
||||
"Confirm settings and finish setup": "Подтвердите настройки и завершите установку",
|
||||
"confirm that I bear legal responsibility arising from deployment": "подтверждаю, что несу юридическую ответственность, возникающую из развертывания",
|
||||
"Confirm the verification code sent to your new email address.": "Введите код подтверждения, отправленный на новую почту.",
|
||||
"Confirm Unbind": "Подтвердить отвязку",
|
||||
"Confirm usage reset": "Подтвердить сброс использования",
|
||||
"Confirm your identity before accessing this sensitive action.": "Подтвердите личность перед выполнением этой важной операции.",
|
||||
@@ -1127,6 +1137,7 @@
|
||||
"Content width": "Ширина контента",
|
||||
"Context": "Контекст",
|
||||
"Continue": "Продолжить",
|
||||
"Continue account binding": "Продолжить привязку аккаунта",
|
||||
"Continue with {{name}}": "Продолжить с {{name}}",
|
||||
"Continue with an account already linked to your profile.": "Продолжите с аккаунтом, уже привязанным к профилю.",
|
||||
"Continue with Discord": "Продолжить с Discord",
|
||||
@@ -1280,12 +1291,14 @@
|
||||
"Current Billing": "Текущие счета",
|
||||
"Current Cache Size": "Текущий размер кэша",
|
||||
"Current domain": "Текущий домен",
|
||||
"Current email verification code": "Код подтверждения текущей почты",
|
||||
"Current email: {{email}}. Enter a new email to change.": "Текущий email: {{email}}. Введите новый email для изменения.",
|
||||
"Current key": "Текущий ключ",
|
||||
"Current legacy JSON is invalid, cannot append": "Текущий JSON старого формата невалиден, добавление невозможно",
|
||||
"Current Level Only": "Только текущий уровень",
|
||||
"Current models for the longest channel in this tag. May not include all models from all channels.": "Текущие модели для самого длинного канала в этом теге. Может не включать все модели из всех каналов.",
|
||||
"Current Password": "Текущий пароль",
|
||||
"Current password is incorrect.": "Текущий пароль неверен.",
|
||||
"Current Price": "Текущая цена",
|
||||
"Current quota": "Текущая квота",
|
||||
"Current token": "Текущий токен",
|
||||
@@ -1668,10 +1681,13 @@
|
||||
"Email Address": "Адрес электронной почты",
|
||||
"Email Alias Restriction": "Ограничение по псевдониму Email",
|
||||
"Email bound successfully!": "Email успешно привязан!",
|
||||
"Email confirmation code resend": "Повторная отправка кода подтверждения почты",
|
||||
"Email Domain Restriction": "Ограничение по домену Email",
|
||||
"Email Domain Whitelist": "Белый список доменов Email",
|
||||
"Email Field": "Поле email",
|
||||
"Email Verification": "Верификация Email",
|
||||
"Email verification code is incorrect.": "Неверный код подтверждения почты.",
|
||||
"Email verification has ended. Start again to continue.": "Подтверждение почты завершено. Начните заново, чтобы продолжить.",
|
||||
"Email, summarisation, knowledge work": "Электронная почта, резюме, knowledge work",
|
||||
"Embeddings": "Встраивания",
|
||||
"Empty": "Пусто",
|
||||
@@ -1795,6 +1811,7 @@
|
||||
"Enter only a top-level callback domain, for example https://api.example.com, without any path.": "Введите только домен верхнего уровня для callback, например https://api.example.com, без пути.",
|
||||
"Enter password": "Введите пароль",
|
||||
"Enter password (8-20 characters)": "Введите пароль (8-20 символов)",
|
||||
"Enter password (8–128 characters)": "Введите пароль (8–128 символов)",
|
||||
"Enter quota in {{currency}}": "Введите квоту в {{currency}}",
|
||||
"Enter quota in tokens": "Введите квоту в токенах",
|
||||
"Enter secret key": "Введите секретный ключ",
|
||||
@@ -1802,6 +1819,7 @@
|
||||
"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 email verification code.": "Введите 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, поддерживает",
|
||||
"Enter the Coze agent ID": "Введите ID агента Coze",
|
||||
@@ -2737,6 +2755,7 @@
|
||||
"Logo": "Логотип",
|
||||
"Logo URL": "URL логотипа",
|
||||
"Logs": "Журналы",
|
||||
"Long passwords are unavailable until the password storage upgrade is complete.": "Длинные пароли будут доступны после обновления системы хранения паролей.",
|
||||
"Look for a special ratio rule matching this user group and this billing group. If one exists, use its ratio. Otherwise use the billing group base ratio from the pricing table.": "Найдите правило особого коэффициента для этой группы пользователя и тарифной группы. Если оно есть — используется его коэффициент, иначе базовый коэффициент тарифной группы.",
|
||||
"Low balance": "Низкий баланс",
|
||||
"Lowest median first-token latency": "Минимальная медианная задержка первого токена",
|
||||
@@ -3035,6 +3054,7 @@
|
||||
"New API": "Новый API",
|
||||
"New API <noreply@example.com>": "Новый API <noreply@example.com>",
|
||||
"New API Project Repository:": "Репозиторий проекта New API:",
|
||||
"New email verification code": "Код подтверждения новой почты",
|
||||
"New Format Template": "Шаблон нового формата",
|
||||
"New Group": "Новая группа",
|
||||
"New model": "Новая модель",
|
||||
@@ -3518,6 +3538,7 @@
|
||||
"Passthrough Template": "Шаблон сквозной передачи",
|
||||
"Password": "Пароль",
|
||||
"Password / Access Token": "Пароль / Токен доступа",
|
||||
"Password authentication is disabled.": "Аутентификация по паролю отключена.",
|
||||
"Password changed successfully": "Пароль успешно изменён",
|
||||
"Password copied to clipboard: {{password}}": "Пароль скопирован в буфер обмена: {{password}}",
|
||||
"Password has been copied to clipboard": "Пароль скопирован в буфер обмена",
|
||||
@@ -3525,9 +3546,12 @@
|
||||
"Password must be at least 8 characters": "Пароль должен содержать не менее 8 символов",
|
||||
"Password must be at most 20 characters long": "Пароль должен содержать не более 20 символов",
|
||||
"Password must be between 8 and 20 characters": "Пароль должен содержать от 8 до 20 символов",
|
||||
"Password must contain between 8 and 128 characters.": "Пароль должен содержать от 8 до 128 символов.",
|
||||
"Password Registration": "Регистрация пароля",
|
||||
"Password reset and copied to clipboard: {{password}}": "Пароль сброшен и скопирован в буфер обмена: {{password}}",
|
||||
"Password reset: {{password}}": "Пароль сброшен: {{password}}",
|
||||
"Password set successfully": "Пароль установлен",
|
||||
"Password settings have changed. Reload the page and try again.": "Настройки пароля изменились. Перезагрузите страницу и повторите попытку.",
|
||||
"Passwords do not match": "Пароли не совпадают",
|
||||
"Passwords don't match.": "Пароли не совпадают.",
|
||||
"Paste Connection Info": "Вставить данные подключения",
|
||||
@@ -3677,6 +3701,7 @@
|
||||
"Please wait a moment before trying again.": "Пожалуйста, подождите немного и попробуйте снова.",
|
||||
"Please wait a moment, human check is initializing...": "Пожалуйста, подождите немного, инициализация проверки человеком...",
|
||||
"Please wait before editing to avoid overwriting saved values.": "Дождитесь загрузки перед редактированием, чтобы не перезаписать сохраненные значения.",
|
||||
"Please wait before requesting another verification code.": "Подождите перед повторным запросом кода подтверждения.",
|
||||
"Please wait for the current generation to complete": "Дождитесь завершения текущей генерации",
|
||||
"Plugin": "Плагин",
|
||||
"Plugin author": "Автор плагина",
|
||||
@@ -4099,6 +4124,8 @@
|
||||
"Reroll": "Повторить",
|
||||
"Research, analysis, scientific reasoning": "Исследования, анализ, научные рассуждения",
|
||||
"Resend ({{seconds}}s)": "Отправить повторно ({{seconds}}с)",
|
||||
"Resend codes": "Отправить коды повторно",
|
||||
"Resend in {{seconds}}s": "Повторная отправка через {{seconds}} с",
|
||||
"Reserved for viewing complete channel keys after secure verification.": "Зарезервировано для просмотра полных ключей каналов после безопасной проверки.",
|
||||
"Reset": "Сброс",
|
||||
"Reset {{count}} active subscriptions": "Сброшено активных подписок: {{count}}",
|
||||
@@ -4461,6 +4488,7 @@
|
||||
"Set filters to customize your dashboard statistics and charts.": "Установите фильтры, чтобы настроить статистику и диаграммы вашей панели управления.",
|
||||
"Set filters to narrow down your log search results.": "Установите фильтры, чтобы сузить результаты поиска по журналам.",
|
||||
"Set Header": "Установить заголовок",
|
||||
"Set Password": "Установить пароль",
|
||||
"Set Project to io.cloud when creating/selecting key": "Установите Проект в io.cloud при создании/выборе ключа",
|
||||
"Set quota amount and limits": "Настройте квоту и лимиты",
|
||||
"Set Request Header": "Установить заголовок запроса",
|
||||
@@ -4591,6 +4619,7 @@
|
||||
"Start ≤ end: within the day; start > end: across midnight": "Начало ≤ конца — в пределах дня, начало > конца — через полночь",
|
||||
"Start a conversation to see messages here": "Начните разговор, чтобы увидеть сообщения здесь",
|
||||
"Start a playground chat": "Начните чат в Playground",
|
||||
"Start again": "Начать заново",
|
||||
"Start collecting payments globally without registering a company. Built for indie developers, OPC sole proprietorships, and startups. Waffo Pancake acts as your Merchant of Record, taking on the compliance burden of global payment collection — consumption tax, invoicing, subscription management, refunds, and chargebacks. Solo developers can launch fast and stay focused on product instead of compliance. Onboard in minutes — one prompt to a full integration.": "Начните принимать платежи по всему миру без регистрации компании. Подходит для независимых разработчиков, индивидуальных предпринимателей OPC и стартапов. Waffo Pancake выступает как Merchant of Record и берет на себя комплаенс глобального приема платежей: потребительские налоги, выставление счетов, управление подписками, возвраты и чарджбеки. Одиночные разработчики могут быстро запуститься и сосредоточиться на продукте, а не на комплаенсе. Подключение за минуты — от одного запроса до полной интеграции.",
|
||||
"Start for free with generous limits. No credit card required.": "Начните бесплатно с щедрыми лимитами. Кредитная карта не требуется.",
|
||||
"Start Time": "Время начала",
|
||||
@@ -4828,6 +4857,7 @@
|
||||
"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.",
|
||||
"The change succeeded, but the notification email could not be sent.": "Изменение выполнено, но отправить уведомление по почте не удалось.",
|
||||
"The deployment node that handled the requests": "Узел развёртывания, обработавший запросы",
|
||||
"The downloaded source does not match the sha256 declared in the index. Do not install it.": "Загруженный код не соответствует sha256, указанному в индексе. Не устанавливайте его.",
|
||||
"The effective domain for Passkey registration. Must match the current domain or be its parent domain.": "Действующий домен для регистрации Passkey. Должен совпадать с текущим доменом или быть его родительским доменом.",
|
||||
@@ -4902,8 +4932,11 @@
|
||||
"This data may be unreliable, use with caution": "Эти данные могут быть ненадежными, используйте с осторожностью",
|
||||
"This device does not support Passkey": "Это устройство не поддерживает Passkey",
|
||||
"This device does not support Passkey verification.": "Это устройство не поддерживает проверку с помощью Passkey.",
|
||||
"This email address is already in use.": "Этот адрес почты уже используется.",
|
||||
"This email address is not allowed by the administrator's email policy.": "Этот адрес почты запрещён политикой администратора.",
|
||||
"This expression does not price each combination exactly once, so it opens as a raw expression. Sparse or custom pricing stays in this editor.": "Это выражение не задаёт цену ровно один раз для каждой комбинации, поэтому оно открыто в режиме исходного выражения. Неполные или пользовательские правила ценообразования остаются в этом редакторе.",
|
||||
"This expression is too complex for the visual editor. Please switch to expression mode to edit.": "Для визуального редактора это выражение слишком сложно. Переключитесь в режим выражения для правки.",
|
||||
"This external account is already bound.": "Этот внешний аккаунт уже привязан.",
|
||||
"This FAQ entry will be removed from the list.": "Эта запись FAQ будет удалена из списка.",
|
||||
"This feature is experimental. Configuration format and behavior may change.": "Эта функция является экспериментальной. Формат конфигурации и поведение могут измениться.",
|
||||
"This field does not support wildcards or regular expressions.": "Это поле не поддерживает подстановочные знаки или регулярные выражения.",
|
||||
@@ -5057,6 +5090,7 @@
|
||||
"Tokens-only mode will show raw quota values regardless of this toggle.": "Режим «только токены» будет показывать необработанные значения квот независимо от этого переключателя.",
|
||||
"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.": "Достигнут лимит активных сеансов входа. На устройстве, где вы уже вошли, откройте «Сеансы входа» и выберите «Завершить другие сеансы», чтобы отозвать их. Если доступа к такому устройству нет, сбросьте пароль, чтобы завершить все сеансы.",
|
||||
"Too many files. Some were not added.": "Слишком много файлов. Некоторые не были добавлены.",
|
||||
"Too many incorrect codes. Start email verification again.": "Слишком много неверных кодов. Начните подтверждение почты заново.",
|
||||
"Too many login sessions were created recently. Please wait for the rolling window to pass, then try again.": "За последнее время создано слишком много сеансов входа. Дождитесь окончания скользящего временного окна и повторите попытку.",
|
||||
"Too many requests": "Слишком много запросов",
|
||||
"Tool / function declarations the model may call": "Объявления инструментов и функций, которые модель может вызывать",
|
||||
@@ -5200,6 +5234,7 @@
|
||||
"Unsaved changes": "Несохранённые изменения",
|
||||
"Unset price": "Цена не задана",
|
||||
"Unset price models": "Модели с неустановленной ценой",
|
||||
"Unsupported account password hashing configuration.": "Неподдерживаемая конфигурация хеширования паролей.",
|
||||
"Unsupported verification method: {{method}}": "Неподдерживаемый способ проверки: {{method}}",
|
||||
"Until": "До",
|
||||
"Untitled": "Без названия",
|
||||
@@ -5323,6 +5358,7 @@
|
||||
"USD price per 1M input tokens.": "Цена в USD за 1 млн входных токенов.",
|
||||
"USD price per 1M tokens.": "Цена в USD за 1 млн токенов.",
|
||||
"Use +: to add a group, -: to remove a default selectable group, or no prefix to append a group.": "Используйте +: для добавления группы, -: для удаления выбираемой по умолчанию группы, без префикса — для добавления в конец.",
|
||||
"Use 8–128 characters.": "Используйте от 8 до 128 символов.",
|
||||
"Use a compatible browser or device with biometric authentication or a security key to register a Passkey.": "Используйте совместимый браузер или устройство с биометрической аутентификацией или ключ безопасности для регистрации ключа доступа.",
|
||||
"Use a different stable value for each instance, then restart the service.": "Используйте разные стабильные значения для каждого экземпляра, затем перезапустите сервис.",
|
||||
"Use a path to append it to the channel Base URL, or enter a full URL to override the Base URL for this route.": "Укажите путь, чтобы добавить его к Base URL канала, или введите полный URL, чтобы переопределить Base URL для этого маршрута.",
|
||||
@@ -5435,6 +5471,7 @@
|
||||
"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 could not be sent. Start email verification again.": "Не удалось отправить письмо с кодом. Начните подтверждение почты заново.",
|
||||
"Verification email sent": "Письмо для подтверждения отправлено",
|
||||
"Verification failed": "Подтверждение не удалось",
|
||||
"Verification failed. Please try again.": "Подтверждение не удалось. Повторите попытку.",
|
||||
@@ -5644,6 +5681,7 @@
|
||||
"Your Discord OAuth Client Secret": "Ваш Discord OAuth Client Secret",
|
||||
"Your GitHub OAuth Client ID": "Ваш ID клиента GitHub OAuth",
|
||||
"Your GitHub OAuth Client Secret": "Ваш секрет клиента GitHub OAuth",
|
||||
"Your identity has been verified. Continue to the provider to finish linking your account.": "Ваша личность подтверждена. Перейдите к провайдеру, чтобы завершить привязку аккаунта.",
|
||||
"Your new backup codes are ready": "Ваши новые резервные коды готовы",
|
||||
"Your Referral Link": "Ваша реферальная ссылка",
|
||||
"Your setup guide is collapsed so usage stays in focus.": "Руководство свернуто, чтобы основные показатели оставались в фокусе.",
|
||||
|
||||
@@ -145,13 +145,18 @@
|
||||
"Access tokens are shown only once": "Token truy cập chỉ được hiển thị một lần",
|
||||
"AccessKey / SecretAccessKey": "AccessKey / SecretAccessKey",
|
||||
"Account Actions": "Thao tác tài khoản",
|
||||
"Account binding": "Liên kết tài khoản",
|
||||
"Account Binding Management": "Quản lý liên kết tài khoản",
|
||||
"Account binding request": "Yêu cầu liên kết tài khoản",
|
||||
"Account Bindings": "Liên kết tài khoản",
|
||||
"Account bindings have changed. Start this operation again.": "Liên kết tài khoản đã thay đổi. Vui lòng thực hiện lại.",
|
||||
"Account created! Please sign in": "Tài khoản đã được tạo! Vui lòng đăng nhập",
|
||||
"Account deleted successfully": "Tài khoản đã được xóa thành công",
|
||||
"Account ID *": "ID tài khoản *",
|
||||
"Account Info": "Thông tin tài khoản",
|
||||
"Account password change": "Thay đổi mật khẩu tài khoản",
|
||||
"Account security": "Bảo mật tài khoản",
|
||||
"Account unlinking": "Hủy liên kết tài khoản",
|
||||
"Account used when authenticating with the SMTP server": "Tài khoản được sử dụng khi xác thực với máy chủ SMTP",
|
||||
"acknowledge the related legal risks": "thừa nhận các rủi ro pháp lý liên quan",
|
||||
"Across all groups": "Trên mọi nhóm",
|
||||
@@ -187,6 +192,7 @@
|
||||
"Add an index URL to browse installable plugins.": "Thêm một URL chỉ mục để xem các plugin có thể cài đặt.",
|
||||
"Add and submit": "Thêm và gửi",
|
||||
"Add Announcement": "Thêm Thông báo",
|
||||
"Add another login method before unlinking this account.": "Thêm phương thức đăng nhập khác trước khi hủy liên kết tài khoản này.",
|
||||
"Add API": "Thêm API",
|
||||
"Add API Shortcut": "Thêm lối tắt API",
|
||||
"Add auto group": "Thêm nhóm tự động",
|
||||
@@ -689,6 +695,7 @@
|
||||
"Bind Email": "Liên kết Email",
|
||||
"Bind task plugins": "Gắn plugin tác vụ",
|
||||
"Bind Telegram Account": "Liên kết tài khoản Telegram",
|
||||
"Bind WeChat": "Liên kết WeChat",
|
||||
"Bind WeChat Account": "Liên kết tài khoản WeChat",
|
||||
"Binding Information": "Thông tin Ràng buộc",
|
||||
"Binding successful!": "Liên kết thành công!",
|
||||
@@ -1071,6 +1078,7 @@
|
||||
"Confirm and enable": "Xác nhận và bật",
|
||||
"Confirm Batch Update": "Xác nhận Cập nhật Hàng loạt",
|
||||
"Confirm Billing Conflicts": "Xác nhận xung đột thanh toán",
|
||||
"Confirm both your current and new email addresses to finish this change.": "Xác nhận cả email hiện tại và email mới để hoàn tất thay đổi.",
|
||||
"Confirm Changes": "Xác nhận thay đổi",
|
||||
"Confirm Cleanup": "Xác nhận dọn dẹp",
|
||||
"Confirm cleanup of inactive disk cache?": "Xác nhận dọn dẹp bộ nhớ đệm đĩa không hoạt động?",
|
||||
@@ -1081,6 +1089,7 @@
|
||||
"Confirm Creem Purchase": "Xác nhận mua Creem",
|
||||
"Confirm delete": "Xác nhận xóa",
|
||||
"Confirm disable": "Xác nhận vô hiệu hóa",
|
||||
"Confirm email": "Xác nhận email",
|
||||
"Confirm enable": "Xác nhận kích hoạt",
|
||||
"Confirm invalidate": "Xác nhận vô hiệu hóa",
|
||||
"Confirm log cleanup": "Xác nhận dọn dẹp nhật ký",
|
||||
@@ -1091,6 +1100,7 @@
|
||||
"Confirm Selection": "Xác nhận lựa chọn",
|
||||
"Confirm settings and finish setup": "Xác nhận cài đặt và hoàn tất thiết lập",
|
||||
"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 the verification code sent to your new email address.": "Nhập mã xác minh đã gửi đến địa chỉ email mới.",
|
||||
"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.",
|
||||
@@ -1127,6 +1137,7 @@
|
||||
"Content width": "Chiều rộng nội dung",
|
||||
"Context": "Ngữ cảnh",
|
||||
"Continue": "Tiếp tục",
|
||||
"Continue account binding": "Tiếp tục liên kết tài khoản",
|
||||
"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",
|
||||
@@ -1280,12 +1291,14 @@
|
||||
"Current Billing": "Thanh toán hiện tại",
|
||||
"Current Cache Size": "Kích thước bộ nhớ đệm hiện tại",
|
||||
"Current domain": "Tên miền hiện tại",
|
||||
"Current email verification code": "Mã xác minh email hiện tại",
|
||||
"Current email: {{email}}. Enter a new email to change.": "Email hiện tại: {{email}}. Nhập email mới để thay đổi.",
|
||||
"Current key": "Khóa hiện tại",
|
||||
"Current legacy JSON is invalid, cannot append": "JSON định dạng cũ hiện tại không hợp lệ, không thể thêm",
|
||||
"Current Level Only": "Chỉ cấp hiện tại",
|
||||
"Current models for the longest channel in this tag. May not include all models from all channels.": "Các mô hình hiện tại cho kênh dài nhất trong thẻ này. Có thể không bao gồm tất cả các mô hình từ tất cả các kênh.",
|
||||
"Current Password": "Mật khẩu hiện tại",
|
||||
"Current password is incorrect.": "Mật khẩu hiện tại không đúng.",
|
||||
"Current Price": "Giá hiện tại",
|
||||
"Current quota": "Hạn mức hiện tại",
|
||||
"Current token": "Token hiện tại",
|
||||
@@ -1668,10 +1681,13 @@
|
||||
"Email Address": "Địa chỉ email",
|
||||
"Email Alias Restriction": "Hạn chế Bí danh Email",
|
||||
"Email bound successfully!": "Email đã được liên kết thành công!",
|
||||
"Email confirmation code resend": "Gửi lại mã xác nhận email",
|
||||
"Email Domain Restriction": "Hạn chế Tên miền Email",
|
||||
"Email Domain Whitelist": "Danh sách trắng tên miền email",
|
||||
"Email Field": "Trường Email",
|
||||
"Email Verification": "Xác minh Email",
|
||||
"Email verification code is incorrect.": "Mã xác minh email không đúng.",
|
||||
"Email verification has ended. Start again to continue.": "Xác minh email đã kết thúc. Vui lòng bắt đầu lại để tiếp tục.",
|
||||
"Email, summarisation, knowledge work": "Email, tóm tắt, làm việc tri thức",
|
||||
"Embeddings": "Embeddings",
|
||||
"Empty": "Trống",
|
||||
@@ -1795,6 +1811,7 @@
|
||||
"Enter only a top-level callback domain, for example https://api.example.com, without any path.": "Chỉ nhập tên miền callback cấp cao nhất, ví dụ https://api.example.com, không kèm đường dẫn.",
|
||||
"Enter password": "Nhập mật khẩu",
|
||||
"Enter password (8-20 characters)": "Nhập mật khẩu (8-20 ký tự)",
|
||||
"Enter password (8–128 characters)": "Nhập mật khẩu (8–128 ký tự)",
|
||||
"Enter quota in {{currency}}": "Nhập hạn mức bằng {{currency}}",
|
||||
"Enter quota in tokens": "Nhập hạn mức bằng token",
|
||||
"Enter secret key": "Nhập khóa bí mật",
|
||||
@@ -1802,6 +1819,7 @@
|
||||
"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 email verification code.": "Nhập mã xác minh email gồm 6 chữ số.",
|
||||
"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ợ",
|
||||
"Enter the Coze agent ID": "Nhập ID tác nhân Coze",
|
||||
@@ -2737,6 +2755,7 @@
|
||||
"Logo": "Logo",
|
||||
"Logo URL": "URL Logo",
|
||||
"Logs": "Nhật ký",
|
||||
"Long passwords are unavailable until the password storage upgrade is complete.": "Mật khẩu dài chỉ khả dụng sau khi hoàn tất nâng cấp hệ thống lưu trữ mật khẩu.",
|
||||
"Look for a special ratio rule matching this user group and this billing group. If one exists, use its ratio. Otherwise use the billing group base ratio from the pricing table.": "Tìm quy tắc hệ số đặc biệt khớp với nhóm người dùng và nhóm tính phí này. Nếu có thì dùng hệ số của quy tắc, nếu không thì dùng hệ số cơ bản của nhóm tính phí trong bảng định giá.",
|
||||
"Low balance": "Số dư thấp",
|
||||
"Lowest median first-token latency": "Độ trễ trung vị token đầu tiên thấp nhất",
|
||||
@@ -3035,6 +3054,7 @@
|
||||
"New API": "API mới",
|
||||
"New API <noreply@example.com>": "API mới <noreply@example.com>",
|
||||
"New API Project Repository:": "Kho lưu trữ Dự án API Mới:",
|
||||
"New email verification code": "Mã xác minh email mới",
|
||||
"New Format Template": "Mẫu định dạng mới",
|
||||
"New Group": "Nhóm mới",
|
||||
"New model": "Mô hình mới",
|
||||
@@ -3518,6 +3538,7 @@
|
||||
"Passthrough Template": "Mẫu truyền qua",
|
||||
"Password": "Mật khẩu",
|
||||
"Password / Access Token": "Mật khẩu / Access Token",
|
||||
"Password authentication is disabled.": "Xác thực bằng mật khẩu đã bị tắt.",
|
||||
"Password changed successfully": "Đổi mật khẩu thành công",
|
||||
"Password copied to clipboard: {{password}}": "Mật khẩu đã sao chép vào clipboard: {{password}}",
|
||||
"Password has been copied to clipboard": "Mật khẩu đã được sao chép vào bộ nhớ tạm",
|
||||
@@ -3525,9 +3546,12 @@
|
||||
"Password must be at least 8 characters": "Mật khẩu phải có ít nhất 8 ký tự",
|
||||
"Password must be at most 20 characters long": "Mật khẩu tối đa 20 ký tự",
|
||||
"Password must be between 8 and 20 characters": "Mật khẩu phải từ 8 đến 20 ký tự",
|
||||
"Password must contain between 8 and 128 characters.": "Mật khẩu phải có từ 8 đến 128 ký tự.",
|
||||
"Password Registration": "Đăng ký mật khẩu",
|
||||
"Password reset and copied to clipboard: {{password}}": "Mật khẩu đã đặt lại và sao chép vào clipboard: {{password}}",
|
||||
"Password reset: {{password}}": "Mật khẩu đã đặt lại: {{password}}",
|
||||
"Password set successfully": "Đã đặt mật khẩu thành công",
|
||||
"Password settings have changed. Reload the page and try again.": "Cài đặt mật khẩu đã thay đổi. Tải lại trang và thử lại.",
|
||||
"Passwords do not match": "Mật khẩu không khớp",
|
||||
"Passwords don't match.": "Mật khẩu không khớp.",
|
||||
"Paste Connection Info": "Dán thông tin kết nối",
|
||||
@@ -3677,6 +3701,7 @@
|
||||
"Please wait a moment before trying again.": "Vui lòng chờ một lát rồi thử lại.",
|
||||
"Please wait a moment, human check is initializing...": "Vui lòng đợi một chút, kiểm tra con người đang khởi tạo...",
|
||||
"Please wait before editing to avoid overwriting saved values.": "Vui lòng chờ trước khi chỉnh sửa để tránh ghi đè các giá trị đã lưu.",
|
||||
"Please wait before requesting another verification code.": "Vui lòng đợi trước khi yêu cầu mã xác minh khác.",
|
||||
"Please wait for the current generation to complete": "Vui lòng đợi lượt tạo hiện tại hoàn tất",
|
||||
"Plugin": "Plugin",
|
||||
"Plugin author": "Tác giả plugin",
|
||||
@@ -4099,6 +4124,8 @@
|
||||
"Reroll": "Quay lại",
|
||||
"Research, analysis, scientific reasoning": "Nghiên cứu, phân tích, suy luận khoa học",
|
||||
"Resend ({{seconds}}s)": "Gửi lại ({{seconds}}s)",
|
||||
"Resend codes": "Gửi lại mã",
|
||||
"Resend in {{seconds}}s": "Gửi lại sau {{seconds}} giây",
|
||||
"Reserved for viewing complete channel keys after secure verification.": "Dành riêng để xem khóa kênh đầy đủ sau khi xác minh bảo mật.",
|
||||
"Reset": "Đặt lại",
|
||||
"Reset {{count}} active subscriptions": "Đã đặt lại {{count}} gói đăng ký đang hoạt động",
|
||||
@@ -4461,6 +4488,7 @@
|
||||
"Set filters to customize your dashboard statistics and charts.": "Đặt bộ lọc để tùy chỉnh số liệu thống kê và biểu đồ trên bảng điều khiển của bạn.",
|
||||
"Set filters to narrow down your log search results.": "Đặt bộ lọc để thu hẹp kết quả tìm kiếm nhật ký của bạn.",
|
||||
"Set Header": "Đặt tiêu đề",
|
||||
"Set Password": "Đặt mật khẩu",
|
||||
"Set Project to io.cloud when creating/selecting key": "Đặt Dự án thành io.cloud khi tạo/chọn khóa",
|
||||
"Set quota amount and limits": "Thiết lập hạn mức và giới hạn",
|
||||
"Set Request Header": "Đặt header yêu cầu",
|
||||
@@ -4591,6 +4619,7 @@
|
||||
"Start ≤ end: within the day; start > end: across midnight": "Bắt đầu ≤ kết thúc: trong ngày; bắt đầu > kết thúc: qua nửa đêm",
|
||||
"Start a conversation to see messages here": "Bắt đầu một cuộc trò chuyện để xem tin nhắn tại đây",
|
||||
"Start a playground chat": "Bắt đầu cuộc trò chuyện trong playground",
|
||||
"Start again": "Bắt đầu lại",
|
||||
"Start collecting payments globally without registering a company. Built for indie developers, OPC sole proprietorships, and startups. Waffo Pancake acts as your Merchant of Record, taking on the compliance burden of global payment collection — consumption tax, invoicing, subscription management, refunds, and chargebacks. Solo developers can launch fast and stay focused on product instead of compliance. Onboard in minutes — one prompt to a full integration.": "Bắt đầu thu thanh toán toàn cầu mà không cần đăng ký công ty. Dành cho lập trình viên độc lập, chủ sở hữu OPC và startup. Waffo Pancake đóng vai trò Merchant of Record, chịu trách nhiệm tuân thủ cho việc thu thanh toán toàn cầu — thuế tiêu dùng, hóa đơn, quản lý đăng ký, hoàn tiền và tranh chấp thanh toán. Lập trình viên cá nhân có thể ra mắt nhanh và tập trung vào sản phẩm thay vì tuân thủ. Onboard trong vài phút — từ một prompt đến tích hợp hoàn chỉnh.",
|
||||
"Start for free with generous limits. No credit card required.": "Bắt đầu miễn phí với giới hạn hào phóng. Không cần thẻ tín dụng.",
|
||||
"Start Time": "Thời gian bắt đầu",
|
||||
@@ -4828,6 +4857,7 @@
|
||||
"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.",
|
||||
"The change succeeded, but the notification email could not be sent.": "Thay đổi đã hoàn tất nhưng không thể gửi email thông báo.",
|
||||
"The deployment node that handled the requests": "Nút triển khai đã xử lý các yêu cầu",
|
||||
"The downloaded source does not match the sha256 declared in the index. Do not install it.": "Mã nguồn đã tải không khớp với sha256 khai báo trong chỉ mục. Đừng cài đặt nó.",
|
||||
"The effective domain for Passkey registration. Must match the current domain or be its parent domain.": "Mi",
|
||||
@@ -4902,8 +4932,11 @@
|
||||
"This data may be unreliable, use with caution": "Dữ liệu này có thể không đáng tin cậy, sử dụng thận trọng",
|
||||
"This device does not support Passkey": "Thiết bị này không hỗ trợ Passkey",
|
||||
"This device does not support Passkey verification.": "Thiết bị này không hỗ trợ xác minh Passkey.",
|
||||
"This email address is already in use.": "Địa chỉ email này đã được sử dụng.",
|
||||
"This email address is not allowed by the administrator's email policy.": "Địa chỉ email này không được chính sách email của quản trị viên cho phép.",
|
||||
"This expression does not price each combination exactly once, so it opens as a raw expression. Sparse or custom pricing stays in this editor.": "Biểu thức này không định giá chính xác một lần cho từng tổ hợp, vì vậy nó được mở dưới dạng biểu thức thô. Cách định giá không đầy đủ hoặc tùy chỉnh vẫn được giữ trong trình chỉnh sửa này.",
|
||||
"This expression is too complex for the visual editor. Please switch to expression mode to edit.": "Biểu thức này quá phức tạp cho trình sửa trực quan. Hãy chuyển sang chế độ biểu thức để chỉnh sửa.",
|
||||
"This external account is already bound.": "Tài khoản bên ngoài này đã được liên kết.",
|
||||
"This FAQ entry will be removed from the list.": "Mục FAQ này sẽ bị xóa khỏi danh sách.",
|
||||
"This feature is experimental. Configuration format and behavior may change.": "Tính năng này đang ở giai đoạn thử nghiệm. Định dạng cấu hình và hành vi có thể thay đổi.",
|
||||
"This field does not support wildcards or regular expressions.": "Trường này không hỗ trợ ký tự đại diện hoặc biểu thức chính quy.",
|
||||
@@ -5057,6 +5090,7 @@
|
||||
"Tokens-only mode will show raw quota values regardless of this toggle.": "Chế độ Tokens-only sẽ hiển thị giá trị quota thô bất kể tùy chọn này.",
|
||||
"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.": "Đã đạt giới hạn phiên đăng nhập đang hoạt động. Trên một thiết bị đã đăng nhập, hãy mở “Phiên đăng nhập” và dùng “Đăng xuất các phiên khác” để thu hồi chúng. Nếu bạn không thể truy cập thiết bị nào đã đăng nhập, hãy đặt lại mật khẩu để đăng xuất khỏi tất cả phiên.",
|
||||
"Too many files. Some were not added.": "Quá nhiều tệp. Một số không được thêm.",
|
||||
"Too many incorrect codes. Start email verification again.": "Nhập sai mã quá nhiều lần. Vui lòng bắt đầu xác minh email lại.",
|
||||
"Too many login sessions were created recently. Please wait for the rolling window to pass, then try again.": "Gần đây đã tạo quá nhiều phiên đăng nhập. Vui lòng chờ cửa sổ thời gian trượt kết thúc rồi thử lại.",
|
||||
"Too many requests": "Quá nhiều yêu cầu",
|
||||
"Tool / function declarations the model may call": "Khai báo công cụ / hàm mà model có thể gọi",
|
||||
@@ -5200,6 +5234,7 @@
|
||||
"Unsaved changes": "Thay đổi chưa được lưu",
|
||||
"Unset price": "Chưa đặt giá",
|
||||
"Unset price models": "Mô hình chưa thiết lập giá",
|
||||
"Unsupported account password hashing configuration.": "Cấu hình băm mật khẩu tài khoản không được hỗ trợ.",
|
||||
"Unsupported verification method: {{method}}": "Phương thức xác minh không được hỗ trợ: {{method}}",
|
||||
"Until": "Cho đến",
|
||||
"Untitled": "Không có tiêu đề",
|
||||
@@ -5323,6 +5358,7 @@
|
||||
"USD price per 1M input tokens.": "Giá USD cho mỗi 1 triệu token đầu vào.",
|
||||
"USD price per 1M tokens.": "Giá USD cho mỗi 1 triệu token.",
|
||||
"Use +: to add a group, -: to remove a default selectable group, or no prefix to append a group.": "Dùng +: để thêm nhóm, -: để xóa nhóm có thể chọn mặc định, hoặc không có tiền tố để nối nhóm.",
|
||||
"Use 8–128 characters.": "Sử dụng 8–128 ký tự.",
|
||||
"Use a compatible browser or device with biometric authentication or a security key to register a Passkey.": "Sử dụng trình duyệt hoặc thiết bị tương thích có xác thực sinh trắc học hoặc khóa bảo mật để đăng ký Khóa truy cập.",
|
||||
"Use a different stable value for each instance, then restart the service.": "Dùng một giá trị ổn định khác nhau cho mỗi phiên bản, sau đó khởi động lại dịch vụ.",
|
||||
"Use a path to append it to the channel Base URL, or enter a full URL to override the Base URL for this route.": "Dùng đường dẫn để nối vào Base URL của kênh, hoặc nhập URL đầy đủ để ghi đè Base URL cho tuyến này.",
|
||||
@@ -5435,6 +5471,7 @@
|
||||
"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 could not be sent. Start email verification again.": "Không thể gửi email xác minh. Vui lòng bắt đầu xác minh email 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.",
|
||||
@@ -5644,6 +5681,7 @@
|
||||
"Your Discord OAuth Client Secret": "Discord OAuth Client Secret của bạn",
|
||||
"Your GitHub OAuth Client ID": "Client ID OAuth GitHub của bạn",
|
||||
"Your GitHub OAuth Client Secret": "Bí mật ứng dụng OAuth của GitHub của bạn",
|
||||
"Your identity has been verified. Continue to the provider to finish linking your account.": "Danh tính đã được xác minh. Tiếp tục đến nhà cung cấp để hoàn tất liên kết tài khoản.",
|
||||
"Your new backup codes are ready": "Mã dự phòng mới của bạn đã sẵn sàng",
|
||||
"Your Referral Link": "Liên kết giới thiệu của bạn",
|
||||
"Your setup guide is collapsed so usage stays in focus.": "Hướng dẫn thiết lập đã thu gọn để giữ phần sử dụng ở vị trí nổi bật.",
|
||||
|
||||
@@ -145,13 +145,18 @@
|
||||
"Access tokens are shown only once": "存取令牌僅顯示一次",
|
||||
"AccessKey / SecretAccessKey": "AccessKey / SecretAccessKey",
|
||||
"Account Actions": "帳戶操作",
|
||||
"Account binding": "帳戶綁定",
|
||||
"Account Binding Management": "用戶連結管理",
|
||||
"Account binding request": "帳戶綁定請求",
|
||||
"Account Bindings": "用戶連結",
|
||||
"Account bindings have changed. Start this operation again.": "帳戶綁定已變更,請重新操作。",
|
||||
"Account created! Please sign in": "用戶已建立!請登入",
|
||||
"Account deleted successfully": "用戶刪除成功",
|
||||
"Account ID *": "用戶 ID *",
|
||||
"Account Info": "用戶資訊",
|
||||
"Account password change": "帳戶密碼變更",
|
||||
"Account security": "帳戶安全",
|
||||
"Account unlinking": "帳戶解除綁定",
|
||||
"Account used when authenticating with the SMTP server": "用於與 SMTP 伺服器進行身份驗證的用戶",
|
||||
"acknowledge the related legal risks": "確認相關法律風險",
|
||||
"Across all groups": "跨所有分組",
|
||||
@@ -187,6 +192,7 @@
|
||||
"Add an index URL to browse installable plugins.": "新增一個索引 URL 即可瀏覽可安裝的外掛。",
|
||||
"Add and submit": "新增並提交",
|
||||
"Add Announcement": "新增公告",
|
||||
"Add another login method before unlinking this account.": "請先新增其他登入方式,再解除此帳戶綁定。",
|
||||
"Add API": "新增 API",
|
||||
"Add API Shortcut": "新增 API 快捷方式",
|
||||
"Add auto group": "新增自動分組",
|
||||
@@ -689,6 +695,7 @@
|
||||
"Bind Email": "連結電郵",
|
||||
"Bind task plugins": "綁定任務外掛",
|
||||
"Bind Telegram Account": "連結 Telegram 用戶",
|
||||
"Bind WeChat": "綁定微信",
|
||||
"Bind WeChat Account": "連結微信用戶",
|
||||
"Binding Information": "連結資訊",
|
||||
"Binding successful!": "連結成功!",
|
||||
@@ -1071,6 +1078,7 @@
|
||||
"Confirm and enable": "確認並啟用",
|
||||
"Confirm Batch Update": "確認大量更新",
|
||||
"Confirm Billing Conflicts": "確認賬單衝突",
|
||||
"Confirm both your current and new email addresses to finish this change.": "請確認目前信箱和新信箱,完成此次變更。",
|
||||
"Confirm Changes": "確認更改",
|
||||
"Confirm Cleanup": "確認清理",
|
||||
"Confirm cleanup of inactive disk cache?": "確認清理不活躍的磁碟緩存?",
|
||||
@@ -1081,6 +1089,7 @@
|
||||
"Confirm Creem Purchase": "確認 Creem 購買",
|
||||
"Confirm delete": "確認刪除",
|
||||
"Confirm disable": "確認停用",
|
||||
"Confirm email": "確認信箱",
|
||||
"Confirm enable": "確認啟用",
|
||||
"Confirm invalidate": "確認作廢",
|
||||
"Confirm log cleanup": "確認日誌清理",
|
||||
@@ -1091,6 +1100,7 @@
|
||||
"Confirm Selection": "確認選擇",
|
||||
"Confirm settings and finish setup": "確認設定並完成安裝",
|
||||
"confirm that I bear legal responsibility arising from deployment": "確認承擔因部署",
|
||||
"Confirm the verification code sent to your new email address.": "請輸入傳送至新信箱的驗證碼。",
|
||||
"Confirm Unbind": "確認解綁",
|
||||
"Confirm usage reset": "確認重置用量",
|
||||
"Confirm your identity before accessing this sensitive action.": "執行此敏感操作前,請先驗證身分。",
|
||||
@@ -1127,6 +1137,7 @@
|
||||
"Content width": "內容寬度",
|
||||
"Context": "上下文",
|
||||
"Continue": "繼續",
|
||||
"Continue account binding": "繼續綁定帳戶",
|
||||
"Continue with {{name}}": "使用 {{name}} 繼續",
|
||||
"Continue with an account already linked to your profile.": "使用已綁定的帳號繼續驗證。",
|
||||
"Continue with Discord": "使用 Discord 繼續",
|
||||
@@ -1280,12 +1291,14 @@
|
||||
"Current Billing": "目前收費",
|
||||
"Current Cache Size": "目前緩存大小",
|
||||
"Current domain": "目前域名",
|
||||
"Current email verification code": "目前信箱驗證碼",
|
||||
"Current email: {{email}}. Enter a new email to change.": "目前電郵:{{email}}。輸入新電郵以更改。",
|
||||
"Current key": "目前金鑰",
|
||||
"Current legacy JSON is invalid, cannot append": "目前舊格式 JSON 不合法,無法追加模板",
|
||||
"Current Level Only": "僅目前層",
|
||||
"Current models for the longest channel in this tag. May not include all models from all channels.": "此標籤中最長渠道的目前模型。可能不包括所有渠道的所有模型。",
|
||||
"Current Password": "目前密碼",
|
||||
"Current password is incorrect.": "目前密碼不正確。",
|
||||
"Current Price": "目前價格",
|
||||
"Current quota": "目前額度",
|
||||
"Current token": "目前權杖",
|
||||
@@ -1668,10 +1681,13 @@
|
||||
"Email Address": "電郵地址",
|
||||
"Email Alias Restriction": "電郵別名限制",
|
||||
"Email bound successfully!": "電郵連結成功!",
|
||||
"Email confirmation code resend": "重送信箱確認碼",
|
||||
"Email Domain Restriction": "電郵域限制",
|
||||
"Email Domain Whitelist": "電郵域白名單",
|
||||
"Email Field": "電郵欄位",
|
||||
"Email Verification": "電郵驗證",
|
||||
"Email verification code is incorrect.": "信箱驗證碼不正確。",
|
||||
"Email verification has ended. Start again to continue.": "信箱驗證已結束,請重新開始。",
|
||||
"Email, summarisation, knowledge work": "郵件、摘要與知識工作",
|
||||
"Embeddings": "嵌入",
|
||||
"Empty": "空",
|
||||
@@ -1795,6 +1811,7 @@
|
||||
"Enter only a top-level callback domain, for example https://api.example.com, without any path.": "只填寫Callback頂級域名,例如 https://api.example.com,不要帶任何路徑。",
|
||||
"Enter password": "輸入密碼",
|
||||
"Enter password (8-20 characters)": "輸入密碼(8-20 個字元)",
|
||||
"Enter password (8–128 characters)": "輸入密碼(8–128 個字元)",
|
||||
"Enter quota in {{currency}}": "輸入 {{currency}} 額度",
|
||||
"Enter quota in tokens": "輸入令牌配額",
|
||||
"Enter secret key": "輸入金鑰",
|
||||
@@ -1802,6 +1819,7 @@
|
||||
"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 email verification code.": "請輸入六位信箱驗證碼。",
|
||||
"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,支援",
|
||||
"Enter the Coze agent ID": "輸入 Coze 代理 ID",
|
||||
@@ -2737,6 +2755,7 @@
|
||||
"Logo": "徽標",
|
||||
"Logo URL": "徽標 URL",
|
||||
"Logs": "日誌",
|
||||
"Long passwords are unavailable until the password storage upgrade is complete.": "密碼儲存升級完成前暫不支援長密碼。",
|
||||
"Look for a special ratio rule matching this user group and this billing group. If one exists, use its ratio. Otherwise use the billing group base ratio from the pricing table.": "查找匹配「該用戶分組 + 該收費分組」的特殊倍率規則。有就用規則裡的倍率,沒有就用定價分組表中收費分組的基礎倍率。",
|
||||
"Low balance": "餘額偏低",
|
||||
"Lowest median first-token latency": "最低首 token 延遲中位數",
|
||||
@@ -3035,6 +3054,7 @@
|
||||
"New API": "New API",
|
||||
"New API <noreply@example.com>": "New API <noreply@example.com>",
|
||||
"New API Project Repository:": "New API 項目倉庫:",
|
||||
"New email verification code": "新信箱驗證碼",
|
||||
"New Format Template": "新格式模板",
|
||||
"New Group": "新建分組",
|
||||
"New model": "新模型",
|
||||
@@ -3518,6 +3538,7 @@
|
||||
"Passthrough Template": "透傳模板",
|
||||
"Password": "密碼",
|
||||
"Password / Access Token": "密碼 / 存取令牌",
|
||||
"Password authentication is disabled.": "密碼驗證已停用。",
|
||||
"Password changed successfully": "密碼更改成功",
|
||||
"Password copied to clipboard: {{password}}": "密碼已複製到剪貼簿:{{password}}",
|
||||
"Password has been copied to clipboard": "密碼已複製到剪貼簿",
|
||||
@@ -3525,9 +3546,12 @@
|
||||
"Password must be at least 8 characters": "密碼必須至少 8 個字元",
|
||||
"Password must be at most 20 characters long": "密碼最多 20 個字元",
|
||||
"Password must be between 8 and 20 characters": "密碼長度必須在 8 到 20 個字元之間",
|
||||
"Password must contain between 8 and 128 characters.": "密碼長度必須為 8–128 個字元。",
|
||||
"Password Registration": "密碼註冊",
|
||||
"Password reset and copied to clipboard: {{password}}": "密碼已重置並複製到剪貼簿:{{password}}",
|
||||
"Password reset: {{password}}": "密碼已重置:{{password}}",
|
||||
"Password set successfully": "密碼設定成功",
|
||||
"Password settings have changed. Reload the page and try again.": "密碼設定已變更,請重新載入頁面後再試。",
|
||||
"Passwords do not match": "密碼不匹配",
|
||||
"Passwords don't match.": "兩次輸入的密碼不一致。",
|
||||
"Paste Connection Info": "貼上連線資訊",
|
||||
@@ -3677,6 +3701,7 @@
|
||||
"Please wait a moment before trying again.": "請稍候再試。",
|
||||
"Please wait a moment, human check is initializing...": "請稍等,人機驗證正在初始化...",
|
||||
"Please wait before editing to avoid overwriting saved values.": "請等待載入完成後再編輯,以免覆蓋已儲存的值。",
|
||||
"Please wait before requesting another verification code.": "請稍後再要求驗證碼。",
|
||||
"Please wait for the current generation to complete": "請等待目前生成完成",
|
||||
"Plugin": "外掛",
|
||||
"Plugin author": "外掛作者",
|
||||
@@ -4099,6 +4124,8 @@
|
||||
"Reroll": "重繪",
|
||||
"Research, analysis, scientific reasoning": "研究、分析與科學推理",
|
||||
"Resend ({{seconds}}s)": "重新發送 ({{seconds}}s)",
|
||||
"Resend codes": "重新傳送驗證碼",
|
||||
"Resend in {{seconds}}s": "{{seconds}} 秒後重送",
|
||||
"Reserved for viewing complete channel keys after secure verification.": "預留用於在安全驗證後查看完整渠道金鑰。",
|
||||
"Reset": "重置",
|
||||
"Reset {{count}} active subscriptions": "已重置 {{count}} 個有效訂閱",
|
||||
@@ -4461,6 +4488,7 @@
|
||||
"Set filters to customize your dashboard statistics and charts.": "設定篩選器以自訂您的儀表板統計數據和圖表。",
|
||||
"Set filters to narrow down your log search results.": "設定篩選器以縮小日誌搜尋結果範圍。",
|
||||
"Set Header": "設請求頭",
|
||||
"Set Password": "設定密碼",
|
||||
"Set Project to io.cloud when creating/selecting key": "建立/選擇金鑰時將項目設定為 io.cloud",
|
||||
"Set quota amount and limits": "設定令牌可用額度和數量",
|
||||
"Set Request Header": "設定請求頭",
|
||||
@@ -4591,6 +4619,7 @@
|
||||
"Start ≤ end: within the day; start > end: across midnight": "開始 ≤ 結束為當日區間,開始 > 結束為跨午夜區間",
|
||||
"Start a conversation to see messages here": "開始對話以在此處查看訊息",
|
||||
"Start a playground chat": "開始一場遊樂場對話",
|
||||
"Start again": "重新開始",
|
||||
"Start collecting payments globally without registering a company. Built for indie developers, OPC sole proprietorships, and startups. Waffo Pancake acts as your Merchant of Record, taking on the compliance burden of global payment collection — consumption tax, invoicing, subscription management, refunds, and chargebacks. Solo developers can launch fast and stay focused on product instead of compliance. Onboard in minutes — one prompt to a full integration.": "無需註冊公司即可開始全球收款。面向獨立開發者、OPC 個體經營者和初創團隊構建。Waffo Pancake 作為你的登記商戶(Merchant of Record),承擔全球收款相關的合規負擔,包括消費稅、開票、訂閱管理、退款和拒付。個人開發者可以快速上線,專注產品而不是合規事務。幾分鐘即可完成入駐,從一個提示詞到完整整合。",
|
||||
"Start for free with generous limits. No credit card required.": "免費開始使用,額度充足,無需連結信用卡。",
|
||||
"Start Time": "起始時間",
|
||||
@@ -4828,6 +4857,7 @@
|
||||
"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 目錄時才需要連結不同店鋪。",
|
||||
"The change succeeded, but the notification email could not be sent.": "變更已完成,但通知郵件傳送失敗。",
|
||||
"The deployment node that handled the requests": "處理請求的部署節點",
|
||||
"The downloaded source does not match the sha256 declared in the index. Do not install it.": "下載到的原始碼與索引宣告的 sha256 不一致,請勿安裝。",
|
||||
"The effective domain for Passkey registration. Must match the current domain or be its parent domain.": "用於 Passkey 註冊的有效域。必須與目前域匹配或為其父域。",
|
||||
@@ -4902,8 +4932,11 @@
|
||||
"This data may be unreliable, use with caution": "此數據可能不可靠,請謹慎使用",
|
||||
"This device does not support Passkey": "此設備不支援 Passkey",
|
||||
"This device does not support Passkey verification.": "此設備不支援 Passkey 驗證。",
|
||||
"This email address is already in use.": "此信箱地址已被使用。",
|
||||
"This email address is not allowed by the administrator's email policy.": "此信箱地址不符合管理員設定的信箱規則。",
|
||||
"This expression does not price each combination exactly once, so it opens as a raw expression. Sparse or custom pricing stays in this editor.": "此運算式未對每種組合恰好定價一次,因此將以原始運算式模式開啟。稀疏或自訂定價會保留在此編輯器中。",
|
||||
"This expression is too complex for the visual editor. Please switch to expression mode to edit.": "此表達式對可視化編輯器過於複雜,請切換到表達式模式進行編輯。",
|
||||
"This external account is already bound.": "此第三方帳戶已被綁定。",
|
||||
"This FAQ entry will be removed from the list.": "此 FAQ 條目將從列表中移除。",
|
||||
"This feature is experimental. Configuration format and behavior may change.": "此功能為實驗性功能。設定格式和行為可能會發生變化。",
|
||||
"This field does not support wildcards or regular expressions.": "這裡不支援萬用字元或正則表達式。",
|
||||
@@ -5057,6 +5090,7 @@
|
||||
"Tokens-only mode will show raw quota values regardless of this toggle.": "Tokens-only 模式將無視此開關顯示原始配額值。",
|
||||
"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.": "有效登入工作階段數量已達上限。請在一台已登入的裝置上開啟「登入工作階段」,使用「登出其他工作階段」將其撤銷。如果無法存取任何已登入裝置,請重設密碼以登出所有工作階段。",
|
||||
"Too many files. Some were not added.": "檔案過多。部分未添加。",
|
||||
"Too many incorrect codes. Start email verification again.": "驗證碼錯誤次數過多,請重新開始信箱驗證。",
|
||||
"Too many login sessions were created recently. Please wait for the rolling window to pass, then try again.": "近期建立的登入工作階段過多。請等待滾動時間窗口結束後再試。",
|
||||
"Too many requests": "請求過於頻繁",
|
||||
"Tool / function declarations the model may call": "模型可呼叫的工具 / 函數聲明",
|
||||
@@ -5200,6 +5234,7 @@
|
||||
"Unsaved changes": "未儲存的變更",
|
||||
"Unset price": "未設定價格",
|
||||
"Unset price models": "未設定價格模型",
|
||||
"Unsupported account password hashing configuration.": "帳戶密碼雜湊設定不受支援。",
|
||||
"Unsupported verification method: {{method}}": "不支援的驗證方式:{{method}}",
|
||||
"Until": "至",
|
||||
"Untitled": "未命名",
|
||||
@@ -5323,6 +5358,7 @@
|
||||
"USD price per 1M input tokens.": "每 100 萬輸入 token 的美元價格。",
|
||||
"USD price per 1M tokens.": "每 100 萬 token 的美元價格。",
|
||||
"Use +: to add a group, -: to remove a default selectable group, or no prefix to append a group.": "使用 +: 新增分組,使用 -: 移除預設可選分組,不加前綴則追加分組。",
|
||||
"Use 8–128 characters.": "使用 8–128 個字元。",
|
||||
"Use a compatible browser or device with biometric authentication or a security key to register a Passkey.": "請使用支援生物識別認證或安全金鑰的兼容瀏覽器或設備來註冊通行金鑰。",
|
||||
"Use a different stable value for each instance, then restart the service.": "每個實例使用不同且穩定的值,然後重啟服務。",
|
||||
"Use a path to append it to the channel Base URL, or enter a full URL to override the Base URL for this route.": "填寫以 / 開頭的路徑時會自動拼接渠道 Base URL;填寫完整 URL 時,此路由會直接使用該 URL。",
|
||||
@@ -5435,6 +5471,7 @@
|
||||
"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 could not be sent. Start email verification again.": "驗證郵件傳送失敗,請重新開始信箱驗證。",
|
||||
"Verification email sent": "驗證郵件已發送",
|
||||
"Verification failed": "驗證失敗",
|
||||
"Verification failed. Please try again.": "驗證失敗,請重試。",
|
||||
@@ -5644,6 +5681,7 @@
|
||||
"Your Discord OAuth Client Secret": "您的 Discord OAuth 用戶端密鑰",
|
||||
"Your GitHub OAuth Client ID": "您的 GitHub OAuth 用戶端 ID",
|
||||
"Your GitHub OAuth Client Secret": "您的 GitHub OAuth 用戶端密鑰",
|
||||
"Your identity has been verified. Continue to the provider to finish linking your account.": "身分驗證已通過,請前往服務提供商完成帳戶綁定。",
|
||||
"Your new backup codes are ready": "您的新備份代碼已準備就緒",
|
||||
"Your Referral Link": "您的推薦連結",
|
||||
"Your setup guide is collapsed so usage stays in focus.": "設定引導已收起,讓用量資訊保持在焦點位置。",
|
||||
|
||||
@@ -145,13 +145,18 @@
|
||||
"Access tokens are shown only once": "访问令牌仅显示一次",
|
||||
"AccessKey / SecretAccessKey": "AccessKey / SecretAccessKey",
|
||||
"Account Actions": "账户操作",
|
||||
"Account binding": "账户绑定",
|
||||
"Account Binding Management": "账户绑定管理",
|
||||
"Account binding request": "账户绑定请求",
|
||||
"Account Bindings": "账户绑定",
|
||||
"Account bindings have changed. Start this operation again.": "账户绑定已变化,请重新操作。",
|
||||
"Account created! Please sign in": "账户已创建!请登录",
|
||||
"Account deleted successfully": "账户删除成功",
|
||||
"Account ID *": "账户 ID *",
|
||||
"Account Info": "账户信息",
|
||||
"Account password change": "账户密码变更",
|
||||
"Account security": "账户安全",
|
||||
"Account unlinking": "账户解绑",
|
||||
"Account used when authenticating with the SMTP server": "用于与 SMTP 服务器进行身份验证的账户",
|
||||
"acknowledge the related legal risks": "确认相关法律风险",
|
||||
"Across all groups": "跨所有分组",
|
||||
@@ -187,6 +192,7 @@
|
||||
"Add an index URL to browse installable plugins.": "添加一个索引 URL 即可浏览可安装的插件。",
|
||||
"Add and submit": "添加后提交",
|
||||
"Add Announcement": "添加公告",
|
||||
"Add another login method before unlinking this account.": "请先添加其他登录方式,再解除此账户绑定。",
|
||||
"Add API": "添加 API",
|
||||
"Add API Shortcut": "添加 API 快捷方式",
|
||||
"Add auto group": "添加自动分组",
|
||||
@@ -689,6 +695,7 @@
|
||||
"Bind Email": "绑定邮箱",
|
||||
"Bind task plugins": "绑定任务插件",
|
||||
"Bind Telegram Account": "绑定 Telegram 账户",
|
||||
"Bind WeChat": "绑定微信",
|
||||
"Bind WeChat Account": "绑定微信账户",
|
||||
"Binding Information": "绑定信息",
|
||||
"Binding successful!": "绑定成功!",
|
||||
@@ -1071,6 +1078,7 @@
|
||||
"Confirm and enable": "确认并启用",
|
||||
"Confirm Batch Update": "确认批量更新",
|
||||
"Confirm Billing Conflicts": "确认账单冲突",
|
||||
"Confirm both your current and new email addresses to finish this change.": "请确认当前邮箱和新邮箱,完成此次变更。",
|
||||
"Confirm Changes": "确认更改",
|
||||
"Confirm Cleanup": "确认清理",
|
||||
"Confirm cleanup of inactive disk cache?": "确认清理不活跃的磁盘缓存?",
|
||||
@@ -1081,6 +1089,7 @@
|
||||
"Confirm Creem Purchase": "确认 Creem 购买",
|
||||
"Confirm delete": "确认删除",
|
||||
"Confirm disable": "确认禁用",
|
||||
"Confirm email": "确认邮箱",
|
||||
"Confirm enable": "确认启用",
|
||||
"Confirm invalidate": "确认作废",
|
||||
"Confirm log cleanup": "确认日志清理",
|
||||
@@ -1091,6 +1100,7 @@
|
||||
"Confirm Selection": "确认选择",
|
||||
"Confirm settings and finish setup": "确认设置并完成安装",
|
||||
"confirm that I bear legal responsibility arising from deployment": "确认承担因部署",
|
||||
"Confirm the verification code sent to your new email address.": "请输入发送到新邮箱的验证码。",
|
||||
"Confirm Unbind": "确认解绑",
|
||||
"Confirm usage reset": "确认重置用量",
|
||||
"Confirm your identity before accessing this sensitive action.": "执行此敏感操作前,请先验证身份。",
|
||||
@@ -1127,6 +1137,7 @@
|
||||
"Content width": "内容宽度",
|
||||
"Context": "上下文",
|
||||
"Continue": "继续",
|
||||
"Continue account binding": "继续绑定账户",
|
||||
"Continue with {{name}}": "使用 {{name}} 继续",
|
||||
"Continue with an account already linked to your profile.": "使用已绑定的账号继续验证。",
|
||||
"Continue with Discord": "使用 Discord 继续",
|
||||
@@ -1280,12 +1291,14 @@
|
||||
"Current Billing": "当前计费",
|
||||
"Current Cache Size": "当前缓存大小",
|
||||
"Current domain": "当前域名",
|
||||
"Current email verification code": "当前邮箱验证码",
|
||||
"Current email: {{email}}. Enter a new email to change.": "当前邮箱:{{email}}。输入新邮箱以更改。",
|
||||
"Current key": "当前密钥",
|
||||
"Current legacy JSON is invalid, cannot append": "当前旧格式 JSON 不合法,无法追加模板",
|
||||
"Current Level Only": "仅当前层",
|
||||
"Current models for the longest channel in this tag. May not include all models from all channels.": "此标签中最长渠道的当前模型。可能不包括所有渠道的所有模型。",
|
||||
"Current Password": "当前密码",
|
||||
"Current password is incorrect.": "当前密码不正确。",
|
||||
"Current Price": "当前价格",
|
||||
"Current quota": "当前额度",
|
||||
"Current token": "当前令牌",
|
||||
@@ -1668,10 +1681,13 @@
|
||||
"Email Address": "电子邮件地址",
|
||||
"Email Alias Restriction": "电子邮件别名限制",
|
||||
"Email bound successfully!": "邮箱绑定成功!",
|
||||
"Email confirmation code resend": "重发邮箱确认码",
|
||||
"Email Domain Restriction": "电子邮件域限制",
|
||||
"Email Domain Whitelist": "电子邮件域白名单",
|
||||
"Email Field": "邮箱字段",
|
||||
"Email Verification": "电子邮件验证",
|
||||
"Email verification code is incorrect.": "邮箱验证码不正确。",
|
||||
"Email verification has ended. Start again to continue.": "邮箱验证已结束,请重新开始。",
|
||||
"Email, summarisation, knowledge work": "邮件、摘要与知识工作",
|
||||
"Embeddings": "嵌入",
|
||||
"Empty": "空",
|
||||
@@ -1795,6 +1811,7 @@
|
||||
"Enter only a top-level callback domain, for example https://api.example.com, without any path.": "只填写回调顶级域名,例如 https://api.example.com,不要带任何路径。",
|
||||
"Enter password": "输入密码",
|
||||
"Enter password (8-20 characters)": "输入密码(8-20 个字符)",
|
||||
"Enter password (8–128 characters)": "输入密码(8–128 个字符)",
|
||||
"Enter quota in {{currency}}": "输入 {{currency}} 额度",
|
||||
"Enter quota in tokens": "输入令牌配额",
|
||||
"Enter secret key": "输入密钥",
|
||||
@@ -1802,6 +1819,7 @@
|
||||
"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 email verification code.": "请输入六位邮箱验证码。",
|
||||
"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,支持",
|
||||
"Enter the Coze agent ID": "输入 Coze 代理 ID",
|
||||
@@ -2737,6 +2755,7 @@
|
||||
"Logo": "徽标",
|
||||
"Logo URL": "徽标 URL",
|
||||
"Logs": "日志",
|
||||
"Long passwords are unavailable until the password storage upgrade is complete.": "密码存储升级完成前暂不支持长密码。",
|
||||
"Look for a special ratio rule matching this user group and this billing group. If one exists, use its ratio. Otherwise use the billing group base ratio from the pricing table.": "查找匹配「该用户分组 + 该计费分组」的特殊倍率规则。有就用规则里的倍率,没有就用定价分组表中计费分组的基础倍率。",
|
||||
"Low balance": "余额偏低",
|
||||
"Lowest median first-token latency": "最低首 token 延迟中位数",
|
||||
@@ -3035,6 +3054,7 @@
|
||||
"New API": "New API",
|
||||
"New API <noreply@example.com>": "New API <noreply@example.com>",
|
||||
"New API Project Repository:": "New API 项目仓库:",
|
||||
"New email verification code": "新邮箱验证码",
|
||||
"New Format Template": "新格式模板",
|
||||
"New Group": "新建分组",
|
||||
"New model": "新模型",
|
||||
@@ -3518,6 +3538,7 @@
|
||||
"Passthrough Template": "透传模板",
|
||||
"Password": "密码",
|
||||
"Password / Access Token": "密码 / 访问令牌",
|
||||
"Password authentication is disabled.": "密码认证已禁用。",
|
||||
"Password changed successfully": "密码更改成功",
|
||||
"Password copied to clipboard: {{password}}": "密码已复制到剪贴板:{{password}}",
|
||||
"Password has been copied to clipboard": "密码已复制到剪贴板",
|
||||
@@ -3525,9 +3546,12 @@
|
||||
"Password must be at least 8 characters": "密码必须至少 8 个字符",
|
||||
"Password must be at most 20 characters long": "密码最多 20 个字符",
|
||||
"Password must be between 8 and 20 characters": "密码长度必须在 8 到 20 个字符之间",
|
||||
"Password must contain between 8 and 128 characters.": "密码长度必须为 8–128 个字符。",
|
||||
"Password Registration": "密码注册",
|
||||
"Password reset and copied to clipboard: {{password}}": "密码已重置并复制到剪贴板:{{password}}",
|
||||
"Password reset: {{password}}": "密码已重置:{{password}}",
|
||||
"Password set successfully": "密码设置成功",
|
||||
"Password settings have changed. Reload the page and try again.": "密码设置已变化,请刷新页面后重试。",
|
||||
"Passwords do not match": "密码不匹配",
|
||||
"Passwords don't match.": "两次输入的密码不一致。",
|
||||
"Paste Connection Info": "粘贴连接信息",
|
||||
@@ -3677,6 +3701,7 @@
|
||||
"Please wait a moment before trying again.": "请稍候再试。",
|
||||
"Please wait a moment, human check is initializing...": "请稍等,人机验证正在初始化...",
|
||||
"Please wait before editing to avoid overwriting saved values.": "请等待加载完成后再编辑,以免覆盖已保存的值。",
|
||||
"Please wait before requesting another verification code.": "请稍后再请求验证码。",
|
||||
"Please wait for the current generation to complete": "请等待当前生成完成",
|
||||
"Plugin": "插件",
|
||||
"Plugin author": "插件作者",
|
||||
@@ -4099,6 +4124,8 @@
|
||||
"Reroll": "重绘",
|
||||
"Research, analysis, scientific reasoning": "研究、分析与科学推理",
|
||||
"Resend ({{seconds}}s)": "重新发送 ({{seconds}}s)",
|
||||
"Resend codes": "重新发送验证码",
|
||||
"Resend in {{seconds}}s": "{{seconds}} 秒后重发",
|
||||
"Reserved for viewing complete channel keys after secure verification.": "预留用于在安全验证后查看完整渠道密钥。",
|
||||
"Reset": "重置",
|
||||
"Reset {{count}} active subscriptions": "已重置 {{count}} 个有效订阅",
|
||||
@@ -4461,6 +4488,7 @@
|
||||
"Set filters to customize your dashboard statistics and charts.": "设置筛选器以自定义您的仪表板统计数据和图表。",
|
||||
"Set filters to narrow down your log search results.": "设置筛选器以缩小日志搜索结果范围。",
|
||||
"Set Header": "设请求头",
|
||||
"Set Password": "设置密码",
|
||||
"Set Project to io.cloud when creating/selecting key": "创建/选择密钥时将项目设置为 io.cloud",
|
||||
"Set quota amount and limits": "设置令牌可用额度和数量",
|
||||
"Set Request Header": "设置请求头",
|
||||
@@ -4591,6 +4619,7 @@
|
||||
"Start ≤ end: within the day; start > end: across midnight": "开始 ≤ 结束为当日区间,开始 > 结束为跨零点区间",
|
||||
"Start a conversation to see messages here": "开始对话以在此处查看消息",
|
||||
"Start a playground chat": "开始一场游乐场对话",
|
||||
"Start again": "重新开始",
|
||||
"Start collecting payments globally without registering a company. Built for indie developers, OPC sole proprietorships, and startups. Waffo Pancake acts as your Merchant of Record, taking on the compliance burden of global payment collection — consumption tax, invoicing, subscription management, refunds, and chargebacks. Solo developers can launch fast and stay focused on product instead of compliance. Onboard in minutes — one prompt to a full integration.": "无需注册公司即可开始全球收款。面向独立开发者、OPC 个体经营者和初创团队构建。Waffo Pancake 作为你的登记商户(Merchant of Record),承担全球收款相关的合规负担,包括消费税、开票、订阅管理、退款和拒付。个人开发者可以快速上线,专注产品而不是合规事务。几分钟即可完成入驻,从一个提示词到完整集成。",
|
||||
"Start for free with generous limits. No credit card required.": "免费开始使用,额度充足,无需绑定信用卡。",
|
||||
"Start Time": "起始时间",
|
||||
@@ -4828,6 +4857,7 @@
|
||||
"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 目录时才需要绑定不同店铺。",
|
||||
"The change succeeded, but the notification email could not be sent.": "变更已完成,但通知邮件发送失败。",
|
||||
"The deployment node that handled the requests": "处理请求的部署节点",
|
||||
"The downloaded source does not match the sha256 declared in the index. Do not install it.": "下载到的源码与索引声明的 sha256 不一致,请勿安装。",
|
||||
"The effective domain for Passkey registration. Must match the current domain or be its parent domain.": "用于 Passkey 注册的有效域。必须与当前域匹配或为其父域。",
|
||||
@@ -4902,8 +4932,11 @@
|
||||
"This data may be unreliable, use with caution": "此数据可能不可靠,请谨慎使用",
|
||||
"This device does not support Passkey": "此设备不支持 Passkey",
|
||||
"This device does not support Passkey verification.": "此设备不支持 Passkey 验证。",
|
||||
"This email address is already in use.": "此邮箱地址已被使用。",
|
||||
"This email address is not allowed by the administrator's email policy.": "此邮箱地址不符合管理员设置的邮箱规则。",
|
||||
"This expression does not price each combination exactly once, so it opens as a raw expression. Sparse or custom pricing stays in this editor.": "此表达式未对每种组合恰好定价一次,因此将以原始表达式模式打开。稀疏或自定义定价会保留在此编辑器中。",
|
||||
"This expression is too complex for the visual editor. Please switch to expression mode to edit.": "此表达式对可视化编辑器过于复杂,请切换到表达式模式进行编辑。",
|
||||
"This external account is already bound.": "此第三方账户已被绑定。",
|
||||
"This FAQ entry will be removed from the list.": "此 FAQ 条目将从列表中移除。",
|
||||
"This feature is experimental. Configuration format and behavior may change.": "此功能为实验性功能。配置格式和行为可能会发生变化。",
|
||||
"This field does not support wildcards or regular expressions.": "这里不支持通配符或正则表达式。",
|
||||
@@ -5057,6 +5090,7 @@
|
||||
"Tokens-only mode will show raw quota values regardless of this toggle.": "Tokens-only 模式将无视此开关显示原始配额值。",
|
||||
"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.": "活跃登录会话数量已达上限。请在一台已登录的设备上打开“登录会话”,使用“退出其他登录会话”将其撤销。如果无法访问任何已登录设备,请重置密码以退出所有会话。",
|
||||
"Too many files. Some were not added.": "文件过多。部分未添加。",
|
||||
"Too many incorrect codes. Start email verification again.": "验证码错误次数过多,请重新开始邮箱验证。",
|
||||
"Too many login sessions were created recently. Please wait for the rolling window to pass, then try again.": "近期创建的登录会话过多。请等待滚动时间窗口结束后再试。",
|
||||
"Too many requests": "请求过于频繁",
|
||||
"Tool / function declarations the model may call": "模型可调用的工具 / 函数声明",
|
||||
@@ -5200,6 +5234,7 @@
|
||||
"Unsaved changes": "未保存的更改",
|
||||
"Unset price": "未设置价格",
|
||||
"Unset price models": "未设置价格模型",
|
||||
"Unsupported account password hashing configuration.": "账户密码哈希配置不受支持。",
|
||||
"Unsupported verification method: {{method}}": "不支持的验证方式:{{method}}",
|
||||
"Until": "至",
|
||||
"Untitled": "未命名",
|
||||
@@ -5323,6 +5358,7 @@
|
||||
"USD price per 1M input tokens.": "每 100 万输入 token 的美元价格。",
|
||||
"USD price per 1M tokens.": "每 100 万 token 的美元价格。",
|
||||
"Use +: to add a group, -: to remove a default selectable group, or no prefix to append a group.": "使用 +: 添加分组,使用 -: 移除默认可选分组,不加前缀则追加分组。",
|
||||
"Use 8–128 characters.": "使用 8–128 个字符。",
|
||||
"Use a compatible browser or device with biometric authentication or a security key to register a Passkey.": "请使用支持生物识别认证或安全密钥的兼容浏览器或设备来注册通行密钥。",
|
||||
"Use a different stable value for each instance, then restart the service.": "每个实例使用不同且稳定的值,然后重启服务。",
|
||||
"Use a path to append it to the channel Base URL, or enter a full URL to override the Base URL for this route.": "填写以 / 开头的路径时会自动拼接渠道 Base URL;填写完整 URL 时,此路由会直接使用该 URL。",
|
||||
@@ -5435,6 +5471,7 @@
|
||||
"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 could not be sent. Start email verification again.": "验证邮件发送失败,请重新开始邮箱验证。",
|
||||
"Verification email sent": "验证邮件已发送",
|
||||
"Verification failed": "验证失败",
|
||||
"Verification failed. Please try again.": "验证失败,请重试。",
|
||||
@@ -5644,6 +5681,7 @@
|
||||
"Your Discord OAuth Client Secret": "您的 Discord OAuth 客户端密钥",
|
||||
"Your GitHub OAuth Client ID": "您的 GitHub OAuth 客户端 ID",
|
||||
"Your GitHub OAuth Client Secret": "您的 GitHub OAuth 客户端密钥",
|
||||
"Your identity has been verified. Continue to the provider to finish linking your account.": "身份验证已通过,请前往服务提供商完成账户绑定。",
|
||||
"Your new backup codes are ready": "您的新备份代码已准备就绪",
|
||||
"Your Referral Link": "您的推荐链接",
|
||||
"Your setup guide is collapsed so usage stays in focus.": "设置引导已收起,让用量信息保持在焦点位置。",
|
||||
|
||||
@@ -588,4 +588,43 @@ export const STATIC_I18N_KEYS = [
|
||||
"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.',
|
||||
// Account binding and password-operation messages.
|
||||
'Account bindings have changed. Start this operation again.',
|
||||
'Add another login method before unlinking this account.',
|
||||
'Bind WeChat',
|
||||
'Continue account binding',
|
||||
'Current email verification code',
|
||||
'Current password is incorrect.',
|
||||
'Email verification code is incorrect.',
|
||||
'Email verification has ended. Start again to continue.',
|
||||
'Enter password (8–128 characters)',
|
||||
'Long passwords are unavailable until the password storage upgrade is complete.',
|
||||
'New email verification code',
|
||||
'Password must contain between 8 and 128 characters.',
|
||||
'Password settings have changed. Reload the page and try again.',
|
||||
'Please wait before requesting another verification code.',
|
||||
'Resend codes',
|
||||
'Resend in {{seconds}}s',
|
||||
'Start again',
|
||||
'The change succeeded, but the notification email could not be sent.',
|
||||
"This email address is not allowed by the administrator's email policy.",
|
||||
'Too many incorrect codes. Start email verification again.',
|
||||
'Unsupported account password hashing configuration.',
|
||||
'Use 8–128 characters.',
|
||||
'Verification email could not be sent. Start email verification again.',
|
||||
'Your identity has been verified. Continue to the provider to finish linking your account.',
|
||||
'Set Password',
|
||||
'Password set successfully',
|
||||
'Confirm email',
|
||||
'Confirm both your current and new email addresses to finish this change.',
|
||||
'Confirm the verification code sent to your new email address.',
|
||||
'Enter the 6-digit email verification code.',
|
||||
'Password authentication is disabled.',
|
||||
'This external account is already bound.',
|
||||
'This email address is already in use.',
|
||||
'Account password change',
|
||||
'Account binding request',
|
||||
'Account binding',
|
||||
'Account unlinking',
|
||||
'Email confirmation code resend',
|
||||
] as const
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { z } from 'zod'
|
||||
|
||||
// Match the backend's Unicode character count without modifying the password.
|
||||
export const accountPasswordSchema = z.string().refine((password) => {
|
||||
const length = [...password].length
|
||||
return length >= 8 && length <= 128
|
||||
}, 'Password must contain between 8 and 128 characters.')
|
||||
@@ -27,6 +27,7 @@ export type UserPermissions = {
|
||||
}
|
||||
|
||||
export interface AuthUser {
|
||||
has_password?: boolean
|
||||
id: number
|
||||
username: string
|
||||
display_name?: string
|
||||
|
||||
Reference in new issue
Block a user