saaslayer 0.2.0 → 0.4.0

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 (68) hide show
  1. package/README.md +132 -16
  2. package/bin/saaslayer.js +387 -61
  3. package/package.json +3 -2
  4. package/src/api-client.js +37 -1
  5. package/src/aws-sigv4.js +74 -26
  6. package/src/cognito-user-api.js +80 -0
  7. package/src/commands/access-admins.js +2 -2
  8. package/src/commands/account-email.js +43 -0
  9. package/src/commands/admin-allowlist.js +65 -0
  10. package/src/commands/api-keys.js +83 -0
  11. package/src/commands/audit.js +77 -0
  12. package/src/commands/aws.js +355 -82
  13. package/src/commands/binding-handoff.js +174 -0
  14. package/src/commands/bindings.js +111 -0
  15. package/src/commands/catalog.js +30 -3
  16. package/src/commands/deploy.js +33 -10
  17. package/src/commands/env-export.js +58 -0
  18. package/src/commands/first-admin.js +15 -4
  19. package/src/commands/foundation.js +75 -117
  20. package/src/commands/hooks.js +271 -0
  21. package/src/commands/integration-credentials.js +1 -1
  22. package/src/commands/lifecycle.js +149 -24
  23. package/src/commands/login-domain.js +259 -0
  24. package/src/commands/login.js +53 -16
  25. package/src/commands/org-members.js +109 -0
  26. package/src/commands/permission-orgs.js +80 -0
  27. package/src/commands/release-manifest.js +17 -8
  28. package/src/commands/service-principals.js +42 -5
  29. package/src/commands/settings.js +21 -5
  30. package/src/commands/sms-registration.js +182 -0
  31. package/src/commands/sms.js +178 -0
  32. package/src/commands/social.js +265 -0
  33. package/src/commands/support-staff.js +72 -0
  34. package/src/commands/trust-policies.js +172 -0
  35. package/src/commands/users-management.js +2 -20
  36. package/src/commands/users.js +56 -11
  37. package/src/commands/versions.js +61 -0
  38. package/src/connection-proof.js +41 -0
  39. package/src/deployment-api-auth.js +166 -8
  40. package/src/deployments.js +1 -1
  41. package/src/foundation-change-set.js +180 -0
  42. package/src/foundation-home.js +121 -0
  43. package/src/foundation-template.js +51 -10
  44. package/src/foundation-trust-write.js +379 -0
  45. package/src/iam-session.js +14 -8
  46. package/src/login-domain.js +139 -0
  47. package/src/login-methods.js +118 -0
  48. package/src/module-catalog.js +3 -2
  49. package/src/permissions-request.js +15 -9
  50. package/src/release-manifest.js +11 -4
  51. package/src/scope.js +3 -1
  52. package/src/settings.js +85 -13
  53. package/src/sms/number.js +37 -0
  54. package/src/sms/registration-fields.js +167 -0
  55. package/src/sms/registration-validate.js +151 -0
  56. package/src/sms/registration.js +216 -0
  57. package/src/sms/release.js +55 -0
  58. package/src/sms/scope.js +86 -0
  59. package/src/sms/status.js +181 -0
  60. package/src/ssm-api.js +31 -0
  61. package/src/trust-entries.js +350 -0
  62. package/src/user-service-instance.js +27 -0
  63. package/src/users-api.js +55 -8
  64. package/src/users-import/checkpoint.js +76 -0
  65. package/src/users-import/import.js +233 -24
  66. package/src/versions.js +80 -0
  67. package/templates/saaslayer-foundation-region.yml +45 -1
  68. package/templates/saaslayer-foundation.yml +747 -296
@@ -0,0 +1,167 @@
1
+ // The US toll-free registration form as `saaslayer sms register` fills it: each registration.json answer, the AWS field
2
+ // it goes to, and how its value is written, resolved against AWS's own DescribeRegistrationFieldDefinitions.
3
+ 'use strict'
4
+
5
+ const REGISTRATION_TYPE = 'US_TOLL_FREE_REGISTRATION'
6
+
7
+ /**
8
+ * @typedef {'TEXT'|'SELECT'|'ATTACHMENT'} FieldType
9
+ * @typedef {{ key: string, path: string|null, title: string, type: FieldType, required: boolean|((answers: object) => boolean),
10
+ * derive?: (answers: object, options: string[]) => string|undefined, select?: (answer: unknown, options: string[]) => string|undefined }} Field
11
+ * @typedef {Field & { path: string, definition: Record<string, any> }} ResolvedField
12
+ */
13
+
14
+ /** Lowercase letters and digits only: compares AWS titles and select options loosely. @param {unknown} s */
15
+ const loose = (s) => String(s == null ? '' : s).toLowerCase().replace(/\(?optional\)?/g, '').replace(/[^a-z0-9]/g, '')
16
+
17
+ /** The option matching an answer loosely (`Private profit` ↔ `PRIVATE_PROFIT`). @param {unknown} answer @param {string[]} options */
18
+ function matchOption(answer, options) {
19
+ if (answer === undefined || answer === null || answer === '') return undefined
20
+ return options.find((o) => loose(o) === loose(answer))
21
+ }
22
+
23
+ /** The smallest volume bucket that holds the expected monthly count (`1000` → `1,000`). @param {unknown} answer @param {string[]} options */
24
+ function volumeOption(answer, options) {
25
+ const n = Number(answer)
26
+ if (!Number.isInteger(n) || n <= 0) return undefined
27
+ const buckets = options.map((o) => ({ o, n: Number(String(o).replace(/[^0-9]/g, '')) })).sort((a, b) => a.n - b.n)
28
+ const fit = buckets.find((b) => b.n >= n)
29
+ return (fit || buckets[buckets.length - 1] || {}).o
30
+ }
31
+
32
+ /** Login codes are one-time passcodes; AWS names that category a few ways across its forms. */
33
+ const USE_CASE_CATEGORIES = ['One-time passcodes', 'One time passcodes', 'One-time passwords', 'Two-factor authentication']
34
+ const DEFAULT_OPT_IN_CATEGORY = 'Digital form'
35
+ /** A sole proprietor has no company identification number (AWS: required for every other business type). */
36
+ const needsCompanyId = (answers) => loose(answers && answers.company && answers.company.businessType) !== 'soleproprietor'
37
+
38
+ /**
39
+ * Every field the CLI fills. `path` is the FieldPath from the AWS docs (the toll-free automation guide); fields the
40
+ * console has but the docs give no path for are found by their console title. Order is the order they are asked.
41
+ * @type {Field[]}
42
+ */
43
+ const FIELDS = [
44
+ { key: 'company.name', path: 'companyInfo.companyName', title: 'Company Name', type: 'TEXT', required: true },
45
+ { key: 'company.address1', path: 'companyInfo.address1', title: 'Address 1', type: 'TEXT', required: true },
46
+ { key: 'company.address2', path: 'companyInfo.address2', title: 'Address 2', type: 'TEXT', required: false },
47
+ { key: 'company.city', path: 'companyInfo.city', title: 'City', type: 'TEXT', required: true },
48
+ { key: 'company.state', path: 'companyInfo.state', title: 'State/Province', type: 'TEXT', required: true },
49
+ { key: 'company.zipCode', path: 'companyInfo.zipCode', title: 'Zip Code/Postal code', type: 'TEXT', required: true },
50
+ { key: 'company.isoCountryCode', path: 'companyInfo.isoCountryCode', title: 'Country', type: 'TEXT', required: true },
51
+ { key: 'company.businessType', path: null, title: 'Business type', type: 'SELECT', required: true, select: matchOption },
52
+ { key: 'company.taxId', path: null, title: 'Company identification number', type: 'TEXT', required: needsCompanyId },
53
+ { key: 'company.taxIdType', path: null, title: 'Identification number type', type: 'SELECT', required: needsCompanyId, select: matchOption },
54
+ { key: 'company.taxIdCountry', path: null, title: 'Identification number country', type: 'TEXT', required: needsCompanyId },
55
+ { key: 'website', path: 'companyInfo.website', title: 'Company website', type: 'TEXT', required: true },
56
+ { key: 'privacyPolicyUrl', path: null, title: 'Privacy Policy URL', type: 'TEXT', required: true },
57
+ { key: 'termsUrl', path: null, title: 'Terms and Conditions URL', type: 'TEXT', required: true },
58
+ { key: 'contact.firstName', path: 'contactInfo.firstName', title: 'First Name', type: 'TEXT', required: true },
59
+ { key: 'contact.lastName', path: 'contactInfo.lastName', title: 'Last Name', type: 'TEXT', required: true },
60
+ { key: 'contact.email', path: 'contactInfo.supportEmail', title: 'Support Email', type: 'TEXT', required: true },
61
+ { key: 'contact.phone', path: 'contactInfo.supportPhoneNumber', title: 'Support Phone Number', type: 'TEXT', required: true },
62
+ {
63
+ key: 'useCaseCategory', path: 'messagingUseCase.useCaseCategory', title: 'Use Case Category', type: 'SELECT', required: true,
64
+ derive: (_answers, options) => USE_CASE_CATEGORIES.map((c) => matchOption(c, options)).find(Boolean),
65
+ },
66
+ {
67
+ key: 'useCaseDetails', path: 'messagingUseCase.useCaseDetails', title: 'Use Case Details', type: 'TEXT', required: true,
68
+ derive: (answers) => `${answers.company.name} sends one-time sign-in and account verification codes by SMS to its users who sign in with their phone number. Messages are sent only when the user asks for a code.`,
69
+ },
70
+ { key: 'optIn.category', path: null, title: 'Opt-in category', type: 'SELECT', required: false, select: (answer, options) => matchOption(answer || DEFAULT_OPT_IN_CATEGORY, options) },
71
+ { key: 'optIn.description', path: 'messagingUseCase.optInDescription', title: 'Opt-in Workflow Description', type: 'TEXT', required: true },
72
+ { key: 'optIn.evidence', path: 'messagingUseCase.optInImage', title: 'Opt-in workflow image', type: 'ATTACHMENT', required: true },
73
+ { key: 'samples.0', path: 'messageSamples.messageSample1', title: 'Message Sample 1', type: 'TEXT', required: true },
74
+ { key: 'samples.1', path: 'messageSamples.messageSample2', title: 'Message Sample 2', type: 'TEXT', required: false },
75
+ { key: 'samples.2', path: 'messageSamples.messageSample3', title: 'Message Sample 3', type: 'TEXT', required: false },
76
+ { key: 'monthlyVolume', path: 'messagingUseCase.monthlyMessageVolume', title: 'Monthly SMS Volume', type: 'SELECT', required: true, select: volumeOption },
77
+ ]
78
+
79
+ /** @param {Field} field @param {object} answers */
80
+ function isRequired(field, answers) {
81
+ return typeof field.required === 'function' ? field.required(answers) : field.required
82
+ }
83
+
84
+ /**
85
+ * Match the table against AWS's current field definitions: by documented path, else by console title. Refuses a table
86
+ * field that AWS has no field for (unless optional) and a REQUIRED AWS field that the table does not fill, so a form
87
+ * AWS changed is caught before anything is written.
88
+ * @param {Array<Record<string, any>>} definitions DescribeRegistrationFieldDefinitions for US_TOLL_FREE_REGISTRATION
89
+ * @returns {ResolvedField[]}
90
+ */
91
+ function resolveFields(definitions) {
92
+ const byPath = new Map(definitions.map((d) => [d.FieldPath, d]))
93
+ /** @type {ResolvedField[]} */
94
+ const resolved = []
95
+ const problems = []
96
+ for (const field of FIELDS) {
97
+ const definition = (field.path && byPath.get(field.path)) || definitions.find((d) => loose(d.DisplayHints && d.DisplayHints.Title) === loose(field.title))
98
+ if (!definition) {
99
+ if (field.required !== false) problems.push(`no AWS field for ${field.key} (${field.title})`)
100
+ continue
101
+ }
102
+ if (definition.FieldType !== field.type) problems.push(`AWS field ${definition.FieldPath} (${field.title}) is ${definition.FieldType}, expected ${field.type}`)
103
+ resolved.push({ ...field, path: definition.FieldPath, definition })
104
+ }
105
+ const covered = new Set(resolved.map((f) => f.path))
106
+ for (const d of definitions) {
107
+ if (d.FieldRequirement === 'REQUIRED' && !covered.has(d.FieldPath)) problems.push(`AWS now requires ${d.FieldPath} (${(d.DisplayHints && d.DisplayHints.Title) || 'untitled'}), which this CLI does not fill`)
108
+ }
109
+ if (problems.length) throw new Error(`the ${REGISTRATION_TYPE} form does not match this CLI's field table; update saaslayer:\n ${problems.join('\n ')}`)
110
+ return resolved
111
+ }
112
+
113
+ /** A dotted key's value in the answers (`company.name`, `samples.0`). @param {object} answers @param {string} key */
114
+ function answerAt(answers, key) {
115
+ return key.split('.').reduce((v, k) => (v == null ? undefined : v[k]), answers)
116
+ }
117
+
118
+ /** A copy of the answers with a dotted key set. @param {object} answers @param {string} key @param {unknown} value */
119
+ function withAnswer(answers, key, value) {
120
+ const out = JSON.parse(JSON.stringify(answers || {}))
121
+ const parts = key.split('.')
122
+ let node = out
123
+ for (let i = 0; i < parts.length - 1; i++) {
124
+ const next = /^\d+$/.test(parts[i + 1]) ? [] : {}
125
+ if (node[parts[i]] == null) node[parts[i]] = next
126
+ node = node[parts[i]]
127
+ }
128
+ node[parts[parts.length - 1]] = value
129
+ return out
130
+ }
131
+
132
+ /**
133
+ * The value written for a resolved field, or undefined when an optional field is empty. Attachments are written by id.
134
+ * @param {ResolvedField} field @param {object} answers
135
+ * @returns {{ TextValue?: string, SelectChoices?: string[] }|undefined}
136
+ */
137
+ function fieldValue(field, answers) {
138
+ const options = (field.definition.SelectValidation && field.definition.SelectValidation.Options) || []
139
+ if (field.derive) {
140
+ const v = field.derive(answers, options)
141
+ return v === undefined ? undefined : field.type === 'SELECT' ? { SelectChoices: [v] } : { TextValue: v }
142
+ }
143
+ const answer = answerAt(answers, field.key)
144
+ if (field.type === 'SELECT') {
145
+ const choice = (field.select || matchOption)(answer, options)
146
+ return choice === undefined ? undefined : { SelectChoices: [choice] }
147
+ }
148
+ if (field.type === 'TEXT') return answer === undefined || answer === null || String(answer).trim() === '' ? undefined : { TextValue: String(answer).trim() }
149
+ return undefined
150
+ }
151
+
152
+ /**
153
+ * Answers rebuilt from a registration's current field values (the defaults a resubmission starts from).
154
+ * @param {ResolvedField[]} fields @param {Array<Record<string, any>>} values DescribeRegistrationFieldValues
155
+ */
156
+ function answersFromValues(fields, values) {
157
+ let answers = {}
158
+ for (const v of values) {
159
+ const field = fields.find((f) => f.path === v.FieldPath)
160
+ if (!field || field.derive || field.type === 'ATTACHMENT') continue
161
+ const value = v.TextValue !== undefined ? v.TextValue : v.SelectChoices && v.SelectChoices[0]
162
+ if (value !== undefined) answers = withAnswer(answers, field.key, field.key === 'monthlyVolume' ? Number(String(value).replace(/[^0-9]/g, '')) : value)
163
+ }
164
+ return answers
165
+ }
166
+
167
+ module.exports = { REGISTRATION_TYPE, FIELDS, resolveFields, isRequired, answerAt, withAnswer, fieldValue, answersFromValues, matchOption }
@@ -0,0 +1,151 @@
1
+ // Checks registration answers before `saaslayer sms register` writes anything: https URLs a carrier reviewer can open,
2
+ // a complete address, samples that name the brand and carry HELP/STOP, AWS's field limits, and the opt-in screenshot.
3
+ 'use strict'
4
+ const fs = require('fs')
5
+ const path = require('path')
6
+ const { answerAt, fieldValue, isRequired } = require('./registration-fields')
7
+
8
+ /** AWS: the opt-in workflow image is a PNG of at most 400 KB. */
9
+ const MAX_ATTACHMENT_BYTES = 400 * 1024
10
+ const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
11
+ const URL_KEYS = ['website', 'privacyPolicyUrl', 'termsUrl']
12
+ const E164 = /^\+[1-9]\d{6,14}$/
13
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
14
+
15
+ /**
16
+ * @typedef {(url: string, init?: object) => Promise<{ ok: boolean, status: number, arrayBuffer: () => Promise<ArrayBuffer> }>} Fetch
17
+ * @typedef {{ errors: string[], attachment: Buffer|null }} Validation
18
+ */
19
+
20
+ /** @param {unknown} v */
21
+ const blank = (v) => v === undefined || v === null || String(v).trim() === ''
22
+
23
+ /**
24
+ * An https URL on a public host name (no IP literal, no single-label or .local name), or why not.
25
+ * @param {string} value
26
+ * @returns {string|null}
27
+ */
28
+ function httpsProblem(value) {
29
+ let url
30
+ try { url = new URL(value) } catch { return 'must be an https:// URL' }
31
+ if (url.protocol !== 'https:') return 'must be an https:// URL'
32
+ const host = url.hostname
33
+ if (!host.includes('.') || /\.(local|internal|localhost)$/.test(host) || /^[\d.]+$/.test(host) || host.includes(':')) return 'must be on a public host name'
34
+ return null
35
+ }
36
+
37
+ /**
38
+ * An unauthenticated GET must answer 200, as a carrier reviewer would see it.
39
+ * @param {Fetch} fetchImpl @param {string} url
40
+ * @returns {Promise<string|null>}
41
+ */
42
+ async function reachProblem(fetchImpl, url) {
43
+ try {
44
+ const res = await fetchImpl(url, { method: 'GET', redirect: 'follow' })
45
+ return res.status === 200 ? null : `${url} answered ${res.status}; it must be publicly reachable (an unauthenticated GET returns 200)`
46
+ } catch (err) {
47
+ return `${url} is not reachable (${err.message}); it must be publicly reachable`
48
+ }
49
+ }
50
+
51
+ /**
52
+ * The opt-in screenshot: a local PNG (relative to cwd) or an https URL to one.
53
+ * @param {string} evidence @param {{ fetch: Fetch, cwd: string }} io
54
+ * @returns {Promise<{ body?: Buffer, problem?: string }>}
55
+ */
56
+ async function readEvidence(evidence, { fetch: fetchImpl, cwd }) {
57
+ let body
58
+ if (/^https?:\/\//i.test(evidence)) {
59
+ const problem = httpsProblem(evidence) || (await reachProblem(fetchImpl, evidence))
60
+ if (problem) return { problem }
61
+ body = Buffer.from(await (await fetchImpl(evidence, { method: 'GET', redirect: 'follow' })).arrayBuffer())
62
+ } else {
63
+ const file = path.resolve(cwd, evidence)
64
+ try { body = fs.readFileSync(file) } catch { return { problem: `cannot read ${file}` } }
65
+ }
66
+ if (body.byteLength > MAX_ATTACHMENT_BYTES || !body.subarray(0, 8).equals(PNG_SIGNATURE)) return { problem: 'a PNG of at most 400 KB (AWS\'s limit for the opt-in workflow image)' }
67
+ return { body }
68
+ }
69
+
70
+ /**
71
+ * AWS's own limits from the field definition (length, pattern, choices).
72
+ * @param {import('./registration-fields').ResolvedField} field @param {object} answers
73
+ * @returns {string|null}
74
+ */
75
+ function limitProblem(field, answers) {
76
+ const value = fieldValue(field, answers)
77
+ if (!value) return blank(answerAt(answers, field.key)) || field.derive ? null : `not one of AWS's choices: ${((field.definition.SelectValidation || {}).Options || []).join(', ')}`
78
+ const text = value.TextValue
79
+ const v = field.definition.TextValidation
80
+ if (text === undefined || !v) return null
81
+ if (v.MaxLength && text.length > v.MaxLength) return `at most ${v.MaxLength} characters (has ${text.length})`
82
+ if (v.MinLength && text.length < v.MinLength) return `at least ${v.MinLength} characters`
83
+ if (v.Pattern) {
84
+ let re = null
85
+ try { re = new RegExp(v.Pattern) } catch { re = null }
86
+ if (re && !re.test(text)) return `does not match AWS's format ${v.Pattern}`
87
+ }
88
+ return null
89
+ }
90
+
91
+ /**
92
+ * Field-specific rules beyond AWS's limits.
93
+ * @param {string} key @param {unknown} value @param {object} answers
94
+ * @returns {string|string[]|null}
95
+ */
96
+ function ruleProblem(key, value, answers) {
97
+ const s = String(value).trim()
98
+ if (URL_KEYS.includes(key)) return httpsProblem(s)
99
+ if (key === 'company.isoCountryCode' || key === 'company.taxIdCountry') return /^[A-Z]{2}$/.test(s) ? null : 'a two-letter ISO country code, e.g. US'
100
+ if (key === 'company.zipCode' && answerAt(answers, 'company.isoCountryCode') === 'US') return /^\d{5}(-\d{4})?$/.test(s) ? null : 'a US ZIP code (12345 or 12345-6789)'
101
+ if (key === 'contact.email') return EMAIL.test(s) ? null : 'an email address'
102
+ if (key === 'contact.phone') return E164.test(s) ? null : 'E.164, e.g. +14155550100 (no spaces or punctuation)'
103
+ if (key === 'monthlyVolume') return Number.isInteger(Number(value)) && Number(value) > 0 ? null : 'a whole number of messages per month, e.g. 1000'
104
+ if (key.startsWith('samples.')) {
105
+ const brand = String(answerAt(answers, 'company.name') || '').trim()
106
+ const problems = []
107
+ if (brand && !s.toLowerCase().includes(brand.toLowerCase())) problems.push(`must name the brand "${brand}"`)
108
+ if (!/\bHELP\b/.test(s) || !/\bSTOP\b/.test(s)) problems.push('must include HELP and STOP (e.g. "Reply HELP for help, STOP to opt out.")')
109
+ return problems
110
+ }
111
+ return null
112
+ }
113
+
114
+ /**
115
+ * Validate the answers for the given fields (all of them on a first submission, only the flagged ones on a resubmission).
116
+ * Nothing is written to AWS; the opt-in screenshot is read so it can be uploaded once everything passes.
117
+ * @param {object} answers
118
+ * @param {import('./registration-fields').ResolvedField[]} fields
119
+ * @param {{ fetch: Fetch, cwd: string }} io
120
+ * @returns {Promise<Validation>}
121
+ */
122
+ async function validateRegistration(answers, fields, io) {
123
+ const errors = []
124
+ let attachment = null
125
+ if (!Array.isArray(answers.samples) && fields.some((f) => f.key.startsWith('samples.'))) errors.push('samples: a list of one to three message samples')
126
+ for (const field of fields) {
127
+ if (field.derive) continue
128
+ const value = answerAt(answers, field.key)
129
+ if (blank(value)) {
130
+ if (isRequired(field, answers)) errors.push(`${field.key}: required (${field.title})`)
131
+ continue
132
+ }
133
+ if (field.type === 'ATTACHMENT') {
134
+ const evidence = await readEvidence(String(value), io)
135
+ if (evidence.problem) errors.push(`${field.key}: ${evidence.problem}`)
136
+ else attachment = evidence.body
137
+ continue
138
+ }
139
+ const rule = ruleProblem(field.key, value, answers)
140
+ const ruled = Array.isArray(rule) ? rule : rule ? [rule] : []
141
+ const problems = ruled.length ? ruled : [limitProblem(field, answers)].filter(Boolean)
142
+ for (const problem of problems) errors.push(`${field.key}: ${problem}`)
143
+ if (!problems.length && URL_KEYS.includes(field.key)) {
144
+ const unreachable = await reachProblem(io.fetch, String(value).trim())
145
+ if (unreachable) errors.push(`${field.key}: ${unreachable}`)
146
+ }
147
+ }
148
+ return { errors, attachment }
149
+ }
150
+
151
+ module.exports = { validateRegistration, MAX_ATTACHMENT_BYTES }
@@ -0,0 +1,216 @@
1
+ // The AWS side of `saaslayer sms register` / `status` / `release` (End User Messaging SMS): the number's registration
2
+ // (found by association, else by tag), idempotent create, field writes, opt-in attachment, association, submission, delete.
3
+ 'use strict'
4
+ const crypto = require('crypto')
5
+ const {
6
+ PinpointSMSVoiceV2Client, DescribePhoneNumbersCommand, DescribeRegistrationsCommand, ListTagsForResourceCommand,
7
+ CreateRegistrationCommand, DescribeRegistrationFieldDefinitionsCommand, DescribeRegistrationFieldValuesCommand,
8
+ DescribeRegistrationVersionsCommand, PutRegistrationFieldValueCommand, CreateRegistrationAttachmentCommand,
9
+ DescribeRegistrationAttachmentsCommand, ListRegistrationAssociationsCommand, CreateRegistrationAssociationCommand,
10
+ CreateRegistrationVersionCommand, SubmitRegistrationVersionCommand, DeleteRegistrationCommand,
11
+ } = require('@aws-sdk/client-pinpoint-sms-voice-v2')
12
+ const { REGISTRATION_TYPE, fieldValue } = require('./registration-fields')
13
+
14
+ /** The tag that finds a registration for its number before the number is associated (plan §7). */
15
+ const ORIGINATION_NUMBER_TAG = 'saaslayer:originationNumber'
16
+ /** States `sms register` edits; every other live state is left as it is. */
17
+ const EDITABLE_STATUSES = ['CREATED', 'REQUIRES_UPDATES']
18
+ /** A registration in one of these states is gone: the next run starts a new one. */
19
+ const ENDED_STATUSES = ['DELETED', 'CLOSED']
20
+ /** Page cap per listing, as the deployer's readiness reader uses. */
21
+ const MAX_PAGES = 50
22
+ const ATTACHMENT_POLLS = 30
23
+ const ATTACHMENT_POLL_MS = 2000
24
+
25
+ /**
26
+ * @typedef {{ send: (command: unknown) => Promise<any> }} SmsClient
27
+ * @typedef {{ PhoneNumberId: string, PhoneNumberArn: string, PhoneNumber?: string, Status?: string, NumberType?: string, RegistrationId?: string }} PhoneNumber
28
+ * @typedef {{ RegistrationId: string, RegistrationArn: string, RegistrationStatus: string, CurrentVersionNumber: number, LatestDeniedVersionNumber?: number }} Registration
29
+ */
30
+
31
+ /** @param {{ region: string, profile?: string }} o @returns {SmsClient} */
32
+ function createSmsClient({ region, profile }) {
33
+ return new PinpointSMSVoiceV2Client({ region, ...(profile ? { profile } : {}) })
34
+ }
35
+
36
+ /**
37
+ * Every item of a paged listing.
38
+ * @param {SmsClient} sms @param {new (input: object) => unknown} Command @param {object} input @param {string} key
39
+ */
40
+ async function listAll(sms, Command, input, key) {
41
+ const items = []
42
+ let NextToken
43
+ for (let page = 0; page < MAX_PAGES; page++) {
44
+ const out = await sms.send(new Command({ ...input, ...(NextToken ? { NextToken } : {}) }))
45
+ items.push(...(out[key] || []))
46
+ NextToken = out.NextToken
47
+ if (!NextToken) return items
48
+ }
49
+ throw new Error(`${key}: more than ${MAX_PAGES} pages`)
50
+ }
51
+
52
+ /** @param {SmsClient} sms @param {string} arn @returns {Promise<PhoneNumber>} */
53
+ async function describeNumber(sms, arn) {
54
+ const out = await sms.send(new DescribePhoneNumbersCommand({ PhoneNumberIds: [arn] }))
55
+ const number = (out.PhoneNumbers || [])[0]
56
+ if (!number) throw new Error(`the foundation's sending number ${arn} was not found in End User Messaging`)
57
+ return number
58
+ }
59
+
60
+ /**
61
+ * The CreateRegistration client token: derived from the number (and any ended registrations it replaces), so a retried
62
+ * create returns the same registration and a start-over after DELETED/CLOSED gets a new one.
63
+ * @param {string} phoneNumberId @param {string[]} endedIds
64
+ */
65
+ function registrationClientToken(phoneNumberId, endedIds) {
66
+ return `sl-${crypto.createHash('sha256').update([phoneNumberId, ...[...endedIds].sort()].join('|')).digest('hex').slice(0, 40)}`
67
+ }
68
+
69
+ /** @param {SmsClient} sms @param {string} id @returns {Promise<Registration|null>} */
70
+ async function describeRegistration(sms, id) {
71
+ const out = await sms.send(new DescribeRegistrationsCommand({ RegistrationIds: [id] }))
72
+ return (out.Registrations || [])[0] || null
73
+ }
74
+
75
+ /**
76
+ * The number's registration without creating one: its RegistrationId once associated, else the one tagged for it.
77
+ * More than one live tagged registration is refused. Ended registrations are returned so a new one can replace them.
78
+ * @param {SmsClient} sms @param {PhoneNumber} number
79
+ * @returns {Promise<{ registration: Registration|null, ended: string[] }>}
80
+ */
81
+ async function findRegistration(sms, number) {
82
+ const ended = []
83
+ if (number.RegistrationId) {
84
+ const r = await describeRegistration(sms, number.RegistrationId)
85
+ if (r && !ENDED_STATUSES.includes(r.RegistrationStatus)) return { registration: r, ended }
86
+ ended.push(number.RegistrationId)
87
+ }
88
+ // AWS has no tag filter on registrations: list this type, then read each one's tags.
89
+ const all = await listAll(sms, DescribeRegistrationsCommand, { Filters: [{ Name: 'registration-type', Values: [REGISTRATION_TYPE] }] }, 'Registrations')
90
+ const live = []
91
+ for (const r of all) {
92
+ const tags = (await sms.send(new ListTagsForResourceCommand({ ResourceArn: r.RegistrationArn }))).Tags || []
93
+ if (!tags.some((t) => t.Key === ORIGINATION_NUMBER_TAG && t.Value === number.PhoneNumberId)) continue
94
+ if (ENDED_STATUSES.includes(r.RegistrationStatus)) { if (!ended.includes(r.RegistrationId)) ended.push(r.RegistrationId) } else live.push(r)
95
+ }
96
+ if (live.length > 1) throw new Error(`more than one registration is tagged for ${number.PhoneNumberId}: ${live.map((r) => r.RegistrationId).join(', ')}; delete the extra one(s) in AWS End User Messaging, then retry`)
97
+ return { registration: live[0] || null, ended }
98
+ }
99
+
100
+ /**
101
+ * Create the number's registration, tagged for it, with a client token derived from the number and the ended
102
+ * registrations it replaces (a retried create returns the same registration).
103
+ * @param {SmsClient} sms @param {PhoneNumber} number @param {string[]} ended
104
+ * @returns {Promise<Registration>}
105
+ */
106
+ function createRegistration(sms, number, ended) {
107
+ return sms.send(new CreateRegistrationCommand({
108
+ RegistrationType: REGISTRATION_TYPE,
109
+ Tags: [{ Key: ORIGINATION_NUMBER_TAG, Value: number.PhoneNumberId }],
110
+ ClientToken: registrationClientToken(number.PhoneNumberId, ended),
111
+ }))
112
+ }
113
+
114
+ /** @param {SmsClient} sms */
115
+ function fieldDefinitions(sms) {
116
+ return listAll(sms, DescribeRegistrationFieldDefinitionsCommand, { RegistrationType: REGISTRATION_TYPE }, 'RegistrationFieldDefinitions')
117
+ }
118
+
119
+ /** @param {SmsClient} sms @param {string} registrationId @param {number} [version] */
120
+ function fieldValues(sms, registrationId, version) {
121
+ return listAll(sms, DescribeRegistrationFieldValuesCommand, { RegistrationId: registrationId, ...(version ? { VersionNumber: version } : {}) }, 'RegistrationFieldValues')
122
+ }
123
+
124
+ /** @param {SmsClient} sms @param {string} registrationId @param {number} version */
125
+ async function describeVersion(sms, registrationId, version) {
126
+ const out = await sms.send(new DescribeRegistrationVersionsCommand({ RegistrationId: registrationId, VersionNumbers: [version] }))
127
+ return (out.RegistrationVersions || [])[0] || null
128
+ }
129
+
130
+ /**
131
+ * Upload the opt-in screenshot once (the client token is derived from the number and the image) and wait for it.
132
+ * @param {SmsClient} sms @param {Buffer} body @param {string} phoneNumberId @param {(ms: number) => Promise<void>} sleep
133
+ * @returns {Promise<string>} the attachment id
134
+ */
135
+ async function uploadAttachment(sms, body, phoneNumberId, sleep) {
136
+ const digest = crypto.createHash('sha256').update(phoneNumberId).update(body).digest('hex').slice(0, 40)
137
+ const created = await sms.send(new CreateRegistrationAttachmentCommand({ AttachmentBody: body, ClientToken: `sl-${digest}`, Tags: [{ Key: ORIGINATION_NUMBER_TAG, Value: phoneNumberId }] }))
138
+ const id = created.RegistrationAttachmentId
139
+ for (let i = 0; i < ATTACHMENT_POLLS; i++) {
140
+ const a = ((await sms.send(new DescribeRegistrationAttachmentsCommand({ RegistrationAttachmentIds: [id] }))).RegistrationAttachments || [])[0] || {}
141
+ if (a.AttachmentStatus === 'UPLOAD_COMPLETE') return id
142
+ if (a.AttachmentStatus === 'UPLOAD_FAILED' || a.AttachmentStatus === 'DELETED') throw new Error(`the opt-in image upload failed (${a.AttachmentUploadErrorReason || a.AttachmentStatus})`)
143
+ await sleep(ATTACHMENT_POLL_MS)
144
+ }
145
+ throw new Error(`the opt-in image ${id} did not finish uploading; run sms register again`)
146
+ }
147
+
148
+ /**
149
+ * Write each field whose value differs from the registration's current one.
150
+ * @param {SmsClient} sms @param {string} registrationId
151
+ * @param {import('./registration-fields').ResolvedField[]} fields @param {object} answers
152
+ * @param {{ attachmentId: string|null, current: Array<Record<string, any>> }} o
153
+ * @returns {Promise<string[]>} the field paths written
154
+ */
155
+ async function writeFields(sms, registrationId, fields, answers, { attachmentId, current }) {
156
+ const written = []
157
+ for (const field of fields) {
158
+ const value = field.type === 'ATTACHMENT' ? (attachmentId ? { RegistrationAttachmentId: attachmentId } : undefined) : fieldValue(field, answers)
159
+ if (!value) continue
160
+ const now = current.find((v) => v.FieldPath === field.path) || {}
161
+ const same = value.TextValue !== undefined ? now.TextValue === value.TextValue
162
+ : value.SelectChoices ? JSON.stringify(now.SelectChoices || []) === JSON.stringify(value.SelectChoices)
163
+ : now.RegistrationAttachmentId === value.RegistrationAttachmentId
164
+ if (same && !now.DeniedReason) continue
165
+ await sms.send(new PutRegistrationFieldValueCommand({ RegistrationId: registrationId, FieldPath: field.path, ...value }))
166
+ written.push(field.path)
167
+ }
168
+ return written
169
+ }
170
+
171
+ /**
172
+ * Associate the number with the registration (before submission); an existing association counts as done.
173
+ * @param {SmsClient} sms @param {string} registrationId @param {PhoneNumber} number
174
+ * @returns {Promise<boolean>} whether this call created it
175
+ */
176
+ async function ensureAssociation(sms, registrationId, number) {
177
+ const associated = async () => (await listAll(sms, ListRegistrationAssociationsCommand, { RegistrationId: registrationId }, 'RegistrationAssociations'))
178
+ .some((a) => a.ResourceArn === number.PhoneNumberArn || a.ResourceId === number.PhoneNumberId)
179
+ if (number.RegistrationId === registrationId || (await associated())) return false
180
+ try {
181
+ await sms.send(new CreateRegistrationAssociationCommand({ RegistrationId: registrationId, ResourceId: number.PhoneNumberArn }))
182
+ return true
183
+ } catch (err) {
184
+ if (err && err.name === 'ConflictException' && (await associated())) return false
185
+ throw err
186
+ }
187
+ }
188
+
189
+ /** @param {SmsClient} sms @param {string} registrationId */
190
+ function newVersion(sms, registrationId) {
191
+ return sms.send(new CreateRegistrationVersionCommand({ RegistrationId: registrationId }))
192
+ }
193
+
194
+ /** @param {SmsClient} sms @param {string} registrationId */
195
+ function submitVersion(sms, registrationId) {
196
+ return sms.send(new SubmitRegistrationVersionCommand({ RegistrationId: registrationId }))
197
+ }
198
+
199
+ /**
200
+ * Delete a registration (AWS keeps a closed one until it is deleted); one already gone counts as deleted.
201
+ * @param {SmsClient} sms @param {string} registrationId
202
+ */
203
+ async function deleteRegistration(sms, registrationId) {
204
+ try {
205
+ await sms.send(new DeleteRegistrationCommand({ RegistrationId: registrationId }))
206
+ } catch (err) {
207
+ if (!err || err.name !== 'ResourceNotFoundException') throw err
208
+ }
209
+ }
210
+
211
+ module.exports = {
212
+ ORIGINATION_NUMBER_TAG, EDITABLE_STATUSES, ENDED_STATUSES,
213
+ createSmsClient, listAll, describeNumber, registrationClientToken, findRegistration, createRegistration,
214
+ fieldDefinitions, fieldValues, describeVersion, uploadAttachment, writeFields, ensureAssociation, newVersion, submitVersion,
215
+ deleteRegistration,
216
+ }
@@ -0,0 +1,55 @@
1
+ // The control plane's SMS release record of an account, region and sender (plan §5): read it, move it a phase, and, from
2
+ // the region foundation's actual state, record a number removal that landed (used by `sms release` and `sms status`).
3
+ 'use strict'
4
+ const { STABLE_STATUSES } = require('../foundation-change-set')
5
+ const { smsNumberOf } = require('./number')
6
+ const { smsReleasePath } = require('./scope')
7
+
8
+ /** @param {string|null|undefined} phase */
9
+ const isUnfinished = (phase) => phase !== 'done' && phase !== 'refused'
10
+
11
+ /**
12
+ * The release record of the target, or null when no release was ever started.
13
+ * @param {Function} api @param {import('./scope').SmsTarget} target @param {object} flags
14
+ */
15
+ async function readRelease(api, target, flags) {
16
+ try {
17
+ return (await api('GET', smsReleasePath(target), undefined, flags)).data.attributes
18
+ } catch (err) {
19
+ if (err.status === 404) return null
20
+ throw err
21
+ }
22
+ }
23
+
24
+ /**
25
+ * Move the release from `from` to `phase` (the control plane refuses a stale or invalid move).
26
+ * @param {Function} api @param {import('./scope').SmsTarget} target @param {object} flags @param {string} from @param {string} phase
27
+ */
28
+ async function advanceRelease(api, target, flags, from, phase) {
29
+ return (await api('PATCH', smsReleasePath(target), { data: { type: 'sms-releases', attributes: { from, phase } } }, flags)).data.attributes
30
+ }
31
+
32
+ /** The number removal landed: the stack is settled and has no number. @param {{ StackStatus: string }} stack */
33
+ function numberRemoved(stack) {
34
+ return smsNumberOf(stack).numberType === 'none' && STABLE_STATUSES.includes(stack.StackStatus)
35
+ }
36
+
37
+ /**
38
+ * Move an unfinished release forward as far as the stack's actual state allows, without changing AWS: a removal that
39
+ * landed is recorded (`releasing-number` -> `number-released`), and a released number with no registration finishes the
40
+ * release. A stack still updating, or a number still there, leaves the record (and its lock) as it is.
41
+ * @param {{ api: Function, target: import('./scope').SmsTarget, flags: object, stack: { StackStatus: string }|null }} o
42
+ * `stack`: the region foundation as described now (null when absent)
43
+ * @returns {Promise<Record<string, any>|null>} the record as it is now; null when no release was in progress
44
+ */
45
+ async function recordLandedRelease({ api, target, flags, stack }) {
46
+ let record = await readRelease(api, target, flags)
47
+ if (!record || !isUnfinished(record.phase)) return null
48
+ if (record.phase === 'releasing-number') {
49
+ if (stack && numberRemoved(stack)) record = await advanceRelease(api, target, flags, 'releasing-number', 'number-released')
50
+ }
51
+ if (record.phase === 'number-released' && !record.registrationId) record = await advanceRelease(api, target, flags, 'number-released', 'done')
52
+ return record
53
+ }
54
+
55
+ module.exports = { isUnfinished, readRelease, advanceRelease, numberRemoved, recordLandedRelease }