feat(browser): Implement fallback SHA256 for non-HTTPS environments and enhance browser tests for consistent hashing

This commit is contained in:
Juergen Kunz
2025-06-19 23:03:36 +00:00
parent 0bae2d6eec
commit 23ad99d0e2
7 changed files with 250 additions and 10 deletions

View File

@ -1,4 +1,5 @@
import * as plugins from './plugins.js';
import { sha256Fallback } from './sha256.fallback.js';
/**
* Convert ArrayBuffer to hex string
@ -21,15 +22,28 @@ const hex = (buffer: ArrayBuffer): string => {
return hexCodes.join("");
};
/**
* Check if crypto.subtle is available
*/
const isCryptoSubtleAvailable = (): boolean => {
return typeof crypto !== 'undefined' && crypto.subtle !== undefined;
};
/**
* Computes sha256 Hash from String
*/
export const sha256FromString = async (stringArg: string): Promise<string> => {
// Get the string as arraybuffer.
const buffer = (new TextEncoder()).encode(stringArg);
const hash = await crypto.subtle.digest("SHA-256", buffer);
const result = hex(hash);
return result;
if (isCryptoSubtleAvailable()) {
const hash = await crypto.subtle.digest("SHA-256", buffer);
const result = hex(hash);
return result;
} else {
// Use fallback for non-HTTPS environments
return sha256Fallback(buffer);
}
};
/**
@ -45,9 +59,15 @@ export const sha256FromStringSync = (stringArg: string): string => {
* Computes sha256 Hash from ArrayBuffer
*/
export const sha256FromBuffer = async (bufferArg: ArrayBuffer | Uint8Array): Promise<string> => {
const hash = await crypto.subtle.digest("SHA-256", bufferArg);
const result = hex(hash);
return result;
if (isCryptoSubtleAvailable()) {
const hash = await crypto.subtle.digest("SHA-256", bufferArg);
const result = hex(hash);
return result;
} else {
// Use fallback for non-HTTPS environments
const uint8Array = bufferArg instanceof Uint8Array ? bufferArg : new Uint8Array(bufferArg);
return sha256Fallback(uint8Array);
}
};
/**