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 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 290x 2x 288x 288x 288x 2x 6x 5x 1x 2x 573x 573x 2x 581x 2x 579x 579x 18388x 579x 2x 581x 581x 581x 283x 283x 283x 283x 283x 283x 283x 285x 285x 270x 270x 270x 270x 270x 270x 284x 284x 284x 1x 281x 281x 270x 6x 6x 6x 6x 6x 5x 5x 243x 243x 243x 238x 238x 238x 60x 2x 2x 2x 2x 2x 509x 509x 509x 509x 509x 509x 2x 511x 511x 9126x 519x 519x 2x 8607x 509x 2x 505x 505x 8033x 8033x 8033x 24099x 24099x 24099x 2587x 21512x 24099x 39x 24060x 24099x 4x 501x 2x 514x 1x 513x 2x 511x 2x 509x 509x 4x 505x 4x 2x 514x 514x 514x 2x 63x 4x 59x 59x 1x 58x | /*
* This file is part of midnight-js.
* Copyright (C) 2025-2026 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 { Buffer } from 'buffer';
import { type CryptoBackend, type CryptoBackendType, resolveCryptoBackend } from './crypto-backend';
export type PrivateStoragePasswordProvider = () => string | Promise<string>;
export interface StorageEncryptionOptions {
existingSalt?: Buffer | Uint8Array;
cryptoBackend?: CryptoBackendType;
}
const KEY_LENGTH = 32;
const IV_LENGTH = 12;
const AUTH_TAG_LENGTH = 16;
const SALT_LENGTH = 32;
const PBKDF2_ITERATIONS_V1 = 100000;
const PBKDF2_ITERATIONS_V2 = 600000;
const ENCRYPTION_VERSION_V1 = 1;
const ENCRYPTION_VERSION_V2 = 2;
const CURRENT_ENCRYPTION_VERSION = ENCRYPTION_VERSION_V2;
const VERSION_PREFIX_LENGTH = 1;
const HEADER_LENGTH = VERSION_PREFIX_LENGTH + SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH;
interface EncryptedComponents {
version: number;
salt: Buffer;
iv: Buffer;
authTag: Buffer;
encrypted: Buffer;
}
const extractEncryptedComponents = (data: Buffer): EncryptedComponents => {
if (data.length < HEADER_LENGTH) {
throw new Error('Invalid encrypted data: too short');
}
const version = data[0];
Iif (version !== ENCRYPTION_VERSION_V1 && version !== ENCRYPTION_VERSION_V2) {
throw new Error(`Unsupported encryption version: ${version}`);
}
return {
version,
salt: data.subarray(VERSION_PREFIX_LENGTH, VERSION_PREFIX_LENGTH + SALT_LENGTH),
iv: data.subarray(VERSION_PREFIX_LENGTH + SALT_LENGTH, VERSION_PREFIX_LENGTH + SALT_LENGTH + IV_LENGTH),
authTag: data.subarray(
VERSION_PREFIX_LENGTH + SALT_LENGTH + IV_LENGTH,
VERSION_PREFIX_LENGTH + SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH
),
encrypted: data.subarray(HEADER_LENGTH)
};
};
const getIterationsForVersion = (version: number): number => {
switch (version) {
case ENCRYPTION_VERSION_V1:
return PBKDF2_ITERATIONS_V1;
case ENCRYPTION_VERSION_V2:
return PBKDF2_ITERATIONS_V2;
default:
throw new Error(`Unsupported encryption version: ${version}`);
}
};
const deriveEncryptionKey = async (
backend: CryptoBackend,
password: string,
salt: Uint8Array,
iterations: number,
): Promise<Uint8Array> => {
const passwordBytes = new TextEncoder().encode(password);
return backend.pbkdf2(passwordBytes, salt, iterations, KEY_LENGTH);
};
const constantTimeBufferEqual = (aBuf: Buffer, bBuf: Buffer): boolean => {
if (aBuf.length !== bBuf.length) {
throw new RangeError('Input buffers must have the same byte length');
}
let result = 0;
for (let i = 0; i < aBuf.length; i++) {
result |= aBuf[i] ^ bBuf[i];
}
return result === 0;
};
/**
* Compares two Buffers or Uint8Arrays in constant time.
*
* @param a - First buffer to compare.
* @param b - Second buffer to compare.
* @returns `true` if the buffers are equal, `false` otherwise.
*
* @remarks
* If the inputs differ in length, an error is thrown (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. For variable-length buffers, callers should be
* aware of potential timing leakage.
*/
export const timingSafeEqual = (a: Buffer | Uint8Array, b: Buffer | Uint8Array): boolean => {
const aBuf = Buffer.isBuffer(a) ? a : Buffer.from(a);
const bBuf = Buffer.isBuffer(b) ? b : Buffer.from(b);
return constantTimeBufferEqual(aBuf, bBuf);
};
export class StorageEncryption {
private readonly encryptionKey: Uint8Array;
private readonly salt: Uint8Array;
private readonly backend: CryptoBackend;
private constructor(encryptionKey: Uint8Array, salt: Uint8Array, backend: CryptoBackend) {
this.encryptionKey = encryptionKey;
this.salt = salt;
this.backend = backend;
}
static async create(password: string, options?: StorageEncryptionOptions): Promise<StorageEncryption> {
const backend = resolveCryptoBackend(options?.cryptoBackend);
const salt = options?.existingSalt ? new Uint8Array(options.existingSalt) : backend.randomBytes(SALT_LENGTH);
const encryptionKey = await deriveEncryptionKey(backend, password, salt, PBKDF2_ITERATIONS_V2);
return new StorageEncryption(encryptionKey, salt, backend);
}
async verifyPassword(password: string): Promise<boolean> {
const candidateKey = await deriveEncryptionKey(this.backend, password, this.salt, PBKDF2_ITERATIONS_V2);
return timingSafeEqual(candidateKey, this.encryptionKey);
}
async encrypt(data: string): Promise<string> {
const plaintext = new TextEncoder().encode(data);
const iv = this.backend.randomBytes(IV_LENGTH);
const { ciphertext, authTag } = await this.backend.aesGcmEncrypt(this.encryptionKey, iv, plaintext);
const version = new Uint8Array([CURRENT_ENCRYPTION_VERSION]);
const result = Buffer.concat([version, this.salt, iv, authTag, ciphertext]);
return result.toString('base64');
}
async decrypt(encryptedData: string): Promise<string> {
const data = Buffer.from(encryptedData, 'base64');
const { version, salt, iv, authTag, encrypted } = extractEncryptedComponents(data);
if (version === ENCRYPTION_VERSION_V1) {
throw new Error('V1 encrypted data requires password for decryption. Use decryptWithPassword() instead.');
}
Iif (!timingSafeEqual(Buffer.from(this.salt), salt)) {
throw new Error('Salt mismatch: data was encrypted with a different password');
}
const decrypted = await this.backend.aesGcmDecrypt(this.encryptionKey, iv, encrypted, authTag);
return Buffer.from(decrypted).toString('utf-8');
}
async decryptWithPassword(encryptedData: string, password: string): Promise<string> {
const data = Buffer.from(encryptedData, 'base64');
const { version, salt, iv, authTag, encrypted } = extractEncryptedComponents(data);
Iif (!timingSafeEqual(Buffer.from(this.salt), salt)) {
throw new Error('Salt mismatch: data was encrypted with a different password');
}
const iterations = getIterationsForVersion(version);
const decryptionKey = version === CURRENT_ENCRYPTION_VERSION
? this.encryptionKey
: await deriveEncryptionKey(this.backend, password, salt, iterations);
const decrypted = await this.backend.aesGcmDecrypt(decryptionKey, iv, encrypted, authTag);
return Buffer.from(decrypted).toString('utf-8');
}
static isEncrypted(data: string): boolean {
const buffer = Buffer.from(data, 'base64');
const version = buffer[0];
return buffer.length >= HEADER_LENGTH &&
(version === ENCRYPTION_VERSION_V1 || version === ENCRYPTION_VERSION_V2);
}
static getVersion(encryptedData: string): number {
const buffer = Buffer.from(encryptedData, 'base64');
Iif (buffer.length < 1) {
throw new Error('Invalid encrypted data: too short');
}
return buffer[0];
}
getSalt(): Buffer {
return Buffer.from(this.salt);
}
}
const MIN_PASSWORD_LENGTH = 16;
const MIN_CHARACTER_CLASSES = 3;
const MAX_CONSECUTIVE_REPEATED = 3;
const MIN_SEQUENTIAL_LENGTH = 4;
const countCharacterClasses = (password: string): number => {
let count = 0;
if (/[a-z]/.test(password)) count++;
if (/[A-Z]/.test(password)) count++;
if (/[0-9]/.test(password)) count++;
if (/[^a-zA-Z0-9]/.test(password)) count++;
return count;
};
const hasRepeatedCharacters = (password: string): boolean => {
let consecutiveCount = 1;
for (let i = 1; i < password.length; i++) {
if (password[i] === password[i - 1]) {
consecutiveCount++;
if (consecutiveCount > MAX_CONSECUTIVE_REPEATED) {
return true;
}
} else {
consecutiveCount = 1;
}
}
return false;
};
const hasSequentialPattern = (password: string): boolean => {
const lowerPassword = password.toLowerCase();
for (let i = 0; i <= lowerPassword.length - MIN_SEQUENTIAL_LENGTH; i++) {
let ascendingCount = 1;
let descendingCount = 1;
for (let j = 1; j < MIN_SEQUENTIAL_LENGTH; j++) {
const currentCode = lowerPassword.charCodeAt(i + j);
const prevCode = lowerPassword.charCodeAt(i + j - 1);
if (currentCode === prevCode + 1) {
ascendingCount++;
} else {
ascendingCount = 1;
}
if (currentCode === prevCode - 1) {
descendingCount++;
} else {
descendingCount = 1;
}
if (ascendingCount >= MIN_SEQUENTIAL_LENGTH || descendingCount >= MIN_SEQUENTIAL_LENGTH) {
return true;
}
}
}
return false;
};
const validatePassword = (password: string): void => {
if (!password) {
throw new Error(
'Password is required for private state encryption.\n' +
'Please provide a password via privateStoragePasswordProvider in the configuration.'
);
}
if (password.length < MIN_PASSWORD_LENGTH) {
throw new Error(
`Password must be at least ${MIN_PASSWORD_LENGTH} characters long. Current length: ${password.length}`
);
}
if (hasRepeatedCharacters(password)) {
throw new Error(
`Password contains too many repeated characters (more than ${MAX_CONSECUTIVE_REPEATED} identical in a row)`
);
}
const characterClasses = countCharacterClasses(password);
if (characterClasses < MIN_CHARACTER_CLASSES) {
throw new Error(
`Password must contain at least ${MIN_CHARACTER_CLASSES} of: uppercase letters, lowercase letters, digits, special characters. Found: ${characterClasses}`
);
}
if (hasSequentialPattern(password)) {
throw new Error(
"Password contains sequential patterns (e.g., '1234', 'abcd'). Use a more random password"
);
}
};
export const getPasswordFromProvider = async (provider: PrivateStoragePasswordProvider): Promise<string> => {
const password = await provider();
validatePassword(password);
return password;
};
export const decryptValue = async (
encryptedValue: string,
encryption: StorageEncryption,
password: string
): Promise<string> => {
if (!StorageEncryption.isEncrypted(encryptedValue)) {
throw new Error(
'Unrecognized or unencrypted data encountered during decryption'
);
}
const version = StorageEncryption.getVersion(encryptedValue);
if (version === 1) {
return encryption.decryptWithPassword(encryptedValue, password);
}
return encryption.decrypt(encryptedValue);
};
|