OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.
TypeScript
feat: add secure settings with encrypted API key storage
lvalics37a2bfa65fa2
diff --git a/apps/web/src/components/editor/Toolbar.tsx b/apps/web/src/components/editor/Toolbar.tsxindex f7cde28a..1e93ed94 100644--- a/apps/web/src/components/editor/Toolbar.tsx+++ b/apps/web/src/components/editor/Toolbar.tsx@@ -40,7 +40,9 @@ import { ExportDialog } from "./ExportDialog";import { ScreenRecorder } from "./ScreenRecorder";import { HistoryPanel } from "./inspector/HistoryPanel";import { ProjectSwitcher } from "./ProjectSwitcher";+import { SettingsDialog } from "./settings/SettingsDialog";import { toast } from "../../stores/notification-store";+import { useSettingsStore } from "../../stores/settings-store";import { useAnalytics, AnalyticsEvents } from "../../hooks/useAnalytics";import { startTour, ONBOARDING_KEY, startMoGraphTour, MOGRAPH_TOUR_KEY } from "./tour";import {@@ -88,6 +90,7 @@ export const Toolbar: React.FC = () => {} = useUIStore();const { mode: themeMode, toggleTheme } = useThemeStore();const { navigate } = useRouter();+ const { openSettings } = useSettingsStore();const [isExportOpen, setIsExportOpen] = useState(false);const [isExportDialogOpen, setIsExportDialogOpen] = useState(false);const [isRecorderOpen, setIsRecorderOpen] = useState(false);@@ -768,6 +771,20 @@ export const Toolbar: React.FC = () => {</TooltipContent></Tooltip>+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ onClick={() => openSettings()}+ className="p-2 rounded-lg hover:bg-background-elevated text-text-secondary hover:text-text-primary transition-colors"+ >+ <Settings size={16} />+ </button>+ </TooltipTrigger>+ <TooltipContent>+ <p>Settings & API Keys</p>+ </TooltipContent>+ </Tooltip>+<Tooltip><TooltipTrigger asChild><button@@ -1006,6 +1023,8 @@ export const Toolbar: React.FC = () => {onRecordingComplete={handleRecordingComplete}/>+ <SettingsDialog />+{isHistoryOpen && (<><divdiff --git a/apps/web/src/components/editor/settings/ApiKeysPanel.tsx b/apps/web/src/components/editor/settings/ApiKeysPanel.tsxnew file mode 100644index 00000000..54b3a786--- /dev/null+++ b/apps/web/src/components/editor/settings/ApiKeysPanel.tsx@@ -0,0 +1,404 @@+import React, { useState, useEffect, useCallback } from "react";+import {+ Key,+ Plus,+ Trash2,+ Eye,+ EyeOff,+ Lock,+ Unlock,+ ExternalLink,+ Shield,+ KeyRound,+} from "lucide-react";+import { Input } from "@openreel/ui";+import { Button } from "@openreel/ui";+import { useSettingsStore, SERVICE_REGISTRY } from "../../../stores/settings-store";+import {+ isMasterPasswordSet,+ isSessionUnlocked,+ setupMasterPassword,+ unlockSession,+ lockSession,+ saveSecret,+ getSecret,+ deleteSecret,+ listSecrets,+ changeMasterPassword,+} from "../../../services/secure-storage";+import { MasterPasswordDialog } from "./MasterPasswordDialog";+import { toast } from "../../../stores/notification-store";++export const ApiKeysPanel: React.FC = () => {+ const { addConfiguredService, removeConfiguredService } =+ useSettingsStore();++ const [passwordSet, setPasswordSet] = useState(false);+ const [unlocked, setUnlocked] = useState(false);+ const [passwordDialogMode, setPasswordDialogMode] = useState<+ "setup" | "unlock" | "change" | null+ >(null);+ const [storedKeys, setStoredKeys] = useState<+ Array<{ id: string; label: string; createdAt: number; updatedAt: number }>+ >([]);+ const [addingService, setAddingService] = useState<string | null>(null);+ const [newKeyValue, setNewKeyValue] = useState("");+ const [revealedKeys, setRevealedKeys] = useState<Record<string, string>>({});+ const [showKey, setShowKey] = useState<Record<string, boolean>>({});++ const refreshState = useCallback(async () => {+ const isSet = await isMasterPasswordSet();+ setPasswordSet(isSet);+ setUnlocked(isSessionUnlocked());++ if (isSessionUnlocked()) {+ const keys = await listSecrets();+ setStoredKeys(keys);+ }+ }, []);++ useEffect(() => {+ refreshState();+ }, [refreshState]);++ const handlePasswordSubmit = useCallback(+ async (password: string, newPassword?: string): Promise<boolean> => {+ if (passwordDialogMode === "setup") {+ await setupMasterPassword(password);+ setPasswordDialogMode(null);+ await refreshState();+ toast.success("Master password set", "Your API keys will be encrypted with AES-256-GCM.");+ return true;+ }++ if (passwordDialogMode === "unlock") {+ const success = await unlockSession(password);+ if (success) {+ setPasswordDialogMode(null);+ await refreshState();+ toast.success("Session unlocked", "You can now manage API keys.");+ }+ return success;+ }++ if (passwordDialogMode === "change" && newPassword) {+ const success = await changeMasterPassword(password, newPassword);+ if (success) {+ setPasswordDialogMode(null);+ await refreshState();+ toast.success("Password changed", "All keys have been re-encrypted.");+ }+ return success;+ }++ return false;+ },+ [passwordDialogMode, refreshState],+ );++ const handleSaveKey = useCallback(+ async (serviceId: string) => {+ if (!newKeyValue.trim()) return;++ const service = SERVICE_REGISTRY.find((s) => s.id === serviceId);+ if (!service) return;++ try {+ await saveSecret(serviceId, service.label, newKeyValue.trim());+ addConfiguredService(serviceId);+ setNewKeyValue("");+ setAddingService(null);+ await refreshState();+ toast.success(`${service.label} key saved`, "API key encrypted and stored.");+ } catch (err) {+ toast.error("Failed to save", err instanceof Error ? err.message : "Unknown error");+ }+ },+ [newKeyValue, addConfiguredService, refreshState],+ );++ const handleDeleteKey = useCallback(+ async (serviceId: string) => {+ const service = SERVICE_REGISTRY.find((s) => s.id === serviceId);+ try {+ await deleteSecret(serviceId);+ removeConfiguredService(serviceId);+ setRevealedKeys((prev) => {+ const next = { ...prev };+ delete next[serviceId];+ return next;+ });+ await refreshState();+ toast.success(`${service?.label ?? serviceId} key removed`);+ } catch (err) {+ toast.error("Failed to delete", err instanceof Error ? err.message : "Unknown error");+ }+ },+ [removeConfiguredService, refreshState],+ );++ const handleRevealKey = useCallback(async (serviceId: string) => {+ if (revealedKeys[serviceId]) {+ setShowKey((prev) => ({ ...prev, [serviceId]: !prev[serviceId] }));+ return;+ }++ try {+ const value = await getSecret(serviceId);+ if (value) {+ setRevealedKeys((prev) => ({ ...prev, [serviceId]: value }));+ setShowKey((prev) => ({ ...prev, [serviceId]: true }));+ }+ } catch (err) {+ toast.error("Failed to decrypt", err instanceof Error ? err.message : "Unknown error");+ }+ }, [revealedKeys]);++ const handleLock = useCallback(() => {+ lockSession();+ setUnlocked(false);+ setStoredKeys([]);+ setRevealedKeys({});+ setShowKey({});+ }, []);++ const availableServices = SERVICE_REGISTRY.filter(+ (s) => !storedKeys.some((k) => k.id === s.id),+ );++ // Not set up yet+ if (!passwordSet) {+ return (+ <div className="flex flex-col items-center justify-center py-12 px-4 text-center">+ <div className="w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mb-4">+ <Shield size={32} className="text-primary" />+ </div>+ <h3 className="text-lg font-medium text-text-primary mb-2">+ Secure API Key Storage+ </h3>+ <p className="text-sm text-text-muted mb-6 max-w-sm">+ Set up a master password to encrypt and store your API keys locally.+ Keys are encrypted with AES-256-GCM and never leave your browser.+ </p>+ <Button onClick={() => setPasswordDialogMode("setup")}>+ <KeyRound size={16} className="mr-2" />+ Set Up Master Password+ </Button>++ {passwordDialogMode && (+ <MasterPasswordDialog+ isOpen={!!passwordDialogMode}+ onClose={() => setPasswordDialogMode(null)}+ mode={passwordDialogMode}+ onSubmit={handlePasswordSubmit}+ />+ )}+ </div>+ );+ }++ // Locked+ if (!unlocked) {+ return (+ <div className="flex flex-col items-center justify-center py-12 px-4 text-center">+ <div className="w-16 h-16 rounded-full bg-amber-500/10 flex items-center justify-center mb-4">+ <Lock size={32} className="text-amber-500" />+ </div>+ <h3 className="text-lg font-medium text-text-primary mb-2">+ Session Locked+ </h3>+ <p className="text-sm text-text-muted mb-6 max-w-sm">+ Enter your master password to view and manage API keys.+ </p>+ <Button onClick={() => setPasswordDialogMode("unlock")}>+ <Unlock size={16} className="mr-2" />+ Unlock+ </Button>++ {passwordDialogMode && (+ <MasterPasswordDialog+ isOpen={!!passwordDialogMode}+ onClose={() => setPasswordDialogMode(null)}+ mode={passwordDialogMode}+ onSubmit={handlePasswordSubmit}+ />+ )}+ </div>+ );+ }++ // Unlocked — full management UI+ return (+ <div className="space-y-6">+ {/* Header actions */}+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2 text-sm text-text-muted">+ <Shield size={14} className="text-primary" />+ <span>+ {storedKeys.length} key{storedKeys.length !== 1 ? "s" : ""} stored+ </span>+ </div>+ <div className="flex items-center gap-2">+ <Button+ variant="outline"+ size="sm"+ onClick={() => setPasswordDialogMode("change")}+ >+ <Key size={14} className="mr-1" />+ Change Password+ </Button>+ <Button variant="outline" size="sm" onClick={handleLock}>+ <Lock size={14} className="mr-1" />+ Lock+ </Button>+ </div>+ </div>++ {/* Stored keys list */}+ <div className="space-y-3">+ {storedKeys.map((stored) => {+ const service = SERVICE_REGISTRY.find((s) => s.id === stored.id);+ const isRevealed = showKey[stored.id] && revealedKeys[stored.id];++ return (+ <div+ key={stored.id}+ className="border border-border rounded-lg p-4 bg-background-secondary"+ >+ <div className="flex items-center justify-between mb-2">+ <div className="flex items-center gap-2">+ <Key size={14} className="text-primary" />+ <span className="text-sm font-medium text-text-primary">+ {service?.label ?? stored.label}+ </span>+ {service?.docsUrl && (+ <a+ href={service.docsUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="text-text-muted hover:text-primary transition-colors"+ >+ <ExternalLink size={12} />+ </a>+ )}+ </div>+ <div className="flex items-center gap-1">+ <button+ onClick={() => handleRevealKey(stored.id)}+ className="p-1.5 rounded hover:bg-background-tertiary text-text-muted hover:text-text-primary transition-colors"+ title={isRevealed ? "Hide key" : "Show key"}+ >+ {isRevealed ? <EyeOff size={14} /> : <Eye size={14} />}+ </button>+ <button+ onClick={() => handleDeleteKey(stored.id)}+ className="p-1.5 rounded hover:bg-error/10 text-text-muted hover:text-error transition-colors"+ title="Delete key"+ >+ <Trash2 size={14} />+ </button>+ </div>+ </div>++ {service && (+ <p className="text-xs text-text-muted mb-2">+ {service.description}+ </p>+ )}++ <div className="font-mono text-xs bg-background rounded px-3 py-2 text-text-secondary">+ {isRevealed+ ? revealedKeys[stored.id]+ : "••••••••••••••••••••••••••••••••"}+ </div>++ <div className="text-[10px] text-text-muted mt-2">+ Added {new Date(stored.createdAt).toLocaleDateString()} ·+ Updated {new Date(stored.updatedAt).toLocaleDateString()}+ </div>+ </div>+ );+ })}+ </div>++ {/* Add new key */}+ {addingService ? (+ <div className="border border-primary/30 rounded-lg p-4 bg-primary/5">+ <div className="flex items-center gap-2 mb-3">+ <Plus size={14} className="text-primary" />+ <span className="text-sm font-medium text-text-primary">+ Add{" "}+ {SERVICE_REGISTRY.find((s) => s.id === addingService)?.label} Key+ </span>+ </div>+ <Input+ type="password"+ value={newKeyValue}+ onChange={(e) => setNewKeyValue(e.target.value)}+ placeholder="Paste your API key here"+ autoFocus+ className="mb-3 font-mono text-xs"+ />+ <div className="flex justify-end gap-2">+ <Button+ variant="outline"+ size="sm"+ onClick={() => {+ setAddingService(null);+ setNewKeyValue("");+ }}+ >+ Cancel+ </Button>+ <Button+ size="sm"+ onClick={() => handleSaveKey(addingService)}+ disabled={!newKeyValue.trim()}+ >+ Save Key+ </Button>+ </div>+ </div>+ ) : availableServices.length > 0 ? (+ <div>+ <h4 className="text-sm font-medium text-text-secondary mb-3">+ Add API Key+ </h4>+ <div className="grid gap-2">+ {availableServices.map((service) => (+ <button+ key={service.id}+ onClick={() => setAddingService(service.id)}+ className="flex items-center gap-3 p-3 rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-all text-left group"+ >+ <div className="p-2 rounded-lg bg-background-tertiary group-hover:bg-primary/10 transition-colors">+ <Plus+ size={14}+ className="text-text-muted group-hover:text-primary transition-colors"+ />+ </div>+ <div>+ <div className="text-sm font-medium text-text-primary">+ {service.label}+ </div>+ <div className="text-xs text-text-muted">+ {service.description}+ </div>+ </div>+ </button>+ ))}+ </div>+ </div>+ ) : null}++ {passwordDialogMode && (+ <MasterPasswordDialog+ isOpen={!!passwordDialogMode}+ onClose={() => setPasswordDialogMode(null)}+ mode={passwordDialogMode}+ onSubmit={handlePasswordSubmit}+ />+ )}+ </div>+ );+};diff --git a/apps/web/src/components/editor/settings/GeneralPanel.tsx b/apps/web/src/components/editor/settings/GeneralPanel.tsxnew file mode 100644index 00000000..48d16e59--- /dev/null+++ b/apps/web/src/components/editor/settings/GeneralPanel.tsx@@ -0,0 +1,148 @@+import React from "react";+import { Switch } from "@openreel/ui";+import { Label } from "@openreel/ui";+import { useSettingsStore, SERVICE_REGISTRY } from "../../../stores/settings-store";++export const GeneralPanel: React.FC = () => {+ const {+ autoSave,+ autoSaveInterval,+ defaultTtsProvider,+ defaultLlmProvider,+ defaultAggregator,+ configuredServices,+ setAutoSave,+ setAutoSaveInterval,+ setDefaultTtsProvider,+ setDefaultLlmProvider,+ setDefaultAggregator,+ } = useSettingsStore();++ const ttsProviders = SERVICE_REGISTRY.filter(+ (s) => s.id === "elevenlabs" || configuredServices.includes(s.id),+ );++ const llmProviders = SERVICE_REGISTRY.filter(+ (s) =>+ s.id === "openai" ||+ s.id === "anthropic" ||+ configuredServices.includes(s.id),+ );++ const aggregatorProviders = SERVICE_REGISTRY.filter(+ (s) =>+ s.id === "kie-ai" ||+ s.id === "freepik" ||+ configuredServices.includes(s.id),+ );++ return (+ <div className="space-y-6 pb-4">+ {/* Auto-save */}+ <div className="space-y-4">+ <h3 className="text-sm font-medium text-text-primary">Auto-Save</h3>++ <div className="flex items-center justify-between">+ <div>+ <Label className="text-sm text-text-secondary">Enable auto-save</Label>+ <p className="text-xs text-text-muted mt-0.5">+ Automatically save your project at regular intervals+ </p>+ </div>+ <Switch checked={autoSave} onCheckedChange={setAutoSave} />+ </div>++ {autoSave && (+ <div className="flex items-center gap-3">+ <Label className="text-sm text-text-secondary whitespace-nowrap">+ Save every+ </Label>+ <select+ value={autoSaveInterval}+ onChange={(e) => setAutoSaveInterval(Number(e.target.value))}+ className="h-9 rounded-md border border-input bg-background px-3 text-sm"+ >+ <option value={1}>1 minute</option>+ <option value={2}>2 minutes</option>+ <option value={5}>5 minutes</option>+ <option value={10}>10 minutes</option>+ <option value={15}>15 minutes</option>+ <option value={30}>30 minutes</option>+ </select>+ </div>+ )}+ </div>++ <div className="h-px bg-border" />++ {/* Default providers */}+ <div className="space-y-4">+ <h3 className="text-sm font-medium text-text-primary">+ Default AI Providers+ </h3>+ <p className="text-xs text-text-muted">+ Choose which service to use by default for AI features.+ Configure API keys in the "API Keys" tab first.+ </p>++ <div className="space-y-3">+ <div className="flex items-center justify-between">+ <Label className="text-sm text-text-secondary">+ Text to Speech/Voice To Speech/Sound Effects+ </Label>+ <select+ value={defaultTtsProvider}+ onChange={(e) => setDefaultTtsProvider(e.target.value)}+ className="h-9 rounded-md border border-input bg-background px-3 text-sm min-w-[140px]"+ >+ {ttsProviders.map((s) => (+ <option key={s.id} value={s.id}>+ {s.label}+ </option>+ ))}+ </select>+ </div>++ <div className="flex items-center justify-between">+ <Label className="text-sm text-text-secondary">+ AI Assistant (LLM)+ </Label>+ <select+ value={defaultLlmProvider}+ onChange={(e) => setDefaultLlmProvider(e.target.value)}+ className="h-9 rounded-md border border-input bg-background px-3 text-sm min-w-[140px]"+ >+ {llmProviders.map((s) => (+ <option key={s.id} value={s.id}>+ {s.label}+ </option>+ ))}+ </select>+ </div>++ <div className="flex items-center justify-between">+ <div>+ <Label className="text-sm text-text-secondary">+ AI Aggregator+ </Label>+ <p className="text-xs text-text-muted mt-0.5">+ Video/image generation, upscaling, and creative AI tools+ </p>+ </div>+ <select+ value={defaultAggregator}+ onChange={(e) => setDefaultAggregator(e.target.value)}+ className="h-9 rounded-md border border-input bg-background px-3 text-sm min-w-[140px]"+ >+ {aggregatorProviders.map((s) => (+ <option key={s.id} value={s.id}>+ {s.label}+ </option>+ ))}+ </select>+ </div>+ </div>+ </div>+ </div>+ );+};diff --git a/apps/web/src/components/editor/settings/MasterPasswordDialog.tsx b/apps/web/src/components/editor/settings/MasterPasswordDialog.tsxnew file mode 100644index 00000000..bfe3a664--- /dev/null+++ b/apps/web/src/components/editor/settings/MasterPasswordDialog.tsx@@ -0,0 +1,265 @@+import React, { useState, useCallback } from "react";+import { Lock, Eye, EyeOff, ShieldCheck, AlertTriangle } from "lucide-react";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogFooter,+} from "@openreel/ui";+import { Input } from "@openreel/ui";+import { Button } from "@openreel/ui";++interface MasterPasswordDialogProps {+ isOpen: boolean;+ onClose: () => void;+ mode: "setup" | "unlock" | "change";+ onSubmit: (password: string, newPassword?: string) => Promise<boolean>;+}++export const MasterPasswordDialog: React.FC<MasterPasswordDialogProps> = ({+ isOpen,+ onClose,+ mode,+ onSubmit,+}) => {+ const [password, setPassword] = useState("");+ const [newPassword, setNewPassword] = useState("");+ const [confirmPassword, setConfirmPassword] = useState("");+ const [showPassword, setShowPassword] = useState(false);+ const [showNewPassword, setShowNewPassword] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [loading, setLoading] = useState(false);++ const resetForm = useCallback(() => {+ setPassword("");+ setNewPassword("");+ setConfirmPassword("");+ setShowPassword(false);+ setShowNewPassword(false);+ setError(null);+ setLoading(false);+ }, []);++ const handleClose = useCallback(() => {+ resetForm();+ onClose();+ }, [onClose, resetForm]);++ const handleSubmit = useCallback(async (e: React.FormEvent) => {+ e.preventDefault();+ setError(null);++ if (mode === "setup") {+ if (password.length < 8) {+ setError("Password must be at least 8 characters");+ return;+ }+ if (password !== confirmPassword) {+ setError("Passwords do not match");+ return;+ }+ }++ if (mode === "change") {+ if (newPassword.length < 8) {+ setError("New password must be at least 8 characters");+ return;+ }+ if (newPassword !== confirmPassword) {+ setError("New passwords do not match");+ return;+ }+ }++ setLoading(true);+ try {+ const success = await onSubmit(+ password,+ mode === "change" ? newPassword : undefined,+ );+ if (success) {+ resetForm();+ } else {+ setError(+ mode === "unlock"+ ? "Incorrect password"+ : "Operation failed. Check your current password.",+ );+ }+ } catch (err) {+ setError(err instanceof Error ? err.message : "An error occurred");+ } finally {+ setLoading(false);+ }+ }, [mode, password, newPassword, confirmPassword, onSubmit, resetForm]);++ const titles = {+ setup: "Set Master Password",+ unlock: "Unlock Settings",+ change: "Change Master Password",+ };++ const descriptions = {+ setup: "Create a master password to encrypt your API keys. This password is never stored — only a verification hash is kept.",+ unlock: "Enter your master password to access encrypted API keys.",+ change: "Change your master password. All stored keys will be re-encrypted.",+ };++ return (+ <Dialog open={isOpen} onOpenChange={(open) => !open && handleClose()}>+ <DialogContent className="sm:max-w-md bg-background">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ <Lock size={18} className="text-primary" />+ {titles[mode]}+ </DialogTitle>+ <DialogDescription>{descriptions[mode]}</DialogDescription>+ </DialogHeader>++ <form onSubmit={handleSubmit} className="space-y-4">+ {mode === "change" && (+ <div className="space-y-2">+ <label className="text-sm font-medium text-text-secondary">+ Current Password+ </label>+ <div className="relative">+ <Input+ type={showPassword ? "text" : "password"}+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ placeholder="Enter current password"+ autoFocus+ className="pr-10"+ />+ <button+ type="button"+ onClick={() => setShowPassword(!showPassword)}+ className="absolute right-3 top-1/2 -translate-y-1/2 text-text-muted hover:text-text-primary transition-colors"+ >+ {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}+ </button>+ </div>+ </div>+ )}++ {(mode === "setup" || mode === "unlock") && (+ <div className="space-y-2">+ <label className="text-sm font-medium text-text-secondary">+ {mode === "setup" ? "Password" : "Master Password"}+ </label>+ <div className="relative">+ <Input+ type={showPassword ? "text" : "password"}+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ placeholder={+ mode === "setup"+ ? "Min. 8 characters"+ : "Enter master password"+ }+ autoFocus+ className="pr-10"+ />+ <button+ type="button"+ onClick={() => setShowPassword(!showPassword)}+ className="absolute right-3 top-1/2 -translate-y-1/2 text-text-muted hover:text-text-primary transition-colors"+ >+ {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}+ </button>+ </div>+ </div>+ )}++ {(mode === "setup" || mode === "change") && (+ <>+ <div className="space-y-2">+ <label className="text-sm font-medium text-text-secondary">+ {mode === "change" ? "New Password" : "Confirm Password"}+ </label>+ <div className="relative">+ <Input+ type={showNewPassword ? "text" : "password"}+ value={mode === "change" ? newPassword : confirmPassword}+ onChange={(e) =>+ mode === "change"+ ? setNewPassword(e.target.value)+ : setConfirmPassword(e.target.value)+ }+ placeholder={+ mode === "change"+ ? "Min. 8 characters"+ : "Repeat password"+ }+ className="pr-10"+ />+ <button+ type="button"+ onClick={() => setShowNewPassword(!showNewPassword)}+ className="absolute right-3 top-1/2 -translate-y-1/2 text-text-muted hover:text-text-primary transition-colors"+ >+ {showNewPassword ? <EyeOff size={16} /> : <Eye size={16} />}+ </button>+ </div>+ </div>++ {mode === "change" && (+ <div className="space-y-2">+ <label className="text-sm font-medium text-text-secondary">+ Confirm New Password+ </label>+ <Input+ type={showNewPassword ? "text" : "password"}+ value={confirmPassword}+ onChange={(e) => setConfirmPassword(e.target.value)}+ placeholder="Repeat new password"+ />+ </div>+ )}+ </>+ )}++ {error && (+ <div className="flex items-center gap-2 text-sm text-error bg-error/10 px-3 py-2 rounded-lg">+ <AlertTriangle size={14} />+ {error}+ </div>+ )}++ {mode === "setup" && (+ <div className="flex items-start gap-2 text-xs text-text-muted bg-background-secondary px-3 py-2 rounded-lg">+ <ShieldCheck size={14} className="mt-0.5 shrink-0 text-primary" />+ <span>+ Your password is used to derive an encryption key via PBKDF2+ (100k iterations). API keys are encrypted with AES-256-GCM.+ If you forget this password, stored keys cannot be recovered.+ </span>+ </div>+ )}++ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ onClick={handleClose}+ disabled={loading}+ >+ Cancel+ </Button>+ <Button type="submit" disabled={loading}>+ {loading+ ? "Processing..."+ : mode === "setup"+ ? "Set Password"+ : mode === "unlock"+ ? "Unlock"+ : "Change Password"}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+};diff --git a/apps/web/src/components/editor/settings/SettingsDialog.tsx b/apps/web/src/components/editor/settings/SettingsDialog.tsxnew file mode 100644index 00000000..bd692a8b--- /dev/null+++ b/apps/web/src/components/editor/settings/SettingsDialog.tsx@@ -0,0 +1,65 @@+import React, { useCallback } from "react";+import { Settings, Key } from "lucide-react";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+} from "@openreel/ui";+import { useSettingsStore } from "../../../stores/settings-store";+import { GeneralPanel } from "./GeneralPanel";+import { ApiKeysPanel } from "./ApiKeysPanel";++const TABS = [+ { id: "general", label: "General", icon: Settings },+ { id: "api-keys", label: "API Keys", icon: Key },+] as const;++export const SettingsDialog: React.FC = () => {+ const { settingsOpen, settingsTab, closeSettings } = useSettingsStore();++ const setTab = useCallback((tab: string) => {+ useSettingsStore.setState({ settingsTab: tab });+ }, []);++ return (+ <Dialog open={settingsOpen} onOpenChange={(open) => !open && closeSettings()}>+ <DialogContent className="sm:max-w-2xl max-h-[85vh] bg-background flex flex-col overflow-y-auto">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ <Settings size={18} className="text-primary" />+ Settings+ </DialogTitle>+ <DialogDescription>+ Configure preferences and manage API keys for external services.+ </DialogDescription>+ </DialogHeader>++ {/* Tab bar */}+ <div className="flex gap-1 p-1 bg-muted rounded-md">+ {TABS.map((tab) => (+ <button+ key={tab.id}+ onClick={() => setTab(tab.id)}+ className={`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-sm transition-colors ${+ settingsTab === tab.id+ ? "bg-background text-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground"+ }`}+ >+ <tab.icon size={14} />+ {tab.label}+ </button>+ ))}+ </div>++ {/* Tab content */}+ <div className="flex-1 overflow-y-auto pr-1 mt-2">+ {settingsTab === "general" && <GeneralPanel />}+ {settingsTab === "api-keys" && <ApiKeysPanel />}+ </div>+ </DialogContent>+ </Dialog>+ );+};diff --git a/apps/web/src/services/secure-storage.ts b/apps/web/src/services/secure-storage.tsnew file mode 100644index 00000000..3bfe1685--- /dev/null+++ b/apps/web/src/services/secure-storage.ts@@ -0,0 +1,488 @@+/**+ * Secure storage service for encrypting/decrypting sensitive data (API keys)+ * using Web Crypto API with PBKDF2 key derivation and AES-GCM encryption.+ *+ * Security model:+ * - Master password → PBKDF2 (100k iterations, SHA-256) → derived AES-GCM-256 key+ * - Each secret encrypted with unique IV+ * - Derived key held in memory only, never persisted+ * - Salt stored alongside encrypted data (not secret)+ * - A verification hash is stored to validate the master password+ */++const SECURE_DB_NAME = "openreel-secure";+const SECURE_DB_VERSION = 1;+const STORE_SECRETS = "secrets";+const STORE_META = "meta";++const PBKDF2_ITERATIONS = 100_000;+const SALT_LENGTH = 16;+const IV_LENGTH = 12;++export interface SecureRecord {+ readonly id: string;+ readonly label: string;+ readonly encryptedData: ArrayBuffer;+ readonly iv: Uint8Array;+ readonly createdAt: number;+ readonly updatedAt: number;+}++interface MetaRecord {+ readonly id: string;+ readonly value: ArrayBuffer | Uint8Array;+}++let derivedKey: CryptoKey | null = null;+let inactivityTimer: ReturnType<typeof setTimeout> | null = null;++const SESSION_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes++function resetInactivityTimer(): void {+ if (inactivityTimer) {+ clearTimeout(inactivityTimer);+ }+ inactivityTimer = setTimeout(() => {+ lockSession();+ }, SESSION_TIMEOUT_MS);+}++function openDatabase(): Promise<IDBDatabase> {+ return new Promise((resolve, reject) => {+ const request = indexedDB.open(SECURE_DB_NAME, SECURE_DB_VERSION);++ request.onerror = () => {+ reject(new Error(`Failed to open secure database: ${request.error?.message}`));+ };++ request.onsuccess = () => {+ resolve(request.result);+ };++ request.onupgradeneeded = (event) => {+ const db = (event.target as IDBOpenDBRequest).result;++ if (!db.objectStoreNames.contains(STORE_SECRETS)) {+ db.createObjectStore(STORE_SECRETS, { keyPath: "id" });+ }++ if (!db.objectStoreNames.contains(STORE_META)) {+ db.createObjectStore(STORE_META, { keyPath: "id" });+ }+ };+ });+}++function idbTransaction<T>(+ db: IDBDatabase,+ storeName: string,+ mode: "readonly" | "readwrite",+ operation: (store: IDBObjectStore) => IDBRequest<T>,+): Promise<T> {+ return new Promise((resolve, reject) => {+ const tx = db.transaction(storeName, mode);+ const store = tx.objectStore(storeName);+ const request = operation(store);++ request.onsuccess = () => resolve(request.result);+ request.onerror = () => reject(new Error(`IDB operation failed: ${request.error?.message}`));+ });+}++async function deriveKey(password: string, salt: Uint8Array): Promise<CryptoKey> {+ const encoder = new TextEncoder();+ const keyMaterial = await crypto.subtle.importKey(+ "raw",+ encoder.encode(password),+ "PBKDF2",+ false,+ ["deriveKey"],+ );++ return crypto.subtle.deriveKey(+ {+ name: "PBKDF2",+ salt: salt.buffer as ArrayBuffer,+ iterations: PBKDF2_ITERATIONS,+ hash: "SHA-256",+ },+ keyMaterial,+ { name: "AES-GCM", length: 256 },+ false,+ ["encrypt", "decrypt"],+ );+}++async function encrypt(data: string, key: CryptoKey): Promise<{ encrypted: ArrayBuffer; iv: Uint8Array }> {+ const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));+ const encoder = new TextEncoder();++ const encrypted = await crypto.subtle.encrypt(+ { name: "AES-GCM", iv: iv.buffer as ArrayBuffer },+ key,+ encoder.encode(data),+ );++ return { encrypted, iv };+}++async function decrypt(encrypted: ArrayBuffer, iv: Uint8Array, key: CryptoKey): Promise<string> {+ const decrypted = await crypto.subtle.decrypt(+ { name: "AES-GCM", iv: iv.buffer as ArrayBuffer },+ key,+ encrypted,+ );++ return new TextDecoder().decode(decrypted);+}++/**+ * Check if a master password has been configured.+ */+export async function isMasterPasswordSet(): Promise<boolean> {+ const db = await openDatabase();+ try {+ const meta = await idbTransaction<MetaRecord | undefined>(+ db,+ STORE_META,+ "readonly",+ (store) => store.get("verification"),+ );+ return !!meta;+ } finally {+ db.close();+ }+}++/**+ * Check if the session is currently unlocked.+ */+export function isSessionUnlocked(): boolean {+ return derivedKey !== null;+}++/**+ * Set up the master password for the first time.+ * Generates a random salt, derives a key, and stores a verification token.+ */+export async function setupMasterPassword(password: string): Promise<void> {+ if (password.length < 8) {+ throw new Error("Master password must be at least 8 characters");+ }++ const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH));+ const key = await deriveKey(password, salt);++ // Create a verification token: encrypt a known string+ const verificationPlaintext = "openreel-verify-v1";+ const { encrypted: verificationData, iv: verificationIv } = await encrypt(verificationPlaintext, key);++ const db = await openDatabase();+ try {+ await idbTransaction(db, STORE_META, "readwrite", (store) =>+ store.put({ id: "salt", value: salt }),+ );+ await idbTransaction(db, STORE_META, "readwrite", (store) =>+ store.put({ id: "verification", value: verificationData }),+ );+ await idbTransaction(db, STORE_META, "readwrite", (store) =>+ store.put({ id: "verification_iv", value: verificationIv }),+ );+ } finally {+ db.close();+ }++ derivedKey = key;++ resetInactivityTimer();+}++/**+ * Unlock the session with the master password.+ * Verifies the password against the stored verification token.+ */+export async function unlockSession(password: string): Promise<boolean> {+ const db = await openDatabase();+ try {+ const saltMeta = await idbTransaction<MetaRecord | undefined>(+ db,+ STORE_META,+ "readonly",+ (store) => store.get("salt"),+ );+ const verificationMeta = await idbTransaction<MetaRecord | undefined>(+ db,+ STORE_META,+ "readonly",+ (store) => store.get("verification"),+ );+ const verificationIvMeta = await idbTransaction<MetaRecord | undefined>(+ db,+ STORE_META,+ "readonly",+ (store) => store.get("verification_iv"),+ );++ if (!saltMeta || !verificationMeta || !verificationIvMeta) {+ throw new Error("Master password not configured");+ }++ const salt = saltMeta.value instanceof Uint8Array+ ? saltMeta.value+ : new Uint8Array(saltMeta.value as ArrayBuffer);+ const key = await deriveKey(password, salt);++ try {+ const iv = verificationIvMeta.value instanceof Uint8Array+ ? verificationIvMeta.value+ : new Uint8Array(verificationIvMeta.value as ArrayBuffer);+ const decrypted = await decrypt(verificationMeta.value as ArrayBuffer, iv, key);++ if (decrypted !== "openreel-verify-v1") {+ return false;+ }+ } catch {+ // Decryption failure means wrong password+ return false;+ }++ derivedKey = key;++ resetInactivityTimer();+ return true;+ } finally {+ db.close();+ }+}++/**+ * Lock the session, clearing the derived key from memory.+ */+export function lockSession(): void {+ derivedKey = null;++ if (inactivityTimer) {+ clearTimeout(inactivityTimer);+ inactivityTimer = null;+ }+}++/**+ * Change the master password. Re-encrypts all stored secrets.+ */+export async function changeMasterPassword(+ currentPassword: string,+ newPassword: string,+): Promise<boolean> {+ if (newPassword.length < 8) {+ throw new Error("New password must be at least 8 characters");+ }++ // Verify current password+ const unlocked = await unlockSession(currentPassword);+ if (!unlocked || !derivedKey) {+ return false;+ }++ const oldKey = derivedKey;++ // Decrypt all existing secrets+ const db = await openDatabase();+ try {+ const allSecrets = await new Promise<SecureRecord[]>((resolve, reject) => {+ const tx = db.transaction(STORE_SECRETS, "readonly");+ const store = tx.objectStore(STORE_SECRETS);+ const request = store.getAll();+ request.onsuccess = () => resolve(request.result);+ request.onerror = () => reject(request.error);+ });++ const decryptedSecrets: Array<{ id: string; label: string; value: string; createdAt: number }> = [];+ for (const record of allSecrets) {+ const iv = record.iv instanceof Uint8Array+ ? record.iv+ : new Uint8Array(record.iv as unknown as ArrayBuffer);+ const value = await decrypt(record.encryptedData, iv, oldKey);+ decryptedSecrets.push({+ id: record.id,+ label: record.label,+ value,+ createdAt: record.createdAt,+ });+ }++ // Set up new password+ const newSalt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH));+ const newKey = await deriveKey(newPassword, newSalt);++ // Store new salt and verification+ const verificationPlaintext = "openreel-verify-v1";+ const { encrypted: verificationData, iv: verificationIv } = await encrypt(verificationPlaintext, newKey);++ await idbTransaction(db, STORE_META, "readwrite", (store) =>+ store.put({ id: "salt", value: newSalt }),+ );+ await idbTransaction(db, STORE_META, "readwrite", (store) =>+ store.put({ id: "verification", value: verificationData }),+ );+ await idbTransaction(db, STORE_META, "readwrite", (store) =>+ store.put({ id: "verification_iv", value: verificationIv }),+ );++ // Re-encrypt all secrets with new key+ for (const secret of decryptedSecrets) {+ const { encrypted, iv } = await encrypt(secret.value, newKey);+ const record: SecureRecord = {+ id: secret.id,+ label: secret.label,+ encryptedData: encrypted,+ iv,+ createdAt: secret.createdAt,+ updatedAt: Date.now(),+ };+ await idbTransaction(db, STORE_SECRETS, "readwrite", (store) =>+ store.put(record),+ );+ }++ derivedKey = newKey;+ resetInactivityTimer();+ return true;+ } finally {+ db.close();+ }+}++/**+ * Save an encrypted secret (API key).+ * Session must be unlocked.+ */+export async function saveSecret(id: string, label: string, value: string): Promise<void> {+ if (!derivedKey) {+ throw new Error("Session is locked. Unlock with master password first.");+ }++ resetInactivityTimer();++ const { encrypted, iv } = await encrypt(value, derivedKey);++ const db = await openDatabase();+ try {+ // Check if record exists to preserve createdAt+ const existing = await idbTransaction<SecureRecord | undefined>(+ db,+ STORE_SECRETS,+ "readonly",+ (store) => store.get(id),+ );++ const record: SecureRecord = {+ id,+ label,+ encryptedData: encrypted,+ iv,+ createdAt: existing?.createdAt ?? Date.now(),+ updatedAt: Date.now(),+ };++ await idbTransaction(db, STORE_SECRETS, "readwrite", (store) =>+ store.put(record),+ );+ } finally {+ db.close();+ }+}++/**+ * Retrieve and decrypt a secret.+ * Session must be unlocked.+ */+export async function getSecret(id: string): Promise<string | null> {+ if (!derivedKey) {+ throw new Error("Session is locked. Unlock with master password first.");+ }++ resetInactivityTimer();++ const db = await openDatabase();+ try {+ const record = await idbTransaction<SecureRecord | undefined>(+ db,+ STORE_SECRETS,+ "readonly",+ (store) => store.get(id),+ );++ if (!record) {+ return null;+ }++ const iv = record.iv instanceof Uint8Array+ ? record.iv+ : new Uint8Array(record.iv as unknown as ArrayBuffer);++ return await decrypt(record.encryptedData, iv, derivedKey);+ } finally {+ db.close();+ }+}++/**+ * Delete a secret.+ */+export async function deleteSecret(id: string): Promise<void> {+ const db = await openDatabase();+ try {+ await idbTransaction(db, STORE_SECRETS, "readwrite", (store) =>+ store.delete(id),+ );+ } finally {+ db.close();+ }+}++/**+ * List all stored secret metadata (without decrypted values).+ */+export async function listSecrets(): Promise<Array<{ id: string; label: string; createdAt: number; updatedAt: number }>> {+ const db = await openDatabase();+ try {+ const records = await new Promise<SecureRecord[]>((resolve, reject) => {+ const tx = db.transaction(STORE_SECRETS, "readonly");+ const store = tx.objectStore(STORE_SECRETS);+ const request = store.getAll();+ request.onsuccess = () => resolve(request.result);+ request.onerror = () => reject(request.error);+ });++ return records.map((r) => ({+ id: r.id,+ label: r.label,+ createdAt: r.createdAt,+ updatedAt: r.updatedAt,+ }));+ } finally {+ db.close();+ }+}++/**+ * Completely reset all secure storage (master password + all secrets).+ * Use with caution — this is irreversible.+ */+export async function resetSecureStorage(): Promise<void> {+ lockSession();++ return new Promise((resolve, reject) => {+ const request = indexedDB.deleteDatabase(SECURE_DB_NAME);+ request.onsuccess = () => resolve();+ request.onerror = () => reject(new Error("Failed to reset secure storage"));+ });+}++// Lock session when tab is closing+if (typeof window !== "undefined") {+ window.addEventListener("beforeunload", () => {+ lockSession();+ });+}diff --git a/apps/web/src/stores/settings-store.ts b/apps/web/src/stores/settings-store.tsnew file mode 100644index 00000000..46ad3d3d--- /dev/null+++ b/apps/web/src/stores/settings-store.ts@@ -0,0 +1,146 @@+import { create } from "zustand";+import { subscribeWithSelector, persist } from "zustand/middleware";++export interface ServiceConfig {+ readonly id: string;+ readonly label: string;+ readonly description: string;+ readonly docsUrl?: string;+}++/**+ * Registry of supported external services that require API keys.+ * Add new services here as the app integrates more third-party APIs.+ */+export const SERVICE_REGISTRY: readonly ServiceConfig[] = [+ {+ id: "elevenlabs",+ label: "ElevenLabs",+ description: "AI voice generation and text-to-speech",+ docsUrl: "https://elevenlabs.io/docs/api-reference",+ },+ {+ id: "openai",+ label: "OpenAI",+ description: "GPT models for script generation and AI features",+ docsUrl: "https://platform.openai.com/docs/api-reference",+ },+ {+ id: "anthropic",+ label: "Anthropic",+ description: "Claude models for AI-assisted editing",+ docsUrl: "https://docs.anthropic.com/en/docs",+ },+ {+ id: "kie-ai",+ label: "Kie.ai",+ description: "AI aggregator for video/image generation, upscaling, and editing",+ docsUrl: "https://kie.ai",+ },+ {+ id: "freepik",+ label: "Freepik",+ description: "AI aggregator for image generation, vectors, and creative assets",+ docsUrl: "https://www.freepik.com/api",+ },+] as const;++export interface SettingsState {+ // General preferences+ autoSave: boolean;+ autoSaveInterval: number; // minutes+ language: string;++ // AI/Service preferences+ defaultTtsProvider: string;+ defaultLlmProvider: string;+ defaultAggregator: string;+ configuredServices: string[]; // IDs of services with stored API keys++ // Settings dialog state+ settingsOpen: boolean;+ settingsTab: string;++ // Actions+ setAutoSave: (enabled: boolean) => void;+ setAutoSaveInterval: (minutes: number) => void;+ setLanguage: (lang: string) => void;+ setDefaultTtsProvider: (provider: string) => void;+ setDefaultLlmProvider: (provider: string) => void;+ setDefaultAggregator: (provider: string) => void;+ addConfiguredService: (serviceId: string) => void;+ removeConfiguredService: (serviceId: string) => void;+ openSettings: (tab?: string) => void;+ closeSettings: () => void;+}++export const useSettingsStore = create<SettingsState>()(+ subscribeWithSelector(+ persist(+ (set, get) => ({+ autoSave: true,+ autoSaveInterval: 5,+ language: "en",++ defaultTtsProvider: "elevenlabs",+ defaultLlmProvider: "openai",+ defaultAggregator: "kie-ai",+ configuredServices: [],++ settingsOpen: false,+ settingsTab: "general",++ setAutoSave: (enabled: boolean) => set({ autoSave: enabled }),++ setAutoSaveInterval: (minutes: number) =>+ set({ autoSaveInterval: Math.max(1, Math.min(30, minutes)) }),++ setLanguage: (lang: string) => set({ language: lang }),++ setDefaultTtsProvider: (provider: string) =>+ set({ defaultTtsProvider: provider }),++ setDefaultLlmProvider: (provider: string) =>+ set({ defaultLlmProvider: provider }),++ setDefaultAggregator: (provider: string) =>+ set({ defaultAggregator: provider }),++ addConfiguredService: (serviceId: string) => {+ const { configuredServices } = get();+ if (!configuredServices.includes(serviceId)) {+ set({ configuredServices: [...configuredServices, serviceId] });+ }+ },++ removeConfiguredService: (serviceId: string) => {+ const { configuredServices } = get();+ set({+ configuredServices: configuredServices.filter((id) => id !== serviceId),+ });+ },++ openSettings: (tab?: string) =>+ set({+ settingsOpen: true,+ settingsTab: tab ?? get().settingsTab,+ }),++ closeSettings: () => set({ settingsOpen: false }),+ }),+ {+ name: "openreel-settings",+ version: 1,+ partialize: (state) => ({+ autoSave: state.autoSave,+ autoSaveInterval: state.autoSaveInterval,+ language: state.language,+ defaultTtsProvider: state.defaultTtsProvider,+ defaultLlmProvider: state.defaultLlmProvider,+ defaultAggregator: state.defaultAggregator,+ configuredServices: state.configuredServices,+ }),+ },+ ),+ ),+);