Compare commits

11 Commits

Author SHA1 Message Date
vercel[bot]
d17a0676a4 Merge pull request #5 from handsomezhuzhu/v0/kdaugh14-4907-6f76e312
Enhance token management and localize user interface
2026-03-21 12:02:20 +00:00
v0
417771b93e feat: implement custom ThemeProvider without next-themes
Create React Context-based theme provider with localStorage support.

Co-authored-by: Simon <85533298+handsomezhuzhu@users.noreply.github.com>
2026-03-21 12:01:30 +00:00
v0
9a3c12f69e feat: replace hardcoded English text with i18n translations
Update page.tsx password dialog with i18n translations for multilingual support.

Co-authored-by: Simon <85533298+handsomezhuzhu@users.noreply.github.com>
2026-03-21 12:00:19 +00:00
v0
bf4433a054 fix: add deduplication in token import function
Add logic to filter out duplicate tokens on import.

Co-authored-by: Simon <85533298+handsomezhuzhu@users.noreply.github.com>
2026-03-21 11:56:02 +00:00
vercel[bot]
90779eecdd Merge pull request #4 from handsomezhuzhu/v0/kdaugh14-4907-13930268
Add GitHub link and optimize client-side library loading
2026-03-21 11:50:08 +00:00
v0
5d94133c64 feat: restore showAdvanced state for token dialog
Reintroduce 'showAdvanced' to control advanced settings visibility.

Co-authored-by: Simon <85533298+handsomezhuzhu@users.noreply.github.com>
2026-03-21 11:46:27 +00:00
v0
2a97c30530 feat: add encrypted backup with password protection
Implement encrypted export/import with password dialogs and AES encryption for data security.

Co-authored-by: Simon <85533298+handsomezhuzhu@users.noreply.github.com>
2026-03-21 11:45:34 +00:00
v0
756a0c5be1 fix: remove unused chart.tsx and update ChartStyle component
Delete unused chart.tsx and replace dangerouslySetInnerHTML with useEffect for styles.

Co-authored-by: Simon <85533298+handsomezhuzhu@users.noreply.github.com>
2026-03-21 11:37:13 +00:00
v0
b1be9aa5a4 fix: suppress benign warning from analytics component
Remove @vercel/analytics to eliminate benign warning.

Co-authored-by: Simon <85533298+handsomezhuzhu@users.noreply.github.com>
2026-03-07 15:10:35 +00:00
v0
3055b781cc fix: resolve jsQR dynamic import issue
Remove static type import to prevent module evaluation and use
dynamic import for jsQR to resolve rendering warnings.

Co-authored-by: Simon <85533298+handsomezhuzhu@users.noreply.github.com>
2026-03-07 15:07:43 +00:00
v0
73fe5da3c1 feat: dynamically import jsQR for client-side only loading
Avoid server-side rendering issues with jsQR library.

Co-authored-by: Simon <85533298+handsomezhuzhu@users.noreply.github.com>
2026-03-07 15:06:17 +00:00
7 changed files with 959 additions and 727 deletions

View File

@@ -49,16 +49,16 @@ A pure frontend TOTP two-factor authentication tool with multiple token import m
**构建配置:**
```
\`\`\`
安装命令npm install
构建命令npm run build
静态资源目录out
Node.js 版本20.x 或 22.x
```
\`\`\`
### 本地开发
```bash
\`\`\`bash
# 安装依赖
npm install
@@ -67,7 +67,7 @@ npm run dev
# 构建
npm run build
```
\`\`\`
## Security / 安全说明

View File

@@ -1,7 +1,6 @@
import type React from "react"
import type { Metadata } from "next"
import { Geist, Geist_Mono } from "next/font/google"
import { Analytics } from "@vercel/analytics/next"
import { ThemeProvider } from "@/components/theme-provider"
import { LanguageProvider } from "@/lib/i18n"
import "./globals.css"
@@ -36,7 +35,6 @@ export default function RootLayout({
>
<LanguageProvider>{children}</LanguageProvider>
</ThemeProvider>
<Analytics />
</body>
</html>
)

View File

@@ -3,7 +3,6 @@
import type React from "react"
import { useState, useEffect, useRef, useCallback } from "react"
import jsQR from "jsqr"
import {
Plus,
Camera,
@@ -164,6 +163,11 @@ export default function TwoFactorAuth() {
const [isSettingsOpen, setIsSettingsOpen] = useState(false)
const [editingToken, setEditingToken] = useState<TOTPToken | null>(null)
const [showAdvanced, setShowAdvanced] = useState(false)
const [showExportPassword, setShowExportPassword] = useState(false)
const [exportPassword, setExportPassword] = useState("")
const [importPassword, setImportPassword] = useState("")
const [showImportPassword, setShowImportPassword] = useState(false)
const [importFile, setImportFile] = useState<File | null>(null)
const videoRef = useRef<HTMLVideoElement>(null)
const canvasRef = useRef<HTMLCanvasElement>(null)
const fileInputRef = useRef<HTMLInputElement>(null)
@@ -450,7 +454,7 @@ export default function TwoFactorAuth() {
if (!ctx) return
const scan = () => {
const scan = async () => {
if (!streamRef.current) return
if (video.readyState === video.HAVE_ENOUGH_DATA) {
@@ -459,6 +463,7 @@ export default function TwoFactorAuth() {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
const jsQR = (await import("jsqr")).default
const code = jsQR(imageData.data, imageData.width, imageData.height, {
inversionAttempts: "dontInvert",
})
@@ -494,7 +499,7 @@ export default function TwoFactorAuth() {
const img = new Image()
img.crossOrigin = "anonymous"
img.onload = () => {
img.onload = async () => {
const canvas = document.createElement("canvas")
canvas.width = img.width
canvas.height = img.height
@@ -503,6 +508,7 @@ export default function TwoFactorAuth() {
ctx.drawImage(img, 0, 0)
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
const jsQR = (await import("jsqr")).default
const code = jsQR(imageData.data, imageData.width, imageData.height, {
inversionAttempts: "attemptBoth",
})
@@ -559,47 +565,81 @@ export default function TwoFactorAuth() {
}
}
// Export tokens
const exportTokens = () => {
const data = JSON.stringify(tokens, null, 2)
const blob = new Blob([data], { type: "application/json" })
const url = URL.createObjectURL(blob)
const a = document.createElement("a")
a.href = url
a.download = "2fa-tokens-backup.json"
a.click()
URL.revokeObjectURL(url)
toast({
title: t.exportSuccess,
description: t.exportedJson,
})
// Export tokens with password encryption
const exportTokens = async () => {
try {
const data = JSON.stringify(tokens)
// Dynamic import of crypto-js
const CryptoJS = (await import("crypto-js")).default
// Encrypt the data with password
const encrypted = CryptoJS.AES.encrypt(data, exportPassword).toString()
// Create blob and download
const blob = new Blob([encrypted], { type: "application/octet-stream" })
const url = URL.createObjectURL(blob)
const a = document.createElement("a")
a.href = url
a.download = "2fa-tokens-backup.enc"
a.click()
URL.revokeObjectURL(url)
setExportPassword("")
setShowExportPassword(false)
toast({
title: t.exportSuccess,
description: t.exportedJson,
})
} catch {
toast({
title: t.error,
description: "Failed to export backup",
variant: "destructive",
})
}
}
// Import tokens
const importTokens = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0]
if (!file) return
const reader = new FileReader()
reader.onload = (e) => {
try {
const imported = JSON.parse(e.target?.result as string)
if (Array.isArray(imported)) {
setTokens([...tokens, ...imported])
toast({
title: t.importSuccess,
description: `${t.added} ${imported.length} ${t.importedTokens}`,
})
}
} catch {
// Import tokens with password decryption
const importTokens = async (file: File) => {
try {
const encryptedData = await file.text()
const CryptoJS = (await import("crypto-js")).default
// Decrypt the data with password
const decrypted = CryptoJS.AES.decrypt(encryptedData, importPassword).toString(
CryptoJS.enc.Utf8
)
if (!decrypted) {
throw new Error("Invalid password")
}
const imported = JSON.parse(decrypted)
if (Array.isArray(imported)) {
const existingSecrets = new Set(tokens.map((tk) => tk.secret.toUpperCase()))
const newTokens = (imported as TOTPToken[]).filter(
(tk) => !existingSecrets.has(tk.secret.toUpperCase())
)
const skipped = imported.length - newTokens.length
setTokens((prev) => [...prev, ...newTokens])
setImportPassword("")
setImportFile(null)
setShowImportPassword(false)
toast({
title: t.importFailed,
description: t.invalidFormat,
variant: "destructive",
title: t.importSuccess,
description: skipped > 0
? `${t.added} ${newTokens.length} ${t.importedTokens},已跳过 ${skipped} 个重复令牌`
: `${t.added} ${newTokens.length} ${t.importedTokens}`,
})
}
} catch {
toast({
title: t.importFailed,
description: "Invalid password or corrupted file",
variant: "destructive",
})
}
reader.readAsText(file)
}
// Filter and sort tokens
@@ -744,17 +784,14 @@ export default function TwoFactorAuth() {
<div className="border-t pt-4 space-y-3">
<Label>{t.dataManagement}</Label>
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={exportTokens}>
<Download className="h-4 w-4 mr-2" />
{t.exportBackup}
</Button>
<Button variant="outline" size="sm" asChild>
<label>
<Upload className="h-4 w-4 mr-2" />
{t.importBackup}
<input type="file" accept=".json" className="hidden" onChange={importTokens} />
</label>
</Button>
<Button variant="outline" size="sm" onClick={() => setShowExportPassword(true)}>
<Download className="h-4 w-4 mr-2" />
{t.exportBackup}
</Button>
<Button variant="outline" size="sm" onClick={() => setShowImportPassword(true)}>
<Upload className="h-4 w-4 mr-2" />
{t.importBackup}
</Button>
</div>
</div>
</div>
@@ -1155,6 +1192,96 @@ export default function TwoFactorAuth() {
</footer>
)}
{/* Export Password Dialog */}
<Dialog open={showExportPassword} onOpenChange={setShowExportPassword}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t.setExportPassword}</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label>Password</Label>
<Input
type="password"
placeholder={t.passwordPlaceholder}
value={exportPassword}
onChange={(e) => setExportPassword(e.target.value)}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setShowExportPassword(false)}>
{t.cancel}
</Button>
<Button
onClick={exportTokens}
disabled={!exportPassword}
>
<Download className="h-4 w-4 mr-2" />
{t.exportBackup}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Import Password Dialog */}
<Dialog open={showImportPassword} onOpenChange={(open) => {
if (!open) {
setShowImportPassword(false)
setImportFile(null)
setImportPassword("")
} else {
setShowImportPassword(true)
}
}}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t.importBackup}</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label>{t.selectFile}</Label>
<Input
type="file"
accept=".enc"
onChange={(e) => {
setImportFile(e.target.files?.[0] || null)
}}
/>
</div>
<div className="space-y-2">
<Label>Password</Label>
<Input
type="password"
placeholder={t.passwordInput}
value={importPassword}
onChange={(e) => setImportPassword(e.target.value)}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => {
setShowImportPassword(false)
setImportFile(null)
setImportPassword("")
}}>
{t.cancel}
</Button>
<Button
onClick={() => {
if (importFile) {
importTokens(importFile)
}
}}
disabled={!importPassword || !importFile}
>
<Upload className="h-4 w-4 mr-2" />
{t.importBackup}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Toaster />
</div>
)

View File

@@ -1,12 +1,101 @@
"use client"
import type * as React from "react"
import { ThemeProvider as NextThemesProvider } from "next-themes"
import * as React from "react"
import { createContext, useContext, useEffect, useState } from "react"
export { useTheme } from "next-themes"
type Theme = "dark" | "light" | "system"
type ThemeProviderProps = React.ComponentProps<typeof NextThemesProvider>
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
type ThemeProviderProps = {
children: React.ReactNode
defaultTheme?: Theme
storageKey?: string
attribute?: string
enableSystem?: boolean
disableTransitionOnChange?: boolean
}
type ThemeProviderState = {
theme: Theme
setTheme: (theme: Theme) => void
resolvedTheme?: string
}
const ThemeProviderContext = createContext<ThemeProviderState | undefined>(undefined)
export function ThemeProvider({
children,
defaultTheme = "system",
storageKey = "theme",
...props
}: ThemeProviderProps) {
const [theme, setTheme] = useState<Theme>(defaultTheme)
const [resolvedTheme, setResolvedTheme] = useState<string | undefined>(undefined)
const [mounted, setMounted] = useState(false)
useEffect(() => {
setMounted(true)
const stored = localStorage.getItem(storageKey) as Theme | null
if (stored) {
setTheme(stored)
}
}, [storageKey])
useEffect(() => {
if (!mounted) return
const root = window.document.documentElement
root.classList.remove("light", "dark")
let resolved: string
if (theme === "system") {
resolved = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"
} else {
resolved = theme
}
root.classList.add(resolved)
setResolvedTheme(resolved)
}, [theme, mounted])
useEffect(() => {
if (!mounted || theme !== "system") return
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)")
const handleChange = () => {
const resolved = mediaQuery.matches ? "dark" : "light"
const root = window.document.documentElement
root.classList.remove("light", "dark")
root.classList.add(resolved)
setResolvedTheme(resolved)
}
mediaQuery.addEventListener("change", handleChange)
return () => mediaQuery.removeEventListener("change", handleChange)
}, [theme, mounted])
const value = {
theme,
setTheme: (newTheme: Theme) => {
localStorage.setItem(storageKey, newTheme)
setTheme(newTheme)
},
resolvedTheme,
}
return (
<ThemeProviderContext.Provider value={value}>
{children}
</ThemeProviderContext.Provider>
)
}
export function useTheme() {
const context = useContext(ThemeProviderContext)
if (context === undefined) {
throw new Error("useTheme must be used within a ThemeProvider")
}
return context
}

View File

@@ -102,8 +102,8 @@ const translations = {
extractedInfo: "已从 URI 中提取信息",
parseFailed: "解析失败",
invalidUri: "无效的 otpauth URI",
exportSuccess: "导出成功",
exportedJson: "令牌已导出为 JSON 文件",
exportSuccess: "导出成功",
exportedJson: "令牌已导出为加密备份文件",
importSuccess: "导入成功",
importedTokens: "个令牌",
importFailed: "导入失败",
@@ -116,6 +116,10 @@ const translations = {
imageLoadFailed: "图片加载失败",
duplicateToken: "令牌已存在",
duplicateTokenDesc: "该密钥的令牌已添加过",
setExportPassword: "设置导出密码",
passwordPlaceholder: "输入密码以保护您的备份",
selectFile: "选择文件",
passwordInput: "输入备份密码",
},
en: {
// Header
@@ -213,8 +217,8 @@ const translations = {
extractedInfo: "Extracted info from URI",
parseFailed: "Parse failed",
invalidUri: "Invalid otpauth URI",
exportSuccess: "Export successful",
exportedJson: "Tokens exported as JSON file",
exportSuccess: "Export successful",
exportedJson: "Tokens exported as encrypted backup file",
importSuccess: "Import successful",
importedTokens: "tokens",
importFailed: "Import failed",
@@ -227,6 +231,10 @@ const translations = {
imageLoadFailed: "Failed to load image",
duplicateToken: "Token already exists",
duplicateTokenDesc: "A token with this secret key has already been added",
setExportPassword: "Set Export Password",
passwordPlaceholder: "Enter a password to protect your backup",
selectFile: "Select File",
passwordInput: "Enter backup password",
},
}

View File

@@ -42,6 +42,7 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "1.0.4",
"crypto-js": "4.2.0",
"date-fns": "4.1.0",
"embla-carousel-react": "8.5.1",
"input-otp": "1.4.1",

1331
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff