All files / src/components/Settings SecureStorage.tsx

0% Statements 0/293
0% Branches 0/1
0% Functions 0/1
0% Lines 0/293

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
/**
 * SecureStorage - OS Keyring/Keychain Management UI
 *
 * Allows users to view, add, and delete securely stored credentials
 * using the OS keyring (Windows DPAPI, macOS Keychain, Linux Secret Service).
 */
import { useState, useEffect } from 'react';
import {
  Key,
  Plus,
  Trash2,
  Eye,
  EyeOff,
  RefreshCw,
  AlertCircle,
  CheckCircle,
  Shield,
  ShieldOff,
} from 'lucide-react';
import { secureStorage, isSecureStorageAvailable } from '../../lib/secure-storage';
 
interface StoredKey {
  key: string;
  hasValue: boolean;
  preview?: string;
}
 
// Known storage keys used by the application
const KNOWN_KEYS = [
  { key: 'zclaw_api_key', label: 'API Key', description: 'LLM API 密钥' },
  { key: 'zclaw_device_keys_private', label: 'Device Private Key', description: '设备私钥 (Ed25519)' },
  { key: 'zclaw_gateway_token', label: 'Gateway Token', description: 'Gateway 认证令牌' },
  { key: 'zclaw_feishu_secret', label: '飞书 Secret', description: '飞书应用密钥' },
  { key: 'zclaw_discord_token', label: 'Discord Token', description: 'Discord Bot Token' },
  { key: 'zclaw_slack_token', label: 'Slack Token', description: 'Slack Bot Token' },
  { key: 'zclaw_telegram_token', label: 'Telegram Token', description: 'Telegram Bot Token' },
];
 
export function SecureStorage() {
  const [isAvailable, setIsAvailable] = useState<boolean | null>(null);
  const [storedKeys, setStoredKeys] = useState<StoredKey[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [showAddForm, setShowAddForm] = useState(false);
  const [newKey, setNewKey] = useState('');
  const [newValue, setNewValue] = useState('');
  const [showValue, setShowValue] = useState<Record<string, boolean>>({});
  const [revealedValues, setRevealedValues] = useState<Record<string, string>>({});
  const [isSaving, setIsSaving] = useState(false);
  const [isDeleting, setIsDeleting] = useState<string | null>(null);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
 
  const loadStoredKeys = async () => {
    setIsLoading(true);
    try {
      const available = await isSecureStorageAvailable();
      setIsAvailable(available);
 
      const keys: StoredKey[] = [];
      for (const knownKey of KNOWN_KEYS) {
        const value = await secureStorage.get(knownKey.key);
        keys.push({
          key: knownKey.key,
          hasValue: !!value,
          preview: value ? `${value.slice(0, 8)}${value.length > 8 ? '...' : ''}` : undefined,
        });
      }
      setStoredKeys(keys);
    } catch (error) {
      console.error('Failed to load stored keys:', error);
    } finally {
      setIsLoading(false);
    }
  };
 
  useEffect(() => {
    loadStoredKeys();
  }, []);
 
  const handleReveal = async (key: string) => {
    if (revealedValues[key]) {
      // Hide if already revealed
      setRevealedValues((prev) => {
        const next = { ...prev };
        delete next[key];
        return next;
      });
      setShowValue((prev) => ({ ...prev, [key]: false }));
    } else {
      // Reveal the value
      const value = await secureStorage.get(key);
      if (value) {
        setRevealedValues((prev) => ({ ...prev, [key]: value }));
        setShowValue((prev) => ({ ...prev, [key]: true }));
      }
    }
  };
 
  const handleAddKey = async () => {
    if (!newKey.trim() || !newValue.trim()) {
      setMessage({ type: 'error', text: '请填写密钥名称和值' });
      return;
    }
 
    setIsSaving(true);
    setMessage(null);
    try {
      await secureStorage.set(newKey.trim(), newValue.trim());
      setMessage({ type: 'success', text: '密钥已保存' });
      setNewKey('');
      setNewValue('');
      setShowAddForm(false);
      await loadStoredKeys();
    } catch (error) {
      setMessage({ type: 'error', text: `保存失败: ${error instanceof Error ? error.message : '未知错误'}` });
    } finally {
      setIsSaving(false);
    }
  };
 
  const handleDeleteKey = async (key: string) => {
    if (!confirm(`确定要删除密钥 "${key}" 吗?此操作无法撤销。`)) {
      return;
    }
 
    setIsDeleting(key);
    setMessage(null);
    try {
      await secureStorage.delete(key);
      setMessage({ type: 'success', text: '密钥已删除' });
      setRevealedValues((prev) => {
        const next = { ...prev };
        delete next[key];
        return next;
      });
      await loadStoredKeys();
    } catch (error) {
      setMessage({ type: 'error', text: `删除失败: ${error instanceof Error ? error.message : '未知错误'}` });
    } finally {
      setIsDeleting(null);
    }
  };
 
  const getKeyLabel = (key: string) => {
    const known = KNOWN_KEYS.find((k) => k.key === key);
    return known ? known.label : key;
  };
 
  const getKeyDescription = (key: string) => {
    const known = KNOWN_KEYS.find((k) => k.key === key);
    return known?.description;
  };
 
  return (
    <div className="max-w-3xl">
      <div className="flex justify-between items-center mb-6">
        <div>
          <h1 className="text-xl font-bold text-gray-900 dark:text-white">安全存储</h1>
          <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
            使用系统密钥库 (Keyring/Keychain) 安全存储敏感信息
          </p>
        </div>
        <div className="flex gap-2 items-center">
          {isAvailable !== null && (
            <span className={`text-xs flex items-center gap-1 ${isAvailable ? 'text-green-600' : 'text-amber-600'}`}>
              {isAvailable ? (
                <>
                  <Shield className="w-3 h-3" /> Keyring 可用
                </>
              ) : (
                <>
                  <ShieldOff className="w-3 h-3" /> 使用加密本地存储
                </>
              )}
            </span>
          )}
          <button
            onClick={loadStoredKeys}
            disabled={isLoading}
            className="text-xs text-white bg-orange-500 hover:bg-orange-600 px-3 py-1.5 rounded-lg flex items-center gap-1 transition-colors disabled:opacity-50"
          >
            <RefreshCw className={`w-3 h-3 ${isLoading ? 'animate-spin' : ''}`} /> 刷新
          </button>
        </div>
      </div>
 
      {/* Status Banner */}
      {isAvailable === false && (
        <div className="mb-6 p-4 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg">
          <div className="flex items-start gap-2">
            <AlertCircle className="w-4 h-4 text-amber-500 mt-0.5" />
            <div className="text-xs text-amber-700 dark:text-amber-300">
              <p className="font-medium">Keyring 不可用</p>
              <p className="mt-1">
                系统密钥库不可用,将使用 AES-GCM 加密的本地存储作为后备方案。
                建议在 Tauri 环境中运行以获得最佳安全性。
              </p>
            </div>
          </div>
        </div>
      )}
 
      {/* Message */}
      {message && (
        <div className={`mb-4 p-3 rounded-lg flex items-center gap-2 ${
          message.type === 'success'
            ? 'bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300'
            : 'bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-300'
        }`}>
          {message.type === 'success' ? (
            <CheckCircle className="w-4 h-4" />
          ) : (
            <AlertCircle className="w-4 h-4" />
          )}
          {message.text}
        </div>
      )}
 
      {/* Stored Keys List */}
      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 mb-6 shadow-sm">
        {isLoading ? (
          <div className="h-40 flex items-center justify-center text-sm text-gray-400">
            <RefreshCw className="w-4 h-4 animate-spin mr-2" />
            加载中...
          </div>
        ) : storedKeys.length > 0 ? (
          <div className="divide-y divide-gray-100 dark:divide-gray-700">
            {storedKeys.map((item) => (
              <div key={item.key} className="p-4">
                <div className="flex items-center gap-4">
                  <div className={`w-10 h-10 rounded-xl flex items-center justify-center ${
                    item.hasValue
                      ? 'bg-gradient-to-br from-green-500 to-emerald-500 text-white'
                      : 'bg-gray-200 dark:bg-gray-700 text-gray-400'
                  }`}>
                    <Key className="w-4 h-4" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="text-sm font-medium text-gray-900 dark:text-white">
                      {getKeyLabel(item.key)}
                    </div>
                    <div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
                      {getKeyDescription(item.key) || item.key}
                    </div>
                    {item.hasValue && (
                      <div className="text-xs text-gray-400 dark:text-gray-500 mt-1 font-mono">
                        {showValue[item.key] ? (
                          <span className="break-all">{revealedValues[item.key]}</span>
                        ) : (
                          <span>{item.preview}</span>
                        )}
                      </div>
                    )}
                  </div>
                  <div className="flex items-center gap-2">
                    {item.hasValue && (
                      <>
                        <button
                          onClick={() => handleReveal(item.key)}
                          className="p-2 text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
                          title={showValue[item.key] ? '隐藏' : '显示'}
                        >
                          {showValue[item.key] ? (
                            <EyeOff className="w-4 h-4" />
                          ) : (
                            <Eye className="w-4 h-4" />
                          )}
                        </button>
                        <button
                          onClick={() => handleDeleteKey(item.key)}
                          disabled={isDeleting === item.key}
                          className="p-2 text-gray-400 hover:text-red-600 dark:hover:text-red-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors disabled:opacity-50"
                          title="删除"
                        >
                          {isDeleting === item.key ? (
                            <RefreshCw className="w-4 h-4 animate-spin" />
                          ) : (
                            <Trash2 className="w-4 h-4" />
                          )}
                        </button>
                      </>
                    )}
                    {!item.hasValue && (
                      <span className="text-xs text-gray-400 dark:text-gray-500 px-2">未设置</span>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="h-40 flex items-center justify-center text-sm text-gray-400">
            暂无存储的密钥
          </div>
        )}
      </div>
 
      {/* Add New Key */}
      <div className="mb-6">
        {!showAddForm ? (
          <button
            onClick={() => setShowAddForm(true)}
            className="w-full p-4 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-xl text-gray-500 dark:text-gray-400 hover:border-orange-400 hover:text-orange-500 transition-colors flex items-center justify-center gap-2"
          >
            <Plus className="w-4 h-4" />
            <span className="text-sm">添加新密钥</span>
          </button>
        ) : (
          <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4 shadow-sm">
            <h3 className="text-sm font-medium text-gray-900 dark:text-white mb-4">添加新密钥</h3>
            <div className="space-y-3">
              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  密钥名称
                </label>
                <input
                  type="text"
                  value={newKey}
                  onChange={(e) => setNewKey(e.target.value)}
                  placeholder="例如: zclaw_custom_key"
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
              </div>
              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  密钥值
                </label>
                <input
                  type="password"
                  value={newValue}
                  onChange={(e) => setNewValue(e.target.value)}
                  placeholder="输入密钥值"
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
              </div>
              <div className="flex gap-2 pt-2">
                <button
                  onClick={() => {
                    setShowAddForm(false);
                    setNewKey('');
                    setNewValue('');
                    setMessage(null);
                  }}
                  className="flex-1 px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 text-sm"
                >
                  取消
                </button>
                <button
                  onClick={handleAddKey}
                  disabled={isSaving || !newKey.trim() || !newValue.trim()}
                  className="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 flex items-center justify-center gap-2 text-sm"
                >
                  {isSaving ? (
                    <>
                      <RefreshCw className="w-3 h-3 animate-spin" />
                      保存中...
                    </>
                  ) : (
                    <>
                      <CheckCircle className="w-3 h-3" />
                      保存
                    </>
                  )}
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
 
      {/* Info Section */}
      <div className="p-4 bg-gray-50 dark:bg-gray-800/50 rounded-lg border border-gray-200 dark:border-gray-700">
        <h3 className="text-sm font-medium text-gray-900 dark:text-white mb-2">关于安全存储</h3>
        <ul className="text-xs text-gray-500 dark:text-gray-400 space-y-1">
          <li>• Windows: 使用 DPAPI 加密</li>
          <li>• macOS: 使用 Keychain 存储</li>
          <li>• Linux: 使用 Secret Service API (gnome-keyring, kwallet 等)</li>
          <li>• 后备方案: AES-GCM 加密的 localStorage</li>
        </ul>
      </div>
    </div>
  );
}