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 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 270x 2x 268x 268x 268x 2x 3x 2x 1x 2x 531x 2x 2x 282x 282x 282x 282x 257x 257x 257x 259x 274x 274x 274x 256x 256x 256x 256x 256x 256x 256x 256x 267x 267x 267x 1x 264x 264x 264x 264x 264x 3x 3x 3x 3x 3x 3x 3x 3x 3x 224x 224x 224x 224x 226x 226x 226x 53x 2x 2x 2x 2x 2x 491x 491x 491x 491x 491x 491x 2x 493x 493x 8802x 501x 501x 2x 8301x 491x 2x 487x 487x 7745x 7745x 7745x 23235x 23235x 23235x 2515x 20720x 23235x 39x 23196x 23235x 4x 483x 2x 496x 1x 495x 2x 493x 2x 491x 491x 4x 487x 4x 2x 496x 496x 496x 2x 54x 54x 54x 54x | /*
* 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 { createCipheriv, createDecipheriv, createHash, pbkdf2Sync, randomBytes } from 'crypto';
import * as crypto from 'crypto';
export type PrivateStoragePasswordProvider = () => string | Promise<string>;
const ALGORITHM = 'aes-256-gcm';
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;
const HAS_NATIVE_TIMINGSAFEEQUAL =
'timingSafeEqual' in crypto && typeof crypto.timingSafeEqual === 'function';
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 hashPassword = (password: string): string => {
return createHash('sha256').update(password).digest('hex');
};
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);
Eif (HAS_NATIVE_TIMINGSAFEEQUAL) {
// Use the native `timingSafeEqual` function and let any errors propagate.
return crypto.timingSafeEqual(aBuf, bBuf);
}
return constantTimeBufferEqual(aBuf, bBuf);
};
export class StorageEncryption {
private readonly encryptionKey: Buffer;
private readonly salt: Buffer;
private readonly passwordHash: string;
constructor(password: string, existingSalt?: Buffer) {
this.salt = existingSalt ?? randomBytes(SALT_LENGTH);
this.encryptionKey = this.deriveKey(password, this.salt, PBKDF2_ITERATIONS_V2);
this.passwordHash = hashPassword(password);
}
private deriveKey(password: string, salt: Buffer, iterations: number): Buffer {
return pbkdf2Sync(password, salt, iterations, KEY_LENGTH, 'sha256');
}
verifyPassword(password: string): boolean {
const inputHash = Buffer.from(hashPassword(password), 'hex');
const storedHash = Buffer.from(this.passwordHash, 'hex');
return timingSafeEqual(inputHash, storedHash);
}
encrypt(data: string): string {
const plaintext = Buffer.from(data, 'utf-8');
const iv = randomBytes(IV_LENGTH);
const cipher = createCipheriv(ALGORITHM, this.encryptionKey, iv);
const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
const authTag = cipher.getAuthTag();
const version = Buffer.from([CURRENT_ENCRYPTION_VERSION]);
const result = Buffer.concat([version, this.salt, iv, authTag, encrypted]);
return result.toString('base64');
}
decrypt(encryptedData: string): 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 (!this.salt.equals(salt)) {
throw new Error('Salt mismatch: data was encrypted with a different password');
}
const decipher = createDecipheriv(ALGORITHM, this.encryptionKey, iv, { authTagLength: AUTH_TAG_LENGTH });
decipher.setAuthTag(authTag);
const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
return decrypted.toString('utf-8');
}
decryptWithPassword(encryptedData: string, password: string): string {
const data = Buffer.from(encryptedData, 'base64');
const { version, salt, iv, authTag, encrypted } = extractEncryptedComponents(data);
Iif (!this.salt.equals(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
: this.deriveKey(password, salt, iterations);
const decipher = createDecipheriv(ALGORITHM, decryptionKey, iv, { authTagLength: AUTH_TAG_LENGTH });
decipher.setAuthTag(authTag);
const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
return decrypted.toString('utf-8');
}
static isEncrypted(data: string): boolean {
try {
const buffer = Buffer.from(data, 'base64');
const version = buffer[0];
return buffer.length >= HEADER_LENGTH &&
(version === ENCRYPTION_VERSION_V1 || version === ENCRYPTION_VERSION_V2);
} catch {
return false;
}
}
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 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 = (
encryptedValue: string,
encryption: StorageEncryption,
password: string
): string => {
Iif (!StorageEncryption.isEncrypted(encryptedValue)) {
console.debug('MIDNIGHT: Encountered unencrypted data during decryption - passing through as-is');
return encryptedValue;
}
const version = StorageEncryption.getVersion(encryptedValue);
Iif (version === 1) {
return encryption.decryptWithPassword(encryptedValue, password);
}
return encryption.decrypt(encryptedValue);
};
|