@ellipticltd/aml-utils 0.1.0 → 0.1.1-ts.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.
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ var __importStar = (this && this.__importStar) || function (mod) {
3
+ if (mod && mod.__esModule) return mod;
4
+ var result = {};
5
+ if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
6
+ result["default"] = mod;
7
+ return result;
8
+ };
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ const _ = __importStar(require("lodash"));
11
+ const rethrowError = (fnName, e) => {
12
+ let formattedError;
13
+ if (_.isPlainObject(e.error) || _.isArray(e.error)) {
14
+ formattedError = `\n${JSON.stringify(e.error, null, 2)}`;
15
+ }
16
+ else {
17
+ formattedError = e.error;
18
+ }
19
+ return `${fnName} - ${e.name}: ${e.statusCode} - ${formattedError}`;
20
+ };
21
+ const sqlEscapeWildcard = (str) => str.replace(/_|%|\\/g, x => `\\${x}`);
22
+ module.exports = {
23
+ rethrowError,
24
+ sqlEscapeWildcard,
25
+ };
File without changes
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ module.exports = {
3
+ types: require('./types'),
4
+ validations: require('./validations'),
5
+ errors: require('./errors'),
6
+ formatting: require('./formatting'),
7
+ middleware: require('./middleware'),
8
+ ormHelpers: require('./ormHelpers'),
9
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const T = require('./types');
4
+ const ensureType = (type) => (req, res, next, id, name) => {
5
+ let error;
6
+ try {
7
+ T.ensureType(type, id, `Invalid ${name}`);
8
+ return next();
9
+ }
10
+ catch (error1) {
11
+ error = error1;
12
+ return next(error);
13
+ }
14
+ };
15
+ const ensureUUID = ensureType('UUID');
16
+ const ensureHex32 = ensureType('Hex32');
17
+ const ensureInteger = ensureType('IntString');
18
+ module.exports = {
19
+ ensureType,
20
+ ensureUUID,
21
+ ensureHex32,
22
+ ensureInteger,
23
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ var __importStar = (this && this.__importStar) || function (mod) {
3
+ if (mod && mod.__esModule) return mod;
4
+ var result = {};
5
+ if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
6
+ result["default"] = mod;
7
+ return result;
8
+ };
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ const _ = __importStar(require("lodash"));
11
+ const includeNested = (orm, models) => _.map(_.toPairs(models), (arg) => {
12
+ const [modelName, inclusion] = arg;
13
+ const include = includeNested(orm, inclusion);
14
+ const model = orm[modelName];
15
+ if (_.isEmpty(include)) {
16
+ return model;
17
+ }
18
+ return {
19
+ model,
20
+ include,
21
+ };
22
+ });
23
+ module.exports = {
24
+ includeNested,
25
+ };
package/dist/test.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/test.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1 @@
1
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1,207 @@
1
+ "use strict";
2
+ var __importStar = (this && this.__importStar) || function (mod) {
3
+ if (mod && mod.__esModule) return mod;
4
+ var result = {};
5
+ if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
6
+ result["default"] = mod;
7
+ return result;
8
+ };
9
+ var __importDefault = (this && this.__importDefault) || function (mod) {
10
+ return (mod && mod.__esModule) ? mod : { "default": mod };
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ // @ts-ignore
14
+ const TC = __importStar(require("type-check"));
15
+ const _ = __importStar(require("lodash"));
16
+ const validations_1 = __importDefault(require("./validations"));
17
+ const E = __importStar(require("./errors"));
18
+ const customTypes = {
19
+ Integer: {
20
+ typeOf: 'Number',
21
+ validate(x) {
22
+ return x % 1 === 0;
23
+ },
24
+ },
25
+ IntString: {
26
+ typeOf: 'String',
27
+ validate: validations_1.default.isInt,
28
+ },
29
+ BoolString: {
30
+ typeOf: 'String',
31
+ validate: validations_1.default.isBoolean,
32
+ },
33
+ Hex32: {
34
+ typeOf: 'String',
35
+ validate(x) {
36
+ return validations_1.default.isHexadecimal(x) && x.length === 32;
37
+ },
38
+ },
39
+ Email: {
40
+ typeOf: 'String',
41
+ validate: validations_1.default.isEmail,
42
+ },
43
+ UUID: {
44
+ typeOf: 'String',
45
+ validate: validations_1.default.isUUID,
46
+ },
47
+ UUIDv4: {
48
+ typeOf: 'String',
49
+ validate(x) {
50
+ return validations_1.default.isUUID(x, 4);
51
+ },
52
+ },
53
+ JSON: {
54
+ typeOf: 'String',
55
+ validate: validations_1.default.isJSON,
56
+ },
57
+ Url: {
58
+ typeOf: 'String',
59
+ validate: validations_1.default.isURL,
60
+ },
61
+ NonEmptyArray: {
62
+ typeOf: 'Array',
63
+ validate: validations_1.default.nonEmpty,
64
+ },
65
+ NonNullString: {
66
+ typeOf: 'String',
67
+ validate: validations_1.default.nonEmpty,
68
+ },
69
+ CustomerReference: {
70
+ typeOf: 'String',
71
+ validate: validations_1.default.isCustomerReference,
72
+ },
73
+ CustomerLabelName: {
74
+ typeOf: 'String',
75
+ validate: validations_1.default.isCustomerLabelName,
76
+ },
77
+ BitcoinAddress: {
78
+ typeOf: 'String',
79
+ validate: validations_1.default.bitcoin.isAddress,
80
+ },
81
+ EthereumAddress: {
82
+ typeOf: 'String',
83
+ validate: validations_1.default.ethereum.isAddress,
84
+ },
85
+ EthereumTx: {
86
+ typeOf: 'String',
87
+ validate: validations_1.default.ethereum.isTxHash,
88
+ },
89
+ EthereumBlockHash: {
90
+ typeOf: 'String',
91
+ validate: validations_1.default.ethereum.isBlockHash,
92
+ },
93
+ EthereumWeiAmount: {
94
+ typeOf: 'String',
95
+ validate: validations_1.default.ethereum.isValidWeiAmount,
96
+ },
97
+ EthereumAddressCode: {
98
+ typeOf: 'String',
99
+ validate: validations_1.default.ethereum.isAddressCode,
100
+ },
101
+ MineId: {
102
+ typeOf: 'String',
103
+ validate(x) {
104
+ return x === 'mine';
105
+ },
106
+ },
107
+ BitcoinTxHash: {
108
+ typeOf: 'String',
109
+ validate: validations_1.default.bitcoin.isTxHash,
110
+ },
111
+ BitcoinAddressArray: {
112
+ typeOf: 'Array',
113
+ validate(as) {
114
+ return _.every(as, validations_1.default.bitcoin.isAddress);
115
+ },
116
+ },
117
+ BitcoinTxHashArray: {
118
+ typeOf: 'Array',
119
+ validate(as) {
120
+ return _.every(as, validations_1.default.bitcoin.isTxHash);
121
+ },
122
+ },
123
+ BitcoinTxHex: {
124
+ typeOf: 'String',
125
+ validate: validations_1.default.bitcoin.isTxHex,
126
+ },
127
+ BitcoinScriptHex: {
128
+ typeOf: 'String',
129
+ validate: validations_1.default.bitcoin.isScriptHex,
130
+ },
131
+ BitcoinHDPath: {
132
+ typeOf: 'String',
133
+ validate: validations_1.default.bitcoin.isHDPath,
134
+ },
135
+ BitcoinPublicKey: {
136
+ typeOf: 'String',
137
+ validate: validations_1.default.bitcoin.isPublicKey,
138
+ },
139
+ BitcoinXpub: {
140
+ typeOf: 'String',
141
+ validate: validations_1.default.bitcoin.isHDPublicKey,
142
+ },
143
+ BitcoinTxSignature: {
144
+ typeOf: 'String',
145
+ validate: validations_1.default.bitcoin.isTxSignature,
146
+ },
147
+ BitcoinBlockHeight: {
148
+ typeOf: 'Number',
149
+ validate: validations_1.default.bitcoin.isBlockHeight,
150
+ },
151
+ };
152
+ // add support for nullable properties
153
+ const withNullable = Object.keys(customTypes).reduce((acc, _type) => {
154
+ acc[_type] = customTypes[_type];
155
+ const { typeOf, validate } = customTypes[_type];
156
+ // for every type, add Nullable+type. A nullable string can also be empty
157
+ acc[`Nullable${_type}`] = Object.assign({}, customTypes[_type], {
158
+ validate: (x) => x == null || (typeOf === 'String' && x === '') || validate(x),
159
+ });
160
+ return acc;
161
+ }, {});
162
+ module.exports = {
163
+ parseType(str) {
164
+ return TC.parseType(str);
165
+ },
166
+ parsedTypeCheck(type, obj) {
167
+ return TC.parsedTypeCheck(type, obj, this.opts);
168
+ },
169
+ typeCheck(type, obj) {
170
+ return TC.typeCheck(type, obj, this.opts);
171
+ },
172
+ opts: {
173
+ customTypes: withNullable,
174
+ },
175
+ ensureType(type, obj, msg) {
176
+ return validations_1.default.ensure(this.typeCheck(type, obj), msg);
177
+ },
178
+ checkArg(obj, prop, type, msg) {
179
+ if (msg == null) {
180
+ msg = `Invalid ${prop}`;
181
+ }
182
+ this.ensureType(type, obj[prop], msg);
183
+ return obj[prop];
184
+ },
185
+ checkArgs(input, types) {
186
+ const inputKeys = {};
187
+ const [typ] = types;
188
+ const fields = typ.of;
189
+ let numInputKeys = 0;
190
+ let numKeys;
191
+ Object.keys(input).forEach((k) => {
192
+ inputKeys[k] = true;
193
+ numInputKeys += 1;
194
+ });
195
+ numKeys = 0;
196
+ Object.keys(fields).forEach((key) => {
197
+ types = fields[key];
198
+ validations_1.default.ensure(this.parsedTypeCheck(types, input[key]), `Invalid ${key}`);
199
+ if (inputKeys[key]) {
200
+ numKeys += 1;
201
+ }
202
+ });
203
+ if (!(typ.subset || numInputKeys === numKeys)) {
204
+ throw new E.BadRequest('invalid extra arguments are present');
205
+ }
206
+ },
207
+ };
@@ -0,0 +1,49 @@
1
+ declare type ValidatorFunction = (...args: any) => any;
2
+ declare type Validations = {
3
+ _validate: (Err: new (msg: string) => Error, pred: (x: any) => boolean, x: any, msg: string) => any;
4
+ _validateArg: (pred: (x: any) => boolean, x: any, msg: string) => any;
5
+ _tryCheck: (fn: (arg: any) => any, arg: any) => boolean;
6
+ exists: (x: any) => boolean;
7
+ argExists: (x: any, msg: string) => boolean;
8
+ nonEmpty: ValidatorFunction;
9
+ isNonEmptyString: ValidatorFunction;
10
+ ensureShortEnough: ValidatorFunction;
11
+ ensure: ValidatorFunction;
12
+ check: {
13
+ matches: ValidatorFunction;
14
+ wasFound: ValidatorFunction;
15
+ wasCreated: ValidatorFunction;
16
+ isTrue: ValidatorFunction;
17
+ isFalse: ValidatorFunction;
18
+ };
19
+ isCustomerReference: ValidatorFunction;
20
+ isCustomerLabelName: ValidatorFunction;
21
+ ethereum: {
22
+ isAddress: ValidatorFunction;
23
+ isBlockHash: ValidatorFunction;
24
+ isTxHash: ValidatorFunction;
25
+ isAddressCode: ValidatorFunction;
26
+ isValidWeiAmount: ValidatorFunction;
27
+ };
28
+ bitcoin: {
29
+ isAddress: ValidatorFunction;
30
+ isHDPublicKey: ValidatorFunction;
31
+ isPublicKey: ValidatorFunction;
32
+ isTxHash: ValidatorFunction;
33
+ isTxHex: ValidatorFunction;
34
+ isHDPath: ValidatorFunction;
35
+ isScriptHex: ValidatorFunction;
36
+ isTxSignature: ValidatorFunction;
37
+ isBlockHeight: ValidatorFunction;
38
+ };
39
+ bitcoinCash: {
40
+ isAddress: ValidatorFunction;
41
+ isTxHash: ValidatorFunction;
42
+ };
43
+ litecoin: {
44
+ isAddress: ValidatorFunction;
45
+ isTxHash: ValidatorFunction;
46
+ };
47
+ };
48
+ declare const _default: Validations & IValidatorStatic;
49
+ export default _default;
@@ -0,0 +1,238 @@
1
+ "use strict";
2
+ var __importStar = (this && this.__importStar) || function (mod) {
3
+ if (mod && mod.__esModule) return mod;
4
+ var result = {};
5
+ if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
6
+ result["default"] = mod;
7
+ return result;
8
+ };
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ const _ = __importStar(require("lodash"));
11
+ const V = __importStar(require("validator"));
12
+ const E = __importStar(require("./errors"));
13
+ const { crypto: { Signature }, HDPrivateKey, HDPublicKey, PublicKey, Script, Transaction, } = require('bitcore-lib');
14
+ const addressValidator = require('wallet-address-validator');
15
+ const web3 = require('web3-utils');
16
+ const helpers = {};
17
+ const validations = {
18
+ _validate(Err, pred, x, msg) {
19
+ if (pred(x)) {
20
+ return x;
21
+ }
22
+ throw new Err(msg);
23
+ },
24
+ _validateArg(pred, x, msg) {
25
+ return this._validate(E.InvalidArguments, pred, x, msg);
26
+ },
27
+ _tryCheck(fn, arg) {
28
+ try {
29
+ fn(arg);
30
+ return true;
31
+ }
32
+ catch (error) {
33
+ return false;
34
+ }
35
+ },
36
+ exists(x) {
37
+ return x != null;
38
+ },
39
+ argExists(x, msg) {
40
+ return this._validateArg(this.exists, x, msg);
41
+ },
42
+ nonEmpty(x) {
43
+ return (x != null ? x.length : undefined) > 0;
44
+ },
45
+ isNonEmptyString(x) {
46
+ return _.isString(x) && (x != null ? x.length : 0) > 0;
47
+ },
48
+ ensureShortEnough(limit, x) {
49
+ const l = x != null ? x.length : undefined;
50
+ if (l <= limit) {
51
+ return true;
52
+ }
53
+ throw new E.BadRequest(`Max query size exceeded: ${l} / ${limit}`);
54
+ },
55
+ ensure(crit, msg) {
56
+ if (crit) {
57
+ return true;
58
+ }
59
+ throw new E.BadRequest(msg);
60
+ },
61
+ check: {
62
+ matches(required, given, msg) {
63
+ given = _.uniq(given);
64
+ const crit = _.intersection(given, required).length === given.length;
65
+ if (crit) {
66
+ return true;
67
+ }
68
+ throw new E.BadRequest(msg);
69
+ },
70
+ wasFound(type) {
71
+ return (item) => {
72
+ if (item == null) {
73
+ throw new E.NotFound(`Unknown ${type}`);
74
+ }
75
+ else {
76
+ return item;
77
+ }
78
+ };
79
+ },
80
+ wasCreated(msg) {
81
+ return (arr) => {
82
+ if (!arr[1]) {
83
+ throw new E.BadRequest(msg);
84
+ }
85
+ else {
86
+ return arr;
87
+ }
88
+ };
89
+ },
90
+ isTrue(crit, msg) {
91
+ if (crit) {
92
+ return true;
93
+ }
94
+ throw new E.BadRequest(msg);
95
+ },
96
+ isFalse(crit, msg) {
97
+ if (!crit) {
98
+ return true;
99
+ }
100
+ throw new E.BadRequest(msg);
101
+ },
102
+ },
103
+ isCustomerReference(x) {
104
+ return (_.isString(x) &&
105
+ (x != null ? x.length > 0 : false) &&
106
+ (x != null ? x.length <= 100 : false));
107
+ },
108
+ isCustomerLabelName(x) {
109
+ return (_.isString(x) &&
110
+ (x != null ? x.length > 0 : false) &&
111
+ (x != null ? x.length <= 50 : false));
112
+ },
113
+ ethereum: {
114
+ isAddress(str) {
115
+ return web3.isAddress(str);
116
+ },
117
+ isBlockHash(str) {
118
+ return str.length === 66 && web3.isHexStrict(str);
119
+ },
120
+ isTxHash(str) {
121
+ return str.length === 66 && web3.isHexStrict(str);
122
+ },
123
+ isAddressCode(str) {
124
+ return web3.isHexStrict(str);
125
+ },
126
+ isValidWeiAmount(str) {
127
+ try {
128
+ web3.fromWei(str);
129
+ return true;
130
+ }
131
+ catch (e) {
132
+ return false;
133
+ }
134
+ },
135
+ },
136
+ bitcoin: {
137
+ isAddress(str) {
138
+ const network = process.env.BITCOIN_NETWORK === 'testnet' ? 'testnet' : 'livenet';
139
+ return typeof str === 'string' && addressValidator.validate(str.trim(), 'BTC', network);
140
+ },
141
+ isHDPublicKey(str) {
142
+ try {
143
+ HDPublicKey(str);
144
+ return true;
145
+ }
146
+ catch (error) {
147
+ return false;
148
+ }
149
+ },
150
+ isPublicKey(str) {
151
+ try {
152
+ PublicKey(str);
153
+ return true;
154
+ }
155
+ catch (error) {
156
+ return false;
157
+ }
158
+ },
159
+ isTxHash(str) {
160
+ if (!V.isHexadecimal(`${str}`)) {
161
+ return false;
162
+ }
163
+ return str.length === 64;
164
+ },
165
+ isTxHex(str) {
166
+ if (!V.isHexadecimal(`${str}`)) {
167
+ return false;
168
+ }
169
+ try {
170
+ Transaction(str);
171
+ return true;
172
+ }
173
+ catch (error) {
174
+ return false;
175
+ }
176
+ },
177
+ isHDPath(str) {
178
+ return HDPrivateKey.isValidPath(str);
179
+ },
180
+ isScriptHex(str) {
181
+ if (!V.isHexadecimal(`${str}`)) {
182
+ return false;
183
+ }
184
+ try {
185
+ Script(str);
186
+ return true;
187
+ }
188
+ catch (error) {
189
+ return false;
190
+ }
191
+ },
192
+ isTxSignature(str) {
193
+ if (!V.isHexadecimal(`${str}`)) {
194
+ return false;
195
+ }
196
+ try {
197
+ const b = Buffer.from(str, 'hex');
198
+ Signature.fromTxFormat(b);
199
+ return true;
200
+ }
201
+ catch (error) {
202
+ return false;
203
+ }
204
+ },
205
+ isBlockHeight(obj) {
206
+ return _.isInteger(+obj) && parseInt(obj, 10) >= 0;
207
+ },
208
+ },
209
+ bitcoinCash: {
210
+ isAddress(str) {
211
+ return /^[13][a-km-zA-HJ-NP-Z1-9]{25,34}|^(bitcoincash:)?[q|p][a-z0-9]{41}|^(BITCOINCASH:)?[Q|P][A-Z0-9]{41}/.test(str);
212
+ },
213
+ isTxHash(str) {
214
+ if (!V.isHexadecimal(`${str}`)) {
215
+ return false;
216
+ }
217
+ return str.length === 64;
218
+ },
219
+ },
220
+ litecoin: {
221
+ isAddress(str) {
222
+ return /^[3LM][a-km-zA-HJ-NP-Z1-9]{24,33}|^ltc1[ac-hj-np-z02-9]{6,86}|^LTC1[AC-HJ-NP-Z02-9]{6,86}/.test(str);
223
+ },
224
+ isTxHash(str) {
225
+ if (!V.isHexadecimal(`${str}`)) {
226
+ return false;
227
+ }
228
+ return str.length === 64;
229
+ },
230
+ },
231
+ };
232
+ Object.assign(validations, helpers);
233
+ Object.keys(V).forEach((k) => {
234
+ const v = V[k];
235
+ // don't trigger validation with null values (prevents swagger 500 error)
236
+ validations[k] = (x) => (x === null ? false : v(x));
237
+ });
238
+ exports.default = validations;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ellipticltd/aml-utils",
3
- "version": "0.1.0",
3
+ "version": "0.1.1-ts.0",
4
4
  "description": "Utilities, helpers, validations, type-checking, etc",
5
5
  "engines": {
6
6
  "node": "10.1.0",
@@ -11,10 +11,12 @@
11
11
  "url": "git+ssh://git@bitbucket.org/elliptic/aml-utils.git"
12
12
  },
13
13
  "homepage": "https://bitbucket.org/elliptic/aml-utils#readme",
14
- "main": "index.js",
14
+ "main": "dist/index.js",
15
15
  "scripts": {
16
- "test": "./node_modules/.bin/mocha --reporter spec --compilers coffee:coffee-script/register --require 'test/index.coffee'",
17
- "compile": "./node_modules/coffee-script/bin/coffee -c index.coffee **/*.coffee",
16
+ "prepublish": "npm run build",
17
+ "test": "npm run build && mocha --reporter spec --compilers coffee:coffee-script/register --require 'test/index.coffee'",
18
+ "lint": "tslint --project tsconfig.json -c tslint.json lib/**/*.ts",
19
+ "build": "tsc",
18
20
  "preprocess": "npm run compile"
19
21
  },
20
22
  "author": "Adam Joyce <adam@ellipitc.co>",
@@ -30,11 +32,18 @@
30
32
  },
31
33
  "devDependencies": {
32
34
  "@ellipticltd/eslint-config": "0.0.3",
35
+ "@types/express": "^4.17.0",
36
+ "@types/lodash": "^4.14.135",
37
+ "@types/node": "^12.0.10",
38
+ "@types/validator": "^10.11.1",
33
39
  "chai": "4.1.1",
34
40
  "coffee-script": "1.12.7",
35
41
  "eslint": "5.9.0",
36
42
  "eslint-config-airbnb-base": "13.1.0",
37
43
  "eslint-plugin-import": "^2.18.0",
38
- "mocha": "3.5.0"
44
+ "mocha": "3.5.0",
45
+ "tslint": "^5.18.0",
46
+ "tslint-config-airbnb": "^5.11.1",
47
+ "typescript": "^3.5.2"
39
48
  }
40
49
  }