@apify/utilities 2.35.11 → 3.0.0-beta.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/code_hash_manager.d.ts +34 -0
- package/code_hash_manager.js +66 -0
- package/code_hash_manager.js.map +1 -0
- package/crypto.d.ts +35 -0
- package/crypto.js +58 -0
- package/crypto.js.map +1 -0
- package/exponential_backoff.d.ts +9 -0
- package/exponential_backoff.js +47 -0
- package/exponential_backoff.js.map +1 -0
- package/health_checker.d.ts +61 -0
- package/health_checker.js +132 -0
- package/health_checker.js.map +1 -0
- package/hmac.d.ts +20 -0
- package/hmac.js +59 -0
- package/hmac.js.map +1 -0
- package/index.d.ts +14 -0
- package/index.js +15 -0
- package/index.js.map +1 -0
- package/package.json +16 -21
- package/parse_boolean.d.ts +10 -0
- package/parse_boolean.js +25 -0
- package/parse_boolean.js.map +1 -0
- package/parse_jsonl_stream.d.ts +25 -0
- package/parse_jsonl_stream.js +79 -0
- package/parse_jsonl_stream.js.map +1 -0
- package/storages.d.ts +29 -0
- package/storages.js +37 -0
- package/storages.js.map +1 -0
- package/streams_utilities.d.ts +10 -0
- package/streams_utilities.js +26 -0
- package/streams_utilities.js.map +1 -0
- package/url_params_utils.d.ts +7 -0
- package/url_params_utils.js +11 -0
- package/url_params_utils.js.map +1 -0
- package/usernames.d.ts +10 -0
- package/usernames.js +1137 -0
- package/usernames.js.map +1 -0
- package/utilities.client.d.ts +125 -0
- package/utilities.client.js +408 -0
- package/utilities.client.js.map +1 -0
- package/utilities.d.ts +111 -0
- package/utilities.js +263 -0
- package/utilities.js.map +1 -0
- package/webhook_payload_template.d.ts +114 -0
- package/webhook_payload_template.js +245 -0
- package/webhook_payload_template.js.map +1 -0
- package/cjs/index.cjs +0 -2402
- package/cjs/index.cjs.map +0 -1
- package/cjs/index.d.ts +0 -609
- package/esm/index.d.mts +0 -609
- package/esm/index.mjs +0 -2314
- package/esm/index.mjs.map +0 -1
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export declare enum CodeHashMetaKey {
|
|
2
|
+
VERSION = "v",
|
|
3
|
+
USER = "u"
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Allows hashing of an Actor input together with some metadata into a shareable link for the "Run on Apify" button.
|
|
7
|
+
* Uses a common secret for checking the signatures.
|
|
8
|
+
*
|
|
9
|
+
* The hash consists of 3 parts separated by a dot, as in `ABC.DEF.GHI`, each being a base64url encoded string:
|
|
10
|
+
* - `meta` object with the `version` and `user` properties.
|
|
11
|
+
* - `data` data object (the one that gets encoded)
|
|
12
|
+
* - `signature` used for verification of the URL hash, computed from the `meta` and `data` objects
|
|
13
|
+
*/
|
|
14
|
+
export declare class CodeHashManager {
|
|
15
|
+
private readonly secret;
|
|
16
|
+
static readonly SECTION_SEPARATOR = ".";
|
|
17
|
+
static readonly VERSION = 1;
|
|
18
|
+
constructor(secret: string);
|
|
19
|
+
/**
|
|
20
|
+
* Encodes object (e.g. input for actor) to a string hash and uses the `secret` to sign the hash.
|
|
21
|
+
*/
|
|
22
|
+
encode<T extends object>(data: T, userId: string): string;
|
|
23
|
+
decode(urlHash: string): {
|
|
24
|
+
data: any;
|
|
25
|
+
meta: {
|
|
26
|
+
userId: any;
|
|
27
|
+
version: any;
|
|
28
|
+
isSignatureValid: boolean;
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
private toBase64;
|
|
32
|
+
private fromBase64;
|
|
33
|
+
private generateSignature;
|
|
34
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
export var CodeHashMetaKey;
|
|
3
|
+
(function (CodeHashMetaKey) {
|
|
4
|
+
CodeHashMetaKey["VERSION"] = "v";
|
|
5
|
+
CodeHashMetaKey["USER"] = "u";
|
|
6
|
+
})(CodeHashMetaKey || (CodeHashMetaKey = {}));
|
|
7
|
+
/**
|
|
8
|
+
* Allows hashing of an Actor input together with some metadata into a shareable link for the "Run on Apify" button.
|
|
9
|
+
* Uses a common secret for checking the signatures.
|
|
10
|
+
*
|
|
11
|
+
* The hash consists of 3 parts separated by a dot, as in `ABC.DEF.GHI`, each being a base64url encoded string:
|
|
12
|
+
* - `meta` object with the `version` and `user` properties.
|
|
13
|
+
* - `data` data object (the one that gets encoded)
|
|
14
|
+
* - `signature` used for verification of the URL hash, computed from the `meta` and `data` objects
|
|
15
|
+
*/
|
|
16
|
+
export class CodeHashManager {
|
|
17
|
+
secret;
|
|
18
|
+
static SECTION_SEPARATOR = '.';
|
|
19
|
+
static VERSION = 1;
|
|
20
|
+
constructor(secret) {
|
|
21
|
+
this.secret = secret;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Encodes object (e.g. input for actor) to a string hash and uses the `secret` to sign the hash.
|
|
25
|
+
*/
|
|
26
|
+
encode(data, userId) {
|
|
27
|
+
const meta = {
|
|
28
|
+
[CodeHashMetaKey.USER]: userId,
|
|
29
|
+
[CodeHashMetaKey.VERSION]: CodeHashManager.VERSION,
|
|
30
|
+
};
|
|
31
|
+
const metaBase64 = this.toBase64(JSON.stringify(meta));
|
|
32
|
+
const inputBase64 = this.toBase64(JSON.stringify(data));
|
|
33
|
+
const dataToSign = [metaBase64, inputBase64].join(CodeHashManager.SECTION_SEPARATOR);
|
|
34
|
+
const signature = this.generateSignature(dataToSign);
|
|
35
|
+
const signatureBase64 = this.toBase64(signature);
|
|
36
|
+
const parts = [metaBase64, inputBase64, signatureBase64];
|
|
37
|
+
return parts.join(CodeHashManager.SECTION_SEPARATOR);
|
|
38
|
+
}
|
|
39
|
+
decode(urlHash) {
|
|
40
|
+
const parts = urlHash.split(CodeHashManager.SECTION_SEPARATOR);
|
|
41
|
+
const dataToSign = parts.slice(0, 2).join(CodeHashManager.SECTION_SEPARATOR);
|
|
42
|
+
const meta = JSON.parse(this.fromBase64(parts[0]).toString());
|
|
43
|
+
const data = JSON.parse(this.fromBase64(parts[1]).toString());
|
|
44
|
+
const signature = this.fromBase64(parts[2]);
|
|
45
|
+
const expectedSignature = this.generateSignature(dataToSign);
|
|
46
|
+
const isSignatureValid = timingSafeEqual(signature, expectedSignature);
|
|
47
|
+
return {
|
|
48
|
+
data,
|
|
49
|
+
meta: {
|
|
50
|
+
userId: meta[CodeHashMetaKey.USER],
|
|
51
|
+
version: meta[CodeHashMetaKey.VERSION],
|
|
52
|
+
isSignatureValid,
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
toBase64(data) {
|
|
57
|
+
return Buffer.from(data).toString('base64url');
|
|
58
|
+
}
|
|
59
|
+
fromBase64(encoded) {
|
|
60
|
+
return Buffer.from(encoded, 'base64url');
|
|
61
|
+
}
|
|
62
|
+
generateSignature(data) {
|
|
63
|
+
return createHmac('sha256', this.secret).update(data).digest();
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
//# sourceMappingURL=code_hash_manager.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"code_hash_manager.js","sourceRoot":"","sources":["../src/code_hash_manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAE1D,MAAM,CAAN,IAAY,eAGX;AAHD,WAAY,eAAe;IACvB,gCAAa,CAAA;IACb,6BAAU,CAAA;AACd,CAAC,EAHW,eAAe,KAAf,eAAe,QAG1B;AAED;;;;;;;;GAQG;AACH,MAAM,OAAO,eAAe;IAIK;IAH7B,MAAM,CAAU,iBAAiB,GAAG,GAAG,CAAC;IACxC,MAAM,CAAU,OAAO,GAAG,CAAC,CAAC;IAE5B,YAA6B,MAAc;QAAd,WAAM,GAAN,MAAM,CAAQ;IAAG,CAAC;IAE/C;;OAEG;IACH,MAAM,CAAmB,IAAO,EAAE,MAAc;QAC5C,MAAM,IAAI,GAAG;YACT,CAAC,eAAe,CAAC,IAAI,CAAC,EAAE,MAAM;YAC9B,CAAC,eAAe,CAAC,OAAO,CAA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AAG,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,CAAC;QAC7D,MAAM,gBAAgB,GAAG,eAAe,CAAC,SAAS,EAAE,iBAAiB,CAAC,CAAC;QAEvE,OAAO;YACH,IAAI;YACJ,IAAI,EAAE;gBACF,MAAM,EAAE,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC;gBAClC,OAAO,EAAE,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC;gBACtC,gBAAgB;aACnB;SACJ,CAAC;IACN,CAAC;IAEO,QAAQ,CAAC,IAAqB;QAClC,OAAO,MAAM,CAAC,IAAI,CAAC,IAAc,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;IAC7D,CAAC;IAEO,UAAU,CAAC,OAAe;QAC9B,OAAO,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;IAC7C,CAAC;IAEO,iBAAiB,CAAC,IAAY;QAClC,OAAO,UAAU,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,CAAC;IACnE,CAAC","sourcesContent":["import { createHmac, timingSafeEqual } from 'node:crypto';\n\nexport enum CodeHashMetaKey {\n VERSION = 'v',\n USER = 'u',\n}\n\n/**\n * Allows hashing of an Actor input together with some metadata into a shareable link for the \"Run on Apify\" button.\n * Uses a common secret for checking the signatures.\n *\n * The hash consists of 3 parts separated by a dot, as in `ABC.DEF.GHI`, each being a base64url encoded string:\n * - `meta` object with the `version` and `user` properties.\n * - `data` data object (the one that gets encoded)\n * - `signature` used for verification of the URL hash, computed from the `meta` and `data` objects\n */\nexport class CodeHashManager {\n static readonly SECTION_SEPARATOR = '.';\n static readonly VERSION = 1;\n\n constructor(private readonly secret: string) {}\n\n /**\n * Encodes object (e.g. input for actor) to a string hash and uses the `secret` to sign the hash.\n */\n encode<T extends object>(data: T, userId: string) {\n const meta = {\n [CodeHashMetaKey.USER]: userId,\n [CodeHashMetaKey.VERSION]: CodeHashManager.VERSION,\n };\n const metaBase64 = this.toBase64(JSON.stringify(meta));\n const inputBase64 = this.toBase64(JSON.stringify(data));\n const dataToSign = [metaBase64, inputBase64].join(CodeHashManager.SECTION_SEPARATOR);\n const signature = this.generateSignature(dataToSign);\n const signatureBase64 = this.toBase64(signature);\n const parts = [metaBase64, inputBase64, signatureBase64];\n\n return parts.join(CodeHashManager.SECTION_SEPARATOR);\n }\n\n decode(urlHash: string) {\n const parts = urlHash.split(CodeHashManager.SECTION_SEPARATOR);\n const dataToSign = parts.slice(0, 2).join(CodeHashManager.SECTION_SEPARATOR);\n const meta = JSON.parse(this.fromBase64(parts[0]).toString());\n const data = JSON.parse(this.fromBase64(parts[1]).toString());\n const signature = this.fromBase64(parts[2]);\n const expectedSignature = this.generateSignature(dataToSign);\n const isSignatureValid = timingSafeEqual(signature, expectedSignature);\n\n return {\n data,\n meta: {\n userId: meta[CodeHashMetaKey.USER],\n version: meta[CodeHashMetaKey.VERSION],\n isSignatureValid,\n },\n };\n }\n\n private toBase64(data: string | Buffer) {\n return Buffer.from(data as Buffer).toString('base64url');\n }\n\n private fromBase64(encoded: string) {\n return Buffer.from(encoded, 'base64url');\n }\n\n private generateSignature(data: string) {\n return createHmac('sha256', this.secret).update(data).digest();\n }\n}\n"]}
|
package/crypto.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { KeyObject } from 'node:crypto';
|
|
2
|
+
type DecryptOptions = {
|
|
3
|
+
privateKey: KeyObject;
|
|
4
|
+
encryptedPassword: string;
|
|
5
|
+
encryptedValue: string;
|
|
6
|
+
};
|
|
7
|
+
type EncryptOptions = {
|
|
8
|
+
publicKey: KeyObject;
|
|
9
|
+
value: string;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* It encrypts the given value using AES cipher and the password for encryption using the public key.
|
|
13
|
+
* NOTE: The encryption password is a string of encryption key and initial vector used for cipher.
|
|
14
|
+
* It returns the encrypted password and encrypted value in BASE64 format.
|
|
15
|
+
*
|
|
16
|
+
* @param publicKey {KeyObject} Public key used for encryption
|
|
17
|
+
* @param value {string} Value to be encrypted
|
|
18
|
+
* @returns {Object<encryptedPassword, encryptedValue>}
|
|
19
|
+
*/
|
|
20
|
+
export declare function publicEncrypt({ publicKey, value }: EncryptOptions): {
|
|
21
|
+
encryptedPassword: string;
|
|
22
|
+
encryptedValue: string;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* It decrypts encrypted password using private key
|
|
26
|
+
* and uses the password(consists of encrypted key and initial vector)
|
|
27
|
+
* to decrypt the encrypted value.
|
|
28
|
+
*
|
|
29
|
+
* @param privateKey {KeyObject} Private key used for decryption
|
|
30
|
+
* @param encryptedPassword {string} Password in Base64 encrypted using private key
|
|
31
|
+
* @param encryptedValue {string} Content in Base64 encrypted using AES cipher
|
|
32
|
+
* @returns {string}
|
|
33
|
+
*/
|
|
34
|
+
export declare function privateDecrypt({ privateKey, encryptedPassword, encryptedValue }: DecryptOptions): string;
|
|
35
|
+
export {};
|
package/crypto.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import { cryptoRandomObjectId } from './utilities.js';
|
|
3
|
+
const ENCRYPTION_ALGORITHM = 'aes-256-gcm';
|
|
4
|
+
const ENCRYPTION_KEY_LENGTH = 32;
|
|
5
|
+
const ENCRYPTION_IV_LENGTH = 16;
|
|
6
|
+
const ENCRYPTION_AUTH_TAG_LENGTH = 16;
|
|
7
|
+
/**
|
|
8
|
+
* It encrypts the given value using AES cipher and the password for encryption using the public key.
|
|
9
|
+
* NOTE: The encryption password is a string of encryption key and initial vector used for cipher.
|
|
10
|
+
* It returns the encrypted password and encrypted value in BASE64 format.
|
|
11
|
+
*
|
|
12
|
+
* @param publicKey {KeyObject} Public key used for encryption
|
|
13
|
+
* @param value {string} Value to be encrypted
|
|
14
|
+
* @returns {Object<encryptedPassword, encryptedValue>}
|
|
15
|
+
*/
|
|
16
|
+
export function publicEncrypt({ publicKey, value }) {
|
|
17
|
+
const key = cryptoRandomObjectId(ENCRYPTION_KEY_LENGTH);
|
|
18
|
+
const initVector = cryptoRandomObjectId(ENCRYPTION_IV_LENGTH);
|
|
19
|
+
const cipher = crypto.createCipheriv(ENCRYPTION_ALGORITHM, key, initVector);
|
|
20
|
+
const bufferFromValue = Buffer.from(value, 'utf-8');
|
|
21
|
+
const bufferFromKey = Buffer.from(key, 'utf-8');
|
|
22
|
+
const bufferFromInitVector = Buffer.from(initVector, 'utf-8');
|
|
23
|
+
const passwordBuffer = Buffer.concat([bufferFromKey, bufferFromInitVector]);
|
|
24
|
+
// NOTE: Auth Tag is appended to the end of the encrypted data, it has length of 16 bytes and ensures integrity of the data.
|
|
25
|
+
const encryptedValue = Buffer.concat([cipher.update(bufferFromValue), cipher.final(), cipher.getAuthTag()]);
|
|
26
|
+
const encryptedPassword = crypto.publicEncrypt(publicKey, passwordBuffer);
|
|
27
|
+
return {
|
|
28
|
+
encryptedPassword: encryptedPassword.toString('base64'),
|
|
29
|
+
encryptedValue: encryptedValue.toString('base64'),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* It decrypts encrypted password using private key
|
|
34
|
+
* and uses the password(consists of encrypted key and initial vector)
|
|
35
|
+
* to decrypt the encrypted value.
|
|
36
|
+
*
|
|
37
|
+
* @param privateKey {KeyObject} Private key used for decryption
|
|
38
|
+
* @param encryptedPassword {string} Password in Base64 encrypted using private key
|
|
39
|
+
* @param encryptedValue {string} Content in Base64 encrypted using AES cipher
|
|
40
|
+
* @returns {string}
|
|
41
|
+
*/
|
|
42
|
+
export function privateDecrypt({ privateKey, encryptedPassword, encryptedValue }) {
|
|
43
|
+
const encryptedValueBuffer = Buffer.from(encryptedValue, 'base64');
|
|
44
|
+
const encryptedPasswordBuffer = Buffer.from(encryptedPassword, 'base64');
|
|
45
|
+
const passwordBuffer = crypto.privateDecrypt(privateKey, encryptedPasswordBuffer);
|
|
46
|
+
if (passwordBuffer.length !== ENCRYPTION_KEY_LENGTH + ENCRYPTION_IV_LENGTH) {
|
|
47
|
+
throw new Error('privateDecrypt: Decryption failed, invalid password length!');
|
|
48
|
+
}
|
|
49
|
+
// Slice Auth tag from the final value cipher
|
|
50
|
+
const authTagBuffer = encryptedValueBuffer.slice(encryptedValueBuffer.length - ENCRYPTION_AUTH_TAG_LENGTH);
|
|
51
|
+
const encryptedDataBuffer = encryptedValueBuffer.slice(0, encryptedValueBuffer.length - ENCRYPTION_AUTH_TAG_LENGTH);
|
|
52
|
+
const encryptionKeyBuffer = passwordBuffer.slice(0, ENCRYPTION_KEY_LENGTH);
|
|
53
|
+
const initVectorBuffer = passwordBuffer.slice(ENCRYPTION_KEY_LENGTH);
|
|
54
|
+
const decipher = crypto.createDecipheriv(ENCRYPTION_ALGORITHM, encryptionKeyBuffer, initVectorBuffer);
|
|
55
|
+
decipher.setAuthTag(authTagBuffer);
|
|
56
|
+
return Buffer.concat([decipher.update(encryptedDataBuffer), decipher.final()]).toString('utf-8');
|
|
57
|
+
}
|
|
58
|
+
//# sourceMappingURL=crypto.js.map
|
package/crypto.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"crypto.js","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AACA,OAAO,MAAM,MAAM,aAAa,CAAC;AAEjC,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAEtD,MAAM,oBAAoB,GAAG,aAAa,CAAC;AAC3C,MAAM,qBAAqB,GAAG,EAAE,CAAC;AACjC,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAChC,MAAM,0BAA0B,GAAG,EAAE,CAAC;AAatC;;;;;;;;GAQG;AACH,MAAM,UAAU,aAAa,CAAC,EAAE,SAAS,EAAE,KAAK,EAAkB;IAC9D,MAAM,GAAG,GAAG,oBAAoB,CAAC,qBAAqB,CAAC,CAAC;IACxD,MAAM,UAAU,GAAG,oB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,cAAc,CAAC,MAAM,KAAK,qBAAqB,GAAG,oBAAoB,EAAE,CAAC;QACzE,MAAM,IAAI,KAAK,CAAC,6DAA6D,CAAC,CAAC;IACnF,CAAC;IAED,6CAA6C;IAC7C,MAAM,aAAa,GAAG,oBAAoB,CAAC,KAAK,CAAC,oBAAoB,CAAC,MAAM,GAAG,0BAA0B,CAAC,CAAC;IAC3G,MAAM,mBAAmB,GAAG,oBAAoB,CAAC,KAAK,CAAC,CAAC,EAAE,oBAAoB,CAAC,MAAM,GAAG,0BAA0B,CAAC,CAAC;IAEpH,MAAM,mBAAmB,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC,EAAE,qBAAqB,CAAC,CAAC;IAC3E,MAAM,gBAAgB,GAAG,cAAc,CAAC,KAAK,CAAC,qBAAqB,CAAC,CAAC;IACrE,MAAM,QAAQ,GAAG,MAAM,CAAC,gBAAgB,CAAC,oBAAoB,EAAE,mBAAmB,EAAE,gBAAgB,CAAC,CAAC;IACtG,QAAQ,CAAC,UAAU,CAAC,aAAa,CAAC,CAAC;IAEnC,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,mBAAmB,CAAC,EAAE,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AACrG,CAAC","sourcesContent":["import type { KeyObject } from 'node:crypto';\nimport crypto from 'node:crypto';\n\nimport { cryptoRandomObjectId } from './utilities.js';\n\nconst ENCRYPTION_ALGORITHM = 'aes-256-gcm';\nconst ENCRYPTION_KEY_LENGTH = 32;\nconst ENCRYPTION_IV_LENGTH = 16;\nconst ENCRYPTION_AUTH_TAG_LENGTH = 16;\n\ntype DecryptOptions = {\n privateKey: KeyObject;\n encryptedPassword: string;\n encryptedValue: string;\n};\n\ntype EncryptOptions = {\n publicKey: KeyObject;\n value: string;\n};\n\n/**\n * It encrypts the given value using AES cipher and the password for encryption using the public key.\n * NOTE: The encryption password is a string of encryption key and initial vector used for cipher.\n * It returns the encrypted password and encrypted value in BASE64 format.\n *\n * @param publicKey {KeyObject} Public key used for encryption\n * @param value {string} Value to be encrypted\n * @returns {Object<encryptedPassword, encryptedValue>}\n */\nexport function publicEncrypt({ publicKey, value }: EncryptOptions) {\n const key = cryptoRandomObjectId(ENCRYPTION_KEY_LENGTH);\n const initVector = cryptoRandomObjectId(ENCRYPTION_IV_LENGTH);\n const cipher = crypto.createCipheriv(ENCRYPTION_ALGORITHM, key, initVector);\n\n const bufferFromValue = Buffer.from(value, 'utf-8');\n const bufferFromKey = Buffer.from(key, 'utf-8');\n const bufferFromInitVector = Buffer.from(initVector, 'utf-8');\n const passwordBuffer = Buffer.concat([bufferFromKey, bufferFromInitVector]);\n\n // NOTE: Auth Tag is appended to the end of the encrypted data, it has length of 16 bytes and ensures integrity of the data.\n const encryptedValue = Buffer.concat([cipher.update(bufferFromValue), cipher.final(), cipher.getAuthTag()]);\n const encryptedPassword = crypto.publicEncrypt(publicKey, passwordBuffer);\n\n return {\n encryptedPassword: encryptedPassword.toString('base64'),\n encryptedValue: encryptedValue.toString('base64'),\n };\n}\n\n/**\n * It decrypts encrypted password using private key\n * and uses the password(consists of encrypted key and initial vector)\n * to decrypt the encrypted value.\n *\n * @param privateKey {KeyObject} Private key used for decryption\n * @param encryptedPassword {string} Password in Base64 encrypted using private key\n * @param encryptedValue {string} Content in Base64 encrypted using AES cipher\n * @returns {string}\n */\nexport function privateDecrypt({ privateKey, encryptedPassword, encryptedValue }: DecryptOptions): string {\n const encryptedValueBuffer = Buffer.from(encryptedValue, 'base64');\n const encryptedPasswordBuffer = Buffer.from(encryptedPassword, 'base64');\n\n const passwordBuffer = crypto.privateDecrypt(privateKey, encryptedPasswordBuffer);\n if (passwordBuffer.length !== ENCRYPTION_KEY_LENGTH + ENCRYPTION_IV_LENGTH) {\n throw new Error('privateDecrypt: Decryption failed, invalid password length!');\n }\n\n // Slice Auth tag from the final value cipher\n const authTagBuffer = encryptedValueBuffer.slice(encryptedValueBuffer.length - ENCRYPTION_AUTH_TAG_LENGTH);\n const encryptedDataBuffer = encryptedValueBuffer.slice(0, encryptedValueBuffer.length - ENCRYPTION_AUTH_TAG_LENGTH);\n\n const encryptionKeyBuffer = passwordBuffer.slice(0, ENCRYPTION_KEY_LENGTH);\n const initVectorBuffer = passwordBuffer.slice(ENCRYPTION_KEY_LENGTH);\n const decipher = crypto.createDecipheriv(ENCRYPTION_ALGORITHM, encryptionKeyBuffer, initVectorBuffer);\n decipher.setAuthTag(authTagBuffer);\n\n return Buffer.concat([decipher.update(encryptedDataBuffer), decipher.final()]).toString('utf-8');\n}\n"]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export declare class RetryableError extends Error {
|
|
2
|
+
readonly error: Error;
|
|
3
|
+
constructor(error: Error, ...args: unknown[]);
|
|
4
|
+
}
|
|
5
|
+
export declare function retryWithExpBackoff<T>(params: {
|
|
6
|
+
func: (...args: unknown[]) => T | Promise<T>;
|
|
7
|
+
expBackoffMillis: number;
|
|
8
|
+
expBackoffMaxRepeats: number;
|
|
9
|
+
}): Promise<T>;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import log from '@apify/log';
|
|
2
|
+
import { delayPromise } from './utilities.js';
|
|
3
|
+
export class RetryableError extends Error {
|
|
4
|
+
error;
|
|
5
|
+
constructor(error, ...args) {
|
|
6
|
+
super(...args);
|
|
7
|
+
this.error = error;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export async function retryWithExpBackoff(params) {
|
|
11
|
+
const { func, expBackoffMillis, expBackoffMaxRepeats } = params;
|
|
12
|
+
if (typeof func !== 'function') {
|
|
13
|
+
throw new Error('Parameter "func" should be a function.');
|
|
14
|
+
}
|
|
15
|
+
if (typeof expBackoffMillis !== 'number') {
|
|
16
|
+
throw new Error('Parameter "expBackoffMillis" should be a number.');
|
|
17
|
+
}
|
|
18
|
+
if (typeof expBackoffMaxRepeats !== 'number') {
|
|
19
|
+
throw new Error('Parameter "expBackoffMaxRepeats" should be a number.');
|
|
20
|
+
}
|
|
21
|
+
for (let i = 0;; i++) {
|
|
22
|
+
let error;
|
|
23
|
+
try {
|
|
24
|
+
return await func();
|
|
25
|
+
}
|
|
26
|
+
catch (e) {
|
|
27
|
+
error = e;
|
|
28
|
+
}
|
|
29
|
+
if (!(error instanceof RetryableError)) {
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
if (i >= expBackoffMaxRepeats - 1) {
|
|
33
|
+
throw error.error;
|
|
34
|
+
}
|
|
35
|
+
const waitMillis = expBackoffMillis * 2 ** i;
|
|
36
|
+
const rand = (from, to) => from + Math.floor(Math.random() * (to - from + 1));
|
|
37
|
+
const randomizedWaitMillis = rand(waitMillis, waitMillis * 2);
|
|
38
|
+
if (i === Math.round(expBackoffMaxRepeats / 2)) {
|
|
39
|
+
log.warning(`Retry failed ${i} times and will be repeated in ${randomizedWaitMillis}ms`, {
|
|
40
|
+
originalError: error.error.message,
|
|
41
|
+
errorDetails: Reflect.get(error.error, 'details'),
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
await delayPromise(randomizedWaitMillis);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=exponential_backoff.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"exponential_backoff.js","sourceRoot":"","sources":["../src/exponential_backoff.ts"],"names":[],"mappings":"AAAA,OAAO,GAAG,MAAM,YAAY,CAAC;AAE7B,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C,MAAM,OAAO,cAAe,SAAQ,KAAK;IAC5B,KAAK,CAAQ;IAEtB,YAAY,KAAY,EAAE,GAAG,IAAe;QACxC,KAAK,CAAC,GAAI,IAAiB,CAAC,CAAC;QAC7B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACvB,CAAC;CACJ;AAED,MAAM,CAAC,KAAK,UAAU,mBAAmB,CAAI,MAI5C;IACG,MAAM,E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AC,EAAE,CAAC;YAC7C,GAAG,CAAC,OAAO,CAAC,gBAAgB,CAAC,kCAAkC,oBAAoB,IAAI,EAAE;gBACrF,aAAa,EAAE,KAAK,CAAC,KAAK,CAAC,OAAO;gBAClC,YAAY,EAAE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,SAAS,CAAC;aACpD,CAAC,CAAC;QACP,CAAC;QAED,MAAM,YAAY,CAAC,oBAAoB,CAAC,CAAC;IAC7C,CAAC;AACL,CAAC","sourcesContent":["import log from '@apify/log';\n\nimport { delayPromise } from './utilities.js';\n\nexport class RetryableError extends Error {\n readonly error: Error;\n\n constructor(error: Error, ...args: unknown[]) {\n super(...(args as [string]));\n this.error = error;\n }\n}\n\nexport async function retryWithExpBackoff<T>(params: {\n func: (...args: unknown[]) => T | Promise<T>;\n expBackoffMillis: number;\n expBackoffMaxRepeats: number;\n}): Promise<T> {\n const { func, expBackoffMillis, expBackoffMaxRepeats } = params;\n\n if (typeof func !== 'function') {\n throw new Error('Parameter \"func\" should be a function.');\n }\n\n if (typeof expBackoffMillis !== 'number') {\n throw new Error('Parameter \"expBackoffMillis\" should be a number.');\n }\n\n if (typeof expBackoffMaxRepeats !== 'number') {\n throw new Error('Parameter \"expBackoffMaxRepeats\" should be a number.');\n }\n\n for (let i = 0; ; i++) {\n let error;\n\n try {\n return await func();\n } catch (e) {\n error = e;\n }\n\n if (!(error instanceof RetryableError)) {\n throw error;\n }\n\n if (i >= expBackoffMaxRepeats - 1) {\n throw error.error;\n }\n\n const waitMillis = expBackoffMillis * 2 ** i;\n const rand = (from: number, to: number) => from + Math.floor(Math.random() * (to - from + 1));\n const randomizedWaitMillis = rand(waitMillis, waitMillis * 2);\n\n if (i === Math.round(expBackoffMaxRepeats / 2)) {\n log.warning(`Retry failed ${i} times and will be repeated in ${randomizedWaitMillis}ms`, {\n originalError: error.error.message,\n errorDetails: Reflect.get(error.error, 'details'),\n });\n }\n\n await delayPromise(randomizedWaitMillis);\n }\n}\n"]}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
export declare enum CHECK_TYPES {
|
|
2
|
+
MONGODB_PING = "MONGODB_PING",
|
|
3
|
+
MONGODB_READ = "MONGODB_READ",
|
|
4
|
+
MONGODB_WRITE = "MONGODB_WRITE",
|
|
5
|
+
REDIS = "REDIS",// Old alias for 'REDIS_WRITE', deprecated
|
|
6
|
+
REDIS_PING = "REDIS_PING",
|
|
7
|
+
REDIS_WRITE = "REDIS_WRITE"
|
|
8
|
+
}
|
|
9
|
+
type CheckType<T extends Record<string, any> = Record<string, any>> = {
|
|
10
|
+
client: T;
|
|
11
|
+
type: CHECK_TYPES;
|
|
12
|
+
};
|
|
13
|
+
interface HealthCheckerOptions {
|
|
14
|
+
checks: CheckType[];
|
|
15
|
+
redisPrefix?: string;
|
|
16
|
+
redisTtlSecs?: number;
|
|
17
|
+
checkTimeoutMillis?: number;
|
|
18
|
+
mongoDbWriteTestCollection?: string;
|
|
19
|
+
mongoDbWriteTestRemoveOlderThanSecs?: number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Provides health-checking functionality to ensure that connection to Redis and MongoDB is working.
|
|
23
|
+
*
|
|
24
|
+
* Example use:
|
|
25
|
+
*
|
|
26
|
+
* ```javascript
|
|
27
|
+
* const redis = new Redis();
|
|
28
|
+
* const mongo = await MongoClient.connect('mongodb://127.0.0.1:3001/my-db');
|
|
29
|
+
*
|
|
30
|
+
* const checks = [{
|
|
31
|
+
* client: redis,
|
|
32
|
+
* type: HealthChecker.CHECK_TYPES.REDIS,
|
|
33
|
+
* }, {
|
|
34
|
+
* client: mongo.db('my-db'),
|
|
35
|
+
* type: HealthChecker.CHECK_TYPES.MONGODB_READ,
|
|
36
|
+
* }];
|
|
37
|
+
*
|
|
38
|
+
* const checker = new HealthChecker({ checks });
|
|
39
|
+
* setInterval(() => checker.ensureIsHealthy().then(() => console.log('ok'), err => console.log(err)), 5000);
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export declare class HealthChecker {
|
|
43
|
+
private readonly options;
|
|
44
|
+
static readonly CHECK_TYPES: typeof CHECK_TYPES;
|
|
45
|
+
checks: CheckType[];
|
|
46
|
+
redisPrefix: string;
|
|
47
|
+
redisTtlSecs: number;
|
|
48
|
+
checkTimeoutMillis: number;
|
|
49
|
+
mongoDbWriteTestCollection: string;
|
|
50
|
+
mongoDbWriteTestRemoveOlderThanSecs: number;
|
|
51
|
+
constructor(options: HealthCheckerOptions);
|
|
52
|
+
ensureIsHealthy(): Promise<void>;
|
|
53
|
+
_validateCheck(check: CheckType): void;
|
|
54
|
+
_performCheck(check: CheckType): Promise<void>;
|
|
55
|
+
_testMongoDbPing({ client }: CheckType): Promise<void>;
|
|
56
|
+
_testMongoDbRead({ client }: CheckType): Promise<void>;
|
|
57
|
+
_testMongoDbWrite({ client }: CheckType): Promise<void>;
|
|
58
|
+
_testRedisPing({ client }: CheckType): Promise<void>;
|
|
59
|
+
_testRedisWrite({ client }: CheckType): Promise<void>;
|
|
60
|
+
}
|
|
61
|
+
export {};
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { cryptoRandomObjectId, timeoutPromise } from './utilities.js';
|
|
2
|
+
export var CHECK_TYPES;
|
|
3
|
+
(function (CHECK_TYPES) {
|
|
4
|
+
CHECK_TYPES["MONGODB_PING"] = "MONGODB_PING";
|
|
5
|
+
CHECK_TYPES["MONGODB_READ"] = "MONGODB_READ";
|
|
6
|
+
CHECK_TYPES["MONGODB_WRITE"] = "MONGODB_WRITE";
|
|
7
|
+
CHECK_TYPES["REDIS"] = "REDIS";
|
|
8
|
+
CHECK_TYPES["REDIS_PING"] = "REDIS_PING";
|
|
9
|
+
CHECK_TYPES["REDIS_WRITE"] = "REDIS_WRITE";
|
|
10
|
+
})(CHECK_TYPES || (CHECK_TYPES = {}));
|
|
11
|
+
/**
|
|
12
|
+
* Provides health-checking functionality to ensure that connection to Redis and MongoDB is working.
|
|
13
|
+
*
|
|
14
|
+
* Example use:
|
|
15
|
+
*
|
|
16
|
+
* ```javascript
|
|
17
|
+
* const redis = new Redis();
|
|
18
|
+
* const mongo = await MongoClient.connect('mongodb://127.0.0.1:3001/my-db');
|
|
19
|
+
*
|
|
20
|
+
* const checks = [{
|
|
21
|
+
* client: redis,
|
|
22
|
+
* type: HealthChecker.CHECK_TYPES.REDIS,
|
|
23
|
+
* }, {
|
|
24
|
+
* client: mongo.db('my-db'),
|
|
25
|
+
* type: HealthChecker.CHECK_TYPES.MONGODB_READ,
|
|
26
|
+
* }];
|
|
27
|
+
*
|
|
28
|
+
* const checker = new HealthChecker({ checks });
|
|
29
|
+
* setInterval(() => checker.ensureIsHealthy().then(() => console.log('ok'), err => console.log(err)), 5000);
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export class HealthChecker {
|
|
33
|
+
options;
|
|
34
|
+
static CHECK_TYPES = CHECK_TYPES;
|
|
35
|
+
checks;
|
|
36
|
+
redisPrefix;
|
|
37
|
+
redisTtlSecs;
|
|
38
|
+
checkTimeoutMillis;
|
|
39
|
+
mongoDbWriteTestCollection;
|
|
40
|
+
mongoDbWriteTestRemoveOlderThanSecs;
|
|
41
|
+
constructor(options) {
|
|
42
|
+
this.options = options;
|
|
43
|
+
const { checks, redisPrefix = 'health-check', redisTtlSecs = 15, checkTimeoutMillis = 15000, mongoDbWriteTestCollection = 'healthCheckPlayground', mongoDbWriteTestRemoveOlderThanSecs = 15, } = options;
|
|
44
|
+
if (!Array.isArray(checks))
|
|
45
|
+
throw new Error('Parameter "check" must be an array');
|
|
46
|
+
checks.map((check) => this._validateCheck(check));
|
|
47
|
+
this.checks = checks;
|
|
48
|
+
this.redisPrefix = redisPrefix;
|
|
49
|
+
this.redisTtlSecs = redisTtlSecs;
|
|
50
|
+
this.checkTimeoutMillis = checkTimeoutMillis;
|
|
51
|
+
this.mongoDbWriteTestCollection = mongoDbWriteTestCollection;
|
|
52
|
+
this.mongoDbWriteTestRemoveOlderThanSecs = mongoDbWriteTestRemoveOlderThanSecs;
|
|
53
|
+
}
|
|
54
|
+
async ensureIsHealthy() {
|
|
55
|
+
for (const check of this.checks) {
|
|
56
|
+
try {
|
|
57
|
+
const checkPromise = this._performCheck(check);
|
|
58
|
+
await timeoutPromise(checkPromise, this.checkTimeoutMillis, 'Check has timed-out');
|
|
59
|
+
}
|
|
60
|
+
catch (_err) {
|
|
61
|
+
const err = _err;
|
|
62
|
+
throw new Error(`Health check test "${check.type}" failed with an error: ${err.message}"`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
_validateCheck(check) {
|
|
67
|
+
if (!(check.type in CHECK_TYPES))
|
|
68
|
+
throw new Error(`Check type "${check.type}" is invalid`);
|
|
69
|
+
if (typeof check.client !== 'object')
|
|
70
|
+
throw new Error(`Check client must be an object got "${typeof check.client}" instead`);
|
|
71
|
+
}
|
|
72
|
+
async _performCheck(check) {
|
|
73
|
+
switch (check.type) {
|
|
74
|
+
case CHECK_TYPES.MONGODB_PING:
|
|
75
|
+
return this._testMongoDbPing(check);
|
|
76
|
+
case CHECK_TYPES.MONGODB_READ:
|
|
77
|
+
return this._testMongoDbRead(check);
|
|
78
|
+
case CHECK_TYPES.MONGODB_WRITE:
|
|
79
|
+
return this._testMongoDbWrite(check);
|
|
80
|
+
case CHECK_TYPES.REDIS_PING:
|
|
81
|
+
return this._testRedisPing(check);
|
|
82
|
+
case CHECK_TYPES.REDIS:
|
|
83
|
+
case CHECK_TYPES.REDIS_WRITE:
|
|
84
|
+
return this._testRedisWrite(check);
|
|
85
|
+
default:
|
|
86
|
+
throw new Error('Unknown check type');
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
async _testMongoDbPing({ client }) {
|
|
90
|
+
const response = await client.command({ ping: 1 });
|
|
91
|
+
if (response.ok !== 1)
|
|
92
|
+
throw new Error(`Got ${response.ok} instead of 1!`);
|
|
93
|
+
}
|
|
94
|
+
async _testMongoDbRead({ client }) {
|
|
95
|
+
const response = await client.listCollections().toArray();
|
|
96
|
+
if (!Array.isArray(response))
|
|
97
|
+
throw new Error(`Got ${typeof response} instead of an array!`);
|
|
98
|
+
}
|
|
99
|
+
async _testMongoDbWrite({ client }) {
|
|
100
|
+
const id = cryptoRandomObjectId();
|
|
101
|
+
const collection = client.collection(this.mongoDbWriteTestCollection);
|
|
102
|
+
// Remove old test items.
|
|
103
|
+
await collection.deleteMany({
|
|
104
|
+
createdAt: {
|
|
105
|
+
$lt: new Date(Date.now() - this.mongoDbWriteTestRemoveOlderThanSecs * 1000),
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
// Insert and read some item.
|
|
109
|
+
await collection.insertOne({
|
|
110
|
+
_id: id,
|
|
111
|
+
createdAt: new Date(),
|
|
112
|
+
});
|
|
113
|
+
const retrieved = await collection.findOne({ _id: id });
|
|
114
|
+
if (!retrieved)
|
|
115
|
+
throw new Error(`Item with ID "${id}" not found!`);
|
|
116
|
+
}
|
|
117
|
+
async _testRedisPing({ client }) {
|
|
118
|
+
const response = await client.ping();
|
|
119
|
+
if (response !== 'PONG')
|
|
120
|
+
throw new Error(`Got "${response}" instead of "PONG"!`);
|
|
121
|
+
}
|
|
122
|
+
async _testRedisWrite({ client }) {
|
|
123
|
+
const key = `${this.redisPrefix}:${cryptoRandomObjectId()}`;
|
|
124
|
+
const expected = 'OK';
|
|
125
|
+
// Set some value in Redis and try to read it.
|
|
126
|
+
await client.set(key, expected, 'EX', this.redisTtlSecs);
|
|
127
|
+
const given = await client.get(key);
|
|
128
|
+
if (given !== expected)
|
|
129
|
+
throw new Error(`Returned value "${given}" is not equal to "${expected}"!`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
//# sourceMappingURL=health_checker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"health_checker.js","sourceRoot":"","sources":["../src/health_checker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,gBAAgB,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,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC;QACxD,IAAI,CAAC,SAAS;YAAE,MAAM,IAAI,KAAK,CAAC,iBAAiB,EAAE,cAAc,CAAC,CAAC;IACvE,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,EAAE,MAAM,EAAa;QACtC,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;QACrC,IAAI,QAAQ,KAAK,MAAM;YAAE,MAAM,IAAI,KAAK,CAAC,QAAQ,QAAQ,sBAAsB,CAAC,CAAC;IACrF,CAAC;IAED,KAAK,CAAC,eAAe,CAAC,EAAE,MAAM,EAAa;QACvC,MAAM,GAAG,GAAG,GAAG,IAAI,CAAC,WAAW,IAAI,oBAAoB,EAAE,EAAE,CAAC;QAC5D,MAAM,QAAQ,GAAG,IAAI,CAAC;QAEtB,8CAA8C;QAC9C,MAAM,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;QACzD,MAAM,KAAK,GAAG,MAAM,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACpC,IAAI,KAAK,KAAK,QAAQ;YAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,KAAK,sBAAsB,QAAQ,IAAI,CAAC,CAAC;IACxG,CAAC","sourcesContent":["import { cryptoRandomObjectId, timeoutPromise } from './utilities.js';\n\nexport enum CHECK_TYPES {\n MONGODB_PING = 'MONGODB_PING',\n MONGODB_READ = 'MONGODB_READ',\n MONGODB_WRITE = 'MONGODB_WRITE',\n REDIS = 'REDIS', // Old alias for 'REDIS_WRITE', deprecated\n REDIS_PING = 'REDIS_PING',\n REDIS_WRITE = 'REDIS_WRITE',\n}\n\ntype CheckType<T extends Record<string, any> = Record<string, any>> = { client: T; type: CHECK_TYPES };\n\ninterface HealthCheckerOptions {\n checks: CheckType[];\n redisPrefix?: string;\n redisTtlSecs?: number;\n checkTimeoutMillis?: number;\n mongoDbWriteTestCollection?: string;\n mongoDbWriteTestRemoveOlderThanSecs?: number;\n}\n\n/**\n * Provides health-checking functionality to ensure that connection to Redis and MongoDB is working.\n *\n * Example use:\n *\n * ```javascript\n * const redis = new Redis();\n * const mongo = await MongoClient.connect('mongodb://127.0.0.1:3001/my-db');\n *\n * const checks = [{\n * client: redis,\n * type: HealthChecker.CHECK_TYPES.REDIS,\n * }, {\n * client: mongo.db('my-db'),\n * type: HealthChecker.CHECK_TYPES.MONGODB_READ,\n * }];\n *\n * const checker = new HealthChecker({ checks });\n * setInterval(() => checker.ensureIsHealthy().then(() => console.log('ok'), err => console.log(err)), 5000);\n * ```\n */\nexport class HealthChecker {\n static readonly CHECK_TYPES = CHECK_TYPES;\n\n checks: CheckType[];\n\n redisPrefix: string;\n\n redisTtlSecs: number;\n\n checkTimeoutMillis: number;\n\n mongoDbWriteTestCollection: string;\n\n mongoDbWriteTestRemoveOlderThanSecs: number;\n\n constructor(private readonly options: HealthCheckerOptions) {\n const {\n checks,\n redisPrefix = 'health-check',\n redisTtlSecs = 15,\n checkTimeoutMillis = 15000,\n mongoDbWriteTestCollection = 'healthCheckPlayground',\n mongoDbWriteTestRemoveOlderThanSecs = 15,\n } = options;\n\n if (!Array.isArray(checks)) throw new Error('Parameter \"check\" must be an array');\n checks.map((check) => this._validateCheck(check));\n\n this.checks = checks;\n this.redisPrefix = redisPrefix;\n this.redisTtlSecs = redisTtlSecs;\n this.checkTimeoutMillis = checkTimeoutMillis;\n this.mongoDbWriteTestCollection = mongoDbWriteTestCollection;\n this.mongoDbWriteTestRemoveOlderThanSecs = mongoDbWriteTestRemoveOlderThanSecs;\n }\n\n async ensureIsHealthy() {\n for (const check of this.checks) {\n try {\n const checkPromise = this._performCheck(check);\n await timeoutPromise(checkPromise, this.checkTimeoutMillis, 'Check has timed-out');\n } catch (_err) {\n const err = _err as Error;\n throw new Error(`Health check test \"${check.type}\" failed with an error: ${err.message}\"`);\n }\n }\n }\n\n _validateCheck(check: CheckType): void {\n if (!(check.type in CHECK_TYPES)) throw new Error(`Check type \"${check.type}\" is invalid`);\n if (typeof check.client !== 'object')\n throw new Error(`Check client must be an object got \"${typeof check.client}\" instead`);\n }\n\n async _performCheck(check: CheckType): Promise<void> {\n switch (check.type) {\n case CHECK_TYPES.MONGODB_PING:\n return this._testMongoDbPing(check);\n case CHECK_TYPES.MONGODB_READ:\n return this._testMongoDbRead(check);\n case CHECK_TYPES.MONGODB_WRITE:\n return this._testMongoDbWrite(check);\n case CHECK_TYPES.REDIS_PING:\n return this._testRedisPing(check);\n case CHECK_TYPES.REDIS:\n case CHECK_TYPES.REDIS_WRITE:\n return this._testRedisWrite(check);\n default:\n throw new Error('Unknown check type');\n }\n }\n\n async _testMongoDbPing({ client }: CheckType) {\n const response = await client.command({ ping: 1 });\n if (response.ok !== 1) throw new Error(`Got ${response.ok} instead of 1!`);\n }\n\n async _testMongoDbRead({ client }: CheckType) {\n const response = await client.listCollections().toArray();\n if (!Array.isArray(response)) throw new Error(`Got ${typeof response} instead of an array!`);\n }\n\n async _testMongoDbWrite({ client }: CheckType) {\n const id = cryptoRandomObjectId();\n const collection = client.collection(this.mongoDbWriteTestCollection);\n\n // Remove old test items.\n await collection.deleteMany({\n createdAt: {\n $lt: new Date(Date.now() - this.mongoDbWriteTestRemoveOlderThanSecs * 1000),\n },\n });\n\n // Insert and read some item.\n await collection.insertOne({\n _id: id,\n createdAt: new Date(),\n });\n const retrieved = await collection.findOne({ _id: id });\n if (!retrieved) throw new Error(`Item with ID \"${id}\" not found!`);\n }\n\n async _testRedisPing({ client }: CheckType) {\n const response = await client.ping();\n if (response !== 'PONG') throw new Error(`Got \"${response}\" instead of \"PONG\"!`);\n }\n\n async _testRedisWrite({ client }: CheckType) {\n const key = `${this.redisPrefix}:${cryptoRandomObjectId()}`;\n const expected = 'OK';\n\n // Set some value in Redis and try to read it.\n await client.set(key, expected, 'EX', this.redisTtlSecs);\n const given = await client.get(key);\n if (given !== expected) throw new Error(`Returned value \"${given}\" is not equal to \"${expected}\"!`);\n }\n}\n"]}
|
package/hmac.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generates an HMAC signature and encodes it using Base62.
|
|
3
|
+
* Base62 encoding reduces the signature length.
|
|
4
|
+
*
|
|
5
|
+
* @param secretKey {string} Secret key used for signing signatures
|
|
6
|
+
* @param message {string} Message to be signed
|
|
7
|
+
* @returns string
|
|
8
|
+
* @deprecated Use {@link createHmacSignatureAsync} instead, which uses Web Crypto API and
|
|
9
|
+
* is available in both Node.js and browsers without the need for polyfills.
|
|
10
|
+
*/
|
|
11
|
+
export declare function createHmacSignature(secretKey: string, message: string): string;
|
|
12
|
+
/**
|
|
13
|
+
* Generates an HMAC signature and encodes it using Base62.
|
|
14
|
+
* Base62 encoding reduces the signature length.
|
|
15
|
+
*
|
|
16
|
+
* @param secretKey {string} Secret key used for signing signatures
|
|
17
|
+
* @param message {string} Message to be signed
|
|
18
|
+
* @returns Promise<string>
|
|
19
|
+
*/
|
|
20
|
+
export declare function createHmacSignatureAsync(secretKey: string, message: string): Promise<string>;
|
package/hmac.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
const CHARSET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
|
|
3
|
+
/**
|
|
4
|
+
* Encodes BigInt to base62.
|
|
5
|
+
*/
|
|
6
|
+
function encodeBase62(num) {
|
|
7
|
+
if (num === 0n) {
|
|
8
|
+
return CHARSET[0];
|
|
9
|
+
}
|
|
10
|
+
let res = '';
|
|
11
|
+
while (num > 0n) {
|
|
12
|
+
res = CHARSET[Number(num % 62n)] + res;
|
|
13
|
+
num /= 62n;
|
|
14
|
+
}
|
|
15
|
+
return res;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Generates an HMAC signature and encodes it using Base62.
|
|
19
|
+
* Base62 encoding reduces the signature length.
|
|
20
|
+
*
|
|
21
|
+
* @param secretKey {string} Secret key used for signing signatures
|
|
22
|
+
* @param message {string} Message to be signed
|
|
23
|
+
* @returns string
|
|
24
|
+
* @deprecated Use {@link createHmacSignatureAsync} instead, which uses Web Crypto API and
|
|
25
|
+
* is available in both Node.js and browsers without the need for polyfills.
|
|
26
|
+
*/
|
|
27
|
+
export function createHmacSignature(secretKey, message) {
|
|
28
|
+
const signature = crypto.createHmac('sha256', secretKey).update(message).digest('hex').substring(0, 30);
|
|
29
|
+
return encodeBase62(BigInt(`0x${signature}`));
|
|
30
|
+
}
|
|
31
|
+
const subtleCrypto = globalThis.crypto?.subtle;
|
|
32
|
+
function ensureSubtleCryptoExists() {
|
|
33
|
+
if (!subtleCrypto) {
|
|
34
|
+
throw new Error(`SubtleCrypto is not available in this environment.
|
|
35
|
+
Please ensure you're running in an environment that supports Web Crypto API,
|
|
36
|
+
or submit an issue to https://github.com/apify/apify-shared-js so we can help you further.`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Generates an HMAC signature and encodes it using Base62.
|
|
41
|
+
* Base62 encoding reduces the signature length.
|
|
42
|
+
*
|
|
43
|
+
* @param secretKey {string} Secret key used for signing signatures
|
|
44
|
+
* @param message {string} Message to be signed
|
|
45
|
+
* @returns Promise<string>
|
|
46
|
+
*/
|
|
47
|
+
export async function createHmacSignatureAsync(secretKey, message) {
|
|
48
|
+
ensureSubtleCryptoExists();
|
|
49
|
+
const encoder = new TextEncoder();
|
|
50
|
+
const key = await subtleCrypto.importKey('raw', encoder.encode(secretKey), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
51
|
+
const signatureBuffer = await subtleCrypto.sign('HMAC', key, encoder.encode(message));
|
|
52
|
+
const signatureArray = new Uint8Array(signatureBuffer);
|
|
53
|
+
const signatureHex = Array.from(signatureArray)
|
|
54
|
+
.map((b) => b.toString(16).padStart(2, '0'))
|
|
55
|
+
.join('')
|
|
56
|
+
.substring(0, 30);
|
|
57
|
+
return encodeBase62(BigInt(`0x${signatureHex}`));
|
|
58
|
+
}
|
|
59
|
+
//# sourceMappingURL=hmac.js.map
|
package/hmac.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hmac.js","sourceRoot":"","sources":["../src/hmac.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAC;AAEjC,MAAM,OAAO,GAAG,gEAAgE,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;AAE3F;;GAEG;AACH,SAAS,YAAY,CAAC,GAAW;IAC7B,IAAI,GAAG,KAAK,EAAE,EAAE,CAAC;QACb,OAAO,OAAO,CAAC,CAAC,CAAC,CAAC;IACtB,CAAC;IAED,IAAI,GAAG,GAAG,EAAE,CAAC;IACb,OAAO,GAAG,GAAG,EAAE,EAAE,CAAC;QACd,GAAG,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,GAAG,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC;QACvC,GAAG,IAAI,GAAG,CAAC;IACf,CAAC;IACD,OAAO,GAAG,CAAC;AACf,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,mBAAmB,CAAC,SAAiB,EAAE,OAAe;IAClE,MAAM,SAAS,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IAExG,OAAO,YAAY,CAAC,MAAM,CAAC,KAAK,SAAS,EAAE,CAAC,CAAC,CAAC;AAClD,CAAC;AAED,MAAM,YAAY,GAAG,UAAU,CAAC,MAAM,EAAE,MAAM,CAAC;AAE/C,SAAS,wBAAwB;IAC7B,IAAI,CAAC,YAAY,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CAAC;;2FAEmE,CAAC,CAAC;IACzF,CAAC;AACL,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAAC,SAAiB,EAAE,OAAe;IAC7E,wBAAwB,EAAE,CAAC;IAC3B,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAElC,MAAM,GAAG,GAAG,MAAM,YAAY,CAAC,SAAS,CACpC,KAAK,EACL,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,EACzB,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,EACjC,KAAK,EACL,CAAC,MAAM,CAAC,CACX,CAAC;IAEF,MAAM,eAAe,GAAG,MAAM,YAAY,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;IAEtF,MAAM,cAAc,GAAG,IAAI,UAAU,CAAC,eAAe,CAAC,CAAC;IACvD,MAAM,YAAY,GAAG,KAAK,CAAC,IAAI,CAAC,cAAc,CAAC;SAC1C,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;SAC3C,IAAI,CAAC,EAAE,CAAC;SACR,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IAEtB,OAAO,YAAY,CAAC,MAAM,CAAC,KAAK,YAAY,EAAE,CAAC,CAAC,CAAC;AACrD,CAAC","sourcesContent":["import crypto from 'node:crypto';\n\nconst CHARSET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');\n\n/**\n * Encodes BigInt to base62.\n */\nfunction encodeBase62(num: bigint) {\n if (num === 0n) {\n return CHARSET[0];\n }\n\n let res = '';\n while (num > 0n) {\n res = CHARSET[Number(num % 62n)] + res;\n num /= 62n;\n }\n return res;\n}\n\n/**\n * Generates an HMAC signature and encodes it using Base62.\n * Base62 encoding reduces the signature length.\n *\n * @param secretKey {string} Secret key used for signing signatures\n * @param message {string} Message to be signed\n * @returns string\n * @deprecated Use {@link createHmacSignatureAsync} instead, which uses Web Crypto API and\n * is available in both Node.js and browsers without the need for polyfills.\n */\nexport function createHmacSignature(secretKey: string, message: string): string {\n const signature = crypto.createHmac('sha256', secretKey).update(message).digest('hex').substring(0, 30);\n\n return encodeBase62(BigInt(`0x${signature}`));\n}\n\nconst subtleCrypto = globalThis.crypto?.subtle;\n\nfunction ensureSubtleCryptoExists() {\n if (!subtleCrypto) {\n throw new Error(`SubtleCrypto is not available in this environment.\nPlease ensure you're running in an environment that supports Web Crypto API,\nor submit an issue to https://github.com/apify/apify-shared-js so we can help you further.`);\n }\n}\n\n/**\n * Generates an HMAC signature and encodes it using Base62.\n * Base62 encoding reduces the signature length.\n *\n * @param secretKey {string} Secret key used for signing signatures\n * @param message {string} Message to be signed\n * @returns Promise<string>\n */\nexport async function createHmacSignatureAsync(secretKey: string, message: string): Promise<string> {\n ensureSubtleCryptoExists();\n const encoder = new TextEncoder();\n\n const key = await subtleCrypto.importKey(\n 'raw',\n encoder.encode(secretKey),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n\n const signatureBuffer = await subtleCrypto.sign('HMAC', key, encoder.encode(message));\n\n const signatureArray = new Uint8Array(signatureBuffer);\n const signatureHex = Array.from(signatureArray)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n .substring(0, 30);\n\n return encodeBase62(BigInt(`0x${signatureHex}`));\n}\n"]}
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export * from './utilities.js';
|
|
2
|
+
export * from './utilities.client.js';
|
|
3
|
+
export * from './usernames.js';
|
|
4
|
+
export * from './exponential_backoff.js';
|
|
5
|
+
export * from './health_checker.js';
|
|
6
|
+
export * from './parse_jsonl_stream.js';
|
|
7
|
+
export * from './streams_utilities.js';
|
|
8
|
+
export * from './webhook_payload_template.js';
|
|
9
|
+
export * from './crypto.js';
|
|
10
|
+
export * from './url_params_utils.js';
|
|
11
|
+
export * from './code_hash_manager.js';
|
|
12
|
+
export * from './hmac.js';
|
|
13
|
+
export * from './storages.js';
|
|
14
|
+
export * from './parse_boolean.js';
|
package/index.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export * from './utilities.js';
|
|
2
|
+
export * from './utilities.client.js';
|
|
3
|
+
export * from './usernames.js';
|
|
4
|
+
export * from './exponential_backoff.js';
|
|
5
|
+
export * from './health_checker.js';
|
|
6
|
+
export * from './parse_jsonl_stream.js';
|
|
7
|
+
export * from './streams_utilities.js';
|
|
8
|
+
export * from './webhook_payload_template.js';
|
|
9
|
+
export * from './crypto.js';
|
|
10
|
+
export * from './url_params_utils.js';
|
|
11
|
+
export * from './code_hash_manager.js';
|
|
12
|
+
export * from './hmac.js';
|
|
13
|
+
export * from './storages.js';
|
|
14
|
+
export * from './parse_boolean.js';
|
|
15
|
+
//# sourceMappingURL=index.js.map
|
package/index.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,uBAAuB,CAAC;AACtC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,0BAA0B,CAAC;AACzC,cAAc,qBAAqB,CAAC;AACpC,cAAc,yBAAyB,CAAC;AACxC,cAAc,wBAAwB,CAAC;AACvC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,aAAa,CAAC;AAC5B,cAAc,uBAAuB,CAAC;AACtC,cAAc,wBAAwB,CAAC;AACvC,cAAc,WAAW,CAAC;AAC1B,cAAc,eAAe,CAAC;AAC9B,cAAc,oBAAoB,CAAC","sourcesContent":["export * from './utilities.js';\nexport * from './utilities.client.js';\nexport * from './usernames.js';\nexport * from './exponential_backoff.js';\nexport * from './health_checker.js';\nexport * from './parse_jsonl_stream.js';\nexport * from './streams_utilities.js';\nexport * from './webhook_payload_template.js';\nexport * from './crypto.js';\nexport * from './url_params_utils.js';\nexport * from './code_hash_manager.js';\nexport * from './hmac.js';\nexport * from './storages.js';\nexport * from './parse_boolean.js';\n"]}
|