All files level-private-state-provider.ts

95.78% Statements 182/190
91.48% Branches 86/94
100% Functions 33/33
95.74% Lines 180/188

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595                                                                                  1x         1x         1x                                                                                               1x                             1x   373x 26x 45x         1x         424x     424x     424x 424x 424x 424x   424x 424x       1x   1x         175x   175x 175x 175x 175x 28x   147x 147x 147x   28x 28x       28x 28x         1x           88x   88x 88x 88x   87x 30x         57x 57x             57x   57x       57x   1x     1x               1x         15x   15x 15x   15x   36x 15x         21x 21x           21x 21x     15x                             1x 1x 1x 1x         1x 15x 2x                 1x 23x 1x   22x 1x                                   1x     110x   110x 1x           109x 1x           108x 2x   110x   110x 141x 3x   138x     110x   98x     74x 74x               4x 4x 3x       63x 63x         62x 62x   62x 62x       38x 1x   37x     15x               2x     2x       10x         10x 10x   10x     10x       32x       16x       16x     16x 4x       15x     12x             15x 15x 15x 21x 21x 21x       15x 1x     14x 1x             13x         19x         13x 13x   13x                     26x       26x 26x     26x 1x       25x 2x       23x     23x 11x       20x       10x 10x 10x 10x 10x     4x       16x           2x       14x 1x           13x     13x 1x     12x 1x             11x 8x 8x 11x 11x 3x     8x 2x         9x 9x 9x   9x 12x 12x   12x 3x 2x 2x 1x 1x         10x 10x   9x 8x       8x        
/*
 * This file is part of midnight-js.
 * Copyright (C) 2025 Midnight Foundation
 * SPDX-License-Identifier: Apache-2.0
 * Licensed under the Apache License, Version 2.0 (the "License");
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
import type { ContractAddress, SigningKey } from '@midnight-ntwrk/compact-runtime';
import {
  ExportDecryptionError,
  type ExportPrivateStatesOptions,
  ImportConflictError,
  type ImportPrivateStatesOptions,
  type ImportPrivateStatesResult,
  InvalidExportFormatError,
  MAX_EXPORT_STATES,
  type PrivateStateExport,
  PrivateStateExportError,
  type PrivateStateId,
  type PrivateStateProvider,
  type WalletProvider
} from '@midnight-ntwrk/midnight-js-types';
import { type AbstractSublevel } from 'abstract-level';
import { Buffer } from 'buffer';
import { Level } from 'level';
import _ from 'lodash';
import * as superjson from 'superjson';
 
import { getPasswordFromProvider, type PrivateStoragePasswordProvider, StorageEncryption } from './storage-encryption';
 
/**
 * The default name of the indexedDB database for Midnight.
 */
export const MN_LDB_DEFAULT_DB_NAME = 'midnight-level-db';
 
/**
 * The default name of the private state store.
 */
export const MN_LDB_DEFAULT_PRIS_STORE_NAME = 'private-states';
 
/**
 * The default name of the signing key store.
 */
export const MN_LDB_DEFAULT_KEY_STORE_NAME = 'signing-keys';
 
/**
 * Optional properties for the indexedDB based private state provider configuration.
 */
export interface LevelPrivateStateProviderConfig {
  /**
   * The name of the LevelDB database used to store all Midnight related data.
   */
  readonly midnightDbName: string;
  /**
   * The name of the object store containing private states.
   */
  readonly privateStateStoreName: string;
  /**
   * The name of the object store containing signing keys.
   */
  readonly signingKeyStoreName: string;
  /**
   * Wallet provider used to get the encryption public key for password derivation.
   * If privateStoragePasswordProvider is not provided, the wallet's encryption public key
   * will be used as the password.
   */
  readonly walletProvider?: WalletProvider;
  /**
   * Provider function that returns the password used for encrypting private state.
   * The password must be at least 16 characters long.
   *
   * If not provided, defaults to using walletProvider.getEncryptionPublicKey().
   *
   * @example
   * ```typescript
   * // Using default (wallet's encryption public key)
   * { walletProvider: wallet }
   *
   * // Using custom password provider
   * {
   *   walletProvider: wallet,
   *   privateStoragePasswordProvider: async () => await getUserPassword()
   * }
   * ```
   */
  readonly privateStoragePasswordProvider?: PrivateStoragePasswordProvider;
}
 
/**
 * The default configuration for the level database.
 */
export const DEFAULT_CONFIG = {
  /**
   * The name of the database.
   */
  midnightDbName: MN_LDB_DEFAULT_DB_NAME,
  /**
   * The name of the "level" on which to store private state.
   */
  privateStateStoreName: MN_LDB_DEFAULT_PRIS_STORE_NAME,
  /**
   * The name of the "level" on which to store signing keys.
   */
  signingKeyStoreName: MN_LDB_DEFAULT_KEY_STORE_NAME
};
 
superjson.registerCustom<Buffer, string>(
  {
    isApplicable: (v): v is Buffer => v instanceof Buffer,
    serialize: (v) => v.toString('hex'),
    deserialize: (v) => Buffer.from(v, 'hex')
  },
  'buffer'
);
 
const withSubLevel = async <K, V, A>(
  dbName: string,
  levelName: string,
  thunk: (subLevel: AbstractSublevel<Level, string | Uint8Array | Buffer, K, V>) => Promise<A>
): Promise<A> => {
  const level = new Level(dbName, {
    createIfMissing: true
  });
  const subLevel = level.sublevel<K, V>(levelName, {
    valueEncoding: 'utf-8'
  });
  try {
    await level.open();
    await subLevel.open();
    return await thunk(subLevel);
  } finally {
    await subLevel.close();
    await level.close();
  }
};
 
const METADATA_KEY = '__midnight_encryption_metadata__';
 
const getOrCreateEncryption = async (
  dbName: string,
  levelName: string,
  passwordProvider: PrivateStoragePasswordProvider
): Promise<StorageEncryption> => {
  const password = await getPasswordFromProvider(passwordProvider);
 
  return withSubLevel<string, string, StorageEncryption>(dbName, levelName, async (subLevel) => {
    try {
      const metadataJson = await subLevel.get(METADATA_KEY);
      if (!metadataJson) {
        throw new Error('Metadata not found');
      }
      const metadata = JSON.parse(metadataJson);
      const salt = Buffer.from(metadata.salt, 'hex');
      return new StorageEncryption(password, salt);
    } catch {
      const encryption = new StorageEncryption(password);
      const metadata = {
        salt: encryption.getSalt().toString('hex'),
        version: 1
      };
      await subLevel.put(METADATA_KEY, JSON.stringify(metadata));
      return encryption;
    }
  });
};
 
const subLevelMaybeGet = async <K, V>(
  dbName: string,
  levelName: string,
  key: K,
  passwordProvider: PrivateStoragePasswordProvider
): Promise<V | null> => {
  const encryption = await getOrCreateEncryption(dbName, levelName, passwordProvider);
 
  return withSubLevel<K, string, V | null>(dbName, levelName, async (subLevel) => {
    try {
      const encryptedValue = await subLevel.get(key);
 
      if (encryptedValue === undefined) {
        return null;
      }
 
      let decryptedValue: string;
 
      if (StorageEncryption.isEncrypted(encryptedValue)) {
        decryptedValue = encryption.decrypt(encryptedValue);
      } else E{
        decryptedValue = encryptedValue;
        const reEncrypted = encryption.encrypt(encryptedValue);
        await subLevel.put(key, reEncrypted);
      }
 
      const value = superjson.parse<V>(decryptedValue);
 
      Iif (value === undefined) {
        return null;
      }
 
      return value;
    } catch (error: unknown) {
      Iif (error && typeof error === 'object' && 'code' in error && error.code === 'LEVEL_NOT_FOUND') {
        return null;
      }
      throw error;
    }
  });
};
 
/**
 * Iterate all key-value pairs in a sublevel, excluding metadata keys.
 */
const getAllEntries = async <K extends string, V>(
  dbName: string,
  levelName: string,
  passwordProvider: PrivateStoragePasswordProvider
): Promise<Map<K, V>> => {
  const encryption = await getOrCreateEncryption(dbName, levelName, passwordProvider);
 
  return withSubLevel<K, string, Map<K, V>>(dbName, levelName, async (subLevel) => {
    const entries = new Map<K, V>();
 
    for await (const [key, encryptedValue] of subLevel.iterator()) {
      // Skip metadata key
      if (key === METADATA_KEY) {
        continue;
      }
 
      let decryptedValue: string;
 
      if (StorageEncryption.isEncrypted(encryptedValue)) {
        decryptedValue = encryption.decrypt(encryptedValue);
      } else E{
        // Legacy unencrypted data
        decryptedValue = encryptedValue;
      }
 
      const value = superjson.parse<V>(decryptedValue);
      entries.set(key as K, value);
    }
 
    return entries;
  });
};
 
/**
 * Internal structure of the decrypted export payload.
 * Includes metadata to ensure it's authenticated by the encryption.
 */
interface PrivateStatePayload<PSI extends PrivateStateId = PrivateStateId> {
  readonly version: number;
  readonly exportedAt: string;
  readonly stateCount: number;
  readonly states: Record<PSI, string>;
}
 
const CURRENT_EXPORT_VERSION = 1;
const SUPPORTED_EXPORT_VERSIONS = [1];
const EXPECTED_SALT_LENGTH = 64; // 32 bytes as hex
const MIN_PASSWORD_LENGTH = 16;
 
/**
 * Validates a custom password meets minimum requirements.
 */
const validateExportPassword = (password: string): void => {
  if (password.length < MIN_PASSWORD_LENGTH) {
    throw new PrivateStateExportError(
      `Password must be at least ${MIN_PASSWORD_LENGTH} characters`
    );
  }
};
 
/**
 * Validates the salt format and length.
 */
const validateSalt = (salt: string): void => {
  if (salt.length !== EXPECTED_SALT_LENGTH) {
    throw new InvalidExportFormatError('Invalid salt length');
  }
  if (!/^[0-9a-fA-F]+$/.test(salt)) {
    throw new InvalidExportFormatError('Invalid salt format');
  }
};
 
/* eslint-disable @typescript-eslint/no-explicit-any */
 
/**
 * Constructs an instance of {@link PrivateStateProvider} based on {@link Level} database.
 *
 * ⚠️ WARNING
 *
 * RISK: This provider lacks a recovery mechanism.
 * Clearing browser cache or deleting local files permanently destroys the private state (contract state/keys).
 * For assets with real-world value, this may result in irreversible financial loss.
 * DO NOT use for production applications requiring data persistence.
 *
 * @param config Database configuration options.
 */
export const levelPrivateStateProvider = <PSI extends PrivateStateId, PS = any>(
  config: Partial<LevelPrivateStateProviderConfig>
): PrivateStateProvider<PSI, PS> => {
  const fullConfig = _.defaults(config, DEFAULT_CONFIG);
 
  if (config.privateStoragePasswordProvider && config.walletProvider) {
    throw new Error(
      'Cannot provide both privateStoragePasswordProvider and walletProvider.\n' +
      'Provide only one: walletProvider for default behavior, or privateStoragePasswordProvider for custom password.'
    );
  }
 
  if (!config.privateStoragePasswordProvider && !config.walletProvider) {
    throw new Error(
      'Either privateStoragePasswordProvider or walletProvider must be provided.\n' +
      'Provide walletProvider to use wallet encryption key, or privateStoragePasswordProvider for custom password.'
    );
  }
 
  const passwordProvider: PrivateStoragePasswordProvider = config.privateStoragePasswordProvider ||
    (() => config.walletProvider!.getEncryptionPublicKey());
 
  let contractAddress: ContractAddress | null = null;
 
  const getScopedKey = (privateStateId: PSI): string => {
    if (contractAddress === null) {
      throw new Error('Contract address not set. Call setContractAddress() before accessing private state.');
    }
    return `${contractAddress}:${privateStateId}`;
  };
 
  return {
    setContractAddress(address: ContractAddress): void {
      contractAddress = address;
    },
    async get(privateStateId: PSI): Promise<PS | null> {
      const scopedKey = getScopedKey(privateStateId);
      return subLevelMaybeGet<string, PS>(
        fullConfig.midnightDbName,
        fullConfig.privateStateStoreName,
        scopedKey,
        passwordProvider
      );
    },
    async remove(privateStateId: PSI): Promise<void> {
      const scopedKey = getScopedKey(privateStateId);
      return withSubLevel<string, string, void>(fullConfig.midnightDbName, fullConfig.privateStateStoreName, (subLevel) =>
        subLevel.del(scopedKey)
      );
    },
    async set(privateStateId: PSI, state: PS): Promise<void> {
      const scopedKey = getScopedKey(privateStateId);
      const encryption = await getOrCreateEncryption(
        fullConfig.midnightDbName,
        fullConfig.privateStateStoreName,
        passwordProvider
      );
      const serialized = superjson.stringify(state);
      const encrypted = encryption.encrypt(serialized);
 
      return withSubLevel<string, string, void>(fullConfig.midnightDbName, fullConfig.privateStateStoreName, (subLevel) =>
        subLevel.put(scopedKey, encrypted)
      );
    },
    async clear(): Promise<void> {
      if (contractAddress === null) {
        throw new Error('Contract address not set. Call setContractAddress() before accessing private state.');
      }
      return withSubLevel(fullConfig.midnightDbName, fullConfig.privateStateStoreName, (subLevel) => subLevel.clear());
    },
    getSigningKey(address: ContractAddress): Promise<SigningKey | null> {
      return subLevelMaybeGet<ContractAddress, SigningKey>(
        fullConfig.midnightDbName,
        fullConfig.signingKeyStoreName,
        address,
        passwordProvider
      );
    },
    removeSigningKey(address: ContractAddress): Promise<void> {
      return withSubLevel<ContractAddress, string, void>(
        fullConfig.midnightDbName,
        fullConfig.signingKeyStoreName,
        (subLevel) => subLevel.del(address)
      );
    },
    async setSigningKey(address: ContractAddress, signingKey: SigningKey): Promise<void> {
      const encryption = await getOrCreateEncryption(
        fullConfig.midnightDbName,
        fullConfig.signingKeyStoreName,
        passwordProvider
      );
      const serialized = superjson.stringify(signingKey);
      const encrypted = encryption.encrypt(serialized);
 
      return withSubLevel<ContractAddress, string, void>(
        fullConfig.midnightDbName,
        fullConfig.signingKeyStoreName,
        (subLevel) => subLevel.put(address, encrypted)
      );
    },
    clearSigningKeys(): Promise<void> {
      return withSubLevel(fullConfig.midnightDbName, fullConfig.signingKeyStoreName, (subLevel) => subLevel.clear());
    },
 
    async exportPrivateStates(options?: ExportPrivateStatesOptions): Promise<PrivateStateExport> {
      Iif (contractAddress === null) {
        throw new Error('Contract address not set. Call setContractAddress() before exporting private states.');
      }
 
      const maxStates = options?.maxStates ?? MAX_EXPORT_STATES;
 
      // Validate custom password if provided
      if (options?.password !== undefined) {
        validateExportPassword(options.password);
      }
 
      // Determine export password - use provided password or storage password
      const exportPassword = options?.password ?? await getPasswordFromProvider(passwordProvider);
 
      // Get all private states (not signing keys)
      const allStates = await getAllEntries<string, PS>(
        fullConfig.midnightDbName,
        fullConfig.privateStateStoreName,
        passwordProvider
      );
 
      // Filter and extract only states for the current contract address
      const prefix = `${contractAddress}:`;
      const states = new Map<PSI, PS>();
      for (const [scopedKey, value] of allStates.entries()) {
        Eif (scopedKey.startsWith(prefix)) {
          const rawStateId = scopedKey.slice(prefix.length) as PSI;
          states.set(rawStateId, value);
        }
      }
 
      if (states.size === 0) {
        throw new PrivateStateExportError('No private states to export');
      }
 
      if (states.size > maxStates) {
        throw new PrivateStateExportError(
          `Too many states to export (${states.size}). Maximum allowed: ${maxStates}`
        );
      }
 
      // Serialize states using superjson (to preserve types like BigInt, Buffer, etc.)
      // Include metadata in the encrypted payload to ensure it's authenticated
      const payload: PrivateStatePayload<PSI> = {
        version: CURRENT_EXPORT_VERSION,
        exportedAt: new Date().toISOString(),
        stateCount: states.size,
        states: Object.fromEntries(
          Array.from(states.entries()).map(([key, value]) => [key, superjson.stringify(value)])
        ) as Record<PSI, string>
      };
 
      // Create new encryption instance for export (different salt from storage)
      const exportEncryption = new StorageEncryption(exportPassword);
      const encryptedPayload = exportEncryption.encrypt(JSON.stringify(payload));
 
      return {
        format: 'midnight-private-state-export',
        encryptedPayload,
        salt: exportEncryption.getSalt().toString('hex')
      };
    },
 
    async importPrivateStates(
      exportData: PrivateStateExport,
      options?: ImportPrivateStatesOptions
    ): Promise<ImportPrivateStatesResult> {
      Iif (contractAddress === null) {
        throw new Error('Contract address not set. Call setContractAddress() before importing private states.');
      }
 
      const conflictStrategy = options?.conflictStrategy ?? 'error';
      const maxStates = options?.maxStates ?? MAX_EXPORT_STATES;
 
      // Validate format identifier
      if (exportData.format !== 'midnight-private-state-export') {
        throw new InvalidExportFormatError('Unrecognized export format');
      }
 
      // Validate structure
      if (!exportData.encryptedPayload || !exportData.salt) {
        throw new InvalidExportFormatError('Missing required fields');
      }
 
      // Validate salt format
      validateSalt(exportData.salt);
 
      // Validate custom password if provided
      if (options?.password !== undefined) {
        validateExportPassword(options.password);
      }
 
      // Determine import password - use provided password or storage password
      const importPassword = options?.password ?? await getPasswordFromProvider(passwordProvider);
 
      // Decrypt the payload - use single generic error to prevent oracle attacks
      let payload: PrivateStatePayload<PSI>;
      try {
        const salt = Buffer.from(exportData.salt, 'hex');
        const importEncryption = new StorageEncryption(importPassword, salt);
        const decryptedJson = importEncryption.decrypt(exportData.encryptedPayload);
        payload = JSON.parse(decryptedJson);
      } catch {
        // Single generic error - don't reveal whether password was wrong or data was corrupted
        throw new ExportDecryptionError();
      }
 
      // Validate payload structure (metadata is now inside encrypted payload)
      if (
        !payload.states ||
        typeof payload.states !== 'object' ||
        typeof payload.version !== 'number' ||
        typeof payload.stateCount !== 'number'
      ) {
        throw new ExportDecryptionError();
      }
 
      // Validate version from authenticated payload
      if (!SUPPORTED_EXPORT_VERSIONS.includes(payload.version)) {
        throw new InvalidExportFormatError(
          `Export version ${payload.version} is not supported. Supported versions: ${SUPPORTED_EXPORT_VERSIONS.join(', ')}`
        );
      }
 
      // stateIds are raw state IDs (not scoped with contract address)
      const stateIds = Object.keys(payload.states) as PSI[];
 
      // Validate state count matches and is within limits
      if (stateIds.length !== payload.stateCount) {
        throw new ExportDecryptionError();
      }
 
      if (stateIds.length > maxStates) {
        throw new InvalidExportFormatError(
          `Too many states in export (${stateIds.length}). Maximum allowed: ${maxStates}`
        );
      }
 
      // Check for conflicts if strategy is 'error'
      // Use this.get() which properly scopes the state IDs
      if (conflictStrategy === 'error') {
        let conflictCount = 0;
        for (const stateId of stateIds) {
          const existing = await this.get(stateId);
          if (existing !== null) {
            conflictCount++;
          }
        }
        if (conflictCount > 0) {
          throw new ImportConflictError(conflictCount);
        }
      }
 
      // Import states
      let imported = 0;
      let skipped = 0;
      let overwritten = 0;
 
      for (const stateId of stateIds) {
        const serializedState = payload.states[stateId];
        const existingState = await this.get(stateId);
 
        if (existingState !== null) {
          if (conflictStrategy === 'skip') {
            skipped++;
            continue;
          E} else if (conflictStrategy === 'overwrite') {
            overwritten++;
          }
        }
 
        // Deserialize and store the state
        const state = superjson.parse<PS>(serializedState);
        await this.set(stateId, state);
 
        if (existingState === null) {
          imported++;
        }
      }
 
      return { imported, skipped, overwritten };
    }
  };
};