ag-common 0.0.419 → 0.0.421

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.
Files changed (178) hide show
  1. package/dist/api/helpers/api.js +35 -34
  2. package/dist/api/helpers/aws.js +13 -9
  3. package/dist/api/helpers/cloudfront.js +24 -7
  4. package/dist/api/helpers/dynamo.js +134 -85
  5. package/dist/api/helpers/dynamoInfra.js +19 -14
  6. package/dist/api/helpers/enforceDynamoProvisionCap.js +18 -14
  7. package/dist/api/helpers/index.js +30 -14
  8. package/dist/api/helpers/openApiHelpers.js +37 -34
  9. package/dist/api/helpers/s3.js +126 -81
  10. package/dist/api/helpers/ses.js +28 -9
  11. package/dist/api/helpers/sqs.js +26 -9
  12. package/dist/api/helpers/ssm.js +14 -8
  13. package/dist/api/helpers/sts.js +34 -16
  14. package/dist/api/helpers/validateOpenApi.js +103 -92
  15. package/dist/api/helpers/validations.js +46 -29
  16. package/dist/api/index.js +18 -2
  17. package/dist/api/openapi-prefix.js +38 -25
  18. package/dist/api/types/aws.js +2 -1
  19. package/dist/api/types/index.js +17 -1
  20. package/dist/common/const.js +5 -2
  21. package/dist/common/helpers/array.js +19 -8
  22. package/dist/common/helpers/async.js +28 -10
  23. package/dist/common/helpers/binary.js +10 -5
  24. package/dist/common/helpers/date.js +25 -14
  25. package/dist/common/helpers/email.js +11 -5
  26. package/dist/common/helpers/func.js +7 -3
  27. package/dist/common/helpers/generator.js +24 -9
  28. package/dist/common/helpers/groupBy.js +9 -3
  29. package/dist/common/helpers/hashCode.js +9 -3
  30. package/dist/common/helpers/i18n.js +17 -9
  31. package/dist/common/helpers/index.js +34 -18
  32. package/dist/common/helpers/log.js +28 -16
  33. package/dist/common/helpers/math.js +21 -9
  34. package/dist/common/helpers/memo.js +7 -3
  35. package/dist/common/helpers/object.js +35 -20
  36. package/dist/common/helpers/random.js +10 -4
  37. package/dist/common/helpers/secondsInNearest.js +7 -2
  38. package/dist/common/helpers/sleep.js +5 -1
  39. package/dist/common/helpers/string/base64.js +7 -2
  40. package/dist/common/helpers/string/chunk.js +5 -1
  41. package/dist/common/helpers/string/contains.js +7 -2
  42. package/dist/common/helpers/string/getExtendedStringSegment.js +9 -5
  43. package/dist/common/helpers/string/index.js +26 -10
  44. package/dist/common/helpers/string/json.js +5 -1
  45. package/dist/common/helpers/string/object.js +5 -1
  46. package/dist/common/helpers/string/surround.js +5 -1
  47. package/dist/common/helpers/string/trim.js +7 -2
  48. package/dist/common/helpers/string/truncate.js +5 -1
  49. package/dist/common/helpers/string/url.js +9 -4
  50. package/dist/common/index.js +18 -2
  51. package/dist/index.js +19 -3
  52. package/dist/ui/components/BorderGradient/index.js +25 -18
  53. package/dist/ui/components/Button/index.js +25 -17
  54. package/dist/ui/components/Chevron/index.js +16 -9
  55. package/dist/ui/components/Close/index.js +13 -6
  56. package/dist/ui/components/Confirm/Dialog.js +25 -9
  57. package/dist/ui/components/Confirm/Modal.js +27 -20
  58. package/dist/ui/components/Confirm/index.js +19 -3
  59. package/dist/ui/components/Confirm/types.js +2 -1
  60. package/dist/ui/components/DropdownList/Base.js +64 -33
  61. package/dist/ui/components/DropdownList/Dialog.js +24 -8
  62. package/dist/ui/components/DropdownList/index.js +18 -2
  63. package/dist/ui/components/DropdownList/types.js +2 -1
  64. package/dist/ui/components/FlexColumn/index.js +14 -4
  65. package/dist/ui/components/FlexRow/index.js +14 -4
  66. package/dist/ui/components/HeadersRaw/index.js +27 -20
  67. package/dist/ui/components/HorizontalScrollBar/index.js +34 -6
  68. package/dist/ui/components/Icon/index.js +16 -9
  69. package/dist/ui/components/Image/index.js +28 -10
  70. package/dist/ui/components/InfiniteScroll/index.js +50 -18
  71. package/dist/ui/components/KebabDots/index.js +13 -6
  72. package/dist/ui/components/Loader/index.js +39 -9
  73. package/dist/ui/components/Modal/Dialog.js +23 -7
  74. package/dist/ui/components/Modal/Modal.js +49 -19
  75. package/dist/ui/components/Modal/index.js +19 -3
  76. package/dist/ui/components/Modal/types.js +2 -1
  77. package/dist/ui/components/OpenApiCodeBlock/OpenApiCodeBlock.js +34 -26
  78. package/dist/ui/components/OpenApiCodeBlock/curl/helpers/body.js +19 -12
  79. package/dist/ui/components/OpenApiCodeBlock/curl/helpers/getCurlLines.js +11 -6
  80. package/dist/ui/components/OpenApiCodeBlock/curl/helpers/security.js +15 -8
  81. package/dist/ui/components/OpenApiCodeBlock/curl/index.js +21 -14
  82. package/dist/ui/components/OpenApiCodeBlock/fetch/helpers/call.js +15 -8
  83. package/dist/ui/components/OpenApiCodeBlock/fetch/helpers/getFetchLines.js +8 -3
  84. package/dist/ui/components/OpenApiCodeBlock/fetch/helpers/req.js +34 -27
  85. package/dist/ui/components/OpenApiCodeBlock/fetch/index.js +18 -11
  86. package/dist/ui/components/OpenApiCodeBlock/helpers/common.js +17 -7
  87. package/dist/ui/components/OpenApiCodeBlock/helpers/joinJsx.js +15 -6
  88. package/dist/ui/components/OpenApiCodeBlock/index.js +18 -2
  89. package/dist/ui/components/OpenApiCodeBlock/types.js +2 -1
  90. package/dist/ui/components/PieChart/index.js +18 -11
  91. package/dist/ui/components/ProgressBar/index.js +45 -15
  92. package/dist/ui/components/Prompt/Dialog.js +23 -7
  93. package/dist/ui/components/Prompt/Modal.js +55 -25
  94. package/dist/ui/components/Prompt/index.js +18 -2
  95. package/dist/ui/components/RowOrColumn/index.js +17 -7
  96. package/dist/ui/components/Search/AutoHideSearchBox.js +56 -24
  97. package/dist/ui/components/Search/Base.js +52 -21
  98. package/dist/ui/components/Search/Dialog.js +26 -10
  99. package/dist/ui/components/Search/Inline.js +10 -3
  100. package/dist/ui/components/Search/Modal.js +17 -10
  101. package/dist/ui/components/Search/SearchBox.js +58 -26
  102. package/dist/ui/components/Search/index.js +23 -7
  103. package/dist/ui/components/Search/types.js +2 -1
  104. package/dist/ui/components/Sidebar/index.js +25 -18
  105. package/dist/ui/components/SparkLine/index.js +27 -17
  106. package/dist/ui/components/Table/index.js +22 -15
  107. package/dist/ui/components/TextEdit/CheckboxEdit.js +51 -21
  108. package/dist/ui/components/TextEdit/ColourEdit.js +44 -17
  109. package/dist/ui/components/TextEdit/LengthBox.js +12 -5
  110. package/dist/ui/components/TextEdit/ListboxEdit.js +42 -15
  111. package/dist/ui/components/TextEdit/RadioGroup.js +43 -13
  112. package/dist/ui/components/TextEdit/TextEdit.js +78 -48
  113. package/dist/ui/components/TextEdit/common.js +17 -11
  114. package/dist/ui/components/TextEdit/index.js +22 -6
  115. package/dist/ui/components/TextEdit/types.js +2 -1
  116. package/dist/ui/components/TextWithButton/index.js +40 -10
  117. package/dist/ui/components/TimelineChart/index.js +24 -14
  118. package/dist/ui/components/Toast/Cross.js +16 -9
  119. package/dist/ui/components/Toast/Tick.js +11 -4
  120. package/dist/ui/components/Toast/Warning.js +15 -8
  121. package/dist/ui/components/Toast/base.js +65 -33
  122. package/dist/ui/components/Toast/index.js +18 -2
  123. package/dist/ui/components/Toast/types.js +2 -1
  124. package/dist/ui/components/UserImage/index.js +48 -17
  125. package/dist/ui/components/index.js +46 -30
  126. package/dist/ui/helpers/axiosHelper.js +39 -25
  127. package/dist/ui/helpers/browserHelpers.js +22 -7
  128. package/dist/ui/helpers/callOpenApi/cached.js +37 -18
  129. package/dist/ui/helpers/callOpenApi/direct.js +59 -46
  130. package/dist/ui/helpers/callOpenApi/helpers.js +40 -25
  131. package/dist/ui/helpers/callOpenApi/hook.js +36 -47
  132. package/dist/ui/helpers/callOpenApi/index.js +21 -5
  133. package/dist/ui/helpers/callOpenApi/types.js +2 -1
  134. package/dist/ui/helpers/cognito.js +2 -1
  135. package/dist/ui/helpers/cookie/const.js +5 -2
  136. package/dist/ui/helpers/cookie/get.js +14 -13
  137. package/dist/ui/helpers/cookie/index.js +21 -5
  138. package/dist/ui/helpers/cookie/raw.js +16 -9
  139. package/dist/ui/helpers/cookie/set.js +15 -10
  140. package/dist/ui/helpers/cookie/use.js +16 -23
  141. package/dist/ui/helpers/date.js +15 -10
  142. package/dist/ui/helpers/debounce.js +10 -5
  143. package/dist/ui/helpers/dom.js +13 -6
  144. package/dist/ui/helpers/extractAttributes.js +7 -2
  145. package/dist/ui/helpers/index.js +41 -25
  146. package/dist/ui/helpers/jwt.js +2 -1
  147. package/dist/ui/helpers/plural.js +5 -1
  148. package/dist/ui/helpers/routes.js +24 -17
  149. package/dist/ui/helpers/serviceWorker.js +23 -8
  150. package/dist/ui/helpers/useContextMenu.js +14 -9
  151. package/dist/ui/helpers/useElementAttribute.js +7 -3
  152. package/dist/ui/helpers/useGranularHook.js +10 -5
  153. package/dist/ui/helpers/useInterval.js +12 -8
  154. package/dist/ui/helpers/useLocalStorage.js +32 -24
  155. package/dist/ui/helpers/useLockBodyScroll.js +7 -3
  156. package/dist/ui/helpers/useOnClickOutside.js +12 -7
  157. package/dist/ui/helpers/useOnScroll.js +21 -15
  158. package/dist/ui/helpers/useOverloadPageSearch.js +7 -3
  159. package/dist/ui/helpers/useQueryString.js +20 -14
  160. package/dist/ui/helpers/useResize.js +19 -17
  161. package/dist/ui/helpers/useTimeout.js +9 -5
  162. package/dist/ui/icons/ChevronRight.js +9 -3
  163. package/dist/ui/icons/CrossIcon.js +12 -5
  164. package/dist/ui/icons/Door.js +10 -4
  165. package/dist/ui/icons/HorizontalDots.js +9 -3
  166. package/dist/ui/icons/Magnify.js +10 -3
  167. package/dist/ui/icons/Pencil.js +12 -5
  168. package/dist/ui/icons/Save.js +11 -4
  169. package/dist/ui/icons/Undo.js +12 -5
  170. package/dist/ui/icons/UserOutline.js +9 -3
  171. package/dist/ui/icons/index.js +25 -9
  172. package/dist/ui/index.js +20 -4
  173. package/dist/ui/styles/colours.js +12 -7
  174. package/dist/ui/styles/common.js +22 -14
  175. package/dist/ui/styles/index.js +20 -4
  176. package/dist/ui/styles/media.js +10 -7
  177. package/dist/ui/styles/standaloneStyles.js +16 -10
  178. package/package.json +2 -2
@@ -1,20 +1,26 @@
1
- import { aws_ssm as ssm, Fn } from 'aws-cdk-lib';
2
- import { toBase64 } from '../../common/helpers/string/base64';
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.loadSsmStringList = exports.loadSsmString = exports.saveToSsm = void 0;
4
+ const aws_cdk_lib_1 = require("aws-cdk-lib");
5
+ const base64_1 = require("../../common/helpers/string/base64");
3
6
  /**
4
7
  * save a value to ssm
5
8
  * @param param0
6
9
  */
7
- export const saveToSsm = ({ stack, path, value, }) => {
8
- const name = toBase64(path);
9
- new ssm.StringParameter(stack, name, {
10
+ const saveToSsm = ({ stack, path, value, }) => {
11
+ const name = (0, base64_1.toBase64)(path);
12
+ new aws_cdk_lib_1.aws_ssm.StringParameter(stack, name, {
10
13
  allowedPattern: '.*',
11
14
  description: `${name} (cdk)`,
12
15
  parameterName: path,
13
16
  stringValue: value,
14
- tier: ssm.ParameterTier.STANDARD,
17
+ tier: aws_cdk_lib_1.aws_ssm.ParameterTier.STANDARD,
15
18
  });
16
19
  };
20
+ exports.saveToSsm = saveToSsm;
17
21
  /** load a string from ssm */
18
- export const loadSsmString = ({ stack, path, }) => ssm.StringParameter.valueForStringParameter(stack, path);
22
+ const loadSsmString = ({ stack, path, }) => aws_cdk_lib_1.aws_ssm.StringParameter.valueForStringParameter(stack, path);
23
+ exports.loadSsmString = loadSsmString;
19
24
  /** load a csv from ssm */
20
- export const loadSsmStringList = ({ stack, path, }) => Fn.split(',', loadSsmString({ stack, path }));
25
+ const loadSsmStringList = ({ stack, path, }) => aws_cdk_lib_1.Fn.split(',', (0, exports.loadSsmString)({ stack, path }));
26
+ exports.loadSsmStringList = loadSsmStringList;
@@ -1,21 +1,39 @@
1
- import STS from 'aws-sdk/clients/sts';
2
- import { info } from '../../common/helpers/log';
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.assumeRole = void 0;
16
+ const sts_1 = __importDefault(require("aws-sdk/clients/sts"));
17
+ const log_1 = require("../../common/helpers/log");
3
18
  /**
4
19
  * @param {assumeRoleArn} assume this role arn
5
20
  * @returns {string} assumed accountId
6
21
  */
7
- export async function assumeRole({ assumeRoleArn, region, }) {
8
- const sts = new STS({ region });
9
- info(`assuming:${assumeRoleArn} in region:${region}`);
10
- const data = await sts
11
- .assumeRole({
12
- RoleArn: assumeRoleArn,
13
- RoleSessionName: 'stssession',
14
- })
15
- .promise();
16
- if (data.$response.error) {
17
- throw new Error(JSON.stringify(data.$response.error, null, 2));
18
- }
19
- info(`resp:${data}`);
20
- return data.Credentials;
22
+ function assumeRole({ assumeRoleArn, region, }) {
23
+ return __awaiter(this, void 0, void 0, function* () {
24
+ const sts = new sts_1.default({ region });
25
+ (0, log_1.info)(`assuming:${assumeRoleArn} in region:${region}`);
26
+ const data = yield sts
27
+ .assumeRole({
28
+ RoleArn: assumeRoleArn,
29
+ RoleSessionName: 'stssession',
30
+ })
31
+ .promise();
32
+ if (data.$response.error) {
33
+ throw new Error(JSON.stringify(data.$response.error, null, 2));
34
+ }
35
+ (0, log_1.info)(`resp:${data}`);
36
+ return data.Credentials;
37
+ });
21
38
  }
39
+ exports.assumeRole = assumeRole;
@@ -1,20 +1,36 @@
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;
1
16
  // eslint-disable-next-line import/no-unresolved
2
- import OpenAPIRequestValidator from 'openapi-request-validator';
3
- import { getValidatedLang } from '../../common/helpers/i18n';
4
- import { debug, error as errorF, info, warn } from '../../common/helpers/log';
5
- import { objectKeysToLowerCase, tryJsonParse, } from '../../common/helpers/object';
6
- import { returnCode } from './api';
7
- import { getAndValidateToken } from './validations';
17
+ const openapi_request_validator_1 = __importDefault(require("openapi-request-validator"));
18
+ const i18n_1 = require("../../common/helpers/i18n");
19
+ const log_1 = require("../../common/helpers/log");
20
+ const object_1 = require("../../common/helpers/object");
21
+ const api_1 = require("./api");
22
+ const validations_1 = require("./validations");
8
23
  //
9
24
  const getOperation = ({ path, method, resource, schema, }) => {
25
+ var _a;
10
26
  const resourcePath = Object.keys(schema.paths).find((rp) => rp === resource);
11
27
  if (!resourcePath) {
12
28
  throw new Error('incorrect path');
13
29
  }
14
- const operation = schema.paths[resourcePath]?.[method];
30
+ const operation = (_a = schema.paths[resourcePath]) === null || _a === void 0 ? void 0 : _a[method];
15
31
  if (!operation) {
16
32
  const msg = `no operation found for ${method}/${path}`;
17
- warn(`${msg} ${Object.keys(schema.paths)}`);
33
+ (0, log_1.warn)(`${msg} ${Object.keys(schema.paths)}`);
18
34
  throw new Error(msg);
19
35
  }
20
36
  /*
@@ -24,96 +40,91 @@ const getOperation = ({ path, method, resource, schema, }) => {
24
40
  const re = new RegExp(resourcePath
25
41
  .replace(/\//gim, `\\/`)
26
42
  .replace(/\{(.+?)\}/gim, '(?<$1>[^\\\\]+)'), 'i').exec(path);
27
- const pathParams = re?.groups && JSON.parse(JSON.stringify(re?.groups));
43
+ const pathParams = (re === null || re === void 0 ? void 0 : re.groups) && JSON.parse(JSON.stringify(re === null || re === void 0 ? void 0 : re.groups));
28
44
  return { operation, pathParams };
29
45
  };
30
- export async function validateOpenApi({ event, next, authorized, schema, COGNITO_USER_POOL_ID, jwksRegion = 'ap-southeast-2', getAndValidateTokenOverride, }) {
31
- if (!schema) {
32
- throw new Error('schema undefined!');
33
- }
34
- if (!COGNITO_USER_POOL_ID) {
35
- throw new Error('COGNITO_USER_POOL_ID undefined');
36
- }
37
- const request = {
38
- method: event.httpMethod,
39
- path: event.path,
40
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
41
- params: undefined,
42
- query: event.queryStringParameters,
43
- body: tryJsonParse(event.body, event.body),
44
- headers: objectKeysToLowerCase(event?.headers),
45
- };
46
- const method = event.requestContext.httpMethod.toLowerCase();
47
- const pathParameters = event.pathParameters || {};
48
- const queryStringParameters = event.queryStringParameters || {};
49
- //
50
- const opm = getOperation({
51
- path: event.path,
52
- method,
53
- resource: event.resource,
54
- schema,
55
- });
56
- if (!opm?.operation) {
57
- const msg = `no request handler found! for ${method} ${event.path} - cant validate`;
58
- errorF(msg);
59
- return returnCode(400, msg);
60
- }
61
- if (!opm.operation.requestBody && !opm.operation.parameters) {
62
- if (!!event.body || Object.keys(pathParameters).length > 0) {
63
- warn(`bad req, unexpected params`);
64
- return returnCode(400, 'bad data');
46
+ function validateOpenApi({ event, next, authorized, schema, COGNITO_USER_POOL_ID, jwksRegion = 'ap-southeast-2', getAndValidateTokenOverride, }) {
47
+ var _a, _b, _c, _d, _e, _f, _g;
48
+ return __awaiter(this, void 0, void 0, function* () {
49
+ if (!schema) {
50
+ throw new Error('schema undefined!');
65
51
  }
66
- // no validation necessary
67
- }
68
- else {
69
- try {
70
- request.params = opm.pathParams;
71
- info('req=', JSON.stringify({
72
- ...request,
73
- body: (request.body?.length ?? 0) > 2000
74
- ? '(truncating long body)'
75
- : request.body,
76
- }, null, 2));
77
- const resp = new OpenAPIRequestValidator({
78
- ...opm.operation,
79
- schemas: schema.components.schemas,
80
- }).validateRequest(request);
81
- if (resp) {
82
- warn('bad request');
83
- warn('opm=', JSON.stringify(opm, null, 2));
84
- warn('resp=', JSON.stringify(resp, null, 2));
85
- return returnCode(400, `error:${resp?.errors?.[0]?.message}`);
52
+ if (!COGNITO_USER_POOL_ID) {
53
+ throw new Error('COGNITO_USER_POOL_ID undefined');
54
+ }
55
+ const request = {
56
+ method: event.httpMethod,
57
+ path: event.path,
58
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
59
+ params: undefined,
60
+ query: event.queryStringParameters,
61
+ body: (0, object_1.tryJsonParse)(event.body, event.body),
62
+ headers: (0, object_1.objectKeysToLowerCase)(event === null || event === void 0 ? void 0 : event.headers),
63
+ };
64
+ const method = event.requestContext.httpMethod.toLowerCase();
65
+ const pathParameters = event.pathParameters || {};
66
+ const queryStringParameters = event.queryStringParameters || {};
67
+ //
68
+ const opm = getOperation({
69
+ path: event.path,
70
+ method,
71
+ resource: event.resource,
72
+ schema,
73
+ });
74
+ if (!(opm === null || opm === void 0 ? void 0 : opm.operation)) {
75
+ const msg = `no request handler found! for ${method} ${event.path} - cant validate`;
76
+ (0, log_1.error)(msg);
77
+ return (0, api_1.returnCode)(400, msg);
78
+ }
79
+ if (!opm.operation.requestBody && !opm.operation.parameters) {
80
+ if (!!event.body || Object.keys(pathParameters).length > 0) {
81
+ (0, log_1.warn)(`bad req, unexpected params`);
82
+ return (0, api_1.returnCode)(400, 'bad data');
86
83
  }
87
- debug(`validated request:`, event.path);
84
+ // no validation necessary
88
85
  }
89
- catch (e) {
90
- errorF('e=', e, JSON.stringify(opm));
86
+ else {
87
+ try {
88
+ request.params = opm.pathParams;
89
+ (0, log_1.info)('req=', JSON.stringify(Object.assign(Object.assign({}, request), { body: ((_b = (_a = request.body) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) > 2000
90
+ ? '(truncating long body)'
91
+ : request.body }), null, 2));
92
+ const resp = new openapi_request_validator_1.default(Object.assign(Object.assign({}, opm.operation), { schemas: schema.components.schemas })).validateRequest(request);
93
+ if (resp) {
94
+ (0, log_1.warn)('bad request');
95
+ (0, log_1.warn)('opm=', JSON.stringify(opm, null, 2));
96
+ (0, log_1.warn)('resp=', JSON.stringify(resp, null, 2));
97
+ return (0, api_1.returnCode)(400, `error:${(_d = (_c = resp === null || resp === void 0 ? void 0 : resp.errors) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.message}`);
98
+ }
99
+ (0, log_1.debug)(`validated request:`, event.path);
100
+ }
101
+ catch (e) {
102
+ (0, log_1.error)('e=', e, JSON.stringify(opm));
103
+ }
91
104
  }
92
- }
93
- let userProfile;
94
- let error;
95
- const authHeader = event.headers?.Authorization || event.headers?.authorization;
96
- if (authorized === true || (authorized === 'optional' && authHeader)) {
97
- const vf = getAndValidateTokenOverride ?? getAndValidateToken;
98
- ({ error, userProfile } = await vf({
99
- tokenRaw: authHeader,
100
- COGNITO_USER_POOL_ID,
101
- jwksRegion,
102
- }));
103
- if (error) {
104
- return error;
105
+ let userProfile;
106
+ let error;
107
+ const authHeader = ((_e = event.headers) === null || _e === void 0 ? void 0 : _e.Authorization) || ((_f = event.headers) === null || _f === void 0 ? void 0 : _f.authorization);
108
+ if (authorized === true || (authorized === 'optional' && authHeader)) {
109
+ const vf = getAndValidateTokenOverride !== null && getAndValidateTokenOverride !== void 0 ? getAndValidateTokenOverride : validations_1.getAndValidateToken;
110
+ ({ error, userProfile } = yield vf({
111
+ tokenRaw: authHeader,
112
+ COGNITO_USER_POOL_ID,
113
+ jwksRegion,
114
+ }));
115
+ if (error) {
116
+ return error;
117
+ }
105
118
  }
106
- }
107
- const params = {
108
- ...(pathParameters || {}),
109
- ...(queryStringParameters || {}),
110
- };
111
- const res = await next({
112
- params,
113
- event,
114
- body: tryJsonParse(event.body, event.body),
115
- userProfile,
116
- lang: getValidatedLang(event.headers['x-lang'] ?? ''),
119
+ const params = Object.assign(Object.assign({}, (pathParameters || {})), (queryStringParameters || {}));
120
+ const res = yield next({
121
+ params,
122
+ event,
123
+ body: (0, object_1.tryJsonParse)(event.body, event.body),
124
+ userProfile,
125
+ lang: (0, i18n_1.getValidatedLang)((_g = event.headers['x-lang']) !== null && _g !== void 0 ? _g : ''),
126
+ });
127
+ return res;
117
128
  });
118
- return res;
119
129
  }
130
+ exports.validateOpenApi = validateOpenApi;
@@ -1,13 +1,28 @@
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;
1
16
  /* eslint-disable import/no-unresolved */
2
- import { decode, verify } from 'jsonwebtoken';
17
+ const jsonwebtoken_1 = require("jsonwebtoken");
3
18
  // eslint-disable-next-line import/no-named-as-default
4
- import JwksClient from 'jwks-rsa';
5
- import { debug, error, info } from '../../common/helpers/log';
6
- import { returnCode } from './api';
19
+ const jwks_rsa_1 = __importDefault(require("jwks-rsa"));
20
+ const log_1 = require("../../common/helpers/log");
21
+ const api_1 = require("./api");
7
22
  let jwksClient;
8
- const jwtVerify = async ({ token, jwksUri, issuer, }) => {
23
+ const jwtVerify = ({ token, jwksUri, issuer, }) => __awaiter(void 0, void 0, void 0, function* () {
9
24
  return new Promise((resolve, reject) => {
10
- verify(token, (header, callback) => {
25
+ (0, jsonwebtoken_1.verify)(token, (header, callback) => {
11
26
  if (!jwksClient) {
12
27
  const jc = {
13
28
  cache: true,
@@ -15,20 +30,20 @@ const jwtVerify = async ({ token, jwksUri, issuer, }) => {
15
30
  jwksRequestsPerMinute: 10,
16
31
  jwksUri,
17
32
  };
18
- info(`jwksClient config=`, jc);
19
- jwksClient = JwksClient(jc);
33
+ (0, log_1.info)(`jwksClient config=`, jc);
34
+ jwksClient = (0, jwks_rsa_1.default)(jc);
20
35
  }
21
36
  jwksClient.getSigningKey(header.kid, (errorV, key) => {
22
37
  if (errorV) {
23
38
  const msg = `signing key error. jwks=${jwksUri} iss=${issuer}` + errorV;
24
- error(msg);
39
+ (0, log_1.error)(msg);
25
40
  reject(msg);
26
41
  return;
27
42
  }
28
- const signingKey = key?.publicKey || key?.rsaPublicKey || undefined;
43
+ const signingKey = (key === null || key === void 0 ? void 0 : key.publicKey) || (key === null || key === void 0 ? void 0 : key.rsaPublicKey) || undefined;
29
44
  if (!signingKey) {
30
45
  const msg = `no key error`;
31
- error(msg);
46
+ (0, log_1.error)(msg);
32
47
  reject(msg);
33
48
  }
34
49
  else {
@@ -46,48 +61,49 @@ const jwtVerify = async ({ token, jwksUri, issuer, }) => {
46
61
  resolve(decoded);
47
62
  });
48
63
  });
49
- };
64
+ });
50
65
  /** extracts user details from oauth token */
51
- export const getAndValidateToken = async ({ tokenRaw, jwksRegion = 'ap-southeast-2', COGNITO_USER_POOL_ID, }) => {
66
+ const getAndValidateToken = ({ tokenRaw, jwksRegion = 'ap-southeast-2', COGNITO_USER_POOL_ID, }) => __awaiter(void 0, void 0, void 0, function* () {
67
+ var _a, _b;
52
68
  const jwksUri = `https://cognito-idp.${jwksRegion}.amazonaws.com/${COGNITO_USER_POOL_ID}/.well-known/jwks.json`;
53
69
  const issuer = `https://cognito-idp.${jwksRegion}.amazonaws.com/${COGNITO_USER_POOL_ID}`;
54
70
  let token = '';
55
71
  try {
56
72
  if (!tokenRaw) {
57
73
  const m = 'auth error: no auth headers';
58
- error(m);
74
+ (0, log_1.error)(m);
59
75
  return {
60
- error: returnCode(403, m),
76
+ error: (0, api_1.returnCode)(403, m),
61
77
  };
62
78
  }
63
79
  token = tokenRaw.substring(tokenRaw.indexOf(' ') + 1);
64
80
  if (!token) {
65
81
  const m = 'auth error: no token';
66
- error(m);
82
+ (0, log_1.error)(m);
67
83
  return {
68
- error: returnCode(403, m),
84
+ error: (0, api_1.returnCode)(403, m),
69
85
  };
70
86
  }
71
87
  let subject;
72
88
  try {
73
- await jwtVerify({ token, jwksUri, issuer });
74
- const decoded = decode(token);
75
- debug(`decoded=${JSON.stringify(decoded, null, 2)}`);
89
+ yield jwtVerify({ token, jwksUri, issuer });
90
+ const decoded = (0, jsonwebtoken_1.decode)(token);
91
+ (0, log_1.debug)(`decoded=${JSON.stringify(decoded, null, 2)}`);
76
92
  if (!decoded.email) {
77
93
  const m = 'auth error, no email';
78
- error(m);
94
+ (0, log_1.error)(m);
79
95
  return {
80
- error: returnCode(403, m),
96
+ error: (0, api_1.returnCode)(403, m),
81
97
  };
82
98
  }
83
- subject = decoded?.sub;
99
+ subject = decoded === null || decoded === void 0 ? void 0 : decoded.sub;
84
100
  if (!subject) {
85
101
  const mess = 'user should have responded with subject (sub) field';
86
- error(mess);
102
+ (0, log_1.error)(mess);
87
103
  throw new Error(mess);
88
104
  }
89
105
  let { picture } = decoded;
90
- if (decoded?.identities?.[0]?.providerName === 'Facebook') {
106
+ 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') {
91
107
  picture = JSON.parse(decoded.picture).data.url;
92
108
  }
93
109
  const userId = decoded.email.toLowerCase();
@@ -106,16 +122,17 @@ export const getAndValidateToken = async ({ tokenRaw, jwksRegion = 'ap-southeast
106
122
  const ex = e;
107
123
  // expiry is too common to log
108
124
  if (ex.toString().indexOf('jwt expired') !== -1) {
109
- info(`jwt fail:${e}`);
125
+ (0, log_1.info)(`jwt fail:${e}`);
110
126
  }
111
127
  throw e;
112
128
  }
113
129
  }
114
130
  catch (e) {
115
131
  const m = 'auth error:' + JSON.stringify(e, null, 2);
116
- error(m);
132
+ (0, log_1.error)(m);
117
133
  return {
118
- error: returnCode(403, m),
134
+ error: (0, api_1.returnCode)(403, m),
119
135
  };
120
136
  }
121
- };
137
+ });
138
+ exports.getAndValidateToken = getAndValidateToken;
package/dist/api/index.js CHANGED
@@ -1,2 +1,18 @@
1
- export * from './helpers';
2
- export * from './types';
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./helpers"), exports);
18
+ __exportStar(require("./types"), exports);
@@ -1,4 +1,13 @@
1
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
+ };
2
11
  /* eslint-disable import/no-extraneous-dependencies */
3
12
  /* eslint-disable @typescript-eslint/no-var-requires */
4
13
  /* eslint-disable no-console */
@@ -50,33 +59,37 @@ function cleanSrc() {
50
59
  });
51
60
  }
52
61
  //
53
- async function generateJs() {
54
- try {
55
- console.log('generating openapi ts');
56
- var p = resolvePath('./openapi.yml');
57
- if (!fs.existsSync(p)) {
58
- p = resolvePath('./openapi/index.yml');
59
- process.chdir(resolvePath('./openapi'));
62
+ function generateJs() {
63
+ return __awaiter(this, void 0, void 0, function* () {
64
+ try {
65
+ console.log('generating openapi ts');
66
+ var p = resolvePath('./openapi.yml');
67
+ if (!fs.existsSync(p)) {
68
+ p = resolvePath('./openapi/index.yml');
69
+ process.chdir(resolvePath('./openapi'));
70
+ }
71
+ if (!fs.existsSync(p)) {
72
+ console.error('cant generate swagger, expecting openapi.yml or openapi/index.yml');
73
+ return;
74
+ }
75
+ const yml = load(fs.readFileSync(p, 'utf8'));
76
+ // eslint-disable-next-line
77
+ const schema = yield SwaggerParser.validate(yml);
78
+ const content = `var ret=${JSON.stringify(schema)};\nmodule.exports.default=ret`;
79
+ fs.writeFileSync(resolvePath('./openapi.generated.js'), content);
80
+ console.log('generated');
60
81
  }
61
- if (!fs.existsSync(p)) {
62
- console.error('cant generate swagger, expecting openapi.yml or openapi/index.yml');
63
- return;
82
+ catch (e) {
83
+ // eslint-disable-next-line no-console
84
+ console.log('err=', e);
64
85
  }
65
- const yml = load(fs.readFileSync(p, 'utf8'));
66
- // eslint-disable-next-line
67
- const schema = await SwaggerParser.validate(yml);
68
- const content = `var ret=${JSON.stringify(schema)};\nmodule.exports.default=ret`;
69
- fs.writeFileSync(resolvePath('./openapi.generated.js'), content);
70
- console.log('generated');
71
- }
72
- catch (e) {
73
- // eslint-disable-next-line no-console
74
- console.log('err=', e);
75
- }
86
+ });
76
87
  }
77
- async function run() {
78
- console.log('start openapi fix in ' + cwd);
79
- cleanSrc();
80
- await generateJs();
88
+ function run() {
89
+ return __awaiter(this, void 0, void 0, function* () {
90
+ console.log('start openapi fix in ' + cwd);
91
+ cleanSrc();
92
+ yield generateJs();
93
+ });
81
94
  }
82
95
  void run();
@@ -1 +1,2 @@
1
- export {};
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -1 +1,17 @@
1
- export * from './aws';
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./aws"), exports);
@@ -1,2 +1,5 @@
1
- export const retryHttpCodes = [429, 408, 502, 503, 504];
2
- export const retryHttpMs = 1500;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.retryHttpMs = exports.retryHttpCodes = void 0;
4
+ exports.retryHttpCodes = [429, 408, 502, 503, 504];
5
+ exports.retryHttpMs = 1500;