This commit is contained in:
2025-07-25 23:24:13 +08:00
parent e34bcd80dd
commit 4f366c12a3
84 changed files with 12608 additions and 2 deletions

30
hw-sign-browser/.gitignore vendored Normal file
View File

@@ -0,0 +1,30 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
.DS_Store
dist
dist-ssr
coverage
*.local
/cypress/videos/
/cypress/screenshots/
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
*.tsbuildinfo

33
hw-sign-browser/README.md Normal file
View File

@@ -0,0 +1,33 @@
# hw-sign-browser
This template should help get you started developing with Vue 3 in Vite.
## Recommended IDE Setup
[VSCode](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur).
## Type Support for `.vue` Imports in TS
TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) to make the TypeScript language service aware of `.vue` types.
## Customize configuration
See [Vite Configuration Reference](https://vite.dev/config/).
## Project Setup
```sh
npm install
```
### Compile and Hot-Reload for Development
```sh
npm run dev
```
### Type-Check, Compile and Minify for Production
```sh
npm run build
```

1
hw-sign-browser/env.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
/// <reference types="vite/client" />

View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DBCS Demo</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

View File

@@ -0,0 +1,31 @@
{
"name": "hw-sign-browser",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --port 3000",
"build": "run-p type-check \"build-only {@}\" --",
"preview": "vite preview",
"build-only": "vite build",
"type-check": "vue-tsc --build"
},
"dependencies": {
"axios": "^1.8.4",
"vue": "^3.5.13"
},
"devDependencies": {
"@tsconfig/node22": "^22.0.0",
"@types/node": "^22.13.9",
"@vitejs/plugin-vue": "^5.2.1",
"@vue/tsconfig": "^0.7.0",
"autoprefixer": "^10.4.21",
"npm-run-all2": "^7.0.2",
"postcss": "^8.5.3",
"tailwindcss": "3",
"typescript": "~5.8.0",
"vite": "^6.2.1",
"vite-plugin-vue-devtools": "^7.7.2",
"vue-tsc": "^2.2.8"
}
}

2886
hw-sign-browser/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

260
hw-sign-browser/src/App.vue Normal file
View File

@@ -0,0 +1,260 @@
<script setup lang="ts">
import { ref, watch, onMounted, computed } from 'vue';
import {
register,
login,
logout,
isAuthenticated as checkAuthService,
toggleSymmetricEncryption,
isSymmetricEncryptionEnabled
} from './services/authService';
// Reactive state
const isAuthenticated = ref(false);
const message = ref('');
const username = ref('');
const password = ref('');
const darkMode = ref(false);
const isLoading = ref(false);
const useSymmetric = ref(true);
// Computed properties for UI state
const messageClass = computed(() => ({
'text-green-600 dark:text-green-400': message.value.includes('successful'),
'text-red-600 dark:text-red-400': !message.value.includes('successful')
}));
const formIsValid = computed(() => username.value && password.value);
// Auth handlers
async function handleRegister() {
if (!formIsValid.value) {
message.value = 'Please enter both username and password';
return;
}
await performAuthOperation(async () => {
await register({ username: username.value, password: password.value });
return 'Registration successful! Please log in.';
});
}
async function handleLogin() {
if (!formIsValid.value) {
message.value = 'Please enter both username and password';
return;
}
await performAuthOperation(async () => {
await login({ username: username.value, password: password.value });
isAuthenticated.value = true;
return 'Login successful!';
});
}
function handleLogout() {
logout();
isAuthenticated.value = false;
}
async function checkAuthentication() {
await performAuthOperation(async () => {
const authenticated = await checkAuthService();
return authenticated
? 'You are successfully authenticated and token protected by hardware!'
: 'You are not authenticated, something went wrong.';
});
}
async function handleToggleEncryption() {
try {
useSymmetric.value = await toggleSymmetricEncryption();
message.value = `Encryption mode changed to ${useSymmetric.value ? 'symmetric (ECDH/HMAC)' : 'asymmetric (signature-based)'}`;
} catch (error) {
console.error('Failed to toggle encryption mode:', error);
message.value = 'Failed to change encryption mode';
}
}
// Helper function to reduce repetitive code in auth operations
async function performAuthOperation(operation: () => Promise<string>) {
isLoading.value = true;
try {
message.value = await operation();
} catch (error) {
message.value = error instanceof Error ? error.message : 'Operation failed';
console.error('Auth operation failed:', error);
} finally {
isLoading.value = false;
}
}
// Toggle dark mode
function toggleDarkMode() {
darkMode.value = !darkMode.value;
}
// Initialization
onMounted(async () => {
try {
isLoading.value = true;
// Check initial auth state and load preferences
isAuthenticated.value = await checkAuthService();
useSymmetric.value = isSymmetricEncryptionEnabled();
// Setup dark mode based on saved preference or system preference
initializeDarkMode();
// Add cleanup handler
window.addEventListener('unload', () => {
if (!isAuthenticated.value) {
logout(); // Clean up IndexedDB if not authenticated
}
});
} catch (e) {
console.debug('Initial setup failed:', e);
} finally {
isLoading.value = false;
}
});
// Initialize dark mode based on saved preference or system preference
function initializeDarkMode() {
darkMode.value = localStorage.getItem('darkMode') === 'true' ||
(localStorage.getItem('darkMode') === null &&
window.matchMedia('(prefers-color-scheme: dark)').matches);
applyDarkMode();
}
// Apply dark mode to document
function applyDarkMode() {
if (darkMode.value) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
}
// Watch for dark mode changes to save preference and apply
watch(darkMode, (newValue) => {
localStorage.setItem('darkMode', newValue.toString());
applyDarkMode();
});
</script>
<template>
<div class="min-h-screen w-full flex items-center justify-center bg-gray-100 dark:bg-gray-900">
<!-- Loading overlay -->
<div v-if="isLoading" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
<div class="bg-white dark:bg-gray-800 rounded-lg p-4 flex flex-col items-center shadow-lg">
<svg class="animate-spin h-8 w-8 text-indigo-600 dark:text-indigo-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
</svg>
<p class="mt-4 text-gray-700 dark:text-gray-300">Processing...</p>
</div>
</div>
<div
class="w-full max-w-lg bg-white dark:bg-gray-800 rounded-lg shadow-lg p-8 border border-gray-200 dark:border-gray-700">
<h1 class="text-2xl font-bold text-center mb-6 text-gray-900 dark:text-gray-100">User Authentication</h1>
<!-- Login Form -->
<div v-if="!isAuthenticated" class="space-y-6">
<div>
<label for="username" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Username</label>
<input v-model="username" id="username" type="text" :disabled="isLoading"
class="mt-2 block w-full rounded-lg border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-gray-100 px-4 py-2"
placeholder="Enter your username" />
</div>
<div>
<label for="password" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Password</label>
<input v-model="password" id="password" type="password" :disabled="isLoading"
class="mt-2 block w-full rounded-lg border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-gray-100 px-4 py-2"
placeholder="Enter your password" />
</div>
<div class="flex justify-between">
<button @click="handleRegister" :disabled="isLoading" class="btn-green">
Register
</button>
<button @click="handleLogin" :disabled="isLoading" class="btn-primary">
Login
</button>
</div>
</div>
<!-- Authenticated View -->
<div v-else class="text-center">
<p class="text-lg font-medium text-green-600 dark:text-green-400 mb-4">You are authenticated!</p>
<div class="space-y-4">
<button @click="checkAuthentication" :disabled="isLoading" class="btn-primary w-full">
Check Hardware Sign Status
</button>
<button @click="handleToggleEncryption" class="btn-yellow w-full">
{{ useSymmetric ? 'Using ECDH+HMAC (Faster)' : 'Using Asymmetric Signatures' }}
</button>
<button @click="handleLogout" class="btn-danger w-full">
Logout
</button>
</div>
</div>
<!-- Status message -->
<p class="mt-4 text-center text-sm" :class="messageClass">
{{ message ?? 'Ready' }}
</p>
<!-- Dark mode toggle -->
<div class="mt-6 flex justify-end">
<button @click="toggleDarkMode"
class="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 text-2xl">
{{ darkMode ? '☀️' : '🌙' }}
</button>
</div>
</div>
</div>
</template>
<style scoped>
body {
font-family: 'Inter', sans-serif;
}
/* Button styles */
.btn-primary {
@apply bg-indigo-600 text-white py-2 px-4 rounded-lg hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 dark:focus:ring-offset-gray-900 disabled:opacity-50 disabled:cursor-not-allowed;
}
.btn-green {
@apply bg-green-600 text-white py-2 px-4 rounded-lg hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 dark:focus:ring-offset-gray-900 disabled:opacity-50 disabled:cursor-not-allowed;
}
.btn-yellow {
@apply bg-yellow-600 text-white py-2 px-4 rounded-lg hover:bg-yellow-700 focus:outline-none focus:ring-2 focus:ring-yellow-500 focus:ring-offset-2 dark:focus:ring-offset-gray-900;
}
.btn-danger {
@apply bg-red-600 text-white py-2 px-4 rounded-lg hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2;
}
/* Add styles for the loading overlay */
.fixed {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.bg-opacity-50 {
background-color: rgba(0, 0, 0, 0.5);
}
.z-50 {
z-index: 50;
}
</style>

View File

@@ -0,0 +1,90 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/* color palette from <https://github.com/vuejs/theme> */
:root {
--vt-c-white: #ffffff;
--vt-c-white-soft: #f8f8f8;
--vt-c-white-mute: #f2f2f2;
--vt-c-black: #181818;
--vt-c-black-soft: #222222;
--vt-c-black-mute: #282828;
--vt-c-indigo: #2c3e50;
--vt-c-divider-light-1: rgba(60, 60, 60, 0.29);
--vt-c-divider-light-2: rgba(60, 60, 60, 0.12);
--vt-c-divider-dark-1: rgba(84, 84, 84, 0.65);
--vt-c-divider-dark-2: rgba(84, 84, 84, 0.48);
--vt-c-text-light-1: var(--vt-c-indigo);
--vt-c-text-light-2: rgba(60, 60, 60, 0.66);
--vt-c-text-dark-1: var(--vt-c-white);
--vt-c-text-dark-2: rgba(235, 235, 235, 0.64);
}
/* semantic color variables for this project */
:root {
--color-background: var(--vt-c-white);
--color-background-soft: var(--vt-c-white-soft);
--color-background-mute: var(--vt-c-white-mute);
--color-border: var(--vt-c-divider-light-2);
--color-border-hover: var(--vt-c-divider-light-1);
--color-heading: var(--vt-c-text-light-1);
--color-text: var(--vt-c-text-light-1);
--section-gap: 160px;
}
@media (prefers-color-scheme: dark) {
:root {
--color-background: var(--vt-c-black);
--color-background-soft: var(--vt-c-black-soft);
--color-background-mute: var(--vt-c-black-mute);
--color-border: var(--vt-c-divider-dark-2);
--color-border-hover: var(--vt-c-divider-dark-1);
--color-heading: var(--vt-c-text-dark-1);
--color-text: var(--vt-c-text-dark-2);
}
}
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
font-weight: normal;
}
body {
min-height: 100vh;
color: var(--color-text);
background: var(--color-background);
transition:
color 0.5s,
background-color 0.5s;
line-height: 1.6;
font-family:
Inter,
-apple-system,
BlinkMacSystemFont,
'Segoe UI',
Roboto,
Oxygen,
Ubuntu,
Cantarell,
'Fira Sans',
'Droid Sans',
'Helvetica Neue',
sans-serif;
font-size: 15px;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 261.76 226.69"><path d="M161.096.001l-30.225 52.351L100.647.001H-.005l130.877 226.688L261.749.001z" fill="#41b883"/><path d="M161.096.001l-30.225 52.351L100.647.001H52.346l78.526 136.01L209.398.001z" fill="#34495e"/></svg>

After

Width:  |  Height:  |  Size: 276 B

View File

@@ -0,0 +1,20 @@
@import './base.css';
#app {
margin: 0 auto;
font-weight: normal;
}
a,
.green {
text-decoration: none;
color: hsla(160, 100%, 37%, 1);
transition: 0.4s;
padding: 3px;
}
@media (hover: hover) {
a:hover {
background-color: hsla(160, 100%, 37%, 0.2);
}
}

View File

@@ -0,0 +1,5 @@
import './assets/main.css';
import { createApp } from 'vue';
import App from './App.vue';
createApp(App).mount('#app');

View File

@@ -0,0 +1,701 @@
import axios, { AxiosError } from 'axios';
// Response type definitions
interface ServerResponse {
message?: string;
}
interface LoginResponse extends ServerResponse {
token: string;
}
interface AuthResponse extends ServerResponse {
authenticated: boolean;
}
const apiClient = axios.create({
baseURL: import.meta.env.DEV ? 'http://127.0.0.1:28280' : 'https://dbcs-api.ovo.fan',
headers: { 'Content-Type': 'application/json' },
});
// Storage constants
const DB_NAME = 'DBCS';
const DB_VERSION = 1;
const STORE_NAME = 'auth_data';
const HW_KEY_ID = 'hardware_key';
const AUTH_TOKEN_ID = 'auth_token';
const ACCEL_KEY_ID_STORE = 'accel_key_id';
const PREFER_SYMMETRIC_STORE = 'prefer_symmetric';
// In-memory state
let hardwareKey: CryptoKeyPair | null = null;
let accelerationKey: CryptoKeyPair | null = null;
let accelerationKeyId: string | null = null;
let ecdhAccelerationKey: CryptoKeyPair | null = null;
let symmetricKey: CryptoKey | null = null;
let preferSymmetricEncryption = true; // Default to true for better performance
// Add debug logger
function debugLog(step: string, message: string, data?: any): void {
const timestamp = new Date().toISOString();
console.debug(`[${timestamp}] [DBCS] ${step}: ${message}`, data || '');
}
// IndexedDB helper functions
async function openDB(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
request.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME);
}
};
});
}
async function storeData(key: string, value: any): Promise<void> {
const db = await openDB();
return new Promise((resolve, reject) => {
const transaction = db.transaction(STORE_NAME, 'readwrite');
const store = transaction.objectStore(STORE_NAME);
const request = store.put(value, key);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve();
transaction.oncomplete = () => db.close();
});
}
async function loadData(key: string): Promise<any> {
const db = await openDB();
return new Promise((resolve, reject) => {
const transaction = db.transaction(STORE_NAME, 'readonly');
const store = transaction.objectStore(STORE_NAME);
const request = store.get(key);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result || null);
transaction.oncomplete = () => db.close();
});
}
async function deleteData(key: string): Promise<void> {
const db = await openDB();
return new Promise((resolve, reject) => {
const transaction = db.transaction(STORE_NAME, 'readwrite');
const store = transaction.objectStore(STORE_NAME);
const request = store.delete(key);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve();
transaction.oncomplete = () => db.close();
});
}
// Key storage wrappers
const storage = {
hardwareKey: {
store: (key: CryptoKeyPair) => storeData(HW_KEY_ID, key),
load: () => loadData(HW_KEY_ID) as Promise<CryptoKeyPair | null>,
delete: () => deleteData(HW_KEY_ID)
},
authToken: {
store: (token: string) => storeData(AUTH_TOKEN_ID, token),
load: () => loadData(AUTH_TOKEN_ID) as Promise<string | null>,
delete: () => deleteData(AUTH_TOKEN_ID)
},
preferSymmetric: {
store: (value: boolean) => storeData(PREFER_SYMMETRIC_STORE, value),
load: async () => {
const value = await loadData(PREFER_SYMMETRIC_STORE);
return value !== false; // Default to true if not set
}
}
};
// Supported key algorithms
type KeyAlgorithm = 'Ed25519' | 'ECDSA' | 'RSA-PSS' | 'ECDH';
// Generate keys with fallback support
async function tryGenerateKey(type: KeyAlgorithm, extractable: boolean): Promise<CryptoKeyPair | null> {
if (!window.crypto?.subtle) return null;
try {
debugLog('Key Generation', `Attempting to generate ${type} key, extractable: ${extractable}`);
switch (type) {
case 'Ed25519':
return await window.crypto.subtle.generateKey(
{ name: 'Ed25519' },
extractable,
['sign', 'verify']
);
case 'ECDSA':
return await window.crypto.subtle.generateKey(
{ name: 'ECDSA', namedCurve: 'P-256' },
extractable,
['sign', 'verify']
);
case 'RSA-PSS':
return await window.crypto.subtle.generateKey(
{
name: 'RSA-PSS',
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: 'SHA-256',
},
extractable,
['sign', 'verify']
);
case 'ECDH':
return await window.crypto.subtle.generateKey(
{ name: 'ECDH', namedCurve: 'P-256' },
extractable,
['deriveKey', 'deriveBits']
);
default:
return null;
}
} catch (e) {
debugLog('Key Generation', `Failed to generate ${type} key:`, e);
console.debug(`Failed to generate ${type} key:`, e);
return null;
}
}
async function generateKey(extractable: boolean, type?: KeyAlgorithm): Promise<CryptoKeyPair> {
if (!window.crypto?.subtle) {
debugLog('Key Generation', 'Web Crypto API not supported');
throw new Error('Web Crypto API not supported');
}
// If a specific algorithm is requested, try it first
if (type) {
const key = await tryGenerateKey(type, extractable);
if (key) {
console.debug(`Using ${type} for key`);
debugLog('Key Generation', `Successfully generated ${key.publicKey.algorithm.name} key`);
return key;
}
}
// Try algorithms in order of preference
const algorithms: KeyAlgorithm[] = ['Ed25519', 'ECDSA', 'RSA-PSS'];
for (const algo of algorithms) {
const key = await tryGenerateKey(algo, extractable);
if (key) {
console.debug(`Using ${algo} for ${extractable ? 'acceleration' : 'hardware'} key`);
debugLog('Key Generation', `Successfully generated ${key.publicKey.algorithm.name} key`);
return key;
}
}
throw new Error('No supported key algorithms available');
}
// Utility functions for data conversion and encryption
function arrayBufferToBase64(buffer: ArrayBuffer): string {
return btoa(String.fromCharCode(...new Uint8Array(buffer)));
}
function base64ToArrayBuffer(base64: string): ArrayBuffer {
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
async function exportPublicKey(key: CryptoKey): Promise<string> {
// Choose export format based on algorithm
const format = ['Ed25519', 'ECDH'].includes(key.algorithm.name) ? 'raw' : 'spki';
const exported = await window.crypto.subtle.exportKey(format, key);
return arrayBufferToBase64(exported);
}
// HMAC generation for ECDH-derived keys
async function generateHMAC(key: CryptoKey, data: string): Promise<string> {
debugLog('HMAC', `Generating HMAC for data (${data.length} chars)`, {
dataPreview: data.substring(0, 20) + '...',
keyAlgo: key.algorithm.name,
keyUsages: key.usages
});
const encoder = new TextEncoder();
const dataBuffer = encoder.encode(data);
const signature = await window.crypto.subtle.sign(
{ name: 'HMAC' },
key,
dataBuffer
);
debugLog('HMAC', `Generated HMAC: ${signature.byteLength} bytes`);
return arrayBufferToBase64(signature);
}
// Function to derive shared secret and create HMAC key
async function deriveSharedKey(privateKey: CryptoKey, publicKeyBase64: string): Promise<CryptoKey> {
debugLog('ECDH', 'Starting key derivation process', {
publicKeyLength: publicKeyBase64.length,
privateKeyAlgo: privateKey.algorithm.name
});
try {
// Import the server's public key
const publicKeyData = base64ToArrayBuffer(publicKeyBase64);
// Import the raw key data for ECDH
const serverPublicKey = await window.crypto.subtle.importKey(
'raw',
publicKeyData,
{ name: 'ECDH', namedCurve: 'P-256' },
false,
[]
);
// Derive bits from the ECDH exchange
const derivedBits = await window.crypto.subtle.deriveBits(
{ name: 'ECDH', public: serverPublicKey },
privateKey,
256 // 256 bits for HMAC key
);
debugLog('ECDH', 'Derived HMAC key successfully', {
derivedBitsLength: derivedBits.byteLength
});
// Create HMAC key from the derived bits
return await window.crypto.subtle.importKey(
'raw',
derivedBits,
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign', 'verify']
);
} catch (error) {
debugLog('ECDH', 'Failed to derive shared key', error);
console.error('Failed to derive shared key:', error);
throw new Error('Failed to derive HMAC key');
}
}
// Key management functions
async function setupECDHAccelerationKey(): Promise<{
ecdhPubKeyBase64: string;
ecdhPubKeySig: string;
}> {
debugLog('ECDH Setup', 'Generating ECDH acceleration key pair');
try {
// Generate ECDH key pair - set extractable to FALSE for better security
ecdhAccelerationKey = await generateKey(false, 'ECDH');
// Export the public key
const ecdhPubKeyBase64 = await exportPublicKey(ecdhAccelerationKey.publicKey);
debugLog('ECDH Setup', 'ECDH key pair generated successfully', {
publicKeyLength: ecdhPubKeyBase64.length
});
// Sign the public key with hardware key
const ecdhPubKeySig = await signWithKey(hardwareKey!.privateKey, ecdhPubKeyBase64);
debugLog('ECDH Setup', 'Signed ECDH public key with hardware key');
return { ecdhPubKeyBase64, ecdhPubKeySig };
} catch (error) {
debugLog('ECDH Setup', 'Failed to setup ECDH key', error);
console.error('Failed to setup ECDH key:', error);
throw error;
}
}
async function setupAccelerationKey(): Promise<{ accelPubKeyBase64: string; accelPubKeySig: string; keyType: string }> {
if (accelerationKey) {
const accelPubKeyBase64 = await exportPublicKey(accelerationKey.publicKey);
const accelPubKeySig = await signWithKey(hardwareKey!.privateKey, accelPubKeyBase64);
const keyType = accelerationKey.publicKey.algorithm.name.toLowerCase();
return { accelPubKeyBase64, accelPubKeySig, keyType };
}
try {
// Generate new acceleration key
accelerationKey = await generateKey(true);
// Export acceleration public key
const accelPubKeyBase64 = await exportPublicKey(accelerationKey.publicKey);
const accelPubKeySig = await signWithKey(hardwareKey!.privateKey, accelPubKeyBase64);
const keyType = accelerationKey.publicKey.algorithm.name.toLowerCase();
return { accelPubKeyBase64, accelPubKeySig, keyType };
} catch (error) {
// Reset the acceleration key on failure
accelerationKey = null;
accelerationKeyId = null;
throw error;
}
}
async function checkStorageSupport(): Promise<boolean> {
if (!window.indexedDB) return false;
try {
const db = await openDB();
db.close();
return true;
} catch (e) {
console.debug('IndexedDB not available:', e);
return false;
}
}
async function initHardwareKey(): Promise<void> {
debugLog('Hardware Key', 'Initializing hardware key');
if (hardwareKey) {
debugLog('Hardware Key', 'Hardware key already initialized');
return; // Already initialized
}
// Check storage support first
const hasStorage = await checkStorageSupport();
if (!hasStorage) {
throw new Error('Secure key storage is not available in your browser. Please enable IndexedDB or use a modern browser.');
}
// Try to load existing key first
hardwareKey = await storage.hardwareKey.load();
debugLog('Hardware Key', hardwareKey ? 'Loaded existing hardware key' : 'Generating new hardware key');
if (!hardwareKey) {
// Generate new key if none exists
hardwareKey = await generateKey(false); // Ensure hardware key is non-exportable
await storage.hardwareKey.store(hardwareKey);
}
debugLog('Hardware Key', 'Hardware key initialization complete');
}
async function init(): Promise<void> {
try {
// Load hardware key and auth token
await initHardwareKey();
// Load symmetric encryption preference
preferSymmetricEncryption = await storage.preferSymmetric.load();
} catch (error) {
console.error('Failed to initialize auth service', error);
}
}
async function signWithKey(key: CryptoKey, data: string): Promise<string> {
const dataBuffer = new TextEncoder().encode(data);
// Configure algorithm parameters based on key type
const params = key.algorithm.name === 'RSA-PSS'
? { name: 'RSA-PSS', saltLength: 32 }
: key.algorithm.name === 'ECDSA'
? { name: 'ECDSA', hash: 'SHA-256' }
: { name: key.algorithm.name };
const signature = await window.crypto.subtle.sign(
params,
key,
dataBuffer
);
return arrayBufferToBase64(signature);
}
// Primary authentication function
async function authenticatedRequest<T>(
method: 'get' | 'post',
url: string,
data?: any
): Promise<T> {
debugLog('Auth Request', `${method.toUpperCase()} ${url}`, data ? { dataType: typeof data } : {});
try {
const token = await storage.authToken.load();
if (!token) throw new Error('Not authenticated');
// Ensure hardware key is ready
await initHardwareKey();
// Prepare request data
const timestamp = Date.now().toString();
const requestData = data ? JSON.stringify(data) : timestamp;
const headers: Record<string, string> = { 'Authorization': `Bearer ${token}` };
debugLog('Auth Request', `Using ${accelerationKeyId ? 'existing' : 'new'} acceleration key`);
// Handle different authentication methods based on available keys
if (accelerationKeyId) {
// Use existing acceleration key ID
await handleExistingKeyAuth(headers, requestData);
} else {
// Register new acceleration key
await handleNewKeyRegistration(headers, requestData);
}
// Make the authenticated request
const response = await apiClient.request<T>({
method,
url,
data,
headers
});
// Process response if this was a new key registration
if (!accelerationKeyId && response.headers['x-rpc-sec-bound-token-accel-pub-id']) {
const headers = Object.fromEntries(
Object.entries(response.headers).map(([key, value]) => [key, String(value)])
);
await processKeyRegistrationResponse(headers);
}
debugLog('Auth Request', 'Request completed successfully');
return response.data;
} catch (error) {
debugLog('Auth Request', 'Request failed', error);
if (axios.isAxiosError(error)) {
const axiosError = error as AxiosError<ServerResponse>;
if (axiosError.response?.data?.message) {
throw new Error(axiosError.response.data.message);
}
}
throw error;
}
}
// Helper for existing key authentication
async function handleExistingKeyAuth(headers: Record<string, string>, requestData: string): Promise<void> {
debugLog('Existing Auth', 'Setting up authentication with existing key', {
keyType: symmetricKey && preferSymmetricEncryption ? 'symmetric' : 'asymmetric',
dataLength: requestData.length,
accelerationKeyId
});
if (symmetricKey && preferSymmetricEncryption) {
// Use HMAC for authentication
debugLog('Existing Auth', 'Using HMAC authentication');
const hmac = await generateHMAC(symmetricKey, requestData);
debugLog('Existing Auth', `Generated HMAC signature: ${hmac.substring(0, 20)}...`);
headers['x-rpc-sec-bound-token-data'] = requestData;
headers['x-rpc-sec-bound-token-data-sig'] = hmac; // Unified header for signature
headers['x-rpc-sec-bound-token-accel-pub-id'] = accelerationKeyId!;
} else if (accelerationKey) {
// Use asymmetric signatures
debugLog('Existing Auth', 'Using asymmetric signature authentication');
const signature = await signWithKey(accelerationKey.privateKey, requestData);
debugLog('Existing Auth', `Generated signature: ${signature.substring(0, 20)}...`);
headers['x-rpc-sec-bound-token-data'] = requestData;
headers['x-rpc-sec-bound-token-data-sig'] = signature; // Unified header for signature
headers['x-rpc-sec-bound-token-accel-pub-id'] = accelerationKeyId!;
} else {
debugLog('Existing Auth', 'Invalid key state, forcing new registration');
accelerationKeyId = null;
throw new Error('Invalid key state, will register new key');
}
}
// Helper for new key registration
async function handleNewKeyRegistration(headers: Record<string, string>, requestData: string): Promise<void> {
debugLog('New Key Auth', 'Registering new acceleration key', {
preferSymmetric: preferSymmetricEncryption
});
let isEcdhGenerated = false;
// Try ECDH key exchange if supported and preferred
if (window.crypto.subtle && preferSymmetricEncryption) {
try {
// Setup ECDH key exchange
const { ecdhPubKeyBase64, ecdhPubKeySig } = await setupECDHAccelerationKey();
// Sign request data with hardware key for this first exchange
const dataSig = await signWithKey(hardwareKey!.privateKey, requestData);
headers['x-rpc-sec-bound-token-accel-pub'] = ecdhPubKeyBase64;
headers['x-rpc-sec-bound-token-accel-pub-type'] = 'ecdh';
headers['x-rpc-sec-bound-token-accel-pub-sig'] = ecdhPubKeySig;
headers['x-rpc-sec-bound-token-data'] = requestData;
headers['x-rpc-sec-bound-token-data-sig'] = dataSig;
isEcdhGenerated = true;
} catch (error) {
debugLog('New Key Auth', 'ECDH key exchange failed, falling back to asymmetric keys', error);
console.debug('ECDH key exchange failed, falling back to asymmetric keys', error);
}
}
// Fall back to asymmetric keys if ECDH isn't available or failed
if (!isEcdhGenerated) {
debugLog('New Key Auth', 'Using asymmetric key pair');
const { accelPubKeyBase64, accelPubKeySig, keyType } = await setupAccelerationKey();
const signature = await signWithKey(accelerationKey!.privateKey, requestData);
headers['x-rpc-sec-bound-token-accel-pub'] = accelPubKeyBase64;
headers['x-rpc-sec-bound-token-accel-pub-type'] = keyType;
headers['x-rpc-sec-bound-token-accel-pub-sig'] = accelPubKeySig;
headers['x-rpc-sec-bound-token-data'] = requestData;
headers['x-rpc-sec-bound-token-data-sig'] = signature;
}
debugLog('New Key Auth', 'New key registration headers set up');
}
// Process key registration response
async function processKeyRegistrationResponse(headers: Record<string, string>): Promise<void> {
debugLog('Key Registration', 'Processing key registration response', headers);
// Store the key ID
const keyId = headers['x-rpc-sec-bound-token-accel-pub-id'];
if (keyId) {
debugLog('Key Registration', `Received key ID: ${keyId}`);
accelerationKeyId = keyId;
// If this was an ECDH key exchange, process server's public key
const serverPubKey = headers['x-rpc-sec-bound-token-accel-pub'];
if (ecdhAccelerationKey && serverPubKey && preferSymmetricEncryption) {
debugLog('Key Registration', 'Processing ECDH server public key', {
publicKeyLength: serverPubKey.length
});
try {
// Derive the shared secret and create the HMAC key
symmetricKey = await deriveSharedKey(ecdhAccelerationKey.privateKey, serverPubKey);
debugLog('Key Registration', 'ECDH key exchange completed successfully');
console.debug('ECDH key exchange successful, HMAC authentication enabled');
} catch (error) {
debugLog('Key Registration', 'Failed to establish HMAC key', error);
console.error('Failed to establish HMAC key:', error);
}
}
} else {
debugLog('Key Registration', 'No acceleration key ID received');
}
}
// Public API functions
export async function toggleSymmetricEncryption(): Promise<boolean> {
debugLog('API', `Toggling symmetric encryption from ${preferSymmetricEncryption} to ${!preferSymmetricEncryption}`);
// Toggle the preference
preferSymmetricEncryption = !preferSymmetricEncryption;
// Store the updated preference
await storage.preferSymmetric.store(preferSymmetricEncryption);
// If disabling, clear the symmetric key (we'll keep using asymmetric with existing key ID)
if (!preferSymmetricEncryption) {
symmetricKey = null;
}
// Reset key state
accelerationKeyId = null;
debugLog('API', `Symmetric encryption set to ${preferSymmetricEncryption}`);
return preferSymmetricEncryption;
}
export function isSymmetricEncryptionEnabled(): boolean {
return preferSymmetricEncryption;
}
export async function register(userData: { username: string; password: string }) {
const response = await apiClient.post<ServerResponse>('/register', userData);
return response.data;
}
export async function login(credentials: { username: string; password: string }) {
debugLog('API', 'Login attempt', { username: credentials.username });
// Ensure hardware key is ready for login
await initHardwareKey();
// Get hardware public key
const hwPubKey = await exportPublicKey(hardwareKey!.publicKey);
const hwKeyType = hardwareKey!.publicKey.algorithm.name.toLowerCase();
debugLog('API', 'Hardware key prepared', {
keyType: hwKeyType,
publicKeyLength: hwPubKey.length
});
// Setup request with hardware key headers
const response = await apiClient.post<LoginResponse>(
'/login',
credentials,
{
headers: {
'x-rpc-sec-bound-token-hw-pub': hwPubKey,
'x-rpc-sec-bound-token-hw-pub-type': hwKeyType,
}
}
);
// Store the auth token
await storage.authToken.store(response.data.token);
// Clear any existing acceleration keys when logging in
accelerationKey = null;
accelerationKeyId = null;
ecdhAccelerationKey = null;
symmetricKey = null;
debugLog('API', 'Login successful');
return response.data;
}
export async function isAuthenticated(): Promise<boolean> {
debugLog('API', 'Checking authentication status');
try {
const token = await storage.authToken.load();
if (!token) return false;
// Make an authenticated request to verify the token is valid
const response = await authenticatedRequest<AuthResponse>('get', '/authenticated');
debugLog('API', `Authentication status: ${response.authenticated}`);
return response.authenticated;
} catch (error) {
debugLog('API', 'Authentication check failed', error);
console.debug('Authentication check failed:', error);
return false;
}
}
export function logout(): void {
debugLog('API', 'Logging out, clearing all keys and tokens');
Promise.all([
storage.authToken.delete(),
storage.hardwareKey.delete(),
]).catch(console.error);
// Clear all sensitive data from memory
hardwareKey = null;
accelerationKey = null;
accelerationKeyId = null;
ecdhAccelerationKey = null;
symmetricKey = null;
}
// Initialize the service on module load
init().catch(error => {
debugLog('Init', 'Service initialization failed', error);
console.error(error);
});
// Add window unload handler to clear sensitive keys from memory
if (typeof window !== 'undefined') {
window.addEventListener('beforeunload', () => {
ecdhAccelerationKey = null;
symmetricKey = null;
});
}

View File

@@ -0,0 +1,9 @@
/** @type {import('tailwindcss').Config} */
export default {
content: ["./index.html", "./src/**/*.{vue,js,ts,jsx,tsx}"],
darkMode: 'class',
theme: {
extend: {},
},
plugins: [],
};

View File

@@ -0,0 +1,12 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
"exclude": ["src/**/__tests__/*"],
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"paths": {
"@/*": ["./src/*"]
}
}
}

View File

@@ -0,0 +1,11 @@
{
"files": [],
"references": [
{
"path": "./tsconfig.node.json"
},
{
"path": "./tsconfig.app.json"
}
]
}

View File

@@ -0,0 +1,19 @@
{
"extends": "@tsconfig/node22/tsconfig.json",
"include": [
"vite.config.*",
"vitest.config.*",
"cypress.config.*",
"nightwatch.conf.*",
"playwright.config.*",
"eslint.config.*"
],
"compilerOptions": {
"noEmit": true,
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"module": "ESNext",
"moduleResolution": "Bundler",
"types": ["node"]
}
}

View File

@@ -0,0 +1,18 @@
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
// https://vite.dev/config/
export default defineConfig({
plugins: [
vue(),
vueDevTools(),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
},
},
})