Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .oxlintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
}
12 changes: 8 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
# 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.

| | |
| ------------ | -------------------------------------- |
| **Package** | `@tbridge/sdk` |
| **Runtime** | Browser only |
| **Language** | TypeScript → ESM + CJS |
| **Language** | TypeScript → ESM |
| **Crypto** | NaCl box via `tweetnacl` (overridable) |
| **License** | MIT |

Expand Down Expand Up @@ -194,4 +198,4 @@ bridge.on('disconnect', ({ reason }) => {

## License

MIT
MIT © [Ivan Lomovtcev](https://telegram.me/frntbck)
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
"prebuild": "pnpm typecheck && pnpm lint"
},
"dependencies": {
"qr": "^0.5.0",
"qr": "^0.7.2",
"tweetnacl": "^1.0.3"
},
"devDependencies": {
Expand Down
10 changes: 5 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

109 changes: 105 additions & 4 deletions wallet/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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<ArrayBuffer> {
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<CryptoKey | null> {
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<string | null> {
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<string | null> {
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<string | null> {
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<void> {
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 {
Expand Down Expand Up @@ -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 {
Expand All @@ -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 (
Expand Down Expand Up @@ -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;
Expand Down
Loading