ag-common 0.0.418 → 0.0.419

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