@apify/utilities 2.20.3 → 2.23.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/cjs/index.d.ts CHANGED
@@ -548,15 +548,29 @@ declare class CodeHashManager {
548
548
  * @param secretKey {string} Secret key used for signing signatures
549
549
  * @param message {string} Message to be signed
550
550
  * @returns string
551
+ * @deprecated Use {@link createHmacSignatureAsync} instead, which uses Web Crypto API and
552
+ * is available in both Node.js and browsers without the need for polyfills.
551
553
  */
552
554
  declare function createHmacSignature(secretKey: string, message: string): string;
555
+ /**
556
+ * Generates an HMAC signature and encodes it using Base62.
557
+ * Base62 encoding reduces the signature length.
558
+ *
559
+ * @param secretKey {string} Secret key used for signing signatures
560
+ * @param message {string} Message to be signed
561
+ * @returns Promise<string>
562
+ */
563
+ declare function createHmacSignatureAsync(secretKey: string, message: string): Promise<string>;
553
564
 
554
565
  /**
555
566
  * Creates a secure signature for a resource like a dataset or key-value store.
556
567
  * This signature is used to generate a signed URL for authenticated access, which can be expiring or permanent.
557
568
  * The signature is created using HMAC with the provided secret key and includes the resource ID, expiration time, and version.
558
569
  *
559
- * Note: expirationMillis is optional. If not provided, the signature will not expire.
570
+ * Note: expiresInMillis is optional. If not provided, the signature will not expire.
571
+ *
572
+ * @deprecated Use {@link createStorageContentSignatureAsync} instead, which uses Web Crypto API and
573
+ * is available in both Node.js and browsers without the need for polyfills.
560
574
  */
561
575
  declare function createStorageContentSignature({ resourceId, urlSigningSecretKey, expiresInMillis, version, }: {
562
576
  resourceId: string;
@@ -564,5 +578,18 @@ declare function createStorageContentSignature({ resourceId, urlSigningSecretKey
564
578
  expiresInMillis?: number;
565
579
  version?: number;
566
580
  }): string;
581
+ /**
582
+ * Creates a secure signature for a resource like a dataset or key-value store.
583
+ * This signature is used to generate a signed URL for authenticated access, which can be expiring or permanent.
584
+ * The signature is created using HMAC with the provided secret key and includes the resource ID, expiration time, and version.
585
+ *
586
+ * Note: expiresInMillis is optional. If not provided, the signature will not expire.
587
+ */
588
+ declare function createStorageContentSignatureAsync({ resourceId, urlSigningSecretKey, expiresInMillis, version, }: {
589
+ resourceId: string;
590
+ urlSigningSecretKey: string;
591
+ expiresInMillis?: number;
592
+ version?: number;
593
+ }): Promise<string>;
567
594
 
568
- export { type BetterIntervalID, CHECK_TYPES, CodeHashManager, CodeHashMetaKey, HealthChecker, InvalidJsonError, InvalidVariableError, JsonVariable, ParseJsonlStream, RetryableError, WebhookPayloadTemplate, betterClearInterval, betterSetInterval, buildOrVersionNumberIntToStr, checkParamPrototypeOrThrow, concatStreamToBuffer, configureLogger, createHmacSignature, createInjectableRegExp, createStorageContentSignature, cryptoRandomObjectId, dateToString, delayPromise, deterministicUniqueId, escapeForBson, escapePropertyName, escapeRegExp, expressErrorHandler, getOrdinalSuffix, getRandomInt, http404Route, isBadForMongo, isBuffer, isForbiddenUsername, isNullOrUndefined, isUrlRelative, jsonStringifyExtended, leftpad, markedDecreaseHeadsLevel, markedSetNofollowLinks, normalizeUrl, parseDateFromJson, parseUrl, privateDecrypt, promisifyServerListen, publicEncrypt, readStreamToString, removeFromArray, retryWithExpBackoff, separateImports, sequentializePromises, splitFullName, timeoutPromise, traverseObject, truncate, unescapeFromBson, unescapePropertyName, weightedAverage };
595
+ export { type BetterIntervalID, CHECK_TYPES, CodeHashManager, CodeHashMetaKey, HealthChecker, InvalidJsonError, InvalidVariableError, JsonVariable, ParseJsonlStream, RetryableError, WebhookPayloadTemplate, betterClearInterval, betterSetInterval, buildOrVersionNumberIntToStr, checkParamPrototypeOrThrow, concatStreamToBuffer, configureLogger, createHmacSignature, createHmacSignatureAsync, createInjectableRegExp, createStorageContentSignature, createStorageContentSignatureAsync, cryptoRandomObjectId, dateToString, delayPromise, deterministicUniqueId, escapeForBson, escapePropertyName, escapeRegExp, expressErrorHandler, getOrdinalSuffix, getRandomInt, http404Route, isBadForMongo, isBuffer, isForbiddenUsername, isNullOrUndefined, isUrlRelative, jsonStringifyExtended, leftpad, markedDecreaseHeadsLevel, markedSetNofollowLinks, normalizeUrl, parseDateFromJson, parseUrl, privateDecrypt, promisifyServerListen, publicEncrypt, readStreamToString, removeFromArray, retryWithExpBackoff, separateImports, sequentializePromises, splitFullName, timeoutPromise, traverseObject, truncate, unescapeFromBson, unescapePropertyName, weightedAverage };
package/esm/index.d.mts CHANGED
@@ -548,15 +548,29 @@ declare class CodeHashManager {
548
548
  * @param secretKey {string} Secret key used for signing signatures
549
549
  * @param message {string} Message to be signed
550
550
  * @returns string
551
+ * @deprecated Use {@link createHmacSignatureAsync} instead, which uses Web Crypto API and
552
+ * is available in both Node.js and browsers without the need for polyfills.
551
553
  */
552
554
  declare function createHmacSignature(secretKey: string, message: string): string;
555
+ /**
556
+ * Generates an HMAC signature and encodes it using Base62.
557
+ * Base62 encoding reduces the signature length.
558
+ *
559
+ * @param secretKey {string} Secret key used for signing signatures
560
+ * @param message {string} Message to be signed
561
+ * @returns Promise<string>
562
+ */
563
+ declare function createHmacSignatureAsync(secretKey: string, message: string): Promise<string>;
553
564
 
554
565
  /**
555
566
  * Creates a secure signature for a resource like a dataset or key-value store.
556
567
  * This signature is used to generate a signed URL for authenticated access, which can be expiring or permanent.
557
568
  * The signature is created using HMAC with the provided secret key and includes the resource ID, expiration time, and version.
558
569
  *
559
- * Note: expirationMillis is optional. If not provided, the signature will not expire.
570
+ * Note: expiresInMillis is optional. If not provided, the signature will not expire.
571
+ *
572
+ * @deprecated Use {@link createStorageContentSignatureAsync} instead, which uses Web Crypto API and
573
+ * is available in both Node.js and browsers without the need for polyfills.
560
574
  */
561
575
  declare function createStorageContentSignature({ resourceId, urlSigningSecretKey, expiresInMillis, version, }: {
562
576
  resourceId: string;
@@ -564,5 +578,18 @@ declare function createStorageContentSignature({ resourceId, urlSigningSecretKey
564
578
  expiresInMillis?: number;
565
579
  version?: number;
566
580
  }): string;
581
+ /**
582
+ * Creates a secure signature for a resource like a dataset or key-value store.
583
+ * This signature is used to generate a signed URL for authenticated access, which can be expiring or permanent.
584
+ * The signature is created using HMAC with the provided secret key and includes the resource ID, expiration time, and version.
585
+ *
586
+ * Note: expiresInMillis is optional. If not provided, the signature will not expire.
587
+ */
588
+ declare function createStorageContentSignatureAsync({ resourceId, urlSigningSecretKey, expiresInMillis, version, }: {
589
+ resourceId: string;
590
+ urlSigningSecretKey: string;
591
+ expiresInMillis?: number;
592
+ version?: number;
593
+ }): Promise<string>;
567
594
 
568
- export { type BetterIntervalID, CHECK_TYPES, CodeHashManager, CodeHashMetaKey, HealthChecker, InvalidJsonError, InvalidVariableError, JsonVariable, ParseJsonlStream, RetryableError, WebhookPayloadTemplate, betterClearInterval, betterSetInterval, buildOrVersionNumberIntToStr, checkParamPrototypeOrThrow, concatStreamToBuffer, configureLogger, createHmacSignature, createInjectableRegExp, createStorageContentSignature, cryptoRandomObjectId, dateToString, delayPromise, deterministicUniqueId, escapeForBson, escapePropertyName, escapeRegExp, expressErrorHandler, getOrdinalSuffix, getRandomInt, http404Route, isBadForMongo, isBuffer, isForbiddenUsername, isNullOrUndefined, isUrlRelative, jsonStringifyExtended, leftpad, markedDecreaseHeadsLevel, markedSetNofollowLinks, normalizeUrl, parseDateFromJson, parseUrl, privateDecrypt, promisifyServerListen, publicEncrypt, readStreamToString, removeFromArray, retryWithExpBackoff, separateImports, sequentializePromises, splitFullName, timeoutPromise, traverseObject, truncate, unescapeFromBson, unescapePropertyName, weightedAverage };
595
+ export { type BetterIntervalID, CHECK_TYPES, CodeHashManager, CodeHashMetaKey, HealthChecker, InvalidJsonError, InvalidVariableError, JsonVariable, ParseJsonlStream, RetryableError, WebhookPayloadTemplate, betterClearInterval, betterSetInterval, buildOrVersionNumberIntToStr, checkParamPrototypeOrThrow, concatStreamToBuffer, configureLogger, createHmacSignature, createHmacSignatureAsync, createInjectableRegExp, createStorageContentSignature, createStorageContentSignatureAsync, cryptoRandomObjectId, dateToString, delayPromise, deterministicUniqueId, escapeForBson, escapePropertyName, escapeRegExp, expressErrorHandler, getOrdinalSuffix, getRandomInt, http404Route, isBadForMongo, isBuffer, isForbiddenUsername, isNullOrUndefined, isUrlRelative, jsonStringifyExtended, leftpad, markedDecreaseHeadsLevel, markedSetNofollowLinks, normalizeUrl, parseDateFromJson, parseUrl, privateDecrypt, promisifyServerListen, publicEncrypt, readStreamToString, removeFromArray, retryWithExpBackoff, separateImports, sequentializePromises, splitFullName, timeoutPromise, traverseObject, truncate, unescapeFromBson, unescapePropertyName, weightedAverage };
package/esm/index.mjs CHANGED
@@ -1870,6 +1870,42 @@ function createHmacSignature(secretKey, message) {
1870
1870
  return encodeBase62(BigInt(`0x${signature}`));
1871
1871
  }
1872
1872
  __name(createHmacSignature, "createHmacSignature");
1873
+ var subtleCrypto = globalThis.crypto?.subtle;
1874
+ async function ensureSubtleCryptoExists() {
1875
+ if (!subtleCrypto) {
1876
+ if (globalThis.require) {
1877
+ subtleCrypto = globalThis.require("node:crypto")?.webcrypto?.subtle;
1878
+ } else {
1879
+ subtleCrypto = (await import("crypto"))?.webcrypto?.subtle;
1880
+ }
1881
+ if (!subtleCrypto) {
1882
+ throw new Error(`SubtleCrypto is not available in this environment.
1883
+ Please ensure you're running in an environment that supports Web Crypto API,
1884
+ or submit an issue to https://github.com/apify/apify-shared-js so we can help you further.`);
1885
+ }
1886
+ }
1887
+ }
1888
+ __name(ensureSubtleCryptoExists, "ensureSubtleCryptoExists");
1889
+ async function createHmacSignatureAsync(secretKey, message) {
1890
+ await ensureSubtleCryptoExists();
1891
+ const encoder = new TextEncoder();
1892
+ const key = await subtleCrypto.importKey(
1893
+ "raw",
1894
+ encoder.encode(secretKey),
1895
+ { name: "HMAC", hash: "SHA-256" },
1896
+ false,
1897
+ ["sign"]
1898
+ );
1899
+ const signatureBuffer = await subtleCrypto.sign(
1900
+ "HMAC",
1901
+ key,
1902
+ encoder.encode(message)
1903
+ );
1904
+ const signatureArray = new Uint8Array(signatureBuffer);
1905
+ const signatureHex = Array.from(signatureArray).map((b) => b.toString(16).padStart(2, "0")).join("").substring(0, 30);
1906
+ return encodeBase62(BigInt(`0x${signatureHex}`));
1907
+ }
1908
+ __name(createHmacSignatureAsync, "createHmacSignatureAsync");
1873
1909
 
1874
1910
  // src/storages.ts
1875
1911
  function createStorageContentSignature({
@@ -1883,6 +1919,26 @@ function createStorageContentSignature({
1883
1919
  return Buffer.from(`${version}.${expiresAt}.${hmac}`).toString("base64url");
1884
1920
  }
1885
1921
  __name(createStorageContentSignature, "createStorageContentSignature");
1922
+ function typedArrayToBase64Url(typedArray) {
1923
+ let binary = "";
1924
+ for (let i = 0; i < typedArray.length; i++) {
1925
+ binary += String.fromCharCode(typedArray[i]);
1926
+ }
1927
+ const base64 = btoa(binary);
1928
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1929
+ }
1930
+ __name(typedArrayToBase64Url, "typedArrayToBase64Url");
1931
+ async function createStorageContentSignatureAsync({
1932
+ resourceId,
1933
+ urlSigningSecretKey,
1934
+ expiresInMillis,
1935
+ version = 0
1936
+ }) {
1937
+ const expiresAt = expiresInMillis ? (/* @__PURE__ */ new Date()).getTime() + expiresInMillis : 0;
1938
+ const hmac = await createHmacSignatureAsync(urlSigningSecretKey, `${version}.${expiresAt}.${resourceId}`);
1939
+ return typedArrayToBase64Url(new TextEncoder().encode(`${version}.${expiresAt}.${hmac}`));
1940
+ }
1941
+ __name(createStorageContentSignatureAsync, "createStorageContentSignatureAsync");
1886
1942
  export {
1887
1943
  CHECK_TYPES,
1888
1944
  CodeHashManager,
@@ -1901,8 +1957,10 @@ export {
1901
1957
  concatStreamToBuffer,
1902
1958
  configureLogger,
1903
1959
  createHmacSignature,
1960
+ createHmacSignatureAsync,
1904
1961
  createInjectableRegExp,
1905
1962
  createStorageContentSignature,
1963
+ createStorageContentSignatureAsync,
1906
1964
  cryptoRandomObjectId,
1907
1965
  dateToString,
1908
1966
  delayPromise,