@apify/utilities 2.20.2 → 2.23.0

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/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,31 @@ function createHmacSignature(secretKey, message) {
1870
1870
  return encodeBase62(BigInt(`0x${signature}`));
1871
1871
  }
1872
1872
  __name(createHmacSignature, "createHmacSignature");
1873
+ var webcrypto = globalThis.crypto?.subtle;
1874
+ async function ensureCryptoSubtleExists() {
1875
+ webcrypto ?? (webcrypto = (await import("crypto")).webcrypto.subtle);
1876
+ }
1877
+ __name(ensureCryptoSubtleExists, "ensureCryptoSubtleExists");
1878
+ async function createHmacSignatureAsync(secretKey, message) {
1879
+ await ensureCryptoSubtleExists();
1880
+ const encoder = new TextEncoder();
1881
+ const key = await webcrypto.importKey(
1882
+ "raw",
1883
+ encoder.encode(secretKey),
1884
+ { name: "HMAC", hash: "SHA-256" },
1885
+ false,
1886
+ ["sign"]
1887
+ );
1888
+ const signatureBuffer = await webcrypto.sign(
1889
+ "HMAC",
1890
+ key,
1891
+ encoder.encode(message)
1892
+ );
1893
+ const signatureArray = new Uint8Array(signatureBuffer);
1894
+ const signatureHex = Array.from(signatureArray).map((b) => b.toString(16).padStart(2, "0")).join("").substring(0, 30);
1895
+ return encodeBase62(BigInt(`0x${signatureHex}`));
1896
+ }
1897
+ __name(createHmacSignatureAsync, "createHmacSignatureAsync");
1873
1898
 
1874
1899
  // src/storages.ts
1875
1900
  function createStorageContentSignature({
@@ -1883,6 +1908,26 @@ function createStorageContentSignature({
1883
1908
  return Buffer.from(`${version}.${expiresAt}.${hmac}`).toString("base64url");
1884
1909
  }
1885
1910
  __name(createStorageContentSignature, "createStorageContentSignature");
1911
+ function typedArrayToBase64Url(typedArray) {
1912
+ let binary = "";
1913
+ for (let i = 0; i < typedArray.length; i++) {
1914
+ binary += String.fromCharCode(typedArray[i]);
1915
+ }
1916
+ const base64 = btoa(binary);
1917
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1918
+ }
1919
+ __name(typedArrayToBase64Url, "typedArrayToBase64Url");
1920
+ async function createStorageContentSignatureAsync({
1921
+ resourceId,
1922
+ urlSigningSecretKey,
1923
+ expiresInMillis,
1924
+ version = 0
1925
+ }) {
1926
+ const expiresAt = expiresInMillis ? (/* @__PURE__ */ new Date()).getTime() + expiresInMillis : 0;
1927
+ const hmac = await createHmacSignatureAsync(urlSigningSecretKey, `${version}.${expiresAt}.${resourceId}`);
1928
+ return typedArrayToBase64Url(new TextEncoder().encode(`${version}.${expiresAt}.${hmac}`));
1929
+ }
1930
+ __name(createStorageContentSignatureAsync, "createStorageContentSignatureAsync");
1886
1931
  export {
1887
1932
  CHECK_TYPES,
1888
1933
  CodeHashManager,
@@ -1901,8 +1946,10 @@ export {
1901
1946
  concatStreamToBuffer,
1902
1947
  configureLogger,
1903
1948
  createHmacSignature,
1949
+ createHmacSignatureAsync,
1904
1950
  createInjectableRegExp,
1905
1951
  createStorageContentSignature,
1952
+ createStorageContentSignatureAsync,
1906
1953
  cryptoRandomObjectId,
1907
1954
  dateToString,
1908
1955
  delayPromise,