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.
- package/README.md +199 -18
- package/bin/saaslayer.js +335 -62
- package/package.json +3 -2
- package/src/aws-sigv4.js +74 -26
- package/src/commands/access-admins.js +2 -2
- package/src/commands/admin-allowlist.js +23 -3
- package/src/commands/api-keys.js +83 -0
- package/src/commands/audit.js +77 -0
- package/src/commands/aws.js +355 -82
- package/src/commands/binding-handoff.js +174 -0
- package/src/commands/bindings.js +111 -0
- package/src/commands/catalog.js +30 -3
- package/src/commands/deploy.js +49 -11
- package/src/commands/env-export.js +58 -0
- package/src/commands/first-admin.js +15 -4
- package/src/commands/foundation.js +75 -117
- package/src/commands/hooks.js +271 -0
- package/src/commands/integration-credentials.js +1 -1
- package/src/commands/lifecycle.js +149 -24
- package/src/commands/login-domain.js +259 -0
- package/src/commands/permission-orgs.js +80 -0
- package/src/commands/release-manifest.js +17 -8
- package/src/commands/service-principals.js +42 -5
- package/src/commands/settings.js +21 -5
- package/src/commands/sms-registration.js +182 -0
- package/src/commands/sms.js +178 -0
- package/src/commands/social.js +265 -0
- package/src/commands/support-staff.js +72 -0
- package/src/commands/users-management.js +2 -20
- package/src/commands/users.js +56 -11
- package/src/commands/versions.js +61 -0
- package/src/connection-proof.js +41 -0
- package/src/deployments.js +14 -2
- package/src/foundation-change-set.js +180 -0
- package/src/foundation-home.js +121 -0
- package/src/foundation-template.js +51 -10
- package/src/foundation-trust-write.js +379 -0
- package/src/iam-session.js +14 -8
- package/src/login-domain.js +138 -0
- package/src/login-methods.js +118 -0
- package/src/module-catalog.js +3 -2
- package/src/release-manifest.js +11 -4
- package/src/scope.js +3 -1
- package/src/settings.js +85 -13
- package/src/sms/number.js +37 -0
- package/src/sms/registration-fields.js +167 -0
- package/src/sms/registration-validate.js +151 -0
- package/src/sms/registration.js +216 -0
- package/src/sms/release.js +55 -0
- package/src/sms/scope.js +86 -0
- package/src/sms/status.js +181 -0
- package/src/ssm-api.js +31 -0
- package/src/trust-entries.js +350 -0
- package/src/user-service-instance.js +27 -0
- package/src/users-api.js +55 -8
- package/src/users-import/checkpoint.js +76 -0
- package/src/users-import/import.js +233 -24
- package/src/versions.js +80 -0
- package/templates/bootstrap/saaslayer-bootstrap-permission-set-inline-policy.json +148 -0
- package/templates/bootstrap/saaslayer-bootstrap-policy-email-sender.json +22 -0
- package/templates/bootstrap/saaslayer-bootstrap-policy-sms-number.json +22 -0
- package/templates/bootstrap/saaslayer-bootstrap-policy.json +114 -0
- package/templates/bootstrap/saaslayer-bootstrap-trust-policy.json +18 -0
- package/templates/saaslayer-foundation-region.yml +45 -1
- package/templates/saaslayer-foundation.yml +759 -309
|
@@ -7,6 +7,7 @@ const { finishMutation, requestKeyHeaders } = require('./operations')
|
|
|
7
7
|
const { applySettings, fetchSchema, readDeploymentSettings } = require('./settings')
|
|
8
8
|
const { formatChanges } = require('../settings')
|
|
9
9
|
const rm = require('../release-manifest')
|
|
10
|
+
const { checkReleaseChoice } = require('../versions')
|
|
10
11
|
const { version: CLI_VERSION } = require('../../package.json')
|
|
11
12
|
|
|
12
13
|
const USAGE = 'usage: saaslayer release-manifest create --env E [--out FILE] [--name NAME] (see saaslayer --help)'
|
|
@@ -41,6 +42,7 @@ async function updateFromManifest(flags) {
|
|
|
41
42
|
if (flags['commit-sha'] !== undefined || flags.commitSha !== undefined || flags.param !== undefined) {
|
|
42
43
|
throw new Error('--manifest sets the release and settings: drop --commit-sha and --param')
|
|
43
44
|
}
|
|
45
|
+
if (flags.version !== undefined || flags.channel !== undefined) throw new Error('--manifest sets the release and settings: drop --version and --channel')
|
|
44
46
|
const file = flags.manifest
|
|
45
47
|
if (typeof file !== 'string') throw new Error('update --manifest needs a release manifest file')
|
|
46
48
|
const manifest = rm.readManifest(file)
|
|
@@ -58,13 +60,17 @@ async function updateFromManifest(flags) {
|
|
|
58
60
|
noWait: flagOn(flags, 'no-wait'),
|
|
59
61
|
})
|
|
60
62
|
const target = manifest.bundle.revision
|
|
63
|
+
// A versioned manifest moves by version (checked against the control plane first); its revision is the commit the
|
|
64
|
+
// contracts above were checked at.
|
|
65
|
+
const version = manifest.bundle.version
|
|
66
|
+
const targetLabel = version ? `${version} (${target.slice(0, 7)})` : target.slice(0, 7)
|
|
61
67
|
const where = `${env} (${deployment.deploymentId})`
|
|
62
68
|
if (!result.ok) {
|
|
63
69
|
const lines = result.problems.map((p) => ` - ${p.code}: ${p.message}${p.action ? `\n → ${p.action}` : ''}`)
|
|
64
70
|
throw new Error(`preflight ${where} failed — nothing was changed:\n${lines.join('\n')}`)
|
|
65
71
|
}
|
|
66
72
|
console.log(`preflight ${where}: ok${manifest.name ? ` (${manifest.name})` : ''}`)
|
|
67
|
-
console.log(` release: ${result.fromRevisions.map((r) => r.slice(0, 7)).join(', ')} → ${
|
|
73
|
+
console.log(` release: ${result.fromRevisions.map((r) => r.slice(0, 7)).join(', ')} → ${targetLabel}${result.moveRelease ? '' : ' (already deployed)'}`)
|
|
68
74
|
if (result.patch) for (const line of formatChanges(result.patch, settings)) console.log(line)
|
|
69
75
|
else console.log(` settings: ${envPatch ? 'match' : `none named for ${env}`}`)
|
|
70
76
|
if (flagOn(flags, 'dry-run')) {
|
|
@@ -72,15 +78,16 @@ async function updateFromManifest(flags) {
|
|
|
72
78
|
return result
|
|
73
79
|
}
|
|
74
80
|
if (!result.moveRelease && !result.patch) {
|
|
75
|
-
console.log(`${deployment.deploymentId} already runs ${
|
|
81
|
+
console.log(`${deployment.deploymentId} already runs ${targetLabel} and its settings match: nothing to change`)
|
|
76
82
|
return result
|
|
77
83
|
}
|
|
78
84
|
if (result.moveRelease) {
|
|
79
|
-
const attributes = { commitSha: target }
|
|
85
|
+
const attributes = version ? { version } : { commitSha: target }
|
|
86
|
+
if (version) await checkReleaseChoice({ version }, flags)
|
|
80
87
|
if (flags.reason) attributes.reason = flags.reason
|
|
81
88
|
if (flagOn(flags, 'force')) attributes.force = true
|
|
82
89
|
const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(deployment.deploymentId)}/update`, { data: { type: 'deployments', attributes } }, flags, { headers: requestKeyHeaders() })
|
|
83
|
-
console.log(`✅ release move to ${target.slice(0, 7)} started for ${deployment.deploymentId}`)
|
|
90
|
+
console.log(`✅ release move to ${version || target.slice(0, 7)} started for ${deployment.deploymentId}`)
|
|
84
91
|
await finishMutation({ response: res, deploymentId: deployment.deploymentId, flags })
|
|
85
92
|
}
|
|
86
93
|
if (result.patch) await applySettings(result.patch, flags)
|
|
@@ -88,8 +95,9 @@ async function updateFromManifest(flags) {
|
|
|
88
95
|
}
|
|
89
96
|
|
|
90
97
|
/**
|
|
91
|
-
* `release-manifest create --env E [--out FILE] [--name NAME]`: the revision, settings-contract hashes and
|
|
92
|
-
* declaration of a tested deployment, and this CLI's version.
|
|
98
|
+
* `release-manifest create --env E [--out FILE] [--name NAME]`: the version and revision, settings-contract hashes and
|
|
99
|
+
* permissions writer declaration of a tested deployment, and this CLI's version. A deployment on an unversioned commit
|
|
100
|
+
* is refused: a manifest moves by version. Reader declarations and environment settings are left
|
|
93
101
|
* for the author: a missing reader declaration is never inferred.
|
|
94
102
|
* @param {object} flags
|
|
95
103
|
*/
|
|
@@ -100,6 +108,7 @@ async function createManifest(flags) {
|
|
|
100
108
|
throw new Error(`${deployment.deploymentId} runs more than one revision (${settings.modules.map((m) => `${m.module}@${(m.revision || '—').slice(0, 7)}`).join(', ')}): update it to one tested release first`)
|
|
101
109
|
}
|
|
102
110
|
const revision = /** @type {string} */ (revisions[0])
|
|
111
|
+
if (!deployment.version) throw new Error(`${deployment.deploymentId} runs an unversioned release (${revision.slice(0, 7)}): move it to a version first (saaslayer versions lists them)`)
|
|
103
112
|
/** @type {Record<string, { settingsContractSha256: string }>} */
|
|
104
113
|
const modules = {}
|
|
105
114
|
for (const m of settings.modules) modules[m.module] = { settingsContractSha256: rm.contractHash(await fetchSchema(m.module, revision, flags)) }
|
|
@@ -108,7 +117,7 @@ async function createManifest(flags) {
|
|
|
108
117
|
const manifest = {
|
|
109
118
|
schemaVersion: rm.MANIFEST_SCHEMA_VERSION,
|
|
110
119
|
...(typeof flags.name === 'string' ? { name: flags.name } : {}),
|
|
111
|
-
bundle: { revision, modules },
|
|
120
|
+
bundle: { revision, version: deployment.version, modules },
|
|
112
121
|
tooling: { cli: CLI_VERSION },
|
|
113
122
|
...(writer ? { compatibility: { permissions: rm.permissionsWriterRelease(docSetting ? docSetting.value : undefined) } } : {}),
|
|
114
123
|
environments: {},
|
|
@@ -118,7 +127,7 @@ async function createManifest(flags) {
|
|
|
118
127
|
const text = `${JSON.stringify(manifest, null, 2)}\n`
|
|
119
128
|
if (typeof flags.out === 'string') {
|
|
120
129
|
fs.writeFileSync(flags.out, text)
|
|
121
|
-
console.log(`release manifest for ${deployment.deploymentId} @ ${revision.slice(0, 7)} written to ${flags.out}`)
|
|
130
|
+
console.log(`release manifest for ${deployment.deploymentId} @ ${deployment.version} (${revision.slice(0, 7)}) written to ${flags.out}`)
|
|
122
131
|
} else {
|
|
123
132
|
console.log(text)
|
|
124
133
|
}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
// `saaslayer permissions service-principal roles|assign|unassign`: typed role assignment for service
|
|
2
|
-
// — a declared IAM machine's mapped principal (--machine <principalId> → iam.<principalId>) or any
|
|
1
|
+
// `saaslayer permissions service-principal roles|assign|unassign|verifier-key create`: typed role assignment for service
|
|
2
|
+
// principals (matrix R10) — a declared IAM machine's mapped principal (--machine <principalId> → iam.<principalId>) or any
|
|
3
|
+
// service account id — and verify-only API keys for a customer backend's service account.
|
|
3
4
|
'use strict'
|
|
4
|
-
const { exchangeIamToken } = require('../iam-session')
|
|
5
|
+
const { exchangeIamToken, awsCredentials } = require('../iam-session')
|
|
5
6
|
const { authHeaders } = require('../deployment-api-auth')
|
|
7
|
+
const { ssmApi } = require('../ssm-api')
|
|
6
8
|
|
|
7
9
|
/**
|
|
8
|
-
* @typedef {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, machine?: string, role?: string, scope?: string }} ServicePrincipalFlags
|
|
10
|
+
* @typedef {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, machine?: string, role?: string, scope?: string, 'ssm-parameter'?: string }} ServicePrincipalFlags
|
|
9
11
|
*/
|
|
10
12
|
|
|
11
13
|
/**
|
|
@@ -78,4 +80,39 @@ async function servicePrincipalUnassign(positional, flags, deps = {}) {
|
|
|
78
80
|
await call('permissions service-principal unassign', `${apiBase}/principals/serviceAccount/${encodeURIComponent(id)}/roles/${encodeURIComponent(flags.role)}${qs}`, { method: 'DELETE', headers: auth })
|
|
79
81
|
}
|
|
80
82
|
|
|
81
|
-
|
|
83
|
+
/**
|
|
84
|
+
* Issue a service principal a deployment-wide key whose only permission is verifying API keys (created, owned by the
|
|
85
|
+
* caller, when missing). The secret is returned only by this call.
|
|
86
|
+
* @param {string[]} positional [servicePrincipalId] @param {ServicePrincipalFlags} flags
|
|
87
|
+
* @param {{ exchange?: typeof exchangeIamToken }} [deps]
|
|
88
|
+
* @returns {Promise<{ keyId: string, apiKey: string, servicePrincipalId: string, expiresAt: string|null }>}
|
|
89
|
+
*/
|
|
90
|
+
async function verifierKeyCreate(positional, flags, deps = {}) {
|
|
91
|
+
const { id, apiBase } = target('permissions service-principal verifier-key create', positional, flags)
|
|
92
|
+
const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
|
|
93
|
+
const body = await call('permissions service-principal verifier-key create', `${apiBase}/service-principals/${encodeURIComponent(id)}/verifier-keys`, {
|
|
94
|
+
method: 'POST',
|
|
95
|
+
headers: { ...auth, 'content-type': 'application/json' },
|
|
96
|
+
body: JSON.stringify({}),
|
|
97
|
+
})
|
|
98
|
+
const { attributes } = body.data
|
|
99
|
+
return { keyId: body.data.id, apiKey: attributes.apiKey, servicePrincipalId: attributes.servicePrincipal.id, expiresAt: attributes.expiresAt || null }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Write a verifier key to the SecureString --ssm-parameter (replacing the key it held), with the caller's AWS credentials
|
|
104
|
+
* (--profile) in --region (default $AWS_REGION).
|
|
105
|
+
* @param {string} apiKey @param {ServicePrincipalFlags} flags
|
|
106
|
+
* @param {{ credentials?: () => { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, fetch?: typeof fetch }} [deps]
|
|
107
|
+
* @returns {Promise<{ name: string, version: number }>}
|
|
108
|
+
*/
|
|
109
|
+
async function storeVerifierKey(apiKey, flags, deps = {}) {
|
|
110
|
+
const name = String(flags['ssm-parameter'])
|
|
111
|
+
const region = flags.region || process.env.AWS_REGION
|
|
112
|
+
if (!region) throw new Error('permissions service-principal verifier-key create: --region (or $AWS_REGION) is required with --ssm-parameter')
|
|
113
|
+
const put = ssmApi({ region, credentials: deps.credentials || (() => awsCredentials({ profile: flags.profile })), fetchImpl: deps.fetch || fetch })
|
|
114
|
+
const doc = await put('PutParameter', { Name: name, Value: apiKey, Type: 'SecureString', Overwrite: true, Description: 'SaaSLayer verifier API key (keys:api-key:verify only)' })
|
|
115
|
+
return { name, version: doc.Version }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
module.exports = { servicePrincipalRoles, servicePrincipalAssign, servicePrincipalUnassign, verifierKeyCreate, storeVerifierKey }
|
package/src/commands/settings.js
CHANGED
|
@@ -4,9 +4,11 @@
|
|
|
4
4
|
const { apiCall } = require('../api-client')
|
|
5
5
|
const { resolveDeployment } = require('../deployments')
|
|
6
6
|
const { finishMutation, requestKeyHeaders } = require('./operations')
|
|
7
|
-
const { parseSetFlags, readSettingsFile, mergePatches, checkPatch, formatSchema, formatSettings, formatChanges, PROTECTED_ENVS } = require('../settings')
|
|
7
|
+
const { parseSetFlags, readSettingsFile, mergePatches, checkPatch, formatSchema, formatSettings, formatChanges, readableSchema, PROTECTED_ENVS } = require('../settings')
|
|
8
8
|
const { readManifest, environmentSettings } = require('../release-manifest')
|
|
9
9
|
const { compareEnvironments, formatComparison } = require('../env-compare')
|
|
10
|
+
const { refuseManagedLoginDomainSettings, admitLoginDomainChanges, loginDomainChecklist } = require('../login-domain')
|
|
11
|
+
const { USER_SERVICE, signInChange, signInRefusalHint } = require('../login-methods')
|
|
10
12
|
|
|
11
13
|
const USAGE = 'usage: saaslayer settings <schema|get|set|diff> … (see saaslayer --help)'
|
|
12
14
|
|
|
@@ -39,7 +41,7 @@ async function readDeploymentSettings(flags) {
|
|
|
39
41
|
*/
|
|
40
42
|
async function fetchSchema(module, revision, flags) {
|
|
41
43
|
const doc = await apiCall('GET', `/api/modules/${encodeURIComponent(module)}/settings-schema?revision=${encodeURIComponent(revision)}`, undefined, flags)
|
|
42
|
-
return doc.data.attributes
|
|
44
|
+
return readableSchema(doc.data.attributes)
|
|
43
45
|
}
|
|
44
46
|
|
|
45
47
|
/** `settings schema --module M [--revision SHA]`; without --revision, the revision the selected deployment runs. @param {object} flags */
|
|
@@ -74,26 +76,40 @@ async function settingsGet(flags) {
|
|
|
74
76
|
async function applySettings(input, flags) {
|
|
75
77
|
const { deployment, settings } = await readDeploymentSettings(flags)
|
|
76
78
|
const schemas = Object.fromEntries(settings.modules.filter((m) => !m.schemaError).map((m) => [m.module, { module: m.module, revision: m.revision, settings: m.settings }]))
|
|
77
|
-
const
|
|
79
|
+
const current = Object.fromEntries(settings.modules.map((m) => [m.module, Object.fromEntries(m.settings.map((s) => [s.name, s]))]))
|
|
80
|
+
const { patch, billing, security } = checkPatch(input, schemas, { op: 'update', current })
|
|
81
|
+
refuseManagedLoginDomainSettings(patch)
|
|
82
|
+
const signIn = patch[USER_SERVICE] ? signInChange({ op: 'update', values: patch[USER_SERVICE], current: current[USER_SERVICE], env: deployment.env }) : null
|
|
83
|
+
if (signIn && signIn.problems.length) throw new Error(signIn.problems.join('\n'))
|
|
78
84
|
const reason = typeof flags.reason === 'string' ? flags.reason : undefined
|
|
85
|
+
if (!reason && signIn && signIn.added.length) throw new Error(`${USER_SERVICE} adds ${signIn.added.map((a) => a.loginMethod).join(' and ')} sign-in, which cannot be turned off and has costs: pass --reason <text>`)
|
|
79
86
|
if (!reason && billing.length) throw new Error(`${billing.join(', ')} changes billing: pass --reason <text>`)
|
|
87
|
+
if (!reason && security.length) throw new Error(`${security.join(', ')} changes security: pass --reason <text>`)
|
|
80
88
|
if (!reason && PROTECTED_ENVS.has(deployment.env)) throw new Error(`${deployment.env} is a protected environment: pass --reason <text>`)
|
|
89
|
+
const { domainHandoff, handoffs } = await admitLoginDomainChanges({ patch, settings, deploymentId: deployment.deploymentId, flags })
|
|
81
90
|
console.log(`Changing settings of ${deployment.deploymentId} (settings revision ${settings.settingsRevision}):`)
|
|
82
91
|
for (const line of formatChanges(patch, settings)) console.log(line)
|
|
83
|
-
const
|
|
92
|
+
for (const line of signIn ? signIn.preview : []) console.log(` ${line}`)
|
|
93
|
+
const attributes = { expectedRevision: settings.settingsRevision, settings: patch, ...(reason ? { reason } : {}), ...(domainHandoff ? { domainHandoff } : {}) }
|
|
84
94
|
let res
|
|
85
95
|
try {
|
|
86
96
|
res = await apiCall('PATCH', `/api/deployments/${encodeURIComponent(deployment.deploymentId)}/settings`, { data: { type: 'deployment-settings', attributes } }, flags, { headers: requestKeyHeaders() })
|
|
87
97
|
} catch (err) {
|
|
88
98
|
if (err.status === 409) err.message += `\nthe settings changed after they were read (revision ${settings.settingsRevision}): check them with \`saaslayer settings get\` and run the command again`
|
|
99
|
+
const hint = signInRefusalHint(err, deployment.env)
|
|
100
|
+
if (hint) err.message += `\n${hint}`
|
|
89
101
|
throw err
|
|
90
102
|
}
|
|
91
103
|
const written = res.data.attributes
|
|
92
104
|
console.log(`✅ settings revision ${settings.settingsRevision} → ${written.settingsRevision} (operation ${written.operationId})`)
|
|
105
|
+
if (handoffs.length > 0) {
|
|
106
|
+
console.log('Login domain handoff: the confirmation acknowledges what breaks; finish each step:')
|
|
107
|
+
for (const line of loginDomainChecklist(handoffs)) console.log(line)
|
|
108
|
+
}
|
|
93
109
|
return finishMutation({ response: res, deploymentId: deployment.deploymentId, flags })
|
|
94
110
|
}
|
|
95
111
|
|
|
96
|
-
/** `settings set --env E (--set M.S=V … | --file F) [--reason T]`. @param {object} flags */
|
|
112
|
+
/** `settings set --env E (--set M.S=V … | --file F) [--reason T] [--domain-handoff --confirm-domain D]`. @param {object} flags */
|
|
97
113
|
async function settingsSet(flags) {
|
|
98
114
|
const patch = mergePatches(typeof flags.file === 'string' ? readSettingsFile(flags.file) : undefined, parseSetFlags(flags.set, '--set'))
|
|
99
115
|
if (!patch) throw new Error('settings set needs --set <module>.<Setting>=<value> or --file <settings.json>')
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// `saaslayer sms register` and `saaslayer sms status` (cloud-prem): register the foundation's toll-free number with
|
|
2
|
+
// AWS from prompts or registration.json, and show what still stands between the account and delivered SMS.
|
|
3
|
+
'use strict'
|
|
4
|
+
const fs = require('fs')
|
|
5
|
+
const path = require('path')
|
|
6
|
+
const { execFileSync } = require('child_process')
|
|
7
|
+
const { jsonApiCall } = require('../api-client')
|
|
8
|
+
const { ask: promptAsk } = require('../prompt')
|
|
9
|
+
const { describeStack } = require('../foundation-change-set')
|
|
10
|
+
const { foundationRegionStackName } = require('./aws')
|
|
11
|
+
const { cloudPremTarget } = require('../sms/scope')
|
|
12
|
+
const { smsNumberOf } = require('../sms/number')
|
|
13
|
+
const { recordLandedRelease } = require('../sms/release')
|
|
14
|
+
const { resolveFields, isRequired, answerAt, withAnswer, answersFromValues } = require('../sms/registration-fields')
|
|
15
|
+
const { validateRegistration } = require('../sms/registration-validate')
|
|
16
|
+
const sms = require('../sms/registration')
|
|
17
|
+
const { smsStatusReport, formatSmsStatus } = require('../sms/status')
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @typedef {{ api?: typeof jsonApiCall, exec?: (cmd: string, args: string[]) => string, sms?: import('../sms/registration').SmsClient,
|
|
21
|
+
* fetch?: import('../sms/registration-validate').Fetch, ask?: (q: string) => Promise<string>, interactive?: boolean,
|
|
22
|
+
* cwd?: string, sleep?: (ms: number) => Promise<void>, log?: (...a: unknown[]) => void, err?: (...a: unknown[]) => void }} Deps
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/** @param {string} cmd @param {string[]} args */
|
|
26
|
+
const defaultExec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 16 * 1024 * 1024 })
|
|
27
|
+
const REVIEW_TIME = 'AWS review takes up to 15 business days'
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The account, region and sending number a command acts on, after the cloud-prem checks.
|
|
31
|
+
* @param {Record<string, any>} flags @param {string} command @param {Required<Pick<Deps, 'api'|'exec'|'err'>> & Deps} d
|
|
32
|
+
*/
|
|
33
|
+
async function smsContext(flags, command, d) {
|
|
34
|
+
const { target, aws } = await cloudPremTarget(flags, command, { api: d.api, exec: d.exec, log: d.err })
|
|
35
|
+
const stack = describeStack(aws, foundationRegionStackName(target.region))
|
|
36
|
+
const arn = stack ? smsNumberOf(stack).arn : null
|
|
37
|
+
const client = d.sms || sms.createSmsClient({ region: target.region, profile: flags.profile })
|
|
38
|
+
return { target, stack, arn, client }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** @param {Deps} deps */
|
|
42
|
+
function withDefaults(deps) {
|
|
43
|
+
return {
|
|
44
|
+
api: jsonApiCall, exec: defaultExec, fetch: globalThis.fetch, ask: promptAsk, interactive: Boolean(process.stdin.isTTY),
|
|
45
|
+
cwd: process.cwd(), sleep: (ms) => new Promise((r) => setTimeout(r, ms)), log: console.log, err: console.error, ...deps,
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Ask for each field's answer; Enter keeps the shown value; a required field is asked again until answered.
|
|
51
|
+
* @param {import('../sms/registration-fields').ResolvedField[]} fields @param {object} current @param {(q: string) => Promise<string>} ask
|
|
52
|
+
*/
|
|
53
|
+
async function promptAnswers(fields, current, ask) {
|
|
54
|
+
let answers = current
|
|
55
|
+
for (const field of fields) {
|
|
56
|
+
if (field.derive) continue
|
|
57
|
+
const shown = answerAt(current, field.key)
|
|
58
|
+
const options = field.type === 'SELECT' && field.key !== 'monthlyVolume' ? ` (choices: ${((field.definition.SelectValidation || {}).Options || []).join(', ')})` : ''
|
|
59
|
+
const hint = field.type === 'ATTACHMENT' ? ' (PNG file or https URL)' : field.key === 'monthlyVolume' ? ' (messages per month)' : ''
|
|
60
|
+
for (;;) {
|
|
61
|
+
const required = isRequired(field, answers)
|
|
62
|
+
const reply = await ask(`${field.title}${required ? '' : ' (optional)'}${options}${hint}${shown !== undefined ? ` [${shown}]` : ''}: `)
|
|
63
|
+
const value = reply === '' ? shown : reply
|
|
64
|
+
if ((value === undefined || value === '') && required) continue
|
|
65
|
+
if (value !== undefined && value !== '') answers = withAnswer(answers, field.key, field.key === 'monthlyVolume' ? Number(String(value).replace(/[^0-9]/g, '')) : value)
|
|
66
|
+
break
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return answers
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The answers for `fields`: from --file (only those fields' keys are taken) or asked in a terminal.
|
|
74
|
+
* @param {Record<string, any>} flags @param {import('../sms/registration-fields').ResolvedField[]} fields @param {object} current
|
|
75
|
+
* @param {ReturnType<typeof withDefaults>} d
|
|
76
|
+
*/
|
|
77
|
+
async function collectAnswers(flags, fields, current, d) {
|
|
78
|
+
if (typeof flags.file === 'string') {
|
|
79
|
+
const file = path.resolve(d.cwd, flags.file)
|
|
80
|
+
let doc
|
|
81
|
+
try { doc = JSON.parse(fs.readFileSync(file, 'utf8')) } catch (e) { throw new Error(`cannot read ${file} as JSON: ${e.message}`) }
|
|
82
|
+
let answers = current
|
|
83
|
+
for (const field of fields) {
|
|
84
|
+
const value = answerAt(doc, field.key)
|
|
85
|
+
if (value !== undefined) answers = withAnswer(answers, field.key, value)
|
|
86
|
+
}
|
|
87
|
+
// The file's samples list replaces the current one when samples are being written.
|
|
88
|
+
if (fields.some((f) => f.key.startsWith('samples.')) && Array.isArray(doc.samples)) answers = withAnswer(answers, 'samples', doc.samples)
|
|
89
|
+
return { answers, cwd: path.dirname(file) }
|
|
90
|
+
}
|
|
91
|
+
if (!d.interactive) throw new Error('sms register needs answers: pass --file registration.json when not running in a terminal')
|
|
92
|
+
return { answers: await promptAnswers(fields, current, d.ask), cwd: d.cwd }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** @param {Array<Record<string, any>>} reasons @param {(...a: unknown[]) => void} log */
|
|
96
|
+
function logReasons(reasons, log) {
|
|
97
|
+
for (const r of reasons) log(` ${r.Reason}: ${r.ShortDescription || ''}${r.DocumentationLink ? ` (${r.DocumentationLink})` : ''}`)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* `saaslayer sms register --env <env> [--file registration.json]`: create or resume the number's toll-free registration,
|
|
102
|
+
* validate and fill it, attach the opt-in evidence, associate the number and submit; resubmit after REQUIRES_UPDATES.
|
|
103
|
+
* @param {Record<string, any>} flags @param {Deps} [deps]
|
|
104
|
+
* @returns {Promise<{ registrationId: string|null, status: string|null, changed: boolean }>}
|
|
105
|
+
*/
|
|
106
|
+
async function smsRegister(flags, deps = {}) {
|
|
107
|
+
const d = withDefaults(deps)
|
|
108
|
+
const { target, arn, client } = await smsContext(flags, 'sms register', d)
|
|
109
|
+
if (!arn) throw new Error(`no SMS sending number in account ${target.accountId} (${target.region}): run \`saaslayer sms setup --env ${target.env}\` first`)
|
|
110
|
+
const number = await sms.describeNumber(client, arn)
|
|
111
|
+
if (number.NumberType === 'SIMULATOR') {
|
|
112
|
+
d.log(`${number.PhoneNumberId} is a simulator number; it needs no registration (it delivers to simulator destinations only)`)
|
|
113
|
+
return { registrationId: null, status: null, changed: false }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const { registration: found, ended } = await sms.findRegistration(client, number)
|
|
117
|
+
if (found && !sms.EDITABLE_STATUSES.includes(found.RegistrationStatus)) {
|
|
118
|
+
d.log(`${found.RegistrationId} is ${found.RegistrationStatus}; nothing to change. Check progress with \`saaslayer sms status --env ${target.env}\`.`)
|
|
119
|
+
return { registrationId: found.RegistrationId, status: found.RegistrationStatus, changed: false }
|
|
120
|
+
}
|
|
121
|
+
const fields = resolveFields(await sms.fieldDefinitions(client))
|
|
122
|
+
|
|
123
|
+
let version = found ? found.CurrentVersionNumber : 1
|
|
124
|
+
let toWrite = fields
|
|
125
|
+
let current = found ? await sms.fieldValues(client, found.RegistrationId, version) : []
|
|
126
|
+
let needsVersion = false
|
|
127
|
+
if (found && found.RegistrationStatus === 'REQUIRES_UPDATES') {
|
|
128
|
+
const id = found.RegistrationId
|
|
129
|
+
const denied = found.LatestDeniedVersionNumber || version
|
|
130
|
+
const deniedVersion = await sms.describeVersion(client, id, denied)
|
|
131
|
+
const deniedValues = await sms.fieldValues(client, id, denied)
|
|
132
|
+
d.log(`AWS sent ${id} back for updates (version ${denied}):`)
|
|
133
|
+
logReasons((deniedVersion && deniedVersion.DeniedReasons) || [], d.log)
|
|
134
|
+
const flagged = deniedValues.filter((v) => v.DeniedReason)
|
|
135
|
+
for (const v of flagged) {
|
|
136
|
+
const field = fields.find((f) => f.path === v.FieldPath)
|
|
137
|
+
d.log(` ${field ? `${field.key} (${field.title})` : v.FieldPath}: ${v.DeniedReason}`)
|
|
138
|
+
}
|
|
139
|
+
// Only the flagged fields are asked again; with none flagged, every field is.
|
|
140
|
+
const flaggedPaths = flagged.map((v) => v.FieldPath)
|
|
141
|
+
toWrite = flaggedPaths.length ? fields.filter((f) => flaggedPaths.includes(f.path)) : fields
|
|
142
|
+
current = deniedValues
|
|
143
|
+
const latest = await sms.describeVersion(client, id, version)
|
|
144
|
+
needsVersion = !latest || latest.RegistrationVersionStatus !== 'DRAFT'
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Every answer is checked before anything (the registration included) is written.
|
|
148
|
+
const { answers, cwd } = await collectAnswers(flags, toWrite.filter((f) => !f.derive), answersFromValues(fields, current), d)
|
|
149
|
+
const checked = await validateRegistration(answers, toWrite, { fetch: d.fetch, cwd })
|
|
150
|
+
if (checked.errors.length) throw new Error(`registration answers need fixing (nothing was sent to AWS):\n ${checked.errors.join('\n ')}`)
|
|
151
|
+
|
|
152
|
+
const registration = found || (await sms.createRegistration(client, number, ended))
|
|
153
|
+
const id = registration.RegistrationId
|
|
154
|
+
d.log(`${found ? 'resuming' : 'created'} registration ${id} (${registration.RegistrationStatus}) for ${number.PhoneNumber || number.PhoneNumberId}`)
|
|
155
|
+
if (needsVersion) {
|
|
156
|
+
version = (await sms.newVersion(client, id)).VersionNumber
|
|
157
|
+
current = await sms.fieldValues(client, id, version)
|
|
158
|
+
}
|
|
159
|
+
const attachmentId = checked.attachment ? await sms.uploadAttachment(client, checked.attachment, number.PhoneNumberId, d.sleep) : null
|
|
160
|
+
const written = await sms.writeFields(client, id, toWrite, answers, { attachmentId, current: needsVersion ? current.map(({ DeniedReason, ...v }) => v) : current })
|
|
161
|
+
if (await sms.ensureAssociation(client, id, number)) d.log(`associated ${number.PhoneNumber || number.PhoneNumberId} with ${id}`)
|
|
162
|
+
const submitted = await sms.submitVersion(client, id)
|
|
163
|
+
d.log(`submitted ${id} version ${submitted.VersionNumber || version} (${written.length} field(s) written); ${REVIEW_TIME}. Check progress with \`saaslayer sms status --env ${target.env}\`.`)
|
|
164
|
+
return { registrationId: id, status: submitted.RegistrationVersionStatus || 'SUBMITTED', changed: true }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* `saaslayer sms status --env <env> [--json]`: number, registration, sandbox/production, spend limit, what is missing
|
|
169
|
+
* (as readiness codes) and the support requests AWS has no API for. An unfinished release is moved forward as far as the
|
|
170
|
+
* stack's actual state allows (plan §5 step 5) and shown with the command that resumes it.
|
|
171
|
+
* @param {Record<string, any>} flags @param {Deps} [deps]
|
|
172
|
+
*/
|
|
173
|
+
async function smsStatus(flags, deps = {}) {
|
|
174
|
+
const d = withDefaults(deps)
|
|
175
|
+
const { target, stack, arn, client } = await smsContext(flags, 'sms status', d)
|
|
176
|
+
const release = await recordLandedRelease({ api: d.api, target, flags, stack })
|
|
177
|
+
const report = await smsStatusReport({ target, arn, sms: client, release })
|
|
178
|
+
d.log(flags.json ? JSON.stringify(report, null, 2) : formatSmsStatus(report).join('\n'))
|
|
179
|
+
return report
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
module.exports = { smsRegister, smsStatus }
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// `saaslayer sms setup|release` (cloud-prem): install the account's SMS sending number on the region foundation (toll-free,
|
|
2
|
+
// or dev-only simulator) and retire it as a resumable control-plane release (plan §3, §5); routes `sms register|status`.
|
|
3
|
+
'use strict'
|
|
4
|
+
const { execFileSync } = require('child_process')
|
|
5
|
+
const { jsonApiCall } = require('../api-client')
|
|
6
|
+
const { confirm: promptConfirm } = require('../prompt')
|
|
7
|
+
const { describeStack, applyRegionFoundation, waitForStack } = require('../foundation-change-set')
|
|
8
|
+
const { FOUNDATION_REGION_TEMPLATE, foundationRegionStackName } = require('./aws')
|
|
9
|
+
const { cloudPremTarget, smsReleasePath } = require('../sms/scope')
|
|
10
|
+
const { SMS_NUMBER_COST, smsNumberOf, logSmsNextSteps } = require('../sms/number')
|
|
11
|
+
const { isUnfinished, readRelease, advanceRelease, numberRemoved } = require('../sms/release')
|
|
12
|
+
const { createSmsClient, describeNumber, findRegistration, deleteRegistration } = require('../sms/registration')
|
|
13
|
+
|
|
14
|
+
/** @param {string} cmd @param {string[]} args */
|
|
15
|
+
const defaultExec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 16 * 1024 * 1024 })
|
|
16
|
+
const DEFAULT_WAIT = { sleep: (ms) => new Promise((r) => setTimeout(r, ms)), pollMs: 5000, maxPolls: 720 }
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @typedef {{ exec?: typeof defaultExec, api?: typeof jsonApiCall, confirm?: (q: string) => Promise<boolean>,
|
|
20
|
+
* log?: (...a: unknown[]) => void, wait?: import('../foundation-change-set').Wait,
|
|
21
|
+
* sms?: import('../sms/registration').SmsClient }} Deps
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** The region foundation stack of the target, refused when the account was never connected in that region. */
|
|
25
|
+
function regionStack(aws, target) {
|
|
26
|
+
const stack = describeStack(aws, foundationRegionStackName(target.region))
|
|
27
|
+
if (!stack) throw new Error(`${foundationRegionStackName(target.region)} is not installed in ${target.accountId}; connect the account in ${target.region} first: saaslayer aws connect --aws-account ${target.accountId} --region ${target.region}`)
|
|
28
|
+
return stack
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* `saaslayer sms setup --env <env> [--region R] [--simulator] [--yes]`: install the toll-free (or, dev only, simulator)
|
|
33
|
+
* sending number on the region foundation of the env's account and region. Returns null when the prompt is declined.
|
|
34
|
+
* @param {object} flags @param {Deps} [deps]
|
|
35
|
+
*/
|
|
36
|
+
async function smsSetup(flags, { exec = defaultExec, api = jsonApiCall, confirm = promptConfirm, log = console.log, wait = DEFAULT_WAIT } = {}) {
|
|
37
|
+
const simulator = flags.simulator === true
|
|
38
|
+
const numberType = simulator ? 'simulator' : 'toll-free'
|
|
39
|
+
const { target, aws } = await cloudPremTarget(flags, 'sms setup', { api, exec })
|
|
40
|
+
if (simulator && target.env !== 'dev') throw new Error(`--simulator is for dev only (plan §5a); --env is ${target.env}`)
|
|
41
|
+
if (simulator && target.protectedDeployments) {
|
|
42
|
+
throw new Error(`--simulator refused: ${target.accountId} has staging or prod deployments; a simulator number belongs in a dev or test account`)
|
|
43
|
+
}
|
|
44
|
+
const stackName = foundationRegionStackName(target.region)
|
|
45
|
+
const installed = smsNumberOf(regionStack(aws, target))
|
|
46
|
+
if (installed.numberType === numberType && installed.arn) {
|
|
47
|
+
log(`${target.accountId} ${target.region} already has a ${numberType} SMS number.`)
|
|
48
|
+
logSmsNextSteps(log, { arn: installed.arn, env: target.env, numberType })
|
|
49
|
+
return { arn: installed.arn, numberType, accountId: target.accountId, region: target.region, changed: false }
|
|
50
|
+
}
|
|
51
|
+
if (installed.numberType !== 'none') {
|
|
52
|
+
throw new Error(`${target.accountId} ${target.region} already has a ${installed.numberType} SMS number (one per account and region); to replace it: saaslayer sms release --env ${target.env} first, then saaslayer sms setup`)
|
|
53
|
+
}
|
|
54
|
+
const release = await readRelease(api, target, flags)
|
|
55
|
+
if (release && isUnfinished(release.phase)) {
|
|
56
|
+
throw new Error(`an SMS release of ${release.phoneNumberArn} is ${release.phase}; finish it first: saaslayer sms release --env ${target.env}`)
|
|
57
|
+
}
|
|
58
|
+
if (release && release.phase === 'done' && !simulator) {
|
|
59
|
+
log(`A number was released here before: setting SMS up again buys a new number and needs a new registration (AWS review: up to 15 business days).`)
|
|
60
|
+
}
|
|
61
|
+
const what = simulator ? 'a simulator number (dev testing only, sends to AWS simulator destinations)' : 'a US toll-free number'
|
|
62
|
+
log(`This installs ${what} in ${target.accountId} ${target.region} through ${stackName}.`)
|
|
63
|
+
if (!flags.yes && !(await confirm(`AWS bills the number ${SMS_NUMBER_COST} to ${target.accountId} while it exists. Install it?`))) {
|
|
64
|
+
log('Nothing changed.')
|
|
65
|
+
return null
|
|
66
|
+
}
|
|
67
|
+
await applyRegionFoundation({ aws, stackName, templateFile: FOUNDATION_REGION_TEMPLATE, overrides: { SmsOriginationNumberType: numberType }, wait, log })
|
|
68
|
+
const { arn } = smsNumberOf(regionStack(aws, target))
|
|
69
|
+
if (!arn) throw new Error(`${stackName} updated but reports no SmsOriginationIdentityArn; check the stack in the CloudFormation console`)
|
|
70
|
+
logSmsNextSteps(log, { arn, env: target.env, numberType })
|
|
71
|
+
return { arn, numberType, accountId: target.accountId, region: target.region, changed: true }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Waits out an in-progress stack operation, then returns the stack. */
|
|
75
|
+
async function settledStack(aws, target, wait) {
|
|
76
|
+
const stack = regionStack(aws, target)
|
|
77
|
+
if (!/_IN_PROGRESS$/.test(stack.StackStatus)) return stack
|
|
78
|
+
try { await waitForStack(aws, stack.StackName || foundationRegionStackName(target.region), 'UPDATE', wait) } catch { /* its final state is read below */ }
|
|
79
|
+
return regionStack(aws, target)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* `saaslayer sms release --env <env> [--yes]` (plan §5): lock and record first, reference check under the lock, confirm,
|
|
84
|
+
* release the number (parameter -> none), then delete its registration. Every step is recorded in the control plane, so a
|
|
85
|
+
* re-run from any machine resumes from the recorded phase; the lock is kept while CloudFormation's outcome is uncertain.
|
|
86
|
+
* @param {object} flags @param {Deps} [deps]
|
|
87
|
+
*/
|
|
88
|
+
async function smsRelease(flags, { exec = defaultExec, api = jsonApiCall, confirm = promptConfirm, log = console.log, wait = DEFAULT_WAIT, sms } = {}) {
|
|
89
|
+
const { target, aws } = await cloudPremTarget(flags, 'sms release', { api, exec })
|
|
90
|
+
const client = sms || createSmsClient({ region: target.region, profile: flags.profile })
|
|
91
|
+
const path = smsReleasePath(target)
|
|
92
|
+
const advance = (from, phase) => advanceRelease(api, target, flags, from, phase)
|
|
93
|
+
|
|
94
|
+
let record = await readRelease(api, target, flags)
|
|
95
|
+
if (record && isUnfinished(record.phase)) {
|
|
96
|
+
log(`Resuming the SMS release of ${record.phoneNumberArn} (${record.phase}).`)
|
|
97
|
+
} else {
|
|
98
|
+
const number = smsNumberOf(regionStack(aws, target))
|
|
99
|
+
if (!number.arn) {
|
|
100
|
+
log(`${target.accountId} ${target.region} has no SMS number; nothing to release.`)
|
|
101
|
+
return { phase: null }
|
|
102
|
+
}
|
|
103
|
+
// The number's registration: the one AWS associated with it, else the live one tagged for it (plan §4 step 1).
|
|
104
|
+
const registration = number.numberType === 'simulator' ? null : (await findRegistration(client, await describeNumber(client, number.arn))).registration
|
|
105
|
+
const registrationId = registration ? registration.RegistrationId : null
|
|
106
|
+
record = (await api('POST', path, { data: { type: 'sms-releases', attributes: { phoneNumberId: number.phoneNumberId, phoneNumberArn: number.arn, registrationId, numberType: number.numberType } } }, flags)).data.attributes
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (record.phase === 'checking') {
|
|
110
|
+
if (!record.referenceCheckedAt) {
|
|
111
|
+
try {
|
|
112
|
+
record = (await api('POST', `${path}/reference-check`, undefined, flags)).data.attributes
|
|
113
|
+
} catch (err) {
|
|
114
|
+
const first = err.body && Array.isArray(err.body.errors) ? err.body.errors[0] : null
|
|
115
|
+
if (first && first.code === 'SMS_ORIGINATION_IN_USE') {
|
|
116
|
+
const { references = [], otherReferences = 0 } = first.meta || {}
|
|
117
|
+
log(`Release refused: deployments still use ${record.phoneNumberArn}.`)
|
|
118
|
+
for (const r of references) log(` ${r.deploymentId} project ${r.customerId || '—'} env ${r.environment || '—'} ${r.services.join(', ')}${r.inFlight ? ' (run in flight)' : ''}`)
|
|
119
|
+
if (otherReferences) log(` and ${otherReferences} in projects you cannot see`)
|
|
120
|
+
throw new Error('point those deployments at another number (or remove PhoneSmsOriginationIdentity) first; nothing was released')
|
|
121
|
+
}
|
|
122
|
+
// Fail closed: nothing is released. Drop the lock if the control plane answers; a re-run starts over otherwise.
|
|
123
|
+
await advance('checking', 'refused').catch(() => {})
|
|
124
|
+
throw new Error(`the reference check could not complete (${err.message}); nothing was released`)
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const loses = record.registrationId ? `its registration ${record.registrationId} (approved or not) is deleted, and ` : ''
|
|
128
|
+
log(`Releasing ${record.phoneNumberArn} (${record.numberType}) in ${target.accountId} ${target.region}: AWS deletes the number, ${loses}a new number needs a new registration (AWS review: up to 15 business days).`)
|
|
129
|
+
if (!flags.yes && !(await confirm('Release this number?'))) {
|
|
130
|
+
await advance('checking', 'refused')
|
|
131
|
+
log('Nothing released.')
|
|
132
|
+
return { phase: 'refused' }
|
|
133
|
+
}
|
|
134
|
+
record = await advance('checking', 'releasing-number')
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (record.phase === 'releasing-number') {
|
|
138
|
+
const stack = await settledStack(aws, target, wait)
|
|
139
|
+
if (!numberRemoved(stack)) {
|
|
140
|
+
const stackName = foundationRegionStackName(target.region)
|
|
141
|
+
try {
|
|
142
|
+
await applyRegionFoundation({ aws, stackName, templateFile: FOUNDATION_REGION_TEMPLATE, overrides: { SmsOriginationNumberType: 'none' }, wait, log, allowSmsNumberRemoval: true })
|
|
143
|
+
} catch (err) {
|
|
144
|
+
throw new Error(`the number release did not finish (${err.message}); the release keeps its lock. Re-run saaslayer sms release --env ${target.env} (from any machine) once ${stackName} has settled`)
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
record = await advance('releasing-number', 'number-released')
|
|
148
|
+
log(`Number released: ${record.phoneNumberArn} is deleted and no longer billed.`)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (record.phase === 'number-released') {
|
|
152
|
+
record = await advance('number-released', record.registrationId ? 'deleting-registration' : 'done')
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (record.phase === 'deleting-registration') {
|
|
156
|
+
try {
|
|
157
|
+
await deleteRegistration(client, record.registrationId)
|
|
158
|
+
} catch (err) {
|
|
159
|
+
throw new Error(`number released, registration cleanup pending: deleting ${record.registrationId} failed (${err.message}). Re-run saaslayer sms release --env ${target.env} (from any machine) to finish`)
|
|
160
|
+
}
|
|
161
|
+
record = await advance('deleting-registration', 'done')
|
|
162
|
+
log(`Registration ${record.registrationId} deleted.`)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
if (record.phase === 'done') log(`SMS release done; the lock on ${target.accountId} ${target.region} is dropped. To send again: saaslayer sms setup --env ${target.env} (a new number and registration).`)
|
|
166
|
+
return { phase: record.phase }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** @param {string} sub @param {object} flags */
|
|
170
|
+
async function smsCommand(sub, flags) {
|
|
171
|
+
if (sub === 'setup') return smsSetup(flags)
|
|
172
|
+
if (sub === 'release') return smsRelease(flags)
|
|
173
|
+
if (sub === 'register') return require('./sms-registration').smsRegister(flags)
|
|
174
|
+
if (sub === 'status') return require('./sms-registration').smsStatus(flags)
|
|
175
|
+
throw new Error('usage: saaslayer sms <setup|register|status|release> --env <env> [--region R] (see saaslayer --help)')
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
module.exports = { smsSetup, smsRelease, smsCommand }
|