diff --git a/.oxlintrc.json b/.oxlintrc.json index abb7302..d9fce29 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -14,7 +14,8 @@ "eslint/no-debugger": "error", "eslint/no-eval": "error", "eslint/eqeqeq": "error", - "unicorn/no-useless-undefined": "off" + "unicorn/no-useless-undefined": "off", + "no-underscore-dangle": "off" }, "ignorePatterns": ["dist/**", "node_modules/**", "coverage/**", "**/*.d.ts"] } diff --git a/README.md b/README.md index dc60455..e815402 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,10 @@ -# TBridge +# TBridge SDK -**Enterprise-grade TON wallet connector for the browser.** +[![CI](https://github.com/advanceddev/tbridge-sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/advanceddev/tbridge-sdk/actions/workflows/ci.yml) + +**An blazing fast, enterprise-grade connector for TON wallets for the browser.** + +⚡ [Live demo](https://advanceddev.github.io/tbridge-demo-app/) TBridge is a pure TypeScript SDK for discovering wallets, establishing encrypted sessions, and requesting signatures / transfers on TON. It is framework-agnostic (React, Vue, Svelte, or vanilla), ships an optional vanilla UI, and is designed for production dApps and Telegram Mini Apps. @@ -8,7 +12,7 @@ TBridge is a pure TypeScript SDK for discovering wallets, establishing encrypted | ------------ | -------------------------------------- | | **Package** | `@tbridge/sdk` | | **Runtime** | Browser only | -| **Language** | TypeScript → ESM + CJS | +| **Language** | TypeScript → ESM | | **Crypto** | NaCl box via `tweetnacl` (overridable) | | **License** | MIT | @@ -194,4 +198,4 @@ bridge.on('disconnect', ({ reason }) => { ## License -MIT +MIT © [Ivan Lomovtcev](https://telegram.me/frntbck) diff --git a/package.json b/package.json index 6773a74..e7a444b 100644 --- a/package.json +++ b/package.json @@ -60,7 +60,7 @@ "prebuild": "pnpm typecheck && pnpm lint" }, "dependencies": { - "qr": "^0.5.0", + "qr": "^0.7.2", "tweetnacl": "^1.0.3" }, "devDependencies": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bf4b8c1..a4e335b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9,8 +9,8 @@ importers: .: dependencies: qr: - specifier: ^0.5.0 - version: 0.5.5 + specifier: ^0.7.2 + version: 0.7.2 tweetnacl: specifier: ^1.0.3 version: 1.0.3 @@ -803,8 +803,8 @@ packages: resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} engines: {node: ^10 || ^12 || >=14} - qr@0.5.5: - resolution: {integrity: sha512-iQBvKj7MRKO+co+MY0IZpyLO+ezvttxsmV86WywrgPuAmgBkv0pytyi03wourniSoPgzffeBW6cBgIkpqcvjTg==} + qr@0.7.2: + resolution: {integrity: sha512-yovYRuacJBJkG9fWSwcB2bKZhr58c04DpOXguDU+rAAoJZdi6/J3DtlomkKqdd1MutIptIK+kigWmT7LKz8y7A==} engines: {node: '>= 20.19.0'} quansync@0.2.11: @@ -1486,7 +1486,7 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.2 - qr@0.5.5: {} + qr@0.7.2: {} quansync@0.2.11: {} diff --git a/wallet/session.ts b/wallet/session.ts index 6b6aa19..4234d78 100644 --- a/wallet/session.ts +++ b/wallet/session.ts @@ -16,6 +16,9 @@ import { safeJsonParse } from '../core/security'; import type { StorageAdapter } from '../core/storage'; import type { PersistedSession } from '../core/types'; +const SESSION_SECRET_PREFIX = 'enc:v1:'; +const SESSION_SECRET_SALT = 'wallet-session-secret-salt'; + export type SessionPersistence = 'local' | 'session'; let persistenceMode: SessionPersistence = 'local'; @@ -38,6 +41,104 @@ function readSessionStorage(key: string): string | null { } } +function bytesToBase64(bytes: Uint8Array): string { + let binary = ''; + for (let i = 0; i < bytes.length; i += 1) binary += String.fromCharCode(bytes[i]); + return btoa(binary); +} + +function base64ToBytes(base64: string): Uint8Array { + const clean = base64.replace(/-/g, '+').replace(/_/g, '/'); + const padding = clean.length % 4 === 0 ? 0 : 4 - (clean.length % 4); + const binary = atob(clean + '='.repeat(padding)); + + const buffer = new ArrayBuffer(binary.length); + const bytes = new Uint8Array(buffer); + + for (let i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i); + } + + return bytes; +} + +function getSessionEncryptionPassphrase(): string | null { + if (typeof window === 'undefined') return null; + const maybe = (window as typeof window & { __WALLET_SESSION_SECRET__?: unknown }) + .__WALLET_SESSION_SECRET__; + return typeof maybe === 'string' && maybe.length > 0 ? maybe : null; +} + +async function deriveAesKey(passphrase: string): Promise { + if (typeof window === 'undefined' || !window.crypto?.subtle) return null; + const enc = new TextEncoder(); + const baseKey = await window.crypto.subtle.importKey( + 'raw', + enc.encode(passphrase), + 'PBKDF2', + false, + ['deriveKey'], + ); + return window.crypto.subtle.deriveKey( + { name: 'PBKDF2', salt: enc.encode(SESSION_SECRET_SALT), iterations: 100000, hash: 'SHA-256' }, + baseKey, + { name: 'AES-GCM', length: 256 }, + false, + ['encrypt', 'decrypt'], + ); +} + +async function encryptSecretForStorage(secret: string): Promise { + const passphrase = getSessionEncryptionPassphrase(); + if (!passphrase || typeof window === 'undefined' || !window.crypto?.getRandomValues) return null; + const key = await deriveAesKey(passphrase); + if (!key) return null; + const iv = window.crypto.getRandomValues(new Uint8Array(12)); + const enc = new TextEncoder(); + const ciphertext = await window.crypto.subtle.encrypt( + { name: 'AES-GCM', iv }, + key, + enc.encode(secret), + ); + return `${SESSION_SECRET_PREFIX}${bytesToBase64(iv)}:${bytesToBase64(new Uint8Array(ciphertext))}`; +} + +async function decryptSecretFromStorage(payload: string): Promise { + const passphrase = getSessionEncryptionPassphrase(); + if (!passphrase || !payload.startsWith(SESSION_SECRET_PREFIX) || typeof window === 'undefined') { + return null; + } + const body = payload.slice(SESSION_SECRET_PREFIX.length); + const parts = body.split(':'); + if (parts.length !== 2) return null; + const iv = base64ToBytes(parts[0]); + const data = base64ToBytes(parts[1]); + const key = await deriveAesKey(passphrase); + if (!key) return null; + const plain = await window.crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, data); + return new TextDecoder().decode(plain); +} + +async function readEncryptedSessionSecret(key: string): Promise { + const stored = readSessionStorage(key); + if (!stored) return null; + try { + return await decryptSecretFromStorage(stored); + } catch { + removeSessionStorage(key); + return null; + } +} + +async function writeEncryptedSessionSecret(key: string, value: string): Promise { + try { + const encrypted = await encryptSecretForStorage(value); + if (encrypted) writeSessionStorage(key, encrypted); + } catch { + /* ignore */ + } +} + function writeSessionStorage(key: string, value: string): void { if (typeof window === 'undefined') return; try { @@ -73,11 +174,11 @@ export async function loadPersistedSession( if (persistenceMode === 'session') { // Volatile: secret only from sessionStorage - let secret = readSessionStorage(STORAGE_KEYS.SESSION_SECRET); + let secret = await readEncryptedSessionSecret(STORAGE_KEYS.SESSION_SECRET); if (!secret && typeof data.secretKeyHex === 'string' && data.secretKeyHex.length > 0) { // Migrate legacy full blob → sessionStorage secret = data.secretKeyHex; - writeSessionStorage(STORAGE_KEYS.SESSION_SECRET, secret); + await writeEncryptedSessionSecret(STORAGE_KEYS.SESSION_SECRET, secret); try { await storage.setItem(STORAGE_KEYS.SESSION, JSON.stringify(stripSecret(data))); } catch { @@ -92,7 +193,7 @@ export async function loadPersistedSession( const secret = (typeof data.secretKeyHex === 'string' && data.secretKeyHex.length > 0 ? data.secretKeyHex - : null) ?? readSessionStorage(STORAGE_KEYS.SESSION_SECRET); + : null) ?? (await readEncryptedSessionSecret(STORAGE_KEYS.SESSION_SECRET)); // Promote sessionStorage secret into local blob once (upgrade path) if ( @@ -123,7 +224,7 @@ export async function savePersistedSession( const secret = session.secretKeyHex; if (persistenceMode === 'session') { - if (secret) writeSessionStorage(STORAGE_KEYS.SESSION_SECRET, secret); + if (secret) await writeEncryptedSessionSecret(STORAGE_KEYS.SESSION_SECRET, secret); else removeSessionStorage(STORAGE_KEYS.SESSION_SECRET); await storage.setItem(STORAGE_KEYS.SESSION, JSON.stringify(stripSecret(session))); return;