saaslayer 0.3.0 → 0.4.1

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 (65) hide show
  1. package/README.md +199 -18
  2. package/bin/saaslayer.js +335 -62
  3. package/package.json +3 -2
  4. package/src/aws-sigv4.js +74 -26
  5. package/src/commands/access-admins.js +2 -2
  6. package/src/commands/admin-allowlist.js +23 -3
  7. package/src/commands/api-keys.js +83 -0
  8. package/src/commands/audit.js +77 -0
  9. package/src/commands/aws.js +355 -82
  10. package/src/commands/binding-handoff.js +174 -0
  11. package/src/commands/bindings.js +111 -0
  12. package/src/commands/catalog.js +30 -3
  13. package/src/commands/deploy.js +49 -11
  14. package/src/commands/env-export.js +58 -0
  15. package/src/commands/first-admin.js +15 -4
  16. package/src/commands/foundation.js +75 -117
  17. package/src/commands/hooks.js +271 -0
  18. package/src/commands/integration-credentials.js +1 -1
  19. package/src/commands/lifecycle.js +149 -24
  20. package/src/commands/login-domain.js +259 -0
  21. package/src/commands/permission-orgs.js +80 -0
  22. package/src/commands/release-manifest.js +17 -8
  23. package/src/commands/service-principals.js +42 -5
  24. package/src/commands/settings.js +21 -5
  25. package/src/commands/sms-registration.js +182 -0
  26. package/src/commands/sms.js +178 -0
  27. package/src/commands/social.js +265 -0
  28. package/src/commands/support-staff.js +72 -0
  29. package/src/commands/users-management.js +2 -20
  30. package/src/commands/users.js +56 -11
  31. package/src/commands/versions.js +61 -0
  32. package/src/connection-proof.js +41 -0
  33. package/src/deployments.js +14 -2
  34. package/src/foundation-change-set.js +180 -0
  35. package/src/foundation-home.js +121 -0
  36. package/src/foundation-template.js +51 -10
  37. package/src/foundation-trust-write.js +379 -0
  38. package/src/iam-session.js +14 -8
  39. package/src/login-domain.js +138 -0
  40. package/src/login-methods.js +118 -0
  41. package/src/module-catalog.js +3 -2
  42. package/src/release-manifest.js +11 -4
  43. package/src/scope.js +3 -1
  44. package/src/settings.js +85 -13
  45. package/src/sms/number.js +37 -0
  46. package/src/sms/registration-fields.js +167 -0
  47. package/src/sms/registration-validate.js +151 -0
  48. package/src/sms/registration.js +216 -0
  49. package/src/sms/release.js +55 -0
  50. package/src/sms/scope.js +86 -0
  51. package/src/sms/status.js +181 -0
  52. package/src/ssm-api.js +31 -0
  53. package/src/trust-entries.js +350 -0
  54. package/src/user-service-instance.js +27 -0
  55. package/src/users-api.js +55 -8
  56. package/src/users-import/checkpoint.js +76 -0
  57. package/src/users-import/import.js +233 -24
  58. package/src/versions.js +80 -0
  59. package/templates/bootstrap/saaslayer-bootstrap-permission-set-inline-policy.json +148 -0
  60. package/templates/bootstrap/saaslayer-bootstrap-policy-email-sender.json +22 -0
  61. package/templates/bootstrap/saaslayer-bootstrap-policy-sms-number.json +22 -0
  62. package/templates/bootstrap/saaslayer-bootstrap-policy.json +114 -0
  63. package/templates/bootstrap/saaslayer-bootstrap-trust-policy.json +18 -0
  64. package/templates/saaslayer-foundation-region.yml +45 -1
  65. package/templates/saaslayer-foundation.yml +759 -309
@@ -0,0 +1,180 @@
1
+ // Reviewed CloudFormation change sets for the foundation stacks. Every path that updates the region foundation goes
2
+ // through a change set that keeps each installed parameter value and is refused if it would replace or remove an SMS
3
+ // sending number (any AWS::SMSVOICE::PhoneNumber); `--allow-replacement` never covers one. Only `sms release` removes it.
4
+ 'use strict'
5
+ const fs = require('fs')
6
+ const { templateInfo, writeDeployableTemplate } = require('./foundation-template')
7
+
8
+ /**
9
+ * @typedef {(args: string[]) => any} AwsJson runs `aws <args>` and returns the parsed JSON reply
10
+ * @typedef {{ action: string, logicalId: string, type: string, replacement: string, scope: string[], properties?: string[] }} Change
11
+ * @typedef {{ sleep: (ms: number) => Promise<void>, pollMs: number, maxPolls: number }} Wait
12
+ */
13
+
14
+ /** Stack states a change set can be created and executed from. */
15
+ const STABLE_STATUSES = ['CREATE_COMPLETE', 'UPDATE_COMPLETE', 'UPDATE_ROLLBACK_COMPLETE', 'IMPORT_COMPLETE', 'IMPORT_ROLLBACK_COMPLETE']
16
+
17
+ /** CloudFormation's change-set status reasons when the template + params match what is installed. */
18
+ const NO_CHANGES = /didn't contain changes|No updates are to be performed/i
19
+
20
+ /** The region foundation's SMS sending number. Replacing it loses its approved registration. */
21
+ const SMS_ORIGINATION_NUMBER = 'SmsOriginationNumber'
22
+ /** Every SMS sending number is protected by its type, whatever its logical id. */
23
+ const SMS_PHONE_NUMBER_TYPE = 'AWS::SMSVOICE::PhoneNumber'
24
+
25
+ /**
26
+ * Runs `aws <args>` in a region (and optional profile) and parses the JSON reply. `exec` decides the credentials.
27
+ * @param {(cmd: string, args: string[]) => string} exec
28
+ * @param {{ region: string, profile?: string }} where
29
+ * @returns {AwsJson}
30
+ */
31
+ function awsRunner(exec, { region, profile }) {
32
+ return (args) => {
33
+ const full = [...args, '--region', region, ...(profile ? ['--profile', profile] : []), '--output', 'json']
34
+ let out
35
+ try {
36
+ out = exec('aws', full)
37
+ } catch (err) {
38
+ const detail = String(err.stderr || err.message || '').trim()
39
+ const e = new Error(`aws ${args.slice(0, 2).join(' ')} failed: ${detail}`)
40
+ e.stderr = detail
41
+ throw e
42
+ }
43
+ return out && String(out).trim() ? JSON.parse(out) : {}
44
+ }
45
+ }
46
+
47
+ /**
48
+ * The stack as describe-stacks reports it, or null when it does not exist.
49
+ * @param {AwsJson} aws @param {string} stackName
50
+ */
51
+ function describeStack(aws, stackName) {
52
+ try {
53
+ return aws(['cloudformation', 'describe-stacks', '--stack-name', stackName]).Stacks[0]
54
+ } catch (err) {
55
+ if (/does not exist/.test(err.stderr || err.message)) return null
56
+ throw err
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Waits for a change set to finish creating and returns its status, every resource change (with the names of the
62
+ * properties it changes) and the parameter values the change set resolved.
63
+ * @param {AwsJson} aws @param {string} stackName @param {string} changeSetName @param {Wait} wait
64
+ * @returns {Promise<{ status: string, reason: string, changes: Change[], parameters: Record<string, string> }>}
65
+ */
66
+ async function waitForChangeSet(aws, stackName, changeSetName, { sleep, pollMs, maxPolls }) {
67
+ const base = ['cloudformation', 'describe-change-set', '--stack-name', stackName, '--change-set-name', changeSetName]
68
+ for (let i = 0; i < maxPolls; i++) {
69
+ const first = aws(base)
70
+ if (first.Status === 'CREATE_COMPLETE' || first.Status === 'FAILED') {
71
+ // The aws CLI auto-paginates describe-change-set, so Changes holds every page.
72
+ /** @type {Change[]} */
73
+ const changes = (first.Changes || []).filter((c) => c.Type === 'Resource').map(({ ResourceChange: rc }) => ({
74
+ action: rc.Action, logicalId: rc.LogicalResourceId, type: rc.ResourceType, replacement: rc.Replacement || '', scope: rc.Scope || [],
75
+ properties: (rc.Details || []).filter((d) => d.Target && d.Target.Attribute === 'Properties' && d.Target.Name).map((d) => d.Target.Name),
76
+ }))
77
+ const parameters = Object.fromEntries((first.Parameters || []).map((p) => [p.ParameterKey, p.ParameterValue]))
78
+ return { status: first.Status, reason: first.StatusReason || '', changes, parameters }
79
+ }
80
+ await sleep(pollMs)
81
+ }
82
+ throw new Error(`change set ${changeSetName} on ${stackName} did not finish creating`)
83
+ }
84
+
85
+ /** @param {Change[]} changes */
86
+ function formatChanges(changes) {
87
+ const w = (key) => Math.max(...changes.map((c) => String(c[key]).length))
88
+ const [wa, wl, wt] = [w('action'), w('logicalId'), w('type')]
89
+ return changes.map((c) => ` ${c.action.padEnd(wa)} ${c.logicalId.padEnd(wl)} ${c.type.padEnd(wt)} replacement=${c.replacement || '-'} scope=${c.scope.join(',') || '-'}`)
90
+ }
91
+
92
+ /**
93
+ * Changes that would replace (True or Conditional) or remove an SMS sending number (any AWS::SMSVOICE::PhoneNumber).
94
+ * `allowRemoval` (only `sms release`) lets a removal through; a replacement is always refused.
95
+ * @param {Change[]} changes @param {{ allowRemoval?: boolean }} [opts]
96
+ */
97
+ function smsNumberChanges(changes, { allowRemoval = false } = {}) {
98
+ const isNumber = (c) => c.type === SMS_PHONE_NUMBER_TYPE || c.logicalId === SMS_ORIGINATION_NUMBER
99
+ return changes.filter((c) => isNumber(c) && ((c.action === 'Remove' && !allowRemoval) || c.replacement === 'True' || c.replacement === 'Conditional'))
100
+ }
101
+
102
+ /**
103
+ * The refusal for a change set that would replace or remove an SMS sending number, or null when it leaves them alone.
104
+ * @param {string} label @param {Change[]} changes @param {{ allowRemoval?: boolean }} [opts]
105
+ * @returns {Error|null}
106
+ */
107
+ function smsNumberRefusal(label, changes, opts) {
108
+ const hit = smsNumberChanges(changes, opts)
109
+ if (!hit.length) return null
110
+ const ids = [...new Set(hit.map((c) => c.logicalId))].join(', ')
111
+ return new Error(`${label}: this change would replace or remove ${ids}, the account's SMS sending number, and lose its approved registration. ` +
112
+ '--allow-replacement does not cover it. To move to a different number: saaslayer sms release, then saaslayer sms setup, then a new registration (saaslayer sms register).')
113
+ }
114
+
115
+ /**
116
+ * Creates or updates the region foundation stack through a reviewed change set: a parameter the stack already has keeps
117
+ * its value unless `overrides` sets it, one it lacks takes the template default. Refuses a change set that would replace
118
+ * or remove an SMS sending number; `allowSmsNumberRemoval` (only `sms release`) lets its removal through. `onExecute`
119
+ * runs just before the change set executes. Returns created | updated | up to date.
120
+ * @param {{ aws: AwsJson, stackName: string, templateFile: string, overrides: Record<string, string>, wait: Wait, log?: (...a: unknown[]) => void,
121
+ * allowSmsNumberRemoval?: boolean, onExecute?: (changes: Change[]) => Promise<void> }} o
122
+ * @returns {Promise<{ result: 'created'|'updated'|'up to date', changes: Change[] }>}
123
+ */
124
+ async function applyRegionFoundation({ aws, stackName, templateFile, overrides, wait, log = () => {}, allowSmsNumberRemoval = false, onExecute }) {
125
+ const stack = describeStack(aws, stackName)
126
+ if (stack && !STABLE_STATUSES.includes(stack.StackStatus)) {
127
+ throw new Error(`${stackName} is ${stack.StackStatus}; an update needs one of ${STABLE_STATUSES.join(', ')}. Resolve it in CloudFormation first.`)
128
+ }
129
+ const installed = stack ? (stack.Parameters || []).map((p) => p.ParameterKey) : []
130
+ const parameters = templateInfo(fs.readFileSync(templateFile, 'utf8')).parameters.flatMap((p) => {
131
+ if (p.name in overrides) return [{ ParameterKey: p.name, ParameterValue: overrides[p.name] }]
132
+ return installed.includes(p.name) ? [{ ParameterKey: p.name, UsePreviousValue: true }] : []
133
+ })
134
+ const type = stack ? 'UPDATE' : 'CREATE'
135
+ const changeSetName = `saaslayer-region-${Date.now()}`
136
+ const del = () => aws(['cloudformation', 'delete-change-set', '--stack-name', stackName, '--change-set-name', changeSetName])
137
+ aws([
138
+ 'cloudformation', 'create-change-set', '--stack-name', stackName, '--change-set-name', changeSetName,
139
+ '--change-set-type', type, '--template-body', `file://${writeDeployableTemplate(templateFile)}`,
140
+ '--parameters', JSON.stringify(parameters),
141
+ ])
142
+ const cs = await waitForChangeSet(aws, stackName, changeSetName, wait)
143
+ if (cs.status === 'FAILED') {
144
+ del()
145
+ if (NO_CHANGES.test(cs.reason)) return { result: 'up to date', changes: [] }
146
+ throw new Error(`${stackName}: change set failed: ${cs.reason}`)
147
+ }
148
+ log(` ${stackName} changes (${cs.changes.length}):`)
149
+ for (const line of formatChanges(cs.changes)) log(line)
150
+ const refusal = smsNumberRefusal(stackName, cs.changes, { allowRemoval: allowSmsNumberRemoval })
151
+ if (refusal) {
152
+ del()
153
+ throw refusal
154
+ }
155
+ if (onExecute) await onExecute(cs.changes)
156
+ aws(['cloudformation', 'execute-change-set', '--stack-name', stackName, '--change-set-name', changeSetName])
157
+ return { result: await waitForStack(aws, stackName, type, wait), changes: cs.changes }
158
+ }
159
+
160
+ /**
161
+ * Waits for the stack's in-progress operation to settle; `${type}_COMPLETE` is created/updated, anything else throws.
162
+ * @param {AwsJson} aws @param {string} stackName @param {'CREATE'|'UPDATE'} type @param {Wait} wait
163
+ * @returns {Promise<'created'|'updated'>}
164
+ */
165
+ async function waitForStack(aws, stackName, type, wait) {
166
+ for (let i = 0; i < wait.maxPolls; i++) {
167
+ const s = describeStack(aws, stackName)
168
+ if (s && !/_IN_PROGRESS$/.test(s.StackStatus)) {
169
+ if (s.StackStatus !== `${type}_COMPLETE`) throw new Error(`${stackName} ended ${s.StackStatus}; check its events in the CloudFormation console`)
170
+ return type === 'CREATE' ? 'created' : 'updated'
171
+ }
172
+ await wait.sleep(wait.pollMs)
173
+ }
174
+ throw new Error(`${stackName} did not finish; check it in the CloudFormation console`)
175
+ }
176
+
177
+ module.exports = {
178
+ STABLE_STATUSES, NO_CHANGES, SMS_ORIGINATION_NUMBER, SMS_PHONE_NUMBER_TYPE,
179
+ awsRunner, describeStack, waitForChangeSet, waitForStack, formatChanges, smsNumberChanges, smsNumberRefusal, applyRegionFoundation,
180
+ }
@@ -0,0 +1,121 @@
1
+ // Foundation home (ADR 0005 §2.1): the one account-global saaslayer-foundation stack and its home region, recovered from
2
+ // the entry roles' aws:cloudformation:stack-id tag (or the recorded stack); a missing or conflicting home is blocked.
3
+ 'use strict'
4
+
5
+ /** The account-global foundation stack name. */
6
+ const FOUNDATION_STACK = 'saaslayer-foundation'
7
+ /** The foundation roles whose stack-id tag names the home stack. */
8
+ const HOME_ROLES = ['sl-foundation-deploy-role', 'sl-foundation-support-ro-role']
9
+ const STACK_ID_TAG = 'aws:cloudformation:stack-id'
10
+ const BLOCKED = 'this account\'s trust relationship is blocked for reconciliation'
11
+
12
+ /**
13
+ * @typedef {import('./foundation-change-set').AwsJson} AwsJson
14
+ * @typedef {{ state: 'absent' } | { state: 'home', stackId: string, homeRegion: string, source: 'role-tags'|'record'|'stack-resources' }} FoundationHome
15
+ */
16
+
17
+ /**
18
+ * The region of a CloudFormation stack ARN.
19
+ * @param {string} arn
20
+ */
21
+ function stackRegion(arn) {
22
+ const match = /^arn:aws[\w-]*:cloudformation:([a-z0-9-]+):[0-9]{12}:stack\/[^/]+\/.+$/.exec(String(arn))
23
+ if (!match) throw new Error(`${JSON.stringify(arn)} is not a CloudFormation stack ARN`)
24
+ return match[1]
25
+ }
26
+
27
+ /** @param {string} arn */
28
+ const stackNameOf = (arn) => String(arn).split(':stack/')[1].split('/')[0]
29
+
30
+ /**
31
+ * A foundation role's stack-id tag: undefined when the role does not exist, null when it carries no such tag.
32
+ * @param {AwsJson} aws @param {string} roleName
33
+ * @returns {string|null|undefined}
34
+ */
35
+ function roleStackId(aws, roleName) {
36
+ try {
37
+ const { Tags = [] } = aws(['iam', 'list-role-tags', '--role-name', roleName])
38
+ const tag = Tags.find((t) => t.Key === STACK_ID_TAG)
39
+ return tag ? tag.Value : null
40
+ } catch (err) {
41
+ if (/NoSuchEntity/.test(err.stderr || err.message)) return undefined
42
+ throw err
43
+ }
44
+ }
45
+
46
+ /**
47
+ * The StackId of the stack in this region that owns a role (CloudFormation does not tag the IAM roles it creates), or null
48
+ * when no stack in this region owns it.
49
+ * @param {AwsJson} aws @param {string} roleName
50
+ * @returns {string|null}
51
+ */
52
+ function roleOwnerStackId(aws, roleName) {
53
+ try {
54
+ const { StackResources = [] } = aws(['cloudformation', 'describe-stack-resources', '--physical-resource-id', roleName])
55
+ return StackResources.length ? StackResources[0].StackId : null
56
+ } catch (err) {
57
+ if (/does not exist/.test(err.stderr || err.message)) return null
58
+ throw err
59
+ }
60
+ }
61
+
62
+ /**
63
+ * The StackId of the account foundation stack in a region, or null when that region has none.
64
+ * @param {AwsJson} aws @param {string} stackName
65
+ */
66
+ function foundationStackId(aws, stackName) {
67
+ try {
68
+ return aws(['cloudformation', 'describe-stacks', '--stack-name', stackName]).Stacks[0].StackId
69
+ } catch (err) {
70
+ if (/does not exist/.test(err.stderr || err.message)) return null
71
+ throw err
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Resolves the account's foundation home with the caller's credentials. `absent` means no foundation roles and no
77
+ * foundation stack in the requested region (a first install there). Throws when the home is missing or conflicting:
78
+ * role tags naming different stacks, a recorded stack that disagrees, a second account foundation in the requested
79
+ * region, or a home stack that no longer exists. Never guesses a region.
80
+ * @param {{ awsIn: (region: string) => AwsJson, requestedRegion: string, recorded?: { arn: string, homeRegion?: string }|null,
81
+ * stackName?: string }} o
82
+ * @returns {FoundationHome}
83
+ */
84
+ function resolveFoundationHome({ awsIn, requestedRegion, recorded = null, stackName = FOUNDATION_STACK }) {
85
+ const local = awsIn(requestedRegion)
86
+ const tags = HOME_ROLES.map((name) => ({ name, stackId: roleStackId(local, name) }))
87
+ const present = tags.filter((t) => t.stackId !== undefined)
88
+ if (!present.length) {
89
+ if (foundationStackId(local, stackName)) throw new Error(`${stackName} exists in ${requestedRegion} without its foundation roles; ${BLOCKED}`)
90
+ if (recorded && recorded.arn) throw new Error(`the recorded foundation stack ${recorded.arn} has no foundation roles in this account; ${BLOCKED}`)
91
+ return { state: 'absent' }
92
+ }
93
+ const missing = tags.filter((t) => t.stackId === undefined)
94
+ if (missing.length) throw new Error(`foundation role ${missing.map((t) => t.name).join(', ')} is missing; ${BLOCKED}`)
95
+ const tagged = [...new Set(tags.map((t) => t.stackId).filter(Boolean))]
96
+ if (tagged.length > 1) throw new Error(`the foundation role tags name different stacks (${tagged.join(', ')}); ${BLOCKED}`)
97
+ if (!tagged.length && !(recorded && recorded.arn)) {
98
+ const owners = [...new Set(tags.map((t) => roleOwnerStackId(local, t.name)))]
99
+ if (owners.includes(null)) {
100
+ throw new Error(`the foundation roles carry no ${STACK_ID_TAG} tag and no stack in ${requestedRegion} owns them; rerun with --region <the foundation's home region>; ${BLOCKED}`)
101
+ }
102
+ if (owners.length > 1) throw new Error(`the foundation roles belong to different stacks (${owners.join(', ')}); ${BLOCKED}`)
103
+ if (stackNameOf(owners[0]) !== stackName) throw new Error(`the foundation roles belong to ${stackNameOf(owners[0])}, not ${stackName}; ${BLOCKED}`)
104
+ return { state: 'home', stackId: owners[0], homeRegion: stackRegion(owners[0]), source: 'stack-resources' }
105
+ }
106
+ if (recorded && recorded.arn && tagged.length && recorded.arn !== tagged[0]) {
107
+ throw new Error(`the recorded foundation stack ${recorded.arn} differs from the one the foundation roles name (${tagged[0]}); ${BLOCKED}`)
108
+ }
109
+ const stackId = tagged[0] || (recorded && recorded.arn) || null
110
+ if (!stackId) throw new Error(`the foundation roles carry no ${STACK_ID_TAG} tag and no recorded foundation stack is known; ${BLOCKED}`)
111
+ if (stackNameOf(stackId) !== stackName) throw new Error(`the foundation roles belong to ${stackNameOf(stackId)}, not ${stackName}; ${BLOCKED}`)
112
+ const homeRegion = stackRegion(stackId)
113
+ if (foundationStackId(awsIn(homeRegion), stackName) !== stackId) throw new Error(`the home stack ${stackId} was not found in ${homeRegion}; ${BLOCKED}`)
114
+ if (requestedRegion !== homeRegion) {
115
+ const other = foundationStackId(local, stackName)
116
+ if (other) throw new Error(`a second account foundation ${other} exists in ${requestedRegion} besides the home stack in ${homeRegion}; ${BLOCKED}`)
117
+ }
118
+ return { state: 'home', stackId, homeRegion, source: tagged.length ? 'role-tags' : 'record' }
119
+ }
120
+
121
+ module.exports = { FOUNDATION_STACK, HOME_ROLES, resolveFoundationHome, stackRegion }
@@ -1,5 +1,5 @@
1
1
  // Deployable copy of the foundation template: whole-line comments stripped so it fits CloudFormation's
2
- // 51,200-byte inline template limit (the documented source is larger), plus redaction for deploy argv in errors.
2
+ // 51,200-byte inline template limit (the documented source is larger), plus parameter files and redaction that keep secrets out of argv and errors.
3
3
  'use strict'
4
4
  const fs = require('fs')
5
5
  const os = require('os')
@@ -19,14 +19,41 @@ function stripComments(text) {
19
19
  }
20
20
 
21
21
  /**
22
- * Writes the stripped template to a temp file and returns its path, for `aws cloudformation deploy --template-file`.
22
+ * The bundled template's version (Mappings.Meta.<name>.Version) and its parameters with their defaults.
23
+ * @param {string} text template YAML
24
+ * @returns {{ version: string|null, parameters: { name: string, hasDefault: boolean, default?: string }[] }}
25
+ */
26
+ function templateInfo(text) {
27
+ const lines = stripComments(text).split('\n')
28
+ const versionMatch = /^ {2}Meta:\s*\n {4}\w+:\s*\n {6}Version:\s*'?([^'\s]+)'?/m.exec(lines.join('\n'))
29
+ const parameters = []
30
+ const start = lines.indexOf('Parameters:')
31
+ if (start !== -1) {
32
+ for (let i = start + 1; i < lines.length && !/^\S/.test(lines[i]); i++) {
33
+ const name = /^ {2}(\w+):\s*$/.exec(lines[i])
34
+ if (name) { parameters.push({ name: name[1], hasDefault: false }); continue }
35
+ const def = /^ {4}Default:\s*(.*)$/.exec(lines[i])
36
+ if (def && parameters.length) {
37
+ const current = parameters[parameters.length - 1]
38
+ current.hasDefault = true
39
+ current.default = def[1].trim().replace(/^'(.*)'$/, '$1').replace(/^"(.*)"$/, '$1')
40
+ }
41
+ }
42
+ }
43
+ return { version: versionMatch ? versionMatch[1] : null, parameters }
44
+ }
45
+
46
+ /**
47
+ * Writes the stripped template (or `text`, a rendered copy of it) to a temp file and returns its path, for
48
+ * `aws cloudformation deploy --template-file` or `--template-body file://`.
23
49
  * @param {string} templatePath
50
+ * @param {string} [text] the template content to write instead of the file's own
24
51
  * @returns {string}
25
52
  */
26
- function writeDeployableTemplate(templatePath) {
53
+ function writeDeployableTemplate(templatePath, text = fs.readFileSync(templatePath, 'utf8')) {
27
54
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'saaslayer-foundation-'))
28
55
  const file = path.join(dir, path.basename(templatePath))
29
- fs.writeFileSync(file, stripComments(fs.readFileSync(templatePath, 'utf8')))
56
+ fs.writeFileSync(file, stripComments(text))
30
57
  return file
31
58
  }
32
59
 
@@ -40,18 +67,32 @@ function redactArgs(args) {
40
67
  }
41
68
 
42
69
  /**
43
- * `aws cloudformation deploy` argv for `saaslayer init`, deploying the stripped template copy. A re-run that
44
- * changes nothing is a clean no-op.
45
- * @param {{ template: string, stackName: string, region: string, controlPlaneAccount: string, externalId: string, stackPrefix: string, orgId: string }} o
70
+ * Writes CloudFormation parameter overrides to a 0600 file inside a private (0700) temp dir, for
71
+ * `aws cloudformation deploy --parameter-overrides file://<file>`, so secret values (the ExternalId) never appear
72
+ * in argv or `ps`. Call remove() once the deploy has finished.
73
+ * @param {Record<string, string>} params
74
+ * @returns {{ file: string, remove: () => void }}
75
+ */
76
+ function writeParameterOverridesFile(params) {
77
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'saaslayer-params-'))
78
+ const file = path.join(dir, 'parameters.json')
79
+ const body = Object.entries(params).map(([ParameterKey, ParameterValue]) => ({ ParameterKey, ParameterValue: String(ParameterValue) }))
80
+ fs.writeFileSync(file, JSON.stringify(body), { mode: 0o600 })
81
+ return { file, remove: () => fs.rmSync(dir, { recursive: true, force: true }) }
82
+ }
83
+
84
+ /**
85
+ * `aws cloudformation deploy` argv for `saaslayer init`, deploying the stripped template copy with parameters read
86
+ * from `parametersFile` (see writeParameterOverridesFile). A re-run that changes nothing is a clean no-op.
87
+ * @param {{ template: string, stackName: string, region: string, parametersFile: string }} o
46
88
  * @returns {string[]}
47
89
  */
48
90
  function initDeployArgs(o) {
49
91
  return [
50
92
  'cloudformation', 'deploy', '--template-file', writeDeployableTemplate(o.template), '--stack-name', o.stackName, '--region', o.region,
51
93
  '--capabilities', 'CAPABILITY_NAMED_IAM', '--no-fail-on-empty-changeset',
52
- '--parameter-overrides',
53
- `ControlPlaneAccountId=${o.controlPlaneAccount}`, `ExternalId=${o.externalId}`, `StackNamePrefix=${o.stackPrefix}`, `OrgId=${o.orgId}`,
94
+ '--parameter-overrides', `file://${o.parametersFile}`,
54
95
  ]
55
96
  }
56
97
 
57
- module.exports = { CFN_INLINE_TEMPLATE_LIMIT, stripComments, writeDeployableTemplate, redactArgs, initDeployArgs }
98
+ module.exports = { CFN_INLINE_TEMPLATE_LIMIT, stripComments, templateInfo, writeDeployableTemplate, redactArgs, writeParameterOverridesFile, initDeployArgs }