@midnightntwrk/midnight-js-level-private-state-provider 0.0.0-stage → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,292 @@
1
- # Temporary Holding Version
1
+ # ⚠️ WARNING
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > RISK: This provider lacks a recovery mechanism.
4
+ > Clearing browser cache or deleting local files permanently destroys the private state (contract state/keys).
5
+ > For assets with real-world value, this may result in irreversible financial loss.
6
+ > DO NOT use for production applications requiring data persistence.
7
+ ---
8
+
9
+ # Level Private State Provider
10
+
11
+ Encrypted LevelDB storage for Midnight private states and signing keys.
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ yarn add @midnightntwrk/midnight-js-level-private-state-provider
17
+ ```
18
+
19
+ ## Quick Start
20
+
21
+ ```typescript
22
+ import { levelPrivateStateProvider } from '@midnightntwrk/midnight-js-level-private-state-provider';
23
+
24
+ const provider = levelPrivateStateProvider({
25
+ privateStoragePasswordProvider: () => 'your-secure-password',
26
+ accountId: walletProvider.getCoinPublicKey()
27
+ });
28
+
29
+ const states = provider.forContract(contractAddress);
30
+ await states.set('stateId', privateStateData);
31
+ const state = await states.get('stateId');
32
+ ```
33
+
34
+ ## Configuration
35
+
36
+ | Option | Required | Default | Description |
37
+ | -------------------------------- | -------- | ------------------- | -------------------------------------- |
38
+ | `privateStoragePasswordProvider` | ✓ | - | Function returning encryption password |
39
+ | `accountId` | ✓ | - | The wallet's coin public key, `walletProvider.getCoinPublicKey()`, for a new store. Keep an existing store's value |
40
+ | `midnightDbName` | | `midnight-level-db` | Database name |
41
+ | `privateStateStoreName` | | `private-states` | Store name for states |
42
+ | `signingKeyStoreName` | | `signing-keys` | Store name for keys |
43
+ | `cryptoBackend` | | auto-detected (`'webcrypto'` if available, else `'noble'`) | `'webcrypto' \| 'noble'`. Auto-detects Web Crypto availability; set explicitly to force a backend (e.g. `'noble'` in Node.js tests, or `'webcrypto'` for explicit browser intent). Added in #827. |
44
+ | `levelFactory` | | `(dbName) => new Level(dbName, { createIfMissing: true })` | `LevelFactory`. Custom storage factory. The `level` package auto-selects `browser-level` (IndexedDB) or `classic-level` (Node.js) based on bundler target. |
45
+
46
+ ## Security
47
+
48
+ ### Encryption
49
+
50
+ All data is encrypted using **AES-256-GCM** with **PBKDF2-SHA256** key derivation (600,000 iterations).
51
+
52
+ ### Password Requirements
53
+
54
+ - Minimum 16 characters
55
+ - At least 3 character types (uppercase, lowercase, digits, special)
56
+ - No more than 3 consecutive identical characters
57
+ - No sequential patterns (e.g., `1234`, `abcd`)
58
+
59
+ ### Account Isolation
60
+
61
+ Each `accountId` creates isolated storage namespaces. The ID is SHA-256 hashed before use in storage paths.
62
+
63
+ For a new store, use the wallet's coin public key, `walletProvider.getCoinPublicKey()`, as it is.
64
+ For an existing store, keep the `accountId` it was created with: another value opens another,
65
+ empty store. The private states and signing keys stored under the old value stay in the database,
66
+ but this provider no longer reads them.
67
+
68
+ Contract addresses are compared in lower case, for private states and for signing keys.
69
+
70
+ ### Concurrency
71
+
72
+ Within one JavaScript process, operations on the same `midnightDbName` run one at a time, in call order.
73
+ This is what keeps a password rotation from racing a write.
74
+
75
+ An operation that needs the password holds its place in that order until `privateStoragePasswordProvider`
76
+ resolves, so a slow provider (for example, one waiting for user input) delays every later operation on
77
+ the database. The provider must not call this provider itself: the call waits behind the operation that
78
+ asked for the password and never completes.
79
+
80
+ Use one database from **one process or one browser tab only**:
81
+
82
+ - **Node.js** — a second process opening the same database fails with a LevelDB lock error.
83
+ - **Browser** — IndexedDB takes no lock, so a second tab is not refused. Two tabs writing to one
84
+ database while either rotates the password can store data that can no longer be decrypted.
85
+
86
+ ## API
87
+
88
+ ### Private States
89
+
90
+ Private states are reached per contract. A view is fixed to one contract address, so operations
91
+ for different contracts never mix, even when they run at the same time.
92
+
93
+ ```typescript
94
+ const states = provider.forContract(contractAddress);
95
+ await states.get(privateStateId); // Read state
96
+ await states.set(privateStateId, state); // Write state
97
+ await states.remove(privateStateId); // Delete state
98
+ await states.clear(); // Clear all states of this contract
99
+
100
+ await provider.clearAll(); // Clear the states of every contract of this account
101
+ ```
102
+
103
+ ### Signing Keys
104
+
105
+ ```typescript
106
+ await provider.getSigningKey(contractAddress);
107
+ await provider.setSigningKey(contractAddress, key);
108
+ await provider.removeSigningKey(contractAddress);
109
+ await provider.clearSigningKeys();
110
+ ```
111
+
112
+ `getSigningKey`, `setSigningKey` and `removeSigningKey` throw `InvalidArgumentError` for a value that is
113
+ not a contract address. `importSigningKeys` refuses an export that holds such an address with
114
+ `InvalidExportFormatError` and imports nothing.
115
+
116
+ ### Password Rotation
117
+
118
+ ```typescript
119
+ // Rotate the private state password of every contract of this account
120
+ await provider.changePassword(
121
+ () => 'old-password',
122
+ () => 'new-password'
123
+ );
124
+
125
+ // Rotate signing keys password
126
+ await provider.changeSigningKeysPassword(
127
+ () => 'old-password',
128
+ () => 'new-password'
129
+ );
130
+ ```
131
+
132
+ Password rotation is atomic—all data is re-encrypted or none is.
133
+
134
+ Each of the two stores, private states and signing keys, keeps a key check: a known value encrypted
135
+ with the store's password. Every read, write, remove and clear checks the password against it first.
136
+ A password that does not match fails with `PrivateStateDecryptionError` (reason `wrong-key`), and nothing
137
+ is changed. A rotation whose old password does not match fails with `InvalidArgumentError`.
138
+ `clearAll` and `clearSigningKeys` need the password too, so a store whose password is lost can only be
139
+ reset by deleting the database.
140
+
141
+ Both stores read the same `privateStoragePasswordProvider`, and each has its own rotation. Run
142
+ `changePassword` and `changeSigningKeysPassword`, then make the provider return the new password.
143
+ Until then, operations on a store that is already rotated fail with `wrong-key`; run them again once
144
+ the provider returns the new password.
145
+
146
+ A store written before the key check gets one on its first operation:
147
+
148
+ - if the store holds an encrypted record, only after the password has opened that record;
149
+ - if the store holds no encrypted record, with the password of that first operation.
150
+
151
+ A store that already holds records encrypted under two passwords is not repaired.
152
+
153
+ ### Export/Import
154
+
155
+ ```typescript
156
+ // Export the states of one contract
157
+ const statesExport = await provider.forContract(contractAddress).exportPrivateStates({ password: 'export-pw' });
158
+ const keysExport = await provider.exportSigningKeys({ password: 'export-pw' });
159
+
160
+ // Import
161
+ await provider.forContract(contractAddress).importPrivateStates(statesExport, {
162
+ password: 'export-pw',
163
+ conflictStrategy: 'skip' // 'skip' | 'overwrite' | 'error'
164
+ });
165
+ await provider.importSigningKeys(keysExport, {
166
+ password: 'export-pw',
167
+ conflictStrategy: 'skip'
168
+ });
169
+ ```
170
+
171
+ ### Cache Management
172
+
173
+ Encryption keys are cached to avoid repeated PBKDF2 derivation. Invalidate manually when needed:
174
+
175
+ ```typescript
176
+ provider.invalidateEncryptionCache();
177
+ ```
178
+
179
+ Cache is automatically invalidated after password rotation.
180
+
181
+ ## Migration
182
+
183
+ ### From Unscoped Storage
184
+
185
+ ```typescript
186
+ import { migrateToAccountScoped } from '@midnightntwrk/midnight-js-level-private-state-provider';
187
+
188
+ const result = await migrateToAccountScoped({ accountId: walletProvider.getCoinPublicKey() });
189
+ // Original data is preserved for rollback
190
+ ```
191
+
192
+ ### From Unencrypted Storage
193
+
194
+ Unencrypted data is automatically encrypted on first read. No action required.
195
+
196
+ ## Exports
197
+
198
+ ```typescript
199
+ import {
200
+ levelPrivateStateProvider,
201
+ migrateToAccountScoped,
202
+ StorageEncryption,
203
+ decryptValue,
204
+ timingSafeEqual,
205
+ DEFAULT_CONFIG,
206
+ type LevelPrivateStateProviderConfig,
207
+ type PrivateStoragePasswordProvider,
208
+ type PasswordRotationResult,
209
+ type MigrationResult
210
+ } from '@midnightntwrk/midnight-js-level-private-state-provider';
211
+ ```
212
+
213
+ ---
214
+
215
+ ### `timingSafeEqual`
216
+
217
+ Compares two `Buffer`s or `Uint8Array`s in constant time. If the inputs differ in length, returns false immediately (not constant-time for length mismatch). This matches the Node.js native `timingSafeEqual` behavior (which throws on length mismatch). For fixed-length buffers (e.g., hashes), this is safe. When used with variable-length buffers, you should be aware of potential timing leakage.
218
+
219
+
220
+ ## Detailed
221
+
222
+ ### Storage Structure
223
+
224
+ ```
225
+ LevelDB (midnight-level-db)
226
+ ├── private-states:{hashedAccountId}
227
+ │ ├── __midnight_encryption_metadata__ (salt, version, keyCheck)
228
+ │ └── {contractAddress}:{privateStateId} (encrypted state)
229
+ │
230
+ └── signing-keys:{hashedAccountId}
231
+ ├── __midnight_encryption_metadata__ (salt, version, keyCheck)
232
+ └── {contractAddress} (encrypted signing key)
233
+ ```
234
+
235
+ ### Data Flow
236
+
237
+ ```
238
+ ┌─────────────────────────────────────────────────────────────────┐
239
+ │ levelPrivateStateProvider() │
240
+ │ │
241
+ │ ┌──────────────┐ ┌──────────────────┐ ┌───────────────┐ │
242
+ │ │ Password │───►│ StorageEncryption│◄───│ Encryption │ │
243
+ │ │ Provider │ │ (PBKDF2 + AES) │ │ Cache │ │
244
+ │ └──────────────┘ └──────────────────┘ └───────────────┘ │
245
+ │ │ │ ▲ │
246
+ │ │ ▼ │ │
247
+ │ │ ┌──────────────────┐ │ │
248
+ │ │ │ withSubLevel() │───────────┘ │
249
+ │ │ │ (LevelDB wrapper)│ │
250
+ │ │ └──────────────────┘ │
251
+ │ │ │ │
252
+ │ ▼ ▼ │
253
+ │ ┌──────────────┐ ┌──────────────────┐ │
254
+ │ │ DB access │ │ Account-scoped │ │
255
+ │ │ queue │ │ Sublevels │ │
256
+ │ └──────────────┘ └──────────────────┘ │
257
+ └─────────────────────────────────────────────────────────────────┘
258
+ ```
259
+
260
+ ### Key Components
261
+
262
+ | Component | Description |
263
+ | ------------------------------- | ------------------------------------------------------ |
264
+ | `levelPrivateStateProvider()` | Factory returning PrivateStateProvider instance |
265
+ | `StorageEncryption` | AES-256-GCM encryption with PBKDF2 key derivation |
266
+ | `encryptionCache` | Module-level cache avoiding repeated key derivation |
267
+ | `dbAccessQueues` | Runs operations on one database one at a time |
268
+ | `superjson` | Type-preserving serialization (Buffer, BigInt, Uint8Array) |
269
+
270
+ ### Encryption Specification
271
+
272
+ | Parameter | Value |
273
+ | ------------------ | --------------- |
274
+ | Algorithm | AES-256-GCM |
275
+ | Key Derivation | PBKDF2-SHA256 |
276
+ | Iterations (V2) | 600,000 |
277
+ | Iterations (V1) | 100,000 (legacy, auto-migrates) |
278
+ | Salt Length | 32 bytes |
279
+ | IV Length | 12 bytes |
280
+ | Auth Tag Length | 16 bytes |
281
+ | Encoding | Base64 |
282
+
283
+ ## Resources
284
+
285
+ - [Midnight Network](https://midnight.network)
286
+ - [Developer Hub](https://midnight.network/developer-hub)
287
+
288
+ ## Terms & License
289
+
290
+ By using this package, you agree to [Midnight's Terms and Conditions](https://midnight.network/static/terms.pdf) and [Privacy Policy](https://midnight.network/static/privacy-policy.pdf).
291
+
292
+ Licensed under [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0).
@@ -0,0 +1,190 @@
1
+ import { PrivateStateId, PrivateStateProvider } from '@midnightntwrk/midnight-js-types';
2
+ import { AbstractLevel } from 'abstract-level';
3
+ import { Buffer } from 'buffer';
4
+ import * as _midnightntwrk_midnight_js_utils from '@midnightntwrk/midnight-js-utils';
5
+ import { MidnightJsError } from '@midnightntwrk/midnight-js-protocol/errors';
6
+ import { ContractAddress } from '@midnightntwrk/midnight-js-protocol/v9/compact-runtime';
7
+
8
+ interface CryptoBackend {
9
+ randomBytes(length: number): Uint8Array;
10
+ sha256(data: Uint8Array): Promise<Uint8Array>;
11
+ pbkdf2(password: Uint8Array, salt: Uint8Array, iterations: number, keyLength: number): Promise<Uint8Array>;
12
+ aesGcmEncrypt(key: Uint8Array, iv: Uint8Array, plaintext: Uint8Array): Promise<{
13
+ ciphertext: Uint8Array;
14
+ authTag: Uint8Array;
15
+ }>;
16
+ aesGcmDecrypt(key: Uint8Array, iv: Uint8Array, ciphertext: Uint8Array, authTag: Uint8Array): Promise<Uint8Array>;
17
+ }
18
+ type CryptoBackendType = 'webcrypto' | 'noble';
19
+
20
+ type PrivateStoragePasswordProvider = () => string | Promise<string>;
21
+ interface StorageEncryptionOptions {
22
+ existingSalt?: Buffer | Uint8Array;
23
+ cryptoBackend?: CryptoBackendType;
24
+ }
25
+ declare class StorageEncryption {
26
+ private readonly encryptionKey;
27
+ private readonly salt;
28
+ private readonly backend;
29
+ private constructor();
30
+ static create(password: string, options?: StorageEncryptionOptions): Promise<StorageEncryption>;
31
+ verifyPassword(password: string): Promise<boolean>;
32
+ encrypt(data: string): Promise<string>;
33
+ decrypt(encryptedData: string): Promise<string>;
34
+ decryptWithPassword(encryptedData: string, password: string): Promise<string>;
35
+ private authenticatedDecrypt;
36
+ static isEncrypted(data: string): boolean;
37
+ static getVersion(encryptedData: string): number;
38
+ getSalt(): Buffer;
39
+ }
40
+ declare const decryptValue: (encryptedValue: string, encryption: StorageEncryption, password: string) => Promise<string>;
41
+
42
+ /**
43
+ * Configuration properties for the LevelDB based private state provider.
44
+ */
45
+ interface LevelPrivateStateProviderConfig {
46
+ /**
47
+ * The name of the LevelDB database used to store all Midnight related data.
48
+ */
49
+ readonly midnightDbName: string;
50
+ /**
51
+ * The name of the object store containing private states.
52
+ */
53
+ readonly privateStateStoreName: string;
54
+ /**
55
+ * The name of the object store containing signing keys.
56
+ */
57
+ readonly signingKeyStoreName: string;
58
+ /**
59
+ * Provider function that returns the password used for encrypting private state.
60
+ *
61
+ * The password must satisfy the strength policy enforced by `validatePassword`
62
+ * from `@midnightntwrk/midnight-js-utils`:
63
+ * - minimum 16 characters
64
+ * - at least 3 of: uppercase, lowercase, digits, special characters
65
+ * - no more than 3 consecutive identical characters
66
+ * - no sequential patterns of length 4+ (e.g. `1234`, `abcd`)
67
+ *
68
+ * The same policy is applied to custom passwords passed to
69
+ * {@link ContractPrivateStates.exportPrivateStates} / `exportSigningKeys` and
70
+ * their `importPrivateStates` / `importSigningKeys` counterparts. Violations
71
+ * surface as `PasswordValidationError` on storage paths, wrapped as
72
+ * `PrivateStateExportError` / `SigningKeyExportError` (with `cause`) on
73
+ * export paths, and as `ImportPasswordValidationError` (with
74
+ * `passwordError`) on import paths.
75
+ *
76
+ * SECURITY: Use a strong, secret password. Never use public key material
77
+ * or other non-secret values as the password source.
78
+ *
79
+ * Private state is stored with `superjson`. Plain objects, arrays, `string`,
80
+ * `number`, `boolean`, `null`, `undefined`, `bigint`, `NaN`, `Infinity`, `Date`,
81
+ * `RegExp`, `URL`, `Map`, `Set`, `Buffer` and the nine built-in typed arrays are
82
+ * read back unchanged, and shared references and cycles are preserved. Anything
83
+ * else — including `Error`, `ArrayBuffer`, `DataView`, `BigInt64Array`, and any
84
+ * subclass of the types above — is refused by
85
+ * {@link ContractPrivateStates.set} with a `PrivateStateSerializationError`,
86
+ * because storage would drop it, empty it or read it back as a different value.
87
+ *
88
+ * @example
89
+ * ```typescript
90
+ * {
91
+ * privateStoragePasswordProvider: async () => await getSecretPassword()
92
+ * }
93
+ * ```
94
+ */
95
+ readonly privateStoragePasswordProvider: PrivateStoragePasswordProvider;
96
+ /**
97
+ * Account identifier used to scope storage. This ensures data isolation
98
+ * between different accounts/wallets using the same database.
99
+ *
100
+ * For a new store, use the wallet's coin public key, `walletProvider.getCoinPublicKey()`,
101
+ * as it is. For an existing store, keep the value it was created with: another value
102
+ * opens another, empty store, and the private states and signing keys stored under the
103
+ * old value are no longer read.
104
+ *
105
+ * The accountId is hashed (SHA-256, first 32 chars) before being used
106
+ * in storage paths.
107
+ *
108
+ * @example
109
+ * ```typescript
110
+ * {
111
+ * accountId: walletProvider.getCoinPublicKey()
112
+ * }
113
+ * ```
114
+ */
115
+ readonly accountId: string;
116
+ readonly cryptoBackend?: CryptoBackendType;
117
+ readonly levelFactory?: LevelFactory;
118
+ }
119
+ type DatabaseLevel = AbstractLevel<string | Buffer | Uint8Array, string, string>;
120
+ type LevelFactory = (dbName: string) => DatabaseLevel;
121
+ /**
122
+ * The default configuration for the level database.
123
+ */
124
+ declare const DEFAULT_CONFIG: {
125
+ /**
126
+ * The name of the database.
127
+ */
128
+ midnightDbName: string;
129
+ /**
130
+ * The name of the "level" on which to store private state.
131
+ */
132
+ privateStateStoreName: string;
133
+ /**
134
+ * The name of the "level" on which to store signing keys.
135
+ */
136
+ signingKeyStoreName: string;
137
+ };
138
+ interface PasswordRotationResult {
139
+ readonly entriesMigrated: number;
140
+ }
141
+ interface PasswordRotationOptions {
142
+ readonly maxEntries?: number;
143
+ }
144
+ /**
145
+ * Constructs an instance of {@link PrivateStateProvider} based on {@link Level} database.
146
+ *
147
+ * ⚠️ WARNING
148
+ *
149
+ * RISK: This provider lacks a recovery mechanism.
150
+ * Clearing browser cache or deleting local files permanently destroys the private state (contract state/keys).
151
+ * For assets with real-world value, this may result in irreversible financial loss.
152
+ * DO NOT use for production applications requiring data persistence.
153
+ *
154
+ * @param config Database configuration options.
155
+ */
156
+ declare const levelPrivateStateProvider: <PSI extends PrivateStateId, PS = any>(config: Partial<LevelPrivateStateProviderConfig> & Pick<LevelPrivateStateProviderConfig, "privateStoragePasswordProvider" | "accountId">) => PrivateStateProvider<PSI, PS> & {
157
+ invalidateEncryptionCache(): Promise<void>;
158
+ /** Re-encrypts the private states of every contract of this account with a new password. */
159
+ changePassword(oldPasswordProvider: PrivateStoragePasswordProvider, newPasswordProvider: PrivateStoragePasswordProvider, options?: PasswordRotationOptions): Promise<PasswordRotationResult>;
160
+ changeSigningKeysPassword(oldPasswordProvider: PrivateStoragePasswordProvider, newPasswordProvider: PrivateStoragePasswordProvider, options?: PasswordRotationOptions): Promise<PasswordRotationResult>;
161
+ };
162
+ interface MigrationResult {
163
+ readonly privateStatesMigrated: number;
164
+ readonly signingKeysMigrated: number;
165
+ }
166
+ /**
167
+ * Migrates existing unscoped private state and signing key data to account-scoped sublevels.
168
+ *
169
+ * This function copies data from the legacy unscoped locations to the new account-scoped
170
+ * locations. The original data is preserved (not deleted) to allow for safe rollback if needed.
171
+ * To remove old data after successful migration, manually clear the unscoped sublevels.
172
+ *
173
+ * Note: Running this function multiple times is safe but will re-copy all data, overwriting
174
+ * any changes made in the scoped location since the last migration.
175
+ */
176
+ declare const migrateToAccountScoped: (config: Partial<LevelPrivateStateProviderConfig> & Pick<LevelPrivateStateProviderConfig, "accountId">) => Promise<MigrationResult>;
177
+
178
+ /**
179
+ * Thrown when a signing key read from the store is neither a structured
180
+ * `SigningKey` nor a key written by a 4.x client.
181
+ */
182
+ declare class StoredSigningKeyFormatError extends MidnightJsError {
183
+ readonly code: "MIDNIGHT_JS_PR_STORED_SIGNING_KEY_INVALID";
184
+ readonly category: _midnightntwrk_midnight_js_utils.MidnightJsErrorCategory;
185
+ readonly contractAddress: ContractAddress;
186
+ constructor(contractAddress: ContractAddress);
187
+ }
188
+
189
+ export { DEFAULT_CONFIG, StorageEncryption, StoredSigningKeyFormatError, decryptValue, levelPrivateStateProvider, migrateToAccountScoped };
190
+ export type { CryptoBackend, CryptoBackendType, DatabaseLevel, LevelFactory, LevelPrivateStateProviderConfig, MigrationResult, PasswordRotationOptions, PasswordRotationResult, PrivateStoragePasswordProvider, StorageEncryptionOptions };