@middy/ssm 3.0.0-alpha.3 → 3.0.0-alpha.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.
Files changed (3) hide show
  1. package/README.md +26 -16
  2. package/index.js +2 -175
  3. package/package.json +4 -4
package/README.md CHANGED
@@ -1,26 +1,36 @@
1
- # Middy ssm middleware
2
-
3
- <div align="center">
4
- <img alt="Middy logo" src="https://raw.githubusercontent.com/middyjs/middy/main/docs/img/middy-logo.png"/>
5
- </div>
6
-
7
1
  <div align="center">
2
+ <h1>Middy ssm middleware</h1>
3
+ <img alt="Middy logo" src="https://raw.githubusercontent.com/middyjs/middy/main/docs/img/middy-logo.svg"/>
8
4
  <p><strong>SSM (AWS System Manager Parameter) middleware for the middy framework, the stylish Node.js middleware engine for AWS Lambda</strong></p>
9
- </div>
10
-
11
- <div align="center">
12
5
  <p>
13
- <a href="http://badge.fury.io/js/%40middy%2Fssm">
6
+ <a href="https://www.npmjs.com/package/@middy/ssm?activeTab=versions">
14
7
  <img src="https://badge.fury.io/js/%40middy%2Fssm.svg" alt="npm version" style="max-width:100%;">
15
8
  </a>
9
+ <a href="https://packagephobia.com/result?p=@middy/ssm">
10
+ <img src="https://packagephobia.com/badge?p=@middy/ssm" alt="npm install size" style="max-width:100%;">
11
+ </a>
12
+ <a href="https://github.com/middyjs/middy/actions">
13
+ <img src="https://github.com/middyjs/middy/workflows/Tests/badge.svg" alt="GitHub Actions test status badge" style="max-width:100%;">
14
+ </a>
15
+ <br/>
16
+ <a href="https://standardjs.com/">
17
+ <img src="https://img.shields.io/badge/code_style-standard-brightgreen.svg" alt="Standard Code Style" style="max-width:100%;">
18
+ </a>
16
19
  <a href="https://snyk.io/test/github/middyjs/middy">
17
20
  <img src="https://snyk.io/test/github/middyjs/middy/badge.svg" alt="Known Vulnerabilities" data-canonical-src="https://snyk.io/test/github/middyjs/middy" style="max-width:100%;">
18
21
  </a>
19
- <a href="https://standardjs.com/">
20
- <img src="https://img.shields.io/badge/code_style-standard-brightgreen.svg" alt="Standard Code Style" style="max-width:100%;">
22
+ <a href="https://lgtm.com/projects/g/middyjs/middy/context:javascript">
23
+ <img src="https://img.shields.io/lgtm/grade/javascript/g/middyjs/middy.svg?logo=lgtm&logoWidth=18" alt="Language grade: JavaScript" style="max-width:100%;">
24
+ </a>
25
+ <a href="https://bestpractices.coreinfrastructure.org/projects/5280">
26
+ <img src="https://bestpractices.coreinfrastructure.org/projects/5280/badge" alt="Core Infrastructure Initiative (CII) Best Practices" style="max-width:100%;">
21
27
  </a>
28
+ <br/>
22
29
  <a href="https://gitter.im/middyjs/Lobby">
23
- <img src="https://badges.gitter.im/gitterHQ/gitter.svg" alt="Chat on Gitter" style="max-width:100%;">
30
+ <img src="https://badges.gitter.im/gitterHQ/gitter.svg" alt="Chat on Gitter" style="max-width:100%;">
31
+ </a>
32
+ <a href="https://stackoverflow.com/questions/tagged/middy?sort=Newest&uqlId=35052">
33
+ <img src="https://img.shields.io/badge/StackOverflow-[middy]-yellow" alt="Ask questions on StackOverflow" style="max-width:100%;">
24
34
  </a>
25
35
  </p>
26
36
  </div>
@@ -48,9 +58,9 @@ npm install --save @middy/ssm
48
58
  ## Options
49
59
 
50
60
  - `AwsClient` (object) (default `AWS.SSM`): AWS.SSM class constructor (e.g. that has been instrumented with AWS X-Ray). Must be from `aws-sdk` v2.
51
- - `awsClientOptions` (object) (optional): Options to pass to AWS.SSM class constructor.
52
- - `awsClientAssumeRole` (string) (optional): Internal key where role tokens are stored. See [@middy/sts](/packages/sts/README.md) on to set this.
53
- - `awsClientCapture` (function) (optional): Enable AWS X-Ray by passing `captureAWSClient` from `aws-xray-sdk` in.
61
+ - `awsClientOptions` (object) (default `undefined`): Options to pass to AWS.SSM class constructor.
62
+ - `awsClientAssumeRole` (string) (default `undefined`): Internal key where role tokens are stored. See [@middy/sts](/packages/sts/README.md) on to set this.
63
+ - `awsClientCapture` (function) (default `undefined`): Enable AWS X-Ray by passing `captureAWSClient` from `aws-xray-sdk` in.
54
64
  - `fetchData` (object) (required): Mapping of internal key name to API request parameter `Names`/`Path`. `SecureString` are automatically decrypted.
55
65
  - `disablePrefetch` (boolean) (default `false`): On cold start requests will trigger early if they can. Setting `awsClientAssumeRole` disables prefetch.
56
66
  - `cacheKey` (string) (default `ssm`): Cache key for the fetched data responses. Must be unique across all middleware.
package/index.js CHANGED
@@ -1,176 +1,3 @@
1
- import {
2
- canPrefetch,
3
- createPrefetchClient,
4
- createClient,
5
- processCache,
6
- getCache,
7
- modifyCache,
8
- jsonSafeParse,
9
- getInternal,
10
- sanitizeKey
11
- } from '@middy/util'
12
- import SSM from 'aws-sdk/clients/ssm.js' // v2
13
- // import { SSM } from '@aws-sdk/client-ssm' // v3
1
+ import{canPrefetch,createPrefetchClient,createClient,processCache,getCache,modifyCache,jsonSafeParse,getInternal,sanitizeKey}from'@middy/util';import SSM from'aws-sdk/clients/ssm.js';const awsRequestLimit=10;const defaults={AwsClient:SSM,awsClientOptions:{},awsClientAssumeRole:undefined,awsClientCapture:undefined,fetchData:{},disablePrefetch:false,cacheKey:'ssm',cacheExpiry:-1,setToContext:false};const ssmMiddleware=(opts={})=>{const options={...defaults,...opts};const fetch=(request,cachedValues)=>{return{...fetchSingle(request,cachedValues),...fetchByPath(request,cachedValues)}};const fetchSingle=(request,cachedValues={})=>{const values={};let batchReq=null;let batchInternalKeys=[];let batchFetchKeys=[];const internalKeys=Object.keys(options.fetchData);const fetchKeys=Object.values(options.fetchData);for(const[idx,internalKey2]of internalKeys.entries()){if(cachedValues[internalKey2])continue;const fetchKey1=options.fetchData[internalKey2];if(fetchKey1.substr(-1)==='/')continue;batchInternalKeys.push(internalKey2);batchFetchKeys.push(fetchKey1);if((!idx||(idx+1)%awsRequestLimit!==0)&&!(idx+1===internalKeys.length)){continue}batchReq=client.getParameters({Names:batchFetchKeys,WithDecryption:true}).promise().then(resp=>{return Object.assign(...(resp.InvalidParameters??[]).map(fetchKey=>{return{[fetchKey]:new Promise(()=>{const internalKey=internalKeys[fetchKeys.indexOf(fetchKey)];const value=getCache(options.cacheKey).value??{};value[internalKey]=undefined;modifyCache(options.cacheKey,value);throw new Error('[ssm] InvalidParameter '+fetchKey)})}}),...(resp.Parameters??[]).map(param=>{return{[param.Name]:parseValue(param)}}))}).catch(e=>{const value=getCache(options.cacheKey).value??{};value[internalKey2]=undefined;modifyCache(options.cacheKey,value);throw e});for(const internalKey1 of batchInternalKeys){values[internalKey1]=batchReq.then(params=>{return params[options.fetchData[internalKey1]]})}batchInternalKeys=[];batchFetchKeys=[];batchReq=null}return values};const fetchByPath=(request,cachedValues={})=>{const values={};for(const internalKey in options.fetchData){if(cachedValues[internalKey])continue;const fetchKey=options.fetchData[internalKey];if(fetchKey.substr(-1)!=='/')continue;values[internalKey]=fetchPath(fetchKey).catch(e=>{const value=getCache(options.cacheKey).value??{};value[internalKey]=undefined;modifyCache(options.cacheKey,value);throw e})}return values};const fetchPath=(path,nextToken,values={})=>{return client.getParametersByPath({Path:path,NextToken:nextToken,Recursive:true,WithDecryption:true}).promise().then(resp=>{Object.assign(values,...resp.Parameters.map(param=>{return{[sanitizeKey(param.Name.replace(path,''))]:parseValue(param)}}));if(resp.NextToken)return fetchPath(path,resp.NextToken,values);return values})};const parseValue=param=>{if(param.Type==='StringList'){return param.Value.split(',')}return jsonSafeParse(param.Value)};let prefetch,client;if(canPrefetch(options)){client=createPrefetchClient(options);prefetch=processCache(options,fetch)}const ssmMiddlewareBefore=async request=>{if(!client){client=await createClient(options,request)}const{value}=prefetch??processCache(options,fetch,request);Object.assign(request.internal,value);if(options.setToContext){const data=await getInternal(Object.keys(options.fetchData),request);Object.assign(request.context,data)}prefetch=null};return{before:ssmMiddlewareBefore}};export default ssmMiddleware
14
2
 
15
- const awsRequestLimit = 10
16
- const defaults = {
17
- AwsClient: SSM, // Allow for XRay
18
- awsClientOptions: {},
19
- awsClientAssumeRole: undefined,
20
- awsClientCapture: undefined,
21
- fetchData: {}, // { contextKey: fetchKey, contextPrefix: fetchPath/ }
22
- disablePrefetch: false,
23
- cacheKey: 'ssm',
24
- cacheExpiry: -1,
25
- setToContext: false
26
- }
27
-
28
- const ssmMiddleware = (opts = {}) => {
29
- const options = { ...defaults, ...opts }
30
-
31
- const fetch = (request, cachedValues) => {
32
- return {
33
- ...fetchSingle(request, cachedValues),
34
- ...fetchByPath(request, cachedValues)
35
- }
36
- }
37
-
38
- const fetchSingle = (request, cachedValues = {}) => {
39
- const values = {}
40
- let batchReq = null
41
- let batchInternalKeys = []
42
- let batchFetchKeys = []
43
-
44
- const internalKeys = Object.keys(options.fetchData)
45
- const fetchKeys = Object.values(options.fetchData)
46
- for (const [idx, internalKey] of internalKeys.entries()) {
47
- if (cachedValues[internalKey]) continue
48
- const fetchKey = options.fetchData[internalKey]
49
- if (fetchKey.substr(-1) === '/') continue // Skip path passed in
50
- batchInternalKeys.push(internalKey)
51
- batchFetchKeys.push(fetchKey)
52
- // from the first to the batch size skip, unless it's the last entry
53
- if (
54
- (!idx || (idx + 1) % awsRequestLimit !== 0) &&
55
- !(idx + 1 === internalKeys.length)
56
- ) {
57
- continue
58
- }
59
-
60
- batchReq = client
61
- .getParameters({ Names: batchFetchKeys, WithDecryption: true })
62
- .promise() // Required for aws-sdk v2
63
- .then((resp) => {
64
- // Don't sanitize key, mapped to set value in options
65
- return Object.assign(
66
- ...(resp.InvalidParameters ?? []).map((fetchKey) => {
67
- return {
68
- [fetchKey]: new Promise(() => {
69
- const internalKey = internalKeys[fetchKeys.indexOf(fetchKey)]
70
- const value = getCache(options.cacheKey).value ?? {}
71
- value[internalKey] = undefined
72
- modifyCache(options.cacheKey, value)
73
- throw new Error('ssm.InvalidParameter ' + fetchKey)
74
- })
75
- }
76
- }),
77
- ...(resp.Parameters ?? []).map((param) => {
78
- return { [param.Name]: parseValue(param) }
79
- })
80
- )
81
- })
82
- .catch((e) => {
83
- const value = getCache(options.cacheKey).value ?? {}
84
- value[internalKey] = undefined
85
- modifyCache(options.cacheKey, value)
86
- throw e
87
- })
88
-
89
- for (const internalKey of batchInternalKeys) {
90
- values[internalKey] = batchReq.then((params) => {
91
- return params[options.fetchData[internalKey]]
92
- })
93
- }
94
-
95
- batchInternalKeys = []
96
- batchFetchKeys = []
97
- batchReq = null
98
- }
99
-
100
- return values
101
- }
102
-
103
- const fetchByPath = (request, cachedValues = {}) => {
104
- const values = {}
105
- for (const internalKey in options.fetchData) {
106
- if (cachedValues[internalKey]) continue
107
- const fetchKey = options.fetchData[internalKey]
108
- if (fetchKey.substr(-1) !== '/') continue // Skip not path passed in
109
- values[internalKey] = fetchPath(fetchKey).catch((e) => {
110
- const value = getCache(options.cacheKey).value ?? {}
111
- value[internalKey] = undefined
112
- modifyCache(options.cacheKey, value)
113
- throw e
114
- })
115
- }
116
- return values
117
- }
118
-
119
- const fetchPath = (path, nextToken, values = {}) => {
120
- return client
121
- .getParametersByPath({
122
- Path: path,
123
- NextToken: nextToken,
124
- Recursive: true,
125
- WithDecryption: true
126
- })
127
- .promise() // Required for aws-sdk v2
128
- .then((resp) => {
129
- Object.assign(
130
- values,
131
- ...resp.Parameters.map((param) => {
132
- return {
133
- [sanitizeKey(param.Name.replace(path, ''))]: parseValue(param)
134
- }
135
- })
136
- )
137
- if (resp.NextToken) return fetchPath(path, resp.NextToken, values)
138
- return values
139
- })
140
- }
141
-
142
- const parseValue = (param) => {
143
- if (param.Type === 'StringList') {
144
- return param.Value.split(',')
145
- }
146
- return jsonSafeParse(param.Value)
147
- }
148
-
149
- let prefetch, client
150
- if (canPrefetch(options)) {
151
- client = createPrefetchClient(options)
152
- prefetch = processCache(options, fetch)
153
- }
154
-
155
- const ssmMiddlewareBefore = async (request) => {
156
- if (!client) {
157
- client = await createClient(options, request)
158
- }
159
-
160
- const { value } = prefetch ?? processCache(options, fetch, request)
161
-
162
- Object.assign(request.internal, value)
163
-
164
- if (options.setToContext) {
165
- const data = await getInternal(Object.keys(options.fetchData), request)
166
- Object.assign(request.context, data)
167
- }
168
-
169
- prefetch = null
170
- }
171
-
172
- return {
173
- before: ssmMiddlewareBefore
174
- }
175
- }
176
- export default ssmMiddleware
3
+ //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@middy/ssm",
3
- "version": "3.0.0-alpha.3",
3
+ "version": "3.0.0-alpha.7",
4
4
  "description": "SSM (EC2 Systems Manager) parameters middleware for the middy framework",
5
5
  "type": "module",
6
6
  "engines": {
@@ -48,12 +48,12 @@
48
48
  },
49
49
  "homepage": "https://github.com/middyjs/middy#readme",
50
50
  "dependencies": {
51
- "@middy/util": "^3.0.0-alpha.3"
51
+ "@middy/util": "^3.0.0-alpha.7"
52
52
  },
53
53
  "devDependencies": {
54
- "@middy/core": "^3.0.0-alpha.3",
54
+ "@middy/core": "^3.0.0-alpha.7",
55
55
  "aws-sdk": "^2.939.0",
56
56
  "aws-xray-sdk": "^3.3.3"
57
57
  },
58
- "gitHead": "1441158711580313765e6d156046ef0fade0d156"
58
+ "gitHead": "5cef39ebe49c201f97d71bb0680004de4b82cb91"
59
59
  }