Skip to content

feat: passkey - #1912

Merged
seefs001 merged 5 commits into
QuantumNous:mainfrom
seefs001:feature/passkey
Sep 30, 2025
Merged

seefs001 merged 5 commits into
QuantumNous:mainfrom
seefs001:feature/passkey

Conversation

@seefs001

@seefs001 seefs001 commented Sep 29, 2025 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Full Passkey (WebAuthn) support: register, login, verify, remove, admin reset; UI in login, personal & system settings, status, last-used and backup info, plus translations.
    • Universal secure verification: generic verify endpoints and client flow (2FA or Passkey) for protected actions (e.g., viewing channel keys), plus browser helpers.
    • User management: reset user Passkey and reset user 2FA actions.
  • Refactor

    • Replaced 2FA-only flows with a unified Secure Verification modal, hook and service.
  • Chores

    • Updated runtime/dependencies and DB migrations to support Passkey credentials.

@coderabbitai

coderabbitai Bot commented Sep 29, 2025 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

Walkthrough

Adds end-to-end Passkey (WebAuthn) support plus a generic secure verification system. Changes span backend controllers, models, services, middleware, migrations, go.mod updates, and frontend helpers, hooks, components, and translations; routes updated to require/handle secure verification.

Changes

Cohort / File(s) Summary
Controllers (Passkey, Secure Verification, Channel, Misc)
controller/passkey.go, controller/secure_verification.go, controller/channel.go, controller/misc.go
New Passkey endpoints (register/login/verify/finish/delete/status/admin-reset); universal secure verification APIs and helpers; GetChannelKey removed in-handler 2FA and now requires SecureVerificationRequired; GetStatus includes passkey settings.
Middleware
middleware/secure_verification.go
New middlewares SecureVerificationRequired, OptionalSecureVerification, and ClearSecureVerification plus session key/timeout constants and verification checks.
Routing
router/api-router.go
Adds passkey and verification routes (user/self/admin scopes) and applies SecureVerificationRequired to channel key route.
Models & Migrations
model/passkey.go, model/main.go
New PasskeyCredential model (webauthn integration, transports, CRUD helpers) and added to DB migrations.
Passkey Backend Service & Session
service/passkey/service.go, service/passkey/session.go, service/passkey/user.go
WebAuthn builder (origins/RPID resolution), session save/pop helpers, and WebAuthnUser adapter.
Settings
setting/system_setting/passkey.go
New PasskeySettings struct, default registration and getter GetPasskeySettings().
Go Modules
go.mod
Bumps Go/toolchain and adds/upgrades WebAuthn and related dependencies.
Frontend Helpers (Passkey)
web/src/helpers/passkey.js, web/src/helpers/index.js
New WebAuthn utilities (base64/url buffers, prepare/build options/results, feature detect); re-exported in helpers index.
Secure Verification Client & Service
web/src/services/secureVerification.js, web/src/hooks/common/useSecureVerification.jsx, web/src/helpers/secureApiCall.js
New SecureVerificationService (checkAvailable/verify dispatcher), createApiCalls factory, secure API error helpers, and useSecureVerification hook driving modal verification flows.
Frontend Auth & Verification UI
web/src/components/auth/LoginForm.jsx, web/src/components/common/modals/SecureVerificationModal.jsx, web/src/components/common/examples/ChannelKeyViewExample.jsx
Passkey login UI and buttons; new SecureVerificationModal supporting 2FA and Passkey; example component for verified channel key viewing.
User Settings & Account UI
web/src/components/settings/PersonalSetting.jsx, web/src/components/settings/personal/cards/AccountManagement.jsx, web/src/components/settings/SystemSetting.jsx
Personal flows for Passkey registration/removal/status; AccountManagement shows passkey status/actions; SystemSetting adds Passkey configuration UI and save logic.
Channels Edit & Key Display
web/src/components/table/channels/modals/EditChannelModal.jsx
Replaced 2FA-only flow with generic SecureVerification flow using useSecureVerification; centralized key display and verification orchestration.
Users Table / Admin Modals & Hooks
web/src/components/table/users/UsersTable.jsx, web/src/components/table/users/UsersColumnDefs.jsx, web/src/components/table/users/modals/ResetPasskeyModal.jsx, web/src/components/table/users/modals/ResetTwoFAModal.jsx, web/src/hooks/users/useUsersData.jsx
Admin actions/UI to reset user Passkey and 2FA: added modals, handlers, hook actions, and column operations.
Helpers & Utilities
web/src/helpers/index.js, web/src/helpers/passkey.js, web/src/helpers/secureApiCall.js
Expose passkey helpers; secure API call helpers to detect/extract verification-required errors.
I18n / Localization
web/src/i18n/locales/en.json, web/src/i18n/locales/zh.json
Large set of Passkey/WebAuthn and verification-related translations added for English and Chinese.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant FE as Frontend
  participant API as Backend
  participant WAuthn as Browser WebAuthn
  participant DB as Database

  rect rgb(238,246,255)
  note right of User: Passkey Registration (high level)
  User->>FE: Click "Register Passkey"
  FE->>API: POST /api/user/passkey/register/begin
  API-->>FE: CredentialCreationOptions + session stored
  FE->>WAuthn: navigator.credentials.create(options)
  WAuthn-->>FE: credential
  FE->>API: POST /api/user/passkey/register/finish (credential + session)
  API->>DB: Upsert PasskeyCredential
  API-->>FE: success
  end
Loading
sequenceDiagram
  autonumber
  actor User
  participant FE as Frontend
  participant API as Backend
  participant WAuthn as Browser WebAuthn
  participant DB as Database

  rect rgb(239,252,244)
  note right of User: Secure Verification -> View Channel Key
  User->>FE: Request "View Channel Key"
  FE->>FE: checkAvailableVerificationMethods()
  alt chosen 2FA
    FE->>API: POST /api/.../channel/:id/key { method: "2fa", code }
  else chosen Passkey
    FE->>API: POST /api/user/passkey/verify/begin
    API-->>FE: assertion options + session stored
    FE->>WAuthn: navigator.credentials.get(options)
    WAuthn-->>FE: assertion
    FE->>API: POST /api/user/passkey/verify/finish (assertion + session)
    API-->>FE: verification OK
    FE->>API: POST /api/.../channel/:id/key { method: "passkey" }
  end
  API->>DB: Fetch channel key
  API-->>FE: channel key
  FE-->>User: display key
  end
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

Poem

A rabbit nudges keys at dawn,
New passkeys bloom where old locks yawn.
Two gentle hops — verify, bind,
Secrets shown, safe and kind.
🐇🔐 Hooray for hops that guard the mind.

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title Check ❓ Inconclusive The title “feat: passkey” is related to the primary addition of passkey functionality but is overly terse and does not clearly convey the scope or intent of the changeset, which includes comprehensive WebAuthn integration, API, middleware, model, and UI updates. It therefore provides insufficient context for team members reviewing the repository history. Please revise the title to be more descriptive of the main change, for example “Add WebAuthn passkey authentication support” to clearly communicate the feature being introduced.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4c13666 and 013a575.

📒 Files selected for processing (4)
  • model/passkey.go (1 hunks)
  • web/src/components/settings/personal/cards/AccountManagement.jsx (3 hunks)
  • web/src/i18n/locales/en.json (3 hunks)
  • web/src/i18n/locales/zh.json (2 hunks)

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🧪 Early access (Sonnet 4.5): enabled

We are currently testing the Sonnet 4.5 model, which is expected to improve code review quality. However, this model may lead to increased noise levels in the review comments. Please disable the early access features if the noise level causes any inconvenience.

Note:

  • Public repositories are always opted into early access features.
  • You can enable or disable early access features from the CodeRabbit UI or by updating the CodeRabbit configuration file.

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 13

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
controller/channel.go (1)

387-461: Critical: Passkey path trusts the client without server-side verification

In both the explicit "passkey" branch and the default flow, a caller can set method="passkey" (or leave it blank) and obtain the channel key as long as a passkey is bound. There’s no server validation of a recent, action-scoped WebAuthn assertion or a short‑lived verification token/session. This allows trivial bypass of secure verification.

Require a short‑lived, server‑issued verification token (set only after a successful Passkey assertion on the server) and validate it here before returning the key.

Apply a minimal example refactor:

 func GetChannelKey(c *gin.Context) {
   type GetChannelKeyRequest struct {
-    Code   string `json:"code,omitempty"`   // 2FA验证码或备用码
-    Method string `json:"method,omitempty"` // 验证方式: "2fa" 或 "passkey"
+    Code         string `json:"code,omitempty"`           // 2FA验证码或备用码
+    Method       string `json:"method,omitempty"`         // 验证方式: "2fa" 或 "passkey"
+    VerifyToken  string `json:"verify_token,omitempty"`   // 短期验证令牌(Passkey 验证完成后由服务端签发)
   }
@@
   switch req.Method {
   case "2fa":
@@
   case "passkey":
     if !hasPasskey {
       common.ApiError(c, fmt.Errorf("用户未启用Passkey"))
       return
     }
-    // Passkey验证已在前端完成,这里只需要检查是否有有效的Passkey验证会话
-    // 由于Passkey验证是基于WebAuthn协议的,验证过程已经在PasskeyVerifyFinish中完成
-    // 这里我们可以设置一个临时标记来验证Passkey验证是否成功
+    token := strings.TrimSpace(req.VerifyToken)
+    if token == "" {
+      token = strings.TrimSpace(c.GetHeader("X-Secure-Verify"))
+    }
+    if token == "" {
+      common.ApiError(c, fmt.Errorf("缺少Passkey验证令牌"))
+      return
+    }
+    ok, err := service.VerifySecureVerification(c, userId, "passkey", token) // must be server-side, short-lived, action-scoped
+    if err != nil || !ok {
+      common.ApiError(c, fmt.Errorf("Passkey验证无效或已过期"))
+      return
+    }
   default:
     // 自动选择验证方式:如果提供了code则使用2FA,否则需要用户明确指定
🧹 Nitpick comments (43)
go.mod (1)

25-25: WebAuthn dependencies properly added.

The WebAuthn library and its transitive dependencies are correctly added. The version updates for golang.org/x packages (crypto, net, sync, sys, text) are substantial jumps that should improve security and compatibility.

Consider pinning the WebAuthn library to a specific patch version (e.g., v0.14.0) if you haven't already tested with the latest patch releases, to ensure build reproducibility.

Also applies to: 41-44, 64-64, 72-76, 101-101, 105-106

web/src/components/settings/SystemSetting.jsx (2)

613-650: Consider adding error handling for submitPasskeySettings.

The function correctly handles changed values and always includes origins, but could benefit from explicit error handling.

Consider wrapping the updateOptions call in a try-catch block for better error handling:

 const submitPasskeySettings = async () => {
   const options = [];
 
   // ... existing option building code ...
 
   if (options.length > 0) {
+    try {
       await updateOptions(options);
+    } catch (error) {
+      showError(t('Failed to save Passkey settings'));
+      console.error('Passkey settings update failed:', error);
+    }
   }
 };

1027-1145: Comprehensive Passkey configuration UI.

The UI section provides all necessary configuration options for WebAuthn/Passkey with clear labels and helpful descriptions. The form fields are well-organized and include appropriate validation hints.

Consider adding validation for the Origins field to ensure URLs are properly formatted:

 <TagInput
   value={passkeyOrigins}
   onChange={(value) => {
+    // Validate that each origin is a valid URL
+    const validOrigins = value.filter(origin => {
+      try {
+        new URL(origin);
+        return true;
+      } catch {
+        showError(t('Invalid URL format: ') + origin);
+        return false;
+      }
+    });
-    setPasskeyOrigins(value);
+    setPasskeyOrigins(validOrigins);
     setInputs(prev => ({
       ...prev,
-      'passkey.origins': value
+      'passkey.origins': validOrigins
     }));
   }}
   placeholder={t('输入 Origin 后回车,如:https://example.com')}
   style={{ width: '100%' }}
 />
model/passkey.go (5)

172-189: Avoid hard delete upsert; use DB-native upsert for auditability and atomicity

The delete-then-create pattern (Unscoped) drops audit history and can race under concurrency. Prefer ON CONFLICT/ON DUPLICATE KEY via GORM clauses.

-func UpsertPasskeyCredential(credential *PasskeyCredential) error {
-  if credential == nil {
-    common.SysLog("UpsertPasskeyCredential: nil credential provided")
-    return fmt.Errorf("Passkey 保存失败,请重试")
-  }
-  return DB.Transaction(func(tx *gorm.DB) error {
-    // 使用Unscoped()进行硬删除,避免唯一索引冲突
-    if err := tx.Unscoped().Where("user_id = ?", credential.UserID).Delete(&PasskeyCredential{}).Error; err != nil {
-      common.SysLog(fmt.Sprintf("UpsertPasskeyCredential: failed to delete existing credential for user %d: %v", credential.UserID, err))
-      return fmt.Errorf("Passkey 保存失败,请重试")
-    }
-    if err := tx.Create(credential).Error; err != nil {
-      common.SysLog(fmt.Sprintf("UpsertPasskeyCredential: failed to create credential for user %d: %v", credential.UserID, err))
-      return fmt.Errorf("Passkey 保存失败,请重试")
-    }
-    return nil
-  })
-}
+func UpsertPasskeyCredential(credential *PasskeyCredential) error {
+  if credential == nil {
+    common.SysLog("UpsertPasskeyCredential: nil credential provided")
+    return fmt.Errorf("Passkey 保存失败,请重试")
+  }
+  // Upsert by user_id
+  return DB.
+    Clauses(clause.OnConflict{
+      Columns:   []clause.Column{{Name: "user_id"}},
+      DoUpdates: clause.AssignmentColumns([]string{
+        "credential_id", "public_key", "attestation_type", "aaguid",
+        "sign_count", "clone_warning", "user_present", "user_verified",
+        "backup_eligible", "backup_state", "transports", "attachment", "updated_at",
+      }),
+    }).
+    Create(credential).Error
+}

Also add:

// imports
"gorm.io/gorm/clause"

42-55: Don’t swallow JSON decode errors for transports

Returning nil hides corrupted data. Log once to aid ops.

- if err := json.Unmarshal([]byte(p.Transports), &transports); err != nil {
-   return nil
- }
+ if err := json.Unmarshal([]byte(p.Transports), &transports); err != nil {
+   common.SysLog(fmt.Sprintf("TransportList: failed to unmarshal transports: %v", err))
+   return nil
+ }

57-71: Marshal error handling and empty state for SetTransports

On marshal error we silently return and leave stale value. Log and default to "[]".

- encoded, err := json.Marshal(stringList)
- if err != nil {
-   return
- }
+ encoded, err := json.Marshal(stringList)
+ if err != nil {
+   common.SysLog(fmt.Sprintf("SetTransports: failed to marshal transports: %v", err))
+   p.Transports = "[]"
+   return
+ }

16-19: Remove unused error symbol or use it internally

ErrPasskeyNotFound is defined but never used. Remove it or use it for internal branching/logging.

 var (
-  ErrPasskeyNotFound         = errors.New("passkey credential not found")
   ErrFriendlyPasskeyNotFound = errors.New("Passkey 验证失败,请重试或联系管理员")
 )

34-36: Consider JSON type for Transports and omit empty in API responses

If this field is serialized to clients, empty string is awkward. Consider datatypes.JSON with omitempty to emit [] or nothing; otherwise, add ,omitempty to the current tag.

- Transports      string         `json:"transports" gorm:"type:text"`
+ Transports      string         `json:"transports,omitempty" gorm:"type:text"`
web/src/i18n/locales/zh.json (1)

90-90: Terminology consistency: “两步验证” vs “二步验证”

The file mixes “两步验证” (Line 85) and “二步验证” (Line 90). Unify to one term to avoid UX inconsistency.

-  "二步验证已重置": "二步验证已重置"
+  "两步验证已重置": "两步验证已重置"
web/src/components/table/users/modals/ResetPasskeyModal.jsx (1)

25-34: Add explicit destructive-action affordances (ok/cancel text, block accidental close).

Recommend: set ok/cancel labels via i18n, and prevent accidental closure for an admin-only destructive reset.

 <Modal
-  title={t('确认重置 Passkey')}
+  title={t('确认重置 Passkey')}
   visible={visible}
   onCancel={onCancel}
   onOk={onConfirm}
-  type='warning'
+  type='warning'
+  okText={t('确认重置')}
+  cancelText={t('取消')}
+  maskClosable={false}
 >
web/src/components/table/users/modals/ResetTwoFAModal.jsx (1)

25-34: Align 2FA reset modal with stronger confirmation UX.

Same suggestion as Passkey modal: explicit ok/cancel text and maskClosable=false to avoid accidental dismiss/confirm.

 <Modal
-  title={t('确认重置两步验证')}
+  title={t('确认重置两步验证')}
   visible={visible}
   onCancel={onCancel}
   onOk={onConfirm}
-  type='warning'
+  type='warning'
+  okText={t('确认重置')}
+  cancelText={t('取消')}
+  maskClosable={false}
 >
router/api-router.go (3)

48-49: Avoid caching of WebAuthn “begin” responses.

Passkey challenges/options must not be cached by proxies/clients. Add DisableCache() to these “begin” endpoints.

-userRoute.POST("/passkey/login/begin", middleware.CriticalRateLimit(), controller.PasskeyLoginBegin)
+userRoute.POST("/passkey/login/begin", middleware.CriticalRateLimit(), middleware.DisableCache(), controller.PasskeyLoginBegin)

65-69: Also disable cache for self passkey begin/verify endpoints.

Same rationale: options/challenges must be non-cacheable.

-selfRoute.POST("/passkey/register/begin", controller.PasskeyRegisterBegin)
+selfRoute.POST("/passkey/register/begin", middleware.DisableCache(), controller.PasskeyRegisterBegin)
-selfRoute.POST("/passkey/verify/begin", controller.PasskeyVerifyBegin)
+selfRoute.POST("/passkey/verify/begin", middleware.DisableCache(), controller.PasskeyVerifyBegin)

98-98: Consider rate limiting admin passkey resets.

Resetting another user’s passkey is sensitive. Add CriticalRateLimit to reduce abuse potential.

-adminRoute.DELETE("/:id/passkey", controller.AdminResetPasskey)
+adminRoute.DELETE("/:id/passkey", middleware.CriticalRateLimit(), controller.AdminResetPasskey)
web/src/components/table/users/UsersColumnDefs.jsx (1)

258-271: Style destructive operations as dangerous and add tooltips.

These actions are irreversible/security‑sensitive. Use danger styling and short tooltips to reduce misclicks.

-<Button
-  type='warning'
+<Button
+  type='danger'
   size='small'
   onClick={() => showResetPasskeyModal(record)}
 >
-  {t('重置 Passkey')}
+  {t('重置 Passkey')}
 </Button>

-<Button
-  type='warning'
+<Button
+  type='danger'
   size='small'
   onClick={() => showResetTwoFAModal(record)}
 >
   {t('重置 2FA')}
 </Button>

Optionally wrap with <Tooltip content={t('需要确认,操作不可撤销')}>….

web/src/components/settings/personal/cards/AccountManagement.jsx (2)

95-99: Guard date parsing for robustness.

If last_used_at arrives as an invalid/empty value, new Date(...) can produce “Invalid Date”. You already gate on presence; add a sanity check for parseability to avoid edge cases.

-const lastUsedLabel = passkeyStatus?.last_used_at
-  ? new Date(passkeyStatus.last_used_at).toLocaleString()
-  : t('尚未使用');
+const lastUsedLabel = (() => {
+  const v = passkeyStatus?.last_used_at;
+  const d = v ? new Date(v) : null;
+  return d && !isNaN(d.getTime()) ? d.toLocaleString() : t('尚未使用');
+})();

489-539: Good UX; add reason tooltip when action is disabled.

When device doesn’t support Passkey and it’s not enabled, the button is disabled. Consider a tooltip explaining why to reduce confusion.

-<Button
+{/* Wrap with Tooltip when disabled */}
+<Tooltip content={!passkeySupported && !passkeyEnabled ? t('当前设备不支持 Passkey') : undefined}>
+  <Button
     type='primary'
     theme={passkeyEnabled ? 'outline' : 'solid'}
     onClick={passkeyEnabled ? onPasskeyDelete : onPasskeyRegister}
     className='w-full sm:w-auto'
     icon={<IconKey />}
     disabled={!passkeySupported && !passkeyEnabled}
     loading={passkeyEnabled ? passkeyDeleteLoading : passkeyRegisterLoading}
   >
     {passkeyEnabled ? t('解绑 Passkey') : t('注册 Passkey')}
-  </Button>
+  </Button>
+</Tooltip>
setting/system_setting/passkey.go (3)

8-16: Constrain config with enums to avoid typos and invalid values

UserVerification and AttachmentPreference are free-form strings; a typo will silently degrade behavior. Use typed enums.

+type UserVerification string
+const (
+  UVRequired    UserVerification = "required"
+  UVPreferred   UserVerification = "preferred"
+  UVDiscouraged UserVerification = "discouraged"
+)
+
+type AttachmentPreference string
+const (
+  AttachPlatform      AttachmentPreference = "platform"
+  AttachCrossPlatform AttachmentPreference = "cross-platform"
+  AttachAuto          AttachmentPreference = ""
+)
 
-type PasskeySettings struct {
+type PasskeySettings struct {
   Enabled              bool     `json:"enabled"`
   RPDisplayName        string   `json:"rp_display_name"`
   RPID                 string   `json:"rp_id"`
   Origins              []string `json:"origins"`
   AllowInsecureOrigin  bool     `json:"allow_insecure_origin"`
-  UserVerification     string   `json:"user_verification"`
-  AttachmentPreference string   `json:"attachment_preference"`
+  UserVerification     UserVerification     `json:"user_verification"`
+  AttachmentPreference AttachmentPreference `json:"attachment_preference"`
 }

18-26: Validate RPID and Origins early to catch misconfigurations

Defaults leave RPID and Origins empty. At runtime, this can cause subtle failures or weaker domain binding. Add validation/normalization:

  • RPID must be a registrable domain and align with the request host.
  • Origins must be https:// origins (except loopback when AllowInsecureOrigin is true).
  • Reject unknown UserVerification / AttachmentPreference values.
+import (
+  "errors"
+  "net/url"
+  "strings"
+)
+
+func (s *PasskeySettings) Normalize() {
+  s.RPID = strings.ToLower(strings.TrimSpace(s.RPID))
+}
+
+func (s *PasskeySettings) Validate() error {
+  if s.Enabled {
+    if s.RPID == "" {
+      return errors.New("passkey.rp_id must be set when passkeys are enabled")
+    }
+    for _, o := range s.Origins {
+      u, err := url.Parse(o)
+      if err != nil || (u.Scheme != "https" && !(s.AllowInsecureOrigin && (u.Hostname() == "localhost" || u.Hostname() == "127.0.0.1"))) {
+        return errors.New("invalid origin: " + o)
+      }
+    }
+  }
+  return nil
+}

To ensure we’re aligned, please confirm whether service/passkey uses a fallback host when RPID is empty, and whether validation already exists upstream.


32-34: Avoid exposing mutable global state; provide a snapshot getter

Returning a pointer to a package-level var invites accidental mutation by callers. Keep GetPasskeySettings for wiring, but add a read-only snapshot for general use.

 func GetPasskeySettings() *PasskeySettings {
   return &defaultPasskeySettings
 }
+
+// Safer for read-only use in other packages.
+func GetPasskeySettingsSnapshot() PasskeySettings {
+  return defaultPasskeySettings
+}
web/src/hooks/users/useUsersData.jsx (2)

157-172: Harden guard and refresh list after successful Passkey reset

  • Also check user.id to avoid 404s.
  • Refresh data so UI reflects the reset state.
-const resetUserPasskey = async (user) => {
-  if (!user) {
-    return;
-  }
+const resetUserPasskey = async (user) => {
+  if (!user || !user.id) {
+    showError(t('无效的用户'));
+    return;
+  }
   try {
     const res = await API.delete(`/api/user/${user.id}/passkey`);
     const { success, message } = res.data;
     if (success) {
       showSuccess(t('Passkey 已重置'));
+      await refresh();
     } else {
       showError(message || t('操作失败,请重试'));
     }
   } catch (error) {
     showError(t('操作失败,请重试'));
   }
 };

174-189: Apply same guard/refresh for 2FA reset

Mirror the above for consistency and UI correctness.

-const resetUserTwoFA = async (user) => {
-  if (!user) {
-    return;
-  }
+const resetUserTwoFA = async (user) => {
+  if (!user || !user.id) {
+    showError(t('无效的用户'));
+    return;
+  }
   try {
     const res = await API.delete(`/api/user/${user.id}/2fa`);
     const { success, message } = res.data;
     if (success) {
       showSuccess(t('二步验证已重置'));
+      await refresh();
     } else {
       showError(message || t('操作失败,请重试'));
     }
   } catch (error) {
     showError(t('操作失败,请重试'));
   }
 };
web/src/components/settings/PersonalSetting.jsx (3)

174-191: Status loader LGTM; consider logging failures for diagnostics

Current catch silently ignores errors. Optional: log at debug to aid support.

   } catch (error) {
-    // 忽略错误,保留默认状态
+    // 可选:记录调试日志以便诊断
+    console.debug?.('loadPasskeyStatus failed', error);
   }

193-231: Handle insecure contexts and common cancellation errors in registration

  • Add secure-context guard for clearer UX (non-localhost HTTP will fail).
  • Treat NotAllowedError (common cancel) as a benign cancel, like AbortError.
  • Handle null credential explicitly.
 const handleRegisterPasskey = async () => {
-  if (!passkeySupported || !window.PublicKeyCredential) {
+  if (!passkeySupported || !window.PublicKeyCredential) {
     showInfo(t('当前设备不支持 Passkey'));
     return;
   }
+  if (!window.isSecureContext && !/^localhost|127\\.0\\.0\\.1$/.test(window.location.hostname)) {
+    showInfo(t('请在安全环境(HTTPS 或 localhost)下进行 Passkey 注册'));
+    return;
+  }
   setPasskeyRegisterLoading(true);
   try {
     const beginRes = await API.post('/api/user/passkey/register/begin');
     const { success, message, data } = beginRes.data;
     if (!success) {
       showError(message || t('无法发起 Passkey 注册'));
       return;
     }
 
     const publicKey = prepareCredentialCreationOptions(data?.options || data?.publicKey || data);
-    const credential = await navigator.credentials.create({ publicKey });
+    const credential = await navigator.credentials.create({ publicKey });
+    if (!credential) {
+      showInfo(t('已取消 Passkey 注册'));
+      return;
+    }
     const payload = buildRegistrationResult(credential);
     if (!payload) {
       showError(t('Passkey 注册失败,请重试'));
       return;
     }
 
     const finishRes = await API.post('/api/user/passkey/register/finish', payload);
     if (finishRes.data.success) {
       showSuccess(t('Passkey 注册成功'));
       await loadPasskeyStatus();
     } else {
       showError(finishRes.data.message || t('Passkey 注册失败,请重试'));
     }
   } catch (error) {
-    if (error?.name === 'AbortError') {
+    if (error?.name === 'AbortError' || error?.name === 'NotAllowedError') {
       showInfo(t('已取消 Passkey 注册'));
     } else {
       showError(t('Passkey 注册失败,请重试'));
     }
   } finally {
     setPasskeyRegisterLoading(false);
   }
 };

233-249: Passkey deletion flow LGTM; optional confirm

Consider adding a confirm dialog at the call site to prevent accidental removal.

controller/channel.go (2)

425-461: Add brute-force mitigation for 2FA attempts

Consider per‑user rate limiting and temporary lockouts on failed 2FA attempts to reduce guessing. Enforce minimal delays or use a token bucket keyed by userId.

Would you like a small Redis-backed limiter snippet wired into this handler?


475-481: Log the resolved verification method

If you adopt token-based passkey verification (above), ensure logMethod reflects the actual validated method (including defaulted paths). Today it defaults to "2fa" when method is empty; after token enforcement, callers should always specify method.

web/src/components/auth/LoginForm.jsx (1)

280-327: Harden Passkey login UX and error handling

  • Guard against double‑clicks.
  • Treat NotAllowedError as user cancel.
  • Optional: pass mediation when available for better UX.
-  const handlePasskeyLogin = async () => {
+  const handlePasskeyLogin = async () => {
+    if (passkeyLoading) return;
     if (!passkeySupported) {
       showInfo('当前环境无法使用 Passkey 登录');
       return;
     }
     if (!window.PublicKeyCredential) {
       showInfo('当前浏览器不支持 Passkey');
       return;
     }
@@
-      const assertion = await navigator.credentials.get({ publicKey: publicKeyOptions });
+      const assertion = await navigator.credentials.get({
+        publicKey: publicKeyOptions,
+        // mediation hint improves UX where supported
+        ...(window.PublicKeyCredential.isConditionalMediationAvailable
+          ? { mediation: 'conditional' }
+          : {}),
+      });
@@
-    } catch (error) {
-      if (error?.name === 'AbortError') {
+    } catch (error) {
+      if (error?.name === 'AbortError' || error?.name === 'NotAllowedError') {
         showInfo('已取消 Passkey 登录');
       } else {
         showError('Passkey 登录失败,请重试');
       }
     } finally {
       setPasskeyLoading(false);
     }
   };
web/src/components/common/modals/SecureVerificationModal.jsx (3)

158-159: Provide a safe default active tab

If method is null, Tabs may render with no active pane. Default to 2FA when available, else passkey.

-        <Tabs activeKey={method} onChange={onMethodSwitch} type='card'>
+        <Tabs
+          activeKey={method || (has2FA ? '2fa' : (hasPasskey && passkeySupported ? 'passkey' : '2fa'))}
+          onChange={onMethodSwitch}
+          type='card'
+        >

182-193: Improve 2FA input ergonomics

Add numeric input hints for TOTP while still allowing backup codes; enforce min length before enabling “验证”.

-                    <Input
+                    <Input
                       placeholder={t('请输入认证器验证码或备用码')}
                       value={code}
                       onChange={onCodeChange}
                       size='large'
-                      maxLength={8}
+                      maxLength={8}
+                      inputMode='numeric'
+                      pattern='[0-9]*'
                       onKeyDown={handleKeyDown}
                       autoFocus={method === '2fa'}
                     />

250-259: Passkey verify button callback

If parent may pass method=null initially, call with a literal to avoid ambiguity.

-                      onClick={() => onVerify(method)}
+                      onClick={() => onVerify('passkey')}
service/passkey/user.go (2)

22-27: Use FormatInt for int-size portability

Avoid implicit platform int size in string conversion.

- return []byte(strconv.Itoa(u.user.Id))
+ return []byte(strconv.FormatInt(int64(u.user.Id), 10))

51-57: Prefer empty slice over nil for credentials

Some callers iterate without nil checks.

 func (u *WebAuthnUser) WebAuthnCredentials() []webauthn.Credential {
-  if u == nil || u.credential == nil {
-    return nil
-  }
+  if u == nil || u.credential == nil {
+    return []webauthn.Credential{}
+  }
   cred := u.credential.ToWebAuthnCredential()
   return []webauthn.Credential{cred}
 }
web/src/helpers/passkey.js (4)

1-12: Harden base64url decoding and accept typed arrays

Add try/catch and handle ArrayBuffer/ArrayBufferView inputs to avoid DOMExceptions and improve interop.

-export function base64UrlToBuffer(base64url) {
-  if (!base64url) return new ArrayBuffer(0);
-  let padding = '='.repeat((4 - (base64url.length % 4)) % 4);
-  const base64 = (base64url + padding).replace(/-/g, '+').replace(/_/g, '/');
-  const rawData = window.atob(base64);
+export function base64UrlToBuffer(input) {
+  if (!input) return new ArrayBuffer(0);
+  if (input instanceof ArrayBuffer) return input;
+  if (ArrayBuffer.isView(input)) {
+    return input.buffer.slice(input.byteOffset, input.byteOffset + input.byteLength);
+  }
+  const base64url = String(input);
+  const padding = '='.repeat((4 - (base64url.length % 4)) % 4);
+  const base64 = (base64url + padding).replace(/-/g, '+').replace(/_/g, '/');
+  let rawData;
+  try {
+    rawData = window.atob(base64);
+  } catch (e) {
+    throw new Error('Invalid base64url input');
+  }
   const buffer = new ArrayBuffer(rawData.length);
   const uintArray = new Uint8Array(buffer);
   for (let i = 0; i < rawData.length; i += 1) {
     uintArray[i] = rawData.charCodeAt(i);
   }
   return buffer;
 }

14-26: Support ArrayBufferView in encoder

Make encoder robust to ArrayBuffer and typed views.

 export function bufferToBase64Url(buffer) {
   if (!buffer) return '';
-  const uintArray = new Uint8Array(buffer);
+  const uintArray = buffer instanceof ArrayBuffer
+    ? new Uint8Array(buffer)
+    : new Uint8Array(buffer.buffer, buffer.byteOffset ?? 0, buffer.byteLength ?? buffer.length);
   let binary = '';
   for (let i = 0; i < uintArray.byteLength; i += 1) {
     binary += String.fromCharCode(uintArray[i]);
   }
   return window
     .btoa(binary)

28-54: Validate required fields and pass-through already-binary inputs

Guard for missing challenge/user.id and avoid double decoding if already ArrayBuffer.

 export function prepareCredentialCreationOptions(payload) {
   const options = payload?.publicKey || payload?.PublicKey || payload?.response || payload?.Response;
   if (!options) {
     throw new Error('无法从服务端响应中解析 Passkey 注册参数');
   }
+  if (!options.challenge || !options.user?.id) {
+    throw new Error('注册参数缺失:challenge 或 user.id');
+  }
   const publicKey = {
     ...options,
-    challenge: base64UrlToBuffer(options.challenge),
+    challenge: (options.challenge instanceof ArrayBuffer || ArrayBuffer.isView(options.challenge))
+      ? options.challenge
+      : base64UrlToBuffer(options.challenge),
     user: {
       ...options.user,
-      id: base64UrlToBuffer(options.user?.id),
+      id: (options.user?.id instanceof ArrayBuffer || ArrayBuffer.isView(options.user?.id))
+        ? options.user.id
+        : base64UrlToBuffer(options.user?.id),
     },
   };
 
   if (Array.isArray(options.excludeCredentials)) {
     publicKey.excludeCredentials = options.excludeCredentials.map((item) => ({
       ...item,
-      id: base64UrlToBuffer(item.id),
+      id: (item.id instanceof ArrayBuffer || ArrayBuffer.isView(item.id))
+        ? item.id
+        : base64UrlToBuffer(item.id),
     }));
   }
 
   if (Array.isArray(options.attestationFormats) && options.attestationFormats.length === 0) {
     delete publicKey.attestationFormats;
   }
 
   return publicKey;
 }

56-74: Mirror the same robustness for request options

Same pass-through and validation for allowCredentials.

 export function prepareCredentialRequestOptions(payload) {
   const options = payload?.publicKey || payload?.PublicKey || payload?.response || payload?.Response;
   if (!options) {
     throw new Error('无法从服务端响应中解析 Passkey 登录参数');
   }
   const publicKey = {
     ...options,
-    challenge: base64UrlToBuffer(options.challenge),
+    challenge: (options.challenge instanceof ArrayBuffer || ArrayBuffer.isView(options.challenge))
+      ? options.challenge
+      : base64UrlToBuffer(options.challenge),
   };
 
   if (Array.isArray(options.allowCredentials)) {
     publicKey.allowCredentials = options.allowCredentials.map((item) => ({
       ...item,
-      id: base64UrlToBuffer(item.id),
+      id: (item.id instanceof ArrayBuffer || ArrayBuffer.isView(item.id))
+        ? item.id
+        : base64UrlToBuffer(item.id),
     }));
   }
 
   return publicKey;
 }
web/src/hooks/common/useSecureVerification.jsx (2)

124-160: Default to current selected method and pass full error object

Avoid requiring callers to always pass method; preserve Axios error info by passing the error object to showError.

-  const executeVerification = useCallback(async (method, code = '') => {
+  const executeVerification = useCallback(async (method, code = '') => {
     if (!verificationState.apiCall) {
       showError(t('验证配置错误'));
       return;
     }
 
     setVerificationState(prev => ({ ...prev, loading: true }));
 
     try {
-      const result = await SecureVerificationService.verify(method, {
+      const chosen = method || verificationState.method;
+      const result = await SecureVerificationService.verify(chosen, {
         code,
         apiCall: verificationState.apiCall
       });
 
       // 显示成功消息
       if (successMessage) {
         showSuccess(successMessage);
       }
 
       // 调用成功回调
-      onSuccess?.(result, method);
+      onSuccess?.(result, chosen);
 
       // 自动重置状态
       if (autoReset) {
         resetState();
       }
 
       return result;
     } catch (error) {
-      showError(error.message || t('验证失败,请重试'));
+      showError(error);
       onError?.(error);
       throw error;
     } finally {
       setVerificationState(prev => ({ ...prev, loading: false }));
     }
   }, [verificationState.apiCall, successMessage, onSuccess, onError, autoReset, resetState, t]);

84-95: Gate console logs in production

Reduce noise and potential info leakage.

You already applied this in the previous diff via NODE_ENV checks; apply similarly to other console.* in this module if any remain.

web/src/services/secureVerification.js (2)

88-96: Preflight support check before WebAuthn call

Guard against environments without WebAuthn to fail fast with a clear error.

   static async verifyPasskey(apiCall) {
     try {
+      if (!(await isPasskeySupported())) {
+        throw new Error('当前浏览器不支持 Passkey');
+      }
       // 开始Passkey验证
       const beginResponse = await API.post('/api/user/passkey/verify/begin');

37-47: Remove or gate noisy console logs

These leak auth capability info to the console; gate behind a dev flag or remove.

-      console.log('Checking user verification methods...');
...
-      console.log('2FA response:', twoFAResponse);
-      console.log('Passkey response:', passkeyResponse);
-      console.log('Passkey browser support:', passkeySupported);
...
-      console.log('Final verification methods result:', result);

Also applies to: 54-55

service/passkey/service.go (2)

47-55: Make resident keys preferred, not strictly required

Requiring RK can exclude some authenticators; “preferred” keeps passkey UX while staying compatible.

-	selection := protocol.AuthenticatorSelection{
-		ResidentKey:        protocol.ResidentKeyRequirementRequired,
-		RequireResidentKey: protocol.ResidentKeyRequired(),
-		UserVerification:   protocol.UserVerificationRequirement(settings.UserVerification),
-	}
+	selection := protocol.AuthenticatorSelection{
+		ResidentKey:        protocol.ResidentKeyRequirementPreferred,
+		RequireResidentKey: protocol.ResidentKeyNotRequired(),
+		UserVerification:   protocol.UserVerificationRequirement(settings.UserVerification),
+	}

137-142: Derive RPID from the current request host when available

Choosing the first origin may mismatch in multi-origin setups behind proxies.

-	parsed, err := url.Parse(origins[0])
-	if err != nil {
-		return "", fmt.Errorf("无法解析 Passkey Origin: %w", err)
-	}
-	return hostWithoutPort(parsed.Host), nil
+	host := strings.TrimSpace(r.Host)
+	if host == "" {
+		parsed, err := url.Parse(origins[0])
+		if err != nil {
+			return "", fmt.Errorf("无法解析 Passkey Origin: %w", err)
+		}
+		host = parsed.Host
+	}
+	return hostWithoutPort(host), nil
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c7a5237 and dcf4336.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (29)
  • controller/channel.go (4 hunks)
  • controller/misc.go (2 hunks)
  • controller/passkey.go (1 hunks)
  • go.mod (5 hunks)
  • model/main.go (2 hunks)
  • model/passkey.go (1 hunks)
  • router/api-router.go (4 hunks)
  • service/passkey/service.go (1 hunks)
  • service/passkey/session.go (1 hunks)
  • service/passkey/user.go (1 hunks)
  • setting/system_setting/passkey.go (1 hunks)
  • web/src/components/auth/LoginForm.jsx (6 hunks)
  • web/src/components/common/examples/ChannelKeyViewExample.jsx (1 hunks)
  • web/src/components/common/modals/SecureVerificationModal.jsx (1 hunks)
  • web/src/components/settings/PersonalSetting.jsx (5 hunks)
  • web/src/components/settings/SystemSetting.jsx (6 hunks)
  • web/src/components/settings/personal/cards/AccountManagement.jsx (3 hunks)
  • web/src/components/table/channels/modals/EditChannelModal.jsx (6 hunks)
  • web/src/components/table/users/UsersColumnDefs.jsx (4 hunks)
  • web/src/components/table/users/UsersTable.jsx (7 hunks)
  • web/src/components/table/users/modals/ResetPasskeyModal.jsx (1 hunks)
  • web/src/components/table/users/modals/ResetTwoFAModal.jsx (1 hunks)
  • web/src/helpers/index.js (1 hunks)
  • web/src/helpers/passkey.js (1 hunks)
  • web/src/hooks/common/useSecureVerification.jsx (1 hunks)
  • web/src/hooks/users/useUsersData.jsx (3 hunks)
  • web/src/i18n/locales/en.json (2 hunks)
  • web/src/i18n/locales/zh.json (2 hunks)
  • web/src/services/secureVerification.js (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (20)
controller/misc.go (1)
setting/system_setting/passkey.go (1)
  • GetPasskeySettings (32-34)
web/src/components/table/users/UsersColumnDefs.jsx (1)
web/src/components/table/users/UsersTable.jsx (2)
  • showResetPasskeyModal (62-62)
  • showResetTwoFAModal (63-63)
web/src/components/settings/PersonalSetting.jsx (2)
web/src/helpers/passkey.js (6)
  • isPasskeySupported (116-136)
  • publicKey (33-40)
  • publicKey (61-64)
  • prepareCredentialCreationOptions (28-54)
  • credential (79-79)
  • buildRegistrationResult (76-94)
web/src/helpers/utils.jsx (3)
  • showError (122-151)
  • showInfo (161-163)
  • showSuccess (157-159)
web/src/hooks/users/useUsersData.jsx (1)
web/src/helpers/utils.jsx (2)
  • showSuccess (157-159)
  • showError (122-151)
setting/system_setting/passkey.go (2)
common/constants.go (1)
  • SystemName (14-14)
setting/config/config.go (1)
  • GlobalConfig (18-18)
web/src/services/secureVerification.js (1)
web/src/helpers/passkey.js (5)
  • isPasskeySupported (116-136)
  • publicKey (33-40)
  • publicKey (61-64)
  • prepareCredentialRequestOptions (56-74)
  • buildAssertionResult (96-114)
model/passkey.go (2)
common/sys_log.go (1)
  • SysLog (11-14)
model/main.go (1)
  • DB (63-63)
web/src/components/table/users/UsersTable.jsx (3)
web/src/hooks/users/useUsersData.jsx (2)
  • resetUserPasskey (157-172)
  • resetUserTwoFA (174-189)
web/src/components/table/users/modals/ResetPasskeyModal.jsx (1)
  • ResetPasskeyModal (23-36)
web/src/components/table/users/modals/ResetTwoFAModal.jsx (1)
  • ResetTwoFAModal (23-36)
web/src/components/table/channels/modals/EditChannelModal.jsx (4)
web/src/hooks/common/useSecureVerification.jsx (10)
  • useSecureVerification (33-225)
  • useSecureVerification (33-225)
  • startVerification (83-122)
  • isModalVisible (49-49)
  • verificationMethods (42-46)
  • verificationState (52-57)
  • executeVerification (125-160)
  • cancelVerification (173-175)
  • setVerificationCode (163-165)
  • switchVerificationMethod (168-170)
web/src/services/secureVerification.js (2)
  • createApiCalls (152-183)
  • createApiCalls (152-183)
web/src/components/common/modals/SecureVerificationModal.jsx (3)
  • SecureVerificationModal (38-269)
  • verificationMethods (51-51)
  • verificationState (52-52)
web/src/components/common/ui/ChannelKeyDisplay.jsx (1)
  • ChannelKeyDisplay (86-278)
model/main.go (1)
model/passkey.go (1)
  • PasskeyCredential (21-40)
web/src/components/common/modals/SecureVerificationModal.jsx (1)
web/src/hooks/common/useSecureVerification.jsx (2)
  • verificationMethods (42-46)
  • verificationState (52-57)
web/src/components/settings/personal/cards/AccountManagement.jsx (1)
web/src/components/settings/PersonalSetting.jsx (4)
  • passkeyStatus (72-72)
  • passkeySupported (75-75)
  • passkeyDeleteLoading (74-74)
  • passkeyRegisterLoading (73-73)
controller/channel.go (5)
model/twofa.go (1)
  • GetTwoFAByUserId (40-55)
common/gin.go (1)
  • ApiError (95-100)
model/passkey.go (1)
  • GetPasskeyByUserID (136-151)
model/log.go (1)
  • RecordLog (78-94)
model/channel.go (1)
  • GetChannelById (331-346)
router/api-router.go (3)
controller/passkey.go (9)
  • PasskeyLoginBegin (208-241)
  • PasskeyLoginFinish (243-332)
  • PasskeyStatus (165-206)
  • PasskeyRegisterBegin (21-79)
  • PasskeyRegisterFinish (81-142)
  • PasskeyVerifyBegin (370-422)
  • PasskeyVerifyFinish (424-482)
  • PasskeyDelete (144-163)
  • AdminResetPasskey (334-368)
middleware/disable-cache.go (1)
  • DisableCache (5-12)
controller/channel.go (1)
  • GetChannelKeyWithPasskey (493-535)
web/src/hooks/common/useSecureVerification.jsx (5)
web/src/components/common/examples/ChannelKeyViewExample.jsx (2)
  • useSecureVerification (38-56)
  • useTranslation (33-33)
web/src/components/table/channels/modals/EditChannelModal.jsx (2)
  • useSecureVerification (205-225)
  • useTranslation (133-133)
web/src/components/common/modals/SecureVerificationModal.jsx (3)
  • useTranslation (49-49)
  • verificationMethods (51-51)
  • verificationState (52-52)
web/src/services/secureVerification.js (1)
  • SecureVerificationService (30-147)
web/src/helpers/utils.jsx (2)
  • showError (122-151)
  • showSuccess (157-159)
web/src/components/auth/LoginForm.jsx (4)
web/src/helpers/passkey.js (4)
  • isPasskeySupported (116-136)
  • prepareCredentialRequestOptions (56-74)
  • assertion (99-99)
  • buildAssertionResult (96-114)
web/src/helpers/utils.jsx (3)
  • showInfo (161-163)
  • showError (122-151)
  • showSuccess (157-159)
web/src/helpers/api.js (2)
  • payload (117-122)
  • updateAPI (69-81)
web/src/helpers/data.js (1)
  • setUserData (57-59)
web/src/components/common/examples/ChannelKeyViewExample.jsx (5)
web/src/components/common/modals/SecureVerificationModal.jsx (4)
  • useTranslation (49-49)
  • SecureVerificationModal (38-269)
  • verificationMethods (51-51)
  • verificationState (52-52)
web/src/components/table/channels/modals/EditChannelModal.jsx (3)
  • useTranslation (133-133)
  • useSecureVerification (205-225)
  • channelId (134-134)
web/src/hooks/common/useSecureVerification.jsx (11)
  • useTranslation (39-39)
  • useSecureVerification (33-225)
  • useSecureVerification (33-225)
  • startVerification (83-122)
  • isModalVisible (49-49)
  • verificationMethods (42-46)
  • verificationState (52-57)
  • executeVerification (125-160)
  • cancelVerification (173-175)
  • setVerificationCode (163-165)
  • switchVerificationMethod (168-170)
web/src/services/secureVerification.js (2)
  • createApiCalls (152-183)
  • createApiCalls (152-183)
web/src/components/common/ui/ChannelKeyDisplay.jsx (1)
  • ChannelKeyDisplay (86-278)
controller/passkey.go (7)
setting/system_setting/passkey.go (1)
  • GetPasskeySettings (32-34)
model/passkey.go (6)
  • GetPasskeyByUserID (136-151)
  • ErrPasskeyNotFound (17-17)
  • NewPasskeyCredentialFromWebAuthn (96-116)
  • UpsertPasskeyCredential (172-189)
  • DeletePasskeyByUserID (191-202)
  • GetPasskeyByCredentialID (153-170)
common/gin.go (2)
  • ApiError (95-100)
  • ApiErrorMsg (102-107)
service/passkey/service.go (4)
  • BuildWebAuthn (26-80)
  • RegistrationSessionKey (20-20)
  • LoginSessionKey (21-21)
  • VerifySessionKey (22-22)
service/passkey/user.go (2)
  • NewWebAuthnUser (18-20)
  • WebAuthnUser (13-16)
service/passkey/session.go (2)
  • SaveSessionData (14-26)
  • PopSessionData (28-50)
common/constants.go (1)
  • UserStatusEnabled (174-174)
service/passkey/user.go (1)
model/passkey.go (1)
  • PasskeyCredential (21-40)
service/passkey/service.go (3)
setting/system_setting/passkey.go (2)
  • GetPasskeySettings (32-34)
  • PasskeySettings (8-16)
common/constants.go (2)
  • SystemName (14-14)
  • DebugEnabled (70-70)
setting/system_setting/system_setting_old.go (1)
  • ServerAddress (3-3)
🔇 Additional comments (35)
model/main.go (1)

254-254: LGTM! PasskeyCredential properly integrated into migrations.

The PasskeyCredential model is correctly added to both the standard and parallel migration flows, maintaining consistency across both migration methods.

Also applies to: 287-287

controller/misc.go (1)

45-46: LGTM! Passkey settings properly integrated into status endpoint.

The passkey settings are correctly retrieved within the mutex lock and all relevant fields are properly exposed in the status response, maintaining consistency with other authentication methods in the response structure.

Also applies to: 99-105

web/src/components/settings/SystemSetting.jsx (1)

81-87: Passkey state initialization and parsing handled correctly.

The passkey configuration fields are properly initialized and parsed with appropriate type handling and safe fallbacks for JSON parsing errors.

Also applies to: 125-125, 190-206

go.mod (1)

4-6: No changes needed for Go version
Go 1.24.0 and toolchain go1.24.6 are valid; the current stable release is Go 1.25.1 (released September 3, 2025).

model/passkey.go (3)

73-94: Mapping to webauthn.Credential looks correct

Fields and flags map 1:1; Attachment cast is appropriate.

Ensure the service layer updates SignCount on successful assertions and refuses assertions with decreased/newer-than-expected counters to detect cloning.


136-151: Friendly errors and logging are fine

Getter reads are safe; soft-deleted rows are excluded by default. LGTM.


153-170: Lookup by credential ID LGTM

Binary comparison via driver is fine; friendly error avoids leakage.

web/src/helpers/index.js (1)

30-30: Re-export of passkey helpers is good

This exposes Passkey utilities at a stable entrypoint for consumers.

web/src/components/table/users/UsersColumnDefs.jsx (1)

197-211: ```bash
#!/bin/bash

Locate all getUsersColumns calls to inspect passed props

rg -nP "getUsersColumns\s*(" -g '*.{js,jsx}' -C3

Please share the output for further verification.

</blockquote></details>
<details>
<summary>web/src/hooks/users/useUsersData.jsx (2)</summary><blockquote>

`89-121`: **No functional change in searchUsers signature**

Formatting-only change; behavior remains intact.

---

`304-310`: **Confirm admin routes and RBAC**  
- DELETE /api/user/:id/passkey and DELETE /api/user/:id/2fa are defined under `adminRoute` in router/api-router.go  
- Verify that `adminRoute` is guarded by an admin-only middleware (or that `AdminResetPasskey` and `AdminDisable2FA` handlers explicitly check `model.IsAdmin`) so only admins can invoke these endpoints

</blockquote></details>
<details>
<summary>web/src/components/settings/PersonalSetting.jsx (4)</summary><blockquote>

`123-126`: **Capability check LGTM**

Gracefully detects support and falls back to disabled state.

---

`256-256`: **Nice: refresh status after user load**

Ensures UI reflects actual Passkey binding state.

---

`29-32`: **Imports grouped coherently**

Passkey helpers are imported from a single barrel; no issues.

---

`445-449`: **No runtime warning risk for Passkey props in AccountManagement**  
All new Passkey-related props are destructured and used with optional chaining and guarded rendering, and the parent component always supplies defined boolean and object defaults—no additional fallbacks needed.

</blockquote></details>
<details>
<summary>web/src/components/auth/LoginForm.jsx (5)</summary><blockquote>

`35-38`: **Imports LGTM**

Helper imports and IconKey addition are correct and scoped to new Passkey UI.




Also applies to: 45-45

---

`80-82`: **State additions LGTM**

Dedicated flags for Passkey support/loading are appropriate.

---

`103-107`: **Capability detection LGTM**

Async isPasskeySupported on mount is fine; fallback to false on error is appropriate.

---

`448-459`: **Passkey button rendering LGTM**

Gated by status.passkey_login and capability; loading wired correctly.

---

`513-524`: **Duplicate Passkey entry point LGTM**

Providing the Passkey button in the email form improves discoverability.

</blockquote></details>
<details>
<summary>web/src/components/common/modals/SecureVerificationModal.jsx (1)</summary><blockquote>

`61-100`: **Empty-methods view LGTM**

Clear guidance when neither 2FA nor Passkey is available.

</blockquote></details>
<details>
<summary>controller/channel.go (1)</summary><blockquote>

`371-376`: **Authorization middleware confirmed**  
`GetChannelKey` and `GetChannelKeyWithPasskey` routes in `router/api-router.go` are under `channelRoute.Use(middleware.AdminAuth())` at line 120, ensuring only admins can access raw channel keys.

</blockquote></details>
<details>
<summary>service/passkey/user.go (4)</summary><blockquote>

`13-21`: **Adapter design and nil-guards look solid**

Constructor and struct fields are straightforward and safe.

---

`29-38`: **Ensure WebAuthnName uniqueness and spec-compat**

Downstream libraries expect a stable, unique RP user handle/name. Your fallback is fine; confirm that Username is unique across tenants and sanitized for CTAP2 constraints.

Would you confirm Username uniqueness and allowed chars in your user model?

---

`40-49`: **DisplayName fallback is appropriate**

Trim and fallback to name is a good default.

---

`10-11`: **No stub required for WebAuthnIcon()**  
The `webauthn.User` interface in the current minor release only mandates `WebAuthnID()`, `WebAuthnName()`, `WebAuthnDisplayName()`, and `WebAuthnCredentials()`. `WebAuthnIcon()` isn’t part of the upstream interface, so no stub is needed.

</blockquote></details>
<details>
<summary>web/src/hooks/common/useSecureVerification.jsx (1)</summary><blockquote>

`200-224`: No occurrences of `executeVerification(` found. Please manually verify that all callsites correctly invoke `executeVerification` with an explicit method argument.

</blockquote></details>
<details>
<summary>web/src/components/table/channels/modals/EditChannelModal.jsx (7)</summary><blockquote>

`59-63`: **Good modularization: adopting SecureVerificationModal/useSecureVerification.**
Imports look correct and align with the new abstraction.

---

`198-203`: **Key exposure state reset is scoped and cleared.**
State is localized and explicitly reset; avoids stale sensitive data.  
If there are route changes outside this modal flow, confirm on unmount the state can’t linger in memory.

---

`204-225`: **Hook integration LGTM; success path shows key.**
onSuccess gate on result.success and data.key is appropriate; success toast is user-friendly.

---

`227-233`: **Clear key data on close.**
Reset helper avoids accidental retention in memory.

---

`735-737`: **Nice: central close resets verification and key state.**
Ensures modal-close hygiene.

---

`2491-2501`: **SecureVerificationModal wiring is correct.**
Props match the hook; title/description fall back inside the modal.  
Confirm Tabs handle `activeKey` if `method` is briefly null on first open (Semi Tabs typically require a valid key). If needed, pass a fallback from `getRecommendedMethod()`.

---

`2523-2529`: **Channel key modal integration LGTM.**
Visibility, close handler, and data flow are correct. 


Also applies to: 2534-2534

</blockquote></details>
<details>
<summary>web/src/i18n/locales/en.json (1)</summary><blockquote>

`9-9`: **New login option key is fine.**
"使用 Passkey 认证" translation reads well.

</blockquote></details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Comment thread controller/channel.go Resolved
Comment thread controller/passkey.go
Comment on lines +463 to +475
waUser := passkeysvc.NewWebAuthnUser(user, credential)
_, err = wa.FinishLogin(waUser, *sessionData, c.Request)
if err != nil {
common.ApiError(c, err)
return
}

// 更新凭证的最后使用时间
now := time.Now()
credential.LastUsedAt = &now
if err := model.UpsertPasskeyCredential(credential); err != nil {
common.ApiError(c, err)
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Not updating credential counters on verify flow

FinishLogin result is ignored; DB only updates LastUsedAt, leaving SignCount/flags stale and weakening clone detection.

-	waUser := passkeysvc.NewWebAuthnUser(user, credential)
-	_, err = wa.FinishLogin(waUser, *sessionData, c.Request)
+	waUser := passkeysvc.NewWebAuthnUser(user, credential)
+	_, verifiedCred, err := wa.FinishLogin(waUser, *sessionData, c.Request)
 	if err != nil {
 		common.ApiError(c, err)
 		return
 	}
 
-	// 更新凭证的最后使用时间
-	now := time.Now()
-	credential.LastUsedAt = &now
-	if err := model.UpsertPasskeyCredential(credential); err != nil {
+	// 使用库返回的最新信息更新凭证(计数器、flags、AAGUID等)
+	updated := model.NewPasskeyCredentialFromWebAuthn(user.Id, verifiedCred)
+	now := time.Now()
+	updated.LastUsedAt = &now
+	if err := model.UpsertPasskeyCredential(updated); err != nil {
 		common.ApiError(c, err)
 		return
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
waUser := passkeysvc.NewWebAuthnUser(user, credential)
_, err = wa.FinishLogin(waUser, *sessionData, c.Request)
if err != nil {
common.ApiError(c, err)
return
}
// 更新凭证的最后使用时间
now := time.Now()
credential.LastUsedAt = &now
if err := model.UpsertPasskeyCredential(credential); err != nil {
common.ApiError(c, err)
return
waUser := passkeysvc.NewWebAuthnUser(user, credential)
_, verifiedCred, err := wa.FinishLogin(waUser, *sessionData, c.Request)
if err != nil {
common.ApiError(c, err)
return
}
// 使用库返回的最新信息更新凭证(计数器、flags、AAGUID等)
updated := model.NewPasskeyCredentialFromWebAuthn(user.Id, verifiedCred)
now := time.Now()
updated.LastUsedAt = &now
if err := model.UpsertPasskeyCredential(updated); err != nil {
common.ApiError(c, err)
return
}
🤖 Prompt for AI Agents
In controller/passkey.go around lines 463-475, the code ignores FinishLogin's
result and only updates LastUsedAt, so SignCount and clone-detection flags
remain stale; change the flow to capture FinishLogin's returned
assertion/updated credential data, extract the new SignCount (and any flags like
CloneWarning/CloneDetected), assign them to the credential along with
LastUsedAt, and persist all fields via model.UpsertPasskeyCredential (handling
Upsert errors as currently done); ensure you validate/convert types as needed
and only update the DB after successfully reading these values from FinishLogin.

Comment thread controller/passkey.go
Comment on lines +490 to +493
id, ok := idRaw.(int)
if !ok {
return nil, errors.New("无效的会话信息")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Session user ID type-casting is too strict

Sessions often store IDs as string/int64/float64; current code rejects those.

-	id, ok := idRaw.(int)
-	if !ok {
-		return nil, errors.New("无效的会话信息")
-	}
+	var id int
+	switch v := idRaw.(type) {
+	case int:
+		id = v
+	case int64:
+		id = int(v)
+	case float64:
+		id = int(v)
+	case string:
+		parsed, err := strconv.Atoi(v)
+		if err != nil {
+			return nil, errors.New("无效的会话信息")
+		}
+		id = parsed
+	default:
+		return nil, errors.New("无效的会话信息")
+	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
id, ok := idRaw.(int)
if !ok {
return nil, errors.New("无效的会话信息")
}
var id int
switch v := idRaw.(type) {
case int:
id = v
case int64:
id = int(v)
case float64:
id = int(v)
case string:
parsed, err := strconv.Atoi(v)
if err != nil {
return nil, errors.New("无效的会话信息")
}
id = parsed
default:
return nil, errors.New("无效的会话信息")
}
🤖 Prompt for AI Agents
In controller/passkey.go around lines 490 to 493, the session user ID type
assertion is too strict (only int) and rejects common stored types like int64,
float64, or string; update the logic to accept int, int64, float64, and string
(trim and parse) by normalizing the value into an int64 (or int) before use,
e.g., switch on the dynamic type and convert/parse accordingly, returning the
same "无效的会话信息" error only if conversion fails or value is nil. Ensure you handle
nil, negative/zero checks if required, and preserve existing error semantics.

Comment thread model/passkey.go
Comment on lines +21 to +40
type PasskeyCredential struct {
ID int `json:"id" gorm:"primaryKey"`
UserID int `json:"user_id" gorm:"uniqueIndex;not null"`
CredentialID []byte `json:"credential_id" gorm:"type:blob;uniqueIndex;not null"`
PublicKey []byte `json:"public_key" gorm:"type:blob;not null"`
AttestationType string `json:"attestation_type" gorm:"type:varchar(255)"`
AAGUID []byte `json:"aaguid" gorm:"type:blob"`
SignCount uint32 `json:"sign_count" gorm:"default:0"`
CloneWarning bool `json:"clone_warning"`
UserPresent bool `json:"user_present"`
UserVerified bool `json:"user_verified"`
BackupEligible bool `json:"backup_eligible"`
BackupState bool `json:"backup_state"`
Transports string `json:"transports" gorm:"type:text"`
Attachment string `json:"attachment" gorm:"type:varchar(32)"`
LastUsedAt *time.Time `json:"last_used_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

MySQL portability: uniqueIndex on BLOB/[]byte often fails; consider hash or varchar storage

uniqueIndex on BLOB columns (CredentialID, PublicKey, AAGUID) is not portable to MySQL/MariaDB without prefix length; migrations can fail. Two safer options:

  • Store hex/base64 of CredentialID as VARCHAR(1024) with uniqueIndex.
  • Or store raw bytes plus a SHA-256 hash column for uniqueness and lookup.

At minimum, confirm DB dialect; escalate if MySQL is in use. I can provide a follow-up migration plan.

Would you like me to generate a migration that adds CredentialIDHash and switches lookups to it?


🏁 Script executed:

#!/bin/bash
sed -n '1,200p' model/passkey.go

Length of output: 7188


🏁 Script executed:

#!/bin/bash
rg -n "gorm.Open" -C3 --color never

Length of output: 1316


Clarify BLOB index portability and add a hash for CredentialID uniqueness
CredentialID is the only BLOB column with uniqueIndex; MySQL/MariaDB require prefix lengths on BLOB/TEXT indexes, so migrations can fail when using uniqueIndex on raw bytes. Introduce a SHA-256 (or similar) hash column (e.g. CredentialIDHash VARCHAR(64)) with uniqueIndex for lookups, and retain the raw BLOB for actual data. Ensure DB dialect is MySQL before applying, or specify a prefix length (e.g. gorm:"uniqueIndex:idx_credential_id,sort:255") when MySQL is detected.

Comment thread model/passkey.go
Comment on lines +118 to +134
func (p *PasskeyCredential) ApplyValidatedCredential(credential *webauthn.Credential) {
if credential == nil || p == nil {
return
}
p.CredentialID = credential.ID
p.PublicKey = credential.PublicKey
p.AttestationType = credential.AttestationType
p.AAGUID = credential.Authenticator.AAGUID
p.SignCount = credential.Authenticator.SignCount
p.CloneWarning = credential.Authenticator.CloneWarning
p.UserPresent = credential.Flags.UserPresent
p.UserVerified = credential.Flags.UserVerified
p.BackupEligible = credential.Flags.BackupEligible
p.BackupState = credential.Flags.BackupState
p.Attachment = string(credential.Authenticator.Attachment)
p.SetTransports(credential.Transport)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Prevent silent credential rebind; guard ID and update last-used time

ApplyValidatedCredential overwrites CredentialID without verifying it matches the stored one. If called with a different validated credential, this can rebind the user’s passkey silently. Add an ID-equality guard and return an error; also set LastUsedAt on successful assertion.

-func (p *PasskeyCredential) ApplyValidatedCredential(credential *webauthn.Credential) {
-  if credential == nil || p == nil {
-    return
-  }
-  p.CredentialID = credential.ID
+func (p *PasskeyCredential) ApplyValidatedCredential(credential *webauthn.Credential) error {
+  if credential == nil || p == nil {
+    return nil
+  }
+  // Only update mutable fields for the same credential
+  if !bytes.Equal(p.CredentialID, credential.ID) {
+    common.SysLog("ApplyValidatedCredential: credential ID mismatch; refusing to rebind")
+    return fmt.Errorf("credential mismatch")
+  }
   p.PublicKey = credential.PublicKey
   p.AttestationType = credential.AttestationType
   p.AAGUID = credential.Authenticator.AAGUID
   p.SignCount = credential.Authenticator.SignCount
   p.CloneWarning = credential.Authenticator.CloneWarning
   p.UserPresent = credential.Flags.UserPresent
   p.UserVerified = credential.Flags.UserVerified
   p.BackupEligible = credential.Flags.BackupEligible
   p.BackupState = credential.Flags.BackupState
   p.Attachment = string(credential.Authenticator.Attachment)
   p.SetTransports(credential.Transport)
-}
+  now := time.Now()
+  p.LastUsedAt = &now
+  return nil
+}

Add missing import:

// add to imports
"bytes"
🤖 Prompt for AI Agents
In model/passkey.go around lines 118 to 134, ApplyValidatedCredential currently
always overwrites CredentialID and never reports mismatch; change it to first
compare the incoming credential.ID with the stored p.CredentialID (use
bytes.Equal), return an error if they differ, and only then update fields; on
successful assertion set p.LastUsedAt = time.Now(). Update the function
signature to return error and propagate that error from callers, and add the
missing import "bytes" (and ensure "time" is imported if not already).

Comment on lines 607 to 630
// 显示安全验证模态框并开始验证流程
const handleShow2FAModal = async () => {
try {
const res = await API.post(`/api/channel/${channelId}/key`, {
code: verifyCode,
console.log('=== handleShow2FAModal called ===');
console.log('channelId:', channelId);
console.log('startVerification function:', typeof startVerification);

// 测试模态框状态
console.log('Current modal state:', isModalVisible);

const apiCall = createApiCalls.viewChannelKey(channelId);
console.log('apiCall created:', typeof apiCall);

const result = await startVerification(apiCall, {
title: t('查看渠道密钥'),
description: t('为了保护账户安全,请验证您的身份。'),
preferredMethod: 'passkey', // 优先使用 Passkey
});
if (res.data.success) {
// 验证成功,显示密钥
updateTwoFAState({
showModal: true,
showKey: true,
keyData: res.data.data.key,
});
reset2FAVerifyState();
showSuccess(t('验证成功'));
} else {
showError(res.data.message);
}
console.log('startVerification result:', result);
} catch (error) {
showError(t('获取密钥失败'));
} finally {
setVerifyLoading(false);
console.error('handleShow2FAModal error:', error);
showError(error.message || t('启动验证失败'));
}
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Rename, guard, and remove verbose logs in production.

  • Name is 2FA-specific but flow is now generic; rename for clarity.
  • Add a defensive guard if channelId is falsy.
  • Console noise should be dev-only.

Apply:

-  // 显示安全验证模态框并开始验证流程
-  const handleShow2FAModal = async () => {
+  // 显示安全验证模态框并开始验证流程
+  const handleSecureVerification = async () => {
     try {
-      console.log('=== handleShow2FAModal called ===');
-      console.log('channelId:', channelId);
-      console.log('startVerification function:', typeof startVerification);
-      
-      // 测试模态框状态
-      console.log('Current modal state:', isModalVisible);
-      
+      if (!channelId) {
+        showError(t('渠道未找到,请刷新页面后重试。'));
+        return;
+      }
       const apiCall = createApiCalls.viewChannelKey(channelId);
-      console.log('apiCall created:', typeof apiCall);
-      
       const result = await startVerification(apiCall, {
         title: t('查看渠道密钥'),
-        description: t('为了保护账户安全,请验证您的身份。'),
+        description: t('为了保护账户安全,请验证您的身份。'),
         preferredMethod: 'passkey', // 优先使用 Passkey
       });
-      console.log('startVerification result:', result);
     } catch (error) {
-      console.error('handleShow2FAModal error:', error);
       showError(error.message || t('启动验证失败'));
     }
   };

Update call sites:

- onClick={handleShow2FAModal}
+ onClick={handleSecureVerification}

(Replace at Lines 1412, 1531, and 1601.)
If you prefer keeping logs, wrap them: if (process.env.NODE_ENV === 'development') console.log(...).

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// 显示安全验证模态框并开始验证流程
const handleShow2FAModal = async () => {
try {
const res = await API.post(`/api/channel/${channelId}/key`, {
code: verifyCode,
console.log('=== handleShow2FAModal called ===');
console.log('channelId:', channelId);
console.log('startVerification function:', typeof startVerification);
// 测试模态框状态
console.log('Current modal state:', isModalVisible);
const apiCall = createApiCalls.viewChannelKey(channelId);
console.log('apiCall created:', typeof apiCall);
const result = await startVerification(apiCall, {
title: t('查看渠道密钥'),
description: t('为了保护账户安全,请验证您的身份。'),
preferredMethod: 'passkey', // 优先使用 Passkey
});
if (res.data.success) {
// 验证成功,显示密钥
updateTwoFAState({
showModal: true,
showKey: true,
keyData: res.data.data.key,
});
reset2FAVerifyState();
showSuccess(t('验证成功'));
} else {
showError(res.data.message);
}
console.log('startVerification result:', result);
} catch (error) {
showError(t('获取密钥失败'));
} finally {
setVerifyLoading(false);
console.error('handleShow2FAModal error:', error);
showError(error.message || t('启动验证失败'));
}
};
// 显示安全验证模态框并开始验证流程
const handleSecureVerification = async () => {
try {
if (!channelId) {
showError(t('渠道未找到,请刷新页面后重试。'));
return;
}
const apiCall = createApiCalls.viewChannelKey(channelId);
const result = await startVerification(apiCall, {
title: t('查看渠道密钥'),
description: t('为了保护账户安全,请验证您的身份。'),
preferredMethod: 'passkey', // 优先使用 Passkey
});
} catch (error) {
showError(error.message || t('启动验证失败'));
}
};
🤖 Prompt for AI Agents
In web/src/components/table/channels/modals/EditChannelModal.jsx around lines
607 to 630, the handler is 2FA-specific, lacks a guard for falsy channelId, and
contains verbose console logs; rename the function to a generic name (e.g.,
handleStartVerificationModal), add a defensive check that returns early and
shows an error if channelId is falsy, remove or wrap all
console.log/console.error calls so they only run in development (if
(process.env.NODE_ENV === 'development') ...), and update all call sites at
lines 1412, 1531, and 1601 to use the new function name.

Comment thread web/src/i18n/locales/en.json Outdated
Comment on lines +2134 to +2187
"黑名单": "Blacklist",
"Passkey 登录": "Passkey Sign-in",
"已启用 Passkey,无需密码即可登录": "Passkey enabled. Passwordless login available.",
"使用 Passkey 实现免密且更安全的登录体验": "Use Passkey for a passwordless and more secure login experience.",
"最后使用时间": "Last used time",
"备份支持": "Backup support",
"支持备份": "Supported",
"不支持": "Not supported",
"备份状态": "Backup state",
"已备份": "Backed up",
"未备份": "Not backed up",
"当前设备不支持 Passkey": "Passkey is not supported on this device",
"注册 Passkey": "Register Passkey",
"解绑 Passkey": "Remove Passkey",
"Passkey 注册成功": "Passkey registration successful",
"Passkey 注册失败,请重试": "Passkey registration failed. Please try again.",
"已取消 Passkey 注册": "Passkey registration cancelled",
"Passkey 已解绑": "Passkey removed",
"操作失败,请重试": "Operation failed, please retry",
"重置 Passkey": "Reset Passkey",
"重置 2FA": "Reset 2FA",
"确认重置 Passkey": "Confirm Passkey Reset",
"确认重置两步验证": "Confirm Two-Factor Reset",
"此操作将解绑用户当前的 Passkey,下次登录需要重新注册。": "This will detach the user's current Passkey. They will need to register again on next login.",
"此操作将禁用该用户当前的两步验证配置,下次登录将不再强制输入验证码,直到用户重新启用。": "This will disable the user's current two-factor setup. No verification code will be required until they enable it again.",
"目标用户:{{username}}": "Target user: {{username}}",
"Passkey 已重置": "Passkey has been reset",
"二步验证已重置": "Two-factor authentication has been reset",
"配置 Passkey": "Configure Passkey",
"用以支持基于 WebAuthn 的无密码登录注册": "Support WebAuthn-based passwordless login and registration",
"Passkey 是基于 WebAuthn 标准的无密码身份验证方法,支持指纹、面容、硬件密钥等认证方式": "Passkey is a passwordless authentication method based on WebAuthn standard, supporting fingerprint, face recognition, hardware keys and other authentication methods",
"服务显示名称": "Service Display Name",
"默认使用系统名称": "Default uses system name",
"用户注册时看到的网站名称,比如'我的网站'": "Website name users see during registration, e.g. 'My Website'",
"网站域名标识": "Website Domain ID",
"例如:example.com": "e.g.: example.com",
"留空自动使用当前域名": "Leave blank to auto-use current domain",
"安全验证级别": "Security Verification Level",
"是否要求指纹/面容等生物识别": "Whether to require fingerprint/face recognition",
"preferred": "preferred",
"required": "required",
"discouraged": "discouraged",
"推荐:用户可以选择是否使用指纹等验证": "Recommended: Users can choose whether to use fingerprint verification",
"设备类型偏好": "Device Type Preference",
"选择支持的认证设备类型": "Choose supported authentication device types",
"platform": "platform",
"cross-platform": "cross-platform",
"本设备:手机指纹/面容,外接:USB安全密钥": "Built-in: phone fingerprint/face, External: USB security key",
"允许不安全的 Origin(HTTP)": "Allow insecure Origin (HTTP)",
"仅用于开发环境,生产环境应使用 HTTPS": "For development only, use HTTPS in production",
"允许的 Origins": "Allowed Origins",
"留空将自动使用服务器地址,多个 Origin 用于支持多域名部署": "Leave blank to auto-use server address, multiple Origins for multi-domain deployment",
"输入 Origin 后回车,如:https://example.com": "Enter Origin and press Enter, e.g.: https://example.com",
"保存 Passkey 设置": "Save Passkey Settings"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Add missing translations used by the new modal and hook.
SecureVerificationModal/useSecureVerification introduce several t(...) strings not present in en.json. Without these, English locale will show Chinese. Please add:

   "黑名单": "Blacklist",
+  "需要安全验证": "Security verification required",
+  "您需要先启用两步验证或 Passkey 才能查看敏感信息。": "You need to enable Two‑Factor Authentication or Passkey to view sensitive information.",
+  "请前往个人设置 → 安全设置进行配置。": "Please go to Personal Settings → Security Settings to configure.",
+  "使用 Passkey 验证": "Verify with Passkey",
+  "点击下方按钮,使用您的生物特征或安全密钥进行验证": "Click the button below to verify using your biometrics or security key",
+  "验证中...": "Verifying...",
+  "验证 Passkey": "Verify Passkey",
+  "两步验证": "Two‑Factor Authentication",
+  "为了保护账户安全,请验证您的身份。": "To protect your account, please verify your identity.",
+  "您需要先启用两步验证或 Passkey 才能执行此操作": "You need to enable Two‑Factor Authentication or Passkey before performing this action",
   "Passkey 登录": "Passkey Sign-in",

Optional wording tweak:

  • "备份支持" → "Backup capability" (current "Supported" reads like a state rather than capability).
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"黑名单": "Blacklist",
"Passkey 登录": "Passkey Sign-in",
"已启用 Passkey,无需密码即可登录": "Passkey enabled. Passwordless login available.",
"使用 Passkey 实现免密且更安全的登录体验": "Use Passkey for a passwordless and more secure login experience.",
"最后使用时间": "Last used time",
"备份支持": "Backup support",
"支持备份": "Supported",
"不支持": "Not supported",
"备份状态": "Backup state",
"已备份": "Backed up",
"未备份": "Not backed up",
"当前设备不支持 Passkey": "Passkey is not supported on this device",
"注册 Passkey": "Register Passkey",
"解绑 Passkey": "Remove Passkey",
"Passkey 注册成功": "Passkey registration successful",
"Passkey 注册失败,请重试": "Passkey registration failed. Please try again.",
"已取消 Passkey 注册": "Passkey registration cancelled",
"Passkey 已解绑": "Passkey removed",
"操作失败,请重试": "Operation failed, please retry",
"重置 Passkey": "Reset Passkey",
"重置 2FA": "Reset 2FA",
"确认重置 Passkey": "Confirm Passkey Reset",
"确认重置两步验证": "Confirm Two-Factor Reset",
"此操作将解绑用户当前的 Passkey,下次登录需要重新注册。": "This will detach the user's current Passkey. They will need to register again on next login.",
"此操作将禁用该用户当前的两步验证配置,下次登录将不再强制输入验证码,直到用户重新启用。": "This will disable the user's current two-factor setup. No verification code will be required until they enable it again.",
"目标用户:{{username}}": "Target user: {{username}}",
"Passkey 已重置": "Passkey has been reset",
"二步验证已重置": "Two-factor authentication has been reset",
"配置 Passkey": "Configure Passkey",
"用以支持基于 WebAuthn 的无密码登录注册": "Support WebAuthn-based passwordless login and registration",
"Passkey 是基于 WebAuthn 标准的无密码身份验证方法,支持指纹、面容、硬件密钥等认证方式": "Passkey is a passwordless authentication method based on WebAuthn standard, supporting fingerprint, face recognition, hardware keys and other authentication methods",
"服务显示名称": "Service Display Name",
"默认使用系统名称": "Default uses system name",
"用户注册时看到的网站名称,比如'我的网站'": "Website name users see during registration, e.g. 'My Website'",
"网站域名标识": "Website Domain ID",
"例如:example.com": "e.g.: example.com",
"留空自动使用当前域名": "Leave blank to auto-use current domain",
"安全验证级别": "Security Verification Level",
"是否要求指纹/面容等生物识别": "Whether to require fingerprint/face recognition",
"preferred": "preferred",
"required": "required",
"discouraged": "discouraged",
"推荐:用户可以选择是否使用指纹等验证": "Recommended: Users can choose whether to use fingerprint verification",
"设备类型偏好": "Device Type Preference",
"选择支持的认证设备类型": "Choose supported authentication device types",
"platform": "platform",
"cross-platform": "cross-platform",
"本设备:手机指纹/面容,外接:USB安全密钥": "Built-in: phone fingerprint/face, External: USB security key",
"允许不安全的 Origin(HTTP)": "Allow insecure Origin (HTTP)",
"仅用于开发环境,生产环境应使用 HTTPS": "For development only, use HTTPS in production",
"允许的 Origins": "Allowed Origins",
"留空将自动使用服务器地址,多个 Origin 用于支持多域名部署": "Leave blank to auto-use server address, multiple Origins for multi-domain deployment",
"输入 Origin 后回车,如:https://example.com": "Enter Origin and press Enter, e.g.: https://example.com",
"保存 Passkey 设置": "Save Passkey Settings"
"黑名单": "Blacklist",
"需要安全验证": "Security verification required",
"您需要先启用两步验证或 Passkey 才能查看敏感信息。": "You need to enable Two-Factor Authentication or Passkey to view sensitive information.",
"请前往个人设置 → 安全设置进行配置。": "Please go to Personal Settings → Security Settings to configure.",
"使用 Passkey 验证": "Verify with Passkey",
"点击下方按钮,使用您的生物特征或安全密钥进行验证": "Click the button below to verify using your biometrics or security key",
"验证中...": "Verifying...",
"验证 Passkey": "Verify Passkey",
"两步验证": "Two-Factor Authentication",
"为了保护账户安全,请验证您的身份。": "To protect your account, please verify your identity.",
"您需要先启用两步验证或 Passkey 才能执行此操作": "You need to enable Two-Factor Authentication or Passkey before performing this action",
"Passkey 登录": "Passkey Sign-in",

Comment on lines +48 to +52
const result = {
has2FA: twoFAResponse.success && twoFAResponse.data?.enabled === true,
hasPasskey: passkeyResponse.success && (passkeyResponse.data?.enabled === true || passkeyResponse.data?.status === 'enabled' || passkeyResponse.data !== null),
passkeySupported
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Incorrect hasPasskey detection can show Passkey as available when it is not

You treat any non-null data as enabled. This will mark users without a bound passkey as having one.

-      const result = {
-        has2FA: twoFAResponse.success && twoFAResponse.data?.enabled === true,
-        hasPasskey: passkeyResponse.success && (passkeyResponse.data?.enabled === true || passkeyResponse.data?.status === 'enabled' || passkeyResponse.data !== null),
-        passkeySupported
-      };
+      const result = {
+        has2FA: twoFAResponse.success && twoFAResponse.data?.enabled === true,
+        hasPasskey:
+          passkeyResponse.success &&
+          (passkeyResponse.data?.enabled === true || passkeyResponse.data?.status === 'enabled'),
+        passkeySupported
+      };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const result = {
has2FA: twoFAResponse.success && twoFAResponse.data?.enabled === true,
hasPasskey: passkeyResponse.success && (passkeyResponse.data?.enabled === true || passkeyResponse.data?.status === 'enabled' || passkeyResponse.data !== null),
passkeySupported
};
const result = {
has2FA: twoFAResponse.success && twoFAResponse.data?.enabled === true,
hasPasskey:
passkeyResponse.success &&
(passkeyResponse.data?.enabled === true || passkeyResponse.data?.status === 'enabled'),
passkeySupported
};
🤖 Prompt for AI Agents
In web/src/services/secureVerification.js around lines 48–52, the hasPasskey
logic incorrectly treats any non-null passkeyResponse.data as enabled; change
the condition to only consider explicit indicators (e.g.
passkeyResponse.data?.enabled === true OR passkeyResponse.data?.status ===
'enabled' OR a definitive bound/key count like
Array.isArray(passkeyResponse.data.keys) && passkeyResponse.data.keys.length >
0) and remove the broad passkeyResponse.data !== null check so users without a
bound passkey are not marked as having one.

Comment thread web/src/services/secureVerification.js Outdated
Comment on lines +167 to +179
custom: (url, method = 'POST', extraData = {}) => async (verificationData) => {
const data = { ...extraData, ...verificationData };

switch (method.toUpperCase()) {
case 'GET':
return await API.get(url, { params: data });
case 'POST':
return await API.post(url, data);
case 'PUT':
return await API.put(url, data);
case 'DELETE':
return await API.delete(url, { data });
default:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Avoid sending verification secrets via GET

Merging verificationData (e.g., 2FA codes) into GET query params risks leakage via logs, caches, and referrers.

   custom: (url, method = 'POST', extraData = {}) => async (verificationData) => {
-    const data = { ...extraData, ...verificationData };
+    const data = { ...extraData, ...verificationData };
+    if (method.toUpperCase() === 'GET' && (data.code || data.backupCode)) {
+      throw new Error('出于安全考虑,GET 请求不支持携带验证码参数');
+    }
     
     switch (method.toUpperCase()) {
       case 'GET':
         return await API.get(url, { params: data });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
custom: (url, method = 'POST', extraData = {}) => async (verificationData) => {
const data = { ...extraData, ...verificationData };
switch (method.toUpperCase()) {
case 'GET':
return await API.get(url, { params: data });
case 'POST':
return await API.post(url, data);
case 'PUT':
return await API.put(url, data);
case 'DELETE':
return await API.delete(url, { data });
default:
custom: (url, method = 'POST', extraData = {}) => async (verificationData) => {
const data = { ...extraData, ...verificationData };
if (method.toUpperCase() === 'GET' && (data.code || data.backupCode)) {
throw new Error('出于安全考虑,GET 请求不支持携带验证码参数');
}
switch (method.toUpperCase()) {
case 'GET':
return await API.get(url, { params: data });
case 'POST':
return await API.post(url, data);
case 'PUT':
return await API.put(url, data);
case 'DELETE':
return await API.delete(url, { data });
default:
// …
🤖 Prompt for AI Agents
In web/src/services/secureVerification.js around lines 167 to 179, the custom
helper merges verificationData into query params for GET requests which can leak
secrets (2FA codes, tokens) via logs, caches and referrers; update the function
to prevent sending sensitive verification fields in GET: detect when method is
GET and if verificationData contains common secret keys (e.g., code, token, otp,
secret, verificationCode) then throw an error (or automatically switch to POST)
and instruct callers to use POST/PUT with body or include non-sensitive
identifiers only; ensure the check runs before merging data and keep existing
behavior for non-sensitive GETs.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
web/src/services/secureVerification.js (2)

43-46: Gate and redact debug logs.

Console-dumping full responses risks leaking sensitive info and adds noise in prod. Wrap in a NODE_ENV guard and log only necessary fields.

-      console.log('=== DEBUGGING VERIFICATION METHODS ===');
-      console.log('2FA Response:', JSON.stringify(twoFAResponse, null, 2));
-      console.log('Passkey Response:', JSON.stringify(passkeyResponse, null, 2));
+      if (process.env.NODE_ENV !== 'production') {
+        console.log('=== DEBUGGING VERIFICATION METHODS ===');
+        console.log('2FA success:', twoFAResponse?.data?.success);
+        console.log('Passkey success:', passkeyResponse?.data?.success);
+      }
@@
-      console.log('has2FA calculation:', {
+      if (process.env.NODE_ENV !== 'production') console.log('has2FA calculation:', {
         success: twoFAResponse.data?.success,
         dataExists: !!twoFAResponse.data?.data,
         enabled: twoFAResponse.data?.data?.enabled,
         result: has2FA
       });
-      
-      console.log('hasPasskey calculation:', {
+      if (process.env.NODE_ENV !== 'production') console.log('hasPasskey calculation:', {
         success: passkeyResponse.data?.success,
         dataExists: !!passkeyResponse.data?.data,
         enabled: passkeyResponse.data?.data?.enabled,
         result: hasPasskey
       });

Also applies to: 50-63


48-49: Confirm passkey “enabled” shape; add tolerant check if needed.

If backend sometimes returns status: 'enabled' (or a keys count) instead of boolean enabled, current detection under-reports availability. Consider:

-      const hasPasskey = passkeyResponse.data?.success && passkeyResponse.data?.data?.enabled === true;
+      const hasPasskey = passkeyResponse.data?.success && (
+        passkeyResponse.data?.data?.enabled === true ||
+        passkeyResponse.data?.data?.status === 'enabled'
+        // || (Array.isArray(passkeyResponse.data?.data?.keys) && passkeyResponse.data.data.keys.length > 0)
+      );

Please confirm the exact API payload contract before changing.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dcf4336 and 84cdd24.

📒 Files selected for processing (3)
  • web/src/components/table/channels/modals/EditChannelModal.jsx (6 hunks)
  • web/src/hooks/common/useSecureVerification.jsx (1 hunks)
  • web/src/services/secureVerification.js (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
web/src/components/table/channels/modals/EditChannelModal.jsx (5)
web/src/hooks/common/useSecureVerification.jsx (10)
  • useSecureVerification (33-219)
  • useSecureVerification (33-219)
  • startVerification (83-116)
  • isModalVisible (49-49)
  • verificationMethods (42-46)
  • verificationState (52-57)
  • executeVerification (119-154)
  • cancelVerification (167-169)
  • setVerificationCode (157-159)
  • switchVerificationMethod (162-164)
web/src/helpers/utils.jsx (2)
  • showSuccess (157-159)
  • showError (122-151)
web/src/services/secureVerification.js (2)
  • createApiCalls (167-198)
  • createApiCalls (167-198)
web/src/components/common/modals/SecureVerificationModal.jsx (3)
  • SecureVerificationModal (38-269)
  • verificationMethods (51-51)
  • verificationState (52-52)
web/src/components/common/ui/ChannelKeyDisplay.jsx (1)
  • ChannelKeyDisplay (86-278)
web/src/hooks/common/useSecureVerification.jsx (4)
web/src/components/table/channels/modals/EditChannelModal.jsx (1)
  • useSecureVerification (205-225)
web/src/components/common/examples/ChannelKeyViewExample.jsx (1)
  • useSecureVerification (38-56)
web/src/services/secureVerification.js (1)
  • SecureVerificationService (30-162)
web/src/helpers/utils.jsx (2)
  • showError (122-151)
  • showSuccess (157-159)
web/src/services/secureVerification.js (1)
web/src/helpers/passkey.js (5)
  • isPasskeySupported (116-136)
  • publicKey (33-40)
  • publicKey (61-64)
  • prepareCredentialRequestOptions (56-74)
  • buildAssertionResult (96-114)
🔇 Additional comments (4)
web/src/hooks/common/useSecureVerification.jsx (1)

96-104: Validate preferredMethod against availability before selecting.

Avoid picking an unusable tab (e.g., 'passkey' when unsupported), which can desync UI state with Tabs.

-    // 设置默认验证方式
-    let defaultMethod = preferredMethod;
-    if (!defaultMethod) {
+    // 设置默认验证方式
+    let defaultMethod = preferredMethod;
+    // 仅当可用时才保留首选方式
+    const preferredUsable =
+      (preferredMethod === 'passkey' && methods.hasPasskey && methods.passkeySupported) ||
+      (preferredMethod === '2fa' && methods.has2FA);
+    if (!preferredUsable) {
+      defaultMethod = undefined;
+    }
+    if (!defaultMethod) {
       if (methods.hasPasskey && methods.passkeySupported) {
         defaultMethod = 'passkey';
       } else if (methods.has2FA) {
         defaultMethod = '2fa';
       }
     }
web/src/components/table/channels/modals/EditChannelModal.jsx (2)

607-621: Rename to generic handler, guard channelId, and keep logs dev-only.

The flow is no longer 2FA-specific. Also add a defensive check for falsy channelId. Avoid raw console.error in prod.

-  // 显示安全验证模态框并开始验证流程
-  const handleShow2FAModal = async () => {
+  // 显示安全验证模态框并开始验证流程
+  const handleSecureVerification = async () => {
     try {
-      const apiCall = createApiCalls.viewChannelKey(channelId);
-      
+      if (!channelId) {
+        showError(t('渠道未找到,请刷新页面后重试。'));
+        return;
+      }
+      const apiCall = createApiCalls.viewChannelKey(channelId);
       await startVerification(apiCall, {
         title: t('查看渠道密钥'),
         description: t('为了保护账户安全,请验证您的身份。'),
         preferredMethod: 'passkey', // 优先使用 Passkey
       });
     } catch (error) {
-      console.error('Failed to start verification:', error);
-      showError(error.message || t('启动验证失败'));
+      if (process.env.NODE_ENV !== 'production') console.error('Failed to start verification:', error);
+      showError(error?.message || t('启动验证失败'));
     }
   };

1399-1407: Update call sites to use the renamed handler.

-                              onClick={handleShow2FAModal}
+                              onClick={handleSecureVerification}
-                                      onClick={handleShow2FAModal}
+                                      onClick={handleSecureVerification}
-                                  onClick={handleShow2FAModal}
+                                  onClick={handleSecureVerification}

Also applies to: 1517-1525, 1587-1596

web/src/services/secureVerification.js (1)

182-197: Do not send secrets via GET (2FA codes leak in logs/caches).

Merging verification data into query params allows OTP/backup codes in URLs. Block secrets on GET (throw or switch to POST).

-  custom: (url, method = 'POST', extraData = {}) => async (verificationData) => {
-    const data = { ...extraData, ...verificationData };
-    
-    switch (method.toUpperCase()) {
+  custom: (url, method = 'POST', extraData = {}) => async (verificationData) => {
+    const upper = method.toUpperCase();
+    const data = { ...extraData, ...verificationData };
+    if (upper === 'GET') {
+      const secretKeys = ['code', 'backupCode', 'otp', 'token', 'verificationCode', 'secret'];
+      const hasSecret = secretKeys.some((k) => k in (verificationData || {}));
+      if (hasSecret) {
+        throw new Error('出于安全考虑,GET 请求不支持携带验证码参数');
+      }
+    }
+    switch (upper) {
       case 'GET':
         return await API.get(url, { params: data });
       case 'POST':
         return await API.post(url, data);
       case 'PUT':
         return await API.put(url, data);
       case 'DELETE':
         return await API.delete(url, { data });
       default:
         throw new Error(`不支持的HTTP方法: ${method}`);
     }
   }

Comment thread web/src/services/secureVerification.js Resolved
# Conflicts:
#	web/src/components/settings/PersonalSetting.jsx
#	web/src/i18n/locales/en.json
#	web/src/i18n/locales/zh.json

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

♻️ Duplicate comments (3)
controller/secure_verification.go (1)

16-21: Constants duplicated - see middleware review.

This is the same duplication issue flagged in the middleware file review.

web/src/hooks/common/useSecureVerification.jsx (1)

84-117: Validate preferredMethod against availability.

The past review comment correctly identified that preferredMethod is not validated against available methods. If the caller passes preferredMethod: 'passkey' but the user only has 2FA enabled, the hook will still select passkey as the method, leading to a broken flow.

Apply the validation suggested in the past review:

   const startVerification = useCallback(async (apiCall, options = {}) => {
     const { preferredMethod, title, description } = options;
-    
+
     // 检查验证方式
     const methods = await checkVerificationMethods();
-    
+
     if (!methods.has2FA && !methods.hasPasskey) {
       const errorMessage = t('您需要先启用两步验证或 Passkey 才能执行此操作');
       showError(errorMessage);
       onError?.(new Error(errorMessage));
       return false;
     }
 
     // 设置默认验证方式
     let defaultMethod = preferredMethod;
+    // Validate preferredMethod against availability
+    const preferredUsable =
+      (preferredMethod === 'passkey' && methods.hasPasskey && methods.passkeySupported) ||
+      (preferredMethod === '2fa' && methods.has2FA);
+    if (!preferredUsable) {
+      defaultMethod = undefined;
+    }
     if (!defaultMethod) {
       if (methods.hasPasskey && methods.passkeySupported) {
         defaultMethod = 'passkey';
       } else if (methods.has2FA) {
         defaultMethod = '2fa';
       }
     }
 
     setVerificationState(prev => ({
       ...prev,
       method: defaultMethod,
       apiCall,
       title,
       description
     }));
     setIsModalVisible(true);
-    
+
     return true;
   }, [checkVerificationMethods, onError, t]);
web/src/components/table/channels/modals/EditChannelModal.jsx (1)

616-640: Unresolved issues from previous review: rename handler, add channelId guard, remove console noise.

This handler still has the issues flagged in the previous review comment:

  1. Name is 2FA-specific but the flow is now generic verification. Rename to handleSecureVerification or handleViewChannelKey.
  2. Missing defensive guard: if channelId is falsy, createApiCalls.viewChannelKey(channelId) will be called with an invalid ID. Add an early return with showError.
  3. Console.error at line 637: production noise—remove or wrap in a dev-only guard.

Apply this diff to address all three issues:

-  // 查看渠道密钥(透明验证)
-  const handleShow2FAModal = async () => {
+  // 查看渠道密钥(透明验证)
+  const handleViewChannelKey = async () => {
     try {
+      if (!channelId) {
+        showError(t('渠道未找到,请刷新页面后重试。'));
+        return;
+      }
       // 使用 withVerification 包装,会自动处理需要验证的情况
       const result = await withVerification(
         createApiCalls.viewChannelKey(channelId),
         {
           title: t('查看渠道密钥'),
           description: t('为了保护账户安全,请验证您的身份。'),
           preferredMethod: 'passkey', // 优先使用 Passkey
         }
       );

       // 如果直接返回了结果(已验证),显示密钥
       if (result && result.success && result.data?.key) {
         showSuccess(t('密钥获取成功'));
         setKeyDisplayState({
           showModal: true,
           keyData: result.data.key,
         });
       }
     } catch (error) {
-      console.error('Failed to view channel key:', error);
       showError(error.message || t('获取密钥失败'));
     }
   };

Then update all call sites at lines 1422, 1540, and 1611:

- onClick={handleShow2FAModal}
+ onClick={handleViewChannelKey}
🧹 Nitpick comments (2)
web/src/components/settings/SystemSetting.jsx (1)

613-650: Consider optimizing the origins submission logic.

The implementation correctly follows the pattern of other submit functions in this file. However, the comment on line 641 states that origins are always submitted because users might clear them, but the function already checks for changes in other fields.

For consistency with the change-detection pattern used throughout this file, consider also checking if passkeyOrigins has changed:

-    // Origins总是提交,因为它们可能会被用户清空
-    options.push({
-      key: 'passkey.origins',
-      value: JSON.stringify(Array.isArray(passkeyOrigins) ? passkeyOrigins : []),
-    });
+    // Check if origins have changed (including clearing to empty array)
+    const originsStringified = JSON.stringify(Array.isArray(passkeyOrigins) ? passkeyOrigins : []);
+    const originOriginsStringified = JSON.stringify(originInputs['passkey.origins'] || []);
+    if (originsStringified !== originOriginsStringified) {
+      options.push({
+        key: 'passkey.origins',
+        value: originsStringified,
+      });
+    }

This avoids unnecessary API calls when origins haven't changed while still handling the empty array case correctly.

web/src/services/secureVerification.js (1)

44-63: Remove verbose debug logs before production.

Lines 44–63 contain extensive console.log statements that will clutter production logs and expose internal state.

Wrap them in a development guard or remove them:

-      console.log('=== DEBUGGING VERIFICATION METHODS ===');
-      console.log('2FA Response:', JSON.stringify(twoFAResponse, null, 2));
-      console.log('Passkey Response:', JSON.stringify(passkeyResponse, null, 2));
-      
       const has2FA = twoFAResponse.data?.success && twoFAResponse.data?.data?.enabled === true;
       const hasPasskey = passkeyResponse.data?.success && passkeyResponse.data?.data?.enabled === true;
-      
-      console.log('has2FA calculation:', {
-        success: twoFAResponse.data?.success,
-        dataExists: !!twoFAResponse.data?.data,
-        enabled: twoFAResponse.data?.data?.enabled,
-        result: has2FA
-      });
-      
-      console.log('hasPasskey calculation:', {
-        success: passkeyResponse.data?.success,
-        dataExists: !!passkeyResponse.data?.data,
-        enabled: passkeyResponse.data?.data?.enabled,
-        result: hasPasskey
-      });

Or guard them:

if (process.env.NODE_ENV === 'development') {
  console.log('2FA Response:', twoFAResponse);
  console.log('Passkey Response:', passkeyResponse);
}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 84cdd24 and e8425ad.

📒 Files selected for processing (12)
  • controller/channel.go (2 hunks)
  • controller/secure_verification.go (1 hunks)
  • middleware/secure_verification.go (1 hunks)
  • router/api-router.go (4 hunks)
  • web/src/components/common/modals/SecureVerificationModal.jsx (1 hunks)
  • web/src/components/settings/SystemSetting.jsx (6 hunks)
  • web/src/components/table/channels/modals/EditChannelModal.jsx (6 hunks)
  • web/src/helpers/secureApiCall.js (1 hunks)
  • web/src/hooks/common/useSecureVerification.jsx (1 hunks)
  • web/src/i18n/locales/en.json (3 hunks)
  • web/src/i18n/locales/zh.json (2 hunks)
  • web/src/services/secureVerification.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • web/src/i18n/locales/zh.json
  • web/src/i18n/locales/en.json
🧰 Additional context used
🧬 Code graph analysis (8)
controller/secure_verification.go (8)
common/gin.go (1)
  • ApiError (95-100)
model/twofa.go (1)
  • GetTwoFAByUserId (40-55)
model/passkey.go (2)
  • GetPasskeyByUserID (136-151)
  • UpsertPasskeyCredential (172-189)
model/log.go (1)
  • RecordLog (78-94)
setting/system_setting/passkey.go (1)
  • GetPasskeySettings (32-34)
service/passkey/service.go (1)
  • BuildWebAuthn (26-80)
service/passkey/user.go (1)
  • NewWebAuthnUser (18-20)
service/passkey/session.go (1)
  • PopSessionData (28-50)
router/api-router.go (6)
middleware/auth.go (1)
  • UserAuth (156-160)
controller/secure_verification.go (2)
  • UniversalVerify (35-133)
  • GetVerificationStatus (136-195)
controller/passkey.go (8)
  • PasskeyLoginBegin (208-241)
  • PasskeyLoginFinish (243-332)
  • PasskeyRegisterBegin (21-79)
  • PasskeyRegisterFinish (81-142)
  • PasskeyVerifyBegin (370-422)
  • PasskeyVerifyFinish (424-482)
  • PasskeyDelete (144-163)
  • AdminResetPasskey (334-368)
middleware/disable-cache.go (1)
  • DisableCache (5-12)
middleware/secure_verification.go (1)
  • SecureVerificationRequired (21-80)
controller/channel.go (1)
  • GetChannelKey (389-420)
middleware/secure_verification.go (1)
controller/secure_verification.go (2)
  • SecureVerificationSessionKey (18-18)
  • SecureVerificationTimeout (20-20)
web/src/components/common/modals/SecureVerificationModal.jsx (1)
web/src/hooks/common/useSecureVerification.jsx (2)
  • verificationMethods (43-47)
  • verificationState (53-58)
web/src/components/settings/SystemSetting.jsx (1)
web/src/helpers/passkey.js (2)
  • options (29-29)
  • options (57-57)
web/src/components/table/channels/modals/EditChannelModal.jsx (5)
web/src/hooks/common/useSecureVerification.jsx (10)
  • useSecureVerification (34-246)
  • useSecureVerification (34-246)
  • withVerification (203-218)
  • isModalVisible (50-50)
  • verificationMethods (43-47)
  • verificationState (53-58)
  • executeVerification (120-156)
  • cancelVerification (169-171)
  • setVerificationCode (159-161)
  • switchVerificationMethod (164-166)
web/src/helpers/utils.jsx (2)
  • showSuccess (157-159)
  • showError (122-151)
web/src/services/secureVerification.js (2)
  • createApiCalls (177-217)
  • createApiCalls (177-217)
web/src/components/common/modals/SecureVerificationModal.jsx (3)
  • SecureVerificationModal (38-283)
  • verificationMethods (53-53)
  • verificationState (54-54)
web/src/components/common/ui/ChannelKeyDisplay.jsx (1)
  • ChannelKeyDisplay (86-278)
web/src/services/secureVerification.js (1)
web/src/helpers/passkey.js (5)
  • isPasskeySupported (116-136)
  • publicKey (33-40)
  • publicKey (61-64)
  • prepareCredentialRequestOptions (56-74)
  • buildAssertionResult (96-114)
web/src/hooks/common/useSecureVerification.jsx (5)
web/src/components/table/channels/modals/EditChannelModal.jsx (1)
  • useSecureVerification (205-233)
web/src/components/common/examples/ChannelKeyViewExample.jsx (1)
  • useSecureVerification (38-56)
web/src/services/secureVerification.js (1)
  • SecureVerificationService (31-172)
web/src/helpers/utils.jsx (2)
  • showError (122-151)
  • showSuccess (157-159)
web/src/helpers/secureApiCall.js (2)
  • error (33-33)
  • isVerificationRequiredError (30-47)
🔇 Additional comments (30)
web/src/components/settings/SystemSetting.jsx (5)

33-33: LGTM!

The Select component import is correctly added and used in the Passkey configuration section for dropdown fields.


81-87: LGTM!

Passkey state initialization follows the existing pattern and includes sensible defaults. The user_verification default of 'preferred' aligns with WebAuthn best practices.


125-125: LGTM!

The passkeyOrigins state is properly initialized as an array for managing multiple allowed origins.


185-206: LGTM!

The option parsing logic for Passkey fields is robust and follows established patterns:

  • Booleans are properly parsed with toBoolean
  • Origins array parsing includes proper error handling with safe fallback
  • String fields are ensured to be non-null/undefined (line 205)

The defensive programming approach with try-catch and type validation is appropriate for user-configurable settings.


1027-1145: LGTM!

The Passkey configuration UI is well-structured and follows the established patterns in this file:

  • Consistent Card/Form.Section layout with other settings blocks
  • Helpful Banner providing context about WebAuthn
  • Proper state management with two-way binding between passkeyOrigins and inputs
  • Select options align with WebAuthn specification values
  • Descriptive help text and translations throughout

The UI provides a clear, user-friendly interface for configuring Passkey authentication.

router/api-router.go (5)

43-45: LGTM! Universal verification routes are properly secured.

The universal verification routes are correctly protected with UserAuth() and CriticalRateLimit() middleware, ensuring only authenticated users can access verification endpoints with appropriate rate limiting.


52-53: LGTM! Passkey login routes are properly configured.

The passkey login begin/finish endpoints are appropriately protected with CriticalRateLimit() middleware to prevent abuse, and they're correctly placed in the public user route group since they're used for authentication.


68-73: LGTM! Passkey management routes are well-structured.

All passkey management routes are correctly placed within the UserAuth() protected route group, ensuring only authenticated users can register, verify, or delete their passkeys. The route organization follows REST conventions.


102-102: LGTM! Admin passkey reset is properly secured.

The admin passkey reset endpoint is correctly placed within the AdminAuth() protected route group, ensuring only administrators can reset user passkeys.


131-131: LGTM! The insecure endpoint has been removed and replaced with proper middleware protection.

The previous security vulnerability (the insecure /passkey route mentioned in past reviews) has been addressed. The current implementation correctly uses SecureVerificationRequired() middleware in addition to existing protections, ensuring users must complete a fresh verification (2FA or Passkey) before accessing channel keys.

controller/channel.go (1)

387-420: LGTM! Clean separation of concerns with middleware-based verification.

The refactoring properly delegates security verification to the SecureVerificationRequired middleware, simplifying the handler logic. The updated success message ("获取成功") correctly reflects that the handler is now focused solely on key retrieval rather than performing verification.

The approach is sound:

  • Verification is enforced consistently at the middleware layer
  • Handler logic is simplified and focused on a single responsibility
  • The session-based verification check in the middleware (with timeout) provides appropriate step-up authentication
web/src/helpers/secureApiCall.js (2)

30-47: LGTM! Proper error detection for verification flows.

The isVerificationRequiredError function correctly identifies verification-required scenarios by checking for 403 status and matching against the specific error codes (VERIFICATION_REQUIRED, VERIFICATION_EXPIRED, VERIFICATION_INVALID) returned by the backend middleware.


54-62: LGTM! Safe error info extraction with defensive programming.

The extractVerificationInfo function properly uses optional chaining to safely extract error details and provides sensible defaults. The returned object structure is clear and consistent.

web/src/components/common/modals/SecureVerificationModal.jsx (4)

65-72: LGTM! Proper keyboard accessibility.

The keyboard handler correctly implements:

  • Enter key triggers verification (only when code is provided and not loading for 2FA)
  • Escape key cancels the modal (only when not loading)

This provides good keyboard-only navigation support.


75-114: LGTM! Clear messaging when no verification methods are available.

The fallback view provides clear, actionable guidance to users who need to enable security options before they can view sensitive information. The warning icon and instructions are user-friendly.


155-214: LGTM! Well-structured 2FA tab with good UX.

The 2FA tab implementation includes:

  • Clear input field with visual prefix icon
  • Proper input constraints (maxLength: 8 for backup codes)
  • AutoFocus when the tab is active
  • Loading and disabled states properly managed
  • Helpful hint text about code sources
  • Clean action buttons layout

216-278: LGTM! Clear and accessible Passkey verification UI.

The Passkey tab provides:

  • Visual icon to indicate authentication method
  • Clear instructions for users
  • Proper loading state handling
  • Consistent button layout with the 2FA tab
  • Only renders when both passkey is enabled AND browser supports it
middleware/secure_verification.go (2)

21-80: LGTM with minor observation.

The middleware correctly enforces authentication, validates session data type, checks expiration, and provides clear error codes. The progressive validation approach (login → session existence → type → expiration) is well-structured.

Minor note: Line 24 uses c.GetInt("id") which returns 0 if the key doesn't exist or has type mismatch. The comparison userId == 0 on line 25 is correct but could be userId <= 0 to be more defensive against negative IDs (though this is unlikely given the context).


85-123: LGTM!

The optional middleware correctly implements non-blocking verification checks with appropriate context flag setting. The logic mirrors SecureVerificationRequired but sets context flags instead of aborting, which is the correct approach for optional checks.

controller/secure_verification.go (2)

136-195: LGTM!

The status check correctly handles missing sessions, type mismatches, and expiration. The response structure is consistent, and cleanup of expired sessions is appropriate.


234-313: LGTM with observation.

The Passkey verification flow correctly integrates WebAuthn validation, credential updates, session management, and logging. The flow properly validates user status, credential existence, and WebAuthn assertion.

One observation: Line 293 updates LastUsedAt and calls UpsertPasskeyCredential. The Upsert operation (based on snippet from model/passkey.go) does a hard delete + create, which is more expensive than a simple update for just LastUsedAt. Consider adding a lighter UpdateLastUsed method if this becomes a performance concern.

web/src/hooks/common/useSecureVerification.jsx (2)

203-218: LGTM!

The withVerification wrapper correctly implements automatic verification flow when an API returns a verification-required error. The error detection via isVerificationRequiredError and the transparent retry mechanism are well-designed.


220-246: LGTM!

The return object provides a comprehensive API with clear separation between state, methods, helpers, and convenience properties. The exported surface is well-documented and intuitive.

web/src/services/secureVerification.js (4)

87-103: LGTM!

The 2FA verification logic is correct: validates code presence, trims it, posts to the verification endpoint, and handles success/error appropriately.


109-154: LGTM!

The Passkey verification flow is correct: initiates verification, handles WebAuthn credential retrieval, completes verification, and sets the session via the /api/verify endpoint. Response shape handling and error handling for common WebAuthn errors are appropriate.


162-171: LGTM!

The verify dispatcher correctly routes to the appropriate verification method based on the method parameter.


177-216: LGTM!

The createApiCalls factory provides appropriate helpers for API calls. The custom helper no longer merges verification secrets into GET query params as the new architecture handles verification via middleware before these calls execute, resolving the past review concern.

web/src/components/table/channels/modals/EditChannelModal.jsx (3)

198-241: LGTM!

The keyDisplayState structure and reset logic are clean and correctly implemented.


2501-2511: LGTM!

The SecureVerificationModal is correctly wired with props from the useSecureVerification hook. All handlers and state are properly connected.


2514-2552: LGTM!

The key display modal correctly uses keyDisplayState for visibility and data. Reset handlers are properly bound.

Comment on lines +35 to +133
func UniversalVerify(c *gin.Context) {
userId := c.GetInt("id")
if userId == 0 {
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"message": "未登录",
})
return
}

var req UniversalVerifyRequest
if err := c.ShouldBindJSON(&req); err != nil {
common.ApiError(c, fmt.Errorf("参数错误: %v", err))
return
}

// 获取用户信息
user := &model.User{Id: userId}
if err := user.FillUserById(); err != nil {
common.ApiError(c, fmt.Errorf("获取用户信息失败: %v", err))
return
}

if user.Status != common.UserStatusEnabled {
common.ApiError(c, fmt.Errorf("该用户已被禁用"))
return
}

// 检查用户的验证方式
twoFA, _ := model.GetTwoFAByUserId(userId)
has2FA := twoFA != nil && twoFA.IsEnabled

passkey, passkeyErr := model.GetPasskeyByUserID(userId)
hasPasskey := passkeyErr == nil && passkey != nil

if !has2FA && !hasPasskey {
common.ApiError(c, fmt.Errorf("用户未启用2FA或Passkey"))
return
}

// 根据验证方式进行验证
var verified bool
var verifyMethod string

switch req.Method {
case "2fa":
if !has2FA {
common.ApiError(c, fmt.Errorf("用户未启用2FA"))
return
}
if req.Code == "" {
common.ApiError(c, fmt.Errorf("验证码不能为空"))
return
}
verified = validateTwoFactorAuth(twoFA, req.Code)
verifyMethod = "2FA"

case "passkey":
if !hasPasskey {
common.ApiError(c, fmt.Errorf("用户未启用Passkey"))
return
}
// Passkey 验证需要先调用 PasskeyVerifyBegin 和 PasskeyVerifyFinish
// 这里只是验证 Passkey 验证流程是否已经完成
// 实际上,前端应该先调用这两个接口,然后再调用本接口
verified = true // Passkey 验证逻辑已在 PasskeyVerifyFinish 中完成
verifyMethod = "Passkey"

default:
common.ApiError(c, fmt.Errorf("不支持的验证方式: %s", req.Method))
return
}

if !verified {
common.ApiError(c, fmt.Errorf("验证失败,请检查验证码"))
return
}

// 验证成功,在 session 中记录时间戳
session := sessions.Default(c)
now := time.Now().Unix()
session.Set(SecureVerificationSessionKey, now)
if err := session.Save(); err != nil {
common.ApiError(c, fmt.Errorf("保存验证状态失败: %v", err))
return
}

// 记录日志
model.RecordLog(userId, model.LogTypeSystem, fmt.Sprintf("通用安全验证成功 (验证方式: %s)", verifyMethod))

c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "验证成功",
"data": gin.H{
"verified": true,
"expires_at": now + SecureVerificationTimeout,
},
})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Passkey verification logic is incomplete and misleading.

Lines 92-101 handle the "passkey" method case but simply set verified = true with a comment stating "Passkey 验证逻辑已在 PasskeyVerifyFinish 中完成" (Passkey verification logic completed in PasskeyVerifyFinish). However, this function doesn't actually verify that the Passkey flow was completed successfully—it blindly trusts the method and marks verification as passed.

This creates a security vulnerability: an attacker who has 2FA or Passkey enabled could call this API with method: "passkey" without actually completing the WebAuthn flow, and the session would be marked as verified.

You have two options to fix this:

Option 1 (Recommended): Remove the "passkey" case from UniversalVerify entirely, since Passkey verification should use the dedicated PasskeyVerifyForSecure endpoint which properly validates the WebAuthn flow:

 	switch req.Method {
 	case "2fa":
 		if !has2FA {
 			common.ApiError(c, fmt.Errorf("用户未启用2FA"))
 			return
 		}
 		if req.Code == "" {
 			common.ApiError(c, fmt.Errorf("验证码不能为空"))
 			return
 		}
 		verified = validateTwoFactorAuth(twoFA, req.Code)
 		verifyMethod = "2FA"
-
-	case "passkey":
-		if !hasPasskey {
-			common.ApiError(c, fmt.Errorf("用户未启用Passkey"))
-			return
-		}
-		// Passkey 验证需要先调用 PasskeyVerifyBegin 和 PasskeyVerifyFinish
-		// 这里只是验证 Passkey 验证流程是否已经完成
-		// 实际上,前端应该先调用这两个接口,然后再调用本接口
-		verified = true // Passkey 验证逻辑已在 PasskeyVerifyFinish 中完成
-		verifyMethod = "Passkey"

 	default:
 		common.ApiError(c, fmt.Errorf("不支持的验证方式: %s", req.Method))
 		return
 	}

Option 2: If you need to keep the unified API, verify that a Passkey verification session exists and was recently completed:

 	case "passkey":
 		if !hasPasskey {
 			common.ApiError(c, fmt.Errorf("用户未启用Passkey"))
 			return
 		}
-		// Passkey 验证需要先调用 PasskeyVerifyBegin 和 PasskeyVerifyFinish
-		// 这里只是验证 Passkey 验证流程是否已经完成
-		// 实际上,前端应该先调用这两个接口,然后再调用本接口
-		verified = true // Passkey 验证逻辑已在 PasskeyVerifyFinish 中完成
+		// Check if Passkey verification was recently completed
+		verified = CheckSecureVerification(c)
+		if !verified {
+			common.ApiError(c, fmt.Errorf("请先完成 Passkey 验证"))
+			return
+		}
 		verifyMethod = "Passkey"

Option 1 is recommended because it's clearer that Passkey verification follows a different flow.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func UniversalVerify(c *gin.Context) {
userId := c.GetInt("id")
if userId == 0 {
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"message": "未登录",
})
return
}
var req UniversalVerifyRequest
if err := c.ShouldBindJSON(&req); err != nil {
common.ApiError(c, fmt.Errorf("参数错误: %v", err))
return
}
// 获取用户信息
user := &model.User{Id: userId}
if err := user.FillUserById(); err != nil {
common.ApiError(c, fmt.Errorf("获取用户信息失败: %v", err))
return
}
if user.Status != common.UserStatusEnabled {
common.ApiError(c, fmt.Errorf("该用户已被禁用"))
return
}
// 检查用户的验证方式
twoFA, _ := model.GetTwoFAByUserId(userId)
has2FA := twoFA != nil && twoFA.IsEnabled
passkey, passkeyErr := model.GetPasskeyByUserID(userId)
hasPasskey := passkeyErr == nil && passkey != nil
if !has2FA && !hasPasskey {
common.ApiError(c, fmt.Errorf("用户未启用2FA或Passkey"))
return
}
// 根据验证方式进行验证
var verified bool
var verifyMethod string
switch req.Method {
case "2fa":
if !has2FA {
common.ApiError(c, fmt.Errorf("用户未启用2FA"))
return
}
if req.Code == "" {
common.ApiError(c, fmt.Errorf("验证码不能为空"))
return
}
verified = validateTwoFactorAuth(twoFA, req.Code)
verifyMethod = "2FA"
case "passkey":
if !hasPasskey {
common.ApiError(c, fmt.Errorf("用户未启用Passkey"))
return
}
// Passkey 验证需要先调用 PasskeyVerifyBegin 和 PasskeyVerifyFinish
// 这里只是验证 Passkey 验证流程是否已经完成
// 实际上,前端应该先调用这两个接口,然后再调用本接口
verified = true // Passkey 验证逻辑已在 PasskeyVerifyFinish 中完成
verifyMethod = "Passkey"
default:
common.ApiError(c, fmt.Errorf("不支持的验证方式: %s", req.Method))
return
}
if !verified {
common.ApiError(c, fmt.Errorf("验证失败,请检查验证码"))
return
}
// 验证成功,在 session 中记录时间戳
session := sessions.Default(c)
now := time.Now().Unix()
session.Set(SecureVerificationSessionKey, now)
if err := session.Save(); err != nil {
common.ApiError(c, fmt.Errorf("保存验证状态失败: %v", err))
return
}
// 记录日志
model.RecordLog(userId, model.LogTypeSystem, fmt.Sprintf("通用安全验证成功 (验证方式: %s)", verifyMethod))
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "验证成功",
"data": gin.H{
"verified": true,
"expires_at": now + SecureVerificationTimeout,
},
})
}
func UniversalVerify(c *gin.Context) {
userId := c.GetInt("id")
if userId == 0 {
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"message": "未登录",
})
return
}
var req UniversalVerifyRequest
if err := c.ShouldBindJSON(&req); err != nil {
common.ApiError(c, fmt.Errorf("参数错误: %v", err))
return
}
// 获取用户信息
user := &model.User{Id: userId}
if err := user.FillUserById(); err != nil {
common.ApiError(c, fmt.Errorf("获取用户信息失败: %v", err))
return
}
if user.Status != common.UserStatusEnabled {
common.ApiError(c, fmt.Errorf("该用户已被禁用"))
return
}
// 检查用户的验证方式
twoFA, _ := model.GetTwoFAByUserId(userId)
has2FA := twoFA != nil && twoFA.IsEnabled
passkey, passkeyErr := model.GetPasskeyByUserID(userId)
hasPasskey := passkeyErr == nil && passkey != nil
if !has2FA && !hasPasskey {
common.ApiError(c, fmt.Errorf("用户未启用2FA或Passkey"))
return
}
// 根据验证方式进行验证
var verified bool
var verifyMethod string
switch req.Method {
case "2fa":
if !has2FA {
common.ApiError(c, fmt.Errorf("用户未启用2FA"))
return
}
if req.Code == "" {
common.ApiError(c, fmt.Errorf("验证码不能为空"))
return
}
verified = validateTwoFactorAuth(twoFA, req.Code)
verifyMethod = "2FA"
default:
common.ApiError(c, fmt.Errorf("不支持的验证方式: %s", req.Method))
return
}
if !verified {
common.ApiError(c, fmt.Errorf("验证失败,请检查验证码"))
return
}
// 验证成功,在 session 中记录时间戳
session := sessions.Default(c)
now := time.Now().Unix()
session.Set(SecureVerificationSessionKey, now)
if err := session.Save(); err != nil {
common.ApiError(c, fmt.Errorf("保存验证状态失败: %v", err))
return
}
// 记录日志
model.RecordLog(userId, model.LogTypeSystem, fmt.Sprintf("通用安全验证成功 (验证方式: %s)", verifyMethod))
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "验证成功",
"data": gin.H{
"verified": true,
"expires_at": now + SecureVerificationTimeout,
},
})
}
🤖 Prompt for AI Agents
In controller/secure_verification.go around lines 35 to 133, the "passkey"
branch (lines ~92-101) blindly sets verified = true without confirming a
completed WebAuthn flow, which is a security hole; remove the entire "passkey"
case from UniversalVerify and instead return an error when req.Method ==
"passkey" instructing clients to use the dedicated PasskeyVerifyForSecure
endpoint (or simply treat it as unsupported), update any tests and API docs
accordingly, and ensure logging/error messages clearly direct callers to the
proper Passkey verification flow.

Comment on lines +199 to +221
func CheckSecureVerification(c *gin.Context) bool {
session := sessions.Default(c)
verifiedAtRaw := session.Get(SecureVerificationSessionKey)

if verifiedAtRaw == nil {
return false
}

verifiedAt, ok := verifiedAtRaw.(int64)
if !ok {
return false
}

elapsed := time.Now().Unix() - verifiedAt
if elapsed >= SecureVerificationTimeout {
// 验证已过期,清除 session
session.Delete(SecureVerificationSessionKey)
_ = session.Save()
return false
}

return true
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Silent session save error on expiration cleanup.

Line 216 ignores the session save error when cleaning up expired verification state. While this is a read-only check function, failing to save after deleting the expired key could leave stale data in the session.

Consider logging the error:

 	elapsed := time.Now().Unix() - verifiedAt
 	if elapsed >= SecureVerificationTimeout {
 		// 验证已过期,清除 session
 		session.Delete(SecureVerificationSessionKey)
-		_ = session.Save()
+		if err := session.Save(); err != nil {
+			common.SysLog(fmt.Sprintf("Failed to clear expired verification session: %v", err))
+		}
 		return false
 	}
🤖 Prompt for AI Agents
In controller/secure_verification.go around lines 199 to 221, the session save
error returned after deleting the expired SecureVerificationSessionKey is
currently ignored; modify the cleanup to capture the error from session.Save(),
and log or surface it (use the request context logger or
c.Error/c.Writer/standard logger consistent with project logging conventions) so
failures to persist the deletion are visible; ensure the function still returns
false on error but records the save error for debugging.

Comment on lines +225 to +230
func PasskeyVerifyAndSetSession(c *gin.Context) {
session := sessions.Default(c)
now := time.Now().Unix()
session.Set(SecureVerificationSessionKey, now)
_ = session.Save()
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Silent session save error.

Line 229 ignores the session save error. Given this function is called after successful Passkey verification (security-sensitive operation), save failures should be logged or handled.

Apply this change:

 func PasskeyVerifyAndSetSession(c *gin.Context) {
 	session := sessions.Default(c)
 	now := time.Now().Unix()
 	session.Set(SecureVerificationSessionKey, now)
-	_ = session.Save()
+	if err := session.Save(); err != nil {
+		common.SysLog(fmt.Sprintf("Failed to save verification session: %v", err))
+	}
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func PasskeyVerifyAndSetSession(c *gin.Context) {
session := sessions.Default(c)
now := time.Now().Unix()
session.Set(SecureVerificationSessionKey, now)
_ = session.Save()
}
func PasskeyVerifyAndSetSession(c *gin.Context) {
session := sessions.Default(c)
now := time.Now().Unix()
session.Set(SecureVerificationSessionKey, now)
if err := session.Save(); err != nil {
common.SysLog(fmt.Sprintf("Failed to save verification session: %v", err))
}
}
🤖 Prompt for AI Agents
In controller/secure_verification.go around lines 225 to 230, the call to
session.Save() swallows any returned error; update the code to capture the error
(err := session.Save()), check if err != nil, and handle it by logging the
failure with context (e.g., include user/session identifier or request context)
and take any necessary follow-up action (return an error response or trigger
retry/alert) instead of ignoring it; ensure you use the project’s standard
logging/error handling mechanism (e.g., c.Error, process logger, or log package)
and keep behavior consistent with other security-sensitive handlers.

Comment on lines +11 to +16
const (
// SecureVerificationSessionKey 安全验证的 session key(与 controller 保持一致)
SecureVerificationSessionKey = "secure_verified_at"
// SecureVerificationTimeout 验证有效期(秒)
SecureVerificationTimeout = 300 // 5分钟
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Constants duplicated across packages.

The constants SecureVerificationSessionKey and SecureVerificationTimeout are defined identically in both middleware/secure_verification.go and controller/secure_verification.go (lines 17-20). This duplication creates a maintenance risk if the values need to change.

Move these constants to a shared package (e.g., common/constants.go or a new common/verification.go) and import them in both files:

// In common/verification.go
package common

const (
    SecureVerificationSessionKey = "secure_verified_at"
    SecureVerificationTimeout    = 300 // 5分钟
)

Then import and use in both files:

-const (
-	// SecureVerificationSessionKey 安全验证的 session key(与 controller 保持一致)
-	SecureVerificationSessionKey = "secure_verified_at"
-	// SecureVerificationTimeout 验证有效期(秒)
-	SecureVerificationTimeout = 300 // 5分钟
-)
+import "one-api/common"
🤖 Prompt for AI Agents
In middleware/secure_verification.go (lines 11-16) and
controller/secure_verification.go (around lines 17-20) the constants
SecureVerificationSessionKey and SecureVerificationTimeout are duplicated;
extract them into a shared package file (e.g., common/verification.go) with
package name common and the two const declarations, remove the duplicate const
blocks from both middleware and controller, update both files to import the
common package and reference common.SecureVerificationSessionKey and
common.SecureVerificationTimeout, then run go build/go vet to ensure imports and
references compile cleanly.

Comment on lines +127 to +131
func ClearSecureVerification(c *gin.Context) {
session := sessions.Default(c)
session.Delete(SecureVerificationSessionKey)
_ = session.Save()
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Session.Save error is silently ignored.

While ignoring session save errors with _ = session.Save() might be acceptable in some scenarios, this function is specifically for clearing security state (e.g., during logout). If the save fails, the verification state persists in the session, which could be a security concern.

Consider logging the error or returning it to the caller:

 func ClearSecureVerification(c *gin.Context) {
 	session := sessions.Default(c)
 	session.Delete(SecureVerificationSessionKey)
-	_ = session.Save()
+	if err := session.Save(); err != nil {
+		common.SysLog(fmt.Sprintf("Failed to clear secure verification session: %v", err))
+	}
 }

Alternatively, change the signature to return an error if callers need to handle failures explicitly.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func ClearSecureVerification(c *gin.Context) {
session := sessions.Default(c)
session.Delete(SecureVerificationSessionKey)
_ = session.Save()
}
func ClearSecureVerification(c *gin.Context) {
session := sessions.Default(c)
session.Delete(SecureVerificationSessionKey)
if err := session.Save(); err != nil {
common.SysLog(fmt.Sprintf("Failed to clear secure verification session: %v", err))
}
}
🤖 Prompt for AI Agents
In middleware/secure_verification.go around lines 127-131,
ClearSecureVerification currently ignores the error from session.Save(); modify
the function to handle that error: either log the returned error with context
using the existing logger (e.g., "failed to save session after clearing secure
verification") or change the function signature to return an error and propagate
it to callers so they can react; specifically, call err := session.Save(), if
err != nil then log error and/or return err, and update all callers if you
choose the returning approach.

Comment on lines +205 to +233
const {
isModalVisible,
verificationMethods,
verificationState,
withVerification,
executeVerification,
cancelVerification,
setVerificationCode,
switchVerificationMethod,
} = useSecureVerification({
onSuccess: (result) => {
// 验证成功后显示密钥
console.log('Verification success, result:', result);
if (result && result.success && result.data?.key) {
showSuccess(t('密钥获取成功'));
setKeyDisplayState({
showModal: true,
keyData: result.data.key,
});
} else if (result && result.key) {
// 直接返回了 key(没有包装在 data 中)
showSuccess(t('密钥获取成功'));
setKeyDisplayState({
showModal: true,
keyData: result.key,
});
}
},
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Remove verbose console.log from production code.

The console.log at line 217 adds noise in production. Remove it or wrap it in a development-only guard.

Apply this diff:

   } = useSecureVerification({
     onSuccess: (result) => {
       // 验证成功后显示密钥
-      console.log('Verification success, result:', result);
       if (result && result.success && result.data?.key) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const {
isModalVisible,
verificationMethods,
verificationState,
withVerification,
executeVerification,
cancelVerification,
setVerificationCode,
switchVerificationMethod,
} = useSecureVerification({
onSuccess: (result) => {
// 验证成功后显示密钥
console.log('Verification success, result:', result);
if (result && result.success && result.data?.key) {
showSuccess(t('密钥获取成功'));
setKeyDisplayState({
showModal: true,
keyData: result.data.key,
});
} else if (result && result.key) {
// 直接返回了 key(没有包装在 data 中)
showSuccess(t('密钥获取成功'));
setKeyDisplayState({
showModal: true,
keyData: result.key,
});
}
},
});
const {
isModalVisible,
verificationMethods,
verificationState,
withVerification,
executeVerification,
cancelVerification,
setVerificationCode,
switchVerificationMethod,
} = useSecureVerification({
onSuccess: (result) => {
// 验证成功后显示密钥
if (result && result.success && result.data?.key) {
showSuccess(t('密钥获取成功'));
setKeyDisplayState({
showModal: true,
keyData: result.data.key,
});
} else if (result && result.key) {
// 直接返回了 key(没有包装在 data 中)
showSuccess(t('密钥获取成功'));
setKeyDisplayState({
showModal: true,
keyData: result.key,
});
}
},
});
🤖 Prompt for AI Agents
In web/src/components/table/channels/modals/EditChannelModal.jsx around lines
205 to 233, remove the development-only console.log statement inside the
useSecureVerification onSuccess handler (the line logging 'Verification success,
result:'). Replace it by either nothing or a development-only guard (e.g., wrap
the log in if (process.env.NODE_ENV === 'development') { ... }) so no verbose
console output appears in production, keeping the remaining success handling and
setKeyDisplayState logic unchanged.

Comment on lines +120 to +156
const executeVerification = useCallback(async (method, code = '') => {
if (!verificationState.apiCall) {
showError(t('验证配置错误'));
return;
}

setVerificationState(prev => ({ ...prev, loading: true }));

try {
// 先调用验证 API,成功后后端会设置 session
await SecureVerificationService.verify(method, code);

// 验证成功,调用业务 API(此时中间件会通过)
const result = await verificationState.apiCall();

// 显示成功消息
if (successMessage) {
showSuccess(successMessage);
}

// 调用成功回调
onSuccess?.(result, method);

// 自动重置状态
if (autoReset) {
resetState();
}

return result;
} catch (error) {
showError(error.message || t('验证失败,请重试'));
onError?.(error);
throw error;
} finally {
setVerificationState(prev => ({ ...prev, loading: false }));
}
}, [verificationState.apiCall, successMessage, onSuccess, onError, autoReset, resetState, t]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify the backend Passkey flow integration.

Lines 129-133 call SecureVerificationService.verify(method, code) and then immediately call the stored apiCall(). Based on the controller review, there's an issue with how Passkey verification is handled in the backend's UniversalVerify endpoint—it doesn't actually validate the WebAuthn flow.

Ensure that when method === 'passkey', the frontend uses the dedicated Passkey flow (begin → WebAuthn → finish → set session), not the UniversalVerify endpoint with method: 'passkey'. Review the implementation in SecureVerificationService.verifyPasskey() (lines 77-117 in services/secureVerification.js) to confirm it calls the correct endpoints.

Run this script to verify the Passkey verification flow in the service:

If the service calls /api/verify with method: 'passkey' after the WebAuthn flow, that's vulnerable due to the backend issue. The flow should instead rely on PasskeyVerifyForSecure setting the session directly.


🏁 Script executed:

#!/bin/bash
# Verify that SecureVerificationService.verifyPasskey uses the correct endpoints

echo "=== Checking Passkey verification flow ==="
rg -A 10 'static async verifyPasskey' web/src/services/secureVerification.js

echo ""
echo "=== Checking if UniversalVerify API is called with method=passkey ==="
rg -C 3 "method.*['\"]passkey['\"]" web/src/services/

Length of output: 1400


Use the dedicated Passkey flow instead of the UniversalVerify endpoint
In useSecureVerification (web/src/hooks/common/useSecureVerification.jsx:129-133), branch on method === 'passkey' to call SecureVerificationService.verifyPasskey() rather than verify(). Then update verifyPasskey() (web/src/services/secureVerification.js:77-117) to call the backend’s Passkey-specific finish endpoint (e.g. /api/user/passkey/verify/finish or PasskeyVerifyForSecure) instead of posting to /api/verify with method: 'passkey'.

🤖 Prompt for AI Agents
In web/src/hooks/common/useSecureVerification.jsx around lines 120 to 156, the
verification flow always calls SecureVerificationService.verify(), but when
method === 'passkey' it must call the dedicated passkey flow; change
executeVerification to branch on method === 'passkey' and call
SecureVerificationService.verifyPasskey(code) for that branch, otherwise call
verify(method, code) as before, then proceed with the existing
success/error/reset logic; additionally update
web/src/services/secureVerification.js verifyPasskey() (lines ~77-117) so it
posts to the backend's Passkey-specific finish endpoint (e.g.
/api/user/passkey/verify/finish or the PasskeyVerifyForSecure route) instead of
posting to /api/verify with method: 'passkey', and ensure the request/response
shape matches the backend API.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (3)
web/src/i18n/locales/en.json (1)

2137-2190: Passkey translations added, but SecureVerificationModal strings still missing.

The Passkey-related translations added here are comprehensive and well-structured, covering:

  • User registration and login flows
  • Device support and backup states
  • Admin management functionality
  • System configuration parameters

However, this is a duplicate of a previous concern: the translations for SecureVerificationModal and useSecureVerification mentioned in the past review are still missing. The AI summary indicates these components exist in the codebase, but their translation keys are not present in this file.

Missing translations (from previous review):

+  "需要安全验证": "Security verification required",
+  "您需要先启用两步验证或 Passkey 才能查看敏感信息。": "You need to enable Two‑Factor Authentication or Passkey to view sensitive information.",
+  "请前往个人设置 → 安全设置进行配置。": "Please go to Personal Settings → Security Settings to configure.",
+  "使用 Passkey 验证": "Verify with Passkey",
+  "点击下方按钮,使用您的生物特征或安全密钥进行验证": "Click the button below to verify using your biometrics or security key",
+  "验证中...": "Verifying...",
+  "验证 Passkey": "Verify Passkey",
+  "为了保护账户安全,请验证您的身份。": "To protect your account, please verify your identity.",
+  "您需要先启用两步验证或 Passkey 才能执行此操作": "You need to enable Two‑Factor Authentication or Passkey before performing this action",

Without these translations, English-speaking users will see Chinese text in the secure verification modal.

web/src/components/table/channels/modals/EditChannelModal.jsx (2)

216-233: Remove verbose console.log from production code.

The console.log at line 218 adds noise in production and was flagged in a previous review. Remove it or wrap it in a development-only guard.

Apply this diff:

   } = useSecureVerification({
     onSuccess: (result) => {
       // 验证成功后显示密钥
-      console.log('Verification success, result:', result);
       if (result && result.success && result.data?.key) {

Or wrap it:

+      if (process.env.NODE_ENV === 'development') {
+        console.log('Verification success, result:', result);
+      }

616-641: Rename, guard, and remove verbose logs in production.

This handler still has the issues flagged in the previous review:

  • The name handleShow2FAModal is 2FA-specific but the flow is now generic.
  • No defensive guard if channelId is falsy.
  • Console noise (console.error at line 638) should be dev-only or removed.

Apply this diff:

-  // 查看渠道密钥(透明验证)
-  const handleShow2FAModal = async () => {
+  // 查看渠道密钥(透明验证)
+  const handleSecureVerification = async () => {
     try {
+      if (!channelId) {
+        showError(t('渠道未找到,请刷新页面后重试。'));
+        return;
+      }
       // 使用 withVerification 包装,会自动处理需要验证的情况
       const result = await withVerification(
         createApiCalls.viewChannelKey(channelId),
         {
           title: t('查看渠道密钥'),
           description: t('为了保护账户安全,请验证您的身份。'),
           preferredMethod: 'passkey', // 优先使用 Passkey
         }
       );

       // 如果直接返回了结果(已验证),显示密钥
       if (result && result.success && result.data?.key) {
         showSuccess(t('密钥获取成功'));
         setKeyDisplayState({
           showModal: true,
           keyData: result.data.key,
         });
       }
     } catch (error) {
-      console.error('Failed to view channel key:', error);
+      if (process.env.NODE_ENV === 'development') {
+        console.error('Failed to view channel key:', error);
+      }
       showError(error.message || t('获取密钥失败'));
     }
   };

Update call sites at lines 1423, 1541, and 1612:

- onClick={handleShow2FAModal}
+ onClick={handleSecureVerification}
🧹 Nitpick comments (1)
web/src/i18n/locales/zh.json (1)

41-94: Consider grouping Passkey translations under a namespace.

The 50+ new Passkey-related translations are added at the root level, which may impact maintainability as the application grows. Consider organizing them under a dedicated namespace (e.g., "passkey": {...}) similar to the existing "common" namespace at line 37-39.

This would:

  • Improve code organization and searchability
  • Reduce risk of key naming conflicts
  • Make it easier to manage related translations as a unit

Example structure:

  "common": {
    "changeLanguage": "切换语言"
  },
  "允许在 Stripe 支付中输入促销码": "允许在 Stripe 支付中输入促销码",
+ "passkey": {
+   "title": "Passkey 认证",
+   "enabled": "已启用 Passkey,可进行无密码认证",
+   "description": "使用 Passkey 实现免密且更安全的认证体验",
+   ...
+ }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e8425ad and 4c13666.

📒 Files selected for processing (4)
  • web/src/components/settings/PersonalSetting.jsx (5 hunks)
  • web/src/components/table/channels/modals/EditChannelModal.jsx (6 hunks)
  • web/src/i18n/locales/en.json (3 hunks)
  • web/src/i18n/locales/zh.json (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • web/src/components/settings/PersonalSetting.jsx
🧰 Additional context used
🧬 Code graph analysis (1)
web/src/components/table/channels/modals/EditChannelModal.jsx (5)
web/src/hooks/common/useSecureVerification.jsx (10)
  • useSecureVerification (34-246)
  • useSecureVerification (34-246)
  • withVerification (203-218)
  • isModalVisible (50-50)
  • verificationMethods (43-47)
  • verificationState (53-58)
  • executeVerification (120-156)
  • cancelVerification (169-171)
  • setVerificationCode (159-161)
  • switchVerificationMethod (164-166)
web/src/helpers/utils.jsx (2)
  • showSuccess (157-159)
  • showError (122-151)
web/src/services/secureVerification.js (2)
  • createApiCalls (177-217)
  • createApiCalls (177-217)
web/src/components/common/modals/SecureVerificationModal.jsx (3)
  • SecureVerificationModal (38-283)
  • verificationMethods (53-53)
  • verificationState (54-54)
web/src/components/common/ui/ChannelKeyDisplay.jsx (1)
  • ChannelKeyDisplay (86-278)
🔇 Additional comments (8)
web/src/i18n/locales/en.json (1)

9-9: LGTM! Passkey login option translations look good.

The translations for Passkey authentication in the login flow and system settings are clear and consistent.

Also applies to: 336-336

web/src/components/table/channels/modals/EditChannelModal.jsx (5)

59-62: LGTM!

The new imports correctly support the generic secure verification flow, replacing the old 2FA-specific modal.


236-242: LGTM!

The reset function correctly clears the key display state.


724-748: LGTM!

The modal reset logic correctly includes resetting the key display state, ensuring clean state management when the modal closes.


2501-2512: LGTM!

The SecureVerificationModal is correctly wired to the new verification state and handlers, replacing the old 2FA-specific modal.


2514-2553: LGTM!

The key display modal correctly uses keyDisplayState for visibility and data, with proper reset handlers.

web/src/i18n/locales/zh.json (2)

40-40: LGTM!

The trailing comma addition is correct and necessary for the subsequent entries.


65-67: Verify enum translation keys intent and address missing entries

  • The keys "preferred", "required", "discouraged", "platform", and "cross-platform" currently mirror their English identifiers in both en.json and zh.json, and are absent from fr.json.
  • Confirm whether these should be user-facing display strings (and supply proper localized values in all locales), or if they’re purely technical identifiers (in which case they might not belong in the translation files).
  • If they’re translatable, restructure or namespace the keys (e.g. verificationLevel.preferred) and add the corresponding Chinese and French translations.

@seefs001
seefs001 merged commit 9f20e49 into QuantumNous:main Sep 30, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Nov 22, 2025
2 tasks done
x22x22 pushed a commit to x22x22/new-api that referenced this pull request Apr 24, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Jun 24, 2026
8 of 11 tasks
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants