ag-common 0.0.3 → 0.0.7

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/LICENSE.md ADDED
@@ -0,0 +1,7 @@
1
+ ISC License
2
+
3
+ Copyright 2021 Andrei Gec
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,22 @@
1
+ # ag-common
2
+
3
+ > Various reusable libaries for: common ts/js / api (aws cognito, aws-cdk) / ui (react)
4
+
5
+ [![NPM Version][npm-image]][npm-url]
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm i -S ag-common
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ Please raise any issues or requests you might have [here](https://github.com/andreigec/ag-common/issues)
16
+
17
+ ## License
18
+
19
+ [ISC](./LICENSE.md)
20
+
21
+ [npm-image]: https://img.shields.io/npm/v/ag-common.svg
22
+ [npm-url]: https://www.npmjs.com/package/ag-common
@@ -1,3 +1,5 @@
1
1
  export * from './api';
2
2
  export * from './dynamoInfra';
3
3
  export * from './openApiHelpers';
4
+ export * from './validateOpenApi';
5
+ export * from './validations';
@@ -13,3 +13,5 @@ Object.defineProperty(exports, "__esModule", { value: true });
13
13
  __exportStar(require("./api"), exports);
14
14
  __exportStar(require("./dynamoInfra"), exports);
15
15
  __exportStar(require("./openApiHelpers"), exports);
16
+ __exportStar(require("./validateOpenApi"), exports);
17
+ __exportStar(require("./validations"), exports);
@@ -5,7 +5,7 @@ exports.openApiImpl = void 0;
5
5
  const aws_cdk_lib_1 = require("aws-cdk-lib");
6
6
  const distinctBy_1 = require("../../common/helpers/distinctBy");
7
7
  const log_1 = require("../../common/helpers/log");
8
- // eslint-disable-next-line @typescript-eslint/no-var-requires
8
+ // eslint-disable-next-line
9
9
  const getPaths = (schema) => Object.entries(schema.paths).map(([fullPath, verbs]) => ({
10
10
  fullPath,
11
11
  pathList: fullPath.split('/').filter((s) => s),
@@ -0,0 +1,15 @@
1
+ import { APIGatewayEvent, APIGatewayProxyResult } from 'aws-lambda';
2
+ import { User } from 'analytica.click';
3
+ export declare type NextType<T> = ({ event, body, params, userProfile, }: {
4
+ params: Record<string, string>;
5
+ event: APIGatewayEvent;
6
+ body: T;
7
+ userProfile?: User;
8
+ }) => Promise<APIGatewayProxyResult>;
9
+ export declare function validateOpenApi<T>({ event, next, authorized, schema, COGNITO_USER_POOL_ID, }: {
10
+ COGNITO_USER_POOL_ID: string;
11
+ schema: any;
12
+ event: APIGatewayEvent;
13
+ next: NextType<T>;
14
+ authorized?: true | false | 'optional';
15
+ }): Promise<APIGatewayProxyResult>;
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.validateOpenApi = void 0;
16
+ const openapi_request_validator_1 = __importDefault(require("openapi-request-validator"));
17
+ const validations_1 = require("./validations");
18
+ const log_1 = require("../../common/helpers/log");
19
+ const object_1 = require("../../common/helpers/object");
20
+ const api_1 = require("./api");
21
+ //
22
+ const getOperation = ({ path, method, resource, schema, }) => {
23
+ var _a;
24
+ const resourcePath = Object.keys(schema.paths).find((rp) => rp === resource);
25
+ if (!resourcePath) {
26
+ throw new Error('incorrect path');
27
+ }
28
+ const operation = (_a = schema.paths[resourcePath]) === null || _a === void 0 ? void 0 : _a[method];
29
+ if (!operation) {
30
+ const msg = `no operation found for ${method}/${path}`;
31
+ (0, log_1.warn)(`${msg} ${Object.keys(schema.paths)}`);
32
+ throw new Error(msg);
33
+ }
34
+ /*
35
+ var path= '/events/12345/topics/2216026039415263/like'
36
+ var resourcePath ='/events/{eventCode}/topics/{topicId}/like'
37
+ */
38
+ const re = new RegExp(resourcePath
39
+ .replace(/\//gim, `\\/`)
40
+ .replace(/\{(.+?)\}/gim, '(?<$1>[^\\\\]+)'), 'i').exec(path);
41
+ const pathParams = (re === null || re === void 0 ? void 0 : re.groups) && JSON.parse(JSON.stringify(re === null || re === void 0 ? void 0 : re.groups));
42
+ return { operation, pathParams };
43
+ };
44
+ function validateOpenApi({ event, next, authorized, schema, COGNITO_USER_POOL_ID, }) {
45
+ var _a, _b, _c, _d;
46
+ return __awaiter(this, void 0, void 0, function* () {
47
+ const request = {
48
+ method: event.httpMethod,
49
+ path: event.path,
50
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
51
+ params: undefined,
52
+ query: event.queryStringParameters,
53
+ body: event.body && JSON.parse(event.body),
54
+ headers: (0, object_1.objectKeysToLowerCase)(event === null || event === void 0 ? void 0 : event.headers),
55
+ };
56
+ const method = event.requestContext.httpMethod.toLowerCase();
57
+ const pathParameters = event.pathParameters || {};
58
+ const queryStringParameters = event.queryStringParameters || {};
59
+ //
60
+ const opm = getOperation({
61
+ path: event.path,
62
+ method,
63
+ resource: event.resource,
64
+ schema,
65
+ });
66
+ if (!(opm === null || opm === void 0 ? void 0 : opm.operation)) {
67
+ const msg = `no request handler found! for ${method} ${event.path} - cant validate`;
68
+ (0, log_1.error)(msg);
69
+ return (0, api_1.returnCode)(400, msg);
70
+ }
71
+ if (!opm.operation.requestBody && !opm.operation.parameters) {
72
+ if (!!event.body || Object.keys(pathParameters).length > 0) {
73
+ (0, log_1.warn)(`bad req, unexpected params`);
74
+ return (0, api_1.returnCode)(400, 'bad data');
75
+ }
76
+ // no validation necessary
77
+ }
78
+ else {
79
+ try {
80
+ request.params = opm.pathParams;
81
+ (0, log_1.info)('req=', JSON.stringify(request, null, 2));
82
+ const resp = new openapi_request_validator_1.default(Object.assign(Object.assign({}, opm.operation), { schemas: schema.components.schemas })).validateRequest(request);
83
+ if (resp) {
84
+ (0, log_1.warn)('bad request');
85
+ (0, log_1.warn)('opm=', JSON.stringify(opm, null, 2));
86
+ (0, log_1.warn)('resp=', JSON.stringify(resp, null, 2));
87
+ return (0, api_1.returnCode)(400, `error:${(_b = (_a = resp === null || resp === void 0 ? void 0 : resp.errors) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.message}`);
88
+ }
89
+ (0, log_1.debug)(`validated request:`, event.path);
90
+ }
91
+ catch (e) {
92
+ (0, log_1.error)('e=', e, JSON.stringify(opm));
93
+ }
94
+ }
95
+ let userProfile;
96
+ let error;
97
+ const authHeader = ((_c = event.headers) === null || _c === void 0 ? void 0 : _c.Authorization) || ((_d = event.headers) === null || _d === void 0 ? void 0 : _d.authorization);
98
+ if (authorized === true || (authorized === 'optional' && authHeader)) {
99
+ ({ error, userProfile } = yield (0, validations_1.getAndValidateToken)({
100
+ tokenRaw: authHeader,
101
+ COGNITO_USER_POOL_ID,
102
+ }));
103
+ if (error) {
104
+ return error;
105
+ }
106
+ }
107
+ const params = Object.assign(Object.assign({}, (pathParameters || {})), (queryStringParameters || {}));
108
+ const res = yield next({
109
+ params,
110
+ event,
111
+ body: (event.body && JSON.parse(event.body)),
112
+ userProfile,
113
+ });
114
+ return res;
115
+ });
116
+ }
117
+ exports.validateOpenApi = validateOpenApi;
@@ -0,0 +1,11 @@
1
+ import { APIGatewayProxyResult } from 'aws-lambda';
2
+ import { User } from 'analytica.click';
3
+ import { error } from '../../common/helpers/log';
4
+ export declare const getAndValidateToken: ({ tokenRaw, COGNITO_USER_POOL_ID, }: {
5
+ tokenRaw?: string | undefined;
6
+ COGNITO_USER_POOL_ID: string;
7
+ }) => Promise<{
8
+ error?: APIGatewayProxyResult | undefined;
9
+ token?: string | undefined;
10
+ userProfile?: User | undefined;
11
+ }>;
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.getAndValidateToken = void 0;
16
+ const jwks_rsa_1 = __importDefault(require("jwks-rsa"));
17
+ const jsonwebtoken_1 = require("jsonwebtoken");
18
+ const log_1 = require("../../common/helpers/log");
19
+ const api_1 = require("./api");
20
+ let jwksClient;
21
+ const jwtVerify = ({ COGNITO_USER_POOL_ID, token, }) => __awaiter(void 0, void 0, void 0, function* () {
22
+ const jwksUri = `https://cognito-idp.ap-southeast-2.amazonaws.com/${COGNITO_USER_POOL_ID}/.well-known/jwks.json`;
23
+ const issuer = `https://cognito-idp.ap-southeast-2.amazonaws.com/${COGNITO_USER_POOL_ID}`;
24
+ return new Promise((resolve, reject) => {
25
+ (0, jsonwebtoken_1.verify)(token, (header, callback) => {
26
+ if (!jwksClient) {
27
+ const jc = {
28
+ cache: true,
29
+ rateLimit: true,
30
+ jwksRequestsPerMinute: 10,
31
+ jwksUri,
32
+ };
33
+ (0, log_1.info)(`jwksClient config=`, jc);
34
+ jwksClient = (0, jwks_rsa_1.default)(jc);
35
+ }
36
+ jwksClient.getSigningKey(header.kid, (errorV, key) => {
37
+ if (errorV) {
38
+ reject(errorV);
39
+ return;
40
+ }
41
+ const signingKey = (key === null || key === void 0 ? void 0 : key.publicKey) || (key === null || key === void 0 ? void 0 : key.rsaPublicKey) || undefined;
42
+ if (!signingKey) {
43
+ callback('no key');
44
+ }
45
+ else {
46
+ callback(null, signingKey);
47
+ }
48
+ });
49
+ }, {
50
+ issuer,
51
+ algorithms: ['RS256'],
52
+ }, (errorV, decoded) => {
53
+ if (errorV) {
54
+ reject(errorV);
55
+ return;
56
+ }
57
+ resolve(decoded);
58
+ });
59
+ });
60
+ });
61
+ const getAndValidateToken = ({ tokenRaw, COGNITO_USER_POOL_ID, }) => __awaiter(void 0, void 0, void 0, function* () {
62
+ var _a, _b;
63
+ let token = '';
64
+ try {
65
+ if (!tokenRaw) {
66
+ (0, log_1.error)('no auth headers');
67
+ return {
68
+ error: (0, api_1.returnCode)(403, 'auth failed'),
69
+ };
70
+ }
71
+ token = tokenRaw.substr(tokenRaw.indexOf(' ') + 1);
72
+ let subject;
73
+ try {
74
+ yield jwtVerify({ token, COGNITO_USER_POOL_ID });
75
+ const decoded = (0, jsonwebtoken_1.decode)(token);
76
+ (0, log_1.debug)(`decoded=${JSON.stringify(decoded)}`);
77
+ subject = decoded === null || decoded === void 0 ? void 0 : decoded.sub;
78
+ if (!subject) {
79
+ const mess = 'user should have responded with subject (sub) field';
80
+ (0, log_1.error)(mess);
81
+ throw new Error(mess);
82
+ }
83
+ let { picture } = decoded;
84
+ if (((_b = (_a = decoded === null || decoded === void 0 ? void 0 : decoded.identities) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.providerName) === 'Facebook') {
85
+ picture = JSON.parse(decoded.picture).data.url;
86
+ }
87
+ const userId = decoded.email.toLowerCase();
88
+ const userProfile = {
89
+ isAdmin: ['andreigec@hotmail.com', 'andreigec@gmail.com'].includes(userId),
90
+ idJwt: decoded,
91
+ userId,
92
+ nickname: decoded.nickname || decoded['cognito:username'],
93
+ fullname: decoded.name || decoded['cognito:username'],
94
+ picture,
95
+ updatedAt: parseInt(`${decoded.auth_time}000`, 10),
96
+ };
97
+ if (!userProfile || !token || !userProfile.userId) {
98
+ (0, log_1.error)('auth fail');
99
+ return {
100
+ error: (0, api_1.returnCode)(403, 'auth fail'),
101
+ };
102
+ }
103
+ return { token, userProfile };
104
+ }
105
+ catch (e) {
106
+ const ex = e;
107
+ // expiry is too common to log
108
+ if (ex.toString().indexOf('jwt expired') !== -1) {
109
+ (0, log_1.info)(`jwt fail:${e}`);
110
+ }
111
+ throw e;
112
+ }
113
+ }
114
+ catch (e) {
115
+ (0, log_1.error)('auth error', e);
116
+ return {
117
+ error: (0, api_1.returnCode)(403, 'auth fail'),
118
+ };
119
+ }
120
+ });
121
+ exports.getAndValidateToken = getAndValidateToken;
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
10
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
11
  };
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
+ /* eslint-disable prettier/prettier */
13
14
  __exportStar(require("./ui"), exports);
14
15
  __exportStar(require("./common"), exports);
15
16
  __exportStar(require("./api"), exports);
@@ -1,3 +1,3 @@
1
- import { TResource } from "../../../common/helpers/i18n";
1
+ import { TResource } from '../../../common/helpers/i18n';
2
2
  export declare const getstarted: TResource;
3
3
  export declare const login: TResource;
@@ -14,6 +14,7 @@ const cookie_1 = require("./cookie");
14
14
  const debounce_1 = require("./debounce");
15
15
  const callOpenApi = ({ func, apiUrl, overrideAuth, refreshToken, logout, newDefaultApi, }) => __awaiter(void 0, void 0, void 0, function* () {
16
16
  var _a, _b, _c, _d, _e, _f;
17
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
17
18
  let error;
18
19
  let data;
19
20
  const config = {
@@ -45,6 +46,7 @@ const callOpenApi = ({ func, apiUrl, overrideAuth, refreshToken, logout, newDefa
45
46
  throw new Error(JSON.stringify(resp.data) || resp.statusText);
46
47
  }
47
48
  catch (e) {
49
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
48
50
  const ae = e;
49
51
  const status = (_c = ae.response) === null || _c === void 0 ? void 0 : _c.status;
50
52
  const errorMessage = (((_d = ae.response) === null || _d === void 0 ? void 0 : _d.data) ||
@@ -1,6 +1,12 @@
1
1
  import { AxiosResponse } from 'axios';
2
2
  import { AxiosWrapper, User } from 'analytica.click';
3
3
  import { CacheItems } from './routes';
4
+ export declare const setMutexData: ({ key, data, ttlSeconds, }: {
5
+ key: string;
6
+ data: any;
7
+ ttlSeconds: number;
8
+ }) => void;
9
+ export declare const getMutexData: <T>(key: string) => AxiosWrapper<T>;
4
10
  export declare const useOpenApiStore: <T, TDefaultApi>({ func, cacheKey, ttlSeconds, logout, refreshToken, disabled, apiUrl, newDefaultApi, }: {
5
11
  ttlSeconds?: number | undefined;
6
12
  func: (f: TDefaultApi) => Promise<AxiosResponse<T, any>>;
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.setOpenApiCache = exports.useOpenApiStore = void 0;
12
+ exports.setOpenApiCache = exports.useOpenApiStore = exports.getMutexData = exports.setMutexData = void 0;
13
13
  const react_1 = require("react");
14
14
  const mutex_1 = require("./mutex");
15
15
  const mutexData_1 = require("./mutexData");
@@ -36,9 +36,13 @@ const setMutexData = ({ key, data, ttlSeconds = 3600, }) => {
36
36
  };
37
37
  mutexData.setData(key, wrap, ttlSeconds);
38
38
  };
39
+ exports.setMutexData = setMutexData;
39
40
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
40
41
  const getMutexData = (key) => mutexData.getData(key);
41
- function mLock(key, func, ttlSeconds, logout, refreshToken, apiUrl, newDefaultApi) {
42
+ exports.getMutexData = getMutexData;
43
+ function mLock(key, func, ttlSeconds, logout, refreshToken, apiUrl,
44
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
45
+ newDefaultApi) {
42
46
  return __awaiter(this, void 0, void 0, function* () {
43
47
  let unlock;
44
48
  try {
package/package.json CHANGED
@@ -1,32 +1,48 @@
1
1
  {
2
2
  "name": "ag-common",
3
- "version": "0.0.3",
3
+ "version": "0.0.7",
4
4
  "main": "./dist/index.js",
5
5
  "types": "./dist/index.d.ts",
6
+ "author": "Andrei Gec <@andreigec> (https://gec.dev/)",
7
+ "repository": "github:andreigec/ag-common",
8
+ "license": "ISC",
6
9
  "dependencies": {
10
+ "aws-lambda": "1.0.7",
11
+ "styled-components": "5.3.3",
7
12
  "axios": "0.24.0",
8
- "typescript": "4.5.4"
9
- },
10
- "devDependencies": {
11
- "@types/node": "^17.0.5",
12
- "@types/aws-lambda": "8.10.89",
13
- "@types/react": "*",
14
- "@types/react-dom": "*",
15
- "@types/styled-components": "*",
16
- "analytica.click": "*",
17
- "aws-cdk-lib": "*",
13
+ "typescript": "4.5.4",
14
+ "openapi-request-validator": "10.0.0",
15
+ "analytica.click": "0.0.123",
18
16
  "aws-sdk": "2.1048.0",
19
- "constructs": "*",
20
- "eslint": "*",
21
- "react": "*",
22
- "react-dom": "*",
17
+ "aws-cdk-lib": "2.3.0",
18
+ "constructs": "10.0.17",
19
+ "react": "17.0.2",
20
+ "react-dom": "17.0.2",
23
21
  "react-hot-toast": "2.1.1",
24
- "rimraf": "*",
25
- "typescript-styled-plugin": "*"
22
+ "jsonwebtoken": "8.5.1",
23
+ "jwks-rsa": "2.0.5"
26
24
  },
27
- "peerDependencies": {
28
- "aws-lambda": "1.0.7",
29
- "styled-components": "*"
25
+ "devDependencies": {
26
+ "@typescript-eslint/eslint-plugin": "5.8.1",
27
+ "@typescript-eslint/parser": "5.8.1",
28
+ "prettier": "2.5.1",
29
+ "@types/node": "17.0.5",
30
+ "@types/aws-lambda": "8.10.89",
31
+ "@types/react": "17.0.38",
32
+ "@types/react-dom": "17.0.11",
33
+ "@types/styled-components": "5.1.19",
34
+ "eslint": "8.5.0",
35
+ "eslint-config-airbnb-typescript": "16.1.0",
36
+ "eslint-config-prettier": "8.3.0",
37
+ "eslint-config-react-app": "7.0.0",
38
+ "eslint-plugin-import": "2.25.3",
39
+ "eslint-plugin-jsx-a11y": "6.5.1",
40
+ "eslint-plugin-prettier": "4.0.0",
41
+ "eslint-plugin-react": "7.28.0",
42
+ "eslint-plugin-react-hooks": "4.3.0",
43
+ "rimraf": "3.0.2",
44
+ "typescript-styled-plugin": "0.18.2",
45
+ "@types/jsonwebtoken": "8.5.6"
30
46
  },
31
47
  "scripts": {
32
48
  "build": "rimraf dist && tsc",
@@ -35,6 +51,8 @@
35
51
  "start": "tsc --watch"
36
52
  },
37
53
  "files": [
38
- "dist/**/*"
54
+ "dist/**/*",
55
+ "README.md",
56
+ "LICENSE.md"
39
57
  ]
40
58
  }