@mbc-cqrs-serverless/cli 1.3.3 → 1.3.5

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.
@@ -5,7 +5,7 @@
5
5
  "main": "index.js",
6
6
  "scripts": {
7
7
  "postinstall": "patch-package",
8
- "dev": "HOST=0.0.0.0 npx cognito-local",
8
+ "dev": "sh ./start.sh",
9
9
  "test": "echo \"Error: no test specified\" && exit 1"
10
10
  },
11
11
  "author": "",
@@ -17,6 +17,7 @@
17
17
  "overrides": {
18
18
  "cognito-local": {
19
19
  "jsonwebtoken": "^9.0.0"
20
- }
20
+ },
21
+ "uuid": "^11.1.1"
21
22
  }
22
23
  }
@@ -0,0 +1,46 @@
1
+ #!/bin/sh
2
+ set -e
3
+
4
+ # cognito-local derives the JWT `iss` claim from TokenConfig.IssuerDomain
5
+ # (default http://localhost:9229) in .cognito/config.json, independent of the
6
+ # listen port. To let the port be configured via LOCAL_COGNITO_PORT, we listen
7
+ # on $PORT and write a matching IssuerDomain so the emitted `iss` and the
8
+ # serverless authorizer's issuerUrl stay consistent (both http://localhost:$PORT).
9
+ #
10
+ # The config is merged (not overwritten) so any other cognito-local defaults or
11
+ # user-provided settings in .cognito/config.json are preserved.
12
+
13
+ PORT="${PORT:-9229}"
14
+ CONFIG_DIR="/app/.cognito"
15
+ CONFIG_FILE="${CONFIG_DIR}/config.json"
16
+
17
+ mkdir -p "${CONFIG_DIR}"
18
+
19
+ PORT="${PORT}" CONFIG_FILE="${CONFIG_FILE}" node -e '
20
+ const fs = require("fs");
21
+ const file = process.env.CONFIG_FILE;
22
+ const port = process.env.PORT;
23
+ let config = {};
24
+ try {
25
+ config = JSON.parse(fs.readFileSync(file, "utf8"));
26
+ } catch (e) {
27
+ if (e.code !== "ENOENT") {
28
+ // The file exists but could not be read/parsed (corrupted, permissions,
29
+ // manual edit mistake). Do NOT silently reset it — that would drop any
30
+ // other cognito-local settings the developer added. Fail fast instead.
31
+ console.error(
32
+ `[cognito-local] Failed to read ${file}: ${e.message}. ` +
33
+ "Refusing to overwrite it — fix or delete the file and retry.",
34
+ );
35
+ process.exit(1);
36
+ }
37
+ // ENOENT: first run, no config yet — start from an empty object.
38
+ }
39
+ config.TokenConfig = Object.assign({}, config.TokenConfig, {
40
+ IssuerDomain: `http://localhost:${port}`,
41
+ });
42
+ fs.writeFileSync(file, JSON.stringify(config, null, 2));
43
+ console.log(`[cognito-local] IssuerDomain set to http://localhost:${port}`);
44
+ '
45
+
46
+ exec env HOST=0.0.0.0 PORT="${PORT}" npx cognito-local
@@ -60,7 +60,6 @@ services:
60
60
  image: localstack/localstack
61
61
  ports:
62
62
  - '${LOCAL_S3_PORT:-4566}:4566'
63
- - '4510-4559:4510-4559'
64
63
  environment:
65
64
  - SERVICES=s3
66
65
  - AWS_DEFAULT_REGION=ap-northeast-1
@@ -85,7 +84,12 @@ services:
85
84
  build:
86
85
  context: ./cognito-local
87
86
  dockerfile: Dockerfile
87
+ environment:
88
+ # cognito-local listens on $PORT and emits JWT `iss` as http://localhost:$PORT
89
+ # (see cognito-local/start.sh). Host and container use the same port so the
90
+ # `iss` claim stays reachable from the serverless-offline authorizer.
91
+ - PORT=${LOCAL_COGNITO_PORT:-9229}
88
92
  ports:
89
- - ${LOCAL_COGNITO_PORT:-9229}:9229
93
+ - ${LOCAL_COGNITO_PORT:-9229}:${LOCAL_COGNITO_PORT:-9229}
90
94
  volumes:
91
95
  - ./docker-data/.cognito:/app/.cognito
@@ -11,15 +11,18 @@ Get-Content .env | ForEach-Object {
11
11
  }
12
12
  }
13
13
 
14
+ # Get S3 port from environment variable with default
15
+ $s3Port = if ($env:LOCAL_S3_PORT) { $env:LOCAL_S3_PORT } else { "4566" }
16
+
14
17
  Write-Host "======= check if S3 bucket exists ======="
15
- $bucketExists = aws --endpoint-url=http://localhost:4566 s3 ls | Select-String $env:S3_BUCKET_NAME
18
+ $bucketExists = aws --endpoint-url=http://localhost:$s3Port s3 ls | Select-String $env:S3_BUCKET_NAME
16
19
 
17
20
  if (-not $bucketExists) {
18
21
  Write-Host "Bucket $env:S3_BUCKET_NAME does not exist. Creating it..."
19
- aws --endpoint-url=http://localhost:4566 s3 mb "s3://$env:S3_BUCKET_NAME"
22
+ aws --endpoint-url=http://localhost:$s3Port s3 mb "s3://$env:S3_BUCKET_NAME"
20
23
  } else {
21
24
  Write-Host "Bucket $env:S3_BUCKET_NAME already exists."
22
25
  }
23
26
 
24
27
  Write-Host "======= list S3 buckets ======="
25
- aws --endpoint-url=http://localhost:4566 s3 ls
28
+ aws --endpoint-url=http://localhost:$s3Port s3 ls
@@ -5,15 +5,19 @@ if [ -f .env ]; then
5
5
  export $(echo $(cat .env | sed 's/#.*//g' | xargs) | envsubst)
6
6
  fi
7
7
 
8
+ # Get S3 port from environment variable with default
9
+ S3_PORT="${LOCAL_S3_PORT:-4566}"
10
+ S3_ENDPOINT_URL="http://localhost:${S3_PORT}"
11
+
8
12
  echo "======= check if S3 bucket exists ======="
9
- bucket_exists=$(aws --endpoint-url=http://localhost:4566 s3 ls | grep "$S3_BUCKET_NAME" | wc -l)
13
+ bucket_exists=$(aws --endpoint-url=${S3_ENDPOINT_URL} s3 ls | grep "$S3_BUCKET_NAME" | wc -l)
10
14
 
11
15
  if [ "$bucket_exists" -eq 0 ]; then
12
16
  echo "Bucket $S3_BUCKET_NAME does not exist. Creating it..."
13
- aws --endpoint-url=http://localhost:4566 s3 mb s3://$S3_BUCKET_NAME
17
+ aws --endpoint-url=${S3_ENDPOINT_URL} s3 mb s3://$S3_BUCKET_NAME
14
18
  else
15
19
  echo "Bucket $S3_BUCKET_NAME already exists."
16
20
  fi
17
21
 
18
22
  echo "======= list S3 buckets ======="
19
- aws --endpoint-url=http://localhost:4566 s3 ls
23
+ aws --endpoint-url=${S3_ENDPOINT_URL} s3 ls
@@ -84,7 +84,8 @@ while ($true) {
84
84
  }
85
85
  }
86
86
 
87
- # Wait for serverless to start
87
+ # Wait for serverless to start (cold start compiles TS and initializes many
88
+ # plugins, so allow a generous timeout to avoid failing the local startup flow)
88
89
  $start = Get-Date
89
90
  while ($true) {
90
91
  $elapsed = (New-TimeSpan -Start $start).TotalSeconds
@@ -117,6 +118,98 @@ while ($true) {
117
118
  }
118
119
 
119
120
 
121
+ # Register Step Functions state machines before triggering streams
122
+ $sfnPort = if ($env:LOCAL_SFN_PORT) { $env:LOCAL_SFN_PORT } else { "8083" }
123
+ $sfnEndpoint = "http://localhost:$sfnPort"
124
+
125
+ # Wait for Step Functions Local to accept connections before registering, so a
126
+ # not-yet-ready endpoint (the exact race this block fixes) does not cause silent
127
+ # registration failures.
128
+ $sfnStart = Get-Date
129
+ while ($true) {
130
+ $sfnElapsed = ((Get-Date) - $sfnStart).TotalSeconds
131
+ if ($sfnElapsed -gt 30) {
132
+ Write-Host "Timeout waiting for Step Functions Local at $sfnEndpoint"
133
+ exit 1
134
+ }
135
+ Write-Host "Check health Step Functions Local"
136
+ aws stepfunctions list-state-machines --endpoint-url $sfnEndpoint --region ap-northeast-1 *> $null
137
+ if ($LASTEXITCODE -eq 0) {
138
+ Write-Host "Step Functions Local is ACTIVE"
139
+ break
140
+ }
141
+ Write-Host "Step Functions Local is not ACTIVE"
142
+ Start-Sleep -Seconds 1
143
+ }
144
+
145
+ Write-Host "Registering Step Functions state machines..."
146
+
147
+ # Extract state machine names and definitions from serverless.yml using Node.js
148
+ $nodeScript = @"
149
+ const fs = require('fs');
150
+ const yaml = require('js-yaml');
151
+ let content = fs.readFileSync('./infra-local/serverless.yml', 'utf8');
152
+ content = content.replace(/\`$\{[^}]+\}/g, 'PLACEHOLDER');
153
+ const data = yaml.load(content);
154
+ const sms = (data.stepFunctions || {}).stateMachines || {};
155
+ const result = [];
156
+ for (const [key, sm] of Object.entries(sms)) {
157
+ result.push({ name: sm.name || key, definition: JSON.stringify(sm.definition) });
158
+ }
159
+ console.log(JSON.stringify(result));
160
+ "@
161
+
162
+ # Fail fast if extraction fails (e.g. js-yaml missing) so registration is not
163
+ # silently skipped and later surfaced only as repeated runtime warnings.
164
+ $nodeOutput = node -e $nodeScript
165
+ if ($LASTEXITCODE -ne 0) {
166
+ Write-Host "Failed to extract state machines from serverless.yml (is js-yaml installed?)"
167
+ exit 1
168
+ }
169
+ $stateMachines = $nodeOutput | ConvertFrom-Json
170
+
171
+ foreach ($sm in $stateMachines) {
172
+ $smName = $sm.name
173
+ $smDefinition = $sm.definition
174
+ Write-Host "Checking state machine: $smName"
175
+ # stderr discarded and success decided by $LASTEXITCODE (not string-matching
176
+ # the output) so a CLI error is not mistaken for an existing state machine.
177
+ $existing = aws stepfunctions list-state-machines `
178
+ --endpoint-url $sfnEndpoint `
179
+ --region ap-northeast-1 `
180
+ --query "stateMachines[?name=='$smName'].name" `
181
+ --output text 2>$null
182
+
183
+ if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($existing)) {
184
+ Write-Host "Creating state machine: $smName"
185
+ # Escape embedded double quotes before passing the JSON definition to
186
+ # aws.exe (same pattern as the put-item call below); native-command
187
+ # failures are detected via $LASTEXITCODE, not try/catch, which does not
188
+ # trigger on non-zero exit of external executables.
189
+ $escapedDefinition = $smDefinition -replace '"', '\"'
190
+ # The serverless-step-functions-local plugin also auto-registers state
191
+ # machines on offline:start:init; this block is a fallback for the race
192
+ # where Step Functions Local starts after that hook runs. A benign
193
+ # "already exists" is treated as success; only a real failure aborts.
194
+ $createOut = aws stepfunctions create-state-machine `
195
+ --endpoint-url $sfnEndpoint `
196
+ --region ap-northeast-1 `
197
+ --name $smName `
198
+ --role-arn "arn:aws:iam::101010101010:role/DummyRole" `
199
+ --definition $escapedDefinition 2>&1 | Out-String
200
+ if ($LASTEXITCODE -eq 0) {
201
+ Write-Host "Created $smName"
202
+ } elseif ($createOut -match "already exists|StateMachineAlreadyExists") {
203
+ Write-Host "State machine $smName already exists"
204
+ } else {
205
+ Write-Host "Failed to create ${smName}: $createOut"
206
+ exit 1
207
+ }
208
+ } else {
209
+ Write-Host "State machine $smName already exists"
210
+ }
211
+ }
212
+
120
213
  # Trigger command stream
121
214
  $timestamp = [math]::Round((Get-Date).Subtract((Get-Date "01/01/1970")).TotalSeconds)
122
215
  foreach ($table in $tables) {
@@ -141,6 +234,6 @@ foreach ($table in $tables) {
141
234
  # Trigger tasks stream
142
235
  Write-Host "Send a command to trigger command stream tasks"
143
236
  $command = @"
144
- aws dynamodb put-item --endpoint $endpoint --table-name "$tablePrefix-tasks" --item '{\"input\":{\"M\":{}},\"sk\":{\"S\":\"$timestamp\"},\"pk\":{\"S\":\"test\"}}'
237
+ aws dynamodb put-item --endpoint $endpoint --table-name "$tablePrefix-tasks" --item '{\"input\":{\"M\":{\"action\":{\"S\":\"trigger\"}}},\"sk\":{\"S\":\"$timestamp\"},\"pk\":{\"S\":\"test\"}}'
145
238
  "@
146
239
  Invoke-Expression $command
@@ -73,12 +73,13 @@ while true; do
73
73
  fi
74
74
  done
75
75
 
76
- # Wait serverless start
76
+ # Wait serverless start (cold start compiles TS and initializes many plugins,
77
+ # so allow a generous timeout to avoid failing the local startup flow)
77
78
  start=$(date +%s)
78
79
  while true; do
79
80
 
80
81
  elapsed=$(($(date +%s) - ${start}))
81
- if [[ ${elapsed} -gt 10 ]]; then
82
+ if [[ ${elapsed} -gt 100 ]]; then
82
83
  echo "Timeout"
83
84
  exit 1
84
85
  fi
@@ -95,6 +96,91 @@ while true; do
95
96
  fi
96
97
  done
97
98
 
99
+ # Register Step Functions state machines before triggering streams
100
+ SFN_PORT="${LOCAL_SFN_PORT:-8083}"
101
+ SFN_ENDPOINT="http://localhost:${SFN_PORT}"
102
+
103
+ # Wait for Step Functions Local to accept connections before registering, so a
104
+ # not-yet-ready endpoint (the exact race this block fixes) does not cause silent
105
+ # registration failures.
106
+ start=$(date +%s)
107
+ while true; do
108
+ elapsed=$(($(date +%s) - ${start}))
109
+ if [[ ${elapsed} -gt 30 ]]; then
110
+ echo "Timeout waiting for Step Functions Local at ${SFN_ENDPOINT}"
111
+ exit 1
112
+ fi
113
+ echo "Check health Step Functions Local"
114
+ if aws stepfunctions list-state-machines \
115
+ --endpoint-url ${SFN_ENDPOINT} \
116
+ --region ap-northeast-1 >/dev/null 2>&1; then
117
+ echo "Step Functions Local is ACTIVE"
118
+ break
119
+ fi
120
+ echo "Step Functions Local is not ACTIVE"
121
+ sleep 1
122
+ done
123
+
124
+ echo "Registering Step Functions state machines..."
125
+
126
+ # Extract state machine names and definitions from serverless.yml using Node.js.
127
+ # Fail fast if extraction fails (e.g. js-yaml missing) so registration is not
128
+ # silently skipped and later surfaced only as repeated runtime warnings.
129
+ sm_data=$(node -e "
130
+ const fs = require('fs');
131
+ const yaml = require('js-yaml');
132
+ let content = fs.readFileSync('./infra-local/serverless.yml', 'utf8');
133
+ // Replace Serverless Framework variable syntax to avoid YAML parse errors
134
+ content = content.replace(/\\\$\{[^}]+\}/g, 'PLACEHOLDER');
135
+ const data = yaml.load(content);
136
+ const sms = (data.stepFunctions || {}).stateMachines || {};
137
+ for (const [key, sm] of Object.entries(sms)) {
138
+ const name = sm.name || key;
139
+ const definition = JSON.stringify(sm.definition);
140
+ console.log(name + '\t' + definition);
141
+ }
142
+ ")
143
+ if [ $? -ne 0 ]; then
144
+ echo "Failed to extract state machines from serverless.yml (is js-yaml installed?)"
145
+ exit 1
146
+ fi
147
+
148
+ # A here-string (not a pipe) keeps the loop in the current shell so an "exit"
149
+ # on a failed create actually aborts the script before triggering streams.
150
+ while IFS=$'\t' read -r sm_name sm_definition; do
151
+ [ -z "${sm_name}" ] && continue
152
+ echo "Checking state machine: ${sm_name}"
153
+ # stderr is discarded (not captured) so a connection error is not mistaken
154
+ # for an existing state machine; readiness is already ensured above.
155
+ existing=$(aws stepfunctions list-state-machines \
156
+ --endpoint-url ${SFN_ENDPOINT} \
157
+ --region ap-northeast-1 \
158
+ --query "stateMachines[?name=='${sm_name}'].name" \
159
+ --output text 2>/dev/null)
160
+ if [ -z "${existing}" ]; then
161
+ echo "Creating state machine: ${sm_name}"
162
+ # The serverless-step-functions-local plugin also auto-registers state
163
+ # machines on offline:start:init; this block is a fallback for the race
164
+ # where Step Functions Local starts after that hook runs. A benign
165
+ # "already exists" is treated as success; only a real failure aborts.
166
+ if create_out=$(aws stepfunctions create-state-machine \
167
+ --endpoint-url ${SFN_ENDPOINT} \
168
+ --region ap-northeast-1 \
169
+ --name "${sm_name}" \
170
+ --role-arn "arn:aws:iam::101010101010:role/DummyRole" \
171
+ --definition "${sm_definition}" 2>&1); then
172
+ echo "Created ${sm_name}"
173
+ elif echo "${create_out}" | grep -qi "already exists\|StateMachineAlreadyExists"; then
174
+ echo "State machine ${sm_name} already exists"
175
+ else
176
+ echo "Failed to create ${sm_name}: ${create_out}"
177
+ exit 1
178
+ fi
179
+ else
180
+ echo "State machine ${sm_name} already exists"
181
+ fi
182
+ done <<< "${sm_data}"
183
+
98
184
  # Trigger command stream
99
185
  timestamp=$(date +%s)
100
186
  for table in "${tables[@]}"; do
@@ -103,4 +189,4 @@ for table in "${tables[@]}"; do
103
189
  done
104
190
 
105
191
  echo "Send a command to trigger command stream tasks"
106
- aws --endpoint=${endpoint} dynamodb put-item --table-name ${TABLE_PREFIX}-tasks --item "{\"input\":{\"M\":{}},\"sk\":{\"S\":\"${timestamp}\"},\"pk\":{\"S\":\"test\"}}"
192
+ aws --endpoint=${endpoint} dynamodb put-item --table-name ${TABLE_PREFIX}-tasks --item "{\"input\":{\"M\":{\"action\":{\"S\":\"trigger\"}}},\"sk\":{\"S\":\"${timestamp}\"},\"pk\":{\"S\":\"test\"}}"
@@ -24,6 +24,11 @@ custom:
24
24
  sesPort: ${env:LOCAL_SES_PORT, 8005}
25
25
  cognitoPort: ${env:LOCAL_COGNITO_PORT, 9229}
26
26
 
27
+ # serverless-offline-lambda plugin (external Lambda invoke, separate from serverless-offline lambdaPort)
28
+ lambda:
29
+ port: ${env:LOCAL_OFFLINE_LAMBDA_PORT, 4000}
30
+ host: 0.0.0.0
31
+
27
32
  serverless-offline:
28
33
  corsAllowOrigin: '*'
29
34
  corsAllowHeaders: '*'
@@ -85,6 +90,9 @@ custom:
85
90
  region: ap-northeast-1
86
91
  # lambdaEndpoint: http://0.0.0.0:3002
87
92
  externalInstance: true
93
+ # Honor LOCAL_SFN_PORT so a non-default port reaches Step Functions Local
94
+ # (Docker mapping, the SDK and the registration script all use this port).
95
+ stepFunctionsEndpoint: http://localhost:${env:LOCAL_SFN_PORT, 8083}
88
96
  serverless-dynamodb:
89
97
  stages:
90
98
  # set for create tables on dev enviroment
@@ -125,6 +133,9 @@ provider:
125
133
  localAuthorizer:
126
134
  type: jwt
127
135
  identitySource: $request.header.Authorization
136
+ # cognito-local emits the JWT `iss` claim as http://localhost:${LOCAL_COGNITO_PORT}
137
+ # (its listen port; see infra-local/cognito-local/start.sh, which writes a matching
138
+ # TokenConfig.IssuerDomain). Keep issuerUrl in sync with that configurable port.
128
139
  issuerUrl: http://localhost:${self:custom.cognitoPort}/local_2G7noHgW
129
140
  audience:
130
141
  - dnk8y7ii3wled35p3lw0l2cd7