Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e57f81c9c3 | |||
| 0a5811cc68 | |||
| 0d94b684bf | |||
| 3c2579b3ed | |||
| c413ee1cf6 |
@@ -21,12 +21,8 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- platform: macos-14 # apple silicon
|
||||
args: "--target aarch64-apple-darwin --bundles app,updater"
|
||||
- platform: macos-13 # intel
|
||||
args: "--target x86_64-apple-darwin --bundles app,updater"
|
||||
- platform: ubuntu-22.04
|
||||
args: ""
|
||||
- platform: macos-14 # universal binary covers both Intel + Apple Silicon
|
||||
args: "--target universal-apple-darwin --bundles app,updater"
|
||||
- platform: windows-latest
|
||||
args: ""
|
||||
|
||||
@@ -47,13 +43,7 @@ jobs:
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.platform == 'macos-14' && 'aarch64-apple-darwin' || matrix.platform == 'macos-13' && 'x86_64-apple-darwin' || '' }}
|
||||
|
||||
- name: Install Linux build deps
|
||||
if: matrix.platform == 'ubuntu-22.04'
|
||||
run: |
|
||||
sudo apt update
|
||||
sudo apt install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf libgtk-3-dev
|
||||
targets: ${{ matrix.platform == 'macos-14' && 'aarch64-apple-darwin,x86_64-apple-darwin' || '' }}
|
||||
|
||||
- name: Install JS deps
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
@@ -1 +1 @@
|
||||
dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDg0Q0Y0N0I1Q0U2MjBEMzcKUldRM0RXTE90VWZQaERVWnBGNTVKUVZ2MWZyRktaaDFJaXVWc3NGNUZVb08yVHNxaVp2c2dOL2oK
|
||||
dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDQ5N0U0RDcxOTU2OEQ0QUUKUldTdTFHaVZjVTErU1ZuMk1lWXBUbEcyS1RHYzJQN3k4VDdiUGRvRnVJYVJKR3BxWG1xcENpdlYK
|
||||
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 3.0 KiB |
|
Before Width: | Height: | Size: 23 KiB After Width: | Height: | Size: 4.9 KiB |
|
Before Width: | Height: | Size: 2.2 KiB After Width: | Height: | Size: 948 B |
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 2.8 KiB |
|
After Width: | Height: | Size: 3.4 KiB |
|
After Width: | Height: | Size: 3.6 KiB |
|
After Width: | Height: | Size: 5.5 KiB |
|
After Width: | Height: | Size: 928 B |
|
After Width: | Height: | Size: 5.8 KiB |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 2.5 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
</adaptive-icon>
|
||||
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 3.6 KiB |
|
After Width: | Height: | Size: 2.3 KiB |
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 2.7 KiB |
|
After Width: | Height: | Size: 2.2 KiB |
|
After Width: | Height: | Size: 4.5 KiB |
|
After Width: | Height: | Size: 4.5 KiB |
|
After Width: | Height: | Size: 4.9 KiB |
|
After Width: | Height: | Size: 7.3 KiB |
|
After Width: | Height: | Size: 6.1 KiB |
|
After Width: | Height: | Size: 8.4 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 7.7 KiB |
|
After Width: | Height: | Size: 12 KiB |
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="ic_launcher_background">#fff</color>
|
||||
</resources>
|
||||
|
Before Width: | Height: | Size: 37 KiB After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 8.7 KiB |
|
After Width: | Height: | Size: 611 B |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 1.6 KiB |
|
After Width: | Height: | Size: 858 B |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 2.3 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 2.8 KiB |
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 2.8 KiB |
|
After Width: | Height: | Size: 3.7 KiB |
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 3.4 KiB |
|
After Width: | Height: | Size: 3.6 KiB |
@@ -0,0 +1,14 @@
|
||||
<svg viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<clipPath id="cp02">
|
||||
<polygon points="32,5 57,19 57,45 32,59 7,45 7,19"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
<polygon points="32,5 57,19 57,45 32,59 7,45 7,19" fill="#2e1065"/>
|
||||
<g clip-path="url(#cp02)">
|
||||
<path d="M-4 32 Q 16 18 32 32 T 68 32 L 68 64 L -4 64 Z" fill="#7c4dff"/>
|
||||
<path d="M-4 32 Q 16 18 32 32 T 68 32" stroke="#a78bfa" stroke-width="2" fill="none"/>
|
||||
</g>
|
||||
<polygon points="32,5 57,19 57,45 32,59 7,45 7,19"
|
||||
fill="none" stroke="#a78bfa" stroke-width="1.5" opacity="0.4"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 667 B |
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "ChatApp",
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.1",
|
||||
"identifier": "com.meinname.chatapp",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm vite:dev",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
|
||||
|
||||
import { AppShell } from './components/AppShell';
|
||||
import { UpdateToast } from './components/UpdateToast';
|
||||
import { RequireAdmin, RequireAuth, RequireDevice } from './components/guards';
|
||||
import { AuthProvider } from './context/AuthContext';
|
||||
import { CallProvider } from './context/CallContext';
|
||||
@@ -44,6 +45,7 @@ export function App() {
|
||||
</Route>
|
||||
<Route path="*" element={<Navigate to="/chats" replace />} />
|
||||
</Routes>
|
||||
<UpdateToast />
|
||||
</BrowserRouter>
|
||||
</CallProvider>
|
||||
</ConversationsProvider>
|
||||
|
||||
@@ -4,7 +4,6 @@ import { Outlet } from 'react-router-dom';
|
||||
import { ensureNotificationPermission } from '../lib/osNotify';
|
||||
import { CallUI } from './CallUI';
|
||||
import { Sidebar } from './Sidebar';
|
||||
import { UpdateToast } from './UpdateToast';
|
||||
|
||||
export function AppShell() {
|
||||
useEffect(() => {
|
||||
@@ -25,7 +24,6 @@ export function AppShell() {
|
||||
</main>
|
||||
</div>
|
||||
<CallUI />
|
||||
<UpdateToast />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { CallBar } from './CallUI';
|
||||
import {
|
||||
ChatBubbleIcon,
|
||||
GearIcon,
|
||||
LogoMark,
|
||||
LogoLockup,
|
||||
ShieldIcon,
|
||||
SignOutIcon,
|
||||
UsersIcon,
|
||||
@@ -33,7 +33,7 @@ const ADMIN_NAV_ITEM: NavItem = {
|
||||
};
|
||||
|
||||
export function Sidebar() {
|
||||
const { t } = useTranslation(['app', 'common']);
|
||||
const { t } = useTranslation(['app']);
|
||||
const { signOut, profile } = useAuth();
|
||||
const { incomingCount } = useFriendshipsContext();
|
||||
const { totalUnread } = useConversationsContext();
|
||||
@@ -45,11 +45,8 @@ export function Sidebar() {
|
||||
aria-label="Primary navigation"
|
||||
className="flex h-screen w-72 shrink-0 flex-col border-r border-white/5 bg-ink-900/70 backdrop-blur-xl"
|
||||
>
|
||||
<div className="flex items-center gap-2.5 px-5 pb-3 pt-5">
|
||||
<LogoMark className="h-7 w-7" />
|
||||
<span className="font-display text-base font-semibold tracking-tight text-white">
|
||||
{t('common:app_name')}
|
||||
</span>
|
||||
<div className="flex items-center px-5 pb-3 pt-5">
|
||||
<LogoLockup tone="dark" className="h-8 w-auto" aria-label="Netralax" />
|
||||
</div>
|
||||
|
||||
<nav className="mt-2 flex flex-col gap-0.5 px-3">
|
||||
|
||||
@@ -340,28 +340,94 @@ export function LogoMark(props: IconProps) {
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 32 32"
|
||||
viewBox="0 0 64 64"
|
||||
fill="none"
|
||||
aria-hidden="true"
|
||||
{...props}
|
||||
>
|
||||
<defs>
|
||||
<linearGradient id="logo-grad" x1="0" y1="0" x2="32" y2="32" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0" stopColor="#818CF8" />
|
||||
<stop offset="1" stopColor="#4F46E5" />
|
||||
</linearGradient>
|
||||
<clipPath id="logo-hex-clip">
|
||||
<polygon points="32,5 57,19 57,45 32,59 7,45 7,19" />
|
||||
</clipPath>
|
||||
</defs>
|
||||
<path
|
||||
d="M6 9a5 5 0 0 1 5-5h10a5 5 0 0 1 5 5v8a5 5 0 0 1-5 5h-5.5L9 27v-5H11a5 5 0 0 1-5-5V9Z"
|
||||
fill="url(#logo-grad)"
|
||||
<polygon
|
||||
points="32,5 57,19 57,45 32,59 7,45 7,19"
|
||||
fill="#2e1065"
|
||||
/>
|
||||
<path
|
||||
d="M12 14h8M12 10h8"
|
||||
stroke="#0A0A0F"
|
||||
strokeWidth="1.75"
|
||||
strokeLinecap="round"
|
||||
strokeOpacity="0.5"
|
||||
<g clipPath="url(#logo-hex-clip)">
|
||||
<path
|
||||
d="M-4 32 Q 16 18 32 32 T 68 32 L 68 64 L -4 64 Z"
|
||||
fill="#7c4dff"
|
||||
/>
|
||||
<path
|
||||
d="M-4 32 Q 16 18 32 32 T 68 32"
|
||||
stroke="#a78bfa"
|
||||
strokeWidth="2"
|
||||
fill="none"
|
||||
/>
|
||||
</g>
|
||||
<polygon
|
||||
points="32,5 57,19 57,45 32,59 7,45 7,19"
|
||||
fill="none"
|
||||
stroke="#a78bfa"
|
||||
strokeWidth="1.5"
|
||||
opacity="0.4"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
// Full lockup: hex icon + "Netralax" wordmark. `tone` decides text colour:
|
||||
// "dark" = white text (use on dark background), "light" = black text.
|
||||
export function LogoLockup({
|
||||
tone = 'dark',
|
||||
...props
|
||||
}: IconProps & { tone?: 'dark' | 'light' }) {
|
||||
const textFill = tone === 'dark' ? '#ffffff' : '#0F172A';
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 260 64"
|
||||
fill="none"
|
||||
aria-hidden="true"
|
||||
{...props}
|
||||
>
|
||||
<defs>
|
||||
<clipPath id="logo-lockup-hex-clip">
|
||||
<polygon points="32,5 57,19 57,45 32,59 7,45 7,19" />
|
||||
</clipPath>
|
||||
</defs>
|
||||
<polygon points="32,5 57,19 57,45 32,59 7,45 7,19" fill="#2e1065" />
|
||||
<g clipPath="url(#logo-lockup-hex-clip)">
|
||||
<path
|
||||
d="M-4 32 Q 16 18 32 32 T 68 32 L 68 64 L -4 64 Z"
|
||||
fill="#7c4dff"
|
||||
/>
|
||||
<path
|
||||
d="M-4 32 Q 16 18 32 32 T 68 32"
|
||||
stroke="#a78bfa"
|
||||
strokeWidth="2"
|
||||
fill="none"
|
||||
/>
|
||||
</g>
|
||||
<polygon
|
||||
points="32,5 57,19 57,45 32,59 7,45 7,19"
|
||||
fill="none"
|
||||
stroke="#a78bfa"
|
||||
strokeWidth="1.5"
|
||||
opacity="0.4"
|
||||
/>
|
||||
<text
|
||||
x="78"
|
||||
y="42"
|
||||
fontFamily="'Space Grotesk', system-ui, sans-serif"
|
||||
fontSize="30"
|
||||
fontWeight="600"
|
||||
letterSpacing="-0.6"
|
||||
fill={textFill}
|
||||
>
|
||||
Netralax
|
||||
</text>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { findExistingDevice } from '../lib/device';
|
||||
import { setSecretStoreUser } from '../lib/secretStore';
|
||||
import { supabase } from '../lib/supabase';
|
||||
|
||||
interface AuthContextValue {
|
||||
@@ -81,6 +82,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const { data: sub } = supabase.auth.onAuthStateChange((_event, s) => {
|
||||
setSession(s);
|
||||
setReady(true);
|
||||
void setSecretStoreUser(s?.user.id ?? null);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { getCryptoBackend } from '@chat-app/shared/crypto';
|
||||
import sodium from 'libsodium-wrappers';
|
||||
|
||||
// Encrypts/decrypts the device private key with a user-provided passphrase
|
||||
// so the backup string can be safely written down or stored in a password
|
||||
// manager. Uses Argon2id (libsodium crypto_pwhash) for the KDF and
|
||||
// XSalsa20-Poly1305 (crypto_secretbox) for the AEAD.
|
||||
//
|
||||
// Backup format (base64url-encoded blob, prefixed with a magic string so we
|
||||
// can version it):
|
||||
//
|
||||
// chatapp-backup-v1.<base64url(salt(16) | nonce(24) | ciphertext)>
|
||||
|
||||
const MAGIC = 'chatapp-backup-v1.';
|
||||
const SALT_LEN = 16; // crypto_pwhash_SALTBYTES
|
||||
const NONCE_LEN = 24; // crypto_secretbox_NONCEBYTES
|
||||
const KEY_LEN = 32; // crypto_secretbox_KEYBYTES
|
||||
|
||||
async function ensureSodium(): Promise<typeof sodium> {
|
||||
await sodium.ready;
|
||||
return sodium;
|
||||
}
|
||||
|
||||
function b64url(bytes: Uint8Array): string {
|
||||
let s = '';
|
||||
for (const b of bytes) s += String.fromCharCode(b);
|
||||
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
function unb64url(s: string): Uint8Array {
|
||||
let str = s.replace(/-/g, '+').replace(/_/g, '/');
|
||||
while (str.length % 4) str += '=';
|
||||
const bin = atob(str);
|
||||
const out = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
||||
return out;
|
||||
}
|
||||
|
||||
async function deriveKey(passphrase: string, salt: Uint8Array, sodiumLib: typeof sodium): Promise<Uint8Array> {
|
||||
return sodiumLib.crypto_pwhash(
|
||||
KEY_LEN,
|
||||
passphrase,
|
||||
salt,
|
||||
sodiumLib.crypto_pwhash_OPSLIMIT_MODERATE,
|
||||
sodiumLib.crypto_pwhash_MEMLIMIT_MODERATE,
|
||||
sodiumLib.crypto_pwhash_ALG_ARGON2ID13,
|
||||
);
|
||||
}
|
||||
|
||||
export async function exportDeviceKey(
|
||||
privateKey: Uint8Array,
|
||||
passphrase: string,
|
||||
): Promise<string> {
|
||||
if (passphrase.length < 8) throw new Error('Passphrase must be at least 8 characters.');
|
||||
const s = await ensureSodium();
|
||||
const salt = s.randombytes_buf(SALT_LEN);
|
||||
const nonce = s.randombytes_buf(NONCE_LEN);
|
||||
const key = await deriveKey(passphrase, salt, s);
|
||||
const backend = getCryptoBackend();
|
||||
const ciphertext = backend.secretbox(privateKey, nonce, key);
|
||||
s.memzero(key);
|
||||
const blob = new Uint8Array(SALT_LEN + NONCE_LEN + ciphertext.length);
|
||||
blob.set(salt, 0);
|
||||
blob.set(nonce, SALT_LEN);
|
||||
blob.set(ciphertext, SALT_LEN + NONCE_LEN);
|
||||
return MAGIC + b64url(blob);
|
||||
}
|
||||
|
||||
export async function importDeviceKey(
|
||||
backup: string,
|
||||
passphrase: string,
|
||||
): Promise<Uint8Array> {
|
||||
if (!backup.startsWith(MAGIC)) {
|
||||
throw new Error('Invalid backup format');
|
||||
}
|
||||
const blob = unb64url(backup.slice(MAGIC.length));
|
||||
if (blob.length < SALT_LEN + NONCE_LEN + 1) {
|
||||
throw new Error('Backup too short');
|
||||
}
|
||||
const salt = blob.slice(0, SALT_LEN);
|
||||
const nonce = blob.slice(SALT_LEN, SALT_LEN + NONCE_LEN);
|
||||
const ciphertext = blob.slice(SALT_LEN + NONCE_LEN);
|
||||
const s = await ensureSodium();
|
||||
const key = await deriveKey(passphrase, salt, s);
|
||||
const backend = getCryptoBackend();
|
||||
try {
|
||||
return backend.secretboxOpen(ciphertext, nonce, key);
|
||||
} catch {
|
||||
throw new Error('Wrong passphrase or corrupt backup');
|
||||
} finally {
|
||||
s.memzero(key);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,21 @@
|
||||
import { base64FromBytes, bytesFromBase64, type SecretStore } from '@chat-app/shared/auth';
|
||||
|
||||
// M1 dev-only impl: persists secrets as base64 in localStorage.
|
||||
// Swap this out for a tauri-plugin-stronghold implementation before release.
|
||||
// The SecretStore interface stays identical so callers won't notice.
|
||||
import { isTauriRuntime } from './globalShortcut';
|
||||
import { makeStrongholdStore, migrateLocalStorageToStronghold } from './strongholdStore';
|
||||
|
||||
// Secret store with two backends:
|
||||
// - Tauri: Stronghold-encrypted vault file in appLocalDataDir. Survives app
|
||||
// reinstalls and is encrypted at rest with a password derived from the
|
||||
// authenticated user-id.
|
||||
// - Web / pre-auth: localStorage (legacy dev fallback).
|
||||
//
|
||||
// Callers don't need to care which one is active — they import a singleton
|
||||
// and call setSecretStoreUser(userId) once the session is known. Until that
|
||||
// happens, calls fall through to localStorage.
|
||||
|
||||
const PREFIX = 'chatapp.secret:';
|
||||
|
||||
export const devLocalSecretStore: SecretStore = {
|
||||
const localStore: SecretStore = {
|
||||
async getSecret(key: string): Promise<Uint8Array | null> {
|
||||
const raw = window.localStorage.getItem(PREFIX + key);
|
||||
if (!raw) return null;
|
||||
@@ -20,3 +29,42 @@ export const devLocalSecretStore: SecretStore = {
|
||||
window.localStorage.removeItem(PREFIX + key);
|
||||
},
|
||||
};
|
||||
|
||||
let activeBackend: SecretStore = localStore;
|
||||
let activeUserId: string | null = null;
|
||||
|
||||
export async function setSecretStoreUser(userId: string | null): Promise<void> {
|
||||
if (userId === activeUserId) return;
|
||||
activeUserId = userId;
|
||||
|
||||
if (userId && isTauriRuntime()) {
|
||||
const stronghold = makeStrongholdStore(userId);
|
||||
activeBackend = stronghold;
|
||||
try {
|
||||
await migrateLocalStorageToStronghold(userId, PREFIX);
|
||||
} catch (err: unknown) {
|
||||
console.warn('stronghold migration failed', err);
|
||||
}
|
||||
} else {
|
||||
activeBackend = localStore;
|
||||
}
|
||||
}
|
||||
|
||||
// Singleton with stable identity — internals delegate to whichever backend is
|
||||
// currently active. Existing call-sites that imported `devLocalSecretStore`
|
||||
// keep working without changes.
|
||||
export const devLocalSecretStore: SecretStore = {
|
||||
async getSecret(key) {
|
||||
return activeBackend.getSecret(key);
|
||||
},
|
||||
async setSecret(key, value) {
|
||||
return activeBackend.setSecret(key, value);
|
||||
},
|
||||
async removeSecret(key) {
|
||||
return activeBackend.removeSecret(key);
|
||||
},
|
||||
};
|
||||
|
||||
export function isStrongholdActive(): boolean {
|
||||
return activeBackend !== localStore;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import type { SecretStore } from '@chat-app/shared/auth';
|
||||
import { appLocalDataDir } from '@tauri-apps/api/path';
|
||||
import { type Client, type Store, Stronghold } from '@tauri-apps/plugin-stronghold';
|
||||
|
||||
// Stronghold-backed SecretStore. Vault file lives in Tauri's
|
||||
// `appLocalDataDir/chatapp.stronghold` and survives app re-installs (the
|
||||
// directory is preserved by the OS on macOS/Windows/Linux unless the user
|
||||
// manually removes it). Vault password is derived from the Supabase user-id
|
||||
// so the same user re-installing the app on the same machine recovers their
|
||||
// device key automatically.
|
||||
|
||||
const VAULT_NAME = 'chatapp.stronghold';
|
||||
const CLIENT_NAME = 'chatapp';
|
||||
|
||||
let strongholdRef: Stronghold | null = null;
|
||||
let storeRef: Store | null = null;
|
||||
let initPromise: Promise<void> | null = null;
|
||||
let initializedFor: string | null = null;
|
||||
|
||||
async function derivePassword(userId: string): Promise<string> {
|
||||
const enc = new TextEncoder();
|
||||
const buf = await crypto.subtle.digest(
|
||||
'SHA-256',
|
||||
enc.encode('chatapp-stronghold-v1:' + userId),
|
||||
);
|
||||
return Array.from(new Uint8Array(buf))
|
||||
.map((b) => b.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
}
|
||||
|
||||
async function ensureInit(userId: string): Promise<void> {
|
||||
if (initializedFor === userId && storeRef) return;
|
||||
if (initPromise) return initPromise;
|
||||
|
||||
initPromise = (async () => {
|
||||
const dir = await appLocalDataDir();
|
||||
const sep = dir.endsWith('/') || dir.endsWith('\\') ? '' : '/';
|
||||
const vaultPath = dir + sep + VAULT_NAME;
|
||||
const password = await derivePassword(userId);
|
||||
|
||||
strongholdRef = await Stronghold.load(vaultPath, password);
|
||||
let client: Client;
|
||||
try {
|
||||
client = await strongholdRef.loadClient(CLIENT_NAME);
|
||||
} catch {
|
||||
client = await strongholdRef.createClient(CLIENT_NAME);
|
||||
}
|
||||
storeRef = client.getStore();
|
||||
initializedFor = userId;
|
||||
})().finally(() => {
|
||||
initPromise = null;
|
||||
});
|
||||
return initPromise;
|
||||
}
|
||||
|
||||
export function makeStrongholdStore(userId: string): SecretStore {
|
||||
return {
|
||||
async getSecret(key: string): Promise<Uint8Array | null> {
|
||||
await ensureInit(userId);
|
||||
const val = await storeRef!.get(key);
|
||||
if (!val) return null;
|
||||
return val instanceof Uint8Array ? val : new Uint8Array(val);
|
||||
},
|
||||
async setSecret(key: string, value: Uint8Array): Promise<void> {
|
||||
await ensureInit(userId);
|
||||
await storeRef!.insert(key, Array.from(value));
|
||||
await strongholdRef!.save();
|
||||
},
|
||||
async removeSecret(key: string): Promise<void> {
|
||||
await ensureInit(userId);
|
||||
await storeRef!.remove(key);
|
||||
await strongholdRef!.save();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// One-time migration: copies any keys we find in localStorage (the legacy
|
||||
// dev store) into Stronghold so a user who upgrades from a localStorage-only
|
||||
// build doesn't lose their device key. Safe to call multiple times — no-op
|
||||
// once the marker key is present.
|
||||
export async function migrateLocalStorageToStronghold(
|
||||
userId: string,
|
||||
prefix: string,
|
||||
): Promise<void> {
|
||||
await ensureInit(userId);
|
||||
if (!storeRef) return;
|
||||
const markerKey = '__migrated_from_localstorage';
|
||||
const already = await storeRef.get(markerKey);
|
||||
if (already) return;
|
||||
|
||||
for (let i = 0; i < window.localStorage.length; i++) {
|
||||
const fullKey = window.localStorage.key(i);
|
||||
if (!fullKey || !fullKey.startsWith(prefix)) continue;
|
||||
const raw = window.localStorage.getItem(fullKey);
|
||||
if (!raw) continue;
|
||||
try {
|
||||
const decoded = Uint8Array.from(atob(raw), (c) => c.charCodeAt(0));
|
||||
const shortKey = fullKey.slice(prefix.length);
|
||||
await storeRef.insert(shortKey, Array.from(decoded));
|
||||
} catch {
|
||||
// Skip malformed entries.
|
||||
}
|
||||
}
|
||||
await storeRef.insert(markerKey, [1]);
|
||||
if (strongholdRef) await strongholdRef.save();
|
||||
}
|
||||
@@ -9,6 +9,9 @@ import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { LockIcon } from '../components/icons';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { loadDevicePrivateKey, saveDevicePrivateKey } from '@chat-app/shared/auth';
|
||||
import { exportDeviceKey, importDeviceKey } from '../lib/deviceBackup';
|
||||
import { devLocalSecretStore } from '../lib/secretStore';
|
||||
import {
|
||||
getPttSettings,
|
||||
keyCodeToLabel,
|
||||
@@ -161,6 +164,7 @@ export function SettingsPage() {
|
||||
</dl>
|
||||
</div>
|
||||
)}
|
||||
<DeviceKeyBackupControls />
|
||||
</Section>
|
||||
|
||||
{/* Danger zone */}
|
||||
@@ -323,6 +327,160 @@ function AudioQualityControls() {
|
||||
);
|
||||
}
|
||||
|
||||
function DeviceKeyBackupControls() {
|
||||
const { t } = useTranslation(['app']);
|
||||
const { profile, device } = useAuth();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [backupOut, setBackupOut] = useState<string | null>(null);
|
||||
const [exportPass, setExportPass] = useState('');
|
||||
const [importPass, setImportPass] = useState('');
|
||||
const [importBlob, setImportBlob] = useState('');
|
||||
const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);
|
||||
|
||||
const canRun = !!profile?.userId && !!device?.id;
|
||||
|
||||
async function handleExport() {
|
||||
if (!canRun) return;
|
||||
setMsg(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
const priv = await loadDevicePrivateKey(devLocalSecretStore, profile.userId, device.id);
|
||||
if (!priv) throw new Error('No device key on this install');
|
||||
const out = await exportDeviceKey(priv, exportPass);
|
||||
setBackupOut(out);
|
||||
setExportPass('');
|
||||
setMsg({
|
||||
kind: 'ok',
|
||||
text: t('app:settings.backup_export_ok', {
|
||||
defaultValue: 'Backup erstellt — kopiere und bewahre es sicher auf.',
|
||||
}),
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
setMsg({
|
||||
kind: 'err',
|
||||
text: err instanceof Error ? err.message : 'export failed',
|
||||
});
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleImport() {
|
||||
if (!canRun) return;
|
||||
setMsg(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
const priv = await importDeviceKey(importBlob.trim(), importPass);
|
||||
await saveDevicePrivateKey(devLocalSecretStore, profile.userId, device.id, priv);
|
||||
setImportBlob('');
|
||||
setImportPass('');
|
||||
setMsg({
|
||||
kind: 'ok',
|
||||
text: t('app:settings.backup_import_ok', {
|
||||
defaultValue:
|
||||
'Schlüssel importiert. Beim nächsten Reload sollten alte Nachrichten lesbar sein.',
|
||||
}),
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
setMsg({
|
||||
kind: 'err',
|
||||
text: err instanceof Error ? err.message : 'import failed',
|
||||
});
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mt-4 rounded-xl border border-white/10 bg-ink-900/40 p-4">
|
||||
<div className="text-sm font-semibold text-white">
|
||||
{t('app:settings.device_key_backup', { defaultValue: 'Geräteschlüssel-Backup' })}
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-neutral-400">
|
||||
{t('app:settings.device_key_backup_hint', {
|
||||
defaultValue:
|
||||
'Sichere deinen privaten Schlüssel passwortgeschützt, damit du auf neuen Geräten alte Nachrichten weiter lesen kannst.',
|
||||
})}
|
||||
</p>
|
||||
|
||||
<div className="mt-4 space-y-2">
|
||||
<div className="text-xs font-semibold uppercase tracking-wide text-neutral-500">
|
||||
{t('app:settings.backup_export', { defaultValue: 'Export' })}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="password"
|
||||
value={exportPass}
|
||||
onChange={(e) => setExportPass(e.target.value)}
|
||||
placeholder={t('app:settings.backup_passphrase', { defaultValue: 'Passphrase (min 8)' })}
|
||||
className="flex-1 rounded-lg border border-white/10 bg-ink-800 px-3 py-2 text-sm text-white placeholder-neutral-500 focus:border-brand-400 focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || exportPass.length < 8 || !canRun}
|
||||
onClick={() => void handleExport()}
|
||||
className="cursor-pointer rounded-lg bg-brand-500/80 px-4 text-sm font-semibold text-white transition hover:bg-brand-400 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{t('app:settings.backup_create', { defaultValue: 'Erstellen' })}
|
||||
</button>
|
||||
</div>
|
||||
{backupOut && (
|
||||
<textarea
|
||||
readOnly
|
||||
value={backupOut}
|
||||
onClick={(e) => (e.target as HTMLTextAreaElement).select()}
|
||||
rows={3}
|
||||
className="w-full rounded-lg border border-emerald-500/30 bg-ink-950/60 p-2 font-mono text-[10px] text-emerald-200"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-4 space-y-2 border-t border-white/5 pt-4">
|
||||
<div className="text-xs font-semibold uppercase tracking-wide text-neutral-500">
|
||||
{t('app:settings.backup_import', { defaultValue: 'Import' })}
|
||||
</div>
|
||||
<textarea
|
||||
value={importBlob}
|
||||
onChange={(e) => setImportBlob(e.target.value)}
|
||||
rows={3}
|
||||
placeholder={t('app:settings.backup_blob_placeholder', {
|
||||
defaultValue: 'chatapp-backup-v1.…',
|
||||
})}
|
||||
className="w-full rounded-lg border border-white/10 bg-ink-800 p-2 font-mono text-[11px] text-white placeholder-neutral-500 focus:border-brand-400 focus:outline-none"
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="password"
|
||||
value={importPass}
|
||||
onChange={(e) => setImportPass(e.target.value)}
|
||||
placeholder={t('app:settings.backup_passphrase', { defaultValue: 'Passphrase' })}
|
||||
className="flex-1 rounded-lg border border-white/10 bg-ink-800 px-3 py-2 text-sm text-white placeholder-neutral-500 focus:border-brand-400 focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || !importBlob || !importPass || !canRun}
|
||||
onClick={() => void handleImport()}
|
||||
className="cursor-pointer rounded-lg bg-emerald-500/80 px-4 text-sm font-semibold text-white transition hover:bg-emerald-400 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{t('app:settings.backup_restore', { defaultValue: 'Wiederherstellen' })}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{msg && (
|
||||
<p
|
||||
className={
|
||||
'mt-3 text-xs ' +
|
||||
(msg.kind === 'ok' ? 'text-emerald-300' : 'text-rose-300')
|
||||
}
|
||||
>
|
||||
{msg.text}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ScreenShareControls() {
|
||||
const { t } = useTranslation(['app']);
|
||||
const [cfg, setCfg] = useState<ScreenShareSettings>(() => getScreenShareSettings());
|
||||
|
||||
@@ -141,6 +141,17 @@ export async function forgetDevicePrivateKey(
|
||||
await secretStore.removeSecret(privateKeySecretName(userId, deviceId));
|
||||
}
|
||||
|
||||
// Writes a device private key into the secret store. Used by the
|
||||
// backup-restore flow to re-import a key generated on another machine.
|
||||
export async function saveDevicePrivateKey(
|
||||
secretStore: SecretStore,
|
||||
userId: string,
|
||||
deviceId: string,
|
||||
privateKey: Uint8Array,
|
||||
): Promise<void> {
|
||||
await secretStore.setSecret(privateKeySecretName(userId, deviceId), privateKey);
|
||||
}
|
||||
|
||||
// Lightweight helpers for platforms that want to cache their current device id
|
||||
// in JSON storage (separate from the secret store, which only holds raw bytes).
|
||||
export const DEVICE_ID_STORAGE_KEY_PREFIX = 'chatapp.device_id';
|
||||
|
||||