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
|
@@ -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 }
|
package/src/sms/scope.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// The account and region an `saaslayer sms …` command acts on (plan §3): resolved by the control plane from the project's
|
|
2
|
+
// deployment for --env, else its connected account; printed under the scope line, then the cloud-prem checks.
|
|
3
|
+
'use strict'
|
|
4
|
+
const { jsonApiCall } = require('../api-client')
|
|
5
|
+
const { resolveScope, formatScopeLine } = require('../scope')
|
|
6
|
+
const { awsRunner } = require('../foundation-change-set')
|
|
7
|
+
|
|
8
|
+
/** v1 has one sender per account and region (plan §5b); commands take a sender name internally, no flag yet. */
|
|
9
|
+
const DEFAULT_SMS_SENDER = 'default'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @typedef {{ accountId: string, region: string, source: 'deployment'|'connected-account', deploymentId: string|null,
|
|
13
|
+
* accountOwnership: string, dedicatedAccount: boolean, protectedDeployments: boolean, env: string, project: string,
|
|
14
|
+
* sender: string, scope: import('../scope').Scope }} SmsTarget
|
|
15
|
+
* @typedef {{ api?: typeof jsonApiCall, log?: (...a: unknown[]) => void, sender?: string }} ScopeDeps
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Resolve the target account and region of `--env` (and `--region` when the env spans several). Prints the scope line and
|
|
20
|
+
* the target line on stderr (--json suppresses both).
|
|
21
|
+
* @param {Record<string, any>} flags
|
|
22
|
+
* @param {ScopeDeps} [deps]
|
|
23
|
+
* @returns {Promise<SmsTarget>}
|
|
24
|
+
*/
|
|
25
|
+
async function resolveSmsTarget(flags, { api = jsonApiCall, log = console.error, sender = DEFAULT_SMS_SENDER } = {}) {
|
|
26
|
+
if (typeof flags.env !== 'string' || !flags.env) throw new Error('--env is required (the environment whose account and region send the SMS, e.g. --env dev)')
|
|
27
|
+
const scope = resolveScope(flags, { env: flags.env })
|
|
28
|
+
if (!flags.json) log(formatScopeLine(scope))
|
|
29
|
+
const project = String(scope.project.value)
|
|
30
|
+
const query = new URLSearchParams({ environment: flags.env, ...(typeof flags.region === 'string' ? { region: flags.region } : {}) })
|
|
31
|
+
const doc = await api('GET', `/api/projects/${encodeURIComponent(project)}/sms-target?${query}`, undefined, flags)
|
|
32
|
+
const a = doc.data.attributes
|
|
33
|
+
/** @type {SmsTarget} */
|
|
34
|
+
const target = { ...a, env: flags.env, project, sender, scope }
|
|
35
|
+
if (!flags.json) log(`target: account=${a.accountId} region=${a.region} (from: ${a.source === 'deployment' ? `${flags.env} deployment ${a.deploymentId}` : 'connected account'})`)
|
|
36
|
+
return target
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The AWS-calling `sms` commands run with the customer's own credentials (cloud-prem); anything else is refused. A shared
|
|
41
|
+
* hosted account can never carry a customer's brand (D7); a dedicated one waits on the control plane making these calls
|
|
42
|
+
* (monorepo-aagbc).
|
|
43
|
+
* @param {SmsTarget} target @param {string} command
|
|
44
|
+
*/
|
|
45
|
+
function refuseHostedAccount(target, command) {
|
|
46
|
+
if (target.accountOwnership === 'cloud-prem') return
|
|
47
|
+
if (target.accountOwnership === 'hosted' && !target.dedicatedAccount) {
|
|
48
|
+
throw new Error(`${command}: account ${target.accountId}: sms.shared-account-unsupported: phone SMS needs a dedicated account: this is a shared hosted account, and one account-wide sending number cannot carry each customer's registered brand; deploy phone sign-in to a dedicated hosted account or to your own AWS account`)
|
|
49
|
+
}
|
|
50
|
+
throw new Error(`${command}: account ${target.accountId} is a SaaSLayer-hosted account; ${command} works on your own AWS account (cloud-prem) only for now — hosted accounts are not supported yet (the control plane would make these AWS calls there)`)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Cloud-prem: the caller's AWS credentials must be for the target account (the account check `aws connect` makes).
|
|
55
|
+
* @param {import('../foundation-change-set').AwsJson} aws @param {SmsTarget} target
|
|
56
|
+
* @returns {string} the caller's ARN
|
|
57
|
+
*/
|
|
58
|
+
function checkCallerAccount(aws, target) {
|
|
59
|
+
const identity = aws(['sts', 'get-caller-identity'])
|
|
60
|
+
if (identity.Account !== target.accountId) {
|
|
61
|
+
throw new Error(`your AWS credentials are for account ${identity.Account}, not ${target.accountId} (the ${target.env} ${target.source === 'deployment' ? 'deployment' : 'connected'} account); switch credentials (or pass --profile) and retry`)
|
|
62
|
+
}
|
|
63
|
+
return String(identity.Arn)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The target of an AWS-calling `sms` command after the cloud-prem checks (not hosted, the caller's credentials are for
|
|
68
|
+
* the target account), with an `aws` CLI runner for its region and --profile.
|
|
69
|
+
* @param {Record<string, any>} flags @param {string} command
|
|
70
|
+
* @param {{ api?: typeof jsonApiCall, exec: (cmd: string, args: string[]) => string, log?: (...a: unknown[]) => void }} deps
|
|
71
|
+
* @returns {Promise<{ target: SmsTarget, aws: import('../foundation-change-set').AwsJson }>}
|
|
72
|
+
*/
|
|
73
|
+
async function cloudPremTarget(flags, command, { api, exec, log }) {
|
|
74
|
+
const target = await resolveSmsTarget(flags, { api, log })
|
|
75
|
+
refuseHostedAccount(target, command)
|
|
76
|
+
const aws = awsRunner(exec, { region: target.region, profile: flags.profile })
|
|
77
|
+
checkCallerAccount(aws, target)
|
|
78
|
+
return { target, aws }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The control-plane path of the SMS release record of the target's account, region and sender. @param {SmsTarget} t */
|
|
82
|
+
function smsReleasePath(t) {
|
|
83
|
+
return `/api/accounts/${t.accountId}/regions/${encodeURIComponent(t.region)}/sms-senders/${encodeURIComponent(t.sender)}/release`
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
module.exports = { DEFAULT_SMS_SENDER, resolveSmsTarget, refuseHostedAccount, checkCallerAccount, cloudPremTarget, smsReleasePath }
|