SHA256
Restore registration step flow and create new session on login
This commit is contained in:
@@ -0,0 +1,175 @@
|
||||
import { WsJsonClient } from './ws-client.js?v=20260327192619';
|
||||
import {
|
||||
deriveEd25519FromPassword,
|
||||
exportEd25519PublicKeyB64,
|
||||
exportPkcs8B64,
|
||||
generateEd25519Pair,
|
||||
randomBase64,
|
||||
signBase64,
|
||||
} from './crypto-utils.js?v=20260327192619';
|
||||
import { saveEncryptedUserSecrets, saveSessionMaterial } from './key-vault.js?v=20260327192619';
|
||||
|
||||
const BCH_SUFFIX = '001';
|
||||
|
||||
function normalizeServerUrl(url) {
|
||||
const value = (url || '').trim();
|
||||
if (!value) return 'wss://shineup.me/ws';
|
||||
if (value.startsWith('ws://') || value.startsWith('wss://')) return value;
|
||||
if (value.startsWith('https://') || value.startsWith('http://')) {
|
||||
return `${value.replace(/^http/, 'ws').replace(/\/$/, '')}/ws`;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function opError(op, response) {
|
||||
const message = response?.payload?.message || response?.message || 'Неизвестная ошибка сервера';
|
||||
const code = response?.payload?.code || response?.code || 'UNKNOWN';
|
||||
return new Error(`${op}: ${message} (${code})`);
|
||||
}
|
||||
|
||||
function makeClientInfo() {
|
||||
const ua = navigator.userAgent || 'unknown';
|
||||
return ua.slice(0, 50);
|
||||
}
|
||||
|
||||
export class AuthService {
|
||||
constructor(serverUrl) {
|
||||
this.serverUrl = normalizeServerUrl(serverUrl);
|
||||
this.ws = new WsJsonClient(this.serverUrl);
|
||||
}
|
||||
|
||||
async reconnect(serverUrl) {
|
||||
const normalized = normalizeServerUrl(serverUrl);
|
||||
if (normalized === this.serverUrl) return;
|
||||
this.ws.close();
|
||||
this.serverUrl = normalized;
|
||||
this.ws = new WsJsonClient(this.serverUrl);
|
||||
}
|
||||
|
||||
async getUser(login) {
|
||||
const response = await this.ws.request('GetUser', { login });
|
||||
if (response.status !== 200) throw opError('GetUser', response);
|
||||
return response.payload || {};
|
||||
}
|
||||
|
||||
async ensureLoginFree(login) {
|
||||
const payload = await this.getUser(login);
|
||||
return payload.exists !== true;
|
||||
}
|
||||
|
||||
async derivePasswordKeyBundle(password) {
|
||||
if (!password) throw new Error('Введите пароль');
|
||||
const rootPair = await deriveEd25519FromPassword(password, 'root.key');
|
||||
const blockchainPair = await deriveEd25519FromPassword(password, 'bch.key');
|
||||
const devicePair = await deriveEd25519FromPassword(password, 'dev.key');
|
||||
return { rootPair, blockchainPair, devicePair };
|
||||
}
|
||||
|
||||
async createAuthSession(login, keyBundle) {
|
||||
const cleanLogin = (login || '').trim();
|
||||
if (!cleanLogin) throw new Error('Введите логин');
|
||||
|
||||
const sessionPair = await generateEd25519Pair();
|
||||
const sessionKeyPub = await exportEd25519PublicKeyB64(sessionPair.publicKey);
|
||||
const sessionKey = `ed25519/${sessionKeyPub}`;
|
||||
const storagePwd = randomBase64(32);
|
||||
|
||||
const challengeResp = await this.ws.request('AuthChallenge', { login: cleanLogin });
|
||||
if (challengeResp.status !== 200) throw opError('AuthChallenge', challengeResp);
|
||||
|
||||
const authNonce = challengeResp?.payload?.authNonce;
|
||||
if (!authNonce) throw new Error('AuthChallenge: сервер не вернул authNonce');
|
||||
|
||||
const timeMs = Date.now();
|
||||
const preimage = `AUTH_CREATE_SESSION:${cleanLogin}:${sessionKey}:${storagePwd}:${timeMs}:${authNonce}`;
|
||||
const signatureB64 = await signBase64(keyBundle.devicePair.privateKey, preimage);
|
||||
|
||||
const createResp = await this.ws.request('CreateAuthSession', {
|
||||
login: cleanLogin,
|
||||
storagePwd,
|
||||
sessionKey,
|
||||
timeMs,
|
||||
authNonce,
|
||||
deviceKey: keyBundle.devicePair.publicKeyB64,
|
||||
signatureB64,
|
||||
clientInfo: makeClientInfo(),
|
||||
});
|
||||
if (createResp.status !== 200) throw opError('CreateAuthSession', createResp);
|
||||
|
||||
const sessionId = createResp?.payload?.sessionId;
|
||||
if (!sessionId) throw new Error('CreateAuthSession: не вернулся sessionId');
|
||||
|
||||
return {
|
||||
login: cleanLogin,
|
||||
sessionId,
|
||||
storagePwd,
|
||||
sessionMaterial: {
|
||||
sessionId,
|
||||
sessionKey,
|
||||
sessionPrivPkcs8: await exportPkcs8B64(sessionPair.privateKey),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async registerUser(login, password) {
|
||||
const cleanLogin = (login || '').trim();
|
||||
if (!cleanLogin) throw new Error('Введите логин');
|
||||
if (!password) throw new Error('Введите пароль');
|
||||
|
||||
const isFree = await this.ensureLoginFree(cleanLogin);
|
||||
if (!isFree) throw new Error('Этот логин уже занят');
|
||||
|
||||
const keyBundle = await this.derivePasswordKeyBundle(password);
|
||||
|
||||
const addResp = await this.ws.request('AddUser', {
|
||||
login: cleanLogin,
|
||||
blockchainName: `${cleanLogin}-${BCH_SUFFIX}`,
|
||||
solanaKey: keyBundle.rootPair.publicKeyB64,
|
||||
blockchainKey: keyBundle.blockchainPair.publicKeyB64,
|
||||
deviceKey: keyBundle.devicePair.publicKeyB64,
|
||||
bchLimit: 1000000,
|
||||
});
|
||||
if (addResp.status !== 200) throw opError('AddUser', addResp);
|
||||
|
||||
const session = await this.createAuthSession(cleanLogin, keyBundle);
|
||||
return { ...session, keyBundle };
|
||||
}
|
||||
|
||||
async createSessionForExistingUser(login, password) {
|
||||
const cleanLogin = (login || '').trim();
|
||||
if (!cleanLogin) throw new Error('Введите логин');
|
||||
if (!password) throw new Error('Введите пароль');
|
||||
|
||||
const user = await this.getUser(cleanLogin);
|
||||
if (!user.exists) throw new Error('Пользователь не найден');
|
||||
|
||||
const keyBundle = await this.derivePasswordKeyBundle(password);
|
||||
return this.createAuthSession(cleanLogin, keyBundle);
|
||||
}
|
||||
|
||||
async persistSelectedKeys(login, storagePwd, keyBundle, saveOptions = { saveRoot: true, saveBlockchain: true }) {
|
||||
const secrets = { deviceKey: keyBundle.devicePair.privatePkcs8B64 };
|
||||
if (saveOptions.saveRoot) secrets.rootKey = keyBundle.rootPair.privatePkcs8B64;
|
||||
if (saveOptions.saveBlockchain) secrets.blockchainKey = keyBundle.blockchainPair.privatePkcs8B64;
|
||||
await saveEncryptedUserSecrets(login, storagePwd, secrets);
|
||||
}
|
||||
|
||||
async persistSessionMaterial(login, sessionMaterial) {
|
||||
await saveSessionMaterial(login, sessionMaterial);
|
||||
}
|
||||
|
||||
async listSessions() {
|
||||
const response = await this.ws.request('ListSessions', {});
|
||||
if (response.status !== 200) throw opError('ListSessions', response);
|
||||
return response?.payload?.sessions || [];
|
||||
}
|
||||
|
||||
async closeSession(sessionId) {
|
||||
const response = await this.ws.request('CloseActiveSession', { sessionId });
|
||||
if (response.status !== 200) throw opError('CloseActiveSession', response);
|
||||
}
|
||||
|
||||
close() {
|
||||
this.ws.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
|
||||
function base64UrlToBase64(value) {
|
||||
const normalized = value.replace(/-/g, '+').replace(/_/g, '/');
|
||||
const padLen = (4 - (normalized.length % 4)) % 4;
|
||||
return normalized + '='.repeat(padLen);
|
||||
}
|
||||
|
||||
export function randomBase64(byteLen = 32) {
|
||||
const bytes = crypto.getRandomValues(new Uint8Array(byteLen));
|
||||
return bytesToBase64(bytes);
|
||||
}
|
||||
|
||||
export function bytesToBase64(bytes) {
|
||||
let binary = '';
|
||||
bytes.forEach((b) => {
|
||||
binary += String.fromCharCode(b);
|
||||
});
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
export function base64ToBytes(base64) {
|
||||
const normalized = (base64 || '').trim();
|
||||
const binary = atob(normalized);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i += 1) {
|
||||
bytes[i] = binary.charCodeAt(i);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
export function utf8Bytes(value) {
|
||||
return encoder.encode(value);
|
||||
}
|
||||
|
||||
export async function sha256Bytes(bytes) {
|
||||
const digest = await crypto.subtle.digest('SHA-256', bytes);
|
||||
return new Uint8Array(digest);
|
||||
}
|
||||
|
||||
export async function sha256Text(text) {
|
||||
return sha256Bytes(utf8Bytes(text));
|
||||
}
|
||||
|
||||
export async function derivePasswordSeed(password, suffix) {
|
||||
const base = await sha256Text(password || '');
|
||||
const concat = `${bytesToBase64(base)}${suffix}`;
|
||||
return sha256Text(concat);
|
||||
}
|
||||
|
||||
function ed25519Pkcs8FromSeed(seed32) {
|
||||
if (seed32.length !== 32) {
|
||||
throw new Error('Для Ed25519 нужен seed длиной 32 байта');
|
||||
}
|
||||
const prefix = new Uint8Array([
|
||||
0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,
|
||||
]);
|
||||
const out = new Uint8Array(prefix.length + seed32.length);
|
||||
out.set(prefix, 0);
|
||||
out.set(seed32, prefix.length);
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function deriveEd25519FromPassword(password, suffix) {
|
||||
const seed = await derivePasswordSeed(password, suffix);
|
||||
const pkcs8 = ed25519Pkcs8FromSeed(seed);
|
||||
const privateKey = await crypto.subtle.importKey('pkcs8', pkcs8, { name: 'Ed25519' }, true, ['sign']);
|
||||
const jwk = await crypto.subtle.exportKey('jwk', privateKey);
|
||||
if (!jwk.x) throw new Error('Не удалось получить публичный ключ Ed25519');
|
||||
|
||||
return {
|
||||
privateKey,
|
||||
publicKeyB64: bytesToBase64(base64ToBytes(base64UrlToBase64(jwk.x))),
|
||||
privatePkcs8B64: bytesToBase64(pkcs8),
|
||||
};
|
||||
}
|
||||
|
||||
export async function deriveAesKeyFromStoragePwd(storagePwd, saltBytes) {
|
||||
const baseKey = await crypto.subtle.importKey(
|
||||
'raw',
|
||||
utf8Bytes(storagePwd),
|
||||
{ name: 'PBKDF2' },
|
||||
false,
|
||||
['deriveKey'],
|
||||
);
|
||||
|
||||
return crypto.subtle.deriveKey(
|
||||
{
|
||||
name: 'PBKDF2',
|
||||
salt: saltBytes,
|
||||
iterations: 210000,
|
||||
hash: 'SHA-256',
|
||||
},
|
||||
baseKey,
|
||||
{
|
||||
name: 'AES-GCM',
|
||||
length: 256,
|
||||
},
|
||||
false,
|
||||
['encrypt', 'decrypt'],
|
||||
);
|
||||
}
|
||||
|
||||
export async function encryptJsonWithStoragePwd(value, storagePwd) {
|
||||
const salt = crypto.getRandomValues(new Uint8Array(16));
|
||||
const iv = crypto.getRandomValues(new Uint8Array(12));
|
||||
const key = await deriveAesKeyFromStoragePwd(storagePwd, salt);
|
||||
const plainBytes = utf8Bytes(JSON.stringify(value));
|
||||
const cipher = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, plainBytes);
|
||||
|
||||
return {
|
||||
saltB64: bytesToBase64(salt),
|
||||
ivB64: bytesToBase64(iv),
|
||||
cipherB64: bytesToBase64(new Uint8Array(cipher)),
|
||||
};
|
||||
}
|
||||
|
||||
export async function decryptJsonWithStoragePwd(envelope, storagePwd) {
|
||||
const salt = base64ToBytes(envelope.saltB64);
|
||||
const iv = base64ToBytes(envelope.ivB64);
|
||||
const cipher = base64ToBytes(envelope.cipherB64);
|
||||
const key = await deriveAesKeyFromStoragePwd(storagePwd, salt);
|
||||
const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, cipher);
|
||||
const text = new TextDecoder().decode(plain);
|
||||
return JSON.parse(text);
|
||||
}
|
||||
|
||||
export async function generateEd25519Pair() {
|
||||
return crypto.subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify']);
|
||||
}
|
||||
|
||||
export async function exportEd25519PublicKeyB64(publicKey) {
|
||||
const raw = await crypto.subtle.exportKey('raw', publicKey);
|
||||
return bytesToBase64(new Uint8Array(raw));
|
||||
}
|
||||
|
||||
export async function exportPkcs8B64(privateKey) {
|
||||
const raw = await crypto.subtle.exportKey('pkcs8', privateKey);
|
||||
return bytesToBase64(new Uint8Array(raw));
|
||||
}
|
||||
|
||||
export async function importPkcs8Ed25519(pkcs8B64) {
|
||||
return crypto.subtle.importKey('pkcs8', base64ToBytes(pkcs8B64), { name: 'Ed25519' }, false, ['sign']);
|
||||
}
|
||||
|
||||
export async function signBase64(privateKey, text) {
|
||||
const signature = await crypto.subtle.sign({ name: 'Ed25519' }, privateKey, utf8Bytes(text));
|
||||
return bytesToBase64(new Uint8Array(signature));
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import {
|
||||
decryptJsonWithStoragePwd,
|
||||
encryptJsonWithStoragePwd,
|
||||
} from './crypto-utils.js?v=20260327192619';
|
||||
|
||||
const DB_NAME = 'shine-ui-auth';
|
||||
const DB_VERSION = 1;
|
||||
const STORE_SECRETS = 'encrypted-secrets';
|
||||
const STORE_SESSIONS = 'session-keys';
|
||||
|
||||
function openDb() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(DB_NAME, DB_VERSION);
|
||||
request.onupgradeneeded = () => {
|
||||
const db = request.result;
|
||||
if (!db.objectStoreNames.contains(STORE_SECRETS)) {
|
||||
db.createObjectStore(STORE_SECRETS, { keyPath: 'login' });
|
||||
}
|
||||
if (!db.objectStoreNames.contains(STORE_SESSIONS)) {
|
||||
db.createObjectStore(STORE_SESSIONS, { keyPath: 'login' });
|
||||
}
|
||||
};
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error || new Error('IndexedDB недоступен'));
|
||||
});
|
||||
}
|
||||
|
||||
async function put(storeName, value) {
|
||||
const db = await openDb();
|
||||
await new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(storeName, 'readwrite');
|
||||
tx.objectStore(storeName).put(value);
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = () => reject(tx.error || new Error('Ошибка записи в IndexedDB'));
|
||||
});
|
||||
db.close();
|
||||
}
|
||||
|
||||
async function get(storeName, key) {
|
||||
const db = await openDb();
|
||||
const result = await new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(storeName, 'readonly');
|
||||
const req = tx.objectStore(storeName).get(key);
|
||||
req.onsuccess = () => resolve(req.result || null);
|
||||
req.onerror = () => reject(req.error || new Error('Ошибка чтения из IndexedDB'));
|
||||
});
|
||||
db.close();
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function saveEncryptedUserSecrets(login, storagePwd, keys) {
|
||||
const encrypted = await encryptJsonWithStoragePwd(keys, storagePwd);
|
||||
await put(STORE_SECRETS, {
|
||||
login,
|
||||
encrypted,
|
||||
updatedAtMs: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadEncryptedUserSecrets(login, storagePwd) {
|
||||
const row = await get(STORE_SECRETS, login);
|
||||
if (!row?.encrypted) {
|
||||
throw new Error('На устройстве нет сохранённых ключей для этого логина');
|
||||
}
|
||||
return decryptJsonWithStoragePwd(row.encrypted, storagePwd);
|
||||
}
|
||||
|
||||
export async function saveSessionMaterial(login, material) {
|
||||
await put(STORE_SESSIONS, {
|
||||
login,
|
||||
...material,
|
||||
updatedAtMs: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadSessionMaterial(login) {
|
||||
return get(STORE_SESSIONS, login);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
const DEFAULT_TIMEOUT_MS = 12000;
|
||||
|
||||
function buildWsUrl(raw) {
|
||||
const value = (raw || '').trim();
|
||||
if (!value) return 'wss://shineup.me/ws';
|
||||
if (value.startsWith('ws://') || value.startsWith('wss://')) return value;
|
||||
if (value.startsWith('http://')) return `ws://${value.slice('http://'.length)}`;
|
||||
if (value.startsWith('https://')) return `wss://${value.slice('https://'.length)}`;
|
||||
return value;
|
||||
}
|
||||
|
||||
function createRequestId(op) {
|
||||
return `${op}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
||||
}
|
||||
|
||||
export class WsJsonClient {
|
||||
constructor(url) {
|
||||
this.url = buildWsUrl(url);
|
||||
this.ws = null;
|
||||
this.pending = new Map();
|
||||
this.openPromise = null;
|
||||
}
|
||||
|
||||
async open() {
|
||||
if (this.ws && this.ws.readyState === WebSocket.OPEN) return;
|
||||
if (this.openPromise) return this.openPromise;
|
||||
|
||||
this.openPromise = new Promise((resolve, reject) => {
|
||||
const ws = new WebSocket(this.url);
|
||||
this.ws = ws;
|
||||
|
||||
ws.addEventListener('open', () => {
|
||||
resolve();
|
||||
}, { once: true });
|
||||
|
||||
ws.addEventListener('error', () => {
|
||||
reject(new Error(`Не удалось подключиться к ${this.url}`));
|
||||
}, { once: true });
|
||||
|
||||
ws.addEventListener('close', () => {
|
||||
this.failPending('Соединение WebSocket закрыто');
|
||||
});
|
||||
|
||||
ws.addEventListener('message', (event) => {
|
||||
this.handleMessage(event.data);
|
||||
});
|
||||
}).finally(() => {
|
||||
this.openPromise = null;
|
||||
});
|
||||
|
||||
return this.openPromise;
|
||||
}
|
||||
|
||||
async request(op, payload = {}, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
||||
await this.open();
|
||||
const requestId = createRequestId(op);
|
||||
const body = { op, requestId, payload };
|
||||
|
||||
const responsePromise = new Promise((resolve, reject) => {
|
||||
const timer = window.setTimeout(() => {
|
||||
this.pending.delete(requestId);
|
||||
reject(new Error(`Таймаут ответа для операции ${op}`));
|
||||
}, timeoutMs);
|
||||
|
||||
this.pending.set(requestId, {
|
||||
resolve: (value) => {
|
||||
window.clearTimeout(timer);
|
||||
resolve(value);
|
||||
},
|
||||
reject: (error) => {
|
||||
window.clearTimeout(timer);
|
||||
reject(error);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
this.ws.send(JSON.stringify(body));
|
||||
return responsePromise;
|
||||
}
|
||||
|
||||
close() {
|
||||
if (this.ws) {
|
||||
this.ws.close();
|
||||
this.ws = null;
|
||||
}
|
||||
}
|
||||
|
||||
handleMessage(raw) {
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(raw);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const requestId = data?.requestId;
|
||||
if (!requestId) return;
|
||||
|
||||
const slot = this.pending.get(requestId);
|
||||
if (!slot) return;
|
||||
this.pending.delete(requestId);
|
||||
slot.resolve(data);
|
||||
}
|
||||
|
||||
failPending(message) {
|
||||
const error = new Error(message);
|
||||
for (const [, slot] of this.pending.entries()) {
|
||||
slot.reject(error);
|
||||
}
|
||||
this.pending.clear();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user